From 323a599f1545c82a0f41307327e79f2734f6aecc Mon Sep 17 00:00:00 2001 From: Marco Salazar Date: Wed, 4 Dec 2024 10:59:17 -0500 Subject: [PATCH 01/13] rewrite auto-complete --- js_modules/dagster-ui/.gitattributes | 1 + .../dagster-ui/packages/ui-core/package.json | 1 + .../asset-selection/AntlrAssetSelection.ts | 45 +- .../input/AssetSelectionAutoComplete.ts | 246 -- .../input/AssetSelectionInput.oss.tsx | 173 +- .../input/AssetSelectionLinter.ts | 26 +- .../input/AssetSelectionMode.ts | 128 - .../AssetSelectionSyntaxErrorListener.tsx | 4 +- .../ui-core/src/scripts/generateSelection.ts | 16 + .../src/selection/CustomErrorListener.ts | 37 + .../src/selection/SelectionAutoComplete.g4 | 147 + .../src/selection/SelectionAutoComplete.ts | 483 +++ .../SelectionAutoCompleteHighlighter.ts | 265 ++ .../SelectionAutoCompleteInputParser.ts | 109 + .../selection/SelectionAutoCompleteUtil.ts | 32 + .../__tests__/SelectionAutoComplete.test.ts | 711 ++++ .../generated/SelectionAutoComplete.interp | 60 + .../generated/SelectionAutoComplete.tokens | 23 + .../SelectionAutoCompleteLexer.interp | 59 + .../SelectionAutoCompleteLexer.tokens | 23 + .../generated/SelectionAutoCompleteLexer.ts | 172 + .../SelectionAutoCompleteListener.ts | 764 +++++ .../generated/SelectionAutoCompleteParser.ts | 2997 +++++++++++++++++ .../generated/SelectionAutoCompleteVisitor.ts | 501 +++ 24 files changed, 6545 insertions(+), 478 deletions(-) delete mode 100644 js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionAutoComplete.ts delete mode 100644 js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionMode.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/scripts/generateSelection.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/CustomErrorListener.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteInputParser.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteUtil.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.tokens create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.interp create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.tokens create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts diff --git a/js_modules/dagster-ui/.gitattributes b/js_modules/dagster-ui/.gitattributes index 02bbb04e9ffdd..efe38e28267b6 100644 --- a/js_modules/dagster-ui/.gitattributes +++ b/js_modules/dagster-ui/.gitattributes @@ -8,3 +8,4 @@ packages/ui-core/src/graphql/* linguist-generated=true packages/ui-core/src/**/types/* linguist-generated=true packages/ui-core/client.json linguist-generated=true packages/ui-core/src/asset-selection/generated/* linguist-generated=true +packages/ui-core/src/selection/generated/* linguist-generated=true diff --git a/js_modules/dagster-ui/packages/ui-core/package.json b/js_modules/dagster-ui/packages/ui-core/package.json index 26a7d6b073dab..3490e3d788d4e 100644 --- a/js_modules/dagster-ui/packages/ui-core/package.json +++ b/js_modules/dagster-ui/packages/ui-core/package.json @@ -15,6 +15,7 @@ "generate-graphql": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generateGraphQLTypes.ts", "generate-perms": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generatePermissions.ts", "generate-asset-selection": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generateAssetSelection.ts && eslint src/asset-selection/generated/ --fix -c .eslintrc.js", + "generate-selection-autocomplete": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generateSelection.ts && eslint src/selection/generated/ --fix -c .eslintrc.js", "storybook": "storybook dev -p 6006", "build-storybook": "storybook build" }, diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts index 17722bca32662..8ecf6b03fc28e 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts @@ -38,31 +38,27 @@ type AssetSelectionQueryResult = { export const parseAssetSelectionQuery = ( all_assets: AssetGraphQueryItem[], query: string, -): AssetSelectionQueryResult | Error => { - try { - const lexer = new AssetSelectionLexer(CharStreams.fromString(query)); - lexer.removeErrorListeners(); - lexer.addErrorListener(new AntlrInputErrorListener()); +): AssetSelectionQueryResult => { + const lexer = new AssetSelectionLexer(CharStreams.fromString(query)); + lexer.removeErrorListeners(); + lexer.addErrorListener(new AntlrInputErrorListener()); - const tokenStream = new CommonTokenStream(lexer); + const tokenStream = new CommonTokenStream(lexer); - const parser = new AssetSelectionParser(tokenStream); - parser.removeErrorListeners(); - parser.addErrorListener(new AntlrInputErrorListener()); + const parser = new AssetSelectionParser(tokenStream); + parser.removeErrorListeners(); + parser.addErrorListener(new AntlrInputErrorListener()); - const tree = parser.start(); + const tree = parser.start(); - const visitor = new AntlrAssetSelectionVisitor(all_assets); - const all_selection = visitor.visit(tree); - const focus_selection = visitor.focus_assets; + const visitor = new AntlrAssetSelectionVisitor(all_assets); + const all_selection = visitor.visit(tree); + const focus_selection = visitor.focus_assets; - return { - all: Array.from(all_selection), - focus: Array.from(focus_selection), - }; - } catch (e) { - return e as Error; - } + return { + all: Array.from(all_selection), + focus: Array.from(focus_selection), + }; }; export const filterAssetSelectionByQuery = ( @@ -70,12 +66,9 @@ export const filterAssetSelectionByQuery = ( query: string, ): AssetSelectionQueryResult => { if (featureEnabled(FeatureFlag.flagAssetSelectionSyntax)) { - const result = parseAssetSelectionQuery(all_assets, query); - if (result instanceof Error) { - // fall back to old behavior - return filterByQuery(all_assets, query); - } - return result; + try { + return parseAssetSelectionQuery(all_assets, query); + } catch {} } return filterByQuery(all_assets, query); }; diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionAutoComplete.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionAutoComplete.ts deleted file mode 100644 index 6ef3c0dfd86a3..0000000000000 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionAutoComplete.ts +++ /dev/null @@ -1,246 +0,0 @@ -import CodeMirror, {HintFunction, Hints} from 'codemirror'; - -import {assertUnreachable} from '../../app/Util'; -import {AssetGraphQueryItem} from '../../asset-graph/useAssetGraphData'; -import {buildRepoPathForHuman} from '../../workspace/buildRepoAddress'; - -export const possibleKeywords = [ - 'key:', - 'key_substring:', - 'tag:', - 'owner:', - 'group:', - 'kind:', - 'code_location:', - 'sinks()', - 'roots()', - 'not', - '*', - '+', -]; - -const logicalOperators = ['and', 'or', '*', '+']; - -export const createAssetSelectionHint = (assets: AssetGraphQueryItem[]): HintFunction => { - const assetNamesSet: Set = new Set(); - const tagNamesSet: Set = new Set(); - const ownersSet: Set = new Set(); - const groupsSet: Set = new Set(); - const kindsSet: Set = new Set(); - const codeLocationSet: Set = new Set(); - - assets.forEach((asset) => { - assetNamesSet.add(asset.name); - asset.node.tags.forEach((tag) => { - if (tag.key && tag.value) { - tagNamesSet.add(`${tag.key}=${tag.value}`); - } else { - tagNamesSet.add(tag.key); - } - }); - asset.node.owners.forEach((owner) => { - switch (owner.__typename) { - case 'TeamAssetOwner': - ownersSet.add(owner.team); - break; - case 'UserAssetOwner': - ownersSet.add(owner.email); - break; - default: - assertUnreachable(owner); - } - }); - if (asset.node.groupName) { - groupsSet.add(asset.node.groupName); - } - asset.node.kinds.forEach((kind) => { - kindsSet.add(kind); - }); - const location = buildRepoPathForHuman( - asset.node.repository.name, - asset.node.repository.location.name, - ); - codeLocationSet.add(location); - }); - - const assetNames = Array.from(assetNamesSet).map(addQuotesToString); - const tagNames = Array.from(tagNamesSet).map(addQuotesToString); - const owners = Array.from(ownersSet).map(addQuotesToString); - const groups = Array.from(groupsSet).map(addQuotesToString); - const kinds = Array.from(kindsSet).map(addQuotesToString); - const codeLocations = Array.from(codeLocationSet).map(addQuotesToString); - - return (cm: CodeMirror.Editor): Hints | undefined => { - const cursor = cm.getCursor(); - const token = cm.getTokenAt(cursor); - - const indexOfToken: number = token.state.tokenIndex - 1; - const allTokens = token.state.tokens; - - const previous2Tokens = - token.string.trim() === '' - ? [allTokens[indexOfToken - 1]?.text, allTokens[indexOfToken]?.text] - : [allTokens[indexOfToken - 2]?.text, allTokens[indexOfToken - 1]?.text]; - - let start = token.start; - const end = token.end; - const tokenString = token.string.trim(); - const tokenUpToCursor = cm.getRange(CodeMirror.Pos(cursor.line, start), cursor).trim(); - const unquotedTokenString = removeQuotesFromString(tokenString); - - const isAfterAttributeValue = previous2Tokens[0] === ':' && previous2Tokens[1] !== undefined; - - const isAfterParenthesizedExpressions = - // if tokenUpToCursor === '' and tokenString ===') then the cursor is to the left of the parenthesis - previous2Tokens[1] === ')' || (tokenString === ')' && tokenUpToCursor !== ''); - - const isInKeyValue = - (previous2Tokens[1] === ':' && token.string.trim() !== '') || tokenString === ':'; - - const isTraversal = /^[*+]+$/.test(tokenString); - - const tokensBefore = allTokens - .slice(0, indexOfToken + 1) - .map((token: any) => token.text?.trim()); - const preTraversal = isTraversal && isPreTraversal(tokensBefore); - const isPostTraversal = isTraversal && !preTraversal; - - const isEndOfKeyValueExpression = - isInKeyValue && - tokenString.endsWith('"') && - tokenString.length > 2 && - tokenUpToCursor.endsWith('"'); - - const isAfterTraversal = ['+', '*'].includes(previous2Tokens[1]); - - function getSuggestions() { - if (isEndOfKeyValueExpression) { - start = end; - } - - if ( - isPostTraversal || - isAfterAttributeValue || - isAfterParenthesizedExpressions || - isEndOfKeyValueExpression || - isAfterTraversal - ) { - return logicalOperators; - } - - if (isInKeyValue) { - let type = previous2Tokens[0]; - if (tokenString === ':') { - type = previous2Tokens[1]; - } - switch (type) { - case 'key_substring': - case 'key': - return assetNames; - case 'tag': - return tagNames; - case 'owner': - return owners; - case 'group': - return groups; - case 'kind': - return kinds; - case 'code_location': - return codeLocations; - } - } - - if (tokenString === '' || tokenString === '(' || tokenString === ')' || preTraversal) { - return possibleKeywords; - } - return [ - `key_substring:"${unquotedTokenString}"`, - `key:"${unquotedTokenString}"`, - ...possibleKeywords, - ]; - } - - let suggestions = getSuggestions(); - - if (!(isTraversal || isEndOfKeyValueExpression || ['', ':', '(', ')'].includes(tokenString))) { - suggestions = suggestions.filter( - (item) => - item.startsWith(tokenString) || - item.startsWith(unquotedTokenString) || - item.includes(`:"${unquotedTokenString}`) || - item.startsWith(`"${unquotedTokenString}`), - ); - } - - const list = suggestions.map((item) => { - let text = item; - if (token.string[0] === ' ') { - text = ' ' + item; - } - if (tokenString === ':') { - text = `:${item}`; - } - - if (tokenString === '(') { - text = `(${text}`; - } - if (tokenString === ')') { - if (isAfterParenthesizedExpressions) { - text = `) ${text}`; - } else { - text = `${text})`; - } - } - - const trimmedText = text.trim(); - - if (isTraversal) { - if (text === '+' || text === '*') { - text = `${tokenString}${text}`; - } else if (trimmedText === 'and' || trimmedText === 'or' || trimmedText === 'not') { - text = `${tokenString} ${text}`; - } - } else if (trimmedText === 'and' || trimmedText === 'or' || trimmedText === 'not') { - text = ` ${trimmedText} `; // Insert spaces around the logical operator - } - - return { - text: text.replaceAll(/(\s)+/g, ' ').replaceAll(/(")+/g, '"'), - displayText: removeQuotesFromString(item), - }; - }); - - return { - list, - from: CodeMirror.Pos(cursor.line, start), - to: CodeMirror.Pos(cursor.line, end), - }; - }; -}; - -const removeQuotesFromString = (value: string) => { - if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') { - return value.slice(1, value.length - 1); - } - return value; -}; - -const addQuotesToString = (value: string) => `"${value}"`; - -const isPreTraversal = (tokensBefore: string[]) => { - // If there are no tokens before, it's the start of the line - if (tokensBefore.length === 0) { - return true; - } - - const previousToken = tokensBefore[tokensBefore.length - 1]; - - // Check if the previous token is 'and', 'or', or '(' - return ( - previousToken === 'and' || - previousToken === 'or' || - previousToken === '(' || - !previousToken || - tokensBefore.every((token) => ['*', '+'].includes(token)) - ); -}; diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionInput.oss.tsx b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionInput.oss.tsx index ef85abc7f3120..f3060d7f460f8 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionInput.oss.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionInput.oss.tsx @@ -1,14 +1,19 @@ -import {Colors, Icon, TextInputStyles} from '@dagster-io/ui-components'; +import {Colors, Icon, Icons} from '@dagster-io/ui-components'; import CodeMirror, {Editor, HintFunction} from 'codemirror'; import {useLayoutEffect, useMemo, useRef} from 'react'; -import styled, {createGlobalStyle} from 'styled-components'; +import styled, {createGlobalStyle, css} from 'styled-components'; -import {createAssetSelectionHint} from './AssetSelectionAutoComplete'; import {lintAssetSelection} from './AssetSelectionLinter'; -import {assetSelectionMode} from './AssetSelectionMode'; +import {assertUnreachable} from '../../app/Util'; import {AssetGraphQueryItem} from '../../asset-graph/useAssetGraphData'; import {useUpdatingRef} from '../../hooks/useUpdatingRef'; +import {createSelectionHint} from '../../selection/SelectionAutoComplete'; +import { + SelectionAutoCompleteInputCSS, + applyStaticSyntaxHighlighting, +} from '../../selection/SelectionAutoCompleteHighlighter'; import {placeholderTextForItems} from '../../ui/GraphQueryInput'; +import {buildRepoPathForHuman} from '../../workspace/buildRepoAddress'; import 'codemirror/addon/edit/closebrackets'; import 'codemirror/lib/codemirror.css'; @@ -24,18 +29,81 @@ interface AssetSelectionInputProps { onChange: (value: string) => void; } +const FUNCTIONS = ['sinks', 'roots']; + export const AssetSelectionInput = ({value, onChange, assets}: AssetSelectionInputProps) => { const editorRef = useRef(null); const cmInstance = useRef(null); const currentValueRef = useRef(value); - const hintRef = useUpdatingRef(useMemo(() => createAssetSelectionHint(assets), [assets])); + const hintRef = useUpdatingRef( + useMemo(() => { + const assetNamesSet: Set = new Set(); + const tagNamesSet: Set = new Set(); + const ownersSet: Set = new Set(); + const groupsSet: Set = new Set(); + const kindsSet: Set = new Set(); + const codeLocationSet: Set = new Set(); + + assets.forEach((asset) => { + assetNamesSet.add(asset.name); + asset.node.tags.forEach((tag) => { + if (tag.key && tag.value) { + tagNamesSet.add(`${tag.key}=${tag.value}`); + } else { + tagNamesSet.add(tag.key); + } + }); + asset.node.owners.forEach((owner) => { + switch (owner.__typename) { + case 'TeamAssetOwner': + ownersSet.add(owner.team); + break; + case 'UserAssetOwner': + ownersSet.add(owner.email); + break; + default: + assertUnreachable(owner); + } + }); + if (asset.node.groupName) { + groupsSet.add(asset.node.groupName); + } + asset.node.kinds.forEach((kind) => { + kindsSet.add(kind); + }); + const location = buildRepoPathForHuman( + asset.node.repository.name, + asset.node.repository.location.name, + ); + codeLocationSet.add(location); + }); + + const assetNames = Array.from(assetNamesSet); + const tagNames = Array.from(tagNamesSet); + const owners = Array.from(ownersSet); + const groups = Array.from(groupsSet); + const kinds = Array.from(kindsSet); + const codeLocations = Array.from(codeLocationSet); + + return createSelectionHint( + 'key', + { + key: assetNames, + tag: tagNames, + owner: owners, + group: groups, + kind: kinds, + code_location: codeLocations, + }, + FUNCTIONS, + ); + }, [assets]), + ); useLayoutEffect(() => { if (editorRef.current && !cmInstance.current) { - CodeMirror.defineMode('assetSelection', assetSelectionMode); - cmInstance.current = CodeMirror(editorRef.current, { value, mode: 'assetSelection', @@ -66,11 +134,11 @@ export const AssetSelectionInput = ({value, onChange, assets}: AssetSelectionInp }); cmInstance.current.on('change', (instance: Editor, change) => { - const newValue = instance.getValue(); + const newValue = instance.getValue().replace(/\s+/g, ' '); currentValueRef.current = newValue; onChange(newValue); - if (change.origin === 'complete' && change.text[0]?.endsWith(')')) { + if (change.origin === 'complete' && change.text[0]?.endsWith('()')) { // Set cursor inside the right parenthesis const cursor = instance.getCursor(); instance.setCursor({...cursor, ch: cursor.ch - 1}); @@ -82,8 +150,17 @@ export const AssetSelectionInput = ({value, onChange, assets}: AssetSelectionInp }); cmInstance.current.on('cursorActivity', (instance: Editor) => { + applyStaticSyntaxHighlighting(instance); showHint(instance, hintRef.current); }); + + requestAnimationFrame(() => { + if (!cmInstance.current) { + return; + } + + applyStaticSyntaxHighlighting(cmInstance.current); + }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -117,65 +194,24 @@ export const AssetSelectionInput = ({value, onChange, assets}: AssetSelectionInp ); }; - -const InputDiv = styled.div` - height: 32px; - width: 100%; - ${TextInputStyles} - flex-shrink: 1; - overflow: auto; - - .CodeMirror-placeholder.CodeMirror-placeholder.CodeMirror-placeholder { - color: ${Colors.textLighter()}; - } - - .CodeMirror-vscrollbar, - .CodeMirror-hscrollbar { - display: none !important; - } - - .CodeMirror-sizer, - .CodeMirror-lines { - height: 20px !important; - padding: 0; - } - - .CodeMirror-cursor.CodeMirror-cursor { - border-color: ${Colors.textLight()}; - } - - .CodeMirror { - background: transparent; - color: ${Colors.textDefault()}; - } - - .cm-attribute { - color: ${Colors.textCyan()}; - font-weight: bold; - } - - .cm-operator { - color: ${Colors.textRed()}; - font-weight: bold; - } - - .cm-string { - color: ${Colors.textGreen()}; - } - - .cm-function { - color: ${Colors.textYellow()}; - font-style: italic; +const iconStyle = (img: string) => css` + &:before { + content: ' '; + width: 14px; + mask-size: contain; + mask-repeat: no-repeat; + mask-position: center; + mask-image: url(${img}); + background: ${Colors.accentPrimary()}; + display: inline-block; } +`; - .cm-punctuation { - color: ${Colors.textDefault()}; - } +const InputDiv = styled.div` + ${SelectionAutoCompleteInputCSS} - .cm-error { - text-decoration-line: underline; - text-decoration-style: wavy; - text-decoration-color: ${Colors.accentRed()}; + .attribute-owner { + ${iconStyle(Icons.owner.src)} } `; @@ -200,6 +236,11 @@ const GlobalHintStyles = createGlobalStyle` function showHint(instance: Editor, hint: HintFunction) { requestAnimationFrame(() => { - instance.showHint({hint, completeSingle: false, moveOnOverlap: true}); + instance.showHint({ + hint, + completeSingle: false, + moveOnOverlap: true, + updateOnCursorActivity: true, + }); }); } diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts index 52bbb00b1b305..45b56fe1e08c2 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts @@ -1,23 +1,29 @@ import {CharStreams, CommonTokenStream} from 'antlr4ts'; import CodeMirror from 'codemirror'; -import {SyntaxErrorListener} from './AssetSelectionSyntaxErrorListener'; +import {AssetSelectionSyntaxErrorListener} from './AssetSelectionSyntaxErrorListener'; import {AssetSelectionLexer} from '../generated/AssetSelectionLexer'; import {AssetSelectionParser} from '../generated/AssetSelectionParser'; export const lintAssetSelection = (text: string) => { - const inputStream = CharStreams.fromString(text); - const lexer = new AssetSelectionLexer(inputStream); - const tokens = new CommonTokenStream(lexer); - const parser = new AssetSelectionParser(tokens); + const errorListener = new AssetSelectionSyntaxErrorListener(); - const errorListener = new SyntaxErrorListener(); - parser.removeErrorListeners(); // Remove default console error listener - parser.addErrorListener(errorListener); + try { + const inputStream = CharStreams.fromString(text); + const lexer = new AssetSelectionLexer(inputStream); - // Attempt to parse the input - parser.start(); // Assuming 'start' is the entry point of your grammar + lexer.removeErrorListeners(); + lexer.addErrorListener(errorListener); + const tokens = new CommonTokenStream(lexer); + const parser = new AssetSelectionParser(tokens); + + parser.removeErrorListeners(); // Remove default console error listener + parser.addErrorListener(errorListener); + + // Attempt to parse the input + parser.start(); // Assuming 'start' is the entry point of your grammar + } catch {} // Map syntax errors to CodeMirror's lint format const lintErrors = errorListener.errors.map((error) => ({ message: error.message.replace(', ', ''), diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionMode.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionMode.ts deleted file mode 100644 index dfcaaa0013cec..0000000000000 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionMode.ts +++ /dev/null @@ -1,128 +0,0 @@ -import {CharStreams, Token, Vocabulary} from 'antlr4ts'; -import {Mode} from 'codemirror'; - -import {AssetSelectionLexer} from '../generated/AssetSelectionLexer'; - -// Define an interface for the state to keep track of tokens and errors -interface AssetSelectionState { - tokens: Token[]; - tokenIndex: number; - errors: {start: number; end: number; message: string}[]; -} - -export function assetSelectionMode(): Mode { - return { - startState(): AssetSelectionState { - return { - tokens: [], - tokenIndex: 0, - errors: [], - }; - }, - token(stream, state) { - // Consume any whitespace at the current stream position - while (/\s/.test(stream.peek() ?? '')) { - stream.next(); - } - - // If all tokens have been processed, lex the rest of the line - if (state.tokenIndex >= state.tokens.length) { - // Read the rest of the line from the current position - const currentLine = stream.string.slice(stream.pos); - - if (currentLine.length === 0) { - // No more input to process - return null; - } - - try { - // Create a CharStream from the current line - const inputStream = CharStreams.fromString(currentLine); - - // Initialize the lexer with the input stream - const lexer = new AssetSelectionLexer(inputStream); - - // Collect all tokens from the lexer - const tokens: Token[] = []; - let token = lexer.nextToken(); - while (token.type !== Token.EOF) { - tokens.push(token); - token = lexer.nextToken(); - } - - // Update the state with the new tokens - state.tokens = tokens; - state.tokenIndex = 0; - } catch { - // Advance the stream to the end, marking as error - stream.skipToEnd(); - - // Return the 'error' style - return 'error'; - } - } - - if (state.tokenIndex < state.tokens.length) { - const token = state.tokens[state.tokenIndex++]!; - const tokenText = token.text!; - - // Consume any whitespace before matching the token - while (/\s/.test(stream.peek() ?? '')) { - stream.next(); - } - - // Match the token text from the stream - if (stream.match(tokenText)) { - // Map the token type to a CodeMirror style - const style = tokenTypeToStyle(token.type, AssetSelectionLexer.VOCABULARY); - return style; - } else { - // If there's a mismatch, consume the rest of the line and mark as error - stream.skipToEnd(); - return 'error'; - } - } else { - // No more tokens; skip to the end of the line - stream.skipToEnd(); - return null; - } - }, - }; -} - -function tokenTypeToStyle(tokenType: number, vocabulary: Vocabulary): string | null { - const tokenName = vocabulary.getSymbolicName(tokenType); - switch (tokenName) { - case 'KEY': - case 'KEY_SUBSTRING': - case 'TAG': - case 'OWNER': - case 'GROUP': - case 'KIND': - case 'CODE_LOCATION': - return 'attribute'; - case 'AND': - case 'OR': - case 'NOT': - return 'operator'; - case 'QUOTED_STRING': - case 'UNQUOTED_STRING': - return 'string'; - case 'SINKS': - case 'ROOTS': - return 'function'; - case 'STAR': - case 'PLUS': - return 'operator'; - case 'COLON': - case 'EQUAL': - case 'LPAREN': - case 'RPAREN': - case 'COMMA': - return 'punctuation'; - case 'WS': - return null; - default: - return 'error'; // Map any unknown tokens to 'error' style - } -} diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionSyntaxErrorListener.tsx b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionSyntaxErrorListener.tsx index c2bba4c13a072..89d87f2dbf09e 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionSyntaxErrorListener.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionSyntaxErrorListener.tsx @@ -6,7 +6,7 @@ interface SyntaxError { column: number; } -export class SyntaxErrorListener implements ANTLRErrorListener { +export class AssetSelectionSyntaxErrorListener implements ANTLRErrorListener { public errors: SyntaxError[] = []; syntaxError( @@ -15,7 +15,7 @@ export class SyntaxErrorListener implements ANTLRErrorListener { line: number, charPositionInLine: number, msg: string, - e: RecognitionException | undefined, + _e: RecognitionException | undefined, ): void { this.errors.push({ message: msg, diff --git a/js_modules/dagster-ui/packages/ui-core/src/scripts/generateSelection.ts b/js_modules/dagster-ui/packages/ui-core/src/scripts/generateSelection.ts new file mode 100644 index 0000000000000..8867ab86d630e --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/scripts/generateSelection.ts @@ -0,0 +1,16 @@ +import {execSync} from 'child_process'; +import path from 'path'; + +const SELECTION_GRAMMAR_FILE_PATH = path.resolve('./src/selection/SelectionAutoComplete.g4'); +execSync(`antlr4ts -visitor -o ./src/selection/generated ${SELECTION_GRAMMAR_FILE_PATH}`); + +const files = [ + 'SelectionAutoCompleteLexer.ts', + 'SelectionAutoCompleteListener.ts', + 'SelectionAutoCompleteParser.ts', + 'SelectionAutoCompleteVisitor.ts', +]; + +files.forEach((file) => { + execSync(`yarn prettier ./src/selection/generated/${file} --write`); +}); diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/CustomErrorListener.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/CustomErrorListener.ts new file mode 100644 index 0000000000000..39b40f9dcc68e --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/CustomErrorListener.ts @@ -0,0 +1,37 @@ +import {ANTLRErrorListener, RecognitionException, Recognizer} from 'antlr4ts'; +import {Token} from 'antlr4ts/Token'; + +export interface SyntaxError { + message: string; + line: number; + column: number; + offendingSymbol: Token | null; +} + +export class CustomErrorListener implements ANTLRErrorListener { + private errors: SyntaxError[]; + + constructor() { + this.errors = []; + } + + syntaxError( + _recognizer: Recognizer, + offendingSymbol: any, + line: number, + charPositionInLine: number, + msg: string, + _e: RecognitionException | undefined, + ): void { + this.errors.push({ + message: msg, + line, + column: charPositionInLine, + offendingSymbol, + }); + } + + getErrors(): SyntaxError[] { + return this.errors; + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 new file mode 100644 index 0000000000000..81553e238c0a2 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 @@ -0,0 +1,147 @@ +grammar SelectionAutoComplete; + +// Root rule for parsing expressions +start: expr EOF; + +// Root expression rule +expr + : traversalAllowedExpr afterExpressionWhitespace # TraversalAllowedExpression + | upTraversalExp traversalAllowedExpr downTraversalExp afterExpressionWhitespace # UpAndDownTraversalExpression + | upTraversalExp traversalAllowedExpr afterExpressionWhitespace # UpTraversalExpression + | traversalAllowedExpr downTraversalExp afterExpressionWhitespace # DownTraversalExpression + | notToken afterLogicalOperatorWhitespace expr afterExpressionWhitespace # NotExpression + | expr afterExpressionWhitespace andToken afterLogicalOperatorWhitespace expr afterExpressionWhitespace # AndExpression + | expr afterExpressionWhitespace orToken afterLogicalOperatorWhitespace expr afterExpressionWhitespace # OrExpression + | expr afterExpressionWhitespace andToken afterLogicalOperatorWhitespace # IncompleteAndExpression + | expr afterExpressionWhitespace orToken afterLogicalOperatorWhitespace # IncompleteOrExpression + | notToken afterLogicalOperatorWhitespace # IncompleteNotExpression + | expr afterExpressionWhitespace value afterLogicalOperatorWhitespace # UnmatchedExpressionContinuation + | STAR afterExpressionWhitespace # AllExpression + | value afterExpressionWhitespace # UnmatchedValue + ; + + +// Allowed expressions within traversal contexts +traversalAllowedExpr + : attributeName colonToken attributeValue # AttributeExpression + | functionName parenthesizedExpr # FunctionCallExpression + | parenthesizedExpr # ParenthesizedExpressionWrapper + | incompleteExpressionsWrapper # IncompleteExpression + ; + + +parenthesizedExpr + : leftParenToken expr rightParenToken # ParenthesizedExpression + ; + +// Incomplete expressions wrapper +incompleteExpressionsWrapper + : attributeName colonToken # IncompleteAttributeExpressionMissingValue + | functionName expressionLessParenthesizedExpr # ExpressionlessFunctionExpression + | functionName leftParenToken # UnclosedExpressionlessFunctionExpression + | functionName leftParenToken expr # UnclosedFunctionExpression + | leftParenToken expr # UnclosedParenthesizedExpression + | expressionLessParenthesizedExpr # ExpressionlessParenthesizedExpressionWrapper + | leftParenToken # UnclosedExpressionlessParenthesizedExpression + | PLUS+ # IncompleteTraversalExpression + | colonToken attributeValue # IncompleteAttributeExpressionMissingKey + ; + +expressionLessParenthesizedExpr + : leftParenToken rightParenToken # ExpressionlessParenthesizedExpression + ; + +upTraversalExp + : traversal # UpTraversal + ; + +downTraversalExp + : traversal # DownTraversal + ; + +traversal + : STAR + | PLUS+ + ; + +// Attribute and function names (to be validated externally) +attributeName + : IDENTIFIER + ; + + +attributeValue + : value + ; + +functionName + : IDENTIFIER + ; + +orToken + : OR + ; + +andToken + : AND + ; + +notToken + : NOT + ; + +colonToken + : COLON + ; + +leftParenToken + : LPAREN + ; + +rightParenToken + : RPAREN + ; + +afterExpressionWhitespace + : WS* + ; + +afterLogicalOperatorWhitespace + : WS* + ; + + +// Value can be a quoted string, unquoted string, or identifier +value + : QUOTED_STRING # QuotedStringValue + | INCOMPLETE_LEFT_QUOTED_STRING # IncompleteLeftQuotedStringValue + | INCOMPLETE_RIGHT_QUOTED_STRING # IncompleteRightQuotedStringValue + | IDENTIFIER # UnquotedStringValue + ; + +// Tokens for operators and keywords +AND : 'and'; +OR : 'or'; +NOT : 'not'; + +STAR : '*'; +PLUS : '+'; + +COLON : ':'; + +LPAREN : '('; +RPAREN : ')'; + +EQUAL : '='; + +// Tokens for strings +QUOTED_STRING : '"' (~["\\\r\n])* '"' ; +INCOMPLETE_LEFT_QUOTED_STRING: '"' (~["\\\r\n():])* ; +INCOMPLETE_RIGHT_QUOTED_STRING: (~["\\\r\n:()])* '"' ; + +// Identifiers (attributes and functions) +IDENTIFIER : [a-zA-Z_][a-zA-Z0-9_]*; + + +// Whitespace +WS : [ \t\r\n]+; diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts new file mode 100644 index 0000000000000..9b99867ec01df --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts @@ -0,0 +1,483 @@ +import {ParserRuleContext} from 'antlr4ts'; +import {AbstractParseTreeVisitor} from 'antlr4ts/tree/AbstractParseTreeVisitor'; +import {ParseTree} from 'antlr4ts/tree/ParseTree'; +import {RuleNode} from 'antlr4ts/tree/RuleNode'; +import CodeMirror from 'codemirror'; + +import {parseInput} from './SelectionAutoCompleteInputParser'; +import { + isInsideExpressionlessParenthesizedExpression, + removeQuotesFromString, +} from './SelectionAutoCompleteUtil'; +import { + AfterExpressionWhitespaceContext, + AfterLogicalOperatorWhitespaceContext, + AllExpressionContext, + AndTokenContext, + AttributeNameContext, + AttributeValueContext, + ColonTokenContext, + FunctionNameContext, + LeftParenTokenContext, + OrTokenContext, + ParenthesizedExpressionContext, + UnmatchedValueContext, + UpTraversalContext, +} from './generated/SelectionAutoCompleteParser'; +import {SelectionAutoCompleteVisitor as _SelectionAutoCompleteVisitor} from './generated/SelectionAutoCompleteVisitor'; + +type Suggestion = {text: string; displayText?: string}; +type TextCallback = (value: string) => string; +const DEFAULT_TEXT_CALLBACK = (value: string) => value; + +// set to true for useful debug output. +const DEBUG = true; + +export class SelectionAutoCompleteVisitor + extends AbstractParseTreeVisitor + implements _SelectionAutoCompleteVisitor +{ + private cursorIndex: number; + private line: string; + private attributesMap: Record; + private functions: string[]; + private nameBase: string; + private attributesWithNameBase: string[]; + private allAttributes: {key: string; value: string}[]; + public list: Suggestion[] = []; + public _startReplacementIndex: number = 0; + public _stopReplacementIndex: number = 0; + + set startReplacementIndex(newValue: number) { + if (DEBUG) { + console.log('Autocomplete suggestions being set by stack:', new Error()); + } + this._startReplacementIndex = newValue; + } + set stopReplacementIndex(newValue: number) { + this._stopReplacementIndex = newValue; + } + get startReplacementIndex() { + return this._startReplacementIndex; + } + get stopReplacementIndex() { + return this._stopReplacementIndex; + } + + constructor({ + attributesMap, + functions, + nameBase, + line, + cursorIndex, + }: { + attributesMap: Record; + functions: string[]; + nameBase: string; + line: string; + cursorIndex: number; + }) { + super(); + this.cursorIndex = cursorIndex; + this.line = line; + this.attributesMap = attributesMap; + this.functions = functions; + this.nameBase = nameBase; + this.attributesWithNameBase = [ + `${this.nameBase}_substring`, + this.nameBase, + ...Object.keys(attributesMap).filter((name) => name !== this.nameBase), + ]; + this.allAttributes = Object.keys(attributesMap).flatMap((key) => { + return ( + attributesMap[key]?.sort((a, b) => a.localeCompare(b)).map((value) => ({key, value})) ?? [] + ); + }); + this._startReplacementIndex = cursorIndex; + this._stopReplacementIndex = cursorIndex; + } + + visit(tree: ParseTree) { + const _tree = tree as ParserRuleContext; + if ( + _tree.start.startIndex !== undefined && + _tree.stop?.stopIndex !== undefined && + !this.nodeIncludesCursor(_tree) + ) { + if (!tree.parent) { + // If we're at the root but not within the expression then we're at the whitespace before any expression. + this.addUnmatchedValueResults(''); + this.startReplacementIndex = this.cursorIndex; + this.stopReplacementIndex = this.cursorIndex; + } + return; + } + return super.visit(tree); + } + + visitChildren(node: RuleNode): void { + let result = this.defaultResult(); + const n = node.childCount; + for (let i = 0; i < n; i++) { + if (!this.shouldVisitNextChild(node, result)) { + break; + } + const c = node.getChild(i) as any; + if (c.start && c.stop) { + const isWhiteSpace = c.constructor.name.endsWith('WhitespaceContext'); + if ( + !this.nodeIncludesCursor(c) && + (!isWhiteSpace || c.start.startIndex !== this.cursorIndex) + ) { + continue; + } + } + if (DEBUG) { + console.log('visiting child', c.constructor.name, c.text); + } + const childResult = c.accept(this); + result = this.aggregateResult(result, childResult); + } + return result; + } + + protected defaultResult() {} + + private nodeIncludesCursor(ctx: Pick): boolean { + const start = ctx.start.startIndex; + const stop = ctx.stop ? ctx.stop.stopIndex : ctx.start.startIndex; + + return Math.max(0, this.cursorIndex - 1) >= start && this.cursorIndex - 1 <= stop; + } + + private addAttributeResults(value: string, textCallback: TextCallback = DEFAULT_TEXT_CALLBACK) { + this.list.push( + ...this.attributesWithNameBase + .filter((attr) => attr.startsWith(value.trim())) + .map((val) => { + const suggestionValue = `${val}:`; + return {text: textCallback(suggestionValue), displayText: suggestionValue}; + }), + ); + } + + private addFunctionResults( + value: string, + textCallback: TextCallback = DEFAULT_TEXT_CALLBACK, + includeParenthesis: boolean = false, + ) { + this.list.push( + ...this.functions + .filter((fn) => fn.startsWith(value.trim())) + .map((val) => { + const suggestionValue = `${val}${includeParenthesis ? '()' : ''}`; + return { + text: textCallback(suggestionValue), + displayText: suggestionValue, + }; + }), + ); + } + + public addUnmatchedValueResults( + _value: string, + textCallback: TextCallback = DEFAULT_TEXT_CALLBACK, + options: {excludeNot?: boolean} = {}, + ) { + const value = _value.trim(); + if (value) { + const substringMatchDisplayText = `${this.nameBase}_substring:${removeQuotesFromString( + value, + )}`; + const substringMatchText = `${this.nameBase}_substring:"${removeQuotesFromString(value)}"`; + this.list.push({ + text: textCallback(substringMatchText), + displayText: substringMatchDisplayText, + }); + } + this.addAttributeResults(value, textCallback); + this.addFunctionResults(value, textCallback, true); + + if (value) { + this.allAttributes.forEach((attribute) => { + if (attribute.value.includes(value.toLowerCase())) { + this.list.push({ + text: textCallback(`${attribute.key}:"${attribute.value}"`), + displayText: `${attribute.key}:${attribute.value}`, + }); + } + }); + } + + if (!options.excludeNot && 'not'.startsWith(value)) { + this.list.push({text: textCallback('not '), displayText: 'not'}); + } + if (value === '') { + this.list.push( + {text: textCallback('*'), displayText: '*'}, + {text: textCallback('+'), displayText: '+'}, + {text: textCallback('()'), displayText: '('}, + ); + } + } + + private addAttributeValueResults( + attributeKey: string, + value: string, + textCallback: TextCallback = DEFAULT_TEXT_CALLBACK, + ) { + let possibleValues = this.attributesMap[attributeKey] ?? []; + if (attributeKey === `${this.nameBase}_substring`) { + possibleValues = this.attributesMap[this.nameBase]!; + } + const unquotedValue = removeQuotesFromString(value); + possibleValues.forEach((attributeValue) => { + if (attributeValue.includes(unquotedValue)) { + this.list.push({ + text: textCallback(`"${attributeValue}"`), + displayText: attributeValue, + }); + } + }); + } + + private addAfterExpressionResults(ctx: ParserRuleContext) { + this.list.push( + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ); + + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')', displayText: ')'}); + } + } + + visitAllExpression(ctx: AllExpressionContext) { + this.startReplacementIndex = this.cursorIndex; + this.stopReplacementIndex = this.cursorIndex; + this.addUnmatchedValueResults(''); + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')', displayText: ')'}); + } + } + + visitUpTraversal(ctx: UpTraversalContext) { + if (ctx.text.includes('+')) { + this.list.push({text: '+', displayText: '+'}); + } + this.list.push({text: '(', displayText: '('}); + } + + visitDownTraversal(ctx: UpTraversalContext) { + this.list.push({text: ' and ', displayText: 'and'}); + this.list.push({text: ' or ', displayText: 'or'}); + if (ctx.text.includes('+')) { + this.list.push({text: '+', displayText: '+'}); + } + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')', displayText: ')'}); + } + } + + visitParenthesizedExpression(ctx: ParenthesizedExpressionContext) { + if (this.nodeIncludesCursor(ctx.leftParenToken())) { + // Move the cursor to the right and visit that expression. + this.cursorIndex += 1; + } + this.visit(ctx.expr()); + } + + visitFunctionName(ctx: FunctionNameContext) { + if (this.nodeIncludesCursor(ctx)) { + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.addFunctionResults(ctx.text); + } + } + + visitAttributeValue(ctx: AttributeValueContext) { + if (this.nodeIncludesCursor(ctx)) { + const stopIndex = ctx.stop!.stopIndex; + if (this.cursorIndex > stopIndex && this.line[stopIndex] === '"') { + this.addAfterExpressionResults(ctx); + return; + } + this.startReplacementIndex = ctx.start!.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + const parentChildren = ctx.parent?.children ?? []; + if (parentChildren[0]?.constructor.name === 'AttributeNameContext') { + this.addAttributeValueResults(parentChildren[0].text, getValue(ctx.value())); + } + } + } + + visitColonToken(ctx: ColonTokenContext) { + if (this.nodeIncludesCursor(ctx)) { + let attributeName = ''; + + let valueNode: ParserRuleContext | null = null; + const parentChildren = ctx.parent?.children ?? []; + if (parentChildren[0]?.constructor.name === 'AttributeNameContext') { + attributeName = parentChildren[0].text; + } + if (parentChildren[1]?.constructor.name === 'AttributeValueContext') { + valueNode = parentChildren[1] as any; + } else if (parentChildren[2]?.constructor.name === 'AttributeValueContext') { + valueNode = parentChildren[2] as any; + } + if (attributeName) { + this.startReplacementIndex = ctx.start.startIndex + 1; + this.stopReplacementIndex = this.startReplacementIndex; + if (valueNode?.stop) { + this.stopReplacementIndex = valueNode.stop?.stopIndex + 1; + } + this.addAttributeValueResults(attributeName, getValue(valueNode)); + } + } + } + + visitAttributeName(ctx: AttributeNameContext) { + if (this.nodeIncludesCursor(ctx)) { + if (this.line[this.cursorIndex] === ':') { + // Increase cursor index to make sure the colon character is visited. + this.cursorIndex += 1; + } else { + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 2; + this.addAttributeResults(ctx.text); + } + } + } + + visitOrToken(ctx: OrTokenContext) { + if (this.cursorIndex > ctx.stop!.stopIndex) { + // Let whitespace token handle this + } else { + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.list.push({text: 'or', displayText: 'or'}, {text: 'and', displayText: 'and'}); + } + } + + visitAndToken(ctx: AndTokenContext) { + if (this.cursorIndex > ctx.stop!.stopIndex) { + // Let whitespace token handle this + } else { + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.list.push({text: 'and', displayText: 'and'}, {text: 'or', displayText: 'or'}); + } + } + + visitUnmatchedValue(ctx: UnmatchedValueContext) { + if (this.nodeIncludesCursor(ctx)) { + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.addUnmatchedValueResults(ctx.text); + } + } + + // This is visited even if the whitespace has length 0. + visitAfterExpressionWhitespace(ctx: AfterExpressionWhitespaceContext) { + if (!this.list.length) { + // Check if anything before us already made suggestions + // Since we get called even if the previous token handled it + this.addAfterExpressionResults(ctx); + } + } + + // This is visited even if the whitespace has length 0. + visitAfterLogicalOperatorWhitespace(ctx: AfterLogicalOperatorWhitespaceContext) { + // Check if anything before us already made suggestions + // Since we get called even if the previous token handled it + if (!this.list.length) { + const isAfterNot = this.line.slice(0, this.cursorIndex).trim().toLowerCase().endsWith('not'); + const needsWhitespace = this.cursorIndex === ctx.start.startIndex; + this.addUnmatchedValueResults('', (text) => `${needsWhitespace ? ' ' : ''}${text}`, { + excludeNot: isAfterNot, + }); + } + } + + visitLeftParenToken(_ctx: LeftParenTokenContext) { + this.addUnmatchedValueResults(''); + } +} + +export function createSelectionHint, N extends keyof T>( + _nameBase: N, + attributesMap: T, + functions: string[], +): CodeMirror.HintFunction { + const nameBase = _nameBase as string; + + return function (cm: CodeMirror.Editor, _options: CodeMirror.ShowHintOptions): any { + const line = cm.getLine(0); + const {parseTrees} = parseInput(line); + + let start = 0; + const actualCursorIndex = cm.getCursor().ch; + + let visitorWithAutoComplete; + if (!parseTrees.length) { + // Special case empty string to add unmatched value results + visitorWithAutoComplete = new SelectionAutoCompleteVisitor({ + attributesMap, + functions, + nameBase, + line, + cursorIndex: actualCursorIndex, + }); + start = actualCursorIndex; + visitorWithAutoComplete.addUnmatchedValueResults(''); + } else { + for (const {tree, line} of parseTrees) { + const cursorIndex = actualCursorIndex - start; + const visitor = new SelectionAutoCompleteVisitor({ + attributesMap, + functions, + nameBase, + line, + cursorIndex, + }); + visitor.visit(tree); + const length = line.length; + if (cursorIndex <= length) { + visitorWithAutoComplete = visitor; + break; + } + start += length; + } + } + if (visitorWithAutoComplete) { + return { + list: visitorWithAutoComplete.list, + from: cm.posFromIndex(start + visitorWithAutoComplete.startReplacementIndex), + to: cm.posFromIndex(start + visitorWithAutoComplete.stopReplacementIndex), + }; + } + }; +} + +function getValue(ctx: ParserRuleContext | null) { + switch (ctx?.constructor.name) { + case 'UnquotedStringValueContext': { + return ctx.text; + } + case 'IncompleteLeftQuotedStringValueContext': { + return ctx.text.slice(1); + } + case 'IncompleteRightQuotedStringValueContext': { + return ctx.text.slice(0, -1); + } + case 'QuotedStringValueContext': { + return ctx.text.slice(1, -1); + } + case 'AttributeValueContext': { + return getValue((ctx as AttributeValueContext).value()); + } + } + return ctx?.text ?? ''; +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts new file mode 100644 index 0000000000000..de562dd93771a --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts @@ -0,0 +1,265 @@ +import {Colors, TextInputStyles} from '@dagster-io/ui-components'; +import {ParserRuleContext} from 'antlr4ts'; +import {AbstractParseTreeVisitor} from 'antlr4ts/tree/AbstractParseTreeVisitor'; +import CodeMirror from 'codemirror'; +import {css} from 'styled-components'; + +import {parseInput} from './SelectionAutoCompleteInputParser'; +import { + AllExpressionContext, + AttributeExpressionContext, + AttributeNameContext, + AttributeValueContext, + FunctionNameContext, + IncompleteAttributeExpressionMissingKeyContext, + IncompleteAttributeExpressionMissingValueContext, + ParenthesizedExpressionContext, + QuotedStringValueContext, + StartContext, + UnquotedStringValueContext, +} from './generated/SelectionAutoCompleteParser'; +import {SelectionAutoCompleteVisitor} from './generated/SelectionAutoCompleteVisitor'; + +export class SyntaxHighlightingVisitor + extends AbstractParseTreeVisitor + implements SelectionAutoCompleteVisitor +{ + private cm: CodeMirror.Editor; + private startOffset: number; + private cursorIndex: number; + + constructor(cm: CodeMirror.Editor, startOffSet: number, cursorIndex: number) { + super(); + this.cm = cm; + this.startOffset = startOffSet; + this.cursorIndex = cursorIndex; + } + + protected defaultResult() {} + + private addClass(ctx: ParserRuleContext, klass: string) { + const from = this.cm.posFromIndex(this.startOffset + ctx.start.startIndex); + const to = this.cm.posFromIndex(this.startOffset + ctx.stop!.stopIndex + 1); + this.cm.markText(from, to, {className: klass}); + } + + private addActiveClass(ctx: ParserRuleContext, klass: string = 'active') { + if (ctx.start.startIndex < this.cursorIndex && (ctx.stop?.stopIndex ?? 0) < this.cursorIndex) { + this.addClass(ctx, klass); + } + } + + // Visit methods + visitStart(ctx: StartContext) { + this.visit(ctx.expr()); + } + + visitIncompleteAttributeExpressionMissingValue( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) { + this.addClass(ctx, 'expression attribute-expression'); + this.visitChildren(ctx); + } + visitIncompleteAttributeExpressionMissingKey( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) { + this.addClass(ctx, 'expression attribute-expression'); + this.visitChildren(ctx); + } + + visitAttributeExpression(ctx: AttributeExpressionContext) { + this.addClass(ctx, 'expression attribute-expression'); + this.visitChildren(ctx); + } + + visitAttributeName(ctx: AttributeNameContext) { + this.addClass(ctx, `attribute-name attribute-${ctx.text}`); + this.visitChildren(ctx); + } + + visitAttributeValue(ctx: AttributeValueContext) { + this.addClass(ctx, `attribute-value`); + this.visitChildren(ctx); + } + + visitFunctionName(ctx: FunctionNameContext) { + this.addClass(ctx, `function-name function-${ctx.text}`); + this.visitChildren(ctx); + } + + visitQuotedStringValue(ctx: QuotedStringValueContext) { + this.addClass(ctx, 'value'); + this.visitChildren(ctx); + } + + visitUnquotedStringValue(ctx: UnquotedStringValueContext) { + this.addClass(ctx, 'value'); + this.visitChildren(ctx); + } + + visitAllExpression(ctx: AllExpressionContext) { + this.addClass(ctx, 'value'); + this.visitChildren(ctx); + } + visitIncompleteLeftQuotedStringValue(ctx: ParserRuleContext) { + this.addClass(ctx, 'value'); + this.visitChildren(ctx); + } + visitIncompleteRightQuotedStringValue(ctx: ParserRuleContext) { + this.addClass(ctx, 'value'); + this.visitChildren(ctx); + } + visitTraversalAllowedExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitUpAndDownTraversalExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitUpTraversalExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitDownTraversalExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitNotExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitOrExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitAndExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitIncompleteNotExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitIncompleteOrExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitIncompleteAndExpression(ctx: ParserRuleContext) { + this.addClass(ctx, 'expression'); + this.visitChildren(ctx); + } + visitParenthesizedExpression(ctx: ParenthesizedExpressionContext) { + this.addActiveClass(ctx, 'active-parenthesis'); + this.visitChildren(ctx); + } +} + +export function applyStaticSyntaxHighlighting(cm: CodeMirror.Editor): void { + const value = cm.getValue(); + + // Clear existing marks to avoid duplication + cm.getAllMarks().forEach((mark) => { + // Don't clear error marks coming from the linter which uses the real grammar's parser + if ((mark as any)?.__annotation?.severity !== 'error') { + mark.clear(); + } + }); + + const cursorIndex = cm.getCursor().ch; + const {parseTrees} = parseInput(value); + let start = 0; + for (const {tree, line} of parseTrees) { + const visitor = new SyntaxHighlightingVisitor(cm, start, cursorIndex - start); + visitor.visit(tree); + start += line.length; + } + cm.markText(cm.posFromIndex(0), cm.posFromIndex(value.length), {className: 'selection'}); +} + +const lastElementInTokenStyle = css` + padding-right: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; +`; + +export const SelectionAutoCompleteInputCSS = css` + height: 32px; + width: 100%; + ${TextInputStyles} + flex-shrink: 1; + overflow: auto; + + .CodeMirror-placeholder.CodeMirror-placeholder.CodeMirror-placeholder { + color: ${Colors.textLighter()}; + } + .CodeMirror-line > span { + align-items: center; + } + + .CodeMirror-scrollbar-filler, + .CodeMirror-vscrollbar, + .CodeMirror-hscrollbar { + display: none !important; + } + + .CodeMirror-sizer, + .CodeMirror-lines { + height: 20px !important; + padding: 0; + } + + .CodeMirror-cursor.CodeMirror-cursor { + border-color: ${Colors.textLight()}; + } + + .CodeMirror { + background: transparent; + color: ${Colors.textDefault()}; + } + + .CodeMirror-line .selection:not(.expression), + .CodeMirror-lint-mark-error { + background: unset; + text-decoration-line: underline; + text-decoration-style: wavy; + text-decoration-color: ${Colors.accentRed()}; + } + + .expression { + color: ${Colors.textRed()}; + font-weight: bold; + } + + .attribute-expression { + color: ${Colors.textDefault()}; + } + + .attribute-expression:not(.attribute-expression + .attribute-expression) { + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; + } + + .attribute-name { + color: ${Colors.textCyan()}; + font-weight: bold; + padding-left: 4px; + } + + .attribute-expression { + background: ${Colors.backgroundYellow()}; + } + + .attribute-expression:not(:has(+ .attribute-expression)) { + ${lastElementInTokenStyle} + } + + .value { + color: ${Colors.textGreen()}; + } + + .function-name { + color: ${Colors.textYellow()}; + font-style: italic; + } +`; diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteInputParser.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteInputParser.ts new file mode 100644 index 0000000000000..77d3b5b52c832 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteInputParser.ts @@ -0,0 +1,109 @@ +// parser.ts + +import {BailErrorStrategy, CharStreams, CommonTokenStream} from 'antlr4ts'; +import {ParseTree} from 'antlr4ts/tree/ParseTree'; +import memoize from 'lodash/memoize'; + +import {CustomErrorListener, SyntaxError} from './CustomErrorListener'; +import {SelectionAutoCompleteLexer} from './generated/SelectionAutoCompleteLexer'; +import {SelectionAutoCompleteParser} from './generated/SelectionAutoCompleteParser'; + +/** + * Represents the result of parsing, including the array of parse trees and any syntax errors. + */ +interface ParseResult { + parseTrees: ParseTreeResult[]; + errors: SyntaxError[]; +} + +interface ParseTreeResult { + tree: ParseTree; + line: string; +} + +/** + * Parses the input and constructs an array of parse trees along with any syntax errors. + * @param input - The input string to parse. + * @returns The parse result containing the array of parse trees and syntax errors. + */ +export const parseInput = memoize((input: string): ParseResult => { + const parseTrees: ParseTreeResult[] = []; + const errors: SyntaxError[] = []; + + let currentPosition = 0; + const inputLength = input.length; + + while (currentPosition < inputLength) { + // Create a substring from the current position + const substring = input.substring(currentPosition); + + // Initialize ANTLR input stream, lexer, and parser + const inputStream = CharStreams.fromString(substring); + const lexer = new SelectionAutoCompleteLexer(inputStream); + const tokenStream = new CommonTokenStream(lexer); + const parser = new SelectionAutoCompleteParser(tokenStream); + + // Attach custom error listener + const errorListener = new CustomErrorListener(); + parser.removeErrorListeners(); + parser.addErrorListener(errorListener); + + // Set the error handler to bail on error to prevent infinite loops + parser.errorHandler = new BailErrorStrategy(); + + let tree: ParseTree | null = null; + try { + // Parse using the 'expr' rule instead of 'start' to allow partial parsing + tree = parser.expr(); + parseTrees.push({tree, line: substring}); + + // Advance currentPosition to the end of the parsed input + const lastToken = tokenStream.get(tokenStream.index - 1); + currentPosition += lastToken.stopIndex + 1; + } catch (e) { + // Parsing error occurred + const currentErrors = errorListener.getErrors(); + + if (currentErrors.length > 0) { + const error = currentErrors[0]!; + const errorCharPos = error.column; + const errorIndex = currentPosition + errorCharPos; + + // Parse up to the error + const validInput = input.substring(currentPosition, errorIndex); + if (validInput.trim().length > 0) { + const validInputStream = CharStreams.fromString(validInput); + const validLexer = new SelectionAutoCompleteLexer(validInputStream); + const validTokenStream = new CommonTokenStream(validLexer); + const validParser = new SelectionAutoCompleteParser(validTokenStream); + + // Remove error listeners for the valid parser + validParser.removeErrorListeners(); + + try { + const validTree = validParser.expr(); + parseTrees.push({tree: validTree, line: validInput}); + } catch { + // Ignore errors here since we already have an error in currentErrors + } + } + + // Add the error to the errors array + errors.push({ + message: error.message, + line: error.line, + column: error.column + currentPosition, + offendingSymbol: error.offendingSymbol, + }); + + // Advance currentPosition beyond the error + currentPosition = errorIndex + 1; + } else { + // Critical parsing error, break the loop + break; + } + } + } + + return {parseTrees, errors}; +}); diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteUtil.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteUtil.ts new file mode 100644 index 0000000000000..892c743769525 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteUtil.ts @@ -0,0 +1,32 @@ +import {ParserRuleContext} from 'antlr4ts'; + +export const removeQuotesFromString = (value: string) => { + if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') { + return value.slice(1, value.length - 1); + } + return value; +}; + +export function getValueNodeValue(ctx: ParserRuleContext) { + let nodeValue = ctx.text; + const nodeType = ctx.constructor.name; + if (nodeType === 'QuotedStringValueContext') { + nodeValue = nodeValue.slice(1, -1); + } else if (nodeType === 'IncompleteLeftQuotedStringValueContext') { + nodeValue = nodeValue.slice(1); + } else if (nodeType === 'IncompleteRightQuotedStringValueContext') { + nodeValue = nodeValue.slice(0, -1); + } + return nodeValue.trim(); +} + +export function isInsideExpressionlessParenthesizedExpression(context: ParserRuleContext) { + if (context.parent) { + const nodeType = context.parent.constructor.name; + if (nodeType.startsWith('Unclosed')) { + return true; + } + return isInsideExpressionlessParenthesizedExpression(context.parent); + } + return false; +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts new file mode 100644 index 0000000000000..bf4bb8ce7f5b8 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts @@ -0,0 +1,711 @@ +import {Hint, Hints, Position} from 'codemirror'; + +import {createSelectionHint} from '../SelectionAutoComplete'; + +describe('createAssetSelectionHint', () => { + const selectionHint = createSelectionHint( + 'key', + { + key: ['asset1', 'asset2', 'asset3'], + tag: ['tag1', 'tag2', 'tag3'], + owner: ['marco@dagsterlabs.com', 'team:frontend'], + group: ['group1', 'group2'], + kind: ['kind1', 'kind2'], + code_location: ['repo1@location1', 'repo2@location2'], + }, + ['sinks', 'roots'], + ); + + type HintsModified = Omit & { + list: Array; + }; + + function testAutocomplete(testString: string) { + const cursorIndex = testString.indexOf('|'); + const string = testString.split('|').join(''); + + mockEditor.getCursor.mockReturnValue({ch: cursorIndex}); + mockEditor.getLine.mockReturnValue(string); + + const hints = selectionHint(mockEditor, {}) as HintsModified; + + return { + list: hints.list, + from: hints.from.ch, + to: hints.to.ch, + }; + } + + const mockEditor = { + getCursor: jest.fn(), + getLine: jest.fn(), + posFromIndex: (index: number) => + ({ + ch: index, + line: 0, + }) as Position, + } as any; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should suggest asset names after typing key_substring:', () => { + // cursorIndex 14 + expect(testAutocomplete('key_substring:|')).toEqual({ + list: [ + {text: '"asset1"', displayText: 'asset1'}, + {text: '"asset2"', displayText: 'asset2'}, + {text: '"asset3"', displayText: 'asset3'}, + ], + from: 14, // cursor location + to: 14, // cursor location + }); + }); + + it('should suggest owners after typing owner:', () => { + expect(testAutocomplete('owner:|')).toEqual({ + list: [ + { + text: '"marco@dagsterlabs.com"', + displayText: 'marco@dagsterlabs.com', + }, + { + text: '"team:frontend"', + displayText: 'team:frontend', + }, + ], + from: 6, // cursor location + to: 6, // cursor location + }); + }); + + it('should suggest tag names after typing tag:', () => { + expect(testAutocomplete('tag:|')).toEqual({ + list: [ + {text: '"tag1"', displayText: 'tag1'}, + {text: '"tag2"', displayText: 'tag2'}, + {text: '"tag3"', displayText: 'tag3'}, + ], + from: 4, // cursor location + to: 4, // cursor location + }); + }); + + it('should suggest logical operators after an expression', () => { + expect(testAutocomplete('key:"asset1" |')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 13, // cursor location + to: 13, // cursor location + }); + + expect(testAutocomplete('key:"asset1"|')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 12, // cursor location + to: 12, // cursor location + }); + }); + + it('should filter suggestions based on partial input', () => { + expect(testAutocomplete('owner:marco|')).toEqual({ + list: [ + { + text: '"marco@dagsterlabs.com"', + displayText: 'marco@dagsterlabs.com', + }, + ], + from: 6, // start of value "marco" + to: 11, // end of value + }); + }); + + it('should suggest possible keywords', () => { + // empty case + expect(testAutocomplete('|')).toEqual({ + list: [ + {displayText: 'key_substring:', text: 'key_substring:'}, + {displayText: 'key:', text: 'key:'}, + {displayText: 'tag:', text: 'tag:'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'group:', text: 'group:'}, + {displayText: 'kind:', text: 'kind:'}, + {displayText: 'code_location:', text: 'code_location:'}, + {displayText: 'sinks()', text: 'sinks()'}, + {displayText: 'roots()', text: 'roots()'}, + {displayText: 'not', text: 'not '}, + {displayText: '*', text: '*'}, + {displayText: '+', text: '+'}, + {displayText: '(', text: '()'}, + ], + from: 0, // cursor location + to: 0, // cursor location + }); + + // filtered case + expect(testAutocomplete('o|')).toEqual({ + list: [ + {displayText: 'key_substring:o', text: 'key_substring:"o"'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'owner:marco@dagsterlabs.com', text: 'owner:"marco@dagsterlabs.com"'}, + {displayText: 'owner:team:frontend', text: 'owner:"team:frontend"'}, + {displayText: 'group:group1', text: 'group:"group1"'}, + {displayText: 'group:group2', text: 'group:"group2"'}, + {displayText: 'code_location:repo1@location1', text: 'code_location:"repo1@location1"'}, + {displayText: 'code_location:repo2@location2', text: 'code_location:"repo2@location2"'}, + ], + from: 0, // start of input + to: 1, // cursor location + }); + }); + + it('should handle traversal operators correctly', () => { + expect(testAutocomplete('*|')).toEqual({ + list: [ + {displayText: 'key_substring:', text: 'key_substring:'}, + {displayText: 'key:', text: 'key:'}, + {displayText: 'tag:', text: 'tag:'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'group:', text: 'group:'}, + {displayText: 'kind:', text: 'kind:'}, + {displayText: 'code_location:', text: 'code_location:'}, + {displayText: 'sinks()', text: 'sinks()'}, + {displayText: 'roots()', text: 'roots()'}, + {displayText: 'not', text: 'not '}, + {displayText: '*', text: '*'}, + {displayText: '+', text: '+'}, + {displayText: '(', text: '()'}, + ], + from: 1, // cursor location + to: 1, // cursor location + }); + }); + + it('should suggest code locations after typing code_location:', () => { + expect(testAutocomplete('code_location:|')).toEqual({ + list: [ + {text: '"repo1@location1"', displayText: 'repo1@location1'}, + {text: '"repo2@location2"', displayText: 'repo2@location2'}, + ], + from: 14, + to: 14, + }); + }); + + it('should handle incomplete "not" expressions', () => { + expect(testAutocomplete('not|')).toEqual({ + list: [ + {text: ' key_substring:', displayText: 'key_substring:'}, + {text: ' key:', displayText: 'key:'}, + {text: ' tag:', displayText: 'tag:'}, + {text: ' owner:', displayText: 'owner:'}, + {text: ' group:', displayText: 'group:'}, + {text: ' kind:', displayText: 'kind:'}, + {text: ' code_location:', displayText: 'code_location:'}, + {text: ' sinks()', displayText: 'sinks()'}, + {text: ' roots()', displayText: 'roots()'}, + {text: ' *', displayText: '*'}, + {text: ' +', displayText: '+'}, + {text: ' ()', displayText: '('}, + ], + from: 3, // cursor location + to: 3, // cursor location + }); + + expect(testAutocomplete('not |')).toEqual({ + list: [ + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 4, // cursor location + to: 4, // cursor location + }); + }); + + it('should handle incomplete and expressions', () => { + expect(testAutocomplete('key:"asset1" and |')).toEqual({ + list: [ + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: 'not ', displayText: 'not'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 17, // cursor location + to: 17, // cursor location + }); + }); + + it('should handle incomplete or expressions', () => { + expect(testAutocomplete('key:"asset1" or |')).toEqual({ + list: [ + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: 'not ', displayText: 'not'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 16, // cursor location + to: 16, // cursor location + }); + }); + + it('should handle incomplete quoted strings gracefully', () => { + expect(testAutocomplete('key:"asse|')).toEqual({ + list: [ + {displayText: 'asset1', text: '"asset1"'}, + {displayText: 'asset2', text: '"asset2"'}, + {displayText: 'asset3', text: '"asset3"'}, + ], + from: 4, // start of value + to: 9, // end of value + }); + }); + + it('should handle incomplete or expression within function', () => { + expect( + testAutocomplete('sinks(key_substring:"FIVETRAN/google_ads/ad_group_history" or |)'), + ).toEqual({ + list: [ + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: 'not ', displayText: 'not'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 62, // cursor location + to: 62, // cursor location + }); + }); + + it('should handle incomplete or expression within function with cursor right after the "or"', () => { + expect( + testAutocomplete('sinks(key_substring:"FIVETRAN/google_ads/ad_group_history" or|)'), + ).toEqual({ + list: [ + // Inserts a space before the string + {text: ' key_substring:', displayText: 'key_substring:'}, + {text: ' key:', displayText: 'key:'}, + {text: ' tag:', displayText: 'tag:'}, + {text: ' owner:', displayText: 'owner:'}, + {text: ' group:', displayText: 'group:'}, + {text: ' kind:', displayText: 'kind:'}, + {text: ' code_location:', displayText: 'code_location:'}, + {text: ' sinks()', displayText: 'sinks()'}, + {text: ' roots()', displayText: 'roots()'}, + {text: ' not ', displayText: 'not'}, + {text: ' *', displayText: '*'}, + {text: ' +', displayText: '+'}, + {text: ' ()', displayText: '('}, + ], + from: 61, // cursor location + to: 61, // cursor location + }); + }); + + it('should handle IncompleteAttributeExpression inside OrExpression within ParenthesizedExpression', () => { + expect( + testAutocomplete( + 'sinks(key_substring:"FIVETRAN/google_ads/ad_group_history" or key_substring:|)', + ), + ).toEqual({ + list: [ + { + text: '"asset1"', + displayText: 'asset1', + }, + { + text: '"asset2"', + displayText: 'asset2', + }, + { + text: '"asset3"', + displayText: 'asset3', + }, + ], + from: 76, // cursor location + to: 76, // cursor location + }); + }); + + it('suggestions after downtraversal "+"', () => { + expect(testAutocomplete('key:"value"+|')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '+', displayText: '+'}, + ], + from: 12, // cursor location + to: 12, // cursor location + }); + + // UpAndDownTraversal + expect(testAutocomplete('*key:"value"|+')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 12, // cursor location + to: 12, // cursor location + }); + + // DownTraversal + expect(testAutocomplete('key:"value"|+')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 11, // cursor location + to: 11, // cursor location + }); + }); + + it('suggestions after IncompleteOrExpression chain', () => { + expect( + testAutocomplete('key:"test" or key_substring:"FIVETRAN/google_ads/ad_group_history"+ or |'), + ).toEqual({ + list: [ + // Inserts a space before the string + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: 'not ', displayText: 'not'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 71, // cursor position + to: 71, // cursor position + }); + }); + + it('suggestions inside parenthesized expression', () => { + expect(testAutocomplete('(|)')).toEqual({ + list: [ + // Inserts a space before the string + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: 'not ', displayText: 'not'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 1, // cursor location + to: 1, // cursor location + }); + }); + + it('suggestions outside parenthesized expression before', () => { + expect(testAutocomplete('|()')).toEqual({ + list: [ + {text: 'key_substring:', displayText: 'key_substring:'}, + {text: 'key:', displayText: 'key:'}, + {text: 'tag:', displayText: 'tag:'}, + {text: 'owner:', displayText: 'owner:'}, + {text: 'group:', displayText: 'group:'}, + {text: 'kind:', displayText: 'kind:'}, + {text: 'code_location:', displayText: 'code_location:'}, + {text: 'sinks()', displayText: 'sinks()'}, + {text: 'roots()', displayText: 'roots()'}, + {text: 'not ', displayText: 'not'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + {text: '()', displayText: '('}, + ], + from: 0, // cursor position + to: 0, // cursor position + }); + }); + + it('suggestions outside parenthesized expression after', () => { + expect(testAutocomplete('()|')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 2, // cursor position + to: 2, // cursor position + }); + }); + + it('suggestions within parenthesized expression', () => { + expect(testAutocomplete('(tag:"dagster/kind/dlt"|)')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 23, // cursor position + to: 23, // cursor position + }); + + expect(testAutocomplete('sinks(key_substring:"set" or key_substring:"asset"|)')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 50, // cursor position + to: 50, // cursor position + }); + + expect(testAutocomplete('sinks(key_substring:"asset" or key_substring:"s|et2")')).toEqual({ + list: [{text: '"asset2"', displayText: 'asset2'}], + from: 45, // start of value + to: 51, // end of value + }); + + expect(testAutocomplete('sinks(key_substring:"sset1"| or key_substring:"set")')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '*', displayText: '*'}, + {text: '+', displayText: '+'}, + ], + from: 27, // cursor position + to: 27, // cursor position + }); + }); + + it('makes suggestions around traversals', () => { + expect(testAutocomplete('sinks()++|')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '+', displayText: '+'}, + ], + from: 9, // start of value + to: 9, // end of value + }); + + expect(testAutocomplete('sinks()+|+')).toEqual({ + list: [ + {text: ' and ', displayText: 'and'}, + {text: ' or ', displayText: 'or'}, + {text: '+', displayText: '+'}, + ], + from: 8, // start of value + to: 8, // end of value + }); + + expect(testAutocomplete('|++sinks()++')).toEqual({ + list: [ + {text: '+', displayText: '+'}, + {text: '(', displayText: '('}, + ], + from: 0, // start of value + to: 0, // end of value + }); + + expect(testAutocomplete('+|+sinks()++')).toEqual({ + list: [ + {text: '+', displayText: '+'}, + {text: '(', displayText: '('}, + ], + from: 1, // start of value + to: 1, // end of value + }); + }); + + it('makes suggestions for IncompleteExpression inside of the ParenthesizedExpression', () => { + expect(testAutocomplete('(key:tag and |)')).toEqual({ + list: [ + {displayText: 'key_substring:', text: 'key_substring:'}, + {displayText: 'key:', text: 'key:'}, + {displayText: 'tag:', text: 'tag:'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'group:', text: 'group:'}, + {displayText: 'kind:', text: 'kind:'}, + {displayText: 'code_location:', text: 'code_location:'}, + {displayText: 'sinks()', text: 'sinks()'}, + {displayText: 'roots()', text: 'roots()'}, + {displayText: 'not', text: 'not '}, + {displayText: '*', text: '*'}, + {displayText: '+', text: '+'}, + {displayText: '(', text: '()'}, + ], + from: 13, + to: 13, + }); + + expect(testAutocomplete('(key:tag and|)')).toEqual({ + list: [ + {displayText: 'key_substring:', text: ' key_substring:'}, + {displayText: 'key:', text: ' key:'}, + {displayText: 'tag:', text: ' tag:'}, + {displayText: 'owner:', text: ' owner:'}, + {displayText: 'group:', text: ' group:'}, + {displayText: 'kind:', text: ' kind:'}, + {displayText: 'code_location:', text: ' code_location:'}, + {displayText: 'sinks()', text: ' sinks()'}, + {displayText: 'roots()', text: ' roots()'}, + {displayText: 'not', text: ' not '}, + {displayText: '*', text: ' *'}, + {displayText: '+', text: ' +'}, + {displayText: '(', text: ' ()'}, + ], + from: 12, + to: 12, + }); + + expect(testAutocomplete('(key:tag and| )')).toEqual({ + list: [ + {displayText: 'key_substring:', text: ' key_substring:'}, + {displayText: 'key:', text: ' key:'}, + {displayText: 'tag:', text: ' tag:'}, + {displayText: 'owner:', text: ' owner:'}, + {displayText: 'group:', text: ' group:'}, + {displayText: 'kind:', text: ' kind:'}, + {displayText: 'code_location:', text: ' code_location:'}, + {displayText: 'sinks()', text: ' sinks()'}, + {displayText: 'roots()', text: ' roots()'}, + {displayText: 'not', text: ' not '}, + {displayText: '*', text: ' *'}, + {displayText: '+', text: ' +'}, + {displayText: '(', text: ' ()'}, + ], + from: 12, + to: 12, + }); + }); + + it('suggestions within incomplete function call expression', () => { + expect( + testAutocomplete('(sinks(key:"value"++ or (key_substring:"aws_cost_report"++)|'), + ).toEqual({ + from: 59, + list: [ + {displayText: 'and', text: ' and '}, + {displayText: 'or', text: ' or '}, + {displayText: '*', text: '*'}, + {displayText: '+', text: '+'}, + {displayText: ')', text: ')'}, + ], + to: 59, + }); + }); + + it('makes suggestion in whitespace after or token in between two incomplete or expressions', () => { + expect( + testAutocomplete('key_substring:"aws_cost_report" or |or key_substring:"aws_cost_report"'), + ).toEqual({ + from: 35, + list: [ + {displayText: 'key_substring:', text: 'key_substring:'}, + {displayText: 'key:', text: 'key:'}, + {displayText: 'tag:', text: 'tag:'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'group:', text: 'group:'}, + {displayText: 'kind:', text: 'kind:'}, + {displayText: 'code_location:', text: 'code_location:'}, + {displayText: 'sinks()', text: 'sinks()'}, + {displayText: 'roots()', text: 'roots()'}, + {displayText: 'not', text: 'not '}, + {displayText: '*', text: '*'}, + {displayText: '+', text: '+'}, + {displayText: '(', text: '()'}, + ], + to: 35, + }); + }); + + it('suggests and/or logical operators', () => { + expect( + testAutocomplete('key_substring:"aws_cost_report" o|r and key_substring:"aws_cost_report"'), + ).toEqual({ + from: 32, + list: [ + { + displayText: 'or', + text: 'or', + }, + { + displayText: 'and', + text: 'and', + }, + ], + to: 34, + }); + + expect( + testAutocomplete('key_substring:"aws_cost_report" a|nd and key_substring:"aws_cost_report"'), + ).toEqual({ + from: 32, + list: [ + { + displayText: 'and', + text: 'and', + }, + { + displayText: 'or', + text: 'or', + }, + ], + to: 35, + }); + }); +}); diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp new file mode 100644 index 0000000000000..1e107956d815c --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp @@ -0,0 +1,60 @@ +token literal names: +null +'and' +'or' +'not' +'*' +'+' +':' +'(' +')' +'=' +null +null +null +null +null + +token symbolic names: +null +AND +OR +NOT +STAR +PLUS +COLON +LPAREN +RPAREN +EQUAL +QUOTED_STRING +INCOMPLETE_LEFT_QUOTED_STRING +INCOMPLETE_RIGHT_QUOTED_STRING +IDENTIFIER +WS + +rule names: +start +expr +traversalAllowedExpr +parenthesizedExpr +incompleteExpressionsWrapper +expressionLessParenthesizedExpr +upTraversalExp +downTraversalExp +traversal +attributeName +attributeValue +functionName +orToken +andToken +notToken +colonToken +leftParenToken +rightParenToken +afterExpressionWhitespace +afterLogicalOperatorWhitespace +value + + +atn: +[3, 51485, 51898, 1421, 44986, 20307, 1543, 60043, 49729, 3, 16, 208, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4, 18, 9, 18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 3, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 3, 78, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 109, 10, 3, 12, 3, 14, 3, 112, 11, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 123, 10, 4, 3, 5, 3, 5, 3, 5, 3, 5, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 6, 6, 148, 10, 6, 13, 6, 14, 6, 149, 3, 6, 3, 6, 3, 6, 5, 6, 155, 10, 6, 3, 7, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 10, 3, 10, 6, 10, 166, 10, 10, 13, 10, 14, 10, 167, 5, 10, 170, 10, 10, 3, 11, 3, 11, 3, 12, 3, 12, 3, 13, 3, 13, 3, 14, 3, 14, 3, 15, 3, 15, 3, 16, 3, 16, 3, 17, 3, 17, 3, 18, 3, 18, 3, 19, 3, 19, 3, 20, 7, 20, 191, 10, 20, 12, 20, 14, 20, 194, 11, 20, 3, 21, 7, 21, 197, 10, 21, 12, 21, 14, 21, 200, 11, 21, 3, 22, 3, 22, 3, 22, 3, 22, 5, 22, 206, 10, 22, 3, 22, 2, 2, 3, 4, 23, 2, 2, 4, 2, 6, 2, 8, 2, 10, 2, 12, 2, 14, 2, 16, 2, 18, 2, 20, 2, 22, 2, 24, 2, 26, 2, 28, 2, 30, 2, 32, 2, 34, 2, 36, 2, 38, 2, 40, 2, 42, 2, 2, 2, 2, 217, 2, 44, 3, 2, 2, 2, 4, 77, 3, 2, 2, 2, 6, 122, 3, 2, 2, 2, 8, 124, 3, 2, 2, 2, 10, 154, 3, 2, 2, 2, 12, 156, 3, 2, 2, 2, 14, 159, 3, 2, 2, 2, 16, 161, 3, 2, 2, 2, 18, 169, 3, 2, 2, 2, 20, 171, 3, 2, 2, 2, 22, 173, 3, 2, 2, 2, 24, 175, 3, 2, 2, 2, 26, 177, 3, 2, 2, 2, 28, 179, 3, 2, 2, 2, 30, 181, 3, 2, 2, 2, 32, 183, 3, 2, 2, 2, 34, 185, 3, 2, 2, 2, 36, 187, 3, 2, 2, 2, 38, 192, 3, 2, 2, 2, 40, 198, 3, 2, 2, 2, 42, 205, 3, 2, 2, 2, 44, 45, 5, 4, 3, 2, 45, 46, 7, 2, 2, 3, 46, 3, 3, 2, 2, 2, 47, 48, 8, 3, 1, 2, 48, 49, 5, 6, 4, 2, 49, 50, 5, 38, 20, 2, 50, 78, 3, 2, 2, 2, 51, 52, 5, 14, 8, 2, 52, 53, 5, 6, 4, 2, 53, 54, 5, 16, 9, 2, 54, 55, 5, 38, 20, 2, 55, 78, 3, 2, 2, 2, 56, 57, 5, 14, 8, 2, 57, 58, 5, 6, 4, 2, 58, 59, 5, 38, 20, 2, 59, 78, 3, 2, 2, 2, 60, 61, 5, 6, 4, 2, 61, 62, 5, 16, 9, 2, 62, 63, 5, 38, 20, 2, 63, 78, 3, 2, 2, 2, 64, 65, 5, 30, 16, 2, 65, 66, 5, 40, 21, 2, 66, 67, 5, 4, 3, 2, 67, 68, 5, 38, 20, 2, 68, 78, 3, 2, 2, 2, 69, 70, 5, 30, 16, 2, 70, 71, 5, 40, 21, 2, 71, 78, 3, 2, 2, 2, 72, 73, 7, 6, 2, 2, 73, 78, 5, 38, 20, 2, 74, 75, 5, 42, 22, 2, 75, 76, 5, 38, 20, 2, 76, 78, 3, 2, 2, 2, 77, 47, 3, 2, 2, 2, 77, 51, 3, 2, 2, 2, 77, 56, 3, 2, 2, 2, 77, 60, 3, 2, 2, 2, 77, 64, 3, 2, 2, 2, 77, 69, 3, 2, 2, 2, 77, 72, 3, 2, 2, 2, 77, 74, 3, 2, 2, 2, 78, 110, 3, 2, 2, 2, 79, 80, 12, 10, 2, 2, 80, 81, 5, 38, 20, 2, 81, 82, 5, 28, 15, 2, 82, 83, 5, 40, 21, 2, 83, 84, 5, 4, 3, 2, 84, 85, 5, 38, 20, 2, 85, 109, 3, 2, 2, 2, 86, 87, 12, 9, 2, 2, 87, 88, 5, 38, 20, 2, 88, 89, 5, 26, 14, 2, 89, 90, 5, 40, 21, 2, 90, 91, 5, 4, 3, 2, 91, 92, 5, 38, 20, 2, 92, 109, 3, 2, 2, 2, 93, 94, 12, 8, 2, 2, 94, 95, 5, 38, 20, 2, 95, 96, 5, 28, 15, 2, 96, 97, 5, 40, 21, 2, 97, 109, 3, 2, 2, 2, 98, 99, 12, 7, 2, 2, 99, 100, 5, 38, 20, 2, 100, 101, 5, 26, 14, 2, 101, 102, 5, 40, 21, 2, 102, 109, 3, 2, 2, 2, 103, 104, 12, 5, 2, 2, 104, 105, 5, 38, 20, 2, 105, 106, 5, 42, 22, 2, 106, 107, 5, 40, 21, 2, 107, 109, 3, 2, 2, 2, 108, 79, 3, 2, 2, 2, 108, 86, 3, 2, 2, 2, 108, 93, 3, 2, 2, 2, 108, 98, 3, 2, 2, 2, 108, 103, 3, 2, 2, 2, 109, 112, 3, 2, 2, 2, 110, 108, 3, 2, 2, 2, 110, 111, 3, 2, 2, 2, 111, 5, 3, 2, 2, 2, 112, 110, 3, 2, 2, 2, 113, 114, 5, 20, 11, 2, 114, 115, 5, 32, 17, 2, 115, 116, 5, 22, 12, 2, 116, 123, 3, 2, 2, 2, 117, 118, 5, 24, 13, 2, 118, 119, 5, 8, 5, 2, 119, 123, 3, 2, 2, 2, 120, 123, 5, 8, 5, 2, 121, 123, 5, 10, 6, 2, 122, 113, 3, 2, 2, 2, 122, 117, 3, 2, 2, 2, 122, 120, 3, 2, 2, 2, 122, 121, 3, 2, 2, 2, 123, 7, 3, 2, 2, 2, 124, 125, 5, 34, 18, 2, 125, 126, 5, 4, 3, 2, 126, 127, 5, 36, 19, 2, 127, 9, 3, 2, 2, 2, 128, 129, 5, 20, 11, 2, 129, 130, 5, 32, 17, 2, 130, 155, 3, 2, 2, 2, 131, 132, 5, 24, 13, 2, 132, 133, 5, 12, 7, 2, 133, 155, 3, 2, 2, 2, 134, 135, 5, 24, 13, 2, 135, 136, 5, 34, 18, 2, 136, 155, 3, 2, 2, 2, 137, 138, 5, 24, 13, 2, 138, 139, 5, 34, 18, 2, 139, 140, 5, 4, 3, 2, 140, 155, 3, 2, 2, 2, 141, 142, 5, 34, 18, 2, 142, 143, 5, 4, 3, 2, 143, 155, 3, 2, 2, 2, 144, 155, 5, 12, 7, 2, 145, 155, 5, 34, 18, 2, 146, 148, 7, 7, 2, 2, 147, 146, 3, 2, 2, 2, 148, 149, 3, 2, 2, 2, 149, 147, 3, 2, 2, 2, 149, 150, 3, 2, 2, 2, 150, 155, 3, 2, 2, 2, 151, 152, 5, 32, 17, 2, 152, 153, 5, 22, 12, 2, 153, 155, 3, 2, 2, 2, 154, 128, 3, 2, 2, 2, 154, 131, 3, 2, 2, 2, 154, 134, 3, 2, 2, 2, 154, 137, 3, 2, 2, 2, 154, 141, 3, 2, 2, 2, 154, 144, 3, 2, 2, 2, 154, 145, 3, 2, 2, 2, 154, 147, 3, 2, 2, 2, 154, 151, 3, 2, 2, 2, 155, 11, 3, 2, 2, 2, 156, 157, 5, 34, 18, 2, 157, 158, 5, 36, 19, 2, 158, 13, 3, 2, 2, 2, 159, 160, 5, 18, 10, 2, 160, 15, 3, 2, 2, 2, 161, 162, 5, 18, 10, 2, 162, 17, 3, 2, 2, 2, 163, 170, 7, 6, 2, 2, 164, 166, 7, 7, 2, 2, 165, 164, 3, 2, 2, 2, 166, 167, 3, 2, 2, 2, 167, 165, 3, 2, 2, 2, 167, 168, 3, 2, 2, 2, 168, 170, 3, 2, 2, 2, 169, 163, 3, 2, 2, 2, 169, 165, 3, 2, 2, 2, 170, 19, 3, 2, 2, 2, 171, 172, 7, 15, 2, 2, 172, 21, 3, 2, 2, 2, 173, 174, 5, 42, 22, 2, 174, 23, 3, 2, 2, 2, 175, 176, 7, 15, 2, 2, 176, 25, 3, 2, 2, 2, 177, 178, 7, 4, 2, 2, 178, 27, 3, 2, 2, 2, 179, 180, 7, 3, 2, 2, 180, 29, 3, 2, 2, 2, 181, 182, 7, 5, 2, 2, 182, 31, 3, 2, 2, 2, 183, 184, 7, 8, 2, 2, 184, 33, 3, 2, 2, 2, 185, 186, 7, 9, 2, 2, 186, 35, 3, 2, 2, 2, 187, 188, 7, 10, 2, 2, 188, 37, 3, 2, 2, 2, 189, 191, 7, 16, 2, 2, 190, 189, 3, 2, 2, 2, 191, 194, 3, 2, 2, 2, 192, 190, 3, 2, 2, 2, 192, 193, 3, 2, 2, 2, 193, 39, 3, 2, 2, 2, 194, 192, 3, 2, 2, 2, 195, 197, 7, 16, 2, 2, 196, 195, 3, 2, 2, 2, 197, 200, 3, 2, 2, 2, 198, 196, 3, 2, 2, 2, 198, 199, 3, 2, 2, 2, 199, 41, 3, 2, 2, 2, 200, 198, 3, 2, 2, 2, 201, 206, 7, 12, 2, 2, 202, 206, 7, 13, 2, 2, 203, 206, 7, 14, 2, 2, 204, 206, 7, 15, 2, 2, 205, 201, 3, 2, 2, 2, 205, 202, 3, 2, 2, 2, 205, 203, 3, 2, 2, 2, 205, 204, 3, 2, 2, 2, 206, 43, 3, 2, 2, 2, 13, 77, 108, 110, 122, 149, 154, 167, 169, 192, 198, 205] \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.tokens b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.tokens new file mode 100644 index 0000000000000..f995c7bb6ea28 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.tokens @@ -0,0 +1,23 @@ +AND=1 +OR=2 +NOT=3 +STAR=4 +PLUS=5 +COLON=6 +LPAREN=7 +RPAREN=8 +EQUAL=9 +QUOTED_STRING=10 +INCOMPLETE_LEFT_QUOTED_STRING=11 +INCOMPLETE_RIGHT_QUOTED_STRING=12 +IDENTIFIER=13 +WS=14 +'and'=1 +'or'=2 +'not'=3 +'*'=4 +'+'=5 +':'=6 +'('=7 +')'=8 +'='=9 diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.interp b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.interp new file mode 100644 index 0000000000000..bbfc87f6345d0 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.interp @@ -0,0 +1,59 @@ +token literal names: +null +'and' +'or' +'not' +'*' +'+' +':' +'(' +')' +'=' +null +null +null +null +null + +token symbolic names: +null +AND +OR +NOT +STAR +PLUS +COLON +LPAREN +RPAREN +EQUAL +QUOTED_STRING +INCOMPLETE_LEFT_QUOTED_STRING +INCOMPLETE_RIGHT_QUOTED_STRING +IDENTIFIER +WS + +rule names: +AND +OR +NOT +STAR +PLUS +COLON +LPAREN +RPAREN +EQUAL +QUOTED_STRING +INCOMPLETE_LEFT_QUOTED_STRING +INCOMPLETE_RIGHT_QUOTED_STRING +IDENTIFIER +WS + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[3, 51485, 51898, 1421, 44986, 20307, 1543, 60043, 49729, 2, 16, 90, 8, 1, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 3, 2, 3, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 5, 3, 5, 3, 6, 3, 6, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 10, 3, 10, 3, 11, 3, 11, 7, 11, 57, 10, 11, 12, 11, 14, 11, 60, 11, 11, 3, 11, 3, 11, 3, 12, 3, 12, 7, 12, 66, 10, 12, 12, 12, 14, 12, 69, 11, 12, 3, 13, 7, 13, 72, 10, 13, 12, 13, 14, 13, 75, 11, 13, 3, 13, 3, 13, 3, 14, 3, 14, 7, 14, 81, 10, 14, 12, 14, 14, 14, 84, 11, 14, 3, 15, 6, 15, 87, 10, 15, 13, 15, 14, 15, 88, 2, 2, 2, 16, 3, 2, 3, 5, 2, 4, 7, 2, 5, 9, 2, 6, 11, 2, 7, 13, 2, 8, 15, 2, 9, 17, 2, 10, 19, 2, 11, 21, 2, 12, 23, 2, 13, 25, 2, 14, 27, 2, 15, 29, 2, 16, 3, 2, 7, 6, 2, 12, 12, 15, 15, 36, 36, 94, 94, 8, 2, 12, 12, 15, 15, 36, 36, 42, 43, 60, 60, 94, 94, 5, 2, 67, 92, 97, 97, 99, 124, 6, 2, 50, 59, 67, 92, 97, 97, 99, 124, 5, 2, 11, 12, 15, 15, 34, 34, 2, 94, 2, 3, 3, 2, 2, 2, 2, 5, 3, 2, 2, 2, 2, 7, 3, 2, 2, 2, 2, 9, 3, 2, 2, 2, 2, 11, 3, 2, 2, 2, 2, 13, 3, 2, 2, 2, 2, 15, 3, 2, 2, 2, 2, 17, 3, 2, 2, 2, 2, 19, 3, 2, 2, 2, 2, 21, 3, 2, 2, 2, 2, 23, 3, 2, 2, 2, 2, 25, 3, 2, 2, 2, 2, 27, 3, 2, 2, 2, 2, 29, 3, 2, 2, 2, 3, 31, 3, 2, 2, 2, 5, 35, 3, 2, 2, 2, 7, 38, 3, 2, 2, 2, 9, 42, 3, 2, 2, 2, 11, 44, 3, 2, 2, 2, 13, 46, 3, 2, 2, 2, 15, 48, 3, 2, 2, 2, 17, 50, 3, 2, 2, 2, 19, 52, 3, 2, 2, 2, 21, 54, 3, 2, 2, 2, 23, 63, 3, 2, 2, 2, 25, 73, 3, 2, 2, 2, 27, 78, 3, 2, 2, 2, 29, 86, 3, 2, 2, 2, 31, 32, 7, 99, 2, 2, 32, 33, 7, 112, 2, 2, 33, 34, 7, 102, 2, 2, 34, 4, 3, 2, 2, 2, 35, 36, 7, 113, 2, 2, 36, 37, 7, 116, 2, 2, 37, 6, 3, 2, 2, 2, 38, 39, 7, 112, 2, 2, 39, 40, 7, 113, 2, 2, 40, 41, 7, 118, 2, 2, 41, 8, 3, 2, 2, 2, 42, 43, 7, 44, 2, 2, 43, 10, 3, 2, 2, 2, 44, 45, 7, 45, 2, 2, 45, 12, 3, 2, 2, 2, 46, 47, 7, 60, 2, 2, 47, 14, 3, 2, 2, 2, 48, 49, 7, 42, 2, 2, 49, 16, 3, 2, 2, 2, 50, 51, 7, 43, 2, 2, 51, 18, 3, 2, 2, 2, 52, 53, 7, 63, 2, 2, 53, 20, 3, 2, 2, 2, 54, 58, 7, 36, 2, 2, 55, 57, 10, 2, 2, 2, 56, 55, 3, 2, 2, 2, 57, 60, 3, 2, 2, 2, 58, 56, 3, 2, 2, 2, 58, 59, 3, 2, 2, 2, 59, 61, 3, 2, 2, 2, 60, 58, 3, 2, 2, 2, 61, 62, 7, 36, 2, 2, 62, 22, 3, 2, 2, 2, 63, 67, 7, 36, 2, 2, 64, 66, 10, 3, 2, 2, 65, 64, 3, 2, 2, 2, 66, 69, 3, 2, 2, 2, 67, 65, 3, 2, 2, 2, 67, 68, 3, 2, 2, 2, 68, 24, 3, 2, 2, 2, 69, 67, 3, 2, 2, 2, 70, 72, 10, 3, 2, 2, 71, 70, 3, 2, 2, 2, 72, 75, 3, 2, 2, 2, 73, 71, 3, 2, 2, 2, 73, 74, 3, 2, 2, 2, 74, 76, 3, 2, 2, 2, 75, 73, 3, 2, 2, 2, 76, 77, 7, 36, 2, 2, 77, 26, 3, 2, 2, 2, 78, 82, 9, 4, 2, 2, 79, 81, 9, 5, 2, 2, 80, 79, 3, 2, 2, 2, 81, 84, 3, 2, 2, 2, 82, 80, 3, 2, 2, 2, 82, 83, 3, 2, 2, 2, 83, 28, 3, 2, 2, 2, 84, 82, 3, 2, 2, 2, 85, 87, 9, 6, 2, 2, 86, 85, 3, 2, 2, 2, 87, 88, 3, 2, 2, 2, 88, 86, 3, 2, 2, 2, 88, 89, 3, 2, 2, 2, 89, 30, 3, 2, 2, 2, 8, 2, 58, 67, 73, 82, 88, 2] \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.tokens b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.tokens new file mode 100644 index 0000000000000..f995c7bb6ea28 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.tokens @@ -0,0 +1,23 @@ +AND=1 +OR=2 +NOT=3 +STAR=4 +PLUS=5 +COLON=6 +LPAREN=7 +RPAREN=8 +EQUAL=9 +QUOTED_STRING=10 +INCOMPLETE_LEFT_QUOTED_STRING=11 +INCOMPLETE_RIGHT_QUOTED_STRING=12 +IDENTIFIER=13 +WS=14 +'and'=1 +'or'=2 +'not'=3 +'*'=4 +'+'=5 +':'=6 +'('=7 +')'=8 +'='=9 diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.ts new file mode 100644 index 0000000000000..4d8a9a5165066 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteLexer.ts @@ -0,0 +1,172 @@ +// Generated from /Users/marcosalazar/code/dagster/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 by ANTLR 4.9.0-SNAPSHOT + +import {CharStream} from 'antlr4ts/CharStream'; +import {Lexer} from 'antlr4ts/Lexer'; +import {Vocabulary} from 'antlr4ts/Vocabulary'; +import {VocabularyImpl} from 'antlr4ts/VocabularyImpl'; +import {ATN} from 'antlr4ts/atn/ATN'; +import {ATNDeserializer} from 'antlr4ts/atn/ATNDeserializer'; +import {LexerATNSimulator} from 'antlr4ts/atn/LexerATNSimulator'; +import * as Utils from 'antlr4ts/misc/Utils'; + +export class SelectionAutoCompleteLexer extends Lexer { + public static readonly AND = 1; + public static readonly OR = 2; + public static readonly NOT = 3; + public static readonly STAR = 4; + public static readonly PLUS = 5; + public static readonly COLON = 6; + public static readonly LPAREN = 7; + public static readonly RPAREN = 8; + public static readonly EQUAL = 9; + public static readonly QUOTED_STRING = 10; + public static readonly INCOMPLETE_LEFT_QUOTED_STRING = 11; + public static readonly INCOMPLETE_RIGHT_QUOTED_STRING = 12; + public static readonly IDENTIFIER = 13; + public static readonly WS = 14; + + // tslint:disable:no-trailing-whitespace + public static readonly channelNames: string[] = ['DEFAULT_TOKEN_CHANNEL', 'HIDDEN']; + + // tslint:disable:no-trailing-whitespace + public static readonly modeNames: string[] = ['DEFAULT_MODE']; + + public static readonly ruleNames: string[] = [ + 'AND', + 'OR', + 'NOT', + 'STAR', + 'PLUS', + 'COLON', + 'LPAREN', + 'RPAREN', + 'EQUAL', + 'QUOTED_STRING', + 'INCOMPLETE_LEFT_QUOTED_STRING', + 'INCOMPLETE_RIGHT_QUOTED_STRING', + 'IDENTIFIER', + 'WS', + ]; + + private static readonly _LITERAL_NAMES: Array = [ + undefined, + "'and'", + "'or'", + "'not'", + "'*'", + "'+'", + "':'", + "'('", + "')'", + "'='", + ]; + private static readonly _SYMBOLIC_NAMES: Array = [ + undefined, + 'AND', + 'OR', + 'NOT', + 'STAR', + 'PLUS', + 'COLON', + 'LPAREN', + 'RPAREN', + 'EQUAL', + 'QUOTED_STRING', + 'INCOMPLETE_LEFT_QUOTED_STRING', + 'INCOMPLETE_RIGHT_QUOTED_STRING', + 'IDENTIFIER', + 'WS', + ]; + public static readonly VOCABULARY: Vocabulary = new VocabularyImpl( + SelectionAutoCompleteLexer._LITERAL_NAMES, + SelectionAutoCompleteLexer._SYMBOLIC_NAMES, + [], + ); + + // @Override + // @NotNull + public get vocabulary(): Vocabulary { + return SelectionAutoCompleteLexer.VOCABULARY; + } + // tslint:enable:no-trailing-whitespace + + constructor(input: CharStream) { + super(input); + this._interp = new LexerATNSimulator(SelectionAutoCompleteLexer._ATN, this); + } + + // @Override + public get grammarFileName(): string { + return 'SelectionAutoComplete.g4'; + } + + // @Override + public get ruleNames(): string[] { + return SelectionAutoCompleteLexer.ruleNames; + } + + // @Override + public get serializedATN(): string { + return SelectionAutoCompleteLexer._serializedATN; + } + + // @Override + public get channelNames(): string[] { + return SelectionAutoCompleteLexer.channelNames; + } + + // @Override + public get modeNames(): string[] { + return SelectionAutoCompleteLexer.modeNames; + } + + public static readonly _serializedATN: string = + '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02\x10Z\b\x01\x04' + + '\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04' + + '\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r' + + '\x04\x0E\t\x0E\x04\x0F\t\x0F\x03\x02\x03\x02\x03\x02\x03\x02\x03\x03\x03' + + '\x03\x03\x03\x03\x04\x03\x04\x03\x04\x03\x04\x03\x05\x03\x05\x03\x06\x03' + + '\x06\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03\t\x03\n\x03\n\x03\v\x03\v\x07' + + '\v9\n\v\f\v\x0E\v<\v\v\x03\v\x03\v\x03\f\x03\f\x07\fB\n\f\f\f\x0E\fE\v' + + '\f\x03\r\x07\rH\n\r\f\r\x0E\rK\v\r\x03\r\x03\r\x03\x0E\x03\x0E\x07\x0E' + + 'Q\n\x0E\f\x0E\x0E\x0ET\v\x0E\x03\x0F\x06\x0FW\n\x0F\r\x0F\x0E\x0FX\x02' + + '\x02\x02\x10\x03\x02\x03\x05\x02\x04\x07\x02\x05\t\x02\x06\v\x02\x07\r' + + '\x02\b\x0F\x02\t\x11\x02\n\x13\x02\v\x15\x02\f\x17\x02\r\x19\x02\x0E\x1B' + + '\x02\x0F\x1D\x02\x10\x03\x02\x07\x06\x02\f\f\x0F\x0F$$^^\b\x02\f\f\x0F' + + '\x0F$$*+<<^^\x05\x02C\\aac|\x06\x022;C\\aac|\x05\x02\v\f\x0F\x0F""\x02' + + '^\x02\x03\x03\x02\x02\x02\x02\x05\x03\x02\x02\x02\x02\x07\x03\x02\x02' + + '\x02\x02\t\x03\x02\x02\x02\x02\v\x03\x02\x02\x02\x02\r\x03\x02\x02\x02' + + '\x02\x0F\x03\x02\x02\x02\x02\x11\x03\x02\x02\x02\x02\x13\x03\x02\x02\x02' + + '\x02\x15\x03\x02\x02\x02\x02\x17\x03\x02\x02\x02\x02\x19\x03\x02\x02\x02' + + '\x02\x1B\x03\x02\x02\x02\x02\x1D\x03\x02\x02\x02\x03\x1F\x03\x02\x02\x02' + + '\x05#\x03\x02\x02\x02\x07&\x03\x02\x02\x02\t*\x03\x02\x02\x02\v,\x03\x02' + + '\x02\x02\r.\x03\x02\x02\x02\x0F0\x03\x02\x02\x02\x112\x03\x02\x02\x02' + + '\x134\x03\x02\x02\x02\x156\x03\x02\x02\x02\x17?\x03\x02\x02\x02\x19I\x03' + + '\x02\x02\x02\x1BN\x03\x02\x02\x02\x1DV\x03\x02\x02\x02\x1F \x07c\x02\x02' + + ' !\x07p\x02\x02!"\x07f\x02\x02"\x04\x03\x02\x02\x02#$\x07q\x02\x02$' + + "%\x07t\x02\x02%\x06\x03\x02\x02\x02&'\x07p\x02\x02'(\x07q\x02\x02()" + + '\x07v\x02\x02)\b\x03\x02\x02\x02*+\x07,\x02\x02+\n\x03\x02\x02\x02,-\x07' + + '-\x02\x02-\f\x03\x02\x02\x02./\x07<\x02\x02/\x0E\x03\x02\x02\x0201\x07' + + '*\x02\x021\x10\x03\x02\x02\x0223\x07+\x02\x023\x12\x03\x02\x02\x0245\x07' + + '?\x02\x025\x14\x03\x02\x02\x026:\x07$\x02\x0279\n\x02\x02\x0287\x03\x02' + + '\x02\x029<\x03\x02\x02\x02:8\x03\x02\x02\x02:;\x03\x02\x02\x02;=\x03\x02' + + '\x02\x02<:\x03\x02\x02\x02=>\x07$\x02\x02>\x16\x03\x02\x02\x02?C\x07$' + + '\x02\x02@B\n\x03\x02\x02A@\x03\x02\x02\x02BE\x03\x02\x02\x02CA\x03\x02' + + '\x02\x02CD\x03\x02\x02\x02D\x18\x03\x02\x02\x02EC\x03\x02\x02\x02FH\n' + + '\x03\x02\x02GF\x03\x02\x02\x02HK\x03\x02\x02\x02IG\x03\x02\x02\x02IJ\x03' + + '\x02\x02\x02JL\x03\x02\x02\x02KI\x03\x02\x02\x02LM\x07$\x02\x02M\x1A\x03' + + '\x02\x02\x02NR\t\x04\x02\x02OQ\t\x05\x02\x02PO\x03\x02\x02\x02QT\x03\x02' + + '\x02\x02RP\x03\x02\x02\x02RS\x03\x02\x02\x02S\x1C\x03\x02\x02\x02TR\x03' + + '\x02\x02\x02UW\t\x06\x02\x02VU\x03\x02\x02\x02WX\x03\x02\x02\x02XV\x03' + + '\x02\x02\x02XY\x03\x02\x02\x02Y\x1E\x03\x02\x02\x02\b\x02:CIRX\x02'; + public static __ATN: ATN; + public static get _ATN(): ATN { + if (!SelectionAutoCompleteLexer.__ATN) { + SelectionAutoCompleteLexer.__ATN = new ATNDeserializer().deserialize( + Utils.toCharArray(SelectionAutoCompleteLexer._serializedATN), + ); + } + + return SelectionAutoCompleteLexer.__ATN; + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts new file mode 100644 index 0000000000000..d47ae283cf6ac --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts @@ -0,0 +1,764 @@ +// Generated from /Users/marcosalazar/code/dagster/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 by ANTLR 4.9.0-SNAPSHOT + +import {ParseTreeListener} from 'antlr4ts/tree/ParseTreeListener'; + +import { + AfterExpressionWhitespaceContext, + AfterLogicalOperatorWhitespaceContext, + AllExpressionContext, + AndExpressionContext, + AndTokenContext, + AttributeExpressionContext, + AttributeNameContext, + AttributeValueContext, + ColonTokenContext, + DownTraversalContext, + DownTraversalExpContext, + DownTraversalExpressionContext, + ExprContext, + ExpressionLessParenthesizedExprContext, + ExpressionlessFunctionExpressionContext, + ExpressionlessParenthesizedExpressionContext, + ExpressionlessParenthesizedExpressionWrapperContext, + FunctionCallExpressionContext, + FunctionNameContext, + IncompleteAndExpressionContext, + IncompleteAttributeExpressionMissingKeyContext, + IncompleteAttributeExpressionMissingValueContext, + IncompleteExpressionContext, + IncompleteExpressionsWrapperContext, + IncompleteLeftQuotedStringValueContext, + IncompleteNotExpressionContext, + IncompleteOrExpressionContext, + IncompleteRightQuotedStringValueContext, + IncompleteTraversalExpressionContext, + LeftParenTokenContext, + NotExpressionContext, + NotTokenContext, + OrExpressionContext, + OrTokenContext, + ParenthesizedExprContext, + ParenthesizedExpressionContext, + ParenthesizedExpressionWrapperContext, + QuotedStringValueContext, + RightParenTokenContext, + StartContext, + TraversalAllowedExprContext, + TraversalAllowedExpressionContext, + TraversalContext, + UnclosedExpressionlessFunctionExpressionContext, + UnclosedExpressionlessParenthesizedExpressionContext, + UnclosedFunctionExpressionContext, + UnclosedParenthesizedExpressionContext, + UnmatchedExpressionContinuationContext, + UnmatchedValueContext, + UnquotedStringValueContext, + UpAndDownTraversalExpressionContext, + UpTraversalContext, + UpTraversalExpContext, + UpTraversalExpressionContext, + ValueContext, +} from './SelectionAutoCompleteParser'; + +/** + * This interface defines a complete listener for a parse tree produced by + * `SelectionAutoCompleteParser`. + */ +export interface SelectionAutoCompleteListener extends ParseTreeListener { + /** + * Enter a parse tree produced by the `DownTraversal` + * labeled alternative in `SelectionAutoCompleteParser.downTraversalExp`. + * @param ctx the parse tree + */ + enterDownTraversal?: (ctx: DownTraversalContext) => void; + /** + * Exit a parse tree produced by the `DownTraversal` + * labeled alternative in `SelectionAutoCompleteParser.downTraversalExp`. + * @param ctx the parse tree + */ + exitDownTraversal?: (ctx: DownTraversalContext) => void; + + /** + * Enter a parse tree produced by the `AttributeExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterAttributeExpression?: (ctx: AttributeExpressionContext) => void; + /** + * Exit a parse tree produced by the `AttributeExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitAttributeExpression?: (ctx: AttributeExpressionContext) => void; + + /** + * Enter a parse tree produced by the `FunctionCallExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => void; + /** + * Exit a parse tree produced by the `FunctionCallExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => void; + + /** + * Enter a parse tree produced by the `ParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterParenthesizedExpressionWrapper?: (ctx: ParenthesizedExpressionWrapperContext) => void; + /** + * Exit a parse tree produced by the `ParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitParenthesizedExpressionWrapper?: (ctx: ParenthesizedExpressionWrapperContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterIncompleteExpression?: (ctx: IncompleteExpressionContext) => void; + /** + * Exit a parse tree produced by the `IncompleteExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitIncompleteExpression?: (ctx: IncompleteExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UpTraversal` + * labeled alternative in `SelectionAutoCompleteParser.upTraversalExp`. + * @param ctx the parse tree + */ + enterUpTraversal?: (ctx: UpTraversalContext) => void; + /** + * Exit a parse tree produced by the `UpTraversal` + * labeled alternative in `SelectionAutoCompleteParser.upTraversalExp`. + * @param ctx the parse tree + */ + exitUpTraversal?: (ctx: UpTraversalContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteAttributeExpressionMissingValue` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterIncompleteAttributeExpressionMissingValue?: ( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) => void; + /** + * Exit a parse tree produced by the `IncompleteAttributeExpressionMissingValue` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitIncompleteAttributeExpressionMissingValue?: ( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) => void; + + /** + * Enter a parse tree produced by the `ExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => void; + /** + * Exit a parse tree produced by the `ExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UnclosedExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterUnclosedExpressionlessFunctionExpression?: ( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) => void; + /** + * Exit a parse tree produced by the `UnclosedExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitUnclosedExpressionlessFunctionExpression?: ( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) => void; + + /** + * Enter a parse tree produced by the `UnclosedFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => void; + /** + * Exit a parse tree produced by the `UnclosedFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UnclosedParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => void; + /** + * Exit a parse tree produced by the `UnclosedParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => void; + + /** + * Enter a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterExpressionlessParenthesizedExpressionWrapper?: ( + ctx: ExpressionlessParenthesizedExpressionWrapperContext, + ) => void; + /** + * Exit a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitExpressionlessParenthesizedExpressionWrapper?: ( + ctx: ExpressionlessParenthesizedExpressionWrapperContext, + ) => void; + + /** + * Enter a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterUnclosedExpressionlessParenthesizedExpression?: ( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) => void; + /** + * Exit a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitUnclosedExpressionlessParenthesizedExpression?: ( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) => void; + + /** + * Enter a parse tree produced by the `IncompleteTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterIncompleteTraversalExpression?: (ctx: IncompleteTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `IncompleteTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitIncompleteTraversalExpression?: (ctx: IncompleteTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteAttributeExpressionMissingKey` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterIncompleteAttributeExpressionMissingKey?: ( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) => void; + /** + * Exit a parse tree produced by the `IncompleteAttributeExpressionMissingKey` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitIncompleteAttributeExpressionMissingKey?: ( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) => void; + + /** + * Enter a parse tree produced by the `ParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.parenthesizedExpr`. + * @param ctx the parse tree + */ + enterParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => void; + /** + * Exit a parse tree produced by the `ParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.parenthesizedExpr`. + * @param ctx the parse tree + */ + exitParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => void; + + /** + * Enter a parse tree produced by the `TraversalAllowedExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterTraversalAllowedExpression?: (ctx: TraversalAllowedExpressionContext) => void; + /** + * Exit a parse tree produced by the `TraversalAllowedExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitTraversalAllowedExpression?: (ctx: TraversalAllowedExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UpAndDownTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterUpAndDownTraversalExpression?: (ctx: UpAndDownTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `UpAndDownTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitUpAndDownTraversalExpression?: (ctx: UpAndDownTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UpTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterUpTraversalExpression?: (ctx: UpTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `UpTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitUpTraversalExpression?: (ctx: UpTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `DownTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterDownTraversalExpression?: (ctx: DownTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `DownTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitDownTraversalExpression?: (ctx: DownTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `NotExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterNotExpression?: (ctx: NotExpressionContext) => void; + /** + * Exit a parse tree produced by the `NotExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitNotExpression?: (ctx: NotExpressionContext) => void; + + /** + * Enter a parse tree produced by the `AndExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterAndExpression?: (ctx: AndExpressionContext) => void; + /** + * Exit a parse tree produced by the `AndExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitAndExpression?: (ctx: AndExpressionContext) => void; + + /** + * Enter a parse tree produced by the `OrExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterOrExpression?: (ctx: OrExpressionContext) => void; + /** + * Exit a parse tree produced by the `OrExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitOrExpression?: (ctx: OrExpressionContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteAndExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterIncompleteAndExpression?: (ctx: IncompleteAndExpressionContext) => void; + /** + * Exit a parse tree produced by the `IncompleteAndExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitIncompleteAndExpression?: (ctx: IncompleteAndExpressionContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteOrExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterIncompleteOrExpression?: (ctx: IncompleteOrExpressionContext) => void; + /** + * Exit a parse tree produced by the `IncompleteOrExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitIncompleteOrExpression?: (ctx: IncompleteOrExpressionContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteNotExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterIncompleteNotExpression?: (ctx: IncompleteNotExpressionContext) => void; + /** + * Exit a parse tree produced by the `IncompleteNotExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitIncompleteNotExpression?: (ctx: IncompleteNotExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UnmatchedExpressionContinuation` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterUnmatchedExpressionContinuation?: (ctx: UnmatchedExpressionContinuationContext) => void; + /** + * Exit a parse tree produced by the `UnmatchedExpressionContinuation` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitUnmatchedExpressionContinuation?: (ctx: UnmatchedExpressionContinuationContext) => void; + + /** + * Enter a parse tree produced by the `AllExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterAllExpression?: (ctx: AllExpressionContext) => void; + /** + * Exit a parse tree produced by the `AllExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitAllExpression?: (ctx: AllExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UnmatchedValue` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterUnmatchedValue?: (ctx: UnmatchedValueContext) => void; + /** + * Exit a parse tree produced by the `UnmatchedValue` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitUnmatchedValue?: (ctx: UnmatchedValueContext) => void; + + /** + * Enter a parse tree produced by the `ExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. + * @param ctx the parse tree + */ + enterExpressionlessParenthesizedExpression?: ( + ctx: ExpressionlessParenthesizedExpressionContext, + ) => void; + /** + * Exit a parse tree produced by the `ExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. + * @param ctx the parse tree + */ + exitExpressionlessParenthesizedExpression?: ( + ctx: ExpressionlessParenthesizedExpressionContext, + ) => void; + + /** + * Enter a parse tree produced by the `QuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + enterQuotedStringValue?: (ctx: QuotedStringValueContext) => void; + /** + * Exit a parse tree produced by the `QuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + exitQuotedStringValue?: (ctx: QuotedStringValueContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteLeftQuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + enterIncompleteLeftQuotedStringValue?: (ctx: IncompleteLeftQuotedStringValueContext) => void; + /** + * Exit a parse tree produced by the `IncompleteLeftQuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + exitIncompleteLeftQuotedStringValue?: (ctx: IncompleteLeftQuotedStringValueContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteRightQuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + enterIncompleteRightQuotedStringValue?: (ctx: IncompleteRightQuotedStringValueContext) => void; + /** + * Exit a parse tree produced by the `IncompleteRightQuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + exitIncompleteRightQuotedStringValue?: (ctx: IncompleteRightQuotedStringValueContext) => void; + + /** + * Enter a parse tree produced by the `UnquotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + enterUnquotedStringValue?: (ctx: UnquotedStringValueContext) => void; + /** + * Exit a parse tree produced by the `UnquotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + exitUnquotedStringValue?: (ctx: UnquotedStringValueContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.start`. + * @param ctx the parse tree + */ + enterStart?: (ctx: StartContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.start`. + * @param ctx the parse tree + */ + exitStart?: (ctx: StartContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + enterExpr?: (ctx: ExprContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + */ + exitExpr?: (ctx: ExprContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterTraversalAllowedExpr?: (ctx: TraversalAllowedExprContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitTraversalAllowedExpr?: (ctx: TraversalAllowedExprContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.parenthesizedExpr`. + * @param ctx the parse tree + */ + enterParenthesizedExpr?: (ctx: ParenthesizedExprContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.parenthesizedExpr`. + * @param ctx the parse tree + */ + exitParenthesizedExpr?: (ctx: ParenthesizedExprContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + enterIncompleteExpressionsWrapper?: (ctx: IncompleteExpressionsWrapperContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + */ + exitIncompleteExpressionsWrapper?: (ctx: IncompleteExpressionsWrapperContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. + * @param ctx the parse tree + */ + enterExpressionLessParenthesizedExpr?: (ctx: ExpressionLessParenthesizedExprContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. + * @param ctx the parse tree + */ + exitExpressionLessParenthesizedExpr?: (ctx: ExpressionLessParenthesizedExprContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.upTraversalExp`. + * @param ctx the parse tree + */ + enterUpTraversalExp?: (ctx: UpTraversalExpContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.upTraversalExp`. + * @param ctx the parse tree + */ + exitUpTraversalExp?: (ctx: UpTraversalExpContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.downTraversalExp`. + * @param ctx the parse tree + */ + enterDownTraversalExp?: (ctx: DownTraversalExpContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.downTraversalExp`. + * @param ctx the parse tree + */ + exitDownTraversalExp?: (ctx: DownTraversalExpContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.traversal`. + * @param ctx the parse tree + */ + enterTraversal?: (ctx: TraversalContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.traversal`. + * @param ctx the parse tree + */ + exitTraversal?: (ctx: TraversalContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.attributeName`. + * @param ctx the parse tree + */ + enterAttributeName?: (ctx: AttributeNameContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.attributeName`. + * @param ctx the parse tree + */ + exitAttributeName?: (ctx: AttributeNameContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.attributeValue`. + * @param ctx the parse tree + */ + enterAttributeValue?: (ctx: AttributeValueContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.attributeValue`. + * @param ctx the parse tree + */ + exitAttributeValue?: (ctx: AttributeValueContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.functionName`. + * @param ctx the parse tree + */ + enterFunctionName?: (ctx: FunctionNameContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.functionName`. + * @param ctx the parse tree + */ + exitFunctionName?: (ctx: FunctionNameContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.orToken`. + * @param ctx the parse tree + */ + enterOrToken?: (ctx: OrTokenContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.orToken`. + * @param ctx the parse tree + */ + exitOrToken?: (ctx: OrTokenContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.andToken`. + * @param ctx the parse tree + */ + enterAndToken?: (ctx: AndTokenContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.andToken`. + * @param ctx the parse tree + */ + exitAndToken?: (ctx: AndTokenContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.notToken`. + * @param ctx the parse tree + */ + enterNotToken?: (ctx: NotTokenContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.notToken`. + * @param ctx the parse tree + */ + exitNotToken?: (ctx: NotTokenContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.colonToken`. + * @param ctx the parse tree + */ + enterColonToken?: (ctx: ColonTokenContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.colonToken`. + * @param ctx the parse tree + */ + exitColonToken?: (ctx: ColonTokenContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.leftParenToken`. + * @param ctx the parse tree + */ + enterLeftParenToken?: (ctx: LeftParenTokenContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.leftParenToken`. + * @param ctx the parse tree + */ + exitLeftParenToken?: (ctx: LeftParenTokenContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.rightParenToken`. + * @param ctx the parse tree + */ + enterRightParenToken?: (ctx: RightParenTokenContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.rightParenToken`. + * @param ctx the parse tree + */ + exitRightParenToken?: (ctx: RightParenTokenContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.afterExpressionWhitespace`. + * @param ctx the parse tree + */ + enterAfterExpressionWhitespace?: (ctx: AfterExpressionWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.afterExpressionWhitespace`. + * @param ctx the parse tree + */ + exitAfterExpressionWhitespace?: (ctx: AfterExpressionWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.afterLogicalOperatorWhitespace`. + * @param ctx the parse tree + */ + enterAfterLogicalOperatorWhitespace?: (ctx: AfterLogicalOperatorWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.afterLogicalOperatorWhitespace`. + * @param ctx the parse tree + */ + exitAfterLogicalOperatorWhitespace?: (ctx: AfterLogicalOperatorWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + enterValue?: (ctx: ValueContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + */ + exitValue?: (ctx: ValueContext) => void; +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts new file mode 100644 index 0000000000000..b45a64e19042c --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts @@ -0,0 +1,2997 @@ +// Generated from /Users/marcosalazar/code/dagster/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 by ANTLR 4.9.0-SNAPSHOT + +import {FailedPredicateException} from 'antlr4ts/FailedPredicateException'; +import {NoViableAltException} from 'antlr4ts/NoViableAltException'; +import {Parser} from 'antlr4ts/Parser'; +import {ParserRuleContext} from 'antlr4ts/ParserRuleContext'; +import {RecognitionException} from 'antlr4ts/RecognitionException'; +import {RuleContext} from 'antlr4ts/RuleContext'; +//import { RuleVersion } from "antlr4ts/RuleVersion"; +import {TokenStream} from 'antlr4ts/TokenStream'; +import {Vocabulary} from 'antlr4ts/Vocabulary'; +import {VocabularyImpl} from 'antlr4ts/VocabularyImpl'; +import {ATN} from 'antlr4ts/atn/ATN'; +import {ATNDeserializer} from 'antlr4ts/atn/ATNDeserializer'; +import {ParserATNSimulator} from 'antlr4ts/atn/ParserATNSimulator'; +import * as Utils from 'antlr4ts/misc/Utils'; +import {TerminalNode} from 'antlr4ts/tree/TerminalNode'; + +import {SelectionAutoCompleteListener} from './SelectionAutoCompleteListener'; +import {SelectionAutoCompleteVisitor} from './SelectionAutoCompleteVisitor'; + +export class SelectionAutoCompleteParser extends Parser { + public static readonly AND = 1; + public static readonly OR = 2; + public static readonly NOT = 3; + public static readonly STAR = 4; + public static readonly PLUS = 5; + public static readonly COLON = 6; + public static readonly LPAREN = 7; + public static readonly RPAREN = 8; + public static readonly EQUAL = 9; + public static readonly QUOTED_STRING = 10; + public static readonly INCOMPLETE_LEFT_QUOTED_STRING = 11; + public static readonly INCOMPLETE_RIGHT_QUOTED_STRING = 12; + public static readonly IDENTIFIER = 13; + public static readonly WS = 14; + public static readonly RULE_start = 0; + public static readonly RULE_expr = 1; + public static readonly RULE_traversalAllowedExpr = 2; + public static readonly RULE_parenthesizedExpr = 3; + public static readonly RULE_incompleteExpressionsWrapper = 4; + public static readonly RULE_expressionLessParenthesizedExpr = 5; + public static readonly RULE_upTraversalExp = 6; + public static readonly RULE_downTraversalExp = 7; + public static readonly RULE_traversal = 8; + public static readonly RULE_attributeName = 9; + public static readonly RULE_attributeValue = 10; + public static readonly RULE_functionName = 11; + public static readonly RULE_orToken = 12; + public static readonly RULE_andToken = 13; + public static readonly RULE_notToken = 14; + public static readonly RULE_colonToken = 15; + public static readonly RULE_leftParenToken = 16; + public static readonly RULE_rightParenToken = 17; + public static readonly RULE_afterExpressionWhitespace = 18; + public static readonly RULE_afterLogicalOperatorWhitespace = 19; + public static readonly RULE_value = 20; + // tslint:disable:no-trailing-whitespace + public static readonly ruleNames: string[] = [ + 'start', + 'expr', + 'traversalAllowedExpr', + 'parenthesizedExpr', + 'incompleteExpressionsWrapper', + 'expressionLessParenthesizedExpr', + 'upTraversalExp', + 'downTraversalExp', + 'traversal', + 'attributeName', + 'attributeValue', + 'functionName', + 'orToken', + 'andToken', + 'notToken', + 'colonToken', + 'leftParenToken', + 'rightParenToken', + 'afterExpressionWhitespace', + 'afterLogicalOperatorWhitespace', + 'value', + ]; + + private static readonly _LITERAL_NAMES: Array = [ + undefined, + "'and'", + "'or'", + "'not'", + "'*'", + "'+'", + "':'", + "'('", + "')'", + "'='", + ]; + private static readonly _SYMBOLIC_NAMES: Array = [ + undefined, + 'AND', + 'OR', + 'NOT', + 'STAR', + 'PLUS', + 'COLON', + 'LPAREN', + 'RPAREN', + 'EQUAL', + 'QUOTED_STRING', + 'INCOMPLETE_LEFT_QUOTED_STRING', + 'INCOMPLETE_RIGHT_QUOTED_STRING', + 'IDENTIFIER', + 'WS', + ]; + public static readonly VOCABULARY: Vocabulary = new VocabularyImpl( + SelectionAutoCompleteParser._LITERAL_NAMES, + SelectionAutoCompleteParser._SYMBOLIC_NAMES, + [], + ); + + // @Override + // @NotNull + public get vocabulary(): Vocabulary { + return SelectionAutoCompleteParser.VOCABULARY; + } + // tslint:enable:no-trailing-whitespace + + // @Override + public get grammarFileName(): string { + return 'SelectionAutoComplete.g4'; + } + + // @Override + public get ruleNames(): string[] { + return SelectionAutoCompleteParser.ruleNames; + } + + // @Override + public get serializedATN(): string { + return SelectionAutoCompleteParser._serializedATN; + } + + protected createFailedPredicateException( + predicate?: string, + message?: string, + ): FailedPredicateException { + return new FailedPredicateException(this, predicate, message); + } + + constructor(input: TokenStream) { + super(input); + this._interp = new ParserATNSimulator(SelectionAutoCompleteParser._ATN, this); + } + // @RuleVersion(0) + public start(): StartContext { + const _localctx: StartContext = new StartContext(this._ctx, this.state); + this.enterRule(_localctx, 0, SelectionAutoCompleteParser.RULE_start); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 42; + this.expr(0); + this.state = 43; + this.match(SelectionAutoCompleteParser.EOF); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + + public expr(): ExprContext; + public expr(_p: number): ExprContext; + // @RuleVersion(0) + public expr(_p?: number): ExprContext { + if (_p === undefined) { + _p = 0; + } + + const _parentctx: ParserRuleContext = this._ctx; + const _parentState: number = this.state; + let _localctx: ExprContext = new ExprContext(this._ctx, _parentState); + let _prevctx: ExprContext = _localctx; + const _startState: number = 2; + this.enterRecursionRule(_localctx, 2, SelectionAutoCompleteParser.RULE_expr, _p); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 75; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 0, this._ctx)) { + case 1: + { + _localctx = new TraversalAllowedExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + + this.state = 46; + this.traversalAllowedExpr(); + this.state = 47; + this.afterExpressionWhitespace(); + } + break; + + case 2: + { + _localctx = new UpAndDownTraversalExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 49; + this.upTraversalExp(); + this.state = 50; + this.traversalAllowedExpr(); + this.state = 51; + this.downTraversalExp(); + this.state = 52; + this.afterExpressionWhitespace(); + } + break; + + case 3: + { + _localctx = new UpTraversalExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 54; + this.upTraversalExp(); + this.state = 55; + this.traversalAllowedExpr(); + this.state = 56; + this.afterExpressionWhitespace(); + } + break; + + case 4: + { + _localctx = new DownTraversalExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 58; + this.traversalAllowedExpr(); + this.state = 59; + this.downTraversalExp(); + this.state = 60; + this.afterExpressionWhitespace(); + } + break; + + case 5: + { + _localctx = new NotExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 62; + this.notToken(); + this.state = 63; + this.afterLogicalOperatorWhitespace(); + this.state = 64; + this.expr(0); + this.state = 65; + this.afterExpressionWhitespace(); + } + break; + + case 6: + { + _localctx = new IncompleteNotExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 67; + this.notToken(); + this.state = 68; + this.afterLogicalOperatorWhitespace(); + } + break; + + case 7: + { + _localctx = new AllExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 70; + this.match(SelectionAutoCompleteParser.STAR); + this.state = 71; + this.afterExpressionWhitespace(); + } + break; + + case 8: + { + _localctx = new UnmatchedValueContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 72; + this.value(); + this.state = 73; + this.afterExpressionWhitespace(); + } + break; + } + this._ctx._stop = this._input.tryLT(-1); + this.state = 108; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + if (this._parseListeners != null) { + this.triggerExitRuleEvent(); + } + _prevctx = _localctx; + { + this.state = 106; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 1, this._ctx)) { + case 1: + { + _localctx = new AndExpressionContext(new ExprContext(_parentctx, _parentState)); + this.pushNewRecursionContext( + _localctx, + _startState, + SelectionAutoCompleteParser.RULE_expr, + ); + this.state = 77; + if (!this.precpred(this._ctx, 8)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 8)'); + } + this.state = 78; + this.afterExpressionWhitespace(); + this.state = 79; + this.andToken(); + this.state = 80; + this.afterLogicalOperatorWhitespace(); + this.state = 81; + this.expr(0); + this.state = 82; + this.afterExpressionWhitespace(); + } + break; + + case 2: + { + _localctx = new OrExpressionContext(new ExprContext(_parentctx, _parentState)); + this.pushNewRecursionContext( + _localctx, + _startState, + SelectionAutoCompleteParser.RULE_expr, + ); + this.state = 84; + if (!this.precpred(this._ctx, 7)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 7)'); + } + this.state = 85; + this.afterExpressionWhitespace(); + this.state = 86; + this.orToken(); + this.state = 87; + this.afterLogicalOperatorWhitespace(); + this.state = 88; + this.expr(0); + this.state = 89; + this.afterExpressionWhitespace(); + } + break; + + case 3: + { + _localctx = new IncompleteAndExpressionContext( + new ExprContext(_parentctx, _parentState), + ); + this.pushNewRecursionContext( + _localctx, + _startState, + SelectionAutoCompleteParser.RULE_expr, + ); + this.state = 91; + if (!this.precpred(this._ctx, 6)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 6)'); + } + this.state = 92; + this.afterExpressionWhitespace(); + this.state = 93; + this.andToken(); + this.state = 94; + this.afterLogicalOperatorWhitespace(); + } + break; + + case 4: + { + _localctx = new IncompleteOrExpressionContext( + new ExprContext(_parentctx, _parentState), + ); + this.pushNewRecursionContext( + _localctx, + _startState, + SelectionAutoCompleteParser.RULE_expr, + ); + this.state = 96; + if (!this.precpred(this._ctx, 5)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 5)'); + } + this.state = 97; + this.afterExpressionWhitespace(); + this.state = 98; + this.orToken(); + this.state = 99; + this.afterLogicalOperatorWhitespace(); + } + break; + + case 5: + { + _localctx = new UnmatchedExpressionContinuationContext( + new ExprContext(_parentctx, _parentState), + ); + this.pushNewRecursionContext( + _localctx, + _startState, + SelectionAutoCompleteParser.RULE_expr, + ); + this.state = 101; + if (!this.precpred(this._ctx, 3)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 3)'); + } + this.state = 102; + this.afterExpressionWhitespace(); + this.state = 103; + this.value(); + this.state = 104; + this.afterLogicalOperatorWhitespace(); + } + break; + } + } + } + this.state = 110; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.unrollRecursionContexts(_parentctx); + } + return _localctx; + } + // @RuleVersion(0) + public traversalAllowedExpr(): TraversalAllowedExprContext { + let _localctx: TraversalAllowedExprContext = new TraversalAllowedExprContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 4, SelectionAutoCompleteParser.RULE_traversalAllowedExpr); + try { + this.state = 120; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 3, this._ctx)) { + case 1: + _localctx = new AttributeExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 111; + this.attributeName(); + this.state = 112; + this.colonToken(); + this.state = 113; + this.attributeValue(); + } + break; + + case 2: + _localctx = new FunctionCallExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 2); + { + this.state = 115; + this.functionName(); + this.state = 116; + this.parenthesizedExpr(); + } + break; + + case 3: + _localctx = new ParenthesizedExpressionWrapperContext(_localctx); + this.enterOuterAlt(_localctx, 3); + { + this.state = 118; + this.parenthesizedExpr(); + } + break; + + case 4: + _localctx = new IncompleteExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 4); + { + this.state = 119; + this.incompleteExpressionsWrapper(); + } + break; + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public parenthesizedExpr(): ParenthesizedExprContext { + let _localctx: ParenthesizedExprContext = new ParenthesizedExprContext(this._ctx, this.state); + this.enterRule(_localctx, 6, SelectionAutoCompleteParser.RULE_parenthesizedExpr); + try { + _localctx = new ParenthesizedExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 122; + this.leftParenToken(); + this.state = 123; + this.expr(0); + this.state = 124; + this.rightParenToken(); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public incompleteExpressionsWrapper(): IncompleteExpressionsWrapperContext { + let _localctx: IncompleteExpressionsWrapperContext = new IncompleteExpressionsWrapperContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 8, SelectionAutoCompleteParser.RULE_incompleteExpressionsWrapper); + try { + let _alt: number; + this.state = 152; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 5, this._ctx)) { + case 1: + _localctx = new IncompleteAttributeExpressionMissingValueContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 126; + this.attributeName(); + this.state = 127; + this.colonToken(); + } + break; + + case 2: + _localctx = new ExpressionlessFunctionExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 2); + { + this.state = 129; + this.functionName(); + this.state = 130; + this.expressionLessParenthesizedExpr(); + } + break; + + case 3: + _localctx = new UnclosedExpressionlessFunctionExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 3); + { + this.state = 132; + this.functionName(); + this.state = 133; + this.leftParenToken(); + } + break; + + case 4: + _localctx = new UnclosedFunctionExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 4); + { + this.state = 135; + this.functionName(); + this.state = 136; + this.leftParenToken(); + this.state = 137; + this.expr(0); + } + break; + + case 5: + _localctx = new UnclosedParenthesizedExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 5); + { + this.state = 139; + this.leftParenToken(); + this.state = 140; + this.expr(0); + } + break; + + case 6: + _localctx = new ExpressionlessParenthesizedExpressionWrapperContext(_localctx); + this.enterOuterAlt(_localctx, 6); + { + this.state = 142; + this.expressionLessParenthesizedExpr(); + } + break; + + case 7: + _localctx = new UnclosedExpressionlessParenthesizedExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 7); + { + this.state = 143; + this.leftParenToken(); + } + break; + + case 8: + _localctx = new IncompleteTraversalExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 8); + { + this.state = 145; + this._errHandler.sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + this.state = 144; + this.match(SelectionAutoCompleteParser.PLUS); + } + } + break; + default: + throw new NoViableAltException(this); + } + this.state = 147; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 4, this._ctx); + } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); + } + break; + + case 9: + _localctx = new IncompleteAttributeExpressionMissingKeyContext(_localctx); + this.enterOuterAlt(_localctx, 9); + { + this.state = 149; + this.colonToken(); + this.state = 150; + this.attributeValue(); + } + break; + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public expressionLessParenthesizedExpr(): ExpressionLessParenthesizedExprContext { + let _localctx: ExpressionLessParenthesizedExprContext = + new ExpressionLessParenthesizedExprContext(this._ctx, this.state); + this.enterRule(_localctx, 10, SelectionAutoCompleteParser.RULE_expressionLessParenthesizedExpr); + try { + _localctx = new ExpressionlessParenthesizedExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 154; + this.leftParenToken(); + this.state = 155; + this.rightParenToken(); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public upTraversalExp(): UpTraversalExpContext { + let _localctx: UpTraversalExpContext = new UpTraversalExpContext(this._ctx, this.state); + this.enterRule(_localctx, 12, SelectionAutoCompleteParser.RULE_upTraversalExp); + try { + _localctx = new UpTraversalContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 157; + this.traversal(); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public downTraversalExp(): DownTraversalExpContext { + let _localctx: DownTraversalExpContext = new DownTraversalExpContext(this._ctx, this.state); + this.enterRule(_localctx, 14, SelectionAutoCompleteParser.RULE_downTraversalExp); + try { + _localctx = new DownTraversalContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 159; + this.traversal(); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public traversal(): TraversalContext { + const _localctx: TraversalContext = new TraversalContext(this._ctx, this.state); + this.enterRule(_localctx, 16, SelectionAutoCompleteParser.RULE_traversal); + try { + let _alt: number; + this.state = 167; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case SelectionAutoCompleteParser.STAR: + this.enterOuterAlt(_localctx, 1); + { + this.state = 161; + this.match(SelectionAutoCompleteParser.STAR); + } + break; + case SelectionAutoCompleteParser.PLUS: + this.enterOuterAlt(_localctx, 2); + { + this.state = 163; + this._errHandler.sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + this.state = 162; + this.match(SelectionAutoCompleteParser.PLUS); + } + } + break; + default: + throw new NoViableAltException(this); + } + this.state = 165; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 6, this._ctx); + } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); + } + break; + default: + throw new NoViableAltException(this); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public attributeName(): AttributeNameContext { + const _localctx: AttributeNameContext = new AttributeNameContext(this._ctx, this.state); + this.enterRule(_localctx, 18, SelectionAutoCompleteParser.RULE_attributeName); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 169; + this.match(SelectionAutoCompleteParser.IDENTIFIER); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public attributeValue(): AttributeValueContext { + const _localctx: AttributeValueContext = new AttributeValueContext(this._ctx, this.state); + this.enterRule(_localctx, 20, SelectionAutoCompleteParser.RULE_attributeValue); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 171; + this.value(); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public functionName(): FunctionNameContext { + const _localctx: FunctionNameContext = new FunctionNameContext(this._ctx, this.state); + this.enterRule(_localctx, 22, SelectionAutoCompleteParser.RULE_functionName); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 173; + this.match(SelectionAutoCompleteParser.IDENTIFIER); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public orToken(): OrTokenContext { + const _localctx: OrTokenContext = new OrTokenContext(this._ctx, this.state); + this.enterRule(_localctx, 24, SelectionAutoCompleteParser.RULE_orToken); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 175; + this.match(SelectionAutoCompleteParser.OR); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public andToken(): AndTokenContext { + const _localctx: AndTokenContext = new AndTokenContext(this._ctx, this.state); + this.enterRule(_localctx, 26, SelectionAutoCompleteParser.RULE_andToken); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 177; + this.match(SelectionAutoCompleteParser.AND); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public notToken(): NotTokenContext { + const _localctx: NotTokenContext = new NotTokenContext(this._ctx, this.state); + this.enterRule(_localctx, 28, SelectionAutoCompleteParser.RULE_notToken); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 179; + this.match(SelectionAutoCompleteParser.NOT); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public colonToken(): ColonTokenContext { + const _localctx: ColonTokenContext = new ColonTokenContext(this._ctx, this.state); + this.enterRule(_localctx, 30, SelectionAutoCompleteParser.RULE_colonToken); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 181; + this.match(SelectionAutoCompleteParser.COLON); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public leftParenToken(): LeftParenTokenContext { + const _localctx: LeftParenTokenContext = new LeftParenTokenContext(this._ctx, this.state); + this.enterRule(_localctx, 32, SelectionAutoCompleteParser.RULE_leftParenToken); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 183; + this.match(SelectionAutoCompleteParser.LPAREN); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public rightParenToken(): RightParenTokenContext { + const _localctx: RightParenTokenContext = new RightParenTokenContext(this._ctx, this.state); + this.enterRule(_localctx, 34, SelectionAutoCompleteParser.RULE_rightParenToken); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 185; + this.match(SelectionAutoCompleteParser.RPAREN); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + const _localctx: AfterExpressionWhitespaceContext = new AfterExpressionWhitespaceContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 36, SelectionAutoCompleteParser.RULE_afterExpressionWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 190; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 187; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 192; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + const _localctx: AfterLogicalOperatorWhitespaceContext = + new AfterLogicalOperatorWhitespaceContext(this._ctx, this.state); + this.enterRule(_localctx, 38, SelectionAutoCompleteParser.RULE_afterLogicalOperatorWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 196; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 9, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 193; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 198; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 9, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public value(): ValueContext { + let _localctx: ValueContext = new ValueContext(this._ctx, this.state); + this.enterRule(_localctx, 40, SelectionAutoCompleteParser.RULE_value); + try { + this.state = 203; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case SelectionAutoCompleteParser.QUOTED_STRING: + _localctx = new QuotedStringValueContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 199; + this.match(SelectionAutoCompleteParser.QUOTED_STRING); + } + break; + case SelectionAutoCompleteParser.INCOMPLETE_LEFT_QUOTED_STRING: + _localctx = new IncompleteLeftQuotedStringValueContext(_localctx); + this.enterOuterAlt(_localctx, 2); + { + this.state = 200; + this.match(SelectionAutoCompleteParser.INCOMPLETE_LEFT_QUOTED_STRING); + } + break; + case SelectionAutoCompleteParser.INCOMPLETE_RIGHT_QUOTED_STRING: + _localctx = new IncompleteRightQuotedStringValueContext(_localctx); + this.enterOuterAlt(_localctx, 3); + { + this.state = 201; + this.match(SelectionAutoCompleteParser.INCOMPLETE_RIGHT_QUOTED_STRING); + } + break; + case SelectionAutoCompleteParser.IDENTIFIER: + _localctx = new UnquotedStringValueContext(_localctx); + this.enterOuterAlt(_localctx, 4); + { + this.state = 202; + this.match(SelectionAutoCompleteParser.IDENTIFIER); + } + break; + default: + throw new NoViableAltException(this); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + + public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { + switch (ruleIndex) { + case 1: + return this.expr_sempred(_localctx as ExprContext, predIndex); + } + return true; + } + private expr_sempred(_localctx: ExprContext, predIndex: number): boolean { + switch (predIndex) { + case 0: + return this.precpred(this._ctx, 8); + + case 1: + return this.precpred(this._ctx, 7); + + case 2: + return this.precpred(this._ctx, 6); + + case 3: + return this.precpred(this._ctx, 5); + + case 4: + return this.precpred(this._ctx, 3); + } + return true; + } + + public static readonly _serializedATN: string = + '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x10\xD0\x04\x02' + + '\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07' + + '\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r\x04' + + '\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t\x12\x04' + + '\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x03\x02\x03\x02\x03' + + '\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x05\x03N\n\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x07\x03m' + + '\n\x03\f\x03\x0E\x03p\v\x03\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03' + + '\x04\x03\x04\x03\x04\x03\x04\x05\x04{\n\x04\x03\x05\x03\x05\x03\x05\x03' + + '\x05\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03' + + '\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03' + + '\x06\x03\x06\x06\x06\x94\n\x06\r\x06\x0E\x06\x95\x03\x06\x03\x06\x03\x06' + + '\x05\x06\x9B\n\x06\x03\x07\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03\t\x03' + + '\n\x03\n\x06\n\xA6\n\n\r\n\x0E\n\xA7\x05\n\xAA\n\n\x03\v\x03\v\x03\f\x03' + + '\f\x03\r\x03\r\x03\x0E\x03\x0E\x03\x0F\x03\x0F\x03\x10\x03\x10\x03\x11' + + '\x03\x11\x03\x12\x03\x12\x03\x13\x03\x13\x03\x14\x07\x14\xBF\n\x14\f\x14' + + '\x0E\x14\xC2\v\x14\x03\x15\x07\x15\xC5\n\x15\f\x15\x0E\x15\xC8\v\x15\x03' + + '\x16\x03\x16\x03\x16\x03\x16\x05\x16\xCE\n\x16\x03\x16\x02\x02\x03\x04' + + '\x17\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10\x02\x12\x02' + + '\x14\x02\x16\x02\x18\x02\x1A\x02\x1C\x02\x1E\x02 \x02"\x02$\x02&\x02' + + '(\x02*\x02\x02\x02\x02\xD9\x02,\x03\x02\x02\x02\x04M\x03\x02\x02\x02\x06' + + 'z\x03\x02\x02\x02\b|\x03\x02\x02\x02\n\x9A\x03\x02\x02\x02\f\x9C\x03\x02' + + '\x02\x02\x0E\x9F\x03\x02\x02\x02\x10\xA1\x03\x02\x02\x02\x12\xA9\x03\x02' + + '\x02\x02\x14\xAB\x03\x02\x02\x02\x16\xAD\x03\x02\x02\x02\x18\xAF\x03\x02' + + '\x02\x02\x1A\xB1\x03\x02\x02\x02\x1C\xB3\x03\x02\x02\x02\x1E\xB5\x03\x02' + + '\x02\x02 \xB7\x03\x02\x02\x02"\xB9\x03\x02\x02\x02$\xBB\x03\x02\x02\x02' + + '&\xC0\x03\x02\x02\x02(\xC6\x03\x02\x02\x02*\xCD\x03\x02\x02\x02,-\x05' + + '\x04\x03\x02-.\x07\x02\x02\x03.\x03\x03\x02\x02\x02/0\b\x03\x01\x0201' + + '\x05\x06\x04\x0212\x05&\x14\x022N\x03\x02\x02\x0234\x05\x0E\b\x0245\x05' + + '\x06\x04\x0256\x05\x10\t\x0267\x05&\x14\x027N\x03\x02\x02\x0289\x05\x0E' + + '\b\x029:\x05\x06\x04\x02:;\x05&\x14\x02;N\x03\x02\x02\x02<=\x05\x06\x04' + + '\x02=>\x05\x10\t\x02>?\x05&\x14\x02?N\x03\x02\x02\x02@A\x05\x1E\x10\x02' + + 'AB\x05(\x15\x02BC\x05\x04\x03\x02CD\x05&\x14\x02DN\x03\x02\x02\x02EF\x05' + + '\x1E\x10\x02FG\x05(\x15\x02GN\x03\x02\x02\x02HI\x07\x06\x02\x02IN\x05' + + '&\x14\x02JK\x05*\x16\x02KL\x05&\x14\x02LN\x03\x02\x02\x02M/\x03\x02\x02' + + '\x02M3\x03\x02\x02\x02M8\x03\x02\x02\x02M<\x03\x02\x02\x02M@\x03\x02\x02' + + '\x02ME\x03\x02\x02\x02MH\x03\x02\x02\x02MJ\x03\x02\x02\x02Nn\x03\x02\x02' + + '\x02OP\f\n\x02\x02PQ\x05&\x14\x02QR\x05\x1C\x0F\x02RS\x05(\x15\x02ST\x05' + + '\x04\x03\x02TU\x05&\x14\x02Um\x03\x02\x02\x02VW\f\t\x02\x02WX\x05&\x14' + + '\x02XY\x05\x1A\x0E\x02YZ\x05(\x15\x02Z[\x05\x04\x03\x02[\\\x05&\x14\x02' + + '\\m\x03\x02\x02\x02]^\f\b\x02\x02^_\x05&\x14\x02_`\x05\x1C\x0F\x02`a\x05' + + '(\x15\x02am\x03\x02\x02\x02bc\f\x07\x02\x02cd\x05&\x14\x02de\x05\x1A\x0E' + + '\x02ef\x05(\x15\x02fm\x03\x02\x02\x02gh\f\x05\x02\x02hi\x05&\x14\x02i' + + 'j\x05*\x16\x02jk\x05(\x15\x02km\x03\x02\x02\x02lO\x03\x02\x02\x02lV\x03' + + '\x02\x02\x02l]\x03\x02\x02\x02lb\x03\x02\x02\x02lg\x03\x02\x02\x02mp\x03' + + '\x02\x02\x02nl\x03\x02\x02\x02no\x03\x02\x02\x02o\x05\x03\x02\x02\x02' + + 'pn\x03\x02\x02\x02qr\x05\x14\v\x02rs\x05 \x11\x02st\x05\x16\f\x02t{\x03' + + '\x02\x02\x02uv\x05\x18\r\x02vw\x05\b\x05\x02w{\x03\x02\x02\x02x{\x05\b' + + '\x05\x02y{\x05\n\x06\x02zq\x03\x02\x02\x02zu\x03\x02\x02\x02zx\x03\x02' + + '\x02\x02zy\x03\x02\x02\x02{\x07\x03\x02\x02\x02|}\x05"\x12\x02}~\x05' + + '\x04\x03\x02~\x7F\x05$\x13\x02\x7F\t\x03\x02\x02\x02\x80\x81\x05\x14\v' + + '\x02\x81\x82\x05 \x11\x02\x82\x9B\x03\x02\x02\x02\x83\x84\x05\x18\r\x02' + + '\x84\x85\x05\f\x07\x02\x85\x9B\x03\x02\x02\x02\x86\x87\x05\x18\r\x02\x87' + + '\x88\x05"\x12\x02\x88\x9B\x03\x02\x02\x02\x89\x8A\x05\x18\r\x02\x8A\x8B' + + '\x05"\x12\x02\x8B\x8C\x05\x04\x03\x02\x8C\x9B\x03\x02\x02\x02\x8D\x8E' + + '\x05"\x12\x02\x8E\x8F\x05\x04\x03\x02\x8F\x9B\x03\x02\x02\x02\x90\x9B' + + '\x05\f\x07\x02\x91\x9B\x05"\x12\x02\x92\x94\x07\x07\x02\x02\x93\x92\x03' + + '\x02\x02\x02\x94\x95\x03\x02\x02\x02\x95\x93\x03\x02\x02\x02\x95\x96\x03' + + '\x02\x02\x02\x96\x9B\x03\x02\x02\x02\x97\x98\x05 \x11\x02\x98\x99\x05' + + '\x16\f\x02\x99\x9B\x03\x02\x02\x02\x9A\x80\x03\x02\x02\x02\x9A\x83\x03' + + '\x02\x02\x02\x9A\x86\x03\x02\x02\x02\x9A\x89\x03\x02\x02\x02\x9A\x8D\x03' + + '\x02\x02\x02\x9A\x90\x03\x02\x02\x02\x9A\x91\x03\x02\x02\x02\x9A\x93\x03' + + '\x02\x02\x02\x9A\x97\x03\x02\x02\x02\x9B\v\x03\x02\x02\x02\x9C\x9D\x05' + + '"\x12\x02\x9D\x9E\x05$\x13\x02\x9E\r\x03\x02\x02\x02\x9F\xA0\x05\x12' + + '\n\x02\xA0\x0F\x03\x02\x02\x02\xA1\xA2\x05\x12\n\x02\xA2\x11\x03\x02\x02' + + '\x02\xA3\xAA\x07\x06\x02\x02\xA4\xA6\x07\x07\x02\x02\xA5\xA4\x03\x02\x02' + + '\x02\xA6\xA7\x03\x02\x02\x02\xA7\xA5\x03\x02\x02\x02\xA7\xA8\x03\x02\x02' + + '\x02\xA8\xAA\x03\x02\x02\x02\xA9\xA3\x03\x02\x02\x02\xA9\xA5\x03\x02\x02' + + '\x02\xAA\x13\x03\x02\x02\x02\xAB\xAC\x07\x0F\x02\x02\xAC\x15\x03\x02\x02' + + '\x02\xAD\xAE\x05*\x16\x02\xAE\x17\x03\x02\x02\x02\xAF\xB0\x07\x0F\x02' + + '\x02\xB0\x19\x03\x02\x02\x02\xB1\xB2\x07\x04\x02\x02\xB2\x1B\x03\x02\x02' + + '\x02\xB3\xB4\x07\x03\x02\x02\xB4\x1D\x03\x02\x02\x02\xB5\xB6\x07\x05\x02' + + '\x02\xB6\x1F\x03\x02\x02\x02\xB7\xB8\x07\b\x02\x02\xB8!\x03\x02\x02\x02' + + '\xB9\xBA\x07\t\x02\x02\xBA#\x03\x02\x02\x02\xBB\xBC\x07\n\x02\x02\xBC' + + '%\x03\x02\x02\x02\xBD\xBF\x07\x10\x02\x02\xBE\xBD\x03\x02\x02\x02\xBF' + + '\xC2\x03\x02\x02\x02\xC0\xBE\x03\x02\x02\x02\xC0\xC1\x03\x02\x02\x02\xC1' + + "'\x03\x02\x02\x02\xC2\xC0\x03\x02\x02\x02\xC3\xC5\x07\x10\x02\x02\xC4" + + '\xC3\x03\x02\x02\x02\xC5\xC8\x03\x02\x02\x02\xC6\xC4\x03\x02\x02\x02\xC6' + + '\xC7\x03\x02\x02\x02\xC7)\x03\x02\x02\x02\xC8\xC6\x03\x02\x02\x02\xC9' + + '\xCE\x07\f\x02\x02\xCA\xCE\x07\r\x02\x02\xCB\xCE\x07\x0E\x02\x02\xCC\xCE' + + '\x07\x0F\x02\x02\xCD\xC9\x03\x02\x02\x02\xCD\xCA\x03\x02\x02\x02\xCD\xCB' + + '\x03\x02\x02\x02\xCD\xCC\x03\x02\x02\x02\xCE+\x03\x02\x02\x02\rMlnz\x95' + + '\x9A\xA7\xA9\xC0\xC6\xCD'; + public static __ATN: ATN; + public static get _ATN(): ATN { + if (!SelectionAutoCompleteParser.__ATN) { + SelectionAutoCompleteParser.__ATN = new ATNDeserializer().deserialize( + Utils.toCharArray(SelectionAutoCompleteParser._serializedATN), + ); + } + + return SelectionAutoCompleteParser.__ATN; + } +} + +export class StartContext extends ParserRuleContext { + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public EOF(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.EOF, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_start; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterStart) { + listener.enterStart(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitStart) { + listener.exitStart(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitStart) { + return visitor.visitStart(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_expr; + } + public copyFrom(ctx: ExprContext): void { + super.copyFrom(ctx); + } +} +export class TraversalAllowedExpressionContext extends ExprContext { + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterTraversalAllowedExpression) { + listener.enterTraversalAllowedExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitTraversalAllowedExpression) { + listener.exitTraversalAllowedExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitTraversalAllowedExpression) { + return visitor.visitTraversalAllowedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UpAndDownTraversalExpressionContext extends ExprContext { + public upTraversalExp(): UpTraversalExpContext { + return this.getRuleContext(0, UpTraversalExpContext); + } + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + public downTraversalExp(): DownTraversalExpContext { + return this.getRuleContext(0, DownTraversalExpContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUpAndDownTraversalExpression) { + listener.enterUpAndDownTraversalExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUpAndDownTraversalExpression) { + listener.exitUpAndDownTraversalExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUpAndDownTraversalExpression) { + return visitor.visitUpAndDownTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UpTraversalExpressionContext extends ExprContext { + public upTraversalExp(): UpTraversalExpContext { + return this.getRuleContext(0, UpTraversalExpContext); + } + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUpTraversalExpression) { + listener.enterUpTraversalExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUpTraversalExpression) { + listener.exitUpTraversalExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUpTraversalExpression) { + return visitor.visitUpTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class DownTraversalExpressionContext extends ExprContext { + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + public downTraversalExp(): DownTraversalExpContext { + return this.getRuleContext(0, DownTraversalExpContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterDownTraversalExpression) { + listener.enterDownTraversalExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitDownTraversalExpression) { + listener.exitDownTraversalExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitDownTraversalExpression) { + return visitor.visitDownTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class NotExpressionContext extends ExprContext { + public notToken(): NotTokenContext { + return this.getRuleContext(0, NotTokenContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterNotExpression) { + listener.enterNotExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitNotExpression) { + listener.exitNotExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitNotExpression) { + return visitor.visitNotExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class AndExpressionContext extends ExprContext { + public expr(): ExprContext[]; + public expr(i: number): ExprContext; + public expr(i?: number): ExprContext | ExprContext[] { + if (i === undefined) { + return this.getRuleContexts(ExprContext); + } else { + return this.getRuleContext(i, ExprContext); + } + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext[]; + public afterExpressionWhitespace(i: number): AfterExpressionWhitespaceContext; + public afterExpressionWhitespace( + i?: number, + ): AfterExpressionWhitespaceContext | AfterExpressionWhitespaceContext[] { + if (i === undefined) { + return this.getRuleContexts(AfterExpressionWhitespaceContext); + } else { + return this.getRuleContext(i, AfterExpressionWhitespaceContext); + } + } + public andToken(): AndTokenContext { + return this.getRuleContext(0, AndTokenContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAndExpression) { + listener.enterAndExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAndExpression) { + listener.exitAndExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAndExpression) { + return visitor.visitAndExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class OrExpressionContext extends ExprContext { + public expr(): ExprContext[]; + public expr(i: number): ExprContext; + public expr(i?: number): ExprContext | ExprContext[] { + if (i === undefined) { + return this.getRuleContexts(ExprContext); + } else { + return this.getRuleContext(i, ExprContext); + } + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext[]; + public afterExpressionWhitespace(i: number): AfterExpressionWhitespaceContext; + public afterExpressionWhitespace( + i?: number, + ): AfterExpressionWhitespaceContext | AfterExpressionWhitespaceContext[] { + if (i === undefined) { + return this.getRuleContexts(AfterExpressionWhitespaceContext); + } else { + return this.getRuleContext(i, AfterExpressionWhitespaceContext); + } + } + public orToken(): OrTokenContext { + return this.getRuleContext(0, OrTokenContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterOrExpression) { + listener.enterOrExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitOrExpression) { + listener.exitOrExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitOrExpression) { + return visitor.visitOrExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteAndExpressionContext extends ExprContext { + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + public andToken(): AndTokenContext { + return this.getRuleContext(0, AndTokenContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteAndExpression) { + listener.enterIncompleteAndExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteAndExpression) { + listener.exitIncompleteAndExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteAndExpression) { + return visitor.visitIncompleteAndExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteOrExpressionContext extends ExprContext { + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + public orToken(): OrTokenContext { + return this.getRuleContext(0, OrTokenContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteOrExpression) { + listener.enterIncompleteOrExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteOrExpression) { + listener.exitIncompleteOrExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteOrExpression) { + return visitor.visitIncompleteOrExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteNotExpressionContext extends ExprContext { + public notToken(): NotTokenContext { + return this.getRuleContext(0, NotTokenContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteNotExpression) { + listener.enterIncompleteNotExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteNotExpression) { + listener.exitIncompleteNotExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteNotExpression) { + return visitor.visitIncompleteNotExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnmatchedExpressionContinuationContext extends ExprContext { + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + public value(): ValueContext { + return this.getRuleContext(0, ValueContext); + } + public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnmatchedExpressionContinuation) { + listener.enterUnmatchedExpressionContinuation(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnmatchedExpressionContinuation) { + listener.exitUnmatchedExpressionContinuation(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnmatchedExpressionContinuation) { + return visitor.visitUnmatchedExpressionContinuation(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class AllExpressionContext extends ExprContext { + public STAR(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.STAR, 0); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAllExpression) { + listener.enterAllExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAllExpression) { + listener.exitAllExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAllExpression) { + return visitor.visitAllExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnmatchedValueContext extends ExprContext { + public value(): ValueContext { + return this.getRuleContext(0, ValueContext); + } + public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { + return this.getRuleContext(0, AfterExpressionWhitespaceContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnmatchedValue) { + listener.enterUnmatchedValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnmatchedValue) { + listener.exitUnmatchedValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnmatchedValue) { + return visitor.visitUnmatchedValue(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class TraversalAllowedExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_traversalAllowedExpr; + } + public copyFrom(ctx: TraversalAllowedExprContext): void { + super.copyFrom(ctx); + } +} +export class AttributeExpressionContext extends TraversalAllowedExprContext { + public attributeName(): AttributeNameContext { + return this.getRuleContext(0, AttributeNameContext); + } + public colonToken(): ColonTokenContext { + return this.getRuleContext(0, ColonTokenContext); + } + public attributeValue(): AttributeValueContext { + return this.getRuleContext(0, AttributeValueContext); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAttributeExpression) { + listener.enterAttributeExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAttributeExpression) { + listener.exitAttributeExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAttributeExpression) { + return visitor.visitAttributeExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class FunctionCallExpressionContext extends TraversalAllowedExprContext { + public functionName(): FunctionNameContext { + return this.getRuleContext(0, FunctionNameContext); + } + public parenthesizedExpr(): ParenthesizedExprContext { + return this.getRuleContext(0, ParenthesizedExprContext); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterFunctionCallExpression) { + listener.enterFunctionCallExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitFunctionCallExpression) { + listener.exitFunctionCallExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitFunctionCallExpression) { + return visitor.visitFunctionCallExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class ParenthesizedExpressionWrapperContext extends TraversalAllowedExprContext { + public parenthesizedExpr(): ParenthesizedExprContext { + return this.getRuleContext(0, ParenthesizedExprContext); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterParenthesizedExpressionWrapper) { + listener.enterParenthesizedExpressionWrapper(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitParenthesizedExpressionWrapper) { + listener.exitParenthesizedExpressionWrapper(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitParenthesizedExpressionWrapper) { + return visitor.visitParenthesizedExpressionWrapper(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteExpressionContext extends TraversalAllowedExprContext { + public incompleteExpressionsWrapper(): IncompleteExpressionsWrapperContext { + return this.getRuleContext(0, IncompleteExpressionsWrapperContext); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteExpression) { + listener.enterIncompleteExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteExpression) { + listener.exitIncompleteExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteExpression) { + return visitor.visitIncompleteExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ParenthesizedExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_parenthesizedExpr; + } + public copyFrom(ctx: ParenthesizedExprContext): void { + super.copyFrom(ctx); + } +} +export class ParenthesizedExpressionContext extends ParenthesizedExprContext { + public leftParenToken(): LeftParenTokenContext { + return this.getRuleContext(0, LeftParenTokenContext); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public rightParenToken(): RightParenTokenContext { + return this.getRuleContext(0, RightParenTokenContext); + } + constructor(ctx: ParenthesizedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterParenthesizedExpression) { + listener.enterParenthesizedExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitParenthesizedExpression) { + listener.exitParenthesizedExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitParenthesizedExpression) { + return visitor.visitParenthesizedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class IncompleteExpressionsWrapperContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_incompleteExpressionsWrapper; + } + public copyFrom(ctx: IncompleteExpressionsWrapperContext): void { + super.copyFrom(ctx); + } +} +export class IncompleteAttributeExpressionMissingValueContext extends IncompleteExpressionsWrapperContext { + public attributeName(): AttributeNameContext { + return this.getRuleContext(0, AttributeNameContext); + } + public colonToken(): ColonTokenContext { + return this.getRuleContext(0, ColonTokenContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteAttributeExpressionMissingValue) { + listener.enterIncompleteAttributeExpressionMissingValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteAttributeExpressionMissingValue) { + listener.exitIncompleteAttributeExpressionMissingValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteAttributeExpressionMissingValue) { + return visitor.visitIncompleteAttributeExpressionMissingValue(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class ExpressionlessFunctionExpressionContext extends IncompleteExpressionsWrapperContext { + public functionName(): FunctionNameContext { + return this.getRuleContext(0, FunctionNameContext); + } + public expressionLessParenthesizedExpr(): ExpressionLessParenthesizedExprContext { + return this.getRuleContext(0, ExpressionLessParenthesizedExprContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterExpressionlessFunctionExpression) { + listener.enterExpressionlessFunctionExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitExpressionlessFunctionExpression) { + listener.exitExpressionlessFunctionExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitExpressionlessFunctionExpression) { + return visitor.visitExpressionlessFunctionExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnclosedExpressionlessFunctionExpressionContext extends IncompleteExpressionsWrapperContext { + public functionName(): FunctionNameContext { + return this.getRuleContext(0, FunctionNameContext); + } + public leftParenToken(): LeftParenTokenContext { + return this.getRuleContext(0, LeftParenTokenContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnclosedExpressionlessFunctionExpression) { + listener.enterUnclosedExpressionlessFunctionExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnclosedExpressionlessFunctionExpression) { + listener.exitUnclosedExpressionlessFunctionExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnclosedExpressionlessFunctionExpression) { + return visitor.visitUnclosedExpressionlessFunctionExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnclosedFunctionExpressionContext extends IncompleteExpressionsWrapperContext { + public functionName(): FunctionNameContext { + return this.getRuleContext(0, FunctionNameContext); + } + public leftParenToken(): LeftParenTokenContext { + return this.getRuleContext(0, LeftParenTokenContext); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnclosedFunctionExpression) { + listener.enterUnclosedFunctionExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnclosedFunctionExpression) { + listener.exitUnclosedFunctionExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnclosedFunctionExpression) { + return visitor.visitUnclosedFunctionExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnclosedParenthesizedExpressionContext extends IncompleteExpressionsWrapperContext { + public leftParenToken(): LeftParenTokenContext { + return this.getRuleContext(0, LeftParenTokenContext); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnclosedParenthesizedExpression) { + listener.enterUnclosedParenthesizedExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnclosedParenthesizedExpression) { + listener.exitUnclosedParenthesizedExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnclosedParenthesizedExpression) { + return visitor.visitUnclosedParenthesizedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class ExpressionlessParenthesizedExpressionWrapperContext extends IncompleteExpressionsWrapperContext { + public expressionLessParenthesizedExpr(): ExpressionLessParenthesizedExprContext { + return this.getRuleContext(0, ExpressionLessParenthesizedExprContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterExpressionlessParenthesizedExpressionWrapper) { + listener.enterExpressionlessParenthesizedExpressionWrapper(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitExpressionlessParenthesizedExpressionWrapper) { + listener.exitExpressionlessParenthesizedExpressionWrapper(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitExpressionlessParenthesizedExpressionWrapper) { + return visitor.visitExpressionlessParenthesizedExpressionWrapper(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnclosedExpressionlessParenthesizedExpressionContext extends IncompleteExpressionsWrapperContext { + public leftParenToken(): LeftParenTokenContext { + return this.getRuleContext(0, LeftParenTokenContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnclosedExpressionlessParenthesizedExpression) { + listener.enterUnclosedExpressionlessParenthesizedExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnclosedExpressionlessParenthesizedExpression) { + listener.exitUnclosedExpressionlessParenthesizedExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnclosedExpressionlessParenthesizedExpression) { + return visitor.visitUnclosedExpressionlessParenthesizedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteTraversalExpressionContext extends IncompleteExpressionsWrapperContext { + public PLUS(): TerminalNode[]; + public PLUS(i: number): TerminalNode; + public PLUS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.PLUS); + } else { + return this.getToken(SelectionAutoCompleteParser.PLUS, i); + } + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteTraversalExpression) { + listener.enterIncompleteTraversalExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteTraversalExpression) { + listener.exitIncompleteTraversalExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteTraversalExpression) { + return visitor.visitIncompleteTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteAttributeExpressionMissingKeyContext extends IncompleteExpressionsWrapperContext { + public colonToken(): ColonTokenContext { + return this.getRuleContext(0, ColonTokenContext); + } + public attributeValue(): AttributeValueContext { + return this.getRuleContext(0, AttributeValueContext); + } + constructor(ctx: IncompleteExpressionsWrapperContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteAttributeExpressionMissingKey) { + listener.enterIncompleteAttributeExpressionMissingKey(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteAttributeExpressionMissingKey) { + listener.exitIncompleteAttributeExpressionMissingKey(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteAttributeExpressionMissingKey) { + return visitor.visitIncompleteAttributeExpressionMissingKey(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ExpressionLessParenthesizedExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_expressionLessParenthesizedExpr; + } + public copyFrom(ctx: ExpressionLessParenthesizedExprContext): void { + super.copyFrom(ctx); + } +} +export class ExpressionlessParenthesizedExpressionContext extends ExpressionLessParenthesizedExprContext { + public leftParenToken(): LeftParenTokenContext { + return this.getRuleContext(0, LeftParenTokenContext); + } + public rightParenToken(): RightParenTokenContext { + return this.getRuleContext(0, RightParenTokenContext); + } + constructor(ctx: ExpressionLessParenthesizedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterExpressionlessParenthesizedExpression) { + listener.enterExpressionlessParenthesizedExpression(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitExpressionlessParenthesizedExpression) { + listener.exitExpressionlessParenthesizedExpression(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitExpressionlessParenthesizedExpression) { + return visitor.visitExpressionlessParenthesizedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class UpTraversalExpContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_upTraversalExp; + } + public copyFrom(ctx: UpTraversalExpContext): void { + super.copyFrom(ctx); + } +} +export class UpTraversalContext extends UpTraversalExpContext { + public traversal(): TraversalContext { + return this.getRuleContext(0, TraversalContext); + } + constructor(ctx: UpTraversalExpContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUpTraversal) { + listener.enterUpTraversal(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUpTraversal) { + listener.exitUpTraversal(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUpTraversal) { + return visitor.visitUpTraversal(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class DownTraversalExpContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_downTraversalExp; + } + public copyFrom(ctx: DownTraversalExpContext): void { + super.copyFrom(ctx); + } +} +export class DownTraversalContext extends DownTraversalExpContext { + public traversal(): TraversalContext { + return this.getRuleContext(0, TraversalContext); + } + constructor(ctx: DownTraversalExpContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterDownTraversal) { + listener.enterDownTraversal(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitDownTraversal) { + listener.exitDownTraversal(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitDownTraversal) { + return visitor.visitDownTraversal(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class TraversalContext extends ParserRuleContext { + public STAR(): TerminalNode | undefined { + return this.tryGetToken(SelectionAutoCompleteParser.STAR, 0); + } + public PLUS(): TerminalNode[]; + public PLUS(i: number): TerminalNode; + public PLUS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.PLUS); + } else { + return this.getToken(SelectionAutoCompleteParser.PLUS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_traversal; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterTraversal) { + listener.enterTraversal(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitTraversal) { + listener.exitTraversal(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitTraversal) { + return visitor.visitTraversal(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class AttributeNameContext extends ParserRuleContext { + public IDENTIFIER(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.IDENTIFIER, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_attributeName; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAttributeName) { + listener.enterAttributeName(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAttributeName) { + listener.exitAttributeName(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAttributeName) { + return visitor.visitAttributeName(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class AttributeValueContext extends ParserRuleContext { + public value(): ValueContext { + return this.getRuleContext(0, ValueContext); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_attributeValue; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAttributeValue) { + listener.enterAttributeValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAttributeValue) { + listener.exitAttributeValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAttributeValue) { + return visitor.visitAttributeValue(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class FunctionNameContext extends ParserRuleContext { + public IDENTIFIER(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.IDENTIFIER, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_functionName; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterFunctionName) { + listener.enterFunctionName(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitFunctionName) { + listener.exitFunctionName(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitFunctionName) { + return visitor.visitFunctionName(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class OrTokenContext extends ParserRuleContext { + public OR(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.OR, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_orToken; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterOrToken) { + listener.enterOrToken(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitOrToken) { + listener.exitOrToken(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitOrToken) { + return visitor.visitOrToken(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class AndTokenContext extends ParserRuleContext { + public AND(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.AND, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_andToken; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAndToken) { + listener.enterAndToken(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAndToken) { + listener.exitAndToken(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAndToken) { + return visitor.visitAndToken(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class NotTokenContext extends ParserRuleContext { + public NOT(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.NOT, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_notToken; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterNotToken) { + listener.enterNotToken(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitNotToken) { + listener.exitNotToken(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitNotToken) { + return visitor.visitNotToken(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ColonTokenContext extends ParserRuleContext { + public COLON(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.COLON, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_colonToken; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterColonToken) { + listener.enterColonToken(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitColonToken) { + listener.exitColonToken(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitColonToken) { + return visitor.visitColonToken(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class LeftParenTokenContext extends ParserRuleContext { + public LPAREN(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.LPAREN, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_leftParenToken; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterLeftParenToken) { + listener.enterLeftParenToken(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitLeftParenToken) { + listener.exitLeftParenToken(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitLeftParenToken) { + return visitor.visitLeftParenToken(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class RightParenTokenContext extends ParserRuleContext { + public RPAREN(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.RPAREN, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_rightParenToken; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterRightParenToken) { + listener.enterRightParenToken(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitRightParenToken) { + listener.exitRightParenToken(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitRightParenToken) { + return visitor.visitRightParenToken(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class AfterExpressionWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_afterExpressionWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAfterExpressionWhitespace) { + listener.enterAfterExpressionWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAfterExpressionWhitespace) { + listener.exitAfterExpressionWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAfterExpressionWhitespace) { + return visitor.visitAfterExpressionWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class AfterLogicalOperatorWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_afterLogicalOperatorWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAfterLogicalOperatorWhitespace) { + listener.enterAfterLogicalOperatorWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAfterLogicalOperatorWhitespace) { + listener.exitAfterLogicalOperatorWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAfterLogicalOperatorWhitespace) { + return visitor.visitAfterLogicalOperatorWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ValueContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_value; + } + public copyFrom(ctx: ValueContext): void { + super.copyFrom(ctx); + } +} +export class QuotedStringValueContext extends ValueContext { + public QUOTED_STRING(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.QUOTED_STRING, 0); + } + constructor(ctx: ValueContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterQuotedStringValue) { + listener.enterQuotedStringValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitQuotedStringValue) { + listener.exitQuotedStringValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitQuotedStringValue) { + return visitor.visitQuotedStringValue(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteLeftQuotedStringValueContext extends ValueContext { + public INCOMPLETE_LEFT_QUOTED_STRING(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.INCOMPLETE_LEFT_QUOTED_STRING, 0); + } + constructor(ctx: ValueContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteLeftQuotedStringValue) { + listener.enterIncompleteLeftQuotedStringValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteLeftQuotedStringValue) { + listener.exitIncompleteLeftQuotedStringValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteLeftQuotedStringValue) { + return visitor.visitIncompleteLeftQuotedStringValue(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class IncompleteRightQuotedStringValueContext extends ValueContext { + public INCOMPLETE_RIGHT_QUOTED_STRING(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.INCOMPLETE_RIGHT_QUOTED_STRING, 0); + } + constructor(ctx: ValueContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterIncompleteRightQuotedStringValue) { + listener.enterIncompleteRightQuotedStringValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitIncompleteRightQuotedStringValue) { + listener.exitIncompleteRightQuotedStringValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitIncompleteRightQuotedStringValue) { + return visitor.visitIncompleteRightQuotedStringValue(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UnquotedStringValueContext extends ValueContext { + public IDENTIFIER(): TerminalNode { + return this.getToken(SelectionAutoCompleteParser.IDENTIFIER, 0); + } + constructor(ctx: ValueContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterUnquotedStringValue) { + listener.enterUnquotedStringValue(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitUnquotedStringValue) { + listener.exitUnquotedStringValue(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitUnquotedStringValue) { + return visitor.visitUnquotedStringValue(this); + } else { + return visitor.visitChildren(this); + } + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts new file mode 100644 index 0000000000000..54ecce5aeaef3 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts @@ -0,0 +1,501 @@ +// Generated from /Users/marcosalazar/code/dagster/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 by ANTLR 4.9.0-SNAPSHOT + +import {ParseTreeVisitor} from 'antlr4ts/tree/ParseTreeVisitor'; + +import { + AfterExpressionWhitespaceContext, + AfterLogicalOperatorWhitespaceContext, + AllExpressionContext, + AndExpressionContext, + AndTokenContext, + AttributeExpressionContext, + AttributeNameContext, + AttributeValueContext, + ColonTokenContext, + DownTraversalContext, + DownTraversalExpContext, + DownTraversalExpressionContext, + ExprContext, + ExpressionLessParenthesizedExprContext, + ExpressionlessFunctionExpressionContext, + ExpressionlessParenthesizedExpressionContext, + ExpressionlessParenthesizedExpressionWrapperContext, + FunctionCallExpressionContext, + FunctionNameContext, + IncompleteAndExpressionContext, + IncompleteAttributeExpressionMissingKeyContext, + IncompleteAttributeExpressionMissingValueContext, + IncompleteExpressionContext, + IncompleteExpressionsWrapperContext, + IncompleteLeftQuotedStringValueContext, + IncompleteNotExpressionContext, + IncompleteOrExpressionContext, + IncompleteRightQuotedStringValueContext, + IncompleteTraversalExpressionContext, + LeftParenTokenContext, + NotExpressionContext, + NotTokenContext, + OrExpressionContext, + OrTokenContext, + ParenthesizedExprContext, + ParenthesizedExpressionContext, + ParenthesizedExpressionWrapperContext, + QuotedStringValueContext, + RightParenTokenContext, + StartContext, + TraversalAllowedExprContext, + TraversalAllowedExpressionContext, + TraversalContext, + UnclosedExpressionlessFunctionExpressionContext, + UnclosedExpressionlessParenthesizedExpressionContext, + UnclosedFunctionExpressionContext, + UnclosedParenthesizedExpressionContext, + UnmatchedExpressionContinuationContext, + UnmatchedValueContext, + UnquotedStringValueContext, + UpAndDownTraversalExpressionContext, + UpTraversalContext, + UpTraversalExpContext, + UpTraversalExpressionContext, + ValueContext, +} from './SelectionAutoCompleteParser'; + +/** + * This interface defines a complete generic visitor for a parse tree produced + * by `SelectionAutoCompleteParser`. + * + * @param The return type of the visit operation. Use `void` for + * operations with no return type. + */ +export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor { + /** + * Visit a parse tree produced by the `DownTraversal` + * labeled alternative in `SelectionAutoCompleteParser.downTraversalExp`. + * @param ctx the parse tree + * @return the visitor result + */ + visitDownTraversal?: (ctx: DownTraversalContext) => Result; + + /** + * Visit a parse tree produced by the `AttributeExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAttributeExpression?: (ctx: AttributeExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `FunctionCallExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `ParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitParenthesizedExpressionWrapper?: (ctx: ParenthesizedExpressionWrapperContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteExpression` + * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteExpression?: (ctx: IncompleteExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UpTraversal` + * labeled alternative in `SelectionAutoCompleteParser.upTraversalExp`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUpTraversal?: (ctx: UpTraversalContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteAttributeExpressionMissingValue` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteAttributeExpressionMissingValue?: ( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) => Result; + + /** + * Visit a parse tree produced by the `ExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UnclosedExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedExpressionlessFunctionExpression?: ( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) => Result; + + /** + * Visit a parse tree produced by the `UnclosedFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UnclosedParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpressionlessParenthesizedExpressionWrapper?: ( + ctx: ExpressionlessParenthesizedExpressionWrapperContext, + ) => Result; + + /** + * Visit a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedExpressionlessParenthesizedExpression?: ( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) => Result; + + /** + * Visit a parse tree produced by the `IncompleteTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteTraversalExpression?: (ctx: IncompleteTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteAttributeExpressionMissingKey` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteAttributeExpressionMissingKey?: ( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) => Result; + + /** + * Visit a parse tree produced by the `ParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.parenthesizedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `TraversalAllowedExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitTraversalAllowedExpression?: (ctx: TraversalAllowedExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UpAndDownTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUpAndDownTraversalExpression?: (ctx: UpAndDownTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UpTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUpTraversalExpression?: (ctx: UpTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `DownTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitDownTraversalExpression?: (ctx: DownTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `NotExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitNotExpression?: (ctx: NotExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `AndExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAndExpression?: (ctx: AndExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `OrExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitOrExpression?: (ctx: OrExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteAndExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteAndExpression?: (ctx: IncompleteAndExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteOrExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteOrExpression?: (ctx: IncompleteOrExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteNotExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteNotExpression?: (ctx: IncompleteNotExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UnmatchedExpressionContinuation` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnmatchedExpressionContinuation?: (ctx: UnmatchedExpressionContinuationContext) => Result; + + /** + * Visit a parse tree produced by the `AllExpression` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAllExpression?: (ctx: AllExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UnmatchedValue` + * labeled alternative in `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnmatchedValue?: (ctx: UnmatchedValueContext) => Result; + + /** + * Visit a parse tree produced by the `ExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpressionlessParenthesizedExpression?: ( + ctx: ExpressionlessParenthesizedExpressionContext, + ) => Result; + + /** + * Visit a parse tree produced by the `QuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + * @return the visitor result + */ + visitQuotedStringValue?: (ctx: QuotedStringValueContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteLeftQuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteLeftQuotedStringValue?: (ctx: IncompleteLeftQuotedStringValueContext) => Result; + + /** + * Visit a parse tree produced by the `IncompleteRightQuotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteRightQuotedStringValue?: (ctx: IncompleteRightQuotedStringValueContext) => Result; + + /** + * Visit a parse tree produced by the `UnquotedStringValue` + * labeled alternative in `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnquotedStringValue?: (ctx: UnquotedStringValueContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.start`. + * @param ctx the parse tree + * @return the visitor result + */ + visitStart?: (ctx: StartContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpr?: (ctx: ExprContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitTraversalAllowedExpr?: (ctx: TraversalAllowedExprContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.parenthesizedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitParenthesizedExpr?: (ctx: ParenthesizedExprContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteExpressionsWrapper?: (ctx: IncompleteExpressionsWrapperContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpressionLessParenthesizedExpr?: (ctx: ExpressionLessParenthesizedExprContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.upTraversalExp`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUpTraversalExp?: (ctx: UpTraversalExpContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.downTraversalExp`. + * @param ctx the parse tree + * @return the visitor result + */ + visitDownTraversalExp?: (ctx: DownTraversalExpContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.traversal`. + * @param ctx the parse tree + * @return the visitor result + */ + visitTraversal?: (ctx: TraversalContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.attributeName`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAttributeName?: (ctx: AttributeNameContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.attributeValue`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAttributeValue?: (ctx: AttributeValueContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.functionName`. + * @param ctx the parse tree + * @return the visitor result + */ + visitFunctionName?: (ctx: FunctionNameContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.orToken`. + * @param ctx the parse tree + * @return the visitor result + */ + visitOrToken?: (ctx: OrTokenContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.andToken`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAndToken?: (ctx: AndTokenContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.notToken`. + * @param ctx the parse tree + * @return the visitor result + */ + visitNotToken?: (ctx: NotTokenContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.colonToken`. + * @param ctx the parse tree + * @return the visitor result + */ + visitColonToken?: (ctx: ColonTokenContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.leftParenToken`. + * @param ctx the parse tree + * @return the visitor result + */ + visitLeftParenToken?: (ctx: LeftParenTokenContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.rightParenToken`. + * @param ctx the parse tree + * @return the visitor result + */ + visitRightParenToken?: (ctx: RightParenTokenContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.afterExpressionWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAfterExpressionWhitespace?: (ctx: AfterExpressionWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.afterLogicalOperatorWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAfterLogicalOperatorWhitespace?: (ctx: AfterLogicalOperatorWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.value`. + * @param ctx the parse tree + * @return the visitor result + */ + visitValue?: (ctx: ValueContext) => Result; +} From fb760ac5ce62c90125e904badb6ba00d7673b698 Mon Sep 17 00:00:00 2001 From: Marco Salazar Date: Thu, 5 Dec 2024 10:31:25 -0500 Subject: [PATCH 02/13] mo --- .../input/AssetSelectionLinter.ts | 22 +- .../src/selection/SelectionAutoComplete.g4 | 208 +- .../src/selection/SelectionAutoComplete.ts | 194 +- .../SelectionAutoCompleteHighlighter.ts | 4 +- .../selection/SelectionAutoCompleteVisitor.ts | 475 + .../__tests__/SelectionAutoComplete.test.ts | 63 +- .../generated/SelectionAutoComplete.interp | 18 +- .../SelectionAutoCompleteListener.ts | 442 +- .../generated/SelectionAutoCompleteParser.ts | 1261 +- .../generated/SelectionAutoCompleteVisitor.ts | 272 +- .../graphiql/graphiql.min.js | 202268 ++++++++------- .../dagster-pyspark/dagster_pyspark/types.py | 4 +- 12 files changed, 116214 insertions(+), 89017 deletions(-) create mode 100644 js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteVisitor.ts diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts index 45b56fe1e08c2..57122566a8bae 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/input/AssetSelectionLinter.ts @@ -8,22 +8,18 @@ import {AssetSelectionParser} from '../generated/AssetSelectionParser'; export const lintAssetSelection = (text: string) => { const errorListener = new AssetSelectionSyntaxErrorListener(); - try { - const inputStream = CharStreams.fromString(text); - const lexer = new AssetSelectionLexer(inputStream); + const inputStream = CharStreams.fromString(text); + const lexer = new AssetSelectionLexer(inputStream); - lexer.removeErrorListeners(); - lexer.addErrorListener(errorListener); + lexer.removeErrorListeners(); + lexer.addErrorListener(errorListener); - const tokens = new CommonTokenStream(lexer); - const parser = new AssetSelectionParser(tokens); + const tokens = new CommonTokenStream(lexer); + const parser = new AssetSelectionParser(tokens); - parser.removeErrorListeners(); // Remove default console error listener - parser.addErrorListener(errorListener); + parser.removeErrorListeners(); // Remove default console error listener + parser.addErrorListener(errorListener); - // Attempt to parse the input - parser.start(); // Assuming 'start' is the entry point of your grammar - } catch {} // Map syntax errors to CodeMirror's lint format const lintErrors = errorListener.errors.map((error) => ({ message: error.message.replace(', ', ''), @@ -32,5 +28,7 @@ export const lintAssetSelection = (text: string) => { to: CodeMirror.Pos(error.line, text.length), })); + console.log({lintErrors}); + return lintErrors; }; diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 index 81553e238c0a2..e1913d1830553 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.g4 @@ -1,147 +1,127 @@ grammar SelectionAutoComplete; -// Root rule for parsing expressions start: expr EOF; -// Root expression rule -expr - : traversalAllowedExpr afterExpressionWhitespace # TraversalAllowedExpression - | upTraversalExp traversalAllowedExpr downTraversalExp afterExpressionWhitespace # UpAndDownTraversalExpression - | upTraversalExp traversalAllowedExpr afterExpressionWhitespace # UpTraversalExpression - | traversalAllowedExpr downTraversalExp afterExpressionWhitespace # DownTraversalExpression - | notToken afterLogicalOperatorWhitespace expr afterExpressionWhitespace # NotExpression - | expr afterExpressionWhitespace andToken afterLogicalOperatorWhitespace expr afterExpressionWhitespace # AndExpression - | expr afterExpressionWhitespace orToken afterLogicalOperatorWhitespace expr afterExpressionWhitespace # OrExpression - | expr afterExpressionWhitespace andToken afterLogicalOperatorWhitespace # IncompleteAndExpression - | expr afterExpressionWhitespace orToken afterLogicalOperatorWhitespace # IncompleteOrExpression - | notToken afterLogicalOperatorWhitespace # IncompleteNotExpression - | expr afterExpressionWhitespace value afterLogicalOperatorWhitespace # UnmatchedExpressionContinuation - | STAR afterExpressionWhitespace # AllExpression - | value afterExpressionWhitespace # UnmatchedValue - ; - +/* + * Apply a specific whitespace parser rule (e.g., afterLogicalOperatorWhitespace, + * afterExpressionWhitespace) after every leaf node. This strategy prevents multiple parser rules + * from conflicting over the same whitespace. Add more whitespace types to adjust autocomplete + * boundary behavior within and after tokens. + */ +expr: + traversalAllowedExpr # TraversalAllowedExpression + | upTraversalExpr traversalAllowedExpr downTraversalExpr # UpAndDownTraversalExpression + | upTraversalExpr traversalAllowedExpr # UpTraversalExpression + | traversalAllowedExpr downTraversalExpr # DownTraversalExpression + | notToken postNotOperatorWhitespace expr # NotExpression + | expr andToken postLogicalOperatorWhitespace expr # AndExpression + | expr orToken postLogicalOperatorWhitespace expr # OrExpression + | expr andToken postLogicalOperatorWhitespace # IncompleteAndExpression + | expr orToken postLogicalOperatorWhitespace # IncompleteOrExpression + | notToken postNotOperatorWhitespace # IncompleteNotExpression + | expr value postLogicalOperatorWhitespace # UnmatchedExpressionContinuation + | STAR postExpressionWhitespace # AllExpression + | value postExpressionWhitespace # UnmatchedValue; // Allowed expressions within traversal contexts -traversalAllowedExpr - : attributeName colonToken attributeValue # AttributeExpression - | functionName parenthesizedExpr # FunctionCallExpression - | parenthesizedExpr # ParenthesizedExpressionWrapper - | incompleteExpressionsWrapper # IncompleteExpression - ; - - -parenthesizedExpr - : leftParenToken expr rightParenToken # ParenthesizedExpression - ; - -// Incomplete expressions wrapper -incompleteExpressionsWrapper - : attributeName colonToken # IncompleteAttributeExpressionMissingValue - | functionName expressionLessParenthesizedExpr # ExpressionlessFunctionExpression - | functionName leftParenToken # UnclosedExpressionlessFunctionExpression - | functionName leftParenToken expr # UnclosedFunctionExpression - | leftParenToken expr # UnclosedParenthesizedExpression - | expressionLessParenthesizedExpr # ExpressionlessParenthesizedExpressionWrapper - | leftParenToken # UnclosedExpressionlessParenthesizedExpression - | PLUS+ # IncompleteTraversalExpression - | colonToken attributeValue # IncompleteAttributeExpressionMissingKey - ; - -expressionLessParenthesizedExpr - : leftParenToken rightParenToken # ExpressionlessParenthesizedExpression - ; - -upTraversalExp - : traversal # UpTraversal - ; - -downTraversalExp - : traversal # DownTraversal - ; - -traversal - : STAR - | PLUS+ - ; +traversalAllowedExpr: + attributeName colonToken attributeValue postAttributeValueWhitespace # AttributeExpression + | functionName parenthesizedExpr # FunctionCallExpression + | parenthesizedExpr # TraversalAllowedParenthesizedExpression + | incompleteExpr # IncompleteExpression; + +parenthesizedExpr: + leftParenToken postLogicalOperatorWhitespace expr rightParenToken postExpressionWhitespace # + ParenthesizedExpression; + +incompleteExpr: + attributeName colonToken attributeValueWhitespace # IncompleteAttributeExpressionMissingValue + | functionName expressionLessParenthesizedExpr # ExpressionlessFunctionExpression + | functionName leftParenToken postLogicalOperatorWhitespace # + UnclosedExpressionlessFunctionExpression + | functionName leftParenToken expr # UnclosedFunctionExpression + | leftParenToken postLogicalOperatorWhitespace expr # UnclosedParenthesizedExpression + | expressionLessParenthesizedExpr # ExpressionlessParenthesizedExpressionWrapper + | leftParenToken postLogicalOperatorWhitespace # UnclosedExpressionlessParenthesizedExpression + | PLUS+ postNeighborTraversalWhitespace # IncompletePlusTraversalExpression + | colonToken attributeValue postExpressionWhitespace # IncompleteAttributeExpressionMissingKey; + +expressionLessParenthesizedExpr: + leftParenToken postLogicalOperatorWhitespace rightParenToken postExpressionWhitespace # + ExpressionlessParenthesizedExpression; + +upTraversalExpr: + traversal postUpwardTraversalWhitespace # UpTraversal; + +downTraversalExpr: + traversal postDownwardTraversalWhitespace # DownTraversal; + +traversal: STAR | PLUS+; // Attribute and function names (to be validated externally) -attributeName - : IDENTIFIER - ; +attributeName: IDENTIFIER; + +attributeValue: value; + +functionName: IDENTIFIER; + +orToken: OR; +andToken: AND; -attributeValue - : value - ; +notToken: NOT; -functionName - : IDENTIFIER - ; +colonToken: COLON; -orToken - : OR - ; +leftParenToken: LPAREN; -andToken - : AND - ; +rightParenToken: RPAREN; -notToken - : NOT - ; +attributeValueWhitespace: WS*; -colonToken - : COLON - ; +postAttributeValueWhitespace: WS*; -leftParenToken - : LPAREN - ; +postExpressionWhitespace: WS*; -rightParenToken - : RPAREN - ; +postNotOperatorWhitespace: WS*; -afterExpressionWhitespace - : WS* - ; +postLogicalOperatorWhitespace: WS*; -afterLogicalOperatorWhitespace - : WS* - ; - +postNeighborTraversalWhitespace: WS*; + +postUpwardTraversalWhitespace: WS*; + +postDownwardTraversalWhitespace: WS*; // Value can be a quoted string, unquoted string, or identifier -value - : QUOTED_STRING # QuotedStringValue - | INCOMPLETE_LEFT_QUOTED_STRING # IncompleteLeftQuotedStringValue - | INCOMPLETE_RIGHT_QUOTED_STRING # IncompleteRightQuotedStringValue - | IDENTIFIER # UnquotedStringValue - ; +value: + QUOTED_STRING # QuotedStringValue + | INCOMPLETE_LEFT_QUOTED_STRING # IncompleteLeftQuotedStringValue + | INCOMPLETE_RIGHT_QUOTED_STRING # IncompleteRightQuotedStringValue + | IDENTIFIER # UnquotedStringValue; // Tokens for operators and keywords -AND : 'and'; -OR : 'or'; -NOT : 'not'; +AND: 'and'; +OR: 'or'; +NOT: 'not'; -STAR : '*'; -PLUS : '+'; +STAR: '*'; +PLUS: '+'; -COLON : ':'; +COLON: ':'; -LPAREN : '('; -RPAREN : ')'; +LPAREN: '('; +RPAREN: ')'; -EQUAL : '='; +EQUAL: '='; // Tokens for strings -QUOTED_STRING : '"' (~["\\\r\n])* '"' ; -INCOMPLETE_LEFT_QUOTED_STRING: '"' (~["\\\r\n():])* ; -INCOMPLETE_RIGHT_QUOTED_STRING: (~["\\\r\n:()])* '"' ; +QUOTED_STRING: '"' (~["\\\r\n])* '"'; +INCOMPLETE_LEFT_QUOTED_STRING: '"' (~["\\\r\n():])*; +INCOMPLETE_RIGHT_QUOTED_STRING: (~["\\\r\n:()])* '"'; // Identifiers (attributes and functions) -IDENTIFIER : [a-zA-Z_][a-zA-Z0-9_]*; - +IDENTIFIER: [a-zA-Z_][a-zA-Z0-9_]*; // Whitespace -WS : [ \t\r\n]+; +WS: [ \t\r\n]+; \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts index 9b99867ec01df..8404899a8988d 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoComplete.ts @@ -10,17 +10,24 @@ import { removeQuotesFromString, } from './SelectionAutoCompleteUtil'; import { - AfterExpressionWhitespaceContext, - AfterLogicalOperatorWhitespaceContext, AllExpressionContext, AndTokenContext, AttributeNameContext, AttributeValueContext, ColonTokenContext, + DownTraversalContext, FunctionNameContext, + IncompleteAttributeExpressionMissingValueContext, + IncompletePlusTraversalExpressionContext, LeftParenTokenContext, OrTokenContext, ParenthesizedExpressionContext, + PostAttributeValueWhitespaceContext, + PostDownwardTraversalWhitespaceContext, + PostLogicalOperatorWhitespaceContext, + PostNeighborTraversalWhitespaceContext, + PostNotOperatorWhitespaceContext, + PostUpwardTraversalWhitespaceContext, UnmatchedValueContext, UpTraversalContext, } from './generated/SelectionAutoCompleteParser'; @@ -124,13 +131,21 @@ export class SelectionAutoCompleteVisitor } const c = node.getChild(i) as any; if (c.start && c.stop) { - const isWhiteSpace = c.constructor.name.endsWith('WhitespaceContext'); + const isWhitespace = c.constructor.name.endsWith('WhitespaceContext'); if ( !this.nodeIncludesCursor(c) && - (!isWhiteSpace || c.start.startIndex !== this.cursorIndex) + (!isWhitespace || c.start.startIndex !== this.cursorIndex) ) { continue; } + const nextChild = node.childCount - 1 > i ? (node.getChild(i + 1) as any) : null; + if ( + !this.nodeIncludesCursor(c, 0) && + nextChild?.constructor.name.endsWith('WhitespaceContext') + ) { + // Let the whitespace handle the suggestion + continue; + } } if (DEBUG) { console.log('visiting child', c.constructor.name, c.text); @@ -143,11 +158,14 @@ export class SelectionAutoCompleteVisitor protected defaultResult() {} - private nodeIncludesCursor(ctx: Pick): boolean { + private nodeIncludesCursor( + ctx: Pick, + modifier: number = -1, + ): boolean { const start = ctx.start.startIndex; const stop = ctx.stop ? ctx.stop.stopIndex : ctx.start.startIndex; - return Math.max(0, this.cursorIndex - 1) >= start && this.cursorIndex - 1 <= stop; + return Math.max(0, this.cursorIndex + modifier) >= start && this.cursorIndex + modifier <= stop; } private addAttributeResults(value: string, textCallback: TextCallback = DEFAULT_TEXT_CALLBACK) { @@ -182,8 +200,9 @@ export class SelectionAutoCompleteVisitor public addUnmatchedValueResults( _value: string, textCallback: TextCallback = DEFAULT_TEXT_CALLBACK, - options: {excludeNot?: boolean} = {}, + options: {excludeNot?: boolean; excludeStar?: boolean; excludePlus?: boolean} = {}, ) { + console.log('addUnmatchedValueResults', new Error()); const value = _value.trim(); if (value) { const substringMatchDisplayText = `${this.nameBase}_substring:${removeQuotesFromString( @@ -213,11 +232,13 @@ export class SelectionAutoCompleteVisitor this.list.push({text: textCallback('not '), displayText: 'not'}); } if (value === '') { - this.list.push( - {text: textCallback('*'), displayText: '*'}, - {text: textCallback('+'), displayText: '+'}, - {text: textCallback('()'), displayText: '('}, - ); + if (!options.excludeStar) { + this.list.push({text: textCallback('*'), displayText: '*'}); + } + if (!options.excludePlus) { + this.list.push({text: textCallback('+'), displayText: '+'}); + } + this.list.push({text: textCallback('()'), displayText: '('}); } } @@ -241,13 +262,22 @@ export class SelectionAutoCompleteVisitor }); } - private addAfterExpressionResults(ctx: ParserRuleContext) { - this.list.push( - {text: ' and ', displayText: 'and'}, - {text: ' or ', displayText: 'or'}, - {text: '*', displayText: '*'}, - {text: '+', displayText: '+'}, - ); + private addAfterExpressionResults( + ctx: ParserRuleContext, + options: { + excludeStar?: boolean; + excludePlus?: boolean; + } = {}, + ) { + console.log('addAfterExpressionResults', new Error()); + this.list.push({text: ' and ', displayText: 'and'}, {text: ' or ', displayText: 'or'}); + + if (!options.excludeStar) { + this.list.push({text: '*', displayText: '*'}); + } + if (!options.excludePlus) { + this.list.push({text: '+', displayText: '+'}); + } if (isInsideExpressionlessParenthesizedExpression(ctx)) { this.list.push({text: ')', displayText: ')'}); @@ -255,11 +285,18 @@ export class SelectionAutoCompleteVisitor } visitAllExpression(ctx: AllExpressionContext) { - this.startReplacementIndex = this.cursorIndex; - this.stopReplacementIndex = this.cursorIndex; - this.addUnmatchedValueResults(''); - if (isInsideExpressionlessParenthesizedExpression(ctx)) { - this.list.push({text: ')', displayText: ')'}); + if (this.nodeIncludesCursor(ctx.postExpressionWhitespace())) { + this.visit(ctx.postExpressionWhitespace()); + } else { + this.startReplacementIndex = this.cursorIndex; + this.stopReplacementIndex = this.cursorIndex; + this.addUnmatchedValueResults('', DEFAULT_TEXT_CALLBACK, { + excludeStar: true, + excludePlus: true, + }); + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')', displayText: ')'}); + } } } @@ -267,10 +304,10 @@ export class SelectionAutoCompleteVisitor if (ctx.text.includes('+')) { this.list.push({text: '+', displayText: '+'}); } - this.list.push({text: '(', displayText: '('}); + this.list.push({text: '()', displayText: '('}); } - visitDownTraversal(ctx: UpTraversalContext) { + visitDownTraversal(ctx: DownTraversalContext) { this.list.push({text: ' and ', displayText: 'and'}); this.list.push({text: ' or ', displayText: 'or'}); if (ctx.text.includes('+')) { @@ -286,7 +323,7 @@ export class SelectionAutoCompleteVisitor // Move the cursor to the right and visit that expression. this.cursorIndex += 1; } - this.visit(ctx.expr()); + this.visitChildren(ctx); } visitFunctionName(ctx: FunctionNameContext) { @@ -315,40 +352,32 @@ export class SelectionAutoCompleteVisitor visitColonToken(ctx: ColonTokenContext) { if (this.nodeIncludesCursor(ctx)) { - let attributeName = ''; + let attributeName: any; let valueNode: ParserRuleContext | null = null; const parentChildren = ctx.parent?.children ?? []; if (parentChildren[0]?.constructor.name === 'AttributeNameContext') { - attributeName = parentChildren[0].text; + attributeName = parentChildren[0]; } if (parentChildren[1]?.constructor.name === 'AttributeValueContext') { valueNode = parentChildren[1] as any; } else if (parentChildren[2]?.constructor.name === 'AttributeValueContext') { valueNode = parentChildren[2] as any; } - if (attributeName) { - this.startReplacementIndex = ctx.start.startIndex + 1; - this.stopReplacementIndex = this.startReplacementIndex; - if (valueNode?.stop) { - this.stopReplacementIndex = valueNode.stop?.stopIndex + 1; - } + if (attributeName?.stop && this.cursorIndex >= attributeName.stop?.stopIndex) { this.addAttributeValueResults(attributeName, getValue(valueNode)); + } else { + this.startReplacementIndex = ctx.start.startIndex - 1; + this.stopReplacementIndex = this.startReplacementIndex; + this.addAttributeResults(attributeName); } } } visitAttributeName(ctx: AttributeNameContext) { - if (this.nodeIncludesCursor(ctx)) { - if (this.line[this.cursorIndex] === ':') { - // Increase cursor index to make sure the colon character is visited. - this.cursorIndex += 1; - } else { - this.startReplacementIndex = ctx.start.startIndex; - this.stopReplacementIndex = ctx.stop!.stopIndex + 2; - this.addAttributeResults(ctx.text); - } - } + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 2; + this.addAttributeResults(ctx.text); } visitOrToken(ctx: OrTokenContext) { @@ -379,28 +408,91 @@ export class SelectionAutoCompleteVisitor } } - // This is visited even if the whitespace has length 0. - visitAfterExpressionWhitespace(ctx: AfterExpressionWhitespaceContext) { + visitIncompletePlusTraversalExpression(ctx: IncompletePlusTraversalExpressionContext) { + if ( + this.nodeIncludesCursor(ctx.postNeighborTraversalWhitespace()) && + ctx.postNeighborTraversalWhitespace().text.length + ) { + return this.visit(ctx.postNeighborTraversalWhitespace()); + } + this.addUnmatchedValueResults('', DEFAULT_TEXT_CALLBACK, { + excludeStar: true, + excludeNot: true, + }); + } + + visitIncompleteAttributeExpressionMissingValue( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) { + if (this.nodeIncludesCursor(ctx.attributeName())) { + this.visit(ctx.attributeName()); + } else { + this.startReplacementIndex = ctx.attributeValueWhitespace().start.startIndex; + this.stopReplacementIndex = this.startReplacementIndex; + this.addAttributeValueResults(ctx.attributeName().text, ''); + } + } + + visitPostNotOperatorWhitespace(_ctx: PostNotOperatorWhitespaceContext) { + this.addUnmatchedValueResults('', DEFAULT_TEXT_CALLBACK, { + excludeNot: true, + }); + } + + visitPostNeighborTraversalWhitespace(ctx: PostNeighborTraversalWhitespaceContext) { + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex; + this.addUnmatchedValueResults('', DEFAULT_TEXT_CALLBACK, { + excludeStar: true, + }); + } + + visitPostUpwardTraversalWhitespace(ctx: PostUpwardTraversalWhitespaceContext) { + this.addUnmatchedValueResults('', DEFAULT_TEXT_CALLBACK, { + excludeStar: true, + excludePlus: ctx.parent?.children?.[0]?.text.includes('+'), + }); + } + + visitPostDownwardTraversalWhitespace(ctx: PostDownwardTraversalWhitespaceContext) { + this.addAfterExpressionResults(ctx, { + excludeStar: true, + excludePlus: ctx.parent?.children?.[0]?.text.includes('+'), + }); + } + + visitPostExpressionWhitespace(ctx: ParserRuleContext) { if (!this.list.length) { - // Check if anything before us already made suggestions - // Since we get called even if the previous token handled it this.addAfterExpressionResults(ctx); } } // This is visited even if the whitespace has length 0. - visitAfterLogicalOperatorWhitespace(ctx: AfterLogicalOperatorWhitespaceContext) { + visitPostLogicalOperatorWhitespace(ctx: PostLogicalOperatorWhitespaceContext) { // Check if anything before us already made suggestions // Since we get called even if the previous token handled it if (!this.list.length) { const isAfterNot = this.line.slice(0, this.cursorIndex).trim().toLowerCase().endsWith('not'); - const needsWhitespace = this.cursorIndex === ctx.start.startIndex; + + const isAfterLeftParen = this.line[this.cursorIndex - 1] === '('; + + // If the cursor is at the start then we need a space before... + const needsWhitespace = !isAfterLeftParen && this.cursorIndex === ctx.start.startIndex; this.addUnmatchedValueResults('', (text) => `${needsWhitespace ? ' ' : ''}${text}`, { excludeNot: isAfterNot, }); } } + visitPostAttributeValueWhitespace(ctx: PostAttributeValueWhitespaceContext) { + if (this.cursorIndex === ctx.start.startIndex + 1) { + this.cursorIndex -= 1; + ctx.parent!.accept(this); + } else { + this.visitPostExpressionWhitespace(ctx); + } + } + visitLeftParenToken(_ctx: LeftParenTokenContext) { this.addUnmatchedValueResults(''); } diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts index de562dd93771a..4d9601757ca72 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts @@ -98,7 +98,7 @@ export class SyntaxHighlightingVisitor } visitAllExpression(ctx: AllExpressionContext) { - this.addClass(ctx, 'value'); + this.addClass(ctx, 'expression'); this.visitChildren(ctx); } visitIncompleteLeftQuotedStringValue(ctx: ParserRuleContext) { @@ -218,7 +218,7 @@ export const SelectionAutoCompleteInputCSS = css` color: ${Colors.textDefault()}; } - .CodeMirror-line .selection:not(.expression), + .CodeMirror-line .selection:not(.expression):not(.value), .CodeMirror-lint-mark-error { background: unset; text-decoration-line: underline; diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteVisitor.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteVisitor.ts new file mode 100644 index 0000000000000..893ead35f7be9 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteVisitor.ts @@ -0,0 +1,475 @@ +// AutoCompleteSuggestionVisitor.ts + +import {ParserRuleContext} from 'antlr4ts'; +import {AbstractParseTreeVisitor} from 'antlr4ts/tree/AbstractParseTreeVisitor'; +import CodeMirror from 'codemirror'; + +import { + AllExpressionContext, + AndExpressionContext, + AttributeExpressionContext, + AttributeNameContext, + DownTraversalExpressionContext, + ExpressionlessFunctionExpressionContext, + ExpressionlessParenthesizedExpressionContext, + FunctionCallExpressionContext, + FunctionNameContext, + IncompleteAndExpressionContext, + IncompleteAttributeExpressionContext, + IncompleteNotExpressionContext, + IncompleteOrExpressionContext, + IncompleteTraversalExpressionContext, + NotExpressionContext, + OrExpressionContext, + ParenthesizedExpressionContext, + QuotedStringValueContext, + StartContext, + TraversalContext, + UnclosedExpressionlessFunctionExpressionContext, + UnclosedExpressionlessParenthesizedExpressionContext, + UnmatchedValueContext, + UnquotedStringValueContext, + UpAndDownTraversalExpressionContext, + UpTraversalExpressionContext, +} from './generated/SelectionAutoCompleteParser'; +import {SelectionAutoCompleteVisitor as _SelectionAutoCompleteVisitor} from './generated/SelectionAutoCompleteVisitor'; + +type Suggestion = {text: string; displayText?: string}; +type TextCallback = (value: string) => string; +const DEFAULT_TEXT_CALLBACK = (value: string) => value; + +export class SelectionAutoCompleteVisitor + extends AbstractParseTreeVisitor + implements _SelectionAutoCompleteVisitor +{ + private cm: CodeMirror.Editor; + private cursorIndex: number; + private line: string; + private attributesMap: Record; + private functions: string[]; + private nameBase: string; + private attributesWithNameBase: string[]; + private allAttributes: {key: string; value: string}[]; + public list: Suggestion[] = []; + public startReplacementIndex: number = 0; + public stopReplacementIndex: number = 0; + private currentNode: ParserRuleContext | null = null; + + constructor( + cm: CodeMirror.Editor, + attributesMap: Record, + functions: string[], + nameBase: string, + ) { + super(); + this.cm = cm; + const cursor = cm.getCursor(); + this.cursorIndex = Math.max(0, cm.indexFromPos(cursor) - 1); + this.line = cm.getLine(0); + this.attributesMap = attributesMap; + this.functions = functions; + this.nameBase = nameBase; + this.attributesWithNameBase = [ + `${this.nameBase}_substring`, + this.nameBase, + ...Object.keys(attributesMap).filter((name) => name !== this.nameBase), + ]; + this.allAttributes = Object.keys(attributesMap).flatMap((key) => { + return attributesMap[key]?.map((value) => ({key, value})) ?? []; + }); + } + + protected defaultResult() {} + + private nodeIncludesCursor(ctx: ParserRuleContext): boolean { + const start = ctx.start.startIndex; + const stop = ctx.stop ? ctx.stop.stopIndex : ctx.start.startIndex; + return this.cursorIndex >= start && this.cursorIndex <= stop; + } + + private addAttributeResults(value: string, textCallback: TextCallback = DEFAULT_TEXT_CALLBACK) { + this.list.push( + ...this.attributesWithNameBase + .filter((attr) => attr.includes(value)) + .map((val) => { + const suggestionValue = `${val}:`; + return {text: textCallback(suggestionValue), displayText: suggestionValue}; + }), + ); + } + + private addFunctionResults(value: string, textCallback: TextCallback = DEFAULT_TEXT_CALLBACK) { + this.list.push( + ...this.functions + .filter((fn) => fn.includes(value)) + .map((val) => { + const suggestionValue = `${val}()`; + return { + text: textCallback(suggestionValue), + displayText: suggestionValue, + }; + }), + ); + } + + private addUnmatchedValueResults( + value: string, + textCallback: TextCallback = DEFAULT_TEXT_CALLBACK, + ) { + if (value) { + const substringMatchDisplayText = `${this.nameBase}_substring:${removeQuotesFromString( + value, + )}`; + const substringMatchText = `${this.nameBase}_substring:"${removeQuotesFromString(value)}"`; + this.list.push({ + text: textCallback(substringMatchText), + displayText: substringMatchDisplayText, + }); + this.allAttributes.forEach((attribute) => { + if (attribute.value.includes(value)) { + this.list.push({ + text: textCallback(`${attribute.key}:"${attribute.value}"`), + displayText: `${attribute.key}:${attribute.value}`, + }); + } + }); + } + this.addAttributeResults(value, textCallback); + this.addFunctionResults(value, textCallback); + + if (value === '') { + this.list.push({text: 'not ', displayText: 'not'}); + this.list.push({text: '*'}, {text: '+'}, {text: '()', displayText: '('}); + } + } + + private addAttributeValueResults( + attributeKey: string, + value: string, + textCallback: TextCallback = DEFAULT_TEXT_CALLBACK, + ) { + let possibleValues = this.attributesMap[attributeKey] ?? []; + if (attributeKey === `${this.nameBase}_substring`) { + possibleValues = this.attributesMap[this.nameBase]!; + } + possibleValues.forEach((attributeValue) => { + if (attributeValue.includes(removeQuotesFromString(value))) { + this.list.push({ + text: textCallback(`"${attributeValue}"`), + displayText: attributeValue, + }); + } + }); + } + + // Visit methods for each node type + visitStart(ctx: StartContext) { + if (this.nodeIncludesCursor(ctx)) { + this.currentNode = ctx; + this.startReplacementIndex = ctx.start.startIndex; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.visit(ctx.expr()); + } + } + + visitAllExpression(ctx: AllExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')'}); + } + // No need to visit children + return; + } + } + + visitIncompleteTraversalExpression(ctx: IncompleteTraversalExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + // Handle suggestions for incomplete traversal + // No specific suggestions in original logic + return; + } + } + + visitTraversal(ctx: TraversalContext) { + // Traversal is handled within other contexts + } + + visitDownTraversalExpression(ctx: DownTraversalExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + const traversal = ctx.traversal(); + const expr = ctx.traversalAllowedExpr(); + + if (this.nodeIncludesCursor(traversal)) { + // Cursor is within traversal operator + // No specific suggestions + return; + } else if (this.nodeIncludesCursor(expr)) { + this.visit(expr); + return; + } else { + // After traversal operator + this.startReplacementIndex = this.cursorIndex; + this.stopReplacementIndex = this.cursorIndex; + this.list.push({text: ' and ', displayText: 'and'}); + this.list.push({text: ' or ', displayText: 'or'}); + if (ctx.traversal().text.includes('+')) { + this.list.push({text: '+'}); + } + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')'}); + } + return; + } + } + } + + visitUpTraversalExpression(ctx: UpTraversalExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + const traversal = ctx.traversal(); + const expr = ctx.traversalAllowedExpr(); + + if (this.nodeIncludesCursor(traversal)) { + // Cursor is within traversal operator + // No specific suggestions + return; + } else if (this.nodeIncludesCursor(expr)) { + this.visit(expr); + return; + } else { + // After traversal operator + this.startReplacementIndex = this.cursorIndex; + this.stopReplacementIndex = this.cursorIndex; + this.list.push({text: '(', displayText: '('}); + return; + } + } + } + + visitUpAndDownTraversalExpression(ctx: UpAndDownTraversalExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + // Similar handling as up and down traversal expressions + this.visit(ctx.traversalAllowedExpr()); + return; + } + } + + visitAttributeName(ctx: AttributeNameContext) { + if (this.nodeIncludesCursor(ctx)) { + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.addAttributeResults(ctx.text); + } + } + + visitIncompleteAttributeExpression(ctx: IncompleteAttributeExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + const keyNode = ctx.attributeName(); + const key = keyNode.text; + + this.startReplacementIndex = keyNode.stop!.stopIndex + 1; // After colon + this.stopReplacementIndex = keyNode.stop!.stopIndex + 1; + this.addAttributeValueResults(key, ''); + return; + } + } + + visitParenthesizedExpression(ctx: ParenthesizedExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + if (this.cursorIndex === ctx.stop!.stopIndex) { + this.startReplacementIndex = ctx.stop!.stopIndex + 1; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.list.push({text: ' and ', displayText: 'and'}, {text: ' or ', displayText: 'or'}); + if (this.line[this.stopReplacementIndex] !== '*') { + this.list.push({text: '+'}); + if (this.line[this.startReplacementIndex] !== '+') { + this.list.push({text: '*'}); + } + } + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')'}); + } + return; + } + this.visit(ctx.expr()); + } + } + + visitIncompleteNotExpression(ctx: IncompleteNotExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.startReplacementIndex = this.cursorIndex + 1; + this.stopReplacementIndex = this.cursorIndex + 1; + let needsSpaceBefore = false; + if (this.line[this.cursorIndex] !== ' ') { + needsSpaceBefore = true; + } + this.addUnmatchedValueResults('', (text) => `${needsSpaceBefore ? ' ' : ''}${text}`); + return; + } + } + + visitIncompleteAndExpression(ctx: IncompleteAndExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.startReplacementIndex = this.cursorIndex + 1; + this.stopReplacementIndex = this.cursorIndex + 1; + let needsSpaceBefore = false; + if (this.line[this.cursorIndex] !== ' ') { + needsSpaceBefore = true; + } + this.addUnmatchedValueResults('', (text) => `${needsSpaceBefore ? ' ' : ''}${text}`); + return; + } + } + + visitIncompleteOrExpression(ctx: IncompleteOrExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.startReplacementIndex = this.cursorIndex + 1; + this.stopReplacementIndex = this.cursorIndex + 1; + let needsSpaceBefore = false; + if (this.line[this.cursorIndex] !== ' ') { + needsSpaceBefore = true; + } + this.addUnmatchedValueResults('', (text) => `${needsSpaceBefore ? ' ' : ''}${text}`); + return; + } + } + + visitFunctionName(ctx: FunctionNameContext) { + if (this.nodeIncludesCursor(ctx)) { + this.addFunctionResults(ctx.text); + } + } + + visitAttributeExpression(ctx: AttributeExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + const keyNode = ctx.attributeName(); + const valueNode = ctx.value(); + const attributeKey = keyNode.text; + const nodeValue = valueNode.text; + + this.startReplacementIndex = valueNode.start.startIndex; + this.stopReplacementIndex = valueNode.stop!.stopIndex + 1; + this.addAttributeValueResults(attributeKey, nodeValue); + return; + } + } + + visitFunctionCallExpression(ctx: FunctionCallExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + if (this.cursorIndex === ctx.stop!.stopIndex) { + this.startReplacementIndex = ctx.stop!.stopIndex + 1; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.list.push({text: ' and ', displayText: 'and'}, {text: ' or ', displayText: 'or'}); + if (this.line[this.stopReplacementIndex] !== '*') { + this.list.push({text: '+'}); + if (this.line[this.startReplacementIndex] !== '+') { + this.list.push({text: '*'}); + } + } + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')'}); + } + return; + } + this.visit(ctx.functionAllowedExpr()); + } + } + + visitQuotedStringValue(ctx: QuotedStringValueContext) { + if (this.nodeIncludesCursor(ctx)) { + if (ctx.parent instanceof UnmatchedValueContext) { + this.addUnmatchedValueResults(ctx.text); + return; + } + if (this.cursorIndex === ctx.stop!.stopIndex) { + this.startReplacementIndex = ctx.stop!.stopIndex + 1; + this.stopReplacementIndex = ctx.stop!.stopIndex + 1; + this.list.push({text: ' and ', displayText: 'and'}, {text: ' or ', displayText: 'or'}); + if (this.line[this.stopReplacementIndex] !== '*') { + this.list.push({text: '+'}); + if (this.line[this.startReplacementIndex] !== '+') { + this.list.push({text: '*'}); + } + } + if (isInsideExpressionlessParenthesizedExpression(ctx)) { + this.list.push({text: ')'}); + } + return; + } + const nodeValue = getValueNodeValue(ctx); + if (ctx.parent instanceof AttributeExpressionContext) { + const attributeKey = ctx.parent.attributeName().text; + this.addAttributeValueResults(attributeKey, nodeValue); + } + } + } + + visitUnquotedStringValue(ctx: UnquotedStringValueContext) { + if (this.nodeIncludesCursor(ctx)) { + if (ctx.parent instanceof UnmatchedValueContext) { + this.addUnmatchedValueResults(ctx.text); + return; + } + const nodeValue = getValueNodeValue(ctx); + if (ctx.parent instanceof AttributeExpressionContext) { + const attributeKey = ctx.parent.attributeName().text; + this.addAttributeValueResults(attributeKey, nodeValue); + } + } + } + + visitAndExpression(ctx: AndExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.visit(ctx.expr(0)); + this.visit(ctx.expr(1)); + } + } + + visitOrExpression(ctx: OrExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.visit(ctx.expr(0)); + this.visit(ctx.expr(1)); + } + } + + visitNotExpression(ctx: NotExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.visit(ctx.expr()); + } + } + + visitExpressionlessParenthesizedExpression(ctx: ExpressionlessParenthesizedExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + const char = this.line[this.cursorIndex]; + if (char !== ')') { + this.addUnmatchedValueResults(''); + } + } + } + + visitUnclosedExpressionlessParenthesizedExpression( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) { + if (this.nodeIncludesCursor(ctx)) { + this.addUnmatchedValueResults(''); + } + } + + visitExpressionlessFunctionExpression(ctx: ExpressionlessFunctionExpressionContext) { + if (this.nodeIncludesCursor(ctx)) { + this.addUnmatchedValueResults(''); + } + } + + visitUnclosedExpressionlessFunctionExpression( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) { + if (this.nodeIncludesCursor(ctx)) { + this.addUnmatchedValueResults(''); + } + } + + visitUnmatchedValue(ctx: UnmatchedValueContext) { + if (this.nodeIncludesCursor(ctx)) { + this.addUnmatchedValueResults(ctx.text); + } + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts index bf4bb8ce7f5b8..a70208ed5524f 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/__tests__/SelectionAutoComplete.test.ts @@ -181,13 +181,58 @@ describe('createAssetSelectionHint', () => { {displayText: 'sinks()', text: 'sinks()'}, {displayText: 'roots()', text: 'roots()'}, {displayText: 'not', text: 'not '}, - {displayText: '*', text: '*'}, - {displayText: '+', text: '+'}, {displayText: '(', text: '()'}, ], from: 1, // cursor location to: 1, // cursor location }); + + expect(testAutocomplete('* |')).toEqual({ + from: 2, + list: [ + {displayText: 'and', text: ' and '}, + {displayText: 'or', text: ' or '}, + ], + to: 2, + }); + + expect(testAutocomplete('+ |')).toEqual({ + from: 2, + list: [ + {displayText: 'key_substring:', text: 'key_substring:'}, + {displayText: 'key:', text: 'key:'}, + {displayText: 'tag:', text: 'tag:'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'group:', text: 'group:'}, + {displayText: 'kind:', text: 'kind:'}, + {displayText: 'code_location:', text: 'code_location:'}, + {displayText: 'sinks()', text: 'sinks()'}, + {displayText: 'roots()', text: 'roots()'}, + {displayText: 'not', text: 'not '}, + {displayText: '*', text: '*'}, + {displayText: '+', text: '+'}, + {displayText: '(', text: '()'}, + ], + to: 2, + }); + + expect(testAutocomplete('+|')).toEqual({ + from: 1, + list: [ + {displayText: 'key_substring:', text: 'key_substring:'}, + {displayText: 'key:', text: 'key:'}, + {displayText: 'tag:', text: 'tag:'}, + {displayText: 'owner:', text: 'owner:'}, + {displayText: 'group:', text: 'group:'}, + {displayText: 'kind:', text: 'kind:'}, + {displayText: 'code_location:', text: 'code_location:'}, + {displayText: 'sinks()', text: 'sinks()'}, + {displayText: 'roots()', text: 'roots()'}, + {displayText: '+', text: '+'}, + {displayText: '(', text: '()'}, + ], + to: 1, + }); }); it('should suggest code locations after typing code_location:', () => { @@ -346,7 +391,7 @@ describe('createAssetSelectionHint', () => { }); }); - it('should handle IncompleteAttributeExpression inside OrExpression within ParenthesizedExpression', () => { + it('should suggest tag values to the right of colon of an attribute expression inside of an IncompleteAttributeExpression, OrExpression, and ParenthesizedExpression', () => { expect( testAutocomplete( 'sinks(key_substring:"FIVETRAN/google_ads/ad_group_history" or key_substring:|)', @@ -555,7 +600,7 @@ describe('createAssetSelectionHint', () => { expect(testAutocomplete('|++sinks()++')).toEqual({ list: [ {text: '+', displayText: '+'}, - {text: '(', displayText: '('}, + {text: '()', displayText: '('}, ], from: 0, // start of value to: 0, // end of value @@ -564,7 +609,7 @@ describe('createAssetSelectionHint', () => { expect(testAutocomplete('+|+sinks()++')).toEqual({ list: [ {text: '+', displayText: '+'}, - {text: '(', displayText: '('}, + {text: '()', displayText: '('}, ], from: 1, // start of value to: 1, // end of value @@ -708,4 +753,12 @@ describe('createAssetSelectionHint', () => { to: 35, }); }); + + it('suggests attribute names when cursor left of the colon', () => { + expect(testAutocomplete('tag:"dagster/kind/fivetran" or t|:"a"')).toEqual({ + from: 31, + list: [{displayText: 'tag:', text: 'tag:'}], + to: 33, + }); + }); }); diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp index 1e107956d815c..311bacb3330dc 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoComplete.interp @@ -37,10 +37,10 @@ start expr traversalAllowedExpr parenthesizedExpr -incompleteExpressionsWrapper +incompleteExpr expressionLessParenthesizedExpr -upTraversalExp -downTraversalExp +upTraversalExpr +downTraversalExpr traversal attributeName attributeValue @@ -51,10 +51,16 @@ notToken colonToken leftParenToken rightParenToken -afterExpressionWhitespace -afterLogicalOperatorWhitespace +attributeValueWhitespace +postAttributeValueWhitespace +postExpressionWhitespace +postNotOperatorWhitespace +postLogicalOperatorWhitespace +postNeighborTraversalWhitespace +postUpwardTraversalWhitespace +postDownwardTraversalWhitespace value atn: -[3, 51485, 51898, 1421, 44986, 20307, 1543, 60043, 49729, 3, 16, 208, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4, 18, 9, 18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 3, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 3, 78, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 109, 10, 3, 12, 3, 14, 3, 112, 11, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 123, 10, 4, 3, 5, 3, 5, 3, 5, 3, 5, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 6, 6, 148, 10, 6, 13, 6, 14, 6, 149, 3, 6, 3, 6, 3, 6, 5, 6, 155, 10, 6, 3, 7, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 10, 3, 10, 6, 10, 166, 10, 10, 13, 10, 14, 10, 167, 5, 10, 170, 10, 10, 3, 11, 3, 11, 3, 12, 3, 12, 3, 13, 3, 13, 3, 14, 3, 14, 3, 15, 3, 15, 3, 16, 3, 16, 3, 17, 3, 17, 3, 18, 3, 18, 3, 19, 3, 19, 3, 20, 7, 20, 191, 10, 20, 12, 20, 14, 20, 194, 11, 20, 3, 21, 7, 21, 197, 10, 21, 12, 21, 14, 21, 200, 11, 21, 3, 22, 3, 22, 3, 22, 3, 22, 5, 22, 206, 10, 22, 3, 22, 2, 2, 3, 4, 23, 2, 2, 4, 2, 6, 2, 8, 2, 10, 2, 12, 2, 14, 2, 16, 2, 18, 2, 20, 2, 22, 2, 24, 2, 26, 2, 28, 2, 30, 2, 32, 2, 34, 2, 36, 2, 38, 2, 40, 2, 42, 2, 2, 2, 2, 217, 2, 44, 3, 2, 2, 2, 4, 77, 3, 2, 2, 2, 6, 122, 3, 2, 2, 2, 8, 124, 3, 2, 2, 2, 10, 154, 3, 2, 2, 2, 12, 156, 3, 2, 2, 2, 14, 159, 3, 2, 2, 2, 16, 161, 3, 2, 2, 2, 18, 169, 3, 2, 2, 2, 20, 171, 3, 2, 2, 2, 22, 173, 3, 2, 2, 2, 24, 175, 3, 2, 2, 2, 26, 177, 3, 2, 2, 2, 28, 179, 3, 2, 2, 2, 30, 181, 3, 2, 2, 2, 32, 183, 3, 2, 2, 2, 34, 185, 3, 2, 2, 2, 36, 187, 3, 2, 2, 2, 38, 192, 3, 2, 2, 2, 40, 198, 3, 2, 2, 2, 42, 205, 3, 2, 2, 2, 44, 45, 5, 4, 3, 2, 45, 46, 7, 2, 2, 3, 46, 3, 3, 2, 2, 2, 47, 48, 8, 3, 1, 2, 48, 49, 5, 6, 4, 2, 49, 50, 5, 38, 20, 2, 50, 78, 3, 2, 2, 2, 51, 52, 5, 14, 8, 2, 52, 53, 5, 6, 4, 2, 53, 54, 5, 16, 9, 2, 54, 55, 5, 38, 20, 2, 55, 78, 3, 2, 2, 2, 56, 57, 5, 14, 8, 2, 57, 58, 5, 6, 4, 2, 58, 59, 5, 38, 20, 2, 59, 78, 3, 2, 2, 2, 60, 61, 5, 6, 4, 2, 61, 62, 5, 16, 9, 2, 62, 63, 5, 38, 20, 2, 63, 78, 3, 2, 2, 2, 64, 65, 5, 30, 16, 2, 65, 66, 5, 40, 21, 2, 66, 67, 5, 4, 3, 2, 67, 68, 5, 38, 20, 2, 68, 78, 3, 2, 2, 2, 69, 70, 5, 30, 16, 2, 70, 71, 5, 40, 21, 2, 71, 78, 3, 2, 2, 2, 72, 73, 7, 6, 2, 2, 73, 78, 5, 38, 20, 2, 74, 75, 5, 42, 22, 2, 75, 76, 5, 38, 20, 2, 76, 78, 3, 2, 2, 2, 77, 47, 3, 2, 2, 2, 77, 51, 3, 2, 2, 2, 77, 56, 3, 2, 2, 2, 77, 60, 3, 2, 2, 2, 77, 64, 3, 2, 2, 2, 77, 69, 3, 2, 2, 2, 77, 72, 3, 2, 2, 2, 77, 74, 3, 2, 2, 2, 78, 110, 3, 2, 2, 2, 79, 80, 12, 10, 2, 2, 80, 81, 5, 38, 20, 2, 81, 82, 5, 28, 15, 2, 82, 83, 5, 40, 21, 2, 83, 84, 5, 4, 3, 2, 84, 85, 5, 38, 20, 2, 85, 109, 3, 2, 2, 2, 86, 87, 12, 9, 2, 2, 87, 88, 5, 38, 20, 2, 88, 89, 5, 26, 14, 2, 89, 90, 5, 40, 21, 2, 90, 91, 5, 4, 3, 2, 91, 92, 5, 38, 20, 2, 92, 109, 3, 2, 2, 2, 93, 94, 12, 8, 2, 2, 94, 95, 5, 38, 20, 2, 95, 96, 5, 28, 15, 2, 96, 97, 5, 40, 21, 2, 97, 109, 3, 2, 2, 2, 98, 99, 12, 7, 2, 2, 99, 100, 5, 38, 20, 2, 100, 101, 5, 26, 14, 2, 101, 102, 5, 40, 21, 2, 102, 109, 3, 2, 2, 2, 103, 104, 12, 5, 2, 2, 104, 105, 5, 38, 20, 2, 105, 106, 5, 42, 22, 2, 106, 107, 5, 40, 21, 2, 107, 109, 3, 2, 2, 2, 108, 79, 3, 2, 2, 2, 108, 86, 3, 2, 2, 2, 108, 93, 3, 2, 2, 2, 108, 98, 3, 2, 2, 2, 108, 103, 3, 2, 2, 2, 109, 112, 3, 2, 2, 2, 110, 108, 3, 2, 2, 2, 110, 111, 3, 2, 2, 2, 111, 5, 3, 2, 2, 2, 112, 110, 3, 2, 2, 2, 113, 114, 5, 20, 11, 2, 114, 115, 5, 32, 17, 2, 115, 116, 5, 22, 12, 2, 116, 123, 3, 2, 2, 2, 117, 118, 5, 24, 13, 2, 118, 119, 5, 8, 5, 2, 119, 123, 3, 2, 2, 2, 120, 123, 5, 8, 5, 2, 121, 123, 5, 10, 6, 2, 122, 113, 3, 2, 2, 2, 122, 117, 3, 2, 2, 2, 122, 120, 3, 2, 2, 2, 122, 121, 3, 2, 2, 2, 123, 7, 3, 2, 2, 2, 124, 125, 5, 34, 18, 2, 125, 126, 5, 4, 3, 2, 126, 127, 5, 36, 19, 2, 127, 9, 3, 2, 2, 2, 128, 129, 5, 20, 11, 2, 129, 130, 5, 32, 17, 2, 130, 155, 3, 2, 2, 2, 131, 132, 5, 24, 13, 2, 132, 133, 5, 12, 7, 2, 133, 155, 3, 2, 2, 2, 134, 135, 5, 24, 13, 2, 135, 136, 5, 34, 18, 2, 136, 155, 3, 2, 2, 2, 137, 138, 5, 24, 13, 2, 138, 139, 5, 34, 18, 2, 139, 140, 5, 4, 3, 2, 140, 155, 3, 2, 2, 2, 141, 142, 5, 34, 18, 2, 142, 143, 5, 4, 3, 2, 143, 155, 3, 2, 2, 2, 144, 155, 5, 12, 7, 2, 145, 155, 5, 34, 18, 2, 146, 148, 7, 7, 2, 2, 147, 146, 3, 2, 2, 2, 148, 149, 3, 2, 2, 2, 149, 147, 3, 2, 2, 2, 149, 150, 3, 2, 2, 2, 150, 155, 3, 2, 2, 2, 151, 152, 5, 32, 17, 2, 152, 153, 5, 22, 12, 2, 153, 155, 3, 2, 2, 2, 154, 128, 3, 2, 2, 2, 154, 131, 3, 2, 2, 2, 154, 134, 3, 2, 2, 2, 154, 137, 3, 2, 2, 2, 154, 141, 3, 2, 2, 2, 154, 144, 3, 2, 2, 2, 154, 145, 3, 2, 2, 2, 154, 147, 3, 2, 2, 2, 154, 151, 3, 2, 2, 2, 155, 11, 3, 2, 2, 2, 156, 157, 5, 34, 18, 2, 157, 158, 5, 36, 19, 2, 158, 13, 3, 2, 2, 2, 159, 160, 5, 18, 10, 2, 160, 15, 3, 2, 2, 2, 161, 162, 5, 18, 10, 2, 162, 17, 3, 2, 2, 2, 163, 170, 7, 6, 2, 2, 164, 166, 7, 7, 2, 2, 165, 164, 3, 2, 2, 2, 166, 167, 3, 2, 2, 2, 167, 165, 3, 2, 2, 2, 167, 168, 3, 2, 2, 2, 168, 170, 3, 2, 2, 2, 169, 163, 3, 2, 2, 2, 169, 165, 3, 2, 2, 2, 170, 19, 3, 2, 2, 2, 171, 172, 7, 15, 2, 2, 172, 21, 3, 2, 2, 2, 173, 174, 5, 42, 22, 2, 174, 23, 3, 2, 2, 2, 175, 176, 7, 15, 2, 2, 176, 25, 3, 2, 2, 2, 177, 178, 7, 4, 2, 2, 178, 27, 3, 2, 2, 2, 179, 180, 7, 3, 2, 2, 180, 29, 3, 2, 2, 2, 181, 182, 7, 5, 2, 2, 182, 31, 3, 2, 2, 2, 183, 184, 7, 8, 2, 2, 184, 33, 3, 2, 2, 2, 185, 186, 7, 9, 2, 2, 186, 35, 3, 2, 2, 2, 187, 188, 7, 10, 2, 2, 188, 37, 3, 2, 2, 2, 189, 191, 7, 16, 2, 2, 190, 189, 3, 2, 2, 2, 191, 194, 3, 2, 2, 2, 192, 190, 3, 2, 2, 2, 192, 193, 3, 2, 2, 2, 193, 39, 3, 2, 2, 2, 194, 192, 3, 2, 2, 2, 195, 197, 7, 16, 2, 2, 196, 195, 3, 2, 2, 2, 197, 200, 3, 2, 2, 2, 198, 196, 3, 2, 2, 2, 198, 199, 3, 2, 2, 2, 199, 41, 3, 2, 2, 2, 200, 198, 3, 2, 2, 2, 201, 206, 7, 12, 2, 2, 202, 206, 7, 13, 2, 2, 203, 206, 7, 14, 2, 2, 204, 206, 7, 15, 2, 2, 205, 201, 3, 2, 2, 2, 205, 202, 3, 2, 2, 2, 205, 203, 3, 2, 2, 2, 205, 204, 3, 2, 2, 2, 206, 43, 3, 2, 2, 2, 13, 77, 108, 110, 122, 149, 154, 167, 169, 192, 198, 205] \ No newline at end of file +[3, 51485, 51898, 1421, 44986, 20307, 1543, 60043, 49729, 3, 16, 257, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 4, 18, 9, 18, 4, 19, 9, 19, 4, 20, 9, 20, 4, 21, 9, 21, 4, 22, 9, 22, 4, 23, 9, 23, 4, 24, 9, 24, 4, 25, 9, 25, 4, 26, 9, 26, 4, 27, 9, 27, 4, 28, 9, 28, 3, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 3, 84, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 108, 10, 3, 12, 3, 14, 3, 111, 11, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 123, 10, 4, 3, 5, 3, 5, 3, 5, 3, 5, 3, 5, 3, 5, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 6, 6, 155, 10, 6, 13, 6, 14, 6, 156, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 5, 6, 164, 10, 6, 3, 7, 3, 7, 3, 7, 3, 7, 3, 7, 3, 8, 3, 8, 3, 8, 3, 9, 3, 9, 3, 9, 3, 10, 3, 10, 6, 10, 179, 10, 10, 13, 10, 14, 10, 180, 5, 10, 183, 10, 10, 3, 11, 3, 11, 3, 12, 3, 12, 3, 13, 3, 13, 3, 14, 3, 14, 3, 15, 3, 15, 3, 16, 3, 16, 3, 17, 3, 17, 3, 18, 3, 18, 3, 19, 3, 19, 3, 20, 7, 20, 204, 10, 20, 12, 20, 14, 20, 207, 11, 20, 3, 21, 7, 21, 210, 10, 21, 12, 21, 14, 21, 213, 11, 21, 3, 22, 7, 22, 216, 10, 22, 12, 22, 14, 22, 219, 11, 22, 3, 23, 7, 23, 222, 10, 23, 12, 23, 14, 23, 225, 11, 23, 3, 24, 7, 24, 228, 10, 24, 12, 24, 14, 24, 231, 11, 24, 3, 25, 7, 25, 234, 10, 25, 12, 25, 14, 25, 237, 11, 25, 3, 26, 7, 26, 240, 10, 26, 12, 26, 14, 26, 243, 11, 26, 3, 27, 7, 27, 246, 10, 27, 12, 27, 14, 27, 249, 11, 27, 3, 28, 3, 28, 3, 28, 3, 28, 5, 28, 255, 10, 28, 3, 28, 2, 2, 3, 4, 29, 2, 2, 4, 2, 6, 2, 8, 2, 10, 2, 12, 2, 14, 2, 16, 2, 18, 2, 20, 2, 22, 2, 24, 2, 26, 2, 28, 2, 30, 2, 32, 2, 34, 2, 36, 2, 38, 2, 40, 2, 42, 2, 44, 2, 46, 2, 48, 2, 50, 2, 52, 2, 54, 2, 2, 2, 2, 266, 2, 56, 3, 2, 2, 2, 4, 83, 3, 2, 2, 2, 6, 122, 3, 2, 2, 2, 8, 124, 3, 2, 2, 2, 10, 163, 3, 2, 2, 2, 12, 165, 3, 2, 2, 2, 14, 170, 3, 2, 2, 2, 16, 173, 3, 2, 2, 2, 18, 182, 3, 2, 2, 2, 20, 184, 3, 2, 2, 2, 22, 186, 3, 2, 2, 2, 24, 188, 3, 2, 2, 2, 26, 190, 3, 2, 2, 2, 28, 192, 3, 2, 2, 2, 30, 194, 3, 2, 2, 2, 32, 196, 3, 2, 2, 2, 34, 198, 3, 2, 2, 2, 36, 200, 3, 2, 2, 2, 38, 205, 3, 2, 2, 2, 40, 211, 3, 2, 2, 2, 42, 217, 3, 2, 2, 2, 44, 223, 3, 2, 2, 2, 46, 229, 3, 2, 2, 2, 48, 235, 3, 2, 2, 2, 50, 241, 3, 2, 2, 2, 52, 247, 3, 2, 2, 2, 54, 254, 3, 2, 2, 2, 56, 57, 5, 4, 3, 2, 57, 58, 7, 2, 2, 3, 58, 3, 3, 2, 2, 2, 59, 60, 8, 3, 1, 2, 60, 84, 5, 6, 4, 2, 61, 62, 5, 14, 8, 2, 62, 63, 5, 6, 4, 2, 63, 64, 5, 16, 9, 2, 64, 84, 3, 2, 2, 2, 65, 66, 5, 14, 8, 2, 66, 67, 5, 6, 4, 2, 67, 84, 3, 2, 2, 2, 68, 69, 5, 6, 4, 2, 69, 70, 5, 16, 9, 2, 70, 84, 3, 2, 2, 2, 71, 72, 5, 30, 16, 2, 72, 73, 5, 44, 23, 2, 73, 74, 5, 4, 3, 11, 74, 84, 3, 2, 2, 2, 75, 76, 5, 30, 16, 2, 76, 77, 5, 44, 23, 2, 77, 84, 3, 2, 2, 2, 78, 79, 7, 6, 2, 2, 79, 84, 5, 42, 22, 2, 80, 81, 5, 54, 28, 2, 81, 82, 5, 42, 22, 2, 82, 84, 3, 2, 2, 2, 83, 59, 3, 2, 2, 2, 83, 61, 3, 2, 2, 2, 83, 65, 3, 2, 2, 2, 83, 68, 3, 2, 2, 2, 83, 71, 3, 2, 2, 2, 83, 75, 3, 2, 2, 2, 83, 78, 3, 2, 2, 2, 83, 80, 3, 2, 2, 2, 84, 109, 3, 2, 2, 2, 85, 86, 12, 10, 2, 2, 86, 87, 5, 28, 15, 2, 87, 88, 5, 46, 24, 2, 88, 89, 5, 4, 3, 11, 89, 108, 3, 2, 2, 2, 90, 91, 12, 9, 2, 2, 91, 92, 5, 26, 14, 2, 92, 93, 5, 46, 24, 2, 93, 94, 5, 4, 3, 10, 94, 108, 3, 2, 2, 2, 95, 96, 12, 8, 2, 2, 96, 97, 5, 28, 15, 2, 97, 98, 5, 46, 24, 2, 98, 108, 3, 2, 2, 2, 99, 100, 12, 7, 2, 2, 100, 101, 5, 26, 14, 2, 101, 102, 5, 46, 24, 2, 102, 108, 3, 2, 2, 2, 103, 104, 12, 5, 2, 2, 104, 105, 5, 54, 28, 2, 105, 106, 5, 46, 24, 2, 106, 108, 3, 2, 2, 2, 107, 85, 3, 2, 2, 2, 107, 90, 3, 2, 2, 2, 107, 95, 3, 2, 2, 2, 107, 99, 3, 2, 2, 2, 107, 103, 3, 2, 2, 2, 108, 111, 3, 2, 2, 2, 109, 107, 3, 2, 2, 2, 109, 110, 3, 2, 2, 2, 110, 5, 3, 2, 2, 2, 111, 109, 3, 2, 2, 2, 112, 113, 5, 20, 11, 2, 113, 114, 5, 32, 17, 2, 114, 115, 5, 22, 12, 2, 115, 116, 5, 40, 21, 2, 116, 123, 3, 2, 2, 2, 117, 118, 5, 24, 13, 2, 118, 119, 5, 8, 5, 2, 119, 123, 3, 2, 2, 2, 120, 123, 5, 8, 5, 2, 121, 123, 5, 10, 6, 2, 122, 112, 3, 2, 2, 2, 122, 117, 3, 2, 2, 2, 122, 120, 3, 2, 2, 2, 122, 121, 3, 2, 2, 2, 123, 7, 3, 2, 2, 2, 124, 125, 5, 34, 18, 2, 125, 126, 5, 46, 24, 2, 126, 127, 5, 4, 3, 2, 127, 128, 5, 36, 19, 2, 128, 129, 5, 42, 22, 2, 129, 9, 3, 2, 2, 2, 130, 131, 5, 20, 11, 2, 131, 132, 5, 32, 17, 2, 132, 133, 5, 38, 20, 2, 133, 164, 3, 2, 2, 2, 134, 135, 5, 24, 13, 2, 135, 136, 5, 12, 7, 2, 136, 164, 3, 2, 2, 2, 137, 138, 5, 24, 13, 2, 138, 139, 5, 34, 18, 2, 139, 140, 5, 46, 24, 2, 140, 164, 3, 2, 2, 2, 141, 142, 5, 24, 13, 2, 142, 143, 5, 34, 18, 2, 143, 144, 5, 4, 3, 2, 144, 164, 3, 2, 2, 2, 145, 146, 5, 34, 18, 2, 146, 147, 5, 46, 24, 2, 147, 148, 5, 4, 3, 2, 148, 164, 3, 2, 2, 2, 149, 164, 5, 12, 7, 2, 150, 151, 5, 34, 18, 2, 151, 152, 5, 46, 24, 2, 152, 164, 3, 2, 2, 2, 153, 155, 7, 7, 2, 2, 154, 153, 3, 2, 2, 2, 155, 156, 3, 2, 2, 2, 156, 154, 3, 2, 2, 2, 156, 157, 3, 2, 2, 2, 157, 158, 3, 2, 2, 2, 158, 164, 5, 48, 25, 2, 159, 160, 5, 32, 17, 2, 160, 161, 5, 22, 12, 2, 161, 162, 5, 42, 22, 2, 162, 164, 3, 2, 2, 2, 163, 130, 3, 2, 2, 2, 163, 134, 3, 2, 2, 2, 163, 137, 3, 2, 2, 2, 163, 141, 3, 2, 2, 2, 163, 145, 3, 2, 2, 2, 163, 149, 3, 2, 2, 2, 163, 150, 3, 2, 2, 2, 163, 154, 3, 2, 2, 2, 163, 159, 3, 2, 2, 2, 164, 11, 3, 2, 2, 2, 165, 166, 5, 34, 18, 2, 166, 167, 5, 46, 24, 2, 167, 168, 5, 36, 19, 2, 168, 169, 5, 42, 22, 2, 169, 13, 3, 2, 2, 2, 170, 171, 5, 18, 10, 2, 171, 172, 5, 50, 26, 2, 172, 15, 3, 2, 2, 2, 173, 174, 5, 18, 10, 2, 174, 175, 5, 52, 27, 2, 175, 17, 3, 2, 2, 2, 176, 183, 7, 6, 2, 2, 177, 179, 7, 7, 2, 2, 178, 177, 3, 2, 2, 2, 179, 180, 3, 2, 2, 2, 180, 178, 3, 2, 2, 2, 180, 181, 3, 2, 2, 2, 181, 183, 3, 2, 2, 2, 182, 176, 3, 2, 2, 2, 182, 178, 3, 2, 2, 2, 183, 19, 3, 2, 2, 2, 184, 185, 7, 15, 2, 2, 185, 21, 3, 2, 2, 2, 186, 187, 5, 54, 28, 2, 187, 23, 3, 2, 2, 2, 188, 189, 7, 15, 2, 2, 189, 25, 3, 2, 2, 2, 190, 191, 7, 4, 2, 2, 191, 27, 3, 2, 2, 2, 192, 193, 7, 3, 2, 2, 193, 29, 3, 2, 2, 2, 194, 195, 7, 5, 2, 2, 195, 31, 3, 2, 2, 2, 196, 197, 7, 8, 2, 2, 197, 33, 3, 2, 2, 2, 198, 199, 7, 9, 2, 2, 199, 35, 3, 2, 2, 2, 200, 201, 7, 10, 2, 2, 201, 37, 3, 2, 2, 2, 202, 204, 7, 16, 2, 2, 203, 202, 3, 2, 2, 2, 204, 207, 3, 2, 2, 2, 205, 203, 3, 2, 2, 2, 205, 206, 3, 2, 2, 2, 206, 39, 3, 2, 2, 2, 207, 205, 3, 2, 2, 2, 208, 210, 7, 16, 2, 2, 209, 208, 3, 2, 2, 2, 210, 213, 3, 2, 2, 2, 211, 209, 3, 2, 2, 2, 211, 212, 3, 2, 2, 2, 212, 41, 3, 2, 2, 2, 213, 211, 3, 2, 2, 2, 214, 216, 7, 16, 2, 2, 215, 214, 3, 2, 2, 2, 216, 219, 3, 2, 2, 2, 217, 215, 3, 2, 2, 2, 217, 218, 3, 2, 2, 2, 218, 43, 3, 2, 2, 2, 219, 217, 3, 2, 2, 2, 220, 222, 7, 16, 2, 2, 221, 220, 3, 2, 2, 2, 222, 225, 3, 2, 2, 2, 223, 221, 3, 2, 2, 2, 223, 224, 3, 2, 2, 2, 224, 45, 3, 2, 2, 2, 225, 223, 3, 2, 2, 2, 226, 228, 7, 16, 2, 2, 227, 226, 3, 2, 2, 2, 228, 231, 3, 2, 2, 2, 229, 227, 3, 2, 2, 2, 229, 230, 3, 2, 2, 2, 230, 47, 3, 2, 2, 2, 231, 229, 3, 2, 2, 2, 232, 234, 7, 16, 2, 2, 233, 232, 3, 2, 2, 2, 234, 237, 3, 2, 2, 2, 235, 233, 3, 2, 2, 2, 235, 236, 3, 2, 2, 2, 236, 49, 3, 2, 2, 2, 237, 235, 3, 2, 2, 2, 238, 240, 7, 16, 2, 2, 239, 238, 3, 2, 2, 2, 240, 243, 3, 2, 2, 2, 241, 239, 3, 2, 2, 2, 241, 242, 3, 2, 2, 2, 242, 51, 3, 2, 2, 2, 243, 241, 3, 2, 2, 2, 244, 246, 7, 16, 2, 2, 245, 244, 3, 2, 2, 2, 246, 249, 3, 2, 2, 2, 247, 245, 3, 2, 2, 2, 247, 248, 3, 2, 2, 2, 248, 53, 3, 2, 2, 2, 249, 247, 3, 2, 2, 2, 250, 255, 7, 12, 2, 2, 251, 255, 7, 13, 2, 2, 252, 255, 7, 14, 2, 2, 253, 255, 7, 15, 2, 2, 254, 250, 3, 2, 2, 2, 254, 251, 3, 2, 2, 2, 254, 252, 3, 2, 2, 2, 254, 253, 3, 2, 2, 2, 255, 55, 3, 2, 2, 2, 19, 83, 107, 109, 122, 156, 163, 180, 182, 205, 211, 217, 223, 229, 235, 241, 247, 254] \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts index d47ae283cf6ac..8a766441e2250 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteListener.ts @@ -3,17 +3,16 @@ import {ParseTreeListener} from 'antlr4ts/tree/ParseTreeListener'; import { - AfterExpressionWhitespaceContext, - AfterLogicalOperatorWhitespaceContext, AllExpressionContext, AndExpressionContext, AndTokenContext, AttributeExpressionContext, AttributeNameContext, AttributeValueContext, + AttributeValueWhitespaceContext, ColonTokenContext, DownTraversalContext, - DownTraversalExpContext, + DownTraversalExprContext, DownTraversalExpressionContext, ExprContext, ExpressionLessParenthesizedExprContext, @@ -25,13 +24,13 @@ import { IncompleteAndExpressionContext, IncompleteAttributeExpressionMissingKeyContext, IncompleteAttributeExpressionMissingValueContext, + IncompleteExprContext, IncompleteExpressionContext, - IncompleteExpressionsWrapperContext, IncompleteLeftQuotedStringValueContext, IncompleteNotExpressionContext, IncompleteOrExpressionContext, + IncompletePlusTraversalExpressionContext, IncompleteRightQuotedStringValueContext, - IncompleteTraversalExpressionContext, LeftParenTokenContext, NotExpressionContext, NotTokenContext, @@ -39,12 +38,19 @@ import { OrTokenContext, ParenthesizedExprContext, ParenthesizedExpressionContext, - ParenthesizedExpressionWrapperContext, + PostAttributeValueWhitespaceContext, + PostDownwardTraversalWhitespaceContext, + PostExpressionWhitespaceContext, + PostLogicalOperatorWhitespaceContext, + PostNeighborTraversalWhitespaceContext, + PostNotOperatorWhitespaceContext, + PostUpwardTraversalWhitespaceContext, QuotedStringValueContext, RightParenTokenContext, StartContext, TraversalAllowedExprContext, TraversalAllowedExpressionContext, + TraversalAllowedParenthesizedExpressionContext, TraversalContext, UnclosedExpressionlessFunctionExpressionContext, UnclosedExpressionlessParenthesizedExpressionContext, @@ -55,7 +61,7 @@ import { UnquotedStringValueContext, UpAndDownTraversalExpressionContext, UpTraversalContext, - UpTraversalExpContext, + UpTraversalExprContext, UpTraversalExpressionContext, ValueContext, } from './SelectionAutoCompleteParser'; @@ -65,19 +71,6 @@ import { * `SelectionAutoCompleteParser`. */ export interface SelectionAutoCompleteListener extends ParseTreeListener { - /** - * Enter a parse tree produced by the `DownTraversal` - * labeled alternative in `SelectionAutoCompleteParser.downTraversalExp`. - * @param ctx the parse tree - */ - enterDownTraversal?: (ctx: DownTraversalContext) => void; - /** - * Exit a parse tree produced by the `DownTraversal` - * labeled alternative in `SelectionAutoCompleteParser.downTraversalExp`. - * @param ctx the parse tree - */ - exitDownTraversal?: (ctx: DownTraversalContext) => void; - /** * Enter a parse tree produced by the `AttributeExpression` * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. @@ -105,17 +98,21 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { exitFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => void; /** - * Enter a parse tree produced by the `ParenthesizedExpressionWrapper` + * Enter a parse tree produced by the `TraversalAllowedParenthesizedExpression` * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. * @param ctx the parse tree */ - enterParenthesizedExpressionWrapper?: (ctx: ParenthesizedExpressionWrapperContext) => void; + enterTraversalAllowedParenthesizedExpression?: ( + ctx: TraversalAllowedParenthesizedExpressionContext, + ) => void; /** - * Exit a parse tree produced by the `ParenthesizedExpressionWrapper` + * Exit a parse tree produced by the `TraversalAllowedParenthesizedExpression` * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. * @param ctx the parse tree */ - exitParenthesizedExpressionWrapper?: (ctx: ParenthesizedExpressionWrapperContext) => void; + exitTraversalAllowedParenthesizedExpression?: ( + ctx: TraversalAllowedParenthesizedExpressionContext, + ) => void; /** * Enter a parse tree produced by the `IncompleteExpression` @@ -132,154 +129,17 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { /** * Enter a parse tree produced by the `UpTraversal` - * labeled alternative in `SelectionAutoCompleteParser.upTraversalExp`. + * labeled alternative in `SelectionAutoCompleteParser.upTraversalExpr`. * @param ctx the parse tree */ enterUpTraversal?: (ctx: UpTraversalContext) => void; /** * Exit a parse tree produced by the `UpTraversal` - * labeled alternative in `SelectionAutoCompleteParser.upTraversalExp`. + * labeled alternative in `SelectionAutoCompleteParser.upTraversalExpr`. * @param ctx the parse tree */ exitUpTraversal?: (ctx: UpTraversalContext) => void; - /** - * Enter a parse tree produced by the `IncompleteAttributeExpressionMissingValue` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterIncompleteAttributeExpressionMissingValue?: ( - ctx: IncompleteAttributeExpressionMissingValueContext, - ) => void; - /** - * Exit a parse tree produced by the `IncompleteAttributeExpressionMissingValue` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitIncompleteAttributeExpressionMissingValue?: ( - ctx: IncompleteAttributeExpressionMissingValueContext, - ) => void; - - /** - * Enter a parse tree produced by the `ExpressionlessFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => void; - /** - * Exit a parse tree produced by the `ExpressionlessFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => void; - - /** - * Enter a parse tree produced by the `UnclosedExpressionlessFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterUnclosedExpressionlessFunctionExpression?: ( - ctx: UnclosedExpressionlessFunctionExpressionContext, - ) => void; - /** - * Exit a parse tree produced by the `UnclosedExpressionlessFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitUnclosedExpressionlessFunctionExpression?: ( - ctx: UnclosedExpressionlessFunctionExpressionContext, - ) => void; - - /** - * Enter a parse tree produced by the `UnclosedFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => void; - /** - * Exit a parse tree produced by the `UnclosedFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => void; - - /** - * Enter a parse tree produced by the `UnclosedParenthesizedExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => void; - /** - * Exit a parse tree produced by the `UnclosedParenthesizedExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => void; - - /** - * Enter a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterExpressionlessParenthesizedExpressionWrapper?: ( - ctx: ExpressionlessParenthesizedExpressionWrapperContext, - ) => void; - /** - * Exit a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitExpressionlessParenthesizedExpressionWrapper?: ( - ctx: ExpressionlessParenthesizedExpressionWrapperContext, - ) => void; - - /** - * Enter a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterUnclosedExpressionlessParenthesizedExpression?: ( - ctx: UnclosedExpressionlessParenthesizedExpressionContext, - ) => void; - /** - * Exit a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitUnclosedExpressionlessParenthesizedExpression?: ( - ctx: UnclosedExpressionlessParenthesizedExpressionContext, - ) => void; - - /** - * Enter a parse tree produced by the `IncompleteTraversalExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterIncompleteTraversalExpression?: (ctx: IncompleteTraversalExpressionContext) => void; - /** - * Exit a parse tree produced by the `IncompleteTraversalExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitIncompleteTraversalExpression?: (ctx: IncompleteTraversalExpressionContext) => void; - - /** - * Enter a parse tree produced by the `IncompleteAttributeExpressionMissingKey` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - enterIncompleteAttributeExpressionMissingKey?: ( - ctx: IncompleteAttributeExpressionMissingKeyContext, - ) => void; - /** - * Exit a parse tree produced by the `IncompleteAttributeExpressionMissingKey` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - */ - exitIncompleteAttributeExpressionMissingKey?: ( - ctx: IncompleteAttributeExpressionMissingKeyContext, - ) => void; - /** * Enter a parse tree produced by the `ParenthesizedExpression` * labeled alternative in `SelectionAutoCompleteParser.parenthesizedExpr`. @@ -479,6 +339,19 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { ctx: ExpressionlessParenthesizedExpressionContext, ) => void; + /** + * Enter a parse tree produced by the `DownTraversal` + * labeled alternative in `SelectionAutoCompleteParser.downTraversalExpr`. + * @param ctx the parse tree + */ + enterDownTraversal?: (ctx: DownTraversalContext) => void; + /** + * Exit a parse tree produced by the `DownTraversal` + * labeled alternative in `SelectionAutoCompleteParser.downTraversalExpr`. + * @param ctx the parse tree + */ + exitDownTraversal?: (ctx: DownTraversalContext) => void; + /** * Enter a parse tree produced by the `QuotedStringValue` * labeled alternative in `SelectionAutoCompleteParser.value`. @@ -531,6 +404,143 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { */ exitUnquotedStringValue?: (ctx: UnquotedStringValueContext) => void; + /** + * Enter a parse tree produced by the `IncompleteAttributeExpressionMissingValue` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterIncompleteAttributeExpressionMissingValue?: ( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) => void; + /** + * Exit a parse tree produced by the `IncompleteAttributeExpressionMissingValue` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitIncompleteAttributeExpressionMissingValue?: ( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) => void; + + /** + * Enter a parse tree produced by the `ExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => void; + /** + * Exit a parse tree produced by the `ExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UnclosedExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterUnclosedExpressionlessFunctionExpression?: ( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) => void; + /** + * Exit a parse tree produced by the `UnclosedExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitUnclosedExpressionlessFunctionExpression?: ( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) => void; + + /** + * Enter a parse tree produced by the `UnclosedFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => void; + /** + * Exit a parse tree produced by the `UnclosedFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UnclosedParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => void; + /** + * Exit a parse tree produced by the `UnclosedParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => void; + + /** + * Enter a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterExpressionlessParenthesizedExpressionWrapper?: ( + ctx: ExpressionlessParenthesizedExpressionWrapperContext, + ) => void; + /** + * Exit a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitExpressionlessParenthesizedExpressionWrapper?: ( + ctx: ExpressionlessParenthesizedExpressionWrapperContext, + ) => void; + + /** + * Enter a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterUnclosedExpressionlessParenthesizedExpression?: ( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) => void; + /** + * Exit a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitUnclosedExpressionlessParenthesizedExpression?: ( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) => void; + + /** + * Enter a parse tree produced by the `IncompletePlusTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterIncompletePlusTraversalExpression?: (ctx: IncompletePlusTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `IncompletePlusTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitIncompletePlusTraversalExpression?: (ctx: IncompletePlusTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `IncompleteAttributeExpressionMissingKey` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + enterIncompleteAttributeExpressionMissingKey?: ( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) => void; + /** + * Exit a parse tree produced by the `IncompleteAttributeExpressionMissingKey` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + */ + exitIncompleteAttributeExpressionMissingKey?: ( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) => void; + /** * Enter a parse tree produced by `SelectionAutoCompleteParser.start`. * @param ctx the parse tree @@ -576,15 +586,15 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { exitParenthesizedExpr?: (ctx: ParenthesizedExprContext) => void; /** - * Enter a parse tree produced by `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * Enter a parse tree produced by `SelectionAutoCompleteParser.incompleteExpr`. * @param ctx the parse tree */ - enterIncompleteExpressionsWrapper?: (ctx: IncompleteExpressionsWrapperContext) => void; + enterIncompleteExpr?: (ctx: IncompleteExprContext) => void; /** - * Exit a parse tree produced by `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * Exit a parse tree produced by `SelectionAutoCompleteParser.incompleteExpr`. * @param ctx the parse tree */ - exitIncompleteExpressionsWrapper?: (ctx: IncompleteExpressionsWrapperContext) => void; + exitIncompleteExpr?: (ctx: IncompleteExprContext) => void; /** * Enter a parse tree produced by `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. @@ -598,26 +608,26 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { exitExpressionLessParenthesizedExpr?: (ctx: ExpressionLessParenthesizedExprContext) => void; /** - * Enter a parse tree produced by `SelectionAutoCompleteParser.upTraversalExp`. + * Enter a parse tree produced by `SelectionAutoCompleteParser.upTraversalExpr`. * @param ctx the parse tree */ - enterUpTraversalExp?: (ctx: UpTraversalExpContext) => void; + enterUpTraversalExpr?: (ctx: UpTraversalExprContext) => void; /** - * Exit a parse tree produced by `SelectionAutoCompleteParser.upTraversalExp`. + * Exit a parse tree produced by `SelectionAutoCompleteParser.upTraversalExpr`. * @param ctx the parse tree */ - exitUpTraversalExp?: (ctx: UpTraversalExpContext) => void; + exitUpTraversalExpr?: (ctx: UpTraversalExprContext) => void; /** - * Enter a parse tree produced by `SelectionAutoCompleteParser.downTraversalExp`. + * Enter a parse tree produced by `SelectionAutoCompleteParser.downTraversalExpr`. * @param ctx the parse tree */ - enterDownTraversalExp?: (ctx: DownTraversalExpContext) => void; + enterDownTraversalExpr?: (ctx: DownTraversalExprContext) => void; /** - * Exit a parse tree produced by `SelectionAutoCompleteParser.downTraversalExp`. + * Exit a parse tree produced by `SelectionAutoCompleteParser.downTraversalExpr`. * @param ctx the parse tree */ - exitDownTraversalExp?: (ctx: DownTraversalExpContext) => void; + exitDownTraversalExpr?: (ctx: DownTraversalExprContext) => void; /** * Enter a parse tree produced by `SelectionAutoCompleteParser.traversal`. @@ -730,26 +740,92 @@ export interface SelectionAutoCompleteListener extends ParseTreeListener { exitRightParenToken?: (ctx: RightParenTokenContext) => void; /** - * Enter a parse tree produced by `SelectionAutoCompleteParser.afterExpressionWhitespace`. + * Enter a parse tree produced by `SelectionAutoCompleteParser.attributeValueWhitespace`. + * @param ctx the parse tree + */ + enterAttributeValueWhitespace?: (ctx: AttributeValueWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.attributeValueWhitespace`. + * @param ctx the parse tree + */ + exitAttributeValueWhitespace?: (ctx: AttributeValueWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.postAttributeValueWhitespace`. + * @param ctx the parse tree + */ + enterPostAttributeValueWhitespace?: (ctx: PostAttributeValueWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.postAttributeValueWhitespace`. + * @param ctx the parse tree + */ + exitPostAttributeValueWhitespace?: (ctx: PostAttributeValueWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.postExpressionWhitespace`. + * @param ctx the parse tree + */ + enterPostExpressionWhitespace?: (ctx: PostExpressionWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.postExpressionWhitespace`. + * @param ctx the parse tree + */ + exitPostExpressionWhitespace?: (ctx: PostExpressionWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.postNotOperatorWhitespace`. + * @param ctx the parse tree + */ + enterPostNotOperatorWhitespace?: (ctx: PostNotOperatorWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.postNotOperatorWhitespace`. + * @param ctx the parse tree + */ + exitPostNotOperatorWhitespace?: (ctx: PostNotOperatorWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.postLogicalOperatorWhitespace`. + * @param ctx the parse tree + */ + enterPostLogicalOperatorWhitespace?: (ctx: PostLogicalOperatorWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.postLogicalOperatorWhitespace`. + * @param ctx the parse tree + */ + exitPostLogicalOperatorWhitespace?: (ctx: PostLogicalOperatorWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.postNeighborTraversalWhitespace`. + * @param ctx the parse tree + */ + enterPostNeighborTraversalWhitespace?: (ctx: PostNeighborTraversalWhitespaceContext) => void; + /** + * Exit a parse tree produced by `SelectionAutoCompleteParser.postNeighborTraversalWhitespace`. + * @param ctx the parse tree + */ + exitPostNeighborTraversalWhitespace?: (ctx: PostNeighborTraversalWhitespaceContext) => void; + + /** + * Enter a parse tree produced by `SelectionAutoCompleteParser.postUpwardTraversalWhitespace`. * @param ctx the parse tree */ - enterAfterExpressionWhitespace?: (ctx: AfterExpressionWhitespaceContext) => void; + enterPostUpwardTraversalWhitespace?: (ctx: PostUpwardTraversalWhitespaceContext) => void; /** - * Exit a parse tree produced by `SelectionAutoCompleteParser.afterExpressionWhitespace`. + * Exit a parse tree produced by `SelectionAutoCompleteParser.postUpwardTraversalWhitespace`. * @param ctx the parse tree */ - exitAfterExpressionWhitespace?: (ctx: AfterExpressionWhitespaceContext) => void; + exitPostUpwardTraversalWhitespace?: (ctx: PostUpwardTraversalWhitespaceContext) => void; /** - * Enter a parse tree produced by `SelectionAutoCompleteParser.afterLogicalOperatorWhitespace`. + * Enter a parse tree produced by `SelectionAutoCompleteParser.postDownwardTraversalWhitespace`. * @param ctx the parse tree */ - enterAfterLogicalOperatorWhitespace?: (ctx: AfterLogicalOperatorWhitespaceContext) => void; + enterPostDownwardTraversalWhitespace?: (ctx: PostDownwardTraversalWhitespaceContext) => void; /** - * Exit a parse tree produced by `SelectionAutoCompleteParser.afterLogicalOperatorWhitespace`. + * Exit a parse tree produced by `SelectionAutoCompleteParser.postDownwardTraversalWhitespace`. * @param ctx the parse tree */ - exitAfterLogicalOperatorWhitespace?: (ctx: AfterLogicalOperatorWhitespaceContext) => void; + exitPostDownwardTraversalWhitespace?: (ctx: PostDownwardTraversalWhitespaceContext) => void; /** * Enter a parse tree produced by `SelectionAutoCompleteParser.value`. diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts index b45a64e19042c..ecd3f257543a8 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteParser.ts @@ -38,10 +38,10 @@ export class SelectionAutoCompleteParser extends Parser { public static readonly RULE_expr = 1; public static readonly RULE_traversalAllowedExpr = 2; public static readonly RULE_parenthesizedExpr = 3; - public static readonly RULE_incompleteExpressionsWrapper = 4; + public static readonly RULE_incompleteExpr = 4; public static readonly RULE_expressionLessParenthesizedExpr = 5; - public static readonly RULE_upTraversalExp = 6; - public static readonly RULE_downTraversalExp = 7; + public static readonly RULE_upTraversalExpr = 6; + public static readonly RULE_downTraversalExpr = 7; public static readonly RULE_traversal = 8; public static readonly RULE_attributeName = 9; public static readonly RULE_attributeValue = 10; @@ -52,19 +52,25 @@ export class SelectionAutoCompleteParser extends Parser { public static readonly RULE_colonToken = 15; public static readonly RULE_leftParenToken = 16; public static readonly RULE_rightParenToken = 17; - public static readonly RULE_afterExpressionWhitespace = 18; - public static readonly RULE_afterLogicalOperatorWhitespace = 19; - public static readonly RULE_value = 20; + public static readonly RULE_attributeValueWhitespace = 18; + public static readonly RULE_postAttributeValueWhitespace = 19; + public static readonly RULE_postExpressionWhitespace = 20; + public static readonly RULE_postNotOperatorWhitespace = 21; + public static readonly RULE_postLogicalOperatorWhitespace = 22; + public static readonly RULE_postNeighborTraversalWhitespace = 23; + public static readonly RULE_postUpwardTraversalWhitespace = 24; + public static readonly RULE_postDownwardTraversalWhitespace = 25; + public static readonly RULE_value = 26; // tslint:disable:no-trailing-whitespace public static readonly ruleNames: string[] = [ 'start', 'expr', 'traversalAllowedExpr', 'parenthesizedExpr', - 'incompleteExpressionsWrapper', + 'incompleteExpr', 'expressionLessParenthesizedExpr', - 'upTraversalExp', - 'downTraversalExp', + 'upTraversalExpr', + 'downTraversalExpr', 'traversal', 'attributeName', 'attributeValue', @@ -75,8 +81,14 @@ export class SelectionAutoCompleteParser extends Parser { 'colonToken', 'leftParenToken', 'rightParenToken', - 'afterExpressionWhitespace', - 'afterLogicalOperatorWhitespace', + 'attributeValueWhitespace', + 'postAttributeValueWhitespace', + 'postExpressionWhitespace', + 'postNotOperatorWhitespace', + 'postLogicalOperatorWhitespace', + 'postNeighborTraversalWhitespace', + 'postUpwardTraversalWhitespace', + 'postDownwardTraversalWhitespace', 'value', ]; @@ -155,9 +167,9 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 42; + this.state = 54; this.expr(0); - this.state = 43; + this.state = 55; this.match(SelectionAutoCompleteParser.EOF); } } catch (re) { @@ -192,7 +204,7 @@ export class SelectionAutoCompleteParser extends Parser { let _alt: number; this.enterOuterAlt(_localctx, 1); { - this.state = 75; + this.state = 81; this._errHandler.sync(this); switch (this.interpreter.adaptivePredict(this._input, 0, this._ctx)) { case 1: @@ -201,10 +213,8 @@ export class SelectionAutoCompleteParser extends Parser { this._ctx = _localctx; _prevctx = _localctx; - this.state = 46; + this.state = 58; this.traversalAllowedExpr(); - this.state = 47; - this.afterExpressionWhitespace(); } break; @@ -213,14 +223,12 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UpAndDownTraversalExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 49; - this.upTraversalExp(); - this.state = 50; + this.state = 59; + this.upTraversalExpr(); + this.state = 60; this.traversalAllowedExpr(); - this.state = 51; - this.downTraversalExp(); - this.state = 52; - this.afterExpressionWhitespace(); + this.state = 61; + this.downTraversalExpr(); } break; @@ -229,12 +237,10 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UpTraversalExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 54; - this.upTraversalExp(); - this.state = 55; + this.state = 63; + this.upTraversalExpr(); + this.state = 64; this.traversalAllowedExpr(); - this.state = 56; - this.afterExpressionWhitespace(); } break; @@ -243,12 +249,10 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new DownTraversalExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 58; + this.state = 66; this.traversalAllowedExpr(); - this.state = 59; - this.downTraversalExp(); - this.state = 60; - this.afterExpressionWhitespace(); + this.state = 67; + this.downTraversalExpr(); } break; @@ -257,14 +261,12 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new NotExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 62; + this.state = 69; this.notToken(); - this.state = 63; - this.afterLogicalOperatorWhitespace(); - this.state = 64; - this.expr(0); - this.state = 65; - this.afterExpressionWhitespace(); + this.state = 70; + this.postNotOperatorWhitespace(); + this.state = 71; + this.expr(9); } break; @@ -273,10 +275,10 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new IncompleteNotExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 67; + this.state = 73; this.notToken(); - this.state = 68; - this.afterLogicalOperatorWhitespace(); + this.state = 74; + this.postNotOperatorWhitespace(); } break; @@ -285,10 +287,10 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new AllExpressionContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 70; + this.state = 76; this.match(SelectionAutoCompleteParser.STAR); - this.state = 71; - this.afterExpressionWhitespace(); + this.state = 77; + this.postExpressionWhitespace(); } break; @@ -297,15 +299,15 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UnmatchedValueContext(_localctx); this._ctx = _localctx; _prevctx = _localctx; - this.state = 72; + this.state = 78; this.value(); - this.state = 73; - this.afterExpressionWhitespace(); + this.state = 79; + this.postExpressionWhitespace(); } break; } this._ctx._stop = this._input.tryLT(-1); - this.state = 108; + this.state = 107; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { @@ -315,7 +317,7 @@ export class SelectionAutoCompleteParser extends Parser { } _prevctx = _localctx; { - this.state = 106; + this.state = 105; this._errHandler.sync(this); switch (this.interpreter.adaptivePredict(this._input, 1, this._ctx)) { case 1: @@ -326,20 +328,16 @@ export class SelectionAutoCompleteParser extends Parser { _startState, SelectionAutoCompleteParser.RULE_expr, ); - this.state = 77; + this.state = 83; if (!this.precpred(this._ctx, 8)) { throw this.createFailedPredicateException('this.precpred(this._ctx, 8)'); } - this.state = 78; - this.afterExpressionWhitespace(); - this.state = 79; + this.state = 84; this.andToken(); - this.state = 80; - this.afterLogicalOperatorWhitespace(); - this.state = 81; - this.expr(0); - this.state = 82; - this.afterExpressionWhitespace(); + this.state = 85; + this.postLogicalOperatorWhitespace(); + this.state = 86; + this.expr(9); } break; @@ -351,20 +349,16 @@ export class SelectionAutoCompleteParser extends Parser { _startState, SelectionAutoCompleteParser.RULE_expr, ); - this.state = 84; + this.state = 88; if (!this.precpred(this._ctx, 7)) { throw this.createFailedPredicateException('this.precpred(this._ctx, 7)'); } - this.state = 85; - this.afterExpressionWhitespace(); - this.state = 86; - this.orToken(); - this.state = 87; - this.afterLogicalOperatorWhitespace(); - this.state = 88; - this.expr(0); this.state = 89; - this.afterExpressionWhitespace(); + this.orToken(); + this.state = 90; + this.postLogicalOperatorWhitespace(); + this.state = 91; + this.expr(8); } break; @@ -378,16 +372,14 @@ export class SelectionAutoCompleteParser extends Parser { _startState, SelectionAutoCompleteParser.RULE_expr, ); - this.state = 91; + this.state = 93; if (!this.precpred(this._ctx, 6)) { throw this.createFailedPredicateException('this.precpred(this._ctx, 6)'); } - this.state = 92; - this.afterExpressionWhitespace(); - this.state = 93; - this.andToken(); this.state = 94; - this.afterLogicalOperatorWhitespace(); + this.andToken(); + this.state = 95; + this.postLogicalOperatorWhitespace(); } break; @@ -401,16 +393,14 @@ export class SelectionAutoCompleteParser extends Parser { _startState, SelectionAutoCompleteParser.RULE_expr, ); - this.state = 96; + this.state = 97; if (!this.precpred(this._ctx, 5)) { throw this.createFailedPredicateException('this.precpred(this._ctx, 5)'); } - this.state = 97; - this.afterExpressionWhitespace(); this.state = 98; this.orToken(); this.state = 99; - this.afterLogicalOperatorWhitespace(); + this.postLogicalOperatorWhitespace(); } break; @@ -429,17 +419,15 @@ export class SelectionAutoCompleteParser extends Parser { throw this.createFailedPredicateException('this.precpred(this._ctx, 3)'); } this.state = 102; - this.afterExpressionWhitespace(); - this.state = 103; this.value(); - this.state = 104; - this.afterLogicalOperatorWhitespace(); + this.state = 103; + this.postLogicalOperatorWhitespace(); } break; } } } - this.state = 110; + this.state = 109; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); } @@ -472,12 +460,14 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new AttributeExpressionContext(_localctx); this.enterOuterAlt(_localctx, 1); { - this.state = 111; + this.state = 110; this.attributeName(); - this.state = 112; + this.state = 111; this.colonToken(); - this.state = 113; + this.state = 112; this.attributeValue(); + this.state = 113; + this.postAttributeValueWhitespace(); } break; @@ -493,7 +483,7 @@ export class SelectionAutoCompleteParser extends Parser { break; case 3: - _localctx = new ParenthesizedExpressionWrapperContext(_localctx); + _localctx = new TraversalAllowedParenthesizedExpressionContext(_localctx); this.enterOuterAlt(_localctx, 3); { this.state = 118; @@ -506,7 +496,7 @@ export class SelectionAutoCompleteParser extends Parser { this.enterOuterAlt(_localctx, 4); { this.state = 119; - this.incompleteExpressionsWrapper(); + this.incompleteExpr(); } break; } @@ -534,9 +524,13 @@ export class SelectionAutoCompleteParser extends Parser { this.state = 122; this.leftParenToken(); this.state = 123; - this.expr(0); + this.postLogicalOperatorWhitespace(); this.state = 124; + this.expr(0); + this.state = 125; this.rightParenToken(); + this.state = 126; + this.postExpressionWhitespace(); } } catch (re) { if (re instanceof RecognitionException) { @@ -552,25 +546,24 @@ export class SelectionAutoCompleteParser extends Parser { return _localctx; } // @RuleVersion(0) - public incompleteExpressionsWrapper(): IncompleteExpressionsWrapperContext { - let _localctx: IncompleteExpressionsWrapperContext = new IncompleteExpressionsWrapperContext( - this._ctx, - this.state, - ); - this.enterRule(_localctx, 8, SelectionAutoCompleteParser.RULE_incompleteExpressionsWrapper); + public incompleteExpr(): IncompleteExprContext { + let _localctx: IncompleteExprContext = new IncompleteExprContext(this._ctx, this.state); + this.enterRule(_localctx, 8, SelectionAutoCompleteParser.RULE_incompleteExpr); try { let _alt: number; - this.state = 152; + this.state = 161; this._errHandler.sync(this); switch (this.interpreter.adaptivePredict(this._input, 5, this._ctx)) { case 1: _localctx = new IncompleteAttributeExpressionMissingValueContext(_localctx); this.enterOuterAlt(_localctx, 1); { - this.state = 126; + this.state = 128; this.attributeName(); - this.state = 127; + this.state = 129; this.colonToken(); + this.state = 130; + this.attributeValueWhitespace(); } break; @@ -578,9 +571,9 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new ExpressionlessFunctionExpressionContext(_localctx); this.enterOuterAlt(_localctx, 2); { - this.state = 129; + this.state = 132; this.functionName(); - this.state = 130; + this.state = 133; this.expressionLessParenthesizedExpr(); } break; @@ -589,10 +582,12 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UnclosedExpressionlessFunctionExpressionContext(_localctx); this.enterOuterAlt(_localctx, 3); { - this.state = 132; + this.state = 135; this.functionName(); - this.state = 133; + this.state = 136; this.leftParenToken(); + this.state = 137; + this.postLogicalOperatorWhitespace(); } break; @@ -600,11 +595,11 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UnclosedFunctionExpressionContext(_localctx); this.enterOuterAlt(_localctx, 4); { - this.state = 135; + this.state = 139; this.functionName(); - this.state = 136; + this.state = 140; this.leftParenToken(); - this.state = 137; + this.state = 141; this.expr(0); } break; @@ -613,9 +608,11 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UnclosedParenthesizedExpressionContext(_localctx); this.enterOuterAlt(_localctx, 5); { - this.state = 139; + this.state = 143; this.leftParenToken(); - this.state = 140; + this.state = 144; + this.postLogicalOperatorWhitespace(); + this.state = 145; this.expr(0); } break; @@ -624,7 +621,7 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new ExpressionlessParenthesizedExpressionWrapperContext(_localctx); this.enterOuterAlt(_localctx, 6); { - this.state = 142; + this.state = 147; this.expressionLessParenthesizedExpr(); } break; @@ -633,16 +630,18 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UnclosedExpressionlessParenthesizedExpressionContext(_localctx); this.enterOuterAlt(_localctx, 7); { - this.state = 143; + this.state = 148; this.leftParenToken(); + this.state = 149; + this.postLogicalOperatorWhitespace(); } break; case 8: - _localctx = new IncompleteTraversalExpressionContext(_localctx); + _localctx = new IncompletePlusTraversalExpressionContext(_localctx); this.enterOuterAlt(_localctx, 8); { - this.state = 145; + this.state = 152; this._errHandler.sync(this); _alt = 1; do { @@ -650,7 +649,7 @@ export class SelectionAutoCompleteParser extends Parser { case 1: { { - this.state = 144; + this.state = 151; this.match(SelectionAutoCompleteParser.PLUS); } } @@ -658,10 +657,12 @@ export class SelectionAutoCompleteParser extends Parser { default: throw new NoViableAltException(this); } - this.state = 147; + this.state = 154; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 4, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); + this.state = 156; + this.postNeighborTraversalWhitespace(); } break; @@ -669,10 +670,12 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new IncompleteAttributeExpressionMissingKeyContext(_localctx); this.enterOuterAlt(_localctx, 9); { - this.state = 149; + this.state = 157; this.colonToken(); - this.state = 150; + this.state = 158; this.attributeValue(); + this.state = 159; + this.postExpressionWhitespace(); } break; } @@ -698,10 +701,14 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new ExpressionlessParenthesizedExpressionContext(_localctx); this.enterOuterAlt(_localctx, 1); { - this.state = 154; + this.state = 163; this.leftParenToken(); - this.state = 155; + this.state = 164; + this.postLogicalOperatorWhitespace(); + this.state = 165; this.rightParenToken(); + this.state = 166; + this.postExpressionWhitespace(); } } catch (re) { if (re instanceof RecognitionException) { @@ -717,15 +724,17 @@ export class SelectionAutoCompleteParser extends Parser { return _localctx; } // @RuleVersion(0) - public upTraversalExp(): UpTraversalExpContext { - let _localctx: UpTraversalExpContext = new UpTraversalExpContext(this._ctx, this.state); - this.enterRule(_localctx, 12, SelectionAutoCompleteParser.RULE_upTraversalExp); + public upTraversalExpr(): UpTraversalExprContext { + let _localctx: UpTraversalExprContext = new UpTraversalExprContext(this._ctx, this.state); + this.enterRule(_localctx, 12, SelectionAutoCompleteParser.RULE_upTraversalExpr); try { _localctx = new UpTraversalContext(_localctx); this.enterOuterAlt(_localctx, 1); { - this.state = 157; + this.state = 168; this.traversal(); + this.state = 169; + this.postUpwardTraversalWhitespace(); } } catch (re) { if (re instanceof RecognitionException) { @@ -741,15 +750,17 @@ export class SelectionAutoCompleteParser extends Parser { return _localctx; } // @RuleVersion(0) - public downTraversalExp(): DownTraversalExpContext { - let _localctx: DownTraversalExpContext = new DownTraversalExpContext(this._ctx, this.state); - this.enterRule(_localctx, 14, SelectionAutoCompleteParser.RULE_downTraversalExp); + public downTraversalExpr(): DownTraversalExprContext { + let _localctx: DownTraversalExprContext = new DownTraversalExprContext(this._ctx, this.state); + this.enterRule(_localctx, 14, SelectionAutoCompleteParser.RULE_downTraversalExpr); try { _localctx = new DownTraversalContext(_localctx); this.enterOuterAlt(_localctx, 1); { - this.state = 159; + this.state = 171; this.traversal(); + this.state = 172; + this.postDownwardTraversalWhitespace(); } } catch (re) { if (re instanceof RecognitionException) { @@ -770,20 +781,20 @@ export class SelectionAutoCompleteParser extends Parser { this.enterRule(_localctx, 16, SelectionAutoCompleteParser.RULE_traversal); try { let _alt: number; - this.state = 167; + this.state = 180; this._errHandler.sync(this); switch (this._input.LA(1)) { case SelectionAutoCompleteParser.STAR: this.enterOuterAlt(_localctx, 1); { - this.state = 161; + this.state = 174; this.match(SelectionAutoCompleteParser.STAR); } break; case SelectionAutoCompleteParser.PLUS: this.enterOuterAlt(_localctx, 2); { - this.state = 163; + this.state = 176; this._errHandler.sync(this); _alt = 1; do { @@ -791,7 +802,7 @@ export class SelectionAutoCompleteParser extends Parser { case 1: { { - this.state = 162; + this.state = 175; this.match(SelectionAutoCompleteParser.PLUS); } } @@ -799,7 +810,7 @@ export class SelectionAutoCompleteParser extends Parser { default: throw new NoViableAltException(this); } - this.state = 165; + this.state = 178; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 6, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); @@ -828,7 +839,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 169; + this.state = 182; this.match(SelectionAutoCompleteParser.IDENTIFIER); } } catch (re) { @@ -851,7 +862,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 171; + this.state = 184; this.value(); } } catch (re) { @@ -874,7 +885,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 173; + this.state = 186; this.match(SelectionAutoCompleteParser.IDENTIFIER); } } catch (re) { @@ -897,7 +908,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 175; + this.state = 188; this.match(SelectionAutoCompleteParser.OR); } } catch (re) { @@ -920,7 +931,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 177; + this.state = 190; this.match(SelectionAutoCompleteParser.AND); } } catch (re) { @@ -943,7 +954,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 179; + this.state = 192; this.match(SelectionAutoCompleteParser.NOT); } } catch (re) { @@ -966,7 +977,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 181; + this.state = 194; this.match(SelectionAutoCompleteParser.COLON); } } catch (re) { @@ -989,7 +1000,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 183; + this.state = 196; this.match(SelectionAutoCompleteParser.LPAREN); } } catch (re) { @@ -1012,7 +1023,7 @@ export class SelectionAutoCompleteParser extends Parser { try { this.enterOuterAlt(_localctx, 1); { - this.state = 185; + this.state = 198; this.match(SelectionAutoCompleteParser.RPAREN); } } catch (re) { @@ -1029,29 +1040,29 @@ export class SelectionAutoCompleteParser extends Parser { return _localctx; } // @RuleVersion(0) - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - const _localctx: AfterExpressionWhitespaceContext = new AfterExpressionWhitespaceContext( + public attributeValueWhitespace(): AttributeValueWhitespaceContext { + const _localctx: AttributeValueWhitespaceContext = new AttributeValueWhitespaceContext( this._ctx, this.state, ); - this.enterRule(_localctx, 36, SelectionAutoCompleteParser.RULE_afterExpressionWhitespace); + this.enterRule(_localctx, 36, SelectionAutoCompleteParser.RULE_attributeValueWhitespace); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { - this.state = 190; + this.state = 203; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { - this.state = 187; + this.state = 200; this.match(SelectionAutoCompleteParser.WS); } } } - this.state = 192; + this.state = 205; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); } @@ -1070,27 +1081,29 @@ export class SelectionAutoCompleteParser extends Parser { return _localctx; } // @RuleVersion(0) - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - const _localctx: AfterLogicalOperatorWhitespaceContext = - new AfterLogicalOperatorWhitespaceContext(this._ctx, this.state); - this.enterRule(_localctx, 38, SelectionAutoCompleteParser.RULE_afterLogicalOperatorWhitespace); + public postAttributeValueWhitespace(): PostAttributeValueWhitespaceContext { + const _localctx: PostAttributeValueWhitespaceContext = new PostAttributeValueWhitespaceContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 38, SelectionAutoCompleteParser.RULE_postAttributeValueWhitespace); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { - this.state = 196; + this.state = 209; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 9, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { - this.state = 193; + this.state = 206; this.match(SelectionAutoCompleteParser.WS); } } } - this.state = 198; + this.state = 211; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 9, this._ctx); } @@ -1109,18 +1122,254 @@ export class SelectionAutoCompleteParser extends Parser { return _localctx; } // @RuleVersion(0) + public postExpressionWhitespace(): PostExpressionWhitespaceContext { + const _localctx: PostExpressionWhitespaceContext = new PostExpressionWhitespaceContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 40, SelectionAutoCompleteParser.RULE_postExpressionWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 215; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 10, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 212; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 217; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 10, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public postNotOperatorWhitespace(): PostNotOperatorWhitespaceContext { + const _localctx: PostNotOperatorWhitespaceContext = new PostNotOperatorWhitespaceContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 42, SelectionAutoCompleteParser.RULE_postNotOperatorWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 221; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 11, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 218; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 223; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 11, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + const _localctx: PostLogicalOperatorWhitespaceContext = + new PostLogicalOperatorWhitespaceContext(this._ctx, this.state); + this.enterRule(_localctx, 44, SelectionAutoCompleteParser.RULE_postLogicalOperatorWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 227; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 224; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 229; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public postNeighborTraversalWhitespace(): PostNeighborTraversalWhitespaceContext { + const _localctx: PostNeighborTraversalWhitespaceContext = + new PostNeighborTraversalWhitespaceContext(this._ctx, this.state); + this.enterRule(_localctx, 46, SelectionAutoCompleteParser.RULE_postNeighborTraversalWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 233; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 13, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 230; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 235; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 13, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public postUpwardTraversalWhitespace(): PostUpwardTraversalWhitespaceContext { + const _localctx: PostUpwardTraversalWhitespaceContext = + new PostUpwardTraversalWhitespaceContext(this._ctx, this.state); + this.enterRule(_localctx, 48, SelectionAutoCompleteParser.RULE_postUpwardTraversalWhitespace); + let _la: number; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 239; + this._errHandler.sync(this); + _la = this._input.LA(1); + while (_la === SelectionAutoCompleteParser.WS) { + { + { + this.state = 236; + this.match(SelectionAutoCompleteParser.WS); + } + } + this.state = 241; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public postDownwardTraversalWhitespace(): PostDownwardTraversalWhitespaceContext { + const _localctx: PostDownwardTraversalWhitespaceContext = + new PostDownwardTraversalWhitespaceContext(this._ctx, this.state); + this.enterRule(_localctx, 50, SelectionAutoCompleteParser.RULE_postDownwardTraversalWhitespace); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 245; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 15, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + { + { + this.state = 242; + this.match(SelectionAutoCompleteParser.WS); + } + } + } + this.state = 247; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 15, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) public value(): ValueContext { let _localctx: ValueContext = new ValueContext(this._ctx, this.state); - this.enterRule(_localctx, 40, SelectionAutoCompleteParser.RULE_value); + this.enterRule(_localctx, 52, SelectionAutoCompleteParser.RULE_value); try { - this.state = 203; + this.state = 252; this._errHandler.sync(this); switch (this._input.LA(1)) { case SelectionAutoCompleteParser.QUOTED_STRING: _localctx = new QuotedStringValueContext(_localctx); this.enterOuterAlt(_localctx, 1); { - this.state = 199; + this.state = 248; this.match(SelectionAutoCompleteParser.QUOTED_STRING); } break; @@ -1128,7 +1377,7 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new IncompleteLeftQuotedStringValueContext(_localctx); this.enterOuterAlt(_localctx, 2); { - this.state = 200; + this.state = 249; this.match(SelectionAutoCompleteParser.INCOMPLETE_LEFT_QUOTED_STRING); } break; @@ -1136,7 +1385,7 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new IncompleteRightQuotedStringValueContext(_localctx); this.enterOuterAlt(_localctx, 3); { - this.state = 201; + this.state = 250; this.match(SelectionAutoCompleteParser.INCOMPLETE_RIGHT_QUOTED_STRING); } break; @@ -1144,7 +1393,7 @@ export class SelectionAutoCompleteParser extends Parser { _localctx = new UnquotedStringValueContext(_localctx); this.enterOuterAlt(_localctx, 4); { - this.state = 202; + this.state = 251; this.match(SelectionAutoCompleteParser.IDENTIFIER); } break; @@ -1193,94 +1442,117 @@ export class SelectionAutoCompleteParser extends Parser { } public static readonly _serializedATN: string = - '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x10\xD0\x04\x02' + - '\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07' + - '\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r\x04' + - '\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t\x12\x04' + - '\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x03\x02\x03\x02\x03' + - '\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + - '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x10\u0101\x04' + + '\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04' + + '\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r' + + '\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t\x12' + + '\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t\x17' + + '\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04\x1C\t\x1C' + + '\x03\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + - '\x03\x03\x03\x03\x03\x03\x03\x05\x03N\n\x03\x03\x03\x03\x03\x03\x03\x03' + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x05\x03T\n\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + - '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x07\x03m' + - '\n\x03\f\x03\x0E\x03p\v\x03\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03' + - '\x04\x03\x04\x03\x04\x03\x04\x05\x04{\n\x04\x03\x05\x03\x05\x03\x05\x03' + - '\x05\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03' + - '\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03' + - '\x06\x03\x06\x06\x06\x94\n\x06\r\x06\x0E\x06\x95\x03\x06\x03\x06\x03\x06' + - '\x05\x06\x9B\n\x06\x03\x07\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03\t\x03' + - '\n\x03\n\x06\n\xA6\n\n\r\n\x0E\n\xA7\x05\n\xAA\n\n\x03\v\x03\v\x03\f\x03' + - '\f\x03\r\x03\r\x03\x0E\x03\x0E\x03\x0F\x03\x0F\x03\x10\x03\x10\x03\x11' + - '\x03\x11\x03\x12\x03\x12\x03\x13\x03\x13\x03\x14\x07\x14\xBF\n\x14\f\x14' + - '\x0E\x14\xC2\v\x14\x03\x15\x07\x15\xC5\n\x15\f\x15\x0E\x15\xC8\v\x15\x03' + - '\x16\x03\x16\x03\x16\x03\x16\x05\x16\xCE\n\x16\x03\x16\x02\x02\x03\x04' + - '\x17\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10\x02\x12\x02' + - '\x14\x02\x16\x02\x18\x02\x1A\x02\x1C\x02\x1E\x02 \x02"\x02$\x02&\x02' + - '(\x02*\x02\x02\x02\x02\xD9\x02,\x03\x02\x02\x02\x04M\x03\x02\x02\x02\x06' + - 'z\x03\x02\x02\x02\b|\x03\x02\x02\x02\n\x9A\x03\x02\x02\x02\f\x9C\x03\x02' + - '\x02\x02\x0E\x9F\x03\x02\x02\x02\x10\xA1\x03\x02\x02\x02\x12\xA9\x03\x02' + - '\x02\x02\x14\xAB\x03\x02\x02\x02\x16\xAD\x03\x02\x02\x02\x18\xAF\x03\x02' + - '\x02\x02\x1A\xB1\x03\x02\x02\x02\x1C\xB3\x03\x02\x02\x02\x1E\xB5\x03\x02' + - '\x02\x02 \xB7\x03\x02\x02\x02"\xB9\x03\x02\x02\x02$\xBB\x03\x02\x02\x02' + - '&\xC0\x03\x02\x02\x02(\xC6\x03\x02\x02\x02*\xCD\x03\x02\x02\x02,-\x05' + - '\x04\x03\x02-.\x07\x02\x02\x03.\x03\x03\x02\x02\x02/0\b\x03\x01\x0201' + - '\x05\x06\x04\x0212\x05&\x14\x022N\x03\x02\x02\x0234\x05\x0E\b\x0245\x05' + - '\x06\x04\x0256\x05\x10\t\x0267\x05&\x14\x027N\x03\x02\x02\x0289\x05\x0E' + - '\b\x029:\x05\x06\x04\x02:;\x05&\x14\x02;N\x03\x02\x02\x02<=\x05\x06\x04' + - '\x02=>\x05\x10\t\x02>?\x05&\x14\x02?N\x03\x02\x02\x02@A\x05\x1E\x10\x02' + - 'AB\x05(\x15\x02BC\x05\x04\x03\x02CD\x05&\x14\x02DN\x03\x02\x02\x02EF\x05' + - '\x1E\x10\x02FG\x05(\x15\x02GN\x03\x02\x02\x02HI\x07\x06\x02\x02IN\x05' + - '&\x14\x02JK\x05*\x16\x02KL\x05&\x14\x02LN\x03\x02\x02\x02M/\x03\x02\x02' + - '\x02M3\x03\x02\x02\x02M8\x03\x02\x02\x02M<\x03\x02\x02\x02M@\x03\x02\x02' + - '\x02ME\x03\x02\x02\x02MH\x03\x02\x02\x02MJ\x03\x02\x02\x02Nn\x03\x02\x02' + - '\x02OP\f\n\x02\x02PQ\x05&\x14\x02QR\x05\x1C\x0F\x02RS\x05(\x15\x02ST\x05' + - '\x04\x03\x02TU\x05&\x14\x02Um\x03\x02\x02\x02VW\f\t\x02\x02WX\x05&\x14' + - '\x02XY\x05\x1A\x0E\x02YZ\x05(\x15\x02Z[\x05\x04\x03\x02[\\\x05&\x14\x02' + - '\\m\x03\x02\x02\x02]^\f\b\x02\x02^_\x05&\x14\x02_`\x05\x1C\x0F\x02`a\x05' + - '(\x15\x02am\x03\x02\x02\x02bc\f\x07\x02\x02cd\x05&\x14\x02de\x05\x1A\x0E' + - '\x02ef\x05(\x15\x02fm\x03\x02\x02\x02gh\f\x05\x02\x02hi\x05&\x14\x02i' + - 'j\x05*\x16\x02jk\x05(\x15\x02km\x03\x02\x02\x02lO\x03\x02\x02\x02lV\x03' + - '\x02\x02\x02l]\x03\x02\x02\x02lb\x03\x02\x02\x02lg\x03\x02\x02\x02mp\x03' + - '\x02\x02\x02nl\x03\x02\x02\x02no\x03\x02\x02\x02o\x05\x03\x02\x02\x02' + - 'pn\x03\x02\x02\x02qr\x05\x14\v\x02rs\x05 \x11\x02st\x05\x16\f\x02t{\x03' + - '\x02\x02\x02uv\x05\x18\r\x02vw\x05\b\x05\x02w{\x03\x02\x02\x02x{\x05\b' + - '\x05\x02y{\x05\n\x06\x02zq\x03\x02\x02\x02zu\x03\x02\x02\x02zx\x03\x02' + - '\x02\x02zy\x03\x02\x02\x02{\x07\x03\x02\x02\x02|}\x05"\x12\x02}~\x05' + - '\x04\x03\x02~\x7F\x05$\x13\x02\x7F\t\x03\x02\x02\x02\x80\x81\x05\x14\v' + - '\x02\x81\x82\x05 \x11\x02\x82\x9B\x03\x02\x02\x02\x83\x84\x05\x18\r\x02' + - '\x84\x85\x05\f\x07\x02\x85\x9B\x03\x02\x02\x02\x86\x87\x05\x18\r\x02\x87' + - '\x88\x05"\x12\x02\x88\x9B\x03\x02\x02\x02\x89\x8A\x05\x18\r\x02\x8A\x8B' + - '\x05"\x12\x02\x8B\x8C\x05\x04\x03\x02\x8C\x9B\x03\x02\x02\x02\x8D\x8E' + - '\x05"\x12\x02\x8E\x8F\x05\x04\x03\x02\x8F\x9B\x03\x02\x02\x02\x90\x9B' + - '\x05\f\x07\x02\x91\x9B\x05"\x12\x02\x92\x94\x07\x07\x02\x02\x93\x92\x03' + - '\x02\x02\x02\x94\x95\x03\x02\x02\x02\x95\x93\x03\x02\x02\x02\x95\x96\x03' + - '\x02\x02\x02\x96\x9B\x03\x02\x02\x02\x97\x98\x05 \x11\x02\x98\x99\x05' + - '\x16\f\x02\x99\x9B\x03\x02\x02\x02\x9A\x80\x03\x02\x02\x02\x9A\x83\x03' + - '\x02\x02\x02\x9A\x86\x03\x02\x02\x02\x9A\x89\x03\x02\x02\x02\x9A\x8D\x03' + - '\x02\x02\x02\x9A\x90\x03\x02\x02\x02\x9A\x91\x03\x02\x02\x02\x9A\x93\x03' + - '\x02\x02\x02\x9A\x97\x03\x02\x02\x02\x9B\v\x03\x02\x02\x02\x9C\x9D\x05' + - '"\x12\x02\x9D\x9E\x05$\x13\x02\x9E\r\x03\x02\x02\x02\x9F\xA0\x05\x12' + - '\n\x02\xA0\x0F\x03\x02\x02\x02\xA1\xA2\x05\x12\n\x02\xA2\x11\x03\x02\x02' + - '\x02\xA3\xAA\x07\x06\x02\x02\xA4\xA6\x07\x07\x02\x02\xA5\xA4\x03\x02\x02' + - '\x02\xA6\xA7\x03\x02\x02\x02\xA7\xA5\x03\x02\x02\x02\xA7\xA8\x03\x02\x02' + - '\x02\xA8\xAA\x03\x02\x02\x02\xA9\xA3\x03\x02\x02\x02\xA9\xA5\x03\x02\x02' + - '\x02\xAA\x13\x03\x02\x02\x02\xAB\xAC\x07\x0F\x02\x02\xAC\x15\x03\x02\x02' + - '\x02\xAD\xAE\x05*\x16\x02\xAE\x17\x03\x02\x02\x02\xAF\xB0\x07\x0F\x02' + - '\x02\xB0\x19\x03\x02\x02\x02\xB1\xB2\x07\x04\x02\x02\xB2\x1B\x03\x02\x02' + - '\x02\xB3\xB4\x07\x03\x02\x02\xB4\x1D\x03\x02\x02\x02\xB5\xB6\x07\x05\x02' + - '\x02\xB6\x1F\x03\x02\x02\x02\xB7\xB8\x07\b\x02\x02\xB8!\x03\x02\x02\x02' + - '\xB9\xBA\x07\t\x02\x02\xBA#\x03\x02\x02\x02\xBB\xBC\x07\n\x02\x02\xBC' + - '%\x03\x02\x02\x02\xBD\xBF\x07\x10\x02\x02\xBE\xBD\x03\x02\x02\x02\xBF' + - '\xC2\x03\x02\x02\x02\xC0\xBE\x03\x02\x02\x02\xC0\xC1\x03\x02\x02\x02\xC1' + - "'\x03\x02\x02\x02\xC2\xC0\x03\x02\x02\x02\xC3\xC5\x07\x10\x02\x02\xC4" + - '\xC3\x03\x02\x02\x02\xC5\xC8\x03\x02\x02\x02\xC6\xC4\x03\x02\x02\x02\xC6' + - '\xC7\x03\x02\x02\x02\xC7)\x03\x02\x02\x02\xC8\xC6\x03\x02\x02\x02\xC9' + - '\xCE\x07\f\x02\x02\xCA\xCE\x07\r\x02\x02\xCB\xCE\x07\x0E\x02\x02\xCC\xCE' + - '\x07\x0F\x02\x02\xCD\xC9\x03\x02\x02\x02\xCD\xCA\x03\x02\x02\x02\xCD\xCB' + - '\x03\x02\x02\x02\xCD\xCC\x03\x02\x02\x02\xCE+\x03\x02\x02\x02\rMlnz\x95' + - '\x9A\xA7\xA9\xC0\xC6\xCD'; + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x07\x03l\n\x03\f\x03' + + '\x0E\x03o\v\x03\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04' + + '\x03\x04\x03\x04\x03\x04\x05\x04{\n\x04\x03\x05\x03\x05\x03\x05\x03\x05' + + '\x03\x05\x03\x05\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06' + + '\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06' + + '\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x06\x06' + + '\x9B\n\x06\r\x06\x0E\x06\x9C\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x05' + + '\x06\xA4\n\x06\x03\x07\x03\x07\x03\x07\x03\x07\x03\x07\x03\b\x03\b\x03' + + '\b\x03\t\x03\t\x03\t\x03\n\x03\n\x06\n\xB3\n\n\r\n\x0E\n\xB4\x05\n\xB7' + + '\n\n\x03\v\x03\v\x03\f\x03\f\x03\r\x03\r\x03\x0E\x03\x0E\x03\x0F\x03\x0F' + + '\x03\x10\x03\x10\x03\x11\x03\x11\x03\x12\x03\x12\x03\x13\x03\x13\x03\x14' + + '\x07\x14\xCC\n\x14\f\x14\x0E\x14\xCF\v\x14\x03\x15\x07\x15\xD2\n\x15\f' + + '\x15\x0E\x15\xD5\v\x15\x03\x16\x07\x16\xD8\n\x16\f\x16\x0E\x16\xDB\v\x16' + + '\x03\x17\x07\x17\xDE\n\x17\f\x17\x0E\x17\xE1\v\x17\x03\x18\x07\x18\xE4' + + '\n\x18\f\x18\x0E\x18\xE7\v\x18\x03\x19\x07\x19\xEA\n\x19\f\x19\x0E\x19' + + '\xED\v\x19\x03\x1A\x07\x1A\xF0\n\x1A\f\x1A\x0E\x1A\xF3\v\x1A\x03\x1B\x07' + + '\x1B\xF6\n\x1B\f\x1B\x0E\x1B\xF9\v\x1B\x03\x1C\x03\x1C\x03\x1C\x03\x1C' + + '\x05\x1C\xFF\n\x1C\x03\x1C\x02\x02\x03\x04\x1D\x02\x02\x04\x02\x06\x02' + + '\b\x02\n\x02\f\x02\x0E\x02\x10\x02\x12\x02\x14\x02\x16\x02\x18\x02\x1A' + + '\x02\x1C\x02\x1E\x02 \x02"\x02$\x02&\x02(\x02*\x02,\x02.\x020\x022\x02' + + '4\x026\x02\x02\x02\x02\u010A\x028\x03\x02\x02\x02\x04S\x03\x02\x02\x02' + + '\x06z\x03\x02\x02\x02\b|\x03\x02\x02\x02\n\xA3\x03\x02\x02\x02\f\xA5\x03' + + '\x02\x02\x02\x0E\xAA\x03\x02\x02\x02\x10\xAD\x03\x02\x02\x02\x12\xB6\x03' + + '\x02\x02\x02\x14\xB8\x03\x02\x02\x02\x16\xBA\x03\x02\x02\x02\x18\xBC\x03' + + '\x02\x02\x02\x1A\xBE\x03\x02\x02\x02\x1C\xC0\x03\x02\x02\x02\x1E\xC2\x03' + + '\x02\x02\x02 \xC4\x03\x02\x02\x02"\xC6\x03\x02\x02\x02$\xC8\x03\x02\x02' + + '\x02&\xCD\x03\x02\x02\x02(\xD3\x03\x02\x02\x02*\xD9\x03\x02\x02\x02,\xDF' + + '\x03\x02\x02\x02.\xE5\x03\x02\x02\x020\xEB\x03\x02\x02\x022\xF1\x03\x02' + + '\x02\x024\xF7\x03\x02\x02\x026\xFE\x03\x02\x02\x0289\x05\x04\x03\x029' + + ':\x07\x02\x02\x03:\x03\x03\x02\x02\x02;<\b\x03\x01\x02\x05\x0E\b\x02>?\x05\x06\x04\x02?@\x05\x10\t\x02@T\x03\x02\x02\x02A' + + 'B\x05\x0E\b\x02BC\x05\x06\x04\x02CT\x03\x02\x02\x02DE\x05\x06\x04\x02' + + 'EF\x05\x10\t\x02FT\x03\x02\x02\x02GH\x05\x1E\x10\x02HI\x05,\x17\x02IJ' + + '\x05\x04\x03\vJT\x03\x02\x02\x02KL\x05\x1E\x10\x02LM\x05,\x17\x02MT\x03' + + '\x02\x02\x02NO\x07\x06\x02\x02OT\x05*\x16\x02PQ\x056\x1C\x02QR\x05*\x16' + + '\x02RT\x03\x02\x02\x02S;\x03\x02\x02\x02S=\x03\x02\x02\x02SA\x03\x02\x02' + + '\x02SD\x03\x02\x02\x02SG\x03\x02\x02\x02SK\x03\x02\x02\x02SN\x03\x02\x02' + + '\x02SP\x03\x02\x02\x02Tm\x03\x02\x02\x02UV\f\n\x02\x02VW\x05\x1C\x0F\x02' + + 'WX\x05.\x18\x02XY\x05\x04\x03\vYl\x03\x02\x02\x02Z[\f\t\x02\x02[\\\x05' + + '\x1A\x0E\x02\\]\x05.\x18\x02]^\x05\x04\x03\n^l\x03\x02\x02\x02_`\f\b\x02' + + '\x02`a\x05\x1C\x0F\x02ab\x05.\x18\x02bl\x03\x02\x02\x02cd\f\x07\x02\x02' + + 'de\x05\x1A\x0E\x02ef\x05.\x18\x02fl\x03\x02\x02\x02gh\f\x05\x02\x02hi' + + '\x056\x1C\x02ij\x05.\x18\x02jl\x03\x02\x02\x02kU\x03\x02\x02\x02kZ\x03' + + '\x02\x02\x02k_\x03\x02\x02\x02kc\x03\x02\x02\x02kg\x03\x02\x02\x02lo\x03' + + '\x02\x02\x02mk\x03\x02\x02\x02mn\x03\x02\x02\x02n\x05\x03\x02\x02\x02' + + 'om\x03\x02\x02\x02pq\x05\x14\v\x02qr\x05 \x11\x02rs\x05\x16\f\x02st\x05' + + '(\x15\x02t{\x03\x02\x02\x02uv\x05\x18\r\x02vw\x05\b\x05\x02w{\x03\x02' + + '\x02\x02x{\x05\b\x05\x02y{\x05\n\x06\x02zp\x03\x02\x02\x02zu\x03\x02\x02' + + '\x02zx\x03\x02\x02\x02zy\x03\x02\x02\x02{\x07\x03\x02\x02\x02|}\x05"' + + '\x12\x02}~\x05.\x18\x02~\x7F\x05\x04\x03\x02\x7F\x80\x05$\x13\x02\x80' + + '\x81\x05*\x16\x02\x81\t\x03\x02\x02\x02\x82\x83\x05\x14\v\x02\x83\x84' + + '\x05 \x11\x02\x84\x85\x05&\x14\x02\x85\xA4\x03\x02\x02\x02\x86\x87\x05' + + '\x18\r\x02\x87\x88\x05\f\x07\x02\x88\xA4\x03\x02\x02\x02\x89\x8A\x05\x18' + + '\r\x02\x8A\x8B\x05"\x12\x02\x8B\x8C\x05.\x18\x02\x8C\xA4\x03\x02\x02' + + '\x02\x8D\x8E\x05\x18\r\x02\x8E\x8F\x05"\x12\x02\x8F\x90\x05\x04\x03\x02' + + '\x90\xA4\x03\x02\x02\x02\x91\x92\x05"\x12\x02\x92\x93\x05.\x18\x02\x93' + + '\x94\x05\x04\x03\x02\x94\xA4\x03\x02\x02\x02\x95\xA4\x05\f\x07\x02\x96' + + '\x97\x05"\x12\x02\x97\x98\x05.\x18\x02\x98\xA4\x03\x02\x02\x02\x99\x9B' + + '\x07\x07\x02\x02\x9A\x99\x03\x02\x02\x02\x9B\x9C\x03\x02\x02\x02\x9C\x9A' + + '\x03\x02\x02\x02\x9C\x9D\x03\x02\x02\x02\x9D\x9E\x03\x02\x02\x02\x9E\xA4' + + '\x050\x19\x02\x9F\xA0\x05 \x11\x02\xA0\xA1\x05\x16\f\x02\xA1\xA2\x05*' + + '\x16\x02\xA2\xA4\x03\x02\x02\x02\xA3\x82\x03\x02\x02\x02\xA3\x86\x03\x02' + + '\x02\x02\xA3\x89\x03\x02\x02\x02\xA3\x8D\x03\x02\x02\x02\xA3\x91\x03\x02' + + '\x02\x02\xA3\x95\x03\x02\x02\x02\xA3\x96\x03\x02\x02\x02\xA3\x9A\x03\x02' + + '\x02\x02\xA3\x9F\x03\x02\x02\x02\xA4\v\x03\x02\x02\x02\xA5\xA6\x05"\x12' + + '\x02\xA6\xA7\x05.\x18\x02\xA7\xA8\x05$\x13\x02\xA8\xA9\x05*\x16\x02\xA9' + + '\r\x03\x02\x02\x02\xAA\xAB\x05\x12\n\x02\xAB\xAC\x052\x1A\x02\xAC\x0F' + + '\x03\x02\x02\x02\xAD\xAE\x05\x12\n\x02\xAE\xAF\x054\x1B\x02\xAF\x11\x03' + + '\x02\x02\x02\xB0\xB7\x07\x06\x02\x02\xB1\xB3\x07\x07\x02\x02\xB2\xB1\x03' + + '\x02\x02\x02\xB3\xB4\x03\x02\x02\x02\xB4\xB2\x03\x02\x02\x02\xB4\xB5\x03' + + '\x02\x02\x02\xB5\xB7\x03\x02\x02\x02\xB6\xB0\x03\x02\x02\x02\xB6\xB2\x03' + + '\x02\x02\x02\xB7\x13\x03\x02\x02\x02\xB8\xB9\x07\x0F\x02\x02\xB9\x15\x03' + + '\x02\x02\x02\xBA\xBB\x056\x1C\x02\xBB\x17\x03\x02\x02\x02\xBC\xBD\x07' + + '\x0F\x02\x02\xBD\x19\x03\x02\x02\x02\xBE\xBF\x07\x04\x02\x02\xBF\x1B\x03' + + '\x02\x02\x02\xC0\xC1\x07\x03\x02\x02\xC1\x1D\x03\x02\x02\x02\xC2\xC3\x07' + + '\x05\x02\x02\xC3\x1F\x03\x02\x02\x02\xC4\xC5\x07\b\x02\x02\xC5!\x03\x02' + + '\x02\x02\xC6\xC7\x07\t\x02\x02\xC7#\x03\x02\x02\x02\xC8\xC9\x07\n\x02' + + '\x02\xC9%\x03\x02\x02\x02\xCA\xCC\x07\x10\x02\x02\xCB\xCA\x03\x02\x02' + + '\x02\xCC\xCF\x03\x02\x02\x02\xCD\xCB\x03\x02\x02\x02\xCD\xCE\x03\x02\x02' + + "\x02\xCE'\x03\x02\x02\x02\xCF\xCD\x03\x02\x02\x02\xD0\xD2\x07\x10\x02" + + '\x02\xD1\xD0\x03\x02\x02\x02\xD2\xD5\x03\x02\x02\x02\xD3\xD1\x03\x02\x02' + + '\x02\xD3\xD4\x03\x02\x02\x02\xD4)\x03\x02\x02\x02\xD5\xD3\x03\x02\x02' + + '\x02\xD6\xD8\x07\x10\x02\x02\xD7\xD6\x03\x02\x02\x02\xD8\xDB\x03\x02\x02' + + '\x02\xD9\xD7\x03\x02\x02\x02\xD9\xDA\x03\x02\x02\x02\xDA+\x03\x02\x02' + + '\x02\xDB\xD9\x03\x02\x02\x02\xDC\xDE\x07\x10\x02\x02\xDD\xDC\x03\x02\x02' + + '\x02\xDE\xE1\x03\x02\x02\x02\xDF\xDD\x03\x02\x02\x02\xDF\xE0\x03\x02\x02' + + '\x02\xE0-\x03\x02\x02\x02\xE1\xDF\x03\x02\x02\x02\xE2\xE4\x07\x10\x02' + + '\x02\xE3\xE2\x03\x02\x02\x02\xE4\xE7\x03\x02\x02\x02\xE5\xE3\x03\x02\x02' + + '\x02\xE5\xE6\x03\x02\x02\x02\xE6/\x03\x02\x02\x02\xE7\xE5\x03\x02\x02' + + '\x02\xE8\xEA\x07\x10\x02\x02\xE9\xE8\x03\x02\x02\x02\xEA\xED\x03\x02\x02' + + '\x02\xEB\xE9\x03\x02\x02\x02\xEB\xEC\x03\x02\x02\x02\xEC1\x03\x02\x02' + + '\x02\xED\xEB\x03\x02\x02\x02\xEE\xF0\x07\x10\x02\x02\xEF\xEE\x03\x02\x02' + + '\x02\xF0\xF3\x03\x02\x02\x02\xF1\xEF\x03\x02\x02\x02\xF1\xF2\x03\x02\x02' + + '\x02\xF23\x03\x02\x02\x02\xF3\xF1\x03\x02\x02\x02\xF4\xF6\x07\x10\x02' + + '\x02\xF5\xF4\x03\x02\x02\x02\xF6\xF9\x03\x02\x02\x02\xF7\xF5\x03\x02\x02' + + '\x02\xF7\xF8\x03\x02\x02\x02\xF85\x03\x02\x02\x02\xF9\xF7\x03\x02\x02' + + '\x02\xFA\xFF\x07\f\x02\x02\xFB\xFF\x07\r\x02\x02\xFC\xFF\x07\x0E\x02\x02' + + '\xFD\xFF\x07\x0F\x02\x02\xFE\xFA\x03\x02\x02\x02\xFE\xFB\x03\x02\x02\x02' + + '\xFE\xFC\x03\x02\x02\x02\xFE\xFD\x03\x02\x02\x02\xFF7\x03\x02\x02\x02' + + '\x13Skmz\x9C\xA3\xB4\xB6\xCD\xD3\xD9\xDF\xE5\xEB\xF1\xF7\xFE'; public static __ATN: ATN; public static get _ATN(): ATN { if (!SelectionAutoCompleteParser.__ATN) { @@ -1345,9 +1617,6 @@ export class TraversalAllowedExpressionContext extends ExprContext { public traversalAllowedExpr(): TraversalAllowedExprContext { return this.getRuleContext(0, TraversalAllowedExprContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); - } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); @@ -1374,17 +1643,14 @@ export class TraversalAllowedExpressionContext extends ExprContext { } } export class UpAndDownTraversalExpressionContext extends ExprContext { - public upTraversalExp(): UpTraversalExpContext { - return this.getRuleContext(0, UpTraversalExpContext); + public upTraversalExpr(): UpTraversalExprContext { + return this.getRuleContext(0, UpTraversalExprContext); } public traversalAllowedExpr(): TraversalAllowedExprContext { return this.getRuleContext(0, TraversalAllowedExprContext); } - public downTraversalExp(): DownTraversalExpContext { - return this.getRuleContext(0, DownTraversalExpContext); - } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); + public downTraversalExpr(): DownTraversalExprContext { + return this.getRuleContext(0, DownTraversalExprContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1412,15 +1678,12 @@ export class UpAndDownTraversalExpressionContext extends ExprContext { } } export class UpTraversalExpressionContext extends ExprContext { - public upTraversalExp(): UpTraversalExpContext { - return this.getRuleContext(0, UpTraversalExpContext); + public upTraversalExpr(): UpTraversalExprContext { + return this.getRuleContext(0, UpTraversalExprContext); } public traversalAllowedExpr(): TraversalAllowedExprContext { return this.getRuleContext(0, TraversalAllowedExprContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); - } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); @@ -1450,11 +1713,8 @@ export class DownTraversalExpressionContext extends ExprContext { public traversalAllowedExpr(): TraversalAllowedExprContext { return this.getRuleContext(0, TraversalAllowedExprContext); } - public downTraversalExp(): DownTraversalExpContext { - return this.getRuleContext(0, DownTraversalExpContext); - } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); + public downTraversalExpr(): DownTraversalExprContext { + return this.getRuleContext(0, DownTraversalExprContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1485,15 +1745,12 @@ export class NotExpressionContext extends ExprContext { public notToken(): NotTokenContext { return this.getRuleContext(0, NotTokenContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postNotOperatorWhitespace(): PostNotOperatorWhitespaceContext { + return this.getRuleContext(0, PostNotOperatorWhitespaceContext); } public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); - } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); @@ -1529,22 +1786,11 @@ export class AndExpressionContext extends ExprContext { return this.getRuleContext(i, ExprContext); } } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext[]; - public afterExpressionWhitespace(i: number): AfterExpressionWhitespaceContext; - public afterExpressionWhitespace( - i?: number, - ): AfterExpressionWhitespaceContext | AfterExpressionWhitespaceContext[] { - if (i === undefined) { - return this.getRuleContexts(AfterExpressionWhitespaceContext); - } else { - return this.getRuleContext(i, AfterExpressionWhitespaceContext); - } - } public andToken(): AndTokenContext { return this.getRuleContext(0, AndTokenContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1581,22 +1827,11 @@ export class OrExpressionContext extends ExprContext { return this.getRuleContext(i, ExprContext); } } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext[]; - public afterExpressionWhitespace(i: number): AfterExpressionWhitespaceContext; - public afterExpressionWhitespace( - i?: number, - ): AfterExpressionWhitespaceContext | AfterExpressionWhitespaceContext[] { - if (i === undefined) { - return this.getRuleContexts(AfterExpressionWhitespaceContext); - } else { - return this.getRuleContext(i, AfterExpressionWhitespaceContext); - } - } public orToken(): OrTokenContext { return this.getRuleContext(0, OrTokenContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1627,14 +1862,11 @@ export class IncompleteAndExpressionContext extends ExprContext { public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); - } public andToken(): AndTokenContext { return this.getRuleContext(0, AndTokenContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1665,14 +1897,11 @@ export class IncompleteOrExpressionContext extends ExprContext { public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); - } public orToken(): OrTokenContext { return this.getRuleContext(0, OrTokenContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1703,8 +1932,8 @@ export class IncompleteNotExpressionContext extends ExprContext { public notToken(): NotTokenContext { return this.getRuleContext(0, NotTokenContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postNotOperatorWhitespace(): PostNotOperatorWhitespaceContext { + return this.getRuleContext(0, PostNotOperatorWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1735,14 +1964,11 @@ export class UnmatchedExpressionContinuationContext extends ExprContext { public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); - } public value(): ValueContext { return this.getRuleContext(0, ValueContext); } - public afterLogicalOperatorWhitespace(): AfterLogicalOperatorWhitespaceContext { - return this.getRuleContext(0, AfterLogicalOperatorWhitespaceContext); + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1773,8 +1999,8 @@ export class AllExpressionContext extends ExprContext { public STAR(): TerminalNode { return this.getToken(SelectionAutoCompleteParser.STAR, 0); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); + public postExpressionWhitespace(): PostExpressionWhitespaceContext { + return this.getRuleContext(0, PostExpressionWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1805,8 +2031,8 @@ export class UnmatchedValueContext extends ExprContext { public value(): ValueContext { return this.getRuleContext(0, ValueContext); } - public afterExpressionWhitespace(): AfterExpressionWhitespaceContext { - return this.getRuleContext(0, AfterExpressionWhitespaceContext); + public postExpressionWhitespace(): PostExpressionWhitespaceContext { + return this.getRuleContext(0, PostExpressionWhitespaceContext); } constructor(ctx: ExprContext) { super(ctx.parent, ctx.invokingState); @@ -1856,6 +2082,9 @@ export class AttributeExpressionContext extends TraversalAllowedExprContext { public attributeValue(): AttributeValueContext { return this.getRuleContext(0, AttributeValueContext); } + public postAttributeValueWhitespace(): PostAttributeValueWhitespaceContext { + return this.getRuleContext(0, PostAttributeValueWhitespaceContext); + } constructor(ctx: TraversalAllowedExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); @@ -1913,7 +2142,7 @@ export class FunctionCallExpressionContext extends TraversalAllowedExprContext { } } } -export class ParenthesizedExpressionWrapperContext extends TraversalAllowedExprContext { +export class TraversalAllowedParenthesizedExpressionContext extends TraversalAllowedExprContext { public parenthesizedExpr(): ParenthesizedExprContext { return this.getRuleContext(0, ParenthesizedExprContext); } @@ -1923,28 +2152,28 @@ export class ParenthesizedExpressionWrapperContext extends TraversalAllowedExprC } // @Override public enterRule(listener: SelectionAutoCompleteListener): void { - if (listener.enterParenthesizedExpressionWrapper) { - listener.enterParenthesizedExpressionWrapper(this); + if (listener.enterTraversalAllowedParenthesizedExpression) { + listener.enterTraversalAllowedParenthesizedExpression(this); } } // @Override public exitRule(listener: SelectionAutoCompleteListener): void { - if (listener.exitParenthesizedExpressionWrapper) { - listener.exitParenthesizedExpressionWrapper(this); + if (listener.exitTraversalAllowedParenthesizedExpression) { + listener.exitTraversalAllowedParenthesizedExpression(this); } } // @Override public accept(visitor: SelectionAutoCompleteVisitor): Result { - if (visitor.visitParenthesizedExpressionWrapper) { - return visitor.visitParenthesizedExpressionWrapper(this); + if (visitor.visitTraversalAllowedParenthesizedExpression) { + return visitor.visitTraversalAllowedParenthesizedExpression(this); } else { return visitor.visitChildren(this); } } } export class IncompleteExpressionContext extends TraversalAllowedExprContext { - public incompleteExpressionsWrapper(): IncompleteExpressionsWrapperContext { - return this.getRuleContext(0, IncompleteExpressionsWrapperContext); + public incompleteExpr(): IncompleteExprContext { + return this.getRuleContext(0, IncompleteExprContext); } constructor(ctx: TraversalAllowedExprContext) { super(ctx.parent, ctx.invokingState); @@ -1988,12 +2217,18 @@ export class ParenthesizedExpressionContext extends ParenthesizedExprContext { public leftParenToken(): LeftParenTokenContext { return this.getRuleContext(0, LeftParenTokenContext); } + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); + } public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } public rightParenToken(): RightParenTokenContext { return this.getRuleContext(0, RightParenTokenContext); } + public postExpressionWhitespace(): PostExpressionWhitespaceContext { + return this.getRuleContext(0, PostExpressionWhitespaceContext); + } constructor(ctx: ParenthesizedExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); @@ -2020,26 +2255,29 @@ export class ParenthesizedExpressionContext extends ParenthesizedExprContext { } } -export class IncompleteExpressionsWrapperContext extends ParserRuleContext { +export class IncompleteExprContext extends ParserRuleContext { constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { - return SelectionAutoCompleteParser.RULE_incompleteExpressionsWrapper; + return SelectionAutoCompleteParser.RULE_incompleteExpr; } - public copyFrom(ctx: IncompleteExpressionsWrapperContext): void { + public copyFrom(ctx: IncompleteExprContext): void { super.copyFrom(ctx); } } -export class IncompleteAttributeExpressionMissingValueContext extends IncompleteExpressionsWrapperContext { +export class IncompleteAttributeExpressionMissingValueContext extends IncompleteExprContext { public attributeName(): AttributeNameContext { return this.getRuleContext(0, AttributeNameContext); } public colonToken(): ColonTokenContext { return this.getRuleContext(0, ColonTokenContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + public attributeValueWhitespace(): AttributeValueWhitespaceContext { + return this.getRuleContext(0, AttributeValueWhitespaceContext); + } + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2064,14 +2302,14 @@ export class IncompleteAttributeExpressionMissingValueContext extends Incomplete } } } -export class ExpressionlessFunctionExpressionContext extends IncompleteExpressionsWrapperContext { +export class ExpressionlessFunctionExpressionContext extends IncompleteExprContext { public functionName(): FunctionNameContext { return this.getRuleContext(0, FunctionNameContext); } public expressionLessParenthesizedExpr(): ExpressionLessParenthesizedExprContext { return this.getRuleContext(0, ExpressionLessParenthesizedExprContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2096,14 +2334,17 @@ export class ExpressionlessFunctionExpressionContext extends IncompleteExpressio } } } -export class UnclosedExpressionlessFunctionExpressionContext extends IncompleteExpressionsWrapperContext { +export class UnclosedExpressionlessFunctionExpressionContext extends IncompleteExprContext { public functionName(): FunctionNameContext { return this.getRuleContext(0, FunctionNameContext); } public leftParenToken(): LeftParenTokenContext { return this.getRuleContext(0, LeftParenTokenContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); + } + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2128,7 +2369,7 @@ export class UnclosedExpressionlessFunctionExpressionContext extends IncompleteE } } } -export class UnclosedFunctionExpressionContext extends IncompleteExpressionsWrapperContext { +export class UnclosedFunctionExpressionContext extends IncompleteExprContext { public functionName(): FunctionNameContext { return this.getRuleContext(0, FunctionNameContext); } @@ -2138,7 +2379,7 @@ export class UnclosedFunctionExpressionContext extends IncompleteExpressionsWrap public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2163,14 +2404,17 @@ export class UnclosedFunctionExpressionContext extends IncompleteExpressionsWrap } } } -export class UnclosedParenthesizedExpressionContext extends IncompleteExpressionsWrapperContext { +export class UnclosedParenthesizedExpressionContext extends IncompleteExprContext { public leftParenToken(): LeftParenTokenContext { return this.getRuleContext(0, LeftParenTokenContext); } + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); + } public expr(): ExprContext { return this.getRuleContext(0, ExprContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2195,11 +2439,11 @@ export class UnclosedParenthesizedExpressionContext extends IncompleteExpression } } } -export class ExpressionlessParenthesizedExpressionWrapperContext extends IncompleteExpressionsWrapperContext { +export class ExpressionlessParenthesizedExpressionWrapperContext extends IncompleteExprContext { public expressionLessParenthesizedExpr(): ExpressionLessParenthesizedExprContext { return this.getRuleContext(0, ExpressionLessParenthesizedExprContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2224,11 +2468,14 @@ export class ExpressionlessParenthesizedExpressionWrapperContext extends Incompl } } } -export class UnclosedExpressionlessParenthesizedExpressionContext extends IncompleteExpressionsWrapperContext { +export class UnclosedExpressionlessParenthesizedExpressionContext extends IncompleteExprContext { public leftParenToken(): LeftParenTokenContext { return this.getRuleContext(0, LeftParenTokenContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); + } + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2253,7 +2500,10 @@ export class UnclosedExpressionlessParenthesizedExpressionContext extends Incomp } } } -export class IncompleteTraversalExpressionContext extends IncompleteExpressionsWrapperContext { +export class IncompletePlusTraversalExpressionContext extends IncompleteExprContext { + public postNeighborTraversalWhitespace(): PostNeighborTraversalWhitespaceContext { + return this.getRuleContext(0, PostNeighborTraversalWhitespaceContext); + } public PLUS(): TerminalNode[]; public PLUS(i: number): TerminalNode; public PLUS(i?: number): TerminalNode | TerminalNode[] { @@ -2263,39 +2513,42 @@ export class IncompleteTraversalExpressionContext extends IncompleteExpressionsW return this.getToken(SelectionAutoCompleteParser.PLUS, i); } } - constructor(ctx: IncompleteExpressionsWrapperContext) { + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } // @Override public enterRule(listener: SelectionAutoCompleteListener): void { - if (listener.enterIncompleteTraversalExpression) { - listener.enterIncompleteTraversalExpression(this); + if (listener.enterIncompletePlusTraversalExpression) { + listener.enterIncompletePlusTraversalExpression(this); } } // @Override public exitRule(listener: SelectionAutoCompleteListener): void { - if (listener.exitIncompleteTraversalExpression) { - listener.exitIncompleteTraversalExpression(this); + if (listener.exitIncompletePlusTraversalExpression) { + listener.exitIncompletePlusTraversalExpression(this); } } // @Override public accept(visitor: SelectionAutoCompleteVisitor): Result { - if (visitor.visitIncompleteTraversalExpression) { - return visitor.visitIncompleteTraversalExpression(this); + if (visitor.visitIncompletePlusTraversalExpression) { + return visitor.visitIncompletePlusTraversalExpression(this); } else { return visitor.visitChildren(this); } } } -export class IncompleteAttributeExpressionMissingKeyContext extends IncompleteExpressionsWrapperContext { +export class IncompleteAttributeExpressionMissingKeyContext extends IncompleteExprContext { public colonToken(): ColonTokenContext { return this.getRuleContext(0, ColonTokenContext); } public attributeValue(): AttributeValueContext { return this.getRuleContext(0, AttributeValueContext); } - constructor(ctx: IncompleteExpressionsWrapperContext) { + public postExpressionWhitespace(): PostExpressionWhitespaceContext { + return this.getRuleContext(0, PostExpressionWhitespaceContext); + } + constructor(ctx: IncompleteExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2337,9 +2590,15 @@ export class ExpressionlessParenthesizedExpressionContext extends ExpressionLess public leftParenToken(): LeftParenTokenContext { return this.getRuleContext(0, LeftParenTokenContext); } + public postLogicalOperatorWhitespace(): PostLogicalOperatorWhitespaceContext { + return this.getRuleContext(0, PostLogicalOperatorWhitespaceContext); + } public rightParenToken(): RightParenTokenContext { return this.getRuleContext(0, RightParenTokenContext); } + public postExpressionWhitespace(): PostExpressionWhitespaceContext { + return this.getRuleContext(0, PostExpressionWhitespaceContext); + } constructor(ctx: ExpressionLessParenthesizedExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); @@ -2366,23 +2625,26 @@ export class ExpressionlessParenthesizedExpressionContext extends ExpressionLess } } -export class UpTraversalExpContext extends ParserRuleContext { +export class UpTraversalExprContext extends ParserRuleContext { constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { - return SelectionAutoCompleteParser.RULE_upTraversalExp; + return SelectionAutoCompleteParser.RULE_upTraversalExpr; } - public copyFrom(ctx: UpTraversalExpContext): void { + public copyFrom(ctx: UpTraversalExprContext): void { super.copyFrom(ctx); } } -export class UpTraversalContext extends UpTraversalExpContext { +export class UpTraversalContext extends UpTraversalExprContext { public traversal(): TraversalContext { return this.getRuleContext(0, TraversalContext); } - constructor(ctx: UpTraversalExpContext) { + public postUpwardTraversalWhitespace(): PostUpwardTraversalWhitespaceContext { + return this.getRuleContext(0, PostUpwardTraversalWhitespaceContext); + } + constructor(ctx: UpTraversalExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2408,23 +2670,26 @@ export class UpTraversalContext extends UpTraversalExpContext { } } -export class DownTraversalExpContext extends ParserRuleContext { +export class DownTraversalExprContext extends ParserRuleContext { constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { - return SelectionAutoCompleteParser.RULE_downTraversalExp; + return SelectionAutoCompleteParser.RULE_downTraversalExpr; } - public copyFrom(ctx: DownTraversalExpContext): void { + public copyFrom(ctx: DownTraversalExprContext): void { super.copyFrom(ctx); } } -export class DownTraversalContext extends DownTraversalExpContext { +export class DownTraversalContext extends DownTraversalExprContext { public traversal(): TraversalContext { return this.getRuleContext(0, TraversalContext); } - constructor(ctx: DownTraversalExpContext) { + public postDownwardTraversalWhitespace(): PostDownwardTraversalWhitespaceContext { + return this.getRuleContext(0, PostDownwardTraversalWhitespaceContext); + } + constructor(ctx: DownTraversalExprContext) { super(ctx.parent, ctx.invokingState); this.copyFrom(ctx); } @@ -2789,7 +3054,241 @@ export class RightParenTokenContext extends ParserRuleContext { } } -export class AfterExpressionWhitespaceContext extends ParserRuleContext { +export class AttributeValueWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_attributeValueWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterAttributeValueWhitespace) { + listener.enterAttributeValueWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitAttributeValueWhitespace) { + listener.exitAttributeValueWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitAttributeValueWhitespace) { + return visitor.visitAttributeValueWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class PostAttributeValueWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_postAttributeValueWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterPostAttributeValueWhitespace) { + listener.enterPostAttributeValueWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitPostAttributeValueWhitespace) { + listener.exitPostAttributeValueWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitPostAttributeValueWhitespace) { + return visitor.visitPostAttributeValueWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class PostExpressionWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_postExpressionWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterPostExpressionWhitespace) { + listener.enterPostExpressionWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitPostExpressionWhitespace) { + listener.exitPostExpressionWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitPostExpressionWhitespace) { + return visitor.visitPostExpressionWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class PostNotOperatorWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_postNotOperatorWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterPostNotOperatorWhitespace) { + listener.enterPostNotOperatorWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitPostNotOperatorWhitespace) { + listener.exitPostNotOperatorWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitPostNotOperatorWhitespace) { + return visitor.visitPostNotOperatorWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class PostLogicalOperatorWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_postLogicalOperatorWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterPostLogicalOperatorWhitespace) { + listener.enterPostLogicalOperatorWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitPostLogicalOperatorWhitespace) { + listener.exitPostLogicalOperatorWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitPostLogicalOperatorWhitespace) { + return visitor.visitPostLogicalOperatorWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class PostNeighborTraversalWhitespaceContext extends ParserRuleContext { + public WS(): TerminalNode[]; + public WS(i: number): TerminalNode; + public WS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(SelectionAutoCompleteParser.WS); + } else { + return this.getToken(SelectionAutoCompleteParser.WS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return SelectionAutoCompleteParser.RULE_postNeighborTraversalWhitespace; + } + // @Override + public enterRule(listener: SelectionAutoCompleteListener): void { + if (listener.enterPostNeighborTraversalWhitespace) { + listener.enterPostNeighborTraversalWhitespace(this); + } + } + // @Override + public exitRule(listener: SelectionAutoCompleteListener): void { + if (listener.exitPostNeighborTraversalWhitespace) { + listener.exitPostNeighborTraversalWhitespace(this); + } + } + // @Override + public accept(visitor: SelectionAutoCompleteVisitor): Result { + if (visitor.visitPostNeighborTraversalWhitespace) { + return visitor.visitPostNeighborTraversalWhitespace(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class PostUpwardTraversalWhitespaceContext extends ParserRuleContext { public WS(): TerminalNode[]; public WS(i: number): TerminalNode; public WS(i?: number): TerminalNode | TerminalNode[] { @@ -2804,31 +3303,31 @@ export class AfterExpressionWhitespaceContext extends ParserRuleContext { } // @Override public get ruleIndex(): number { - return SelectionAutoCompleteParser.RULE_afterExpressionWhitespace; + return SelectionAutoCompleteParser.RULE_postUpwardTraversalWhitespace; } // @Override public enterRule(listener: SelectionAutoCompleteListener): void { - if (listener.enterAfterExpressionWhitespace) { - listener.enterAfterExpressionWhitespace(this); + if (listener.enterPostUpwardTraversalWhitespace) { + listener.enterPostUpwardTraversalWhitespace(this); } } // @Override public exitRule(listener: SelectionAutoCompleteListener): void { - if (listener.exitAfterExpressionWhitespace) { - listener.exitAfterExpressionWhitespace(this); + if (listener.exitPostUpwardTraversalWhitespace) { + listener.exitPostUpwardTraversalWhitespace(this); } } // @Override public accept(visitor: SelectionAutoCompleteVisitor): Result { - if (visitor.visitAfterExpressionWhitespace) { - return visitor.visitAfterExpressionWhitespace(this); + if (visitor.visitPostUpwardTraversalWhitespace) { + return visitor.visitPostUpwardTraversalWhitespace(this); } else { return visitor.visitChildren(this); } } } -export class AfterLogicalOperatorWhitespaceContext extends ParserRuleContext { +export class PostDownwardTraversalWhitespaceContext extends ParserRuleContext { public WS(): TerminalNode[]; public WS(i: number): TerminalNode; public WS(i?: number): TerminalNode | TerminalNode[] { @@ -2843,24 +3342,24 @@ export class AfterLogicalOperatorWhitespaceContext extends ParserRuleContext { } // @Override public get ruleIndex(): number { - return SelectionAutoCompleteParser.RULE_afterLogicalOperatorWhitespace; + return SelectionAutoCompleteParser.RULE_postDownwardTraversalWhitespace; } // @Override public enterRule(listener: SelectionAutoCompleteListener): void { - if (listener.enterAfterLogicalOperatorWhitespace) { - listener.enterAfterLogicalOperatorWhitespace(this); + if (listener.enterPostDownwardTraversalWhitespace) { + listener.enterPostDownwardTraversalWhitespace(this); } } // @Override public exitRule(listener: SelectionAutoCompleteListener): void { - if (listener.exitAfterLogicalOperatorWhitespace) { - listener.exitAfterLogicalOperatorWhitespace(this); + if (listener.exitPostDownwardTraversalWhitespace) { + listener.exitPostDownwardTraversalWhitespace(this); } } // @Override public accept(visitor: SelectionAutoCompleteVisitor): Result { - if (visitor.visitAfterLogicalOperatorWhitespace) { - return visitor.visitAfterLogicalOperatorWhitespace(this); + if (visitor.visitPostDownwardTraversalWhitespace) { + return visitor.visitPostDownwardTraversalWhitespace(this); } else { return visitor.visitChildren(this); } diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts index 54ecce5aeaef3..d659e55b6fb29 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/generated/SelectionAutoCompleteVisitor.ts @@ -3,17 +3,16 @@ import {ParseTreeVisitor} from 'antlr4ts/tree/ParseTreeVisitor'; import { - AfterExpressionWhitespaceContext, - AfterLogicalOperatorWhitespaceContext, AllExpressionContext, AndExpressionContext, AndTokenContext, AttributeExpressionContext, AttributeNameContext, AttributeValueContext, + AttributeValueWhitespaceContext, ColonTokenContext, DownTraversalContext, - DownTraversalExpContext, + DownTraversalExprContext, DownTraversalExpressionContext, ExprContext, ExpressionLessParenthesizedExprContext, @@ -25,13 +24,13 @@ import { IncompleteAndExpressionContext, IncompleteAttributeExpressionMissingKeyContext, IncompleteAttributeExpressionMissingValueContext, + IncompleteExprContext, IncompleteExpressionContext, - IncompleteExpressionsWrapperContext, IncompleteLeftQuotedStringValueContext, IncompleteNotExpressionContext, IncompleteOrExpressionContext, + IncompletePlusTraversalExpressionContext, IncompleteRightQuotedStringValueContext, - IncompleteTraversalExpressionContext, LeftParenTokenContext, NotExpressionContext, NotTokenContext, @@ -39,12 +38,19 @@ import { OrTokenContext, ParenthesizedExprContext, ParenthesizedExpressionContext, - ParenthesizedExpressionWrapperContext, + PostAttributeValueWhitespaceContext, + PostDownwardTraversalWhitespaceContext, + PostExpressionWhitespaceContext, + PostLogicalOperatorWhitespaceContext, + PostNeighborTraversalWhitespaceContext, + PostNotOperatorWhitespaceContext, + PostUpwardTraversalWhitespaceContext, QuotedStringValueContext, RightParenTokenContext, StartContext, TraversalAllowedExprContext, TraversalAllowedExpressionContext, + TraversalAllowedParenthesizedExpressionContext, TraversalContext, UnclosedExpressionlessFunctionExpressionContext, UnclosedExpressionlessParenthesizedExpressionContext, @@ -55,7 +61,7 @@ import { UnquotedStringValueContext, UpAndDownTraversalExpressionContext, UpTraversalContext, - UpTraversalExpContext, + UpTraversalExprContext, UpTraversalExpressionContext, ValueContext, } from './SelectionAutoCompleteParser'; @@ -68,14 +74,6 @@ import { * operations with no return type. */ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor { - /** - * Visit a parse tree produced by the `DownTraversal` - * labeled alternative in `SelectionAutoCompleteParser.downTraversalExp`. - * @param ctx the parse tree - * @return the visitor result - */ - visitDownTraversal?: (ctx: DownTraversalContext) => Result; - /** * Visit a parse tree produced by the `AttributeExpression` * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. @@ -93,12 +91,14 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; /** - * Visit a parse tree produced by the `ParenthesizedExpressionWrapper` + * Visit a parse tree produced by the `TraversalAllowedParenthesizedExpression` * labeled alternative in `SelectionAutoCompleteParser.traversalAllowedExpr`. * @param ctx the parse tree * @return the visitor result */ - visitParenthesizedExpressionWrapper?: (ctx: ParenthesizedExpressionWrapperContext) => Result; + visitTraversalAllowedParenthesizedExpression?: ( + ctx: TraversalAllowedParenthesizedExpressionContext, + ) => Result; /** * Visit a parse tree produced by the `IncompleteExpression` @@ -110,94 +110,12 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; - /** - * Visit a parse tree produced by the `IncompleteAttributeExpressionMissingValue` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitIncompleteAttributeExpressionMissingValue?: ( - ctx: IncompleteAttributeExpressionMissingValueContext, - ) => Result; - - /** - * Visit a parse tree produced by the `ExpressionlessFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => Result; - - /** - * Visit a parse tree produced by the `UnclosedExpressionlessFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitUnclosedExpressionlessFunctionExpression?: ( - ctx: UnclosedExpressionlessFunctionExpressionContext, - ) => Result; - - /** - * Visit a parse tree produced by the `UnclosedFunctionExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => Result; - - /** - * Visit a parse tree produced by the `UnclosedParenthesizedExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => Result; - - /** - * Visit a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitExpressionlessParenthesizedExpressionWrapper?: ( - ctx: ExpressionlessParenthesizedExpressionWrapperContext, - ) => Result; - - /** - * Visit a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitUnclosedExpressionlessParenthesizedExpression?: ( - ctx: UnclosedExpressionlessParenthesizedExpressionContext, - ) => Result; - - /** - * Visit a parse tree produced by the `IncompleteTraversalExpression` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitIncompleteTraversalExpression?: (ctx: IncompleteTraversalExpressionContext) => Result; - - /** - * Visit a parse tree produced by the `IncompleteAttributeExpressionMissingKey` - * labeled alternative in `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. - * @param ctx the parse tree - * @return the visitor result - */ - visitIncompleteAttributeExpressionMissingKey?: ( - ctx: IncompleteAttributeExpressionMissingKeyContext, - ) => Result; - /** * Visit a parse tree produced by the `ParenthesizedExpression` * labeled alternative in `SelectionAutoCompleteParser.parenthesizedExpr`. @@ -320,6 +238,14 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; + /** + * Visit a parse tree produced by the `DownTraversal` + * labeled alternative in `SelectionAutoCompleteParser.downTraversalExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitDownTraversal?: (ctx: DownTraversalContext) => Result; + /** * Visit a parse tree produced by the `QuotedStringValue` * labeled alternative in `SelectionAutoCompleteParser.value`. @@ -352,6 +278,90 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; + /** + * Visit a parse tree produced by the `IncompleteAttributeExpressionMissingValue` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteAttributeExpressionMissingValue?: ( + ctx: IncompleteAttributeExpressionMissingValueContext, + ) => Result; + + /** + * Visit a parse tree produced by the `ExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpressionlessFunctionExpression?: (ctx: ExpressionlessFunctionExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UnclosedExpressionlessFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedExpressionlessFunctionExpression?: ( + ctx: UnclosedExpressionlessFunctionExpressionContext, + ) => Result; + + /** + * Visit a parse tree produced by the `UnclosedFunctionExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedFunctionExpression?: (ctx: UnclosedFunctionExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UnclosedParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedParenthesizedExpression?: (ctx: UnclosedParenthesizedExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `ExpressionlessParenthesizedExpressionWrapper` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpressionlessParenthesizedExpressionWrapper?: ( + ctx: ExpressionlessParenthesizedExpressionWrapperContext, + ) => Result; + + /** + * Visit a parse tree produced by the `UnclosedExpressionlessParenthesizedExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUnclosedExpressionlessParenthesizedExpression?: ( + ctx: UnclosedExpressionlessParenthesizedExpressionContext, + ) => Result; + + /** + * Visit a parse tree produced by the `IncompletePlusTraversalExpression` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompletePlusTraversalExpression?: ( + ctx: IncompletePlusTraversalExpressionContext, + ) => Result; + + /** + * Visit a parse tree produced by the `IncompleteAttributeExpressionMissingKey` + * labeled alternative in `SelectionAutoCompleteParser.incompleteExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitIncompleteAttributeExpressionMissingKey?: ( + ctx: IncompleteAttributeExpressionMissingKeyContext, + ) => Result; + /** * Visit a parse tree produced by `SelectionAutoCompleteParser.start`. * @param ctx the parse tree @@ -381,11 +391,11 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; /** - * Visit a parse tree produced by `SelectionAutoCompleteParser.incompleteExpressionsWrapper`. + * Visit a parse tree produced by `SelectionAutoCompleteParser.incompleteExpr`. * @param ctx the parse tree * @return the visitor result */ - visitIncompleteExpressionsWrapper?: (ctx: IncompleteExpressionsWrapperContext) => Result; + visitIncompleteExpr?: (ctx: IncompleteExprContext) => Result; /** * Visit a parse tree produced by `SelectionAutoCompleteParser.expressionLessParenthesizedExpr`. @@ -395,18 +405,18 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; /** - * Visit a parse tree produced by `SelectionAutoCompleteParser.upTraversalExp`. + * Visit a parse tree produced by `SelectionAutoCompleteParser.upTraversalExpr`. * @param ctx the parse tree * @return the visitor result */ - visitUpTraversalExp?: (ctx: UpTraversalExpContext) => Result; + visitUpTraversalExpr?: (ctx: UpTraversalExprContext) => Result; /** - * Visit a parse tree produced by `SelectionAutoCompleteParser.downTraversalExp`. + * Visit a parse tree produced by `SelectionAutoCompleteParser.downTraversalExpr`. * @param ctx the parse tree * @return the visitor result */ - visitDownTraversalExp?: (ctx: DownTraversalExpContext) => Result; + visitDownTraversalExpr?: (ctx: DownTraversalExprContext) => Result; /** * Visit a parse tree produced by `SelectionAutoCompleteParser.traversal`. @@ -479,18 +489,60 @@ export interface SelectionAutoCompleteVisitor extends ParseTreeVisitor Result; /** - * Visit a parse tree produced by `SelectionAutoCompleteParser.afterExpressionWhitespace`. + * Visit a parse tree produced by `SelectionAutoCompleteParser.attributeValueWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAttributeValueWhitespace?: (ctx: AttributeValueWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.postAttributeValueWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitPostAttributeValueWhitespace?: (ctx: PostAttributeValueWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.postExpressionWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitPostExpressionWhitespace?: (ctx: PostExpressionWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.postNotOperatorWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitPostNotOperatorWhitespace?: (ctx: PostNotOperatorWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.postLogicalOperatorWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitPostLogicalOperatorWhitespace?: (ctx: PostLogicalOperatorWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.postNeighborTraversalWhitespace`. + * @param ctx the parse tree + * @return the visitor result + */ + visitPostNeighborTraversalWhitespace?: (ctx: PostNeighborTraversalWhitespaceContext) => Result; + + /** + * Visit a parse tree produced by `SelectionAutoCompleteParser.postUpwardTraversalWhitespace`. * @param ctx the parse tree * @return the visitor result */ - visitAfterExpressionWhitespace?: (ctx: AfterExpressionWhitespaceContext) => Result; + visitPostUpwardTraversalWhitespace?: (ctx: PostUpwardTraversalWhitespaceContext) => Result; /** - * Visit a parse tree produced by `SelectionAutoCompleteParser.afterLogicalOperatorWhitespace`. + * Visit a parse tree produced by `SelectionAutoCompleteParser.postDownwardTraversalWhitespace`. * @param ctx the parse tree * @return the visitor result */ - visitAfterLogicalOperatorWhitespace?: (ctx: AfterLogicalOperatorWhitespaceContext) => Result; + visitPostDownwardTraversalWhitespace?: (ctx: PostDownwardTraversalWhitespaceContext) => Result; /** * Visit a parse tree produced by `SelectionAutoCompleteParser.value`. diff --git a/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js b/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js index b99f18412f191..359faa88a51ca 100644 --- a/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js +++ b/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js @@ -1,12409 +1,17015 @@ -/******/ (function() { // webpackBootstrap -/******/ "use strict"; -/******/ var __webpack_modules__ = ({ - -/***/ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js": -/*!**************************************************************************************!*\ +/******/ (function () { + // webpackBootstrap + /******/ "use strict"; + /******/ var __webpack_modules__ = { + /***/ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js": + /*!**************************************************************************************!*\ !*** ../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js ***! \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _memoize = _interopRequireDefault(__webpack_require__(/*! @emotion/memoize */ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 - -var index = (0, _memoize.default)(function (prop) { - return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 - /* o */ && prop.charCodeAt(1) === 110 - /* n */ && prop.charCodeAt(2) < 91; -} -/* Z+1 */); -var _default = exports["default"] = index; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = void 0; + var _memoize = _interopRequireDefault( + __webpack_require__( + /*! @emotion/memoize */ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js" + ) + ); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + var reactPropsRegex = + /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 + + var index = (0, _memoize.default)( + function (prop) { + return ( + reactPropsRegex.test(prop) || + (prop.charCodeAt(0) === 111 && + /* o */ prop.charCodeAt(1) === 110 && + /* n */ prop.charCodeAt(2) < 91) + ); + } + /* Z+1 */ + ); + var _default = (exports["default"] = index); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js": -/*!**************************************************************************!*\ + /***/ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js": + /*!**************************************************************************!*\ !*** ../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js ***! \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -function memoize(fn) { - var cache = {}; - return function (arg) { - if (cache[arg] === undefined) cache[arg] = fn(arg); - return cache[arg]; - }; -} -var _default = exports["default"] = memoize; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = void 0; + function memoize(fn) { + var cache = {}; + return function (arg) { + if (cache[arg] === undefined) cache[arg] = fn(arg); + return cache[arg]; + }; + } + var _default = (exports["default"] = memoize); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js": -/*!****************************************************************************!*\ + /***/ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js": + /*!****************************************************************************!*\ !*** ../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js ***! \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.computePosition = exports.autoPlacement = exports.arrow = void 0; -exports.detectOverflow = detectOverflow; -exports.offset = exports.limitShift = exports.inline = exports.hide = exports.flip = void 0; -exports.rectToClientRect = rectToClientRect; -exports.size = exports.shift = void 0; -function getAlignment(placement) { - return placement.split('-')[1]; -} -function getLengthFromAxis(axis) { - return axis === 'y' ? 'height' : 'width'; -} -function getSide(placement) { - return placement.split('-')[0]; -} -function getMainAxisFromPlacement(placement) { - return ['top', 'bottom'].includes(getSide(placement)) ? 'x' : 'y'; -} -function computeCoordsFromPlacement(_ref, placement, rtl) { - let { - reference, - floating - } = _ref; - const commonX = reference.x + reference.width / 2 - floating.width / 2; - const commonY = reference.y + reference.height / 2 - floating.height / 2; - const mainAxis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(mainAxis); - const commonAlign = reference[length] / 2 - floating[length] / 2; - const side = getSide(placement); - const isVertical = mainAxis === 'x'; - let coords; - switch (side) { - case 'top': - coords = { - x: commonX, - y: reference.y - floating.height - }; - break; - case 'bottom': - coords = { - x: commonX, - y: reference.y + reference.height - }; - break; - case 'right': - coords = { - x: reference.x + reference.width, - y: commonY - }; - break; - case 'left': - coords = { - x: reference.x - floating.width, - y: commonY - }; - break; - default: - coords = { - x: reference.x, - y: reference.y - }; - } - switch (getAlignment(placement)) { - case 'start': - coords[mainAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); - break; - case 'end': - coords[mainAxis] += commonAlign * (rtl && isVertical ? -1 : 1); - break; - } - return coords; -} - -/** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain positioning strategy. - * - * This export does not have any `platform` interface logic. You will need to - * write one for the platform you are using Floating UI with. - */ -const computePosition = async (reference, floating, config) => { - const { - placement = 'bottom', - strategy = 'absolute', - middleware = [], - platform - } = config; - const validMiddleware = middleware.filter(Boolean); - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); - let rects = await platform.getElementRects({ - reference, - floating, - strategy - }); - let { - x, - y - } = computeCoordsFromPlacement(rects, placement, rtl); - let statefulPlacement = placement; - let middlewareData = {}; - let resetCount = 0; - for (let i = 0; i < validMiddleware.length; i++) { - const { - name, - fn - } = validMiddleware[i]; - const { - x: nextX, - y: nextY, - data, - reset - } = await fn({ - x, - y, - initialPlacement: placement, - placement: statefulPlacement, - strategy, - middlewareData, - rects, - platform, - elements: { - reference, - floating - } - }); - x = nextX != null ? nextX : x; - y = nextY != null ? nextY : y; - middlewareData = { - ...middlewareData, - [name]: { - ...middlewareData[name], - ...data - } - }; - if (reset && resetCount <= 50) { - resetCount++; - if (typeof reset === 'object') { - if (reset.placement) { - statefulPlacement = reset.placement; - } - if (reset.rects) { - rects = reset.rects === true ? await platform.getElementRects({ - reference, - floating, - strategy - }) : reset.rects; - } - ({ - x, - y - } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); - } - i = -1; - continue; - } - } - return { - x, - y, - placement: statefulPlacement, - strategy, - middlewareData - }; -}; -exports.computePosition = computePosition; -function evaluate(value, param) { - return typeof value === 'function' ? value(param) : value; -} -function expandPaddingObject(padding) { - return { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...padding - }; -} -function getSideObjectFromPadding(padding) { - return typeof padding !== 'number' ? expandPaddingObject(padding) : { - top: padding, - right: padding, - bottom: padding, - left: padding - }; -} -function rectToClientRect(rect) { - return { - ...rect, - top: rect.y, - left: rect.x, - right: rect.x + rect.width, - bottom: rect.y + rect.height - }; -} - -/** - * Resolves with an object of overflow side offsets that determine how much the - * element is overflowing a given clipping boundary on each side. - * - positive = overflowing the boundary by that number of pixels - * - negative = how many pixels left before it will overflow - * - 0 = lies flush with the boundary - * @see https://floating-ui.com/docs/detectOverflow - */ -async function detectOverflow(state, options) { - var _await$platform$isEle; - if (options === void 0) { - options = {}; - } - const { - x, - y, - platform, - rects, - elements, - strategy - } = state; - const { - boundary = 'clippingAncestors', - rootBoundary = 'viewport', - elementContext = 'floating', - altBoundary = false, - padding = 0 - } = evaluate(options, state); - const paddingObject = getSideObjectFromPadding(padding); - const altContext = elementContext === 'floating' ? 'reference' : 'floating'; - const element = elements[altBoundary ? altContext : elementContext]; - const clippingClientRect = rectToClientRect(await platform.getClippingRect({ - element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), - boundary, - rootBoundary, - strategy - })); - const rect = elementContext === 'floating' ? { - ...rects.floating, - x, - y - } : rects.reference; - const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); - const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { - x: 1, - y: 1 - } : { - x: 1, - y: 1 - }; - const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ - rect, - offsetParent, - strategy - }) : rect); - return { - top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, - bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, - left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, - right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x - }; -} -const min = Math.min; -const max = Math.max; -function within(min$1, value, max$1) { - return max(min$1, min(value, max$1)); -} - -/** - * Provides data to position an inner element of the floating element so that it - * appears centered to the reference element. - * @see https://floating-ui.com/docs/arrow - */ -const arrow = options => ({ - name: 'arrow', - options, - async fn(state) { - const { - x, - y, - placement, - rects, - platform, - elements - } = state; - // Since `element` is required, we don't Partial<> the type. - const { - element, - padding = 0 - } = evaluate(options, state) || {}; - if (element == null) { - return {}; - } - const paddingObject = getSideObjectFromPadding(padding); - const coords = { - x, - y - }; - const axis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(axis); - const arrowDimensions = await platform.getDimensions(element); - const isYAxis = axis === 'y'; - const minProp = isYAxis ? 'top' : 'left'; - const maxProp = isYAxis ? 'bottom' : 'right'; - const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; - const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; - const startDiff = coords[axis] - rects.reference[axis]; - const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); - let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; - - // DOM platform can return `window` as the `offsetParent`. - if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { - clientSize = elements.floating[clientProp] || rects.floating[length]; - } - const centerToReference = endDiff / 2 - startDiff / 2; - - // If the padding is large enough that it causes the arrow to no longer be - // centered, modify the padding so that it is centered. - const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; - const minPadding = min(paddingObject[minProp], largestPossiblePadding); - const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); - - // Make sure the arrow doesn't overflow the floating element if the center - // point is outside the floating element's bounds. - const min$1 = minPadding; - const max = clientSize - arrowDimensions[length] - maxPadding; - const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; - const offset = within(min$1, center, max); - - // If the reference is small enough that the arrow's padding causes it to - // to point to nothing for an aligned placement, adjust the offset of the - // floating element itself. This stops `shift()` from taking action, but can - // be worked around by calling it again after the `arrow()` if desired. - const shouldAddOffset = getAlignment(placement) != null && center != offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; - const alignmentOffset = shouldAddOffset ? center < min$1 ? min$1 - center : max - center : 0; - return { - [axis]: coords[axis] - alignmentOffset, - data: { - [axis]: offset, - centerOffset: center - offset - } - }; - } -}); -exports.arrow = arrow; -const sides = ['top', 'right', 'bottom', 'left']; -const allPlacements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-start", side + "-end"), []); -const oppositeSideMap = { - left: 'right', - right: 'left', - bottom: 'top', - top: 'bottom' -}; -function getOppositePlacement(placement) { - return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); -} -function getAlignmentSides(placement, rects, rtl) { - if (rtl === void 0) { - rtl = false; - } - const alignment = getAlignment(placement); - const mainAxis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(mainAxis); - let mainAlignmentSide = mainAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; - if (rects.reference[length] > rects.floating[length]) { - mainAlignmentSide = getOppositePlacement(mainAlignmentSide); - } - return { - main: mainAlignmentSide, - cross: getOppositePlacement(mainAlignmentSide) - }; -} -const oppositeAlignmentMap = { - start: 'end', - end: 'start' -}; -function getOppositeAlignmentPlacement(placement) { - return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); -} -function getPlacementList(alignment, autoAlignment, allowedPlacements) { - const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); - return allowedPlacementsSortedByAlignment.filter(placement => { - if (alignment) { - return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); - } - return true; - }); -} -/** - * Optimizes the visibility of the floating element by choosing the placement - * that has the most space available automatically, without needing to specify a - * preferred placement. Alternative to `flip`. - * @see https://floating-ui.com/docs/autoPlacement - */ -const autoPlacement = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'autoPlacement', - options, - async fn(state) { - var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; - const { - rects, - middlewareData, - placement, - platform, - elements - } = state; - const { - crossAxis = false, - alignment, - allowedPlacements = allPlacements, - autoAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const placements = alignment !== undefined || allowedPlacements === allPlacements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; - const overflow = await detectOverflow(state, detectOverflowOptions); - const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; - const currentPlacement = placements[currentIndex]; - if (currentPlacement == null) { - return {}; - } - const { - main, - cross - } = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); - - // Make `computeCoords` start from the right place. - if (placement !== currentPlacement) { - return { - reset: { - placement: placements[0] + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.computePosition = + exports.autoPlacement = + exports.arrow = + void 0; + exports.detectOverflow = detectOverflow; + exports.offset = + exports.limitShift = + exports.inline = + exports.hide = + exports.flip = + void 0; + exports.rectToClientRect = rectToClientRect; + exports.size = exports.shift = void 0; + function getAlignment(placement) { + return placement.split("-")[1]; + } + function getLengthFromAxis(axis) { + return axis === "y" ? "height" : "width"; + } + function getSide(placement) { + return placement.split("-")[0]; + } + function getMainAxisFromPlacement(placement) { + return ["top", "bottom"].includes(getSide(placement)) ? "x" : "y"; + } + function computeCoordsFromPlacement(_ref, placement, rtl) { + let { reference, floating } = _ref; + const commonX = + reference.x + reference.width / 2 - floating.width / 2; + const commonY = + reference.y + reference.height / 2 - floating.height / 2; + const mainAxis = getMainAxisFromPlacement(placement); + const length = getLengthFromAxis(mainAxis); + const commonAlign = reference[length] / 2 - floating[length] / 2; + const side = getSide(placement); + const isVertical = mainAxis === "x"; + let coords; + switch (side) { + case "top": + coords = { + x: commonX, + y: reference.y - floating.height, + }; + break; + case "bottom": + coords = { + x: commonX, + y: reference.y + reference.height, + }; + break; + case "right": + coords = { + x: reference.x + reference.width, + y: commonY, + }; + break; + case "left": + coords = { + x: reference.x - floating.width, + y: commonY, + }; + break; + default: + coords = { + x: reference.x, + y: reference.y, + }; } - }; - } - const currentOverflows = [overflow[getSide(currentPlacement)], overflow[main], overflow[cross]]; - const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { - placement: currentPlacement, - overflows: currentOverflows - }]; - const nextPlacement = placements[currentIndex + 1]; - - // There are more placements to check. - if (nextPlacement) { - return { - data: { - index: currentIndex + 1, - overflows: allOverflows - }, - reset: { - placement: nextPlacement + switch (getAlignment(placement)) { + case "start": + coords[mainAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); + break; + case "end": + coords[mainAxis] += commonAlign * (rtl && isVertical ? -1 : 1); + break; } - }; - } - const placementsSortedByMostSpace = allOverflows.map(d => { - const alignment = getAlignment(d.placement); - return [d.placement, alignment && crossAxis ? - // Check along the mainAxis and main crossAxis side. - d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : - // Check only the mainAxis. - d.overflows[0], d.overflows]; - }).sort((a, b) => a[1] - b[1]); - const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, - // Aligned placements should not check their opposite crossAxis - // side. - getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); - const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; - if (resetPlacement !== placement) { - return { - data: { - index: currentIndex + 1, - overflows: allOverflows - }, - reset: { - placement: resetPlacement + return coords; + } + + /** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a reference element when it is given a certain positioning strategy. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ + const computePosition = async (reference, floating, config) => { + const { + placement = "bottom", + strategy = "absolute", + middleware = [], + platform, + } = config; + const validMiddleware = middleware.filter(Boolean); + const rtl = await (platform.isRTL == null + ? void 0 + : platform.isRTL(floating)); + let rects = await platform.getElementRects({ + reference, + floating, + strategy, + }); + let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); + let statefulPlacement = placement; + let middlewareData = {}; + let resetCount = 0; + for (let i = 0; i < validMiddleware.length; i++) { + const { name, fn } = validMiddleware[i]; + const { + x: nextX, + y: nextY, + data, + reset, + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform, + elements: { + reference, + floating, + }, + }); + x = nextX != null ? nextX : x; + y = nextY != null ? nextY : y; + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data, + }, + }; + if (reset && resetCount <= 50) { + resetCount++; + if (typeof reset === "object") { + if (reset.placement) { + statefulPlacement = reset.placement; + } + if (reset.rects) { + rects = + reset.rects === true + ? await platform.getElementRects({ + reference, + floating, + strategy, + }) + : reset.rects; + } + ({ x, y } = computeCoordsFromPlacement( + rects, + statefulPlacement, + rtl + )); + } + i = -1; + continue; + } } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData, + }; }; - } - return {}; - } - }; -}; -exports.autoPlacement = autoPlacement; -function getExpandedPlacements(placement) { - const oppositePlacement = getOppositePlacement(placement); - return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; -} -function getSideList(side, isStart, rtl) { - const lr = ['left', 'right']; - const rl = ['right', 'left']; - const tb = ['top', 'bottom']; - const bt = ['bottom', 'top']; - switch (side) { - case 'top': - case 'bottom': - if (rtl) return isStart ? rl : lr; - return isStart ? lr : rl; - case 'left': - case 'right': - return isStart ? tb : bt; - default: - return []; - } -} -function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { - const alignment = getAlignment(placement); - let list = getSideList(getSide(placement), direction === 'start', rtl); - if (alignment) { - list = list.map(side => side + "-" + alignment); - if (flipAlignment) { - list = list.concat(list.map(getOppositeAlignmentPlacement)); - } - } - return list; -} - -/** - * Optimizes the visibility of the floating element by flipping the `placement` - * in order to keep it in view when the preferred placement(s) will overflow the - * clipping boundary. Alternative to `autoPlacement`. - * @see https://floating-ui.com/docs/flip - */ -const flip = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'flip', - options, - async fn(state) { - var _middlewareData$flip; - const { - placement, - middlewareData, - rects, - initialPlacement, - platform, - elements - } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true, - fallbackPlacements: specifiedFallbackPlacements, - fallbackStrategy = 'bestFit', - fallbackAxisSideDirection = 'none', - flipAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const side = getSide(placement); - const isBasePlacement = getSide(initialPlacement) === initialPlacement; - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); - const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); - if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') { - fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); - } - const placements = [initialPlacement, ...fallbackPlacements]; - const overflow = await detectOverflow(state, detectOverflowOptions); - const overflows = []; - let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; - if (checkMainAxis) { - overflows.push(overflow[side]); - } - if (checkCrossAxis) { - const { - main, - cross - } = getAlignmentSides(placement, rects, rtl); - overflows.push(overflow[main], overflow[cross]); - } - overflowsData = [...overflowsData, { - placement, - overflows - }]; - - // One or more sides is overflowing. - if (!overflows.every(side => side <= 0)) { - var _middlewareData$flip2, _overflowsData$filter; - const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; - const nextPlacement = placements[nextIndex]; - if (nextPlacement) { - // Try next placement and re-run the lifecycle. + exports.computePosition = computePosition; + function evaluate(value, param) { + return typeof value === "function" ? value(param) : value; + } + function expandPaddingObject(padding) { return { - data: { - index: nextIndex, - overflows: overflowsData - }, - reset: { - placement: nextPlacement - } + top: 0, + right: 0, + bottom: 0, + left: 0, + ...padding, + }; + } + function getSideObjectFromPadding(padding) { + return typeof padding !== "number" + ? expandPaddingObject(padding) + : { + top: padding, + right: padding, + bottom: padding, + left: padding, + }; + } + function rectToClientRect(rect) { + return { + ...rect, + top: rect.y, + left: rect.x, + right: rect.x + rect.width, + bottom: rect.y + rect.height, }; } - // First, find the candidates that fit on the mainAxis side of overflow, - // then find the placement that fits the best on the main crossAxis side. - let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; - - // Otherwise fallback. - if (!resetPlacement) { - switch (fallbackStrategy) { - case 'bestFit': - { - var _overflowsData$map$so; - const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0]; - if (placement) { - resetPlacement = placement; + /** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ + async function detectOverflow(state, options) { + var _await$platform$isEle; + if (options === void 0) { + options = {}; + } + const { x, y, platform, rects, elements, strategy } = state; + const { + boundary = "clippingAncestors", + rootBoundary = "viewport", + elementContext = "floating", + altBoundary = false, + padding = 0, + } = evaluate(options, state); + const paddingObject = getSideObjectFromPadding(padding); + const altContext = + elementContext === "floating" ? "reference" : "floating"; + const element = elements[altBoundary ? altContext : elementContext]; + const clippingClientRect = rectToClientRect( + await platform.getClippingRect({ + element: ( + (_await$platform$isEle = await (platform.isElement == null + ? void 0 + : platform.isElement(element))) != null + ? _await$platform$isEle + : true + ) + ? element + : element.contextElement || + (await (platform.getDocumentElement == null + ? void 0 + : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy, + }) + ); + const rect = + elementContext === "floating" + ? { + ...rects.floating, + x, + y, } - break; + : rects.reference; + const offsetParent = await (platform.getOffsetParent == null + ? void 0 + : platform.getOffsetParent(elements.floating)); + const offsetScale = (await (platform.isElement == null + ? void 0 + : platform.isElement(offsetParent))) + ? (await (platform.getScale == null + ? void 0 + : platform.getScale(offsetParent))) || { + x: 1, + y: 1, } - case 'initialPlacement': - resetPlacement = initialPlacement; - break; - } - } - if (placement !== resetPlacement) { + : { + x: 1, + y: 1, + }; + const elementClientRect = rectToClientRect( + platform.convertOffsetParentRelativeRectToViewportRelativeRect + ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect( + { + rect, + offsetParent, + strategy, + } + ) + : rect + ); return { - reset: { - placement: resetPlacement - } + top: + (clippingClientRect.top - + elementClientRect.top + + paddingObject.top) / + offsetScale.y, + bottom: + (elementClientRect.bottom - + clippingClientRect.bottom + + paddingObject.bottom) / + offsetScale.y, + left: + (clippingClientRect.left - + elementClientRect.left + + paddingObject.left) / + offsetScale.x, + right: + (elementClientRect.right - + clippingClientRect.right + + paddingObject.right) / + offsetScale.x, }; } - } - return {}; - } - }; -}; -exports.flip = flip; -function getSideOffsets(overflow, rect) { - return { - top: overflow.top - rect.height, - right: overflow.right - rect.width, - bottom: overflow.bottom - rect.height, - left: overflow.left - rect.width - }; -} -function isAnySideFullyClipped(overflow) { - return sides.some(side => overflow[side] >= 0); -} -/** - * Provides data to hide the floating element in applicable situations, such as - * when it is not in the same clipping context as the reference element. - * @see https://floating-ui.com/docs/hide - */ -const hide = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'hide', - options, - async fn(state) { - const { - rects - } = state; - const { - strategy = 'referenceHidden', - ...detectOverflowOptions - } = evaluate(options, state); - switch (strategy) { - case 'referenceHidden': - { - const overflow = await detectOverflow(state, { - ...detectOverflowOptions, - elementContext: 'reference' - }); - const offsets = getSideOffsets(overflow, rects.reference); - return { - data: { - referenceHiddenOffsets: offsets, - referenceHidden: isAnySideFullyClipped(offsets) - } + const min = Math.min; + const max = Math.max; + function within(min$1, value, max$1) { + return max(min$1, min(value, max$1)); + } + + /** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ + const arrow = (options) => ({ + name: "arrow", + options, + async fn(state) { + const { x, y, placement, rects, platform, elements } = state; + // Since `element` is required, we don't Partial<> the type. + const { element, padding = 0 } = evaluate(options, state) || {}; + if (element == null) { + return {}; + } + const paddingObject = getSideObjectFromPadding(padding); + const coords = { + x, + y, }; - } - case 'escaped': - { - const overflow = await detectOverflow(state, { - ...detectOverflowOptions, - altBoundary: true - }); - const offsets = getSideOffsets(overflow, rects.floating); + const axis = getMainAxisFromPlacement(placement); + const length = getLengthFromAxis(axis); + const arrowDimensions = await platform.getDimensions(element); + const isYAxis = axis === "y"; + const minProp = isYAxis ? "top" : "left"; + const maxProp = isYAxis ? "bottom" : "right"; + const clientProp = isYAxis ? "clientHeight" : "clientWidth"; + const endDiff = + rects.reference[length] + + rects.reference[axis] - + coords[axis] - + rects.floating[length]; + const startDiff = coords[axis] - rects.reference[axis]; + const arrowOffsetParent = await (platform.getOffsetParent == null + ? void 0 + : platform.getOffsetParent(element)); + let clientSize = arrowOffsetParent + ? arrowOffsetParent[clientProp] + : 0; + + // DOM platform can return `window` as the `offsetParent`. + if ( + !clientSize || + !(await (platform.isElement == null + ? void 0 + : platform.isElement(arrowOffsetParent))) + ) { + clientSize = + elements.floating[clientProp] || rects.floating[length]; + } + const centerToReference = endDiff / 2 - startDiff / 2; + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = + clientSize / 2 - arrowDimensions[length] / 2 - 1; + const minPadding = min( + paddingObject[minProp], + largestPossiblePadding + ); + const maxPadding = min( + paddingObject[maxProp], + largestPossiblePadding + ); + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1 = minPadding; + const max = clientSize - arrowDimensions[length] - maxPadding; + const center = + clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; + const offset = within(min$1, center, max); + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. This stops `shift()` from taking action, but can + // be worked around by calling it again after the `arrow()` if desired. + const shouldAddOffset = + getAlignment(placement) != null && + center != offset && + rects.reference[length] / 2 - + (center < min$1 ? minPadding : maxPadding) - + arrowDimensions[length] / 2 < + 0; + const alignmentOffset = shouldAddOffset + ? center < min$1 + ? min$1 - center + : max - center + : 0; return { + [axis]: coords[axis] - alignmentOffset, data: { - escapedOffsets: offsets, - escaped: isAnySideFullyClipped(offsets) - } - }; - } - default: - { - return {}; - } - } - } - }; -}; -exports.hide = hide; -function getBoundingRect(rects) { - const minX = min(...rects.map(rect => rect.left)); - const minY = min(...rects.map(rect => rect.top)); - const maxX = max(...rects.map(rect => rect.right)); - const maxY = max(...rects.map(rect => rect.bottom)); - return { - x: minX, - y: minY, - width: maxX - minX, - height: maxY - minY - }; -} -function getRectsByLine(rects) { - const sortedRects = rects.slice().sort((a, b) => a.y - b.y); - const groups = []; - let prevRect = null; - for (let i = 0; i < sortedRects.length; i++) { - const rect = sortedRects[i]; - if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { - groups.push([rect]); - } else { - groups[groups.length - 1].push(rect); - } - prevRect = rect; - } - return groups.map(rect => rectToClientRect(getBoundingRect(rect))); -} -/** - * Provides improved positioning for inline reference elements that can span - * over multiple lines, such as hyperlinks or range selections. - * @see https://floating-ui.com/docs/inline - */ -const inline = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'inline', - options, - async fn(state) { - const { - placement, - elements, - rects, - platform, - strategy - } = state; - // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a - // ClientRect's bounds, despite the event listener being triggered. A - // padding of 2 seems to handle this issue. - const { - padding = 2, - x, - y - } = evaluate(options, state); - const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); - const clientRects = getRectsByLine(nativeClientRects); - const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); - const paddingObject = getSideObjectFromPadding(padding); - function getBoundingClientRect() { - // There are two rects and they are disjoined. - if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { - // Find the first rect in which the point is fully inside. - return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; - } - - // There are 2 or more connected rects. - if (clientRects.length >= 2) { - if (getMainAxisFromPlacement(placement) === 'x') { - const firstRect = clientRects[0]; - const lastRect = clientRects[clientRects.length - 1]; - const isTop = getSide(placement) === 'top'; - const top = firstRect.top; - const bottom = lastRect.bottom; - const left = isTop ? firstRect.left : lastRect.left; - const right = isTop ? firstRect.right : lastRect.right; - const width = right - left; - const height = bottom - top; - return { - top, - bottom, - left, - right, - width, - height, - x: left, - y: top + [axis]: offset, + centerOffset: center - offset, + }, }; + }, + }); + exports.arrow = arrow; + const sides = ["top", "right", "bottom", "left"]; + const allPlacements = /*#__PURE__*/ sides.reduce( + (acc, side) => acc.concat(side, side + "-start", side + "-end"), + [] + ); + const oppositeSideMap = { + left: "right", + right: "left", + bottom: "top", + top: "bottom", + }; + function getOppositePlacement(placement) { + return placement.replace( + /left|right|bottom|top/g, + (side) => oppositeSideMap[side] + ); + } + function getAlignmentSides(placement, rects, rtl) { + if (rtl === void 0) { + rtl = false; + } + const alignment = getAlignment(placement); + const mainAxis = getMainAxisFromPlacement(placement); + const length = getLengthFromAxis(mainAxis); + let mainAlignmentSide = + mainAxis === "x" + ? alignment === (rtl ? "end" : "start") + ? "right" + : "left" + : alignment === "start" + ? "bottom" + : "top"; + if (rects.reference[length] > rects.floating[length]) { + mainAlignmentSide = getOppositePlacement(mainAlignmentSide); } - const isLeftSide = getSide(placement) === 'left'; - const maxRight = max(...clientRects.map(rect => rect.right)); - const minLeft = min(...clientRects.map(rect => rect.left)); - const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); - const top = measureRects[0].top; - const bottom = measureRects[measureRects.length - 1].bottom; - const left = minLeft; - const right = maxRight; - const width = right - left; - const height = bottom - top; return { - top, - bottom, - left, - right, - width, - height, - x: left, - y: top + main: mainAlignmentSide, + cross: getOppositePlacement(mainAlignmentSide), }; } - return fallback; - } - const resetRects = await platform.getElementRects({ - reference: { - getBoundingClientRect - }, - floating: elements.floating, - strategy - }); - if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { - return { - reset: { - rects: resetRects - } + const oppositeAlignmentMap = { + start: "end", + end: "start", }; - } - return {}; - } - }; -}; -exports.inline = inline; -async function convertValueToCoords(state, options) { - const { - placement, - platform, - elements - } = state; - const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); - const side = getSide(placement); - const alignment = getAlignment(placement); - const isVertical = getMainAxisFromPlacement(placement) === 'x'; - const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; - const crossAxisMulti = rtl && isVertical ? -1 : 1; - const rawValue = evaluate(options, state); - - // eslint-disable-next-line prefer-const - let { - mainAxis, - crossAxis, - alignmentAxis - } = typeof rawValue === 'number' ? { - mainAxis: rawValue, - crossAxis: 0, - alignmentAxis: null - } : { - mainAxis: 0, - crossAxis: 0, - alignmentAxis: null, - ...rawValue - }; - if (alignment && typeof alignmentAxis === 'number') { - crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; - } - return isVertical ? { - x: crossAxis * crossAxisMulti, - y: mainAxis * mainAxisMulti - } : { - x: mainAxis * mainAxisMulti, - y: crossAxis * crossAxisMulti - }; -} - -/** - * Modifies the placement by translating the floating element along the - * specified axes. - * A number (shorthand for `mainAxis` or distance), or an axes configuration - * object may be passed. - * @see https://floating-ui.com/docs/offset - */ -const offset = function (options) { - if (options === void 0) { - options = 0; - } - return { - name: 'offset', - options, - async fn(state) { - const { - x, - y - } = state; - const diffCoords = await convertValueToCoords(state, options); - return { - x: x + diffCoords.x, - y: y + diffCoords.y, - data: diffCoords - }; - } - }; -}; -exports.offset = offset; -function getCrossAxis(axis) { - return axis === 'x' ? 'y' : 'x'; -} - -/** - * Optimizes the visibility of the floating element by shifting it in order to - * keep it in view when it will overflow the clipping boundary. - * @see https://floating-ui.com/docs/shift - */ -const shift = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'shift', - options, - async fn(state) { - const { - x, - y, - placement - } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = false, - limiter = { - fn: _ref => { - let { - x, - y - } = _ref; - return { - x, - y - }; - } - }, - ...detectOverflowOptions - } = evaluate(options, state); - const coords = { - x, - y - }; - const overflow = await detectOverflow(state, detectOverflowOptions); - const mainAxis = getMainAxisFromPlacement(getSide(placement)); - const crossAxis = getCrossAxis(mainAxis); - let mainAxisCoord = coords[mainAxis]; - let crossAxisCoord = coords[crossAxis]; - if (checkMainAxis) { - const minSide = mainAxis === 'y' ? 'top' : 'left'; - const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; - const min = mainAxisCoord + overflow[minSide]; - const max = mainAxisCoord - overflow[maxSide]; - mainAxisCoord = within(min, mainAxisCoord, max); - } - if (checkCrossAxis) { - const minSide = crossAxis === 'y' ? 'top' : 'left'; - const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; - const min = crossAxisCoord + overflow[minSide]; - const max = crossAxisCoord - overflow[maxSide]; - crossAxisCoord = within(min, crossAxisCoord, max); - } - const limitedCoords = limiter.fn({ - ...state, - [mainAxis]: mainAxisCoord, - [crossAxis]: crossAxisCoord - }); - return { - ...limitedCoords, - data: { - x: limitedCoords.x - x, - y: limitedCoords.y - y - } - }; - } - }; -}; -/** - * Built-in `limiter` that will stop `shift()` at a certain point. - */ -exports.shift = shift; -const limitShift = function (options) { - if (options === void 0) { - options = {}; - } - return { - options, - fn(state) { - const { - x, - y, - placement, - rects, - middlewareData - } = state; - const { - offset = 0, - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true - } = evaluate(options, state); - const coords = { - x, - y - }; - const mainAxis = getMainAxisFromPlacement(placement); - const crossAxis = getCrossAxis(mainAxis); - let mainAxisCoord = coords[mainAxis]; - let crossAxisCoord = coords[crossAxis]; - const rawOffset = evaluate(offset, state); - const computedOffset = typeof rawOffset === 'number' ? { - mainAxis: rawOffset, - crossAxis: 0 - } : { - mainAxis: 0, - crossAxis: 0, - ...rawOffset - }; - if (checkMainAxis) { - const len = mainAxis === 'y' ? 'height' : 'width'; - const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; - const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; - if (mainAxisCoord < limitMin) { - mainAxisCoord = limitMin; - } else if (mainAxisCoord > limitMax) { - mainAxisCoord = limitMax; - } - } - if (checkCrossAxis) { - var _middlewareData$offse, _middlewareData$offse2; - const len = mainAxis === 'y' ? 'width' : 'height'; - const isOriginSide = ['top', 'left'].includes(getSide(placement)); - const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); - const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); - if (crossAxisCoord < limitMin) { - crossAxisCoord = limitMin; - } else if (crossAxisCoord > limitMax) { - crossAxisCoord = limitMax; + function getOppositeAlignmentPlacement(placement) { + return placement.replace( + /start|end/g, + (alignment) => oppositeAlignmentMap[alignment] + ); } - } - return { - [mainAxis]: mainAxisCoord, - [crossAxis]: crossAxisCoord - }; - } - }; -}; - -/** - * Provides data that allows you to change the size of the floating element — - * for instance, prevent it from overflowing the clipping boundary or match the - * width of the reference element. - * @see https://floating-ui.com/docs/size - */ -exports.limitShift = limitShift; -const size = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: 'size', - options, - async fn(state) { - const { - placement, - rects, - platform, - elements - } = state; - const { - apply = () => {}, - ...detectOverflowOptions - } = evaluate(options, state); - const overflow = await detectOverflow(state, detectOverflowOptions); - const side = getSide(placement); - const alignment = getAlignment(placement); - const axis = getMainAxisFromPlacement(placement); - const isXAxis = axis === 'x'; - const { - width, - height - } = rects.floating; - let heightSide; - let widthSide; - if (side === 'top' || side === 'bottom') { - heightSide = side; - widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; - } else { - widthSide = side; - heightSide = alignment === 'end' ? 'top' : 'bottom'; - } - const overflowAvailableHeight = height - overflow[heightSide]; - const overflowAvailableWidth = width - overflow[widthSide]; - const noShift = !state.middlewareData.shift; - let availableHeight = overflowAvailableHeight; - let availableWidth = overflowAvailableWidth; - if (isXAxis) { - const maximumClippingWidth = width - overflow.left - overflow.right; - availableWidth = alignment || noShift ? min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth; - } else { - const maximumClippingHeight = height - overflow.top - overflow.bottom; - availableHeight = alignment || noShift ? min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight; - } - if (noShift && !alignment) { - const xMin = max(overflow.left, 0); - const xMax = max(overflow.right, 0); - const yMin = max(overflow.top, 0); - const yMax = max(overflow.bottom, 0); - if (isXAxis) { - availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); - } else { - availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); + function getPlacementList(alignment, autoAlignment, allowedPlacements) { + const allowedPlacementsSortedByAlignment = alignment + ? [ + ...allowedPlacements.filter( + (placement) => getAlignment(placement) === alignment + ), + ...allowedPlacements.filter( + (placement) => getAlignment(placement) !== alignment + ), + ] + : allowedPlacements.filter( + (placement) => getSide(placement) === placement + ); + return allowedPlacementsSortedByAlignment.filter((placement) => { + if (alignment) { + return ( + getAlignment(placement) === alignment || + (autoAlignment + ? getOppositeAlignmentPlacement(placement) !== placement + : false) + ); + } + return true; + }); } - } - await apply({ - ...state, - availableWidth, - availableHeight - }); - const nextDimensions = await platform.getDimensions(elements.floating); - if (width !== nextDimensions.width || height !== nextDimensions.height) { - return { - reset: { - rects: true + /** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ + const autoPlacement = function (options) { + if (options === void 0) { + options = {}; } - }; - } - return {}; - } - }; -}; -exports.size = size; - -/***/ }), + return { + name: "autoPlacement", + options, + async fn(state) { + var _middlewareData$autoP, + _middlewareData$autoP2, + _placementsThatFitOnE; + const { rects, middlewareData, placement, platform, elements } = + state; + const { + crossAxis = false, + alignment, + allowedPlacements = allPlacements, + autoAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const placements = + alignment !== undefined || allowedPlacements === allPlacements + ? getPlacementList( + alignment || null, + autoAlignment, + allowedPlacements + ) + : allowedPlacements; + const overflow = await detectOverflow( + state, + detectOverflowOptions + ); + const currentIndex = + ((_middlewareData$autoP = middlewareData.autoPlacement) == null + ? void 0 + : _middlewareData$autoP.index) || 0; + const currentPlacement = placements[currentIndex]; + if (currentPlacement == null) { + return {}; + } + const { main, cross } = getAlignmentSides( + currentPlacement, + rects, + await (platform.isRTL == null + ? void 0 + : platform.isRTL(elements.floating)) + ); + + // Make `computeCoords` start from the right place. + if (placement !== currentPlacement) { + return { + reset: { + placement: placements[0], + }, + }; + } + const currentOverflows = [ + overflow[getSide(currentPlacement)], + overflow[main], + overflow[cross], + ]; + const allOverflows = [ + ...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == + null + ? void 0 + : _middlewareData$autoP2.overflows) || []), + { + placement: currentPlacement, + overflows: currentOverflows, + }, + ]; + const nextPlacement = placements[currentIndex + 1]; -/***/ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // There are more placements to check. + if (nextPlacement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows, + }, + reset: { + placement: nextPlacement, + }, + }; + } + const placementsSortedByMostSpace = allOverflows + .map((d) => { + const alignment = getAlignment(d.placement); + return [ + d.placement, + alignment && crossAxis + ? // Check along the mainAxis and main crossAxis side. + d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) + : // Check only the mainAxis. + d.overflows[0], + d.overflows, + ]; + }) + .sort((a, b) => a[1] - b[1]); + const placementsThatFitOnEachSide = + placementsSortedByMostSpace.filter((d) => + d[2] + .slice( + 0, + // Aligned placements should not check their opposite crossAxis + // side. + getAlignment(d[0]) ? 2 : 3 + ) + .every((v) => v <= 0) + ); + const resetPlacement = + ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == + null + ? void 0 + : _placementsThatFitOnE[0]) || + placementsSortedByMostSpace[0][0]; + if (resetPlacement !== placement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows, + }, + reset: { + placement: resetPlacement, + }, + }; + } + return {}; + }, + }; + }; + exports.autoPlacement = autoPlacement; + function getExpandedPlacements(placement) { + const oppositePlacement = getOppositePlacement(placement); + return [ + getOppositeAlignmentPlacement(placement), + oppositePlacement, + getOppositeAlignmentPlacement(oppositePlacement), + ]; + } + function getSideList(side, isStart, rtl) { + const lr = ["left", "right"]; + const rl = ["right", "left"]; + const tb = ["top", "bottom"]; + const bt = ["bottom", "top"]; + switch (side) { + case "top": + case "bottom": + if (rtl) return isStart ? rl : lr; + return isStart ? lr : rl; + case "left": + case "right": + return isStart ? tb : bt; + default: + return []; + } + } + function getOppositeAxisPlacements( + placement, + flipAlignment, + direction, + rtl + ) { + const alignment = getAlignment(placement); + let list = getSideList( + getSide(placement), + direction === "start", + rtl + ); + if (alignment) { + list = list.map((side) => side + "-" + alignment); + if (flipAlignment) { + list = list.concat(list.map(getOppositeAlignmentPlacement)); + } + } + return list; + } + /** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ + const flip = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: "flip", + options, + async fn(state) { + var _middlewareData$flip; + const { + placement, + middlewareData, + rects, + initialPlacement, + platform, + elements, + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = "bestFit", + fallbackAxisSideDirection = "none", + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const side = getSide(placement); + const isBasePlacement = + getSide(initialPlacement) === initialPlacement; + const rtl = await (platform.isRTL == null + ? void 0 + : platform.isRTL(elements.floating)); + const fallbackPlacements = + specifiedFallbackPlacements || + (isBasePlacement || !flipAlignment + ? [getOppositePlacement(initialPlacement)] + : getExpandedPlacements(initialPlacement)); + if ( + !specifiedFallbackPlacements && + fallbackAxisSideDirection !== "none" + ) { + fallbackPlacements.push( + ...getOppositeAxisPlacements( + initialPlacement, + flipAlignment, + fallbackAxisSideDirection, + rtl + ) + ); + } + const placements = [initialPlacement, ...fallbackPlacements]; + const overflow = await detectOverflow( + state, + detectOverflowOptions + ); + const overflows = []; + let overflowsData = + ((_middlewareData$flip = middlewareData.flip) == null + ? void 0 + : _middlewareData$flip.overflows) || []; + if (checkMainAxis) { + overflows.push(overflow[side]); + } + if (checkCrossAxis) { + const { main, cross } = getAlignmentSides( + placement, + rects, + rtl + ); + overflows.push(overflow[main], overflow[cross]); + } + overflowsData = [ + ...overflowsData, + { + placement, + overflows, + }, + ]; + + // One or more sides is overflowing. + if (!overflows.every((side) => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter; + const nextIndex = + (((_middlewareData$flip2 = middlewareData.flip) == null + ? void 0 + : _middlewareData$flip2.index) || 0) + 1; + const nextPlacement = placements[nextIndex]; + if (nextPlacement) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData, + }, + reset: { + placement: nextPlacement, + }, + }; + } + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = + (_overflowsData$filter = overflowsData + .filter((d) => d.overflows[0] <= 0) + .sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null + ? void 0 + : _overflowsData$filter.placement; + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case "bestFit": { + var _overflowsData$map$so; + const placement = + (_overflowsData$map$so = overflowsData + .map((d) => [ + d.placement, + d.overflows + .filter((overflow) => overflow > 0) + .reduce((acc, overflow) => acc + overflow, 0), + ]) + .sort((a, b) => a[1] - b[1])[0]) == null + ? void 0 + : _overflowsData$map$so[0]; + if (placement) { + resetPlacement = placement; + } + break; + } + case "initialPlacement": + resetPlacement = initialPlacement; + break; + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement, + }, + }; + } + } + return {}; + }, + }; + }; + exports.flip = flip; + function getSideOffsets(overflow, rect) { + return { + top: overflow.top - rect.height, + right: overflow.right - rect.width, + bottom: overflow.bottom - rect.height, + left: overflow.left - rect.width, + }; + } + function isAnySideFullyClipped(overflow) { + return sides.some((side) => overflow[side] >= 0); + } + /** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ + const hide = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: "hide", + options, + async fn(state) { + const { rects } = state; + const { strategy = "referenceHidden", ...detectOverflowOptions } = + evaluate(options, state); + switch (strategy) { + case "referenceHidden": { + const overflow = await detectOverflow(state, { + ...detectOverflowOptions, + elementContext: "reference", + }); + const offsets = getSideOffsets(overflow, rects.reference); + return { + data: { + referenceHiddenOffsets: offsets, + referenceHidden: isAnySideFullyClipped(offsets), + }, + }; + } + case "escaped": { + const overflow = await detectOverflow(state, { + ...detectOverflowOptions, + altBoundary: true, + }); + const offsets = getSideOffsets(overflow, rects.floating); + return { + data: { + escapedOffsets: offsets, + escaped: isAnySideFullyClipped(offsets), + }, + }; + } + default: { + return {}; + } + } + }, + }; + }; + exports.hide = hide; + function getBoundingRect(rects) { + const minX = min(...rects.map((rect) => rect.left)); + const minY = min(...rects.map((rect) => rect.top)); + const maxX = max(...rects.map((rect) => rect.right)); + const maxY = max(...rects.map((rect) => rect.bottom)); + return { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY, + }; + } + function getRectsByLine(rects) { + const sortedRects = rects.slice().sort((a, b) => a.y - b.y); + const groups = []; + let prevRect = null; + for (let i = 0; i < sortedRects.length; i++) { + const rect = sortedRects[i]; + if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { + groups.push([rect]); + } else { + groups[groups.length - 1].push(rect); + } + prevRect = rect; + } + return groups.map((rect) => rectToClientRect(getBoundingRect(rect))); + } + /** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ + const inline = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: "inline", + options, + async fn(state) { + const { placement, elements, rects, platform, strategy } = state; + // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a + // ClientRect's bounds, despite the event listener being triggered. A + // padding of 2 seems to handle this issue. + const { padding = 2, x, y } = evaluate(options, state); + const nativeClientRects = Array.from( + (await (platform.getClientRects == null + ? void 0 + : platform.getClientRects(elements.reference))) || [] + ); + const clientRects = getRectsByLine(nativeClientRects); + const fallback = rectToClientRect( + getBoundingRect(nativeClientRects) + ); + const paddingObject = getSideObjectFromPadding(padding); + function getBoundingClientRect() { + // There are two rects and they are disjoined. + if ( + clientRects.length === 2 && + clientRects[0].left > clientRects[1].right && + x != null && + y != null + ) { + // Find the first rect in which the point is fully inside. + return ( + clientRects.find( + (rect) => + x > rect.left - paddingObject.left && + x < rect.right + paddingObject.right && + y > rect.top - paddingObject.top && + y < rect.bottom + paddingObject.bottom + ) || fallback + ); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "arrow", ({ - enumerable: true, - get: function () { - return _core.arrow; - } -})); -Object.defineProperty(exports, "autoPlacement", ({ - enumerable: true, - get: function () { - return _core.autoPlacement; - } -})); -exports.autoUpdate = autoUpdate; -exports.computePosition = void 0; -Object.defineProperty(exports, "detectOverflow", ({ - enumerable: true, - get: function () { - return _core.detectOverflow; - } -})); -Object.defineProperty(exports, "flip", ({ - enumerable: true, - get: function () { - return _core.flip; - } -})); -exports.getOverflowAncestors = getOverflowAncestors; -Object.defineProperty(exports, "hide", ({ - enumerable: true, - get: function () { - return _core.hide; - } -})); -Object.defineProperty(exports, "inline", ({ - enumerable: true, - get: function () { - return _core.inline; - } -})); -Object.defineProperty(exports, "limitShift", ({ - enumerable: true, - get: function () { - return _core.limitShift; - } -})); -Object.defineProperty(exports, "offset", ({ - enumerable: true, - get: function () { - return _core.offset; - } -})); -exports.platform = void 0; -Object.defineProperty(exports, "shift", ({ - enumerable: true, - get: function () { - return _core.shift; - } -})); -Object.defineProperty(exports, "size", ({ - enumerable: true, - get: function () { - return _core.size; - } -})); -var _core = __webpack_require__(/*! @floating-ui/core */ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js"); -function getWindow(node) { - var _node$ownerDocument; - return ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; -} -function getComputedStyle$1(element) { - return getWindow(element).getComputedStyle(element); -} -function isNode(value) { - return value instanceof getWindow(value).Node; -} -function getNodeName(node) { - return isNode(node) ? (node.nodeName || '').toLowerCase() : ''; -} -function isHTMLElement(value) { - return value instanceof getWindow(value).HTMLElement; -} -function isElement(value) { - return value instanceof getWindow(value).Element; -} -function isShadowRoot(node) { - // Browsers without `ShadowRoot` support. - if (typeof ShadowRoot === 'undefined') { - return false; - } - const OwnElement = getWindow(node).ShadowRoot; - return node instanceof OwnElement || node instanceof ShadowRoot; -} -function isOverflowElement(element) { - const { - overflow, - overflowX, - overflowY, - display - } = getComputedStyle$1(element); - return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display); -} -function isTableElement(element) { - return ['table', 'td', 'th'].includes(getNodeName(element)); -} -function isContainingBlock(element) { - const safari = isSafari(); - const css = getComputedStyle$1(element); - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - return css.transform !== 'none' || css.perspective !== 'none' || !safari && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !safari && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value)); -} -function isSafari() { - if (typeof CSS === 'undefined' || !CSS.supports) return false; - return CSS.supports('-webkit-backdrop-filter', 'none'); -} -function isLastTraversableNode(node) { - return ['html', 'body', '#document'].includes(getNodeName(node)); -} -const min = Math.min; -const max = Math.max; -const round = Math.round; -function getCssDimensions(element) { - const css = getComputedStyle$1(element); - // In testing environments, the `width` and `height` properties are empty - // strings for SVG elements, returning NaN. Fallback to `0` in this case. - let width = parseFloat(css.width) || 0; - let height = parseFloat(css.height) || 0; - const hasOffset = isHTMLElement(element); - const offsetWidth = hasOffset ? element.offsetWidth : width; - const offsetHeight = hasOffset ? element.offsetHeight : height; - const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; - if (shouldFallback) { - width = offsetWidth; - height = offsetHeight; - } - return { - width, - height, - fallback: shouldFallback - }; -} -function unwrapElement(element) { - return !isElement(element) ? element.contextElement : element; -} -const FALLBACK_SCALE = { - x: 1, - y: 1 -}; -function getScale(element) { - const domElement = unwrapElement(element); - if (!isHTMLElement(domElement)) { - return FALLBACK_SCALE; - } - const rect = domElement.getBoundingClientRect(); - const { - width, - height, - fallback - } = getCssDimensions(domElement); - let x = (fallback ? round(rect.width) : rect.width) / width; - let y = (fallback ? round(rect.height) : rect.height) / height; - - // 0, NaN, or Infinity should always fallback to 1. - - if (!x || !Number.isFinite(x)) { - x = 1; - } - if (!y || !Number.isFinite(y)) { - y = 1; - } - return { - x, - y - }; -} -const noOffsets = { - x: 0, - y: 0 -}; -function getVisualOffsets(element, isFixed, floatingOffsetParent) { - var _win$visualViewport, _win$visualViewport2; - if (isFixed === void 0) { - isFixed = true; - } - if (!isSafari()) { - return noOffsets; - } - const win = element ? getWindow(element) : window; - if (!floatingOffsetParent || isFixed && floatingOffsetParent !== win) { - return noOffsets; - } - return { - x: ((_win$visualViewport = win.visualViewport) == null ? void 0 : _win$visualViewport.offsetLeft) || 0, - y: ((_win$visualViewport2 = win.visualViewport) == null ? void 0 : _win$visualViewport2.offsetTop) || 0 - }; -} -function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { - if (includeScale === void 0) { - includeScale = false; - } - if (isFixedStrategy === void 0) { - isFixedStrategy = false; - } - const clientRect = element.getBoundingClientRect(); - const domElement = unwrapElement(element); - let scale = FALLBACK_SCALE; - if (includeScale) { - if (offsetParent) { - if (isElement(offsetParent)) { - scale = getScale(offsetParent); - } - } else { - scale = getScale(element); - } - } - const visualOffsets = getVisualOffsets(domElement, isFixedStrategy, offsetParent); - let x = (clientRect.left + visualOffsets.x) / scale.x; - let y = (clientRect.top + visualOffsets.y) / scale.y; - let width = clientRect.width / scale.x; - let height = clientRect.height / scale.y; - if (domElement) { - const win = getWindow(domElement); - const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; - let currentIFrame = win.frameElement; - while (currentIFrame && offsetParent && offsetWin !== win) { - const iframeScale = getScale(currentIFrame); - const iframeRect = currentIFrame.getBoundingClientRect(); - const css = getComputedStyle(currentIFrame); - iframeRect.x += (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; - iframeRect.y += (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; - x *= iframeScale.x; - y *= iframeScale.y; - width *= iframeScale.x; - height *= iframeScale.y; - x += iframeRect.x; - y += iframeRect.y; - currentIFrame = getWindow(currentIFrame).frameElement; - } - } - return (0, _core.rectToClientRect)({ - width, - height, - x, - y - }); -} -function getDocumentElement(node) { - return ((isNode(node) ? node.ownerDocument : node.document) || window.document).documentElement; -} -function getNodeScroll(element) { - if (isElement(element)) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop - }; - } - return { - scrollLeft: element.pageXOffset, - scrollTop: element.pageYOffset - }; -} -function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { - let { - rect, - offsetParent, - strategy - } = _ref; - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - if (offsetParent === documentElement) { - return rect; - } - let scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - let scale = { - x: 1, - y: 1 - }; - const offsets = { - x: 0, - y: 0 - }; - if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') { - if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect(offsetParent); - scale = getScale(offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } - } - return { - width: rect.width * scale.x, - height: rect.height * scale.y, - x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, - y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y - }; -} -function getWindowScrollBarX(element) { - // If has a CSS width greater than the viewport, then this will be - // incorrect for RTL. - return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft; -} - -// Gets the entire size of the scrollable document area, even extending outside -// of the `` and `` rect bounds if horizontally scrollable. -function getDocumentRect(element) { - const html = getDocumentElement(element); - const scroll = getNodeScroll(element); - const body = element.ownerDocument.body; - const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); - const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); - let x = -scroll.scrollLeft + getWindowScrollBarX(element); - const y = -scroll.scrollTop; - if (getComputedStyle$1(body).direction === 'rtl') { - x += max(html.clientWidth, body.clientWidth) - width; - } - return { - width, - height, - x, - y - }; -} -function getParentNode(node) { - if (getNodeName(node) === 'html') { - return node; - } - const result = - // Step into the shadow DOM of the parent of a slotted node. - node.assignedSlot || - // DOM Element detected. - node.parentNode || - // ShadowRoot detected. - isShadowRoot(node) && node.host || - // Fallback. - getDocumentElement(node); - return isShadowRoot(result) ? result.host : result; -} -function getNearestOverflowAncestor(node) { - const parentNode = getParentNode(node); - if (isLastTraversableNode(parentNode)) { - // `getParentNode` will never return a `Document` due to the fallback - // check, so it's either the or element. - return parentNode.ownerDocument.body; - } - if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { - return parentNode; - } - return getNearestOverflowAncestor(parentNode); -} -function getOverflowAncestors(node, list) { - var _node$ownerDocument; - if (list === void 0) { - list = []; - } - const scrollableAncestor = getNearestOverflowAncestor(node); - const isBody = scrollableAncestor === ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.body); - const win = getWindow(scrollableAncestor); - if (isBody) { - return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : []); - } - return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor)); -} -function getViewportRect(element, strategy) { - const win = getWindow(element); - const html = getDocumentElement(element); - const visualViewport = win.visualViewport; - let width = html.clientWidth; - let height = html.clientHeight; - let x = 0; - let y = 0; - if (visualViewport) { - width = visualViewport.width; - height = visualViewport.height; - const visualViewportBased = isSafari(); - if (!visualViewportBased || visualViewportBased && strategy === 'fixed') { - x = visualViewport.offsetLeft; - y = visualViewport.offsetTop; - } - } - return { - width, - height, - x, - y - }; -} - -// Returns the inner client rect, subtracting scrollbars if present. -function getInnerBoundingClientRect(element, strategy) { - const clientRect = getBoundingClientRect(element, true, strategy === 'fixed'); - const top = clientRect.top + element.clientTop; - const left = clientRect.left + element.clientLeft; - const scale = isHTMLElement(element) ? getScale(element) : { - x: 1, - y: 1 - }; - const width = element.clientWidth * scale.x; - const height = element.clientHeight * scale.y; - const x = left * scale.x; - const y = top * scale.y; - return { - width, - height, - x, - y - }; -} -function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { - let rect; - if (clippingAncestor === 'viewport') { - rect = getViewportRect(element, strategy); - } else if (clippingAncestor === 'document') { - rect = getDocumentRect(getDocumentElement(element)); - } else if (isElement(clippingAncestor)) { - rect = getInnerBoundingClientRect(clippingAncestor, strategy); - } else { - const visualOffsets = getVisualOffsets(element); - rect = { - ...clippingAncestor, - x: clippingAncestor.x - visualOffsets.x, - y: clippingAncestor.y - visualOffsets.y - }; - } - return (0, _core.rectToClientRect)(rect); -} -function hasFixedPositionAncestor(element, stopNode) { - const parentNode = getParentNode(element); - if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { - return false; - } - return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode); -} - -// A "clipping ancestor" is an `overflow` element with the characteristic of -// clipping (or hiding) child elements. This returns all clipping ancestors -// of the given element up the tree. -function getClippingElementAncestors(element, cache) { - const cachedResult = cache.get(element); - if (cachedResult) { - return cachedResult; - } - let result = getOverflowAncestors(element).filter(el => isElement(el) && getNodeName(el) !== 'body'); - let currentContainingBlockComputedStyle = null; - const elementIsFixed = getComputedStyle$1(element).position === 'fixed'; - let currentNode = elementIsFixed ? getParentNode(element) : element; - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { - const computedStyle = getComputedStyle$1(currentNode); - const currentNodeIsContaining = isContainingBlock(currentNode); - if (!currentNodeIsContaining && computedStyle.position === 'fixed') { - currentContainingBlockComputedStyle = null; - } - const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); - if (shouldDropCurrentNode) { - // Drop non-containing blocks. - result = result.filter(ancestor => ancestor !== currentNode); - } else { - // Record last containing block for next iteration. - currentContainingBlockComputedStyle = computedStyle; - } - currentNode = getParentNode(currentNode); - } - cache.set(element, result); - return result; -} - -// Gets the maximum area that the element is visible in due to any number of -// clipping ancestors. -function getClippingRect(_ref) { - let { - element, - boundary, - rootBoundary, - strategy - } = _ref; - const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary); - const clippingAncestors = [...elementClippingAncestors, rootBoundary]; - const firstClippingAncestor = clippingAncestors[0]; - const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { - const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); - accRect.top = max(rect.top, accRect.top); - accRect.right = min(rect.right, accRect.right); - accRect.bottom = min(rect.bottom, accRect.bottom); - accRect.left = max(rect.left, accRect.left); - return accRect; - }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); - return { - width: clippingRect.right - clippingRect.left, - height: clippingRect.bottom - clippingRect.top, - x: clippingRect.left, - y: clippingRect.top - }; -} -function getDimensions(element) { - return getCssDimensions(element); -} -function getTrueOffsetParent(element, polyfill) { - if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') { - return null; - } - if (polyfill) { - return polyfill(element); - } - return element.offsetParent; -} -function getContainingBlock(element) { - let currentNode = getParentNode(element); - while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { - if (isContainingBlock(currentNode)) { - return currentNode; - } else { - currentNode = getParentNode(currentNode); - } - } - return null; -} - -// Gets the closest ancestor positioned element. Handles some edge cases, -// such as table ancestors and cross browser bugs. -function getOffsetParent(element, polyfill) { - const window = getWindow(element); - if (!isHTMLElement(element)) { - return window; - } - let offsetParent = getTrueOffsetParent(element, polyfill); - while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') { - offsetParent = getTrueOffsetParent(offsetParent, polyfill); - } - if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) { - return window; - } - return offsetParent || getContainingBlock(element) || window; -} -function getRectRelativeToOffsetParent(element, offsetParent, strategy) { - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - const isFixed = strategy === 'fixed'; - const rect = getBoundingClientRect(element, true, isFixed, offsetParent); - let scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - const offsets = { - x: 0, - y: 0 - }; - if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { - if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement); - } - } - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height - }; -} -const platform = exports.platform = { - getClippingRect, - convertOffsetParentRelativeRectToViewportRelativeRect, - isElement, - getDimensions, - getOffsetParent, - getDocumentElement, - getScale, - async getElementRects(_ref) { - let { - reference, - floating, - strategy - } = _ref; - const getOffsetParentFn = this.getOffsetParent || getOffsetParent; - const getDimensionsFn = this.getDimensions; - return { - reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy), - floating: { - x: 0, - y: 0, - ...(await getDimensionsFn(floating)) - } - }; - }, - getClientRects: element => Array.from(element.getClientRects()), - isRTL: element => getComputedStyle$1(element).direction === 'rtl' -}; + // There are 2 or more connected rects. + if (clientRects.length >= 2) { + if (getMainAxisFromPlacement(placement) === "x") { + const firstRect = clientRects[0]; + const lastRect = clientRects[clientRects.length - 1]; + const isTop = getSide(placement) === "top"; + const top = firstRect.top; + const bottom = lastRect.bottom; + const left = isTop ? firstRect.left : lastRect.left; + const right = isTop ? firstRect.right : lastRect.right; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top, + }; + } + const isLeftSide = getSide(placement) === "left"; + const maxRight = max( + ...clientRects.map((rect) => rect.right) + ); + const minLeft = min(...clientRects.map((rect) => rect.left)); + const measureRects = clientRects.filter((rect) => + isLeftSide ? rect.left === minLeft : rect.right === maxRight + ); + const top = measureRects[0].top; + const bottom = measureRects[measureRects.length - 1].bottom; + const left = minLeft; + const right = maxRight; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top, + }; + } + return fallback; + } + const resetRects = await platform.getElementRects({ + reference: { + getBoundingClientRect, + }, + floating: elements.floating, + strategy, + }); + if ( + rects.reference.x !== resetRects.reference.x || + rects.reference.y !== resetRects.reference.y || + rects.reference.width !== resetRects.reference.width || + rects.reference.height !== resetRects.reference.height + ) { + return { + reset: { + rects: resetRects, + }, + }; + } + return {}; + }, + }; + }; + exports.inline = inline; + async function convertValueToCoords(state, options) { + const { placement, platform, elements } = state; + const rtl = await (platform.isRTL == null + ? void 0 + : platform.isRTL(elements.floating)); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isVertical = getMainAxisFromPlacement(placement) === "x"; + const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1; + const crossAxisMulti = rtl && isVertical ? -1 : 1; + const rawValue = evaluate(options, state); + + // eslint-disable-next-line prefer-const + let { mainAxis, crossAxis, alignmentAxis } = + typeof rawValue === "number" + ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null, + } + : { + mainAxis: 0, + crossAxis: 0, + alignmentAxis: null, + ...rawValue, + }; + if (alignment && typeof alignmentAxis === "number") { + crossAxis = + alignment === "end" ? alignmentAxis * -1 : alignmentAxis; + } + return isVertical + ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti, + } + : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti, + }; + } -/** - * Automatically updates the position of the floating element when necessary. - * Should only be called when the floating element is mounted on the DOM or - * visible on the screen. - * @returns cleanup function that should be invoked when the floating element is - * removed from the DOM or hidden from the screen. - * @see https://floating-ui.com/docs/autoUpdate - */ -function autoUpdate(reference, floating, update, options) { - if (options === void 0) { - options = {}; - } - const { - ancestorScroll = true, - ancestorResize = true, - elementResize = true, - animationFrame = false - } = options; - const ancestors = ancestorScroll || ancestorResize ? [...(isElement(reference) ? getOverflowAncestors(reference) : reference.contextElement ? getOverflowAncestors(reference.contextElement) : []), ...getOverflowAncestors(floating)] : []; - ancestors.forEach(ancestor => { - // ignores Window, checks for [object VisualViewport] - const isVisualViewport = !isElement(ancestor) && ancestor.toString().includes('V'); - if (ancestorScroll && (animationFrame ? isVisualViewport : true)) { - ancestor.addEventListener('scroll', update, { - passive: true - }); - } - ancestorResize && ancestor.addEventListener('resize', update); - }); - let observer = null; - if (elementResize) { - observer = new ResizeObserver(() => { - update(); - }); - isElement(reference) && !animationFrame && observer.observe(reference); - if (!isElement(reference) && reference.contextElement && !animationFrame) { - observer.observe(reference.contextElement); - } - observer.observe(floating); - } - let frameId; - let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null; - if (animationFrame) { - frameLoop(); - } - function frameLoop() { - const nextRefRect = getBoundingClientRect(reference); - if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) { - update(); - } - prevRefRect = nextRefRect; - frameId = requestAnimationFrame(frameLoop); - } - update(); - return () => { - var _observer; - ancestors.forEach(ancestor => { - ancestorScroll && ancestor.removeEventListener('scroll', update); - ancestorResize && ancestor.removeEventListener('resize', update); - }); - (_observer = observer) == null ? void 0 : _observer.disconnect(); - observer = null; - if (animationFrame) { - cancelAnimationFrame(frameId); - } - }; -} - -/** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain CSS positioning - * strategy. - */ -const computePosition = (reference, floating, options) => { - // This caches the expensive `getClippingElementAncestors` function so that - // multiple lifecycle resets re-use the same result. It only lives for a - // single call. If other functions become expensive, we can add them as well. - const cache = new Map(); - const mergedOptions = { - platform, - ...options - }; - const platformWithCache = { - ...mergedOptions.platform, - _c: cache - }; - return (0, _core.computePosition)(reference, floating, { - ...mergedOptions, - platform: platformWithCache - }); -}; -exports.computePosition = computePosition; + /** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ + const offset = function (options) { + if (options === void 0) { + options = 0; + } + return { + name: "offset", + options, + async fn(state) { + const { x, y } = state; + const diffCoords = await convertValueToCoords(state, options); + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: diffCoords, + }; + }, + }; + }; + exports.offset = offset; + function getCrossAxis(axis) { + return axis === "x" ? "y" : "x"; + } -/***/ }), + /** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ + const shift = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: "shift", + options, + async fn(state) { + const { x, y, placement } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: (_ref) => { + let { x, y } = _ref; + return { + x, + y, + }; + }, + }, + ...detectOverflowOptions + } = evaluate(options, state); + const coords = { + x, + y, + }; + const overflow = await detectOverflow( + state, + detectOverflowOptions + ); + const mainAxis = getMainAxisFromPlacement(getSide(placement)); + const crossAxis = getCrossAxis(mainAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + if (checkMainAxis) { + const minSide = mainAxis === "y" ? "top" : "left"; + const maxSide = mainAxis === "y" ? "bottom" : "right"; + const min = mainAxisCoord + overflow[minSide]; + const max = mainAxisCoord - overflow[maxSide]; + mainAxisCoord = within(min, mainAxisCoord, max); + } + if (checkCrossAxis) { + const minSide = crossAxis === "y" ? "top" : "left"; + const maxSide = crossAxis === "y" ? "bottom" : "right"; + const min = crossAxisCoord + overflow[minSide]; + const max = crossAxisCoord - overflow[maxSide]; + crossAxisCoord = within(min, crossAxisCoord, max); + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord, + }); + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y, + }, + }; + }, + }; + }; + /** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ + exports.shift = shift; + const limitShift = function (options) { + if (options === void 0) { + options = {}; + } + return { + options, + fn(state) { + const { x, y, placement, rects, middlewareData } = state; + const { + offset = 0, + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + } = evaluate(options, state); + const coords = { + x, + y, + }; + const mainAxis = getMainAxisFromPlacement(placement); + const crossAxis = getCrossAxis(mainAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + const rawOffset = evaluate(offset, state); + const computedOffset = + typeof rawOffset === "number" + ? { + mainAxis: rawOffset, + crossAxis: 0, + } + : { + mainAxis: 0, + crossAxis: 0, + ...rawOffset, + }; + if (checkMainAxis) { + const len = mainAxis === "y" ? "height" : "width"; + const limitMin = + rects.reference[mainAxis] - + rects.floating[len] + + computedOffset.mainAxis; + const limitMax = + rects.reference[mainAxis] + + rects.reference[len] - + computedOffset.mainAxis; + if (mainAxisCoord < limitMin) { + mainAxisCoord = limitMin; + } else if (mainAxisCoord > limitMax) { + mainAxisCoord = limitMax; + } + } + if (checkCrossAxis) { + var _middlewareData$offse, _middlewareData$offse2; + const len = mainAxis === "y" ? "width" : "height"; + const isOriginSide = ["top", "left"].includes( + getSide(placement) + ); + const limitMin = + rects.reference[crossAxis] - + rects.floating[len] + + (isOriginSide + ? ((_middlewareData$offse = middlewareData.offset) == null + ? void 0 + : _middlewareData$offse[crossAxis]) || 0 + : 0) + + (isOriginSide ? 0 : computedOffset.crossAxis); + const limitMax = + rects.reference[crossAxis] + + rects.reference[len] + + (isOriginSide + ? 0 + : ((_middlewareData$offse2 = middlewareData.offset) == null + ? void 0 + : _middlewareData$offse2[crossAxis]) || 0) - + (isOriginSide ? computedOffset.crossAxis : 0); + if (crossAxisCoord < limitMin) { + crossAxisCoord = limitMin; + } else if (crossAxisCoord > limitMax) { + crossAxisCoord = limitMax; + } + } + return { + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord, + }; + }, + }; + }; -/***/ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ + exports.limitShift = limitShift; + const size = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: "size", + options, + async fn(state) { + const { placement, rects, platform, elements } = state; + const { apply = () => {}, ...detectOverflowOptions } = evaluate( + options, + state + ); + const overflow = await detectOverflow( + state, + detectOverflowOptions + ); + const side = getSide(placement); + const alignment = getAlignment(placement); + const axis = getMainAxisFromPlacement(placement); + const isXAxis = axis === "x"; + const { width, height } = rects.floating; + let heightSide; + let widthSide; + if (side === "top" || side === "bottom") { + heightSide = side; + widthSide = + alignment === + ((await (platform.isRTL == null + ? void 0 + : platform.isRTL(elements.floating))) + ? "start" + : "end") + ? "left" + : "right"; + } else { + widthSide = side; + heightSide = alignment === "end" ? "top" : "bottom"; + } + const overflowAvailableHeight = height - overflow[heightSide]; + const overflowAvailableWidth = width - overflow[widthSide]; + const noShift = !state.middlewareData.shift; + let availableHeight = overflowAvailableHeight; + let availableWidth = overflowAvailableWidth; + if (isXAxis) { + const maximumClippingWidth = + width - overflow.left - overflow.right; + availableWidth = + alignment || noShift + ? min(overflowAvailableWidth, maximumClippingWidth) + : maximumClippingWidth; + } else { + const maximumClippingHeight = + height - overflow.top - overflow.bottom; + availableHeight = + alignment || noShift + ? min(overflowAvailableHeight, maximumClippingHeight) + : maximumClippingHeight; + } + if (noShift && !alignment) { + const xMin = max(overflow.left, 0); + const xMax = max(overflow.right, 0); + const yMin = max(overflow.top, 0); + const yMax = max(overflow.bottom, 0); + if (isXAxis) { + availableWidth = + width - + 2 * + (xMin !== 0 || xMax !== 0 + ? xMin + xMax + : max(overflow.left, overflow.right)); + } else { + availableHeight = + height - + 2 * + (yMin !== 0 || yMax !== 0 + ? yMin + yMax + : max(overflow.top, overflow.bottom)); + } + } + await apply({ + ...state, + availableWidth, + availableHeight, + }); + const nextDimensions = await platform.getDimensions( + elements.floating + ); + if ( + width !== nextDimensions.width || + height !== nextDimensions.height + ) { + return { + reset: { + rects: true, + }, + }; + } + return {}; + }, + }; + }; + exports.size = size; + /***/ + }, + /***/ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "arrow", { + enumerable: true, + get: function () { + return _core.arrow; + }, + }); + Object.defineProperty(exports, "autoPlacement", { + enumerable: true, + get: function () { + return _core.autoPlacement; + }, + }); + exports.autoUpdate = autoUpdate; + exports.computePosition = void 0; + Object.defineProperty(exports, "detectOverflow", { + enumerable: true, + get: function () { + return _core.detectOverflow; + }, + }); + Object.defineProperty(exports, "flip", { + enumerable: true, + get: function () { + return _core.flip; + }, + }); + exports.getOverflowAncestors = getOverflowAncestors; + Object.defineProperty(exports, "hide", { + enumerable: true, + get: function () { + return _core.hide; + }, + }); + Object.defineProperty(exports, "inline", { + enumerable: true, + get: function () { + return _core.inline; + }, + }); + Object.defineProperty(exports, "limitShift", { + enumerable: true, + get: function () { + return _core.limitShift; + }, + }); + Object.defineProperty(exports, "offset", { + enumerable: true, + get: function () { + return _core.offset; + }, + }); + exports.platform = void 0; + Object.defineProperty(exports, "shift", { + enumerable: true, + get: function () { + return _core.shift; + }, + }); + Object.defineProperty(exports, "size", { + enumerable: true, + get: function () { + return _core.size; + }, + }); + var _core = __webpack_require__( + /*! @floating-ui/core */ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js" + ); + function getWindow(node) { + var _node$ownerDocument; + return ( + ((_node$ownerDocument = node.ownerDocument) == null + ? void 0 + : _node$ownerDocument.defaultView) || window + ); + } + function getComputedStyle$1(element) { + return getWindow(element).getComputedStyle(element); + } + function isNode(value) { + return value instanceof getWindow(value).Node; + } + function getNodeName(node) { + return isNode(node) ? (node.nodeName || "").toLowerCase() : ""; + } + function isHTMLElement(value) { + return value instanceof getWindow(value).HTMLElement; + } + function isElement(value) { + return value instanceof getWindow(value).Element; + } + function isShadowRoot(node) { + // Browsers without `ShadowRoot` support. + if (typeof ShadowRoot === "undefined") { + return false; + } + const OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; + } + function isOverflowElement(element) { + const { overflow, overflowX, overflowY, display } = + getComputedStyle$1(element); + return ( + /auto|scroll|overlay|hidden|clip/.test( + overflow + overflowY + overflowX + ) && !["inline", "contents"].includes(display) + ); + } + function isTableElement(element) { + return ["table", "td", "th"].includes(getNodeName(element)); + } + function isContainingBlock(element) { + const safari = isSafari(); + const css = getComputedStyle$1(element); + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + return ( + css.transform !== "none" || + css.perspective !== "none" || + (!safari && + (css.backdropFilter ? css.backdropFilter !== "none" : false)) || + (!safari && (css.filter ? css.filter !== "none" : false)) || + ["transform", "perspective", "filter"].some((value) => + (css.willChange || "").includes(value) + ) || + ["paint", "layout", "strict", "content"].some((value) => + (css.contain || "").includes(value) + ) + ); + } + function isSafari() { + if (typeof CSS === "undefined" || !CSS.supports) return false; + return CSS.supports("-webkit-backdrop-filter", "none"); + } + function isLastTraversableNode(node) { + return ["html", "body", "#document"].includes(getNodeName(node)); + } + const min = Math.min; + const max = Math.max; + const round = Math.round; + function getCssDimensions(element) { + const css = getComputedStyle$1(element); + // In testing environments, the `width` and `height` properties are empty + // strings for SVG elements, returning NaN. Fallback to `0` in this case. + let width = parseFloat(css.width) || 0; + let height = parseFloat(css.height) || 0; + const hasOffset = isHTMLElement(element); + const offsetWidth = hasOffset ? element.offsetWidth : width; + const offsetHeight = hasOffset ? element.offsetHeight : height; + const shouldFallback = + round(width) !== offsetWidth || round(height) !== offsetHeight; + if (shouldFallback) { + width = offsetWidth; + height = offsetHeight; + } + return { + width, + height, + fallback: shouldFallback, + }; + } + function unwrapElement(element) { + return !isElement(element) ? element.contextElement : element; + } + const FALLBACK_SCALE = { + x: 1, + y: 1, + }; + function getScale(element) { + const domElement = unwrapElement(element); + if (!isHTMLElement(domElement)) { + return FALLBACK_SCALE; + } + const rect = domElement.getBoundingClientRect(); + const { width, height, fallback } = getCssDimensions(domElement); + let x = (fallback ? round(rect.width) : rect.width) / width; + let y = (fallback ? round(rect.height) : rect.height) / height; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.arrow = void 0; -Object.defineProperty(exports, "autoPlacement", ({ - enumerable: true, - get: function () { - return _dom.autoPlacement; - } -})); -Object.defineProperty(exports, "autoUpdate", ({ - enumerable: true, - get: function () { - return _dom.autoUpdate; - } -})); -Object.defineProperty(exports, "computePosition", ({ - enumerable: true, - get: function () { - return _dom.computePosition; - } -})); -Object.defineProperty(exports, "detectOverflow", ({ - enumerable: true, - get: function () { - return _dom.detectOverflow; - } -})); -Object.defineProperty(exports, "flip", ({ - enumerable: true, - get: function () { - return _dom.flip; - } -})); -Object.defineProperty(exports, "getOverflowAncestors", ({ - enumerable: true, - get: function () { - return _dom.getOverflowAncestors; - } -})); -Object.defineProperty(exports, "hide", ({ - enumerable: true, - get: function () { - return _dom.hide; - } -})); -Object.defineProperty(exports, "inline", ({ - enumerable: true, - get: function () { - return _dom.inline; - } -})); -Object.defineProperty(exports, "limitShift", ({ - enumerable: true, - get: function () { - return _dom.limitShift; - } -})); -Object.defineProperty(exports, "offset", ({ - enumerable: true, - get: function () { - return _dom.offset; - } -})); -Object.defineProperty(exports, "platform", ({ - enumerable: true, - get: function () { - return _dom.platform; - } -})); -Object.defineProperty(exports, "shift", ({ - enumerable: true, - get: function () { - return _dom.shift; - } -})); -Object.defineProperty(exports, "size", ({ - enumerable: true, - get: function () { - return _dom.size; - } -})); -exports.useFloating = useFloating; -var _dom = __webpack_require__(/*! @floating-ui/dom */ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js"); -var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var React = _react; -var ReactDOM = _interopRequireWildcard(__webpack_require__(/*! react-dom */ "react-dom")); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -/** - * Provides data to position an inner element of the floating element so that it - * appears centered to the reference element. - * This wraps the core `arrow` middleware to allow React refs as the element. - * @see https://floating-ui.com/docs/arrow - */ -const arrow = options => { - function isRef(value) { - return {}.hasOwnProperty.call(value, 'current'); - } - return { - name: 'arrow', - options, - fn(state) { - const { - element, - padding - } = typeof options === 'function' ? options(state) : options; - if (element && isRef(element)) { - if (element.current != null) { - return (0, _dom.arrow)({ - element: element.current, - padding - }).fn(state); - } - return {}; - } else if (element) { - return (0, _dom.arrow)({ - element, - padding - }).fn(state); - } - return {}; - } - }; -}; -exports.arrow = arrow; -var index = typeof document !== 'undefined' ? _react.useLayoutEffect : _react.useEffect; + // 0, NaN, or Infinity should always fallback to 1. -// Fork of `fast-deep-equal` that only does the comparisons we need and compares -// functions -function deepEqual(a, b) { - if (a === b) { - return true; - } - if (typeof a !== typeof b) { - return false; - } - if (typeof a === 'function' && a.toString() === b.toString()) { - return true; - } - let length, i, keys; - if (a && b && typeof a == 'object') { - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) { - if (!deepEqual(a[i], b[i])) { - return false; + if (!x || !Number.isFinite(x)) { + x = 1; + } + if (!y || !Number.isFinite(y)) { + y = 1; + } + return { + x, + y, + }; + } + const noOffsets = { + x: 0, + y: 0, + }; + function getVisualOffsets(element, isFixed, floatingOffsetParent) { + var _win$visualViewport, _win$visualViewport2; + if (isFixed === void 0) { + isFixed = true; + } + if (!isSafari()) { + return noOffsets; + } + const win = element ? getWindow(element) : window; + if ( + !floatingOffsetParent || + (isFixed && floatingOffsetParent !== win) + ) { + return noOffsets; + } + return { + x: + ((_win$visualViewport = win.visualViewport) == null + ? void 0 + : _win$visualViewport.offsetLeft) || 0, + y: + ((_win$visualViewport2 = win.visualViewport) == null + ? void 0 + : _win$visualViewport2.offsetTop) || 0, + }; + } + function getBoundingClientRect( + element, + includeScale, + isFixedStrategy, + offsetParent + ) { + if (includeScale === void 0) { + includeScale = false; + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + const clientRect = element.getBoundingClientRect(); + const domElement = unwrapElement(element); + let scale = FALLBACK_SCALE; + if (includeScale) { + if (offsetParent) { + if (isElement(offsetParent)) { + scale = getScale(offsetParent); + } + } else { + scale = getScale(element); + } + } + const visualOffsets = getVisualOffsets( + domElement, + isFixedStrategy, + offsetParent + ); + let x = (clientRect.left + visualOffsets.x) / scale.x; + let y = (clientRect.top + visualOffsets.y) / scale.y; + let width = clientRect.width / scale.x; + let height = clientRect.height / scale.y; + if (domElement) { + const win = getWindow(domElement); + const offsetWin = + offsetParent && isElement(offsetParent) + ? getWindow(offsetParent) + : offsetParent; + let currentIFrame = win.frameElement; + while (currentIFrame && offsetParent && offsetWin !== win) { + const iframeScale = getScale(currentIFrame); + const iframeRect = currentIFrame.getBoundingClientRect(); + const css = getComputedStyle(currentIFrame); + iframeRect.x += + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * + iframeScale.x; + iframeRect.y += + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * + iframeScale.y; + x *= iframeScale.x; + y *= iframeScale.y; + width *= iframeScale.x; + height *= iframeScale.y; + x += iframeRect.x; + y += iframeRect.y; + currentIFrame = getWindow(currentIFrame).frameElement; + } + } + return (0, _core.rectToClientRect)({ + width, + height, + x, + y, + }); + } + function getDocumentElement(node) { + return ( + (isNode(node) ? node.ownerDocument : node.document) || + window.document + ).documentElement; + } + function getNodeScroll(element) { + if (isElement(element)) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop, + }; + } + return { + scrollLeft: element.pageXOffset, + scrollTop: element.pageYOffset, + }; + } + function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { + let { rect, offsetParent, strategy } = _ref; + const isOffsetParentAnElement = isHTMLElement(offsetParent); + const documentElement = getDocumentElement(offsetParent); + if (offsetParent === documentElement) { + return rect; + } + let scroll = { + scrollLeft: 0, + scrollTop: 0, + }; + let scale = { + x: 1, + y: 1, + }; + const offsets = { + x: 0, + y: 0, + }; + if ( + isOffsetParentAnElement || + (!isOffsetParentAnElement && strategy !== "fixed") + ) { + if ( + getNodeName(offsetParent) !== "body" || + isOverflowElement(documentElement) + ) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + const offsetRect = getBoundingClientRect(offsetParent); + scale = getScale(offsetParent); + offsets.x = offsetRect.x + offsetParent.clientLeft; + offsets.y = offsetRect.y + offsetParent.clientTop; + } + } + return { + width: rect.width * scale.x, + height: rect.height * scale.y, + x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, + y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y, + }; + } + function getWindowScrollBarX(element) { + // If has a CSS width greater than the viewport, then this will be + // incorrect for RTL. + return ( + getBoundingClientRect(getDocumentElement(element)).left + + getNodeScroll(element).scrollLeft + ); } - } - return true; - } - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) { - return false; - } - for (i = length; i-- !== 0;) { - if (!{}.hasOwnProperty.call(b, keys[i])) { - return false; - } - } - for (i = length; i-- !== 0;) { - const key = keys[i]; - if (key === '_owner' && a.$$typeof) { - continue; - } - if (!deepEqual(a[key], b[key])) { - return false; - } - } - return true; - } - return a !== a && b !== b; -} -function getDPR(element) { - if (typeof window === 'undefined') { - return 1; - } - const win = element.ownerDocument.defaultView || window; - return win.devicePixelRatio || 1; -} -function roundByDPR(element, value) { - const dpr = getDPR(element); - return Math.round(value * dpr) / dpr; -} -function useLatestRef(value) { - const ref = React.useRef(value); - index(() => { - ref.current = value; - }); - return ref; -} - -/** - * Provides data to position a floating element. - * @see https://floating-ui.com/docs/react - */ -function useFloating(options) { - if (options === void 0) { - options = {}; - } - const { - placement = 'bottom', - strategy = 'absolute', - middleware = [], - platform, - elements: { - reference: externalReference, - floating: externalFloating - } = {}, - transform = true, - whileElementsMounted, - open - } = options; - const [data, setData] = React.useState({ - x: 0, - y: 0, - strategy, - placement, - middlewareData: {}, - isPositioned: false - }); - const [latestMiddleware, setLatestMiddleware] = React.useState(middleware); - if (!deepEqual(latestMiddleware, middleware)) { - setLatestMiddleware(middleware); - } - const [_reference, _setReference] = React.useState(null); - const [_floating, _setFloating] = React.useState(null); - const setReference = React.useCallback(node => { - if (node != referenceRef.current) { - referenceRef.current = node; - _setReference(node); - } - }, [_setReference]); - const setFloating = React.useCallback(node => { - if (node !== floatingRef.current) { - floatingRef.current = node; - _setFloating(node); - } - }, [_setFloating]); - const referenceEl = externalReference || _reference; - const floatingEl = externalFloating || _floating; - const referenceRef = React.useRef(null); - const floatingRef = React.useRef(null); - const dataRef = React.useRef(data); - const whileElementsMountedRef = useLatestRef(whileElementsMounted); - const platformRef = useLatestRef(platform); - const update = React.useCallback(() => { - if (!referenceRef.current || !floatingRef.current) { - return; - } - const config = { - placement, - strategy, - middleware: latestMiddleware - }; - if (platformRef.current) { - config.platform = platformRef.current; - } - (0, _dom.computePosition)(referenceRef.current, floatingRef.current, config).then(data => { - const fullData = { - ...data, - isPositioned: true - }; - if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) { - dataRef.current = fullData; - ReactDOM.flushSync(() => { - setData(fullData); - }); - } - }); - }, [latestMiddleware, placement, strategy, platformRef]); - index(() => { - if (open === false && dataRef.current.isPositioned) { - dataRef.current.isPositioned = false; - setData(data => ({ - ...data, - isPositioned: false - })); - } - }, [open]); - const isMountedRef = React.useRef(false); - index(() => { - isMountedRef.current = true; - return () => { - isMountedRef.current = false; - }; - }, []); - index(() => { - if (referenceEl) referenceRef.current = referenceEl; - if (floatingEl) floatingRef.current = floatingEl; - if (referenceEl && floatingEl) { - if (whileElementsMountedRef.current) { - return whileElementsMountedRef.current(referenceEl, floatingEl, update); - } else { - update(); - } - } - }, [referenceEl, floatingEl, update, whileElementsMountedRef]); - const refs = React.useMemo(() => ({ - reference: referenceRef, - floating: floatingRef, - setReference, - setFloating - }), [setReference, setFloating]); - const elements = React.useMemo(() => ({ - reference: referenceEl, - floating: floatingEl - }), [referenceEl, floatingEl]); - const floatingStyles = React.useMemo(() => { - const initialStyles = { - position: strategy, - left: 0, - top: 0 - }; - if (!elements.floating) { - return initialStyles; - } - const x = roundByDPR(elements.floating, data.x); - const y = roundByDPR(elements.floating, data.y); - if (transform) { - return { - ...initialStyles, - transform: "translate(" + x + "px, " + y + "px)", - ...(getDPR(elements.floating) >= 1.5 && { - willChange: 'transform' - }) - }; - } - return { - position: strategy, - left: x, - top: y - }; - }, [strategy, transform, elements.floating, data.x, data.y]); - return React.useMemo(() => ({ - ...data, - update, - refs, - elements, - floatingStyles - }), [data, update, refs, elements, floatingStyles]); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/animation/dist/Animation.es.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/Animation.es.js ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Animation = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js"); -class Animation { - constructor(output, keyframes = [0, 1], { - easing, - duration: initialDuration = _utils.defaults.duration, - delay = _utils.defaults.delay, - endDelay = _utils.defaults.endDelay, - repeat = _utils.defaults.repeat, - offset, - direction = "normal" - } = {}) { - this.startTime = null; - this.rate = 1; - this.t = 0; - this.cancelTimestamp = null; - this.easing = _utils.noopReturn; - this.duration = 0; - this.totalDuration = 0; - this.repeat = 0; - this.playState = "idle"; - this.finished = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - easing = easing || _utils.defaults.easing; - if ((0, _utils.isEasingGenerator)(easing)) { - const custom = easing.createAnimation(keyframes); - easing = custom.easing; - keyframes = custom.keyframes || keyframes; - initialDuration = custom.duration || initialDuration; - } - this.repeat = repeat; - this.easing = (0, _utils.isEasingList)(easing) ? _utils.noopReturn : (0, _easingEs.getEasingFunction)(easing); - this.updateDuration(initialDuration); - const interpolate$1 = (0, _utils.interpolate)(keyframes, offset, (0, _utils.isEasingList)(easing) ? easing.map(_easingEs.getEasingFunction) : _utils.noopReturn); - this.tick = timestamp => { - var _a; - // TODO: Temporary fix for OptionsResolver typing - delay = delay; - let t = 0; - if (this.pauseTime !== undefined) { - t = this.pauseTime; - } else { - t = (timestamp - this.startTime) * this.rate; - } - this.t = t; - // Convert to seconds - t /= 1000; - // Rebase on delay - t = Math.max(t - delay, 0); - /** - * If this animation has finished, set the current time - * to the total duration. - */ - if (this.playState === "finished" && this.pauseTime === undefined) { - t = this.totalDuration; - } - /** - * Get the current progress (0-1) of the animation. If t is > - * than duration we'll get values like 2.5 (midway through the - * third iteration) - */ - const progress = t / this.duration; - // TODO progress += iterationStart - /** - * Get the current iteration (0 indexed). For instance the floor of - * 2.5 is 2. - */ - let currentIteration = Math.floor(progress); - /** - * Get the current progress of the iteration by taking the remainder - * so 2.5 is 0.5 through iteration 2 - */ - let iterationProgress = progress % 1.0; - if (!iterationProgress && progress >= 1) { - iterationProgress = 1; - } - /** - * If iteration progress is 1 we count that as the end - * of the previous iteration. - */ - iterationProgress === 1 && currentIteration--; - /** - * Reverse progress if we're not running in "normal" direction - */ - const iterationIsOdd = currentIteration % 2; - if (direction === "reverse" || direction === "alternate" && iterationIsOdd || direction === "alternate-reverse" && !iterationIsOdd) { - iterationProgress = 1 - iterationProgress; - } - const p = t >= this.totalDuration ? 1 : Math.min(iterationProgress, 1); - const latest = interpolate$1(this.easing(p)); - output(latest); - const isAnimationFinished = this.pauseTime === undefined && (this.playState === "finished" || t >= this.totalDuration + endDelay); - if (isAnimationFinished) { - this.playState = "finished"; - (_a = this.resolve) === null || _a === void 0 ? void 0 : _a.call(this, latest); - } else if (this.playState !== "idle") { - this.frameRequestId = requestAnimationFrame(this.tick); - } - }; - this.play(); - } - play() { - const now = performance.now(); - this.playState = "running"; - if (this.pauseTime !== undefined) { - this.startTime = now - this.pauseTime; - } else if (!this.startTime) { - this.startTime = now; - } - this.cancelTimestamp = this.startTime; - this.pauseTime = undefined; - this.frameRequestId = requestAnimationFrame(this.tick); - } - pause() { - this.playState = "paused"; - this.pauseTime = this.t; - } - finish() { - this.playState = "finished"; - this.tick(0); - } - stop() { - var _a; - this.playState = "idle"; - if (this.frameRequestId !== undefined) { - cancelAnimationFrame(this.frameRequestId); - } - (_a = this.reject) === null || _a === void 0 ? void 0 : _a.call(this, false); - } - cancel() { - this.stop(); - this.tick(this.cancelTimestamp); - } - reverse() { - this.rate *= -1; - } - commitStyles() {} - updateDuration(duration) { - this.duration = duration; - this.totalDuration = duration * (this.repeat + 1); - } - get currentTime() { - return this.t; - } - set currentTime(t) { - if (this.pauseTime !== undefined || this.rate === 0) { - this.pauseTime = t; - } else { - this.startTime = performance.now() - t / this.rate; - } - } - get playbackRate() { - return this.rate; - } - set playbackRate(rate) { - this.rate = rate; - } -} -exports.Animation = Animation; -/***/ }), + // Gets the entire size of the scrollable document area, even extending outside + // of the `` and `` rect bounds if horizontally scrollable. + function getDocumentRect(element) { + const html = getDocumentElement(element); + const scroll = getNodeScroll(element); + const body = element.ownerDocument.body; + const width = max( + html.scrollWidth, + html.clientWidth, + body.scrollWidth, + body.clientWidth + ); + const height = max( + html.scrollHeight, + html.clientHeight, + body.scrollHeight, + body.clientHeight + ); + let x = -scroll.scrollLeft + getWindowScrollBarX(element); + const y = -scroll.scrollTop; + if (getComputedStyle$1(body).direction === "rtl") { + x += max(html.clientWidth, body.clientWidth) - width; + } + return { + width, + height, + x, + y, + }; + } + function getParentNode(node) { + if (getNodeName(node) === "html") { + return node; + } + const result = + // Step into the shadow DOM of the parent of a slotted node. + node.assignedSlot || + // DOM Element detected. + node.parentNode || + // ShadowRoot detected. + (isShadowRoot(node) && node.host) || + // Fallback. + getDocumentElement(node); + return isShadowRoot(result) ? result.host : result; + } + function getNearestOverflowAncestor(node) { + const parentNode = getParentNode(node); + if (isLastTraversableNode(parentNode)) { + // `getParentNode` will never return a `Document` due to the fallback + // check, so it's either the or element. + return parentNode.ownerDocument.body; + } + if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { + return parentNode; + } + return getNearestOverflowAncestor(parentNode); + } + function getOverflowAncestors(node, list) { + var _node$ownerDocument; + if (list === void 0) { + list = []; + } + const scrollableAncestor = getNearestOverflowAncestor(node); + const isBody = + scrollableAncestor === + ((_node$ownerDocument = node.ownerDocument) == null + ? void 0 + : _node$ownerDocument.body); + const win = getWindow(scrollableAncestor); + if (isBody) { + return list.concat( + win, + win.visualViewport || [], + isOverflowElement(scrollableAncestor) ? scrollableAncestor : [] + ); + } + return list.concat( + scrollableAncestor, + getOverflowAncestors(scrollableAncestor) + ); + } + function getViewportRect(element, strategy) { + const win = getWindow(element); + const html = getDocumentElement(element); + const visualViewport = win.visualViewport; + let width = html.clientWidth; + let height = html.clientHeight; + let x = 0; + let y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + const visualViewportBased = isSafari(); + if ( + !visualViewportBased || + (visualViewportBased && strategy === "fixed") + ) { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + return { + width, + height, + x, + y, + }; + } -/***/ "../../../node_modules/@motionone/animation/dist/index.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/index.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // Returns the inner client rect, subtracting scrollbars if present. + function getInnerBoundingClientRect(element, strategy) { + const clientRect = getBoundingClientRect( + element, + true, + strategy === "fixed" + ); + const top = clientRect.top + element.clientTop; + const left = clientRect.left + element.clientLeft; + const scale = isHTMLElement(element) + ? getScale(element) + : { + x: 1, + y: 1, + }; + const width = element.clientWidth * scale.x; + const height = element.clientHeight * scale.y; + const x = left * scale.x; + const y = top * scale.y; + return { + width, + height, + x, + y, + }; + } + function getClientRectFromClippingAncestor( + element, + clippingAncestor, + strategy + ) { + let rect; + if (clippingAncestor === "viewport") { + rect = getViewportRect(element, strategy); + } else if (clippingAncestor === "document") { + rect = getDocumentRect(getDocumentElement(element)); + } else if (isElement(clippingAncestor)) { + rect = getInnerBoundingClientRect(clippingAncestor, strategy); + } else { + const visualOffsets = getVisualOffsets(element); + rect = { + ...clippingAncestor, + x: clippingAncestor.x - visualOffsets.x, + y: clippingAncestor.y - visualOffsets.y, + }; + } + return (0, _core.rectToClientRect)(rect); + } + function hasFixedPositionAncestor(element, stopNode) { + const parentNode = getParentNode(element); + if ( + parentNode === stopNode || + !isElement(parentNode) || + isLastTraversableNode(parentNode) + ) { + return false; + } + return ( + getComputedStyle$1(parentNode).position === "fixed" || + hasFixedPositionAncestor(parentNode, stopNode) + ); + } + // A "clipping ancestor" is an `overflow` element with the characteristic of + // clipping (or hiding) child elements. This returns all clipping ancestors + // of the given element up the tree. + function getClippingElementAncestors(element, cache) { + const cachedResult = cache.get(element); + if (cachedResult) { + return cachedResult; + } + let result = getOverflowAncestors(element).filter( + (el) => isElement(el) && getNodeName(el) !== "body" + ); + let currentContainingBlockComputedStyle = null; + const elementIsFixed = + getComputedStyle$1(element).position === "fixed"; + let currentNode = elementIsFixed ? getParentNode(element) : element; + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + while ( + isElement(currentNode) && + !isLastTraversableNode(currentNode) + ) { + const computedStyle = getComputedStyle$1(currentNode); + const currentNodeIsContaining = isContainingBlock(currentNode); + if ( + !currentNodeIsContaining && + computedStyle.position === "fixed" + ) { + currentContainingBlockComputedStyle = null; + } + const shouldDropCurrentNode = elementIsFixed + ? !currentNodeIsContaining && !currentContainingBlockComputedStyle + : (!currentNodeIsContaining && + computedStyle.position === "static" && + !!currentContainingBlockComputedStyle && + ["absolute", "fixed"].includes( + currentContainingBlockComputedStyle.position + )) || + (isOverflowElement(currentNode) && + !currentNodeIsContaining && + hasFixedPositionAncestor(element, currentNode)); + if (shouldDropCurrentNode) { + // Drop non-containing blocks. + result = result.filter((ancestor) => ancestor !== currentNode); + } else { + // Record last containing block for next iteration. + currentContainingBlockComputedStyle = computedStyle; + } + currentNode = getParentNode(currentNode); + } + cache.set(element, result); + return result; + } + // Gets the maximum area that the element is visible in due to any number of + // clipping ancestors. + function getClippingRect(_ref) { + let { element, boundary, rootBoundary, strategy } = _ref; + const elementClippingAncestors = + boundary === "clippingAncestors" + ? getClippingElementAncestors(element, this._c) + : [].concat(boundary); + const clippingAncestors = [...elementClippingAncestors, rootBoundary]; + const firstClippingAncestor = clippingAncestors[0]; + const clippingRect = clippingAncestors.reduce( + (accRect, clippingAncestor) => { + const rect = getClientRectFromClippingAncestor( + element, + clippingAncestor, + strategy + ); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, + getClientRectFromClippingAncestor( + element, + firstClippingAncestor, + strategy + ) + ); + return { + width: clippingRect.right - clippingRect.left, + height: clippingRect.bottom - clippingRect.top, + x: clippingRect.left, + y: clippingRect.top, + }; + } + function getDimensions(element) { + return getCssDimensions(element); + } + function getTrueOffsetParent(element, polyfill) { + if ( + !isHTMLElement(element) || + getComputedStyle$1(element).position === "fixed" + ) { + return null; + } + if (polyfill) { + return polyfill(element); + } + return element.offsetParent; + } + function getContainingBlock(element) { + let currentNode = getParentNode(element); + while ( + isHTMLElement(currentNode) && + !isLastTraversableNode(currentNode) + ) { + if (isContainingBlock(currentNode)) { + return currentNode; + } else { + currentNode = getParentNode(currentNode); + } + } + return null; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "Animation", ({ - enumerable: true, - get: function () { - return _AnimationEs.Animation; - } -})); -Object.defineProperty(exports, "getEasingFunction", ({ - enumerable: true, - get: function () { - return _easingEs.getEasingFunction; - } -})); -var _AnimationEs = __webpack_require__(/*! ./Animation.es.js */ "../../../node_modules/@motionone/animation/dist/Animation.es.js"); -var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/utils/easing.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getEasingFunction = getEasingFunction; -var _easing = __webpack_require__(/*! @motionone/easing */ "../../../node_modules/@motionone/easing/dist/index.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const namedEasings = { - ease: (0, _easing.cubicBezier)(0.25, 0.1, 0.25, 1.0), - "ease-in": (0, _easing.cubicBezier)(0.42, 0.0, 1.0, 1.0), - "ease-in-out": (0, _easing.cubicBezier)(0.42, 0.0, 0.58, 1.0), - "ease-out": (0, _easing.cubicBezier)(0.0, 0.0, 0.58, 1.0) -}; -const functionArgsRegex = /\((.*?)\)/; -function getEasingFunction(definition) { - // If already an easing function, return - if ((0, _utils.isFunction)(definition)) return definition; - // If an easing curve definition, return bezier function - if ((0, _utils.isCubicBezier)(definition)) return (0, _easing.cubicBezier)(...definition); - // If we have a predefined easing function, return - if (namedEasings[definition]) return namedEasings[definition]; - // If this is a steps function, attempt to create easing curve - if (definition.startsWith("steps")) { - const args = functionArgsRegex.exec(definition); - if (args) { - const argsArray = args[1].split(","); - return (0, _easing.steps)(parseFloat(argsArray[0]), argsArray[1].trim()); - } - } - return _utils.noopReturn; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.animateStyle = animateStyle; -var _dataEs = __webpack_require__(/*! ./data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); -var _cssVarEs = __webpack_require__(/*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js"); -var _animation = __webpack_require__(/*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _transformsEs = __webpack_require__(/*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js"); -var _featureDetectionEs = __webpack_require__(/*! ./utils/feature-detection.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js"); -var _keyframesEs = __webpack_require__(/*! ./utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js"); -var _styleEs = __webpack_require__(/*! ./style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); -var _getStyleNameEs = __webpack_require__(/*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); -var _stopAnimationEs = __webpack_require__(/*! ./utils/stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js"); -function getDevToolsRecord() { - return window.__MOTION_DEV_TOOLS_RECORD; -} -function animateStyle(element, key, keyframesDefinition, options = {}) { - const record = getDevToolsRecord(); - const isRecording = options.record !== false && record; - let animation; - let { - duration = _utils.defaults.duration, - delay = _utils.defaults.delay, - endDelay = _utils.defaults.endDelay, - repeat = _utils.defaults.repeat, - easing = _utils.defaults.easing, - direction, - offset, - allowWebkitAcceleration = false - } = options; - const data = (0, _dataEs.getAnimationData)(element); - let canAnimateNatively = _featureDetectionEs.supports.waapi(); - const valueIsTransform = (0, _transformsEs.isTransform)(key); - /** - * If this is an individual transform, we need to map its - * key to a CSS variable and update the element's transform style - */ - valueIsTransform && (0, _transformsEs.addTransformToElement)(element, key); - const name = (0, _getStyleNameEs.getStyleName)(key); - const motionValue = (0, _dataEs.getMotionValue)(data.values, name); - /** - * Get definition of value, this will be used to convert numerical - * keyframes into the default value type. - */ - const definition = _transformsEs.transformDefinitions.get(name); - /** - * Stop the current animation, if any. Because this will trigger - * commitStyles (DOM writes) and we might later trigger DOM reads, - * this is fired now and we return a factory function to create - * the actual animation that can get called in batch, - */ - (0, _stopAnimationEs.stopAnimation)(motionValue.animation, !((0, _utils.isEasingGenerator)(easing) && motionValue.generator) && options.record !== false); - /** - * Batchable factory function containing all DOM reads. - */ - return () => { - const readInitialValue = () => { - var _a, _b; - return (_b = (_a = _styleEs.style.get(element, name)) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition.initialValue) !== null && _b !== void 0 ? _b : 0; - }; - /** - * Replace null values with the previous keyframe value, or read - * it from the DOM if it's the first keyframe. - */ - let keyframes = (0, _keyframesEs.hydrateKeyframes)((0, _keyframesEs.keyframesList)(keyframesDefinition), readInitialValue); - if ((0, _utils.isEasingGenerator)(easing)) { - const custom = easing.createAnimation(keyframes, readInitialValue, valueIsTransform, name, motionValue); - easing = custom.easing; - if (custom.keyframes !== undefined) keyframes = custom.keyframes; - if (custom.duration !== undefined) duration = custom.duration; - } - /** - * If this is a CSS variable we need to register it with the browser - * before it can be animated natively. We also set it with setProperty - * rather than directly onto the element.style object. - */ - if ((0, _cssVarEs.isCssVar)(name)) { - if (_featureDetectionEs.supports.cssRegisterProperty()) { - (0, _cssVarEs.registerCssVariable)(name); - } else { - canAnimateNatively = false; - } - } - /** - * If we can animate this value with WAAPI, do so. Currently this only - * feature detects CSS.registerProperty but could check WAAPI too. - */ - if (canAnimateNatively) { - /** - * Convert numbers to default value types. Currently this only supports - * transforms but it could also support other value types. - */ - if (definition) { - keyframes = keyframes.map(value => (0, _utils.isNumber)(value) ? definition.toDefaultUnit(value) : value); - } - /** - * If this browser doesn't support partial/implicit keyframes we need to - * explicitly provide one. - */ - if (keyframes.length === 1 && (!_featureDetectionEs.supports.partialKeyframes() || isRecording)) { - keyframes.unshift(readInitialValue()); - } - const animationOptions = { - delay: _utils.time.ms(delay), - duration: _utils.time.ms(duration), - endDelay: _utils.time.ms(endDelay), - easing: !(0, _utils.isEasingList)(easing) ? (0, _easingEs.convertEasing)(easing) : undefined, - direction, - iterations: repeat + 1, - fill: "both" - }; - animation = element.animate({ - [name]: keyframes, - offset, - easing: (0, _utils.isEasingList)(easing) ? easing.map(_easingEs.convertEasing) : undefined - }, animationOptions); - /** - * Polyfill finished Promise in browsers that don't support it - */ - if (!animation.finished) { - animation.finished = new Promise((resolve, reject) => { - animation.onfinish = resolve; - animation.oncancel = reject; + // Gets the closest ancestor positioned element. Handles some edge cases, + // such as table ancestors and cross browser bugs. + function getOffsetParent(element, polyfill) { + const window = getWindow(element); + if (!isHTMLElement(element)) { + return window; + } + let offsetParent = getTrueOffsetParent(element, polyfill); + while ( + offsetParent && + isTableElement(offsetParent) && + getComputedStyle$1(offsetParent).position === "static" + ) { + offsetParent = getTrueOffsetParent(offsetParent, polyfill); + } + if ( + offsetParent && + (getNodeName(offsetParent) === "html" || + (getNodeName(offsetParent) === "body" && + getComputedStyle$1(offsetParent).position === "static" && + !isContainingBlock(offsetParent))) + ) { + return window; + } + return offsetParent || getContainingBlock(element) || window; + } + function getRectRelativeToOffsetParent( + element, + offsetParent, + strategy + ) { + const isOffsetParentAnElement = isHTMLElement(offsetParent); + const documentElement = getDocumentElement(offsetParent); + const isFixed = strategy === "fixed"; + const rect = getBoundingClientRect( + element, + true, + isFixed, + offsetParent + ); + let scroll = { + scrollLeft: 0, + scrollTop: 0, + }; + const offsets = { + x: 0, + y: 0, + }; + if ( + isOffsetParentAnElement || + (!isOffsetParentAnElement && !isFixed) + ) { + if ( + getNodeName(offsetParent) !== "body" || + isOverflowElement(documentElement) + ) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + const offsetRect = getBoundingClientRect( + offsetParent, + true, + isFixed, + offsetParent + ); + offsets.x = offsetRect.x + offsetParent.clientLeft; + offsets.y = offsetRect.y + offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height, + }; + } + const platform = (exports.platform = { + getClippingRect, + convertOffsetParentRelativeRectToViewportRelativeRect, + isElement, + getDimensions, + getOffsetParent, + getDocumentElement, + getScale, + async getElementRects(_ref) { + let { reference, floating, strategy } = _ref; + const getOffsetParentFn = this.getOffsetParent || getOffsetParent; + const getDimensionsFn = this.getDimensions; + return { + reference: getRectRelativeToOffsetParent( + reference, + await getOffsetParentFn(floating), + strategy + ), + floating: { + x: 0, + y: 0, + ...(await getDimensionsFn(floating)), + }, + }; + }, + getClientRects: (element) => Array.from(element.getClientRects()), + isRTL: (element) => getComputedStyle$1(element).direction === "rtl", }); - } - const target = keyframes[keyframes.length - 1]; - animation.finished.then(() => { - // Apply styles to target - _styleEs.style.set(element, name, target); - // Ensure fill modes don't persist - animation.cancel(); - }).catch(_utils.noop); - /** - * This forces Webkit to run animations on the main thread by exploiting - * this condition: - * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099 - * - * This fixes Webkit's timing bugs, like accelerated animations falling - * out of sync with main thread animations and massive delays in starting - * accelerated animations in WKWebView. - */ - if (!allowWebkitAcceleration) animation.playbackRate = 1.000001; - /** - * If we can't animate the value natively then we can fallback to the numbers-only - * polyfill for transforms. - */ - } else if (valueIsTransform) { - /** - * If any keyframe is a string (because we measured it from the DOM), we need to convert - * it into a number before passing to the Animation polyfill. - */ - keyframes = keyframes.map(value => typeof value === "string" ? parseFloat(value) : value); - /** - * If we only have a single keyframe, we need to create an initial keyframe by reading - * the current value from the DOM. - */ - if (keyframes.length === 1) { - keyframes.unshift(parseFloat(readInitialValue())); - } - const render = latest => { - if (definition) latest = definition.toDefaultUnit(latest); - _styleEs.style.set(element, name, latest); - }; - animation = new _animation.Animation(render, keyframes, Object.assign(Object.assign({}, options), { - duration, - easing - })); - } else { - const target = keyframes[keyframes.length - 1]; - _styleEs.style.set(element, name, definition && (0, _utils.isNumber)(target) ? definition.toDefaultUnit(target) : target); - } - if (isRecording) { - record(element, key, keyframes, { - duration, - delay: delay, - easing, - repeat, - offset - }, "motion-one"); - } - motionValue.setAnimation(animation); - return animation; - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/data.es.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/data.es.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getAnimationData = getAnimationData; -exports.getMotionValue = getMotionValue; -var _types = __webpack_require__(/*! @motionone/types */ "../../../node_modules/@motionone/types/dist/index.es.js"); -const data = new WeakMap(); -function getAnimationData(element) { - if (!data.has(element)) { - data.set(element, { - transforms: [], - values: new Map() - }); - } - return data.get(element); -} -function getMotionValue(motionValues, name) { - if (!motionValues.has(name)) { - motionValues.set(name, new _types.MotionValue()); - } - return motionValues.get(name); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/index.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/index.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.animate = animate; -var _animateStyleEs = __webpack_require__(/*! ./animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _optionsEs = __webpack_require__(/*! ./utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); -var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -var _controlsEs = __webpack_require__(/*! ./utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); -var _staggerEs = __webpack_require__(/*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); -function animate(elements, keyframes, options = {}) { - elements = (0, _resolveElementsEs.resolveElements)(elements); - const numElements = elements.length; - /** - * Create and start new animations - */ - const animationFactories = []; - for (let i = 0; i < numElements; i++) { - const element = elements[i]; - for (const key in keyframes) { - const valueOptions = (0, _optionsEs.getOptions)(options, key); - valueOptions.delay = (0, _staggerEs.resolveOption)(valueOptions.delay, i, numElements); - const animation = (0, _animateStyleEs.animateStyle)(element, key, keyframes[key], valueOptions); - animationFactories.push(animation); - } - } - return (0, _controlsEs.withControls)(animationFactories, options, - /** - * TODO: - * If easing is set to spring or glide, duration will be dynamically - * generated. Ideally we would dynamically generate this from - * animation.effect.getComputedTiming().duration but this isn't - * supported in iOS13 or our number polyfill. Perhaps it's possible - * to Proxy animations returned from animateStyle that has duration - * as a getter. - */ - options.duration); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/style.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/style.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.style = void 0; -var _cssVarEs = __webpack_require__(/*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js"); -var _getStyleNameEs = __webpack_require__(/*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); -var _transformsEs = __webpack_require__(/*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -const style = exports.style = { - get: (element, name) => { - name = (0, _getStyleNameEs.getStyleName)(name); - let value = (0, _cssVarEs.isCssVar)(name) ? element.style.getPropertyValue(name) : getComputedStyle(element)[name]; - if (!value && value !== 0) { - const definition = _transformsEs.transformDefinitions.get(name); - if (definition) value = definition.initialValue; - } - return value; - }, - set: (element, name, value) => { - name = (0, _getStyleNameEs.getStyleName)(name); - if ((0, _cssVarEs.isCssVar)(name)) { - element.style.setProperty(name, value); - } else { - element.style[name] = value; - } - } -}; -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.withControls = exports.controls = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _stopAnimationEs = __webpack_require__(/*! ./stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js"); -const createAnimation = factory => factory(); -const withControls = (animationFactory, options, duration = _utils.defaults.duration) => { - return new Proxy({ - animations: animationFactory.map(createAnimation).filter(Boolean), - duration, - options - }, controls); -}; -/** - * TODO: - * Currently this returns the first animation, ideally it would return - * the first active animation. - */ -exports.withControls = withControls; -const getActiveAnimation = state => state.animations[0]; -const controls = exports.controls = { - get: (target, key) => { - const activeAnimation = getActiveAnimation(target); - switch (key) { - case "duration": - return target.duration; - case "currentTime": - return _utils.time.s((activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) || 0); - case "playbackRate": - case "playState": - return activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]; - case "finished": - if (!target.finished) { - target.finished = Promise.all(target.animations.map(selectFinished)).catch(_utils.noop); - } - return target.finished; - case "stop": - return () => { - target.animations.forEach(animation => (0, _stopAnimationEs.stopAnimation)(animation)); - }; - case "forEachNative": /** - * This is for internal use only, fire a callback for each - * underlying animation. + * Automatically updates the position of the floating element when necessary. + * Should only be called when the floating element is mounted on the DOM or + * visible on the screen. + * @returns cleanup function that should be invoked when the floating element is + * removed from the DOM or hidden from the screen. + * @see https://floating-ui.com/docs/autoUpdate */ - return callback => { - target.animations.forEach(animation => callback(animation, target)); - }; - default: - return typeof (activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) === "undefined" ? undefined : () => target.animations.forEach(animation => animation[key]()); - } - }, - set: (target, key, value) => { - switch (key) { - case "currentTime": - value = _utils.time.ms(value); - case "currentTime": - case "playbackRate": - for (let i = 0; i < target.animations.length; i++) { - target.animations[i][key] = value; - } - return true; - } - return false; - } -}; -const selectFinished = animation => animation.finished; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isCssVar = void 0; -exports.registerCssVariable = registerCssVariable; -exports.registeredProperties = void 0; -var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -const isCssVar = name => name.startsWith("--"); -exports.isCssVar = isCssVar; -const registeredProperties = exports.registeredProperties = new Set(); -function registerCssVariable(name) { - if (registeredProperties.has(name)) return; - registeredProperties.add(name); - try { - const { - syntax, - initialValue - } = _transformsEs.transformDefinitions.has(name) ? _transformsEs.transformDefinitions.get(name) : {}; - CSS.registerProperty({ - name, - inherits: false, - syntax, - initialValue - }); - } catch (e) {} -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.cubicBezierAsString = exports.convertEasing = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const convertEasing = easing => (0, _utils.isCubicBezier)(easing) ? cubicBezierAsString(easing) : easing; -exports.convertEasing = convertEasing; -const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`; -exports.cubicBezierAsString = cubicBezierAsString; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js": -/*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js ***! - \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.supports = void 0; -const testAnimation = keyframes => document.createElement("div").animate(keyframes, { - duration: 0.001 -}); -const featureTests = { - cssRegisterProperty: () => typeof CSS !== "undefined" && Object.hasOwnProperty.call(CSS, "registerProperty"), - waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"), - partialKeyframes: () => { - try { - testAnimation({ - opacity: [1] - }); - } catch (e) { - return false; - } - return true; - }, - finished: () => Boolean(testAnimation({ - opacity: [0, 1] - }).finished) -}; -const results = {}; -const supports = exports.supports = {}; -for (const key in featureTests) { - supports[key] = () => { - if (results[key] === undefined) results[key] = featureTests[key](); - return results[key]; - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js": -/*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getStyleName = getStyleName; -var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -function getStyleName(key) { - if (_transformsEs.transformAlias[key]) key = _transformsEs.transformAlias[key]; - return (0, _transformsEs.isTransform)(key) ? (0, _transformsEs.asTransformCssVar)(key) : key; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js": -/*!*******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js ***! - \*******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hydrateKeyframes = hydrateKeyframes; -exports.keyframesList = void 0; -function hydrateKeyframes(keyframes, readInitialValue) { - for (let i = 0; i < keyframes.length; i++) { - if (keyframes[i] === null) { - keyframes[i] = i ? keyframes[i - 1] : readInitialValue(); - } - } - return keyframes; -} -const keyframesList = keyframes => Array.isArray(keyframes) ? keyframes : [keyframes]; -exports.keyframesList = keyframesList; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getOptions = void 0; -const getOptions = (options, key) => -/** - * TODO: Make test for this - * Always return a new object otherwise delay is overwritten by results of stagger - * and this results in no stagger - */ -options[key] ? Object.assign(Object.assign({}, options), options[key]) : Object.assign({}, options); -exports.getOptions = getOptions; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js": -/*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.stopAnimation = stopAnimation; -function stopAnimation(animation, needsCommit = true) { - if (!animation || animation.playState === "finished") return; - // Suppress error thrown by WAAPI - try { - if (animation.stop) { - animation.stop(); - } else { - needsCommit && animation.commitStyles(); - animation.cancel(); - } - } catch (e) {} -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createStyles = createStyles; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -function createStyles(keyframes) { - const initialKeyframes = {}; - const transformKeys = []; - for (let key in keyframes) { - const value = keyframes[key]; - if ((0, _transformsEs.isTransform)(key)) { - if (_transformsEs.transformAlias[key]) key = _transformsEs.transformAlias[key]; - transformKeys.push(key); - key = (0, _transformsEs.asTransformCssVar)(key); - } - let initialKeyframe = Array.isArray(value) ? value[0] : value; - /** - * If this is a number and we have a default value type, convert the number - * to this type. - */ - const definition = _transformsEs.transformDefinitions.get(key); - if (definition) { - initialKeyframe = (0, _utils.isNumber)(value) ? definition.toDefaultUnit(value) : value; - } - initialKeyframes[key] = initialKeyframe; - } - if (transformKeys.length) { - initialKeyframes.transform = (0, _transformsEs.buildTransformTemplate)(transformKeys); - } - return initialKeyframes; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createStyleString = createStyleString; -var _styleObjectEs = __webpack_require__(/*! ./style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js"); -const camelLetterToPipeLetter = letter => `-${letter.toLowerCase()}`; -const camelToPipeCase = str => str.replace(/[A-Z]/g, camelLetterToPipeLetter); -function createStyleString(target = {}) { - const styles = (0, _styleObjectEs.createStyles)(target); - let style = ""; - for (const key in styles) { - style += key.startsWith("--") ? key : camelToPipeCase(key); - style += `: ${styles[key]}; `; - } - return style; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js": -/*!********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.transformDefinitions = exports.transformAlias = exports.isTransform = exports.compareTransformOrder = exports.buildTransformTemplate = exports.axes = exports.asTransformCssVar = exports.addTransformToElement = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _dataEs = __webpack_require__(/*! ../data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); -/** - * A list of all transformable axes. We'll use this list to generated a version - * of each axes for each transform. - */ -const axes = exports.axes = ["", "X", "Y", "Z"]; -/** - * An ordered array of each transformable value. By default, transform values - * will be sorted to this order. - */ -const order = ["translate", "scale", "rotate", "skew"]; -const transformAlias = exports.transformAlias = { - x: "translateX", - y: "translateY", - z: "translateZ" -}; -const rotation = { - syntax: "", - initialValue: "0deg", - toDefaultUnit: v => v + "deg" -}; -const baseTransformProperties = { - translate: { - syntax: "", - initialValue: "0px", - toDefaultUnit: v => v + "px" - }, - rotate: rotation, - scale: { - syntax: "", - initialValue: 1, - toDefaultUnit: _utils.noopReturn - }, - skew: rotation -}; -const transformDefinitions = exports.transformDefinitions = new Map(); -const asTransformCssVar = name => `--motion-${name}`; -/** - * Generate a list of every possible transform key - */ -exports.asTransformCssVar = asTransformCssVar; -const transforms = ["x", "y", "z"]; -order.forEach(name => { - axes.forEach(axis => { - transforms.push(name + axis); - transformDefinitions.set(asTransformCssVar(name + axis), baseTransformProperties[name]); - }); -}); -/** - * A function to use with Array.sort to sort transform keys by their default order. - */ -const compareTransformOrder = (a, b) => transforms.indexOf(a) - transforms.indexOf(b); -/** - * Provide a quick way to check if a string is the name of a transform - */ -exports.compareTransformOrder = compareTransformOrder; -const transformLookup = new Set(transforms); -const isTransform = name => transformLookup.has(name); -exports.isTransform = isTransform; -const addTransformToElement = (element, name) => { - // Map x to translateX etc - if (transformAlias[name]) name = transformAlias[name]; - const { - transforms - } = (0, _dataEs.getAnimationData)(element); - (0, _utils.addUniqueItem)(transforms, name); - /** - * TODO: An optimisation here could be to cache the transform in element data - * and only update if this has changed. - */ - element.style.transform = buildTransformTemplate(transforms); -}; -exports.addTransformToElement = addTransformToElement; -const buildTransformTemplate = transforms => transforms.sort(compareTransformOrder).reduce(transformListToString, "").trim(); -exports.buildTransformTemplate = buildTransformTemplate; -const transformListToString = (template, name) => `${template} ${name}(var(${asTransformCssVar(name)}))`; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createGeneratorEasing = createGeneratorEasing; -var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); -function createGeneratorEasing(createGenerator) { - const keyframesCache = new WeakMap(); - return (options = {}) => { - const generatorCache = new Map(); - const getGenerator = (from = 0, to = 100, velocity = 0, isScale = false) => { - const key = `${from}-${to}-${velocity}-${isScale}`; - if (!generatorCache.has(key)) { - generatorCache.set(key, createGenerator(Object.assign({ - from, - to, - velocity, - restSpeed: isScale ? 0.05 : 2, - restDistance: isScale ? 0.01 : 0.5 - }, options))); - } - return generatorCache.get(key); - }; - const getKeyframes = generator => { - if (!keyframesCache.has(generator)) { - keyframesCache.set(generator, (0, _generators.pregenerateKeyframes)(generator)); - } - return keyframesCache.get(generator); - }; - return { - createAnimation: (keyframes, getOrigin, canUseGenerator, name, motionValue) => { - var _a, _b; - let settings; - const numKeyframes = keyframes.length; - let shouldUseGenerator = canUseGenerator && numKeyframes <= 2 && keyframes.every(isNumberOrNull); - if (shouldUseGenerator) { - const target = keyframes[numKeyframes - 1]; - const unresolvedOrigin = numKeyframes === 1 ? null : keyframes[0]; - let velocity = 0; - let origin = 0; - const prevGenerator = motionValue === null || motionValue === void 0 ? void 0 : motionValue.generator; - if (prevGenerator) { - /** - * If we have a generator for this value we can use it to resolve - * the animations's current value and velocity. - */ - const { - animation, - generatorStartTime - } = motionValue; - const startTime = (animation === null || animation === void 0 ? void 0 : animation.startTime) || generatorStartTime || 0; - const currentTime = (animation === null || animation === void 0 ? void 0 : animation.currentTime) || performance.now() - startTime; - const prevGeneratorCurrent = prevGenerator(currentTime).current; - origin = (_a = unresolvedOrigin) !== null && _a !== void 0 ? _a : prevGeneratorCurrent; - if (numKeyframes === 1 || numKeyframes === 2 && keyframes[0] === null) { - velocity = (0, _generators.calcGeneratorVelocity)(t => prevGenerator(t).current, currentTime, prevGeneratorCurrent); - } - } else { - origin = (_b = unresolvedOrigin) !== null && _b !== void 0 ? _b : parseFloat(getOrigin()); + function autoUpdate(reference, floating, update, options) { + if (options === void 0) { + options = {}; } - const generator = getGenerator(origin, target, velocity, name === null || name === void 0 ? void 0 : name.includes("scale")); - const keyframesMetadata = getKeyframes(generator); - settings = Object.assign(Object.assign({}, keyframesMetadata), { - easing: "linear" + const { + ancestorScroll = true, + ancestorResize = true, + elementResize = true, + animationFrame = false, + } = options; + const ancestors = + ancestorScroll || ancestorResize + ? [ + ...(isElement(reference) + ? getOverflowAncestors(reference) + : reference.contextElement + ? getOverflowAncestors(reference.contextElement) + : []), + ...getOverflowAncestors(floating), + ] + : []; + ancestors.forEach((ancestor) => { + // ignores Window, checks for [object VisualViewport] + const isVisualViewport = + !isElement(ancestor) && ancestor.toString().includes("V"); + if (ancestorScroll && (animationFrame ? isVisualViewport : true)) { + ancestor.addEventListener("scroll", update, { + passive: true, + }); + } + ancestorResize && ancestor.addEventListener("resize", update); }); - // TODO Add test for this - if (motionValue) { - motionValue.generator = generator; - motionValue.generatorStartTime = performance.now(); + let observer = null; + if (elementResize) { + observer = new ResizeObserver(() => { + update(); + }); + isElement(reference) && + !animationFrame && + observer.observe(reference); + if ( + !isElement(reference) && + reference.contextElement && + !animationFrame + ) { + observer.observe(reference.contextElement); + } + observer.observe(floating); + } + let frameId; + let prevRefRect = animationFrame + ? getBoundingClientRect(reference) + : null; + if (animationFrame) { + frameLoop(); + } + function frameLoop() { + const nextRefRect = getBoundingClientRect(reference); + if ( + prevRefRect && + (nextRefRect.x !== prevRefRect.x || + nextRefRect.y !== prevRefRect.y || + nextRefRect.width !== prevRefRect.width || + nextRefRect.height !== prevRefRect.height) + ) { + update(); + } + prevRefRect = nextRefRect; + frameId = requestAnimationFrame(frameLoop); } - } else { - const keyframesMetadata = getKeyframes(getGenerator(0, 100)); - settings = { - easing: "ease", - duration: keyframesMetadata.overshootDuration + update(); + return () => { + var _observer; + ancestors.forEach((ancestor) => { + ancestorScroll && ancestor.removeEventListener("scroll", update); + ancestorResize && ancestor.removeEventListener("resize", update); + }); + (_observer = observer) == null ? void 0 : _observer.disconnect(); + observer = null; + if (animationFrame) { + cancelAnimationFrame(frameId); + } }; } - return settings; - } - }; - }; -} -const isNumberOrNull = value => typeof value !== "string"; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.glide = void 0; -var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); -var _createGeneratorEasingEs = __webpack_require__(/*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js"); -const glide = exports.glide = (0, _createGeneratorEasingEs.createGeneratorEasing)(_generators.glide); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.spring = void 0; -var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); -var _createGeneratorEasingEs = __webpack_require__(/*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js"); -const spring = exports.spring = (0, _createGeneratorEasingEs.createGeneratorEasing)(_generators.spring); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - + /** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a reference element when it is given a certain CSS positioning + * strategy. + */ + const computePosition = (reference, floating, options) => { + // This caches the expensive `getClippingElementAncestors` function so that + // multiple lifecycle resets re-use the same result. It only lives for a + // single call. If other functions become expensive, we can add them as well. + const cache = new Map(); + const mergedOptions = { + platform, + ...options, + }; + const platformWithCache = { + ...mergedOptions.platform, + _c: cache, + }; + return (0, _core.computePosition)(reference, floating, { + ...mergedOptions, + platform: platformWithCache, + }); + }; + exports.computePosition = computePosition; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.inView = inView; -var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -const thresholds = { - any: 0, - all: 1 -}; -function inView(elementOrSelector, onStart, { - root, - margin: rootMargin, - amount = "any" -} = {}) { - /** - * If this browser doesn't support IntersectionObserver, return a dummy stop function. - * Default triggering of onStart is tricky - it could be used for starting/stopping - * videos, lazy loading content etc. We could provide an option to enable a fallback, or - * provide a fallback callback option. - */ - if (typeof IntersectionObserver === "undefined") { - return () => {}; - } - const elements = (0, _resolveElementsEs.resolveElements)(elementOrSelector); - const activeIntersections = new WeakMap(); - const onIntersectionChange = entries => { - entries.forEach(entry => { - const onEnd = activeIntersections.get(entry.target); - /** - * If there's no change to the intersection, we don't need to - * do anything here. - */ - if (entry.isIntersecting === Boolean(onEnd)) return; - if (entry.isIntersecting) { - const newOnEnd = onStart(entry); - if (typeof newOnEnd === "function") { - activeIntersections.set(entry.target, newOnEnd); - } else { - observer.unobserve(entry.target); - } - } else if (onEnd) { - onEnd(entry); - activeIntersections.delete(entry.target); - } - }); - }; - const observer = new IntersectionObserver(onIntersectionChange, { - root, - rootMargin, - threshold: typeof amount === "number" ? amount : thresholds[amount] - }); - elements.forEach(element => observer.observe(element)); - return () => observer.disconnect(); -} - -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js ***! + /***/ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js ***! \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resizeElement = resizeElement; -var _resolveElementsEs = __webpack_require__(/*! ../../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -const resizeHandlers = new WeakMap(); -let observer; -function getElementSize(target, borderBoxSize) { - if (borderBoxSize) { - const { - inlineSize, - blockSize - } = borderBoxSize[0]; - return { - width: inlineSize, - height: blockSize - }; - } else if (target instanceof SVGElement && "getBBox" in target) { - return target.getBBox(); - } else { - return { - width: target.offsetWidth, - height: target.offsetHeight - }; - } -} -function notifyTarget({ - target, - contentRect, - borderBoxSize -}) { - var _a; - (_a = resizeHandlers.get(target)) === null || _a === void 0 ? void 0 : _a.forEach(handler => { - handler({ - target, - contentSize: contentRect, - get size() { - return getElementSize(target, borderBoxSize); - } - }); - }); -} -function notifyAll(entries) { - entries.forEach(notifyTarget); -} -function createResizeObserver() { - if (typeof ResizeObserver === "undefined") return; - observer = new ResizeObserver(notifyAll); -} -function resizeElement(target, handler) { - if (!observer) createResizeObserver(); - const elements = (0, _resolveElementsEs.resolveElements)(target); - elements.forEach(element => { - let elementHandlers = resizeHandlers.get(element); - if (!elementHandlers) { - elementHandlers = new Set(); - resizeHandlers.set(element, elementHandlers); - } - elementHandlers.add(handler); - observer === null || observer === void 0 ? void 0 : observer.observe(element); - }); - return () => { - elements.forEach(element => { - const elementHandlers = resizeHandlers.get(element); - elementHandlers === null || elementHandlers === void 0 ? void 0 : elementHandlers.delete(handler); - if (!(elementHandlers === null || elementHandlers === void 0 ? void 0 : elementHandlers.size)) { - observer === null || observer === void 0 ? void 0 : observer.unobserve(element); - } - }); - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js": -/*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js ***! - \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resizeWindow = resizeWindow; -const windowCallbacks = new Set(); -let windowResizeHandler; -function createWindowResizeHandler() { - windowResizeHandler = () => { - const size = { - width: window.innerWidth, - height: window.innerHeight - }; - const info = { - target: window, - size, - contentSize: size - }; - windowCallbacks.forEach(callback => callback(info)); - }; - window.addEventListener("resize", windowResizeHandler); -} -function resizeWindow(callback) { - windowCallbacks.add(callback); - if (!windowResizeHandler) createWindowResizeHandler(); - return () => { - windowCallbacks.delete(callback); - if (!windowCallbacks.size && windowResizeHandler) { - windowResizeHandler = undefined; - } - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resize = resize; -var _handleElementEs = __webpack_require__(/*! ./handle-element.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js"); -var _handleWindowEs = __webpack_require__(/*! ./handle-window.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js"); -function resize(a, b) { - return typeof a === "function" ? (0, _handleWindowEs.resizeWindow)(a) : (0, _handleElementEs.resizeElement)(a, b); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.scroll = scroll; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _indexEs = __webpack_require__(/*! ../resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js"); -var _infoEs = __webpack_require__(/*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js"); -var _onScrollHandlerEs = __webpack_require__(/*! ./on-scroll-handler.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js"); -const scrollListeners = new WeakMap(); -const resizeListeners = new WeakMap(); -const onScrollHandlers = new WeakMap(); -const getEventTarget = element => element === document.documentElement ? window : element; -function scroll(onScroll, _a = {}) { - var { - container = document.documentElement - } = _a, - options = (0, _tslib.__rest)(_a, ["container"]); - let containerHandlers = onScrollHandlers.get(container); - /** - * Get the onScroll handlers for this container. - * If one isn't found, create a new one. - */ - if (!containerHandlers) { - containerHandlers = new Set(); - onScrollHandlers.set(container, containerHandlers); - } - /** - * Create a new onScroll handler for the provided callback. - */ - const info = (0, _infoEs.createScrollInfo)(); - const containerHandler = (0, _onScrollHandlerEs.createOnScrollHandler)(container, onScroll, info, options); - containerHandlers.add(containerHandler); - /** - * Check if there's a scroll event listener for this container. - * If not, create one. - */ - if (!scrollListeners.has(container)) { - const listener = () => { - const time = performance.now(); - for (const handler of containerHandlers) handler.measure(); - for (const handler of containerHandlers) handler.update(time); - for (const handler of containerHandlers) handler.notify(); - }; - scrollListeners.set(container, listener); - const target = getEventTarget(container); - window.addEventListener("resize", listener, { - passive: true - }); - if (container !== document.documentElement) { - resizeListeners.set(container, (0, _indexEs.resize)(container, listener)); - } - target.addEventListener("scroll", listener, { - passive: true - }); - } - const listener = scrollListeners.get(container); - const onLoadProcesss = requestAnimationFrame(listener); - return () => { - var _a; - if (typeof onScroll !== "function") onScroll.stop(); - cancelAnimationFrame(onLoadProcesss); - /** - * Check if we even have any handlers for this container. - */ - const containerHandlers = onScrollHandlers.get(container); - if (!containerHandlers) return; - containerHandlers.delete(containerHandler); - if (containerHandlers.size) return; - /** - * If no more handlers, remove the scroll listener too. - */ - const listener = scrollListeners.get(container); - scrollListeners.delete(container); - if (listener) { - getEventTarget(container).removeEventListener("scroll", listener); - (_a = resizeListeners.get(container)) === null || _a === void 0 ? void 0 : _a(); - window.removeEventListener("resize", listener); - } - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createScrollInfo = void 0; -exports.updateScrollInfo = updateScrollInfo; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -/** - * A time in milliseconds, beyond which we consider the scroll velocity to be 0. - */ -const maxElapsed = 50; -const createAxisInfo = () => ({ - current: 0, - offset: [], - progress: 0, - scrollLength: 0, - targetOffset: 0, - targetLength: 0, - containerLength: 0, - velocity: 0 -}); -const createScrollInfo = () => ({ - time: 0, - x: createAxisInfo(), - y: createAxisInfo() -}); -exports.createScrollInfo = createScrollInfo; -const keys = { - x: { - length: "Width", - position: "Left" - }, - y: { - length: "Height", - position: "Top" - } -}; -function updateAxisInfo(element, axisName, info, time) { - const axis = info[axisName]; - const { - length, - position - } = keys[axisName]; - const prev = axis.current; - const prevTime = info.time; - axis.current = element["scroll" + position]; - axis.scrollLength = element["scroll" + length] - element["client" + length]; - axis.offset.length = 0; - axis.offset[0] = 0; - axis.offset[1] = axis.scrollLength; - axis.progress = (0, _utils.progress)(0, axis.scrollLength, axis.current); - const elapsed = time - prevTime; - axis.velocity = elapsed > maxElapsed ? 0 : (0, _utils.velocityPerSecond)(axis.current - prev, elapsed); -} -function updateScrollInfo(element, info, time) { - updateAxisInfo(element, "x", info, time); - updateAxisInfo(element, "y", info, time); - info.time = time; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js": -/*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.namedEdges = void 0; -exports.resolveEdge = resolveEdge; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const namedEdges = exports.namedEdges = { - start: 0, - center: 0.5, - end: 1 -}; -function resolveEdge(edge, length, inset = 0) { - let delta = 0; - /** - * If we have this edge defined as a preset, replace the definition - * with the numerical value. - */ - if (namedEdges[edge] !== undefined) { - edge = namedEdges[edge]; - } - /** - * Handle unit values - */ - if ((0, _utils.isString)(edge)) { - const asNumber = parseFloat(edge); - if (edge.endsWith("px")) { - delta = asNumber; - } else if (edge.endsWith("%")) { - edge = asNumber / 100; - } else if (edge.endsWith("vw")) { - delta = asNumber / 100 * document.documentElement.clientWidth; - } else if (edge.endsWith("vh")) { - delta = asNumber / 100 * document.documentElement.clientHeight; - } else { - edge = asNumber; - } - } - /** - * If the edge is defined as a number, handle as a progress value. - */ - if ((0, _utils.isNumber)(edge)) { - delta = length * edge; - } - return inset + delta; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js": -/*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js ***! - \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveOffsets = resolveOffsets; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _insetEs = __webpack_require__(/*! ./inset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js"); -var _presetsEs = __webpack_require__(/*! ./presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js"); -var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js"); -const point = { - x: 0, - y: 0 -}; -function resolveOffsets(container, info, options) { - let { - offset: offsetDefinition = _presetsEs.ScrollOffset.All - } = options; - const { - target = container, - axis = "y" - } = options; - const lengthLabel = axis === "y" ? "height" : "width"; - const inset = target !== container ? (0, _insetEs.calcInset)(target, container) : point; - /** - * Measure the target and container. If they're the same thing then we - * use the container's scrollWidth/Height as the target, from there - * all other calculations can remain the same. - */ - const targetSize = target === container ? { - width: container.scrollWidth, - height: container.scrollHeight - } : { - width: target.clientWidth, - height: target.clientHeight - }; - const containerSize = { - width: container.clientWidth, - height: container.clientHeight - }; - /** - * Reset the length of the resolved offset array rather than creating a new one. - * TODO: More reusable data structures for targetSize/containerSize would also be good. - */ - info[axis].offset.length = 0; - /** - * Populate the offset array by resolving the user's offset definition into - * a list of pixel scroll offets. - */ - let hasChanged = !info[axis].interpolate; - const numOffsets = offsetDefinition.length; - for (let i = 0; i < numOffsets; i++) { - const offset = (0, _offsetEs.resolveOffset)(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); - if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { - hasChanged = true; - } - info[axis].offset[i] = offset; - } - /** - * If the pixel scroll offsets have changed, create a new interpolator function - * to map scroll value into a progress. - */ - if (hasChanged) { - info[axis].interpolate = (0, _utils.interpolate)((0, _utils.defaultOffset)(numOffsets), info[axis].offset); - info[axis].interpolatorOffsets = [...info[axis].offset]; - } - info[axis].progress = info[axis].interpolate(info[axis].current); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js": -/*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js ***! - \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.arrow = void 0; + Object.defineProperty(exports, "autoPlacement", { + enumerable: true, + get: function () { + return _dom.autoPlacement; + }, + }); + Object.defineProperty(exports, "autoUpdate", { + enumerable: true, + get: function () { + return _dom.autoUpdate; + }, + }); + Object.defineProperty(exports, "computePosition", { + enumerable: true, + get: function () { + return _dom.computePosition; + }, + }); + Object.defineProperty(exports, "detectOverflow", { + enumerable: true, + get: function () { + return _dom.detectOverflow; + }, + }); + Object.defineProperty(exports, "flip", { + enumerable: true, + get: function () { + return _dom.flip; + }, + }); + Object.defineProperty(exports, "getOverflowAncestors", { + enumerable: true, + get: function () { + return _dom.getOverflowAncestors; + }, + }); + Object.defineProperty(exports, "hide", { + enumerable: true, + get: function () { + return _dom.hide; + }, + }); + Object.defineProperty(exports, "inline", { + enumerable: true, + get: function () { + return _dom.inline; + }, + }); + Object.defineProperty(exports, "limitShift", { + enumerable: true, + get: function () { + return _dom.limitShift; + }, + }); + Object.defineProperty(exports, "offset", { + enumerable: true, + get: function () { + return _dom.offset; + }, + }); + Object.defineProperty(exports, "platform", { + enumerable: true, + get: function () { + return _dom.platform; + }, + }); + Object.defineProperty(exports, "shift", { + enumerable: true, + get: function () { + return _dom.shift; + }, + }); + Object.defineProperty(exports, "size", { + enumerable: true, + get: function () { + return _dom.size; + }, + }); + exports.useFloating = useFloating; + var _dom = __webpack_require__( + /*! @floating-ui/dom */ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js" + ); + var _react = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var React = _react; + var ReactDOM = _interopRequireWildcard( + __webpack_require__(/*! react-dom */ "react-dom") + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + /** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * This wraps the core `arrow` middleware to allow React refs as the element. + * @see https://floating-ui.com/docs/arrow + */ + const arrow = (options) => { + function isRef(value) { + return {}.hasOwnProperty.call(value, "current"); + } + return { + name: "arrow", + options, + fn(state) { + const { element, padding } = + typeof options === "function" ? options(state) : options; + if (element && isRef(element)) { + if (element.current != null) { + return (0, _dom.arrow)({ + element: element.current, + padding, + }).fn(state); + } + return {}; + } else if (element) { + return (0, _dom.arrow)({ + element, + padding, + }).fn(state); + } + return {}; + }, + }; + }; + exports.arrow = arrow; + var index = + typeof document !== "undefined" + ? _react.useLayoutEffect + : _react.useEffect; + + // Fork of `fast-deep-equal` that only does the comparisons we need and compares + // functions + function deepEqual(a, b) { + if (a === b) { + return true; + } + if (typeof a !== typeof b) { + return false; + } + if (typeof a === "function" && a.toString() === b.toString()) { + return true; + } + let length, i, keys; + if (a && b && typeof a == "object") { + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) { + if (!deepEqual(a[i], b[i])) { + return false; + } + } + return true; + } + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) { + return false; + } + for (i = length; i-- !== 0; ) { + if (!{}.hasOwnProperty.call(b, keys[i])) { + return false; + } + } + for (i = length; i-- !== 0; ) { + const key = keys[i]; + if (key === "_owner" && a.$$typeof) { + continue; + } + if (!deepEqual(a[key], b[key])) { + return false; + } + } + return true; + } + return a !== a && b !== b; + } + function getDPR(element) { + if (typeof window === "undefined") { + return 1; + } + const win = element.ownerDocument.defaultView || window; + return win.devicePixelRatio || 1; + } + function roundByDPR(element, value) { + const dpr = getDPR(element); + return Math.round(value * dpr) / dpr; + } + function useLatestRef(value) { + const ref = React.useRef(value); + index(() => { + ref.current = value; + }); + return ref; + } + /** + * Provides data to position a floating element. + * @see https://floating-ui.com/docs/react + */ + function useFloating(options) { + if (options === void 0) { + options = {}; + } + const { + placement = "bottom", + strategy = "absolute", + middleware = [], + platform, + elements: { + reference: externalReference, + floating: externalFloating, + } = {}, + transform = true, + whileElementsMounted, + open, + } = options; + const [data, setData] = React.useState({ + x: 0, + y: 0, + strategy, + placement, + middlewareData: {}, + isPositioned: false, + }); + const [latestMiddleware, setLatestMiddleware] = + React.useState(middleware); + if (!deepEqual(latestMiddleware, middleware)) { + setLatestMiddleware(middleware); + } + const [_reference, _setReference] = React.useState(null); + const [_floating, _setFloating] = React.useState(null); + const setReference = React.useCallback( + (node) => { + if (node != referenceRef.current) { + referenceRef.current = node; + _setReference(node); + } + }, + [_setReference] + ); + const setFloating = React.useCallback( + (node) => { + if (node !== floatingRef.current) { + floatingRef.current = node; + _setFloating(node); + } + }, + [_setFloating] + ); + const referenceEl = externalReference || _reference; + const floatingEl = externalFloating || _floating; + const referenceRef = React.useRef(null); + const floatingRef = React.useRef(null); + const dataRef = React.useRef(data); + const whileElementsMountedRef = useLatestRef(whileElementsMounted); + const platformRef = useLatestRef(platform); + const update = React.useCallback(() => { + if (!referenceRef.current || !floatingRef.current) { + return; + } + const config = { + placement, + strategy, + middleware: latestMiddleware, + }; + if (platformRef.current) { + config.platform = platformRef.current; + } + (0, _dom.computePosition)( + referenceRef.current, + floatingRef.current, + config + ).then((data) => { + const fullData = { + ...data, + isPositioned: true, + }; + if ( + isMountedRef.current && + !deepEqual(dataRef.current, fullData) + ) { + dataRef.current = fullData; + ReactDOM.flushSync(() => { + setData(fullData); + }); + } + }); + }, [latestMiddleware, placement, strategy, platformRef]); + index(() => { + if (open === false && dataRef.current.isPositioned) { + dataRef.current.isPositioned = false; + setData((data) => ({ + ...data, + isPositioned: false, + })); + } + }, [open]); + const isMountedRef = React.useRef(false); + index(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + }; + }, []); + index(() => { + if (referenceEl) referenceRef.current = referenceEl; + if (floatingEl) floatingRef.current = floatingEl; + if (referenceEl && floatingEl) { + if (whileElementsMountedRef.current) { + return whileElementsMountedRef.current( + referenceEl, + floatingEl, + update + ); + } else { + update(); + } + } + }, [referenceEl, floatingEl, update, whileElementsMountedRef]); + const refs = React.useMemo( + () => ({ + reference: referenceRef, + floating: floatingRef, + setReference, + setFloating, + }), + [setReference, setFloating] + ); + const elements = React.useMemo( + () => ({ + reference: referenceEl, + floating: floatingEl, + }), + [referenceEl, floatingEl] + ); + const floatingStyles = React.useMemo(() => { + const initialStyles = { + position: strategy, + left: 0, + top: 0, + }; + if (!elements.floating) { + return initialStyles; + } + const x = roundByDPR(elements.floating, data.x); + const y = roundByDPR(elements.floating, data.y); + if (transform) { + return { + ...initialStyles, + transform: "translate(" + x + "px, " + y + "px)", + ...(getDPR(elements.floating) >= 1.5 && { + willChange: "transform", + }), + }; + } + return { + position: strategy, + left: x, + top: y, + }; + }, [strategy, transform, elements.floating, data.x, data.y]); + return React.useMemo( + () => ({ + ...data, + update, + refs, + elements, + floatingStyles, + }), + [data, update, refs, elements, floatingStyles] + ); + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcInset = calcInset; -function calcInset(element, container) { - let inset = { - x: 0, - y: 0 - }; - let current = element; - while (current && current !== container) { - if (current instanceof HTMLElement) { - inset.x += current.offsetLeft; - inset.y += current.offsetTop; - current = current.offsetParent; - } else if (current instanceof SVGGraphicsElement && "getBBox" in current) { - const { - top, - left - } = current.getBBox(); - inset.x += left; - inset.y += top; - /** - * Assign the next parent element as the tag. - */ - while (current && current.tagName !== "svg") { - current = current.parentNode; - } - } - } - return inset; -} + /***/ "../../../node_modules/@motionone/animation/dist/Animation.es.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/@motionone/animation/dist/Animation.es.js ***! + \***********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Animation = void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _easingEs = __webpack_require__( + /*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js" + ); + class Animation { + constructor( + output, + keyframes = [0, 1], + { + easing, + duration: initialDuration = _utils.defaults.duration, + delay = _utils.defaults.delay, + endDelay = _utils.defaults.endDelay, + repeat = _utils.defaults.repeat, + offset, + direction = "normal", + } = {} + ) { + this.startTime = null; + this.rate = 1; + this.t = 0; + this.cancelTimestamp = null; + this.easing = _utils.noopReturn; + this.duration = 0; + this.totalDuration = 0; + this.repeat = 0; + this.playState = "idle"; + this.finished = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + easing = easing || _utils.defaults.easing; + if ((0, _utils.isEasingGenerator)(easing)) { + const custom = easing.createAnimation(keyframes); + easing = custom.easing; + keyframes = custom.keyframes || keyframes; + initialDuration = custom.duration || initialDuration; + } + this.repeat = repeat; + this.easing = (0, _utils.isEasingList)(easing) + ? _utils.noopReturn + : (0, _easingEs.getEasingFunction)(easing); + this.updateDuration(initialDuration); + const interpolate$1 = (0, _utils.interpolate)( + keyframes, + offset, + (0, _utils.isEasingList)(easing) + ? easing.map(_easingEs.getEasingFunction) + : _utils.noopReturn + ); + this.tick = (timestamp) => { + var _a; + // TODO: Temporary fix for OptionsResolver typing + delay = delay; + let t = 0; + if (this.pauseTime !== undefined) { + t = this.pauseTime; + } else { + t = (timestamp - this.startTime) * this.rate; + } + this.t = t; + // Convert to seconds + t /= 1000; + // Rebase on delay + t = Math.max(t - delay, 0); + /** + * If this animation has finished, set the current time + * to the total duration. + */ + if ( + this.playState === "finished" && + this.pauseTime === undefined + ) { + t = this.totalDuration; + } + /** + * Get the current progress (0-1) of the animation. If t is > + * than duration we'll get values like 2.5 (midway through the + * third iteration) + */ + const progress = t / this.duration; + // TODO progress += iterationStart + /** + * Get the current iteration (0 indexed). For instance the floor of + * 2.5 is 2. + */ + let currentIteration = Math.floor(progress); + /** + * Get the current progress of the iteration by taking the remainder + * so 2.5 is 0.5 through iteration 2 + */ + let iterationProgress = progress % 1.0; + if (!iterationProgress && progress >= 1) { + iterationProgress = 1; + } + /** + * If iteration progress is 1 we count that as the end + * of the previous iteration. + */ + iterationProgress === 1 && currentIteration--; + /** + * Reverse progress if we're not running in "normal" direction + */ + const iterationIsOdd = currentIteration % 2; + if ( + direction === "reverse" || + (direction === "alternate" && iterationIsOdd) || + (direction === "alternate-reverse" && !iterationIsOdd) + ) { + iterationProgress = 1 - iterationProgress; + } + const p = + t >= this.totalDuration ? 1 : Math.min(iterationProgress, 1); + const latest = interpolate$1(this.easing(p)); + output(latest); + const isAnimationFinished = + this.pauseTime === undefined && + (this.playState === "finished" || + t >= this.totalDuration + endDelay); + if (isAnimationFinished) { + this.playState = "finished"; + (_a = this.resolve) === null || _a === void 0 + ? void 0 + : _a.call(this, latest); + } else if (this.playState !== "idle") { + this.frameRequestId = requestAnimationFrame(this.tick); + } + }; + this.play(); + } + play() { + const now = performance.now(); + this.playState = "running"; + if (this.pauseTime !== undefined) { + this.startTime = now - this.pauseTime; + } else if (!this.startTime) { + this.startTime = now; + } + this.cancelTimestamp = this.startTime; + this.pauseTime = undefined; + this.frameRequestId = requestAnimationFrame(this.tick); + } + pause() { + this.playState = "paused"; + this.pauseTime = this.t; + } + finish() { + this.playState = "finished"; + this.tick(0); + } + stop() { + var _a; + this.playState = "idle"; + if (this.frameRequestId !== undefined) { + cancelAnimationFrame(this.frameRequestId); + } + (_a = this.reject) === null || _a === void 0 + ? void 0 + : _a.call(this, false); + } + cancel() { + this.stop(); + this.tick(this.cancelTimestamp); + } + reverse() { + this.rate *= -1; + } + commitStyles() {} + updateDuration(duration) { + this.duration = duration; + this.totalDuration = duration * (this.repeat + 1); + } + get currentTime() { + return this.t; + } + set currentTime(t) { + if (this.pauseTime !== undefined || this.rate === 0) { + this.pauseTime = t; + } else { + this.startTime = performance.now() - t / this.rate; + } + } + get playbackRate() { + return this.rate; + } + set playbackRate(rate) { + this.rate = rate; + } + } + exports.Animation = Animation; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js": -/*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveOffset = resolveOffset; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _edgeEs = __webpack_require__(/*! ./edge.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js"); -const defaultOffset = [0, 0]; -function resolveOffset(offset, containerLength, targetLength, targetInset) { - let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; - let targetPoint = 0; - let containerPoint = 0; - if ((0, _utils.isNumber)(offset)) { - /** - * If we're provided offset: [0, 0.5, 1] then each number x should become - * [x, x], so we default to the behaviour of mapping 0 => 0 of both target - * and container etc. - */ - offsetDefinition = [offset, offset]; - } else if ((0, _utils.isString)(offset)) { - offset = offset.trim(); - if (offset.includes(" ")) { - offsetDefinition = offset.split(" "); - } else { - /** - * If we're provided a definition like "100px" then we want to apply - * that only to the top of the target point, leaving the container at 0. - * Whereas a named offset like "end" should be applied to both. - */ - offsetDefinition = [offset, _edgeEs.namedEdges[offset] ? offset : `0`]; - } - } - targetPoint = (0, _edgeEs.resolveEdge)(offsetDefinition[0], targetLength, targetInset); - containerPoint = (0, _edgeEs.resolveEdge)(offsetDefinition[1], containerLength); - return targetPoint - containerPoint; -} + /***/ "../../../node_modules/@motionone/animation/dist/index.es.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@motionone/animation/dist/index.es.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "Animation", { + enumerable: true, + get: function () { + return _AnimationEs.Animation; + }, + }); + Object.defineProperty(exports, "getEasingFunction", { + enumerable: true, + get: function () { + return _easingEs.getEasingFunction; + }, + }); + var _AnimationEs = __webpack_require__( + /*! ./Animation.es.js */ "../../../node_modules/@motionone/animation/dist/Animation.es.js" + ); + var _easingEs = __webpack_require__( + /*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js" + ); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js": -/*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js ***! - \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/animation/dist/utils/easing.es.js ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getEasingFunction = getEasingFunction; + var _easing = __webpack_require__( + /*! @motionone/easing */ "../../../node_modules/@motionone/easing/dist/index.es.js" + ); + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + const namedEasings = { + ease: (0, _easing.cubicBezier)(0.25, 0.1, 0.25, 1.0), + "ease-in": (0, _easing.cubicBezier)(0.42, 0.0, 1.0, 1.0), + "ease-in-out": (0, _easing.cubicBezier)(0.42, 0.0, 0.58, 1.0), + "ease-out": (0, _easing.cubicBezier)(0.0, 0.0, 0.58, 1.0), + }; + const functionArgsRegex = /\((.*?)\)/; + function getEasingFunction(definition) { + // If already an easing function, return + if ((0, _utils.isFunction)(definition)) return definition; + // If an easing curve definition, return bezier function + if ((0, _utils.isCubicBezier)(definition)) + return (0, _easing.cubicBezier)(...definition); + // If we have a predefined easing function, return + if (namedEasings[definition]) return namedEasings[definition]; + // If this is a steps function, attempt to create easing curve + if (definition.startsWith("steps")) { + const args = functionArgsRegex.exec(definition); + if (args) { + const argsArray = args[1].split(","); + return (0, _easing.steps)( + parseFloat(argsArray[0]), + argsArray[1].trim() + ); + } + } + return _utils.noopReturn; + } + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js ***! + \*****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.animateStyle = animateStyle; + var _dataEs = __webpack_require__( + /*! ./data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js" + ); + var _cssVarEs = __webpack_require__( + /*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js" + ); + var _animation = __webpack_require__( + /*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js" + ); + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _transformsEs = __webpack_require__( + /*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" + ); + var _easingEs = __webpack_require__( + /*! ./utils/easing.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js" + ); + var _featureDetectionEs = __webpack_require__( + /*! ./utils/feature-detection.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js" + ); + var _keyframesEs = __webpack_require__( + /*! ./utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js" + ); + var _styleEs = __webpack_require__( + /*! ./style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js" + ); + var _getStyleNameEs = __webpack_require__( + /*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js" + ); + var _stopAnimationEs = __webpack_require__( + /*! ./utils/stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js" + ); + function getDevToolsRecord() { + return window.__MOTION_DEV_TOOLS_RECORD; + } + function animateStyle(element, key, keyframesDefinition, options = {}) { + const record = getDevToolsRecord(); + const isRecording = options.record !== false && record; + let animation; + let { + duration = _utils.defaults.duration, + delay = _utils.defaults.delay, + endDelay = _utils.defaults.endDelay, + repeat = _utils.defaults.repeat, + easing = _utils.defaults.easing, + direction, + offset, + allowWebkitAcceleration = false, + } = options; + const data = (0, _dataEs.getAnimationData)(element); + let canAnimateNatively = _featureDetectionEs.supports.waapi(); + const valueIsTransform = (0, _transformsEs.isTransform)(key); + /** + * If this is an individual transform, we need to map its + * key to a CSS variable and update the element's transform style + */ + valueIsTransform && + (0, _transformsEs.addTransformToElement)(element, key); + const name = (0, _getStyleNameEs.getStyleName)(key); + const motionValue = (0, _dataEs.getMotionValue)(data.values, name); + /** + * Get definition of value, this will be used to convert numerical + * keyframes into the default value type. + */ + const definition = _transformsEs.transformDefinitions.get(name); + /** + * Stop the current animation, if any. Because this will trigger + * commitStyles (DOM writes) and we might later trigger DOM reads, + * this is fired now and we return a factory function to create + * the actual animation that can get called in batch, + */ + (0, _stopAnimationEs.stopAnimation)( + motionValue.animation, + !((0, _utils.isEasingGenerator)(easing) && motionValue.generator) && + options.record !== false + ); + /** + * Batchable factory function containing all DOM reads. + */ + return () => { + const readInitialValue = () => { + var _a, _b; + return (_b = + (_a = _styleEs.style.get(element, name)) !== null && + _a !== void 0 + ? _a + : definition === null || definition === void 0 + ? void 0 + : definition.initialValue) !== null && _b !== void 0 + ? _b + : 0; + }; + /** + * Replace null values with the previous keyframe value, or read + * it from the DOM if it's the first keyframe. + */ + let keyframes = (0, _keyframesEs.hydrateKeyframes)( + (0, _keyframesEs.keyframesList)(keyframesDefinition), + readInitialValue + ); + if ((0, _utils.isEasingGenerator)(easing)) { + const custom = easing.createAnimation( + keyframes, + readInitialValue, + valueIsTransform, + name, + motionValue + ); + easing = custom.easing; + if (custom.keyframes !== undefined) keyframes = custom.keyframes; + if (custom.duration !== undefined) duration = custom.duration; + } + /** + * If this is a CSS variable we need to register it with the browser + * before it can be animated natively. We also set it with setProperty + * rather than directly onto the element.style object. + */ + if ((0, _cssVarEs.isCssVar)(name)) { + if (_featureDetectionEs.supports.cssRegisterProperty()) { + (0, _cssVarEs.registerCssVariable)(name); + } else { + canAnimateNatively = false; + } + } + /** + * If we can animate this value with WAAPI, do so. Currently this only + * feature detects CSS.registerProperty but could check WAAPI too. + */ + if (canAnimateNatively) { + /** + * Convert numbers to default value types. Currently this only supports + * transforms but it could also support other value types. + */ + if (definition) { + keyframes = keyframes.map((value) => + (0, _utils.isNumber)(value) + ? definition.toDefaultUnit(value) + : value + ); + } + /** + * If this browser doesn't support partial/implicit keyframes we need to + * explicitly provide one. + */ + if ( + keyframes.length === 1 && + (!_featureDetectionEs.supports.partialKeyframes() || + isRecording) + ) { + keyframes.unshift(readInitialValue()); + } + const animationOptions = { + delay: _utils.time.ms(delay), + duration: _utils.time.ms(duration), + endDelay: _utils.time.ms(endDelay), + easing: !(0, _utils.isEasingList)(easing) + ? (0, _easingEs.convertEasing)(easing) + : undefined, + direction, + iterations: repeat + 1, + fill: "both", + }; + animation = element.animate( + { + [name]: keyframes, + offset, + easing: (0, _utils.isEasingList)(easing) + ? easing.map(_easingEs.convertEasing) + : undefined, + }, + animationOptions + ); + /** + * Polyfill finished Promise in browsers that don't support it + */ + if (!animation.finished) { + animation.finished = new Promise((resolve, reject) => { + animation.onfinish = resolve; + animation.oncancel = reject; + }); + } + const target = keyframes[keyframes.length - 1]; + animation.finished + .then(() => { + // Apply styles to target + _styleEs.style.set(element, name, target); + // Ensure fill modes don't persist + animation.cancel(); + }) + .catch(_utils.noop); + /** + * This forces Webkit to run animations on the main thread by exploiting + * this condition: + * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099 + * + * This fixes Webkit's timing bugs, like accelerated animations falling + * out of sync with main thread animations and massive delays in starting + * accelerated animations in WKWebView. + */ + if (!allowWebkitAcceleration) animation.playbackRate = 1.000001; + /** + * If we can't animate the value natively then we can fallback to the numbers-only + * polyfill for transforms. + */ + } else if (valueIsTransform) { + /** + * If any keyframe is a string (because we measured it from the DOM), we need to convert + * it into a number before passing to the Animation polyfill. + */ + keyframes = keyframes.map((value) => + typeof value === "string" ? parseFloat(value) : value + ); + /** + * If we only have a single keyframe, we need to create an initial keyframe by reading + * the current value from the DOM. + */ + if (keyframes.length === 1) { + keyframes.unshift(parseFloat(readInitialValue())); + } + const render = (latest) => { + if (definition) latest = definition.toDefaultUnit(latest); + _styleEs.style.set(element, name, latest); + }; + animation = new _animation.Animation( + render, + keyframes, + Object.assign(Object.assign({}, options), { + duration, + easing, + }) + ); + } else { + const target = keyframes[keyframes.length - 1]; + _styleEs.style.set( + element, + name, + definition && (0, _utils.isNumber)(target) + ? definition.toDefaultUnit(target) + : target + ); + } + if (isRecording) { + record( + element, + key, + keyframes, + { + duration, + delay: delay, + easing, + repeat, + offset, + }, + "motion-one" + ); + } + motionValue.setAnimation(animation); + return animation; + }; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ScrollOffset = void 0; -const ScrollOffset = exports.ScrollOffset = { - Enter: [[0, 1], [1, 1]], - Exit: [[0, 0], [1, 0]], - Any: [[1, 0], [0, 1]], - All: [[0, 0], [1, 1]] -}; - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js": -/*!*****************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js ***! - \*****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createOnScrollHandler = createOnScrollHandler; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _infoEs = __webpack_require__(/*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js"); -var _indexEs = __webpack_require__(/*! ./offsets/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js"); -function measure(container, target = container, info) { - /** - * Find inset of target within scrollable container - */ - info.x.targetOffset = 0; - info.y.targetOffset = 0; - if (target !== container) { - let node = target; - while (node && node != container) { - info.x.targetOffset += node.offsetLeft; - info.y.targetOffset += node.offsetTop; - node = node.offsetParent; - } - } - info.x.targetLength = target === container ? target.scrollWidth : target.clientWidth; - info.y.targetLength = target === container ? target.scrollHeight : target.clientHeight; - info.x.containerLength = container.clientWidth; - info.y.containerLength = container.clientHeight; -} -function createOnScrollHandler(element, onScroll, info, options = {}) { - const axis = options.axis || "y"; - return { - measure: () => measure(element, options.target, info), - update: time => { - (0, _infoEs.updateScrollInfo)(element, info, time); - if (options.offset || options.target) { - (0, _indexEs.resolveOffsets)(element, info, options); - } - }, - notify: typeof onScroll === "function" ? () => onScroll(info) : scrubAnimation(onScroll, info[axis]) - }; -} -function scrubAnimation(controls, axisInfo) { - controls.pause(); - controls.forEachNative((animation, { - easing - }) => { - var _a, _b; - if (animation.updateDuration) { - if (!easing) animation.easing = _utils.noopReturn; - animation.updateDuration(1); - } else { - const timingOptions = { - duration: 1000 - }; - if (!easing) timingOptions.easing = "linear"; - (_b = (_a = animation.effect) === null || _a === void 0 ? void 0 : _a.updateTiming) === null || _b === void 0 ? void 0 : _b.call(_a, timingOptions); - } - }); - return () => { - controls.currentTime = axisInfo.progress; - }; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/index.es.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/index.es.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/animate/data.es.js": + /*!********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/data.es.js ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getAnimationData = getAnimationData; + exports.getMotionValue = getMotionValue; + var _types = __webpack_require__( + /*! @motionone/types */ "../../../node_modules/@motionone/types/dist/index.es.js" + ); + const data = new WeakMap(); + function getAnimationData(element) { + if (!data.has(element)) { + data.set(element, { + transforms: [], + values: new Map(), + }); + } + return data.get(element); + } + function getMotionValue(motionValues, name) { + if (!motionValues.has(name)) { + motionValues.set(name, new _types.MotionValue()); + } + return motionValues.get(name); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "ScrollOffset", ({ - enumerable: true, - get: function () { - return _presetsEs.ScrollOffset; - } -})); -Object.defineProperty(exports, "animate", ({ - enumerable: true, - get: function () { - return _indexEs.animate; - } -})); -Object.defineProperty(exports, "animateStyle", ({ - enumerable: true, - get: function () { - return _animateStyleEs.animateStyle; - } -})); -Object.defineProperty(exports, "createMotionState", ({ - enumerable: true, - get: function () { - return _indexEs7.createMotionState; - } -})); -Object.defineProperty(exports, "createStyleString", ({ - enumerable: true, - get: function () { - return _styleStringEs.createStyleString; - } -})); -Object.defineProperty(exports, "createStyles", ({ - enumerable: true, - get: function () { - return _styleObjectEs.createStyles; - } -})); -Object.defineProperty(exports, "getAnimationData", ({ - enumerable: true, - get: function () { - return _dataEs.getAnimationData; - } -})); -Object.defineProperty(exports, "getStyleName", ({ - enumerable: true, - get: function () { - return _getStyleNameEs.getStyleName; - } -})); -Object.defineProperty(exports, "glide", ({ - enumerable: true, - get: function () { - return _indexEs4.glide; - } -})); -Object.defineProperty(exports, "inView", ({ - enumerable: true, - get: function () { - return _inViewEs.inView; - } -})); -Object.defineProperty(exports, "mountedStates", ({ - enumerable: true, - get: function () { - return _indexEs7.mountedStates; - } -})); -Object.defineProperty(exports, "resize", ({ - enumerable: true, - get: function () { - return _indexEs5.resize; - } -})); -Object.defineProperty(exports, "scroll", ({ - enumerable: true, - get: function () { - return _indexEs6.scroll; - } -})); -Object.defineProperty(exports, "spring", ({ - enumerable: true, - get: function () { - return _indexEs3.spring; - } -})); -Object.defineProperty(exports, "stagger", ({ - enumerable: true, - get: function () { - return _staggerEs.stagger; - } -})); -Object.defineProperty(exports, "style", ({ - enumerable: true, - get: function () { - return _styleEs.style; - } -})); -Object.defineProperty(exports, "timeline", ({ - enumerable: true, - get: function () { - return _indexEs2.timeline; - } -})); -Object.defineProperty(exports, "withControls", ({ - enumerable: true, - get: function () { - return _controlsEs.withControls; - } -})); -var _indexEs = __webpack_require__(/*! ./animate/index.es.js */ "../../../node_modules/@motionone/dom/dist/animate/index.es.js"); -var _animateStyleEs = __webpack_require__(/*! ./animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _indexEs2 = __webpack_require__(/*! ./timeline/index.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js"); -var _staggerEs = __webpack_require__(/*! ./utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); -var _indexEs3 = __webpack_require__(/*! ./easing/spring/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js"); -var _indexEs4 = __webpack_require__(/*! ./easing/glide/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js"); -var _styleEs = __webpack_require__(/*! ./animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); -var _inViewEs = __webpack_require__(/*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js"); -var _indexEs5 = __webpack_require__(/*! ./gestures/resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js"); -var _indexEs6 = __webpack_require__(/*! ./gestures/scroll/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js"); -var _presetsEs = __webpack_require__(/*! ./gestures/scroll/offsets/presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js"); -var _controlsEs = __webpack_require__(/*! ./animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); -var _dataEs = __webpack_require__(/*! ./animate/data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); -var _getStyleNameEs = __webpack_require__(/*! ./animate/utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); -var _indexEs7 = __webpack_require__(/*! ./state/index.es.js */ "../../../node_modules/@motionone/dom/dist/state/index.es.js"); -var _styleObjectEs = __webpack_require__(/*! ./animate/utils/style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js"); -var _styleStringEs = __webpack_require__(/*! ./animate/utils/style-string.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/animate/index.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/index.es.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.animate = animate; + var _animateStyleEs = __webpack_require__( + /*! ./animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" + ); + var _optionsEs = __webpack_require__( + /*! ./utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js" + ); + var _resolveElementsEs = __webpack_require__( + /*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" + ); + var _controlsEs = __webpack_require__( + /*! ./utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js" + ); + var _staggerEs = __webpack_require__( + /*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js" + ); + function animate(elements, keyframes, options = {}) { + elements = (0, _resolveElementsEs.resolveElements)(elements); + const numElements = elements.length; + /** + * Create and start new animations + */ + const animationFactories = []; + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + for (const key in keyframes) { + const valueOptions = (0, _optionsEs.getOptions)(options, key); + valueOptions.delay = (0, _staggerEs.resolveOption)( + valueOptions.delay, + i, + numElements + ); + const animation = (0, _animateStyleEs.animateStyle)( + element, + key, + keyframes[key], + valueOptions + ); + animationFactories.push(animation); + } + } + return (0, _controlsEs.withControls)( + animationFactories, + options, + /** + * TODO: + * If easing is set to spring or glide, duration will be dynamically + * generated. Ideally we would dynamically generate this from + * animation.effect.getComputedTiming().duration but this isn't + * supported in iOS13 or our number polyfill. Perhaps it's possible + * to Proxy animations returned from animateStyle that has duration + * as a getter. + */ + options.duration + ); + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hover = void 0; -var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -const mouseEvent = (element, name, action) => event => { - if (event.pointerType && event.pointerType !== "mouse") return; - action(); - (0, _eventsEs.dispatchPointerEvent)(element, name, event); -}; -const hover = exports.hover = { - isActive: options => Boolean(options.hover), - subscribe: (element, { - enable, - disable - }) => { - const onEnter = mouseEvent(element, "hoverstart", enable); - const onLeave = mouseEvent(element, "hoverend", disable); - element.addEventListener("pointerenter", onEnter); - element.addEventListener("pointerleave", onLeave); - return () => { - element.removeEventListener("pointerenter", onEnter); - element.removeEventListener("pointerleave", onLeave); - }; - } -}; + /***/ "../../../node_modules/@motionone/dom/dist/animate/style.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/style.es.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.style = void 0; + var _cssVarEs = __webpack_require__( + /*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js" + ); + var _getStyleNameEs = __webpack_require__( + /*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js" + ); + var _transformsEs = __webpack_require__( + /*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" + ); + const style = (exports.style = { + get: (element, name) => { + name = (0, _getStyleNameEs.getStyleName)(name); + let value = (0, _cssVarEs.isCssVar)(name) + ? element.style.getPropertyValue(name) + : getComputedStyle(element)[name]; + if (!value && value !== 0) { + const definition = _transformsEs.transformDefinitions.get(name); + if (definition) value = definition.initialValue; + } + return value; + }, + set: (element, name, value) => { + name = (0, _getStyleNameEs.getStyleName)(name); + if ((0, _cssVarEs.isCssVar)(name)) { + element.style.setProperty(name, value); + } else { + element.style[name] = value; + } + }, + }); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js ***! + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js ***! \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.inView = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -var _inViewEs = __webpack_require__(/*! ../../gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js"); -const inView = exports.inView = { - isActive: options => Boolean(options.inView), - subscribe: (element, { - enable, - disable - }, { - inViewOptions = {} - }) => { - const { - once - } = inViewOptions, - viewOptions = (0, _tslib.__rest)(inViewOptions, ["once"]); - return (0, _inViewEs.inView)(element, enterEntry => { - enable(); - (0, _eventsEs.dispatchViewEvent)(element, "viewenter", enterEntry); - if (!once) { - return leaveEntry => { - disable(); - (0, _eventsEs.dispatchViewEvent)(element, "viewleave", leaveEntry); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.withControls = exports.controls = void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _stopAnimationEs = __webpack_require__( + /*! ./stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js" + ); + const createAnimation = (factory) => factory(); + const withControls = ( + animationFactory, + options, + duration = _utils.defaults.duration + ) => { + return new Proxy( + { + animations: animationFactory.map(createAnimation).filter(Boolean), + duration, + options, + }, + controls + ); }; - } - }, viewOptions); - } -}; + /** + * TODO: + * Currently this returns the first animation, ideally it would return + * the first active animation. + */ + exports.withControls = withControls; + const getActiveAnimation = (state) => state.animations[0]; + const controls = (exports.controls = { + get: (target, key) => { + const activeAnimation = getActiveAnimation(target); + switch (key) { + case "duration": + return target.duration; + case "currentTime": + return _utils.time.s( + (activeAnimation === null || activeAnimation === void 0 + ? void 0 + : activeAnimation[key]) || 0 + ); + case "playbackRate": + case "playState": + return activeAnimation === null || activeAnimation === void 0 + ? void 0 + : activeAnimation[key]; + case "finished": + if (!target.finished) { + target.finished = Promise.all( + target.animations.map(selectFinished) + ).catch(_utils.noop); + } + return target.finished; + case "stop": + return () => { + target.animations.forEach((animation) => + (0, _stopAnimationEs.stopAnimation)(animation) + ); + }; + case "forEachNative": + /** + * This is for internal use only, fire a callback for each + * underlying animation. + */ + return (callback) => { + target.animations.forEach((animation) => + callback(animation, target) + ); + }; + default: + return typeof (activeAnimation === null || + activeAnimation === void 0 + ? void 0 + : activeAnimation[key]) === "undefined" + ? undefined + : () => + target.animations.forEach((animation) => + animation[key]() + ); + } + }, + set: (target, key, value) => { + switch (key) { + case "currentTime": + value = _utils.time.ms(value); + case "currentTime": + case "playbackRate": + for (let i = 0; i < target.animations.length; i++) { + target.animations[i][key] = value; + } + return true; + } + return false; + }, + }); + const selectFinished = (animation) => animation.finished; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.press = void 0; -var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -const press = exports.press = { - isActive: options => Boolean(options.press), - subscribe: (element, { - enable, - disable - }) => { - const onPointerUp = event => { - disable(); - (0, _eventsEs.dispatchPointerEvent)(element, "pressend", event); - window.removeEventListener("pointerup", onPointerUp); - }; - const onPointerDown = event => { - enable(); - (0, _eventsEs.dispatchPointerEvent)(element, "pressstart", event); - window.addEventListener("pointerup", onPointerUp); - }; - element.addEventListener("pointerdown", onPointerDown); - return () => { - element.removeEventListener("pointerdown", onPointerDown); - window.removeEventListener("pointerup", onPointerUp); - }; - } -}; + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js ***! + \*****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isCssVar = void 0; + exports.registerCssVariable = registerCssVariable; + exports.registeredProperties = void 0; + var _transformsEs = __webpack_require__( + /*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" + ); + const isCssVar = (name) => name.startsWith("--"); + exports.isCssVar = isCssVar; + const registeredProperties = (exports.registeredProperties = new Set()); + function registerCssVariable(name) { + if (registeredProperties.has(name)) return; + registeredProperties.add(name); + try { + const { syntax, initialValue } = + _transformsEs.transformDefinitions.has(name) + ? _transformsEs.transformDefinitions.get(name) + : {}; + CSS.registerProperty({ + name, + inherits: false, + syntax, + initialValue, + }); + } catch (e) {} + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/state/index.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/index.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createMotionState = createMotionState; -exports.mountedStates = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _animateStyleEs = __webpack_require__(/*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _styleEs = __webpack_require__(/*! ../animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); -var _optionsEs = __webpack_require__(/*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); -var _hasChangedEs = __webpack_require__(/*! ./utils/has-changed.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js"); -var _resolveVariantEs = __webpack_require__(/*! ./utils/resolve-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js"); -var _scheduleEs = __webpack_require__(/*! ./utils/schedule.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js"); -var _inViewEs = __webpack_require__(/*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js"); -var _hoverEs = __webpack_require__(/*! ./gestures/hover.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js"); -var _pressEs = __webpack_require__(/*! ./gestures/press.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js"); -var _eventsEs = __webpack_require__(/*! ./utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); -const gestures = { - inView: _inViewEs.inView, - hover: _hoverEs.hover, - press: _pressEs.press -}; -/** - * A list of state types, in priority order. If a value is defined in - * a righter-most type, it will override any definition in a lefter-most. - */ -const stateTypes = ["initial", "animate", ...Object.keys(gestures), "exit"]; -/** - * A global store of all generated motion states. This can be used to lookup - * a motion state for a given Element. - */ -const mountedStates = exports.mountedStates = new WeakMap(); -function createMotionState(options = {}, parent) { - /** - * The element represented by the motion state. This is an empty reference - * when we create the state to support SSR and allow for later mounting - * in view libraries. - * - * @ts-ignore - */ - let element; - /** - * Calculate a depth that we can use to order motion states by tree depth. - */ - let depth = parent ? parent.getDepth() + 1 : 0; - /** - * Track which states are currently active. - */ - const activeStates = { - initial: true, - animate: true - }; - /** - * A map of functions that, when called, will remove event listeners for - * a given gesture. - */ - const gestureSubscriptions = {}; - /** - * Initialise a context to share through motion states. This - * will be populated by variant names (if any). - */ - const context = {}; - for (const name of stateTypes) { - context[name] = typeof options[name] === "string" ? options[name] : parent === null || parent === void 0 ? void 0 : parent.getContext()[name]; - } - /** - * If initial is set to false we use the animate prop as the initial - * animation state. - */ - const initialVariantSource = options.initial === false ? "animate" : "initial"; - /** - * Destructure an initial target out from the resolved initial variant. - */ - let _a = (0, _resolveVariantEs.resolveVariant)(options[initialVariantSource] || context[initialVariantSource], options.variants) || {}, - target = (0, _tslib.__rest)(_a, ["transition"]); - /** - * The base target is a cached map of values that we'll use to animate - * back to if a value is removed from all active state types. This - * is usually the initial value as read from the DOM, for instance if - * it hasn't been defined in initial. - */ - const baseTarget = Object.assign({}, target); - /** - * A generator that will be processed by the global animation scheduler. - * This yeilds when it switches from reading the DOM to writing to it - * to prevent layout thrashing. - */ - function* animateUpdates() { - var _a, _b; - const prevTarget = target; - target = {}; - const animationOptions = {}; - for (const name of stateTypes) { - if (!activeStates[name]) continue; - const variant = (0, _resolveVariantEs.resolveVariant)(options[name]); - if (!variant) continue; - for (const key in variant) { - if (key === "transition") continue; - target[key] = variant[key]; - animationOptions[key] = (0, _optionsEs.getOptions)((_b = (_a = variant.transition) !== null && _a !== void 0 ? _a : options.transition) !== null && _b !== void 0 ? _b : {}, key); - } - } - const allTargetKeys = new Set([...Object.keys(target), ...Object.keys(prevTarget)]); - const animationFactories = []; - allTargetKeys.forEach(key => { - var _a; - if (target[key] === undefined) { - target[key] = baseTarget[key]; - } - if ((0, _hasChangedEs.hasChanged)(prevTarget[key], target[key])) { - (_a = baseTarget[key]) !== null && _a !== void 0 ? _a : baseTarget[key] = _styleEs.style.get(element, key); - animationFactories.push((0, _animateStyleEs.animateStyle)(element, key, target[key], animationOptions[key])); - } - }); - // Wait for all animation states to read from the DOM - yield; - const animations = animationFactories.map(factory => factory()).filter(Boolean); - if (!animations.length) return; - const animationTarget = target; - element.dispatchEvent((0, _eventsEs.motionEvent)("motionstart", animationTarget)); - Promise.all(animations.map(animation => animation.finished)).then(() => { - element.dispatchEvent((0, _eventsEs.motionEvent)("motioncomplete", animationTarget)); - }).catch(_utils.noop); - } - const setGesture = (name, isActive) => () => { - activeStates[name] = isActive; - (0, _scheduleEs.scheduleAnimation)(state); - }; - const updateGestureSubscriptions = () => { - for (const name in gestures) { - const isGestureActive = gestures[name].isActive(options); - const remove = gestureSubscriptions[name]; - if (isGestureActive && !remove) { - gestureSubscriptions[name] = gestures[name].subscribe(element, { - enable: setGesture(name, true), - disable: setGesture(name, false) - }, options); - } else if (!isGestureActive && remove) { - remove(); - delete gestureSubscriptions[name]; - } - } - }; - const state = { - update: newOptions => { - if (!element) return; - options = newOptions; - updateGestureSubscriptions(); - (0, _scheduleEs.scheduleAnimation)(state); - }, - setActive: (name, isActive) => { - if (!element) return; - activeStates[name] = isActive; - (0, _scheduleEs.scheduleAnimation)(state); - }, - animateUpdates, - getDepth: () => depth, - getTarget: () => target, - getOptions: () => options, - getContext: () => context, - mount: newElement => { - (0, _heyListen.invariant)(Boolean(newElement), "Animation state must be mounted with valid Element"); - element = newElement; - mountedStates.set(element, state); - updateGestureSubscriptions(); - return () => { - mountedStates.delete(element); - (0, _scheduleEs.unscheduleAnimation)(state); - for (const key in gestureSubscriptions) { - gestureSubscriptions[key](); - } - }; - }, - isMounted: () => Boolean(element) - }; - return state; -} + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js ***! + \****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.cubicBezierAsString = exports.convertEasing = void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + const convertEasing = (easing) => + (0, _utils.isCubicBezier)(easing) + ? cubicBezierAsString(easing) + : easing; + exports.convertEasing = convertEasing; + const cubicBezierAsString = ([a, b, c, d]) => + `cubic-bezier(${a}, ${b}, ${c}, ${d})`; + exports.cubicBezierAsString = cubicBezierAsString; + + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js": + /*!***************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js ***! + \***************************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.supports = void 0; + const testAnimation = (keyframes) => + document.createElement("div").animate(keyframes, { + duration: 0.001, + }); + const featureTests = { + cssRegisterProperty: () => + typeof CSS !== "undefined" && + Object.hasOwnProperty.call(CSS, "registerProperty"), + waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"), + partialKeyframes: () => { + try { + testAnimation({ + opacity: [1], + }); + } catch (e) { + return false; + } + return true; + }, + finished: () => + Boolean( + testAnimation({ + opacity: [0, 1], + }).finished + ), + }; + const results = {}; + const supports = (exports.supports = {}); + for (const key in featureTests) { + supports[key] = () => { + if (results[key] === undefined) results[key] = featureTests[key](); + return results[key]; + }; + } -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/events.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js": + /*!************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js ***! + \************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getStyleName = getStyleName; + var _transformsEs = __webpack_require__( + /*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" + ); + function getStyleName(key) { + if (_transformsEs.transformAlias[key]) + key = _transformsEs.transformAlias[key]; + return (0, _transformsEs.isTransform)(key) + ? (0, _transformsEs.asTransformCssVar)(key) + : key; + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.dispatchPointerEvent = dispatchPointerEvent; -exports.dispatchViewEvent = dispatchViewEvent; -exports.motionEvent = void 0; -const motionEvent = (name, target) => new CustomEvent(name, { - detail: { - target - } -}); -exports.motionEvent = motionEvent; -function dispatchPointerEvent(element, name, event) { - element.dispatchEvent(new CustomEvent(name, { - detail: { - originalEvent: event - } - })); -} -function dispatchViewEvent(element, name, entry) { - element.dispatchEvent(new CustomEvent(name, { - detail: { - originalEntry: entry - } - })); -} + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js": + /*!*******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js ***! + \*******************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.hydrateKeyframes = hydrateKeyframes; + exports.keyframesList = void 0; + function hydrateKeyframes(keyframes, readInitialValue) { + for (let i = 0; i < keyframes.length; i++) { + if (keyframes[i] === null) { + keyframes[i] = i ? keyframes[i - 1] : readInitialValue(); + } + } + return keyframes; + } + const keyframesList = (keyframes) => + Array.isArray(keyframes) ? keyframes : [keyframes]; + exports.keyframesList = keyframesList; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js": -/*!*******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js ***! - \*******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hasChanged = hasChanged; -exports.shallowCompare = shallowCompare; -function hasChanged(a, b) { - if (typeof a !== typeof b) return true; - if (Array.isArray(a) && Array.isArray(b)) return !shallowCompare(a, b); - return a !== b; -} -function shallowCompare(next, prev) { - const prevLength = prev.length; - if (prevLength !== next.length) return false; - for (let i = 0; i < prevLength; i++) { - if (prev[i] !== next[i]) return false; - } - return true; -} + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js ***! + \*****************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getOptions = void 0; + const getOptions = (options, key) => + /** + * TODO: Make test for this + * Always return a new object otherwise delay is overwritten by results of stagger + * and this results in no stagger + */ + options[key] + ? Object.assign(Object.assign({}, options), options[key]) + : Object.assign({}, options); + exports.getOptions = getOptions; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isVariant = isVariant; -function isVariant(definition) { - return typeof definition === "object"; -} - -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js": + /*!************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js ***! + \************************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.stopAnimation = stopAnimation; + function stopAnimation(animation, needsCommit = true) { + if (!animation || animation.playState === "finished") return; + // Suppress error thrown by WAAPI + try { + if (animation.stop) { + animation.stop(); + } else { + needsCommit && animation.commitStyles(); + animation.cancel(); + } + } catch (e) {} + } -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js": -/*!***********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js ***! - \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js ***! + \**********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createStyles = createStyles; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _transformsEs = __webpack_require__( + /*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" + ); + function createStyles(keyframes) { + const initialKeyframes = {}; + const transformKeys = []; + for (let key in keyframes) { + const value = keyframes[key]; + if ((0, _transformsEs.isTransform)(key)) { + if (_transformsEs.transformAlias[key]) + key = _transformsEs.transformAlias[key]; + transformKeys.push(key); + key = (0, _transformsEs.asTransformCssVar)(key); + } + let initialKeyframe = Array.isArray(value) ? value[0] : value; + /** + * If this is a number and we have a default value type, convert the number + * to this type. + */ + const definition = _transformsEs.transformDefinitions.get(key); + if (definition) { + initialKeyframe = (0, _utils.isNumber)(value) + ? definition.toDefaultUnit(value) + : value; + } + initialKeyframes[key] = initialKeyframe; + } + if (transformKeys.length) { + initialKeyframes.transform = (0, + _transformsEs.buildTransformTemplate)(transformKeys); + } + return initialKeyframes; + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveVariant = resolveVariant; -var _isVariantEs = __webpack_require__(/*! ./is-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js"); -function resolveVariant(definition, variants) { - if ((0, _isVariantEs.isVariant)(definition)) { - return definition; - } else if (definition && variants) { - return variants[definition]; - } -} + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js ***! + \**********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createStyleString = createStyleString; + var _styleObjectEs = __webpack_require__( + /*! ./style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js" + ); + const camelLetterToPipeLetter = (letter) => `-${letter.toLowerCase()}`; + const camelToPipeCase = (str) => + str.replace(/[A-Z]/g, camelLetterToPipeLetter); + function createStyleString(target = {}) { + const styles = (0, _styleObjectEs.createStyles)(target); + let style = ""; + for (const key in styles) { + style += key.startsWith("--") ? key : camelToPipeCase(key); + style += `: ${styles[key]}; `; + } + return style; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js ***! - \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.scheduleAnimation = scheduleAnimation; -exports.unscheduleAnimation = unscheduleAnimation; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -let scheduled = undefined; -function processScheduledAnimations() { - if (!scheduled) return; - const generators = scheduled.sort(compareByDepth).map(fireAnimateUpdates); - generators.forEach(fireNext); - generators.forEach(fireNext); - scheduled = undefined; -} -function scheduleAnimation(state) { - if (!scheduled) { - scheduled = [state]; - requestAnimationFrame(processScheduledAnimations); - } else { - (0, _utils.addUniqueItem)(scheduled, state); - } -} -function unscheduleAnimation(state) { - scheduled && (0, _utils.removeItem)(scheduled, state); -} -const compareByDepth = (a, b) => a.getDepth() - b.getDepth(); -const fireAnimateUpdates = state => state.animateUpdates(); -const fireNext = iterator => iterator.next(); - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js": -/*!**********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/index.es.js ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createAnimationsFromTimeline = createAnimationsFromTimeline; -exports.timeline = timeline; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _staggerEs = __webpack_require__(/*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); -var _animateStyleEs = __webpack_require__(/*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); -var _controlsEs = __webpack_require__(/*! ../animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); -var _keyframesEs = __webpack_require__(/*! ../animate/utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js"); -var _optionsEs = __webpack_require__(/*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); -var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); -var _transformsEs = __webpack_require__(/*! ../animate/utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); -var _calcTimeEs = __webpack_require__(/*! ./utils/calc-time.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js"); -var _editEs = __webpack_require__(/*! ./utils/edit.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js"); -var _sortEs = __webpack_require__(/*! ./utils/sort.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js"); -function timeline(definition, options = {}) { - var _a; - const animationDefinitions = createAnimationsFromTimeline(definition, options); - /** - * Create and start animations - */ - const animationFactories = animationDefinitions.map(definition => (0, _animateStyleEs.animateStyle)(...definition)).filter(Boolean); - return (0, _controlsEs.withControls)(animationFactories, options, - // Get the duration from the first animation definition - (_a = animationDefinitions[0]) === null || _a === void 0 ? void 0 : _a[3].duration); -} -function createAnimationsFromTimeline(definition, _a = {}) { - var { - defaultOptions = {} - } = _a, - timelineOptions = (0, _tslib.__rest)(_a, ["defaultOptions"]); - const animationDefinitions = []; - const elementSequences = new Map(); - const elementCache = {}; - const timeLabels = new Map(); - let prevTime = 0; - let currentTime = 0; - let totalDuration = 0; - /** - * Build the timeline by mapping over the definition array and converting - * the definitions into keyframes and offsets with absolute time values. - * These will later get converted into relative offsets in a second pass. - */ - for (let i = 0; i < definition.length; i++) { - const segment = definition[i]; - /** - * If this is a timeline label, mark it and skip the rest of this iteration. - */ - if ((0, _utils.isString)(segment)) { - timeLabels.set(segment, currentTime); - continue; - } else if (!Array.isArray(segment)) { - timeLabels.set(segment.name, (0, _calcTimeEs.calcNextTime)(currentTime, segment.at, prevTime, timeLabels)); - continue; - } - const [elementDefinition, keyframes, options = {}] = segment; - /** - * If a relative or absolute time value has been specified we need to resolve - * it in relation to the currentTime. - */ - if (options.at !== undefined) { - currentTime = (0, _calcTimeEs.calcNextTime)(currentTime, options.at, prevTime, timeLabels); - } - /** - * Keep track of the maximum duration in this definition. This will be - * applied to currentTime once the definition has been parsed. - */ - let maxDuration = 0; - /** - * Find all the elements specified in the definition and parse value - * keyframes from their timeline definitions. - */ - const elements = (0, _resolveElementsEs.resolveElements)(elementDefinition, elementCache); - const numElements = elements.length; - for (let elementIndex = 0; elementIndex < numElements; elementIndex++) { - const element = elements[elementIndex]; - const elementSequence = getElementSequence(element, elementSequences); - for (const key in keyframes) { - const valueSequence = getValueSequence(key, elementSequence); - let valueKeyframes = (0, _keyframesEs.keyframesList)(keyframes[key]); - const valueOptions = (0, _optionsEs.getOptions)(options, key); - let { - duration = defaultOptions.duration || _utils.defaults.duration, - easing = defaultOptions.easing || _utils.defaults.easing - } = valueOptions; - if ((0, _utils.isEasingGenerator)(easing)) { - const valueIsTransform = (0, _transformsEs.isTransform)(key); - (0, _heyListen.invariant)(valueKeyframes.length === 2 || !valueIsTransform, "spring must be provided 2 keyframes within timeline"); - const custom = easing.createAnimation(valueKeyframes, - // TODO We currently only support explicit keyframes - // so this doesn't currently read from the DOM - () => "0", valueIsTransform); - easing = custom.easing; - if (custom.keyframes !== undefined) valueKeyframes = custom.keyframes; - if (custom.duration !== undefined) duration = custom.duration; - } - const delay = (0, _staggerEs.resolveOption)(options.delay, elementIndex, numElements) || 0; - const startTime = currentTime + delay; - const targetTime = startTime + duration; + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js": + /*!********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js ***! + \********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.transformDefinitions = + exports.transformAlias = + exports.isTransform = + exports.compareTransformOrder = + exports.buildTransformTemplate = + exports.axes = + exports.asTransformCssVar = + exports.addTransformToElement = + void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _dataEs = __webpack_require__( + /*! ../data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js" + ); /** - * + * A list of all transformable axes. We'll use this list to generated a version + * of each axes for each transform. */ - let { - offset = (0, _utils.defaultOffset)(valueKeyframes.length) - } = valueOptions; + const axes = (exports.axes = ["", "X", "Y", "Z"]); /** - * If there's only one offset of 0, fill in a second with length 1 - * - * TODO: Ensure there's a test that covers this removal + * An ordered array of each transformable value. By default, transform values + * will be sorted to this order. */ - if (offset.length === 1 && offset[0] === 0) { - offset[1] = 1; - } + const order = ["translate", "scale", "rotate", "skew"]; + const transformAlias = (exports.transformAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + }); + const rotation = { + syntax: "", + initialValue: "0deg", + toDefaultUnit: (v) => v + "deg", + }; + const baseTransformProperties = { + translate: { + syntax: "", + initialValue: "0px", + toDefaultUnit: (v) => v + "px", + }, + rotate: rotation, + scale: { + syntax: "", + initialValue: 1, + toDefaultUnit: _utils.noopReturn, + }, + skew: rotation, + }; + const transformDefinitions = (exports.transformDefinitions = new Map()); + const asTransformCssVar = (name) => `--motion-${name}`; /** - * Fill out if offset if fewer offsets than keyframes + * Generate a list of every possible transform key */ - const remainder = length - valueKeyframes.length; - remainder > 0 && (0, _utils.fillOffset)(offset, remainder); + exports.asTransformCssVar = asTransformCssVar; + const transforms = ["x", "y", "z"]; + order.forEach((name) => { + axes.forEach((axis) => { + transforms.push(name + axis); + transformDefinitions.set( + asTransformCssVar(name + axis), + baseTransformProperties[name] + ); + }); + }); /** - * If only one value has been set, ie [1], push a null to the start of - * the keyframe array. This will let us mark a keyframe at this point - * that will later be hydrated with the previous value. + * A function to use with Array.sort to sort transform keys by their default order. */ - valueKeyframes.length === 1 && valueKeyframes.unshift(null); + const compareTransformOrder = (a, b) => + transforms.indexOf(a) - transforms.indexOf(b); /** - * Add keyframes, mapping offsets to absolute time. + * Provide a quick way to check if a string is the name of a transform */ - (0, _editEs.addKeyframes)(valueSequence, valueKeyframes, easing, offset, startTime, targetTime); - maxDuration = Math.max(delay + duration, maxDuration); - totalDuration = Math.max(targetTime, totalDuration); - } - } - prevTime = currentTime; - currentTime += maxDuration; - } - /** - * For every element and value combination create a new animation. - */ - elementSequences.forEach((valueSequences, element) => { - for (const key in valueSequences) { - const valueSequence = valueSequences[key]; - /** - * Arrange all the keyframes in ascending time order. - */ - valueSequence.sort(_sortEs.compareByTime); - const keyframes = []; - const valueOffset = []; - const valueEasing = []; - /** - * For each keyframe, translate absolute times into - * relative offsets based on the total duration of the timeline. - */ - for (let i = 0; i < valueSequence.length; i++) { - const { - at, - value, - easing - } = valueSequence[i]; - keyframes.push(value); - valueOffset.push((0, _utils.progress)(0, totalDuration, at)); - valueEasing.push(easing || _utils.defaults.easing); - } - /** - * If the first keyframe doesn't land on offset: 0 - * provide one by duplicating the initial keyframe. This ensures - * it snaps to the first keyframe when the animation starts. - */ - if (valueOffset[0] !== 0) { - valueOffset.unshift(0); - keyframes.unshift(keyframes[0]); - valueEasing.unshift("linear"); - } - /** - * If the last keyframe doesn't land on offset: 1 - * provide one with a null wildcard value. This will ensure it - * stays static until the end of the animation. - */ - if (valueOffset[valueOffset.length - 1] !== 1) { - valueOffset.push(1); - keyframes.push(null); - } - animationDefinitions.push([element, key, keyframes, Object.assign(Object.assign(Object.assign({}, defaultOptions), { - duration: totalDuration, - easing: valueEasing, - offset: valueOffset - }), timelineOptions)]); - } - }); - return animationDefinitions; -} -function getElementSequence(element, sequences) { - !sequences.has(element) && sequences.set(element, {}); - return sequences.get(element); -} -function getValueSequence(name, sequences) { - if (!sequences[name]) sequences[name] = []; - return sequences[name]; -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js": -/*!********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcNextTime = calcNextTime; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -function calcNextTime(current, next, prev, labels) { - var _a; - if ((0, _utils.isNumber)(next)) { - return next; - } else if (next.startsWith("-") || next.startsWith("+")) { - return Math.max(0, current + parseFloat(next)); - } else if (next === "<") { - return prev; - } else { - return (_a = labels.get(next)) !== null && _a !== void 0 ? _a : current; - } -} + exports.compareTransformOrder = compareTransformOrder; + const transformLookup = new Set(transforms); + const isTransform = (name) => transformLookup.has(name); + exports.isTransform = isTransform; + const addTransformToElement = (element, name) => { + // Map x to translateX etc + if (transformAlias[name]) name = transformAlias[name]; + const { transforms } = (0, _dataEs.getAnimationData)(element); + (0, _utils.addUniqueItem)(transforms, name); + /** + * TODO: An optimisation here could be to cache the transform in element data + * and only update if this has changed. + */ + element.style.transform = buildTransformTemplate(transforms); + }; + exports.addTransformToElement = addTransformToElement; + const buildTransformTemplate = (transforms) => + transforms + .sort(compareTransformOrder) + .reduce(transformListToString, "") + .trim(); + exports.buildTransformTemplate = buildTransformTemplate; + const transformListToString = (template, name) => + `${template} ${name}(var(${asTransformCssVar(name)}))`; + + /***/ + }, + + /***/ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js ***! + \**************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createGeneratorEasing = createGeneratorEasing; + var _generators = __webpack_require__( + /*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js" + ); + function createGeneratorEasing(createGenerator) { + const keyframesCache = new WeakMap(); + return (options = {}) => { + const generatorCache = new Map(); + const getGenerator = ( + from = 0, + to = 100, + velocity = 0, + isScale = false + ) => { + const key = `${from}-${to}-${velocity}-${isScale}`; + if (!generatorCache.has(key)) { + generatorCache.set( + key, + createGenerator( + Object.assign( + { + from, + to, + velocity, + restSpeed: isScale ? 0.05 : 2, + restDistance: isScale ? 0.01 : 0.5, + }, + options + ) + ) + ); + } + return generatorCache.get(key); + }; + const getKeyframes = (generator) => { + if (!keyframesCache.has(generator)) { + keyframesCache.set( + generator, + (0, _generators.pregenerateKeyframes)(generator) + ); + } + return keyframesCache.get(generator); + }; + return { + createAnimation: ( + keyframes, + getOrigin, + canUseGenerator, + name, + motionValue + ) => { + var _a, _b; + let settings; + const numKeyframes = keyframes.length; + let shouldUseGenerator = + canUseGenerator && + numKeyframes <= 2 && + keyframes.every(isNumberOrNull); + if (shouldUseGenerator) { + const target = keyframes[numKeyframes - 1]; + const unresolvedOrigin = + numKeyframes === 1 ? null : keyframes[0]; + let velocity = 0; + let origin = 0; + const prevGenerator = + motionValue === null || motionValue === void 0 + ? void 0 + : motionValue.generator; + if (prevGenerator) { + /** + * If we have a generator for this value we can use it to resolve + * the animations's current value and velocity. + */ + const { animation, generatorStartTime } = motionValue; + const startTime = + (animation === null || animation === void 0 + ? void 0 + : animation.startTime) || + generatorStartTime || + 0; + const currentTime = + (animation === null || animation === void 0 + ? void 0 + : animation.currentTime) || + performance.now() - startTime; + const prevGeneratorCurrent = + prevGenerator(currentTime).current; + origin = + (_a = unresolvedOrigin) !== null && _a !== void 0 + ? _a + : prevGeneratorCurrent; + if ( + numKeyframes === 1 || + (numKeyframes === 2 && keyframes[0] === null) + ) { + velocity = (0, _generators.calcGeneratorVelocity)( + (t) => prevGenerator(t).current, + currentTime, + prevGeneratorCurrent + ); + } + } else { + origin = + (_b = unresolvedOrigin) !== null && _b !== void 0 + ? _b + : parseFloat(getOrigin()); + } + const generator = getGenerator( + origin, + target, + velocity, + name === null || name === void 0 + ? void 0 + : name.includes("scale") + ); + const keyframesMetadata = getKeyframes(generator); + settings = Object.assign( + Object.assign({}, keyframesMetadata), + { + easing: "linear", + } + ); + // TODO Add test for this + if (motionValue) { + motionValue.generator = generator; + motionValue.generatorStartTime = performance.now(); + } + } else { + const keyframesMetadata = getKeyframes(getGenerator(0, 100)); + settings = { + easing: "ease", + duration: keyframesMetadata.overshootDuration, + }; + } + return settings; + }, + }; + }; + } + const isNumberOrNull = (value) => typeof value !== "string"; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.addKeyframes = addKeyframes; -exports.eraseKeyframes = eraseKeyframes; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -function eraseKeyframes(sequence, startTime, endTime) { - for (let i = 0; i < sequence.length; i++) { - const keyframe = sequence[i]; - if (keyframe.at > startTime && keyframe.at < endTime) { - (0, _utils.removeItem)(sequence, keyframe); - // If we remove this item we have to push the pointer back one - i--; - } - } -} -function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) { - /** - * Erase every existing value between currentTime and targetTime, - * this will essentially splice this timeline into any currently - * defined ones. - */ - eraseKeyframes(sequence, startTime, endTime); - for (let i = 0; i < keyframes.length; i++) { - sequence.push({ - value: keyframes[i], - at: (0, _utils.mix)(startTime, endTime, offset[i]), - easing: (0, _utils.getEasingForSegment)(easing, i) - }); - } -} + /***/ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.glide = void 0; + var _generators = __webpack_require__( + /*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js" + ); + var _createGeneratorEasingEs = __webpack_require__( + /*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js" + ); + const glide = (exports.glide = (0, + _createGeneratorEasingEs.createGeneratorEasing)(_generators.glide)); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js ***! + /***/ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js ***! \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.spring = void 0; + var _generators = __webpack_require__( + /*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js" + ); + var _createGeneratorEasingEs = __webpack_require__( + /*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js" + ); + const spring = (exports.spring = (0, + _createGeneratorEasingEs.createGeneratorEasing)(_generators.spring)); + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js ***! + \************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.inView = inView; + var _resolveElementsEs = __webpack_require__( + /*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" + ); + const thresholds = { + any: 0, + all: 1, + }; + function inView( + elementOrSelector, + onStart, + { root, margin: rootMargin, amount = "any" } = {} + ) { + /** + * If this browser doesn't support IntersectionObserver, return a dummy stop function. + * Default triggering of onStart is tricky - it could be used for starting/stopping + * videos, lazy loading content etc. We could provide an option to enable a fallback, or + * provide a fallback callback option. + */ + if (typeof IntersectionObserver === "undefined") { + return () => {}; + } + const elements = (0, _resolveElementsEs.resolveElements)( + elementOrSelector + ); + const activeIntersections = new WeakMap(); + const onIntersectionChange = (entries) => { + entries.forEach((entry) => { + const onEnd = activeIntersections.get(entry.target); + /** + * If there's no change to the intersection, we don't need to + * do anything here. + */ + if (entry.isIntersecting === Boolean(onEnd)) return; + if (entry.isIntersecting) { + const newOnEnd = onStart(entry); + if (typeof newOnEnd === "function") { + activeIntersections.set(entry.target, newOnEnd); + } else { + observer.unobserve(entry.target); + } + } else if (onEnd) { + onEnd(entry); + activeIntersections.delete(entry.target); + } + }); + }; + const observer = new IntersectionObserver(onIntersectionChange, { + root, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholds[amount], + }); + elements.forEach((element) => observer.observe(element)); + return () => observer.disconnect(); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.compareByTime = compareByTime; -function compareByTime(a, b) { - if (a.at === b.at) { - return a.value === null ? 1 : -1; - } else { - return a.at - b.at; - } -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js ***! + \**************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resizeElement = resizeElement; + var _resolveElementsEs = __webpack_require__( + /*! ../../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" + ); + const resizeHandlers = new WeakMap(); + let observer; + function getElementSize(target, borderBoxSize) { + if (borderBoxSize) { + const { inlineSize, blockSize } = borderBoxSize[0]; + return { + width: inlineSize, + height: blockSize, + }; + } else if (target instanceof SVGElement && "getBBox" in target) { + return target.getBBox(); + } else { + return { + width: target.offsetWidth, + height: target.offsetHeight, + }; + } + } + function notifyTarget({ target, contentRect, borderBoxSize }) { + var _a; + (_a = resizeHandlers.get(target)) === null || _a === void 0 + ? void 0 + : _a.forEach((handler) => { + handler({ + target, + contentSize: contentRect, + get size() { + return getElementSize(target, borderBoxSize); + }, + }); + }); + } + function notifyAll(entries) { + entries.forEach(notifyTarget); + } + function createResizeObserver() { + if (typeof ResizeObserver === "undefined") return; + observer = new ResizeObserver(notifyAll); + } + function resizeElement(target, handler) { + if (!observer) createResizeObserver(); + const elements = (0, _resolveElementsEs.resolveElements)(target); + elements.forEach((element) => { + let elementHandlers = resizeHandlers.get(element); + if (!elementHandlers) { + elementHandlers = new Set(); + resizeHandlers.set(element, elementHandlers); + } + elementHandlers.add(handler); + observer === null || observer === void 0 + ? void 0 + : observer.observe(element); + }); + return () => { + elements.forEach((element) => { + const elementHandlers = resizeHandlers.get(element); + elementHandlers === null || elementHandlers === void 0 + ? void 0 + : elementHandlers.delete(handler); + if ( + !(elementHandlers === null || elementHandlers === void 0 + ? void 0 + : elementHandlers.size) + ) { + observer === null || observer === void 0 + ? void 0 + : observer.unobserve(element); + } + }); + }; + } -/***/ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.resolveElements = resolveElements; -function resolveElements(elements, selectorCache) { - var _a; - if (typeof elements === "string") { - if (selectorCache) { - (_a = selectorCache[elements]) !== null && _a !== void 0 ? _a : selectorCache[elements] = document.querySelectorAll(elements); - elements = selectorCache[elements]; - } else { - elements = document.querySelectorAll(elements); - } - } else if (elements instanceof Element) { - elements = [elements]; - } - /** - * Return an empty array - */ - return Array.from(elements || []); -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js ***! + \*************************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resizeWindow = resizeWindow; + const windowCallbacks = new Set(); + let windowResizeHandler; + function createWindowResizeHandler() { + windowResizeHandler = () => { + const size = { + width: window.innerWidth, + height: window.innerHeight, + }; + const info = { + target: window, + size, + contentSize: size, + }; + windowCallbacks.forEach((callback) => callback(info)); + }; + window.addEventListener("resize", windowResizeHandler); + } + function resizeWindow(callback) { + windowCallbacks.add(callback); + if (!windowResizeHandler) createWindowResizeHandler(); + return () => { + windowCallbacks.delete(callback); + if (!windowCallbacks.size && windowResizeHandler) { + windowResizeHandler = undefined; + } + }; + } -/***/ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/utils/stagger.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getFromIndex = getFromIndex; -exports.resolveOption = resolveOption; -exports.stagger = stagger; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _animation = __webpack_require__(/*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js"); -function stagger(duration = 0.1, { - start = 0, - from = 0, - easing -} = {}) { - return (i, total) => { - const fromIndex = (0, _utils.isNumber)(from) ? from : getFromIndex(from, total); - const distance = Math.abs(fromIndex - i); - let delay = duration * distance; - if (easing) { - const maxDelay = total * duration; - const easingFunction = (0, _animation.getEasingFunction)(easing); - delay = easingFunction(delay / maxDelay) * maxDelay; - } - return start + delay; - }; -} -function getFromIndex(from, total) { - if (from === "first") { - return 0; - } else { - const lastIndex = total - 1; - return from === "last" ? lastIndex : lastIndex / 2; - } -} -function resolveOption(option, i, total) { - return typeof option === "function" ? option(i, total) : option; -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js ***! + \*****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resize = resize; + var _handleElementEs = __webpack_require__( + /*! ./handle-element.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js" + ); + var _handleWindowEs = __webpack_require__( + /*! ./handle-window.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js" + ); + function resize(a, b) { + return typeof a === "function" + ? (0, _handleWindowEs.resizeWindow)(a) + : (0, _handleElementEs.resizeElement)(a, b); + } -/***/ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js ***! + \*****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.scroll = scroll; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var _indexEs = __webpack_require__( + /*! ../resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js" + ); + var _infoEs = __webpack_require__( + /*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js" + ); + var _onScrollHandlerEs = __webpack_require__( + /*! ./on-scroll-handler.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js" + ); + const scrollListeners = new WeakMap(); + const resizeListeners = new WeakMap(); + const onScrollHandlers = new WeakMap(); + const getEventTarget = (element) => + element === document.documentElement ? window : element; + function scroll(onScroll, _a = {}) { + var { container = document.documentElement } = _a, + options = (0, _tslib.__rest)(_a, ["container"]); + let containerHandlers = onScrollHandlers.get(container); + /** + * Get the onScroll handlers for this container. + * If one isn't found, create a new one. + */ + if (!containerHandlers) { + containerHandlers = new Set(); + onScrollHandlers.set(container, containerHandlers); + } + /** + * Create a new onScroll handler for the provided callback. + */ + const info = (0, _infoEs.createScrollInfo)(); + const containerHandler = (0, + _onScrollHandlerEs.createOnScrollHandler)( + container, + onScroll, + info, + options + ); + containerHandlers.add(containerHandler); + /** + * Check if there's a scroll event listener for this container. + * If not, create one. + */ + if (!scrollListeners.has(container)) { + const listener = () => { + const time = performance.now(); + for (const handler of containerHandlers) handler.measure(); + for (const handler of containerHandlers) handler.update(time); + for (const handler of containerHandlers) handler.notify(); + }; + scrollListeners.set(container, listener); + const target = getEventTarget(container); + window.addEventListener("resize", listener, { + passive: true, + }); + if (container !== document.documentElement) { + resizeListeners.set( + container, + (0, _indexEs.resize)(container, listener) + ); + } + target.addEventListener("scroll", listener, { + passive: true, + }); + } + const listener = scrollListeners.get(container); + const onLoadProcesss = requestAnimationFrame(listener); + return () => { + var _a; + if (typeof onScroll !== "function") onScroll.stop(); + cancelAnimationFrame(onLoadProcesss); + /** + * Check if we even have any handlers for this container. + */ + const containerHandlers = onScrollHandlers.get(container); + if (!containerHandlers) return; + containerHandlers.delete(containerHandler); + if (containerHandlers.size) return; + /** + * If no more handlers, remove the scroll listener too. + */ + const listener = scrollListeners.get(container); + scrollListeners.delete(container); + if (listener) { + getEventTarget(container).removeEventListener("scroll", listener); + (_a = resizeListeners.get(container)) === null || _a === void 0 + ? void 0 + : _a(); + window.removeEventListener("resize", listener); + } + }; + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.cubicBezier = cubicBezier; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -/* - Bezier function generator + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js ***! + \****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createScrollInfo = void 0; + exports.updateScrollInfo = updateScrollInfo; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + /** + * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + */ + const maxElapsed = 50; + const createAxisInfo = () => ({ + current: 0, + offset: [], + progress: 0, + scrollLength: 0, + targetOffset: 0, + targetLength: 0, + containerLength: 0, + velocity: 0, + }); + const createScrollInfo = () => ({ + time: 0, + x: createAxisInfo(), + y: createAxisInfo(), + }); + exports.createScrollInfo = createScrollInfo; + const keys = { + x: { + length: "Width", + position: "Left", + }, + y: { + length: "Height", + position: "Top", + }, + }; + function updateAxisInfo(element, axisName, info, time) { + const axis = info[axisName]; + const { length, position } = keys[axisName]; + const prev = axis.current; + const prevTime = info.time; + axis.current = element["scroll" + position]; + axis.scrollLength = + element["scroll" + length] - element["client" + length]; + axis.offset.length = 0; + axis.offset[0] = 0; + axis.offset[1] = axis.scrollLength; + axis.progress = (0, _utils.progress)( + 0, + axis.scrollLength, + axis.current + ); + const elapsed = time - prevTime; + axis.velocity = + elapsed > maxElapsed + ? 0 + : (0, _utils.velocityPerSecond)(axis.current - prev, elapsed); + } + function updateScrollInfo(element, info, time) { + updateAxisInfo(element, "x", info, time); + updateAxisInfo(element, "y", info, time); + info.time = time; + } - This has been modified from Gaëtan Renaudeau's BezierEasing - https://github.com/gre/bezier-easing/blob/master/src/index.js - https://github.com/gre/bezier-easing/blob/master/LICENSE - - I've removed the newtonRaphsonIterate algo because in benchmarking it - wasn't noticiably faster than binarySubdivision, indeed removing it - usually improved times, depending on the curve. - - I also removed the lookup table, as for the added bundle size and loop we're - only cutting ~4 or so subdivision iterations. I bumped the max iterations up - to 12 to compensate and this still tended to be faster for no perceivable - loss in accuracy. - - Usage - const easeOut = cubicBezier(.17,.67,.83,.67); - const x = easeOut(0.5); // returns 0.627... -*/ -// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. -const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) * t; -const subdivisionPrecision = 0.0000001; -const subdivisionMaxIterations = 12; -function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { - let currentX; - let currentT; - let i = 0; - do { - currentT = lowerBound + (upperBound - lowerBound) / 2.0; - currentX = calcBezier(currentT, mX1, mX2) - x; - if (currentX > 0.0) { - upperBound = currentT; - } else { - lowerBound = currentT; - } - } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); - return currentT; -} -function cubicBezier(mX1, mY1, mX2, mY2) { - // If this is a linear gradient, return linear easing - if (mX1 === mY1 && mX2 === mY2) return _utils.noopReturn; - const getTForX = aX => binarySubdivide(aX, 0, 1, mX1, mX2); - // If animation is at start/end, return t without easing - return t => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/easing/dist/index.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/index.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js": + /*!************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js ***! + \************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.namedEdges = void 0; + exports.resolveEdge = resolveEdge; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + const namedEdges = (exports.namedEdges = { + start: 0, + center: 0.5, + end: 1, + }); + function resolveEdge(edge, length, inset = 0) { + let delta = 0; + /** + * If we have this edge defined as a preset, replace the definition + * with the numerical value. + */ + if (namedEdges[edge] !== undefined) { + edge = namedEdges[edge]; + } + /** + * Handle unit values + */ + if ((0, _utils.isString)(edge)) { + const asNumber = parseFloat(edge); + if (edge.endsWith("px")) { + delta = asNumber; + } else if (edge.endsWith("%")) { + edge = asNumber / 100; + } else if (edge.endsWith("vw")) { + delta = (asNumber / 100) * document.documentElement.clientWidth; + } else if (edge.endsWith("vh")) { + delta = (asNumber / 100) * document.documentElement.clientHeight; + } else { + edge = asNumber; + } + } + /** + * If the edge is defined as a number, handle as a progress value. + */ + if ((0, _utils.isNumber)(edge)) { + delta = length * edge; + } + return inset + delta; + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "cubicBezier", ({ - enumerable: true, - get: function () { - return _cubicBezierEs.cubicBezier; - } -})); -Object.defineProperty(exports, "steps", ({ - enumerable: true, - get: function () { - return _stepsEs.steps; - } -})); -var _cubicBezierEs = __webpack_require__(/*! ./cubic-bezier.es.js */ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js"); -var _stepsEs = __webpack_require__(/*! ./steps.es.js */ "../../../node_modules/@motionone/easing/dist/steps.es.js"); + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js ***! + \*************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resolveOffsets = resolveOffsets; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _insetEs = __webpack_require__( + /*! ./inset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js" + ); + var _presetsEs = __webpack_require__( + /*! ./presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js" + ); + var _offsetEs = __webpack_require__( + /*! ./offset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js" + ); + const point = { + x: 0, + y: 0, + }; + function resolveOffsets(container, info, options) { + let { offset: offsetDefinition = _presetsEs.ScrollOffset.All } = + options; + const { target = container, axis = "y" } = options; + const lengthLabel = axis === "y" ? "height" : "width"; + const inset = + target !== container + ? (0, _insetEs.calcInset)(target, container) + : point; + /** + * Measure the target and container. If they're the same thing then we + * use the container's scrollWidth/Height as the target, from there + * all other calculations can remain the same. + */ + const targetSize = + target === container + ? { + width: container.scrollWidth, + height: container.scrollHeight, + } + : { + width: target.clientWidth, + height: target.clientHeight, + }; + const containerSize = { + width: container.clientWidth, + height: container.clientHeight, + }; + /** + * Reset the length of the resolved offset array rather than creating a new one. + * TODO: More reusable data structures for targetSize/containerSize would also be good. + */ + info[axis].offset.length = 0; + /** + * Populate the offset array by resolving the user's offset definition into + * a list of pixel scroll offets. + */ + let hasChanged = !info[axis].interpolate; + const numOffsets = offsetDefinition.length; + for (let i = 0; i < numOffsets; i++) { + const offset = (0, _offsetEs.resolveOffset)( + offsetDefinition[i], + containerSize[lengthLabel], + targetSize[lengthLabel], + inset[axis] + ); + if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { + hasChanged = true; + } + info[axis].offset[i] = offset; + } + /** + * If the pixel scroll offsets have changed, create a new interpolator function + * to map scroll value into a progress. + */ + if (hasChanged) { + info[axis].interpolate = (0, _utils.interpolate)( + (0, _utils.defaultOffset)(numOffsets), + info[axis].offset + ); + info[axis].interpolatorOffsets = [...info[axis].offset]; + } + info[axis].progress = info[axis].interpolate(info[axis].current); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/easing/dist/steps.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/steps.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js ***! + \*************************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.calcInset = calcInset; + function calcInset(element, container) { + let inset = { + x: 0, + y: 0, + }; + let current = element; + while (current && current !== container) { + if (current instanceof HTMLElement) { + inset.x += current.offsetLeft; + inset.y += current.offsetTop; + current = current.offsetParent; + } else if ( + current instanceof SVGGraphicsElement && + "getBBox" in current + ) { + const { top, left } = current.getBBox(); + inset.x += left; + inset.y += top; + /** + * Assign the next parent element as the tag. + */ + while (current && current.tagName !== "svg") { + current = current.parentNode; + } + } + } + return inset; + } + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js ***! + \**************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resolveOffset = resolveOffset; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _edgeEs = __webpack_require__( + /*! ./edge.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js" + ); + const defaultOffset = [0, 0]; + function resolveOffset( + offset, + containerLength, + targetLength, + targetInset + ) { + let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; + let targetPoint = 0; + let containerPoint = 0; + if ((0, _utils.isNumber)(offset)) { + /** + * If we're provided offset: [0, 0.5, 1] then each number x should become + * [x, x], so we default to the behaviour of mapping 0 => 0 of both target + * and container etc. + */ + offsetDefinition = [offset, offset]; + } else if ((0, _utils.isString)(offset)) { + offset = offset.trim(); + if (offset.includes(" ")) { + offsetDefinition = offset.split(" "); + } else { + /** + * If we're provided a definition like "100px" then we want to apply + * that only to the top of the target point, leaving the container at 0. + * Whereas a named offset like "end" should be applied to both. + */ + offsetDefinition = [ + offset, + _edgeEs.namedEdges[offset] ? offset : `0`, + ]; + } + } + targetPoint = (0, _edgeEs.resolveEdge)( + offsetDefinition[0], + targetLength, + targetInset + ); + containerPoint = (0, _edgeEs.resolveEdge)( + offsetDefinition[1], + containerLength + ); + return targetPoint - containerPoint; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.steps = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const steps = (steps, direction = "end") => progress => { - progress = direction === "end" ? Math.min(progress, 0.999) : Math.max(progress, 0.001); - const expanded = progress * steps; - const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded); - return (0, _utils.clamp)(0, 1, rounded / steps); -}; -exports.steps = steps; + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js": + /*!***************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js ***! + \***************************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.ScrollOffset = void 0; + const ScrollOffset = (exports.ScrollOffset = { + Enter: [ + [0, 1], + [1, 1], + ], + Exit: [ + [0, 0], + [1, 0], + ], + Any: [ + [1, 0], + [0, 1], + ], + All: [ + [0, 0], + [1, 1], + ], + }); -/***/ "../../../node_modules/@motionone/generators/dist/glide/index.es.js": -/*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/glide/index.es.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.glide = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _velocityEs = __webpack_require__(/*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js"); -var _indexEs = __webpack_require__(/*! ../spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js"); -const glide = ({ - from = 0, - velocity = 0.0, - power = 0.8, - decay = 0.325, - bounceDamping, - bounceStiffness, - changeTarget, - min, - max, - restDistance = 0.5, - restSpeed -}) => { - decay = _utils.time.ms(decay); - const state = { - hasReachedTarget: false, - done: false, - current: from, - target: from - }; - const isOutOfBounds = v => min !== undefined && v < min || max !== undefined && v > max; - const nearestBoundary = v => { - if (min === undefined) return max; - if (max === undefined) return min; - return Math.abs(min - v) < Math.abs(max - v) ? min : max; - }; - let amplitude = power * velocity; - const ideal = from + amplitude; - const target = changeTarget === undefined ? ideal : changeTarget(ideal); - state.target = target; - /** - * If the target has changed we need to re-calculate the amplitude, otherwise - * the animation will start from the wrong position. - */ - if (target !== ideal) amplitude = target - from; - const calcDelta = t => -amplitude * Math.exp(-t / decay); - const calcLatest = t => target + calcDelta(t); - const applyFriction = t => { - const delta = calcDelta(t); - const latest = calcLatest(t); - state.done = Math.abs(delta) <= restDistance; - state.current = state.done ? target : latest; - }; - /** - * Ideally this would resolve for t in a stateless way, we could - * do that by always precalculating the animation but as we know - * this will be done anyway we can assume that spring will - * be discovered during that. - */ - let timeReachedBoundary; - let spring$1; - const checkCatchBoundary = t => { - if (!isOutOfBounds(state.current)) return; - timeReachedBoundary = t; - spring$1 = (0, _indexEs.spring)({ - from: state.current, - to: nearestBoundary(state.current), - velocity: (0, _velocityEs.calcGeneratorVelocity)(calcLatest, t, state.current), - damping: bounceDamping, - stiffness: bounceStiffness, - restDistance, - restSpeed - }); - }; - checkCatchBoundary(0); - return t => { - /** - * We need to resolve the friction to figure out if we need a - * spring but we don't want to do this twice per frame. So here - * we flag if we updated for this frame and later if we did - * we can skip doing it again. - */ - let hasUpdatedFrame = false; - if (!spring$1 && timeReachedBoundary === undefined) { - hasUpdatedFrame = true; - applyFriction(t); - checkCatchBoundary(t); - } - /** - * If we have a spring and the provided t is beyond the moment the friction - * animation crossed the min/max boundary, use the spring. - */ - if (timeReachedBoundary !== undefined && t > timeReachedBoundary) { - state.hasReachedTarget = true; - return spring$1(t - timeReachedBoundary); - } else { - state.hasReachedTarget = false; - !hasUpdatedFrame && applyFriction(t); - return state; - } - }; -}; -exports.glide = glide; + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js": + /*!*****************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js ***! + \*****************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createOnScrollHandler = createOnScrollHandler; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _infoEs = __webpack_require__( + /*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js" + ); + var _indexEs = __webpack_require__( + /*! ./offsets/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js" + ); + function measure(container, target = container, info) { + /** + * Find inset of target within scrollable container + */ + info.x.targetOffset = 0; + info.y.targetOffset = 0; + if (target !== container) { + let node = target; + while (node && node != container) { + info.x.targetOffset += node.offsetLeft; + info.y.targetOffset += node.offsetTop; + node = node.offsetParent; + } + } + info.x.targetLength = + target === container ? target.scrollWidth : target.clientWidth; + info.y.targetLength = + target === container ? target.scrollHeight : target.clientHeight; + info.x.containerLength = container.clientWidth; + info.y.containerLength = container.clientHeight; + } + function createOnScrollHandler(element, onScroll, info, options = {}) { + const axis = options.axis || "y"; + return { + measure: () => measure(element, options.target, info), + update: (time) => { + (0, _infoEs.updateScrollInfo)(element, info, time); + if (options.offset || options.target) { + (0, _indexEs.resolveOffsets)(element, info, options); + } + }, + notify: + typeof onScroll === "function" + ? () => onScroll(info) + : scrubAnimation(onScroll, info[axis]), + }; + } + function scrubAnimation(controls, axisInfo) { + controls.pause(); + controls.forEachNative((animation, { easing }) => { + var _a, _b; + if (animation.updateDuration) { + if (!easing) animation.easing = _utils.noopReturn; + animation.updateDuration(1); + } else { + const timingOptions = { + duration: 1000, + }; + if (!easing) timingOptions.easing = "linear"; + (_b = + (_a = animation.effect) === null || _a === void 0 + ? void 0 + : _a.updateTiming) === null || _b === void 0 + ? void 0 + : _b.call(_a, timingOptions); + } + }); + return () => { + controls.currentTime = axisInfo.progress; + }; + } -/***/ "../../../node_modules/@motionone/generators/dist/index.es.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/index.es.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/index.es.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/index.es.js ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "ScrollOffset", { + enumerable: true, + get: function () { + return _presetsEs.ScrollOffset; + }, + }); + Object.defineProperty(exports, "animate", { + enumerable: true, + get: function () { + return _indexEs.animate; + }, + }); + Object.defineProperty(exports, "animateStyle", { + enumerable: true, + get: function () { + return _animateStyleEs.animateStyle; + }, + }); + Object.defineProperty(exports, "createMotionState", { + enumerable: true, + get: function () { + return _indexEs7.createMotionState; + }, + }); + Object.defineProperty(exports, "createStyleString", { + enumerable: true, + get: function () { + return _styleStringEs.createStyleString; + }, + }); + Object.defineProperty(exports, "createStyles", { + enumerable: true, + get: function () { + return _styleObjectEs.createStyles; + }, + }); + Object.defineProperty(exports, "getAnimationData", { + enumerable: true, + get: function () { + return _dataEs.getAnimationData; + }, + }); + Object.defineProperty(exports, "getStyleName", { + enumerable: true, + get: function () { + return _getStyleNameEs.getStyleName; + }, + }); + Object.defineProperty(exports, "glide", { + enumerable: true, + get: function () { + return _indexEs4.glide; + }, + }); + Object.defineProperty(exports, "inView", { + enumerable: true, + get: function () { + return _inViewEs.inView; + }, + }); + Object.defineProperty(exports, "mountedStates", { + enumerable: true, + get: function () { + return _indexEs7.mountedStates; + }, + }); + Object.defineProperty(exports, "resize", { + enumerable: true, + get: function () { + return _indexEs5.resize; + }, + }); + Object.defineProperty(exports, "scroll", { + enumerable: true, + get: function () { + return _indexEs6.scroll; + }, + }); + Object.defineProperty(exports, "spring", { + enumerable: true, + get: function () { + return _indexEs3.spring; + }, + }); + Object.defineProperty(exports, "stagger", { + enumerable: true, + get: function () { + return _staggerEs.stagger; + }, + }); + Object.defineProperty(exports, "style", { + enumerable: true, + get: function () { + return _styleEs.style; + }, + }); + Object.defineProperty(exports, "timeline", { + enumerable: true, + get: function () { + return _indexEs2.timeline; + }, + }); + Object.defineProperty(exports, "withControls", { + enumerable: true, + get: function () { + return _controlsEs.withControls; + }, + }); + var _indexEs = __webpack_require__( + /*! ./animate/index.es.js */ "../../../node_modules/@motionone/dom/dist/animate/index.es.js" + ); + var _animateStyleEs = __webpack_require__( + /*! ./animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" + ); + var _indexEs2 = __webpack_require__( + /*! ./timeline/index.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js" + ); + var _staggerEs = __webpack_require__( + /*! ./utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js" + ); + var _indexEs3 = __webpack_require__( + /*! ./easing/spring/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js" + ); + var _indexEs4 = __webpack_require__( + /*! ./easing/glide/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js" + ); + var _styleEs = __webpack_require__( + /*! ./animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js" + ); + var _inViewEs = __webpack_require__( + /*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js" + ); + var _indexEs5 = __webpack_require__( + /*! ./gestures/resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js" + ); + var _indexEs6 = __webpack_require__( + /*! ./gestures/scroll/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js" + ); + var _presetsEs = __webpack_require__( + /*! ./gestures/scroll/offsets/presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js" + ); + var _controlsEs = __webpack_require__( + /*! ./animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js" + ); + var _dataEs = __webpack_require__( + /*! ./animate/data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js" + ); + var _getStyleNameEs = __webpack_require__( + /*! ./animate/utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js" + ); + var _indexEs7 = __webpack_require__( + /*! ./state/index.es.js */ "../../../node_modules/@motionone/dom/dist/state/index.es.js" + ); + var _styleObjectEs = __webpack_require__( + /*! ./animate/utils/style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js" + ); + var _styleStringEs = __webpack_require__( + /*! ./animate/utils/style-string.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js" + ); + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "calcGeneratorVelocity", ({ - enumerable: true, - get: function () { - return _velocityEs.calcGeneratorVelocity; - } -})); -Object.defineProperty(exports, "glide", ({ - enumerable: true, - get: function () { - return _indexEs.glide; - } -})); -Object.defineProperty(exports, "pregenerateKeyframes", ({ - enumerable: true, - get: function () { - return _pregenerateKeyframesEs.pregenerateKeyframes; - } -})); -Object.defineProperty(exports, "spring", ({ - enumerable: true, - get: function () { - return _indexEs2.spring; - } -})); -var _indexEs = __webpack_require__(/*! ./glide/index.es.js */ "../../../node_modules/@motionone/generators/dist/glide/index.es.js"); -var _indexEs2 = __webpack_require__(/*! ./spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js"); -var _pregenerateKeyframesEs = __webpack_require__(/*! ./utils/pregenerate-keyframes.es.js */ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js"); -var _velocityEs = __webpack_require__(/*! ./utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js"); + /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js ***! + \****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.hover = void 0; + var _eventsEs = __webpack_require__( + /*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" + ); + const mouseEvent = (element, name, action) => (event) => { + if (event.pointerType && event.pointerType !== "mouse") return; + action(); + (0, _eventsEs.dispatchPointerEvent)(element, name, event); + }; + const hover = (exports.hover = { + isActive: (options) => Boolean(options.hover), + subscribe: (element, { enable, disable }) => { + const onEnter = mouseEvent(element, "hoverstart", enable); + const onLeave = mouseEvent(element, "hoverend", disable); + element.addEventListener("pointerenter", onEnter); + element.addEventListener("pointerleave", onLeave); + return () => { + element.removeEventListener("pointerenter", onEnter); + element.removeEventListener("pointerleave", onLeave); + }; + }, + }); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/defaults.es.js ***! + /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js ***! \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.inView = void 0; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var _eventsEs = __webpack_require__( + /*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" + ); + var _inViewEs = __webpack_require__( + /*! ../../gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js" + ); + const inView = (exports.inView = { + isActive: (options) => Boolean(options.inView), + subscribe: (element, { enable, disable }, { inViewOptions = {} }) => { + const { once } = inViewOptions, + viewOptions = (0, _tslib.__rest)(inViewOptions, ["once"]); + return (0, _inViewEs.inView)( + element, + (enterEntry) => { + enable(); + (0, _eventsEs.dispatchViewEvent)( + element, + "viewenter", + enterEntry + ); + if (!once) { + return (leaveEntry) => { + disable(); + (0, _eventsEs.dispatchViewEvent)( + element, + "viewleave", + leaveEntry + ); + }; + } + }, + viewOptions + ); + }, + }); + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaults = void 0; -const defaults = exports.defaults = { - stiffness: 100.0, - damping: 10.0, - mass: 1.0 -}; - -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js ***! + \****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.press = void 0; + var _eventsEs = __webpack_require__( + /*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" + ); + const press = (exports.press = { + isActive: (options) => Boolean(options.press), + subscribe: (element, { enable, disable }) => { + const onPointerUp = (event) => { + disable(); + (0, _eventsEs.dispatchPointerEvent)(element, "pressend", event); + window.removeEventListener("pointerup", onPointerUp); + }; + const onPointerDown = (event) => { + enable(); + (0, _eventsEs.dispatchPointerEvent)(element, "pressstart", event); + window.addEventListener("pointerup", onPointerUp); + }; + element.addEventListener("pointerdown", onPointerDown); + return () => { + element.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerup", onPointerUp); + }; + }, + }); -/***/ "../../../node_modules/@motionone/generators/dist/spring/index.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/index.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.spring = void 0; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -var _defaultsEs = __webpack_require__(/*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js"); -var _utilsEs = __webpack_require__(/*! ./utils.es.js */ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js"); -var _hasReachedTargetEs = __webpack_require__(/*! ../utils/has-reached-target.es.js */ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js"); -var _velocityEs = __webpack_require__(/*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js"); -const spring = ({ - stiffness = _defaultsEs.defaults.stiffness, - damping = _defaultsEs.defaults.damping, - mass = _defaultsEs.defaults.mass, - from = 0, - to = 1, - velocity = 0.0, - restSpeed = 2, - restDistance = 0.5 -} = {}) => { - velocity = velocity ? _utils.time.s(velocity) : 0.0; - const state = { - done: false, - hasReachedTarget: false, - current: from, - target: to - }; - const initialDelta = to - from; - const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; - const dampingRatio = (0, _utilsEs.calcDampingRatio)(stiffness, damping, mass); - let resolveSpring; - if (dampingRatio < 1) { - const angularFreq = undampedAngularFreq * Math.sqrt(1 - dampingRatio * dampingRatio); - // Underdamped spring (bouncy) - resolveSpring = t => to - Math.exp(-dampingRatio * undampedAngularFreq * t) * ((-velocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); - } else { - // Critically damped spring - resolveSpring = t => { - return to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (-velocity + undampedAngularFreq * initialDelta) * t); - }; - } - return t => { - state.current = resolveSpring(t); - const currentVelocity = t === 0 ? velocity : (0, _velocityEs.calcGeneratorVelocity)(resolveSpring, t, state.current); - const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; - const isBelowDisplacementThreshold = Math.abs(to - state.current) <= restDistance; - state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold; - state.hasReachedTarget = (0, _hasReachedTargetEs.hasReachedTarget)(from, to, state.current); - return state; - }; -}; -exports.spring = spring; + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/state/index.es.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/index.es.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createMotionState = createMotionState; + exports.mountedStates = void 0; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var _heyListen = __webpack_require__( + /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" + ); + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _animateStyleEs = __webpack_require__( + /*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" + ); + var _styleEs = __webpack_require__( + /*! ../animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js" + ); + var _optionsEs = __webpack_require__( + /*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js" + ); + var _hasChangedEs = __webpack_require__( + /*! ./utils/has-changed.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js" + ); + var _resolveVariantEs = __webpack_require__( + /*! ./utils/resolve-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js" + ); + var _scheduleEs = __webpack_require__( + /*! ./utils/schedule.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js" + ); + var _inViewEs = __webpack_require__( + /*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js" + ); + var _hoverEs = __webpack_require__( + /*! ./gestures/hover.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js" + ); + var _pressEs = __webpack_require__( + /*! ./gestures/press.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js" + ); + var _eventsEs = __webpack_require__( + /*! ./utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" + ); + const gestures = { + inView: _inViewEs.inView, + hover: _hoverEs.hover, + press: _pressEs.press, + }; + /** + * A list of state types, in priority order. If a value is defined in + * a righter-most type, it will override any definition in a lefter-most. + */ + const stateTypes = [ + "initial", + "animate", + ...Object.keys(gestures), + "exit", + ]; + /** + * A global store of all generated motion states. This can be used to lookup + * a motion state for a given Element. + */ + const mountedStates = (exports.mountedStates = new WeakMap()); + function createMotionState(options = {}, parent) { + /** + * The element represented by the motion state. This is an empty reference + * when we create the state to support SSR and allow for later mounting + * in view libraries. + * + * @ts-ignore + */ + let element; + /** + * Calculate a depth that we can use to order motion states by tree depth. + */ + let depth = parent ? parent.getDepth() + 1 : 0; + /** + * Track which states are currently active. + */ + const activeStates = { + initial: true, + animate: true, + }; + /** + * A map of functions that, when called, will remove event listeners for + * a given gesture. + */ + const gestureSubscriptions = {}; + /** + * Initialise a context to share through motion states. This + * will be populated by variant names (if any). + */ + const context = {}; + for (const name of stateTypes) { + context[name] = + typeof options[name] === "string" + ? options[name] + : parent === null || parent === void 0 + ? void 0 + : parent.getContext()[name]; + } + /** + * If initial is set to false we use the animate prop as the initial + * animation state. + */ + const initialVariantSource = + options.initial === false ? "animate" : "initial"; + /** + * Destructure an initial target out from the resolved initial variant. + */ + let _a = + (0, _resolveVariantEs.resolveVariant)( + options[initialVariantSource] || context[initialVariantSource], + options.variants + ) || {}, + target = (0, _tslib.__rest)(_a, ["transition"]); + /** + * The base target is a cached map of values that we'll use to animate + * back to if a value is removed from all active state types. This + * is usually the initial value as read from the DOM, for instance if + * it hasn't been defined in initial. + */ + const baseTarget = Object.assign({}, target); + /** + * A generator that will be processed by the global animation scheduler. + * This yeilds when it switches from reading the DOM to writing to it + * to prevent layout thrashing. + */ + function* animateUpdates() { + var _a, _b; + const prevTarget = target; + target = {}; + const animationOptions = {}; + for (const name of stateTypes) { + if (!activeStates[name]) continue; + const variant = (0, _resolveVariantEs.resolveVariant)( + options[name] + ); + if (!variant) continue; + for (const key in variant) { + if (key === "transition") continue; + target[key] = variant[key]; + animationOptions[key] = (0, _optionsEs.getOptions)( + (_b = + (_a = variant.transition) !== null && _a !== void 0 + ? _a + : options.transition) !== null && _b !== void 0 + ? _b + : {}, + key + ); + } + } + const allTargetKeys = new Set([ + ...Object.keys(target), + ...Object.keys(prevTarget), + ]); + const animationFactories = []; + allTargetKeys.forEach((key) => { + var _a; + if (target[key] === undefined) { + target[key] = baseTarget[key]; + } + if ((0, _hasChangedEs.hasChanged)(prevTarget[key], target[key])) { + (_a = baseTarget[key]) !== null && _a !== void 0 + ? _a + : (baseTarget[key] = _styleEs.style.get(element, key)); + animationFactories.push( + (0, _animateStyleEs.animateStyle)( + element, + key, + target[key], + animationOptions[key] + ) + ); + } + }); + // Wait for all animation states to read from the DOM + yield; + const animations = animationFactories + .map((factory) => factory()) + .filter(Boolean); + if (!animations.length) return; + const animationTarget = target; + element.dispatchEvent( + (0, _eventsEs.motionEvent)("motionstart", animationTarget) + ); + Promise.all(animations.map((animation) => animation.finished)) + .then(() => { + element.dispatchEvent( + (0, _eventsEs.motionEvent)("motioncomplete", animationTarget) + ); + }) + .catch(_utils.noop); + } + const setGesture = (name, isActive) => () => { + activeStates[name] = isActive; + (0, _scheduleEs.scheduleAnimation)(state); + }; + const updateGestureSubscriptions = () => { + for (const name in gestures) { + const isGestureActive = gestures[name].isActive(options); + const remove = gestureSubscriptions[name]; + if (isGestureActive && !remove) { + gestureSubscriptions[name] = gestures[name].subscribe( + element, + { + enable: setGesture(name, true), + disable: setGesture(name, false), + }, + options + ); + } else if (!isGestureActive && remove) { + remove(); + delete gestureSubscriptions[name]; + } + } + }; + const state = { + update: (newOptions) => { + if (!element) return; + options = newOptions; + updateGestureSubscriptions(); + (0, _scheduleEs.scheduleAnimation)(state); + }, + setActive: (name, isActive) => { + if (!element) return; + activeStates[name] = isActive; + (0, _scheduleEs.scheduleAnimation)(state); + }, + animateUpdates, + getDepth: () => depth, + getTarget: () => target, + getOptions: () => options, + getContext: () => context, + mount: (newElement) => { + (0, _heyListen.invariant)( + Boolean(newElement), + "Animation state must be mounted with valid Element" + ); + element = newElement; + mountedStates.set(element, state); + updateGestureSubscriptions(); + return () => { + mountedStates.delete(element); + (0, _scheduleEs.unscheduleAnimation)(state); + for (const key in gestureSubscriptions) { + gestureSubscriptions[key](); + } + }; + }, + isMounted: () => Boolean(element), + }; + return state; + } -/***/ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/utils.es.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/events.es.js ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.dispatchPointerEvent = dispatchPointerEvent; + exports.dispatchViewEvent = dispatchViewEvent; + exports.motionEvent = void 0; + const motionEvent = (name, target) => + new CustomEvent(name, { + detail: { + target, + }, + }); + exports.motionEvent = motionEvent; + function dispatchPointerEvent(element, name, event) { + element.dispatchEvent( + new CustomEvent(name, { + detail: { + originalEvent: event, + }, + }) + ); + } + function dispatchViewEvent(element, name, entry) { + element.dispatchEvent( + new CustomEvent(name, { + detail: { + originalEntry: entry, + }, + }) + ); + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcDampingRatio = void 0; -var _defaultsEs = __webpack_require__(/*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js"); -const calcDampingRatio = (stiffness = _defaultsEs.defaults.stiffness, damping = _defaultsEs.defaults.damping, mass = _defaultsEs.defaults.mass) => damping / (2 * Math.sqrt(stiffness * mass)); -exports.calcDampingRatio = calcDampingRatio; + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js": + /*!*******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js ***! + \*******************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.hasChanged = hasChanged; + exports.shallowCompare = shallowCompare; + function hasChanged(a, b) { + if (typeof a !== typeof b) return true; + if (Array.isArray(a) && Array.isArray(b)) + return !shallowCompare(a, b); + return a !== b; + } + function shallowCompare(next, prev) { + const prevLength = prev.length; + if (prevLength !== next.length) return false; + for (let i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) return false; + } + return true; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js": -/*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js ***! - \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js ***! + \******************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isVariant = isVariant; + function isVariant(definition) { + return typeof definition === "object"; + } + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js ***! + \***********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resolveVariant = resolveVariant; + var _isVariantEs = __webpack_require__( + /*! ./is-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js" + ); + function resolveVariant(definition, variants) { + if ((0, _isVariantEs.isVariant)(definition)) { + return definition; + } else if (definition && variants) { + return variants[definition]; + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.hasReachedTarget = hasReachedTarget; -function hasReachedTarget(origin, target, current) { - return origin < target && current >= target || origin > target && current <= target; -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js ***! + \****************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.scheduleAnimation = scheduleAnimation; + exports.unscheduleAnimation = unscheduleAnimation; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + let scheduled = undefined; + function processScheduledAnimations() { + if (!scheduled) return; + const generators = scheduled + .sort(compareByDepth) + .map(fireAnimateUpdates); + generators.forEach(fireNext); + generators.forEach(fireNext); + scheduled = undefined; + } + function scheduleAnimation(state) { + if (!scheduled) { + scheduled = [state]; + requestAnimationFrame(processScheduledAnimations); + } else { + (0, _utils.addUniqueItem)(scheduled, state); + } + } + function unscheduleAnimation(state) { + scheduled && (0, _utils.removeItem)(scheduled, state); + } + const compareByDepth = (a, b) => a.getDepth() - b.getDepth(); + const fireAnimateUpdates = (state) => state.animateUpdates(); + const fireNext = (iterator) => iterator.next(); -/***/ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js": -/*!******************************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js ***! - \******************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.pregenerateKeyframes = pregenerateKeyframes; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const timeStep = 10; -const maxDuration = 10000; -function pregenerateKeyframes(generator, toUnit = _utils.noopReturn) { - let overshootDuration = undefined; - let timestamp = timeStep; - let state = generator(0); - const keyframes = [toUnit(state.current)]; - while (!state.done && timestamp < maxDuration) { - state = generator(timestamp); - keyframes.push(toUnit(state.done ? state.target : state.current)); - if (overshootDuration === undefined && state.hasReachedTarget) { - overshootDuration = timestamp; - } - timestamp += timeStep; - } - const duration = timestamp - timeStep; - /** - * If generating an animation that didn't actually move, - * generate a second keyframe so we have an origin and target. - */ - if (keyframes.length === 1) keyframes.push(state.current); - return { - keyframes, - duration: duration / 1000, - overshootDuration: (overshootDuration !== null && overshootDuration !== void 0 ? overshootDuration : duration) / 1000 - }; -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js": + /*!**********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/timeline/index.es.js ***! + \**********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createAnimationsFromTimeline = createAnimationsFromTimeline; + exports.timeline = timeline; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var _heyListen = __webpack_require__( + /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" + ); + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _staggerEs = __webpack_require__( + /*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js" + ); + var _animateStyleEs = __webpack_require__( + /*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" + ); + var _controlsEs = __webpack_require__( + /*! ../animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js" + ); + var _keyframesEs = __webpack_require__( + /*! ../animate/utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js" + ); + var _optionsEs = __webpack_require__( + /*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js" + ); + var _resolveElementsEs = __webpack_require__( + /*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" + ); + var _transformsEs = __webpack_require__( + /*! ../animate/utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" + ); + var _calcTimeEs = __webpack_require__( + /*! ./utils/calc-time.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js" + ); + var _editEs = __webpack_require__( + /*! ./utils/edit.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js" + ); + var _sortEs = __webpack_require__( + /*! ./utils/sort.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js" + ); + function timeline(definition, options = {}) { + var _a; + const animationDefinitions = createAnimationsFromTimeline( + definition, + options + ); + /** + * Create and start animations + */ + const animationFactories = animationDefinitions + .map((definition) => + (0, _animateStyleEs.animateStyle)(...definition) + ) + .filter(Boolean); + return (0, _controlsEs.withControls)( + animationFactories, + options, + // Get the duration from the first animation definition + (_a = animationDefinitions[0]) === null || _a === void 0 + ? void 0 + : _a[3].duration + ); + } + function createAnimationsFromTimeline(definition, _a = {}) { + var { defaultOptions = {} } = _a, + timelineOptions = (0, _tslib.__rest)(_a, ["defaultOptions"]); + const animationDefinitions = []; + const elementSequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the definition array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < definition.length; i++) { + const segment = definition[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if ((0, _utils.isString)(segment)) { + timeLabels.set(segment, currentTime); + continue; + } else if (!Array.isArray(segment)) { + timeLabels.set( + segment.name, + (0, _calcTimeEs.calcNextTime)( + currentTime, + segment.at, + prevTime, + timeLabels + ) + ); + continue; + } + const [elementDefinition, keyframes, options = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (options.at !== undefined) { + currentTime = (0, _calcTimeEs.calcNextTime)( + currentTime, + options.at, + prevTime, + timeLabels + ); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + /** + * Find all the elements specified in the definition and parse value + * keyframes from their timeline definitions. + */ + const elements = (0, _resolveElementsEs.resolveElements)( + elementDefinition, + elementCache + ); + const numElements = elements.length; + for ( + let elementIndex = 0; + elementIndex < numElements; + elementIndex++ + ) { + const element = elements[elementIndex]; + const elementSequence = getElementSequence( + element, + elementSequences + ); + for (const key in keyframes) { + const valueSequence = getValueSequence(key, elementSequence); + let valueKeyframes = (0, _keyframesEs.keyframesList)( + keyframes[key] + ); + const valueOptions = (0, _optionsEs.getOptions)(options, key); + let { + duration = defaultOptions.duration || + _utils.defaults.duration, + easing = defaultOptions.easing || _utils.defaults.easing, + } = valueOptions; + if ((0, _utils.isEasingGenerator)(easing)) { + const valueIsTransform = (0, _transformsEs.isTransform)(key); + (0, _heyListen.invariant)( + valueKeyframes.length === 2 || !valueIsTransform, + "spring must be provided 2 keyframes within timeline" + ); + const custom = easing.createAnimation( + valueKeyframes, + // TODO We currently only support explicit keyframes + // so this doesn't currently read from the DOM + () => "0", + valueIsTransform + ); + easing = custom.easing; + if (custom.keyframes !== undefined) + valueKeyframes = custom.keyframes; + if (custom.duration !== undefined) duration = custom.duration; + } + const delay = + (0, _staggerEs.resolveOption)( + options.delay, + elementIndex, + numElements + ) || 0; + const startTime = currentTime + delay; + const targetTime = startTime + duration; + /** + * + */ + let { + offset = (0, _utils.defaultOffset)(valueKeyframes.length), + } = valueOptions; + /** + * If there's only one offset of 0, fill in a second with length 1 + * + * TODO: Ensure there's a test that covers this removal + */ + if (offset.length === 1 && offset[0] === 0) { + offset[1] = 1; + } + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = length - valueKeyframes.length; + remainder > 0 && (0, _utils.fillOffset)(offset, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframes.length === 1 && valueKeyframes.unshift(null); + /** + * Add keyframes, mapping offsets to absolute time. + */ + (0, _editEs.addKeyframes)( + valueSequence, + valueKeyframes, + easing, + offset, + startTime, + targetTime + ); + maxDuration = Math.max(delay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); + } + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + elementSequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; + /** + * Arrange all the keyframes in ascending time order. + */ + valueSequence.sort(_sortEs.compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; + /** + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. + */ + for (let i = 0; i < valueSequence.length; i++) { + const { at, value, easing } = valueSequence[i]; + keyframes.push(value); + valueOffset.push((0, _utils.progress)(0, totalDuration, at)); + valueEasing.push(easing || _utils.defaults.easing); + } + /** + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. + */ + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift("linear"); + } + /** + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. + */ + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); + } + animationDefinitions.push([ + element, + key, + keyframes, + Object.assign( + Object.assign(Object.assign({}, defaultOptions), { + duration: totalDuration, + easing: valueEasing, + offset: valueOffset, + }), + timelineOptions + ), + ]); + } + }); + return animationDefinitions; + } + function getElementSequence(element, sequences) { + !sequences.has(element) && sequences.set(element, {}); + return sequences.get(element); + } + function getValueSequence(name, sequences) { + if (!sequences[name]) sequences[name] = []; + return sequences[name]; + } -/***/ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/velocity.es.js ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js": + /*!********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js ***! + \********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.calcNextTime = calcNextTime; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + function calcNextTime(current, next, prev, labels) { + var _a; + if ((0, _utils.isNumber)(next)) { + return next; + } else if (next.startsWith("-") || next.startsWith("+")) { + return Math.max(0, current + parseFloat(next)); + } else if (next === "<") { + return prev; + } else { + return (_a = labels.get(next)) !== null && _a !== void 0 + ? _a + : current; + } + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.calcGeneratorVelocity = calcGeneratorVelocity; -var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); -const sampleT = 5; // ms -function calcGeneratorVelocity(resolveValue, t, current) { - const prevT = Math.max(t - sampleT, 0); - return (0, _utils.velocityPerSecond)(current - resolveValue(prevT), t - prevT); -} + /***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.addKeyframes = addKeyframes; + exports.eraseKeyframes = eraseKeyframes; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + function eraseKeyframes(sequence, startTime, endTime) { + for (let i = 0; i < sequence.length; i++) { + const keyframe = sequence[i]; + if (keyframe.at > startTime && keyframe.at < endTime) { + (0, _utils.removeItem)(sequence, keyframe); + // If we remove this item we have to push the pointer back one + i--; + } + } + } + function addKeyframes( + sequence, + keyframes, + easing, + offset, + startTime, + endTime + ) { + /** + * Erase every existing value between currentTime and targetTime, + * this will essentially splice this timeline into any currently + * defined ones. + */ + eraseKeyframes(sequence, startTime, endTime); + for (let i = 0; i < keyframes.length; i++) { + sequence.push({ + value: keyframes[i], + at: (0, _utils.mix)(startTime, endTime, offset[i]), + easing: (0, _utils.getEasingForSegment)(easing, i), + }); + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/types/dist/MotionValue.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/types/dist/MotionValue.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.MotionValue = void 0; -/** - * The MotionValue tracks the state of a single animatable - * value. Currently, updatedAt and current are unused. The - * long term idea is to use this to minimise the number - * of DOM reads, and to abstract the DOM interactions here. - */ -class MotionValue { - setAnimation(animation) { - this.animation = animation; - animation === null || animation === void 0 ? void 0 : animation.finished.then(() => this.clearAnimation()).catch(() => {}); - } - clearAnimation() { - this.animation = this.generator = undefined; - } -} -exports.MotionValue = MotionValue; + /***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.compareByTime = compareByTime; + function compareByTime(a, b) { + if (a.at === b.at) { + return a.value === null ? 1 : -1; + } else { + return a.at - b.at; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/types/dist/index.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/types/dist/index.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js ***! + \******************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.resolveElements = resolveElements; + function resolveElements(elements, selectorCache) { + var _a; + if (typeof elements === "string") { + if (selectorCache) { + (_a = selectorCache[elements]) !== null && _a !== void 0 + ? _a + : (selectorCache[elements] = + document.querySelectorAll(elements)); + elements = selectorCache[elements]; + } else { + elements = document.querySelectorAll(elements); + } + } else if (elements instanceof Element) { + elements = [elements]; + } + /** + * Return an empty array + */ + return Array.from(elements || []); + } + /***/ + }, + /***/ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/utils/stagger.es.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getFromIndex = getFromIndex; + exports.resolveOption = resolveOption; + exports.stagger = stagger; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _animation = __webpack_require__( + /*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js" + ); + function stagger(duration = 0.1, { start = 0, from = 0, easing } = {}) { + return (i, total) => { + const fromIndex = (0, _utils.isNumber)(from) + ? from + : getFromIndex(from, total); + const distance = Math.abs(fromIndex - i); + let delay = duration * distance; + if (easing) { + const maxDelay = total * duration; + const easingFunction = (0, _animation.getEasingFunction)(easing); + delay = easingFunction(delay / maxDelay) * maxDelay; + } + return start + delay; + }; + } + function getFromIndex(from, total) { + if (from === "first") { + return 0; + } else { + const lastIndex = total - 1; + return from === "last" ? lastIndex : lastIndex / 2; + } + } + function resolveOption(option, i, total) { + return typeof option === "function" ? option(i, total) : option; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "MotionValue", ({ - enumerable: true, - get: function () { - return _MotionValueEs.MotionValue; - } -})); -var _MotionValueEs = __webpack_require__(/*! ./MotionValue.es.js */ "../../../node_modules/@motionone/types/dist/MotionValue.es.js"); + /***/ + }, -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/array.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/array.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.addUniqueItem = addUniqueItem; -exports.removeItem = removeItem; -function addUniqueItem(array, item) { - array.indexOf(item) === -1 && array.push(item); -} -function removeItem(arr, item) { - const index = arr.indexOf(item); - index > -1 && arr.splice(index, 1); -} - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/clamp.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/clamp.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.clamp = void 0; -const clamp = (min, max, v) => Math.min(Math.max(v, min), max); -exports.clamp = clamp; + /***/ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js ***! + \***********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.cubicBezier = cubicBezier; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + /* + Bezier function generator -/***/ }), + This has been modified from Gaëtan Renaudeau's BezierEasing + https://github.com/gre/bezier-easing/blob/master/src/index.js + https://github.com/gre/bezier-easing/blob/master/LICENSE + + I've removed the newtonRaphsonIterate algo because in benchmarking it + wasn't noticiably faster than binarySubdivision, indeed removing it + usually improved times, depending on the curve. -/***/ "../../../node_modules/@motionone/utils/dist/defaults.es.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/defaults.es.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + I also removed the lookup table, as for the added bundle size and loop we're + only cutting ~4 or so subdivision iterations. I bumped the max iterations up + to 12 to compensate and this still tended to be faster for no perceivable + loss in accuracy. + Usage + const easeOut = cubicBezier(.17,.67,.83,.67); + const x = easeOut(0.5); // returns 0.627... +*/ + // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. + const calcBezier = (t, a1, a2) => + (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + + 3.0 * a1) * + t; + const subdivisionPrecision = 0.0000001; + const subdivisionMaxIterations = 12; + function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { + let currentX; + let currentT; + let i = 0; + do { + currentT = lowerBound + (upperBound - lowerBound) / 2.0; + currentX = calcBezier(currentT, mX1, mX2) - x; + if (currentX > 0.0) { + upperBound = currentT; + } else { + lowerBound = currentT; + } + } while ( + Math.abs(currentX) > subdivisionPrecision && + ++i < subdivisionMaxIterations + ); + return currentT; + } + function cubicBezier(mX1, mY1, mX2, mY2) { + // If this is a linear gradient, return linear easing + if (mX1 === mY1 && mX2 === mY2) return _utils.noopReturn; + const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2); + // If animation is at start/end, return t without easing + return (t) => + t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaults = void 0; -const defaults = exports.defaults = { - duration: 0.3, - delay: 0, - endDelay: 0, - repeat: 0, - easing: "ease" -}; + /***/ "../../../node_modules/@motionone/easing/dist/index.es.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/@motionone/easing/dist/index.es.js ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "cubicBezier", { + enumerable: true, + get: function () { + return _cubicBezierEs.cubicBezier; + }, + }); + Object.defineProperty(exports, "steps", { + enumerable: true, + get: function () { + return _stepsEs.steps; + }, + }); + var _cubicBezierEs = __webpack_require__( + /*! ./cubic-bezier.es.js */ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js" + ); + var _stepsEs = __webpack_require__( + /*! ./steps.es.js */ "../../../node_modules/@motionone/easing/dist/steps.es.js" + ); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/easing.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/easing.es.js ***! + /***/ "../../../node_modules/@motionone/easing/dist/steps.es.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/@motionone/easing/dist/steps.es.js ***! \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.steps = void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + const steps = + (steps, direction = "end") => + (progress) => { + progress = + direction === "end" + ? Math.min(progress, 0.999) + : Math.max(progress, 0.001); + const expanded = progress * steps; + const rounded = + direction === "end" ? Math.floor(expanded) : Math.ceil(expanded); + return (0, _utils.clamp)(0, 1, rounded / steps); + }; + exports.steps = steps; + /***/ + }, + /***/ "../../../node_modules/@motionone/generators/dist/glide/index.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/glide/index.es.js ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.glide = void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _velocityEs = __webpack_require__( + /*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js" + ); + var _indexEs = __webpack_require__( + /*! ../spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js" + ); + const glide = ({ + from = 0, + velocity = 0.0, + power = 0.8, + decay = 0.325, + bounceDamping, + bounceStiffness, + changeTarget, + min, + max, + restDistance = 0.5, + restSpeed, + }) => { + decay = _utils.time.ms(decay); + const state = { + hasReachedTarget: false, + done: false, + current: from, + target: from, + }; + const isOutOfBounds = (v) => + (min !== undefined && v < min) || (max !== undefined && v > max); + const nearestBoundary = (v) => { + if (min === undefined) return max; + if (max === undefined) return min; + return Math.abs(min - v) < Math.abs(max - v) ? min : max; + }; + let amplitude = power * velocity; + const ideal = from + amplitude; + const target = + changeTarget === undefined ? ideal : changeTarget(ideal); + state.target = target; + /** + * If the target has changed we need to re-calculate the amplitude, otherwise + * the animation will start from the wrong position. + */ + if (target !== ideal) amplitude = target - from; + const calcDelta = (t) => -amplitude * Math.exp(-t / decay); + const calcLatest = (t) => target + calcDelta(t); + const applyFriction = (t) => { + const delta = calcDelta(t); + const latest = calcLatest(t); + state.done = Math.abs(delta) <= restDistance; + state.current = state.done ? target : latest; + }; + /** + * Ideally this would resolve for t in a stateless way, we could + * do that by always precalculating the animation but as we know + * this will be done anyway we can assume that spring will + * be discovered during that. + */ + let timeReachedBoundary; + let spring$1; + const checkCatchBoundary = (t) => { + if (!isOutOfBounds(state.current)) return; + timeReachedBoundary = t; + spring$1 = (0, _indexEs.spring)({ + from: state.current, + to: nearestBoundary(state.current), + velocity: (0, _velocityEs.calcGeneratorVelocity)( + calcLatest, + t, + state.current + ), + damping: bounceDamping, + stiffness: bounceStiffness, + restDistance, + restSpeed, + }); + }; + checkCatchBoundary(0); + return (t) => { + /** + * We need to resolve the friction to figure out if we need a + * spring but we don't want to do this twice per frame. So here + * we flag if we updated for this frame and later if we did + * we can skip doing it again. + */ + let hasUpdatedFrame = false; + if (!spring$1 && timeReachedBoundary === undefined) { + hasUpdatedFrame = true; + applyFriction(t); + checkCatchBoundary(t); + } + /** + * If we have a spring and the provided t is beyond the moment the friction + * animation crossed the min/max boundary, use the spring. + */ + if (timeReachedBoundary !== undefined && t > timeReachedBoundary) { + state.hasReachedTarget = true; + return spring$1(t - timeReachedBoundary); + } else { + state.hasReachedTarget = false; + !hasUpdatedFrame && applyFriction(t); + return state; + } + }; + }; + exports.glide = glide; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getEasingForSegment = getEasingForSegment; -var _isEasingListEs = __webpack_require__(/*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js"); -var _wrapEs = __webpack_require__(/*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js"); -function getEasingForSegment(easing, i) { - return (0, _isEasingListEs.isEasingList)(easing) ? easing[(0, _wrapEs.wrap)(0, easing.length, i)] : easing; -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/generators/dist/index.es.js": + /*!********************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/index.es.js ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "calcGeneratorVelocity", { + enumerable: true, + get: function () { + return _velocityEs.calcGeneratorVelocity; + }, + }); + Object.defineProperty(exports, "glide", { + enumerable: true, + get: function () { + return _indexEs.glide; + }, + }); + Object.defineProperty(exports, "pregenerateKeyframes", { + enumerable: true, + get: function () { + return _pregenerateKeyframesEs.pregenerateKeyframes; + }, + }); + Object.defineProperty(exports, "spring", { + enumerable: true, + get: function () { + return _indexEs2.spring; + }, + }); + var _indexEs = __webpack_require__( + /*! ./glide/index.es.js */ "../../../node_modules/@motionone/generators/dist/glide/index.es.js" + ); + var _indexEs2 = __webpack_require__( + /*! ./spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js" + ); + var _pregenerateKeyframesEs = __webpack_require__( + /*! ./utils/pregenerate-keyframes.es.js */ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js" + ); + var _velocityEs = __webpack_require__( + /*! ./utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js" + ); -/***/ "../../../node_modules/@motionone/utils/dist/index.es.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/index.es.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + /***/ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/spring/defaults.es.js ***! + \******************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.defaults = void 0; + const defaults = (exports.defaults = { + stiffness: 100.0, + damping: 10.0, + mass: 1.0, + }); + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "addUniqueItem", ({ - enumerable: true, - get: function () { - return _arrayEs.addUniqueItem; - } -})); -Object.defineProperty(exports, "clamp", ({ - enumerable: true, - get: function () { - return _clampEs.clamp; - } -})); -Object.defineProperty(exports, "defaultOffset", ({ - enumerable: true, - get: function () { - return _offsetEs.defaultOffset; - } -})); -Object.defineProperty(exports, "defaults", ({ - enumerable: true, - get: function () { - return _defaultsEs.defaults; - } -})); -Object.defineProperty(exports, "fillOffset", ({ - enumerable: true, - get: function () { - return _offsetEs.fillOffset; - } -})); -Object.defineProperty(exports, "getEasingForSegment", ({ - enumerable: true, - get: function () { - return _easingEs.getEasingForSegment; - } -})); -Object.defineProperty(exports, "interpolate", ({ - enumerable: true, - get: function () { - return _interpolateEs.interpolate; - } -})); -Object.defineProperty(exports, "isCubicBezier", ({ - enumerable: true, - get: function () { - return _isCubicBezierEs.isCubicBezier; - } -})); -Object.defineProperty(exports, "isEasingGenerator", ({ - enumerable: true, - get: function () { - return _isEasingGeneratorEs.isEasingGenerator; - } -})); -Object.defineProperty(exports, "isEasingList", ({ - enumerable: true, - get: function () { - return _isEasingListEs.isEasingList; - } -})); -Object.defineProperty(exports, "isFunction", ({ - enumerable: true, - get: function () { - return _isFunctionEs.isFunction; - } -})); -Object.defineProperty(exports, "isNumber", ({ - enumerable: true, - get: function () { - return _isNumberEs.isNumber; - } -})); -Object.defineProperty(exports, "isString", ({ - enumerable: true, - get: function () { - return _isStringEs.isString; - } -})); -Object.defineProperty(exports, "mix", ({ - enumerable: true, - get: function () { - return _mixEs.mix; - } -})); -Object.defineProperty(exports, "noop", ({ - enumerable: true, - get: function () { - return _noopEs.noop; - } -})); -Object.defineProperty(exports, "noopReturn", ({ - enumerable: true, - get: function () { - return _noopEs.noopReturn; - } -})); -Object.defineProperty(exports, "progress", ({ - enumerable: true, - get: function () { - return _progressEs.progress; - } -})); -Object.defineProperty(exports, "removeItem", ({ - enumerable: true, - get: function () { - return _arrayEs.removeItem; - } -})); -Object.defineProperty(exports, "time", ({ - enumerable: true, - get: function () { - return _timeEs.time; - } -})); -Object.defineProperty(exports, "velocityPerSecond", ({ - enumerable: true, - get: function () { - return _velocityEs.velocityPerSecond; - } -})); -Object.defineProperty(exports, "wrap", ({ - enumerable: true, - get: function () { - return _wrapEs.wrap; - } -})); -var _arrayEs = __webpack_require__(/*! ./array.es.js */ "../../../node_modules/@motionone/utils/dist/array.es.js"); -var _clampEs = __webpack_require__(/*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js"); -var _defaultsEs = __webpack_require__(/*! ./defaults.es.js */ "../../../node_modules/@motionone/utils/dist/defaults.es.js"); -var _easingEs = __webpack_require__(/*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js"); -var _interpolateEs = __webpack_require__(/*! ./interpolate.es.js */ "../../../node_modules/@motionone/utils/dist/interpolate.es.js"); -var _isCubicBezierEs = __webpack_require__(/*! ./is-cubic-bezier.es.js */ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js"); -var _isEasingGeneratorEs = __webpack_require__(/*! ./is-easing-generator.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js"); -var _isEasingListEs = __webpack_require__(/*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js"); -var _isFunctionEs = __webpack_require__(/*! ./is-function.es.js */ "../../../node_modules/@motionone/utils/dist/is-function.es.js"); -var _isNumberEs = __webpack_require__(/*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js"); -var _isStringEs = __webpack_require__(/*! ./is-string.es.js */ "../../../node_modules/@motionone/utils/dist/is-string.es.js"); -var _mixEs = __webpack_require__(/*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js"); -var _noopEs = __webpack_require__(/*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js"); -var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js"); -var _progressEs = __webpack_require__(/*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js"); -var _timeEs = __webpack_require__(/*! ./time.es.js */ "../../../node_modules/@motionone/utils/dist/time.es.js"); -var _velocityEs = __webpack_require__(/*! ./velocity.es.js */ "../../../node_modules/@motionone/utils/dist/velocity.es.js"); -var _wrapEs = __webpack_require__(/*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js"); - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/interpolate.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/interpolate.es.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.interpolate = interpolate; -var _mixEs = __webpack_require__(/*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js"); -var _noopEs = __webpack_require__(/*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js"); -var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js"); -var _progressEs = __webpack_require__(/*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js"); -var _easingEs = __webpack_require__(/*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js"); -var _clampEs = __webpack_require__(/*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js"); -function interpolate(output, input = (0, _offsetEs.defaultOffset)(output.length), easing = _noopEs.noopReturn) { - const length = output.length; - /** - * If the input length is lower than the output we - * fill the input to match. This currently assumes the input - * is an animation progress value so is a good candidate for - * moving outside the function. - */ - const remainder = length - input.length; - remainder > 0 && (0, _offsetEs.fillOffset)(input, remainder); - return t => { - let i = 0; - for (; i < length - 2; i++) { - if (t < input[i + 1]) break; - } - let progressInRange = (0, _clampEs.clamp)(0, 1, (0, _progressEs.progress)(input[i], input[i + 1], t)); - const segmentEasing = (0, _easingEs.getEasingForSegment)(easing, i); - progressInRange = segmentEasing(progressInRange); - return (0, _mixEs.mix)(output[i], output[i + 1], progressInRange); - }; -} + /***/ "../../../node_modules/@motionone/generators/dist/spring/index.es.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/spring/index.es.js ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.spring = void 0; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + var _defaultsEs = __webpack_require__( + /*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js" + ); + var _utilsEs = __webpack_require__( + /*! ./utils.es.js */ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js" + ); + var _hasReachedTargetEs = __webpack_require__( + /*! ../utils/has-reached-target.es.js */ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js" + ); + var _velocityEs = __webpack_require__( + /*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js" + ); + const spring = ({ + stiffness = _defaultsEs.defaults.stiffness, + damping = _defaultsEs.defaults.damping, + mass = _defaultsEs.defaults.mass, + from = 0, + to = 1, + velocity = 0.0, + restSpeed = 2, + restDistance = 0.5, + } = {}) => { + velocity = velocity ? _utils.time.s(velocity) : 0.0; + const state = { + done: false, + hasReachedTarget: false, + current: from, + target: to, + }; + const initialDelta = to - from; + const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; + const dampingRatio = (0, _utilsEs.calcDampingRatio)( + stiffness, + damping, + mass + ); + let resolveSpring; + if (dampingRatio < 1) { + const angularFreq = + undampedAngularFreq * Math.sqrt(1 - dampingRatio * dampingRatio); + // Underdamped spring (bouncy) + resolveSpring = (t) => + to - + Math.exp(-dampingRatio * undampedAngularFreq * t) * + (((-velocity + + dampingRatio * undampedAngularFreq * initialDelta) / + angularFreq) * + Math.sin(angularFreq * t) + + initialDelta * Math.cos(angularFreq * t)); + } else { + // Critically damped spring + resolveSpring = (t) => { + return ( + to - + Math.exp(-undampedAngularFreq * t) * + (initialDelta + + (-velocity + undampedAngularFreq * initialDelta) * t) + ); + }; + } + return (t) => { + state.current = resolveSpring(t); + const currentVelocity = + t === 0 + ? velocity + : (0, _velocityEs.calcGeneratorVelocity)( + resolveSpring, + t, + state.current + ); + const isBelowVelocityThreshold = + Math.abs(currentVelocity) <= restSpeed; + const isBelowDisplacementThreshold = + Math.abs(to - state.current) <= restDistance; + state.done = + isBelowVelocityThreshold && isBelowDisplacementThreshold; + state.hasReachedTarget = (0, _hasReachedTargetEs.hasReachedTarget)( + from, + to, + state.current + ); + return state; + }; + }; + exports.spring = spring; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js": -/*!*************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js ***! - \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/spring/utils.es.js ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.calcDampingRatio = void 0; + var _defaultsEs = __webpack_require__( + /*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js" + ); + const calcDampingRatio = ( + stiffness = _defaultsEs.defaults.stiffness, + damping = _defaultsEs.defaults.damping, + mass = _defaultsEs.defaults.mass + ) => damping / (2 * Math.sqrt(stiffness * mass)); + exports.calcDampingRatio = calcDampingRatio; + + /***/ + }, + /***/ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js": + /*!***************************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js ***! + \***************************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.hasReachedTarget = hasReachedTarget; + function hasReachedTarget(origin, target, current) { + return ( + (origin < target && current >= target) || + (origin > target && current <= target) + ); + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isCubicBezier = void 0; -var _isNumberEs = __webpack_require__(/*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js"); -const isCubicBezier = easing => Array.isArray(easing) && (0, _isNumberEs.isNumber)(easing[0]); -exports.isCubicBezier = isCubicBezier; + /***/ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js": + /*!******************************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js ***! + \******************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.pregenerateKeyframes = pregenerateKeyframes; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + const timeStep = 10; + const maxDuration = 10000; + function pregenerateKeyframes(generator, toUnit = _utils.noopReturn) { + let overshootDuration = undefined; + let timestamp = timeStep; + let state = generator(0); + const keyframes = [toUnit(state.current)]; + while (!state.done && timestamp < maxDuration) { + state = generator(timestamp); + keyframes.push(toUnit(state.done ? state.target : state.current)); + if (overshootDuration === undefined && state.hasReachedTarget) { + overshootDuration = timestamp; + } + timestamp += timeStep; + } + const duration = timestamp - timeStep; + /** + * If generating an animation that didn't actually move, + * generate a second keyframe so we have an origin and target. + */ + if (keyframes.length === 1) keyframes.push(state.current); + return { + keyframes, + duration: duration / 1000, + overshootDuration: + (overshootDuration !== null && overshootDuration !== void 0 + ? overshootDuration + : duration) / 1000, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js ***! + /***/ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/generators/dist/utils/velocity.es.js ***! \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isEasingGenerator = void 0; -const isEasingGenerator = easing => typeof easing === "object" && Boolean(easing.createAnimation); -exports.isEasingGenerator = isEasingGenerator; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-easing-list.es.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isEasingList = void 0; -var _isNumberEs = __webpack_require__(/*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js"); -const isEasingList = easing => Array.isArray(easing) && !(0, _isNumberEs.isNumber)(easing[0]); -exports.isEasingList = isEasingList; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.calcGeneratorVelocity = calcGeneratorVelocity; + var _utils = __webpack_require__( + /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" + ); + const sampleT = 5; // ms + function calcGeneratorVelocity(resolveValue, t, current) { + const prevT = Math.max(t - sampleT, 0); + return (0, _utils.velocityPerSecond)( + current - resolveValue(prevT), + t - prevT + ); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/is-function.es.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-function.es.js ***! + /***/ "../../../node_modules/@motionone/types/dist/MotionValue.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/types/dist/MotionValue.es.js ***! \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isFunction = void 0; -const isFunction = value => typeof value === "function"; -exports.isFunction = isFunction; - -/***/ }), - -/***/ "../../../node_modules/@motionone/utils/dist/is-number.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-number.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.MotionValue = void 0; + /** + * The MotionValue tracks the state of a single animatable + * value. Currently, updatedAt and current are unused. The + * long term idea is to use this to minimise the number + * of DOM reads, and to abstract the DOM interactions here. + */ + class MotionValue { + setAnimation(animation) { + this.animation = animation; + animation === null || animation === void 0 + ? void 0 + : animation.finished + .then(() => this.clearAnimation()) + .catch(() => {}); + } + clearAnimation() { + this.animation = this.generator = undefined; + } + } + exports.MotionValue = MotionValue; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isNumber = void 0; -const isNumber = value => typeof value === "number"; -exports.isNumber = isNumber; + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/types/dist/index.es.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/@motionone/types/dist/index.es.js ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "MotionValue", { + enumerable: true, + get: function () { + return _MotionValueEs.MotionValue; + }, + }); + var _MotionValueEs = __webpack_require__( + /*! ./MotionValue.es.js */ "../../../node_modules/@motionone/types/dist/MotionValue.es.js" + ); -/***/ "../../../node_modules/@motionone/utils/dist/is-string.es.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-string.es.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ + }, + /***/ "../../../node_modules/@motionone/utils/dist/array.es.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/array.es.js ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.addUniqueItem = addUniqueItem; + exports.removeItem = removeItem; + function addUniqueItem(array, item) { + array.indexOf(item) === -1 && array.push(item); + } + function removeItem(arr, item) { + const index = arr.indexOf(item); + index > -1 && arr.splice(index, 1); + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isString = void 0; -const isString = value => typeof value === "string"; -exports.isString = isString; + /***/ "../../../node_modules/@motionone/utils/dist/clamp.es.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/clamp.es.js ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.clamp = void 0; + const clamp = (min, max, v) => Math.min(Math.max(v, min), max); + exports.clamp = clamp; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/mix.es.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/mix.es.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ "../../../node_modules/@motionone/utils/dist/defaults.es.js": + /*!******************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/defaults.es.js ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.defaults = void 0; + const defaults = (exports.defaults = { + duration: 0.3, + delay: 0, + endDelay: 0, + repeat: 0, + easing: "ease", + }); + /***/ + }, + /***/ "../../../node_modules/@motionone/utils/dist/easing.es.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/easing.es.js ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getEasingForSegment = getEasingForSegment; + var _isEasingListEs = __webpack_require__( + /*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js" + ); + var _wrapEs = __webpack_require__( + /*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js" + ); + function getEasingForSegment(easing, i) { + return (0, _isEasingListEs.isEasingList)(easing) + ? easing[(0, _wrapEs.wrap)(0, easing.length, i)] + : easing; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.mix = void 0; -const mix = (min, max, progress) => -progress * min + progress * max + min; -exports.mix = mix; + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/utils/dist/index.es.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/index.es.js ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "addUniqueItem", { + enumerable: true, + get: function () { + return _arrayEs.addUniqueItem; + }, + }); + Object.defineProperty(exports, "clamp", { + enumerable: true, + get: function () { + return _clampEs.clamp; + }, + }); + Object.defineProperty(exports, "defaultOffset", { + enumerable: true, + get: function () { + return _offsetEs.defaultOffset; + }, + }); + Object.defineProperty(exports, "defaults", { + enumerable: true, + get: function () { + return _defaultsEs.defaults; + }, + }); + Object.defineProperty(exports, "fillOffset", { + enumerable: true, + get: function () { + return _offsetEs.fillOffset; + }, + }); + Object.defineProperty(exports, "getEasingForSegment", { + enumerable: true, + get: function () { + return _easingEs.getEasingForSegment; + }, + }); + Object.defineProperty(exports, "interpolate", { + enumerable: true, + get: function () { + return _interpolateEs.interpolate; + }, + }); + Object.defineProperty(exports, "isCubicBezier", { + enumerable: true, + get: function () { + return _isCubicBezierEs.isCubicBezier; + }, + }); + Object.defineProperty(exports, "isEasingGenerator", { + enumerable: true, + get: function () { + return _isEasingGeneratorEs.isEasingGenerator; + }, + }); + Object.defineProperty(exports, "isEasingList", { + enumerable: true, + get: function () { + return _isEasingListEs.isEasingList; + }, + }); + Object.defineProperty(exports, "isFunction", { + enumerable: true, + get: function () { + return _isFunctionEs.isFunction; + }, + }); + Object.defineProperty(exports, "isNumber", { + enumerable: true, + get: function () { + return _isNumberEs.isNumber; + }, + }); + Object.defineProperty(exports, "isString", { + enumerable: true, + get: function () { + return _isStringEs.isString; + }, + }); + Object.defineProperty(exports, "mix", { + enumerable: true, + get: function () { + return _mixEs.mix; + }, + }); + Object.defineProperty(exports, "noop", { + enumerable: true, + get: function () { + return _noopEs.noop; + }, + }); + Object.defineProperty(exports, "noopReturn", { + enumerable: true, + get: function () { + return _noopEs.noopReturn; + }, + }); + Object.defineProperty(exports, "progress", { + enumerable: true, + get: function () { + return _progressEs.progress; + }, + }); + Object.defineProperty(exports, "removeItem", { + enumerable: true, + get: function () { + return _arrayEs.removeItem; + }, + }); + Object.defineProperty(exports, "time", { + enumerable: true, + get: function () { + return _timeEs.time; + }, + }); + Object.defineProperty(exports, "velocityPerSecond", { + enumerable: true, + get: function () { + return _velocityEs.velocityPerSecond; + }, + }); + Object.defineProperty(exports, "wrap", { + enumerable: true, + get: function () { + return _wrapEs.wrap; + }, + }); + var _arrayEs = __webpack_require__( + /*! ./array.es.js */ "../../../node_modules/@motionone/utils/dist/array.es.js" + ); + var _clampEs = __webpack_require__( + /*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js" + ); + var _defaultsEs = __webpack_require__( + /*! ./defaults.es.js */ "../../../node_modules/@motionone/utils/dist/defaults.es.js" + ); + var _easingEs = __webpack_require__( + /*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js" + ); + var _interpolateEs = __webpack_require__( + /*! ./interpolate.es.js */ "../../../node_modules/@motionone/utils/dist/interpolate.es.js" + ); + var _isCubicBezierEs = __webpack_require__( + /*! ./is-cubic-bezier.es.js */ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js" + ); + var _isEasingGeneratorEs = __webpack_require__( + /*! ./is-easing-generator.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js" + ); + var _isEasingListEs = __webpack_require__( + /*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js" + ); + var _isFunctionEs = __webpack_require__( + /*! ./is-function.es.js */ "../../../node_modules/@motionone/utils/dist/is-function.es.js" + ); + var _isNumberEs = __webpack_require__( + /*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js" + ); + var _isStringEs = __webpack_require__( + /*! ./is-string.es.js */ "../../../node_modules/@motionone/utils/dist/is-string.es.js" + ); + var _mixEs = __webpack_require__( + /*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js" + ); + var _noopEs = __webpack_require__( + /*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js" + ); + var _offsetEs = __webpack_require__( + /*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js" + ); + var _progressEs = __webpack_require__( + /*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js" + ); + var _timeEs = __webpack_require__( + /*! ./time.es.js */ "../../../node_modules/@motionone/utils/dist/time.es.js" + ); + var _velocityEs = __webpack_require__( + /*! ./velocity.es.js */ "../../../node_modules/@motionone/utils/dist/velocity.es.js" + ); + var _wrapEs = __webpack_require__( + /*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js" + ); -/***/ "../../../node_modules/@motionone/utils/dist/noop.es.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/noop.es.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ + }, + + /***/ "../../../node_modules/@motionone/utils/dist/interpolate.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/interpolate.es.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.interpolate = interpolate; + var _mixEs = __webpack_require__( + /*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js" + ); + var _noopEs = __webpack_require__( + /*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js" + ); + var _offsetEs = __webpack_require__( + /*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js" + ); + var _progressEs = __webpack_require__( + /*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js" + ); + var _easingEs = __webpack_require__( + /*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js" + ); + var _clampEs = __webpack_require__( + /*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js" + ); + function interpolate( + output, + input = (0, _offsetEs.defaultOffset)(output.length), + easing = _noopEs.noopReturn + ) { + const length = output.length; + /** + * If the input length is lower than the output we + * fill the input to match. This currently assumes the input + * is an animation progress value so is a good candidate for + * moving outside the function. + */ + const remainder = length - input.length; + remainder > 0 && (0, _offsetEs.fillOffset)(input, remainder); + return (t) => { + let i = 0; + for (; i < length - 2; i++) { + if (t < input[i + 1]) break; + } + let progressInRange = (0, _clampEs.clamp)( + 0, + 1, + (0, _progressEs.progress)(input[i], input[i + 1], t) + ); + const segmentEasing = (0, _easingEs.getEasingForSegment)(easing, i); + progressInRange = segmentEasing(progressInRange); + return (0, _mixEs.mix)(output[i], output[i + 1], progressInRange); + }; + } + + /***/ + }, + + /***/ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js": + /*!*************************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js ***! + \*************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isCubicBezier = void 0; + var _isNumberEs = __webpack_require__( + /*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js" + ); + const isCubicBezier = (easing) => + Array.isArray(easing) && (0, _isNumberEs.isNumber)(easing[0]); + exports.isCubicBezier = isCubicBezier; + /***/ + }, + /***/ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js ***! + \*****************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isEasingGenerator = void 0; + const isEasingGenerator = (easing) => + typeof easing === "object" && Boolean(easing.createAnimation); + exports.isEasingGenerator = isEasingGenerator; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.noopReturn = exports.noop = void 0; -const noop = () => {}; -exports.noop = noop; -const noopReturn = v => v; -exports.noopReturn = noopReturn; + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/is-easing-list.es.js ***! + \************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isEasingList = void 0; + var _isNumberEs = __webpack_require__( + /*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js" + ); + const isEasingList = (easing) => + Array.isArray(easing) && !(0, _isNumberEs.isNumber)(easing[0]); + exports.isEasingList = isEasingList; -/***/ "../../../node_modules/@motionone/utils/dist/offset.es.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/offset.es.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaultOffset = defaultOffset; -exports.fillOffset = fillOffset; -var _mixEs = __webpack_require__(/*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js"); -var _progressEs = __webpack_require__(/*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js"); -function fillOffset(offset, remaining) { - const min = offset[offset.length - 1]; - for (let i = 1; i <= remaining; i++) { - const offsetProgress = (0, _progressEs.progress)(0, remaining, i); - offset.push((0, _mixEs.mix)(min, 1, offsetProgress)); - } -} -function defaultOffset(length) { - const offset = [0]; - fillOffset(offset, length - 1); - return offset; -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@motionone/utils/dist/is-function.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/is-function.es.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isFunction = void 0; + const isFunction = (value) => typeof value === "function"; + exports.isFunction = isFunction; -/***/ "../../../node_modules/@motionone/utils/dist/progress.es.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/progress.es.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ + }, + /***/ "../../../node_modules/@motionone/utils/dist/is-number.es.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/is-number.es.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isNumber = void 0; + const isNumber = (value) => typeof value === "number"; + exports.isNumber = isNumber; + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.progress = void 0; -const progress = (min, max, value) => max - min === 0 ? 1 : (value - min) / (max - min); -exports.progress = progress; + /***/ "../../../node_modules/@motionone/utils/dist/is-string.es.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/is-string.es.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isString = void 0; + const isString = (value) => typeof value === "string"; + exports.isString = isString; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/time.es.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/time.es.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ "../../../node_modules/@motionone/utils/dist/mix.es.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/mix.es.js ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.mix = void 0; + const mix = (min, max, progress) => + -progress * min + progress * max + min; + exports.mix = mix; + /***/ + }, + /***/ "../../../node_modules/@motionone/utils/dist/noop.es.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/noop.es.js ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.noopReturn = exports.noop = void 0; + const noop = () => {}; + exports.noop = noop; + const noopReturn = (v) => v; + exports.noopReturn = noopReturn; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.time = void 0; -const time = exports.time = { - ms: seconds => seconds * 1000, - s: milliseconds => milliseconds / 1000 -}; + /***/ + }, + + /***/ "../../../node_modules/@motionone/utils/dist/offset.es.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/offset.es.js ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.defaultOffset = defaultOffset; + exports.fillOffset = fillOffset; + var _mixEs = __webpack_require__( + /*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js" + ); + var _progressEs = __webpack_require__( + /*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js" + ); + function fillOffset(offset, remaining) { + const min = offset[offset.length - 1]; + for (let i = 1; i <= remaining; i++) { + const offsetProgress = (0, _progressEs.progress)(0, remaining, i); + offset.push((0, _mixEs.mix)(min, 1, offsetProgress)); + } + } + function defaultOffset(length) { + const offset = [0]; + fillOffset(offset, length - 1); + return offset; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/velocity.es.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/velocity.es.js ***! + /***/ "../../../node_modules/@motionone/utils/dist/progress.es.js": + /*!******************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/progress.es.js ***! \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.progress = void 0; + const progress = (min, max, value) => + max - min === 0 ? 1 : (value - min) / (max - min); + exports.progress = progress; + + /***/ + }, + /***/ "../../../node_modules/@motionone/utils/dist/time.es.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/time.es.js ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.time = void 0; + const time = (exports.time = { + ms: (seconds) => seconds * 1000, + s: (milliseconds) => milliseconds / 1000, + }); + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.velocityPerSecond = velocityPerSecond; -/* + /***/ "../../../node_modules/@motionone/utils/dist/velocity.es.js": + /*!******************************************************************!*\ + !*** ../../../node_modules/@motionone/utils/dist/velocity.es.js ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.velocityPerSecond = velocityPerSecond; + /* Convert velocity into velocity per second @param [number]: Unit per frame @param [number]: Frame duration in ms */ -function velocityPerSecond(velocity, frameDuration) { - return frameDuration ? velocity * (1000 / frameDuration) : 0; -} + function velocityPerSecond(velocity, frameDuration) { + return frameDuration ? velocity * (1000 / frameDuration) : 0; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@motionone/utils/dist/wrap.es.js": -/*!**************************************************************!*\ + /***/ "../../../node_modules/@motionone/utils/dist/wrap.es.js": + /*!**************************************************************!*\ !*** ../../../node_modules/@motionone/utils/dist/wrap.es.js ***! \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.wrap = void 0; -const wrap = (min, max, v) => { - const rangeSize = max - min; - return ((v - min) % rangeSize + rangeSize) % rangeSize + min; -}; -exports.wrap = wrap; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.wrap = void 0; + const wrap = (min, max, v) => { + const rangeSize = max - min; + return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min; + }; + exports.wrap = wrap; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js": -/*!********************************************************************************!*\ + /***/ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js": + /*!********************************************************************************!*\ !*** ../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js ***! \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + function createDeferred() { + const d = {}; + d.promise = new Promise((resolve, reject) => { + d.resolve = resolve; + d.reject = reject; + }); + return d; + } + const SYMBOL_FINISHED = Symbol(); + const SYMBOL_NEW_VALUE = Symbol(); + /** + * makePushPullAsyncIterableIterator + * + * The iterable will publish values until return or throw is called. + * Afterwards it is in the completed state and cannot be used for publishing any further values. + * It will handle back-pressure and keep pushed values until they are consumed by a source. + */ + function makePushPullAsyncIterableIterator() { + let isRunning = true; + const values = []; + let newValueD = createDeferred(); + const finishedD = createDeferred(); + const asyncIterableIterator = + (async function* PushPullAsyncIterableIterator() { + while (true) { + if (values.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + yield values.shift(); + } else { + const result = await Promise.race([ + newValueD.promise, + finishedD.promise, + ]); + if (result === SYMBOL_FINISHED) { + break; + } + if (result !== SYMBOL_NEW_VALUE) { + throw result; + } + } + } + })(); + function pushValue(value) { + if (isRunning === false) { + // TODO: Should this throw? + return; + } + values.push(value); + newValueD.resolve(SYMBOL_NEW_VALUE); + newValueD = createDeferred(); + } + // We monkey patch the original generator for clean-up + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const originalReturn = asyncIterableIterator.return.bind( + asyncIterableIterator + ); + asyncIterableIterator.return = ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ...args + ) => { + isRunning = false; + finishedD.resolve(SYMBOL_FINISHED); + return originalReturn(...args); + }; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const originalThrow = asyncIterableIterator.throw.bind( + asyncIterableIterator + ); + asyncIterableIterator.throw = (err) => { + isRunning = false; + finishedD.resolve(err); + return originalThrow(err); + }; + return { + pushValue, + asyncIterableIterator, + }; + } + const makeAsyncIterableIteratorFromSink = (make) => { + const { pushValue, asyncIterableIterator } = + makePushPullAsyncIterableIterator(); + const dispose = make({ + next: (value) => { + pushValue(value); + }, + complete: () => { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + asyncIterableIterator.return(); + }, + error: (err) => { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + asyncIterableIterator.throw(err); + }, + }); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const originalReturn = asyncIterableIterator.return; + let returnValue = undefined; + asyncIterableIterator.return = () => { + if (returnValue === undefined) { + dispose(); + returnValue = originalReturn(); + } + return returnValue; + }; + return asyncIterableIterator; + }; + function applyAsyncIterableIteratorToSink(asyncIterableIterator, sink) { + const run = async () => { + try { + for await (const value of asyncIterableIterator) { + sink.next(value); + } + sink.complete(); + } catch (err) { + sink.error(err); + } + }; + run(); + return () => { + var _a; + (_a = asyncIterableIterator.return) === null || _a === void 0 + ? void 0 + : _a.call(asyncIterableIterator); + }; + } + function isAsyncIterable(input) { + return ( + typeof input === "object" && + input !== null && + // The AsyncGenerator check is for Safari on iOS which currently does not have + // Symbol.asyncIterator implemented + // That means every custom AsyncIterable must be built using a AsyncGeneratorFunction (async function * () {}) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (input[Symbol.toStringTag] === "AsyncGenerator" || + (Symbol.asyncIterator && Symbol.asyncIterator in input)) + ); + } + exports.applyAsyncIterableIteratorToSink = + applyAsyncIterableIteratorToSink; + exports.isAsyncIterable = isAsyncIterable; + exports.makeAsyncIterableIteratorFromSink = + makeAsyncIterableIteratorFromSink; + exports.makePushPullAsyncIterableIterator = + makePushPullAsyncIterableIterator; + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -function createDeferred() { - const d = {}; - d.promise = new Promise((resolve, reject) => { - d.resolve = resolve; - d.reject = reject; - }); - return d; -} -const SYMBOL_FINISHED = Symbol(); -const SYMBOL_NEW_VALUE = Symbol(); -/** - * makePushPullAsyncIterableIterator - * - * The iterable will publish values until return or throw is called. - * Afterwards it is in the completed state and cannot be used for publishing any further values. - * It will handle back-pressure and keep pushed values until they are consumed by a source. - */ -function makePushPullAsyncIterableIterator() { - let isRunning = true; - const values = []; - let newValueD = createDeferred(); - const finishedD = createDeferred(); - const asyncIterableIterator = async function* PushPullAsyncIterableIterator() { - while (true) { - if (values.length > 0) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield values.shift(); - } else { - const result = await Promise.race([newValueD.promise, finishedD.promise]); - if (result === SYMBOL_FINISHED) { - break; - } - if (result !== SYMBOL_NEW_VALUE) { - throw result; + /***/ "../../../node_modules/@radix-ui/primitive/dist/index.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/@radix-ui/primitive/dist/index.js ***! + \***************************************************************/ + /***/ function (module) { + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "composeEventHandlers", + () => $1a6a90a521dcd173$export$b9ecd428b558ff10 + ); + function $1a6a90a521dcd173$export$b9ecd428b558ff10( + originalEventHandler, + ourEventHandler, + { checkForDefaultPrevented = true } = {} + ) { + return function handleEvent(event) { + originalEventHandler === null || + originalEventHandler === void 0 || + originalEventHandler(event); + if (checkForDefaultPrevented === false || !event.defaultPrevented) + return ourEventHandler === null || ourEventHandler === void 0 + ? void 0 + : ourEventHandler(event); + }; } - } - } - }(); - function pushValue(value) { - if (isRunning === false) { - // TODO: Should this throw? - return; - } - values.push(value); - newValueD.resolve(SYMBOL_NEW_VALUE); - newValueD = createDeferred(); - } - // We monkey patch the original generator for clean-up - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalReturn = asyncIterableIterator.return.bind(asyncIterableIterator); - asyncIterableIterator.return = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args) => { - isRunning = false; - finishedD.resolve(SYMBOL_FINISHED); - return originalReturn(...args); - }; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalThrow = asyncIterableIterator.throw.bind(asyncIterableIterator); - asyncIterableIterator.throw = err => { - isRunning = false; - finishedD.resolve(err); - return originalThrow(err); - }; - return { - pushValue, - asyncIterableIterator - }; -} -const makeAsyncIterableIteratorFromSink = make => { - const { - pushValue, - asyncIterableIterator - } = makePushPullAsyncIterableIterator(); - const dispose = make({ - next: value => { - pushValue(value); - }, - complete: () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - asyncIterableIterator.return(); - }, - error: err => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - asyncIterableIterator.throw(err); - } - }); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalReturn = asyncIterableIterator.return; - let returnValue = undefined; - asyncIterableIterator.return = () => { - if (returnValue === undefined) { - dispose(); - returnValue = originalReturn(); - } - return returnValue; - }; - return asyncIterableIterator; -}; -function applyAsyncIterableIteratorToSink(asyncIterableIterator, sink) { - const run = async () => { - try { - for await (const value of asyncIterableIterator) { - sink.next(value); - } - sink.complete(); - } catch (err) { - sink.error(err); - } - }; - run(); - return () => { - var _a; - (_a = asyncIterableIterator.return) === null || _a === void 0 ? void 0 : _a.call(asyncIterableIterator); - }; -} -function isAsyncIterable(input) { - return typeof input === "object" && input !== null && ( - // The AsyncGenerator check is for Safari on iOS which currently does not have - // Symbol.asyncIterator implemented - // That means every custom AsyncIterable must be built using a AsyncGeneratorFunction (async function * () {}) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - input[Symbol.toStringTag] === "AsyncGenerator" || Symbol.asyncIterator && Symbol.asyncIterator in input); -} -exports.applyAsyncIterableIteratorToSink = applyAsyncIterableIteratorToSink; -exports.isAsyncIterable = isAsyncIterable; -exports.makeAsyncIterableIteratorFromSink = makeAsyncIterableIteratorFromSink; -exports.makePushPullAsyncIterableIterator = makePushPullAsyncIterableIterator; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/primitive/dist/index.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/@radix-ui/primitive/dist/index.js ***! - \***************************************************************/ -/***/ (function(module) { - - - -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "composeEventHandlers", () => $1a6a90a521dcd173$export$b9ecd428b558ff10); -function $1a6a90a521dcd173$export$b9ecd428b558ff10(originalEventHandler, ourEventHandler, { - checkForDefaultPrevented = true -} = {}) { - return function handleEvent(event) { - originalEventHandler === null || originalEventHandler === void 0 || originalEventHandler(event); - if (checkForDefaultPrevented === false || !event.defaultPrevented) return ourEventHandler === null || ourEventHandler === void 0 ? void 0 : ourEventHandler(event); - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@radix-ui/react-arrow/dist/index.js": -/*!*****************************************************************!*\ + /***/ "../../../node_modules/@radix-ui/react-arrow/dist/index.js": + /*!*****************************************************************!*\ !*** ../../../node_modules/@radix-ui/react-arrow/dist/index.js ***! \*****************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $eQpDd$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $eQpDd$react = __webpack_require__(/*! react */ "react"); + var $eQpDd$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "Arrow", + () => $09f4ad68a9251bc3$export$21b07c8f274aebd5 + ); + $parcel$export( + module.exports, + "Root", + () => $09f4ad68a9251bc3$export$be92b6f5f03c0fe9 + ); + /* ------------------------------------------------------------------------------------------------- + * Arrow + * -----------------------------------------------------------------------------------------------*/ + const $09f4ad68a9251bc3$var$NAME = "Arrow"; + const $09f4ad68a9251bc3$export$21b07c8f274aebd5 = + /*#__PURE__*/ $eQpDd$react.forwardRef((props, forwardedRef) => { + const { + children: children, + width = 10, + height = 5, + ...arrowProps + } = props; + return /*#__PURE__*/ $eQpDd$react.createElement( + $eQpDd$radixuireactprimitive.Primitive.svg, + $parcel$interopDefault($eQpDd$babelruntimehelpersextends)( + {}, + arrowProps, + { + ref: forwardedRef, + width: width, + height: height, + viewBox: "0 0 30 10", + preserveAspectRatio: "none", + } + ), + props.asChild + ? children + : /*#__PURE__*/ $eQpDd$react.createElement("polygon", { + points: "0,0 30,0 15,10", + }) + ); + }); + /*#__PURE__*/ + Object.assign($09f4ad68a9251bc3$export$21b07c8f274aebd5, { + displayName: $09f4ad68a9251bc3$var$NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + const $09f4ad68a9251bc3$export$be92b6f5f03c0fe9 = + $09f4ad68a9251bc3$export$21b07c8f274aebd5; + /***/ + }, -var $eQpDd$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $eQpDd$react = __webpack_require__(/*! react */ "react"); -var $eQpDd$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Arrow", () => $09f4ad68a9251bc3$export$21b07c8f274aebd5); -$parcel$export(module.exports, "Root", () => $09f4ad68a9251bc3$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * Arrow - * -----------------------------------------------------------------------------------------------*/ -const $09f4ad68a9251bc3$var$NAME = 'Arrow'; -const $09f4ad68a9251bc3$export$21b07c8f274aebd5 = /*#__PURE__*/$eQpDd$react.forwardRef((props, forwardedRef) => { - const { - children: children, - width = 10, - height = 5, - ...arrowProps - } = props; - return /*#__PURE__*/$eQpDd$react.createElement($eQpDd$radixuireactprimitive.Primitive.svg, $parcel$interopDefault($eQpDd$babelruntimehelpersextends)({}, arrowProps, { - ref: forwardedRef, - width: width, - height: height, - viewBox: "0 0 30 10", - preserveAspectRatio: "none" - }), props.asChild ? children : /*#__PURE__*/$eQpDd$react.createElement("polygon", { - points: "0,0 30,0 15,10" - })); -}); -/*#__PURE__*/ -Object.assign($09f4ad68a9251bc3$export$21b07c8f274aebd5, { - displayName: $09f4ad68a9251bc3$var$NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $09f4ad68a9251bc3$export$be92b6f5f03c0fe9 = $09f4ad68a9251bc3$export$21b07c8f274aebd5; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-collection/dist/index.js": -/*!**********************************************************************!*\ + /***/ "../../../node_modules/@radix-ui/react-collection/dist/index.js": + /*!**********************************************************************!*\ !*** ../../../node_modules/@radix-ui/react-collection/dist/index.js ***! \**********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $hnlpS$react = __webpack_require__(/*! react */ "react"); + var $hnlpS$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $hnlpS$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $hnlpS$radixuireactslot = __webpack_require__( + /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "createCollection", + () => $1a96635ec239608b$export$c74125a8e3af6bb2 + ); -var $hnlpS$react = __webpack_require__(/*! react */ "react"); -var $hnlpS$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $hnlpS$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $hnlpS$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createCollection", () => $1a96635ec239608b$export$c74125a8e3af6bb2); - -// We have resorted to returning slots directly rather than exposing primitives that can then -// be slotted like ``. -// This is because we encountered issues with generic types that cannot be statically analysed -// due to creating them dynamically via createCollection. -function $1a96635ec239608b$export$c74125a8e3af6bb2(name) { - /* ----------------------------------------------------------------------------------------------- - * CollectionProvider - * ---------------------------------------------------------------------------------------------*/ - const PROVIDER_NAME = name + 'CollectionProvider'; - const [createCollectionContext, createCollectionScope] = $hnlpS$radixuireactcontext.createContextScope(PROVIDER_NAME); - const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(PROVIDER_NAME, { - collectionRef: { - current: null - }, - itemMap: new Map() - }); - const CollectionProvider = props => { - const { - scope: scope, - children: children - } = props; - const ref = $parcel$interopDefault($hnlpS$react).useRef(null); - const itemMap = $parcel$interopDefault($hnlpS$react).useRef(new Map()).current; - return /*#__PURE__*/$parcel$interopDefault($hnlpS$react).createElement(CollectionProviderImpl, { - scope: scope, - itemMap: itemMap, - collectionRef: ref - }, children); - }; - /*#__PURE__*/ - Object.assign(CollectionProvider, { - displayName: PROVIDER_NAME - }); - /* ----------------------------------------------------------------------------------------------- - * CollectionSlot - * ---------------------------------------------------------------------------------------------*/ - const COLLECTION_SLOT_NAME = name + 'CollectionSlot'; - const CollectionSlot = /*#__PURE__*/$parcel$interopDefault($hnlpS$react).forwardRef((props, forwardedRef) => { - const { - scope: scope, - children: children - } = props; - const context = useCollectionContext(COLLECTION_SLOT_NAME, scope); - const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs(forwardedRef, context.collectionRef); - return /*#__PURE__*/$parcel$interopDefault($hnlpS$react).createElement($hnlpS$radixuireactslot.Slot, { - ref: composedRefs - }, children); - }); - /*#__PURE__*/ - Object.assign(CollectionSlot, { - displayName: COLLECTION_SLOT_NAME - }); - /* ----------------------------------------------------------------------------------------------- - * CollectionItem - * ---------------------------------------------------------------------------------------------*/ - const ITEM_SLOT_NAME = name + 'CollectionItemSlot'; - const ITEM_DATA_ATTR = 'data-radix-collection-item'; - const CollectionItemSlot = /*#__PURE__*/$parcel$interopDefault($hnlpS$react).forwardRef((props, forwardedRef) => { - const { - scope: scope, - children: children, - ...itemData - } = props; - const ref = $parcel$interopDefault($hnlpS$react).useRef(null); - const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const context = useCollectionContext(ITEM_SLOT_NAME, scope); - $parcel$interopDefault($hnlpS$react).useEffect(() => { - context.itemMap.set(ref, { - ref: ref, - ...itemData - }); - return () => void context.itemMap.delete(ref); - }); - return /*#__PURE__*/$parcel$interopDefault($hnlpS$react).createElement($hnlpS$radixuireactslot.Slot, { - [ITEM_DATA_ATTR]: '', - ref: composedRefs - }, children); - }); - /*#__PURE__*/ - Object.assign(CollectionItemSlot, { - displayName: ITEM_SLOT_NAME - }); - /* ----------------------------------------------------------------------------------------------- - * useCollection - * ---------------------------------------------------------------------------------------------*/ - function useCollection(scope) { - const context = useCollectionContext(name + 'CollectionConsumer', scope); - const getItems = $parcel$interopDefault($hnlpS$react).useCallback(() => { - const collectionNode = context.collectionRef.current; - if (!collectionNode) return []; - const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`)); - const items = Array.from(context.itemMap.values()); - const orderedItems = items.sort((a, b) => orderedNodes.indexOf(a.ref.current) - orderedNodes.indexOf(b.ref.current)); - return orderedItems; - }, [context.collectionRef, context.itemMap]); - return getItems; - } - return [{ - Provider: CollectionProvider, - Slot: CollectionSlot, - ItemSlot: CollectionItemSlot - }, useCollection, createCollectionScope]; -} + // We have resorted to returning slots directly rather than exposing primitives that can then + // be slotted like ``. + // This is because we encountered issues with generic types that cannot be statically analysed + // due to creating them dynamically via createCollection. + function $1a96635ec239608b$export$c74125a8e3af6bb2(name) { + /* ----------------------------------------------------------------------------------------------- + * CollectionProvider + * ---------------------------------------------------------------------------------------------*/ + const PROVIDER_NAME = name + "CollectionProvider"; + const [createCollectionContext, createCollectionScope] = + $hnlpS$radixuireactcontext.createContextScope(PROVIDER_NAME); + const [CollectionProviderImpl, useCollectionContext] = + createCollectionContext(PROVIDER_NAME, { + collectionRef: { + current: null, + }, + itemMap: new Map(), + }); + const CollectionProvider = (props) => { + const { scope: scope, children: children } = props; + const ref = $parcel$interopDefault($hnlpS$react).useRef(null); + const itemMap = $parcel$interopDefault($hnlpS$react).useRef( + new Map() + ).current; + return /*#__PURE__*/ $parcel$interopDefault( + $hnlpS$react + ).createElement( + CollectionProviderImpl, + { + scope: scope, + itemMap: itemMap, + collectionRef: ref, + }, + children + ); + }; + /*#__PURE__*/ + Object.assign(CollectionProvider, { + displayName: PROVIDER_NAME, + }); + /* ----------------------------------------------------------------------------------------------- + * CollectionSlot + * ---------------------------------------------------------------------------------------------*/ + const COLLECTION_SLOT_NAME = name + "CollectionSlot"; + const CollectionSlot = /*#__PURE__*/ $parcel$interopDefault( + $hnlpS$react + ).forwardRef((props, forwardedRef) => { + const { scope: scope, children: children } = props; + const context = useCollectionContext(COLLECTION_SLOT_NAME, scope); + const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + context.collectionRef + ); + return /*#__PURE__*/ $parcel$interopDefault( + $hnlpS$react + ).createElement( + $hnlpS$radixuireactslot.Slot, + { + ref: composedRefs, + }, + children + ); + }); + /*#__PURE__*/ + Object.assign(CollectionSlot, { + displayName: COLLECTION_SLOT_NAME, + }); + /* ----------------------------------------------------------------------------------------------- + * CollectionItem + * ---------------------------------------------------------------------------------------------*/ + const ITEM_SLOT_NAME = name + "CollectionItemSlot"; + const ITEM_DATA_ATTR = "data-radix-collection-item"; + const CollectionItemSlot = /*#__PURE__*/ $parcel$interopDefault( + $hnlpS$react + ).forwardRef((props, forwardedRef) => { + const { scope: scope, children: children, ...itemData } = props; + const ref = $parcel$interopDefault($hnlpS$react).useRef(null); + const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + const context = useCollectionContext(ITEM_SLOT_NAME, scope); + $parcel$interopDefault($hnlpS$react).useEffect(() => { + context.itemMap.set(ref, { + ref: ref, + ...itemData, + }); + return () => void context.itemMap.delete(ref); + }); + return /*#__PURE__*/ $parcel$interopDefault( + $hnlpS$react + ).createElement( + $hnlpS$radixuireactslot.Slot, + { + [ITEM_DATA_ATTR]: "", + ref: composedRefs, + }, + children + ); + }); + /*#__PURE__*/ + Object.assign(CollectionItemSlot, { + displayName: ITEM_SLOT_NAME, + }); + /* ----------------------------------------------------------------------------------------------- + * useCollection + * ---------------------------------------------------------------------------------------------*/ + function useCollection(scope) { + const context = useCollectionContext( + name + "CollectionConsumer", + scope + ); + const getItems = $parcel$interopDefault( + $hnlpS$react + ).useCallback(() => { + const collectionNode = context.collectionRef.current; + if (!collectionNode) return []; + const orderedNodes = Array.from( + collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`) + ); + const items = Array.from(context.itemMap.values()); + const orderedItems = items.sort( + (a, b) => + orderedNodes.indexOf(a.ref.current) - + orderedNodes.indexOf(b.ref.current) + ); + return orderedItems; + }, [context.collectionRef, context.itemMap]); + return getItems; + } + return [ + { + Provider: CollectionProvider, + Slot: CollectionSlot, + ItemSlot: CollectionItemSlot, + }, + useCollection, + createCollectionScope, + ]; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js": -/*!************************************************************************!*\ + /***/ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js": + /*!************************************************************************!*\ !*** ../../../node_modules/@radix-ui/react-compose-refs/dist/index.js ***! \************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $dJwbH$react = __webpack_require__(/*! react */ "react"); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "composeRefs", + () => $9c2aaba23466b352$export$43e446d32b3d21af + ); + $parcel$export( + module.exports, + "useComposedRefs", + () => $9c2aaba23466b352$export$c7b2cbe3552a0d05 + ); + /** + * Set a given ref to a given value + * This utility takes care of different types of refs: callback refs and RefObject(s) + */ + function $9c2aaba23466b352$var$setRef(ref, value) { + if (typeof ref === "function") ref(value); + else if (ref !== null && ref !== undefined) ref.current = value; + } + /** + * A utility to compose multiple refs together + * Accepts callback refs and RefObject(s) + */ + function $9c2aaba23466b352$export$43e446d32b3d21af(...refs) { + return (node) => + refs.forEach((ref) => $9c2aaba23466b352$var$setRef(ref, node)); + } + /** + * A custom hook that composes multiple refs + * Accepts callback refs and RefObject(s) + */ + function $9c2aaba23466b352$export$c7b2cbe3552a0d05(...refs) { + // eslint-disable-next-line react-hooks/exhaustive-deps + return $dJwbH$react.useCallback( + $9c2aaba23466b352$export$43e446d32b3d21af(...refs), + refs + ); + } + /***/ + }, -var $dJwbH$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "composeRefs", () => $9c2aaba23466b352$export$43e446d32b3d21af); -$parcel$export(module.exports, "useComposedRefs", () => $9c2aaba23466b352$export$c7b2cbe3552a0d05); - -/** - * Set a given ref to a given value - * This utility takes care of different types of refs: callback refs and RefObject(s) - */ -function $9c2aaba23466b352$var$setRef(ref, value) { - if (typeof ref === 'function') ref(value);else if (ref !== null && ref !== undefined) ref.current = value; -} -/** - * A utility to compose multiple refs together - * Accepts callback refs and RefObject(s) - */ -function $9c2aaba23466b352$export$43e446d32b3d21af(...refs) { - return node => refs.forEach(ref => $9c2aaba23466b352$var$setRef(ref, node)); -} -/** - * A custom hook that composes multiple refs - * Accepts callback refs and RefObject(s) - */ -function $9c2aaba23466b352$export$c7b2cbe3552a0d05(...refs) { - // eslint-disable-next-line react-hooks/exhaustive-deps - return $dJwbH$react.useCallback($9c2aaba23466b352$export$43e446d32b3d21af(...refs), refs); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-context/dist/index.js": -/*!*******************************************************************!*\ + /***/ "../../../node_modules/@radix-ui/react-context/dist/index.js": + /*!*******************************************************************!*\ !*** ../../../node_modules/@radix-ui/react-context/dist/index.js ***! \*******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $4O1Ne$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "createContext", () => $dec3cc0142d4f286$export$fd42f52fd3ae1109); -$parcel$export(module.exports, "createContextScope", () => $dec3cc0142d4f286$export$50c7b4e9d9f19c1); -function $dec3cc0142d4f286$export$fd42f52fd3ae1109(rootComponentName, defaultContext) { - const Context = /*#__PURE__*/$4O1Ne$react.createContext(defaultContext); - function Provider(props) { - const { - children: children, - ...context - } = props; // Only re-memoize when prop values change - // eslint-disable-next-line react-hooks/exhaustive-deps - const value = $4O1Ne$react.useMemo(() => context, Object.values(context)); - return /*#__PURE__*/$4O1Ne$react.createElement(Context.Provider, { - value: value - }, children); - } - function useContext(consumerName) { - const context = $4O1Ne$react.useContext(Context); - if (context) return context; - if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. - throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); - } - Provider.displayName = rootComponentName + 'Provider'; - return [Provider, useContext]; -} -/* ------------------------------------------------------------------------------------------------- - * createContextScope - * -----------------------------------------------------------------------------------------------*/ -function $dec3cc0142d4f286$export$50c7b4e9d9f19c1(scopeName, createContextScopeDeps = []) { - let defaultContexts = []; - /* ----------------------------------------------------------------------------------------------- - * createContext - * ---------------------------------------------------------------------------------------------*/ - function $dec3cc0142d4f286$export$fd42f52fd3ae1109(rootComponentName, defaultContext) { - const BaseContext = /*#__PURE__*/$4O1Ne$react.createContext(defaultContext); - const index = defaultContexts.length; - defaultContexts = [...defaultContexts, defaultContext]; - function Provider(props) { - const { - scope: scope, - children: children, - ...context - } = props; - const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index]) || BaseContext; // Only re-memoize when prop values change - // eslint-disable-next-line react-hooks/exhaustive-deps - const value = $4O1Ne$react.useMemo(() => context, Object.values(context)); - return /*#__PURE__*/$4O1Ne$react.createElement(Context.Provider, { - value: value - }, children); - } - function useContext(consumerName, scope) { - const Context = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index]) || BaseContext; - const context = $4O1Ne$react.useContext(Context); - if (context) return context; - if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. - throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); - } - Provider.displayName = rootComponentName + 'Provider'; - return [Provider, useContext]; - } - /* ----------------------------------------------------------------------------------------------- - * createScope - * ---------------------------------------------------------------------------------------------*/ - const createScope = () => { - const scopeContexts = defaultContexts.map(defaultContext => { - return /*#__PURE__*/$4O1Ne$react.createContext(defaultContext); - }); - return function useScope(scope) { - const contexts = (scope === null || scope === void 0 ? void 0 : scope[scopeName]) || scopeContexts; - return $4O1Ne$react.useMemo(() => ({ - [`__scope${scopeName}`]: { - ...scope, - [scopeName]: contexts - } - }), [scope, contexts]); - }; - }; - createScope.scopeName = scopeName; - return [$dec3cc0142d4f286$export$fd42f52fd3ae1109, $dec3cc0142d4f286$var$composeContextScopes(createScope, ...createContextScopeDeps)]; -} -/* ------------------------------------------------------------------------------------------------- - * composeContextScopes - * -----------------------------------------------------------------------------------------------*/ -function $dec3cc0142d4f286$var$composeContextScopes(...scopes) { - const baseScope = scopes[0]; - if (scopes.length === 1) return baseScope; - const createScope1 = () => { - const scopeHooks = scopes.map(createScope => ({ - useScope: createScope(), - scopeName: createScope.scopeName - })); - return function useComposedScopes(overrideScopes) { - const nextScopes1 = scopeHooks.reduce((nextScopes, { - useScope: useScope, - scopeName: scopeName - }) => { - // We are calling a hook inside a callback which React warns against to avoid inconsistent - // renders, however, scoping doesn't have render side effects so we ignore the rule. - // eslint-disable-next-line react-hooks/rules-of-hooks - const scopeProps = useScope(overrideScopes); - const currentScope = scopeProps[`__scope${scopeName}`]; - return { - ...nextScopes, - ...currentScope - }; - }, {}); - return $4O1Ne$react.useMemo(() => ({ - [`__scope${baseScope.scopeName}`]: nextScopes1 - }), [nextScopes1]); - }; - }; - createScope1.scopeName = baseScope.scopeName; - return createScope1; -} + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $4O1Ne$react = __webpack_require__(/*! react */ "react"); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "createContext", + () => $dec3cc0142d4f286$export$fd42f52fd3ae1109 + ); + $parcel$export( + module.exports, + "createContextScope", + () => $dec3cc0142d4f286$export$50c7b4e9d9f19c1 + ); + function $dec3cc0142d4f286$export$fd42f52fd3ae1109( + rootComponentName, + defaultContext + ) { + const Context = + /*#__PURE__*/ $4O1Ne$react.createContext(defaultContext); + function Provider(props) { + const { children: children, ...context } = props; // Only re-memoize when prop values change + // eslint-disable-next-line react-hooks/exhaustive-deps + const value = $4O1Ne$react.useMemo( + () => context, + Object.values(context) + ); + return /*#__PURE__*/ $4O1Ne$react.createElement( + Context.Provider, + { + value: value, + }, + children + ); + } + function useContext(consumerName) { + const context = $4O1Ne$react.useContext(Context); + if (context) return context; + if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. + throw new Error( + `\`${consumerName}\` must be used within \`${rootComponentName}\`` + ); + } + Provider.displayName = rootComponentName + "Provider"; + return [Provider, useContext]; + } + /* ------------------------------------------------------------------------------------------------- + * createContextScope + * -----------------------------------------------------------------------------------------------*/ + function $dec3cc0142d4f286$export$50c7b4e9d9f19c1( + scopeName, + createContextScopeDeps = [] + ) { + let defaultContexts = []; + /* ----------------------------------------------------------------------------------------------- + * createContext + * ---------------------------------------------------------------------------------------------*/ + function $dec3cc0142d4f286$export$fd42f52fd3ae1109( + rootComponentName, + defaultContext + ) { + const BaseContext = + /*#__PURE__*/ $4O1Ne$react.createContext(defaultContext); + const index = defaultContexts.length; + defaultContexts = [...defaultContexts, defaultContext]; + function Provider(props) { + const { scope: scope, children: children, ...context } = props; + const Context = + (scope === null || scope === void 0 + ? void 0 + : scope[scopeName][index]) || BaseContext; // Only re-memoize when prop values change + // eslint-disable-next-line react-hooks/exhaustive-deps + const value = $4O1Ne$react.useMemo( + () => context, + Object.values(context) + ); + return /*#__PURE__*/ $4O1Ne$react.createElement( + Context.Provider, + { + value: value, + }, + children + ); + } + function useContext(consumerName, scope) { + const Context = + (scope === null || scope === void 0 + ? void 0 + : scope[scopeName][index]) || BaseContext; + const context = $4O1Ne$react.useContext(Context); + if (context) return context; + if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. + throw new Error( + `\`${consumerName}\` must be used within \`${rootComponentName}\`` + ); + } + Provider.displayName = rootComponentName + "Provider"; + return [Provider, useContext]; + } + /* ----------------------------------------------------------------------------------------------- + * createScope + * ---------------------------------------------------------------------------------------------*/ + const createScope = () => { + const scopeContexts = defaultContexts.map((defaultContext) => { + return /*#__PURE__*/ $4O1Ne$react.createContext(defaultContext); + }); + return function useScope(scope) { + const contexts = + (scope === null || scope === void 0 + ? void 0 + : scope[scopeName]) || scopeContexts; + return $4O1Ne$react.useMemo( + () => ({ + [`__scope${scopeName}`]: { + ...scope, + [scopeName]: contexts, + }, + }), + [scope, contexts] + ); + }; + }; + createScope.scopeName = scopeName; + return [ + $dec3cc0142d4f286$export$fd42f52fd3ae1109, + $dec3cc0142d4f286$var$composeContextScopes( + createScope, + ...createContextScopeDeps + ), + ]; + } + /* ------------------------------------------------------------------------------------------------- + * composeContextScopes + * -----------------------------------------------------------------------------------------------*/ + function $dec3cc0142d4f286$var$composeContextScopes(...scopes) { + const baseScope = scopes[0]; + if (scopes.length === 1) return baseScope; + const createScope1 = () => { + const scopeHooks = scopes.map((createScope) => ({ + useScope: createScope(), + scopeName: createScope.scopeName, + })); + return function useComposedScopes(overrideScopes) { + const nextScopes1 = scopeHooks.reduce( + (nextScopes, { useScope: useScope, scopeName: scopeName }) => { + // We are calling a hook inside a callback which React warns against to avoid inconsistent + // renders, however, scoping doesn't have render side effects so we ignore the rule. + // eslint-disable-next-line react-hooks/rules-of-hooks + const scopeProps = useScope(overrideScopes); + const currentScope = scopeProps[`__scope${scopeName}`]; + return { + ...nextScopes, + ...currentScope, + }; + }, + {} + ); + return $4O1Ne$react.useMemo( + () => ({ + [`__scope${baseScope.scopeName}`]: nextScopes1, + }), + [nextScopes1] + ); + }; + }; + createScope1.scopeName = baseScope.scopeName; + return createScope1; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@radix-ui/react-dialog/dist/index.js": -/*!******************************************************************!*\ + /***/ "../../../node_modules/@radix-ui/react-dialog/dist/index.js": + /*!******************************************************************!*\ !*** ../../../node_modules/@radix-ui/react-dialog/dist/index.js ***! \******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $aJCrN$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $aJCrN$react = __webpack_require__(/*! react */ "react"); -var $aJCrN$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $aJCrN$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $aJCrN$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $aJCrN$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $aJCrN$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $aJCrN$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); -var $aJCrN$radixuireactfocusscope = __webpack_require__(/*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js"); -var $aJCrN$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); -var $aJCrN$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); -var $aJCrN$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $aJCrN$radixuireactfocusguards = __webpack_require__(/*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js"); -var $aJCrN$reactremovescroll = __webpack_require__(/*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js"); -var $aJCrN$ariahidden = __webpack_require__(/*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js"); -var $aJCrN$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createDialogScope", () => $f4833395aa1bca1a$export$cc702773b8ea3e41); -$parcel$export(module.exports, "Dialog", () => $f4833395aa1bca1a$export$3ddf2d174ce01153); -$parcel$export(module.exports, "DialogTrigger", () => $f4833395aa1bca1a$export$2e1e1122cf0cba88); -$parcel$export(module.exports, "DialogPortal", () => $f4833395aa1bca1a$export$dad7c95542bacce0); -$parcel$export(module.exports, "DialogOverlay", () => $f4833395aa1bca1a$export$bd1d06c79be19e17); -$parcel$export(module.exports, "DialogContent", () => $f4833395aa1bca1a$export$b6d9565de1e068cf); -$parcel$export(module.exports, "DialogTitle", () => $f4833395aa1bca1a$export$16f7638e4a34b909); -$parcel$export(module.exports, "DialogDescription", () => $f4833395aa1bca1a$export$94e94c2ec2c954d5); -$parcel$export(module.exports, "DialogClose", () => $f4833395aa1bca1a$export$fba2fb7cd781b7ac); -$parcel$export(module.exports, "Root", () => $f4833395aa1bca1a$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Trigger", () => $f4833395aa1bca1a$export$41fb9f06171c75f4); -$parcel$export(module.exports, "Portal", () => $f4833395aa1bca1a$export$602eac185826482c); -$parcel$export(module.exports, "Overlay", () => $f4833395aa1bca1a$export$c6fdb837b070b4ff); -$parcel$export(module.exports, "Content", () => $f4833395aa1bca1a$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Title", () => $f4833395aa1bca1a$export$f99233281efd08a0); -$parcel$export(module.exports, "Description", () => $f4833395aa1bca1a$export$393edc798c47379d); -$parcel$export(module.exports, "Close", () => $f4833395aa1bca1a$export$f39c2d165cd861fe); -$parcel$export(module.exports, "WarningProvider", () => $f4833395aa1bca1a$export$69b62a49393917d6); - -/* ------------------------------------------------------------------------------------------------- - * Dialog - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DIALOG_NAME = 'Dialog'; -const [$f4833395aa1bca1a$var$createDialogContext, $f4833395aa1bca1a$export$cc702773b8ea3e41] = $aJCrN$radixuireactcontext.createContextScope($f4833395aa1bca1a$var$DIALOG_NAME); -const [$f4833395aa1bca1a$var$DialogProvider, $f4833395aa1bca1a$var$useDialogContext] = $f4833395aa1bca1a$var$createDialogContext($f4833395aa1bca1a$var$DIALOG_NAME); -const $f4833395aa1bca1a$export$3ddf2d174ce01153 = props => { - const { - __scopeDialog: __scopeDialog, - children: children, - open: openProp, - defaultOpen: defaultOpen, - onOpenChange: onOpenChange, - modal = true - } = props; - const triggerRef = $aJCrN$react.useRef(null); - const contentRef = $aJCrN$react.useRef(null); - const [open = false, setOpen] = $aJCrN$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange - }); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogProvider, { - scope: __scopeDialog, - triggerRef: triggerRef, - contentRef: contentRef, - contentId: $aJCrN$radixuireactid.useId(), - titleId: $aJCrN$radixuireactid.useId(), - descriptionId: $aJCrN$radixuireactid.useId(), - open: open, - onOpenChange: setOpen, - onOpenToggle: $aJCrN$react.useCallback(() => setOpen(prevOpen => !prevOpen), [setOpen]), - modal: modal - }, children); -}; -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$3ddf2d174ce01153, { - displayName: $f4833395aa1bca1a$var$DIALOG_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogTrigger - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$TRIGGER_NAME = 'DialogTrigger'; -const $f4833395aa1bca1a$export$2e1e1122cf0cba88 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...triggerProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$TRIGGER_NAME, __scopeDialog); - const composedTriggerRef = $aJCrN$radixuireactcomposerefs.useComposedRefs(forwardedRef, context.triggerRef); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.button, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - type: "button", - "aria-haspopup": "dialog", - "aria-expanded": context.open, - "aria-controls": context.contentId, - "data-state": $f4833395aa1bca1a$var$getState(context.open) - }, triggerProps, { - ref: composedTriggerRef, - onClick: $aJCrN$radixuiprimitive.composeEventHandlers(props.onClick, context.onOpenToggle) - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$2e1e1122cf0cba88, { - displayName: $f4833395aa1bca1a$var$TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogPortal - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$PORTAL_NAME = 'DialogPortal'; -const [$f4833395aa1bca1a$var$PortalProvider, $f4833395aa1bca1a$var$usePortalContext] = $f4833395aa1bca1a$var$createDialogContext($f4833395aa1bca1a$var$PORTAL_NAME, { - forceMount: undefined -}); -const $f4833395aa1bca1a$export$dad7c95542bacce0 = props => { - const { - __scopeDialog: __scopeDialog, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$PORTAL_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$PortalProvider, { - scope: __scopeDialog, - forceMount: forceMount - }, $aJCrN$react.Children.map(children, child => /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactportal.Portal, { - asChild: true, - container: container - }, child)))); -}; -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$dad7c95542bacce0, { - displayName: $f4833395aa1bca1a$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogOverlay - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$OVERLAY_NAME = 'DialogOverlay'; -const $f4833395aa1bca1a$export$bd1d06c79be19e17 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const portalContext = $f4833395aa1bca1a$var$usePortalContext($f4833395aa1bca1a$var$OVERLAY_NAME, props.__scopeDialog); - const { - forceMount = portalContext.forceMount, - ...overlayProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$OVERLAY_NAME, props.__scopeDialog); - return context.modal ? /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogOverlayImpl, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, overlayProps, { - ref: forwardedRef - }))) : null; -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$bd1d06c79be19e17, { - displayName: $f4833395aa1bca1a$var$OVERLAY_NAME -}); -const $f4833395aa1bca1a$var$DialogOverlayImpl = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...overlayProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$OVERLAY_NAME, __scopeDialog); - return /*#__PURE__*/ (// Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll` - // ie. when `Overlay` and `Content` are siblings - $aJCrN$react.createElement($aJCrN$reactremovescroll.RemoveScroll, { - as: $aJCrN$radixuireactslot.Slot, - allowPinchZoom: true, - shards: [context.contentRef] - }, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.div, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - "data-state": $f4833395aa1bca1a$var$getState(context.open) - }, overlayProps, { - ref: forwardedRef // We re-enable pointer-events prevented by `Dialog.Content` to allow scrolling the overlay. - , - - style: { - pointerEvents: 'auto', - ...overlayProps.style - } - }))) - ); -}); -/* ------------------------------------------------------------------------------------------------- - * DialogContent - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$CONTENT_NAME = 'DialogContent'; -const $f4833395aa1bca1a$export$b6d9565de1e068cf = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const portalContext = $f4833395aa1bca1a$var$usePortalContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - const { - forceMount = portalContext.forceMount, - ...contentProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactpresence.Presence, { - present: forceMount || context.open - }, context.modal ? /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentModal, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentNonModal, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - }))); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$b6d9565de1e068cf, { - displayName: $f4833395aa1bca1a$var$CONTENT_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DialogContentModal = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - const contentRef = $aJCrN$react.useRef(null); - const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs(forwardedRef, context.contentRef, contentRef); // aria-hide everything except the content (better supported equivalent to setting aria-modal) - $aJCrN$react.useEffect(() => { - const content = contentRef.current; - if (content) return $aJCrN$ariahidden.hideOthers(content); - }, []); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentImpl, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, props, { - ref: composedRefs // we make sure focus isn't trapped once `DialogContent` has been closed - , - - trapFocus: context.open, - disableOutsidePointerEvents: true, - onCloseAutoFocus: $aJCrN$radixuiprimitive.composeEventHandlers(props.onCloseAutoFocus, event => { - var _context$triggerRef$c; - event.preventDefault(); - (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus(); - }), - onPointerDownOutside: $aJCrN$radixuiprimitive.composeEventHandlers(props.onPointerDownOutside, event => { - const originalEvent = event.detail.originalEvent; - const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; - const isRightClick = originalEvent.button === 2 || ctrlLeftClick; // If the event is a right-click, we shouldn't close because - // it is effectively as if we right-clicked the `Overlay`. - if (isRightClick) event.preventDefault(); - }) // When focus is trapped, a `focusout` event may still happen. - , - - onFocusOutside: $aJCrN$radixuiprimitive.composeEventHandlers(props.onFocusOutside, event => event.preventDefault()) - })); -}); -/* -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DialogContentNonModal = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, props.__scopeDialog); - const hasInteractedOutsideRef = $aJCrN$react.useRef(false); - const hasPointerDownOutsideRef = $aJCrN$react.useRef(false); - return /*#__PURE__*/$aJCrN$react.createElement($f4833395aa1bca1a$var$DialogContentImpl, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - trapFocus: false, - disableOutsidePointerEvents: false, - onCloseAutoFocus: event => { - var _props$onCloseAutoFoc; - (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || _props$onCloseAutoFoc === void 0 || _props$onCloseAutoFoc.call(props, event); - if (!event.defaultPrevented) { - var _context$triggerRef$c2; - if (!hasInteractedOutsideRef.current) (_context$triggerRef$c2 = context.triggerRef.current) === null || _context$triggerRef$c2 === void 0 || _context$triggerRef$c2.focus(); // Always prevent auto focus because we either focus manually or want user agent focus - event.preventDefault(); - } - hasInteractedOutsideRef.current = false; - hasPointerDownOutsideRef.current = false; - }, - onInteractOutside: event => { - var _props$onInteractOuts, _context$triggerRef$c3; - (_props$onInteractOuts = props.onInteractOutside) === null || _props$onInteractOuts === void 0 || _props$onInteractOuts.call(props, event); - if (!event.defaultPrevented) { - hasInteractedOutsideRef.current = true; - if (event.detail.originalEvent.type === 'pointerdown') hasPointerDownOutsideRef.current = true; - } // Prevent dismissing when clicking the trigger. - // As the trigger is already setup to close, without doing so would - // cause it to close and immediately open. - const target = event.target; - const targetIsTrigger = (_context$triggerRef$c3 = context.triggerRef.current) === null || _context$triggerRef$c3 === void 0 ? void 0 : _context$triggerRef$c3.contains(target); - if (targetIsTrigger) event.preventDefault(); // On Safari if the trigger is inside a container with tabIndex={0}, when clicked - // we will get the pointer down outside event on the trigger, but then a subsequent - // focus outside event on the container, we ignore any focus outside event when we've - // already had a pointer down outside event. - if (event.detail.originalEvent.type === 'focusin' && hasPointerDownOutsideRef.current) event.preventDefault(); - } - })); -}); -/* -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DialogContentImpl = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - trapFocus: trapFocus, - onOpenAutoFocus: onOpenAutoFocus, - onCloseAutoFocus: onCloseAutoFocus, - ...contentProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CONTENT_NAME, __scopeDialog); - const contentRef = $aJCrN$react.useRef(null); - const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs(forwardedRef, contentRef); // Make sure the whole tree has focus guards as our `Dialog` will be - // the last element in the DOM (beacuse of the `Portal`) - $aJCrN$radixuireactfocusguards.useFocusGuards(); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$react.Fragment, null, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactfocusscope.FocusScope, { - asChild: true, - loop: true, - trapped: trapFocus, - onMountAutoFocus: onOpenAutoFocus, - onUnmountAutoFocus: onCloseAutoFocus - }, /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactdismissablelayer.DismissableLayer, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - role: "dialog", - id: context.contentId, - "aria-describedby": context.descriptionId, - "aria-labelledby": context.titleId, - "data-state": $f4833395aa1bca1a$var$getState(context.open) - }, contentProps, { - ref: composedRefs, - onDismiss: () => context.onOpenChange(false) - }))), false); -}); -/* ------------------------------------------------------------------------------------------------- - * DialogTitle - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$TITLE_NAME = 'DialogTitle'; -const $f4833395aa1bca1a$export$16f7638e4a34b909 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...titleProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$TITLE_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.h2, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - id: context.titleId - }, titleProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$16f7638e4a34b909, { - displayName: $f4833395aa1bca1a$var$TITLE_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogDescription - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$DESCRIPTION_NAME = 'DialogDescription'; -const $f4833395aa1bca1a$export$94e94c2ec2c954d5 = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...descriptionProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$DESCRIPTION_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.p, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - id: context.descriptionId - }, descriptionProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$94e94c2ec2c954d5, { - displayName: $f4833395aa1bca1a$var$DESCRIPTION_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DialogClose - * -----------------------------------------------------------------------------------------------*/ -const $f4833395aa1bca1a$var$CLOSE_NAME = 'DialogClose'; -const $f4833395aa1bca1a$export$fba2fb7cd781b7ac = /*#__PURE__*/$aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - ...closeProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext($f4833395aa1bca1a$var$CLOSE_NAME, __scopeDialog); - return /*#__PURE__*/$aJCrN$react.createElement($aJCrN$radixuireactprimitive.Primitive.button, $parcel$interopDefault($aJCrN$babelruntimehelpersextends)({ - type: "button" - }, closeProps, { - ref: forwardedRef, - onClick: $aJCrN$radixuiprimitive.composeEventHandlers(props.onClick, () => context.onOpenChange(false)) - })); -}); -/*#__PURE__*/ -Object.assign($f4833395aa1bca1a$export$fba2fb7cd781b7ac, { - displayName: $f4833395aa1bca1a$var$CLOSE_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $f4833395aa1bca1a$var$getState(open) { - return open ? 'open' : 'closed'; -} -const $f4833395aa1bca1a$var$TITLE_WARNING_NAME = 'DialogTitleWarning'; -const [$f4833395aa1bca1a$export$69b62a49393917d6, $f4833395aa1bca1a$var$useWarningContext] = $aJCrN$radixuireactcontext.createContext($f4833395aa1bca1a$var$TITLE_WARNING_NAME, { - contentName: $f4833395aa1bca1a$var$CONTENT_NAME, - titleName: $f4833395aa1bca1a$var$TITLE_NAME, - docsSlug: 'dialog' -}); -const $f4833395aa1bca1a$var$TitleWarning = ({ - titleId: titleId -}) => { - const titleWarningContext = $f4833395aa1bca1a$var$useWarningContext($f4833395aa1bca1a$var$TITLE_WARNING_NAME); - const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users. - -If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component. - -For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`; - $aJCrN$react.useEffect(() => { - if (titleId) { - const hasTitle = document.getElementById(titleId); - if (!hasTitle) throw new Error(MESSAGE); - } - }, [MESSAGE, titleId]); - return null; -}; -const $f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME = 'DialogDescriptionWarning'; -const $f4833395aa1bca1a$var$DescriptionWarning = ({ - contentRef: contentRef, - descriptionId: descriptionId -}) => { - const descriptionWarningContext = $f4833395aa1bca1a$var$useWarningContext($f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME); - const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`; - $aJCrN$react.useEffect(() => { - var _contentRef$current; - const describedById = (_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 ? void 0 : _contentRef$current.getAttribute('aria-describedby'); // if we have an id and the user hasn't set aria-describedby={undefined} - if (descriptionId && describedById) { - const hasDescription = document.getElementById(descriptionId); - if (!hasDescription) console.warn(MESSAGE); - } - }, [MESSAGE, contentRef, descriptionId]); - return null; -}; -const $f4833395aa1bca1a$export$be92b6f5f03c0fe9 = $f4833395aa1bca1a$export$3ddf2d174ce01153; -const $f4833395aa1bca1a$export$41fb9f06171c75f4 = $f4833395aa1bca1a$export$2e1e1122cf0cba88; -const $f4833395aa1bca1a$export$602eac185826482c = $f4833395aa1bca1a$export$dad7c95542bacce0; -const $f4833395aa1bca1a$export$c6fdb837b070b4ff = $f4833395aa1bca1a$export$bd1d06c79be19e17; -const $f4833395aa1bca1a$export$7c6e2c02157bb7d2 = $f4833395aa1bca1a$export$b6d9565de1e068cf; -const $f4833395aa1bca1a$export$f99233281efd08a0 = $f4833395aa1bca1a$export$16f7638e4a34b909; -const $f4833395aa1bca1a$export$393edc798c47379d = $f4833395aa1bca1a$export$94e94c2ec2c954d5; -const $f4833395aa1bca1a$export$f39c2d165cd861fe = $f4833395aa1bca1a$export$fba2fb7cd781b7ac; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-direction/dist/index.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-direction/dist/index.js ***! - \*********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $9g4ps$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useDirection", () => $cc45c1b701a63adc$export$b39126d51d94e6f3); -$parcel$export(module.exports, "Provider", () => $cc45c1b701a63adc$export$2881499e37b75b9a); -$parcel$export(module.exports, "DirectionProvider", () => $cc45c1b701a63adc$export$c760c09fdd558351); -const $cc45c1b701a63adc$var$DirectionContext = /*#__PURE__*/$9g4ps$react.createContext(undefined); -/* ------------------------------------------------------------------------------------------------- - * Direction - * -----------------------------------------------------------------------------------------------*/ -const $cc45c1b701a63adc$export$c760c09fdd558351 = props => { - const { - dir: dir, - children: children - } = props; - return /*#__PURE__*/$9g4ps$react.createElement($cc45c1b701a63adc$var$DirectionContext.Provider, { - value: dir - }, children); -}; -/* -----------------------------------------------------------------------------------------------*/ -function $cc45c1b701a63adc$export$b39126d51d94e6f3(localDir) { - const globalDir = $9g4ps$react.useContext($cc45c1b701a63adc$var$DirectionContext); - return localDir || globalDir || 'ltr'; -} -const $cc45c1b701a63adc$export$2881499e37b75b9a = $cc45c1b701a63adc$export$c760c09fdd558351; - -/***/ }), + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $aJCrN$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $aJCrN$react = __webpack_require__(/*! react */ "react"); + var $aJCrN$radixuiprimitive = __webpack_require__( + /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" + ); + var $aJCrN$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $aJCrN$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $aJCrN$radixuireactid = __webpack_require__( + /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" + ); + var $aJCrN$radixuireactusecontrollablestate = __webpack_require__( + /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" + ); + var $aJCrN$radixuireactdismissablelayer = __webpack_require__( + /*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js" + ); + var $aJCrN$radixuireactfocusscope = __webpack_require__( + /*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js" + ); + var $aJCrN$radixuireactportal = __webpack_require__( + /*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js" + ); + var $aJCrN$radixuireactpresence = __webpack_require__( + /*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js" + ); + var $aJCrN$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $aJCrN$radixuireactfocusguards = __webpack_require__( + /*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js" + ); + var $aJCrN$reactremovescroll = __webpack_require__( + /*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js" + ); + var $aJCrN$ariahidden = __webpack_require__( + /*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js" + ); + var $aJCrN$radixuireactslot = __webpack_require__( + /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "createDialogScope", + () => $f4833395aa1bca1a$export$cc702773b8ea3e41 + ); + $parcel$export( + module.exports, + "Dialog", + () => $f4833395aa1bca1a$export$3ddf2d174ce01153 + ); + $parcel$export( + module.exports, + "DialogTrigger", + () => $f4833395aa1bca1a$export$2e1e1122cf0cba88 + ); + $parcel$export( + module.exports, + "DialogPortal", + () => $f4833395aa1bca1a$export$dad7c95542bacce0 + ); + $parcel$export( + module.exports, + "DialogOverlay", + () => $f4833395aa1bca1a$export$bd1d06c79be19e17 + ); + $parcel$export( + module.exports, + "DialogContent", + () => $f4833395aa1bca1a$export$b6d9565de1e068cf + ); + $parcel$export( + module.exports, + "DialogTitle", + () => $f4833395aa1bca1a$export$16f7638e4a34b909 + ); + $parcel$export( + module.exports, + "DialogDescription", + () => $f4833395aa1bca1a$export$94e94c2ec2c954d5 + ); + $parcel$export( + module.exports, + "DialogClose", + () => $f4833395aa1bca1a$export$fba2fb7cd781b7ac + ); + $parcel$export( + module.exports, + "Root", + () => $f4833395aa1bca1a$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Trigger", + () => $f4833395aa1bca1a$export$41fb9f06171c75f4 + ); + $parcel$export( + module.exports, + "Portal", + () => $f4833395aa1bca1a$export$602eac185826482c + ); + $parcel$export( + module.exports, + "Overlay", + () => $f4833395aa1bca1a$export$c6fdb837b070b4ff + ); + $parcel$export( + module.exports, + "Content", + () => $f4833395aa1bca1a$export$7c6e2c02157bb7d2 + ); + $parcel$export( + module.exports, + "Title", + () => $f4833395aa1bca1a$export$f99233281efd08a0 + ); + $parcel$export( + module.exports, + "Description", + () => $f4833395aa1bca1a$export$393edc798c47379d + ); + $parcel$export( + module.exports, + "Close", + () => $f4833395aa1bca1a$export$f39c2d165cd861fe + ); + $parcel$export( + module.exports, + "WarningProvider", + () => $f4833395aa1bca1a$export$69b62a49393917d6 + ); -/***/ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js ***! - \*****************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $g2vWm$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $g2vWm$react = __webpack_require__(/*! react */ "react"); -var $g2vWm$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $g2vWm$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $g2vWm$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $g2vWm$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $g2vWm$radixuireactuseescapekeydown = __webpack_require__(/*! @radix-ui/react-use-escape-keydown */ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "DismissableLayer", () => $d715e0554b679f1f$export$177fb62ff3ec1f22); -$parcel$export(module.exports, "DismissableLayerBranch", () => $d715e0554b679f1f$export$4d5eb2109db14228); -$parcel$export(module.exports, "Root", () => $d715e0554b679f1f$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Branch", () => $d715e0554b679f1f$export$aecb2ddcb55c95be); - -/* ------------------------------------------------------------------------------------------------- - * DismissableLayer - * -----------------------------------------------------------------------------------------------*/ -const $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME = 'DismissableLayer'; -const $d715e0554b679f1f$var$CONTEXT_UPDATE = 'dismissableLayer.update'; -const $d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside'; -const $d715e0554b679f1f$var$FOCUS_OUTSIDE = 'dismissableLayer.focusOutside'; -let $d715e0554b679f1f$var$originalBodyPointerEvents; -const $d715e0554b679f1f$var$DismissableLayerContext = /*#__PURE__*/$g2vWm$react.createContext({ - layers: new Set(), - layersWithOutsidePointerEventsDisabled: new Set(), - branches: new Set() -}); -const $d715e0554b679f1f$export$177fb62ff3ec1f22 = /*#__PURE__*/$g2vWm$react.forwardRef((props, forwardedRef) => { - var _node$ownerDocument; - const { - disableOutsidePointerEvents = false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - ...layerProps - } = props; - const context = $g2vWm$react.useContext($d715e0554b679f1f$var$DismissableLayerContext); - const [node1, setNode] = $g2vWm$react.useState(null); - const ownerDocument = (_node$ownerDocument = node1 === null || node1 === void 0 ? void 0 : node1.ownerDocument) !== null && _node$ownerDocument !== void 0 ? _node$ownerDocument : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document; - const [, force] = $g2vWm$react.useState({}); - const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs(forwardedRef, node => setNode(node)); - const layers = Array.from(context.layers); - const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore - const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore - const index = node1 ? layers.indexOf(node1) : -1; - const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0; - const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex; - const pointerDownOutside = $d715e0554b679f1f$var$usePointerDownOutside(event => { - const target = event.target; - const isPointerDownOnBranch = [...context.branches].some(branch => branch.contains(target)); - if (!isPointerEventsEnabled || isPointerDownOnBranch) return; - onPointerDownOutside === null || onPointerDownOutside === void 0 || onPointerDownOutside(event); - onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); - if (!event.defaultPrevented) onDismiss === null || onDismiss === void 0 || onDismiss(); - }, ownerDocument); - const focusOutside = $d715e0554b679f1f$var$useFocusOutside(event => { - const target = event.target; - const isFocusInBranch = [...context.branches].some(branch => branch.contains(target)); - if (isFocusInBranch) return; - onFocusOutside === null || onFocusOutside === void 0 || onFocusOutside(event); - onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event); - if (!event.defaultPrevented) onDismiss === null || onDismiss === void 0 || onDismiss(); - }, ownerDocument); - $g2vWm$radixuireactuseescapekeydown.useEscapeKeydown(event => { - const isHighestLayer = index === context.layers.size - 1; - if (!isHighestLayer) return; - onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event); - if (!event.defaultPrevented && onDismiss) { - event.preventDefault(); - onDismiss(); - } - }, ownerDocument); - $g2vWm$react.useEffect(() => { - if (!node1) return; - if (disableOutsidePointerEvents) { - if (context.layersWithOutsidePointerEventsDisabled.size === 0) { - $d715e0554b679f1f$var$originalBodyPointerEvents = ownerDocument.body.style.pointerEvents; - ownerDocument.body.style.pointerEvents = 'none'; - } - context.layersWithOutsidePointerEventsDisabled.add(node1); - } - context.layers.add(node1); - $d715e0554b679f1f$var$dispatchUpdate(); - return () => { - if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) ownerDocument.body.style.pointerEvents = $d715e0554b679f1f$var$originalBodyPointerEvents; - }; - }, [node1, ownerDocument, disableOutsidePointerEvents, context]); - /** - * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect - * because a change to `disableOutsidePointerEvents` would remove this layer from the stack - * and add it to the end again so the layering order wouldn't be _creation order_. - * We only want them to be removed from context stacks when unmounted. - */ - $g2vWm$react.useEffect(() => { - return () => { - if (!node1) return; - context.layers.delete(node1); - context.layersWithOutsidePointerEventsDisabled.delete(node1); - $d715e0554b679f1f$var$dispatchUpdate(); - }; - }, [node1, context]); - $g2vWm$react.useEffect(() => { - const handleUpdate = () => force({}); - document.addEventListener($d715e0554b679f1f$var$CONTEXT_UPDATE, handleUpdate); - return () => document.removeEventListener($d715e0554b679f1f$var$CONTEXT_UPDATE, handleUpdate); - }, []); - return /*#__PURE__*/$g2vWm$react.createElement($g2vWm$radixuireactprimitive.Primitive.div, $parcel$interopDefault($g2vWm$babelruntimehelpersextends)({}, layerProps, { - ref: composedRefs, - style: { - pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? 'auto' : 'none' : undefined, - ...props.style - }, - onFocusCapture: $g2vWm$radixuiprimitive.composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture), - onBlurCapture: $g2vWm$radixuiprimitive.composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture), - onPointerDownCapture: $g2vWm$radixuiprimitive.composeEventHandlers(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture) - })); -}); -/*#__PURE__*/ -Object.assign($d715e0554b679f1f$export$177fb62ff3ec1f22, { - displayName: $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DismissableLayerBranch - * -----------------------------------------------------------------------------------------------*/ -const $d715e0554b679f1f$var$BRANCH_NAME = 'DismissableLayerBranch'; -const $d715e0554b679f1f$export$4d5eb2109db14228 = /*#__PURE__*/$g2vWm$react.forwardRef((props, forwardedRef) => { - const context = $g2vWm$react.useContext($d715e0554b679f1f$var$DismissableLayerContext); - const ref = $g2vWm$react.useRef(null); - const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - $g2vWm$react.useEffect(() => { - const node = ref.current; - if (node) { - context.branches.add(node); - return () => { - context.branches.delete(node); - }; - } - }, [context.branches]); - return /*#__PURE__*/$g2vWm$react.createElement($g2vWm$radixuireactprimitive.Primitive.div, $parcel$interopDefault($g2vWm$babelruntimehelpersextends)({}, props, { - ref: composedRefs - })); -}); -/*#__PURE__*/ -Object.assign($d715e0554b679f1f$export$4d5eb2109db14228, { - displayName: $d715e0554b679f1f$var$BRANCH_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ /** - * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup` - * to mimic layer dismissing behaviour present in OS. - * Returns props to pass to the node we want to check for outside events. - */ -function $d715e0554b679f1f$var$usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const handlePointerDownOutside = $g2vWm$radixuireactusecallbackref.useCallbackRef(onPointerDownOutside); - const isPointerInsideReactTreeRef = $g2vWm$react.useRef(false); - const handleClickRef = $g2vWm$react.useRef(() => {}); - $g2vWm$react.useEffect(() => { - const handlePointerDown = event => { - if (event.target && !isPointerInsideReactTreeRef.current) { - const eventDetail = { - originalEvent: event + /* ------------------------------------------------------------------------------------------------- + * Dialog + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$DIALOG_NAME = "Dialog"; + const [ + $f4833395aa1bca1a$var$createDialogContext, + $f4833395aa1bca1a$export$cc702773b8ea3e41, + ] = $aJCrN$radixuireactcontext.createContextScope( + $f4833395aa1bca1a$var$DIALOG_NAME + ); + const [ + $f4833395aa1bca1a$var$DialogProvider, + $f4833395aa1bca1a$var$useDialogContext, + ] = $f4833395aa1bca1a$var$createDialogContext( + $f4833395aa1bca1a$var$DIALOG_NAME + ); + const $f4833395aa1bca1a$export$3ddf2d174ce01153 = (props) => { + const { + __scopeDialog: __scopeDialog, + children: children, + open: openProp, + defaultOpen: defaultOpen, + onOpenChange: onOpenChange, + modal = true, + } = props; + const triggerRef = $aJCrN$react.useRef(null); + const contentRef = $aJCrN$react.useRef(null); + const [open = false, setOpen] = + $aJCrN$radixuireactusecontrollablestate.useControllableState({ + prop: openProp, + defaultProp: defaultOpen, + onChange: onOpenChange, + }); + return /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$DialogProvider, + { + scope: __scopeDialog, + triggerRef: triggerRef, + contentRef: contentRef, + contentId: $aJCrN$radixuireactid.useId(), + titleId: $aJCrN$radixuireactid.useId(), + descriptionId: $aJCrN$radixuireactid.useId(), + open: open, + onOpenChange: setOpen, + onOpenToggle: $aJCrN$react.useCallback( + () => setOpen((prevOpen) => !prevOpen), + [setOpen] + ), + modal: modal, + }, + children + ); }; - function handleAndDispatchPointerDownOutsideEvent() { - $d715e0554b679f1f$var$handleAndDispatchCustomEvent($d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { - discrete: true - }); - } - /** - * On touch devices, we need to wait for a click event because browsers implement - * a ~350ms delay between the time the user stops touching the display and when the - * browser executres events. We need to ensure we don't reactivate pointer-events within - * this timeframe otherwise the browser may execute events that should have been prevented. - * - * Additionally, this also lets us deal automatically with cancellations when a click event - * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc. - * - * This is why we also continuously remove the previous listener, because we cannot be - * certain that it was raised, and therefore cleaned-up. - */ - if (event.pointerType === 'touch') { - ownerDocument.removeEventListener('click', handleClickRef.current); - handleClickRef.current = handleAndDispatchPointerDownOutsideEvent; - ownerDocument.addEventListener('click', handleClickRef.current, { - once: true - }); - } else handleAndDispatchPointerDownOutsideEvent(); - } - isPointerInsideReactTreeRef.current = false; - }; - /** - * if this hook executes in a component that mounts via a `pointerdown` event, the event - * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid - * this by delaying the event listener registration on the document. - * This is not React specific, but rather how the DOM works, ie: - * ``` - * button.addEventListener('pointerdown', () => { - * console.log('I will log'); - * document.addEventListener('pointerdown', () => { - * console.log('I will also log'); - * }) - * }); - */ - const timerId = window.setTimeout(() => { - ownerDocument.addEventListener('pointerdown', handlePointerDown); - }, 0); - return () => { - window.clearTimeout(timerId); - ownerDocument.removeEventListener('pointerdown', handlePointerDown); - ownerDocument.removeEventListener('click', handleClickRef.current); - }; - }, [ownerDocument, handlePointerDownOutside]); - return { - // ensures we check React component tree (not just DOM tree) - onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true - }; -} -/** - * Listens for when focus happens outside a react subtree. - * Returns props to pass to the root (node) of the subtree we want to check. - */ -function $d715e0554b679f1f$var$useFocusOutside(onFocusOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const handleFocusOutside = $g2vWm$radixuireactusecallbackref.useCallbackRef(onFocusOutside); - const isFocusInsideReactTreeRef = $g2vWm$react.useRef(false); - $g2vWm$react.useEffect(() => { - const handleFocus = event => { - if (event.target && !isFocusInsideReactTreeRef.current) { - const eventDetail = { - originalEvent: event + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$3ddf2d174ce01153, { + displayName: $f4833395aa1bca1a$var$DIALOG_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DialogTrigger + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$TRIGGER_NAME = "DialogTrigger"; + const $f4833395aa1bca1a$export$2e1e1122cf0cba88 = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const { __scopeDialog: __scopeDialog, ...triggerProps } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$TRIGGER_NAME, + __scopeDialog + ); + const composedTriggerRef = + $aJCrN$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + context.triggerRef + ); + return /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactprimitive.Primitive.button, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + { + type: "button", + "aria-haspopup": "dialog", + "aria-expanded": context.open, + "aria-controls": context.contentId, + "data-state": $f4833395aa1bca1a$var$getState(context.open), + }, + triggerProps, + { + ref: composedTriggerRef, + onClick: $aJCrN$radixuiprimitive.composeEventHandlers( + props.onClick, + context.onOpenToggle + ), + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$2e1e1122cf0cba88, { + displayName: $f4833395aa1bca1a$var$TRIGGER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DialogPortal + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$PORTAL_NAME = "DialogPortal"; + const [ + $f4833395aa1bca1a$var$PortalProvider, + $f4833395aa1bca1a$var$usePortalContext, + ] = $f4833395aa1bca1a$var$createDialogContext( + $f4833395aa1bca1a$var$PORTAL_NAME, + { + forceMount: undefined, + } + ); + const $f4833395aa1bca1a$export$dad7c95542bacce0 = (props) => { + const { + __scopeDialog: __scopeDialog, + forceMount: forceMount, + children: children, + container: container, + } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$PORTAL_NAME, + __scopeDialog + ); + return /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$PortalProvider, + { + scope: __scopeDialog, + forceMount: forceMount, + }, + $aJCrN$react.Children.map(children, (child) => + /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactportal.Portal, + { + asChild: true, + container: container, + }, + child + ) + ) + ) + ); }; - $d715e0554b679f1f$var$handleAndDispatchCustomEvent($d715e0554b679f1f$var$FOCUS_OUTSIDE, handleFocusOutside, eventDetail, { - discrete: false + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$dad7c95542bacce0, { + displayName: $f4833395aa1bca1a$var$PORTAL_NAME, }); - } - }; - ownerDocument.addEventListener('focusin', handleFocus); - return () => ownerDocument.removeEventListener('focusin', handleFocus); - }, [ownerDocument, handleFocusOutside]); - return { - onFocusCapture: () => isFocusInsideReactTreeRef.current = true, - onBlurCapture: () => isFocusInsideReactTreeRef.current = false - }; -} -function $d715e0554b679f1f$var$dispatchUpdate() { - const event = new CustomEvent($d715e0554b679f1f$var$CONTEXT_UPDATE); - document.dispatchEvent(event); -} -function $d715e0554b679f1f$var$handleAndDispatchCustomEvent(name, handler, detail, { - discrete: discrete -}) { - const target = detail.originalEvent.target; - const event = new CustomEvent(name, { - bubbles: false, - cancelable: true, - detail: detail - }); - if (handler) target.addEventListener(name, handler, { - once: true - }); - if (discrete) $g2vWm$radixuireactprimitive.dispatchDiscreteCustomEvent(target, event);else target.dispatchEvent(event); -} -const $d715e0554b679f1f$export$be92b6f5f03c0fe9 = $d715e0554b679f1f$export$177fb62ff3ec1f22; -const $d715e0554b679f1f$export$aecb2ddcb55c95be = $d715e0554b679f1f$export$4d5eb2109db14228; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js": -/*!*************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js ***! - \*************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $7dQ7Q$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $7dQ7Q$react = __webpack_require__(/*! react */ "react"); -var $7dQ7Q$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $7dQ7Q$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $7dQ7Q$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $7dQ7Q$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $7dQ7Q$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $7dQ7Q$radixuireactmenu = __webpack_require__(/*! @radix-ui/react-menu */ "../../../node_modules/@radix-ui/react-menu/dist/index.js"); -var $7dQ7Q$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createDropdownMenuScope", () => $d1bf075a6b218014$export$c0623cd925aeb687); -$parcel$export(module.exports, "DropdownMenu", () => $d1bf075a6b218014$export$e44a253a59704894); -$parcel$export(module.exports, "DropdownMenuTrigger", () => $d1bf075a6b218014$export$d2469213b3befba9); -$parcel$export(module.exports, "DropdownMenuPortal", () => $d1bf075a6b218014$export$cd369b4d4d54efc9); -$parcel$export(module.exports, "DropdownMenuContent", () => $d1bf075a6b218014$export$6e76d93a37c01248); -$parcel$export(module.exports, "DropdownMenuGroup", () => $d1bf075a6b218014$export$246bebaba3a2f70e); -$parcel$export(module.exports, "DropdownMenuLabel", () => $d1bf075a6b218014$export$76e48c5b57f24495); -$parcel$export(module.exports, "DropdownMenuItem", () => $d1bf075a6b218014$export$ed97964d1871885d); -$parcel$export(module.exports, "DropdownMenuCheckboxItem", () => $d1bf075a6b218014$export$53a69729da201fa9); -$parcel$export(module.exports, "DropdownMenuRadioGroup", () => $d1bf075a6b218014$export$3323ad73d55f587e); -$parcel$export(module.exports, "DropdownMenuRadioItem", () => $d1bf075a6b218014$export$e4f69b41b1637536); -$parcel$export(module.exports, "DropdownMenuItemIndicator", () => $d1bf075a6b218014$export$42355ae145153fb6); -$parcel$export(module.exports, "DropdownMenuSeparator", () => $d1bf075a6b218014$export$da160178fd3bc7e9); -$parcel$export(module.exports, "DropdownMenuArrow", () => $d1bf075a6b218014$export$34b8980744021ec5); -$parcel$export(module.exports, "DropdownMenuSub", () => $d1bf075a6b218014$export$2f307d81a64f5442); -$parcel$export(module.exports, "DropdownMenuSubTrigger", () => $d1bf075a6b218014$export$21dcb7ec56f874cf); -$parcel$export(module.exports, "DropdownMenuSubContent", () => $d1bf075a6b218014$export$f34ec8bc2482cc5f); -$parcel$export(module.exports, "Root", () => $d1bf075a6b218014$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Trigger", () => $d1bf075a6b218014$export$41fb9f06171c75f4); -$parcel$export(module.exports, "Portal", () => $d1bf075a6b218014$export$602eac185826482c); -$parcel$export(module.exports, "Content", () => $d1bf075a6b218014$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Group", () => $d1bf075a6b218014$export$eb2fcfdbd7ba97d4); -$parcel$export(module.exports, "Label", () => $d1bf075a6b218014$export$b04be29aa201d4f5); -$parcel$export(module.exports, "Item", () => $d1bf075a6b218014$export$6d08773d2e66f8f2); -$parcel$export(module.exports, "CheckboxItem", () => $d1bf075a6b218014$export$16ce288f89fa631c); -$parcel$export(module.exports, "RadioGroup", () => $d1bf075a6b218014$export$a98f0dcb43a68a25); -$parcel$export(module.exports, "RadioItem", () => $d1bf075a6b218014$export$371ab307eab489c0); -$parcel$export(module.exports, "ItemIndicator", () => $d1bf075a6b218014$export$c3468e2714d175fa); -$parcel$export(module.exports, "Separator", () => $d1bf075a6b218014$export$1ff3c3f08ae963c0); -$parcel$export(module.exports, "Arrow", () => $d1bf075a6b218014$export$21b07c8f274aebd5); -$parcel$export(module.exports, "Sub", () => $d1bf075a6b218014$export$d7a01e11500dfb6f); -$parcel$export(module.exports, "SubTrigger", () => $d1bf075a6b218014$export$2ea8a7a591ac5eac); -$parcel$export(module.exports, "SubContent", () => $d1bf075a6b218014$export$6d4de93b380beddf); - -/* ------------------------------------------------------------------------------------------------- - * DropdownMenu - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$DROPDOWN_MENU_NAME = 'DropdownMenu'; -const [$d1bf075a6b218014$var$createDropdownMenuContext, $d1bf075a6b218014$export$c0623cd925aeb687] = $7dQ7Q$radixuireactcontext.createContextScope($d1bf075a6b218014$var$DROPDOWN_MENU_NAME, [$7dQ7Q$radixuireactmenu.createMenuScope]); -const $d1bf075a6b218014$var$useMenuScope = $7dQ7Q$radixuireactmenu.createMenuScope(); -const [$d1bf075a6b218014$var$DropdownMenuProvider, $d1bf075a6b218014$var$useDropdownMenuContext] = $d1bf075a6b218014$var$createDropdownMenuContext($d1bf075a6b218014$var$DROPDOWN_MENU_NAME); -const $d1bf075a6b218014$export$e44a253a59704894 = props => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - children: children, - dir: dir, - open: openProp, - defaultOpen: defaultOpen, - onOpenChange: onOpenChange, - modal = true - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const triggerRef = $7dQ7Q$react.useRef(null); - const [open = false, setOpen] = $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange - }); - return /*#__PURE__*/$7dQ7Q$react.createElement($d1bf075a6b218014$var$DropdownMenuProvider, { - scope: __scopeDropdownMenu, - triggerId: $7dQ7Q$radixuireactid.useId(), - triggerRef: triggerRef, - contentId: $7dQ7Q$radixuireactid.useId(), - open: open, - onOpenChange: setOpen, - onOpenToggle: $7dQ7Q$react.useCallback(() => setOpen(prevOpen => !prevOpen), [setOpen]), - modal: modal - }, /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Root, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, { - open: open, - onOpenChange: setOpen, - dir: dir, - modal: modal - }), children)); -}; -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$e44a253a59704894, { - displayName: $d1bf075a6b218014$var$DROPDOWN_MENU_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuTrigger - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$TRIGGER_NAME = 'DropdownMenuTrigger'; -const $d1bf075a6b218014$export$d2469213b3befba9 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - disabled = false, - ...triggerProps - } = props; - const context = $d1bf075a6b218014$var$useDropdownMenuContext($d1bf075a6b218014$var$TRIGGER_NAME, __scopeDropdownMenu); - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Anchor, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({ - asChild: true - }, menuScope), /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactprimitive.Primitive.button, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({ - type: "button", - id: context.triggerId, - "aria-haspopup": "menu", - "aria-expanded": context.open, - "aria-controls": context.open ? context.contentId : undefined, - "data-state": context.open ? 'open' : 'closed', - "data-disabled": disabled ? '' : undefined, - disabled: disabled - }, triggerProps, { - ref: $7dQ7Q$radixuireactcomposerefs.composeRefs(forwardedRef, context.triggerRef), - onPointerDown: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onPointerDown, event => { - // only call handler if it's the left button (mousedown gets triggered by all mouse buttons) - // but not when the control key is pressed (avoiding MacOS right click) - if (!disabled && event.button === 0 && event.ctrlKey === false) { - context.onOpenToggle(); // prevent trigger focusing when opening - // this allows the content to be given focus without competition - if (!context.open) event.preventDefault(); - } - }), - onKeyDown: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - if (disabled) return; - if (['Enter', ' '].includes(event.key)) context.onOpenToggle(); - if (event.key === 'ArrowDown') context.onOpenChange(true); // prevent keydown from scrolling window / first focused item to execute - // that keydown (inadvertently closing the menu) - if (['Enter', ' ', 'ArrowDown'].includes(event.key)) event.preventDefault(); - }) - }))); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$d2469213b3befba9, { - displayName: $d1bf075a6b218014$var$TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuPortal - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$PORTAL_NAME = 'DropdownMenuPortal'; -const $d1bf075a6b218014$export$cd369b4d4d54efc9 = props => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...portalProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Portal, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, portalProps)); -}; -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$cd369b4d4d54efc9, { - displayName: $d1bf075a6b218014$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuContent - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$CONTENT_NAME = 'DropdownMenuContent'; -const $d1bf075a6b218014$export$6e76d93a37c01248 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...contentProps - } = props; - const context = $d1bf075a6b218014$var$useDropdownMenuContext($d1bf075a6b218014$var$CONTENT_NAME, __scopeDropdownMenu); - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const hasInteractedOutsideRef = $7dQ7Q$react.useRef(false); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Content, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({ - id: context.contentId, - "aria-labelledby": context.triggerId - }, menuScope, contentProps, { - ref: forwardedRef, - onCloseAutoFocus: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onCloseAutoFocus, event => { - var _context$triggerRef$c; - if (!hasInteractedOutsideRef.current) (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus(); - hasInteractedOutsideRef.current = false; // Always prevent auto focus because we either focus manually or want user agent focus - event.preventDefault(); - }), - onInteractOutside: $7dQ7Q$radixuiprimitive.composeEventHandlers(props.onInteractOutside, event => { - const originalEvent = event.detail.originalEvent; - const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; - const isRightClick = originalEvent.button === 2 || ctrlLeftClick; - if (!context.modal || isRightClick) hasInteractedOutsideRef.current = true; - }), - style: { - ...props.style, - '--radix-dropdown-menu-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-dropdown-menu-content-available-width': 'var(--radix-popper-available-width)', - '--radix-dropdown-menu-content-available-height': 'var(--radix-popper-available-height)', - '--radix-dropdown-menu-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-dropdown-menu-trigger-height': 'var(--radix-popper-anchor-height)' - } - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$6e76d93a37c01248, { - displayName: $d1bf075a6b218014$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuGroup - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$GROUP_NAME = 'DropdownMenuGroup'; -const $d1bf075a6b218014$export$246bebaba3a2f70e = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...groupProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Group, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, groupProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$246bebaba3a2f70e, { - displayName: $d1bf075a6b218014$var$GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuLabel - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$LABEL_NAME = 'DropdownMenuLabel'; -const $d1bf075a6b218014$export$76e48c5b57f24495 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...labelProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Label, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, labelProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$76e48c5b57f24495, { - displayName: $d1bf075a6b218014$var$LABEL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuItem - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$ITEM_NAME = 'DropdownMenuItem'; -const $d1bf075a6b218014$export$ed97964d1871885d = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...itemProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Item, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, itemProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$ed97964d1871885d, { - displayName: $d1bf075a6b218014$var$ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuCheckboxItem - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME = 'DropdownMenuCheckboxItem'; -const $d1bf075a6b218014$export$53a69729da201fa9 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...checkboxItemProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.CheckboxItem, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, checkboxItemProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$53a69729da201fa9, { - displayName: $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuRadioGroup - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$RADIO_GROUP_NAME = 'DropdownMenuRadioGroup'; -const $d1bf075a6b218014$export$3323ad73d55f587e = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...radioGroupProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.RadioGroup, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, radioGroupProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$3323ad73d55f587e, { - displayName: $d1bf075a6b218014$var$RADIO_GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuRadioItem - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$RADIO_ITEM_NAME = 'DropdownMenuRadioItem'; -const $d1bf075a6b218014$export$e4f69b41b1637536 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...radioItemProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.RadioItem, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, radioItemProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$e4f69b41b1637536, { - displayName: $d1bf075a6b218014$var$RADIO_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuItemIndicator - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$INDICATOR_NAME = 'DropdownMenuItemIndicator'; -const $d1bf075a6b218014$export$42355ae145153fb6 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...itemIndicatorProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.ItemIndicator, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, itemIndicatorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$42355ae145153fb6, { - displayName: $d1bf075a6b218014$var$INDICATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSeparator - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$SEPARATOR_NAME = 'DropdownMenuSeparator'; -const $d1bf075a6b218014$export$da160178fd3bc7e9 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...separatorProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Separator, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, separatorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$da160178fd3bc7e9, { - displayName: $d1bf075a6b218014$var$SEPARATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuArrow - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$ARROW_NAME = 'DropdownMenuArrow'; -const $d1bf075a6b218014$export$34b8980744021ec5 = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...arrowProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Arrow, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, arrowProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$34b8980744021ec5, { - displayName: $d1bf075a6b218014$var$ARROW_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSub - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$export$2f307d81a64f5442 = props => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - children: children, - open: openProp, - onOpenChange: onOpenChange, - defaultOpen: defaultOpen - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const [open = false, setOpen] = $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange - }); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.Sub, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, { - open: open, - onOpenChange: setOpen - }), children); -}; -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSubTrigger - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$SUB_TRIGGER_NAME = 'DropdownMenuSubTrigger'; -const $d1bf075a6b218014$export$21dcb7ec56f874cf = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...subTriggerProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.SubTrigger, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, subTriggerProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$21dcb7ec56f874cf, { - displayName: $d1bf075a6b218014$var$SUB_TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * DropdownMenuSubContent - * -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$var$SUB_CONTENT_NAME = 'DropdownMenuSubContent'; -const $d1bf075a6b218014$export$f34ec8bc2482cc5f = /*#__PURE__*/$7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...subContentProps - } = props; - const menuScope = $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/$7dQ7Q$react.createElement($7dQ7Q$radixuireactmenu.SubContent, $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)({}, menuScope, subContentProps, { - ref: forwardedRef, - style: { - ...props.style, - '--radix-dropdown-menu-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-dropdown-menu-content-available-width': 'var(--radix-popper-available-width)', - '--radix-dropdown-menu-content-available-height': 'var(--radix-popper-available-height)', - '--radix-dropdown-menu-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-dropdown-menu-trigger-height': 'var(--radix-popper-anchor-height)' - } - })); -}); -/*#__PURE__*/ -Object.assign($d1bf075a6b218014$export$f34ec8bc2482cc5f, { - displayName: $d1bf075a6b218014$var$SUB_CONTENT_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $d1bf075a6b218014$export$be92b6f5f03c0fe9 = $d1bf075a6b218014$export$e44a253a59704894; -const $d1bf075a6b218014$export$41fb9f06171c75f4 = $d1bf075a6b218014$export$d2469213b3befba9; -const $d1bf075a6b218014$export$602eac185826482c = $d1bf075a6b218014$export$cd369b4d4d54efc9; -const $d1bf075a6b218014$export$7c6e2c02157bb7d2 = $d1bf075a6b218014$export$6e76d93a37c01248; -const $d1bf075a6b218014$export$eb2fcfdbd7ba97d4 = $d1bf075a6b218014$export$246bebaba3a2f70e; -const $d1bf075a6b218014$export$b04be29aa201d4f5 = $d1bf075a6b218014$export$76e48c5b57f24495; -const $d1bf075a6b218014$export$6d08773d2e66f8f2 = $d1bf075a6b218014$export$ed97964d1871885d; -const $d1bf075a6b218014$export$16ce288f89fa631c = $d1bf075a6b218014$export$53a69729da201fa9; -const $d1bf075a6b218014$export$a98f0dcb43a68a25 = $d1bf075a6b218014$export$3323ad73d55f587e; -const $d1bf075a6b218014$export$371ab307eab489c0 = $d1bf075a6b218014$export$e4f69b41b1637536; -const $d1bf075a6b218014$export$c3468e2714d175fa = $d1bf075a6b218014$export$42355ae145153fb6; -const $d1bf075a6b218014$export$1ff3c3f08ae963c0 = $d1bf075a6b218014$export$da160178fd3bc7e9; -const $d1bf075a6b218014$export$21b07c8f274aebd5 = $d1bf075a6b218014$export$34b8980744021ec5; -const $d1bf075a6b218014$export$d7a01e11500dfb6f = $d1bf075a6b218014$export$2f307d81a64f5442; -const $d1bf075a6b218014$export$2ea8a7a591ac5eac = $d1bf075a6b218014$export$21dcb7ec56f874cf; -const $d1bf075a6b218014$export$6d4de93b380beddf = $d1bf075a6b218014$export$f34ec8bc2482cc5f; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-focus-guards/dist/index.js ***! - \************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /* ------------------------------------------------------------------------------------------------- + * DialogOverlay + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$OVERLAY_NAME = "DialogOverlay"; + const $f4833395aa1bca1a$export$bd1d06c79be19e17 = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const portalContext = $f4833395aa1bca1a$var$usePortalContext( + $f4833395aa1bca1a$var$OVERLAY_NAME, + props.__scopeDialog + ); + const { forceMount = portalContext.forceMount, ...overlayProps } = + props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$OVERLAY_NAME, + props.__scopeDialog + ); + return context.modal + ? /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$DialogOverlayImpl, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + {}, + overlayProps, + { + ref: forwardedRef, + } + ) + ) + ) + : null; + }); + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$bd1d06c79be19e17, { + displayName: $f4833395aa1bca1a$var$OVERLAY_NAME, + }); + const $f4833395aa1bca1a$var$DialogOverlayImpl = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const { __scopeDialog: __scopeDialog, ...overlayProps } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$OVERLAY_NAME, + __scopeDialog + ); + return ( + /*#__PURE__*/ // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll` + // ie. when `Overlay` and `Content` are siblings + $aJCrN$react.createElement( + $aJCrN$reactremovescroll.RemoveScroll, + { + as: $aJCrN$radixuireactslot.Slot, + allowPinchZoom: true, + shards: [context.contentRef], + }, + /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + { + "data-state": $f4833395aa1bca1a$var$getState( + context.open + ), + }, + overlayProps, + { + ref: forwardedRef, // We re-enable pointer-events prevented by `Dialog.Content` to allow scrolling the overlay. + style: { + pointerEvents: "auto", + ...overlayProps.style, + }, + } + ) + ) + ) + ); + }); + /* ------------------------------------------------------------------------------------------------- + * DialogContent + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$CONTENT_NAME = "DialogContent"; + const $f4833395aa1bca1a$export$b6d9565de1e068cf = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const portalContext = $f4833395aa1bca1a$var$usePortalContext( + $f4833395aa1bca1a$var$CONTENT_NAME, + props.__scopeDialog + ); + const { forceMount = portalContext.forceMount, ...contentProps } = + props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$CONTENT_NAME, + props.__scopeDialog + ); + return /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + context.modal + ? /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$DialogContentModal, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + {}, + contentProps, + { + ref: forwardedRef, + } + ) + ) + : /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$DialogContentNonModal, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + {}, + contentProps, + { + ref: forwardedRef, + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$b6d9565de1e068cf, { + displayName: $f4833395aa1bca1a$var$CONTENT_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$DialogContentModal = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$CONTENT_NAME, + props.__scopeDialog + ); + const contentRef = $aJCrN$react.useRef(null); + const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + context.contentRef, + contentRef + ); // aria-hide everything except the content (better supported equivalent to setting aria-modal) + $aJCrN$react.useEffect(() => { + const content = contentRef.current; + if (content) return $aJCrN$ariahidden.hideOthers(content); + }, []); + return /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$DialogContentImpl, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + {}, + props, + { + ref: composedRefs, // we make sure focus isn't trapped once `DialogContent` has been closed + trapFocus: context.open, + disableOutsidePointerEvents: true, + onCloseAutoFocus: + $aJCrN$radixuiprimitive.composeEventHandlers( + props.onCloseAutoFocus, + (event) => { + var _context$triggerRef$c; + event.preventDefault(); + (_context$triggerRef$c = context.triggerRef.current) === + null || + _context$triggerRef$c === void 0 || + _context$triggerRef$c.focus(); + } + ), + onPointerDownOutside: + $aJCrN$radixuiprimitive.composeEventHandlers( + props.onPointerDownOutside, + (event) => { + const originalEvent = event.detail.originalEvent; + const ctrlLeftClick = + originalEvent.button === 0 && + originalEvent.ctrlKey === true; + const isRightClick = + originalEvent.button === 2 || ctrlLeftClick; // If the event is a right-click, we shouldn't close because + // it is effectively as if we right-clicked the `Overlay`. + if (isRightClick) event.preventDefault(); + } + ), // When focus is trapped, a `focusout` event may still happen. + onFocusOutside: $aJCrN$radixuiprimitive.composeEventHandlers( + props.onFocusOutside, + (event) => event.preventDefault() + ), + } + ) + ); + }); + /* -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$DialogContentNonModal = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$CONTENT_NAME, + props.__scopeDialog + ); + const hasInteractedOutsideRef = $aJCrN$react.useRef(false); + const hasPointerDownOutsideRef = $aJCrN$react.useRef(false); + return /*#__PURE__*/ $aJCrN$react.createElement( + $f4833395aa1bca1a$var$DialogContentImpl, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + {}, + props, + { + ref: forwardedRef, + trapFocus: false, + disableOutsidePointerEvents: false, + onCloseAutoFocus: (event) => { + var _props$onCloseAutoFoc; + (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || + _props$onCloseAutoFoc === void 0 || + _props$onCloseAutoFoc.call(props, event); + if (!event.defaultPrevented) { + var _context$triggerRef$c2; + if (!hasInteractedOutsideRef.current) + (_context$triggerRef$c2 = + context.triggerRef.current) === null || + _context$triggerRef$c2 === void 0 || + _context$triggerRef$c2.focus(); // Always prevent auto focus because we either focus manually or want user agent focus + event.preventDefault(); + } + hasInteractedOutsideRef.current = false; + hasPointerDownOutsideRef.current = false; + }, + onInteractOutside: (event) => { + var _props$onInteractOuts, _context$triggerRef$c3; + (_props$onInteractOuts = props.onInteractOutside) === + null || + _props$onInteractOuts === void 0 || + _props$onInteractOuts.call(props, event); + if (!event.defaultPrevented) { + hasInteractedOutsideRef.current = true; + if (event.detail.originalEvent.type === "pointerdown") + hasPointerDownOutsideRef.current = true; + } // Prevent dismissing when clicking the trigger. + // As the trigger is already setup to close, without doing so would + // cause it to close and immediately open. + const target = event.target; + const targetIsTrigger = + (_context$triggerRef$c3 = context.triggerRef.current) === + null || _context$triggerRef$c3 === void 0 + ? void 0 + : _context$triggerRef$c3.contains(target); + if (targetIsTrigger) event.preventDefault(); // On Safari if the trigger is inside a container with tabIndex={0}, when clicked + // we will get the pointer down outside event on the trigger, but then a subsequent + // focus outside event on the container, we ignore any focus outside event when we've + // already had a pointer down outside event. + if ( + event.detail.originalEvent.type === "focusin" && + hasPointerDownOutsideRef.current + ) + event.preventDefault(); + }, + } + ) + ); + }); + /* -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$DialogContentImpl = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const { + __scopeDialog: __scopeDialog, + trapFocus: trapFocus, + onOpenAutoFocus: onOpenAutoFocus, + onCloseAutoFocus: onCloseAutoFocus, + ...contentProps + } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$CONTENT_NAME, + __scopeDialog + ); + const contentRef = $aJCrN$react.useRef(null); + const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + contentRef + ); // Make sure the whole tree has focus guards as our `Dialog` will be + // the last element in the DOM (beacuse of the `Portal`) + $aJCrN$radixuireactfocusguards.useFocusGuards(); + return /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$react.Fragment, + null, + /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactfocusscope.FocusScope, + { + asChild: true, + loop: true, + trapped: trapFocus, + onMountAutoFocus: onOpenAutoFocus, + onUnmountAutoFocus: onCloseAutoFocus, + }, + /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactdismissablelayer.DismissableLayer, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + { + role: "dialog", + id: context.contentId, + "aria-describedby": context.descriptionId, + "aria-labelledby": context.titleId, + "data-state": $f4833395aa1bca1a$var$getState( + context.open + ), + }, + contentProps, + { + ref: composedRefs, + onDismiss: () => context.onOpenChange(false), + } + ) + ) + ), + false + ); + }); + /* ------------------------------------------------------------------------------------------------- + * DialogTitle + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$TITLE_NAME = "DialogTitle"; + const $f4833395aa1bca1a$export$16f7638e4a34b909 = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const { __scopeDialog: __scopeDialog, ...titleProps } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$TITLE_NAME, + __scopeDialog + ); + return /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactprimitive.Primitive.h2, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + { + id: context.titleId, + }, + titleProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$16f7638e4a34b909, { + displayName: $f4833395aa1bca1a$var$TITLE_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DialogDescription + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$DESCRIPTION_NAME = "DialogDescription"; + const $f4833395aa1bca1a$export$94e94c2ec2c954d5 = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const { __scopeDialog: __scopeDialog, ...descriptionProps } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$DESCRIPTION_NAME, + __scopeDialog + ); + return /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactprimitive.Primitive.p, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + { + id: context.descriptionId, + }, + descriptionProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$94e94c2ec2c954d5, { + displayName: $f4833395aa1bca1a$var$DESCRIPTION_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DialogClose + * -----------------------------------------------------------------------------------------------*/ + const $f4833395aa1bca1a$var$CLOSE_NAME = "DialogClose"; + const $f4833395aa1bca1a$export$fba2fb7cd781b7ac = + /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { + const { __scopeDialog: __scopeDialog, ...closeProps } = props; + const context = $f4833395aa1bca1a$var$useDialogContext( + $f4833395aa1bca1a$var$CLOSE_NAME, + __scopeDialog + ); + return /*#__PURE__*/ $aJCrN$react.createElement( + $aJCrN$radixuireactprimitive.Primitive.button, + $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( + { + type: "button", + }, + closeProps, + { + ref: forwardedRef, + onClick: $aJCrN$radixuiprimitive.composeEventHandlers( + props.onClick, + () => context.onOpenChange(false) + ), + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($f4833395aa1bca1a$export$fba2fb7cd781b7ac, { + displayName: $f4833395aa1bca1a$var$CLOSE_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + function $f4833395aa1bca1a$var$getState(open) { + return open ? "open" : "closed"; + } + const $f4833395aa1bca1a$var$TITLE_WARNING_NAME = "DialogTitleWarning"; + const [ + $f4833395aa1bca1a$export$69b62a49393917d6, + $f4833395aa1bca1a$var$useWarningContext, + ] = $aJCrN$radixuireactcontext.createContext( + $f4833395aa1bca1a$var$TITLE_WARNING_NAME, + { + contentName: $f4833395aa1bca1a$var$CONTENT_NAME, + titleName: $f4833395aa1bca1a$var$TITLE_NAME, + docsSlug: "dialog", + } + ); + const $f4833395aa1bca1a$var$TitleWarning = ({ titleId: titleId }) => { + const titleWarningContext = $f4833395aa1bca1a$var$useWarningContext( + $f4833395aa1bca1a$var$TITLE_WARNING_NAME + ); + const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users. +If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component. +For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`; + $aJCrN$react.useEffect(() => { + if (titleId) { + const hasTitle = document.getElementById(titleId); + if (!hasTitle) throw new Error(MESSAGE); + } + }, [MESSAGE, titleId]); + return null; + }; + const $f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME = + "DialogDescriptionWarning"; + const $f4833395aa1bca1a$var$DescriptionWarning = ({ + contentRef: contentRef, + descriptionId: descriptionId, + }) => { + const descriptionWarningContext = + $f4833395aa1bca1a$var$useWarningContext( + $f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME + ); + const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`; + $aJCrN$react.useEffect(() => { + var _contentRef$current; + const describedById = + (_contentRef$current = contentRef.current) === null || + _contentRef$current === void 0 + ? void 0 + : _contentRef$current.getAttribute("aria-describedby"); // if we have an id and the user hasn't set aria-describedby={undefined} + if (descriptionId && describedById) { + const hasDescription = document.getElementById(descriptionId); + if (!hasDescription) console.warn(MESSAGE); + } + }, [MESSAGE, contentRef, descriptionId]); + return null; + }; + const $f4833395aa1bca1a$export$be92b6f5f03c0fe9 = + $f4833395aa1bca1a$export$3ddf2d174ce01153; + const $f4833395aa1bca1a$export$41fb9f06171c75f4 = + $f4833395aa1bca1a$export$2e1e1122cf0cba88; + const $f4833395aa1bca1a$export$602eac185826482c = + $f4833395aa1bca1a$export$dad7c95542bacce0; + const $f4833395aa1bca1a$export$c6fdb837b070b4ff = + $f4833395aa1bca1a$export$bd1d06c79be19e17; + const $f4833395aa1bca1a$export$7c6e2c02157bb7d2 = + $f4833395aa1bca1a$export$b6d9565de1e068cf; + const $f4833395aa1bca1a$export$f99233281efd08a0 = + $f4833395aa1bca1a$export$16f7638e4a34b909; + const $f4833395aa1bca1a$export$393edc798c47379d = + $f4833395aa1bca1a$export$94e94c2ec2c954d5; + const $f4833395aa1bca1a$export$f39c2d165cd861fe = + $f4833395aa1bca1a$export$fba2fb7cd781b7ac; + + /***/ + }, -var $cnctE$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "FocusGuards", () => $71476a6ed7dbbaf3$export$ac5b58043b79449b); -$parcel$export(module.exports, "Root", () => $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "useFocusGuards", () => $71476a6ed7dbbaf3$export$b7ece24a22aeda8c); - -/** Number of components which have requested interest to have focus guards */ -let $71476a6ed7dbbaf3$var$count = 0; -function $71476a6ed7dbbaf3$export$ac5b58043b79449b(props) { - $71476a6ed7dbbaf3$export$b7ece24a22aeda8c(); - return props.children; -} -/** - * Injects a pair of focus guards at the edges of the whole DOM tree - * to ensure `focusin` & `focusout` events can be caught consistently. - */ -function $71476a6ed7dbbaf3$export$b7ece24a22aeda8c() { - $cnctE$react.useEffect(() => { - var _edgeGuards$, _edgeGuards$2; - const edgeGuards = document.querySelectorAll('[data-radix-focus-guard]'); - document.body.insertAdjacentElement('afterbegin', (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 ? _edgeGuards$ : $71476a6ed7dbbaf3$var$createFocusGuard()); - document.body.insertAdjacentElement('beforeend', (_edgeGuards$2 = edgeGuards[1]) !== null && _edgeGuards$2 !== void 0 ? _edgeGuards$2 : $71476a6ed7dbbaf3$var$createFocusGuard()); - $71476a6ed7dbbaf3$var$count++; - return () => { - if ($71476a6ed7dbbaf3$var$count === 1) document.querySelectorAll('[data-radix-focus-guard]').forEach(node => node.remove()); - $71476a6ed7dbbaf3$var$count--; - }; - }, []); -} -function $71476a6ed7dbbaf3$var$createFocusGuard() { - const element = document.createElement('span'); - element.setAttribute('data-radix-focus-guard', ''); - element.tabIndex = 0; - element.style.cssText = 'outline: none; opacity: 0; position: fixed; pointer-events: none'; - return element; -} -const $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9 = $71476a6ed7dbbaf3$export$ac5b58043b79449b; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-focus-scope/dist/index.js ***! - \***********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /***/ "../../../node_modules/@radix-ui/react-direction/dist/index.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-direction/dist/index.js ***! + \*********************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $9g4ps$react = __webpack_require__(/*! react */ "react"); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "useDirection", + () => $cc45c1b701a63adc$export$b39126d51d94e6f3 + ); + $parcel$export( + module.exports, + "Provider", + () => $cc45c1b701a63adc$export$2881499e37b75b9a + ); + $parcel$export( + module.exports, + "DirectionProvider", + () => $cc45c1b701a63adc$export$c760c09fdd558351 + ); + const $cc45c1b701a63adc$var$DirectionContext = + /*#__PURE__*/ $9g4ps$react.createContext(undefined); + /* ------------------------------------------------------------------------------------------------- + * Direction + * -----------------------------------------------------------------------------------------------*/ + const $cc45c1b701a63adc$export$c760c09fdd558351 = (props) => { + const { dir: dir, children: children } = props; + return /*#__PURE__*/ $9g4ps$react.createElement( + $cc45c1b701a63adc$var$DirectionContext.Provider, + { + value: dir, + }, + children + ); + }; + /* -----------------------------------------------------------------------------------------------*/ + function $cc45c1b701a63adc$export$b39126d51d94e6f3(localDir) { + const globalDir = $9g4ps$react.useContext( + $cc45c1b701a63adc$var$DirectionContext + ); + return localDir || globalDir || "ltr"; + } + const $cc45c1b701a63adc$export$2881499e37b75b9a = + $cc45c1b701a63adc$export$c760c09fdd558351; + /***/ + }, + /***/ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js ***! + \*****************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $g2vWm$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $g2vWm$react = __webpack_require__(/*! react */ "react"); + var $g2vWm$radixuiprimitive = __webpack_require__( + /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" + ); + var $g2vWm$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $g2vWm$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $g2vWm$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + var $g2vWm$radixuireactuseescapekeydown = __webpack_require__( + /*! @radix-ui/react-use-escape-keydown */ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "DismissableLayer", + () => $d715e0554b679f1f$export$177fb62ff3ec1f22 + ); + $parcel$export( + module.exports, + "DismissableLayerBranch", + () => $d715e0554b679f1f$export$4d5eb2109db14228 + ); + $parcel$export( + module.exports, + "Root", + () => $d715e0554b679f1f$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Branch", + () => $d715e0554b679f1f$export$aecb2ddcb55c95be + ); -var $buum9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $buum9$react = __webpack_require__(/*! react */ "react"); -var $buum9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $buum9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $buum9$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "FocusScope", () => $2bc01e66e04aa9ed$export$20e40289641fbbb6); -$parcel$export(module.exports, "Root", () => $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9); -const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount'; -const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount'; -const $2bc01e66e04aa9ed$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true -}; -/* ------------------------------------------------------------------------------------------------- - * FocusScope - * -----------------------------------------------------------------------------------------------*/ -const $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME = 'FocusScope'; -const $2bc01e66e04aa9ed$export$20e40289641fbbb6 = /*#__PURE__*/$buum9$react.forwardRef((props, forwardedRef) => { - const { - loop = false, - trapped = false, - onMountAutoFocus: onMountAutoFocusProp, - onUnmountAutoFocus: onUnmountAutoFocusProp, - ...scopeProps - } = props; - const [container1, setContainer] = $buum9$react.useState(null); - const onMountAutoFocus = $buum9$radixuireactusecallbackref.useCallbackRef(onMountAutoFocusProp); - const onUnmountAutoFocus = $buum9$radixuireactusecallbackref.useCallbackRef(onUnmountAutoFocusProp); - const lastFocusedElementRef = $buum9$react.useRef(null); - const composedRefs = $buum9$radixuireactcomposerefs.useComposedRefs(forwardedRef, node => setContainer(node)); - const focusScope = $buum9$react.useRef({ - paused: false, - pause() { - this.paused = true; - }, - resume() { - this.paused = false; - } - }).current; // Takes care of trapping focus if focus is moved outside programmatically for example - $buum9$react.useEffect(() => { - if (trapped) { - function handleFocusIn(event) { - if (focusScope.paused || !container1) return; - const target = event.target; - if (container1.contains(target)) lastFocusedElementRef.current = target;else $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { - select: true + /* ------------------------------------------------------------------------------------------------- + * DismissableLayer + * -----------------------------------------------------------------------------------------------*/ + const $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME = "DismissableLayer"; + const $d715e0554b679f1f$var$CONTEXT_UPDATE = "dismissableLayer.update"; + const $d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE = + "dismissableLayer.pointerDownOutside"; + const $d715e0554b679f1f$var$FOCUS_OUTSIDE = + "dismissableLayer.focusOutside"; + let $d715e0554b679f1f$var$originalBodyPointerEvents; + const $d715e0554b679f1f$var$DismissableLayerContext = + /*#__PURE__*/ $g2vWm$react.createContext({ + layers: new Set(), + layersWithOutsidePointerEventsDisabled: new Set(), + branches: new Set(), + }); + const $d715e0554b679f1f$export$177fb62ff3ec1f22 = + /*#__PURE__*/ $g2vWm$react.forwardRef((props, forwardedRef) => { + var _node$ownerDocument; + const { + disableOutsidePointerEvents = false, + onEscapeKeyDown: onEscapeKeyDown, + onPointerDownOutside: onPointerDownOutside, + onFocusOutside: onFocusOutside, + onInteractOutside: onInteractOutside, + onDismiss: onDismiss, + ...layerProps + } = props; + const context = $g2vWm$react.useContext( + $d715e0554b679f1f$var$DismissableLayerContext + ); + const [node1, setNode] = $g2vWm$react.useState(null); + const ownerDocument = + (_node$ownerDocument = + node1 === null || node1 === void 0 + ? void 0 + : node1.ownerDocument) !== null && + _node$ownerDocument !== void 0 + ? _node$ownerDocument + : globalThis === null || globalThis === void 0 + ? void 0 + : globalThis.document; + const [, force] = $g2vWm$react.useState({}); + const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + (node) => setNode(node) + ); + const layers = Array.from(context.layers); + const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore + const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore + const index = node1 ? layers.indexOf(node1) : -1; + const isBodyPointerEventsDisabled = + context.layersWithOutsidePointerEventsDisabled.size > 0; + const isPointerEventsEnabled = + index >= highestLayerWithOutsidePointerEventsDisabledIndex; + const pointerDownOutside = + $d715e0554b679f1f$var$usePointerDownOutside((event) => { + const target = event.target; + const isPointerDownOnBranch = [...context.branches].some( + (branch) => branch.contains(target) + ); + if (!isPointerEventsEnabled || isPointerDownOnBranch) return; + onPointerDownOutside === null || + onPointerDownOutside === void 0 || + onPointerDownOutside(event); + onInteractOutside === null || + onInteractOutside === void 0 || + onInteractOutside(event); + if (!event.defaultPrevented) + onDismiss === null || onDismiss === void 0 || onDismiss(); + }, ownerDocument); + const focusOutside = $d715e0554b679f1f$var$useFocusOutside( + (event) => { + const target = event.target; + const isFocusInBranch = [...context.branches].some((branch) => + branch.contains(target) + ); + if (isFocusInBranch) return; + onFocusOutside === null || + onFocusOutside === void 0 || + onFocusOutside(event); + onInteractOutside === null || + onInteractOutside === void 0 || + onInteractOutside(event); + if (!event.defaultPrevented) + onDismiss === null || onDismiss === void 0 || onDismiss(); + }, + ownerDocument + ); + $g2vWm$radixuireactuseescapekeydown.useEscapeKeydown((event) => { + const isHighestLayer = index === context.layers.size - 1; + if (!isHighestLayer) return; + onEscapeKeyDown === null || + onEscapeKeyDown === void 0 || + onEscapeKeyDown(event); + if (!event.defaultPrevented && onDismiss) { + event.preventDefault(); + onDismiss(); + } + }, ownerDocument); + $g2vWm$react.useEffect(() => { + if (!node1) return; + if (disableOutsidePointerEvents) { + if (context.layersWithOutsidePointerEventsDisabled.size === 0) { + $d715e0554b679f1f$var$originalBodyPointerEvents = + ownerDocument.body.style.pointerEvents; + ownerDocument.body.style.pointerEvents = "none"; + } + context.layersWithOutsidePointerEventsDisabled.add(node1); + } + context.layers.add(node1); + $d715e0554b679f1f$var$dispatchUpdate(); + return () => { + if ( + disableOutsidePointerEvents && + context.layersWithOutsidePointerEventsDisabled.size === 1 + ) + ownerDocument.body.style.pointerEvents = + $d715e0554b679f1f$var$originalBodyPointerEvents; + }; + }, [node1, ownerDocument, disableOutsidePointerEvents, context]); + /** + * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect + * because a change to `disableOutsidePointerEvents` would remove this layer from the stack + * and add it to the end again so the layering order wouldn't be _creation order_. + * We only want them to be removed from context stacks when unmounted. + */ + $g2vWm$react.useEffect(() => { + return () => { + if (!node1) return; + context.layers.delete(node1); + context.layersWithOutsidePointerEventsDisabled.delete(node1); + $d715e0554b679f1f$var$dispatchUpdate(); + }; + }, [node1, context]); + $g2vWm$react.useEffect(() => { + const handleUpdate = () => force({}); + document.addEventListener( + $d715e0554b679f1f$var$CONTEXT_UPDATE, + handleUpdate + ); + return () => + document.removeEventListener( + $d715e0554b679f1f$var$CONTEXT_UPDATE, + handleUpdate + ); + }, []); + return /*#__PURE__*/ $g2vWm$react.createElement( + $g2vWm$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($g2vWm$babelruntimehelpersextends)( + {}, + layerProps, + { + ref: composedRefs, + style: { + pointerEvents: isBodyPointerEventsDisabled + ? isPointerEventsEnabled + ? "auto" + : "none" + : undefined, + ...props.style, + }, + onFocusCapture: $g2vWm$radixuiprimitive.composeEventHandlers( + props.onFocusCapture, + focusOutside.onFocusCapture + ), + onBlurCapture: $g2vWm$radixuiprimitive.composeEventHandlers( + props.onBlurCapture, + focusOutside.onBlurCapture + ), + onPointerDownCapture: + $g2vWm$radixuiprimitive.composeEventHandlers( + props.onPointerDownCapture, + pointerDownOutside.onPointerDownCapture + ), + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d715e0554b679f1f$export$177fb62ff3ec1f22, { + displayName: $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME, }); - } - function handleFocusOut(event) { - if (focusScope.paused || !container1) return; - const relatedTarget = event.relatedTarget; // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases: - // - // 1. When the user switches app/tabs/windows/the browser itself loses focus. - // 2. In Google Chrome, when the focused element is removed from the DOM. - // - // We let the browser do its thing here because: - // - // 1. The browser already keeps a memory of what's focused for when the page gets refocused. - // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it - // throws the CPU to 100%, so we avoid doing anything for this reason here too. - if (relatedTarget === null) return; // If the focus has moved to an actual legitimate element (`relatedTarget !== null`) - // that is outside the container, we move focus to the last valid focused element inside. - if (!container1.contains(relatedTarget)) $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { - select: true - }); - } // When the focused element gets removed from the DOM, browsers move focus - // back to the document.body. In this case, we move focus to the container - // to keep focus trapped correctly. - function handleMutations(mutations) { - const focusedElement = document.activeElement; - for (const mutation of mutations) { - if (mutation.removedNodes.length > 0) { - if (!(container1 !== null && container1 !== void 0 && container1.contains(focusedElement))) $2bc01e66e04aa9ed$var$focus(container1); - } + /* ------------------------------------------------------------------------------------------------- + * DismissableLayerBranch + * -----------------------------------------------------------------------------------------------*/ + const $d715e0554b679f1f$var$BRANCH_NAME = "DismissableLayerBranch"; + const $d715e0554b679f1f$export$4d5eb2109db14228 = + /*#__PURE__*/ $g2vWm$react.forwardRef((props, forwardedRef) => { + const context = $g2vWm$react.useContext( + $d715e0554b679f1f$var$DismissableLayerContext + ); + const ref = $g2vWm$react.useRef(null); + const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + $g2vWm$react.useEffect(() => { + const node = ref.current; + if (node) { + context.branches.add(node); + return () => { + context.branches.delete(node); + }; + } + }, [context.branches]); + return /*#__PURE__*/ $g2vWm$react.createElement( + $g2vWm$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($g2vWm$babelruntimehelpersextends)( + {}, + props, + { + ref: composedRefs, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d715e0554b679f1f$export$4d5eb2109db14228, { + displayName: $d715e0554b679f1f$var$BRANCH_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ /** + * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup` + * to mimic layer dismissing behaviour present in OS. + * Returns props to pass to the node we want to check for outside events. + */ + function $d715e0554b679f1f$var$usePointerDownOutside( + onPointerDownOutside, + ownerDocument = globalThis === null || globalThis === void 0 + ? void 0 + : globalThis.document + ) { + const handlePointerDownOutside = + $g2vWm$radixuireactusecallbackref.useCallbackRef( + onPointerDownOutside + ); + const isPointerInsideReactTreeRef = $g2vWm$react.useRef(false); + const handleClickRef = $g2vWm$react.useRef(() => {}); + $g2vWm$react.useEffect(() => { + const handlePointerDown = (event) => { + if (event.target && !isPointerInsideReactTreeRef.current) { + const eventDetail = { + originalEvent: event, + }; + function handleAndDispatchPointerDownOutsideEvent() { + $d715e0554b679f1f$var$handleAndDispatchCustomEvent( + $d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE, + handlePointerDownOutside, + eventDetail, + { + discrete: true, + } + ); + } + /** + * On touch devices, we need to wait for a click event because browsers implement + * a ~350ms delay between the time the user stops touching the display and when the + * browser executres events. We need to ensure we don't reactivate pointer-events within + * this timeframe otherwise the browser may execute events that should have been prevented. + * + * Additionally, this also lets us deal automatically with cancellations when a click event + * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc. + * + * This is why we also continuously remove the previous listener, because we cannot be + * certain that it was raised, and therefore cleaned-up. + */ + if (event.pointerType === "touch") { + ownerDocument.removeEventListener( + "click", + handleClickRef.current + ); + handleClickRef.current = + handleAndDispatchPointerDownOutsideEvent; + ownerDocument.addEventListener( + "click", + handleClickRef.current, + { + once: true, + } + ); + } else handleAndDispatchPointerDownOutsideEvent(); + } + isPointerInsideReactTreeRef.current = false; + }; + /** + * if this hook executes in a component that mounts via a `pointerdown` event, the event + * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid + * this by delaying the event listener registration on the document. + * This is not React specific, but rather how the DOM works, ie: + * ``` + * button.addEventListener('pointerdown', () => { + * console.log('I will log'); + * document.addEventListener('pointerdown', () => { + * console.log('I will also log'); + * }) + * }); + */ + const timerId = window.setTimeout(() => { + ownerDocument.addEventListener("pointerdown", handlePointerDown); + }, 0); + return () => { + window.clearTimeout(timerId); + ownerDocument.removeEventListener( + "pointerdown", + handlePointerDown + ); + ownerDocument.removeEventListener( + "click", + handleClickRef.current + ); + }; + }, [ownerDocument, handlePointerDownOutside]); + return { + // ensures we check React component tree (not just DOM tree) + onPointerDownCapture: () => + (isPointerInsideReactTreeRef.current = true), + }; } - } - document.addEventListener('focusin', handleFocusIn); - document.addEventListener('focusout', handleFocusOut); - const mutationObserver = new MutationObserver(handleMutations); - if (container1) mutationObserver.observe(container1, { - childList: true, - subtree: true - }); - return () => { - document.removeEventListener('focusin', handleFocusIn); - document.removeEventListener('focusout', handleFocusOut); - mutationObserver.disconnect(); - }; - } - }, [trapped, container1, focusScope.paused]); - $buum9$react.useEffect(() => { - if (container1) { - $2bc01e66e04aa9ed$var$focusScopesStack.add(focusScope); - const previouslyFocusedElement = document.activeElement; - const hasFocusedCandidate = container1.contains(previouslyFocusedElement); - if (!hasFocusedCandidate) { - const mountEvent = new CustomEvent($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, $2bc01e66e04aa9ed$var$EVENT_OPTIONS); - container1.addEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); - container1.dispatchEvent(mountEvent); - if (!mountEvent.defaultPrevented) { - $2bc01e66e04aa9ed$var$focusFirst($2bc01e66e04aa9ed$var$removeLinks($2bc01e66e04aa9ed$var$getTabbableCandidates(container1)), { - select: true - }); - if (document.activeElement === previouslyFocusedElement) $2bc01e66e04aa9ed$var$focus(container1); + /** + * Listens for when focus happens outside a react subtree. + * Returns props to pass to the root (node) of the subtree we want to check. + */ + function $d715e0554b679f1f$var$useFocusOutside( + onFocusOutside, + ownerDocument = globalThis === null || globalThis === void 0 + ? void 0 + : globalThis.document + ) { + const handleFocusOutside = + $g2vWm$radixuireactusecallbackref.useCallbackRef(onFocusOutside); + const isFocusInsideReactTreeRef = $g2vWm$react.useRef(false); + $g2vWm$react.useEffect(() => { + const handleFocus = (event) => { + if (event.target && !isFocusInsideReactTreeRef.current) { + const eventDetail = { + originalEvent: event, + }; + $d715e0554b679f1f$var$handleAndDispatchCustomEvent( + $d715e0554b679f1f$var$FOCUS_OUTSIDE, + handleFocusOutside, + eventDetail, + { + discrete: false, + } + ); + } + }; + ownerDocument.addEventListener("focusin", handleFocus); + return () => + ownerDocument.removeEventListener("focusin", handleFocus); + }, [ownerDocument, handleFocusOutside]); + return { + onFocusCapture: () => (isFocusInsideReactTreeRef.current = true), + onBlurCapture: () => (isFocusInsideReactTreeRef.current = false), + }; } - } - return () => { - container1.removeEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus); // We hit a react bug (fixed in v17) with focusing in unmount. - // We need to delay the focus a little to get around it for now. - // See: https://github.com/facebook/react/issues/17894 - setTimeout(() => { - const unmountEvent = new CustomEvent($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, $2bc01e66e04aa9ed$var$EVENT_OPTIONS); - container1.addEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); - container1.dispatchEvent(unmountEvent); - if (!unmountEvent.defaultPrevented) $2bc01e66e04aa9ed$var$focus(previouslyFocusedElement !== null && previouslyFocusedElement !== void 0 ? previouslyFocusedElement : document.body, { - select: true - }); - // we need to remove the listener after we `dispatchEvent` - container1.removeEventListener($2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); - $2bc01e66e04aa9ed$var$focusScopesStack.remove(focusScope); - }, 0); - }; - } - }, [container1, onMountAutoFocus, onUnmountAutoFocus, focusScope]); // Takes care of looping focus (when tabbing whilst at the edges) - const handleKeyDown = $buum9$react.useCallback(event => { - if (!loop && !trapped) return; - if (focusScope.paused) return; - const isTabKey = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey; - const focusedElement = document.activeElement; - if (isTabKey && focusedElement) { - const container = event.currentTarget; - const [first, last] = $2bc01e66e04aa9ed$var$getTabbableEdges(container); - const hasTabbableElementsInside = first && last; // we can only wrap focus if we have tabbable edges - if (!hasTabbableElementsInside) { - if (focusedElement === container) event.preventDefault(); - } else { - if (!event.shiftKey && focusedElement === last) { - event.preventDefault(); - if (loop) $2bc01e66e04aa9ed$var$focus(first, { - select: true - }); - } else if (event.shiftKey && focusedElement === first) { - event.preventDefault(); - if (loop) $2bc01e66e04aa9ed$var$focus(last, { - select: true + function $d715e0554b679f1f$var$dispatchUpdate() { + const event = new CustomEvent($d715e0554b679f1f$var$CONTEXT_UPDATE); + document.dispatchEvent(event); + } + function $d715e0554b679f1f$var$handleAndDispatchCustomEvent( + name, + handler, + detail, + { discrete: discrete } + ) { + const target = detail.originalEvent.target; + const event = new CustomEvent(name, { + bubbles: false, + cancelable: true, + detail: detail, }); + if (handler) + target.addEventListener(name, handler, { + once: true, + }); + if (discrete) + $g2vWm$radixuireactprimitive.dispatchDiscreteCustomEvent( + target, + event + ); + else target.dispatchEvent(event); } - } - } - }, [loop, trapped, focusScope.paused]); - return /*#__PURE__*/$buum9$react.createElement($buum9$radixuireactprimitive.Primitive.div, $parcel$interopDefault($buum9$babelruntimehelpersextends)({ - tabIndex: -1 - }, scopeProps, { - ref: composedRefs, - onKeyDown: handleKeyDown - })); -}); -/*#__PURE__*/ -Object.assign($2bc01e66e04aa9ed$export$20e40289641fbbb6, { - displayName: $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Attempts focusing the first element in a list of candidates. - * Stops when focus has actually moved. - */ -function $2bc01e66e04aa9ed$var$focusFirst(candidates, { - select = false -} = {}) { - const previouslyFocusedElement = document.activeElement; - for (const candidate of candidates) { - $2bc01e66e04aa9ed$var$focus(candidate, { - select: select - }); - if (document.activeElement !== previouslyFocusedElement) return; - } -} -/** - * Returns the first and last tabbable elements inside a container. - */ -function $2bc01e66e04aa9ed$var$getTabbableEdges(container) { - const candidates = $2bc01e66e04aa9ed$var$getTabbableCandidates(container); - const first = $2bc01e66e04aa9ed$var$findVisible(candidates, container); - const last = $2bc01e66e04aa9ed$var$findVisible(candidates.reverse(), container); - return [first, last]; -} -/** - * Returns a list of potential tabbable candidates. - * - * NOTE: This is only a close approximation. For example it doesn't take into account cases like when - * elements are not visible. This cannot be worked out easily by just reading a property, but rather - * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately. - * - * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker - * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1 - */ -function $2bc01e66e04aa9ed$var$getTabbableCandidates(container) { - const nodes = []; - const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { - acceptNode: node => { - const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden'; - if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP; // `.tabIndex` is not the same as the `tabindex` attribute. It works on the - // runtime's understanding of tabbability, so this automatically accounts - // for any kind of element that could be tabbed to. - return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; - } - }); - while (walker.nextNode()) nodes.push(walker.currentNode); // we do not take into account the order of nodes with positive `tabIndex` as it - // hinders accessibility to have tab order different from visual order. - return nodes; -} -/** - * Returns the first visible element in a list. - * NOTE: Only checks visibility up to the `container`. - */ -function $2bc01e66e04aa9ed$var$findVisible(elements, container) { - for (const element of elements) { - // we stop checking if it's hidden at the `container` level (excluding) - if (!$2bc01e66e04aa9ed$var$isHidden(element, { - upTo: container - })) return element; - } -} -function $2bc01e66e04aa9ed$var$isHidden(node, { - upTo: upTo -}) { - if (getComputedStyle(node).visibility === 'hidden') return true; - while (node) { - // we stop at `upTo` (excluding it) - if (upTo !== undefined && node === upTo) return false; - if (getComputedStyle(node).display === 'none') return true; - node = node.parentElement; - } - return false; -} -function $2bc01e66e04aa9ed$var$isSelectableInput(element) { - return element instanceof HTMLInputElement && 'select' in element; -} -function $2bc01e66e04aa9ed$var$focus(element, { - select = false -} = {}) { - // only focus if that element is focusable - if (element && element.focus) { - const previouslyFocusedElement = document.activeElement; // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users - element.focus({ - preventScroll: true - }); // only select if its not the same element, it supports selection and we need to select - if (element !== previouslyFocusedElement && $2bc01e66e04aa9ed$var$isSelectableInput(element) && select) element.select(); - } -} -/* ------------------------------------------------------------------------------------------------- - * FocusScope stack - * -----------------------------------------------------------------------------------------------*/ -const $2bc01e66e04aa9ed$var$focusScopesStack = $2bc01e66e04aa9ed$var$createFocusScopesStack(); -function $2bc01e66e04aa9ed$var$createFocusScopesStack() { - /** A stack of focus scopes, with the active one at the top */let stack = []; - return { - add(focusScope) { - // pause the currently active focus scope (at the top of the stack) - const activeFocusScope = stack[0]; - if (focusScope !== activeFocusScope) activeFocusScope === null || activeFocusScope === void 0 || activeFocusScope.pause(); - // remove in case it already exists (because we'll re-add it at the top of the stack) - stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); - stack.unshift(focusScope); - }, - remove(focusScope) { - var _stack$; - stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); - (_stack$ = stack[0]) === null || _stack$ === void 0 || _stack$.resume(); - } - }; -} -function $2bc01e66e04aa9ed$var$arrayRemove(array, item) { - const updatedArray = [...array]; - const index = updatedArray.indexOf(item); - if (index !== -1) updatedArray.splice(index, 1); - return updatedArray; -} -function $2bc01e66e04aa9ed$var$removeLinks(items) { - return items.filter(item => item.tagName !== 'A'); -} -const $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9 = $2bc01e66e04aa9ed$export$20e40289641fbbb6; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-id/dist/index.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-id/dist/index.js ***! - \**************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - + const $d715e0554b679f1f$export$be92b6f5f03c0fe9 = + $d715e0554b679f1f$export$177fb62ff3ec1f22; + const $d715e0554b679f1f$export$aecb2ddcb55c95be = + $d715e0554b679f1f$export$4d5eb2109db14228; + /***/ + }, -var $47woD$react = __webpack_require__(/*! react */ "react"); -var $47woD$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useId", () => $dc478e4659f630c5$export$f680877a34711e37); -const $dc478e4659f630c5$var$useReactId = $47woD$react['useId'.toString()] || (() => undefined); -let $dc478e4659f630c5$var$count = 0; -function $dc478e4659f630c5$export$f680877a34711e37(deterministicId) { - const [id, setId] = $47woD$react.useState($dc478e4659f630c5$var$useReactId()); // React versions older than 18 will have client-side ids only. - $47woD$radixuireactuselayouteffect.useLayoutEffect(() => { - if (!deterministicId) setId(reactId => reactId !== null && reactId !== void 0 ? reactId : String($dc478e4659f630c5$var$count++)); - }, [deterministicId]); - return deterministicId || (id ? `radix-${id}` : ''); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-menu/dist/index.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-menu/dist/index.js ***! - \****************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $cnSS2$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $cnSS2$react = __webpack_require__(/*! react */ "react"); -var $cnSS2$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $cnSS2$radixuireactcollection = __webpack_require__(/*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js"); -var $cnSS2$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $cnSS2$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $cnSS2$radixuireactdirection = __webpack_require__(/*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js"); -var $cnSS2$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); -var $cnSS2$radixuireactfocusguards = __webpack_require__(/*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js"); -var $cnSS2$radixuireactfocusscope = __webpack_require__(/*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js"); -var $cnSS2$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $cnSS2$radixuireactpopper = __webpack_require__(/*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js"); -var $cnSS2$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); -var $cnSS2$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); -var $cnSS2$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $cnSS2$radixuireactrovingfocus = __webpack_require__(/*! @radix-ui/react-roving-focus */ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js"); -var $cnSS2$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -var $cnSS2$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $cnSS2$ariahidden = __webpack_require__(/*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js"); -var $cnSS2$reactremovescroll = __webpack_require__(/*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createMenuScope", () => $213e4d2df823067d$export$4027731b685e72eb); -$parcel$export(module.exports, "Menu", () => $213e4d2df823067d$export$d9b273488cd8ce6f); -$parcel$export(module.exports, "MenuAnchor", () => $213e4d2df823067d$export$9fa5ebd18bee4d43); -$parcel$export(module.exports, "MenuPortal", () => $213e4d2df823067d$export$793392f970497feb); -$parcel$export(module.exports, "MenuContent", () => $213e4d2df823067d$export$479f0f2f71193efe); -$parcel$export(module.exports, "MenuGroup", () => $213e4d2df823067d$export$22a631d1f72787bb); -$parcel$export(module.exports, "MenuLabel", () => $213e4d2df823067d$export$dd37bec0e8a99143); -$parcel$export(module.exports, "MenuItem", () => $213e4d2df823067d$export$2ce376c2cc3355c8); -$parcel$export(module.exports, "MenuCheckboxItem", () => $213e4d2df823067d$export$f6f243521332502d); -$parcel$export(module.exports, "MenuRadioGroup", () => $213e4d2df823067d$export$ea2200c9eee416b3); -$parcel$export(module.exports, "MenuRadioItem", () => $213e4d2df823067d$export$69bd225e9817f6d0); -$parcel$export(module.exports, "MenuItemIndicator", () => $213e4d2df823067d$export$a2593e23056970a3); -$parcel$export(module.exports, "MenuSeparator", () => $213e4d2df823067d$export$1cec7dcdd713e220); -$parcel$export(module.exports, "MenuArrow", () => $213e4d2df823067d$export$bcdda4773debf5fa); -$parcel$export(module.exports, "MenuSub", () => $213e4d2df823067d$export$71bdb9d1e2909932); -$parcel$export(module.exports, "MenuSubTrigger", () => $213e4d2df823067d$export$5fbbb3ba7297405f); -$parcel$export(module.exports, "MenuSubContent", () => $213e4d2df823067d$export$e7142ab31822bde6); -$parcel$export(module.exports, "Root", () => $213e4d2df823067d$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Anchor", () => $213e4d2df823067d$export$b688253958b8dfe7); -$parcel$export(module.exports, "Portal", () => $213e4d2df823067d$export$602eac185826482c); -$parcel$export(module.exports, "Content", () => $213e4d2df823067d$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Group", () => $213e4d2df823067d$export$eb2fcfdbd7ba97d4); -$parcel$export(module.exports, "Label", () => $213e4d2df823067d$export$b04be29aa201d4f5); -$parcel$export(module.exports, "Item", () => $213e4d2df823067d$export$6d08773d2e66f8f2); -$parcel$export(module.exports, "CheckboxItem", () => $213e4d2df823067d$export$16ce288f89fa631c); -$parcel$export(module.exports, "RadioGroup", () => $213e4d2df823067d$export$a98f0dcb43a68a25); -$parcel$export(module.exports, "RadioItem", () => $213e4d2df823067d$export$371ab307eab489c0); -$parcel$export(module.exports, "ItemIndicator", () => $213e4d2df823067d$export$c3468e2714d175fa); -$parcel$export(module.exports, "Separator", () => $213e4d2df823067d$export$1ff3c3f08ae963c0); -$parcel$export(module.exports, "Arrow", () => $213e4d2df823067d$export$21b07c8f274aebd5); -$parcel$export(module.exports, "Sub", () => $213e4d2df823067d$export$d7a01e11500dfb6f); -$parcel$export(module.exports, "SubTrigger", () => $213e4d2df823067d$export$2ea8a7a591ac5eac); -$parcel$export(module.exports, "SubContent", () => $213e4d2df823067d$export$6d4de93b380beddf); -const $213e4d2df823067d$var$SELECTION_KEYS = ['Enter', ' ']; -const $213e4d2df823067d$var$FIRST_KEYS = ['ArrowDown', 'PageUp', 'Home']; -const $213e4d2df823067d$var$LAST_KEYS = ['ArrowUp', 'PageDown', 'End']; -const $213e4d2df823067d$var$FIRST_LAST_KEYS = [...$213e4d2df823067d$var$FIRST_KEYS, ...$213e4d2df823067d$var$LAST_KEYS]; -const $213e4d2df823067d$var$SUB_OPEN_KEYS = { - ltr: [...$213e4d2df823067d$var$SELECTION_KEYS, 'ArrowRight'], - rtl: [...$213e4d2df823067d$var$SELECTION_KEYS, 'ArrowLeft'] -}; -const $213e4d2df823067d$var$SUB_CLOSE_KEYS = { - ltr: ['ArrowLeft'], - rtl: ['ArrowRight'] -}; -/* ------------------------------------------------------------------------------------------------- - * Menu - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$MENU_NAME = 'Menu'; -const [$213e4d2df823067d$var$Collection, $213e4d2df823067d$var$useCollection, $213e4d2df823067d$var$createCollectionScope] = $cnSS2$radixuireactcollection.createCollection($213e4d2df823067d$var$MENU_NAME); -const [$213e4d2df823067d$var$createMenuContext, $213e4d2df823067d$export$4027731b685e72eb] = $cnSS2$radixuireactcontext.createContextScope($213e4d2df823067d$var$MENU_NAME, [$213e4d2df823067d$var$createCollectionScope, $cnSS2$radixuireactpopper.createPopperScope, $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope]); -const $213e4d2df823067d$var$usePopperScope = $cnSS2$radixuireactpopper.createPopperScope(); -const $213e4d2df823067d$var$useRovingFocusGroupScope = $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope(); -const [$213e4d2df823067d$var$MenuProvider, $213e4d2df823067d$var$useMenuContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$MENU_NAME); -const [$213e4d2df823067d$var$MenuRootProvider, $213e4d2df823067d$var$useMenuRootContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$MENU_NAME); -const $213e4d2df823067d$export$d9b273488cd8ce6f = props => { - const { - __scopeMenu: __scopeMenu, - open = false, - children: children, - dir: dir, - onOpenChange: onOpenChange, - modal = true - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const [content, setContent] = $cnSS2$react.useState(null); - const isUsingKeyboardRef = $cnSS2$react.useRef(false); - const handleOpenChange = $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); - const direction = $cnSS2$radixuireactdirection.useDirection(dir); - $cnSS2$react.useEffect(() => { - // Capture phase ensures we set the boolean before any side effects execute - // in response to the key or pointer event as they might depend on this value. - const handleKeyDown = () => { - isUsingKeyboardRef.current = true; - document.addEventListener('pointerdown', handlePointer, { - capture: true, - once: true - }); - document.addEventListener('pointermove', handlePointer, { - capture: true, - once: true - }); - }; - const handlePointer = () => isUsingKeyboardRef.current = false; - document.addEventListener('keydown', handleKeyDown, { - capture: true - }); - return () => { - document.removeEventListener('keydown', handleKeyDown, { - capture: true - }); - document.removeEventListener('pointerdown', handlePointer, { - capture: true - }); - document.removeEventListener('pointermove', handlePointer, { - capture: true - }); - }; - }, []); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Root, popperScope, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuProvider, { - scope: __scopeMenu, - open: open, - onOpenChange: handleOpenChange, - content: content, - onContentChange: setContent - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuRootProvider, { - scope: __scopeMenu, - onClose: $cnSS2$react.useCallback(() => handleOpenChange(false), [handleOpenChange]), - isUsingKeyboardRef: isUsingKeyboardRef, - dir: direction, - modal: modal - }, children))); -}; -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$d9b273488cd8ce6f, { - displayName: $213e4d2df823067d$var$MENU_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuAnchor - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ANCHOR_NAME = 'MenuAnchor'; -const $213e4d2df823067d$export$9fa5ebd18bee4d43 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...anchorProps - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Anchor, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, popperScope, anchorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$9fa5ebd18bee4d43, { - displayName: $213e4d2df823067d$var$ANCHOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuPortal - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$PORTAL_NAME = 'MenuPortal'; -const [$213e4d2df823067d$var$PortalProvider, $213e4d2df823067d$var$usePortalContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$PORTAL_NAME, { - forceMount: undefined -}); -const $213e4d2df823067d$export$793392f970497feb = props => { - const { - __scopeMenu: __scopeMenu, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$PORTAL_NAME, __scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$PortalProvider, { - scope: __scopeMenu, - forceMount: forceMount - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactportal.Portal, { - asChild: true, - container: container - }, children))); -}; -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$793392f970497feb, { - displayName: $213e4d2df823067d$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuContent - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$CONTENT_NAME = 'MenuContent'; -const [$213e4d2df823067d$var$MenuContentProvider, $213e4d2df823067d$var$useMenuContentContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$CONTENT_NAME); -const $213e4d2df823067d$export$479f0f2f71193efe = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const portalContext = $213e4d2df823067d$var$usePortalContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const { - forceMount = portalContext.forceMount, - ...contentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Provider, { - scope: props.__scopeMenu - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Slot, { - scope: props.__scopeMenu - }, rootContext.modal ? /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuRootContentModal, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuRootContentNonModal, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, contentProps, { - ref: forwardedRef - }))))); -}); -/* ---------------------------------------------------------------------------------------------- */ -const $213e4d2df823067d$var$MenuRootContentModal = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); // Hide everything from ARIA except the `MenuContent` - $cnSS2$react.useEffect(() => { - const content = ref.current; - if (content) return $cnSS2$ariahidden.hideOthers(content); - }, []); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, props, { - ref: composedRefs // we make sure we're not trapping once it's been closed - , - - trapFocus: context.open // make sure to only disable pointer events when open - , - - disableOutsidePointerEvents: context.open, - disableOutsideScroll: true // When focus is trapped, a `focusout` event may still happen. - , - - onFocusOutside: $cnSS2$radixuiprimitive.composeEventHandlers(props.onFocusOutside, event => event.preventDefault(), { - checkForDefaultPrevented: false - }), - onDismiss: () => context.onOpenChange(false) - })); -}); -const $213e4d2df823067d$var$MenuRootContentNonModal = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - trapFocus: false, - disableOutsidePointerEvents: false, - disableOutsideScroll: false, - onDismiss: () => context.onOpenChange(false) - })); -}); -/* ---------------------------------------------------------------------------------------------- */ -const $213e4d2df823067d$var$MenuContentImpl = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - loop = false, - trapFocus: trapFocus, - onOpenAutoFocus: onOpenAutoFocus, - onCloseAutoFocus: onCloseAutoFocus, - disableOutsidePointerEvents: disableOutsidePointerEvents, - onEntryFocus: onEntryFocus, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - disableOutsideScroll: disableOutsideScroll, - ...contentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, __scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$CONTENT_NAME, __scopeMenu); - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const rovingFocusGroupScope = $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); - const getItems = $213e4d2df823067d$var$useCollection(__scopeMenu); - const [currentItemId, setCurrentItemId] = $cnSS2$react.useState(null); - const contentRef = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, contentRef, context.onContentChange); - const timerRef = $cnSS2$react.useRef(0); - const searchRef = $cnSS2$react.useRef(''); - const pointerGraceTimerRef = $cnSS2$react.useRef(0); - const pointerGraceIntentRef = $cnSS2$react.useRef(null); - const pointerDirRef = $cnSS2$react.useRef('right'); - const lastPointerXRef = $cnSS2$react.useRef(0); - const ScrollLockWrapper = disableOutsideScroll ? $cnSS2$reactremovescroll.RemoveScroll : $cnSS2$react.Fragment; - const scrollLockWrapperProps = disableOutsideScroll ? { - as: $cnSS2$radixuireactslot.Slot, - allowPinchZoom: true - } : undefined; - const handleTypeaheadSearch = key => { - var _items$find, _items$find2; - const search = searchRef.current + key; - const items = getItems().filter(item => !item.disabled); - const currentItem = document.activeElement; - const currentMatch = (_items$find = items.find(item => item.ref.current === currentItem)) === null || _items$find === void 0 ? void 0 : _items$find.textValue; - const values = items.map(item => item.textValue); - const nextMatch = $213e4d2df823067d$var$getNextMatch(values, search, currentMatch); - const newItem = (_items$find2 = items.find(item => item.textValue === nextMatch)) === null || _items$find2 === void 0 ? void 0 : _items$find2.ref.current; // Reset `searchRef` 1 second after it was last updated - (function updateSearch(value) { - searchRef.current = value; - window.clearTimeout(timerRef.current); - if (value !== '') timerRef.current = window.setTimeout(() => updateSearch(''), 1000); - })(search); - if (newItem) - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => newItem.focus()); - }; - $cnSS2$react.useEffect(() => { - return () => window.clearTimeout(timerRef.current); - }, []); // Make sure the whole tree has focus guards as our `MenuContent` may be - // the last element in the DOM (beacuse of the `Portal`) - $cnSS2$radixuireactfocusguards.useFocusGuards(); - const isPointerMovingToSubmenu = $cnSS2$react.useCallback(event => { - var _pointerGraceIntentRe, _pointerGraceIntentRe2; - const isMovingTowards = pointerDirRef.current === ((_pointerGraceIntentRe = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe === void 0 ? void 0 : _pointerGraceIntentRe.side); - return isMovingTowards && $213e4d2df823067d$var$isPointerInGraceArea(event, (_pointerGraceIntentRe2 = pointerGraceIntentRef.current) === null || _pointerGraceIntentRe2 === void 0 ? void 0 : _pointerGraceIntentRe2.area); - }, []); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentProvider, { - scope: __scopeMenu, - searchRef: searchRef, - onItemEnter: $cnSS2$react.useCallback(event => { - if (isPointerMovingToSubmenu(event)) event.preventDefault(); - }, [isPointerMovingToSubmenu]), - onItemLeave: $cnSS2$react.useCallback(event => { - var _contentRef$current; - if (isPointerMovingToSubmenu(event)) return; - (_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 || _contentRef$current.focus(); - setCurrentItemId(null); - }, [isPointerMovingToSubmenu]), - onTriggerLeave: $cnSS2$react.useCallback(event => { - if (isPointerMovingToSubmenu(event)) event.preventDefault(); - }, [isPointerMovingToSubmenu]), - pointerGraceTimerRef: pointerGraceTimerRef, - onPointerGraceIntentChange: $cnSS2$react.useCallback(intent => { - pointerGraceIntentRef.current = intent; - }, []) - }, /*#__PURE__*/$cnSS2$react.createElement(ScrollLockWrapper, scrollLockWrapperProps, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactfocusscope.FocusScope, { - asChild: true, - trapped: trapFocus, - onMountAutoFocus: $cnSS2$radixuiprimitive.composeEventHandlers(onOpenAutoFocus, event => { - var _contentRef$current2; - // when opening, explicitly focus the content area only and leave - // `onEntryFocus` in control of focusing first item - event.preventDefault(); - (_contentRef$current2 = contentRef.current) === null || _contentRef$current2 === void 0 || _contentRef$current2.focus(); - }), - onUnmountAutoFocus: onCloseAutoFocus - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactdismissablelayer.DismissableLayer, { - asChild: true, - disableOutsidePointerEvents: disableOutsidePointerEvents, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactrovingfocus.Root, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - asChild: true - }, rovingFocusGroupScope, { - dir: rootContext.dir, - orientation: "vertical", - loop: loop, - currentTabStopId: currentItemId, - onCurrentTabStopIdChange: setCurrentItemId, - onEntryFocus: $cnSS2$radixuiprimitive.composeEventHandlers(onEntryFocus, event => { - // only focus first item when using keyboard - if (!rootContext.isUsingKeyboardRef.current) event.preventDefault(); - }) - }), /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Content, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menu", - "aria-orientation": "vertical", - "data-state": $213e4d2df823067d$var$getOpenState(context.open), - "data-radix-menu-content": "", - dir: rootContext.dir - }, popperScope, contentProps, { - ref: composedRefs, - style: { - outline: 'none', - ...contentProps.style - }, - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(contentProps.onKeyDown, event => { - // submenu key events bubble through portals. We only care about keys in this menu. - const target = event.target; - const isKeyDownInside = target.closest('[data-radix-menu-content]') === event.currentTarget; - const isModifierKey = event.ctrlKey || event.altKey || event.metaKey; - const isCharacterKey = event.key.length === 1; - if (isKeyDownInside) { - // menus should not be navigated using tab key so we prevent it - if (event.key === 'Tab') event.preventDefault(); - if (!isModifierKey && isCharacterKey) handleTypeaheadSearch(event.key); - } // focus first/last item based on key pressed - const content = contentRef.current; - if (event.target !== content) return; - if (!$213e4d2df823067d$var$FIRST_LAST_KEYS.includes(event.key)) return; - event.preventDefault(); - const items = getItems().filter(item => !item.disabled); - const candidateNodes = items.map(item => item.ref.current); - if ($213e4d2df823067d$var$LAST_KEYS.includes(event.key)) candidateNodes.reverse(); - $213e4d2df823067d$var$focusFirst(candidateNodes); - }), - onBlur: $cnSS2$radixuiprimitive.composeEventHandlers(props.onBlur, event => { - // clear search buffer when leaving the menu - if (!event.currentTarget.contains(event.target)) { - window.clearTimeout(timerRef.current); - searchRef.current = ''; - } - }), - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerMove, $213e4d2df823067d$var$whenMouse(event => { - const target = event.target; - const pointerXHasChanged = lastPointerXRef.current !== event.clientX; // We don't use `event.movementX` for this check because Safari will - // always return `0` on a pointer event. - if (event.currentTarget.contains(target) && pointerXHasChanged) { - const newDir = event.clientX > lastPointerXRef.current ? 'right' : 'left'; - pointerDirRef.current = newDir; - lastPointerXRef.current = event.clientX; - } - })) - }))))))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$479f0f2f71193efe, { - displayName: $213e4d2df823067d$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuGroup - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$GROUP_NAME = 'MenuGroup'; -const $213e4d2df823067d$export$22a631d1f72787bb = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...groupProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "group" - }, groupProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$22a631d1f72787bb, { - displayName: $213e4d2df823067d$var$GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuLabel - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$LABEL_NAME = 'MenuLabel'; -const $213e4d2df823067d$export$dd37bec0e8a99143 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...labelProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, labelProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$dd37bec0e8a99143, { - displayName: $213e4d2df823067d$var$LABEL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuItem - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ITEM_NAME = 'MenuItem'; -const $213e4d2df823067d$var$ITEM_SELECT = 'menu.itemSelect'; -const $213e4d2df823067d$export$2ce376c2cc3355c8 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - disabled = false, - onSelect: onSelect, - ...itemProps - } = props; - const ref = $cnSS2$react.useRef(null); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$ITEM_NAME, props.__scopeMenu); - const contentContext = $213e4d2df823067d$var$useMenuContentContext($213e4d2df823067d$var$ITEM_NAME, props.__scopeMenu); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const isPointerDownRef = $cnSS2$react.useRef(false); - const handleSelect = () => { - const menuItem = ref.current; - if (!disabled && menuItem) { - const itemSelectEvent = new CustomEvent($213e4d2df823067d$var$ITEM_SELECT, { - bubbles: true, - cancelable: true - }); - menuItem.addEventListener($213e4d2df823067d$var$ITEM_SELECT, event => onSelect === null || onSelect === void 0 ? void 0 : onSelect(event), { - once: true - }); - $cnSS2$radixuireactprimitive.dispatchDiscreteCustomEvent(menuItem, itemSelectEvent); - if (itemSelectEvent.defaultPrevented) isPointerDownRef.current = false;else rootContext.onClose(); - } - }; - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuItemImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, itemProps, { - ref: composedRefs, - disabled: disabled, - onClick: $cnSS2$radixuiprimitive.composeEventHandlers(props.onClick, handleSelect), - onPointerDown: event => { - var _props$onPointerDown; - (_props$onPointerDown = props.onPointerDown) === null || _props$onPointerDown === void 0 || _props$onPointerDown.call(props, event); - isPointerDownRef.current = true; - }, - onPointerUp: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerUp, event => { - var _event$currentTarget; - // Pointer down can move to a different menu item which should activate it on pointer up. - // We dispatch a click for selection to allow composition with click based triggers and to - // prevent Firefox from getting stuck in text selection mode when the menu closes. - if (!isPointerDownRef.current) (_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 || _event$currentTarget.click(); - }), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - const isTypingAhead = contentContext.searchRef.current !== ''; - if (disabled || isTypingAhead && event.key === ' ') return; - if ($213e4d2df823067d$var$SELECTION_KEYS.includes(event.key)) { - event.currentTarget.click(); - /** - * We prevent default browser behaviour for selection keys as they should trigger - * a selection only: - * - prevents space from scrolling the page. - * - if keydown causes focus to move, prevents keydown from firing on the new target. - */ - event.preventDefault(); - } - }) - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$2ce376c2cc3355c8, { - displayName: $213e4d2df823067d$var$ITEM_NAME -}); -/* ---------------------------------------------------------------------------------------------- */ -const $213e4d2df823067d$var$MenuItemImpl = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - disabled = false, - textValue: textValue, - ...itemProps - } = props; - const contentContext = $213e4d2df823067d$var$useMenuContentContext($213e4d2df823067d$var$ITEM_NAME, __scopeMenu); - const rovingFocusGroupScope = $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const [isFocused, setIsFocused] = $cnSS2$react.useState(false); // get the item's `.textContent` as default strategy for typeahead `textValue` - const [textContent, setTextContent] = $cnSS2$react.useState(''); - $cnSS2$react.useEffect(() => { - const menuItem = ref.current; - if (menuItem) { - var _menuItem$textContent; - setTextContent(((_menuItem$textContent = menuItem.textContent) !== null && _menuItem$textContent !== void 0 ? _menuItem$textContent : '').trim()); - } - }, [itemProps.children]); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.ItemSlot, { - scope: __scopeMenu, - disabled: disabled, - textValue: textValue !== null && textValue !== void 0 ? textValue : textContent - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactrovingfocus.Item, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - asChild: true - }, rovingFocusGroupScope, { - focusable: !disabled - }), /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menuitem", - "data-highlighted": isFocused ? '' : undefined, - "aria-disabled": disabled || undefined, - "data-disabled": disabled ? '' : undefined - }, itemProps, { - ref: composedRefs, - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerMove, $213e4d2df823067d$var$whenMouse(event => { - if (disabled) contentContext.onItemLeave(event);else { - contentContext.onItemEnter(event); - if (!event.defaultPrevented) { - const item = event.currentTarget; - item.focus(); + /***/ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js": + /*!*************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js ***! + \*************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $7dQ7Q$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $7dQ7Q$react = __webpack_require__(/*! react */ "react"); + var $7dQ7Q$radixuiprimitive = __webpack_require__( + /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" + ); + var $7dQ7Q$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $7dQ7Q$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $7dQ7Q$radixuireactusecontrollablestate = __webpack_require__( + /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" + ); + var $7dQ7Q$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $7dQ7Q$radixuireactmenu = __webpack_require__( + /*! @radix-ui/react-menu */ "../../../node_modules/@radix-ui/react-menu/dist/index.js" + ); + var $7dQ7Q$radixuireactid = __webpack_require__( + /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); } - } - })), - onPointerLeave: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerLeave, $213e4d2df823067d$var$whenMouse(event => contentContext.onItemLeave(event))), - onFocus: $cnSS2$radixuiprimitive.composeEventHandlers(props.onFocus, () => setIsFocused(true)), - onBlur: $cnSS2$radixuiprimitive.composeEventHandlers(props.onBlur, () => setIsFocused(false)) - })))); -}); -/* ------------------------------------------------------------------------------------------------- - * MenuCheckboxItem - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$CHECKBOX_ITEM_NAME = 'MenuCheckboxItem'; -const $213e4d2df823067d$export$f6f243521332502d = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - checked = false, - onCheckedChange: onCheckedChange, - ...checkboxItemProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$ItemIndicatorProvider, { - scope: props.__scopeMenu, - checked: checked - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$2ce376c2cc3355c8, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menuitemcheckbox", - "aria-checked": $213e4d2df823067d$var$isIndeterminate(checked) ? 'mixed' : checked - }, checkboxItemProps, { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState(checked), - onSelect: $cnSS2$radixuiprimitive.composeEventHandlers(checkboxItemProps.onSelect, () => onCheckedChange === null || onCheckedChange === void 0 ? void 0 : onCheckedChange($213e4d2df823067d$var$isIndeterminate(checked) ? true : !checked), { - checkForDefaultPrevented: false - }) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$f6f243521332502d, { - displayName: $213e4d2df823067d$var$CHECKBOX_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuRadioGroup - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$RADIO_GROUP_NAME = 'MenuRadioGroup'; -const [$213e4d2df823067d$var$RadioGroupProvider, $213e4d2df823067d$var$useRadioGroupContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$RADIO_GROUP_NAME, { - value: undefined, - onValueChange: () => {} -}); -const $213e4d2df823067d$export$ea2200c9eee416b3 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - value: value, - onValueChange: onValueChange, - ...groupProps - } = props; - const handleValueChange = $cnSS2$radixuireactusecallbackref.useCallbackRef(onValueChange); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$RadioGroupProvider, { - scope: props.__scopeMenu, - value: value, - onValueChange: handleValueChange - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$22a631d1f72787bb, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, groupProps, { - ref: forwardedRef - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$ea2200c9eee416b3, { - displayName: $213e4d2df823067d$var$RADIO_GROUP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuRadioItem - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$RADIO_ITEM_NAME = 'MenuRadioItem'; -const $213e4d2df823067d$export$69bd225e9817f6d0 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - value: value, - ...radioItemProps - } = props; - const context = $213e4d2df823067d$var$useRadioGroupContext($213e4d2df823067d$var$RADIO_ITEM_NAME, props.__scopeMenu); - const checked = value === context.value; - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$ItemIndicatorProvider, { - scope: props.__scopeMenu, - checked: checked - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$2ce376c2cc3355c8, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "menuitemradio", - "aria-checked": checked - }, radioItemProps, { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState(checked), - onSelect: $cnSS2$radixuiprimitive.composeEventHandlers(radioItemProps.onSelect, () => { - var _context$onValueChang; - return (_context$onValueChang = context.onValueChange) === null || _context$onValueChang === void 0 ? void 0 : _context$onValueChang.call(context, value); - }, { - checkForDefaultPrevented: false - }) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$69bd225e9817f6d0, { - displayName: $213e4d2df823067d$var$RADIO_ITEM_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuItemIndicator - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ITEM_INDICATOR_NAME = 'MenuItemIndicator'; -const [$213e4d2df823067d$var$ItemIndicatorProvider, $213e4d2df823067d$var$useItemIndicatorContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$ITEM_INDICATOR_NAME, { - checked: false -}); -const $213e4d2df823067d$export$a2593e23056970a3 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - forceMount: forceMount, - ...itemIndicatorProps - } = props; - const indicatorContext = $213e4d2df823067d$var$useItemIndicatorContext($213e4d2df823067d$var$ITEM_INDICATOR_NAME, __scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || $213e4d2df823067d$var$isIndeterminate(indicatorContext.checked) || indicatorContext.checked === true - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.span, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, itemIndicatorProps, { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState(indicatorContext.checked) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$a2593e23056970a3, { - displayName: $213e4d2df823067d$var$ITEM_INDICATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSeparator - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SEPARATOR_NAME = 'MenuSeparator'; -const $213e4d2df823067d$export$1cec7dcdd713e220 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...separatorProps - } = props; - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactprimitive.Primitive.div, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - role: "separator", - "aria-orientation": "horizontal" - }, separatorProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$1cec7dcdd713e220, { - displayName: $213e4d2df823067d$var$SEPARATOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuArrow - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$ARROW_NAME = 'MenuArrow'; -const $213e4d2df823067d$export$bcdda4773debf5fa = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - ...arrowProps - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Arrow, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({}, popperScope, arrowProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$bcdda4773debf5fa, { - displayName: $213e4d2df823067d$var$ARROW_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSub - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SUB_NAME = 'MenuSub'; -const [$213e4d2df823067d$var$MenuSubProvider, $213e4d2df823067d$var$useMenuSubContext] = $213e4d2df823067d$var$createMenuContext($213e4d2df823067d$var$SUB_NAME); -const $213e4d2df823067d$export$71bdb9d1e2909932 = props => { - const { - __scopeMenu: __scopeMenu, - children: children, - open = false, - onOpenChange: onOpenChange - } = props; - const parentMenuContext = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$SUB_NAME, __scopeMenu); - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const [trigger, setTrigger] = $cnSS2$react.useState(null); - const [content, setContent] = $cnSS2$react.useState(null); - const handleOpenChange = $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); // Prevent the parent menu from reopening with open submenus. - $cnSS2$react.useEffect(() => { - if (parentMenuContext.open === false) handleOpenChange(false); - return () => handleOpenChange(false); - }, [parentMenuContext.open, handleOpenChange]); - return /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpopper.Root, popperScope, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuProvider, { - scope: __scopeMenu, - open: open, - onOpenChange: handleOpenChange, - content: content, - onContentChange: setContent - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuSubProvider, { - scope: __scopeMenu, - contentId: $cnSS2$radixuireactid.useId(), - triggerId: $cnSS2$radixuireactid.useId(), - trigger: trigger, - onTriggerChange: setTrigger - }, children))); -}; -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$71bdb9d1e2909932, { - displayName: $213e4d2df823067d$var$SUB_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSubTrigger - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SUB_TRIGGER_NAME = 'MenuSubTrigger'; -const $213e4d2df823067d$export$5fbbb3ba7297405f = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const subContext = $213e4d2df823067d$var$useMenuSubContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const contentContext = $213e4d2df823067d$var$useMenuContentContext($213e4d2df823067d$var$SUB_TRIGGER_NAME, props.__scopeMenu); - const openTimerRef = $cnSS2$react.useRef(null); - const { - pointerGraceTimerRef: pointerGraceTimerRef, - onPointerGraceIntentChange: onPointerGraceIntentChange - } = contentContext; - const scope = { - __scopeMenu: props.__scopeMenu - }; - const clearOpenTimer = $cnSS2$react.useCallback(() => { - if (openTimerRef.current) window.clearTimeout(openTimerRef.current); - openTimerRef.current = null; - }, []); - $cnSS2$react.useEffect(() => clearOpenTimer, [clearOpenTimer]); - $cnSS2$react.useEffect(() => { - const pointerGraceTimer = pointerGraceTimerRef.current; - return () => { - window.clearTimeout(pointerGraceTimer); - onPointerGraceIntentChange(null); - }; - }, [pointerGraceTimerRef, onPointerGraceIntentChange]); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$export$9fa5ebd18bee4d43, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - asChild: true - }, scope), /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuItemImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - id: subContext.triggerId, - "aria-haspopup": "menu", - "aria-expanded": context.open, - "aria-controls": subContext.contentId, - "data-state": $213e4d2df823067d$var$getOpenState(context.open) - }, props, { - ref: $cnSS2$radixuireactcomposerefs.composeRefs(forwardedRef, subContext.onTriggerChange) // This is redundant for mouse users but we cannot determine pointer type from - , - - onClick: event => { - var _props$onClick; - (_props$onClick = props.onClick) === null || _props$onClick === void 0 || _props$onClick.call(props, event); - if (props.disabled || event.defaultPrevented) return; - /** - * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons) - * and we rely heavily on `onFocusOutside` for submenus to close when switching - * between separate submenus. - */ - event.currentTarget.focus(); - if (!context.open) context.onOpenChange(true); - }, - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerMove, $213e4d2df823067d$var$whenMouse(event => { - contentContext.onItemEnter(event); - if (event.defaultPrevented) return; - if (!props.disabled && !context.open && !openTimerRef.current) { - contentContext.onPointerGraceIntentChange(null); - openTimerRef.current = window.setTimeout(() => { - context.onOpenChange(true); - clearOpenTimer(); - }, 100); - } - })), - onPointerLeave: $cnSS2$radixuiprimitive.composeEventHandlers(props.onPointerLeave, $213e4d2df823067d$var$whenMouse(event => { - var _context$content; - clearOpenTimer(); - const contentRect = (_context$content = context.content) === null || _context$content === void 0 ? void 0 : _context$content.getBoundingClientRect(); - if (contentRect) { - var _context$content2; - // TODO: make sure to update this when we change positioning logic - const side = (_context$content2 = context.content) === null || _context$content2 === void 0 ? void 0 : _context$content2.dataset.side; - const rightSide = side === 'right'; - const bleed = rightSide ? -5 : 5; - const contentNearEdge = contentRect[rightSide ? 'left' : 'right']; - const contentFarEdge = contentRect[rightSide ? 'right' : 'left']; - contentContext.onPointerGraceIntentChange({ - area: [ - // consistently within polygon bounds - { - x: event.clientX + bleed, - y: event.clientY - }, { - x: contentNearEdge, - y: contentRect.top - }, { - x: contentFarEdge, - y: contentRect.top - }, { - x: contentFarEdge, - y: contentRect.bottom - }, { - x: contentNearEdge, - y: contentRect.bottom - }], - side: side - }); - window.clearTimeout(pointerGraceTimerRef.current); - pointerGraceTimerRef.current = window.setTimeout(() => contentContext.onPointerGraceIntentChange(null), 300); - } else { - contentContext.onTriggerLeave(event); - if (event.defaultPrevented) return; // There's 100ms where the user may leave an item before the submenu was opened. - contentContext.onPointerGraceIntentChange(null); - } - })), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - const isTypingAhead = contentContext.searchRef.current !== ''; - if (props.disabled || isTypingAhead && event.key === ' ') return; - if ($213e4d2df823067d$var$SUB_OPEN_KEYS[rootContext.dir].includes(event.key)) { - var _context$content3; - context.onOpenChange(true); // The trigger may hold focus if opened via pointer interaction - // so we ensure content is given focus again when switching to keyboard. - (_context$content3 = context.content) === null || _context$content3 === void 0 || _context$content3.focus(); // prevent window from scrolling - event.preventDefault(); - } - }) - }))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$5fbbb3ba7297405f, { - displayName: $213e4d2df823067d$var$SUB_TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * MenuSubContent - * -----------------------------------------------------------------------------------------------*/ -const $213e4d2df823067d$var$SUB_CONTENT_NAME = 'MenuSubContent'; -const $213e4d2df823067d$export$e7142ab31822bde6 = /*#__PURE__*/$cnSS2$react.forwardRef((props, forwardedRef) => { - const portalContext = $213e4d2df823067d$var$usePortalContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const { - forceMount = portalContext.forceMount, - ...subContentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const rootContext = $213e4d2df823067d$var$useMenuRootContext($213e4d2df823067d$var$CONTENT_NAME, props.__scopeMenu); - const subContext = $213e4d2df823067d$var$useMenuSubContext($213e4d2df823067d$var$SUB_CONTENT_NAME, props.__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - return /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Provider, { - scope: props.__scopeMenu - }, /*#__PURE__*/$cnSS2$react.createElement($cnSS2$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$Collection.Slot, { - scope: props.__scopeMenu - }, /*#__PURE__*/$cnSS2$react.createElement($213e4d2df823067d$var$MenuContentImpl, $parcel$interopDefault($cnSS2$babelruntimehelpersextends)({ - id: subContext.contentId, - "aria-labelledby": subContext.triggerId - }, subContentProps, { - ref: composedRefs, - align: "start", - side: rootContext.dir === 'rtl' ? 'left' : 'right', - disableOutsidePointerEvents: false, - disableOutsideScroll: false, - trapFocus: false, - onOpenAutoFocus: event => { - var _ref$current; - // when opening a submenu, focus content for keyboard users only - if (rootContext.isUsingKeyboardRef.current) (_ref$current = ref.current) === null || _ref$current === void 0 || _ref$current.focus(); - event.preventDefault(); - } // The menu might close because of focusing another menu item in the parent menu. We - , - - onCloseAutoFocus: event => event.preventDefault(), - onFocusOutside: $cnSS2$radixuiprimitive.composeEventHandlers(props.onFocusOutside, event => { - // We prevent closing when the trigger is focused to avoid triggering a re-open animation - // on pointer interaction. - if (event.target !== subContext.trigger) context.onOpenChange(false); - }), - onEscapeKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onEscapeKeyDown, event => { - rootContext.onClose(); // ensure pressing escape in submenu doesn't escape full screen mode - event.preventDefault(); - }), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - // Submenu key events bubble through portals. We only care about keys in this menu. - const isKeyDownInside = event.currentTarget.contains(event.target); - const isCloseKey = $213e4d2df823067d$var$SUB_CLOSE_KEYS[rootContext.dir].includes(event.key); - if (isKeyDownInside && isCloseKey) { - var _subContext$trigger; - context.onOpenChange(false); // We focus manually because we prevented it in `onCloseAutoFocus` - (_subContext$trigger = subContext.trigger) === null || _subContext$trigger === void 0 || _subContext$trigger.focus(); // prevent window from scrolling - event.preventDefault(); - } - }) - }))))); -}); -/*#__PURE__*/ -Object.assign($213e4d2df823067d$export$e7142ab31822bde6, { - displayName: $213e4d2df823067d$var$SUB_CONTENT_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $213e4d2df823067d$var$getOpenState(open) { - return open ? 'open' : 'closed'; -} -function $213e4d2df823067d$var$isIndeterminate(checked) { - return checked === 'indeterminate'; -} -function $213e4d2df823067d$var$getCheckedState(checked) { - return $213e4d2df823067d$var$isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked'; -} -function $213e4d2df823067d$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } -} -/** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ -function $213e4d2df823067d$var$wrapArray(array, startIndex) { - return array.map((_, index) => array[(startIndex + index) % array.length]); -} -/** - * This is the "meat" of the typeahead matching logic. It takes in all the values, - * the search and the current match, and returns the next match (or `undefined`). - * - * We normalize the search because if a user has repeatedly pressed a character, - * we want the exact same behavior as if we only had that one character - * (ie. cycle through options starting with that character) - * - * We also reorder the values by wrapping the array around the current match. - * This is so we always look forward from the current match, and picking the first - * match will always be the correct one. - * - * Finally, if the normalized search is exactly one character, we exclude the - * current match from the values because otherwise it would be the first to match always - * and focus would never move. This is as opposed to the regular case, where we - * don't want focus to move if the current match still matches. - */ -function $213e4d2df823067d$var$getNextMatch(values, search, currentMatch) { - const isRepeated = search.length > 1 && Array.from(search).every(char => char === search[0]); - const normalizedSearch = isRepeated ? search[0] : search; - const currentMatchIndex = currentMatch ? values.indexOf(currentMatch) : -1; - let wrappedValues = $213e4d2df823067d$var$wrapArray(values, Math.max(currentMatchIndex, 0)); - const excludeCurrentMatch = normalizedSearch.length === 1; - if (excludeCurrentMatch) wrappedValues = wrappedValues.filter(v => v !== currentMatch); - const nextMatch = wrappedValues.find(value => value.toLowerCase().startsWith(normalizedSearch.toLowerCase())); - return nextMatch !== currentMatch ? nextMatch : undefined; -} -// Determine if a point is inside of a polygon. -// Based on https://github.com/substack/point-in-polygon -function $213e4d2df823067d$var$isPointInPolygon(point, polygon) { - const { - x: x, - y: y - } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; -} -function $213e4d2df823067d$var$isPointerInGraceArea(event, area) { - if (!area) return false; - const cursorPos = { - x: event.clientX, - y: event.clientY - }; - return $213e4d2df823067d$var$isPointInPolygon(cursorPos, area); -} -function $213e4d2df823067d$var$whenMouse(handler) { - return event => event.pointerType === 'mouse' ? handler(event) : undefined; -} -const $213e4d2df823067d$export$be92b6f5f03c0fe9 = $213e4d2df823067d$export$d9b273488cd8ce6f; -const $213e4d2df823067d$export$b688253958b8dfe7 = $213e4d2df823067d$export$9fa5ebd18bee4d43; -const $213e4d2df823067d$export$602eac185826482c = $213e4d2df823067d$export$793392f970497feb; -const $213e4d2df823067d$export$7c6e2c02157bb7d2 = $213e4d2df823067d$export$479f0f2f71193efe; -const $213e4d2df823067d$export$eb2fcfdbd7ba97d4 = $213e4d2df823067d$export$22a631d1f72787bb; -const $213e4d2df823067d$export$b04be29aa201d4f5 = $213e4d2df823067d$export$dd37bec0e8a99143; -const $213e4d2df823067d$export$6d08773d2e66f8f2 = $213e4d2df823067d$export$2ce376c2cc3355c8; -const $213e4d2df823067d$export$16ce288f89fa631c = $213e4d2df823067d$export$f6f243521332502d; -const $213e4d2df823067d$export$a98f0dcb43a68a25 = $213e4d2df823067d$export$ea2200c9eee416b3; -const $213e4d2df823067d$export$371ab307eab489c0 = $213e4d2df823067d$export$69bd225e9817f6d0; -const $213e4d2df823067d$export$c3468e2714d175fa = $213e4d2df823067d$export$a2593e23056970a3; -const $213e4d2df823067d$export$1ff3c3f08ae963c0 = $213e4d2df823067d$export$1cec7dcdd713e220; -const $213e4d2df823067d$export$21b07c8f274aebd5 = $213e4d2df823067d$export$bcdda4773debf5fa; -const $213e4d2df823067d$export$d7a01e11500dfb6f = $213e4d2df823067d$export$71bdb9d1e2909932; -const $213e4d2df823067d$export$2ea8a7a591ac5eac = $213e4d2df823067d$export$5fbbb3ba7297405f; -const $213e4d2df823067d$export$6d4de93b380beddf = $213e4d2df823067d$export$e7142ab31822bde6; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-popper/dist/index.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-popper/dist/index.js ***! - \******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $50Iv9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $50Iv9$react = __webpack_require__(/*! react */ "react"); -var $50Iv9$floatinguireactdom = __webpack_require__(/*! @floating-ui/react-dom */ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js"); -var $50Iv9$radixuireactarrow = __webpack_require__(/*! @radix-ui/react-arrow */ "../../../node_modules/@radix-ui/react-arrow/dist/index.js"); -var $50Iv9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $50Iv9$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $50Iv9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $50Iv9$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $50Iv9$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -var $50Iv9$radixuireactusesize = __webpack_require__(/*! @radix-ui/react-use-size */ "../../../node_modules/@radix-ui/react-use-size/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createPopperScope", () => $34310caa050a8d63$export$722aac194ae923); -$parcel$export(module.exports, "Popper", () => $34310caa050a8d63$export$badac9ada3a0bdf9); -$parcel$export(module.exports, "PopperAnchor", () => $34310caa050a8d63$export$ecd4e1ccab6ed6d); -$parcel$export(module.exports, "PopperContent", () => $34310caa050a8d63$export$bc4ae5855d3c4fc); -$parcel$export(module.exports, "PopperArrow", () => $34310caa050a8d63$export$79d62cd4e10a3fd0); -$parcel$export(module.exports, "Root", () => $34310caa050a8d63$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Anchor", () => $34310caa050a8d63$export$b688253958b8dfe7); -$parcel$export(module.exports, "Content", () => $34310caa050a8d63$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Arrow", () => $34310caa050a8d63$export$21b07c8f274aebd5); -$parcel$export(module.exports, "SIDE_OPTIONS", () => $34310caa050a8d63$export$36f0086da09c4b9f); -$parcel$export(module.exports, "ALIGN_OPTIONS", () => $34310caa050a8d63$export$3671ffab7b302fc9); -const $34310caa050a8d63$export$36f0086da09c4b9f = ['top', 'right', 'bottom', 'left']; -const $34310caa050a8d63$export$3671ffab7b302fc9 = ['start', 'center', 'end']; -/* ------------------------------------------------------------------------------------------------- - * Popper - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$POPPER_NAME = 'Popper'; -const [$34310caa050a8d63$var$createPopperContext, $34310caa050a8d63$export$722aac194ae923] = $50Iv9$radixuireactcontext.createContextScope($34310caa050a8d63$var$POPPER_NAME); -const [$34310caa050a8d63$var$PopperProvider, $34310caa050a8d63$var$usePopperContext] = $34310caa050a8d63$var$createPopperContext($34310caa050a8d63$var$POPPER_NAME); -const $34310caa050a8d63$export$badac9ada3a0bdf9 = props => { - const { - __scopePopper: __scopePopper, - children: children - } = props; - const [anchor, setAnchor] = $50Iv9$react.useState(null); - return /*#__PURE__*/$50Iv9$react.createElement($34310caa050a8d63$var$PopperProvider, { - scope: __scopePopper, - anchor: anchor, - onAnchorChange: setAnchor - }, children); -}; -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$badac9ada3a0bdf9, { - displayName: $34310caa050a8d63$var$POPPER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * PopperAnchor - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$ANCHOR_NAME = 'PopperAnchor'; -const $34310caa050a8d63$export$ecd4e1ccab6ed6d = /*#__PURE__*/$50Iv9$react.forwardRef((props, forwardedRef) => { - const { - __scopePopper: __scopePopper, - virtualRef: virtualRef, - ...anchorProps - } = props; - const context = $34310caa050a8d63$var$usePopperContext($34310caa050a8d63$var$ANCHOR_NAME, __scopePopper); - const ref = $50Iv9$react.useRef(null); - const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - $50Iv9$react.useEffect(() => { - // Consumer can anchor the popper to something that isn't - // a DOM node e.g. pointer position, so we override the - // `anchorRef` with their virtual ref in this case. - context.onAnchorChange((virtualRef === null || virtualRef === void 0 ? void 0 : virtualRef.current) || ref.current); - }); - return virtualRef ? null : /*#__PURE__*/$50Iv9$react.createElement($50Iv9$radixuireactprimitive.Primitive.div, $parcel$interopDefault($50Iv9$babelruntimehelpersextends)({}, anchorProps, { - ref: composedRefs - })); -}); -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$ecd4e1ccab6ed6d, { - displayName: $34310caa050a8d63$var$ANCHOR_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * PopperContent - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$CONTENT_NAME = 'PopperContent'; -const [$34310caa050a8d63$var$PopperContentProvider, $34310caa050a8d63$var$useContentContext] = $34310caa050a8d63$var$createPopperContext($34310caa050a8d63$var$CONTENT_NAME); -const $34310caa050a8d63$export$bc4ae5855d3c4fc = /*#__PURE__*/$50Iv9$react.forwardRef((props, forwardedRef) => { - var _arrowSize$width, _arrowSize$height, _middlewareData$arrow, _middlewareData$arrow2, _middlewareData$arrow3, _middlewareData$trans, _middlewareData$trans2, _middlewareData$hide; - const { - __scopePopper: __scopePopper, - side = 'bottom', - sideOffset = 0, - align = 'center', - alignOffset = 0, - arrowPadding = 0, - collisionBoundary = [], - collisionPadding: collisionPaddingProp = 0, - sticky = 'partial', - hideWhenDetached = false, - avoidCollisions = true, - onPlaced: onPlaced, - ...contentProps - } = props; - const context = $34310caa050a8d63$var$usePopperContext($34310caa050a8d63$var$CONTENT_NAME, __scopePopper); - const [content, setContent] = $50Iv9$react.useState(null); - const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs(forwardedRef, node => setContent(node)); - const [arrow, setArrow] = $50Iv9$react.useState(null); - const arrowSize = $50Iv9$radixuireactusesize.useSize(arrow); - const arrowWidth = (_arrowSize$width = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.width) !== null && _arrowSize$width !== void 0 ? _arrowSize$width : 0; - const arrowHeight = (_arrowSize$height = arrowSize === null || arrowSize === void 0 ? void 0 : arrowSize.height) !== null && _arrowSize$height !== void 0 ? _arrowSize$height : 0; - const desiredPlacement = side + (align !== 'center' ? '-' + align : ''); - const collisionPadding = typeof collisionPaddingProp === 'number' ? collisionPaddingProp : { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...collisionPaddingProp - }; - const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary]; - const hasExplicitBoundaries = boundary.length > 0; - const detectOverflowOptions = { - padding: collisionPadding, - boundary: boundary.filter($34310caa050a8d63$var$isNotNull), - // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries - altBoundary: hasExplicitBoundaries - }; - const { - refs: refs, - floatingStyles: floatingStyles, - placement: placement, - isPositioned: isPositioned, - middlewareData: middlewareData - } = $50Iv9$floatinguireactdom.useFloating({ - // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues - strategy: 'fixed', - placement: desiredPlacement, - whileElementsMounted: $50Iv9$floatinguireactdom.autoUpdate, - elements: { - reference: context.anchor - }, - middleware: [$50Iv9$floatinguireactdom.offset({ - mainAxis: sideOffset + arrowHeight, - alignmentAxis: alignOffset - }), avoidCollisions && $50Iv9$floatinguireactdom.shift({ - mainAxis: true, - crossAxis: false, - limiter: sticky === 'partial' ? $50Iv9$floatinguireactdom.limitShift() : undefined, - ...detectOverflowOptions - }), avoidCollisions && $50Iv9$floatinguireactdom.flip({ - ...detectOverflowOptions - }), $50Iv9$floatinguireactdom.size({ - ...detectOverflowOptions, - apply: ({ - elements: elements, - rects: rects, - availableWidth: availableWidth, - availableHeight: availableHeight - }) => { - const { - width: anchorWidth, - height: anchorHeight - } = rects.reference; - const contentStyle = elements.floating.style; - contentStyle.setProperty('--radix-popper-available-width', `${availableWidth}px`); - contentStyle.setProperty('--radix-popper-available-height', `${availableHeight}px`); - contentStyle.setProperty('--radix-popper-anchor-width', `${anchorWidth}px`); - contentStyle.setProperty('--radix-popper-anchor-height', `${anchorHeight}px`); - } - }), arrow && $50Iv9$floatinguireactdom.arrow({ - element: arrow, - padding: arrowPadding - }), $34310caa050a8d63$var$transformOrigin({ - arrowWidth: arrowWidth, - arrowHeight: arrowHeight - }), hideWhenDetached && $50Iv9$floatinguireactdom.hide({ - strategy: 'referenceHidden' - })] - }); - const [placedSide, placedAlign] = $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); - const handlePlaced = $50Iv9$radixuireactusecallbackref.useCallbackRef(onPlaced); - $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { - if (isPositioned) handlePlaced === null || handlePlaced === void 0 || handlePlaced(); - }, [isPositioned, handlePlaced]); - const arrowX = (_middlewareData$arrow = middlewareData.arrow) === null || _middlewareData$arrow === void 0 ? void 0 : _middlewareData$arrow.x; - const arrowY = (_middlewareData$arrow2 = middlewareData.arrow) === null || _middlewareData$arrow2 === void 0 ? void 0 : _middlewareData$arrow2.y; - const cannotCenterArrow = ((_middlewareData$arrow3 = middlewareData.arrow) === null || _middlewareData$arrow3 === void 0 ? void 0 : _middlewareData$arrow3.centerOffset) !== 0; - const [contentZIndex, setContentZIndex] = $50Iv9$react.useState(); - $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { - if (content) setContentZIndex(window.getComputedStyle(content).zIndex); - }, [content]); - return /*#__PURE__*/$50Iv9$react.createElement("div", { - ref: refs.setFloating, - "data-radix-popper-content-wrapper": "", - style: { - ...floatingStyles, - transform: isPositioned ? floatingStyles.transform : 'translate(0, -200%)', - // keep off the page when measuring - minWidth: 'max-content', - zIndex: contentZIndex, - ['--radix-popper-transform-origin']: [(_middlewareData$trans = middlewareData.transformOrigin) === null || _middlewareData$trans === void 0 ? void 0 : _middlewareData$trans.x, (_middlewareData$trans2 = middlewareData.transformOrigin) === null || _middlewareData$trans2 === void 0 ? void 0 : _middlewareData$trans2.y].join(' ') - } // Floating UI interally calculates logical alignment based the `dir` attribute on - , - - dir: props.dir - }, /*#__PURE__*/$50Iv9$react.createElement($34310caa050a8d63$var$PopperContentProvider, { - scope: __scopePopper, - placedSide: placedSide, - onArrowChange: setArrow, - arrowX: arrowX, - arrowY: arrowY, - shouldHideArrow: cannotCenterArrow - }, /*#__PURE__*/$50Iv9$react.createElement($50Iv9$radixuireactprimitive.Primitive.div, $parcel$interopDefault($50Iv9$babelruntimehelpersextends)({ - "data-side": placedSide, - "data-align": placedAlign - }, contentProps, { - ref: composedRefs, - style: { - ...contentProps.style, - // if the PopperContent hasn't been placed yet (not all measurements done) - // we prevent animations so that users's animation don't kick in too early referring wrong sides - animation: !isPositioned ? 'none' : undefined, - // hide the content if using the hide middleware and should be hidden - opacity: (_middlewareData$hide = middlewareData.hide) !== null && _middlewareData$hide !== void 0 && _middlewareData$hide.referenceHidden ? 0 : undefined - } - })))); -}); -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$bc4ae5855d3c4fc, { - displayName: $34310caa050a8d63$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * PopperArrow - * -----------------------------------------------------------------------------------------------*/ -const $34310caa050a8d63$var$ARROW_NAME = 'PopperArrow'; -const $34310caa050a8d63$var$OPPOSITE_SIDE = { - top: 'bottom', - right: 'left', - bottom: 'top', - left: 'right' -}; -const $34310caa050a8d63$export$79d62cd4e10a3fd0 = /*#__PURE__*/$50Iv9$react.forwardRef(function $34310caa050a8d63$export$79d62cd4e10a3fd0(props, forwardedRef) { - const { - __scopePopper: __scopePopper, - ...arrowProps - } = props; - const contentContext = $34310caa050a8d63$var$useContentContext($34310caa050a8d63$var$ARROW_NAME, __scopePopper); - const baseSide = $34310caa050a8d63$var$OPPOSITE_SIDE[contentContext.placedSide]; - return /*#__PURE__*/ (// we have to use an extra wrapper because `ResizeObserver` (used by `useSize`) - // doesn't report size as we'd expect on SVG elements. - // it reports their bounding box which is effectively the largest path inside the SVG. - $50Iv9$react.createElement("span", { - ref: contentContext.onArrowChange, - style: { - position: 'absolute', - left: contentContext.arrowX, - top: contentContext.arrowY, - [baseSide]: 0, - transformOrigin: { - top: '', - right: '0 0', - bottom: 'center 0', - left: '100% 0' - }[contentContext.placedSide], - transform: { - top: 'translateY(100%)', - right: 'translateY(50%) rotate(90deg) translateX(-50%)', - bottom: `rotate(180deg)`, - left: 'translateY(50%) rotate(-90deg) translateX(50%)' - }[contentContext.placedSide], - visibility: contentContext.shouldHideArrow ? 'hidden' : undefined - } - }, /*#__PURE__*/$50Iv9$react.createElement($50Iv9$radixuireactarrow.Root, $parcel$interopDefault($50Iv9$babelruntimehelpersextends)({}, arrowProps, { - ref: forwardedRef, - style: { - ...arrowProps.style, - // ensures the element can be measured correctly (mostly for if SVG) - display: 'block' - } - }))) - ); -}); -/*#__PURE__*/ -Object.assign($34310caa050a8d63$export$79d62cd4e10a3fd0, { - displayName: $34310caa050a8d63$var$ARROW_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $34310caa050a8d63$var$isNotNull(value) { - return value !== null; -} -const $34310caa050a8d63$var$transformOrigin = options => ({ - name: 'transformOrigin', - options: options, - fn(data) { - var _middlewareData$arrow4, _middlewareData$arrow5, _middlewareData$arrow6, _middlewareData$arrow7, _middlewareData$arrow8; - const { - placement: placement, - rects: rects, - middlewareData: middlewareData - } = data; - const cannotCenterArrow = ((_middlewareData$arrow4 = middlewareData.arrow) === null || _middlewareData$arrow4 === void 0 ? void 0 : _middlewareData$arrow4.centerOffset) !== 0; - const isArrowHidden = cannotCenterArrow; - const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; - const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; - const [placedSide, placedAlign] = $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); - const noArrowAlign = { - start: '0%', - center: '50%', - end: '100%' - }[placedAlign]; - const arrowXCenter = ((_middlewareData$arrow5 = (_middlewareData$arrow6 = middlewareData.arrow) === null || _middlewareData$arrow6 === void 0 ? void 0 : _middlewareData$arrow6.x) !== null && _middlewareData$arrow5 !== void 0 ? _middlewareData$arrow5 : 0) + arrowWidth / 2; - const arrowYCenter = ((_middlewareData$arrow7 = (_middlewareData$arrow8 = middlewareData.arrow) === null || _middlewareData$arrow8 === void 0 ? void 0 : _middlewareData$arrow8.y) !== null && _middlewareData$arrow7 !== void 0 ? _middlewareData$arrow7 : 0) + arrowHeight / 2; - let x = ''; - let y = ''; - if (placedSide === 'bottom') { - x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; - y = `${-arrowHeight}px`; - } else if (placedSide === 'top') { - x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; - y = `${rects.floating.height + arrowHeight}px`; - } else if (placedSide === 'right') { - x = `${-arrowHeight}px`; - y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; - } else if (placedSide === 'left') { - x = `${rects.floating.width + arrowHeight}px`; - y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; - } - return { - data: { - x: x, - y: y - } - }; - } -}); -function $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement) { - const [side, align = 'center'] = placement.split('-'); - return [side, align]; -} -const $34310caa050a8d63$export$be92b6f5f03c0fe9 = $34310caa050a8d63$export$badac9ada3a0bdf9; -const $34310caa050a8d63$export$b688253958b8dfe7 = $34310caa050a8d63$export$ecd4e1ccab6ed6d; -const $34310caa050a8d63$export$7c6e2c02157bb7d2 = $34310caa050a8d63$export$bc4ae5855d3c4fc; -const $34310caa050a8d63$export$21b07c8f274aebd5 = $34310caa050a8d63$export$79d62cd4e10a3fd0; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-portal/dist/index.js": -/*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-portal/dist/index.js ***! - \******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $amzHf$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $amzHf$react = __webpack_require__(/*! react */ "react"); -var $amzHf$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); -var $amzHf$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Portal", () => $913a70b877676c16$export$602eac185826482c); -$parcel$export(module.exports, "Root", () => $913a70b877676c16$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * Portal - * -----------------------------------------------------------------------------------------------*/ -const $913a70b877676c16$var$PORTAL_NAME = 'Portal'; -const $913a70b877676c16$export$602eac185826482c = /*#__PURE__*/$amzHf$react.forwardRef((props, forwardedRef) => { - var _globalThis$document; - const { - container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body, - ...portalProps - } = props; - return container ? /*#__PURE__*/$parcel$interopDefault($amzHf$reactdom).createPortal( /*#__PURE__*/$amzHf$react.createElement($amzHf$radixuireactprimitive.Primitive.div, $parcel$interopDefault($amzHf$babelruntimehelpersextends)({}, portalProps, { - ref: forwardedRef - })), container) : null; -}); -/*#__PURE__*/ -Object.assign($913a70b877676c16$export$602eac185826482c, { - displayName: $913a70b877676c16$var$PORTAL_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $913a70b877676c16$export$be92b6f5f03c0fe9 = $913a70b877676c16$export$602eac185826482c; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-presence/dist/index.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-presence/dist/index.js ***! - \********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $fnLeV$react = __webpack_require__(/*! react */ "react"); -var $fnLeV$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); -var $fnLeV$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $fnLeV$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "Presence", () => $a2fa0214bb2735a1$export$99c2b779aa4e8b8b); -function $8f63844556d0d3cd$export$3e6543de14f8614f(initialState, machine) { - return $fnLeV$react.useReducer((state, event) => { - const nextState = machine[state][event]; - return nextState !== null && nextState !== void 0 ? nextState : state; - }, initialState); -} -const $a2fa0214bb2735a1$export$99c2b779aa4e8b8b = props => { - const { - present: present, - children: children - } = props; - const presence = $a2fa0214bb2735a1$var$usePresence(present); - const child = typeof children === 'function' ? children({ - present: presence.isPresent - }) : $fnLeV$react.Children.only(children); - const ref = $fnLeV$radixuireactcomposerefs.useComposedRefs(presence.ref, child.ref); - const forceMount = typeof children === 'function'; - return forceMount || presence.isPresent ? /*#__PURE__*/$fnLeV$react.cloneElement(child, { - ref: ref - }) : null; -}; -$a2fa0214bb2735a1$export$99c2b779aa4e8b8b.displayName = 'Presence'; -/* ------------------------------------------------------------------------------------------------- - * usePresence - * -----------------------------------------------------------------------------------------------*/ -function $a2fa0214bb2735a1$var$usePresence(present) { - const [node1, setNode] = $fnLeV$react.useState(); - const stylesRef = $fnLeV$react.useRef({}); - const prevPresentRef = $fnLeV$react.useRef(present); - const prevAnimationNameRef = $fnLeV$react.useRef('none'); - const initialState = present ? 'mounted' : 'unmounted'; - const [state, send] = $8f63844556d0d3cd$export$3e6543de14f8614f(initialState, { - mounted: { - UNMOUNT: 'unmounted', - ANIMATION_OUT: 'unmountSuspended' - }, - unmountSuspended: { - MOUNT: 'mounted', - ANIMATION_END: 'unmounted' - }, - unmounted: { - MOUNT: 'mounted' - } - }); - $fnLeV$react.useEffect(() => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none'; - }, [state]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - const styles = stylesRef.current; - const wasPresent = prevPresentRef.current; - const hasPresentChanged = wasPresent !== present; - if (hasPresentChanged) { - const prevAnimationName = prevAnimationNameRef.current; - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(styles); - if (present) send('MOUNT');else if (currentAnimationName === 'none' || (styles === null || styles === void 0 ? void 0 : styles.display) === 'none') - // If there is no exit animation or the element is hidden, animations won't run - // so we unmount instantly - send('UNMOUNT');else { - /** - * When `present` changes to `false`, we check changes to animation-name to - * determine whether an animation has started. We chose this approach (reading - * computed styles) because there is no `animationrun` event and `animationstart` - * fires after `animation-delay` has expired which would be too late. - */ - const isAnimating = prevAnimationName !== currentAnimationName; - if (wasPresent && isAnimating) send('ANIMATION_OUT');else send('UNMOUNT'); - } - prevPresentRef.current = present; - } - }, [present, send]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - if (node1) { - /** - * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel` - * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we - * make sure we only trigger ANIMATION_END for the currently active animation. - */ - const handleAnimationEnd = event => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - const isCurrentAnimation = currentAnimationName.includes(event.animationName); - if (event.target === node1 && isCurrentAnimation) - // With React 18 concurrency this update is applied - // a frame after the animation ends, creating a flash of visible content. - // By manually flushing we ensure they sync within a frame, removing the flash. - $fnLeV$reactdom.flushSync(() => send('ANIMATION_END')); - }; - const handleAnimationStart = event => { - if (event.target === node1) - // if animation occurred, store its name as the previous animation. - prevAnimationNameRef.current = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - }; - node1.addEventListener('animationstart', handleAnimationStart); - node1.addEventListener('animationcancel', handleAnimationEnd); - node1.addEventListener('animationend', handleAnimationEnd); - return () => { - node1.removeEventListener('animationstart', handleAnimationStart); - node1.removeEventListener('animationcancel', handleAnimationEnd); - node1.removeEventListener('animationend', handleAnimationEnd); - }; - } else - // Transition to the unmounted state if the node is removed prematurely. - // We avoid doing so during cleanup as the node may change but still exist. - send('ANIMATION_END'); - }, [node1, send]); - return { - isPresent: ['mounted', 'unmountSuspended'].includes(state), - ref: $fnLeV$react.useCallback(node => { - if (node) stylesRef.current = getComputedStyle(node); - setNode(node); - }, []) - }; -} -/* -----------------------------------------------------------------------------------------------*/ -function $a2fa0214bb2735a1$var$getAnimationName(styles) { - return (styles === null || styles === void 0 ? void 0 : styles.animationName) || 'none'; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-primitive/dist/index.js": -/*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-primitive/dist/index.js ***! - \*********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "createDropdownMenuScope", + () => $d1bf075a6b218014$export$c0623cd925aeb687 + ); + $parcel$export( + module.exports, + "DropdownMenu", + () => $d1bf075a6b218014$export$e44a253a59704894 + ); + $parcel$export( + module.exports, + "DropdownMenuTrigger", + () => $d1bf075a6b218014$export$d2469213b3befba9 + ); + $parcel$export( + module.exports, + "DropdownMenuPortal", + () => $d1bf075a6b218014$export$cd369b4d4d54efc9 + ); + $parcel$export( + module.exports, + "DropdownMenuContent", + () => $d1bf075a6b218014$export$6e76d93a37c01248 + ); + $parcel$export( + module.exports, + "DropdownMenuGroup", + () => $d1bf075a6b218014$export$246bebaba3a2f70e + ); + $parcel$export( + module.exports, + "DropdownMenuLabel", + () => $d1bf075a6b218014$export$76e48c5b57f24495 + ); + $parcel$export( + module.exports, + "DropdownMenuItem", + () => $d1bf075a6b218014$export$ed97964d1871885d + ); + $parcel$export( + module.exports, + "DropdownMenuCheckboxItem", + () => $d1bf075a6b218014$export$53a69729da201fa9 + ); + $parcel$export( + module.exports, + "DropdownMenuRadioGroup", + () => $d1bf075a6b218014$export$3323ad73d55f587e + ); + $parcel$export( + module.exports, + "DropdownMenuRadioItem", + () => $d1bf075a6b218014$export$e4f69b41b1637536 + ); + $parcel$export( + module.exports, + "DropdownMenuItemIndicator", + () => $d1bf075a6b218014$export$42355ae145153fb6 + ); + $parcel$export( + module.exports, + "DropdownMenuSeparator", + () => $d1bf075a6b218014$export$da160178fd3bc7e9 + ); + $parcel$export( + module.exports, + "DropdownMenuArrow", + () => $d1bf075a6b218014$export$34b8980744021ec5 + ); + $parcel$export( + module.exports, + "DropdownMenuSub", + () => $d1bf075a6b218014$export$2f307d81a64f5442 + ); + $parcel$export( + module.exports, + "DropdownMenuSubTrigger", + () => $d1bf075a6b218014$export$21dcb7ec56f874cf + ); + $parcel$export( + module.exports, + "DropdownMenuSubContent", + () => $d1bf075a6b218014$export$f34ec8bc2482cc5f + ); + $parcel$export( + module.exports, + "Root", + () => $d1bf075a6b218014$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Trigger", + () => $d1bf075a6b218014$export$41fb9f06171c75f4 + ); + $parcel$export( + module.exports, + "Portal", + () => $d1bf075a6b218014$export$602eac185826482c + ); + $parcel$export( + module.exports, + "Content", + () => $d1bf075a6b218014$export$7c6e2c02157bb7d2 + ); + $parcel$export( + module.exports, + "Group", + () => $d1bf075a6b218014$export$eb2fcfdbd7ba97d4 + ); + $parcel$export( + module.exports, + "Label", + () => $d1bf075a6b218014$export$b04be29aa201d4f5 + ); + $parcel$export( + module.exports, + "Item", + () => $d1bf075a6b218014$export$6d08773d2e66f8f2 + ); + $parcel$export( + module.exports, + "CheckboxItem", + () => $d1bf075a6b218014$export$16ce288f89fa631c + ); + $parcel$export( + module.exports, + "RadioGroup", + () => $d1bf075a6b218014$export$a98f0dcb43a68a25 + ); + $parcel$export( + module.exports, + "RadioItem", + () => $d1bf075a6b218014$export$371ab307eab489c0 + ); + $parcel$export( + module.exports, + "ItemIndicator", + () => $d1bf075a6b218014$export$c3468e2714d175fa + ); + $parcel$export( + module.exports, + "Separator", + () => $d1bf075a6b218014$export$1ff3c3f08ae963c0 + ); + $parcel$export( + module.exports, + "Arrow", + () => $d1bf075a6b218014$export$21b07c8f274aebd5 + ); + $parcel$export( + module.exports, + "Sub", + () => $d1bf075a6b218014$export$d7a01e11500dfb6f + ); + $parcel$export( + module.exports, + "SubTrigger", + () => $d1bf075a6b218014$export$2ea8a7a591ac5eac + ); + $parcel$export( + module.exports, + "SubContent", + () => $d1bf075a6b218014$export$6d4de93b380beddf + ); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenu + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$DROPDOWN_MENU_NAME = "DropdownMenu"; + const [ + $d1bf075a6b218014$var$createDropdownMenuContext, + $d1bf075a6b218014$export$c0623cd925aeb687, + ] = $7dQ7Q$radixuireactcontext.createContextScope( + $d1bf075a6b218014$var$DROPDOWN_MENU_NAME, + [$7dQ7Q$radixuireactmenu.createMenuScope] + ); + const $d1bf075a6b218014$var$useMenuScope = + $7dQ7Q$radixuireactmenu.createMenuScope(); + const [ + $d1bf075a6b218014$var$DropdownMenuProvider, + $d1bf075a6b218014$var$useDropdownMenuContext, + ] = $d1bf075a6b218014$var$createDropdownMenuContext( + $d1bf075a6b218014$var$DROPDOWN_MENU_NAME + ); + const $d1bf075a6b218014$export$e44a253a59704894 = (props) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + children: children, + dir: dir, + open: openProp, + defaultOpen: defaultOpen, + onOpenChange: onOpenChange, + modal = true, + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + const triggerRef = $7dQ7Q$react.useRef(null); + const [open = false, setOpen] = + $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ + prop: openProp, + defaultProp: defaultOpen, + onChange: onOpenChange, + }); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $d1bf075a6b218014$var$DropdownMenuProvider, + { + scope: __scopeDropdownMenu, + triggerId: $7dQ7Q$radixuireactid.useId(), + triggerRef: triggerRef, + contentId: $7dQ7Q$radixuireactid.useId(), + open: open, + onOpenChange: setOpen, + onOpenToggle: $7dQ7Q$react.useCallback( + () => setOpen((prevOpen) => !prevOpen), + [setOpen] + ), + modal: modal, + }, + /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Root, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + { + open: open, + onOpenChange: setOpen, + dir: dir, + modal: modal, + } + ), + children + ) + ); + }; + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$e44a253a59704894, { + displayName: $d1bf075a6b218014$var$DROPDOWN_MENU_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuTrigger + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$TRIGGER_NAME = "DropdownMenuTrigger"; + const $d1bf075a6b218014$export$d2469213b3befba9 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + disabled = false, + ...triggerProps + } = props; + const context = $d1bf075a6b218014$var$useDropdownMenuContext( + $d1bf075a6b218014$var$TRIGGER_NAME, + __scopeDropdownMenu + ); + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Anchor, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + { + asChild: true, + }, + menuScope + ), + /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactprimitive.Primitive.button, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + { + type: "button", + id: context.triggerId, + "aria-haspopup": "menu", + "aria-expanded": context.open, + "aria-controls": context.open + ? context.contentId + : undefined, + "data-state": context.open ? "open" : "closed", + "data-disabled": disabled ? "" : undefined, + disabled: disabled, + }, + triggerProps, + { + ref: $7dQ7Q$radixuireactcomposerefs.composeRefs( + forwardedRef, + context.triggerRef + ), + onPointerDown: $7dQ7Q$radixuiprimitive.composeEventHandlers( + props.onPointerDown, + (event) => { + // only call handler if it's the left button (mousedown gets triggered by all mouse buttons) + // but not when the control key is pressed (avoiding MacOS right click) + if ( + !disabled && + event.button === 0 && + event.ctrlKey === false + ) { + context.onOpenToggle(); // prevent trigger focusing when opening + // this allows the content to be given focus without competition + if (!context.open) event.preventDefault(); + } + } + ), + onKeyDown: $7dQ7Q$radixuiprimitive.composeEventHandlers( + props.onKeyDown, + (event) => { + if (disabled) return; + if (["Enter", " "].includes(event.key)) + context.onOpenToggle(); + if (event.key === "ArrowDown") + context.onOpenChange(true); // prevent keydown from scrolling window / first focused item to execute + // that keydown (inadvertently closing the menu) + if (["Enter", " ", "ArrowDown"].includes(event.key)) + event.preventDefault(); + } + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$d2469213b3befba9, { + displayName: $d1bf075a6b218014$var$TRIGGER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuPortal + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$PORTAL_NAME = "DropdownMenuPortal"; + const $d1bf075a6b218014$export$cd369b4d4d54efc9 = (props) => { + const { __scopeDropdownMenu: __scopeDropdownMenu, ...portalProps } = + props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Portal, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + portalProps + ) + ); + }; + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$cd369b4d4d54efc9, { + displayName: $d1bf075a6b218014$var$PORTAL_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuContent + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$CONTENT_NAME = "DropdownMenuContent"; + const $d1bf075a6b218014$export$6e76d93a37c01248 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...contentProps + } = props; + const context = $d1bf075a6b218014$var$useDropdownMenuContext( + $d1bf075a6b218014$var$CONTENT_NAME, + __scopeDropdownMenu + ); + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + const hasInteractedOutsideRef = $7dQ7Q$react.useRef(false); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Content, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + { + id: context.contentId, + "aria-labelledby": context.triggerId, + }, + menuScope, + contentProps, + { + ref: forwardedRef, + onCloseAutoFocus: + $7dQ7Q$radixuiprimitive.composeEventHandlers( + props.onCloseAutoFocus, + (event) => { + var _context$triggerRef$c; + if (!hasInteractedOutsideRef.current) + (_context$triggerRef$c = + context.triggerRef.current) === null || + _context$triggerRef$c === void 0 || + _context$triggerRef$c.focus(); + hasInteractedOutsideRef.current = false; // Always prevent auto focus because we either focus manually or want user agent focus + event.preventDefault(); + } + ), + onInteractOutside: + $7dQ7Q$radixuiprimitive.composeEventHandlers( + props.onInteractOutside, + (event) => { + const originalEvent = event.detail.originalEvent; + const ctrlLeftClick = + originalEvent.button === 0 && + originalEvent.ctrlKey === true; + const isRightClick = + originalEvent.button === 2 || ctrlLeftClick; + if (!context.modal || isRightClick) + hasInteractedOutsideRef.current = true; + } + ), + style: { + ...props.style, + "--radix-dropdown-menu-content-transform-origin": + "var(--radix-popper-transform-origin)", + "--radix-dropdown-menu-content-available-width": + "var(--radix-popper-available-width)", + "--radix-dropdown-menu-content-available-height": + "var(--radix-popper-available-height)", + "--radix-dropdown-menu-trigger-width": + "var(--radix-popper-anchor-width)", + "--radix-dropdown-menu-trigger-height": + "var(--radix-popper-anchor-height)", + }, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$6e76d93a37c01248, { + displayName: $d1bf075a6b218014$var$CONTENT_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuGroup + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$GROUP_NAME = "DropdownMenuGroup"; + const $d1bf075a6b218014$export$246bebaba3a2f70e = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { __scopeDropdownMenu: __scopeDropdownMenu, ...groupProps } = + props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Group, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + groupProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$246bebaba3a2f70e, { + displayName: $d1bf075a6b218014$var$GROUP_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuLabel + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$LABEL_NAME = "DropdownMenuLabel"; + const $d1bf075a6b218014$export$76e48c5b57f24495 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { __scopeDropdownMenu: __scopeDropdownMenu, ...labelProps } = + props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Label, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + labelProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$76e48c5b57f24495, { + displayName: $d1bf075a6b218014$var$LABEL_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuItem + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$ITEM_NAME = "DropdownMenuItem"; + const $d1bf075a6b218014$export$ed97964d1871885d = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { __scopeDropdownMenu: __scopeDropdownMenu, ...itemProps } = + props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Item, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + itemProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$ed97964d1871885d, { + displayName: $d1bf075a6b218014$var$ITEM_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuCheckboxItem + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME = + "DropdownMenuCheckboxItem"; + const $d1bf075a6b218014$export$53a69729da201fa9 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...checkboxItemProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.CheckboxItem, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + checkboxItemProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$53a69729da201fa9, { + displayName: $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuRadioGroup + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$RADIO_GROUP_NAME = "DropdownMenuRadioGroup"; + const $d1bf075a6b218014$export$3323ad73d55f587e = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...radioGroupProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.RadioGroup, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + radioGroupProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$3323ad73d55f587e, { + displayName: $d1bf075a6b218014$var$RADIO_GROUP_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuRadioItem + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$RADIO_ITEM_NAME = "DropdownMenuRadioItem"; + const $d1bf075a6b218014$export$e4f69b41b1637536 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...radioItemProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.RadioItem, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + radioItemProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$e4f69b41b1637536, { + displayName: $d1bf075a6b218014$var$RADIO_ITEM_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuItemIndicator + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$INDICATOR_NAME = + "DropdownMenuItemIndicator"; + const $d1bf075a6b218014$export$42355ae145153fb6 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...itemIndicatorProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.ItemIndicator, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + itemIndicatorProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$42355ae145153fb6, { + displayName: $d1bf075a6b218014$var$INDICATOR_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuSeparator + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$SEPARATOR_NAME = "DropdownMenuSeparator"; + const $d1bf075a6b218014$export$da160178fd3bc7e9 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...separatorProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Separator, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + separatorProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$da160178fd3bc7e9, { + displayName: $d1bf075a6b218014$var$SEPARATOR_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuArrow + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$ARROW_NAME = "DropdownMenuArrow"; + const $d1bf075a6b218014$export$34b8980744021ec5 = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { __scopeDropdownMenu: __scopeDropdownMenu, ...arrowProps } = + props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Arrow, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + arrowProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$34b8980744021ec5, { + displayName: $d1bf075a6b218014$var$ARROW_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuSub + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$export$2f307d81a64f5442 = (props) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + children: children, + open: openProp, + onOpenChange: onOpenChange, + defaultOpen: defaultOpen, + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + const [open = false, setOpen] = + $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ + prop: openProp, + defaultProp: defaultOpen, + onChange: onOpenChange, + }); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.Sub, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + { + open: open, + onOpenChange: setOpen, + } + ), + children + ); + }; + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuSubTrigger + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$SUB_TRIGGER_NAME = "DropdownMenuSubTrigger"; + const $d1bf075a6b218014$export$21dcb7ec56f874cf = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...subTriggerProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.SubTrigger, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + subTriggerProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$21dcb7ec56f874cf, { + displayName: $d1bf075a6b218014$var$SUB_TRIGGER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * DropdownMenuSubContent + * -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$var$SUB_CONTENT_NAME = "DropdownMenuSubContent"; + const $d1bf075a6b218014$export$f34ec8bc2482cc5f = + /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { + const { + __scopeDropdownMenu: __scopeDropdownMenu, + ...subContentProps + } = props; + const menuScope = + $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); + return /*#__PURE__*/ $7dQ7Q$react.createElement( + $7dQ7Q$radixuireactmenu.SubContent, + $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( + {}, + menuScope, + subContentProps, + { + ref: forwardedRef, + style: { + ...props.style, + "--radix-dropdown-menu-content-transform-origin": + "var(--radix-popper-transform-origin)", + "--radix-dropdown-menu-content-available-width": + "var(--radix-popper-available-width)", + "--radix-dropdown-menu-content-available-height": + "var(--radix-popper-available-height)", + "--radix-dropdown-menu-trigger-width": + "var(--radix-popper-anchor-width)", + "--radix-dropdown-menu-trigger-height": + "var(--radix-popper-anchor-height)", + }, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($d1bf075a6b218014$export$f34ec8bc2482cc5f, { + displayName: $d1bf075a6b218014$var$SUB_CONTENT_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + const $d1bf075a6b218014$export$be92b6f5f03c0fe9 = + $d1bf075a6b218014$export$e44a253a59704894; + const $d1bf075a6b218014$export$41fb9f06171c75f4 = + $d1bf075a6b218014$export$d2469213b3befba9; + const $d1bf075a6b218014$export$602eac185826482c = + $d1bf075a6b218014$export$cd369b4d4d54efc9; + const $d1bf075a6b218014$export$7c6e2c02157bb7d2 = + $d1bf075a6b218014$export$6e76d93a37c01248; + const $d1bf075a6b218014$export$eb2fcfdbd7ba97d4 = + $d1bf075a6b218014$export$246bebaba3a2f70e; + const $d1bf075a6b218014$export$b04be29aa201d4f5 = + $d1bf075a6b218014$export$76e48c5b57f24495; + const $d1bf075a6b218014$export$6d08773d2e66f8f2 = + $d1bf075a6b218014$export$ed97964d1871885d; + const $d1bf075a6b218014$export$16ce288f89fa631c = + $d1bf075a6b218014$export$53a69729da201fa9; + const $d1bf075a6b218014$export$a98f0dcb43a68a25 = + $d1bf075a6b218014$export$3323ad73d55f587e; + const $d1bf075a6b218014$export$371ab307eab489c0 = + $d1bf075a6b218014$export$e4f69b41b1637536; + const $d1bf075a6b218014$export$c3468e2714d175fa = + $d1bf075a6b218014$export$42355ae145153fb6; + const $d1bf075a6b218014$export$1ff3c3f08ae963c0 = + $d1bf075a6b218014$export$da160178fd3bc7e9; + const $d1bf075a6b218014$export$21b07c8f274aebd5 = + $d1bf075a6b218014$export$34b8980744021ec5; + const $d1bf075a6b218014$export$d7a01e11500dfb6f = + $d1bf075a6b218014$export$2f307d81a64f5442; + const $d1bf075a6b218014$export$2ea8a7a591ac5eac = + $d1bf075a6b218014$export$21dcb7ec56f874cf; + const $d1bf075a6b218014$export$6d4de93b380beddf = + $d1bf075a6b218014$export$f34ec8bc2482cc5f; + + /***/ + }, -var $iMixA$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $iMixA$react = __webpack_require__(/*! react */ "react"); -var $iMixA$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); -var $iMixA$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Primitive", () => $c3def6332c2749a6$export$250ffa63cdc0d034); -$parcel$export(module.exports, "Root", () => $c3def6332c2749a6$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "dispatchDiscreteCustomEvent", () => $c3def6332c2749a6$export$6d1a0317bde7de7f); -const $c3def6332c2749a6$var$NODES = ['a', 'button', 'div', 'form', 'h2', 'h3', 'img', 'input', 'label', 'li', 'nav', 'ol', 'p', 'span', 'svg', 'ul']; // Temporary while we await merge of this fix: -// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/55396 -// prettier-ignore -/* ------------------------------------------------------------------------------------------------- - * Primitive - * -----------------------------------------------------------------------------------------------*/ -const $c3def6332c2749a6$export$250ffa63cdc0d034 = $c3def6332c2749a6$var$NODES.reduce((primitive, node) => { - const Node = /*#__PURE__*/$iMixA$react.forwardRef((props, forwardedRef) => { - const { - asChild: asChild, - ...primitiveProps - } = props; - const Comp = asChild ? $iMixA$radixuireactslot.Slot : node; - $iMixA$react.useEffect(() => { - window[Symbol.for('radix-ui')] = true; - }, []); - return /*#__PURE__*/$iMixA$react.createElement(Comp, $parcel$interopDefault($iMixA$babelruntimehelpersextends)({}, primitiveProps, { - ref: forwardedRef - })); - }); - Node.displayName = `Primitive.${node}`; - return { - ...primitive, - [node]: Node - }; -}, {}); -/* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Flush custom event dispatch - * https://github.com/radix-ui/primitives/pull/1378 - * - * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types. - * - * Internally, React prioritises events in the following order: - * - discrete - * - continuous - * - default - * - * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350 - * - * `discrete` is an important distinction as updates within these events are applied immediately. - * React however, is not able to infer the priority of custom event types due to how they are detected internally. - * Because of this, it's possible for updates from custom events to be unexpectedly batched when - * dispatched by another `discrete` event. - * - * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch. - * This utility should be used when dispatching a custom event from within another `discrete` event, this utility - * is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event. - * For example: - * - * dispatching a known click 👎 - * target.dispatchEvent(new Event(‘click’)) - * - * dispatching a custom type within a non-discrete event 👎 - * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(‘customType’))} - * - * dispatching a custom type within a `discrete` event 👍 - * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(‘customType’))} - * - * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use - * this utility with them. This is because it's possible for those handlers to be called implicitly during render - * e.g. when focus is within a component as it is unmounted, or when managing focus on mount. - */ -function $c3def6332c2749a6$export$6d1a0317bde7de7f(target, event) { - if (target) $iMixA$reactdom.flushSync(() => target.dispatchEvent(event)); -} -/* -----------------------------------------------------------------------------------------------*/ -const $c3def6332c2749a6$export$be92b6f5f03c0fe9 = $c3def6332c2749a6$export$250ffa63cdc0d034; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-roving-focus/dist/index.js ***! + /***/ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-focus-guards/dist/index.js ***! \************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $9QJ9Y$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $9QJ9Y$react = __webpack_require__(/*! react */ "react"); -var $9QJ9Y$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $9QJ9Y$radixuireactcollection = __webpack_require__(/*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js"); -var $9QJ9Y$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $9QJ9Y$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $9QJ9Y$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $9QJ9Y$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $9QJ9Y$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -var $9QJ9Y$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $9QJ9Y$radixuireactdirection = __webpack_require__(/*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createRovingFocusGroupScope", () => $0063afae63b3fa70$export$c7109489551a4f4); -$parcel$export(module.exports, "RovingFocusGroup", () => $0063afae63b3fa70$export$8699f7c8af148338); -$parcel$export(module.exports, "RovingFocusGroupItem", () => $0063afae63b3fa70$export$ab9df7c53fe8454); -$parcel$export(module.exports, "Root", () => $0063afae63b3fa70$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Item", () => $0063afae63b3fa70$export$6d08773d2e66f8f2); -const $0063afae63b3fa70$var$ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus'; -const $0063afae63b3fa70$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true -}; -/* ------------------------------------------------------------------------------------------------- - * RovingFocusGroup - * -----------------------------------------------------------------------------------------------*/ -const $0063afae63b3fa70$var$GROUP_NAME = 'RovingFocusGroup'; -const [$0063afae63b3fa70$var$Collection, $0063afae63b3fa70$var$useCollection, $0063afae63b3fa70$var$createCollectionScope] = $9QJ9Y$radixuireactcollection.createCollection($0063afae63b3fa70$var$GROUP_NAME); -const [$0063afae63b3fa70$var$createRovingFocusGroupContext, $0063afae63b3fa70$export$c7109489551a4f4] = $9QJ9Y$radixuireactcontext.createContextScope($0063afae63b3fa70$var$GROUP_NAME, [$0063afae63b3fa70$var$createCollectionScope]); -const [$0063afae63b3fa70$var$RovingFocusProvider, $0063afae63b3fa70$var$useRovingFocusContext] = $0063afae63b3fa70$var$createRovingFocusGroupContext($0063afae63b3fa70$var$GROUP_NAME); -const $0063afae63b3fa70$export$8699f7c8af148338 = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.Provider, { - scope: props.__scopeRovingFocusGroup - }, /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.Slot, { - scope: props.__scopeRovingFocusGroup - }, /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$RovingFocusGroupImpl, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({}, props, { - ref: forwardedRef - })))); -}); -/*#__PURE__*/ -Object.assign($0063afae63b3fa70$export$8699f7c8af148338, { - displayName: $0063afae63b3fa70$var$GROUP_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $0063afae63b3fa70$var$RovingFocusGroupImpl = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - orientation: orientation, - loop = false, - dir: dir, - currentTabStopId: currentTabStopIdProp, - defaultCurrentTabStopId: defaultCurrentTabStopId, - onCurrentTabStopIdChange: onCurrentTabStopIdChange, - onEntryFocus: onEntryFocus, - ...groupProps - } = props; - const ref = $9QJ9Y$react.useRef(null); - const composedRefs = $9QJ9Y$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const direction = $9QJ9Y$radixuireactdirection.useDirection(dir); - const [currentTabStopId = null, setCurrentTabStopId] = $9QJ9Y$radixuireactusecontrollablestate.useControllableState({ - prop: currentTabStopIdProp, - defaultProp: defaultCurrentTabStopId, - onChange: onCurrentTabStopIdChange - }); - const [isTabbingBackOut, setIsTabbingBackOut] = $9QJ9Y$react.useState(false); - const handleEntryFocus = $9QJ9Y$radixuireactusecallbackref.useCallbackRef(onEntryFocus); - const getItems = $0063afae63b3fa70$var$useCollection(__scopeRovingFocusGroup); - const isClickFocusRef = $9QJ9Y$react.useRef(false); - const [focusableItemsCount, setFocusableItemsCount] = $9QJ9Y$react.useState(0); - $9QJ9Y$react.useEffect(() => { - const node = ref.current; - if (node) { - node.addEventListener($0063afae63b3fa70$var$ENTRY_FOCUS, handleEntryFocus); - return () => node.removeEventListener($0063afae63b3fa70$var$ENTRY_FOCUS, handleEntryFocus); - } - }, [handleEntryFocus]); - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$RovingFocusProvider, { - scope: __scopeRovingFocusGroup, - orientation: orientation, - dir: direction, - loop: loop, - currentTabStopId: currentTabStopId, - onItemFocus: $9QJ9Y$react.useCallback(tabStopId => setCurrentTabStopId(tabStopId), [setCurrentTabStopId]), - onItemShiftTab: $9QJ9Y$react.useCallback(() => setIsTabbingBackOut(true), []), - onFocusableItemAdd: $9QJ9Y$react.useCallback(() => setFocusableItemsCount(prevCount => prevCount + 1), []), - onFocusableItemRemove: $9QJ9Y$react.useCallback(() => setFocusableItemsCount(prevCount => prevCount - 1), []) - }, /*#__PURE__*/$9QJ9Y$react.createElement($9QJ9Y$radixuireactprimitive.Primitive.div, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({ - tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0, - "data-orientation": orientation - }, groupProps, { - ref: composedRefs, - style: { - outline: 'none', - ...props.style - }, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onMouseDown, () => { - isClickFocusRef.current = true; - }), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onFocus, event => { - // We normally wouldn't need this check, because we already check - // that the focus is on the current target and not bubbling to it. - // We do this because Safari doesn't focus buttons when clicked, and - // instead, the wrapper will get focused and not through a bubbling event. - const isKeyboardFocus = !isClickFocusRef.current; - if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) { - const entryFocusEvent = new CustomEvent($0063afae63b3fa70$var$ENTRY_FOCUS, $0063afae63b3fa70$var$EVENT_OPTIONS); - event.currentTarget.dispatchEvent(entryFocusEvent); - if (!entryFocusEvent.defaultPrevented) { - const items = getItems().filter(item => item.focusable); - const activeItem = items.find(item => item.active); - const currentItem = items.find(item => item.id === currentTabStopId); - const candidateItems = [activeItem, currentItem, ...items].filter(Boolean); - const candidateNodes = candidateItems.map(item => item.ref.current); - $0063afae63b3fa70$var$focusFirst(candidateNodes); + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $cnctE$react = __webpack_require__(/*! react */ "react"); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); } - } - isClickFocusRef.current = false; - }), - onBlur: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false)) - }))); -}); -/* ------------------------------------------------------------------------------------------------- - * RovingFocusGroupItem - * -----------------------------------------------------------------------------------------------*/ -const $0063afae63b3fa70$var$ITEM_NAME = 'RovingFocusGroupItem'; -const $0063afae63b3fa70$export$ab9df7c53fe8454 = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - focusable = true, - active = false, - tabStopId: tabStopId, - ...itemProps - } = props; - const autoId = $9QJ9Y$radixuireactid.useId(); - const id = tabStopId || autoId; - const context = $0063afae63b3fa70$var$useRovingFocusContext($0063afae63b3fa70$var$ITEM_NAME, __scopeRovingFocusGroup); - const isCurrentTabStop = context.currentTabStopId === id; - const getItems = $0063afae63b3fa70$var$useCollection(__scopeRovingFocusGroup); - const { - onFocusableItemAdd: onFocusableItemAdd, - onFocusableItemRemove: onFocusableItemRemove - } = context; - $9QJ9Y$react.useEffect(() => { - if (focusable) { - onFocusableItemAdd(); - return () => onFocusableItemRemove(); - } - }, [focusable, onFocusableItemAdd, onFocusableItemRemove]); - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.ItemSlot, { - scope: __scopeRovingFocusGroup, - id: id, - focusable: focusable, - active: active - }, /*#__PURE__*/$9QJ9Y$react.createElement($9QJ9Y$radixuireactprimitive.Primitive.span, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({ - tabIndex: isCurrentTabStop ? 0 : -1, - "data-orientation": context.orientation - }, itemProps, { - ref: forwardedRef, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onMouseDown, event => { - // We prevent focusing non-focusable items on `mousedown`. - // Even though the item has tabIndex={-1}, that only means take it out of the tab order. - if (!focusable) event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also - else context.onItemFocus(id); - }), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onFocus, () => context.onItemFocus(id)), - onKeyDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - if (event.key === 'Tab' && event.shiftKey) { - context.onItemShiftTab(); - return; - } - if (event.target !== event.currentTarget) return; - const focusIntent = $0063afae63b3fa70$var$getFocusIntent(event, context.orientation, context.dir); - if (focusIntent !== undefined) { - event.preventDefault(); - const items = getItems().filter(item => item.focusable); - let candidateNodes = items.map(item => item.ref.current); - if (focusIntent === 'last') candidateNodes.reverse();else if (focusIntent === 'prev' || focusIntent === 'next') { - if (focusIntent === 'prev') candidateNodes.reverse(); - const currentIndex = candidateNodes.indexOf(event.currentTarget); - candidateNodes = context.loop ? $0063afae63b3fa70$var$wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1); - } - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => $0063afae63b3fa70$var$focusFirst(candidateNodes)); - } - }) - }))); -}); -/*#__PURE__*/ -Object.assign($0063afae63b3fa70$export$ab9df7c53fe8454, { - displayName: $0063afae63b3fa70$var$ITEM_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ // prettier-ignore -const $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT = { - ArrowLeft: 'prev', - ArrowUp: 'prev', - ArrowRight: 'next', - ArrowDown: 'next', - PageUp: 'first', - Home: 'first', - PageDown: 'last', - End: 'last' -}; -function $0063afae63b3fa70$var$getDirectionAwareKey(key, dir) { - if (dir !== 'rtl') return key; - return key === 'ArrowLeft' ? 'ArrowRight' : key === 'ArrowRight' ? 'ArrowLeft' : key; -} -function $0063afae63b3fa70$var$getFocusIntent(event, orientation, dir) { - const key = $0063afae63b3fa70$var$getDirectionAwareKey(event.key, dir); - if (orientation === 'vertical' && ['ArrowLeft', 'ArrowRight'].includes(key)) return undefined; - if (orientation === 'horizontal' && ['ArrowUp', 'ArrowDown'].includes(key)) return undefined; - return $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT[key]; -} -function $0063afae63b3fa70$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } -} -/** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ -function $0063afae63b3fa70$var$wrapArray(array, startIndex) { - return array.map((_, index) => array[(startIndex + index) % array.length]); -} -const $0063afae63b3fa70$export$be92b6f5f03c0fe9 = $0063afae63b3fa70$export$8699f7c8af148338; -const $0063afae63b3fa70$export$6d08773d2e66f8f2 = $0063afae63b3fa70$export$ab9df7c53fe8454; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-slot/dist/index.js": -/*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-slot/dist/index.js ***! - \****************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - + $parcel$export( + module.exports, + "FocusGuards", + () => $71476a6ed7dbbaf3$export$ac5b58043b79449b + ); + $parcel$export( + module.exports, + "Root", + () => $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "useFocusGuards", + () => $71476a6ed7dbbaf3$export$b7ece24a22aeda8c + ); -var $dAvBt$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $dAvBt$react = __webpack_require__(/*! react */ "react"); -var $dAvBt$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "Slot", () => $82dc8d030dec7549$export$8c6ed5c666ac1360); -$parcel$export(module.exports, "Slottable", () => $82dc8d030dec7549$export$d9f1ccf0bdb05d45); -$parcel$export(module.exports, "Root", () => $82dc8d030dec7549$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * Slot - * -----------------------------------------------------------------------------------------------*/ -const $82dc8d030dec7549$export$8c6ed5c666ac1360 = /*#__PURE__*/$dAvBt$react.forwardRef((props, forwardedRef) => { - const { - children: children, - ...slotProps - } = props; - const childrenArray = $dAvBt$react.Children.toArray(children); - const slottable = childrenArray.find($82dc8d030dec7549$var$isSlottable); - if (slottable) { - // the new element to render is the one passed as a child of `Slottable` - const newElement = slottable.props.children; - const newChildren = childrenArray.map(child => { - if (child === slottable) { - // because the new element will be the one rendered, we are only interested - // in grabbing its children (`newElement.props.children`) - if ($dAvBt$react.Children.count(newElement) > 1) return $dAvBt$react.Children.only(null); - return /*#__PURE__*/$dAvBt$react.isValidElement(newElement) ? newElement.props.children : null; - } else return child; - }); - return /*#__PURE__*/$dAvBt$react.createElement($82dc8d030dec7549$var$SlotClone, $parcel$interopDefault($dAvBt$babelruntimehelpersextends)({}, slotProps, { - ref: forwardedRef - }), /*#__PURE__*/$dAvBt$react.isValidElement(newElement) ? /*#__PURE__*/$dAvBt$react.cloneElement(newElement, undefined, newChildren) : null); - } - return /*#__PURE__*/$dAvBt$react.createElement($82dc8d030dec7549$var$SlotClone, $parcel$interopDefault($dAvBt$babelruntimehelpersextends)({}, slotProps, { - ref: forwardedRef - }), children); -}); -$82dc8d030dec7549$export$8c6ed5c666ac1360.displayName = 'Slot'; -/* ------------------------------------------------------------------------------------------------- - * SlotClone - * -----------------------------------------------------------------------------------------------*/ -const $82dc8d030dec7549$var$SlotClone = /*#__PURE__*/$dAvBt$react.forwardRef((props, forwardedRef) => { - const { - children: children, - ...slotProps - } = props; - if ( /*#__PURE__*/$dAvBt$react.isValidElement(children)) return /*#__PURE__*/$dAvBt$react.cloneElement(children, { - ...$82dc8d030dec7549$var$mergeProps(slotProps, children.props), - ref: forwardedRef ? $dAvBt$radixuireactcomposerefs.composeRefs(forwardedRef, children.ref) : children.ref - }); - return $dAvBt$react.Children.count(children) > 1 ? $dAvBt$react.Children.only(null) : null; -}); -$82dc8d030dec7549$var$SlotClone.displayName = 'SlotClone'; -/* ------------------------------------------------------------------------------------------------- - * Slottable - * -----------------------------------------------------------------------------------------------*/ -const $82dc8d030dec7549$export$d9f1ccf0bdb05d45 = ({ - children: children -}) => { - return /*#__PURE__*/$dAvBt$react.createElement($dAvBt$react.Fragment, null, children); -}; -/* ---------------------------------------------------------------------------------------------- */ -function $82dc8d030dec7549$var$isSlottable(child) { - return /*#__PURE__*/$dAvBt$react.isValidElement(child) && child.type === $82dc8d030dec7549$export$d9f1ccf0bdb05d45; -} -function $82dc8d030dec7549$var$mergeProps(slotProps, childProps) { - // all child props should override - const overrideProps = { - ...childProps - }; - for (const propName in childProps) { - const slotPropValue = slotProps[propName]; - const childPropValue = childProps[propName]; - const isHandler = /^on[A-Z]/.test(propName); - if (isHandler) { - // if the handler exists on both, we compose them - if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => { - childPropValue(...args); - slotPropValue(...args); - };else if (slotPropValue) overrideProps[propName] = slotPropValue; - } else if (propName === 'style') overrideProps[propName] = { - ...slotPropValue, - ...childPropValue - };else if (propName === 'className') overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' '); - } - return { - ...slotProps, - ...overrideProps - }; -} -const $82dc8d030dec7549$export$be92b6f5f03c0fe9 = $82dc8d030dec7549$export$8c6ed5c666ac1360; + /** Number of components which have requested interest to have focus guards */ + let $71476a6ed7dbbaf3$var$count = 0; + function $71476a6ed7dbbaf3$export$ac5b58043b79449b(props) { + $71476a6ed7dbbaf3$export$b7ece24a22aeda8c(); + return props.children; + } + /** + * Injects a pair of focus guards at the edges of the whole DOM tree + * to ensure `focusin` & `focusout` events can be caught consistently. + */ + function $71476a6ed7dbbaf3$export$b7ece24a22aeda8c() { + $cnctE$react.useEffect(() => { + var _edgeGuards$, _edgeGuards$2; + const edgeGuards = document.querySelectorAll( + "[data-radix-focus-guard]" + ); + document.body.insertAdjacentElement( + "afterbegin", + (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 + ? _edgeGuards$ + : $71476a6ed7dbbaf3$var$createFocusGuard() + ); + document.body.insertAdjacentElement( + "beforeend", + (_edgeGuards$2 = edgeGuards[1]) !== null && + _edgeGuards$2 !== void 0 + ? _edgeGuards$2 + : $71476a6ed7dbbaf3$var$createFocusGuard() + ); + $71476a6ed7dbbaf3$var$count++; + return () => { + if ($71476a6ed7dbbaf3$var$count === 1) + document + .querySelectorAll("[data-radix-focus-guard]") + .forEach((node) => node.remove()); + $71476a6ed7dbbaf3$var$count--; + }; + }, []); + } + function $71476a6ed7dbbaf3$var$createFocusGuard() { + const element = document.createElement("span"); + element.setAttribute("data-radix-focus-guard", ""); + element.tabIndex = 0; + element.style.cssText = + "outline: none; opacity: 0; position: fixed; pointer-events: none"; + return element; + } + const $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9 = + $71476a6ed7dbbaf3$export$ac5b58043b79449b; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-tooltip/dist/index.js ***! - \*******************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $iVrL9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $iVrL9$react = __webpack_require__(/*! react */ "react"); -var $iVrL9$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); -var $iVrL9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); -var $iVrL9$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); -var $iVrL9$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); -var $iVrL9$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); -var $iVrL9$radixuireactpopper = __webpack_require__(/*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js"); -var $iVrL9$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); -var $iVrL9$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); -var $iVrL9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -var $iVrL9$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); -var $iVrL9$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); -var $iVrL9$radixuireactvisuallyhidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "createTooltipScope", () => $c34afbc43c90cc6f$export$1c540a2224f0d865); -$parcel$export(module.exports, "TooltipProvider", () => $c34afbc43c90cc6f$export$f78649fb9ca566b8); -$parcel$export(module.exports, "Tooltip", () => $c34afbc43c90cc6f$export$28c660c63b792dea); -$parcel$export(module.exports, "TooltipTrigger", () => $c34afbc43c90cc6f$export$8c610744efcf8a1d); -$parcel$export(module.exports, "TooltipPortal", () => $c34afbc43c90cc6f$export$7b36b8f925ab7497); -$parcel$export(module.exports, "TooltipContent", () => $c34afbc43c90cc6f$export$e9003e2be37ec060); -$parcel$export(module.exports, "TooltipArrow", () => $c34afbc43c90cc6f$export$c27ee0ad710f7559); -$parcel$export(module.exports, "Provider", () => $c34afbc43c90cc6f$export$2881499e37b75b9a); -$parcel$export(module.exports, "Root", () => $c34afbc43c90cc6f$export$be92b6f5f03c0fe9); -$parcel$export(module.exports, "Trigger", () => $c34afbc43c90cc6f$export$41fb9f06171c75f4); -$parcel$export(module.exports, "Portal", () => $c34afbc43c90cc6f$export$602eac185826482c); -$parcel$export(module.exports, "Content", () => $c34afbc43c90cc6f$export$7c6e2c02157bb7d2); -$parcel$export(module.exports, "Arrow", () => $c34afbc43c90cc6f$export$21b07c8f274aebd5); -const [$c34afbc43c90cc6f$var$createTooltipContext, $c34afbc43c90cc6f$export$1c540a2224f0d865] = $iVrL9$radixuireactcontext.createContextScope('Tooltip', [$iVrL9$radixuireactpopper.createPopperScope]); -const $c34afbc43c90cc6f$var$usePopperScope = $iVrL9$radixuireactpopper.createPopperScope(); -/* ------------------------------------------------------------------------------------------------- - * TooltipProvider - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$PROVIDER_NAME = 'TooltipProvider'; -const $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION = 700; -const $c34afbc43c90cc6f$var$TOOLTIP_OPEN = 'tooltip.open'; -const [$c34afbc43c90cc6f$var$TooltipProviderContextProvider, $c34afbc43c90cc6f$var$useTooltipProviderContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$PROVIDER_NAME); -const $c34afbc43c90cc6f$export$f78649fb9ca566b8 = props => { - const { - __scopeTooltip: __scopeTooltip, - delayDuration = $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION, - skipDelayDuration = 300, - disableHoverableContent = false, - children: children - } = props; - const [isOpenDelayed, setIsOpenDelayed] = $iVrL9$react.useState(true); - const isPointerInTransitRef = $iVrL9$react.useRef(false); - const skipDelayTimerRef = $iVrL9$react.useRef(0); - $iVrL9$react.useEffect(() => { - const skipDelayTimer = skipDelayTimerRef.current; - return () => window.clearTimeout(skipDelayTimer); - }, []); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipProviderContextProvider, { - scope: __scopeTooltip, - isOpenDelayed: isOpenDelayed, - delayDuration: delayDuration, - onOpen: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - setIsOpenDelayed(false); - }, []), - onClose: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - skipDelayTimerRef.current = window.setTimeout(() => setIsOpenDelayed(true), skipDelayDuration); - }, [skipDelayDuration]), - isPointerInTransitRef: isPointerInTransitRef, - onPointerInTransitChange: $iVrL9$react.useCallback(inTransit => { - isPointerInTransitRef.current = inTransit; - }, []), - disableHoverableContent: disableHoverableContent - }, children); -}; -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$f78649fb9ca566b8, { - displayName: $c34afbc43c90cc6f$var$PROVIDER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * Tooltip - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$TOOLTIP_NAME = 'Tooltip'; -const [$c34afbc43c90cc6f$var$TooltipContextProvider, $c34afbc43c90cc6f$var$useTooltipContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$TOOLTIP_NAME); -const $c34afbc43c90cc6f$export$28c660c63b792dea = props => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - open: openProp, - defaultOpen = false, - onOpenChange: onOpenChange, - disableHoverableContent: disableHoverableContentProp, - delayDuration: delayDurationProp - } = props; - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$TOOLTIP_NAME, props.__scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const [trigger, setTrigger] = $iVrL9$react.useState(null); - const contentId = $iVrL9$radixuireactid.useId(); - const openTimerRef = $iVrL9$react.useRef(0); - const disableHoverableContent = disableHoverableContentProp !== null && disableHoverableContentProp !== void 0 ? disableHoverableContentProp : providerContext.disableHoverableContent; - const delayDuration = delayDurationProp !== null && delayDurationProp !== void 0 ? delayDurationProp : providerContext.delayDuration; - const wasOpenDelayedRef = $iVrL9$react.useRef(false); - const [open1 = false, setOpen] = $iVrL9$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: open => { - if (open) { - providerContext.onOpen(); // as `onChange` is called within a lifecycle method we - // avoid dispatching via `dispatchDiscreteCustomEvent`. - document.dispatchEvent(new CustomEvent($c34afbc43c90cc6f$var$TOOLTIP_OPEN)); - } else providerContext.onClose(); - onOpenChange === null || onOpenChange === void 0 || onOpenChange(open); - } - }); - const stateAttribute = $iVrL9$react.useMemo(() => { - return open1 ? wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open' : 'closed'; - }, [open1]); - const handleOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - wasOpenDelayedRef.current = false; - setOpen(true); - }, [setOpen]); - const handleClose = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - setOpen(false); - }, [setOpen]); - const handleDelayedOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - openTimerRef.current = window.setTimeout(() => { - wasOpenDelayedRef.current = true; - setOpen(true); - }, delayDuration); - }, [delayDuration, setOpen]); - $iVrL9$react.useEffect(() => { - return () => window.clearTimeout(openTimerRef.current); - }, []); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Root, popperScope, /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContextProvider, { - scope: __scopeTooltip, - contentId: contentId, - open: open1, - stateAttribute: stateAttribute, - trigger: trigger, - onTriggerChange: setTrigger, - onTriggerEnter: $iVrL9$react.useCallback(() => { - if (providerContext.isOpenDelayed) handleDelayedOpen();else handleOpen(); - }, [providerContext.isOpenDelayed, handleDelayedOpen, handleOpen]), - onTriggerLeave: $iVrL9$react.useCallback(() => { - if (disableHoverableContent) handleClose();else - // Clear the timer in case the pointer leaves the trigger before the tooltip is opened. - window.clearTimeout(openTimerRef.current); - }, [handleClose, disableHoverableContent]), - onOpen: handleOpen, - onClose: handleClose, - disableHoverableContent: disableHoverableContent - }, children)); -}; -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$28c660c63b792dea, { - displayName: $c34afbc43c90cc6f$var$TOOLTIP_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipTrigger - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$TRIGGER_NAME = 'TooltipTrigger'; -const $c34afbc43c90cc6f$export$8c610744efcf8a1d = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - ...triggerProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$TRIGGER_NAME, __scopeTooltip); - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$TRIGGER_NAME, __scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref, context.onTriggerChange); - const isPointerDownRef = $iVrL9$react.useRef(false); - const hasPointerMoveOpenedRef = $iVrL9$react.useRef(false); - const handlePointerUp = $iVrL9$react.useCallback(() => isPointerDownRef.current = false, []); - $iVrL9$react.useEffect(() => { - return () => document.removeEventListener('pointerup', handlePointerUp); - }, [handlePointerUp]); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Anchor, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - asChild: true - }, popperScope), /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactprimitive.Primitive.button, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - // We purposefully avoid adding `type=button` here because tooltip triggers are also - // commonly anchors and the anchor `type` attribute signifies MIME type. - "aria-describedby": context.open ? context.contentId : undefined, - "data-state": context.stateAttribute - }, triggerProps, { - ref: composedRefs, - onPointerMove: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerMove, event => { - if (event.pointerType === 'touch') return; - if (!hasPointerMoveOpenedRef.current && !providerContext.isPointerInTransitRef.current) { - context.onTriggerEnter(); - hasPointerMoveOpenedRef.current = true; - } - }), - onPointerLeave: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerLeave, () => { - context.onTriggerLeave(); - hasPointerMoveOpenedRef.current = false; - }), - onPointerDown: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerDown, () => { - isPointerDownRef.current = true; - document.addEventListener('pointerup', handlePointerUp, { - once: true - }); - }), - onFocus: $iVrL9$radixuiprimitive.composeEventHandlers(props.onFocus, () => { - if (!isPointerDownRef.current) context.onOpen(); - }), - onBlur: $iVrL9$radixuiprimitive.composeEventHandlers(props.onBlur, context.onClose), - onClick: $iVrL9$radixuiprimitive.composeEventHandlers(props.onClick, context.onClose) - }))); -}); -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$8c610744efcf8a1d, { - displayName: $c34afbc43c90cc6f$var$TRIGGER_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipPortal - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$PORTAL_NAME = 'TooltipPortal'; -const [$c34afbc43c90cc6f$var$PortalProvider, $c34afbc43c90cc6f$var$usePortalContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$PORTAL_NAME, { - forceMount: undefined -}); -const $c34afbc43c90cc6f$export$7b36b8f925ab7497 = props => { - const { - __scopeTooltip: __scopeTooltip, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$PORTAL_NAME, __scopeTooltip); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$PortalProvider, { - scope: __scopeTooltip, - forceMount: forceMount - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactportal.Portal, { - asChild: true, - container: container - }, children))); -}; -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$7b36b8f925ab7497, { - displayName: $c34afbc43c90cc6f$var$PORTAL_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipContent - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$CONTENT_NAME = 'TooltipContent'; -const $c34afbc43c90cc6f$export$e9003e2be37ec060 = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const portalContext = $c34afbc43c90cc6f$var$usePortalContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const { - forceMount = portalContext.forceMount, - side = 'top', - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpresence.Presence, { - present: forceMount || context.open - }, context.disableHoverableContent ? /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentImpl, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - side: side - }, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentHoverable, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - side: side - }, contentProps, { - ref: forwardedRef - }))); -}); -const $c34afbc43c90cc6f$var$TooltipContentHoverable = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const [pointerGraceArea, setPointerGraceArea] = $iVrL9$react.useState(null); - const { - trigger: trigger, - onClose: onClose - } = context; - const content = ref.current; - const { - onPointerInTransitChange: onPointerInTransitChange - } = providerContext; - const handleRemoveGraceArea = $iVrL9$react.useCallback(() => { - setPointerGraceArea(null); - onPointerInTransitChange(false); - }, [onPointerInTransitChange]); - const handleCreateGraceArea = $iVrL9$react.useCallback((event, hoverTarget) => { - const currentTarget = event.currentTarget; - const exitPoint = { - x: event.clientX, - y: event.clientY - }; - const exitSide = $c34afbc43c90cc6f$var$getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect()); - const paddedExitPoints = $c34afbc43c90cc6f$var$getPaddedExitPoints(exitPoint, exitSide); - const hoverTargetPoints = $c34afbc43c90cc6f$var$getPointsFromRect(hoverTarget.getBoundingClientRect()); - const graceArea = $c34afbc43c90cc6f$var$getHull([...paddedExitPoints, ...hoverTargetPoints]); - setPointerGraceArea(graceArea); - onPointerInTransitChange(true); - }, [onPointerInTransitChange]); - $iVrL9$react.useEffect(() => { - return () => handleRemoveGraceArea(); - }, [handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (trigger && content) { - const handleTriggerLeave = event => handleCreateGraceArea(event, content); - const handleContentLeave = event => handleCreateGraceArea(event, trigger); - trigger.addEventListener('pointerleave', handleTriggerLeave); - content.addEventListener('pointerleave', handleContentLeave); - return () => { - trigger.removeEventListener('pointerleave', handleTriggerLeave); - content.removeEventListener('pointerleave', handleContentLeave); - }; - } - }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (pointerGraceArea) { - const handleTrackPointerGrace = event => { - const target = event.target; - const pointerPosition = { - x: event.clientX, - y: event.clientY + /***/ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-focus-scope/dist/index.js ***! + \***********************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $buum9$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $buum9$react = __webpack_require__(/*! react */ "react"); + var $buum9$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $buum9$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $buum9$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "FocusScope", + () => $2bc01e66e04aa9ed$export$20e40289641fbbb6 + ); + $parcel$export( + module.exports, + "Root", + () => $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9 + ); + const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT = + "focusScope.autoFocusOnMount"; + const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT = + "focusScope.autoFocusOnUnmount"; + const $2bc01e66e04aa9ed$var$EVENT_OPTIONS = { + bubbles: false, + cancelable: true, }; - const hasEnteredTarget = (trigger === null || trigger === void 0 ? void 0 : trigger.contains(target)) || (content === null || content === void 0 ? void 0 : content.contains(target)); - const isPointerOutsideGraceArea = !$c34afbc43c90cc6f$var$isPointInPolygon(pointerPosition, pointerGraceArea); - if (hasEnteredTarget) handleRemoveGraceArea();else if (isPointerOutsideGraceArea) { - handleRemoveGraceArea(); - onClose(); - } - }; - document.addEventListener('pointermove', handleTrackPointerGrace); - return () => document.removeEventListener('pointermove', handleTrackPointerGrace); - } - }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentImpl, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({}, props, { - ref: composedRefs - })); -}); -const [$c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$TOOLTIP_NAME, { - isInside: false -}); -const $c34afbc43c90cc6f$var$TooltipContentImpl = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - 'aria-label': ariaLabel, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, __scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const { - onClose: onClose - } = context; // Close this tooltip if another one opens - $iVrL9$react.useEffect(() => { - document.addEventListener($c34afbc43c90cc6f$var$TOOLTIP_OPEN, onClose); - return () => document.removeEventListener($c34afbc43c90cc6f$var$TOOLTIP_OPEN, onClose); - }, [onClose]); // Close the tooltip if the trigger is scrolled - $iVrL9$react.useEffect(() => { - if (context.trigger) { - const handleScroll = event => { - const target = event.target; - if (target !== null && target !== void 0 && target.contains(context.trigger)) onClose(); - }; - window.addEventListener('scroll', handleScroll, { - capture: true - }); - return () => window.removeEventListener('scroll', handleScroll, { - capture: true - }); - } - }, [context.trigger, onClose]); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactdismissablelayer.DismissableLayer, { - asChild: true, - disableOutsidePointerEvents: false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: event => event.preventDefault(), - onDismiss: onClose - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Content, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - "data-state": context.stateAttribute - }, popperScope, contentProps, { - ref: forwardedRef, - style: { - ...contentProps.style, - '--radix-tooltip-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-tooltip-content-available-width': 'var(--radix-popper-available-width)', - '--radix-tooltip-content-available-height': 'var(--radix-popper-available-height)', - '--radix-tooltip-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-tooltip-trigger-height': 'var(--radix-popper-anchor-height)' - } - }), /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactslot.Slottable, null, children), /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, { - scope: __scopeTooltip, - isInside: true - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactvisuallyhidden.Root, { - id: context.contentId, - role: "tooltip" - }, ariaLabel || children)))); -}); -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$e9003e2be37ec060, { - displayName: $c34afbc43c90cc6f$var$CONTENT_NAME -}); -/* ------------------------------------------------------------------------------------------------- - * TooltipArrow - * -----------------------------------------------------------------------------------------------*/ -const $c34afbc43c90cc6f$var$ARROW_NAME = 'TooltipArrow'; -const $c34afbc43c90cc6f$export$c27ee0ad710f7559 = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - ...arrowProps - } = props; - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const visuallyHiddenContentContext = $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext($c34afbc43c90cc6f$var$ARROW_NAME, __scopeTooltip); // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to - // prevent issues in positioning the arrow due to the duplicate - return visuallyHiddenContentContext.isInside ? null : /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Arrow, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({}, popperScope, arrowProps, { - ref: forwardedRef - })); -}); -/*#__PURE__*/ -Object.assign($c34afbc43c90cc6f$export$c27ee0ad710f7559, { - displayName: $c34afbc43c90cc6f$var$ARROW_NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -function $c34afbc43c90cc6f$var$getExitSideFromRect(point, rect) { - const top = Math.abs(rect.top - point.y); - const bottom = Math.abs(rect.bottom - point.y); - const right = Math.abs(rect.right - point.x); - const left = Math.abs(rect.left - point.x); - switch (Math.min(top, bottom, right, left)) { - case left: - return 'left'; - case right: - return 'right'; - case top: - return 'top'; - case bottom: - return 'bottom'; - default: - throw new Error('unreachable'); - } -} -function $c34afbc43c90cc6f$var$getPaddedExitPoints(exitPoint, exitSide, padding = 5) { - const paddedExitPoints = []; - switch (exitSide) { - case 'top': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y + padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y + padding - }); - break; - case 'bottom': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y - padding - }); - break; - case 'left': - paddedExitPoints.push({ - x: exitPoint.x + padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y + padding - }); - break; - case 'right': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x - padding, - y: exitPoint.y + padding - }); - break; - } - return paddedExitPoints; -} -function $c34afbc43c90cc6f$var$getPointsFromRect(rect) { - const { - top: top, - right: right, - bottom: bottom, - left: left - } = rect; - return [{ - x: left, - y: top - }, { - x: right, - y: top - }, { - x: right, - y: bottom - }, { - x: left, - y: bottom - }]; -} // Determine if a point is inside of a polygon. -// Based on https://github.com/substack/point-in-polygon -function $c34afbc43c90cc6f$var$isPointInPolygon(point, polygon) { - const { - x: x, - y: y - } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; -} // Returns a new array of points representing the convex hull of the given set of points. -// https://www.nayuki.io/page/convex-hull-algorithm -function $c34afbc43c90cc6f$var$getHull(points) { - const newPoints = points.slice(); - newPoints.sort((a, b) => { - if (a.x < b.x) return -1;else if (a.x > b.x) return 1;else if (a.y < b.y) return -1;else if (a.y > b.y) return 1;else return 0; - }); - return $c34afbc43c90cc6f$var$getHullPresorted(newPoints); -} // Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time. -function $c34afbc43c90cc6f$var$getHullPresorted(points) { - if (points.length <= 1) return points.slice(); - const upperHull = []; - for (let i = 0; i < points.length; i++) { - const p = points[i]; - while (upperHull.length >= 2) { - const q = upperHull[upperHull.length - 1]; - const r = upperHull[upperHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) upperHull.pop();else break; - } - upperHull.push(p); - } - upperHull.pop(); - const lowerHull = []; - for (let i1 = points.length - 1; i1 >= 0; i1--) { - const p = points[i1]; - while (lowerHull.length >= 2) { - const q = lowerHull[lowerHull.length - 1]; - const r = lowerHull[lowerHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) lowerHull.pop();else break; - } - lowerHull.push(p); - } - lowerHull.pop(); - if (upperHull.length === 1 && lowerHull.length === 1 && upperHull[0].x === lowerHull[0].x && upperHull[0].y === lowerHull[0].y) return upperHull;else return upperHull.concat(lowerHull); -} -const $c34afbc43c90cc6f$export$2881499e37b75b9a = $c34afbc43c90cc6f$export$f78649fb9ca566b8; -const $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 = $c34afbc43c90cc6f$export$28c660c63b792dea; -const $c34afbc43c90cc6f$export$41fb9f06171c75f4 = $c34afbc43c90cc6f$export$8c610744efcf8a1d; -const $c34afbc43c90cc6f$export$602eac185826482c = $c34afbc43c90cc6f$export$7b36b8f925ab7497; -const $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 = $c34afbc43c90cc6f$export$e9003e2be37ec060; -const $c34afbc43c90cc6f$export$21b07c8f274aebd5 = $c34afbc43c90cc6f$export$c27ee0ad710f7559; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js": -/*!****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js ***! - \****************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $92muK$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useCallbackRef", () => $28e03942f763e819$export$25bec8c6f54ee79a); - -/** - * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a - * prop or avoid re-executing effects when passed as a dependency - */ -function $28e03942f763e819$export$25bec8c6f54ee79a(callback) { - const callbackRef = $92muK$react.useRef(callback); - $92muK$react.useEffect(() => { - callbackRef.current = callback; - }); // https://github.com/facebook/react/issues/19240 - return $92muK$react.useMemo(() => (...args) => { - var _callbackRef$current; - return (_callbackRef$current = callbackRef.current) === null || _callbackRef$current === void 0 ? void 0 : _callbackRef$current.call(callbackRef, ...args); - }, []); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js ***! - \**********************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $ijazI$react = __webpack_require__(/*! react */ "react"); -var $ijazI$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useControllableState", () => $b84d42d44371bff7$export$6f32135080cb4c3); -function $b84d42d44371bff7$export$6f32135080cb4c3({ - prop: prop, - defaultProp: defaultProp, - onChange = () => {} -}) { - const [uncontrolledProp, setUncontrolledProp] = $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange - }); - const isControlled = prop !== undefined; - const value1 = isControlled ? prop : uncontrolledProp; - const handleChange = $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - const setValue = $ijazI$react.useCallback(nextValue => { - if (isControlled) { - const setter = nextValue; - const value = typeof nextValue === 'function' ? setter(prop) : nextValue; - if (value !== prop) handleChange(value); - } else setUncontrolledProp(nextValue); - }, [isControlled, prop, setUncontrolledProp, handleChange]); - return [value1, setValue]; -} -function $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange -}) { - const uncontrolledState = $ijazI$react.useState(defaultProp); - const [value] = uncontrolledState; - const prevValueRef = $ijazI$react.useRef(value); - const handleChange = $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - $ijazI$react.useEffect(() => { - if (prevValueRef.current !== value) { - handleChange(value); - prevValueRef.current = value; - } - }, [value, prevValueRef, handleChange]); - return uncontrolledState; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js": -/*!******************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js ***! - \******************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $b0gz3$react = __webpack_require__(/*! react */ "react"); -var $b0gz3$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useEscapeKeydown", () => $24c84e9f83c4454f$export$3a72a57244d6e765); - -/** - * Listens for when the escape key is down - */ -function $24c84e9f83c4454f$export$3a72a57244d6e765(onEscapeKeyDownProp, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const onEscapeKeyDown = $b0gz3$radixuireactusecallbackref.useCallbackRef(onEscapeKeyDownProp); - $b0gz3$react.useEffect(() => { - const handleKeyDown = event => { - if (event.key === 'Escape') onEscapeKeyDown(event); - }; - ownerDocument.addEventListener('keydown', handleKeyDown); - return () => ownerDocument.removeEventListener('keydown', handleKeyDown); - }, [onEscapeKeyDown, ownerDocument]); -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js": -/*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js ***! - \*****************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $caHyQ$react = __webpack_require__(/*! react */ "react"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useLayoutEffect", () => $ca21affb0542a8a4$export$e5c5a5f917a5871c); - -/** - * On the server, React emits a warning when calling `useLayoutEffect`. - * This is because neither `useLayoutEffect` nor `useEffect` run on the server. - * We use this safe version which suppresses the warning by replacing it with a noop on the server. - * - * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect - */ -const $ca21affb0542a8a4$export$e5c5a5f917a5871c = Boolean(globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) ? $caHyQ$react.useLayoutEffect : () => {}; - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-use-size/dist/index.js": -/*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-size/dist/index.js ***! - \********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var $ksDzM$react = __webpack_require__(/*! react */ "react"); -var $ksDzM$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -$parcel$export(module.exports, "useSize", () => $d2c1d285af17635b$export$1ab7ae714698c4b8); -function $d2c1d285af17635b$export$1ab7ae714698c4b8(element) { - const [size, setSize] = $ksDzM$react.useState(undefined); - $ksDzM$radixuireactuselayouteffect.useLayoutEffect(() => { - if (element) { - // provide size as early as possible - setSize({ - width: element.offsetWidth, - height: element.offsetHeight - }); - const resizeObserver = new ResizeObserver(entries => { - if (!Array.isArray(entries)) return; - // Since we only observe the one element, we don't need to loop over the - // array - if (!entries.length) return; - const entry = entries[0]; - let width; - let height; - if ('borderBoxSize' in entry) { - const borderSizeEntry = entry['borderBoxSize']; // iron out differences between browsers - const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry; - width = borderSize['inlineSize']; - height = borderSize['blockSize']; - } else { - // for browsers that don't support `borderBoxSize` - // we calculate it ourselves to get the correct border box. - width = element.offsetWidth; - height = element.offsetHeight; - } - setSize({ - width: width, - height: height - }); - }); - resizeObserver.observe(element, { - box: 'border-box' - }); - return () => resizeObserver.unobserve(element); - } else - // We only want to reset to `undefined` when the element becomes `null`, - // not if it changes to another element. - setSize(undefined); - }, [element]); - return size; -} - -/***/ }), - -/***/ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js": -/*!***************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js ***! - \***************************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - + /* ------------------------------------------------------------------------------------------------- + * FocusScope + * -----------------------------------------------------------------------------------------------*/ + const $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME = "FocusScope"; + const $2bc01e66e04aa9ed$export$20e40289641fbbb6 = + /*#__PURE__*/ $buum9$react.forwardRef((props, forwardedRef) => { + const { + loop = false, + trapped = false, + onMountAutoFocus: onMountAutoFocusProp, + onUnmountAutoFocus: onUnmountAutoFocusProp, + ...scopeProps + } = props; + const [container1, setContainer] = $buum9$react.useState(null); + const onMountAutoFocus = + $buum9$radixuireactusecallbackref.useCallbackRef( + onMountAutoFocusProp + ); + const onUnmountAutoFocus = + $buum9$radixuireactusecallbackref.useCallbackRef( + onUnmountAutoFocusProp + ); + const lastFocusedElementRef = $buum9$react.useRef(null); + const composedRefs = $buum9$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + (node) => setContainer(node) + ); + const focusScope = $buum9$react.useRef({ + paused: false, + pause() { + this.paused = true; + }, + resume() { + this.paused = false; + }, + }).current; // Takes care of trapping focus if focus is moved outside programmatically for example + $buum9$react.useEffect(() => { + if (trapped) { + function handleFocusIn(event) { + if (focusScope.paused || !container1) return; + const target = event.target; + if (container1.contains(target)) + lastFocusedElementRef.current = target; + else + $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { + select: true, + }); + } + function handleFocusOut(event) { + if (focusScope.paused || !container1) return; + const relatedTarget = event.relatedTarget; // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases: + // + // 1. When the user switches app/tabs/windows/the browser itself loses focus. + // 2. In Google Chrome, when the focused element is removed from the DOM. + // + // We let the browser do its thing here because: + // + // 1. The browser already keeps a memory of what's focused for when the page gets refocused. + // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it + // throws the CPU to 100%, so we avoid doing anything for this reason here too. + if (relatedTarget === null) return; // If the focus has moved to an actual legitimate element (`relatedTarget !== null`) + // that is outside the container, we move focus to the last valid focused element inside. + if (!container1.contains(relatedTarget)) + $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { + select: true, + }); + } // When the focused element gets removed from the DOM, browsers move focus + // back to the document.body. In this case, we move focus to the container + // to keep focus trapped correctly. + function handleMutations(mutations) { + const focusedElement = document.activeElement; + for (const mutation of mutations) { + if (mutation.removedNodes.length > 0) { + if ( + !( + container1 !== null && + container1 !== void 0 && + container1.contains(focusedElement) + ) + ) + $2bc01e66e04aa9ed$var$focus(container1); + } + } + } + document.addEventListener("focusin", handleFocusIn); + document.addEventListener("focusout", handleFocusOut); + const mutationObserver = new MutationObserver(handleMutations); + if (container1) + mutationObserver.observe(container1, { + childList: true, + subtree: true, + }); + return () => { + document.removeEventListener("focusin", handleFocusIn); + document.removeEventListener("focusout", handleFocusOut); + mutationObserver.disconnect(); + }; + } + }, [trapped, container1, focusScope.paused]); + $buum9$react.useEffect(() => { + if (container1) { + $2bc01e66e04aa9ed$var$focusScopesStack.add(focusScope); + const previouslyFocusedElement = document.activeElement; + const hasFocusedCandidate = container1.contains( + previouslyFocusedElement + ); + if (!hasFocusedCandidate) { + const mountEvent = new CustomEvent( + $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, + $2bc01e66e04aa9ed$var$EVENT_OPTIONS + ); + container1.addEventListener( + $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, + onMountAutoFocus + ); + container1.dispatchEvent(mountEvent); + if (!mountEvent.defaultPrevented) { + $2bc01e66e04aa9ed$var$focusFirst( + $2bc01e66e04aa9ed$var$removeLinks( + $2bc01e66e04aa9ed$var$getTabbableCandidates(container1) + ), + { + select: true, + } + ); + if (document.activeElement === previouslyFocusedElement) + $2bc01e66e04aa9ed$var$focus(container1); + } + } + return () => { + container1.removeEventListener( + $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, + onMountAutoFocus + ); // We hit a react bug (fixed in v17) with focusing in unmount. + // We need to delay the focus a little to get around it for now. + // See: https://github.com/facebook/react/issues/17894 + setTimeout(() => { + const unmountEvent = new CustomEvent( + $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, + $2bc01e66e04aa9ed$var$EVENT_OPTIONS + ); + container1.addEventListener( + $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, + onUnmountAutoFocus + ); + container1.dispatchEvent(unmountEvent); + if (!unmountEvent.defaultPrevented) + $2bc01e66e04aa9ed$var$focus( + previouslyFocusedElement !== null && + previouslyFocusedElement !== void 0 + ? previouslyFocusedElement + : document.body, + { + select: true, + } + ); + // we need to remove the listener after we `dispatchEvent` + container1.removeEventListener( + $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, + onUnmountAutoFocus + ); + $2bc01e66e04aa9ed$var$focusScopesStack.remove(focusScope); + }, 0); + }; + } + }, [container1, onMountAutoFocus, onUnmountAutoFocus, focusScope]); // Takes care of looping focus (when tabbing whilst at the edges) + const handleKeyDown = $buum9$react.useCallback( + (event) => { + if (!loop && !trapped) return; + if (focusScope.paused) return; + const isTabKey = + event.key === "Tab" && + !event.altKey && + !event.ctrlKey && + !event.metaKey; + const focusedElement = document.activeElement; + if (isTabKey && focusedElement) { + const container = event.currentTarget; + const [first, last] = + $2bc01e66e04aa9ed$var$getTabbableEdges(container); + const hasTabbableElementsInside = first && last; // we can only wrap focus if we have tabbable edges + if (!hasTabbableElementsInside) { + if (focusedElement === container) event.preventDefault(); + } else { + if (!event.shiftKey && focusedElement === last) { + event.preventDefault(); + if (loop) + $2bc01e66e04aa9ed$var$focus(first, { + select: true, + }); + } else if (event.shiftKey && focusedElement === first) { + event.preventDefault(); + if (loop) + $2bc01e66e04aa9ed$var$focus(last, { + select: true, + }); + } + } + } + }, + [loop, trapped, focusScope.paused] + ); + return /*#__PURE__*/ $buum9$react.createElement( + $buum9$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($buum9$babelruntimehelpersextends)( + { + tabIndex: -1, + }, + scopeProps, + { + ref: composedRefs, + onKeyDown: handleKeyDown, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($2bc01e66e04aa9ed$export$20e40289641fbbb6, { + displayName: $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * Utils + * -----------------------------------------------------------------------------------------------*/ /** + * Attempts focusing the first element in a list of candidates. + * Stops when focus has actually moved. + */ + function $2bc01e66e04aa9ed$var$focusFirst( + candidates, + { select = false } = {} + ) { + const previouslyFocusedElement = document.activeElement; + for (const candidate of candidates) { + $2bc01e66e04aa9ed$var$focus(candidate, { + select: select, + }); + if (document.activeElement !== previouslyFocusedElement) return; + } + } + /** + * Returns the first and last tabbable elements inside a container. + */ + function $2bc01e66e04aa9ed$var$getTabbableEdges(container) { + const candidates = + $2bc01e66e04aa9ed$var$getTabbableCandidates(container); + const first = $2bc01e66e04aa9ed$var$findVisible( + candidates, + container + ); + const last = $2bc01e66e04aa9ed$var$findVisible( + candidates.reverse(), + container + ); + return [first, last]; + } + /** + * Returns a list of potential tabbable candidates. + * + * NOTE: This is only a close approximation. For example it doesn't take into account cases like when + * elements are not visible. This cannot be worked out easily by just reading a property, but rather + * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately. + * + * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker + * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1 + */ + function $2bc01e66e04aa9ed$var$getTabbableCandidates(container) { + const nodes = []; + const walker = document.createTreeWalker( + container, + NodeFilter.SHOW_ELEMENT, + { + acceptNode: (node) => { + const isHiddenInput = + node.tagName === "INPUT" && node.type === "hidden"; + if (node.disabled || node.hidden || isHiddenInput) + return NodeFilter.FILTER_SKIP; // `.tabIndex` is not the same as the `tabindex` attribute. It works on the + // runtime's understanding of tabbability, so this automatically accounts + // for any kind of element that could be tabbed to. + return node.tabIndex >= 0 + ? NodeFilter.FILTER_ACCEPT + : NodeFilter.FILTER_SKIP; + }, + } + ); + while (walker.nextNode()) nodes.push(walker.currentNode); // we do not take into account the order of nodes with positive `tabIndex` as it + // hinders accessibility to have tab order different from visual order. + return nodes; + } + /** + * Returns the first visible element in a list. + * NOTE: Only checks visibility up to the `container`. + */ + function $2bc01e66e04aa9ed$var$findVisible(elements, container) { + for (const element of elements) { + // we stop checking if it's hidden at the `container` level (excluding) + if ( + !$2bc01e66e04aa9ed$var$isHidden(element, { + upTo: container, + }) + ) + return element; + } + } + function $2bc01e66e04aa9ed$var$isHidden(node, { upTo: upTo }) { + if (getComputedStyle(node).visibility === "hidden") return true; + while (node) { + // we stop at `upTo` (excluding it) + if (upTo !== undefined && node === upTo) return false; + if (getComputedStyle(node).display === "none") return true; + node = node.parentElement; + } + return false; + } + function $2bc01e66e04aa9ed$var$isSelectableInput(element) { + return element instanceof HTMLInputElement && "select" in element; + } + function $2bc01e66e04aa9ed$var$focus(element, { select = false } = {}) { + // only focus if that element is focusable + if (element && element.focus) { + const previouslyFocusedElement = document.activeElement; // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users + element.focus({ + preventScroll: true, + }); // only select if its not the same element, it supports selection and we need to select + if ( + element !== previouslyFocusedElement && + $2bc01e66e04aa9ed$var$isSelectableInput(element) && + select + ) + element.select(); + } + } + /* ------------------------------------------------------------------------------------------------- + * FocusScope stack + * -----------------------------------------------------------------------------------------------*/ + const $2bc01e66e04aa9ed$var$focusScopesStack = + $2bc01e66e04aa9ed$var$createFocusScopesStack(); + function $2bc01e66e04aa9ed$var$createFocusScopesStack() { + /** A stack of focus scopes, with the active one at the top */ let stack = + []; + return { + add(focusScope) { + // pause the currently active focus scope (at the top of the stack) + const activeFocusScope = stack[0]; + if (focusScope !== activeFocusScope) + activeFocusScope === null || + activeFocusScope === void 0 || + activeFocusScope.pause(); + // remove in case it already exists (because we'll re-add it at the top of the stack) + stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); + stack.unshift(focusScope); + }, + remove(focusScope) { + var _stack$; + stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); + (_stack$ = stack[0]) === null || + _stack$ === void 0 || + _stack$.resume(); + }, + }; + } + function $2bc01e66e04aa9ed$var$arrayRemove(array, item) { + const updatedArray = [...array]; + const index = updatedArray.indexOf(item); + if (index !== -1) updatedArray.splice(index, 1); + return updatedArray; + } + function $2bc01e66e04aa9ed$var$removeLinks(items) { + return items.filter((item) => item.tagName !== "A"); + } + const $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9 = + $2bc01e66e04aa9ed$export$20e40289641fbbb6; + /***/ + }, -var $awrN2$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); -var $awrN2$react = __webpack_require__(/*! react */ "react"); -var $awrN2$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); -function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); -} -function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; -} -$parcel$export(module.exports, "VisuallyHidden", () => $685371e9c20848e2$export$439d29a4e110a164); -$parcel$export(module.exports, "Root", () => $685371e9c20848e2$export$be92b6f5f03c0fe9); - -/* ------------------------------------------------------------------------------------------------- - * VisuallyHidden - * -----------------------------------------------------------------------------------------------*/ -const $685371e9c20848e2$var$NAME = 'VisuallyHidden'; -const $685371e9c20848e2$export$439d29a4e110a164 = /*#__PURE__*/$awrN2$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/$awrN2$react.createElement($awrN2$radixuireactprimitive.Primitive.span, $parcel$interopDefault($awrN2$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - style: { - // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss - position: 'absolute', - border: 0, - width: 1, - height: 1, - padding: 0, - margin: -1, - overflow: 'hidden', - clip: 'rect(0, 0, 0, 0)', - whiteSpace: 'nowrap', - wordWrap: 'normal', - ...props.style - } - })); -}); -/*#__PURE__*/ -Object.assign($685371e9c20848e2$export$439d29a4e110a164, { - displayName: $685371e9c20848e2$var$NAME -}); -/* -----------------------------------------------------------------------------------------------*/ -const $685371e9c20848e2$export$be92b6f5f03c0fe9 = $685371e9c20848e2$export$439d29a4e110a164; - -/***/ }), - -/***/ "../../../node_modules/aria-hidden/dist/es2015/index.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/aria-hidden/dist/es2015/index.js ***! + /***/ "../../../node_modules/@radix-ui/react-id/dist/index.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-id/dist/index.js ***! \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.suppressOthers = exports.supportsInert = exports.inertOthers = exports.hideOthers = void 0; -var getDefaultParent = function (originalTarget) { - if (typeof document === 'undefined') { - return null; - } - var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget; - return sampleTarget.ownerDocument.body; -}; -var counterMap = new WeakMap(); -var uncontrolledNodes = new WeakMap(); -var markerMap = {}; -var lockCount = 0; -var unwrapHost = function (node) { - return node && (node.host || unwrapHost(node.parentNode)); -}; -var correctTargets = function (parent, targets) { - return targets.map(function (target) { - if (parent.contains(target)) { - return target; - } - var correctedTarget = unwrapHost(target); - if (correctedTarget && parent.contains(correctedTarget)) { - return correctedTarget; - } - console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing'); - return null; - }).filter(function (x) { - return Boolean(x); - }); -}; -/** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @param {String} [controlAttribute] - html Attribute to control - * @return {Undo} undo command - */ -var applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) { - var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]); - if (!markerMap[markerName]) { - markerMap[markerName] = new WeakMap(); - } - var markerCounter = markerMap[markerName]; - var hiddenNodes = []; - var elementsToKeep = new Set(); - var elementsToStop = new Set(targets); - var keep = function (el) { - if (!el || elementsToKeep.has(el)) { - return; - } - elementsToKeep.add(el); - keep(el.parentNode); - }; - targets.forEach(keep); - var deep = function (parent) { - if (!parent || elementsToStop.has(parent)) { - return; - } - Array.prototype.forEach.call(parent.children, function (node) { - if (elementsToKeep.has(node)) { - deep(node); - } else { - var attr = node.getAttribute(controlAttribute); - var alreadyHidden = attr !== null && attr !== 'false'; - var counterValue = (counterMap.get(node) || 0) + 1; - var markerValue = (markerCounter.get(node) || 0) + 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - hiddenNodes.push(node); - if (counterValue === 1 && alreadyHidden) { - uncontrolledNodes.set(node, true); - } - if (markerValue === 1) { - node.setAttribute(markerName, 'true'); - } - if (!alreadyHidden) { - node.setAttribute(controlAttribute, 'true'); + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $47woD$react = __webpack_require__(/*! react */ "react"); + var $47woD$radixuireactuselayouteffect = __webpack_require__( + /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); } - } - }); - }; - deep(parentNode); - elementsToKeep.clear(); - lockCount++; - return function () { - hiddenNodes.forEach(function (node) { - var counterValue = counterMap.get(node) - 1; - var markerValue = markerCounter.get(node) - 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - if (!counterValue) { - if (!uncontrolledNodes.has(node)) { - node.removeAttribute(controlAttribute); - } - uncontrolledNodes.delete(node); - } - if (!markerValue) { - node.removeAttribute(markerName); - } - }); - lockCount--; - if (!lockCount) { - // clear - counterMap = new WeakMap(); - counterMap = new WeakMap(); - uncontrolledNodes = new WeakMap(); - markerMap = {}; - } - }; -}; -/** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ -var hideOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-aria-hidden'; - } - var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]); - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - // we should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10 - targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live]'))); - return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden'); -}; -/** - * Marks everything except given node(or nodes) as inert - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ -exports.hideOthers = hideOthers; -var inertOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-inert-ed'; - } - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert'); -}; -/** - * @returns if current browser supports inert - */ -exports.inertOthers = inertOthers; -var supportsInert = function () { - return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert'); -}; -/** - * Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ -exports.supportsInert = supportsInert; -var suppressOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-suppressed'; - } - return (supportsInert() ? inertOthers : hideOthers)(originalTarget, parentNode, markerName); -}; -exports.suppressOthers = suppressOthers; - -/***/ }), - -/***/ "../../../node_modules/clsx/dist/clsx.m.js": -/*!*************************************************!*\ - !*** ../../../node_modules/clsx/dist/clsx.m.js ***! - \*************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.clsx = clsx; -exports["default"] = void 0; -function r(e) { - var t, - f, - n = ""; - if ("string" == typeof e || "number" == typeof e) n += e;else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);else for (t in e) e[t] && (n && (n += " "), n += t); - return n; -} -function clsx() { - for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t); - return n; -} -var _default = exports["default"] = clsx; - -/***/ }), - -/***/ "../../../node_modules/copy-to-clipboard/index.js": -/*!********************************************************!*\ - !*** ../../../node_modules/copy-to-clipboard/index.js ***! - \********************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - + $parcel$export( + module.exports, + "useId", + () => $dc478e4659f630c5$export$f680877a34711e37 + ); + const $dc478e4659f630c5$var$useReactId = + $47woD$react["useId".toString()] || (() => undefined); + let $dc478e4659f630c5$var$count = 0; + function $dc478e4659f630c5$export$f680877a34711e37(deterministicId) { + const [id, setId] = $47woD$react.useState( + $dc478e4659f630c5$var$useReactId() + ); // React versions older than 18 will have client-side ids only. + $47woD$radixuireactuselayouteffect.useLayoutEffect(() => { + if (!deterministicId) + setId((reactId) => + reactId !== null && reactId !== void 0 + ? reactId + : String($dc478e4659f630c5$var$count++) + ); + }, [deterministicId]); + return deterministicId || (id ? `radix-${id}` : ""); + } + + /***/ + }, -var deselectCurrent = __webpack_require__(/*! toggle-selection */ "../../../node_modules/toggle-selection/index.js"); -var clipboardToIE11Formatting = { - "text/plain": "Text", - "text/html": "Url", - "default": "Text" -}; -var defaultMessage = "Copy to clipboard: #{key}, Enter"; -function format(message) { - var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; - return message.replace(/#{\s*key\s*}/g, copyKey); -} -function copy(text, options) { - var debug, - message, - reselectPrevious, - range, - selection, - mark, - success = false; - if (!options) { - options = {}; - } - debug = options.debug || false; - try { - reselectPrevious = deselectCurrent(); - range = document.createRange(); - selection = document.getSelection(); - mark = document.createElement("span"); - mark.textContent = text; - // avoid screen readers from reading out loud the text - mark.ariaHidden = "true"; - // reset user styles for span element - mark.style.all = "unset"; - // prevents scrolling to the end of the page - mark.style.position = "fixed"; - mark.style.top = 0; - mark.style.clip = "rect(0, 0, 0, 0)"; - // used to preserve spaces and line breaks - mark.style.whiteSpace = "pre"; - // do not inherit user-select (it may be `none`) - mark.style.webkitUserSelect = "text"; - mark.style.MozUserSelect = "text"; - mark.style.msUserSelect = "text"; - mark.style.userSelect = "text"; - mark.addEventListener("copy", function (e) { - e.stopPropagation(); - if (options.format) { - e.preventDefault(); - if (typeof e.clipboardData === "undefined") { - // IE 11 - debug && console.warn("unable to use e.clipboardData"); - debug && console.warn("trying IE specific stuff"); - window.clipboardData.clearData(); - var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; - window.clipboardData.setData(format, text); - } else { - // all other browsers - e.clipboardData.clearData(); - e.clipboardData.setData(options.format, text); + /***/ "../../../node_modules/@radix-ui/react-menu/dist/index.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-menu/dist/index.js ***! + \****************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $cnSS2$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $cnSS2$react = __webpack_require__(/*! react */ "react"); + var $cnSS2$radixuiprimitive = __webpack_require__( + /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" + ); + var $cnSS2$radixuireactcollection = __webpack_require__( + /*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js" + ); + var $cnSS2$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $cnSS2$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $cnSS2$radixuireactdirection = __webpack_require__( + /*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js" + ); + var $cnSS2$radixuireactdismissablelayer = __webpack_require__( + /*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js" + ); + var $cnSS2$radixuireactfocusguards = __webpack_require__( + /*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js" + ); + var $cnSS2$radixuireactfocusscope = __webpack_require__( + /*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js" + ); + var $cnSS2$radixuireactid = __webpack_require__( + /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" + ); + var $cnSS2$radixuireactpopper = __webpack_require__( + /*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js" + ); + var $cnSS2$radixuireactportal = __webpack_require__( + /*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js" + ); + var $cnSS2$radixuireactpresence = __webpack_require__( + /*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js" + ); + var $cnSS2$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $cnSS2$radixuireactrovingfocus = __webpack_require__( + /*! @radix-ui/react-roving-focus */ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js" + ); + var $cnSS2$radixuireactslot = __webpack_require__( + /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" + ); + var $cnSS2$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + var $cnSS2$ariahidden = __webpack_require__( + /*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js" + ); + var $cnSS2$reactremovescroll = __webpack_require__( + /*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); } - } - if (options.onCopy) { - e.preventDefault(); - options.onCopy(e.clipboardData); - } - }); - document.body.appendChild(mark); - range.selectNodeContents(mark); - selection.addRange(range); - var successful = document.execCommand("copy"); - if (!successful) { - throw new Error("copy command was unsuccessful"); - } - success = true; - } catch (err) { - debug && console.error("unable to copy using execCommand: ", err); - debug && console.warn("trying IE specific stuff"); - try { - window.clipboardData.setData(options.format || "text", text); - options.onCopy && options.onCopy(window.clipboardData); - success = true; - } catch (err) { - debug && console.error("unable to copy using clipboardData: ", err); - debug && console.error("falling back to prompt"); - message = format("message" in options ? options.message : defaultMessage); - window.prompt(message, text); - } - } finally { - if (selection) { - if (typeof selection.removeRange == "function") { - selection.removeRange(range); - } else { - selection.removeAllRanges(); - } - } - if (mark) { - document.body.removeChild(mark); - } - reselectPrevious(); - } - return success; -} -module.exports = copy; - -/***/ }), - -/***/ "../../../node_modules/detect-node-es/esm/browser.js": -/*!***********************************************************!*\ - !*** ../../../node_modules/detect-node-es/esm/browser.js ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isNode = void 0; -const isNode = exports.isNode = false; - -/***/ }), - -/***/ "../../../node_modules/entities/lib/decode.js": -/*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/decode.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); -} : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); -var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); -} : function (o, v) { - o["default"] = v; -}); -var __importStar = void 0 && (void 0).__importStar || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = void 0 && (void 0).__importDefault || function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; -}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decodeXML = exports.decodeHTMLStrict = exports.decodeHTMLAttribute = exports.decodeHTML = exports.determineBranch = exports.EntityDecoder = exports.DecodingMode = exports.BinTrieFlags = exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = void 0; -var decode_data_html_js_1 = __importDefault(__webpack_require__(/*! ./generated/decode-data-html.js */ "../../../node_modules/entities/lib/generated/decode-data-html.js")); -exports.htmlDecodeTree = decode_data_html_js_1.default; -var decode_data_xml_js_1 = __importDefault(__webpack_require__(/*! ./generated/decode-data-xml.js */ "../../../node_modules/entities/lib/generated/decode-data-xml.js")); -exports.xmlDecodeTree = decode_data_xml_js_1.default; -var decode_codepoint_js_1 = __importStar(__webpack_require__(/*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js")); -exports.decodeCodePoint = decode_codepoint_js_1.default; -var decode_codepoint_js_2 = __webpack_require__(/*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js"); -Object.defineProperty(exports, "replaceCodePoint", ({ - enumerable: true, - get: function () { - return decode_codepoint_js_2.replaceCodePoint; - } -})); -Object.defineProperty(exports, "fromCodePoint", ({ - enumerable: true, - get: function () { - return decode_codepoint_js_2.fromCodePoint; - } -})); -var CharCodes; -(function (CharCodes) { - CharCodes[CharCodes["NUM"] = 35] = "NUM"; - CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; - CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; - CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; - CharCodes[CharCodes["NINE"] = 57] = "NINE"; - CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; - CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; - CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; - CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; - CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; - CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; - CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; -})(CharCodes || (CharCodes = {})); -/** Bit that needs to be set to convert an upper case ASCII character to lower case */ -var TO_LOWER_BIT = 32; -var BinTrieFlags; -(function (BinTrieFlags) { - BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; - BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; - BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; -})(BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {})); -function isNumber(code) { - return code >= CharCodes.ZERO && code <= CharCodes.NINE; -} -function isHexadecimalCharacter(code) { - return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F; -} -function isAsciiAlphaNumeric(code) { - return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z || isNumber(code); -} -/** - * Checks if the given character is a valid end character for an entity in an attribute. - * - * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. - * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state - */ -function isEntityInAttributeInvalidEnd(code) { - return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); -} -var EntityDecoderState; -(function (EntityDecoderState) { - EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; - EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; - EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; - EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; - EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; -})(EntityDecoderState || (EntityDecoderState = {})); -var DecodingMode; -(function (DecodingMode) { - /** Entities in text nodes that can end with any character. */ - DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; - /** Only allow entities terminated with a semicolon. */ - DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; - /** Entities in attributes have limitations on ending characters. */ - DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; -})(DecodingMode = exports.DecodingMode || (exports.DecodingMode = {})); -/** - * Token decoder with support of writing partial entities. - */ -var EntityDecoder = /** @class */function () { - function EntityDecoder( /** The tree used to decode entities. */ - decodeTree, - /** - * The function that is called when a codepoint is decoded. - * - * For multi-byte named entities, this will be called multiple times, - * with the second codepoint, and the same `consumed` value. - * - * @param codepoint The decoded codepoint. - * @param consumed The number of bytes consumed by the decoder. - */ - emitCodePoint, /** An object that is used to produce errors. */ - errors) { - this.decodeTree = decodeTree; - this.emitCodePoint = emitCodePoint; - this.errors = errors; - /** The current state of the decoder. */ - this.state = EntityDecoderState.EntityStart; - /** Characters that were consumed while parsing an entity. */ - this.consumed = 1; - /** - * The result of the entity. - * - * Either the result index of a numeric entity, or the codepoint of a - * numeric entity. - */ - this.result = 0; - /** The current index in the decode tree. */ - this.treeIndex = 0; - /** The number of characters that were consumed in excess. */ - this.excess = 1; - /** The mode in which the decoder is operating. */ - this.decodeMode = DecodingMode.Strict; - } - /** Resets the instance to make it reusable. */ - EntityDecoder.prototype.startEntity = function (decodeMode) { - this.decodeMode = decodeMode; - this.state = EntityDecoderState.EntityStart; - this.result = 0; - this.treeIndex = 0; - this.excess = 1; - this.consumed = 1; - }; - /** - * Write an entity to the decoder. This can be called multiple times with partial entities. - * If the entity is incomplete, the decoder will return -1. - * - * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the - * entity is incomplete, and resume when the next string is written. - * - * @param string The string containing the entity (or a continuation of the entity). - * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.write = function (str, offset) { - switch (this.state) { - case EntityDecoderState.EntityStart: - { - if (str.charCodeAt(offset) === CharCodes.NUM) { - this.state = EntityDecoderState.NumericStart; - this.consumed += 1; - return this.stateNumericStart(str, offset + 1); - } - this.state = EntityDecoderState.NamedEntity; - return this.stateNamedEntity(str, offset); - } - case EntityDecoderState.NumericStart: - { - return this.stateNumericStart(str, offset); - } - case EntityDecoderState.NumericDecimal: - { - return this.stateNumericDecimal(str, offset); - } - case EntityDecoderState.NumericHex: - { - return this.stateNumericHex(str, offset); - } - case EntityDecoderState.NamedEntity: - { - return this.stateNamedEntity(str, offset); + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; } - } - }; - /** - * Switches between the numeric decimal and hexadecimal states. - * - * Equivalent to the `Numeric character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericStart = function (str, offset) { - if (offset >= str.length) { - return -1; - } - if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { - this.state = EntityDecoderState.NumericHex; - this.consumed += 1; - return this.stateNumericHex(str, offset + 1); - } - this.state = EntityDecoderState.NumericDecimal; - return this.stateNumericDecimal(str, offset); - }; - EntityDecoder.prototype.addToNumericResult = function (str, start, end, base) { - if (start !== end) { - var digitCount = end - start; - this.result = this.result * Math.pow(base, digitCount) + parseInt(str.substr(start, digitCount), base); - this.consumed += digitCount; - } - }; - /** - * Parses a hexadecimal numeric entity. - * - * Equivalent to the `Hexademical character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericHex = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char) || isHexadecimalCharacter(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 16); - return this.emitNumericEntity(char, 3); - } - } - this.addToNumericResult(str, startIdx, offset, 16); - return -1; - }; - /** - * Parses a decimal numeric entity. - * - * Equivalent to the `Decimal character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericDecimal = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 10); - return this.emitNumericEntity(char, 2); - } - } - this.addToNumericResult(str, startIdx, offset, 10); - return -1; - }; - /** - * Validate and emit a numeric entity. - * - * Implements the logic from the `Hexademical character reference start - * state` and `Numeric character reference end state` in the HTML spec. - * - * @param lastCp The last code point of the entity. Used to see if the - * entity was terminated with a semicolon. - * @param expectedLength The minimum number of characters that should be - * consumed. Used to validate that at least one digit - * was consumed. - * @returns The number of characters that were consumed. - */ - EntityDecoder.prototype.emitNumericEntity = function (lastCp, expectedLength) { - var _a; - // Ensure we consumed at least one digit. - if (this.consumed <= expectedLength) { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - // Figure out if this is a legit end of the entity - if (lastCp === CharCodes.SEMI) { - this.consumed += 1; - } else if (this.decodeMode === DecodingMode.Strict) { - return 0; - } - this.emitCodePoint((0, decode_codepoint_js_1.replaceCodePoint)(this.result), this.consumed); - if (this.errors) { - if (lastCp !== CharCodes.SEMI) { - this.errors.missingSemicolonAfterCharacterReference(); - } - this.errors.validateNumericCharacterReference(this.result); - } - return this.consumed; - }; - /** - * Parses a named entity. - * - * Equivalent to the `Named character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNamedEntity = function (str, offset) { - var decodeTree = this.decodeTree; - var current = decodeTree[this.treeIndex]; - // The mask is the number of bytes of the value, including the current byte. - var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - for (; offset < str.length; offset++, this.excess++) { - var char = str.charCodeAt(offset); - this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); - if (this.treeIndex < 0) { - return this.result === 0 || - // If we are parsing an attribute - this.decodeMode === DecodingMode.Attribute && ( - // We shouldn't have consumed any characters after the entity, - valueLength === 0 || - // And there should be no invalid characters. - isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity(); - } - current = decodeTree[this.treeIndex]; - valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - // If the branch is a value, store it and continue - if (valueLength !== 0) { - // If the entity is terminated by a semicolon, we are done. - if (char === CharCodes.SEMI) { - return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); - } - // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. - if (this.decodeMode !== DecodingMode.Strict) { - this.result = this.treeIndex; - this.consumed += this.excess; - this.excess = 0; + $parcel$export( + module.exports, + "createMenuScope", + () => $213e4d2df823067d$export$4027731b685e72eb + ); + $parcel$export( + module.exports, + "Menu", + () => $213e4d2df823067d$export$d9b273488cd8ce6f + ); + $parcel$export( + module.exports, + "MenuAnchor", + () => $213e4d2df823067d$export$9fa5ebd18bee4d43 + ); + $parcel$export( + module.exports, + "MenuPortal", + () => $213e4d2df823067d$export$793392f970497feb + ); + $parcel$export( + module.exports, + "MenuContent", + () => $213e4d2df823067d$export$479f0f2f71193efe + ); + $parcel$export( + module.exports, + "MenuGroup", + () => $213e4d2df823067d$export$22a631d1f72787bb + ); + $parcel$export( + module.exports, + "MenuLabel", + () => $213e4d2df823067d$export$dd37bec0e8a99143 + ); + $parcel$export( + module.exports, + "MenuItem", + () => $213e4d2df823067d$export$2ce376c2cc3355c8 + ); + $parcel$export( + module.exports, + "MenuCheckboxItem", + () => $213e4d2df823067d$export$f6f243521332502d + ); + $parcel$export( + module.exports, + "MenuRadioGroup", + () => $213e4d2df823067d$export$ea2200c9eee416b3 + ); + $parcel$export( + module.exports, + "MenuRadioItem", + () => $213e4d2df823067d$export$69bd225e9817f6d0 + ); + $parcel$export( + module.exports, + "MenuItemIndicator", + () => $213e4d2df823067d$export$a2593e23056970a3 + ); + $parcel$export( + module.exports, + "MenuSeparator", + () => $213e4d2df823067d$export$1cec7dcdd713e220 + ); + $parcel$export( + module.exports, + "MenuArrow", + () => $213e4d2df823067d$export$bcdda4773debf5fa + ); + $parcel$export( + module.exports, + "MenuSub", + () => $213e4d2df823067d$export$71bdb9d1e2909932 + ); + $parcel$export( + module.exports, + "MenuSubTrigger", + () => $213e4d2df823067d$export$5fbbb3ba7297405f + ); + $parcel$export( + module.exports, + "MenuSubContent", + () => $213e4d2df823067d$export$e7142ab31822bde6 + ); + $parcel$export( + module.exports, + "Root", + () => $213e4d2df823067d$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Anchor", + () => $213e4d2df823067d$export$b688253958b8dfe7 + ); + $parcel$export( + module.exports, + "Portal", + () => $213e4d2df823067d$export$602eac185826482c + ); + $parcel$export( + module.exports, + "Content", + () => $213e4d2df823067d$export$7c6e2c02157bb7d2 + ); + $parcel$export( + module.exports, + "Group", + () => $213e4d2df823067d$export$eb2fcfdbd7ba97d4 + ); + $parcel$export( + module.exports, + "Label", + () => $213e4d2df823067d$export$b04be29aa201d4f5 + ); + $parcel$export( + module.exports, + "Item", + () => $213e4d2df823067d$export$6d08773d2e66f8f2 + ); + $parcel$export( + module.exports, + "CheckboxItem", + () => $213e4d2df823067d$export$16ce288f89fa631c + ); + $parcel$export( + module.exports, + "RadioGroup", + () => $213e4d2df823067d$export$a98f0dcb43a68a25 + ); + $parcel$export( + module.exports, + "RadioItem", + () => $213e4d2df823067d$export$371ab307eab489c0 + ); + $parcel$export( + module.exports, + "ItemIndicator", + () => $213e4d2df823067d$export$c3468e2714d175fa + ); + $parcel$export( + module.exports, + "Separator", + () => $213e4d2df823067d$export$1ff3c3f08ae963c0 + ); + $parcel$export( + module.exports, + "Arrow", + () => $213e4d2df823067d$export$21b07c8f274aebd5 + ); + $parcel$export( + module.exports, + "Sub", + () => $213e4d2df823067d$export$d7a01e11500dfb6f + ); + $parcel$export( + module.exports, + "SubTrigger", + () => $213e4d2df823067d$export$2ea8a7a591ac5eac + ); + $parcel$export( + module.exports, + "SubContent", + () => $213e4d2df823067d$export$6d4de93b380beddf + ); + const $213e4d2df823067d$var$SELECTION_KEYS = ["Enter", " "]; + const $213e4d2df823067d$var$FIRST_KEYS = [ + "ArrowDown", + "PageUp", + "Home", + ]; + const $213e4d2df823067d$var$LAST_KEYS = ["ArrowUp", "PageDown", "End"]; + const $213e4d2df823067d$var$FIRST_LAST_KEYS = [ + ...$213e4d2df823067d$var$FIRST_KEYS, + ...$213e4d2df823067d$var$LAST_KEYS, + ]; + const $213e4d2df823067d$var$SUB_OPEN_KEYS = { + ltr: [...$213e4d2df823067d$var$SELECTION_KEYS, "ArrowRight"], + rtl: [...$213e4d2df823067d$var$SELECTION_KEYS, "ArrowLeft"], + }; + const $213e4d2df823067d$var$SUB_CLOSE_KEYS = { + ltr: ["ArrowLeft"], + rtl: ["ArrowRight"], + }; + /* ------------------------------------------------------------------------------------------------- + * Menu + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$MENU_NAME = "Menu"; + const [ + $213e4d2df823067d$var$Collection, + $213e4d2df823067d$var$useCollection, + $213e4d2df823067d$var$createCollectionScope, + ] = $cnSS2$radixuireactcollection.createCollection( + $213e4d2df823067d$var$MENU_NAME + ); + const [ + $213e4d2df823067d$var$createMenuContext, + $213e4d2df823067d$export$4027731b685e72eb, + ] = $cnSS2$radixuireactcontext.createContextScope( + $213e4d2df823067d$var$MENU_NAME, + [ + $213e4d2df823067d$var$createCollectionScope, + $cnSS2$radixuireactpopper.createPopperScope, + $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope, + ] + ); + const $213e4d2df823067d$var$usePopperScope = + $cnSS2$radixuireactpopper.createPopperScope(); + const $213e4d2df823067d$var$useRovingFocusGroupScope = + $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope(); + const [ + $213e4d2df823067d$var$MenuProvider, + $213e4d2df823067d$var$useMenuContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$MENU_NAME + ); + const [ + $213e4d2df823067d$var$MenuRootProvider, + $213e4d2df823067d$var$useMenuRootContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$MENU_NAME + ); + const $213e4d2df823067d$export$d9b273488cd8ce6f = (props) => { + const { + __scopeMenu: __scopeMenu, + open = false, + children: children, + dir: dir, + onOpenChange: onOpenChange, + modal = true, + } = props; + const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); + const [content, setContent] = $cnSS2$react.useState(null); + const isUsingKeyboardRef = $cnSS2$react.useRef(false); + const handleOpenChange = + $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); + const direction = $cnSS2$radixuireactdirection.useDirection(dir); + $cnSS2$react.useEffect(() => { + // Capture phase ensures we set the boolean before any side effects execute + // in response to the key or pointer event as they might depend on this value. + const handleKeyDown = () => { + isUsingKeyboardRef.current = true; + document.addEventListener("pointerdown", handlePointer, { + capture: true, + once: true, + }); + document.addEventListener("pointermove", handlePointer, { + capture: true, + once: true, + }); + }; + const handlePointer = () => (isUsingKeyboardRef.current = false); + document.addEventListener("keydown", handleKeyDown, { + capture: true, + }); + return () => { + document.removeEventListener("keydown", handleKeyDown, { + capture: true, + }); + document.removeEventListener("pointerdown", handlePointer, { + capture: true, + }); + document.removeEventListener("pointermove", handlePointer, { + capture: true, + }); + }; + }, []); + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpopper.Root, + popperScope, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuProvider, + { + scope: __scopeMenu, + open: open, + onOpenChange: handleOpenChange, + content: content, + onContentChange: setContent, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuRootProvider, + { + scope: __scopeMenu, + onClose: $cnSS2$react.useCallback( + () => handleOpenChange(false), + [handleOpenChange] + ), + isUsingKeyboardRef: isUsingKeyboardRef, + dir: direction, + modal: modal, + }, + children + ) + ) + ); + }; + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$d9b273488cd8ce6f, { + displayName: $213e4d2df823067d$var$MENU_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuAnchor + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$ANCHOR_NAME = "MenuAnchor"; + const $213e4d2df823067d$export$9fa5ebd18bee4d43 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { __scopeMenu: __scopeMenu, ...anchorProps } = props; + const popperScope = + $213e4d2df823067d$var$usePopperScope(__scopeMenu); + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpopper.Anchor, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + popperScope, + anchorProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$9fa5ebd18bee4d43, { + displayName: $213e4d2df823067d$var$ANCHOR_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuPortal + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$PORTAL_NAME = "MenuPortal"; + const [ + $213e4d2df823067d$var$PortalProvider, + $213e4d2df823067d$var$usePortalContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$PORTAL_NAME, + { + forceMount: undefined, + } + ); + const $213e4d2df823067d$export$793392f970497feb = (props) => { + const { + __scopeMenu: __scopeMenu, + forceMount: forceMount, + children: children, + container: container, + } = props; + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$PORTAL_NAME, + __scopeMenu + ); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$PortalProvider, + { + scope: __scopeMenu, + forceMount: forceMount, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactportal.Portal, + { + asChild: true, + container: container, + }, + children + ) + ) + ); + }; + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$793392f970497feb, { + displayName: $213e4d2df823067d$var$PORTAL_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuContent + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$CONTENT_NAME = "MenuContent"; + const [ + $213e4d2df823067d$var$MenuContentProvider, + $213e4d2df823067d$var$useMenuContentContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$CONTENT_NAME + ); + const $213e4d2df823067d$export$479f0f2f71193efe = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const portalContext = $213e4d2df823067d$var$usePortalContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + const { forceMount = portalContext.forceMount, ...contentProps } = + props; + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + const rootContext = $213e4d2df823067d$var$useMenuRootContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$Collection.Provider, + { + scope: props.__scopeMenu, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$Collection.Slot, + { + scope: props.__scopeMenu, + }, + rootContext.modal + ? /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuRootContentModal, + $parcel$interopDefault( + $cnSS2$babelruntimehelpersextends + )({}, contentProps, { + ref: forwardedRef, + }) + ) + : /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuRootContentNonModal, + $parcel$interopDefault( + $cnSS2$babelruntimehelpersextends + )({}, contentProps, { + ref: forwardedRef, + }) + ) + ) + ) + ); + }); + /* ---------------------------------------------------------------------------------------------- */ + const $213e4d2df823067d$var$MenuRootContentModal = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + const ref = $cnSS2$react.useRef(null); + const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); // Hide everything from ARIA except the `MenuContent` + $cnSS2$react.useEffect(() => { + const content = ref.current; + if (content) return $cnSS2$ariahidden.hideOthers(content); + }, []); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuContentImpl, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + props, + { + ref: composedRefs, // we make sure we're not trapping once it's been closed + trapFocus: context.open, // make sure to only disable pointer events when open + disableOutsidePointerEvents: context.open, + disableOutsideScroll: true, // When focus is trapped, a `focusout` event may still happen. + onFocusOutside: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onFocusOutside, + (event) => event.preventDefault(), + { + checkForDefaultPrevented: false, + } + ), + onDismiss: () => context.onOpenChange(false), + } + ) + ); + }); + const $213e4d2df823067d$var$MenuRootContentNonModal = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuContentImpl, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + props, + { + ref: forwardedRef, + trapFocus: false, + disableOutsidePointerEvents: false, + disableOutsideScroll: false, + onDismiss: () => context.onOpenChange(false), + } + ) + ); + }); + /* ---------------------------------------------------------------------------------------------- */ + const $213e4d2df823067d$var$MenuContentImpl = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { + __scopeMenu: __scopeMenu, + loop = false, + trapFocus: trapFocus, + onOpenAutoFocus: onOpenAutoFocus, + onCloseAutoFocus: onCloseAutoFocus, + disableOutsidePointerEvents: disableOutsidePointerEvents, + onEntryFocus: onEntryFocus, + onEscapeKeyDown: onEscapeKeyDown, + onPointerDownOutside: onPointerDownOutside, + onFocusOutside: onFocusOutside, + onInteractOutside: onInteractOutside, + onDismiss: onDismiss, + disableOutsideScroll: disableOutsideScroll, + ...contentProps + } = props; + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$CONTENT_NAME, + __scopeMenu + ); + const rootContext = $213e4d2df823067d$var$useMenuRootContext( + $213e4d2df823067d$var$CONTENT_NAME, + __scopeMenu + ); + const popperScope = + $213e4d2df823067d$var$usePopperScope(__scopeMenu); + const rovingFocusGroupScope = + $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); + const getItems = $213e4d2df823067d$var$useCollection(__scopeMenu); + const [currentItemId, setCurrentItemId] = + $cnSS2$react.useState(null); + const contentRef = $cnSS2$react.useRef(null); + const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + contentRef, + context.onContentChange + ); + const timerRef = $cnSS2$react.useRef(0); + const searchRef = $cnSS2$react.useRef(""); + const pointerGraceTimerRef = $cnSS2$react.useRef(0); + const pointerGraceIntentRef = $cnSS2$react.useRef(null); + const pointerDirRef = $cnSS2$react.useRef("right"); + const lastPointerXRef = $cnSS2$react.useRef(0); + const ScrollLockWrapper = disableOutsideScroll + ? $cnSS2$reactremovescroll.RemoveScroll + : $cnSS2$react.Fragment; + const scrollLockWrapperProps = disableOutsideScroll + ? { + as: $cnSS2$radixuireactslot.Slot, + allowPinchZoom: true, + } + : undefined; + const handleTypeaheadSearch = (key) => { + var _items$find, _items$find2; + const search = searchRef.current + key; + const items = getItems().filter((item) => !item.disabled); + const currentItem = document.activeElement; + const currentMatch = + (_items$find = items.find( + (item) => item.ref.current === currentItem + )) === null || _items$find === void 0 + ? void 0 + : _items$find.textValue; + const values = items.map((item) => item.textValue); + const nextMatch = $213e4d2df823067d$var$getNextMatch( + values, + search, + currentMatch + ); + const newItem = + (_items$find2 = items.find( + (item) => item.textValue === nextMatch + )) === null || _items$find2 === void 0 + ? void 0 + : _items$find2.ref.current; // Reset `searchRef` 1 second after it was last updated + (function updateSearch(value) { + searchRef.current = value; + window.clearTimeout(timerRef.current); + if (value !== "") + timerRef.current = window.setTimeout( + () => updateSearch(""), + 1000 + ); + })(search); + if (newItem) + /** + * Imperative focus during keydown is risky so we prevent React's batching updates + * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 + */ + setTimeout(() => newItem.focus()); + }; + $cnSS2$react.useEffect(() => { + return () => window.clearTimeout(timerRef.current); + }, []); // Make sure the whole tree has focus guards as our `MenuContent` may be + // the last element in the DOM (beacuse of the `Portal`) + $cnSS2$radixuireactfocusguards.useFocusGuards(); + const isPointerMovingToSubmenu = $cnSS2$react.useCallback( + (event) => { + var _pointerGraceIntentRe, _pointerGraceIntentRe2; + const isMovingTowards = + pointerDirRef.current === + ((_pointerGraceIntentRe = pointerGraceIntentRef.current) === + null || _pointerGraceIntentRe === void 0 + ? void 0 + : _pointerGraceIntentRe.side); + return ( + isMovingTowards && + $213e4d2df823067d$var$isPointerInGraceArea( + event, + (_pointerGraceIntentRe2 = pointerGraceIntentRef.current) === + null || _pointerGraceIntentRe2 === void 0 + ? void 0 + : _pointerGraceIntentRe2.area + ) + ); + }, + [] + ); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuContentProvider, + { + scope: __scopeMenu, + searchRef: searchRef, + onItemEnter: $cnSS2$react.useCallback( + (event) => { + if (isPointerMovingToSubmenu(event)) event.preventDefault(); + }, + [isPointerMovingToSubmenu] + ), + onItemLeave: $cnSS2$react.useCallback( + (event) => { + var _contentRef$current; + if (isPointerMovingToSubmenu(event)) return; + (_contentRef$current = contentRef.current) === null || + _contentRef$current === void 0 || + _contentRef$current.focus(); + setCurrentItemId(null); + }, + [isPointerMovingToSubmenu] + ), + onTriggerLeave: $cnSS2$react.useCallback( + (event) => { + if (isPointerMovingToSubmenu(event)) event.preventDefault(); + }, + [isPointerMovingToSubmenu] + ), + pointerGraceTimerRef: pointerGraceTimerRef, + onPointerGraceIntentChange: $cnSS2$react.useCallback( + (intent) => { + pointerGraceIntentRef.current = intent; + }, + [] + ), + }, + /*#__PURE__*/ $cnSS2$react.createElement( + ScrollLockWrapper, + scrollLockWrapperProps, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactfocusscope.FocusScope, + { + asChild: true, + trapped: trapFocus, + onMountAutoFocus: + $cnSS2$radixuiprimitive.composeEventHandlers( + onOpenAutoFocus, + (event) => { + var _contentRef$current2; + // when opening, explicitly focus the content area only and leave + // `onEntryFocus` in control of focusing first item + event.preventDefault(); + (_contentRef$current2 = contentRef.current) === + null || + _contentRef$current2 === void 0 || + _contentRef$current2.focus(); + } + ), + onUnmountAutoFocus: onCloseAutoFocus, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactdismissablelayer.DismissableLayer, + { + asChild: true, + disableOutsidePointerEvents: disableOutsidePointerEvents, + onEscapeKeyDown: onEscapeKeyDown, + onPointerDownOutside: onPointerDownOutside, + onFocusOutside: onFocusOutside, + onInteractOutside: onInteractOutside, + onDismiss: onDismiss, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactrovingfocus.Root, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + asChild: true, + }, + rovingFocusGroupScope, + { + dir: rootContext.dir, + orientation: "vertical", + loop: loop, + currentTabStopId: currentItemId, + onCurrentTabStopIdChange: setCurrentItemId, + onEntryFocus: + $cnSS2$radixuiprimitive.composeEventHandlers( + onEntryFocus, + (event) => { + // only focus first item when using keyboard + if (!rootContext.isUsingKeyboardRef.current) + event.preventDefault(); + } + ), + } + ), + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpopper.Content, + $parcel$interopDefault( + $cnSS2$babelruntimehelpersextends + )( + { + role: "menu", + "aria-orientation": "vertical", + "data-state": $213e4d2df823067d$var$getOpenState( + context.open + ), + "data-radix-menu-content": "", + dir: rootContext.dir, + }, + popperScope, + contentProps, + { + ref: composedRefs, + style: { + outline: "none", + ...contentProps.style, + }, + onKeyDown: + $cnSS2$radixuiprimitive.composeEventHandlers( + contentProps.onKeyDown, + (event) => { + // submenu key events bubble through portals. We only care about keys in this menu. + const target = event.target; + const isKeyDownInside = + target.closest( + "[data-radix-menu-content]" + ) === event.currentTarget; + const isModifierKey = + event.ctrlKey || + event.altKey || + event.metaKey; + const isCharacterKey = event.key.length === 1; + if (isKeyDownInside) { + // menus should not be navigated using tab key so we prevent it + if (event.key === "Tab") + event.preventDefault(); + if (!isModifierKey && isCharacterKey) + handleTypeaheadSearch(event.key); + } // focus first/last item based on key pressed + const content = contentRef.current; + if (event.target !== content) return; + if ( + !$213e4d2df823067d$var$FIRST_LAST_KEYS.includes( + event.key + ) + ) + return; + event.preventDefault(); + const items = getItems().filter( + (item) => !item.disabled + ); + const candidateNodes = items.map( + (item) => item.ref.current + ); + if ( + $213e4d2df823067d$var$LAST_KEYS.includes( + event.key + ) + ) + candidateNodes.reverse(); + $213e4d2df823067d$var$focusFirst( + candidateNodes + ); + } + ), + onBlur: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onBlur, + (event) => { + // clear search buffer when leaving the menu + if ( + !event.currentTarget.contains(event.target) + ) { + window.clearTimeout(timerRef.current); + searchRef.current = ""; + } + } + ), + onPointerMove: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onPointerMove, + $213e4d2df823067d$var$whenMouse((event) => { + const target = event.target; + const pointerXHasChanged = + lastPointerXRef.current !== event.clientX; // We don't use `event.movementX` for this check because Safari will + // always return `0` on a pointer event. + if ( + event.currentTarget.contains(target) && + pointerXHasChanged + ) { + const newDir = + event.clientX > lastPointerXRef.current + ? "right" + : "left"; + pointerDirRef.current = newDir; + lastPointerXRef.current = event.clientX; + } + }) + ), + } + ) + ) + ) + ) + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$479f0f2f71193efe, { + displayName: $213e4d2df823067d$var$CONTENT_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuGroup + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$GROUP_NAME = "MenuGroup"; + const $213e4d2df823067d$export$22a631d1f72787bb = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { __scopeMenu: __scopeMenu, ...groupProps } = props; + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + role: "group", + }, + groupProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$22a631d1f72787bb, { + displayName: $213e4d2df823067d$var$GROUP_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuLabel + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$LABEL_NAME = "MenuLabel"; + const $213e4d2df823067d$export$dd37bec0e8a99143 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { __scopeMenu: __scopeMenu, ...labelProps } = props; + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + labelProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$dd37bec0e8a99143, { + displayName: $213e4d2df823067d$var$LABEL_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuItem + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$ITEM_NAME = "MenuItem"; + const $213e4d2df823067d$var$ITEM_SELECT = "menu.itemSelect"; + const $213e4d2df823067d$export$2ce376c2cc3355c8 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { + disabled = false, + onSelect: onSelect, + ...itemProps + } = props; + const ref = $cnSS2$react.useRef(null); + const rootContext = $213e4d2df823067d$var$useMenuRootContext( + $213e4d2df823067d$var$ITEM_NAME, + props.__scopeMenu + ); + const contentContext = $213e4d2df823067d$var$useMenuContentContext( + $213e4d2df823067d$var$ITEM_NAME, + props.__scopeMenu + ); + const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + const isPointerDownRef = $cnSS2$react.useRef(false); + const handleSelect = () => { + const menuItem = ref.current; + if (!disabled && menuItem) { + const itemSelectEvent = new CustomEvent( + $213e4d2df823067d$var$ITEM_SELECT, + { + bubbles: true, + cancelable: true, + } + ); + menuItem.addEventListener( + $213e4d2df823067d$var$ITEM_SELECT, + (event) => + onSelect === null || onSelect === void 0 + ? void 0 + : onSelect(event), + { + once: true, + } + ); + $cnSS2$radixuireactprimitive.dispatchDiscreteCustomEvent( + menuItem, + itemSelectEvent + ); + if (itemSelectEvent.defaultPrevented) + isPointerDownRef.current = false; + else rootContext.onClose(); + } + }; + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuItemImpl, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + itemProps, + { + ref: composedRefs, + disabled: disabled, + onClick: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onClick, + handleSelect + ), + onPointerDown: (event) => { + var _props$onPointerDown; + (_props$onPointerDown = props.onPointerDown) === null || + _props$onPointerDown === void 0 || + _props$onPointerDown.call(props, event); + isPointerDownRef.current = true; + }, + onPointerUp: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onPointerUp, + (event) => { + var _event$currentTarget; + // Pointer down can move to a different menu item which should activate it on pointer up. + // We dispatch a click for selection to allow composition with click based triggers and to + // prevent Firefox from getting stuck in text selection mode when the menu closes. + if (!isPointerDownRef.current) + (_event$currentTarget = event.currentTarget) === null || + _event$currentTarget === void 0 || + _event$currentTarget.click(); + } + ), + onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onKeyDown, + (event) => { + const isTypingAhead = + contentContext.searchRef.current !== ""; + if (disabled || (isTypingAhead && event.key === " ")) + return; + if ( + $213e4d2df823067d$var$SELECTION_KEYS.includes(event.key) + ) { + event.currentTarget.click(); + /** + * We prevent default browser behaviour for selection keys as they should trigger + * a selection only: + * - prevents space from scrolling the page. + * - if keydown causes focus to move, prevents keydown from firing on the new target. + */ + event.preventDefault(); + } + } + ), + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$2ce376c2cc3355c8, { + displayName: $213e4d2df823067d$var$ITEM_NAME, + }); + /* ---------------------------------------------------------------------------------------------- */ + const $213e4d2df823067d$var$MenuItemImpl = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { + __scopeMenu: __scopeMenu, + disabled = false, + textValue: textValue, + ...itemProps + } = props; + const contentContext = $213e4d2df823067d$var$useMenuContentContext( + $213e4d2df823067d$var$ITEM_NAME, + __scopeMenu + ); + const rovingFocusGroupScope = + $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); + const ref = $cnSS2$react.useRef(null); + const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + const [isFocused, setIsFocused] = $cnSS2$react.useState(false); // get the item's `.textContent` as default strategy for typeahead `textValue` + const [textContent, setTextContent] = $cnSS2$react.useState(""); + $cnSS2$react.useEffect(() => { + const menuItem = ref.current; + if (menuItem) { + var _menuItem$textContent; + setTextContent( + ((_menuItem$textContent = menuItem.textContent) !== null && + _menuItem$textContent !== void 0 + ? _menuItem$textContent + : "" + ).trim() + ); + } + }, [itemProps.children]); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$Collection.ItemSlot, + { + scope: __scopeMenu, + disabled: disabled, + textValue: + textValue !== null && textValue !== void 0 + ? textValue + : textContent, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactrovingfocus.Item, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + asChild: true, + }, + rovingFocusGroupScope, + { + focusable: !disabled, + } + ), + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + role: "menuitem", + "data-highlighted": isFocused ? "" : undefined, + "aria-disabled": disabled || undefined, + "data-disabled": disabled ? "" : undefined, + }, + itemProps, + { + ref: composedRefs, + onPointerMove: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onPointerMove, + $213e4d2df823067d$var$whenMouse((event) => { + if (disabled) contentContext.onItemLeave(event); + else { + contentContext.onItemEnter(event); + if (!event.defaultPrevented) { + const item = event.currentTarget; + item.focus(); + } + } + }) + ), + onPointerLeave: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onPointerLeave, + $213e4d2df823067d$var$whenMouse((event) => + contentContext.onItemLeave(event) + ) + ), + onFocus: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onFocus, + () => setIsFocused(true) + ), + onBlur: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onBlur, + () => setIsFocused(false) + ), + } + ) + ) + ) + ); + }); + /* ------------------------------------------------------------------------------------------------- + * MenuCheckboxItem + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$CHECKBOX_ITEM_NAME = "MenuCheckboxItem"; + const $213e4d2df823067d$export$f6f243521332502d = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { + checked = false, + onCheckedChange: onCheckedChange, + ...checkboxItemProps + } = props; + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$ItemIndicatorProvider, + { + scope: props.__scopeMenu, + checked: checked, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$export$2ce376c2cc3355c8, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + role: "menuitemcheckbox", + "aria-checked": $213e4d2df823067d$var$isIndeterminate( + checked + ) + ? "mixed" + : checked, + }, + checkboxItemProps, + { + ref: forwardedRef, + "data-state": + $213e4d2df823067d$var$getCheckedState(checked), + onSelect: $cnSS2$radixuiprimitive.composeEventHandlers( + checkboxItemProps.onSelect, + () => + onCheckedChange === null || onCheckedChange === void 0 + ? void 0 + : onCheckedChange( + $213e4d2df823067d$var$isIndeterminate(checked) + ? true + : !checked + ), + { + checkForDefaultPrevented: false, + } + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$f6f243521332502d, { + displayName: $213e4d2df823067d$var$CHECKBOX_ITEM_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuRadioGroup + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$RADIO_GROUP_NAME = "MenuRadioGroup"; + const [ + $213e4d2df823067d$var$RadioGroupProvider, + $213e4d2df823067d$var$useRadioGroupContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$RADIO_GROUP_NAME, + { + value: undefined, + onValueChange: () => {}, + } + ); + const $213e4d2df823067d$export$ea2200c9eee416b3 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { + value: value, + onValueChange: onValueChange, + ...groupProps + } = props; + const handleValueChange = + $cnSS2$radixuireactusecallbackref.useCallbackRef(onValueChange); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$RadioGroupProvider, + { + scope: props.__scopeMenu, + value: value, + onValueChange: handleValueChange, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$export$22a631d1f72787bb, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + groupProps, + { + ref: forwardedRef, + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$ea2200c9eee416b3, { + displayName: $213e4d2df823067d$var$RADIO_GROUP_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuRadioItem + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$RADIO_ITEM_NAME = "MenuRadioItem"; + const $213e4d2df823067d$export$69bd225e9817f6d0 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { value: value, ...radioItemProps } = props; + const context = $213e4d2df823067d$var$useRadioGroupContext( + $213e4d2df823067d$var$RADIO_ITEM_NAME, + props.__scopeMenu + ); + const checked = value === context.value; + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$ItemIndicatorProvider, + { + scope: props.__scopeMenu, + checked: checked, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$export$2ce376c2cc3355c8, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + role: "menuitemradio", + "aria-checked": checked, + }, + radioItemProps, + { + ref: forwardedRef, + "data-state": + $213e4d2df823067d$var$getCheckedState(checked), + onSelect: $cnSS2$radixuiprimitive.composeEventHandlers( + radioItemProps.onSelect, + () => { + var _context$onValueChang; + return (_context$onValueChang = + context.onValueChange) === null || + _context$onValueChang === void 0 + ? void 0 + : _context$onValueChang.call(context, value); + }, + { + checkForDefaultPrevented: false, + } + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$69bd225e9817f6d0, { + displayName: $213e4d2df823067d$var$RADIO_ITEM_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuItemIndicator + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$ITEM_INDICATOR_NAME = "MenuItemIndicator"; + const [ + $213e4d2df823067d$var$ItemIndicatorProvider, + $213e4d2df823067d$var$useItemIndicatorContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$ITEM_INDICATOR_NAME, + { + checked: false, + } + ); + const $213e4d2df823067d$export$a2593e23056970a3 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { + __scopeMenu: __scopeMenu, + forceMount: forceMount, + ...itemIndicatorProps + } = props; + const indicatorContext = + $213e4d2df823067d$var$useItemIndicatorContext( + $213e4d2df823067d$var$ITEM_INDICATOR_NAME, + __scopeMenu + ); + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpresence.Presence, + { + present: + forceMount || + $213e4d2df823067d$var$isIndeterminate( + indicatorContext.checked + ) || + indicatorContext.checked === true, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactprimitive.Primitive.span, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + itemIndicatorProps, + { + ref: forwardedRef, + "data-state": $213e4d2df823067d$var$getCheckedState( + indicatorContext.checked + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$a2593e23056970a3, { + displayName: $213e4d2df823067d$var$ITEM_INDICATOR_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuSeparator + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$SEPARATOR_NAME = "MenuSeparator"; + const $213e4d2df823067d$export$1cec7dcdd713e220 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { __scopeMenu: __scopeMenu, ...separatorProps } = props; + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + role: "separator", + "aria-orientation": "horizontal", + }, + separatorProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$1cec7dcdd713e220, { + displayName: $213e4d2df823067d$var$SEPARATOR_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuArrow + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$ARROW_NAME = "MenuArrow"; + const $213e4d2df823067d$export$bcdda4773debf5fa = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const { __scopeMenu: __scopeMenu, ...arrowProps } = props; + const popperScope = + $213e4d2df823067d$var$usePopperScope(__scopeMenu); + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpopper.Arrow, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + {}, + popperScope, + arrowProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$bcdda4773debf5fa, { + displayName: $213e4d2df823067d$var$ARROW_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuSub + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$SUB_NAME = "MenuSub"; + const [ + $213e4d2df823067d$var$MenuSubProvider, + $213e4d2df823067d$var$useMenuSubContext, + ] = $213e4d2df823067d$var$createMenuContext( + $213e4d2df823067d$var$SUB_NAME + ); + const $213e4d2df823067d$export$71bdb9d1e2909932 = (props) => { + const { + __scopeMenu: __scopeMenu, + children: children, + open = false, + onOpenChange: onOpenChange, + } = props; + const parentMenuContext = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$SUB_NAME, + __scopeMenu + ); + const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); + const [trigger, setTrigger] = $cnSS2$react.useState(null); + const [content, setContent] = $cnSS2$react.useState(null); + const handleOpenChange = + $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); // Prevent the parent menu from reopening with open submenus. + $cnSS2$react.useEffect(() => { + if (parentMenuContext.open === false) handleOpenChange(false); + return () => handleOpenChange(false); + }, [parentMenuContext.open, handleOpenChange]); + return /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpopper.Root, + popperScope, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuProvider, + { + scope: __scopeMenu, + open: open, + onOpenChange: handleOpenChange, + content: content, + onContentChange: setContent, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuSubProvider, + { + scope: __scopeMenu, + contentId: $cnSS2$radixuireactid.useId(), + triggerId: $cnSS2$radixuireactid.useId(), + trigger: trigger, + onTriggerChange: setTrigger, + }, + children + ) + ) + ); + }; + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$71bdb9d1e2909932, { + displayName: $213e4d2df823067d$var$SUB_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuSubTrigger + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$SUB_TRIGGER_NAME = "MenuSubTrigger"; + const $213e4d2df823067d$export$5fbbb3ba7297405f = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$SUB_TRIGGER_NAME, + props.__scopeMenu + ); + const rootContext = $213e4d2df823067d$var$useMenuRootContext( + $213e4d2df823067d$var$SUB_TRIGGER_NAME, + props.__scopeMenu + ); + const subContext = $213e4d2df823067d$var$useMenuSubContext( + $213e4d2df823067d$var$SUB_TRIGGER_NAME, + props.__scopeMenu + ); + const contentContext = $213e4d2df823067d$var$useMenuContentContext( + $213e4d2df823067d$var$SUB_TRIGGER_NAME, + props.__scopeMenu + ); + const openTimerRef = $cnSS2$react.useRef(null); + const { + pointerGraceTimerRef: pointerGraceTimerRef, + onPointerGraceIntentChange: onPointerGraceIntentChange, + } = contentContext; + const scope = { + __scopeMenu: props.__scopeMenu, + }; + const clearOpenTimer = $cnSS2$react.useCallback(() => { + if (openTimerRef.current) + window.clearTimeout(openTimerRef.current); + openTimerRef.current = null; + }, []); + $cnSS2$react.useEffect(() => clearOpenTimer, [clearOpenTimer]); + $cnSS2$react.useEffect(() => { + const pointerGraceTimer = pointerGraceTimerRef.current; + return () => { + window.clearTimeout(pointerGraceTimer); + onPointerGraceIntentChange(null); + }; + }, [pointerGraceTimerRef, onPointerGraceIntentChange]); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$export$9fa5ebd18bee4d43, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + asChild: true, + }, + scope + ), + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuItemImpl, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + id: subContext.triggerId, + "aria-haspopup": "menu", + "aria-expanded": context.open, + "aria-controls": subContext.contentId, + "data-state": $213e4d2df823067d$var$getOpenState( + context.open + ), + }, + props, + { + ref: $cnSS2$radixuireactcomposerefs.composeRefs( + forwardedRef, + subContext.onTriggerChange + ), // This is redundant for mouse users but we cannot determine pointer type from + onClick: (event) => { + var _props$onClick; + (_props$onClick = props.onClick) === null || + _props$onClick === void 0 || + _props$onClick.call(props, event); + if (props.disabled || event.defaultPrevented) return; + /** + * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons) + * and we rely heavily on `onFocusOutside` for submenus to close when switching + * between separate submenus. + */ + event.currentTarget.focus(); + if (!context.open) context.onOpenChange(true); + }, + onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onPointerMove, + $213e4d2df823067d$var$whenMouse((event) => { + contentContext.onItemEnter(event); + if (event.defaultPrevented) return; + if ( + !props.disabled && + !context.open && + !openTimerRef.current + ) { + contentContext.onPointerGraceIntentChange(null); + openTimerRef.current = window.setTimeout(() => { + context.onOpenChange(true); + clearOpenTimer(); + }, 100); + } + }) + ), + onPointerLeave: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onPointerLeave, + $213e4d2df823067d$var$whenMouse((event) => { + var _context$content; + clearOpenTimer(); + const contentRect = + (_context$content = context.content) === null || + _context$content === void 0 + ? void 0 + : _context$content.getBoundingClientRect(); + if (contentRect) { + var _context$content2; + // TODO: make sure to update this when we change positioning logic + const side = + (_context$content2 = context.content) === null || + _context$content2 === void 0 + ? void 0 + : _context$content2.dataset.side; + const rightSide = side === "right"; + const bleed = rightSide ? -5 : 5; + const contentNearEdge = + contentRect[rightSide ? "left" : "right"]; + const contentFarEdge = + contentRect[rightSide ? "right" : "left"]; + contentContext.onPointerGraceIntentChange({ + area: [ + // consistently within polygon bounds + { + x: event.clientX + bleed, + y: event.clientY, + }, + { + x: contentNearEdge, + y: contentRect.top, + }, + { + x: contentFarEdge, + y: contentRect.top, + }, + { + x: contentFarEdge, + y: contentRect.bottom, + }, + { + x: contentNearEdge, + y: contentRect.bottom, + }, + ], + side: side, + }); + window.clearTimeout(pointerGraceTimerRef.current); + pointerGraceTimerRef.current = window.setTimeout( + () => + contentContext.onPointerGraceIntentChange(null), + 300 + ); + } else { + contentContext.onTriggerLeave(event); + if (event.defaultPrevented) return; // There's 100ms where the user may leave an item before the submenu was opened. + contentContext.onPointerGraceIntentChange(null); + } + }) + ), + onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onKeyDown, + (event) => { + const isTypingAhead = + contentContext.searchRef.current !== ""; + if ( + props.disabled || + (isTypingAhead && event.key === " ") + ) + return; + if ( + $213e4d2df823067d$var$SUB_OPEN_KEYS[ + rootContext.dir + ].includes(event.key) + ) { + var _context$content3; + context.onOpenChange(true); // The trigger may hold focus if opened via pointer interaction + // so we ensure content is given focus again when switching to keyboard. + (_context$content3 = context.content) === null || + _context$content3 === void 0 || + _context$content3.focus(); // prevent window from scrolling + event.preventDefault(); + } + } + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$5fbbb3ba7297405f, { + displayName: $213e4d2df823067d$var$SUB_TRIGGER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * MenuSubContent + * -----------------------------------------------------------------------------------------------*/ + const $213e4d2df823067d$var$SUB_CONTENT_NAME = "MenuSubContent"; + const $213e4d2df823067d$export$e7142ab31822bde6 = + /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { + const portalContext = $213e4d2df823067d$var$usePortalContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + const { + forceMount = portalContext.forceMount, + ...subContentProps + } = props; + const context = $213e4d2df823067d$var$useMenuContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + const rootContext = $213e4d2df823067d$var$useMenuRootContext( + $213e4d2df823067d$var$CONTENT_NAME, + props.__scopeMenu + ); + const subContext = $213e4d2df823067d$var$useMenuSubContext( + $213e4d2df823067d$var$SUB_CONTENT_NAME, + props.__scopeMenu + ); + const ref = $cnSS2$react.useRef(null); + const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + return /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$Collection.Provider, + { + scope: props.__scopeMenu, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $cnSS2$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$Collection.Slot, + { + scope: props.__scopeMenu, + }, + /*#__PURE__*/ $cnSS2$react.createElement( + $213e4d2df823067d$var$MenuContentImpl, + $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( + { + id: subContext.contentId, + "aria-labelledby": subContext.triggerId, + }, + subContentProps, + { + ref: composedRefs, + align: "start", + side: rootContext.dir === "rtl" ? "left" : "right", + disableOutsidePointerEvents: false, + disableOutsideScroll: false, + trapFocus: false, + onOpenAutoFocus: (event) => { + var _ref$current; + // when opening a submenu, focus content for keyboard users only + if (rootContext.isUsingKeyboardRef.current) + (_ref$current = ref.current) === null || + _ref$current === void 0 || + _ref$current.focus(); + event.preventDefault(); + }, // The menu might close because of focusing another menu item in the parent menu. We + onCloseAutoFocus: (event) => event.preventDefault(), + onFocusOutside: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onFocusOutside, + (event) => { + // We prevent closing when the trigger is focused to avoid triggering a re-open animation + // on pointer interaction. + if (event.target !== subContext.trigger) + context.onOpenChange(false); + } + ), + onEscapeKeyDown: + $cnSS2$radixuiprimitive.composeEventHandlers( + props.onEscapeKeyDown, + (event) => { + rootContext.onClose(); // ensure pressing escape in submenu doesn't escape full screen mode + event.preventDefault(); + } + ), + onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers( + props.onKeyDown, + (event) => { + // Submenu key events bubble through portals. We only care about keys in this menu. + const isKeyDownInside = + event.currentTarget.contains(event.target); + const isCloseKey = + $213e4d2df823067d$var$SUB_CLOSE_KEYS[ + rootContext.dir + ].includes(event.key); + if (isKeyDownInside && isCloseKey) { + var _subContext$trigger; + context.onOpenChange(false); // We focus manually because we prevented it in `onCloseAutoFocus` + (_subContext$trigger = subContext.trigger) === + null || + _subContext$trigger === void 0 || + _subContext$trigger.focus(); // prevent window from scrolling + event.preventDefault(); + } + } + ), + } + ) + ) + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($213e4d2df823067d$export$e7142ab31822bde6, { + displayName: $213e4d2df823067d$var$SUB_CONTENT_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + function $213e4d2df823067d$var$getOpenState(open) { + return open ? "open" : "closed"; } - } - } - return -1; - }; - /** - * Emit a named entity that was not terminated with a semicolon. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.emitNotTerminatedNamedEntity = function () { - var _a; - var _b = this, - result = _b.result, - decodeTree = _b.decodeTree; - var valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; - this.emitNamedEntityData(result, valueLength, this.consumed); - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); - return this.consumed; - }; - /** - * Emit a named entity. - * - * @param result The index of the entity in the decode tree. - * @param valueLength The number of bytes in the entity. - * @param consumed The number of characters consumed. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.emitNamedEntityData = function (result, valueLength, consumed) { - var decodeTree = this.decodeTree; - this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed); - if (valueLength === 3) { - // For multi-byte values, we need to emit the second byte. - this.emitCodePoint(decodeTree[result + 2], consumed); - } - return consumed; - }; - /** - * Signal to the parser that the end of the input was reached. - * - * Remaining data will be emitted and relevant errors will be produced. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.end = function () { - var _a; - switch (this.state) { - case EntityDecoderState.NamedEntity: - { - // Emit a named entity if we have one. - return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0; - } - // Otherwise, emit a numeric entity if we have one. - case EntityDecoderState.NumericDecimal: - { - return this.emitNumericEntity(0, 2); - } - case EntityDecoderState.NumericHex: - { - return this.emitNumericEntity(0, 3); - } - case EntityDecoderState.NumericStart: - { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - case EntityDecoderState.EntityStart: - { - // Return 0 if we have no entity. - return 0; + function $213e4d2df823067d$var$isIndeterminate(checked) { + return checked === "indeterminate"; } - } - }; - return EntityDecoder; -}(); -exports.EntityDecoder = EntityDecoder; -/** - * Creates a function that decodes entities in a string. - * - * @param decodeTree The decode tree. - * @returns A function that decodes entities in a string. - */ -function getDecoder(decodeTree) { - var ret = ""; - var decoder = new EntityDecoder(decodeTree, function (str) { - return ret += (0, decode_codepoint_js_1.fromCodePoint)(str); - }); - return function decodeWithTrie(str, decodeMode) { - var lastIndex = 0; - var offset = 0; - while ((offset = str.indexOf("&", offset)) >= 0) { - ret += str.slice(lastIndex, offset); - decoder.startEntity(decodeMode); - var len = decoder.write(str, - // Skip the "&" - offset + 1); - if (len < 0) { - lastIndex = offset + decoder.end(); - break; - } - lastIndex = offset + len; - // If `len` is 0, skip the current `&` and continue. - offset = len === 0 ? lastIndex + 1 : lastIndex; - } - var result = ret + str.slice(lastIndex); - // Make sure we don't keep a reference to the final string. - ret = ""; - return result; - }; -} -/** - * Determines the branch of the current node that is taken given the current - * character. This function is used to traverse the trie. - * - * @param decodeTree The trie. - * @param current The current node. - * @param nodeIdx The index right after the current node and its value. - * @param char The current character. - * @returns The index of the next node, or -1 if no branch is taken. - */ -function determineBranch(decodeTree, current, nodeIdx, char) { - var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; - var jumpOffset = current & BinTrieFlags.JUMP_TABLE; - // Case 1: Single branch encoded in jump offset - if (branchCount === 0) { - return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; - } - // Case 2: Multiple branches encoded in jump table - if (jumpOffset) { - var value = char - jumpOffset; - return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIdx + value] - 1; - } - // Case 3: Multiple branches encoded in dictionary - // Binary search for the character. - var lo = nodeIdx; - var hi = lo + branchCount - 1; - while (lo <= hi) { - var mid = lo + hi >>> 1; - var midVal = decodeTree[mid]; - if (midVal < char) { - lo = mid + 1; - } else if (midVal > char) { - hi = mid - 1; - } else { - return decodeTree[mid + branchCount]; - } - } - return -1; -} -exports.determineBranch = determineBranch; -var htmlDecoder = getDecoder(decode_data_html_js_1.default); -var xmlDecoder = getDecoder(decode_data_xml_js_1.default); -/** - * Decodes an HTML string. - * - * @param str The string to decode. - * @param mode The decoding mode. - * @returns The decoded string. - */ -function decodeHTML(str, mode) { - if (mode === void 0) { - mode = DecodingMode.Legacy; - } - return htmlDecoder(str, mode); -} -exports.decodeHTML = decodeHTML; -/** - * Decodes an HTML string in an attribute. - * - * @param str The string to decode. - * @returns The decoded string. - */ -function decodeHTMLAttribute(str) { - return htmlDecoder(str, DecodingMode.Attribute); -} -exports.decodeHTMLAttribute = decodeHTMLAttribute; -/** - * Decodes an HTML string, requiring all entities to be terminated by a semicolon. - * - * @param str The string to decode. - * @returns The decoded string. - */ -function decodeHTMLStrict(str) { - return htmlDecoder(str, DecodingMode.Strict); -} -exports.decodeHTMLStrict = decodeHTMLStrict; -/** - * Decodes an XML string, requiring all entities to be terminated by a semicolon. - * - * @param str The string to decode. - * @returns The decoded string. - */ -function decodeXML(str) { - return xmlDecoder(str, DecodingMode.Strict); -} -exports.decodeXML = decodeXML; - -/***/ }), - -/***/ "../../../node_modules/entities/lib/decode_codepoint.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/entities/lib/decode_codepoint.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 -var _a; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.replaceCodePoint = exports.fromCodePoint = void 0; -var decodeMap = new Map([[0, 65533], -// C1 Unicode control character reference replacements -[128, 8364], [130, 8218], [131, 402], [132, 8222], [133, 8230], [134, 8224], [135, 8225], [136, 710], [137, 8240], [138, 352], [139, 8249], [140, 338], [142, 381], [145, 8216], [146, 8217], [147, 8220], [148, 8221], [149, 8226], [150, 8211], [151, 8212], [152, 732], [153, 8482], [154, 353], [155, 8250], [156, 339], [158, 382], [159, 376]]); -/** - * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. - */ -exports.fromCodePoint = -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins -(_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) { - var output = ""; - if (codePoint > 0xffff) { - codePoint -= 0x10000; - output += String.fromCharCode(codePoint >>> 10 & 0x3ff | 0xd800); - codePoint = 0xdc00 | codePoint & 0x3ff; - } - output += String.fromCharCode(codePoint); - return output; -}; -/** - * Replace the given code point with a replacement character if it is a - * surrogate or is outside the valid range. Otherwise return the code - * point unchanged. - */ -function replaceCodePoint(codePoint) { - var _a; - if (codePoint >= 0xd800 && codePoint <= 0xdfff || codePoint > 0x10ffff) { - return 0xfffd; - } - return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; -} -exports.replaceCodePoint = replaceCodePoint; -/** - * Replace the code point if relevant, then convert it to a string. - * - * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. - * @param codePoint The code point to decode. - * @returns The decoded code point. - */ -function decodeCodePoint(codePoint) { - return (0, exports.fromCodePoint)(replaceCodePoint(codePoint)); -} -exports["default"] = decodeCodePoint; - -/***/ }), - -/***/ "../../../node_modules/entities/lib/encode.js": -/*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/encode.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -var __importDefault = void 0 && (void 0).__importDefault || function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; -}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.encodeNonAsciiHTML = exports.encodeHTML = void 0; -var encode_html_js_1 = __importDefault(__webpack_require__(/*! ./generated/encode-html.js */ "../../../node_modules/entities/lib/generated/encode-html.js")); -var escape_js_1 = __webpack_require__(/*! ./escape.js */ "../../../node_modules/entities/lib/escape.js"); -var htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g; -/** - * Encodes all characters in the input using HTML entities. This includes - * characters that are valid ASCII characters in HTML documents, such as `#`. - * - * To get a more compact output, consider using the `encodeNonAsciiHTML` - * function, which will only encode characters that are not valid in HTML - * documents, as well as non-ASCII characters. - * - * If a character has no equivalent entity, a numeric hexadecimal reference - * (eg. `ü`) will be used. - */ -function encodeHTML(data) { - return encodeHTMLTrieRe(htmlReplacer, data); -} -exports.encodeHTML = encodeHTML; -/** - * Encodes all non-ASCII characters, as well as characters not valid in HTML - * documents using HTML entities. This function will not encode characters that - * are valid in HTML documents, such as `#`. - * - * If a character has no equivalent entity, a numeric hexadecimal reference - * (eg. `ü`) will be used. - */ -function encodeNonAsciiHTML(data) { - return encodeHTMLTrieRe(escape_js_1.xmlReplacer, data); -} -exports.encodeNonAsciiHTML = encodeNonAsciiHTML; -function encodeHTMLTrieRe(regExp, str) { - var ret = ""; - var lastIdx = 0; - var match; - while ((match = regExp.exec(str)) !== null) { - var i = match.index; - ret += str.substring(lastIdx, i); - var char = str.charCodeAt(i); - var next = encode_html_js_1.default.get(char); - if (typeof next === "object") { - // We are in a branch. Try to match the next char. - if (i + 1 < str.length) { - var nextChar = str.charCodeAt(i + 1); - var value = typeof next.n === "number" ? next.n === nextChar ? next.o : undefined : next.n.get(nextChar); - if (value !== undefined) { - ret += value; - lastIdx = regExp.lastIndex += 1; - continue; + function $213e4d2df823067d$var$getCheckedState(checked) { + return $213e4d2df823067d$var$isIndeterminate(checked) + ? "indeterminate" + : checked + ? "checked" + : "unchecked"; } - } - next = next.v; - } - // We might have a tree node without a value; skip and use a numeric entity. - if (next !== undefined) { - ret += next; - lastIdx = i + 1; - } else { - var cp = (0, escape_js_1.getCodePoint)(str, i); - ret += "&#x".concat(cp.toString(16), ";"); - // Increase by 1 if we have a surrogate pair - lastIdx = regExp.lastIndex += Number(cp !== char); - } - } - return ret + str.substr(lastIdx); -} - -/***/ }), - -/***/ "../../../node_modules/entities/lib/escape.js": -/*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/escape.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.getCodePoint = exports.xmlReplacer = void 0; -exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g; -var xmlCodeMap = new Map([[34, """], [38, "&"], [39, "'"], [60, "<"], [62, ">"]]); -// For compatibility with node < 4, we wrap `codePointAt` -exports.getCodePoint = -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -String.prototype.codePointAt != null ? function (str, index) { - return str.codePointAt(index); -} : -// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae -function (c, index) { - return (c.charCodeAt(index) & 0xfc00) === 0xd800 ? (c.charCodeAt(index) - 0xd800) * 0x400 + c.charCodeAt(index + 1) - 0xdc00 + 0x10000 : c.charCodeAt(index); -}; -/** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using XML entities. - * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. - */ -function encodeXML(str) { - var ret = ""; - var lastIdx = 0; - var match; - while ((match = exports.xmlReplacer.exec(str)) !== null) { - var i = match.index; - var char = str.charCodeAt(i); - var next = xmlCodeMap.get(char); - if (next !== undefined) { - ret += str.substring(lastIdx, i) + next; - lastIdx = i + 1; - } else { - ret += "".concat(str.substring(lastIdx, i), "&#x").concat((0, exports.getCodePoint)(str, i).toString(16), ";"); - // Increase by 1 if we have a surrogate pair - lastIdx = exports.xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800); - } - } - return ret + str.substr(lastIdx); -} -exports.encodeXML = encodeXML; -/** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using numeric hexadecimal reference (eg. `ü`). - * - * Have a look at `escapeUTF8` if you want a more concise output at the expense - * of reduced transportability. - * - * @param data String to escape. - */ -exports.escape = encodeXML; -/** - * Creates a function that escapes all characters matched by the given regular - * expression using the given map of characters to escape to their entities. - * - * @param regex Regular expression to match characters to escape. - * @param map Map of characters to escape to their entities. - * - * @returns Function that escapes all characters matched by the given regular - * expression using the given map of characters to escape to their entities. - */ -function getEscaper(regex, map) { - return function escape(data) { - var match; - var lastIdx = 0; - var result = ""; - while (match = regex.exec(data)) { - if (lastIdx !== match.index) { - result += data.substring(lastIdx, match.index); - } - // We know that this character will be in the map. - result += map.get(match[0].charCodeAt(0)); - // Every match will be of length 1 - lastIdx = match.index + 1; - } - return result + data.substring(lastIdx); - }; -} -/** - * Encodes all characters not valid in XML documents using XML entities. - * - * Note that the output will be character-set dependent. - * - * @param data String to escape. - */ -exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap); -/** - * Encodes all characters that have to be escaped in HTML attributes, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - * - * @param data String to escape. - */ -exports.escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([[34, """], [38, "&"], [160, " "]])); -/** - * Encodes all characters that have to be escaped in HTML text, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - * - * @param data String to escape. - */ -exports.escapeText = getEscaper(/[&<>\u00A0]/g, new Map([[38, "&"], [60, "<"], [62, ">"], [160, " "]])); - -/***/ }), - -/***/ "../../../node_modules/entities/lib/generated/decode-data-html.js": -/*!************************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/decode-data-html.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -// Generated using scripts/write-decode-map.ts -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = new Uint16Array( -// prettier-ignore -"\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c".split("").map(function (c) { - return c.charCodeAt(0); -})); - -/***/ }), + function $213e4d2df823067d$var$focusFirst(candidates) { + const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; + for (const candidate of candidates) { + // if focus is already where we want to go, we don't want to keep going through the candidates + if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; + candidate.focus(); + if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; + } + } + /** + * Wraps an array around itself at a given start index + * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` + */ + function $213e4d2df823067d$var$wrapArray(array, startIndex) { + return array.map( + (_, index) => array[(startIndex + index) % array.length] + ); + } + /** + * This is the "meat" of the typeahead matching logic. It takes in all the values, + * the search and the current match, and returns the next match (or `undefined`). + * + * We normalize the search because if a user has repeatedly pressed a character, + * we want the exact same behavior as if we only had that one character + * (ie. cycle through options starting with that character) + * + * We also reorder the values by wrapping the array around the current match. + * This is so we always look forward from the current match, and picking the first + * match will always be the correct one. + * + * Finally, if the normalized search is exactly one character, we exclude the + * current match from the values because otherwise it would be the first to match always + * and focus would never move. This is as opposed to the regular case, where we + * don't want focus to move if the current match still matches. + */ + function $213e4d2df823067d$var$getNextMatch( + values, + search, + currentMatch + ) { + const isRepeated = + search.length > 1 && + Array.from(search).every((char) => char === search[0]); + const normalizedSearch = isRepeated ? search[0] : search; + const currentMatchIndex = currentMatch + ? values.indexOf(currentMatch) + : -1; + let wrappedValues = $213e4d2df823067d$var$wrapArray( + values, + Math.max(currentMatchIndex, 0) + ); + const excludeCurrentMatch = normalizedSearch.length === 1; + if (excludeCurrentMatch) + wrappedValues = wrappedValues.filter((v) => v !== currentMatch); + const nextMatch = wrappedValues.find((value) => + value.toLowerCase().startsWith(normalizedSearch.toLowerCase()) + ); + return nextMatch !== currentMatch ? nextMatch : undefined; + } + // Determine if a point is inside of a polygon. + // Based on https://github.com/substack/point-in-polygon + function $213e4d2df823067d$var$isPointInPolygon(point, polygon) { + const { x: x, y: y } = point; + let inside = false; + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const xi = polygon[i].x; + const yi = polygon[i].y; + const xj = polygon[j].x; + const yj = polygon[j].y; // prettier-ignore + const intersect = + yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi; + if (intersect) inside = !inside; + } + return inside; + } + function $213e4d2df823067d$var$isPointerInGraceArea(event, area) { + if (!area) return false; + const cursorPos = { + x: event.clientX, + y: event.clientY, + }; + return $213e4d2df823067d$var$isPointInPolygon(cursorPos, area); + } + function $213e4d2df823067d$var$whenMouse(handler) { + return (event) => + event.pointerType === "mouse" ? handler(event) : undefined; + } + const $213e4d2df823067d$export$be92b6f5f03c0fe9 = + $213e4d2df823067d$export$d9b273488cd8ce6f; + const $213e4d2df823067d$export$b688253958b8dfe7 = + $213e4d2df823067d$export$9fa5ebd18bee4d43; + const $213e4d2df823067d$export$602eac185826482c = + $213e4d2df823067d$export$793392f970497feb; + const $213e4d2df823067d$export$7c6e2c02157bb7d2 = + $213e4d2df823067d$export$479f0f2f71193efe; + const $213e4d2df823067d$export$eb2fcfdbd7ba97d4 = + $213e4d2df823067d$export$22a631d1f72787bb; + const $213e4d2df823067d$export$b04be29aa201d4f5 = + $213e4d2df823067d$export$dd37bec0e8a99143; + const $213e4d2df823067d$export$6d08773d2e66f8f2 = + $213e4d2df823067d$export$2ce376c2cc3355c8; + const $213e4d2df823067d$export$16ce288f89fa631c = + $213e4d2df823067d$export$f6f243521332502d; + const $213e4d2df823067d$export$a98f0dcb43a68a25 = + $213e4d2df823067d$export$ea2200c9eee416b3; + const $213e4d2df823067d$export$371ab307eab489c0 = + $213e4d2df823067d$export$69bd225e9817f6d0; + const $213e4d2df823067d$export$c3468e2714d175fa = + $213e4d2df823067d$export$a2593e23056970a3; + const $213e4d2df823067d$export$1ff3c3f08ae963c0 = + $213e4d2df823067d$export$1cec7dcdd713e220; + const $213e4d2df823067d$export$21b07c8f274aebd5 = + $213e4d2df823067d$export$bcdda4773debf5fa; + const $213e4d2df823067d$export$d7a01e11500dfb6f = + $213e4d2df823067d$export$71bdb9d1e2909932; + const $213e4d2df823067d$export$2ea8a7a591ac5eac = + $213e4d2df823067d$export$5fbbb3ba7297405f; + const $213e4d2df823067d$export$6d4de93b380beddf = + $213e4d2df823067d$export$e7142ab31822bde6; + + /***/ + }, -/***/ "../../../node_modules/entities/lib/generated/decode-data-xml.js": -/*!***********************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/decode-data-xml.js ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ "../../../node_modules/@radix-ui/react-popper/dist/index.js": + /*!******************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-popper/dist/index.js ***! + \******************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $50Iv9$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $50Iv9$react = __webpack_require__(/*! react */ "react"); + var $50Iv9$floatinguireactdom = __webpack_require__( + /*! @floating-ui/react-dom */ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js" + ); + var $50Iv9$radixuireactarrow = __webpack_require__( + /*! @radix-ui/react-arrow */ "../../../node_modules/@radix-ui/react-arrow/dist/index.js" + ); + var $50Iv9$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $50Iv9$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $50Iv9$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $50Iv9$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + var $50Iv9$radixuireactuselayouteffect = __webpack_require__( + /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" + ); + var $50Iv9$radixuireactusesize = __webpack_require__( + /*! @radix-ui/react-use-size */ "../../../node_modules/@radix-ui/react-use-size/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "createPopperScope", + () => $34310caa050a8d63$export$722aac194ae923 + ); + $parcel$export( + module.exports, + "Popper", + () => $34310caa050a8d63$export$badac9ada3a0bdf9 + ); + $parcel$export( + module.exports, + "PopperAnchor", + () => $34310caa050a8d63$export$ecd4e1ccab6ed6d + ); + $parcel$export( + module.exports, + "PopperContent", + () => $34310caa050a8d63$export$bc4ae5855d3c4fc + ); + $parcel$export( + module.exports, + "PopperArrow", + () => $34310caa050a8d63$export$79d62cd4e10a3fd0 + ); + $parcel$export( + module.exports, + "Root", + () => $34310caa050a8d63$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Anchor", + () => $34310caa050a8d63$export$b688253958b8dfe7 + ); + $parcel$export( + module.exports, + "Content", + () => $34310caa050a8d63$export$7c6e2c02157bb7d2 + ); + $parcel$export( + module.exports, + "Arrow", + () => $34310caa050a8d63$export$21b07c8f274aebd5 + ); + $parcel$export( + module.exports, + "SIDE_OPTIONS", + () => $34310caa050a8d63$export$36f0086da09c4b9f + ); + $parcel$export( + module.exports, + "ALIGN_OPTIONS", + () => $34310caa050a8d63$export$3671ffab7b302fc9 + ); + const $34310caa050a8d63$export$36f0086da09c4b9f = [ + "top", + "right", + "bottom", + "left", + ]; + const $34310caa050a8d63$export$3671ffab7b302fc9 = [ + "start", + "center", + "end", + ]; + /* ------------------------------------------------------------------------------------------------- + * Popper + * -----------------------------------------------------------------------------------------------*/ + const $34310caa050a8d63$var$POPPER_NAME = "Popper"; + const [ + $34310caa050a8d63$var$createPopperContext, + $34310caa050a8d63$export$722aac194ae923, + ] = $50Iv9$radixuireactcontext.createContextScope( + $34310caa050a8d63$var$POPPER_NAME + ); + const [ + $34310caa050a8d63$var$PopperProvider, + $34310caa050a8d63$var$usePopperContext, + ] = $34310caa050a8d63$var$createPopperContext( + $34310caa050a8d63$var$POPPER_NAME + ); + const $34310caa050a8d63$export$badac9ada3a0bdf9 = (props) => { + const { __scopePopper: __scopePopper, children: children } = props; + const [anchor, setAnchor] = $50Iv9$react.useState(null); + return /*#__PURE__*/ $50Iv9$react.createElement( + $34310caa050a8d63$var$PopperProvider, + { + scope: __scopePopper, + anchor: anchor, + onAnchorChange: setAnchor, + }, + children + ); + }; + /*#__PURE__*/ + Object.assign($34310caa050a8d63$export$badac9ada3a0bdf9, { + displayName: $34310caa050a8d63$var$POPPER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * PopperAnchor + * -----------------------------------------------------------------------------------------------*/ + const $34310caa050a8d63$var$ANCHOR_NAME = "PopperAnchor"; + const $34310caa050a8d63$export$ecd4e1ccab6ed6d = + /*#__PURE__*/ $50Iv9$react.forwardRef((props, forwardedRef) => { + const { + __scopePopper: __scopePopper, + virtualRef: virtualRef, + ...anchorProps + } = props; + const context = $34310caa050a8d63$var$usePopperContext( + $34310caa050a8d63$var$ANCHOR_NAME, + __scopePopper + ); + const ref = $50Iv9$react.useRef(null); + const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + $50Iv9$react.useEffect(() => { + // Consumer can anchor the popper to something that isn't + // a DOM node e.g. pointer position, so we override the + // `anchorRef` with their virtual ref in this case. + context.onAnchorChange( + (virtualRef === null || virtualRef === void 0 + ? void 0 + : virtualRef.current) || ref.current + ); + }); + return virtualRef + ? null + : /*#__PURE__*/ $50Iv9$react.createElement( + $50Iv9$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($50Iv9$babelruntimehelpersextends)( + {}, + anchorProps, + { + ref: composedRefs, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($34310caa050a8d63$export$ecd4e1ccab6ed6d, { + displayName: $34310caa050a8d63$var$ANCHOR_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * PopperContent + * -----------------------------------------------------------------------------------------------*/ + const $34310caa050a8d63$var$CONTENT_NAME = "PopperContent"; + const [ + $34310caa050a8d63$var$PopperContentProvider, + $34310caa050a8d63$var$useContentContext, + ] = $34310caa050a8d63$var$createPopperContext( + $34310caa050a8d63$var$CONTENT_NAME + ); + const $34310caa050a8d63$export$bc4ae5855d3c4fc = + /*#__PURE__*/ $50Iv9$react.forwardRef((props, forwardedRef) => { + var _arrowSize$width, + _arrowSize$height, + _middlewareData$arrow, + _middlewareData$arrow2, + _middlewareData$arrow3, + _middlewareData$trans, + _middlewareData$trans2, + _middlewareData$hide; + const { + __scopePopper: __scopePopper, + side = "bottom", + sideOffset = 0, + align = "center", + alignOffset = 0, + arrowPadding = 0, + collisionBoundary = [], + collisionPadding: collisionPaddingProp = 0, + sticky = "partial", + hideWhenDetached = false, + avoidCollisions = true, + onPlaced: onPlaced, + ...contentProps + } = props; + const context = $34310caa050a8d63$var$usePopperContext( + $34310caa050a8d63$var$CONTENT_NAME, + __scopePopper + ); + const [content, setContent] = $50Iv9$react.useState(null); + const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + (node) => setContent(node) + ); + const [arrow, setArrow] = $50Iv9$react.useState(null); + const arrowSize = $50Iv9$radixuireactusesize.useSize(arrow); + const arrowWidth = + (_arrowSize$width = + arrowSize === null || arrowSize === void 0 + ? void 0 + : arrowSize.width) !== null && _arrowSize$width !== void 0 + ? _arrowSize$width + : 0; + const arrowHeight = + (_arrowSize$height = + arrowSize === null || arrowSize === void 0 + ? void 0 + : arrowSize.height) !== null && _arrowSize$height !== void 0 + ? _arrowSize$height + : 0; + const desiredPlacement = + side + (align !== "center" ? "-" + align : ""); + const collisionPadding = + typeof collisionPaddingProp === "number" + ? collisionPaddingProp + : { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...collisionPaddingProp, + }; + const boundary = Array.isArray(collisionBoundary) + ? collisionBoundary + : [collisionBoundary]; + const hasExplicitBoundaries = boundary.length > 0; + const detectOverflowOptions = { + padding: collisionPadding, + boundary: boundary.filter($34310caa050a8d63$var$isNotNull), + // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries + altBoundary: hasExplicitBoundaries, + }; + const { + refs: refs, + floatingStyles: floatingStyles, + placement: placement, + isPositioned: isPositioned, + middlewareData: middlewareData, + } = $50Iv9$floatinguireactdom.useFloating({ + // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues + strategy: "fixed", + placement: desiredPlacement, + whileElementsMounted: $50Iv9$floatinguireactdom.autoUpdate, + elements: { + reference: context.anchor, + }, + middleware: [ + $50Iv9$floatinguireactdom.offset({ + mainAxis: sideOffset + arrowHeight, + alignmentAxis: alignOffset, + }), + avoidCollisions && + $50Iv9$floatinguireactdom.shift({ + mainAxis: true, + crossAxis: false, + limiter: + sticky === "partial" + ? $50Iv9$floatinguireactdom.limitShift() + : undefined, + ...detectOverflowOptions, + }), + avoidCollisions && + $50Iv9$floatinguireactdom.flip({ + ...detectOverflowOptions, + }), + $50Iv9$floatinguireactdom.size({ + ...detectOverflowOptions, + apply: ({ + elements: elements, + rects: rects, + availableWidth: availableWidth, + availableHeight: availableHeight, + }) => { + const { width: anchorWidth, height: anchorHeight } = + rects.reference; + const contentStyle = elements.floating.style; + contentStyle.setProperty( + "--radix-popper-available-width", + `${availableWidth}px` + ); + contentStyle.setProperty( + "--radix-popper-available-height", + `${availableHeight}px` + ); + contentStyle.setProperty( + "--radix-popper-anchor-width", + `${anchorWidth}px` + ); + contentStyle.setProperty( + "--radix-popper-anchor-height", + `${anchorHeight}px` + ); + }, + }), + arrow && + $50Iv9$floatinguireactdom.arrow({ + element: arrow, + padding: arrowPadding, + }), + $34310caa050a8d63$var$transformOrigin({ + arrowWidth: arrowWidth, + arrowHeight: arrowHeight, + }), + hideWhenDetached && + $50Iv9$floatinguireactdom.hide({ + strategy: "referenceHidden", + }), + ], + }); + const [placedSide, placedAlign] = + $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); + const handlePlaced = + $50Iv9$radixuireactusecallbackref.useCallbackRef(onPlaced); + $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { + if (isPositioned) + handlePlaced === null || + handlePlaced === void 0 || + handlePlaced(); + }, [isPositioned, handlePlaced]); + const arrowX = + (_middlewareData$arrow = middlewareData.arrow) === null || + _middlewareData$arrow === void 0 + ? void 0 + : _middlewareData$arrow.x; + const arrowY = + (_middlewareData$arrow2 = middlewareData.arrow) === null || + _middlewareData$arrow2 === void 0 + ? void 0 + : _middlewareData$arrow2.y; + const cannotCenterArrow = + ((_middlewareData$arrow3 = middlewareData.arrow) === null || + _middlewareData$arrow3 === void 0 + ? void 0 + : _middlewareData$arrow3.centerOffset) !== 0; + const [contentZIndex, setContentZIndex] = $50Iv9$react.useState(); + $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { + if (content) + setContentZIndex(window.getComputedStyle(content).zIndex); + }, [content]); + return /*#__PURE__*/ $50Iv9$react.createElement( + "div", + { + ref: refs.setFloating, + "data-radix-popper-content-wrapper": "", + style: { + ...floatingStyles, + transform: isPositioned + ? floatingStyles.transform + : "translate(0, -200%)", + // keep off the page when measuring + minWidth: "max-content", + zIndex: contentZIndex, + ["--radix-popper-transform-origin"]: [ + (_middlewareData$trans = middlewareData.transformOrigin) === + null || _middlewareData$trans === void 0 + ? void 0 + : _middlewareData$trans.x, + (_middlewareData$trans2 = + middlewareData.transformOrigin) === null || + _middlewareData$trans2 === void 0 + ? void 0 + : _middlewareData$trans2.y, + ].join(" "), + }, // Floating UI interally calculates logical alignment based the `dir` attribute on + dir: props.dir, + }, + /*#__PURE__*/ $50Iv9$react.createElement( + $34310caa050a8d63$var$PopperContentProvider, + { + scope: __scopePopper, + placedSide: placedSide, + onArrowChange: setArrow, + arrowX: arrowX, + arrowY: arrowY, + shouldHideArrow: cannotCenterArrow, + }, + /*#__PURE__*/ $50Iv9$react.createElement( + $50Iv9$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($50Iv9$babelruntimehelpersextends)( + { + "data-side": placedSide, + "data-align": placedAlign, + }, + contentProps, + { + ref: composedRefs, + style: { + ...contentProps.style, + // if the PopperContent hasn't been placed yet (not all measurements done) + // we prevent animations so that users's animation don't kick in too early referring wrong sides + animation: !isPositioned ? "none" : undefined, + // hide the content if using the hide middleware and should be hidden + opacity: + (_middlewareData$hide = middlewareData.hide) !== + null && + _middlewareData$hide !== void 0 && + _middlewareData$hide.referenceHidden + ? 0 + : undefined, + }, + } + ) + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($34310caa050a8d63$export$bc4ae5855d3c4fc, { + displayName: $34310caa050a8d63$var$CONTENT_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * PopperArrow + * -----------------------------------------------------------------------------------------------*/ + const $34310caa050a8d63$var$ARROW_NAME = "PopperArrow"; + const $34310caa050a8d63$var$OPPOSITE_SIDE = { + top: "bottom", + right: "left", + bottom: "top", + left: "right", + }; + const $34310caa050a8d63$export$79d62cd4e10a3fd0 = + /*#__PURE__*/ $50Iv9$react.forwardRef( + function $34310caa050a8d63$export$79d62cd4e10a3fd0( + props, + forwardedRef + ) { + const { __scopePopper: __scopePopper, ...arrowProps } = props; + const contentContext = $34310caa050a8d63$var$useContentContext( + $34310caa050a8d63$var$ARROW_NAME, + __scopePopper + ); + const baseSide = + $34310caa050a8d63$var$OPPOSITE_SIDE[contentContext.placedSide]; + return ( + /*#__PURE__*/ // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`) + // doesn't report size as we'd expect on SVG elements. + // it reports their bounding box which is effectively the largest path inside the SVG. + $50Iv9$react.createElement( + "span", + { + ref: contentContext.onArrowChange, + style: { + position: "absolute", + left: contentContext.arrowX, + top: contentContext.arrowY, + [baseSide]: 0, + transformOrigin: { + top: "", + right: "0 0", + bottom: "center 0", + left: "100% 0", + }[contentContext.placedSide], + transform: { + top: "translateY(100%)", + right: "translateY(50%) rotate(90deg) translateX(-50%)", + bottom: `rotate(180deg)`, + left: "translateY(50%) rotate(-90deg) translateX(50%)", + }[contentContext.placedSide], + visibility: contentContext.shouldHideArrow + ? "hidden" + : undefined, + }, + }, + /*#__PURE__*/ $50Iv9$react.createElement( + $50Iv9$radixuireactarrow.Root, + $parcel$interopDefault($50Iv9$babelruntimehelpersextends)( + {}, + arrowProps, + { + ref: forwardedRef, + style: { + ...arrowProps.style, + // ensures the element can be measured correctly (mostly for if SVG) + display: "block", + }, + } + ) + ) + ) + ); + } + ); + /*#__PURE__*/ + Object.assign($34310caa050a8d63$export$79d62cd4e10a3fd0, { + displayName: $34310caa050a8d63$var$ARROW_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + function $34310caa050a8d63$var$isNotNull(value) { + return value !== null; + } + const $34310caa050a8d63$var$transformOrigin = (options) => ({ + name: "transformOrigin", + options: options, + fn(data) { + var _middlewareData$arrow4, + _middlewareData$arrow5, + _middlewareData$arrow6, + _middlewareData$arrow7, + _middlewareData$arrow8; + const { + placement: placement, + rects: rects, + middlewareData: middlewareData, + } = data; + const cannotCenterArrow = + ((_middlewareData$arrow4 = middlewareData.arrow) === null || + _middlewareData$arrow4 === void 0 + ? void 0 + : _middlewareData$arrow4.centerOffset) !== 0; + const isArrowHidden = cannotCenterArrow; + const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; + const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; + const [placedSide, placedAlign] = + $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); + const noArrowAlign = { + start: "0%", + center: "50%", + end: "100%", + }[placedAlign]; + const arrowXCenter = + ((_middlewareData$arrow5 = + (_middlewareData$arrow6 = middlewareData.arrow) === null || + _middlewareData$arrow6 === void 0 + ? void 0 + : _middlewareData$arrow6.x) !== null && + _middlewareData$arrow5 !== void 0 + ? _middlewareData$arrow5 + : 0) + + arrowWidth / 2; + const arrowYCenter = + ((_middlewareData$arrow7 = + (_middlewareData$arrow8 = middlewareData.arrow) === null || + _middlewareData$arrow8 === void 0 + ? void 0 + : _middlewareData$arrow8.y) !== null && + _middlewareData$arrow7 !== void 0 + ? _middlewareData$arrow7 + : 0) + + arrowHeight / 2; + let x = ""; + let y = ""; + if (placedSide === "bottom") { + x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; + y = `${-arrowHeight}px`; + } else if (placedSide === "top") { + x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; + y = `${rects.floating.height + arrowHeight}px`; + } else if (placedSide === "right") { + x = `${-arrowHeight}px`; + y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; + } else if (placedSide === "left") { + x = `${rects.floating.width + arrowHeight}px`; + y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; + } + return { + data: { + x: x, + y: y, + }, + }; + }, + }); + function $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement) { + const [side, align = "center"] = placement.split("-"); + return [side, align]; + } + const $34310caa050a8d63$export$be92b6f5f03c0fe9 = + $34310caa050a8d63$export$badac9ada3a0bdf9; + const $34310caa050a8d63$export$b688253958b8dfe7 = + $34310caa050a8d63$export$ecd4e1ccab6ed6d; + const $34310caa050a8d63$export$7c6e2c02157bb7d2 = + $34310caa050a8d63$export$bc4ae5855d3c4fc; + const $34310caa050a8d63$export$21b07c8f274aebd5 = + $34310caa050a8d63$export$79d62cd4e10a3fd0; + + /***/ + }, + /***/ "../../../node_modules/@radix-ui/react-portal/dist/index.js": + /*!******************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-portal/dist/index.js ***! + \******************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $amzHf$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $amzHf$react = __webpack_require__(/*! react */ "react"); + var $amzHf$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); + var $amzHf$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "Portal", + () => $913a70b877676c16$export$602eac185826482c + ); + $parcel$export( + module.exports, + "Root", + () => $913a70b877676c16$export$be92b6f5f03c0fe9 + ); + /* ------------------------------------------------------------------------------------------------- + * Portal + * -----------------------------------------------------------------------------------------------*/ + const $913a70b877676c16$var$PORTAL_NAME = "Portal"; + const $913a70b877676c16$export$602eac185826482c = + /*#__PURE__*/ $amzHf$react.forwardRef((props, forwardedRef) => { + var _globalThis$document; + const { + container = globalThis === null || globalThis === void 0 + ? void 0 + : (_globalThis$document = globalThis.document) === null || + _globalThis$document === void 0 + ? void 0 + : _globalThis$document.body, + ...portalProps + } = props; + return container + ? /*#__PURE__*/ $parcel$interopDefault( + $amzHf$reactdom + ).createPortal( + /*#__PURE__*/ $amzHf$react.createElement( + $amzHf$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($amzHf$babelruntimehelpersextends)( + {}, + portalProps, + { + ref: forwardedRef, + } + ) + ), + container + ) + : null; + }); + /*#__PURE__*/ + Object.assign($913a70b877676c16$export$602eac185826482c, { + displayName: $913a70b877676c16$var$PORTAL_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + const $913a70b877676c16$export$be92b6f5f03c0fe9 = + $913a70b877676c16$export$602eac185826482c; -// Generated using scripts/write-decode-map.ts -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = new Uint16Array( -// prettier-ignore -"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022".split("").map(function (c) { - return c.charCodeAt(0); -})); + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@radix-ui/react-presence/dist/index.js": + /*!********************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-presence/dist/index.js ***! + \********************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $fnLeV$react = __webpack_require__(/*! react */ "react"); + var $fnLeV$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); + var $fnLeV$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $fnLeV$radixuireactuselayouteffect = __webpack_require__( + /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "Presence", + () => $a2fa0214bb2735a1$export$99c2b779aa4e8b8b + ); + function $8f63844556d0d3cd$export$3e6543de14f8614f( + initialState, + machine + ) { + return $fnLeV$react.useReducer((state, event) => { + const nextState = machine[state][event]; + return nextState !== null && nextState !== void 0 + ? nextState + : state; + }, initialState); + } + const $a2fa0214bb2735a1$export$99c2b779aa4e8b8b = (props) => { + const { present: present, children: children } = props; + const presence = $a2fa0214bb2735a1$var$usePresence(present); + const child = + typeof children === "function" + ? children({ + present: presence.isPresent, + }) + : $fnLeV$react.Children.only(children); + const ref = $fnLeV$radixuireactcomposerefs.useComposedRefs( + presence.ref, + child.ref + ); + const forceMount = typeof children === "function"; + return forceMount || presence.isPresent + ? /*#__PURE__*/ $fnLeV$react.cloneElement(child, { + ref: ref, + }) + : null; + }; + $a2fa0214bb2735a1$export$99c2b779aa4e8b8b.displayName = "Presence"; + /* ------------------------------------------------------------------------------------------------- + * usePresence + * -----------------------------------------------------------------------------------------------*/ + function $a2fa0214bb2735a1$var$usePresence(present) { + const [node1, setNode] = $fnLeV$react.useState(); + const stylesRef = $fnLeV$react.useRef({}); + const prevPresentRef = $fnLeV$react.useRef(present); + const prevAnimationNameRef = $fnLeV$react.useRef("none"); + const initialState = present ? "mounted" : "unmounted"; + const [state, send] = $8f63844556d0d3cd$export$3e6543de14f8614f( + initialState, + { + mounted: { + UNMOUNT: "unmounted", + ANIMATION_OUT: "unmountSuspended", + }, + unmountSuspended: { + MOUNT: "mounted", + ANIMATION_END: "unmounted", + }, + unmounted: { + MOUNT: "mounted", + }, + } + ); + $fnLeV$react.useEffect(() => { + const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName( + stylesRef.current + ); + prevAnimationNameRef.current = + state === "mounted" ? currentAnimationName : "none"; + }, [state]); + $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { + const styles = stylesRef.current; + const wasPresent = prevPresentRef.current; + const hasPresentChanged = wasPresent !== present; + if (hasPresentChanged) { + const prevAnimationName = prevAnimationNameRef.current; + const currentAnimationName = + $a2fa0214bb2735a1$var$getAnimationName(styles); + if (present) send("MOUNT"); + else if ( + currentAnimationName === "none" || + (styles === null || styles === void 0 + ? void 0 + : styles.display) === "none" + ) + // If there is no exit animation or the element is hidden, animations won't run + // so we unmount instantly + send("UNMOUNT"); + else { + /** + * When `present` changes to `false`, we check changes to animation-name to + * determine whether an animation has started. We chose this approach (reading + * computed styles) because there is no `animationrun` event and `animationstart` + * fires after `animation-delay` has expired which would be too late. + */ + const isAnimating = prevAnimationName !== currentAnimationName; + if (wasPresent && isAnimating) send("ANIMATION_OUT"); + else send("UNMOUNT"); + } + prevPresentRef.current = present; + } + }, [present, send]); + $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { + if (node1) { + /** + * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel` + * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we + * make sure we only trigger ANIMATION_END for the currently active animation. + */ + const handleAnimationEnd = (event) => { + const currentAnimationName = + $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); + const isCurrentAnimation = currentAnimationName.includes( + event.animationName + ); + if (event.target === node1 && isCurrentAnimation) + // With React 18 concurrency this update is applied + // a frame after the animation ends, creating a flash of visible content. + // By manually flushing we ensure they sync within a frame, removing the flash. + $fnLeV$reactdom.flushSync(() => send("ANIMATION_END")); + }; + const handleAnimationStart = (event) => { + if (event.target === node1) + // if animation occurred, store its name as the previous animation. + prevAnimationNameRef.current = + $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); + }; + node1.addEventListener("animationstart", handleAnimationStart); + node1.addEventListener("animationcancel", handleAnimationEnd); + node1.addEventListener("animationend", handleAnimationEnd); + return () => { + node1.removeEventListener( + "animationstart", + handleAnimationStart + ); + node1.removeEventListener( + "animationcancel", + handleAnimationEnd + ); + node1.removeEventListener("animationend", handleAnimationEnd); + }; + } + // Transition to the unmounted state if the node is removed prematurely. + // We avoid doing so during cleanup as the node may change but still exist. + else send("ANIMATION_END"); + }, [node1, send]); + return { + isPresent: ["mounted", "unmountSuspended"].includes(state), + ref: $fnLeV$react.useCallback((node) => { + if (node) stylesRef.current = getComputedStyle(node); + setNode(node); + }, []), + }; + } + /* -----------------------------------------------------------------------------------------------*/ + function $a2fa0214bb2735a1$var$getAnimationName(styles) { + return ( + (styles === null || styles === void 0 + ? void 0 + : styles.animationName) || "none" + ); + } -/***/ "../../../node_modules/entities/lib/generated/encode-html.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/encode-html.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ + }, + /***/ "../../../node_modules/@radix-ui/react-primitive/dist/index.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-primitive/dist/index.js ***! + \*********************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $iMixA$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $iMixA$react = __webpack_require__(/*! react */ "react"); + var $iMixA$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); + var $iMixA$radixuireactslot = __webpack_require__( + /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "Primitive", + () => $c3def6332c2749a6$export$250ffa63cdc0d034 + ); + $parcel$export( + module.exports, + "Root", + () => $c3def6332c2749a6$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "dispatchDiscreteCustomEvent", + () => $c3def6332c2749a6$export$6d1a0317bde7de7f + ); + const $c3def6332c2749a6$var$NODES = [ + "a", + "button", + "div", + "form", + "h2", + "h3", + "img", + "input", + "label", + "li", + "nav", + "ol", + "p", + "span", + "svg", + "ul", + ]; // Temporary while we await merge of this fix: + // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/55396 + // prettier-ignore + /* ------------------------------------------------------------------------------------------------- + * Primitive + * -----------------------------------------------------------------------------------------------*/ + const $c3def6332c2749a6$export$250ffa63cdc0d034 = $c3def6332c2749a6$var$NODES.reduce((primitive, node) => { + const Node = /*#__PURE__*/$iMixA$react.forwardRef((props, forwardedRef) => { + const { + asChild: asChild, + ...primitiveProps + } = props; + const Comp = asChild ? $iMixA$radixuireactslot.Slot : node; + $iMixA$react.useEffect(() => { + window[Symbol.for('radix-ui')] = true; + }, []); + return /*#__PURE__*/$iMixA$react.createElement(Comp, $parcel$interopDefault($iMixA$babelruntimehelpersextends)({}, primitiveProps, { + ref: forwardedRef + })); + }); + Node.displayName = `Primitive.${node}`; + return { + ...primitive, + [node]: Node + }; +}, {}); + /* ------------------------------------------------------------------------------------------------- + * Utils + * -----------------------------------------------------------------------------------------------*/ /** + * Flush custom event dispatch + * https://github.com/radix-ui/primitives/pull/1378 + * + * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types. + * + * Internally, React prioritises events in the following order: + * - discrete + * - continuous + * - default + * + * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350 + * + * `discrete` is an important distinction as updates within these events are applied immediately. + * React however, is not able to infer the priority of custom event types due to how they are detected internally. + * Because of this, it's possible for updates from custom events to be unexpectedly batched when + * dispatched by another `discrete` event. + * + * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch. + * This utility should be used when dispatching a custom event from within another `discrete` event, this utility + * is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event. + * For example: + * + * dispatching a known click 👎 + * target.dispatchEvent(new Event(‘click’)) + * + * dispatching a custom type within a non-discrete event 👎 + * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(‘customType’))} + * + * dispatching a custom type within a `discrete` event 👍 + * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(‘customType’))} + * + * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use + * this utility with them. This is because it's possible for those handlers to be called implicitly during render + * e.g. when focus is within a component as it is unmounted, or when managing focus on mount. + */ + function $c3def6332c2749a6$export$6d1a0317bde7de7f(target, event) { + if (target) + $iMixA$reactdom.flushSync(() => target.dispatchEvent(event)); + } + /* -----------------------------------------------------------------------------------------------*/ + const $c3def6332c2749a6$export$be92b6f5f03c0fe9 = + $c3def6332c2749a6$export$250ffa63cdc0d034; + /***/ + }, -// Generated using scripts/write-encode-map.ts -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -function restoreDiff(arr) { - for (var i = 1; i < arr.length; i++) { - arr[i][0] += arr[i - 1][0] + 1; - } - return arr; -} -// prettier-ignore -exports["default"] = new Map( /* #__PURE__ */restoreDiff([[9, " "], [0, " "], [22, "!"], [0, """], [0, "#"], [0, "$"], [0, "%"], [0, "&"], [0, "'"], [0, "("], [0, ")"], [0, "*"], [0, "+"], [0, ","], [1, "."], [0, "/"], [10, ":"], [0, ";"], [0, { - v: "<", - n: 8402, - o: "<⃒" -}], [0, { - v: "=", - n: 8421, - o: "=⃥" -}], [0, { - v: ">", - n: 8402, - o: ">⃒" -}], [0, "?"], [0, "@"], [26, "["], [0, "\"], [0, "]"], [0, "^"], [0, "_"], [0, "`"], [5, { - n: 106, - o: "fj" -}], [20, "{"], [0, "|"], [0, "}"], [34, " "], [0, "¡"], [0, "¢"], [0, "£"], [0, "¤"], [0, "¥"], [0, "¦"], [0, "§"], [0, "¨"], [0, "©"], [0, "ª"], [0, "«"], [0, "¬"], [0, "­"], [0, "®"], [0, "¯"], [0, "°"], [0, "±"], [0, "²"], [0, "³"], [0, "´"], [0, "µ"], [0, "¶"], [0, "·"], [0, "¸"], [0, "¹"], [0, "º"], [0, "»"], [0, "¼"], [0, "½"], [0, "¾"], [0, "¿"], [0, "À"], [0, "Á"], [0, "Â"], [0, "Ã"], [0, "Ä"], [0, "Å"], [0, "Æ"], [0, "Ç"], [0, "È"], [0, "É"], [0, "Ê"], [0, "Ë"], [0, "Ì"], [0, "Í"], [0, "Î"], [0, "Ï"], [0, "Ð"], [0, "Ñ"], [0, "Ò"], [0, "Ó"], [0, "Ô"], [0, "Õ"], [0, "Ö"], [0, "×"], [0, "Ø"], [0, "Ù"], [0, "Ú"], [0, "Û"], [0, "Ü"], [0, "Ý"], [0, "Þ"], [0, "ß"], [0, "à"], [0, "á"], [0, "â"], [0, "ã"], [0, "ä"], [0, "å"], [0, "æ"], [0, "ç"], [0, "è"], [0, "é"], [0, "ê"], [0, "ë"], [0, "ì"], [0, "í"], [0, "î"], [0, "ï"], [0, "ð"], [0, "ñ"], [0, "ò"], [0, "ó"], [0, "ô"], [0, "õ"], [0, "ö"], [0, "÷"], [0, "ø"], [0, "ù"], [0, "ú"], [0, "û"], [0, "ü"], [0, "ý"], [0, "þ"], [0, "ÿ"], [0, "Ā"], [0, "ā"], [0, "Ă"], [0, "ă"], [0, "Ą"], [0, "ą"], [0, "Ć"], [0, "ć"], [0, "Ĉ"], [0, "ĉ"], [0, "Ċ"], [0, "ċ"], [0, "Č"], [0, "č"], [0, "Ď"], [0, "ď"], [0, "Đ"], [0, "đ"], [0, "Ē"], [0, "ē"], [2, "Ė"], [0, "ė"], [0, "Ę"], [0, "ę"], [0, "Ě"], [0, "ě"], [0, "Ĝ"], [0, "ĝ"], [0, "Ğ"], [0, "ğ"], [0, "Ġ"], [0, "ġ"], [0, "Ģ"], [1, "Ĥ"], [0, "ĥ"], [0, "Ħ"], [0, "ħ"], [0, "Ĩ"], [0, "ĩ"], [0, "Ī"], [0, "ī"], [2, "Į"], [0, "į"], [0, "İ"], [0, "ı"], [0, "IJ"], [0, "ij"], [0, "Ĵ"], [0, "ĵ"], [0, "Ķ"], [0, "ķ"], [0, "ĸ"], [0, "Ĺ"], [0, "ĺ"], [0, "Ļ"], [0, "ļ"], [0, "Ľ"], [0, "ľ"], [0, "Ŀ"], [0, "ŀ"], [0, "Ł"], [0, "ł"], [0, "Ń"], [0, "ń"], [0, "Ņ"], [0, "ņ"], [0, "Ň"], [0, "ň"], [0, "ʼn"], [0, "Ŋ"], [0, "ŋ"], [0, "Ō"], [0, "ō"], [2, "Ő"], [0, "ő"], [0, "Œ"], [0, "œ"], [0, "Ŕ"], [0, "ŕ"], [0, "Ŗ"], [0, "ŗ"], [0, "Ř"], [0, "ř"], [0, "Ś"], [0, "ś"], [0, "Ŝ"], [0, "ŝ"], [0, "Ş"], [0, "ş"], [0, "Š"], [0, "š"], [0, "Ţ"], [0, "ţ"], [0, "Ť"], [0, "ť"], [0, "Ŧ"], [0, "ŧ"], [0, "Ũ"], [0, "ũ"], [0, "Ū"], [0, "ū"], [0, "Ŭ"], [0, "ŭ"], [0, "Ů"], [0, "ů"], [0, "Ű"], [0, "ű"], [0, "Ų"], [0, "ų"], [0, "Ŵ"], [0, "ŵ"], [0, "Ŷ"], [0, "ŷ"], [0, "Ÿ"], [0, "Ź"], [0, "ź"], [0, "Ż"], [0, "ż"], [0, "Ž"], [0, "ž"], [19, "ƒ"], [34, "Ƶ"], [63, "ǵ"], [65, "ȷ"], [142, "ˆ"], [0, "ˇ"], [16, "˘"], [0, "˙"], [0, "˚"], [0, "˛"], [0, "˜"], [0, "˝"], [51, "̑"], [127, "Α"], [0, "Β"], [0, "Γ"], [0, "Δ"], [0, "Ε"], [0, "Ζ"], [0, "Η"], [0, "Θ"], [0, "Ι"], [0, "Κ"], [0, "Λ"], [0, "Μ"], [0, "Ν"], [0, "Ξ"], [0, "Ο"], [0, "Π"], [0, "Ρ"], [1, "Σ"], [0, "Τ"], [0, "Υ"], [0, "Φ"], [0, "Χ"], [0, "Ψ"], [0, "Ω"], [7, "α"], [0, "β"], [0, "γ"], [0, "δ"], [0, "ε"], [0, "ζ"], [0, "η"], [0, "θ"], [0, "ι"], [0, "κ"], [0, "λ"], [0, "μ"], [0, "ν"], [0, "ξ"], [0, "ο"], [0, "π"], [0, "ρ"], [0, "ς"], [0, "σ"], [0, "τ"], [0, "υ"], [0, "φ"], [0, "χ"], [0, "ψ"], [0, "ω"], [7, "ϑ"], [0, "ϒ"], [2, "ϕ"], [0, "ϖ"], [5, "Ϝ"], [0, "ϝ"], [18, "ϰ"], [0, "ϱ"], [3, "ϵ"], [0, "϶"], [10, "Ё"], [0, "Ђ"], [0, "Ѓ"], [0, "Є"], [0, "Ѕ"], [0, "І"], [0, "Ї"], [0, "Ј"], [0, "Љ"], [0, "Њ"], [0, "Ћ"], [0, "Ќ"], [1, "Ў"], [0, "Џ"], [0, "А"], [0, "Б"], [0, "В"], [0, "Г"], [0, "Д"], [0, "Е"], [0, "Ж"], [0, "З"], [0, "И"], [0, "Й"], [0, "К"], [0, "Л"], [0, "М"], [0, "Н"], [0, "О"], [0, "П"], [0, "Р"], [0, "С"], [0, "Т"], [0, "У"], [0, "Ф"], [0, "Х"], [0, "Ц"], [0, "Ч"], [0, "Ш"], [0, "Щ"], [0, "Ъ"], [0, "Ы"], [0, "Ь"], [0, "Э"], [0, "Ю"], [0, "Я"], [0, "а"], [0, "б"], [0, "в"], [0, "г"], [0, "д"], [0, "е"], [0, "ж"], [0, "з"], [0, "и"], [0, "й"], [0, "к"], [0, "л"], [0, "м"], [0, "н"], [0, "о"], [0, "п"], [0, "р"], [0, "с"], [0, "т"], [0, "у"], [0, "ф"], [0, "х"], [0, "ц"], [0, "ч"], [0, "ш"], [0, "щ"], [0, "ъ"], [0, "ы"], [0, "ь"], [0, "э"], [0, "ю"], [0, "я"], [1, "ё"], [0, "ђ"], [0, "ѓ"], [0, "є"], [0, "ѕ"], [0, "і"], [0, "ї"], [0, "ј"], [0, "љ"], [0, "њ"], [0, "ћ"], [0, "ќ"], [1, "ў"], [0, "џ"], [7074, " "], [0, " "], [0, " "], [0, " "], [1, " "], [0, " "], [0, " "], [0, " "], [0, "​"], [0, "‌"], [0, "‍"], [0, "‎"], [0, "‏"], [0, "‐"], [2, "–"], [0, "—"], [0, "―"], [0, "‖"], [1, "‘"], [0, "’"], [0, "‚"], [1, "“"], [0, "”"], [0, "„"], [1, "†"], [0, "‡"], [0, "•"], [2, "‥"], [0, "…"], [9, "‰"], [0, "‱"], [0, "′"], [0, "″"], [0, "‴"], [0, "‵"], [3, "‹"], [0, "›"], [3, "‾"], [2, "⁁"], [1, "⁃"], [0, "⁄"], [10, "⁏"], [7, "⁗"], [7, { - v: " ", - n: 8202, - o: "  " -}], [0, "⁠"], [0, "⁡"], [0, "⁢"], [0, "⁣"], [72, "€"], [46, "⃛"], [0, "⃜"], [37, "ℂ"], [2, "℅"], [4, "ℊ"], [0, "ℋ"], [0, "ℌ"], [0, "ℍ"], [0, "ℎ"], [0, "ℏ"], [0, "ℐ"], [0, "ℑ"], [0, "ℒ"], [0, "ℓ"], [1, "ℕ"], [0, "№"], [0, "℗"], [0, "℘"], [0, "ℙ"], [0, "ℚ"], [0, "ℛ"], [0, "ℜ"], [0, "ℝ"], [0, "℞"], [3, "™"], [1, "ℤ"], [2, "℧"], [0, "ℨ"], [0, "℩"], [2, "ℬ"], [0, "ℭ"], [1, "ℯ"], [0, "ℰ"], [0, "ℱ"], [1, "ℳ"], [0, "ℴ"], [0, "ℵ"], [0, "ℶ"], [0, "ℷ"], [0, "ℸ"], [12, "ⅅ"], [0, "ⅆ"], [0, "ⅇ"], [0, "ⅈ"], [10, "⅓"], [0, "⅔"], [0, "⅕"], [0, "⅖"], [0, "⅗"], [0, "⅘"], [0, "⅙"], [0, "⅚"], [0, "⅛"], [0, "⅜"], [0, "⅝"], [0, "⅞"], [49, "←"], [0, "↑"], [0, "→"], [0, "↓"], [0, "↔"], [0, "↕"], [0, "↖"], [0, "↗"], [0, "↘"], [0, "↙"], [0, "↚"], [0, "↛"], [1, { - v: "↝", - n: 824, - o: "↝̸" -}], [0, "↞"], [0, "↟"], [0, "↠"], [0, "↡"], [0, "↢"], [0, "↣"], [0, "↤"], [0, "↥"], [0, "↦"], [0, "↧"], [1, "↩"], [0, "↪"], [0, "↫"], [0, "↬"], [0, "↭"], [0, "↮"], [1, "↰"], [0, "↱"], [0, "↲"], [0, "↳"], [1, "↵"], [0, "↶"], [0, "↷"], [2, "↺"], [0, "↻"], [0, "↼"], [0, "↽"], [0, "↾"], [0, "↿"], [0, "⇀"], [0, "⇁"], [0, "⇂"], [0, "⇃"], [0, "⇄"], [0, "⇅"], [0, "⇆"], [0, "⇇"], [0, "⇈"], [0, "⇉"], [0, "⇊"], [0, "⇋"], [0, "⇌"], [0, "⇍"], [0, "⇎"], [0, "⇏"], [0, "⇐"], [0, "⇑"], [0, "⇒"], [0, "⇓"], [0, "⇔"], [0, "⇕"], [0, "⇖"], [0, "⇗"], [0, "⇘"], [0, "⇙"], [0, "⇚"], [0, "⇛"], [1, "⇝"], [6, "⇤"], [0, "⇥"], [15, "⇵"], [7, "⇽"], [0, "⇾"], [0, "⇿"], [0, "∀"], [0, "∁"], [0, { - v: "∂", - n: 824, - o: "∂̸" -}], [0, "∃"], [0, "∄"], [0, "∅"], [1, "∇"], [0, "∈"], [0, "∉"], [1, "∋"], [0, "∌"], [2, "∏"], [0, "∐"], [0, "∑"], [0, "−"], [0, "∓"], [0, "∔"], [1, "∖"], [0, "∗"], [0, "∘"], [1, "√"], [2, "∝"], [0, "∞"], [0, "∟"], [0, { - v: "∠", + /***/ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-roving-focus/dist/index.js ***! + \************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $9QJ9Y$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $9QJ9Y$react = __webpack_require__(/*! react */ "react"); + var $9QJ9Y$radixuiprimitive = __webpack_require__( + /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" + ); + var $9QJ9Y$radixuireactcollection = __webpack_require__( + /*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js" + ); + var $9QJ9Y$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $9QJ9Y$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $9QJ9Y$radixuireactid = __webpack_require__( + /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" + ); + var $9QJ9Y$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $9QJ9Y$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + var $9QJ9Y$radixuireactusecontrollablestate = __webpack_require__( + /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" + ); + var $9QJ9Y$radixuireactdirection = __webpack_require__( + /*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "createRovingFocusGroupScope", + () => $0063afae63b3fa70$export$c7109489551a4f4 + ); + $parcel$export( + module.exports, + "RovingFocusGroup", + () => $0063afae63b3fa70$export$8699f7c8af148338 + ); + $parcel$export( + module.exports, + "RovingFocusGroupItem", + () => $0063afae63b3fa70$export$ab9df7c53fe8454 + ); + $parcel$export( + module.exports, + "Root", + () => $0063afae63b3fa70$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Item", + () => $0063afae63b3fa70$export$6d08773d2e66f8f2 + ); + const $0063afae63b3fa70$var$ENTRY_FOCUS = + "rovingFocusGroup.onEntryFocus"; + const $0063afae63b3fa70$var$EVENT_OPTIONS = { + bubbles: false, + cancelable: true, + }; + /* ------------------------------------------------------------------------------------------------- + * RovingFocusGroup + * -----------------------------------------------------------------------------------------------*/ + const $0063afae63b3fa70$var$GROUP_NAME = "RovingFocusGroup"; + const [ + $0063afae63b3fa70$var$Collection, + $0063afae63b3fa70$var$useCollection, + $0063afae63b3fa70$var$createCollectionScope, + ] = $9QJ9Y$radixuireactcollection.createCollection( + $0063afae63b3fa70$var$GROUP_NAME + ); + const [ + $0063afae63b3fa70$var$createRovingFocusGroupContext, + $0063afae63b3fa70$export$c7109489551a4f4, + ] = $9QJ9Y$radixuireactcontext.createContextScope( + $0063afae63b3fa70$var$GROUP_NAME, + [$0063afae63b3fa70$var$createCollectionScope] + ); + const [ + $0063afae63b3fa70$var$RovingFocusProvider, + $0063afae63b3fa70$var$useRovingFocusContext, + ] = $0063afae63b3fa70$var$createRovingFocusGroupContext( + $0063afae63b3fa70$var$GROUP_NAME + ); + const $0063afae63b3fa70$export$8699f7c8af148338 = + /*#__PURE__*/ $9QJ9Y$react.forwardRef((props, forwardedRef) => { + return /*#__PURE__*/ $9QJ9Y$react.createElement( + $0063afae63b3fa70$var$Collection.Provider, + { + scope: props.__scopeRovingFocusGroup, + }, + /*#__PURE__*/ $9QJ9Y$react.createElement( + $0063afae63b3fa70$var$Collection.Slot, + { + scope: props.__scopeRovingFocusGroup, + }, + /*#__PURE__*/ $9QJ9Y$react.createElement( + $0063afae63b3fa70$var$RovingFocusGroupImpl, + $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)( + {}, + props, + { + ref: forwardedRef, + } + ) + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($0063afae63b3fa70$export$8699f7c8af148338, { + displayName: $0063afae63b3fa70$var$GROUP_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + const $0063afae63b3fa70$var$RovingFocusGroupImpl = + /*#__PURE__*/ $9QJ9Y$react.forwardRef((props, forwardedRef) => { + const { + __scopeRovingFocusGroup: __scopeRovingFocusGroup, + orientation: orientation, + loop = false, + dir: dir, + currentTabStopId: currentTabStopIdProp, + defaultCurrentTabStopId: defaultCurrentTabStopId, + onCurrentTabStopIdChange: onCurrentTabStopIdChange, + onEntryFocus: onEntryFocus, + ...groupProps + } = props; + const ref = $9QJ9Y$react.useRef(null); + const composedRefs = $9QJ9Y$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + const direction = $9QJ9Y$radixuireactdirection.useDirection(dir); + const [currentTabStopId = null, setCurrentTabStopId] = + $9QJ9Y$radixuireactusecontrollablestate.useControllableState({ + prop: currentTabStopIdProp, + defaultProp: defaultCurrentTabStopId, + onChange: onCurrentTabStopIdChange, + }); + const [isTabbingBackOut, setIsTabbingBackOut] = + $9QJ9Y$react.useState(false); + const handleEntryFocus = + $9QJ9Y$radixuireactusecallbackref.useCallbackRef(onEntryFocus); + const getItems = $0063afae63b3fa70$var$useCollection( + __scopeRovingFocusGroup + ); + const isClickFocusRef = $9QJ9Y$react.useRef(false); + const [focusableItemsCount, setFocusableItemsCount] = + $9QJ9Y$react.useState(0); + $9QJ9Y$react.useEffect(() => { + const node = ref.current; + if (node) { + node.addEventListener( + $0063afae63b3fa70$var$ENTRY_FOCUS, + handleEntryFocus + ); + return () => + node.removeEventListener( + $0063afae63b3fa70$var$ENTRY_FOCUS, + handleEntryFocus + ); + } + }, [handleEntryFocus]); + return /*#__PURE__*/ $9QJ9Y$react.createElement( + $0063afae63b3fa70$var$RovingFocusProvider, + { + scope: __scopeRovingFocusGroup, + orientation: orientation, + dir: direction, + loop: loop, + currentTabStopId: currentTabStopId, + onItemFocus: $9QJ9Y$react.useCallback( + (tabStopId) => setCurrentTabStopId(tabStopId), + [setCurrentTabStopId] + ), + onItemShiftTab: $9QJ9Y$react.useCallback( + () => setIsTabbingBackOut(true), + [] + ), + onFocusableItemAdd: $9QJ9Y$react.useCallback( + () => setFocusableItemsCount((prevCount) => prevCount + 1), + [] + ), + onFocusableItemRemove: $9QJ9Y$react.useCallback( + () => setFocusableItemsCount((prevCount) => prevCount - 1), + [] + ), + }, + /*#__PURE__*/ $9QJ9Y$react.createElement( + $9QJ9Y$radixuireactprimitive.Primitive.div, + $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)( + { + tabIndex: + isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0, + "data-orientation": orientation, + }, + groupProps, + { + ref: composedRefs, + style: { + outline: "none", + ...props.style, + }, + onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers( + props.onMouseDown, + () => { + isClickFocusRef.current = true; + } + ), + onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers( + props.onFocus, + (event) => { + // We normally wouldn't need this check, because we already check + // that the focus is on the current target and not bubbling to it. + // We do this because Safari doesn't focus buttons when clicked, and + // instead, the wrapper will get focused and not through a bubbling event. + const isKeyboardFocus = !isClickFocusRef.current; + if ( + event.target === event.currentTarget && + isKeyboardFocus && + !isTabbingBackOut + ) { + const entryFocusEvent = new CustomEvent( + $0063afae63b3fa70$var$ENTRY_FOCUS, + $0063afae63b3fa70$var$EVENT_OPTIONS + ); + event.currentTarget.dispatchEvent(entryFocusEvent); + if (!entryFocusEvent.defaultPrevented) { + const items = getItems().filter( + (item) => item.focusable + ); + const activeItem = items.find( + (item) => item.active + ); + const currentItem = items.find( + (item) => item.id === currentTabStopId + ); + const candidateItems = [ + activeItem, + currentItem, + ...items, + ].filter(Boolean); + const candidateNodes = candidateItems.map( + (item) => item.ref.current + ); + $0063afae63b3fa70$var$focusFirst(candidateNodes); + } + } + isClickFocusRef.current = false; + } + ), + onBlur: $9QJ9Y$radixuiprimitive.composeEventHandlers( + props.onBlur, + () => setIsTabbingBackOut(false) + ), + } + ) + ) + ); + }); + /* ------------------------------------------------------------------------------------------------- + * RovingFocusGroupItem + * -----------------------------------------------------------------------------------------------*/ + const $0063afae63b3fa70$var$ITEM_NAME = "RovingFocusGroupItem"; + const $0063afae63b3fa70$export$ab9df7c53fe8454 = + /*#__PURE__*/ $9QJ9Y$react.forwardRef((props, forwardedRef) => { + const { + __scopeRovingFocusGroup: __scopeRovingFocusGroup, + focusable = true, + active = false, + tabStopId: tabStopId, + ...itemProps + } = props; + const autoId = $9QJ9Y$radixuireactid.useId(); + const id = tabStopId || autoId; + const context = $0063afae63b3fa70$var$useRovingFocusContext( + $0063afae63b3fa70$var$ITEM_NAME, + __scopeRovingFocusGroup + ); + const isCurrentTabStop = context.currentTabStopId === id; + const getItems = $0063afae63b3fa70$var$useCollection( + __scopeRovingFocusGroup + ); + const { + onFocusableItemAdd: onFocusableItemAdd, + onFocusableItemRemove: onFocusableItemRemove, + } = context; + $9QJ9Y$react.useEffect(() => { + if (focusable) { + onFocusableItemAdd(); + return () => onFocusableItemRemove(); + } + }, [focusable, onFocusableItemAdd, onFocusableItemRemove]); + return /*#__PURE__*/ $9QJ9Y$react.createElement( + $0063afae63b3fa70$var$Collection.ItemSlot, + { + scope: __scopeRovingFocusGroup, + id: id, + focusable: focusable, + active: active, + }, + /*#__PURE__*/ $9QJ9Y$react.createElement( + $9QJ9Y$radixuireactprimitive.Primitive.span, + $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)( + { + tabIndex: isCurrentTabStop ? 0 : -1, + "data-orientation": context.orientation, + }, + itemProps, + { + ref: forwardedRef, + onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers( + props.onMouseDown, + (event) => { + // We prevent focusing non-focusable items on `mousedown`. + // Even though the item has tabIndex={-1}, that only means take it out of the tab order. + if (!focusable) + event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also + else context.onItemFocus(id); + } + ), + onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers( + props.onFocus, + () => context.onItemFocus(id) + ), + onKeyDown: $9QJ9Y$radixuiprimitive.composeEventHandlers( + props.onKeyDown, + (event) => { + if (event.key === "Tab" && event.shiftKey) { + context.onItemShiftTab(); + return; + } + if (event.target !== event.currentTarget) return; + const focusIntent = + $0063afae63b3fa70$var$getFocusIntent( + event, + context.orientation, + context.dir + ); + if (focusIntent !== undefined) { + event.preventDefault(); + const items = getItems().filter( + (item) => item.focusable + ); + let candidateNodes = items.map( + (item) => item.ref.current + ); + if (focusIntent === "last") candidateNodes.reverse(); + else if ( + focusIntent === "prev" || + focusIntent === "next" + ) { + if (focusIntent === "prev") + candidateNodes.reverse(); + const currentIndex = candidateNodes.indexOf( + event.currentTarget + ); + candidateNodes = context.loop + ? $0063afae63b3fa70$var$wrapArray( + candidateNodes, + currentIndex + 1 + ) + : candidateNodes.slice(currentIndex + 1); + } + /** + * Imperative focus during keydown is risky so we prevent React's batching updates + * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 + */ + setTimeout(() => + $0063afae63b3fa70$var$focusFirst(candidateNodes) + ); + } + } + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($0063afae63b3fa70$export$ab9df7c53fe8454, { + displayName: $0063afae63b3fa70$var$ITEM_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ // prettier-ignore + const $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT = { + ArrowLeft: 'prev', + ArrowUp: 'prev', + ArrowRight: 'next', + ArrowDown: 'next', + PageUp: 'first', + Home: 'first', + PageDown: 'last', + End: 'last' +}; + function $0063afae63b3fa70$var$getDirectionAwareKey(key, dir) { + if (dir !== "rtl") return key; + return key === "ArrowLeft" + ? "ArrowRight" + : key === "ArrowRight" + ? "ArrowLeft" + : key; + } + function $0063afae63b3fa70$var$getFocusIntent(event, orientation, dir) { + const key = $0063afae63b3fa70$var$getDirectionAwareKey( + event.key, + dir + ); + if ( + orientation === "vertical" && + ["ArrowLeft", "ArrowRight"].includes(key) + ) + return undefined; + if ( + orientation === "horizontal" && + ["ArrowUp", "ArrowDown"].includes(key) + ) + return undefined; + return $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT[key]; + } + function $0063afae63b3fa70$var$focusFirst(candidates) { + const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; + for (const candidate of candidates) { + // if focus is already where we want to go, we don't want to keep going through the candidates + if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; + candidate.focus(); + if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; + } + } + /** + * Wraps an array around itself at a given start index + * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` + */ + function $0063afae63b3fa70$var$wrapArray(array, startIndex) { + return array.map( + (_, index) => array[(startIndex + index) % array.length] + ); + } + const $0063afae63b3fa70$export$be92b6f5f03c0fe9 = + $0063afae63b3fa70$export$8699f7c8af148338; + const $0063afae63b3fa70$export$6d08773d2e66f8f2 = + $0063afae63b3fa70$export$ab9df7c53fe8454; + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-slot/dist/index.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-slot/dist/index.js ***! + \****************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $dAvBt$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $dAvBt$react = __webpack_require__(/*! react */ "react"); + var $dAvBt$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "Slot", + () => $82dc8d030dec7549$export$8c6ed5c666ac1360 + ); + $parcel$export( + module.exports, + "Slottable", + () => $82dc8d030dec7549$export$d9f1ccf0bdb05d45 + ); + $parcel$export( + module.exports, + "Root", + () => $82dc8d030dec7549$export$be92b6f5f03c0fe9 + ); + + /* ------------------------------------------------------------------------------------------------- + * Slot + * -----------------------------------------------------------------------------------------------*/ + const $82dc8d030dec7549$export$8c6ed5c666ac1360 = + /*#__PURE__*/ $dAvBt$react.forwardRef((props, forwardedRef) => { + const { children: children, ...slotProps } = props; + const childrenArray = $dAvBt$react.Children.toArray(children); + const slottable = childrenArray.find( + $82dc8d030dec7549$var$isSlottable + ); + if (slottable) { + // the new element to render is the one passed as a child of `Slottable` + const newElement = slottable.props.children; + const newChildren = childrenArray.map((child) => { + if (child === slottable) { + // because the new element will be the one rendered, we are only interested + // in grabbing its children (`newElement.props.children`) + if ($dAvBt$react.Children.count(newElement) > 1) + return $dAvBt$react.Children.only(null); + return /*#__PURE__*/ $dAvBt$react.isValidElement(newElement) + ? newElement.props.children + : null; + } else return child; + }); + return /*#__PURE__*/ $dAvBt$react.createElement( + $82dc8d030dec7549$var$SlotClone, + $parcel$interopDefault($dAvBt$babelruntimehelpersextends)( + {}, + slotProps, + { + ref: forwardedRef, + } + ), + /*#__PURE__*/ $dAvBt$react.isValidElement(newElement) + ? /*#__PURE__*/ $dAvBt$react.cloneElement( + newElement, + undefined, + newChildren + ) + : null + ); + } + return /*#__PURE__*/ $dAvBt$react.createElement( + $82dc8d030dec7549$var$SlotClone, + $parcel$interopDefault($dAvBt$babelruntimehelpersextends)( + {}, + slotProps, + { + ref: forwardedRef, + } + ), + children + ); + }); + $82dc8d030dec7549$export$8c6ed5c666ac1360.displayName = "Slot"; + /* ------------------------------------------------------------------------------------------------- + * SlotClone + * -----------------------------------------------------------------------------------------------*/ + const $82dc8d030dec7549$var$SlotClone = + /*#__PURE__*/ $dAvBt$react.forwardRef((props, forwardedRef) => { + const { children: children, ...slotProps } = props; + if (/*#__PURE__*/ $dAvBt$react.isValidElement(children)) + return /*#__PURE__*/ $dAvBt$react.cloneElement(children, { + ...$82dc8d030dec7549$var$mergeProps(slotProps, children.props), + ref: forwardedRef + ? $dAvBt$radixuireactcomposerefs.composeRefs( + forwardedRef, + children.ref + ) + : children.ref, + }); + return $dAvBt$react.Children.count(children) > 1 + ? $dAvBt$react.Children.only(null) + : null; + }); + $82dc8d030dec7549$var$SlotClone.displayName = "SlotClone"; + /* ------------------------------------------------------------------------------------------------- + * Slottable + * -----------------------------------------------------------------------------------------------*/ + const $82dc8d030dec7549$export$d9f1ccf0bdb05d45 = ({ + children: children, + }) => { + return /*#__PURE__*/ $dAvBt$react.createElement( + $dAvBt$react.Fragment, + null, + children + ); + }; + /* ---------------------------------------------------------------------------------------------- */ + function $82dc8d030dec7549$var$isSlottable(child) { + return ( + /*#__PURE__*/ $dAvBt$react.isValidElement(child) && + child.type === $82dc8d030dec7549$export$d9f1ccf0bdb05d45 + ); + } + function $82dc8d030dec7549$var$mergeProps(slotProps, childProps) { + // all child props should override + const overrideProps = { + ...childProps, + }; + for (const propName in childProps) { + const slotPropValue = slotProps[propName]; + const childPropValue = childProps[propName]; + const isHandler = /^on[A-Z]/.test(propName); + if (isHandler) { + // if the handler exists on both, we compose them + if (slotPropValue && childPropValue) + overrideProps[propName] = (...args) => { + childPropValue(...args); + slotPropValue(...args); + }; + else if (slotPropValue) overrideProps[propName] = slotPropValue; + } else if (propName === "style") + overrideProps[propName] = { + ...slotPropValue, + ...childPropValue, + }; + else if (propName === "className") + overrideProps[propName] = [slotPropValue, childPropValue] + .filter(Boolean) + .join(" "); + } + return { + ...slotProps, + ...overrideProps, + }; + } + const $82dc8d030dec7549$export$be92b6f5f03c0fe9 = + $82dc8d030dec7549$export$8c6ed5c666ac1360; + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-tooltip/dist/index.js ***! + \*******************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $iVrL9$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $iVrL9$react = __webpack_require__(/*! react */ "react"); + var $iVrL9$radixuiprimitive = __webpack_require__( + /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" + ); + var $iVrL9$radixuireactcomposerefs = __webpack_require__( + /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" + ); + var $iVrL9$radixuireactcontext = __webpack_require__( + /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" + ); + var $iVrL9$radixuireactdismissablelayer = __webpack_require__( + /*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js" + ); + var $iVrL9$radixuireactid = __webpack_require__( + /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" + ); + var $iVrL9$radixuireactpopper = __webpack_require__( + /*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js" + ); + var $iVrL9$radixuireactportal = __webpack_require__( + /*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js" + ); + var $iVrL9$radixuireactpresence = __webpack_require__( + /*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js" + ); + var $iVrL9$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + var $iVrL9$radixuireactslot = __webpack_require__( + /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" + ); + var $iVrL9$radixuireactusecontrollablestate = __webpack_require__( + /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" + ); + var $iVrL9$radixuireactvisuallyhidden = __webpack_require__( + /*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "createTooltipScope", + () => $c34afbc43c90cc6f$export$1c540a2224f0d865 + ); + $parcel$export( + module.exports, + "TooltipProvider", + () => $c34afbc43c90cc6f$export$f78649fb9ca566b8 + ); + $parcel$export( + module.exports, + "Tooltip", + () => $c34afbc43c90cc6f$export$28c660c63b792dea + ); + $parcel$export( + module.exports, + "TooltipTrigger", + () => $c34afbc43c90cc6f$export$8c610744efcf8a1d + ); + $parcel$export( + module.exports, + "TooltipPortal", + () => $c34afbc43c90cc6f$export$7b36b8f925ab7497 + ); + $parcel$export( + module.exports, + "TooltipContent", + () => $c34afbc43c90cc6f$export$e9003e2be37ec060 + ); + $parcel$export( + module.exports, + "TooltipArrow", + () => $c34afbc43c90cc6f$export$c27ee0ad710f7559 + ); + $parcel$export( + module.exports, + "Provider", + () => $c34afbc43c90cc6f$export$2881499e37b75b9a + ); + $parcel$export( + module.exports, + "Root", + () => $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 + ); + $parcel$export( + module.exports, + "Trigger", + () => $c34afbc43c90cc6f$export$41fb9f06171c75f4 + ); + $parcel$export( + module.exports, + "Portal", + () => $c34afbc43c90cc6f$export$602eac185826482c + ); + $parcel$export( + module.exports, + "Content", + () => $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 + ); + $parcel$export( + module.exports, + "Arrow", + () => $c34afbc43c90cc6f$export$21b07c8f274aebd5 + ); + const [ + $c34afbc43c90cc6f$var$createTooltipContext, + $c34afbc43c90cc6f$export$1c540a2224f0d865, + ] = $iVrL9$radixuireactcontext.createContextScope("Tooltip", [ + $iVrL9$radixuireactpopper.createPopperScope, + ]); + const $c34afbc43c90cc6f$var$usePopperScope = + $iVrL9$radixuireactpopper.createPopperScope(); + /* ------------------------------------------------------------------------------------------------- + * TooltipProvider + * -----------------------------------------------------------------------------------------------*/ + const $c34afbc43c90cc6f$var$PROVIDER_NAME = "TooltipProvider"; + const $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION = 700; + const $c34afbc43c90cc6f$var$TOOLTIP_OPEN = "tooltip.open"; + const [ + $c34afbc43c90cc6f$var$TooltipProviderContextProvider, + $c34afbc43c90cc6f$var$useTooltipProviderContext, + ] = $c34afbc43c90cc6f$var$createTooltipContext( + $c34afbc43c90cc6f$var$PROVIDER_NAME + ); + const $c34afbc43c90cc6f$export$f78649fb9ca566b8 = (props) => { + const { + __scopeTooltip: __scopeTooltip, + delayDuration = $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION, + skipDelayDuration = 300, + disableHoverableContent = false, + children: children, + } = props; + const [isOpenDelayed, setIsOpenDelayed] = $iVrL9$react.useState(true); + const isPointerInTransitRef = $iVrL9$react.useRef(false); + const skipDelayTimerRef = $iVrL9$react.useRef(0); + $iVrL9$react.useEffect(() => { + const skipDelayTimer = skipDelayTimerRef.current; + return () => window.clearTimeout(skipDelayTimer); + }, []); + return /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$TooltipProviderContextProvider, + { + scope: __scopeTooltip, + isOpenDelayed: isOpenDelayed, + delayDuration: delayDuration, + onOpen: $iVrL9$react.useCallback(() => { + window.clearTimeout(skipDelayTimerRef.current); + setIsOpenDelayed(false); + }, []), + onClose: $iVrL9$react.useCallback(() => { + window.clearTimeout(skipDelayTimerRef.current); + skipDelayTimerRef.current = window.setTimeout( + () => setIsOpenDelayed(true), + skipDelayDuration + ); + }, [skipDelayDuration]), + isPointerInTransitRef: isPointerInTransitRef, + onPointerInTransitChange: $iVrL9$react.useCallback( + (inTransit) => { + isPointerInTransitRef.current = inTransit; + }, + [] + ), + disableHoverableContent: disableHoverableContent, + }, + children + ); + }; + /*#__PURE__*/ + Object.assign($c34afbc43c90cc6f$export$f78649fb9ca566b8, { + displayName: $c34afbc43c90cc6f$var$PROVIDER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * Tooltip + * -----------------------------------------------------------------------------------------------*/ + const $c34afbc43c90cc6f$var$TOOLTIP_NAME = "Tooltip"; + const [ + $c34afbc43c90cc6f$var$TooltipContextProvider, + $c34afbc43c90cc6f$var$useTooltipContext, + ] = $c34afbc43c90cc6f$var$createTooltipContext( + $c34afbc43c90cc6f$var$TOOLTIP_NAME + ); + const $c34afbc43c90cc6f$export$28c660c63b792dea = (props) => { + const { + __scopeTooltip: __scopeTooltip, + children: children, + open: openProp, + defaultOpen = false, + onOpenChange: onOpenChange, + disableHoverableContent: disableHoverableContentProp, + delayDuration: delayDurationProp, + } = props; + const providerContext = + $c34afbc43c90cc6f$var$useTooltipProviderContext( + $c34afbc43c90cc6f$var$TOOLTIP_NAME, + props.__scopeTooltip + ); + const popperScope = + $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); + const [trigger, setTrigger] = $iVrL9$react.useState(null); + const contentId = $iVrL9$radixuireactid.useId(); + const openTimerRef = $iVrL9$react.useRef(0); + const disableHoverableContent = + disableHoverableContentProp !== null && + disableHoverableContentProp !== void 0 + ? disableHoverableContentProp + : providerContext.disableHoverableContent; + const delayDuration = + delayDurationProp !== null && delayDurationProp !== void 0 + ? delayDurationProp + : providerContext.delayDuration; + const wasOpenDelayedRef = $iVrL9$react.useRef(false); + const [open1 = false, setOpen] = + $iVrL9$radixuireactusecontrollablestate.useControllableState({ + prop: openProp, + defaultProp: defaultOpen, + onChange: (open) => { + if (open) { + providerContext.onOpen(); // as `onChange` is called within a lifecycle method we + // avoid dispatching via `dispatchDiscreteCustomEvent`. + document.dispatchEvent( + new CustomEvent($c34afbc43c90cc6f$var$TOOLTIP_OPEN) + ); + } else providerContext.onClose(); + onOpenChange === null || + onOpenChange === void 0 || + onOpenChange(open); + }, + }); + const stateAttribute = $iVrL9$react.useMemo(() => { + return open1 + ? wasOpenDelayedRef.current + ? "delayed-open" + : "instant-open" + : "closed"; + }, [open1]); + const handleOpen = $iVrL9$react.useCallback(() => { + window.clearTimeout(openTimerRef.current); + wasOpenDelayedRef.current = false; + setOpen(true); + }, [setOpen]); + const handleClose = $iVrL9$react.useCallback(() => { + window.clearTimeout(openTimerRef.current); + setOpen(false); + }, [setOpen]); + const handleDelayedOpen = $iVrL9$react.useCallback(() => { + window.clearTimeout(openTimerRef.current); + openTimerRef.current = window.setTimeout(() => { + wasOpenDelayedRef.current = true; + setOpen(true); + }, delayDuration); + }, [delayDuration, setOpen]); + $iVrL9$react.useEffect(() => { + return () => window.clearTimeout(openTimerRef.current); + }, []); + return /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactpopper.Root, + popperScope, + /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$TooltipContextProvider, + { + scope: __scopeTooltip, + contentId: contentId, + open: open1, + stateAttribute: stateAttribute, + trigger: trigger, + onTriggerChange: setTrigger, + onTriggerEnter: $iVrL9$react.useCallback(() => { + if (providerContext.isOpenDelayed) handleDelayedOpen(); + else handleOpen(); + }, [ + providerContext.isOpenDelayed, + handleDelayedOpen, + handleOpen, + ]), + onTriggerLeave: $iVrL9$react.useCallback(() => { + if (disableHoverableContent) handleClose(); + // Clear the timer in case the pointer leaves the trigger before the tooltip is opened. + else window.clearTimeout(openTimerRef.current); + }, [handleClose, disableHoverableContent]), + onOpen: handleOpen, + onClose: handleClose, + disableHoverableContent: disableHoverableContent, + }, + children + ) + ); + }; + /*#__PURE__*/ + Object.assign($c34afbc43c90cc6f$export$28c660c63b792dea, { + displayName: $c34afbc43c90cc6f$var$TOOLTIP_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * TooltipTrigger + * -----------------------------------------------------------------------------------------------*/ + const $c34afbc43c90cc6f$var$TRIGGER_NAME = "TooltipTrigger"; + const $c34afbc43c90cc6f$export$8c610744efcf8a1d = + /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { + const { __scopeTooltip: __scopeTooltip, ...triggerProps } = props; + const context = $c34afbc43c90cc6f$var$useTooltipContext( + $c34afbc43c90cc6f$var$TRIGGER_NAME, + __scopeTooltip + ); + const providerContext = + $c34afbc43c90cc6f$var$useTooltipProviderContext( + $c34afbc43c90cc6f$var$TRIGGER_NAME, + __scopeTooltip + ); + const popperScope = + $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); + const ref = $iVrL9$react.useRef(null); + const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref, + context.onTriggerChange + ); + const isPointerDownRef = $iVrL9$react.useRef(false); + const hasPointerMoveOpenedRef = $iVrL9$react.useRef(false); + const handlePointerUp = $iVrL9$react.useCallback( + () => (isPointerDownRef.current = false), + [] + ); + $iVrL9$react.useEffect(() => { + return () => + document.removeEventListener("pointerup", handlePointerUp); + }, [handlePointerUp]); + return /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactpopper.Anchor, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + { + asChild: true, + }, + popperScope + ), + /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactprimitive.Primitive.button, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + { + // We purposefully avoid adding `type=button` here because tooltip triggers are also + // commonly anchors and the anchor `type` attribute signifies MIME type. + "aria-describedby": context.open + ? context.contentId + : undefined, + "data-state": context.stateAttribute, + }, + triggerProps, + { + ref: composedRefs, + onPointerMove: $iVrL9$radixuiprimitive.composeEventHandlers( + props.onPointerMove, + (event) => { + if (event.pointerType === "touch") return; + if ( + !hasPointerMoveOpenedRef.current && + !providerContext.isPointerInTransitRef.current + ) { + context.onTriggerEnter(); + hasPointerMoveOpenedRef.current = true; + } + } + ), + onPointerLeave: + $iVrL9$radixuiprimitive.composeEventHandlers( + props.onPointerLeave, + () => { + context.onTriggerLeave(); + hasPointerMoveOpenedRef.current = false; + } + ), + onPointerDown: $iVrL9$radixuiprimitive.composeEventHandlers( + props.onPointerDown, + () => { + isPointerDownRef.current = true; + document.addEventListener( + "pointerup", + handlePointerUp, + { + once: true, + } + ); + } + ), + onFocus: $iVrL9$radixuiprimitive.composeEventHandlers( + props.onFocus, + () => { + if (!isPointerDownRef.current) context.onOpen(); + } + ), + onBlur: $iVrL9$radixuiprimitive.composeEventHandlers( + props.onBlur, + context.onClose + ), + onClick: $iVrL9$radixuiprimitive.composeEventHandlers( + props.onClick, + context.onClose + ), + } + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($c34afbc43c90cc6f$export$8c610744efcf8a1d, { + displayName: $c34afbc43c90cc6f$var$TRIGGER_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * TooltipPortal + * -----------------------------------------------------------------------------------------------*/ + const $c34afbc43c90cc6f$var$PORTAL_NAME = "TooltipPortal"; + const [ + $c34afbc43c90cc6f$var$PortalProvider, + $c34afbc43c90cc6f$var$usePortalContext, + ] = $c34afbc43c90cc6f$var$createTooltipContext( + $c34afbc43c90cc6f$var$PORTAL_NAME, + { + forceMount: undefined, + } + ); + const $c34afbc43c90cc6f$export$7b36b8f925ab7497 = (props) => { + const { + __scopeTooltip: __scopeTooltip, + forceMount: forceMount, + children: children, + container: container, + } = props; + const context = $c34afbc43c90cc6f$var$useTooltipContext( + $c34afbc43c90cc6f$var$PORTAL_NAME, + __scopeTooltip + ); + return /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$PortalProvider, + { + scope: __scopeTooltip, + forceMount: forceMount, + }, + /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactportal.Portal, + { + asChild: true, + container: container, + }, + children + ) + ) + ); + }; + /*#__PURE__*/ + Object.assign($c34afbc43c90cc6f$export$7b36b8f925ab7497, { + displayName: $c34afbc43c90cc6f$var$PORTAL_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * TooltipContent + * -----------------------------------------------------------------------------------------------*/ + const $c34afbc43c90cc6f$var$CONTENT_NAME = "TooltipContent"; + const $c34afbc43c90cc6f$export$e9003e2be37ec060 = + /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { + const portalContext = $c34afbc43c90cc6f$var$usePortalContext( + $c34afbc43c90cc6f$var$CONTENT_NAME, + props.__scopeTooltip + ); + const { + forceMount = portalContext.forceMount, + side = "top", + ...contentProps + } = props; + const context = $c34afbc43c90cc6f$var$useTooltipContext( + $c34afbc43c90cc6f$var$CONTENT_NAME, + props.__scopeTooltip + ); + return /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactpresence.Presence, + { + present: forceMount || context.open, + }, + context.disableHoverableContent + ? /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$TooltipContentImpl, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + { + side: side, + }, + contentProps, + { + ref: forwardedRef, + } + ) + ) + : /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$TooltipContentHoverable, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + { + side: side, + }, + contentProps, + { + ref: forwardedRef, + } + ) + ) + ); + }); + const $c34afbc43c90cc6f$var$TooltipContentHoverable = + /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { + const context = $c34afbc43c90cc6f$var$useTooltipContext( + $c34afbc43c90cc6f$var$CONTENT_NAME, + props.__scopeTooltip + ); + const providerContext = + $c34afbc43c90cc6f$var$useTooltipProviderContext( + $c34afbc43c90cc6f$var$CONTENT_NAME, + props.__scopeTooltip + ); + const ref = $iVrL9$react.useRef(null); + const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs( + forwardedRef, + ref + ); + const [pointerGraceArea, setPointerGraceArea] = + $iVrL9$react.useState(null); + const { trigger: trigger, onClose: onClose } = context; + const content = ref.current; + const { onPointerInTransitChange: onPointerInTransitChange } = + providerContext; + const handleRemoveGraceArea = $iVrL9$react.useCallback(() => { + setPointerGraceArea(null); + onPointerInTransitChange(false); + }, [onPointerInTransitChange]); + const handleCreateGraceArea = $iVrL9$react.useCallback( + (event, hoverTarget) => { + const currentTarget = event.currentTarget; + const exitPoint = { + x: event.clientX, + y: event.clientY, + }; + const exitSide = $c34afbc43c90cc6f$var$getExitSideFromRect( + exitPoint, + currentTarget.getBoundingClientRect() + ); + const paddedExitPoints = + $c34afbc43c90cc6f$var$getPaddedExitPoints( + exitPoint, + exitSide + ); + const hoverTargetPoints = + $c34afbc43c90cc6f$var$getPointsFromRect( + hoverTarget.getBoundingClientRect() + ); + const graceArea = $c34afbc43c90cc6f$var$getHull([ + ...paddedExitPoints, + ...hoverTargetPoints, + ]); + setPointerGraceArea(graceArea); + onPointerInTransitChange(true); + }, + [onPointerInTransitChange] + ); + $iVrL9$react.useEffect(() => { + return () => handleRemoveGraceArea(); + }, [handleRemoveGraceArea]); + $iVrL9$react.useEffect(() => { + if (trigger && content) { + const handleTriggerLeave = (event) => + handleCreateGraceArea(event, content); + const handleContentLeave = (event) => + handleCreateGraceArea(event, trigger); + trigger.addEventListener("pointerleave", handleTriggerLeave); + content.addEventListener("pointerleave", handleContentLeave); + return () => { + trigger.removeEventListener( + "pointerleave", + handleTriggerLeave + ); + content.removeEventListener( + "pointerleave", + handleContentLeave + ); + }; + } + }, [ + trigger, + content, + handleCreateGraceArea, + handleRemoveGraceArea, + ]); + $iVrL9$react.useEffect(() => { + if (pointerGraceArea) { + const handleTrackPointerGrace = (event) => { + const target = event.target; + const pointerPosition = { + x: event.clientX, + y: event.clientY, + }; + const hasEnteredTarget = + (trigger === null || trigger === void 0 + ? void 0 + : trigger.contains(target)) || + (content === null || content === void 0 + ? void 0 + : content.contains(target)); + const isPointerOutsideGraceArea = + !$c34afbc43c90cc6f$var$isPointInPolygon( + pointerPosition, + pointerGraceArea + ); + if (hasEnteredTarget) handleRemoveGraceArea(); + else if (isPointerOutsideGraceArea) { + handleRemoveGraceArea(); + onClose(); + } + }; + document.addEventListener( + "pointermove", + handleTrackPointerGrace + ); + return () => + document.removeEventListener( + "pointermove", + handleTrackPointerGrace + ); + } + }, [ + trigger, + content, + pointerGraceArea, + onClose, + handleRemoveGraceArea, + ]); + return /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$TooltipContentImpl, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + {}, + props, + { + ref: composedRefs, + } + ) + ); + }); + const [ + $c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, + $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext, + ] = $c34afbc43c90cc6f$var$createTooltipContext( + $c34afbc43c90cc6f$var$TOOLTIP_NAME, + { + isInside: false, + } + ); + const $c34afbc43c90cc6f$var$TooltipContentImpl = + /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { + const { + __scopeTooltip: __scopeTooltip, + children: children, + "aria-label": ariaLabel, + onEscapeKeyDown: onEscapeKeyDown, + onPointerDownOutside: onPointerDownOutside, + ...contentProps + } = props; + const context = $c34afbc43c90cc6f$var$useTooltipContext( + $c34afbc43c90cc6f$var$CONTENT_NAME, + __scopeTooltip + ); + const popperScope = + $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); + const { onClose: onClose } = context; // Close this tooltip if another one opens + $iVrL9$react.useEffect(() => { + document.addEventListener( + $c34afbc43c90cc6f$var$TOOLTIP_OPEN, + onClose + ); + return () => + document.removeEventListener( + $c34afbc43c90cc6f$var$TOOLTIP_OPEN, + onClose + ); + }, [onClose]); // Close the tooltip if the trigger is scrolled + $iVrL9$react.useEffect(() => { + if (context.trigger) { + const handleScroll = (event) => { + const target = event.target; + if ( + target !== null && + target !== void 0 && + target.contains(context.trigger) + ) + onClose(); + }; + window.addEventListener("scroll", handleScroll, { + capture: true, + }); + return () => + window.removeEventListener("scroll", handleScroll, { + capture: true, + }); + } + }, [context.trigger, onClose]); + return /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactdismissablelayer.DismissableLayer, + { + asChild: true, + disableOutsidePointerEvents: false, + onEscapeKeyDown: onEscapeKeyDown, + onPointerDownOutside: onPointerDownOutside, + onFocusOutside: (event) => event.preventDefault(), + onDismiss: onClose, + }, + /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactpopper.Content, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + { + "data-state": context.stateAttribute, + }, + popperScope, + contentProps, + { + ref: forwardedRef, + style: { + ...contentProps.style, + "--radix-tooltip-content-transform-origin": + "var(--radix-popper-transform-origin)", + "--radix-tooltip-content-available-width": + "var(--radix-popper-available-width)", + "--radix-tooltip-content-available-height": + "var(--radix-popper-available-height)", + "--radix-tooltip-trigger-width": + "var(--radix-popper-anchor-width)", + "--radix-tooltip-trigger-height": + "var(--radix-popper-anchor-height)", + }, + } + ), + /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactslot.Slottable, + null, + children + ), + /*#__PURE__*/ $iVrL9$react.createElement( + $c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, + { + scope: __scopeTooltip, + isInside: true, + }, + /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactvisuallyhidden.Root, + { + id: context.contentId, + role: "tooltip", + }, + ariaLabel || children + ) + ) + ) + ); + }); + /*#__PURE__*/ + Object.assign($c34afbc43c90cc6f$export$e9003e2be37ec060, { + displayName: $c34afbc43c90cc6f$var$CONTENT_NAME, + }); + /* ------------------------------------------------------------------------------------------------- + * TooltipArrow + * -----------------------------------------------------------------------------------------------*/ + const $c34afbc43c90cc6f$var$ARROW_NAME = "TooltipArrow"; + const $c34afbc43c90cc6f$export$c27ee0ad710f7559 = + /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { + const { __scopeTooltip: __scopeTooltip, ...arrowProps } = props; + const popperScope = + $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); + const visuallyHiddenContentContext = + $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext( + $c34afbc43c90cc6f$var$ARROW_NAME, + __scopeTooltip + ); // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to + // prevent issues in positioning the arrow due to the duplicate + return visuallyHiddenContentContext.isInside + ? null + : /*#__PURE__*/ $iVrL9$react.createElement( + $iVrL9$radixuireactpopper.Arrow, + $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( + {}, + popperScope, + arrowProps, + { + ref: forwardedRef, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($c34afbc43c90cc6f$export$c27ee0ad710f7559, { + displayName: $c34afbc43c90cc6f$var$ARROW_NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + function $c34afbc43c90cc6f$var$getExitSideFromRect(point, rect) { + const top = Math.abs(rect.top - point.y); + const bottom = Math.abs(rect.bottom - point.y); + const right = Math.abs(rect.right - point.x); + const left = Math.abs(rect.left - point.x); + switch (Math.min(top, bottom, right, left)) { + case left: + return "left"; + case right: + return "right"; + case top: + return "top"; + case bottom: + return "bottom"; + default: + throw new Error("unreachable"); + } + } + function $c34afbc43c90cc6f$var$getPaddedExitPoints( + exitPoint, + exitSide, + padding = 5 + ) { + const paddedExitPoints = []; + switch (exitSide) { + case "top": + paddedExitPoints.push( + { + x: exitPoint.x - padding, + y: exitPoint.y + padding, + }, + { + x: exitPoint.x + padding, + y: exitPoint.y + padding, + } + ); + break; + case "bottom": + paddedExitPoints.push( + { + x: exitPoint.x - padding, + y: exitPoint.y - padding, + }, + { + x: exitPoint.x + padding, + y: exitPoint.y - padding, + } + ); + break; + case "left": + paddedExitPoints.push( + { + x: exitPoint.x + padding, + y: exitPoint.y - padding, + }, + { + x: exitPoint.x + padding, + y: exitPoint.y + padding, + } + ); + break; + case "right": + paddedExitPoints.push( + { + x: exitPoint.x - padding, + y: exitPoint.y - padding, + }, + { + x: exitPoint.x - padding, + y: exitPoint.y + padding, + } + ); + break; + } + return paddedExitPoints; + } + function $c34afbc43c90cc6f$var$getPointsFromRect(rect) { + const { top: top, right: right, bottom: bottom, left: left } = rect; + return [ + { + x: left, + y: top, + }, + { + x: right, + y: top, + }, + { + x: right, + y: bottom, + }, + { + x: left, + y: bottom, + }, + ]; + } // Determine if a point is inside of a polygon. + // Based on https://github.com/substack/point-in-polygon + function $c34afbc43c90cc6f$var$isPointInPolygon(point, polygon) { + const { x: x, y: y } = point; + let inside = false; + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const xi = polygon[i].x; + const yi = polygon[i].y; + const xj = polygon[j].x; + const yj = polygon[j].y; // prettier-ignore + const intersect = + yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi; + if (intersect) inside = !inside; + } + return inside; + } // Returns a new array of points representing the convex hull of the given set of points. + // https://www.nayuki.io/page/convex-hull-algorithm + function $c34afbc43c90cc6f$var$getHull(points) { + const newPoints = points.slice(); + newPoints.sort((a, b) => { + if (a.x < b.x) return -1; + else if (a.x > b.x) return 1; + else if (a.y < b.y) return -1; + else if (a.y > b.y) return 1; + else return 0; + }); + return $c34afbc43c90cc6f$var$getHullPresorted(newPoints); + } // Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time. + function $c34afbc43c90cc6f$var$getHullPresorted(points) { + if (points.length <= 1) return points.slice(); + const upperHull = []; + for (let i = 0; i < points.length; i++) { + const p = points[i]; + while (upperHull.length >= 2) { + const q = upperHull[upperHull.length - 1]; + const r = upperHull[upperHull.length - 2]; + if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) + upperHull.pop(); + else break; + } + upperHull.push(p); + } + upperHull.pop(); + const lowerHull = []; + for (let i1 = points.length - 1; i1 >= 0; i1--) { + const p = points[i1]; + while (lowerHull.length >= 2) { + const q = lowerHull[lowerHull.length - 1]; + const r = lowerHull[lowerHull.length - 2]; + if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) + lowerHull.pop(); + else break; + } + lowerHull.push(p); + } + lowerHull.pop(); + if ( + upperHull.length === 1 && + lowerHull.length === 1 && + upperHull[0].x === lowerHull[0].x && + upperHull[0].y === lowerHull[0].y + ) + return upperHull; + else return upperHull.concat(lowerHull); + } + const $c34afbc43c90cc6f$export$2881499e37b75b9a = + $c34afbc43c90cc6f$export$f78649fb9ca566b8; + const $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 = + $c34afbc43c90cc6f$export$28c660c63b792dea; + const $c34afbc43c90cc6f$export$41fb9f06171c75f4 = + $c34afbc43c90cc6f$export$8c610744efcf8a1d; + const $c34afbc43c90cc6f$export$602eac185826482c = + $c34afbc43c90cc6f$export$7b36b8f925ab7497; + const $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 = + $c34afbc43c90cc6f$export$e9003e2be37ec060; + const $c34afbc43c90cc6f$export$21b07c8f274aebd5 = + $c34afbc43c90cc6f$export$c27ee0ad710f7559; + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js ***! + \****************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $92muK$react = __webpack_require__(/*! react */ "react"); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "useCallbackRef", + () => $28e03942f763e819$export$25bec8c6f54ee79a + ); + + /** + * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a + * prop or avoid re-executing effects when passed as a dependency + */ + function $28e03942f763e819$export$25bec8c6f54ee79a(callback) { + const callbackRef = $92muK$react.useRef(callback); + $92muK$react.useEffect(() => { + callbackRef.current = callback; + }); // https://github.com/facebook/react/issues/19240 + return $92muK$react.useMemo( + () => + (...args) => { + var _callbackRef$current; + return (_callbackRef$current = callbackRef.current) === null || + _callbackRef$current === void 0 + ? void 0 + : _callbackRef$current.call(callbackRef, ...args); + }, + [] + ); + } + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js ***! + \**********************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $ijazI$react = __webpack_require__(/*! react */ "react"); + var $ijazI$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "useControllableState", + () => $b84d42d44371bff7$export$6f32135080cb4c3 + ); + function $b84d42d44371bff7$export$6f32135080cb4c3({ + prop: prop, + defaultProp: defaultProp, + onChange = () => {}, + }) { + const [uncontrolledProp, setUncontrolledProp] = + $b84d42d44371bff7$var$useUncontrolledState({ + defaultProp: defaultProp, + onChange: onChange, + }); + const isControlled = prop !== undefined; + const value1 = isControlled ? prop : uncontrolledProp; + const handleChange = + $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); + const setValue = $ijazI$react.useCallback( + (nextValue) => { + if (isControlled) { + const setter = nextValue; + const value = + typeof nextValue === "function" ? setter(prop) : nextValue; + if (value !== prop) handleChange(value); + } else setUncontrolledProp(nextValue); + }, + [isControlled, prop, setUncontrolledProp, handleChange] + ); + return [value1, setValue]; + } + function $b84d42d44371bff7$var$useUncontrolledState({ + defaultProp: defaultProp, + onChange: onChange, + }) { + const uncontrolledState = $ijazI$react.useState(defaultProp); + const [value] = uncontrolledState; + const prevValueRef = $ijazI$react.useRef(value); + const handleChange = + $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); + $ijazI$react.useEffect(() => { + if (prevValueRef.current !== value) { + handleChange(value); + prevValueRef.current = value; + } + }, [value, prevValueRef, handleChange]); + return uncontrolledState; + } + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js ***! + \******************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $b0gz3$react = __webpack_require__(/*! react */ "react"); + var $b0gz3$radixuireactusecallbackref = __webpack_require__( + /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "useEscapeKeydown", + () => $24c84e9f83c4454f$export$3a72a57244d6e765 + ); + + /** + * Listens for when the escape key is down + */ + function $24c84e9f83c4454f$export$3a72a57244d6e765( + onEscapeKeyDownProp, + ownerDocument = globalThis === null || globalThis === void 0 + ? void 0 + : globalThis.document + ) { + const onEscapeKeyDown = + $b0gz3$radixuireactusecallbackref.useCallbackRef( + onEscapeKeyDownProp + ); + $b0gz3$react.useEffect(() => { + const handleKeyDown = (event) => { + if (event.key === "Escape") onEscapeKeyDown(event); + }; + ownerDocument.addEventListener("keydown", handleKeyDown); + return () => + ownerDocument.removeEventListener("keydown", handleKeyDown); + }, [onEscapeKeyDown, ownerDocument]); + } + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js ***! + \*****************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $caHyQ$react = __webpack_require__(/*! react */ "react"); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "useLayoutEffect", + () => $ca21affb0542a8a4$export$e5c5a5f917a5871c + ); + + /** + * On the server, React emits a warning when calling `useLayoutEffect`. + * This is because neither `useLayoutEffect` nor `useEffect` run on the server. + * We use this safe version which suppresses the warning by replacing it with a noop on the server. + * + * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect + */ + const $ca21affb0542a8a4$export$e5c5a5f917a5871c = Boolean( + globalThis === null || globalThis === void 0 + ? void 0 + : globalThis.document + ) + ? $caHyQ$react.useLayoutEffect + : () => {}; + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-use-size/dist/index.js": + /*!********************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-use-size/dist/index.js ***! + \********************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $ksDzM$react = __webpack_require__(/*! react */ "react"); + var $ksDzM$radixuireactuselayouteffect = __webpack_require__( + /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + $parcel$export( + module.exports, + "useSize", + () => $d2c1d285af17635b$export$1ab7ae714698c4b8 + ); + function $d2c1d285af17635b$export$1ab7ae714698c4b8(element) { + const [size, setSize] = $ksDzM$react.useState(undefined); + $ksDzM$radixuireactuselayouteffect.useLayoutEffect(() => { + if (element) { + // provide size as early as possible + setSize({ + width: element.offsetWidth, + height: element.offsetHeight, + }); + const resizeObserver = new ResizeObserver((entries) => { + if (!Array.isArray(entries)) return; + // Since we only observe the one element, we don't need to loop over the + // array + if (!entries.length) return; + const entry = entries[0]; + let width; + let height; + if ("borderBoxSize" in entry) { + const borderSizeEntry = entry["borderBoxSize"]; // iron out differences between browsers + const borderSize = Array.isArray(borderSizeEntry) + ? borderSizeEntry[0] + : borderSizeEntry; + width = borderSize["inlineSize"]; + height = borderSize["blockSize"]; + } else { + // for browsers that don't support `borderBoxSize` + // we calculate it ourselves to get the correct border box. + width = element.offsetWidth; + height = element.offsetHeight; + } + setSize({ + width: width, + height: height, + }); + }); + resizeObserver.observe(element, { + box: "border-box", + }); + return () => resizeObserver.unobserve(element); + } + // We only want to reset to `undefined` when the element becomes `null`, + // not if it changes to another element. + else setSize(undefined); + }, [element]); + return size; + } + + /***/ + }, + + /***/ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js ***! + \***************************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var $awrN2$babelruntimehelpersextends = __webpack_require__( + /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" + ); + var $awrN2$react = __webpack_require__(/*! react */ "react"); + var $awrN2$radixuireactprimitive = __webpack_require__( + /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" + ); + function $parcel$export(e, n, v, s) { + Object.defineProperty(e, n, { + get: v, + set: s, + enumerable: true, + configurable: true, + }); + } + function $parcel$interopDefault(a) { + return a && a.__esModule ? a.default : a; + } + $parcel$export( + module.exports, + "VisuallyHidden", + () => $685371e9c20848e2$export$439d29a4e110a164 + ); + $parcel$export( + module.exports, + "Root", + () => $685371e9c20848e2$export$be92b6f5f03c0fe9 + ); + + /* ------------------------------------------------------------------------------------------------- + * VisuallyHidden + * -----------------------------------------------------------------------------------------------*/ + const $685371e9c20848e2$var$NAME = "VisuallyHidden"; + const $685371e9c20848e2$export$439d29a4e110a164 = + /*#__PURE__*/ $awrN2$react.forwardRef((props, forwardedRef) => { + return /*#__PURE__*/ $awrN2$react.createElement( + $awrN2$radixuireactprimitive.Primitive.span, + $parcel$interopDefault($awrN2$babelruntimehelpersextends)( + {}, + props, + { + ref: forwardedRef, + style: { + // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss + position: "absolute", + border: 0, + width: 1, + height: 1, + padding: 0, + margin: -1, + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + wordWrap: "normal", + ...props.style, + }, + } + ) + ); + }); + /*#__PURE__*/ + Object.assign($685371e9c20848e2$export$439d29a4e110a164, { + displayName: $685371e9c20848e2$var$NAME, + }); + /* -----------------------------------------------------------------------------------------------*/ + const $685371e9c20848e2$export$be92b6f5f03c0fe9 = + $685371e9c20848e2$export$439d29a4e110a164; + + /***/ + }, + + /***/ "../../../node_modules/aria-hidden/dist/es2015/index.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/aria-hidden/dist/es2015/index.js ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.suppressOthers = + exports.supportsInert = + exports.inertOthers = + exports.hideOthers = + void 0; + var getDefaultParent = function (originalTarget) { + if (typeof document === "undefined") { + return null; + } + var sampleTarget = Array.isArray(originalTarget) + ? originalTarget[0] + : originalTarget; + return sampleTarget.ownerDocument.body; + }; + var counterMap = new WeakMap(); + var uncontrolledNodes = new WeakMap(); + var markerMap = {}; + var lockCount = 0; + var unwrapHost = function (node) { + return node && (node.host || unwrapHost(node.parentNode)); + }; + var correctTargets = function (parent, targets) { + return targets + .map(function (target) { + if (parent.contains(target)) { + return target; + } + var correctedTarget = unwrapHost(target); + if (correctedTarget && parent.contains(correctedTarget)) { + return correctedTarget; + } + console.error( + "aria-hidden", + target, + "in not contained inside", + parent, + ". Doing nothing" + ); + return null; + }) + .filter(function (x) { + return Boolean(x); + }); + }; + /** + * Marks everything except given node(or nodes) as aria-hidden + * @param {Element | Element[]} originalTarget - elements to keep on the page + * @param [parentNode] - top element, defaults to document.body + * @param {String} [markerName] - a special attribute to mark every node + * @param {String} [controlAttribute] - html Attribute to control + * @return {Undo} undo command + */ + var applyAttributeToOthers = function ( + originalTarget, + parentNode, + markerName, + controlAttribute + ) { + var targets = correctTargets( + parentNode, + Array.isArray(originalTarget) ? originalTarget : [originalTarget] + ); + if (!markerMap[markerName]) { + markerMap[markerName] = new WeakMap(); + } + var markerCounter = markerMap[markerName]; + var hiddenNodes = []; + var elementsToKeep = new Set(); + var elementsToStop = new Set(targets); + var keep = function (el) { + if (!el || elementsToKeep.has(el)) { + return; + } + elementsToKeep.add(el); + keep(el.parentNode); + }; + targets.forEach(keep); + var deep = function (parent) { + if (!parent || elementsToStop.has(parent)) { + return; + } + Array.prototype.forEach.call(parent.children, function (node) { + if (elementsToKeep.has(node)) { + deep(node); + } else { + var attr = node.getAttribute(controlAttribute); + var alreadyHidden = attr !== null && attr !== "false"; + var counterValue = (counterMap.get(node) || 0) + 1; + var markerValue = (markerCounter.get(node) || 0) + 1; + counterMap.set(node, counterValue); + markerCounter.set(node, markerValue); + hiddenNodes.push(node); + if (counterValue === 1 && alreadyHidden) { + uncontrolledNodes.set(node, true); + } + if (markerValue === 1) { + node.setAttribute(markerName, "true"); + } + if (!alreadyHidden) { + node.setAttribute(controlAttribute, "true"); + } + } + }); + }; + deep(parentNode); + elementsToKeep.clear(); + lockCount++; + return function () { + hiddenNodes.forEach(function (node) { + var counterValue = counterMap.get(node) - 1; + var markerValue = markerCounter.get(node) - 1; + counterMap.set(node, counterValue); + markerCounter.set(node, markerValue); + if (!counterValue) { + if (!uncontrolledNodes.has(node)) { + node.removeAttribute(controlAttribute); + } + uncontrolledNodes.delete(node); + } + if (!markerValue) { + node.removeAttribute(markerName); + } + }); + lockCount--; + if (!lockCount) { + // clear + counterMap = new WeakMap(); + counterMap = new WeakMap(); + uncontrolledNodes = new WeakMap(); + markerMap = {}; + } + }; + }; + /** + * Marks everything except given node(or nodes) as aria-hidden + * @param {Element | Element[]} originalTarget - elements to keep on the page + * @param [parentNode] - top element, defaults to document.body + * @param {String} [markerName] - a special attribute to mark every node + * @return {Undo} undo command + */ + var hideOthers = function (originalTarget, parentNode, markerName) { + if (markerName === void 0) { + markerName = "data-aria-hidden"; + } + var targets = Array.from( + Array.isArray(originalTarget) ? originalTarget : [originalTarget] + ); + var activeParentNode = parentNode || getDefaultParent(originalTarget); + if (!activeParentNode) { + return function () { + return null; + }; + } + // we should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10 + targets.push.apply( + targets, + Array.from(activeParentNode.querySelectorAll("[aria-live]")) + ); + return applyAttributeToOthers( + targets, + activeParentNode, + markerName, + "aria-hidden" + ); + }; + /** + * Marks everything except given node(or nodes) as inert + * @param {Element | Element[]} originalTarget - elements to keep on the page + * @param [parentNode] - top element, defaults to document.body + * @param {String} [markerName] - a special attribute to mark every node + * @return {Undo} undo command + */ + exports.hideOthers = hideOthers; + var inertOthers = function (originalTarget, parentNode, markerName) { + if (markerName === void 0) { + markerName = "data-inert-ed"; + } + var activeParentNode = parentNode || getDefaultParent(originalTarget); + if (!activeParentNode) { + return function () { + return null; + }; + } + return applyAttributeToOthers( + originalTarget, + activeParentNode, + markerName, + "inert" + ); + }; + /** + * @returns if current browser supports inert + */ + exports.inertOthers = inertOthers; + var supportsInert = function () { + return ( + typeof HTMLElement !== "undefined" && + HTMLElement.prototype.hasOwnProperty("inert") + ); + }; + /** + * Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way + * @param {Element | Element[]} originalTarget - elements to keep on the page + * @param [parentNode] - top element, defaults to document.body + * @param {String} [markerName] - a special attribute to mark every node + * @return {Undo} undo command + */ + exports.supportsInert = supportsInert; + var suppressOthers = function (originalTarget, parentNode, markerName) { + if (markerName === void 0) { + markerName = "data-suppressed"; + } + return (supportsInert() ? inertOthers : hideOthers)( + originalTarget, + parentNode, + markerName + ); + }; + exports.suppressOthers = suppressOthers; + + /***/ + }, + + /***/ "../../../node_modules/clsx/dist/clsx.m.js": + /*!*************************************************!*\ + !*** ../../../node_modules/clsx/dist/clsx.m.js ***! + \*************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.clsx = clsx; + exports["default"] = void 0; + function r(e) { + var t, + f, + n = ""; + if ("string" == typeof e || "number" == typeof e) n += e; + else if ("object" == typeof e) + if (Array.isArray(e)) + for (t = 0; t < e.length; t++) + e[t] && (f = r(e[t])) && (n && (n += " "), (n += f)); + else for (t in e) e[t] && (n && (n += " "), (n += t)); + return n; + } + function clsx() { + for (var e, t, f = 0, n = ""; f < arguments.length; ) + (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), (n += t)); + return n; + } + var _default = (exports["default"] = clsx); + + /***/ + }, + + /***/ "../../../node_modules/copy-to-clipboard/index.js": + /*!********************************************************!*\ + !*** ../../../node_modules/copy-to-clipboard/index.js ***! + \********************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var deselectCurrent = __webpack_require__( + /*! toggle-selection */ "../../../node_modules/toggle-selection/index.js" + ); + var clipboardToIE11Formatting = { + "text/plain": "Text", + "text/html": "Url", + default: "Text", + }; + var defaultMessage = "Copy to clipboard: #{key}, Enter"; + function format(message) { + var copyKey = + (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; + return message.replace(/#{\s*key\s*}/g, copyKey); + } + function copy(text, options) { + var debug, + message, + reselectPrevious, + range, + selection, + mark, + success = false; + if (!options) { + options = {}; + } + debug = options.debug || false; + try { + reselectPrevious = deselectCurrent(); + range = document.createRange(); + selection = document.getSelection(); + mark = document.createElement("span"); + mark.textContent = text; + // avoid screen readers from reading out loud the text + mark.ariaHidden = "true"; + // reset user styles for span element + mark.style.all = "unset"; + // prevents scrolling to the end of the page + mark.style.position = "fixed"; + mark.style.top = 0; + mark.style.clip = "rect(0, 0, 0, 0)"; + // used to preserve spaces and line breaks + mark.style.whiteSpace = "pre"; + // do not inherit user-select (it may be `none`) + mark.style.webkitUserSelect = "text"; + mark.style.MozUserSelect = "text"; + mark.style.msUserSelect = "text"; + mark.style.userSelect = "text"; + mark.addEventListener("copy", function (e) { + e.stopPropagation(); + if (options.format) { + e.preventDefault(); + if (typeof e.clipboardData === "undefined") { + // IE 11 + debug && console.warn("unable to use e.clipboardData"); + debug && console.warn("trying IE specific stuff"); + window.clipboardData.clearData(); + var format = + clipboardToIE11Formatting[options.format] || + clipboardToIE11Formatting["default"]; + window.clipboardData.setData(format, text); + } else { + // all other browsers + e.clipboardData.clearData(); + e.clipboardData.setData(options.format, text); + } + } + if (options.onCopy) { + e.preventDefault(); + options.onCopy(e.clipboardData); + } + }); + document.body.appendChild(mark); + range.selectNodeContents(mark); + selection.addRange(range); + var successful = document.execCommand("copy"); + if (!successful) { + throw new Error("copy command was unsuccessful"); + } + success = true; + } catch (err) { + debug && console.error("unable to copy using execCommand: ", err); + debug && console.warn("trying IE specific stuff"); + try { + window.clipboardData.setData(options.format || "text", text); + options.onCopy && options.onCopy(window.clipboardData); + success = true; + } catch (err) { + debug && + console.error("unable to copy using clipboardData: ", err); + debug && console.error("falling back to prompt"); + message = format( + "message" in options ? options.message : defaultMessage + ); + window.prompt(message, text); + } + } finally { + if (selection) { + if (typeof selection.removeRange == "function") { + selection.removeRange(range); + } else { + selection.removeAllRanges(); + } + } + if (mark) { + document.body.removeChild(mark); + } + reselectPrevious(); + } + return success; + } + module.exports = copy; + + /***/ + }, + + /***/ "../../../node_modules/detect-node-es/esm/browser.js": + /*!***********************************************************!*\ + !*** ../../../node_modules/detect-node-es/esm/browser.js ***! + \***********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isNode = void 0; + const isNode = (exports.isNode = false); + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/decode.js": + /*!****************************************************!*\ + !*** ../../../node_modules/entities/lib/decode.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + var __createBinding = + (void 0 && (void 0).__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ("get" in desc + ? !m.__esModule + : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = + (void 0 && (void 0).__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v, + }); + } + : function (o, v) { + o["default"] = v; + }); + var __importStar = + (void 0 && (void 0).__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if ( + k !== "default" && + Object.prototype.hasOwnProperty.call(mod, k) + ) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + var __importDefault = + (void 0 && (void 0).__importDefault) || + function (mod) { + return mod && mod.__esModule + ? mod + : { + default: mod, + }; + }; + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.decodeXML = + exports.decodeHTMLStrict = + exports.decodeHTMLAttribute = + exports.decodeHTML = + exports.determineBranch = + exports.EntityDecoder = + exports.DecodingMode = + exports.BinTrieFlags = + exports.fromCodePoint = + exports.replaceCodePoint = + exports.decodeCodePoint = + exports.xmlDecodeTree = + exports.htmlDecodeTree = + void 0; + var decode_data_html_js_1 = __importDefault( + __webpack_require__( + /*! ./generated/decode-data-html.js */ "../../../node_modules/entities/lib/generated/decode-data-html.js" + ) + ); + exports.htmlDecodeTree = decode_data_html_js_1.default; + var decode_data_xml_js_1 = __importDefault( + __webpack_require__( + /*! ./generated/decode-data-xml.js */ "../../../node_modules/entities/lib/generated/decode-data-xml.js" + ) + ); + exports.xmlDecodeTree = decode_data_xml_js_1.default; + var decode_codepoint_js_1 = __importStar( + __webpack_require__( + /*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js" + ) + ); + exports.decodeCodePoint = decode_codepoint_js_1.default; + var decode_codepoint_js_2 = __webpack_require__( + /*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js" + ); + Object.defineProperty(exports, "replaceCodePoint", { + enumerable: true, + get: function () { + return decode_codepoint_js_2.replaceCodePoint; + }, + }); + Object.defineProperty(exports, "fromCodePoint", { + enumerable: true, + get: function () { + return decode_codepoint_js_2.fromCodePoint; + }, + }); + var CharCodes; + (function (CharCodes) { + CharCodes[(CharCodes["NUM"] = 35)] = "NUM"; + CharCodes[(CharCodes["SEMI"] = 59)] = "SEMI"; + CharCodes[(CharCodes["EQUALS"] = 61)] = "EQUALS"; + CharCodes[(CharCodes["ZERO"] = 48)] = "ZERO"; + CharCodes[(CharCodes["NINE"] = 57)] = "NINE"; + CharCodes[(CharCodes["LOWER_A"] = 97)] = "LOWER_A"; + CharCodes[(CharCodes["LOWER_F"] = 102)] = "LOWER_F"; + CharCodes[(CharCodes["LOWER_X"] = 120)] = "LOWER_X"; + CharCodes[(CharCodes["LOWER_Z"] = 122)] = "LOWER_Z"; + CharCodes[(CharCodes["UPPER_A"] = 65)] = "UPPER_A"; + CharCodes[(CharCodes["UPPER_F"] = 70)] = "UPPER_F"; + CharCodes[(CharCodes["UPPER_Z"] = 90)] = "UPPER_Z"; + })(CharCodes || (CharCodes = {})); + /** Bit that needs to be set to convert an upper case ASCII character to lower case */ + var TO_LOWER_BIT = 32; + var BinTrieFlags; + (function (BinTrieFlags) { + BinTrieFlags[(BinTrieFlags["VALUE_LENGTH"] = 49152)] = "VALUE_LENGTH"; + BinTrieFlags[(BinTrieFlags["BRANCH_LENGTH"] = 16256)] = + "BRANCH_LENGTH"; + BinTrieFlags[(BinTrieFlags["JUMP_TABLE"] = 127)] = "JUMP_TABLE"; + })( + (BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {})) + ); + function isNumber(code) { + return code >= CharCodes.ZERO && code <= CharCodes.NINE; + } + function isHexadecimalCharacter(code) { + return ( + (code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F) + ); + } + function isAsciiAlphaNumeric(code) { + return ( + (code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || + isNumber(code) + ); + } + /** + * Checks if the given character is a valid end character for an entity in an attribute. + * + * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. + * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state + */ + function isEntityInAttributeInvalidEnd(code) { + return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); + } + var EntityDecoderState; + (function (EntityDecoderState) { + EntityDecoderState[(EntityDecoderState["EntityStart"] = 0)] = + "EntityStart"; + EntityDecoderState[(EntityDecoderState["NumericStart"] = 1)] = + "NumericStart"; + EntityDecoderState[(EntityDecoderState["NumericDecimal"] = 2)] = + "NumericDecimal"; + EntityDecoderState[(EntityDecoderState["NumericHex"] = 3)] = + "NumericHex"; + EntityDecoderState[(EntityDecoderState["NamedEntity"] = 4)] = + "NamedEntity"; + })(EntityDecoderState || (EntityDecoderState = {})); + var DecodingMode; + (function (DecodingMode) { + /** Entities in text nodes that can end with any character. */ + DecodingMode[(DecodingMode["Legacy"] = 0)] = "Legacy"; + /** Only allow entities terminated with a semicolon. */ + DecodingMode[(DecodingMode["Strict"] = 1)] = "Strict"; + /** Entities in attributes have limitations on ending characters. */ + DecodingMode[(DecodingMode["Attribute"] = 2)] = "Attribute"; + })( + (DecodingMode = exports.DecodingMode || (exports.DecodingMode = {})) + ); + /** + * Token decoder with support of writing partial entities. + */ + var EntityDecoder = /** @class */ (function () { + function EntityDecoder /** The tree used to decode entities. */( + decodeTree, + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + emitCodePoint /** An object that is used to produce errors. */, + errors + ) { + this.decodeTree = decodeTree; + this.emitCodePoint = emitCodePoint; + this.errors = errors; + /** The current state of the decoder. */ + this.state = EntityDecoderState.EntityStart; + /** Characters that were consumed while parsing an entity. */ + this.consumed = 1; + /** + * The result of the entity. + * + * Either the result index of a numeric entity, or the codepoint of a + * numeric entity. + */ + this.result = 0; + /** The current index in the decode tree. */ + this.treeIndex = 0; + /** The number of characters that were consumed in excess. */ + this.excess = 1; + /** The mode in which the decoder is operating. */ + this.decodeMode = DecodingMode.Strict; + } + /** Resets the instance to make it reusable. */ + EntityDecoder.prototype.startEntity = function (decodeMode) { + this.decodeMode = decodeMode; + this.state = EntityDecoderState.EntityStart; + this.result = 0; + this.treeIndex = 0; + this.excess = 1; + this.consumed = 1; + }; + /** + * Write an entity to the decoder. This can be called multiple times with partial entities. + * If the entity is incomplete, the decoder will return -1. + * + * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the + * entity is incomplete, and resume when the next string is written. + * + * @param string The string containing the entity (or a continuation of the entity). + * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.write = function (str, offset) { + switch (this.state) { + case EntityDecoderState.EntityStart: { + if (str.charCodeAt(offset) === CharCodes.NUM) { + this.state = EntityDecoderState.NumericStart; + this.consumed += 1; + return this.stateNumericStart(str, offset + 1); + } + this.state = EntityDecoderState.NamedEntity; + return this.stateNamedEntity(str, offset); + } + case EntityDecoderState.NumericStart: { + return this.stateNumericStart(str, offset); + } + case EntityDecoderState.NumericDecimal: { + return this.stateNumericDecimal(str, offset); + } + case EntityDecoderState.NumericHex: { + return this.stateNumericHex(str, offset); + } + case EntityDecoderState.NamedEntity: { + return this.stateNamedEntity(str, offset); + } + } + }; + /** + * Switches between the numeric decimal and hexadecimal states. + * + * Equivalent to the `Numeric character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNumericStart = function (str, offset) { + if (offset >= str.length) { + return -1; + } + if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { + this.state = EntityDecoderState.NumericHex; + this.consumed += 1; + return this.stateNumericHex(str, offset + 1); + } + this.state = EntityDecoderState.NumericDecimal; + return this.stateNumericDecimal(str, offset); + }; + EntityDecoder.prototype.addToNumericResult = function ( + str, + start, + end, + base + ) { + if (start !== end) { + var digitCount = end - start; + this.result = + this.result * Math.pow(base, digitCount) + + parseInt(str.substr(start, digitCount), base); + this.consumed += digitCount; + } + }; + /** + * Parses a hexadecimal numeric entity. + * + * Equivalent to the `Hexademical character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNumericHex = function (str, offset) { + var startIdx = offset; + while (offset < str.length) { + var char = str.charCodeAt(offset); + if (isNumber(char) || isHexadecimalCharacter(char)) { + offset += 1; + } else { + this.addToNumericResult(str, startIdx, offset, 16); + return this.emitNumericEntity(char, 3); + } + } + this.addToNumericResult(str, startIdx, offset, 16); + return -1; + }; + /** + * Parses a decimal numeric entity. + * + * Equivalent to the `Decimal character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNumericDecimal = function (str, offset) { + var startIdx = offset; + while (offset < str.length) { + var char = str.charCodeAt(offset); + if (isNumber(char)) { + offset += 1; + } else { + this.addToNumericResult(str, startIdx, offset, 10); + return this.emitNumericEntity(char, 2); + } + } + this.addToNumericResult(str, startIdx, offset, 10); + return -1; + }; + /** + * Validate and emit a numeric entity. + * + * Implements the logic from the `Hexademical character reference start + * state` and `Numeric character reference end state` in the HTML spec. + * + * @param lastCp The last code point of the entity. Used to see if the + * entity was terminated with a semicolon. + * @param expectedLength The minimum number of characters that should be + * consumed. Used to validate that at least one digit + * was consumed. + * @returns The number of characters that were consumed. + */ + EntityDecoder.prototype.emitNumericEntity = function ( + lastCp, + expectedLength + ) { + var _a; + // Ensure we consumed at least one digit. + if (this.consumed <= expectedLength) { + (_a = this.errors) === null || _a === void 0 + ? void 0 + : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + // Figure out if this is a legit end of the entity + if (lastCp === CharCodes.SEMI) { + this.consumed += 1; + } else if (this.decodeMode === DecodingMode.Strict) { + return 0; + } + this.emitCodePoint( + (0, decode_codepoint_js_1.replaceCodePoint)(this.result), + this.consumed + ); + if (this.errors) { + if (lastCp !== CharCodes.SEMI) { + this.errors.missingSemicolonAfterCharacterReference(); + } + this.errors.validateNumericCharacterReference(this.result); + } + return this.consumed; + }; + /** + * Parses a named entity. + * + * Equivalent to the `Named character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNamedEntity = function (str, offset) { + var decodeTree = this.decodeTree; + var current = decodeTree[this.treeIndex]; + // The mask is the number of bytes of the value, including the current byte. + var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + for (; offset < str.length; offset++, this.excess++) { + var char = str.charCodeAt(offset); + this.treeIndex = determineBranch( + decodeTree, + current, + this.treeIndex + Math.max(1, valueLength), + char + ); + if (this.treeIndex < 0) { + return this.result === 0 || + // If we are parsing an attribute + (this.decodeMode === DecodingMode.Attribute && + // We shouldn't have consumed any characters after the entity, + (valueLength === 0 || + // And there should be no invalid characters. + isEntityInAttributeInvalidEnd(char))) + ? 0 + : this.emitNotTerminatedNamedEntity(); + } + current = decodeTree[this.treeIndex]; + valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + // If the branch is a value, store it and continue + if (valueLength !== 0) { + // If the entity is terminated by a semicolon, we are done. + if (char === CharCodes.SEMI) { + return this.emitNamedEntityData( + this.treeIndex, + valueLength, + this.consumed + this.excess + ); + } + // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. + if (this.decodeMode !== DecodingMode.Strict) { + this.result = this.treeIndex; + this.consumed += this.excess; + this.excess = 0; + } + } + } + return -1; + }; + /** + * Emit a named entity that was not terminated with a semicolon. + * + * @returns The number of characters consumed. + */ + EntityDecoder.prototype.emitNotTerminatedNamedEntity = function () { + var _a; + var _b = this, + result = _b.result, + decodeTree = _b.decodeTree; + var valueLength = + (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; + this.emitNamedEntityData(result, valueLength, this.consumed); + (_a = this.errors) === null || _a === void 0 + ? void 0 + : _a.missingSemicolonAfterCharacterReference(); + return this.consumed; + }; + /** + * Emit a named entity. + * + * @param result The index of the entity in the decode tree. + * @param valueLength The number of bytes in the entity. + * @param consumed The number of characters consumed. + * + * @returns The number of characters consumed. + */ + EntityDecoder.prototype.emitNamedEntityData = function ( + result, + valueLength, + consumed + ) { + var decodeTree = this.decodeTree; + this.emitCodePoint( + valueLength === 1 + ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH + : decodeTree[result + 1], + consumed + ); + if (valueLength === 3) { + // For multi-byte values, we need to emit the second byte. + this.emitCodePoint(decodeTree[result + 2], consumed); + } + return consumed; + }; + /** + * Signal to the parser that the end of the input was reached. + * + * Remaining data will be emitted and relevant errors will be produced. + * + * @returns The number of characters consumed. + */ + EntityDecoder.prototype.end = function () { + var _a; + switch (this.state) { + case EntityDecoderState.NamedEntity: { + // Emit a named entity if we have one. + return this.result !== 0 && + (this.decodeMode !== DecodingMode.Attribute || + this.result === this.treeIndex) + ? this.emitNotTerminatedNamedEntity() + : 0; + } + // Otherwise, emit a numeric entity if we have one. + case EntityDecoderState.NumericDecimal: { + return this.emitNumericEntity(0, 2); + } + case EntityDecoderState.NumericHex: { + return this.emitNumericEntity(0, 3); + } + case EntityDecoderState.NumericStart: { + (_a = this.errors) === null || _a === void 0 + ? void 0 + : _a.absenceOfDigitsInNumericCharacterReference( + this.consumed + ); + return 0; + } + case EntityDecoderState.EntityStart: { + // Return 0 if we have no entity. + return 0; + } + } + }; + return EntityDecoder; + })(); + exports.EntityDecoder = EntityDecoder; + /** + * Creates a function that decodes entities in a string. + * + * @param decodeTree The decode tree. + * @returns A function that decodes entities in a string. + */ + function getDecoder(decodeTree) { + var ret = ""; + var decoder = new EntityDecoder(decodeTree, function (str) { + return (ret += (0, decode_codepoint_js_1.fromCodePoint)(str)); + }); + return function decodeWithTrie(str, decodeMode) { + var lastIndex = 0; + var offset = 0; + while ((offset = str.indexOf("&", offset)) >= 0) { + ret += str.slice(lastIndex, offset); + decoder.startEntity(decodeMode); + var len = decoder.write( + str, + // Skip the "&" + offset + 1 + ); + if (len < 0) { + lastIndex = offset + decoder.end(); + break; + } + lastIndex = offset + len; + // If `len` is 0, skip the current `&` and continue. + offset = len === 0 ? lastIndex + 1 : lastIndex; + } + var result = ret + str.slice(lastIndex); + // Make sure we don't keep a reference to the final string. + ret = ""; + return result; + }; + } + /** + * Determines the branch of the current node that is taken given the current + * character. This function is used to traverse the trie. + * + * @param decodeTree The trie. + * @param current The current node. + * @param nodeIdx The index right after the current node and its value. + * @param char The current character. + * @returns The index of the next node, or -1 if no branch is taken. + */ + function determineBranch(decodeTree, current, nodeIdx, char) { + var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; + var jumpOffset = current & BinTrieFlags.JUMP_TABLE; + // Case 1: Single branch encoded in jump offset + if (branchCount === 0) { + return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; + } + // Case 2: Multiple branches encoded in jump table + if (jumpOffset) { + var value = char - jumpOffset; + return value < 0 || value >= branchCount + ? -1 + : decodeTree[nodeIdx + value] - 1; + } + // Case 3: Multiple branches encoded in dictionary + // Binary search for the character. + var lo = nodeIdx; + var hi = lo + branchCount - 1; + while (lo <= hi) { + var mid = (lo + hi) >>> 1; + var midVal = decodeTree[mid]; + if (midVal < char) { + lo = mid + 1; + } else if (midVal > char) { + hi = mid - 1; + } else { + return decodeTree[mid + branchCount]; + } + } + return -1; + } + exports.determineBranch = determineBranch; + var htmlDecoder = getDecoder(decode_data_html_js_1.default); + var xmlDecoder = getDecoder(decode_data_xml_js_1.default); + /** + * Decodes an HTML string. + * + * @param str The string to decode. + * @param mode The decoding mode. + * @returns The decoded string. + */ + function decodeHTML(str, mode) { + if (mode === void 0) { + mode = DecodingMode.Legacy; + } + return htmlDecoder(str, mode); + } + exports.decodeHTML = decodeHTML; + /** + * Decodes an HTML string in an attribute. + * + * @param str The string to decode. + * @returns The decoded string. + */ + function decodeHTMLAttribute(str) { + return htmlDecoder(str, DecodingMode.Attribute); + } + exports.decodeHTMLAttribute = decodeHTMLAttribute; + /** + * Decodes an HTML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ + function decodeHTMLStrict(str) { + return htmlDecoder(str, DecodingMode.Strict); + } + exports.decodeHTMLStrict = decodeHTMLStrict; + /** + * Decodes an XML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ + function decodeXML(str) { + return xmlDecoder(str, DecodingMode.Strict); + } + exports.decodeXML = decodeXML; + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/decode_codepoint.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/entities/lib/decode_codepoint.js ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 + var _a; + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.replaceCodePoint = exports.fromCodePoint = void 0; + var decodeMap = new Map([ + [0, 65533], + // C1 Unicode control character reference replacements + [128, 8364], + [130, 8218], + [131, 402], + [132, 8222], + [133, 8230], + [134, 8224], + [135, 8225], + [136, 710], + [137, 8240], + [138, 352], + [139, 8249], + [140, 338], + [142, 381], + [145, 8216], + [146, 8217], + [147, 8220], + [148, 8221], + [149, 8226], + [150, 8211], + [151, 8212], + [152, 732], + [153, 8482], + [154, 353], + [155, 8250], + [156, 339], + [158, 382], + [159, 376], + ]); + /** + * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. + */ + exports.fromCodePoint = + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins + (_a = String.fromCodePoint) !== null && _a !== void 0 + ? _a + : function (codePoint) { + var output = ""; + if (codePoint > 0xffff) { + codePoint -= 0x10000; + output += String.fromCharCode( + ((codePoint >>> 10) & 0x3ff) | 0xd800 + ); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + output += String.fromCharCode(codePoint); + return output; + }; + /** + * Replace the given code point with a replacement character if it is a + * surrogate or is outside the valid range. Otherwise return the code + * point unchanged. + */ + function replaceCodePoint(codePoint) { + var _a; + if ( + (codePoint >= 0xd800 && codePoint <= 0xdfff) || + codePoint > 0x10ffff + ) { + return 0xfffd; + } + return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 + ? _a + : codePoint; + } + exports.replaceCodePoint = replaceCodePoint; + /** + * Replace the code point if relevant, then convert it to a string. + * + * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. + * @param codePoint The code point to decode. + * @returns The decoded code point. + */ + function decodeCodePoint(codePoint) { + return (0, exports.fromCodePoint)(replaceCodePoint(codePoint)); + } + exports["default"] = decodeCodePoint; + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/encode.js": + /*!****************************************************!*\ + !*** ../../../node_modules/entities/lib/encode.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + var __importDefault = + (void 0 && (void 0).__importDefault) || + function (mod) { + return mod && mod.__esModule + ? mod + : { + default: mod, + }; + }; + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.encodeNonAsciiHTML = exports.encodeHTML = void 0; + var encode_html_js_1 = __importDefault( + __webpack_require__( + /*! ./generated/encode-html.js */ "../../../node_modules/entities/lib/generated/encode-html.js" + ) + ); + var escape_js_1 = __webpack_require__( + /*! ./escape.js */ "../../../node_modules/entities/lib/escape.js" + ); + var htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g; + /** + * Encodes all characters in the input using HTML entities. This includes + * characters that are valid ASCII characters in HTML documents, such as `#`. + * + * To get a more compact output, consider using the `encodeNonAsciiHTML` + * function, which will only encode characters that are not valid in HTML + * documents, as well as non-ASCII characters. + * + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. + */ + function encodeHTML(data) { + return encodeHTMLTrieRe(htmlReplacer, data); + } + exports.encodeHTML = encodeHTML; + /** + * Encodes all non-ASCII characters, as well as characters not valid in HTML + * documents using HTML entities. This function will not encode characters that + * are valid in HTML documents, such as `#`. + * + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. + */ + function encodeNonAsciiHTML(data) { + return encodeHTMLTrieRe(escape_js_1.xmlReplacer, data); + } + exports.encodeNonAsciiHTML = encodeNonAsciiHTML; + function encodeHTMLTrieRe(regExp, str) { + var ret = ""; + var lastIdx = 0; + var match; + while ((match = regExp.exec(str)) !== null) { + var i = match.index; + ret += str.substring(lastIdx, i); + var char = str.charCodeAt(i); + var next = encode_html_js_1.default.get(char); + if (typeof next === "object") { + // We are in a branch. Try to match the next char. + if (i + 1 < str.length) { + var nextChar = str.charCodeAt(i + 1); + var value = + typeof next.n === "number" + ? next.n === nextChar + ? next.o + : undefined + : next.n.get(nextChar); + if (value !== undefined) { + ret += value; + lastIdx = regExp.lastIndex += 1; + continue; + } + } + next = next.v; + } + // We might have a tree node without a value; skip and use a numeric entity. + if (next !== undefined) { + ret += next; + lastIdx = i + 1; + } else { + var cp = (0, escape_js_1.getCodePoint)(str, i); + ret += "&#x".concat(cp.toString(16), ";"); + // Increase by 1 if we have a surrogate pair + lastIdx = regExp.lastIndex += Number(cp !== char); + } + } + return ret + str.substr(lastIdx); + } + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/escape.js": + /*!****************************************************!*\ + !*** ../../../node_modules/entities/lib/escape.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.escapeText = + exports.escapeAttribute = + exports.escapeUTF8 = + exports.escape = + exports.encodeXML = + exports.getCodePoint = + exports.xmlReplacer = + void 0; + exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g; + var xmlCodeMap = new Map([ + [34, """], + [38, "&"], + [39, "'"], + [60, "<"], + [62, ">"], + ]); + // For compatibility with node < 4, we wrap `codePointAt` + exports.getCodePoint = + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + String.prototype.codePointAt != null + ? function (str, index) { + return str.codePointAt(index); + } + : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + function (c, index) { + return (c.charCodeAt(index) & 0xfc00) === 0xd800 + ? (c.charCodeAt(index) - 0xd800) * 0x400 + + c.charCodeAt(index + 1) - + 0xdc00 + + 0x10000 + : c.charCodeAt(index); + }; + /** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using XML entities. + * + * If a character has no equivalent entity, a + * numeric hexadecimal reference (eg. `ü`) will be used. + */ + function encodeXML(str) { + var ret = ""; + var lastIdx = 0; + var match; + while ((match = exports.xmlReplacer.exec(str)) !== null) { + var i = match.index; + var char = str.charCodeAt(i); + var next = xmlCodeMap.get(char); + if (next !== undefined) { + ret += str.substring(lastIdx, i) + next; + lastIdx = i + 1; + } else { + ret += "" + .concat(str.substring(lastIdx, i), "&#x") + .concat((0, exports.getCodePoint)(str, i).toString(16), ";"); + // Increase by 1 if we have a surrogate pair + lastIdx = exports.xmlReplacer.lastIndex += Number( + (char & 0xfc00) === 0xd800 + ); + } + } + return ret + str.substr(lastIdx); + } + exports.encodeXML = encodeXML; + /** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using numeric hexadecimal reference (eg. `ü`). + * + * Have a look at `escapeUTF8` if you want a more concise output at the expense + * of reduced transportability. + * + * @param data String to escape. + */ + exports.escape = encodeXML; + /** + * Creates a function that escapes all characters matched by the given regular + * expression using the given map of characters to escape to their entities. + * + * @param regex Regular expression to match characters to escape. + * @param map Map of characters to escape to their entities. + * + * @returns Function that escapes all characters matched by the given regular + * expression using the given map of characters to escape to their entities. + */ + function getEscaper(regex, map) { + return function escape(data) { + var match; + var lastIdx = 0; + var result = ""; + while ((match = regex.exec(data))) { + if (lastIdx !== match.index) { + result += data.substring(lastIdx, match.index); + } + // We know that this character will be in the map. + result += map.get(match[0].charCodeAt(0)); + // Every match will be of length 1 + lastIdx = match.index + 1; + } + return result + data.substring(lastIdx); + }; + } + /** + * Encodes all characters not valid in XML documents using XML entities. + * + * Note that the output will be character-set dependent. + * + * @param data String to escape. + */ + exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap); + /** + * Encodes all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ + exports.escapeAttribute = getEscaper( + /["&\u00A0]/g, + new Map([ + [34, """], + [38, "&"], + [160, " "], + ]) + ); + /** + * Encodes all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ + exports.escapeText = getEscaper( + /[&<>\u00A0]/g, + new Map([ + [38, "&"], + [60, "<"], + [62, ">"], + [160, " "], + ]) + ); + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/generated/decode-data-html.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/entities/lib/generated/decode-data-html.js ***! + \************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + // Generated using scripts/write-decode-map.ts + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = new Uint16Array( + // prettier-ignore + "\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c".split("").map(function (c) { + return c.charCodeAt(0); +}) + ); + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/generated/decode-data-xml.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/entities/lib/generated/decode-data-xml.js ***! + \***********************************************************************/ + /***/ function (__unused_webpack_module, exports) { + // Generated using scripts/write-decode-map.ts + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = new Uint16Array( + // prettier-ignore + "\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022".split("").map(function (c) { + return c.charCodeAt(0); +}) + ); + + /***/ + }, + + /***/ "../../../node_modules/entities/lib/generated/encode-html.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/entities/lib/generated/encode-html.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + // Generated using scripts/write-encode-map.ts + Object.defineProperty(exports, "__esModule", { + value: true, + }); + function restoreDiff(arr) { + for (var i = 1; i < arr.length; i++) { + arr[i][0] += arr[i - 1][0] + 1; + } + return arr; + } + // prettier-ignore + exports["default"] = new Map( /* #__PURE__ */restoreDiff([[9, " "], [0, " "], [22, "!"], [0, """], [0, "#"], [0, "$"], [0, "%"], [0, "&"], [0, "'"], [0, "("], [0, ")"], [0, "*"], [0, "+"], [0, ","], [1, "."], [0, "/"], [10, ":"], [0, ";"], [0, { + v: "<", + n: 8402, + o: "<⃒" +}], [0, { + v: "=", + n: 8421, + o: "=⃥" +}], [0, { + v: ">", + n: 8402, + o: ">⃒" +}], [0, "?"], [0, "@"], [26, "["], [0, "\"], [0, "]"], [0, "^"], [0, "_"], [0, "`"], [5, { + n: 106, + o: "fj" +}], [20, "{"], [0, "|"], [0, "}"], [34, " "], [0, "¡"], [0, "¢"], [0, "£"], [0, "¤"], [0, "¥"], [0, "¦"], [0, "§"], [0, "¨"], [0, "©"], [0, "ª"], [0, "«"], [0, "¬"], [0, "­"], [0, "®"], [0, "¯"], [0, "°"], [0, "±"], [0, "²"], [0, "³"], [0, "´"], [0, "µ"], [0, "¶"], [0, "·"], [0, "¸"], [0, "¹"], [0, "º"], [0, "»"], [0, "¼"], [0, "½"], [0, "¾"], [0, "¿"], [0, "À"], [0, "Á"], [0, "Â"], [0, "Ã"], [0, "Ä"], [0, "Å"], [0, "Æ"], [0, "Ç"], [0, "È"], [0, "É"], [0, "Ê"], [0, "Ë"], [0, "Ì"], [0, "Í"], [0, "Î"], [0, "Ï"], [0, "Ð"], [0, "Ñ"], [0, "Ò"], [0, "Ó"], [0, "Ô"], [0, "Õ"], [0, "Ö"], [0, "×"], [0, "Ø"], [0, "Ù"], [0, "Ú"], [0, "Û"], [0, "Ü"], [0, "Ý"], [0, "Þ"], [0, "ß"], [0, "à"], [0, "á"], [0, "â"], [0, "ã"], [0, "ä"], [0, "å"], [0, "æ"], [0, "ç"], [0, "è"], [0, "é"], [0, "ê"], [0, "ë"], [0, "ì"], [0, "í"], [0, "î"], [0, "ï"], [0, "ð"], [0, "ñ"], [0, "ò"], [0, "ó"], [0, "ô"], [0, "õ"], [0, "ö"], [0, "÷"], [0, "ø"], [0, "ù"], [0, "ú"], [0, "û"], [0, "ü"], [0, "ý"], [0, "þ"], [0, "ÿ"], [0, "Ā"], [0, "ā"], [0, "Ă"], [0, "ă"], [0, "Ą"], [0, "ą"], [0, "Ć"], [0, "ć"], [0, "Ĉ"], [0, "ĉ"], [0, "Ċ"], [0, "ċ"], [0, "Č"], [0, "č"], [0, "Ď"], [0, "ď"], [0, "Đ"], [0, "đ"], [0, "Ē"], [0, "ē"], [2, "Ė"], [0, "ė"], [0, "Ę"], [0, "ę"], [0, "Ě"], [0, "ě"], [0, "Ĝ"], [0, "ĝ"], [0, "Ğ"], [0, "ğ"], [0, "Ġ"], [0, "ġ"], [0, "Ģ"], [1, "Ĥ"], [0, "ĥ"], [0, "Ħ"], [0, "ħ"], [0, "Ĩ"], [0, "ĩ"], [0, "Ī"], [0, "ī"], [2, "Į"], [0, "į"], [0, "İ"], [0, "ı"], [0, "IJ"], [0, "ij"], [0, "Ĵ"], [0, "ĵ"], [0, "Ķ"], [0, "ķ"], [0, "ĸ"], [0, "Ĺ"], [0, "ĺ"], [0, "Ļ"], [0, "ļ"], [0, "Ľ"], [0, "ľ"], [0, "Ŀ"], [0, "ŀ"], [0, "Ł"], [0, "ł"], [0, "Ń"], [0, "ń"], [0, "Ņ"], [0, "ņ"], [0, "Ň"], [0, "ň"], [0, "ʼn"], [0, "Ŋ"], [0, "ŋ"], [0, "Ō"], [0, "ō"], [2, "Ő"], [0, "ő"], [0, "Œ"], [0, "œ"], [0, "Ŕ"], [0, "ŕ"], [0, "Ŗ"], [0, "ŗ"], [0, "Ř"], [0, "ř"], [0, "Ś"], [0, "ś"], [0, "Ŝ"], [0, "ŝ"], [0, "Ş"], [0, "ş"], [0, "Š"], [0, "š"], [0, "Ţ"], [0, "ţ"], [0, "Ť"], [0, "ť"], [0, "Ŧ"], [0, "ŧ"], [0, "Ũ"], [0, "ũ"], [0, "Ū"], [0, "ū"], [0, "Ŭ"], [0, "ŭ"], [0, "Ů"], [0, "ů"], [0, "Ű"], [0, "ű"], [0, "Ų"], [0, "ų"], [0, "Ŵ"], [0, "ŵ"], [0, "Ŷ"], [0, "ŷ"], [0, "Ÿ"], [0, "Ź"], [0, "ź"], [0, "Ż"], [0, "ż"], [0, "Ž"], [0, "ž"], [19, "ƒ"], [34, "Ƶ"], [63, "ǵ"], [65, "ȷ"], [142, "ˆ"], [0, "ˇ"], [16, "˘"], [0, "˙"], [0, "˚"], [0, "˛"], [0, "˜"], [0, "˝"], [51, "̑"], [127, "Α"], [0, "Β"], [0, "Γ"], [0, "Δ"], [0, "Ε"], [0, "Ζ"], [0, "Η"], [0, "Θ"], [0, "Ι"], [0, "Κ"], [0, "Λ"], [0, "Μ"], [0, "Ν"], [0, "Ξ"], [0, "Ο"], [0, "Π"], [0, "Ρ"], [1, "Σ"], [0, "Τ"], [0, "Υ"], [0, "Φ"], [0, "Χ"], [0, "Ψ"], [0, "Ω"], [7, "α"], [0, "β"], [0, "γ"], [0, "δ"], [0, "ε"], [0, "ζ"], [0, "η"], [0, "θ"], [0, "ι"], [0, "κ"], [0, "λ"], [0, "μ"], [0, "ν"], [0, "ξ"], [0, "ο"], [0, "π"], [0, "ρ"], [0, "ς"], [0, "σ"], [0, "τ"], [0, "υ"], [0, "φ"], [0, "χ"], [0, "ψ"], [0, "ω"], [7, "ϑ"], [0, "ϒ"], [2, "ϕ"], [0, "ϖ"], [5, "Ϝ"], [0, "ϝ"], [18, "ϰ"], [0, "ϱ"], [3, "ϵ"], [0, "϶"], [10, "Ё"], [0, "Ђ"], [0, "Ѓ"], [0, "Є"], [0, "Ѕ"], [0, "І"], [0, "Ї"], [0, "Ј"], [0, "Љ"], [0, "Њ"], [0, "Ћ"], [0, "Ќ"], [1, "Ў"], [0, "Џ"], [0, "А"], [0, "Б"], [0, "В"], [0, "Г"], [0, "Д"], [0, "Е"], [0, "Ж"], [0, "З"], [0, "И"], [0, "Й"], [0, "К"], [0, "Л"], [0, "М"], [0, "Н"], [0, "О"], [0, "П"], [0, "Р"], [0, "С"], [0, "Т"], [0, "У"], [0, "Ф"], [0, "Х"], [0, "Ц"], [0, "Ч"], [0, "Ш"], [0, "Щ"], [0, "Ъ"], [0, "Ы"], [0, "Ь"], [0, "Э"], [0, "Ю"], [0, "Я"], [0, "а"], [0, "б"], [0, "в"], [0, "г"], [0, "д"], [0, "е"], [0, "ж"], [0, "з"], [0, "и"], [0, "й"], [0, "к"], [0, "л"], [0, "м"], [0, "н"], [0, "о"], [0, "п"], [0, "р"], [0, "с"], [0, "т"], [0, "у"], [0, "ф"], [0, "х"], [0, "ц"], [0, "ч"], [0, "ш"], [0, "щ"], [0, "ъ"], [0, "ы"], [0, "ь"], [0, "э"], [0, "ю"], [0, "я"], [1, "ё"], [0, "ђ"], [0, "ѓ"], [0, "є"], [0, "ѕ"], [0, "і"], [0, "ї"], [0, "ј"], [0, "љ"], [0, "њ"], [0, "ћ"], [0, "ќ"], [1, "ў"], [0, "џ"], [7074, " "], [0, " "], [0, " "], [0, " "], [1, " "], [0, " "], [0, " "], [0, " "], [0, "​"], [0, "‌"], [0, "‍"], [0, "‎"], [0, "‏"], [0, "‐"], [2, "–"], [0, "—"], [0, "―"], [0, "‖"], [1, "‘"], [0, "’"], [0, "‚"], [1, "“"], [0, "”"], [0, "„"], [1, "†"], [0, "‡"], [0, "•"], [2, "‥"], [0, "…"], [9, "‰"], [0, "‱"], [0, "′"], [0, "″"], [0, "‴"], [0, "‵"], [3, "‹"], [0, "›"], [3, "‾"], [2, "⁁"], [1, "⁃"], [0, "⁄"], [10, "⁏"], [7, "⁗"], [7, { + v: " ", + n: 8202, + o: "  " +}], [0, "⁠"], [0, "⁡"], [0, "⁢"], [0, "⁣"], [72, "€"], [46, "⃛"], [0, "⃜"], [37, "ℂ"], [2, "℅"], [4, "ℊ"], [0, "ℋ"], [0, "ℌ"], [0, "ℍ"], [0, "ℎ"], [0, "ℏ"], [0, "ℐ"], [0, "ℑ"], [0, "ℒ"], [0, "ℓ"], [1, "ℕ"], [0, "№"], [0, "℗"], [0, "℘"], [0, "ℙ"], [0, "ℚ"], [0, "ℛ"], [0, "ℜ"], [0, "ℝ"], [0, "℞"], [3, "™"], [1, "ℤ"], [2, "℧"], [0, "ℨ"], [0, "℩"], [2, "ℬ"], [0, "ℭ"], [1, "ℯ"], [0, "ℰ"], [0, "ℱ"], [1, "ℳ"], [0, "ℴ"], [0, "ℵ"], [0, "ℶ"], [0, "ℷ"], [0, "ℸ"], [12, "ⅅ"], [0, "ⅆ"], [0, "ⅇ"], [0, "ⅈ"], [10, "⅓"], [0, "⅔"], [0, "⅕"], [0, "⅖"], [0, "⅗"], [0, "⅘"], [0, "⅙"], [0, "⅚"], [0, "⅛"], [0, "⅜"], [0, "⅝"], [0, "⅞"], [49, "←"], [0, "↑"], [0, "→"], [0, "↓"], [0, "↔"], [0, "↕"], [0, "↖"], [0, "↗"], [0, "↘"], [0, "↙"], [0, "↚"], [0, "↛"], [1, { + v: "↝", + n: 824, + o: "↝̸" +}], [0, "↞"], [0, "↟"], [0, "↠"], [0, "↡"], [0, "↢"], [0, "↣"], [0, "↤"], [0, "↥"], [0, "↦"], [0, "↧"], [1, "↩"], [0, "↪"], [0, "↫"], [0, "↬"], [0, "↭"], [0, "↮"], [1, "↰"], [0, "↱"], [0, "↲"], [0, "↳"], [1, "↵"], [0, "↶"], [0, "↷"], [2, "↺"], [0, "↻"], [0, "↼"], [0, "↽"], [0, "↾"], [0, "↿"], [0, "⇀"], [0, "⇁"], [0, "⇂"], [0, "⇃"], [0, "⇄"], [0, "⇅"], [0, "⇆"], [0, "⇇"], [0, "⇈"], [0, "⇉"], [0, "⇊"], [0, "⇋"], [0, "⇌"], [0, "⇍"], [0, "⇎"], [0, "⇏"], [0, "⇐"], [0, "⇑"], [0, "⇒"], [0, "⇓"], [0, "⇔"], [0, "⇕"], [0, "⇖"], [0, "⇗"], [0, "⇘"], [0, "⇙"], [0, "⇚"], [0, "⇛"], [1, "⇝"], [6, "⇤"], [0, "⇥"], [15, "⇵"], [7, "⇽"], [0, "⇾"], [0, "⇿"], [0, "∀"], [0, "∁"], [0, { + v: "∂", + n: 824, + o: "∂̸" +}], [0, "∃"], [0, "∄"], [0, "∅"], [1, "∇"], [0, "∈"], [0, "∉"], [1, "∋"], [0, "∌"], [2, "∏"], [0, "∐"], [0, "∑"], [0, "−"], [0, "∓"], [0, "∔"], [1, "∖"], [0, "∗"], [0, "∘"], [1, "√"], [2, "∝"], [0, "∞"], [0, "∟"], [0, { + v: "∠", n: 8402, o: "∠⃒" }], [0, "∡"], [0, "∢"], [0, "∣"], [0, "∤"], [0, "∥"], [0, "∦"], [0, "∧"], [0, "∨"], [0, { @@ -12628,32183 +17234,41005 @@ exports["default"] = new Map( /* #__PURE__ */restoreDiff([[9, " "], [0, "&Ne n: new Map( /* #__PURE__ */restoreDiff([[56476, "𝒜"], [1, "𝒞"], [0, "𝒟"], [2, "𝒢"], [2, "𝒥"], [0, "𝒦"], [2, "𝒩"], [0, "𝒪"], [0, "𝒫"], [0, "𝒬"], [1, "𝒮"], [0, "𝒯"], [0, "𝒰"], [0, "𝒱"], [0, "𝒲"], [0, "𝒳"], [0, "𝒴"], [0, "𝒵"], [0, "𝒶"], [0, "𝒷"], [0, "𝒸"], [0, "𝒹"], [1, "𝒻"], [1, "𝒽"], [0, "𝒾"], [0, "𝒿"], [0, "𝓀"], [0, "𝓁"], [0, "𝓂"], [0, "𝓃"], [1, "𝓅"], [0, "𝓆"], [0, "𝓇"], [0, "𝓈"], [0, "𝓉"], [0, "𝓊"], [0, "𝓋"], [0, "𝓌"], [0, "𝓍"], [0, "𝓎"], [0, "𝓏"], [52, "𝔄"], [0, "𝔅"], [1, "𝔇"], [0, "𝔈"], [0, "𝔉"], [0, "𝔊"], [2, "𝔍"], [0, "𝔎"], [0, "𝔏"], [0, "𝔐"], [0, "𝔑"], [0, "𝔒"], [0, "𝔓"], [0, "𝔔"], [1, "𝔖"], [0, "𝔗"], [0, "𝔘"], [0, "𝔙"], [0, "𝔚"], [0, "𝔛"], [0, "𝔜"], [1, "𝔞"], [0, "𝔟"], [0, "𝔠"], [0, "𝔡"], [0, "𝔢"], [0, "𝔣"], [0, "𝔤"], [0, "𝔥"], [0, "𝔦"], [0, "𝔧"], [0, "𝔨"], [0, "𝔩"], [0, "𝔪"], [0, "𝔫"], [0, "𝔬"], [0, "𝔭"], [0, "𝔮"], [0, "𝔯"], [0, "𝔰"], [0, "𝔱"], [0, "𝔲"], [0, "𝔳"], [0, "𝔴"], [0, "𝔵"], [0, "𝔶"], [0, "𝔷"], [0, "𝔸"], [0, "𝔹"], [1, "𝔻"], [0, "𝔼"], [0, "𝔽"], [0, "𝔾"], [1, "𝕀"], [0, "𝕁"], [0, "𝕂"], [0, "𝕃"], [0, "𝕄"], [1, "𝕆"], [3, "𝕊"], [0, "𝕋"], [0, "𝕌"], [0, "𝕍"], [0, "𝕎"], [0, "𝕏"], [0, "𝕐"], [1, "𝕒"], [0, "𝕓"], [0, "𝕔"], [0, "𝕕"], [0, "𝕖"], [0, "𝕗"], [0, "𝕘"], [0, "𝕙"], [0, "𝕚"], [0, "𝕛"], [0, "𝕜"], [0, "𝕝"], [0, "𝕞"], [0, "𝕟"], [0, "𝕠"], [0, "𝕡"], [0, "𝕢"], [0, "𝕣"], [0, "𝕤"], [0, "𝕥"], [0, "𝕦"], [0, "𝕧"], [0, "𝕨"], [0, "𝕩"], [0, "𝕪"], [0, "𝕫"]])) }], [8906, "ff"], [0, "fi"], [0, "fl"], [0, "ffi"], [0, "ffl"]])); -/***/ }), + /***/ + }, + + /***/ "../../../node_modules/entities/lib/index.js": + /*!***************************************************!*\ + !*** ../../../node_modules/entities/lib/index.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.decodeXMLStrict = + exports.decodeHTML5Strict = + exports.decodeHTML4Strict = + exports.decodeHTML5 = + exports.decodeHTML4 = + exports.decodeHTMLAttribute = + exports.decodeHTMLStrict = + exports.decodeHTML = + exports.decodeXML = + exports.DecodingMode = + exports.EntityDecoder = + exports.encodeHTML5 = + exports.encodeHTML4 = + exports.encodeNonAsciiHTML = + exports.encodeHTML = + exports.escapeText = + exports.escapeAttribute = + exports.escapeUTF8 = + exports.escape = + exports.encodeXML = + exports.encode = + exports.decodeStrict = + exports.decode = + exports.EncodingMode = + exports.EntityLevel = + void 0; + var decode_js_1 = __webpack_require__( + /*! ./decode.js */ "../../../node_modules/entities/lib/decode.js" + ); + var encode_js_1 = __webpack_require__( + /*! ./encode.js */ "../../../node_modules/entities/lib/encode.js" + ); + var escape_js_1 = __webpack_require__( + /*! ./escape.js */ "../../../node_modules/entities/lib/escape.js" + ); + /** The level of entities to support. */ + var EntityLevel; + (function (EntityLevel) { + /** Support only XML entities. */ + EntityLevel[(EntityLevel["XML"] = 0)] = "XML"; + /** Support HTML entities, which are a superset of XML entities. */ + EntityLevel[(EntityLevel["HTML"] = 1)] = "HTML"; + })((EntityLevel = exports.EntityLevel || (exports.EntityLevel = {}))); + var EncodingMode; + (function (EncodingMode) { + /** + * The output is UTF-8 encoded. Only characters that need escaping within + * XML will be escaped. + */ + EncodingMode[(EncodingMode["UTF8"] = 0)] = "UTF8"; + /** + * The output consists only of ASCII characters. Characters that need + * escaping within HTML, and characters that aren't ASCII characters will + * be escaped. + */ + EncodingMode[(EncodingMode["ASCII"] = 1)] = "ASCII"; + /** + * Encode all characters that have an equivalent entity, as well as all + * characters that are not ASCII characters. + */ + EncodingMode[(EncodingMode["Extensive"] = 2)] = "Extensive"; + /** + * Encode all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + EncodingMode[(EncodingMode["Attribute"] = 3)] = "Attribute"; + /** + * Encode all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + EncodingMode[(EncodingMode["Text"] = 4)] = "Text"; + })( + (EncodingMode = exports.EncodingMode || (exports.EncodingMode = {})) + ); + /** + * Decodes a string with entities. + * + * @param data String to decode. + * @param options Decoding options. + */ + function decode(data, options) { + if (options === void 0) { + options = EntityLevel.XML; + } + var level = typeof options === "number" ? options : options.level; + if (level === EntityLevel.HTML) { + var mode = typeof options === "object" ? options.mode : undefined; + return (0, decode_js_1.decodeHTML)(data, mode); + } + return (0, decode_js_1.decodeXML)(data); + } + exports.decode = decode; + /** + * Decodes a string with entities. Does not allow missing trailing semicolons for entities. + * + * @param data String to decode. + * @param options Decoding options. + * @deprecated Use `decode` with the `mode` set to `Strict`. + */ + function decodeStrict(data, options) { + var _a; + if (options === void 0) { + options = EntityLevel.XML; + } + var opts = + typeof options === "number" + ? { + level: options, + } + : options; + (_a = opts.mode) !== null && _a !== void 0 + ? _a + : (opts.mode = decode_js_1.DecodingMode.Strict); + return decode(data, opts); + } + exports.decodeStrict = decodeStrict; + /** + * Encodes a string with entities. + * + * @param data String to encode. + * @param options Encoding options. + */ + function encode(data, options) { + if (options === void 0) { + options = EntityLevel.XML; + } + var opts = + typeof options === "number" + ? { + level: options, + } + : options; + // Mode `UTF8` just escapes XML entities + if (opts.mode === EncodingMode.UTF8) + return (0, escape_js_1.escapeUTF8)(data); + if (opts.mode === EncodingMode.Attribute) + return (0, escape_js_1.escapeAttribute)(data); + if (opts.mode === EncodingMode.Text) + return (0, escape_js_1.escapeText)(data); + if (opts.level === EntityLevel.HTML) { + if (opts.mode === EncodingMode.ASCII) { + return (0, encode_js_1.encodeNonAsciiHTML)(data); + } + return (0, encode_js_1.encodeHTML)(data); + } + // ASCII and Extensive are equivalent + return (0, escape_js_1.encodeXML)(data); + } + exports.encode = encode; + var escape_js_2 = __webpack_require__( + /*! ./escape.js */ "../../../node_modules/entities/lib/escape.js" + ); + Object.defineProperty(exports, "encodeXML", { + enumerable: true, + get: function () { + return escape_js_2.encodeXML; + }, + }); + Object.defineProperty(exports, "escape", { + enumerable: true, + get: function () { + return escape_js_2.escape; + }, + }); + Object.defineProperty(exports, "escapeUTF8", { + enumerable: true, + get: function () { + return escape_js_2.escapeUTF8; + }, + }); + Object.defineProperty(exports, "escapeAttribute", { + enumerable: true, + get: function () { + return escape_js_2.escapeAttribute; + }, + }); + Object.defineProperty(exports, "escapeText", { + enumerable: true, + get: function () { + return escape_js_2.escapeText; + }, + }); + var encode_js_2 = __webpack_require__( + /*! ./encode.js */ "../../../node_modules/entities/lib/encode.js" + ); + Object.defineProperty(exports, "encodeHTML", { + enumerable: true, + get: function () { + return encode_js_2.encodeHTML; + }, + }); + Object.defineProperty(exports, "encodeNonAsciiHTML", { + enumerable: true, + get: function () { + return encode_js_2.encodeNonAsciiHTML; + }, + }); + // Legacy aliases (deprecated) + Object.defineProperty(exports, "encodeHTML4", { + enumerable: true, + get: function () { + return encode_js_2.encodeHTML; + }, + }); + Object.defineProperty(exports, "encodeHTML5", { + enumerable: true, + get: function () { + return encode_js_2.encodeHTML; + }, + }); + var decode_js_2 = __webpack_require__( + /*! ./decode.js */ "../../../node_modules/entities/lib/decode.js" + ); + Object.defineProperty(exports, "EntityDecoder", { + enumerable: true, + get: function () { + return decode_js_2.EntityDecoder; + }, + }); + Object.defineProperty(exports, "DecodingMode", { + enumerable: true, + get: function () { + return decode_js_2.DecodingMode; + }, + }); + Object.defineProperty(exports, "decodeXML", { + enumerable: true, + get: function () { + return decode_js_2.decodeXML; + }, + }); + Object.defineProperty(exports, "decodeHTML", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTML; + }, + }); + Object.defineProperty(exports, "decodeHTMLStrict", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTMLStrict; + }, + }); + Object.defineProperty(exports, "decodeHTMLAttribute", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTMLAttribute; + }, + }); + // Legacy aliases (deprecated) + Object.defineProperty(exports, "decodeHTML4", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTML; + }, + }); + Object.defineProperty(exports, "decodeHTML5", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTML; + }, + }); + Object.defineProperty(exports, "decodeHTML4Strict", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTMLStrict; + }, + }); + Object.defineProperty(exports, "decodeHTML5Strict", { + enumerable: true, + get: function () { + return decode_js_2.decodeHTMLStrict; + }, + }); + Object.defineProperty(exports, "decodeXMLStrict", { + enumerable: true, + get: function () { + return decode_js_2.decodeXML; + }, + }); + + /***/ + }, + + /***/ "../../../node_modules/framer-motion/dist/cjs/index.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/framer-motion/dist/cjs/index.js ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + var tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var React = __webpack_require__(/*! react */ "react"); + var heyListen = __webpack_require__( + /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" + ); + var styleValueTypes = __webpack_require__( + /*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js" + ); + var popmotion = __webpack_require__( + /*! popmotion */ "../../../node_modules/popmotion/dist/popmotion.cjs.js" + ); + var sync = __webpack_require__( + /*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js" + ); + var dom = __webpack_require__( + /*! @motionone/dom */ "../../../node_modules/@motionone/dom/dist/index.es.js" + ); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e + ? e + : { + default: e, + }; + } + function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== "default") { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: function () { + return e[k]; + }, + } + ); + } + }); + } + n["default"] = e; + return Object.freeze(n); + } + var React__namespace = /*#__PURE__*/ _interopNamespace(React); + var React__default = /*#__PURE__*/ _interopDefaultLegacy(React); + var sync__default = /*#__PURE__*/ _interopDefaultLegacy(sync); + + /** + * Browser-safe usage of process + */ + var defaultEnvironment = "production"; + var env = + typeof process === "undefined" || process.env === undefined + ? defaultEnvironment + : "development" || 0; + var createDefinition = function (propNames) { + return { + isEnabled: function (props) { + return propNames.some(function (name) { + return !!props[name]; + }); + }, + }; + }; + var featureDefinitions = { + measureLayout: createDefinition(["layout", "layoutId", "drag"]), + animation: createDefinition([ + "animate", + "exit", + "variants", + "whileHover", + "whileTap", + "whileFocus", + "whileDrag", + "whileInView", + ]), + exit: createDefinition(["exit"]), + drag: createDefinition(["drag", "dragControls"]), + focus: createDefinition(["whileFocus"]), + hover: createDefinition(["whileHover", "onHoverStart", "onHoverEnd"]), + tap: createDefinition([ + "whileTap", + "onTap", + "onTapStart", + "onTapCancel", + ]), + pan: createDefinition([ + "onPan", + "onPanStart", + "onPanSessionStart", + "onPanEnd", + ]), + inView: createDefinition([ + "whileInView", + "onViewportEnter", + "onViewportLeave", + ]), + }; + function loadFeatures(features) { + for (var key in features) { + if (features[key] === null) continue; + if (key === "projectionNodeConstructor") { + featureDefinitions.projectionNodeConstructor = features[key]; + } else { + featureDefinitions[key].Component = features[key]; + } + } + } + var LazyContext = React.createContext({ + strict: false, + }); + var featureNames = Object.keys(featureDefinitions); + var numFeatures = featureNames.length; + /** + * Load features via renderless components based on the provided MotionProps. + */ + function useFeatures(props, visualElement, preloadedFeatures) { + var features = []; + var lazyContext = React.useContext(LazyContext); + if (!visualElement) return null; + /** + * If we're in development mode, check to make sure we're not rendering a motion component + * as a child of LazyMotion, as this will break the file-size benefits of using it. + */ + if (env !== "production" && preloadedFeatures && lazyContext.strict) { + heyListen.invariant( + false, + "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead." + ); + } + for (var i = 0; i < numFeatures; i++) { + var name_1 = featureNames[i]; + var _a = featureDefinitions[name_1], + isEnabled = _a.isEnabled, + Component = _a.Component; + /** + * It might be possible in the future to use this moment to + * dynamically request functionality. In initial tests this + * was producing a lot of duplication amongst bundles. + */ + if (isEnabled(props) && Component) { + features.push( + React__namespace.createElement( + Component, + tslib.__assign( + { + key: name_1, + }, + props, + { + visualElement: visualElement, + } + ) + ) + ); + } + } + return features; + } + + /** + * @public + */ + var MotionConfigContext = React.createContext({ + transformPagePoint: function (p) { + return p; + }, + isStatic: false, + reducedMotion: "never", + }); + var MotionContext = React.createContext({}); + function useVisualElementContext() { + return React.useContext(MotionContext).visualElement; + } + + /** + * @public + */ + var PresenceContext = React.createContext(null); + var isBrowser = typeof document !== "undefined"; + var useIsomorphicLayoutEffect = isBrowser + ? React.useLayoutEffect + : React.useEffect; + + // Does this device prefer reduced motion? Returns `null` server-side. + var prefersReducedMotion = { + current: null, + }; + var hasDetected = false; + function initPrefersReducedMotion() { + hasDetected = true; + if (!isBrowser) return; + if (window.matchMedia) { + var motionMediaQuery_1 = window.matchMedia( + "(prefers-reduced-motion)" + ); + var setReducedMotionPreferences = function () { + return (prefersReducedMotion.current = + motionMediaQuery_1.matches); + }; + motionMediaQuery_1.addListener(setReducedMotionPreferences); + setReducedMotionPreferences(); + } else { + prefersReducedMotion.current = false; + } + } + /** + * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. + * + * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing + * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. + * + * It will actively respond to changes and re-render your components with the latest setting. + * + * ```jsx + * export function Sidebar({ isOpen }) { + * const shouldReduceMotion = useReducedMotion() + * const closedX = shouldReduceMotion ? 0 : "-100%" + * + * return ( + * + * ) + * } + * ``` + * + * @return boolean + * + * @public + */ + function useReducedMotion() { + /** + * Lazy initialisation of prefersReducedMotion + */ + !hasDetected && initPrefersReducedMotion(); + var _a = tslib.__read( + React.useState(prefersReducedMotion.current), + 1 + ), + shouldReduceMotion = _a[0]; + /** + * TODO See if people miss automatically updating shouldReduceMotion setting + */ + return shouldReduceMotion; + } + function useReducedMotionConfig() { + var reducedMotionPreference = useReducedMotion(); + var reducedMotion = + React.useContext(MotionConfigContext).reducedMotion; + if (reducedMotion === "never") { + return false; + } else if (reducedMotion === "always") { + return true; + } else { + return reducedMotionPreference; + } + } + function useVisualElement( + Component, + visualState, + props, + createVisualElement + ) { + var lazyContext = React.useContext(LazyContext); + var parent = useVisualElementContext(); + var presenceContext = React.useContext(PresenceContext); + var shouldReduceMotion = useReducedMotionConfig(); + var visualElementRef = React.useRef(undefined); + /** + * If we haven't preloaded a renderer, check to see if we have one lazy-loaded + */ + if (!createVisualElement) createVisualElement = lazyContext.renderer; + if (!visualElementRef.current && createVisualElement) { + visualElementRef.current = createVisualElement(Component, { + visualState: visualState, + parent: parent, + props: props, + presenceId: + presenceContext === null || presenceContext === void 0 + ? void 0 + : presenceContext.id, + blockInitialAnimation: + (presenceContext === null || presenceContext === void 0 + ? void 0 + : presenceContext.initial) === false, + shouldReduceMotion: shouldReduceMotion, + }); + } + var visualElement = visualElementRef.current; + useIsomorphicLayoutEffect(function () { + visualElement === null || visualElement === void 0 + ? void 0 + : visualElement.syncRender(); + }); + React.useEffect(function () { + var _a; + (_a = + visualElement === null || visualElement === void 0 + ? void 0 + : visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.animateChanges(); + }); + useIsomorphicLayoutEffect(function () { + return function () { + return visualElement === null || visualElement === void 0 + ? void 0 + : visualElement.notifyUnmount(); + }; + }, []); + return visualElement; + } + function isRefObject(ref) { + return ( + typeof ref === "object" && + Object.prototype.hasOwnProperty.call(ref, "current") + ); + } + + /** + * Creates a ref function that, when called, hydrates the provided + * external ref and VisualElement. + */ + function useMotionRef(visualState, visualElement, externalRef) { + return React.useCallback( + function (instance) { + var _a; + instance && + ((_a = visualState.mount) === null || _a === void 0 + ? void 0 + : _a.call(visualState, instance)); + if (visualElement) { + instance + ? visualElement.mount(instance) + : visualElement.unmount(); + } + if (externalRef) { + if (typeof externalRef === "function") { + externalRef(instance); + } else if (isRefObject(externalRef)) { + externalRef.current = instance; + } + } + }, + /** + * Only pass a new ref callback to React if we've received a visual element + * factory. Otherwise we'll be mounting/remounting every time externalRef + * or other dependencies change. + */ + [visualElement] + ); + } + + /** + * Decides if the supplied variable is an array of variant labels + */ + function isVariantLabels(v) { + return Array.isArray(v); + } + /** + * Decides if the supplied variable is variant label + */ + function isVariantLabel(v) { + return typeof v === "string" || isVariantLabels(v); + } + /** + * Creates an object containing the latest state of every MotionValue on a VisualElement + */ + function getCurrent(visualElement) { + var current = {}; + visualElement.forEachValue(function (value, key) { + return (current[key] = value.get()); + }); + return current; + } + /** + * Creates an object containing the latest velocity of every MotionValue on a VisualElement + */ + function getVelocity$1(visualElement) { + var velocity = {}; + visualElement.forEachValue(function (value, key) { + return (velocity[key] = value.getVelocity()); + }); + return velocity; + } + function resolveVariantFromProps( + props, + definition, + custom, + currentValues, + currentVelocity + ) { + var _a; + if (currentValues === void 0) { + currentValues = {}; + } + if (currentVelocity === void 0) { + currentVelocity = {}; + } + /** + * If the variant definition is a function, resolve. + */ + if (typeof definition === "function") { + definition = definition( + custom !== null && custom !== void 0 ? custom : props.custom, + currentValues, + currentVelocity + ); + } + /** + * If the variant definition is a variant label, or + * the function returned a variant label, resolve. + */ + if (typeof definition === "string") { + definition = + (_a = props.variants) === null || _a === void 0 + ? void 0 + : _a[definition]; + } + /** + * At this point we've resolved both functions and variant labels, + * but the resolved variant label might itself have been a function. + * If so, resolve. This can only have returned a valid target object. + */ + if (typeof definition === "function") { + definition = definition( + custom !== null && custom !== void 0 ? custom : props.custom, + currentValues, + currentVelocity + ); + } + return definition; + } + function resolveVariant(visualElement, definition, custom) { + var props = visualElement.getProps(); + return resolveVariantFromProps( + props, + definition, + custom !== null && custom !== void 0 ? custom : props.custom, + getCurrent(visualElement), + getVelocity$1(visualElement) + ); + } + function checkIfControllingVariants(props) { + var _a; + return ( + typeof ((_a = props.animate) === null || _a === void 0 + ? void 0 + : _a.start) === "function" || + isVariantLabel(props.initial) || + isVariantLabel(props.animate) || + isVariantLabel(props.whileHover) || + isVariantLabel(props.whileDrag) || + isVariantLabel(props.whileTap) || + isVariantLabel(props.whileFocus) || + isVariantLabel(props.exit) + ); + } + function checkIfVariantNode(props) { + return Boolean(checkIfControllingVariants(props) || props.variants); + } + function getCurrentTreeVariants(props, context) { + if (checkIfControllingVariants(props)) { + var initial = props.initial, + animate = props.animate; + return { + initial: + initial === false || isVariantLabel(initial) + ? initial + : undefined, + animate: isVariantLabel(animate) ? animate : undefined, + }; + } + return props.inherit !== false ? context : {}; + } + function useCreateMotionContext(props) { + var _a = getCurrentTreeVariants( + props, + React.useContext(MotionContext) + ), + initial = _a.initial, + animate = _a.animate; + return React.useMemo( + function () { + return { + initial: initial, + animate: animate, + }; + }, + [ + variantLabelsAsDependency(initial), + variantLabelsAsDependency(animate), + ] + ); + } + function variantLabelsAsDependency(prop) { + return Array.isArray(prop) ? prop.join(" ") : prop; + } + + /** + * Creates a constant value over the lifecycle of a component. + * + * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer + * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` + * you can ensure that initialisers don't execute twice or more. + */ + function useConstant(init) { + var ref = React.useRef(null); + if (ref.current === null) { + ref.current = init(); + } + return ref.current; + } + + /** + * This should only ever be modified on the client otherwise it'll + * persist through server requests. If we need instanced states we + * could lazy-init via root. + */ + var globalProjectionState = { + /** + * Global flag as to whether the tree has animated since the last time + * we resized the window + */ + hasAnimatedSinceResize: true, + /** + * We set this to true once, on the first update. Any nodes added to the tree beyond that + * update will be given a `data-projection-id` attribute. + */ + hasEverUpdated: false, + }; + var id$1 = 1; + function useProjectionId() { + return useConstant(function () { + if (globalProjectionState.hasEverUpdated) { + return id$1++; + } + }); + } + var LayoutGroupContext = React.createContext({}); + + /** + * Internal, exported only for usage in Framer + */ + var SwitchLayoutGroupContext = React.createContext({}); + function useProjection( + projectionId, + _a, + visualElement, + ProjectionNodeConstructor + ) { + var _b; + var layoutId = _a.layoutId, + layout = _a.layout, + drag = _a.drag, + dragConstraints = _a.dragConstraints, + layoutScroll = _a.layoutScroll; + var initialPromotionConfig = React.useContext( + SwitchLayoutGroupContext + ); + if ( + !ProjectionNodeConstructor || + !visualElement || + (visualElement === null || visualElement === void 0 + ? void 0 + : visualElement.projection) + ) { + return; + } + visualElement.projection = new ProjectionNodeConstructor( + projectionId, + visualElement.getLatestValues(), + (_b = visualElement.parent) === null || _b === void 0 + ? void 0 + : _b.projection + ); + visualElement.projection.setOptions({ + layoutId: layoutId, + layout: layout, + alwaysMeasureLayout: + Boolean(drag) || + (dragConstraints && isRefObject(dragConstraints)), + visualElement: visualElement, + scheduleRender: function () { + return visualElement.scheduleRender(); + }, + /** + * TODO: Update options in an effect. This could be tricky as it'll be too late + * to update by the time layout animations run. + * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, + * ensuring it gets called if there's no potential layout animations. + * + */ + animationType: typeof layout === "string" ? layout : "both", + initialPromotionConfig: initialPromotionConfig, + layoutScroll: layoutScroll, + }); + } + var VisualElementHandler = /** @class */ (function (_super) { + tslib.__extends(VisualElementHandler, _super); + function VisualElementHandler() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + /** + * Update visual element props as soon as we know this update is going to be commited. + */ + VisualElementHandler.prototype.getSnapshotBeforeUpdate = function () { + this.updateProps(); + return null; + }; + VisualElementHandler.prototype.componentDidUpdate = function () {}; + VisualElementHandler.prototype.updateProps = function () { + var _a = this.props, + visualElement = _a.visualElement, + props = _a.props; + if (visualElement) visualElement.setProps(props); + }; + VisualElementHandler.prototype.render = function () { + return this.props.children; + }; + return VisualElementHandler; + })(React__default["default"].Component); + + /** + * Create a `motion` component. + * + * This function accepts a Component argument, which can be either a string (ie "div" + * for `motion.div`), or an actual React component. + * + * Alongside this is a config option which provides a way of rendering the provided + * component "offline", or outside the React render cycle. + */ + function createMotionComponent(_a) { + var preloadedFeatures = _a.preloadedFeatures, + createVisualElement = _a.createVisualElement, + projectionNodeConstructor = _a.projectionNodeConstructor, + useRender = _a.useRender, + useVisualState = _a.useVisualState, + Component = _a.Component; + preloadedFeatures && loadFeatures(preloadedFeatures); + function MotionComponent(props, externalRef) { + var layoutId = useLayoutId(props); + props = tslib.__assign(tslib.__assign({}, props), { + layoutId: layoutId, + }); + /** + * If we're rendering in a static environment, we only visually update the component + * as a result of a React-rerender rather than interactions or animations. This + * means we don't need to load additional memory structures like VisualElement, + * or any gesture/animation features. + */ + var config = React.useContext(MotionConfigContext); + var features = null; + var context = useCreateMotionContext(props); + /** + * Create a unique projection ID for this component. If a new component is added + * during a layout animation we'll use this to query the DOM and hydrate its ref early, allowing + * us to measure it as soon as any layout effect flushes pending layout animations. + * + * Performance note: It'd be better not to have to search the DOM for these elements. + * For newly-entering components it could be enough to only correct treeScale, in which + * case we could mount in a scale-correction mode. This wouldn't be enough for + * shared element transitions however. Perhaps for those we could revert to a root node + * that gets forceRendered and layout animations are triggered on its layout effect. + */ + var projectionId = config.isStatic ? undefined : useProjectionId(); + /** + * + */ + var visualState = useVisualState(props, config.isStatic); + if (!config.isStatic && isBrowser) { + /** + * Create a VisualElement for this component. A VisualElement provides a common + * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as + * providing a way of rendering to these APIs outside of the React render loop + * for more performant animations and interactions + */ + context.visualElement = useVisualElement( + Component, + visualState, + tslib.__assign(tslib.__assign({}, config), props), + createVisualElement + ); + useProjection( + projectionId, + props, + context.visualElement, + projectionNodeConstructor || + featureDefinitions.projectionNodeConstructor + ); + /** + * Load Motion gesture and animation features. These are rendered as renderless + * components so each feature can optionally make use of React lifecycle methods. + */ + features = useFeatures( + props, + context.visualElement, + preloadedFeatures + ); + } + /** + * The mount order and hierarchy is specific to ensure our element ref + * is hydrated by the time features fire their effects. + */ + return React__namespace.createElement( + VisualElementHandler, + { + visualElement: context.visualElement, + props: tslib.__assign(tslib.__assign({}, config), props), + }, + features, + React__namespace.createElement( + MotionContext.Provider, + { + value: context, + }, + useRender( + Component, + props, + projectionId, + useMotionRef(visualState, context.visualElement, externalRef), + visualState, + config.isStatic, + context.visualElement + ) + ) + ); + } + return React.forwardRef(MotionComponent); + } + function useLayoutId(_a) { + var _b; + var layoutId = _a.layoutId; + var layoutGroupId = + (_b = React.useContext(LayoutGroupContext)) === null || + _b === void 0 + ? void 0 + : _b.id; + return layoutGroupId && layoutId !== undefined + ? layoutGroupId + "-" + layoutId + : layoutId; + } + + /** + * Convert any React component into a `motion` component. The provided component + * **must** use `React.forwardRef` to the underlying DOM component you want to animate. + * + * ```jsx + * const Component = React.forwardRef((props, ref) => { + * return
+ * }) + * + * const MotionComponent = motion(Component) + * ``` + * + * @public + */ + function createMotionProxy(createConfig) { + function custom(Component, customMotionComponentConfig) { + if (customMotionComponentConfig === void 0) { + customMotionComponentConfig = {}; + } + return createMotionComponent( + createConfig(Component, customMotionComponentConfig) + ); + } + if (typeof Proxy === "undefined") { + return custom; + } + /** + * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. + * Rather than generating them anew every render. + */ + var componentCache = new Map(); + return new Proxy(custom, { + /** + * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. + * The prop name is passed through as `key` and we can use that to generate a `motion` + * DOM component with that name. + */ + get: function (_target, key) { + /** + * If this element doesn't exist in the component cache, create it and cache. + */ + if (!componentCache.has(key)) { + componentCache.set(key, custom(key)); + } + return componentCache.get(key); + }, + }); + } + + /** + * We keep these listed seperately as we use the lowercase tag names as part + * of the runtime bundle to detect SVG components + */ + var lowercaseSVGElements = [ + "animate", + "circle", + "defs", + "desc", + "ellipse", + "g", + "image", + "line", + "filter", + "marker", + "mask", + "metadata", + "path", + "pattern", + "polygon", + "polyline", + "rect", + "stop", + "svg", + "switch", + "symbol", + "text", + "tspan", + "use", + "view", + ]; + function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || + /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-") + ) { + return false; + } else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || + /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/.test(Component) + ) { + return true; + } + return false; + } + var scaleCorrectors = {}; + function addScaleCorrector(correctors) { + Object.assign(scaleCorrectors, correctors); + } + + /** + * A list of all transformable axes. We'll use this list to generated a version + * of each axes for each transform. + */ + var transformAxes = ["", "X", "Y", "Z"]; + /** + * An ordered array of each transformable value. By default, transform values + * will be sorted to this order. + */ + var order = ["translate", "scale", "rotate", "skew"]; + /** + * Generate a list of every possible transform key. + */ + var transformProps = ["transformPerspective", "x", "y", "z"]; + order.forEach(function (operationKey) { + return transformAxes.forEach(function (axesKey) { + return transformProps.push(operationKey + axesKey); + }); + }); + /** + * A function to use with Array.sort to sort transform keys by their default order. + */ + function sortTransformProps(a, b) { + return transformProps.indexOf(a) - transformProps.indexOf(b); + } + /** + * A quick lookup for transform props. + */ + var transformPropSet = new Set(transformProps); + function isTransformProp(key) { + return transformPropSet.has(key); + } + /** + * A quick lookup for transform origin props + */ + var transformOriginProps = new Set(["originX", "originY", "originZ"]); + function isTransformOriginProp(key) { + return transformOriginProps.has(key); + } + function isForcedMotionValue(key, _a) { + var layout = _a.layout, + layoutId = _a.layoutId; + return ( + isTransformProp(key) || + isTransformOriginProp(key) || + ((layout || layoutId !== undefined) && + (!!scaleCorrectors[key] || key === "opacity")) + ); + } + var isMotionValue = function (value) { + return Boolean( + value !== null && typeof value === "object" && value.getVelocity + ); + }; + var translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective", + }; + /** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ + function buildTransform(_a, _b, transformIsDefault, transformTemplate) { + var transform = _a.transform, + transformKeys = _a.transformKeys; + var _c = _b.enableHardwareAcceleration, + enableHardwareAcceleration = _c === void 0 ? true : _c, + _d = _b.allowTransformNone, + allowTransformNone = _d === void 0 ? true : _d; + // The transform string we're going to build into. + var transformString = ""; + // Transform keys into their default order - this will determine the output order. + transformKeys.sort(sortTransformProps); + // Track whether the defined transform has a defined z so we don't add a + // second to enable hardware acceleration + var transformHasZ = false; + // Loop over each transform and build them into transformString + var numTransformKeys = transformKeys.length; + for (var i = 0; i < numTransformKeys; i++) { + var key = transformKeys[i]; + transformString += "" + .concat(translateAlias[key] || key, "(") + .concat(transform[key], ") "); + if (key === "z") transformHasZ = true; + } + if (!transformHasZ && enableHardwareAcceleration) { + transformString += "translateZ(0)"; + } else { + transformString = transformString.trim(); + } + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate( + transform, + transformIsDefault ? "" : transformString + ); + } else if (allowTransformNone && transformIsDefault) { + transformString = "none"; + } + return transformString; + } + /** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ + function buildTransformOrigin(_a) { + var _b = _a.originX, + originX = _b === void 0 ? "50%" : _b, + _c = _a.originY, + originY = _c === void 0 ? "50%" : _c, + _d = _a.originZ, + originZ = _d === void 0 ? 0 : _d; + return "".concat(originX, " ").concat(originY, " ").concat(originZ); + } + + /** + * Returns true if the provided key is a CSS variable + */ + function isCSSVariable$1(key) { + return key.startsWith("--"); + } + + /** + * Provided a value and a ValueType, returns the value as that value type. + */ + var getValueAsType = function (value, type) { + return type && typeof value === "number" + ? type.transform(value) + : value; + }; + var int = tslib.__assign(tslib.__assign({}, styleValueTypes.number), { + transform: Math.round, + }); + var numberValueTypes = { + // Border props + borderWidth: styleValueTypes.px, + borderTopWidth: styleValueTypes.px, + borderRightWidth: styleValueTypes.px, + borderBottomWidth: styleValueTypes.px, + borderLeftWidth: styleValueTypes.px, + borderRadius: styleValueTypes.px, + radius: styleValueTypes.px, + borderTopLeftRadius: styleValueTypes.px, + borderTopRightRadius: styleValueTypes.px, + borderBottomRightRadius: styleValueTypes.px, + borderBottomLeftRadius: styleValueTypes.px, + // Positioning props + width: styleValueTypes.px, + maxWidth: styleValueTypes.px, + height: styleValueTypes.px, + maxHeight: styleValueTypes.px, + size: styleValueTypes.px, + top: styleValueTypes.px, + right: styleValueTypes.px, + bottom: styleValueTypes.px, + left: styleValueTypes.px, + // Spacing props + padding: styleValueTypes.px, + paddingTop: styleValueTypes.px, + paddingRight: styleValueTypes.px, + paddingBottom: styleValueTypes.px, + paddingLeft: styleValueTypes.px, + margin: styleValueTypes.px, + marginTop: styleValueTypes.px, + marginRight: styleValueTypes.px, + marginBottom: styleValueTypes.px, + marginLeft: styleValueTypes.px, + // Transform props + rotate: styleValueTypes.degrees, + rotateX: styleValueTypes.degrees, + rotateY: styleValueTypes.degrees, + rotateZ: styleValueTypes.degrees, + scale: styleValueTypes.scale, + scaleX: styleValueTypes.scale, + scaleY: styleValueTypes.scale, + scaleZ: styleValueTypes.scale, + skew: styleValueTypes.degrees, + skewX: styleValueTypes.degrees, + skewY: styleValueTypes.degrees, + distance: styleValueTypes.px, + translateX: styleValueTypes.px, + translateY: styleValueTypes.px, + translateZ: styleValueTypes.px, + x: styleValueTypes.px, + y: styleValueTypes.px, + z: styleValueTypes.px, + perspective: styleValueTypes.px, + transformPerspective: styleValueTypes.px, + opacity: styleValueTypes.alpha, + originX: styleValueTypes.progressPercentage, + originY: styleValueTypes.progressPercentage, + originZ: styleValueTypes.px, + // Misc + zIndex: int, + // SVG + fillOpacity: styleValueTypes.alpha, + strokeOpacity: styleValueTypes.alpha, + numOctaves: int, + }; + function buildHTMLStyles( + state, + latestValues, + options, + transformTemplate + ) { + var _a; + var style = state.style, + vars = state.vars, + transform = state.transform, + transformKeys = state.transformKeys, + transformOrigin = state.transformOrigin; + // Empty the transformKeys array. As we're throwing out refs to its items + // this might not be as cheap as suspected. Maybe using the array as a buffer + // with a manual incrementation would be better. + transformKeys.length = 0; + // Track whether we encounter any transform or transformOrigin values. + var hasTransform = false; + var hasTransformOrigin = false; + // Does the calculated transform essentially equal "none"? + var transformIsNone = true; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept seperately for further processing. + */ + for (var key in latestValues) { + var value = latestValues[key]; + /** + * If this is a CSS variable we don't do any further processing. + */ + if (isCSSVariable$1(key)) { + vars[key] = value; + continue; + } + // Convert the value to its default value type, ie 0 -> "0px" + var valueType = numberValueTypes[key]; + var valueAsType = getValueAsType(value, valueType); + if (isTransformProp(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + transform[key] = valueAsType; + transformKeys.push(key); + // If we already know we have a non-default transform, early return + if (!transformIsNone) continue; + // Otherwise check to see if this is a default transform + if ( + value !== + ((_a = valueType.default) !== null && _a !== void 0 ? _a : 0) + ) + transformIsNone = false; + } else if (isTransformOriginProp(key)) { + transformOrigin[key] = valueAsType; + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + } else { + style[key] = valueAsType; + } + } + if (hasTransform) { + style.transform = buildTransform( + state, + options, + transformIsNone, + transformTemplate + ); + } else if (transformTemplate) { + style.transform = transformTemplate({}, ""); + } else if (!latestValues.transform && style.transform) { + style.transform = "none"; + } + if (hasTransformOrigin) { + style.transformOrigin = buildTransformOrigin(transformOrigin); + } + } + var createHtmlRenderState = function () { + return { + style: {}, + transform: {}, + transformKeys: [], + transformOrigin: {}, + vars: {}, + }; + }; + function copyRawValuesOnly(target, source, props) { + for (var key in source) { + if ( + !isMotionValue(source[key]) && + !isForcedMotionValue(key, props) + ) { + target[key] = source[key]; + } + } + } + function useInitialMotionValues(_a, visualState, isStatic) { + var transformTemplate = _a.transformTemplate; + return React.useMemo( + function () { + var state = createHtmlRenderState(); + buildHTMLStyles( + state, + visualState, + { + enableHardwareAcceleration: !isStatic, + }, + transformTemplate + ); + var vars = state.vars, + style = state.style; + return tslib.__assign(tslib.__assign({}, vars), style); + }, + [visualState] + ); + } + function useStyle(props, visualState, isStatic) { + var styleProp = props.style || {}; + var style = {}; + /** + * Copy non-Motion Values straight into style + */ + copyRawValuesOnly(style, styleProp, props); + Object.assign( + style, + useInitialMotionValues(props, visualState, isStatic) + ); + if (props.transformValues) { + style = props.transformValues(style); + } + return style; + } + function useHTMLProps(props, visualState, isStatic) { + // The `any` isn't ideal but it is the type of createElement props argument + var htmlProps = {}; + var style = useStyle(props, visualState, isStatic); + if (Boolean(props.drag) && props.dragListener !== false) { + // Disable the ghost element when a user drags + htmlProps.draggable = false; + // Disable text selection + style.userSelect = + style.WebkitUserSelect = + style.WebkitTouchCallout = + "none"; + // Disable scrolling on the draggable direction + style.touchAction = + props.drag === true + ? "none" + : "pan-".concat(props.drag === "x" ? "y" : "x"); + } + htmlProps.style = style; + return htmlProps; + } + + /** + * A list of all valid MotionProps. + * + * @privateRemarks + * This doesn't throw if a `MotionProp` name is missing - it should. + */ + var validMotionProps = new Set([ + "initial", + "animate", + "exit", + "style", + "variants", + "transition", + "transformTemplate", + "transformValues", + "custom", + "inherit", + "layout", + "layoutId", + "layoutDependency", + "onLayoutAnimationStart", + "onLayoutAnimationComplete", + "onLayoutMeasure", + "onBeforeLayoutMeasure", + "onAnimationStart", + "onAnimationComplete", + "onUpdate", + "onDragStart", + "onDrag", + "onDragEnd", + "onMeasureDragConstraints", + "onDirectionLock", + "onDragTransitionEnd", + "drag", + "dragControls", + "dragListener", + "dragConstraints", + "dragDirectionLock", + "dragSnapToOrigin", + "_dragX", + "_dragY", + "dragElastic", + "dragMomentum", + "dragPropagation", + "dragTransition", + "whileDrag", + "onPan", + "onPanStart", + "onPanEnd", + "onPanSessionStart", + "onTap", + "onTapStart", + "onTapCancel", + "onHoverStart", + "onHoverEnd", + "whileFocus", + "whileTap", + "whileHover", + "whileInView", + "onViewportEnter", + "onViewportLeave", + "viewport", + "layoutScroll", + ]); + /** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ + function isValidMotionProp(key) { + return validMotionProps.has(key); + } + var shouldForward = function (key) { + return !isValidMotionProp(key); + }; + function loadExternalIsValidProp(isValidProp) { + if (!isValidProp) return; + // Explicitly filter our events + shouldForward = function (key) { + return key.startsWith("on") + ? !isValidMotionProp(key) + : isValidProp(key); + }; + } + /** + * Emotion and Styled Components both allow users to pass through arbitrary props to their components + * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which + * of these should be passed to the underlying DOM node. + * + * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props + * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props + * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of + * `@emotion/is-prop-valid`, however to fix this problem we need to use it. + * + * By making it an optionalDependency we can offer this functionality only in the situations where it's + * actually required. + */ + try { + /** + * We attempt to import this package but require won't be defined in esm environments, in that case + * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed + * in favour of explicit injection. + */ + loadExternalIsValidProp( + __webpack_require__( + /*! @emotion/is-prop-valid */ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js" + )["default"] + ); + } catch (_a) { + // We don't need to actually do anything here - the fallback is the existing `isPropValid`. + } + function filterProps(props, isDom, forwardMotionProps) { + var filteredProps = {}; + for (var key in props) { + if ( + shouldForward(key) || + (forwardMotionProps === true && isValidMotionProp(key)) || + (!isDom && !isValidMotionProp(key)) || + // If trying to use native HTML drag events, forward drag listeners + (props["draggable"] && key.startsWith("onDrag")) + ) { + filteredProps[key] = props[key]; + } + } + return filteredProps; + } + function calcOrigin$1(origin, offset, size) { + return typeof origin === "string" + ? origin + : styleValueTypes.px.transform(offset + size * origin); + } + /** + * The SVG transform origin defaults are different to CSS and is less intuitive, + * so we use the measured dimensions of the SVG to reconcile these. + */ + function calcSVGTransformOrigin(dimensions, originX, originY) { + var pxOriginX = calcOrigin$1(originX, dimensions.x, dimensions.width); + var pxOriginY = calcOrigin$1( + originY, + dimensions.y, + dimensions.height + ); + return "".concat(pxOriginX, " ").concat(pxOriginY); + } + var dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray", + }; + var camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray", + }; + /** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ + function buildSVGPath(attrs, length, spacing, offset, useDashCase) { + if (spacing === void 0) { + spacing = 1; + } + if (offset === void 0) { + offset = 0; + } + if (useDashCase === void 0) { + useDashCase = true; + } + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + var keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = styleValueTypes.px.transform(-offset); + // Build the dash array + var pathLength = styleValueTypes.px.transform(length); + var pathSpacing = styleValueTypes.px.transform(spacing); + attrs[keys.array] = "".concat(pathLength, " ").concat(pathSpacing); + } + + /** + * Build SVG visual attrbutes, like cx and style.transform + */ + function buildSVGAttrs(state, _a, options, transformTemplate) { + var attrX = _a.attrX, + attrY = _a.attrY, + originX = _a.originX, + originY = _a.originY, + pathLength = _a.pathLength, + _b = _a.pathSpacing, + pathSpacing = _b === void 0 ? 1 : _b, + _c = _a.pathOffset, + pathOffset = _c === void 0 ? 0 : _c, + // This is object creation, which we try to avoid per-frame. + latest = tslib.__rest(_a, [ + "attrX", + "attrY", + "originX", + "originY", + "pathLength", + "pathSpacing", + "pathOffset", + ]); + buildHTMLStyles(state, latest, options, transformTemplate); + state.attrs = state.style; + state.style = {}; + var attrs = state.attrs, + style = state.style, + dimensions = state.dimensions; + /** + * However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs + * and copy it into style. + */ + if (attrs.transform) { + if (dimensions) style.transform = attrs.transform; + delete attrs.transform; + } + // Parse transformOrigin + if ( + dimensions && + (originX !== undefined || originY !== undefined || style.transform) + ) { + style.transformOrigin = calcSVGTransformOrigin( + dimensions, + originX !== undefined ? originX : 0.5, + originY !== undefined ? originY : 0.5 + ); + } + // Treat x/y not as shortcuts but as actual attributes + if (attrX !== undefined) attrs.x = attrX; + if (attrY !== undefined) attrs.y = attrY; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } + } + var createSvgRenderState = function () { + return tslib.__assign(tslib.__assign({}, createHtmlRenderState()), { + attrs: {}, + }); + }; + function useSVGProps(props, visualState) { + var visualProps = React.useMemo( + function () { + var state = createSvgRenderState(); + buildSVGAttrs( + state, + visualState, + { + enableHardwareAcceleration: false, + }, + props.transformTemplate + ); + return tslib.__assign(tslib.__assign({}, state.attrs), { + style: tslib.__assign({}, state.style), + }); + }, + [visualState] + ); + if (props.style) { + var rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = tslib.__assign( + tslib.__assign({}, rawStyles), + visualProps.style + ); + } + return visualProps; + } + function createUseRender(forwardMotionProps) { + if (forwardMotionProps === void 0) { + forwardMotionProps = false; + } + var useRender = function ( + Component, + props, + projectionId, + ref, + _a, + isStatic + ) { + var latestValues = _a.latestValues; + var useVisualProps = isSVGComponent(Component) + ? useSVGProps + : useHTMLProps; + var visualProps = useVisualProps(props, latestValues, isStatic); + var filteredProps = filterProps( + props, + typeof Component === "string", + forwardMotionProps + ); + var elementProps = tslib.__assign( + tslib.__assign(tslib.__assign({}, filteredProps), visualProps), + { + ref: ref, + } + ); + if (projectionId) { + elementProps["data-projection-id"] = projectionId; + } + return React.createElement(Component, elementProps); + }; + return useRender; + } + var CAMEL_CASE_PATTERN = /([a-z])([A-Z])/g; + var REPLACE_TEMPLATE = "$1-$2"; + /** + * Convert camelCase to dash-case properties. + */ + var camelToDash = function (str) { + return str + .replace(CAMEL_CASE_PATTERN, REPLACE_TEMPLATE) + .toLowerCase(); + }; + function renderHTML(element, _a, styleProp, projection) { + var style = _a.style, + vars = _a.vars; + Object.assign( + element.style, + style, + projection && projection.getProjectionStyles(styleProp) + ); + // Loop over any CSS variables and assign those. + for (var key in vars) { + element.style.setProperty(key, vars[key]); + } + } + + /** + * A set of attribute names that are always read/written as camel case. + */ + var camelCaseAttributes = new Set([ + "baseFrequency", + "diffuseConstant", + "kernelMatrix", + "kernelUnitLength", + "keySplines", + "keyTimes", + "limitingConeAngle", + "markerHeight", + "markerWidth", + "numOctaves", + "targetX", + "targetY", + "surfaceScale", + "specularConstant", + "specularExponent", + "stdDeviation", + "tableValues", + "viewBox", + "gradientTransform", + "pathLength", + ]); + function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, undefined, projection); + for (var key in renderState.attrs) { + element.setAttribute( + !camelCaseAttributes.has(key) ? camelToDash(key) : key, + renderState.attrs[key] + ); + } + } + function scrapeMotionValuesFromProps$1(props) { + var style = props.style; + var newValues = {}; + for (var key in style) { + if (isMotionValue(style[key]) || isForcedMotionValue(key, props)) { + newValues[key] = style[key]; + } + } + return newValues; + } + function scrapeMotionValuesFromProps(props) { + var newValues = scrapeMotionValuesFromProps$1(props); + for (var key in props) { + if (isMotionValue(props[key])) { + var targetKey = + key === "x" || key === "y" ? "attr" + key.toUpperCase() : key; + newValues[targetKey] = props[key]; + } + } + return newValues; + } + function isAnimationControls(v) { + return typeof v === "object" && typeof v.start === "function"; + } + var isKeyframesTarget = function (v) { + return Array.isArray(v); + }; + var isCustomValue = function (v) { + return Boolean(v && typeof v === "object" && v.mix && v.toValue); + }; + var resolveFinalValueInKeyframes = function (v) { + // TODO maybe throw if v.length - 1 is placeholder token? + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; + }; + + /** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ + function resolveMotionValue(value) { + var unwrappedValue = isMotionValue(value) ? value.get() : value; + return isCustomValue(unwrappedValue) + ? unwrappedValue.toValue() + : unwrappedValue; + } + function makeState(_a, props, context, presenceContext) { + var scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps, + createRenderState = _a.createRenderState, + onMount = _a.onMount; + var state = { + latestValues: makeLatestValues( + props, + context, + presenceContext, + scrapeMotionValuesFromProps + ), + renderState: createRenderState(), + }; + if (onMount) { + state.mount = function (instance) { + return onMount(props, instance, state); + }; + } + return state; + } + var makeUseVisualState = function (config) { + return function (props, isStatic) { + var context = React.useContext(MotionContext); + var presenceContext = React.useContext(PresenceContext); + return isStatic + ? makeState(config, props, context, presenceContext) + : useConstant(function () { + return makeState(config, props, context, presenceContext); + }); + }; + }; + function makeLatestValues( + props, + context, + presenceContext, + scrapeMotionValues + ) { + var values = {}; + var blockInitialAnimation = + (presenceContext === null || presenceContext === void 0 + ? void 0 + : presenceContext.initial) === false; + var motionValues = scrapeMotionValues(props); + for (var key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + var initial = props.initial, + animate = props.animate; + var isControllingVariants = checkIfControllingVariants(props); + var isVariantNode = checkIfVariantNode(props); + if ( + context && + isVariantNode && + !isControllingVariants && + props.inherit !== false + ) { + initial !== null && initial !== void 0 + ? initial + : (initial = context.initial); + animate !== null && animate !== void 0 + ? animate + : (animate = context.animate); + } + var initialAnimationIsBlocked = + blockInitialAnimation || initial === false; + var variantToSet = initialAnimationIsBlocked ? animate : initial; + if ( + variantToSet && + typeof variantToSet !== "boolean" && + !isAnimationControls(variantToSet) + ) { + var list = Array.isArray(variantToSet) + ? variantToSet + : [variantToSet]; + list.forEach(function (definition) { + var resolved = resolveVariantFromProps(props, definition); + if (!resolved) return; + var transitionEnd = resolved.transitionEnd; + resolved.transition; + var target = tslib.__rest(resolved, [ + "transitionEnd", + "transition", + ]); + for (var key in target) { + var valueTarget = target[key]; + if (Array.isArray(valueTarget)) { + /** + * Take final keyframe if the initial animation is blocked because + * we want to initialise at the end of that blocked animation. + */ + var index = initialAnimationIsBlocked + ? valueTarget.length - 1 + : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (var key in transitionEnd) values[key] = transitionEnd[key]; + }); + } + return values; + } + var svgMotionConfig = { + useVisualState: makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState, + onMount: function (props, instance, _a) { + var renderState = _a.renderState, + latestValues = _a.latestValues; + try { + renderState.dimensions = + typeof instance.getBBox === "function" + ? instance.getBBox() + : instance.getBoundingClientRect(); + } catch (e) { + // Most likely trying to measure an unrendered element under Firefox + renderState.dimensions = { + x: 0, + y: 0, + width: 0, + height: 0, + }; + } + buildSVGAttrs( + renderState, + latestValues, + { + enableHardwareAcceleration: false, + }, + props.transformTemplate + ); + renderSVG(instance, renderState); + }, + }), + }; + var htmlMotionConfig = { + useVisualState: makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + createRenderState: createHtmlRenderState, + }), + }; + function createDomMotionConfig( + Component, + _a, + preloadedFeatures, + createVisualElement, + projectionNodeConstructor + ) { + var _b = _a.forwardMotionProps, + forwardMotionProps = _b === void 0 ? false : _b; + var baseConfig = isSVGComponent(Component) + ? svgMotionConfig + : htmlMotionConfig; + return tslib.__assign(tslib.__assign({}, baseConfig), { + preloadedFeatures: preloadedFeatures, + useRender: createUseRender(forwardMotionProps), + createVisualElement: createVisualElement, + projectionNodeConstructor: projectionNodeConstructor, + Component: Component, + }); + } + exports.AnimationType = void 0; + (function (AnimationType) { + AnimationType["Animate"] = "animate"; + AnimationType["Hover"] = "whileHover"; + AnimationType["Tap"] = "whileTap"; + AnimationType["Drag"] = "whileDrag"; + AnimationType["Focus"] = "whileFocus"; + AnimationType["InView"] = "whileInView"; + AnimationType["Exit"] = "exit"; + })(exports.AnimationType || (exports.AnimationType = {})); + function addDomEvent(target, eventName, handler, options) { + if (options === void 0) { + options = { + passive: true, + }; + } + target.addEventListener(eventName, handler, options); + return function () { + return target.removeEventListener(eventName, handler); + }; + } + /** + * Attaches an event listener directly to the provided DOM element. + * + * Bypassing React's event system can be desirable, for instance when attaching non-passive + * event handlers. + * + * ```jsx + * const ref = useRef(null) + * + * useDomEvent(ref, 'wheel', onWheel, { passive: false }) + * + * return
+ * ``` + * + * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. + * @param eventName - Name of the event you want listen for. + * @param handler - Function to fire when receiving the event. + * @param options - Options to pass to `Event.addEventListener`. + * + * @public + */ + function useDomEvent(ref, eventName, handler, options) { + React.useEffect( + function () { + var element = ref.current; + if (handler && element) { + return addDomEvent(element, eventName, handler, options); + } + }, + [ref, eventName, handler, options] + ); + } + + /** + * + * @param props + * @param ref + * @internal + */ + function useFocusGesture(_a) { + var whileFocus = _a.whileFocus, + visualElement = _a.visualElement; + var onFocus = function () { + var _a; + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.Focus, true); + }; + var onBlur = function () { + var _a; + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.Focus, false); + }; + useDomEvent(visualElement, "focus", whileFocus ? onFocus : undefined); + useDomEvent(visualElement, "blur", whileFocus ? onBlur : undefined); + } + function isMouseEvent(event) { + // PointerEvent inherits from MouseEvent so we can't use a straight instanceof check. + if ( + typeof PointerEvent !== "undefined" && + event instanceof PointerEvent + ) { + return !!(event.pointerType === "mouse"); + } + return event instanceof MouseEvent; + } + function isTouchEvent(event) { + var hasTouches = !!event.touches; + return hasTouches; + } + + /** + * Filters out events not attached to the primary pointer (currently left mouse button) + * @param eventHandler + */ + function filterPrimaryPointer(eventHandler) { + return function (event) { + var isMouseEvent = event instanceof MouseEvent; + var isPrimaryPointer = + !isMouseEvent || (isMouseEvent && event.button === 0); + if (isPrimaryPointer) { + eventHandler(event); + } + }; + } + var defaultPagePoint = { + pageX: 0, + pageY: 0, + }; + function pointFromTouch(e, pointType) { + if (pointType === void 0) { + pointType = "page"; + } + var primaryTouch = e.touches[0] || e.changedTouches[0]; + var point = primaryTouch || defaultPagePoint; + return { + x: point[pointType + "X"], + y: point[pointType + "Y"], + }; + } + function pointFromMouse(point, pointType) { + if (pointType === void 0) { + pointType = "page"; + } + return { + x: point[pointType + "X"], + y: point[pointType + "Y"], + }; + } + function extractEventInfo(event, pointType) { + if (pointType === void 0) { + pointType = "page"; + } + return { + point: isTouchEvent(event) + ? pointFromTouch(event, pointType) + : pointFromMouse(event, pointType), + }; + } + var wrapHandler = function (handler, shouldFilterPrimaryPointer) { + if (shouldFilterPrimaryPointer === void 0) { + shouldFilterPrimaryPointer = false; + } + var listener = function (event) { + return handler(event, extractEventInfo(event)); + }; + return shouldFilterPrimaryPointer + ? filterPrimaryPointer(listener) + : listener; + }; + + // We check for event support via functions in case they've been mocked by a testing suite. + var supportsPointerEvents = function () { + return isBrowser && window.onpointerdown === null; + }; + var supportsTouchEvents = function () { + return isBrowser && window.ontouchstart === null; + }; + var supportsMouseEvents = function () { + return isBrowser && window.onmousedown === null; + }; + var mouseEventNames = { + pointerdown: "mousedown", + pointermove: "mousemove", + pointerup: "mouseup", + pointercancel: "mousecancel", + pointerover: "mouseover", + pointerout: "mouseout", + pointerenter: "mouseenter", + pointerleave: "mouseleave", + }; + var touchEventNames = { + pointerdown: "touchstart", + pointermove: "touchmove", + pointerup: "touchend", + pointercancel: "touchcancel", + }; + function getPointerEventName(name) { + if (supportsPointerEvents()) { + return name; + } else if (supportsTouchEvents()) { + return touchEventNames[name]; + } else if (supportsMouseEvents()) { + return mouseEventNames[name]; + } + return name; + } + function addPointerEvent(target, eventName, handler, options) { + return addDomEvent( + target, + getPointerEventName(eventName), + wrapHandler(handler, eventName === "pointerdown"), + options + ); + } + function usePointerEvent(ref, eventName, handler, options) { + return useDomEvent( + ref, + getPointerEventName(eventName), + handler && wrapHandler(handler, eventName === "pointerdown"), + options + ); + } + function createLock(name) { + var lock = null; + return function () { + var openLock = function () { + lock = null; + }; + if (lock === null) { + lock = name; + return openLock; + } + return false; + }; + } + var globalHorizontalLock = createLock("dragHorizontal"); + var globalVerticalLock = createLock("dragVertical"); + function getGlobalLock(drag) { + var lock = false; + if (drag === "y") { + lock = globalVerticalLock(); + } else if (drag === "x") { + lock = globalHorizontalLock(); + } else { + var openHorizontal_1 = globalHorizontalLock(); + var openVertical_1 = globalVerticalLock(); + if (openHorizontal_1 && openVertical_1) { + lock = function () { + openHorizontal_1(); + openVertical_1(); + }; + } else { + // Release the locks because we don't use them + if (openHorizontal_1) openHorizontal_1(); + if (openVertical_1) openVertical_1(); + } + } + return lock; + } + function isDragActive() { + // Check the gesture lock - if we get it, it means no drag gesture is active + // and we can safely fire the tap gesture. + var openGestureLock = getGlobalLock(true); + if (!openGestureLock) return true; + openGestureLock(); + return false; + } + function createHoverEvent(visualElement, isActive, callback) { + return function (event, info) { + var _a; + if (!isMouseEvent(event) || isDragActive()) return; + /** + * Ensure we trigger animations before firing event callback + */ + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.Hover, isActive); + callback === null || callback === void 0 + ? void 0 + : callback(event, info); + }; + } + function useHoverGesture(_a) { + var onHoverStart = _a.onHoverStart, + onHoverEnd = _a.onHoverEnd, + whileHover = _a.whileHover, + visualElement = _a.visualElement; + usePointerEvent( + visualElement, + "pointerenter", + onHoverStart || whileHover + ? createHoverEvent(visualElement, true, onHoverStart) + : undefined, + { + passive: !onHoverStart, + } + ); + usePointerEvent( + visualElement, + "pointerleave", + onHoverEnd || whileHover + ? createHoverEvent(visualElement, false, onHoverEnd) + : undefined, + { + passive: !onHoverEnd, + } + ); + } + + /** + * Recursively traverse up the tree to check whether the provided child node + * is the parent or a descendant of it. + * + * @param parent - Element to find + * @param child - Element to test against parent + */ + var isNodeOrChild = function (parent, child) { + if (!child) { + return false; + } else if (parent === child) { + return true; + } else { + return isNodeOrChild(parent, child.parentElement); + } + }; + function useUnmountEffect(callback) { + return React.useEffect(function () { + return function () { + return callback(); + }; + }, []); + } + + /** + * @param handlers - + * @internal + */ + function useTapGesture(_a) { + var onTap = _a.onTap, + onTapStart = _a.onTapStart, + onTapCancel = _a.onTapCancel, + whileTap = _a.whileTap, + visualElement = _a.visualElement; + var hasPressListeners = + onTap || onTapStart || onTapCancel || whileTap; + var isPressing = React.useRef(false); + var cancelPointerEndListeners = React.useRef(null); + /** + * Only set listener to passive if there are no external listeners. + */ + var eventOptions = { + passive: !(onTapStart || onTap || onTapCancel || onPointerDown), + }; + function removePointerEndListener() { + var _a; + (_a = cancelPointerEndListeners.current) === null || _a === void 0 + ? void 0 + : _a.call(cancelPointerEndListeners); + cancelPointerEndListeners.current = null; + } + function checkPointerEnd() { + var _a; + removePointerEndListener(); + isPressing.current = false; + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.Tap, false); + return !isDragActive(); + } + function onPointerUp(event, info) { + if (!checkPointerEnd()) return; + /** + * We only count this as a tap gesture if the event.target is the same + * as, or a child of, this component's element + */ + !isNodeOrChild(visualElement.getInstance(), event.target) + ? onTapCancel === null || onTapCancel === void 0 + ? void 0 + : onTapCancel(event, info) + : onTap === null || onTap === void 0 + ? void 0 + : onTap(event, info); + } + function onPointerCancel(event, info) { + if (!checkPointerEnd()) return; + onTapCancel === null || onTapCancel === void 0 + ? void 0 + : onTapCancel(event, info); + } + function onPointerDown(event, info) { + var _a; + removePointerEndListener(); + if (isPressing.current) return; + isPressing.current = true; + cancelPointerEndListeners.current = popmotion.pipe( + addPointerEvent(window, "pointerup", onPointerUp, eventOptions), + addPointerEvent( + window, + "pointercancel", + onPointerCancel, + eventOptions + ) + ); + /** + * Ensure we trigger animations before firing event callback + */ + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.Tap, true); + onTapStart === null || onTapStart === void 0 + ? void 0 + : onTapStart(event, info); + } + usePointerEvent( + visualElement, + "pointerdown", + hasPressListeners ? onPointerDown : undefined, + eventOptions + ); + useUnmountEffect(removePointerEndListener); + } + var warned = new Set(); + function warnOnce(condition, message, element) { + if (condition || warned.has(message)) return; + console.warn(message); + if (element) console.warn(element); + warned.add(message); + } + + /** + * Map an IntersectionHandler callback to an element. We only ever make one handler for one + * element, so even though these handlers might all be triggered by different + * observers, we can keep them in the same map. + */ + var observerCallbacks = new WeakMap(); + /** + * Multiple observers can be created for multiple element/document roots. Each with + * different settings. So here we store dictionaries of observers to each root, + * using serialised settings (threshold/margin) as lookup keys. + */ + var observers = new WeakMap(); + var fireObserverCallback = function (entry) { + var _a; + (_a = observerCallbacks.get(entry.target)) === null || _a === void 0 + ? void 0 + : _a(entry); + }; + var fireAllObserverCallbacks = function (entries) { + entries.forEach(fireObserverCallback); + }; + function initIntersectionObserver(_a) { + var root = _a.root, + options = tslib.__rest(_a, ["root"]); + var lookupRoot = root || document; + /** + * If we don't have an observer lookup map for this root, create one. + */ + if (!observers.has(lookupRoot)) { + observers.set(lookupRoot, {}); + } + var rootObservers = observers.get(lookupRoot); + var key = JSON.stringify(options); + /** + * If we don't have an observer for this combination of root and settings, + * create one. + */ + if (!rootObservers[key]) { + rootObservers[key] = new IntersectionObserver( + fireAllObserverCallbacks, + tslib.__assign( + { + root: root, + }, + options + ) + ); + } + return rootObservers[key]; + } + function observeIntersection(element, options, callback) { + var rootInteresectionObserver = initIntersectionObserver(options); + observerCallbacks.set(element, callback); + rootInteresectionObserver.observe(element); + return function () { + observerCallbacks.delete(element); + rootInteresectionObserver.unobserve(element); + }; + } + function useViewport(_a) { + var visualElement = _a.visualElement, + whileInView = _a.whileInView, + onViewportEnter = _a.onViewportEnter, + onViewportLeave = _a.onViewportLeave, + _b = _a.viewport, + viewport = _b === void 0 ? {} : _b; + var state = React.useRef({ + hasEnteredView: false, + isInView: false, + }); + var shouldObserve = Boolean( + whileInView || onViewportEnter || onViewportLeave + ); + if (viewport.once && state.current.hasEnteredView) + shouldObserve = false; + var useObserver = + typeof IntersectionObserver === "undefined" + ? useMissingIntersectionObserver + : useIntersectionObserver; + useObserver(shouldObserve, state.current, visualElement, viewport); + } + var thresholdNames = { + some: 0, + all: 1, + }; + function useIntersectionObserver( + shouldObserve, + state, + visualElement, + _a + ) { + var root = _a.root, + rootMargin = _a.margin, + _b = _a.amount, + amount = _b === void 0 ? "some" : _b, + once = _a.once; + React.useEffect( + function () { + if (!shouldObserve) return; + var options = { + root: root === null || root === void 0 ? void 0 : root.current, + rootMargin: rootMargin, + threshold: + typeof amount === "number" ? amount : thresholdNames[amount], + }; + var intersectionCallback = function (entry) { + var _a; + var isIntersecting = entry.isIntersecting; + /** + * If there's been no change in the viewport state, early return. + */ + if (state.isInView === isIntersecting) return; + state.isInView = isIntersecting; + /** + * Handle hasEnteredView. If this is only meant to run once, and + * element isn't visible, early return. Otherwise set hasEnteredView to true. + */ + if (once && !isIntersecting && state.hasEnteredView) { + return; + } else if (isIntersecting) { + state.hasEnteredView = true; + } + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.InView, isIntersecting); + /** + * Use the latest committed props rather than the ones in scope + * when this observer is created + */ + var props = visualElement.getProps(); + var callback = isIntersecting + ? props.onViewportEnter + : props.onViewportLeave; + callback === null || callback === void 0 + ? void 0 + : callback(entry); + }; + return observeIntersection( + visualElement.getInstance(), + options, + intersectionCallback + ); + }, + [shouldObserve, root, rootMargin, amount] + ); + } + /** + * If IntersectionObserver is missing, we activate inView and fire onViewportEnter + * on mount. This way, the page will be in the state the author expects users + * to see it in for everyone. + */ + function useMissingIntersectionObserver( + shouldObserve, + state, + visualElement, + _a + ) { + var _b = _a.fallback, + fallback = _b === void 0 ? true : _b; + React.useEffect( + function () { + if (!shouldObserve || !fallback) return; + if (env !== "production") { + warnOnce( + false, + "IntersectionObserver not available on this device. whileInView animations will trigger on mount." + ); + } + /** + * Fire this in an rAF because, at this point, the animation state + * won't have flushed for the first time and there's certain logic in + * there that behaves differently on the initial animation. + * + * This hook should be quite rarely called so setting this in an rAF + * is preferred to changing the behaviour of the animation state. + */ + requestAnimationFrame(function () { + var _a; + state.hasEnteredView = true; + var onViewportEnter = visualElement.getProps().onViewportEnter; + onViewportEnter === null || onViewportEnter === void 0 + ? void 0 + : onViewportEnter(null); + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.InView, true); + }); + }, + [shouldObserve] + ); + } + var makeRenderlessComponent = function (hook) { + return function (props) { + hook(props); + return null; + }; + }; + var gestureAnimations = { + inView: makeRenderlessComponent(useViewport), + tap: makeRenderlessComponent(useTapGesture), + focus: makeRenderlessComponent(useFocusGesture), + hover: makeRenderlessComponent(useHoverGesture), + }; + var counter = 0; + var incrementId = function () { + return counter++; + }; + var useId = function () { + return useConstant(incrementId); + }; + /** + * Ideally we'd use the following code to support React 18 optionally. + * But this fairly fails in Webpack (otherwise treeshaking wouldn't work at all). + * Need to come up with a different way of figuring this out. + */ + // export const useId = (React as any).useId + // ? (React as any).useId + // : () => useConstant(incrementId) + + /** + * When a component is the child of `AnimatePresence`, it can use `usePresence` + * to access information about whether it's still present in the React tree. + * + * ```jsx + * import { usePresence } from "framer-motion" + * + * export const Component = () => { + * const [isPresent, safeToRemove] = usePresence() + * + * useEffect(() => { + * !isPresent && setTimeout(safeToRemove, 1000) + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * If `isPresent` is `false`, it means that a component has been removed the tree, but + * `AnimatePresence` won't really remove it until `safeToRemove` has been called. + * + * @public + */ + function usePresence() { + var context = React.useContext(PresenceContext); + if (context === null) return [true, null]; + var isPresent = context.isPresent, + onExitComplete = context.onExitComplete, + register = context.register; + // It's safe to call the following hooks conditionally (after an early return) because the context will always + // either be null or non-null for the lifespan of the component. + // Replace with useId when released in React + var id = useId(); + React.useEffect(function () { + return register(id); + }, []); + var safeToRemove = function () { + return onExitComplete === null || onExitComplete === void 0 + ? void 0 + : onExitComplete(id); + }; + return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; + } + /** + * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. + * There is no `safeToRemove` function. + * + * ```jsx + * import { useIsPresent } from "framer-motion" + * + * export const Component = () => { + * const isPresent = useIsPresent() + * + * useEffect(() => { + * !isPresent && console.log("I've been removed!") + * }, [isPresent]) + * + * return
+ * } + * ``` + * + * @public + */ + function useIsPresent() { + return isPresent(React.useContext(PresenceContext)); + } + function isPresent(context) { + return context === null ? true : context.isPresent; + } + function shallowCompare(next, prev) { + if (!Array.isArray(prev)) return false; + var prevLength = prev.length; + if (prevLength !== next.length) return false; + for (var i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) return false; + } + return true; + } + + /** + * Converts seconds to milliseconds + * + * @param seconds - Time in seconds. + * @return milliseconds - Converted time in milliseconds. + */ + var secondsToMilliseconds = function (seconds) { + return seconds * 1000; + }; + var easingLookup = { + linear: popmotion.linear, + easeIn: popmotion.easeIn, + easeInOut: popmotion.easeInOut, + easeOut: popmotion.easeOut, + circIn: popmotion.circIn, + circInOut: popmotion.circInOut, + circOut: popmotion.circOut, + backIn: popmotion.backIn, + backInOut: popmotion.backInOut, + backOut: popmotion.backOut, + anticipate: popmotion.anticipate, + bounceIn: popmotion.bounceIn, + bounceInOut: popmotion.bounceInOut, + bounceOut: popmotion.bounceOut, + }; + var easingDefinitionToFunction = function (definition) { + if (Array.isArray(definition)) { + // If cubic bezier definition, create bezier curve + heyListen.invariant( + definition.length === 4, + "Cubic bezier arrays must contain four numerical values." + ); + var _a = tslib.__read(definition, 4), + x1 = _a[0], + y1 = _a[1], + x2 = _a[2], + y2 = _a[3]; + return popmotion.cubicBezier(x1, y1, x2, y2); + } else if (typeof definition === "string") { + // Else lookup from table + heyListen.invariant( + easingLookup[definition] !== undefined, + "Invalid easing type '".concat(definition, "'") + ); + return easingLookup[definition]; + } + return definition; + }; + var isEasingArray = function (ease) { + return Array.isArray(ease) && typeof ease[0] !== "number"; + }; + + /** + * Check if a value is animatable. Examples: + * + * ✅: 100, "100px", "#fff" + * ❌: "block", "url(2.jpg)" + * @param value + * + * @internal + */ + var isAnimatable = function (key, value) { + // If the list of keys tat might be non-animatable grows, replace with Set + if (key === "zIndex") return false; + // If it's a number or a keyframes array, we can animate it. We might at some point + // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this, + // but for now lets leave it like this for performance reasons + if (typeof value === "number" || Array.isArray(value)) return true; + if ( + typeof value === "string" && + // It's animatable if we have a string + styleValueTypes.complex.test(value) && + // And it contains numbers and/or colors + !value.startsWith("url(") // Unless it starts with "url(" + ) { + return true; + } + return false; + }; + var underDampedSpring = function () { + return { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10, + }; + }; + var criticallyDampedSpring = function (to) { + return { + type: "spring", + stiffness: 550, + damping: to === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10, + }; + }; + var linearTween = function () { + return { + type: "keyframes", + ease: "linear", + duration: 0.3, + }; + }; + var keyframes = function (values) { + return { + type: "keyframes", + duration: 0.8, + values: values, + }; + }; + var defaultTransitions = { + x: underDampedSpring, + y: underDampedSpring, + z: underDampedSpring, + rotate: underDampedSpring, + rotateX: underDampedSpring, + rotateY: underDampedSpring, + rotateZ: underDampedSpring, + scaleX: criticallyDampedSpring, + scaleY: criticallyDampedSpring, + scale: criticallyDampedSpring, + opacity: linearTween, + backgroundColor: linearTween, + color: linearTween, + default: criticallyDampedSpring, + }; + var getDefaultTransition = function (valueKey, to) { + var transitionFactory; + if (isKeyframesTarget(to)) { + transitionFactory = keyframes; + } else { + transitionFactory = + defaultTransitions[valueKey] || defaultTransitions.default; + } + return tslib.__assign( + { + to: to, + }, + transitionFactory(to) + ); + }; + + /** + * A map of default value types for common values + */ + var defaultValueTypes = tslib.__assign( + tslib.__assign({}, numberValueTypes), + { + // Color props + color: styleValueTypes.color, + backgroundColor: styleValueTypes.color, + outlineColor: styleValueTypes.color, + fill: styleValueTypes.color, + stroke: styleValueTypes.color, + // Border props + borderColor: styleValueTypes.color, + borderTopColor: styleValueTypes.color, + borderRightColor: styleValueTypes.color, + borderBottomColor: styleValueTypes.color, + borderLeftColor: styleValueTypes.color, + filter: styleValueTypes.filter, + WebkitFilter: styleValueTypes.filter, + } + ); + /** + * Gets the default ValueType for the provided value key + */ + var getDefaultValueType = function (key) { + return defaultValueTypes[key]; + }; + function getAnimatableNone(key, value) { + var _a; + var defaultValueType = getDefaultValueType(key); + if (defaultValueType !== styleValueTypes.filter) + defaultValueType = styleValueTypes.complex; + // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target + return (_a = defaultValueType.getAnimatableNone) === null || + _a === void 0 + ? void 0 + : _a.call(defaultValueType, value); + } + var instantAnimationState = { + current: false, + }; + + /** + * Decide whether a transition is defined on a given Transition. + * This filters out orchestration options and returns true + * if any options are left. + */ + function isTransitionDefined(_a) { + _a.when; + _a.delay; + _a.delayChildren; + _a.staggerChildren; + _a.staggerDirection; + _a.repeat; + _a.repeatType; + _a.repeatDelay; + _a.from; + var transition = tslib.__rest(_a, [ + "when", + "delay", + "delayChildren", + "staggerChildren", + "staggerDirection", + "repeat", + "repeatType", + "repeatDelay", + "from", + ]); + return !!Object.keys(transition).length; + } + var legacyRepeatWarning = false; + /** + * Convert Framer Motion's Transition type into Popmotion-compatible options. + */ + function convertTransitionToAnimationOptions(_a) { + var ease = _a.ease, + times = _a.times, + yoyo = _a.yoyo, + flip = _a.flip, + loop = _a.loop, + transition = tslib.__rest(_a, [ + "ease", + "times", + "yoyo", + "flip", + "loop", + ]); + var options = tslib.__assign({}, transition); + if (times) options["offset"] = times; + /** + * Convert any existing durations from seconds to milliseconds + */ + if (transition.duration) + options["duration"] = secondsToMilliseconds(transition.duration); + if (transition.repeatDelay) + options.repeatDelay = secondsToMilliseconds(transition.repeatDelay); + /** + * Map easing names to Popmotion's easing functions + */ + if (ease) { + options["ease"] = isEasingArray(ease) + ? ease.map(easingDefinitionToFunction) + : easingDefinitionToFunction(ease); + } + /** + * Support legacy transition API + */ + if (transition.type === "tween") options.type = "keyframes"; + /** + * TODO: These options are officially removed from the API. + */ + if (yoyo || loop || flip) { + heyListen.warning( + !legacyRepeatWarning, + "yoyo, loop and flip have been removed from the API. Replace with repeat and repeatType options." + ); + legacyRepeatWarning = true; + if (yoyo) { + options.repeatType = "reverse"; + } else if (loop) { + options.repeatType = "loop"; + } else if (flip) { + options.repeatType = "mirror"; + } + options.repeat = loop || yoyo || flip || transition.repeat; + } + /** + * TODO: Popmotion 9 has the ability to automatically detect whether to use + * a keyframes or spring animation, but does so by detecting velocity and other spring options. + * It'd be good to introduce a similar thing here. + */ + if (transition.type !== "spring") options.type = "keyframes"; + return options; + } + /** + * Get the delay for a value by checking Transition with decreasing specificity. + */ + function getDelayFromTransition(transition, key) { + var _a, _b; + var valueTransition = getValueTransition(transition, key) || {}; + return (_b = + (_a = valueTransition.delay) !== null && _a !== void 0 + ? _a + : transition.delay) !== null && _b !== void 0 + ? _b + : 0; + } + function hydrateKeyframes(options) { + if (Array.isArray(options.to) && options.to[0] === null) { + options.to = tslib.__spreadArray( + [], + tslib.__read(options.to), + false + ); + options.to[0] = options.from; + } + return options; + } + function getPopmotionAnimationOptions(transition, options, key) { + var _a; + if (Array.isArray(options.to)) { + (_a = transition.duration) !== null && _a !== void 0 + ? _a + : (transition.duration = 0.8); + } + hydrateKeyframes(options); + /** + * Get a default transition if none is determined to be defined. + */ + if (!isTransitionDefined(transition)) { + transition = tslib.__assign( + tslib.__assign({}, transition), + getDefaultTransition(key, options.to) + ); + } + return tslib.__assign( + tslib.__assign({}, options), + convertTransitionToAnimationOptions(transition) + ); + } + /** + * + */ + function getAnimation(key, value, target, transition, onComplete) { + var _a; + var valueTransition = getValueTransition(transition, key); + var origin = + (_a = valueTransition.from) !== null && _a !== void 0 + ? _a + : value.get(); + var isTargetAnimatable = isAnimatable(key, target); + if ( + origin === "none" && + isTargetAnimatable && + typeof target === "string" + ) { + /** + * If we're trying to animate from "none", try and get an animatable version + * of the target. This could be improved to work both ways. + */ + origin = getAnimatableNone(key, target); + } else if (isZero(origin) && typeof target === "string") { + origin = getZeroUnit(target); + } else if ( + !Array.isArray(target) && + isZero(target) && + typeof origin === "string" + ) { + target = getZeroUnit(origin); + } + var isOriginAnimatable = isAnimatable(key, origin); + heyListen.warning( + isOriginAnimatable === isTargetAnimatable, + "You are trying to animate " + .concat(key, ' from "') + .concat(origin, '" to "') + .concat(target, '". ') + .concat( + origin, + " is not an animatable value - to enable this animation set " + ) + .concat(origin, " to a value animatable to ") + .concat(target, " via the `style` property.") + ); + function start() { + var options = { + from: origin, + to: target, + velocity: value.getVelocity(), + onComplete: onComplete, + onUpdate: function (v) { + return value.set(v); + }, + }; + return valueTransition.type === "inertia" || + valueTransition.type === "decay" + ? popmotion.inertia( + tslib.__assign(tslib.__assign({}, options), valueTransition) + ) + : popmotion.animate( + tslib.__assign( + tslib.__assign( + {}, + getPopmotionAnimationOptions( + valueTransition, + options, + key + ) + ), + { + onUpdate: function (v) { + var _a; + options.onUpdate(v); + (_a = valueTransition.onUpdate) === null || + _a === void 0 + ? void 0 + : _a.call(valueTransition, v); + }, + onComplete: function () { + var _a; + options.onComplete(); + (_a = valueTransition.onComplete) === null || + _a === void 0 + ? void 0 + : _a.call(valueTransition); + }, + } + ) + ); + } + function set() { + var _a, _b; + var finalTarget = resolveFinalValueInKeyframes(target); + value.set(finalTarget); + onComplete(); + (_a = + valueTransition === null || valueTransition === void 0 + ? void 0 + : valueTransition.onUpdate) === null || _a === void 0 + ? void 0 + : _a.call(valueTransition, finalTarget); + (_b = + valueTransition === null || valueTransition === void 0 + ? void 0 + : valueTransition.onComplete) === null || _b === void 0 + ? void 0 + : _b.call(valueTransition); + return { + stop: function () {}, + }; + } + return !isOriginAnimatable || + !isTargetAnimatable || + valueTransition.type === false + ? set + : start; + } + function isZero(value) { + return ( + value === 0 || + (typeof value === "string" && + parseFloat(value) === 0 && + value.indexOf(" ") === -1) + ); + } + function getZeroUnit(potentialUnitType) { + return typeof potentialUnitType === "number" + ? 0 + : getAnimatableNone("", potentialUnitType); + } + function getValueTransition(transition, key) { + return transition[key] || transition["default"] || transition; + } + /** + * Start animation on a MotionValue. This function is an interface between + * Framer Motion and Popmotion + */ + function startAnimation(key, value, target, transition) { + if (transition === void 0) { + transition = {}; + } + if (instantAnimationState.current) { + transition = { + type: false, + }; + } + return value.start(function (onComplete) { + var delayTimer; + var controls; + var animation = getAnimation( + key, + value, + target, + transition, + onComplete + ); + var delay = getDelayFromTransition(transition, key); + var start = function () { + return (controls = animation()); + }; + if (delay) { + delayTimer = window.setTimeout( + start, + secondsToMilliseconds(delay) + ); + } else { + start(); + } + return function () { + clearTimeout(delayTimer); + controls === null || controls === void 0 + ? void 0 + : controls.stop(); + }; + }); + } + + /** + * Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1" + */ + var isNumericalString = function (v) { + return /^\-?\d*\.?\d+$/.test(v); + }; + + /** + * Check if the value is a zero value string like "0px" or "0%" + */ + var isZeroValueString = function (v) { + return /^0[^.\s]+$/.test(v); + }; + function addUniqueItem(arr, item) { + arr.indexOf(item) === -1 && arr.push(item); + } + function removeItem(arr, item) { + var index = arr.indexOf(item); + index > -1 && arr.splice(index, 1); + } + // Adapted from array-move + function moveItem(_a, fromIndex, toIndex) { + var _b = tslib.__read(_a), + arr = _b.slice(0); + var startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex; + if (startIndex >= 0 && startIndex < arr.length) { + var endIndex = toIndex < 0 ? arr.length + toIndex : toIndex; + var _c = tslib.__read(arr.splice(fromIndex, 1), 1), + item = _c[0]; + arr.splice(endIndex, 0, item); + } + return arr; + } + var SubscriptionManager = /** @class */ (function () { + function SubscriptionManager() { + this.subscriptions = []; + } + SubscriptionManager.prototype.add = function (handler) { + var _this = this; + addUniqueItem(this.subscriptions, handler); + return function () { + return removeItem(_this.subscriptions, handler); + }; + }; + SubscriptionManager.prototype.notify = function (a, b, c) { + var numSubscriptions = this.subscriptions.length; + if (!numSubscriptions) return; + if (numSubscriptions === 1) { + /** + * If there's only a single handler we can just call it without invoking a loop. + */ + this.subscriptions[0](a, b, c); + } else { + for (var i = 0; i < numSubscriptions; i++) { + /** + * Check whether the handler exists before firing as it's possible + * the subscriptions were modified during this loop running. + */ + var handler = this.subscriptions[i]; + handler && handler(a, b, c); + } + } + }; + SubscriptionManager.prototype.getSize = function () { + return this.subscriptions.length; + }; + SubscriptionManager.prototype.clear = function () { + this.subscriptions.length = 0; + }; + return SubscriptionManager; + })(); + var isFloat = function (value) { + return !isNaN(parseFloat(value)); + }; + /** + * `MotionValue` is used to track the state and velocity of motion values. + * + * @public + */ + var MotionValue = /** @class */ (function () { + /** + * @param init - The initiating value + * @param config - Optional configuration options + * + * - `transformer`: A function to transform incoming values with. + * + * @internal + */ + function MotionValue(init) { + var _this = this; + /** + * This will be replaced by the build step with the latest version number. + * When MotionValues are provided to motion components, warn if versions are mixed. + */ + this.version = "6.5.1"; + /** + * Duration, in milliseconds, since last updating frame. + * + * @internal + */ + this.timeDelta = 0; + /** + * Timestamp of the last time this `MotionValue` was updated. + * + * @internal + */ + this.lastUpdated = 0; + /** + * Functions to notify when the `MotionValue` updates. + * + * @internal + */ + this.updateSubscribers = new SubscriptionManager(); + /** + * Functions to notify when the velocity updates. + * + * @internal + */ + this.velocityUpdateSubscribers = new SubscriptionManager(); + /** + * Functions to notify when the `MotionValue` updates and `render` is set to `true`. + * + * @internal + */ + this.renderSubscribers = new SubscriptionManager(); + /** + * Tracks whether this value can output a velocity. Currently this is only true + * if the value is numerical, but we might be able to widen the scope here and support + * other value types. + * + * @internal + */ + this.canTrackVelocity = false; + this.updateAndNotify = function (v, render) { + if (render === void 0) { + render = true; + } + _this.prev = _this.current; + _this.current = v; + // Update timestamp + var _a = sync.getFrameData(), + delta = _a.delta, + timestamp = _a.timestamp; + if (_this.lastUpdated !== timestamp) { + _this.timeDelta = delta; + _this.lastUpdated = timestamp; + sync__default["default"].postRender( + _this.scheduleVelocityCheck + ); + } + // Update update subscribers + if (_this.prev !== _this.current) { + _this.updateSubscribers.notify(_this.current); + } + // Update velocity subscribers + if (_this.velocityUpdateSubscribers.getSize()) { + _this.velocityUpdateSubscribers.notify(_this.getVelocity()); + } + // Update render subscribers + if (render) { + _this.renderSubscribers.notify(_this.current); + } + }; + /** + * Schedule a velocity check for the next frame. + * + * This is an instanced and bound function to prevent generating a new + * function once per frame. + * + * @internal + */ + this.scheduleVelocityCheck = function () { + return sync__default["default"].postRender(_this.velocityCheck); + }; + /** + * Updates `prev` with `current` if the value hasn't been updated this frame. + * This ensures velocity calculations return `0`. + * + * This is an instanced and bound function to prevent generating a new + * function once per frame. + * + * @internal + */ + this.velocityCheck = function (_a) { + var timestamp = _a.timestamp; + if (timestamp !== _this.lastUpdated) { + _this.prev = _this.current; + _this.velocityUpdateSubscribers.notify(_this.getVelocity()); + } + }; + this.hasAnimated = false; + this.prev = this.current = init; + this.canTrackVelocity = isFloat(this.current); + } + /** + * Adds a function that will be notified when the `MotionValue` is updated. + * + * It returns a function that, when called, will cancel the subscription. + * + * When calling `onChange` inside a React component, it should be wrapped with the + * `useEffect` hook. As it returns an unsubscribe function, this should be returned + * from the `useEffect` function to ensure you don't add duplicate subscribers.. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * const y = useMotionValue(0) + * const opacity = useMotionValue(1) + * + * useEffect(() => { + * function updateOpacity() { + * const maxXY = Math.max(x.get(), y.get()) + * const newOpacity = transform(maxXY, [0, 100], [1, 0]) + * opacity.set(newOpacity) + * } + * + * const unsubscribeX = x.onChange(updateOpacity) + * const unsubscribeY = y.onChange(updateOpacity) + * + * return () => { + * unsubscribeX() + * unsubscribeY() + * } + * }, []) + * + * return + * } + * ``` + * + * @privateRemarks + * + * We could look into a `useOnChange` hook if the above lifecycle management proves confusing. + * + * ```jsx + * useOnChange(x, () => {}) + * ``` + * + * @param subscriber - A function that receives the latest value. + * @returns A function that, when called, will cancel this subscription. + * + * @public + */ + MotionValue.prototype.onChange = function (subscription) { + return this.updateSubscribers.add(subscription); + }; + MotionValue.prototype.clearListeners = function () { + this.updateSubscribers.clear(); + }; + /** + * Adds a function that will be notified when the `MotionValue` requests a render. + * + * @param subscriber - A function that's provided the latest value. + * @returns A function that, when called, will cancel this subscription. + * + * @internal + */ + MotionValue.prototype.onRenderRequest = function (subscription) { + // Render immediately + subscription(this.get()); + return this.renderSubscribers.add(subscription); + }; + /** + * Attaches a passive effect to the `MotionValue`. + * + * @internal + */ + MotionValue.prototype.attach = function (passiveEffect) { + this.passiveEffect = passiveEffect; + }; + /** + * Sets the state of the `MotionValue`. + * + * @remarks + * + * ```jsx + * const x = useMotionValue(0) + * x.set(10) + * ``` + * + * @param latest - Latest value to set. + * @param render - Whether to notify render subscribers. Defaults to `true` + * + * @public + */ + MotionValue.prototype.set = function (v, render) { + if (render === void 0) { + render = true; + } + if (!render || !this.passiveEffect) { + this.updateAndNotify(v, render); + } else { + this.passiveEffect(v, this.updateAndNotify); + } + }; + /** + * Returns the latest state of `MotionValue` + * + * @returns - The latest state of `MotionValue` + * + * @public + */ + MotionValue.prototype.get = function () { + return this.current; + }; + /** + * @public + */ + MotionValue.prototype.getPrevious = function () { + return this.prev; + }; + /** + * Returns the latest velocity of `MotionValue` + * + * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. + * + * @public + */ + MotionValue.prototype.getVelocity = function () { + // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful + return this.canTrackVelocity + ? // These casts could be avoided if parseFloat would be typed better + popmotion.velocityPerSecond( + parseFloat(this.current) - parseFloat(this.prev), + this.timeDelta + ) + : 0; + }; + /** + * Registers a new animation to control this `MotionValue`. Only one + * animation can drive a `MotionValue` at one time. + * + * ```jsx + * value.start() + * ``` + * + * @param animation - A function that starts the provided animation + * + * @internal + */ + MotionValue.prototype.start = function (animation) { + var _this = this; + this.stop(); + return new Promise(function (resolve) { + _this.hasAnimated = true; + _this.stopAnimation = animation(resolve); + }).then(function () { + return _this.clearAnimation(); + }); + }; + /** + * Stop the currently active animation. + * + * @public + */ + MotionValue.prototype.stop = function () { + if (this.stopAnimation) this.stopAnimation(); + this.clearAnimation(); + }; + /** + * Returns `true` if this value is currently animating. + * + * @public + */ + MotionValue.prototype.isAnimating = function () { + return !!this.stopAnimation; + }; + MotionValue.prototype.clearAnimation = function () { + this.stopAnimation = null; + }; + /** + * Destroy and clean up subscribers to this `MotionValue`. + * + * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically + * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually + * created a `MotionValue` via the `motionValue` function. + * + * @public + */ + MotionValue.prototype.destroy = function () { + this.updateSubscribers.clear(); + this.renderSubscribers.clear(); + this.stop(); + }; + return MotionValue; + })(); + function motionValue(init) { + return new MotionValue(init); + } + + /** + * Tests a provided value against a ValueType + */ + var testValueType = function (v) { + return function (type) { + return type.test(v); + }; + }; + + /** + * ValueType for "auto" + */ + var auto = { + test: function (v) { + return v === "auto"; + }, + parse: function (v) { + return v; + }, + }; + + /** + * A list of value types commonly used for dimensions + */ + var dimensionValueTypes = [ + styleValueTypes.number, + styleValueTypes.px, + styleValueTypes.percent, + styleValueTypes.degrees, + styleValueTypes.vw, + styleValueTypes.vh, + auto, + ]; + /** + * Tests a dimensional value against the list of dimension ValueTypes + */ + var findDimensionValueType = function (v) { + return dimensionValueTypes.find(testValueType(v)); + }; + + /** + * A list of all ValueTypes + */ + var valueTypes = tslib.__spreadArray( + tslib.__spreadArray([], tslib.__read(dimensionValueTypes), false), + [styleValueTypes.color, styleValueTypes.complex], + false + ); + /** + * Tests a value against the list of ValueTypes + */ + var findValueType = function (v) { + return valueTypes.find(testValueType(v)); + }; + + /** + * Set VisualElement's MotionValue, creating a new MotionValue for it if + * it doesn't exist. + */ + function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } else { + visualElement.addValue(key, motionValue(value)); + } + } + function setTarget(visualElement, definition) { + var resolved = resolveVariant(visualElement, definition); + var _a = resolved + ? visualElement.makeTargetAnimatable(resolved, false) + : {}, + _b = _a.transitionEnd, + transitionEnd = _b === void 0 ? {} : _b; + _a.transition; + var target = tslib.__rest(_a, ["transitionEnd", "transition"]); + target = tslib.__assign(tslib.__assign({}, target), transitionEnd); + for (var key in target) { + var value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } + } + function setVariants(visualElement, variantLabels) { + var reversedLabels = tslib + .__spreadArray([], tslib.__read(variantLabels), false) + .reverse(); + reversedLabels.forEach(function (key) { + var _a; + var variant = visualElement.getVariant(key); + variant && setTarget(visualElement, variant); + (_a = visualElement.variantChildren) === null || _a === void 0 + ? void 0 + : _a.forEach(function (child) { + setVariants(child, variantLabels); + }); + }); + } + function setValues(visualElement, definition) { + if (Array.isArray(definition)) { + return setVariants(visualElement, definition); + } else if (typeof definition === "string") { + return setVariants(visualElement, [definition]); + } else { + setTarget(visualElement, definition); + } + } + function checkTargetForNewValues(visualElement, target, origin) { + var _a, _b, _c; + var _d; + var newValueKeys = Object.keys(target).filter(function (key) { + return !visualElement.hasValue(key); + }); + var numNewValues = newValueKeys.length; + if (!numNewValues) return; + for (var i = 0; i < numNewValues; i++) { + var key = newValueKeys[i]; + var targetValue = target[key]; + var value = null; + /** + * If the target is a series of keyframes, we can use the first value + * in the array. If this first value is null, we'll still need to read from the DOM. + */ + if (Array.isArray(targetValue)) { + value = targetValue[0]; + } + /** + * If the target isn't keyframes, or the first keyframe was null, we need to + * first check if an origin value was explicitly defined in the transition as "from", + * if not read the value from the DOM. As an absolute fallback, take the defined target value. + */ + if (value === null) { + value = + (_b = + (_a = origin[key]) !== null && _a !== void 0 + ? _a + : visualElement.readValue(key)) !== null && _b !== void 0 + ? _b + : target[key]; + } + /** + * If value is still undefined or null, ignore it. Preferably this would throw, + * but this was causing issues in Framer. + */ + if (value === undefined || value === null) continue; + if ( + typeof value === "string" && + (isNumericalString(value) || isZeroValueString(value)) + ) { + // If this is a number read as a string, ie "0" or "200", convert it to a number + value = parseFloat(value); + } else if ( + !findValueType(value) && + styleValueTypes.complex.test(targetValue) + ) { + value = getAnimatableNone(key, targetValue); + } + visualElement.addValue(key, motionValue(value)); + (_c = (_d = origin)[key]) !== null && _c !== void 0 + ? _c + : (_d[key] = value); + visualElement.setBaseTarget(key, value); + } + } + function getOriginFromTransition(key, transition) { + if (!transition) return; + var valueTransition = + transition[key] || transition["default"] || transition; + return valueTransition.from; + } + function getOrigin(target, transition, visualElement) { + var _a, _b; + var origin = {}; + for (var key in target) { + origin[key] = + (_a = getOriginFromTransition(key, transition)) !== null && + _a !== void 0 + ? _a + : (_b = visualElement.getValue(key)) === null || _b === void 0 + ? void 0 + : _b.get(); + } + return origin; + } + function animateVisualElement(visualElement, definition, options) { + if (options === void 0) { + options = {}; + } + visualElement.notifyAnimationStart(definition); + var animation; + if (Array.isArray(definition)) { + var animations = definition.map(function (variant) { + return animateVariant(visualElement, variant, options); + }); + animation = Promise.all(animations); + } else if (typeof definition === "string") { + animation = animateVariant(visualElement, definition, options); + } else { + var resolvedDefinition = + typeof definition === "function" + ? resolveVariant(visualElement, definition, options.custom) + : definition; + animation = animateTarget( + visualElement, + resolvedDefinition, + options + ); + } + return animation.then(function () { + return visualElement.notifyAnimationComplete(definition); + }); + } + function animateVariant(visualElement, variant, options) { + var _a; + if (options === void 0) { + options = {}; + } + var resolved = resolveVariant(visualElement, variant, options.custom); + var _b = (resolved || {}).transition, + transition = + _b === void 0 ? visualElement.getDefaultTransition() || {} : _b; + if (options.transitionOverride) { + transition = options.transitionOverride; + } + /** + * If we have a variant, create a callback that runs it as an animation. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + var getAnimation = resolved + ? function () { + return animateTarget(visualElement, resolved, options); + } + : function () { + return Promise.resolve(); + }; + /** + * If we have children, create a callback that runs all their animations. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + var getChildAnimations = ( + (_a = visualElement.variantChildren) === null || _a === void 0 + ? void 0 + : _a.size + ) + ? function (forwardDelay) { + if (forwardDelay === void 0) { + forwardDelay = 0; + } + var _a = transition.delayChildren, + delayChildren = _a === void 0 ? 0 : _a, + staggerChildren = transition.staggerChildren, + staggerDirection = transition.staggerDirection; + return animateChildren( + visualElement, + variant, + delayChildren + forwardDelay, + staggerChildren, + staggerDirection, + options + ); + } + : function () { + return Promise.resolve(); + }; + /** + * If the transition explicitly defines a "when" option, we need to resolve either + * this animation or all children animations before playing the other. + */ + var when = transition.when; + if (when) { + var _c = tslib.__read( + when === "beforeChildren" + ? [getAnimation, getChildAnimations] + : [getChildAnimations, getAnimation], + 2 + ), + first = _c[0], + last = _c[1]; + return first().then(last); + } else { + return Promise.all([ + getAnimation(), + getChildAnimations(options.delay), + ]); + } + } + /** + * @internal + */ + function animateTarget(visualElement, definition, _a) { + var _b; + var _c = _a === void 0 ? {} : _a, + _d = _c.delay, + delay = _d === void 0 ? 0 : _d, + transitionOverride = _c.transitionOverride, + type = _c.type; + var _e = visualElement.makeTargetAnimatable(definition), + _f = _e.transition, + transition = + _f === void 0 ? visualElement.getDefaultTransition() : _f, + transitionEnd = _e.transitionEnd, + target = tslib.__rest(_e, ["transition", "transitionEnd"]); + if (transitionOverride) transition = transitionOverride; + var animations = []; + var animationTypeState = + type && + ((_b = visualElement.animationState) === null || _b === void 0 + ? void 0 + : _b.getState()[type]); + for (var key in target) { + var value = visualElement.getValue(key); + var valueTarget = target[key]; + if ( + !value || + valueTarget === undefined || + (animationTypeState && + shouldBlockAnimation(animationTypeState, key)) + ) { + continue; + } + var valueTransition = tslib.__assign( + { + delay: delay, + }, + transition + ); + /** + * Make animation instant if this is a transform prop and we should reduce motion. + */ + if (visualElement.shouldReduceMotion && isTransformProp(key)) { + valueTransition = tslib.__assign( + tslib.__assign({}, valueTransition), + { + type: false, + delay: 0, + } + ); + } + var animation = startAnimation( + key, + value, + valueTarget, + valueTransition + ); + animations.push(animation); + } + return Promise.all(animations).then(function () { + transitionEnd && setTarget(visualElement, transitionEnd); + }); + } + function animateChildren( + visualElement, + variant, + delayChildren, + staggerChildren, + staggerDirection, + options + ) { + if (delayChildren === void 0) { + delayChildren = 0; + } + if (staggerChildren === void 0) { + staggerChildren = 0; + } + if (staggerDirection === void 0) { + staggerDirection = 1; + } + var animations = []; + var maxStaggerDuration = + (visualElement.variantChildren.size - 1) * staggerChildren; + var generateStaggerDuration = + staggerDirection === 1 + ? function (i) { + if (i === void 0) { + i = 0; + } + return i * staggerChildren; + } + : function (i) { + if (i === void 0) { + i = 0; + } + return maxStaggerDuration - i * staggerChildren; + }; + Array.from(visualElement.variantChildren) + .sort(sortByTreeOrder) + .forEach(function (child, i) { + animations.push( + animateVariant( + child, + variant, + tslib.__assign(tslib.__assign({}, options), { + delay: delayChildren + generateStaggerDuration(i), + }) + ).then(function () { + return child.notifyAnimationComplete(variant); + }) + ); + }); + return Promise.all(animations); + } + function stopAnimation(visualElement) { + visualElement.forEachValue(function (value) { + return value.stop(); + }); + } + function sortByTreeOrder(a, b) { + return a.sortNodePosition(b); + } + /** + * Decide whether we should block this animation. Previously, we achieved this + * just by checking whether the key was listed in protectedKeys, but this + * posed problems if an animation was triggered by afterChildren and protectedKeys + * had been set to true in the meantime. + */ + function shouldBlockAnimation(_a, key) { + var protectedKeys = _a.protectedKeys, + needsAnimating = _a.needsAnimating; + var shouldBlock = + protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; + } + var variantPriorityOrder = [ + exports.AnimationType.Animate, + exports.AnimationType.InView, + exports.AnimationType.Focus, + exports.AnimationType.Hover, + exports.AnimationType.Tap, + exports.AnimationType.Drag, + exports.AnimationType.Exit, + ]; + var reversePriorityOrder = tslib + .__spreadArray([], tslib.__read(variantPriorityOrder), false) + .reverse(); + var numAnimationTypes = variantPriorityOrder.length; + function animateList(visualElement) { + return function (animations) { + return Promise.all( + animations.map(function (_a) { + var animation = _a.animation, + options = _a.options; + return animateVisualElement(visualElement, animation, options); + }) + ); + }; + } + function createAnimationState(visualElement) { + var animate = animateList(visualElement); + var state = createState(); + var allAnimatedKeys = {}; + var isInitialRender = true; + /** + * This function will be used to reduce the animation definitions for + * each active animation type into an object of resolved values for it. + */ + var buildResolvedTypeValues = function (acc, definition) { + var resolved = resolveVariant(visualElement, definition); + if (resolved) { + resolved.transition; + var transitionEnd = resolved.transitionEnd, + target = tslib.__rest(resolved, [ + "transition", + "transitionEnd", + ]); + acc = tslib.__assign( + tslib.__assign(tslib.__assign({}, acc), target), + transitionEnd + ); + } + return acc; + }; + function isAnimated(key) { + return allAnimatedKeys[key] !== undefined; + } + /** + * This just allows us to inject mocked animation functions + * @internal + */ + function setAnimateFunction(makeAnimator) { + animate = makeAnimator(visualElement); + } + /** + * When we receive new props, we need to: + * 1. Create a list of protected keys for each type. This is a directory of + * value keys that are currently being "handled" by types of a higher priority + * so that whenever an animation is played of a given type, these values are + * protected from being animated. + * 2. Determine if an animation type needs animating. + * 3. Determine if any values have been removed from a type and figure out + * what to animate those to. + */ + function animateChanges(options, changedActiveType) { + var _a; + var props = visualElement.getProps(); + var context = visualElement.getVariantContext(true) || {}; + /** + * A list of animations that we'll build into as we iterate through the animation + * types. This will get executed at the end of the function. + */ + var animations = []; + /** + * Keep track of which values have been removed. Then, as we hit lower priority + * animation types, we can check if they contain removed values and animate to that. + */ + var removedKeys = new Set(); + /** + * A dictionary of all encountered keys. This is an object to let us build into and + * copy it without iteration. Each time we hit an animation type we set its protected + * keys - the keys its not allowed to animate - to the latest version of this object. + */ + var encounteredKeys = {}; + /** + * If a variant has been removed at a given index, and this component is controlling + * variant animations, we want to ensure lower-priority variants are forced to animate. + */ + var removedVariantIndex = Infinity; + var _loop_1 = function (i) { + var type = reversePriorityOrder[i]; + var typeState = state[type]; + var prop = + (_a = props[type]) !== null && _a !== void 0 + ? _a + : context[type]; + var propIsVariant = isVariantLabel(prop); + /** + * If this type has *just* changed isActive status, set activeDelta + * to that status. Otherwise set to null. + */ + var activeDelta = + type === changedActiveType ? typeState.isActive : null; + if (activeDelta === false) removedVariantIndex = i; + /** + * If this prop is an inherited variant, rather than been set directly on the + * component itself, we want to make sure we allow the parent to trigger animations. + * + * TODO: Can probably change this to a !isControllingVariants check + */ + var isInherited = + prop === context[type] && prop !== props[type] && propIsVariant; + /** + * + */ + if ( + isInherited && + isInitialRender && + visualElement.manuallyAnimateOnMount + ) { + isInherited = false; + } + /** + * Set all encountered keys so far as the protected keys for this type. This will + * be any key that has been animated or otherwise handled by active, higher-priortiy types. + */ + typeState.protectedKeys = tslib.__assign({}, encounteredKeys); + // Check if we can skip analysing this prop early + if ( + // If it isn't active and hasn't *just* been set as inactive + (!typeState.isActive && activeDelta === null) || + // If we didn't and don't have any defined prop for this animation type + (!prop && !typeState.prevProp) || + // Or if the prop doesn't define an animation + isAnimationControls(prop) || + typeof prop === "boolean" + ) { + return "continue"; + } + /** + * As we go look through the values defined on this type, if we detect + * a changed value or a value that was removed in a higher priority, we set + * this to true and add this prop to the animation list. + */ + var variantDidChange = checkVariantsDidChange( + typeState.prevProp, + prop + ); + var shouldAnimateType = + variantDidChange || + // If we're making this variant active, we want to always make it active + (type === changedActiveType && + typeState.isActive && + !isInherited && + propIsVariant) || + // If we removed a higher-priority variant (i is in reverse order) + (i > removedVariantIndex && propIsVariant); + /** + * As animations can be set as variant lists, variants or target objects, we + * coerce everything to an array if it isn't one already + */ + var definitionList = Array.isArray(prop) ? prop : [prop]; + /** + * Build an object of all the resolved values. We'll use this in the subsequent + * animateChanges calls to determine whether a value has changed. + */ + var resolvedValues = definitionList.reduce( + buildResolvedTypeValues, + {} + ); + if (activeDelta === false) resolvedValues = {}; + /** + * Now we need to loop through all the keys in the prev prop and this prop, + * and decide: + * 1. If the value has changed, and needs animating + * 2. If it has been removed, and needs adding to the removedKeys set + * 3. If it has been removed in a higher priority type and needs animating + * 4. If it hasn't been removed in a higher priority but hasn't changed, and + * needs adding to the type's protectedKeys list. + */ + var _b = typeState.prevResolvedValues, + prevResolvedValues = _b === void 0 ? {} : _b; + var allKeys = tslib.__assign( + tslib.__assign({}, prevResolvedValues), + resolvedValues + ); + var markToAnimate = function (key) { + shouldAnimateType = true; + removedKeys.delete(key); + typeState.needsAnimating[key] = true; + }; + for (var key in allKeys) { + var next = resolvedValues[key]; + var prev = prevResolvedValues[key]; + // If we've already handled this we can just skip ahead + if (encounteredKeys.hasOwnProperty(key)) continue; + /** + * If the value has changed, we probably want to animate it. + */ + if (next !== prev) { + /** + * If both values are keyframes, we need to shallow compare them to + * detect whether any value has changed. If it has, we animate it. + */ + if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { + if (!shallowCompare(next, prev) || variantDidChange) { + markToAnimate(key); + } else { + /** + * If it hasn't changed, we want to ensure it doesn't animate by + * adding it to the list of protected keys. + */ + typeState.protectedKeys[key] = true; + } + } else if (next !== undefined) { + // If next is defined and doesn't equal prev, it needs animating + markToAnimate(key); + } else { + // If it's undefined, it's been removed. + removedKeys.add(key); + } + } else if (next !== undefined && removedKeys.has(key)) { + /** + * If next hasn't changed and it isn't undefined, we want to check if it's + * been removed by a higher priority + */ + markToAnimate(key); + } else { + /** + * If it hasn't changed, we add it to the list of protected values + * to ensure it doesn't get animated. + */ + typeState.protectedKeys[key] = true; + } + } + /** + * Update the typeState so next time animateChanges is called we can compare the + * latest prop and resolvedValues to these. + */ + typeState.prevProp = prop; + typeState.prevResolvedValues = resolvedValues; + /** + * + */ + if (typeState.isActive) { + encounteredKeys = tslib.__assign( + tslib.__assign({}, encounteredKeys), + resolvedValues + ); + } + if (isInitialRender && visualElement.blockInitialAnimation) { + shouldAnimateType = false; + } + /** + * If this is an inherited prop we want to hard-block animations + * TODO: Test as this should probably still handle animations triggered + * by removed values? + */ + if (shouldAnimateType && !isInherited) { + animations.push.apply( + animations, + tslib.__spreadArray( + [], + tslib.__read( + definitionList.map(function (animation) { + return { + animation: animation, + options: tslib.__assign( + { + type: type, + }, + options + ), + }; + }) + ), + false + ) + ); + } + }; + /** + * Iterate through all animation types in reverse priority order. For each, we want to + * detect which values it's handling and whether or not they've changed (and therefore + * need to be animated). If any values have been removed, we want to detect those in + * lower priority props and flag for animation. + */ + for (var i = 0; i < numAnimationTypes; i++) { + _loop_1(i); + } + allAnimatedKeys = tslib.__assign({}, encounteredKeys); + /** + * If there are some removed value that haven't been dealt with, + * we need to create a new animation that falls back either to the value + * defined in the style prop, or the last read value. + */ + if (removedKeys.size) { + var fallbackAnimation_1 = {}; + removedKeys.forEach(function (key) { + var fallbackTarget = visualElement.getBaseTarget(key); + if (fallbackTarget !== undefined) { + fallbackAnimation_1[key] = fallbackTarget; + } + }); + animations.push({ + animation: fallbackAnimation_1, + }); + } + var shouldAnimate = Boolean(animations.length); + if ( + isInitialRender && + props.initial === false && + !visualElement.manuallyAnimateOnMount + ) { + shouldAnimate = false; + } + isInitialRender = false; + return shouldAnimate ? animate(animations) : Promise.resolve(); + } + /** + * Change whether a certain animation type is active. + */ + function setActive(type, isActive, options) { + var _a; + // If the active state hasn't changed, we can safely do nothing here + if (state[type].isActive === isActive) return Promise.resolve(); + // Propagate active change to children + (_a = visualElement.variantChildren) === null || _a === void 0 + ? void 0 + : _a.forEach(function (child) { + var _a; + return (_a = child.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(type, isActive); + }); + state[type].isActive = isActive; + var animations = animateChanges(options, type); + for (var key in state) { + state[key].protectedKeys = {}; + } + return animations; + } + return { + isAnimated: isAnimated, + animateChanges: animateChanges, + setActive: setActive, + setAnimateFunction: setAnimateFunction, + getState: function () { + return state; + }, + }; + } + function checkVariantsDidChange(prev, next) { + if (typeof next === "string") { + return next !== prev; + } else if (isVariantLabels(next)) { + return !shallowCompare(next, prev); + } + return false; + } + function createTypeState(isActive) { + if (isActive === void 0) { + isActive = false; + } + return { + isActive: isActive, + protectedKeys: {}, + needsAnimating: {}, + prevResolvedValues: {}, + }; + } + function createState() { + var _a; + return ( + (_a = {}), + (_a[exports.AnimationType.Animate] = createTypeState(true)), + (_a[exports.AnimationType.InView] = createTypeState()), + (_a[exports.AnimationType.Hover] = createTypeState()), + (_a[exports.AnimationType.Tap] = createTypeState()), + (_a[exports.AnimationType.Drag] = createTypeState()), + (_a[exports.AnimationType.Focus] = createTypeState()), + (_a[exports.AnimationType.Exit] = createTypeState()), + _a + ); + } + var animations = { + animation: makeRenderlessComponent(function (_a) { + var visualElement = _a.visualElement, + animate = _a.animate; + /** + * We dynamically generate the AnimationState manager as it contains a reference + * to the underlying animation library. We only want to load that if we load this, + * so people can optionally code split it out using the `m` component. + */ + visualElement.animationState || + (visualElement.animationState = + createAnimationState(visualElement)); + /** + * Subscribe any provided AnimationControls to the component's VisualElement + */ + if (isAnimationControls(animate)) { + React.useEffect( + function () { + return animate.subscribe(visualElement); + }, + [animate] + ); + } + }), + exit: makeRenderlessComponent(function (props) { + var custom = props.custom, + visualElement = props.visualElement; + var _a = tslib.__read(usePresence(), 2), + isPresent = _a[0], + safeToRemove = _a[1]; + var presenceContext = React.useContext(PresenceContext); + React.useEffect( + function () { + var _a, _b; + visualElement.isPresent = isPresent; + var animation = + (_a = visualElement.animationState) === null || _a === void 0 + ? void 0 + : _a.setActive(exports.AnimationType.Exit, !isPresent, { + custom: + (_b = + presenceContext === null || + presenceContext === void 0 + ? void 0 + : presenceContext.custom) !== null && + _b !== void 0 + ? _b + : custom, + }); + !isPresent && + (animation === null || animation === void 0 + ? void 0 + : animation.then(safeToRemove)); + }, + [isPresent] + ); + }), + }; + + /** + * @internal + */ + var PanSession = /** @class */ (function () { + function PanSession(event, handlers, _a) { + var _this = this; + var _b = _a === void 0 ? {} : _a, + transformPagePoint = _b.transformPagePoint; + /** + * @internal + */ + this.startEvent = null; + /** + * @internal + */ + this.lastMoveEvent = null; + /** + * @internal + */ + this.lastMoveEventInfo = null; + /** + * @internal + */ + this.handlers = {}; + this.updatePoint = function () { + if (!(_this.lastMoveEvent && _this.lastMoveEventInfo)) return; + var info = getPanInfo(_this.lastMoveEventInfo, _this.history); + var isPanStarted = _this.startEvent !== null; + // Only start panning if the offset is larger than 3 pixels. If we make it + // any larger than this we'll want to reset the pointer history + // on the first update to avoid visual snapping to the cursoe. + var isDistancePastThreshold = + popmotion.distance(info.offset, { + x: 0, + y: 0, + }) >= 3; + if (!isPanStarted && !isDistancePastThreshold) return; + var point = info.point; + var timestamp = sync.getFrameData().timestamp; + _this.history.push( + tslib.__assign(tslib.__assign({}, point), { + timestamp: timestamp, + }) + ); + var _a = _this.handlers, + onStart = _a.onStart, + onMove = _a.onMove; + if (!isPanStarted) { + onStart && onStart(_this.lastMoveEvent, info); + _this.startEvent = _this.lastMoveEvent; + } + onMove && onMove(_this.lastMoveEvent, info); + }; + this.handlePointerMove = function (event, info) { + _this.lastMoveEvent = event; + _this.lastMoveEventInfo = transformPoint( + info, + _this.transformPagePoint + ); + // Because Safari doesn't trigger mouseup events when it's above a `` - if (isMouseEvent(event) && event.buttons === 0) { - _this.handlePointerUp(event, info); - return; - } - // Throttle mouse move event to once per frame - sync__default["default"].update(_this.updatePoint, true); - }; - this.handlePointerUp = function (event, info) { - _this.end(); - var _a = _this.handlers, - onEnd = _a.onEnd, - onSessionEnd = _a.onSessionEnd; - var panInfo = getPanInfo(transformPoint(info, _this.transformPagePoint), _this.history); - if (_this.startEvent && onEnd) { - onEnd(event, panInfo); - } - onSessionEnd && onSessionEnd(event, panInfo); - }; - // If we have more than one touch, don't start detecting this gesture - if (isTouchEvent(event) && event.touches.length > 1) return; - this.handlers = handlers; - this.transformPagePoint = transformPagePoint; - var info = extractEventInfo(event); - var initialInfo = transformPoint(info, this.transformPagePoint); - var point = initialInfo.point; - var timestamp = sync.getFrameData().timestamp; - this.history = [tslib.__assign(tslib.__assign({}, point), { - timestamp: timestamp - })]; - var onSessionStart = handlers.onSessionStart; - onSessionStart && onSessionStart(event, getPanInfo(initialInfo, this.history)); - this.removeListeners = popmotion.pipe(addPointerEvent(window, "pointermove", this.handlePointerMove), addPointerEvent(window, "pointerup", this.handlePointerUp), addPointerEvent(window, "pointercancel", this.handlePointerUp)); - } - PanSession.prototype.updateHandlers = function (handlers) { - this.handlers = handlers; - }; - PanSession.prototype.end = function () { - this.removeListeners && this.removeListeners(); - sync.cancelSync.update(this.updatePoint); - }; - return PanSession; -}(); -function transformPoint(info, transformPagePoint) { - return transformPagePoint ? { - point: transformPagePoint(info.point) - } : info; -} -function subtractPoint(a, b) { - return { - x: a.x - b.x, - y: a.y - b.y - }; -} -function getPanInfo(_a, history) { - var point = _a.point; - return { - point: point, - delta: subtractPoint(point, lastDevicePoint(history)), - offset: subtractPoint(point, startDevicePoint(history)), - velocity: getVelocity(history, 0.1) - }; -} -function startDevicePoint(history) { - return history[0]; -} -function lastDevicePoint(history) { - return history[history.length - 1]; -} -function getVelocity(history, timeDelta) { - if (history.length < 2) { - return { - x: 0, - y: 0 - }; - } - var i = history.length - 1; - var timestampedPoint = null; - var lastPoint = lastDevicePoint(history); - while (i >= 0) { - timestampedPoint = history[i]; - if (lastPoint.timestamp - timestampedPoint.timestamp > secondsToMilliseconds(timeDelta)) { - break; - } - i--; - } - if (!timestampedPoint) { - return { - x: 0, - y: 0 - }; - } - var time = (lastPoint.timestamp - timestampedPoint.timestamp) / 1000; - if (time === 0) { - return { - x: 0, - y: 0 - }; - } - var currentVelocity = { - x: (lastPoint.x - timestampedPoint.x) / time, - y: (lastPoint.y - timestampedPoint.y) / time - }; - if (currentVelocity.x === Infinity) { - currentVelocity.x = 0; - } - if (currentVelocity.y === Infinity) { - currentVelocity.y = 0; - } - return currentVelocity; -} -function calcLength(axis) { - return axis.max - axis.min; -} -function isNear(value, target, maxDistance) { - if (target === void 0) { - target = 0; - } - if (maxDistance === void 0) { - maxDistance = 0.01; - } - return popmotion.distance(value, target) < maxDistance; -} -function calcAxisDelta(delta, source, target, origin) { - if (origin === void 0) { - origin = 0.5; - } - delta.origin = origin; - delta.originPoint = popmotion.mix(source.min, source.max, delta.origin); - delta.scale = calcLength(target) / calcLength(source); - if (isNear(delta.scale, 1, 0.0001) || isNaN(delta.scale)) delta.scale = 1; - delta.translate = popmotion.mix(target.min, target.max, delta.origin) - delta.originPoint; - if (isNear(delta.translate) || isNaN(delta.translate)) delta.translate = 0; -} -function calcBoxDelta(delta, source, target, origin) { - calcAxisDelta(delta.x, source.x, target.x, origin === null || origin === void 0 ? void 0 : origin.originX); - calcAxisDelta(delta.y, source.y, target.y, origin === null || origin === void 0 ? void 0 : origin.originY); -} -function calcRelativeAxis(target, relative, parent) { - target.min = parent.min + relative.min; - target.max = target.min + calcLength(relative); -} -function calcRelativeBox(target, relative, parent) { - calcRelativeAxis(target.x, relative.x, parent.x); - calcRelativeAxis(target.y, relative.y, parent.y); -} -function calcRelativeAxisPosition(target, layout, parent) { - target.min = layout.min - parent.min; - target.max = target.min + calcLength(layout); -} -function calcRelativePosition(target, layout, parent) { - calcRelativeAxisPosition(target.x, layout.x, parent.x); - calcRelativeAxisPosition(target.y, layout.y, parent.y); -} - -/** - * Apply constraints to a point. These constraints are both physical along an - * axis, and an elastic factor that determines how much to constrain the point - * by if it does lie outside the defined parameters. - */ -function applyConstraints(point, _a, elastic) { - var min = _a.min, - max = _a.max; - if (min !== undefined && point < min) { - // If we have a min point defined, and this is outside of that, constrain - point = elastic ? popmotion.mix(min, point, elastic.min) : Math.max(point, min); - } else if (max !== undefined && point > max) { - // If we have a max point defined, and this is outside of that, constrain - point = elastic ? popmotion.mix(max, point, elastic.max) : Math.min(point, max); - } - return point; -} -/** - * Calculate constraints in terms of the viewport when defined relatively to the - * measured axis. This is measured from the nearest edge, so a max constraint of 200 - * on an axis with a max value of 300 would return a constraint of 500 - axis length - */ -function calcRelativeAxisConstraints(axis, min, max) { - return { - min: min !== undefined ? axis.min + min : undefined, - max: max !== undefined ? axis.max + max - (axis.max - axis.min) : undefined - }; -} -/** - * Calculate constraints in terms of the viewport when - * defined relatively to the measured bounding box. - */ -function calcRelativeConstraints(layoutBox, _a) { - var top = _a.top, - left = _a.left, - bottom = _a.bottom, - right = _a.right; - return { - x: calcRelativeAxisConstraints(layoutBox.x, left, right), - y: calcRelativeAxisConstraints(layoutBox.y, top, bottom) - }; -} -/** - * Calculate viewport constraints when defined as another viewport-relative axis - */ -function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { - var _a; - var min = constraintsAxis.min - layoutAxis.min; - var max = constraintsAxis.max - layoutAxis.max; - // If the constraints axis is actually smaller than the layout axis then we can - // flip the constraints - if (constraintsAxis.max - constraintsAxis.min < layoutAxis.max - layoutAxis.min) { - _a = tslib.__read([max, min], 2), min = _a[0], max = _a[1]; - } - return { - min: min, - max: max - }; -} -/** - * Calculate viewport constraints when defined as another viewport-relative box - */ -function calcViewportConstraints(layoutBox, constraintsBox) { - return { - x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), - y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y) - }; -} -/** - * Calculate a transform origin relative to the source axis, between 0-1, that results - * in an asthetically pleasing scale/transform needed to project from source to target. - */ -function calcOrigin(source, target) { - var origin = 0.5; - var sourceLength = calcLength(source); - var targetLength = calcLength(target); - if (targetLength > sourceLength) { - origin = popmotion.progress(target.min, target.max - sourceLength, source.min); - } else if (sourceLength > targetLength) { - origin = popmotion.progress(source.min, source.max - targetLength, target.min); - } - return popmotion.clamp(0, 1, origin); -} -/** - * Rebase the calculated viewport constraints relative to the layout.min point. - */ -function rebaseAxisConstraints(layout, constraints) { - var relativeConstraints = {}; - if (constraints.min !== undefined) { - relativeConstraints.min = constraints.min - layout.min; - } - if (constraints.max !== undefined) { - relativeConstraints.max = constraints.max - layout.min; - } - return relativeConstraints; -} -var defaultElastic = 0.35; -/** - * Accepts a dragElastic prop and returns resolved elastic values for each axis. - */ -function resolveDragElastic(dragElastic) { - if (dragElastic === void 0) { - dragElastic = defaultElastic; - } - if (dragElastic === false) { - dragElastic = 0; - } else if (dragElastic === true) { - dragElastic = defaultElastic; - } - return { - x: resolveAxisElastic(dragElastic, "left", "right"), - y: resolveAxisElastic(dragElastic, "top", "bottom") - }; -} -function resolveAxisElastic(dragElastic, minLabel, maxLabel) { - return { - min: resolvePointElastic(dragElastic, minLabel), - max: resolvePointElastic(dragElastic, maxLabel) - }; -} -function resolvePointElastic(dragElastic, label) { - var _a; - return typeof dragElastic === "number" ? dragElastic : (_a = dragElastic[label]) !== null && _a !== void 0 ? _a : 0; -} -var createAxisDelta = function () { - return { - translate: 0, - scale: 1, - origin: 0, - originPoint: 0 - }; -}; -var createDelta = function () { - return { - x: createAxisDelta(), - y: createAxisDelta() - }; -}; -var createAxis = function () { - return { - min: 0, - max: 0 - }; -}; -var createBox = function () { - return { - x: createAxis(), - y: createAxis() - }; -}; -function eachAxis(callback) { - return [callback("x"), callback("y")]; -} - -/** - * Bounding boxes tend to be defined as top, left, right, bottom. For various operations - * it's easier to consider each axis individually. This function returns a bounding box - * as a map of single-axis min/max values. - */ -function convertBoundingBoxToBox(_a) { - var top = _a.top, - left = _a.left, - right = _a.right, - bottom = _a.bottom; - return { - x: { - min: left, - max: right - }, - y: { - min: top, - max: bottom - } - }; -} -function convertBoxToBoundingBox(_a) { - var x = _a.x, - y = _a.y; - return { - top: y.min, - right: x.max, - bottom: y.max, - left: x.min - }; -} -/** - * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function - * provided by Framer to allow measured points to be corrected for device scaling. This is used - * when measuring DOM elements and DOM event points. - */ -function transformBoxPoints(point, transformPoint) { - if (!transformPoint) return point; - var topLeft = transformPoint({ - x: point.left, - y: point.top - }); - var bottomRight = transformPoint({ - x: point.right, - y: point.bottom - }); - return { - top: topLeft.y, - left: topLeft.x, - bottom: bottomRight.y, - right: bottomRight.x - }; -} -function isIdentityScale(scale) { - return scale === undefined || scale === 1; -} -function hasScale(_a) { - var scale = _a.scale, - scaleX = _a.scaleX, - scaleY = _a.scaleY; - return !isIdentityScale(scale) || !isIdentityScale(scaleX) || !isIdentityScale(scaleY); -} -function hasTransform(values) { - return hasScale(values) || hasTranslate(values.x) || hasTranslate(values.y) || values.z || values.rotate || values.rotateX || values.rotateY; -} -function hasTranslate(value) { - return value && value !== "0%"; -} - -/** - * Scales a point based on a factor and an originPoint - */ -function scalePoint(point, scale, originPoint) { - var distanceFromOrigin = point - originPoint; - var scaled = scale * distanceFromOrigin; - return originPoint + scaled; -} -/** - * Applies a translate/scale delta to a point - */ -function applyPointDelta(point, translate, scale, originPoint, boxScale) { - if (boxScale !== undefined) { - point = scalePoint(point, boxScale, originPoint); - } - return scalePoint(point, scale, originPoint) + translate; -} -/** - * Applies a translate/scale delta to an axis - */ -function applyAxisDelta(axis, translate, scale, originPoint, boxScale) { - if (translate === void 0) { - translate = 0; - } - if (scale === void 0) { - scale = 1; - } - axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale); - axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale); -} -/** - * Applies a translate/scale delta to a box - */ -function applyBoxDelta(box, _a) { - var x = _a.x, - y = _a.y; - applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); - applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); -} -/** - * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms - * in a tree upon our box before then calculating how to project it into our desired viewport-relative box - * - * This is the final nested loop within updateLayoutDelta for future refactoring - */ -function applyTreeDeltas(box, treeScale, treePath, isSharedTransition) { - var _a, _b; - if (isSharedTransition === void 0) { - isSharedTransition = false; - } - var treeLength = treePath.length; - if (!treeLength) return; - // Reset the treeScale - treeScale.x = treeScale.y = 1; - var node; - var delta; - for (var i = 0; i < treeLength; i++) { - node = treePath[i]; - delta = node.projectionDelta; - if (((_b = (_a = node.instance) === null || _a === void 0 ? void 0 : _a.style) === null || _b === void 0 ? void 0 : _b.display) === "contents") continue; - if (isSharedTransition && node.options.layoutScroll && node.scroll && node !== node.root) { - transformBox(box, { - x: -node.scroll.x, - y: -node.scroll.y - }); - } - if (delta) { - // Incoporate each ancestor's scale into a culmulative treeScale for this component - treeScale.x *= delta.x.scale; - treeScale.y *= delta.y.scale; - // Apply each ancestor's calculated delta into this component's recorded layout box - applyBoxDelta(box, delta); - } - if (isSharedTransition && hasTransform(node.latestValues)) { - transformBox(box, node.latestValues); - } - } -} -function translateAxis(axis, distance) { - axis.min = axis.min + distance; - axis.max = axis.max + distance; -} -/** - * Apply a transform to an axis from the latest resolved motion values. - * This function basically acts as a bridge between a flat motion value map - * and applyAxisDelta - */ -function transformAxis(axis, transforms, _a) { - var _b = tslib.__read(_a, 3), - key = _b[0], - scaleKey = _b[1], - originKey = _b[2]; - var axisOrigin = transforms[originKey] !== undefined ? transforms[originKey] : 0.5; - var originPoint = popmotion.mix(axis.min, axis.max, axisOrigin); - // Apply the axis delta to the final axis - applyAxisDelta(axis, transforms[key], transforms[scaleKey], originPoint, transforms.scale); -} -/** - * The names of the motion values we want to apply as translation, scale and origin. - */ -var xKeys$1 = ["x", "scaleX", "originX"]; -var yKeys$1 = ["y", "scaleY", "originY"]; -/** - * Apply a transform to a box from the latest resolved motion values. - */ -function transformBox(box, transform) { - transformAxis(box.x, transform, xKeys$1); - transformAxis(box.y, transform, yKeys$1); -} -function measureViewportBox(instance, transformPoint) { - return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); -} -function measurePageBox(element, rootProjectionNode, transformPagePoint) { - var viewportBox = measureViewportBox(element, transformPagePoint); - var scroll = rootProjectionNode.scroll; - if (scroll) { - translateAxis(viewportBox.x, scroll.x); - translateAxis(viewportBox.y, scroll.y); - } - return viewportBox; -} -var elementDragControls = new WeakMap(); -/** - * - */ -// let latestPointerEvent: AnyPointerEvent -var VisualElementDragControls = /** @class */function () { - function VisualElementDragControls(visualElement) { - // This is a reference to the global drag gesture lock, ensuring only one component - // can "capture" the drag of one or both axes. - // TODO: Look into moving this into pansession? - this.openGlobalLock = null; - this.isDragging = false; - this.currentDirection = null; - this.originPoint = { - x: 0, - y: 0 - }; - /** - * The permitted boundaries of travel, in pixels. - */ - this.constraints = false; - this.hasMutatedConstraints = false; - /** - * The per-axis resolved elastic values. - */ - this.elastic = createBox(); - this.visualElement = visualElement; - } - VisualElementDragControls.prototype.start = function (originEvent, _a) { - var _this = this; - var _b = _a === void 0 ? {} : _a, - _c = _b.snapToCursor, - snapToCursor = _c === void 0 ? false : _c; - /** - * Don't start dragging if this component is exiting - */ - if (this.visualElement.isPresent === false) return; - var onSessionStart = function (event) { - // Stop any animations on both axis values immediately. This allows the user to throw and catch - // the component. - _this.stopAnimation(); - if (snapToCursor) { - _this.snapToCursor(extractEventInfo(event, "page").point); - } - }; - var onStart = function (event, info) { - var _a; - // Attempt to grab the global drag gesture lock - maybe make this part of PanSession - var _b = _this.getProps(), - drag = _b.drag, - dragPropagation = _b.dragPropagation, - onDragStart = _b.onDragStart; - if (drag && !dragPropagation) { - if (_this.openGlobalLock) _this.openGlobalLock(); - _this.openGlobalLock = getGlobalLock(drag); - // If we don 't have the lock, don't start dragging - if (!_this.openGlobalLock) return; - } - _this.isDragging = true; - _this.currentDirection = null; - _this.resolveConstraints(); - if (_this.visualElement.projection) { - _this.visualElement.projection.isAnimationBlocked = true; - _this.visualElement.projection.target = undefined; - } - /** - * Record gesture origin - */ - eachAxis(function (axis) { - var _a, _b; - var current = _this.getAxisMotionValue(axis).get() || 0; - /** - * If the MotionValue is a percentage value convert to px - */ - if (styleValueTypes.percent.test(current)) { - var measuredAxis = (_b = (_a = _this.visualElement.projection) === null || _a === void 0 ? void 0 : _a.layout) === null || _b === void 0 ? void 0 : _b.actual[axis]; - if (measuredAxis) { - var length_1 = calcLength(measuredAxis); - current = length_1 * (parseFloat(current) / 100); - } - } - _this.originPoint[axis] = current; - }); - // Fire onDragStart event - onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(event, info); - (_a = _this.visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Drag, true); - }; - var onMove = function (event, info) { - // latestPointerEvent = event - var _a = _this.getProps(), - dragPropagation = _a.dragPropagation, - dragDirectionLock = _a.dragDirectionLock, - onDirectionLock = _a.onDirectionLock, - onDrag = _a.onDrag; - // If we didn't successfully receive the gesture lock, early return. - if (!dragPropagation && !_this.openGlobalLock) return; - var offset = info.offset; - // Attempt to detect drag direction if directionLock is true - if (dragDirectionLock && _this.currentDirection === null) { - _this.currentDirection = getCurrentDirection(offset); - // If we've successfully set a direction, notify listener - if (_this.currentDirection !== null) { - onDirectionLock === null || onDirectionLock === void 0 ? void 0 : onDirectionLock(_this.currentDirection); - } - return; - } - // Update each point with the latest position - _this.updateAxis("x", info.point, offset); - _this.updateAxis("y", info.point, offset); - /** - * Ideally we would leave the renderer to fire naturally at the end of - * this frame but if the element is about to change layout as the result - * of a re-render we want to ensure the browser can read the latest - * bounding box to ensure the pointer and element don't fall out of sync. - */ - _this.visualElement.syncRender(); - /** - * This must fire after the syncRender call as it might trigger a state - * change which itself might trigger a layout update. - */ - onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, info); - }; - var onSessionEnd = function (event, info) { - return _this.stop(event, info); - }; - this.panSession = new PanSession(originEvent, { - onSessionStart: onSessionStart, - onStart: onStart, - onMove: onMove, - onSessionEnd: onSessionEnd - }, { - transformPagePoint: this.visualElement.getTransformPagePoint() - }); - }; - VisualElementDragControls.prototype.stop = function (event, info) { - var isDragging = this.isDragging; - this.cancel(); - if (!isDragging) return; - var velocity = info.velocity; - this.startAnimation(velocity); - var onDragEnd = this.getProps().onDragEnd; - onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd(event, info); - }; - VisualElementDragControls.prototype.cancel = function () { - var _a, _b; - this.isDragging = false; - if (this.visualElement.projection) { - this.visualElement.projection.isAnimationBlocked = false; - } - (_a = this.panSession) === null || _a === void 0 ? void 0 : _a.end(); - this.panSession = undefined; - var dragPropagation = this.getProps().dragPropagation; - if (!dragPropagation && this.openGlobalLock) { - this.openGlobalLock(); - this.openGlobalLock = null; - } - (_b = this.visualElement.animationState) === null || _b === void 0 ? void 0 : _b.setActive(exports.AnimationType.Drag, false); - }; - VisualElementDragControls.prototype.updateAxis = function (axis, _point, offset) { - var drag = this.getProps().drag; - // If we're not dragging this axis, do an early return. - if (!offset || !shouldDrag(axis, drag, this.currentDirection)) return; - var axisValue = this.getAxisMotionValue(axis); - var next = this.originPoint[axis] + offset[axis]; - // Apply constraints - if (this.constraints && this.constraints[axis]) { - next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); - } - axisValue.set(next); - }; - VisualElementDragControls.prototype.resolveConstraints = function () { - var _this = this; - var _a = this.getProps(), - dragConstraints = _a.dragConstraints, - dragElastic = _a.dragElastic; - var layout = (this.visualElement.projection || {}).layout; - var prevConstraints = this.constraints; - if (dragConstraints && isRefObject(dragConstraints)) { - if (!this.constraints) { - this.constraints = this.resolveRefConstraints(); - } - } else { - if (dragConstraints && layout) { - this.constraints = calcRelativeConstraints(layout.actual, dragConstraints); - } else { - this.constraints = false; - } - } - this.elastic = resolveDragElastic(dragElastic); - /** - * If we're outputting to external MotionValues, we want to rebase the measured constraints - * from viewport-relative to component-relative. - */ - if (prevConstraints !== this.constraints && layout && this.constraints && !this.hasMutatedConstraints) { - eachAxis(function (axis) { - if (_this.getAxisMotionValue(axis)) { - _this.constraints[axis] = rebaseAxisConstraints(layout.actual[axis], _this.constraints[axis]); + async function executeSubscription(exeContext) { + const { schema, fragments, operation, variableValues, rootValue } = + exeContext; + const rootType = schema.getSubscriptionType(); + if (rootType == null) { + throw new _GraphQLError.GraphQLError( + "Schema is not configured to execute subscription operation.", + { + nodes: operation, + } + ); + } + const rootFields = (0, _collectFields.collectFields)( + schema, + fragments, + variableValues, + rootType, + operation.selectionSet + ); + const [responseName, fieldNodes] = [...rootFields.entries()][0]; + const fieldDef = (0, _execute.getFieldDef)( + schema, + rootType, + fieldNodes[0] + ); + if (!fieldDef) { + const fieldName = fieldNodes[0].name.value; + throw new _GraphQLError.GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + { + nodes: fieldNodes, + } + ); + } + const path = (0, _Path.addPath)( + undefined, + responseName, + rootType.name + ); + const info = (0, _execute.buildResolveInfo)( + exeContext, + fieldDef, + fieldNodes, + rootType, + path + ); + try { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = (0, _values.getArgumentValues)( + fieldDef, + fieldNodes[0], + variableValues + ); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + const resolveFn = + (_fieldDef$subscribe = fieldDef.subscribe) !== null && + _fieldDef$subscribe !== void 0 + ? _fieldDef$subscribe + : exeContext.subscribeFieldResolver; + const eventStream = await resolveFn( + rootValue, + args, + contextValue, + info + ); + if (eventStream instanceof Error) { + throw eventStream; + } + return eventStream; + } catch (error) { + throw (0, _locatedError.locatedError)( + error, + fieldNodes, + (0, _Path.pathToArray)(path) + ); + } } - }); - } - }; - VisualElementDragControls.prototype.resolveRefConstraints = function () { - var _a = this.getProps(), - constraints = _a.dragConstraints, - onMeasureDragConstraints = _a.onMeasureDragConstraints; - if (!constraints || !isRefObject(constraints)) return false; - var constraintsElement = constraints.current; - heyListen.invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop."); - var projection = this.visualElement.projection; - // TODO - if (!projection || !projection.layout) return false; - var constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); - var measuredConstraints = calcViewportConstraints(projection.layout.actual, constraintsBox); - /** - * If there's an onMeasureDragConstraints listener we call it and - * if different constraints are returned, set constraints to that - */ - if (onMeasureDragConstraints) { - var userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); - this.hasMutatedConstraints = !!userConstraints; - if (userConstraints) { - measuredConstraints = convertBoundingBoxToBox(userConstraints); - } - } - return measuredConstraints; - }; - VisualElementDragControls.prototype.startAnimation = function (velocity) { - var _this = this; - var _a = this.getProps(), - drag = _a.drag, - dragMomentum = _a.dragMomentum, - dragElastic = _a.dragElastic, - dragTransition = _a.dragTransition, - dragSnapToOrigin = _a.dragSnapToOrigin, - onDragTransitionEnd = _a.onDragTransitionEnd; - var constraints = this.constraints || {}; - var momentumAnimations = eachAxis(function (axis) { - var _a; - if (!shouldDrag(axis, drag, _this.currentDirection)) { - return; - } - var transition = (_a = constraints === null || constraints === void 0 ? void 0 : constraints[axis]) !== null && _a !== void 0 ? _a : {}; - if (dragSnapToOrigin) transition = { - min: 0, - max: 0 - }; - /** - * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame - * of spring animations so we should look into adding a disable spring option to `inertia`. - * We could do something here where we affect the `bounceStiffness` and `bounceDamping` - * using the value of `dragElastic`. - */ - var bounceStiffness = dragElastic ? 200 : 1000000; - var bounceDamping = dragElastic ? 40 : 10000000; - var inertia = tslib.__assign(tslib.__assign({ - type: "inertia", - velocity: dragMomentum ? velocity[axis] : 0, - bounceStiffness: bounceStiffness, - bounceDamping: bounceDamping, - timeConstant: 750, - restDelta: 1, - restSpeed: 10 - }, dragTransition), transition); - // If we're not animating on an externally-provided `MotionValue` we can use the - // component's animation controls which will handle interactions with whileHover (etc), - // otherwise we just have to animate the `MotionValue` itself. - return _this.startAxisValueAnimation(axis, inertia); - }); - // Run all animations and then resolve the new drag constraints. - return Promise.all(momentumAnimations).then(onDragTransitionEnd); - }; - VisualElementDragControls.prototype.startAxisValueAnimation = function (axis, transition) { - var axisValue = this.getAxisMotionValue(axis); - return startAnimation(axis, axisValue, 0, transition); - }; - VisualElementDragControls.prototype.stopAnimation = function () { - var _this = this; - eachAxis(function (axis) { - return _this.getAxisMotionValue(axis).stop(); - }); - }; - /** - * Drag works differently depending on which props are provided. - * - * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. - * - Otherwise, we apply the delta to the x/y motion values. - */ - VisualElementDragControls.prototype.getAxisMotionValue = function (axis) { - var _a, _b; - var dragKey = "_drag" + axis.toUpperCase(); - var externalMotionValue = this.visualElement.getProps()[dragKey]; - return externalMotionValue ? externalMotionValue : this.visualElement.getValue(axis, (_b = (_a = this.visualElement.getProps().initial) === null || _a === void 0 ? void 0 : _a[axis]) !== null && _b !== void 0 ? _b : 0); - }; - VisualElementDragControls.prototype.snapToCursor = function (point) { - var _this = this; - eachAxis(function (axis) { - var drag = _this.getProps().drag; - // If we're not dragging this axis, do an early return. - if (!shouldDrag(axis, drag, _this.currentDirection)) return; - var projection = _this.visualElement.projection; - var axisValue = _this.getAxisMotionValue(axis); - if (projection && projection.layout) { - var _a = projection.layout.actual[axis], - min = _a.min, - max = _a.max; - axisValue.set(point[axis] - popmotion.mix(min, max, 0.5)); - } - }); - }; - /** - * When the viewport resizes we want to check if the measured constraints - * have changed and, if so, reposition the element within those new constraints - * relative to where it was before the resize. - */ - VisualElementDragControls.prototype.scalePositionWithinConstraints = function () { - var _this = this; - var _a; - var _b = this.getProps(), - drag = _b.drag, - dragConstraints = _b.dragConstraints; - var projection = this.visualElement.projection; - if (!isRefObject(dragConstraints) || !projection || !this.constraints) return; - /** - * Stop current animations as there can be visual glitching if we try to do - * this mid-animation - */ - this.stopAnimation(); - /** - * Record the relative position of the dragged element relative to the - * constraints box and save as a progress value. - */ - var boxProgress = { - x: 0, - y: 0 - }; - eachAxis(function (axis) { - var axisValue = _this.getAxisMotionValue(axis); - if (axisValue) { - var latest = axisValue.get(); - boxProgress[axis] = calcOrigin({ - min: latest, - max: latest - }, _this.constraints[axis]); - } - }); - /** - * Update the layout of this element and resolve the latest drag constraints - */ - var transformTemplate = this.visualElement.getProps().transformTemplate; - this.visualElement.getInstance().style.transform = transformTemplate ? transformTemplate({}, "") : "none"; - (_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll(); - projection.updateLayout(); - this.resolveConstraints(); - /** - * For each axis, calculate the current progress of the layout axis - * within the new constraints. - */ - eachAxis(function (axis) { - if (!shouldDrag(axis, drag, null)) return; - /** - * Calculate a new transform based on the previous box progress - */ - var axisValue = _this.getAxisMotionValue(axis); - var _a = _this.constraints[axis], - min = _a.min, - max = _a.max; - axisValue.set(popmotion.mix(min, max, boxProgress[axis])); - }); - }; - VisualElementDragControls.prototype.addListeners = function () { - var _this = this; - var _a; - elementDragControls.set(this.visualElement, this); - var element = this.visualElement.getInstance(); - /** - * Attach a pointerdown event listener on this DOM element to initiate drag tracking. - */ - var stopPointerListener = addPointerEvent(element, "pointerdown", function (event) { - var _a = _this.getProps(), - drag = _a.drag, - _b = _a.dragListener, - dragListener = _b === void 0 ? true : _b; - drag && dragListener && _this.start(event); - }); - var measureDragConstraints = function () { - var dragConstraints = _this.getProps().dragConstraints; - if (isRefObject(dragConstraints)) { - _this.constraints = _this.resolveRefConstraints(); - } - }; - var projection = this.visualElement.projection; - var stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); - if (projection && !projection.layout) { - (_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll(); - projection.updateLayout(); - } - measureDragConstraints(); - /** - * Attach a window resize listener to scale the draggable target within its defined - * constraints as the window resizes. - */ - var stopResizeListener = addDomEvent(window, "resize", function () { - return _this.scalePositionWithinConstraints(); - }); - /** - * If the element's layout changes, calculate the delta and apply that to - * the drag gesture's origin point. - */ - projection.addEventListener("didUpdate", function (_a) { - var delta = _a.delta, - hasLayoutChanged = _a.hasLayoutChanged; - if (_this.isDragging && hasLayoutChanged) { - eachAxis(function (axis) { - var motionValue = _this.getAxisMotionValue(axis); - if (!motionValue) return; - _this.originPoint[axis] += delta[axis].translate; - motionValue.set(motionValue.get() + delta[axis].translate); - }); - _this.visualElement.syncRender(); - } - }); - return function () { - stopResizeListener(); - stopPointerListener(); - stopMeasureLayoutListener(); - }; - }; - VisualElementDragControls.prototype.getProps = function () { - var props = this.visualElement.getProps(); - var _a = props.drag, - drag = _a === void 0 ? false : _a, - _b = props.dragDirectionLock, - dragDirectionLock = _b === void 0 ? false : _b, - _c = props.dragPropagation, - dragPropagation = _c === void 0 ? false : _c, - _d = props.dragConstraints, - dragConstraints = _d === void 0 ? false : _d, - _e = props.dragElastic, - dragElastic = _e === void 0 ? defaultElastic : _e, - _f = props.dragMomentum, - dragMomentum = _f === void 0 ? true : _f; - return tslib.__assign(tslib.__assign({}, props), { - drag: drag, - dragDirectionLock: dragDirectionLock, - dragPropagation: dragPropagation, - dragConstraints: dragConstraints, - dragElastic: dragElastic, - dragMomentum: dragMomentum - }); - }; - return VisualElementDragControls; -}(); -function shouldDrag(direction, drag, currentDirection) { - return (drag === true || drag === direction) && (currentDirection === null || currentDirection === direction); -} -/** - * Based on a x/y offset determine the current drag direction. If both axis' offsets are lower - * than the provided threshold, return `null`. - * - * @param offset - The x/y offset from origin. - * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction. - */ -function getCurrentDirection(offset, lockThreshold) { - if (lockThreshold === void 0) { - lockThreshold = 10; - } - var direction = null; - if (Math.abs(offset.y) > lockThreshold) { - direction = "y"; - } else if (Math.abs(offset.x) > lockThreshold) { - direction = "x"; - } - return direction; -} - -/** - * A hook that allows an element to be dragged. - * - * @internal - */ -function useDrag(props) { - var groupDragControls = props.dragControls, - visualElement = props.visualElement; - var dragControls = useConstant(function () { - return new VisualElementDragControls(visualElement); - }); - // If we've been provided a DragControls for manual control over the drag gesture, - // subscribe this component to it on mount. - React.useEffect(function () { - return groupDragControls && groupDragControls.subscribe(dragControls); - }, [dragControls, groupDragControls]); - // Apply the event listeners to the element - React.useEffect(function () { - return dragControls.addListeners(); - }, [dragControls]); -} - -/** - * - * @param handlers - - * @param ref - - * - * @privateRemarks - * Currently this sets new pan gesture functions every render. The memo route has been explored - * in the past but ultimately we're still creating new functions every render. An optimisation - * to explore is creating the pan gestures and loading them into a `ref`. - * - * @internal - */ -function usePanGesture(_a) { - var onPan = _a.onPan, - onPanStart = _a.onPanStart, - onPanEnd = _a.onPanEnd, - onPanSessionStart = _a.onPanSessionStart, - visualElement = _a.visualElement; - var hasPanEvents = onPan || onPanStart || onPanEnd || onPanSessionStart; - var panSession = React.useRef(null); - var transformPagePoint = React.useContext(MotionConfigContext).transformPagePoint; - var handlers = { - onSessionStart: onPanSessionStart, - onStart: onPanStart, - onMove: onPan, - onEnd: function (event, info) { - panSession.current = null; - onPanEnd && onPanEnd(event, info); - } - }; - React.useEffect(function () { - if (panSession.current !== null) { - panSession.current.updateHandlers(handlers); - } - }); - function onPointerDown(event) { - panSession.current = new PanSession(event, handlers, { - transformPagePoint: transformPagePoint - }); - } - usePointerEvent(visualElement, "pointerdown", hasPanEvents && onPointerDown); - useUnmountEffect(function () { - return panSession.current && panSession.current.end(); - }); -} -var drag = { - pan: makeRenderlessComponent(usePanGesture), - drag: makeRenderlessComponent(useDrag) -}; -var names = ["LayoutMeasure", "BeforeLayoutMeasure", "LayoutUpdate", "ViewportBoxUpdate", "Update", "Render", "AnimationComplete", "LayoutAnimationComplete", "AnimationStart", "LayoutAnimationStart", "SetAxisTarget", "Unmount"]; -function createLifecycles() { - var managers = names.map(function () { - return new SubscriptionManager(); - }); - var propSubscriptions = {}; - var lifecycles = { - clearAllListeners: function () { - return managers.forEach(function (manager) { - return manager.clear(); - }); - }, - updatePropListeners: function (props) { - names.forEach(function (name) { - var _a; - var on = "on" + name; - var propListener = props[on]; - // Unsubscribe existing subscription - (_a = propSubscriptions[name]) === null || _a === void 0 ? void 0 : _a.call(propSubscriptions); - // Add new subscription - if (propListener) { - propSubscriptions[name] = lifecycles[on](propListener); - } - }); - } - }; - managers.forEach(function (manager, i) { - lifecycles["on" + names[i]] = function (handler) { - return manager.add(handler); - }; - lifecycles["notify" + names[i]] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return manager.notify.apply(manager, tslib.__spreadArray([], tslib.__read(args), false)); - }; - }); - return lifecycles; -} -function updateMotionValuesFromProps(element, next, prev) { - var _a; - for (var key in next) { - var nextValue = next[key]; - var prevValue = prev[key]; - if (isMotionValue(nextValue)) { - /** - * If this is a motion value found in props or style, we want to add it - * to our visual element's motion value map. - */ - element.addValue(key, nextValue); - /** - * Check the version of the incoming motion value with this version - * and warn against mismatches. - */ - if (true) { - warnOnce(nextValue.version === "6.5.1", "Attempting to mix Framer Motion versions ".concat(nextValue.version, " with 6.5.1 may not work as expected.")); - } - } else if (isMotionValue(prevValue)) { - /** - * If we're swapping to a new motion value, create a new motion value - * from that - */ - element.addValue(key, motionValue(nextValue)); - } else if (prevValue !== nextValue) { - /** - * If this is a flat value that has changed, update the motion value - * or create one if it doesn't exist. We only want to do this if we're - * not handling the value with our animation state. - */ - if (element.hasValue(key)) { - var existingValue = element.getValue(key); - // TODO: Only update values that aren't being animated or even looked at - !existingValue.hasAnimated && existingValue.set(nextValue); - } else { - element.addValue(key, motionValue((_a = element.getStaticValue(key)) !== null && _a !== void 0 ? _a : nextValue)); - } - } - } - // Handle removed values - for (var key in prev) { - if (next[key] === undefined) element.removeValue(key); - } - return next; -} -var visualElement = function (_a) { - var _b = _a.treeType, - treeType = _b === void 0 ? "" : _b, - build = _a.build, - getBaseTarget = _a.getBaseTarget, - makeTargetAnimatable = _a.makeTargetAnimatable, - measureViewportBox = _a.measureViewportBox, - renderInstance = _a.render, - readValueFromInstance = _a.readValueFromInstance, - removeValueFromRenderState = _a.removeValueFromRenderState, - sortNodePosition = _a.sortNodePosition, - scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps; - return function (_a, options) { - var parent = _a.parent, - props = _a.props, - presenceId = _a.presenceId, - blockInitialAnimation = _a.blockInitialAnimation, - visualState = _a.visualState, - shouldReduceMotion = _a.shouldReduceMotion; - if (options === void 0) { - options = {}; - } - var isMounted = false; - var latestValues = visualState.latestValues, - renderState = visualState.renderState; - /** - * The instance of the render-specific node that will be hydrated by the - * exposed React ref. So for example, this visual element can host a - * HTMLElement, plain object, or Three.js object. The functions provided - * in VisualElementConfig allow us to interface with this instance. - */ - var instance; - /** - * Manages the subscriptions for a visual element's lifecycle, for instance - * onRender - */ - var lifecycles = createLifecycles(); - /** - * A map of all motion values attached to this visual element. Motion - * values are source of truth for any given animated value. A motion - * value might be provided externally by the component via props. - */ - var values = new Map(); - /** - * A map of every subscription that binds the provided or generated - * motion values onChange listeners to this visual element. - */ - var valueSubscriptions = new Map(); - /** - * A reference to the previously-provided motion values as returned - * from scrapeMotionValuesFromProps. We use the keys in here to determine - * if any motion values need to be removed after props are updated. - */ - var prevMotionValues = {}; - /** - * When values are removed from all animation props we need to search - * for a fallback value to animate to. These values are tracked in baseTarget. - */ - var baseTarget = tslib.__assign({}, latestValues); - // Internal methods ======================== - /** - * On mount, this will be hydrated with a callback to disconnect - * this visual element from its parent on unmount. - */ - var removeFromVariantTree; - /** - * Render the element with the latest styles outside of the React - * render lifecycle - */ - function render() { - if (!instance || !isMounted) return; - triggerBuild(); - renderInstance(instance, renderState, props.style, element.projection); - } - function triggerBuild() { - build(element, renderState, latestValues, options, props); - } - function update() { - lifecycles.notifyUpdate(latestValues); - } - /** - * - */ - function bindToMotionValue(key, value) { - var removeOnChange = value.onChange(function (latestValue) { - latestValues[key] = latestValue; - props.onUpdate && sync__default["default"].update(update, false, true); - }); - var removeOnRenderRequest = value.onRenderRequest(element.scheduleRender); - valueSubscriptions.set(key, function () { - removeOnChange(); - removeOnRenderRequest(); - }); - } - /** - * Any motion values that are provided to the element when created - * aren't yet bound to the element, as this would technically be impure. - * However, we iterate through the motion values and set them to the - * initial values for this component. - * - * TODO: This is impure and we should look at changing this to run on mount. - * Doing so will break some tests but this isn't neccessarily a breaking change, - * more a reflection of the test. - */ - var initialMotionValues = scrapeMotionValuesFromProps(props); - for (var key in initialMotionValues) { - var value = initialMotionValues[key]; - if (latestValues[key] !== undefined && isMotionValue(value)) { - value.set(latestValues[key], false); - } - } - /** - * Determine what role this visual element should take in the variant tree. - */ - var isControllingVariants = checkIfControllingVariants(props); - var isVariantNode = checkIfVariantNode(props); - var element = tslib.__assign(tslib.__assign({ - treeType: treeType, - /** - * This is a mirror of the internal instance prop, which keeps - * VisualElement type-compatible with React's RefObject. - */ - current: null, - /** - * The depth of this visual element within the visual element tree. - */ - depth: parent ? parent.depth + 1 : 0, - parent: parent, - children: new Set(), - /** - * - */ - presenceId: presenceId, - shouldReduceMotion: shouldReduceMotion, - /** - * If this component is part of the variant tree, it should track - * any children that are also part of the tree. This is essentially - * a shadow tree to simplify logic around how to stagger over children. - */ - variantChildren: isVariantNode ? new Set() : undefined, - /** - * Whether this instance is visible. This can be changed imperatively - * by the projection tree, is analogous to CSS's visibility in that - * hidden elements should take up layout, and needs enacting by the configured - * render function. - */ - isVisible: undefined, - /** - * Normally, if a component is controlled by a parent's variants, it can - * rely on that ancestor to trigger animations further down the tree. - * However, if a component is created after its parent is mounted, the parent - * won't trigger that mount animation so the child needs to. - * - * TODO: This might be better replaced with a method isParentMounted - */ - manuallyAnimateOnMount: Boolean(parent === null || parent === void 0 ? void 0 : parent.isMounted()), - /** - * This can be set by AnimatePresence to force components that mount - * at the same time as it to mount as if they have initial={false} set. - */ - blockInitialAnimation: blockInitialAnimation, - /** - * Determine whether this component has mounted yet. This is mostly used - * by variant children to determine whether they need to trigger their - * own animations on mount. - */ - isMounted: function () { - return Boolean(instance); + + /***/ + }, + + /***/ "../../../node_modules/graphql/execution/values.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/execution/values.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getArgumentValues = getArgumentValues; + exports.getDirectiveValues = getDirectiveValues; + exports.getVariableValues = getVariableValues; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _printPathArray = __webpack_require__( + /*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _printer = __webpack_require__( + /*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _coerceInputValue = __webpack_require__( + /*! ../utilities/coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + var _valueFromAST = __webpack_require__( + /*! ../utilities/valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs" + ); + /** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors; + try { + const coerced = coerceVariableValues( + schema, + varDefNodes, + inputs, + (error) => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new _GraphQLError.GraphQLError( + "Too many errors processing variables, error limit reached. Execution aborted." + ); + } + errors.push(error); + } + ); + if (errors.length === 0) { + return { + coerced, + }; + } + } catch (error) { + errors.push(error); + } + return { + errors, + }; + } + function coerceVariableValues(schema, varDefNodes, inputs, onError) { + const coercedValues = {}; + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = (0, _typeFromAST.typeFromAST)( + schema, + varDefNode.type + ); + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = (0, _printer.print)(varDefNode.type); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, + { + nodes: varDefNode.type, + } + ) + ); + continue; + } + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)( + varDefNode.defaultValue, + varType + ); + } else if ((0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, + { + nodes: varDefNode, + } + ) + ); + } + continue; + } + const value = inputs[varName]; + if (value === null && (0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, + { + nodes: varDefNode, + } + ) + ); + continue; + } + coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)( + value, + varType, + (path, invalidValue, error) => { + let prefix = + `Variable "$${varName}" got invalid value ` + + (0, _inspect.inspect)(invalidValue); + if (path.length > 0) { + prefix += ` at "${varName}${(0, + _printPathArray.printPathArray)(path)}"`; + } + onError( + new _GraphQLError.GraphQLError( + prefix + "; " + error.message, + { + nodes: varDefNode, + originalError: error, + } + ) + ); + } + ); + } + return coercedValues; + } + /** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + function getArgumentValues(def, node, variableValues) { + var _node$arguments; + const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = + (_node$arguments = node.arguments) !== null && + _node$arguments !== void 0 + ? _node$arguments + : []; + const argNodeMap = (0, _keyMap.keyMap)( + argumentNodes, + (arg) => arg.name.value + ); + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of required type "${(0, _inspect.inspect)( + argType + )}" ` + "was not provided.", + { + nodes: node, + } + ); + } + continue; + } + const valueNode = argumentNode.value; + let isNull = valueNode.kind === _kinds.Kind.NULL; + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if ( + variableValues == null || + !hasOwnProperty(variableValues, variableName) + ) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of required type "${(0, + _inspect.inspect)(argType)}" ` + + `was provided the variable "$${variableName}" which was not provided a runtime value.`, + { + nodes: valueNode, + } + ); + } + continue; + } + isNull = variableValues[variableName] == null; + } + if (isNull && (0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of non-null type "${(0, _inspect.inspect)( + argType + )}" ` + "must not be null.", + { + nodes: valueNode, + } + ); + } + const coercedValue = (0, _valueFromAST.valueFromAST)( + valueNode, + argType, + variableValues + ); + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError( + `Argument "${name}" has invalid value ${(0, _printer.print)( + valueNode + )}.`, + { + nodes: valueNode, + } + ); + } + coercedValues[name] = coercedValue; + } + return coercedValues; + } + /** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + function getDirectiveValues(directiveDef, node, variableValues) { + var _node$directives; + const directiveNode = + (_node$directives = node.directives) === null || + _node$directives === void 0 + ? void 0 + : _node$directives.find( + (directive) => directive.name.value === directiveDef.name + ); + if (directiveNode) { + return getArgumentValues( + directiveDef, + directiveNode, + variableValues + ); + } + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /***/ }, - mount: function (newInstance) { - isMounted = true; - instance = element.current = newInstance; - if (element.projection) { - element.projection.mount(newInstance); + + /***/ "../../../node_modules/graphql/graphql.mjs": + /*!*************************************************!*\ + !*** ../../../node_modules/graphql/graphql.mjs ***! + \*************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.graphql = graphql; + exports.graphqlSync = graphqlSync; + var _devAssert = __webpack_require__( + /*! ./jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _isPromise = __webpack_require__( + /*! ./jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs" + ); + var _parser = __webpack_require__( + /*! ./language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs" + ); + var _validate = __webpack_require__( + /*! ./type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs" + ); + var _validate2 = __webpack_require__( + /*! ./validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs" + ); + var _execute = __webpack_require__( + /*! ./execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs" + ); + /** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + * typeResolver: + * A type resolver function to use when none is provided by the schema. + * If not provided, the default type resolver is used (which looks for a + * `__typename` field or alternatively calls the `isTypeOf` method). + */ + + function graphql(args) { + // Always return a Promise for a consistent API. + return new Promise((resolve) => resolve(graphqlImpl(args))); + } + /** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + function graphqlSync(args) { + const result = graphqlImpl(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error( + "GraphQL execution failed to complete synchronously." + ); + } + return result; } - if (isVariantNode && parent && !isControllingVariants) { - removeFromVariantTree = parent === null || parent === void 0 ? void 0 : parent.addVariantChild(element); + function graphqlImpl(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + "graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead." + ); + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + } = args; // Validate Schema + + const schemaValidationErrors = (0, _validate.validateSchema)(schema); + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors, + }; + } // Parse + + let document; + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError], + }; + } // Validate + + const validationErrors = (0, _validate2.validate)(schema, document); + if (validationErrors.length > 0) { + return { + errors: validationErrors, + }; + } // Execute + + return (0, _execute.execute)({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); } - values.forEach(function (value, key) { - return bindToMotionValue(key, value); + + /***/ + }, + + /***/ "../../../node_modules/graphql/index.mjs": + /*!***********************************************!*\ + !*** ../../../node_modules/graphql/index.mjs ***! + \***********************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function () { + return _index2.BREAK; + }, + }); + Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function () { + return _index6.BreakingChangeType; + }, + }); + Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function () { + return _index.DEFAULT_DEPRECATION_REASON; + }, + }); + Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function () { + return _index6.DangerousChangeType; + }, + }); + Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function () { + return _index2.DirectiveLocation; + }, + }); + Object.defineProperty(exports, "ExecutableDefinitionsRule", { + enumerable: true, + get: function () { + return _index4.ExecutableDefinitionsRule; + }, + }); + Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function () { + return _index4.FieldsOnCorrectTypeRule; + }, + }); + Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function () { + return _index4.FragmentsOnCompositeTypesRule; + }, + }); + Object.defineProperty(exports, "GRAPHQL_MAX_INT", { + enumerable: true, + get: function () { + return _index.GRAPHQL_MAX_INT; + }, + }); + Object.defineProperty(exports, "GRAPHQL_MIN_INT", { + enumerable: true, + get: function () { + return _index.GRAPHQL_MIN_INT; + }, + }); + Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function () { + return _index.GraphQLBoolean; + }, + }); + Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function () { + return _index.GraphQLDeprecatedDirective; + }, + }); + Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function () { + return _index.GraphQLDirective; + }, + }); + Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function () { + return _index.GraphQLEnumType; + }, + }); + Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function () { + return _index5.GraphQLError; + }, + }); + Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function () { + return _index.GraphQLFloat; + }, + }); + Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function () { + return _index.GraphQLID; + }, + }); + Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function () { + return _index.GraphQLIncludeDirective; + }, + }); + Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function () { + return _index.GraphQLInputObjectType; + }, + }); + Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function () { + return _index.GraphQLInt; + }, + }); + Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function () { + return _index.GraphQLInterfaceType; + }, + }); + Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function () { + return _index.GraphQLList; + }, + }); + Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function () { + return _index.GraphQLNonNull; + }, + }); + Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function () { + return _index.GraphQLObjectType; + }, + }); + Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function () { + return _index.GraphQLScalarType; + }, + }); + Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function () { + return _index.GraphQLSchema; + }, + }); + Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function () { + return _index.GraphQLSkipDirective; + }, + }); + Object.defineProperty(exports, "GraphQLSpecifiedByDirective", { + enumerable: true, + get: function () { + return _index.GraphQLSpecifiedByDirective; + }, + }); + Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function () { + return _index.GraphQLString; + }, + }); + Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function () { + return _index.GraphQLUnionType; + }, + }); + Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function () { + return _index2.Kind; + }, + }); + Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function () { + return _index4.KnownArgumentNamesRule; + }, + }); + Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function () { + return _index4.KnownDirectivesRule; + }, + }); + Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function () { + return _index4.KnownFragmentNamesRule; + }, + }); + Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function () { + return _index4.KnownTypeNamesRule; + }, + }); + Object.defineProperty(exports, "Lexer", { + enumerable: true, + get: function () { + return _index2.Lexer; + }, + }); + Object.defineProperty(exports, "Location", { + enumerable: true, + get: function () { + return _index2.Location; + }, + }); + Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function () { + return _index4.LoneAnonymousOperationRule; + }, + }); + Object.defineProperty(exports, "LoneSchemaDefinitionRule", { + enumerable: true, + get: function () { + return _index4.LoneSchemaDefinitionRule; + }, + }); + Object.defineProperty(exports, "NoDeprecatedCustomRule", { + enumerable: true, + get: function () { + return _index4.NoDeprecatedCustomRule; + }, + }); + Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function () { + return _index4.NoFragmentCyclesRule; + }, + }); + Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", { + enumerable: true, + get: function () { + return _index4.NoSchemaIntrospectionCustomRule; + }, + }); + Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function () { + return _index4.NoUndefinedVariablesRule; + }, + }); + Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function () { + return _index4.NoUnusedFragmentsRule; + }, + }); + Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function () { + return _index4.NoUnusedVariablesRule; + }, + }); + Object.defineProperty(exports, "OperationTypeNode", { + enumerable: true, + get: function () { + return _index2.OperationTypeNode; + }, + }); + Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function () { + return _index4.OverlappingFieldsCanBeMergedRule; + }, + }); + Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function () { + return _index4.PossibleFragmentSpreadsRule; + }, + }); + Object.defineProperty(exports, "PossibleTypeExtensionsRule", { + enumerable: true, + get: function () { + return _index4.PossibleTypeExtensionsRule; + }, + }); + Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function () { + return _index4.ProvidedRequiredArgumentsRule; + }, + }); + Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function () { + return _index4.ScalarLeafsRule; + }, + }); + Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function () { + return _index.SchemaMetaFieldDef; + }, + }); + Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function () { + return _index4.SingleFieldSubscriptionsRule; + }, + }); + Object.defineProperty(exports, "Source", { + enumerable: true, + get: function () { + return _index2.Source; + }, + }); + Object.defineProperty(exports, "Token", { + enumerable: true, + get: function () { + return _index2.Token; + }, + }); + Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function () { + return _index2.TokenKind; + }, + }); + Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function () { + return _index6.TypeInfo; + }, + }); + Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function () { + return _index.TypeKind; + }, + }); + Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function () { + return _index.TypeMetaFieldDef; + }, + }); + Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function () { + return _index.TypeNameMetaFieldDef; + }, + }); + Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueArgumentDefinitionNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueArgumentNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueDirectiveNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueDirectiveNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function () { + return _index4.UniqueDirectivesPerLocationRule; + }, + }); + Object.defineProperty(exports, "UniqueEnumValueNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueEnumValueNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueFieldDefinitionNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueFragmentNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueInputFieldNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueOperationNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueOperationTypesRule", { + enumerable: true, + get: function () { + return _index4.UniqueOperationTypesRule; + }, + }); + Object.defineProperty(exports, "UniqueTypeNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueTypeNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function () { + return _index4.UniqueVariableNamesRule; + }, + }); + Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function () { + return _index4.ValidationContext; + }, + }); + Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function () { + return _index4.ValuesOfCorrectTypeRule; + }, + }); + Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function () { + return _index4.VariablesAreInputTypesRule; + }, + }); + Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function () { + return _index4.VariablesInAllowedPositionRule; + }, + }); + Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function () { + return _index.__Directive; + }, + }); + Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function () { + return _index.__DirectiveLocation; + }, + }); + Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function () { + return _index.__EnumValue; + }, + }); + Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function () { + return _index.__Field; + }, + }); + Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function () { + return _index.__InputValue; + }, + }); + Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function () { + return _index.__Schema; + }, + }); + Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function () { + return _index.__Type; + }, + }); + Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function () { + return _index.__TypeKind; + }, + }); + Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function () { + return _index.assertAbstractType; + }, + }); + Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function () { + return _index.assertCompositeType; + }, + }); + Object.defineProperty(exports, "assertDirective", { + enumerable: true, + get: function () { + return _index.assertDirective; + }, + }); + Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function () { + return _index.assertEnumType; + }, + }); + Object.defineProperty(exports, "assertEnumValueName", { + enumerable: true, + get: function () { + return _index.assertEnumValueName; + }, + }); + Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function () { + return _index.assertInputObjectType; + }, + }); + Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function () { + return _index.assertInputType; + }, + }); + Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function () { + return _index.assertInterfaceType; + }, + }); + Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function () { + return _index.assertLeafType; + }, + }); + Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function () { + return _index.assertListType; + }, + }); + Object.defineProperty(exports, "assertName", { + enumerable: true, + get: function () { + return _index.assertName; + }, + }); + Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function () { + return _index.assertNamedType; + }, + }); + Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function () { + return _index.assertNonNullType; + }, + }); + Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function () { + return _index.assertNullableType; + }, + }); + Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function () { + return _index.assertObjectType; + }, + }); + Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function () { + return _index.assertOutputType; + }, + }); + Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function () { + return _index.assertScalarType; + }, + }); + Object.defineProperty(exports, "assertSchema", { + enumerable: true, + get: function () { + return _index.assertSchema; + }, + }); + Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function () { + return _index.assertType; + }, + }); + Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function () { + return _index.assertUnionType; + }, + }); + Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function () { + return _index6.assertValidName; + }, + }); + Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function () { + return _index.assertValidSchema; + }, + }); + Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function () { + return _index.assertWrappingType; + }, + }); + Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function () { + return _index6.astFromValue; + }, + }); + Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function () { + return _index6.buildASTSchema; + }, + }); + Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function () { + return _index6.buildClientSchema; + }, + }); + Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function () { + return _index6.buildSchema; + }, + }); + Object.defineProperty(exports, "coerceInputValue", { + enumerable: true, + get: function () { + return _index6.coerceInputValue; + }, + }); + Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function () { + return _index6.concatAST; + }, + }); + Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function () { + return _index3.createSourceEventStream; + }, + }); + Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function () { + return _index3.defaultFieldResolver; + }, + }); + Object.defineProperty(exports, "defaultTypeResolver", { + enumerable: true, + get: function () { + return _index3.defaultTypeResolver; + }, + }); + Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function () { + return _index6.doTypesOverlap; + }, + }); + Object.defineProperty(exports, "execute", { + enumerable: true, + get: function () { + return _index3.execute; + }, + }); + Object.defineProperty(exports, "executeSync", { + enumerable: true, + get: function () { + return _index3.executeSync; + }, + }); + Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function () { + return _index6.extendSchema; + }, + }); + Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function () { + return _index6.findBreakingChanges; + }, + }); + Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function () { + return _index6.findDangerousChanges; + }, + }); + Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function () { + return _index5.formatError; + }, + }); + Object.defineProperty(exports, "getArgumentValues", { + enumerable: true, + get: function () { + return _index3.getArgumentValues; + }, + }); + Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function () { + return _index3.getDirectiveValues; + }, + }); + Object.defineProperty(exports, "getEnterLeaveForKind", { + enumerable: true, + get: function () { + return _index2.getEnterLeaveForKind; + }, + }); + Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function () { + return _index6.getIntrospectionQuery; + }, + }); + Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function () { + return _index2.getLocation; + }, + }); + Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function () { + return _index.getNamedType; + }, + }); + Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function () { + return _index.getNullableType; + }, + }); + Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function () { + return _index6.getOperationAST; + }, + }); + Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function () { + return _index6.getOperationRootType; + }, + }); + Object.defineProperty(exports, "getVariableValues", { + enumerable: true, + get: function () { + return _index3.getVariableValues; + }, + }); + Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function () { + return _index2.getVisitFn; + }, + }); + Object.defineProperty(exports, "graphql", { + enumerable: true, + get: function () { + return _graphql.graphql; + }, + }); + Object.defineProperty(exports, "graphqlSync", { + enumerable: true, + get: function () { + return _graphql.graphqlSync; + }, + }); + Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function () { + return _index6.introspectionFromSchema; + }, + }); + Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function () { + return _index.introspectionTypes; + }, + }); + Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function () { + return _index.isAbstractType; + }, + }); + Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function () { + return _index.isCompositeType; + }, + }); + Object.defineProperty(exports, "isConstValueNode", { + enumerable: true, + get: function () { + return _index2.isConstValueNode; + }, + }); + Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function () { + return _index2.isDefinitionNode; + }, + }); + Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function () { + return _index.isDirective; + }, + }); + Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function () { + return _index.isEnumType; + }, + }); + Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function () { + return _index6.isEqualType; + }, + }); + Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function () { + return _index2.isExecutableDefinitionNode; + }, + }); + Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function () { + return _index.isInputObjectType; + }, + }); + Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function () { + return _index.isInputType; + }, + }); + Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function () { + return _index.isInterfaceType; + }, + }); + Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function () { + return _index.isIntrospectionType; + }, + }); + Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function () { + return _index.isLeafType; + }, + }); + Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function () { + return _index.isListType; + }, + }); + Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function () { + return _index.isNamedType; + }, + }); + Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function () { + return _index.isNonNullType; + }, + }); + Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function () { + return _index.isNullableType; + }, + }); + Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function () { + return _index.isObjectType; + }, + }); + Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function () { + return _index.isOutputType; + }, + }); + Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function () { + return _index.isRequiredArgument; + }, + }); + Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function () { + return _index.isRequiredInputField; + }, + }); + Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function () { + return _index.isScalarType; + }, + }); + Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function () { + return _index.isSchema; + }, + }); + Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function () { + return _index2.isSelectionNode; + }, + }); + Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function () { + return _index.isSpecifiedDirective; + }, + }); + Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function () { + return _index.isSpecifiedScalarType; + }, + }); + Object.defineProperty(exports, "isType", { + enumerable: true, + get: function () { + return _index.isType; + }, + }); + Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function () { + return _index2.isTypeDefinitionNode; + }, + }); + Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function () { + return _index2.isTypeExtensionNode; + }, + }); + Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function () { + return _index2.isTypeNode; + }, + }); + Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function () { + return _index6.isTypeSubTypeOf; + }, + }); + Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function () { + return _index2.isTypeSystemDefinitionNode; + }, + }); + Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function () { + return _index2.isTypeSystemExtensionNode; + }, + }); + Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function () { + return _index.isUnionType; + }, + }); + Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function () { + return _index6.isValidNameError; + }, + }); + Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function () { + return _index2.isValueNode; + }, + }); + Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function () { + return _index.isWrappingType; + }, + }); + Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function () { + return _index6.lexicographicSortSchema; + }, + }); + Object.defineProperty(exports, "locatedError", { + enumerable: true, + get: function () { + return _index5.locatedError; + }, + }); + Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _index2.parse; + }, + }); + Object.defineProperty(exports, "parseConstValue", { + enumerable: true, + get: function () { + return _index2.parseConstValue; + }, + }); + Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function () { + return _index2.parseType; + }, + }); + Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function () { + return _index2.parseValue; + }, + }); + Object.defineProperty(exports, "print", { + enumerable: true, + get: function () { + return _index2.print; + }, + }); + Object.defineProperty(exports, "printError", { + enumerable: true, + get: function () { + return _index5.printError; + }, + }); + Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function () { + return _index6.printIntrospectionSchema; + }, + }); + Object.defineProperty(exports, "printLocation", { + enumerable: true, + get: function () { + return _index2.printLocation; + }, + }); + Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function () { + return _index6.printSchema; + }, + }); + Object.defineProperty(exports, "printSourceLocation", { + enumerable: true, + get: function () { + return _index2.printSourceLocation; + }, + }); + Object.defineProperty(exports, "printType", { + enumerable: true, + get: function () { + return _index6.printType; + }, + }); + Object.defineProperty(exports, "resolveObjMapThunk", { + enumerable: true, + get: function () { + return _index.resolveObjMapThunk; + }, + }); + Object.defineProperty(exports, "resolveReadonlyArrayThunk", { + enumerable: true, + get: function () { + return _index.resolveReadonlyArrayThunk; + }, + }); + Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function () { + return _index3.responsePathAsArray; + }, + }); + Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function () { + return _index6.separateOperations; + }, + }); + Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function () { + return _index.specifiedDirectives; + }, + }); + Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function () { + return _index4.specifiedRules; + }, + }); + Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function () { + return _index.specifiedScalarTypes; + }, }); - parent === null || parent === void 0 ? void 0 : parent.children.add(element); - element.setProps(props); - }, - /** - * - */ - unmount: function () { - var _a; - (_a = element.projection) === null || _a === void 0 ? void 0 : _a.unmount(); - sync.cancelSync.update(update); - sync.cancelSync.render(render); - valueSubscriptions.forEach(function (remove) { - return remove(); - }); - removeFromVariantTree === null || removeFromVariantTree === void 0 ? void 0 : removeFromVariantTree(); - parent === null || parent === void 0 ? void 0 : parent.children.delete(element); - lifecycles.clearAllListeners(); - instance = undefined; - isMounted = false; - }, - /** - * Add a child visual element to our set of children. - */ - addVariantChild: function (child) { - var _a; - var closestVariantNode = element.getClosestVariantNode(); - if (closestVariantNode) { - (_a = closestVariantNode.variantChildren) === null || _a === void 0 ? void 0 : _a.add(child); - return function () { - return closestVariantNode.variantChildren.delete(child); - }; - } - }, - sortNodePosition: function (other) { - /** - * If these nodes aren't even of the same type we can't compare their depth. - */ - if (!sortNodePosition || treeType !== other.treeType) return 0; - return sortNodePosition(element.getInstance(), other.getInstance()); - }, - /** - * Returns the closest variant node in the tree starting from - * this visual element. - */ - getClosestVariantNode: function () { - return isVariantNode ? element : parent === null || parent === void 0 ? void 0 : parent.getClosestVariantNode(); - }, - /** - * Expose the latest layoutId prop. - */ - getLayoutId: function () { - return props.layoutId; - }, - /** - * Returns the current instance. - */ - getInstance: function () { - return instance; - }, - /** - * Get/set the latest static values. - */ - getStaticValue: function (key) { - return latestValues[key]; - }, - setStaticValue: function (key, value) { - return latestValues[key] = value; - }, - /** - * Returns the latest motion value state. Currently only used to take - * a snapshot of the visual element - perhaps this can return the whole - * visual state - */ - getLatestValues: function () { - return latestValues; - }, - /** - * Set the visiblity of the visual element. If it's changed, schedule - * a render to reflect these changes. - */ - setVisibility: function (visibility) { - if (element.isVisible === visibility) return; - element.isVisible = visibility; - element.scheduleRender(); - }, - /** - * Make a target animatable by Popmotion. For instance, if we're - * trying to animate width from 100px to 100vw we need to measure 100vw - * in pixels to determine what we really need to animate to. This is also - * pluggable to support Framer's custom value types like Color, - * and CSS variables. - */ - makeTargetAnimatable: function (target, canMutate) { - if (canMutate === void 0) { - canMutate = true; - } - return makeTargetAnimatable(element, target, props, canMutate); - }, - /** - * Measure the current viewport box with or without transforms. - * Only measures axis-aligned boxes, rotate and skew must be manually - * removed with a re-render to work. - */ - measureViewportBox: function () { - return measureViewportBox(instance, props); - }, - // Motion values ======================== - /** - * Add a motion value and bind it to this visual element. - */ - addValue: function (key, value) { - // Remove existing value if it exists - if (element.hasValue(key)) element.removeValue(key); - values.set(key, value); - latestValues[key] = value.get(); - bindToMotionValue(key, value); - }, - /** - * Remove a motion value and unbind any active subscriptions. - */ - removeValue: function (key) { - var _a; - values.delete(key); - (_a = valueSubscriptions.get(key)) === null || _a === void 0 ? void 0 : _a(); - valueSubscriptions.delete(key); - delete latestValues[key]; - removeValueFromRenderState(key, renderState); - }, - /** - * Check whether we have a motion value for this key - */ - hasValue: function (key) { - return values.has(key); - }, - /** - * Get a motion value for this key. If called with a default - * value, we'll create one if none exists. - */ - getValue: function (key, defaultValue) { - var value = values.get(key); - if (value === undefined && defaultValue !== undefined) { - value = motionValue(defaultValue); - element.addValue(key, value); - } - return value; - }, - /** - * Iterate over our motion values. - */ - forEachValue: function (callback) { - return values.forEach(callback); - }, - /** - * If we're trying to animate to a previously unencountered value, - * we need to check for it in our state and as a last resort read it - * directly from the instance (which might have performance implications). - */ - readValue: function (key) { - var _a; - return (_a = latestValues[key]) !== null && _a !== void 0 ? _a : readValueFromInstance(instance, key, options); - }, - /** - * Set the base target to later animate back to. This is currently - * only hydrated on creation and when we first read a value. - */ - setBaseTarget: function (key, value) { - baseTarget[key] = value; - }, - /** - * Find the base target for a value thats been removed from all animation - * props. - */ - getBaseTarget: function (key) { - if (getBaseTarget) { - var target = getBaseTarget(props, key); - if (target !== undefined && !isMotionValue(target)) return target; - } - return baseTarget[key]; - } - }, lifecycles), { - /** - * Build the renderer state based on the latest visual state. - */ - build: function () { - triggerBuild(); - return renderState; - }, - /** - * Schedule a render on the next animation frame. - */ - scheduleRender: function () { - sync__default["default"].render(render, false, true); - }, - /** - * Synchronously fire render. It's prefered that we batch renders but - * in many circumstances, like layout measurement, we need to run this - * synchronously. However in those instances other measures should be taken - * to batch reads/writes. - */ - syncRender: render, - /** - * Update the provided props. Ensure any newly-added motion values are - * added to our map, old ones removed, and listeners updated. - */ - setProps: function (newProps) { - if (newProps.transformTemplate || props.transformTemplate) { - element.scheduleRender(); - } - props = newProps; - lifecycles.updatePropListeners(newProps); - prevMotionValues = updateMotionValuesFromProps(element, scrapeMotionValuesFromProps(props), prevMotionValues); - }, - getProps: function () { - return props; - }, - // Variants ============================== - /** - * Returns the variant definition with a given name. - */ - getVariant: function (name) { - var _a; - return (_a = props.variants) === null || _a === void 0 ? void 0 : _a[name]; - }, - /** - * Returns the defined default transition on this component. - */ - getDefaultTransition: function () { - return props.transition; - }, - getTransformPagePoint: function () { - return props.transformPagePoint; - }, - /** - * Used by child variant nodes to get the closest ancestor variant props. - */ - getVariantContext: function (startAtParent) { - if (startAtParent === void 0) { - startAtParent = false; - } - if (startAtParent) return parent === null || parent === void 0 ? void 0 : parent.getVariantContext(); - if (!isControllingVariants) { - var context_1 = (parent === null || parent === void 0 ? void 0 : parent.getVariantContext()) || {}; - if (props.initial !== undefined) { - context_1.initial = props.initial; - } - return context_1; - } - var context = {}; - for (var i = 0; i < numVariantProps; i++) { - var name_1 = variantProps[i]; - var prop = props[name_1]; - if (isVariantLabel(prop) || prop === false) { - context[name_1] = prop; - } - } - return context; - } - }); - return element; - }; -}; -var variantProps = tslib.__spreadArray(["initial"], tslib.__read(variantPriorityOrder), false); -var numVariantProps = variantProps.length; -function isCSSVariable(value) { - return typeof value === "string" && value.startsWith("var(--"); -} -/** - * Parse Framer's special CSS variable format into a CSS token and a fallback. - * - * ``` - * `var(--foo, #fff)` => [`--foo`, '#fff'] - * ``` - * - * @param current - */ -var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; -function parseCSSVariable(current) { - var match = cssVariableRegex.exec(current); - if (!match) return [,]; - var _a = tslib.__read(match, 3), - token = _a[1], - fallback = _a[2]; - return [token, fallback]; -} -var maxDepth = 4; -function getVariableValue(current, element, depth) { - if (depth === void 0) { - depth = 1; - } - heyListen.invariant(depth <= maxDepth, "Max CSS variable fallback depth detected in property \"".concat(current, "\". This may indicate a circular fallback dependency.")); - var _a = tslib.__read(parseCSSVariable(current), 2), - token = _a[0], - fallback = _a[1]; - // No CSS variable detected - if (!token) return; - // Attempt to read this CSS variable off the element - var resolved = window.getComputedStyle(element).getPropertyValue(token); - if (resolved) { - return resolved.trim(); - } else if (isCSSVariable(fallback)) { - // The fallback might itself be a CSS variable, in which case we attempt to resolve it too. - return getVariableValue(fallback, element, depth + 1); - } else { - return fallback; - } -} -/** - * Resolve CSS variables from - * - * @internal - */ -function resolveCSSVariables(visualElement, _a, transitionEnd) { - var _b; - var target = tslib.__rest(_a, []); - var element = visualElement.getInstance(); - if (!(element instanceof Element)) return { - target: target, - transitionEnd: transitionEnd - }; - // If `transitionEnd` isn't `undefined`, clone it. We could clone `target` and `transitionEnd` - // only if they change but I think this reads clearer and this isn't a performance-critical path. - if (transitionEnd) { - transitionEnd = tslib.__assign({}, transitionEnd); - } - // Go through existing `MotionValue`s and ensure any existing CSS variables are resolved - visualElement.forEachValue(function (value) { - var current = value.get(); - if (!isCSSVariable(current)) return; - var resolved = getVariableValue(current, element); - if (resolved) value.set(resolved); - }); - // Cycle through every target property and resolve CSS variables. Currently - // we only read single-var properties like `var(--foo)`, not `calc(var(--foo) + 20px)` - for (var key in target) { - var current = target[key]; - if (!isCSSVariable(current)) continue; - var resolved = getVariableValue(current, element); - if (!resolved) continue; - // Clone target if it hasn't already been - target[key] = resolved; - // If the user hasn't already set this key on `transitionEnd`, set it to the unresolved - // CSS variable. This will ensure that after the animation the component will reflect - // changes in the value of the CSS variable. - if (transitionEnd) (_b = transitionEnd[key]) !== null && _b !== void 0 ? _b : transitionEnd[key] = current; - } - return { - target: target, - transitionEnd: transitionEnd - }; -} -var positionalKeys = new Set(["width", "height", "top", "left", "right", "bottom", "x", "y"]); -var isPositionalKey = function (key) { - return positionalKeys.has(key); -}; -var hasPositionalKey = function (target) { - return Object.keys(target).some(isPositionalKey); -}; -var setAndResetVelocity = function (value, to) { - // Looks odd but setting it twice doesn't render, it'll just - // set both prev and current to the latest value - value.set(to, false); - value.set(to); -}; -var isNumOrPxType = function (v) { - return v === styleValueTypes.number || v === styleValueTypes.px; -}; -var BoundingBoxDimension; -(function (BoundingBoxDimension) { - BoundingBoxDimension["width"] = "width"; - BoundingBoxDimension["height"] = "height"; - BoundingBoxDimension["left"] = "left"; - BoundingBoxDimension["right"] = "right"; - BoundingBoxDimension["top"] = "top"; - BoundingBoxDimension["bottom"] = "bottom"; -})(BoundingBoxDimension || (BoundingBoxDimension = {})); -var getPosFromMatrix = function (matrix, pos) { - return parseFloat(matrix.split(", ")[pos]); -}; -var getTranslateFromMatrix = function (pos2, pos3) { - return function (_bbox, _a) { - var transform = _a.transform; - if (transform === "none" || !transform) return 0; - var matrix3d = transform.match(/^matrix3d\((.+)\)$/); - if (matrix3d) { - return getPosFromMatrix(matrix3d[1], pos3); - } else { - var matrix = transform.match(/^matrix\((.+)\)$/); - if (matrix) { - return getPosFromMatrix(matrix[1], pos2); - } else { - return 0; - } - } - }; -}; -var transformKeys = new Set(["x", "y", "z"]); -var nonTranslationalTransformKeys = transformProps.filter(function (key) { - return !transformKeys.has(key); -}); -function removeNonTranslationalTransform(visualElement) { - var removedTransforms = []; - nonTranslationalTransformKeys.forEach(function (key) { - var value = visualElement.getValue(key); - if (value !== undefined) { - removedTransforms.push([key, value.get()]); - value.set(key.startsWith("scale") ? 1 : 0); - } - }); - // Apply changes to element before measurement - if (removedTransforms.length) visualElement.syncRender(); - return removedTransforms; -} -var positionalValues = { - // Dimensions - width: function (_a, _b) { - var x = _a.x; - var _c = _b.paddingLeft, - paddingLeft = _c === void 0 ? "0" : _c, - _d = _b.paddingRight, - paddingRight = _d === void 0 ? "0" : _d; - return x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight); - }, - height: function (_a, _b) { - var y = _a.y; - var _c = _b.paddingTop, - paddingTop = _c === void 0 ? "0" : _c, - _d = _b.paddingBottom, - paddingBottom = _d === void 0 ? "0" : _d; - return y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom); - }, - top: function (_bbox, _a) { - var top = _a.top; - return parseFloat(top); - }, - left: function (_bbox, _a) { - var left = _a.left; - return parseFloat(left); - }, - bottom: function (_a, _b) { - var y = _a.y; - var top = _b.top; - return parseFloat(top) + (y.max - y.min); - }, - right: function (_a, _b) { - var x = _a.x; - var left = _b.left; - return parseFloat(left) + (x.max - x.min); - }, - // Transform - x: getTranslateFromMatrix(4, 13), - y: getTranslateFromMatrix(5, 14) -}; -var convertChangedValueTypes = function (target, visualElement, changedKeys) { - var originBbox = visualElement.measureViewportBox(); - var element = visualElement.getInstance(); - var elementComputedStyle = getComputedStyle(element); - var display = elementComputedStyle.display; - var origin = {}; - // If the element is currently set to display: "none", make it visible before - // measuring the target bounding box - if (display === "none") { - visualElement.setStaticValue("display", target.display || "block"); - } - /** - * Record origins before we render and update styles - */ - changedKeys.forEach(function (key) { - origin[key] = positionalValues[key](originBbox, elementComputedStyle); - }); - // Apply the latest values (as set in checkAndConvertChangedValueTypes) - visualElement.syncRender(); - var targetBbox = visualElement.measureViewportBox(); - changedKeys.forEach(function (key) { - // Restore styles to their **calculated computed style**, not their actual - // originally set style. This allows us to animate between equivalent pixel units. - var value = visualElement.getValue(key); - setAndResetVelocity(value, origin[key]); - target[key] = positionalValues[key](targetBbox, elementComputedStyle); - }); - return target; -}; -var checkAndConvertChangedValueTypes = function (visualElement, target, origin, transitionEnd) { - if (origin === void 0) { - origin = {}; - } - if (transitionEnd === void 0) { - transitionEnd = {}; - } - target = tslib.__assign({}, target); - transitionEnd = tslib.__assign({}, transitionEnd); - var targetPositionalKeys = Object.keys(target).filter(isPositionalKey); - // We want to remove any transform values that could affect the element's bounding box before - // it's measured. We'll reapply these later. - var removedTransformValues = []; - var hasAttemptedToRemoveTransformValues = false; - var changedValueTypeKeys = []; - targetPositionalKeys.forEach(function (key) { - var value = visualElement.getValue(key); - if (!visualElement.hasValue(key)) return; - var from = origin[key]; - var fromType = findDimensionValueType(from); - var to = target[key]; - var toType; - // TODO: The current implementation of this basically throws an error - // if you try and do value conversion via keyframes. There's probably - // a way of doing this but the performance implications would need greater scrutiny, - // as it'd be doing multiple resize-remeasure operations. - if (isKeyframesTarget(to)) { - var numKeyframes = to.length; - var fromIndex = to[0] === null ? 1 : 0; - from = to[fromIndex]; - fromType = findDimensionValueType(from); - for (var i = fromIndex; i < numKeyframes; i++) { - if (!toType) { - toType = findDimensionValueType(to[i]); - heyListen.invariant(toType === fromType || isNumOrPxType(fromType) && isNumOrPxType(toType), "Keyframes must be of the same dimension as the current value"); - } else { - heyListen.invariant(findDimensionValueType(to[i]) === toType, "All keyframes must be of the same type"); - } - } - } else { - toType = findDimensionValueType(to); - } - if (fromType !== toType) { - // If they're both just number or px, convert them both to numbers rather than - // relying on resize/remeasure to convert (which is wasteful in this situation) - if (isNumOrPxType(fromType) && isNumOrPxType(toType)) { - var current = value.get(); - if (typeof current === "string") { - value.set(parseFloat(current)); - } - if (typeof to === "string") { - target[key] = parseFloat(to); - } else if (Array.isArray(to) && toType === styleValueTypes.px) { - target[key] = to.map(parseFloat); - } - } else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) && (toType === null || toType === void 0 ? void 0 : toType.transform) && (from === 0 || to === 0)) { - // If one or the other value is 0, it's safe to coerce it to the - // type of the other without measurement - if (from === 0) { - value.set(toType.transform(from)); - } else { - target[key] = fromType.transform(to); - } - } else { - // If we're going to do value conversion via DOM measurements, we first - // need to remove non-positional transform values that could affect the bbox measurements. - if (!hasAttemptedToRemoveTransformValues) { - removedTransformValues = removeNonTranslationalTransform(visualElement); - hasAttemptedToRemoveTransformValues = true; - } - changedValueTypeKeys.push(key); - transitionEnd[key] = transitionEnd[key] !== undefined ? transitionEnd[key] : target[key]; - setAndResetVelocity(value, to); - } - } - }); - if (changedValueTypeKeys.length) { - var scrollY_1 = changedValueTypeKeys.indexOf("height") >= 0 ? window.pageYOffset : null; - var convertedTarget = convertChangedValueTypes(target, visualElement, changedValueTypeKeys); - // If we removed transform values, reapply them before the next render - if (removedTransformValues.length) { - removedTransformValues.forEach(function (_a) { - var _b = tslib.__read(_a, 2), - key = _b[0], - value = _b[1]; - visualElement.getValue(key).set(value); - }); - } - // Reapply original values - visualElement.syncRender(); - // Restore scroll position - if (scrollY_1 !== null) window.scrollTo({ - top: scrollY_1 - }); - return { - target: convertedTarget, - transitionEnd: transitionEnd - }; - } else { - return { - target: target, - transitionEnd: transitionEnd - }; - } -}; -/** - * Convert value types for x/y/width/height/top/left/bottom/right - * - * Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'` - * - * @internal - */ -function unitConversion(visualElement, target, origin, transitionEnd) { - return hasPositionalKey(target) ? checkAndConvertChangedValueTypes(visualElement, target, origin, transitionEnd) : { - target: target, - transitionEnd: transitionEnd - }; -} - -/** - * Parse a DOM variant to make it animatable. This involves resolving CSS variables - * and ensuring animations like "20%" => "calc(50vw)" are performed in pixels. - */ -var parseDomVariant = function (visualElement, target, origin, transitionEnd) { - var resolved = resolveCSSVariables(visualElement, target, transitionEnd); - target = resolved.target; - transitionEnd = resolved.transitionEnd; - return unitConversion(visualElement, target, origin, transitionEnd); -}; -function getComputedStyle$1(element) { - return window.getComputedStyle(element); -} -var htmlConfig = { - treeType: "dom", - readValueFromInstance: function (domElement, key) { - if (isTransformProp(key)) { - var defaultType = getDefaultValueType(key); - return defaultType ? defaultType.default || 0 : 0; - } else { - var computedStyle = getComputedStyle$1(domElement); - return (isCSSVariable$1(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0; - } - }, - sortNodePosition: function (a, b) { - /** - * compareDocumentPosition returns a bitmask, by using the bitwise & - * we're returning true if 2 in that bitmask is set to true. 2 is set - * to true if b preceeds a. - */ - return a.compareDocumentPosition(b) & 2 ? 1 : -1; - }, - getBaseTarget: function (props, key) { - var _a; - return (_a = props.style) === null || _a === void 0 ? void 0 : _a[key]; - }, - measureViewportBox: function (element, _a) { - var transformPagePoint = _a.transformPagePoint; - return measureViewportBox(element, transformPagePoint); - }, - /** - * Reset the transform on the current Element. This is called as part - * of a batched process across the entire layout tree. To remove this write - * cycle it'd be interesting to see if it's possible to "undo" all the current - * layout transforms up the tree in the same way this.getBoundingBoxWithoutTransforms - * works - */ - resetTransform: function (element, domElement, props) { - var transformTemplate = props.transformTemplate; - domElement.style.transform = transformTemplate ? transformTemplate({}, "") : "none"; - // Ensure that whatever happens next, we restore our transform on the next frame - element.scheduleRender(); - }, - restoreTransform: function (instance, mutableState) { - instance.style.transform = mutableState.style.transform; - }, - removeValueFromRenderState: function (key, _a) { - var vars = _a.vars, - style = _a.style; - delete vars[key]; - delete style[key]; - }, - /** - * Ensure that HTML and Framer-specific value types like `px`->`%` and `Color` - * can be animated by Motion. - */ - makeTargetAnimatable: function (element, _a, _b, isMounted) { - var transformValues = _b.transformValues; - if (isMounted === void 0) { - isMounted = true; - } - var transition = _a.transition, - transitionEnd = _a.transitionEnd, - target = tslib.__rest(_a, ["transition", "transitionEnd"]); - var origin = getOrigin(target, transition || {}, element); - /** - * If Framer has provided a function to convert `Color` etc value types, convert them - */ - if (transformValues) { - if (transitionEnd) transitionEnd = transformValues(transitionEnd); - if (target) target = transformValues(target); - if (origin) origin = transformValues(origin); - } - if (isMounted) { - checkTargetForNewValues(element, target, origin); - var parsed = parseDomVariant(element, target, origin, transitionEnd); - transitionEnd = parsed.transitionEnd; - target = parsed.target; - } - return tslib.__assign({ - transition: transition, - transitionEnd: transitionEnd - }, target); - }, - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, - build: function (element, renderState, latestValues, options, props) { - if (element.isVisible !== undefined) { - renderState.style.visibility = element.isVisible ? "visible" : "hidden"; - } - buildHTMLStyles(renderState, latestValues, options, props.transformTemplate); - }, - render: renderHTML -}; -var htmlVisualElement = visualElement(htmlConfig); -var svgVisualElement = visualElement(tslib.__assign(tslib.__assign({}, htmlConfig), { - getBaseTarget: function (props, key) { - return props[key]; - }, - readValueFromInstance: function (domElement, key) { - var _a; - if (isTransformProp(key)) { - return ((_a = getDefaultValueType(key)) === null || _a === void 0 ? void 0 : _a.default) || 0; - } - key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; - return domElement.getAttribute(key); - }, - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, - build: function (_element, renderState, latestValues, options, props) { - buildSVGAttrs(renderState, latestValues, options, props.transformTemplate); - }, - render: renderSVG -})); -var createDomVisualElement = function (Component, options) { - return isSVGComponent(Component) ? svgVisualElement(options, { - enableHardwareAcceleration: false - }) : htmlVisualElement(options, { - enableHardwareAcceleration: true - }); -}; -function pixelsToPercent(pixels, axis) { - if (axis.max === axis.min) return 0; - return pixels / (axis.max - axis.min) * 100; -} -/** - * We always correct borderRadius as a percentage rather than pixels to reduce paints. - * For example, if you are projecting a box that is 100px wide with a 10px borderRadius - * into a box that is 200px wide with a 20px borderRadius, that is actually a 10% - * borderRadius in both states. If we animate between the two in pixels that will trigger - * a paint each time. If we animate between the two in percentage we'll avoid a paint. - */ -var correctBorderRadius = { - correct: function (latest, node) { - if (!node.target) return latest; - /** - * If latest is a string, if it's a percentage we can return immediately as it's - * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number. - */ - if (typeof latest === "string") { - if (styleValueTypes.px.test(latest)) { - latest = parseFloat(latest); - } else { - return latest; - } - } - /** - * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that - * pixel value as a percentage of each axis - */ - var x = pixelsToPercent(latest, node.target.x); - var y = pixelsToPercent(latest, node.target.y); - return "".concat(x, "% ").concat(y, "%"); - } -}; -var varToken = "_$css"; -var correctBoxShadow = { - correct: function (latest, _a) { - var treeScale = _a.treeScale, - projectionDelta = _a.projectionDelta; - var original = latest; - /** - * We need to first strip and store CSS variables from the string. - */ - var containsCSSVariables = latest.includes("var("); - var cssVariables = []; - if (containsCSSVariables) { - latest = latest.replace(cssVariableRegex, function (match) { - cssVariables.push(match); - return varToken; - }); - } - var shadow = styleValueTypes.complex.parse(latest); - // TODO: Doesn't support multiple shadows - if (shadow.length > 5) return original; - var template = styleValueTypes.complex.createTransformer(latest); - var offset = typeof shadow[0] !== "number" ? 1 : 0; - // Calculate the overall context scale - var xScale = projectionDelta.x.scale * treeScale.x; - var yScale = projectionDelta.y.scale * treeScale.y; - shadow[0 + offset] /= xScale; - shadow[1 + offset] /= yScale; - /** - * Ideally we'd correct x and y scales individually, but because blur and - * spread apply to both we have to take a scale average and apply that instead. - * We could potentially improve the outcome of this by incorporating the ratio between - * the two scales. - */ - var averageScale = popmotion.mix(xScale, yScale, 0.5); - // Blur - if (typeof shadow[2 + offset] === "number") shadow[2 + offset] /= averageScale; - // Spread - if (typeof shadow[3 + offset] === "number") shadow[3 + offset] /= averageScale; - var output = template(shadow); - if (containsCSSVariables) { - var i_1 = 0; - output = output.replace(varToken, function () { - var cssVariable = cssVariables[i_1]; - i_1++; - return cssVariable; - }); - } - return output; - } -}; -var MeasureLayoutWithContext = /** @class */function (_super) { - tslib.__extends(MeasureLayoutWithContext, _super); - function MeasureLayoutWithContext() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * This only mounts projection nodes for components that - * need measuring, we might want to do it for all components - * in order to incorporate transforms - */ - MeasureLayoutWithContext.prototype.componentDidMount = function () { - var _this = this; - var _a = this.props, - visualElement = _a.visualElement, - layoutGroup = _a.layoutGroup, - switchLayoutGroup = _a.switchLayoutGroup, - layoutId = _a.layoutId; - var projection = visualElement.projection; - addScaleCorrector(defaultScaleCorrectors); - if (projection) { - if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group) layoutGroup.group.add(projection); - if ((switchLayoutGroup === null || switchLayoutGroup === void 0 ? void 0 : switchLayoutGroup.register) && layoutId) { - switchLayoutGroup.register(projection); - } - projection.root.didUpdate(); - projection.addEventListener("animationComplete", function () { - _this.safeToRemove(); - }); - projection.setOptions(tslib.__assign(tslib.__assign({}, projection.options), { - onExitComplete: function () { - return _this.safeToRemove(); - } - })); - } - globalProjectionState.hasEverUpdated = true; - }; - MeasureLayoutWithContext.prototype.getSnapshotBeforeUpdate = function (prevProps) { - var _this = this; - var _a = this.props, - layoutDependency = _a.layoutDependency, - visualElement = _a.visualElement, - drag = _a.drag, - isPresent = _a.isPresent; - var projection = visualElement.projection; - if (!projection) return null; - /** - * TODO: We use this data in relegate to determine whether to - * promote a previous element. There's no guarantee its presence data - * will have updated by this point - if a bug like this arises it will - * have to be that we markForRelegation and then find a new lead some other way, - * perhaps in didUpdate - */ - projection.isPresent = isPresent; - if (drag || prevProps.layoutDependency !== layoutDependency || layoutDependency === undefined) { - projection.willUpdate(); - } else { - this.safeToRemove(); - } - if (prevProps.isPresent !== isPresent) { - if (isPresent) { - projection.promote(); - } else if (!projection.relegate()) { - /** - * If there's another stack member taking over from this one, - * it's in charge of the exit animation and therefore should - * be in charge of the safe to remove. Otherwise we call it here. - */ - sync__default["default"].postRender(function () { - var _a; - if (!((_a = projection.getStack()) === null || _a === void 0 ? void 0 : _a.members.length)) { - _this.safeToRemove(); - } + Object.defineProperty(exports, "stripIgnoredCharacters", { + enumerable: true, + get: function () { + return _index6.stripIgnoredCharacters; + }, }); - } - } - return null; - }; - MeasureLayoutWithContext.prototype.componentDidUpdate = function () { - var projection = this.props.visualElement.projection; - if (projection) { - projection.root.didUpdate(); - if (!projection.currentAnimation && projection.isLead()) { - this.safeToRemove(); - } - } - }; - MeasureLayoutWithContext.prototype.componentWillUnmount = function () { - var _a = this.props, - visualElement = _a.visualElement, - layoutGroup = _a.layoutGroup, - promoteContext = _a.switchLayoutGroup; - var projection = visualElement.projection; - if (projection) { - projection.scheduleCheckAfterUnmount(); - if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group) layoutGroup.group.remove(projection); - if (promoteContext === null || promoteContext === void 0 ? void 0 : promoteContext.deregister) promoteContext.deregister(projection); - } - }; - MeasureLayoutWithContext.prototype.safeToRemove = function () { - var safeToRemove = this.props.safeToRemove; - safeToRemove === null || safeToRemove === void 0 ? void 0 : safeToRemove(); - }; - MeasureLayoutWithContext.prototype.render = function () { - return null; - }; - return MeasureLayoutWithContext; -}(React__default["default"].Component); -function MeasureLayout(props) { - var _a = tslib.__read(usePresence(), 2), - isPresent = _a[0], - safeToRemove = _a[1]; - var layoutGroup = React.useContext(LayoutGroupContext); - return React__default["default"].createElement(MeasureLayoutWithContext, tslib.__assign({}, props, { - layoutGroup: layoutGroup, - switchLayoutGroup: React.useContext(SwitchLayoutGroupContext), - isPresent: isPresent, - safeToRemove: safeToRemove - })); -} -var defaultScaleCorrectors = { - borderRadius: tslib.__assign(tslib.__assign({}, correctBorderRadius), { - applyTo: ["borderTopLeftRadius", "borderTopRightRadius", "borderBottomLeftRadius", "borderBottomRightRadius"] - }), - borderTopLeftRadius: correctBorderRadius, - borderTopRightRadius: correctBorderRadius, - borderBottomLeftRadius: correctBorderRadius, - borderBottomRightRadius: correctBorderRadius, - boxShadow: correctBoxShadow -}; -var layoutFeatures = { - measureLayout: MeasureLayout -}; - -/** - * Animate a single value or a `MotionValue`. - * - * The first argument is either a `MotionValue` to animate, or an initial animation value. - * - * The second is either a value to animate to, or an array of keyframes to animate through. - * - * The third argument can be either tween or spring options, and optional lifecycle methods: `onUpdate`, `onPlay`, `onComplete`, `onRepeat` and `onStop`. - * - * Returns `AnimationPlaybackControls`, currently just a `stop` method. - * - * ```javascript - * const x = useMotionValue(0) - * - * useEffect(() => { - * const controls = animate(x, 100, { - * type: "spring", - * stiffness: 2000, - * onComplete: v => {} - * }) - * - * return controls.stop - * }) - * ``` - * - * @public - */ -function animate(from, to, transition) { - if (transition === void 0) { - transition = {}; - } - var value = isMotionValue(from) ? from : motionValue(from); - startAnimation("", value, to, transition); - return { - stop: function () { - return value.stop(); - }, - isAnimating: function () { - return value.isAnimating(); - } - }; -} -var borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"]; -var numBorders = borders.length; -var asNumber = function (value) { - return typeof value === "string" ? parseFloat(value) : value; -}; -var isPx = function (value) { - return typeof value === "number" || styleValueTypes.px.test(value); -}; -function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) { - var _a, _b, _c, _d; - if (shouldCrossfadeOpacity) { - target.opacity = popmotion.mix(0, - // (follow?.opacity as number) ?? 0, - // TODO Reinstate this if only child - (_a = lead.opacity) !== null && _a !== void 0 ? _a : 1, easeCrossfadeIn(progress)); - target.opacityExit = popmotion.mix((_b = follow.opacity) !== null && _b !== void 0 ? _b : 1, 0, easeCrossfadeOut(progress)); - } else if (isOnlyMember) { - target.opacity = popmotion.mix((_c = follow.opacity) !== null && _c !== void 0 ? _c : 1, (_d = lead.opacity) !== null && _d !== void 0 ? _d : 1, progress); - } - /** - * Mix border radius - */ - for (var i = 0; i < numBorders; i++) { - var borderLabel = "border".concat(borders[i], "Radius"); - var followRadius = getRadius(follow, borderLabel); - var leadRadius = getRadius(lead, borderLabel); - if (followRadius === undefined && leadRadius === undefined) continue; - followRadius || (followRadius = 0); - leadRadius || (leadRadius = 0); - var canMix = followRadius === 0 || leadRadius === 0 || isPx(followRadius) === isPx(leadRadius); - if (canMix) { - target[borderLabel] = Math.max(popmotion.mix(asNumber(followRadius), asNumber(leadRadius), progress), 0); - if (styleValueTypes.percent.test(leadRadius) || styleValueTypes.percent.test(followRadius)) { - target[borderLabel] += "%"; - } - } else { - target[borderLabel] = leadRadius; - } - } - /** - * Mix rotation - */ - if (follow.rotate || lead.rotate) { - target.rotate = popmotion.mix(follow.rotate || 0, lead.rotate || 0, progress); - } -} -function getRadius(values, radiusName) { - var _a; - return (_a = values[radiusName]) !== null && _a !== void 0 ? _a : values.borderRadius; -} -// /** -// * We only want to mix the background color if there's a follow element -// * that we're not crossfading opacity between. For instance with switch -// * AnimateSharedLayout animations, this helps the illusion of a continuous -// * element being animated but also cuts down on the number of paints triggered -// * for elements where opacity is doing that work for us. -// */ -// if ( -// !hasFollowElement && -// latestLeadValues.backgroundColor && -// latestFollowValues.backgroundColor -// ) { -// /** -// * This isn't ideal performance-wise as mixColor is creating a new function every frame. -// * We could probably create a mixer that runs at the start of the animation but -// * the idea behind the crossfader is that it runs dynamically between two potentially -// * changing targets (ie opacity or borderRadius may be animating independently via variants) -// */ -// leadState.backgroundColor = followState.backgroundColor = mixColor( -// latestFollowValues.backgroundColor as string, -// latestLeadValues.backgroundColor as string -// )(p) -// } -var easeCrossfadeIn = compress(0, 0.5, popmotion.circOut); -var easeCrossfadeOut = compress(0.5, 0.95, popmotion.linear); -function compress(min, max, easing) { - return function (p) { - // Could replace ifs with clamp - if (p < min) return 0; - if (p > max) return 1; - return easing(popmotion.progress(min, max, p)); - }; -} - -/** - * Reset an axis to the provided origin box. - * - * This is a mutative operation. - */ -function copyAxisInto(axis, originAxis) { - axis.min = originAxis.min; - axis.max = originAxis.max; -} -/** - * Reset a box to the provided origin box. - * - * This is a mutative operation. - */ -function copyBoxInto(box, originBox) { - copyAxisInto(box.x, originBox.x); - copyAxisInto(box.y, originBox.y); -} - -/** - * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse - */ -function removePointDelta(point, translate, scale, originPoint, boxScale) { - point -= translate; - point = scalePoint(point, 1 / scale, originPoint); - if (boxScale !== undefined) { - point = scalePoint(point, 1 / boxScale, originPoint); - } - return point; -} -/** - * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse - */ -function removeAxisDelta(axis, translate, scale, origin, boxScale, originAxis, sourceAxis) { - if (translate === void 0) { - translate = 0; - } - if (scale === void 0) { - scale = 1; - } - if (origin === void 0) { - origin = 0.5; - } - if (originAxis === void 0) { - originAxis = axis; - } - if (sourceAxis === void 0) { - sourceAxis = axis; - } - if (styleValueTypes.percent.test(translate)) { - translate = parseFloat(translate); - var relativeProgress = popmotion.mix(sourceAxis.min, sourceAxis.max, translate / 100); - translate = relativeProgress - sourceAxis.min; - } - if (typeof translate !== "number") return; - var originPoint = popmotion.mix(originAxis.min, originAxis.max, origin); - if (axis === originAxis) originPoint -= translate; - axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale); - axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale); -} -/** - * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse - * and acts as a bridge between motion values and removeAxisDelta - */ -function removeAxisTransforms(axis, transforms, _a, origin, sourceAxis) { - var _b = tslib.__read(_a, 3), - key = _b[0], - scaleKey = _b[1], - originKey = _b[2]; - removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); -} -/** - * The names of the motion values we want to apply as translation, scale and origin. - */ -var xKeys = ["x", "scaleX", "originX"]; -var yKeys = ["y", "scaleY", "originY"]; -/** - * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse - * and acts as a bridge between motion values and removeAxisDelta - */ -function removeBoxTransforms(box, transforms, originBox, sourceBox) { - removeAxisTransforms(box.x, transforms, xKeys, originBox === null || originBox === void 0 ? void 0 : originBox.x, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.x); - removeAxisTransforms(box.y, transforms, yKeys, originBox === null || originBox === void 0 ? void 0 : originBox.y, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.y); -} -function isAxisDeltaZero(delta) { - return delta.translate === 0 && delta.scale === 1; -} -function isDeltaZero(delta) { - return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); -} -function boxEquals(a, b) { - return a.x.min === b.x.min && a.x.max === b.x.max && a.y.min === b.y.min && a.y.max === b.y.max; -} -var NodeStack = /** @class */function () { - function NodeStack() { - this.members = []; - } - NodeStack.prototype.add = function (node) { - addUniqueItem(this.members, node); - node.scheduleRender(); - }; - NodeStack.prototype.remove = function (node) { - removeItem(this.members, node); - if (node === this.prevLead) { - this.prevLead = undefined; - } - if (node === this.lead) { - var prevLead = this.members[this.members.length - 1]; - if (prevLead) { - this.promote(prevLead); - } - } - }; - NodeStack.prototype.relegate = function (node) { - var indexOfNode = this.members.findIndex(function (member) { - return node === member; - }); - if (indexOfNode === 0) return false; - /** - * Find the next projection node that is present - */ - var prevLead; - for (var i = indexOfNode; i >= 0; i--) { - var member = this.members[i]; - if (member.isPresent !== false) { - prevLead = member; - break; - } - } - if (prevLead) { - this.promote(prevLead); - return true; - } else { - return false; - } - }; - NodeStack.prototype.promote = function (node, preserveFollowOpacity) { - var _a; - var prevLead = this.lead; - if (node === prevLead) return; - this.prevLead = prevLead; - this.lead = node; - node.show(); - if (prevLead) { - prevLead.instance && prevLead.scheduleRender(); - node.scheduleRender(); - node.resumeFrom = prevLead; - if (preserveFollowOpacity) { - node.resumeFrom.preserveOpacity = true; - } - if (prevLead.snapshot) { - node.snapshot = prevLead.snapshot; - node.snapshot.latestValues = prevLead.animationValues || prevLead.latestValues; - node.snapshot.isShared = true; - } - if ((_a = node.root) === null || _a === void 0 ? void 0 : _a.isUpdating) { - node.isLayoutDirty = true; - } - var crossfade = node.options.crossfade; - if (crossfade === false) { - prevLead.hide(); - } - /** - * TODO: - * - Test border radius when previous node was deleted - * - boxShadow mixing - * - Shared between element A in scrolled container and element B (scroll stays the same or changes) - * - Shared between element A in transformed container and element B (transform stays the same or changes) - * - Shared between element A in scrolled page and element B (scroll stays the same or changes) - * --- - * - Crossfade opacity of root nodes - * - layoutId changes after animation - * - layoutId changes mid animation - */ - } - }; - NodeStack.prototype.exitAnimationComplete = function () { - this.members.forEach(function (node) { - var _a, _b, _c, _d, _e; - (_b = (_a = node.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a); - (_e = (_c = node.resumingFrom) === null || _c === void 0 ? void 0 : (_d = _c.options).onExitComplete) === null || _e === void 0 ? void 0 : _e.call(_d); - }); - }; - NodeStack.prototype.scheduleRender = function () { - this.members.forEach(function (node) { - node.instance && node.scheduleRender(false); - }); - }; - /** - * Clear any leads that have been removed this render to prevent them from being - * used in future animations and to prevent memory leaks - */ - NodeStack.prototype.removeLeadSnapshot = function () { - if (this.lead && this.lead.snapshot) { - this.lead.snapshot = undefined; - } - }; - return NodeStack; -}(); -var identityProjection = "translate3d(0px, 0px, 0) scale(1, 1) scale(1, 1)"; -function buildProjectionTransform(delta, treeScale, latestTransform) { - /** - * The translations we use to calculate are always relative to the viewport coordinate space. - * But when we apply scales, we also scale the coordinate space of an element and its children. - * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need - * to move an element 100 pixels, we actually need to move it 200 in within that scaled space. - */ - var xTranslate = delta.x.translate / treeScale.x; - var yTranslate = delta.y.translate / treeScale.y; - var transform = "translate3d(".concat(xTranslate, "px, ").concat(yTranslate, "px, 0) "); - /** - * Apply scale correction for the tree transform. - * This will apply scale to the screen-orientated axes. - */ - transform += "scale(".concat(1 / treeScale.x, ", ").concat(1 / treeScale.y, ") "); - if (latestTransform) { - var rotate = latestTransform.rotate, - rotateX = latestTransform.rotateX, - rotateY = latestTransform.rotateY; - if (rotate) transform += "rotate(".concat(rotate, "deg) "); - if (rotateX) transform += "rotateX(".concat(rotateX, "deg) "); - if (rotateY) transform += "rotateY(".concat(rotateY, "deg) "); - } - /** - * Apply scale to match the size of the element to the size we want it. - * This will apply scale to the element-orientated axes. - */ - var elementScaleX = delta.x.scale * treeScale.x; - var elementScaleY = delta.y.scale * treeScale.y; - transform += "scale(".concat(elementScaleX, ", ").concat(elementScaleY, ")"); - return transform === identityProjection ? "none" : transform; -} -var compareByDepth = function (a, b) { - return a.depth - b.depth; -}; -var FlatTree = /** @class */function () { - function FlatTree() { - this.children = []; - this.isDirty = false; - } - FlatTree.prototype.add = function (child) { - addUniqueItem(this.children, child); - this.isDirty = true; - }; - FlatTree.prototype.remove = function (child) { - removeItem(this.children, child); - this.isDirty = true; - }; - FlatTree.prototype.forEach = function (callback) { - this.isDirty && this.children.sort(compareByDepth); - this.isDirty = false; - this.children.forEach(callback); - }; - return FlatTree; -}(); - -/** - * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1 - * which has a noticeable difference in spring animations - */ -var animationTarget = 1000; -function createProjectionNode(_a) { - var attachResizeListener = _a.attachResizeListener, - defaultParent = _a.defaultParent, - measureScroll = _a.measureScroll, - checkIsScrollRoot = _a.checkIsScrollRoot, - resetTransform = _a.resetTransform; - return /** @class */function () { - function ProjectionNode(id, latestValues, parent) { - var _this = this; - if (latestValues === void 0) { - latestValues = {}; - } - if (parent === void 0) { - parent = defaultParent === null || defaultParent === void 0 ? void 0 : defaultParent(); - } - /** - * A Set containing all this component's children. This is used to iterate - * through the children. - * - * TODO: This could be faster to iterate as a flat array stored on the root node. - */ - this.children = new Set(); - /** - * Options for the node. We use this to configure what kind of layout animations - * we should perform (if any). - */ - this.options = {}; - /** - * We use this to detect when its safe to shut down part of a projection tree. - * We have to keep projecting children for scale correction and relative projection - * until all their parents stop performing layout animations. - */ - this.isTreeAnimating = false; - this.isAnimationBlocked = false; - /** - * Flag to true if we think this layout has been changed. We can't always know this, - * currently we set it to true every time a component renders, or if it has a layoutDependency - * if that has changed between renders. Additionally, components can be grouped by LayoutGroup - * and if one node is dirtied, they all are. - */ - this.isLayoutDirty = false; - /** - * Block layout updates for instant layout transitions throughout the tree. - */ - this.updateManuallyBlocked = false; - this.updateBlockedByResize = false; - /** - * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate` - * call. - */ - this.isUpdating = false; - /** - * If this is an SVG element we currently disable projection transforms - */ - this.isSVG = false; - /** - * Flag to true (during promotion) if a node doing an instant layout transition needs to reset - * its projection styles. - */ - this.needsReset = false; - /** - * Flags whether this node should have its transform reset prior to measuring. - */ - this.shouldResetTransform = false; - /** - * An object representing the calculated contextual/accumulated/tree scale. - * This will be used to scale calculcated projection transforms, as these are - * calculated in screen-space but need to be scaled for elements to actually - * make it to their calculated destinations. - * - * TODO: Lazy-init - */ - this.treeScale = { - x: 1, - y: 1 - }; - /** - * - */ - this.eventHandlers = new Map(); - // Note: Currently only running on root node - this.potentialNodes = new Map(); - this.checkUpdateFailed = function () { - if (_this.isUpdating) { - _this.isUpdating = false; - _this.clearAllSnapshots(); - } - }; - this.updateProjection = function () { - _this.nodes.forEach(resolveTargetDelta); - _this.nodes.forEach(calcProjection); - }; - this.hasProjected = false; - this.isVisible = true; - this.animationProgress = 0; - /** - * Shared layout - */ - // TODO Only running on root node - this.sharedNodes = new Map(); - this.id = id; - this.latestValues = latestValues; - this.root = parent ? parent.root || parent : this; - this.path = parent ? tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(parent.path), false), [parent], false) : []; - this.parent = parent; - this.depth = parent ? parent.depth + 1 : 0; - id && this.root.registerPotentialNode(id, this); - for (var i = 0; i < this.path.length; i++) { - this.path[i].shouldResetTransform = true; - } - if (this.root === this) this.nodes = new FlatTree(); - } - ProjectionNode.prototype.addEventListener = function (name, handler) { - if (!this.eventHandlers.has(name)) { - this.eventHandlers.set(name, new SubscriptionManager()); - } - return this.eventHandlers.get(name).add(handler); - }; - ProjectionNode.prototype.notifyListeners = function (name) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var subscriptionManager = this.eventHandlers.get(name); - subscriptionManager === null || subscriptionManager === void 0 ? void 0 : subscriptionManager.notify.apply(subscriptionManager, tslib.__spreadArray([], tslib.__read(args), false)); - }; - ProjectionNode.prototype.hasListeners = function (name) { - return this.eventHandlers.has(name); - }; - ProjectionNode.prototype.registerPotentialNode = function (id, node) { - this.potentialNodes.set(id, node); - }; - /** - * Lifecycles - */ - ProjectionNode.prototype.mount = function (instance, isLayoutDirty) { - var _this = this; - var _a; - if (isLayoutDirty === void 0) { - isLayoutDirty = false; - } - if (this.instance) return; - this.isSVG = instance instanceof SVGElement && instance.tagName !== "svg"; - this.instance = instance; - var _b = this.options, - layoutId = _b.layoutId, - layout = _b.layout, - visualElement = _b.visualElement; - if (visualElement && !visualElement.getInstance()) { - visualElement.mount(instance); - } - this.root.nodes.add(this); - (_a = this.parent) === null || _a === void 0 ? void 0 : _a.children.add(this); - this.id && this.root.potentialNodes.delete(this.id); - if (isLayoutDirty && (layout || layoutId)) { - this.isLayoutDirty = true; - } - if (attachResizeListener) { - var unblockTimeout_1; - var resizeUnblockUpdate_1 = function () { - return _this.root.updateBlockedByResize = false; - }; - attachResizeListener(instance, function () { - _this.root.updateBlockedByResize = true; - clearTimeout(unblockTimeout_1); - unblockTimeout_1 = window.setTimeout(resizeUnblockUpdate_1, 250); - if (globalProjectionState.hasAnimatedSinceResize) { - globalProjectionState.hasAnimatedSinceResize = false; - _this.nodes.forEach(finishAnimation); - } + Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function () { + return _index3.subscribe; + }, }); - } - if (layoutId) { - this.root.registerSharedNode(layoutId, this); - } - // Only register the handler if it requires layout animation - if (this.options.animate !== false && visualElement && (layoutId || layout)) { - this.addEventListener("didUpdate", function (_a) { - var _b, _c, _d, _e, _f; - var delta = _a.delta, - hasLayoutChanged = _a.hasLayoutChanged, - hasRelativeTargetChanged = _a.hasRelativeTargetChanged, - newLayout = _a.layout; - if (_this.isTreeAnimationBlocked()) { - _this.target = undefined; - _this.relativeTarget = undefined; - return; - } - // TODO: Check here if an animation exists - var layoutTransition = (_c = (_b = _this.options.transition) !== null && _b !== void 0 ? _b : visualElement.getDefaultTransition()) !== null && _c !== void 0 ? _c : defaultLayoutTransition; - var _g = visualElement.getProps(), - onLayoutAnimationStart = _g.onLayoutAnimationStart, - onLayoutAnimationComplete = _g.onLayoutAnimationComplete; - /** - * The target layout of the element might stay the same, - * but its position relative to its parent has changed. - */ - var targetChanged = !_this.targetLayout || !boxEquals(_this.targetLayout, newLayout) || hasRelativeTargetChanged; - /** - * If the layout hasn't seemed to have changed, it might be that the - * element is visually in the same place in the document but its position - * relative to its parent has indeed changed. So here we check for that. - */ - var hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeTargetChanged; - if (((_d = _this.resumeFrom) === null || _d === void 0 ? void 0 : _d.instance) || hasOnlyRelativeTargetChanged || hasLayoutChanged && (targetChanged || !_this.currentAnimation)) { - if (_this.resumeFrom) { - _this.resumingFrom = _this.resumeFrom; - _this.resumingFrom.resumingFrom = undefined; - } - _this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); - var animationOptions = tslib.__assign(tslib.__assign({}, getValueTransition(layoutTransition, "layout")), { - onPlay: onLayoutAnimationStart, - onComplete: onLayoutAnimationComplete - }); - if (visualElement.shouldReduceMotion) { - animationOptions.delay = 0; - animationOptions.type = false; - } - _this.startAnimation(animationOptions); - } else { - /** - * If the layout hasn't changed and we have an animation that hasn't started yet, - * finish it immediately. Otherwise it will be animating from a location - * that was probably never commited to screen and look like a jumpy box. - */ - if (!hasLayoutChanged && _this.animationProgress === 0) { - _this.finishAnimation(); - } - _this.isLead() && ((_f = (_e = _this.options).onExitComplete) === null || _f === void 0 ? void 0 : _f.call(_e)); - } - _this.targetLayout = newLayout; + Object.defineProperty(exports, "syntaxError", { + enumerable: true, + get: function () { + return _index5.syntaxError; + }, + }); + Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function () { + return _index6.typeFromAST; + }, + }); + Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _index4.validate; + }, + }); + Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function () { + return _index.validateSchema; + }, + }); + Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function () { + return _index6.valueFromAST; + }, + }); + Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function () { + return _index6.valueFromASTUntyped; + }, + }); + Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.version; + }, + }); + Object.defineProperty(exports, "versionInfo", { + enumerable: true, + get: function () { + return _version.versionInfo; + }, }); - } - }; - ProjectionNode.prototype.unmount = function () { - var _a, _b; - this.options.layoutId && this.willUpdate(); - this.root.nodes.remove(this); - (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.remove(this); - (_b = this.parent) === null || _b === void 0 ? void 0 : _b.children.delete(this); - this.instance = undefined; - sync.cancelSync.preRender(this.updateProjection); - }; - // only on the root - ProjectionNode.prototype.blockUpdate = function () { - this.updateManuallyBlocked = true; - }; - ProjectionNode.prototype.unblockUpdate = function () { - this.updateManuallyBlocked = false; - }; - ProjectionNode.prototype.isUpdateBlocked = function () { - return this.updateManuallyBlocked || this.updateBlockedByResize; - }; - ProjectionNode.prototype.isTreeAnimationBlocked = function () { - var _a; - return this.isAnimationBlocked || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimationBlocked()) || false; - }; - // Note: currently only running on root node - ProjectionNode.prototype.startUpdate = function () { - var _a; - if (this.isUpdateBlocked()) return; - this.isUpdating = true; - (_a = this.nodes) === null || _a === void 0 ? void 0 : _a.forEach(resetRotation); - }; - ProjectionNode.prototype.willUpdate = function (shouldNotifyListeners) { - var _a, _b, _c; - if (shouldNotifyListeners === void 0) { - shouldNotifyListeners = true; - } - if (this.root.isUpdateBlocked()) { - (_b = (_a = this.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a); - return; - } - !this.root.isUpdating && this.root.startUpdate(); - if (this.isLayoutDirty) return; - this.isLayoutDirty = true; - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - node.shouldResetTransform = true; - /** - * TODO: Check we haven't updated the scroll - * since the last didUpdate - */ - node.updateScroll(); - } - var _d = this.options, - layoutId = _d.layoutId, - layout = _d.layout; - if (layoutId === undefined && !layout) return; - var transformTemplate = (_c = this.options.visualElement) === null || _c === void 0 ? void 0 : _c.getProps().transformTemplate; - this.prevTransformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, ""); - this.updateSnapshot(); - shouldNotifyListeners && this.notifyListeners("willUpdate"); - }; - // Note: Currently only running on root node - ProjectionNode.prototype.didUpdate = function () { - var updateWasBlocked = this.isUpdateBlocked(); - // When doing an instant transition, we skip the layout update, - // but should still clean up the measurements so that the next - // snapshot could be taken correctly. - if (updateWasBlocked) { - this.unblockUpdate(); - this.clearAllSnapshots(); - this.nodes.forEach(clearMeasurements); - return; - } - if (!this.isUpdating) return; - this.isUpdating = false; - /** - * Search for and mount newly-added projection elements. - * - * TODO: Every time a new component is rendered we could search up the tree for - * the closest mounted node and query from there rather than document. - */ - if (this.potentialNodes.size) { - this.potentialNodes.forEach(mountNodeEarly); - this.potentialNodes.clear(); - } - /** - * Write - */ - this.nodes.forEach(resetTransformStyle); - /** - * Read ================== - */ - // Update layout measurements of updated children - this.nodes.forEach(updateLayout); - /** - * Write - */ - // Notify listeners that the layout is updated - this.nodes.forEach(notifyLayoutUpdate); - this.clearAllSnapshots(); - // Flush any scheduled updates - sync.flushSync.update(); - sync.flushSync.preRender(); - sync.flushSync.render(); - }; - ProjectionNode.prototype.clearAllSnapshots = function () { - this.nodes.forEach(clearSnapshot); - this.sharedNodes.forEach(removeLeadSnapshots); - }; - ProjectionNode.prototype.scheduleUpdateProjection = function () { - sync__default["default"].preRender(this.updateProjection, false, true); - }; - ProjectionNode.prototype.scheduleCheckAfterUnmount = function () { - var _this = this; - /** - * If the unmounting node is in a layoutGroup and did trigger a willUpdate, - * we manually call didUpdate to give a chance to the siblings to animate. - * Otherwise, cleanup all snapshots to prevents future nodes from reusing them. - */ - sync__default["default"].postRender(function () { - if (_this.isLayoutDirty) { - _this.root.didUpdate(); - } else { - _this.root.checkUpdateFailed(); - } - }); - }; - /** - * Update measurements - */ - ProjectionNode.prototype.updateSnapshot = function () { - if (this.snapshot || !this.instance) return; - var measured = this.measure(); - var layout = this.removeTransform(this.removeElementScroll(measured)); - roundBox(layout); - this.snapshot = { - measured: measured, - layout: layout, - latestValues: {} - }; - }; - ProjectionNode.prototype.updateLayout = function () { - var _a; - if (!this.instance) return; - // TODO: Incorporate into a forwarded scroll offset - this.updateScroll(); - if (!(this.options.alwaysMeasureLayout && this.isLead()) && !this.isLayoutDirty) { - return; - } - /** - * When a node is mounted, it simply resumes from the prevLead's - * snapshot instead of taking a new one, but the ancestors scroll - * might have updated while the prevLead is unmounted. We need to - * update the scroll again to make sure the layout we measure is - * up to date. - */ - if (this.resumeFrom && !this.resumeFrom.instance) { - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - node.updateScroll(); - } - } - var measured = this.measure(); - roundBox(measured); - var prevLayout = this.layout; - this.layout = { - measured: measured, - actual: this.removeElementScroll(measured) - }; - this.layoutCorrected = createBox(); - this.isLayoutDirty = false; - this.projectionDelta = undefined; - this.notifyListeners("measure", this.layout.actual); - (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.notifyLayoutMeasure(this.layout.actual, prevLayout === null || prevLayout === void 0 ? void 0 : prevLayout.actual); - }; - ProjectionNode.prototype.updateScroll = function () { - if (this.options.layoutScroll && this.instance) { - this.isScrollRoot = checkIsScrollRoot(this.instance); - this.scroll = measureScroll(this.instance); - } - }; - ProjectionNode.prototype.resetTransform = function () { - var _a; - if (!resetTransform) return; - var isResetRequested = this.isLayoutDirty || this.shouldResetTransform; - var hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); - var transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate; - var transformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, ""); - var transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; - if (isResetRequested && (hasProjection || hasTransform(this.latestValues) || transformTemplateHasChanged)) { - resetTransform(this.instance, transformTemplateValue); - this.shouldResetTransform = false; - this.scheduleRender(); - } - }; - ProjectionNode.prototype.measure = function () { - var visualElement = this.options.visualElement; - if (!visualElement) return createBox(); - var box = visualElement.measureViewportBox(); - // Remove viewport scroll to give page-relative coordinates - var scroll = this.root.scroll; - if (scroll) { - translateAxis(box.x, scroll.x); - translateAxis(box.y, scroll.y); - } - return box; - }; - ProjectionNode.prototype.removeElementScroll = function (box) { - var boxWithoutScroll = createBox(); - copyBoxInto(boxWithoutScroll, box); - /** - * Performance TODO: Keep a cumulative scroll offset down the tree - * rather than loop back up the path. - */ - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - var scroll_1 = node.scroll, - options = node.options, - isScrollRoot = node.isScrollRoot; - if (node !== this.root && scroll_1 && options.layoutScroll) { - /** - * If this is a new scroll root, we want to remove all previous scrolls - * from the viewport box. - */ - if (isScrollRoot) { - copyBoxInto(boxWithoutScroll, box); - var rootScroll = this.root.scroll; - /** - * Undo the application of page scroll that was originally added - * to the measured bounding box. - */ - if (rootScroll) { - translateAxis(boxWithoutScroll.x, -rootScroll.x); - translateAxis(boxWithoutScroll.y, -rootScroll.y); - } - } - translateAxis(boxWithoutScroll.x, scroll_1.x); - translateAxis(boxWithoutScroll.y, scroll_1.y); - } - } - return boxWithoutScroll; - }; - ProjectionNode.prototype.applyTransform = function (box, transformOnly) { - if (transformOnly === void 0) { - transformOnly = false; - } - var withTransforms = createBox(); - copyBoxInto(withTransforms, box); - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - if (!transformOnly && node.options.layoutScroll && node.scroll && node !== node.root) { - transformBox(withTransforms, { - x: -node.scroll.x, - y: -node.scroll.y - }); - } - if (!hasTransform(node.latestValues)) continue; - transformBox(withTransforms, node.latestValues); - } - if (hasTransform(this.latestValues)) { - transformBox(withTransforms, this.latestValues); - } - return withTransforms; - }; - ProjectionNode.prototype.removeTransform = function (box) { - var _a; - var boxWithoutTransform = createBox(); - copyBoxInto(boxWithoutTransform, box); - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - if (!node.instance) continue; - if (!hasTransform(node.latestValues)) continue; - hasScale(node.latestValues) && node.updateSnapshot(); - var sourceBox = createBox(); - var nodeBox = node.measure(); - copyBoxInto(sourceBox, nodeBox); - removeBoxTransforms(boxWithoutTransform, node.latestValues, (_a = node.snapshot) === null || _a === void 0 ? void 0 : _a.layout, sourceBox); - } - if (hasTransform(this.latestValues)) { - removeBoxTransforms(boxWithoutTransform, this.latestValues); - } - return boxWithoutTransform; - }; - /** - * - */ - ProjectionNode.prototype.setTargetDelta = function (delta) { - this.targetDelta = delta; - this.root.scheduleUpdateProjection(); - }; - ProjectionNode.prototype.setOptions = function (options) { - var _a; - this.options = tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), options), { - crossfade: (_a = options.crossfade) !== null && _a !== void 0 ? _a : true - }); - }; - ProjectionNode.prototype.clearMeasurements = function () { - this.scroll = undefined; - this.layout = undefined; - this.snapshot = undefined; - this.prevTransformTemplateValue = undefined; - this.targetDelta = undefined; - this.target = undefined; - this.isLayoutDirty = false; - }; - /** - * Frame calculations - */ - ProjectionNode.prototype.resolveTargetDelta = function () { - var _a; - var _b = this.options, - layout = _b.layout, - layoutId = _b.layoutId; - /** - * If we have no layout, we can't perform projection, so early return - */ - if (!this.layout || !(layout || layoutId)) return; - /** - * If we don't have a targetDelta but do have a layout, we can attempt to resolve - * a relativeParent. This will allow a component to perform scale correction - * even if no animation has started. - */ - // TODO If this is unsuccessful this currently happens every frame - if (!this.targetDelta && !this.relativeTarget) { - // TODO: This is a semi-repetition of further down this function, make DRY - this.relativeParent = this.getClosestProjectingParent(); - if (this.relativeParent && this.relativeParent.layout) { - this.relativeTarget = createBox(); - this.relativeTargetOrigin = createBox(); - calcRelativePosition(this.relativeTargetOrigin, this.layout.actual, this.relativeParent.layout.actual); - copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); - } - } - /** - * If we have no relative target or no target delta our target isn't valid - * for this frame. - */ - if (!this.relativeTarget && !this.targetDelta) return; - /** - * Lazy-init target data structure - */ - if (!this.target) { - this.target = createBox(); - this.targetWithTransforms = createBox(); - } - /** - * If we've got a relative box for this component, resolve it into a target relative to the parent. - */ - if (this.relativeTarget && this.relativeTargetOrigin && ((_a = this.relativeParent) === null || _a === void 0 ? void 0 : _a.target)) { - calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target); - /** - * If we've only got a targetDelta, resolve it into a target - */ - } else if (this.targetDelta) { - if (Boolean(this.resumingFrom)) { - // TODO: This is creating a new object every frame - this.target = this.applyTransform(this.layout.actual); - } else { - copyBoxInto(this.target, this.layout.actual); - } - applyBoxDelta(this.target, this.targetDelta); - } else { - /** - * If no target, use own layout as target - */ - copyBoxInto(this.target, this.layout.actual); - } - /** - * If we've been told to attempt to resolve a relative target, do so. - */ - if (this.attemptToResolveRelativeTarget) { - this.attemptToResolveRelativeTarget = false; - this.relativeParent = this.getClosestProjectingParent(); - if (this.relativeParent && Boolean(this.relativeParent.resumingFrom) === Boolean(this.resumingFrom) && !this.relativeParent.options.layoutScroll && this.relativeParent.target) { - this.relativeTarget = createBox(); - this.relativeTargetOrigin = createBox(); - calcRelativePosition(this.relativeTargetOrigin, this.target, this.relativeParent.target); - copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); - } - } - }; - ProjectionNode.prototype.getClosestProjectingParent = function () { - if (!this.parent || hasTransform(this.parent.latestValues)) return undefined; - if ((this.parent.relativeTarget || this.parent.targetDelta) && this.parent.layout) { - return this.parent; - } else { - return this.parent.getClosestProjectingParent(); - } - }; - ProjectionNode.prototype.calcProjection = function () { - var _a; - var _b = this.options, - layout = _b.layout, - layoutId = _b.layoutId; - /** - * If this section of the tree isn't animating we can - * delete our target sources for the following frame. - */ - this.isTreeAnimating = Boolean(((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimating) || this.currentAnimation || this.pendingAnimation); - if (!this.isTreeAnimating) { - this.targetDelta = this.relativeTarget = undefined; - } - if (!this.layout || !(layout || layoutId)) return; - var lead = this.getLead(); - /** - * Reset the corrected box with the latest values from box, as we're then going - * to perform mutative operations on it. - */ - copyBoxInto(this.layoutCorrected, this.layout.actual); - /** - * Apply all the parent deltas to this box to produce the corrected box. This - * is the layout box, as it will appear on screen as a result of the transforms of its parents. - */ - applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, Boolean(this.resumingFrom) || this !== lead); - var target = lead.target; - if (!target) return; - if (!this.projectionDelta) { - this.projectionDelta = createDelta(); - this.projectionDeltaWithTransform = createDelta(); - } - var prevTreeScaleX = this.treeScale.x; - var prevTreeScaleY = this.treeScale.y; - var prevProjectionTransform = this.projectionTransform; - /** - * Update the delta between the corrected box and the target box before user-set transforms were applied. - * This will allow us to calculate the corrected borderRadius and boxShadow to compensate - * for our layout reprojection, but still allow them to be scaled correctly by the user. - * It might be that to simplify this we may want to accept that user-set scale is also corrected - * and we wouldn't have to keep and calc both deltas, OR we could support a user setting - * to allow people to choose whether these styles are corrected based on just the - * layout reprojection or the final bounding box. - */ - calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); - this.projectionTransform = buildProjectionTransform(this.projectionDelta, this.treeScale); - if (this.projectionTransform !== prevProjectionTransform || this.treeScale.x !== prevTreeScaleX || this.treeScale.y !== prevTreeScaleY) { - this.hasProjected = true; - this.scheduleRender(); - this.notifyListeners("projectionUpdate", target); - } - }; - ProjectionNode.prototype.hide = function () { - this.isVisible = false; - // TODO: Schedule render - }; - ProjectionNode.prototype.show = function () { - this.isVisible = true; - // TODO: Schedule render - }; - ProjectionNode.prototype.scheduleRender = function (notifyAll) { - var _a, _b, _c; - if (notifyAll === void 0) { - notifyAll = true; - } - (_b = (_a = this.options).scheduleRender) === null || _b === void 0 ? void 0 : _b.call(_a); - notifyAll && ((_c = this.getStack()) === null || _c === void 0 ? void 0 : _c.scheduleRender()); - if (this.resumingFrom && !this.resumingFrom.instance) { - this.resumingFrom = undefined; - } - }; - ProjectionNode.prototype.setAnimationOrigin = function (delta, hasOnlyRelativeTargetChanged) { - var _this = this; - var _a; - if (hasOnlyRelativeTargetChanged === void 0) { - hasOnlyRelativeTargetChanged = false; - } - var snapshot = this.snapshot; - var snapshotLatestValues = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.latestValues) || {}; - var mixedValues = tslib.__assign({}, this.latestValues); - var targetDelta = createDelta(); - this.relativeTarget = this.relativeTargetOrigin = undefined; - this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; - var relativeLayout = createBox(); - var isSharedLayoutAnimation = snapshot === null || snapshot === void 0 ? void 0 : snapshot.isShared; - var isOnlyMember = (((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.members.length) || 0) <= 1; - var shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && !isOnlyMember && this.options.crossfade === true && !this.path.some(hasOpacityCrossfade)); - this.animationProgress = 0; - this.mixTargetDelta = function (latest) { - var _a; - var progress = latest / 1000; - mixAxisDelta(targetDelta.x, delta.x, progress); - mixAxisDelta(targetDelta.y, delta.y, progress); - _this.setTargetDelta(targetDelta); - if (_this.relativeTarget && _this.relativeTargetOrigin && _this.layout && ((_a = _this.relativeParent) === null || _a === void 0 ? void 0 : _a.layout)) { - calcRelativePosition(relativeLayout, _this.layout.actual, _this.relativeParent.layout.actual); - mixBox(_this.relativeTarget, _this.relativeTargetOrigin, relativeLayout, progress); - } - if (isSharedLayoutAnimation) { - _this.animationValues = mixedValues; - mixValues(mixedValues, snapshotLatestValues, _this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember); - } - _this.root.scheduleUpdateProjection(); - _this.scheduleRender(); - _this.animationProgress = progress; - }; - this.mixTargetDelta(0); - }; - ProjectionNode.prototype.startAnimation = function (options) { - var _this = this; - var _a, _b; - this.notifyListeners("animationStart"); - (_a = this.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); - if (this.resumingFrom) { - (_b = this.resumingFrom.currentAnimation) === null || _b === void 0 ? void 0 : _b.stop(); - } - if (this.pendingAnimation) { - sync.cancelSync.update(this.pendingAnimation); - this.pendingAnimation = undefined; - } - /** - * Start the animation in the next frame to have a frame with progress 0, - * where the target is the same as when the animation started, so we can - * calculate the relative positions correctly for instant transitions. - */ - this.pendingAnimation = sync__default["default"].update(function () { - globalProjectionState.hasAnimatedSinceResize = true; - _this.currentAnimation = animate(0, animationTarget, tslib.__assign(tslib.__assign({}, options), { - onUpdate: function (latest) { - var _a; - _this.mixTargetDelta(latest); - (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, latest); + Object.defineProperty(exports, "visit", { + enumerable: true, + get: function () { + return _index2.visit; }, - onComplete: function () { - var _a; - (_a = options.onComplete) === null || _a === void 0 ? void 0 : _a.call(options); - _this.completeAnimation(); - } - })); - if (_this.resumingFrom) { - _this.resumingFrom.currentAnimation = _this.currentAnimation; - } - _this.pendingAnimation = undefined; - }); - }; - ProjectionNode.prototype.completeAnimation = function () { - var _a; - if (this.resumingFrom) { - this.resumingFrom.currentAnimation = undefined; - this.resumingFrom.preserveOpacity = undefined; - } - (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.exitAnimationComplete(); - this.resumingFrom = this.currentAnimation = this.animationValues = undefined; - this.notifyListeners("animationComplete"); - }; - ProjectionNode.prototype.finishAnimation = function () { - var _a; - if (this.currentAnimation) { - (_a = this.mixTargetDelta) === null || _a === void 0 ? void 0 : _a.call(this, animationTarget); - this.currentAnimation.stop(); - } - this.completeAnimation(); - }; - ProjectionNode.prototype.applyTransformsToTarget = function () { - var _a = this.getLead(), - targetWithTransforms = _a.targetWithTransforms, - target = _a.target, - layout = _a.layout, - latestValues = _a.latestValues; - if (!targetWithTransforms || !target || !layout) return; - copyBoxInto(targetWithTransforms, target); - /** - * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal. - * This is the final box that we will then project into by calculating a transform delta and - * applying it to the corrected box. - */ - transformBox(targetWithTransforms, latestValues); - /** - * Update the delta between the corrected box and the final target box, after - * user-set transforms are applied to it. This will be used by the renderer to - * create a transform style that will reproject the element from its actual layout - * into the desired bounding box. - */ - calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); - }; - ProjectionNode.prototype.registerSharedNode = function (layoutId, node) { - var _a, _b, _c; - if (!this.sharedNodes.has(layoutId)) { - this.sharedNodes.set(layoutId, new NodeStack()); - } - var stack = this.sharedNodes.get(layoutId); - stack.add(node); - node.promote({ - transition: (_a = node.options.initialPromotionConfig) === null || _a === void 0 ? void 0 : _a.transition, - preserveFollowOpacity: (_c = (_b = node.options.initialPromotionConfig) === null || _b === void 0 ? void 0 : _b.shouldPreserveFollowOpacity) === null || _c === void 0 ? void 0 : _c.call(_b, node) - }); - }; - ProjectionNode.prototype.isLead = function () { - var stack = this.getStack(); - return stack ? stack.lead === this : true; - }; - ProjectionNode.prototype.getLead = function () { - var _a; - var layoutId = this.options.layoutId; - return layoutId ? ((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.lead) || this : this; - }; - ProjectionNode.prototype.getPrevLead = function () { - var _a; - var layoutId = this.options.layoutId; - return layoutId ? (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.prevLead : undefined; - }; - ProjectionNode.prototype.getStack = function () { - var layoutId = this.options.layoutId; - if (layoutId) return this.root.sharedNodes.get(layoutId); - }; - ProjectionNode.prototype.promote = function (_a) { - var _b = _a === void 0 ? {} : _a, - needsReset = _b.needsReset, - transition = _b.transition, - preserveFollowOpacity = _b.preserveFollowOpacity; - var stack = this.getStack(); - if (stack) stack.promote(this, preserveFollowOpacity); - if (needsReset) { - this.projectionDelta = undefined; - this.needsReset = true; - } - if (transition) this.setOptions({ - transition: transition - }); - }; - ProjectionNode.prototype.relegate = function () { - var stack = this.getStack(); - if (stack) { - return stack.relegate(this); - } else { - return false; - } - }; - ProjectionNode.prototype.resetRotation = function () { - var visualElement = this.options.visualElement; - if (!visualElement) return; - // If there's no detected rotation values, we can early return without a forced render. - var hasRotate = false; - // Keep a record of all the values we've reset - var resetValues = {}; - // Check the rotate value of all axes and reset to 0 - for (var i = 0; i < transformAxes.length; i++) { - var axis = transformAxes[i]; - var key = "rotate" + axis; - // If this rotation doesn't exist as a motion value, then we don't - // need to reset it - if (!visualElement.getStaticValue(key)) { - continue; - } - hasRotate = true; - // Record the rotation and then temporarily set it to 0 - resetValues[key] = visualElement.getStaticValue(key); - visualElement.setStaticValue(key, 0); - } - // If there's no rotation values, we don't need to do any more. - if (!hasRotate) return; - // Force a render of this element to apply the transform with all rotations - // set to 0. - visualElement === null || visualElement === void 0 ? void 0 : visualElement.syncRender(); - // Put back all the values we reset - for (var key in resetValues) { - visualElement.setStaticValue(key, resetValues[key]); - } - // Schedule a render for the next frame. This ensures we won't visually - // see the element with the reset rotate value applied. - visualElement.scheduleRender(); - }; - ProjectionNode.prototype.getProjectionStyles = function (styleProp) { - var _a, _b, _c, _d, _e, _f; - if (styleProp === void 0) { - styleProp = {}; - } - // TODO: Return lifecycle-persistent object - var styles = {}; - if (!this.instance || this.isSVG) return styles; - if (!this.isVisible) { - return { - visibility: "hidden" - }; - } else { - styles.visibility = ""; - } - var transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate; - if (this.needsReset) { - this.needsReset = false; - styles.opacity = ""; - styles.pointerEvents = resolveMotionValue(styleProp.pointerEvents) || ""; - styles.transform = transformTemplate ? transformTemplate(this.latestValues, "") : "none"; - return styles; - } - var lead = this.getLead(); - if (!this.projectionDelta || !this.layout || !lead.target) { - var emptyStyles = {}; - if (this.options.layoutId) { - emptyStyles.opacity = (_b = this.latestValues.opacity) !== null && _b !== void 0 ? _b : 1; - emptyStyles.pointerEvents = resolveMotionValue(styleProp.pointerEvents) || ""; - } - if (this.hasProjected && !hasTransform(this.latestValues)) { - emptyStyles.transform = transformTemplate ? transformTemplate({}, "") : "none"; - this.hasProjected = false; - } - return emptyStyles; - } - var valuesToRender = lead.animationValues || lead.latestValues; - this.applyTransformsToTarget(); - styles.transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); - if (transformTemplate) { - styles.transform = transformTemplate(valuesToRender, styles.transform); - } - var _g = this.projectionDelta, - x = _g.x, - y = _g.y; - styles.transformOrigin = "".concat(x.origin * 100, "% ").concat(y.origin * 100, "% 0"); - if (lead.animationValues) { + }); + Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function () { + return _index2.visitInParallel; + }, + }); + Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function () { + return _index6.visitWithTypeInfo; + }, + }); + var _version = __webpack_require__( + /*! ./version.mjs */ "../../../node_modules/graphql/version.mjs" + ); + var _graphql = __webpack_require__( + /*! ./graphql.mjs */ "../../../node_modules/graphql/graphql.mjs" + ); + var _index = __webpack_require__( + /*! ./type/index.mjs */ "../../../node_modules/graphql/type/index.mjs" + ); + var _index2 = __webpack_require__( + /*! ./language/index.mjs */ "../../../node_modules/graphql/language/index.mjs" + ); + var _index3 = __webpack_require__( + /*! ./execution/index.mjs */ "../../../node_modules/graphql/execution/index.mjs" + ); + var _index4 = __webpack_require__( + /*! ./validation/index.mjs */ "../../../node_modules/graphql/validation/index.mjs" + ); + var _index5 = __webpack_require__( + /*! ./error/index.mjs */ "../../../node_modules/graphql/error/index.mjs" + ); + var _index6 = __webpack_require__( + /*! ./utilities/index.mjs */ "../../../node_modules/graphql/utilities/index.mjs" + ); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/Path.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/Path.mjs ***! + \******************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.addPath = addPath; + exports.pathToArray = pathToArray; /** - * If the lead component is animating, assign this either the entering/leaving - * opacity + * Given a Path and a key, return a new Path containing the new key. */ - styles.opacity = lead === this ? (_d = (_c = valuesToRender.opacity) !== null && _c !== void 0 ? _c : this.latestValues.opacity) !== null && _d !== void 0 ? _d : 1 : this.preserveOpacity ? this.latestValues.opacity : valuesToRender.opacityExit; - } else { + function addPath(prev, key, typename) { + return { + prev, + key, + typename, + }; + } /** - * Or we're not animating at all, set the lead component to its actual - * opacity and other components to hidden. + * Given a Path, return an Array of the path keys. */ - styles.opacity = lead === this ? (_e = valuesToRender.opacity) !== null && _e !== void 0 ? _e : "" : (_f = valuesToRender.opacityExit) !== null && _f !== void 0 ? _f : 0; - } - /** - * Apply scale correction - */ - for (var key in scaleCorrectors) { - if (valuesToRender[key] === undefined) continue; - var _h = scaleCorrectors[key], - correct = _h.correct, - applyTo = _h.applyTo; - var corrected = correct(valuesToRender[key], lead); - if (applyTo) { - var num = applyTo.length; - for (var i = 0; i < num; i++) { - styles[applyTo[i]] = corrected; - } - } else { - styles[key] = corrected; - } - } - /** - * Disable pointer events on follow components. This is to ensure - * that if a follow component covers a lead component it doesn't block - * pointer events on the lead. - */ - if (this.options.layoutId) { - styles.pointerEvents = lead === this ? resolveMotionValue(styleProp.pointerEvents) || "" : "none"; - } - return styles; - }; - ProjectionNode.prototype.clearSnapshot = function () { - this.resumeFrom = this.snapshot = undefined; - }; - // Only run on root - ProjectionNode.prototype.resetTree = function () { - this.root.nodes.forEach(function (node) { - var _a; - return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); - }); - this.root.nodes.forEach(clearMeasurements); - this.root.sharedNodes.clear(); - }; - return ProjectionNode; - }(); -} -function updateLayout(node) { - node.updateLayout(); -} -function notifyLayoutUpdate(node) { - var _a, _b, _c, _d; - var snapshot = (_b = (_a = node.resumeFrom) === null || _a === void 0 ? void 0 : _a.snapshot) !== null && _b !== void 0 ? _b : node.snapshot; - if (node.isLead() && node.layout && snapshot && node.hasListeners("didUpdate")) { - var _e = node.layout, - layout_1 = _e.actual, - measuredLayout = _e.measured; - // TODO Maybe we want to also resize the layout snapshot so we don't trigger - // animations for instance if layout="size" and an element has only changed position - if (node.options.animationType === "size") { - eachAxis(function (axis) { - var axisSnapshot = snapshot.isShared ? snapshot.measured[axis] : snapshot.layout[axis]; - var length = calcLength(axisSnapshot); - axisSnapshot.min = layout_1[axis].min; - axisSnapshot.max = axisSnapshot.min + length; - }); - } else if (node.options.animationType === "position") { - eachAxis(function (axis) { - var axisSnapshot = snapshot.isShared ? snapshot.measured[axis] : snapshot.layout[axis]; - var length = calcLength(layout_1[axis]); - axisSnapshot.max = axisSnapshot.min + length; - }); - } - var layoutDelta = createDelta(); - calcBoxDelta(layoutDelta, layout_1, snapshot.layout); - var visualDelta = createDelta(); - if (snapshot.isShared) { - calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measured); - } else { - calcBoxDelta(visualDelta, layout_1, snapshot.layout); - } - var hasLayoutChanged = !isDeltaZero(layoutDelta); - var hasRelativeTargetChanged = false; - if (!node.resumeFrom) { - node.relativeParent = node.getClosestProjectingParent(); - /** - * If the relativeParent is itself resuming from a different element then - * the relative snapshot is not relavent - */ - if (node.relativeParent && !node.relativeParent.resumeFrom) { - var _f = node.relativeParent, - parentSnapshot = _f.snapshot, - parentLayout = _f.layout; - if (parentSnapshot && parentLayout) { - var relativeSnapshot = createBox(); - calcRelativePosition(relativeSnapshot, snapshot.layout, parentSnapshot.layout); - var relativeLayout = createBox(); - calcRelativePosition(relativeLayout, layout_1, parentLayout.actual); - if (!boxEquals(relativeSnapshot, relativeLayout)) { - hasRelativeTargetChanged = true; + + function pathToArray(path) { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; } + return flattened.reverse(); } - } - } - node.notifyListeners("didUpdate", { - layout: layout_1, - snapshot: snapshot, - delta: visualDelta, - layoutDelta: layoutDelta, - hasLayoutChanged: hasLayoutChanged, - hasRelativeTargetChanged: hasRelativeTargetChanged - }); - } else if (node.isLead()) { - (_d = (_c = node.options).onExitComplete) === null || _d === void 0 ? void 0 : _d.call(_c); - } - /** - * Clearing transition - * TODO: Investigate why this transition is being passed in as {type: false } from Framer - * and why we need it at all - */ - node.options.transition = undefined; -} -function clearSnapshot(node) { - node.clearSnapshot(); -} -function clearMeasurements(node) { - node.clearMeasurements(); -} -function resetTransformStyle(node) { - var visualElement = node.options.visualElement; - if (visualElement === null || visualElement === void 0 ? void 0 : visualElement.getProps().onBeforeLayoutMeasure) { - visualElement.notifyBeforeLayoutMeasure(); - } - node.resetTransform(); -} -function finishAnimation(node) { - node.finishAnimation(); - node.targetDelta = node.relativeTarget = node.target = undefined; -} -function resolveTargetDelta(node) { - node.resolveTargetDelta(); -} -function calcProjection(node) { - node.calcProjection(); -} -function resetRotation(node) { - node.resetRotation(); -} -function removeLeadSnapshots(stack) { - stack.removeLeadSnapshot(); -} -function mixAxisDelta(output, delta, p) { - output.translate = popmotion.mix(delta.translate, 0, p); - output.scale = popmotion.mix(delta.scale, 1, p); - output.origin = delta.origin; - output.originPoint = delta.originPoint; -} -function mixAxis(output, from, to, p) { - output.min = popmotion.mix(from.min, to.min, p); - output.max = popmotion.mix(from.max, to.max, p); -} -function mixBox(output, from, to, p) { - mixAxis(output.x, from.x, to.x, p); - mixAxis(output.y, from.y, to.y, p); -} -function hasOpacityCrossfade(node) { - return node.animationValues && node.animationValues.opacityExit !== undefined; -} -var defaultLayoutTransition = { - duration: 0.45, - ease: [0.4, 0, 0.1, 1] -}; -function mountNodeEarly(node, id) { - /** - * Rather than searching the DOM from document we can search the - * path for the deepest mounted ancestor and search from there - */ - var searchNode = node.root; - for (var i = node.path.length - 1; i >= 0; i--) { - if (Boolean(node.path[i].instance)) { - searchNode = node.path[i]; - break; - } - } - var searchElement = searchNode && searchNode !== node.root ? searchNode.instance : document; - var element = searchElement.querySelector("[data-projection-id=\"".concat(id, "\"]")); - if (element) node.mount(element, true); -} -function roundAxis(axis) { - axis.min = Math.round(axis.min); - axis.max = Math.round(axis.max); -} -function roundBox(box) { - roundAxis(box.x); - roundAxis(box.y); -} -var DocumentProjectionNode = createProjectionNode({ - attachResizeListener: function (ref, notify) { - return addDomEvent(ref, "resize", notify); - }, - measureScroll: function () { - return { - x: document.documentElement.scrollLeft || document.body.scrollLeft, - y: document.documentElement.scrollTop || document.body.scrollTop - }; - }, - checkIsScrollRoot: function () { - return true; - } -}); -var rootProjectionNode = { - current: undefined -}; -var HTMLProjectionNode = createProjectionNode({ - measureScroll: function (instance) { - return { - x: instance.scrollLeft, - y: instance.scrollTop - }; - }, - defaultParent: function () { - if (!rootProjectionNode.current) { - var documentNode = new DocumentProjectionNode(0, {}); - documentNode.mount(window); - documentNode.setOptions({ - layoutScroll: true - }); - rootProjectionNode.current = documentNode; - } - return rootProjectionNode.current; - }, - resetTransform: function (instance, value) { - instance.style.transform = value !== null && value !== void 0 ? value : "none"; - }, - checkIsScrollRoot: function (instance) { - return Boolean(window.getComputedStyle(instance).position === "fixed"); - } -}); -var featureBundle = tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, animations), gestureAnimations), drag), layoutFeatures); -/** - * HTML & SVG components, optimised for use with gestures and animation. These can be used as - * drop-in replacements for any HTML & SVG component, all CSS & SVG properties are supported. - * - * @public - */ -var motion = /*@__PURE__*/createMotionProxy(function (Component, config) { - return createDomMotionConfig(Component, config, featureBundle, createDomVisualElement, HTMLProjectionNode); -}); -/** - * Create a DOM `motion` component with the provided string. This is primarily intended - * as a full alternative to `motion` for consumers who have to support environments that don't - * support `Proxy`. - * - * ```javascript - * import { createDomMotionComponent } from "framer-motion" - * - * const motion = { - * div: createDomMotionComponent('div') - * } - * ``` - * - * @public - */ -function createDomMotionComponent(key) { - return createMotionComponent(createDomMotionConfig(key, { - forwardMotionProps: false - }, featureBundle, createDomVisualElement, HTMLProjectionNode)); -} - -/** - * @public - */ -var m = createMotionProxy(createDomMotionConfig); -function useIsMounted() { - var isMounted = React.useRef(false); - useIsomorphicLayoutEffect(function () { - isMounted.current = true; - return function () { - isMounted.current = false; - }; - }, []); - return isMounted; -} -function useForceUpdate() { - var isMounted = useIsMounted(); - var _a = tslib.__read(React.useState(0), 2), - forcedRenderCount = _a[0], - setForcedRenderCount = _a[1]; - var forceRender = React.useCallback(function () { - isMounted.current && setForcedRenderCount(forcedRenderCount + 1); - }, [forcedRenderCount]); - /** - * Defer this to the end of the next animation frame in case there are multiple - * synchronous calls. - */ - var deferredForceRender = React.useCallback(function () { - return sync__default["default"].postRender(forceRender); - }, [forceRender]); - return [deferredForceRender, forcedRenderCount]; -} -var PresenceChild = function (_a) { - var children = _a.children, - initial = _a.initial, - isPresent = _a.isPresent, - onExitComplete = _a.onExitComplete, - custom = _a.custom, - presenceAffectsLayout = _a.presenceAffectsLayout; - var presenceChildren = useConstant(newChildrenMap); - var id = useId(); - var context = React.useMemo(function () { - return { - id: id, - initial: initial, - isPresent: isPresent, - custom: custom, - onExitComplete: function (childId) { - var e_1, _a; - presenceChildren.set(childId, true); - try { - for (var _b = tslib.__values(presenceChildren.values()), _c = _b.next(); !_c.done; _c = _b.next()) { - var isComplete = _c.value; - if (!isComplete) return; // can stop searching when any is incomplete - } - } catch (e_1_1) { - e_1 = { - error: e_1_1 - }; - } finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } finally { - if (e_1) throw e_1.error; + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/devAssert.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/devAssert.mjs ***! + \***********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.devAssert = devAssert; + function devAssert(condition, message) { + const booleanCondition = Boolean(condition); + if (!booleanCondition) { + throw new Error(message); } } - onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete(); - }, - register: function (childId) { - presenceChildren.set(childId, false); - return function () { - return presenceChildren.delete(childId); - }; - } - }; - }, - /** - * If the presence of a child affects the layout of the components around it, - * we want to make a new context value to ensure they get re-rendered - * so they can detect that layout change. - */ - presenceAffectsLayout ? undefined : [isPresent]); - React.useMemo(function () { - presenceChildren.forEach(function (_, key) { - return presenceChildren.set(key, false); - }); - }, [isPresent]); - /** - * If there's no `motion` components to fire exit animations, we want to remove this - * component immediately. - */ - React__namespace.useEffect(function () { - !isPresent && !presenceChildren.size && (onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete()); - }, [isPresent]); - return React__namespace.createElement(PresenceContext.Provider, { - value: context - }, children); -}; -function newChildrenMap() { - return new Map(); -} -var getChildKey = function (child) { - return child.key || ""; -}; -function updateChildLookup(children, allChildren) { - children.forEach(function (child) { - var key = getChildKey(child); - allChildren.set(key, child); - }); -} -function onlyElements(children) { - var filtered = []; - // We use forEach here instead of map as map mutates the component key by preprending `.$` - React.Children.forEach(children, function (child) { - if (React.isValidElement(child)) filtered.push(child); - }); - return filtered; -} -/** - * `AnimatePresence` enables the animation of components that have been removed from the tree. - * - * When adding/removing more than a single child, every child **must** be given a unique `key` prop. - * - * Any `motion` components that have an `exit` property defined will animate out when removed from - * the tree. - * - * ```jsx - * import { motion, AnimatePresence } from 'framer-motion' - * - * export const Items = ({ items }) => ( - * - * {items.map(item => ( - * - * ))} - * - * ) - * ``` - * - * You can sequence exit animations throughout a tree using variants. - * - * If a child contains multiple `motion` components with `exit` props, it will only unmount the child - * once all `motion` components have finished animating out. Likewise, any components using - * `usePresence` all need to call `safeToRemove`. - * - * @public - */ -var AnimatePresence = function (_a) { - var children = _a.children, - custom = _a.custom, - _b = _a.initial, - initial = _b === void 0 ? true : _b, - onExitComplete = _a.onExitComplete, - exitBeforeEnter = _a.exitBeforeEnter, - _c = _a.presenceAffectsLayout, - presenceAffectsLayout = _c === void 0 ? true : _c; - // We want to force a re-render once all exiting animations have finished. We - // either use a local forceRender function, or one from a parent context if it exists. - var _d = tslib.__read(useForceUpdate(), 1), - forceRender = _d[0]; - var forceRenderLayoutGroup = React.useContext(LayoutGroupContext).forceRender; - if (forceRenderLayoutGroup) forceRender = forceRenderLayoutGroup; - var isMounted = useIsMounted(); - // Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key - var filteredChildren = onlyElements(children); - var childrenToRender = filteredChildren; - var exiting = new Set(); - // Keep a living record of the children we're actually rendering so we - // can diff to figure out which are entering and exiting - var presentChildren = React.useRef(childrenToRender); - // A lookup table to quickly reference components by key - var allChildren = React.useRef(new Map()).current; - // If this is the initial component render, just deal with logic surrounding whether - // we play onMount animations or not. - var isInitialRender = React.useRef(true); - useIsomorphicLayoutEffect(function () { - isInitialRender.current = false; - updateChildLookup(filteredChildren, allChildren); - presentChildren.current = childrenToRender; - }); - useUnmountEffect(function () { - isInitialRender.current = true; - allChildren.clear(); - exiting.clear(); - }); - if (isInitialRender.current) { - return React__namespace.createElement(React__namespace.Fragment, null, childrenToRender.map(function (child) { - return React__namespace.createElement(PresenceChild, { - key: getChildKey(child), - isPresent: true, - initial: initial ? undefined : false, - presenceAffectsLayout: presenceAffectsLayout - }, child); - })); - } - // If this is a subsequent render, deal with entering and exiting children - childrenToRender = tslib.__spreadArray([], tslib.__read(childrenToRender), false); - // Diff the keys of the currently-present and target children to update our - // exiting list. - var presentKeys = presentChildren.current.map(getChildKey); - var targetKeys = filteredChildren.map(getChildKey); - // Diff the present children with our target children and mark those that are exiting - var numPresent = presentKeys.length; - for (var i = 0; i < numPresent; i++) { - var key = presentKeys[i]; - if (targetKeys.indexOf(key) === -1) { - exiting.add(key); - } - } - // If we currently have exiting children, and we're deferring rendering incoming children - // until after all current children have exiting, empty the childrenToRender array - if (exitBeforeEnter && exiting.size) { - childrenToRender = []; - } - // Loop through all currently exiting components and clone them to overwrite `animate` - // with any `exit` prop they might have defined. - exiting.forEach(function (key) { - // If this component is actually entering again, early return - if (targetKeys.indexOf(key) !== -1) return; - var child = allChildren.get(key); - if (!child) return; - var insertionIndex = presentKeys.indexOf(key); - var onExit = function () { - allChildren.delete(key); - exiting.delete(key); - // Remove this child from the present children - var removeIndex = presentChildren.current.findIndex(function (presentChild) { - return presentChild.key === key; - }); - presentChildren.current.splice(removeIndex, 1); - // Defer re-rendering until all exiting children have indeed left - if (!exiting.size) { - presentChildren.current = filteredChildren; - if (isMounted.current === false) return; - forceRender(); - onExitComplete && onExitComplete(); - } - }; - childrenToRender.splice(insertionIndex, 0, React__namespace.createElement(PresenceChild, { - key: getChildKey(child), - isPresent: false, - onExitComplete: onExit, - custom: custom, - presenceAffectsLayout: presenceAffectsLayout - }, child)); - }); - // Add `MotionContext` even to children that don't need it to ensure we're rendering - // the same tree between renders - childrenToRender = childrenToRender.map(function (child) { - var key = child.key; - return exiting.has(key) ? child : React__namespace.createElement(PresenceChild, { - key: getChildKey(child), - isPresent: true, - presenceAffectsLayout: presenceAffectsLayout - }, child); - }); - if (env !== "production" && exitBeforeEnter && childrenToRender.length > 1) { - console.warn("You're attempting to animate multiple children within AnimatePresence, but its exitBeforeEnter prop is set to true. This will lead to odd visual behaviour."); - } - return React__namespace.createElement(React__namespace.Fragment, null, exiting.size ? childrenToRender : childrenToRender.map(function (child) { - return React.cloneElement(child); - })); -}; -/** - * @deprecated - */ -var DeprecatedLayoutGroupContext = React.createContext(null); -var notify = function (node) { - return !node.isLayoutDirty && node.willUpdate(false); -}; -function nodeGroup() { - var nodes = new Set(); - var subscriptions = new WeakMap(); - var dirtyAll = function () { - return nodes.forEach(notify); - }; - return { - add: function (node) { - nodes.add(node); - subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll)); - }, - remove: function (node) { - var _a; - nodes.delete(node); - (_a = subscriptions.get(node)) === null || _a === void 0 ? void 0 : _a(); - subscriptions.delete(node); - dirtyAll(); - }, - dirty: dirtyAll - }; -} -var shouldInheritGroup = function (inherit) { - return inherit === true; -}; -var shouldInheritId = function (inherit) { - return shouldInheritGroup(inherit === true) || inherit === "id"; -}; -var LayoutGroup = function (_a) { - var _b, _c; - var children = _a.children, - id = _a.id, - inheritId = _a.inheritId, - _d = _a.inherit, - inherit = _d === void 0 ? true : _d; - // Maintain backwards-compatibility with inheritId until 7.0 - if (inheritId !== undefined) inherit = inheritId; - var layoutGroupContext = React.useContext(LayoutGroupContext); - var deprecatedLayoutGroupContext = React.useContext(DeprecatedLayoutGroupContext); - var _e = tslib.__read(useForceUpdate(), 2), - forceRender = _e[0], - key = _e[1]; - var context = React.useRef(null); - var upstreamId = (_b = layoutGroupContext.id) !== null && _b !== void 0 ? _b : deprecatedLayoutGroupContext; - if (context.current === null) { - if (shouldInheritId(inherit) && upstreamId) { - id = id ? upstreamId + "-" + id : upstreamId; - } - context.current = { - id: id, - group: shouldInheritGroup(inherit) ? (_c = layoutGroupContext === null || layoutGroupContext === void 0 ? void 0 : layoutGroupContext.group) !== null && _c !== void 0 ? _c : nodeGroup() : nodeGroup() - }; - } - var memoizedContext = React.useMemo(function () { - return tslib.__assign(tslib.__assign({}, context.current), { - forceRender: forceRender - }); - }, [key]); - return React__namespace.createElement(LayoutGroupContext.Provider, { - value: memoizedContext - }, children); -}; -var id = 0; -var AnimateSharedLayout = function (_a) { - var children = _a.children; - React__namespace.useEffect(function () { - heyListen.warning(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations"); - }, []); - return React__namespace.createElement(LayoutGroup, { - id: useConstant(function () { - return "asl-".concat(id++); - }) - }, children); -}; + /***/ + }, -/** - * `MotionConfig` is used to set configuration options for all children `motion` components. - * - * ```jsx - * import { motion, MotionConfig } from "framer-motion" - * - * export function App() { - * return ( - * - * - * - * ) - * } - * ``` - * - * @public - */ -function MotionConfig(_a) { - var children = _a.children, - isValidProp = _a.isValidProp, - config = tslib.__rest(_a, ["children", "isValidProp"]); - isValidProp && loadExternalIsValidProp(isValidProp); - /** - * Inherit props from any parent MotionConfig components - */ - config = tslib.__assign(tslib.__assign({}, React.useContext(MotionConfigContext)), config); - /** - * Don't allow isStatic to change between renders as it affects how many hooks - * motion components fire. - */ - config.isStatic = useConstant(function () { - return config.isStatic; - }); - /** - * Creating a new config context object will re-render every `motion` component - * every time it renders. So we only want to create a new one sparingly. - */ - var context = React.useMemo(function () { - return config; - }, [JSON.stringify(config.transition), config.transformPagePoint, config.reducedMotion]); - return React__namespace.createElement(MotionConfigContext.Provider, { - value: context - }, children); -} - -/** - * Used in conjunction with the `m` component to reduce bundle size. - * - * `m` is a version of the `motion` component that only loads functionality - * critical for the initial render. - * - * `LazyMotion` can then be used to either synchronously or asynchronously - * load animation and gesture support. - * - * ```jsx - * // Synchronous loading - * import { LazyMotion, m, domAnimations } from "framer-motion" - * - * function App() { - * return ( - * - * - * - * ) - * } - * - * // Asynchronous loading - * import { LazyMotion, m } from "framer-motion" - * - * function App() { - * return ( - * import('./path/to/domAnimations')}> - * - * - * ) - * } - * ``` - * - * @public - */ -function LazyMotion(_a) { - var children = _a.children, - features = _a.features, - _b = _a.strict, - strict = _b === void 0 ? false : _b; - var _c = tslib.__read(React.useState(!isLazyBundle(features)), 2), - setIsLoaded = _c[1]; - var loadedRenderer = React.useRef(undefined); - /** - * If this is a synchronous load, load features immediately - */ - if (!isLazyBundle(features)) { - var renderer = features.renderer, - loadedFeatures = tslib.__rest(features, ["renderer"]); - loadedRenderer.current = renderer; - loadFeatures(loadedFeatures); - } - React.useEffect(function () { - if (isLazyBundle(features)) { - features().then(function (_a) { - var renderer = _a.renderer, - loadedFeatures = tslib.__rest(_a, ["renderer"]); - loadFeatures(loadedFeatures); - loadedRenderer.current = renderer; - setIsLoaded(true); - }); - } - }, []); - return React__namespace.createElement(LazyContext.Provider, { - value: { - renderer: loadedRenderer.current, - strict: strict - } - }, children); -} -function isLazyBundle(features) { - return typeof features === "function"; -} -var ReorderContext = React.createContext(null); -function checkReorder(order, value, offset, velocity) { - if (!velocity) return order; - var index = order.findIndex(function (item) { - return item.value === value; - }); - if (index === -1) return order; - var nextOffset = velocity > 0 ? 1 : -1; - var nextItem = order[index + nextOffset]; - if (!nextItem) return order; - var item = order[index]; - var nextLayout = nextItem.layout; - var nextItemCenter = popmotion.mix(nextLayout.min, nextLayout.max, 0.5); - if (nextOffset === 1 && item.layout.max + offset > nextItemCenter || nextOffset === -1 && item.layout.min + offset < nextItemCenter) { - return moveItem(order, index, index + nextOffset); - } - return order; -} -function ReorderGroup(_a, externalRef) { - var children = _a.children, - _b = _a.as, - as = _b === void 0 ? "ul" : _b, - _c = _a.axis, - axis = _c === void 0 ? "y" : _c, - onReorder = _a.onReorder, - values = _a.values, - props = tslib.__rest(_a, ["children", "as", "axis", "onReorder", "values"]); - var Component = useConstant(function () { - return motion(as); - }); - var order = []; - var isReordering = React.useRef(false); - heyListen.invariant(Boolean(values), "Reorder.Group must be provided a values prop"); - var context = { - axis: axis, - registerItem: function (value, layout) { - /** - * Ensure entries can't add themselves more than once - */ - if (layout && order.findIndex(function (entry) { - return value === entry.value; - }) === -1) { - order.push({ - value: value, - layout: layout[axis] - }); - order.sort(compareMin); - } - }, - updateOrder: function (id, offset, velocity) { - if (isReordering.current) return; - var newOrder = checkReorder(order, id, offset, velocity); - if (order !== newOrder) { - isReordering.current = true; - onReorder(newOrder.map(getValue).filter(function (value) { - return values.indexOf(value) !== -1; - })); - } - } - }; - React.useEffect(function () { - isReordering.current = false; - }); - return React__namespace.createElement(Component, tslib.__assign({}, props, { - ref: externalRef - }), React__namespace.createElement(ReorderContext.Provider, { - value: context - }, children)); -} -var Group = React.forwardRef(ReorderGroup); -function getValue(item) { - return item.value; -} -function compareMin(a, b) { - return a.layout.min - b.layout.min; -} - -/** - * Creates a `MotionValue` to track the state and velocity of a value. - * - * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. - * - * ```jsx - * export const MyComponent = () => { - * const scale = useMotionValue(1) - * - * return - * } - * ``` - * - * @param initial - The initial state. - * - * @public - */ -function useMotionValue(initial) { - var value = useConstant(function () { - return motionValue(initial); - }); - /** - * If this motion value is being used in static mode, like on - * the Framer canvas, force components to rerender when the motion - * value is updated. - */ - var isStatic = React.useContext(MotionConfigContext).isStatic; - if (isStatic) { - var _a = tslib.__read(React.useState(initial), 2), - setLatest_1 = _a[1]; - React.useEffect(function () { - return value.onChange(setLatest_1); - }, []); - } - return value; -} -var isCustomValueType = function (v) { - return typeof v === "object" && v.mix; -}; -var getMixer = function (v) { - return isCustomValueType(v) ? v.mix : undefined; -}; -function transform() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var useImmediate = !Array.isArray(args[0]); - var argOffset = useImmediate ? 0 : -1; - var inputValue = args[0 + argOffset]; - var inputRange = args[1 + argOffset]; - var outputRange = args[2 + argOffset]; - var options = args[3 + argOffset]; - var interpolator = popmotion.interpolate(inputRange, outputRange, tslib.__assign({ - mixer: getMixer(outputRange[0]) - }, options)); - return useImmediate ? interpolator(inputValue) : interpolator; -} -function useOnChange(value, callback) { - useIsomorphicLayoutEffect(function () { - if (isMotionValue(value)) return value.onChange(callback); - }, [callback]); -} -function useMultiOnChange(values, handler) { - useIsomorphicLayoutEffect(function () { - var subscriptions = values.map(function (value) { - return value.onChange(handler); - }); - return function () { - return subscriptions.forEach(function (unsubscribe) { - return unsubscribe(); - }); - }; - }); -} -function useCombineMotionValues(values, combineValues) { - /** - * Initialise the returned motion value. This remains the same between renders. - */ - var value = useMotionValue(combineValues()); - /** - * Create a function that will update the template motion value with the latest values. - * This is pre-bound so whenever a motion value updates it can schedule its - * execution in Framesync. If it's already been scheduled it won't be fired twice - * in a single frame. - */ - var updateValue = function () { - return value.set(combineValues()); - }; - /** - * Synchronously update the motion value with the latest values during the render. - * This ensures that within a React render, the styles applied to the DOM are up-to-date. - */ - updateValue(); - /** - * Subscribe to all motion values found within the template. Whenever any of them change, - * schedule an update. - */ - useMultiOnChange(values, function () { - return sync__default["default"].update(updateValue, false, true); - }); - return value; -} -function useTransform(input, inputRangeOrTransformer, outputRange, options) { - var transformer = typeof inputRangeOrTransformer === "function" ? inputRangeOrTransformer : transform(inputRangeOrTransformer, outputRange, options); - return Array.isArray(input) ? useListTransform(input, transformer) : useListTransform([input], function (_a) { - var _b = tslib.__read(_a, 1), - latest = _b[0]; - return transformer(latest); - }); -} -function useListTransform(values, transformer) { - var latest = useConstant(function () { - return []; - }); - return useCombineMotionValues(values, function () { - latest.length = 0; - var numValues = values.length; - for (var i = 0; i < numValues; i++) { - latest[i] = values[i].get(); - } - return transformer(latest); - }); -} -function useDefaultMotionValue(value, defaultValue) { - if (defaultValue === void 0) { - defaultValue = 0; - } - return isMotionValue(value) ? value : useMotionValue(defaultValue); -} -function ReorderItem(_a, externalRef) { - var children = _a.children, - style = _a.style, - value = _a.value, - _b = _a.as, - as = _b === void 0 ? "li" : _b, - onDrag = _a.onDrag, - _c = _a.layout, - layout = _c === void 0 ? true : _c, - props = tslib.__rest(_a, ["children", "style", "value", "as", "onDrag", "layout"]); - var Component = useConstant(function () { - return motion(as); - }); - var context = React.useContext(ReorderContext); - var point = { - x: useDefaultMotionValue(style === null || style === void 0 ? void 0 : style.x), - y: useDefaultMotionValue(style === null || style === void 0 ? void 0 : style.y) - }; - var zIndex = useTransform([point.x, point.y], function (_a) { - var _b = tslib.__read(_a, 2), - latestX = _b[0], - latestY = _b[1]; - return latestX || latestY ? 1 : "unset"; - }); - var measuredLayout = React.useRef(null); - heyListen.invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group"); - var _d = context, - axis = _d.axis, - registerItem = _d.registerItem, - updateOrder = _d.updateOrder; - React.useEffect(function () { - registerItem(value, measuredLayout.current); - }, [context]); - return React__namespace.createElement(Component, tslib.__assign({ - drag: axis - }, props, { - dragSnapToOrigin: true, - style: tslib.__assign(tslib.__assign({}, style), { - x: point.x, - y: point.y, - zIndex: zIndex - }), - layout: layout, - onDrag: function (event, gesturePoint) { - var velocity = gesturePoint.velocity; - velocity[axis] && updateOrder(value, point[axis].get(), velocity[axis]); - onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, gesturePoint); - }, - onLayoutMeasure: function (measured) { - measuredLayout.current = measured; - }, - ref: externalRef - }), children); -} -var Item = React.forwardRef(ReorderItem); -var Reorder = { - Group: Group, - Item: Item -}; + /***/ "../../../node_modules/graphql/jsutils/didYouMean.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/didYouMean.mjs ***! + \************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.didYouMean = didYouMean; + const MAX_SUGGESTIONS = 5; + /** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ -/** - * @public - */ -var domAnimation = tslib.__assign(tslib.__assign({ - renderer: createDomVisualElement -}, animations), gestureAnimations); - -/** - * @public - */ -var domMax = tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, domAnimation), drag), layoutFeatures), { - projectionNodeConstructor: HTMLProjectionNode -}); - -/** - * Combine multiple motion values into a new one using a string template literal. - * - * ```jsx - * import { - * motion, - * useSpring, - * useMotionValue, - * useMotionTemplate - * } from "framer-motion" - * - * function Component() { - * const shadowX = useSpring(0) - * const shadowY = useMotionValue(0) - * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` - * - * return - * } - * ``` - * - * @public - */ -function useMotionTemplate(fragments) { - var values = []; - for (var _i = 1; _i < arguments.length; _i++) { - values[_i - 1] = arguments[_i]; - } - /** - * Create a function that will build a string from the latest motion values. - */ - var numFragments = fragments.length; - function buildValue() { - var output = ""; - for (var i = 0; i < numFragments; i++) { - output += fragments[i]; - var value = values[i]; - if (value) output += values[i].get(); - } - return output; - } - return useCombineMotionValues(values, buildValue); -} - -/** - * Creates a `MotionValue` that, when `set`, will use a spring animation to animate to its new state. - * - * It can either work as a stand-alone `MotionValue` by initialising it with a value, or as a subscriber - * to another `MotionValue`. - * - * @remarks - * - * ```jsx - * const x = useSpring(0, { stiffness: 300 }) - * const y = useSpring(x, { damping: 10 }) - * ``` - * - * @param inputValue - `MotionValue` or number. If provided a `MotionValue`, when the input `MotionValue` changes, the created `MotionValue` will spring towards that value. - * @param springConfig - Configuration options for the spring. - * @returns `MotionValue` - * - * @public - */ -function useSpring(source, config) { - if (config === void 0) { - config = {}; - } - var isStatic = React.useContext(MotionConfigContext).isStatic; - var activeSpringAnimation = React.useRef(null); - var value = useMotionValue(isMotionValue(source) ? source.get() : source); - React.useMemo(function () { - return value.attach(function (v, set) { - /** - * A more hollistic approach to this might be to use isStatic to fix VisualElement animations - * at that level, but this will work for now - */ - if (isStatic) return set(v); - if (activeSpringAnimation.current) { - activeSpringAnimation.current.stop(); - } - activeSpringAnimation.current = popmotion.animate(tslib.__assign(tslib.__assign({ - from: value.get(), - to: v, - velocity: value.getVelocity() - }, config), { - onUpdate: set - })); - return value.get(); - }); - }, [JSON.stringify(config)]); - useOnChange(source, function (v) { - return value.set(parseFloat(v)); - }); - return value; -} - -/** - * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. - * - * ```javascript - * const x = useMotionValue(0) - * const xVelocity = useVelocity(x) - * const xAcceleration = useVelocity(xVelocity) - * ``` - * - * @public - */ -function useVelocity(value) { - var velocity = useMotionValue(value.getVelocity()); - React.useEffect(function () { - return value.velocityUpdateSubscribers.add(function (newVelocity) { - velocity.set(newVelocity); - }); - }, [value]); - return velocity; -} -var createScrollMotionValues = function () { - return { - scrollX: motionValue(0), - scrollY: motionValue(0), - scrollXProgress: motionValue(0), - scrollYProgress: motionValue(0) - }; -}; -function useScroll(_a) { - if (_a === void 0) { - _a = {}; - } - var container = _a.container, - target = _a.target, - options = tslib.__rest(_a, ["container", "target"]); - var values = useConstant(createScrollMotionValues); - useIsomorphicLayoutEffect(function () { - return dom.scroll(function (_a) { - var x = _a.x, - y = _a.y; - values.scrollX.set(x.current); - values.scrollXProgress.set(x.progress); - values.scrollY.set(y.current); - values.scrollYProgress.set(y.progress); - }, tslib.__assign(tslib.__assign({}, options), { - container: (container === null || container === void 0 ? void 0 : container.current) || undefined, - target: (target === null || target === void 0 ? void 0 : target.current) || undefined - })); - }, []); - return values; -} -function useElementScroll(ref) { - warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref })."); - return useScroll({ - container: ref - }); -} -function useViewportScroll() { - warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll()."); - return useScroll(); -} -var getCurrentTime = typeof performance !== "undefined" ? function () { - return performance.now(); -} : function () { - return Date.now(); -}; -function useAnimationFrame(callback) { - var initialTimestamp = useConstant(getCurrentTime); - var isStatic = React.useContext(MotionConfigContext).isStatic; - React.useEffect(function () { - if (isStatic) return; - var provideTimeSinceStart = function (_a) { - var timestamp = _a.timestamp; - callback(timestamp - initialTimestamp); - }; - sync__default["default"].update(provideTimeSinceStart, true); - return function () { - return sync.cancelSync.update(provideTimeSinceStart); - }; - }, [callback]); -} -function useTime() { - var time = useMotionValue(0); - useAnimationFrame(function (t) { - return time.set(t); - }); - return time; -} - -/** - * @public - */ -function animationControls() { - /** - * Track whether the host component has mounted. - */ - var hasMounted = false; - /** - * Pending animations that are started before a component is mounted. - * TODO: Remove this as animations should only run in effects - */ - var pendingAnimations = []; - /** - * A collection of linked component animation controls. - */ - var subscribers = new Set(); - var controls = { - subscribe: function (visualElement) { - subscribers.add(visualElement); - return function () { - return void subscribers.delete(visualElement); - }; - }, - start: function (definition, transitionOverride) { - /** - * TODO: We only perform this hasMounted check because in Framer we used to - * encourage the ability to start an animation within the render phase. This - * isn't behaviour concurrent-safe so when we make Framer concurrent-safe - * we can ditch this. - */ - if (hasMounted) { - var animations_1 = []; - subscribers.forEach(function (visualElement) { - animations_1.push(animateVisualElement(visualElement, definition, { - transitionOverride: transitionOverride - })); + function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = secondArg + ? [firstArg, secondArg] + : [undefined, firstArg]; + let message = " Did you mean "; + if (subMessage) { + message += subMessage + " "; + } + const suggestions = suggestionsArg.map((x) => `"${x}"`); + switch (suggestions.length) { + case 0: + return ""; + case 1: + return message + suggestions[0] + "?"; + case 2: + return message + suggestions[0] + " or " + suggestions[1] + "?"; + } + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(", ") + ", or " + lastItem + "?"; + } + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/groupBy.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/groupBy.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - return Promise.all(animations_1); - } else { - return new Promise(function (resolve) { - pendingAnimations.push({ - animation: [definition, transitionOverride], - resolve: resolve - }); + exports.groupBy = groupBy; + /** + * Groups array items into a Map, given a function to produce grouping key. + */ + function groupBy(list, keyFn) { + const result = new Map(); + for (const item of list) { + const key = keyFn(item); + const group = result.get(key); + if (group === undefined) { + result.set(key, [item]); + } else { + group.push(item); + } + } + return result; + } + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/identityFunc.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/identityFunc.mjs ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - }, - set: function (definition) { - heyListen.invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook."); - return subscribers.forEach(function (visualElement) { - setValues(visualElement, definition); - }); - }, - stop: function () { - subscribers.forEach(function (visualElement) { - stopAnimation(visualElement); - }); - }, - mount: function () { - hasMounted = true; - pendingAnimations.forEach(function (_a) { - var animation = _a.animation, - resolve = _a.resolve; - controls.start.apply(controls, tslib.__spreadArray([], tslib.__read(animation), false)).then(resolve); - }); - return function () { - hasMounted = false; - controls.stop(); - }; - } - }; - return controls; -} - -/** - * Creates `AnimationControls`, which can be used to manually start, stop - * and sequence animations on one or more components. - * - * The returned `AnimationControls` should be passed to the `animate` property - * of the components you want to animate. - * - * These components can then be animated with the `start` method. - * - * ```jsx - * import * as React from 'react' - * import { motion, useAnimation } from 'framer-motion' - * - * export function MyComponent(props) { - * const controls = useAnimation() - * - * controls.start({ - * x: 100, - * transition: { duration: 0.5 }, - * }) - * - * return - * } - * ``` - * - * @returns Animation controller with `start` and `stop` methods - * - * @public - */ -function useAnimationControls() { - var controls = useConstant(animationControls); - React.useEffect(controls.mount, []); - return controls; -} -var useAnimation = useAnimationControls; - -/** - * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. - * - * An index value can be passed to the returned `cycle` function to cycle to a specific index. - * - * ```jsx - * import * as React from "react" - * import { motion, useCycle } from "framer-motion" - * - * export const MyComponent = () => { - * const [x, cycleX] = useCycle(0, 50, 100) - * - * return ( - * cycleX()} - * /> - * ) - * } - * ``` - * - * @param items - items to cycle through - * @returns [currentState, cycleState] - * - * @public - */ -function useCycle() { - var items = []; - for (var _i = 0; _i < arguments.length; _i++) { - items[_i] = arguments[_i]; - } - var index = React.useRef(0); - var _a = tslib.__read(React.useState(items[index.current]), 2), - item = _a[0], - setItem = _a[1]; - var runCycle = React.useCallback(function (next) { - index.current = typeof next !== "number" ? popmotion.wrap(0, items.length, index.current + 1) : next; - setItem(items[index.current]); - }, tslib.__spreadArray([items.length], tslib.__read(items), false)); - return [item, runCycle]; -} -function useInView(ref, _a) { - var _b = _a === void 0 ? {} : _a, - root = _b.root, - margin = _b.margin, - amount = _b.amount, - _c = _b.once, - once = _c === void 0 ? false : _c; - var _d = tslib.__read(React.useState(false), 2), - isInView = _d[0], - setInView = _d[1]; - React.useEffect(function () { - var _a; - if (!ref.current || once && isInView) return; - var onEnter = function () { - setInView(true); - return once ? undefined : function () { - return setInView(false); - }; - }; - var options = { - root: (_a = root === null || root === void 0 ? void 0 : root.current) !== null && _a !== void 0 ? _a : undefined, - margin: margin, - amount: amount === "some" ? "any" : amount - }; - return dom.inView(ref.current, onEnter, options); - }, [root, ref, margin, once]); - return isInView; -} - -/** - * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. - * - * ```jsx - * const dragControls = useDragControls() - * - * function startDrag(event) { - * dragControls.start(event, { snapToCursor: true }) - * } - * - * return ( - * <> - *
- * - * - * ) - * ``` - * - * @public - */ -var DragControls = /** @class */function () { - function DragControls() { - this.componentControls = new Set(); - } - /** - * Subscribe a component's internal `VisualElementDragControls` to the user-facing API. - * - * @internal - */ - DragControls.prototype.subscribe = function (controls) { - var _this = this; - this.componentControls.add(controls); - return function () { - return _this.componentControls.delete(controls); - }; - }; - /** - * Start a drag gesture on every `motion` component that has this set of drag controls - * passed into it via the `dragControls` prop. - * - * ```jsx - * dragControls.start(e, { - * snapToCursor: true - * }) - * ``` - * - * @param event - PointerEvent - * @param options - Options - * - * @public - */ - DragControls.prototype.start = function (event, options) { - this.componentControls.forEach(function (controls) { - controls.start(event.nativeEvent || event, options); - }); - }; - return DragControls; -}(); -var createDragControls = function () { - return new DragControls(); -}; -/** - * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop - * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we - * might want to initiate that dragging from a different component than the draggable one. - * - * By creating a `dragControls` using the `useDragControls` hook, we can pass this into - * the draggable component's `dragControls` prop. It exposes a `start` method - * that can start dragging from pointer events on other components. - * - * ```jsx - * const dragControls = useDragControls() - * - * function startDrag(event) { - * dragControls.start(event, { snapToCursor: true }) - * } - * - * return ( - * <> - *
- * - * - * ) - * ``` - * - * @public - */ -function useDragControls() { - return useConstant(createDragControls); -} -function useInstantLayoutTransition() { - return startTransition; -} -function startTransition(cb) { - if (!rootProjectionNode.current) return; - rootProjectionNode.current.isUpdating = false; - rootProjectionNode.current.blockUpdate(); - cb === null || cb === void 0 ? void 0 : cb(); -} -function useInstantTransition() { - var _a = tslib.__read(useForceUpdate(), 2), - forceUpdate = _a[0], - forcedRenderCount = _a[1]; - var startInstantLayoutTransition = useInstantLayoutTransition(); - React.useEffect(function () { - /** - * Unblock after two animation frames, otherwise this will unblock too soon. - */ - sync__default["default"].postRender(function () { - return sync__default["default"].postRender(function () { - return instantAnimationState.current = false; - }); - }); - }, [forcedRenderCount]); - return function (callback) { - startInstantLayoutTransition(function () { - instantAnimationState.current = true; - forceUpdate(); - callback(); - }); - }; -} -function useResetProjection() { - var reset = React__namespace.useCallback(function () { - var root = rootProjectionNode.current; - if (!root) return; - root.resetTree(); - }, []); - return reset; -} -var createObject = function () { - return {}; -}; -var stateVisualElement = visualElement({ - build: function () {}, - measureViewportBox: createBox, - resetTransform: function () {}, - restoreTransform: function () {}, - removeValueFromRenderState: function () {}, - render: function () {}, - scrapeMotionValuesFromProps: createObject, - readValueFromInstance: function (_state, key, options) { - return options.initialState[key] || 0; - }, - makeTargetAnimatable: function (element, _a) { - var transition = _a.transition, - transitionEnd = _a.transitionEnd, - target = tslib.__rest(_a, ["transition", "transitionEnd"]); - var origin = getOrigin(target, transition || {}, element); - checkTargetForNewValues(element, target, origin); - return tslib.__assign({ - transition: transition, - transitionEnd: transitionEnd - }, target); - } -}); -var useVisualState = makeUseVisualState({ - scrapeMotionValuesFromProps: createObject, - createRenderState: createObject -}); -/** - * This is not an officially supported API and may be removed - * on any version. - */ -function useAnimatedState(initialState) { - var _a = tslib.__read(React.useState(initialState), 2), - animationState = _a[0], - setAnimationState = _a[1]; - var visualState = useVisualState({}, false); - var element = useConstant(function () { - return stateVisualElement({ - props: {}, - visualState: visualState - }, { - initialState: initialState - }); - }); - React.useEffect(function () { - element.mount({}); - return element.unmount; - }, [element]); - React.useEffect(function () { - element.setProps({ - onUpdate: function (v) { - setAnimationState(tslib.__assign({}, v)); - } - }); - }, [setAnimationState, element]); - var startAnimation = useConstant(function () { - return function (animationDefinition) { - return animateVisualElement(element, animationDefinition); - }; - }); - return [animationState, startAnimation]; -} - -// Keep things reasonable and avoid scale: Infinity. In practise we might need -// to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1] -// to simply hide content at unreasonable scales. -var maxScale = 100000; -var invertScale = function (scale) { - return scale > 0.001 ? 1 / scale : maxScale; -}; -var hasWarned = false; -/** - * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse - * of their respective parent scales. - * - * This is useful for undoing the distortion of content when scaling a parent component. - * - * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. - * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output - * of those instead. - * - * ```jsx - * const MyComponent = () => { - * const { scaleX, scaleY } = useInvertedScale() - * return - * } - * ``` - * - * @deprecated - */ -function useInvertedScale(scale) { - var parentScaleX = useMotionValue(1); - var parentScaleY = useMotionValue(1); - var visualElement = useVisualElementContext(); - heyListen.invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component."); - heyListen.warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead."); - hasWarned = true; - if (scale) { - parentScaleX = scale.scaleX || parentScaleX; - parentScaleY = scale.scaleY || parentScaleY; - } else if (visualElement) { - parentScaleX = visualElement.getValue("scaleX", 1); - parentScaleY = visualElement.getValue("scaleY", 1); - } - var scaleX = useTransform(parentScaleX, invertScale); - var scaleY = useTransform(parentScaleY, invertScale); - return { - scaleX: scaleX, - scaleY: scaleY - }; -} -exports.AnimatePresence = AnimatePresence; -exports.AnimateSharedLayout = AnimateSharedLayout; -exports.DeprecatedLayoutGroupContext = DeprecatedLayoutGroupContext; -exports.DragControls = DragControls; -exports.FlatTree = FlatTree; -exports.LayoutGroup = LayoutGroup; -exports.LayoutGroupContext = LayoutGroupContext; -exports.LazyMotion = LazyMotion; -exports.MotionConfig = MotionConfig; -exports.MotionConfigContext = MotionConfigContext; -exports.MotionContext = MotionContext; -exports.MotionValue = MotionValue; -exports.PresenceContext = PresenceContext; -exports.Reorder = Reorder; -exports.SwitchLayoutGroupContext = SwitchLayoutGroupContext; -exports.addPointerEvent = addPointerEvent; -exports.addScaleCorrector = addScaleCorrector; -exports.animate = animate; -exports.animateVisualElement = animateVisualElement; -exports.animationControls = animationControls; -exports.animations = animations; -exports.calcLength = calcLength; -exports.checkTargetForNewValues = checkTargetForNewValues; -exports.createBox = createBox; -exports.createDomMotionComponent = createDomMotionComponent; -exports.createMotionComponent = createMotionComponent; -exports.domAnimation = domAnimation; -exports.domMax = domMax; -exports.filterProps = filterProps; -exports.isBrowser = isBrowser; -exports.isDragActive = isDragActive; -exports.isMotionValue = isMotionValue; -exports.isValidMotionProp = isValidMotionProp; -exports.m = m; -exports.makeUseVisualState = makeUseVisualState; -exports.motion = motion; -exports.motionValue = motionValue; -exports.resolveMotionValue = resolveMotionValue; -exports.transform = transform; -exports.useAnimation = useAnimation; -exports.useAnimationControls = useAnimationControls; -exports.useAnimationFrame = useAnimationFrame; -exports.useCycle = useCycle; -exports.useDeprecatedAnimatedState = useAnimatedState; -exports.useDeprecatedInvertedScale = useInvertedScale; -exports.useDomEvent = useDomEvent; -exports.useDragControls = useDragControls; -exports.useElementScroll = useElementScroll; -exports.useForceUpdate = useForceUpdate; -exports.useInView = useInView; -exports.useInstantLayoutTransition = useInstantLayoutTransition; -exports.useInstantTransition = useInstantTransition; -exports.useIsPresent = useIsPresent; -exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect; -exports.useMotionTemplate = useMotionTemplate; -exports.useMotionValue = useMotionValue; -exports.usePresence = usePresence; -exports.useReducedMotion = useReducedMotion; -exports.useReducedMotionConfig = useReducedMotionConfig; -exports.useResetProjection = useResetProjection; -exports.useScroll = useScroll; -exports.useSpring = useSpring; -exports.useTime = useTime; -exports.useTransform = useTransform; -exports.useUnmountEffect = useUnmountEffect; -exports.useVelocity = useVelocity; -exports.useViewportScroll = useViewportScroll; -exports.useVisualElementContext = useVisualElementContext; -exports.visualElement = visualElement; -exports.wrapHandler = wrapHandler; - -/***/ }), - -/***/ "../../../node_modules/framesync/dist/framesync.cjs.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/framesync/dist/framesync.cjs.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -const defaultTimestep = 1 / 60 * 1000; -const getCurrentTime = typeof performance !== "undefined" ? () => performance.now() : () => Date.now(); -const onNextFrame = typeof window !== "undefined" ? callback => window.requestAnimationFrame(callback) : callback => setTimeout(() => callback(getCurrentTime()), defaultTimestep); -function createRenderStep(runNextFrame) { - let toRun = []; - let toRunNextFrame = []; - let numToRun = 0; - let isProcessing = false; - let flushNextFrame = false; - const toKeepAlive = new WeakSet(); - const step = { - schedule: (callback, keepAlive = false, immediate = false) => { - const addToCurrentFrame = immediate && isProcessing; - const buffer = addToCurrentFrame ? toRun : toRunNextFrame; - if (keepAlive) toKeepAlive.add(callback); - if (buffer.indexOf(callback) === -1) { - buffer.push(callback); - if (addToCurrentFrame && isProcessing) numToRun = toRun.length; - } - return callback; - }, - cancel: callback => { - const index = toRunNextFrame.indexOf(callback); - if (index !== -1) toRunNextFrame.splice(index, 1); - toKeepAlive.delete(callback); - }, - process: frameData => { - if (isProcessing) { - flushNextFrame = true; - return; - } - isProcessing = true; - [toRun, toRunNextFrame] = [toRunNextFrame, toRun]; - toRunNextFrame.length = 0; - numToRun = toRun.length; - if (numToRun) { - for (let i = 0; i < numToRun; i++) { - const callback = toRun[i]; - callback(frameData); - if (toKeepAlive.has(callback)) { - step.schedule(callback); - runNextFrame(); + exports.identityFunc = identityFunc; + /** + * Returns the first argument it receives. + */ + function identityFunc(x) { + return x; + } + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/inspect.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/inspect.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.inspect = inspect; + const MAX_ARRAY_LENGTH = 10; + const MAX_RECURSIVE_DEPTH = 2; + /** + * Used to print values in error messages. + */ + + function inspect(value) { + return formatValue(value, []); + } + function formatValue(value, seenValues) { + switch (typeof value) { + case "string": + return JSON.stringify(value); + case "function": + return value.name ? `[function ${value.name}]` : "[function]"; + case "object": + return formatObjectValue(value, seenValues); + default: + return String(value); } } - } - isProcessing = false; - if (flushNextFrame) { - flushNextFrame = false; - step.process(frameData); - } - } - }; - return step; -} -const maxElapsed = 40; -let useDefaultElapsed = true; -let runNextFrame = false; -let isProcessing = false; -const frame = { - delta: 0, - timestamp: 0 -}; -const stepsOrder = ["read", "update", "preRender", "render", "postRender"]; -const steps = stepsOrder.reduce((acc, key) => { - acc[key] = createRenderStep(() => runNextFrame = true); - return acc; -}, {}); -const sync = stepsOrder.reduce((acc, key) => { - const step = steps[key]; - acc[key] = (process, keepAlive = false, immediate = false) => { - if (!runNextFrame) startLoop(); - return step.schedule(process, keepAlive, immediate); - }; - return acc; -}, {}); -const cancelSync = stepsOrder.reduce((acc, key) => { - acc[key] = steps[key].cancel; - return acc; -}, {}); -const flushSync = stepsOrder.reduce((acc, key) => { - acc[key] = () => steps[key].process(frame); - return acc; -}, {}); -const processStep = stepId => steps[stepId].process(frame); -const processFrame = timestamp => { - runNextFrame = false; - frame.delta = useDefaultElapsed ? defaultTimestep : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1); - frame.timestamp = timestamp; - isProcessing = true; - stepsOrder.forEach(processStep); - isProcessing = false; - if (runNextFrame) { - useDefaultElapsed = false; - onNextFrame(processFrame); - } -}; -const startLoop = () => { - runNextFrame = true; - useDefaultElapsed = true; - if (!isProcessing) onNextFrame(processFrame); -}; -const getFrameData = () => frame; -exports.cancelSync = cancelSync; -exports["default"] = sync; -exports.flushSync = flushSync; -exports.getFrameData = getFrameData; + function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return "null"; + } + if (previouslySeenValues.includes(value)) { + return "[Circular]"; + } + const seenValues = [...previouslySeenValues, value]; + if (isJSONable(value)) { + const jsonValue = value.toJSON(); // check for infinite recursion + + if (jsonValue !== value) { + return typeof jsonValue === "string" + ? jsonValue + : formatValue(jsonValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + return formatObject(value, seenValues); + } + function isJSONable(value) { + return typeof value.toJSON === "function"; + } + function formatObject(object, seenValues) { + const entries = Object.entries(object); + if (entries.length === 0) { + return "{}"; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return "[" + getObjectTag(object) + "]"; + } + const properties = entries.map( + ([key, value]) => key + ": " + formatValue(value, seenValues) + ); + return "{ " + properties.join(", ") + " }"; + } + function formatArray(array, seenValues) { + if (array.length === 0) { + return "[]"; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return "[Array]"; + } + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + if (remaining === 1) { + items.push("... 1 more item"); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + return "[" + items.join(", ") + "]"; + } + function getObjectTag(object) { + const tag = Object.prototype.toString + .call(object) + .replace(/^\[object /, "") + .replace(/]$/, ""); + if (tag === "Object" && typeof object.constructor === "function") { + const name = object.constructor.name; + if (typeof name === "string" && name !== "") { + return name; + } + } + return tag; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/get-nonce/dist/es2015/index.js": -/*!************************************************************!*\ - !*** ../../../node_modules/get-nonce/dist/es2015/index.js ***! + /***/ "../../../node_modules/graphql/jsutils/instanceOf.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/instanceOf.mjs ***! \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.instanceOf = void 0; + var _inspect = __webpack_require__( + /*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + /** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + */ + + const instanceOf = (exports.instanceOf = + /* c8 ignore next 6 */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + globalThis.process && globalThis.process.env.NODE_ENV === "production" + ? function instanceOf(value, constructor) { + return value instanceof constructor; + } + : function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + if (typeof value === "object" && value !== null) { + var _value$constructor; + + // Prefer Symbol.toStringTag since it is immune to minification. + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = + // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 + ? value[Symbol.toStringTag] + : (_value$constructor = value.constructor) === null || + _value$constructor === void 0 + ? void 0 + : _value$constructor.name; + if (className === valueClassName) { + const stringifiedValue = (0, _inspect.inspect)(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. +https://yarnpkg.com/en/docs/selective-version-resolutions -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.setNonce = exports.getNonce = void 0; -var currentNonce; -var setNonce = function (nonce) { - currentNonce = nonce; -}; -exports.setNonce = setNonce; -var getNonce = function () { - if (currentNonce) { - return currentNonce; - } - if (true) { - return __webpack_require__.nc; - } - return undefined; -}; -exports.getNonce = getNonce; +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`); + } + } + return false; + }); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql-ws/lib/client.mjs": -/*!*******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/client.mjs ***! - \*******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "../../../node_modules/graphql/jsutils/invariant.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/invariant.mjs ***! + \***********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.invariant = invariant; + function invariant(condition, message) { + const booleanCondition = Boolean(condition); + if (!booleanCondition) { + throw new Error( + message != null ? message : "Unexpected invariant triggered." + ); + } + } + /***/ + }, + /***/ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs": + /*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isAsyncIterable.mjs ***! + \*****************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isAsyncIterable = isAsyncIterable; + /** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + */ + function isAsyncIterable(maybeAsyncIterable) { + return ( + typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 + ? void 0 + : maybeAsyncIterable[Symbol.asyncIterator]) === "function" + ); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _exportNames = { - createClient: true -}; -exports.createClient = createClient; -var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); -Object.keys(_common).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _common[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _common[key]; - } - }); -}); -var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); -/** - * - * client - * - */ -var __await = void 0 && (void 0).__await || function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -}; -var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -}; + /***/ + }, -/** This file is the entry point for browsers, re-export common elements. */ - -/** - * Creates a disposable GraphQL over WebSocket client. - * - * @category Client - */ -function createClient(options) { - const { - url, - connectionParams, - lazy = true, - onNonLazyError = console.error, - lazyCloseTimeout: lazyCloseTimeoutMs = 0, - keepAlive = 0, - disablePong, - connectionAckWaitTimeout = 0, - retryAttempts = 5, - retryWait = async function randomisedExponentialBackoff(retries) { - let retryDelay = 1000; // start with 1s delay - for (let i = 0; i < retries; i++) { - retryDelay *= 2; - } - await new Promise(resolve => setTimeout(resolve, retryDelay + - // add random timeout from 300ms to 3s - Math.floor(Math.random() * (3000 - 300) + 300))); - }, - shouldRetry = isLikeCloseEvent, - isFatalConnectionProblem, - on, - webSocketImpl, - /** - * Generates a v4 UUID to be used as the ID using `Math` - * as the random number generator. Supply your own generator - * in case you need more uniqueness. - * - * Reference: https://gist.github.com/jed/982883 - */ - generateID = function generateUUID() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { - const r = Math.random() * 16 | 0, - v = c == 'x' ? r : r & 0x3 | 0x8; - return v.toString(16); - }); - }, - jsonMessageReplacer: replacer, - jsonMessageReviver: reviver - } = options; - let ws; - if (webSocketImpl) { - if (!isWebSocket(webSocketImpl)) { - throw new Error('Invalid WebSocket implementation provided'); - } - ws = webSocketImpl; - } else if (typeof WebSocket !== 'undefined') { - ws = WebSocket; - } else if (typeof __webpack_require__.g !== 'undefined') { - ws = __webpack_require__.g.WebSocket || - // @ts-expect-error: Support more browsers - __webpack_require__.g.MozWebSocket; - } else if (typeof window !== 'undefined') { - ws = window.WebSocket || - // @ts-expect-error: Support more browsers - window.MozWebSocket; - } - if (!ws) throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`"); - const WebSocketImpl = ws; - // websocket status emitter, subscriptions are handled differently - const emitter = (() => { - const message = (() => { - const listeners = {}; - return { - on(id, listener) { - listeners[id] = listener; - return () => { - delete listeners[id]; - }; - }, - emit(message) { - var _a; - if ('id' in message) (_a = listeners[message.id]) === null || _a === void 0 ? void 0 : _a.call(listeners, message); + /***/ "../../../node_modules/graphql/jsutils/isIterableObject.mjs": + /*!******************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isIterableObject.mjs ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isIterableObject = isIterableObject; + /** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @example + * ```ts + * isIterableObject([ 1, 2, 3 ]) // true + * isIterableObject(new Map()) // true + * isIterableObject('ABC') // false + * isIterableObject({ key: 'value' }) // false + * isIterableObject({ length: 1, 0: 'Alpha' }) // false + * ``` + */ + function isIterableObject(maybeIterable) { + return ( + typeof maybeIterable === "object" && + typeof (maybeIterable === null || maybeIterable === void 0 + ? void 0 + : maybeIterable[Symbol.iterator]) === "function" + ); } - }; - })(); - const listeners = { - connecting: (on === null || on === void 0 ? void 0 : on.connecting) ? [on.connecting] : [], - opened: (on === null || on === void 0 ? void 0 : on.opened) ? [on.opened] : [], - connected: (on === null || on === void 0 ? void 0 : on.connected) ? [on.connected] : [], - ping: (on === null || on === void 0 ? void 0 : on.ping) ? [on.ping] : [], - pong: (on === null || on === void 0 ? void 0 : on.pong) ? [on.pong] : [], - message: (on === null || on === void 0 ? void 0 : on.message) ? [message.emit, on.message] : [message.emit], - closed: (on === null || on === void 0 ? void 0 : on.closed) ? [on.closed] : [], - error: (on === null || on === void 0 ? void 0 : on.error) ? [on.error] : [] - }; - return { - onMessage: message.on, - on(event, listener) { - const l = listeners[event]; - l.push(listener); - return () => { - l.splice(l.indexOf(listener), 1); - }; + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/isObjectLike.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isObjectLike.mjs ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isObjectLike = isObjectLike; + /** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ + function isObjectLike(value) { + return typeof value == "object" && value !== null; + } + + /***/ }, - emit(event, ...args) { - // we copy the listeners so that unlistens dont "pull the rug under our feet" - for (const listener of [...listeners[event]]) { - // @ts-expect-error: The args should fit - listener(...args); + + /***/ "../../../node_modules/graphql/jsutils/isPromise.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isPromise.mjs ***! + \***********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isPromise = isPromise; + /** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ + function isPromise(value) { + return ( + typeof (value === null || value === void 0 + ? void 0 + : value.then) === "function" + ); } - } - }; - })(); - // invokes the callback either when an error or closed event is emitted, - // first one that gets called prevails, other emissions are ignored - function errorOrClosed(cb) { - const listening = [ - // errors are fatal and more critical than close events, throw them first - emitter.on('error', err => { - listening.forEach(unlisten => unlisten()); - cb(err); - }), - // closes can be graceful and not fatal, throw them second (if error didnt throw) - emitter.on('closed', event => { - listening.forEach(unlisten => unlisten()); - cb(event); - })]; - } - let connecting, - locks = 0, - lazyCloseTimeout, - retrying = false, - retries = 0, - disposed = false; - async function connect() { - // clear the lazy close timeout immediatelly so that close gets debounced - // see: https://github.com/enisdenjo/graphql-ws/issues/388 - clearTimeout(lazyCloseTimeout); - const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : connecting = new Promise((connected, denied) => (async () => { - if (retrying) { - await retryWait(retries); - // subscriptions might complete while waiting for retry - if (!locks) { - connecting = undefined; - return denied({ - code: 1000, - reason: 'All Subscriptions Gone' - }); - } - retries++; - } - emitter.emit('connecting'); - const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, _common.GRAPHQL_TRANSPORT_WS_PROTOCOL); - let connectionAckTimeout, queuedPing; - function enqueuePing() { - if (isFinite(keepAlive) && keepAlive > 0) { - clearTimeout(queuedPing); // in case where a pong was received before a ping (this is valid behaviour) - queuedPing = setTimeout(() => { - if (socket.readyState === WebSocketImpl.OPEN) { - socket.send((0, _common.stringifyMessage)({ - type: _common.MessageType.Ping - })); - emitter.emit('ping', false, undefined); - } - }, keepAlive); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/keyMap.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/keyMap.mjs ***! + \********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.keyMap = keyMap; + /** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { + * // Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } + * // } + * + * const jennyEntry = entriesByName['Jenny'] + * + * // { name: 'Jenny', num: '857-6309' } + * ``` + */ + function keyMap(list, keyFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = item; + } + return result; } - } - errorOrClosed(errOrEvent => { - connecting = undefined; - clearTimeout(connectionAckTimeout); - clearTimeout(queuedPing); - denied(errOrEvent); - if (isLikeCloseEvent(errOrEvent) && errOrEvent.code === 4499) { - socket.close(4499, 'Terminated'); // close event is artificial and emitted manually, see `Client.terminate()` below - socket.onerror = null; - socket.onclose = null; - } - }); - socket.onerror = err => emitter.emit('error', err); - socket.onclose = event => emitter.emit('closed', event); - socket.onopen = async () => { - try { - emitter.emit('opened', socket); - const payload = typeof connectionParams === 'function' ? await connectionParams() : connectionParams; - // connectionParams might take too long causing the server to kick off the client - // the necessary error/close event is already reported - simply stop execution - if (socket.readyState !== WebSocketImpl.OPEN) return; - socket.send((0, _common.stringifyMessage)(payload ? { - type: _common.MessageType.ConnectionInit, - payload - } : { - type: _common.MessageType.ConnectionInit - // payload is completely absent if not provided - }, replacer)); - if (isFinite(connectionAckWaitTimeout) && connectionAckWaitTimeout > 0) { - connectionAckTimeout = setTimeout(() => { - socket.close(_common.CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout'); - }, connectionAckWaitTimeout); - } - enqueuePing(); // enqueue ping (noop if disabled) - } catch (err) { - emitter.emit('error', err); - socket.close(_common.CloseCode.InternalClientError, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Internal client error')); - } - }; - let acknowledged = false; - socket.onmessage = ({ - data - }) => { - try { - const message = (0, _common.parseMessage)(data, reviver); - emitter.emit('message', message); - if (message.type === 'ping' || message.type === 'pong') { - emitter.emit(message.type, true, message.payload); // received - if (message.type === 'pong') { - enqueuePing(); // enqueue next ping (noop if disabled) - } else if (!disablePong) { - // respond with pong on ping - socket.send((0, _common.stringifyMessage)(message.payload ? { - type: _common.MessageType.Pong, - payload: message.payload - } : { - type: _common.MessageType.Pong - // payload is completely absent if not provided - })); - emitter.emit('pong', false, message.payload); - } - return; // ping and pongs can be received whenever - } - if (acknowledged) return; // already connected and acknowledged - if (message.type !== _common.MessageType.ConnectionAck) throw new Error(`First message cannot be of type ${message.type}`); - clearTimeout(connectionAckTimeout); - acknowledged = true; - emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged - retrying = false; // future lazy connects are not retries - retries = 0; // reset the retries on connect - connected([socket, new Promise((_, reject) => errorOrClosed(reject))]); - } catch (err) { - socket.onmessage = null; // stop reading messages as soon as reading breaks once - emitter.emit('error', err); - socket.close(_common.CloseCode.BadResponse, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Bad response')); - } - }; - })())); - // if the provided socket is in a closing state, wait for the throw on close - if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose; - let release = () => { - // releases this connection - }; - const released = new Promise(resolve => release = resolve); - return [socket, release, Promise.race([ - // wait for - released.then(() => { - if (!locks) { - // and if no more locks are present, complete the connection - const complete = () => socket.close(1000, 'Normal Closure'); - if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) { - // if the keepalive is set, allow for the specified calmdown time and - // then complete if the socket is still open. - lazyCloseTimeout = setTimeout(() => { - if (socket.readyState === WebSocketImpl.OPEN) complete(); - }, lazyCloseTimeoutMs); - } else { - // otherwise complete immediately - complete(); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/keyValMap.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/keyValMap.mjs ***! + \***********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.keyValMap = keyValMap; + /** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * ``` + */ + function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + return result; } - } - }), - // or - throwOnClose])]; - } - /** - * Checks the `connect` problem and evaluates if the client should retry. - */ - function shouldRetryConnectOrThrow(errOrCloseEvent) { - // some close codes are worth reporting immediately - if (isLikeCloseEvent(errOrCloseEvent) && (isFatalInternalCloseCode(errOrCloseEvent.code) || [_common.CloseCode.InternalServerError, _common.CloseCode.InternalClientError, _common.CloseCode.BadRequest, _common.CloseCode.BadResponse, _common.CloseCode.Unauthorized, - // CloseCode.Forbidden, might grant access out after retry - _common.CloseCode.SubprotocolNotAcceptable, - // CloseCode.ConnectionInitialisationTimeout, might not time out after retry - // CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry - _common.CloseCode.SubscriberAlreadyExists, _common.CloseCode.TooManyInitialisationRequests - // 4499, // Terminated, probably because the socket froze, we want to retry - ].includes(errOrCloseEvent.code))) throw errOrCloseEvent; - // client was disposed, no retries should proceed regardless - if (disposed) return false; - // normal closure (possibly all subscriptions have completed) - // if no locks were acquired in the meantime, shouldnt try again - if (isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1000) return locks > 0; - // retries are not allowed or we tried to many times, report error - if (!retryAttempts || retries >= retryAttempts) throw errOrCloseEvent; - // throw non-retryable connection problems - if (!shouldRetry(errOrCloseEvent)) throw errOrCloseEvent; - // @deprecated throw fatal connection problems immediately - if (isFatalConnectionProblem === null || isFatalConnectionProblem === void 0 ? void 0 : isFatalConnectionProblem(errOrCloseEvent)) throw errOrCloseEvent; - // looks good, start retrying - return retrying = true; - } - // in non-lazy (hot?) mode always hold one connection lock to persist the socket - if (!lazy) { - (async () => { - locks++; - for (;;) { - try { - const [,, throwOnClose] = await connect(); - await throwOnClose; // will always throw because releaser is not used - } catch (errOrCloseEvent) { - try { - if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; - } catch (errOrCloseEvent) { - // report thrown error, no further retries - return onNonLazyError === null || onNonLazyError === void 0 ? void 0 : onNonLazyError(errOrCloseEvent); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/mapValue.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/mapValue.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.mapValue = mapValue; + /** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ + function mapValue(map, fn) { + const result = Object.create(null); + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); } + return result; } - } - })(); - } - return { - on: emitter.on, - subscribe(payload, sink) { - const id = generateID(payload); - let done = false, - errored = false, - releaser = () => { - // for handling completions before connect - locks--; - done = true; - }; - (async () => { - locks++; - for (;;) { - try { - const [socket, release, waitForReleaseOrThrowOnClose] = await connect(); - // if done while waiting for connect, release the connection lock right away - if (done) return release(); - const unlisten = emitter.onMessage(id, message => { - switch (message.type) { - case _common.MessageType.Next: - { - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- payload will fit type - sink.next(message.payload); - return; - } - case _common.MessageType.Error: - { - errored = true, done = true; - sink.error(message.payload); - releaser(); - return; - } - case _common.MessageType.Complete: - { - done = true; - releaser(); // release completes the sink - return; - } - } - }); - socket.send((0, _common.stringifyMessage)({ - id, - type: _common.MessageType.Subscribe, - payload - }, replacer)); - releaser = () => { - if (!done && socket.readyState === WebSocketImpl.OPEN) - // if not completed already and socket is open, send complete message to server on release - socket.send((0, _common.stringifyMessage)({ - id, - type: _common.MessageType.Complete - }, replacer)); - locks--; - done = true; - release(); - }; - // either the releaser will be called, connection completed and - // the promise resolved or the socket closed and the promise rejected. - // whatever happens though, we want to stop listening for messages - await waitForReleaseOrThrowOnClose.finally(unlisten); - return; // completed, shouldnt try again - } catch (errOrCloseEvent) { - if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; - } - } - })().then(() => { - // delivering either an error or a complete terminates the sequence - if (!errored) sink.complete(); - }) // resolves on release or normal closure - .catch(err => { - sink.error(err); - }); // rejects on close events and errors - return () => { - // dispose only of active subscriptions - if (!done) releaser(); - }; - }, - iterate(request) { - const pending = []; - const deferred = { - done: false, - error: null, - resolve: () => { - // noop - } - }; - const dispose = this.subscribe(request, { - next(val) { - pending.push(val); - deferred.resolve(); - }, - error(err) { - deferred.done = true; - deferred.error = err; - deferred.resolve(); - }, - complete() { - deferred.done = true; - deferred.resolve(); - } - }); - const iterator = function iterator() { - return __asyncGenerator(this, arguments, function* iterator_1() { - for (;;) { - if (!pending.length) { - // only wait if there are no pending messages available - yield __await(new Promise(resolve => deferred.resolve = resolve)); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/memoize3.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/memoize3.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.memoize3 = memoize3; + /** + * Memoizes the provided three-argument function. + */ + function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + if (cache0 === undefined) { + cache0 = new WeakMap(); } - // first flush - while (pending.length) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield yield __await(pending.shift()); + let cache1 = cache0.get(a1); + if (cache1 === undefined) { + cache1 = new WeakMap(); + cache0.set(a1, cache1); } - // then error - if (deferred.error) { - throw deferred.error; + let cache2 = cache1.get(a2); + if (cache2 === undefined) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); } - // or complete - if (deferred.done) { - return yield __await(void 0); + let fnResult = cache2.get(a3); + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); } - } - }); - }(); - iterator.throw = async err => { - if (!deferred.done) { - deferred.done = true; - deferred.error = err; - deferred.resolve(); + return fnResult; + }; } - return { - done: true, - value: undefined - }; - }; - iterator.return = async () => { - dispose(); - return { - done: true, - value: undefined - }; - }; - return iterator; - }, - async dispose() { - disposed = true; - if (connecting) { - // if there is a connection, close it - const [socket] = await connecting; - socket.close(1000, 'Normal Closure'); - } - }, - terminate() { - if (connecting) { - // only if there is a connection - emitter.emit('closed', { - code: 4499, - reason: 'Terminated', - wasClean: false + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/naturalCompare.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/naturalCompare.mjs ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - } - }; -} -function isLikeCloseEvent(val) { - return (0, _utils.isObject)(val) && 'code' in val && 'reason' in val; -} -function isFatalInternalCloseCode(code) { - if ([1000, 1001, 1006, 1005, 1012, 1013, 1013 // Bad Gateway - ].includes(code)) return false; - // all other internal errors are fatal - return code >= 1000 && code <= 1999; -} -function isWebSocket(val) { - return typeof val === 'function' && 'constructor' in val && 'CLOSED' in val && 'CLOSING' in val && 'CONNECTING' in val && 'OPEN' in val; -} - -/***/ }), - -/***/ "../../../node_modules/graphql-ws/lib/common.mjs": -/*!*******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/common.mjs ***! - \*******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.MessageType = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.CloseCode = void 0; -exports.isMessage = isMessage; -exports.parseMessage = parseMessage; -exports.stringifyMessage = stringifyMessage; -exports.validateMessage = validateMessage; -var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); -/** - * - * common - * - */ - -/** - * The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). - * - * @category Common - */ -const GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws'; -/** - * The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws). - * - * @private - */ -const DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws'; -/** - * `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). - * - * @category Common - */ -var CloseCode; -(function (CloseCode) { - CloseCode[CloseCode["InternalServerError"] = 4500] = "InternalServerError"; - CloseCode[CloseCode["InternalClientError"] = 4005] = "InternalClientError"; - CloseCode[CloseCode["BadRequest"] = 4400] = "BadRequest"; - CloseCode[CloseCode["BadResponse"] = 4004] = "BadResponse"; - /** Tried subscribing before connect ack */ - CloseCode[CloseCode["Unauthorized"] = 4401] = "Unauthorized"; - CloseCode[CloseCode["Forbidden"] = 4403] = "Forbidden"; - CloseCode[CloseCode["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable"; - CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout"; - CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout"; - /** Subscriber distinction is very important */ - CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists"; - CloseCode[CloseCode["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests"; -})(CloseCode || (exports.CloseCode = CloseCode = {})); -/** - * Types of messages allowed to be sent by the client/server over the WS protocol. - * - * @category Common - */ -var MessageType; -(function (MessageType) { - MessageType["ConnectionInit"] = "connection_init"; - MessageType["ConnectionAck"] = "connection_ack"; - MessageType["Ping"] = "ping"; - MessageType["Pong"] = "pong"; - MessageType["Subscribe"] = "subscribe"; - MessageType["Next"] = "next"; - MessageType["Error"] = "error"; - MessageType["Complete"] = "complete"; -})(MessageType || (exports.MessageType = MessageType = {})); -/** - * Validates the message against the GraphQL over WebSocket Protocol. - * - * Invalid messages will throw descriptive errors. - * - * @category Common - */ -function validateMessage(val) { - if (!(0, _utils.isObject)(val)) { - throw new Error(`Message is expected to be an object, but got ${(0, _utils.extendedTypeof)(val)}`); - } - if (!val.type) { - throw new Error(`Message is missing the 'type' property`); - } - if (typeof val.type !== 'string') { - throw new Error(`Message is expects the 'type' property to be a string, but got ${(0, _utils.extendedTypeof)(val.type)}`); - } - switch (val.type) { - case MessageType.ConnectionInit: - case MessageType.ConnectionAck: - case MessageType.Ping: - case MessageType.Pong: - { - if (val.payload != null && !(0, _utils.isObject)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${val.payload}"`); - } - break; - } - case MessageType.Subscribe: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); - } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); - } - if (!(0, _utils.isObject)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); - } - if (typeof val.payload.query !== 'string') { - throw new Error(`"${val.type}" message payload expects the 'query' property to be a string, but got ${(0, _utils.extendedTypeof)(val.payload.query)}`); - } - if (val.payload.variables != null && !(0, _utils.isObject)(val.payload.variables)) { - throw new Error(`"${val.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.variables)}`); + exports.naturalCompare = naturalCompare; + /** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ + function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + let bNum = 0; + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + if (aNum < bNum) { + return -1; + } + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + if (aChar > bChar) { + return 1; + } + ++aIndex; + ++bIndex; + } + } + return aStr.length - bStr.length; } - if (val.payload.operationName != null && (0, _utils.extendedTypeof)(val.payload.operationName) !== 'string') { - throw new Error(`"${val.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.operationName)}`); + const DIGIT_0 = 48; + const DIGIT_9 = 57; + function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; } - if (val.payload.extensions != null && !(0, _utils.isObject)(val.payload.extensions)) { - throw new Error(`"${val.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.extensions)}`); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/printPathArray.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/printPathArray.mjs ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.printPathArray = printPathArray; + /** + * Build a string describing the path. + */ + function printPathArray(path) { + return path + .map((key) => + typeof key === "number" ? "[" + key.toString() + "]" : "." + key + ) + .join(""); } - break; - } - case MessageType.Next: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/promiseForObject.mjs": + /*!******************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/promiseForObject.mjs ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.promiseForObject = promiseForObject; + /** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ + function promiseForObject(object) { + return Promise.all(Object.values(object)).then((resolvedValues) => { + const resolvedObject = Object.create(null); + for (const [i, key] of Object.keys(object).entries()) { + resolvedObject[key] = resolvedValues[i]; + } + return resolvedObject; + }); } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/promiseReduce.mjs": + /*!***************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/promiseReduce.mjs ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.promiseReduce = promiseReduce; + var _isPromise = __webpack_require__( + /*! ./isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs" + ); + /** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ + function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + for (const value of values) { + accumulator = (0, _isPromise.isPromise)(accumulator) + ? accumulator.then((resolved) => callbackFn(resolved, value)) + : callbackFn(accumulator, value); + } + return accumulator; } - if (!(0, _utils.isObject)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/suggestionList.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/suggestionList.mjs ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.suggestionList = suggestionList; + var _naturalCompare = __webpack_require__( + /*! ./naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs" + ); + /** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ + + function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 + ? distanceDiff + : (0, _naturalCompare.naturalCompare)(a, b); + }); } - break; - } - case MessageType.Error: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + /** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ + + class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [ + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + ]; + } + measure(option, threshold) { + if (this._input === option) { + return 0; + } + const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + const aLength = a.length; + const bLength = b.length; + if (aLength - bLength > threshold) { + return undefined; + } + const rows = this._rows; + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = (currentRow[0] = i); + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min( + upRow[j] + 1, + // delete + currentRow[j - 1] + 1, + // insert + upRow[j - 1] + cost // substitute + ); + if ( + i > 1 && + j > 1 && + a[i - 1] === b[j - 2] && + a[i - 2] === b[j - 1] + ) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + currentRow[j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + if (smallestCell > threshold) { + return undefined; + } + } + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + return array; } - if (!(0, _utils.areGraphQLErrors)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(val.payload)}`); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/toError.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/toError.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.toError = toError; + var _inspect = __webpack_require__( + /*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + /** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + */ + + function toError(thrownValue) { + return thrownValue instanceof Error + ? thrownValue + : new NonErrorThrown(thrownValue); } - break; - } - case MessageType.Complete: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + class NonErrorThrown extends Error { + constructor(thrownValue) { + super( + "Unexpected error value: " + (0, _inspect.inspect)(thrownValue) + ); + this.name = "NonErrorThrown"; + this.thrownValue = thrownValue; + } } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + + /***/ + }, + + /***/ "../../../node_modules/graphql/jsutils/toObjMap.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/toObjMap.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.toObjMap = toObjMap; + function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + const map = Object.create(null); + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + return map; } - break; - } - default: - throw new Error(`Invalid message 'type' property "${val.type}"`); - } - return val; -} -/** - * Checks if the provided value is a valid GraphQL over WebSocket message. - * - * @deprecated Use `validateMessage` instead. - * - * @category Common - */ -function isMessage(val) { - try { - validateMessage(val); - return true; - } catch (_a) { - return false; - } -} -/** - * Parses the raw websocket message data to a valid message. - * - * @category Common - */ -function parseMessage(data, reviver) { - return validateMessage(typeof data === 'string' ? JSON.parse(data, reviver) : data); -} -/** - * Stringifies a valid message ready to be sent through the socket. - * - * @category Common - */ -function stringifyMessage(msg, replacer) { - validateMessage(msg); - return JSON.stringify(msg, replacer); -} - -/***/ }), - -/***/ "../../../node_modules/graphql-ws/lib/index.js": -/*!*****************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/index.js ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + + /***/ "../../../node_modules/graphql/language/ast.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql/language/ast.mjs ***! + \******************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Token = + exports.QueryDocumentKeys = + exports.OperationTypeNode = + exports.Location = + void 0; + exports.isNode = isNode; + /** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ + class Location { + /** + * The character offset at which this Node begins. + */ + /** + * The character offset at which this Node ends. + */ -var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); -} : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); -var __exportStar = void 0 && (void 0).__exportStar || function (m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -__exportStar(__webpack_require__(/*! ./client */ "../../../node_modules/graphql-ws/lib/client.mjs"), exports); -__exportStar(__webpack_require__(/*! ./server */ "../../../node_modules/graphql-ws/lib/server.mjs"), exports); -__exportStar(__webpack_require__(/*! ./common */ "../../../node_modules/graphql-ws/lib/common.mjs"), exports); + /** + * The Token at which this Node begins. + */ -/***/ }), + /** + * The Token at which this Node ends. + */ -/***/ "../../../node_modules/graphql-ws/lib/server.mjs": -/*!*******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/server.mjs ***! - \*******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.handleProtocols = handleProtocols; -exports.makeServer = makeServer; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); -var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); -/** - * - * server - * - */ -var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function (v) { - return new Promise(function (resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } -}; -/** - * Makes a Protocol complient WebSocket GraphQL server. The server - * is actually an API which is to be used with your favourite WebSocket - * server library! - * - * Read more about the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). - * - * @category Server - */ -function makeServer(options) { - const { - schema, - context, - roots, - validate, - execute, - subscribe, - connectionInitWaitTimeout = 3000, - // 3 seconds - onConnect, - onDisconnect, - onClose, - onSubscribe, - onOperation, - onNext, - onError, - onComplete, - jsonMessageReviver: reviver, - jsonMessageReplacer: replacer - } = options; - return { - opened(socket, extra) { - const ctx = { - connectionInitReceived: false, - acknowledged: false, - subscriptions: {}, - extra - }; - if (socket.protocol !== _common.GRAPHQL_TRANSPORT_WS_PROTOCOL) { - socket.close(_common.CloseCode.SubprotocolNotAcceptable, 'Subprotocol not acceptable'); - return async (code, reason) => { - /* nothing was set up, just notify the closure */ - await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); - }; - } - // kick the client off (close socket) if the connection has - // not been initialised after the specified wait timeout - const connectionInitWait = connectionInitWaitTimeout > 0 && isFinite(connectionInitWaitTimeout) ? setTimeout(() => { - if (!ctx.connectionInitReceived) socket.close(_common.CloseCode.ConnectionInitialisationTimeout, 'Connection initialisation timeout'); - }, connectionInitWaitTimeout) : null; - socket.onMessage(async function onMessage(data) { - var _a, e_1, _b, _c; - var _d; - let message; - try { - message = (0, _common.parseMessage)(data, reviver); - } catch (err) { - return socket.close(_common.CloseCode.BadRequest, 'Invalid message received'); + /** + * The Source document the AST represents. + */ + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + get [Symbol.toStringTag]() { + return "Location"; + } + toJSON() { + return { + start: this.start, + end: this.end, + }; + } } - switch (message.type) { - case _common.MessageType.ConnectionInit: - { - if (ctx.connectionInitReceived) return socket.close(_common.CloseCode.TooManyInitialisationRequests, 'Too many initialisation requests'); - // @ts-expect-error: I can write - ctx.connectionInitReceived = true; - if ((0, _utils.isObject)(message.payload)) - // @ts-expect-error: I can write - ctx.connectionParams = message.payload; - const permittedOrPayload = await (onConnect === null || onConnect === void 0 ? void 0 : onConnect(ctx)); - if (permittedOrPayload === false) return socket.close(_common.CloseCode.Forbidden, 'Forbidden'); - await socket.send((0, _common.stringifyMessage)((0, _utils.isObject)(permittedOrPayload) ? { - type: _common.MessageType.ConnectionAck, - payload: permittedOrPayload - } : { - type: _common.MessageType.ConnectionAck - // payload is completely absent if not provided - }, replacer)); - // @ts-expect-error: I can write - ctx.acknowledged = true; - return; - } - case _common.MessageType.Ping: - { - if (socket.onPing) - // if the onPing listener is registered, automatic pong is disabled - return await socket.onPing(message.payload); - await socket.send((0, _common.stringifyMessage)(message.payload ? { - type: _common.MessageType.Pong, - payload: message.payload - } : { - type: _common.MessageType.Pong - // payload is completely absent if not provided - })); - return; - } - case _common.MessageType.Pong: - return await ((_d = socket.onPong) === null || _d === void 0 ? void 0 : _d.call(socket, message.payload)); - case _common.MessageType.Subscribe: - { - if (!ctx.acknowledged) return socket.close(_common.CloseCode.Unauthorized, 'Unauthorized'); - const { - id, - payload - } = message; - if (id in ctx.subscriptions) return socket.close(_common.CloseCode.SubscriberAlreadyExists, `Subscriber for ${id} already exists`); - // if this turns out to be a streaming operation, the subscription value - // will change to an `AsyncIterable`, otherwise it will stay as is - ctx.subscriptions[id] = null; - const emit = { - next: async (result, args) => { - let nextMessage = { - id, - type: _common.MessageType.Next, - payload: result - }; - const maybeResult = await (onNext === null || onNext === void 0 ? void 0 : onNext(ctx, nextMessage, args, result)); - if (maybeResult) nextMessage = Object.assign(Object.assign({}, nextMessage), { - payload: maybeResult - }); - await socket.send((0, _common.stringifyMessage)(nextMessage, replacer)); - }, - error: async errors => { - let errorMessage = { - id, - type: _common.MessageType.Error, - payload: errors - }; - const maybeErrors = await (onError === null || onError === void 0 ? void 0 : onError(ctx, errorMessage, errors)); - if (maybeErrors) errorMessage = Object.assign(Object.assign({}, errorMessage), { - payload: maybeErrors - }); - await socket.send((0, _common.stringifyMessage)(errorMessage, replacer)); - }, - complete: async notifyClient => { - const completeMessage = { - id, - type: _common.MessageType.Complete - }; - await (onComplete === null || onComplete === void 0 ? void 0 : onComplete(ctx, completeMessage)); - if (notifyClient) await socket.send((0, _common.stringifyMessage)(completeMessage, replacer)); - } - }; - try { - let execArgs; - const maybeExecArgsOrErrors = await (onSubscribe === null || onSubscribe === void 0 ? void 0 : onSubscribe(ctx, message)); - if (maybeExecArgsOrErrors) { - if ((0, _utils.areGraphQLErrors)(maybeExecArgsOrErrors)) return await emit.error(maybeExecArgsOrErrors);else if (Array.isArray(maybeExecArgsOrErrors)) throw new Error('Invalid return value from onSubscribe hook, expected an array of GraphQLError objects'); - // not errors, is exec args - execArgs = maybeExecArgsOrErrors; - } else { - // you either provide a schema dynamically through - // `onSubscribe` or you set one up during the server setup - if (!schema) throw new Error('The GraphQL schema is not provided'); - const args = { - operationName: payload.operationName, - document: (0, _graphql.parse)(payload.query), - variableValues: payload.variables - }; - execArgs = Object.assign(Object.assign({}, args), { - schema: typeof schema === 'function' ? await schema(ctx, message, args) : schema - }); - const validationErrors = (validate !== null && validate !== void 0 ? validate : _graphql.validate)(execArgs.schema, execArgs.document); - if (validationErrors.length > 0) return await emit.error(validationErrors); - } - const operationAST = (0, _graphql.getOperationAST)(execArgs.document, execArgs.operationName); - if (!operationAST) return await emit.error([new _graphql.GraphQLError('Unable to identify operation')]); - // if `onSubscribe` didnt specify a rootValue, inject one - if (!('rootValue' in execArgs)) execArgs.rootValue = roots === null || roots === void 0 ? void 0 : roots[operationAST.operation]; - // if `onSubscribe` didn't specify a context, inject one - if (!('contextValue' in execArgs)) execArgs.contextValue = typeof context === 'function' ? await context(ctx, message, execArgs) : context; - // the execution arguments have been prepared - // perform the operation and act accordingly - let operationResult; - if (operationAST.operation === 'subscription') operationResult = await (subscribe !== null && subscribe !== void 0 ? subscribe : _graphql.subscribe)(execArgs); - // operation === 'query' || 'mutation' - else operationResult = await (execute !== null && execute !== void 0 ? execute : _graphql.execute)(execArgs); - const maybeResult = await (onOperation === null || onOperation === void 0 ? void 0 : onOperation(ctx, message, execArgs, operationResult)); - if (maybeResult) operationResult = maybeResult; - if ((0, _utils.isAsyncIterable)(operationResult)) { - /** multiple emitted results */ - if (!(id in ctx.subscriptions)) { - // subscription was completed/canceled before the operation settled - if ((0, _utils.isAsyncGenerator)(operationResult)) operationResult.return(undefined); - } else { - ctx.subscriptions[id] = operationResult; - try { - for (var _e = true, operationResult_1 = __asyncValues(operationResult), operationResult_1_1; operationResult_1_1 = await operationResult_1.next(), _a = operationResult_1_1.done, !_a; _e = true) { - _c = operationResult_1_1.value; - _e = false; - const result = _c; - await emit.next(result, execArgs); - } - } catch (e_1_1) { - e_1 = { - error: e_1_1 - }; - } finally { - try { - if (!_e && !_a && (_b = operationResult_1.return)) await _b.call(operationResult_1); - } finally { - if (e_1) throw e_1.error; - } - } - } - } else { - /** single emitted result */ - // if the client completed the subscription before the single result - // became available, he effectively canceled it and no data should be sent - if (id in ctx.subscriptions) await emit.next(operationResult, execArgs); - } - // lack of subscription at this point indicates that the client - // completed the subscription, he doesnt need to be reminded - await emit.complete(id in ctx.subscriptions); - } finally { - // whatever happens to the subscription, we finally want to get rid of the reservation - delete ctx.subscriptions[id]; - } - return; + /** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + exports.Location = Location; + class Token { + /** + * The kind of Token. + */ + + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The 1-indexed line number on which this Token appears. + */ + + /** + * The 1-indexed column number at which this Token begins. + */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + * + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + constructor(kind, start, end, line, column, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + + this.value = value; + this.prev = null; + this.next = null; + } + get [Symbol.toStringTag]() { + return "Token"; + } + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; + } + } + /** + * The list of all possible AST node types. + */ + + /** + * @internal + */ + exports.Token = Token; + const QueryDocumentKeys = (exports.QueryDocumentKeys = { + Name: [], + Document: ["definitions"], + OperationDefinition: [ + "name", + "variableDefinitions", + "directives", + "selectionSet", + ], + VariableDefinition: [ + "variable", + "type", + "defaultValue", + "directives", + ], + Variable: ["name"], + SelectionSet: ["selections"], + Field: ["alias", "name", "arguments", "directives", "selectionSet"], + Argument: ["name", "value"], + FragmentSpread: ["name", "directives"], + InlineFragment: ["typeCondition", "directives", "selectionSet"], + FragmentDefinition: [ + "name", + // Note: fragment variable definitions are deprecated and will removed in v17.0.0 + "variableDefinitions", + "typeCondition", + "directives", + "selectionSet", + ], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ["values"], + ObjectValue: ["fields"], + ObjectField: ["name", "value"], + Directive: ["name", "arguments"], + NamedType: ["name"], + ListType: ["type"], + NonNullType: ["type"], + SchemaDefinition: ["description", "directives", "operationTypes"], + OperationTypeDefinition: ["type"], + ScalarTypeDefinition: ["description", "name", "directives"], + ObjectTypeDefinition: [ + "description", + "name", + "interfaces", + "directives", + "fields", + ], + FieldDefinition: [ + "description", + "name", + "arguments", + "type", + "directives", + ], + InputValueDefinition: [ + "description", + "name", + "type", + "defaultValue", + "directives", + ], + InterfaceTypeDefinition: [ + "description", + "name", + "interfaces", + "directives", + "fields", + ], + UnionTypeDefinition: ["description", "name", "directives", "types"], + EnumTypeDefinition: ["description", "name", "directives", "values"], + EnumValueDefinition: ["description", "name", "directives"], + InputObjectTypeDefinition: [ + "description", + "name", + "directives", + "fields", + ], + DirectiveDefinition: [ + "description", + "name", + "arguments", + "locations", + ], + SchemaExtension: ["directives", "operationTypes"], + ScalarTypeExtension: ["name", "directives"], + ObjectTypeExtension: ["name", "interfaces", "directives", "fields"], + InterfaceTypeExtension: [ + "name", + "interfaces", + "directives", + "fields", + ], + UnionTypeExtension: ["name", "directives", "types"], + EnumTypeExtension: ["name", "directives", "values"], + InputObjectTypeExtension: ["name", "directives", "fields"], + }); + const kindValues = new Set(Object.keys(QueryDocumentKeys)); + /** + * @internal + */ + + function isNode(maybeNode) { + const maybeKind = + maybeNode === null || maybeNode === void 0 + ? void 0 + : maybeNode.kind; + return typeof maybeKind === "string" && kindValues.has(maybeKind); + } + /** Name */ + + var OperationTypeNode; + (function (OperationTypeNode) { + OperationTypeNode["QUERY"] = "query"; + OperationTypeNode["MUTATION"] = "mutation"; + OperationTypeNode["SUBSCRIPTION"] = "subscription"; + })( + OperationTypeNode || + (exports.OperationTypeNode = OperationTypeNode = {}) + ); + + /***/ + }, + + /***/ "../../../node_modules/graphql/language/blockString.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/language/blockString.mjs ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.dedentBlockStringLines = dedentBlockStringLines; + exports.isPrintableAsBlockString = isPrintableAsBlockString; + exports.printBlockString = printBlockString; + var _characterClasses = __webpack_require__( + /*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs" + ); + /** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ + + function dedentBlockStringLines(lines) { + var _firstNonEmptyLine2; + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + for (let i = 0; i < lines.length; ++i) { + var _firstNonEmptyLine; + const line = lines[i]; + const indent = leadingWhitespace(line); + if (indent === line.length) { + continue; // skip empty lines } - case _common.MessageType.Complete: - { - const subscription = ctx.subscriptions[message.id]; - delete ctx.subscriptions[message.id]; // deleting the subscription means no further activity should take place - if ((0, _utils.isAsyncGenerator)(subscription)) await subscription.return(undefined); - return; + firstNonEmptyLine = + (_firstNonEmptyLine = firstNonEmptyLine) !== null && + _firstNonEmptyLine !== void 0 + ? _firstNonEmptyLine + : i; + lastNonEmptyLine = i; + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; } - default: - throw new Error(`Unexpected message of type ${message.type} received`); + } + return lines // Remove common indentation from all lines but first. + .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines. + .slice( + (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && + _firstNonEmptyLine2 !== void 0 + ? _firstNonEmptyLine2 + : 0, + lastNonEmptyLine + 1 + ); } - }); - // wait for close, cleanup and the disconnect callback - return async (code, reason) => { - if (connectionInitWait) clearTimeout(connectionInitWait); - for (const sub of Object.values(ctx.subscriptions)) { - if ((0, _utils.isAsyncGenerator)(sub)) await sub.return(undefined); + function leadingWhitespace(str) { + let i = 0; + while ( + i < str.length && + (0, _characterClasses.isWhitespace)(str.charCodeAt(i)) + ) { + ++i; + } + return i; } - if (ctx.acknowledged) await (onDisconnect === null || onDisconnect === void 0 ? void 0 : onDisconnect(ctx, code, reason)); - await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); - }; - } - }; -} -/** - * Helper utility for choosing the "graphql-transport-ws" subprotocol from - * a set of WebSocket subprotocols. - * - * Accepts a set of already extracted WebSocket subprotocols or the raw - * Sec-WebSocket-Protocol header value. In either case, if the right - * protocol appears, it will be returned. - * - * By specification, the server should not provide a value with Sec-WebSocket-Protocol - * if it does not agree with client's subprotocols. The client has a responsibility - * to handle the connection afterwards. - * - * @category Server - */ -function handleProtocols(protocols) { - switch (true) { - case protocols instanceof Set && protocols.has(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): - case Array.isArray(protocols) && protocols.includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): - case typeof protocols === 'string' && protocols.split(',').map(p => p.trim()).includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): - return _common.GRAPHQL_TRANSPORT_WS_PROTOCOL; - default: - return false; - } -} + /** + * @internal + */ -/***/ }), + function isPrintableAsBlockString(value) { + if (value === "") { + return true; // empty string is printable + } + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + for (let i = 0; i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0x0000: + case 0x0001: + case 0x0002: + case 0x0003: + case 0x0004: + case 0x0005: + case 0x0006: + case 0x0007: + case 0x0008: + case 0x000b: + case 0x000c: + case 0x000e: + case 0x000f: + return false; + // Has non-printable characters -/***/ "../../../node_modules/graphql-ws/lib/utils.mjs": -/*!******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/utils.mjs ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.areGraphQLErrors = areGraphQLErrors; -exports.extendedTypeof = extendedTypeof; -exports.isAsyncGenerator = isAsyncGenerator; -exports.isAsyncIterable = isAsyncIterable; -exports.isObject = isObject; -exports.limitCloseReason = limitCloseReason; -/** @private */ -function extendedTypeof(val) { - if (val === null) { - return 'null'; - } - if (Array.isArray(val)) { - return 'array'; - } - return typeof val; -} -/** @private */ -function isObject(val) { - return extendedTypeof(val) === 'object'; -} -/** @private */ -function isAsyncIterable(val) { - return typeof Object(val)[Symbol.asyncIterator] === 'function'; -} -/** @private */ -function isAsyncGenerator(val) { - return isObject(val) && typeof Object(val)[Symbol.asyncIterator] === 'function' && typeof val.return === 'function' - // for lazy ones, we only need the return anyway - // typeof val.throw === 'function' && - // typeof val.next === 'function' - ; -} -/** @private */ -function areGraphQLErrors(obj) { - return Array.isArray(obj) && - // must be at least one error - obj.length > 0 && - // error has at least a message - obj.every(ob => 'message' in ob); -} -/** - * Limits the WebSocket close event reason to not exceed a length of one frame. - * Reference: https://datatracker.ietf.org/doc/html/rfc6455#section-5.2. - * - * @private - */ -function limitCloseReason(reason, whenTooLong) { - return reason.length < 124 ? reason : whenTooLong; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/error/GraphQLError.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/error/GraphQLError.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GraphQLError = void 0; -exports.formatError = formatError; -exports.printError = printError; -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _location = __webpack_require__(/*! ../language/location.mjs */ "../../../node_modules/graphql/language/location.mjs"); -var _printLocation = __webpack_require__(/*! ../language/printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); -function toNormalizedOptions(args) { - const firstArg = args[0]; - if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { - return { - nodes: firstArg, - source: args[1], - positions: args[2], - path: args[3], - originalError: args[4], - extensions: args[5] - }; - } - return firstArg; -} -/** - * A GraphQLError describes an Error found during the parse, validate, or - * execute phases of performing a GraphQL operation. In addition to a message - * and stack trace, it also includes information about the locations in a - * GraphQL document and/or execution result that correspond to the Error. - */ - -class GraphQLError extends Error { - /** - * An array of `{ line, column }` locations within the source GraphQL document - * which correspond to this error. - * - * Errors during validation often contain multiple locations, for example to - * point out two things with the same name. Errors during execution include a - * single location, the field which produced the error. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - - /** - * An array describing the JSON-path into the execution response which - * corresponds to this error. Only included for errors during execution. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - - /** - * An array of GraphQL AST Nodes corresponding to this error. - */ - - /** - * The source GraphQL document for the first location of this error. - * - * Note that if this Error represents more than one node, the source may not - * represent nodes after the first node. - */ - - /** - * An array of character offsets within the source GraphQL document - * which correspond to this error. - */ - - /** - * The original error thrown from a field resolver during execution. - */ - - /** - * Extension fields to add to the formatted error. - */ - - /** - * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. - */ - constructor(message, ...rawArgs) { - var _this$nodes, _nodeLocations$, _ref; - const { - nodes, - source, - positions, - path, - originalError, - extensions - } = toNormalizedOptions(rawArgs); - super(message); - this.name = 'GraphQLError'; - this.path = path !== null && path !== void 0 ? path : undefined; - this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. - - this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); - const nodeLocations = undefinedIfEmpty((_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map(node => node.loc).filter(loc => loc != null)); // Compute locations in the source for the given nodes/positions. - - this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source; - this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => loc.start); - this.locations = positions && source ? positions.map(pos => (0, _location.getLocation)(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => (0, _location.getLocation)(loc.source, loc.start)); - const originalExtensions = (0, _isObjectLike.isObjectLike)(originalError === null || originalError === void 0 ? void 0 : originalError.extensions) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : undefined; - this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : Object.create(null); // Only properties prescribed by the spec should be enumerable. - // Keep the rest as non-enumerable. - - Object.defineProperties(this, { - message: { - writable: true, - enumerable: true - }, - name: { - enumerable: false - }, - nodes: { - enumerable: false - }, - source: { - enumerable: false - }, - positions: { - enumerable: false + case 0x000d: + // \r + return false; + // Has \r or \r\n which will be replaced as \n + + case 10: + // \n + if (isEmptyLine && !seenNonEmptyLine) { + return false; // Has leading new line + } + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + case 9: // \t + + case 32: + // + hasIndent || (hasIndent = isEmptyLine); + break; + default: + hasCommonIndent && (hasCommonIndent = hasIndent); + isEmptyLine = false; + } + } + if (isEmptyLine) { + return false; // Has trailing empty lines + } + if (hasCommonIndent && seenNonEmptyLine) { + return false; // Has internal indent + } + return true; + } + /** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + + function printBlockString(value, options) { + const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + + const forceLeadingNewLine = + lines.length > 1 && + lines + .slice(1) + .every( + (line) => + line.length === 0 || + (0, _characterClasses.isWhitespace)(line.charCodeAt(0)) + ); // Trailing triple quotes just looks confusing but doesn't force trailing new line + + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line + + const hasTrailingQuote = + value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith("\\"); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = + !(options !== null && options !== void 0 && options.minimize) && + // add leading and trailing new lines only if it improves readability + (!isSingleLine || + value.length > 70 || + forceTrailingNewline || + forceLeadingNewLine || + hasTrailingTripleQuotes); + let result = ""; // Format a multi-line block quote to account for leading space. + + const skipLeadingNewLine = + isSingleLine && + (0, _characterClasses.isWhitespace)(value.charCodeAt(0)); + if ( + (printAsMultipleLines && !skipLeadingNewLine) || + forceLeadingNewLine + ) { + result += "\n"; + } + result += escapedValue; + if (printAsMultipleLines || forceTrailingNewline) { + result += "\n"; + } + return '"""' + result + '"""'; + } + + /***/ }, - originalError: { - enumerable: false - } - }); // Include (non-enumerable) stack trace. - - /* c8 ignore start */ - // FIXME: https://github.com/graphql/graphql-js/issues/2317 - - if (originalError !== null && originalError !== void 0 && originalError.stack) { - Object.defineProperty(this, 'stack', { - value: originalError.stack, - writable: true, - configurable: true - }); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, GraphQLError); - } else { - Object.defineProperty(this, 'stack', { - value: Error().stack, - writable: true, - configurable: true - }); - } - /* c8 ignore stop */ - } - get [Symbol.toStringTag]() { - return 'GraphQLError'; - } - toString() { - let output = this.message; - if (this.nodes) { - for (const node of this.nodes) { - if (node.loc) { - output += '\n\n' + (0, _printLocation.printLocation)(node.loc); + + /***/ "../../../node_modules/graphql/language/characterClasses.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/language/characterClasses.mjs ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isDigit = isDigit; + exports.isLetter = isLetter; + exports.isNameContinue = isNameContinue; + exports.isNameStart = isNameStart; + exports.isWhitespace = isWhitespace; + /** + * ``` + * Whitespace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ + function isWhitespace(code) { + return code === 0x0009 || code === 0x0020; } - } - } else if (this.source && this.locations) { - for (const location of this.locations) { - output += '\n\n' + (0, _printLocation.printSourceLocation)(this.source, location); - } - } - return output; - } - toJSON() { - const formattedError = { - message: this.message - }; - if (this.locations != null) { - formattedError.locations = this.locations; - } - if (this.path != null) { - formattedError.path = this.path; - } - if (this.extensions != null && Object.keys(this.extensions).length > 0) { - formattedError.extensions = this.extensions; - } - return formattedError; - } -} -exports.GraphQLError = GraphQLError; -function undefinedIfEmpty(array) { - return array === undefined || array.length === 0 ? undefined : array; -} -/** - * See: https://spec.graphql.org/draft/#sec-Errors - */ - -/** - * Prints a GraphQLError to a string, representing useful location information - * about the error's position in the source. - * - * @deprecated Please use `error.toString` instead. Will be removed in v17 - */ -function printError(error) { - return error.toString(); -} -/** - * Given a GraphQLError, format it according to the rules described by the - * Response Format, Errors section of the GraphQL Specification. - * - * @deprecated Please use `error.toJSON` instead. Will be removed in v17 - */ - -function formatError(error) { - return error.toJSON(); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/error/index.mjs": -/*!*****************************************************!*\ - !*** ../../../node_modules/graphql/error/index.mjs ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ + + function isDigit(code) { + return code >= 0x0030 && code <= 0x0039; + } + /** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ + + function isLetter(code) { + return ( + (code >= 0x0061 && code <= 0x007a) || + // A-Z + (code >= 0x0041 && code <= 0x005a) // a-z + ); + } + /** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ + function isNameStart(code) { + return isLetter(code) || code === 0x005f; + } + /** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ + function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 0x005f; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "GraphQLError", ({ - enumerable: true, - get: function () { - return _GraphQLError.GraphQLError; - } -})); -Object.defineProperty(exports, "formatError", ({ - enumerable: true, - get: function () { - return _GraphQLError.formatError; - } -})); -Object.defineProperty(exports, "locatedError", ({ - enumerable: true, - get: function () { - return _locatedError.locatedError; - } -})); -Object.defineProperty(exports, "printError", ({ - enumerable: true, - get: function () { - return _GraphQLError.printError; - } -})); -Object.defineProperty(exports, "syntaxError", ({ - enumerable: true, - get: function () { - return _syntaxError.syntaxError; - } -})); -var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _syntaxError = __webpack_require__(/*! ./syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); -var _locatedError = __webpack_require__(/*! ./locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); + /***/ + }, + + /***/ "../../../node_modules/graphql/language/directiveLocation.mjs": + /*!********************************************************************!*\ + !*** ../../../node_modules/graphql/language/directiveLocation.mjs ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.DirectiveLocation = void 0; + /** + * The set of allowed directive location values. + */ + var DirectiveLocation; + (function (DirectiveLocation) { + DirectiveLocation["QUERY"] = "QUERY"; + DirectiveLocation["MUTATION"] = "MUTATION"; + DirectiveLocation["SUBSCRIPTION"] = "SUBSCRIPTION"; + DirectiveLocation["FIELD"] = "FIELD"; + DirectiveLocation["FRAGMENT_DEFINITION"] = "FRAGMENT_DEFINITION"; + DirectiveLocation["FRAGMENT_SPREAD"] = "FRAGMENT_SPREAD"; + DirectiveLocation["INLINE_FRAGMENT"] = "INLINE_FRAGMENT"; + DirectiveLocation["VARIABLE_DEFINITION"] = "VARIABLE_DEFINITION"; + DirectiveLocation["SCHEMA"] = "SCHEMA"; + DirectiveLocation["SCALAR"] = "SCALAR"; + DirectiveLocation["OBJECT"] = "OBJECT"; + DirectiveLocation["FIELD_DEFINITION"] = "FIELD_DEFINITION"; + DirectiveLocation["ARGUMENT_DEFINITION"] = "ARGUMENT_DEFINITION"; + DirectiveLocation["INTERFACE"] = "INTERFACE"; + DirectiveLocation["UNION"] = "UNION"; + DirectiveLocation["ENUM"] = "ENUM"; + DirectiveLocation["ENUM_VALUE"] = "ENUM_VALUE"; + DirectiveLocation["INPUT_OBJECT"] = "INPUT_OBJECT"; + DirectiveLocation["INPUT_FIELD_DEFINITION"] = + "INPUT_FIELD_DEFINITION"; + })( + DirectiveLocation || + (exports.DirectiveLocation = DirectiveLocation = {}) + ); -/***/ }), + /** + * The enum type representing the directive location values. + * + * @deprecated Please use `DirectiveLocation`. Will be remove in v17. + */ -/***/ "../../../node_modules/graphql/error/locatedError.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/error/locatedError.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ + }, + + /***/ "../../../node_modules/graphql/language/index.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/index.mjs ***! + \********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function () { + return _visitor.BREAK; + }, + }); + Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function () { + return _directiveLocation.DirectiveLocation; + }, + }); + Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function () { + return _kinds.Kind; + }, + }); + Object.defineProperty(exports, "Lexer", { + enumerable: true, + get: function () { + return _lexer.Lexer; + }, + }); + Object.defineProperty(exports, "Location", { + enumerable: true, + get: function () { + return _ast.Location; + }, + }); + Object.defineProperty(exports, "OperationTypeNode", { + enumerable: true, + get: function () { + return _ast.OperationTypeNode; + }, + }); + Object.defineProperty(exports, "Source", { + enumerable: true, + get: function () { + return _source.Source; + }, + }); + Object.defineProperty(exports, "Token", { + enumerable: true, + get: function () { + return _ast.Token; + }, + }); + Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function () { + return _tokenKind.TokenKind; + }, + }); + Object.defineProperty(exports, "getEnterLeaveForKind", { + enumerable: true, + get: function () { + return _visitor.getEnterLeaveForKind; + }, + }); + Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function () { + return _location.getLocation; + }, + }); + Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function () { + return _visitor.getVisitFn; + }, + }); + Object.defineProperty(exports, "isConstValueNode", { + enumerable: true, + get: function () { + return _predicates.isConstValueNode; + }, + }); + Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function () { + return _predicates.isDefinitionNode; + }, + }); + Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function () { + return _predicates.isExecutableDefinitionNode; + }, + }); + Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function () { + return _predicates.isSelectionNode; + }, + }); + Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function () { + return _predicates.isTypeDefinitionNode; + }, + }); + Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function () { + return _predicates.isTypeExtensionNode; + }, + }); + Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function () { + return _predicates.isTypeNode; + }, + }); + Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function () { + return _predicates.isTypeSystemDefinitionNode; + }, + }); + Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function () { + return _predicates.isTypeSystemExtensionNode; + }, + }); + Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function () { + return _predicates.isValueNode; + }, + }); + Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parser.parse; + }, + }); + Object.defineProperty(exports, "parseConstValue", { + enumerable: true, + get: function () { + return _parser.parseConstValue; + }, + }); + Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function () { + return _parser.parseType; + }, + }); + Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function () { + return _parser.parseValue; + }, + }); + Object.defineProperty(exports, "print", { + enumerable: true, + get: function () { + return _printer.print; + }, + }); + Object.defineProperty(exports, "printLocation", { + enumerable: true, + get: function () { + return _printLocation.printLocation; + }, + }); + Object.defineProperty(exports, "printSourceLocation", { + enumerable: true, + get: function () { + return _printLocation.printSourceLocation; + }, + }); + Object.defineProperty(exports, "visit", { + enumerable: true, + get: function () { + return _visitor.visit; + }, + }); + Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function () { + return _visitor.visitInParallel; + }, + }); + var _source = __webpack_require__( + /*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs" + ); + var _location = __webpack_require__( + /*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs" + ); + var _printLocation = __webpack_require__( + /*! ./printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs" + ); + var _kinds = __webpack_require__( + /*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _tokenKind = __webpack_require__( + /*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs" + ); + var _lexer = __webpack_require__( + /*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs" + ); + var _parser = __webpack_require__( + /*! ./parser.mjs */ "../../../node_modules/graphql/language/parser.mjs" + ); + var _printer = __webpack_require__( + /*! ./printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _visitor = __webpack_require__( + /*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs" + ); + var _ast = __webpack_require__( + /*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _predicates = __webpack_require__( + /*! ./predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs" + ); + var _directiveLocation = __webpack_require__( + /*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs" + ); + /***/ + }, + /***/ "../../../node_modules/graphql/language/kinds.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/kinds.mjs ***! + \********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Kind = void 0; + /** + * The set of allowed kind values for AST nodes. + */ + var Kind; + (function (Kind) { + Kind["NAME"] = "Name"; + Kind["DOCUMENT"] = "Document"; + Kind["OPERATION_DEFINITION"] = "OperationDefinition"; + Kind["VARIABLE_DEFINITION"] = "VariableDefinition"; + Kind["SELECTION_SET"] = "SelectionSet"; + Kind["FIELD"] = "Field"; + Kind["ARGUMENT"] = "Argument"; + Kind["FRAGMENT_SPREAD"] = "FragmentSpread"; + Kind["INLINE_FRAGMENT"] = "InlineFragment"; + Kind["FRAGMENT_DEFINITION"] = "FragmentDefinition"; + Kind["VARIABLE"] = "Variable"; + Kind["INT"] = "IntValue"; + Kind["FLOAT"] = "FloatValue"; + Kind["STRING"] = "StringValue"; + Kind["BOOLEAN"] = "BooleanValue"; + Kind["NULL"] = "NullValue"; + Kind["ENUM"] = "EnumValue"; + Kind["LIST"] = "ListValue"; + Kind["OBJECT"] = "ObjectValue"; + Kind["OBJECT_FIELD"] = "ObjectField"; + Kind["DIRECTIVE"] = "Directive"; + Kind["NAMED_TYPE"] = "NamedType"; + Kind["LIST_TYPE"] = "ListType"; + Kind["NON_NULL_TYPE"] = "NonNullType"; + Kind["SCHEMA_DEFINITION"] = "SchemaDefinition"; + Kind["OPERATION_TYPE_DEFINITION"] = "OperationTypeDefinition"; + Kind["SCALAR_TYPE_DEFINITION"] = "ScalarTypeDefinition"; + Kind["OBJECT_TYPE_DEFINITION"] = "ObjectTypeDefinition"; + Kind["FIELD_DEFINITION"] = "FieldDefinition"; + Kind["INPUT_VALUE_DEFINITION"] = "InputValueDefinition"; + Kind["INTERFACE_TYPE_DEFINITION"] = "InterfaceTypeDefinition"; + Kind["UNION_TYPE_DEFINITION"] = "UnionTypeDefinition"; + Kind["ENUM_TYPE_DEFINITION"] = "EnumTypeDefinition"; + Kind["ENUM_VALUE_DEFINITION"] = "EnumValueDefinition"; + Kind["INPUT_OBJECT_TYPE_DEFINITION"] = "InputObjectTypeDefinition"; + Kind["DIRECTIVE_DEFINITION"] = "DirectiveDefinition"; + Kind["SCHEMA_EXTENSION"] = "SchemaExtension"; + Kind["SCALAR_TYPE_EXTENSION"] = "ScalarTypeExtension"; + Kind["OBJECT_TYPE_EXTENSION"] = "ObjectTypeExtension"; + Kind["INTERFACE_TYPE_EXTENSION"] = "InterfaceTypeExtension"; + Kind["UNION_TYPE_EXTENSION"] = "UnionTypeExtension"; + Kind["ENUM_TYPE_EXTENSION"] = "EnumTypeExtension"; + Kind["INPUT_OBJECT_TYPE_EXTENSION"] = "InputObjectTypeExtension"; + })(Kind || (exports.Kind = Kind = {})); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.locatedError = locatedError; -var _toError = __webpack_require__(/*! ../jsutils/toError.mjs */ "../../../node_modules/graphql/jsutils/toError.mjs"); -var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Given an arbitrary value, presumably thrown while attempting to execute a - * GraphQL operation, produce a new GraphQLError aware of the location in the - * document responsible for the original Error. - */ + /** + * The enum type representing the possible kind values of AST nodes. + * + * @deprecated Please use `Kind`. Will be remove in v17. + */ -function locatedError(rawOriginalError, nodes, path) { - var _nodes; - const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + /***/ + }, - if (isLocatedGraphQLError(originalError)) { - return originalError; - } - return new _GraphQLError.GraphQLError(originalError.message, { - nodes: (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, - source: originalError.source, - positions: originalError.positions, - path, - originalError - }); -} -function isLocatedGraphQLError(error) { - return Array.isArray(error.path); -} + /***/ "../../../node_modules/graphql/language/lexer.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/lexer.mjs ***! + \********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Lexer = void 0; + exports.isPunctuatorTokenKind = isPunctuatorTokenKind; + var _syntaxError = __webpack_require__( + /*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs" + ); + var _ast = __webpack_require__( + /*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _blockString = __webpack_require__( + /*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs" + ); + var _characterClasses = __webpack_require__( + /*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs" + ); + var _tokenKind = __webpack_require__( + /*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs" + ); + /** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ -/***/ }), + class Lexer { + /** + * The previously focused non-ignored token. + */ -/***/ "../../../node_modules/graphql/error/syntaxError.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/error/syntaxError.mjs ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /** + * The currently focused non-ignored token. + */ + /** + * The (1-indexed) line containing the current token. + */ + /** + * The character offset at which the current line begins. + */ + constructor(source) { + const startOfFileToken = new _ast.Token( + _tokenKind.TokenKind.SOF, + 0, + 0, + 0, + 0 + ); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + get [Symbol.toStringTag]() { + return "Lexer"; + } + /** + * Advances the token stream to the next non-ignored token. + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.syntaxError = syntaxError; -var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Produces a GraphQLError representing a syntax error, containing useful - * descriptive information about the syntax error's position in the source. - */ + advance() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ -function syntaxError(source, position, description) { - return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { - source, - positions: [position] - }); -} + lookahead() { + let token = this.token; + if (token.kind !== _tokenKind.TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. -/***/ }), + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. -/***/ "../../../node_modules/graphql/execution/collectFields.mjs": -/*!*****************************************************************!*\ - !*** ../../../node_modules/graphql/execution/collectFields.mjs ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.collectFields = collectFields; -exports.collectSubfields = collectSubfields; -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); -/** - * Given a selectionSet, collects all of the fields and returns them. - * - * CollectFields requires the "runtime type" of an object. For a field that - * returns an Interface or Union type, the "runtime type" will be the actual - * object type returned by that field. - * - * @internal - */ - -function collectFields(schema, fragments, variableValues, runtimeType, selectionSet) { - const fields = new Map(); - collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, new Set()); - return fields; -} -/** - * Given an array of field nodes, collects all of the subfields of the passed - * in fields, and returns them at the end. - * - * CollectSubFields requires the "return type" of an object. For a field that - * returns an Interface or Union type, the "return type" will be the actual - * object type returned by that field. - * - * @internal - */ - -function collectSubfields(schema, fragments, variableValues, returnType, fieldNodes) { - const subFieldNodes = new Map(); - const visitedFragmentNames = new Set(); - for (const node of fieldNodes) { - if (node.selectionSet) { - collectFieldsImpl(schema, fragments, variableValues, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); - } - } - return subFieldNodes; -} -function collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, visitedFragmentNames) { - for (const selection of selectionSet.selections) { - switch (selection.kind) { - case _kinds.Kind.FIELD: - { - if (!shouldIncludeNode(variableValues, selection)) { - continue; - } - const name = getFieldEntryKey(selection); - const fieldList = fields.get(name); - if (fieldList !== undefined) { - fieldList.push(selection); - } else { - fields.set(name, [selection]); - } - break; - } - case _kinds.Kind.INLINE_FRAGMENT: - { - if (!shouldIncludeNode(variableValues, selection) || !doesFragmentConditionMatch(schema, selection, runtimeType)) { - continue; + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === _tokenKind.TokenKind.COMMENT); + } + return token; } - collectFieldsImpl(schema, fragments, variableValues, runtimeType, selection.selectionSet, fields, visitedFragmentNames); - break; } - case _kinds.Kind.FRAGMENT_SPREAD: - { - const fragName = selection.name.value; - if (visitedFragmentNames.has(fragName) || !shouldIncludeNode(variableValues, selection)) { - continue; - } - visitedFragmentNames.add(fragName); - const fragment = fragments[fragName]; - if (!fragment || !doesFragmentConditionMatch(schema, fragment, runtimeType)) { - continue; - } - collectFieldsImpl(schema, fragments, variableValues, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); - break; + /** + * @internal + */ + exports.Lexer = Lexer; + function isPunctuatorTokenKind(kind) { + return ( + kind === _tokenKind.TokenKind.BANG || + kind === _tokenKind.TokenKind.DOLLAR || + kind === _tokenKind.TokenKind.AMP || + kind === _tokenKind.TokenKind.PAREN_L || + kind === _tokenKind.TokenKind.PAREN_R || + kind === _tokenKind.TokenKind.SPREAD || + kind === _tokenKind.TokenKind.COLON || + kind === _tokenKind.TokenKind.EQUALS || + kind === _tokenKind.TokenKind.AT || + kind === _tokenKind.TokenKind.BRACKET_L || + kind === _tokenKind.TokenKind.BRACKET_R || + kind === _tokenKind.TokenKind.BRACE_L || + kind === _tokenKind.TokenKind.PIPE || + kind === _tokenKind.TokenKind.BRACE_R + ); } - } - } -} -/** - * Determines if a field should be included based on the `@include` and `@skip` - * directives, where `@skip` has higher precedence than `@include`. - */ - -function shouldIncludeNode(variableValues, node) { - const skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, variableValues); - if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { - return false; - } - const include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, variableValues); - if ((include === null || include === void 0 ? void 0 : include.if) === false) { - return false; - } - return true; -} -/** - * Determines if a fragment is applicable to the given type. - */ - -function doesFragmentConditionMatch(schema, fragment, type) { - const typeConditionNode = fragment.typeCondition; - if (!typeConditionNode) { - return true; - } - const conditionalType = (0, _typeFromAST.typeFromAST)(schema, typeConditionNode); - if (conditionalType === type) { - return true; - } - if ((0, _definition.isAbstractType)(conditionalType)) { - return schema.isSubType(conditionalType, type); - } - return false; -} -/** - * Implements the logic to compute the key of a given field's entry - */ - -function getFieldEntryKey(node) { - return node.alias ? node.alias.value : node.name.value; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/execution/execute.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/execution/execute.mjs ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.assertValidExecutionArguments = assertValidExecutionArguments; -exports.buildExecutionContext = buildExecutionContext; -exports.buildResolveInfo = buildResolveInfo; -exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; -exports.execute = execute; -exports.executeSync = executeSync; -exports.getFieldDef = getFieldDef; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _isPromise = __webpack_require__(/*! ../jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); -var _memoize = __webpack_require__(/*! ../jsutils/memoize3.mjs */ "../../../node_modules/graphql/jsutils/memoize3.mjs"); -var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); -var _promiseForObject = __webpack_require__(/*! ../jsutils/promiseForObject.mjs */ "../../../node_modules/graphql/jsutils/promiseForObject.mjs"); -var _promiseReduce = __webpack_require__(/*! ../jsutils/promiseReduce.mjs */ "../../../node_modules/graphql/jsutils/promiseReduce.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); -var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); -var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); -var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); -/** - * A memoized collection of relevant subfields with regard to the return - * type. Memoizing ensures the subfields are not repeatedly calculated, which - * saves overhead when resolving lists of values. - */ - -const collectSubfields = (0, _memoize.memoize3)((exeContext, returnType, fieldNodes) => (0, _collectFields.collectSubfields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, returnType, fieldNodes)); -/** - * Terminology - * - * "Definitions" are the generic name for top-level statements in the document. - * Examples of this include: - * 1) Operations (such as a query) - * 2) Fragments - * - * "Operations" are a generic name for requests in the document. - * Examples of this include: - * 1) query, - * 2) mutation - * - * "Selections" are the definitions that can appear legally and at - * single level of the query. These include: - * 1) field references e.g `a` - * 2) fragment "spreads" e.g. `...c` - * 3) inline fragment "spreads" e.g. `...on Type { a }` - */ - -/** - * Data that must be available at all points during query execution. - * - * Namely, schema of the type system that is currently executing, - * and the fragments defined in the query document - */ - -/** - * Implements the "Executing requests" section of the GraphQL specification. - * - * Returns either a synchronous ExecutionResult (if all encountered resolvers - * are synchronous), or a Promise of an ExecutionResult that will eventually be - * resolved and never rejected. - * - * If the arguments to this function do not result in a legal execution context, - * a GraphQLError will be thrown immediately explaining the invalid input. - */ -function execute(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); - const { - schema, - document, - variableValues, - rootValue - } = args; // If arguments are missing or incorrect, throw an error. - - assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, - // a "Response" with only errors is returned. - - const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. - - if (!('schema' in exeContext)) { - return { - errors: exeContext - }; - } // Return a Promise that will eventually resolve to the data described by - // The "Response" section of the GraphQL specification. - // - // If errors are encountered while executing a GraphQL field, only that - // field and its descendants will be omitted, and sibling fields will still - // be executed. An execution which encounters errors will still result in a - // resolved Promise. - // - // Errors from sub-fields of a NonNull type may propagate to the top level, - // at which point we still log the error and null the parent field, which - // in this case is the entire response. - - try { - const { - operation - } = exeContext; - const result = executeOperation(exeContext, operation, rootValue); - if ((0, _isPromise.isPromise)(result)) { - return result.then(data => buildResponse(data, exeContext.errors), error => { - exeContext.errors.push(error); - return buildResponse(null, exeContext.errors); - }); - } - return buildResponse(result, exeContext.errors); - } catch (error) { - exeContext.errors.push(error); - return buildResponse(null, exeContext.errors); - } -} -/** - * Also implements the "Executing requests" section of the GraphQL specification. - * However, it guarantees to complete synchronously (or throw an error) assuming - * that all field resolvers are also synchronous. - */ - -function executeSync(args) { - const result = execute(args); // Assert that the execution was synchronous. - - if ((0, _isPromise.isPromise)(result)) { - throw new Error('GraphQL execution failed to complete synchronously.'); - } - return result; -} -/** - * Given a completed execution context and data, build the `{ errors, data }` - * response defined by the "Response" section of the GraphQL specification. - */ - -function buildResponse(data, errors) { - return errors.length === 0 ? { - data - } : { - errors, - data - }; -} -/** - * Essential assertions before executing to provide developer feedback for - * improper use of the GraphQL library. - * - * @internal - */ - -function assertValidExecutionArguments(schema, document, rawVariableValues) { - document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. - - (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. - - rawVariableValues == null || (0, _isObjectLike.isObjectLike)(rawVariableValues) || (0, _devAssert.devAssert)(false, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); -} -/** - * Constructs a ExecutionContext object from the arguments passed to - * execute, which we will pass throughout the other execution methods. - * - * Throws a GraphQLError if a valid execution context cannot be created. - * - * @internal - */ - -function buildExecutionContext(args) { - var _definition$name, _operation$variableDe; - const { - schema, - document, - rootValue, - contextValue, - variableValues: rawVariableValues, - operationName, - fieldResolver, - typeResolver, - subscribeFieldResolver - } = args; - let operation; - const fragments = Object.create(null); - for (const definition of document.definitions) { - switch (definition.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - if (operationName == null) { - if (operation !== undefined) { - return [new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')]; - } - operation = definition; - } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { - operation = definition; - } - break; - case _kinds.Kind.FRAGMENT_DEFINITION: - fragments[definition.name.value] = definition; - break; - default: // ignore non-executable definitions - } - } - if (!operation) { - if (operationName != null) { - return [new _GraphQLError.GraphQLError(`Unknown operation named "${operationName}".`)]; - } - return [new _GraphQLError.GraphQLError('Must provide an operation.')]; - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ + /** + * A Unicode scalar value is any Unicode code point except surrogate code + * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and + * 0xE000 to 0x10FFFF. + * + * SourceCharacter :: + * - "Any Unicode scalar value" + */ - const variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : []; - const coercedVariableValues = (0, _values.getVariableValues)(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, { - maxErrors: 50 - }); - if (coercedVariableValues.errors) { - return coercedVariableValues.errors; - } - return { - schema, - fragments, - rootValue, - contextValue, - operation, - variableValues: coercedVariableValues.coerced, - fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver, - typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver, - subscribeFieldResolver: subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 ? subscribeFieldResolver : defaultFieldResolver, - errors: [] - }; -} -/** - * Implements the "Executing operations" section of the spec. - */ - -function executeOperation(exeContext, operation, rootValue) { - const rootType = exeContext.schema.getRootType(operation.operation); - if (rootType == null) { - throw new _GraphQLError.GraphQLError(`Schema is not configured to execute ${operation.operation} operation.`, { - nodes: operation - }); - } - const rootFields = (0, _collectFields.collectFields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, rootType, operation.selectionSet); - const path = undefined; - switch (operation.operation) { - case _ast.OperationTypeNode.QUERY: - return executeFields(exeContext, rootType, rootValue, path, rootFields); - case _ast.OperationTypeNode.MUTATION: - return executeFieldsSerially(exeContext, rootType, rootValue, path, rootFields); - case _ast.OperationTypeNode.SUBSCRIPTION: - // TODO: deprecate `subscribe` and move all logic here - // Temporary solution until we finish merging execute and subscribe together - return executeFields(exeContext, rootType, rootValue, path, rootFields); - } -} -/** - * Implements the "Executing selection sets" section of the spec - * for fields that must be executed serially. - */ - -function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { - return (0, _promiseReduce.promiseReduce)(fields.entries(), (results, [responseName, fieldNodes]) => { - const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); - const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); - if (result === undefined) { - return results; - } - if ((0, _isPromise.isPromise)(result)) { - return result.then(resolvedResult => { - results[responseName] = resolvedResult; - return results; - }); - } - results[responseName] = result; - return results; - }, Object.create(null)); -} -/** - * Implements the "Executing selection sets" section of the spec - * for fields that may be executed in parallel. - */ - -function executeFields(exeContext, parentType, sourceValue, path, fields) { - const results = Object.create(null); - let containsPromise = false; - try { - for (const [responseName, fieldNodes] of fields.entries()) { - const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); - const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); - if (result !== undefined) { - results[responseName] = result; - if ((0, _isPromise.isPromise)(result)) { - containsPromise = true; + function isUnicodeScalarValue(code) { + return ( + (code >= 0x0000 && code <= 0xd7ff) || + (code >= 0xe000 && code <= 0x10ffff) + ); } - } - } - } catch (error) { - if (containsPromise) { - // Ensure that any promises returned by other fields are handled, as they may also reject. - return (0, _promiseForObject.promiseForObject)(results).finally(() => { - throw error; - }); - } - throw error; - } // If there are no promises, we can just return the object - - if (!containsPromise) { - return results; - } // Otherwise, results is a map from field name to the result of resolving that - // field, which is possibly a promise. Return a promise that will return this - // same map, but with any promises replaced with the values they resolved to. - - return (0, _promiseForObject.promiseForObject)(results); -} -/** - * Implements the "Executing fields" section of the spec - * In particular, this function figures out the value that the field returns by - * calling its resolve function, then calls completeValue to complete promises, - * serialize scalars, or execute the sub-selection-set for objects. - */ - -function executeField(exeContext, parentType, source, fieldNodes, path) { - var _fieldDef$resolve; - const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); - if (!fieldDef) { - return; - } - const returnType = fieldDef.type; - const resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver; - const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error). - - try { - // Build a JS object of arguments from the field.arguments AST, using the - // variables scope to fulfill any variable references. - // TODO: find a way to memoize, in case this field is within a List type. - const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. - - const contextValue = exeContext.contextValue; - const result = resolveFn(source, args, contextValue, info); - let completed; - if ((0, _isPromise.isPromise)(result)) { - completed = result.then(resolved => completeValue(exeContext, returnType, fieldNodes, info, path, resolved)); - } else { - completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); - } - if ((0, _isPromise.isPromise)(completed)) { - // Note: we don't rely on a `catch` method, but we do expect "thenable" - // to take a second callback for the error case. - return completed.then(undefined, rawError => { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); - return handleFieldError(error, returnType, exeContext); - }); - } - return completed; - } catch (rawError) { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); - return handleFieldError(error, returnType, exeContext); - } -} -/** - * @internal - */ - -function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { - // The resolve function's optional fourth argument is a collection of - // information about the current execution state. - return { - fieldName: fieldDef.name, - fieldNodes, - returnType: fieldDef.type, - parentType, - path, - schema: exeContext.schema, - fragments: exeContext.fragments, - rootValue: exeContext.rootValue, - operation: exeContext.operation, - variableValues: exeContext.variableValues - }; -} -function handleFieldError(error, returnType, exeContext) { - // If the field type is non-nullable, then it is resolved without any - // protection from errors, however it still properly locates the error. - if ((0, _definition.isNonNullType)(returnType)) { - throw error; - } // Otherwise, error protection is applied, logging the error and resolving - // a null value for this field if one is encountered. - - exeContext.errors.push(error); - return null; -} -/** - * Implements the instructions for completeValue as defined in the - * "Value Completion" section of the spec. - * - * If the field type is Non-Null, then this recursively completes the value - * for the inner type. It throws a field error if that completion returns null, - * as per the "Nullability" section of the spec. - * - * If the field type is a List, then this recursively completes the value - * for the inner type on each item in the list. - * - * If the field type is a Scalar or Enum, ensures the completed value is a legal - * value of the type by calling the `serialize` method of GraphQL type - * definition. - * - * If the field is an abstract type, determine the runtime type of the value - * and then complete based on that type - * - * Otherwise, the field type expects a sub-selection set, and will complete the - * value by executing all sub-selections. - */ - -function completeValue(exeContext, returnType, fieldNodes, info, path, result) { - // If result is an Error, throw a located error. - if (result instanceof Error) { - throw result; - } // If field type is NonNull, complete for inner type, and throw field error - // if result is null. - - if ((0, _definition.isNonNullType)(returnType)) { - const completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); - if (completed === null) { - throw new Error(`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`); - } - return completed; - } // If result value is null or undefined then return null. - - if (result == null) { - return null; - } // If field type is List, complete each item in the list with the inner type - - if ((0, _definition.isListType)(returnType)) { - return completeListValue(exeContext, returnType, fieldNodes, info, path, result); - } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, - // returning null if serialization is not possible. - - if ((0, _definition.isLeafType)(returnType)) { - return completeLeafValue(returnType, result); - } // If field type is an abstract type, Interface or Union, determine the - // runtime Object type and complete for that type. - - if ((0, _definition.isAbstractType)(returnType)) { - return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); - } // If field type is Object, execute and complete all sub-selections. - - if ((0, _definition.isObjectType)(returnType)) { - return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); - } - /* c8 ignore next 6 */ - // Not reachable, all possible output types have been considered. - - false || (0, _invariant.invariant)(false, 'Cannot complete value of unexpected output type: ' + (0, _inspect.inspect)(returnType)); -} -/** - * Complete a list value by completing each item in the list with the - * inner type - */ - -function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { - if (!(0, _isIterableObject.isIterableObject)(result)) { - throw new _GraphQLError.GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`); - } // This is specified as a simple map, however we're optimizing the path - // where the list contains no Promises by avoiding creating another Promise. - - const itemType = returnType.ofType; - let containsPromise = false; - const completedResults = Array.from(result, (item, index) => { - // No need to modify the info object containing the path, - // since from here on it is not ever accessed by resolver functions. - const itemPath = (0, _Path.addPath)(path, index, undefined); - try { - let completedItem; - if ((0, _isPromise.isPromise)(item)) { - completedItem = item.then(resolved => completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved)); - } else { - completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item); - } - if ((0, _isPromise.isPromise)(completedItem)) { - containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" - // to take a second callback for the error case. + /** + * The GraphQL specification defines source text as a sequence of unicode scalar + * values (which Unicode defines to exclude surrogate code points). However + * JavaScript defines strings as a sequence of UTF-16 code units which may + * include surrogates. A surrogate pair is a valid source character as it + * encodes a supplementary code point (above U+FFFF), but unpaired surrogate + * code points are not valid source characters. + */ - return completedItem.then(undefined, rawError => { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); - return handleFieldError(error, itemType, exeContext); - }); - } - return completedItem; - } catch (rawError) { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); - return handleFieldError(error, itemType, exeContext); - } - }); - return containsPromise ? Promise.all(completedResults) : completedResults; -} -/** - * Complete a Scalar or Enum by serializing to a valid value, returning - * null if serialization is not possible. - */ - -function completeLeafValue(returnType, result) { - const serializedResult = returnType.serialize(result); - if (serializedResult == null) { - throw new Error(`Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, _inspect.inspect)(result)})\` to ` + `return non-nullable value, returned: ${(0, _inspect.inspect)(serializedResult)}`); - } - return serializedResult; -} -/** - * Complete a value of an abstract type by determining the runtime object type - * of that value, then complete the value for that type. - */ - -function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { - var _returnType$resolveTy; - const resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver; - const contextValue = exeContext.contextValue; - const runtimeType = resolveTypeFn(result, contextValue, info, returnType); - if ((0, _isPromise.isPromise)(runtimeType)) { - return runtimeType.then(resolvedRuntimeType => completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result)); - } - return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); -} -function ensureValidRuntimeType(runtimeTypeName, exeContext, returnType, fieldNodes, info, result) { - if (runtimeTypeName == null) { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, fieldNodes); - } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` - // TODO: remove in 17.0.0 release - - if ((0, _definition.isObjectType)(runtimeTypeName)) { - throw new _GraphQLError.GraphQLError('Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.'); - } - if (typeof runtimeTypeName !== 'string') { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + `value ${(0, _inspect.inspect)(result)}, received "${(0, _inspect.inspect)(runtimeTypeName)}".`); - } - const runtimeType = exeContext.schema.getType(runtimeTypeName); - if (runtimeType == null) { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, { - nodes: fieldNodes - }); - } - if (!(0, _definition.isObjectType)(runtimeType)) { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, { - nodes: fieldNodes - }); - } - if (!exeContext.schema.isSubType(returnType, runtimeType)) { - throw new _GraphQLError.GraphQLError(`Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, { - nodes: fieldNodes - }); - } - return runtimeType; -} -/** - * Complete an Object value by executing all sub-selections. - */ - -function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { - // Collect sub-fields to execute to complete this value. - const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the - // current result. If isTypeOf returns false, then raise an error rather - // than continuing execution. - - if (returnType.isTypeOf) { - const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); - if ((0, _isPromise.isPromise)(isTypeOf)) { - return isTypeOf.then(resolvedIsTypeOf => { - if (!resolvedIsTypeOf) { - throw invalidReturnTypeError(returnType, result, fieldNodes); - } - return executeFields(exeContext, returnType, result, path, subFieldNodes); - }); - } - if (!isTypeOf) { - throw invalidReturnTypeError(returnType, result, fieldNodes); - } - } - return executeFields(exeContext, returnType, result, path, subFieldNodes); -} -function invalidReturnTypeError(returnType, result, fieldNodes) { - return new _GraphQLError.GraphQLError(`Expected value of type "${returnType.name}" but got: ${(0, _inspect.inspect)(result)}.`, { - nodes: fieldNodes - }); -} -/** - * If a resolveType function is not given, then a default resolve behavior is - * used which attempts two strategies: - * - * First, See if the provided value has a `__typename` field defined, if so, use - * that value as name of the resolved type. - * - * Otherwise, test each possible type for the abstract type by calling - * isTypeOf for the object being coerced, returning the first type that matches. - */ - -const defaultTypeResolver = function (value, contextValue, info, abstractType) { - // First, look for `__typename`. - if ((0, _isObjectLike.isObjectLike)(value) && typeof value.__typename === 'string') { - return value.__typename; - } // Otherwise, test each possible type. - - const possibleTypes = info.schema.getPossibleTypes(abstractType); - const promisedIsTypeOfResults = []; - for (let i = 0; i < possibleTypes.length; i++) { - const type = possibleTypes[i]; - if (type.isTypeOf) { - const isTypeOfResult = type.isTypeOf(value, contextValue, info); - if ((0, _isPromise.isPromise)(isTypeOfResult)) { - promisedIsTypeOfResults[i] = isTypeOfResult; - } else if (isTypeOfResult) { - return type.name; - } - } - } - if (promisedIsTypeOfResults.length) { - return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { - for (let i = 0; i < isTypeOfResults.length; i++) { - if (isTypeOfResults[i]) { - return possibleTypes[i].name; + function isSupplementaryCodePoint(body, location) { + return ( + isLeadingSurrogate(body.charCodeAt(location)) && + isTrailingSurrogate(body.charCodeAt(location + 1)) + ); } - } - }); - } -}; -/** - * If a resolve function is not given, then a default resolve behavior is used - * which takes the property of the source object of the same name as the field - * and returns it as the result, or if it's a function, returns the result - * of calling that function while passing along args and context value. - */ -exports.defaultTypeResolver = defaultTypeResolver; -const defaultFieldResolver = function (source, args, contextValue, info) { - // ensure source is a value for which property access is acceptable. - if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { - const property = source[info.fieldName]; - if (typeof property === 'function') { - return source[info.fieldName](args, contextValue, info); - } - return property; - } -}; -/** - * This method looks up the field on the given type definition. - * It has special casing for the three introspection fields, - * __schema, __type and __typename. __typename is special because - * it can always be queried as a field, even in situations where no - * other fields are allowed, like on a Union. __schema and __type - * could get automatically added to the query type, but that would - * require mutating type definitions, which would cause issues. - * - * @internal - */ -exports.defaultFieldResolver = defaultFieldResolver; -function getFieldDef(schema, parentType, fieldNode) { - const fieldName = fieldNode.name.value; - if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.SchemaMetaFieldDef; - } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.TypeMetaFieldDef; - } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { - return _introspection.TypeNameMetaFieldDef; - } - return parentType.getFields()[fieldName]; -} - -/***/ }), + function isLeadingSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; + } + function isTrailingSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; + } + /** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + */ -/***/ "../../../node_modules/graphql/execution/index.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/execution/index.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); + if (code === undefined) { + return _tokenKind.TokenKind.EOF; + } else if (code >= 0x0020 && code <= 0x007e) { + // Printable ASCII + const char = String.fromCodePoint(code); + return char === '"' ? "'\"'" : `"${char}"`; + } // Unicode code point + return "U+" + code.toString(16).toUpperCase().padStart(4, "0"); + } + /** + * Create a token with line and column location information. + */ + function createToken(lexer, kind, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new _ast.Token(kind, start, end, line, col, value); + } + /** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createSourceEventStream", ({ - enumerable: true, - get: function () { - return _subscribe.createSourceEventStream; - } -})); -Object.defineProperty(exports, "defaultFieldResolver", ({ - enumerable: true, - get: function () { - return _execute.defaultFieldResolver; - } -})); -Object.defineProperty(exports, "defaultTypeResolver", ({ - enumerable: true, - get: function () { - return _execute.defaultTypeResolver; - } -})); -Object.defineProperty(exports, "execute", ({ - enumerable: true, - get: function () { - return _execute.execute; - } -})); -Object.defineProperty(exports, "executeSync", ({ - enumerable: true, - get: function () { - return _execute.executeSync; - } -})); -Object.defineProperty(exports, "getArgumentValues", ({ - enumerable: true, - get: function () { - return _values.getArgumentValues; - } -})); -Object.defineProperty(exports, "getDirectiveValues", ({ - enumerable: true, - get: function () { - return _values.getDirectiveValues; - } -})); -Object.defineProperty(exports, "getVariableValues", ({ - enumerable: true, - get: function () { - return _values.getVariableValues; - } -})); -Object.defineProperty(exports, "responsePathAsArray", ({ - enumerable: true, - get: function () { - return _Path.pathToArray; - } -})); -Object.defineProperty(exports, "subscribe", ({ - enumerable: true, - get: function () { - return _subscribe.subscribe; - } -})); -var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); -var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); -var _subscribe = __webpack_require__(/*! ./subscribe.mjs */ "../../../node_modules/graphql/execution/subscribe.mjs"); -var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + while (position < bodyLength) { + const code = body.charCodeAt(position); // SourceCharacter + + switch (code) { + // Ignored :: + // - UnicodeBOM + // - Whitespace + // - LineTerminator + // - Comment + // - Comma + // + // UnicodeBOM :: "Byte Order Mark (U+FEFF)" + // + // Whitespace :: + // - "Horizontal Tab (U+0009)" + // - "Space (U+0020)" + // + // Comma :: , + case 0xfeff: // + + case 0x0009: // \t + + case 0x0020: // + + case 0x002c: + // , + ++position; + continue; + // LineTerminator :: + // - "New Line (U+000A)" + // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] + // - "Carriage Return (U+000D)" "New Line (U+000A)" + + case 0x000a: + // \n + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; + case 0x000d: + // \r + if (body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + continue; + // Comment + + case 0x0023: + // # + return readComment(lexer, position); + // Token :: + // - Punctuator + // - Name + // - IntValue + // - FloatValue + // - StringValue + // + // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } + + case 0x0021: + // ! + return createToken( + lexer, + _tokenKind.TokenKind.BANG, + position, + position + 1 + ); + case 0x0024: + // $ + return createToken( + lexer, + _tokenKind.TokenKind.DOLLAR, + position, + position + 1 + ); + case 0x0026: + // & + return createToken( + lexer, + _tokenKind.TokenKind.AMP, + position, + position + 1 + ); + case 0x0028: + // ( + return createToken( + lexer, + _tokenKind.TokenKind.PAREN_L, + position, + position + 1 + ); + case 0x0029: + // ) + return createToken( + lexer, + _tokenKind.TokenKind.PAREN_R, + position, + position + 1 + ); + case 0x002e: + // . + if ( + body.charCodeAt(position + 1) === 0x002e && + body.charCodeAt(position + 2) === 0x002e + ) { + return createToken( + lexer, + _tokenKind.TokenKind.SPREAD, + position, + position + 3 + ); + } + break; + case 0x003a: + // : + return createToken( + lexer, + _tokenKind.TokenKind.COLON, + position, + position + 1 + ); + case 0x003d: + // = + return createToken( + lexer, + _tokenKind.TokenKind.EQUALS, + position, + position + 1 + ); + case 0x0040: + // @ + return createToken( + lexer, + _tokenKind.TokenKind.AT, + position, + position + 1 + ); + case 0x005b: + // [ + return createToken( + lexer, + _tokenKind.TokenKind.BRACKET_L, + position, + position + 1 + ); + case 0x005d: + // ] + return createToken( + lexer, + _tokenKind.TokenKind.BRACKET_R, + position, + position + 1 + ); + case 0x007b: + // { + return createToken( + lexer, + _tokenKind.TokenKind.BRACE_L, + position, + position + 1 + ); + case 0x007c: + // | + return createToken( + lexer, + _tokenKind.TokenKind.PIPE, + position, + position + 1 + ); + case 0x007d: + // } + return createToken( + lexer, + _tokenKind.TokenKind.BRACE_R, + position, + position + 1 + ); + // StringValue + + case 0x0022: + // " + if ( + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + return readBlockString(lexer, position); + } + return readString(lexer, position); + } // IntValue | FloatValue (Digit | -) -/***/ }), + if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { + return readNumber(lexer, position, code); + } // Name -/***/ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs": -/*!********************************************************************!*\ - !*** ../../../node_modules/graphql/execution/mapAsyncIterator.mjs ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.mapAsyncIterator = mapAsyncIterator; -/** - * Given an AsyncIterable and a callback function, return an AsyncIterator - * which produces values mapped via calling the callback function. - */ -function mapAsyncIterator(iterable, callback) { - const iterator = iterable[Symbol.asyncIterator](); - async function mapResult(result) { - if (result.done) { - return result; - } - try { - return { - value: await callback(result.value), - done: false - }; - } catch (error) { - /* c8 ignore start */ - // FIXME: add test case - if (typeof iterator.return === 'function') { - try { - await iterator.return(); - } catch (_e) { - /* ignore error */ + if ((0, _characterClasses.isNameStart)(code)) { + return readName(lexer, position); + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + code === 0x0027 + ? "Unexpected single quote character ('), did you mean to use a double quote (\")?" + : isUnicodeScalarValue(code) || + isSupplementaryCodePoint(body, position) + ? `Unexpected character: ${printCodePointAt(lexer, position)}.` + : `Invalid character: ${printCodePointAt(lexer, position)}.` + ); + } + return createToken( + lexer, + _tokenKind.TokenKind.EOF, + bodyLength, + bodyLength + ); } - } - throw error; - /* c8 ignore stop */ - } - } - return { - async next() { - return mapResult(await iterator.next()); - }, - async return() { - // If iterator.return() does not exist, then type R must be undefined. - return typeof iterator.return === 'function' ? mapResult(await iterator.return()) : { - value: undefined, - done: true - }; - }, - async throw(error) { - if (typeof iterator.throw === 'function') { - return mapResult(await iterator.throw(error)); - } - throw error; - }, - [Symbol.asyncIterator]() { - return this; - } - }; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/execution/subscribe.mjs": -/*!*************************************************************!*\ - !*** ../../../node_modules/graphql/execution/subscribe.mjs ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createSourceEventStream = createSourceEventStream; -exports.subscribe = subscribe; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _isAsyncIterable = __webpack_require__(/*! ../jsutils/isAsyncIterable.mjs */ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs"); -var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); -var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); -var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); -var _mapAsyncIterator = __webpack_require__(/*! ./mapAsyncIterator.mjs */ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs"); -var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); -/** - * Implements the "Subscribe" algorithm described in the GraphQL specification. - * - * Returns a Promise which resolves to either an AsyncIterator (if successful) - * or an ExecutionResult (error). The promise will be rejected if the schema or - * other arguments to this function are invalid, or if the resolved event stream - * is not an async iterable. - * - * If the client-provided arguments to this function do not result in a - * compliant subscription, a GraphQL Response (ExecutionResult) with - * descriptive errors and no data will be returned. - * - * If the source stream could not be created due to faulty subscription - * resolver logic or underlying systems, the promise will resolve to a single - * ExecutionResult containing `errors` and no `data`. - * - * If the operation succeeded, the promise resolves to an AsyncIterator, which - * yields a stream of ExecutionResults representing the response stream. - * - * Accepts either an object with named arguments, or individual arguments. - */ - -async function subscribe(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); - const resultOrStream = await createSourceEventStream(args); - if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { - return resultOrStream; - } // For each payload yielded from a subscription, map it over the normal - // GraphQL `execute` function, with `payload` as the rootValue. - // This implements the "MapSourceToResponseEvent" algorithm described in - // the GraphQL specification. The `execute` function provides the - // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the - // "ExecuteQuery" algorithm, for which `execute` is also used. - - const mapSourceToResponse = payload => (0, _execute.execute)({ - ...args, - rootValue: payload - }); // Map every source value to a ExecutionResult value as described above. - - return (0, _mapAsyncIterator.mapAsyncIterator)(resultOrStream, mapSourceToResponse); -} -function toNormalizedArgs(args) { - const firstArg = args[0]; - if (firstArg && 'document' in firstArg) { - return firstArg; - } - return { - schema: firstArg, - // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 - document: args[1], - rootValue: args[2], - contextValue: args[3], - variableValues: args[4], - operationName: args[5], - subscribeFieldResolver: args[6] - }; -} -/** - * Implements the "CreateSourceEventStream" algorithm described in the - * GraphQL specification, resolving the subscription source event stream. - * - * Returns a Promise which resolves to either an AsyncIterable (if successful) - * or an ExecutionResult (error). The promise will be rejected if the schema or - * other arguments to this function are invalid, or if the resolved event stream - * is not an async iterable. - * - * If the client-provided arguments to this function do not result in a - * compliant subscription, a GraphQL Response (ExecutionResult) with - * descriptive errors and no data will be returned. - * - * If the the source stream could not be created due to faulty subscription - * resolver logic or underlying systems, the promise will resolve to a single - * ExecutionResult containing `errors` and no `data`. - * - * If the operation succeeded, the promise resolves to the AsyncIterable for the - * event stream returned by the resolver. - * - * A Source Event Stream represents a sequence of events, each of which triggers - * a GraphQL execution for that event. - * - * This may be useful when hosting the stateful subscription service in a - * different process or machine than the stateless GraphQL execution engine, - * or otherwise separating these two steps. For more on this, see the - * "Supporting Subscriptions at Scale" information in the GraphQL specification. - */ - -async function createSourceEventStream(...rawArgs) { - const args = toNormalizedArgs(rawArgs); - const { - schema, - document, - variableValues - } = args; // If arguments are missing or incorrectly typed, this is an internal - // developer mistake which should throw an early error. - - (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, - // a "Response" with only errors is returned. - - const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. - - if (!('schema' in exeContext)) { - return { - errors: exeContext - }; - } - try { - const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. + /** + * Reads a comment token from the source file. + * + * ``` + * Comment :: # CommentChar* [lookahead != CommentChar] + * + * CommentChar :: SourceCharacter but not LineTerminator + * ``` + */ - if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { - throw new Error('Subscription field must return Async Iterable. ' + `Received: ${(0, _inspect.inspect)(eventStream)}.`); - } - return eventStream; - } catch (error) { - // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. - // Otherwise treat the error as a system-class error and re-throw it. - if (error instanceof _GraphQLError.GraphQLError) { - return { - errors: [error] - }; - } - throw error; - } -} -async function executeSubscription(exeContext) { - const { - schema, - fragments, - operation, - variableValues, - rootValue - } = exeContext; - const rootType = schema.getSubscriptionType(); - if (rootType == null) { - throw new _GraphQLError.GraphQLError('Schema is not configured to execute subscription operation.', { - nodes: operation - }); - } - const rootFields = (0, _collectFields.collectFields)(schema, fragments, variableValues, rootType, operation.selectionSet); - const [responseName, fieldNodes] = [...rootFields.entries()][0]; - const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); - if (!fieldDef) { - const fieldName = fieldNodes[0].name.value; - throw new _GraphQLError.GraphQLError(`The subscription field "${fieldName}" is not defined.`, { - nodes: fieldNodes - }); - } - const path = (0, _Path.addPath)(undefined, responseName, rootType.name); - const info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, rootType, path); - try { - var _fieldDef$subscribe; - - // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. - // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. - // Build a JS object of arguments from the field.arguments AST, using the - // variables scope to fulfill any variable references. - const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. - - const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an - // AsyncIterable yielding raw payloads. - - const resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.subscribeFieldResolver; - const eventStream = await resolveFn(rootValue, args, contextValue, info); - if (eventStream instanceof Error) { - throw eventStream; - } - return eventStream; - } catch (error) { - throw (0, _locatedError.locatedError)(error, fieldNodes, (0, _Path.pathToArray)(path)); - } -} + function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); // LineTerminator (\n | \r) -/***/ }), + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter -/***/ "../../../node_modules/graphql/execution/values.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/execution/values.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getArgumentValues = getArgumentValues; -exports.getDirectiveValues = getDirectiveValues; -exports.getVariableValues = getVariableValues; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _coerceInputValue = __webpack_require__(/*! ../utilities/coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); -var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -var _valueFromAST = __webpack_require__(/*! ../utilities/valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); -/** - * Prepares an object map of variableValues of the correct type based on the - * provided variable definitions and arbitrary input. If the input cannot be - * parsed to match the variable definitions, a GraphQLError will be thrown. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ -function getVariableValues(schema, varDefNodes, inputs, options) { - const errors = []; - const maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors; - try { - const coerced = coerceVariableValues(schema, varDefNodes, inputs, error => { - if (maxErrors != null && errors.length >= maxErrors) { - throw new _GraphQLError.GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.'); - } - errors.push(error); - }); - if (errors.length === 0) { - return { - coerced - }; - } - } catch (error) { - errors.push(error); - } - return { - errors - }; -} -function coerceVariableValues(schema, varDefNodes, inputs, onError) { - const coercedValues = {}; - for (const varDefNode of varDefNodes) { - const varName = varDefNode.variable.name.value; - const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); - if (!(0, _definition.isInputType)(varType)) { - // Must use input types for variables. This should be caught during - // validation, however is checked again here for safety. - const varTypeStr = (0, _printer.print)(varDefNode.type); - onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, { - nodes: varDefNode.type - })); - continue; - } - if (!hasOwnProperty(inputs, varName)) { - if (varDefNode.defaultValue) { - coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); - } else if ((0, _definition.isNonNullType)(varType)) { - const varTypeStr = (0, _inspect.inspect)(varType); - onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, { - nodes: varDefNode - })); - } - continue; - } - const value = inputs[varName]; - if (value === null && (0, _definition.isNonNullType)(varType)) { - const varTypeStr = (0, _inspect.inspect)(varType); - onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, { - nodes: varDefNode - })); - continue; - } - coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)(value, varType, (path, invalidValue, error) => { - let prefix = `Variable "$${varName}" got invalid value ` + (0, _inspect.inspect)(invalidValue); - if (path.length > 0) { - prefix += ` at "${varName}${(0, _printPathArray.printPathArray)(path)}"`; - } - onError(new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { - nodes: varDefNode, - originalError: error - })); - }); - } - return coercedValues; -} -/** - * Prepares an object map of argument values given a list of argument - * definitions and list of argument AST nodes. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ - -function getArgumentValues(def, node, variableValues) { - var _node$arguments; - const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : []; - const argNodeMap = (0, _keyMap.keyMap)(argumentNodes, arg => arg.name.value); - for (const argDef of def.args) { - const name = argDef.name; - const argType = argDef.type; - const argumentNode = argNodeMap[name]; - if (!argumentNode) { - if (argDef.defaultValue !== undefined) { - coercedValues[name] = argDef.defaultValue; - } else if ((0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + 'was not provided.', { - nodes: node - }); - } - continue; - } - const valueNode = argumentNode.value; - let isNull = valueNode.kind === _kinds.Kind.NULL; - if (valueNode.kind === _kinds.Kind.VARIABLE) { - const variableName = valueNode.name.value; - if (variableValues == null || !hasOwnProperty(variableValues, variableName)) { - if (argDef.defaultValue !== undefined) { - coercedValues[name] = argDef.defaultValue; - } else if ((0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + `was provided the variable "$${variableName}" which was not provided a runtime value.`, { - nodes: valueNode - }); - } - continue; - } - isNull = variableValues[variableName] == null; - } - if (isNull && (0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError(`Argument "${name}" of non-null type "${(0, _inspect.inspect)(argType)}" ` + 'must not be null.', { - nodes: valueNode - }); - } - const coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); - if (coercedValue === undefined) { - // Note: ValuesOfCorrectTypeRule validation should catch this before - // execution. This is a runtime check to ensure execution does not - // continue with an invalid argument value. - throw new _GraphQLError.GraphQLError(`Argument "${name}" has invalid value ${(0, _printer.print)(valueNode)}.`, { - nodes: valueNode - }); - } - coercedValues[name] = coercedValue; - } - return coercedValues; -} -/** - * Prepares an object map of argument values given a directive definition - * and a AST node which may contain directives. Optionally also accepts a map - * of variable values. - * - * If the directive does not exist on the node, returns undefined. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ - -function getDirectiveValues(directiveDef, node, variableValues) { - var _node$directives; - const directiveNode = (_node$directives = node.directives) === null || _node$directives === void 0 ? void 0 : _node$directives.find(directive => directive.name.value === directiveDef.name); - if (directiveNode) { - return getArgumentValues(directiveDef, directiveNode, variableValues); - } -} -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; + } + } + return createToken( + lexer, + _tokenKind.TokenKind.COMMENT, + start, + position, + body.slice(start + 1, position) + ); + } + /** + * Reads a number token from the source file, either a FloatValue or an IntValue + * depending on whether a FractionalPart or ExponentPart is encountered. + * + * ``` + * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] + * + * IntegerPart :: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit Digit* + * + * NegativeSign :: - + * + * NonZeroDigit :: Digit but not `0` + * + * FloatValue :: + * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * + * FractionalPart :: . Digit+ + * + * ExponentPart :: ExponentIndicator Sign? Digit+ + * + * ExponentIndicator :: one of `e` `E` + * + * Sign :: one of + - + * ``` + */ -/***/ }), + function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; // NegativeSign (-) + + if (code === 0x002d) { + code = body.charCodeAt(++position); + } // Zero (0) + + if (code === 0x0030) { + code = body.charCodeAt(++position); + if ((0, _characterClasses.isDigit)(code)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid number, unexpected digit after 0: ${printCodePointAt( + lexer, + position + )}.` + ); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Full stop (.) + + if (code === 0x002e) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // E e + + if (code === 0x0045 || code === 0x0065) { + isFloat = true; + code = body.charCodeAt(++position); // + - + + if (code === 0x002b || code === 0x002d) { + code = body.charCodeAt(++position); + } + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + position + )}.` + ); + } + return createToken( + lexer, + isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, + start, + position, + body.slice(start, position) + ); + } + /** + * Returns the new position in the source after reading one or more digits. + */ -/***/ "../../../node_modules/graphql/graphql.mjs": -/*!*************************************************!*\ - !*** ../../../node_modules/graphql/graphql.mjs ***! - \*************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.graphql = graphql; -exports.graphqlSync = graphqlSync; -var _devAssert = __webpack_require__(/*! ./jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _isPromise = __webpack_require__(/*! ./jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); -var _parser = __webpack_require__(/*! ./language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); -var _validate = __webpack_require__(/*! ./type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); -var _validate2 = __webpack_require__(/*! ./validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); -var _execute = __webpack_require__(/*! ./execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); -/** - * This is the primary entry point function for fulfilling GraphQL operations - * by parsing, validating, and executing a GraphQL document along side a - * GraphQL schema. - * - * More sophisticated GraphQL servers, such as those which persist queries, - * may wish to separate the validation and execution phases to a static time - * tooling step, and a server runtime step. - * - * Accepts either an object with named arguments, or individual arguments: - * - * schema: - * The GraphQL type system to use when validating and executing a query. - * source: - * A GraphQL language formatted string representing the requested operation. - * rootValue: - * The value provided as the first argument to resolver functions on the top - * level type (e.g. the query object type). - * contextValue: - * The context value is provided as an argument to resolver functions after - * field arguments. It is used to pass shared information useful at any point - * during executing this query, for example the currently logged in user and - * connections to databases or other services. - * variableValues: - * A mapping of variable name to runtime value to use for all variables - * defined in the requestString. - * operationName: - * The name of the operation to use if requestString contains multiple - * possible operations. Can be omitted if requestString contains only - * one operation. - * fieldResolver: - * A resolver function to use when one is not provided by the schema. - * If not provided, the default field resolver is used (which looks for a - * value or method on the source value with the field's name). - * typeResolver: - * A type resolver function to use when none is provided by the schema. - * If not provided, the default type resolver is used (which looks for a - * `__typename` field or alternatively calls the `isTypeOf` method). - */ - -function graphql(args) { - // Always return a Promise for a consistent API. - return new Promise(resolve => resolve(graphqlImpl(args))); -} -/** - * The graphqlSync function also fulfills GraphQL operations by parsing, - * validating, and executing a GraphQL document along side a GraphQL schema. - * However, it guarantees to complete synchronously (or throw an error) assuming - * that all field resolvers are also synchronous. - */ - -function graphqlSync(args) { - const result = graphqlImpl(args); // Assert that the execution was synchronous. - - if ((0, _isPromise.isPromise)(result)) { - throw new Error('GraphQL execution failed to complete synchronously.'); - } - return result; -} -function graphqlImpl(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); - const { - schema, - source, - rootValue, - contextValue, - variableValues, - operationName, - fieldResolver, - typeResolver - } = args; // Validate Schema - - const schemaValidationErrors = (0, _validate.validateSchema)(schema); - if (schemaValidationErrors.length > 0) { - return { - errors: schemaValidationErrors - }; - } // Parse - - let document; - try { - document = (0, _parser.parse)(source); - } catch (syntaxError) { - return { - errors: [syntaxError] - }; - } // Validate + function readDigits(lexer, start, firstCode) { + if (!(0, _characterClasses.isDigit)(firstCode)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + start, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + start + )}.` + ); + } + const body = lexer.source.body; + let position = start + 1; // +1 to skip first firstCode - const validationErrors = (0, _validate2.validate)(schema, document); - if (validationErrors.length > 0) { - return { - errors: validationErrors - }; - } // Execute - - return (0, _execute.execute)({ - schema, - document, - rootValue, - contextValue, - variableValues, - operationName, - fieldResolver, - typeResolver - }); -} + while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { + ++position; + } + return position; + } + /** + * Reads a single-quote string token from the source file. + * + * ``` + * StringValue :: + * - `""` [lookahead != `"`] + * - `"` StringCharacter+ `"` + * + * StringCharacter :: + * - SourceCharacter but not `"` or `\` or LineTerminator + * - `\u` EscapedUnicode + * - `\` EscapedCharacter + * + * EscapedUnicode :: + * - `{` HexDigit+ `}` + * - HexDigit HexDigit HexDigit HexDigit + * + * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` + * ``` + */ -/***/ }), + function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ""; + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Quote (") + + if (code === 0x0022) { + value += body.slice(chunkStart, position); + return createToken( + lexer, + _tokenKind.TokenKind.STRING, + start, + position + 1, + value + ); + } // Escape Sequence (\) + + if (code === 0x005c) { + value += body.slice(chunkStart, position); + const escape = + body.charCodeAt(position + 1) === 0x0075 // u + ? body.charCodeAt(position + 2) === 0x007b // { + ? readEscapedUnicodeVariableWidth(lexer, position) + : readEscapedUnicodeFixedWidth(lexer, position) + : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } // LineTerminator (\n | \r) -/***/ "../../../node_modules/graphql/index.mjs": -/*!***********************************************!*\ - !*** ../../../node_modules/graphql/index.mjs ***! - \***********************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position + )}.` + ); + } + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + "Unterminated string." + ); + } // The string value and lexed size of an escape sequence. + function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; // Cannot be larger than 12 chars (\u{00000000}). -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "BREAK", ({ - enumerable: true, - get: function () { - return _index2.BREAK; - } -})); -Object.defineProperty(exports, "BreakingChangeType", ({ - enumerable: true, - get: function () { - return _index6.BreakingChangeType; - } -})); -Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ - enumerable: true, - get: function () { - return _index.DEFAULT_DEPRECATION_REASON; - } -})); -Object.defineProperty(exports, "DangerousChangeType", ({ - enumerable: true, - get: function () { - return _index6.DangerousChangeType; - } -})); -Object.defineProperty(exports, "DirectiveLocation", ({ - enumerable: true, - get: function () { - return _index2.DirectiveLocation; - } -})); -Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ - enumerable: true, - get: function () { - return _index4.ExecutableDefinitionsRule; - } -})); -Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _index4.FieldsOnCorrectTypeRule; - } -})); -Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ - enumerable: true, - get: function () { - return _index4.FragmentsOnCompositeTypesRule; - } -})); -Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ - enumerable: true, - get: function () { - return _index.GRAPHQL_MAX_INT; - } -})); -Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ - enumerable: true, - get: function () { - return _index.GRAPHQL_MIN_INT; - } -})); -Object.defineProperty(exports, "GraphQLBoolean", ({ - enumerable: true, - get: function () { - return _index.GraphQLBoolean; - } -})); -Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLDeprecatedDirective; - } -})); -Object.defineProperty(exports, "GraphQLDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLDirective; - } -})); -Object.defineProperty(exports, "GraphQLEnumType", ({ - enumerable: true, - get: function () { - return _index.GraphQLEnumType; - } -})); -Object.defineProperty(exports, "GraphQLError", ({ - enumerable: true, - get: function () { - return _index5.GraphQLError; - } -})); -Object.defineProperty(exports, "GraphQLFloat", ({ - enumerable: true, - get: function () { - return _index.GraphQLFloat; - } -})); -Object.defineProperty(exports, "GraphQLID", ({ - enumerable: true, - get: function () { - return _index.GraphQLID; - } -})); -Object.defineProperty(exports, "GraphQLIncludeDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLIncludeDirective; - } -})); -Object.defineProperty(exports, "GraphQLInputObjectType", ({ - enumerable: true, - get: function () { - return _index.GraphQLInputObjectType; - } -})); -Object.defineProperty(exports, "GraphQLInt", ({ - enumerable: true, - get: function () { - return _index.GraphQLInt; - } -})); -Object.defineProperty(exports, "GraphQLInterfaceType", ({ - enumerable: true, - get: function () { - return _index.GraphQLInterfaceType; - } -})); -Object.defineProperty(exports, "GraphQLList", ({ - enumerable: true, - get: function () { - return _index.GraphQLList; - } -})); -Object.defineProperty(exports, "GraphQLNonNull", ({ - enumerable: true, - get: function () { - return _index.GraphQLNonNull; - } -})); -Object.defineProperty(exports, "GraphQLObjectType", ({ - enumerable: true, - get: function () { - return _index.GraphQLObjectType; - } -})); -Object.defineProperty(exports, "GraphQLScalarType", ({ - enumerable: true, - get: function () { - return _index.GraphQLScalarType; - } -})); -Object.defineProperty(exports, "GraphQLSchema", ({ - enumerable: true, - get: function () { - return _index.GraphQLSchema; - } -})); -Object.defineProperty(exports, "GraphQLSkipDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLSkipDirective; - } -})); -Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLSpecifiedByDirective; - } -})); -Object.defineProperty(exports, "GraphQLString", ({ - enumerable: true, - get: function () { - return _index.GraphQLString; - } -})); -Object.defineProperty(exports, "GraphQLUnionType", ({ - enumerable: true, - get: function () { - return _index.GraphQLUnionType; - } -})); -Object.defineProperty(exports, "Kind", ({ - enumerable: true, - get: function () { - return _index2.Kind; - } -})); -Object.defineProperty(exports, "KnownArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownArgumentNamesRule; - } -})); -Object.defineProperty(exports, "KnownDirectivesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownDirectivesRule; - } -})); -Object.defineProperty(exports, "KnownFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownFragmentNamesRule; - } -})); -Object.defineProperty(exports, "KnownTypeNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownTypeNamesRule; - } -})); -Object.defineProperty(exports, "Lexer", ({ - enumerable: true, - get: function () { - return _index2.Lexer; - } -})); -Object.defineProperty(exports, "Location", ({ - enumerable: true, - get: function () { - return _index2.Location; - } -})); -Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ - enumerable: true, - get: function () { - return _index4.LoneAnonymousOperationRule; - } -})); -Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ - enumerable: true, - get: function () { - return _index4.LoneSchemaDefinitionRule; - } -})); -Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ - enumerable: true, - get: function () { - return _index4.NoDeprecatedCustomRule; - } -})); -Object.defineProperty(exports, "NoFragmentCyclesRule", ({ - enumerable: true, - get: function () { - return _index4.NoFragmentCyclesRule; - } -})); -Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ - enumerable: true, - get: function () { - return _index4.NoSchemaIntrospectionCustomRule; - } -})); -Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ - enumerable: true, - get: function () { - return _index4.NoUndefinedVariablesRule; - } -})); -Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ - enumerable: true, - get: function () { - return _index4.NoUnusedFragmentsRule; - } -})); -Object.defineProperty(exports, "NoUnusedVariablesRule", ({ - enumerable: true, - get: function () { - return _index4.NoUnusedVariablesRule; - } -})); -Object.defineProperty(exports, "OperationTypeNode", ({ - enumerable: true, - get: function () { - return _index2.OperationTypeNode; - } -})); -Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ - enumerable: true, - get: function () { - return _index4.OverlappingFieldsCanBeMergedRule; - } -})); -Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ - enumerable: true, - get: function () { - return _index4.PossibleFragmentSpreadsRule; - } -})); -Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ - enumerable: true, - get: function () { - return _index4.PossibleTypeExtensionsRule; - } -})); -Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ - enumerable: true, - get: function () { - return _index4.ProvidedRequiredArgumentsRule; - } -})); -Object.defineProperty(exports, "ScalarLeafsRule", ({ - enumerable: true, - get: function () { - return _index4.ScalarLeafsRule; - } -})); -Object.defineProperty(exports, "SchemaMetaFieldDef", ({ - enumerable: true, - get: function () { - return _index.SchemaMetaFieldDef; - } -})); -Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ - enumerable: true, - get: function () { - return _index4.SingleFieldSubscriptionsRule; - } -})); -Object.defineProperty(exports, "Source", ({ - enumerable: true, - get: function () { - return _index2.Source; - } -})); -Object.defineProperty(exports, "Token", ({ - enumerable: true, - get: function () { - return _index2.Token; - } -})); -Object.defineProperty(exports, "TokenKind", ({ - enumerable: true, - get: function () { - return _index2.TokenKind; - } -})); -Object.defineProperty(exports, "TypeInfo", ({ - enumerable: true, - get: function () { - return _index6.TypeInfo; - } -})); -Object.defineProperty(exports, "TypeKind", ({ - enumerable: true, - get: function () { - return _index.TypeKind; - } -})); -Object.defineProperty(exports, "TypeMetaFieldDef", ({ - enumerable: true, - get: function () { - return _index.TypeMetaFieldDef; - } -})); -Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ - enumerable: true, - get: function () { - return _index.TypeNameMetaFieldDef; - } -})); -Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueArgumentDefinitionNamesRule; - } -})); -Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueArgumentNamesRule; - } -})); -Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueDirectiveNamesRule; - } -})); -Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueDirectivesPerLocationRule; - } -})); -Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueEnumValueNamesRule; - } -})); -Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueFieldDefinitionNamesRule; - } -})); -Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueFragmentNamesRule; - } -})); -Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueInputFieldNamesRule; - } -})); -Object.defineProperty(exports, "UniqueOperationNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueOperationNamesRule; - } -})); -Object.defineProperty(exports, "UniqueOperationTypesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueOperationTypesRule; - } -})); -Object.defineProperty(exports, "UniqueTypeNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueTypeNamesRule; - } -})); -Object.defineProperty(exports, "UniqueVariableNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueVariableNamesRule; - } -})); -Object.defineProperty(exports, "ValidationContext", ({ - enumerable: true, - get: function () { - return _index4.ValidationContext; - } -})); -Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _index4.ValuesOfCorrectTypeRule; - } -})); -Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ - enumerable: true, - get: function () { - return _index4.VariablesAreInputTypesRule; - } -})); -Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ - enumerable: true, - get: function () { - return _index4.VariablesInAllowedPositionRule; - } -})); -Object.defineProperty(exports, "__Directive", ({ - enumerable: true, - get: function () { - return _index.__Directive; - } -})); -Object.defineProperty(exports, "__DirectiveLocation", ({ - enumerable: true, - get: function () { - return _index.__DirectiveLocation; - } -})); -Object.defineProperty(exports, "__EnumValue", ({ - enumerable: true, - get: function () { - return _index.__EnumValue; - } -})); -Object.defineProperty(exports, "__Field", ({ - enumerable: true, - get: function () { - return _index.__Field; - } -})); -Object.defineProperty(exports, "__InputValue", ({ - enumerable: true, - get: function () { - return _index.__InputValue; - } -})); -Object.defineProperty(exports, "__Schema", ({ - enumerable: true, - get: function () { - return _index.__Schema; - } -})); -Object.defineProperty(exports, "__Type", ({ - enumerable: true, - get: function () { - return _index.__Type; - } -})); -Object.defineProperty(exports, "__TypeKind", ({ - enumerable: true, - get: function () { - return _index.__TypeKind; - } -})); -Object.defineProperty(exports, "assertAbstractType", ({ - enumerable: true, - get: function () { - return _index.assertAbstractType; - } -})); -Object.defineProperty(exports, "assertCompositeType", ({ - enumerable: true, - get: function () { - return _index.assertCompositeType; - } -})); -Object.defineProperty(exports, "assertDirective", ({ - enumerable: true, - get: function () { - return _index.assertDirective; - } -})); -Object.defineProperty(exports, "assertEnumType", ({ - enumerable: true, - get: function () { - return _index.assertEnumType; - } -})); -Object.defineProperty(exports, "assertEnumValueName", ({ - enumerable: true, - get: function () { - return _index.assertEnumValueName; - } -})); -Object.defineProperty(exports, "assertInputObjectType", ({ - enumerable: true, - get: function () { - return _index.assertInputObjectType; - } -})); -Object.defineProperty(exports, "assertInputType", ({ - enumerable: true, - get: function () { - return _index.assertInputType; - } -})); -Object.defineProperty(exports, "assertInterfaceType", ({ - enumerable: true, - get: function () { - return _index.assertInterfaceType; - } -})); -Object.defineProperty(exports, "assertLeafType", ({ - enumerable: true, - get: function () { - return _index.assertLeafType; - } -})); -Object.defineProperty(exports, "assertListType", ({ - enumerable: true, - get: function () { - return _index.assertListType; - } -})); -Object.defineProperty(exports, "assertName", ({ - enumerable: true, - get: function () { - return _index.assertName; - } -})); -Object.defineProperty(exports, "assertNamedType", ({ - enumerable: true, - get: function () { - return _index.assertNamedType; - } -})); -Object.defineProperty(exports, "assertNonNullType", ({ - enumerable: true, - get: function () { - return _index.assertNonNullType; - } -})); -Object.defineProperty(exports, "assertNullableType", ({ - enumerable: true, - get: function () { - return _index.assertNullableType; - } -})); -Object.defineProperty(exports, "assertObjectType", ({ - enumerable: true, - get: function () { - return _index.assertObjectType; - } -})); -Object.defineProperty(exports, "assertOutputType", ({ - enumerable: true, - get: function () { - return _index.assertOutputType; - } -})); -Object.defineProperty(exports, "assertScalarType", ({ - enumerable: true, - get: function () { - return _index.assertScalarType; - } -})); -Object.defineProperty(exports, "assertSchema", ({ - enumerable: true, - get: function () { - return _index.assertSchema; - } -})); -Object.defineProperty(exports, "assertType", ({ - enumerable: true, - get: function () { - return _index.assertType; - } -})); -Object.defineProperty(exports, "assertUnionType", ({ - enumerable: true, - get: function () { - return _index.assertUnionType; - } -})); -Object.defineProperty(exports, "assertValidName", ({ - enumerable: true, - get: function () { - return _index6.assertValidName; - } -})); -Object.defineProperty(exports, "assertValidSchema", ({ - enumerable: true, - get: function () { - return _index.assertValidSchema; - } -})); -Object.defineProperty(exports, "assertWrappingType", ({ - enumerable: true, - get: function () { - return _index.assertWrappingType; - } -})); -Object.defineProperty(exports, "astFromValue", ({ - enumerable: true, - get: function () { - return _index6.astFromValue; - } -})); -Object.defineProperty(exports, "buildASTSchema", ({ - enumerable: true, - get: function () { - return _index6.buildASTSchema; - } -})); -Object.defineProperty(exports, "buildClientSchema", ({ - enumerable: true, - get: function () { - return _index6.buildClientSchema; - } -})); -Object.defineProperty(exports, "buildSchema", ({ - enumerable: true, - get: function () { - return _index6.buildSchema; - } -})); -Object.defineProperty(exports, "coerceInputValue", ({ - enumerable: true, - get: function () { - return _index6.coerceInputValue; - } -})); -Object.defineProperty(exports, "concatAST", ({ - enumerable: true, - get: function () { - return _index6.concatAST; - } -})); -Object.defineProperty(exports, "createSourceEventStream", ({ - enumerable: true, - get: function () { - return _index3.createSourceEventStream; - } -})); -Object.defineProperty(exports, "defaultFieldResolver", ({ - enumerable: true, - get: function () { - return _index3.defaultFieldResolver; - } -})); -Object.defineProperty(exports, "defaultTypeResolver", ({ - enumerable: true, - get: function () { - return _index3.defaultTypeResolver; - } -})); -Object.defineProperty(exports, "doTypesOverlap", ({ - enumerable: true, - get: function () { - return _index6.doTypesOverlap; - } -})); -Object.defineProperty(exports, "execute", ({ - enumerable: true, - get: function () { - return _index3.execute; - } -})); -Object.defineProperty(exports, "executeSync", ({ - enumerable: true, - get: function () { - return _index3.executeSync; - } -})); -Object.defineProperty(exports, "extendSchema", ({ - enumerable: true, - get: function () { - return _index6.extendSchema; - } -})); -Object.defineProperty(exports, "findBreakingChanges", ({ - enumerable: true, - get: function () { - return _index6.findBreakingChanges; - } -})); -Object.defineProperty(exports, "findDangerousChanges", ({ - enumerable: true, - get: function () { - return _index6.findDangerousChanges; - } -})); -Object.defineProperty(exports, "formatError", ({ - enumerable: true, - get: function () { - return _index5.formatError; - } -})); -Object.defineProperty(exports, "getArgumentValues", ({ - enumerable: true, - get: function () { - return _index3.getArgumentValues; - } -})); -Object.defineProperty(exports, "getDirectiveValues", ({ - enumerable: true, - get: function () { - return _index3.getDirectiveValues; - } -})); -Object.defineProperty(exports, "getEnterLeaveForKind", ({ - enumerable: true, - get: function () { - return _index2.getEnterLeaveForKind; - } -})); -Object.defineProperty(exports, "getIntrospectionQuery", ({ - enumerable: true, - get: function () { - return _index6.getIntrospectionQuery; - } -})); -Object.defineProperty(exports, "getLocation", ({ - enumerable: true, - get: function () { - return _index2.getLocation; - } -})); -Object.defineProperty(exports, "getNamedType", ({ - enumerable: true, - get: function () { - return _index.getNamedType; - } -})); -Object.defineProperty(exports, "getNullableType", ({ - enumerable: true, - get: function () { - return _index.getNullableType; - } -})); -Object.defineProperty(exports, "getOperationAST", ({ - enumerable: true, - get: function () { - return _index6.getOperationAST; - } -})); -Object.defineProperty(exports, "getOperationRootType", ({ - enumerable: true, - get: function () { - return _index6.getOperationRootType; - } -})); -Object.defineProperty(exports, "getVariableValues", ({ - enumerable: true, - get: function () { - return _index3.getVariableValues; - } -})); -Object.defineProperty(exports, "getVisitFn", ({ - enumerable: true, - get: function () { - return _index2.getVisitFn; - } -})); -Object.defineProperty(exports, "graphql", ({ - enumerable: true, - get: function () { - return _graphql.graphql; - } -})); -Object.defineProperty(exports, "graphqlSync", ({ - enumerable: true, - get: function () { - return _graphql.graphqlSync; - } -})); -Object.defineProperty(exports, "introspectionFromSchema", ({ - enumerable: true, - get: function () { - return _index6.introspectionFromSchema; - } -})); -Object.defineProperty(exports, "introspectionTypes", ({ - enumerable: true, - get: function () { - return _index.introspectionTypes; - } -})); -Object.defineProperty(exports, "isAbstractType", ({ - enumerable: true, - get: function () { - return _index.isAbstractType; - } -})); -Object.defineProperty(exports, "isCompositeType", ({ - enumerable: true, - get: function () { - return _index.isCompositeType; - } -})); -Object.defineProperty(exports, "isConstValueNode", ({ - enumerable: true, - get: function () { - return _index2.isConstValueNode; - } -})); -Object.defineProperty(exports, "isDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isDefinitionNode; - } -})); -Object.defineProperty(exports, "isDirective", ({ - enumerable: true, - get: function () { - return _index.isDirective; - } -})); -Object.defineProperty(exports, "isEnumType", ({ - enumerable: true, - get: function () { - return _index.isEnumType; - } -})); -Object.defineProperty(exports, "isEqualType", ({ - enumerable: true, - get: function () { - return _index6.isEqualType; - } -})); -Object.defineProperty(exports, "isExecutableDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isExecutableDefinitionNode; - } -})); -Object.defineProperty(exports, "isInputObjectType", ({ - enumerable: true, - get: function () { - return _index.isInputObjectType; - } -})); -Object.defineProperty(exports, "isInputType", ({ - enumerable: true, - get: function () { - return _index.isInputType; - } -})); -Object.defineProperty(exports, "isInterfaceType", ({ - enumerable: true, - get: function () { - return _index.isInterfaceType; - } -})); -Object.defineProperty(exports, "isIntrospectionType", ({ - enumerable: true, - get: function () { - return _index.isIntrospectionType; - } -})); -Object.defineProperty(exports, "isLeafType", ({ - enumerable: true, - get: function () { - return _index.isLeafType; - } -})); -Object.defineProperty(exports, "isListType", ({ - enumerable: true, - get: function () { - return _index.isListType; - } -})); -Object.defineProperty(exports, "isNamedType", ({ - enumerable: true, - get: function () { - return _index.isNamedType; - } -})); -Object.defineProperty(exports, "isNonNullType", ({ - enumerable: true, - get: function () { - return _index.isNonNullType; - } -})); -Object.defineProperty(exports, "isNullableType", ({ - enumerable: true, - get: function () { - return _index.isNullableType; - } -})); -Object.defineProperty(exports, "isObjectType", ({ - enumerable: true, - get: function () { - return _index.isObjectType; - } -})); -Object.defineProperty(exports, "isOutputType", ({ - enumerable: true, - get: function () { - return _index.isOutputType; - } -})); -Object.defineProperty(exports, "isRequiredArgument", ({ - enumerable: true, - get: function () { - return _index.isRequiredArgument; - } -})); -Object.defineProperty(exports, "isRequiredInputField", ({ - enumerable: true, - get: function () { - return _index.isRequiredInputField; - } -})); -Object.defineProperty(exports, "isScalarType", ({ - enumerable: true, - get: function () { - return _index.isScalarType; - } -})); -Object.defineProperty(exports, "isSchema", ({ - enumerable: true, - get: function () { - return _index.isSchema; - } -})); -Object.defineProperty(exports, "isSelectionNode", ({ - enumerable: true, - get: function () { - return _index2.isSelectionNode; - } -})); -Object.defineProperty(exports, "isSpecifiedDirective", ({ - enumerable: true, - get: function () { - return _index.isSpecifiedDirective; - } -})); -Object.defineProperty(exports, "isSpecifiedScalarType", ({ - enumerable: true, - get: function () { - return _index.isSpecifiedScalarType; - } -})); -Object.defineProperty(exports, "isType", ({ - enumerable: true, - get: function () { - return _index.isType; - } -})); -Object.defineProperty(exports, "isTypeDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeDefinitionNode; - } -})); -Object.defineProperty(exports, "isTypeExtensionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeExtensionNode; - } -})); -Object.defineProperty(exports, "isTypeNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeNode; - } -})); -Object.defineProperty(exports, "isTypeSubTypeOf", ({ - enumerable: true, - get: function () { - return _index6.isTypeSubTypeOf; - } -})); -Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeSystemDefinitionNode; - } -})); -Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeSystemExtensionNode; - } -})); -Object.defineProperty(exports, "isUnionType", ({ - enumerable: true, - get: function () { - return _index.isUnionType; - } -})); -Object.defineProperty(exports, "isValidNameError", ({ - enumerable: true, - get: function () { - return _index6.isValidNameError; - } -})); -Object.defineProperty(exports, "isValueNode", ({ - enumerable: true, - get: function () { - return _index2.isValueNode; - } -})); -Object.defineProperty(exports, "isWrappingType", ({ - enumerable: true, - get: function () { - return _index.isWrappingType; - } -})); -Object.defineProperty(exports, "lexicographicSortSchema", ({ - enumerable: true, - get: function () { - return _index6.lexicographicSortSchema; - } -})); -Object.defineProperty(exports, "locatedError", ({ - enumerable: true, - get: function () { - return _index5.locatedError; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _index2.parse; - } -})); -Object.defineProperty(exports, "parseConstValue", ({ - enumerable: true, - get: function () { - return _index2.parseConstValue; - } -})); -Object.defineProperty(exports, "parseType", ({ - enumerable: true, - get: function () { - return _index2.parseType; - } -})); -Object.defineProperty(exports, "parseValue", ({ - enumerable: true, - get: function () { - return _index2.parseValue; - } -})); -Object.defineProperty(exports, "print", ({ - enumerable: true, - get: function () { - return _index2.print; - } -})); -Object.defineProperty(exports, "printError", ({ - enumerable: true, - get: function () { - return _index5.printError; - } -})); -Object.defineProperty(exports, "printIntrospectionSchema", ({ - enumerable: true, - get: function () { - return _index6.printIntrospectionSchema; - } -})); -Object.defineProperty(exports, "printLocation", ({ - enumerable: true, - get: function () { - return _index2.printLocation; - } -})); -Object.defineProperty(exports, "printSchema", ({ - enumerable: true, - get: function () { - return _index6.printSchema; - } -})); -Object.defineProperty(exports, "printSourceLocation", ({ - enumerable: true, - get: function () { - return _index2.printSourceLocation; - } -})); -Object.defineProperty(exports, "printType", ({ - enumerable: true, - get: function () { - return _index6.printType; - } -})); -Object.defineProperty(exports, "resolveObjMapThunk", ({ - enumerable: true, - get: function () { - return _index.resolveObjMapThunk; - } -})); -Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ - enumerable: true, - get: function () { - return _index.resolveReadonlyArrayThunk; - } -})); -Object.defineProperty(exports, "responsePathAsArray", ({ - enumerable: true, - get: function () { - return _index3.responsePathAsArray; - } -})); -Object.defineProperty(exports, "separateOperations", ({ - enumerable: true, - get: function () { - return _index6.separateOperations; - } -})); -Object.defineProperty(exports, "specifiedDirectives", ({ - enumerable: true, - get: function () { - return _index.specifiedDirectives; - } -})); -Object.defineProperty(exports, "specifiedRules", ({ - enumerable: true, - get: function () { - return _index4.specifiedRules; - } -})); -Object.defineProperty(exports, "specifiedScalarTypes", ({ - enumerable: true, - get: function () { - return _index.specifiedScalarTypes; - } -})); -Object.defineProperty(exports, "stripIgnoredCharacters", ({ - enumerable: true, - get: function () { - return _index6.stripIgnoredCharacters; - } -})); -Object.defineProperty(exports, "subscribe", ({ - enumerable: true, - get: function () { - return _index3.subscribe; - } -})); -Object.defineProperty(exports, "syntaxError", ({ - enumerable: true, - get: function () { - return _index5.syntaxError; - } -})); -Object.defineProperty(exports, "typeFromAST", ({ - enumerable: true, - get: function () { - return _index6.typeFromAST; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _index4.validate; - } -})); -Object.defineProperty(exports, "validateSchema", ({ - enumerable: true, - get: function () { - return _index.validateSchema; - } -})); -Object.defineProperty(exports, "valueFromAST", ({ - enumerable: true, - get: function () { - return _index6.valueFromAST; - } -})); -Object.defineProperty(exports, "valueFromASTUntyped", ({ - enumerable: true, - get: function () { - return _index6.valueFromASTUntyped; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.version; - } -})); -Object.defineProperty(exports, "versionInfo", ({ - enumerable: true, - get: function () { - return _version.versionInfo; - } -})); -Object.defineProperty(exports, "visit", ({ - enumerable: true, - get: function () { - return _index2.visit; - } -})); -Object.defineProperty(exports, "visitInParallel", ({ - enumerable: true, - get: function () { - return _index2.visitInParallel; - } -})); -Object.defineProperty(exports, "visitWithTypeInfo", ({ - enumerable: true, - get: function () { - return _index6.visitWithTypeInfo; - } -})); -var _version = __webpack_require__(/*! ./version.mjs */ "../../../node_modules/graphql/version.mjs"); -var _graphql = __webpack_require__(/*! ./graphql.mjs */ "../../../node_modules/graphql/graphql.mjs"); -var _index = __webpack_require__(/*! ./type/index.mjs */ "../../../node_modules/graphql/type/index.mjs"); -var _index2 = __webpack_require__(/*! ./language/index.mjs */ "../../../node_modules/graphql/language/index.mjs"); -var _index3 = __webpack_require__(/*! ./execution/index.mjs */ "../../../node_modules/graphql/execution/index.mjs"); -var _index4 = __webpack_require__(/*! ./validation/index.mjs */ "../../../node_modules/graphql/validation/index.mjs"); -var _index5 = __webpack_require__(/*! ./error/index.mjs */ "../../../node_modules/graphql/error/index.mjs"); -var _index6 = __webpack_require__(/*! ./utilities/index.mjs */ "../../../node_modules/graphql/utilities/index.mjs"); - -/***/ }), - -/***/ "../../../node_modules/graphql/jsutils/Path.mjs": -/*!******************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/Path.mjs ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports) { + while (size < 12) { + const code = body.charCodeAt(position + size++); // Closing Brace (}) + + if (code === 0x007d) { + // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } + return { + value: String.fromCodePoint(point), + size, + }; + } // Append this hex digit to the code point. + point = (point << 4) | readHexDigit(code); + if (point < 0) { + break; + } + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice( + position, + position + size + )}".` + ); + } + function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); + if (isUnicodeScalarValue(code)) { + return { + value: String.fromCodePoint(code), + size: 6, + }; + } // GraphQL allows JSON-style surrogate pair escape sequences, but only when + // a valid pair is formed. + + if (isLeadingSurrogate(code)) { + // \u + if ( + body.charCodeAt(position + 6) === 0x005c && + body.charCodeAt(position + 7) === 0x0075 + ) { + const trailingCode = read16BitHexCode(body, position + 8); + if (isTrailingSurrogate(trailingCode)) { + // JavaScript defines strings as a sequence of UTF-16 code units and + // encodes Unicode code points above U+FFFF using a surrogate pair of + // code units. Since this is a surrogate pair escape sequence, just + // include both codes into the JavaScript string value. Had JavaScript + // not been internally based on UTF-16, then this surrogate pair would + // be decoded to retrieve the supplementary code point. + return { + value: String.fromCodePoint(code, trailingCode), + size: 12, + }; + } + } + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice( + position, + position + 6 + )}".` + ); + } + /** + * Reads four hexadecimal characters and returns the positive integer that 16bit + * hexadecimal string represents. For example, "000f" will return 15, and "dead" + * will return 57005. + * + * Returns a negative number if any char was not a valid hexadecimal digit. + */ + + function read16BitHexCode(body, position) { + // readHexDigit() returns -1 on error. ORing a negative value with any other + // value always produces a negative value. + return ( + (readHexDigit(body.charCodeAt(position)) << 12) | + (readHexDigit(body.charCodeAt(position + 1)) << 8) | + (readHexDigit(body.charCodeAt(position + 2)) << 4) | + readHexDigit(body.charCodeAt(position + 3)) + ); + } + /** + * Reads a hexadecimal character and returns its positive integer value (0-15). + * + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 if the provided character code was not a valid hexadecimal digit. + * + * HexDigit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * - `A` `B` `C` `D` `E` `F` + * - `a` `b` `c` `d` `e` `f` + */ + function readHexDigit(code) { + return code >= 0x0030 && code <= 0x0039 // 0-9 + ? code - 0x0030 + : code >= 0x0041 && code <= 0x0046 // A-F + ? code - 0x0037 + : code >= 0x0061 && code <= 0x0066 // a-f + ? code - 0x0057 + : -1; + } + /** + * | Escaped Character | Code Point | Character Name | + * | ----------------- | ---------- | ---------------------------- | + * | `"` | U+0022 | double quote | + * | `\` | U+005C | reverse solidus (back slash) | + * | `/` | U+002F | solidus (forward slash) | + * | `b` | U+0008 | backspace | + * | `f` | U+000C | form feed | + * | `n` | U+000A | line feed (new line) | + * | `r` | U+000D | carriage return | + * | `t` | U+0009 | horizontal tab | + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.addPath = addPath; -exports.pathToArray = pathToArray; -/** - * Given a Path and a key, return a new Path containing the new key. - */ -function addPath(prev, key, typename) { - return { - prev, - key, - typename - }; -} -/** - * Given a Path, return an Array of the path keys. - */ - -function pathToArray(path) { - const flattened = []; - let curr = path; - while (curr) { - flattened.push(curr.key); - curr = curr.prev; - } - return flattened.reverse(); -} + function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); + switch (code) { + case 0x0022: + // " + return { + value: "\u0022", + size: 2, + }; + case 0x005c: + // \ + return { + value: "\u005c", + size: 2, + }; + case 0x002f: + // / + return { + value: "\u002f", + size: 2, + }; + case 0x0062: + // b + return { + value: "\u0008", + size: 2, + }; + case 0x0066: + // f + return { + value: "\u000c", + size: 2, + }; + case 0x006e: + // n + return { + value: "\u000a", + size: 2, + }; + case 0x0072: + // r + return { + value: "\u000d", + size: 2, + }; + case 0x0074: + // t + return { + value: "\u0009", + size: 2, + }; + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character escape sequence: "${body.slice( + position, + position + 2 + )}".` + ); + } + /** + * Reads a block string token from the source file. + * + * ``` + * StringValue :: + * - `"""` BlockStringCharacter* `"""` + * + * BlockStringCharacter :: + * - SourceCharacter but not `"""` or `\"""` + * - `\"""` + * ``` + */ -/***/ }), + function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ""; + const blockLines = []; + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Triple-Quote (""") + + if ( + code === 0x0022 && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken( + lexer, + _tokenKind.TokenKind.BLOCK_STRING, + start, + position + 3, + // Return a string of the lines joined with U+000A. + (0, _blockString.dedentBlockStringLines)(blockLines).join("\n") + ); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } // Escaped Triple-Quote (\""") + + if ( + code === 0x005c && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 && + body.charCodeAt(position + 3) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; // skip only slash + + position += 4; + continue; + } // LineTerminator -/***/ "../../../node_modules/graphql/jsutils/devAssert.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/devAssert.mjs ***! + if (code === 0x000a || code === 0x000d) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + currentLine = ""; + chunkStart = position; + lineStart = position; + continue; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position + )}.` + ); + } + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + "Unterminated string." + ); + } + /** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + */ + + function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if ((0, _characterClasses.isNameContinue)(code)) { + ++position; + } else { + break; + } + } + return createToken( + lexer, + _tokenKind.TokenKind.NAME, + start, + position, + body.slice(start, position) + ); + } + + /***/ + }, + + /***/ "../../../node_modules/graphql/language/location.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/language/location.mjs ***! \***********************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getLocation = getLocation; + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + const LineRegExp = /\r\n|[\n\r]/g; + /** + * Represents a location in a Source. + */ + /** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ + function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; + for (const match of source.body.matchAll(LineRegExp)) { + typeof match.index === "number" || (0, _invariant.invariant)(false); + if (match.index >= position) { + break; + } + lastLineStart = match.index + match[0].length; + line += 1; + } + return { + line, + column: position + 1 - lastLineStart, + }; + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.devAssert = devAssert; -function devAssert(condition, message) { - const booleanCondition = Boolean(condition); - if (!booleanCondition) { - throw new Error(message); - } -} + /***/ "../../../node_modules/graphql/language/parser.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/language/parser.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Parser = void 0; + exports.parse = parse; + exports.parseConstValue = parseConstValue; + exports.parseType = parseType; + exports.parseValue = parseValue; + var _syntaxError = __webpack_require__( + /*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs" + ); + var _ast = __webpack_require__( + /*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _directiveLocation = __webpack_require__( + /*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs" + ); + var _kinds = __webpack_require__( + /*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _lexer = __webpack_require__( + /*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs" + ); + var _source = __webpack_require__( + /*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs" + ); + var _tokenKind = __webpack_require__( + /*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs" + ); + /** + * Configuration options to control parser behavior + */ + + /** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ + function parse(source, options) { + const parser = new Parser(source, options); + return parser.parseDocument(); + } + /** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ -/***/ }), + function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; + } + /** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + */ -/***/ "../../../node_modules/graphql/jsutils/didYouMean.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/didYouMean.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; + } + /** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + + function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return type; + } + /** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + + class Parser { + constructor(source, options = {}) { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + this._lexer = new _lexer.Lexer(sourceObj); + this._options = options; + this._tokenCounter = 0; + } + /** + * Converts a name lex token into a name parse node. + */ + parseName() { + const token = this.expectToken(_tokenKind.TokenKind.NAME); + return this.node(token, { + kind: _kinds.Kind.NAME, + value: token.value, + }); + } // Implements the parsing rules in the Document section. + /** + * Document : Definition+ + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.didYouMean = didYouMean; -const MAX_SUGGESTIONS = 5; -/** - * Given [ A, B, C ] return ' Did you mean A, B, or C?'. - */ + parseDocument() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.DOCUMENT, + definitions: this.many( + _tokenKind.TokenKind.SOF, + this.parseDefinition, + _tokenKind.TokenKind.EOF + ), + }); + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ -function didYouMean(firstArg, secondArg) { - const [subMessage, suggestionsArg] = secondArg ? [firstArg, secondArg] : [undefined, firstArg]; - let message = ' Did you mean '; - if (subMessage) { - message += subMessage + ' '; - } - const suggestions = suggestionsArg.map(x => `"${x}"`); - switch (suggestions.length) { - case 0: - return ''; - case 1: - return message + suggestions[0] + '?'; - case 2: - return message + suggestions[0] + ' or ' + suggestions[1] + '?'; - } - const selected = suggestions.slice(0, MAX_SUGGESTIONS); - const lastItem = selected.pop(); - return message + selected.join(', ') + ', or ' + lastItem + '?'; -} + parseDefinition() { + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } // Many definitions begin with a description and require a lookahead. + + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription + ? this._lexer.lookahead() + : this._lexer.token; + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case "schema": + return this.parseSchemaDefinition(); + case "scalar": + return this.parseScalarTypeDefinition(); + case "type": + return this.parseObjectTypeDefinition(); + case "interface": + return this.parseInterfaceTypeDefinition(); + case "union": + return this.parseUnionTypeDefinition(); + case "enum": + return this.parseEnumTypeDefinition(); + case "input": + return this.parseInputObjectTypeDefinition(); + case "directive": + return this.parseDirectiveDefinition(); + } + if (hasDescription) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + "Unexpected description, descriptions are supported only on type definitions." + ); + } + switch (keywordToken.value) { + case "query": + case "mutation": + case "subscription": + return this.parseOperationDefinition(); + case "fragment": + return this.parseFragmentDefinition(); + case "extend": + return this.parseTypeSystemExtension(); + } + } + throw this.unexpected(keywordToken); + } // Implements the parsing rules in the Operations section. -/***/ }), + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ -/***/ "../../../node_modules/graphql/jsutils/groupBy.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/groupBy.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.groupBy = groupBy; -/** - * Groups array items into a Map, given a function to produce grouping key. - */ -function groupBy(list, keyFn) { - const result = new Map(); - for (const item of list) { - const key = keyFn(item); - const group = result.get(key); - if (group === undefined) { - result.set(key, [item]); - } else { - group.push(item); - } - } - return result; -} + parseOperationDefinition() { + const start = this._lexer.token; + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: _ast.OperationTypeNode.QUERY, + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + }); + } + const operation = this.parseOperationType(); + let name; + if (this.peek(_tokenKind.TokenKind.NAME)) { + name = this.parseName(); + } + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * OperationType : one of query mutation subscription + */ + + parseOperationType() { + const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); + switch (operationToken.value) { + case "query": + return _ast.OperationTypeNode.QUERY; + case "mutation": + return _ast.OperationTypeNode.MUTATION; + case "subscription": + return _ast.OperationTypeNode.SUBSCRIPTION; + } + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ + + parseVariableDefinitions() { + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + this.parseVariableDefinition, + _tokenKind.TokenKind.PAREN_R + ); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: + (this.expectToken(_tokenKind.TokenKind.COLON), + this.parseTypeReference()), + defaultValue: this.expectOptionalToken( + _tokenKind.TokenKind.EQUALS + ) + ? this.parseConstValueLiteral() + : undefined, + directives: this.parseConstDirectives(), + }); + } + /** + * Variable : $ Name + */ + + parseVariable() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.DOLLAR); + return this.node(start, { + kind: _kinds.Kind.VARIABLE, + name: this.parseName(), + }); + } + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + */ + + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.SELECTION_SET, + selections: this.many( + _tokenKind.TokenKind.BRACE_L, + this.parseSelection, + _tokenKind.TokenKind.BRACE_R + ), + }); + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + parseSelection() { + return this.peek(_tokenKind.TokenKind.SPREAD) + ? this.parseFragment() + : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; + if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + return this.node(start, { + kind: _kinds.Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) + ? this.parseSelectionSet() + : undefined, + }); + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + item, + _tokenKind.TokenKind.PAREN_R + ); + } + /** + * Argument[Const] : Name : Value[?Const] + */ + + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst), + }); + } + parseConstArgument() { + return this.parseArgument(true); + } // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + + parseFragment() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword("on"); + if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + }); + } + return this.node(start, { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition + ? this.parseNamedType() + : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + parseFragmentDefinition() { + const start = this._lexer.token; + this.expectKeyword("fragment"); // Legacy support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (this._options.allowLegacyFragmentVariables === true) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: + (this.expectKeyword("on"), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword("on"), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentName : Name but not `on` + */ + + parseFragmentName() { + if (this._lexer.token.value === "on") { + throw this.unexpected(); + } + return this.parseName(); + } // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + + parseValueLiteral(isConst) { + const token = this._lexer.token; + switch (token.kind) { + case _tokenKind.TokenKind.BRACKET_L: + return this.parseList(isConst); + case _tokenKind.TokenKind.BRACE_L: + return this.parseObject(isConst); + case _tokenKind.TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.INT, + value: token.value, + }); + case _tokenKind.TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.FLOAT, + value: token.value, + }); + case _tokenKind.TokenKind.STRING: + case _tokenKind.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + case _tokenKind.TokenKind.NAME: + this.advanceLexer(); + switch (token.value) { + case "true": + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: true, + }); + case "false": + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: false, + }); + case "null": + return this.node(token, { + kind: _kinds.Kind.NULL, + }); + default: + return this.node(token, { + kind: _kinds.Kind.ENUM, + value: token.value, + }); + } + case _tokenKind.TokenKind.DOLLAR: + if (isConst) { + this.expectToken(_tokenKind.TokenKind.DOLLAR); + if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { + const varName = this._lexer.token.value; + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Unexpected variable "$${varName}" in constant value.` + ); + } else { + throw this.unexpected(token); + } + } + return this.parseVariable(); + default: + throw this.unexpected(); + } + } + parseConstValueLiteral() { + return this.parseValueLiteral(true); + } + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _tokenKind.TokenKind.BLOCK_STRING, + }); + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.LIST, + values: this.any( + _tokenKind.TokenKind.BRACKET_L, + item, + _tokenKind.TokenKind.BRACKET_R + ), + }); + } + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + */ + + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.OBJECT, + fields: this.any( + _tokenKind.TokenKind.BRACE_L, + item, + _tokenKind.TokenKind.BRACE_R + ), + }); + } + /** + * ObjectField[Const] : Name : Value[?Const] + */ + + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst), + }); + } // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + */ -/***/ }), + parseDirectives(isConst) { + const directives = []; + while (this.peek(_tokenKind.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + return directives; + } + parseConstDirectives() { + return this.parseDirectives(true); + } + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + */ -/***/ "../../../node_modules/graphql/jsutils/identityFunc.mjs": -/*!**************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/identityFunc.mjs ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.AT); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + }); + } // Implements the parsing rules in the Types section. + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + parseTypeReference() { + const start = this._lexer.token; + let type; + if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(_tokenKind.TokenKind.BRACKET_R); + type = this.node(start, { + kind: _kinds.Kind.LIST_TYPE, + type: innerType, + }); + } else { + type = this.parseNamedType(); + } + if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { + return this.node(start, { + kind: _kinds.Kind.NON_NULL_TYPE, + type, + }); + } + return type; + } + /** + * NamedType : Name + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.identityFunc = identityFunc; -/** - * Returns the first argument it receives. - */ -function identityFunc(x) { - return x; -} + parseNamedType() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.NAMED_TYPE, + name: this.parseName(), + }); + } // Implements the parsing rules in the Type Definition section. -/***/ }), + peekDescription() { + return ( + this.peek(_tokenKind.TokenKind.STRING) || + this.peek(_tokenKind.TokenKind.BLOCK_STRING) + ); + } + /** + * Description : StringValue + */ -/***/ "../../../node_modules/graphql/jsutils/inspect.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/inspect.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.inspect = inspect; -const MAX_ARRAY_LENGTH = 10; -const MAX_RECURSIVE_DEPTH = 2; -/** - * Used to print values in error messages. - */ - -function inspect(value) { - return formatValue(value, []); -} -function formatValue(value, seenValues) { - switch (typeof value) { - case 'string': - return JSON.stringify(value); - case 'function': - return value.name ? `[function ${value.name}]` : '[function]'; - case 'object': - return formatObjectValue(value, seenValues); - default: - return String(value); - } -} -function formatObjectValue(value, previouslySeenValues) { - if (value === null) { - return 'null'; - } - if (previouslySeenValues.includes(value)) { - return '[Circular]'; - } - const seenValues = [...previouslySeenValues, value]; - if (isJSONable(value)) { - const jsonValue = value.toJSON(); // check for infinite recursion + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + */ - if (jsonValue !== value) { - return typeof jsonValue === 'string' ? jsonValue : formatValue(jsonValue, seenValues); - } - } else if (Array.isArray(value)) { - return formatArray(value, seenValues); - } - return formatObject(value, seenValues); -} -function isJSONable(value) { - return typeof value.toJSON === 'function'; -} -function formatObject(object, seenValues) { - const entries = Object.entries(object); - if (entries.length === 0) { - return '{}'; - } - if (seenValues.length > MAX_RECURSIVE_DEPTH) { - return '[' + getObjectTag(object) + ']'; - } - const properties = entries.map(([key, value]) => key + ': ' + formatValue(value, seenValues)); - return '{ ' + properties.join(', ') + ' }'; -} -function formatArray(array, seenValues) { - if (array.length === 0) { - return '[]'; - } - if (seenValues.length > MAX_RECURSIVE_DEPTH) { - return '[Array]'; - } - const len = Math.min(MAX_ARRAY_LENGTH, array.length); - const remaining = array.length - len; - const items = []; - for (let i = 0; i < len; ++i) { - items.push(formatValue(array[i], seenValues)); - } - if (remaining === 1) { - items.push('... 1 more item'); - } else if (remaining > 1) { - items.push(`... ${remaining} more items`); - } - return '[' + items.join(', ') + ']'; -} -function getObjectTag(object) { - const tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, ''); - if (tag === 'Object' && typeof object.constructor === 'function') { - const name = object.constructor.name; - if (typeof name === 'string' && name !== '') { - return name; - } - } - return tag; -} + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("schema"); + const directives = this.parseConstDirectives(); + const operationTypes = this.many( + _tokenKind.TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + _tokenKind.TokenKind.BRACE_R + ); + return this.node(start, { + kind: _kinds.Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes, + }); + } + /** + * OperationTypeDefinition : OperationType : NamedType + */ -/***/ }), + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + }); + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ -/***/ "../../../node_modules/graphql/jsutils/instanceOf.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/instanceOf.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.instanceOf = void 0; -var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -/** - * A replacement for instanceof which includes an error warning when multi-realm - * constructors are detected. - * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production - * See: https://webpack.js.org/guides/production/ - */ - -const instanceOf = exports.instanceOf = /* c8 ignore next 6 */ -// FIXME: https://github.com/graphql/graphql-js/issues/2317 -globalThis.process && globalThis.process.env.NODE_ENV === 'production' ? function instanceOf(value, constructor) { - return value instanceof constructor; -} : function instanceOf(value, constructor) { - if (value instanceof constructor) { - return true; - } - if (typeof value === 'object' && value !== null) { - var _value$constructor; - - // Prefer Symbol.toStringTag since it is immune to minification. - const className = constructor.prototype[Symbol.toStringTag]; - const valueClassName = - // We still need to support constructor's name to detect conflicts with older versions of this library. - Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 - ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name; - if (className === valueClassName) { - const stringifiedValue = (0, _inspect.inspect)(value); - throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("scalar"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + }); + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ -Ensure that there is only one instance of "graphql" in the node_modules -directory. If different versions of "graphql" are the dependencies of other -relied on modules, use "resolutions" to ensure only one version is installed. + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("type"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ -https://yarnpkg.com/en/docs/selective-version-resolutions + parseImplementsInterfaces() { + return this.expectOptionalKeyword("implements") + ? this.delimitedMany( + _tokenKind.TokenKind.AMP, + this.parseNamedType + ) + : []; + } + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + */ -Duplicate "graphql" modules cannot be used at the same time since different -versions may have different capabilities and behavior. The data from one -version used in the function from another could produce confusing and -spurious results.`); - } - } - return false; -}; + parseFieldsDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseFieldDefinition, + _tokenKind.TokenKind.BRACE_R + ); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ -/***/ }), + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + }); + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ -/***/ "../../../node_modules/graphql/jsutils/invariant.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/invariant.mjs ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports) { + parseArgumentDefs() { + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + this.parseInputValueDef, + _tokenKind.TokenKind.PAREN_R + ); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + }); + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("interface"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("union"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + }); + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.invariant = invariant; -function invariant(condition, message) { - const booleanCondition = Boolean(condition); - if (!booleanCondition) { - throw new Error(message != null ? message : 'Unexpected invariant triggered.'); - } -} + parseUnionMemberTypes() { + return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) + ? this.delimitedMany( + _tokenKind.TokenKind.PIPE, + this.parseNamedType + ) + : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ -/***/ }), + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("enum"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + }); + } + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + */ -/***/ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs": -/*!*****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isAsyncIterable.mjs ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + parseEnumValuesDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseEnumValueDefinition, + _tokenKind.TokenKind.BRACE_R + ); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + */ + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + }); + } + /** + * EnumValue : Name but not `true`, `false` or `null` + */ + parseEnumValueName() { + if ( + this._lexer.token.value === "true" || + this._lexer.token.value === "false" || + this._lexer.token.value === "null" + ) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + `${getTokenDesc( + this._lexer.token + )} is reserved and cannot be used for an enum value.` + ); + } + return this.parseName(); + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isAsyncIterable = isAsyncIterable; -/** - * Returns true if the provided object implements the AsyncIterator protocol via - * implementing a `Symbol.asyncIterator` method. - */ -function isAsyncIterable(maybeAsyncIterable) { - return typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 ? void 0 : maybeAsyncIterable[Symbol.asyncIterator]) === 'function'; -} + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("input"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + }); + } + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + */ -/***/ }), + parseInputFieldsDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseInputValueDef, + _tokenKind.TokenKind.BRACE_R + ); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ -/***/ "../../../node_modules/graphql/jsutils/isIterableObject.mjs": -/*!******************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isIterableObject.mjs ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isIterableObject = isIterableObject; -/** - * Returns true if the provided object is an Object (i.e. not a string literal) - * and implements the Iterator protocol. - * - * This may be used in place of [Array.isArray()][isArray] to determine if - * an object should be iterated-over e.g. Array, Map, Set, Int8Array, - * TypedArray, etc. but excludes string literals. - * - * @example - * ```ts - * isIterableObject([ 1, 2, 3 ]) // true - * isIterableObject(new Map()) // true - * isIterableObject('ABC') // false - * isIterableObject({ key: 'value' }) // false - * isIterableObject({ length: 1, 0: 'Alpha' }) // false - * ``` - */ -function isIterableObject(maybeIterable) { - return typeof maybeIterable === 'object' && typeof (maybeIterable === null || maybeIterable === void 0 ? void 0 : maybeIterable[Symbol.iterator]) === 'function'; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/jsutils/isObjectLike.mjs": -/*!**************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isObjectLike.mjs ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case "schema": + return this.parseSchemaExtension(); + case "scalar": + return this.parseScalarTypeExtension(); + case "type": + return this.parseObjectTypeExtension(); + case "interface": + return this.parseInterfaceTypeExtension(); + case "union": + return this.parseUnionTypeExtension(); + case "enum": + return this.parseEnumTypeExtension(); + case "input": + return this.parseInputObjectTypeExtension(); + } + } + throw this.unexpected(keywordToken); + } + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + */ + parseSchemaExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("schema"); + const directives = this.parseConstDirectives(); + const operationTypes = this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + _tokenKind.TokenKind.BRACE_R + ); + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + }); + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("scalar"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + if (directives.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + }); + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isObjectLike = isObjectLike; -/** - * Return true if `value` is object-like. A value is object-like if it's not - * `null` and has a `typeof` result of "object". - */ -function isObjectLike(value) { - return typeof value == 'object' && value !== null; -} + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("type"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ -/***/ }), + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("interface"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ -/***/ "../../../node_modules/graphql/jsutils/isPromise.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isPromise.mjs ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports) { + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("union"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + }); + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("enum"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + }); + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("input"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + }); + } + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isPromise = isPromise; -/** - * Returns true if the value acts like a Promise, i.e. has a "then" function, - * otherwise returns false. - */ -function isPromise(value) { - return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function'; -} + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("directive"); + this.expectToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const repeatable = this.expectOptionalKeyword("repeatable"); + this.expectKeyword("on"); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + repeatable, + locations, + }); + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ -/***/ }), + parseDirectiveLocations() { + return this.delimitedMany( + _tokenKind.TokenKind.PIPE, + this.parseDirectiveLocation + ); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ -/***/ "../../../node_modules/graphql/jsutils/keyMap.mjs": -/*!********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/keyMap.mjs ***! - \********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.keyMap = keyMap; -/** - * Creates a keyed JS object from an array, given a function to produce the keys - * for each value in the array. - * - * This provides a convenient lookup for the array items if the key function - * produces unique results. - * ```ts - * const phoneBook = [ - * { name: 'Jon', num: '555-1234' }, - * { name: 'Jenny', num: '867-5309' } - * ] - * - * const entriesByName = keyMap( - * phoneBook, - * entry => entry.name - * ) - * - * // { - * // Jon: { name: 'Jon', num: '555-1234' }, - * // Jenny: { name: 'Jenny', num: '867-5309' } - * // } - * - * const jennyEntry = entriesByName['Jenny'] - * - * // { name: 'Jenny', num: '857-6309' } - * ``` - */ -function keyMap(list, keyFn) { - const result = Object.create(null); - for (const item of list) { - result[keyFn(item)] = item; - } - return result; -} + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); + if ( + Object.prototype.hasOwnProperty.call( + _directiveLocation.DirectiveLocation, + name.value + ) + ) { + return name; + } + throw this.unexpected(start); + } // Core parsing utility functions -/***/ }), + /** + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. + */ -/***/ "../../../node_modules/graphql/jsutils/keyValMap.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/keyValMap.mjs ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.keyValMap = keyValMap; -/** - * Creates a keyed JS object from an array, given a function to produce the keys - * and a function to produce the values from each item in the array. - * ```ts - * const phoneBook = [ - * { name: 'Jon', num: '555-1234' }, - * { name: 'Jenny', num: '867-5309' } - * ] - * - * // { Jon: '555-1234', Jenny: '867-5309' } - * const phonesByName = keyValMap( - * phoneBook, - * entry => entry.name, - * entry => entry.num - * ) - * ``` - */ -function keyValMap(list, keyFn, valFn) { - const result = Object.create(null); - for (const item of list) { - result[keyFn(item)] = valFn(item); - } - return result; -} + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new _ast.Location( + startToken, + this._lexer.lastToken, + this._lexer.source + ); + } + return node; + } + /** + * Determines if the next token is of a given kind + */ -/***/ }), + peek(kind) { + return this._lexer.token.kind === kind; + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + */ -/***/ "../../../node_modules/graphql/jsutils/mapValue.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/mapValue.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.mapValue = mapValue; -/** - * Creates an object map with the same keys as `map` and values generated by - * running each value of `map` thru `fn`. - */ -function mapValue(map, fn) { - const result = Object.create(null); - for (const key of Object.keys(map)) { - result[key] = fn(map[key], key); - } - return result; -} + expectToken(kind) { + const token = this._lexer.token; + if (token.kind === kind) { + this.advanceLexer(); + return token; + } + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc( + token + )}.` + ); + } + /** + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ -/***/ }), + expectOptionalToken(kind) { + const token = this._lexer.token; + if (token.kind === kind) { + this.advanceLexer(); + return true; + } + return false; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ -/***/ "../../../node_modules/graphql/jsutils/memoize3.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/memoize3.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.memoize3 = memoize3; -/** - * Memoizes the provided three-argument function. - */ -function memoize3(fn) { - let cache0; - return function memoized(a1, a2, a3) { - if (cache0 === undefined) { - cache0 = new WeakMap(); - } - let cache1 = cache0.get(a1); - if (cache1 === undefined) { - cache1 = new WeakMap(); - cache0.set(a1, cache1); - } - let cache2 = cache1.get(a2); - if (cache2 === undefined) { - cache2 = new WeakMap(); - cache1.set(a2, cache2); - } - let fnResult = cache2.get(a3); - if (fnResult === undefined) { - fnResult = fn(a1, a2, a3); - cache2.set(a3, fnResult); - } - return fnResult; - }; -} + expectKeyword(value) { + const token = this._lexer.token; + if ( + token.kind === _tokenKind.TokenKind.NAME && + token.value === value + ) { + this.advanceLexer(); + } else { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}.` + ); + } + } + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ -/***/ }), + expectOptionalKeyword(value) { + const token = this._lexer.token; + if ( + token.kind === _tokenKind.TokenKind.NAME && + token.value === value + ) { + this.advanceLexer(); + return true; + } + return false; + } + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + */ -/***/ "../../../node_modules/graphql/jsutils/naturalCompare.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/naturalCompare.mjs ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.naturalCompare = naturalCompare; -/** - * Returns a number indicating whether a reference string comes before, or after, - * or is the same as the given string in natural sort order. - * - * See: https://en.wikipedia.org/wiki/Natural_sort_order - * - */ -function naturalCompare(aStr, bStr) { - let aIndex = 0; - let bIndex = 0; - while (aIndex < aStr.length && bIndex < bStr.length) { - let aChar = aStr.charCodeAt(aIndex); - let bChar = bStr.charCodeAt(bIndex); - if (isDigit(aChar) && isDigit(bChar)) { - let aNum = 0; - do { - ++aIndex; - aNum = aNum * 10 + aChar - DIGIT_0; - aChar = aStr.charCodeAt(aIndex); - } while (isDigit(aChar) && aNum > 0); - let bNum = 0; - do { - ++bIndex; - bNum = bNum * 10 + bChar - DIGIT_0; - bChar = bStr.charCodeAt(bIndex); - } while (isDigit(bChar) && bNum > 0); - if (aNum < bNum) { - return -1; - } - if (aNum > bNum) { - return 1; - } - } else { - if (aChar < bChar) { - return -1; - } - if (aChar > bChar) { - return 1; - } - ++aIndex; - ++bIndex; - } - } - return aStr.length - bStr.length; -} -const DIGIT_0 = 48; -const DIGIT_9 = 57; -function isDigit(code) { - return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/jsutils/printPathArray.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/printPathArray.mjs ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + unexpected(atToken) { + const token = + atToken !== null && atToken !== void 0 + ? atToken + : this._lexer.token; + return (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}.` + ); + } + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + return []; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.printPathArray = printPathArray; -/** - * Build a string describing the path. - */ -function printPathArray(path) { - return path.map(key => typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key).join(''); -} + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ -/***/ }), + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + return nodes; + } + advanceLexer() { + const { maxTokens } = this._options; + const token = this._lexer.advance(); + if ( + maxTokens !== undefined && + token.kind !== _tokenKind.TokenKind.EOF + ) { + ++this._tokenCounter; + if (this._tokenCounter > maxTokens) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Document contains more that ${maxTokens} tokens. Parsing aborted.` + ); + } + } + } + } + /** + * A helper function to describe a token as a string for debugging. + */ + exports.Parser = Parser; + function getTokenDesc(token) { + const value = token.value; + return ( + getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : "") + ); + } + /** + * A helper function to describe a token kind as a string for debugging. + */ -/***/ "../../../node_modules/graphql/jsutils/promiseForObject.mjs": -/*!******************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/promiseForObject.mjs ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.promiseForObject = promiseForObject; -/** - * This function transforms a JS object `ObjMap>` into - * a `Promise>` - * - * This is akin to bluebird's `Promise.props`, but implemented only using - * `Promise.all` so it will work with any implementation of ES6 promises. - */ -function promiseForObject(object) { - return Promise.all(Object.values(object)).then(resolvedValues => { - const resolvedObject = Object.create(null); - for (const [i, key] of Object.keys(object).entries()) { - resolvedObject[key] = resolvedValues[i]; - } - return resolvedObject; - }); -} + function getTokenKindDesc(kind) { + return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/jsutils/promiseReduce.mjs": -/*!***************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/promiseReduce.mjs ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.promiseReduce = promiseReduce; -var _isPromise = __webpack_require__(/*! ./isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); -/** - * Similar to Array.prototype.reduce(), however the reducing callback may return - * a Promise, in which case reduction will continue after each promise resolves. - * - * If the callback does not return a Promise, then this function will also not - * return a Promise. - */ -function promiseReduce(values, callbackFn, initialValue) { - let accumulator = initialValue; - for (const value of values) { - accumulator = (0, _isPromise.isPromise)(accumulator) ? accumulator.then(resolved => callbackFn(resolved, value)) : callbackFn(accumulator, value); - } - return accumulator; -} + /***/ "../../../node_modules/graphql/language/predicates.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/language/predicates.mjs ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isConstValueNode = isConstValueNode; + exports.isDefinitionNode = isDefinitionNode; + exports.isExecutableDefinitionNode = isExecutableDefinitionNode; + exports.isSelectionNode = isSelectionNode; + exports.isTypeDefinitionNode = isTypeDefinitionNode; + exports.isTypeExtensionNode = isTypeExtensionNode; + exports.isTypeNode = isTypeNode; + exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; + exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; + exports.isValueNode = isValueNode; + var _kinds = __webpack_require__( + /*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + function isDefinitionNode(node) { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); + } + function isExecutableDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.OPERATION_DEFINITION || + node.kind === _kinds.Kind.FRAGMENT_DEFINITION + ); + } + function isSelectionNode(node) { + return ( + node.kind === _kinds.Kind.FIELD || + node.kind === _kinds.Kind.FRAGMENT_SPREAD || + node.kind === _kinds.Kind.INLINE_FRAGMENT + ); + } + function isValueNode(node) { + return ( + node.kind === _kinds.Kind.VARIABLE || + node.kind === _kinds.Kind.INT || + node.kind === _kinds.Kind.FLOAT || + node.kind === _kinds.Kind.STRING || + node.kind === _kinds.Kind.BOOLEAN || + node.kind === _kinds.Kind.NULL || + node.kind === _kinds.Kind.ENUM || + node.kind === _kinds.Kind.LIST || + node.kind === _kinds.Kind.OBJECT + ); + } + function isConstValueNode(node) { + return ( + isValueNode(node) && + (node.kind === _kinds.Kind.LIST + ? node.values.some(isConstValueNode) + : node.kind === _kinds.Kind.OBJECT + ? node.fields.some((field) => isConstValueNode(field.value)) + : node.kind !== _kinds.Kind.VARIABLE) + ); + } + function isTypeNode(node) { + return ( + node.kind === _kinds.Kind.NAMED_TYPE || + node.kind === _kinds.Kind.LIST_TYPE || + node.kind === _kinds.Kind.NON_NULL_TYPE + ); + } + function isTypeSystemDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === _kinds.Kind.DIRECTIVE_DEFINITION + ); + } + function isTypeDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || + node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || + node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || + node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || + node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || + node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION + ); + } + function isTypeSystemExtensionNode(node) { + return ( + node.kind === _kinds.Kind.SCHEMA_EXTENSION || + isTypeExtensionNode(node) + ); + } + function isTypeExtensionNode(node) { + return ( + node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || + node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || + node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || + node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || + node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || + node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION + ); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/jsutils/suggestionList.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/suggestionList.mjs ***! + /***/ "../../../node_modules/graphql/language/printLocation.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/language/printLocation.mjs ***! \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.suggestionList = suggestionList; -var _naturalCompare = __webpack_require__(/*! ./naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); -/** - * Given an invalid input string and a list of valid options, returns a filtered - * list of valid options sorted based on their similarity with the input. - */ - -function suggestionList(input, options) { - const optionsByDistance = Object.create(null); - const lexicalDistance = new LexicalDistance(input); - const threshold = Math.floor(input.length * 0.4) + 1; - for (const option of options) { - const distance = lexicalDistance.measure(option, threshold); - if (distance !== undefined) { - optionsByDistance[option] = distance; - } - } - return Object.keys(optionsByDistance).sort((a, b) => { - const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; - return distanceDiff !== 0 ? distanceDiff : (0, _naturalCompare.naturalCompare)(a, b); - }); -} -/** - * Computes the lexical distance between strings A and B. - * - * The "distance" between two strings is given by counting the minimum number - * of edits needed to transform string A into string B. An edit can be an - * insertion, deletion, or substitution of a single character, or a swap of two - * adjacent characters. - * - * Includes a custom alteration from Damerau-Levenshtein to treat case changes - * as a single edit which helps identify mis-cased values with an edit distance - * of 1. - * - * This distance can be useful for detecting typos in input or sorting - */ - -class LexicalDistance { - constructor(input) { - this._input = input; - this._inputLowerCase = input.toLowerCase(); - this._inputArray = stringToArray(this._inputLowerCase); - this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)]; - } - measure(option, threshold) { - if (this._input === option) { - return 0; - } - const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit - - if (this._inputLowerCase === optionLowerCase) { - return 1; - } - let a = stringToArray(optionLowerCase); - let b = this._inputArray; - if (a.length < b.length) { - const tmp = a; - a = b; - b = tmp; - } - const aLength = a.length; - const bLength = b.length; - if (aLength - bLength > threshold) { - return undefined; - } - const rows = this._rows; - for (let j = 0; j <= bLength; j++) { - rows[0][j] = j; - } - for (let i = 1; i <= aLength; i++) { - const upRow = rows[(i - 1) % 3]; - const currentRow = rows[i % 3]; - let smallestCell = currentRow[0] = i; - for (let j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - let currentCell = Math.min(upRow[j] + 1, - // delete - currentRow[j - 1] + 1, - // insert - upRow[j - 1] + cost // substitute - ); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - // transposition - const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; - currentCell = Math.min(currentCell, doubleDiagonalCell + 1); - } - if (currentCell < smallestCell) { - smallestCell = currentCell; - } - currentRow[j] = currentCell; - } // Early exit, since distance can't go smaller than smallest element of the previous row. - - if (smallestCell > threshold) { - return undefined; - } - } - const distance = rows[aLength % 3][bLength]; - return distance <= threshold ? distance : undefined; - } -} -function stringToArray(str) { - const strLength = str.length; - const array = new Array(strLength); - for (let i = 0; i < strLength; ++i) { - array[i] = str.charCodeAt(i); - } - return array; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.printLocation = printLocation; + exports.printSourceLocation = printSourceLocation; + var _location = __webpack_require__( + /*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs" + ); + /** + * Render a helpful description of the location in the GraphQL Source document. + */ + function printLocation(location) { + return printSourceLocation( + location.source, + (0, _location.getLocation)(location.source, location.start) + ); + } + /** + * Render a helpful description of the location in the GraphQL Source document. + */ -/***/ }), + function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = "".padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = + sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + return ( + locationStr + + printPrefixedLines([ + [`${lineNum} |`, subLines[0]], + ...subLines + .slice(1, subLineIndex + 1) + .map((subLine) => ["|", subLine]), + ["|", "^".padStart(subLineColumnNum)], + ["|", subLines[subLineIndex + 1]], + ]) + ); + } + return ( + locationStr + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1} |`, lines[lineIndex - 1]], + [`${lineNum} |`, locationLine], + ["|", "^".padStart(columnNum)], + [`${lineNum + 1} |`, lines[lineIndex + 1]], + ]) + ); + } + function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max( + ...existingLines.map(([prefix]) => prefix.length) + ); + return existingLines + .map( + ([prefix, line]) => + prefix.padStart(padLen) + (line ? " " + line : "") + ) + .join("\n"); + } -/***/ "../../../node_modules/graphql/jsutils/toError.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/toError.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.toError = toError; -var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -/** - * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. - */ - -function toError(thrownValue) { - return thrownValue instanceof Error ? thrownValue : new NonErrorThrown(thrownValue); -} -class NonErrorThrown extends Error { - constructor(thrownValue) { - super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); - this.name = 'NonErrorThrown'; - this.thrownValue = thrownValue; - } -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/graphql/language/printString.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/language/printString.mjs ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.printString = printString; + /** + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + */ + function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; + } // eslint-disable-next-line no-control-regex -/***/ "../../../node_modules/graphql/jsutils/toObjMap.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/toObjMap.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports) { + const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; +} // prettier-ignore + const escapeSequences = [ + "\\u0000", + "\\u0001", + "\\u0002", + "\\u0003", + "\\u0004", + "\\u0005", + "\\u0006", + "\\u0007", + "\\b", + "\\t", + "\\n", + "\\u000B", + "\\f", + "\\r", + "\\u000E", + "\\u000F", + "\\u0010", + "\\u0011", + "\\u0012", + "\\u0013", + "\\u0014", + "\\u0015", + "\\u0016", + "\\u0017", + "\\u0018", + "\\u0019", + "\\u001A", + "\\u001B", + "\\u001C", + "\\u001D", + "\\u001E", + "\\u001F", + "", + "", + '\\"', + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + // 2F + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + // 3F + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + // 4F + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "\\\\", + "", + "", + "", + // 5F + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + // 6F + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "\\u007F", + "\\u0080", + "\\u0081", + "\\u0082", + "\\u0083", + "\\u0084", + "\\u0085", + "\\u0086", + "\\u0087", + "\\u0088", + "\\u0089", + "\\u008A", + "\\u008B", + "\\u008C", + "\\u008D", + "\\u008E", + "\\u008F", + "\\u0090", + "\\u0091", + "\\u0092", + "\\u0093", + "\\u0094", + "\\u0095", + "\\u0096", + "\\u0097", + "\\u0098", + "\\u0099", + "\\u009A", + "\\u009B", + "\\u009C", + "\\u009D", + "\\u009E", + "\\u009F", + ]; + + /***/ + }, + /***/ "../../../node_modules/graphql/language/printer.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/language/printer.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.print = print; + var _blockString = __webpack_require__( + /*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs" + ); + var _printString = __webpack_require__( + /*! ./printString.mjs */ "../../../node_modules/graphql/language/printString.mjs" + ); + var _visitor = __webpack_require__( + /*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs" + ); + /** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.toObjMap = toObjMap; -function toObjMap(obj) { - if (obj == null) { - return Object.create(null); - } - if (Object.getPrototypeOf(obj) === null) { - return obj; - } - const map = Object.create(null); - for (const [key, value] of Object.entries(obj)) { - map[key] = value; - } - return map; -} + function print(ast) { + return (0, _visitor.visit)(ast, printDocASTReducer); + } + const MAX_LINE_LENGTH = 80; + const printDocASTReducer = { + Name: { + leave: (node) => node.value, + }, + Variable: { + leave: (node) => "$" + node.name, + }, + // Document + Document: { + leave: (node) => join(node.definitions, "\n\n"), + }, + OperationDefinition: { + leave(node) { + const varDefs = wrap( + "(", + join(node.variableDefinitions, ", "), + ")" + ); + const prefix = join( + [ + node.operation, + join([node.name, varDefs]), + join(node.directives, " "), + ], + " " + ); // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return ( + (prefix === "query" ? "" : prefix + " ") + node.selectionSet + ); + }, + }, + VariableDefinition: { + leave: ({ variable, type, defaultValue, directives }) => + variable + + ": " + + type + + wrap(" = ", defaultValue) + + wrap(" ", join(directives, " ")), + }, + SelectionSet: { + leave: ({ selections }) => block(selections), + }, + Field: { + leave({ alias, name, arguments: args, directives, selectionSet }) { + const prefix = wrap("", alias, ": ") + name; + let argsLine = prefix + wrap("(", join(args, ", "), ")"); + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = + prefix + wrap("(\n", indent(join(args, "\n")), "\n)"); + } + return join([argsLine, join(directives, " "), selectionSet], " "); + }, + }, + Argument: { + leave: ({ name, value }) => name + ": " + value, + }, + // Fragments + FragmentSpread: { + leave: ({ name, directives }) => + "..." + name + wrap(" ", join(directives, " ")), + }, + InlineFragment: { + leave: ({ typeCondition, directives, selectionSet }) => + join( + [ + "...", + wrap("on ", typeCondition), + join(directives, " "), + selectionSet, + ], + " " + ), + }, + FragmentDefinition: { + leave: ( + { + name, + typeCondition, + variableDefinitions, + directives, + selectionSet, + } // Note: fragment variable definitions are experimental and may be changed + ) => + // or removed in the future. + `fragment ${name}${wrap( + "(", + join(variableDefinitions, ", "), + ")" + )} ` + + `on ${typeCondition} ${wrap("", join(directives, " "), " ")}` + + selectionSet, + }, + // Value + IntValue: { + leave: ({ value }) => value, + }, + FloatValue: { + leave: ({ value }) => value, + }, + StringValue: { + leave: ({ value, block: isBlockString }) => + isBlockString + ? (0, _blockString.printBlockString)(value) + : (0, _printString.printString)(value), + }, + BooleanValue: { + leave: ({ value }) => (value ? "true" : "false"), + }, + NullValue: { + leave: () => "null", + }, + EnumValue: { + leave: ({ value }) => value, + }, + ListValue: { + leave: ({ values }) => "[" + join(values, ", ") + "]", + }, + ObjectValue: { + leave: ({ fields }) => "{" + join(fields, ", ") + "}", + }, + ObjectField: { + leave: ({ name, value }) => name + ": " + value, + }, + // Directive + Directive: { + leave: ({ name, arguments: args }) => + "@" + name + wrap("(", join(args, ", "), ")"), + }, + // Type + NamedType: { + leave: ({ name }) => name, + }, + ListType: { + leave: ({ type }) => "[" + type + "]", + }, + NonNullType: { + leave: ({ type }) => type + "!", + }, + // Type System Definitions + SchemaDefinition: { + leave: ({ description, directives, operationTypes }) => + wrap("", description, "\n") + + join( + ["schema", join(directives, " "), block(operationTypes)], + " " + ), + }, + OperationTypeDefinition: { + leave: ({ operation, type }) => operation + ": " + type, + }, + ScalarTypeDefinition: { + leave: ({ description, name, directives }) => + wrap("", description, "\n") + + join(["scalar", name, join(directives, " ")], " "), + }, + ObjectTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap("", description, "\n") + + join( + [ + "type", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields), + ], + " " + ), + }, + FieldDefinition: { + leave: ({ description, name, arguments: args, type, directives }) => + wrap("", description, "\n") + + name + + (hasMultilineItems(args) + ? wrap("(\n", indent(join(args, "\n")), "\n)") + : wrap("(", join(args, ", "), ")")) + + ": " + + type + + wrap(" ", join(directives, " ")), + }, + InputValueDefinition: { + leave: ({ description, name, type, defaultValue, directives }) => + wrap("", description, "\n") + + join( + [ + name + ": " + type, + wrap("= ", defaultValue), + join(directives, " "), + ], + " " + ), + }, + InterfaceTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap("", description, "\n") + + join( + [ + "interface", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields), + ], + " " + ), + }, + UnionTypeDefinition: { + leave: ({ description, name, directives, types }) => + wrap("", description, "\n") + + join( + [ + "union", + name, + join(directives, " "), + wrap("= ", join(types, " | ")), + ], + " " + ), + }, + EnumTypeDefinition: { + leave: ({ description, name, directives, values }) => + wrap("", description, "\n") + + join(["enum", name, join(directives, " "), block(values)], " "), + }, + EnumValueDefinition: { + leave: ({ description, name, directives }) => + wrap("", description, "\n") + + join([name, join(directives, " ")], " "), + }, + InputObjectTypeDefinition: { + leave: ({ description, name, directives, fields }) => + wrap("", description, "\n") + + join(["input", name, join(directives, " "), block(fields)], " "), + }, + DirectiveDefinition: { + leave: ({ + description, + name, + arguments: args, + repeatable, + locations, + }) => + wrap("", description, "\n") + + "directive @" + + name + + (hasMultilineItems(args) + ? wrap("(\n", indent(join(args, "\n")), "\n)") + : wrap("(", join(args, ", "), ")")) + + (repeatable ? " repeatable" : "") + + " on " + + join(locations, " | "), + }, + SchemaExtension: { + leave: ({ directives, operationTypes }) => + join( + ["extend schema", join(directives, " "), block(operationTypes)], + " " + ), + }, + ScalarTypeExtension: { + leave: ({ name, directives }) => + join(["extend scalar", name, join(directives, " ")], " "), + }, + ObjectTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + "extend type", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields), + ], + " " + ), + }, + InterfaceTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + "extend interface", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields), + ], + " " + ), + }, + UnionTypeExtension: { + leave: ({ name, directives, types }) => + join( + [ + "extend union", + name, + join(directives, " "), + wrap("= ", join(types, " | ")), + ], + " " + ), + }, + EnumTypeExtension: { + leave: ({ name, directives, values }) => + join( + ["extend enum", name, join(directives, " "), block(values)], + " " + ), + }, + InputObjectTypeExtension: { + leave: ({ name, directives, fields }) => + join( + ["extend input", name, join(directives, " "), block(fields)], + " " + ), + }, + }; + /** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ -/***/ }), + function join(maybeArray, separator = "") { + var _maybeArray$filter$jo; + return (_maybeArray$filter$jo = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.filter((x) => x).join(separator)) !== null && + _maybeArray$filter$jo !== void 0 + ? _maybeArray$filter$jo + : ""; + } + /** + * Given array, print each item on its own line, wrapped in an indented `{ }` block. + */ -/***/ "../../../node_modules/graphql/language/ast.mjs": -/*!******************************************************!*\ - !*** ../../../node_modules/graphql/language/ast.mjs ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Token = exports.QueryDocumentKeys = exports.OperationTypeNode = exports.Location = void 0; -exports.isNode = isNode; -/** - * Contains a range of UTF-8 character offsets and token references that - * identify the region of the source from which the AST derived. - */ -class Location { - /** - * The character offset at which this Node begins. - */ - - /** - * The character offset at which this Node ends. - */ - - /** - * The Token at which this Node begins. - */ - - /** - * The Token at which this Node ends. - */ - - /** - * The Source document the AST represents. - */ - constructor(startToken, endToken, source) { - this.start = startToken.start; - this.end = endToken.end; - this.startToken = startToken; - this.endToken = endToken; - this.source = source; - } - get [Symbol.toStringTag]() { - return 'Location'; - } - toJSON() { - return { - start: this.start, - end: this.end - }; - } -} -/** - * Represents a range of characters represented by a lexical token - * within a Source. - */ -exports.Location = Location; -class Token { - /** - * The kind of Token. - */ - - /** - * The character offset at which this Node begins. - */ - - /** - * The character offset at which this Node ends. - */ - - /** - * The 1-indexed line number on which this Token appears. - */ - - /** - * The 1-indexed column number at which this Token begins. - */ - - /** - * For non-punctuation tokens, represents the interpreted value of the token. - * - * Note: is undefined for punctuation tokens, but typed as string for - * convenience in the parser. - */ - - /** - * Tokens exist as nodes in a double-linked-list amongst all tokens - * including ignored tokens. is always the first node and - * the last. - */ - constructor(kind, start, end, line, column, value) { - this.kind = kind; - this.start = start; - this.end = end; - this.line = line; - this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - - this.value = value; - this.prev = null; - this.next = null; - } - get [Symbol.toStringTag]() { - return 'Token'; - } - toJSON() { - return { - kind: this.kind, - value: this.value, - line: this.line, - column: this.column - }; - } -} -/** - * The list of all possible AST node types. - */ - -/** - * @internal - */ -exports.Token = Token; -const QueryDocumentKeys = exports.QueryDocumentKeys = { - Name: [], - Document: ['definitions'], - OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], - VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], - Variable: ['name'], - SelectionSet: ['selections'], - Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], - Argument: ['name', 'value'], - FragmentSpread: ['name', 'directives'], - InlineFragment: ['typeCondition', 'directives', 'selectionSet'], - FragmentDefinition: ['name', - // Note: fragment variable definitions are deprecated and will removed in v17.0.0 - 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], - IntValue: [], - FloatValue: [], - StringValue: [], - BooleanValue: [], - NullValue: [], - EnumValue: [], - ListValue: ['values'], - ObjectValue: ['fields'], - ObjectField: ['name', 'value'], - Directive: ['name', 'arguments'], - NamedType: ['name'], - ListType: ['type'], - NonNullType: ['type'], - SchemaDefinition: ['description', 'directives', 'operationTypes'], - OperationTypeDefinition: ['type'], - ScalarTypeDefinition: ['description', 'name', 'directives'], - ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], - FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], - InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], - InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], - UnionTypeDefinition: ['description', 'name', 'directives', 'types'], - EnumTypeDefinition: ['description', 'name', 'directives', 'values'], - EnumValueDefinition: ['description', 'name', 'directives'], - InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], - DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], - SchemaExtension: ['directives', 'operationTypes'], - ScalarTypeExtension: ['name', 'directives'], - ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], - InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], - UnionTypeExtension: ['name', 'directives', 'types'], - EnumTypeExtension: ['name', 'directives', 'values'], - InputObjectTypeExtension: ['name', 'directives', 'fields'] -}; -const kindValues = new Set(Object.keys(QueryDocumentKeys)); -/** - * @internal - */ - -function isNode(maybeNode) { - const maybeKind = maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; - return typeof maybeKind === 'string' && kindValues.has(maybeKind); -} -/** Name */ - -var OperationTypeNode; -(function (OperationTypeNode) { - OperationTypeNode['QUERY'] = 'query'; - OperationTypeNode['MUTATION'] = 'mutation'; - OperationTypeNode['SUBSCRIPTION'] = 'subscription'; -})(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); - -/***/ }), - -/***/ "../../../node_modules/graphql/language/blockString.mjs": -/*!**************************************************************!*\ - !*** ../../../node_modules/graphql/language/blockString.mjs ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.dedentBlockStringLines = dedentBlockStringLines; -exports.isPrintableAsBlockString = isPrintableAsBlockString; -exports.printBlockString = printBlockString; -var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); -/** - * Produces the value of a block string from its parsed raw value, similar to - * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. - * - * This implements the GraphQL spec's BlockStringValue() static algorithm. - * - * @internal - */ - -function dedentBlockStringLines(lines) { - var _firstNonEmptyLine2; - let commonIndent = Number.MAX_SAFE_INTEGER; - let firstNonEmptyLine = null; - let lastNonEmptyLine = -1; - for (let i = 0; i < lines.length; ++i) { - var _firstNonEmptyLine; - const line = lines[i]; - const indent = leadingWhitespace(line); - if (indent === line.length) { - continue; // skip empty lines - } - firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i; - lastNonEmptyLine = i; - if (i !== 0 && indent < commonIndent) { - commonIndent = indent; - } - } - return lines // Remove common indentation from all lines but first. - .map((line, i) => i === 0 ? line : line.slice(commonIndent)) // Remove leading and trailing blank lines. - .slice((_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0, lastNonEmptyLine + 1); -} -function leadingWhitespace(str) { - let i = 0; - while (i < str.length && (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i))) { - ++i; - } - return i; -} -/** - * @internal - */ - -function isPrintableAsBlockString(value) { - if (value === '') { - return true; // empty string is printable - } - let isEmptyLine = true; - let hasIndent = false; - let hasCommonIndent = true; - let seenNonEmptyLine = false; - for (let i = 0; i < value.length; ++i) { - switch (value.codePointAt(i)) { - case 0x0000: - case 0x0001: - case 0x0002: - case 0x0003: - case 0x0004: - case 0x0005: - case 0x0006: - case 0x0007: - case 0x0008: - case 0x000b: - case 0x000c: - case 0x000e: - case 0x000f: - return false; - // Has non-printable characters - - case 0x000d: - // \r - return false; - // Has \r or \r\n which will be replaced as \n - - case 10: - // \n - if (isEmptyLine && !seenNonEmptyLine) { - return false; // Has leading new line - } - seenNonEmptyLine = true; - isEmptyLine = true; - hasIndent = false; - break; - case 9: // \t - - case 32: - // - hasIndent || (hasIndent = isEmptyLine); - break; - default: - hasCommonIndent && (hasCommonIndent = hasIndent); - isEmptyLine = false; - } - } - if (isEmptyLine) { - return false; // Has trailing empty lines - } - if (hasCommonIndent && seenNonEmptyLine) { - return false; // Has internal indent - } - return true; -} -/** - * Print a block string in the indented block form by adding a leading and - * trailing blank line. However, if a block string starts with whitespace and is - * a single-line, adding a leading blank line would strip that whitespace. - * - * @internal - */ - -function printBlockString(value, options) { - const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. - - const lines = escapedValue.split(/\r\n|[\n\r]/g); - const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line - - const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every(line => line.length === 0 || (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line - - const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line - - const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; - const hasTrailingSlash = value.endsWith('\\'); - const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; - const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && ( - // add leading and trailing new lines only if it improves readability - !isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes); - let result = ''; // Format a multi-line block quote to account for leading space. - - const skipLeadingNewLine = isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); - if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) { - result += '\n'; - } - result += escapedValue; - if (printAsMultipleLines || forceTrailingNewline) { - result += '\n'; - } - return '"""' + result + '"""'; -} + function block(array) { + return wrap("{\n", indent(join(array, "\n")), "\n}"); + } + /** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ -/***/ }), + function wrap(start, maybeString, end = "") { + return maybeString != null && maybeString !== "" + ? start + maybeString + end + : ""; + } + function indent(str) { + return wrap(" ", str.replace(/\n/g, "\n ")); + } + function hasMultilineItems(maybeArray) { + var _maybeArray$some; -/***/ "../../../node_modules/graphql/language/characterClasses.mjs": -/*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/language/characterClasses.mjs ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isDigit = isDigit; -exports.isLetter = isLetter; -exports.isNameContinue = isNameContinue; -exports.isNameStart = isNameStart; -exports.isWhiteSpace = isWhiteSpace; -/** - * ``` - * WhiteSpace :: - * - "Horizontal Tab (U+0009)" - * - "Space (U+0020)" - * ``` - * @internal - */ -function isWhiteSpace(code) { - return code === 0x0009 || code === 0x0020; -} -/** - * ``` - * Digit :: one of - * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` - * ``` - * @internal - */ - -function isDigit(code) { - return code >= 0x0030 && code <= 0x0039; -} -/** - * ``` - * Letter :: one of - * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` - * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` - * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` - * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` - * ``` - * @internal - */ - -function isLetter(code) { - return code >= 0x0061 && code <= 0x007a || - // A-Z - code >= 0x0041 && code <= 0x005a // a-z - ; -} -/** - * ``` - * NameStart :: - * - Letter - * - `_` - * ``` - * @internal - */ - -function isNameStart(code) { - return isLetter(code) || code === 0x005f; -} -/** - * ``` - * NameContinue :: - * - Letter - * - Digit - * - `_` - * ``` - * @internal - */ - -function isNameContinue(code) { - return isLetter(code) || isDigit(code) || code === 0x005f; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/language/directiveLocation.mjs": -/*!********************************************************************!*\ - !*** ../../../node_modules/graphql/language/directiveLocation.mjs ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.DirectiveLocation = void 0; -/** - * The set of allowed directive location values. - */ -var DirectiveLocation; -(function (DirectiveLocation) { - DirectiveLocation['QUERY'] = 'QUERY'; - DirectiveLocation['MUTATION'] = 'MUTATION'; - DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; - DirectiveLocation['FIELD'] = 'FIELD'; - DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; - DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; - DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; - DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; - DirectiveLocation['SCHEMA'] = 'SCHEMA'; - DirectiveLocation['SCALAR'] = 'SCALAR'; - DirectiveLocation['OBJECT'] = 'OBJECT'; - DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; - DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; - DirectiveLocation['INTERFACE'] = 'INTERFACE'; - DirectiveLocation['UNION'] = 'UNION'; - DirectiveLocation['ENUM'] = 'ENUM'; - DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; - DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; - DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; -})(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); - -/** - * The enum type representing the directive location values. - * - * @deprecated Please use `DirectiveLocation`. Will be remove in v17. - */ - -/***/ }), - -/***/ "../../../node_modules/graphql/language/index.mjs": -/*!********************************************************!*\ - !*** ../../../node_modules/graphql/language/index.mjs ***! - \********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + return (_maybeArray$some = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.some((str) => str.includes("\n"))) !== null && + _maybeArray$some !== void 0 + ? _maybeArray$some + : false; + } + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "BREAK", ({ - enumerable: true, - get: function () { - return _visitor.BREAK; - } -})); -Object.defineProperty(exports, "DirectiveLocation", ({ - enumerable: true, - get: function () { - return _directiveLocation.DirectiveLocation; - } -})); -Object.defineProperty(exports, "Kind", ({ - enumerable: true, - get: function () { - return _kinds.Kind; - } -})); -Object.defineProperty(exports, "Lexer", ({ - enumerable: true, - get: function () { - return _lexer.Lexer; - } -})); -Object.defineProperty(exports, "Location", ({ - enumerable: true, - get: function () { - return _ast.Location; - } -})); -Object.defineProperty(exports, "OperationTypeNode", ({ - enumerable: true, - get: function () { - return _ast.OperationTypeNode; - } -})); -Object.defineProperty(exports, "Source", ({ - enumerable: true, - get: function () { - return _source.Source; - } -})); -Object.defineProperty(exports, "Token", ({ - enumerable: true, - get: function () { - return _ast.Token; - } -})); -Object.defineProperty(exports, "TokenKind", ({ - enumerable: true, - get: function () { - return _tokenKind.TokenKind; - } -})); -Object.defineProperty(exports, "getEnterLeaveForKind", ({ - enumerable: true, - get: function () { - return _visitor.getEnterLeaveForKind; - } -})); -Object.defineProperty(exports, "getLocation", ({ - enumerable: true, - get: function () { - return _location.getLocation; - } -})); -Object.defineProperty(exports, "getVisitFn", ({ - enumerable: true, - get: function () { - return _visitor.getVisitFn; - } -})); -Object.defineProperty(exports, "isConstValueNode", ({ - enumerable: true, - get: function () { - return _predicates.isConstValueNode; - } -})); -Object.defineProperty(exports, "isDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isDefinitionNode; - } -})); -Object.defineProperty(exports, "isExecutableDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isExecutableDefinitionNode; - } -})); -Object.defineProperty(exports, "isSelectionNode", ({ - enumerable: true, - get: function () { - return _predicates.isSelectionNode; - } -})); -Object.defineProperty(exports, "isTypeDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeDefinitionNode; - } -})); -Object.defineProperty(exports, "isTypeExtensionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeExtensionNode; - } -})); -Object.defineProperty(exports, "isTypeNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeNode; - } -})); -Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeSystemDefinitionNode; - } -})); -Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeSystemExtensionNode; - } -})); -Object.defineProperty(exports, "isValueNode", ({ - enumerable: true, - get: function () { - return _predicates.isValueNode; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parser.parse; - } -})); -Object.defineProperty(exports, "parseConstValue", ({ - enumerable: true, - get: function () { - return _parser.parseConstValue; - } -})); -Object.defineProperty(exports, "parseType", ({ - enumerable: true, - get: function () { - return _parser.parseType; - } -})); -Object.defineProperty(exports, "parseValue", ({ - enumerable: true, - get: function () { - return _parser.parseValue; - } -})); -Object.defineProperty(exports, "print", ({ - enumerable: true, - get: function () { - return _printer.print; - } -})); -Object.defineProperty(exports, "printLocation", ({ - enumerable: true, - get: function () { - return _printLocation.printLocation; - } -})); -Object.defineProperty(exports, "printSourceLocation", ({ - enumerable: true, - get: function () { - return _printLocation.printSourceLocation; - } -})); -Object.defineProperty(exports, "visit", ({ - enumerable: true, - get: function () { - return _visitor.visit; - } -})); -Object.defineProperty(exports, "visitInParallel", ({ - enumerable: true, - get: function () { - return _visitor.visitInParallel; - } -})); -var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); -var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); -var _printLocation = __webpack_require__(/*! ./printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); -var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); -var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); -var _parser = __webpack_require__(/*! ./parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); -var _printer = __webpack_require__(/*! ./printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); -var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _predicates = __webpack_require__(/*! ./predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); -var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); - -/***/ }), - -/***/ "../../../node_modules/graphql/language/kinds.mjs": -/*!********************************************************!*\ - !*** ../../../node_modules/graphql/language/kinds.mjs ***! - \********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Kind = void 0; -/** - * The set of allowed kind values for AST nodes. - */ -var Kind; -(function (Kind) { - Kind['NAME'] = 'Name'; - Kind['DOCUMENT'] = 'Document'; - Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; - Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; - Kind['SELECTION_SET'] = 'SelectionSet'; - Kind['FIELD'] = 'Field'; - Kind['ARGUMENT'] = 'Argument'; - Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; - Kind['INLINE_FRAGMENT'] = 'InlineFragment'; - Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; - Kind['VARIABLE'] = 'Variable'; - Kind['INT'] = 'IntValue'; - Kind['FLOAT'] = 'FloatValue'; - Kind['STRING'] = 'StringValue'; - Kind['BOOLEAN'] = 'BooleanValue'; - Kind['NULL'] = 'NullValue'; - Kind['ENUM'] = 'EnumValue'; - Kind['LIST'] = 'ListValue'; - Kind['OBJECT'] = 'ObjectValue'; - Kind['OBJECT_FIELD'] = 'ObjectField'; - Kind['DIRECTIVE'] = 'Directive'; - Kind['NAMED_TYPE'] = 'NamedType'; - Kind['LIST_TYPE'] = 'ListType'; - Kind['NON_NULL_TYPE'] = 'NonNullType'; - Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; - Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; - Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; - Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; - Kind['FIELD_DEFINITION'] = 'FieldDefinition'; - Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; - Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; - Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; - Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; - Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; - Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; - Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; - Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; - Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; - Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; - Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; - Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; - Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; - Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; -})(Kind || (exports.Kind = Kind = {})); - -/** - * The enum type representing the possible kind values of AST nodes. - * - * @deprecated Please use `Kind`. Will be remove in v17. - */ - -/***/ }), - -/***/ "../../../node_modules/graphql/language/lexer.mjs": -/*!********************************************************!*\ - !*** ../../../node_modules/graphql/language/lexer.mjs ***! - \********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Lexer = void 0; -exports.isPunctuatorTokenKind = isPunctuatorTokenKind; -var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); -var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); -var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); -var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); -/** - * Given a Source object, creates a Lexer for that source. - * A Lexer is a stateful stream generator in that every time - * it is advanced, it returns the next token in the Source. Assuming the - * source lexes, the final Token emitted by the lexer will be of kind - * EOF, after which the lexer will repeatedly return the same EOF token - * whenever called. - */ - -class Lexer { - /** - * The previously focused non-ignored token. - */ - - /** - * The currently focused non-ignored token. - */ - - /** - * The (1-indexed) line containing the current token. - */ - - /** - * The character offset at which the current line begins. - */ - constructor(source) { - const startOfFileToken = new _ast.Token(_tokenKind.TokenKind.SOF, 0, 0, 0, 0); - this.source = source; - this.lastToken = startOfFileToken; - this.token = startOfFileToken; - this.line = 1; - this.lineStart = 0; - } - get [Symbol.toStringTag]() { - return 'Lexer'; - } - /** - * Advances the token stream to the next non-ignored token. - */ - - advance() { - this.lastToken = this.token; - const token = this.token = this.lookahead(); - return token; - } - /** - * Looks ahead and returns the next non-ignored token, but does not change - * the state of Lexer. - */ - - lookahead() { - let token = this.token; - if (token.kind !== _tokenKind.TokenKind.EOF) { - do { - if (token.next) { - token = token.next; - } else { - // Read the next token and form a link in the token linked-list. - const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + /***/ "../../../node_modules/graphql/language/source.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/language/source.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Source = void 0; + exports.isSource = isSource; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _instanceOf = __webpack_require__( + /*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs" + ); + /** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ + class Source { + constructor( + body, + name = "GraphQL request", + locationOffset = { + line: 1, + column: 1, + } + ) { + typeof body === "string" || + (0, _devAssert.devAssert)( + false, + `Body must be a string. Received: ${(0, _inspect.inspect)( + body + )}.` + ); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || + (0, _devAssert.devAssert)( + false, + "line in locationOffset is 1-indexed and must be positive." + ); + this.locationOffset.column > 0 || + (0, _devAssert.devAssert)( + false, + "column in locationOffset is 1-indexed and must be positive." + ); + } + get [Symbol.toStringTag]() { + return "Source"; + } + } + /** + * Test if the given value is a Source object. + * + * @internal + */ + exports.Source = Source; + function isSource(source) { + return (0, _instanceOf.instanceOf)(source, Source); + } - token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + /***/ + }, - nextToken.prev = token; - token = nextToken; - } - } while (token.kind === _tokenKind.TokenKind.COMMENT); - } - return token; - } -} -/** - * @internal - */ -exports.Lexer = Lexer; -function isPunctuatorTokenKind(kind) { - return kind === _tokenKind.TokenKind.BANG || kind === _tokenKind.TokenKind.DOLLAR || kind === _tokenKind.TokenKind.AMP || kind === _tokenKind.TokenKind.PAREN_L || kind === _tokenKind.TokenKind.PAREN_R || kind === _tokenKind.TokenKind.SPREAD || kind === _tokenKind.TokenKind.COLON || kind === _tokenKind.TokenKind.EQUALS || kind === _tokenKind.TokenKind.AT || kind === _tokenKind.TokenKind.BRACKET_L || kind === _tokenKind.TokenKind.BRACKET_R || kind === _tokenKind.TokenKind.BRACE_L || kind === _tokenKind.TokenKind.PIPE || kind === _tokenKind.TokenKind.BRACE_R; -} -/** - * A Unicode scalar value is any Unicode code point except surrogate code - * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and - * 0xE000 to 0x10FFFF. - * - * SourceCharacter :: - * - "Any Unicode scalar value" - */ - -function isUnicodeScalarValue(code) { - return code >= 0x0000 && code <= 0xd7ff || code >= 0xe000 && code <= 0x10ffff; -} -/** - * The GraphQL specification defines source text as a sequence of unicode scalar - * values (which Unicode defines to exclude surrogate code points). However - * JavaScript defines strings as a sequence of UTF-16 code units which may - * include surrogates. A surrogate pair is a valid source character as it - * encodes a supplementary code point (above U+FFFF), but unpaired surrogate - * code points are not valid source characters. - */ - -function isSupplementaryCodePoint(body, location) { - return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1)); -} -function isLeadingSurrogate(code) { - return code >= 0xd800 && code <= 0xdbff; -} -function isTrailingSurrogate(code) { - return code >= 0xdc00 && code <= 0xdfff; -} -/** - * Prints the code point (or end of file reference) at a given location in a - * source for use in error messages. - * - * Printable ASCII is printed quoted, while other points are printed in Unicode - * code point form (ie. U+1234). - */ - -function printCodePointAt(lexer, location) { - const code = lexer.source.body.codePointAt(location); - if (code === undefined) { - return _tokenKind.TokenKind.EOF; - } else if (code >= 0x0020 && code <= 0x007e) { - // Printable ASCII - const char = String.fromCodePoint(code); - return char === '"' ? "'\"'" : `"${char}"`; - } // Unicode code point - - return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); -} -/** - * Create a token with line and column location information. - */ - -function createToken(lexer, kind, start, end, value) { - const line = lexer.line; - const col = 1 + start - lexer.lineStart; - return new _ast.Token(kind, start, end, line, col, value); -} -/** - * Gets the next token from the source starting at the given position. - * - * This skips over whitespace until it finds the next lexable token, then lexes - * punctuators immediately or calls the appropriate helper function for more - * complicated tokens. - */ - -function readNextToken(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start; - while (position < bodyLength) { - const code = body.charCodeAt(position); // SourceCharacter - - switch (code) { - // Ignored :: - // - UnicodeBOM - // - WhiteSpace - // - LineTerminator - // - Comment - // - Comma - // - // UnicodeBOM :: "Byte Order Mark (U+FEFF)" - // - // WhiteSpace :: - // - "Horizontal Tab (U+0009)" - // - "Space (U+0020)" - // - // Comma :: , - case 0xfeff: // - - case 0x0009: // \t - - case 0x0020: // - - case 0x002c: - // , - ++position; - continue; - // LineTerminator :: - // - "New Line (U+000A)" - // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] - // - "Carriage Return (U+000D)" "New Line (U+000A)" - - case 0x000a: - // \n - ++position; - ++lexer.line; - lexer.lineStart = position; - continue; - case 0x000d: - // \r - if (body.charCodeAt(position + 1) === 0x000a) { - position += 2; - } else { - ++position; - } - ++lexer.line; - lexer.lineStart = position; - continue; - // Comment - - case 0x0023: - // # - return readComment(lexer, position); - // Token :: - // - Punctuator - // - Name - // - IntValue - // - FloatValue - // - StringValue - // - // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } - - case 0x0021: - // ! - return createToken(lexer, _tokenKind.TokenKind.BANG, position, position + 1); - case 0x0024: - // $ - return createToken(lexer, _tokenKind.TokenKind.DOLLAR, position, position + 1); - case 0x0026: - // & - return createToken(lexer, _tokenKind.TokenKind.AMP, position, position + 1); - case 0x0028: - // ( - return createToken(lexer, _tokenKind.TokenKind.PAREN_L, position, position + 1); - case 0x0029: - // ) - return createToken(lexer, _tokenKind.TokenKind.PAREN_R, position, position + 1); - case 0x002e: - // . - if (body.charCodeAt(position + 1) === 0x002e && body.charCodeAt(position + 2) === 0x002e) { - return createToken(lexer, _tokenKind.TokenKind.SPREAD, position, position + 3); - } - break; - case 0x003a: - // : - return createToken(lexer, _tokenKind.TokenKind.COLON, position, position + 1); - case 0x003d: - // = - return createToken(lexer, _tokenKind.TokenKind.EQUALS, position, position + 1); - case 0x0040: - // @ - return createToken(lexer, _tokenKind.TokenKind.AT, position, position + 1); - case 0x005b: - // [ - return createToken(lexer, _tokenKind.TokenKind.BRACKET_L, position, position + 1); - case 0x005d: - // ] - return createToken(lexer, _tokenKind.TokenKind.BRACKET_R, position, position + 1); - case 0x007b: - // { - return createToken(lexer, _tokenKind.TokenKind.BRACE_L, position, position + 1); - case 0x007c: - // | - return createToken(lexer, _tokenKind.TokenKind.PIPE, position, position + 1); - case 0x007d: - // } - return createToken(lexer, _tokenKind.TokenKind.BRACE_R, position, position + 1); - // StringValue + /***/ "../../../node_modules/graphql/language/tokenKind.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/language/tokenKind.mjs ***! + \************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.TokenKind = void 0; + /** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ + var TokenKind; + (function (TokenKind) { + TokenKind["SOF"] = ""; + TokenKind["EOF"] = ""; + TokenKind["BANG"] = "!"; + TokenKind["DOLLAR"] = "$"; + TokenKind["AMP"] = "&"; + TokenKind["PAREN_L"] = "("; + TokenKind["PAREN_R"] = ")"; + TokenKind["SPREAD"] = "..."; + TokenKind["COLON"] = ":"; + TokenKind["EQUALS"] = "="; + TokenKind["AT"] = "@"; + TokenKind["BRACKET_L"] = "["; + TokenKind["BRACKET_R"] = "]"; + TokenKind["BRACE_L"] = "{"; + TokenKind["PIPE"] = "|"; + TokenKind["BRACE_R"] = "}"; + TokenKind["NAME"] = "Name"; + TokenKind["INT"] = "Int"; + TokenKind["FLOAT"] = "Float"; + TokenKind["STRING"] = "String"; + TokenKind["BLOCK_STRING"] = "BlockString"; + TokenKind["COMMENT"] = "Comment"; + })(TokenKind || (exports.TokenKind = TokenKind = {})); - case 0x0022: - // " - if (body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { - return readBlockString(lexer, position); - } - return readString(lexer, position); - } // IntValue | FloatValue (Digit | -) + /** + * The enum type representing the token kinds values. + * + * @deprecated Please use `TokenKind`. Will be remove in v17. + */ - if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { - return readNumber(lexer, position, code); - } // Name + /***/ + }, - if ((0, _characterClasses.isNameStart)(code)) { - return readName(lexer, position); - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, code === 0x0027 ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`); - } - return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); -} -/** - * Reads a comment token from the source file. - * - * ``` - * Comment :: # CommentChar* [lookahead != CommentChar] - * - * CommentChar :: SourceCharacter but not LineTerminator - * ``` - */ - -function readComment(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - while (position < bodyLength) { - const code = body.charCodeAt(position); // LineTerminator (\n | \r) - - if (code === 0x000a || code === 0x000d) { - break; - } // SourceCharacter - - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - break; - } - } - return createToken(lexer, _tokenKind.TokenKind.COMMENT, start, position, body.slice(start + 1, position)); -} -/** - * Reads a number token from the source file, either a FloatValue or an IntValue - * depending on whether a FractionalPart or ExponentPart is encountered. - * - * ``` - * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] - * - * IntegerPart :: - * - NegativeSign? 0 - * - NegativeSign? NonZeroDigit Digit* - * - * NegativeSign :: - - * - * NonZeroDigit :: Digit but not `0` - * - * FloatValue :: - * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] - * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] - * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] - * - * FractionalPart :: . Digit+ - * - * ExponentPart :: ExponentIndicator Sign? Digit+ - * - * ExponentIndicator :: one of `e` `E` - * - * Sign :: one of + - - * ``` - */ - -function readNumber(lexer, start, firstCode) { - const body = lexer.source.body; - let position = start; - let code = firstCode; - let isFloat = false; // NegativeSign (-) - - if (code === 0x002d) { - code = body.charCodeAt(++position); - } // Zero (0) - - if (code === 0x0030) { - code = body.charCodeAt(++position); - if ((0, _characterClasses.isDigit)(code)) { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, unexpected digit after 0: ${printCodePointAt(lexer, position)}.`); - } - } else { - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // Full stop (.) - - if (code === 0x002e) { - isFloat = true; - code = body.charCodeAt(++position); - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // E e - - if (code === 0x0045 || code === 0x0065) { - isFloat = true; - code = body.charCodeAt(++position); // + - - - if (code === 0x002b || code === 0x002d) { - code = body.charCodeAt(++position); - } - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // Numbers cannot be followed by . or NameStart + /***/ "../../../node_modules/graphql/language/visitor.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/language/visitor.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.BREAK = void 0; + exports.getEnterLeaveForKind = getEnterLeaveForKind; + exports.getVisitFn = getVisitFn; + exports.visit = visit; + exports.visitInParallel = visitInParallel; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _ast = __webpack_require__( + /*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _kinds = __webpack_require__( + /*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + /** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ - if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, expected digit but got: ${printCodePointAt(lexer, position)}.`); - } - return createToken(lexer, isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, start, position, body.slice(start, position)); -} -/** - * Returns the new position in the source after reading one or more digits. - */ - -function readDigits(lexer, start, firstCode) { - if (!(0, _characterClasses.isDigit)(firstCode)) { - throw (0, _syntaxError.syntaxError)(lexer.source, start, `Invalid number, expected digit but got: ${printCodePointAt(lexer, start)}.`); - } - const body = lexer.source.body; - let position = start + 1; // +1 to skip first firstCode + const BREAK = (exports.BREAK = Object.freeze({})); + /** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * ```ts + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * ``` + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to three permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * ``` + * + * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * ``` + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * ```ts + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * ``` + */ - while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { - ++position; - } - return position; -} -/** - * Reads a single-quote string token from the source file. - * - * ``` - * StringValue :: - * - `""` [lookahead != `"`] - * - `"` StringCharacter+ `"` - * - * StringCharacter :: - * - SourceCharacter but not `"` or `\` or LineTerminator - * - `\u` EscapedUnicode - * - `\` EscapedCharacter - * - * EscapedUnicode :: - * - `{` HexDigit+ `}` - * - HexDigit HexDigit HexDigit HexDigit - * - * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` - * ``` - */ - -function readString(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - let chunkStart = position; - let value = ''; - while (position < bodyLength) { - const code = body.charCodeAt(position); // Closing Quote (") - - if (code === 0x0022) { - value += body.slice(chunkStart, position); - return createToken(lexer, _tokenKind.TokenKind.STRING, start, position + 1, value); - } // Escape Sequence (\) - - if (code === 0x005c) { - value += body.slice(chunkStart, position); - const escape = body.charCodeAt(position + 1) === 0x0075 // u - ? body.charCodeAt(position + 2) === 0x007b // { - ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position); - value += escape.value; - position += escape.size; - chunkStart = position; - continue; - } // LineTerminator (\n | \r) - - if (code === 0x000a || code === 0x000d) { - break; - } // SourceCharacter - - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); - } - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); -} // The string value and lexed size of an escape sequence. + function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { + const enterLeaveMap = new Map(); + for (const kind of Object.values(_kinds.Kind)) { + enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); + } + /* eslint-disable no-undef-init */ + + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; + } + } + } else { + node = Object.defineProperties( + {}, + Object.getOwnPropertyDescriptors(node) + ); + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } + } + } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent) { + key = inArray ? index : keys[index]; + node = parent[key]; + if (node === null || node === undefined) { + continue; + } + path.push(key); + } + let result; + if (!Array.isArray(node)) { + var _enterLeaveMap$get, _enterLeaveMap$get2; + (0, _ast.isNode)(node) || + (0, _devAssert.devAssert)( + false, + `Invalid AST Node: ${(0, _inspect.inspect)(node)}.` + ); + const visitFn = isLeaving + ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === + null || _enterLeaveMap$get === void 0 + ? void 0 + : _enterLeaveMap$get.leave + : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === + null || _enterLeaveMap$get2 === void 0 + ? void 0 + : _enterLeaveMap$get2.enter; + result = + visitFn === null || visitFn === void 0 + ? void 0 + : visitFn.call(visitor, node, key, parent, path, ancestors); + if (result === BREAK) { + break; + } + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if ((0, _ast.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + if (result === undefined && isEdited) { + edits.push([key, node]); + } + if (isLeaving) { + path.pop(); + } else { + var _node$kind; + stack = { + inArray, + index, + keys, + edits, + prev: stack, + }; + inArray = Array.isArray(node); + keys = inArray + ? node + : (_node$kind = visitorKeys[node.kind]) !== null && + _node$kind !== void 0 + ? _node$kind + : []; + index = -1; + edits = []; + if (parent) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + if (edits.length !== 0) { + // New root + return edits[edits.length - 1][1]; + } + return root; + } + /** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ -function readEscapedUnicodeVariableWidth(lexer, position) { - const body = lexer.source.body; - let point = 0; - let size = 3; // Cannot be larger than 12 chars (\u{00000000}). + function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); + for (const kind of Object.values(_kinds.Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + for (let i = 0; i < visitors.length; ++i) { + const { enter, leave } = getEnterLeaveForKind(visitors[i], kind); + hasVisitor || (hasVisitor = enter != null || leave != null); + enterList[i] = enter; + leaveList[i] = leave; + } + if (!hasVisitor) { + continue; + } + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _enterList$i; + const result = + (_enterList$i = enterList[i]) === null || + _enterList$i === void 0 + ? void 0 + : _enterList$i.apply(visitors[i], args); + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + }, + leave(...args) { + const node = args[0]; + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _leaveList$i; + const result = + (_leaveList$i = leaveList[i]) === null || + _leaveList$i === void 0 + ? void 0 + : _leaveList$i.apply(visitors[i], args); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; + mergedVisitor[kind] = mergedEnterLeave; + } + return mergedVisitor; + } + /** + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + */ - while (size < 12) { - const code = body.charCodeAt(position + size++); // Closing Brace (}) + function getEnterLeaveForKind(visitor, kind) { + const kindVisitor = visitor[kind]; + if (typeof kindVisitor === "object") { + // { Kind: { enter() {}, leave() {} } } + return kindVisitor; + } else if (typeof kindVisitor === "function") { + // { Kind() {} } + return { + enter: kindVisitor, + leave: undefined, + }; + } // { enter() {}, leave() {} } - if (code === 0x007d) { - // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. - if (size < 5 || !isUnicodeScalarValue(point)) { - break; - } - return { - value: String.fromCodePoint(point), - size - }; - } // Append this hex digit to the code point. - - point = point << 4 | readHexDigit(code); - if (point < 0) { - break; - } - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + size)}".`); -} -function readEscapedUnicodeFixedWidth(lexer, position) { - const body = lexer.source.body; - const code = read16BitHexCode(body, position + 2); - if (isUnicodeScalarValue(code)) { - return { - value: String.fromCodePoint(code), - size: 6 - }; - } // GraphQL allows JSON-style surrogate pair escape sequences, but only when - // a valid pair is formed. - - if (isLeadingSurrogate(code)) { - // \u - if (body.charCodeAt(position + 6) === 0x005c && body.charCodeAt(position + 7) === 0x0075) { - const trailingCode = read16BitHexCode(body, position + 8); - if (isTrailingSurrogate(trailingCode)) { - // JavaScript defines strings as a sequence of UTF-16 code units and - // encodes Unicode code points above U+FFFF using a surrogate pair of - // code units. Since this is a surrogate pair escape sequence, just - // include both codes into the JavaScript string value. Had JavaScript - // not been internally based on UTF-16, then this surrogate pair would - // be decoded to retrieve the supplementary code point. - return { - value: String.fromCodePoint(code, trailingCode), - size: 12 - }; - } - } - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`); -} -/** - * Reads four hexadecimal characters and returns the positive integer that 16bit - * hexadecimal string represents. For example, "000f" will return 15, and "dead" - * will return 57005. - * - * Returns a negative number if any char was not a valid hexadecimal digit. - */ - -function read16BitHexCode(body, position) { - // readHexDigit() returns -1 on error. ORing a negative value with any other - // value always produces a negative value. - return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3)); -} -/** - * Reads a hexadecimal character and returns its positive integer value (0-15). - * - * '0' becomes 0, '9' becomes 9 - * 'A' becomes 10, 'F' becomes 15 - * 'a' becomes 10, 'f' becomes 15 - * - * Returns -1 if the provided character code was not a valid hexadecimal digit. - * - * HexDigit :: one of - * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` - * - `A` `B` `C` `D` `E` `F` - * - `a` `b` `c` `d` `e` `f` - */ - -function readHexDigit(code) { - return code >= 0x0030 && code <= 0x0039 // 0-9 - ? code - 0x0030 : code >= 0x0041 && code <= 0x0046 // A-F - ? code - 0x0037 : code >= 0x0061 && code <= 0x0066 // a-f - ? code - 0x0057 : -1; -} -/** - * | Escaped Character | Code Point | Character Name | - * | ----------------- | ---------- | ---------------------------- | - * | `"` | U+0022 | double quote | - * | `\` | U+005C | reverse solidus (back slash) | - * | `/` | U+002F | solidus (forward slash) | - * | `b` | U+0008 | backspace | - * | `f` | U+000C | form feed | - * | `n` | U+000A | line feed (new line) | - * | `r` | U+000D | carriage return | - * | `t` | U+0009 | horizontal tab | - */ - -function readEscapedCharacter(lexer, position) { - const body = lexer.source.body; - const code = body.charCodeAt(position + 1); - switch (code) { - case 0x0022: - // " - return { - value: '\u0022', - size: 2 - }; - case 0x005c: - // \ - return { - value: '\u005c', - size: 2 - }; - case 0x002f: - // / - return { - value: '\u002f', - size: 2 - }; - case 0x0062: - // b - return { - value: '\u0008', - size: 2 - }; - case 0x0066: - // f - return { - value: '\u000c', - size: 2 - }; - case 0x006e: - // n - return { - value: '\u000a', - size: 2 - }; - case 0x0072: - // r - return { - value: '\u000d', - size: 2 - }; - case 0x0074: - // t - return { - value: '\u0009', - size: 2 - }; - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character escape sequence: "${body.slice(position, position + 2)}".`); -} -/** - * Reads a block string token from the source file. - * - * ``` - * StringValue :: - * - `"""` BlockStringCharacter* `"""` - * - * BlockStringCharacter :: - * - SourceCharacter but not `"""` or `\"""` - * - `\"""` - * ``` - */ - -function readBlockString(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let lineStart = lexer.lineStart; - let position = start + 3; - let chunkStart = position; - let currentLine = ''; - const blockLines = []; - while (position < bodyLength) { - const code = body.charCodeAt(position); // Closing Triple-Quote (""") - - if (code === 0x0022 && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { - currentLine += body.slice(chunkStart, position); - blockLines.push(currentLine); - const token = createToken(lexer, _tokenKind.TokenKind.BLOCK_STRING, start, position + 3, - // Return a string of the lines joined with U+000A. - (0, _blockString.dedentBlockStringLines)(blockLines).join('\n')); - lexer.line += blockLines.length - 1; - lexer.lineStart = lineStart; - return token; - } // Escaped Triple-Quote (\""") - - if (code === 0x005c && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022 && body.charCodeAt(position + 3) === 0x0022) { - currentLine += body.slice(chunkStart, position); - chunkStart = position + 1; // skip only slash - - position += 4; - continue; - } // LineTerminator - - if (code === 0x000a || code === 0x000d) { - currentLine += body.slice(chunkStart, position); - blockLines.push(currentLine); - if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { - position += 2; - } else { - ++position; - } - currentLine = ''; - chunkStart = position; - lineStart = position; - continue; - } // SourceCharacter - - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); - } - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); -} -/** - * Reads an alphanumeric + underscore name from the source. - * - * ``` - * Name :: - * - NameStart NameContinue* [lookahead != NameContinue] - * ``` - */ - -function readName(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - while (position < bodyLength) { - const code = body.charCodeAt(position); - if ((0, _characterClasses.isNameContinue)(code)) { - ++position; - } else { - break; - } - } - return createToken(lexer, _tokenKind.TokenKind.NAME, start, position, body.slice(start, position)); -} + return { + enter: visitor.enter, + leave: visitor.leave, + }; + } + /** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + * + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + */ -/***/ }), + /* c8 ignore next 8 */ -/***/ "../../../node_modules/graphql/language/location.mjs": -/*!***********************************************************!*\ - !*** ../../../node_modules/graphql/language/location.mjs ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getLocation = getLocation; -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -const LineRegExp = /\r\n|[\n\r]/g; -/** - * Represents a location in a Source. - */ - -/** - * Takes a Source and a UTF-8 character offset, and returns the corresponding - * line and column as a SourceLocation. - */ -function getLocation(source, position) { - let lastLineStart = 0; - let line = 1; - for (const match of source.body.matchAll(LineRegExp)) { - typeof match.index === 'number' || (0, _invariant.invariant)(false); - if (match.index >= position) { - break; - } - lastLineStart = match.index + match[0].length; - line += 1; - } - return { - line, - column: position + 1 - lastLineStart - }; -} + function getVisitFn(visitor, kind, isLeaving) { + const { enter, leave } = getEnterLeaveForKind(visitor, kind); + return isLeaving ? leave : enter; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/language/parser.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/language/parser.mjs ***! + /***/ "../../../node_modules/graphql/type/assertName.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/assertName.mjs ***! \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Parser = void 0; -exports.parse = parse; -exports.parseConstValue = parseConstValue; -exports.parseType = parseType; -exports.parseValue = parseValue; -var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); -var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); -var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); -var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); -var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); -/** - * Configuration options to control parser behavior - */ - -/** - * Given a GraphQL source, parses it into a Document. - * Throws GraphQLError if a syntax error is encountered. - */ -function parse(source, options) { - const parser = new Parser(source, options); - return parser.parseDocument(); -} -/** - * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for - * that value. - * Throws GraphQLError if a syntax error is encountered. - * - * This is useful within tools that operate upon GraphQL Values directly and - * in isolation of complete GraphQL documents. - * - * Consider providing the results to the utility function: valueFromAST(). - */ - -function parseValue(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const value = parser.parseValueLiteral(false); - parser.expectToken(_tokenKind.TokenKind.EOF); - return value; -} -/** - * Similar to parseValue(), but raises a parse error if it encounters a - * variable. The return type will be a constant value. - */ - -function parseConstValue(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const value = parser.parseConstValueLiteral(); - parser.expectToken(_tokenKind.TokenKind.EOF); - return value; -} -/** - * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for - * that type. - * Throws GraphQLError if a syntax error is encountered. - * - * This is useful within tools that operate upon GraphQL Types directly and - * in isolation of complete GraphQL documents. - * - * Consider providing the results to the utility function: typeFromAST(). - */ - -function parseType(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const type = parser.parseTypeReference(); - parser.expectToken(_tokenKind.TokenKind.EOF); - return type; -} -/** - * This class is exported only to assist people in implementing their own parsers - * without duplicating too much code and should be used only as last resort for cases - * such as experimental syntax or if certain features could not be contributed upstream. - * - * It is still part of the internal API and is versioned, so any changes to it are never - * considered breaking changes. If you still need to support multiple versions of the - * library, please use the `versionInfo` variable for version detection. - * - * @internal - */ - -class Parser { - constructor(source, options = {}) { - const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); - this._lexer = new _lexer.Lexer(sourceObj); - this._options = options; - this._tokenCounter = 0; - } - /** - * Converts a name lex token into a name parse node. - */ - - parseName() { - const token = this.expectToken(_tokenKind.TokenKind.NAME); - return this.node(token, { - kind: _kinds.Kind.NAME, - value: token.value - }); - } // Implements the parsing rules in the Document section. + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.assertEnumValueName = assertEnumValueName; + exports.assertName = assertName; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _characterClasses = __webpack_require__( + /*! ../language/characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs" + ); + /** + * Upholds the spec rules about naming. + */ - /** - * Document : Definition+ - */ + function assertName(name) { + name != null || + (0, _devAssert.devAssert)(false, "Must provide name."); + typeof name === "string" || + (0, _devAssert.devAssert)(false, "Expected name to be a string."); + if (name.length === 0) { + throw new _GraphQLError.GraphQLError( + "Expected name to be a non-empty string." + ); + } + for (let i = 1; i < name.length; ++i) { + if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { + throw new _GraphQLError.GraphQLError( + `Names must only contain [_a-zA-Z0-9] but "${name}" does not.` + ); + } + } + if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { + throw new _GraphQLError.GraphQLError( + `Names must start with [_a-zA-Z] but "${name}" does not.` + ); + } + return name; + } + /** + * Upholds the spec rules about naming enum values. + * + * @internal + */ - parseDocument() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.DOCUMENT, - definitions: this.many(_tokenKind.TokenKind.SOF, this.parseDefinition, _tokenKind.TokenKind.EOF) - }); - } - /** - * Definition : - * - ExecutableDefinition - * - TypeSystemDefinition - * - TypeSystemExtension - * - * ExecutableDefinition : - * - OperationDefinition - * - FragmentDefinition - * - * TypeSystemDefinition : - * - SchemaDefinition - * - TypeDefinition - * - DirectiveDefinition - * - * TypeDefinition : - * - ScalarTypeDefinition - * - ObjectTypeDefinition - * - InterfaceTypeDefinition - * - UnionTypeDefinition - * - EnumTypeDefinition - * - InputObjectTypeDefinition - */ - - parseDefinition() { - if (this.peek(_tokenKind.TokenKind.BRACE_L)) { - return this.parseOperationDefinition(); - } // Many definitions begin with a description and require a lookahead. - - const hasDescription = this.peekDescription(); - const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token; - if (keywordToken.kind === _tokenKind.TokenKind.NAME) { - switch (keywordToken.value) { - case 'schema': - return this.parseSchemaDefinition(); - case 'scalar': - return this.parseScalarTypeDefinition(); - case 'type': - return this.parseObjectTypeDefinition(); - case 'interface': - return this.parseInterfaceTypeDefinition(); - case 'union': - return this.parseUnionTypeDefinition(); - case 'enum': - return this.parseEnumTypeDefinition(); - case 'input': - return this.parseInputObjectTypeDefinition(); - case 'directive': - return this.parseDirectiveDefinition(); - } - if (hasDescription) { - throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, 'Unexpected description, descriptions are supported only on type definitions.'); - } - switch (keywordToken.value) { - case 'query': - case 'mutation': - case 'subscription': - return this.parseOperationDefinition(); - case 'fragment': - return this.parseFragmentDefinition(); - case 'extend': - return this.parseTypeSystemExtension(); - } - } - throw this.unexpected(keywordToken); - } // Implements the parsing rules in the Operations section. - - /** - * OperationDefinition : - * - SelectionSet - * - OperationType Name? VariableDefinitions? Directives? SelectionSet - */ - - parseOperationDefinition() { - const start = this._lexer.token; - if (this.peek(_tokenKind.TokenKind.BRACE_L)) { - return this.node(start, { - kind: _kinds.Kind.OPERATION_DEFINITION, - operation: _ast.OperationTypeNode.QUERY, - name: undefined, - variableDefinitions: [], - directives: [], - selectionSet: this.parseSelectionSet() - }); - } - const operation = this.parseOperationType(); - let name; - if (this.peek(_tokenKind.TokenKind.NAME)) { - name = this.parseName(); - } - return this.node(start, { - kind: _kinds.Kind.OPERATION_DEFINITION, - operation, - name, - variableDefinitions: this.parseVariableDefinitions(), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); - } - /** - * OperationType : one of query mutation subscription - */ - - parseOperationType() { - const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); - switch (operationToken.value) { - case 'query': - return _ast.OperationTypeNode.QUERY; - case 'mutation': - return _ast.OperationTypeNode.MUTATION; - case 'subscription': - return _ast.OperationTypeNode.SUBSCRIPTION; - } - throw this.unexpected(operationToken); - } - /** - * VariableDefinitions : ( VariableDefinition+ ) - */ + function assertEnumValueName(name) { + if (name === "true" || name === "false" || name === "null") { + throw new _GraphQLError.GraphQLError( + `Enum values cannot be named: ${name}` + ); + } + return assertName(name); + } - parseVariableDefinitions() { - return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseVariableDefinition, _tokenKind.TokenKind.PAREN_R); - } - /** - * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? - */ - - parseVariableDefinition() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.VARIABLE_DEFINITION, - variable: this.parseVariable(), - type: (this.expectToken(_tokenKind.TokenKind.COLON), this.parseTypeReference()), - defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.parseConstValueLiteral() : undefined, - directives: this.parseConstDirectives() - }); - } - /** - * Variable : $ Name - */ - - parseVariable() { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.DOLLAR); - return this.node(start, { - kind: _kinds.Kind.VARIABLE, - name: this.parseName() - }); - } - /** - * ``` - * SelectionSet : { Selection+ } - * ``` - */ - - parseSelectionSet() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.SELECTION_SET, - selections: this.many(_tokenKind.TokenKind.BRACE_L, this.parseSelection, _tokenKind.TokenKind.BRACE_R) - }); - } - /** - * Selection : - * - Field - * - FragmentSpread - * - InlineFragment - */ - - parseSelection() { - return this.peek(_tokenKind.TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); - } - /** - * Field : Alias? Name Arguments? Directives? SelectionSet? - * - * Alias : Name : - */ - - parseField() { - const start = this._lexer.token; - const nameOrAlias = this.parseName(); - let alias; - let name; - if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { - alias = nameOrAlias; - name = this.parseName(); - } else { - name = nameOrAlias; - } - return this.node(start, { - kind: _kinds.Kind.FIELD, - alias, - name, - arguments: this.parseArguments(false), - directives: this.parseDirectives(false), - selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined - }); - } - /** - * Arguments[Const] : ( Argument[?Const]+ ) - */ + /***/ + }, - parseArguments(isConst) { - const item = isConst ? this.parseConstArgument : this.parseArgument; - return this.optionalMany(_tokenKind.TokenKind.PAREN_L, item, _tokenKind.TokenKind.PAREN_R); - } - /** - * Argument[Const] : Name : Value[?Const] - */ - - parseArgument(isConst = false) { - const start = this._lexer.token; - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - return this.node(start, { - kind: _kinds.Kind.ARGUMENT, - name, - value: this.parseValueLiteral(isConst) - }); - } - parseConstArgument() { - return this.parseArgument(true); - } // Implements the parsing rules in the Fragments section. - - /** - * Corresponds to both FragmentSpread and InlineFragment in the spec. - * - * FragmentSpread : ... FragmentName Directives? - * - * InlineFragment : ... TypeCondition? Directives? SelectionSet - */ - - parseFragment() { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.SPREAD); - const hasTypeCondition = this.expectOptionalKeyword('on'); - if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_SPREAD, - name: this.parseFragmentName(), - directives: this.parseDirectives(false) - }); - } - return this.node(start, { - kind: _kinds.Kind.INLINE_FRAGMENT, - typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); - } - /** - * FragmentDefinition : - * - fragment FragmentName on TypeCondition Directives? SelectionSet - * - * TypeCondition : NamedType - */ - - parseFragmentDefinition() { - const start = this._lexer.token; - this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes - // the grammar of FragmentDefinition: - // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet - - if (this._options.allowLegacyFragmentVariables === true) { - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_DEFINITION, - name: this.parseFragmentName(), - variableDefinitions: this.parseVariableDefinitions(), - typeCondition: (this.expectKeyword('on'), this.parseNamedType()), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); - } - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_DEFINITION, - name: this.parseFragmentName(), - typeCondition: (this.expectKeyword('on'), this.parseNamedType()), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); - } - /** - * FragmentName : Name but not `on` - */ + /***/ "../../../node_modules/graphql/type/definition.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/definition.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.GraphQLUnionType = + exports.GraphQLScalarType = + exports.GraphQLObjectType = + exports.GraphQLNonNull = + exports.GraphQLList = + exports.GraphQLInterfaceType = + exports.GraphQLInputObjectType = + exports.GraphQLEnumType = + void 0; + exports.argsToArgsConfig = argsToArgsConfig; + exports.assertAbstractType = assertAbstractType; + exports.assertCompositeType = assertCompositeType; + exports.assertEnumType = assertEnumType; + exports.assertInputObjectType = assertInputObjectType; + exports.assertInputType = assertInputType; + exports.assertInterfaceType = assertInterfaceType; + exports.assertLeafType = assertLeafType; + exports.assertListType = assertListType; + exports.assertNamedType = assertNamedType; + exports.assertNonNullType = assertNonNullType; + exports.assertNullableType = assertNullableType; + exports.assertObjectType = assertObjectType; + exports.assertOutputType = assertOutputType; + exports.assertScalarType = assertScalarType; + exports.assertType = assertType; + exports.assertUnionType = assertUnionType; + exports.assertWrappingType = assertWrappingType; + exports.defineArguments = defineArguments; + exports.getNamedType = getNamedType; + exports.getNullableType = getNullableType; + exports.isAbstractType = isAbstractType; + exports.isCompositeType = isCompositeType; + exports.isEnumType = isEnumType; + exports.isInputObjectType = isInputObjectType; + exports.isInputType = isInputType; + exports.isInterfaceType = isInterfaceType; + exports.isLeafType = isLeafType; + exports.isListType = isListType; + exports.isNamedType = isNamedType; + exports.isNonNullType = isNonNullType; + exports.isNullableType = isNullableType; + exports.isObjectType = isObjectType; + exports.isOutputType = isOutputType; + exports.isRequiredArgument = isRequiredArgument; + exports.isRequiredInputField = isRequiredInputField; + exports.isScalarType = isScalarType; + exports.isType = isType; + exports.isUnionType = isUnionType; + exports.isWrappingType = isWrappingType; + exports.resolveObjMapThunk = resolveObjMapThunk; + exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _didYouMean = __webpack_require__( + /*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _identityFunc = __webpack_require__( + /*! ../jsutils/identityFunc.mjs */ "../../../node_modules/graphql/jsutils/identityFunc.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _instanceOf = __webpack_require__( + /*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _keyValMap = __webpack_require__( + /*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs" + ); + var _mapValue = __webpack_require__( + /*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _toObjMap = __webpack_require__( + /*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _printer = __webpack_require__( + /*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _valueFromASTUntyped = __webpack_require__( + /*! ../utilities/valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs" + ); + var _assertName = __webpack_require__( + /*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs" + ); + function isType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); + } + function assertType(type) { + if (!isType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.` + ); + } + return type; + } + /** + * There are predicates for each kind of GraphQL type. + */ + + function isScalarType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); + } + function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Scalar type.` + ); + } + return type; + } + function isObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); + } + function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Object type.` + ); + } + return type; + } + function isInterfaceType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); + } + function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Interface type.` + ); + } + return type; + } + function isUnionType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); + } + function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Union type.` + ); + } + return type; + } + function isEnumType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); + } + function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Enum type.` + ); + } + return type; + } + function isInputObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); + } + function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Input Object type.` + ); + } + return type; + } + function isListType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLList); + } + function assertListType(type) { + if (!isListType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL List type.` + ); + } + return type; + } + function isNonNullType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); + } + function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL Non-Null type.` + ); + } + return type; + } + /** + * These types may be used as input types for arguments and directives. + */ + + function isInputType(type) { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); + } + function assertInputType(type) { + if (!isInputType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL input type.` + ); + } + return type; + } + /** + * These types may be used as output types as the result of fields. + */ + + function isOutputType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); + } + function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL output type.` + ); + } + return type; + } + /** + * These types may describe types which may be leaf values. + */ - parseFragmentName() { - if (this._lexer.token.value === 'on') { - throw this.unexpected(); - } - return this.parseName(); - } // Implements the parsing rules in the Values section. - - /** - * Value[Const] : - * - [~Const] Variable - * - IntValue - * - FloatValue - * - StringValue - * - BooleanValue - * - NullValue - * - EnumValue - * - ListValue[?Const] - * - ObjectValue[?Const] - * - * BooleanValue : one of `true` `false` - * - * NullValue : `null` - * - * EnumValue : Name but not `true`, `false` or `null` - */ - - parseValueLiteral(isConst) { - const token = this._lexer.token; - switch (token.kind) { - case _tokenKind.TokenKind.BRACKET_L: - return this.parseList(isConst); - case _tokenKind.TokenKind.BRACE_L: - return this.parseObject(isConst); - case _tokenKind.TokenKind.INT: - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.INT, - value: token.value - }); - case _tokenKind.TokenKind.FLOAT: - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.FLOAT, - value: token.value - }); - case _tokenKind.TokenKind.STRING: - case _tokenKind.TokenKind.BLOCK_STRING: - return this.parseStringLiteral(); - case _tokenKind.TokenKind.NAME: - this.advanceLexer(); - switch (token.value) { - case 'true': - return this.node(token, { - kind: _kinds.Kind.BOOLEAN, - value: true - }); - case 'false': - return this.node(token, { - kind: _kinds.Kind.BOOLEAN, - value: false - }); - case 'null': - return this.node(token, { - kind: _kinds.Kind.NULL - }); - default: - return this.node(token, { - kind: _kinds.Kind.ENUM, - value: token.value - }); + function isLeafType(type) { + return isScalarType(type) || isEnumType(type); } - case _tokenKind.TokenKind.DOLLAR: - if (isConst) { - this.expectToken(_tokenKind.TokenKind.DOLLAR); - if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { - const varName = this._lexer.token.value; - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected variable "$${varName}" in constant value.`); - } else { - throw this.unexpected(token); + function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL leaf type.` + ); } + return type; } - return this.parseVariable(); - default: - throw this.unexpected(); - } - } - parseConstValueLiteral() { - return this.parseValueLiteral(true); - } - parseStringLiteral() { - const token = this._lexer.token; - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.STRING, - value: token.value, - block: token.kind === _tokenKind.TokenKind.BLOCK_STRING - }); - } - /** - * ListValue[Const] : - * - [ ] - * - [ Value[?Const]+ ] - */ - - parseList(isConst) { - const item = () => this.parseValueLiteral(isConst); - return this.node(this._lexer.token, { - kind: _kinds.Kind.LIST, - values: this.any(_tokenKind.TokenKind.BRACKET_L, item, _tokenKind.TokenKind.BRACKET_R) - }); - } - /** - * ``` - * ObjectValue[Const] : - * - { } - * - { ObjectField[?Const]+ } - * ``` - */ - - parseObject(isConst) { - const item = () => this.parseObjectField(isConst); - return this.node(this._lexer.token, { - kind: _kinds.Kind.OBJECT, - fields: this.any(_tokenKind.TokenKind.BRACE_L, item, _tokenKind.TokenKind.BRACE_R) - }); - } - /** - * ObjectField[Const] : Name : Value[?Const] - */ - - parseObjectField(isConst) { - const start = this._lexer.token; - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - return this.node(start, { - kind: _kinds.Kind.OBJECT_FIELD, - name, - value: this.parseValueLiteral(isConst) - }); - } // Implements the parsing rules in the Directives section. + /** + * These types may describe the parent context of a selection set. + */ - /** - * Directives[Const] : Directive[?Const]+ - */ + function isCompositeType(type) { + return ( + isObjectType(type) || isInterfaceType(type) || isUnionType(type) + ); + } + function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL composite type.` + ); + } + return type; + } + /** + * These types may describe the parent context of a selection set. + */ - parseDirectives(isConst) { - const directives = []; - while (this.peek(_tokenKind.TokenKind.AT)) { - directives.push(this.parseDirective(isConst)); - } - return directives; - } - parseConstDirectives() { - return this.parseDirectives(true); - } - /** - * ``` - * Directive[Const] : @ Name Arguments[?Const]? - * ``` - */ - - parseDirective(isConst) { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.AT); - return this.node(start, { - kind: _kinds.Kind.DIRECTIVE, - name: this.parseName(), - arguments: this.parseArguments(isConst) - }); - } // Implements the parsing rules in the Types section. - - /** - * Type : - * - NamedType - * - ListType - * - NonNullType - */ - - parseTypeReference() { - const start = this._lexer.token; - let type; - if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { - const innerType = this.parseTypeReference(); - this.expectToken(_tokenKind.TokenKind.BRACKET_R); - type = this.node(start, { - kind: _kinds.Kind.LIST_TYPE, - type: innerType - }); - } else { - type = this.parseNamedType(); - } - if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { - return this.node(start, { - kind: _kinds.Kind.NON_NULL_TYPE, - type - }); - } - return type; - } - /** - * NamedType : Name - */ - - parseNamedType() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.NAMED_TYPE, - name: this.parseName() - }); - } // Implements the parsing rules in the Type Definition section. + function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); + } + function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL abstract type.` + ); + } + return type; + } + /** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ - peekDescription() { - return this.peek(_tokenKind.TokenKind.STRING) || this.peek(_tokenKind.TokenKind.BLOCK_STRING); - } - /** - * Description : StringValue - */ + class GraphQLList { + constructor(ofType) { + isType(ofType) || + (0, _devAssert.devAssert)( + false, + `Expected ${(0, _inspect.inspect)( + ofType + )} to be a GraphQL type.` + ); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return "GraphQLList"; + } + toString() { + return "[" + String(this.ofType) + "]"; + } + toJSON() { + return this.toString(); + } + } + /** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * Note: the enforcement of non-nullability occurs within the executor. + */ + exports.GraphQLList = GraphQLList; + class GraphQLNonNull { + constructor(ofType) { + isNullableType(ofType) || + (0, _devAssert.devAssert)( + false, + `Expected ${(0, _inspect.inspect)( + ofType + )} to be a GraphQL nullable type.` + ); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return "GraphQLNonNull"; + } + toString() { + return String(this.ofType) + "!"; + } + toJSON() { + return this.toString(); + } + } + /** + * These types wrap and modify other types + */ + exports.GraphQLNonNull = GraphQLNonNull; + function isWrappingType(type) { + return isListType(type) || isNonNullType(type); + } + function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL wrapping type.` + ); + } + return type; + } + /** + * These types can all accept null as a value. + */ - parseDescription() { - if (this.peekDescription()) { - return this.parseStringLiteral(); - } - } - /** - * ``` - * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } - * ``` - */ - - parseSchemaDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('schema'); - const directives = this.parseConstDirectives(); - const operationTypes = this.many(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); - return this.node(start, { - kind: _kinds.Kind.SCHEMA_DEFINITION, - description, - directives, - operationTypes - }); - } - /** - * OperationTypeDefinition : OperationType : NamedType - */ - - parseOperationTypeDefinition() { - const start = this._lexer.token; - const operation = this.parseOperationType(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseNamedType(); - return this.node(start, { - kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, - operation, - type - }); - } - /** - * ScalarTypeDefinition : Description? scalar Name Directives[Const]? - */ - - parseScalarTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('scalar'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, - description, - name, - directives - }); - } - /** - * ObjectTypeDefinition : - * Description? - * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? - */ - - parseObjectTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('type'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, - description, - name, - interfaces, - directives, - fields - }); - } - /** - * ImplementsInterfaces : - * - implements `&`? NamedType - * - ImplementsInterfaces & NamedType - */ - - parseImplementsInterfaces() { - return this.expectOptionalKeyword('implements') ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) : []; - } - /** - * ``` - * FieldsDefinition : { FieldDefinition+ } - * ``` - */ - - parseFieldsDefinition() { - return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseFieldDefinition, _tokenKind.TokenKind.BRACE_R); - } - /** - * FieldDefinition : - * - Description? Name ArgumentsDefinition? : Type Directives[Const]? - */ - - parseFieldDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseName(); - const args = this.parseArgumentDefs(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseTypeReference(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.FIELD_DEFINITION, - description, - name, - arguments: args, - type, - directives - }); - } - /** - * ArgumentsDefinition : ( InputValueDefinition+ ) - */ + function isNullableType(type) { + return isType(type) && !isNonNullType(type); + } + function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL nullable type.` + ); + } + return type; + } + function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } + } + /** + * These named types do not include modifiers like List or NonNull. + */ - parseArgumentDefs() { - return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseInputValueDef, _tokenKind.TokenKind.PAREN_R); - } - /** - * InputValueDefinition : - * - Description? Name : Type DefaultValue? Directives[Const]? - */ - - parseInputValueDef() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseTypeReference(); - let defaultValue; - if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { - defaultValue = this.parseConstValueLiteral(); - } - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.INPUT_VALUE_DEFINITION, - description, - name, - type, - defaultValue, - directives - }); - } - /** - * InterfaceTypeDefinition : - * - Description? interface Name Directives[Const]? FieldsDefinition? - */ - - parseInterfaceTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('interface'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, - description, - name, - interfaces, - directives, - fields - }); - } - /** - * UnionTypeDefinition : - * - Description? union Name Directives[Const]? UnionMemberTypes? - */ - - parseUnionTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('union'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const types = this.parseUnionMemberTypes(); - return this.node(start, { - kind: _kinds.Kind.UNION_TYPE_DEFINITION, - description, - name, - directives, - types - }); - } - /** - * UnionMemberTypes : - * - = `|`? NamedType - * - UnionMemberTypes | NamedType - */ - - parseUnionMemberTypes() { - return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) : []; - } - /** - * EnumTypeDefinition : - * - Description? enum Name Directives[Const]? EnumValuesDefinition? - */ - - parseEnumTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('enum'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const values = this.parseEnumValuesDefinition(); - return this.node(start, { - kind: _kinds.Kind.ENUM_TYPE_DEFINITION, - description, - name, - directives, - values - }); - } - /** - * ``` - * EnumValuesDefinition : { EnumValueDefinition+ } - * ``` - */ - - parseEnumValuesDefinition() { - return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseEnumValueDefinition, _tokenKind.TokenKind.BRACE_R); - } - /** - * EnumValueDefinition : Description? EnumValue Directives[Const]? - */ - - parseEnumValueDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseEnumValueName(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.ENUM_VALUE_DEFINITION, - description, - name, - directives - }); - } - /** - * EnumValue : Name but not `true`, `false` or `null` - */ + function isNamedType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); + } + function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type + )} to be a GraphQL named type.` + ); + } + return type; + } + function getNamedType(type) { + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } + } + /** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ - parseEnumValueName() { - if (this._lexer.token.value === 'true' || this._lexer.token.value === 'false' || this._lexer.token.value === 'null') { - throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, `${getTokenDesc(this._lexer.token)} is reserved and cannot be used for an enum value.`); - } - return this.parseName(); - } - /** - * InputObjectTypeDefinition : - * - Description? input Name Directives[Const]? InputFieldsDefinition? - */ - - parseInputObjectTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('input'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const fields = this.parseInputFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, - description, - name, - directives, - fields - }); - } - /** - * ``` - * InputFieldsDefinition : { InputValueDefinition+ } - * ``` - */ - - parseInputFieldsDefinition() { - return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseInputValueDef, _tokenKind.TokenKind.BRACE_R); - } - /** - * TypeSystemExtension : - * - SchemaExtension - * - TypeExtension - * - * TypeExtension : - * - ScalarTypeExtension - * - ObjectTypeExtension - * - InterfaceTypeExtension - * - UnionTypeExtension - * - EnumTypeExtension - * - InputObjectTypeDefinition - */ - - parseTypeSystemExtension() { - const keywordToken = this._lexer.lookahead(); - if (keywordToken.kind === _tokenKind.TokenKind.NAME) { - switch (keywordToken.value) { - case 'schema': - return this.parseSchemaExtension(); - case 'scalar': - return this.parseScalarTypeExtension(); - case 'type': - return this.parseObjectTypeExtension(); - case 'interface': - return this.parseInterfaceTypeExtension(); - case 'union': - return this.parseUnionTypeExtension(); - case 'enum': - return this.parseEnumTypeExtension(); - case 'input': - return this.parseInputObjectTypeExtension(); - } - } - throw this.unexpected(keywordToken); - } - /** - * ``` - * SchemaExtension : - * - extend schema Directives[Const]? { OperationTypeDefinition+ } - * - extend schema Directives[Const] - * ``` - */ - - parseSchemaExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('schema'); - const directives = this.parseConstDirectives(); - const operationTypes = this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); - if (directives.length === 0 && operationTypes.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.SCHEMA_EXTENSION, - directives, - operationTypes - }); - } - /** - * ScalarTypeExtension : - * - extend scalar Name Directives[Const] - */ - - parseScalarTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('scalar'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - if (directives.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, - name, - directives - }); - } - /** - * ObjectTypeExtension : - * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition - * - extend type Name ImplementsInterfaces? Directives[Const] - * - extend type Name ImplementsInterfaces - */ - - parseObjectTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('type'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, - name, - interfaces, - directives, - fields - }); - } - /** - * InterfaceTypeExtension : - * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition - * - extend interface Name ImplementsInterfaces? Directives[Const] - * - extend interface Name ImplementsInterfaces - */ - - parseInterfaceTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('interface'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, - name, - interfaces, - directives, - fields - }); - } - /** - * UnionTypeExtension : - * - extend union Name Directives[Const]? UnionMemberTypes - * - extend union Name Directives[Const] - */ - - parseUnionTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('union'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const types = this.parseUnionMemberTypes(); - if (directives.length === 0 && types.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.UNION_TYPE_EXTENSION, - name, - directives, - types - }); - } - /** - * EnumTypeExtension : - * - extend enum Name Directives[Const]? EnumValuesDefinition - * - extend enum Name Directives[Const] - */ - - parseEnumTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('enum'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const values = this.parseEnumValuesDefinition(); - if (directives.length === 0 && values.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.ENUM_TYPE_EXTENSION, - name, - directives, - values - }); - } - /** - * InputObjectTypeExtension : - * - extend input Name Directives[Const]? InputFieldsDefinition - * - extend input Name Directives[Const] - */ - - parseInputObjectTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('input'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const fields = this.parseInputFieldsDefinition(); - if (directives.length === 0 && fields.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, - name, - directives, - fields - }); - } - /** - * ``` - * DirectiveDefinition : - * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations - * ``` - */ - - parseDirectiveDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('directive'); - this.expectToken(_tokenKind.TokenKind.AT); - const name = this.parseName(); - const args = this.parseArgumentDefs(); - const repeatable = this.expectOptionalKeyword('repeatable'); - this.expectKeyword('on'); - const locations = this.parseDirectiveLocations(); - return this.node(start, { - kind: _kinds.Kind.DIRECTIVE_DEFINITION, - description, - name, - arguments: args, - repeatable, - locations - }); - } - /** - * DirectiveLocations : - * - `|`? DirectiveLocation - * - DirectiveLocations | DirectiveLocation - */ - - parseDirectiveLocations() { - return this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseDirectiveLocation); - } - /* - * DirectiveLocation : - * - ExecutableDirectiveLocation - * - TypeSystemDirectiveLocation - * - * ExecutableDirectiveLocation : one of - * `QUERY` - * `MUTATION` - * `SUBSCRIPTION` - * `FIELD` - * `FRAGMENT_DEFINITION` - * `FRAGMENT_SPREAD` - * `INLINE_FRAGMENT` - * - * TypeSystemDirectiveLocation : one of - * `SCHEMA` - * `SCALAR` - * `OBJECT` - * `FIELD_DEFINITION` - * `ARGUMENT_DEFINITION` - * `INTERFACE` - * `UNION` - * `ENUM` - * `ENUM_VALUE` - * `INPUT_OBJECT` - * `INPUT_FIELD_DEFINITION` - */ - - parseDirectiveLocation() { - const start = this._lexer.token; - const name = this.parseName(); - if (Object.prototype.hasOwnProperty.call(_directiveLocation.DirectiveLocation, name.value)) { - return name; - } - throw this.unexpected(start); - } // Core parsing utility functions - - /** - * Returns a node that, if configured to do so, sets a "loc" field as a - * location object, used to identify the place in the source that created a - * given parsed object. - */ - - node(startToken, node) { - if (this._options.noLocation !== true) { - node.loc = new _ast.Location(startToken, this._lexer.lastToken, this._lexer.source); - } - return node; - } - /** - * Determines if the next token is of a given kind - */ + function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === "function" ? thunk() : thunk; + } + function resolveObjMapThunk(thunk) { + return typeof thunk === "function" ? thunk() : thunk; + } + /** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ - peek(kind) { - return this._lexer.token.kind === kind; - } - /** - * If the next token is of the given kind, return that token after advancing the lexer. - * Otherwise, do not change the parser state and throw an error. - */ - - expectToken(kind) { - const token = this._lexer.token; - if (token.kind === kind) { - this.advanceLexer(); - return token; - } - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`); - } - /** - * If the next token is of the given kind, return "true" after advancing the lexer. - * Otherwise, do not change the parser state and return "false". - */ - - expectOptionalToken(kind) { - const token = this._lexer.token; - if (token.kind === kind) { - this.advanceLexer(); - return true; - } - return false; - } - /** - * If the next token is a given keyword, advance the lexer. - * Otherwise, do not change the parser state and throw an error. - */ - - expectKeyword(value) { - const token = this._lexer.token; - if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { - this.advanceLexer(); - } else { - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.`); - } - } - /** - * If the next token is a given keyword, return "true" after advancing the lexer. - * Otherwise, do not change the parser state and return "false". - */ - - expectOptionalKeyword(value) { - const token = this._lexer.token; - if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { - this.advanceLexer(); - return true; - } - return false; - } - /** - * Helper function for creating an error when an unexpected lexed token is encountered. - */ + /** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. It is always better to validate + * + * Example: + * + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } + * + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` + */ + class GraphQLScalarType { + constructor(config) { + var _config$parseValue, + _config$serialize, + _config$parseLiteral, + _config$extensionASTN; + const parseValue = + (_config$parseValue = config.parseValue) !== null && + _config$parseValue !== void 0 + ? _config$parseValue + : _identityFunc.identityFunc; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = + (_config$serialize = config.serialize) !== null && + _config$serialize !== void 0 + ? _config$serialize + : _identityFunc.identityFunc; + this.parseValue = parseValue; + this.parseLiteral = + (_config$parseLiteral = config.parseLiteral) !== null && + _config$parseLiteral !== void 0 + ? _config$parseLiteral + : (node, variables) => + parseValue( + (0, _valueFromASTUntyped.valueFromASTUntyped)( + node, + variables + ) + ); + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + config.specifiedByURL == null || + typeof config.specifiedByURL === "string" || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "specifiedByURL" as a string, ` + + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.` + ); + config.serialize == null || + typeof config.serialize === "function" || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.` + ); + if (config.parseLiteral) { + (typeof config.parseValue === "function" && + typeof config.parseLiteral === "function") || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide both "parseValue" and "parseLiteral" functions.` + ); + } + } + get [Symbol.toStringTag]() { + return "GraphQLScalarType"; + } + toConfig() { + return { + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } - unexpected(atToken) { - const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; - return (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.`); - } - /** - * Returns a possibly empty list of parse nodes, determined by the parseFn. - * This list begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ - - any(openKind, parseFn, closeKind) { - this.expectToken(openKind); - const nodes = []; - while (!this.expectOptionalToken(closeKind)) { - nodes.push(parseFn.call(this)); - } - return nodes; - } - /** - * Returns a list of parse nodes, determined by the parseFn. - * It can be empty only if open token is missing otherwise it will always return non-empty list - * that begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ - - optionalMany(openKind, parseFn, closeKind) { - if (this.expectOptionalToken(openKind)) { - const nodes = []; - do { - nodes.push(parseFn.call(this)); - } while (!this.expectOptionalToken(closeKind)); - return nodes; - } - return []; - } - /** - * Returns a non-empty list of parse nodes, determined by the parseFn. - * This list begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ - - many(openKind, parseFn, closeKind) { - this.expectToken(openKind); - const nodes = []; - do { - nodes.push(parseFn.call(this)); - } while (!this.expectOptionalToken(closeKind)); - return nodes; - } - /** - * Returns a non-empty list of parse nodes, determined by the parseFn. - * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. - * Advances the parser to the next lex token after last item in the list. - */ - - delimitedMany(delimiterKind, parseFn) { - this.expectOptionalToken(delimiterKind); - const nodes = []; - do { - nodes.push(parseFn.call(this)); - } while (this.expectOptionalToken(delimiterKind)); - return nodes; - } - advanceLexer() { - const { - maxTokens - } = this._options; - const token = this._lexer.advance(); - if (maxTokens !== undefined && token.kind !== _tokenKind.TokenKind.EOF) { - ++this._tokenCounter; - if (this._tokenCounter > maxTokens) { - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Document contains more that ${maxTokens} tokens. Parsing aborted.`); - } - } - } -} -/** - * A helper function to describe a token as a string for debugging. - */ -exports.Parser = Parser; -function getTokenDesc(token) { - const value = token.value; - return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); -} -/** - * A helper function to describe a token kind as a string for debugging. - */ - -function getTokenKindDesc(kind) { - return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/language/predicates.mjs": -/*!*************************************************************!*\ - !*** ../../../node_modules/graphql/language/predicates.mjs ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isConstValueNode = isConstValueNode; -exports.isDefinitionNode = isDefinitionNode; -exports.isExecutableDefinitionNode = isExecutableDefinitionNode; -exports.isSelectionNode = isSelectionNode; -exports.isTypeDefinitionNode = isTypeDefinitionNode; -exports.isTypeExtensionNode = isTypeExtensionNode; -exports.isTypeNode = isTypeNode; -exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; -exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; -exports.isValueNode = isValueNode; -var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -function isDefinitionNode(node) { - return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); -} -function isExecutableDefinitionNode(node) { - return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; -} -function isSelectionNode(node) { - return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; -} -function isValueNode(node) { - return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; -} -function isConstValueNode(node) { - return isValueNode(node) && (node.kind === _kinds.Kind.LIST ? node.values.some(isConstValueNode) : node.kind === _kinds.Kind.OBJECT ? node.fields.some(field => isConstValueNode(field.value)) : node.kind !== _kinds.Kind.VARIABLE); -} -function isTypeNode(node) { - return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; -} -function isTypeSystemDefinitionNode(node) { - return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; -} -function isTypeDefinitionNode(node) { - return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; -} -function isTypeSystemExtensionNode(node) { - return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); -} -function isTypeExtensionNode(node) { - return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/language/printLocation.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/language/printLocation.mjs ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.printLocation = printLocation; -exports.printSourceLocation = printSourceLocation; -var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); -/** - * Render a helpful description of the location in the GraphQL Source document. - */ -function printLocation(location) { - return printSourceLocation(location.source, (0, _location.getLocation)(location.source, location.start)); -} -/** - * Render a helpful description of the location in the GraphQL Source document. - */ - -function printSourceLocation(source, sourceLocation) { - const firstLineColumnOffset = source.locationOffset.column - 1; - const body = ''.padStart(firstLineColumnOffset) + source.body; - const lineIndex = sourceLocation.line - 1; - const lineOffset = source.locationOffset.line - 1; - const lineNum = sourceLocation.line + lineOffset; - const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; - const columnNum = sourceLocation.column + columnOffset; - const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; - const lines = body.split(/\r\n|[\n\r]/g); - const locationLine = lines[lineIndex]; // Special case for minified documents - - if (locationLine.length > 120) { - const subLineIndex = Math.floor(columnNum / 80); - const subLineColumnNum = columnNum % 80; - const subLines = []; - for (let i = 0; i < locationLine.length; i += 80) { - subLines.push(locationLine.slice(i, i + 80)); - } - return locationStr + printPrefixedLines([[`${lineNum} |`, subLines[0]], ...subLines.slice(1, subLineIndex + 1).map(subLine => ['|', subLine]), ['|', '^'.padStart(subLineColumnNum)], ['|', subLines[subLineIndex + 1]]]); - } - return locationStr + printPrefixedLines([ - // Lines specified like this: ["prefix", "string"], - [`${lineNum - 1} |`, lines[lineIndex - 1]], [`${lineNum} |`, locationLine], ['|', '^'.padStart(columnNum)], [`${lineNum + 1} |`, lines[lineIndex + 1]]]); -} -function printPrefixedLines(lines) { - const existingLines = lines.filter(([_, line]) => line !== undefined); - const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); - return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')).join('\n'); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/language/printString.mjs": -/*!**************************************************************!*\ - !*** ../../../node_modules/graphql/language/printString.mjs ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` + */ + exports.GraphQLScalarType = GraphQLScalarType; + class GraphQLObjectType { + constructor(config) { + var _config$extensionASTN2; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN2 = config.extensionASTNodes) !== null && + _config$extensionASTN2 !== void 0 + ? _config$extensionASTN2 + : []; + this._fields = () => defineFieldMap(config); + this._interfaces = () => defineInterfaces(config); + config.isTypeOf == null || + typeof config.isTypeOf === "function" || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.` + ); + } + get [Symbol.toStringTag]() { + return "GraphQLObjectType"; + } + getFields() { + if (typeof this._fields === "function") { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === "function") { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLObjectType = GraphQLObjectType; + function defineInterfaces(config) { + var _config$interfaces; + const interfaces = resolveReadonlyArrayThunk( + (_config$interfaces = config.interfaces) !== null && + _config$interfaces !== void 0 + ? _config$interfaces + : [] + ); + Array.isArray(interfaces) || + (0, _devAssert.devAssert)( + false, + `${config.name} interfaces must be an Array or a function which returns an Array.` + ); + return interfaces; + } + function defineFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + (0, _devAssert.devAssert)( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.` + ); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + var _fieldConfig$args; + isPlainObj(fieldConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field config must be an object.` + ); + fieldConfig.resolve == null || + typeof fieldConfig.resolve === "function" || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${(0, _inspect.inspect)( + fieldConfig.resolve + )}.` + ); + const argsConfig = + (_fieldConfig$args = fieldConfig.args) !== null && + _fieldConfig$args !== void 0 + ? _fieldConfig$args + : {}; + isPlainObj(argsConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} args must be an object with argument names as keys.` + ); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + args: defineArguments(argsConfig), + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); + } + function defineArguments(config) { + return Object.entries(config).map(([argName, argConfig]) => ({ + name: (0, _assertName.assertName)(argName), + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), + astNode: argConfig.astNode, + })); + } + function isPlainObj(obj) { + return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); + } + function fieldsToFieldsConfig(fields) { + return (0, _mapValue.mapValue)(fields, (field) => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); + } + /** + * @internal + */ + function argsToArgsConfig(args) { + return (0, _keyValMap.keyValMap)( + args, + (arg) => arg.name, + (arg) => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode, + }) + ); + } + function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; + } + /** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ + class GraphQLInterfaceType { + constructor(config) { + var _config$extensionASTN3; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN3 = config.extensionASTNodes) !== null && + _config$extensionASTN3 !== void 0 + ? _config$extensionASTN3 + : []; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === "function" || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.resolveType)}.` + ); + } + get [Symbol.toStringTag]() { + return "GraphQLInterfaceType"; + } + getFields() { + if (typeof this._fields === "function") { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === "function") { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.printString = printString; -/** - * Prints a string as a GraphQL StringValue literal. Replaces control characters - * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. - */ -function printString(str) { - return `"${str.replace(escapedRegExp, escapedReplacer)}"`; -} // eslint-disable-next-line no-control-regex + /** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ + exports.GraphQLInterfaceType = GraphQLInterfaceType; + class GraphQLUnionType { + constructor(config) { + var _config$extensionASTN4; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN4 = config.extensionASTNodes) !== null && + _config$extensionASTN4 !== void 0 + ? _config$extensionASTN4 + : []; + this._types = defineTypes.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === "function" || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.resolveType)}.` + ); + } + get [Symbol.toStringTag]() { + return "GraphQLUnionType"; + } + getTypes() { + if (typeof this._types === "function") { + this._types = this._types(); + } + return this._types; + } + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLUnionType = GraphQLUnionType; + function defineTypes(config) { + const types = resolveReadonlyArrayThunk(config.types); + Array.isArray(types) || + (0, _devAssert.devAssert)( + false, + `Must provide Array of types or a function which returns such an array for Union ${config.name}.` + ); + return types; + } -const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; -function escapedReplacer(str) { - return escapeSequences[str.charCodeAt(0)]; -} // prettier-ignore + /** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * ```ts + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ + class GraphQLEnumType { + /* */ + constructor(config) { + var _config$extensionASTN5; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN5 = config.extensionASTNodes) !== null && + _config$extensionASTN5 !== void 0 + ? _config$extensionASTN5 + : []; + this._values = defineEnumValues(this.name, config.values); + this._valueLookup = new Map( + this._values.map((enumValue) => [enumValue.value, enumValue]) + ); + this._nameLookup = (0, _keyMap.keyMap)( + this._values, + (value) => value.name + ); + } + get [Symbol.toStringTag]() { + return "GraphQLEnumType"; + } + getValues() { + return this._values; + } + getValue(name) { + return this._nameLookup[name]; + } + serialize(outputValue) { + const enumValue = this._valueLookup.get(outputValue); + if (enumValue === undefined) { + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent value: ${(0, + _inspect.inspect)(outputValue)}` + ); + } + return enumValue.name; + } + parseValue(inputValue /* T */) { + if (typeof inputValue !== "string") { + const valueStr = (0, _inspect.inspect)(inputValue); + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr) + ); + } + const enumValue = this.getValue(inputValue); + if (enumValue == null) { + throw new _GraphQLError.GraphQLError( + `Value "${inputValue}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, inputValue) + ); + } + return enumValue.value; + } + parseLiteral(valueNode, _variables /* T */) { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== _kinds.Kind.ENUM) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + { + nodes: valueNode, + } + ); + } + const enumValue = this.getValue(valueNode.value); + if (enumValue == null) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError( + `Value "${valueStr}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, valueStr), + { + nodes: valueNode, + } + ); + } + return enumValue.value; + } + toConfig() { + const values = (0, _keyValMap.keyValMap)( + this.getValues(), + (value) => value.name, + (value) => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode, + }) + ); + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLEnumType = GraphQLEnumType; + function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map((value) => value.name); + const suggestedValues = (0, _suggestionList.suggestionList)( + unknownValueStr, + allNames + ); + return (0, _didYouMean.didYouMean)("the enum value", suggestedValues); + } + function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || + (0, _devAssert.devAssert)( + false, + `${typeName} values must be an object with value names as keys.` + ); + return Object.entries(valueMap).map(([valueName, valueConfig]) => { + isPlainObj(valueConfig) || + (0, _devAssert.devAssert)( + false, + `${typeName}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${(0, + _inspect.inspect)(valueConfig)}.` + ); + return { + name: (0, _assertName.assertEnumValueName)(valueName), + description: valueConfig.description, + value: + valueConfig.value !== undefined ? valueConfig.value : valueName, + deprecationReason: valueConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), + astNode: valueConfig.astNode, + }; + }); + } -const escapeSequences = ['\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007', '\\b', '\\t', '\\n', '\\u000B', '\\f', '\\r', '\\u000E', '\\u000F', '\\u0010', '\\u0011', '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019', '\\u001A', '\\u001B', '\\u001C', '\\u001D', '\\u001E', '\\u001F', '', '', '\\"', '', '', '', '', '', '', '', '', '', '', '', '', '', -// 2F -'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', -// 3F -'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', -// 4F -'', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', -// 5F -'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', -// 6F -'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\u007F', '\\u0080', '\\u0081', '\\u0082', '\\u0083', '\\u0084', '\\u0085', '\\u0086', '\\u0087', '\\u0088', '\\u0089', '\\u008A', '\\u008B', '\\u008C', '\\u008D', '\\u008E', '\\u008F', '\\u0090', '\\u0091', '\\u0092', '\\u0093', '\\u0094', '\\u0095', '\\u0096', '\\u0097', '\\u0098', '\\u0099', '\\u009A', '\\u009B', '\\u009C', '\\u009D', '\\u009E', '\\u009F']; - -/***/ }), - -/***/ "../../../node_modules/graphql/language/printer.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/language/printer.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.print = print; -var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); -var _printString = __webpack_require__(/*! ./printString.mjs */ "../../../node_modules/graphql/language/printString.mjs"); -var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); -/** - * Converts an AST into a string, using one set of reasonable - * formatting rules. - */ - -function print(ast) { - return (0, _visitor.visit)(ast, printDocASTReducer); -} -const MAX_LINE_LENGTH = 80; -const printDocASTReducer = { - Name: { - leave: node => node.value - }, - Variable: { - leave: node => '$' + node.name - }, - // Document - Document: { - leave: node => join(node.definitions, '\n\n') - }, - OperationDefinition: { - leave(node) { - const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); - const prefix = join([node.operation, join([node.name, varDefs]), join(node.directives, ' ')], ' '); // Anonymous queries with no directives or variable definitions can use - // the query short form. - - return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; - } - }, - VariableDefinition: { - leave: ({ - variable, - type, - defaultValue, - directives - }) => variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')) - }, - SelectionSet: { - leave: ({ - selections - }) => block(selections) - }, - Field: { - leave({ - alias, - name, - arguments: args, - directives, - selectionSet - }) { - const prefix = wrap('', alias, ': ') + name; - let argsLine = prefix + wrap('(', join(args, ', '), ')'); - if (argsLine.length > MAX_LINE_LENGTH) { - argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); - } - return join([argsLine, join(directives, ' '), selectionSet], ' '); - } - }, - Argument: { - leave: ({ - name, - value - }) => name + ': ' + value - }, - // Fragments - FragmentSpread: { - leave: ({ - name, - directives - }) => '...' + name + wrap(' ', join(directives, ' ')) - }, - InlineFragment: { - leave: ({ - typeCondition, - directives, - selectionSet - }) => join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ') - }, - FragmentDefinition: { - leave: ({ - name, - typeCondition, - variableDefinitions, - directives, - selectionSet - } // Note: fragment variable definitions are experimental and may be changed - ) => - // or removed in the future. - `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + selectionSet - }, - // Value - IntValue: { - leave: ({ - value - }) => value - }, - FloatValue: { - leave: ({ - value - }) => value - }, - StringValue: { - leave: ({ - value, - block: isBlockString - }) => isBlockString ? (0, _blockString.printBlockString)(value) : (0, _printString.printString)(value) - }, - BooleanValue: { - leave: ({ - value - }) => value ? 'true' : 'false' - }, - NullValue: { - leave: () => 'null' - }, - EnumValue: { - leave: ({ - value - }) => value - }, - ListValue: { - leave: ({ - values - }) => '[' + join(values, ', ') + ']' - }, - ObjectValue: { - leave: ({ - fields - }) => '{' + join(fields, ', ') + '}' - }, - ObjectField: { - leave: ({ - name, - value - }) => name + ': ' + value - }, - // Directive - Directive: { - leave: ({ - name, - arguments: args - }) => '@' + name + wrap('(', join(args, ', '), ')') - }, - // Type - NamedType: { - leave: ({ - name - }) => name - }, - ListType: { - leave: ({ - type - }) => '[' + type + ']' - }, - NonNullType: { - leave: ({ - type - }) => type + '!' - }, - // Type System Definitions - SchemaDefinition: { - leave: ({ - description, - directives, - operationTypes - }) => wrap('', description, '\n') + join(['schema', join(directives, ' '), block(operationTypes)], ' ') - }, - OperationTypeDefinition: { - leave: ({ - operation, - type - }) => operation + ': ' + type - }, - ScalarTypeDefinition: { - leave: ({ - description, - name, - directives - }) => wrap('', description, '\n') + join(['scalar', name, join(directives, ' ')], ' ') - }, - ObjectTypeDefinition: { - leave: ({ - description, - name, - interfaces, - directives, - fields - }) => wrap('', description, '\n') + join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - FieldDefinition: { - leave: ({ - description, - name, - arguments: args, - type, - directives - }) => wrap('', description, '\n') + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' ')) - }, - InputValueDefinition: { - leave: ({ - description, - name, - type, - defaultValue, - directives - }) => wrap('', description, '\n') + join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ') - }, - InterfaceTypeDefinition: { - leave: ({ - description, - name, - interfaces, - directives, - fields - }) => wrap('', description, '\n') + join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - UnionTypeDefinition: { - leave: ({ - description, - name, - directives, - types - }) => wrap('', description, '\n') + join(['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') - }, - EnumTypeDefinition: { - leave: ({ - description, - name, - directives, - values - }) => wrap('', description, '\n') + join(['enum', name, join(directives, ' '), block(values)], ' ') - }, - EnumValueDefinition: { - leave: ({ - description, - name, - directives - }) => wrap('', description, '\n') + join([name, join(directives, ' ')], ' ') - }, - InputObjectTypeDefinition: { - leave: ({ - description, - name, - directives, - fields - }) => wrap('', description, '\n') + join(['input', name, join(directives, ' '), block(fields)], ' ') - }, - DirectiveDefinition: { - leave: ({ - description, - name, - arguments: args, - repeatable, - locations - }) => wrap('', description, '\n') + 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ') - }, - SchemaExtension: { - leave: ({ - directives, - operationTypes - }) => join(['extend schema', join(directives, ' '), block(operationTypes)], ' ') - }, - ScalarTypeExtension: { - leave: ({ - name, - directives - }) => join(['extend scalar', name, join(directives, ' ')], ' ') - }, - ObjectTypeExtension: { - leave: ({ - name, - interfaces, - directives, - fields - }) => join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - InterfaceTypeExtension: { - leave: ({ - name, - interfaces, - directives, - fields - }) => join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - UnionTypeExtension: { - leave: ({ - name, - directives, - types - }) => join(['extend union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') - }, - EnumTypeExtension: { - leave: ({ - name, - directives, - values - }) => join(['extend enum', name, join(directives, ' '), block(values)], ' ') - }, - InputObjectTypeExtension: { - leave: ({ - name, - directives, - fields - }) => join(['extend input', name, join(directives, ' '), block(fields)], ' ') - } -}; -/** - * Given maybeArray, print an empty string if it is null or empty, otherwise - * print all items together separated by separator if provided - */ - -function join(maybeArray, separator = '') { - var _maybeArray$filter$jo; - return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(x => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : ''; -} -/** - * Given array, print each item on its own line, wrapped in an indented `{ }` block. - */ - -function block(array) { - return wrap('{\n', indent(join(array, '\n')), '\n}'); -} -/** - * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. - */ - -function wrap(start, maybeString, end = '') { - return maybeString != null && maybeString !== '' ? start + maybeString + end : ''; -} -function indent(str) { - return wrap(' ', str.replace(/\n/g, '\n ')); -} -function hasMultilineItems(maybeArray) { - var _maybeArray$some; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - return (_maybeArray$some = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some(str => str.includes('\n'))) !== null && _maybeArray$some !== void 0 ? _maybeArray$some : false; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/language/source.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/language/source.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Source = void 0; -exports.isSource = isSource; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); -/** - * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are - * optional, but they are useful for clients who store GraphQL documents in source files. - * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might - * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. - * The `line` and `column` properties in `locationOffset` are 1-indexed. - */ -class Source { - constructor(body, name = 'GraphQL request', locationOffset = { - line: 1, - column: 1 - }) { - typeof body === 'string' || (0, _devAssert.devAssert)(false, `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`); - this.body = body; - this.name = name; - this.locationOffset = locationOffset; - this.locationOffset.line > 0 || (0, _devAssert.devAssert)(false, 'line in locationOffset is 1-indexed and must be positive.'); - this.locationOffset.column > 0 || (0, _devAssert.devAssert)(false, 'column in locationOffset is 1-indexed and must be positive.'); - } - get [Symbol.toStringTag]() { - return 'Source'; - } -} -/** - * Test if the given value is a Source object. - * - * @internal - */ -exports.Source = Source; -function isSource(source) { - return (0, _instanceOf.instanceOf)(source, Source); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/language/tokenKind.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/language/tokenKind.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.TokenKind = void 0; -/** - * An exported enum describing the different kinds of tokens that the - * lexer emits. - */ -var TokenKind; -(function (TokenKind) { - TokenKind['SOF'] = ''; - TokenKind['EOF'] = ''; - TokenKind['BANG'] = '!'; - TokenKind['DOLLAR'] = '$'; - TokenKind['AMP'] = '&'; - TokenKind['PAREN_L'] = '('; - TokenKind['PAREN_R'] = ')'; - TokenKind['SPREAD'] = '...'; - TokenKind['COLON'] = ':'; - TokenKind['EQUALS'] = '='; - TokenKind['AT'] = '@'; - TokenKind['BRACKET_L'] = '['; - TokenKind['BRACKET_R'] = ']'; - TokenKind['BRACE_L'] = '{'; - TokenKind['PIPE'] = '|'; - TokenKind['BRACE_R'] = '}'; - TokenKind['NAME'] = 'Name'; - TokenKind['INT'] = 'Int'; - TokenKind['FLOAT'] = 'Float'; - TokenKind['STRING'] = 'String'; - TokenKind['BLOCK_STRING'] = 'BlockString'; - TokenKind['COMMENT'] = 'Comment'; -})(TokenKind || (exports.TokenKind = TokenKind = {})); - -/** - * The enum type representing the token kinds values. - * - * @deprecated Please use `TokenKind`. Will be remove in v17. - */ - -/***/ }), - -/***/ "../../../node_modules/graphql/language/visitor.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/language/visitor.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.BREAK = void 0; -exports.getEnterLeaveForKind = getEnterLeaveForKind; -exports.getVisitFn = getVisitFn; -exports.visit = visit; -exports.visitInParallel = visitInParallel; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -/** - * A visitor is provided to visit, it contains the collection of - * relevant functions to be called during the visitor's traversal. - */ - -const BREAK = exports.BREAK = Object.freeze({}); -/** - * visit() will walk through an AST using a depth-first traversal, calling - * the visitor's enter function at each node in the traversal, and calling the - * leave function after visiting that node and all of its child nodes. - * - * By returning different values from the enter and leave functions, the - * behavior of the visitor can be altered, including skipping over a sub-tree of - * the AST (by returning false), editing the AST by returning a value or null - * to remove the value, or to stop the whole traversal by returning BREAK. - * - * When using visit() to edit an AST, the original AST will not be modified, and - * a new version of the AST with the changes applied will be returned from the - * visit function. - * - * ```ts - * const editedAST = visit(ast, { - * enter(node, key, parent, path, ancestors) { - * // @return - * // undefined: no action - * // false: skip visiting this node - * // visitor.BREAK: stop visiting altogether - * // null: delete this node - * // any value: replace this node with the returned value - * }, - * leave(node, key, parent, path, ancestors) { - * // @return - * // undefined: no action - * // false: no action - * // visitor.BREAK: stop visiting altogether - * // null: delete this node - * // any value: replace this node with the returned value - * } - * }); - * ``` - * - * Alternatively to providing enter() and leave() functions, a visitor can - * instead provide functions named the same as the kinds of AST nodes, or - * enter/leave visitors at a named key, leading to three permutations of the - * visitor API: - * - * 1) Named visitors triggered when entering a node of a specific kind. - * - * ```ts - * visit(ast, { - * Kind(node) { - * // enter the "Kind" node - * } - * }) - * ``` - * - * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. - * - * ```ts - * visit(ast, { - * Kind: { - * enter(node) { - * // enter the "Kind" node - * } - * leave(node) { - * // leave the "Kind" node - * } - * } - * }) - * ``` - * - * 3) Generic visitors that trigger upon entering and leaving any node. - * - * ```ts - * visit(ast, { - * enter(node) { - * // enter any node - * }, - * leave(node) { - * // leave any node - * } - * }) - * ``` - */ - -function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { - const enterLeaveMap = new Map(); - for (const kind of Object.values(_kinds.Kind)) { - enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); - } - /* eslint-disable no-undef-init */ - - let stack = undefined; - let inArray = Array.isArray(root); - let keys = [root]; - let index = -1; - let edits = []; - let node = root; - let key = undefined; - let parent = undefined; - const path = []; - const ancestors = []; - /* eslint-enable no-undef-init */ - - do { - index++; - const isLeaving = index === keys.length; - const isEdited = isLeaving && edits.length !== 0; - if (isLeaving) { - key = ancestors.length === 0 ? undefined : path[path.length - 1]; - node = parent; - parent = ancestors.pop(); - if (isEdited) { - if (inArray) { - node = node.slice(); - let editOffset = 0; - for (const [editKey, editValue] of edits) { - const arrayKey = editKey - editOffset; - if (editValue === null) { - node.splice(arrayKey, 1); - editOffset++; - } else { - node[arrayKey] = editValue; + /** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` + */ + class GraphQLInputObjectType { + constructor(config) { + var _config$extensionASTN6; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN6 = config.extensionASTNodes) !== null && + _config$extensionASTN6 !== void 0 + ? _config$extensionASTN6 + : []; + this._fields = defineInputFieldMap.bind(undefined, config); + } + get [Symbol.toStringTag]() { + return "GraphQLInputObjectType"; + } + getFields() { + if (typeof this._fields === "function") { + this._fields = this._fields(); } + return this._fields; + } + toConfig() { + const fields = (0, _mapValue.mapValue)( + this.getFields(), + (field) => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + }) + ); + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; } - } else { - node = Object.defineProperties({}, Object.getOwnPropertyDescriptors(node)); - for (const [editKey, editValue] of edits) { - node[editKey] = editValue; + toString() { + return this.name; + } + toJSON() { + return this.toString(); } } - } - index = stack.index; - keys = stack.keys; - edits = stack.edits; - inArray = stack.inArray; - stack = stack.prev; - } else if (parent) { - key = inArray ? index : keys[index]; - node = parent[key]; - if (node === null || node === undefined) { - continue; - } - path.push(key); - } - let result; - if (!Array.isArray(node)) { - var _enterLeaveMap$get, _enterLeaveMap$get2; - (0, _ast.isNode)(node) || (0, _devAssert.devAssert)(false, `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`); - const visitFn = isLeaving ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get === void 0 ? void 0 : _enterLeaveMap$get.leave : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get2 === void 0 ? void 0 : _enterLeaveMap$get2.enter; - result = visitFn === null || visitFn === void 0 ? void 0 : visitFn.call(visitor, node, key, parent, path, ancestors); - if (result === BREAK) { - break; - } - if (result === false) { - if (!isLeaving) { - path.pop(); - continue; - } - } else if (result !== undefined) { - edits.push([key, result]); - if (!isLeaving) { - if ((0, _ast.isNode)(result)) { - node = result; - } else { - path.pop(); - continue; + exports.GraphQLInputObjectType = GraphQLInputObjectType; + function defineInputFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + (0, _devAssert.devAssert)( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.` + ); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + !("resolve" in fieldConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.` + ); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); + } + function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; + } + + /***/ + }, + + /***/ "../../../node_modules/graphql/type/directives.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/directives.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.GraphQLSpecifiedByDirective = + exports.GraphQLSkipDirective = + exports.GraphQLIncludeDirective = + exports.GraphQLDirective = + exports.GraphQLDeprecatedDirective = + exports.DEFAULT_DEPRECATION_REASON = + void 0; + exports.assertDirective = assertDirective; + exports.isDirective = isDirective; + exports.isSpecifiedDirective = isSpecifiedDirective; + exports.specifiedDirectives = void 0; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _instanceOf = __webpack_require__( + /*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _toObjMap = __webpack_require__( + /*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs" + ); + var _directiveLocation = __webpack_require__( + /*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs" + ); + var _assertName = __webpack_require__( + /*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs" + ); + var _definition = __webpack_require__( + /*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _scalars = __webpack_require__( + /*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + /** + * Test if the given value is a GraphQL directive. + */ + + function isDirective(directive) { + return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); + } + function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + directive + )} to be a GraphQL directive.` + ); } + return directive; } - } - } - if (result === undefined && isEdited) { - edits.push([key, node]); - } - if (isLeaving) { - path.pop(); - } else { - var _node$kind; - stack = { - inArray, - index, - keys, - edits, - prev: stack - }; - inArray = Array.isArray(node); - keys = inArray ? node : (_node$kind = visitorKeys[node.kind]) !== null && _node$kind !== void 0 ? _node$kind : []; - index = -1; - edits = []; - if (parent) { - ancestors.push(parent); - } - parent = node; - } - } while (stack !== undefined); - if (edits.length !== 0) { - // New root - return edits[edits.length - 1][1]; - } - return root; -} -/** - * Creates a new visitor instance which delegates to many visitors to run in - * parallel. Each visitor will be visited for each node before moving on. - * - * If a prior visitor edits a node, no following visitors will see that node. - */ - -function visitInParallel(visitors) { - const skipping = new Array(visitors.length).fill(null); - const mergedVisitor = Object.create(null); - for (const kind of Object.values(_kinds.Kind)) { - let hasVisitor = false; - const enterList = new Array(visitors.length).fill(undefined); - const leaveList = new Array(visitors.length).fill(undefined); - for (let i = 0; i < visitors.length; ++i) { - const { - enter, - leave - } = getEnterLeaveForKind(visitors[i], kind); - hasVisitor || (hasVisitor = enter != null || leave != null); - enterList[i] = enter; - leaveList[i] = leave; - } - if (!hasVisitor) { - continue; - } - const mergedEnterLeave = { - enter(...args) { - const node = args[0]; - for (let i = 0; i < visitors.length; i++) { - if (skipping[i] === null) { - var _enterList$i; - const result = (_enterList$i = enterList[i]) === null || _enterList$i === void 0 ? void 0 : _enterList$i.apply(visitors[i], args); - if (result === false) { - skipping[i] = node; - } else if (result === BREAK) { - skipping[i] = BREAK; - } else if (result !== undefined) { - return result; - } + /** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + + /** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + class GraphQLDirective { + constructor(config) { + var _config$isRepeatable, _config$args; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = + (_config$isRepeatable = config.isRepeatable) !== null && + _config$isRepeatable !== void 0 + ? _config$isRepeatable + : false; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + Array.isArray(config.locations) || + (0, _devAssert.devAssert)( + false, + `@${config.name} locations must be an Array.` + ); + const args = + (_config$args = config.args) !== null && _config$args !== void 0 + ? _config$args + : {}; + ((0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args)) || + (0, _devAssert.devAssert)( + false, + `@${config.name} args must be an object with argument names as keys.` + ); + this.args = (0, _definition.defineArguments)(args); + } + get [Symbol.toStringTag]() { + return "GraphQLDirective"; + } + toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: (0, _definition.argsToArgsConfig)(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode, + }; + } + toString() { + return "@" + this.name; + } + toJSON() { + return this.toString(); } } + + /** + * Used to conditionally include fields or fragments. + */ + exports.GraphQLDirective = GraphQLDirective; + const GraphQLIncludeDirective = (exports.GraphQLIncludeDirective = + new GraphQLDirective({ + name: "include", + description: + "Directs the executor to include this field or fragment only when the `if` argument is true.", + locations: [ + _directiveLocation.DirectiveLocation.FIELD, + _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: "Included when true.", + }, + }, + })); + /** + * Used to conditionally skip (exclude) fields or fragments. + */ + + const GraphQLSkipDirective = (exports.GraphQLSkipDirective = + new GraphQLDirective({ + name: "skip", + description: + "Directs the executor to skip this field or fragment when the `if` argument is true.", + locations: [ + _directiveLocation.DirectiveLocation.FIELD, + _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: "Skipped when true.", + }, + }, + })); + /** + * Constant string used for default reason for a deprecation. + */ + + const DEFAULT_DEPRECATION_REASON = (exports.DEFAULT_DEPRECATION_REASON = + "No longer supported"); + /** + * Used to declare element of a GraphQL schema as deprecated. + */ + + const GraphQLDeprecatedDirective = (exports.GraphQLDeprecatedDirective = + new GraphQLDirective({ + name: "deprecated", + description: + "Marks an element of a GraphQL schema as no longer supported.", + locations: [ + _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + _directiveLocation.DirectiveLocation.ENUM_VALUE, + ], + args: { + reason: { + type: _scalars.GraphQLString, + description: + "Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).", + defaultValue: DEFAULT_DEPRECATION_REASON, + }, + }, + })); + /** + * Used to provide a URL for specifying the behavior of custom scalar definitions. + */ + + const GraphQLSpecifiedByDirective = + (exports.GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: "specifiedBy", + description: + "Exposes a URL that specifies the behavior of this scalar.", + locations: [_directiveLocation.DirectiveLocation.SCALAR], + args: { + url: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: + "The URL that specifies the behavior of this scalar.", + }, + }, + })); + /** + * The full list of specified directives. + */ + + const specifiedDirectives = (exports.specifiedDirectives = + Object.freeze([ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + ])); + function isSpecifiedDirective(directive) { + return specifiedDirectives.some( + ({ name }) => name === directive.name + ); + } + + /***/ + }, + + /***/ "../../../node_modules/graphql/type/index.mjs": + /*!****************************************************!*\ + !*** ../../../node_modules/graphql/type/index.mjs ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function () { + return _directives.DEFAULT_DEPRECATION_REASON; + }, + }); + Object.defineProperty(exports, "GRAPHQL_MAX_INT", { + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MAX_INT; + }, + }); + Object.defineProperty(exports, "GRAPHQL_MIN_INT", { + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MIN_INT; + }, + }); + Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function () { + return _scalars.GraphQLBoolean; + }, + }); + Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function () { + return _directives.GraphQLDeprecatedDirective; + }, + }); + Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function () { + return _directives.GraphQLDirective; + }, + }); + Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function () { + return _definition.GraphQLEnumType; + }, + }); + Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function () { + return _scalars.GraphQLFloat; + }, + }); + Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function () { + return _scalars.GraphQLID; + }, + }); + Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function () { + return _directives.GraphQLIncludeDirective; + }, + }); + Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function () { + return _definition.GraphQLInputObjectType; + }, + }); + Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function () { + return _scalars.GraphQLInt; + }, + }); + Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function () { + return _definition.GraphQLInterfaceType; + }, + }); + Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function () { + return _definition.GraphQLList; + }, + }); + Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function () { + return _definition.GraphQLNonNull; + }, + }); + Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function () { + return _definition.GraphQLObjectType; + }, + }); + Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function () { + return _definition.GraphQLScalarType; + }, + }); + Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function () { + return _schema.GraphQLSchema; + }, + }); + Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function () { + return _directives.GraphQLSkipDirective; + }, + }); + Object.defineProperty(exports, "GraphQLSpecifiedByDirective", { + enumerable: true, + get: function () { + return _directives.GraphQLSpecifiedByDirective; + }, + }); + Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function () { + return _scalars.GraphQLString; + }, + }); + Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function () { + return _definition.GraphQLUnionType; + }, + }); + Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function () { + return _introspection.SchemaMetaFieldDef; + }, + }); + Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function () { + return _introspection.TypeKind; + }, + }); + Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function () { + return _introspection.TypeMetaFieldDef; + }, + }); + Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function () { + return _introspection.TypeNameMetaFieldDef; + }, + }); + Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function () { + return _introspection.__Directive; + }, + }); + Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function () { + return _introspection.__DirectiveLocation; + }, + }); + Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function () { + return _introspection.__EnumValue; + }, + }); + Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function () { + return _introspection.__Field; + }, + }); + Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function () { + return _introspection.__InputValue; + }, + }); + Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function () { + return _introspection.__Schema; + }, + }); + Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function () { + return _introspection.__Type; + }, + }); + Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function () { + return _introspection.__TypeKind; + }, + }); + Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function () { + return _definition.assertAbstractType; + }, + }); + Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function () { + return _definition.assertCompositeType; + }, + }); + Object.defineProperty(exports, "assertDirective", { + enumerable: true, + get: function () { + return _directives.assertDirective; + }, + }); + Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function () { + return _definition.assertEnumType; + }, + }); + Object.defineProperty(exports, "assertEnumValueName", { + enumerable: true, + get: function () { + return _assertName.assertEnumValueName; + }, + }); + Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function () { + return _definition.assertInputObjectType; + }, + }); + Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function () { + return _definition.assertInputType; + }, + }); + Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function () { + return _definition.assertInterfaceType; + }, + }); + Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function () { + return _definition.assertLeafType; + }, + }); + Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function () { + return _definition.assertListType; + }, + }); + Object.defineProperty(exports, "assertName", { + enumerable: true, + get: function () { + return _assertName.assertName; + }, + }); + Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function () { + return _definition.assertNamedType; + }, + }); + Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function () { + return _definition.assertNonNullType; + }, + }); + Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function () { + return _definition.assertNullableType; + }, + }); + Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function () { + return _definition.assertObjectType; + }, + }); + Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function () { + return _definition.assertOutputType; + }, + }); + Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function () { + return _definition.assertScalarType; + }, + }); + Object.defineProperty(exports, "assertSchema", { + enumerable: true, + get: function () { + return _schema.assertSchema; + }, + }); + Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function () { + return _definition.assertType; + }, + }); + Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function () { + return _definition.assertUnionType; + }, + }); + Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function () { + return _validate.assertValidSchema; + }, + }); + Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function () { + return _definition.assertWrappingType; + }, + }); + Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function () { + return _definition.getNamedType; + }, + }); + Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function () { + return _definition.getNullableType; + }, + }); + Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function () { + return _introspection.introspectionTypes; + }, + }); + Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function () { + return _definition.isAbstractType; + }, + }); + Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function () { + return _definition.isCompositeType; + }, + }); + Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function () { + return _directives.isDirective; + }, + }); + Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function () { + return _definition.isEnumType; + }, + }); + Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function () { + return _definition.isInputObjectType; + }, + }); + Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function () { + return _definition.isInputType; + }, + }); + Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function () { + return _definition.isInterfaceType; + }, + }); + Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function () { + return _introspection.isIntrospectionType; + }, + }); + Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function () { + return _definition.isLeafType; + }, + }); + Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function () { + return _definition.isListType; + }, + }); + Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function () { + return _definition.isNamedType; + }, + }); + Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function () { + return _definition.isNonNullType; + }, + }); + Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function () { + return _definition.isNullableType; + }, + }); + Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function () { + return _definition.isObjectType; + }, + }); + Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function () { + return _definition.isOutputType; + }, + }); + Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function () { + return _definition.isRequiredArgument; + }, + }); + Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function () { + return _definition.isRequiredInputField; + }, + }); + Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function () { + return _definition.isScalarType; + }, + }); + Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function () { + return _schema.isSchema; + }, + }); + Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function () { + return _directives.isSpecifiedDirective; + }, + }); + Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function () { + return _scalars.isSpecifiedScalarType; + }, + }); + Object.defineProperty(exports, "isType", { + enumerable: true, + get: function () { + return _definition.isType; + }, + }); + Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function () { + return _definition.isUnionType; + }, + }); + Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function () { + return _definition.isWrappingType; + }, + }); + Object.defineProperty(exports, "resolveObjMapThunk", { + enumerable: true, + get: function () { + return _definition.resolveObjMapThunk; + }, + }); + Object.defineProperty(exports, "resolveReadonlyArrayThunk", { + enumerable: true, + get: function () { + return _definition.resolveReadonlyArrayThunk; + }, + }); + Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function () { + return _directives.specifiedDirectives; + }, + }); + Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function () { + return _scalars.specifiedScalarTypes; + }, + }); + Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function () { + return _validate.validateSchema; + }, + }); + var _schema = __webpack_require__( + /*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs" + ); + var _definition = __webpack_require__( + /*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _scalars = __webpack_require__( + /*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + var _introspection = __webpack_require__( + /*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _validate = __webpack_require__( + /*! ./validate.mjs */ "../../../node_modules/graphql/type/validate.mjs" + ); + var _assertName = __webpack_require__( + /*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs" + ); + + /***/ }, - leave(...args) { - const node = args[0]; - for (let i = 0; i < visitors.length; i++) { - if (skipping[i] === null) { - var _leaveList$i; - const result = (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 ? void 0 : _leaveList$i.apply(visitors[i], args); - if (result === BREAK) { - skipping[i] = BREAK; - } else if (result !== undefined && result !== false) { - return result; - } - } else if (skipping[i] === node) { - skipping[i] = null; - } - } - } - }; - mergedVisitor[kind] = mergedEnterLeave; - } - return mergedVisitor; -} -/** - * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. - */ - -function getEnterLeaveForKind(visitor, kind) { - const kindVisitor = visitor[kind]; - if (typeof kindVisitor === 'object') { - // { Kind: { enter() {}, leave() {} } } - return kindVisitor; - } else if (typeof kindVisitor === 'function') { - // { Kind() {} } - return { - enter: kindVisitor, - leave: undefined - }; - } // { enter() {}, leave() {} } - return { - enter: visitor.enter, - leave: visitor.leave - }; -} -/** - * Given a visitor instance, if it is leaving or not, and a node kind, return - * the function the visitor runtime should call. - * - * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 - */ - -/* c8 ignore next 8 */ - -function getVisitFn(visitor, kind, isLeaving) { - const { - enter, - leave - } = getEnterLeaveForKind(visitor, kind); - return isLeaving ? leave : enter; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/type/assertName.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/type/assertName.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.assertEnumValueName = assertEnumValueName; -exports.assertName = assertName; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _characterClasses = __webpack_require__(/*! ../language/characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); -/** - * Upholds the spec rules about naming. - */ - -function assertName(name) { - name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); - typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); - if (name.length === 0) { - throw new _GraphQLError.GraphQLError('Expected name to be a non-empty string.'); - } - for (let i = 1; i < name.length; ++i) { - if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { - throw new _GraphQLError.GraphQLError(`Names must only contain [_a-zA-Z0-9] but "${name}" does not.`); - } - } - if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { - throw new _GraphQLError.GraphQLError(`Names must start with [_a-zA-Z] but "${name}" does not.`); - } - return name; -} -/** - * Upholds the spec rules about naming enum values. - * - * @internal - */ - -function assertEnumValueName(name) { - if (name === 'true' || name === 'false' || name === 'null') { - throw new _GraphQLError.GraphQLError(`Enum values cannot be named: ${name}`); - } - return assertName(name); -} + /***/ "../../../node_modules/graphql/type/introspection.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/type/introspection.mjs ***! + \************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.introspectionTypes = + exports.__TypeKind = + exports.__Type = + exports.__Schema = + exports.__InputValue = + exports.__Field = + exports.__EnumValue = + exports.__DirectiveLocation = + exports.__Directive = + exports.TypeNameMetaFieldDef = + exports.TypeMetaFieldDef = + exports.TypeKind = + exports.SchemaMetaFieldDef = + void 0; + exports.isIntrospectionType = isIntrospectionType; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _directiveLocation = __webpack_require__( + /*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs" + ); + var _printer = __webpack_require__( + /*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _astFromValue = __webpack_require__( + /*! ../utilities/astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs" + ); + var _definition = __webpack_require__( + /*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _scalars = __webpack_require__( + /*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + const __Schema = (exports.__Schema = new _definition.GraphQLObjectType({ + name: "__Schema", + description: + "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.", + fields: () => ({ + description: { + type: _scalars.GraphQLString, + resolve: (schema) => schema.description, + }, + types: { + description: "A list of all types supported by this server.", + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Type) + ) + ), + resolve(schema) { + return Object.values(schema.getTypeMap()); + }, + }, + queryType: { + description: "The type that query operations will be rooted at.", + type: new _definition.GraphQLNonNull(__Type), + resolve: (schema) => schema.getQueryType(), + }, + mutationType: { + description: + "If this server supports mutation, the type that mutation operations will be rooted at.", + type: __Type, + resolve: (schema) => schema.getMutationType(), + }, + subscriptionType: { + description: + "If this server support subscription, the type that subscription operations will be rooted at.", + type: __Type, + resolve: (schema) => schema.getSubscriptionType(), + }, + directives: { + description: "A list of all directives supported by this server.", + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Directive) + ) + ), + resolve: (schema) => schema.getDirectives(), + }, + }), + })); + const __Directive = (exports.__Directive = + new _definition.GraphQLObjectType({ + name: "__Directive", + description: + "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (directive) => directive.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (directive) => directive.description, + }, + isRepeatable: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (directive) => directive.isRepeatable, + }, + locations: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__DirectiveLocation) + ) + ), + resolve: (directive) => directive.locations, + }, + args: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue) + ) + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + }), + })); + const __DirectiveLocation = (exports.__DirectiveLocation = + new _definition.GraphQLEnumType({ + name: "__DirectiveLocation", + description: + "A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.", + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: "Location adjacent to a query operation.", + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: "Location adjacent to a mutation operation.", + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: "Location adjacent to a subscription operation.", + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: "Location adjacent to a field.", + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: "Location adjacent to a fragment definition.", + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: "Location adjacent to a fragment spread.", + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: "Location adjacent to an inline fragment.", + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: "Location adjacent to a variable definition.", + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: "Location adjacent to a schema definition.", + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: "Location adjacent to a scalar definition.", + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: "Location adjacent to an object type definition.", + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: "Location adjacent to a field definition.", + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: "Location adjacent to an argument definition.", + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: "Location adjacent to an interface definition.", + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: "Location adjacent to a union definition.", + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: "Location adjacent to an enum definition.", + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: "Location adjacent to an enum value definition.", + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: + "Location adjacent to an input object type definition.", + }, + INPUT_FIELD_DEFINITION: { + value: + _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: + "Location adjacent to an input object field definition.", + }, + }, + })); + const __Type = (exports.__Type = new _definition.GraphQLObjectType({ + name: "__Type", + description: + "The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.", + fields: () => ({ + kind: { + type: new _definition.GraphQLNonNull(__TypeKind), + resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } + if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } + if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } + if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } + if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } + if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } + if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } + if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered) + + false || + (0, _invariant.invariant)( + false, + `Unexpected type: "${(0, _inspect.inspect)(type)}".` + ); + }, + }, + name: { + type: _scalars.GraphQLString, + resolve: (type) => ("name" in type ? type.name : undefined), + }, + description: { + type: _scalars.GraphQLString, + resolve: ( + type /* c8 ignore next */ // FIXME: add test case + ) => ("description" in type ? type.description : undefined), + }, + specifiedByURL: { + type: _scalars.GraphQLString, + resolve: (obj) => + "specifiedByURL" in obj ? obj.specifiedByURL : undefined, + }, + fields: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Field) + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(type, { includeDeprecated }) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + const fields = Object.values(type.getFields()); + return includeDeprecated + ? fields + : fields.filter((field) => field.deprecationReason == null); + } + }, + }, + interfaces: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Type) + ), + resolve(type) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Type) + ), + resolve(type, _args, _context, { schema }) { + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__EnumValue) + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(type, { includeDeprecated }) { + if ((0, _definition.isEnumType)(type)) { + const values = type.getValues(); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + inputFields: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue) + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(type, { includeDeprecated }) { + if ((0, _definition.isInputObjectType)(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + ofType: { + type: __Type, + resolve: (type) => ("ofType" in type ? type.ofType : undefined), + }, + }), + })); + const __Field = (exports.__Field = new _definition.GraphQLObjectType({ + name: "__Field", + description: + "Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (field) => field.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (field) => field.description, + }, + args: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue) + ) + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: (field) => field.type, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (field) => field.deprecationReason, + }, + }), + })); + const __InputValue = (exports.__InputValue = + new _definition.GraphQLObjectType({ + name: "__InputValue", + description: + "Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (inputValue) => inputValue.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (inputValue) => inputValue.description, + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: (inputValue) => inputValue.type, + }, + defaultValue: { + type: _scalars.GraphQLString, + description: + "A GraphQL-formatted string representing the default value for this input value.", + resolve(inputValue) { + const { type, defaultValue } = inputValue; + const valueAST = (0, _astFromValue.astFromValue)( + defaultValue, + type + ); + return valueAST ? (0, _printer.print)(valueAST) : null; + }, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (obj) => obj.deprecationReason, + }, + }), + })); + const __EnumValue = (exports.__EnumValue = + new _definition.GraphQLObjectType({ + name: "__EnumValue", + description: + "One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (enumValue) => enumValue.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (enumValue) => enumValue.description, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (enumValue) => enumValue.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (enumValue) => enumValue.deprecationReason, + }, + }), + })); + var TypeKind; + (function (TypeKind) { + TypeKind["SCALAR"] = "SCALAR"; + TypeKind["OBJECT"] = "OBJECT"; + TypeKind["INTERFACE"] = "INTERFACE"; + TypeKind["UNION"] = "UNION"; + TypeKind["ENUM"] = "ENUM"; + TypeKind["INPUT_OBJECT"] = "INPUT_OBJECT"; + TypeKind["LIST"] = "LIST"; + TypeKind["NON_NULL"] = "NON_NULL"; + })(TypeKind || (exports.TypeKind = TypeKind = {})); + const __TypeKind = (exports.__TypeKind = + new _definition.GraphQLEnumType({ + name: "__TypeKind", + description: + "An enum describing what kind of type a given `__Type` is.", + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: "Indicates this type is a scalar.", + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + "Indicates this type is an object. `fields` and `interfaces` are valid fields.", + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + "Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.", + }, + UNION: { + value: TypeKind.UNION, + description: + "Indicates this type is a union. `possibleTypes` is a valid field.", + }, + ENUM: { + value: TypeKind.ENUM, + description: + "Indicates this type is an enum. `enumValues` is a valid field.", + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + "Indicates this type is an input object. `inputFields` is a valid field.", + }, + LIST: { + value: TypeKind.LIST, + description: + "Indicates this type is a list. `ofType` is a valid field.", + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + "Indicates this type is a non-null. `ofType` is a valid field.", + }, + }, + })); + /** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ -/***/ }), + const SchemaMetaFieldDef = (exports.SchemaMetaFieldDef = { + name: "__schema", + type: new _definition.GraphQLNonNull(__Schema), + description: "Access the current type schema of this server.", + args: [], + resolve: (_source, _args, _context, { schema }) => schema, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }); + const TypeMetaFieldDef = (exports.TypeMetaFieldDef = { + name: "__type", + type: __Type, + description: "Request the type information of a single type.", + args: [ + { + name: "name", + description: undefined, + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }, + ], + resolve: (_source, { name }, _context, { schema }) => + schema.getType(name), + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }); + const TypeNameMetaFieldDef = (exports.TypeNameMetaFieldDef = { + name: "__typename", + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: "The name of the current Object type at runtime.", + args: [], + resolve: (_source, _args, _context, { parentType }) => + parentType.name, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }); + const introspectionTypes = (exports.introspectionTypes = Object.freeze([ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + ])); + function isIntrospectionType(type) { + return introspectionTypes.some(({ name }) => type.name === name); + } + + /***/ + }, -/***/ "../../../node_modules/graphql/type/definition.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/type/definition.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GraphQLUnionType = exports.GraphQLScalarType = exports.GraphQLObjectType = exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInterfaceType = exports.GraphQLInputObjectType = exports.GraphQLEnumType = void 0; -exports.argsToArgsConfig = argsToArgsConfig; -exports.assertAbstractType = assertAbstractType; -exports.assertCompositeType = assertCompositeType; -exports.assertEnumType = assertEnumType; -exports.assertInputObjectType = assertInputObjectType; -exports.assertInputType = assertInputType; -exports.assertInterfaceType = assertInterfaceType; -exports.assertLeafType = assertLeafType; -exports.assertListType = assertListType; -exports.assertNamedType = assertNamedType; -exports.assertNonNullType = assertNonNullType; -exports.assertNullableType = assertNullableType; -exports.assertObjectType = assertObjectType; -exports.assertOutputType = assertOutputType; -exports.assertScalarType = assertScalarType; -exports.assertType = assertType; -exports.assertUnionType = assertUnionType; -exports.assertWrappingType = assertWrappingType; -exports.defineArguments = defineArguments; -exports.getNamedType = getNamedType; -exports.getNullableType = getNullableType; -exports.isAbstractType = isAbstractType; -exports.isCompositeType = isCompositeType; -exports.isEnumType = isEnumType; -exports.isInputObjectType = isInputObjectType; -exports.isInputType = isInputType; -exports.isInterfaceType = isInterfaceType; -exports.isLeafType = isLeafType; -exports.isListType = isListType; -exports.isNamedType = isNamedType; -exports.isNonNullType = isNonNullType; -exports.isNullableType = isNullableType; -exports.isObjectType = isObjectType; -exports.isOutputType = isOutputType; -exports.isRequiredArgument = isRequiredArgument; -exports.isRequiredInputField = isRequiredInputField; -exports.isScalarType = isScalarType; -exports.isType = isType; -exports.isUnionType = isUnionType; -exports.isWrappingType = isWrappingType; -exports.resolveObjMapThunk = resolveObjMapThunk; -exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _identityFunc = __webpack_require__(/*! ../jsutils/identityFunc.mjs */ "../../../node_modules/graphql/jsutils/identityFunc.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); -var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); -var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _valueFromASTUntyped = __webpack_require__(/*! ../utilities/valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); -var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); -function isType(type) { - return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); -} -function assertType(type) { - if (!isType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`); - } - return type; -} -/** - * There are predicates for each kind of GraphQL type. - */ - -function isScalarType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); -} -function assertScalarType(type) { - if (!isScalarType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`); - } - return type; -} -function isObjectType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); -} -function assertObjectType(type) { - if (!isObjectType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`); - } - return type; -} -function isInterfaceType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); -} -function assertInterfaceType(type) { - if (!isInterfaceType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`); - } - return type; -} -function isUnionType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); -} -function assertUnionType(type) { - if (!isUnionType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`); - } - return type; -} -function isEnumType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); -} -function assertEnumType(type) { - if (!isEnumType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`); - } - return type; -} -function isInputObjectType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); -} -function assertInputObjectType(type) { - if (!isInputObjectType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Input Object type.`); - } - return type; -} -function isListType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLList); -} -function assertListType(type) { - if (!isListType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`); - } - return type; -} -function isNonNullType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); -} -function assertNonNullType(type) { - if (!isNonNullType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`); - } - return type; -} -/** - * These types may be used as input types for arguments and directives. - */ - -function isInputType(type) { - return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); -} -function assertInputType(type) { - if (!isInputType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`); - } - return type; -} -/** - * These types may be used as output types as the result of fields. - */ - -function isOutputType(type) { - return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); -} -function assertOutputType(type) { - if (!isOutputType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`); - } - return type; -} -/** - * These types may describe types which may be leaf values. - */ - -function isLeafType(type) { - return isScalarType(type) || isEnumType(type); -} -function assertLeafType(type) { - if (!isLeafType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`); - } - return type; -} -/** - * These types may describe the parent context of a selection set. - */ - -function isCompositeType(type) { - return isObjectType(type) || isInterfaceType(type) || isUnionType(type); -} -function assertCompositeType(type) { - if (!isCompositeType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`); - } - return type; -} -/** - * These types may describe the parent context of a selection set. - */ - -function isAbstractType(type) { - return isInterfaceType(type) || isUnionType(type); -} -function assertAbstractType(type) { - if (!isAbstractType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`); - } - return type; -} -/** - * List Type Wrapper - * - * A list is a wrapping type which points to another type. - * Lists are often created within the context of defining the fields of - * an object type. - * - * Example: - * - * ```ts - * const PersonType = new GraphQLObjectType({ - * name: 'Person', - * fields: () => ({ - * parents: { type: new GraphQLList(PersonType) }, - * children: { type: new GraphQLList(PersonType) }, - * }) - * }) - * ``` - */ - -class GraphQLList { - constructor(ofType) { - isType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`); - this.ofType = ofType; - } - get [Symbol.toStringTag]() { - return 'GraphQLList'; - } - toString() { - return '[' + String(this.ofType) + ']'; - } - toJSON() { - return this.toString(); - } -} -/** - * Non-Null Type Wrapper - * - * A non-null is a wrapping type which points to another type. - * Non-null types enforce that their values are never null and can ensure - * an error is raised if this ever occurs during a request. It is useful for - * fields which you can make a strong guarantee on non-nullability, for example - * usually the id field of a database row will never be null. - * - * Example: - * - * ```ts - * const RowType = new GraphQLObjectType({ - * name: 'Row', - * fields: () => ({ - * id: { type: new GraphQLNonNull(GraphQLString) }, - * }) - * }) - * ``` - * Note: the enforcement of non-nullability occurs within the executor. - */ -exports.GraphQLList = GraphQLList; -class GraphQLNonNull { - constructor(ofType) { - isNullableType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL nullable type.`); - this.ofType = ofType; - } - get [Symbol.toStringTag]() { - return 'GraphQLNonNull'; - } - toString() { - return String(this.ofType) + '!'; - } - toJSON() { - return this.toString(); - } -} -/** - * These types wrap and modify other types - */ -exports.GraphQLNonNull = GraphQLNonNull; -function isWrappingType(type) { - return isListType(type) || isNonNullType(type); -} -function assertWrappingType(type) { - if (!isWrappingType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`); - } - return type; -} -/** - * These types can all accept null as a value. - */ - -function isNullableType(type) { - return isType(type) && !isNonNullType(type); -} -function assertNullableType(type) { - if (!isNullableType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`); - } - return type; -} -function getNullableType(type) { - if (type) { - return isNonNullType(type) ? type.ofType : type; - } -} -/** - * These named types do not include modifiers like List or NonNull. - */ - -function isNamedType(type) { - return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); -} -function assertNamedType(type) { - if (!isNamedType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`); - } - return type; -} -function getNamedType(type) { - if (type) { - let unwrappedType = type; - while (isWrappingType(unwrappedType)) { - unwrappedType = unwrappedType.ofType; - } - return unwrappedType; - } -} -/** - * Used while defining GraphQL types to allow for circular references in - * otherwise immutable type definitions. - */ - -function resolveReadonlyArrayThunk(thunk) { - return typeof thunk === 'function' ? thunk() : thunk; -} -function resolveObjMapThunk(thunk) { - return typeof thunk === 'function' ? thunk() : thunk; -} -/** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ - -/** - * Scalar Type Definition - * - * The leaf values of any request and input values to arguments are - * Scalars (or Enums) and are defined with a name and a series of functions - * used to parse input from ast or variables and to ensure validity. - * - * If a type's serialize function returns `null` or does not return a value - * (i.e. it returns `undefined`) then an error will be raised and a `null` - * value will be returned in the response. It is always better to validate - * - * Example: - * - * ```ts - * const OddType = new GraphQLScalarType({ - * name: 'Odd', - * serialize(value) { - * if (!Number.isFinite(value)) { - * throw new Error( - * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, - * ); - * } - * - * if (value % 2 === 0) { - * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); - * } - * return value; - * } - * }); - * ``` - */ -class GraphQLScalarType { - constructor(config) { - var _config$parseValue, _config$serialize, _config$parseLiteral, _config$extensionASTN; - const parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : _identityFunc.identityFunc; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.specifiedByURL = config.specifiedByURL; - this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : _identityFunc.identityFunc; - this.parseValue = parseValue; - this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : (node, variables) => parseValue((0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables)); - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; - config.specifiedByURL == null || typeof config.specifiedByURL === 'string' || (0, _devAssert.devAssert)(false, `${this.name} must provide "specifiedByURL" as a string, ` + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`); - config.serialize == null || typeof config.serialize === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`); - if (config.parseLiteral) { - typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide both "parseValue" and "parseLiteral" functions.`); - } - } - get [Symbol.toStringTag]() { - return 'GraphQLScalarType'; - } - toConfig() { - return { - name: this.name, - description: this.description, - specifiedByURL: this.specifiedByURL, - serialize: this.serialize, - parseValue: this.parseValue, - parseLiteral: this.parseLiteral, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } -} - -/** - * Object Type Definition - * - * Almost all of the GraphQL types you define will be object types. Object types - * have a name, but most importantly describe their fields. - * - * Example: - * - * ```ts - * const AddressType = new GraphQLObjectType({ - * name: 'Address', - * fields: { - * street: { type: GraphQLString }, - * number: { type: GraphQLInt }, - * formatted: { - * type: GraphQLString, - * resolve(obj) { - * return obj.number + ' ' + obj.street - * } - * } - * } - * }); - * ``` - * - * When two types need to refer to each other, or a type needs to refer to - * itself in a field, you can use a function expression (aka a closure or a - * thunk) to supply the fields lazily. - * - * Example: - * - * ```ts - * const PersonType = new GraphQLObjectType({ - * name: 'Person', - * fields: () => ({ - * name: { type: GraphQLString }, - * bestFriend: { type: PersonType }, - * }) - * }); - * ``` - */ -exports.GraphQLScalarType = GraphQLScalarType; -class GraphQLObjectType { - constructor(config) { - var _config$extensionASTN2; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.isTypeOf = config.isTypeOf; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN2 = config.extensionASTNodes) !== null && _config$extensionASTN2 !== void 0 ? _config$extensionASTN2 : []; - this._fields = () => defineFieldMap(config); - this._interfaces = () => defineInterfaces(config); - config.isTypeOf == null || typeof config.isTypeOf === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "isTypeOf" as a function, ` + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`); - } - get [Symbol.toStringTag]() { - return 'GraphQLObjectType'; - } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } - return this._fields; - } - getInterfaces() { - if (typeof this._interfaces === 'function') { - this._interfaces = this._interfaces(); - } - return this._interfaces; - } - toConfig() { - return { - name: this.name, - description: this.description, - interfaces: this.getInterfaces(), - fields: fieldsToFieldsConfig(this.getFields()), - isTypeOf: this.isTypeOf, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } -} -exports.GraphQLObjectType = GraphQLObjectType; -function defineInterfaces(config) { - var _config$interfaces; - const interfaces = resolveReadonlyArrayThunk((_config$interfaces = config.interfaces) !== null && _config$interfaces !== void 0 ? _config$interfaces : []); - Array.isArray(interfaces) || (0, _devAssert.devAssert)(false, `${config.name} interfaces must be an Array or a function which returns an Array.`); - return interfaces; -} -function defineFieldMap(config) { - const fieldMap = resolveObjMapThunk(config.fields); - isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); - return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { - var _fieldConfig$args; - isPlainObj(fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field config must be an object.`); - fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`); - const argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {}; - isPlainObj(argsConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} args must be an object with argument names as keys.`); - return { - name: (0, _assertName.assertName)(fieldName), - description: fieldConfig.description, - type: fieldConfig.type, - args: defineArguments(argsConfig), - resolve: fieldConfig.resolve, - subscribe: fieldConfig.subscribe, - deprecationReason: fieldConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), - astNode: fieldConfig.astNode - }; - }); -} -function defineArguments(config) { - return Object.entries(config).map(([argName, argConfig]) => ({ - name: (0, _assertName.assertName)(argName), - description: argConfig.description, - type: argConfig.type, - defaultValue: argConfig.defaultValue, - deprecationReason: argConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), - astNode: argConfig.astNode - })); -} -function isPlainObj(obj) { - return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); -} -function fieldsToFieldsConfig(fields) { - return (0, _mapValue.mapValue)(fields, field => ({ - description: field.description, - type: field.type, - args: argsToArgsConfig(field.args), - resolve: field.resolve, - subscribe: field.subscribe, - deprecationReason: field.deprecationReason, - extensions: field.extensions, - astNode: field.astNode - })); -} -/** - * @internal - */ - -function argsToArgsConfig(args) { - return (0, _keyValMap.keyValMap)(args, arg => arg.name, arg => ({ - description: arg.description, - type: arg.type, - defaultValue: arg.defaultValue, - deprecationReason: arg.deprecationReason, - extensions: arg.extensions, - astNode: arg.astNode - })); -} -function isRequiredArgument(arg) { - return isNonNullType(arg.type) && arg.defaultValue === undefined; -} - -/** - * Interface Type Definition - * - * When a field can return one of a heterogeneous set of types, a Interface type - * is used to describe what types are possible, what fields are in common across - * all types, as well as a function to determine which type is actually used - * when the field is resolved. - * - * Example: - * - * ```ts - * const EntityType = new GraphQLInterfaceType({ - * name: 'Entity', - * fields: { - * name: { type: GraphQLString } - * } - * }); - * ``` - */ -class GraphQLInterfaceType { - constructor(config) { - var _config$extensionASTN3; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.resolveType = config.resolveType; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN3 = config.extensionASTNodes) !== null && _config$extensionASTN3 !== void 0 ? _config$extensionASTN3 : []; - this._fields = defineFieldMap.bind(undefined, config); - this._interfaces = defineInterfaces.bind(undefined, config); - config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); - } - get [Symbol.toStringTag]() { - return 'GraphQLInterfaceType'; - } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } - return this._fields; - } - getInterfaces() { - if (typeof this._interfaces === 'function') { - this._interfaces = this._interfaces(); - } - return this._interfaces; - } - toConfig() { - return { - name: this.name, - description: this.description, - interfaces: this.getInterfaces(), - fields: fieldsToFieldsConfig(this.getFields()), - resolveType: this.resolveType, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } -} - -/** - * Union Type Definition - * - * When a field can return one of a heterogeneous set of types, a Union type - * is used to describe what types are possible as well as providing a function - * to determine which type is actually used when the field is resolved. - * - * Example: - * - * ```ts - * const PetType = new GraphQLUnionType({ - * name: 'Pet', - * types: [ DogType, CatType ], - * resolveType(value) { - * if (value instanceof Dog) { - * return DogType; - * } - * if (value instanceof Cat) { - * return CatType; - * } - * } - * }); - * ``` - */ -exports.GraphQLInterfaceType = GraphQLInterfaceType; -class GraphQLUnionType { - constructor(config) { - var _config$extensionASTN4; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.resolveType = config.resolveType; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN4 = config.extensionASTNodes) !== null && _config$extensionASTN4 !== void 0 ? _config$extensionASTN4 : []; - this._types = defineTypes.bind(undefined, config); - config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); - } - get [Symbol.toStringTag]() { - return 'GraphQLUnionType'; - } - getTypes() { - if (typeof this._types === 'function') { - this._types = this._types(); - } - return this._types; - } - toConfig() { - return { - name: this.name, - description: this.description, - types: this.getTypes(), - resolveType: this.resolveType, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } -} -exports.GraphQLUnionType = GraphQLUnionType; -function defineTypes(config) { - const types = resolveReadonlyArrayThunk(config.types); - Array.isArray(types) || (0, _devAssert.devAssert)(false, `Must provide Array of types or a function which returns such an array for Union ${config.name}.`); - return types; -} - -/** - * Enum Type Definition - * - * Some leaf values of requests and input values are Enums. GraphQL serializes - * Enum values as strings, however internally Enums can be represented by any - * kind of type, often integers. - * - * Example: - * - * ```ts - * const RGBType = new GraphQLEnumType({ - * name: 'RGB', - * values: { - * RED: { value: 0 }, - * GREEN: { value: 1 }, - * BLUE: { value: 2 } - * } - * }); - * ``` - * - * Note: If a value is not provided in a definition, the name of the enum value - * will be used as its internal value. - */ -class GraphQLEnumType { - /* */ - constructor(config) { - var _config$extensionASTN5; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN5 = config.extensionASTNodes) !== null && _config$extensionASTN5 !== void 0 ? _config$extensionASTN5 : []; - this._values = defineEnumValues(this.name, config.values); - this._valueLookup = new Map(this._values.map(enumValue => [enumValue.value, enumValue])); - this._nameLookup = (0, _keyMap.keyMap)(this._values, value => value.name); - } - get [Symbol.toStringTag]() { - return 'GraphQLEnumType'; - } - getValues() { - return this._values; - } - getValue(name) { - return this._nameLookup[name]; - } - serialize(outputValue) { - const enumValue = this._valueLookup.get(outputValue); - if (enumValue === undefined) { - throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); - } - return enumValue.name; - } - parseValue(inputValue) /* T */ - { - if (typeof inputValue !== 'string') { - const valueStr = (0, _inspect.inspect)(inputValue); - throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr)); - } - const enumValue = this.getValue(inputValue); - if (enumValue == null) { - throw new _GraphQLError.GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue)); - } - return enumValue.value; - } - parseLiteral(valueNode, _variables) /* T */ - { - // Note: variables will be resolved to a value before calling this function. - if (valueNode.kind !== _kinds.Kind.ENUM) { - const valueStr = (0, _printer.print)(valueNode); - throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr), { - nodes: valueNode - }); - } - const enumValue = this.getValue(valueNode.value); - if (enumValue == null) { - const valueStr = (0, _printer.print)(valueNode); - throw new _GraphQLError.GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr), { - nodes: valueNode - }); - } - return enumValue.value; - } - toConfig() { - const values = (0, _keyValMap.keyValMap)(this.getValues(), value => value.name, value => ({ - description: value.description, - value: value.value, - deprecationReason: value.deprecationReason, - extensions: value.extensions, - astNode: value.astNode - })); - return { - name: this.name, - description: this.description, - values, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } -} -exports.GraphQLEnumType = GraphQLEnumType; -function didYouMeanEnumValue(enumType, unknownValueStr) { - const allNames = enumType.getValues().map(value => value.name); - const suggestedValues = (0, _suggestionList.suggestionList)(unknownValueStr, allNames); - return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); -} -function defineEnumValues(typeName, valueMap) { - isPlainObj(valueMap) || (0, _devAssert.devAssert)(false, `${typeName} values must be an object with value names as keys.`); - return Object.entries(valueMap).map(([valueName, valueConfig]) => { - isPlainObj(valueConfig) || (0, _devAssert.devAssert)(false, `${typeName}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${(0, _inspect.inspect)(valueConfig)}.`); - return { - name: (0, _assertName.assertEnumValueName)(valueName), - description: valueConfig.description, - value: valueConfig.value !== undefined ? valueConfig.value : valueName, - deprecationReason: valueConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), - astNode: valueConfig.astNode - }; - }); -} - -/** - * Input Object Type Definition - * - * An input object defines a structured collection of fields which may be - * supplied to a field argument. - * - * Using `NonNull` will ensure that a value must be provided by the query - * - * Example: - * - * ```ts - * const GeoPoint = new GraphQLInputObjectType({ - * name: 'GeoPoint', - * fields: { - * lat: { type: new GraphQLNonNull(GraphQLFloat) }, - * lon: { type: new GraphQLNonNull(GraphQLFloat) }, - * alt: { type: GraphQLFloat, defaultValue: 0 }, - * } - * }); - * ``` - */ -class GraphQLInputObjectType { - constructor(config) { - var _config$extensionASTN6; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN6 = config.extensionASTNodes) !== null && _config$extensionASTN6 !== void 0 ? _config$extensionASTN6 : []; - this._fields = defineInputFieldMap.bind(undefined, config); - } - get [Symbol.toStringTag]() { - return 'GraphQLInputObjectType'; - } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } - return this._fields; - } - toConfig() { - const fields = (0, _mapValue.mapValue)(this.getFields(), field => ({ - description: field.description, - type: field.type, - defaultValue: field.defaultValue, - deprecationReason: field.deprecationReason, - extensions: field.extensions, - astNode: field.astNode - })); - return { - name: this.name, - description: this.description, - fields, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } -} -exports.GraphQLInputObjectType = GraphQLInputObjectType; -function defineInputFieldMap(config) { - const fieldMap = resolveObjMapThunk(config.fields); - isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); - return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { - !('resolve' in fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`); - return { - name: (0, _assertName.assertName)(fieldName), - description: fieldConfig.description, - type: fieldConfig.type, - defaultValue: fieldConfig.defaultValue, - deprecationReason: fieldConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), - astNode: fieldConfig.astNode - }; - }); -} -function isRequiredInputField(field) { - return isNonNullType(field.type) && field.defaultValue === undefined; -} + /***/ "../../../node_modules/graphql/type/scalars.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql/type/scalars.mjs ***! + \******************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.GraphQLString = + exports.GraphQLInt = + exports.GraphQLID = + exports.GraphQLFloat = + exports.GraphQLBoolean = + exports.GRAPHQL_MIN_INT = + exports.GRAPHQL_MAX_INT = + void 0; + exports.isSpecifiedScalarType = isSpecifiedScalarType; + exports.specifiedScalarTypes = void 0; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _printer = __webpack_require__( + /*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + * */ + + const GRAPHQL_MAX_INT = (exports.GRAPHQL_MAX_INT = 2147483647); + /** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + * */ + + const GRAPHQL_MIN_INT = (exports.GRAPHQL_MIN_INT = -2147483648); + const GraphQLInt = (exports.GraphQLInt = + new _definition.GraphQLScalarType({ + name: "Int", + description: + "The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.", + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === "boolean") { + return coercedValue ? 1 : 0; + } + let num = coercedValue; + if (typeof coercedValue === "string" && coercedValue !== "") { + num = Number(coercedValue); + } + if (typeof num !== "number" || !Number.isInteger(num)) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, + _inspect.inspect)(coercedValue)}` + ); + } + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + "Int cannot represent non 32-bit signed integer value: " + + (0, _inspect.inspect)(coercedValue) + ); + } + return num; + }, + parseValue(inputValue) { + if ( + typeof inputValue !== "number" || + !Number.isInteger(inputValue) + ) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, + _inspect.inspect)(inputValue)}` + ); + } + if ( + inputValue > GRAPHQL_MAX_INT || + inputValue < GRAPHQL_MIN_INT + ) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${inputValue}` + ); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, + _printer.print)(valueNode)}`, + { + nodes: valueNode, + } + ); + } + const num = parseInt(valueNode.value, 10); + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, + { + nodes: valueNode, + } + ); + } + return num; + }, + })); + const GraphQLFloat = (exports.GraphQLFloat = + new _definition.GraphQLScalarType({ + name: "Float", + description: + "The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).", + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === "boolean") { + return coercedValue ? 1 : 0; + } + let num = coercedValue; + if (typeof coercedValue === "string" && coercedValue !== "") { + num = Number(coercedValue); + } + if (typeof num !== "number" || !Number.isFinite(num)) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, + _inspect.inspect)(coercedValue)}` + ); + } + return num; + }, + parseValue(inputValue) { + if ( + typeof inputValue !== "number" || + !Number.isFinite(inputValue) + ) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, + _inspect.inspect)(inputValue)}` + ); + } + return inputValue; + }, + parseLiteral(valueNode) { + if ( + valueNode.kind !== _kinds.Kind.FLOAT && + valueNode.kind !== _kinds.Kind.INT + ) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, + _printer.print)(valueNode)}`, + valueNode + ); + } + return parseFloat(valueNode.value); + }, + })); + const GraphQLString = (exports.GraphQLString = + new _definition.GraphQLScalarType({ + name: "String", + description: + "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.", + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === "string") { + return coercedValue; + } + if (typeof coercedValue === "boolean") { + return coercedValue ? "true" : "false"; + } + if ( + typeof coercedValue === "number" && + Number.isFinite(coercedValue) + ) { + return coercedValue.toString(); + } + throw new _GraphQLError.GraphQLError( + `String cannot represent value: ${(0, _inspect.inspect)( + outputValue + )}` + ); + }, + parseValue(inputValue) { + if (typeof inputValue !== "string") { + throw new _GraphQLError.GraphQLError( + `String cannot represent a non string value: ${(0, + _inspect.inspect)(inputValue)}` + ); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING) { + throw new _GraphQLError.GraphQLError( + `String cannot represent a non string value: ${(0, + _printer.print)(valueNode)}`, + { + nodes: valueNode, + } + ); + } + return valueNode.value; + }, + })); + const GraphQLBoolean = (exports.GraphQLBoolean = + new _definition.GraphQLScalarType({ + name: "Boolean", + description: + "The `Boolean` scalar type represents `true` or `false`.", + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === "boolean") { + return coercedValue; + } + if (Number.isFinite(coercedValue)) { + return coercedValue !== 0; + } + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, + _inspect.inspect)(coercedValue)}` + ); + }, + parseValue(inputValue) { + if (typeof inputValue !== "boolean") { + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, + _inspect.inspect)(inputValue)}` + ); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.BOOLEAN) { + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, + _printer.print)(valueNode)}`, + { + nodes: valueNode, + } + ); + } + return valueNode.value; + }, + })); + const GraphQLID = (exports.GraphQLID = + new _definition.GraphQLScalarType({ + name: "ID", + description: + 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === "string") { + return coercedValue; + } + if (Number.isInteger(coercedValue)) { + return String(coercedValue); + } + throw new _GraphQLError.GraphQLError( + `ID cannot represent value: ${(0, _inspect.inspect)( + outputValue + )}` + ); + }, + parseValue(inputValue) { + if (typeof inputValue === "string") { + return inputValue; + } + if ( + typeof inputValue === "number" && + Number.isInteger(inputValue) + ) { + return inputValue.toString(); + } + throw new _GraphQLError.GraphQLError( + `ID cannot represent value: ${(0, _inspect.inspect)( + inputValue + )}` + ); + }, + parseLiteral(valueNode) { + if ( + valueNode.kind !== _kinds.Kind.STRING && + valueNode.kind !== _kinds.Kind.INT + ) { + throw new _GraphQLError.GraphQLError( + "ID cannot represent a non-string and non-integer value: " + + (0, _printer.print)(valueNode), + { + nodes: valueNode, + } + ); + } + return valueNode.value; + }, + })); + const specifiedScalarTypes = (exports.specifiedScalarTypes = + Object.freeze([ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, + ])); + function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(({ name }) => type.name === name); + } // Support serializing objects with custom valueOf() or toJSON() functions - + // a common way to represent a complex value which can be represented as + // a string (ex: MongoDB id objects). + + function serializeObject(outputValue) { + if ((0, _isObjectLike.isObjectLike)(outputValue)) { + if (typeof outputValue.valueOf === "function") { + const valueOfResult = outputValue.valueOf(); + if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { + return valueOfResult; + } + } + if (typeof outputValue.toJSON === "function") { + return outputValue.toJSON(); + } + } + return outputValue; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/type/directives.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/type/directives.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GraphQLSpecifiedByDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = void 0; -exports.assertDirective = assertDirective; -exports.isDirective = isDirective; -exports.isSpecifiedDirective = isSpecifiedDirective; -exports.specifiedDirectives = void 0; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); -var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); -var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); -var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -/** - * Test if the given value is a GraphQL directive. - */ - -function isDirective(directive) { - return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); -} -function assertDirective(directive) { - if (!isDirective(directive)) { - throw new Error(`Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`); - } - return directive; -} -/** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ - -/** - * Directives are used by the GraphQL runtime as a way of modifying execution - * behavior. Type system creators will usually not create these directly. - */ -class GraphQLDirective { - constructor(config) { - var _config$isRepeatable, _config$args; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.locations = config.locations; - this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - Array.isArray(config.locations) || (0, _devAssert.devAssert)(false, `@${config.name} locations must be an Array.`); - const args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {}; - (0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args) || (0, _devAssert.devAssert)(false, `@${config.name} args must be an object with argument names as keys.`); - this.args = (0, _definition.defineArguments)(args); - } - get [Symbol.toStringTag]() { - return 'GraphQLDirective'; - } - toConfig() { - return { - name: this.name, - description: this.description, - locations: this.locations, - args: (0, _definition.argsToArgsConfig)(this.args), - isRepeatable: this.isRepeatable, - extensions: this.extensions, - astNode: this.astNode - }; - } - toString() { - return '@' + this.name; - } - toJSON() { - return this.toString(); - } -} - -/** - * Used to conditionally include fields or fragments. - */ -exports.GraphQLDirective = GraphQLDirective; -const GraphQLIncludeDirective = exports.GraphQLIncludeDirective = new GraphQLDirective({ - name: 'include', - description: 'Directs the executor to include this field or fragment only when the `if` argument is true.', - locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], - args: { - if: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - description: 'Included when true.' - } - } -}); -/** - * Used to conditionally skip (exclude) fields or fragments. - */ - -const GraphQLSkipDirective = exports.GraphQLSkipDirective = new GraphQLDirective({ - name: 'skip', - description: 'Directs the executor to skip this field or fragment when the `if` argument is true.', - locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], - args: { - if: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - description: 'Skipped when true.' - } - } -}); -/** - * Constant string used for default reason for a deprecation. - */ - -const DEFAULT_DEPRECATION_REASON = exports.DEFAULT_DEPRECATION_REASON = 'No longer supported'; -/** - * Used to declare element of a GraphQL schema as deprecated. - */ - -const GraphQLDeprecatedDirective = exports.GraphQLDeprecatedDirective = new GraphQLDirective({ - name: 'deprecated', - description: 'Marks an element of a GraphQL schema as no longer supported.', - locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], - args: { - reason: { - type: _scalars.GraphQLString, - description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', - defaultValue: DEFAULT_DEPRECATION_REASON - } - } -}); -/** - * Used to provide a URL for specifying the behavior of custom scalar definitions. - */ - -const GraphQLSpecifiedByDirective = exports.GraphQLSpecifiedByDirective = new GraphQLDirective({ - name: 'specifiedBy', - description: 'Exposes a URL that specifies the behavior of this scalar.', - locations: [_directiveLocation.DirectiveLocation.SCALAR], - args: { - url: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - description: 'The URL that specifies the behavior of this scalar.' - } - } -}); -/** - * The full list of specified directives. - */ - -const specifiedDirectives = exports.specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]); -function isSpecifiedDirective(directive) { - return specifiedDirectives.some(({ - name - }) => name === directive.name); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/type/index.mjs": -/*!****************************************************!*\ - !*** ../../../node_modules/graphql/type/index.mjs ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "../../../node_modules/graphql/type/schema.mjs": + /*!*****************************************************!*\ + !*** ../../../node_modules/graphql/type/schema.mjs ***! + \*****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.GraphQLSchema = void 0; + exports.assertSchema = assertSchema; + exports.isSchema = isSchema; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _instanceOf = __webpack_require__( + /*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _toObjMap = __webpack_require__( + /*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs" + ); + var _ast = __webpack_require__( + /*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _definition = __webpack_require__( + /*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _introspection = __webpack_require__( + /*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + /** + * Test if the given value is a GraphQL schema. + */ + function isSchema(schema) { + return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); + } + function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + schema + )} to be a GraphQL schema.` + ); + } + return schema; + } + /** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + /** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * ``` + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * ``` + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * ``` + */ + class GraphQLSchema { + // Used as a cache for validateSchema(). + constructor(config) { + var _config$extensionASTN, _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = + config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + (0, _isObjectLike.isObjectLike)(config) || + (0, _devAssert.devAssert)( + false, + "Must provide configuration object." + ); + !config.types || + Array.isArray(config.types) || + (0, _devAssert.devAssert)( + false, + `"types" must be Array if provided but got: ${(0, + _inspect.inspect)(config.types)}.` + ); + !config.directives || + Array.isArray(config.directives) || + (0, _devAssert.devAssert)( + false, + '"directives" must be Array if provided but got: ' + + `${(0, _inspect.inspect)(config.directives)}.` + ); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = + (_config$directives = config.directives) !== null && + _config$directives !== void 0 + ? _config$directives + : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + const allReferencedTypes = new Set(config.types); + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + if (this._subscriptionType != null) { + collectReferencedTypes( + this._subscriptionType, + allReferencedTypes + ); + } + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if ((0, _directives.isDirective)(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ - enumerable: true, - get: function () { - return _directives.DEFAULT_DEPRECATION_REASON; - } -})); -Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ - enumerable: true, - get: function () { - return _scalars.GRAPHQL_MAX_INT; - } -})); -Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ - enumerable: true, - get: function () { - return _scalars.GRAPHQL_MIN_INT; - } -})); -Object.defineProperty(exports, "GraphQLBoolean", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLBoolean; - } -})); -Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLDeprecatedDirective; - } -})); -Object.defineProperty(exports, "GraphQLDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLDirective; - } -})); -Object.defineProperty(exports, "GraphQLEnumType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLEnumType; - } -})); -Object.defineProperty(exports, "GraphQLFloat", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLFloat; - } -})); -Object.defineProperty(exports, "GraphQLID", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLID; - } -})); -Object.defineProperty(exports, "GraphQLIncludeDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLIncludeDirective; - } -})); -Object.defineProperty(exports, "GraphQLInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLInputObjectType; - } -})); -Object.defineProperty(exports, "GraphQLInt", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLInt; - } -})); -Object.defineProperty(exports, "GraphQLInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLInterfaceType; - } -})); -Object.defineProperty(exports, "GraphQLList", ({ - enumerable: true, - get: function () { - return _definition.GraphQLList; - } -})); -Object.defineProperty(exports, "GraphQLNonNull", ({ - enumerable: true, - get: function () { - return _definition.GraphQLNonNull; - } -})); -Object.defineProperty(exports, "GraphQLObjectType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLObjectType; - } -})); -Object.defineProperty(exports, "GraphQLScalarType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLScalarType; - } -})); -Object.defineProperty(exports, "GraphQLSchema", ({ - enumerable: true, - get: function () { - return _schema.GraphQLSchema; - } -})); -Object.defineProperty(exports, "GraphQLSkipDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLSkipDirective; - } -})); -Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLSpecifiedByDirective; - } -})); -Object.defineProperty(exports, "GraphQLString", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLString; - } -})); -Object.defineProperty(exports, "GraphQLUnionType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLUnionType; - } -})); -Object.defineProperty(exports, "SchemaMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.SchemaMetaFieldDef; - } -})); -Object.defineProperty(exports, "TypeKind", ({ - enumerable: true, - get: function () { - return _introspection.TypeKind; - } -})); -Object.defineProperty(exports, "TypeMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.TypeMetaFieldDef; - } -})); -Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.TypeNameMetaFieldDef; - } -})); -Object.defineProperty(exports, "__Directive", ({ - enumerable: true, - get: function () { - return _introspection.__Directive; - } -})); -Object.defineProperty(exports, "__DirectiveLocation", ({ - enumerable: true, - get: function () { - return _introspection.__DirectiveLocation; - } -})); -Object.defineProperty(exports, "__EnumValue", ({ - enumerable: true, - get: function () { - return _introspection.__EnumValue; - } -})); -Object.defineProperty(exports, "__Field", ({ - enumerable: true, - get: function () { - return _introspection.__Field; - } -})); -Object.defineProperty(exports, "__InputValue", ({ - enumerable: true, - get: function () { - return _introspection.__InputValue; - } -})); -Object.defineProperty(exports, "__Schema", ({ - enumerable: true, - get: function () { - return _introspection.__Schema; - } -})); -Object.defineProperty(exports, "__Type", ({ - enumerable: true, - get: function () { - return _introspection.__Type; - } -})); -Object.defineProperty(exports, "__TypeKind", ({ - enumerable: true, - get: function () { - return _introspection.__TypeKind; - } -})); -Object.defineProperty(exports, "assertAbstractType", ({ - enumerable: true, - get: function () { - return _definition.assertAbstractType; - } -})); -Object.defineProperty(exports, "assertCompositeType", ({ - enumerable: true, - get: function () { - return _definition.assertCompositeType; - } -})); -Object.defineProperty(exports, "assertDirective", ({ - enumerable: true, - get: function () { - return _directives.assertDirective; - } -})); -Object.defineProperty(exports, "assertEnumType", ({ - enumerable: true, - get: function () { - return _definition.assertEnumType; - } -})); -Object.defineProperty(exports, "assertEnumValueName", ({ - enumerable: true, - get: function () { - return _assertName.assertEnumValueName; - } -})); -Object.defineProperty(exports, "assertInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.assertInputObjectType; - } -})); -Object.defineProperty(exports, "assertInputType", ({ - enumerable: true, - get: function () { - return _definition.assertInputType; - } -})); -Object.defineProperty(exports, "assertInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.assertInterfaceType; - } -})); -Object.defineProperty(exports, "assertLeafType", ({ - enumerable: true, - get: function () { - return _definition.assertLeafType; - } -})); -Object.defineProperty(exports, "assertListType", ({ - enumerable: true, - get: function () { - return _definition.assertListType; - } -})); -Object.defineProperty(exports, "assertName", ({ - enumerable: true, - get: function () { - return _assertName.assertName; - } -})); -Object.defineProperty(exports, "assertNamedType", ({ - enumerable: true, - get: function () { - return _definition.assertNamedType; - } -})); -Object.defineProperty(exports, "assertNonNullType", ({ - enumerable: true, - get: function () { - return _definition.assertNonNullType; - } -})); -Object.defineProperty(exports, "assertNullableType", ({ - enumerable: true, - get: function () { - return _definition.assertNullableType; - } -})); -Object.defineProperty(exports, "assertObjectType", ({ - enumerable: true, - get: function () { - return _definition.assertObjectType; - } -})); -Object.defineProperty(exports, "assertOutputType", ({ - enumerable: true, - get: function () { - return _definition.assertOutputType; - } -})); -Object.defineProperty(exports, "assertScalarType", ({ - enumerable: true, - get: function () { - return _definition.assertScalarType; - } -})); -Object.defineProperty(exports, "assertSchema", ({ - enumerable: true, - get: function () { - return _schema.assertSchema; - } -})); -Object.defineProperty(exports, "assertType", ({ - enumerable: true, - get: function () { - return _definition.assertType; - } -})); -Object.defineProperty(exports, "assertUnionType", ({ - enumerable: true, - get: function () { - return _definition.assertUnionType; - } -})); -Object.defineProperty(exports, "assertValidSchema", ({ - enumerable: true, - get: function () { - return _validate.assertValidSchema; - } -})); -Object.defineProperty(exports, "assertWrappingType", ({ - enumerable: true, - get: function () { - return _definition.assertWrappingType; - } -})); -Object.defineProperty(exports, "getNamedType", ({ - enumerable: true, - get: function () { - return _definition.getNamedType; - } -})); -Object.defineProperty(exports, "getNullableType", ({ - enumerable: true, - get: function () { - return _definition.getNullableType; - } -})); -Object.defineProperty(exports, "introspectionTypes", ({ - enumerable: true, - get: function () { - return _introspection.introspectionTypes; - } -})); -Object.defineProperty(exports, "isAbstractType", ({ - enumerable: true, - get: function () { - return _definition.isAbstractType; - } -})); -Object.defineProperty(exports, "isCompositeType", ({ - enumerable: true, - get: function () { - return _definition.isCompositeType; - } -})); -Object.defineProperty(exports, "isDirective", ({ - enumerable: true, - get: function () { - return _directives.isDirective; - } -})); -Object.defineProperty(exports, "isEnumType", ({ - enumerable: true, - get: function () { - return _definition.isEnumType; - } -})); -Object.defineProperty(exports, "isInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.isInputObjectType; - } -})); -Object.defineProperty(exports, "isInputType", ({ - enumerable: true, - get: function () { - return _definition.isInputType; - } -})); -Object.defineProperty(exports, "isInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.isInterfaceType; - } -})); -Object.defineProperty(exports, "isIntrospectionType", ({ - enumerable: true, - get: function () { - return _introspection.isIntrospectionType; - } -})); -Object.defineProperty(exports, "isLeafType", ({ - enumerable: true, - get: function () { - return _definition.isLeafType; - } -})); -Object.defineProperty(exports, "isListType", ({ - enumerable: true, - get: function () { - return _definition.isListType; - } -})); -Object.defineProperty(exports, "isNamedType", ({ - enumerable: true, - get: function () { - return _definition.isNamedType; - } -})); -Object.defineProperty(exports, "isNonNullType", ({ - enumerable: true, - get: function () { - return _definition.isNonNullType; - } -})); -Object.defineProperty(exports, "isNullableType", ({ - enumerable: true, - get: function () { - return _definition.isNullableType; - } -})); -Object.defineProperty(exports, "isObjectType", ({ - enumerable: true, - get: function () { - return _definition.isObjectType; - } -})); -Object.defineProperty(exports, "isOutputType", ({ - enumerable: true, - get: function () { - return _definition.isOutputType; - } -})); -Object.defineProperty(exports, "isRequiredArgument", ({ - enumerable: true, - get: function () { - return _definition.isRequiredArgument; - } -})); -Object.defineProperty(exports, "isRequiredInputField", ({ - enumerable: true, - get: function () { - return _definition.isRequiredInputField; - } -})); -Object.defineProperty(exports, "isScalarType", ({ - enumerable: true, - get: function () { - return _definition.isScalarType; - } -})); -Object.defineProperty(exports, "isSchema", ({ - enumerable: true, - get: function () { - return _schema.isSchema; - } -})); -Object.defineProperty(exports, "isSpecifiedDirective", ({ - enumerable: true, - get: function () { - return _directives.isSpecifiedDirective; - } -})); -Object.defineProperty(exports, "isSpecifiedScalarType", ({ - enumerable: true, - get: function () { - return _scalars.isSpecifiedScalarType; - } -})); -Object.defineProperty(exports, "isType", ({ - enumerable: true, - get: function () { - return _definition.isType; - } -})); -Object.defineProperty(exports, "isUnionType", ({ - enumerable: true, - get: function () { - return _definition.isUnionType; - } -})); -Object.defineProperty(exports, "isWrappingType", ({ - enumerable: true, - get: function () { - return _definition.isWrappingType; - } -})); -Object.defineProperty(exports, "resolveObjMapThunk", ({ - enumerable: true, - get: function () { - return _definition.resolveObjMapThunk; - } -})); -Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ - enumerable: true, - get: function () { - return _definition.resolveReadonlyArrayThunk; - } -})); -Object.defineProperty(exports, "specifiedDirectives", ({ - enumerable: true, - get: function () { - return _directives.specifiedDirectives; - } -})); -Object.defineProperty(exports, "specifiedScalarTypes", ({ - enumerable: true, - get: function () { - return _scalars.specifiedScalarTypes; - } -})); -Object.defineProperty(exports, "validateSchema", ({ - enumerable: true, - get: function () { - return _validate.validateSchema; - } -})); -var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); -var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); -var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); - -/***/ }), - -/***/ "../../../node_modules/graphql/type/introspection.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/type/introspection.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.introspectionTypes = exports.__TypeKind = exports.__Type = exports.__Schema = exports.__InputValue = exports.__Field = exports.__EnumValue = exports.__DirectiveLocation = exports.__Directive = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.TypeKind = exports.SchemaMetaFieldDef = void 0; -exports.isIntrospectionType = isIntrospectionType; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); -var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _astFromValue = __webpack_require__(/*! ../utilities/astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); -var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -const __Schema = exports.__Schema = new _definition.GraphQLObjectType({ - name: '__Schema', - description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', - fields: () => ({ - description: { - type: _scalars.GraphQLString, - resolve: schema => schema.description - }, - types: { - description: 'A list of all types supported by this server.', - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))), - resolve(schema) { - return Object.values(schema.getTypeMap()); - } - }, - queryType: { - description: 'The type that query operations will be rooted at.', - type: new _definition.GraphQLNonNull(__Type), - resolve: schema => schema.getQueryType() - }, - mutationType: { - description: 'If this server supports mutation, the type that mutation operations will be rooted at.', - type: __Type, - resolve: schema => schema.getMutationType() - }, - subscriptionType: { - description: 'If this server support subscription, the type that subscription operations will be rooted at.', - type: __Type, - resolve: schema => schema.getSubscriptionType() - }, - directives: { - description: 'A list of all directives supported by this server.', - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))), - resolve: schema => schema.getDirectives() - } - }) -}); -const __Directive = exports.__Directive = new _definition.GraphQLObjectType({ - name: '__Directive', - description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: directive => directive.name - }, - description: { - type: _scalars.GraphQLString, - resolve: directive => directive.description - }, - isRepeatable: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: directive => directive.isRepeatable - }, - locations: { - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation))), - resolve: directive => directive.locations - }, - args: { - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + const typeName = namedType.name; + typeName || + (0, _devAssert.devAssert)( + false, + "One of the provided types for building the Schema is missing a name." + ); + if (this._typeMap[typeName] !== undefined) { + throw new Error( + `Schema must contain uniquely named types but contains multiple types named "${typeName}".` + ); + } + this._typeMap[typeName] = namedType; + if ((0, _definition.isInterfaceType)(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + implementations.interfaces.push(namedType); + } + } + } else if ((0, _definition.isObjectType)(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + implementations.objects.push(namedType); + } + } + } + } + } + get [Symbol.toStringTag]() { + return "GraphQLSchema"; + } + getQueryType() { + return this._queryType; + } + getMutationType() { + return this._mutationType; + } + getSubscriptionType() { + return this._subscriptionType; + } + getRootType(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return this.getQueryType(); + case _ast.OperationTypeNode.MUTATION: + return this.getMutationType(); + case _ast.OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); + } + } + getTypeMap() { + return this._typeMap; + } + getType(name) { + return this.getTypeMap()[name]; + } + getPossibleTypes(abstractType) { + return (0, _definition.isUnionType)(abstractType) + ? abstractType.getTypes() + : this.getImplementations(abstractType).objects; + } + getImplementations(interfaceType) { + const implementations = + this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 + ? implementations + : { + objects: [], + interfaces: [], + }; + } + isSubType(abstractType, maybeSubType) { + let map = this._subTypeMap[abstractType.name]; + if (map === undefined) { + map = Object.create(null); + if ((0, _definition.isUnionType)(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + for (const type of implementations.objects) { + map[type.name] = true; + } + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + this._subTypeMap[abstractType.name] = map; + } + return map[maybeSubType.name] !== undefined; + } + getDirectives() { + return this._directives; + } + getDirective(name) { + return this.getDirectives().find( + (directive) => directive.name === name + ); + } + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.__validationErrors !== undefined, + }; + } } + exports.GraphQLSchema = GraphQLSchema; + function collectReferencedTypes(type, typeSet) { + const namedType = (0, _definition.getNamedType)(type); + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + if ((0, _definition.isUnionType)(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if ( + (0, _definition.isObjectType)(namedType) || + (0, _definition.isInterfaceType)(namedType) + ) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, _definition.isInputObjectType)(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + return typeSet; + } + + /***/ }, - resolve(field, { - includeDeprecated - }) { - return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); - } - } - }) -}); -const __DirectiveLocation = exports.__DirectiveLocation = new _definition.GraphQLEnumType({ - name: '__DirectiveLocation', - description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', - values: { - QUERY: { - value: _directiveLocation.DirectiveLocation.QUERY, - description: 'Location adjacent to a query operation.' - }, - MUTATION: { - value: _directiveLocation.DirectiveLocation.MUTATION, - description: 'Location adjacent to a mutation operation.' - }, - SUBSCRIPTION: { - value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, - description: 'Location adjacent to a subscription operation.' - }, - FIELD: { - value: _directiveLocation.DirectiveLocation.FIELD, - description: 'Location adjacent to a field.' - }, - FRAGMENT_DEFINITION: { - value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, - description: 'Location adjacent to a fragment definition.' - }, - FRAGMENT_SPREAD: { - value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, - description: 'Location adjacent to a fragment spread.' - }, - INLINE_FRAGMENT: { - value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, - description: 'Location adjacent to an inline fragment.' - }, - VARIABLE_DEFINITION: { - value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, - description: 'Location adjacent to a variable definition.' - }, - SCHEMA: { - value: _directiveLocation.DirectiveLocation.SCHEMA, - description: 'Location adjacent to a schema definition.' - }, - SCALAR: { - value: _directiveLocation.DirectiveLocation.SCALAR, - description: 'Location adjacent to a scalar definition.' - }, - OBJECT: { - value: _directiveLocation.DirectiveLocation.OBJECT, - description: 'Location adjacent to an object type definition.' - }, - FIELD_DEFINITION: { - value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, - description: 'Location adjacent to a field definition.' - }, - ARGUMENT_DEFINITION: { - value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, - description: 'Location adjacent to an argument definition.' - }, - INTERFACE: { - value: _directiveLocation.DirectiveLocation.INTERFACE, - description: 'Location adjacent to an interface definition.' - }, - UNION: { - value: _directiveLocation.DirectiveLocation.UNION, - description: 'Location adjacent to a union definition.' - }, - ENUM: { - value: _directiveLocation.DirectiveLocation.ENUM, - description: 'Location adjacent to an enum definition.' - }, - ENUM_VALUE: { - value: _directiveLocation.DirectiveLocation.ENUM_VALUE, - description: 'Location adjacent to an enum value definition.' - }, - INPUT_OBJECT: { - value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, - description: 'Location adjacent to an input object type definition.' - }, - INPUT_FIELD_DEFINITION: { - value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, - description: 'Location adjacent to an input object field definition.' - } - } -}); -const __Type = exports.__Type = new _definition.GraphQLObjectType({ - name: '__Type', - description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', - fields: () => ({ - kind: { - type: new _definition.GraphQLNonNull(__TypeKind), - resolve(type) { - if ((0, _definition.isScalarType)(type)) { - return TypeKind.SCALAR; + + /***/ "../../../node_modules/graphql/type/validate.mjs": + /*!*******************************************************!*\ + !*** ../../../node_modules/graphql/type/validate.mjs ***! + \*******************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.assertValidSchema = assertValidSchema; + exports.validateSchema = validateSchema; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _ast = __webpack_require__( + /*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _typeComparators = __webpack_require__( + /*! ../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs" + ); + var _definition = __webpack_require__( + /*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _introspection = __webpack_require__( + /*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _schema = __webpack_require__( + /*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs" + ); + /** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ + + function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; } - if ((0, _definition.isObjectType)(type)) { - return TypeKind.OBJECT; + /** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + + function assertValidSchema(schema) { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join("\n\n")); + } + } + class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + this._errors.push( + new _GraphQLError.GraphQLError(message, { + nodes: _nodes, + }) + ); + } + getErrors() { + return this._errors; + } } - if ((0, _definition.isInterfaceType)(type)) { - return TypeKind.INTERFACE; + function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + if (!queryType) { + context.reportError( + "Query root type must be provided.", + schema.astNode + ); + } else if (!(0, _definition.isObjectType)(queryType)) { + var _getOperationTypeNode; + context.reportError( + `Query root type must be Object type, it cannot be ${(0, + _inspect.inspect)(queryType)}.`, + (_getOperationTypeNode = getOperationTypeNode( + schema, + _ast.OperationTypeNode.QUERY + )) !== null && _getOperationTypeNode !== void 0 + ? _getOperationTypeNode + : queryType.astNode + ); + } + const mutationType = schema.getMutationType(); + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + var _getOperationTypeNode2; + context.reportError( + "Mutation root type must be Object type if provided, it cannot be " + + `${(0, _inspect.inspect)(mutationType)}.`, + (_getOperationTypeNode2 = getOperationTypeNode( + schema, + _ast.OperationTypeNode.MUTATION + )) !== null && _getOperationTypeNode2 !== void 0 + ? _getOperationTypeNode2 + : mutationType.astNode + ); + } + const subscriptionType = schema.getSubscriptionType(); + if ( + subscriptionType && + !(0, _definition.isObjectType)(subscriptionType) + ) { + var _getOperationTypeNode3; + context.reportError( + "Subscription root type must be Object type if provided, it cannot be " + + `${(0, _inspect.inspect)(subscriptionType)}.`, + (_getOperationTypeNode3 = getOperationTypeNode( + schema, + _ast.OperationTypeNode.SUBSCRIPTION + )) !== null && _getOperationTypeNode3 !== void 0 + ? _getOperationTypeNode3 + : subscriptionType.astNode + ); + } } - if ((0, _definition.isUnionType)(type)) { - return TypeKind.UNION; + function getOperationTypeNode(schema, operation) { + var _flatMap$find; + return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes] + .flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (schemaNode) => { + var _schemaNode$operation; + return /* c8 ignore next */ (_schemaNode$operation = + schemaNode === null || schemaNode === void 0 + ? void 0 + : schemaNode.operationTypes) !== null && + _schemaNode$operation !== void 0 + ? _schemaNode$operation + : []; + } + ) + .find((operationNode) => operationNode.operation === operation)) === + null || _flatMap$find === void 0 + ? void 0 + : _flatMap$find.type; + } + function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError( + `Expected directive but got: ${(0, _inspect.inspect)( + directive + )}.`, + directive === null || directive === void 0 + ? void 0 + : directive.astNode + ); + continue; + } // Ensure they are named correctly. + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError( + `The type of @${directive.name}(${arg.name}:) must be Input Type ` + + `but got: ${(0, _inspect.inspect)(arg.type)}.`, + arg.astNode + ); + } + if ( + (0, _definition.isRequiredArgument)(arg) && + arg.deprecationReason != null + ) { + var _arg$astNode; + context.reportError( + `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode = arg.astNode) === null || + _arg$astNode === void 0 + ? void 0 + : _arg$astNode.type, + ] + ); + } + } + } } - if ((0, _definition.isEnumType)(type)) { - return TypeKind.ENUM; + function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + if (node.name.startsWith("__")) { + context.reportError( + `Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, + node.astNode + ); + } } - if ((0, _definition.isInputObjectType)(type)) { - return TypeKind.INPUT_OBJECT; + function validateTypes(context) { + const validateInputObjectCircularRefs = + createInputObjectCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + for (const type of Object.values(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError( + `Expected GraphQL named type but got: ${(0, _inspect.inspect)( + type + )}.`, + type.astNode + ); + continue; + } // Ensure it is named correctly (excluding introspection types). + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } } - if ((0, _definition.isListType)(type)) { - return TypeKind.LIST; + function validateFields(context, type) { + const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError( + `Type ${type.name} must define one or more fields.`, + [type.astNode, ...type.extensionASTNodes] + ); + } + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!(0, _definition.isOutputType)(field.type)) { + var _field$astNode; + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${(0, _inspect.inspect)(field.type)}.`, + (_field$astNode = field.astNode) === null || + _field$astNode === void 0 + ? void 0 + : _field$astNode.type + ); + } // Ensure the arguments are valid + + for (const arg of field.args) { + const argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + var _arg$astNode2; + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, + (_arg$astNode2 = arg.astNode) === null || + _arg$astNode2 === void 0 + ? void 0 + : _arg$astNode2.type + ); + } + if ( + (0, _definition.isRequiredArgument)(arg) && + arg.deprecationReason != null + ) { + var _arg$astNode3; + context.reportError( + `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode3 = arg.astNode) === null || + _arg$astNode3 === void 0 + ? void 0 + : _arg$astNode3.type, + ] + ); + } + } + } } - if ((0, _definition.isNonNullType)(type)) { - return TypeKind.NON_NULL; + function validateInterfaces(context, type) { + const ifaceTypeNames = Object.create(null); + for (const iface of type.getInterfaces()) { + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError( + `Type ${(0, _inspect.inspect)( + type + )} must only implement Interface types, ` + + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, + getAllImplementsInterfaceNodes(type, iface) + ); + continue; + } + if (type === iface) { + context.reportError( + `Type ${type.name} cannot implement itself because it would create a circular reference.`, + getAllImplementsInterfaceNodes(type, iface) + ); + continue; + } + if (ifaceTypeNames[iface.name]) { + context.reportError( + `Type ${type.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(type, iface) + ); + continue; + } + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered) + function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); // Assert each interface field is implemented. - false || (0, _invariant.invariant)(false, `Unexpected type: "${(0, _inspect.inspect)(type)}".`); - } - }, - name: { - type: _scalars.GraphQLString, - resolve: type => 'name' in type ? type.name : undefined - }, - description: { - type: _scalars.GraphQLString, - resolve: (type // FIXME: add test case - ) => /* c8 ignore next */ - 'description' in type ? type.description : undefined - }, - specifiedByURL: { - type: _scalars.GraphQLString, - resolve: obj => 'specifiedByURL' in obj ? obj.specifiedByURL : undefined - }, - fields: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false + for (const ifaceField of Object.values(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, + [ifaceField.astNode, type.astNode, ...type.extensionASTNodes] + ); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + if ( + !(0, _typeComparators.isTypeSubTypeOf)( + context.schema, + typeField.type, + ifaceField.type + ) + ) { + var _ifaceField$astNode, _typeField$astNode; + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${(0, _inspect.inspect)(ifaceField.type)} but ${ + type.name + }.${fieldName} ` + + `is type ${(0, _inspect.inspect)(typeField.type)}.`, + [ + (_ifaceField$astNode = ifaceField.astNode) === null || + _ifaceField$astNode === void 0 + ? void 0 + : _ifaceField$astNode.type, + (_typeField$astNode = typeField.astNode) === null || + _typeField$astNode === void 0 + ? void 0 + : _typeField$astNode.type, + ] + ); + } // Assert each interface field arg is implemented. + + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = typeField.args.find( + (arg) => arg.name === argName + ); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, + [ifaceArg.astNode, typeField.astNode] + ); + continue; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + if ( + !(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type) + ) { + var _ifaceArg$astNode, _typeArg$astNode; + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${(0, _inspect.inspect)( + ifaceArg.type + )} but ` + + `${type.name}.${fieldName}(${argName}:) is type ` + + `${(0, _inspect.inspect)(typeArg.type)}.`, + [ + (_ifaceArg$astNode = ifaceArg.astNode) === null || + _ifaceArg$astNode === void 0 + ? void 0 + : _ifaceArg$astNode.type, + (_typeArg$astNode = typeArg.astNode) === null || + _typeArg$astNode === void 0 + ? void 0 + : _typeArg$astNode.type, + ] + ); + } // TODO: validate default values? + } // Assert additional arguments must not be required. + + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = ifaceField.args.find( + (arg) => arg.name === argName + ); + if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { + context.reportError( + `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, + [typeArg.astNode, ifaceField.astNode] + ); + } + } + } } - }, - resolve(type, { - includeDeprecated - }) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { - const fields = Object.values(type.getFields()); - return includeDeprecated ? fields : fields.filter(field => field.deprecationReason == null); + function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError( + transitive === type + ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` + : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, + [ + ...getAllImplementsInterfaceNodes(iface, transitive), + ...getAllImplementsInterfaceNodes(type, iface), + ] + ); + } + } } - } - }, - interfaces: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), - resolve(type) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { - return type.getInterfaces(); + function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + [union.astNode, ...union.extensionASTNodes] + ); + } + const includedTypeNames = Object.create(null); + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name) + ); + continue; + } + includedTypeNames[memberType.name] = true; + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)) + ); + } + } } - } - }, - possibleTypes: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), - resolve(type, _args, _context, { - schema - }) { - if ((0, _definition.isAbstractType)(type)) { - return schema.getPossibleTypes(type); + function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + [enumType.astNode, ...enumType.extensionASTNodes] + ); + } + for (const enumValue of enumValues) { + // Ensure valid name. + validateName(context, enumValue); + } } - } - }, - enumValues: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false + function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + [inputObj.astNode, ...inputObj.extensionASTNodes] + ); + } // Ensure the arguments are valid + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + var _field$astNode2; + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${(0, _inspect.inspect)(field.type)}.`, + (_field$astNode2 = field.astNode) === null || + _field$astNode2 === void 0 + ? void 0 + : _field$astNode2.type + ); + } + if ( + (0, _definition.isRequiredInputField)(field) && + field.deprecationReason != null + ) { + var _field$astNode3; + context.reportError( + `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(field.astNode), + (_field$astNode3 = field.astNode) === null || + _field$astNode3 === void 0 + ? void 0 + : _field$astNode3.type, + ] + ); + } + } } + function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + const fieldPath = []; // Position in the type path + + const fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + const fields = Object.values(inputObj.getFields()); + for (const field of fields) { + if ( + (0, _definition.isNonNullType)(field.type) && + (0, _definition.isInputObjectType)(field.type.ofType) + ) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath + .map((fieldObj) => fieldObj.name) + .join("."); + context.reportError( + `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, + cyclePath.map((fieldObj) => fieldObj.astNode) + ); + } + fieldPath.pop(); + } + } + fieldPathIndexByTypeName[inputObj.name] = undefined; + } + } + function getAllImplementsInterfaceNodes(type, iface) { + const { astNode, extensionASTNodes } = type; + const nodes = + astNode != null + ? [astNode, ...extensionASTNodes] + : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((typeNode) => { + var _typeNode$interfaces; + return /* c8 ignore next */ (_typeNode$interfaces = + typeNode.interfaces) !== null && _typeNode$interfaces !== void 0 + ? _typeNode$interfaces + : []; + }) + .filter((ifaceNode) => ifaceNode.name.value === iface.name); + } + function getUnionMemberTypeNodes(union, typeName) { + const { astNode, extensionASTNodes } = union; + const nodes = + astNode != null + ? [astNode, ...extensionASTNodes] + : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((unionNode) => { + var _unionNode$types; + return /* c8 ignore next */ (_unionNode$types = + unionNode.types) !== null && _unionNode$types !== void 0 + ? _unionNode$types + : []; + }) + .filter((typeNode) => typeNode.name.value === typeName); + } + function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + return definitionNode === null || definitionNode === void 0 + ? void 0 + : (_definitionNode$direc = definitionNode.directives) === null || + _definitionNode$direc === void 0 + ? void 0 + : _definitionNode$direc.find( + (node) => + node.name.value === + _directives.GraphQLDeprecatedDirective.name + ); + } + + /***/ }, - resolve(type, { - includeDeprecated - }) { - if ((0, _definition.isEnumType)(type)) { - const values = type.getValues(); - return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); - } - } - }, - inputFields: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false + + /***/ "../../../node_modules/graphql/utilities/TypeInfo.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/TypeInfo.mjs ***! + \************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.TypeInfo = void 0; + exports.visitWithTypeInfo = visitWithTypeInfo; + var _ast = __webpack_require__( + /*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _visitor = __webpack_require__( + /*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _introspection = __webpack_require__( + /*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + /** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + + class TypeInfo { + constructor( + schema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType /** @deprecated will be removed in 17.0.0 */, + getFieldDefFn + ) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = + getFieldDefFn !== null && getFieldDefFn !== void 0 + ? getFieldDefFn + : getFieldDef; + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + get [Symbol.toStringTag]() { + return "TypeInfo"; + } + getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[ + this._defaultValueStack.length - 1 + ]; + } + } + getDirective() { + return this._directive; + } + getArgument() { + return this._argument; + } + getEnumValue() { + return this._enumValue; + } + enter(node) { + const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: { + const namedType = (0, _definition.getNamedType)(this.getType()); + this._parentTypeStack.push( + (0, _definition.isCompositeType)(namedType) + ? namedType + : undefined + ); + break; + } + case _kinds.Kind.FIELD: { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + if (fieldDef) { + fieldType = fieldDef.type; + } + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push( + (0, _definition.isOutputType)(fieldType) + ? fieldType + : undefined + ); + break; + } + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case _kinds.Kind.OPERATION_DEFINITION: { + const rootType = schema.getRootType(node.operation); + this._typeStack.push( + (0, _definition.isObjectType)(rootType) ? rootType : undefined + ); + break; + } + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST + ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) + : (0, _definition.getNamedType)(this.getType()); + this._typeStack.push( + (0, _definition.isOutputType)(outputType) + ? outputType + : undefined + ); + break; + } + case _kinds.Kind.VARIABLE_DEFINITION: { + const inputType = (0, _typeFromAST.typeFromAST)( + schema, + node.type + ); + this._inputTypeStack.push( + (0, _definition.isInputType)(inputType) + ? inputType + : undefined + ); + break; + } + case _kinds.Kind.ARGUMENT: { + var _this$getDirective; + let argDef; + let argType; + const fieldOrDirective = + (_this$getDirective = this.getDirective()) !== null && + _this$getDirective !== void 0 + ? _this$getDirective + : this.getFieldDef(); + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find( + (arg) => arg.name === node.name.value + ); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._defaultValueStack.push( + argDef ? argDef.defaultValue : undefined + ); + this._inputTypeStack.push( + (0, _definition.isInputType)(argType) ? argType : undefined + ); + break; + } + case _kinds.Kind.LIST: { + const listType = (0, _definition.getNullableType)( + this.getInputType() + ); + const itemType = (0, _definition.isListType)(listType) + ? listType.ofType + : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + this._inputTypeStack.push( + (0, _definition.isInputType)(itemType) ? itemType : undefined + ); + break; + } + case _kinds.Kind.OBJECT_FIELD: { + const objectType = (0, _definition.getNamedType)( + this.getInputType() + ); + let inputFieldType; + let inputField; + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + if (inputField) { + inputFieldType = inputField.type; + } + } + this._defaultValueStack.push( + inputField ? inputField.defaultValue : undefined + ); + this._inputTypeStack.push( + (0, _definition.isInputType)(inputFieldType) + ? inputFieldType + : undefined + ); + break; + } + case _kinds.Kind.ENUM: { + const enumType = (0, _definition.getNamedType)( + this.getInputType() + ); + let enumValue; + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + default: // Ignore other nodes + } + } + leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case _kinds.Kind.ARGUMENT: + this._argument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + default: // Ignore other nodes + } + } } - }, - resolve(type, { - includeDeprecated - }) { - if ((0, _definition.isInputObjectType)(type)) { - const values = Object.values(type.getFields()); - return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); + + /** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ + exports.TypeInfo = TypeInfo; + function getFieldDef(schema, parentType, fieldNode) { + const name = fieldNode.name.value; + if ( + name === _introspection.SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.SchemaMetaFieldDef; + } + if ( + name === _introspection.TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.TypeMetaFieldDef; + } + if ( + name === _introspection.TypeNameMetaFieldDef.name && + (0, _definition.isCompositeType)(parentType) + ) { + return _introspection.TypeNameMetaFieldDef; + } + if ( + (0, _definition.isObjectType)(parentType) || + (0, _definition.isInterfaceType)(parentType) + ) { + return parentType.getFields()[name]; + } } - } - }, - ofType: { - type: __Type, - resolve: type => 'ofType' in type ? type.ofType : undefined - } - }) -}); -const __Field = exports.__Field = new _definition.GraphQLObjectType({ - name: '__Field', - description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: field => field.name - }, - description: { - type: _scalars.GraphQLString, - resolve: field => field.description - }, - args: { - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false + /** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + + function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = (0, _visitor.getEnterLeaveForKind)( + visitor, + node.kind + ).enter; + if (fn) { + const result = fn.apply(visitor, args); + if (result !== undefined) { + typeInfo.leave(node); + if ((0, _ast.isNode)(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(...args) { + const node = args[0]; + const fn = (0, _visitor.getEnterLeaveForKind)( + visitor, + node.kind + ).leave; + let result; + if (fn) { + result = fn.apply(visitor, args); + } + typeInfo.leave(node); + return result; + }, + }; } + + /***/ }, - resolve(field, { - includeDeprecated - }) { - return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); - } - }, - type: { - type: new _definition.GraphQLNonNull(__Type), - resolve: field => field.type - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: field => field.deprecationReason != null - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: field => field.deprecationReason - } - }) -}); -const __InputValue = exports.__InputValue = new _definition.GraphQLObjectType({ - name: '__InputValue', - description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: inputValue => inputValue.name - }, - description: { - type: _scalars.GraphQLString, - resolve: inputValue => inputValue.description - }, - type: { - type: new _definition.GraphQLNonNull(__Type), - resolve: inputValue => inputValue.type - }, - defaultValue: { - type: _scalars.GraphQLString, - description: 'A GraphQL-formatted string representing the default value for this input value.', - resolve(inputValue) { - const { - type, - defaultValue - } = inputValue; - const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); - return valueAST ? (0, _printer.print)(valueAST) : null; - } - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: field => field.deprecationReason != null - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: obj => obj.deprecationReason - } - }) -}); -const __EnumValue = exports.__EnumValue = new _definition.GraphQLObjectType({ - name: '__EnumValue', - description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: enumValue => enumValue.name - }, - description: { - type: _scalars.GraphQLString, - resolve: enumValue => enumValue.description - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: enumValue => enumValue.deprecationReason != null - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: enumValue => enumValue.deprecationReason - } - }) -}); -var TypeKind; -(function (TypeKind) { - TypeKind['SCALAR'] = 'SCALAR'; - TypeKind['OBJECT'] = 'OBJECT'; - TypeKind['INTERFACE'] = 'INTERFACE'; - TypeKind['UNION'] = 'UNION'; - TypeKind['ENUM'] = 'ENUM'; - TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; - TypeKind['LIST'] = 'LIST'; - TypeKind['NON_NULL'] = 'NON_NULL'; -})(TypeKind || (exports.TypeKind = TypeKind = {})); -const __TypeKind = exports.__TypeKind = new _definition.GraphQLEnumType({ - name: '__TypeKind', - description: 'An enum describing what kind of type a given `__Type` is.', - values: { - SCALAR: { - value: TypeKind.SCALAR, - description: 'Indicates this type is a scalar.' - }, - OBJECT: { - value: TypeKind.OBJECT, - description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.' - }, - INTERFACE: { - value: TypeKind.INTERFACE, - description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.' - }, - UNION: { - value: TypeKind.UNION, - description: 'Indicates this type is a union. `possibleTypes` is a valid field.' - }, - ENUM: { - value: TypeKind.ENUM, - description: 'Indicates this type is an enum. `enumValues` is a valid field.' - }, - INPUT_OBJECT: { - value: TypeKind.INPUT_OBJECT, - description: 'Indicates this type is an input object. `inputFields` is a valid field.' - }, - LIST: { - value: TypeKind.LIST, - description: 'Indicates this type is a list. `ofType` is a valid field.' - }, - NON_NULL: { - value: TypeKind.NON_NULL, - description: 'Indicates this type is a non-null. `ofType` is a valid field.' - } - } -}); -/** - * Note that these are GraphQLField and not GraphQLFieldConfig, - * so the format for args is different. - */ - -const SchemaMetaFieldDef = exports.SchemaMetaFieldDef = { - name: '__schema', - type: new _definition.GraphQLNonNull(__Schema), - description: 'Access the current type schema of this server.', - args: [], - resolve: (_source, _args, _context, { - schema - }) => schema, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined -}; -const TypeMetaFieldDef = exports.TypeMetaFieldDef = { - name: '__type', - type: __Type, - description: 'Request the type information of a single type.', - args: [{ - name: 'name', - description: undefined, - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - defaultValue: undefined, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined - }], - resolve: (_source, { - name - }, _context, { - schema - }) => schema.getType(name), - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined -}; -const TypeNameMetaFieldDef = exports.TypeNameMetaFieldDef = { - name: '__typename', - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - description: 'The name of the current Object type at runtime.', - args: [], - resolve: (_source, _args, _context, { - parentType - }) => parentType.name, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined -}; -const introspectionTypes = exports.introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]); -function isIntrospectionType(type) { - return introspectionTypes.some(({ - name - }) => type.name === name); -} -/***/ }), + /***/ "../../../node_modules/graphql/utilities/assertValidName.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/assertValidName.mjs ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.assertValidName = assertValidName; + exports.isValidNameError = isValidNameError; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _assertName = __webpack_require__( + /*! ../type/assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs" + ); + /* c8 ignore start */ -/***/ "../../../node_modules/graphql/type/scalars.mjs": -/*!******************************************************!*\ - !*** ../../../node_modules/graphql/type/scalars.mjs ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GraphQLString = exports.GraphQLInt = exports.GraphQLID = exports.GraphQLFloat = exports.GraphQLBoolean = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = void 0; -exports.isSpecifiedScalarType = isSpecifiedScalarType; -exports.specifiedScalarTypes = void 0; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). - * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 - * */ - -const GRAPHQL_MAX_INT = exports.GRAPHQL_MAX_INT = 2147483647; -/** - * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). - * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) - * */ - -const GRAPHQL_MIN_INT = exports.GRAPHQL_MIN_INT = -2147483648; -const GraphQLInt = exports.GraphQLInt = new _definition.GraphQLScalarType({ - name: 'Int', - description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue ? 1 : 0; - } - let num = coercedValue; - if (typeof coercedValue === 'string' && coercedValue !== '') { - num = Number(coercedValue); - } - if (typeof num !== 'number' || !Number.isInteger(num)) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(coercedValue)}`); - } - if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError('Int cannot represent non 32-bit signed integer value: ' + (0, _inspect.inspect)(coercedValue)); - } - return num; - }, - parseValue(inputValue) { - if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(inputValue)}`); - } - if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${inputValue}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _printer.print)(valueNode)}`, { - nodes: valueNode - }); - } - const num = parseInt(valueNode.value, 10); - if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, { - nodes: valueNode - }); - } - return num; - } -}); -const GraphQLFloat = exports.GraphQLFloat = new _definition.GraphQLScalarType({ - name: 'Float', - description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue ? 1 : 0; - } - let num = coercedValue; - if (typeof coercedValue === 'string' && coercedValue !== '') { - num = Number(coercedValue); - } - if (typeof num !== 'number' || !Number.isFinite(num)) { - throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(coercedValue)}`); - } - return num; - }, - parseValue(inputValue) { - if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { - throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(inputValue)}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.FLOAT && valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _printer.print)(valueNode)}`, valueNode); - } - return parseFloat(valueNode.value); - } -}); -const GraphQLString = exports.GraphQLString = new _definition.GraphQLScalarType({ - name: 'String', - description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not - // attempt to coerce object, function, symbol, or other types as strings. - - if (typeof coercedValue === 'string') { - return coercedValue; - } - if (typeof coercedValue === 'boolean') { - return coercedValue ? 'true' : 'false'; - } - if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { - return coercedValue.toString(); - } - throw new _GraphQLError.GraphQLError(`String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); - }, - parseValue(inputValue) { - if (typeof inputValue !== 'string') { - throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _inspect.inspect)(inputValue)}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.STRING) { - throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _printer.print)(valueNode)}`, { - nodes: valueNode - }); - } - return valueNode.value; - } -}); -const GraphQLBoolean = exports.GraphQLBoolean = new _definition.GraphQLScalarType({ - name: 'Boolean', - description: 'The `Boolean` scalar type represents `true` or `false`.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue; - } - if (Number.isFinite(coercedValue)) { - return coercedValue !== 0; - } - throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(coercedValue)}`); - }, - parseValue(inputValue) { - if (typeof inputValue !== 'boolean') { - throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(inputValue)}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.BOOLEAN) { - throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _printer.print)(valueNode)}`, { - nodes: valueNode - }); - } - return valueNode.value; - } -}); -const GraphQLID = exports.GraphQLID = new _definition.GraphQLScalarType({ - name: 'ID', - description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'string') { - return coercedValue; - } - if (Number.isInteger(coercedValue)) { - return String(coercedValue); - } - throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); - }, - parseValue(inputValue) { - if (typeof inputValue === 'string') { - return inputValue; - } - if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { - return inputValue.toString(); - } - throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`); - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.STRING && valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError('ID cannot represent a non-string and non-integer value: ' + (0, _printer.print)(valueNode), { - nodes: valueNode - }); - } - return valueNode.value; - } -}); -const specifiedScalarTypes = exports.specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]); -function isSpecifiedScalarType(type) { - return specifiedScalarTypes.some(({ - name - }) => type.name === name); -} // Support serializing objects with custom valueOf() or toJSON() functions - -// a common way to represent a complex value which can be represented as -// a string (ex: MongoDB id objects). - -function serializeObject(outputValue) { - if ((0, _isObjectLike.isObjectLike)(outputValue)) { - if (typeof outputValue.valueOf === 'function') { - const valueOfResult = outputValue.valueOf(); - if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { - return valueOfResult; - } - } - if (typeof outputValue.toJSON === 'function') { - return outputValue.toJSON(); - } - } - return outputValue; -} + /** + * Upholds the spec rules about naming. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ -/***/ }), + function assertValidName(name) { + const error = isValidNameError(name); + if (error) { + throw error; + } + return name; + } + /** + * Returns an Error if a name is invalid. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ -/***/ "../../../node_modules/graphql/type/schema.mjs": -/*!*****************************************************!*\ - !*** ../../../node_modules/graphql/type/schema.mjs ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GraphQLSchema = void 0; -exports.assertSchema = assertSchema; -exports.isSchema = isSchema; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); -var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -/** - * Test if the given value is a GraphQL schema. - */ - -function isSchema(schema) { - return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); -} -function assertSchema(schema) { - if (!isSchema(schema)) { - throw new Error(`Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`); - } - return schema; -} -/** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ - -/** - * Schema Definition - * - * A Schema is created by supplying the root types of each type of operation, - * query and mutation (optional). A schema definition is then supplied to the - * validator and executor. - * - * Example: - * - * ```ts - * const MyAppSchema = new GraphQLSchema({ - * query: MyAppQueryRootType, - * mutation: MyAppMutationRootType, - * }) - * ``` - * - * Note: When the schema is constructed, by default only the types that are - * reachable by traversing the root types are included, other types must be - * explicitly referenced. - * - * Example: - * - * ```ts - * const characterInterface = new GraphQLInterfaceType({ - * name: 'Character', - * ... - * }); - * - * const humanType = new GraphQLObjectType({ - * name: 'Human', - * interfaces: [characterInterface], - * ... - * }); - * - * const droidType = new GraphQLObjectType({ - * name: 'Droid', - * interfaces: [characterInterface], - * ... - * }); - * - * const schema = new GraphQLSchema({ - * query: new GraphQLObjectType({ - * name: 'Query', - * fields: { - * hero: { type: characterInterface, ... }, - * } - * }), - * ... - * // Since this schema references only the `Character` interface it's - * // necessary to explicitly list the types that implement it if - * // you want them to be included in the final schema. - * types: [humanType, droidType], - * }) - * ``` - * - * Note: If an array of `directives` are provided to GraphQLSchema, that will be - * the exact list of directives represented and allowed. If `directives` is not - * provided then a default set of the specified directives (e.g. `@include` and - * `@skip`) will be used. If you wish to provide *additional* directives to these - * specified directives, you must explicitly declare them. Example: - * - * ```ts - * const MyAppSchema = new GraphQLSchema({ - * ... - * directives: specifiedDirectives.concat([ myCustomDirective ]), - * }) - * ``` - */ -class GraphQLSchema { - // Used as a cache for validateSchema(). - constructor(config) { - var _config$extensionASTN, _config$directives; - - // If this schema was built from a source known to be valid, then it may be - // marked with assumeValid to avoid an additional type system validation. - this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. - - (0, _isObjectLike.isObjectLike)(config) || (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); - !config.types || Array.isArray(config.types) || (0, _devAssert.devAssert)(false, `"types" must be Array if provided but got: ${(0, _inspect.inspect)(config.types)}.`); - !config.directives || Array.isArray(config.directives) || (0, _devAssert.devAssert)(false, '"directives" must be Array if provided but got: ' + `${(0, _inspect.inspect)(config.directives)}.`); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; - this._queryType = config.query; - this._mutationType = config.mutation; - this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. - - this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to - // the set of "collected" types, so `collectReferencedTypes` ignore them. - - const allReferencedTypes = new Set(config.types); - if (config.types != null) { - for (const type of config.types) { - // When we ready to process this type, we remove it from "collected" types - // and then add it together with all dependent types in the correct position. - allReferencedTypes.delete(type); - collectReferencedTypes(type, allReferencedTypes); - } - } - if (this._queryType != null) { - collectReferencedTypes(this._queryType, allReferencedTypes); - } - if (this._mutationType != null) { - collectReferencedTypes(this._mutationType, allReferencedTypes); - } - if (this._subscriptionType != null) { - collectReferencedTypes(this._subscriptionType, allReferencedTypes); - } - for (const directive of this._directives) { - // Directives are not validated until validateSchema() is called. - if ((0, _directives.isDirective)(directive)) { - for (const arg of directive.args) { - collectReferencedTypes(arg.type, allReferencedTypes); + function isValidNameError(name) { + typeof name === "string" || + (0, _devAssert.devAssert)(false, "Expected name to be a string."); + if (name.startsWith("__")) { + return new _GraphQLError.GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.` + ); + } + try { + (0, _assertName.assertName)(name); + } catch (error) { + return error; + } } - } - } - collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + /* c8 ignore stop */ + + /***/ + }, + + /***/ "../../../node_modules/graphql/utilities/astFromValue.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/astFromValue.mjs ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.astFromValue = astFromValue; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _isIterableObject = __webpack_require__( + /*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _scalars = __webpack_require__( + /*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + /** + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. For example: + * + * astFromValue("value", GraphQLString) + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * + */ + + function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + const astValue = astFromValue(value, type.ofType); + if ( + (astValue === null || astValue === void 0 + ? void 0 + : astValue.kind) === _kinds.Kind.NULL + ) { + return null; + } + return astValue; + } // only explicit null, not undefined, NaN - this._typeMap = Object.create(null); - this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + if (value === null) { + return { + kind: _kinds.Kind.NULL, + }; + } // undefined - this._implementationsMap = Object.create(null); - for (const namedType of allReferencedTypes) { - if (namedType == null) { - continue; - } - const typeName = namedType.name; - typeName || (0, _devAssert.devAssert)(false, 'One of the provided types for building the Schema is missing a name.'); - if (this._typeMap[typeName] !== undefined) { - throw new Error(`Schema must contain uniquely named types but contains multiple types named "${typeName}".`); - } - this._typeMap[typeName] = namedType; - if ((0, _definition.isInterfaceType)(namedType)) { - // Store implementations by interface. - for (const iface of namedType.getInterfaces()) { - if ((0, _definition.isInterfaceType)(iface)) { - let implementations = this._implementationsMap[iface.name]; - if (implementations === undefined) { - implementations = this._implementationsMap[iface.name] = { - objects: [], - interfaces: [] + if (value === undefined) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if ((0, _isIterableObject.isIterableObject)(value)) { + const valuesNodes = []; + for (const item of value) { + const itemNode = astFromValue(item, itemType); + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + return { + kind: _kinds.Kind.LIST, + values: valuesNodes, }; } - implementations.interfaces.push(namedType); - } - } - } else if ((0, _definition.isObjectType)(namedType)) { - // Store implementations by objects. - for (const iface of namedType.getInterfaces()) { - if ((0, _definition.isInterfaceType)(iface)) { - let implementations = this._implementationsMap[iface.name]; - if (implementations === undefined) { - implementations = this._implementationsMap[iface.name] = { - objects: [], - interfaces: [] - }; + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(value)) { + return null; + } + const fieldNodes = []; + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name, + }, + value: fieldValue, + }); + } } - implementations.objects.push(namedType); + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes, + }; } - } - } - } - } - get [Symbol.toStringTag]() { - return 'GraphQLSchema'; - } - getQueryType() { - return this._queryType; - } - getMutationType() { - return this._mutationType; - } - getSubscriptionType() { - return this._subscriptionType; - } - getRootType(operation) { - switch (operation) { - case _ast.OperationTypeNode.QUERY: - return this.getQueryType(); - case _ast.OperationTypeNode.MUTATION: - return this.getMutationType(); - case _ast.OperationTypeNode.SUBSCRIPTION: - return this.getSubscriptionType(); - } - } - getTypeMap() { - return this._typeMap; - } - getType(name) { - return this.getTypeMap()[name]; - } - getPossibleTypes(abstractType) { - return (0, _definition.isUnionType)(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; - } - getImplementations(interfaceType) { - const implementations = this._implementationsMap[interfaceType.name]; - return implementations !== null && implementations !== void 0 ? implementations : { - objects: [], - interfaces: [] - }; - } - isSubType(abstractType, maybeSubType) { - let map = this._subTypeMap[abstractType.name]; - if (map === undefined) { - map = Object.create(null); - if ((0, _definition.isUnionType)(abstractType)) { - for (const type of abstractType.getTypes()) { - map[type.name] = true; - } - } else { - const implementations = this.getImplementations(abstractType); - for (const type of implementations.objects) { - map[type.name] = true; - } - for (const type of implementations.interfaces) { - map[type.name] = true; - } - } - this._subTypeMap[abstractType.name] = map; - } - return map[maybeSubType.name] !== undefined; - } - getDirectives() { - return this._directives; - } - getDirective(name) { - return this.getDirectives().find(directive => directive.name === name); - } - toConfig() { - return { - description: this.description, - query: this.getQueryType(), - mutation: this.getMutationType(), - subscription: this.getSubscriptionType(), - types: Object.values(this.getTypeMap()), - directives: this.getDirectives(), - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - assumeValid: this.__validationErrors !== undefined - }; - } -} -exports.GraphQLSchema = GraphQLSchema; -function collectReferencedTypes(type, typeSet) { - const namedType = (0, _definition.getNamedType)(type); - if (!typeSet.has(namedType)) { - typeSet.add(namedType); - if ((0, _definition.isUnionType)(namedType)) { - for (const memberType of namedType.getTypes()) { - collectReferencedTypes(memberType, typeSet); - } - } else if ((0, _definition.isObjectType)(namedType) || (0, _definition.isInterfaceType)(namedType)) { - for (const interfaceType of namedType.getInterfaces()) { - collectReferencedTypes(interfaceType, typeSet); - } - for (const field of Object.values(namedType.getFields())) { - collectReferencedTypes(field.type, typeSet); - for (const arg of field.args) { - collectReferencedTypes(arg.type, typeSet); - } - } - } else if ((0, _definition.isInputObjectType)(namedType)) { - for (const field of Object.values(namedType.getFields())) { - collectReferencedTypes(field.type, typeSet); - } - } - } - return typeSet; -} + if ((0, _definition.isLeafType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + if (serialized == null) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. -/***/ }), + if (typeof serialized === "boolean") { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized, + }; + } // JavaScript numbers can be Int or Float values. + + if (typeof serialized === "number" && Number.isFinite(serialized)) { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) + ? { + kind: _kinds.Kind.INT, + value: stringNum, + } + : { + kind: _kinds.Kind.FLOAT, + value: stringNum, + }; + } + if (typeof serialized === "string") { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized, + }; + } // ID types can use Int literals. -/***/ "../../../node_modules/graphql/type/validate.mjs": -/*!*******************************************************!*\ - !*** ../../../node_modules/graphql/type/validate.mjs ***! - \*******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.assertValidSchema = assertValidSchema; -exports.validateSchema = validateSchema; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _typeComparators = __webpack_require__(/*! ../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); -var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); -/** - * Implements the "Type Validation" sub-sections of the specification's - * "Type System" section. - * - * Validation runs synchronously, returning an array of encountered errors, or - * an empty array if no errors were encountered and the Schema is valid. - */ - -function validateSchema(schema) { - // First check to ensure the provided value is in fact a GraphQLSchema. - (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. - - if (schema.__validationErrors) { - return schema.__validationErrors; - } // Validate the schema, producing a list of errors. - - const context = new SchemaValidationContext(schema); - validateRootTypes(context); - validateDirectives(context); - validateTypes(context); // Persist the results of validation before returning to ensure validation - // does not run multiple times for this schema. - - const errors = context.getErrors(); - schema.__validationErrors = errors; - return errors; -} -/** - * Utility function which asserts a schema is valid by throwing an error if - * it is invalid. - */ - -function assertValidSchema(schema) { - const errors = validateSchema(schema); - if (errors.length !== 0) { - throw new Error(errors.map(error => error.message).join('\n\n')); - } -} -class SchemaValidationContext { - constructor(schema) { - this._errors = []; - this.schema = schema; - } - reportError(message, nodes) { - const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; - this._errors.push(new _GraphQLError.GraphQLError(message, { - nodes: _nodes - })); - } - getErrors() { - return this._errors; - } -} -function validateRootTypes(context) { - const schema = context.schema; - const queryType = schema.getQueryType(); - if (!queryType) { - context.reportError('Query root type must be provided.', schema.astNode); - } else if (!(0, _definition.isObjectType)(queryType)) { - var _getOperationTypeNode; - context.reportError(`Query root type must be Object type, it cannot be ${(0, _inspect.inspect)(queryType)}.`, (_getOperationTypeNode = getOperationTypeNode(schema, _ast.OperationTypeNode.QUERY)) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode); - } - const mutationType = schema.getMutationType(); - if (mutationType && !(0, _definition.isObjectType)(mutationType)) { - var _getOperationTypeNode2; - context.reportError('Mutation root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(mutationType)}.`, (_getOperationTypeNode2 = getOperationTypeNode(schema, _ast.OperationTypeNode.MUTATION)) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode); - } - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { - var _getOperationTypeNode3; - context.reportError('Subscription root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(subscriptionType)}.`, (_getOperationTypeNode3 = getOperationTypeNode(schema, _ast.OperationTypeNode.SUBSCRIPTION)) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode); - } -} -function getOperationTypeNode(schema, operation) { - var _flatMap$find; - return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes].flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - schemaNode => { - var _schemaNode$operation; - return /* c8 ignore next */( - (_schemaNode$operation = schemaNode === null || schemaNode === void 0 ? void 0 : schemaNode.operationTypes) !== null && _schemaNode$operation !== void 0 ? _schemaNode$operation : [] - ); - }).find(operationNode => operationNode.operation === operation)) === null || _flatMap$find === void 0 ? void 0 : _flatMap$find.type; -} -function validateDirectives(context) { - for (const directive of context.schema.getDirectives()) { - // Ensure all directives are in fact GraphQL directives. - if (!(0, _directives.isDirective)(directive)) { - context.reportError(`Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, directive === null || directive === void 0 ? void 0 : directive.astNode); - continue; - } // Ensure they are named correctly. - - validateName(context, directive); // TODO: Ensure proper locations. - // Ensure the arguments are valid. - - for (const arg of directive.args) { - // Ensure they are named correctly. - validateName(context, arg); // Ensure the type is an input type. - - if (!(0, _definition.isInputType)(arg.type)) { - context.reportError(`The type of @${directive.name}(${arg.name}:) must be Input Type ` + `but got: ${(0, _inspect.inspect)(arg.type)}.`, arg.astNode); - } - if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { - var _arg$astNode; - context.reportError(`Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type]); - } - } - } -} -function validateName(context, node) { - // Ensure names are valid, however introspection types opt out. - if (node.name.startsWith('__')) { - context.reportError(`Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, node.astNode); - } -} -function validateTypes(context) { - const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context); - const typeMap = context.schema.getTypeMap(); - for (const type of Object.values(typeMap)) { - // Ensure all provided types are in fact GraphQL type. - if (!(0, _definition.isNamedType)(type)) { - context.reportError(`Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, type.astNode); - continue; - } // Ensure it is named correctly (excluding introspection types). - - if (!(0, _introspection.isIntrospectionType)(type)) { - validateName(context, type); - } - if ((0, _definition.isObjectType)(type)) { - // Ensure fields are valid - validateFields(context, type); // Ensure objects implement the interfaces they claim to. - - validateInterfaces(context, type); - } else if ((0, _definition.isInterfaceType)(type)) { - // Ensure fields are valid. - validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. - - validateInterfaces(context, type); - } else if ((0, _definition.isUnionType)(type)) { - // Ensure Unions include valid member types. - validateUnionMembers(context, type); - } else if ((0, _definition.isEnumType)(type)) { - // Ensure Enums have valid values. - validateEnumValues(context, type); - } else if ((0, _definition.isInputObjectType)(type)) { - // Ensure Input Object fields are valid. - validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references - - validateInputObjectCircularRefs(type); - } - } -} -function validateFields(context, type) { - const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + if ( + type === _scalars.GraphQLID && + integerStringRegExp.test(serialized) + ) { + return { + kind: _kinds.Kind.INT, + value: serialized, + }; + } + return { + kind: _kinds.Kind.STRING, + value: serialized, + }; + } + throw new TypeError( + `Cannot convert value to AST: ${(0, _inspect.inspect)( + serialized + )}.` + ); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. - if (fields.length === 0) { - context.reportError(`Type ${type.name} must define one or more fields.`, [type.astNode, ...type.extensionASTNodes]); - } - for (const field of fields) { - // Ensure they are named correctly. - validateName(context, field); // Ensure the type is an output type + false || + (0, _invariant.invariant)( + false, + "Unexpected input type: " + (0, _inspect.inspect)(type) + ); + } + /** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ - if (!(0, _definition.isOutputType)(field.type)) { - var _field$astNode; - context.reportError(`The type of ${type.name}.${field.name} must be Output Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type); - } // Ensure the arguments are valid + const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; - for (const arg of field.args) { - const argName = arg.name; // Ensure they are named correctly. + /***/ + }, - validateName(context, arg); // Ensure the type is an input type + /***/ "../../../node_modules/graphql/utilities/buildASTSchema.mjs": + /*!******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/buildASTSchema.mjs ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.buildASTSchema = buildASTSchema; + exports.buildSchema = buildSchema; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _parser = __webpack_require__( + /*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs" + ); + var _directives = __webpack_require__( + /*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _schema = __webpack_require__( + /*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs" + ); + var _validate = __webpack_require__( + /*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs" + ); + var _extendSchema = __webpack_require__( + /*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs" + ); + /** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + */ + function buildASTSchema(documentAST, options) { + (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || + (0, _devAssert.devAssert)( + false, + "Must provide valid Document AST." + ); + if ( + (options === null || options === void 0 + ? void 0 + : options.assumeValid) !== true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + (0, _validate.assertValidSDL)(documentAST); + } + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false, + }; + const config = (0, _extendSchema.extendSchemaImpl)( + emptySchemaConfig, + documentAST, + options + ); + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + case "Query": + // @ts-expect-error validated in `validateSchema` + config.query = type; + break; + case "Mutation": + // @ts-expect-error validated in `validateSchema` + config.mutation = type; + break; + case "Subscription": + // @ts-expect-error validated in `validateSchema` + config.subscription = type; + break; + } + } + } + const directives = [ + ...config.directives, + // If specified directives were not explicitly declared, add them. + ..._directives.specifiedDirectives.filter((stdDirective) => + config.directives.every( + (directive) => directive.name !== stdDirective.name + ) + ), + ]; + return new _schema.GraphQLSchema({ + ...config, + directives, + }); + } + /** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ - if (!(0, _definition.isInputType)(arg.type)) { - var _arg$astNode2; - context.reportError(`The type of ${type.name}.${field.name}(${argName}:) must be Input ` + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type); - } - if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { - var _arg$astNode3; - context.reportError(`Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type]); - } - } - } -} -function validateInterfaces(context, type) { - const ifaceTypeNames = Object.create(null); - for (const iface of type.getInterfaces()) { - if (!(0, _definition.isInterfaceType)(iface)) { - context.reportError(`Type ${(0, _inspect.inspect)(type)} must only implement Interface types, ` + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, getAllImplementsInterfaceNodes(type, iface)); - continue; - } - if (type === iface) { - context.reportError(`Type ${type.name} cannot implement itself because it would create a circular reference.`, getAllImplementsInterfaceNodes(type, iface)); - continue; - } - if (ifaceTypeNames[iface.name]) { - context.reportError(`Type ${type.name} can only implement ${iface.name} once.`, getAllImplementsInterfaceNodes(type, iface)); - continue; - } - ifaceTypeNames[iface.name] = true; - validateTypeImplementsAncestors(context, type, iface); - validateTypeImplementsInterface(context, type, iface); - } -} -function validateTypeImplementsInterface(context, type, iface) { - const typeFieldMap = type.getFields(); // Assert each interface field is implemented. - - for (const ifaceField of Object.values(iface.getFields())) { - const fieldName = ifaceField.name; - const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. - - if (!typeField) { - context.reportError(`Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, [ifaceField.astNode, type.astNode, ...type.extensionASTNodes]); - continue; - } // Assert interface field type is satisfied by type field type, by being - // a valid subtype. (covariant) - - if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, typeField.type, ifaceField.type)) { - var _ifaceField$astNode, _typeField$astNode; - context.reportError(`Interface field ${iface.name}.${fieldName} expects type ` + `${(0, _inspect.inspect)(ifaceField.type)} but ${type.name}.${fieldName} ` + `is type ${(0, _inspect.inspect)(typeField.type)}.`, [(_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]); - } // Assert each interface field arg is implemented. - - for (const ifaceArg of ifaceField.args) { - const argName = ifaceArg.name; - const typeArg = typeField.args.find(arg => arg.name === argName); // Assert interface field arg exists on object field. - - if (!typeArg) { - context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, [ifaceArg.astNode, typeField.astNode]); - continue; - } // Assert interface field arg type matches object field arg type. - // (invariant) - // TODO: change to contravariant? - - if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { - var _ifaceArg$astNode, _typeArg$astNode; - context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + `${type.name}.${fieldName}(${argName}:) is type ` + `${(0, _inspect.inspect)(typeArg.type)}.`, [(_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]); - } // TODO: validate default values? - } // Assert additional arguments must not be required. - - for (const typeArg of typeField.args) { - const argName = typeArg.name; - const ifaceArg = ifaceField.args.find(arg => arg.name === argName); - if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { - context.reportError(`Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, [typeArg.astNode, ifaceField.astNode]); - } - } - } -} -function validateTypeImplementsAncestors(context, type, iface) { - const ifaceInterfaces = type.getInterfaces(); - for (const transitive of iface.getInterfaces()) { - if (!ifaceInterfaces.includes(transitive)) { - context.reportError(transitive === type ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, [...getAllImplementsInterfaceNodes(iface, transitive), ...getAllImplementsInterfaceNodes(type, iface)]); - } - } -} -function validateUnionMembers(context, union) { - const memberTypes = union.getTypes(); - if (memberTypes.length === 0) { - context.reportError(`Union type ${union.name} must define one or more member types.`, [union.astNode, ...union.extensionASTNodes]); - } - const includedTypeNames = Object.create(null); - for (const memberType of memberTypes) { - if (includedTypeNames[memberType.name]) { - context.reportError(`Union type ${union.name} can only include type ${memberType.name} once.`, getUnionMemberTypeNodes(union, memberType.name)); - continue; - } - includedTypeNames[memberType.name] = true; - if (!(0, _definition.isObjectType)(memberType)) { - context.reportError(`Union type ${union.name} can only include Object types, ` + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, getUnionMemberTypeNodes(union, String(memberType))); - } - } -} -function validateEnumValues(context, enumType) { - const enumValues = enumType.getValues(); - if (enumValues.length === 0) { - context.reportError(`Enum type ${enumType.name} must define one or more values.`, [enumType.astNode, ...enumType.extensionASTNodes]); - } - for (const enumValue of enumValues) { - // Ensure valid name. - validateName(context, enumValue); - } -} -function validateInputFields(context, inputObj) { - const fields = Object.values(inputObj.getFields()); - if (fields.length === 0) { - context.reportError(`Input Object type ${inputObj.name} must define one or more fields.`, [inputObj.astNode, ...inputObj.extensionASTNodes]); - } // Ensure the arguments are valid - - for (const field of fields) { - // Ensure they are named correctly. - validateName(context, field); // Ensure the type is an input type - - if (!(0, _definition.isInputType)(field.type)) { - var _field$astNode2; - context.reportError(`The type of ${inputObj.name}.${field.name} must be Input Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type); - } - if ((0, _definition.isRequiredInputField)(field) && field.deprecationReason != null) { - var _field$astNode3; - context.reportError(`Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, [getDeprecatedDirectiveNode(field.astNode), (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type]); - } - } -} -function createInputObjectCircularRefsValidator(context) { - // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. - // Tracks already visited types to maintain O(N) and to ensure that cycles - // are not redundantly reported. - const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors - - const fieldPath = []; // Position in the type path - - const fieldPathIndexByTypeName = Object.create(null); - return detectCycleRecursive; // This does a straight-forward DFS to find cycles. - // It does not terminate when a cycle was found but continues to explore - // the graph to find all possible cycles. - - function detectCycleRecursive(inputObj) { - if (visitedTypes[inputObj.name]) { - return; - } - visitedTypes[inputObj.name] = true; - fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; - const fields = Object.values(inputObj.getFields()); - for (const field of fields) { - if ((0, _definition.isNonNullType)(field.type) && (0, _definition.isInputObjectType)(field.type.ofType)) { - const fieldType = field.type.ofType; - const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; - fieldPath.push(field); - if (cycleIndex === undefined) { - detectCycleRecursive(fieldType); - } else { - const cyclePath = fieldPath.slice(cycleIndex); - const pathStr = cyclePath.map(fieldObj => fieldObj.name).join('.'); - context.reportError(`Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, cyclePath.map(fieldObj => fieldObj.astNode)); + function buildSchema(source, options) { + const document = (0, _parser.parse)(source, { + noLocation: + options === null || options === void 0 + ? void 0 + : options.noLocation, + allowLegacyFragmentVariables: + options === null || options === void 0 + ? void 0 + : options.allowLegacyFragmentVariables, + }); + return buildASTSchema(document, { + assumeValidSDL: + options === null || options === void 0 + ? void 0 + : options.assumeValidSDL, + assumeValid: + options === null || options === void 0 + ? void 0 + : options.assumeValid, + }); } - fieldPath.pop(); - } - } - fieldPathIndexByTypeName[inputObj.name] = undefined; - } -} -function getAllImplementsInterfaceNodes(type, iface) { - const { - astNode, - extensionASTNodes - } = type; - const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - return nodes.flatMap(typeNode => { - var _typeNode$interfaces; - return /* c8 ignore next */( - (_typeNode$interfaces = typeNode.interfaces) !== null && _typeNode$interfaces !== void 0 ? _typeNode$interfaces : [] - ); - }).filter(ifaceNode => ifaceNode.name.value === iface.name); -} -function getUnionMemberTypeNodes(union, typeName) { - const { - astNode, - extensionASTNodes - } = union; - const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - return nodes.flatMap(unionNode => { - var _unionNode$types; - return /* c8 ignore next */( - (_unionNode$types = unionNode.types) !== null && _unionNode$types !== void 0 ? _unionNode$types : [] - ); - }).filter(typeNode => typeNode.name.value === typeName); -} -function getDeprecatedDirectiveNode(definitionNode) { - var _definitionNode$direc; - return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(node => node.name.value === _directives.GraphQLDeprecatedDirective.name); -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/TypeInfo.mjs": -/*!************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/TypeInfo.mjs ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.TypeInfo = void 0; -exports.visitWithTypeInfo = visitWithTypeInfo; -var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -/** - * TypeInfo is a utility class which, given a GraphQL schema, can keep track - * of the current field and type definitions at any point in a GraphQL document - * AST during a recursive descent by calling `enter(node)` and `leave(node)`. - */ - -class TypeInfo { - constructor(schema, - /** - * Initial type may be provided in rare cases to facilitate traversals - * beginning somewhere other than documents. - */ - initialType, /** @deprecated will be removed in 17.0.0 */ - getFieldDefFn) { - this._schema = schema; - this._typeStack = []; - this._parentTypeStack = []; - this._inputTypeStack = []; - this._fieldDefStack = []; - this._defaultValueStack = []; - this._directive = null; - this._argument = null; - this._enumValue = null; - this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef; - if (initialType) { - if ((0, _definition.isInputType)(initialType)) { - this._inputTypeStack.push(initialType); - } - if ((0, _definition.isCompositeType)(initialType)) { - this._parentTypeStack.push(initialType); - } - if ((0, _definition.isOutputType)(initialType)) { - this._typeStack.push(initialType); - } - } - } - get [Symbol.toStringTag]() { - return 'TypeInfo'; - } - getType() { - if (this._typeStack.length > 0) { - return this._typeStack[this._typeStack.length - 1]; - } - } - getParentType() { - if (this._parentTypeStack.length > 0) { - return this._parentTypeStack[this._parentTypeStack.length - 1]; - } - } - getInputType() { - if (this._inputTypeStack.length > 0) { - return this._inputTypeStack[this._inputTypeStack.length - 1]; - } - } - getParentInputType() { - if (this._inputTypeStack.length > 1) { - return this._inputTypeStack[this._inputTypeStack.length - 2]; - } - } - getFieldDef() { - if (this._fieldDefStack.length > 0) { - return this._fieldDefStack[this._fieldDefStack.length - 1]; - } - } - getDefaultValue() { - if (this._defaultValueStack.length > 0) { - return this._defaultValueStack[this._defaultValueStack.length - 1]; - } - } - getDirective() { - return this._directive; - } - getArgument() { - return this._argument; - } - getEnumValue() { - return this._enumValue; - } - enter(node) { - const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop - // any assumptions of a valid schema to ensure runtime types are properly - // checked before continuing since TypeInfo is used as part of validation - // which occurs before guarantees of schema and document validity. - - switch (node.kind) { - case _kinds.Kind.SELECTION_SET: - { - const namedType = (0, _definition.getNamedType)(this.getType()); - this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); - break; - } - case _kinds.Kind.FIELD: - { - const parentType = this.getParentType(); - let fieldDef; - let fieldType; - if (parentType) { - fieldDef = this._getFieldDef(schema, parentType, node); - if (fieldDef) { - fieldType = fieldDef.type; - } - } - this._fieldDefStack.push(fieldDef); - this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined); - break; - } - case _kinds.Kind.DIRECTIVE: - this._directive = schema.getDirective(node.name.value); - break; - case _kinds.Kind.OPERATION_DEFINITION: - { - const rootType = schema.getRootType(node.operation); - this._typeStack.push((0, _definition.isObjectType)(rootType) ? rootType : undefined); - break; - } - case _kinds.Kind.INLINE_FRAGMENT: - case _kinds.Kind.FRAGMENT_DEFINITION: - { - const typeConditionAST = node.typeCondition; - const outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType()); - this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); - break; - } - case _kinds.Kind.VARIABLE_DEFINITION: - { - const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); - this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); - break; - } - case _kinds.Kind.ARGUMENT: - { - var _this$getDirective; - let argDef; - let argType; - const fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef(); - if (fieldOrDirective) { - argDef = fieldOrDirective.args.find(arg => arg.name === node.name.value); - if (argDef) { - argType = argDef.type; - } - } - this._argument = argDef; - this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); - this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined); - break; - } - case _kinds.Kind.LIST: - { - const listType = (0, _definition.getNullableType)(this.getInputType()); - const itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value. - - this._defaultValueStack.push(undefined); - this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined); - break; - } - case _kinds.Kind.OBJECT_FIELD: - { - const objectType = (0, _definition.getNamedType)(this.getInputType()); - let inputFieldType; - let inputField; - if ((0, _definition.isInputObjectType)(objectType)) { - inputField = objectType.getFields()[node.name.value]; - if (inputField) { - inputFieldType = inputField.type; - } - } - this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); - this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined); - break; - } - case _kinds.Kind.ENUM: - { - const enumType = (0, _definition.getNamedType)(this.getInputType()); - let enumValue; - if ((0, _definition.isEnumType)(enumType)) { - enumValue = enumType.getValue(node.value); + /***/ "../../../node_modules/graphql/utilities/buildClientSchema.mjs": + /*!*********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/buildClientSchema.mjs ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.buildClientSchema = buildClientSchema; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _keyValMap = __webpack_require__( + /*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs" + ); + var _parser = __webpack_require__( + /*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _introspection = __webpack_require__( + /*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _scalars = __webpack_require__( + /*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + var _schema = __webpack_require__( + /*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs" + ); + var _valueFromAST = __webpack_require__( + /*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs" + ); + /** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ + + function buildClientSchema(introspection, options) { + ((0, _isObjectLike.isObjectLike)(introspection) && + (0, _isObjectLike.isObjectLike)(introspection.__schema)) || + (0, _devAssert.devAssert)( + false, + `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, + _inspect.inspect)(introspection)}.` + ); // Get the schema from the introspection result. + + const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + const typeMap = (0, _keyValMap.keyValMap)( + schemaIntrospection.types, + (typeIntrospection) => typeIntrospection.name, + (typeIntrospection) => buildType(typeIntrospection) + ); // Include standard types only if they are used. + + for (const stdType of [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, + ]) { + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + const queryType = schemaIntrospection.queryType + ? getObjectType(schemaIntrospection.queryType) + : null; + const mutationType = schemaIntrospection.mutationType + ? getObjectType(schemaIntrospection.mutationType) + : null; + const subscriptionType = schemaIntrospection.subscriptionType + ? getObjectType(schemaIntrospection.subscriptionType) + : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + const directives = schemaIntrospection.directives + ? schemaIntrospection.directives.map(buildDirective) + : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: Object.values(typeMap), + directives, + assumeValid: + options === null || options === void 0 + ? void 0 + : options.assumeValid, + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + const itemRef = typeRef.ofType; + if (!itemRef) { + throw new Error( + "Decorated type deeper than introspection query." + ); + } + return new _definition.GraphQLList(getType(itemRef)); + } + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + if (!nullableRef) { + throw new Error( + "Decorated type deeper than introspection query." + ); + } + const nullableType = getType(nullableRef); + return new _definition.GraphQLNonNull( + (0, _definition.assertNullableType)(nullableType) + ); + } + return getNamedType(typeRef); + } + function getNamedType(typeRef) { + const typeName = typeRef.name; + if (!typeName) { + throw new Error( + `Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.` + ); + } + const type = typeMap[typeName]; + if (!type) { + throw new Error( + `Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.` + ); + } + return type; + } + function getObjectType(typeRef) { + return (0, _definition.assertObjectType)(getNamedType(typeRef)); + } + function getInterfaceType(typeRef) { + return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + function buildType(type) { + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (type != null && type.name != null && type.kind != null) { + // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.` + ); + } + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL, + }); + } + function buildImplementationsList(implementingIntrospection) { + // TODO: Temporary workaround until GraphQL ecosystem will fully support + // 'interfaces' on interface types. + if ( + implementingIntrospection.interfaces === null && + implementingIntrospection.kind === + _introspection.TypeKind.INTERFACE + ) { + return []; + } + if (!implementingIntrospection.interfaces) { + const implementingIntrospectionStr = (0, _inspect.inspect)( + implementingIntrospection + ); + throw new Error( + `Introspection result missing interfaces: ${implementingIntrospectionStr}.` + ); + } + return implementingIntrospection.interfaces.map(getInterfaceType); + } + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => + buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + const unionIntrospectionStr = (0, _inspect.inspect)( + unionIntrospection + ); + throw new Error( + `Introspection result missing possibleTypes: ${unionIntrospectionStr}.` + ); + } + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType), + }); + } + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + const enumIntrospectionStr = (0, _inspect.inspect)( + enumIntrospection + ); + throw new Error( + `Introspection result missing enumValues: ${enumIntrospectionStr}.` + ); + } + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.keyValMap)( + enumIntrospection.enumValues, + (valueIntrospection) => valueIntrospection.name, + (valueIntrospection) => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason, + }) + ), + }); + } + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + const inputObjectIntrospectionStr = (0, _inspect.inspect)( + inputObjectIntrospection + ); + throw new Error( + `Introspection result missing inputFields: ${inputObjectIntrospectionStr}.` + ); + } + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => + buildInputValueDefMap(inputObjectIntrospection.inputFields), + }); + } + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error( + `Introspection result missing fields: ${(0, _inspect.inspect)( + typeIntrospection + )}.` + ); + } + return (0, _keyValMap.keyValMap)( + typeIntrospection.fields, + (fieldIntrospection) => fieldIntrospection.name, + buildField + ); + } + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); + if (!(0, _definition.isOutputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Introspection must provide output type for fields, but received: ${typeStr}.` + ); + } + if (!fieldIntrospection.args) { + const fieldIntrospectionStr = (0, _inspect.inspect)( + fieldIntrospection + ); + throw new Error( + `Introspection result missing field args: ${fieldIntrospectionStr}.` + ); + } + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args), + }; + } + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.keyValMap)( + inputValueIntrospections, + (inputValue) => inputValue.name, + buildInputValue + ); + } + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); + if (!(0, _definition.isInputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Introspection must provide input type for arguments, but received: ${typeStr}.` + ); + } + const defaultValue = + inputValueIntrospection.defaultValue != null + ? (0, _valueFromAST.valueFromAST)( + (0, _parser.parseValue)( + inputValueIntrospection.defaultValue + ), + type + ) + : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason, + }; + } + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + const directiveIntrospectionStr = (0, _inspect.inspect)( + directiveIntrospection + ); + throw new Error( + `Introspection result missing directive args: ${directiveIntrospectionStr}.` + ); + } + if (!directiveIntrospection.locations) { + const directiveIntrospectionStr = (0, _inspect.inspect)( + directiveIntrospection + ); + throw new Error( + `Introspection result missing directive locations: ${directiveIntrospectionStr}.` + ); + } + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args), + }); } - this._enumValue = enumValue; - break; } - default: // Ignore other nodes - } - } - leave(node) { - switch (node.kind) { - case _kinds.Kind.SELECTION_SET: - this._parentTypeStack.pop(); - break; - case _kinds.Kind.FIELD: - this._fieldDefStack.pop(); - this._typeStack.pop(); - break; - case _kinds.Kind.DIRECTIVE: - this._directive = null; - break; - case _kinds.Kind.OPERATION_DEFINITION: - case _kinds.Kind.INLINE_FRAGMENT: - case _kinds.Kind.FRAGMENT_DEFINITION: - this._typeStack.pop(); - break; - case _kinds.Kind.VARIABLE_DEFINITION: - this._inputTypeStack.pop(); - break; - case _kinds.Kind.ARGUMENT: - this._argument = null; - this._defaultValueStack.pop(); - this._inputTypeStack.pop(); - break; - case _kinds.Kind.LIST: - case _kinds.Kind.OBJECT_FIELD: - this._defaultValueStack.pop(); - this._inputTypeStack.pop(); - break; - case _kinds.Kind.ENUM: - this._enumValue = null; - break; - default: // Ignore other nodes - } - } -} - -/** - * Not exactly the same as the executor's definition of getFieldDef, in this - * statically evaluated environment we do not always have an Object type, - * and need to handle Interface and Union types. - */ -exports.TypeInfo = TypeInfo; -function getFieldDef(schema, parentType, fieldNode) { - const name = fieldNode.name.value; - if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.SchemaMetaFieldDef; - } - if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.TypeMetaFieldDef; - } - if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) { - return _introspection.TypeNameMetaFieldDef; - } - if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { - return parentType.getFields()[name]; - } -} -/** - * Creates a new visitor instance which maintains a provided TypeInfo instance - * along with visiting visitor. - */ - -function visitWithTypeInfo(typeInfo, visitor) { - return { - enter(...args) { - const node = args[0]; - typeInfo.enter(node); - const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; - if (fn) { - const result = fn.apply(visitor, args); - if (result !== undefined) { - typeInfo.leave(node); - if ((0, _ast.isNode)(result)) { - typeInfo.enter(result); - } - } - return result; - } - }, - leave(...args) { - const node = args[0]; - const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; - let result; - if (fn) { - result = fn.apply(visitor, args); - } - typeInfo.leave(node); - return result; - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/assertValidName.mjs": -/*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/assertValidName.mjs ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "../../../node_modules/graphql/utilities/coerceInputValue.mjs": + /*!********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/coerceInputValue.mjs ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.coerceInputValue = coerceInputValue; + var _didYouMean = __webpack_require__( + /*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _isIterableObject = __webpack_require__( + /*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs" + ); + var _isObjectLike = __webpack_require__( + /*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs" + ); + var _Path = __webpack_require__( + /*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs" + ); + var _printPathArray = __webpack_require__( + /*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Coerces a JavaScript value given a GraphQL Input Type. + */ + function coerceInputValue(inputValue, type, onError = defaultOnError) { + return coerceInputValueImpl(inputValue, type, onError, undefined); + } + function defaultOnError(path, invalidValue, error) { + let errorPrefix = + "Invalid value " + (0, _inspect.inspect)(invalidValue); + if (path.length > 0) { + errorPrefix += ` at "value${(0, _printPathArray.printPathArray)( + path + )}"`; + } + error.message = errorPrefix + ": " + error.message; + throw error; + } + function coerceInputValueImpl(inputValue, type, onError, path) { + if ((0, _definition.isNonNullType)(type)) { + if (inputValue != null) { + return coerceInputValueImpl( + inputValue, + type.ofType, + onError, + path + ); + } + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected non-nullable type "${(0, _inspect.inspect)( + type + )}" not to be null.` + ) + ); + return; + } + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if ((0, _isIterableObject.isIterableObject)(inputValue)) { + return Array.from(inputValue, (itemValue, index) => { + const itemPath = (0, _Path.addPath)(path, index, undefined); + return coerceInputValueImpl( + itemValue, + itemType, + onError, + itemPath + ); + }); + } // Lists accept a non-list value as a list of one. + + return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(inputValue)) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected type "${type.name}" to be an object.` + ) + ); + return; + } + const coercedValue = {}; + const fieldDefs = type.getFields(); + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + const typeStr = (0, _inspect.inspect)(field.type); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Field "${field.name}" of required type "${typeStr}" was not provided.` + ) + ); + } + continue; + } + coercedValue[field.name] = coerceInputValueImpl( + fieldValue, + field.type, + onError, + (0, _Path.addPath)(path, field.name, type.name) + ); + } // Ensure every provided field is defined. + + for (const fieldName of Object.keys(inputValue)) { + if (!fieldDefs[fieldName]) { + const suggestions = (0, _suggestionList.suggestionList)( + fieldName, + Object.keys(type.getFields()) + ); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Field "${fieldName}" is not defined by type "${type.name}".` + + (0, _didYouMean.didYouMean)(suggestions) + ) + ); + } + } + return coercedValue; + } + if ((0, _definition.isLeafType)(type)) { + let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), + // which can throw to indicate failure. If it throws, maintain a reference + // to the original error. + try { + parseResult = type.parseValue(inputValue); + } catch (error) { + if (error instanceof _GraphQLError.GraphQLError) { + onError((0, _Path.pathToArray)(path), inputValue, error); + } else { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected type "${type.name}". ` + error.message, + { + originalError: error, + } + ) + ); + } + return; + } + if (parseResult === undefined) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError(`Expected type "${type.name}".`) + ); + } + return parseResult; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + false || + (0, _invariant.invariant)( + false, + "Unexpected input type: " + (0, _inspect.inspect)(type) + ); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.assertValidName = assertValidName; -exports.isValidNameError = isValidNameError; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _assertName = __webpack_require__(/*! ../type/assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); -/* c8 ignore start */ + /***/ + }, -/** - * Upholds the spec rules about naming. - * @deprecated Please use `assertName` instead. Will be removed in v17 - */ + /***/ "../../../node_modules/graphql/utilities/concatAST.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/concatAST.mjs ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.concatAST = concatAST; + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + /** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ -function assertValidName(name) { - const error = isValidNameError(name); - if (error) { - throw error; - } - return name; -} -/** - * Returns an Error if a name is invalid. - * @deprecated Please use `assertName` instead. Will be removed in v17 - */ - -function isValidNameError(name) { - typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); - if (name.startsWith('__')) { - return new _GraphQLError.GraphQLError(`Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`); - } - try { - (0, _assertName.assertName)(name); - } catch (error) { - return error; - } -} -/* c8 ignore stop */ + function concatAST(documents) { + const definitions = []; + for (const doc of documents) { + definitions.push(...doc.definitions); + } + return { + kind: _kinds.Kind.DOCUMENT, + definitions, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/astFromValue.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/astFromValue.mjs ***! + /***/ "../../../node_modules/graphql/utilities/extendSchema.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/extendSchema.mjs ***! \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.astFromValue = astFromValue; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -/** - * Produces a GraphQL Value AST given a JavaScript object. - * Function will match JavaScript/JSON values to GraphQL AST schema format - * by using suggested GraphQLInputType. For example: - * - * astFromValue("value", GraphQLString) - * - * A GraphQL type must be provided, which will be used to interpret different - * JavaScript values. - * - * | JSON Value | GraphQL Value | - * | ------------- | -------------------- | - * | Object | Input Object | - * | Array | List | - * | Boolean | Boolean | - * | String | String / Enum Value | - * | Number | Int / Float | - * | Unknown | Enum Value | - * | null | NullValue | - * - */ - -function astFromValue(value, type) { - if ((0, _definition.isNonNullType)(type)) { - const astValue = astFromValue(value, type.ofType); - if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === _kinds.Kind.NULL) { - return null; - } - return astValue; - } // only explicit null, not undefined, NaN - - if (value === null) { - return { - kind: _kinds.Kind.NULL - }; - } // undefined - - if (value === undefined) { - return null; - } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but - // the value is not an array, convert the value using the list's item type. - - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; - if ((0, _isIterableObject.isIterableObject)(value)) { - const valuesNodes = []; - for (const item of value) { - const itemNode = astFromValue(item, itemType); - if (itemNode != null) { - valuesNodes.push(itemNode); - } - } - return { - kind: _kinds.Kind.LIST, - values: valuesNodes - }; - } - return astFromValue(value, itemType); - } // Populate the fields of the input object by creating ASTs from each value - // in the JavaScript object according to the fields in the input type. - - if ((0, _definition.isInputObjectType)(type)) { - if (!(0, _isObjectLike.isObjectLike)(value)) { - return null; - } - const fieldNodes = []; - for (const field of Object.values(type.getFields())) { - const fieldValue = astFromValue(value[field.name], field.type); - if (fieldValue) { - fieldNodes.push({ - kind: _kinds.Kind.OBJECT_FIELD, - name: { - kind: _kinds.Kind.NAME, - value: field.name - }, - value: fieldValue + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - } - return { - kind: _kinds.Kind.OBJECT, - fields: fieldNodes - }; - } - if ((0, _definition.isLeafType)(type)) { - // Since value is an internally represented value, it must be serialized - // to an externally represented value before converting into an AST. - const serialized = type.serialize(value); - if (serialized == null) { - return null; - } // Others serialize based on their corresponding JavaScript scalar types. - - if (typeof serialized === 'boolean') { - return { - kind: _kinds.Kind.BOOLEAN, - value: serialized - }; - } // JavaScript numbers can be Int or Float values. - - if (typeof serialized === 'number' && Number.isFinite(serialized)) { - const stringNum = String(serialized); - return integerStringRegExp.test(stringNum) ? { - kind: _kinds.Kind.INT, - value: stringNum - } : { - kind: _kinds.Kind.FLOAT, - value: stringNum - }; - } - if (typeof serialized === 'string') { - // Enum types use Enum literals. - if ((0, _definition.isEnumType)(type)) { - return { - kind: _kinds.Kind.ENUM, - value: serialized - }; - } // ID types can use Int literals. - - if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { - return { - kind: _kinds.Kind.INT, - value: serialized - }; - } - return { - kind: _kinds.Kind.STRING, - value: serialized - }; - } - throw new TypeError(`Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); -} -/** - * IntValue: - * - NegativeSign? 0 - * - NegativeSign? NonZeroDigit ( Digit+ )? - */ - -const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; - -/***/ }), - -/***/ "../../../node_modules/graphql/utilities/buildASTSchema.mjs": -/*!******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/buildASTSchema.mjs ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.buildASTSchema = buildASTSchema; -exports.buildSchema = buildSchema; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); -var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); -var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); -var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); -/** - * This takes the ast of a schema document produced by the parse function in - * src/language/parser.js. - * - * If no schema definition is provided, then it will look for types named Query, - * Mutation and Subscription. - * - * Given that AST it constructs a GraphQLSchema. The resulting schema - * has no resolve methods, so execution will use default resolvers. - */ -function buildASTSchema(documentAST, options) { - documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); - if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { - (0, _validate.assertValidSDL)(documentAST); - } - const emptySchemaConfig = { - description: undefined, - types: [], - directives: [], - extensions: Object.create(null), - extensionASTNodes: [], - assumeValid: false - }; - const config = (0, _extendSchema.extendSchemaImpl)(emptySchemaConfig, documentAST, options); - if (config.astNode == null) { - for (const type of config.types) { - switch (type.name) { - // Note: While this could make early assertions to get the correctly - // typed values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - case 'Query': - // @ts-expect-error validated in `validateSchema` - config.query = type; - break; - case 'Mutation': - // @ts-expect-error validated in `validateSchema` - config.mutation = type; - break; - case 'Subscription': - // @ts-expect-error validated in `validateSchema` - config.subscription = type; - break; - } - } - } - const directives = [...config.directives, - // If specified directives were not explicitly declared, add them. - ..._directives.specifiedDirectives.filter(stdDirective => config.directives.every(directive => directive.name !== stdDirective.name))]; - return new _schema.GraphQLSchema({ - ...config, - directives - }); -} -/** - * A helper function to build a GraphQLSchema directly from a source - * document. - */ - -function buildSchema(source, options) { - const document = (0, _parser.parse)(source, { - noLocation: options === null || options === void 0 ? void 0 : options.noLocation, - allowLegacyFragmentVariables: options === null || options === void 0 ? void 0 : options.allowLegacyFragmentVariables - }); - return buildASTSchema(document, { - assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL, - assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid - }); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/utilities/buildClientSchema.mjs": -/*!*********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/buildClientSchema.mjs ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.buildClientSchema = buildClientSchema; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); -var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); -var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); -/** - * Build a GraphQLSchema for use by client tools. - * - * Given the result of a client running the introspection query, creates and - * returns a GraphQLSchema instance which can be then used with all graphql-js - * tools, but cannot be used to execute a query, as introspection does not - * represent the "resolver", "parse" or "serialize" functions or any other - * server-internal mechanisms. - * - * This function expects a complete introspection result. Don't forget to check - * the "errors" field of a server response before calling this function. - */ - -function buildClientSchema(introspection, options) { - (0, _isObjectLike.isObjectLike)(introspection) && (0, _isObjectLike.isObjectLike)(introspection.__schema) || (0, _devAssert.devAssert)(false, `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, _inspect.inspect)(introspection)}.`); // Get the schema from the introspection result. - - const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. - - const typeMap = (0, _keyValMap.keyValMap)(schemaIntrospection.types, typeIntrospection => typeIntrospection.name, typeIntrospection => buildType(typeIntrospection)); // Include standard types only if they are used. - - for (const stdType of [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes]) { - if (typeMap[stdType.name]) { - typeMap[stdType.name] = stdType; - } - } // Get the root Query, Mutation, and Subscription types. - - const queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; - const mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; - const subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if - // directives were not queried for. - - const directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. - - return new _schema.GraphQLSchema({ - description: schemaIntrospection.description, - query: queryType, - mutation: mutationType, - subscription: subscriptionType, - types: Object.values(typeMap), - directives, - assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid - }); // Given a type reference in introspection, return the GraphQLType instance. - // preferring cached instances before building new instances. - - function getType(typeRef) { - if (typeRef.kind === _introspection.TypeKind.LIST) { - const itemRef = typeRef.ofType; - if (!itemRef) { - throw new Error('Decorated type deeper than introspection query.'); - } - return new _definition.GraphQLList(getType(itemRef)); - } - if (typeRef.kind === _introspection.TypeKind.NON_NULL) { - const nullableRef = typeRef.ofType; - if (!nullableRef) { - throw new Error('Decorated type deeper than introspection query.'); - } - const nullableType = getType(nullableRef); - return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType)); - } - return getNamedType(typeRef); - } - function getNamedType(typeRef) { - const typeName = typeRef.name; - if (!typeName) { - throw new Error(`Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`); - } - const type = typeMap[typeName]; - if (!type) { - throw new Error(`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`); - } - return type; - } - function getObjectType(typeRef) { - return (0, _definition.assertObjectType)(getNamedType(typeRef)); - } - function getInterfaceType(typeRef) { - return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); - } // Given a type's introspection result, construct the correct - // GraphQLType instance. - - function buildType(type) { - // eslint-disable-next-line @typescript-eslint/prefer-optional-chain - if (type != null && type.name != null && type.kind != null) { - // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 - // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check - switch (type.kind) { - case _introspection.TypeKind.SCALAR: - return buildScalarDef(type); - case _introspection.TypeKind.OBJECT: - return buildObjectDef(type); - case _introspection.TypeKind.INTERFACE: - return buildInterfaceDef(type); - case _introspection.TypeKind.UNION: - return buildUnionDef(type); - case _introspection.TypeKind.ENUM: - return buildEnumDef(type); - case _introspection.TypeKind.INPUT_OBJECT: - return buildInputObjectDef(type); - } - } - const typeStr = (0, _inspect.inspect)(type); - throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`); - } - function buildScalarDef(scalarIntrospection) { - return new _definition.GraphQLScalarType({ - name: scalarIntrospection.name, - description: scalarIntrospection.description, - specifiedByURL: scalarIntrospection.specifiedByURL - }); - } - function buildImplementationsList(implementingIntrospection) { - // TODO: Temporary workaround until GraphQL ecosystem will fully support - // 'interfaces' on interface types. - if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === _introspection.TypeKind.INTERFACE) { - return []; - } - if (!implementingIntrospection.interfaces) { - const implementingIntrospectionStr = (0, _inspect.inspect)(implementingIntrospection); - throw new Error(`Introspection result missing interfaces: ${implementingIntrospectionStr}.`); - } - return implementingIntrospection.interfaces.map(getInterfaceType); - } - function buildObjectDef(objectIntrospection) { - return new _definition.GraphQLObjectType({ - name: objectIntrospection.name, - description: objectIntrospection.description, - interfaces: () => buildImplementationsList(objectIntrospection), - fields: () => buildFieldDefMap(objectIntrospection) - }); - } - function buildInterfaceDef(interfaceIntrospection) { - return new _definition.GraphQLInterfaceType({ - name: interfaceIntrospection.name, - description: interfaceIntrospection.description, - interfaces: () => buildImplementationsList(interfaceIntrospection), - fields: () => buildFieldDefMap(interfaceIntrospection) - }); - } - function buildUnionDef(unionIntrospection) { - if (!unionIntrospection.possibleTypes) { - const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); - throw new Error(`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`); - } - return new _definition.GraphQLUnionType({ - name: unionIntrospection.name, - description: unionIntrospection.description, - types: () => unionIntrospection.possibleTypes.map(getObjectType) - }); - } - function buildEnumDef(enumIntrospection) { - if (!enumIntrospection.enumValues) { - const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); - throw new Error(`Introspection result missing enumValues: ${enumIntrospectionStr}.`); - } - return new _definition.GraphQLEnumType({ - name: enumIntrospection.name, - description: enumIntrospection.description, - values: (0, _keyValMap.keyValMap)(enumIntrospection.enumValues, valueIntrospection => valueIntrospection.name, valueIntrospection => ({ - description: valueIntrospection.description, - deprecationReason: valueIntrospection.deprecationReason - })) - }); - } - function buildInputObjectDef(inputObjectIntrospection) { - if (!inputObjectIntrospection.inputFields) { - const inputObjectIntrospectionStr = (0, _inspect.inspect)(inputObjectIntrospection); - throw new Error(`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`); - } - return new _definition.GraphQLInputObjectType({ - name: inputObjectIntrospection.name, - description: inputObjectIntrospection.description, - fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields) - }); - } - function buildFieldDefMap(typeIntrospection) { - if (!typeIntrospection.fields) { - throw new Error(`Introspection result missing fields: ${(0, _inspect.inspect)(typeIntrospection)}.`); - } - return (0, _keyValMap.keyValMap)(typeIntrospection.fields, fieldIntrospection => fieldIntrospection.name, buildField); - } - function buildField(fieldIntrospection) { - const type = getType(fieldIntrospection.type); - if (!(0, _definition.isOutputType)(type)) { - const typeStr = (0, _inspect.inspect)(type); - throw new Error(`Introspection must provide output type for fields, but received: ${typeStr}.`); - } - if (!fieldIntrospection.args) { - const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); - throw new Error(`Introspection result missing field args: ${fieldIntrospectionStr}.`); - } - return { - description: fieldIntrospection.description, - deprecationReason: fieldIntrospection.deprecationReason, - type, - args: buildInputValueDefMap(fieldIntrospection.args) - }; - } - function buildInputValueDefMap(inputValueIntrospections) { - return (0, _keyValMap.keyValMap)(inputValueIntrospections, inputValue => inputValue.name, buildInputValue); - } - function buildInputValue(inputValueIntrospection) { - const type = getType(inputValueIntrospection.type); - if (!(0, _definition.isInputType)(type)) { - const typeStr = (0, _inspect.inspect)(type); - throw new Error(`Introspection must provide input type for arguments, but received: ${typeStr}.`); - } - const defaultValue = inputValueIntrospection.defaultValue != null ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; - return { - description: inputValueIntrospection.description, - type, - defaultValue, - deprecationReason: inputValueIntrospection.deprecationReason - }; - } - function buildDirective(directiveIntrospection) { - if (!directiveIntrospection.args) { - const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); - throw new Error(`Introspection result missing directive args: ${directiveIntrospectionStr}.`); - } - if (!directiveIntrospection.locations) { - const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); - throw new Error(`Introspection result missing directive locations: ${directiveIntrospectionStr}.`); - } - return new _directives.GraphQLDirective({ - name: directiveIntrospection.name, - description: directiveIntrospection.description, - isRepeatable: directiveIntrospection.isRepeatable, - locations: directiveIntrospection.locations.slice(), - args: buildInputValueDefMap(directiveIntrospection.args) - }); - } -} - -/***/ }), - -/***/ "../../../node_modules/graphql/utilities/coerceInputValue.mjs": -/*!********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/coerceInputValue.mjs ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.coerceInputValue = coerceInputValue; -var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); -var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); -var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); -var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); -var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Coerces a JavaScript value given a GraphQL Input Type. - */ -function coerceInputValue(inputValue, type, onError = defaultOnError) { - return coerceInputValueImpl(inputValue, type, onError, undefined); -} -function defaultOnError(path, invalidValue, error) { - let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); - if (path.length > 0) { - errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; - } - error.message = errorPrefix + ': ' + error.message; - throw error; -} -function coerceInputValueImpl(inputValue, type, onError, path) { - if ((0, _definition.isNonNullType)(type)) { - if (inputValue != null) { - return coerceInputValueImpl(inputValue, type.ofType, onError, path); - } - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected non-nullable type "${(0, _inspect.inspect)(type)}" not to be null.`)); - return; - } - if (inputValue == null) { - // Explicitly return the value null. - return null; - } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; - if ((0, _isIterableObject.isIterableObject)(inputValue)) { - return Array.from(inputValue, (itemValue, index) => { - const itemPath = (0, _Path.addPath)(path, index, undefined); - return coerceInputValueImpl(itemValue, itemType, onError, itemPath); - }); - } // Lists accept a non-list value as a list of one. - - return [coerceInputValueImpl(inputValue, itemType, onError, path)]; - } - if ((0, _definition.isInputObjectType)(type)) { - if (!(0, _isObjectLike.isObjectLike)(inputValue)) { - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}" to be an object.`)); - return; - } - const coercedValue = {}; - const fieldDefs = type.getFields(); - for (const field of Object.values(fieldDefs)) { - const fieldValue = inputValue[field.name]; - if (fieldValue === undefined) { - if (field.defaultValue !== undefined) { - coercedValue[field.name] = field.defaultValue; - } else if ((0, _definition.isNonNullType)(field.type)) { - const typeStr = (0, _inspect.inspect)(field.type); - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${field.name}" of required type "${typeStr}" was not provided.`)); - } - continue; - } - coercedValue[field.name] = coerceInputValueImpl(fieldValue, field.type, onError, (0, _Path.addPath)(path, field.name, type.name)); - } // Ensure every provided field is defined. + exports.extendSchema = extendSchema; + exports.extendSchemaImpl = extendSchemaImpl; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _mapValue = __webpack_require__( + /*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _predicates = __webpack_require__( + /*! ../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _introspection = __webpack_require__( + /*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _scalars = __webpack_require__( + /*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + var _schema = __webpack_require__( + /*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs" + ); + var _validate = __webpack_require__( + /*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs" + ); + var _values = __webpack_require__( + /*! ../execution/values.mjs */ "../../../node_modules/graphql/execution/values.mjs" + ); + var _valueFromAST = __webpack_require__( + /*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs" + ); + /** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + */ + function extendSchema(schema, documentAST, options) { + (0, _schema.assertSchema)(schema); + (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || + (0, _devAssert.devAssert)( + false, + "Must provide valid Document AST." + ); + if ( + (options === null || options === void 0 + ? void 0 + : options.assumeValid) !== true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); + } + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl( + schemaConfig, + documentAST, + options + ); + return schemaConfig === extendedConfig + ? schema + : new _schema.GraphQLSchema(extendedConfig); + } + /** + * @internal + */ - for (const fieldName of Object.keys(inputValue)) { - if (!fieldDefs[fieldName]) { - const suggestions = (0, _suggestionList.suggestionList)(fieldName, Object.keys(type.getFields())); - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${fieldName}" is not defined by type "${type.name}".` + (0, _didYouMean.didYouMean)(suggestions))); - } - } - return coercedValue; - } - if ((0, _definition.isLeafType)(type)) { - let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), - // which can throw to indicate failure. If it throws, maintain a reference - // to the original error. - - try { - parseResult = type.parseValue(inputValue); - } catch (error) { - if (error instanceof _GraphQLError.GraphQLError) { - onError((0, _Path.pathToArray)(path), inputValue, error); - } else { - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}". ` + error.message, { - originalError: error - })); - } - return; - } - if (parseResult === undefined) { - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}".`)); - } - return parseResult; - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. + function extendSchemaImpl(schemaConfig, documentAST, options) { + var _schemaDef, + _schemaDef$descriptio, + _schemaDef2, + _options$assumeValid; + + // Collect the type definitions and extensions found in the document. + const typeDefs = []; + const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + const directiveDefs = []; + let schemaDef; // Schema extensions are collected which may add additional operation types. + + const schemaExtensions = []; + for (const def of documentAST.definitions) { + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + typeDefs.push(def); + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + const extendedTypeName = def.name.value; + const existingTypeExtensions = + typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions + ? existingTypeExtensions.concat([def]) + : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + if ( + Object.keys(typeExtensionsMap).length === 0 && + typeDefs.length === 0 && + directiveDefs.length === 0 && + schemaExtensions.length === 0 && + schemaDef == null + ) { + return schemaConfig; + } + const typeMap = Object.create(null); + for (const existingType of schemaConfig.types) { + typeMap[existingType.name] = extendNamedType(existingType); + } + for (const typeNode of typeDefs) { + var _stdTypeMap$name; + const name = typeNode.name.value; + typeMap[name] = + (_stdTypeMap$name = stdTypeMap[name]) !== null && + _stdTypeMap$name !== void 0 + ? _stdTypeMap$name + : buildType(typeNode); + } + const operationTypes = { + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: + schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: + schemaConfig.subscription && + replaceNamedType(schemaConfig.subscription), + // Then, incorporate schema definition and all schema extensions. + ...(schemaDef && getOperationTypes([schemaDef])), + ...getOperationTypes(schemaExtensions), + }; // Then produce and return a Schema config with these types. - false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); -} + return { + description: + (_schemaDef = schemaDef) === null || _schemaDef === void 0 + ? void 0 + : (_schemaDef$descriptio = _schemaDef.description) === null || + _schemaDef$descriptio === void 0 + ? void 0 + : _schemaDef$descriptio.value, + ...operationTypes, + types: Object.values(typeMap), + directives: [ + ...schemaConfig.directives.map(replaceDirective), + ...directiveDefs.map(buildDirective), + ], + extensions: Object.create(null), + astNode: + (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 + ? _schemaDef2 + : schemaConfig.astNode, + extensionASTNodes: + schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: + (_options$assumeValid = + options === null || options === void 0 + ? void 0 + : options.assumeValid) !== null && + _options$assumeValid !== void 0 + ? _options$assumeValid + : false, + }; // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } + if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME + + return replaceNamedType(type); + } + function replaceNamedType(type) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return typeMap[type.name]; + } + function replaceDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + args: (0, _mapValue.mapValue)(config.args, extendArg), + }); + } + function extendNamedType(type) { + if ( + (0, _introspection.isIntrospectionType)(type) || + (0, _scalars.isSpecifiedScalarType)(type) + ) { + // Builtin types are not extended. + return type; + } + if ((0, _definition.isScalarType)(type)) { + return extendScalarType(type); + } + if ((0, _definition.isObjectType)(type)) { + return extendObjectType(type); + } + if ((0, _definition.isInterfaceType)(type)) { + return extendInterfaceType(type); + } + if ((0, _definition.isUnionType)(type)) { + return extendUnionType(type); + } + if ((0, _definition.isEnumType)(type)) { + return extendEnumType(type); + } + if ((0, _definition.isInputObjectType)(type)) { + return extendInputObjectType(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible type definition nodes have been considered. + + false || + (0, _invariant.invariant)( + false, + "Unexpected type: " + (0, _inspect.inspect)(type) + ); + } + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== + null && _typeExtensionsMap$co !== void 0 + ? _typeExtensionsMap$co + : []; + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, (field) => ({ + ...field, + type: replaceType(field.type), + })), + ...buildInputFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + function extendEnumType(type) { + var _typeExtensionsMap$ty; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && + _typeExtensionsMap$ty !== void 0 + ? _typeExtensionsMap$ty + : []; + return new _definition.GraphQLEnumType({ + ...config, + values: { + ...config.values, + ...buildEnumValueMap(extensions), + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + function extendScalarType(type) { + var _typeExtensionsMap$co2; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== + null && _typeExtensionsMap$co2 !== void 0 + ? _typeExtensionsMap$co2 + : []; + let specifiedByURL = config.specifiedByURL; + for (const extensionNode of extensions) { + var _getSpecifiedByURL; + specifiedByURL = + (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== + null && _getSpecifiedByURL !== void 0 + ? _getSpecifiedByURL + : specifiedByURL; + } + return new _definition.GraphQLScalarType({ + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + function extendObjectType(type) { + var _typeExtensionsMap$co3; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== + null && _typeExtensionsMap$co3 !== void 0 + ? _typeExtensionsMap$co3 + : []; + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== + null && _typeExtensionsMap$co4 !== void 0 + ? _typeExtensionsMap$co4 + : []; + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + function extendUnionType(type) { + var _typeExtensionsMap$co5; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== + null && _typeExtensionsMap$co5 !== void 0 + ? _typeExtensionsMap$co5 + : []; + return new _definition.GraphQLUnionType({ + ...config, + types: () => [ + ...type.getTypes().map(replaceNamedType), + ...buildUnionTypes(extensions), + ], + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + function extendField(field) { + return { + ...field, + type: replaceType(field.type), + args: + field.args && (0, _mapValue.mapValue)(field.args, extendArg), + }; + } + function extendArg(arg) { + return { + ...arg, + type: replaceType(arg.type), + }; + } + function getOperationTypes(nodes) { + const opTypes = {}; + for (const node of nodes) { + var _node$operationTypes; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const operationTypesNodes = + /* c8 ignore next */ + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + for (const operationType of operationTypesNodes) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + opTypes[operationType.operation] = getNamedType( + operationType.type + ); + } + } + return opTypes; + } + function getNamedType(node) { + var _stdTypeMap$name2; + const name = node.name.value; + const type = + (_stdTypeMap$name2 = stdTypeMap[name]) !== null && + _stdTypeMap$name2 !== void 0 + ? _stdTypeMap$name2 + : typeMap[name]; + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); + } + return type; + } + function getWrappedType(node) { + if (node.kind === _kinds.Kind.LIST_TYPE) { + return new _definition.GraphQLList(getWrappedType(node.type)); + } + if (node.kind === _kinds.Kind.NON_NULL_TYPE) { + return new _definition.GraphQLNonNull(getWrappedType(node.type)); + } + return getNamedType(node); + } + function buildDirective(node) { + var _node$description; + return new _directives.GraphQLDirective({ + name: node.name.value, + description: + (_node$description = node.description) === null || + _node$description === void 0 + ? void 0 + : _node$description.value, + // @ts-expect-error + locations: node.locations.map(({ value }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node, + }); + } + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + for (const node of nodes) { + var _node$fields; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const nodeFields = + /* c8 ignore next */ + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + for (const field of nodeFields) { + var _field$description; + fieldConfigMap[field.name.value] = { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: getWrappedType(field.type), + description: + (_field$description = field.description) === null || + _field$description === void 0 + ? void 0 + : _field$description.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + return fieldConfigMap; + } + function buildArgumentMap(args) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const argsNodes = + /* c8 ignore next */ + args !== null && args !== void 0 ? args : []; + const argConfigMap = Object.create(null); + for (const arg of argsNodes) { + var _arg$description; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type, + description: + (_arg$description = arg.description) === null || + _arg$description === void 0 + ? void 0 + : _arg$description.value, + defaultValue: (0, _valueFromAST.valueFromAST)( + arg.defaultValue, + type + ), + deprecationReason: getDeprecationReason(arg), + astNode: arg, + }; + } + return argConfigMap; + } + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + for (const node of nodes) { + var _node$fields2; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fieldsNodes = + /* c8 ignore next */ + (_node$fields2 = node.fields) !== null && + _node$fields2 !== void 0 + ? _node$fields2 + : []; + for (const field of fieldsNodes) { + var _field$description2; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type, + description: + (_field$description2 = field.description) === null || + _field$description2 === void 0 + ? void 0 + : _field$description2.value, + defaultValue: (0, _valueFromAST.valueFromAST)( + field.defaultValue, + type + ), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + return inputFieldMap; + } + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); + for (const node of nodes) { + var _node$values; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const valuesNodes = + /* c8 ignore next */ + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + for (const value of valuesNodes) { + var _value$description; + enumValueMap[value.name.value] = { + description: + (_value$description = value.description) === null || + _value$description === void 0 + ? void 0 + : _value$description.value, + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } + } + return enumValueMap; + } + function buildInterfaces(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$interfaces$map, _node$interfaces; + return /* c8 ignore next */ (_node$interfaces$map = + (_node$interfaces = node.interfaces) === null || + _node$interfaces === void 0 + ? void 0 + : _node$interfaces.map(getNamedType)) !== null && + _node$interfaces$map !== void 0 + ? _node$interfaces$map + : []; + } + ); + } + function buildUnionTypes(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$types$map, _node$types; + return /* c8 ignore next */ (_node$types$map = + (_node$types = node.types) === null || _node$types === void 0 + ? void 0 + : _node$types.map(getNamedType)) !== null && + _node$types$map !== void 0 + ? _node$types$map + : []; + } + ); + } + function buildType(astNode) { + var _typeExtensionsMap$na; + const name = astNode.name.value; + const extensionASTNodes = + (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && + _typeExtensionsMap$na !== void 0 + ? _typeExtensionsMap$na + : []; + switch (astNode.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: { + var _astNode$description; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLObjectType({ + name, + description: + (_astNode$description = astNode.description) === null || + _astNode$description === void 0 + ? void 0 + : _astNode$description.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: { + var _astNode$description2; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInterfaceType({ + name, + description: + (_astNode$description2 = astNode.description) === null || + _astNode$description2 === void 0 + ? void 0 + : _astNode$description2.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + case _kinds.Kind.ENUM_TYPE_DEFINITION: { + var _astNode$description3; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLEnumType({ + name, + description: + (_astNode$description3 = astNode.description) === null || + _astNode$description3 === void 0 + ? void 0 + : _astNode$description3.value, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes, + }); + } + case _kinds.Kind.UNION_TYPE_DEFINITION: { + var _astNode$description4; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLUnionType({ + name, + description: + (_astNode$description4 = astNode.description) === null || + _astNode$description4 === void 0 + ? void 0 + : _astNode$description4.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes, + }); + } + case _kinds.Kind.SCALAR_TYPE_DEFINITION: { + var _astNode$description5; + return new _definition.GraphQLScalarType({ + name, + description: + (_astNode$description5 = astNode.description) === null || + _astNode$description5 === void 0 + ? void 0 + : _astNode$description5.value, + specifiedByURL: getSpecifiedByURL(astNode), + astNode, + extensionASTNodes, + }); + } + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: { + var _astNode$description6; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInputObjectType({ + name, + description: + (_astNode$description6 = astNode.description) === null || + _astNode$description6 === void 0 + ? void 0 + : _astNode$description6.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + } + } + } + const stdTypeMap = (0, _keyMap.keyMap)( + [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, + ], + (type) => type.name + ); + /** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ -/***/ }), + function getDeprecationReason(node) { + const deprecated = (0, _values.getDirectiveValues)( + _directives.GraphQLDeprecatedDirective, + node + ); // @ts-expect-error validated by `getDirectiveValues` -/***/ "../../../node_modules/graphql/utilities/concatAST.mjs": -/*!*************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/concatAST.mjs ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + return deprecated === null || deprecated === void 0 + ? void 0 + : deprecated.reason; + } + /** + * Given a scalar node, returns the string value for the specifiedByURL. + */ + function getSpecifiedByURL(node) { + const specifiedBy = (0, _values.getDirectiveValues)( + _directives.GraphQLSpecifiedByDirective, + node + ); // @ts-expect-error validated by `getDirectiveValues` + return specifiedBy === null || specifiedBy === void 0 + ? void 0 + : specifiedBy.url; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.concatAST = concatAST; -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -/** - * Provided a collection of ASTs, presumably each from different files, - * concatenate the ASTs together into batched AST, useful for validating many - * GraphQL source files which together represent one conceptual application. - */ + /***/ + }, -function concatAST(documents) { - const definitions = []; - for (const doc of documents) { - definitions.push(...doc.definitions); - } - return { - kind: _kinds.Kind.DOCUMENT, - definitions - }; -} + /***/ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs": + /*!***********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/findBreakingChanges.mjs ***! + \***********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.DangerousChangeType = exports.BreakingChangeType = void 0; + exports.findBreakingChanges = findBreakingChanges; + exports.findDangerousChanges = findDangerousChanges; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _printer = __webpack_require__( + /*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _scalars = __webpack_require__( + /*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + var _astFromValue = __webpack_require__( + /*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs" + ); + var _sortValueNode = __webpack_require__( + /*! ./sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs" + ); + var BreakingChangeType; + (function (BreakingChangeType) { + BreakingChangeType["TYPE_REMOVED"] = "TYPE_REMOVED"; + BreakingChangeType["TYPE_CHANGED_KIND"] = "TYPE_CHANGED_KIND"; + BreakingChangeType["TYPE_REMOVED_FROM_UNION"] = + "TYPE_REMOVED_FROM_UNION"; + BreakingChangeType["VALUE_REMOVED_FROM_ENUM"] = + "VALUE_REMOVED_FROM_ENUM"; + BreakingChangeType["REQUIRED_INPUT_FIELD_ADDED"] = + "REQUIRED_INPUT_FIELD_ADDED"; + BreakingChangeType["IMPLEMENTED_INTERFACE_REMOVED"] = + "IMPLEMENTED_INTERFACE_REMOVED"; + BreakingChangeType["FIELD_REMOVED"] = "FIELD_REMOVED"; + BreakingChangeType["FIELD_CHANGED_KIND"] = "FIELD_CHANGED_KIND"; + BreakingChangeType["REQUIRED_ARG_ADDED"] = "REQUIRED_ARG_ADDED"; + BreakingChangeType["ARG_REMOVED"] = "ARG_REMOVED"; + BreakingChangeType["ARG_CHANGED_KIND"] = "ARG_CHANGED_KIND"; + BreakingChangeType["DIRECTIVE_REMOVED"] = "DIRECTIVE_REMOVED"; + BreakingChangeType["DIRECTIVE_ARG_REMOVED"] = "DIRECTIVE_ARG_REMOVED"; + BreakingChangeType["REQUIRED_DIRECTIVE_ARG_ADDED"] = + "REQUIRED_DIRECTIVE_ARG_ADDED"; + BreakingChangeType["DIRECTIVE_REPEATABLE_REMOVED"] = + "DIRECTIVE_REPEATABLE_REMOVED"; + BreakingChangeType["DIRECTIVE_LOCATION_REMOVED"] = + "DIRECTIVE_LOCATION_REMOVED"; + })( + BreakingChangeType || + (exports.BreakingChangeType = BreakingChangeType = {}) + ); + var DangerousChangeType; + (function (DangerousChangeType) { + DangerousChangeType["VALUE_ADDED_TO_ENUM"] = "VALUE_ADDED_TO_ENUM"; + DangerousChangeType["TYPE_ADDED_TO_UNION"] = "TYPE_ADDED_TO_UNION"; + DangerousChangeType["OPTIONAL_INPUT_FIELD_ADDED"] = + "OPTIONAL_INPUT_FIELD_ADDED"; + DangerousChangeType["OPTIONAL_ARG_ADDED"] = "OPTIONAL_ARG_ADDED"; + DangerousChangeType["IMPLEMENTED_INTERFACE_ADDED"] = + "IMPLEMENTED_INTERFACE_ADDED"; + DangerousChangeType["ARG_DEFAULT_VALUE_CHANGE"] = + "ARG_DEFAULT_VALUE_CHANGE"; + })( + DangerousChangeType || + (exports.DangerousChangeType = DangerousChangeType = {}) + ); + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ + function findBreakingChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in BreakingChangeType + ); + } + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ -/***/ }), + function findDangerousChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in DangerousChangeType + ); + } + function findSchemaChanges(oldSchema, newSchema) { + return [ + ...findTypeChanges(oldSchema, newSchema), + ...findDirectiveChanges(oldSchema, newSchema), + ]; + } + function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff( + oldSchema.getDirectives(), + newSchema.getDirectives() + ); + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${oldDirective.name} was removed.`, + }); + } + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`, + }); + } + } + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${oldArg.name} was removed from ${oldDirective.name}.`, + }); + } + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective.name}.`, + }); + } + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.`, + }); + } + } + } + return schemaChanges; + } + function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff( + Object.values(oldSchema.getTypeMap()), + Object.values(newSchema.getTypeMap()) + ); + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: (0, _scalars.isSpecifiedScalarType)(oldType) + ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` + : `${oldType.name} was removed.`, + }); + } + for (const [oldType, newType] of typesDiff.persisted) { + if ( + (0, _definition.isEnumType)(oldType) && + (0, _definition.isEnumType)(newType) + ) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isUnionType)(oldType) && + (0, _definition.isUnionType)(newType) + ) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isInputObjectType)(oldType) && + (0, _definition.isInputObjectType)(newType) + ) { + schemaChanges.push( + ...findInputObjectTypeChanges(oldType, newType) + ); + } else if ( + (0, _definition.isObjectType)(oldType) && + (0, _definition.isObjectType)(newType) + ) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType) + ); + } else if ( + (0, _definition.isInterfaceType)(oldType) && + (0, _definition.isInterfaceType)(newType) + ) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType) + ); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: + `${oldType.name} changed from ` + + `${typeKindName(oldType)} to ${typeKindName(newType)}.`, + }); + } + } + return schemaChanges; + } + function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()) + ); + for (const newField of fieldsDiff.added) { + if ((0, _definition.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField.name} on input type ${oldType.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField.name} on input type ${oldType.name} was added.`, + }); + } + } + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldField.type, + newField.type + ); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + return schemaChanges; + } + function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff( + oldType.getTypes(), + newType.getTypes() + ); + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType.name} was added to union type ${oldType.name}.`, + }); + } + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`, + }); + } + return schemaChanges; + } + function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${newValue.name} was added to enum type ${oldType.name}.`, + }); + } + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${oldValue.name} was removed from enum type ${oldType.name}.`, + }); + } + return schemaChanges; + } + function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff( + oldType.getInterfaces(), + newType.getInterfaces() + ); + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`, + }); + } + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType.name} no longer implements interface ${oldInterface.name}.`, + }); + } + return schemaChanges; + } + function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()) + ); + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldType, oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField( + oldField.type, + newField.type + ); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + return schemaChanges; + } + function findArgChanges(oldType, oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`, + }); + } + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldArg.type, + newArg.type + ); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + + `${String(oldArg.type)} to ${String(newArg.type)}.`, + }); + } else if (oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`, + }); + } else { + // Since we looking only for client's observable changes we should + // compare default values in the same representation as they are + // represented inside introspection. + const oldValueStr = stringifyValue( + oldArg.defaultValue, + oldArg.type + ); + const newValueStr = stringifyValue( + newArg.defaultValue, + newArg.type + ); + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`, + }); + } + } + } + } + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } + } + return schemaChanges; + } + function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + ((0, _definition.isListType)(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType + )) || + // moving from nullable to non-null of the same underlying type is safe + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } + if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return ( + (0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType + ) + ); + } + return ( + // if they're both named types, see if their names are equivalent + ((0, _definition.isNamedType)(newType) && + oldType.name === newType.name) || + // moving from nullable to non-null of the same underlying type is safe + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } + function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return ( + (0, _definition.isListType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType + ) + ); + } + if ((0, _definition.isNonNullType)(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType + )) || + // moving from non-null to nullable of the same underlying type is safe + (!(0, _definition.isNonNullType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType + )) + ); + } // if they're both named types, see if their names are equivalent -/***/ "../../../node_modules/graphql/utilities/extendSchema.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/extendSchema.mjs ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.extendSchema = extendSchema; -exports.extendSchemaImpl = extendSchemaImpl; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _predicates = __webpack_require__(/*! ../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); -var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); -var _values = __webpack_require__(/*! ../execution/values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); -var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); -/** - * Produces a new schema given an existing schema and a document which may - * contain GraphQL type extensions and definitions. The original schema will - * remain unaltered. - * - * Because a schema represents a graph of references, a schema cannot be - * extended without effectively making an entire copy. We do not know until it's - * too late if subgraphs remain unchanged. - * - * This algorithm copies the provided schema, applying extensions while - * producing the copy. The original schema remains unaltered. - */ -function extendSchema(schema, documentAST, options) { - (0, _schema.assertSchema)(schema); - documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); - if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { - (0, _validate.assertValidSDLExtension)(documentAST, schema); - } - const schemaConfig = schema.toConfig(); - const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); - return schemaConfig === extendedConfig ? schema : new _schema.GraphQLSchema(extendedConfig); -} -/** - * @internal - */ - -function extendSchemaImpl(schemaConfig, documentAST, options) { - var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; - - // Collect the type definitions and extensions found in the document. - const typeDefs = []; - const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can - // have the same name. For example, a type named "skip". - - const directiveDefs = []; - let schemaDef; // Schema extensions are collected which may add additional operation types. - - const schemaExtensions = []; - for (const def of documentAST.definitions) { - if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { - schemaDef = def; - } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { - schemaExtensions.push(def); - } else if ((0, _predicates.isTypeDefinitionNode)(def)) { - typeDefs.push(def); - } else if ((0, _predicates.isTypeExtensionNode)(def)) { - const extendedTypeName = def.name.value; - const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; - typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; - } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - directiveDefs.push(def); - } - } // If this document contains no new types, extensions, or directives then - // return the same unmodified GraphQLSchema instance. + return ( + (0, _definition.isNamedType)(newType) && + oldType.name === newType.name + ); + } + function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return "a Scalar type"; + } + if ((0, _definition.isObjectType)(type)) { + return "an Object type"; + } + if ((0, _definition.isInterfaceType)(type)) { + return "an Interface type"; + } + if ((0, _definition.isUnionType)(type)) { + return "a Union type"; + } + if ((0, _definition.isEnumType)(type)) { + return "an Enum type"; + } + if ((0, _definition.isInputObjectType)(type)) { + return "an Input type"; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. - if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) { - return schemaConfig; - } - const typeMap = Object.create(null); - for (const existingType of schemaConfig.types) { - typeMap[existingType.name] = extendNamedType(existingType); - } - for (const typeNode of typeDefs) { - var _stdTypeMap$name; - const name = typeNode.name.value; - typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode); - } - const operationTypes = { - // Get the extended root operation types. - query: schemaConfig.query && replaceNamedType(schemaConfig.query), - mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), - subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), - // Then, incorporate schema definition and all schema extensions. - ...(schemaDef && getOperationTypes([schemaDef])), - ...getOperationTypes(schemaExtensions) - }; // Then produce and return a Schema config with these types. + false || + (0, _invariant.invariant)( + false, + "Unexpected type: " + (0, _inspect.inspect)(type) + ); + } + function stringifyValue(value, type) { + const ast = (0, _astFromValue.astFromValue)(value, type); + ast != null || (0, _invariant.invariant)(false); + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); + } + function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = (0, _keyMap.keyMap)(oldArray, ({ name }) => name); + const newMap = (0, _keyMap.keyMap)(newArray, ({ name }) => name); + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); + } + } + return { + added, + persisted, + removed, + }; + } - return { - description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value, - ...operationTypes, - types: Object.values(typeMap), - directives: [...schemaConfig.directives.map(replaceDirective), ...directiveDefs.map(buildDirective)], - extensions: Object.create(null), - astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode, - extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), - assumeValid: (_options$assumeValid = options === null || options === void 0 ? void 0 : options.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false - }; // Below are functions used for producing this schema that have closed over - // this scope and have access to the schema, cache, and newly defined types. - - function replaceType(type) { - if ((0, _definition.isListType)(type)) { - // @ts-expect-error - return new _definition.GraphQLList(replaceType(type.ofType)); - } - if ((0, _definition.isNonNullType)(type)) { - // @ts-expect-error - return new _definition.GraphQLNonNull(replaceType(type.ofType)); - } // @ts-expect-error FIXME + /***/ + }, - return replaceNamedType(type); - } - function replaceNamedType(type) { - // Note: While this could make early assertions to get the correctly - // typed values, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - return typeMap[type.name]; - } - function replaceDirective(directive) { - const config = directive.toConfig(); - return new _directives.GraphQLDirective({ - ...config, - args: (0, _mapValue.mapValue)(config.args, extendArg) - }); - } - function extendNamedType(type) { - if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) { - // Builtin types are not extended. - return type; - } - if ((0, _definition.isScalarType)(type)) { - return extendScalarType(type); - } - if ((0, _definition.isObjectType)(type)) { - return extendObjectType(type); - } - if ((0, _definition.isInterfaceType)(type)) { - return extendInterfaceType(type); - } - if ((0, _definition.isUnionType)(type)) { - return extendUnionType(type); - } - if ((0, _definition.isEnumType)(type)) { - return extendEnumType(type); - } - if ((0, _definition.isInputObjectType)(type)) { - return extendInputObjectType(type); + /***/ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs": + /*!*************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs ***! + \*************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getIntrospectionQuery = getIntrospectionQuery; + /** + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. + */ + function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + ...options, + }; + const descriptions = optionsWithDefault.descriptions + ? "description" + : ""; + const specifiedByUrl = optionsWithDefault.specifiedByUrl + ? "specifiedByURL" + : ""; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable + ? "isRepeatable" + : ""; + const schemaDescription = optionsWithDefault.schemaDescription + ? descriptions + : ""; + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ""; + } + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + ${descriptions} + ${directiveIsRepeatable} + locations + args${inputDeprecation("(includeDeprecated: true)")} { + ...InputValue + } + } + } } - /* c8 ignore next 3 */ - // Not reachable, all possible type definition nodes have been considered. - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } - function extendInputObjectType(type) { - var _typeExtensionsMap$co; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : []; - return new _definition.GraphQLInputObjectType({ - ...config, - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, field => ({ - ...field, - type: replaceType(field.type) - })), - ...buildInputFieldMap(extensions) - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendEnumType(type) { - var _typeExtensionsMap$ty; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : []; - return new _definition.GraphQLEnumType({ - ...config, - values: { - ...config.values, - ...buildEnumValueMap(extensions) - }, - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendScalarType(type) { - var _typeExtensionsMap$co2; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : []; - let specifiedByURL = config.specifiedByURL; - for (const extensionNode of extensions) { - var _getSpecifiedByURL; - specifiedByURL = (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && _getSpecifiedByURL !== void 0 ? _getSpecifiedByURL : specifiedByURL; - } - return new _definition.GraphQLScalarType({ - ...config, - specifiedByURL, - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendObjectType(type) { - var _typeExtensionsMap$co3; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : []; - return new _definition.GraphQLObjectType({ - ...config, - interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, extendField), - ...buildFieldMap(extensions) - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendInterfaceType(type) { - var _typeExtensionsMap$co4; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : []; - return new _definition.GraphQLInterfaceType({ - ...config, - interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, extendField), - ...buildFieldMap(extensions) - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendUnionType(type) { - var _typeExtensionsMap$co5; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : []; - return new _definition.GraphQLUnionType({ - ...config, - types: () => [...type.getTypes().map(replaceNamedType), ...buildUnionTypes(extensions)], - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendField(field) { - return { - ...field, - type: replaceType(field.type), - args: field.args && (0, _mapValue.mapValue)(field.args, extendArg) - }; - } - function extendArg(arg) { - return { - ...arg, - type: replaceType(arg.type) - }; - } - function getOperationTypes(nodes) { - const opTypes = {}; - for (const node of nodes) { - var _node$operationTypes; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const operationTypesNodes = /* c8 ignore next */ - (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; - for (const operationType of operationTypesNodes) { - // Note: While this could make early assertions to get the correctly - // typed values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - opTypes[operationType.operation] = getNamedType(operationType.type); + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation("(includeDeprecated: true)")} { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason } - } - return opTypes; - } - function getNamedType(node) { - var _stdTypeMap$name2; - const name = node.name.value; - const type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name]; - if (type === undefined) { - throw new Error(`Unknown type: "${name}".`); - } - return type; - } - function getWrappedType(node) { - if (node.kind === _kinds.Kind.LIST_TYPE) { - return new _definition.GraphQLList(getWrappedType(node.type)); - } - if (node.kind === _kinds.Kind.NON_NULL_TYPE) { - return new _definition.GraphQLNonNull(getWrappedType(node.type)); - } - return getNamedType(node); - } - function buildDirective(node) { - var _node$description; - return new _directives.GraphQLDirective({ - name: node.name.value, - description: (_node$description = node.description) === null || _node$description === void 0 ? void 0 : _node$description.value, - // @ts-expect-error - locations: node.locations.map(({ - value - }) => value), - isRepeatable: node.repeatable, - args: buildArgumentMap(node.arguments), - astNode: node - }); - } - function buildFieldMap(nodes) { - const fieldConfigMap = Object.create(null); - for (const node of nodes) { - var _node$fields; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const nodeFields = /* c8 ignore next */ - (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; - for (const field of nodeFields) { - var _field$description; - fieldConfigMap[field.name.value] = { - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - type: getWrappedType(field.type), - description: (_field$description = field.description) === null || _field$description === void 0 ? void 0 : _field$description.value, - args: buildArgumentMap(field.arguments), - deprecationReason: getDeprecationReason(field), - astNode: field - }; + inputFields${inputDeprecation("(includeDeprecated: true)")} { + ...InputValue } - } - return fieldConfigMap; - } - function buildArgumentMap(args) { - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const argsNodes = /* c8 ignore next */ - args !== null && args !== void 0 ? args : []; - const argConfigMap = Object.create(null); - for (const arg of argsNodes) { - var _arg$description; - - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - const type = getWrappedType(arg.type); - argConfigMap[arg.name.value] = { - type, - description: (_arg$description = arg.description) === null || _arg$description === void 0 ? void 0 : _arg$description.value, - defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), - deprecationReason: getDeprecationReason(arg), - astNode: arg - }; - } - return argConfigMap; - } - function buildInputFieldMap(nodes) { - const inputFieldMap = Object.create(null); - for (const node of nodes) { - var _node$fields2; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const fieldsNodes = /* c8 ignore next */ - (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []; - for (const field of fieldsNodes) { - var _field$description2; - - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - const type = getWrappedType(field.type); - inputFieldMap[field.name.value] = { - type, - description: (_field$description2 = field.description) === null || _field$description2 === void 0 ? void 0 : _field$description2.value, - defaultValue: (0, _valueFromAST.valueFromAST)(field.defaultValue, type), - deprecationReason: getDeprecationReason(field), - astNode: field - }; + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef } } - return inputFieldMap; - } - function buildEnumValueMap(nodes) { - const enumValueMap = Object.create(null); - for (const node of nodes) { - var _node$values; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const valuesNodes = /* c8 ignore next */ - (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; - for (const value of valuesNodes) { - var _value$description; - enumValueMap[value.name.value] = { - description: (_value$description = value.description) === null || _value$description === void 0 ? void 0 : _value$description.value, - deprecationReason: getDeprecationReason(value), - astNode: value - }; + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation("isDeprecated")} + ${inputDeprecation("deprecationReason")} + } + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } } } - return enumValueMap; - } - function buildInterfaces(nodes) { - // Note: While this could make assertions to get the correctly typed - // values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - return nodes.flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - node => { - var _node$interfaces$map, _node$interfaces; - return /* c8 ignore next */( - (_node$interfaces$map = (_node$interfaces = node.interfaces) === null || _node$interfaces === void 0 ? void 0 : _node$interfaces.map(getNamedType)) !== null && _node$interfaces$map !== void 0 ? _node$interfaces$map : [] - ); - }); - } - function buildUnionTypes(nodes) { - // Note: While this could make assertions to get the correctly typed - // values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - return nodes.flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - node => { - var _node$types$map, _node$types; - return /* c8 ignore next */( - (_node$types$map = (_node$types = node.types) === null || _node$types === void 0 ? void 0 : _node$types.map(getNamedType)) !== null && _node$types$map !== void 0 ? _node$types$map : [] - ); - }); - } - function buildType(astNode) { - var _typeExtensionsMap$na; - const name = astNode.name.value; - const extensionASTNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : []; - switch (astNode.kind) { - case _kinds.Kind.OBJECT_TYPE_DEFINITION: - { - var _astNode$description; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLObjectType({ - name, - description: (_astNode$description = astNode.description) === null || _astNode$description === void 0 ? void 0 : _astNode$description.value, - interfaces: () => buildInterfaces(allNodes), - fields: () => buildFieldMap(allNodes), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.INTERFACE_TYPE_DEFINITION: - { - var _astNode$description2; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLInterfaceType({ - name, - description: (_astNode$description2 = astNode.description) === null || _astNode$description2 === void 0 ? void 0 : _astNode$description2.value, - interfaces: () => buildInterfaces(allNodes), - fields: () => buildFieldMap(allNodes), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.ENUM_TYPE_DEFINITION: - { - var _astNode$description3; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLEnumType({ - name, - description: (_astNode$description3 = astNode.description) === null || _astNode$description3 === void 0 ? void 0 : _astNode$description3.value, - values: buildEnumValueMap(allNodes), - astNode, - extensionASTNodes - }); + `; } - case _kinds.Kind.UNION_TYPE_DEFINITION: - { - var _astNode$description4; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLUnionType({ - name, - description: (_astNode$description4 = astNode.description) === null || _astNode$description4 === void 0 ? void 0 : _astNode$description4.value, - types: () => buildUnionTypes(allNodes), - astNode, - extensionASTNodes - }); + + /***/ + }, + + /***/ "../../../node_modules/graphql/utilities/getOperationAST.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getOperationAST.mjs ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getOperationAST = getOperationAST; + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + /** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ + + function getOperationAST(documentAST, operationName) { + let operation = null; + for (const definition of documentAST.definitions) { + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + var _definition$name; + if (operationName == null) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + return definition; + } + } + } + return operation; } - case _kinds.Kind.SCALAR_TYPE_DEFINITION: - { - var _astNode$description5; - return new _definition.GraphQLScalarType({ - name, - description: (_astNode$description5 = astNode.description) === null || _astNode$description5 === void 0 ? void 0 : _astNode$description5.value, - specifiedByURL: getSpecifiedByURL(astNode), - astNode, - extensionASTNodes - }); + + /***/ + }, + + /***/ "../../../node_modules/graphql/utilities/getOperationRootType.mjs": + /*!************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getOperationRootType.mjs ***! + \************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getOperationRootType = getOperationRootType; + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Extracts the root type of the operation from the schema. + * + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 + */ + function getOperationRootType(schema, operation) { + if (operation.operation === "query") { + const queryType = schema.getQueryType(); + if (!queryType) { + throw new _GraphQLError.GraphQLError( + "Schema does not define the required query root type.", + { + nodes: operation, + } + ); + } + return queryType; + } + if (operation.operation === "mutation") { + const mutationType = schema.getMutationType(); + if (!mutationType) { + throw new _GraphQLError.GraphQLError( + "Schema is not configured for mutations.", + { + nodes: operation, + } + ); + } + return mutationType; + } + if (operation.operation === "subscription") { + const subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError( + "Schema is not configured for subscriptions.", + { + nodes: operation, + } + ); + } + return subscriptionType; + } + throw new _GraphQLError.GraphQLError( + "Can only have query, mutation and subscription operations.", + { + nodes: operation, + } + ); } - case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: - { - var _astNode$description6; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLInputObjectType({ - name, - description: (_astNode$description6 = astNode.description) === null || _astNode$description6 === void 0 ? void 0 : _astNode$description6.value, - fields: () => buildInputFieldMap(allNodes), - astNode, - extensionASTNodes + + /***/ + }, + + /***/ "../../../node_modules/graphql/utilities/index.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/utilities/index.mjs ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function () { + return _findBreakingChanges.BreakingChangeType; + }, + }); + Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function () { + return _findBreakingChanges.DangerousChangeType; + }, + }); + Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function () { + return _TypeInfo.TypeInfo; + }, + }); + Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function () { + return _assertValidName.assertValidName; + }, + }); + Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function () { + return _astFromValue.astFromValue; + }, + }); + Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function () { + return _buildASTSchema.buildASTSchema; + }, + }); + Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function () { + return _buildClientSchema.buildClientSchema; + }, + }); + Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function () { + return _buildASTSchema.buildSchema; + }, + }); + Object.defineProperty(exports, "coerceInputValue", { + enumerable: true, + get: function () { + return _coerceInputValue.coerceInputValue; + }, + }); + Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function () { + return _concatAST.concatAST; + }, + }); + Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function () { + return _typeComparators.doTypesOverlap; + }, + }); + Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function () { + return _extendSchema.extendSchema; + }, + }); + Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function () { + return _findBreakingChanges.findBreakingChanges; + }, + }); + Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function () { + return _findBreakingChanges.findDangerousChanges; + }, + }); + Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function () { + return _getIntrospectionQuery.getIntrospectionQuery; + }, + }); + Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function () { + return _getOperationAST.getOperationAST; + }, + }); + Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function () { + return _getOperationRootType.getOperationRootType; + }, + }); + Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function () { + return _introspectionFromSchema.introspectionFromSchema; + }, + }); + Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function () { + return _typeComparators.isEqualType; + }, + }); + Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function () { + return _typeComparators.isTypeSubTypeOf; + }, + }); + Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function () { + return _assertValidName.isValidNameError; + }, + }); + Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function () { + return _lexicographicSortSchema.lexicographicSortSchema; + }, + }); + Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function () { + return _printSchema.printIntrospectionSchema; + }, + }); + Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function () { + return _printSchema.printSchema; + }, + }); + Object.defineProperty(exports, "printType", { + enumerable: true, + get: function () { + return _printSchema.printType; + }, + }); + Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function () { + return _separateOperations.separateOperations; + }, + }); + Object.defineProperty(exports, "stripIgnoredCharacters", { + enumerable: true, + get: function () { + return _stripIgnoredCharacters.stripIgnoredCharacters; + }, + }); + Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function () { + return _typeFromAST.typeFromAST; + }, + }); + Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function () { + return _valueFromAST.valueFromAST; + }, + }); + Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function () { + return _valueFromASTUntyped.valueFromASTUntyped; + }, + }); + Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function () { + return _TypeInfo.visitWithTypeInfo; + }, + }); + var _getIntrospectionQuery = __webpack_require__( + /*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs" + ); + var _getOperationAST = __webpack_require__( + /*! ./getOperationAST.mjs */ "../../../node_modules/graphql/utilities/getOperationAST.mjs" + ); + var _getOperationRootType = __webpack_require__( + /*! ./getOperationRootType.mjs */ "../../../node_modules/graphql/utilities/getOperationRootType.mjs" + ); + var _introspectionFromSchema = __webpack_require__( + /*! ./introspectionFromSchema.mjs */ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs" + ); + var _buildClientSchema = __webpack_require__( + /*! ./buildClientSchema.mjs */ "../../../node_modules/graphql/utilities/buildClientSchema.mjs" + ); + var _buildASTSchema = __webpack_require__( + /*! ./buildASTSchema.mjs */ "../../../node_modules/graphql/utilities/buildASTSchema.mjs" + ); + var _extendSchema = __webpack_require__( + /*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs" + ); + var _lexicographicSortSchema = __webpack_require__( + /*! ./lexicographicSortSchema.mjs */ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs" + ); + var _printSchema = __webpack_require__( + /*! ./printSchema.mjs */ "../../../node_modules/graphql/utilities/printSchema.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + var _valueFromAST = __webpack_require__( + /*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs" + ); + var _valueFromASTUntyped = __webpack_require__( + /*! ./valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs" + ); + var _astFromValue = __webpack_require__( + /*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs" + ); + var _TypeInfo = __webpack_require__( + /*! ./TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs" + ); + var _coerceInputValue = __webpack_require__( + /*! ./coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs" + ); + var _concatAST = __webpack_require__( + /*! ./concatAST.mjs */ "../../../node_modules/graphql/utilities/concatAST.mjs" + ); + var _separateOperations = __webpack_require__( + /*! ./separateOperations.mjs */ "../../../node_modules/graphql/utilities/separateOperations.mjs" + ); + var _stripIgnoredCharacters = __webpack_require__( + /*! ./stripIgnoredCharacters.mjs */ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs" + ); + var _typeComparators = __webpack_require__( + /*! ./typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs" + ); + var _assertValidName = __webpack_require__( + /*! ./assertValidName.mjs */ "../../../node_modules/graphql/utilities/assertValidName.mjs" + ); + var _findBreakingChanges = __webpack_require__( + /*! ./findBreakingChanges.mjs */ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs" + ); + + /***/ + }, + + /***/ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs": + /*!***************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/introspectionFromSchema.mjs ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.introspectionFromSchema = introspectionFromSchema; + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _parser = __webpack_require__( + /*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs" + ); + var _execute = __webpack_require__( + /*! ../execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs" + ); + var _getIntrospectionQuery = __webpack_require__( + /*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs" + ); + /** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ + + function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + ...options, + }; + const document = (0, _parser.parse)( + (0, _getIntrospectionQuery.getIntrospectionQuery)( + optionsWithDefaults + ) + ); + const result = (0, _execute.executeSync)({ + schema, + document, }); + (!result.errors && result.data) || (0, _invariant.invariant)(false); + return result.data; } - } - } -} -const stdTypeMap = (0, _keyMap.keyMap)([..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], type => type.name); -/** - * Given a field or enum value node, returns the string value for the - * deprecation reason. - */ -function getDeprecationReason(node) { - const deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues` + /***/ + }, - return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason; -} -/** - * Given a scalar node, returns the string value for the specifiedByURL. - */ + /***/ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs": + /*!***************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.lexicographicSortSchema = lexicographicSortSchema; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _keyValMap = __webpack_require__( + /*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs" + ); + var _naturalCompare = __webpack_require__( + /*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _introspection = __webpack_require__( + /*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _schema = __webpack_require__( + /*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs" + ); + /** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ -function getSpecifiedByURL(node) { - const specifiedBy = (0, _values.getDirectiveValues)(_directives.GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues` + function lexicographicSortSchema(schema) { + const schemaConfig = schema.toConfig(); + const typeMap = (0, _keyValMap.keyValMap)( + sortByName(schemaConfig.types), + (type) => type.name, + sortNamedType + ); + return new _schema.GraphQLSchema({ + ...schemaConfig, + types: Object.values(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription), + }); + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME: TS Conversion + + return replaceNamedType(type); + } + function replaceNamedType(type) { + return typeMap[type.name]; + } + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + function sortDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + locations: sortBy(config.locations, (x) => x), + args: sortArgs(config.args), + }); + } + function sortArgs(args) { + return sortObjMap(args, (arg) => ({ + ...arg, + type: replaceType(arg.type), + })); + } + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + args: field.args && sortArgs(field.args), + })); + } + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + })); + } + function sortTypes(array) { + return sortByName(array).map(replaceNamedType); + } + function sortNamedType(type) { + if ( + (0, _definition.isScalarType)(type) || + (0, _introspection.isIntrospectionType)(type) + ) { + return type; + } + if ((0, _definition.isObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } + if ((0, _definition.isInterfaceType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } + if ((0, _definition.isUnionType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLUnionType({ + ...config, + types: () => sortTypes(config.types), + }); + } + if ((0, _definition.isEnumType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLEnumType({ + ...config, + values: sortObjMap(config.values, (value) => value), + }); + } + if ((0, _definition.isInputObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields), + }); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. - return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url; -} + false || + (0, _invariant.invariant)( + false, + "Unexpected type: " + (0, _inspect.inspect)(type) + ); + } + } + function sortObjMap(map, sortValueFn) { + const sortedMap = Object.create(null); + for (const key of Object.keys(map).sort( + _naturalCompare.naturalCompare + )) { + sortedMap[key] = sortValueFn(map[key]); + } + return sortedMap; + } + function sortByName(array) { + return sortBy(array, (obj) => obj.name); + } + function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return (0, _naturalCompare.naturalCompare)(key1, key2); + }); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs": -/*!***********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/findBreakingChanges.mjs ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.DangerousChangeType = exports.BreakingChangeType = void 0; -exports.findBreakingChanges = findBreakingChanges; -exports.findDangerousChanges = findDangerousChanges; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); -var _sortValueNode = __webpack_require__(/*! ./sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); -var BreakingChangeType; -(function (BreakingChangeType) { - BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; - BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; - BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; - BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; - BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = 'REQUIRED_INPUT_FIELD_ADDED'; - BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = 'IMPLEMENTED_INTERFACE_REMOVED'; - BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; - BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; - BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; - BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; - BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; - BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; - BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; - BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = 'REQUIRED_DIRECTIVE_ARG_ADDED'; - BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = 'DIRECTIVE_REPEATABLE_REMOVED'; - BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = 'DIRECTIVE_LOCATION_REMOVED'; -})(BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {})); -var DangerousChangeType; -(function (DangerousChangeType) { - DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; - DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; - DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = 'OPTIONAL_INPUT_FIELD_ADDED'; - DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; - DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = 'IMPLEMENTED_INTERFACE_ADDED'; - DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; -})(DangerousChangeType || (exports.DangerousChangeType = DangerousChangeType = {})); -/** - * Given two schemas, returns an Array containing descriptions of all the types - * of breaking changes covered by the other functions down below. - */ -function findBreakingChanges(oldSchema, newSchema) { - // @ts-expect-error - return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in BreakingChangeType); -} -/** - * Given two schemas, returns an Array containing descriptions of all the types - * of potentially dangerous changes covered by the other functions down below. - */ - -function findDangerousChanges(oldSchema, newSchema) { - // @ts-expect-error - return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in DangerousChangeType); -} -function findSchemaChanges(oldSchema, newSchema) { - return [...findTypeChanges(oldSchema, newSchema), ...findDirectiveChanges(oldSchema, newSchema)]; -} -function findDirectiveChanges(oldSchema, newSchema) { - const schemaChanges = []; - const directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); - for (const oldDirective of directivesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_REMOVED, - description: `${oldDirective.name} was removed.` - }); - } - for (const [oldDirective, newDirective] of directivesDiff.persisted) { - const argsDiff = diff(oldDirective.args, newDirective.args); - for (const newArg of argsDiff.added) { - if ((0, _definition.isRequiredArgument)(newArg)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, - description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.` - }); - } - } - for (const oldArg of argsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, - description: `${oldArg.name} was removed from ${oldDirective.name}.` - }); - } - if (oldDirective.isRepeatable && !newDirective.isRepeatable) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, - description: `Repeatable flag was removed from ${oldDirective.name}.` - }); - } - for (const location of oldDirective.locations) { - if (!newDirective.locations.includes(location)) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, - description: `${location} was removed from ${oldDirective.name}.` + /***/ "../../../node_modules/graphql/utilities/printSchema.mjs": + /*!***************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/printSchema.mjs ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - } - } - return schemaChanges; -} -function findTypeChanges(oldSchema, newSchema) { - const schemaChanges = []; - const typesDiff = diff(Object.values(oldSchema.getTypeMap()), Object.values(newSchema.getTypeMap())); - for (const oldType of typesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_REMOVED, - description: (0, _scalars.isSpecifiedScalarType)(oldType) ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` : `${oldType.name} was removed.` - }); - } - for (const [oldType, newType] of typesDiff.persisted) { - if ((0, _definition.isEnumType)(oldType) && (0, _definition.isEnumType)(newType)) { - schemaChanges.push(...findEnumTypeChanges(oldType, newType)); - } else if ((0, _definition.isUnionType)(oldType) && (0, _definition.isUnionType)(newType)) { - schemaChanges.push(...findUnionTypeChanges(oldType, newType)); - } else if ((0, _definition.isInputObjectType)(oldType) && (0, _definition.isInputObjectType)(newType)) { - schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); - } else if ((0, _definition.isObjectType)(oldType) && (0, _definition.isObjectType)(newType)) { - schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); - } else if ((0, _definition.isInterfaceType)(oldType) && (0, _definition.isInterfaceType)(newType)) { - schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); - } else if (oldType.constructor !== newType.constructor) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_CHANGED_KIND, - description: `${oldType.name} changed from ` + `${typeKindName(oldType)} to ${typeKindName(newType)}.` - }); - } - } - return schemaChanges; -} -function findInputObjectTypeChanges(oldType, newType) { - const schemaChanges = []; - const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); - for (const newField of fieldsDiff.added) { - if ((0, _definition.isRequiredInputField)(newField)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, - description: `A required field ${newField.name} on input type ${oldType.name} was added.` - }); - } else { - schemaChanges.push({ - type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, - description: `An optional field ${newField.name} on input type ${oldType.name} was added.` - }); - } - } - for (const oldField of fieldsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_REMOVED, - description: `${oldType.name}.${oldField.name} was removed.` - }); - } - for (const [oldField, newField] of fieldsDiff.persisted) { - const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldField.type, newField.type); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_CHANGED_KIND, - description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` - }); - } - } - return schemaChanges; -} -function findUnionTypeChanges(oldType, newType) { - const schemaChanges = []; - const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); - for (const newPossibleType of possibleTypesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.TYPE_ADDED_TO_UNION, - description: `${newPossibleType.name} was added to union type ${oldType.name}.` - }); - } - for (const oldPossibleType of possibleTypesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, - description: `${oldPossibleType.name} was removed from union type ${oldType.name}.` - }); - } - return schemaChanges; -} -function findEnumTypeChanges(oldType, newType) { - const schemaChanges = []; - const valuesDiff = diff(oldType.getValues(), newType.getValues()); - for (const newValue of valuesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.VALUE_ADDED_TO_ENUM, - description: `${newValue.name} was added to enum type ${oldType.name}.` - }); - } - for (const oldValue of valuesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, - description: `${oldValue.name} was removed from enum type ${oldType.name}.` - }); - } - return schemaChanges; -} -function findImplementedInterfacesChanges(oldType, newType) { - const schemaChanges = []; - const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); - for (const newInterface of interfacesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, - description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.` - }); - } - for (const oldInterface of interfacesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, - description: `${oldType.name} no longer implements interface ${oldInterface.name}.` - }); - } - return schemaChanges; -} -function findFieldChanges(oldType, newType) { - const schemaChanges = []; - const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); - for (const oldField of fieldsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_REMOVED, - description: `${oldType.name}.${oldField.name} was removed.` - }); - } - for (const [oldField, newField] of fieldsDiff.persisted) { - schemaChanges.push(...findArgChanges(oldType, oldField, newField)); - const isSafe = isChangeSafeForObjectOrInterfaceField(oldField.type, newField.type); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_CHANGED_KIND, - description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` - }); - } - } - return schemaChanges; -} -function findArgChanges(oldType, oldField, newField) { - const schemaChanges = []; - const argsDiff = diff(oldField.args, newField.args); - for (const oldArg of argsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.ARG_REMOVED, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.` - }); - } - for (const [oldArg, newArg] of argsDiff.persisted) { - const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArg.type, newArg.type); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.ARG_CHANGED_KIND, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` - }); - } else if (oldArg.defaultValue !== undefined) { - if (newArg.defaultValue === undefined) { - schemaChanges.push({ - type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.` - }); - } else { - // Since we looking only for client's observable changes we should - // compare default values in the same representation as they are - // represented inside introspection. - const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); - const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); - if (oldValueStr !== newValueStr) { - schemaChanges.push({ - type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.` - }); + exports.printIntrospectionSchema = printIntrospectionSchema; + exports.printSchema = printSchema; + exports.printType = printType; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _blockString = __webpack_require__( + /*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _printer = __webpack_require__( + /*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + var _introspection = __webpack_require__( + /*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _scalars = __webpack_require__( + /*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + var _astFromValue = __webpack_require__( + /*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs" + ); + function printSchema(schema) { + return printFilteredSchema( + schema, + (n) => !(0, _directives.isSpecifiedDirective)(n), + isDefinedType + ); } - } - } - } - for (const newArg of argsDiff.added) { - if ((0, _definition.isRequiredArgument)(newArg)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_ARG_ADDED, - description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` - }); - } else { - schemaChanges.push({ - type: DangerousChangeType.OPTIONAL_ARG_ADDED, - description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` - }); - } - } - return schemaChanges; -} -function isChangeSafeForObjectOrInterfaceField(oldType, newType) { - if ((0, _definition.isListType)(oldType)) { - return ( - // if they're both lists, make sure the underlying types are compatible - (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || - // moving from nullable to non-null of the same underlying type is safe - (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) - ); - } - if ((0, _definition.isNonNullType)(oldType)) { - // if they're both non-null, make sure the underlying types are compatible - return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); - } - return ( - // if they're both named types, see if their names are equivalent - (0, _definition.isNamedType)(newType) && oldType.name === newType.name || - // moving from nullable to non-null of the same underlying type is safe - (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) - ); -} -function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { - if ((0, _definition.isListType)(oldType)) { - // if they're both lists, make sure the underlying types are compatible - return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); - } - if ((0, _definition.isNonNullType)(oldType)) { - return ( - // if they're both non-null, make sure the underlying types are - // compatible - (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || - // moving from non-null to nullable of the same underlying type is safe - !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) - ); - } // if they're both named types, see if their names are equivalent - - return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; -} -function typeKindName(type) { - if ((0, _definition.isScalarType)(type)) { - return 'a Scalar type'; - } - if ((0, _definition.isObjectType)(type)) { - return 'an Object type'; - } - if ((0, _definition.isInterfaceType)(type)) { - return 'an Interface type'; - } - if ((0, _definition.isUnionType)(type)) { - return 'a Union type'; - } - if ((0, _definition.isEnumType)(type)) { - return 'an Enum type'; - } - if ((0, _definition.isInputObjectType)(type)) { - return 'an Input type'; - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); -} -function stringifyValue(value, type) { - const ast = (0, _astFromValue.astFromValue)(value, type); - ast != null || (0, _invariant.invariant)(false); - return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); -} -function diff(oldArray, newArray) { - const added = []; - const removed = []; - const persisted = []; - const oldMap = (0, _keyMap.keyMap)(oldArray, ({ - name - }) => name); - const newMap = (0, _keyMap.keyMap)(newArray, ({ - name - }) => name); - for (const oldItem of oldArray) { - const newItem = newMap[oldItem.name]; - if (newItem === undefined) { - removed.push(oldItem); - } else { - persisted.push([oldItem, newItem]); - } - } - for (const newItem of newArray) { - if (oldMap[newItem.name] === undefined) { - added.push(newItem); - } - } - return { - added, - persisted, - removed - }; -} + function printIntrospectionSchema(schema) { + return printFilteredSchema( + schema, + _directives.isSpecifiedDirective, + _introspection.isIntrospectionType + ); + } + function isDefinedType(type) { + return ( + !(0, _scalars.isSpecifiedScalarType)(type) && + !(0, _introspection.isIntrospectionType)(type) + ); + } + function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [ + printSchemaDefinition(schema), + ...directives.map((directive) => printDirective(directive)), + ...types.map((type) => printType(type)), + ] + .filter(Boolean) + .join("\n\n"); + } + function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + const operationTypes = []; + const queryType = schema.getQueryType(); + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + const mutationType = schema.getMutationType(); + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + return ( + printDescription(schema) + + `schema {\n${operationTypes.join("\n")}\n}` + ); + } + /** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * ```graphql + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * ``` + * + * When using this naming convention, the schema description can be omitted. + */ -/***/ }), + function isSchemaOfCommonNames(schema) { + const queryType = schema.getQueryType(); + if (queryType && queryType.name !== "Query") { + return false; + } + const mutationType = schema.getMutationType(); + if (mutationType && mutationType.name !== "Mutation") { + return false; + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && subscriptionType.name !== "Subscription") { + return false; + } + return true; + } + function printType(type) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type); + } + if ((0, _definition.isObjectType)(type)) { + return printObject(type); + } + if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type); + } + if ((0, _definition.isUnionType)(type)) { + return printUnion(type); + } + if ((0, _definition.isEnumType)(type)) { + return printEnum(type); + } + if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. -/***/ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs": -/*!*************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs ***! - \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getIntrospectionQuery = getIntrospectionQuery; -/** - * Produce the GraphQL query recommended for a full schema introspection. - * Accepts optional IntrospectionOptions. - */ -function getIntrospectionQuery(options) { - const optionsWithDefault = { - descriptions: true, - specifiedByUrl: false, - directiveIsRepeatable: false, - schemaDescription: false, - inputValueDeprecation: false, - ...options - }; - const descriptions = optionsWithDefault.descriptions ? 'description' : ''; - const specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByURL' : ''; - const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : ''; - const schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ''; - function inputDeprecation(str) { - return optionsWithDefault.inputValueDeprecation ? str : ''; - } - return ` - query IntrospectionQuery { - __schema { - ${schemaDescription} - queryType { name } - mutationType { name } - subscriptionType { name } - types { - ...FullType + false || + (0, _invariant.invariant)( + false, + "Unexpected type: " + (0, _inspect.inspect)(type) + ); } - directives { - name - ${descriptions} - ${directiveIsRepeatable} - locations - args${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue + function printScalar(type) { + return ( + printDescription(type) + + `scalar ${type.name}` + + printSpecifiedByURL(type) + ); + } + function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length + ? " implements " + interfaces.map((i) => i.name).join(" & ") + : ""; + } + function printObject(type) { + return ( + printDescription(type) + + `type ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) + ); + } + function printInterface(type) { + return ( + printDescription(type) + + `interface ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) + ); + } + function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? " = " + types.join(" | ") : ""; + return printDescription(type) + "union " + type.name + possibleTypes; + } + function printEnum(type) { + const values = type + .getValues() + .map( + (value, i) => + printDescription(value, " ", !i) + + " " + + value.name + + printDeprecated(value.deprecationReason) + ); + return ( + printDescription(type) + `enum ${type.name}` + printBlock(values) + ); + } + function printInputObject(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => printDescription(f, " ", !i) + " " + printInputValue(f) + ); + return ( + printDescription(type) + `input ${type.name}` + printBlock(fields) + ); + } + function printFields(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => + printDescription(f, " ", !i) + + " " + + f.name + + printArgs(f.args, " ") + + ": " + + String(f.type) + + printDeprecated(f.deprecationReason) + ); + return printBlock(fields); + } + function printBlock(items) { + return items.length !== 0 ? " {\n" + items.join("\n") + "\n}" : ""; + } + function printArgs(args, indentation = "") { + if (args.length === 0) { + return ""; + } // If every arg does not have a description, print them on one line. + + if (args.every((arg) => !arg.description)) { + return "(" + args.map(printInputValue).join(", ") + ")"; + } + return ( + "(\n" + + args + .map( + (arg, i) => + printDescription(arg, " " + indentation, !i) + + " " + + indentation + + printInputValue(arg) + ) + .join("\n") + + "\n" + + indentation + + ")" + ); + } + function printInputValue(arg) { + const defaultAST = (0, _astFromValue.astFromValue)( + arg.defaultValue, + arg.type + ); + let argDecl = arg.name + ": " + String(arg.type); + if (defaultAST) { + argDecl += ` = ${(0, _printer.print)(defaultAST)}`; + } + return argDecl + printDeprecated(arg.deprecationReason); + } + function printDirective(directive) { + return ( + printDescription(directive) + + "directive @" + + directive.name + + printArgs(directive.args) + + (directive.isRepeatable ? " repeatable" : "") + + " on " + + directive.locations.join(" | ") + ); + } + function printDeprecated(reason) { + if (reason == null) { + return ""; } + if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: reason, + }); + return ` @deprecated(reason: ${astValue})`; + } + return " @deprecated"; } - } - } - - fragment FullType on __Type { - kind - name - ${descriptions} - ${specifiedByUrl} - fields(includeDeprecated: true) { - name - ${descriptions} - args${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue + function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ""; + } + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: scalar.specifiedByURL, + }); + return ` @specifiedBy(url: ${astValue})`; } - type { - ...TypeRef + function printDescription(def, indentation = "", firstInBlock = true) { + const { description } = def; + if (description == null) { + return ""; + } + const blockString = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: description, + block: (0, _blockString.isPrintableAsBlockString)(description), + }); + const prefix = + indentation && !firstInBlock ? "\n" + indentation : indentation; + return prefix + blockString.replace(/\n/g, "\n" + indentation) + "\n"; } - isDeprecated - deprecationReason - } - inputFields${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - interfaces { - ...TypeRef - } - enumValues(includeDeprecated: true) { - name - ${descriptions} - isDeprecated - deprecationReason - } - possibleTypes { - ...TypeRef - } - } - fragment InputValue on __InputValue { - name - ${descriptions} - type { ...TypeRef } - defaultValue - ${inputDeprecation('isDeprecated')} - ${inputDeprecation('deprecationReason')} - } + /***/ + }, + + /***/ "../../../node_modules/graphql/utilities/separateOperations.mjs": + /*!**********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/separateOperations.mjs ***! + \**********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.separateOperations = separateOperations; + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _visitor = __webpack_require__( + /*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs" + ); + /** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ + + function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + case _kinds.Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies( + definitionNode.selectionSet + ); + break; + default: // ignore non-executable definitions + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + const separatedDocumentASTs = Object.create(null); + for (const operation of operations) { + const dependencies = new Set(); + for (const fragmentName of collectDependencies( + operation.selectionSet + )) { + collectTransitiveDependencies( + dependencies, + depGraph, + fragmentName + ); + } // Provides the empty string for anonymous operations. + + const operationName = operation.name ? operation.name.value : ""; // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + separatedDocumentASTs[operationName] = { + kind: _kinds.Kind.DOCUMENT, + definitions: documentAST.definitions.filter( + (node) => + node === operation || + (node.kind === _kinds.Kind.FRAGMENT_DEFINITION && + dependencies.has(node.name.value)) + ), + }; + } + return separatedDocumentASTs; + } - fragment TypeRef on __Type { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - } - } - } - } + // From a dependency graph, collects a list of transitive dependencies by + // recursing through a dependency graph. + function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); } } } } - } - } - `; -} + function collectDependencies(selectionSet) { + const dependencies = []; + (0, _visitor.visit)(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + }, + }); + return dependencies; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/getOperationAST.mjs": -/*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/getOperationAST.mjs ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getOperationAST = getOperationAST; -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -/** - * Returns an operation AST given a document AST and optionally an operation - * name. If a name is not provided, an operation is only returned if only one is - * provided in the document. - */ - -function getOperationAST(documentAST, operationName) { - let operation = null; - for (const definition of documentAST.definitions) { - if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { - var _definition$name; - if (operationName == null) { - // If no operation name was provided, only return an Operation if there - // is one defined in the document. Upon encountering the second, return - // null. - if (operation) { - return null; + /***/ "../../../node_modules/graphql/utilities/sortValueNode.mjs": + /*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/sortValueNode.mjs ***! + \*****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.sortValueNode = sortValueNode; + var _naturalCompare = __webpack_require__( + /*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + /** + * Sort ValueNode. + * + * This function returns a sorted copy of the given ValueNode. + * + * @internal + */ + + function sortValueNode(valueNode) { + switch (valueNode.kind) { + case _kinds.Kind.OBJECT: + return { + ...valueNode, + fields: sortFields(valueNode.fields), + }; + case _kinds.Kind.LIST: + return { + ...valueNode, + values: valueNode.values.map(sortValueNode), + }; + case _kinds.Kind.INT: + case _kinds.Kind.FLOAT: + case _kinds.Kind.STRING: + case _kinds.Kind.BOOLEAN: + case _kinds.Kind.NULL: + case _kinds.Kind.ENUM: + case _kinds.Kind.VARIABLE: + return valueNode; + } + } + function sortFields(fields) { + return fields + .map((fieldNode) => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value), + })) + .sort((fieldA, fieldB) => + (0, _naturalCompare.naturalCompare)( + fieldA.name.value, + fieldB.name.value + ) + ); } - operation = definition; - } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { - return definition; - } - } - } - return operation; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/getOperationRootType.mjs": -/*!************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/getOperationRootType.mjs ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getOperationRootType = getOperationRootType; -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Extracts the root type of the operation from the schema. - * - * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 - */ -function getOperationRootType(schema, operation) { - if (operation.operation === 'query') { - const queryType = schema.getQueryType(); - if (!queryType) { - throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', { - nodes: operation - }); - } - return queryType; - } - if (operation.operation === 'mutation') { - const mutationType = schema.getMutationType(); - if (!mutationType) { - throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', { - nodes: operation - }); - } - return mutationType; - } - if (operation.operation === 'subscription') { - const subscriptionType = schema.getSubscriptionType(); - if (!subscriptionType) { - throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', { - nodes: operation - }); - } - return subscriptionType; - } - throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', { - nodes: operation - }); -} + /***/ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs": + /*!**************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.stripIgnoredCharacters = stripIgnoredCharacters; + var _blockString = __webpack_require__( + /*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs" + ); + var _lexer = __webpack_require__( + /*! ../language/lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs" + ); + var _source = __webpack_require__( + /*! ../language/source.mjs */ "../../../node_modules/graphql/language/source.mjs" + ); + var _tokenKind = __webpack_require__( + /*! ../language/tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs" + ); + /** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - Whitespace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * + * Query example: + * + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * + * SDL example: + * + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + */ -/***/ }), + function stripIgnoredCharacters(source) { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + const body = sourceObj.body; + const lexer = new _lexer.Lexer(sourceObj); + let strippedBody = ""; + let wasLastAddedTokenNonPunctuator = false; + while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + /** + * Every two non-punctuator tokens should have space between them. + * Also prevent case of non-punctuator token following by spread resulting + * in invalid token (e.g. `1...` is invalid Float token). + */ -/***/ "../../../node_modules/graphql/utilities/index.mjs": -/*!*********************************************************!*\ - !*** ../../../node_modules/graphql/utilities/index.mjs ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)( + currentToken.kind + ); + if (wasLastAddedTokenNonPunctuator) { + if ( + isNonPunctuator || + currentToken.kind === _tokenKind.TokenKind.SPREAD + ) { + strippedBody += " "; + } + } + const tokenBody = body.slice(currentToken.start, currentToken.end); + if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { + strippedBody += (0, _blockString.printBlockString)( + currentToken.value, + { + minimize: true, + } + ); + } else { + strippedBody += tokenBody; + } + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + return strippedBody; + } + /***/ + }, + /***/ "../../../node_modules/graphql/utilities/typeComparators.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/typeComparators.mjs ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.doTypesOverlap = doTypesOverlap; + exports.isEqualType = isEqualType; + exports.isTypeSubTypeOf = isTypeSubTypeOf; + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Provided two types, return true if the types are equal (invariant). + */ + function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + if ( + (0, _definition.isNonNullType)(typeA) && + (0, _definition.isNonNullType)(typeB) + ) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + if ( + (0, _definition.isListType)(typeA) && + (0, _definition.isListType)(typeB) + ) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "BreakingChangeType", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.BreakingChangeType; - } -})); -Object.defineProperty(exports, "DangerousChangeType", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.DangerousChangeType; - } -})); -Object.defineProperty(exports, "TypeInfo", ({ - enumerable: true, - get: function () { - return _TypeInfo.TypeInfo; - } -})); -Object.defineProperty(exports, "assertValidName", ({ - enumerable: true, - get: function () { - return _assertValidName.assertValidName; - } -})); -Object.defineProperty(exports, "astFromValue", ({ - enumerable: true, - get: function () { - return _astFromValue.astFromValue; - } -})); -Object.defineProperty(exports, "buildASTSchema", ({ - enumerable: true, - get: function () { - return _buildASTSchema.buildASTSchema; - } -})); -Object.defineProperty(exports, "buildClientSchema", ({ - enumerable: true, - get: function () { - return _buildClientSchema.buildClientSchema; - } -})); -Object.defineProperty(exports, "buildSchema", ({ - enumerable: true, - get: function () { - return _buildASTSchema.buildSchema; - } -})); -Object.defineProperty(exports, "coerceInputValue", ({ - enumerable: true, - get: function () { - return _coerceInputValue.coerceInputValue; - } -})); -Object.defineProperty(exports, "concatAST", ({ - enumerable: true, - get: function () { - return _concatAST.concatAST; - } -})); -Object.defineProperty(exports, "doTypesOverlap", ({ - enumerable: true, - get: function () { - return _typeComparators.doTypesOverlap; - } -})); -Object.defineProperty(exports, "extendSchema", ({ - enumerable: true, - get: function () { - return _extendSchema.extendSchema; - } -})); -Object.defineProperty(exports, "findBreakingChanges", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.findBreakingChanges; - } -})); -Object.defineProperty(exports, "findDangerousChanges", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.findDangerousChanges; - } -})); -Object.defineProperty(exports, "getIntrospectionQuery", ({ - enumerable: true, - get: function () { - return _getIntrospectionQuery.getIntrospectionQuery; - } -})); -Object.defineProperty(exports, "getOperationAST", ({ - enumerable: true, - get: function () { - return _getOperationAST.getOperationAST; - } -})); -Object.defineProperty(exports, "getOperationRootType", ({ - enumerable: true, - get: function () { - return _getOperationRootType.getOperationRootType; - } -})); -Object.defineProperty(exports, "introspectionFromSchema", ({ - enumerable: true, - get: function () { - return _introspectionFromSchema.introspectionFromSchema; - } -})); -Object.defineProperty(exports, "isEqualType", ({ - enumerable: true, - get: function () { - return _typeComparators.isEqualType; - } -})); -Object.defineProperty(exports, "isTypeSubTypeOf", ({ - enumerable: true, - get: function () { - return _typeComparators.isTypeSubTypeOf; - } -})); -Object.defineProperty(exports, "isValidNameError", ({ - enumerable: true, - get: function () { - return _assertValidName.isValidNameError; - } -})); -Object.defineProperty(exports, "lexicographicSortSchema", ({ - enumerable: true, - get: function () { - return _lexicographicSortSchema.lexicographicSortSchema; - } -})); -Object.defineProperty(exports, "printIntrospectionSchema", ({ - enumerable: true, - get: function () { - return _printSchema.printIntrospectionSchema; - } -})); -Object.defineProperty(exports, "printSchema", ({ - enumerable: true, - get: function () { - return _printSchema.printSchema; - } -})); -Object.defineProperty(exports, "printType", ({ - enumerable: true, - get: function () { - return _printSchema.printType; - } -})); -Object.defineProperty(exports, "separateOperations", ({ - enumerable: true, - get: function () { - return _separateOperations.separateOperations; - } -})); -Object.defineProperty(exports, "stripIgnoredCharacters", ({ - enumerable: true, - get: function () { - return _stripIgnoredCharacters.stripIgnoredCharacters; - } -})); -Object.defineProperty(exports, "typeFromAST", ({ - enumerable: true, - get: function () { - return _typeFromAST.typeFromAST; - } -})); -Object.defineProperty(exports, "valueFromAST", ({ - enumerable: true, - get: function () { - return _valueFromAST.valueFromAST; - } -})); -Object.defineProperty(exports, "valueFromASTUntyped", ({ - enumerable: true, - get: function () { - return _valueFromASTUntyped.valueFromASTUntyped; - } -})); -Object.defineProperty(exports, "visitWithTypeInfo", ({ - enumerable: true, - get: function () { - return _TypeInfo.visitWithTypeInfo; - } -})); -var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); -var _getOperationAST = __webpack_require__(/*! ./getOperationAST.mjs */ "../../../node_modules/graphql/utilities/getOperationAST.mjs"); -var _getOperationRootType = __webpack_require__(/*! ./getOperationRootType.mjs */ "../../../node_modules/graphql/utilities/getOperationRootType.mjs"); -var _introspectionFromSchema = __webpack_require__(/*! ./introspectionFromSchema.mjs */ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs"); -var _buildClientSchema = __webpack_require__(/*! ./buildClientSchema.mjs */ "../../../node_modules/graphql/utilities/buildClientSchema.mjs"); -var _buildASTSchema = __webpack_require__(/*! ./buildASTSchema.mjs */ "../../../node_modules/graphql/utilities/buildASTSchema.mjs"); -var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); -var _lexicographicSortSchema = __webpack_require__(/*! ./lexicographicSortSchema.mjs */ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs"); -var _printSchema = __webpack_require__(/*! ./printSchema.mjs */ "../../../node_modules/graphql/utilities/printSchema.mjs"); -var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); -var _valueFromASTUntyped = __webpack_require__(/*! ./valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); -var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); -var _TypeInfo = __webpack_require__(/*! ./TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); -var _coerceInputValue = __webpack_require__(/*! ./coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); -var _concatAST = __webpack_require__(/*! ./concatAST.mjs */ "../../../node_modules/graphql/utilities/concatAST.mjs"); -var _separateOperations = __webpack_require__(/*! ./separateOperations.mjs */ "../../../node_modules/graphql/utilities/separateOperations.mjs"); -var _stripIgnoredCharacters = __webpack_require__(/*! ./stripIgnoredCharacters.mjs */ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs"); -var _typeComparators = __webpack_require__(/*! ./typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); -var _assertValidName = __webpack_require__(/*! ./assertValidName.mjs */ "../../../node_modules/graphql/utilities/assertValidName.mjs"); -var _findBreakingChanges = __webpack_require__(/*! ./findBreakingChanges.mjs */ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs"); - -/***/ }), - -/***/ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs": -/*!***************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/introspectionFromSchema.mjs ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.introspectionFromSchema = introspectionFromSchema; -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); -var _execute = __webpack_require__(/*! ../execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); -var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); -/** - * Build an IntrospectionQuery from a GraphQLSchema - * - * IntrospectionQuery is useful for utilities that care about type and field - * relationships, but do not need to traverse through those relationships. - * - * This is the inverse of buildClientSchema. The primary use case is outside - * of the server context, for instance when doing schema comparisons. - */ - -function introspectionFromSchema(schema, options) { - const optionsWithDefaults = { - specifiedByUrl: true, - directiveIsRepeatable: true, - schemaDescription: true, - inputValueDeprecation: true, - ...options - }; - const document = (0, _parser.parse)((0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults)); - const result = (0, _execute.executeSync)({ - schema, - document - }); - !result.errors && result.data || (0, _invariant.invariant)(false); - return result.data; -} + return false; + } + /** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ -/***/ }), + function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf( + schema, + maybeSubType.ofType, + superType.ofType + ); + } + return false; + } + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf( + schema, + maybeSubType.ofType, + superType.ofType + ); + } + return false; + } + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, check if it is super type of maybeSubType. + // Otherwise, the child type is not a valid subtype of the parent type. + + return ( + (0, _definition.isAbstractType)(superType) && + ((0, _definition.isInterfaceType)(maybeSubType) || + (0, _definition.isObjectType)(maybeSubType)) && + schema.isSubType(superType, maybeSubType) + ); + } + /** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ -/***/ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs": -/*!***************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.lexicographicSortSchema = lexicographicSortSchema; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); -var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); -/** - * Sort GraphQLSchema. - * - * This function returns a sorted copy of the given GraphQLSchema. - */ - -function lexicographicSortSchema(schema) { - const schemaConfig = schema.toConfig(); - const typeMap = (0, _keyValMap.keyValMap)(sortByName(schemaConfig.types), type => type.name, sortNamedType); - return new _schema.GraphQLSchema({ - ...schemaConfig, - types: Object.values(typeMap), - directives: sortByName(schemaConfig.directives).map(sortDirective), - query: replaceMaybeType(schemaConfig.query), - mutation: replaceMaybeType(schemaConfig.mutation), - subscription: replaceMaybeType(schemaConfig.subscription) - }); - function replaceType(type) { - if ((0, _definition.isListType)(type)) { - // @ts-expect-error - return new _definition.GraphQLList(replaceType(type.ofType)); - } else if ((0, _definition.isNonNullType)(type)) { - // @ts-expect-error - return new _definition.GraphQLNonNull(replaceType(type.ofType)); - } // @ts-expect-error FIXME: TS Conversion - - return replaceNamedType(type); - } - function replaceNamedType(type) { - return typeMap[type.name]; - } - function replaceMaybeType(maybeType) { - return maybeType && replaceNamedType(maybeType); - } - function sortDirective(directive) { - const config = directive.toConfig(); - return new _directives.GraphQLDirective({ - ...config, - locations: sortBy(config.locations, x => x), - args: sortArgs(config.args) - }); - } - function sortArgs(args) { - return sortObjMap(args, arg => ({ - ...arg, - type: replaceType(arg.type) - })); - } - function sortFields(fieldsMap) { - return sortObjMap(fieldsMap, field => ({ - ...field, - type: replaceType(field.type), - args: field.args && sortArgs(field.args) - })); - } - function sortInputFields(fieldsMap) { - return sortObjMap(fieldsMap, field => ({ - ...field, - type: replaceType(field.type) - })); - } - function sortTypes(array) { - return sortByName(array).map(replaceNamedType); - } - function sortNamedType(type) { - if ((0, _definition.isScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { - return type; - } - if ((0, _definition.isObjectType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLObjectType({ - ...config, - interfaces: () => sortTypes(config.interfaces), - fields: () => sortFields(config.fields) - }); - } - if ((0, _definition.isInterfaceType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLInterfaceType({ - ...config, - interfaces: () => sortTypes(config.interfaces), - fields: () => sortFields(config.fields) - }); - } - if ((0, _definition.isUnionType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLUnionType({ - ...config, - types: () => sortTypes(config.types) - }); - } - if ((0, _definition.isEnumType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLEnumType({ - ...config, - values: sortObjMap(config.values, value => value) - }); - } - if ((0, _definition.isInputObjectType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLInputObjectType({ - ...config, - fields: () => sortInputFields(config.fields) - }); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. + function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema + .getPossibleTypes(typeA) + .some((type) => schema.isSubType(typeB, type)); + } // Determine if the latter type is a possible concrete type of the former. - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } -} -function sortObjMap(map, sortValueFn) { - const sortedMap = Object.create(null); - for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { - sortedMap[key] = sortValueFn(map[key]); - } - return sortedMap; -} -function sortByName(array) { - return sortBy(array, obj => obj.name); -} -function sortBy(array, mapToKey) { - return array.slice().sort((obj1, obj2) => { - const key1 = mapToKey(obj1); - const key2 = mapToKey(obj2); - return (0, _naturalCompare.naturalCompare)(key1, key2); - }); -} + return schema.isSubType(typeA, typeB); + } + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isSubType(typeB, typeA); + } // Otherwise the types do not overlap. + + return false; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/printSchema.mjs": -/*!***************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/printSchema.mjs ***! + /***/ "../../../node_modules/graphql/utilities/typeFromAST.mjs": + /*!***************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/typeFromAST.mjs ***! \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.printIntrospectionSchema = printIntrospectionSchema; -exports.printSchema = printSchema; -exports.printType = printType; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); -function printSchema(schema) { - return printFilteredSchema(schema, n => !(0, _directives.isSpecifiedDirective)(n), isDefinedType); -} -function printIntrospectionSchema(schema) { - return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType); -} -function isDefinedType(type) { - return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); -} -function printFilteredSchema(schema, directiveFilter, typeFilter) { - const directives = schema.getDirectives().filter(directiveFilter); - const types = Object.values(schema.getTypeMap()).filter(typeFilter); - return [printSchemaDefinition(schema), ...directives.map(directive => printDirective(directive)), ...types.map(type => printType(type))].filter(Boolean).join('\n\n'); -} -function printSchemaDefinition(schema) { - if (schema.description == null && isSchemaOfCommonNames(schema)) { - return; - } - const operationTypes = []; - const queryType = schema.getQueryType(); - if (queryType) { - operationTypes.push(` query: ${queryType.name}`); - } - const mutationType = schema.getMutationType(); - if (mutationType) { - operationTypes.push(` mutation: ${mutationType.name}`); - } - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType) { - operationTypes.push(` subscription: ${subscriptionType.name}`); - } - return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; -} -/** - * GraphQL schema define root types for each type of operation. These types are - * the same as any other type and can be named in any manner, however there is - * a common naming convention: - * - * ```graphql - * schema { - * query: Query - * mutation: Mutation - * subscription: Subscription - * } - * ``` - * - * When using this naming convention, the schema description can be omitted. - */ - -function isSchemaOfCommonNames(schema) { - const queryType = schema.getQueryType(); - if (queryType && queryType.name !== 'Query') { - return false; - } - const mutationType = schema.getMutationType(); - if (mutationType && mutationType.name !== 'Mutation') { - return false; - } - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType && subscriptionType.name !== 'Subscription') { - return false; - } - return true; -} -function printType(type) { - if ((0, _definition.isScalarType)(type)) { - return printScalar(type); - } - if ((0, _definition.isObjectType)(type)) { - return printObject(type); - } - if ((0, _definition.isInterfaceType)(type)) { - return printInterface(type); - } - if ((0, _definition.isUnionType)(type)) { - return printUnion(type); - } - if ((0, _definition.isEnumType)(type)) { - return printEnum(type); - } - if ((0, _definition.isInputObjectType)(type)) { - return printInputObject(type); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); -} -function printScalar(type) { - return printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type); -} -function printImplementedInterfaces(type) { - const interfaces = type.getInterfaces(); - return interfaces.length ? ' implements ' + interfaces.map(i => i.name).join(' & ') : ''; -} -function printObject(type) { - return printDescription(type) + `type ${type.name}` + printImplementedInterfaces(type) + printFields(type); -} -function printInterface(type) { - return printDescription(type) + `interface ${type.name}` + printImplementedInterfaces(type) + printFields(type); -} -function printUnion(type) { - const types = type.getTypes(); - const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; - return printDescription(type) + 'union ' + type.name + possibleTypes; -} -function printEnum(type) { - const values = type.getValues().map((value, i) => printDescription(value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason)); - return printDescription(type) + `enum ${type.name}` + printBlock(values); -} -function printInputObject(type) { - const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f)); - return printDescription(type) + `input ${type.name}` + printBlock(fields); -} -function printFields(type) { - const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + f.name + printArgs(f.args, ' ') + ': ' + String(f.type) + printDeprecated(f.deprecationReason)); - return printBlock(fields); -} -function printBlock(items) { - return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; -} -function printArgs(args, indentation = '') { - if (args.length === 0) { - return ''; - } // If every arg does not have a description, print them on one line. - - if (args.every(arg => !arg.description)) { - return '(' + args.map(printInputValue).join(', ') + ')'; - } - return '(\n' + args.map((arg, i) => printDescription(arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg)).join('\n') + '\n' + indentation + ')'; -} -function printInputValue(arg) { - const defaultAST = (0, _astFromValue.astFromValue)(arg.defaultValue, arg.type); - let argDecl = arg.name + ': ' + String(arg.type); - if (defaultAST) { - argDecl += ` = ${(0, _printer.print)(defaultAST)}`; - } - return argDecl + printDeprecated(arg.deprecationReason); -} -function printDirective(directive) { - return printDescription(directive) + 'directive @' + directive.name + printArgs(directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | '); -} -function printDeprecated(reason) { - if (reason == null) { - return ''; - } - if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { - const astValue = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: reason - }); - return ` @deprecated(reason: ${astValue})`; - } - return ' @deprecated'; -} -function printSpecifiedByURL(scalar) { - if (scalar.specifiedByURL == null) { - return ''; - } - const astValue = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: scalar.specifiedByURL - }); - return ` @specifiedBy(url: ${astValue})`; -} -function printDescription(def, indentation = '', firstInBlock = true) { - const { - description - } = def; - if (description == null) { - return ''; - } - const blockString = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: description, - block: (0, _blockString.isPrintableAsBlockString)(description) - }); - const prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; - return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.typeFromAST = typeFromAST; + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case _kinds.Kind.LIST_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); + } + case _kinds.Kind.NON_NULL_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } + case _kinds.Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/separateOperations.mjs": -/*!**********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/separateOperations.mjs ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.separateOperations = separateOperations; -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); -/** - * separateOperations accepts a single AST document which may contain many - * operations and fragments and returns a collection of AST documents each of - * which contains a single operation as well the fragment definitions it - * refers to. - */ - -function separateOperations(documentAST) { - const operations = []; - const depGraph = Object.create(null); // Populate metadata and build a dependency graph. - - for (const definitionNode of documentAST.definitions) { - switch (definitionNode.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - operations.push(definitionNode); - break; - case _kinds.Kind.FRAGMENT_DEFINITION: - depGraph[definitionNode.name.value] = collectDependencies(definitionNode.selectionSet); - break; - default: // ignore non-executable definitions - } - } // For each operation, produce a new synthesized AST which includes only what - // is necessary for completing that operation. - - const separatedDocumentASTs = Object.create(null); - for (const operation of operations) { - const dependencies = new Set(); - for (const fragmentName of collectDependencies(operation.selectionSet)) { - collectTransitiveDependencies(dependencies, depGraph, fragmentName); - } // Provides the empty string for anonymous operations. - - const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted - // to retain the same order as the original document. - - separatedDocumentASTs[operationName] = { - kind: _kinds.Kind.DOCUMENT, - definitions: documentAST.definitions.filter(node => node === operation || node.kind === _kinds.Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value)) - }; - } - return separatedDocumentASTs; -} - -// From a dependency graph, collects a list of transitive dependencies by -// recursing through a dependency graph. -function collectTransitiveDependencies(collected, depGraph, fromName) { - if (!collected.has(fromName)) { - collected.add(fromName); - const immediateDeps = depGraph[fromName]; - if (immediateDeps !== undefined) { - for (const toName of immediateDeps) { - collectTransitiveDependencies(collected, depGraph, toName); - } - } - } -} -function collectDependencies(selectionSet) { - const dependencies = []; - (0, _visitor.visit)(selectionSet, { - FragmentSpread(node) { - dependencies.push(node.name.value); - } - }); - return dependencies; -} + /***/ "../../../node_modules/graphql/utilities/valueFromAST.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/valueFromAST.mjs ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.valueFromAST = valueFromAST; + var _inspect = __webpack_require__( + /*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _definition = __webpack_require__( + /*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | + * + */ -/***/ }), + function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (variables == null || variables[variableName] === undefined) { + // No valid return value. + return; + } + const variableValue = variables[variableName]; + if ( + variableValue === null && + (0, _definition.isNonNullType)(type) + ) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + return variableValue; + } + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. + } + return valueFromAST(valueNode, type.ofType, variables); + } + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if (valueNode.kind === _kinds.Kind.LIST) { + const coercedValues = []; + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(itemValue); + } + } + return coercedValues; + } + const coercedValue = valueFromAST(valueNode, itemType, variables); + if (coercedValue === undefined) { + return; // Invalid: intentionally return no value. + } + return [coercedValue]; + } + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + const coercedObj = Object.create(null); + const fieldNodes = (0, _keyMap.keyMap)( + valueNode.fields, + (field) => field.name.value + ); + for (const field of Object.values(type.getFields())) { + const fieldNode = fieldNodes[field.name]; + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } + continue; + } + const fieldValue = valueFromAST( + fieldNode.value, + field.type, + variables + ); + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + coercedObj[field.name] = fieldValue; + } + return coercedObj; + } + if ((0, _definition.isLeafType)(type)) { + // Scalars and Enums fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + if (result === undefined) { + return; // Invalid: intentionally return no value. + } + return result; + } + /* c8 ignore next 3 */ + // Not reachable, all possible input types have been considered. -/***/ "../../../node_modules/graphql/utilities/sortValueNode.mjs": -/*!*****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/sortValueNode.mjs ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.sortValueNode = sortValueNode; -var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -/** - * Sort ValueNode. - * - * This function returns a sorted copy of the given ValueNode. - * - * @internal - */ - -function sortValueNode(valueNode) { - switch (valueNode.kind) { - case _kinds.Kind.OBJECT: - return { - ...valueNode, - fields: sortFields(valueNode.fields) - }; - case _kinds.Kind.LIST: - return { - ...valueNode, - values: valueNode.values.map(sortValueNode) - }; - case _kinds.Kind.INT: - case _kinds.Kind.FLOAT: - case _kinds.Kind.STRING: - case _kinds.Kind.BOOLEAN: - case _kinds.Kind.NULL: - case _kinds.Kind.ENUM: - case _kinds.Kind.VARIABLE: - return valueNode; - } -} -function sortFields(fields) { - return fields.map(fieldNode => ({ - ...fieldNode, - value: sortValueNode(fieldNode.value) - })).sort((fieldA, fieldB) => (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value)); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs": -/*!**************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.stripIgnoredCharacters = stripIgnoredCharacters; -var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); -var _lexer = __webpack_require__(/*! ../language/lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); -var _source = __webpack_require__(/*! ../language/source.mjs */ "../../../node_modules/graphql/language/source.mjs"); -var _tokenKind = __webpack_require__(/*! ../language/tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); -/** - * Strips characters that are not significant to the validity or execution - * of a GraphQL document: - * - UnicodeBOM - * - WhiteSpace - * - LineTerminator - * - Comment - * - Comma - * - BlockString indentation - * - * Note: It is required to have a delimiter character between neighboring - * non-punctuator tokens and this function always uses single space as delimiter. - * - * It is guaranteed that both input and output documents if parsed would result - * in the exact same AST except for nodes location. - * - * Warning: It is guaranteed that this function will always produce stable results. - * However, it's not guaranteed that it will stay the same between different - * releases due to bugfixes or changes in the GraphQL specification. - * - * Query example: - * - * ```graphql - * query SomeQuery($foo: String!, $bar: String) { - * someField(foo: $foo, bar: $bar) { - * a - * b { - * c - * d - * } - * } - * } - * ``` - * - * Becomes: - * - * ```graphql - * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} - * ``` - * - * SDL example: - * - * ```graphql - * """ - * Type description - * """ - * type Foo { - * """ - * Field description - * """ - * bar: String - * } - * ``` - * - * Becomes: - * - * ```graphql - * """Type description""" type Foo{"""Field description""" bar:String} - * ``` - */ - -function stripIgnoredCharacters(source) { - const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); - const body = sourceObj.body; - const lexer = new _lexer.Lexer(sourceObj); - let strippedBody = ''; - let wasLastAddedTokenNonPunctuator = false; - while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { - const currentToken = lexer.token; - const tokenKind = currentToken.kind; - /** - * Every two non-punctuator tokens should have space between them. - * Also prevent case of non-punctuator token following by spread resulting - * in invalid token (e.g. `1...` is invalid Float token). - */ + false || + (0, _invariant.invariant)( + false, + "Unexpected input type: " + (0, _inspect.inspect)(type) + ); + } // Returns true if the provided valueNode is a variable which is not defined + // in the set of variables. - const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)(currentToken.kind); - if (wasLastAddedTokenNonPunctuator) { - if (isNonPunctuator || currentToken.kind === _tokenKind.TokenKind.SPREAD) { - strippedBody += ' '; - } - } - const tokenBody = body.slice(currentToken.start, currentToken.end); - if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { - strippedBody += (0, _blockString.printBlockString)(currentToken.value, { - minimize: true - }); - } else { - strippedBody += tokenBody; - } - wasLastAddedTokenNonPunctuator = isNonPunctuator; - } - return strippedBody; -} + function isMissingVariable(valueNode, variables) { + return ( + valueNode.kind === _kinds.Kind.VARIABLE && + (variables == null || variables[valueNode.name.value] === undefined) + ); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/typeComparators.mjs": -/*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/typeComparators.mjs ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.doTypesOverlap = doTypesOverlap; -exports.isEqualType = isEqualType; -exports.isTypeSubTypeOf = isTypeSubTypeOf; -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Provided two types, return true if the types are equal (invariant). - */ -function isEqualType(typeA, typeB) { - // Equivalent types are equal. - if (typeA === typeB) { - return true; - } // If either type is non-null, the other must also be non-null. - - if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) { - return isEqualType(typeA.ofType, typeB.ofType); - } // If either type is a list, the other must also be a list. - - if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) { - return isEqualType(typeA.ofType, typeB.ofType); - } // Otherwise the types are not equal. - - return false; -} -/** - * Provided a type and a super type, return true if the first type is either - * equal or a subset of the second super type (covariant). - */ - -function isTypeSubTypeOf(schema, maybeSubType, superType) { - // Equivalent type is a valid subtype - if (maybeSubType === superType) { - return true; - } // If superType is non-null, maybeSubType must also be non-null. + /***/ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs": + /*!***********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs ***! + \***********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.valueFromASTUntyped = valueFromASTUntyped; + var _keyValMap = __webpack_require__( + /*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs" + ); + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + /** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ - if ((0, _definition.isNonNullType)(superType)) { - if ((0, _definition.isNonNullType)(maybeSubType)) { - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); - } - return false; - } - if ((0, _definition.isNonNullType)(maybeSubType)) { - // If superType is nullable, maybeSubType may be non-null or nullable. - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); - } // If superType type is a list, maybeSubType type must also be a list. - - if ((0, _definition.isListType)(superType)) { - if ((0, _definition.isListType)(maybeSubType)) { - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); - } - return false; - } - if ((0, _definition.isListType)(maybeSubType)) { - // If superType is not a list, maybeSubType must also be not a list. - return false; - } // If superType type is an abstract type, check if it is super type of maybeSubType. - // Otherwise, the child type is not a valid subtype of the parent type. - - return (0, _definition.isAbstractType)(superType) && ((0, _definition.isInterfaceType)(maybeSubType) || (0, _definition.isObjectType)(maybeSubType)) && schema.isSubType(superType, maybeSubType); -} -/** - * Provided two composite types, determine if they "overlap". Two composite - * types overlap when the Sets of possible concrete types for each intersect. - * - * This is often used to determine if a fragment of a given type could possibly - * be visited in a context of another type. - * - * This function is commutative. - */ - -function doTypesOverlap(schema, typeA, typeB) { - // Equivalent types overlap - if (typeA === typeB) { - return true; - } - if ((0, _definition.isAbstractType)(typeA)) { - if ((0, _definition.isAbstractType)(typeB)) { - // If both types are abstract, then determine if there is any intersection - // between possible concrete types of each. - return schema.getPossibleTypes(typeA).some(type => schema.isSubType(typeB, type)); - } // Determine if the latter type is a possible concrete type of the former. - - return schema.isSubType(typeA, typeB); - } - if ((0, _definition.isAbstractType)(typeB)) { - // Determine if the former type is a possible concrete type of the latter. - return schema.isSubType(typeB, typeA); - } // Otherwise the types do not overlap. + function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; + case _kinds.Kind.LIST: + return valueNode.values.map((node) => + valueFromASTUntyped(node, variables) + ); + case _kinds.Kind.OBJECT: + return (0, _keyValMap.keyValMap)( + valueNode.fields, + (field) => field.name.value, + (field) => valueFromASTUntyped(field.value, variables) + ); + case _kinds.Kind.VARIABLE: + return variables === null || variables === void 0 + ? void 0 + : variables[valueNode.name.value]; + } + } + + /***/ + }, - return false; -} + /***/ "../../../node_modules/graphql/validation/ValidationContext.mjs": + /*!**********************************************************************!*\ + !*** ../../../node_modules/graphql/validation/ValidationContext.mjs ***! + \**********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.ValidationContext = + exports.SDLValidationContext = + exports.ASTValidationContext = + void 0; + var _kinds = __webpack_require__( + /*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _visitor = __webpack_require__( + /*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs" + ); + var _TypeInfo = __webpack_require__( + /*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs" + ); + /** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ + class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + get [Symbol.toStringTag]() { + return "ASTValidationContext"; + } + reportError(error) { + this._onError(error); + } + getDocument() { + return this._ast; + } + getFragment(name) { + let fragments; + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + this._fragments = fragments; + } + return fragments[name]; + } + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + while ((set = setsToVisit.pop())) { + for (const selection of set.selections) { + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + } + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit = [operation.selectionSet]; + let node; + while ((node = nodesToVisit.pop())) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } + } + exports.ASTValidationContext = ASTValidationContext; + class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } + get [Symbol.toStringTag]() { + return "SDLValidationContext"; + } + getSchema() { + return this._schema; + } + } + exports.SDLValidationContext = SDLValidationContext; + class ValidationContext extends ASTValidationContext { + constructor(schema, ast, typeInfo, onError) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + get [Symbol.toStringTag]() { + return "ValidationContext"; + } + getSchema() { + return this._schema; + } + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)( + node, + (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + }); + }, + }) + ); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + } + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + for (const frag of this.getRecursivelyReferencedFragments( + operation + )) { + usages = usages.concat(this.getVariableUsages(frag)); + } + this._recursiveVariableUsages.set(operation, usages); + } + return usages; + } + getType() { + return this._typeInfo.getType(); + } + getParentType() { + return this._typeInfo.getParentType(); + } + getInputType() { + return this._typeInfo.getInputType(); + } + getParentInputType() { + return this._typeInfo.getParentInputType(); + } + getFieldDef() { + return this._typeInfo.getFieldDef(); + } + getDirective() { + return this._typeInfo.getDirective(); + } + getArgument() { + return this._typeInfo.getArgument(); + } + getEnumValue() { + return this._typeInfo.getEnumValue(); + } + } + exports.ValidationContext = ValidationContext; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/typeFromAST.mjs": -/*!***************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/typeFromAST.mjs ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.typeFromAST = typeFromAST; -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -function typeFromAST(schema, typeNode) { - switch (typeNode.kind) { - case _kinds.Kind.LIST_TYPE: - { - const innerType = typeFromAST(schema, typeNode.type); - return innerType && new _definition.GraphQLList(innerType); - } - case _kinds.Kind.NON_NULL_TYPE: - { - const innerType = typeFromAST(schema, typeNode.type); - return innerType && new _definition.GraphQLNonNull(innerType); - } - case _kinds.Kind.NAMED_TYPE: - return schema.getType(typeNode.name.value); - } -} + /***/ "../../../node_modules/graphql/validation/index.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/validation/index.mjs ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "ExecutableDefinitionsRule", { + enumerable: true, + get: function () { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + }, + }); + Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function () { + return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; + }, + }); + Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function () { + return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; + }, + }); + Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function () { + return _KnownArgumentNamesRule.KnownArgumentNamesRule; + }, + }); + Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function () { + return _KnownDirectivesRule.KnownDirectivesRule; + }, + }); + Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function () { + return _KnownFragmentNamesRule.KnownFragmentNamesRule; + }, + }); + Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function () { + return _KnownTypeNamesRule.KnownTypeNamesRule; + }, + }); + Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function () { + return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; + }, + }); + Object.defineProperty(exports, "LoneSchemaDefinitionRule", { + enumerable: true, + get: function () { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + }, + }); + Object.defineProperty(exports, "NoDeprecatedCustomRule", { + enumerable: true, + get: function () { + return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; + }, + }); + Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function () { + return _NoFragmentCyclesRule.NoFragmentCyclesRule; + }, + }); + Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", { + enumerable: true, + get: function () { + return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; + }, + }); + Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function () { + return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; + }, + }); + Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function () { + return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; + }, + }); + Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function () { + return _NoUnusedVariablesRule.NoUnusedVariablesRule; + }, + }); + Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function () { + return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; + }, + }); + Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function () { + return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; + }, + }); + Object.defineProperty(exports, "PossibleTypeExtensionsRule", { + enumerable: true, + get: function () { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + }, + }); + Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function () { + return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; + }, + }); + Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function () { + return _ScalarLeafsRule.ScalarLeafsRule; + }, + }); + Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function () { + return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; + }, + }); + Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", { + enumerable: true, + get: function () { + return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function () { + return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueDirectiveNamesRule", { + enumerable: true, + get: function () { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function () { + return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; + }, + }); + Object.defineProperty(exports, "UniqueEnumValueNamesRule", { + enumerable: true, + get: function () { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", { + enumerable: true, + get: function () { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function () { + return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function () { + return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function () { + return _UniqueOperationNamesRule.UniqueOperationNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueOperationTypesRule", { + enumerable: true, + get: function () { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + }, + }); + Object.defineProperty(exports, "UniqueTypeNamesRule", { + enumerable: true, + get: function () { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + }, + }); + Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function () { + return _UniqueVariableNamesRule.UniqueVariableNamesRule; + }, + }); + Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function () { + return _ValidationContext.ValidationContext; + }, + }); + Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function () { + return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; + }, + }); + Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function () { + return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; + }, + }); + Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function () { + return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; + }, + }); + Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function () { + return _specifiedRules.specifiedRules; + }, + }); + Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.validate; + }, + }); + var _validate = __webpack_require__( + /*! ./validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs" + ); + var _ValidationContext = __webpack_require__( + /*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs" + ); + var _specifiedRules = __webpack_require__( + /*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs" + ); + var _ExecutableDefinitionsRule = __webpack_require__( + /*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs" + ); + var _FieldsOnCorrectTypeRule = __webpack_require__( + /*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs" + ); + var _FragmentsOnCompositeTypesRule = __webpack_require__( + /*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs" + ); + var _KnownArgumentNamesRule = __webpack_require__( + /*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs" + ); + var _KnownDirectivesRule = __webpack_require__( + /*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs" + ); + var _KnownFragmentNamesRule = __webpack_require__( + /*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs" + ); + var _KnownTypeNamesRule = __webpack_require__( + /*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs" + ); + var _LoneAnonymousOperationRule = __webpack_require__( + /*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs" + ); + var _NoFragmentCyclesRule = __webpack_require__( + /*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs" + ); + var _NoUndefinedVariablesRule = __webpack_require__( + /*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs" + ); + var _NoUnusedFragmentsRule = __webpack_require__( + /*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs" + ); + var _NoUnusedVariablesRule = __webpack_require__( + /*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs" + ); + var _OverlappingFieldsCanBeMergedRule = __webpack_require__( + /*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs" + ); + var _PossibleFragmentSpreadsRule = __webpack_require__( + /*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs" + ); + var _ProvidedRequiredArgumentsRule = __webpack_require__( + /*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs" + ); + var _ScalarLeafsRule = __webpack_require__( + /*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs" + ); + var _SingleFieldSubscriptionsRule = __webpack_require__( + /*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs" + ); + var _UniqueArgumentNamesRule = __webpack_require__( + /*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs" + ); + var _UniqueDirectivesPerLocationRule = __webpack_require__( + /*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs" + ); + var _UniqueFragmentNamesRule = __webpack_require__( + /*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs" + ); + var _UniqueInputFieldNamesRule = __webpack_require__( + /*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs" + ); + var _UniqueOperationNamesRule = __webpack_require__( + /*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs" + ); + var _UniqueVariableNamesRule = __webpack_require__( + /*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs" + ); + var _ValuesOfCorrectTypeRule = __webpack_require__( + /*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs" + ); + var _VariablesAreInputTypesRule = __webpack_require__( + /*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs" + ); + var _VariablesInAllowedPositionRule = __webpack_require__( + /*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs" + ); + var _LoneSchemaDefinitionRule = __webpack_require__( + /*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs" + ); + var _UniqueOperationTypesRule = __webpack_require__( + /*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs" + ); + var _UniqueTypeNamesRule = __webpack_require__( + /*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs" + ); + var _UniqueEnumValueNamesRule = __webpack_require__( + /*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs" + ); + var _UniqueFieldDefinitionNamesRule = __webpack_require__( + /*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs" + ); + var _UniqueArgumentDefinitionNamesRule = __webpack_require__( + /*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs" + ); + var _UniqueDirectiveNamesRule = __webpack_require__( + /*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs" + ); + var _PossibleTypeExtensionsRule = __webpack_require__( + /*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs" + ); + var _NoDeprecatedCustomRule = __webpack_require__( + /*! ./rules/custom/NoDeprecatedCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs" + ); + var _NoSchemaIntrospectionCustomRule = __webpack_require__( + /*! ./rules/custom/NoSchemaIntrospectionCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs" + ); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/utilities/valueFromAST.mjs": -/*!****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/valueFromAST.mjs ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.valueFromAST = valueFromAST; -var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Produces a JavaScript value given a GraphQL Value AST. - * - * A GraphQL type must be provided, which will be used to interpret different - * GraphQL Value literals. - * - * Returns `undefined` when the value could not be validly coerced according to - * the provided type. - * - * | GraphQL Value | JSON Value | - * | -------------------- | ------------- | - * | Input Object | Object | - * | List | Array | - * | Boolean | Boolean | - * | String | String | - * | Int / Float | Number | - * | Enum Value | Unknown | - * | NullValue | null | - * - */ - -function valueFromAST(valueNode, type, variables) { - if (!valueNode) { - // When there is no node, then there is also no value. - // Importantly, this is different from returning the value null. - return; - } - if (valueNode.kind === _kinds.Kind.VARIABLE) { - const variableName = valueNode.name.value; - if (variables == null || variables[variableName] === undefined) { - // No valid return value. - return; - } - const variableValue = variables[variableName]; - if (variableValue === null && (0, _definition.isNonNullType)(type)) { - return; // Invalid: intentionally return no value. - } // Note: This does no further checking that this variable is correct. - // This assumes that this query has been validated and the variable - // usage here is of the correct type. - - return variableValue; - } - if ((0, _definition.isNonNullType)(type)) { - if (valueNode.kind === _kinds.Kind.NULL) { - return; // Invalid: intentionally return no value. - } - return valueFromAST(valueNode, type.ofType, variables); - } - if (valueNode.kind === _kinds.Kind.NULL) { - // This is explicitly returning the value null. - return null; - } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; - if (valueNode.kind === _kinds.Kind.LIST) { - const coercedValues = []; - for (const itemNode of valueNode.values) { - if (isMissingVariable(itemNode, variables)) { - // If an array contains a missing variable, it is either coerced to - // null or if the item type is non-null, it considered invalid. - if ((0, _definition.isNonNullType)(itemType)) { - return; // Invalid: intentionally return no value. - } - coercedValues.push(null); - } else { - const itemValue = valueFromAST(itemNode, itemType, variables); - if (itemValue === undefined) { - return; // Invalid: intentionally return no value. - } - coercedValues.push(itemValue); + /***/ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs": + /*!************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs ***! + \************************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _predicates = __webpack_require__( + /*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs" + ); + /** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + */ + function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + const defName = + definition.kind === _kinds.Kind.SCHEMA_DEFINITION || + definition.kind === _kinds.Kind.SCHEMA_EXTENSION + ? "schema" + : '"' + definition.name.value + '"'; + context.reportError( + new _GraphQLError.GraphQLError( + `The ${defName} definition is not executable.`, + { + nodes: definition, + } + ) + ); + } + } + return false; + }, + }; } - } - return coercedValues; - } - const coercedValue = valueFromAST(valueNode, itemType, variables); - if (coercedValue === undefined) { - return; // Invalid: intentionally return no value. - } - return [coercedValue]; - } - if ((0, _definition.isInputObjectType)(type)) { - if (valueNode.kind !== _kinds.Kind.OBJECT) { - return; // Invalid: intentionally return no value. - } - const coercedObj = Object.create(null); - const fieldNodes = (0, _keyMap.keyMap)(valueNode.fields, field => field.name.value); - for (const field of Object.values(type.getFields())) { - const fieldNode = fieldNodes[field.name]; - if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { - if (field.defaultValue !== undefined) { - coercedObj[field.name] = field.defaultValue; - } else if ((0, _definition.isNonNullType)(field.type)) { - return; // Invalid: intentionally return no value. - } - continue; - } - const fieldValue = valueFromAST(fieldNode.value, field.type, variables); - if (fieldValue === undefined) { - return; // Invalid: intentionally return no value. - } - coercedObj[field.name] = fieldValue; - } - return coercedObj; - } - if ((0, _definition.isLeafType)(type)) { - // Scalars and Enums fulfill parsing a literal value via parseLiteral(). - // Invalid values represent a failure to parse correctly, in which case - // no value is returned. - let result; - try { - result = type.parseLiteral(valueNode, variables); - } catch (_error) { - return; // Invalid: intentionally return no value. - } - if (result === undefined) { - return; // Invalid: intentionally return no value. - } - return result; - } - /* c8 ignore next 3 */ - // Not reachable, all possible input types have been considered. - false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); -} // Returns true if the provided valueNode is a variable which is not defined -// in the set of variables. - -function isMissingVariable(valueNode, variables) { - return valueNode.kind === _kinds.Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined); -} - -/***/ }), - -/***/ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs": -/*!***********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs ***! - \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.valueFromASTUntyped = valueFromASTUntyped; -var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -/** - * Produces a JavaScript value given a GraphQL Value AST. - * - * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value - * will reflect the provided GraphQL value AST. - * - * | GraphQL Value | JavaScript Value | - * | -------------------- | ---------------- | - * | Input Object | Object | - * | List | Array | - * | Boolean | Boolean | - * | String / Enum | String | - * | Int / Float | Number | - * | Null | null | - * - */ - -function valueFromASTUntyped(valueNode, variables) { - switch (valueNode.kind) { - case _kinds.Kind.NULL: - return null; - case _kinds.Kind.INT: - return parseInt(valueNode.value, 10); - case _kinds.Kind.FLOAT: - return parseFloat(valueNode.value); - case _kinds.Kind.STRING: - case _kinds.Kind.ENUM: - case _kinds.Kind.BOOLEAN: - return valueNode.value; - case _kinds.Kind.LIST: - return valueNode.values.map(node => valueFromASTUntyped(node, variables)); - case _kinds.Kind.OBJECT: - return (0, _keyValMap.keyValMap)(valueNode.fields, field => field.name.value, field => valueFromASTUntyped(field.value, variables)); - case _kinds.Kind.VARIABLE: - return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value]; - } -} - -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/ValidationContext.mjs": -/*!**********************************************************************!*\ - !*** ../../../node_modules/graphql/validation/ValidationContext.mjs ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; -var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); -var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); -/** - * An instance of this class is passed as the "this" context to all validators, - * allowing access to commonly useful contextual information from within a - * validation rule. - */ -class ASTValidationContext { - constructor(ast, onError) { - this._ast = ast; - this._fragments = undefined; - this._fragmentSpreads = new Map(); - this._recursivelyReferencedFragments = new Map(); - this._onError = onError; - } - get [Symbol.toStringTag]() { - return 'ASTValidationContext'; - } - reportError(error) { - this._onError(error); - } - getDocument() { - return this._ast; - } - getFragment(name) { - let fragments; - if (this._fragments) { - fragments = this._fragments; - } else { - fragments = Object.create(null); - for (const defNode of this.getDocument().definitions) { - if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { - fragments[defNode.name.value] = defNode; + /***/ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs ***! + \**********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; + var _didYouMean = __webpack_require__( + /*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _naturalCompare = __webpack_require__( + /*! ../../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + */ + function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + let suggestion = (0, _didYouMean.didYouMean)( + "to use an inline fragment on", + getSuggestedTypeNames(schema, type, fieldName) + ); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === "") { + suggestion = (0, _didYouMean.didYouMean)( + getSuggestedFieldNames(type, fieldName) + ); + } // Report an error, including helpful suggestions. + + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot query field "${fieldName}" on type "${type.name}".` + + suggestion, + { + nodes: node, + } + ) + ); + } + } + }, + }; } - } - this._fragments = fragments; - } - return fragments[name]; - } - getFragmentSpreads(node) { - let spreads = this._fragmentSpreads.get(node); - if (!spreads) { - spreads = []; - const setsToVisit = [node]; - let set; - while (set = setsToVisit.pop()) { - for (const selection of set.selections) { - if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { - spreads.push(selection); - } else if (selection.selectionSet) { - setsToVisit.push(selection.selectionSet); + /** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ + + function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, _definition.isAbstractType)(type)) { + // Must be an Object type, which does not have possible fields. + return []; } - } - } - this._fragmentSpreads.set(node, spreads); - } - return spreads; - } - getRecursivelyReferencedFragments(operation) { - let fragments = this._recursivelyReferencedFragments.get(operation); - if (!fragments) { - fragments = []; - const collectedNames = Object.create(null); - const nodesToVisit = [operation.selectionSet]; - let node; - while (node = nodesToVisit.pop()) { - for (const spread of this.getFragmentSpreads(node)) { - const fragName = spread.name.value; - if (collectedNames[fragName] !== true) { - collectedNames[fragName] = true; - const fragment = this.getFragment(fragName); - if (fragment) { - fragments.push(fragment); - nodesToVisit.push(fragment.selectionSet); + const suggestedTypes = new Set(); + const usageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + for (const possibleInterface of possibleType.getInterfaces()) { + var _usageCount$possibleI; + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = + ((_usageCount$possibleI = + usageCount[possibleInterface.name]) !== null && + _usageCount$possibleI !== void 0 + ? _usageCount$possibleI + : 0) + 1; } } + return [...suggestedTypes] + .sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = + usageCount[typeB.name] - usageCount[typeA.name]; + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + if ( + (0, _definition.isInterfaceType)(typeA) && + schema.isSubType(typeA, typeB) + ) { + return -1; + } + if ( + (0, _definition.isInterfaceType)(typeB) && + schema.isSubType(typeB, typeA) + ) { + return 1; + } + return (0, _naturalCompare.naturalCompare)( + typeA.name, + typeB.name + ); + }) + .map((x) => x.name); } - } - this._recursivelyReferencedFragments.set(operation, fragments); - } - return fragments; - } -} -exports.ASTValidationContext = ASTValidationContext; -class SDLValidationContext extends ASTValidationContext { - constructor(ast, schema, onError) { - super(ast, onError); - this._schema = schema; - } - get [Symbol.toStringTag]() { - return 'SDLValidationContext'; - } - getSchema() { - return this._schema; - } -} -exports.SDLValidationContext = SDLValidationContext; -class ValidationContext extends ASTValidationContext { - constructor(schema, ast, typeInfo, onError) { - super(ast, onError); - this._schema = schema; - this._typeInfo = typeInfo; - this._variableUsages = new Map(); - this._recursiveVariableUsages = new Map(); - } - get [Symbol.toStringTag]() { - return 'ValidationContext'; - } - getSchema() { - return this._schema; - } - getVariableUsages(node) { - let usages = this._variableUsages.get(node); - if (!usages) { - const newUsages = []; - const typeInfo = new _TypeInfo.TypeInfo(this._schema); - (0, _visitor.visit)(node, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { - VariableDefinition: () => false, - Variable(variable) { - newUsages.push({ - node: variable, - type: typeInfo.getInputType(), - defaultValue: typeInfo.getDefaultValue() - }); - } - })); - usages = newUsages; - this._variableUsages.set(node, usages); - } - return usages; - } - getRecursiveVariableUsages(operation) { - let usages = this._recursiveVariableUsages.get(operation); - if (!usages) { - usages = this.getVariableUsages(operation); - for (const frag of this.getRecursivelyReferencedFragments(operation)) { - usages = usages.concat(this.getVariableUsages(frag)); - } - this._recursiveVariableUsages.set(operation, usages); - } - return usages; - } - getType() { - return this._typeInfo.getType(); - } - getParentType() { - return this._typeInfo.getParentType(); - } - getInputType() { - return this._typeInfo.getInputType(); - } - getParentInputType() { - return this._typeInfo.getParentInputType(); - } - getFieldDef() { - return this._typeInfo.getFieldDef(); - } - getDirective() { - return this._typeInfo.getDirective(); - } - getArgument() { - return this._typeInfo.getArgument(); - } - getEnumValue() { - return this._typeInfo.getEnumValue(); - } -} -exports.ValidationContext = ValidationContext; - -/***/ }), - -/***/ "../../../node_modules/graphql/validation/index.mjs": -/*!**********************************************************!*\ - !*** ../../../node_modules/graphql/validation/index.mjs ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - + /** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + function getSuggestedFieldNames(type, fieldName) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + const possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.suggestionList)( + fieldName, + possibleFieldNames + ); + } // Otherwise, must be a Union type, which does not define fields. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ - enumerable: true, - get: function () { - return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; - } -})); -Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; - } -})); -Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ - enumerable: true, - get: function () { - return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; - } -})); -Object.defineProperty(exports, "KnownArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _KnownArgumentNamesRule.KnownArgumentNamesRule; - } -})); -Object.defineProperty(exports, "KnownDirectivesRule", ({ - enumerable: true, - get: function () { - return _KnownDirectivesRule.KnownDirectivesRule; - } -})); -Object.defineProperty(exports, "KnownFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _KnownFragmentNamesRule.KnownFragmentNamesRule; - } -})); -Object.defineProperty(exports, "KnownTypeNamesRule", ({ - enumerable: true, - get: function () { - return _KnownTypeNamesRule.KnownTypeNamesRule; - } -})); -Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ - enumerable: true, - get: function () { - return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; - } -})); -Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ - enumerable: true, - get: function () { - return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; - } -})); -Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ - enumerable: true, - get: function () { - return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; - } -})); -Object.defineProperty(exports, "NoFragmentCyclesRule", ({ - enumerable: true, - get: function () { - return _NoFragmentCyclesRule.NoFragmentCyclesRule; - } -})); -Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ - enumerable: true, - get: function () { - return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; - } -})); -Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ - enumerable: true, - get: function () { - return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; - } -})); -Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ - enumerable: true, - get: function () { - return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; - } -})); -Object.defineProperty(exports, "NoUnusedVariablesRule", ({ - enumerable: true, - get: function () { - return _NoUnusedVariablesRule.NoUnusedVariablesRule; - } -})); -Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ - enumerable: true, - get: function () { - return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; - } -})); -Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ - enumerable: true, - get: function () { - return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; - } -})); -Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ - enumerable: true, - get: function () { - return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; - } -})); -Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ - enumerable: true, - get: function () { - return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; - } -})); -Object.defineProperty(exports, "ScalarLeafsRule", ({ - enumerable: true, - get: function () { - return _ScalarLeafsRule.ScalarLeafsRule; - } -})); -Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ - enumerable: true, - get: function () { - return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; - } -})); -Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; - } -})); -Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; - } -})); -Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; - } -})); -Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ - enumerable: true, - get: function () { - return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; - } -})); -Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; - } -})); -Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; - } -})); -Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; - } -})); -Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; - } -})); -Object.defineProperty(exports, "UniqueOperationNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueOperationNamesRule.UniqueOperationNamesRule; - } -})); -Object.defineProperty(exports, "UniqueOperationTypesRule", ({ - enumerable: true, - get: function () { - return _UniqueOperationTypesRule.UniqueOperationTypesRule; - } -})); -Object.defineProperty(exports, "UniqueTypeNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueTypeNamesRule.UniqueTypeNamesRule; - } -})); -Object.defineProperty(exports, "UniqueVariableNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueVariableNamesRule.UniqueVariableNamesRule; - } -})); -Object.defineProperty(exports, "ValidationContext", ({ - enumerable: true, - get: function () { - return _ValidationContext.ValidationContext; - } -})); -Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; - } -})); -Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ - enumerable: true, - get: function () { - return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; - } -})); -Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ - enumerable: true, - get: function () { - return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; - } -})); -Object.defineProperty(exports, "specifiedRules", ({ - enumerable: true, - get: function () { - return _specifiedRules.specifiedRules; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.validate; - } -})); -var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); -var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); -var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); -var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); -var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); -var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); -var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); -var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); -var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); -var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); -var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); -var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); -var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); -var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); -var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); -var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); -var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); -var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); -var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); -var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); -var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); -var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); -var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); -var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); -var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); -var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); -var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); -var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); -var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); -var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); -var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); -var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); -var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); -var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); -var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); -var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); -var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); -var _NoDeprecatedCustomRule = __webpack_require__(/*! ./rules/custom/NoDeprecatedCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs"); -var _NoSchemaIntrospectionCustomRule = __webpack_require__(/*! ./rules/custom/NoSchemaIntrospectionCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs"); - -/***/ }), - -/***/ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs": -/*!************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs ***! - \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); -/** - * Executable definitions - * - * A GraphQL document is only valid for execution if all definitions are either - * operation or fragment definitions. - * - * See https://spec.graphql.org/draft/#sec-Executable-Definitions - */ -function ExecutableDefinitionsRule(context) { - return { - Document(node) { - for (const definition of node.definitions) { - if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { - const defName = definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"'; - context.reportError(new _GraphQLError.GraphQLError(`The ${defName} definition is not executable.`, { - nodes: definition - })); + return []; } - } - return false; - } - }; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs": -/*!**********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; -var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _naturalCompare = __webpack_require__(/*! ../../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); -var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Fields on correct type - * - * A GraphQL document is only valid if all fields selected are defined by the - * parent type, or are an allowed meta field such as __typename. - * - * See https://spec.graphql.org/draft/#sec-Field-Selections - */ -function FieldsOnCorrectTypeRule(context) { - return { - Field(node) { - const type = context.getParentType(); - if (type) { - const fieldDef = context.getFieldDef(); - if (!fieldDef) { - // This field doesn't exist, lets look for suggestions. - const schema = context.getSchema(); - const fieldName = node.name.value; // First determine if there are any suggested types to condition on. - let suggestion = (0, _didYouMean.didYouMean)('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo? - - if (suggestion === '') { - suggestion = (0, _didYouMean.didYouMean)(getSuggestedFieldNames(type, fieldName)); - } // Report an error, including helpful suggestions. + /***/ + }, - context.reportError(new _GraphQLError.GraphQLError(`Cannot query field "${fieldName}" on type "${type.name}".` + suggestion, { - nodes: node - })); - } - } - } - }; -} -/** - * Go through all of the implementations of type, as well as the interfaces that - * they implement. If any of those types include the provided field, suggest them, - * sorted by how often the type is referenced. - */ - -function getSuggestedTypeNames(schema, type, fieldName) { - if (!(0, _definition.isAbstractType)(type)) { - // Must be an Object type, which does not have possible fields. - return []; - } - const suggestedTypes = new Set(); - const usageCount = Object.create(null); - for (const possibleType of schema.getPossibleTypes(type)) { - if (!possibleType.getFields()[fieldName]) { - continue; - } // This object type defines this field. - - suggestedTypes.add(possibleType); - usageCount[possibleType.name] = 1; - for (const possibleInterface of possibleType.getInterfaces()) { - var _usageCount$possibleI; - if (!possibleInterface.getFields()[fieldName]) { - continue; - } // This interface type defines this field. - - suggestedTypes.add(possibleInterface); - usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1; - } - } - return [...suggestedTypes].sort((typeA, typeB) => { - // Suggest both interface and object types based on how common they are. - const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; - if (usageCountDiff !== 0) { - return usageCountDiff; - } // Suggest super types first followed by subtypes - - if ((0, _definition.isInterfaceType)(typeA) && schema.isSubType(typeA, typeB)) { - return -1; - } - if ((0, _definition.isInterfaceType)(typeB) && schema.isSubType(typeB, typeA)) { - return 1; - } - return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); - }).map(x => x.name); -} -/** - * For the field name provided, determine if there are any similar field names - * that may be the result of a typo. - */ - -function getSuggestedFieldNames(type, fieldName) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { - const possibleFieldNames = Object.keys(type.getFields()); - return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); - } // Otherwise, must be a Union type, which does not define fields. - - return []; -} - -/***/ }), - -/***/ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs": -/*!****************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs": + /*!****************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs ***! \****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -/** - * Fragments on composite type - * - * Fragments use a type condition to determine if they apply, since fragments - * can only be spread into a composite type (object, interface, or union), the - * type condition must also be a composite type. - * - * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types - */ -function FragmentsOnCompositeTypesRule(context) { - return { - InlineFragment(node) { - const typeCondition = node.typeCondition; - if (typeCondition) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); - if (type && !(0, _definition.isCompositeType)(type)) { - const typeStr = (0, _printer.print)(typeCondition); - context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot condition on non composite type "${typeStr}".`, { - nodes: typeCondition - })); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _printer = __webpack_require__( + /*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + /** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + */ + function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + typeCondition + ); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(typeCondition); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment cannot condition on non composite type "${typeStr}".`, + { + nodes: typeCondition, + } + ) + ); + } + } + }, + FragmentDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + node.typeCondition + ); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(node.typeCondition); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, + { + nodes: node.typeCondition, + } + ) + ); + } + }, + }; } - } - }, - FragmentDefinition(node) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); - if (type && !(0, _definition.isCompositeType)(type)) { - const typeStr = (0, _printer.print)(node.typeCondition); - context.reportError(new _GraphQLError.GraphQLError(`Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, { - nodes: node.typeCondition - })); - } - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs": -/*!*********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs": + /*!*********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs ***! \*********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; -exports.KnownArgumentNamesRule = KnownArgumentNamesRule; -var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -/** - * Known argument names - * - * A GraphQL field is only valid if all supplied arguments are defined by - * that field. - * - * See https://spec.graphql.org/draft/#sec-Argument-Names - * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations - */ -function KnownArgumentNamesRule(context) { - return { - // eslint-disable-next-line new-cap - ...KnownArgumentNamesOnDirectivesRule(context), - Argument(argNode) { - const argDef = context.getArgument(); - const fieldDef = context.getFieldDef(); - const parentType = context.getParentType(); - if (!argDef && fieldDef && parentType) { - const argName = argNode.name.value; - const knownArgsNames = fieldDef.args.map(arg => arg.name); - const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgsNames); - context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + (0, _didYouMean.didYouMean)(suggestions), { - nodes: argNode - })); - } - } - }; -} -/** - * @internal - */ - -function KnownArgumentNamesOnDirectivesRule(context) { - const directiveArgs = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - directiveArgs[directive.name] = directive.args.map(arg => arg.name); - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - var _def$arguments; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.KnownArgumentNamesOnDirectivesRule = + KnownArgumentNamesOnDirectivesRule; + exports.KnownArgumentNamesRule = KnownArgumentNamesRule; + var _didYouMean = __webpack_require__( + /*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _directives = __webpack_require__( + /*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + /** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + */ + function KnownArgumentNamesRule(context) { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map((arg) => arg.name); + const suggestions = (0, _suggestionList.suggestionList)( + argName, + knownArgsNames + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: argNode, + } + ) + ); + } + }, + }; + } + /** + * @internal + */ - /* c8 ignore next */ - const argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; - directiveArgs[def.name.value] = argsNodes.map(arg => arg.name.value); - } - } - return { - Directive(directiveNode) { - const directiveName = directiveNode.name.value; - const knownArgs = directiveArgs[directiveName]; - if (directiveNode.arguments && knownArgs) { - for (const argNode of directiveNode.arguments) { - const argName = argNode.name.value; - if (!knownArgs.includes(argName)) { - const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgs); - context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on directive "@${directiveName}".` + (0, _didYouMean.didYouMean)(suggestions), { - nodes: argNode - })); + function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map( + (arg) => arg.name + ); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argsNodes = + (_def$arguments = def.arguments) !== null && + _def$arguments !== void 0 + ? _def$arguments + : []; + directiveArgs[def.name.value] = argsNodes.map( + (arg) => arg.name.value + ); + } } + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (!knownArgs.includes(argName)) { + const suggestions = (0, _suggestionList.suggestionList)( + argName, + knownArgs + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown argument "${argName}" on directive "@${directiveName}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: argNode, + } + ) + ); + } + } + } + return false; + }, + }; } - } - return false; - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs": -/*!******************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs": + /*!******************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs ***! \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.KnownDirectivesRule = KnownDirectivesRule; -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _ast = __webpack_require__(/*! ../../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); -var _directiveLocation = __webpack_require__(/*! ../../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -/** - * Known directives - * - * A GraphQL document is only valid if all `@directives` are known by the - * schema and legally positioned. - * - * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined - */ -function KnownDirectivesRule(context) { - const locationsMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - locationsMap[directive.name] = directive.locations; - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - locationsMap[def.name.value] = def.locations.map(name => name.value); - } - } - return { - Directive(node, _key, _parent, _path, ancestors) { - const name = node.name.value; - const locations = locationsMap[name]; - if (!locations) { - context.reportError(new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { - nodes: node - })); - return; - } - const candidateLocation = getDirectiveLocationForASTPath(ancestors); - if (candidateLocation && !locations.includes(candidateLocation)) { - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${name}" may not be used on ${candidateLocation}.`, { - nodes: node - })); - } - } - }; -} -function getDirectiveLocationForASTPath(ancestors) { - const appliedTo = ancestors[ancestors.length - 1]; - 'kind' in appliedTo || (0, _invariant.invariant)(false); - switch (appliedTo.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - return getDirectiveLocationForOperation(appliedTo.operation); - case _kinds.Kind.FIELD: - return _directiveLocation.DirectiveLocation.FIELD; - case _kinds.Kind.FRAGMENT_SPREAD: - return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; - case _kinds.Kind.INLINE_FRAGMENT: - return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; - case _kinds.Kind.FRAGMENT_DEFINITION: - return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; - case _kinds.Kind.VARIABLE_DEFINITION: - return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; - case _kinds.Kind.SCHEMA_DEFINITION: - case _kinds.Kind.SCHEMA_EXTENSION: - return _directiveLocation.DirectiveLocation.SCHEMA; - case _kinds.Kind.SCALAR_TYPE_DEFINITION: - case _kinds.Kind.SCALAR_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.SCALAR; - case _kinds.Kind.OBJECT_TYPE_DEFINITION: - case _kinds.Kind.OBJECT_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.OBJECT; - case _kinds.Kind.FIELD_DEFINITION: - return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; - case _kinds.Kind.INTERFACE_TYPE_DEFINITION: - case _kinds.Kind.INTERFACE_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.INTERFACE; - case _kinds.Kind.UNION_TYPE_DEFINITION: - case _kinds.Kind.UNION_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.UNION; - case _kinds.Kind.ENUM_TYPE_DEFINITION: - case _kinds.Kind.ENUM_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.ENUM; - case _kinds.Kind.ENUM_VALUE_DEFINITION: - return _directiveLocation.DirectiveLocation.ENUM_VALUE; - case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: - case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.INPUT_OBJECT; - case _kinds.Kind.INPUT_VALUE_DEFINITION: - { - const parentNode = ancestors[ancestors.length - 3]; - 'kind' in parentNode || (0, _invariant.invariant)(false); - return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; - } - // Not reachable, all possible types have been considered. + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.KnownDirectivesRule = KnownDirectivesRule; + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _ast = __webpack_require__( + /*! ../../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs" + ); + var _directiveLocation = __webpack_require__( + /*! ../../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _directives = __webpack_require__( + /*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + /** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + */ + function KnownDirectivesRule(context) { + const locationsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map( + (name) => name.value + ); + } + } + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + if (!locations) { + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown directive "@${name}".`, + { + nodes: node, + } + ) + ); + return; + } + const candidateLocation = + getDirectiveLocationForASTPath(ancestors); + if (candidateLocation && !locations.includes(candidateLocation)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${name}" may not be used on ${candidateLocation}.`, + { + nodes: node, + } + ) + ); + } + }, + }; + } + function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + "kind" in appliedTo || (0, _invariant.invariant)(false); + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + case _kinds.Kind.INPUT_VALUE_DEFINITION: { + const parentNode = ancestors[ancestors.length - 3]; + "kind" in parentNode || (0, _invariant.invariant)(false); + return parentNode.kind === + _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION + ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION + : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + // Not reachable, all possible types have been considered. - /* c8 ignore next */ + /* c8 ignore next */ - default: - false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind)); - } -} -function getDirectiveLocationForOperation(operation) { - switch (operation) { - case _ast.OperationTypeNode.QUERY: - return _directiveLocation.DirectiveLocation.QUERY; - case _ast.OperationTypeNode.MUTATION: - return _directiveLocation.DirectiveLocation.MUTATION; - case _ast.OperationTypeNode.SUBSCRIPTION: - return _directiveLocation.DirectiveLocation.SUBSCRIPTION; - } -} + default: + false || + (0, _invariant.invariant)( + false, + "Unexpected kind: " + (0, _inspect.inspect)(appliedTo.kind) + ); + } + } + function getDirectiveLocationForOperation(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return _directiveLocation.DirectiveLocation.QUERY; + case _ast.OperationTypeNode.MUTATION: + return _directiveLocation.DirectiveLocation.MUTATION; + case _ast.OperationTypeNode.SUBSCRIPTION: + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs": -/*!*********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs": + /*!*********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs ***! \*********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.KnownFragmentNamesRule = KnownFragmentNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Known fragment names - * - * A GraphQL document is only valid if all `...Fragment` fragment spreads refer - * to fragments defined in the same document. - * - * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined - */ -function KnownFragmentNamesRule(context) { - return { - FragmentSpread(node) { - const fragmentName = node.name.value; - const fragment = context.getFragment(fragmentName); - if (!fragment) { - context.reportError(new _GraphQLError.GraphQLError(`Unknown fragment "${fragmentName}".`, { - nodes: node.name - })); - } - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.KnownFragmentNamesRule = KnownFragmentNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined + */ + function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown fragment "${fragmentName}".`, + { + nodes: node.name, + } + ) + ); + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs": -/*!*****************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs": + /*!*****************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs ***! \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.KnownTypeNamesRule = KnownTypeNamesRule; -var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); -var _introspection = __webpack_require__(/*! ../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -var _scalars = __webpack_require__(/*! ../../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); -/** - * Known type names - * - * A GraphQL document is only valid if referenced types (specifically - * variable definitions and fragment conditions) are defined by the type schema. - * - * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence - */ -function KnownTypeNamesRule(context) { - const schema = context.getSchema(); - const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); - const definedTypes = Object.create(null); - for (const def of context.getDocument().definitions) { - if ((0, _predicates.isTypeDefinitionNode)(def)) { - definedTypes[def.name.value] = true; - } - } - const typeNames = [...Object.keys(existingTypesMap), ...Object.keys(definedTypes)]; - return { - NamedType(node, _1, parent, _2, ancestors) { - const typeName = node.name.value; - if (!existingTypesMap[typeName] && !definedTypes[typeName]) { - var _ancestors$; - const definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent; - const isSDL = definitionNode != null && isSDLNode(definitionNode); - if (isSDL && standardTypeNames.includes(typeName)) { - return; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.KnownTypeNamesRule = KnownTypeNamesRule; + var _didYouMean = __webpack_require__( + /*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _predicates = __webpack_require__( + /*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs" + ); + var _introspection = __webpack_require__( + /*! ../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + var _scalars = __webpack_require__( + /*! ../../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs" + ); + /** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + */ + function KnownTypeNamesRule(context) { + const schema = context.getSchema(); + const existingTypesMap = schema + ? schema.getTypeMap() + : Object.create(null); + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = true; + } + } + const typeNames = [ + ...Object.keys(existingTypesMap), + ...Object.keys(definedTypes), + ]; + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + const definitionNode = + (_ancestors$ = ancestors[2]) !== null && + _ancestors$ !== void 0 + ? _ancestors$ + : parent; + const isSDL = + definitionNode != null && isSDLNode(definitionNode); + if (isSDL && standardTypeNames.includes(typeName)) { + return; + } + const suggestedTypes = (0, _suggestionList.suggestionList)( + typeName, + isSDL ? standardTypeNames.concat(typeNames) : typeNames + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown type "${typeName}".` + + (0, _didYouMean.didYouMean)(suggestedTypes), + { + nodes: node, + } + ) + ); + } + }, + }; + } + const standardTypeNames = [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, + ].map((type) => type.name); + function isSDLNode(value) { + return ( + "kind" in value && + ((0, _predicates.isTypeSystemDefinitionNode)(value) || + (0, _predicates.isTypeSystemExtensionNode)(value)) + ); } - const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames); - context.reportError(new _GraphQLError.GraphQLError(`Unknown type "${typeName}".` + (0, _didYouMean.didYouMean)(suggestedTypes), { - nodes: node - })); - } - } - }; -} -const standardTypeNames = [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes].map(type => type.name); -function isSDLNode(value) { - return 'kind' in value && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)); -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs": -/*!*************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs": + /*!*************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs ***! \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -/** - * Lone anonymous operation - * - * A GraphQL document is only valid if when it contains an anonymous operation - * (the query short-hand) that it contains only that one operation definition. - * - * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation - */ -function LoneAnonymousOperationRule(context) { - let operationCount = 0; - return { - Document(node) { - operationCount = node.definitions.filter(definition => definition.kind === _kinds.Kind.OPERATION_DEFINITION).length; - }, - OperationDefinition(node) { - if (!node.name && operationCount > 1) { - context.reportError(new _GraphQLError.GraphQLError('This anonymous operation must be the only defined operation.', { - nodes: node - })); - } - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + /** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation + */ + function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + (definition) => + definition.kind === _kinds.Kind.OPERATION_DEFINITION + ).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + "This anonymous operation must be the only defined operation.", + { + nodes: node, + } + ) + ); + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs": -/*!***********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs": + /*!***********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs ***! \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Lone Schema definition - * - * A GraphQL document is only valid if it contains only one schema definition. - */ -function LoneSchemaDefinitionRule(context) { - var _ref, _ref2, _oldSchema$astNode; - const oldSchema = context.getSchema(); - const alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType(); - let schemaDefinitionsCount = 0; - return { - SchemaDefinition(node) { - if (alreadyDefined) { - context.reportError(new _GraphQLError.GraphQLError('Cannot define a new schema within a schema extension.', { - nodes: node - })); - return; - } - if (schemaDefinitionsCount > 0) { - context.reportError(new _GraphQLError.GraphQLError('Must provide only one schema definition.', { - nodes: node - })); - } - ++schemaDefinitionsCount; - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ + function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + const oldSchema = context.getSchema(); + const alreadyDefined = + (_ref = + (_ref2 = + (_oldSchema$astNode = + oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.astNode) !== null && + _oldSchema$astNode !== void 0 + ? _oldSchema$astNode + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getQueryType()) !== null && _ref2 !== void 0 + ? _ref2 + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getMutationType()) !== null && _ref !== void 0 + ? _ref + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new _GraphQLError.GraphQLError( + "Cannot define a new schema within a schema extension.", + { + nodes: node, + } + ) + ); + return; + } + if (schemaDefinitionsCount > 0) { + context.reportError( + new _GraphQLError.GraphQLError( + "Must provide only one schema definition.", + { + nodes: node, + } + ) + ); + } + ++schemaDefinitionsCount; + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs": -/*!*******************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs": + /*!*******************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs ***! \*******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NoFragmentCyclesRule = NoFragmentCyclesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * No fragment cycles - * - * The graph of fragment spreads must not form any cycles including spreading itself. - * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. - * - * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles - */ -function NoFragmentCyclesRule(context) { - // Tracks already visited fragments to maintain O(N) and to ensure that cycles - // are not redundantly reported. - const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors - - const spreadPath = []; // Position in the spread path - - const spreadPathIndexByName = Object.create(null); - return { - OperationDefinition: () => false, - FragmentDefinition(node) { - detectCycleRecursive(node); - return false; - } - }; // This does a straight-forward DFS to find cycles. - // It does not terminate when a cycle was found but continues to explore - // the graph to find all possible cycles. + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.NoFragmentCyclesRule = NoFragmentCyclesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles + */ + function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors - function detectCycleRecursive(fragment) { - if (visitedFrags[fragment.name.value]) { - return; - } - const fragmentName = fragment.name.value; - visitedFrags[fragmentName] = true; - const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); - if (spreadNodes.length === 0) { - return; - } - spreadPathIndexByName[fragmentName] = spreadPath.length; - for (const spreadNode of spreadNodes) { - const spreadName = spreadNode.name.value; - const cycleIndex = spreadPathIndexByName[spreadName]; - spreadPath.push(spreadNode); - if (cycleIndex === undefined) { - const spreadFragment = context.getFragment(spreadName); - if (spreadFragment) { - detectCycleRecursive(spreadFragment); - } - } else { - const cyclePath = spreadPath.slice(cycleIndex); - const viaPath = cyclePath.slice(0, -1).map(s => '"' + s.name.value + '"').join(', '); - context.reportError(new _GraphQLError.GraphQLError(`Cannot spread fragment "${spreadName}" within itself` + (viaPath !== '' ? ` via ${viaPath}.` : '.'), { - nodes: cyclePath - })); - } - spreadPath.pop(); - } - spreadPathIndexByName[fragmentName] = undefined; - } -} + const spreadPath = []; // Position in the spread path + + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + const spreadNodes = context.getFragmentSpreads( + fragment.selectionSet + ); + if (spreadNodes.length === 0) { + return; + } + spreadPathIndexByName[fragmentName] = spreadPath.length; + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath + .slice(0, -1) + .map((s) => '"' + s.name.value + '"') + .join(", "); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot spread fragment "${spreadName}" within itself` + + (viaPath !== "" ? ` via ${viaPath}.` : "."), + { + nodes: cyclePath, + } + ) + ); + } + spreadPath.pop(); + } + spreadPathIndexByName[fragmentName] = undefined; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs": -/*!***********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs": + /*!***********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs ***! \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * No undefined variables - * - * A GraphQL operation is only valid if all variables encountered, both directly - * and via fragment spreads, are defined by that operation. - * - * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined - */ -function NoUndefinedVariablesRule(context) { - let variableNameDefined = Object.create(null); - return { - OperationDefinition: { - enter() { - variableNameDefined = Object.create(null); - }, - leave(operation) { - const usages = context.getRecursiveVariableUsages(operation); - for (const { - node - } of usages) { - const varName = node.name.value; - if (variableNameDefined[varName] !== true) { - context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` : `Variable "$${varName}" is not defined.`, { - nodes: [node, operation] - })); - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined + */ + function NoUndefinedVariablesRule(context) { + let variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { node } of usages) { + const varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + operation.name + ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` + : `Variable "$${varName}" is not defined.`, + { + nodes: [node, operation], + } + ) + ); + } + } + }, + }, + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; } - } - }, - VariableDefinition(node) { - variableNameDefined[node.variable.name.value] = true; - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs": -/*!********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs": + /*!********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs ***! \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * No unused fragments - * - * A GraphQL document is only valid if all fragment definitions are spread - * within operations, or spread within other fragments spread within operations. - * - * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used - */ -function NoUnusedFragmentsRule(context) { - const operationDefs = []; - const fragmentDefs = []; - return { - OperationDefinition(node) { - operationDefs.push(node); - return false; - }, - FragmentDefinition(node) { - fragmentDefs.push(node); - return false; - }, - Document: { - leave() { - const fragmentNameUsed = Object.create(null); - for (const operation of operationDefs) { - for (const fragment of context.getRecursivelyReferencedFragments(operation)) { - fragmentNameUsed[fragment.name.value] = true; - } - } - for (const fragmentDef of fragmentDefs) { - const fragName = fragmentDef.name.value; - if (fragmentNameUsed[fragName] !== true) { - context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" is never used.`, { - nodes: fragmentDef - })); - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used + */ + function NoUnusedFragmentsRule(context) { + const operationDefs = []; + const fragmentDefs = []; + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${fragName}" is never used.`, + { + nodes: fragmentDef, + } + ) + ); + } + } + }, + }, + }; } - } - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs": -/*!********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs": + /*!********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs ***! \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NoUnusedVariablesRule = NoUnusedVariablesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * No unused variables - * - * A GraphQL operation is only valid if all variables defined by an operation - * are used, either directly or within a spread fragment. - * - * See https://spec.graphql.org/draft/#sec-All-Variables-Used - */ -function NoUnusedVariablesRule(context) { - let variableDefs = []; - return { - OperationDefinition: { - enter() { - variableDefs = []; - }, - leave(operation) { - const variableNameUsed = Object.create(null); - const usages = context.getRecursiveVariableUsages(operation); - for (const { - node - } of usages) { - variableNameUsed[node.name.value] = true; - } - for (const variableDef of variableDefs) { - const variableName = variableDef.variable.name.value; - if (variableNameUsed[variableName] !== true) { - context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` : `Variable "$${variableName}" is never used.`, { - nodes: variableDef - })); - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.NoUnusedVariablesRule = NoUnusedVariablesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + * + * See https://spec.graphql.org/draft/#sec-All-Variables-Used + */ + function NoUnusedVariablesRule(context) { + let variableDefs = []; + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + operation.name + ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` + : `Variable "$${variableName}" is never used.`, + { + nodes: variableDef, + } + ) + ); + } + } + }, + }, + VariableDefinition(def) { + variableDefs.push(def); + }, + }; } - } - }, - VariableDefinition(def) { - variableDefs.push(def); - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs": -/*!*******************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs": + /*!*******************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs ***! \*******************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _sortValueNode = __webpack_require__(/*! ../../utilities/sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); -var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -function reasonMessage(reason) { - if (Array.isArray(reason)) { - return reason.map(([responseName, subReason]) => `subfields "${responseName}" conflict because ` + reasonMessage(subReason)).join(' and '); - } - return reason; -} -/** - * Overlapping fields can be merged - * - * A selection set is only valid if all fields (including spreading any - * fragments) either correspond to distinct response names or can be merged - * without ambiguity. - * - * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging - */ - -function OverlappingFieldsCanBeMergedRule(context) { - // A memoization for when two fragments are compared "between" each other for - // conflicts. Two fragments may be compared many times, so memoizing this can - // dramatically improve the performance of this validator. - const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given - // selection set. Selection sets may be asked for this information multiple - // times, so this improves the performance of this validator. - - const cachedFieldsAndFragmentNames = new Map(); - return { - SelectionSet(selectionSet) { - const conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); - for (const [[responseName, reason], fields1, fields2] of conflicts) { - const reasonMsg = reasonMessage(reason); - context.reportError(new _GraphQLError.GraphQLError(`Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, { - nodes: fields1.concat(fields2) - })); - } - } - }; -} - -/** - * Algorithm: - * - * Conflicts occur when two fields exist in a query which will produce the same - * response name, but represent differing values, thus creating a conflict. - * The algorithm below finds all conflicts via making a series of comparisons - * between fields. In order to compare as few fields as possible, this makes - * a series of comparisons "within" sets of fields and "between" sets of fields. - * - * Given any selection set, a collection produces both a set of fields by - * also including all inline fragments, as well as a list of fragments - * referenced by fragment spreads. - * - * A) Each selection set represented in the document first compares "within" its - * collected set of fields, finding any conflicts between every pair of - * overlapping fields. - * Note: This is the *only time* that a the fields "within" a set are compared - * to each other. After this only fields "between" sets are compared. - * - * B) Also, if any fragment is referenced in a selection set, then a - * comparison is made "between" the original set of fields and the - * referenced fragment. - * - * C) Also, if multiple fragments are referenced, then comparisons - * are made "between" each referenced fragment. - * - * D) When comparing "between" a set of fields and a referenced fragment, first - * a comparison is made between each field in the original set of fields and - * each field in the the referenced set of fields. - * - * E) Also, if any fragment is referenced in the referenced selection set, - * then a comparison is made "between" the original set of fields and the - * referenced fragment (recursively referring to step D). - * - * F) When comparing "between" two fragments, first a comparison is made between - * each field in the first referenced set of fields and each field in the the - * second referenced set of fields. - * - * G) Also, any fragments referenced by the first must be compared to the - * second, and any fragments referenced by the second must be compared to the - * first (recursively referring to step F). - * - * H) When comparing two fields, if both have selection sets, then a comparison - * is made "between" both selection sets, first comparing the set of fields in - * the first selection set with the set of fields in the second. - * - * I) Also, if any fragment is referenced in either selection set, then a - * comparison is made "between" the other set of fields and the - * referenced fragment. - * - * J) Also, if two fragments are referenced in both selection sets, then a - * comparison is made "between" the two fragments. - * - */ -// Find all conflicts found "within" a selection set, including those found -// via spreading in fragments. Called when visiting each SelectionSet in the -// GraphQL Document. -function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { - const conflicts = []; - const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet); // (A) Find find all conflicts "within" the fields of this selection set. - // Note: this is the *only place* `collectConflictsWithin` is called. - - collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); - if (fragmentNames.length !== 0) { - // (B) Then collect conflicts between these fields and those represented by - // each spread fragment name found. - for (let i = 0; i < fragmentNames.length; i++) { - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this - // selection set to collect conflicts between fragments spread together. - // This compares each item in the list of fragment names to every other - // item in that same list (except for itself). - - for (let j = i + 1; j < fragmentNames.length; j++) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); - } - } - } - return conflicts; -} // Collect all conflicts found between a set of fields and a fragment reference -// including via spreading in any nested fragments. - -function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { - const fragment = context.getFragment(fragmentName); - if (!fragment) { - return; - } - const [fieldMap2, referencedFragmentNames] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment); // Do not compare a fragment's fieldMap to itself. - - if (fieldMap === fieldMap2) { - return; - } // (D) First collect any conflicts between the provided collection of fields - // and the collection of fields represented by the given fragment. - - collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields - // and any fragment names found in the given fragment. - - for (const referencedFragmentName of referencedFragmentNames) { - // Memoize so two fragments are not compared for conflicts more than once. - if (comparedFragmentPairs.has(referencedFragmentName, fragmentName, areMutuallyExclusive)) { - continue; - } - comparedFragmentPairs.add(referencedFragmentName, fragmentName, areMutuallyExclusive); - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, referencedFragmentName); - } -} // Collect all conflicts found between two fragments, including via spreading in -// any nested fragments. + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.OverlappingFieldsCanBeMergedRule = + OverlappingFieldsCanBeMergedRule; + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _printer = __webpack_require__( + /*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _sortValueNode = __webpack_require__( + /*! ../../utilities/sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subReason]) => + `subfields "${responseName}" conflict because ` + + reasonMessage(subReason) + ) + .join(" and "); + } + return reason; + } + /** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + */ -function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { - // No need to compare a fragment to itself. - if (fragmentName1 === fragmentName2) { - return; - } // Memoize so two fragments are not compared for conflicts more than once. + function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. - if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { - return; - } - comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); - const fragment1 = context.getFragment(fragmentName1); - const fragment2 = context.getFragment(fragmentName2); - if (!fragment1 || !fragment2) { - return; - } - const [fieldMap1, referencedFragmentNames1] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1); - const [fieldMap2, referencedFragmentNames2] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2); // (F) First, collect all conflicts between these two collections of fields - // (not including any nested fragments). + const cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + context.getParentType(), + selectionSet + ); + for (const [ + [responseName, reason], + fields1, + fields2, + ] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError( + new _GraphQLError.GraphQLError( + `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, + { + nodes: fields1.concat(fields2), + } + ) + ); + } + }, + }; + } - collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested - // fragments spread in the second fragment. + /** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ + // Find all conflicts found "within" a selection set, including those found + // via spreading in fragments. Called when visiting each SelectionSet in the + // GraphQL Document. + function findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentType, + selectionSet + ) { + const conflicts = []; + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet + ); // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + fieldMap + ); + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i] + ); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j] + ); + } + } + } + return conflicts; + } // Collect all conflicts found between a set of fields and a fragment reference + // including via spreading in any nested fragments. + + function collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentName + ) { + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + const [fieldMap2, referencedFragmentNames] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment + ); // Do not compare a fragment's fieldMap to itself. - for (const referencedFragmentName2 of referencedFragmentNames2) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, referencedFragmentName2); - } // (G) Then collect conflicts between the second fragment and any nested - // fragments spread in the first fragment. + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2 + ); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (const referencedFragmentName of referencedFragmentNames) { + // Memoize so two fragments are not compared for conflicts more than once. + if ( + comparedFragmentPairs.has( + referencedFragmentName, + fragmentName, + areMutuallyExclusive + ) + ) { + continue; + } + comparedFragmentPairs.add( + referencedFragmentName, + fragmentName, + areMutuallyExclusive + ); + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + referencedFragmentName + ); + } + } // Collect all conflicts found between two fragments, including via spreading in + // any nested fragments. + + function collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2 + ) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive + ) + ) { + return; + } + comparedFragmentPairs.add( + fragmentName1, + fragmentName2, + areMutuallyExclusive + ); + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; + } + const [fieldMap1, referencedFragmentNames1] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1 + ); + const [fieldMap2, referencedFragmentNames2] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2 + ); // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2 + ); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + referencedFragmentName2 + ); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + referencedFragmentName1, + fragmentName2 + ); + } + } // Find all conflicts found between two selection sets, including those found + // via spreading in fragments. Called when determining if conflicts exist + // between the sub-fields of two overlapping fields. + + function findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + parentType1, + selectionSet1, + parentType2, + selectionSet2 + ) { + const conflicts = []; + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1 + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2 + ); // (H) First, collect all conflicts between these two collections of field. + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2 + ); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentName2 + ); + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentName1 + ); + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + for (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2 + ); + } + } + return conflicts; + } // Collect all Conflicts "within" one collection of fields. + + function collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + fieldMap + ) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of Object.entries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j] + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } + } // Collect all Conflicts between two collections of fields. This is similar to, + // but different from the `collectConflictsWithin` function above. This check + // assumes that `collectConflictsWithin` has already been called on each + // provided collection of fields. This is true because this validator traverses + // each individual selection set. + + function collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + fieldMap1, + fieldMap2 + ) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const [responseName, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2 + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } + } // Determines if there is a conflict between two particular fields, including + // comparing their sub-fields. + + function findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2 + ) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + (0, _definition.isObjectType)(parentType1) && + (0, _definition.isObjectType)(parentType2)); + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [ + [ + responseName, + `"${name1}" and "${name2}" are different fields`, + ], + [node1], + [node2], + ]; + } // Two field calls must have the same arguments. + + if (!sameArguments(node1, node2)) { + return [ + [responseName, "they have differing arguments"], + [node1], + [node2], + ]; + } + } // The return type for each field. + + const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types "${(0, _inspect.inspect)( + type1 + )}" and "${(0, _inspect.inspect)(type2)}"`, + ], + [node1], + [node2], + ]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + (0, _definition.getNamedType)(type1), + selectionSet1, + (0, _definition.getNamedType)(type2), + selectionSet2 + ); + return subfieldConflicts(conflicts, responseName, node1, node2); + } + } + function sameArguments(node1, node2) { + const args1 = node1.arguments; + const args2 = node2.arguments; + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; + } + if (args2 === undefined || args2.length === 0) { + return false; + } + /* c8 ignore next */ - for (const referencedFragmentName1 of referencedFragmentNames1) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, referencedFragmentName1, fragmentName2); - } -} // Find all conflicts found between two selection sets, including those found -// via spreading in fragments. Called when determining if conflicts exist -// between the sub-fields of two overlapping fields. - -function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { - const conflicts = []; - const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1); - const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2); // (H) First, collect all conflicts between these two collections of field. - - collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and - // those referenced by each fragment name associated with the second. - - for (const fragmentName2 of fragmentNames2) { - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentName2); - } // (I) Then collect conflicts between the second collection of fields and - // those referenced by each fragment name associated with the first. - - for (const fragmentName1 of fragmentNames1) { - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentName1); - } // (J) Also collect conflicts between any fragment names by the first and - // fragment names by the second. This compares each item in the first set of - // names to each item in the second set of names. - - for (const fragmentName1 of fragmentNames1) { - for (const fragmentName2 of fragmentNames2) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2); - } - } - return conflicts; -} // Collect all Conflicts "within" one collection of fields. - -function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { - // A field map is a keyed collection, where each key represents a response - // name and the value at that key is a list of all fields which provide that - // response name. For every response name, if there are multiple fields, they - // must be compared to find a potential conflict. - for (const [responseName, fields] of Object.entries(fieldMap)) { - // This compares every field in the list to every other field in this list - // (except to itself). If the list only has one item, nothing needs to - // be compared. - if (fields.length > 1) { - for (let i = 0; i < fields.length; i++) { - for (let j = i + 1; j < fields.length; j++) { - const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, - // within one collection is never mutually exclusive - responseName, fields[i], fields[j]); - if (conflict) { - conflicts.push(conflict); + if (args1.length !== args2.length) { + /* c8 ignore next */ + return false; + /* c8 ignore next */ } + const values2 = new Map( + args2.map(({ name, value }) => [name.value, value]) + ); + return args1.every((arg1) => { + const value1 = arg1.value; + const value2 = values2.get(arg1.name.value); + if (value2 === undefined) { + return false; + } + return stringifyValue(value1) === stringifyValue(value2); + }); } - } - } - } -} // Collect all Conflicts between two collections of fields. This is similar to, -// but different from the `collectConflictsWithin` function above. This check -// assumes that `collectConflictsWithin` has already been called on each -// provided collection of fields. This is true because this validator traverses -// each individual selection set. - -function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { - // A field map is a keyed collection, where each key represents a response - // name and the value at that key is a list of all fields which provide that - // response name. For any response name which appears in both provided field - // maps, each field from the first field map must be compared to every field - // in the second field map to find potential conflicts. - for (const [responseName, fields1] of Object.entries(fieldMap1)) { - const fields2 = fieldMap2[responseName]; - if (fields2) { - for (const field1 of fields1) { - for (const field2 of fields2) { - const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2); - if (conflict) { - conflicts.push(conflict); + function stringifyValue(value) { + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); + } // Two types conflict if both types could not apply to a value simultaneously. + // Composite types are ignored as their individual field types will be compared + // later recursively. However List and Non-Null types must match. + + function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if ((0, _definition.isListType)(type2)) { + return true; + } + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + if ( + (0, _definition.isLeafType)(type1) || + (0, _definition.isLeafType)(type2) + ) { + return type1 !== type2; + } + return false; + } // Given a selection set, return the collection of fields (a mapping of response + // name to field nodes and definitions) as well as a list of fragment names + // referenced via fragment spreads. + + function getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet + ) { + const cached = cachedFieldsAndFragmentNames.get(selectionSet); + if (cached) { + return cached; + } + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames + ); + const result = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, result); + return result; + } // Given a reference to a fragment, return the represented collection of fields + // as well as a list of nested fragment names referenced via fragment spreads. + + function getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment + ) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get( + fragment.selectionSet + ); + if (cached) { + return cached; } + const fragmentType = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + fragment.typeCondition + ); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet + ); } - } - } - } -} // Determines if there is a conflict between two particular fields, including -// comparing their sub-fields. - -function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { - const [parentType1, node1, def1] = field1; - const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same - // time, due to the parent types, then it is safe to permit them to diverge - // in aliased field or arguments used as they will not present any ambiguity - // by differing. - // It is known that two parent types could never overlap if they are - // different Object types. Interface or Union types might overlap - if not - // in the current state of the schema, then perhaps in some future version, - // thus may not safely diverge. - - const areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); - if (!areMutuallyExclusive) { - // Two aliases must refer to the same field. - const name1 = node1.name.value; - const name2 = node2.name.value; - if (name1 !== name2) { - return [[responseName, `"${name1}" and "${name2}" are different fields`], [node1], [node2]]; - } // Two field calls must have the same arguments. - - if (!sameArguments(node1, node2)) { - return [[responseName, 'they have differing arguments'], [node1], [node2]]; - } - } // The return type for each field. - - const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; - const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; - if (type1 && type2 && doTypesConflict(type1, type2)) { - return [[responseName, `they return conflicting types "${(0, _inspect.inspect)(type1)}" and "${(0, _inspect.inspect)(type2)}"`], [node1], [node2]]; - } // Collect and compare sub-fields. Use the same "visited fragment names" list - // for both collections so fields in a fragment reference are never - // compared to themselves. - - const selectionSet1 = node1.selectionSet; - const selectionSet2 = node2.selectionSet; - if (selectionSet1 && selectionSet2) { - const conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); - return subfieldConflicts(conflicts, responseName, node1, node2); - } -} -function sameArguments(node1, node2) { - const args1 = node1.arguments; - const args2 = node2.arguments; - if (args1 === undefined || args1.length === 0) { - return args2 === undefined || args2.length === 0; - } - if (args2 === undefined || args2.length === 0) { - return false; - } - /* c8 ignore next */ + function _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames + ) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: { + const fieldName = selection.name.value; + let fieldDef; + if ( + (0, _definition.isObjectType)(parentType) || + (0, _definition.isInterfaceType)(parentType) + ) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias + ? selection.alias.value + : fieldName; + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + nodeAndDefs[responseName].push([ + parentType, + selection, + fieldDef, + ]); + break; + } + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case _kinds.Kind.INLINE_FRAGMENT: { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? (0, _typeFromAST.typeFromAST)( + context.getSchema(), + typeCondition + ) + : parentType; + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames + ); + break; + } + } + } + } // Given a series of Conflicts which occurred between two sub-fields, generate + // a single Conflict. - if (args1.length !== args2.length) { - /* c8 ignore next */ - return false; - /* c8 ignore next */ - } - const values2 = new Map(args2.map(({ - name, - value - }) => [name.value, value])); - return args1.every(arg1 => { - const value1 = arg1.value; - const value2 = values2.get(arg1.name.value); - if (value2 === undefined) { - return false; - } - return stringifyValue(value1) === stringifyValue(value2); - }); -} -function stringifyValue(value) { - return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); -} // Two types conflict if both types could not apply to a value simultaneously. -// Composite types are ignored as their individual field types will be compared -// later recursively. However List and Non-Null types must match. - -function doTypesConflict(type1, type2) { - if ((0, _definition.isListType)(type1)) { - return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; - } - if ((0, _definition.isListType)(type2)) { - return true; - } - if ((0, _definition.isNonNullType)(type1)) { - return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; - } - if ((0, _definition.isNonNullType)(type2)) { - return true; - } - if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { - return type1 !== type2; - } - return false; -} // Given a selection set, return the collection of fields (a mapping of response -// name to field nodes and definitions) as well as a list of fragment names -// referenced via fragment spreads. - -function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { - const cached = cachedFieldsAndFragmentNames.get(selectionSet); - if (cached) { - return cached; - } - const nodeAndDefs = Object.create(null); - const fragmentNames = Object.create(null); - _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); - const result = [nodeAndDefs, Object.keys(fragmentNames)]; - cachedFieldsAndFragmentNames.set(selectionSet, result); - return result; -} // Given a reference to a fragment, return the represented collection of fields -// as well as a list of nested fragment names referenced via fragment spreads. - -function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { - // Short-circuit building a type from the node if possible. - const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); - if (cached) { - return cached; - } - const fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); - return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); -} -function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { - for (const selection of selectionSet.selections) { - switch (selection.kind) { - case _kinds.Kind.FIELD: - { - const fieldName = selection.name.value; - let fieldDef; - if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { - fieldDef = parentType.getFields()[fieldName]; - } - const responseName = selection.alias ? selection.alias.value : fieldName; - if (!nodeAndDefs[responseName]) { - nodeAndDefs[responseName] = []; - } - nodeAndDefs[responseName].push([parentType, selection, fieldDef]); - break; - } - case _kinds.Kind.FRAGMENT_SPREAD: - fragmentNames[selection.name.value] = true; - break; - case _kinds.Kind.INLINE_FRAGMENT: - { - const typeCondition = selection.typeCondition; - const inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; - _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); - break; + function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + [node1, ...conflicts.map(([, fields1]) => fields1).flat()], + [node2, ...conflicts.map(([, , fields2]) => fields2).flat()], + ]; + } } - } - } -} // Given a series of Conflicts which occurred between two sub-fields, generate -// a single Conflict. + /** + * A way to keep track of pairs of things when the ordering of the pair does not matter. + */ -function subfieldConflicts(conflicts, responseName, node1, node2) { - if (conflicts.length > 0) { - return [[responseName, conflicts.map(([reason]) => reason)], [node1, ...conflicts.map(([, fields1]) => fields1).flat()], [node2, ...conflicts.map(([,, fields2]) => fields2).flat()]]; - } -} -/** - * A way to keep track of pairs of things when the ordering of the pair does not matter. - */ - -class PairSet { - constructor() { - this._data = new Map(); - } - has(a, b, areMutuallyExclusive) { - var _this$_data$get; - const [key1, key2] = a < b ? [a, b] : [b, a]; - const result = (_this$_data$get = this._data.get(key1)) === null || _this$_data$get === void 0 ? void 0 : _this$_data$get.get(key2); - if (result === undefined) { - return false; - } // areMutuallyExclusive being false is a superset of being true, hence if - // we want to know if this PairSet "has" these two with no exclusivity, - // we have to ensure it was added as such. - - return areMutuallyExclusive ? true : areMutuallyExclusive === result; - } - add(a, b, areMutuallyExclusive) { - const [key1, key2] = a < b ? [a, b] : [b, a]; - const map = this._data.get(key1); - if (map === undefined) { - this._data.set(key1, new Map([[key2, areMutuallyExclusive]])); - } else { - map.set(key2, areMutuallyExclusive); - } - } -} + class PairSet { + constructor() { + this._data = new Map(); + } + has(a, b, areMutuallyExclusive) { + var _this$_data$get; + const [key1, key2] = a < b ? [a, b] : [b, a]; + const result = + (_this$_data$get = this._data.get(key1)) === null || + _this$_data$get === void 0 + ? void 0 + : _this$_data$get.get(key2); + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, hence if + // we want to know if this PairSet "has" these two with no exclusivity, + // we have to ensure it was added as such. + + return areMutuallyExclusive + ? true + : areMutuallyExclusive === result; + } + add(a, b, areMutuallyExclusive) { + const [key1, key2] = a < b ? [a, b] : [b, a]; + const map = this._data.get(key1); + if (map === undefined) { + this._data.set(key1, new Map([[key2, areMutuallyExclusive]])); + } else { + map.set(key2, areMutuallyExclusive); + } + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs": -/*!**************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs": + /*!**************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs ***! \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); -var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -/** - * Possible fragment spread - * - * A fragment spread is only valid if the type condition could ever possibly - * be true: if there is a non-empty intersection of the possible parent types, - * and possible types which pass the type condition. - */ -function PossibleFragmentSpreadsRule(context) { - return { - InlineFragment(node) { - const fragType = context.getType(); - const parentType = context.getParentType(); - if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { - const parentTypeStr = (0, _inspect.inspect)(parentType); - const fragTypeStr = (0, _inspect.inspect)(fragType); - context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { - nodes: node - })); - } - }, - FragmentSpread(node) { - const fragName = node.name.value; - const fragType = getFragmentType(context, fragName); - const parentType = context.getParentType(); - if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { - const parentTypeStr = (0, _inspect.inspect)(parentType); - const fragTypeStr = (0, _inspect.inspect)(fragType); - context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { - nodes: node - })); - } - } - }; -} -function getFragmentType(context, name) { - const frag = context.getFragment(name); - if (frag) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); - if ((0, _definition.isCompositeType)(type)) { - return type; - } - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _typeComparators = __webpack_require__( + /*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + /** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ + function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ( + (0, _definition.isCompositeType)(fragType) && + (0, _definition.isCompositeType)(parentType) && + !(0, _typeComparators.doTypesOverlap)( + context.getSchema(), + fragType, + parentType + ) + ) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + } + ) + ); + } + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if ( + fragType && + parentType && + !(0, _typeComparators.doTypesOverlap)( + context.getSchema(), + fragType, + parentType + ) + ) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + } + ) + ); + } + }, + }; + } + function getFragmentType(context, name) { + const frag = context.getFragment(name); + if (frag) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + frag.typeCondition + ); + if ((0, _definition.isCompositeType)(type)) { + return type; + } + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs": -/*!*************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs": + /*!*************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs ***! \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; -var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Possible type extension - * - * A type extension is only valid if the type is defined and has the same kind. - */ -function PossibleTypeExtensionsRule(context) { - const schema = context.getSchema(); - const definedTypes = Object.create(null); - for (const def of context.getDocument().definitions) { - if ((0, _predicates.isTypeDefinitionNode)(def)) { - definedTypes[def.name.value] = def; - } - } - return { - ScalarTypeExtension: checkExtension, - ObjectTypeExtension: checkExtension, - InterfaceTypeExtension: checkExtension, - UnionTypeExtension: checkExtension, - EnumTypeExtension: checkExtension, - InputObjectTypeExtension: checkExtension - }; - function checkExtension(node) { - const typeName = node.name.value; - const defNode = definedTypes[typeName]; - const existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName); - let expectedKind; - if (defNode) { - expectedKind = defKindToExtKind[defNode.kind]; - } else if (existingType) { - expectedKind = typeToExtKind(existingType); - } - if (expectedKind) { - if (expectedKind !== node.kind) { - const kindStr = extensionKindToTypeName(node.kind); - context.reportError(new _GraphQLError.GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, { - nodes: defNode ? [defNode, node] : node - })); - } - } else { - const allTypeNames = Object.keys({ - ...definedTypes, - ...(schema === null || schema === void 0 ? void 0 : schema.getTypeMap()) - }); - const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, allTypeNames); - context.reportError(new _GraphQLError.GraphQLError(`Cannot extend type "${typeName}" because it is not defined.` + (0, _didYouMean.didYouMean)(suggestedTypes), { - nodes: node.name - })); - } - } -} -const defKindToExtKind = { - [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, - [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, - [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, - [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, - [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, - [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION -}; -function typeToExtKind(type) { - if ((0, _definition.isScalarType)(type)) { - return _kinds.Kind.SCALAR_TYPE_EXTENSION; - } - if ((0, _definition.isObjectType)(type)) { - return _kinds.Kind.OBJECT_TYPE_EXTENSION; - } - if ((0, _definition.isInterfaceType)(type)) { - return _kinds.Kind.INTERFACE_TYPE_EXTENSION; - } - if ((0, _definition.isUnionType)(type)) { - return _kinds.Kind.UNION_TYPE_EXTENSION; - } - if ((0, _definition.isEnumType)(type)) { - return _kinds.Kind.ENUM_TYPE_EXTENSION; - } - if ((0, _definition.isInputObjectType)(type)) { - return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; - } - /* c8 ignore next 3 */ - // Not reachable. All possible types have been considered - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); -} -function extensionKindToTypeName(kind) { - switch (kind) { - case _kinds.Kind.SCALAR_TYPE_EXTENSION: - return 'scalar'; - case _kinds.Kind.OBJECT_TYPE_EXTENSION: - return 'object'; - case _kinds.Kind.INTERFACE_TYPE_EXTENSION: - return 'interface'; - case _kinds.Kind.UNION_TYPE_EXTENSION: - return 'union'; - case _kinds.Kind.ENUM_TYPE_EXTENSION: - return 'enum'; - case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: - return 'input object'; - // Not reachable. All possible types have been considered - - /* c8 ignore next */ - - default: - false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(kind)); - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; + var _didYouMean = __webpack_require__( + /*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _invariant = __webpack_require__( + /*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _predicates = __webpack_require__( + /*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ + function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = def; + } + } + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension, + }; + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = + schema === null || schema === void 0 + ? void 0 + : schema.getType(typeName); + let expectedKind; + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot extend non-${kindStr} type "${typeName}".`, + { + nodes: defNode ? [defNode, node] : node, + } + ) + ); + } + } else { + const allTypeNames = Object.keys({ + ...definedTypes, + ...(schema === null || schema === void 0 + ? void 0 + : schema.getTypeMap()), + }); + const suggestedTypes = (0, _suggestionList.suggestionList)( + typeName, + allTypeNames + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot extend type "${typeName}" because it is not defined.` + + (0, _didYouMean.didYouMean)(suggestedTypes), + { + nodes: node.name, + } + ) + ); + } + } + } + const defKindToExtKind = { + [_kinds.Kind.SCALAR_TYPE_DEFINITION]: + _kinds.Kind.SCALAR_TYPE_EXTENSION, + [_kinds.Kind.OBJECT_TYPE_DEFINITION]: + _kinds.Kind.OBJECT_TYPE_EXTENSION, + [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: + _kinds.Kind.INTERFACE_TYPE_EXTENSION, + [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, + [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, + [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: + _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + }; + function typeToExtKind(type) { + if ((0, _definition.isScalarType)(type)) { + return _kinds.Kind.SCALAR_TYPE_EXTENSION; + } + if ((0, _definition.isObjectType)(type)) { + return _kinds.Kind.OBJECT_TYPE_EXTENSION; + } + if ((0, _definition.isInterfaceType)(type)) { + return _kinds.Kind.INTERFACE_TYPE_EXTENSION; + } + if ((0, _definition.isUnionType)(type)) { + return _kinds.Kind.UNION_TYPE_EXTENSION; + } + if ((0, _definition.isEnumType)(type)) { + return _kinds.Kind.ENUM_TYPE_EXTENSION; + } + if ((0, _definition.isInputObjectType)(type)) { + return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + /* c8 ignore next 3 */ + // Not reachable. All possible types have been considered -/***/ }), + false || + (0, _invariant.invariant)( + false, + "Unexpected type: " + (0, _inspect.inspect)(type) + ); + } + function extensionKindToTypeName(kind) { + switch (kind) { + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return "scalar"; + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return "object"; + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return "interface"; + case _kinds.Kind.UNION_TYPE_EXTENSION: + return "union"; + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return "enum"; + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return "input object"; + // Not reachable. All possible types have been considered + + /* c8 ignore next */ + + default: + false || + (0, _invariant.invariant)( + false, + "Unexpected kind: " + (0, _inspect.inspect)(kind) + ); + } + } + + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs": -/*!****************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs": + /*!****************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs ***! \****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ProvidedRequiredArgumentsOnDirectivesRule = ProvidedRequiredArgumentsOnDirectivesRule; -exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -/** - * Provided required arguments - * - * A field or directive is only valid if all required (non-null without a - * default value) field arguments have been provided. - */ -function ProvidedRequiredArgumentsRule(context) { - return { - // eslint-disable-next-line new-cap - ...ProvidedRequiredArgumentsOnDirectivesRule(context), - Field: { - // Validate on leave to allow for deeper errors to appear first. - leave(fieldNode) { - var _fieldNode$arguments; - const fieldDef = context.getFieldDef(); - if (!fieldDef) { - return false; - } - const providedArgs = new Set( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - /* c8 ignore next */ - (_fieldNode$arguments = fieldNode.arguments) === null || _fieldNode$arguments === void 0 ? void 0 : _fieldNode$arguments.map(arg => arg.name.value)); - for (const argDef of fieldDef.args) { - if (!providedArgs.has(argDef.name) && (0, _definition.isRequiredArgument)(argDef)) { - const argTypeStr = (0, _inspect.inspect)(argDef.type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, { - nodes: fieldNode - })); - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.ProvidedRequiredArgumentsOnDirectivesRule = + ProvidedRequiredArgumentsOnDirectivesRule; + exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _printer = __webpack_require__( + /*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _directives = __webpack_require__( + /*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + /** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ + function ProvidedRequiredArgumentsRule(context) { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + var _fieldNode$arguments; + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; + } + const providedArgs = new Set( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + (_fieldNode$arguments = fieldNode.arguments) === null || + _fieldNode$arguments === void 0 + ? void 0 + : _fieldNode$arguments.map((arg) => arg.name.value) + ); + for (const argDef of fieldDef.args) { + if ( + !providedArgs.has(argDef.name) && + (0, _definition.isRequiredArgument)(argDef) + ) { + const argTypeStr = (0, _inspect.inspect)(argDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, + { + nodes: fieldNode, + } + ) + ); + } + } + }, + }, + }; } - } - } - }; -} -/** - * @internal - */ - -function ProvidedRequiredArgumentsOnDirectivesRule(context) { - var _schema$getDirectives; - const requiredArgsMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = (_schema$getDirectives = schema === null || schema === void 0 ? void 0 : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 ? _schema$getDirectives : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - requiredArgsMap[directive.name] = (0, _keyMap.keyMap)(directive.args.filter(_definition.isRequiredArgument), arg => arg.name); - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - var _def$arguments; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; - requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)(argNodes.filter(isRequiredArgumentNode), arg => arg.name.value); - } - } - return { - Directive: { - // Validate on leave to allow for deeper errors to appear first. - leave(directiveNode) { - const directiveName = directiveNode.name.value; - const requiredArgs = requiredArgsMap[directiveName]; - if (requiredArgs) { - var _directiveNode$argume; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /** + * @internal + */ - /* c8 ignore next */ - const argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; - const argNodeMap = new Set(argNodes.map(arg => arg.name.value)); - for (const [argName, argDef] of Object.entries(requiredArgs)) { - if (!argNodeMap.has(argName)) { - const argType = (0, _definition.isType)(argDef.type) ? (0, _inspect.inspect)(argDef.type) : (0, _printer.print)(argDef.type); - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, { - nodes: directiveNode - })); + function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var _schema$getDirectives; + const requiredArgsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = + (_schema$getDirectives = + schema === null || schema === void 0 + ? void 0 + : schema.getDirectives()) !== null && + _schema$getDirectives !== void 0 + ? _schema$getDirectives + : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = (0, _keyMap.keyMap)( + directive.args.filter(_definition.isRequiredArgument), + (arg) => arg.name + ); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_def$arguments = def.arguments) !== null && + _def$arguments !== void 0 + ? _def$arguments + : []; + requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)( + argNodes.filter(isRequiredArgumentNode), + (arg) => arg.name.value + ); } } + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + if (requiredArgs) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_directiveNode$argume = directiveNode.arguments) !== + null && _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + const argNodeMap = new Set( + argNodes.map((arg) => arg.name.value) + ); + for (const [argName, argDef] of Object.entries( + requiredArgs + )) { + if (!argNodeMap.has(argName)) { + const argType = (0, _definition.isType)(argDef.type) + ? (0, _inspect.inspect)(argDef.type) + : (0, _printer.print)(argDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, + { + nodes: directiveNode, + } + ) + ); + } + } + } + }, + }, + }; + } + function isRequiredArgumentNode(arg) { + return ( + arg.type.kind === _kinds.Kind.NON_NULL_TYPE && + arg.defaultValue == null + ); } - } - } - }; -} -function isRequiredArgumentNode(arg) { - return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs": -/*!**************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs": + /*!**************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs ***! \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ScalarLeafsRule = ScalarLeafsRule; -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Scalar leafs - * - * A GraphQL document is valid only if all leaf fields (fields without - * sub selections) are of scalar or enum types. - */ -function ScalarLeafsRule(context) { - return { - Field(node) { - const type = context.getType(); - const selectionSet = node.selectionSet; - if (type) { - if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { - if (selectionSet) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, { - nodes: selectionSet - })); - } - } else if (!selectionSet) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, { - nodes: node - })); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.ScalarLeafsRule = ScalarLeafsRule; + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ + function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if ( + (0, _definition.isLeafType)( + (0, _definition.getNamedType)(type) + ) + ) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, + { + nodes: selectionSet, + } + ) + ); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, + { + nodes: node, + } + ) + ); + } + } + }, + }; } - } - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs": -/*!***************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs": + /*!***************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs ***! \***************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _collectFields = __webpack_require__(/*! ../../execution/collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); -/** - * Subscriptions must only include a non-introspection field. - * - * A GraphQL subscription is valid only if it contains a single root field and - * that root field is not an introspection field. - * - * See https://spec.graphql.org/draft/#sec-Single-root-field - */ -function SingleFieldSubscriptionsRule(context) { - return { - OperationDefinition(node) { - if (node.operation === 'subscription') { - const schema = context.getSchema(); - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType) { - const operationName = node.name ? node.name.value : null; - const variableValues = Object.create(null); - const document = context.getDocument(); - const fragments = Object.create(null); - for (const definition of document.definitions) { - if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { - fragments[definition.name.value] = definition; - } - } - const fields = (0, _collectFields.collectFields)(schema, fragments, variableValues, subscriptionType, node.selectionSet); - if (fields.size > 1) { - const fieldSelectionLists = [...fields.values()]; - const extraFieldSelectionLists = fieldSelectionLists.slice(1); - const extraFieldSelections = extraFieldSelectionLists.flat(); - context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must select only one top level field.` : 'Anonymous Subscription must select only one top level field.', { - nodes: extraFieldSelections - })); - } - for (const fieldNodes of fields.values()) { - const field = fieldNodes[0]; - const fieldName = field.name.value; - if (fieldName.startsWith('__')) { - context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must not select an introspection top level field.` : 'Anonymous Subscription must not select an introspection top level field.', { - nodes: fieldNodes - })); - } - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _collectFields = __webpack_require__( + /*! ../../execution/collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs" + ); + /** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + */ + function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === "subscription") { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document = context.getDocument(); + const fragments = Object.create(null); + for (const definition of document.definitions) { + if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = definition; + } + } + const fields = (0, _collectFields.collectFields)( + schema, + fragments, + variableValues, + subscriptionType, + node.selectionSet + ); + if (fields.size > 1) { + const fieldSelectionLists = [...fields.values()]; + const extraFieldSelectionLists = + fieldSelectionLists.slice(1); + const extraFieldSelections = + extraFieldSelectionLists.flat(); + context.reportError( + new _GraphQLError.GraphQLError( + operationName != null + ? `Subscription "${operationName}" must select only one top level field.` + : "Anonymous Subscription must select only one top level field.", + { + nodes: extraFieldSelections, + } + ) + ); + } + for (const fieldNodes of fields.values()) { + const field = fieldNodes[0]; + const fieldName = field.name.value; + if (fieldName.startsWith("__")) { + context.reportError( + new _GraphQLError.GraphQLError( + operationName != null + ? `Subscription "${operationName}" must not select an introspection top level field.` + : "Anonymous Subscription must not select an introspection top level field.", + { + nodes: fieldNodes, + } + ) + ); + } + } + } + } + }, + }; } - } - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs": -/*!********************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs": + /*!********************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs ***! \********************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; -var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique argument definition names - * - * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. - * A GraphQL Directive is only valid if all its arguments are uniquely named. - */ -function UniqueArgumentDefinitionNamesRule(context) { - return { - DirectiveDefinition(directiveNode) { - var _directiveNode$argume; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argumentNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; - return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); - }, - InterfaceTypeDefinition: checkArgUniquenessPerField, - InterfaceTypeExtension: checkArgUniquenessPerField, - ObjectTypeDefinition: checkArgUniquenessPerField, - ObjectTypeExtension: checkArgUniquenessPerField - }; - function checkArgUniquenessPerField(typeNode) { - var _typeNode$fields; - const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const fieldNodes = (_typeNode$fields = typeNode.fields) !== null && _typeNode$fields !== void 0 ? _typeNode$fields : []; - for (const fieldDef of fieldNodes) { - var _fieldDef$arguments; - const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const argumentNodes = (_fieldDef$arguments = fieldDef.arguments) !== null && _fieldDef$arguments !== void 0 ? _fieldDef$arguments : []; - checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); - } - return false; - } - function checkArgUniqueness(parentName, argumentNodes) { - const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); - for (const [argName, argNodes] of seenArgs) { - if (argNodes.length > 1) { - context.reportError(new _GraphQLError.GraphQLError(`Argument "${parentName}(${argName}:)" can only be defined once.`, { - nodes: argNodes.map(node => node.name) - })); - } - } - return false; - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueArgumentDefinitionNamesRule = + UniqueArgumentDefinitionNamesRule; + var _groupBy = __webpack_require__( + /*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique argument definition names + * + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. + */ + function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + return checkArgUniqueness( + `@${directiveNode.name.value}`, + argumentNodes + ); + }, + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField, + }; + function checkArgUniquenessPerField(typeNode) { + var _typeNode$fields; + const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = + (_typeNode$fields = typeNode.fields) !== null && + _typeNode$fields !== void 0 + ? _typeNode$fields + : []; + for (const fieldDef of fieldNodes) { + var _fieldDef$arguments; + const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = + (_fieldDef$arguments = fieldDef.arguments) !== null && + _fieldDef$arguments !== void 0 + ? _fieldDef$arguments + : []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + } + return false; + } + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = (0, _groupBy.groupBy)( + argumentNodes, + (arg) => arg.name.value + ); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `Argument "${parentName}(${argName}:)" can only be defined once.`, + { + nodes: argNodes.map((node) => node.name), + } + ) + ); + } + } + return false; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs": -/*!**********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs": + /*!**********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs ***! \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; -var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique argument names - * - * A GraphQL field or directive is only valid if all supplied arguments are - * uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Argument-Names - */ -function UniqueArgumentNamesRule(context) { - return { - Field: checkArgUniqueness, - Directive: checkArgUniqueness - }; - function checkArgUniqueness(parentNode) { - var _parentNode$arguments; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argumentNodes = (_parentNode$arguments = parentNode.arguments) !== null && _parentNode$arguments !== void 0 ? _parentNode$arguments : []; - const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); - for (const [argName, argNodes] of seenArgs) { - if (argNodes.length > 1) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one argument named "${argName}".`, { - nodes: argNodes.map(node => node.name) - })); - } - } - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; + var _groupBy = __webpack_require__( + /*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + */ + function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness, + }; + function checkArgUniqueness(parentNode) { + var _parentNode$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_parentNode$arguments = parentNode.arguments) !== null && + _parentNode$arguments !== void 0 + ? _parentNode$arguments + : []; + const seenArgs = (0, _groupBy.groupBy)( + argumentNodes, + (arg) => arg.name.value + ); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one argument named "${argName}".`, + { + nodes: argNodes.map((node) => node.name), + } + ) + ); + } + } + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs": -/*!***********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs": + /*!***********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs ***! \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique directive names - * - * A GraphQL document is only valid if all defined directives have unique names. - */ -function UniqueDirectiveNamesRule(context) { - const knownDirectiveNames = Object.create(null); - const schema = context.getSchema(); - return { - DirectiveDefinition(node) { - const directiveName = node.name.value; - if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) { - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, { - nodes: node.name - })); - return; - } - if (knownDirectiveNames[directiveName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one directive named "@${directiveName}".`, { - nodes: [knownDirectiveNames[directiveName], node.name] - })); - } else { - knownDirectiveNames[directiveName] = node.name; - } - return false; - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ + function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + if ( + schema !== null && + schema !== void 0 && + schema.getDirective(directiveName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, + { + nodes: node.name, + } + ) + ); + return; + } + if (knownDirectiveNames[directiveName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one directive named "@${directiveName}".`, + { + nodes: [knownDirectiveNames[directiveName], node.name], + } + ) + ); + } else { + knownDirectiveNames[directiveName] = node.name; + } + return false; + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs": -/*!******************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs": + /*!******************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs ***! \******************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); -var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); -/** - * Unique directive names per location - * - * A GraphQL document is only valid if all non-repeatable directives at - * a given location are uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location - */ -function UniqueDirectivesPerLocationRule(context) { - const uniqueDirectiveMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - uniqueDirectiveMap[directive.name] = !directive.isRepeatable; - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - uniqueDirectiveMap[def.name.value] = !def.repeatable; - } - } - const schemaDirectives = Object.create(null); - const typeDirectivesMap = Object.create(null); - return { - // Many different AST nodes may contain directives. Rather than listing - // them all, just listen for entering any node, and check to see if it - // defines any directives. - enter(node) { - if (!('directives' in node) || !node.directives) { - return; - } - let seenDirectives; - if (node.kind === _kinds.Kind.SCHEMA_DEFINITION || node.kind === _kinds.Kind.SCHEMA_EXTENSION) { - seenDirectives = schemaDirectives; - } else if ((0, _predicates.isTypeDefinitionNode)(node) || (0, _predicates.isTypeExtensionNode)(node)) { - const typeName = node.name.value; - seenDirectives = typeDirectivesMap[typeName]; - if (seenDirectives === undefined) { - typeDirectivesMap[typeName] = seenDirectives = Object.create(null); - } - } else { - seenDirectives = Object.create(null); - } - for (const directive of node.directives) { - const directiveName = directive.name.value; - if (uniqueDirectiveMap[directiveName]) { - if (seenDirectives[directiveName]) { - context.reportError(new _GraphQLError.GraphQLError(`The directive "@${directiveName}" can only be used once at this location.`, { - nodes: [seenDirectives[directiveName], directive] - })); - } else { - seenDirectives[directiveName] = directive; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueDirectivesPerLocationRule = + UniqueDirectivesPerLocationRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _predicates = __webpack_require__( + /*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs" + ); + var _directives = __webpack_require__( + /*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs" + ); + /** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location + */ + function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } } - } - } - } - }; -} + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (!("directives" in node) || !node.directives) { + return; + } + let seenDirectives; + if ( + node.kind === _kinds.Kind.SCHEMA_DEFINITION || + node.kind === _kinds.Kind.SCHEMA_EXTENSION + ) { + seenDirectives = schemaDirectives; + } else if ( + (0, _predicates.isTypeDefinitionNode)(node) || + (0, _predicates.isTypeExtensionNode)(node) + ) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = + Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + for (const directive of node.directives) { + const directiveName = directive.name.value; + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `The directive "@${directiveName}" can only be used once at this location.`, + { + nodes: [seenDirectives[directiveName], directive], + } + ) + ); + } else { + seenDirectives[directiveName] = directive; + } + } + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs": -/*!***********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs": + /*!***********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs ***! \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Unique enum value names - * - * A GraphQL enum type is only valid if all its values are uniquely named. - */ -function UniqueEnumValueNamesRule(context) { - const schema = context.getSchema(); - const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); - const knownValueNames = Object.create(null); - return { - EnumTypeDefinition: checkValueUniqueness, - EnumTypeExtension: checkValueUniqueness - }; - function checkValueUniqueness(node) { - var _node$values; - const typeName = node.name.value; - if (!knownValueNames[typeName]) { - knownValueNames[typeName] = Object.create(null); - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; - const valueNames = knownValueNames[typeName]; - for (const valueDef of valueNodes) { - const valueName = valueDef.name.value; - const existingType = existingTypeMap[typeName]; - if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) { - context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, { - nodes: valueDef.name - })); - } else if (valueNames[valueName]) { - context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" can only be defined once.`, { - nodes: [valueNames[valueName], valueDef.name] - })); - } else { - valueNames[valueName] = valueDef.name; - } - } - return false; - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ + function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema + ? schema.getTypeMap() + : Object.create(null); + const knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness, + }; + function checkValueUniqueness(node) { + var _node$values; + const typeName = node.name.value; + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const valueNodes = + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + const valueNames = knownValueNames[typeName]; + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + if ( + (0, _definition.isEnumType)(existingType) && + existingType.getValue(valueName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: valueDef.name, + } + ) + ); + } else if (valueNames[valueName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Enum value "${typeName}.${valueName}" can only be defined once.`, + { + nodes: [valueNames[valueName], valueDef.name], + } + ) + ); + } else { + valueNames[valueName] = valueDef.name; + } + } + return false; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs": -/*!*****************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs": + /*!*****************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs ***! \*****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Unique field definition names - * - * A GraphQL complex type is only valid if all its fields are uniquely named. - */ -function UniqueFieldDefinitionNamesRule(context) { - const schema = context.getSchema(); - const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); - const knownFieldNames = Object.create(null); - return { - InputObjectTypeDefinition: checkFieldUniqueness, - InputObjectTypeExtension: checkFieldUniqueness, - InterfaceTypeDefinition: checkFieldUniqueness, - InterfaceTypeExtension: checkFieldUniqueness, - ObjectTypeDefinition: checkFieldUniqueness, - ObjectTypeExtension: checkFieldUniqueness - }; - function checkFieldUniqueness(node) { - var _node$fields; - const typeName = node.name.value; - if (!knownFieldNames[typeName]) { - knownFieldNames[typeName] = Object.create(null); - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; - const fieldNames = knownFieldNames[typeName]; - for (const fieldDef of fieldNodes) { - const fieldName = fieldDef.name.value; - if (hasField(existingTypeMap[typeName], fieldName)) { - context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, { - nodes: fieldDef.name - })); - } else if (fieldNames[fieldName]) { - context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" can only be defined once.`, { - nodes: [fieldNames[fieldName], fieldDef.name] - })); - } else { - fieldNames[fieldName] = fieldDef.name; - } - } - return false; - } -} -function hasField(type, fieldName) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) { - return type.getFields()[fieldName] != null; - } - return false; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ + function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema + ? schema.getTypeMap() + : Object.create(null); + const knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness, + }; + function checkFieldUniqueness(node) { + var _node$fields; + const typeName = node.name.value; + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + const fieldNames = knownFieldNames[typeName]; + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: fieldDef.name, + } + ) + ); + } else if (fieldNames[fieldName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${typeName}.${fieldName}" can only be defined once.`, + { + nodes: [fieldNames[fieldName], fieldDef.name], + } + ) + ); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + return false; + } + } + function hasField(type, fieldName) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) || + (0, _definition.isInputObjectType)(type) + ) { + return type.getFields()[fieldName] != null; + } + return false; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs": -/*!**********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs": + /*!**********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs ***! \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique fragment names - * - * A GraphQL document is only valid if all defined fragments have unique names. - * - * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness - */ -function UniqueFragmentNamesRule(context) { - const knownFragmentNames = Object.create(null); - return { - OperationDefinition: () => false, - FragmentDefinition(node) { - const fragmentName = node.name.value; - if (knownFragmentNames[fragmentName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one fragment named "${fragmentName}".`, { - nodes: [knownFragmentNames[fragmentName], node.name] - })); - } else { - knownFragmentNames[fragmentName] = node.name; - } - return false; - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + */ + function UniqueFragmentNamesRule(context) { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + if (knownFragmentNames[fragmentName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one fragment named "${fragmentName}".`, + { + nodes: [knownFragmentNames[fragmentName], node.name], + } + ) + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs": -/*!************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs": + /*!************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs ***! \************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; -var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique input field names - * - * A GraphQL input object value is only valid if all supplied fields are - * uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness - */ -function UniqueInputFieldNamesRule(context) { - const knownNameStack = []; - let knownNames = Object.create(null); - return { - ObjectValue: { - enter() { - knownNameStack.push(knownNames); - knownNames = Object.create(null); - }, - leave() { - const prevKnownNames = knownNameStack.pop(); - prevKnownNames || (0, _invariant.invariant)(false); - knownNames = prevKnownNames; - } - }, - ObjectField(node) { - const fieldName = node.name.value; - if (knownNames[fieldName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one input field named "${fieldName}".`, { - nodes: [knownNames[fieldName], node.name] - })); - } else { - knownNames[fieldName] = node.name; - } - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; + var _invariant = __webpack_require__( + /*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + */ + function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = Object.create(null); + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave() { + const prevKnownNames = knownNameStack.pop(); + prevKnownNames || (0, _invariant.invariant)(false); + knownNames = prevKnownNames; + }, + }, + ObjectField(node) { + const fieldName = node.name.value; + if (knownNames[fieldName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one input field named "${fieldName}".`, + { + nodes: [knownNames[fieldName], node.name], + } + ) + ); + } else { + knownNames[fieldName] = node.name; + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs": -/*!***********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs": + /*!***********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs ***! \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueOperationNamesRule = UniqueOperationNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique operation names - * - * A GraphQL document is only valid if all defined operations have unique names. - * - * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness - */ -function UniqueOperationNamesRule(context) { - const knownOperationNames = Object.create(null); - return { - OperationDefinition(node) { - const operationName = node.name; - if (operationName) { - if (knownOperationNames[operationName.value]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one operation named "${operationName.value}".`, { - nodes: [knownOperationNames[operationName.value], operationName] - })); - } else { - knownOperationNames[operationName.value] = operationName; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueOperationNamesRule = UniqueOperationNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + */ + function UniqueOperationNamesRule(context) { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one operation named "${operationName.value}".`, + { + nodes: [ + knownOperationNames[operationName.value], + operationName, + ], + } + ) + ); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + return false; + }, + FragmentDefinition: () => false, + }; } - } - return false; - }, - FragmentDefinition: () => false - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs": -/*!***********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs": + /*!***********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs ***! \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueOperationTypesRule = UniqueOperationTypesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique operation types - * - * A GraphQL document is only valid if it has only one type per operation. - */ -function UniqueOperationTypesRule(context) { - const schema = context.getSchema(); - const definedOperationTypes = Object.create(null); - const existingOperationTypes = schema ? { - query: schema.getQueryType(), - mutation: schema.getMutationType(), - subscription: schema.getSubscriptionType() - } : {}; - return { - SchemaDefinition: checkOperationTypes, - SchemaExtension: checkOperationTypes - }; - function checkOperationTypes(node) { - var _node$operationTypes; - - // See: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; - for (const operationType of operationTypesNodes) { - const operation = operationType.operation; - const alreadyDefinedOperationType = definedOperationTypes[operation]; - if (existingOperationTypes[operation]) { - context.reportError(new _GraphQLError.GraphQLError(`Type for ${operation} already defined in the schema. It cannot be redefined.`, { - nodes: operationType - })); - } else if (alreadyDefinedOperationType) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one ${operation} type in schema.`, { - nodes: [alreadyDefinedOperationType, operationType] - })); - } else { - definedOperationTypes[operation] = operationType; - } - } - return false; - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueOperationTypesRule = UniqueOperationTypesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ + function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema + ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType(), + } + : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes, + }; + function checkOperationTypes(node) { + var _node$operationTypes; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const operationTypesNodes = + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = + definedOperationTypes[operation]; + if (existingOperationTypes[operation]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Type for ${operation} already defined in the schema. It cannot be redefined.`, + { + nodes: operationType, + } + ) + ); + } else if (alreadyDefinedOperationType) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one ${operation} type in schema.`, + { + nodes: [alreadyDefinedOperationType, operationType], + } + ) + ); + } else { + definedOperationTypes[operation] = operationType; + } + } + return false; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs": -/*!******************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs": + /*!******************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs ***! \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueTypeNamesRule = UniqueTypeNamesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique type names - * - * A GraphQL document is only valid if all defined types have unique names. - */ -function UniqueTypeNamesRule(context) { - const knownTypeNames = Object.create(null); - const schema = context.getSchema(); - return { - ScalarTypeDefinition: checkTypeName, - ObjectTypeDefinition: checkTypeName, - InterfaceTypeDefinition: checkTypeName, - UnionTypeDefinition: checkTypeName, - EnumTypeDefinition: checkTypeName, - InputObjectTypeDefinition: checkTypeName - }; - function checkTypeName(node) { - const typeName = node.name.value; - if (schema !== null && schema !== void 0 && schema.getType(typeName)) { - context.reportError(new _GraphQLError.GraphQLError(`Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, { - nodes: node.name - })); - return; - } - if (knownTypeNames[typeName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one type named "${typeName}".`, { - nodes: [knownTypeNames[typeName], node.name] - })); - } else { - knownTypeNames[typeName] = node.name; - } - return false; - } -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ + function UniqueTypeNamesRule(context) { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName, + }; + function checkTypeName(node) { + const typeName = node.name.value; + if ( + schema !== null && + schema !== void 0 && + schema.getType(typeName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, + { + nodes: node.name, + } + ) + ); + return; + } + if (knownTypeNames[typeName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one type named "${typeName}".`, + { + nodes: [knownTypeNames[typeName], node.name], + } + ) + ); + } else { + knownTypeNames[typeName] = node.name; + } + return false; + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs": -/*!**********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs": + /*!**********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs ***! \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.UniqueVariableNamesRule = UniqueVariableNamesRule; -var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -/** - * Unique variable names - * - * A GraphQL operation is only valid if all its variables are uniquely named. - */ -function UniqueVariableNamesRule(context) { - return { - OperationDefinition(operationNode) { - var _operationNode$variab; - - // See: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const variableDefinitions = (_operationNode$variab = operationNode.variableDefinitions) !== null && _operationNode$variab !== void 0 ? _operationNode$variab : []; - const seenVariableDefinitions = (0, _groupBy.groupBy)(variableDefinitions, node => node.variable.name.value); - for (const [variableName, variableNodes] of seenVariableDefinitions) { - if (variableNodes.length > 1) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one variable named "$${variableName}".`, { - nodes: variableNodes.map(node => node.variable.name) - })); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.UniqueVariableNamesRule = UniqueVariableNamesRule; + var _groupBy = __webpack_require__( + /*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + /** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + var _operationNode$variab; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const variableDefinitions = + (_operationNode$variab = operationNode.variableDefinitions) !== + null && _operationNode$variab !== void 0 + ? _operationNode$variab + : []; + const seenVariableDefinitions = (0, _groupBy.groupBy)( + variableDefinitions, + (node) => node.variable.name.value + ); + for (const [ + variableName, + variableNodes, + ] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one variable named "$${variableName}".`, + { + nodes: variableNodes.map((node) => node.variable.name), + } + ) + ); + } + } + }, + }; } - } - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs": -/*!**********************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs": + /*!**********************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs ***! \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; -var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); -var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * Value literals of correct type - * - * A GraphQL document is only valid if all value literals are of the type - * expected at their position. - * - * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type - */ -function ValuesOfCorrectTypeRule(context) { - return { - ListValue(node) { - // Note: TypeInfo will traverse into a list's item type, so look to the - // parent input type to check if it is a list. - const type = (0, _definition.getNullableType)(context.getParentInputType()); - if (!(0, _definition.isListType)(type)) { - isValidValueNode(context, node); - return false; // Don't traverse further. - } - }, - ObjectValue(node) { - const type = (0, _definition.getNamedType)(context.getInputType()); - if (!(0, _definition.isInputObjectType)(type)) { - isValidValueNode(context, node); - return false; // Don't traverse further. - } // Ensure every required field exists. - - const fieldNodeMap = (0, _keyMap.keyMap)(node.fields, field => field.name.value); - for (const fieldDef of Object.values(type.getFields())) { - const fieldNode = fieldNodeMap[fieldDef.name]; - if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { - const typeStr = (0, _inspect.inspect)(fieldDef.type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, { - nodes: node - })); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; + var _didYouMean = __webpack_require__( + /*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs" + ); + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _keyMap = __webpack_require__( + /*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs" + ); + var _suggestionList = __webpack_require__( + /*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _printer = __webpack_require__( + /*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + */ + function ValuesOfCorrectTypeRule(context) { + return { + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = (0, _definition.getNullableType)( + context.getParentInputType() + ); + if (!(0, _definition.isListType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue(node) { + const type = (0, _definition.getNamedType)( + context.getInputType() + ); + if (!(0, _definition.isInputObjectType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + const fieldNodeMap = (0, _keyMap.keyMap)( + node.fields, + (field) => field.name.value + ); + for (const fieldDef of Object.values(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; + if ( + !fieldNode && + (0, _definition.isRequiredInputField)(fieldDef) + ) { + const typeStr = (0, _inspect.inspect)(fieldDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, + { + nodes: node, + } + ) + ); + } + } + }, + ObjectField(node) { + const parentType = (0, _definition.getNamedType)( + context.getParentInputType() + ); + const fieldType = context.getInputType(); + if ( + !fieldType && + (0, _definition.isInputObjectType)(parentType) + ) { + const suggestions = (0, _suggestionList.suggestionList)( + node.name.value, + Object.keys(parentType.getFields()) + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${node.name.value}" is not defined by type "${parentType.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: node, + } + ) + ); + } + }, + NullValue(node) { + const type = context.getInputType(); + if ((0, _definition.isNonNullType)(type)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${(0, _inspect.inspect)( + type + )}", found ${(0, _printer.print)(node)}.`, + { + nodes: node, + } + ) + ); + } + }, + EnumValue: (node) => isValidValueNode(context, node), + IntValue: (node) => isValidValueNode(context, node), + FloatValue: (node) => isValidValueNode(context, node), + StringValue: (node) => isValidValueNode(context, node), + BooleanValue: (node) => isValidValueNode(context, node), + }; + } + /** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + + function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + if (!locationType) { + return; + } + const type = (0, _definition.getNamedType)(locationType); + if (!(0, _definition.isLeafType)(type)) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, + _printer.print)(node)}.`, + { + nodes: node, + } + ) + ); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + try { + const parseResult = type.parseLiteral( + node, + undefined + /* variables */ + ); + if (parseResult === undefined) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, + _printer.print)(node)}.`, + { + nodes: node, + } + ) + ); + } + } catch (error) { + const typeStr = (0, _inspect.inspect)(locationType); + if (error instanceof _GraphQLError.GraphQLError) { + context.reportError(error); + } else { + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, + _printer.print)(node)}; ` + error.message, + { + nodes: node, + originalError: error, + } + ) + ); + } + } } - } - }, - ObjectField(node) { - const parentType = (0, _definition.getNamedType)(context.getParentInputType()); - const fieldType = context.getInputType(); - if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { - const suggestions = (0, _suggestionList.suggestionList)(node.name.value, Object.keys(parentType.getFields())); - context.reportError(new _GraphQLError.GraphQLError(`Field "${node.name.value}" is not defined by type "${parentType.name}".` + (0, _didYouMean.didYouMean)(suggestions), { - nodes: node - })); - } - }, - NullValue(node) { - const type = context.getInputType(); - if ((0, _definition.isNonNullType)(type)) { - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${(0, _inspect.inspect)(type)}", found ${(0, _printer.print)(node)}.`, { - nodes: node - })); - } - }, - EnumValue: node => isValidValueNode(context, node), - IntValue: node => isValidValueNode(context, node), - FloatValue: node => isValidValueNode(context, node), - StringValue: node => isValidValueNode(context, node), - BooleanValue: node => isValidValueNode(context, node) - }; -} -/** - * Any value literal may be a valid representation of a Scalar, depending on - * that scalar type. - */ - -function isValidValueNode(context, node) { - // Report any error at the full type expected by the location. - const locationType = context.getInputType(); - if (!locationType) { - return; - } - const type = (0, _definition.getNamedType)(locationType); - if (!(0, _definition.isLeafType)(type)) { - const typeStr = (0, _inspect.inspect)(locationType); - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { - nodes: node - })); - return; - } // Scalars and Enums determine if a literal value is valid via parseLiteral(), - // which may throw or return an invalid value to indicate failure. - - try { - const parseResult = type.parseLiteral(node, undefined - /* variables */); - if (parseResult === undefined) { - const typeStr = (0, _inspect.inspect)(locationType); - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { - nodes: node - })); - } - } catch (error) { - const typeStr = (0, _inspect.inspect)(locationType); - if (error instanceof _GraphQLError.GraphQLError) { - context.reportError(error); - } else { - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}; ` + error.message, { - nodes: node, - originalError: error - })); - } - } -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs": -/*!*************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs": + /*!*************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs ***! \*************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -/** - * Variables are input types - * - * A GraphQL operation is only valid if all the variables it defines are of - * input types (scalar, enum, or input object). - * - * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types - */ -function VariablesAreInputTypesRule(context) { - return { - VariableDefinition(node) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); - if (type !== undefined && !(0, _definition.isInputType)(type)) { - const variableName = node.variable.name.value; - const typeName = (0, _printer.print)(node.type); - context.reportError(new _GraphQLError.GraphQLError(`Variable "$${variableName}" cannot be non-input type "${typeName}".`, { - nodes: node.type - })); - } - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _printer = __webpack_require__( + /*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + /** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + * + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types + */ + function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + node.type + ); + if (type !== undefined && !(0, _definition.isInputType)(type)) { + const variableName = node.variable.name.value; + const typeName = (0, _printer.print)(node.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${variableName}" cannot be non-input type "${typeName}".`, + { + nodes: node.type, + } + ) + ); + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs": -/*!*****************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs": + /*!*****************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs ***! \*****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; -var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); -var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); -var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); -/** - * Variables in allowed position - * - * Variable usages must be compatible with the arguments they are passed to. - * - * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed - */ -function VariablesInAllowedPositionRule(context) { - let varDefMap = Object.create(null); - return { - OperationDefinition: { - enter() { - varDefMap = Object.create(null); - }, - leave(operation) { - const usages = context.getRecursiveVariableUsages(operation); - for (const { - node, - type, - defaultValue - } of usages) { - const varName = node.name.value; - const varDef = varDefMap[varName]; - if (varDef && type) { - // A var type is allowed if it is the same or more strict (e.g. is - // a subtype of) than the expected type. It can be more strict if - // the variable type is non-null when the expected type is nullable. - // If both are list types, the variable item type can be more strict - // than the expected item type (contravariant). - const schema = context.getSchema(); - const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); - if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { - const varTypeStr = (0, _inspect.inspect)(varType); - const typeStr = (0, _inspect.inspect)(type); - context.reportError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, { - nodes: [varDef, node] - })); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; + var _inspect = __webpack_require__( + /*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _kinds = __webpack_require__( + /*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs" + ); + var _definition = __webpack_require__( + /*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _typeComparators = __webpack_require__( + /*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs" + ); + var _typeFromAST = __webpack_require__( + /*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs" + ); + /** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + */ + function VariablesInAllowedPositionRule(context) { + let varDefMap = Object.create(null); + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { node, type, defaultValue } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = (0, _typeFromAST.typeFromAST)( + schema, + varDef.type + ); + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue + ) + ) { + const varTypeStr = (0, _inspect.inspect)(varType); + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, + { + nodes: [varDef, node], + } + ) + ); + } + } + } + }, + }, + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; + } + /** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + + function allowedVariableUsage( + schema, + varType, + varDefaultValue, + locationType, + locationDefaultValue + ) { + if ( + (0, _definition.isNonNullType)(locationType) && + !(0, _definition.isNonNullType)(varType) + ) { + const hasNonNullVariableDefaultValue = + varDefaultValue != null && + varDefaultValue.kind !== _kinds.Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; } + const nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)( + schema, + varType, + nullableLocationType + ); } + return (0, _typeComparators.isTypeSubTypeOf)( + schema, + varType, + locationType + ); } - } - }, - VariableDefinition(node) { - varDefMap[node.variable.name.value] = node; - } - }; -} -/** - * Returns true if the variable is allowed in the location it was found, - * which includes considering if default values exist for either the variable - * or the location at which it is located. - */ - -function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { - if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { - const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; - const hasLocationDefaultValue = locationDefaultValue !== undefined; - if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { - return false; - } - const nullableLocationType = locationType.ofType; - return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); - } - return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs": -/*!****************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs": + /*!****************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs ***! \****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; -var _invariant = __webpack_require__(/*! ../../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); -var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -/** - * No deprecated - * - * A GraphQL document is only valid if all selected fields and all used enum values have not been - * deprecated. - * - * Note: This rule is optional and is not part of the Validation section of the GraphQL - * Specification. The main purpose of this rule is detection of deprecated usages and not - * necessarily to forbid their use when querying a service. - */ -function NoDeprecatedCustomRule(context) { - return { - Field(node) { - const fieldDef = context.getFieldDef(); - const deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason; - if (fieldDef && deprecationReason != null) { - const parentType = context.getParentType(); - parentType != null || (0, _invariant.invariant)(false); - context.reportError(new _GraphQLError.GraphQLError(`The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - }, - Argument(node) { - const argDef = context.getArgument(); - const deprecationReason = argDef === null || argDef === void 0 ? void 0 : argDef.deprecationReason; - if (argDef && deprecationReason != null) { - const directiveDef = context.getDirective(); - if (directiveDef != null) { - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { - nodes: node - })); - } else { - const parentType = context.getParentType(); - const fieldDef = context.getFieldDef(); - parentType != null && fieldDef != null || (0, _invariant.invariant)(false); - context.reportError(new _GraphQLError.GraphQLError(`Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - } - }, - ObjectField(node) { - const inputObjectDef = (0, _definition.getNamedType)(context.getParentInputType()); - if ((0, _definition.isInputObjectType)(inputObjectDef)) { - const inputFieldDef = inputObjectDef.getFields()[node.name.value]; - const deprecationReason = inputFieldDef === null || inputFieldDef === void 0 ? void 0 : inputFieldDef.deprecationReason; - if (deprecationReason != null) { - context.reportError(new _GraphQLError.GraphQLError(`The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, { - nodes: node - })); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; + var _invariant = __webpack_require__( + /*! ../../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + /** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ + function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = + fieldDef === null || fieldDef === void 0 + ? void 0 + : fieldDef.deprecationReason; + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + parentType != null || (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + } + ) + ); + } + }, + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = + argDef === null || argDef === void 0 + ? void 0 + : argDef.deprecationReason; + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); + if (directiveDef != null) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + } + ) + ); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + (parentType != null && fieldDef != null) || + (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + } + ) + ); + } + } + }, + ObjectField(node) { + const inputObjectDef = (0, _definition.getNamedType)( + context.getParentInputType() + ); + if ((0, _definition.isInputObjectType)(inputObjectDef)) { + const inputFieldDef = + inputObjectDef.getFields()[node.name.value]; + const deprecationReason = + inputFieldDef === null || inputFieldDef === void 0 + ? void 0 + : inputFieldDef.deprecationReason; + if (deprecationReason != null) { + context.reportError( + new _GraphQLError.GraphQLError( + `The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + } + ) + ); + } + } + }, + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = + enumValueDef === null || enumValueDef === void 0 + ? void 0 + : enumValueDef.deprecationReason; + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = (0, _definition.getNamedType)( + context.getInputType() + ); + enumTypeDef != null || (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + } + ) + ); + } + }, + }; } - } - }, - EnumValue(node) { - const enumValueDef = context.getEnumValue(); - const deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason; - if (enumValueDef && deprecationReason != null) { - const enumTypeDef = (0, _definition.getNamedType)(context.getInputType()); - enumTypeDef != null || (0, _invariant.invariant)(false); - context.reportError(new _GraphQLError.GraphQLError(`The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - } - }; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs": -/*!*************************************************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs": + /*!*************************************************************************************************!*\ !*** ../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs ***! \*************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; -var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); -var _introspection = __webpack_require__(/*! ../../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); -/** - * Prohibit introspection queries - * - * A GraphQL document is only valid if all fields selected are not fields that - * return an introspection type. - * - * Note: This rule is optional and is not part of the Validation section of the - * GraphQL Specification. This rule effectively disables introspection, which - * does not reflect best practices and should only be done if absolutely necessary. - */ -function NoSchemaIntrospectionCustomRule(context) { - return { - Field(node) { - const type = (0, _definition.getNamedType)(context.getType()); - if (type && (0, _introspection.isIntrospectionType)(type)) { - context.reportError(new _GraphQLError.GraphQLError(`GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, { - nodes: node - })); - } - } - }; -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.NoSchemaIntrospectionCustomRule = + NoSchemaIntrospectionCustomRule; + var _GraphQLError = __webpack_require__( + /*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _definition = __webpack_require__( + /*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs" + ); + var _introspection = __webpack_require__( + /*! ../../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs" + ); + /** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ + function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = (0, _definition.getNamedType)(context.getType()); + if (type && (0, _introspection.isIntrospectionType)(type)) { + context.reportError( + new _GraphQLError.GraphQLError( + `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, + { + nodes: node, + } + ) + ); + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/validation/specifiedRules.mjs": -/*!*******************************************************************!*\ + /***/ "../../../node_modules/graphql/validation/specifiedRules.mjs": + /*!*******************************************************************!*\ !*** ../../../node_modules/graphql/validation/specifiedRules.mjs ***! \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.specifiedSDLRules = exports.specifiedRules = void 0; + var _ExecutableDefinitionsRule = __webpack_require__( + /*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs" + ); + var _FieldsOnCorrectTypeRule = __webpack_require__( + /*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs" + ); + var _FragmentsOnCompositeTypesRule = __webpack_require__( + /*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs" + ); + var _KnownArgumentNamesRule = __webpack_require__( + /*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs" + ); + var _KnownDirectivesRule = __webpack_require__( + /*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs" + ); + var _KnownFragmentNamesRule = __webpack_require__( + /*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs" + ); + var _KnownTypeNamesRule = __webpack_require__( + /*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs" + ); + var _LoneAnonymousOperationRule = __webpack_require__( + /*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs" + ); + var _LoneSchemaDefinitionRule = __webpack_require__( + /*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs" + ); + var _NoFragmentCyclesRule = __webpack_require__( + /*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs" + ); + var _NoUndefinedVariablesRule = __webpack_require__( + /*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs" + ); + var _NoUnusedFragmentsRule = __webpack_require__( + /*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs" + ); + var _NoUnusedVariablesRule = __webpack_require__( + /*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs" + ); + var _OverlappingFieldsCanBeMergedRule = __webpack_require__( + /*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs" + ); + var _PossibleFragmentSpreadsRule = __webpack_require__( + /*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs" + ); + var _PossibleTypeExtensionsRule = __webpack_require__( + /*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs" + ); + var _ProvidedRequiredArgumentsRule = __webpack_require__( + /*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs" + ); + var _ScalarLeafsRule = __webpack_require__( + /*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs" + ); + var _SingleFieldSubscriptionsRule = __webpack_require__( + /*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs" + ); + var _UniqueArgumentDefinitionNamesRule = __webpack_require__( + /*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs" + ); + var _UniqueArgumentNamesRule = __webpack_require__( + /*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs" + ); + var _UniqueDirectiveNamesRule = __webpack_require__( + /*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs" + ); + var _UniqueDirectivesPerLocationRule = __webpack_require__( + /*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs" + ); + var _UniqueEnumValueNamesRule = __webpack_require__( + /*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs" + ); + var _UniqueFieldDefinitionNamesRule = __webpack_require__( + /*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs" + ); + var _UniqueFragmentNamesRule = __webpack_require__( + /*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs" + ); + var _UniqueInputFieldNamesRule = __webpack_require__( + /*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs" + ); + var _UniqueOperationNamesRule = __webpack_require__( + /*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs" + ); + var _UniqueOperationTypesRule = __webpack_require__( + /*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs" + ); + var _UniqueTypeNamesRule = __webpack_require__( + /*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs" + ); + var _UniqueVariableNamesRule = __webpack_require__( + /*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs" + ); + var _ValuesOfCorrectTypeRule = __webpack_require__( + /*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs" + ); + var _VariablesAreInputTypesRule = __webpack_require__( + /*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs" + ); + var _VariablesInAllowedPositionRule = __webpack_require__( + /*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs" + ); + // Spec Section: "Executable Definitions" + // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + // Spec Section: "Fragments on Composite Types" + // Spec Section: "Argument Names" -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.specifiedSDLRules = exports.specifiedRules = void 0; -var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); -var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); -var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); -var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); -var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); -var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); -var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); -var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); -var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); -var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); -var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); -var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); -var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); -var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); -var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); -var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); -var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); -var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); -var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); -var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); -var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); -var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); -var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); -var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); -var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); -var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); -var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); -var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); -var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); -var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); -var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); -var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); -var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); -var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); -// Spec Section: "Executable Definitions" -// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + // Spec Section: "Directives Are Defined" -// Spec Section: "Fragments on Composite Types" + // Spec Section: "Fragment spread target defined" -// Spec Section: "Argument Names" + // Spec Section: "Fragment Spread Type Existence" -// Spec Section: "Directives Are Defined" + // Spec Section: "Lone Anonymous Operation" -// Spec Section: "Fragment spread target defined" + // SDL-specific validation rules -// Spec Section: "Fragment Spread Type Existence" + // Spec Section: "Fragments must not form cycles" -// Spec Section: "Lone Anonymous Operation" + // Spec Section: "All Variable Used Defined" -// SDL-specific validation rules + // Spec Section: "Fragments must be used" -// Spec Section: "Fragments must not form cycles" + // Spec Section: "All Variables Used" -// Spec Section: "All Variable Used Defined" + // Spec Section: "Field Selection Merging" -// Spec Section: "Fragments must be used" + // Spec Section: "Fragment spread is possible" -// Spec Section: "All Variables Used" + // Spec Section: "Argument Optionality" -// Spec Section: "Field Selection Merging" + // Spec Section: "Leaf Field Selections" -// Spec Section: "Fragment spread is possible" + // Spec Section: "Subscriptions with Single Root Field" -// Spec Section: "Argument Optionality" + // Spec Section: "Argument Uniqueness" -// Spec Section: "Leaf Field Selections" + // Spec Section: "Directives Are Unique Per Location" -// Spec Section: "Subscriptions with Single Root Field" + // Spec Section: "Fragment Name Uniqueness" -// Spec Section: "Argument Uniqueness" + // Spec Section: "Input Object Field Uniqueness" -// Spec Section: "Directives Are Unique Per Location" + // Spec Section: "Operation Name Uniqueness" -// Spec Section: "Fragment Name Uniqueness" + // Spec Section: "Variable Uniqueness" -// Spec Section: "Input Object Field Uniqueness" + // Spec Section: "Value Type Correctness" -// Spec Section: "Operation Name Uniqueness" + // Spec Section: "Variables are Input Types" -// Spec Section: "Variable Uniqueness" + // Spec Section: "All Variable Usages Are Allowed" -// Spec Section: "Value Type Correctness" + /** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + const specifiedRules = (exports.specifiedRules = Object.freeze([ + _ExecutableDefinitionsRule.ExecutableDefinitionsRule, + _UniqueOperationNamesRule.UniqueOperationNamesRule, + _LoneAnonymousOperationRule.LoneAnonymousOperationRule, + _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, + _KnownTypeNamesRule.KnownTypeNamesRule, + _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, + _VariablesAreInputTypesRule.VariablesAreInputTypesRule, + _ScalarLeafsRule.ScalarLeafsRule, + _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, + _UniqueFragmentNamesRule.UniqueFragmentNamesRule, + _KnownFragmentNamesRule.KnownFragmentNamesRule, + _NoUnusedFragmentsRule.NoUnusedFragmentsRule, + _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, + _NoFragmentCyclesRule.NoFragmentCyclesRule, + _UniqueVariableNamesRule.UniqueVariableNamesRule, + _NoUndefinedVariablesRule.NoUndefinedVariablesRule, + _NoUnusedVariablesRule.NoUnusedVariablesRule, + _KnownDirectivesRule.KnownDirectivesRule, + _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, + _KnownArgumentNamesRule.KnownArgumentNamesRule, + _UniqueArgumentNamesRule.UniqueArgumentNamesRule, + _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, + _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, + _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, + _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, + _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, + ])); + /** + * @internal + */ -// Spec Section: "Variables are Input Types" + const specifiedSDLRules = (exports.specifiedSDLRules = Object.freeze([ + _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, + _UniqueOperationTypesRule.UniqueOperationTypesRule, + _UniqueTypeNamesRule.UniqueTypeNamesRule, + _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, + _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, + _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, + _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, + _KnownTypeNamesRule.KnownTypeNamesRule, + _KnownDirectivesRule.KnownDirectivesRule, + _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, + _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, + _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, + _UniqueArgumentNamesRule.UniqueArgumentNamesRule, + _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, + _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule, + ])); + + /***/ + }, -// Spec Section: "All Variable Usages Are Allowed" + /***/ "../../../node_modules/graphql/validation/validate.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/validation/validate.mjs ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.assertValidSDL = assertValidSDL; + exports.assertValidSDLExtension = assertValidSDLExtension; + exports.validate = validate; + exports.validateSDL = validateSDL; + var _devAssert = __webpack_require__( + /*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs" + ); + var _GraphQLError = __webpack_require__( + /*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs" + ); + var _visitor = __webpack_require__( + /*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs" + ); + var _validate = __webpack_require__( + /*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs" + ); + var _TypeInfo = __webpack_require__( + /*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs" + ); + var _specifiedRules = __webpack_require__( + /*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs" + ); + var _ValidationContext = __webpack_require__( + /*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs" + ); + /** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so by default `maxErrors` set to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ -/** - * This set includes all validation rules defined by the GraphQL spec. - * - * The order of the rules in this list has been adjusted to lead to the - * most clear output when encountering multiple validation errors. - */ -const specifiedRules = exports.specifiedRules = Object.freeze([_ExecutableDefinitionsRule.ExecutableDefinitionsRule, _UniqueOperationNamesRule.UniqueOperationNamesRule, _LoneAnonymousOperationRule.LoneAnonymousOperationRule, _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, _KnownTypeNamesRule.KnownTypeNamesRule, _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, _VariablesAreInputTypesRule.VariablesAreInputTypesRule, _ScalarLeafsRule.ScalarLeafsRule, _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, _UniqueFragmentNamesRule.UniqueFragmentNamesRule, _KnownFragmentNamesRule.KnownFragmentNamesRule, _NoUnusedFragmentsRule.NoUnusedFragmentsRule, _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, _NoFragmentCyclesRule.NoFragmentCyclesRule, _UniqueVariableNamesRule.UniqueVariableNamesRule, _NoUndefinedVariablesRule.NoUndefinedVariablesRule, _NoUnusedVariablesRule.NoUnusedVariablesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _KnownArgumentNamesRule.KnownArgumentNamesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule]); -/** - * @internal - */ + function validate( + schema, + documentAST, + rules = _specifiedRules.specifiedRules, + options /** @deprecated will be removed in 17.0.0 */, + typeInfo = new _TypeInfo.TypeInfo(schema) + ) { + var _options$maxErrors; + const maxErrors = + (_options$maxErrors = + options === null || options === void 0 + ? void 0 + : options.maxErrors) !== null && _options$maxErrors !== void 0 + ? _options$maxErrors + : 100; + documentAST || + (0, _devAssert.devAssert)(false, "Must provide document."); // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + const abortObj = Object.freeze({}); + const errors = []; + const context = new _ValidationContext.ValidationContext( + schema, + documentAST, + typeInfo, + (error) => { + if (errors.length >= maxErrors) { + errors.push( + new _GraphQLError.GraphQLError( + "Too many validation errors, error limit reached. Validation aborted." + ) + ); // eslint-disable-next-line @typescript-eslint/no-throw-literal + + throw abortObj; + } + errors.push(error); + } + ); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. -const specifiedSDLRules = exports.specifiedSDLRules = Object.freeze([_LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, _UniqueOperationTypesRule.UniqueOperationTypesRule, _UniqueTypeNamesRule.UniqueTypeNamesRule, _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, _KnownTypeNamesRule.KnownTypeNamesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule]); + const visitor = (0, _visitor.visitInParallel)( + rules.map((rule) => rule(context)) + ); // Visit the whole document with each instance of all provided rules. -/***/ }), + try { + (0, _visitor.visit)( + documentAST, + (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor) + ); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + return errors; + } + /** + * @internal + */ -/***/ "../../../node_modules/graphql/validation/validate.mjs": -/*!*************************************************************!*\ - !*** ../../../node_modules/graphql/validation/validate.mjs ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.assertValidSDL = assertValidSDL; -exports.assertValidSDLExtension = assertValidSDLExtension; -exports.validate = validate; -exports.validateSDL = validateSDL; -var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); -var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); -var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); -var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); -var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); -var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); -var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); -/** - * Implements the "Validation" section of the spec. - * - * Validation runs synchronously, returning an array of encountered errors, or - * an empty array if no errors were encountered and the document is valid. - * - * A list of specific validation rules may be provided. If not provided, the - * default list of rules defined by the GraphQL specification will be used. - * - * Each validation rules is a function which returns a visitor - * (see the language/visitor API). Visitor methods are expected to return - * GraphQLErrors, or Arrays of GraphQLErrors when invalid. - * - * Validate will stop validation after a `maxErrors` limit has been reached. - * Attackers can send pathologically invalid queries to induce a DoS attack, - * so by default `maxErrors` set to 100 errors. - * - * Optionally a custom TypeInfo instance may be provided. If not provided, one - * will be created from the provided schema. - */ - -function validate(schema, documentAST, rules = _specifiedRules.specifiedRules, options, /** @deprecated will be removed in 17.0.0 */ -typeInfo = new _TypeInfo.TypeInfo(schema)) { - var _options$maxErrors; - const maxErrors = (_options$maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors) !== null && _options$maxErrors !== void 0 ? _options$maxErrors : 100; - documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. - - (0, _validate.assertValidSchema)(schema); - const abortObj = Object.freeze({}); - const errors = []; - const context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo, error => { - if (errors.length >= maxErrors) { - errors.push(new _GraphQLError.GraphQLError('Too many validation errors, error limit reached. Validation aborted.')); // eslint-disable-next-line @typescript-eslint/no-throw-literal - - throw abortObj; - } - errors.push(error); - }); // This uses a specialized visitor which runs multiple visitors in parallel, - // while maintaining the visitor skip and break API. + function validateSDL( + documentAST, + schemaToExtend, + rules = _specifiedRules.specifiedSDLRules + ) { + const errors = []; + const context = new _ValidationContext.SDLValidationContext( + documentAST, + schemaToExtend, + (error) => { + errors.push(error); + } + ); + const visitors = rules.map((rule) => rule(context)); + (0, _visitor.visit)( + documentAST, + (0, _visitor.visitInParallel)(visitors) + ); + return errors; + } + /** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ - const visitor = (0, _visitor.visitInParallel)(rules.map(rule => rule(context))); // Visit the whole document with each instance of all provided rules. + function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join("\n\n")); + } + } + /** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ - try { - (0, _visitor.visit)(documentAST, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor)); - } catch (e) { - if (e !== abortObj) { - throw e; - } - } - return errors; -} -/** - * @internal - */ - -function validateSDL(documentAST, schemaToExtend, rules = _specifiedRules.specifiedSDLRules) { - const errors = []; - const context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend, error => { - errors.push(error); - }); - const visitors = rules.map(rule => rule(context)); - (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); - return errors; -} -/** - * Utility function which asserts a SDL document is valid by throwing an error - * if it is invalid. - * - * @internal - */ - -function assertValidSDL(documentAST) { - const errors = validateSDL(documentAST); - if (errors.length !== 0) { - throw new Error(errors.map(error => error.message).join('\n\n')); - } -} -/** - * Utility function which asserts a SDL document is valid by throwing an error - * if it is invalid. - * - * @internal - */ - -function assertValidSDLExtension(documentAST, schema) { - const errors = validateSDL(documentAST, schema); - if (errors.length !== 0) { - throw new Error(errors.map(error => error.message).join('\n\n')); - } -} + function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join("\n\n")); + } + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/graphql/version.mjs": -/*!*************************************************!*\ + /***/ "../../../node_modules/graphql/version.mjs": + /*!*************************************************!*\ !*** ../../../node_modules/graphql/version.mjs ***! \*************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.versionInfo = exports.version = void 0; -// Note: This file is autogenerated using "resources/gen-version.js" script and -// automatically updated by "npm version" command. + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.versionInfo = exports.version = void 0; + // Note: This file is autogenerated using "resources/gen-version.js" script and + // automatically updated by "npm version" command. -/** - * A string containing the version of the GraphQL.js library - */ -const version = exports.version = '16.8.1'; -/** - * An object containing the components of the GraphQL.js version string - */ + /** + * A string containing the version of the GraphQL.js library + */ + const version = (exports.version = "16.8.1"); + /** + * An object containing the components of the GraphQL.js version string + */ -const versionInfo = exports.versionInfo = Object.freeze({ - major: 16, - minor: 8, - patch: 1, - preReleaseTag: null -}); + const versionInfo = (exports.versionInfo = Object.freeze({ + major: 16, + minor: 8, + patch: 1, + preReleaseTag: null, + })); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/hey-listen/dist/hey-listen.es.js": -/*!**************************************************************!*\ + /***/ "../../../node_modules/hey-listen/dist/hey-listen.es.js": + /*!**************************************************************!*\ !*** ../../../node_modules/hey-listen/dist/hey-listen.es.js ***! \**************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.warning = exports.invariant = void 0; -var warning = function () {}; -exports.warning = warning; -var invariant = function () {}; -exports.invariant = invariant; -if (true) { - exports.warning = warning = function (check, message) { - if (!check && typeof console !== 'undefined') { - console.warn(message); - } - }; - exports.invariant = invariant = function (check, message) { - if (!check) { - throw new Error(message); - } - }; -} + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.warning = exports.invariant = void 0; + var warning = function () {}; + exports.warning = warning; + var invariant = function () {}; + exports.invariant = invariant; + if (true) { + exports.warning = warning = function (check, message) { + if (!check && typeof console !== "undefined") { + console.warn(message); + } + }; + exports.invariant = invariant = function (check, message) { + if (!check) { + throw new Error(message); + } + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/is-plain-object/index.js": -/*!******************************************************!*\ + /***/ "../../../node_modules/is-plain-object/index.js": + /*!******************************************************!*\ !*** ../../../node_modules/is-plain-object/index.js ***! \******************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - - - -var isObject = __webpack_require__(/*! isobject */ "../../../node_modules/isobject/index.js"); -function isObjectObject(o) { - return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; -} -module.exports = function isPlainObject(o) { - var ctor, prot; - if (isObjectObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; - - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + /*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - // Most likely a plain Object - return true; -}; + var isObject = __webpack_require__( + /*! isobject */ "../../../node_modules/isobject/index.js" + ); + function isObjectObject(o) { + return ( + isObject(o) === true && + Object.prototype.toString.call(o) === "[object Object]" + ); + } + module.exports = function isPlainObject(o) { + var ctor, prot; + if (isObjectObject(o) === false) return false; -/***/ }), + // If has modified constructor + ctor = o.constructor; + if (typeof ctor !== "function") return false; -/***/ "../../../node_modules/is-primitive/index.js": -/*!***************************************************!*\ - !*** ../../../node_modules/is-primitive/index.js ***! - \***************************************************/ -/***/ (function(module) { + // If has modified prototype + prot = ctor.prototype; + if (isObjectObject(prot) === false) return false; -/*! - * is-primitive - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Released under the MIT License. - */ + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty("isPrototypeOf") === false) { + return false; + } + // Most likely a plain Object + return true; + }; + /***/ + }, -module.exports = function isPrimitive(val) { - if (typeof val === 'object') { - return val === null; - } - return typeof val !== 'function'; -}; + /***/ "../../../node_modules/is-primitive/index.js": + /*!***************************************************!*\ + !*** ../../../node_modules/is-primitive/index.js ***! + \***************************************************/ + /***/ function (module) { + /*! + * is-primitive + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + + module.exports = function isPrimitive(val) { + if (typeof val === "object") { + return val === null; + } + return typeof val !== "function"; + }; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/isarray/index.js": -/*!**********************************************!*\ + /***/ "../../../node_modules/isarray/index.js": + /*!**********************************************!*\ !*** ../../../node_modules/isarray/index.js ***! \**********************************************/ -/***/ (function(module) { - - - -var toString = {}.toString; -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + /***/ function (module) { + var toString = {}.toString; + module.exports = + Array.isArray || + function (arr) { + return toString.call(arr) == "[object Array]"; + }; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/isobject/index.js": -/*!***********************************************!*\ + /***/ "../../../node_modules/isobject/index.js": + /*!***********************************************!*\ !*** ../../../node_modules/isobject/index.js ***! \***********************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + /*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + var isArray = __webpack_require__( + /*! isarray */ "../../../node_modules/isarray/index.js" + ); + module.exports = function isObject(val) { + return ( + val != null && typeof val === "object" && isArray(val) === false + ); + }; -/*! - * isobject - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + /***/ + }, + /***/ "../../../node_modules/meros/browser/index.js": + /*!****************************************************!*\ + !*** ../../../node_modules/meros/browser/index.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports) { + var e = new TextDecoder(); + async function t(t, n) { + if (!t.ok || !t.body || t.bodyUsed) return t; + let i = t.headers.get("content-type"); + if (!i || !~i.indexOf("multipart/")) return t; + let l = i.indexOf("boundary="), + r = "-"; + if (~l) { + let e = l + 9, + t = i.indexOf(";", e); + r = i + .slice(e, t > -1 ? t : void 0) + .trim() + .replace(/"/g, ""); + } + return (async function* (t, n, i) { + let l, + r, + d, + o = t.getReader(), + a = !i || !i.multiple, + f = n.length, + s = "", + c = []; + try { + let t; + e: for (; !(t = await o.read()).done; ) { + let i = e.decode(t.value); + (l = s.length), (s += i); + let o = i.indexOf(n); + for (~o ? (l += o) : (l = s.indexOf(n)), c = []; ~l; ) { + let e = s.slice(0, l), + t = s.slice(l + f); + if (r) { + let n = e.indexOf("\r\n\r\n") + 4, + i = e.lastIndexOf("\r\n", n), + l = !1, + r = e.slice(n, i > -1 ? void 0 : i), + o = String(e.slice(0, n)).trim().split("\r\n"), + f = {}, + s = o.length; + for ( + ; + (d = o[--s]); + d = d.split(": "), + f[d.shift().toLowerCase()] = d.join(": ") + ); + if ( + ((d = f["content-type"]), + d && ~d.indexOf("application/json")) + ) + try { + (r = JSON.parse(r)), (l = !0); + } catch (e) {} + if ( + ((d = { + headers: f, + body: r, + json: l, + }), + a ? yield d : c.push(d), + "--" === t.slice(0, 2)) + ) + break e; + } else (n = "\r\n" + n), (r = f += 2); + (s = t), (l = s.indexOf(n)); + } + c.length && (yield c); + } + } finally { + c.length && (yield c), await o.cancel(); + } + })(t.body, `--${r}`, n); + } + exports.meros = t; + /***/ + }, -var isArray = __webpack_require__(/*! isarray */ "../../../node_modules/isarray/index.js"); -module.exports = function isObject(val) { - return val != null && typeof val === 'object' && isArray(val) === false; -}; + /***/ "../../../node_modules/nullthrows/nullthrows.js": + /*!******************************************************!*\ + !*** ../../../node_modules/nullthrows/nullthrows.js ***! + \******************************************************/ + /***/ function (module) { + function nullthrows(x, message) { + if (x != null) { + return x; + } + var error = new Error( + message !== undefined ? message : "Got unexpected " + x + ); + error.framesToPop = 1; // Skip nullthrows's own stack frame. + throw error; + } + module.exports = nullthrows; + module.exports["default"] = nullthrows; + Object.defineProperty(module.exports, "__esModule", { + value: true, + }); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/meros/browser/index.js": -/*!****************************************************!*\ - !*** ../../../node_modules/meros/browser/index.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ "../../../node_modules/popmotion/dist/popmotion.cjs.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/popmotion/dist/popmotion.cjs.js ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + var tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var heyListen = __webpack_require__( + /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" + ); + var styleValueTypes = __webpack_require__( + /*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js" + ); + var sync = __webpack_require__( + /*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js" + ); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e + ? e + : { + default: e, + }; + } + var sync__default = /*#__PURE__*/ _interopDefaultLegacy(sync); + const clamp = (min, max, v) => Math.min(Math.max(v, min), max); + const safeMin = 0.001; + const minDuration = 0.01; + const maxDuration = 10.0; + const minDamping = 0.05; + const maxDamping = 1; + function findSpring({ + duration = 800, + bounce = 0.25, + velocity = 0, + mass = 1, + }) { + let envelope; + let derivative; + heyListen.warning( + duration <= maxDuration * 1000, + "Spring duration must be 10 seconds or less" + ); + let dampingRatio = 1 - bounce; + dampingRatio = clamp(minDamping, maxDamping, dampingRatio); + duration = clamp(minDuration, maxDuration, duration / 1000); + if (dampingRatio < 1) { + envelope = (undampedFreq) => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const a = exponentialDecay - velocity; + const b = calcAngularFreq(undampedFreq, dampingRatio); + const c = Math.exp(-delta); + return safeMin - (a / b) * c; + }; + derivative = (undampedFreq) => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const d = delta * velocity + velocity; + const e = + Math.pow(dampingRatio, 2) * + Math.pow(undampedFreq, 2) * + duration; + const f = Math.exp(-delta); + const g = calcAngularFreq( + Math.pow(undampedFreq, 2), + dampingRatio + ); + const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1; + return (factor * ((d - e) * f)) / g; + }; + } else { + envelope = (undampedFreq) => { + const a = Math.exp(-undampedFreq * duration); + const b = (undampedFreq - velocity) * duration + 1; + return -safeMin + a * b; + }; + derivative = (undampedFreq) => { + const a = Math.exp(-undampedFreq * duration); + const b = (velocity - undampedFreq) * (duration * duration); + return a * b; + }; + } + const initialGuess = 5 / duration; + const undampedFreq = approximateRoot( + envelope, + derivative, + initialGuess + ); + duration = duration * 1000; + if (isNaN(undampedFreq)) { + return { + stiffness: 100, + damping: 10, + duration, + }; + } else { + const stiffness = Math.pow(undampedFreq, 2) * mass; + return { + stiffness, + damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), + duration, + }; + } + } + const rootIterations = 12; + function approximateRoot(envelope, derivative, initialGuess) { + let result = initialGuess; + for (let i = 1; i < rootIterations; i++) { + result = result - envelope(result) / derivative(result); + } + return result; + } + function calcAngularFreq(undampedFreq, dampingRatio) { + return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); + } + const durationKeys = ["duration", "bounce"]; + const physicsKeys = ["stiffness", "damping", "mass"]; + function isSpringType(options, keys) { + return keys.some((key) => options[key] !== undefined); + } + function getSpringOptions(options) { + let springOptions = Object.assign( + { + velocity: 0.0, + stiffness: 100, + damping: 10, + mass: 1.0, + isResolvedFromDuration: false, + }, + options + ); + if ( + !isSpringType(options, physicsKeys) && + isSpringType(options, durationKeys) + ) { + const derived = findSpring(options); + springOptions = Object.assign( + Object.assign(Object.assign({}, springOptions), derived), + { + velocity: 0.0, + mass: 1.0, + } + ); + springOptions.isResolvedFromDuration = true; + } + return springOptions; + } + function spring(_a) { + var { from = 0.0, to = 1.0, restSpeed = 2, restDelta } = _a, + options = tslib.__rest(_a, [ + "from", + "to", + "restSpeed", + "restDelta", + ]); + const state = { + done: false, + value: from, + }; + let { + stiffness, + damping, + mass, + velocity, + duration, + isResolvedFromDuration, + } = getSpringOptions(options); + let resolveSpring = zero; + let resolveVelocity = zero; + function createSpring() { + const initialVelocity = velocity ? -(velocity / 1000) : 0.0; + const initialDelta = to - from; + const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); + const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; + if (restDelta === undefined) { + restDelta = Math.min(Math.abs(to - from) / 100, 0.4); + } + if (dampingRatio < 1) { + const angularFreq = calcAngularFreq( + undampedAngularFreq, + dampingRatio + ); + resolveSpring = (t) => { + const envelope = Math.exp( + -dampingRatio * undampedAngularFreq * t + ); + return ( + to - + envelope * + (((initialVelocity + + dampingRatio * undampedAngularFreq * initialDelta) / + angularFreq) * + Math.sin(angularFreq * t) + + initialDelta * Math.cos(angularFreq * t)) + ); + }; + resolveVelocity = (t) => { + const envelope = Math.exp( + -dampingRatio * undampedAngularFreq * t + ); + return ( + dampingRatio * + undampedAngularFreq * + envelope * + ((Math.sin(angularFreq * t) * + (initialVelocity + + dampingRatio * undampedAngularFreq * initialDelta)) / + angularFreq + + initialDelta * Math.cos(angularFreq * t)) - + envelope * + (Math.cos(angularFreq * t) * + (initialVelocity + + dampingRatio * undampedAngularFreq * initialDelta) - + angularFreq * initialDelta * Math.sin(angularFreq * t)) + ); + }; + } else if (dampingRatio === 1) { + resolveSpring = (t) => + to - + Math.exp(-undampedAngularFreq * t) * + (initialDelta + + (initialVelocity + undampedAngularFreq * initialDelta) * t); + } else { + const dampedAngularFreq = + undampedAngularFreq * + Math.sqrt(dampingRatio * dampingRatio - 1); + resolveSpring = (t) => { + const envelope = Math.exp( + -dampingRatio * undampedAngularFreq * t + ); + const freqForT = Math.min(dampedAngularFreq * t, 300); + return ( + to - + (envelope * + ((initialVelocity + + dampingRatio * undampedAngularFreq * initialDelta) * + Math.sinh(freqForT) + + dampedAngularFreq * initialDelta * Math.cosh(freqForT))) / + dampedAngularFreq + ); + }; + } + } + createSpring(); + return { + next: (t) => { + const current = resolveSpring(t); + if (!isResolvedFromDuration) { + const currentVelocity = resolveVelocity(t) * 1000; + const isBelowVelocityThreshold = + Math.abs(currentVelocity) <= restSpeed; + const isBelowDisplacementThreshold = + Math.abs(to - current) <= restDelta; + state.done = + isBelowVelocityThreshold && isBelowDisplacementThreshold; + } else { + state.done = t >= duration; + } + state.value = state.done ? to : current; + return state; + }, + flipTarget: () => { + velocity = -velocity; + [from, to] = [to, from]; + createSpring(); + }, + }; + } + spring.needsInterpolation = (a, b) => + typeof a === "string" || typeof b === "string"; + const zero = (_t) => 0; + const progress = (from, to, value) => { + const toFromDifference = to - from; + return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; + }; + const mix = (from, to, progress) => + -progress * from + progress * to + from; + function hueToRgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + function hslaToRgba({ hue, saturation, lightness, alpha }) { + hue /= 360; + saturation /= 100; + lightness /= 100; + let red = 0; + let green = 0; + let blue = 0; + if (!saturation) { + red = green = blue = lightness; + } else { + const q = + lightness < 0.5 + ? lightness * (1 + saturation) + : lightness + saturation - lightness * saturation; + const p = 2 * lightness - q; + red = hueToRgb(p, q, hue + 1 / 3); + green = hueToRgb(p, q, hue); + blue = hueToRgb(p, q, hue - 1 / 3); + } + return { + red: Math.round(red * 255), + green: Math.round(green * 255), + blue: Math.round(blue * 255), + alpha, + }; + } + const mixLinearColor = (from, to, v) => { + const fromExpo = from * from; + const toExpo = to * to; + return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo)); + }; + const colorTypes = [ + styleValueTypes.hex, + styleValueTypes.rgba, + styleValueTypes.hsla, + ]; + const getColorType = (v) => colorTypes.find((type) => type.test(v)); + const notAnimatable = (color) => + `'${color}' is not an animatable color. Use the equivalent color code instead.`; + const mixColor = (from, to) => { + let fromColorType = getColorType(from); + let toColorType = getColorType(to); + heyListen.invariant(!!fromColorType, notAnimatable(from)); + heyListen.invariant(!!toColorType, notAnimatable(to)); + let fromColor = fromColorType.parse(from); + let toColor = toColorType.parse(to); + if (fromColorType === styleValueTypes.hsla) { + fromColor = hslaToRgba(fromColor); + fromColorType = styleValueTypes.rgba; + } + if (toColorType === styleValueTypes.hsla) { + toColor = hslaToRgba(toColor); + toColorType = styleValueTypes.rgba; + } + const blended = Object.assign({}, fromColor); + return (v) => { + for (const key in blended) { + if (key !== "alpha") { + blended[key] = mixLinearColor(fromColor[key], toColor[key], v); + } + } + blended.alpha = mix(fromColor.alpha, toColor.alpha, v); + return fromColorType.transform(blended); + }; + }; + const zeroPoint = { + x: 0, + y: 0, + z: 0, + }; + const isNum = (v) => typeof v === "number"; + const combineFunctions = (a, b) => (v) => b(a(v)); + const pipe = (...transformers) => transformers.reduce(combineFunctions); + function getMixer(origin, target) { + if (isNum(origin)) { + return (v) => mix(origin, target, v); + } else if (styleValueTypes.color.test(origin)) { + return mixColor(origin, target); + } else { + return mixComplex(origin, target); + } + } + const mixArray = (from, to) => { + const output = [...from]; + const numValues = output.length; + const blendValue = from.map((fromThis, i) => + getMixer(fromThis, to[i]) + ); + return (v) => { + for (let i = 0; i < numValues; i++) { + output[i] = blendValue[i](v); + } + return output; + }; + }; + const mixObject = (origin, target) => { + const output = Object.assign(Object.assign({}, origin), target); + const blendValue = {}; + for (const key in output) { + if (origin[key] !== undefined && target[key] !== undefined) { + blendValue[key] = getMixer(origin[key], target[key]); + } + } + return (v) => { + for (const key in blendValue) { + output[key] = blendValue[key](v); + } + return output; + }; + }; + function analyse(value) { + const parsed = styleValueTypes.complex.parse(value); + const numValues = parsed.length; + let numNumbers = 0; + let numRGB = 0; + let numHSL = 0; + for (let i = 0; i < numValues; i++) { + if (numNumbers || typeof parsed[i] === "number") { + numNumbers++; + } else { + if (parsed[i].hue !== undefined) { + numHSL++; + } else { + numRGB++; + } + } + } + return { + parsed, + numNumbers, + numRGB, + numHSL, + }; + } + const mixComplex = (origin, target) => { + const template = styleValueTypes.complex.createTransformer(target); + const originStats = analyse(origin); + const targetStats = analyse(target); + const canInterpolate = + originStats.numHSL === targetStats.numHSL && + originStats.numRGB === targetStats.numRGB && + originStats.numNumbers >= targetStats.numNumbers; + if (canInterpolate) { + return pipe( + mixArray(originStats.parsed, targetStats.parsed), + template + ); + } else { + heyListen.warning( + true, + `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.` + ); + return (p) => `${p > 0 ? target : origin}`; + } + }; + const mixNumber = (from, to) => (p) => mix(from, to, p); + function detectMixerFactory(v) { + if (typeof v === "number") { + return mixNumber; + } else if (typeof v === "string") { + if (styleValueTypes.color.test(v)) { + return mixColor; + } else { + return mixComplex; + } + } else if (Array.isArray(v)) { + return mixArray; + } else if (typeof v === "object") { + return mixObject; + } + } + function createMixers(output, ease, customMixer) { + const mixers = []; + const mixerFactory = customMixer || detectMixerFactory(output[0]); + const numMixers = output.length - 1; + for (let i = 0; i < numMixers; i++) { + let mixer = mixerFactory(output[i], output[i + 1]); + if (ease) { + const easingFunction = Array.isArray(ease) ? ease[i] : ease; + mixer = pipe(easingFunction, mixer); + } + mixers.push(mixer); + } + return mixers; + } + function fastInterpolate([from, to], [mixer]) { + return (v) => mixer(progress(from, to, v)); + } + function slowInterpolate(input, mixers) { + const inputLength = input.length; + const lastInputIndex = inputLength - 1; + return (v) => { + let mixerIndex = 0; + let foundMixerIndex = false; + if (v <= input[0]) { + foundMixerIndex = true; + } else if (v >= input[lastInputIndex]) { + mixerIndex = lastInputIndex - 1; + foundMixerIndex = true; + } + if (!foundMixerIndex) { + let i = 1; + for (; i < inputLength; i++) { + if (input[i] > v || i === lastInputIndex) { + break; + } + } + mixerIndex = i - 1; + } + const progressInRange = progress( + input[mixerIndex], + input[mixerIndex + 1], + v + ); + return mixers[mixerIndex](progressInRange); + }; + } + function interpolate( + input, + output, + { clamp: isClamp = true, ease, mixer } = {} + ) { + const inputLength = input.length; + heyListen.invariant( + inputLength === output.length, + "Both input and output ranges must be the same length" + ); + heyListen.invariant( + !ease || !Array.isArray(ease) || ease.length === inputLength - 1, + "Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values." + ); + if (input[0] > input[inputLength - 1]) { + input = [].concat(input); + output = [].concat(output); + input.reverse(); + output.reverse(); + } + const mixers = createMixers(output, ease, mixer); + const interpolator = + inputLength === 2 + ? fastInterpolate(input, mixers) + : slowInterpolate(input, mixers); + return isClamp + ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v)) + : interpolator; + } + const reverseEasing = (easing) => (p) => 1 - easing(1 - p); + const mirrorEasing = (easing) => (p) => + p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; + const createExpoIn = (power) => (p) => Math.pow(p, power); + const createBackIn = (power) => (p) => + p * p * ((power + 1) * p - power); + const createAnticipate = (power) => { + const backEasing = createBackIn(power); + return (p) => + (p *= 2) < 1 + ? 0.5 * backEasing(p) + : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); + }; + const DEFAULT_OVERSHOOT_STRENGTH = 1.525; + const BOUNCE_FIRST_THRESHOLD = 4.0 / 11.0; + const BOUNCE_SECOND_THRESHOLD = 8.0 / 11.0; + const BOUNCE_THIRD_THRESHOLD = 9.0 / 10.0; + const linear = (p) => p; + const easeIn = createExpoIn(2); + const easeOut = reverseEasing(easeIn); + const easeInOut = mirrorEasing(easeIn); + const circIn = (p) => 1 - Math.sin(Math.acos(p)); + const circOut = reverseEasing(circIn); + const circInOut = mirrorEasing(circOut); + const backIn = createBackIn(DEFAULT_OVERSHOOT_STRENGTH); + const backOut = reverseEasing(backIn); + const backInOut = mirrorEasing(backIn); + const anticipate = createAnticipate(DEFAULT_OVERSHOOT_STRENGTH); + const ca = 4356.0 / 361.0; + const cb = 35442.0 / 1805.0; + const cc = 16061.0 / 1805.0; + const bounceOut = (p) => { + if (p === 1 || p === 0) return p; + const p2 = p * p; + return p < BOUNCE_FIRST_THRESHOLD + ? 7.5625 * p2 + : p < BOUNCE_SECOND_THRESHOLD + ? 9.075 * p2 - 9.9 * p + 3.4 + : p < BOUNCE_THIRD_THRESHOLD + ? ca * p2 - cb * p + cc + : 10.8 * p * p - 20.52 * p + 10.72; + }; + const bounceIn = reverseEasing(bounceOut); + const bounceInOut = (p) => + p < 0.5 + ? 0.5 * (1.0 - bounceOut(1.0 - p * 2.0)) + : 0.5 * bounceOut(p * 2.0 - 1.0) + 0.5; + function defaultEasing(values, easing) { + return values + .map(() => easing || easeInOut) + .splice(0, values.length - 1); + } + function defaultOffset(values) { + const numValues = values.length; + return values.map((_value, i) => (i !== 0 ? i / (numValues - 1) : 0)); + } + function convertOffsetToTimes(offset, duration) { + return offset.map((o) => o * duration); + } + function keyframes({ from = 0, to = 1, ease, offset, duration = 300 }) { + const state = { + done: false, + value: from, + }; + const values = Array.isArray(to) ? to : [from, to]; + const times = convertOffsetToTimes( + offset && offset.length === values.length + ? offset + : defaultOffset(values), + duration + ); + function createInterpolator() { + return interpolate(times, values, { + ease: Array.isArray(ease) ? ease : defaultEasing(values, ease), + }); + } + let interpolator = createInterpolator(); + return { + next: (t) => { + state.value = interpolator(t); + state.done = t >= duration; + return state; + }, + flipTarget: () => { + values.reverse(); + interpolator = createInterpolator(); + }, + }; + } + function decay({ + velocity = 0, + from = 0, + power = 0.8, + timeConstant = 350, + restDelta = 0.5, + modifyTarget, + }) { + const state = { + done: false, + value: from, + }; + let amplitude = power * velocity; + const ideal = from + amplitude; + const target = + modifyTarget === undefined ? ideal : modifyTarget(ideal); + if (target !== ideal) amplitude = target - from; + return { + next: (t) => { + const delta = -amplitude * Math.exp(-t / timeConstant); + state.done = !(delta > restDelta || delta < -restDelta); + state.value = state.done ? target : target + delta; + return state; + }, + flipTarget: () => {}, + }; + } + const types = { + keyframes, + spring, + decay, + }; + function detectAnimationFromOptions(config) { + if (Array.isArray(config.to)) { + return keyframes; + } else if (types[config.type]) { + return types[config.type]; + } + const keys = new Set(Object.keys(config)); + if ( + keys.has("ease") || + (keys.has("duration") && !keys.has("dampingRatio")) + ) { + return keyframes; + } else if ( + keys.has("dampingRatio") || + keys.has("stiffness") || + keys.has("mass") || + keys.has("damping") || + keys.has("restSpeed") || + keys.has("restDelta") + ) { + return spring; + } + return keyframes; + } + function loopElapsed(elapsed, duration, delay = 0) { + return elapsed - duration - delay; + } + function reverseElapsed( + elapsed, + duration, + delay = 0, + isForwardPlayback = true + ) { + return isForwardPlayback + ? loopElapsed(duration + -elapsed, duration, delay) + : duration - (elapsed - duration) + delay; + } + function hasRepeatDelayElapsed( + elapsed, + duration, + delay, + isForwardPlayback + ) { + return isForwardPlayback + ? elapsed >= duration + delay + : elapsed <= -delay; + } + const framesync = (update) => { + const passTimestamp = ({ delta }) => update(delta); + return { + start: () => sync__default["default"].update(passTimestamp, true), + stop: () => sync.cancelSync.update(passTimestamp), + }; + }; + function animate(_a) { + var _b, _c; + var { + from, + autoplay = true, + driver = framesync, + elapsed = 0, + repeat: repeatMax = 0, + repeatType = "loop", + repeatDelay = 0, + onPlay, + onStop, + onComplete, + onRepeat, + onUpdate, + } = _a, + options = tslib.__rest(_a, [ + "from", + "autoplay", + "driver", + "elapsed", + "repeat", + "repeatType", + "repeatDelay", + "onPlay", + "onStop", + "onComplete", + "onRepeat", + "onUpdate", + ]); + let { to } = options; + let driverControls; + let repeatCount = 0; + let computedDuration = options.duration; + let latest; + let isComplete = false; + let isForwardPlayback = true; + let interpolateFromNumber; + const animator = detectAnimationFromOptions(options); + if ( + (_c = (_b = animator).needsInterpolation) === null || _c === void 0 + ? void 0 + : _c.call(_b, from, to) + ) { + interpolateFromNumber = interpolate([0, 100], [from, to], { + clamp: false, + }); + from = 0; + to = 100; + } + const animation = animator( + Object.assign(Object.assign({}, options), { + from, + to, + }) + ); + function repeat() { + repeatCount++; + if (repeatType === "reverse") { + isForwardPlayback = repeatCount % 2 === 0; + elapsed = reverseElapsed( + elapsed, + computedDuration, + repeatDelay, + isForwardPlayback + ); + } else { + elapsed = loopElapsed(elapsed, computedDuration, repeatDelay); + if (repeatType === "mirror") animation.flipTarget(); + } + isComplete = false; + onRepeat && onRepeat(); + } + function complete() { + driverControls.stop(); + onComplete && onComplete(); + } + function update(delta) { + if (!isForwardPlayback) delta = -delta; + elapsed += delta; + if (!isComplete) { + const state = animation.next(Math.max(0, elapsed)); + latest = state.value; + if (interpolateFromNumber) latest = interpolateFromNumber(latest); + isComplete = isForwardPlayback ? state.done : elapsed <= 0; + } + onUpdate === null || onUpdate === void 0 + ? void 0 + : onUpdate(latest); + if (isComplete) { + if (repeatCount === 0) + computedDuration !== null && computedDuration !== void 0 + ? computedDuration + : (computedDuration = elapsed); + if (repeatCount < repeatMax) { + hasRepeatDelayElapsed( + elapsed, + computedDuration, + repeatDelay, + isForwardPlayback + ) && repeat(); + } else { + complete(); + } + } + } + function play() { + onPlay === null || onPlay === void 0 ? void 0 : onPlay(); + driverControls = driver(update); + driverControls.start(); + } + autoplay && play(); + return { + stop: () => { + onStop === null || onStop === void 0 ? void 0 : onStop(); + driverControls.stop(); + }, + }; + } + function velocityPerSecond(velocity, frameDuration) { + return frameDuration ? velocity * (1000 / frameDuration) : 0; + } + function inertia({ + from = 0, + velocity = 0, + min, + max, + power = 0.8, + timeConstant = 750, + bounceStiffness = 500, + bounceDamping = 10, + restDelta = 1, + modifyTarget, + driver, + onUpdate, + onComplete, + onStop, + }) { + let currentAnimation; + function isOutOfBounds(v) { + return ( + (min !== undefined && v < min) || (max !== undefined && v > max) + ); + } + function boundaryNearest(v) { + if (min === undefined) return max; + if (max === undefined) return min; + return Math.abs(min - v) < Math.abs(max - v) ? min : max; + } + function startAnimation(options) { + currentAnimation === null || currentAnimation === void 0 + ? void 0 + : currentAnimation.stop(); + currentAnimation = animate( + Object.assign(Object.assign({}, options), { + driver, + onUpdate: (v) => { + var _a; + onUpdate === null || onUpdate === void 0 + ? void 0 + : onUpdate(v); + (_a = options.onUpdate) === null || _a === void 0 + ? void 0 + : _a.call(options, v); + }, + onComplete, + onStop, + }) + ); + } + function startSpring(options) { + startAnimation( + Object.assign( + { + type: "spring", + stiffness: bounceStiffness, + damping: bounceDamping, + restDelta, + }, + options + ) + ); + } + if (isOutOfBounds(from)) { + startSpring({ + from, + velocity, + to: boundaryNearest(from), + }); + } else { + let target = power * velocity + from; + if (typeof modifyTarget !== "undefined") + target = modifyTarget(target); + const boundary = boundaryNearest(target); + const heading = boundary === min ? -1 : 1; + let prev; + let current; + const checkBoundary = (v) => { + prev = current; + current = v; + velocity = velocityPerSecond(v - prev, sync.getFrameData().delta); + if ( + (heading === 1 && v > boundary) || + (heading === -1 && v < boundary) + ) { + startSpring({ + from: v, + to: boundary, + velocity, + }); + } + }; + startAnimation({ + type: "decay", + from, + velocity, + timeConstant, + power, + restDelta, + modifyTarget, + onUpdate: isOutOfBounds(target) ? checkBoundary : undefined, + }); + } + return { + stop: () => + currentAnimation === null || currentAnimation === void 0 + ? void 0 + : currentAnimation.stop(), + }; + } + const radiansToDegrees = (radians) => (radians * 180) / Math.PI; + const angle = (a, b = zeroPoint) => + radiansToDegrees(Math.atan2(b.y - a.y, b.x - a.x)); + const applyOffset = (from, to) => { + let hasReceivedFrom = true; + if (to === undefined) { + to = from; + hasReceivedFrom = false; + } + return (v) => { + if (hasReceivedFrom) { + return v - from + to; + } else { + from = v; + hasReceivedFrom = true; + return to; + } + }; + }; + const identity = (v) => v; + const createAttractor = + (alterDisplacement = identity) => + (constant, origin, v) => { + const displacement = origin - v; + const springModifiedDisplacement = + -(0 - constant + 1) * + (0 - alterDisplacement(Math.abs(displacement))); + return displacement <= 0 + ? origin + springModifiedDisplacement + : origin - springModifiedDisplacement; + }; + const attract = createAttractor(); + const attractExpo = createAttractor(Math.sqrt); + const degreesToRadians = (degrees) => (degrees * Math.PI) / 180; + const isPoint = (point) => + point.hasOwnProperty("x") && point.hasOwnProperty("y"); + const isPoint3D = (point) => + isPoint(point) && point.hasOwnProperty("z"); + const distance1D = (a, b) => Math.abs(a - b); + function distance(a, b) { + if (isNum(a) && isNum(b)) { + return distance1D(a, b); + } else if (isPoint(a) && isPoint(b)) { + const xDelta = distance1D(a.x, b.x); + const yDelta = distance1D(a.y, b.y); + const zDelta = + isPoint3D(a) && isPoint3D(b) ? distance1D(a.z, b.z) : 0; + return Math.sqrt( + Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2) + ); + } + } + const pointFromVector = (origin, angle, distance) => { + angle = degreesToRadians(angle); + return { + x: distance * Math.cos(angle) + origin.x, + y: distance * Math.sin(angle) + origin.y, + }; + }; + const toDecimal = (num, precision = 2) => { + precision = Math.pow(10, precision); + return Math.round(num * precision) / precision; + }; + const smoothFrame = (prevValue, nextValue, duration, smoothing = 0) => + toDecimal( + prevValue + + (duration * (nextValue - prevValue)) / + Math.max(smoothing, duration) + ); + const smooth = (strength = 50) => { + let previousValue = 0; + let lastUpdated = 0; + return (v) => { + const currentFramestamp = sync.getFrameData().timestamp; + const timeDelta = + currentFramestamp !== lastUpdated + ? currentFramestamp - lastUpdated + : 0; + const newValue = timeDelta + ? smoothFrame(previousValue, v, timeDelta, strength) + : previousValue; + lastUpdated = currentFramestamp; + previousValue = newValue; + return newValue; + }; + }; + const snap = (points) => { + if (typeof points === "number") { + return (v) => Math.round(v / points) * points; + } else { + let i = 0; + const numPoints = points.length; + return (v) => { + let lastDistance = Math.abs(points[0] - v); + for (i = 1; i < numPoints; i++) { + const point = points[i]; + const distance = Math.abs(point - v); + if (distance === 0) return point; + if (distance > lastDistance) return points[i - 1]; + if (i === numPoints - 1) return point; + lastDistance = distance; + } + }; + } + }; + function velocityPerFrame(xps, frameDuration) { + return xps / (1000 / frameDuration); + } + const wrap = (min, max, v) => { + const rangeSize = max - min; + return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min; + }; + const a = (a1, a2) => 1.0 - 3.0 * a2 + 3.0 * a1; + const b = (a1, a2) => 3.0 * a2 - 6.0 * a1; + const c = (a1) => 3.0 * a1; + const calcBezier = (t, a1, a2) => + ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; + const getSlope = (t, a1, a2) => + 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1); + const subdivisionPrecision = 0.0000001; + const subdivisionMaxIterations = 10; + function binarySubdivide(aX, aA, aB, mX1, mX2) { + let currentX; + let currentT; + let i = 0; + do { + currentT = aA + (aB - aA) / 2.0; + currentX = calcBezier(currentT, mX1, mX2) - aX; + if (currentX > 0.0) { + aB = currentT; + } else { + aA = currentT; + } + } while ( + Math.abs(currentX) > subdivisionPrecision && + ++i < subdivisionMaxIterations + ); + return currentT; + } + const newtonIterations = 8; + const newtonMinSlope = 0.001; + function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { + for (let i = 0; i < newtonIterations; ++i) { + const currentSlope = getSlope(aGuessT, mX1, mX2); + if (currentSlope === 0.0) { + return aGuessT; + } + const currentX = calcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; + } + return aGuessT; + } + const kSplineTableSize = 11; + const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); + function cubicBezier(mX1, mY1, mX2, mY2) { + if (mX1 === mY1 && mX2 === mY2) return linear; + const sampleValues = new Float32Array(kSplineTableSize); + for (let i = 0; i < kSplineTableSize; ++i) { + sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); + } + function getTForX(aX) { + let intervalStart = 0.0; + let currentSample = 1; + const lastSample = kSplineTableSize - 1; + for ( + ; + currentSample !== lastSample && sampleValues[currentSample] <= aX; + ++currentSample + ) { + intervalStart += kSampleStepSize; + } + --currentSample; + const dist = + (aX - sampleValues[currentSample]) / + (sampleValues[currentSample + 1] - sampleValues[currentSample]); + const guessForT = intervalStart + dist * kSampleStepSize; + const initialSlope = getSlope(guessForT, mX1, mX2); + if (initialSlope >= newtonMinSlope) { + return newtonRaphsonIterate(aX, guessForT, mX1, mX2); + } else if (initialSlope === 0.0) { + return guessForT; + } else { + return binarySubdivide( + aX, + intervalStart, + intervalStart + kSampleStepSize, + mX1, + mX2 + ); + } + } + return (t) => + t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); + } + const steps = + (steps, direction = "end") => + (progress) => { + progress = + direction === "end" + ? Math.min(progress, 0.999) + : Math.max(progress, 0.001); + const expanded = progress * steps; + const rounded = + direction === "end" ? Math.floor(expanded) : Math.ceil(expanded); + return clamp(0, 1, rounded / steps); + }; + exports.angle = angle; + exports.animate = animate; + exports.anticipate = anticipate; + exports.applyOffset = applyOffset; + exports.attract = attract; + exports.attractExpo = attractExpo; + exports.backIn = backIn; + exports.backInOut = backInOut; + exports.backOut = backOut; + exports.bounceIn = bounceIn; + exports.bounceInOut = bounceInOut; + exports.bounceOut = bounceOut; + exports.circIn = circIn; + exports.circInOut = circInOut; + exports.circOut = circOut; + exports.clamp = clamp; + exports.createAnticipate = createAnticipate; + exports.createAttractor = createAttractor; + exports.createBackIn = createBackIn; + exports.createExpoIn = createExpoIn; + exports.cubicBezier = cubicBezier; + exports.decay = decay; + exports.degreesToRadians = degreesToRadians; + exports.distance = distance; + exports.easeIn = easeIn; + exports.easeInOut = easeInOut; + exports.easeOut = easeOut; + exports.inertia = inertia; + exports.interpolate = interpolate; + exports.isPoint = isPoint; + exports.isPoint3D = isPoint3D; + exports.keyframes = keyframes; + exports.linear = linear; + exports.mirrorEasing = mirrorEasing; + exports.mix = mix; + exports.mixColor = mixColor; + exports.mixComplex = mixComplex; + exports.pipe = pipe; + exports.pointFromVector = pointFromVector; + exports.progress = progress; + exports.radiansToDegrees = radiansToDegrees; + exports.reverseEasing = reverseEasing; + exports.smooth = smooth; + exports.smoothFrame = smoothFrame; + exports.snap = snap; + exports.spring = spring; + exports.steps = steps; + exports.toDecimal = toDecimal; + exports.velocityPerFrame = velocityPerFrame; + exports.velocityPerSecond = velocityPerSecond; + exports.wrap = wrap; + + /***/ + }, + /***/ "../../../node_modules/punycode.js/punycode.es6.js": + /*!*********************************************************!*\ + !*** ../../../node_modules/punycode.js/punycode.es6.js ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports) { + /** Highest positive signed 32-bit float value */ + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.toUnicode = + exports.toASCII = + exports.encode = + exports["default"] = + exports.decode = + void 0; + exports.ucs2decode = ucs2decode; + exports.ucs2encode = void 0; + const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + const base = 36; + const tMin = 1; + const tMax = 26; + const skew = 38; + const damp = 700; + const initialBias = 72; + const initialN = 128; // 0x80 + const delimiter = "-"; // '\x2D' + + /** Regular expressions */ + const regexPunycode = /^xn--/; + const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. + const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + const errors = { + overflow: "Overflow: input needs wider integers to process", + "not-basic": "Illegal input >= 0x80 (not a basic code point)", + "invalid-input": "Invalid input", + }; + /** Convenience shortcuts */ + const baseMinusTMin = base - tMin; + const floor = Math.floor; + const stringFromCharCode = String.fromCharCode; -var e = new TextDecoder(); -async function t(t, n) { - if (!t.ok || !t.body || t.bodyUsed) return t; - let i = t.headers.get("content-type"); - if (!i || !~i.indexOf("multipart/")) return t; - let l = i.indexOf("boundary="), - r = "-"; - if (~l) { - let e = l + 9, - t = i.indexOf(";", e); - r = i.slice(e, t > -1 ? t : void 0).trim().replace(/"/g, ""); - } - return async function* (t, n, i) { - let l, - r, - d, - o = t.getReader(), - a = !i || !i.multiple, - f = n.length, - s = "", - c = []; - try { - let t; - e: for (; !(t = await o.read()).done;) { - let i = e.decode(t.value); - l = s.length, s += i; - let o = i.indexOf(n); - for (~o ? l += o : l = s.indexOf(n), c = []; ~l;) { - let e = s.slice(0, l), - t = s.slice(l + f); - if (r) { - let n = e.indexOf("\r\n\r\n") + 4, - i = e.lastIndexOf("\r\n", n), - l = !1, - r = e.slice(n, i > -1 ? void 0 : i), - o = String(e.slice(0, n)).trim().split("\r\n"), - f = {}, - s = o.length; - for (; d = o[--s]; d = d.split(": "), f[d.shift().toLowerCase()] = d.join(": ")); - if (d = f["content-type"], d && ~d.indexOf("application/json")) try { - r = JSON.parse(r), l = !0; - } catch (e) {} - if (d = { - headers: f, - body: r, - json: l - }, a ? yield d : c.push(d), "--" === t.slice(0, 2)) break e; - } else n = "\r\n" + n, r = f += 2; - s = t, l = s.indexOf(n); - } - c.length && (yield c); - } - } finally { - c.length && (yield c), await o.cancel(); - } - }(t.body, `--${r}`, n); -} -exports.meros = t; + /*--------------------------------------------------------------------------*/ -/***/ }), + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } -/***/ "../../../node_modules/nullthrows/nullthrows.js": -/*!******************************************************!*\ - !*** ../../../node_modules/nullthrows/nullthrows.js ***! - \******************************************************/ -/***/ (function(module) { + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; + } + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ + function mapDomain(domain, callback) { + const parts = domain.split("@"); + let result = ""; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + "@"; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, "\x2E"); + const labels = domain.split("."); + const encoded = map(labels, callback).join("."); + return result + encoded; + } + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xd800 && value <= 0xdbff && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xfc00) == 0xdc00) { + // Low surrogate. + output.push( + ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000 + ); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } -function nullthrows(x, message) { - if (x != null) { - return x; - } - var error = new Error(message !== undefined ? message : 'Got unexpected ' + x); - error.framesToPop = 1; // Skip nullthrows's own stack frame. - throw error; -} -module.exports = nullthrows; -module.exports["default"] = nullthrows; -Object.defineProperty(module.exports, "__esModule", ({ - value: true -})); - -/***/ }), - -/***/ "../../../node_modules/popmotion/dist/popmotion.cjs.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/popmotion/dist/popmotion.cjs.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + const ucs2encode = (codePoints) => String.fromCodePoint(...codePoints); + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + exports.ucs2encode = ucs2encode; + const basicToDigit = function (codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3a) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5b) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7b) { + return codePoint - 0x61; + } + return base; + }; + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + const digitToBasic = function (digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + }; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); -var styleValueTypes = __webpack_require__(/*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js"); -var sync = __webpack_require__(/*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js"); -function _interopDefaultLegacy(e) { - return e && typeof e === 'object' && 'default' in e ? e : { - 'default': e - }; -} -var sync__default = /*#__PURE__*/_interopDefaultLegacy(sync); -const clamp = (min, max, v) => Math.min(Math.max(v, min), max); -const safeMin = 0.001; -const minDuration = 0.01; -const maxDuration = 10.0; -const minDamping = 0.05; -const maxDamping = 1; -function findSpring({ - duration = 800, - bounce = 0.25, - velocity = 0, - mass = 1 -}) { - let envelope; - let derivative; - heyListen.warning(duration <= maxDuration * 1000, "Spring duration must be 10 seconds or less"); - let dampingRatio = 1 - bounce; - dampingRatio = clamp(minDamping, maxDamping, dampingRatio); - duration = clamp(minDuration, maxDuration, duration / 1000); - if (dampingRatio < 1) { - envelope = undampedFreq => { - const exponentialDecay = undampedFreq * dampingRatio; - const delta = exponentialDecay * duration; - const a = exponentialDecay - velocity; - const b = calcAngularFreq(undampedFreq, dampingRatio); - const c = Math.exp(-delta); - return safeMin - a / b * c; - }; - derivative = undampedFreq => { - const exponentialDecay = undampedFreq * dampingRatio; - const delta = exponentialDecay * duration; - const d = delta * velocity + velocity; - const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration; - const f = Math.exp(-delta); - const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio); - const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1; - return factor * ((d - e) * f) / g; - }; - } else { - envelope = undampedFreq => { - const a = Math.exp(-undampedFreq * duration); - const b = (undampedFreq - velocity) * duration + 1; - return -safeMin + a * b; - }; - derivative = undampedFreq => { - const a = Math.exp(-undampedFreq * duration); - const b = (velocity - undampedFreq) * (duration * duration); - return a * b; - }; - } - const initialGuess = 5 / duration; - const undampedFreq = approximateRoot(envelope, derivative, initialGuess); - duration = duration * 1000; - if (isNaN(undampedFreq)) { - return { - stiffness: 100, - damping: 10, - duration - }; - } else { - const stiffness = Math.pow(undampedFreq, 2) * mass; - return { - stiffness, - damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), - duration - }; - } -} -const rootIterations = 12; -function approximateRoot(envelope, derivative, initialGuess) { - let result = initialGuess; - for (let i = 1; i < rootIterations; i++) { - result = result - envelope(result) / derivative(result); - } - return result; -} -function calcAngularFreq(undampedFreq, dampingRatio) { - return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); -} -const durationKeys = ["duration", "bounce"]; -const physicsKeys = ["stiffness", "damping", "mass"]; -function isSpringType(options, keys) { - return keys.some(key => options[key] !== undefined); -} -function getSpringOptions(options) { - let springOptions = Object.assign({ - velocity: 0.0, - stiffness: 100, - damping: 10, - mass: 1.0, - isResolvedFromDuration: false - }, options); - if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) { - const derived = findSpring(options); - springOptions = Object.assign(Object.assign(Object.assign({}, springOptions), derived), { - velocity: 0.0, - mass: 1.0 - }); - springOptions.isResolvedFromDuration = true; - } - return springOptions; -} -function spring(_a) { - var { - from = 0.0, - to = 1.0, - restSpeed = 2, - restDelta - } = _a, - options = tslib.__rest(_a, ["from", "to", "restSpeed", "restDelta"]); - const state = { - done: false, - value: from - }; - let { - stiffness, - damping, - mass, - velocity, - duration, - isResolvedFromDuration - } = getSpringOptions(options); - let resolveSpring = zero; - let resolveVelocity = zero; - function createSpring() { - const initialVelocity = velocity ? -(velocity / 1000) : 0.0; - const initialDelta = to - from; - const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); - const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; - if (restDelta === undefined) { - restDelta = Math.min(Math.abs(to - from) / 100, 0.4); - } - if (dampingRatio < 1) { - const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); - resolveSpring = t => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); - }; - resolveVelocity = t => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - return dampingRatio * undampedAngularFreq * envelope * (Math.sin(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq + initialDelta * Math.cos(angularFreq * t)) - envelope * (Math.cos(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) - angularFreq * initialDelta * Math.sin(angularFreq * t)); - }; - } else if (dampingRatio === 1) { - resolveSpring = t => to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t); - } else { - const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); - resolveSpring = t => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - const freqForT = Math.min(dampedAngularFreq * t, 300); - return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq; - }; - } - } - createSpring(); - return { - next: t => { - const current = resolveSpring(t); - if (!isResolvedFromDuration) { - const currentVelocity = resolveVelocity(t) * 1000; - const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; - const isBelowDisplacementThreshold = Math.abs(to - current) <= restDelta; - state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold; - } else { - state.done = t >= duration; - } - state.value = state.done ? to : current; - return state; - }, - flipTarget: () => { - velocity = -velocity; - [from, to] = [to, from]; - createSpring(); - } - }; -} -spring.needsInterpolation = (a, b) => typeof a === "string" || typeof b === "string"; -const zero = _t => 0; -const progress = (from, to, value) => { - const toFromDifference = to - from; - return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; -}; -const mix = (from, to, progress) => -progress * from + progress * to + from; -function hueToRgb(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1 / 6) return p + (q - p) * 6 * t; - if (t < 1 / 2) return q; - if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; - return p; -} -function hslaToRgba({ - hue, - saturation, - lightness, - alpha -}) { - hue /= 360; - saturation /= 100; - lightness /= 100; - let red = 0; - let green = 0; - let blue = 0; - if (!saturation) { - red = green = blue = lightness; - } else { - const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; - const p = 2 * lightness - q; - red = hueToRgb(p, q, hue + 1 / 3); - green = hueToRgb(p, q, hue); - blue = hueToRgb(p, q, hue - 1 / 3); - } - return { - red: Math.round(red * 255), - green: Math.round(green * 255), - blue: Math.round(blue * 255), - alpha - }; -} -const mixLinearColor = (from, to, v) => { - const fromExpo = from * from; - const toExpo = to * to; - return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo)); -}; -const colorTypes = [styleValueTypes.hex, styleValueTypes.rgba, styleValueTypes.hsla]; -const getColorType = v => colorTypes.find(type => type.test(v)); -const notAnimatable = color => `'${color}' is not an animatable color. Use the equivalent color code instead.`; -const mixColor = (from, to) => { - let fromColorType = getColorType(from); - let toColorType = getColorType(to); - heyListen.invariant(!!fromColorType, notAnimatable(from)); - heyListen.invariant(!!toColorType, notAnimatable(to)); - let fromColor = fromColorType.parse(from); - let toColor = toColorType.parse(to); - if (fromColorType === styleValueTypes.hsla) { - fromColor = hslaToRgba(fromColor); - fromColorType = styleValueTypes.rgba; - } - if (toColorType === styleValueTypes.hsla) { - toColor = hslaToRgba(toColor); - toColorType = styleValueTypes.rgba; - } - const blended = Object.assign({}, fromColor); - return v => { - for (const key in blended) { - if (key !== "alpha") { - blended[key] = mixLinearColor(fromColor[key], toColor[key], v); - } - } - blended.alpha = mix(fromColor.alpha, toColor.alpha, v); - return fromColorType.transform(blended); - }; -}; -const zeroPoint = { - x: 0, - y: 0, - z: 0 -}; -const isNum = v => typeof v === 'number'; -const combineFunctions = (a, b) => v => b(a(v)); -const pipe = (...transformers) => transformers.reduce(combineFunctions); -function getMixer(origin, target) { - if (isNum(origin)) { - return v => mix(origin, target, v); - } else if (styleValueTypes.color.test(origin)) { - return mixColor(origin, target); - } else { - return mixComplex(origin, target); - } -} -const mixArray = (from, to) => { - const output = [...from]; - const numValues = output.length; - const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i])); - return v => { - for (let i = 0; i < numValues; i++) { - output[i] = blendValue[i](v); - } - return output; - }; -}; -const mixObject = (origin, target) => { - const output = Object.assign(Object.assign({}, origin), target); - const blendValue = {}; - for (const key in output) { - if (origin[key] !== undefined && target[key] !== undefined) { - blendValue[key] = getMixer(origin[key], target[key]); - } - } - return v => { - for (const key in blendValue) { - output[key] = blendValue[key](v); - } - return output; - }; -}; -function analyse(value) { - const parsed = styleValueTypes.complex.parse(value); - const numValues = parsed.length; - let numNumbers = 0; - let numRGB = 0; - let numHSL = 0; - for (let i = 0; i < numValues; i++) { - if (numNumbers || typeof parsed[i] === "number") { - numNumbers++; - } else { - if (parsed[i].hue !== undefined) { - numHSL++; - } else { - numRGB++; - } - } - } - return { - parsed, - numNumbers, - numRGB, - numHSL - }; -} -const mixComplex = (origin, target) => { - const template = styleValueTypes.complex.createTransformer(target); - const originStats = analyse(origin); - const targetStats = analyse(target); - const canInterpolate = originStats.numHSL === targetStats.numHSL && originStats.numRGB === targetStats.numRGB && originStats.numNumbers >= targetStats.numNumbers; - if (canInterpolate) { - return pipe(mixArray(originStats.parsed, targetStats.parsed), template); - } else { - heyListen.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`); - return p => `${p > 0 ? target : origin}`; - } -}; -const mixNumber = (from, to) => p => mix(from, to, p); -function detectMixerFactory(v) { - if (typeof v === 'number') { - return mixNumber; - } else if (typeof v === 'string') { - if (styleValueTypes.color.test(v)) { - return mixColor; - } else { - return mixComplex; - } - } else if (Array.isArray(v)) { - return mixArray; - } else if (typeof v === 'object') { - return mixObject; - } -} -function createMixers(output, ease, customMixer) { - const mixers = []; - const mixerFactory = customMixer || detectMixerFactory(output[0]); - const numMixers = output.length - 1; - for (let i = 0; i < numMixers; i++) { - let mixer = mixerFactory(output[i], output[i + 1]); - if (ease) { - const easingFunction = Array.isArray(ease) ? ease[i] : ease; - mixer = pipe(easingFunction, mixer); - } - mixers.push(mixer); - } - return mixers; -} -function fastInterpolate([from, to], [mixer]) { - return v => mixer(progress(from, to, v)); -} -function slowInterpolate(input, mixers) { - const inputLength = input.length; - const lastInputIndex = inputLength - 1; - return v => { - let mixerIndex = 0; - let foundMixerIndex = false; - if (v <= input[0]) { - foundMixerIndex = true; - } else if (v >= input[lastInputIndex]) { - mixerIndex = lastInputIndex - 1; - foundMixerIndex = true; - } - if (!foundMixerIndex) { - let i = 1; - for (; i < inputLength; i++) { - if (input[i] > v || i === lastInputIndex) { - break; - } - } - mixerIndex = i - 1; - } - const progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v); - return mixers[mixerIndex](progressInRange); - }; -} -function interpolate(input, output, { - clamp: isClamp = true, - ease, - mixer -} = {}) { - const inputLength = input.length; - heyListen.invariant(inputLength === output.length, 'Both input and output ranges must be the same length'); - heyListen.invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1, 'Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values.'); - if (input[0] > input[inputLength - 1]) { - input = [].concat(input); - output = [].concat(output); - input.reverse(); - output.reverse(); - } - const mixers = createMixers(output, ease, mixer); - const interpolator = inputLength === 2 ? fastInterpolate(input, mixers) : slowInterpolate(input, mixers); - return isClamp ? v => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator; -} -const reverseEasing = easing => p => 1 - easing(1 - p); -const mirrorEasing = easing => p => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; -const createExpoIn = power => p => Math.pow(p, power); -const createBackIn = power => p => p * p * ((power + 1) * p - power); -const createAnticipate = power => { - const backEasing = createBackIn(power); - return p => (p *= 2) < 1 ? 0.5 * backEasing(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); -}; -const DEFAULT_OVERSHOOT_STRENGTH = 1.525; -const BOUNCE_FIRST_THRESHOLD = 4.0 / 11.0; -const BOUNCE_SECOND_THRESHOLD = 8.0 / 11.0; -const BOUNCE_THIRD_THRESHOLD = 9.0 / 10.0; -const linear = p => p; -const easeIn = createExpoIn(2); -const easeOut = reverseEasing(easeIn); -const easeInOut = mirrorEasing(easeIn); -const circIn = p => 1 - Math.sin(Math.acos(p)); -const circOut = reverseEasing(circIn); -const circInOut = mirrorEasing(circOut); -const backIn = createBackIn(DEFAULT_OVERSHOOT_STRENGTH); -const backOut = reverseEasing(backIn); -const backInOut = mirrorEasing(backIn); -const anticipate = createAnticipate(DEFAULT_OVERSHOOT_STRENGTH); -const ca = 4356.0 / 361.0; -const cb = 35442.0 / 1805.0; -const cc = 16061.0 / 1805.0; -const bounceOut = p => { - if (p === 1 || p === 0) return p; - const p2 = p * p; - return p < BOUNCE_FIRST_THRESHOLD ? 7.5625 * p2 : p < BOUNCE_SECOND_THRESHOLD ? 9.075 * p2 - 9.9 * p + 3.4 : p < BOUNCE_THIRD_THRESHOLD ? ca * p2 - cb * p + cc : 10.8 * p * p - 20.52 * p + 10.72; -}; -const bounceIn = reverseEasing(bounceOut); -const bounceInOut = p => p < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - p * 2.0)) : 0.5 * bounceOut(p * 2.0 - 1.0) + 0.5; -function defaultEasing(values, easing) { - return values.map(() => easing || easeInOut).splice(0, values.length - 1); -} -function defaultOffset(values) { - const numValues = values.length; - return values.map((_value, i) => i !== 0 ? i / (numValues - 1) : 0); -} -function convertOffsetToTimes(offset, duration) { - return offset.map(o => o * duration); -} -function keyframes({ - from = 0, - to = 1, - ease, - offset, - duration = 300 -}) { - const state = { - done: false, - value: from - }; - const values = Array.isArray(to) ? to : [from, to]; - const times = convertOffsetToTimes(offset && offset.length === values.length ? offset : defaultOffset(values), duration); - function createInterpolator() { - return interpolate(times, values, { - ease: Array.isArray(ease) ? ease : defaultEasing(values, ease) - }); - } - let interpolator = createInterpolator(); - return { - next: t => { - state.value = interpolator(t); - state.done = t >= duration; - return state; - }, - flipTarget: () => { - values.reverse(); - interpolator = createInterpolator(); - } - }; -} -function decay({ - velocity = 0, - from = 0, - power = 0.8, - timeConstant = 350, - restDelta = 0.5, - modifyTarget -}) { - const state = { - done: false, - value: from - }; - let amplitude = power * velocity; - const ideal = from + amplitude; - const target = modifyTarget === undefined ? ideal : modifyTarget(ideal); - if (target !== ideal) amplitude = target - from; - return { - next: t => { - const delta = -amplitude * Math.exp(-t / timeConstant); - state.done = !(delta > restDelta || delta < -restDelta); - state.value = state.done ? target : target + delta; - return state; - }, - flipTarget: () => {} - }; -} -const types = { - keyframes, - spring, - decay -}; -function detectAnimationFromOptions(config) { - if (Array.isArray(config.to)) { - return keyframes; - } else if (types[config.type]) { - return types[config.type]; - } - const keys = new Set(Object.keys(config)); - if (keys.has("ease") || keys.has("duration") && !keys.has("dampingRatio")) { - return keyframes; - } else if (keys.has("dampingRatio") || keys.has("stiffness") || keys.has("mass") || keys.has("damping") || keys.has("restSpeed") || keys.has("restDelta")) { - return spring; - } - return keyframes; -} -function loopElapsed(elapsed, duration, delay = 0) { - return elapsed - duration - delay; -} -function reverseElapsed(elapsed, duration, delay = 0, isForwardPlayback = true) { - return isForwardPlayback ? loopElapsed(duration + -elapsed, duration, delay) : duration - (elapsed - duration) + delay; -} -function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) { - return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay; -} -const framesync = update => { - const passTimestamp = ({ - delta - }) => update(delta); - return { - start: () => sync__default["default"].update(passTimestamp, true), - stop: () => sync.cancelSync.update(passTimestamp) - }; -}; -function animate(_a) { - var _b, _c; - var { - from, - autoplay = true, - driver = framesync, - elapsed = 0, - repeat: repeatMax = 0, - repeatType = "loop", - repeatDelay = 0, - onPlay, - onStop, - onComplete, - onRepeat, - onUpdate - } = _a, - options = tslib.__rest(_a, ["from", "autoplay", "driver", "elapsed", "repeat", "repeatType", "repeatDelay", "onPlay", "onStop", "onComplete", "onRepeat", "onUpdate"]); - let { - to - } = options; - let driverControls; - let repeatCount = 0; - let computedDuration = options.duration; - let latest; - let isComplete = false; - let isForwardPlayback = true; - let interpolateFromNumber; - const animator = detectAnimationFromOptions(options); - if ((_c = (_b = animator).needsInterpolation) === null || _c === void 0 ? void 0 : _c.call(_b, from, to)) { - interpolateFromNumber = interpolate([0, 100], [from, to], { - clamp: false - }); - from = 0; - to = 100; - } - const animation = animator(Object.assign(Object.assign({}, options), { - from, - to - })); - function repeat() { - repeatCount++; - if (repeatType === "reverse") { - isForwardPlayback = repeatCount % 2 === 0; - elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback); - } else { - elapsed = loopElapsed(elapsed, computedDuration, repeatDelay); - if (repeatType === "mirror") animation.flipTarget(); - } - isComplete = false; - onRepeat && onRepeat(); - } - function complete() { - driverControls.stop(); - onComplete && onComplete(); - } - function update(delta) { - if (!isForwardPlayback) delta = -delta; - elapsed += delta; - if (!isComplete) { - const state = animation.next(Math.max(0, elapsed)); - latest = state.value; - if (interpolateFromNumber) latest = interpolateFromNumber(latest); - isComplete = isForwardPlayback ? state.done : elapsed <= 0; - } - onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(latest); - if (isComplete) { - if (repeatCount === 0) computedDuration !== null && computedDuration !== void 0 ? computedDuration : computedDuration = elapsed; - if (repeatCount < repeatMax) { - hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat(); - } else { - complete(); - } - } - } - function play() { - onPlay === null || onPlay === void 0 ? void 0 : onPlay(); - driverControls = driver(update); - driverControls.start(); - } - autoplay && play(); - return { - stop: () => { - onStop === null || onStop === void 0 ? void 0 : onStop(); - driverControls.stop(); - } - }; -} -function velocityPerSecond(velocity, frameDuration) { - return frameDuration ? velocity * (1000 / frameDuration) : 0; -} -function inertia({ - from = 0, - velocity = 0, - min, - max, - power = 0.8, - timeConstant = 750, - bounceStiffness = 500, - bounceDamping = 10, - restDelta = 1, - modifyTarget, - driver, - onUpdate, - onComplete, - onStop -}) { - let currentAnimation; - function isOutOfBounds(v) { - return min !== undefined && v < min || max !== undefined && v > max; - } - function boundaryNearest(v) { - if (min === undefined) return max; - if (max === undefined) return min; - return Math.abs(min - v) < Math.abs(max - v) ? min : max; - } - function startAnimation(options) { - currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop(); - currentAnimation = animate(Object.assign(Object.assign({}, options), { - driver, - onUpdate: v => { - var _a; - onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(v); - (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, v); - }, - onComplete, - onStop - })); - } - function startSpring(options) { - startAnimation(Object.assign({ - type: "spring", - stiffness: bounceStiffness, - damping: bounceDamping, - restDelta - }, options)); - } - if (isOutOfBounds(from)) { - startSpring({ - from, - velocity, - to: boundaryNearest(from) - }); - } else { - let target = power * velocity + from; - if (typeof modifyTarget !== "undefined") target = modifyTarget(target); - const boundary = boundaryNearest(target); - const heading = boundary === min ? -1 : 1; - let prev; - let current; - const checkBoundary = v => { - prev = current; - current = v; - velocity = velocityPerSecond(v - prev, sync.getFrameData().delta); - if (heading === 1 && v > boundary || heading === -1 && v < boundary) { - startSpring({ - from: v, - to: boundary, - velocity - }); - } - }; - startAnimation({ - type: "decay", - from, - velocity, - timeConstant, - power, - restDelta, - modifyTarget, - onUpdate: isOutOfBounds(target) ? checkBoundary : undefined - }); - } - return { - stop: () => currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop() - }; -} -const radiansToDegrees = radians => radians * 180 / Math.PI; -const angle = (a, b = zeroPoint) => radiansToDegrees(Math.atan2(b.y - a.y, b.x - a.x)); -const applyOffset = (from, to) => { - let hasReceivedFrom = true; - if (to === undefined) { - to = from; - hasReceivedFrom = false; - } - return v => { - if (hasReceivedFrom) { - return v - from + to; - } else { - from = v; - hasReceivedFrom = true; - return to; - } - }; -}; -const identity = v => v; -const createAttractor = (alterDisplacement = identity) => (constant, origin, v) => { - const displacement = origin - v; - const springModifiedDisplacement = -(0 - constant + 1) * (0 - alterDisplacement(Math.abs(displacement))); - return displacement <= 0 ? origin + springModifiedDisplacement : origin - springModifiedDisplacement; -}; -const attract = createAttractor(); -const attractExpo = createAttractor(Math.sqrt); -const degreesToRadians = degrees => degrees * Math.PI / 180; -const isPoint = point => point.hasOwnProperty('x') && point.hasOwnProperty('y'); -const isPoint3D = point => isPoint(point) && point.hasOwnProperty('z'); -const distance1D = (a, b) => Math.abs(a - b); -function distance(a, b) { - if (isNum(a) && isNum(b)) { - return distance1D(a, b); - } else if (isPoint(a) && isPoint(b)) { - const xDelta = distance1D(a.x, b.x); - const yDelta = distance1D(a.y, b.y); - const zDelta = isPoint3D(a) && isPoint3D(b) ? distance1D(a.z, b.z) : 0; - return Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2)); - } -} -const pointFromVector = (origin, angle, distance) => { - angle = degreesToRadians(angle); - return { - x: distance * Math.cos(angle) + origin.x, - y: distance * Math.sin(angle) + origin.y - }; -}; -const toDecimal = (num, precision = 2) => { - precision = Math.pow(10, precision); - return Math.round(num * precision) / precision; -}; -const smoothFrame = (prevValue, nextValue, duration, smoothing = 0) => toDecimal(prevValue + duration * (nextValue - prevValue) / Math.max(smoothing, duration)); -const smooth = (strength = 50) => { - let previousValue = 0; - let lastUpdated = 0; - return v => { - const currentFramestamp = sync.getFrameData().timestamp; - const timeDelta = currentFramestamp !== lastUpdated ? currentFramestamp - lastUpdated : 0; - const newValue = timeDelta ? smoothFrame(previousValue, v, timeDelta, strength) : previousValue; - lastUpdated = currentFramestamp; - previousValue = newValue; - return newValue; - }; -}; -const snap = points => { - if (typeof points === 'number') { - return v => Math.round(v / points) * points; - } else { - let i = 0; - const numPoints = points.length; - return v => { - let lastDistance = Math.abs(points[0] - v); - for (i = 1; i < numPoints; i++) { - const point = points[i]; - const distance = Math.abs(point - v); - if (distance === 0) return point; - if (distance > lastDistance) return points[i - 1]; - if (i === numPoints - 1) return point; - lastDistance = distance; - } - }; - } -}; -function velocityPerFrame(xps, frameDuration) { - return xps / (1000 / frameDuration); -} -const wrap = (min, max, v) => { - const rangeSize = max - min; - return ((v - min) % rangeSize + rangeSize) % rangeSize + min; -}; -const a = (a1, a2) => 1.0 - 3.0 * a2 + 3.0 * a1; -const b = (a1, a2) => 3.0 * a2 - 6.0 * a1; -const c = a1 => 3.0 * a1; -const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; -const getSlope = (t, a1, a2) => 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1); -const subdivisionPrecision = 0.0000001; -const subdivisionMaxIterations = 10; -function binarySubdivide(aX, aA, aB, mX1, mX2) { - let currentX; - let currentT; - let i = 0; - do { - currentT = aA + (aB - aA) / 2.0; - currentX = calcBezier(currentT, mX1, mX2) - aX; - if (currentX > 0.0) { - aB = currentT; - } else { - aA = currentT; - } - } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); - return currentT; -} -const newtonIterations = 8; -const newtonMinSlope = 0.001; -function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { - for (let i = 0; i < newtonIterations; ++i) { - const currentSlope = getSlope(aGuessT, mX1, mX2); - if (currentSlope === 0.0) { - return aGuessT; - } - const currentX = calcBezier(aGuessT, mX1, mX2) - aX; - aGuessT -= currentX / currentSlope; - } - return aGuessT; -} -const kSplineTableSize = 11; -const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); -function cubicBezier(mX1, mY1, mX2, mY2) { - if (mX1 === mY1 && mX2 === mY2) return linear; - const sampleValues = new Float32Array(kSplineTableSize); - for (let i = 0; i < kSplineTableSize; ++i) { - sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); - } - function getTForX(aX) { - let intervalStart = 0.0; - let currentSample = 1; - const lastSample = kSplineTableSize - 1; - for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) { - intervalStart += kSampleStepSize; - } - --currentSample; - const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); - const guessForT = intervalStart + dist * kSampleStepSize; - const initialSlope = getSlope(guessForT, mX1, mX2); - if (initialSlope >= newtonMinSlope) { - return newtonRaphsonIterate(aX, guessForT, mX1, mX2); - } else if (initialSlope === 0.0) { - return guessForT; - } else { - return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); - } - } - return t => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); -} -const steps = (steps, direction = 'end') => progress => { - progress = direction === 'end' ? Math.min(progress, 0.999) : Math.max(progress, 0.001); - const expanded = progress * steps; - const rounded = direction === 'end' ? Math.floor(expanded) : Math.ceil(expanded); - return clamp(0, 1, rounded / steps); -}; -exports.angle = angle; -exports.animate = animate; -exports.anticipate = anticipate; -exports.applyOffset = applyOffset; -exports.attract = attract; -exports.attractExpo = attractExpo; -exports.backIn = backIn; -exports.backInOut = backInOut; -exports.backOut = backOut; -exports.bounceIn = bounceIn; -exports.bounceInOut = bounceInOut; -exports.bounceOut = bounceOut; -exports.circIn = circIn; -exports.circInOut = circInOut; -exports.circOut = circOut; -exports.clamp = clamp; -exports.createAnticipate = createAnticipate; -exports.createAttractor = createAttractor; -exports.createBackIn = createBackIn; -exports.createExpoIn = createExpoIn; -exports.cubicBezier = cubicBezier; -exports.decay = decay; -exports.degreesToRadians = degreesToRadians; -exports.distance = distance; -exports.easeIn = easeIn; -exports.easeInOut = easeInOut; -exports.easeOut = easeOut; -exports.inertia = inertia; -exports.interpolate = interpolate; -exports.isPoint = isPoint; -exports.isPoint3D = isPoint3D; -exports.keyframes = keyframes; -exports.linear = linear; -exports.mirrorEasing = mirrorEasing; -exports.mix = mix; -exports.mixColor = mixColor; -exports.mixComplex = mixComplex; -exports.pipe = pipe; -exports.pointFromVector = pointFromVector; -exports.progress = progress; -exports.radiansToDegrees = radiansToDegrees; -exports.reverseEasing = reverseEasing; -exports.smooth = smooth; -exports.smoothFrame = smoothFrame; -exports.snap = snap; -exports.spring = spring; -exports.steps = steps; -exports.toDecimal = toDecimal; -exports.velocityPerFrame = velocityPerFrame; -exports.velocityPerSecond = velocityPerSecond; -exports.wrap = wrap; - -/***/ }), - -/***/ "../../../node_modules/punycode.js/punycode.es6.js": -/*!*********************************************************!*\ - !*** ../../../node_modules/punycode.js/punycode.es6.js ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -/** Highest positive signed 32-bit float value */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.toUnicode = exports.toASCII = exports.encode = exports["default"] = exports.decode = void 0; -exports.ucs2decode = ucs2decode; -exports.ucs2encode = void 0; -const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - -/** Bootstring parameters */ -const base = 36; -const tMin = 1; -const tMax = 26; -const skew = 38; -const damp = 700; -const initialBias = 72; -const initialN = 128; // 0x80 -const delimiter = '-'; // '\x2D' - -/** Regular expressions */ -const regexPunycode = /^xn--/; -const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. -const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - -/** Error messages */ -const errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' -}; + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + const adapt = function (delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for ( + ; + /* no initialization */ + delta > (baseMinusTMin * tMax) >> 1; + k += base + ) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + ((baseMinusTMin + 1) * delta) / (delta + skew)); + }; -/** Convenience shortcuts */ -const baseMinusTMin = base - tMin; -const floor = Math.floor; -const stringFromCharCode = String.fromCharCode; - -/*--------------------------------------------------------------------------*/ - -/** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ -function error(type) { - throw new RangeError(errors[type]); -} - -/** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ -function map(array, callback) { - const result = []; - let length = array.length; - while (length--) { - result[length] = callback(array[length]); - } - return result; -} - -/** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {String} A new string of characters returned by the callback - * function. - */ -function mapDomain(domain, callback) { - const parts = domain.split('@'); - let result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - domain = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - domain = domain.replace(regexSeparators, '\x2E'); - const labels = domain.split('.'); - const encoded = map(labels, callback).join('.'); - return result + encoded; -} - -/** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ -function ucs2decode(string) { - const output = []; - let counter = 0; - const length = string.length; - while (counter < length) { - const value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // It's a high surrogate, and there is a next character. - const extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // Low surrogate. - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // It's an unmatched surrogate; only append this code unit, in case the - // next code unit is the high surrogate of a surrogate pair. - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; -} - -/** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ -const ucs2encode = codePoints => String.fromCodePoint(...codePoints); - -/** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ -exports.ucs2encode = ucs2encode; -const basicToDigit = function (codePoint) { - if (codePoint >= 0x30 && codePoint < 0x3A) { - return 26 + (codePoint - 0x30); - } - if (codePoint >= 0x41 && codePoint < 0x5B) { - return codePoint - 0x41; - } - if (codePoint >= 0x61 && codePoint < 0x7B) { - return codePoint - 0x61; - } - return base; -}; + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + const decode = function (input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error("not-basic"); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for ( + /* no final expression */ + let index = basic > 0 ? basic + 1 : 0; + index < inputLength; + + ) { + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (/* no condition */ let w = 1, k = base; ; k += base) { + if (index >= inputLength) { + error("invalid-input"); + } + const digit = basicToDigit(input.charCodeAt(index++)); + if (digit >= base) { + error("invalid-input"); + } + if (digit > floor((maxInt - i) / w)) { + error("overflow"); + } + i += digit * w; + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (digit < t) { + break; + } + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error("overflow"); + } + w *= baseMinusT; + } + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); -/** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ -const digitToBasic = function (digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); -}; + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error("overflow"); + } + n += floor(i / out); + i %= out; -/** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ -const adapt = function (delta, numPoints, firstTime) { - let k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for /* no initialization */ - (; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); -}; + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + return String.fromCodePoint(...output); + }; -/** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ -const decode = function (input) { - // Don't use UCS-2. - const output = []; - const inputLength = input.length; - let i = 0; - let n = initialN; - let bias = initialBias; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - let basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - for (let j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + exports.decode = decode; + const encode = function (input) { + const output = []; - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for /* no final expression */ - (let index = basic > 0 ? basic + 1 : 0; index < inputLength;) { - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - const oldi = i; - for /* no condition */ - (let w = 1, k = base;; k += base) { - if (index >= inputLength) { - error('invalid-input'); - } - const digit = basicToDigit(input.charCodeAt(index++)); - if (digit >= base) { - error('invalid-input'); - } - if (digit > floor((maxInt - i) / w)) { - error('overflow'); - } - i += digit * w; - const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (digit < t) { - break; - } - const baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - w *= baseMinusT; - } - const out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - n += floor(i / out); - i %= out; + // Cache the length. + const inputLength = input.length; - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } - return String.fromCodePoint(...output); -}; + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; -/** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ -exports.decode = decode; -const encode = function (input) { - const output = []; - - // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); - - // Cache the length. - const inputLength = input.length; - - // Initialize the state. - let n = initialN; - let delta = 0; - let bias = initialBias; - - // Handle the basic code points. - for (const currentValue of input) { - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - const basicLength = output.length; - let handledCPCount = basicLength; + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + const basicLength = output.length; + let handledCPCount = basicLength; - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - // Finish the basic string with a delimiter unless it's empty. - if (basicLength) { - output.push(delimiter); - } + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } - // Main encoding loop: - while (handledCPCount < inputLength) { - // All non-basic code points < n have been handled already. Find the next - // larger one: - let m = maxInt; - for (const currentValue of input) { - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow. - const handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - delta += (m - n) * handledCPCountPlusOne; - n = m; - for (const currentValue of input) { - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - if (currentValue === n) { - // Represent delta as a generalized variable-length integer. - let q = delta; - for /* no condition */ - (let k = base;; k += base) { - const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error("overflow"); + } + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error("overflow"); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (/* no condition */ let k = base; ; k += base) { + const t = + k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode( + digitToBasic(t + (qMinusT % baseMinusT), 0) + ) + ); + q = floor(qMinusT / baseMinusT); + } + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt( + delta, + handledCPCountPlusOne, + handledCPCount === basicLength + ); + delta = 0; + ++handledCPCount; + } + } + ++delta; + ++n; } - const qMinusT = q - t; - const baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); - delta = 0; - ++handledCPCount; - } - } - ++delta; - ++n; - } - return output.join(''); -}; + return output.join(""); + }; -/** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ -exports.encode = encode; -const toUnicode = function (input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); -}; + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + exports.encode = encode; + const toUnicode = function (input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + }; -/** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ -exports.toUnicode = toUnicode; -const toASCII = function (input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); -}; + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + exports.toUnicode = toUnicode; + const toASCII = function (input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) + ? "xn--" + encode(string) + : string; + }); + }; -/*--------------------------------------------------------------------------*/ - -/** Define the public API */ -exports.toASCII = toASCII; -const punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '2.3.1', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode -}; -var _default = exports["default"] = punycode; + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + exports.toASCII = toASCII; + const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + version: "2.3.1", + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + ucs2: { + decode: ucs2decode, + encode: ucs2encode, + }, + decode: decode, + encode: encode, + toASCII: toASCII, + toUnicode: toUnicode, + }; + var _default = (exports["default"] = punycode); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js": -/*!******************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js": + /*!******************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js ***! \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.RemoveScrollBar = void 0; -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); -var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); -var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -var Style = (0, _reactStyleSingleton.styleSingleton)(); -// important tip - once we measure scrollBar width and remove them -// we could not repeat this operation -// thus we are using style-singleton - only the first "yet correct" style will be applied. -var getStyles = function (_a, allowRelative, gapMode, important) { - var left = _a.left, - top = _a.top, - right = _a.right, - gap = _a.gap; - if (gapMode === void 0) { - gapMode = 'margin'; - } - return "\n .".concat(_constants.noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([allowRelative && "position: relative ".concat(important, ";"), gapMode === 'margin' && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), gapMode === 'padding' && "padding-right: ".concat(gap, "px ").concat(important, ";")].filter(Boolean).join(''), "\n }\n \n .").concat(_constants.zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.zeroRightClassName, " .").concat(_constants.zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " .").concat(_constants.fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body {\n ").concat(_constants.removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); -}; -/** - * Removes page scrollbar and blocks page scroll when mounted - */ -var RemoveScrollBar = function (props) { - var noRelative = props.noRelative, - noImportant = props.noImportant, - _a = props.gapMode, - gapMode = _a === void 0 ? 'margin' : _a; - var gap = React.useMemo(function () { - return (0, _utils.getGapWidth)(gapMode); - }, [gapMode]); - return /*#__PURE__*/React.createElement(Style, { - styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') - }); -}; -exports.RemoveScrollBar = RemoveScrollBar; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.RemoveScrollBar = void 0; + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _reactStyleSingleton = __webpack_require__( + /*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js" + ); + var _constants = __webpack_require__( + /*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js" + ); + var _utils = __webpack_require__( + /*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js" + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + var Style = (0, _reactStyleSingleton.styleSingleton)(); + // important tip - once we measure scrollBar width and remove them + // we could not repeat this operation + // thus we are using style-singleton - only the first "yet correct" style will be applied. + var getStyles = function (_a, allowRelative, gapMode, important) { + var left = _a.left, + top = _a.top, + right = _a.right, + gap = _a.gap; + if (gapMode === void 0) { + gapMode = "margin"; + } + return "\n ." + .concat( + _constants.noScrollbarsClassName, + " {\n overflow: hidden " + ) + .concat(important, ";\n padding-right: ") + .concat(gap, "px ") + .concat(important, ";\n }\n body {\n overflow: hidden ") + .concat(important, ";\n overscroll-behavior: contain;\n ") + .concat( + [ + allowRelative && "position: relative ".concat(important, ";"), + gapMode === "margin" && + "\n padding-left: " + .concat(left, "px;\n padding-top: ") + .concat(top, "px;\n padding-right: ") + .concat( + right, + "px;\n margin-left:0;\n margin-top:0;\n margin-right: " + ) + .concat(gap, "px ") + .concat(important, ";\n "), + gapMode === "padding" && + "padding-right: ".concat(gap, "px ").concat(important, ";"), + ] + .filter(Boolean) + .join(""), + "\n }\n \n ." + ) + .concat(_constants.zeroRightClassName, " {\n right: ") + .concat(gap, "px ") + .concat(important, ";\n }\n \n .") + .concat(_constants.fullWidthClassName, " {\n margin-right: ") + .concat(gap, "px ") + .concat(important, ";\n }\n \n .") + .concat(_constants.zeroRightClassName, " .") + .concat(_constants.zeroRightClassName, " {\n right: 0 ") + .concat(important, ";\n }\n \n .") + .concat(_constants.fullWidthClassName, " .") + .concat(_constants.fullWidthClassName, " {\n margin-right: 0 ") + .concat(important, ";\n }\n \n body {\n ") + .concat(_constants.removedBarSizeVariable, ": ") + .concat(gap, "px;\n }\n"); + }; + /** + * Removes page scrollbar and blocks page scroll when mounted + */ + var RemoveScrollBar = function (props) { + var noRelative = props.noRelative, + noImportant = props.noImportant, + _a = props.gapMode, + gapMode = _a === void 0 ? "margin" : _a; + var gap = React.useMemo( + function () { + return (0, _utils.getGapWidth)(gapMode); + }, + [gapMode] + ); + return /*#__PURE__*/ React.createElement(Style, { + styles: getStyles( + gap, + !noRelative, + gapMode, + !noImportant ? "!important" : "" + ), + }); + }; + exports.RemoveScrollBar = RemoveScrollBar; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js": -/*!******************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js": + /*!******************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js ***! \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.zeroRightClassName = exports.removedBarSizeVariable = exports.noScrollbarsClassName = exports.fullWidthClassName = void 0; -var zeroRightClassName = exports.zeroRightClassName = 'right-scroll-bar-position'; -var fullWidthClassName = exports.fullWidthClassName = 'width-before-scroll-bar'; -var noScrollbarsClassName = exports.noScrollbarsClassName = 'with-scroll-bars-hidden'; -/** - * Name of a CSS variable containing the amount of "hidden" scrollbar - * ! might be undefined ! use will fallback! - */ -var removedBarSizeVariable = exports.removedBarSizeVariable = '--removed-body-scroll-bar-size'; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.zeroRightClassName = + exports.removedBarSizeVariable = + exports.noScrollbarsClassName = + exports.fullWidthClassName = + void 0; + var zeroRightClassName = (exports.zeroRightClassName = + "right-scroll-bar-position"); + var fullWidthClassName = (exports.fullWidthClassName = + "width-before-scroll-bar"); + var noScrollbarsClassName = (exports.noScrollbarsClassName = + "with-scroll-bars-hidden"); + /** + * Name of a CSS variable containing the amount of "hidden" scrollbar + * ! might be undefined ! use will fallback! + */ + var removedBarSizeVariable = (exports.removedBarSizeVariable = + "--removed-body-scroll-bar-size"); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js": -/*!**************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js": + /*!**************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js ***! \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "RemoveScrollBar", ({ - enumerable: true, - get: function () { - return _component.RemoveScrollBar; - } -})); -Object.defineProperty(exports, "fullWidthClassName", ({ - enumerable: true, - get: function () { - return _constants.fullWidthClassName; - } -})); -Object.defineProperty(exports, "getGapWidth", ({ - enumerable: true, - get: function () { - return _utils.getGapWidth; - } -})); -Object.defineProperty(exports, "noScrollbarsClassName", ({ - enumerable: true, - get: function () { - return _constants.noScrollbarsClassName; - } -})); -Object.defineProperty(exports, "removedBarSizeVariable", ({ - enumerable: true, - get: function () { - return _constants.removedBarSizeVariable; - } -})); -Object.defineProperty(exports, "zeroRightClassName", ({ - enumerable: true, - get: function () { - return _constants.zeroRightClassName; - } -})); -var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js"); -var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); -var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "RemoveScrollBar", { + enumerable: true, + get: function () { + return _component.RemoveScrollBar; + }, + }); + Object.defineProperty(exports, "fullWidthClassName", { + enumerable: true, + get: function () { + return _constants.fullWidthClassName; + }, + }); + Object.defineProperty(exports, "getGapWidth", { + enumerable: true, + get: function () { + return _utils.getGapWidth; + }, + }); + Object.defineProperty(exports, "noScrollbarsClassName", { + enumerable: true, + get: function () { + return _constants.noScrollbarsClassName; + }, + }); + Object.defineProperty(exports, "removedBarSizeVariable", { + enumerable: true, + get: function () { + return _constants.removedBarSizeVariable; + }, + }); + Object.defineProperty(exports, "zeroRightClassName", { + enumerable: true, + get: function () { + return _constants.zeroRightClassName; + }, + }); + var _component = __webpack_require__( + /*! ./component */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js" + ); + var _constants = __webpack_require__( + /*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js" + ); + var _utils = __webpack_require__( + /*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js" + ); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js": -/*!**************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js": + /*!**************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js ***! \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.zeroGap = exports.getGapWidth = void 0; -var zeroGap = exports.zeroGap = { - left: 0, - top: 0, - right: 0, - gap: 0 -}; -var parse = function (x) { - return parseInt(x || '', 10) || 0; -}; -var getOffset = function (gapMode) { - var cs = window.getComputedStyle(document.body); - if (true) { - if (cs.overflowY === 'hidden') { - console.error('react-remove-scroll-bar: cannot calculate scrollbar size because it is removed (overflow:hidden on body'); - } - } - var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft']; - var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop']; - var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight']; - return [parse(left), parse(top), parse(right)]; -}; -var getGapWidth = function (gapMode) { - if (gapMode === void 0) { - gapMode = 'margin'; - } - if (typeof window === 'undefined') { - return zeroGap; - } - var offsets = getOffset(gapMode); - var documentWidth = document.documentElement.clientWidth; - var windowWidth = window.innerWidth; - return { - left: offsets[0], - top: offsets[1], - right: offsets[2], - gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) - }; -}; -exports.getGapWidth = getGapWidth; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.zeroGap = exports.getGapWidth = void 0; + var zeroGap = (exports.zeroGap = { + left: 0, + top: 0, + right: 0, + gap: 0, + }); + var parse = function (x) { + return parseInt(x || "", 10) || 0; + }; + var getOffset = function (gapMode) { + var cs = window.getComputedStyle(document.body); + if (true) { + if (cs.overflowY === "hidden") { + console.error( + "react-remove-scroll-bar: cannot calculate scrollbar size because it is removed (overflow:hidden on body" + ); + } + } + var left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"]; + var top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"]; + var right = + cs[gapMode === "padding" ? "paddingRight" : "marginRight"]; + return [parse(left), parse(top), parse(right)]; + }; + var getGapWidth = function (gapMode) { + if (gapMode === void 0) { + gapMode = "margin"; + } + if (typeof window === "undefined") { + return zeroGap; + } + var offsets = getOffset(gapMode); + var documentWidth = document.documentElement.clientWidth; + var windowWidth = window.innerWidth; + return { + left: offsets[0], + top: offsets[1], + right: offsets[2], + gap: Math.max( + 0, + windowWidth - documentWidth + offsets[2] - offsets[0] + ), + }; + }; + exports.getGapWidth = getGapWidth; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js": -/*!****************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js": + /*!****************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/Combination.js ***! \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _UI = __webpack_require__(/*! ./UI */ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js"); -var _sidecar = _interopRequireDefault(__webpack_require__(/*! ./sidecar */ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -var ReactRemoveScroll = /*#__PURE__*/React.forwardRef(function (props, ref) { - return /*#__PURE__*/React.createElement(_UI.RemoveScroll, (0, _tslib.__assign)({}, props, { - ref: ref, - sideCar: _sidecar.default - })); -}); -ReactRemoveScroll.classNames = _UI.RemoveScroll.classNames; -var _default = exports["default"] = ReactRemoveScroll; - -/***/ }), - -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js": -/*!***************************************************************************!*\ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = void 0; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _UI = __webpack_require__( + /*! ./UI */ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js" + ); + var _sidecar = _interopRequireDefault( + __webpack_require__( + /*! ./sidecar */ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js" + ) + ); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + var ReactRemoveScroll = /*#__PURE__*/ React.forwardRef(function ( + props, + ref + ) { + return /*#__PURE__*/ React.createElement( + _UI.RemoveScroll, + (0, _tslib.__assign)({}, props, { + ref: ref, + sideCar: _sidecar.default, + }) + ); + }); + ReactRemoveScroll.classNames = _UI.RemoveScroll.classNames; + var _default = (exports["default"] = ReactRemoveScroll); + + /***/ + }, + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js": + /*!***************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js ***! \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.RemoveScrollSideCar = RemoveScrollSideCar; -exports.getTouchXY = exports.getDeltaXY = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _reactRemoveScrollBar = __webpack_require__(/*! react-remove-scroll-bar */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js"); -var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); -var _aggresiveCapture = __webpack_require__(/*! ./aggresiveCapture */ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js"); -var _handleScroll = __webpack_require__(/*! ./handleScroll */ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js"); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -var getTouchXY = function (event) { - return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; -}; -exports.getTouchXY = getTouchXY; -var getDeltaXY = function (event) { - return [event.deltaX, event.deltaY]; -}; -exports.getDeltaXY = getDeltaXY; -var extractRef = function (ref) { - return ref && 'current' in ref ? ref.current : ref; -}; -var deltaCompare = function (x, y) { - return x[0] === y[0] && x[1] === y[1]; -}; -var generateStyle = function (id) { - return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); -}; -var idCounter = 0; -var lockStack = []; -function RemoveScrollSideCar(props) { - var shouldPreventQueue = React.useRef([]); - var touchStartRef = React.useRef([0, 0]); - var activeAxis = React.useRef(); - var id = React.useState(idCounter++)[0]; - var Style = React.useState(function () { - return (0, _reactStyleSingleton.styleSingleton)(); - })[0]; - var lastProps = React.useRef(props); - React.useEffect(function () { - lastProps.current = props; - }, [props]); - React.useEffect(function () { - if (props.inert) { - document.body.classList.add("block-interactivity-".concat(id)); - var allow_1 = (0, _tslib.__spreadArray)([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); - allow_1.forEach(function (el) { - return el.classList.add("allow-interactivity-".concat(id)); - }); - return function () { - document.body.classList.remove("block-interactivity-".concat(id)); - allow_1.forEach(function (el) { - return el.classList.remove("allow-interactivity-".concat(id)); - }); - }; - } - return; - }, [props.inert, props.lockRef.current, props.shards]); - var shouldCancelEvent = React.useCallback(function (event, parent) { - if ('touches' in event && event.touches.length === 2) { - return !lastProps.current.allowPinchZoom; - } - var touch = getTouchXY(event); - var touchStart = touchStartRef.current; - var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0]; - var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1]; - var currentAxis; - var target = event.target; - var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v'; - // allow horizontal touch move on Range inputs. They will not cause any scroll - if ('touches' in event && moveDirection === 'h' && target.type === 'range') { - return false; - } - var canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); - if (!canBeScrolledInMainDirection) { - return true; - } - if (canBeScrolledInMainDirection) { - currentAxis = moveDirection; - } else { - currentAxis = moveDirection === 'v' ? 'h' : 'v'; - canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); - // other axis might be not scrollable - } - if (!canBeScrolledInMainDirection) { - return false; - } - if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) { - activeAxis.current = currentAxis; - } - if (!currentAxis) { - return true; - } - var cancelingAxis = activeAxis.current || currentAxis; - return (0, _handleScroll.handleScroll)(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true); - }, []); - var shouldPrevent = React.useCallback(function (_event) { - var event = _event; - if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) { - // not the last active - return; - } - var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event); - var sourceEvent = shouldPreventQueue.current.filter(function (e) { - return e.name === event.type && e.target === event.target && deltaCompare(e.delta, delta); - })[0]; - // self event, and should be canceled - if (sourceEvent && sourceEvent.should) { - if (event.cancelable) { - event.preventDefault(); - } - return; - } - // outside or shard event - if (!sourceEvent) { - var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function (node) { - return node.contains(event.target); - }); - var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; - if (shouldStop) { - if (event.cancelable) { - event.preventDefault(); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.RemoveScrollSideCar = RemoveScrollSideCar; + exports.getTouchXY = exports.getDeltaXY = void 0; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _reactRemoveScrollBar = __webpack_require__( + /*! react-remove-scroll-bar */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js" + ); + var _reactStyleSingleton = __webpack_require__( + /*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js" + ); + var _aggresiveCapture = __webpack_require__( + /*! ./aggresiveCapture */ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js" + ); + var _handleScroll = __webpack_require__( + /*! ./handleScroll */ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js" + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; } - } - } - }, []); - var shouldCancel = React.useCallback(function (name, delta, target, should) { - var event = { - name: name, - delta: delta, - target: target, - should: should - }; - shouldPreventQueue.current.push(event); - setTimeout(function () { - shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { - return e !== event; - }); - }, 1); - }, []); - var scrollTouchStart = React.useCallback(function (event) { - touchStartRef.current = getTouchXY(event); - activeAxis.current = undefined; - }, []); - var scrollWheel = React.useCallback(function (event) { - shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); - }, []); - var scrollTouchMove = React.useCallback(function (event) { - shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); - }, []); - React.useEffect(function () { - lockStack.push(Style); - props.setCallbacks({ - onScrollCapture: scrollWheel, - onWheelCapture: scrollWheel, - onTouchMoveCapture: scrollTouchMove - }); - document.addEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); - document.addEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); - document.addEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); - return function () { - lockStack = lockStack.filter(function (inst) { - return inst !== Style; - }); - document.removeEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); - document.removeEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); - document.removeEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); - }; - }, []); - var removeScrollBar = props.removeScrollBar, - inert = props.inert; - return /*#__PURE__*/React.createElement(React.Fragment, null, inert ? /*#__PURE__*/React.createElement(Style, { - styles: generateStyle(id) - }) : null, removeScrollBar ? /*#__PURE__*/React.createElement(_reactRemoveScrollBar.RemoveScrollBar, { - gapMode: "margin" - }) : null); -} - -/***/ }), - -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js": -/*!*******************************************************************!*\ + var getTouchXY = function (event) { + return "changedTouches" in event + ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] + : [0, 0]; + }; + exports.getTouchXY = getTouchXY; + var getDeltaXY = function (event) { + return [event.deltaX, event.deltaY]; + }; + exports.getDeltaXY = getDeltaXY; + var extractRef = function (ref) { + return ref && "current" in ref ? ref.current : ref; + }; + var deltaCompare = function (x, y) { + return x[0] === y[0] && x[1] === y[1]; + }; + var generateStyle = function (id) { + return "\n .block-interactivity-" + .concat(id, " {pointer-events: none;}\n .allow-interactivity-") + .concat(id, " {pointer-events: all;}\n"); + }; + var idCounter = 0; + var lockStack = []; + function RemoveScrollSideCar(props) { + var shouldPreventQueue = React.useRef([]); + var touchStartRef = React.useRef([0, 0]); + var activeAxis = React.useRef(); + var id = React.useState(idCounter++)[0]; + var Style = React.useState(function () { + return (0, _reactStyleSingleton.styleSingleton)(); + })[0]; + var lastProps = React.useRef(props); + React.useEffect( + function () { + lastProps.current = props; + }, + [props] + ); + React.useEffect( + function () { + if (props.inert) { + document.body.classList.add("block-interactivity-".concat(id)); + var allow_1 = (0, _tslib.__spreadArray)( + [props.lockRef.current], + (props.shards || []).map(extractRef), + true + ).filter(Boolean); + allow_1.forEach(function (el) { + return el.classList.add("allow-interactivity-".concat(id)); + }); + return function () { + document.body.classList.remove( + "block-interactivity-".concat(id) + ); + allow_1.forEach(function (el) { + return el.classList.remove( + "allow-interactivity-".concat(id) + ); + }); + }; + } + return; + }, + [props.inert, props.lockRef.current, props.shards] + ); + var shouldCancelEvent = React.useCallback(function (event, parent) { + if ("touches" in event && event.touches.length === 2) { + return !lastProps.current.allowPinchZoom; + } + var touch = getTouchXY(event); + var touchStart = touchStartRef.current; + var deltaX = + "deltaX" in event ? event.deltaX : touchStart[0] - touch[0]; + var deltaY = + "deltaY" in event ? event.deltaY : touchStart[1] - touch[1]; + var currentAxis; + var target = event.target; + var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v"; + // allow horizontal touch move on Range inputs. They will not cause any scroll + if ( + "touches" in event && + moveDirection === "h" && + target.type === "range" + ) { + return false; + } + var canBeScrolledInMainDirection = (0, + _handleScroll.locationCouldBeScrolled)(moveDirection, target); + if (!canBeScrolledInMainDirection) { + return true; + } + if (canBeScrolledInMainDirection) { + currentAxis = moveDirection; + } else { + currentAxis = moveDirection === "v" ? "h" : "v"; + canBeScrolledInMainDirection = (0, + _handleScroll.locationCouldBeScrolled)(moveDirection, target); + // other axis might be not scrollable + } + if (!canBeScrolledInMainDirection) { + return false; + } + if ( + !activeAxis.current && + "changedTouches" in event && + (deltaX || deltaY) + ) { + activeAxis.current = currentAxis; + } + if (!currentAxis) { + return true; + } + var cancelingAxis = activeAxis.current || currentAxis; + return (0, + _handleScroll.handleScroll)(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true); + }, []); + var shouldPrevent = React.useCallback(function (_event) { + var event = _event; + if ( + !lockStack.length || + lockStack[lockStack.length - 1] !== Style + ) { + // not the last active + return; + } + var delta = + "deltaY" in event ? getDeltaXY(event) : getTouchXY(event); + var sourceEvent = shouldPreventQueue.current.filter(function (e) { + return ( + e.name === event.type && + e.target === event.target && + deltaCompare(e.delta, delta) + ); + })[0]; + // self event, and should be canceled + if (sourceEvent && sourceEvent.should) { + if (event.cancelable) { + event.preventDefault(); + } + return; + } + // outside or shard event + if (!sourceEvent) { + var shardNodes = (lastProps.current.shards || []) + .map(extractRef) + .filter(Boolean) + .filter(function (node) { + return node.contains(event.target); + }); + var shouldStop = + shardNodes.length > 0 + ? shouldCancelEvent(event, shardNodes[0]) + : !lastProps.current.noIsolation; + if (shouldStop) { + if (event.cancelable) { + event.preventDefault(); + } + } + } + }, []); + var shouldCancel = React.useCallback(function ( + name, + delta, + target, + should + ) { + var event = { + name: name, + delta: delta, + target: target, + should: should, + }; + shouldPreventQueue.current.push(event); + setTimeout(function () { + shouldPreventQueue.current = shouldPreventQueue.current.filter( + function (e) { + return e !== event; + } + ); + }, 1); + }, + []); + var scrollTouchStart = React.useCallback(function (event) { + touchStartRef.current = getTouchXY(event); + activeAxis.current = undefined; + }, []); + var scrollWheel = React.useCallback(function (event) { + shouldCancel( + event.type, + getDeltaXY(event), + event.target, + shouldCancelEvent(event, props.lockRef.current) + ); + }, []); + var scrollTouchMove = React.useCallback(function (event) { + shouldCancel( + event.type, + getTouchXY(event), + event.target, + shouldCancelEvent(event, props.lockRef.current) + ); + }, []); + React.useEffect(function () { + lockStack.push(Style); + props.setCallbacks({ + onScrollCapture: scrollWheel, + onWheelCapture: scrollWheel, + onTouchMoveCapture: scrollTouchMove, + }); + document.addEventListener( + "wheel", + shouldPrevent, + _aggresiveCapture.nonPassive + ); + document.addEventListener( + "touchmove", + shouldPrevent, + _aggresiveCapture.nonPassive + ); + document.addEventListener( + "touchstart", + scrollTouchStart, + _aggresiveCapture.nonPassive + ); + return function () { + lockStack = lockStack.filter(function (inst) { + return inst !== Style; + }); + document.removeEventListener( + "wheel", + shouldPrevent, + _aggresiveCapture.nonPassive + ); + document.removeEventListener( + "touchmove", + shouldPrevent, + _aggresiveCapture.nonPassive + ); + document.removeEventListener( + "touchstart", + scrollTouchStart, + _aggresiveCapture.nonPassive + ); + }; + }, []); + var removeScrollBar = props.removeScrollBar, + inert = props.inert; + return /*#__PURE__*/ React.createElement( + React.Fragment, + null, + inert + ? /*#__PURE__*/ React.createElement(Style, { + styles: generateStyle(id), + }) + : null, + removeScrollBar + ? /*#__PURE__*/ React.createElement( + _reactRemoveScrollBar.RemoveScrollBar, + { + gapMode: "margin", + } + ) + : null + ); + } + + /***/ + }, + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js": + /*!*******************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/UI.js ***! \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.RemoveScroll = void 0; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _constants = __webpack_require__(/*! react-remove-scroll-bar/constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); -var _useCallbackRef = __webpack_require__(/*! use-callback-ref */ "../../../node_modules/use-callback-ref/dist/es2015/index.js"); -var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -var nothing = function () { - return; -}; -/** - * Removes scrollbar from the page and contain the scroll within the Lock - */ -var RemoveScroll = exports.RemoveScroll = /*#__PURE__*/React.forwardRef(function (props, parentRef) { - var ref = React.useRef(null); - var _a = React.useState({ - onScrollCapture: nothing, - onWheelCapture: nothing, - onTouchMoveCapture: nothing - }), - callbacks = _a[0], - setCallbacks = _a[1]; - var forwardProps = props.forwardProps, - children = props.children, - className = props.className, - removeScrollBar = props.removeScrollBar, - enabled = props.enabled, - shards = props.shards, - sideCar = props.sideCar, - noIsolation = props.noIsolation, - inert = props.inert, - allowPinchZoom = props.allowPinchZoom, - _b = props.as, - Container = _b === void 0 ? 'div' : _b, - rest = (0, _tslib.__rest)(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]); - var SideCar = sideCar; - var containerRef = (0, _useCallbackRef.useMergeRefs)([ref, parentRef]); - var containerProps = (0, _tslib.__assign)((0, _tslib.__assign)({}, rest), callbacks); - return /*#__PURE__*/React.createElement(React.Fragment, null, enabled && ( /*#__PURE__*/React.createElement(SideCar, { - sideCar: _medium.effectCar, - removeScrollBar: removeScrollBar, - shards: shards, - noIsolation: noIsolation, - inert: inert, - setCallbacks: setCallbacks, - allowPinchZoom: !!allowPinchZoom, - lockRef: ref - })), forwardProps ? ( /*#__PURE__*/React.cloneElement(React.Children.only(children), (0, _tslib.__assign)((0, _tslib.__assign)({}, containerProps), { - ref: containerRef - }))) : ( /*#__PURE__*/React.createElement(Container, (0, _tslib.__assign)({}, containerProps, { - className: className, - ref: containerRef - }), children))); -}); -RemoveScroll.defaultProps = { - enabled: true, - removeScrollBar: true, - inert: false -}; -RemoveScroll.classNames = { - fullWidth: _constants.fullWidthClassName, - zeroRight: _constants.zeroRightClassName -}; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.RemoveScroll = void 0; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _constants = __webpack_require__( + /*! react-remove-scroll-bar/constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js" + ); + var _useCallbackRef = __webpack_require__( + /*! use-callback-ref */ "../../../node_modules/use-callback-ref/dist/es2015/index.js" + ); + var _medium = __webpack_require__( + /*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js" + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + var nothing = function () { + return; + }; + /** + * Removes scrollbar from the page and contain the scroll within the Lock + */ + var RemoveScroll = (exports.RemoveScroll = + /*#__PURE__*/ React.forwardRef(function (props, parentRef) { + var ref = React.useRef(null); + var _a = React.useState({ + onScrollCapture: nothing, + onWheelCapture: nothing, + onTouchMoveCapture: nothing, + }), + callbacks = _a[0], + setCallbacks = _a[1]; + var forwardProps = props.forwardProps, + children = props.children, + className = props.className, + removeScrollBar = props.removeScrollBar, + enabled = props.enabled, + shards = props.shards, + sideCar = props.sideCar, + noIsolation = props.noIsolation, + inert = props.inert, + allowPinchZoom = props.allowPinchZoom, + _b = props.as, + Container = _b === void 0 ? "div" : _b, + rest = (0, _tslib.__rest)(props, [ + "forwardProps", + "children", + "className", + "removeScrollBar", + "enabled", + "shards", + "sideCar", + "noIsolation", + "inert", + "allowPinchZoom", + "as", + ]); + var SideCar = sideCar; + var containerRef = (0, _useCallbackRef.useMergeRefs)([ + ref, + parentRef, + ]); + var containerProps = (0, _tslib.__assign)( + (0, _tslib.__assign)({}, rest), + callbacks + ); + return /*#__PURE__*/ React.createElement( + React.Fragment, + null, + enabled && + /*#__PURE__*/ React.createElement(SideCar, { + sideCar: _medium.effectCar, + removeScrollBar: removeScrollBar, + shards: shards, + noIsolation: noIsolation, + inert: inert, + setCallbacks: setCallbacks, + allowPinchZoom: !!allowPinchZoom, + lockRef: ref, + }), + forwardProps + ? /*#__PURE__*/ React.cloneElement( + React.Children.only(children), + (0, _tslib.__assign)( + (0, _tslib.__assign)({}, containerProps), + { + ref: containerRef, + } + ) + ) + : /*#__PURE__*/ React.createElement( + Container, + (0, _tslib.__assign)({}, containerProps, { + className: className, + ref: containerRef, + }), + children + ) + ); + })); + RemoveScroll.defaultProps = { + enabled: true, + removeScrollBar: true, + inert: false, + }; + RemoveScroll.classNames = { + fullWidth: _constants.fullWidthClassName, + zeroRight: _constants.zeroRightClassName, + }; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js": -/*!*********************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js": + /*!*********************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js ***! \*********************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.nonPassive = void 0; -var passiveSupported = false; -if (typeof window !== 'undefined') { - try { - var options = Object.defineProperty({}, 'passive', { - get: function () { - passiveSupported = true; - return true; - } - }); - // @ts-ignore - window.addEventListener('test', options, options); - // @ts-ignore - window.removeEventListener('test', options, options); - } catch (err) { - passiveSupported = false; - } -} -var nonPassive = exports.nonPassive = passiveSupported ? { - passive: false -} : false; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.nonPassive = void 0; + var passiveSupported = false; + if (typeof window !== "undefined") { + try { + var options = Object.defineProperty({}, "passive", { + get: function () { + passiveSupported = true; + return true; + }, + }); + // @ts-ignore + window.addEventListener("test", options, options); + // @ts-ignore + window.removeEventListener("test", options, options); + } catch (err) { + passiveSupported = false; + } + } + var nonPassive = (exports.nonPassive = passiveSupported + ? { + passive: false, + } + : false); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js": -/*!*****************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js": + /*!*****************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js ***! \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.locationCouldBeScrolled = exports.handleScroll = void 0; -var alwaysContainsScroll = function (node) { - // textarea will always _contain_ scroll inside self. It only can be hidden - return node.tagName === 'TEXTAREA'; -}; -var elementCanBeScrolled = function (node, overflow) { - var styles = window.getComputedStyle(node); - return ( - // not-not-scrollable - styles[overflow] !== 'hidden' && - // contains scroll inside self - !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible') - ); -}; -var elementCouldBeVScrolled = function (node) { - return elementCanBeScrolled(node, 'overflowY'); -}; -var elementCouldBeHScrolled = function (node) { - return elementCanBeScrolled(node, 'overflowX'); -}; -var locationCouldBeScrolled = function (axis, node) { - var current = node; - do { - // Skip over shadow root - if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) { - current = current.host; - } - var isScrollable = elementCouldBeScrolled(axis, current); - if (isScrollable) { - var _a = getScrollVariables(axis, current), - s = _a[1], - d = _a[2]; - if (s > d) { - return true; - } - } - current = current.parentNode; - } while (current && current !== document.body); - return false; -}; -exports.locationCouldBeScrolled = locationCouldBeScrolled; -var getVScrollVariables = function (_a) { - var scrollTop = _a.scrollTop, - scrollHeight = _a.scrollHeight, - clientHeight = _a.clientHeight; - return [scrollTop, scrollHeight, clientHeight]; -}; -var getHScrollVariables = function (_a) { - var scrollLeft = _a.scrollLeft, - scrollWidth = _a.scrollWidth, - clientWidth = _a.clientWidth; - return [scrollLeft, scrollWidth, clientWidth]; -}; -var elementCouldBeScrolled = function (axis, node) { - return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); -}; -var getScrollVariables = function (axis, node) { - return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node); -}; -var getDirectionFactor = function (axis, direction) { - /** - * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position, - * and then increasingly negative as you scroll towards the end of the content. - * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft - */ - return axis === 'h' && direction === 'rtl' ? -1 : 1; -}; -var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) { - var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); - var delta = directionFactor * sourceDelta; - // find scrollable target - var target = event.target; - var targetInLock = endTarget.contains(target); - var shouldCancelScroll = false; - var isDeltaPositive = delta > 0; - var availableScroll = 0; - var availableScrollTop = 0; - do { - var _a = getScrollVariables(axis, target), - position = _a[0], - scroll_1 = _a[1], - capacity = _a[2]; - var elementScroll = scroll_1 - capacity - directionFactor * position; - if (position || elementScroll) { - if (elementCouldBeScrolled(axis, target)) { - availableScroll += elementScroll; - availableScrollTop += position; - } - } - target = target.parentNode; - } while ( - // portaled content - !targetInLock && target !== document.body || - // self content - targetInLock && (endTarget.contains(target) || endTarget === target)); - if (isDeltaPositive && (noOverscroll && availableScroll === 0 || !noOverscroll && delta > availableScroll)) { - shouldCancelScroll = true; - } else if (!isDeltaPositive && (noOverscroll && availableScrollTop === 0 || !noOverscroll && -delta > availableScrollTop)) { - shouldCancelScroll = true; - } - return shouldCancelScroll; -}; -exports.handleScroll = handleScroll; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.locationCouldBeScrolled = exports.handleScroll = void 0; + var alwaysContainsScroll = function (node) { + // textarea will always _contain_ scroll inside self. It only can be hidden + return node.tagName === "TEXTAREA"; + }; + var elementCanBeScrolled = function (node, overflow) { + var styles = window.getComputedStyle(node); + return ( + // not-not-scrollable + styles[overflow] !== "hidden" && + // contains scroll inside self + !( + styles.overflowY === styles.overflowX && + !alwaysContainsScroll(node) && + styles[overflow] === "visible" + ) + ); + }; + var elementCouldBeVScrolled = function (node) { + return elementCanBeScrolled(node, "overflowY"); + }; + var elementCouldBeHScrolled = function (node) { + return elementCanBeScrolled(node, "overflowX"); + }; + var locationCouldBeScrolled = function (axis, node) { + var current = node; + do { + // Skip over shadow root + if ( + typeof ShadowRoot !== "undefined" && + current instanceof ShadowRoot + ) { + current = current.host; + } + var isScrollable = elementCouldBeScrolled(axis, current); + if (isScrollable) { + var _a = getScrollVariables(axis, current), + s = _a[1], + d = _a[2]; + if (s > d) { + return true; + } + } + current = current.parentNode; + } while (current && current !== document.body); + return false; + }; + exports.locationCouldBeScrolled = locationCouldBeScrolled; + var getVScrollVariables = function (_a) { + var scrollTop = _a.scrollTop, + scrollHeight = _a.scrollHeight, + clientHeight = _a.clientHeight; + return [scrollTop, scrollHeight, clientHeight]; + }; + var getHScrollVariables = function (_a) { + var scrollLeft = _a.scrollLeft, + scrollWidth = _a.scrollWidth, + clientWidth = _a.clientWidth; + return [scrollLeft, scrollWidth, clientWidth]; + }; + var elementCouldBeScrolled = function (axis, node) { + return axis === "v" + ? elementCouldBeVScrolled(node) + : elementCouldBeHScrolled(node); + }; + var getScrollVariables = function (axis, node) { + return axis === "v" + ? getVScrollVariables(node) + : getHScrollVariables(node); + }; + var getDirectionFactor = function (axis, direction) { + /** + * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position, + * and then increasingly negative as you scroll towards the end of the content. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft + */ + return axis === "h" && direction === "rtl" ? -1 : 1; + }; + var handleScroll = function ( + axis, + endTarget, + event, + sourceDelta, + noOverscroll + ) { + var directionFactor = getDirectionFactor( + axis, + window.getComputedStyle(endTarget).direction + ); + var delta = directionFactor * sourceDelta; + // find scrollable target + var target = event.target; + var targetInLock = endTarget.contains(target); + var shouldCancelScroll = false; + var isDeltaPositive = delta > 0; + var availableScroll = 0; + var availableScrollTop = 0; + do { + var _a = getScrollVariables(axis, target), + position = _a[0], + scroll_1 = _a[1], + capacity = _a[2]; + var elementScroll = + scroll_1 - capacity - directionFactor * position; + if (position || elementScroll) { + if (elementCouldBeScrolled(axis, target)) { + availableScroll += elementScroll; + availableScrollTop += position; + } + } + target = target.parentNode; + } while ( + // portaled content + (!targetInLock && target !== document.body) || + // self content + (targetInLock && + (endTarget.contains(target) || endTarget === target)) + ); + if ( + isDeltaPositive && + ((noOverscroll && availableScroll === 0) || + (!noOverscroll && delta > availableScroll)) + ) { + shouldCancelScroll = true; + } else if ( + !isDeltaPositive && + ((noOverscroll && availableScrollTop === 0) || + (!noOverscroll && -delta > availableScrollTop)) + ) { + shouldCancelScroll = true; + } + return shouldCancelScroll; + }; + exports.handleScroll = handleScroll; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/index.js": -/*!**********************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/index.js": + /*!**********************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/index.js ***! \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "RemoveScroll", ({ - enumerable: true, - get: function () { - return _Combination.default; - } -})); -var _Combination = _interopRequireDefault(__webpack_require__(/*! ./Combination */ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "RemoveScroll", { + enumerable: true, + get: function () { + return _Combination.default; + }, + }); + var _Combination = _interopRequireDefault( + __webpack_require__( + /*! ./Combination */ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js" + ) + ); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js": -/*!***********************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js": + /*!***********************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/medium.js ***! \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.effectCar = void 0; -var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); -var effectCar = exports.effectCar = (0, _useSidecar.createSidecarMedium)(); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.effectCar = void 0; + var _useSidecar = __webpack_require__( + /*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js" + ); + var effectCar = (exports.effectCar = (0, + _useSidecar.createSidecarMedium)()); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js": -/*!************************************************************************!*\ + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js": + /*!************************************************************************!*\ !*** ../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js ***! \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); -var _SideEffect = __webpack_require__(/*! ./SideEffect */ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js"); -var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); -var _default = exports["default"] = (0, _useSidecar.exportSidecar)(_medium.effectCar, _SideEffect.RemoveScrollSideCar); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = void 0; + var _useSidecar = __webpack_require__( + /*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js" + ); + var _SideEffect = __webpack_require__( + /*! ./SideEffect */ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js" + ); + var _medium = __webpack_require__( + /*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js" + ); + var _default = (exports["default"] = (0, _useSidecar.exportSidecar)( + _medium.effectCar, + _SideEffect.RemoveScrollSideCar + )); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-style-singleton/dist/es2015/component.js": -/*!****************************************************************************!*\ + /***/ "../../../node_modules/react-style-singleton/dist/es2015/component.js": + /*!****************************************************************************!*\ !*** ../../../node_modules/react-style-singleton/dist/es2015/component.js ***! \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.styleSingleton = void 0; -var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); -/** - * create a Component to add styles on demand - * - styles are added when first instance is mounted - * - styles are removed when the last instance is unmounted - * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior - */ -var styleSingleton = function () { - var useStyle = (0, _hook.styleHookSingleton)(); - var Sheet = function (_a) { - var styles = _a.styles, - dynamic = _a.dynamic; - useStyle(styles, dynamic); - return null; - }; - return Sheet; -}; -exports.styleSingleton = styleSingleton; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.styleSingleton = void 0; + var _hook = __webpack_require__( + /*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js" + ); + /** + * create a Component to add styles on demand + * - styles are added when first instance is mounted + * - styles are removed when the last instance is unmounted + * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior + */ + var styleSingleton = function () { + var useStyle = (0, _hook.styleHookSingleton)(); + var Sheet = function (_a) { + var styles = _a.styles, + dynamic = _a.dynamic; + useStyle(styles, dynamic); + return null; + }; + return Sheet; + }; + exports.styleSingleton = styleSingleton; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-style-singleton/dist/es2015/hook.js": -/*!***********************************************************************!*\ + /***/ "../../../node_modules/react-style-singleton/dist/es2015/hook.js": + /*!***********************************************************************!*\ !*** ../../../node_modules/react-style-singleton/dist/es2015/hook.js ***! \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.styleHookSingleton = void 0; -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -/** - * creates a hook to control style singleton - * @see {@link styleSingleton} for a safer component version - * @example - * ```tsx - * const useStyle = styleHookSingleton(); - * /// - * useStyle('body { overflow: hidden}'); - */ -var styleHookSingleton = function () { - var sheet = (0, _singleton.stylesheetSingleton)(); - return function (styles, isDynamic) { - React.useEffect(function () { - sheet.add(styles); - return function () { - sheet.remove(); - }; - }, [styles && isDynamic]); - }; -}; -exports.styleHookSingleton = styleHookSingleton; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.styleHookSingleton = void 0; + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _singleton = __webpack_require__( + /*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js" + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + /** + * creates a hook to control style singleton + * @see {@link styleSingleton} for a safer component version + * @example + * ```tsx + * const useStyle = styleHookSingleton(); + * /// + * useStyle('body { overflow: hidden}'); + */ + var styleHookSingleton = function () { + var sheet = (0, _singleton.stylesheetSingleton)(); + return function (styles, isDynamic) { + React.useEffect( + function () { + sheet.add(styles); + return function () { + sheet.remove(); + }; + }, + [styles && isDynamic] + ); + }; + }; + exports.styleHookSingleton = styleHookSingleton; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-style-singleton/dist/es2015/index.js": -/*!************************************************************************!*\ + /***/ "../../../node_modules/react-style-singleton/dist/es2015/index.js": + /*!************************************************************************!*\ !*** ../../../node_modules/react-style-singleton/dist/es2015/index.js ***! \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "styleHookSingleton", ({ - enumerable: true, - get: function () { - return _hook.styleHookSingleton; - } -})); -Object.defineProperty(exports, "styleSingleton", ({ - enumerable: true, - get: function () { - return _component.styleSingleton; - } -})); -Object.defineProperty(exports, "stylesheetSingleton", ({ - enumerable: true, - get: function () { - return _singleton.stylesheetSingleton; - } -})); -var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-style-singleton/dist/es2015/component.js"); -var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); -var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "styleHookSingleton", { + enumerable: true, + get: function () { + return _hook.styleHookSingleton; + }, + }); + Object.defineProperty(exports, "styleSingleton", { + enumerable: true, + get: function () { + return _component.styleSingleton; + }, + }); + Object.defineProperty(exports, "stylesheetSingleton", { + enumerable: true, + get: function () { + return _singleton.stylesheetSingleton; + }, + }); + var _component = __webpack_require__( + /*! ./component */ "../../../node_modules/react-style-singleton/dist/es2015/component.js" + ); + var _singleton = __webpack_require__( + /*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js" + ); + var _hook = __webpack_require__( + /*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js" + ); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js": -/*!****************************************************************************!*\ + /***/ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js": + /*!****************************************************************************!*\ !*** ../../../node_modules/react-style-singleton/dist/es2015/singleton.js ***! \****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.stylesheetSingleton = void 0; -var _getNonce = __webpack_require__(/*! get-nonce */ "../../../node_modules/get-nonce/dist/es2015/index.js"); -function makeStyleTag() { - if (!document) return null; - var tag = document.createElement('style'); - tag.type = 'text/css'; - var nonce = (0, _getNonce.getNonce)(); - if (nonce) { - tag.setAttribute('nonce', nonce); - } - return tag; -} -function injectStyles(tag, css) { - // @ts-ignore - if (tag.styleSheet) { - // @ts-ignore - tag.styleSheet.cssText = css; - } else { - tag.appendChild(document.createTextNode(css)); - } -} -function insertStyleTag(tag) { - var head = document.head || document.getElementsByTagName('head')[0]; - head.appendChild(tag); -} -var stylesheetSingleton = function () { - var counter = 0; - var stylesheet = null; - return { - add: function (style) { - if (counter == 0) { - if (stylesheet = makeStyleTag()) { - injectStyles(stylesheet, style); - insertStyleTag(stylesheet); + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.stylesheetSingleton = void 0; + var _getNonce = __webpack_require__( + /*! get-nonce */ "../../../node_modules/get-nonce/dist/es2015/index.js" + ); + function makeStyleTag() { + if (!document) return null; + var tag = document.createElement("style"); + tag.type = "text/css"; + var nonce = (0, _getNonce.getNonce)(); + if (nonce) { + tag.setAttribute("nonce", nonce); + } + return tag; + } + function injectStyles(tag, css) { + // @ts-ignore + if (tag.styleSheet) { + // @ts-ignore + tag.styleSheet.cssText = css; + } else { + tag.appendChild(document.createTextNode(css)); + } } - } - counter++; - }, - remove: function () { - counter--; - if (!counter && stylesheet) { - stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); - stylesheet = null; - } - } - }; -}; -exports.stylesheetSingleton = stylesheetSingleton; + function insertStyleTag(tag) { + var head = document.head || document.getElementsByTagName("head")[0]; + head.appendChild(tag); + } + var stylesheetSingleton = function () { + var counter = 0; + var stylesheet = null; + return { + add: function (style) { + if (counter == 0) { + if ((stylesheet = makeStyleTag())) { + injectStyles(stylesheet, style); + insertStyleTag(stylesheet); + } + } + counter++; + }, + remove: function () { + counter--; + if (!counter && stylesheet) { + stylesheet.parentNode && + stylesheet.parentNode.removeChild(stylesheet); + stylesheet = null; + } + }, + }; + }; + exports.stylesheetSingleton = stylesheetSingleton; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/react/cjs/react-jsx-runtime.development.js": -/*!************************************************************************!*\ + /***/ "../../../node_modules/react/cjs/react-jsx-runtime.development.js": + /*!************************************************************************!*\ !*** ../../../node_modules/react/cjs/react-jsx-runtime.development.js ***! \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -/** - * @license React - * react-jsx-runtime.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - - -if (true) { - (function () { - 'use strict'; - - var React = __webpack_require__(/*! react */ "react"); - - // ATTENTION - // When adding new symbols to this file, - // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' - // The Symbol used to tag the ReactElement-like types. - var REACT_ELEMENT_TYPE = Symbol.for('react.element'); - var REACT_PORTAL_TYPE = Symbol.for('react.portal'); - var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); - var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); - var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); - var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); - var REACT_CONTEXT_TYPE = Symbol.for('react.context'); - var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); - var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); - var REACT_MEMO_TYPE = Symbol.for('react.memo'); - var REACT_LAZY_TYPE = Symbol.for('react.lazy'); - var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = '@@iterator'; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - return null; - } - var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - function error(format) { - { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning('error', format, args); - } - } - } - function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - if (stack !== '') { - format += '%s'; - args = args.concat([stack]); - } // eslint-disable-next-line react-internal/safe-string-coercion - - var argsWithFormat = args.map(function (item) { - return String(item); - }); // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + /** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ - // ----------------------------------------------------------------------------- + if (true) { + (function () { + "use strict"; + + var React = __webpack_require__(/*! react */ "react"); + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = + (MAYBE_ITERATOR_SYMBOL && + maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var ReactSharedInternals = + React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function error(format) { + { + { + for ( + var _len2 = arguments.length, + args = new Array(_len2 > 1 ? _len2 - 1 : 0), + _key2 = 1; + _key2 < _len2; + _key2++ + ) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = + ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift("Warning: " + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call( + console[level], + console, + argsWithFormat + ); + } + } - var enableScopeAPI = false; // Experimental Create Event Handle API. - var enableCacheElement = false; - var enableTransitionTracing = false; // No known bugs, but needs performance testing + // ----------------------------------------------------------------------------- - var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber - // stuff. Intended to enable React core members to more easily debug scheduling - // issues in DEV builds. + var enableScopeAPI = false; // Experimental Create Event Handle API. + var enableCacheElement = false; + var enableTransitionTracing = false; // No known bugs, but needs performance testing - var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + // stuff. Intended to enable React core members to more easily debug scheduling + // issues in DEV builds. - var REACT_MODULE_REFERENCE; - { - REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); - } - function isValidElementType(type) { - if (typeof type === 'string' || typeof type === 'function') { - return true; - } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + var enableDebugTracing = false; // Track which Fiber(s) schedule render work. - if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { - return true; - } - if (typeof type === 'object' && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || - // This needs to include all possible module reference object - // types supported by any Flight configuration anywhere since - // we don't know which Flight build this will end up being used - // with. - type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { - return true; - } - } - return false; - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ''; - return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; - } // Keep in sync with react-reconciler/getComponentNameFromFiber - - function getContextName(type) { - return type.displayName || 'Context'; - } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - - function getComponentNameFromType(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null; - } - { - if (typeof type.tag === 'number') { - error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); - } - } - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - if (typeof type === 'string') { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment'; - case REACT_PORTAL_TYPE: - return 'Portal'; - case REACT_PROFILER_TYPE: - return 'Profiler'; - case REACT_STRICT_MODE_TYPE: - return 'StrictMode'; - case REACT_SUSPENSE_TYPE: - return 'Suspense'; - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList'; - } - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + '.Consumer'; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + '.Provider'; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef'); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || 'Memo'; - case REACT_LAZY_TYPE: + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + if ( + type === REACT_FRAGMENT_TYPE || + type === REACT_PROFILER_TYPE || + enableDebugTracing || + type === REACT_STRICT_MODE_TYPE || + type === REACT_SUSPENSE_TYPE || + type === REACT_SUSPENSE_LIST_TYPE || + enableLegacyHidden || + type === REACT_OFFSCREEN_TYPE || + enableScopeAPI || + enableCacheElement || + enableTransitionTracing + ) { + return true; + } + if (typeof type === "object" && type !== null) { + if ( + type.$$typeof === REACT_LAZY_TYPE || + type.$$typeof === REACT_MEMO_TYPE || + type.$$typeof === REACT_PROVIDER_TYPE || + type.$$typeof === REACT_CONTEXT_TYPE || + type.$$typeof === REACT_FORWARD_REF_TYPE || + // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || + type.getModuleId !== undefined + ) { + return true; + } + } + return false; + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" + ? wrapperName + "(" + functionName + ")" + : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber + + function getContextName(type) { + return type.displayName || "Context"; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + { + if (typeof type.tag === "number") { + error( + "Received an unexpected object in getComponentNameFromType(). " + + "This is likely a bug in React. Please file an issue." + ); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + return null; + } + var assign = Object.assign; + + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() {} + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true, + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props, + }); + /* eslint-enable react-internal/no-production-logging */ + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true, + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog, + }), + info: assign({}, props, { + value: prevInfo, + }), + warn: assign({}, props, { + value: prevWarn, + }), + error: assign({}, props, { + value: prevError, + }), + group: assign({}, props, { + value: prevGroup, + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed, + }), + groupEnd: assign({}, props, { + value: prevGroupEnd, + }), + }); + /* eslint-enable react-internal/no-production-logging */ + } + if (disabledDepth < 0) { + error( + "disabledDepth fell below zero. " + + "This is a bug in React. Please file an issue." + ); + } + } + } + var ReactCurrentDispatcher = + ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = (match && match[1]) || ""; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = + typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== undefined) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + Object.defineProperty(Fake.prototype, "props", { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + }, + }); + if (typeof Reflect === "object" && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === "string") { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while ( + s >= 1 && + c >= 0 && + sampleLines[s] !== controlLines[c] + ) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = + "\n" + sampleLines[s].replace(" at new ", " at "); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + if ( + fn.displayName && + _frame.includes("") + ) { + _frame = _frame.replace( + "", + fn.displayName + ); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name + ? describeBuiltInComponentFrame(name) + : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV( + type, + source, + ownerFn + ) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame( + type, + shouldConstruct(type) + ); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV( + type.type, + source, + ownerFn + ); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV( + init(payload), + source, + ownerFn + ); + } catch (x) {} + } + } + } + return ""; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = + ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV( + element.type, + element._source, + owner ? owner.type : null + ); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } + } + function checkPropTypes( + typeSpecs, + values, + location, + componentName, + element + ) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== "function") { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error( + (componentName || "React class") + + ": " + + location + + " type `" + + typeSpecName + + "` is invalid; " + + "it must be a function, usually from the `prop-types` package, but received `" + + typeof typeSpecs[typeSpecName] + + "`." + + "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." + ); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName]( + values, + typeSpecName, + componentName, + location, + null, + "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED" + ); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error( + "%s: type specification of %s" + + " `%s` is invalid; the type checker " + + "function must return `null` or an `Error` but returned a %s. " + + "You may have forgotten to pass an argument to the type checker " + + "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + + "shape all require an argument).", + componentName || "React class", + location, + typeSpecName, + typeof error$1 + ); + setCurrentlyValidatingElement(null); + } + if ( + error$1 instanceof Error && + !(error$1.message in loggedTypeFailures) + ) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + + function isArray(a) { + return isArrayImpl(a); + } + + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = + typeof Symbol === "function" && Symbol.toStringTag; + var type = + (hasToStringTag && value[Symbol.toStringTag]) || + value.constructor.name || + "Object"; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. + + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return "" + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error( + "The provided key is an unsupported type %s." + + " This value must be coerced to a string before before using it here.", + typeName(value) + ); + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true, + }; + var specialPropKeyWarningShown; + var specialPropRefWarningShown; + var didWarnAboutStringRefs; { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor( + config, + "ref" + ).get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== undefined; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor( + config, + "key" + ).get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== undefined; + } + function warnIfStringRefCannotBeAutoConverted(config, self) { + { + if ( + typeof config.ref === "string" && + ReactCurrentOwner.current && + self && + ReactCurrentOwner.current.stateNode !== self + ) { + var componentName = getComponentNameFromType( + ReactCurrentOwner.current.type + ); + if (!didWarnAboutStringRefs[componentName]) { + error( + 'Component "%s" contains the string ref "%s". ' + + "Support for string refs will be removed in a future major release. " + + "This case cannot be automatically converted to an arrow function. " + + "We ask you to manually fix this case by using useRef() or createRef() instead. " + + "Learn more about using refs safely here: " + + "https://reactjs.org/link/strict-mode-string-ref", + getComponentNameFromType(ReactCurrentOwner.current.type), + config.ref + ); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function () { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error( + "%s: `key` is not a prop. Trying to access it will result " + + "in `undefined` being returned. If you need to access the same " + + "value within the child component, you should pass it as a different " + + "prop. (https://reactjs.org/link/special-props)", + displayName + ); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true, + }); + } + } + function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function () { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error( + "%s: `ref` is not a prop. Trying to access it will result " + + "in `undefined` being returned. If you need to access the same " + + "value within the child component, you should pass it as a different " + + "prop. (https://reactjs.org/link/special-props)", + displayName + ); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true, + }); } } + /** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ - // eslint-disable-next-line no-fallthrough - } - } - return null; - } - var assign = Object.assign; - - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() {} - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. + var ReactElement = function ( + type, + key, + ref, + self, + source, + owner, + props + ) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner, + }; + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false, + }); // self and source are DEV only properties. + + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self, + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source, + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + /** + * https://github.com/reactjs/rfcs/pull/107 + * @param {*} type + * @param {object} props + * @param {string} key + */ - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } - if (disabledDepth < 0) { - error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ''; - } - } // We use the prefix to ensure our stacks line up with native stack frames. + function jsxDEV(type, config, maybeKey, source, self) { + { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; // Currently, key can be spread in as a prop. This causes a potential + // issue if key is also explicitly declared (ie.
+ // or
). We want to deprecate key spread, + // but as an intermediary step, we will use jsxDEV for everything except + //
, because we aren't currently able to tell if + // key is explicitly declared to be undefined or not. + + if (maybeKey !== undefined) { + { + checkKeyStringCoercion(maybeKey); + } + key = "" + maybeKey; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self); + } // Remaining properties are added to a new props object + + for (propName in config) { + if ( + hasOwnProperty.call(config, propName) && + !RESERVED_PROPS.hasOwnProperty(propName) + ) { + props[propName] = config[propName]; + } + } // Resolve default props - return '\n' + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return ''; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== undefined) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n'); - var controlLines = control.stack.split('\n'); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. - - if (fn.displayName && _frame.includes('')) { - _frame = _frame.replace('', fn.displayName); + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; } - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. - - return _frame; } - } while (s >= 1 && c >= 0); + } + if (key || ref) { + var displayName = + typeof type === "function" + ? type.displayName || type.name || "Unknown" + : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + return ReactElement( + type, + key, + ref, + self, + source, + ReactCurrentOwner.current, + props + ); } - break; } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - var name = fn ? fn.displayName || fn.name : ''; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ''; - } - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame('Suspense'); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList'); - } - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var ReactDebugCurrentFrame$1 = + ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV( + element.type, + element._source, + owner ? owner.type : null + ); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} + propTypesMisspellWarningShown = false; } - } - } - return ''; - } - var hasOwnProperty = Object.prototype.hasOwnProperty; - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - // $FlowFixMe This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. + /** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); - err.name = 'Invariant Violation'; - throw err; + function isValidElement(object) { + { + return ( + typeof object === "object" && + object !== null && + object.$$typeof === REACT_ELEMENT_TYPE + ); } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); - } catch (ex) { - error$1 = ex; } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); + function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType( + ReactCurrentOwner$1.current.type + ); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error('Failed %s type: %s', location, error$1.message); - setCurrentlyValidatingElement(null); + function getSourceInfoErrorAddendum(source) { + { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return ( + "\n\nCheck your code at " + + fileName + + ":" + + lineNumber + + "." + ); + } + return ""; + } } - } - } - } - } - var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ - function isArray(a) { - return isArrayImpl(a); - } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = + typeof parentType === "string" + ? parentType + : parentType.displayName || parentType.name; + if (parentName) { + info = + "\n\nCheck the top-level render call using <" + + parentName + + ">."; + } + } + return info; + } + } + /** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ - /* - * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol - * and Temporal.* types. See https://github.com/facebook/react/pull/22064. - * - * The functions in this module will throw an easier-to-understand, - * easier-to-debug exception with a clear errors message message explaining the - * problem. (Instead of a confusing exception thrown inside the implementation - * of the `value` object). - */ - // $FlowFixMe only called in DEV, so void return is not possible. - function typeName(value) { - { - // toStringTag is needed for namespaced types like Temporal.Instant - var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; - return type; - } - } // $FlowFixMe only called in DEV, so void return is not possible. + function validateExplicitKey(element, parentType) { + { + if ( + !element._store || + element._store.validated || + element.key != null + ) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = + getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ""; + if ( + element && + element._owner && + element._owner !== ReactCurrentOwner$1.current + ) { + // Give the component that originally created this child. + childOwner = + " It was passed a child from " + + getComponentNameFromType(element._owner.type) + + "."; + } + setCurrentlyValidatingElement$1(element); + error( + 'Each child in a list should have a unique "key" prop.' + + "%s%s See https://reactjs.org/link/warning-keys for more information.", + currentComponentErrorInfo, + childOwner + ); + setCurrentlyValidatingElement$1(null); + } + } + /** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - function testStringCoercion(value) { - // If you ended up here by following an exception call stack, here's what's - // happened: you supplied an object or symbol value to React (as a prop, key, - // DOM attribute, CSS property, string ref, etc.) and when React tried to - // coerce it to a string using `'' + value`, an exception was thrown. - // - // The most common types that will cause this exception are `Symbol` instances - // and Temporal objects like `Temporal.Instant`. But any object that has a - // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this - // exception. (Library authors do this to prevent users from using built-in - // numeric operators like `+` or comparison operators like `>=` because custom - // methods are needed to perform accurate arithmetic or comparison.) - // - // To fix the problem, coerce this object or symbol value to a string before - // passing it to React. The most reliable way is usually `String(value)`. - // - // To find which value is throwing, check the browser or debugger console. - // Before this exception was thrown, there should be `console.error` output - // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the - // problem and how that type was used: key, atrribute, input value prop, etc. - // In most cases, this console output also shows the component and its - // ancestor components where the exception happened. - // - // eslint-disable-next-line react-internal/safe-string-coercion - return '' + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } - } - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown; - var specialPropRefWarningShown; - var didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config) { - { - if (hasOwnProperty.call(config, 'ref')) { - var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.ref !== undefined; - } - function hasValidKey(config) { - { - if (hasOwnProperty.call(config, 'key')) { - var getter = Object.getOwnPropertyDescriptor(config, 'key').get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.key !== undefined; - } - function warnIfStringRefCannotBeAutoConverted(config, self) { - { - if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { - var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - function defineKeyPropWarningGetter(props, displayName) { - { - var warnAboutAccessingKey = function () { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, 'key', { - get: warnAboutAccessingKey, - configurable: true - }); - } - } - function defineRefPropWarningGetter(props, displayName) { - { - var warnAboutAccessingRef = function () { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, 'ref', { - get: warnAboutAccessingRef, - configurable: true - }); - } - } - /** - * Factory method to create a new React element. This no longer adheres to - * the class pattern, so do not use new to call it. Also, instanceof check - * will not work. Instead test $$typeof field against Symbol.for('react.element') to check - * if something is a React Element. - * - * @param {*} type - * @param {*} props - * @param {*} key - * @param {string|object} ref - * @param {*} owner - * @param {*} self A *temporary* helper to detect places where `this` is - * different from the `owner` when React.createElement is called, so that we - * can warn. We want to get rid of owner and replace string `ref`s with arrow - * functions, and as long as `this` and owner are the same, there will be no - * change in behavior. - * @param {*} source An annotation object (added by a transpiler or otherwise) - * indicating filename, line number, and/or other information. - * @internal - */ + function validateChildKeys(node, parentType) { + { + if (typeof node !== "object") { + return; + } + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + } + /** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ - var ReactElement = function (type, key, ref, self, source, owner, props) { - var element = { - // This tag allows us to uniquely identify this as a React Element - $$typeof: REACT_ELEMENT_TYPE, - // Built-in properties that belong on the element - type: type, - key: key, - ref: ref, - props: props, - // Record the component responsible for creating this element. - _owner: owner - }; - { - // The validation flag is currently mutative. We put it on - // an external backing store so that we can freeze the whole object. - // This can be replaced with a WeakMap once they are implemented in - // commonly used development environments. - element._store = {}; // To make comparing ReactElements easier for testing purposes, we make - // the validation flag non-enumerable (where possible, which should - // include every environment we run tests in), so the test framework - // ignores it. - - Object.defineProperty(element._store, 'validated', { - configurable: false, - enumerable: false, - writable: true, - value: false - }); // self and source are DEV only properties. - - Object.defineProperty(element, '_self', { - configurable: false, - enumerable: false, - writable: false, - value: self - }); // Two elements created in two different places should be considered - // equal for testing purposes and therefore we hide it from enumeration. - - Object.defineProperty(element, '_source', { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - /** - * https://github.com/reactjs/rfcs/pull/107 - * @param {*} type - * @param {object} props - * @param {string} key - */ + function validatePropTypes(element) { + { + var type = element.type; + if ( + type === null || + type === undefined || + typeof type === "string" + ) { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if ( + typeof type === "object" && + (type.$$typeof === REACT_FORWARD_REF_TYPE || + // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE) + ) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes( + propTypes, + element.props, + "prop", + name, + element + ); + } else if ( + type.PropTypes !== undefined && + !propTypesMisspellWarningShown + ) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + error( + "Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", + _name || "Unknown" + ); + } + if ( + typeof type.getDefaultProps === "function" && + !type.getDefaultProps.isReactClassApproved + ) { + error( + "getDefaultProps is only used on classic React.createClass " + + "definitions. Use a static property named `defaultProps` instead." + ); + } + } + } + /** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ - function jsxDEV(type, config, maybeKey, source, self) { - { - var propName; // Reserved names are extracted + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error( + "Invalid prop `%s` supplied to `React.Fragment`. " + + "React.Fragment can only have `key` and `children` props.", + key + ); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error( + "Invalid attribute `ref` supplied to `React.Fragment`." + ); + setCurrentlyValidatingElement$1(null); + } + } + } + function jsxWithValidation( + type, + props, + key, + isStaticChildren, + source, + self + ) { + { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ""; + if ( + type === undefined || + (typeof type === "object" && + type !== null && + Object.keys(type).length === 0) + ) { + info += + " You likely forgot to export your component from the file " + + "it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendum(source); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray(type)) { + typeString = "array"; + } else if ( + type !== undefined && + type.$$typeof === REACT_ELEMENT_TYPE + ) { + typeString = + "<" + + (getComponentNameFromType(type.type) || "Unknown") + + " />"; + info = + " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + error( + "React.jsx: type is invalid -- expected a string (for " + + "built-in components) or a class/function (for composite " + + "components) but got: %s.%s", + typeString, + info + ); + } + var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + if (validType) { + var children = props.children; + if (children !== undefined) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + validateChildKeys(children[i], type); + } + if (Object.freeze) { + Object.freeze(children); + } + } else { + error( + "React.jsx: Static children should always be an array. " + + "You are likely explicitly calling React.jsxs or React.jsxDEV. " + + "Use the Babel transform instead." + ); + } + } else { + validateChildKeys(children, type); + } + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + } // These two functions exist to still get child warnings in dev + // even with the prod transform. This means that jsxDEV is purely + // opt-in behavior for better messages but that we won't stop + // giving you warnings if you use production apis. - var props = {}; - var key = null; - var ref = null; // Currently, key can be spread in as a prop. This causes a potential - // issue if key is also explicitly declared (ie.
- // or
). We want to deprecate key spread, - // but as an intermediary step, we will use jsxDEV for everything except - //
, because we aren't currently able to tell if - // key is explicitly declared to be undefined or not. + function jsxWithValidationStatic(type, props, key) { + { + return jsxWithValidation(type, props, key, true); + } + } + function jsxWithValidationDynamic(type, props, key) { + { + return jsxWithValidation(type, props, key, false); + } + } + var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children. + // for now we can ship identical prod functions - if (maybeKey !== undefined) { - { - checkKeyStringCoercion(maybeKey); - } - key = '' + maybeKey; + var jsxs = jsxWithValidationStatic; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.jsx = jsx; + exports.jsxs = jsxs; + })(); } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = '' + config.key; - } - if (hasValidRef(config)) { - ref = config.ref; - warnIfStringRefCannotBeAutoConverted(config, self); - } // Remaining properties are added to a new props object - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config[propName]; - } - } // Resolve default props + /***/ + }, - if (type && type.defaultProps) { - var defaultProps = type.defaultProps; - for (propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - } - if (key || ref) { - var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); - } - } - var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + /***/ "../../../node_modules/react/jsx-runtime.js": + /*!**************************************************!*\ + !*** ../../../node_modules/react/jsx-runtime.js ***! + \**************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + if (false) { } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - /** - * Verifies the object is a ReactElement. - * See https://reactjs.org/docs/react-api.html#isvalidelement - * @param {?object} object - * @return {boolean} True if `object` is a ReactElement. - * @final - */ - - function isValidElement(object) { - { - return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - } - function getDeclarationErrorAddendum() { - { - if (ReactCurrentOwner$1.current) { - var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); - if (name) { - return '\n\nCheck the render method of `' + name + '`.'; - } - } - return ''; - } - } - function getSourceInfoErrorAddendum(source) { - { - if (source !== undefined) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ''); - var lineNumber = source.lineNumber; - return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; - } - return ''; - } - } - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } + module.exports = __webpack_require__( + /*! ./cjs/react-jsx-runtime.development.js */ "../../../node_modules/react/cjs/react-jsx-runtime.development.js" + ); } - return info; - } - } - /** - * Warn if the element doesn't have an explicit key assigned to it. - * This element is in an array. The array could grow and shrink or be - * reordered. All children that haven't already been validated are required to - * have a "key" property assigned to it. Error statuses are cached so a warning - * will only be shown once. - * - * @internal - * @param {ReactElement} element Element that requires a key. - * @param {*} parentType element's parent's type. - */ - function validateExplicitKey(element, parentType) { - { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a - // property, it may be the creator of the child that's responsible for - // assigning it a key. + /***/ + }, - var childOwner = ''; - if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { - // Give the component that originally created this child. - childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; - } - setCurrentlyValidatingElement$1(element); - error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - /** - * Ensure that every element either is passed in a static location, in an - * array with an explicit keys property defined, or in an object literal - * with valid key property. - * - * @internal - * @param {ReactNode} node Statically passed child of any type. - * @param {*} parentType node's parent's type. - */ + /***/ "../../../node_modules/set-value/index.js": + /*!************************************************!*\ + !*** ../../../node_modules/set-value/index.js ***! + \************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + /*! + * set-value + * + * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert). + * Released under the MIT License. + */ - function validateChildKeys(node, parentType) { - { - if (typeof node !== 'object') { - return; - } - if (isArray(node)) { - for (var i = 0; i < node.length; i++) { - var child = node[i]; - if (isValidElement(child)) { - validateExplicitKey(child, parentType); + const { deleteProperty } = Reflect; + const isPrimitive = __webpack_require__( + /*! is-primitive */ "../../../node_modules/is-primitive/index.js" + ); + const isPlainObject = __webpack_require__( + /*! is-plain-object */ "../../../node_modules/is-plain-object/index.js" + ); + const isObject = (value) => { + return ( + (typeof value === "object" && value !== null) || + typeof value === "function" + ); + }; + const isUnsafeKey = (key) => { + return ( + key === "__proto__" || key === "constructor" || key === "prototype" + ); + }; + const validateKey = (key) => { + if (!isPrimitive(key)) { + throw new TypeError("Object keys must be strings or symbols"); + } + if (isUnsafeKey(key)) { + throw new Error(`Cannot set unsafe key: "${key}"`); + } + }; + const toStringKey = (input) => { + return Array.isArray(input) + ? input.flat().map(String).join(",") + : input; + }; + const createMemoKey = (input, options) => { + if (typeof input !== "string" || !options) return input; + let key = input + ";"; + if (options.arrays !== undefined) key += `arrays=${options.arrays};`; + if (options.separator !== undefined) + key += `separator=${options.separator};`; + if (options.split !== undefined) key += `split=${options.split};`; + if (options.merge !== undefined) key += `merge=${options.merge};`; + if (options.preservePaths !== undefined) + key += `preservePaths=${options.preservePaths};`; + return key; + }; + const memoize = (input, options, fn) => { + const key = toStringKey( + options ? createMemoKey(input, options) : input + ); + validateKey(key); + const value = setValue.cache.get(key) || fn(); + setValue.cache.set(key, value); + return value; + }; + const splitString = (input, options = {}) => { + const sep = options.separator || "."; + const preserve = sep === "/" ? false : options.preservePaths; + if ( + typeof input === "string" && + preserve !== false && + /\//.test(input) + ) { + return [input]; + } + const parts = []; + let part = ""; + const push = (part) => { + let number; + if ( + part.trim() !== "" && + Number.isInteger((number = Number(part))) + ) { + parts.push(number); + } else { + parts.push(part); + } + }; + for (let i = 0; i < input.length; i++) { + const value = input[i]; + if (value === "\\") { + part += input[++i]; + continue; + } + if (value === sep) { + push(part); + part = ""; + continue; } + part += value; } - } else if (isValidElement(node)) { - // This element was passed in a valid location. - if (node._store) { - node._store.validated = true; + if (part) { + push(part); } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === 'function') { - // Entry iterators used to provide implicit keys, - // but now we print a separate warning for them later. - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType); - } - } + return parts; + }; + const split = (input, options) => { + if (options && typeof options.split === "function") + return options.split(input); + if (typeof input === "symbol") return [input]; + if (Array.isArray(input)) return input; + return memoize(input, options, () => splitString(input, options)); + }; + const assignProp = (obj, prop, value, options) => { + validateKey(prop); + + // Delete property when "value" is undefined + if (value === undefined) { + deleteProperty(obj, prop); + } else if (options && options.merge) { + const merge = + options.merge === "function" ? options.merge : Object.assign; + + // Only merge plain objects + if (merge && isPlainObject(obj[prop]) && isPlainObject(value)) { + obj[prop] = merge(obj[prop], value); + } else { + obj[prop] = value; } + } else { + obj[prop] = value; } - } - } - } - /** - * Given an element, validate that its props follow the propTypes definition, - * provided by the type. - * - * @param {ReactElement} element - */ - - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === undefined || typeof type === 'string') { - return; - } - var propTypes; - if (typeof type === 'function') { - propTypes = type.propTypes; - } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || - // Note: Memo only checks outer props here. - // Inner props are checked in the reconciler. - type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - // Intentionally inside to avoid triggering lazy initializers: - var name = getComponentNameFromType(type); - checkPropTypes(propTypes, element.props, 'prop', name, element); - } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + return obj; + }; + const setValue = (target, path, value, options) => { + if (!path || !isObject(target)) return target; + const keys = split(path, options); + let obj = target; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const next = keys[i + 1]; + validateKey(key); + if (next === undefined) { + assignProp(obj, key, value, options); + break; + } + if (typeof next === "number" && !Array.isArray(obj[key])) { + obj = obj[key] = []; + continue; + } + if (!isObject(obj[key])) { + obj[key] = {}; + } + obj = obj[key]; + } + return target; + }; + setValue.split = split; + setValue.cache = new Map(); + setValue.clear = () => { + setValue.cache = new Map(); + }; + module.exports = setValue; - var _name = getComponentNameFromType(type); - error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); - } - if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { - error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); - } - } - } - /** - * Given a fragment, validate that it can only be provided with fragment props - * @param {ReactElement} fragment - */ + /***/ + }, - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key !== 'children' && key !== 'key') { - setCurrentlyValidatingElement$1(fragment); - error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error('Invalid attribute `ref` supplied to `React.Fragment`.'); - setCurrentlyValidatingElement$1(null); - } - } - } - function jsxWithValidation(type, props, key, isStaticChildren, source, self) { - { - var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to - // succeed and there will likely be errors in render. - - if (!validType) { - var info = ''; - if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { - info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendum(source); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = 'null'; - } else if (isArray(type)) { - typeString = 'array'; - } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; - info = ' Did you accidentally export a JSX literal instead of a component?'; + /***/ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js": + /*!**********************************************************************!*\ + !*** ../../../node_modules/style-value-types/dist/valueTypes.cjs.js ***! + \**********************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + const clamp = (min, max) => (v) => Math.max(Math.min(v, max), min); + const sanitize = (v) => (v % 1 ? Number(v.toFixed(5)) : v); + const floatRegex = /(-)?([\d]*\.?[\d])+/g; + const colorRegex = + /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi; + const singleColorRegex = + /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i; + function isString(v) { + return typeof v === "string"; + } + const number = { + test: (v) => typeof v === "number", + parse: parseFloat, + transform: (v) => v, + }; + const alpha = Object.assign(Object.assign({}, number), { + transform: clamp(0, 1), + }); + const scale = Object.assign(Object.assign({}, number), { + default: 1, + }); + const createUnitType = (unit) => ({ + test: (v) => + isString(v) && v.endsWith(unit) && v.split(" ").length === 1, + parse: parseFloat, + transform: (v) => `${v}${unit}`, + }); + const degrees = createUnitType("deg"); + const percent = createUnitType("%"); + const px = createUnitType("px"); + const vh = createUnitType("vh"); + const vw = createUnitType("vw"); + const progressPercentage = Object.assign(Object.assign({}, percent), { + parse: (v) => percent.parse(v) / 100, + transform: (v) => percent.transform(v * 100), + }); + const isColorString = (type, testProp) => (v) => { + return Boolean( + (isString(v) && singleColorRegex.test(v) && v.startsWith(type)) || + (testProp && Object.prototype.hasOwnProperty.call(v, testProp)) + ); + }; + const splitColor = (aName, bName, cName) => (v) => { + if (!isString(v)) return v; + const [a, b, c, alpha] = v.match(floatRegex); + return { + [aName]: parseFloat(a), + [bName]: parseFloat(b), + [cName]: parseFloat(c), + alpha: alpha !== undefined ? parseFloat(alpha) : 1, + }; + }; + const hsla = { + test: isColorString("hsl", "hue"), + parse: splitColor("hue", "saturation", "lightness"), + transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => { + return ( + "hsla(" + + Math.round(hue) + + ", " + + percent.transform(sanitize(saturation)) + + ", " + + percent.transform(sanitize(lightness)) + + ", " + + sanitize(alpha.transform(alpha$1)) + + ")" + ); + }, + }; + const clampRgbUnit = clamp(0, 255); + const rgbUnit = Object.assign(Object.assign({}, number), { + transform: (v) => Math.round(clampRgbUnit(v)), + }); + const rgba = { + test: isColorString("rgb", "red"), + parse: splitColor("red", "green", "blue"), + transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => + "rgba(" + + rgbUnit.transform(red) + + ", " + + rgbUnit.transform(green) + + ", " + + rgbUnit.transform(blue) + + ", " + + sanitize(alpha.transform(alpha$1)) + + ")", + }; + function parseHex(v) { + let r = ""; + let g = ""; + let b = ""; + let a = ""; + if (v.length > 5) { + r = v.substr(1, 2); + g = v.substr(3, 2); + b = v.substr(5, 2); + a = v.substr(7, 2); } else { - typeString = typeof type; + r = v.substr(1, 1); + g = v.substr(2, 1); + b = v.substr(3, 1); + a = v.substr(4, 1); + r += r; + g += g; + b += b; + a += a; } - error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + return { + red: parseInt(r, 16), + green: parseInt(g, 16), + blue: parseInt(b, 16), + alpha: a ? parseInt(a, 16) / 255 : 1, + }; } - var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. - // TODO: Drop this when these are no longer allowed as the type argument. - - if (element == null) { - return element; - } // Skip key warning if the type isn't valid since our key validation logic - // doesn't expect a non-string/function type and can throw confusing errors. - // We don't want exception behavior to differ between dev and prod. - // (Rendering will throw with a helpful message and as soon as the type is - // fixed, the key warnings will appear.) - - if (validType) { - var children = props.children; - if (children !== undefined) { - if (isStaticChildren) { - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - validateChildKeys(children[i], type); - } - if (Object.freeze) { - Object.freeze(children); - } - } else { - error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); - } + const hex = { + test: isColorString("#"), + parse: parseHex, + transform: rgba.transform, + }; + const color = { + test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v), + parse: (v) => { + if (rgba.test(v)) { + return rgba.parse(v); + } else if (hsla.test(v)) { + return hsla.parse(v); } else { - validateChildKeys(children, type); + return hex.parse(v); } + }, + transform: (v) => { + return isString(v) + ? v + : v.hasOwnProperty("red") + ? rgba.transform(v) + : hsla.transform(v); + }, + }; + const colorToken = "${c}"; + const numberToken = "${n}"; + function test(v) { + var _a, _b, _c, _d; + return ( + isNaN(v) && + isString(v) && + ((_b = + (_a = v.match(floatRegex)) === null || _a === void 0 + ? void 0 + : _a.length) !== null && _b !== void 0 + ? _b + : 0) + + ((_d = + (_c = v.match(colorRegex)) === null || _c === void 0 + ? void 0 + : _c.length) !== null && _d !== void 0 + ? _d + : 0) > + 0 + ); + } + function analyse(v) { + if (typeof v === "number") v = `${v}`; + const values = []; + let numColors = 0; + const colors = v.match(colorRegex); + if (colors) { + numColors = colors.length; + v = v.replace(colorRegex, colorToken); + values.push(...colors.map(color.parse)); + } + const numbers = v.match(floatRegex); + if (numbers) { + v = v.replace(floatRegex, numberToken); + values.push(...numbers.map(number.parse)); } + return { + values, + numColors, + tokenised: v, + }; } - if (type === REACT_FRAGMENT_TYPE) { - validateFragmentProps(element); - } else { - validatePropTypes(element); + function parse(v) { + return analyse(v).values; + } + function createTransformer(v) { + const { values, numColors, tokenised } = analyse(v); + const numValues = values.length; + return (v) => { + let output = tokenised; + for (let i = 0; i < numValues; i++) { + output = output.replace( + i < numColors ? colorToken : numberToken, + i < numColors ? color.transform(v[i]) : sanitize(v[i]) + ); + } + return output; + }; } - return element; - } - } // These two functions exist to still get child warnings in dev - // even with the prod transform. This means that jsxDEV is purely - // opt-in behavior for better messages but that we won't stop - // giving you warnings if you use production apis. - - function jsxWithValidationStatic(type, props, key) { - { - return jsxWithValidation(type, props, key, true); - } - } - function jsxWithValidationDynamic(type, props, key) { - { - return jsxWithValidation(type, props, key, false); - } - } - var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children. - // for now we can ship identical prod functions - - var jsxs = jsxWithValidationStatic; - exports.Fragment = REACT_FRAGMENT_TYPE; - exports.jsx = jsx; - exports.jsxs = jsxs; - })(); -} - -/***/ }), - -/***/ "../../../node_modules/react/jsx-runtime.js": -/*!**************************************************!*\ - !*** ../../../node_modules/react/jsx-runtime.js ***! - \**************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -if (false) {} else { - module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ "../../../node_modules/react/cjs/react-jsx-runtime.development.js"); -} - -/***/ }), - -/***/ "../../../node_modules/set-value/index.js": -/*!************************************************!*\ - !*** ../../../node_modules/set-value/index.js ***! - \************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/*! - * set-value - * - * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert). - * Released under the MIT License. - */ - - - -const { - deleteProperty -} = Reflect; -const isPrimitive = __webpack_require__(/*! is-primitive */ "../../../node_modules/is-primitive/index.js"); -const isPlainObject = __webpack_require__(/*! is-plain-object */ "../../../node_modules/is-plain-object/index.js"); -const isObject = value => { - return typeof value === 'object' && value !== null || typeof value === 'function'; -}; -const isUnsafeKey = key => { - return key === '__proto__' || key === 'constructor' || key === 'prototype'; -}; -const validateKey = key => { - if (!isPrimitive(key)) { - throw new TypeError('Object keys must be strings or symbols'); - } - if (isUnsafeKey(key)) { - throw new Error(`Cannot set unsafe key: "${key}"`); - } -}; -const toStringKey = input => { - return Array.isArray(input) ? input.flat().map(String).join(',') : input; -}; -const createMemoKey = (input, options) => { - if (typeof input !== 'string' || !options) return input; - let key = input + ';'; - if (options.arrays !== undefined) key += `arrays=${options.arrays};`; - if (options.separator !== undefined) key += `separator=${options.separator};`; - if (options.split !== undefined) key += `split=${options.split};`; - if (options.merge !== undefined) key += `merge=${options.merge};`; - if (options.preservePaths !== undefined) key += `preservePaths=${options.preservePaths};`; - return key; -}; -const memoize = (input, options, fn) => { - const key = toStringKey(options ? createMemoKey(input, options) : input); - validateKey(key); - const value = setValue.cache.get(key) || fn(); - setValue.cache.set(key, value); - return value; -}; -const splitString = (input, options = {}) => { - const sep = options.separator || '.'; - const preserve = sep === '/' ? false : options.preservePaths; - if (typeof input === 'string' && preserve !== false && /\//.test(input)) { - return [input]; - } - const parts = []; - let part = ''; - const push = part => { - let number; - if (part.trim() !== '' && Number.isInteger(number = Number(part))) { - parts.push(number); - } else { - parts.push(part); - } - }; - for (let i = 0; i < input.length; i++) { - const value = input[i]; - if (value === '\\') { - part += input[++i]; - continue; - } - if (value === sep) { - push(part); - part = ''; - continue; - } - part += value; - } - if (part) { - push(part); - } - return parts; -}; -const split = (input, options) => { - if (options && typeof options.split === 'function') return options.split(input); - if (typeof input === 'symbol') return [input]; - if (Array.isArray(input)) return input; - return memoize(input, options, () => splitString(input, options)); -}; -const assignProp = (obj, prop, value, options) => { - validateKey(prop); - - // Delete property when "value" is undefined - if (value === undefined) { - deleteProperty(obj, prop); - } else if (options && options.merge) { - const merge = options.merge === 'function' ? options.merge : Object.assign; - - // Only merge plain objects - if (merge && isPlainObject(obj[prop]) && isPlainObject(value)) { - obj[prop] = merge(obj[prop], value); - } else { - obj[prop] = value; - } - } else { - obj[prop] = value; - } - return obj; -}; -const setValue = (target, path, value, options) => { - if (!path || !isObject(target)) return target; - const keys = split(path, options); - let obj = target; - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const next = keys[i + 1]; - validateKey(key); - if (next === undefined) { - assignProp(obj, key, value, options); - break; - } - if (typeof next === 'number' && !Array.isArray(obj[key])) { - obj = obj[key] = []; - continue; - } - if (!isObject(obj[key])) { - obj[key] = {}; - } - obj = obj[key]; - } - return target; -}; -setValue.split = split; -setValue.cache = new Map(); -setValue.clear = () => { - setValue.cache = new Map(); -}; -module.exports = setValue; - -/***/ }), + const convertNumbersToZero = (v) => (typeof v === "number" ? 0 : v); + function getAnimatableNone(v) { + const parsed = parse(v); + const transformer = createTransformer(v); + return transformer(parsed.map(convertNumbersToZero)); + } + const complex = { + test, + parse, + createTransformer, + getAnimatableNone, + }; + const maxDefaults = new Set([ + "brightness", + "contrast", + "saturate", + "opacity", + ]); + function applyDefaultFilter(v) { + let [name, value] = v.slice(0, -1).split("("); + if (name === "drop-shadow") return v; + const [number] = value.match(floatRegex) || []; + if (!number) return v; + const unit = value.replace(number, ""); + let defaultValue = maxDefaults.has(name) ? 1 : 0; + if (number !== value) defaultValue *= 100; + return name + "(" + defaultValue + unit + ")"; + } + const functionRegex = /([a-z-]*)\(.*?\)/g; + const filter = Object.assign(Object.assign({}, complex), { + getAnimatableNone: (v) => { + const functions = v.match(functionRegex); + return functions ? functions.map(applyDefaultFilter).join(" ") : v; + }, + }); + exports.alpha = alpha; + exports.color = color; + exports.complex = complex; + exports.degrees = degrees; + exports.filter = filter; + exports.hex = hex; + exports.hsla = hsla; + exports.number = number; + exports.percent = percent; + exports.progressPercentage = progressPercentage; + exports.px = px; + exports.rgbUnit = rgbUnit; + exports.rgba = rgba; + exports.scale = scale; + exports.vh = vh; + exports.vw = vw; + + /***/ + }, -/***/ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js": -/*!**********************************************************************!*\ - !*** ../../../node_modules/style-value-types/dist/valueTypes.cjs.js ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -const clamp = (min, max) => v => Math.max(Math.min(v, max), min); -const sanitize = v => v % 1 ? Number(v.toFixed(5)) : v; -const floatRegex = /(-)?([\d]*\.?[\d])+/g; -const colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi; -const singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i; -function isString(v) { - return typeof v === 'string'; -} -const number = { - test: v => typeof v === 'number', - parse: parseFloat, - transform: v => v -}; -const alpha = Object.assign(Object.assign({}, number), { - transform: clamp(0, 1) -}); -const scale = Object.assign(Object.assign({}, number), { - default: 1 -}); -const createUnitType = unit => ({ - test: v => isString(v) && v.endsWith(unit) && v.split(' ').length === 1, - parse: parseFloat, - transform: v => `${v}${unit}` -}); -const degrees = createUnitType('deg'); -const percent = createUnitType('%'); -const px = createUnitType('px'); -const vh = createUnitType('vh'); -const vw = createUnitType('vw'); -const progressPercentage = Object.assign(Object.assign({}, percent), { - parse: v => percent.parse(v) / 100, - transform: v => percent.transform(v * 100) -}); -const isColorString = (type, testProp) => v => { - return Boolean(isString(v) && singleColorRegex.test(v) && v.startsWith(type) || testProp && Object.prototype.hasOwnProperty.call(v, testProp)); -}; -const splitColor = (aName, bName, cName) => v => { - if (!isString(v)) return v; - const [a, b, c, alpha] = v.match(floatRegex); - return { - [aName]: parseFloat(a), - [bName]: parseFloat(b), - [cName]: parseFloat(c), - alpha: alpha !== undefined ? parseFloat(alpha) : 1 - }; -}; -const hsla = { - test: isColorString('hsl', 'hue'), - parse: splitColor('hue', 'saturation', 'lightness'), - transform: ({ - hue, - saturation, - lightness, - alpha: alpha$1 = 1 - }) => { - return 'hsla(' + Math.round(hue) + ', ' + percent.transform(sanitize(saturation)) + ', ' + percent.transform(sanitize(lightness)) + ', ' + sanitize(alpha.transform(alpha$1)) + ')'; - } -}; -const clampRgbUnit = clamp(0, 255); -const rgbUnit = Object.assign(Object.assign({}, number), { - transform: v => Math.round(clampRgbUnit(v)) -}); -const rgba = { - test: isColorString('rgb', 'red'), - parse: splitColor('red', 'green', 'blue'), - transform: ({ - red, - green, - blue, - alpha: alpha$1 = 1 - }) => 'rgba(' + rgbUnit.transform(red) + ', ' + rgbUnit.transform(green) + ', ' + rgbUnit.transform(blue) + ', ' + sanitize(alpha.transform(alpha$1)) + ')' -}; -function parseHex(v) { - let r = ''; - let g = ''; - let b = ''; - let a = ''; - if (v.length > 5) { - r = v.substr(1, 2); - g = v.substr(3, 2); - b = v.substr(5, 2); - a = v.substr(7, 2); - } else { - r = v.substr(1, 1); - g = v.substr(2, 1); - b = v.substr(3, 1); - a = v.substr(4, 1); - r += r; - g += g; - b += b; - a += a; - } - return { - red: parseInt(r, 16), - green: parseInt(g, 16), - blue: parseInt(b, 16), - alpha: a ? parseInt(a, 16) / 255 : 1 - }; -} -const hex = { - test: isColorString('#'), - parse: parseHex, - transform: rgba.transform -}; -const color = { - test: v => rgba.test(v) || hex.test(v) || hsla.test(v), - parse: v => { - if (rgba.test(v)) { - return rgba.parse(v); - } else if (hsla.test(v)) { - return hsla.parse(v); - } else { - return hex.parse(v); - } - }, - transform: v => { - return isString(v) ? v : v.hasOwnProperty('red') ? rgba.transform(v) : hsla.transform(v); - } -}; -const colorToken = '${c}'; -const numberToken = '${n}'; -function test(v) { - var _a, _b, _c, _d; - return isNaN(v) && isString(v) && ((_b = (_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0; -} -function analyse(v) { - if (typeof v === 'number') v = `${v}`; - const values = []; - let numColors = 0; - const colors = v.match(colorRegex); - if (colors) { - numColors = colors.length; - v = v.replace(colorRegex, colorToken); - values.push(...colors.map(color.parse)); - } - const numbers = v.match(floatRegex); - if (numbers) { - v = v.replace(floatRegex, numberToken); - values.push(...numbers.map(number.parse)); - } - return { - values, - numColors, - tokenised: v - }; -} -function parse(v) { - return analyse(v).values; -} -function createTransformer(v) { - const { - values, - numColors, - tokenised - } = analyse(v); - const numValues = values.length; - return v => { - let output = tokenised; - for (let i = 0; i < numValues; i++) { - output = output.replace(i < numColors ? colorToken : numberToken, i < numColors ? color.transform(v[i]) : sanitize(v[i])); - } - return output; - }; -} -const convertNumbersToZero = v => typeof v === 'number' ? 0 : v; -function getAnimatableNone(v) { - const parsed = parse(v); - const transformer = createTransformer(v); - return transformer(parsed.map(convertNumbersToZero)); -} -const complex = { - test, - parse, - createTransformer, - getAnimatableNone -}; -const maxDefaults = new Set(['brightness', 'contrast', 'saturate', 'opacity']); -function applyDefaultFilter(v) { - let [name, value] = v.slice(0, -1).split('('); - if (name === 'drop-shadow') return v; - const [number] = value.match(floatRegex) || []; - if (!number) return v; - const unit = value.replace(number, ''); - let defaultValue = maxDefaults.has(name) ? 1 : 0; - if (number !== value) defaultValue *= 100; - return name + '(' + defaultValue + unit + ')'; -} -const functionRegex = /([a-z-]*)\(.*?\)/g; -const filter = Object.assign(Object.assign({}, complex), { - getAnimatableNone: v => { - const functions = v.match(functionRegex); - return functions ? functions.map(applyDefaultFilter).join(' ') : v; - } -}); -exports.alpha = alpha; -exports.color = color; -exports.complex = complex; -exports.degrees = degrees; -exports.filter = filter; -exports.hex = hex; -exports.hsla = hsla; -exports.number = number; -exports.percent = percent; -exports.progressPercentage = progressPercentage; -exports.px = px; -exports.rgbUnit = rgbUnit; -exports.rgba = rgba; -exports.scale = scale; -exports.vh = vh; -exports.vw = vw; - -/***/ }), - -/***/ "../../../node_modules/toggle-selection/index.js": -/*!*******************************************************!*\ + /***/ "../../../node_modules/toggle-selection/index.js": + /*!*******************************************************!*\ !*** ../../../node_modules/toggle-selection/index.js ***! - \*******************************************************/ -/***/ (function(module) { - - - -module.exports = function () { - var selection = document.getSelection(); - if (!selection.rangeCount) { - return function () {}; - } - var active = document.activeElement; - var ranges = []; - for (var i = 0; i < selection.rangeCount; i++) { - ranges.push(selection.getRangeAt(i)); - } - switch (active.tagName.toUpperCase()) { - // .toUpperCase handles XHTML - case 'INPUT': - case 'TEXTAREA': - active.blur(); - break; - default: - active = null; - break; - } - selection.removeAllRanges(); - return function () { - selection.type === 'Caret' && selection.removeAllRanges(); - if (!selection.rangeCount) { - ranges.forEach(function (range) { - selection.addRange(range); - }); - } - active && active.focus(); - }; -}; + \*******************************************************/ + /***/ function (module) { + module.exports = function () { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function () {}; + } + var active = document.activeElement; + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + switch (active.tagName.toUpperCase()) { + // .toUpperCase handles XHTML + case "INPUT": + case "TEXTAREA": + active.blur(); + break; + default: + active = null; + break; + } + selection.removeAllRanges(); + return function () { + selection.type === "Caret" && selection.removeAllRanges(); + if (!selection.rangeCount) { + ranges.forEach(function (range) { + selection.addRange(range); + }); + } + active && active.focus(); + }; + }; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/tslib/tslib.es6.mjs": -/*!*************************************************!*\ + /***/ "../../../node_modules/tslib/tslib.es6.mjs": + /*!*************************************************!*\ !*** ../../../node_modules/tslib/tslib.es6.mjs ***! \*************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.__addDisposableResource = __addDisposableResource; -exports.__assign = void 0; -exports.__asyncDelegator = __asyncDelegator; -exports.__asyncGenerator = __asyncGenerator; -exports.__asyncValues = __asyncValues; -exports.__await = __await; -exports.__awaiter = __awaiter; -exports.__classPrivateFieldGet = __classPrivateFieldGet; -exports.__classPrivateFieldIn = __classPrivateFieldIn; -exports.__classPrivateFieldSet = __classPrivateFieldSet; -exports.__createBinding = void 0; -exports.__decorate = __decorate; -exports.__disposeResources = __disposeResources; -exports.__esDecorate = __esDecorate; -exports.__exportStar = __exportStar; -exports.__extends = __extends; -exports.__generator = __generator; -exports.__importDefault = __importDefault; -exports.__importStar = __importStar; -exports.__makeTemplateObject = __makeTemplateObject; -exports.__metadata = __metadata; -exports.__param = __param; -exports.__propKey = __propKey; -exports.__read = __read; -exports.__rest = __rest; -exports.__runInitializers = __runInitializers; -exports.__setFunctionName = __setFunctionName; -exports.__spread = __spread; -exports.__spreadArray = __spreadArray; -exports.__spreadArrays = __spreadArrays; -exports.__values = __values; -exports["default"] = void 0; -/****************************************************************************** + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.__addDisposableResource = __addDisposableResource; + exports.__assign = void 0; + exports.__asyncDelegator = __asyncDelegator; + exports.__asyncGenerator = __asyncGenerator; + exports.__asyncValues = __asyncValues; + exports.__await = __await; + exports.__awaiter = __awaiter; + exports.__classPrivateFieldGet = __classPrivateFieldGet; + exports.__classPrivateFieldIn = __classPrivateFieldIn; + exports.__classPrivateFieldSet = __classPrivateFieldSet; + exports.__createBinding = void 0; + exports.__decorate = __decorate; + exports.__disposeResources = __disposeResources; + exports.__esDecorate = __esDecorate; + exports.__exportStar = __exportStar; + exports.__extends = __extends; + exports.__generator = __generator; + exports.__importDefault = __importDefault; + exports.__importStar = __importStar; + exports.__makeTemplateObject = __makeTemplateObject; + exports.__metadata = __metadata; + exports.__param = __param; + exports.__propKey = __propKey; + exports.__read = __read; + exports.__rest = __rest; + exports.__runInitializers = __runInitializers; + exports.__setFunctionName = __setFunctionName; + exports.__spread = __spread; + exports.__spreadArray = __spreadArray; + exports.__spreadArrays = __spreadArrays; + exports.__values = __values; + exports["default"] = void 0; + /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -44818,45847 +58246,58385 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol */ - -var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || { - __proto__: [] - } instanceof Array && function (d, b) { - d.__proto__ = b; - } || function (d, b) { - for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; - }; - return extendStatics(d, b); -}; -function __extends(d, b) { - if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -var __assign = function () { - exports.__assign = __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -exports.__assign = __assign; -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; - } - return t; -} -function __decorate(decorators, target, key, desc) { - var c = arguments.length, - r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, - d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -function __param(paramIndex, decorator) { - return function (target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, - key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, - done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { - get: descriptor.get, - set: descriptor.set - } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_);else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -; -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -} -; -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} -; -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { - configurable: true, - value: prefix ? "".concat(prefix, " ", name) : name - }); -} -; -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [] - }, - f, - y, - t, - g; - return g = { - next: verb(0), - "throw": verb(1), - "return": verb(2) - }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { - return this; - }), g; - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { - value: op[1], - done: false + /* global Reflect, Promise, SuppressedError, Symbol */ + + var extendStatics = function (d, b) { + extendStatics = + Object.setPrototypeOf || + ({ + __proto__: [], + } instanceof Array && + function (d, b) { + d.__proto__ = b; + }) || + function (d, b) { + for (var p in b) + if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError( + "Class extends value " + + String(b) + + " is not a constructor or null" + ); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = + b === null + ? Object.create(b) + : ((__.prototype = b.prototype), new __()); + } + var __assign = function () { + exports.__assign = __assign = + Object.assign || + function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + exports.__assign = __assign; + function __rest(s, e) { + var t = {}; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for ( + var i = 0, p = Object.getOwnPropertySymbols(s); + i < p.length; + i++ + ) { + if ( + e.indexOf(p[i]) < 0 && + Object.prototype.propertyIsEnumerable.call(s, p[i]) + ) + t[p[i]] = s[p[i]]; + } + return t; + } + function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = + c < 3 + ? target + : desc === null + ? (desc = Object.getOwnPropertyDescriptor(target, key)) + : desc, + d; + if ( + typeof Reflect === "object" && + typeof Reflect.decorate === "function" + ) + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if ((d = decorators[i])) + r = + (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || + r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + } + function __param(paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; + } + function __esDecorate( + ctor, + descriptorIn, + decorators, + contextIn, + initializers, + extraInitializers + ) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") + throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, + key = + kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = + !descriptorIn && ctor + ? contextIn["static"] + ? ctor + : ctor.prototype + : null; + var descriptor = + descriptorIn || + (target + ? Object.getOwnPropertyDescriptor(target, contextIn.name) + : {}); + var _, + done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) + context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) + context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { + if (done) + throw new TypeError( + "Cannot add initializers after decoration has completed" + ); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])( + kind === "accessor" + ? { + get: descriptor.get, + set: descriptor.set, + } + : descriptor[key], + context + ); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") + throw new TypeError("Object expected"); + if ((_ = accept(result.get))) descriptor.get = _; + if ((_ = accept(result.set))) descriptor.set = _; + if ((_ = accept(result.init))) initializers.unshift(_); + } else if ((_ = accept(result))) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + } + function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue + ? initializers[i].call(thisArg, value) + : initializers[i].call(thisArg); } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; + return useValue ? value : void 0; + } + function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); + } + function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") + name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { + configurable: true, + value: prefix ? "".concat(prefix, " ", name) : name, + }); + } + function __metadata(metadataKey, metadataValue) { + if ( + typeof Reflect === "object" && + typeof Reflect.metadata === "function" + ) + return Reflect.metadata(metadataKey, metadataValue); + } + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + } + function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { + next: verb(0), + throw: verb(1), + return: verb(2), + }), + typeof Symbol === "function" && + (g[Symbol.iterator] = function () { + return this; + }), + g + ); + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while ((g && ((g = 0), op[0] && (_ = 0)), _)) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y["return"] + : op[0] + ? y["throw"] || ((t = y["return"]) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { + value: op[1], + done: false, + }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true, + }; + } + } + var __createBinding = (exports.__createBinding = Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if ( + !desc || + ("get" in desc + ? !m.__esModule + : desc.writable || desc.configurable) + ) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + function __exportStar(m, o) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) + __createBinding(o, m, p); + } + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o, + }; + }, + }; + throw new TypeError( + s ? "Object is not iterable." : "Symbol.iterator is not defined." + ); + } + function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), + r, + ar = [], + e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) + ar.push(r.value); + } catch (error) { + e = { + error: error, + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + } + + /** @deprecated */ + function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + } + + /** @deprecated */ + function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) + s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + } + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) + for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + function __await(v) { + return this instanceof __await + ? ((this.v = v), this) + : new __await(v); + } + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function verb(n) { + if (g[n]) + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } + } + function __asyncDelegator(o) { + var i, p; + return ( + (i = {}), + verb("next"), + verb("throw", function (e) { + throw e; + }), + verb("return"), + (i[Symbol.iterator] = function () { + return this; + }), + i + ); + function verb(n, f) { + i[n] = o[n] + ? function (v) { + return (p = !p) + ? { + value: __await(o[n](v)), + done: false, + } + : f + ? f(v) + : v; + } + : f; + } + } + function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" + ? __values(o) + : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d, + }); + }, reject); + } + } + function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw, + }); + } else { + cooked.raw = raw; + } + return cooked; + } + var __setModuleDefault = Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v, + }); + } + : function (o, v) { + o["default"] = v; + }; + function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if ( + k !== "default" && + Object.prototype.hasOwnProperty.call(mod, k) + ) + __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + } + function __importDefault(mod) { + return mod && mod.__esModule + ? mod + : { + default: mod, + }; + } + function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError( + "Private accessor was defined without a getter" + ); + if ( + typeof state === "function" + ? receiver !== state || !f + : !state.has(receiver) + ) + throw new TypeError( + "Cannot read private member from an object whose class did not declare it" + ); + return kind === "m" + ? f + : kind === "a" + ? f.call(receiver) + : f + ? f.value + : state.get(receiver); + } + function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError( + "Private accessor was defined without a setter" + ); + if ( + typeof state === "function" + ? receiver !== state || !f + : !state.has(receiver) + ) + throw new TypeError( + "Cannot write private member to an object whose class did not declare it" + ); + return ( + kind === "a" + ? f.call(receiver, value) + : f + ? (f.value = value) + : state.set(receiver, value), + value + ); + } + function __classPrivateFieldIn(state, receiver) { + if ( + receiver === null || + (typeof receiver !== "object" && typeof receiver !== "function") + ) + throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" + ? receiver === state + : state.has(receiver); + } + function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") + throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) + throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) + throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") + throw new TypeError("Object not disposable."); + env.stack.push({ + value: value, + dispose: dispose, + async: async, + }); + } else if (async) { + env.stack.push({ + async: true, + }); + } + return value; + } + var _SuppressedError = + typeof SuppressedError === "function" + ? SuppressedError + : function (error, suppressed, message) { + var e = new Error(message); + return ( + (e.name = "SuppressedError"), + (e.error = error), + (e.suppressed = suppressed), + e + ); + }; + function __disposeResources(env) { + function fail(e) { + env.error = env.hasError + ? new _SuppressedError( + e, + env.error, + "An error was suppressed during disposal." + ) + : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) + return Promise.resolve(result).then(next, function (e) { + fail(e); + return next(); + }); + } catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { - value: op[0] ? op[1] : void 0, - done: true - }; - } -} -var __createBinding = exports.__createBinding = Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); -} : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}; -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, - m = s && o[s], - i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { - value: o && o[i++], - done: !o - }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), - r, - ar = [], - e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error) { - e = { - error: error - }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; -} - -/** @deprecated */ -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); - return ar; -} - -/** @deprecated */ -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; - return r; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function () { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function (v) { - return (p = !p) ? { - value: __await(o[n](v)), - done: false - } : f ? f(v) : v; - } : f; - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function (v) { - return new Promise(function (resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { - value: raw - }); - } else { - cooked.raw = raw; - } - return cooked; -} -; -var __setModuleDefault = Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); -} : function (o, v) { - o["default"] = v; -}; -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { - default: mod - }; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - env.stack.push({ - value: value, - dispose: dispose, - async: async - }); - } else if (async) { - env.stack.push({ - async: true - }); - } - return value; -} -var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - function next() { - while (env.stack.length) { - var rec = env.stack.pop(); - try { - var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) return Promise.resolve(result).then(next, function (e) { - fail(e); return next(); + } + var _default = (exports["default"] = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, }); - } catch (e) { - fail(e); - } - } - if (env.hasError) throw env.error; - } - return next(); -} -var _default = exports["default"] = { - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources -}; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js": -/*!***********************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js": + /*!***********************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/assignRef.js ***! \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.assignRef = assignRef; -/** - * Assigns a value for a given ref, no matter of the ref format - * @param {RefObject} ref - a callback function or ref object - * @param value - a new value - * - * @see https://github.com/theKashey/use-callback-ref#assignref - * @example - * const refObject = useRef(); - * const refFn = (ref) => {....} - * - * assignRef(refObject, "refValue"); - * assignRef(refFn, "refValue"); - */ -function assignRef(ref, value) { - if (typeof ref === 'function') { - ref(value); - } else if (ref) { - ref.current = value; - } - return ref; -} + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.assignRef = assignRef; + /** + * Assigns a value for a given ref, no matter of the ref format + * @param {RefObject} ref - a callback function or ref object + * @param value - a new value + * + * @see https://github.com/theKashey/use-callback-ref#assignref + * @example + * const refObject = useRef(); + * const refFn = (ref) => {....} + * + * assignRef(refObject, "refValue"); + * assignRef(refFn, "refValue"); + */ + function assignRef(ref, value) { + if (typeof ref === "function") { + ref(value); + } else if (ref) { + ref.current = value; + } + return ref; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js": -/*!***********************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js": + /*!***********************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/createRef.js ***! \***********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createCallbackRef = createCallbackRef; -/** - * creates a Ref object with on change callback - * @param callback - * @returns {RefObject} - * - * @see {@link useCallbackRef} - * @see https://reactjs.org/docs/refs-and-the-dom.html#creating-refs - */ -function createCallbackRef(callback) { - var current = null; - return { - get current() { - return current; - }, - set current(value) { - var last = current; - if (last !== value) { - current = value; - callback(value, last); - } - } - }; -} + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createCallbackRef = createCallbackRef; + /** + * creates a Ref object with on change callback + * @param callback + * @returns {RefObject} + * + * @see {@link useCallbackRef} + * @see https://reactjs.org/docs/refs-and-the-dom.html#creating-refs + */ + function createCallbackRef(callback) { + var current = null; + return { + get current() { + return current; + }, + set current(value) { + var last = current; + if (last !== value) { + current = value; + callback(value, last); + } + }, + }; + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/index.js": -/*!*******************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/index.js": + /*!*******************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/index.js ***! \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "assignRef", { + enumerable: true, + get: function () { + return _assignRef.assignRef; + }, + }); + Object.defineProperty(exports, "createCallbackRef", { + enumerable: true, + get: function () { + return _createRef.createCallbackRef; + }, + }); + Object.defineProperty(exports, "mergeRefs", { + enumerable: true, + get: function () { + return _mergeRef.mergeRefs; + }, + }); + Object.defineProperty(exports, "refToCallback", { + enumerable: true, + get: function () { + return _refToCallback.refToCallback; + }, + }); + Object.defineProperty(exports, "transformRef", { + enumerable: true, + get: function () { + return _transformRef.transformRef; + }, + }); + Object.defineProperty(exports, "useCallbackRef", { + enumerable: true, + get: function () { + return _useRef.useCallbackRef; + }, + }); + Object.defineProperty(exports, "useMergeRefs", { + enumerable: true, + get: function () { + return _useMergeRef.useMergeRefs; + }, + }); + Object.defineProperty(exports, "useRefToCallback", { + enumerable: true, + get: function () { + return _refToCallback.useRefToCallback; + }, + }); + Object.defineProperty(exports, "useTransformRef", { + enumerable: true, + get: function () { + return _useTransformRef.useTransformRef; + }, + }); + var _assignRef = __webpack_require__( + /*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js" + ); + var _useRef = __webpack_require__( + /*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js" + ); + var _createRef = __webpack_require__( + /*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js" + ); + var _mergeRef = __webpack_require__( + /*! ./mergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js" + ); + var _useMergeRef = __webpack_require__( + /*! ./useMergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js" + ); + var _useTransformRef = __webpack_require__( + /*! ./useTransformRef */ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js" + ); + var _transformRef = __webpack_require__( + /*! ./transformRef */ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js" + ); + var _refToCallback = __webpack_require__( + /*! ./refToCallback */ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js" + ); + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "assignRef", ({ - enumerable: true, - get: function () { - return _assignRef.assignRef; - } -})); -Object.defineProperty(exports, "createCallbackRef", ({ - enumerable: true, - get: function () { - return _createRef.createCallbackRef; - } -})); -Object.defineProperty(exports, "mergeRefs", ({ - enumerable: true, - get: function () { - return _mergeRef.mergeRefs; - } -})); -Object.defineProperty(exports, "refToCallback", ({ - enumerable: true, - get: function () { - return _refToCallback.refToCallback; - } -})); -Object.defineProperty(exports, "transformRef", ({ - enumerable: true, - get: function () { - return _transformRef.transformRef; - } -})); -Object.defineProperty(exports, "useCallbackRef", ({ - enumerable: true, - get: function () { - return _useRef.useCallbackRef; - } -})); -Object.defineProperty(exports, "useMergeRefs", ({ - enumerable: true, - get: function () { - return _useMergeRef.useMergeRefs; - } -})); -Object.defineProperty(exports, "useRefToCallback", ({ - enumerable: true, - get: function () { - return _refToCallback.useRefToCallback; - } -})); -Object.defineProperty(exports, "useTransformRef", ({ - enumerable: true, - get: function () { - return _useTransformRef.useTransformRef; - } -})); -var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); -var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); -var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); -var _mergeRef = __webpack_require__(/*! ./mergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js"); -var _useMergeRef = __webpack_require__(/*! ./useMergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js"); -var _useTransformRef = __webpack_require__(/*! ./useTransformRef */ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js"); -var _transformRef = __webpack_require__(/*! ./transformRef */ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js"); -var _refToCallback = __webpack_require__(/*! ./refToCallback */ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js"); - -/***/ }), - -/***/ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js": -/*!**********************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js": + /*!**********************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js ***! \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.mergeRefs = mergeRefs; -var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); -var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); -/** - * Merges two or more refs together providing a single interface to set their value - * @param {RefObject|Ref} refs - * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} - * - * @see {@link useMergeRefs} to be used in ReactComponents - * @example - * const Component = React.forwardRef((props, ref) => { - * const ownRef = useRef(); - * const domRef = mergeRefs([ref, ownRef]); // 👈 merge together - * return
...
- * } - */ -function mergeRefs(refs) { - return (0, _createRef.createCallbackRef)(function (newValue) { - return refs.forEach(function (ref) { - return (0, _assignRef.assignRef)(ref, newValue); - }); - }); -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.mergeRefs = mergeRefs; + var _assignRef = __webpack_require__( + /*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js" + ); + var _createRef = __webpack_require__( + /*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js" + ); + /** + * Merges two or more refs together providing a single interface to set their value + * @param {RefObject|Ref} refs + * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} + * + * @see {@link useMergeRefs} to be used in ReactComponents + * @example + * const Component = React.forwardRef((props, ref) => { + * const ownRef = useRef(); + * const domRef = mergeRefs([ref, ownRef]); // 👈 merge together + * return
...
+ * } + */ + function mergeRefs(refs) { + return (0, _createRef.createCallbackRef)(function (newValue) { + return refs.forEach(function (ref) { + return (0, _assignRef.assignRef)(ref, newValue); + }); + }); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js": -/*!***************************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js": + /*!***************************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js ***! \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.refToCallback = refToCallback; -exports.useRefToCallback = useRefToCallback; -/** - * Unmemoized version of {@link useRefToCallback} - * @see {@link useRefToCallback} - * @param ref - */ -function refToCallback(ref) { - return function (newValue) { - if (typeof ref === 'function') { - ref(newValue); - } else if (ref) { - ref.current = newValue; - } - }; -} -var nullCallback = function () { - return null; -}; -// lets maintain a weak ref to, well, ref :) -// not using `kashe` to keep this package small -var weakMem = new WeakMap(); -var weakMemoize = function (ref) { - var usedRef = ref || nullCallback; - var storedRef = weakMem.get(usedRef); - if (storedRef) { - return storedRef; - } - var cb = refToCallback(usedRef); - weakMem.set(usedRef, cb); - return cb; -}; -/** - * Transforms a given `ref` into `callback`. - * - * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)} - * - * @param {ReactRef} ref - * @returns {Function} - * - * @see https://github.com/theKashey/use-callback-ref#reftocallback - * - * @example - * const ref = useRef(0); - * const setRef = useRefToCallback(ref); - * 👉 setRef(10); - * ✅ ref.current === 10 - */ -function useRefToCallback(ref) { - return weakMemoize(ref); -} - -/***/ }), - -/***/ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js": -/*!**************************************************************************!*\ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.refToCallback = refToCallback; + exports.useRefToCallback = useRefToCallback; + /** + * Unmemoized version of {@link useRefToCallback} + * @see {@link useRefToCallback} + * @param ref + */ + function refToCallback(ref) { + return function (newValue) { + if (typeof ref === "function") { + ref(newValue); + } else if (ref) { + ref.current = newValue; + } + }; + } + var nullCallback = function () { + return null; + }; + // lets maintain a weak ref to, well, ref :) + // not using `kashe` to keep this package small + var weakMem = new WeakMap(); + var weakMemoize = function (ref) { + var usedRef = ref || nullCallback; + var storedRef = weakMem.get(usedRef); + if (storedRef) { + return storedRef; + } + var cb = refToCallback(usedRef); + weakMem.set(usedRef, cb); + return cb; + }; + /** + * Transforms a given `ref` into `callback`. + * + * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)} + * + * @param {ReactRef} ref + * @returns {Function} + * + * @see https://github.com/theKashey/use-callback-ref#reftocallback + * + * @example + * const ref = useRef(0); + * const setRef = useRefToCallback(ref); + * 👉 setRef(10); + * ✅ ref.current === 10 + */ + function useRefToCallback(ref) { + return weakMemoize(ref); + } + + /***/ + }, + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js": + /*!**************************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/transformRef.js ***! \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.transformRef = transformRef; -var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); -var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); -/** - * Transforms one ref to another - * @example - * ```tsx - * const ResizableWithRef = forwardRef((props, ref) => - * i ? i.resizable : null)}/> - * ); - * ``` - */ -function transformRef(ref, transformer) { - return (0, _createRef.createCallbackRef)(function (value) { - return (0, _assignRef.assignRef)(ref, transformer(value)); - }); -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.transformRef = transformRef; + var _assignRef = __webpack_require__( + /*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js" + ); + var _createRef = __webpack_require__( + /*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js" + ); + /** + * Transforms one ref to another + * @example + * ```tsx + * const ResizableWithRef = forwardRef((props, ref) => + * i ? i.resizable : null)}/> + * ); + * ``` + */ + function transformRef(ref, transformer) { + return (0, _createRef.createCallbackRef)(function (value) { + return (0, _assignRef.assignRef)(ref, transformer(value)); + }); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js": -/*!*************************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js": + /*!*************************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js ***! \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.useMergeRefs = useMergeRefs; -var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); -var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); -/** - * Merges two or more refs together providing a single interface to set their value - * @param {RefObject|Ref} refs - * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} - * - * @see {@link mergeRefs} a version without buit-in memoization - * @see https://github.com/theKashey/use-callback-ref#usemergerefs - * @example - * const Component = React.forwardRef((props, ref) => { - * const ownRef = useRef(); - * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together - * return
...
- * } - */ -function useMergeRefs(refs, defaultValue) { - return (0, _useRef.useCallbackRef)(defaultValue || null, function (newValue) { - return refs.forEach(function (ref) { - return (0, _assignRef.assignRef)(ref, newValue); - }); - }); -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.useMergeRefs = useMergeRefs; + var _assignRef = __webpack_require__( + /*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js" + ); + var _useRef = __webpack_require__( + /*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js" + ); + /** + * Merges two or more refs together providing a single interface to set their value + * @param {RefObject|Ref} refs + * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} + * + * @see {@link mergeRefs} a version without buit-in memoization + * @see https://github.com/theKashey/use-callback-ref#usemergerefs + * @example + * const Component = React.forwardRef((props, ref) => { + * const ownRef = useRef(); + * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together + * return
...
+ * } + */ + function useMergeRefs(refs, defaultValue) { + return (0, _useRef.useCallbackRef)( + defaultValue || null, + function (newValue) { + return refs.forEach(function (ref) { + return (0, _assignRef.assignRef)(ref, newValue); + }); + } + ); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js": -/*!********************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js": + /*!********************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/useRef.js ***! \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.useCallbackRef = useCallbackRef; -var _react = __webpack_require__(/*! react */ "react"); -/** - * creates a MutableRef with ref change callback - * @param initialValue - initial ref value - * @param {Function} callback - a callback to run when value changes - * - * @example - * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue); - * ref.current = 1; - * // prints 0 -> 1 - * - * @see https://reactjs.org/docs/hooks-reference.html#useref - * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref - * @returns {MutableRefObject} - */ -function useCallbackRef(initialValue, callback) { - var ref = (0, _react.useState)(function () { - return { - // value - value: initialValue, - // last callback - callback: callback, - // "memoized" public interface - facade: { - get current() { - return ref.value; - }, - set current(value) { - var last = ref.value; - if (last !== value) { - ref.value = value; - ref.callback(value, last); - } + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.useCallbackRef = useCallbackRef; + var _react = __webpack_require__(/*! react */ "react"); + /** + * creates a MutableRef with ref change callback + * @param initialValue - initial ref value + * @param {Function} callback - a callback to run when value changes + * + * @example + * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue); + * ref.current = 1; + * // prints 0 -> 1 + * + * @see https://reactjs.org/docs/hooks-reference.html#useref + * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref + * @returns {MutableRefObject} + */ + function useCallbackRef(initialValue, callback) { + var ref = (0, _react.useState)(function () { + return { + // value + value: initialValue, + // last callback + callback: callback, + // "memoized" public interface + facade: { + get current() { + return ref.value; + }, + set current(value) { + var last = ref.value; + if (last !== value) { + ref.value = value; + ref.callback(value, last); + } + }, + }, + }; + })[0]; + // update callback + ref.callback = callback; + return ref.facade; } - } - }; - })[0]; - // update callback - ref.callback = callback; - return ref.facade; -} -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js": -/*!*****************************************************************************!*\ + /***/ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js": + /*!*****************************************************************************!*\ !*** ../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js ***! \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.useTransformRef = useTransformRef; -var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); -var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); -/** - * Create a _lense_ on Ref, making it possible to transform ref value - * @param {ReactRef} ref - * @param {Function} transformer. 👉 Ref would be __NOT updated__ on `transformer` update. - * @returns {RefObject} - * - * @see https://github.com/theKashey/use-callback-ref#usetransformref-to-replace-reactuseimperativehandle - * @example - * - * const ResizableWithRef = forwardRef((props, ref) => - * i ? i.resizable : null)}/> - * ); - */ -function useTransformRef(ref, transformer) { - return (0, _useRef.useCallbackRef)(null, function (value) { - return (0, _assignRef.assignRef)(ref, transformer(value)); - }); -} + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.useTransformRef = useTransformRef; + var _assignRef = __webpack_require__( + /*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js" + ); + var _useRef = __webpack_require__( + /*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js" + ); + /** + * Create a _lense_ on Ref, making it possible to transform ref value + * @param {ReactRef} ref + * @param {Function} transformer. 👉 Ref would be __NOT updated__ on `transformer` update. + * @returns {RefObject} + * + * @see https://github.com/theKashey/use-callback-ref#usetransformref-to-replace-reactuseimperativehandle + * @example + * + * const ResizableWithRef = forwardRef((props, ref) => + * i ? i.resizable : null)}/> + * ); + */ + function useTransformRef(ref, transformer) { + return (0, _useRef.useCallbackRef)(null, function (value) { + return (0, _assignRef.assignRef)(ref, transformer(value)); + }); + } -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-sidecar/dist/es2015/config.js": -/*!***************************************************************!*\ + /***/ "../../../node_modules/use-sidecar/dist/es2015/config.js": + /*!***************************************************************!*\ !*** ../../../node_modules/use-sidecar/dist/es2015/config.js ***! \***************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.setConfig = exports.config = void 0; -var config = exports.config = { - onError: function (e) { - return console.error(e); - } -}; -var setConfig = function (conf) { - Object.assign(config, conf); -}; -exports.setConfig = setConfig; + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.setConfig = exports.config = void 0; + var config = (exports.config = { + onError: function (e) { + return console.error(e); + }, + }); + var setConfig = function (conf) { + Object.assign(config, conf); + }; + exports.setConfig = setConfig; -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-sidecar/dist/es2015/env.js": -/*!************************************************************!*\ + /***/ "../../../node_modules/use-sidecar/dist/es2015/env.js": + /*!************************************************************!*\ !*** ../../../node_modules/use-sidecar/dist/es2015/env.js ***! \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.env = void 0; -var _detectNodeEs = __webpack_require__(/*! detect-node-es */ "../../../node_modules/detect-node-es/esm/browser.js"); -var env = exports.env = { - isNode: _detectNodeEs.isNode, - forceCache: false -}; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.env = void 0; + var _detectNodeEs = __webpack_require__( + /*! detect-node-es */ "../../../node_modules/detect-node-es/esm/browser.js" + ); + var env = (exports.env = { + isNode: _detectNodeEs.isNode, + forceCache: false, + }); -/***/ }), + /***/ + }, -/***/ "../../../node_modules/use-sidecar/dist/es2015/exports.js": -/*!****************************************************************!*\ + /***/ "../../../node_modules/use-sidecar/dist/es2015/exports.js": + /*!****************************************************************!*\ !*** ../../../node_modules/use-sidecar/dist/es2015/exports.js ***! \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.exportSidecar = exportSidecar; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -var SideCar = function (_a) { - var sideCar = _a.sideCar, - rest = (0, _tslib.__rest)(_a, ["sideCar"]); - if (!sideCar) { - throw new Error('Sidecar: please provide `sideCar` property to import the right car'); - } - var Target = sideCar.read(); - if (!Target) { - throw new Error('Sidecar medium not found'); - } - return /*#__PURE__*/React.createElement(Target, (0, _tslib.__assign)({}, rest)); -}; -SideCar.isSideCarExport = true; -function exportSidecar(medium, exported) { - medium.useMedium(exported); - return SideCar; -} - -/***/ }), - -/***/ "../../../node_modules/use-sidecar/dist/es2015/hoc.js": -/*!************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/hoc.js ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.sidecar = sidecar; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -// eslint-disable-next-line @typescript-eslint/ban-types -function sidecar(importer, errorComponent) { - var ErrorCase = function () { - return errorComponent; - }; - return function Sidecar(props) { - var _a = (0, _hook.useSidecar)(importer, props.sideCar), - Car = _a[0], - error = _a[1]; - if (error && errorComponent) { - return ErrorCase; - } - // @ts-expect-error type shenanigans - return Car ? /*#__PURE__*/React.createElement(Car, (0, _tslib.__assign)({}, props)) : null; - }; -} - -/***/ }), - -/***/ "../../../node_modules/use-sidecar/dist/es2015/hook.js": -/*!*************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/hook.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.useSidecar = useSidecar; -var _react = __webpack_require__(/*! react */ "react"); -var _env = __webpack_require__(/*! ./env */ "../../../node_modules/use-sidecar/dist/es2015/env.js"); -var cache = new WeakMap(); -var NO_OPTIONS = {}; -function useSidecar(importer, effect) { - var options = effect && effect.options || NO_OPTIONS; - if (_env.env.isNode && !options.ssr) { - return [null, null]; - } - // eslint-disable-next-line react-hooks/rules-of-hooks - return useRealSidecar(importer, effect); -} -function useRealSidecar(importer, effect) { - var options = effect && effect.options || NO_OPTIONS; - var couldUseCache = _env.env.forceCache || _env.env.isNode && !!options.ssr || !options.async; - var _a = (0, _react.useState)(couldUseCache ? function () { - return cache.get(importer); - } : undefined), - Car = _a[0], - setCar = _a[1]; - var _b = (0, _react.useState)(null), - error = _b[0], - setError = _b[1]; - (0, _react.useEffect)(function () { - if (!Car) { - importer().then(function (car) { - var resolved = effect ? effect.read() : car.default || car; - if (!resolved) { - console.error('Sidecar error: with importer', importer); - var error_1; - if (effect) { - console.error('Sidecar error: with medium', effect); - error_1 = new Error('Sidecar medium was not found'); - } else { - error_1 = new Error('Sidecar was not found in exports'); - } - setError(function () { - return error_1; - }); - throw error_1; - } - cache.set(importer, resolved); - setCar(function () { - return resolved; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - }, function (e) { - return setError(function () { - return e; - }); - }); - } - }, []); - return [Car, error]; -} - -/***/ }), - -/***/ "../../../node_modules/use-sidecar/dist/es2015/index.js": -/*!**************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/index.js ***! - \**************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createMedium", ({ - enumerable: true, - get: function () { - return _medium.createMedium; - } -})); -Object.defineProperty(exports, "createSidecarMedium", ({ - enumerable: true, - get: function () { - return _medium.createSidecarMedium; - } -})); -Object.defineProperty(exports, "exportSidecar", ({ - enumerable: true, - get: function () { - return _exports.exportSidecar; - } -})); -Object.defineProperty(exports, "renderCar", ({ - enumerable: true, - get: function () { - return _renderProp.renderCar; - } -})); -Object.defineProperty(exports, "setConfig", ({ - enumerable: true, - get: function () { - return _config.setConfig; - } -})); -Object.defineProperty(exports, "sidecar", ({ - enumerable: true, - get: function () { - return _hoc.sidecar; - } -})); -Object.defineProperty(exports, "useSidecar", ({ - enumerable: true, - get: function () { - return _hook.useSidecar; - } -})); -var _hoc = __webpack_require__(/*! ./hoc */ "../../../node_modules/use-sidecar/dist/es2015/hoc.js"); -var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); -var _config = __webpack_require__(/*! ./config */ "../../../node_modules/use-sidecar/dist/es2015/config.js"); -var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/use-sidecar/dist/es2015/medium.js"); -var _renderProp = __webpack_require__(/*! ./renderProp */ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js"); -var _exports = __webpack_require__(/*! ./exports */ "../../../node_modules/use-sidecar/dist/es2015/exports.js"); - -/***/ }), - -/***/ "../../../node_modules/use-sidecar/dist/es2015/medium.js": -/*!***************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/medium.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createMedium = createMedium; -exports.createSidecarMedium = createSidecarMedium; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -function ItoI(a) { - return a; -} -function innerCreateMedium(defaults, middleware) { - if (middleware === void 0) { - middleware = ItoI; - } - var buffer = []; - var assigned = false; - var medium = { - read: function () { - if (assigned) { - throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.'); - } - if (buffer.length) { - return buffer[buffer.length - 1]; - } - return defaults; - }, - useMedium: function (data) { - var item = middleware(data, assigned); - buffer.push(item); - return function () { - buffer = buffer.filter(function (x) { - return x !== item; - }); - }; - }, - assignSyncMedium: function (cb) { - assigned = true; - while (buffer.length) { - var cbs = buffer; - buffer = []; - cbs.forEach(cb); - } - buffer = { - push: function (x) { - return cb(x); - }, - filter: function () { - return buffer; - } - }; - }, - assignMedium: function (cb) { - assigned = true; - var pendingQueue = []; - if (buffer.length) { - var cbs = buffer; - buffer = []; - cbs.forEach(cb); - pendingQueue = buffer; - } - var executeQueue = function () { - var cbs = pendingQueue; - pendingQueue = []; - cbs.forEach(cb); - }; - var cycle = function () { - return Promise.resolve().then(executeQueue); - }; - cycle(); - buffer = { - push: function (x) { - pendingQueue.push(x); - cycle(); - }, - filter: function (filter) { - pendingQueue = pendingQueue.filter(filter); - return buffer; - } - }; - } - }; - return medium; -} -function createMedium(defaults, middleware) { - if (middleware === void 0) { - middleware = ItoI; - } - return innerCreateMedium(defaults, middleware); -} -// eslint-disable-next-line @typescript-eslint/ban-types -function createSidecarMedium(options) { - if (options === void 0) { - options = {}; - } - var medium = innerCreateMedium(null); - medium.options = (0, _tslib.__assign)({ - async: true, - ssr: false - }, options); - return medium; -} - -/***/ }), - -/***/ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js": -/*!*******************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/renderProp.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.renderCar = renderCar; -var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); -var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var React = _react; -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -function renderCar(WrappedComponent, defaults) { - function State(_a) { - var stateRef = _a.stateRef, - props = _a.props; - var renderTarget = (0, _react.useCallback)(function SideTarget() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - (0, _react.useLayoutEffect)(function () { - stateRef.current(args); - }); - return null; - }, []); - // @ts-ignore - return /*#__PURE__*/React.createElement(WrappedComponent, (0, _tslib.__assign)({}, props, { - children: renderTarget - })); - } - var Children = /*#__PURE__*/React.memo(function (_a) { - var stateRef = _a.stateRef, - defaultState = _a.defaultState, - children = _a.children; - var _b = (0, _react.useState)(defaultState.current), - state = _b[0], - setState = _b[1]; - (0, _react.useEffect)(function () { - stateRef.current = setState; - }, []); - return children.apply(void 0, state); - }, function () { - return true; - }); - return function Combiner(props) { - var defaultState = React.useRef(defaults(props)); - var ref = React.useRef(function (state) { - return defaultState.current = state; - }); - return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(State, { - stateRef: ref, - props: props - }), /*#__PURE__*/React.createElement(Children, { - stateRef: ref, - defaultState: defaultState, - children: props.children - })); - }; -} - -/***/ }), - -/***/ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js": -/*!*************************************************************************!*\ - !*** ../../../node_modules/vscode-languageserver-types/lib/esm/main.js ***! - \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -/* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.uinteger = exports.integer = exports.WorkspaceSymbol = exports.WorkspaceFolder = exports.WorkspaceEdit = exports.WorkspaceChange = exports.VersionedTextDocumentIdentifier = exports.URI = exports.TextEdit = exports.TextDocumentItem = exports.TextDocumentIdentifier = exports.TextDocumentEdit = exports.TextDocument = exports.SymbolTag = exports.SymbolKind = exports.SymbolInformation = exports.SignatureInformation = exports.SemanticTokens = exports.SemanticTokenTypes = exports.SemanticTokenModifiers = exports.SelectionRange = exports.RenameFile = exports.Range = exports.Position = exports.ParameterInformation = exports.OptionalVersionedTextDocumentIdentifier = exports.MarkupKind = exports.MarkupContent = exports.MarkedString = exports.LocationLink = exports.Location = exports.InsertTextMode = exports.InsertTextFormat = exports.InsertReplaceEdit = exports.InlineValueVariableLookup = exports.InlineValueText = exports.InlineValueEvaluatableExpression = exports.InlineValueContext = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlayHint = exports.Hover = exports.FormattingOptions = exports.FoldingRangeKind = exports.FoldingRange = exports.EOL = exports.DocumentUri = exports.DocumentSymbol = exports.DocumentLink = exports.DocumentHighlightKind = exports.DocumentHighlight = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.Diagnostic = exports.DeleteFile = exports.CreateFile = exports.CompletionList = exports.CompletionItemTag = exports.CompletionItemLabelDetails = exports.CompletionItemKind = exports.CompletionItem = exports.Command = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.CodeLens = exports.CodeDescription = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.CodeActionContext = exports.CodeAction = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.AnnotatedTextEdit = void 0; -var DocumentUri; -(function (DocumentUri) { - function is(value) { - return typeof value === 'string'; - } - DocumentUri.is = is; -})(DocumentUri || (exports.DocumentUri = DocumentUri = {})); -var URI; -(function (URI) { - function is(value) { - return typeof value === 'string'; - } - URI.is = is; -})(URI || (exports.URI = URI = {})); -var integer; -(function (integer) { - integer.MIN_VALUE = -2147483648; - integer.MAX_VALUE = 2147483647; - function is(value) { - return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE; - } - integer.is = is; -})(integer || (exports.integer = integer = {})); -var uinteger; -(function (uinteger) { - uinteger.MIN_VALUE = 0; - uinteger.MAX_VALUE = 2147483647; - function is(value) { - return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE; - } - uinteger.is = is; -})(uinteger || (exports.uinteger = uinteger = {})); -/** - * The Position namespace provides helper functions to work with - * {@link Position} literals. - */ -var Position; -(function (Position) { - /** - * Creates a new Position literal from the given line and character. - * @param line The position's line. - * @param character The position's character. - */ - function create(line, character) { - if (line === Number.MAX_VALUE) { - line = uinteger.MAX_VALUE; - } - if (character === Number.MAX_VALUE) { - character = uinteger.MAX_VALUE; - } - return { - line: line, - character: character - }; - } - Position.create = create; - /** - * Checks whether the given literal conforms to the {@link Position} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); - } - Position.is = is; -})(Position || (exports.Position = Position = {})); -/** - * The Range namespace provides helper functions to work with - * {@link Range} literals. - */ -var Range; -(function (Range) { - function create(one, two, three, four) { - if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { - return { - start: Position.create(one, two), - end: Position.create(three, four) - }; - } else if (Position.is(one) && Position.is(two)) { - return { - start: one, - end: two - }; - } else { - throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]")); - } - } - Range.create = create; - /** - * Checks whether the given literal conforms to the {@link Range} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); - } - Range.is = is; -})(Range || (exports.Range = Range = {})); -/** - * The Location namespace provides helper functions to work with - * {@link Location} literals. - */ -var Location; -(function (Location) { - /** - * Creates a Location literal. - * @param uri The location's uri. - * @param range The location's range. - */ - function create(uri, range) { - return { - uri: uri, - range: range - }; - } - Location.create = create; - /** - * Checks whether the given literal conforms to the {@link Location} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); - } - Location.is = is; -})(Location || (exports.Location = Location = {})); -/** - * The LocationLink namespace provides helper functions to work with - * {@link LocationLink} literals. - */ -var LocationLink; -(function (LocationLink) { - /** - * Creates a LocationLink literal. - * @param targetUri The definition's uri. - * @param targetRange The full range of the definition. - * @param targetSelectionRange The span of the symbol definition at the target. - * @param originSelectionRange The span of the symbol being defined in the originating source file. - */ - function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { - return { - targetUri: targetUri, - targetRange: targetRange, - targetSelectionRange: targetSelectionRange, - originSelectionRange: originSelectionRange - }; - } - LocationLink.create = create; - /** - * Checks whether the given literal conforms to the {@link LocationLink} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); - } - LocationLink.is = is; -})(LocationLink || (exports.LocationLink = LocationLink = {})); -/** - * The Color namespace provides helper functions to work with - * {@link Color} literals. - */ -var Color; -(function (Color) { - /** - * Creates a new Color literal. - */ - function create(red, green, blue, alpha) { - return { - red: red, - green: green, - blue: blue, - alpha: alpha - }; - } - Color.create = create; - /** - * Checks whether the given literal conforms to the {@link Color} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); - } - Color.is = is; -})(Color || (exports.Color = Color = {})); -/** - * The ColorInformation namespace provides helper functions to work with - * {@link ColorInformation} literals. - */ -var ColorInformation; -(function (ColorInformation) { - /** - * Creates a new ColorInformation literal. - */ - function create(range, color) { - return { - range: range, - color: color - }; - } - ColorInformation.create = create; - /** - * Checks whether the given literal conforms to the {@link ColorInformation} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color); - } - ColorInformation.is = is; -})(ColorInformation || (exports.ColorInformation = ColorInformation = {})); -/** - * The Color namespace provides helper functions to work with - * {@link ColorPresentation} literals. - */ -var ColorPresentation; -(function (ColorPresentation) { - /** - * Creates a new ColorInformation literal. - */ - function create(label, textEdit, additionalTextEdits) { - return { - label: label, - textEdit: textEdit, - additionalTextEdits: additionalTextEdits - }; - } - ColorPresentation.create = create; - /** - * Checks whether the given literal conforms to the {@link ColorInformation} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); - } - ColorPresentation.is = is; -})(ColorPresentation || (exports.ColorPresentation = ColorPresentation = {})); -/** - * A set of predefined range kinds. - */ -var FoldingRangeKind; -(function (FoldingRangeKind) { - /** - * Folding range for a comment - */ - FoldingRangeKind.Comment = 'comment'; - /** - * Folding range for an import or include - */ - FoldingRangeKind.Imports = 'imports'; - /** - * Folding range for a region (e.g. `#region`) - */ - FoldingRangeKind.Region = 'region'; -})(FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {})); -/** - * The folding range namespace provides helper functions to work with - * {@link FoldingRange} literals. - */ -var FoldingRange; -(function (FoldingRange) { - /** - * Creates a new FoldingRange literal. - */ - function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) { - var result = { - startLine: startLine, - endLine: endLine - }; - if (Is.defined(startCharacter)) { - result.startCharacter = startCharacter; - } - if (Is.defined(endCharacter)) { - result.endCharacter = endCharacter; - } - if (Is.defined(kind)) { - result.kind = kind; - } - if (Is.defined(collapsedText)) { - result.collapsedText = collapsedText; - } - return result; - } - FoldingRange.create = create; - /** - * Checks whether the given literal conforms to the {@link FoldingRange} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); - } - FoldingRange.is = is; -})(FoldingRange || (exports.FoldingRange = FoldingRange = {})); -/** - * The DiagnosticRelatedInformation namespace provides helper functions to work with - * {@link DiagnosticRelatedInformation} literals. - */ -var DiagnosticRelatedInformation; -(function (DiagnosticRelatedInformation) { - /** - * Creates a new DiagnosticRelatedInformation literal. - */ - function create(location, message) { - return { - location: location, - message: message - }; - } - DiagnosticRelatedInformation.create = create; - /** - * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); - } - DiagnosticRelatedInformation.is = is; -})(DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {})); -/** - * The diagnostic's severity. - */ -var DiagnosticSeverity; -(function (DiagnosticSeverity) { - /** - * Reports an error. - */ - DiagnosticSeverity.Error = 1; - /** - * Reports a warning. - */ - DiagnosticSeverity.Warning = 2; - /** - * Reports an information. - */ - DiagnosticSeverity.Information = 3; - /** - * Reports a hint. - */ - DiagnosticSeverity.Hint = 4; -})(DiagnosticSeverity || (exports.DiagnosticSeverity = DiagnosticSeverity = {})); -/** - * The diagnostic tags. - * - * @since 3.15.0 - */ -var DiagnosticTag; -(function (DiagnosticTag) { - /** - * Unused or unnecessary code. - * - * Clients are allowed to render diagnostics with this tag faded out instead of having - * an error squiggle. - */ - DiagnosticTag.Unnecessary = 1; - /** - * Deprecated or obsolete code. - * - * Clients are allowed to rendered diagnostics with this tag strike through. - */ - DiagnosticTag.Deprecated = 2; -})(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {})); -/** - * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. - * - * @since 3.16.0 - */ -var CodeDescription; -(function (CodeDescription) { - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.href); - } - CodeDescription.is = is; -})(CodeDescription || (exports.CodeDescription = CodeDescription = {})); -/** - * The Diagnostic namespace provides helper functions to work with - * {@link Diagnostic} literals. - */ -var Diagnostic; -(function (Diagnostic) { - /** - * Creates a new Diagnostic literal. - */ - function create(range, message, severity, code, source, relatedInformation) { - var result = { - range: range, - message: message - }; - if (Is.defined(severity)) { - result.severity = severity; - } - if (Is.defined(code)) { - result.code = code; - } - if (Is.defined(source)) { - result.source = source; - } - if (Is.defined(relatedInformation)) { - result.relatedInformation = relatedInformation; - } - return result; - } - Diagnostic.create = create; - /** - * Checks whether the given literal conforms to the {@link Diagnostic} interface. - */ - function is(value) { - var _a; - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); - } - Diagnostic.is = is; -})(Diagnostic || (exports.Diagnostic = Diagnostic = {})); -/** - * The Command namespace provides helper functions to work with - * {@link Command} literals. - */ -var Command; -(function (Command) { - /** - * Creates a new Command literal. - */ - function create(title, command) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var result = { - title: title, - command: command - }; - if (Is.defined(args) && args.length > 0) { - result.arguments = args; - } - return result; - } - Command.create = create; - /** - * Checks whether the given literal conforms to the {@link Command} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); - } - Command.is = is; -})(Command || (exports.Command = Command = {})); -/** - * The TextEdit namespace provides helper function to create replace, - * insert and delete edits more easily. - */ -var TextEdit; -(function (TextEdit) { - /** - * Creates a replace text edit. - * @param range The range of text to be replaced. - * @param newText The new text. - */ - function replace(range, newText) { - return { - range: range, - newText: newText - }; - } - TextEdit.replace = replace; - /** - * Creates an insert text edit. - * @param position The position to insert the text at. - * @param newText The text to be inserted. - */ - function insert(position, newText) { - return { - range: { - start: position, - end: position + exports.exportSidecar = exportSidecar; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + var SideCar = function (_a) { + var sideCar = _a.sideCar, + rest = (0, _tslib.__rest)(_a, ["sideCar"]); + if (!sideCar) { + throw new Error( + "Sidecar: please provide `sideCar` property to import the right car" + ); + } + var Target = sideCar.read(); + if (!Target) { + throw new Error("Sidecar medium not found"); + } + return /*#__PURE__*/ React.createElement( + Target, + (0, _tslib.__assign)({}, rest) + ); + }; + SideCar.isSideCarExport = true; + function exportSidecar(medium, exported) { + medium.useMedium(exported); + return SideCar; + } + + /***/ }, - newText: newText - }; - } - TextEdit.insert = insert; - /** - * Creates a delete text edit. - * @param range The range of text to be deleted. - */ - function del(range) { - return { - range: range, - newText: '' - }; - } - TextEdit.del = del; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); - } - TextEdit.is = is; -})(TextEdit || (exports.TextEdit = TextEdit = {})); -var ChangeAnnotation; -(function (ChangeAnnotation) { - function create(label, needsConfirmation, description) { - var result = { - label: label - }; - if (needsConfirmation !== undefined) { - result.needsConfirmation = needsConfirmation; - } - if (description !== undefined) { - result.description = description; - } - return result; - } - ChangeAnnotation.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined); - } - ChangeAnnotation.is = is; -})(ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {})); -var ChangeAnnotationIdentifier; -(function (ChangeAnnotationIdentifier) { - function is(value) { - var candidate = value; - return Is.string(candidate); - } - ChangeAnnotationIdentifier.is = is; -})(ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {})); -var AnnotatedTextEdit; -(function (AnnotatedTextEdit) { - /** - * Creates an annotated replace text edit. - * - * @param range The range of text to be replaced. - * @param newText The new text. - * @param annotation The annotation. - */ - function replace(range, newText, annotation) { - return { - range: range, - newText: newText, - annotationId: annotation - }; - } - AnnotatedTextEdit.replace = replace; - /** - * Creates an annotated insert text edit. - * - * @param position The position to insert the text at. - * @param newText The text to be inserted. - * @param annotation The annotation. - */ - function insert(position, newText, annotation) { - return { - range: { - start: position, - end: position + + /***/ "../../../node_modules/use-sidecar/dist/es2015/hoc.js": + /*!************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/hoc.js ***! + \************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.sidecar = sidecar; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var React = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _hook = __webpack_require__( + /*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js" + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + // eslint-disable-next-line @typescript-eslint/ban-types + function sidecar(importer, errorComponent) { + var ErrorCase = function () { + return errorComponent; + }; + return function Sidecar(props) { + var _a = (0, _hook.useSidecar)(importer, props.sideCar), + Car = _a[0], + error = _a[1]; + if (error && errorComponent) { + return ErrorCase; + } + // @ts-expect-error type shenanigans + return Car + ? /*#__PURE__*/ React.createElement( + Car, + (0, _tslib.__assign)({}, props) + ) + : null; + }; + } + + /***/ }, - newText: newText, - annotationId: annotation - }; - } - AnnotatedTextEdit.insert = insert; - /** - * Creates an annotated delete text edit. - * - * @param range The range of text to be deleted. - * @param annotation The annotation. - */ - function del(range, annotation) { - return { - range: range, - newText: '', - annotationId: annotation - }; - } - AnnotatedTextEdit.del = del; - function is(value) { - var candidate = value; - return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - AnnotatedTextEdit.is = is; -})(AnnotatedTextEdit || (exports.AnnotatedTextEdit = AnnotatedTextEdit = {})); -/** - * The TextDocumentEdit namespace provides helper function to create - * an edit that manipulates a text document. - */ -var TextDocumentEdit; -(function (TextDocumentEdit) { - /** - * Creates a new `TextDocumentEdit` - */ - function create(textDocument, edits) { - return { - textDocument: textDocument, - edits: edits - }; - } - TextDocumentEdit.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); - } - TextDocumentEdit.is = is; -})(TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {})); -var CreateFile; -(function (CreateFile) { - function create(uri, options, annotation) { - var result = { - kind: 'create', - uri: uri - }; - if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { - result.options = options; - } - if (annotation !== undefined) { - result.annotationId = annotation; - } - return result; - } - CreateFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - CreateFile.is = is; -})(CreateFile || (exports.CreateFile = CreateFile = {})); -var RenameFile; -(function (RenameFile) { - function create(oldUri, newUri, options, annotation) { - var result = { - kind: 'rename', - oldUri: oldUri, - newUri: newUri - }; - if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { - result.options = options; - } - if (annotation !== undefined) { - result.annotationId = annotation; - } - return result; - } - RenameFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - RenameFile.is = is; -})(RenameFile || (exports.RenameFile = RenameFile = {})); -var DeleteFile; -(function (DeleteFile) { - function create(uri, options, annotation) { - var result = { - kind: 'delete', - uri: uri - }; - if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) { - result.options = options; - } - if (annotation !== undefined) { - result.annotationId = annotation; - } - return result; - } - DeleteFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - DeleteFile.is = is; -})(DeleteFile || (exports.DeleteFile = DeleteFile = {})); -var WorkspaceEdit; -(function (WorkspaceEdit) { - function is(value) { - var candidate = value; - return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) { - if (Is.string(change.kind)) { - return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); - } else { - return TextDocumentEdit.is(change); - } - })); - } - WorkspaceEdit.is = is; -})(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {})); -var TextEditChangeImpl = /** @class */function () { - function TextEditChangeImpl(edits, changeAnnotations) { - this.edits = edits; - this.changeAnnotations = changeAnnotations; - } - TextEditChangeImpl.prototype.insert = function (position, newText, annotation) { - var edit; - var id; - if (annotation === undefined) { - edit = TextEdit.insert(position, newText); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit = AnnotatedTextEdit.insert(position, newText, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit = AnnotatedTextEdit.insert(position, newText, id); - } - this.edits.push(edit); - if (id !== undefined) { - return id; - } - }; - TextEditChangeImpl.prototype.replace = function (range, newText, annotation) { - var edit; - var id; - if (annotation === undefined) { - edit = TextEdit.replace(range, newText); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit = AnnotatedTextEdit.replace(range, newText, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit = AnnotatedTextEdit.replace(range, newText, id); - } - this.edits.push(edit); - if (id !== undefined) { - return id; - } - }; - TextEditChangeImpl.prototype.delete = function (range, annotation) { - var edit; - var id; - if (annotation === undefined) { - edit = TextEdit.del(range); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit = AnnotatedTextEdit.del(range, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit = AnnotatedTextEdit.del(range, id); - } - this.edits.push(edit); - if (id !== undefined) { - return id; - } - }; - TextEditChangeImpl.prototype.add = function (edit) { - this.edits.push(edit); - }; - TextEditChangeImpl.prototype.all = function () { - return this.edits; - }; - TextEditChangeImpl.prototype.clear = function () { - this.edits.splice(0, this.edits.length); - }; - TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) { - if (value === undefined) { - throw new Error("Text edit change is not configured to manage change annotations."); - } - }; - return TextEditChangeImpl; -}(); -/** - * A helper class - */ -var ChangeAnnotations = /** @class */function () { - function ChangeAnnotations(annotations) { - this._annotations = annotations === undefined ? Object.create(null) : annotations; - this._counter = 0; - this._size = 0; - } - ChangeAnnotations.prototype.all = function () { - return this._annotations; - }; - Object.defineProperty(ChangeAnnotations.prototype, "size", { - get: function () { - return this._size; - }, - enumerable: false, - configurable: true - }); - ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) { - var id; - if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { - id = idOrAnnotation; - } else { - id = this.nextId(); - annotation = idOrAnnotation; - } - if (this._annotations[id] !== undefined) { - throw new Error("Id ".concat(id, " is already in use.")); - } - if (annotation === undefined) { - throw new Error("No annotation provided for id ".concat(id)); - } - this._annotations[id] = annotation; - this._size++; - return id; - }; - ChangeAnnotations.prototype.nextId = function () { - this._counter++; - return this._counter.toString(); - }; - return ChangeAnnotations; -}(); -/** - * A workspace change helps constructing changes to a workspace. - */ -var WorkspaceChange = exports.WorkspaceChange = /** @class */function () { - function WorkspaceChange(workspaceEdit) { - var _this = this; - this._textEditChanges = Object.create(null); - if (workspaceEdit !== undefined) { - this._workspaceEdit = workspaceEdit; - if (workspaceEdit.documentChanges) { - this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); - workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - workspaceEdit.documentChanges.forEach(function (change) { - if (TextDocumentEdit.is(change)) { - var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); - _this._textEditChanges[change.textDocument.uri] = textEditChange; - } - }); - } else if (workspaceEdit.changes) { - Object.keys(workspaceEdit.changes).forEach(function (key) { - var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); - _this._textEditChanges[key] = textEditChange; + + /***/ "../../../node_modules/use-sidecar/dist/es2015/hook.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/hook.js ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - } else { - this._workspaceEdit = {}; - } - } - Object.defineProperty(WorkspaceChange.prototype, "edit", { - /** - * Returns the underlying {@link WorkspaceEdit} literal - * use to be returned from a workspace edit operation like rename. - */ - get: function () { - this.initDocumentChanges(); - if (this._changeAnnotations !== undefined) { - if (this._changeAnnotations.size === 0) { - this._workspaceEdit.changeAnnotations = undefined; - } else { - this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + exports.useSidecar = useSidecar; + var _react = __webpack_require__(/*! react */ "react"); + var _env = __webpack_require__( + /*! ./env */ "../../../node_modules/use-sidecar/dist/es2015/env.js" + ); + var cache = new WeakMap(); + var NO_OPTIONS = {}; + function useSidecar(importer, effect) { + var options = (effect && effect.options) || NO_OPTIONS; + if (_env.env.isNode && !options.ssr) { + return [null, null]; + } + // eslint-disable-next-line react-hooks/rules-of-hooks + return useRealSidecar(importer, effect); + } + function useRealSidecar(importer, effect) { + var options = (effect && effect.options) || NO_OPTIONS; + var couldUseCache = + _env.env.forceCache || + (_env.env.isNode && !!options.ssr) || + !options.async; + var _a = (0, _react.useState)( + couldUseCache + ? function () { + return cache.get(importer); + } + : undefined + ), + Car = _a[0], + setCar = _a[1]; + var _b = (0, _react.useState)(null), + error = _b[0], + setError = _b[1]; + (0, _react.useEffect)(function () { + if (!Car) { + importer().then( + function (car) { + var resolved = effect ? effect.read() : car.default || car; + if (!resolved) { + console.error("Sidecar error: with importer", importer); + var error_1; + if (effect) { + console.error("Sidecar error: with medium", effect); + error_1 = new Error("Sidecar medium was not found"); + } else { + error_1 = new Error("Sidecar was not found in exports"); + } + setError(function () { + return error_1; + }); + throw error_1; + } + cache.set(importer, resolved); + setCar(function () { + return resolved; + }); + }, + function (e) { + return setError(function () { + return e; + }); + } + ); + } + }, []); + return [Car, error]; } - } - return this._workspaceEdit; - }, - enumerable: false, - configurable: true - }); - WorkspaceChange.prototype.getTextEditChange = function (key) { - if (OptionalVersionedTextDocumentIdentifier.is(key)) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var textDocument = { - uri: key.uri, - version: key.version - }; - var result = this._textEditChanges[textDocument.uri]; - if (!result) { - var edits = []; - var textDocumentEdit = { - textDocument: textDocument, - edits: edits - }; - this._workspaceEdit.documentChanges.push(textDocumentEdit); - result = new TextEditChangeImpl(edits, this._changeAnnotations); - this._textEditChanges[textDocument.uri] = result; - } - return result; - } else { - this.initChanges(); - if (this._workspaceEdit.changes === undefined) { - throw new Error('Workspace edit is not configured for normal text edit changes.'); - } - var result = this._textEditChanges[key]; - if (!result) { - var edits = []; - this._workspaceEdit.changes[key] = edits; - result = new TextEditChangeImpl(edits); - this._textEditChanges[key] = result; - } - return result; - } - }; - WorkspaceChange.prototype.initDocumentChanges = function () { - if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { - this._changeAnnotations = new ChangeAnnotations(); - this._workspaceEdit.documentChanges = []; - this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - } - }; - WorkspaceChange.prototype.initChanges = function () { - if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { - this._workspaceEdit.changes = Object.create(null); - } - }; - WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === undefined) { - operation = CreateFile.create(uri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = CreateFile.create(uri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== undefined) { - return id; - } - }; - WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === undefined) { - operation = RenameFile.create(oldUri, newUri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = RenameFile.create(oldUri, newUri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== undefined) { - return id; - } - }; - WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === undefined) { - operation = DeleteFile.create(uri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = DeleteFile.create(uri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== undefined) { - return id; - } - }; - return WorkspaceChange; -}(); -/** - * The TextDocumentIdentifier namespace provides helper functions to work with - * {@link TextDocumentIdentifier} literals. - */ -var TextDocumentIdentifier; -(function (TextDocumentIdentifier) { - /** - * Creates a new TextDocumentIdentifier literal. - * @param uri The document's uri. - */ - function create(uri) { - return { - uri: uri - }; - } - TextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri); - } - TextDocumentIdentifier.is = is; -})(TextDocumentIdentifier || (exports.TextDocumentIdentifier = TextDocumentIdentifier = {})); -/** - * The VersionedTextDocumentIdentifier namespace provides helper functions to work with - * {@link VersionedTextDocumentIdentifier} literals. - */ -var VersionedTextDocumentIdentifier; -(function (VersionedTextDocumentIdentifier) { - /** - * Creates a new VersionedTextDocumentIdentifier literal. - * @param uri The document's uri. - * @param version The document's version. - */ - function create(uri, version) { - return { - uri: uri, - version: version - }; - } - VersionedTextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); - } - VersionedTextDocumentIdentifier.is = is; -})(VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {})); -/** - * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with - * {@link OptionalVersionedTextDocumentIdentifier} literals. - */ -var OptionalVersionedTextDocumentIdentifier; -(function (OptionalVersionedTextDocumentIdentifier) { - /** - * Creates a new OptionalVersionedTextDocumentIdentifier literal. - * @param uri The document's uri. - * @param version The document's version. - */ - function create(uri, version) { - return { - uri: uri, - version: version - }; - } - OptionalVersionedTextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); - } - OptionalVersionedTextDocumentIdentifier.is = is; -})(OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); -/** - * The TextDocumentItem namespace provides helper functions to work with - * {@link TextDocumentItem} literals. - */ -var TextDocumentItem; -(function (TextDocumentItem) { - /** - * Creates a new TextDocumentItem literal. - * @param uri The document's uri. - * @param languageId The document's language identifier. - * @param version The document's version number. - * @param text The document's text. - */ - function create(uri, languageId, version, text) { - return { - uri: uri, - languageId: languageId, - version: version, - text: text - }; - } - TextDocumentItem.create = create; - /** - * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); - } - TextDocumentItem.is = is; -})(TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {})); -/** - * Describes the content type that a client supports in various - * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. - * - * Please note that `MarkupKinds` must not start with a `$`. This kinds - * are reserved for internal usage. - */ -var MarkupKind; -(function (MarkupKind) { - /** - * Plain text is supported as a content format - */ - MarkupKind.PlainText = 'plaintext'; - /** - * Markdown is supported as a content format - */ - MarkupKind.Markdown = 'markdown'; - /** - * Checks whether the given value is a value of the {@link MarkupKind} type. - */ - function is(value) { - var candidate = value; - return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; - } - MarkupKind.is = is; -})(MarkupKind || (exports.MarkupKind = MarkupKind = {})); -var MarkupContent; -(function (MarkupContent) { - /** - * Checks whether the given value conforms to the {@link MarkupContent} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); - } - MarkupContent.is = is; -})(MarkupContent || (exports.MarkupContent = MarkupContent = {})); -/** - * The kind of a completion entry. - */ -var CompletionItemKind; -(function (CompletionItemKind) { - CompletionItemKind.Text = 1; - CompletionItemKind.Method = 2; - CompletionItemKind.Function = 3; - CompletionItemKind.Constructor = 4; - CompletionItemKind.Field = 5; - CompletionItemKind.Variable = 6; - CompletionItemKind.Class = 7; - CompletionItemKind.Interface = 8; - CompletionItemKind.Module = 9; - CompletionItemKind.Property = 10; - CompletionItemKind.Unit = 11; - CompletionItemKind.Value = 12; - CompletionItemKind.Enum = 13; - CompletionItemKind.Keyword = 14; - CompletionItemKind.Snippet = 15; - CompletionItemKind.Color = 16; - CompletionItemKind.File = 17; - CompletionItemKind.Reference = 18; - CompletionItemKind.Folder = 19; - CompletionItemKind.EnumMember = 20; - CompletionItemKind.Constant = 21; - CompletionItemKind.Struct = 22; - CompletionItemKind.Event = 23; - CompletionItemKind.Operator = 24; - CompletionItemKind.TypeParameter = 25; -})(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); -/** - * Defines whether the insert text in a completion item should be interpreted as - * plain text or a snippet. - */ -var InsertTextFormat; -(function (InsertTextFormat) { - /** - * The primary text to be inserted is treated as a plain string. - */ - InsertTextFormat.PlainText = 1; - /** - * The primary text to be inserted is treated as a snippet. - * - * A snippet can define tab stops and placeholders with `$1`, `$2` - * and `${3:foo}`. `$0` defines the final tab stop, it defaults to - * the end of the snippet. Placeholders with equal identifiers are linked, - * that is typing in one will update others too. - * - * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax - */ - InsertTextFormat.Snippet = 2; -})(InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {})); -/** - * Completion item tags are extra annotations that tweak the rendering of a completion - * item. - * - * @since 3.15.0 - */ -var CompletionItemTag; -(function (CompletionItemTag) { - /** - * Render a completion as obsolete, usually using a strike-out. - */ - CompletionItemTag.Deprecated = 1; -})(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {})); -/** - * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. - * - * @since 3.16.0 - */ -var InsertReplaceEdit; -(function (InsertReplaceEdit) { - /** - * Creates a new insert / replace edit - */ - function create(newText, insert, replace) { - return { - newText: newText, - insert: insert, - replace: replace - }; - } - InsertReplaceEdit.create = create; - /** - * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. - */ - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); - } - InsertReplaceEdit.is = is; -})(InsertReplaceEdit || (exports.InsertReplaceEdit = InsertReplaceEdit = {})); -/** - * How whitespace and indentation is handled during completion - * item insertion. - * - * @since 3.16.0 - */ -var InsertTextMode; -(function (InsertTextMode) { - /** - * The insertion or replace strings is taken as it is. If the - * value is multi line the lines below the cursor will be - * inserted using the indentation defined in the string value. - * The client will not apply any kind of adjustments to the - * string. - */ - InsertTextMode.asIs = 1; - /** - * The editor adjusts leading whitespace of new lines so that - * they match the indentation up to the cursor of the line for - * which the item is accepted. - * - * Consider a line like this: <2tabs><3tabs>foo. Accepting a - * multi line completion item is indented using 2 tabs and all - * following lines inserted will be indented using 2 tabs as well. - */ - InsertTextMode.adjustIndentation = 2; -})(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {})); -var CompletionItemLabelDetails; -(function (CompletionItemLabelDetails) { - function is(value) { - var candidate = value; - return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) && (Is.string(candidate.description) || candidate.description === undefined); - } - CompletionItemLabelDetails.is = is; -})(CompletionItemLabelDetails || (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = {})); -/** - * The CompletionItem namespace provides functions to deal with - * completion items. - */ -var CompletionItem; -(function (CompletionItem) { - /** - * Create a completion item and seed it with a label. - * @param label The completion item's label - */ - function create(label) { - return { - label: label - }; - } - CompletionItem.create = create; -})(CompletionItem || (exports.CompletionItem = CompletionItem = {})); -/** - * The CompletionList namespace provides functions to deal with - * completion lists. - */ -var CompletionList; -(function (CompletionList) { - /** - * Creates a new completion list. - * - * @param items The completion items. - * @param isIncomplete The list is not complete. - */ - function create(items, isIncomplete) { - return { - items: items ? items : [], - isIncomplete: !!isIncomplete - }; - } - CompletionList.create = create; -})(CompletionList || (exports.CompletionList = CompletionList = {})); -var MarkedString; -(function (MarkedString) { - /** - * Creates a marked string from plain text. - * - * @param plainText The plain text. - */ - function fromPlainText(plainText) { - return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash - } - MarkedString.fromPlainText = fromPlainText; - /** - * Checks whether the given value conforms to the {@link MarkedString} type. - */ - function is(value) { - var candidate = value; - return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value); - } - MarkedString.is = is; -})(MarkedString || (exports.MarkedString = MarkedString = {})); -var Hover; -(function (Hover) { - /** - * Checks whether the given value conforms to the {@link Hover} interface. - */ - function is(value) { - var candidate = value; - return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range)); - } - Hover.is = is; -})(Hover || (exports.Hover = Hover = {})); -/** - * The ParameterInformation namespace provides helper functions to work with - * {@link ParameterInformation} literals. - */ -var ParameterInformation; -(function (ParameterInformation) { - /** - * Creates a new parameter information literal. - * - * @param label A label string. - * @param documentation A doc string. - */ - function create(label, documentation) { - return documentation ? { - label: label, - documentation: documentation - } : { - label: label - }; - } - ParameterInformation.create = create; -})(ParameterInformation || (exports.ParameterInformation = ParameterInformation = {})); -/** - * The SignatureInformation namespace provides helper functions to work with - * {@link SignatureInformation} literals. - */ -var SignatureInformation; -(function (SignatureInformation) { - function create(label, documentation) { - var parameters = []; - for (var _i = 2; _i < arguments.length; _i++) { - parameters[_i - 2] = arguments[_i]; - } - var result = { - label: label - }; - if (Is.defined(documentation)) { - result.documentation = documentation; - } - if (Is.defined(parameters)) { - result.parameters = parameters; - } else { - result.parameters = []; - } - return result; - } - SignatureInformation.create = create; -})(SignatureInformation || (exports.SignatureInformation = SignatureInformation = {})); -/** - * A document highlight kind. - */ -var DocumentHighlightKind; -(function (DocumentHighlightKind) { - /** - * A textual occurrence. - */ - DocumentHighlightKind.Text = 1; - /** - * Read-access of a symbol, like reading a variable. - */ - DocumentHighlightKind.Read = 2; - /** - * Write-access of a symbol, like writing to a variable. - */ - DocumentHighlightKind.Write = 3; -})(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {})); -/** - * DocumentHighlight namespace to provide helper functions to work with - * {@link DocumentHighlight} literals. - */ -var DocumentHighlight; -(function (DocumentHighlight) { - /** - * Create a DocumentHighlight object. - * @param range The range the highlight applies to. - * @param kind The highlight kind - */ - function create(range, kind) { - var result = { - range: range - }; - if (Is.number(kind)) { - result.kind = kind; - } - return result; - } - DocumentHighlight.create = create; -})(DocumentHighlight || (exports.DocumentHighlight = DocumentHighlight = {})); -/** - * A symbol kind. - */ -var SymbolKind; -(function (SymbolKind) { - SymbolKind.File = 1; - SymbolKind.Module = 2; - SymbolKind.Namespace = 3; - SymbolKind.Package = 4; - SymbolKind.Class = 5; - SymbolKind.Method = 6; - SymbolKind.Property = 7; - SymbolKind.Field = 8; - SymbolKind.Constructor = 9; - SymbolKind.Enum = 10; - SymbolKind.Interface = 11; - SymbolKind.Function = 12; - SymbolKind.Variable = 13; - SymbolKind.Constant = 14; - SymbolKind.String = 15; - SymbolKind.Number = 16; - SymbolKind.Boolean = 17; - SymbolKind.Array = 18; - SymbolKind.Object = 19; - SymbolKind.Key = 20; - SymbolKind.Null = 21; - SymbolKind.EnumMember = 22; - SymbolKind.Struct = 23; - SymbolKind.Event = 24; - SymbolKind.Operator = 25; - SymbolKind.TypeParameter = 26; -})(SymbolKind || (exports.SymbolKind = SymbolKind = {})); -/** - * Symbol tags are extra annotations that tweak the rendering of a symbol. - * - * @since 3.16 - */ -var SymbolTag; -(function (SymbolTag) { - /** - * Render a symbol as obsolete, usually using a strike-out. - */ - SymbolTag.Deprecated = 1; -})(SymbolTag || (exports.SymbolTag = SymbolTag = {})); -var SymbolInformation; -(function (SymbolInformation) { - /** - * Creates a new symbol information literal. - * - * @param name The name of the symbol. - * @param kind The kind of the symbol. - * @param range The range of the location of the symbol. - * @param uri The resource of the location of symbol. - * @param containerName The name of the symbol containing the symbol. - */ - function create(name, kind, range, uri, containerName) { - var result = { - name: name, - kind: kind, - location: { - uri: uri, - range: range - } - }; - if (containerName) { - result.containerName = containerName; - } - return result; - } - SymbolInformation.create = create; -})(SymbolInformation || (exports.SymbolInformation = SymbolInformation = {})); -var WorkspaceSymbol; -(function (WorkspaceSymbol) { - /** - * Create a new workspace symbol. - * - * @param name The name of the symbol. - * @param kind The kind of the symbol. - * @param uri The resource of the location of the symbol. - * @param range An options range of the location. - * @returns A WorkspaceSymbol. - */ - function create(name, kind, uri, range) { - return range !== undefined ? { - name: name, - kind: kind, - location: { - uri: uri, - range: range - } - } : { - name: name, - kind: kind, - location: { - uri: uri - } - }; - } - WorkspaceSymbol.create = create; -})(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {})); -var DocumentSymbol; -(function (DocumentSymbol) { - /** - * Creates a new symbol information literal. - * - * @param name The name of the symbol. - * @param detail The detail of the symbol. - * @param kind The kind of the symbol. - * @param range The range of the symbol. - * @param selectionRange The selectionRange of the symbol. - * @param children Children of the symbol. - */ - function create(name, detail, kind, range, selectionRange, children) { - var result = { - name: name, - detail: detail, - kind: kind, - range: range, - selectionRange: selectionRange - }; - if (children !== undefined) { - result.children = children; - } - return result; - } - DocumentSymbol.create = create; - /** - * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. - */ - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags)); - } - DocumentSymbol.is = is; -})(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {})); -/** - * A set of predefined code action kinds - */ -var CodeActionKind; -(function (CodeActionKind) { - /** - * Empty kind. - */ - CodeActionKind.Empty = ''; - /** - * Base kind for quickfix actions: 'quickfix' - */ - CodeActionKind.QuickFix = 'quickfix'; - /** - * Base kind for refactoring actions: 'refactor' - */ - CodeActionKind.Refactor = 'refactor'; - /** - * Base kind for refactoring extraction actions: 'refactor.extract' - * - * Example extract actions: - * - * - Extract method - * - Extract function - * - Extract variable - * - Extract interface from class - * - ... - */ - CodeActionKind.RefactorExtract = 'refactor.extract'; - /** - * Base kind for refactoring inline actions: 'refactor.inline' - * - * Example inline actions: - * - * - Inline function - * - Inline variable - * - Inline constant - * - ... - */ - CodeActionKind.RefactorInline = 'refactor.inline'; - /** - * Base kind for refactoring rewrite actions: 'refactor.rewrite' - * - * Example rewrite actions: - * - * - Convert JavaScript function to class - * - Add or remove parameter - * - Encapsulate field - * - Make method static - * - Move method to base class - * - ... - */ - CodeActionKind.RefactorRewrite = 'refactor.rewrite'; - /** - * Base kind for source actions: `source` - * - * Source code actions apply to the entire file. - */ - CodeActionKind.Source = 'source'; - /** - * Base kind for an organize imports source action: `source.organizeImports` - */ - CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; - /** - * Base kind for auto-fix source actions: `source.fixAll`. - * - * Fix all actions automatically fix errors that have a clear fix that do not require user input. - * They should not suppress errors or perform unsafe fixes such as generating new types or classes. - * - * @since 3.15.0 - */ - CodeActionKind.SourceFixAll = 'source.fixAll'; -})(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {})); -/** - * The reason why code actions were requested. - * - * @since 3.17.0 - */ -var CodeActionTriggerKind; -(function (CodeActionTriggerKind) { - /** - * Code actions were explicitly requested by the user or by an extension. - */ - CodeActionTriggerKind.Invoked = 1; - /** - * Code actions were requested automatically. - * - * This typically happens when current selection in a file changes, but can - * also be triggered when file content changes. - */ - CodeActionTriggerKind.Automatic = 2; -})(CodeActionTriggerKind || (exports.CodeActionTriggerKind = CodeActionTriggerKind = {})); -/** - * The CodeActionContext namespace provides helper functions to work with - * {@link CodeActionContext} literals. - */ -var CodeActionContext; -(function (CodeActionContext) { - /** - * Creates a new CodeActionContext literal. - */ - function create(diagnostics, only, triggerKind) { - var result = { - diagnostics: diagnostics - }; - if (only !== undefined && only !== null) { - result.only = only; - } - if (triggerKind !== undefined && triggerKind !== null) { - result.triggerKind = triggerKind; - } - return result; - } - CodeActionContext.create = create; - /** - * Checks whether the given literal conforms to the {@link CodeActionContext} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); - } - CodeActionContext.is = is; -})(CodeActionContext || (exports.CodeActionContext = CodeActionContext = {})); -var CodeAction; -(function (CodeAction) { - function create(title, kindOrCommandOrEdit, kind) { - var result = { - title: title - }; - var checkKind = true; - if (typeof kindOrCommandOrEdit === 'string') { - checkKind = false; - result.kind = kindOrCommandOrEdit; - } else if (Command.is(kindOrCommandOrEdit)) { - result.command = kindOrCommandOrEdit; - } else { - result.edit = kindOrCommandOrEdit; - } - if (checkKind && kind !== undefined) { - result.kind = kind; - } - return result; - } - CodeAction.create = create; - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)); - } - CodeAction.is = is; -})(CodeAction || (exports.CodeAction = CodeAction = {})); -/** - * The CodeLens namespace provides helper functions to work with - * {@link CodeLens} literals. - */ -var CodeLens; -(function (CodeLens) { - /** - * Creates a new CodeLens literal. - */ - function create(range, data) { - var result = { - range: range - }; - if (Is.defined(data)) { - result.data = data; - } - return result; - } - CodeLens.create = create; - /** - * Checks whether the given literal conforms to the {@link CodeLens} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); - } - CodeLens.is = is; -})(CodeLens || (exports.CodeLens = CodeLens = {})); -/** - * The FormattingOptions namespace provides helper functions to work with - * {@link FormattingOptions} literals. - */ -var FormattingOptions; -(function (FormattingOptions) { - /** - * Creates a new FormattingOptions literal. - */ - function create(tabSize, insertSpaces) { - return { - tabSize: tabSize, - insertSpaces: insertSpaces - }; - } - FormattingOptions.create = create; - /** - * Checks whether the given literal conforms to the {@link FormattingOptions} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); - } - FormattingOptions.is = is; -})(FormattingOptions || (exports.FormattingOptions = FormattingOptions = {})); -/** - * The DocumentLink namespace provides helper functions to work with - * {@link DocumentLink} literals. - */ -var DocumentLink; -(function (DocumentLink) { - /** - * Creates a new DocumentLink literal. - */ - function create(range, target, data) { - return { - range: range, - target: target, - data: data - }; - } - DocumentLink.create = create; - /** - * Checks whether the given literal conforms to the {@link DocumentLink} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); - } - DocumentLink.is = is; -})(DocumentLink || (exports.DocumentLink = DocumentLink = {})); -/** - * The SelectionRange namespace provides helper function to work with - * SelectionRange literals. - */ -var SelectionRange; -(function (SelectionRange) { - /** - * Creates a new SelectionRange - * @param range the range. - * @param parent an optional parent. - */ - function create(range, parent) { - return { - range: range, - parent: parent - }; - } - SelectionRange.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); - } - SelectionRange.is = is; -})(SelectionRange || (exports.SelectionRange = SelectionRange = {})); -/** - * A set of predefined token types. This set is not fixed - * an clients can specify additional token types via the - * corresponding client capabilities. - * - * @since 3.16.0 - */ -var SemanticTokenTypes; -(function (SemanticTokenTypes) { - SemanticTokenTypes["namespace"] = "namespace"; - /** - * Represents a generic type. Acts as a fallback for types which can't be mapped to - * a specific type like class or enum. - */ - SemanticTokenTypes["type"] = "type"; - SemanticTokenTypes["class"] = "class"; - SemanticTokenTypes["enum"] = "enum"; - SemanticTokenTypes["interface"] = "interface"; - SemanticTokenTypes["struct"] = "struct"; - SemanticTokenTypes["typeParameter"] = "typeParameter"; - SemanticTokenTypes["parameter"] = "parameter"; - SemanticTokenTypes["variable"] = "variable"; - SemanticTokenTypes["property"] = "property"; - SemanticTokenTypes["enumMember"] = "enumMember"; - SemanticTokenTypes["event"] = "event"; - SemanticTokenTypes["function"] = "function"; - SemanticTokenTypes["method"] = "method"; - SemanticTokenTypes["macro"] = "macro"; - SemanticTokenTypes["keyword"] = "keyword"; - SemanticTokenTypes["modifier"] = "modifier"; - SemanticTokenTypes["comment"] = "comment"; - SemanticTokenTypes["string"] = "string"; - SemanticTokenTypes["number"] = "number"; - SemanticTokenTypes["regexp"] = "regexp"; - SemanticTokenTypes["operator"] = "operator"; - /** - * @since 3.17.0 - */ - SemanticTokenTypes["decorator"] = "decorator"; -})(SemanticTokenTypes || (exports.SemanticTokenTypes = SemanticTokenTypes = {})); -/** - * A set of predefined token modifiers. This set is not fixed - * an clients can specify additional token types via the - * corresponding client capabilities. - * - * @since 3.16.0 - */ -var SemanticTokenModifiers; -(function (SemanticTokenModifiers) { - SemanticTokenModifiers["declaration"] = "declaration"; - SemanticTokenModifiers["definition"] = "definition"; - SemanticTokenModifiers["readonly"] = "readonly"; - SemanticTokenModifiers["static"] = "static"; - SemanticTokenModifiers["deprecated"] = "deprecated"; - SemanticTokenModifiers["abstract"] = "abstract"; - SemanticTokenModifiers["async"] = "async"; - SemanticTokenModifiers["modification"] = "modification"; - SemanticTokenModifiers["documentation"] = "documentation"; - SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; -})(SemanticTokenModifiers || (exports.SemanticTokenModifiers = SemanticTokenModifiers = {})); -/** - * @since 3.16.0 - */ -var SemanticTokens; -(function (SemanticTokens) { - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); - } - SemanticTokens.is = is; -})(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {})); -/** - * The InlineValueText namespace provides functions to deal with InlineValueTexts. - * - * @since 3.17.0 - */ -var InlineValueText; -(function (InlineValueText) { - /** - * Creates a new InlineValueText literal. - */ - function create(range, text) { - return { - range: range, - text: text - }; - } - InlineValueText.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text); - } - InlineValueText.is = is; -})(InlineValueText || (exports.InlineValueText = InlineValueText = {})); -/** - * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups. - * - * @since 3.17.0 - */ -var InlineValueVariableLookup; -(function (InlineValueVariableLookup) { - /** - * Creates a new InlineValueText literal. - */ - function create(range, variableName, caseSensitiveLookup) { - return { - range: range, - variableName: variableName, - caseSensitiveLookup: caseSensitiveLookup - }; - } - InlineValueVariableLookup.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === undefined); - } - InlineValueVariableLookup.is = is; -})(InlineValueVariableLookup || (exports.InlineValueVariableLookup = InlineValueVariableLookup = {})); -/** - * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression. - * - * @since 3.17.0 - */ -var InlineValueEvaluatableExpression; -(function (InlineValueEvaluatableExpression) { - /** - * Creates a new InlineValueEvaluatableExpression literal. - */ - function create(range, expression) { - return { - range: range, - expression: expression - }; - } - InlineValueEvaluatableExpression.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === undefined); - } - InlineValueEvaluatableExpression.is = is; -})(InlineValueEvaluatableExpression || (exports.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {})); -/** - * The InlineValueContext namespace provides helper functions to work with - * {@link InlineValueContext} literals. - * - * @since 3.17.0 - */ -var InlineValueContext; -(function (InlineValueContext) { - /** - * Creates a new InlineValueContext literal. - */ - function create(frameId, stoppedLocation) { - return { - frameId: frameId, - stoppedLocation: stoppedLocation - }; - } - InlineValueContext.create = create; - /** - * Checks whether the given literal conforms to the {@link InlineValueContext} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(value.stoppedLocation); - } - InlineValueContext.is = is; -})(InlineValueContext || (exports.InlineValueContext = InlineValueContext = {})); -/** - * Inlay hint kinds. - * - * @since 3.17.0 - */ -var InlayHintKind; -(function (InlayHintKind) { - /** - * An inlay hint that for a type annotation. - */ - InlayHintKind.Type = 1; - /** - * An inlay hint that is for a parameter. - */ - InlayHintKind.Parameter = 2; - function is(value) { - return value === 1 || value === 2; - } - InlayHintKind.is = is; -})(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {})); -var InlayHintLabelPart; -(function (InlayHintLabelPart) { - function create(value) { - return { - value: value - }; - } - InlayHintLabelPart.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === undefined || Location.is(candidate.location)) && (candidate.command === undefined || Command.is(candidate.command)); - } - InlayHintLabelPart.is = is; -})(InlayHintLabelPart || (exports.InlayHintLabelPart = InlayHintLabelPart = {})); -var InlayHint; -(function (InlayHint) { - function create(position, label, kind) { - var result = { - position: position, - label: label - }; - if (kind !== undefined) { - result.kind = kind; - } - return result; - } - InlayHint.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === undefined || InlayHintKind.is(candidate.kind)) && candidate.textEdits === undefined || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight)); - } - InlayHint.is = is; -})(InlayHint || (exports.InlayHint = InlayHint = {})); -var WorkspaceFolder; -(function (WorkspaceFolder) { - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); - } - WorkspaceFolder.is = is; -})(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {})); -var EOL = exports.EOL = ['\n', '\r\n', '\r']; -/** - * @deprecated Use the text document from the new vscode-languageserver-textdocument package. - */ -var TextDocument; -(function (TextDocument) { - /** - * Creates a new ITextDocument literal from the given uri and content. - * @param uri The document's uri. - * @param languageId The document's language Id. - * @param version The document's version. - * @param content The document's content. - */ - function create(uri, languageId, version, content) { - return new FullTextDocument(uri, languageId, version, content); - } - TextDocument.create = create; - /** - * Checks whether the given literal conforms to the {@link ITextDocument} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; - } - TextDocument.is = is; - function applyEdits(document, edits) { - var text = document.getText(); - var sortedEdits = mergeSort(edits, function (a, b) { - var diff = a.range.start.line - b.range.start.line; - if (diff === 0) { - return a.range.start.character - b.range.start.character; - } - return diff; - }); - var lastModifiedOffset = text.length; - for (var i = sortedEdits.length - 1; i >= 0; i--) { - var e = sortedEdits[i]; - var startOffset = document.offsetAt(e.range.start); - var endOffset = document.offsetAt(e.range.end); - if (endOffset <= lastModifiedOffset) { - text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); - } else { - throw new Error('Overlapping edit'); - } - lastModifiedOffset = startOffset; - } - return text; - } - TextDocument.applyEdits = applyEdits; - function mergeSort(data, compare) { - if (data.length <= 1) { - // sorted - return data; - } - var p = data.length / 2 | 0; - var left = data.slice(0, p); - var right = data.slice(p); - mergeSort(left, compare); - mergeSort(right, compare); - var leftIdx = 0; - var rightIdx = 0; - var i = 0; - while (leftIdx < left.length && rightIdx < right.length) { - var ret = compare(left[leftIdx], right[rightIdx]); - if (ret <= 0) { - // smaller_equal -> take left to preserve order - data[i++] = left[leftIdx++]; - } else { - // greater -> take right - data[i++] = right[rightIdx++]; - } - } - while (leftIdx < left.length) { - data[i++] = left[leftIdx++]; - } - while (rightIdx < right.length) { - data[i++] = right[rightIdx++]; - } - return data; - } -})(TextDocument || (exports.TextDocument = TextDocument = {})); -/** - * @deprecated Use the text document from the new vscode-languageserver-textdocument package. - */ -var FullTextDocument = /** @class */function () { - function FullTextDocument(uri, languageId, version, content) { - this._uri = uri; - this._languageId = languageId; - this._version = version; - this._content = content; - this._lineOffsets = undefined; - } - Object.defineProperty(FullTextDocument.prototype, "uri", { - get: function () { - return this._uri; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "languageId", { - get: function () { - return this._languageId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "version", { - get: function () { - return this._version; - }, - enumerable: false, - configurable: true - }); - FullTextDocument.prototype.getText = function (range) { - if (range) { - var start = this.offsetAt(range.start); - var end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - }; - FullTextDocument.prototype.update = function (event, version) { - this._content = event.text; - this._version = version; - this._lineOffsets = undefined; - }; - FullTextDocument.prototype.getLineOffsets = function () { - if (this._lineOffsets === undefined) { - var lineOffsets = []; - var text = this._content; - var isLineStart = true; - for (var i = 0; i < text.length; i++) { - if (isLineStart) { - lineOffsets.push(i); - isLineStart = false; - } - var ch = text.charAt(i); - isLineStart = ch === '\r' || ch === '\n'; - if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { - i++; + + /***/ + }, + + /***/ "../../../node_modules/use-sidecar/dist/es2015/index.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/index.js ***! + \**************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "createMedium", { + enumerable: true, + get: function () { + return _medium.createMedium; + }, + }); + Object.defineProperty(exports, "createSidecarMedium", { + enumerable: true, + get: function () { + return _medium.createSidecarMedium; + }, + }); + Object.defineProperty(exports, "exportSidecar", { + enumerable: true, + get: function () { + return _exports.exportSidecar; + }, + }); + Object.defineProperty(exports, "renderCar", { + enumerable: true, + get: function () { + return _renderProp.renderCar; + }, + }); + Object.defineProperty(exports, "setConfig", { + enumerable: true, + get: function () { + return _config.setConfig; + }, + }); + Object.defineProperty(exports, "sidecar", { + enumerable: true, + get: function () { + return _hoc.sidecar; + }, + }); + Object.defineProperty(exports, "useSidecar", { + enumerable: true, + get: function () { + return _hook.useSidecar; + }, + }); + var _hoc = __webpack_require__( + /*! ./hoc */ "../../../node_modules/use-sidecar/dist/es2015/hoc.js" + ); + var _hook = __webpack_require__( + /*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js" + ); + var _config = __webpack_require__( + /*! ./config */ "../../../node_modules/use-sidecar/dist/es2015/config.js" + ); + var _medium = __webpack_require__( + /*! ./medium */ "../../../node_modules/use-sidecar/dist/es2015/medium.js" + ); + var _renderProp = __webpack_require__( + /*! ./renderProp */ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js" + ); + var _exports = __webpack_require__( + /*! ./exports */ "../../../node_modules/use-sidecar/dist/es2015/exports.js" + ); + + /***/ + }, + + /***/ "../../../node_modules/use-sidecar/dist/es2015/medium.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/medium.js ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createMedium = createMedium; + exports.createSidecarMedium = createSidecarMedium; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + function ItoI(a) { + return a; + } + function innerCreateMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + var buffer = []; + var assigned = false; + var medium = { + read: function () { + if (assigned) { + throw new Error( + "Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`." + ); + } + if (buffer.length) { + return buffer[buffer.length - 1]; + } + return defaults; + }, + useMedium: function (data) { + var item = middleware(data, assigned); + buffer.push(item); + return function () { + buffer = buffer.filter(function (x) { + return x !== item; + }); + }; + }, + assignSyncMedium: function (cb) { + assigned = true; + while (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + } + buffer = { + push: function (x) { + return cb(x); + }, + filter: function () { + return buffer; + }, + }; + }, + assignMedium: function (cb) { + assigned = true; + var pendingQueue = []; + if (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + pendingQueue = buffer; + } + var executeQueue = function () { + var cbs = pendingQueue; + pendingQueue = []; + cbs.forEach(cb); + }; + var cycle = function () { + return Promise.resolve().then(executeQueue); + }; + cycle(); + buffer = { + push: function (x) { + pendingQueue.push(x); + cycle(); + }, + filter: function (filter) { + pendingQueue = pendingQueue.filter(filter); + return buffer; + }, + }; + }, + }; + return medium; } - } - if (isLineStart && text.length > 0) { - lineOffsets.push(text.length); - } - this._lineOffsets = lineOffsets; - } - return this._lineOffsets; - }; - FullTextDocument.prototype.positionAt = function (offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - var lineOffsets = this.getLineOffsets(); - var low = 0, - high = lineOffsets.length; - if (high === 0) { - return Position.create(0, offset); - } - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } else { - low = mid + 1; - } - } - // low is the least x for which the line offset is larger than the current offset - // or array.length if no line offset is larger than the current offset - var line = low - 1; - return Position.create(line, offset - lineOffsets[line]); - }; - FullTextDocument.prototype.offsetAt = function (position) { - var lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } else if (position.line < 0) { - return 0; - } - var lineOffset = lineOffsets[position.line]; - var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - }; - Object.defineProperty(FullTextDocument.prototype, "lineCount", { - get: function () { - return this.getLineOffsets().length; - }, - enumerable: false, - configurable: true - }); - return FullTextDocument; -}(); -var Is; -(function (Is) { - var toString = Object.prototype.toString; - function defined(value) { - return typeof value !== 'undefined'; - } - Is.defined = defined; - function undefined(value) { - return typeof value === 'undefined'; - } - Is.undefined = undefined; - function boolean(value) { - return value === true || value === false; - } - Is.boolean = boolean; - function string(value) { - return toString.call(value) === '[object String]'; - } - Is.string = string; - function number(value) { - return toString.call(value) === '[object Number]'; - } - Is.number = number; - function numberRange(value, min, max) { - return toString.call(value) === '[object Number]' && min <= value && value <= max; - } - Is.numberRange = numberRange; - function integer(value) { - return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647; - } - Is.integer = integer; - function uinteger(value) { - return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647; - } - Is.uinteger = uinteger; - function func(value) { - return toString.call(value) === '[object Function]'; - } - Is.func = func; - function objectLiteral(value) { - // Strictly speaking class instances pass this check as well. Since the LSP - // doesn't use classes we ignore this for now. If we do we need to add something - // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` - return value !== null && typeof value === 'object'; - } - Is.objectLiteral = objectLiteral; - function typedArray(value, check) { - return Array.isArray(value) && value.every(check); - } - Is.typedArray = typedArray; -})(Is || (Is = {})); + function createMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + return innerCreateMedium(defaults, middleware); + } + // eslint-disable-next-line @typescript-eslint/ban-types + function createSidecarMedium(options) { + if (options === void 0) { + options = {}; + } + var medium = innerCreateMedium(null); + medium.options = (0, _tslib.__assign)( + { + async: true, + ssr: false, + }, + options + ); + return medium; + } + + /***/ + }, + + /***/ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/renderProp.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.renderCar = renderCar; + var _tslib = __webpack_require__( + /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" + ); + var _react = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var React = _react; + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + function renderCar(WrappedComponent, defaults) { + function State(_a) { + var stateRef = _a.stateRef, + props = _a.props; + var renderTarget = (0, _react.useCallback)(function SideTarget() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + (0, _react.useLayoutEffect)(function () { + stateRef.current(args); + }); + return null; + }, []); + // @ts-ignore + return /*#__PURE__*/ React.createElement( + WrappedComponent, + (0, _tslib.__assign)({}, props, { + children: renderTarget, + }) + ); + } + var Children = /*#__PURE__*/ React.memo( + function (_a) { + var stateRef = _a.stateRef, + defaultState = _a.defaultState, + children = _a.children; + var _b = (0, _react.useState)(defaultState.current), + state = _b[0], + setState = _b[1]; + (0, _react.useEffect)(function () { + stateRef.current = setState; + }, []); + return children.apply(void 0, state); + }, + function () { + return true; + } + ); + return function Combiner(props) { + var defaultState = React.useRef(defaults(props)); + var ref = React.useRef(function (state) { + return (defaultState.current = state); + }); + return /*#__PURE__*/ React.createElement( + React.Fragment, + null, + /*#__PURE__*/ React.createElement(State, { + stateRef: ref, + props: props, + }), + /*#__PURE__*/ React.createElement(Children, { + stateRef: ref, + defaultState: defaultState, + children: props.children, + }) + ); + }; + } + + /***/ + }, + + /***/ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js": + /*!*************************************************************************!*\ + !*** ../../../node_modules/vscode-languageserver-types/lib/esm/main.js ***! + \*************************************************************************/ + /***/ function (__unused_webpack_module, exports) { + /* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.uinteger = + exports.integer = + exports.WorkspaceSymbol = + exports.WorkspaceFolder = + exports.WorkspaceEdit = + exports.WorkspaceChange = + exports.VersionedTextDocumentIdentifier = + exports.URI = + exports.TextEdit = + exports.TextDocumentItem = + exports.TextDocumentIdentifier = + exports.TextDocumentEdit = + exports.TextDocument = + exports.SymbolTag = + exports.SymbolKind = + exports.SymbolInformation = + exports.SignatureInformation = + exports.SemanticTokens = + exports.SemanticTokenTypes = + exports.SemanticTokenModifiers = + exports.SelectionRange = + exports.RenameFile = + exports.Range = + exports.Position = + exports.ParameterInformation = + exports.OptionalVersionedTextDocumentIdentifier = + exports.MarkupKind = + exports.MarkupContent = + exports.MarkedString = + exports.LocationLink = + exports.Location = + exports.InsertTextMode = + exports.InsertTextFormat = + exports.InsertReplaceEdit = + exports.InlineValueVariableLookup = + exports.InlineValueText = + exports.InlineValueEvaluatableExpression = + exports.InlineValueContext = + exports.InlayHintLabelPart = + exports.InlayHintKind = + exports.InlayHint = + exports.Hover = + exports.FormattingOptions = + exports.FoldingRangeKind = + exports.FoldingRange = + exports.EOL = + exports.DocumentUri = + exports.DocumentSymbol = + exports.DocumentLink = + exports.DocumentHighlightKind = + exports.DocumentHighlight = + exports.DiagnosticTag = + exports.DiagnosticSeverity = + exports.DiagnosticRelatedInformation = + exports.Diagnostic = + exports.DeleteFile = + exports.CreateFile = + exports.CompletionList = + exports.CompletionItemTag = + exports.CompletionItemLabelDetails = + exports.CompletionItemKind = + exports.CompletionItem = + exports.Command = + exports.ColorPresentation = + exports.ColorInformation = + exports.Color = + exports.CodeLens = + exports.CodeDescription = + exports.CodeActionTriggerKind = + exports.CodeActionKind = + exports.CodeActionContext = + exports.CodeAction = + exports.ChangeAnnotationIdentifier = + exports.ChangeAnnotation = + exports.AnnotatedTextEdit = + void 0; + var DocumentUri; + (function (DocumentUri) { + function is(value) { + return typeof value === "string"; + } + DocumentUri.is = is; + })(DocumentUri || (exports.DocumentUri = DocumentUri = {})); + var URI; + (function (URI) { + function is(value) { + return typeof value === "string"; + } + URI.is = is; + })(URI || (exports.URI = URI = {})); + var integer; + (function (integer) { + integer.MIN_VALUE = -2147483648; + integer.MAX_VALUE = 2147483647; + function is(value) { + return ( + typeof value === "number" && + integer.MIN_VALUE <= value && + value <= integer.MAX_VALUE + ); + } + integer.is = is; + })(integer || (exports.integer = integer = {})); + var uinteger; + (function (uinteger) { + uinteger.MIN_VALUE = 0; + uinteger.MAX_VALUE = 2147483647; + function is(value) { + return ( + typeof value === "number" && + uinteger.MIN_VALUE <= value && + value <= uinteger.MAX_VALUE + ); + } + uinteger.is = is; + })(uinteger || (exports.uinteger = uinteger = {})); + /** + * The Position namespace provides helper functions to work with + * {@link Position} literals. + */ + var Position; + (function (Position) { + /** + * Creates a new Position literal from the given line and character. + * @param line The position's line. + * @param character The position's character. + */ + function create(line, character) { + if (line === Number.MAX_VALUE) { + line = uinteger.MAX_VALUE; + } + if (character === Number.MAX_VALUE) { + character = uinteger.MAX_VALUE; + } + return { + line: line, + character: character, + }; + } + Position.create = create; + /** + * Checks whether the given literal conforms to the {@link Position} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Is.uinteger(candidate.line) && + Is.uinteger(candidate.character) + ); + } + Position.is = is; + })(Position || (exports.Position = Position = {})); + /** + * The Range namespace provides helper functions to work with + * {@link Range} literals. + */ + var Range; + (function (Range) { + function create(one, two, three, four) { + if ( + Is.uinteger(one) && + Is.uinteger(two) && + Is.uinteger(three) && + Is.uinteger(four) + ) { + return { + start: Position.create(one, two), + end: Position.create(three, four), + }; + } else if (Position.is(one) && Position.is(two)) { + return { + start: one, + end: two, + }; + } else { + throw new Error( + "Range#create called with invalid arguments[" + .concat(one, ", ") + .concat(two, ", ") + .concat(three, ", ") + .concat(four, "]") + ); + } + } + Range.create = create; + /** + * Checks whether the given literal conforms to the {@link Range} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Position.is(candidate.start) && + Position.is(candidate.end) + ); + } + Range.is = is; + })(Range || (exports.Range = Range = {})); + /** + * The Location namespace provides helper functions to work with + * {@link Location} literals. + */ + var Location; + (function (Location) { + /** + * Creates a Location literal. + * @param uri The location's uri. + * @param range The location's range. + */ + function create(uri, range) { + return { + uri: uri, + range: range, + }; + } + Location.create = create; + /** + * Checks whether the given literal conforms to the {@link Location} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Range.is(candidate.range) && + (Is.string(candidate.uri) || Is.undefined(candidate.uri)) + ); + } + Location.is = is; + })(Location || (exports.Location = Location = {})); + /** + * The LocationLink namespace provides helper functions to work with + * {@link LocationLink} literals. + */ + var LocationLink; + (function (LocationLink) { + /** + * Creates a LocationLink literal. + * @param targetUri The definition's uri. + * @param targetRange The full range of the definition. + * @param targetSelectionRange The span of the symbol definition at the target. + * @param originSelectionRange The span of the symbol being defined in the originating source file. + */ + function create( + targetUri, + targetRange, + targetSelectionRange, + originSelectionRange + ) { + return { + targetUri: targetUri, + targetRange: targetRange, + targetSelectionRange: targetSelectionRange, + originSelectionRange: originSelectionRange, + }; + } + LocationLink.create = create; + /** + * Checks whether the given literal conforms to the {@link LocationLink} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Range.is(candidate.targetRange) && + Is.string(candidate.targetUri) && + Range.is(candidate.targetSelectionRange) && + (Range.is(candidate.originSelectionRange) || + Is.undefined(candidate.originSelectionRange)) + ); + } + LocationLink.is = is; + })(LocationLink || (exports.LocationLink = LocationLink = {})); + /** + * The Color namespace provides helper functions to work with + * {@link Color} literals. + */ + var Color; + (function (Color) { + /** + * Creates a new Color literal. + */ + function create(red, green, blue, alpha) { + return { + red: red, + green: green, + blue: blue, + alpha: alpha, + }; + } + Color.create = create; + /** + * Checks whether the given literal conforms to the {@link Color} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Is.numberRange(candidate.red, 0, 1) && + Is.numberRange(candidate.green, 0, 1) && + Is.numberRange(candidate.blue, 0, 1) && + Is.numberRange(candidate.alpha, 0, 1) + ); + } + Color.is = is; + })(Color || (exports.Color = Color = {})); + /** + * The ColorInformation namespace provides helper functions to work with + * {@link ColorInformation} literals. + */ + var ColorInformation; + (function (ColorInformation) { + /** + * Creates a new ColorInformation literal. + */ + function create(range, color) { + return { + range: range, + color: color, + }; + } + ColorInformation.create = create; + /** + * Checks whether the given literal conforms to the {@link ColorInformation} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Range.is(candidate.range) && + Color.is(candidate.color) + ); + } + ColorInformation.is = is; + })( + ColorInformation || (exports.ColorInformation = ColorInformation = {}) + ); + /** + * The Color namespace provides helper functions to work with + * {@link ColorPresentation} literals. + */ + var ColorPresentation; + (function (ColorPresentation) { + /** + * Creates a new ColorInformation literal. + */ + function create(label, textEdit, additionalTextEdits) { + return { + label: label, + textEdit: textEdit, + additionalTextEdits: additionalTextEdits, + }; + } + ColorPresentation.create = create; + /** + * Checks whether the given literal conforms to the {@link ColorInformation} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Is.string(candidate.label) && + (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && + (Is.undefined(candidate.additionalTextEdits) || + Is.typedArray(candidate.additionalTextEdits, TextEdit.is)) + ); + } + ColorPresentation.is = is; + })( + ColorPresentation || + (exports.ColorPresentation = ColorPresentation = {}) + ); + /** + * A set of predefined range kinds. + */ + var FoldingRangeKind; + (function (FoldingRangeKind) { + /** + * Folding range for a comment + */ + FoldingRangeKind.Comment = "comment"; + /** + * Folding range for an import or include + */ + FoldingRangeKind.Imports = "imports"; + /** + * Folding range for a region (e.g. `#region`) + */ + FoldingRangeKind.Region = "region"; + })( + FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {}) + ); + /** + * The folding range namespace provides helper functions to work with + * {@link FoldingRange} literals. + */ + var FoldingRange; + (function (FoldingRange) { + /** + * Creates a new FoldingRange literal. + */ + function create( + startLine, + endLine, + startCharacter, + endCharacter, + kind, + collapsedText + ) { + var result = { + startLine: startLine, + endLine: endLine, + }; + if (Is.defined(startCharacter)) { + result.startCharacter = startCharacter; + } + if (Is.defined(endCharacter)) { + result.endCharacter = endCharacter; + } + if (Is.defined(kind)) { + result.kind = kind; + } + if (Is.defined(collapsedText)) { + result.collapsedText = collapsedText; + } + return result; + } + FoldingRange.create = create; + /** + * Checks whether the given literal conforms to the {@link FoldingRange} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Is.uinteger(candidate.startLine) && + Is.uinteger(candidate.startLine) && + (Is.undefined(candidate.startCharacter) || + Is.uinteger(candidate.startCharacter)) && + (Is.undefined(candidate.endCharacter) || + Is.uinteger(candidate.endCharacter)) && + (Is.undefined(candidate.kind) || Is.string(candidate.kind)) + ); + } + FoldingRange.is = is; + })(FoldingRange || (exports.FoldingRange = FoldingRange = {})); + /** + * The DiagnosticRelatedInformation namespace provides helper functions to work with + * {@link DiagnosticRelatedInformation} literals. + */ + var DiagnosticRelatedInformation; + (function (DiagnosticRelatedInformation) { + /** + * Creates a new DiagnosticRelatedInformation literal. + */ + function create(location, message) { + return { + location: location, + message: message, + }; + } + DiagnosticRelatedInformation.create = create; + /** + * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Location.is(candidate.location) && + Is.string(candidate.message) + ); + } + DiagnosticRelatedInformation.is = is; + })( + DiagnosticRelatedInformation || + (exports.DiagnosticRelatedInformation = + DiagnosticRelatedInformation = + {}) + ); + /** + * The diagnostic's severity. + */ + var DiagnosticSeverity; + (function (DiagnosticSeverity) { + /** + * Reports an error. + */ + DiagnosticSeverity.Error = 1; + /** + * Reports a warning. + */ + DiagnosticSeverity.Warning = 2; + /** + * Reports an information. + */ + DiagnosticSeverity.Information = 3; + /** + * Reports a hint. + */ + DiagnosticSeverity.Hint = 4; + })( + DiagnosticSeverity || + (exports.DiagnosticSeverity = DiagnosticSeverity = {}) + ); + /** + * The diagnostic tags. + * + * @since 3.15.0 + */ + var DiagnosticTag; + (function (DiagnosticTag) { + /** + * Unused or unnecessary code. + * + * Clients are allowed to render diagnostics with this tag faded out instead of having + * an error squiggle. + */ + DiagnosticTag.Unnecessary = 1; + /** + * Deprecated or obsolete code. + * + * Clients are allowed to rendered diagnostics with this tag strike through. + */ + DiagnosticTag.Deprecated = 2; + })(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {})); + /** + * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. + * + * @since 3.16.0 + */ + var CodeDescription; + (function (CodeDescription) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.href); + } + CodeDescription.is = is; + })(CodeDescription || (exports.CodeDescription = CodeDescription = {})); + /** + * The Diagnostic namespace provides helper functions to work with + * {@link Diagnostic} literals. + */ + var Diagnostic; + (function (Diagnostic) { + /** + * Creates a new Diagnostic literal. + */ + function create( + range, + message, + severity, + code, + source, + relatedInformation + ) { + var result = { + range: range, + message: message, + }; + if (Is.defined(severity)) { + result.severity = severity; + } + if (Is.defined(code)) { + result.code = code; + } + if (Is.defined(source)) { + result.source = source; + } + if (Is.defined(relatedInformation)) { + result.relatedInformation = relatedInformation; + } + return result; + } + Diagnostic.create = create; + /** + * Checks whether the given literal conforms to the {@link Diagnostic} interface. + */ + function is(value) { + var _a; + var candidate = value; + return ( + Is.defined(candidate) && + Range.is(candidate.range) && + Is.string(candidate.message) && + (Is.number(candidate.severity) || + Is.undefined(candidate.severity)) && + (Is.integer(candidate.code) || + Is.string(candidate.code) || + Is.undefined(candidate.code)) && + (Is.undefined(candidate.codeDescription) || + Is.string( + (_a = candidate.codeDescription) === null || _a === void 0 + ? void 0 + : _a.href + )) && + (Is.string(candidate.source) || Is.undefined(candidate.source)) && + (Is.undefined(candidate.relatedInformation) || + Is.typedArray( + candidate.relatedInformation, + DiagnosticRelatedInformation.is + )) + ); + } + Diagnostic.is = is; + })(Diagnostic || (exports.Diagnostic = Diagnostic = {})); + /** + * The Command namespace provides helper functions to work with + * {@link Command} literals. + */ + var Command; + (function (Command) { + /** + * Creates a new Command literal. + */ + function create(title, command) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var result = { + title: title, + command: command, + }; + if (Is.defined(args) && args.length > 0) { + result.arguments = args; + } + return result; + } + Command.create = create; + /** + * Checks whether the given literal conforms to the {@link Command} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Is.string(candidate.title) && + Is.string(candidate.command) + ); + } + Command.is = is; + })(Command || (exports.Command = Command = {})); + /** + * The TextEdit namespace provides helper function to create replace, + * insert and delete edits more easily. + */ + var TextEdit; + (function (TextEdit) { + /** + * Creates a replace text edit. + * @param range The range of text to be replaced. + * @param newText The new text. + */ + function replace(range, newText) { + return { + range: range, + newText: newText, + }; + } + TextEdit.replace = replace; + /** + * Creates an insert text edit. + * @param position The position to insert the text at. + * @param newText The text to be inserted. + */ + function insert(position, newText) { + return { + range: { + start: position, + end: position, + }, + newText: newText, + }; + } + TextEdit.insert = insert; + /** + * Creates a delete text edit. + * @param range The range of text to be deleted. + */ + function del(range) { + return { + range: range, + newText: "", + }; + } + TextEdit.del = del; + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Is.string(candidate.newText) && + Range.is(candidate.range) + ); + } + TextEdit.is = is; + })(TextEdit || (exports.TextEdit = TextEdit = {})); + var ChangeAnnotation; + (function (ChangeAnnotation) { + function create(label, needsConfirmation, description) { + var result = { + label: label, + }; + if (needsConfirmation !== undefined) { + result.needsConfirmation = needsConfirmation; + } + if (description !== undefined) { + result.description = description; + } + return result; + } + ChangeAnnotation.create = create; + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Is.string(candidate.label) && + (Is.boolean(candidate.needsConfirmation) || + candidate.needsConfirmation === undefined) && + (Is.string(candidate.description) || + candidate.description === undefined) + ); + } + ChangeAnnotation.is = is; + })( + ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {}) + ); + var ChangeAnnotationIdentifier; + (function (ChangeAnnotationIdentifier) { + function is(value) { + var candidate = value; + return Is.string(candidate); + } + ChangeAnnotationIdentifier.is = is; + })( + ChangeAnnotationIdentifier || + (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = + {}) + ); + var AnnotatedTextEdit; + (function (AnnotatedTextEdit) { + /** + * Creates an annotated replace text edit. + * + * @param range The range of text to be replaced. + * @param newText The new text. + * @param annotation The annotation. + */ + function replace(range, newText, annotation) { + return { + range: range, + newText: newText, + annotationId: annotation, + }; + } + AnnotatedTextEdit.replace = replace; + /** + * Creates an annotated insert text edit. + * + * @param position The position to insert the text at. + * @param newText The text to be inserted. + * @param annotation The annotation. + */ + function insert(position, newText, annotation) { + return { + range: { + start: position, + end: position, + }, + newText: newText, + annotationId: annotation, + }; + } + AnnotatedTextEdit.insert = insert; + /** + * Creates an annotated delete text edit. + * + * @param range The range of text to be deleted. + * @param annotation The annotation. + */ + function del(range, annotation) { + return { + range: range, + newText: "", + annotationId: annotation, + }; + } + AnnotatedTextEdit.del = del; + function is(value) { + var candidate = value; + return ( + TextEdit.is(candidate) && + (ChangeAnnotation.is(candidate.annotationId) || + ChangeAnnotationIdentifier.is(candidate.annotationId)) + ); + } + AnnotatedTextEdit.is = is; + })( + AnnotatedTextEdit || + (exports.AnnotatedTextEdit = AnnotatedTextEdit = {}) + ); + /** + * The TextDocumentEdit namespace provides helper function to create + * an edit that manipulates a text document. + */ + var TextDocumentEdit; + (function (TextDocumentEdit) { + /** + * Creates a new `TextDocumentEdit` + */ + function create(textDocument, edits) { + return { + textDocument: textDocument, + edits: edits, + }; + } + TextDocumentEdit.create = create; + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + OptionalVersionedTextDocumentIdentifier.is( + candidate.textDocument + ) && + Array.isArray(candidate.edits) + ); + } + TextDocumentEdit.is = is; + })( + TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {}) + ); + var CreateFile; + (function (CreateFile) { + function create(uri, options, annotation) { + var result = { + kind: "create", + uri: uri, + }; + if ( + options !== undefined && + (options.overwrite !== undefined || + options.ignoreIfExists !== undefined) + ) { + result.options = options; + } + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + CreateFile.create = create; + function is(value) { + var candidate = value; + return ( + candidate && + candidate.kind === "create" && + Is.string(candidate.uri) && + (candidate.options === undefined || + ((candidate.options.overwrite === undefined || + Is.boolean(candidate.options.overwrite)) && + (candidate.options.ignoreIfExists === undefined || + Is.boolean(candidate.options.ignoreIfExists)))) && + (candidate.annotationId === undefined || + ChangeAnnotationIdentifier.is(candidate.annotationId)) + ); + } + CreateFile.is = is; + })(CreateFile || (exports.CreateFile = CreateFile = {})); + var RenameFile; + (function (RenameFile) { + function create(oldUri, newUri, options, annotation) { + var result = { + kind: "rename", + oldUri: oldUri, + newUri: newUri, + }; + if ( + options !== undefined && + (options.overwrite !== undefined || + options.ignoreIfExists !== undefined) + ) { + result.options = options; + } + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + RenameFile.create = create; + function is(value) { + var candidate = value; + return ( + candidate && + candidate.kind === "rename" && + Is.string(candidate.oldUri) && + Is.string(candidate.newUri) && + (candidate.options === undefined || + ((candidate.options.overwrite === undefined || + Is.boolean(candidate.options.overwrite)) && + (candidate.options.ignoreIfExists === undefined || + Is.boolean(candidate.options.ignoreIfExists)))) && + (candidate.annotationId === undefined || + ChangeAnnotationIdentifier.is(candidate.annotationId)) + ); + } + RenameFile.is = is; + })(RenameFile || (exports.RenameFile = RenameFile = {})); + var DeleteFile; + (function (DeleteFile) { + function create(uri, options, annotation) { + var result = { + kind: "delete", + uri: uri, + }; + if ( + options !== undefined && + (options.recursive !== undefined || + options.ignoreIfNotExists !== undefined) + ) { + result.options = options; + } + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + DeleteFile.create = create; + function is(value) { + var candidate = value; + return ( + candidate && + candidate.kind === "delete" && + Is.string(candidate.uri) && + (candidate.options === undefined || + ((candidate.options.recursive === undefined || + Is.boolean(candidate.options.recursive)) && + (candidate.options.ignoreIfNotExists === undefined || + Is.boolean(candidate.options.ignoreIfNotExists)))) && + (candidate.annotationId === undefined || + ChangeAnnotationIdentifier.is(candidate.annotationId)) + ); + } + DeleteFile.is = is; + })(DeleteFile || (exports.DeleteFile = DeleteFile = {})); + var WorkspaceEdit; + (function (WorkspaceEdit) { + function is(value) { + var candidate = value; + return ( + candidate && + (candidate.changes !== undefined || + candidate.documentChanges !== undefined) && + (candidate.documentChanges === undefined || + candidate.documentChanges.every(function (change) { + if (Is.string(change.kind)) { + return ( + CreateFile.is(change) || + RenameFile.is(change) || + DeleteFile.is(change) + ); + } else { + return TextDocumentEdit.is(change); + } + })) + ); + } + WorkspaceEdit.is = is; + })(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {})); + var TextEditChangeImpl = /** @class */ (function () { + function TextEditChangeImpl(edits, changeAnnotations) { + this.edits = edits; + this.changeAnnotations = changeAnnotations; + } + TextEditChangeImpl.prototype.insert = function ( + position, + newText, + annotation + ) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.insert(position, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.insert(position, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.insert(position, newText, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.replace = function ( + range, + newText, + annotation + ) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.replace(range, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.replace(range, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.replace(range, newText, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.delete = function (range, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.del(range); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.del(range, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.del(range, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.add = function (edit) { + this.edits.push(edit); + }; + TextEditChangeImpl.prototype.all = function () { + return this.edits; + }; + TextEditChangeImpl.prototype.clear = function () { + this.edits.splice(0, this.edits.length); + }; + TextEditChangeImpl.prototype.assertChangeAnnotations = function ( + value + ) { + if (value === undefined) { + throw new Error( + "Text edit change is not configured to manage change annotations." + ); + } + }; + return TextEditChangeImpl; + })(); + /** + * A helper class + */ + var ChangeAnnotations = /** @class */ (function () { + function ChangeAnnotations(annotations) { + this._annotations = + annotations === undefined ? Object.create(null) : annotations; + this._counter = 0; + this._size = 0; + } + ChangeAnnotations.prototype.all = function () { + return this._annotations; + }; + Object.defineProperty(ChangeAnnotations.prototype, "size", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true, + }); + ChangeAnnotations.prototype.manage = function ( + idOrAnnotation, + annotation + ) { + var id; + if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { + id = idOrAnnotation; + } else { + id = this.nextId(); + annotation = idOrAnnotation; + } + if (this._annotations[id] !== undefined) { + throw new Error("Id ".concat(id, " is already in use.")); + } + if (annotation === undefined) { + throw new Error("No annotation provided for id ".concat(id)); + } + this._annotations[id] = annotation; + this._size++; + return id; + }; + ChangeAnnotations.prototype.nextId = function () { + this._counter++; + return this._counter.toString(); + }; + return ChangeAnnotations; + })(); + /** + * A workspace change helps constructing changes to a workspace. + */ + var WorkspaceChange = (exports.WorkspaceChange = + /** @class */ (function () { + function WorkspaceChange(workspaceEdit) { + var _this = this; + this._textEditChanges = Object.create(null); + if (workspaceEdit !== undefined) { + this._workspaceEdit = workspaceEdit; + if (workspaceEdit.documentChanges) { + this._changeAnnotations = new ChangeAnnotations( + workspaceEdit.changeAnnotations + ); + workspaceEdit.changeAnnotations = + this._changeAnnotations.all(); + workspaceEdit.documentChanges.forEach(function (change) { + if (TextDocumentEdit.is(change)) { + var textEditChange = new TextEditChangeImpl( + change.edits, + _this._changeAnnotations + ); + _this._textEditChanges[change.textDocument.uri] = + textEditChange; + } + }); + } else if (workspaceEdit.changes) { + Object.keys(workspaceEdit.changes).forEach(function (key) { + var textEditChange = new TextEditChangeImpl( + workspaceEdit.changes[key] + ); + _this._textEditChanges[key] = textEditChange; + }); + } + } else { + this._workspaceEdit = {}; + } + } + Object.defineProperty(WorkspaceChange.prototype, "edit", { + /** + * Returns the underlying {@link WorkspaceEdit} literal + * use to be returned from a workspace edit operation like rename. + */ + get: function () { + this.initDocumentChanges(); + if (this._changeAnnotations !== undefined) { + if (this._changeAnnotations.size === 0) { + this._workspaceEdit.changeAnnotations = undefined; + } else { + this._workspaceEdit.changeAnnotations = + this._changeAnnotations.all(); + } + } + return this._workspaceEdit; + }, + enumerable: false, + configurable: true, + }); + WorkspaceChange.prototype.getTextEditChange = function (key) { + if (OptionalVersionedTextDocumentIdentifier.is(key)) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error( + "Workspace edit is not configured for document changes." + ); + } + var textDocument = { + uri: key.uri, + version: key.version, + }; + var result = this._textEditChanges[textDocument.uri]; + if (!result) { + var edits = []; + var textDocumentEdit = { + textDocument: textDocument, + edits: edits, + }; + this._workspaceEdit.documentChanges.push(textDocumentEdit); + result = new TextEditChangeImpl( + edits, + this._changeAnnotations + ); + this._textEditChanges[textDocument.uri] = result; + } + return result; + } else { + this.initChanges(); + if (this._workspaceEdit.changes === undefined) { + throw new Error( + "Workspace edit is not configured for normal text edit changes." + ); + } + var result = this._textEditChanges[key]; + if (!result) { + var edits = []; + this._workspaceEdit.changes[key] = edits; + result = new TextEditChangeImpl(edits); + this._textEditChanges[key] = result; + } + return result; + } + }; + WorkspaceChange.prototype.initDocumentChanges = function () { + if ( + this._workspaceEdit.documentChanges === undefined && + this._workspaceEdit.changes === undefined + ) { + this._changeAnnotations = new ChangeAnnotations(); + this._workspaceEdit.documentChanges = []; + this._workspaceEdit.changeAnnotations = + this._changeAnnotations.all(); + } + }; + WorkspaceChange.prototype.initChanges = function () { + if ( + this._workspaceEdit.documentChanges === undefined && + this._workspaceEdit.changes === undefined + ) { + this._workspaceEdit.changes = Object.create(null); + } + }; + WorkspaceChange.prototype.createFile = function ( + uri, + optionsOrAnnotation, + options + ) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error( + "Workspace edit is not configured for document changes." + ); + } + var annotation; + if ( + ChangeAnnotation.is(optionsOrAnnotation) || + ChangeAnnotationIdentifier.is(optionsOrAnnotation) + ) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = CreateFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) + ? annotation + : this._changeAnnotations.manage(annotation); + operation = CreateFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + WorkspaceChange.prototype.renameFile = function ( + oldUri, + newUri, + optionsOrAnnotation, + options + ) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error( + "Workspace edit is not configured for document changes." + ); + } + var annotation; + if ( + ChangeAnnotation.is(optionsOrAnnotation) || + ChangeAnnotationIdentifier.is(optionsOrAnnotation) + ) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = RenameFile.create(oldUri, newUri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) + ? annotation + : this._changeAnnotations.manage(annotation); + operation = RenameFile.create(oldUri, newUri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + WorkspaceChange.prototype.deleteFile = function ( + uri, + optionsOrAnnotation, + options + ) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error( + "Workspace edit is not configured for document changes." + ); + } + var annotation; + if ( + ChangeAnnotation.is(optionsOrAnnotation) || + ChangeAnnotationIdentifier.is(optionsOrAnnotation) + ) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = DeleteFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) + ? annotation + : this._changeAnnotations.manage(annotation); + operation = DeleteFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + return WorkspaceChange; + })()); + /** + * The TextDocumentIdentifier namespace provides helper functions to work with + * {@link TextDocumentIdentifier} literals. + */ + var TextDocumentIdentifier; + (function (TextDocumentIdentifier) { + /** + * Creates a new TextDocumentIdentifier literal. + * @param uri The document's uri. + */ + function create(uri) { + return { + uri: uri, + }; + } + TextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri); + } + TextDocumentIdentifier.is = is; + })( + TextDocumentIdentifier || + (exports.TextDocumentIdentifier = TextDocumentIdentifier = {}) + ); + /** + * The VersionedTextDocumentIdentifier namespace provides helper functions to work with + * {@link VersionedTextDocumentIdentifier} literals. + */ + var VersionedTextDocumentIdentifier; + (function (VersionedTextDocumentIdentifier) { + /** + * Creates a new VersionedTextDocumentIdentifier literal. + * @param uri The document's uri. + * @param version The document's version. + */ + function create(uri, version) { + return { + uri: uri, + version: version, + }; + } + VersionedTextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Is.string(candidate.uri) && + Is.integer(candidate.version) + ); + } + VersionedTextDocumentIdentifier.is = is; + })( + VersionedTextDocumentIdentifier || + (exports.VersionedTextDocumentIdentifier = + VersionedTextDocumentIdentifier = + {}) + ); + /** + * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with + * {@link OptionalVersionedTextDocumentIdentifier} literals. + */ + var OptionalVersionedTextDocumentIdentifier; + (function (OptionalVersionedTextDocumentIdentifier) { + /** + * Creates a new OptionalVersionedTextDocumentIdentifier literal. + * @param uri The document's uri. + * @param version The document's version. + */ + function create(uri, version) { + return { + uri: uri, + version: version, + }; + } + OptionalVersionedTextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Is.string(candidate.uri) && + (candidate.version === null || Is.integer(candidate.version)) + ); + } + OptionalVersionedTextDocumentIdentifier.is = is; + })( + OptionalVersionedTextDocumentIdentifier || + (exports.OptionalVersionedTextDocumentIdentifier = + OptionalVersionedTextDocumentIdentifier = + {}) + ); + /** + * The TextDocumentItem namespace provides helper functions to work with + * {@link TextDocumentItem} literals. + */ + var TextDocumentItem; + (function (TextDocumentItem) { + /** + * Creates a new TextDocumentItem literal. + * @param uri The document's uri. + * @param languageId The document's language identifier. + * @param version The document's version number. + * @param text The document's text. + */ + function create(uri, languageId, version, text) { + return { + uri: uri, + languageId: languageId, + version: version, + text: text, + }; + } + TextDocumentItem.create = create; + /** + * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Is.string(candidate.uri) && + Is.string(candidate.languageId) && + Is.integer(candidate.version) && + Is.string(candidate.text) + ); + } + TextDocumentItem.is = is; + })( + TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {}) + ); + /** + * Describes the content type that a client supports in various + * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. + * + * Please note that `MarkupKinds` must not start with a `$`. This kinds + * are reserved for internal usage. + */ + var MarkupKind; + (function (MarkupKind) { + /** + * Plain text is supported as a content format + */ + MarkupKind.PlainText = "plaintext"; + /** + * Markdown is supported as a content format + */ + MarkupKind.Markdown = "markdown"; + /** + * Checks whether the given value is a value of the {@link MarkupKind} type. + */ + function is(value) { + var candidate = value; + return ( + candidate === MarkupKind.PlainText || + candidate === MarkupKind.Markdown + ); + } + MarkupKind.is = is; + })(MarkupKind || (exports.MarkupKind = MarkupKind = {})); + var MarkupContent; + (function (MarkupContent) { + /** + * Checks whether the given value conforms to the {@link MarkupContent} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(value) && + MarkupKind.is(candidate.kind) && + Is.string(candidate.value) + ); + } + MarkupContent.is = is; + })(MarkupContent || (exports.MarkupContent = MarkupContent = {})); + /** + * The kind of a completion entry. + */ + var CompletionItemKind; + (function (CompletionItemKind) { + CompletionItemKind.Text = 1; + CompletionItemKind.Method = 2; + CompletionItemKind.Function = 3; + CompletionItemKind.Constructor = 4; + CompletionItemKind.Field = 5; + CompletionItemKind.Variable = 6; + CompletionItemKind.Class = 7; + CompletionItemKind.Interface = 8; + CompletionItemKind.Module = 9; + CompletionItemKind.Property = 10; + CompletionItemKind.Unit = 11; + CompletionItemKind.Value = 12; + CompletionItemKind.Enum = 13; + CompletionItemKind.Keyword = 14; + CompletionItemKind.Snippet = 15; + CompletionItemKind.Color = 16; + CompletionItemKind.File = 17; + CompletionItemKind.Reference = 18; + CompletionItemKind.Folder = 19; + CompletionItemKind.EnumMember = 20; + CompletionItemKind.Constant = 21; + CompletionItemKind.Struct = 22; + CompletionItemKind.Event = 23; + CompletionItemKind.Operator = 24; + CompletionItemKind.TypeParameter = 25; + })( + CompletionItemKind || + (exports.CompletionItemKind = CompletionItemKind = {}) + ); + /** + * Defines whether the insert text in a completion item should be interpreted as + * plain text or a snippet. + */ + var InsertTextFormat; + (function (InsertTextFormat) { + /** + * The primary text to be inserted is treated as a plain string. + */ + InsertTextFormat.PlainText = 1; + /** + * The primary text to be inserted is treated as a snippet. + * + * A snippet can define tab stops and placeholders with `$1`, `$2` + * and `${3:foo}`. `$0` defines the final tab stop, it defaults to + * the end of the snippet. Placeholders with equal identifiers are linked, + * that is typing in one will update others too. + * + * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax + */ + InsertTextFormat.Snippet = 2; + })( + InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {}) + ); + /** + * Completion item tags are extra annotations that tweak the rendering of a completion + * item. + * + * @since 3.15.0 + */ + var CompletionItemTag; + (function (CompletionItemTag) { + /** + * Render a completion as obsolete, usually using a strike-out. + */ + CompletionItemTag.Deprecated = 1; + })( + CompletionItemTag || + (exports.CompletionItemTag = CompletionItemTag = {}) + ); + /** + * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. + * + * @since 3.16.0 + */ + var InsertReplaceEdit; + (function (InsertReplaceEdit) { + /** + * Creates a new insert / replace edit + */ + function create(newText, insert, replace) { + return { + newText: newText, + insert: insert, + replace: replace, + }; + } + InsertReplaceEdit.create = create; + /** + * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. + */ + function is(value) { + var candidate = value; + return ( + candidate && + Is.string(candidate.newText) && + Range.is(candidate.insert) && + Range.is(candidate.replace) + ); + } + InsertReplaceEdit.is = is; + })( + InsertReplaceEdit || + (exports.InsertReplaceEdit = InsertReplaceEdit = {}) + ); + /** + * How whitespace and indentation is handled during completion + * item insertion. + * + * @since 3.16.0 + */ + var InsertTextMode; + (function (InsertTextMode) { + /** + * The insertion or replace strings is taken as it is. If the + * value is multi line the lines below the cursor will be + * inserted using the indentation defined in the string value. + * The client will not apply any kind of adjustments to the + * string. + */ + InsertTextMode.asIs = 1; + /** + * The editor adjusts leading whitespace of new lines so that + * they match the indentation up to the cursor of the line for + * which the item is accepted. + * + * Consider a line like this: <2tabs><3tabs>foo. Accepting a + * multi line completion item is indented using 2 tabs and all + * following lines inserted will be indented using 2 tabs as well. + */ + InsertTextMode.adjustIndentation = 2; + })(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {})); + var CompletionItemLabelDetails; + (function (CompletionItemLabelDetails) { + function is(value) { + var candidate = value; + return ( + candidate && + (Is.string(candidate.detail) || candidate.detail === undefined) && + (Is.string(candidate.description) || + candidate.description === undefined) + ); + } + CompletionItemLabelDetails.is = is; + })( + CompletionItemLabelDetails || + (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = + {}) + ); + /** + * The CompletionItem namespace provides functions to deal with + * completion items. + */ + var CompletionItem; + (function (CompletionItem) { + /** + * Create a completion item and seed it with a label. + * @param label The completion item's label + */ + function create(label) { + return { + label: label, + }; + } + CompletionItem.create = create; + })(CompletionItem || (exports.CompletionItem = CompletionItem = {})); + /** + * The CompletionList namespace provides functions to deal with + * completion lists. + */ + var CompletionList; + (function (CompletionList) { + /** + * Creates a new completion list. + * + * @param items The completion items. + * @param isIncomplete The list is not complete. + */ + function create(items, isIncomplete) { + return { + items: items ? items : [], + isIncomplete: !!isIncomplete, + }; + } + CompletionList.create = create; + })(CompletionList || (exports.CompletionList = CompletionList = {})); + var MarkedString; + (function (MarkedString) { + /** + * Creates a marked string from plain text. + * + * @param plainText The plain text. + */ + function fromPlainText(plainText) { + return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash + } + MarkedString.fromPlainText = fromPlainText; + /** + * Checks whether the given value conforms to the {@link MarkedString} type. + */ + function is(value) { + var candidate = value; + return ( + Is.string(candidate) || + (Is.objectLiteral(candidate) && + Is.string(candidate.language) && + Is.string(candidate.value)) + ); + } + MarkedString.is = is; + })(MarkedString || (exports.MarkedString = MarkedString = {})); + var Hover; + (function (Hover) { + /** + * Checks whether the given value conforms to the {@link Hover} interface. + */ + function is(value) { + var candidate = value; + return ( + !!candidate && + Is.objectLiteral(candidate) && + (MarkupContent.is(candidate.contents) || + MarkedString.is(candidate.contents) || + Is.typedArray(candidate.contents, MarkedString.is)) && + (value.range === undefined || Range.is(value.range)) + ); + } + Hover.is = is; + })(Hover || (exports.Hover = Hover = {})); + /** + * The ParameterInformation namespace provides helper functions to work with + * {@link ParameterInformation} literals. + */ + var ParameterInformation; + (function (ParameterInformation) { + /** + * Creates a new parameter information literal. + * + * @param label A label string. + * @param documentation A doc string. + */ + function create(label, documentation) { + return documentation + ? { + label: label, + documentation: documentation, + } + : { + label: label, + }; + } + ParameterInformation.create = create; + })( + ParameterInformation || + (exports.ParameterInformation = ParameterInformation = {}) + ); + /** + * The SignatureInformation namespace provides helper functions to work with + * {@link SignatureInformation} literals. + */ + var SignatureInformation; + (function (SignatureInformation) { + function create(label, documentation) { + var parameters = []; + for (var _i = 2; _i < arguments.length; _i++) { + parameters[_i - 2] = arguments[_i]; + } + var result = { + label: label, + }; + if (Is.defined(documentation)) { + result.documentation = documentation; + } + if (Is.defined(parameters)) { + result.parameters = parameters; + } else { + result.parameters = []; + } + return result; + } + SignatureInformation.create = create; + })( + SignatureInformation || + (exports.SignatureInformation = SignatureInformation = {}) + ); + /** + * A document highlight kind. + */ + var DocumentHighlightKind; + (function (DocumentHighlightKind) { + /** + * A textual occurrence. + */ + DocumentHighlightKind.Text = 1; + /** + * Read-access of a symbol, like reading a variable. + */ + DocumentHighlightKind.Read = 2; + /** + * Write-access of a symbol, like writing to a variable. + */ + DocumentHighlightKind.Write = 3; + })( + DocumentHighlightKind || + (exports.DocumentHighlightKind = DocumentHighlightKind = {}) + ); + /** + * DocumentHighlight namespace to provide helper functions to work with + * {@link DocumentHighlight} literals. + */ + var DocumentHighlight; + (function (DocumentHighlight) { + /** + * Create a DocumentHighlight object. + * @param range The range the highlight applies to. + * @param kind The highlight kind + */ + function create(range, kind) { + var result = { + range: range, + }; + if (Is.number(kind)) { + result.kind = kind; + } + return result; + } + DocumentHighlight.create = create; + })( + DocumentHighlight || + (exports.DocumentHighlight = DocumentHighlight = {}) + ); + /** + * A symbol kind. + */ + var SymbolKind; + (function (SymbolKind) { + SymbolKind.File = 1; + SymbolKind.Module = 2; + SymbolKind.Namespace = 3; + SymbolKind.Package = 4; + SymbolKind.Class = 5; + SymbolKind.Method = 6; + SymbolKind.Property = 7; + SymbolKind.Field = 8; + SymbolKind.Constructor = 9; + SymbolKind.Enum = 10; + SymbolKind.Interface = 11; + SymbolKind.Function = 12; + SymbolKind.Variable = 13; + SymbolKind.Constant = 14; + SymbolKind.String = 15; + SymbolKind.Number = 16; + SymbolKind.Boolean = 17; + SymbolKind.Array = 18; + SymbolKind.Object = 19; + SymbolKind.Key = 20; + SymbolKind.Null = 21; + SymbolKind.EnumMember = 22; + SymbolKind.Struct = 23; + SymbolKind.Event = 24; + SymbolKind.Operator = 25; + SymbolKind.TypeParameter = 26; + })(SymbolKind || (exports.SymbolKind = SymbolKind = {})); + /** + * Symbol tags are extra annotations that tweak the rendering of a symbol. + * + * @since 3.16 + */ + var SymbolTag; + (function (SymbolTag) { + /** + * Render a symbol as obsolete, usually using a strike-out. + */ + SymbolTag.Deprecated = 1; + })(SymbolTag || (exports.SymbolTag = SymbolTag = {})); + var SymbolInformation; + (function (SymbolInformation) { + /** + * Creates a new symbol information literal. + * + * @param name The name of the symbol. + * @param kind The kind of the symbol. + * @param range The range of the location of the symbol. + * @param uri The resource of the location of symbol. + * @param containerName The name of the symbol containing the symbol. + */ + function create(name, kind, range, uri, containerName) { + var result = { + name: name, + kind: kind, + location: { + uri: uri, + range: range, + }, + }; + if (containerName) { + result.containerName = containerName; + } + return result; + } + SymbolInformation.create = create; + })( + SymbolInformation || + (exports.SymbolInformation = SymbolInformation = {}) + ); + var WorkspaceSymbol; + (function (WorkspaceSymbol) { + /** + * Create a new workspace symbol. + * + * @param name The name of the symbol. + * @param kind The kind of the symbol. + * @param uri The resource of the location of the symbol. + * @param range An options range of the location. + * @returns A WorkspaceSymbol. + */ + function create(name, kind, uri, range) { + return range !== undefined + ? { + name: name, + kind: kind, + location: { + uri: uri, + range: range, + }, + } + : { + name: name, + kind: kind, + location: { + uri: uri, + }, + }; + } + WorkspaceSymbol.create = create; + })(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {})); + var DocumentSymbol; + (function (DocumentSymbol) { + /** + * Creates a new symbol information literal. + * + * @param name The name of the symbol. + * @param detail The detail of the symbol. + * @param kind The kind of the symbol. + * @param range The range of the symbol. + * @param selectionRange The selectionRange of the symbol. + * @param children Children of the symbol. + */ + function create(name, detail, kind, range, selectionRange, children) { + var result = { + name: name, + detail: detail, + kind: kind, + range: range, + selectionRange: selectionRange, + }; + if (children !== undefined) { + result.children = children; + } + return result; + } + DocumentSymbol.create = create; + /** + * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. + */ + function is(value) { + var candidate = value; + return ( + candidate && + Is.string(candidate.name) && + Is.number(candidate.kind) && + Range.is(candidate.range) && + Range.is(candidate.selectionRange) && + (candidate.detail === undefined || Is.string(candidate.detail)) && + (candidate.deprecated === undefined || + Is.boolean(candidate.deprecated)) && + (candidate.children === undefined || + Array.isArray(candidate.children)) && + (candidate.tags === undefined || Array.isArray(candidate.tags)) + ); + } + DocumentSymbol.is = is; + })(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {})); + /** + * A set of predefined code action kinds + */ + var CodeActionKind; + (function (CodeActionKind) { + /** + * Empty kind. + */ + CodeActionKind.Empty = ""; + /** + * Base kind for quickfix actions: 'quickfix' + */ + CodeActionKind.QuickFix = "quickfix"; + /** + * Base kind for refactoring actions: 'refactor' + */ + CodeActionKind.Refactor = "refactor"; + /** + * Base kind for refactoring extraction actions: 'refactor.extract' + * + * Example extract actions: + * + * - Extract method + * - Extract function + * - Extract variable + * - Extract interface from class + * - ... + */ + CodeActionKind.RefactorExtract = "refactor.extract"; + /** + * Base kind for refactoring inline actions: 'refactor.inline' + * + * Example inline actions: + * + * - Inline function + * - Inline variable + * - Inline constant + * - ... + */ + CodeActionKind.RefactorInline = "refactor.inline"; + /** + * Base kind for refactoring rewrite actions: 'refactor.rewrite' + * + * Example rewrite actions: + * + * - Convert JavaScript function to class + * - Add or remove parameter + * - Encapsulate field + * - Make method static + * - Move method to base class + * - ... + */ + CodeActionKind.RefactorRewrite = "refactor.rewrite"; + /** + * Base kind for source actions: `source` + * + * Source code actions apply to the entire file. + */ + CodeActionKind.Source = "source"; + /** + * Base kind for an organize imports source action: `source.organizeImports` + */ + CodeActionKind.SourceOrganizeImports = "source.organizeImports"; + /** + * Base kind for auto-fix source actions: `source.fixAll`. + * + * Fix all actions automatically fix errors that have a clear fix that do not require user input. + * They should not suppress errors or perform unsafe fixes such as generating new types or classes. + * + * @since 3.15.0 + */ + CodeActionKind.SourceFixAll = "source.fixAll"; + })(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {})); + /** + * The reason why code actions were requested. + * + * @since 3.17.0 + */ + var CodeActionTriggerKind; + (function (CodeActionTriggerKind) { + /** + * Code actions were explicitly requested by the user or by an extension. + */ + CodeActionTriggerKind.Invoked = 1; + /** + * Code actions were requested automatically. + * + * This typically happens when current selection in a file changes, but can + * also be triggered when file content changes. + */ + CodeActionTriggerKind.Automatic = 2; + })( + CodeActionTriggerKind || + (exports.CodeActionTriggerKind = CodeActionTriggerKind = {}) + ); + /** + * The CodeActionContext namespace provides helper functions to work with + * {@link CodeActionContext} literals. + */ + var CodeActionContext; + (function (CodeActionContext) { + /** + * Creates a new CodeActionContext literal. + */ + function create(diagnostics, only, triggerKind) { + var result = { + diagnostics: diagnostics, + }; + if (only !== undefined && only !== null) { + result.only = only; + } + if (triggerKind !== undefined && triggerKind !== null) { + result.triggerKind = triggerKind; + } + return result; + } + CodeActionContext.create = create; + /** + * Checks whether the given literal conforms to the {@link CodeActionContext} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Is.typedArray(candidate.diagnostics, Diagnostic.is) && + (candidate.only === undefined || + Is.typedArray(candidate.only, Is.string)) && + (candidate.triggerKind === undefined || + candidate.triggerKind === CodeActionTriggerKind.Invoked || + candidate.triggerKind === CodeActionTriggerKind.Automatic) + ); + } + CodeActionContext.is = is; + })( + CodeActionContext || + (exports.CodeActionContext = CodeActionContext = {}) + ); + var CodeAction; + (function (CodeAction) { + function create(title, kindOrCommandOrEdit, kind) { + var result = { + title: title, + }; + var checkKind = true; + if (typeof kindOrCommandOrEdit === "string") { + checkKind = false; + result.kind = kindOrCommandOrEdit; + } else if (Command.is(kindOrCommandOrEdit)) { + result.command = kindOrCommandOrEdit; + } else { + result.edit = kindOrCommandOrEdit; + } + if (checkKind && kind !== undefined) { + result.kind = kind; + } + return result; + } + CodeAction.create = create; + function is(value) { + var candidate = value; + return ( + candidate && + Is.string(candidate.title) && + (candidate.diagnostics === undefined || + Is.typedArray(candidate.diagnostics, Diagnostic.is)) && + (candidate.kind === undefined || Is.string(candidate.kind)) && + (candidate.edit !== undefined || + candidate.command !== undefined) && + (candidate.command === undefined || + Command.is(candidate.command)) && + (candidate.isPreferred === undefined || + Is.boolean(candidate.isPreferred)) && + (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)) + ); + } + CodeAction.is = is; + })(CodeAction || (exports.CodeAction = CodeAction = {})); + /** + * The CodeLens namespace provides helper functions to work with + * {@link CodeLens} literals. + */ + var CodeLens; + (function (CodeLens) { + /** + * Creates a new CodeLens literal. + */ + function create(range, data) { + var result = { + range: range, + }; + if (Is.defined(data)) { + result.data = data; + } + return result; + } + CodeLens.create = create; + /** + * Checks whether the given literal conforms to the {@link CodeLens} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Range.is(candidate.range) && + (Is.undefined(candidate.command) || Command.is(candidate.command)) + ); + } + CodeLens.is = is; + })(CodeLens || (exports.CodeLens = CodeLens = {})); + /** + * The FormattingOptions namespace provides helper functions to work with + * {@link FormattingOptions} literals. + */ + var FormattingOptions; + (function (FormattingOptions) { + /** + * Creates a new FormattingOptions literal. + */ + function create(tabSize, insertSpaces) { + return { + tabSize: tabSize, + insertSpaces: insertSpaces, + }; + } + FormattingOptions.create = create; + /** + * Checks whether the given literal conforms to the {@link FormattingOptions} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Is.uinteger(candidate.tabSize) && + Is.boolean(candidate.insertSpaces) + ); + } + FormattingOptions.is = is; + })( + FormattingOptions || + (exports.FormattingOptions = FormattingOptions = {}) + ); + /** + * The DocumentLink namespace provides helper functions to work with + * {@link DocumentLink} literals. + */ + var DocumentLink; + (function (DocumentLink) { + /** + * Creates a new DocumentLink literal. + */ + function create(range, target, data) { + return { + range: range, + target: target, + data: data, + }; + } + DocumentLink.create = create; + /** + * Checks whether the given literal conforms to the {@link DocumentLink} interface. + */ + function is(value) { + var candidate = value; + return ( + Is.defined(candidate) && + Range.is(candidate.range) && + (Is.undefined(candidate.target) || Is.string(candidate.target)) + ); + } + DocumentLink.is = is; + })(DocumentLink || (exports.DocumentLink = DocumentLink = {})); + /** + * The SelectionRange namespace provides helper function to work with + * SelectionRange literals. + */ + var SelectionRange; + (function (SelectionRange) { + /** + * Creates a new SelectionRange + * @param range the range. + * @param parent an optional parent. + */ + function create(range, parent) { + return { + range: range, + parent: parent, + }; + } + SelectionRange.create = create; + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + Range.is(candidate.range) && + (candidate.parent === undefined || + SelectionRange.is(candidate.parent)) + ); + } + SelectionRange.is = is; + })(SelectionRange || (exports.SelectionRange = SelectionRange = {})); + /** + * A set of predefined token types. This set is not fixed + * an clients can specify additional token types via the + * corresponding client capabilities. + * + * @since 3.16.0 + */ + var SemanticTokenTypes; + (function (SemanticTokenTypes) { + SemanticTokenTypes["namespace"] = "namespace"; + /** + * Represents a generic type. Acts as a fallback for types which can't be mapped to + * a specific type like class or enum. + */ + SemanticTokenTypes["type"] = "type"; + SemanticTokenTypes["class"] = "class"; + SemanticTokenTypes["enum"] = "enum"; + SemanticTokenTypes["interface"] = "interface"; + SemanticTokenTypes["struct"] = "struct"; + SemanticTokenTypes["typeParameter"] = "typeParameter"; + SemanticTokenTypes["parameter"] = "parameter"; + SemanticTokenTypes["variable"] = "variable"; + SemanticTokenTypes["property"] = "property"; + SemanticTokenTypes["enumMember"] = "enumMember"; + SemanticTokenTypes["event"] = "event"; + SemanticTokenTypes["function"] = "function"; + SemanticTokenTypes["method"] = "method"; + SemanticTokenTypes["macro"] = "macro"; + SemanticTokenTypes["keyword"] = "keyword"; + SemanticTokenTypes["modifier"] = "modifier"; + SemanticTokenTypes["comment"] = "comment"; + SemanticTokenTypes["string"] = "string"; + SemanticTokenTypes["number"] = "number"; + SemanticTokenTypes["regexp"] = "regexp"; + SemanticTokenTypes["operator"] = "operator"; + /** + * @since 3.17.0 + */ + SemanticTokenTypes["decorator"] = "decorator"; + })( + SemanticTokenTypes || + (exports.SemanticTokenTypes = SemanticTokenTypes = {}) + ); + /** + * A set of predefined token modifiers. This set is not fixed + * an clients can specify additional token types via the + * corresponding client capabilities. + * + * @since 3.16.0 + */ + var SemanticTokenModifiers; + (function (SemanticTokenModifiers) { + SemanticTokenModifiers["declaration"] = "declaration"; + SemanticTokenModifiers["definition"] = "definition"; + SemanticTokenModifiers["readonly"] = "readonly"; + SemanticTokenModifiers["static"] = "static"; + SemanticTokenModifiers["deprecated"] = "deprecated"; + SemanticTokenModifiers["abstract"] = "abstract"; + SemanticTokenModifiers["async"] = "async"; + SemanticTokenModifiers["modification"] = "modification"; + SemanticTokenModifiers["documentation"] = "documentation"; + SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; + })( + SemanticTokenModifiers || + (exports.SemanticTokenModifiers = SemanticTokenModifiers = {}) + ); + /** + * @since 3.16.0 + */ + var SemanticTokens; + (function (SemanticTokens) { + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + (candidate.resultId === undefined || + typeof candidate.resultId === "string") && + Array.isArray(candidate.data) && + (candidate.data.length === 0 || + typeof candidate.data[0] === "number") + ); + } + SemanticTokens.is = is; + })(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {})); + /** + * The InlineValueText namespace provides functions to deal with InlineValueTexts. + * + * @since 3.17.0 + */ + var InlineValueText; + (function (InlineValueText) { + /** + * Creates a new InlineValueText literal. + */ + function create(range, text) { + return { + range: range, + text: text, + }; + } + InlineValueText.create = create; + function is(value) { + var candidate = value; + return ( + candidate !== undefined && + candidate !== null && + Range.is(candidate.range) && + Is.string(candidate.text) + ); + } + InlineValueText.is = is; + })(InlineValueText || (exports.InlineValueText = InlineValueText = {})); + /** + * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups. + * + * @since 3.17.0 + */ + var InlineValueVariableLookup; + (function (InlineValueVariableLookup) { + /** + * Creates a new InlineValueText literal. + */ + function create(range, variableName, caseSensitiveLookup) { + return { + range: range, + variableName: variableName, + caseSensitiveLookup: caseSensitiveLookup, + }; + } + InlineValueVariableLookup.create = create; + function is(value) { + var candidate = value; + return ( + candidate !== undefined && + candidate !== null && + Range.is(candidate.range) && + Is.boolean(candidate.caseSensitiveLookup) && + (Is.string(candidate.variableName) || + candidate.variableName === undefined) + ); + } + InlineValueVariableLookup.is = is; + })( + InlineValueVariableLookup || + (exports.InlineValueVariableLookup = InlineValueVariableLookup = {}) + ); + /** + * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression. + * + * @since 3.17.0 + */ + var InlineValueEvaluatableExpression; + (function (InlineValueEvaluatableExpression) { + /** + * Creates a new InlineValueEvaluatableExpression literal. + */ + function create(range, expression) { + return { + range: range, + expression: expression, + }; + } + InlineValueEvaluatableExpression.create = create; + function is(value) { + var candidate = value; + return ( + candidate !== undefined && + candidate !== null && + Range.is(candidate.range) && + (Is.string(candidate.expression) || + candidate.expression === undefined) + ); + } + InlineValueEvaluatableExpression.is = is; + })( + InlineValueEvaluatableExpression || + (exports.InlineValueEvaluatableExpression = + InlineValueEvaluatableExpression = + {}) + ); + /** + * The InlineValueContext namespace provides helper functions to work with + * {@link InlineValueContext} literals. + * + * @since 3.17.0 + */ + var InlineValueContext; + (function (InlineValueContext) { + /** + * Creates a new InlineValueContext literal. + */ + function create(frameId, stoppedLocation) { + return { + frameId: frameId, + stoppedLocation: stoppedLocation, + }; + } + InlineValueContext.create = create; + /** + * Checks whether the given literal conforms to the {@link InlineValueContext} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(value.stoppedLocation); + } + InlineValueContext.is = is; + })( + InlineValueContext || + (exports.InlineValueContext = InlineValueContext = {}) + ); + /** + * Inlay hint kinds. + * + * @since 3.17.0 + */ + var InlayHintKind; + (function (InlayHintKind) { + /** + * An inlay hint that for a type annotation. + */ + InlayHintKind.Type = 1; + /** + * An inlay hint that is for a parameter. + */ + InlayHintKind.Parameter = 2; + function is(value) { + return value === 1 || value === 2; + } + InlayHintKind.is = is; + })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {})); + var InlayHintLabelPart; + (function (InlayHintLabelPart) { + function create(value) { + return { + value: value, + }; + } + InlayHintLabelPart.create = create; + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + (candidate.tooltip === undefined || + Is.string(candidate.tooltip) || + MarkupContent.is(candidate.tooltip)) && + (candidate.location === undefined || + Location.is(candidate.location)) && + (candidate.command === undefined || Command.is(candidate.command)) + ); + } + InlayHintLabelPart.is = is; + })( + InlayHintLabelPart || + (exports.InlayHintLabelPart = InlayHintLabelPart = {}) + ); + var InlayHint; + (function (InlayHint) { + function create(position, label, kind) { + var result = { + position: position, + label: label, + }; + if (kind !== undefined) { + result.kind = kind; + } + return result; + } + InlayHint.create = create; + function is(value) { + var candidate = value; + return ( + (Is.objectLiteral(candidate) && + Position.is(candidate.position) && + (Is.string(candidate.label) || + Is.typedArray(candidate.label, InlayHintLabelPart.is)) && + (candidate.kind === undefined || + InlayHintKind.is(candidate.kind)) && + candidate.textEdits === undefined) || + (Is.typedArray(candidate.textEdits, TextEdit.is) && + (candidate.tooltip === undefined || + Is.string(candidate.tooltip) || + MarkupContent.is(candidate.tooltip)) && + (candidate.paddingLeft === undefined || + Is.boolean(candidate.paddingLeft)) && + (candidate.paddingRight === undefined || + Is.boolean(candidate.paddingRight))) + ); + } + InlayHint.is = is; + })(InlayHint || (exports.InlayHint = InlayHint = {})); + var WorkspaceFolder; + (function (WorkspaceFolder) { + function is(value) { + var candidate = value; + return ( + Is.objectLiteral(candidate) && + URI.is(candidate.uri) && + Is.string(candidate.name) + ); + } + WorkspaceFolder.is = is; + })(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {})); + var EOL = (exports.EOL = ["\n", "\r\n", "\r"]); + /** + * @deprecated Use the text document from the new vscode-languageserver-textdocument package. + */ + var TextDocument; + (function (TextDocument) { + /** + * Creates a new ITextDocument literal from the given uri and content. + * @param uri The document's uri. + * @param languageId The document's language Id. + * @param version The document's version. + * @param content The document's content. + */ + function create(uri, languageId, version, content) { + return new FullTextDocument(uri, languageId, version, content); + } + TextDocument.create = create; + /** + * Checks whether the given literal conforms to the {@link ITextDocument} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && + Is.string(candidate.uri) && + (Is.undefined(candidate.languageId) || + Is.string(candidate.languageId)) && + Is.uinteger(candidate.lineCount) && + Is.func(candidate.getText) && + Is.func(candidate.positionAt) && + Is.func(candidate.offsetAt) + ? true + : false; + } + TextDocument.is = is; + function applyEdits(document, edits) { + var text = document.getText(); + var sortedEdits = mergeSort(edits, function (a, b) { + var diff = a.range.start.line - b.range.start.line; + if (diff === 0) { + return a.range.start.character - b.range.start.character; + } + return diff; + }); + var lastModifiedOffset = text.length; + for (var i = sortedEdits.length - 1; i >= 0; i--) { + var e = sortedEdits[i]; + var startOffset = document.offsetAt(e.range.start); + var endOffset = document.offsetAt(e.range.end); + if (endOffset <= lastModifiedOffset) { + text = + text.substring(0, startOffset) + + e.newText + + text.substring(endOffset, text.length); + } else { + throw new Error("Overlapping edit"); + } + lastModifiedOffset = startOffset; + } + return text; + } + TextDocument.applyEdits = applyEdits; + function mergeSort(data, compare) { + if (data.length <= 1) { + // sorted + return data; + } + var p = (data.length / 2) | 0; + var left = data.slice(0, p); + var right = data.slice(p); + mergeSort(left, compare); + mergeSort(right, compare); + var leftIdx = 0; + var rightIdx = 0; + var i = 0; + while (leftIdx < left.length && rightIdx < right.length) { + var ret = compare(left[leftIdx], right[rightIdx]); + if (ret <= 0) { + // smaller_equal -> take left to preserve order + data[i++] = left[leftIdx++]; + } else { + // greater -> take right + data[i++] = right[rightIdx++]; + } + } + while (leftIdx < left.length) { + data[i++] = left[leftIdx++]; + } + while (rightIdx < right.length) { + data[i++] = right[rightIdx++]; + } + return data; + } + })(TextDocument || (exports.TextDocument = TextDocument = {})); + /** + * @deprecated Use the text document from the new vscode-languageserver-textdocument package. + */ + var FullTextDocument = /** @class */ (function () { + function FullTextDocument(uri, languageId, version, content) { + this._uri = uri; + this._languageId = languageId; + this._version = version; + this._content = content; + this._lineOffsets = undefined; + } + Object.defineProperty(FullTextDocument.prototype, "uri", { + get: function () { + return this._uri; + }, + enumerable: false, + configurable: true, + }); + Object.defineProperty(FullTextDocument.prototype, "languageId", { + get: function () { + return this._languageId; + }, + enumerable: false, + configurable: true, + }); + Object.defineProperty(FullTextDocument.prototype, "version", { + get: function () { + return this._version; + }, + enumerable: false, + configurable: true, + }); + FullTextDocument.prototype.getText = function (range) { + if (range) { + var start = this.offsetAt(range.start); + var end = this.offsetAt(range.end); + return this._content.substring(start, end); + } + return this._content; + }; + FullTextDocument.prototype.update = function (event, version) { + this._content = event.text; + this._version = version; + this._lineOffsets = undefined; + }; + FullTextDocument.prototype.getLineOffsets = function () { + if (this._lineOffsets === undefined) { + var lineOffsets = []; + var text = this._content; + var isLineStart = true; + for (var i = 0; i < text.length; i++) { + if (isLineStart) { + lineOffsets.push(i); + isLineStart = false; + } + var ch = text.charAt(i); + isLineStart = ch === "\r" || ch === "\n"; + if ( + ch === "\r" && + i + 1 < text.length && + text.charAt(i + 1) === "\n" + ) { + i++; + } + } + if (isLineStart && text.length > 0) { + lineOffsets.push(text.length); + } + this._lineOffsets = lineOffsets; + } + return this._lineOffsets; + }; + FullTextDocument.prototype.positionAt = function (offset) { + offset = Math.max(Math.min(offset, this._content.length), 0); + var lineOffsets = this.getLineOffsets(); + var low = 0, + high = lineOffsets.length; + if (high === 0) { + return Position.create(0, offset); + } + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (lineOffsets[mid] > offset) { + high = mid; + } else { + low = mid + 1; + } + } + // low is the least x for which the line offset is larger than the current offset + // or array.length if no line offset is larger than the current offset + var line = low - 1; + return Position.create(line, offset - lineOffsets[line]); + }; + FullTextDocument.prototype.offsetAt = function (position) { + var lineOffsets = this.getLineOffsets(); + if (position.line >= lineOffsets.length) { + return this._content.length; + } else if (position.line < 0) { + return 0; + } + var lineOffset = lineOffsets[position.line]; + var nextLineOffset = + position.line + 1 < lineOffsets.length + ? lineOffsets[position.line + 1] + : this._content.length; + return Math.max( + Math.min(lineOffset + position.character, nextLineOffset), + lineOffset + ); + }; + Object.defineProperty(FullTextDocument.prototype, "lineCount", { + get: function () { + return this.getLineOffsets().length; + }, + enumerable: false, + configurable: true, + }); + return FullTextDocument; + })(); + var Is; + (function (Is) { + var toString = Object.prototype.toString; + function defined(value) { + return typeof value !== "undefined"; + } + Is.defined = defined; + function undefined(value) { + return typeof value === "undefined"; + } + Is.undefined = undefined; + function boolean(value) { + return value === true || value === false; + } + Is.boolean = boolean; + function string(value) { + return toString.call(value) === "[object String]"; + } + Is.string = string; + function number(value) { + return toString.call(value) === "[object Number]"; + } + Is.number = number; + function numberRange(value, min, max) { + return ( + toString.call(value) === "[object Number]" && + min <= value && + value <= max + ); + } + Is.numberRange = numberRange; + function integer(value) { + return ( + toString.call(value) === "[object Number]" && + -2147483648 <= value && + value <= 2147483647 + ); + } + Is.integer = integer; + function uinteger(value) { + return ( + toString.call(value) === "[object Number]" && + 0 <= value && + value <= 2147483647 + ); + } + Is.uinteger = uinteger; + function func(value) { + return toString.call(value) === "[object Function]"; + } + Is.func = func; + function objectLiteral(value) { + // Strictly speaking class instances pass this check as well. Since the LSP + // doesn't use classes we ignore this for now. If we do we need to add something + // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` + return value !== null && typeof value === "object"; + } + Is.objectLiteral = objectLiteral; + function typedArray(value, check) { + return Array.isArray(value) && value.every(check); + } + Is.typedArray = typedArray; + })(Is || (Is = {})); -/***/ }), + /***/ + }, -/***/ "../../graphiql-react/dist/SchemaReference.cjs.js": -/*!********************************************************!*\ + /***/ "../../graphiql-react/dist/SchemaReference.cjs.js": + /*!********************************************************!*\ !*** ../../graphiql-react/dist/SchemaReference.cjs.js ***! \********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); -function getTypeInfo(schema, tokenState) { - const info = { - schema, - type: null, - parentType: null, - inputType: null, - directiveDef: null, - fieldDef: null, - argDef: null, - argDefs: null, - objectFieldDefs: null - }; - forEachState.forEachState(tokenState, state => { - var _a, _b; - switch (state.kind) { - case "Query": - case "ShortQuery": - info.type = schema.getQueryType(); - break; - case "Mutation": - info.type = schema.getMutationType(); - break; - case "Subscription": - info.type = schema.getSubscriptionType(); - break; - case "InlineFragment": - case "FragmentDefinition": - if (state.type) { - info.type = schema.getType(state.type); - } - break; - case "Field": - case "AliasedField": - info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null; - info.type = (_a = info.fieldDef) === null || _a === void 0 ? void 0 : _a.type; - break; - case "SelectionSet": - info.parentType = info.type ? graphql.getNamedType(info.type) : null; - break; - case "Directive": - info.directiveDef = state.name ? schema.getDirective(state.name) : null; - break; - case "Arguments": - const parentDef = state.prevState ? state.prevState.kind === "Field" ? info.fieldDef : state.prevState.kind === "Directive" ? info.directiveDef : state.prevState.kind === "AliasedField" ? state.prevState.name && getFieldDef(schema, info.parentType, state.prevState.name) : null : null; - info.argDefs = parentDef ? parentDef.args : null; - break; - case "Argument": - info.argDef = null; - if (info.argDefs) { - for (let i = 0; i < info.argDefs.length; i++) { - if (info.argDefs[i].name === state.name) { - info.argDef = info.argDefs[i]; - break; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const forEachState = __webpack_require__( + /*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js" + ); + function getTypeInfo(schema, tokenState) { + const info = { + schema, + type: null, + parentType: null, + inputType: null, + directiveDef: null, + fieldDef: null, + argDef: null, + argDefs: null, + objectFieldDefs: null, + }; + forEachState.forEachState(tokenState, (state) => { + var _a, _b; + switch (state.kind) { + case "Query": + case "ShortQuery": + info.type = schema.getQueryType(); + break; + case "Mutation": + info.type = schema.getMutationType(); + break; + case "Subscription": + info.type = schema.getSubscriptionType(); + break; + case "InlineFragment": + case "FragmentDefinition": + if (state.type) { + info.type = schema.getType(state.type); + } + break; + case "Field": + case "AliasedField": + info.fieldDef = + info.type && state.name + ? getFieldDef(schema, info.parentType, state.name) + : null; + info.type = + (_a = info.fieldDef) === null || _a === void 0 + ? void 0 + : _a.type; + break; + case "SelectionSet": + info.parentType = info.type + ? graphql.getNamedType(info.type) + : null; + break; + case "Directive": + info.directiveDef = state.name + ? schema.getDirective(state.name) + : null; + break; + case "Arguments": + const parentDef = state.prevState + ? state.prevState.kind === "Field" + ? info.fieldDef + : state.prevState.kind === "Directive" + ? info.directiveDef + : state.prevState.kind === "AliasedField" + ? state.prevState.name && + getFieldDef(schema, info.parentType, state.prevState.name) + : null + : null; + info.argDefs = parentDef ? parentDef.args : null; + break; + case "Argument": + info.argDef = null; + if (info.argDefs) { + for (let i = 0; i < info.argDefs.length; i++) { + if (info.argDefs[i].name === state.name) { + info.argDef = info.argDefs[i]; + break; + } + } + } + info.inputType = + (_b = info.argDef) === null || _b === void 0 + ? void 0 + : _b.type; + break; + case "EnumValue": + const enumType = info.inputType + ? graphql.getNamedType(info.inputType) + : null; + info.enumValue = + enumType instanceof graphql.GraphQLEnumType + ? find( + enumType.getValues(), + (val) => val.value === state.name + ) + : null; + break; + case "ListValue": + const nullableType = info.inputType + ? graphql.getNullableType(info.inputType) + : null; + info.inputType = + nullableType instanceof graphql.GraphQLList + ? nullableType.ofType + : null; + break; + case "ObjectValue": + const objectType = info.inputType + ? graphql.getNamedType(info.inputType) + : null; + info.objectFieldDefs = + objectType instanceof graphql.GraphQLInputObjectType + ? objectType.getFields() + : null; + break; + case "ObjectField": + const objectField = + state.name && info.objectFieldDefs + ? info.objectFieldDefs[state.name] + : null; + info.inputType = + objectField === null || objectField === void 0 + ? void 0 + : objectField.type; + info.fieldDef = objectField; + break; + case "NamedType": + info.type = state.name ? schema.getType(state.name) : null; + break; + } + }); + return info; + } + function getFieldDef(schema, type, fieldName) { + if ( + fieldName === graphql.SchemaMetaFieldDef.name && + schema.getQueryType() === type + ) { + return graphql.SchemaMetaFieldDef; + } + if ( + fieldName === graphql.TypeMetaFieldDef.name && + schema.getQueryType() === type + ) { + return graphql.TypeMetaFieldDef; + } + if ( + fieldName === graphql.TypeNameMetaFieldDef.name && + graphql.isCompositeType(type) + ) { + return graphql.TypeNameMetaFieldDef; + } + if (type && type.getFields) { + return type.getFields()[fieldName]; + } + } + function find(array, predicate) { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { + return array[i]; } } } - info.inputType = (_b = info.argDef) === null || _b === void 0 ? void 0 : _b.type; - break; - case "EnumValue": - const enumType = info.inputType ? graphql.getNamedType(info.inputType) : null; - info.enumValue = enumType instanceof graphql.GraphQLEnumType ? find(enumType.getValues(), val => val.value === state.name) : null; - break; - case "ListValue": - const nullableType = info.inputType ? graphql.getNullableType(info.inputType) : null; - info.inputType = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; - break; - case "ObjectValue": - const objectType = info.inputType ? graphql.getNamedType(info.inputType) : null; - info.objectFieldDefs = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; - break; - case "ObjectField": - const objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null; - info.inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; - info.fieldDef = objectField; - break; - case "NamedType": - info.type = state.name ? schema.getType(state.name) : null; - break; - } - }); - return info; -} -function getFieldDef(schema, type, fieldName) { - if (fieldName === graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { - return graphql.SchemaMetaFieldDef; - } - if (fieldName === graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { - return graphql.TypeMetaFieldDef; - } - if (fieldName === graphql.TypeNameMetaFieldDef.name && graphql.isCompositeType(type)) { - return graphql.TypeNameMetaFieldDef; - } - if (type && type.getFields) { - return type.getFields()[fieldName]; - } -} -function find(array, predicate) { - for (let i = 0; i < array.length; i++) { - if (predicate(array[i])) { - return array[i]; - } - } -} -function getFieldReference(typeInfo) { - return { - kind: "Field", - schema: typeInfo.schema, - field: typeInfo.fieldDef, - type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType - }; -} -function getDirectiveReference(typeInfo) { - return { - kind: "Directive", - schema: typeInfo.schema, - directive: typeInfo.directiveDef - }; -} -function getArgumentReference(typeInfo) { - return typeInfo.directiveDef ? { - kind: "Argument", - schema: typeInfo.schema, - argument: typeInfo.argDef, - directive: typeInfo.directiveDef - } : { - kind: "Argument", - schema: typeInfo.schema, - argument: typeInfo.argDef, - field: typeInfo.fieldDef, - type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType - }; -} -function getEnumValueReference(typeInfo) { - return { - kind: "EnumValue", - value: typeInfo.enumValue || void 0, - type: typeInfo.inputType ? graphql.getNamedType(typeInfo.inputType) : void 0 - }; -} -function getTypeReference(typeInfo, type) { - return { - kind: "Type", - schema: typeInfo.schema, - type: type || typeInfo.type - }; -} -function isMetaField(fieldDef) { - return fieldDef.name.slice(0, 2) === "__"; -} -exports.getArgumentReference = getArgumentReference; -exports.getDirectiveReference = getDirectiveReference; -exports.getEnumValueReference = getEnumValueReference; -exports.getFieldReference = getFieldReference; -exports.getTypeInfo = getTypeInfo; -exports.getTypeReference = getTypeReference; - -/***/ }), - -/***/ "../../graphiql-react/dist/brace-fold.cjs.js": -/*!***************************************************!*\ + function getFieldReference(typeInfo) { + return { + kind: "Field", + schema: typeInfo.schema, + field: typeInfo.fieldDef, + type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType, + }; + } + function getDirectiveReference(typeInfo) { + return { + kind: "Directive", + schema: typeInfo.schema, + directive: typeInfo.directiveDef, + }; + } + function getArgumentReference(typeInfo) { + return typeInfo.directiveDef + ? { + kind: "Argument", + schema: typeInfo.schema, + argument: typeInfo.argDef, + directive: typeInfo.directiveDef, + } + : { + kind: "Argument", + schema: typeInfo.schema, + argument: typeInfo.argDef, + field: typeInfo.fieldDef, + type: isMetaField(typeInfo.fieldDef) + ? null + : typeInfo.parentType, + }; + } + function getEnumValueReference(typeInfo) { + return { + kind: "EnumValue", + value: typeInfo.enumValue || void 0, + type: typeInfo.inputType + ? graphql.getNamedType(typeInfo.inputType) + : void 0, + }; + } + function getTypeReference(typeInfo, type) { + return { + kind: "Type", + schema: typeInfo.schema, + type: type || typeInfo.type, + }; + } + function isMetaField(fieldDef) { + return fieldDef.name.slice(0, 2) === "__"; + } + exports.getArgumentReference = getArgumentReference; + exports.getDirectiveReference = getDirectiveReference; + exports.getEnumValueReference = getEnumValueReference; + exports.getFieldReference = getFieldReference; + exports.getTypeInfo = getTypeInfo; + exports.getTypeReference = getTypeReference; + + /***/ + }, + + /***/ "../../graphiql-react/dist/brace-fold.cjs.js": + /*!***************************************************!*\ !*** ../../graphiql-react/dist/brace-fold.cjs.js ***! \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var braceFold$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function bracketFolding(pairs) { - return function (cm, start) { - var line = start.line, - lineText = cm.getLine(line); - function findOpening(pair) { - var tokenType; - for (var at = start.ch, pass = 0;;) { - var found2 = at <= 0 ? -1 : lineText.lastIndexOf(pair[0], at - 1); - if (found2 == -1) { - if (pass == 1) break; - pass = 1; - at = lineText.length; - continue; + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } + } + } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); + } + var braceFold$2 = { + exports: {}, + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function bracketFolding(pairs) { + return function (cm, start) { + var line = start.line, + lineText = cm.getLine(line); + function findOpening(pair) { + var tokenType; + for (var at = start.ch, pass = 0; ; ) { + var found2 = + at <= 0 ? -1 : lineText.lastIndexOf(pair[0], at - 1); + if (found2 == -1) { + if (pass == 1) break; + pass = 1; + at = lineText.length; + continue; + } + if (pass == 1 && found2 < start.ch) break; + tokenType = cm.getTokenTypeAt( + CodeMirror.Pos(line, found2 + 1) + ); + if (!/^(comment|string)/.test(tokenType)) + return { + ch: found2 + 1, + tokenType, + pair, + }; + at = found2 - 1; + } + } + function findRange(found2) { + var count = 1, + lastLine = cm.lastLine(), + end, + startCh = found2.ch, + endCh; + outer: for (var i2 = line; i2 <= lastLine; ++i2) { + var text = cm.getLine(i2), + pos = i2 == line ? startCh : 0; + for (;;) { + var nextOpen = text.indexOf(found2.pair[0], pos), + nextClose = text.indexOf(found2.pair[1], pos); + if (nextOpen < 0) nextOpen = text.length; + if (nextClose < 0) nextClose = text.length; + pos = Math.min(nextOpen, nextClose); + if (pos == text.length) break; + if ( + cm.getTokenTypeAt(CodeMirror.Pos(i2, pos + 1)) == + found2.tokenType + ) { + if (pos == nextOpen) ++count; + else if (!--count) { + end = i2; + endCh = pos; + break outer; + } + } + ++pos; + } + } + if (end == null || line == end) return null; + return { + from: CodeMirror.Pos(line, startCh), + to: CodeMirror.Pos(end, endCh), + }; + } + var found = []; + for (var i = 0; i < pairs.length; i++) { + var open = findOpening(pairs[i]); + if (open) found.push(open); + } + found.sort(function (a, b) { + return a.ch - b.ch; + }); + for (var i = 0; i < found.length; i++) { + var range = findRange(found[i]); + if (range) return range; + } + return null; + }; + } + CodeMirror.registerHelper( + "fold", + "brace", + bracketFolding([ + ["{", "}"], + ["[", "]"], + ]) + ); + CodeMirror.registerHelper( + "fold", + "brace-paren", + bracketFolding([ + ["{", "}"], + ["[", "]"], + ["(", ")"], + ]) + ); + CodeMirror.registerHelper("fold", "import", function (cm, start) { + function hasImport(line) { + if (line < cm.firstLine() || line > cm.lastLine()) return null; + var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); + if (!/\S/.test(start2.string)) + start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); + if (start2.type != "keyword" || start2.string != "import") + return null; + for ( + var i = line, e = Math.min(cm.lastLine(), line + 10); + i <= e; + ++i + ) { + var text = cm.getLine(i), + semi = text.indexOf(";"); + if (semi != -1) + return { + startCh: start2.end, + end: CodeMirror.Pos(i, semi), + }; + } + } + var startLine = start.line, + has = hasImport(startLine), + prev; + if ( + !has || + hasImport(startLine - 1) || + ((prev = hasImport(startLine - 2)) && + prev.end.line == startLine - 1) + ) + return null; + for (var end = has.end; ; ) { + var next = hasImport(end.line + 1); + if (next == null) break; + end = next.end; + } + return { + from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), + to: end, + }; + }); + CodeMirror.registerHelper("fold", "include", function (cm, start) { + function hasInclude(line) { + if (line < cm.firstLine() || line > cm.lastLine()) return null; + var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); + if (!/\S/.test(start2.string)) + start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); + if ( + start2.type == "meta" && + start2.string.slice(0, 8) == "#include" + ) + return start2.start + 8; + } + var startLine = start.line, + has = hasInclude(startLine); + if (has == null || hasInclude(startLine - 1) != null) return null; + for (var end = startLine; ; ) { + var next = hasInclude(end + 1); + if (next == null) break; + ++end; + } + return { + from: CodeMirror.Pos(startLine, has + 1), + to: cm.clipPos(CodeMirror.Pos(end)), + }; + }); + }); + })(); + var braceFoldExports = braceFold$2.exports; + const braceFold = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(braceFoldExports); + const braceFold$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: braceFold, + }, + [braceFoldExports] + ); + exports.braceFold = braceFold$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/closebrackets.cjs.js": + /*!******************************************************!*\ + !*** ../../graphiql-react/dist/closebrackets.cjs.js ***! + \******************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } + } + } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); + } + var closebrackets$2 = { + exports: {}, + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var defaults = { + pairs: `()[]{}''""`, + closeBefore: `)]}'":;>`, + triples: "", + explode: "[]{}", + }; + var Pos = CodeMirror.Pos; + CodeMirror.defineOption( + "autoCloseBrackets", + false, + function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.removeKeyMap(keyMap); + cm.state.closeBrackets = null; + } + if (val) { + ensureBound(getOption(val, "pairs")); + cm.state.closeBrackets = val; + cm.addKeyMap(keyMap); + } + } + ); + function getOption(conf, name) { + if (name == "pairs" && typeof conf == "string") return conf; + if (typeof conf == "object" && conf[name] != null) + return conf[name]; + return defaults[name]; + } + var keyMap = { + Backspace: handleBackspace, + Enter: handleEnter, + }; + function ensureBound(chars) { + for (var i = 0; i < chars.length; i++) { + var ch = chars.charAt(i), + key = "'" + ch + "'"; + if (!keyMap[key]) keyMap[key] = handler(ch); + } + } + ensureBound(defaults.pairs + "`"); + function handler(ch) { + return function (cm) { + return handleChar(cm, ch); + }; + } + function getConfig(cm) { + var deflt = cm.state.closeBrackets; + if (!deflt || deflt.override) return deflt; + var mode = cm.getModeAt(cm.getCursor()); + return mode.closeBrackets || deflt; + } + function handleBackspace(cm) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + var pairs = getOption(conf, "pairs"); + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || pairs.indexOf(around) % 2 != 0) + return CodeMirror.Pass; + } + for (var i = ranges.length - 1; i >= 0; i--) { + var cur = ranges[i].head; + cm.replaceRange( + "", + Pos(cur.line, cur.ch - 1), + Pos(cur.line, cur.ch + 1), + "+delete" + ); + } + } + function handleEnter(cm) { + var conf = getConfig(cm); + var explode = conf && getOption(conf, "explode"); + if (!explode || cm.getOption("disableInput")) + return CodeMirror.Pass; + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || explode.indexOf(around) % 2 != 0) + return CodeMirror.Pass; + } + cm.operation(function () { + var linesep = cm.lineSeparator() || "\n"; + cm.replaceSelection(linesep + linesep, null); + moveSel(cm, -1); + ranges = cm.listSelections(); + for (var i2 = 0; i2 < ranges.length; i2++) { + var line = ranges[i2].head.line; + cm.indentLine(line, null, true); + cm.indentLine(line + 1, null, true); + } + }); + } + function moveSel(cm, dir) { + var newRanges = [], + ranges = cm.listSelections(), + primary = 0; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head == cm.getCursor()) primary = i; + var pos = + range.head.ch || dir > 0 + ? { + line: range.head.line, + ch: range.head.ch + dir, + } + : { + line: range.head.line - 1, + }; + newRanges.push({ + anchor: pos, + head: pos, + }); + } + cm.setSelections(newRanges, primary); + } + function contractSelection(sel) { + var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; + return { + anchor: new Pos( + sel.anchor.line, + sel.anchor.ch + (inverted ? -1 : 1) + ), + head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1)), + }; + } + function handleChar(cm, ch) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + var pairs = getOption(conf, "pairs"); + var pos = pairs.indexOf(ch); + if (pos == -1) return CodeMirror.Pass; + var closeBefore = getOption(conf, "closeBefore"); + var triples = getOption(conf, "triples"); + var identical = pairs.charAt(pos + 1) == ch; + var ranges = cm.listSelections(); + var opening = pos % 2 == 0; + var type; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + cur = range.head, + curType; + var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); + if (opening && !range.empty()) { + curType = "surround"; + } else if ((identical || !opening) && next == ch) { + if (identical && stringStartsAfter(cm, cur)) curType = "both"; + else if ( + triples.indexOf(ch) >= 0 && + cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch + ) + curType = "skipThree"; + else curType = "skip"; + } else if ( + identical && + cur.ch > 1 && + triples.indexOf(ch) >= 0 && + cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch + ) { + if ( + cur.ch > 2 && + /\bstring/.test( + cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)) + ) + ) + return CodeMirror.Pass; + curType = "addFour"; + } else if (identical) { + var prev = + cur.ch == 0 + ? " " + : cm.getRange(Pos(cur.line, cur.ch - 1), cur); + if ( + !CodeMirror.isWordChar(next) && + prev != ch && + !CodeMirror.isWordChar(prev) + ) + curType = "both"; + else return CodeMirror.Pass; + } else if ( + opening && + (next.length === 0 || + /\s/.test(next) || + closeBefore.indexOf(next) > -1) + ) { + curType = "both"; + } else { + return CodeMirror.Pass; + } + if (!type) type = curType; + else if (type != curType) return CodeMirror.Pass; + } + var left = pos % 2 ? pairs.charAt(pos - 1) : ch; + var right = pos % 2 ? ch : pairs.charAt(pos + 1); + cm.operation(function () { + if (type == "skip") { + moveSel(cm, 1); + } else if (type == "skipThree") { + moveSel(cm, 3); + } else if (type == "surround") { + var sels = cm.getSelections(); + for (var i2 = 0; i2 < sels.length; i2++) + sels[i2] = left + sels[i2] + right; + cm.replaceSelections(sels, "around"); + sels = cm.listSelections().slice(); + for (var i2 = 0; i2 < sels.length; i2++) + sels[i2] = contractSelection(sels[i2]); + cm.setSelections(sels); + } else if (type == "both") { + cm.replaceSelection(left + right, null); + cm.triggerElectric(left + right); + moveSel(cm, -1); + } else if (type == "addFour") { + cm.replaceSelection(left + left + left + left, "before"); + moveSel(cm, 1); + } + }); + } + function charsAround(cm, pos) { + var str = cm.getRange( + Pos(pos.line, pos.ch - 1), + Pos(pos.line, pos.ch + 1) + ); + return str.length == 2 ? str : null; + } + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)); + return ( + /\bstring/.test(token.type) && + token.start == pos.ch && + (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))) + ); + } + }); + })(); + var closebracketsExports = closebrackets$2.exports; + const closebrackets = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs( + closebracketsExports + ); + const closebrackets$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: closebrackets, + }, + [closebracketsExports] + ); + exports.closebrackets = closebrackets$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/codemirror.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/codemirror.cjs.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror$1 = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } } - if (pass == 1 && found2 < start.ch) break; - tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found2 + 1)); - if (!/^(comment|string)/.test(tokenType)) return { - ch: found2 + 1, - tokenType, - pair - }; - at = found2 - 1; - } - } - function findRange(found2) { - var count = 1, - lastLine = cm.lastLine(), - end, - startCh = found2.ch, - endCh; - outer: for (var i2 = line; i2 <= lastLine; ++i2) { - var text = cm.getLine(i2), - pos = i2 == line ? startCh : 0; - for (;;) { - var nextOpen = text.indexOf(found2.pair[0], pos), - nextClose = text.indexOf(found2.pair[1], pos); - if (nextOpen < 0) nextOpen = text.length; - if (nextClose < 0) nextClose = text.length; - pos = Math.min(nextOpen, nextClose); - if (pos == text.length) break; - if (cm.getTokenTypeAt(CodeMirror.Pos(i2, pos + 1)) == found2.tokenType) { - if (pos == nextOpen) ++count;else if (! --count) { - end = i2; - endCh = pos; - break outer; - } - } - ++pos; - } - } - if (end == null || line == end) return null; - return { - from: CodeMirror.Pos(line, startCh), - to: CodeMirror.Pos(end, endCh) - }; - } - var found = []; - for (var i = 0; i < pairs.length; i++) { - var open = findOpening(pairs[i]); - if (open) found.push(open); - } - found.sort(function (a, b) { - return a.ch - b.ch; - }); - for (var i = 0; i < found.length; i++) { - var range = findRange(found[i]); - if (range) return range; - } - return null; - }; - } - CodeMirror.registerHelper("fold", "brace", bracketFolding([["{", "}"], ["[", "]"]])); - CodeMirror.registerHelper("fold", "brace-paren", bracketFolding([["{", "}"], ["[", "]"], ["(", ")"]])); - CodeMirror.registerHelper("fold", "import", function (cm, start) { - function hasImport(line) { - if (line < cm.firstLine() || line > cm.lastLine()) return null; - var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); - if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); - if (start2.type != "keyword" || start2.string != "import") return null; - for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) { - var text = cm.getLine(i), - semi = text.indexOf(";"); - if (semi != -1) return { - startCh: start2.end, - end: CodeMirror.Pos(i, semi) - }; - } - } - var startLine = start.line, - has = hasImport(startLine), - prev; - if (!has || hasImport(startLine - 1) || (prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1) return null; - for (var end = has.end;;) { - var next = hasImport(end.line + 1); - if (next == null) break; - end = next.end; - } - return { - from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), - to: end - }; - }); - CodeMirror.registerHelper("fold", "include", function (cm, start) { - function hasInclude(line) { - if (line < cm.firstLine() || line > cm.lastLine()) return null; - var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); - if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); - if (start2.type == "meta" && start2.string.slice(0, 8) == "#include") return start2.start + 8; - } - var startLine = start.line, - has = hasInclude(startLine); - if (has == null || hasInclude(startLine - 1) != null) return null; - for (var end = startLine;;) { - var next = hasInclude(end + 1); - if (next == null) break; - ++end; - } - return { - from: CodeMirror.Pos(startLine, has + 1), - to: cm.clipPos(CodeMirror.Pos(end)) - }; - }); - }); -})(); -var braceFoldExports = braceFold$2.exports; -const braceFold = /* @__PURE__ */codemirror.getDefaultExportFromCjs(braceFoldExports); -const braceFold$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: braceFold -}, [braceFoldExports]); -exports.braceFold = braceFold$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/closebrackets.cjs.js": -/*!******************************************************!*\ - !*** ../../graphiql-react/dist/closebrackets.cjs.js ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var closebrackets$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var defaults = { - pairs: `()[]{}''""`, - closeBefore: `)]}'":;>`, - triples: "", - explode: "[]{}" - }; - var Pos = CodeMirror.Pos; - CodeMirror.defineOption("autoCloseBrackets", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.removeKeyMap(keyMap); - cm.state.closeBrackets = null; - } - if (val) { - ensureBound(getOption(val, "pairs")); - cm.state.closeBrackets = val; - cm.addKeyMap(keyMap); - } - }); - function getOption(conf, name) { - if (name == "pairs" && typeof conf == "string") return conf; - if (typeof conf == "object" && conf[name] != null) return conf[name]; - return defaults[name]; - } - var keyMap = { - Backspace: handleBackspace, - Enter: handleEnter - }; - function ensureBound(chars) { - for (var i = 0; i < chars.length; i++) { - var ch = chars.charAt(i), - key = "'" + ch + "'"; - if (!keyMap[key]) keyMap[key] = handler(ch); - } - } - ensureBound(defaults.pairs + "`"); - function handler(ch) { - return function (cm) { - return handleChar(cm, ch); - }; - } - function getConfig(cm) { - var deflt = cm.state.closeBrackets; - if (!deflt || deflt.override) return deflt; - var mode = cm.getModeAt(cm.getCursor()); - return mode.closeBrackets || deflt; - } - function handleBackspace(cm) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - var pairs = getOption(conf, "pairs"); - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - for (var i = ranges.length - 1; i >= 0; i--) { - var cur = ranges[i].head; - cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); - } - } - function handleEnter(cm) { - var conf = getConfig(cm); - var explode = conf && getOption(conf, "explode"); - if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - cm.operation(function () { - var linesep = cm.lineSeparator() || "\n"; - cm.replaceSelection(linesep + linesep, null); - moveSel(cm, -1); - ranges = cm.listSelections(); - for (var i2 = 0; i2 < ranges.length; i2++) { - var line = ranges[i2].head.line; - cm.indentLine(line, null, true); - cm.indentLine(line + 1, null, true); - } - }); - } - function moveSel(cm, dir) { - var newRanges = [], - ranges = cm.listSelections(), - primary = 0; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.head == cm.getCursor()) primary = i; - var pos = range.head.ch || dir > 0 ? { - line: range.head.line, - ch: range.head.ch + dir - } : { - line: range.head.line - 1 + var codemirrorExports = codemirror$1.requireCodemirror(); + const CodeMirror = + /* @__PURE__ */ codemirror$1.getDefaultExportFromCjs( + codemirrorExports + ); + const codemirror = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: CodeMirror, + }, + [codemirrorExports] + ); + exports.CodeMirror = CodeMirror; + exports.codemirror = codemirror; + + /***/ + }, + + /***/ "../../graphiql-react/dist/codemirror.cjs2.js": + /*!****************************************************!*\ + !*** ../../graphiql-react/dist/codemirror.cjs2.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + var commonjsGlobal = + typeof globalThis !== "undefined" + ? globalThis + : typeof window !== "undefined" + ? window + : typeof __webpack_require__.g !== "undefined" + ? __webpack_require__.g + : typeof self !== "undefined" + ? self + : {}; + function getDefaultExportFromCjs(x) { + return x && + x.__esModule && + Object.prototype.hasOwnProperty.call(x, "default") + ? x["default"] + : x; + } + var codemirror = { + exports: {}, }; - newRanges.push({ - anchor: pos, - head: pos - }); - } - cm.setSelections(newRanges, primary); - } - function contractSelection(sel) { - var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; - return { - anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), - head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1)) - }; - } - function handleChar(cm, ch) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - var pairs = getOption(conf, "pairs"); - var pos = pairs.indexOf(ch); - if (pos == -1) return CodeMirror.Pass; - var closeBefore = getOption(conf, "closeBefore"); - var triples = getOption(conf, "triples"); - var identical = pairs.charAt(pos + 1) == ch; - var ranges = cm.listSelections(); - var opening = pos % 2 == 0; - var type; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - cur = range.head, - curType; - var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); - if (opening && !range.empty()) { - curType = "surround"; - } else if ((identical || !opening) && next == ch) { - if (identical && stringStartsAfter(cm, cur)) curType = "both";else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree";else curType = "skip"; - } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { - if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; - curType = "addFour"; - } else if (identical) { - var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur); - if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";else return CodeMirror.Pass; - } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { - curType = "both"; - } else { - return CodeMirror.Pass; - } - if (!type) type = curType;else if (type != curType) return CodeMirror.Pass; - } - var left = pos % 2 ? pairs.charAt(pos - 1) : ch; - var right = pos % 2 ? ch : pairs.charAt(pos + 1); - cm.operation(function () { - if (type == "skip") { - moveSel(cm, 1); - } else if (type == "skipThree") { - moveSel(cm, 3); - } else if (type == "surround") { - var sels = cm.getSelections(); - for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = left + sels[i2] + right; - cm.replaceSelections(sels, "around"); - sels = cm.listSelections().slice(); - for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = contractSelection(sels[i2]); - cm.setSelections(sels); - } else if (type == "both") { - cm.replaceSelection(left + right, null); - cm.triggerElectric(left + right); - moveSel(cm, -1); - } else if (type == "addFour") { - cm.replaceSelection(left + left + left + left, "before"); - moveSel(cm, 1); - } - }); - } - function charsAround(cm, pos) { - var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); - return str.length == 2 ? str : null; - } - function stringStartsAfter(cm, pos) { - var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)); - return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))); - } - }); -})(); -var closebracketsExports = closebrackets$2.exports; -const closebrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(closebracketsExports); -const closebrackets$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: closebrackets -}, [closebracketsExports]); -exports.closebrackets = closebrackets$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/codemirror.cjs.js": -/*!***************************************************!*\ - !*** ../../graphiql-react/dist/codemirror.cjs.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror$1 = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] + var hasRequiredCodemirror; + function requireCodemirror() { + if (hasRequiredCodemirror) return codemirror.exports; + hasRequiredCodemirror = 1; + (function (module2, exports2) { + (function (global2, factory) { + module2.exports = factory(); + })(commonjsGlobal, function () { + var userAgent = navigator.userAgent; + var platform = navigator.platform; + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec( + userAgent + ); + var edge = /Edge\/(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up || edge; + var ie_version = + ie && + (ie_upto10 + ? document.documentMode || 6 + : +(edge || ie_11up)[1]); + var webkit = !edge && /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = !edge && /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test( + userAgent + ); + var phantom = /PhantomJS/.test(userAgent); + var ios = + safari && + (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); + var android = /Android/.test(userAgent); + var mobile = + ios || + android || + /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test( + userAgent + ); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + var presto_version = + presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) { + presto_version = Number(presto_version[1]); + } + if (presto_version && presto_version >= 15) { + presto = false; + webkit = true; + } + var flipCtrlCmd = + mac && + (qtwebkit || + (presto && + (presto_version == null || presto_version < 12.11))); + var captureRightClick = gecko || (ie && ie_version >= 9); + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); + } + var rmClass = function (node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = + current.slice(0, match.index) + + (after ? match[1] + after : ""); + } + }; + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) { + e.removeChild(e.firstChild); + } + return e; + } + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) { + e.className = className; + } + if (style) { + e.style.cssText = style; + } + if (typeof content == "string") { + e.appendChild(document.createTextNode(content)); + } else if (content) { + for (var i2 = 0; i2 < content.length; ++i2) { + e.appendChild(content[i2]); + } + } + return e; + } + function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style); + e.setAttribute("role", "presentation"); + return e; + } + var range; + if (document.createRange) { + range = function (node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + } else { + range = function (node, start, end) { + var r = document.body.createTextRange(); + try { + r.moveToElementText(node.parentNode); + } catch (e) { + return r; + } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + } + function contains(parent, child) { + if (child.nodeType == 3) { + child = child.parentNode; + } + if (parent.contains) { + return parent.contains(child); + } + do { + if (child.nodeType == 11) { + child = child.host; + } + if (child == parent) { + return true; + } + } while ((child = child.parentNode)); + } + function activeElt() { + var activeElement; + try { + activeElement = document.activeElement; + } catch (e) { + activeElement = document.body || null; + } + while ( + activeElement && + activeElement.shadowRoot && + activeElement.shadowRoot.activeElement + ) { + activeElement = activeElement.shadowRoot.activeElement; + } + return activeElement; + } + function addClass(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) { + node.className += (current ? " " : "") + cls; + } + } + function joinClasses(a, b) { + var as = a.split(" "); + for (var i2 = 0; i2 < as.length; i2++) { + if (as[i2] && !classTest(as[i2]).test(b)) { + b += " " + as[i2]; + } + } + return b; + } + var selectInput = function (node) { + node.select(); + }; + if (ios) { + selectInput = function (node) { + node.selectionStart = 0; + node.selectionEnd = node.value.length; + }; + } else if (ie) { + selectInput = function (node) { + try { + node.select(); + } catch (_e) {} + }; + } + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return f.apply(null, args); + }; + } + function copyObj(obj, target, overwrite) { + if (!target) { + target = {}; + } + for (var prop2 in obj) { + if ( + obj.hasOwnProperty(prop2) && + (overwrite !== false || !target.hasOwnProperty(prop2)) + ) { + target[prop2] = obj[prop2]; + } + } + return target; + } + function countColumn( + string, + end, + tabSize, + startIndex, + startValue + ) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) { + end = string.length; + } + } + for (var i2 = startIndex || 0, n = startValue || 0; ; ) { + var nextTab = string.indexOf(" ", i2); + if (nextTab < 0 || nextTab >= end) { + return n + (end - i2); + } + n += nextTab - i2; + n += tabSize - (n % tabSize); + i2 = nextTab + 1; + } + } + var Delayed = function () { + this.id = null; + this.f = null; + this.time = 0; + this.handler = bind(this.onTimeout, this); + }; + Delayed.prototype.onTimeout = function (self2) { + self2.id = 0; + if (self2.time <= +(/* @__PURE__ */ new Date())) { + self2.f(); + } else { + setTimeout( + self2.handler, + self2.time - +(/* @__PURE__ */ new Date()) + ); + } + }; + Delayed.prototype.set = function (ms, f) { + this.f = f; + var time = +(/* @__PURE__ */ new Date()) + ms; + if (!this.id || time < this.time) { + clearTimeout(this.id); + this.id = setTimeout(this.handler, ms); + this.time = time; + } + }; + function indexOf(array, elt2) { + for (var i2 = 0; i2 < array.length; ++i2) { + if (array[i2] == elt2) { + return i2; + } + } + return -1; + } + var scrollerGap = 50; + var Pass = { + toString: function () { + return "CodeMirror.Pass"; + }, + }; + var sel_dontScroll = { + scroll: false, + }, + sel_mouse = { + origin: "*mouse", + }, + sel_move = { + origin: "+move", + }; + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0; ; ) { + var nextTab = string.indexOf(" ", pos); + if (nextTab == -1) { + nextTab = string.length; + } + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) { + return pos + Math.min(skipped, goal - col); + } + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) { + return pos; + } + } + } + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) { + spaceStrs.push(lst(spaceStrs) + " "); + } + return spaceStrs[n]; + } + function lst(arr) { + return arr[arr.length - 1]; + } + function map(array, f) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = f(array[i2], i2); + } + return out; + } + function insertSorted(array, value, score) { + var pos = 0, + priority = score(value); + while (pos < array.length && score(array[pos]) <= priority) { + pos++; + } + array.splice(pos, 0, value); + } + function nothing() {} + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) { + copyObj(props, inst); + } + return inst; + } + var nonASCIISingleCaseWordChar = + /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordCharBasic(ch) { + return ( + /\w/.test(ch) || + (ch > "€" && + (ch.toUpperCase() != ch.toLowerCase() || + nonASCIISingleCaseWordChar.test(ch))) + ); + } + function isWordChar(ch, helper) { + if (!helper) { + return isWordCharBasic(ch); + } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { + return true; + } + return helper.test(ch); + } + function isEmpty(obj) { + for (var n in obj) { + if (obj.hasOwnProperty(n) && obj[n]) { + return false; + } + } + return true; + } + var extendingChars = + /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { + return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); + } + function skipExtendingChars(str, pos, dir) { + while ( + (dir < 0 ? pos > 0 : pos < str.length) && + isExtendingChar(str.charAt(pos)) + ) { + pos += dir; + } + return pos; + } + function findFirst(pred, from, to) { + var dir = from > to ? -1 : 1; + for (;;) { + if (from == to) { + return from; + } + var midF = (from + to) / 2, + mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); + if (mid == from) { + return pred(mid) ? from : to; + } + if (pred(mid)) { + to = mid; + } else { + from = mid + dir; + } + } + } + function iterateBidiSections(order, from, to, f) { + if (!order) { + return f(from, to, "ltr", 0); + } + var found = false; + for (var i2 = 0; i2 < order.length; ++i2) { + var part = order[i2]; + if ( + (part.from < to && part.to > from) || + (from == to && part.to == from) + ) { + f( + Math.max(part.from, from), + Math.min(part.to, to), + part.level == 1 ? "rtl" : "ltr", + i2 + ); + found = true; + } + } + if (!found) { + f(from, to, "ltr"); + } + } + var bidiOther = null; + function getBidiPartAt(order, ch, sticky) { + var found; + bidiOther = null; + for (var i2 = 0; i2 < order.length; ++i2) { + var cur = order[i2]; + if (cur.from < ch && cur.to > ch) { + return i2; + } + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { + found = i2; + } else { + bidiOther = i2; + } + } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { + found = i2; + } else { + bidiOther = i2; + } + } + } + return found != null ? found : bidiOther; + } + var bidiOrdering = /* @__PURE__ */ (function () { + var lowTypes = + "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + var arabicTypes = + "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; + function charType(code) { + if (code <= 247) { + return lowTypes.charAt(code); + } else if (1424 <= code && code <= 1524) { + return "R"; + } else if (1536 <= code && code <= 1785) { + return arabicTypes.charAt(code - 1536); + } else if (1774 <= code && code <= 2220) { + return "r"; + } else if (8192 <= code && code <= 8203) { + return "w"; + } else if (code == 8204) { + return "b"; + } else { + return "L"; + } + } + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, + isStrong = /[LRr]/, + countsAsLeft = /[Lb1n]/, + countsAsNum = /[1n]/; + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; + this.to = to; + } + return function (str, direction) { + var outerType = direction == "ltr" ? "L" : "R"; + if ( + str.length == 0 || + (direction == "ltr" && !bidiRE.test(str)) + ) { + return false; + } + var len = str.length, + types = []; + for (var i2 = 0; i2 < len; ++i2) { + types.push(charType(str.charCodeAt(i2))); + } + for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) { + var type = types[i$12]; + if (type == "m") { + types[i$12] = prev; + } else { + prev = type; + } + } + for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) { + var type$1 = types[i$22]; + if (type$1 == "1" && cur == "r") { + types[i$22] = "n"; + } else if (isStrong.test(type$1)) { + cur = type$1; + if (type$1 == "r") { + types[i$22] = "R"; + } + } + } + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3]; + if ( + type$2 == "+" && + prev$1 == "1" && + types[i$3 + 1] == "1" + ) { + types[i$3] = "1"; + } else if ( + type$2 == "," && + prev$1 == types[i$3 + 1] && + (prev$1 == "1" || prev$1 == "n") + ) { + types[i$3] = prev$1; + } + prev$1 = type$2; + } + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4]; + if (type$3 == ",") { + types[i$4] = "N"; + } else if (type$3 == "%") { + var end = void 0; + for ( + end = i$4 + 1; + end < len && types[end] == "%"; + ++end + ) {} + var replace = + (i$4 && types[i$4 - 1] == "!") || + (end < len && types[end] == "1") + ? "1" + : "N"; + for (var j = i$4; j < end; ++j) { + types[j] = replace; + } + i$4 = end - 1; + } + } + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5]; + if (cur$1 == "L" && type$4 == "1") { + types[i$5] = "L"; + } else if (isStrong.test(type$4)) { + cur$1 = type$4; + } + } + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = void 0; + for ( + end$1 = i$6 + 1; + end$1 < len && isNeutral.test(types[end$1]); + ++end$1 + ) {} + var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; + var after = + (end$1 < len ? types[end$1] : outerType) == "L"; + var replace$1 = + before == after ? (before ? "L" : "R") : outerType; + for (var j$1 = i$6; j$1 < end$1; ++j$1) { + types[j$1] = replace$1; + } + i$6 = end$1 - 1; + } + } + var order = [], + m; + for (var i$7 = 0; i$7 < len; ) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7; + for ( + ++i$7; + i$7 < len && countsAsLeft.test(types[i$7]); + ++i$7 + ) {} + order.push(new BidiSpan(0, start, i$7)); + } else { + var pos = i$7, + at = order.length, + isRTL = direction == "rtl" ? 1 : 0; + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7; ) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { + order.splice(at, 0, new BidiSpan(1, pos, j$2)); + at += isRTL; + } + var nstart = j$2; + for ( + ++j$2; + j$2 < i$7 && countsAsNum.test(types[j$2]); + ++j$2 + ) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)); + at += isRTL; + pos = j$2; + } else { + ++j$2; + } + } + if (pos < i$7) { + order.splice(at, 0, new BidiSpan(1, pos, i$7)); + } + } + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + } + return direction == "rtl" ? order.reverse() : order; + }; + })(); + function getOrder(line, direction) { + var order = line.order; + if (order == null) { + order = line.order = bidiOrdering(line.text, direction); + } + return order; + } + var noHandlers = []; + var on = function (emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false); + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f); + } else { + var map2 = emitter._handlers || (emitter._handlers = {}); + map2[type] = (map2[type] || noHandlers).concat(f); + } + }; + function getHandlers(emitter, type) { + return ( + (emitter._handlers && emitter._handlers[type]) || noHandlers + ); + } + function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false); + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f); + } else { + var map2 = emitter._handlers, + arr = map2 && map2[type]; + if (arr) { + var index = indexOf(arr, f); + if (index > -1) { + map2[type] = arr + .slice(0, index) + .concat(arr.slice(index + 1)); + } + } + } + } + function signal(emitter, type) { + var handlers = getHandlers(emitter, type); + if (!handlers.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2); + for (var i2 = 0; i2 < handlers.length; ++i2) { + handlers[i2].apply(null, args); + } + } + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") { + e = { + type: e, + preventDefault: function () { + this.defaultPrevented = true; + }, + }; + } + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) { + return; + } + var set = + cm.curOp.cursorActivityHandlers || + (cm.curOp.cursorActivityHandlers = []); + for (var i2 = 0; i2 < arr.length; ++i2) { + if (indexOf(set, arr[i2]) == -1) { + set.push(arr[i2]); + } + } + } + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0; + } + function eventMixin(ctor) { + ctor.prototype.on = function (type, f) { + on(this, type, f); + }; + ctor.prototype.off = function (type, f) { + off(this, type, f); + }; + } + function e_preventDefault(e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + } + function e_stopPropagation(e) { + if (e.stopPropagation) { + e.stopPropagation(); + } else { + e.cancelBubble = true; + } + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null + ? e.defaultPrevented + : e.returnValue == false; + } + function e_stop(e) { + e_preventDefault(e); + e_stopPropagation(e); + } + function e_target(e) { + return e.target || e.srcElement; + } + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) { + b = 1; + } else if (e.button & 2) { + b = 3; + } else if (e.button & 4) { + b = 2; + } + } + if (mac && e.ctrlKey && b == 1) { + b = 3; + } + return b; + } + var dragAndDrop = (function () { + if (ie && ie_version < 9) { + return false; + } + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + })(); + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "​"); + removeChildrenAndAdd( + measure, + elt("span", [test, document.createTextNode("x")]) + ); + if (measure.firstChild.offsetHeight != 0) { + zwspSupported = + test.offsetWidth <= 1 && + test.offsetHeight > 2 && + !(ie && ie_version < 8); + } + } + var node = zwspSupported + ? elt("span", "​") + : elt( + "span", + " ", + null, + "display: inline-block; width: 1px; margin-right: -1px" + ); + node.setAttribute("cm-text", ""); + return node; + } + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) { + return badBidiRects; + } + var txt = removeChildrenAndAdd( + measure, + document.createTextNode("AخA") + ); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + var r1 = range(txt, 1, 2).getBoundingClientRect(); + removeChildren(measure); + if (!r0 || r0.left == r0.right) { + return false; + } + return (badBidiRects = r1.right - r0.right < 3); + } + var splitLinesAuto = + "\n\nb".split(/\n/).length != 3 + ? function (string) { + var pos = 0, + result = [], + l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) { + nl = string.length; + } + var line = string.slice( + pos, + string.charAt(nl - 1) == "\r" ? nl - 1 : nl + ); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } + : function (string) { + return string.split(/\r\n?|\n/); + }; + var hasSelection = window.getSelection + ? function (te) { + try { + return te.selectionStart != te.selectionEnd; + } catch (e) { + return false; + } + } + : function (te) { + var range2; + try { + range2 = te.ownerDocument.selection.createRange(); + } catch (e) {} + if (!range2 || range2.parentElement() != te) { + return false; + } + return range2.compareEndPoints("StartToEnd", range2) != 0; + }; + var hasCopyEvent = (function () { + var e = elt("div"); + if ("oncopy" in e) { + return true; + } + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + })(); + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { + return badZoomedRects; + } + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return (badZoomedRects = + Math.abs(normal.left - fromRange.left) > 1); + } + var modes = {}, + mimeModes = {}; + function defineMode(name, mode) { + if (arguments.length > 2) { + mode.dependencies = Array.prototype.slice.call(arguments, 2); + } + modes[name] = mode; + } + function defineMIME(mime, spec) { + mimeModes[mime] = spec; + } + function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if ( + spec && + typeof spec.name == "string" && + mimeModes.hasOwnProperty(spec.name) + ) { + var found = mimeModes[spec.name]; + if (typeof found == "string") { + found = { + name: found, + }; + } + spec = createObj(found, spec); + spec.name = found.name; + } else if ( + typeof spec == "string" && + /^[\w\-]+\/[\w\-]+\+xml$/.test(spec) + ) { + return resolveMode("application/xml"); + } else if ( + typeof spec == "string" && + /^[\w\-]+\/[\w\-]+\+json$/.test(spec) + ) { + return resolveMode("application/json"); + } + if (typeof spec == "string") { + return { + name: spec, + }; + } else { + return ( + spec || { + name: "null", + } + ); + } + } + function getMode(options, spec) { + spec = resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) { + return getMode(options, "text/plain"); + } + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop2 in exts) { + if (!exts.hasOwnProperty(prop2)) { + continue; + } + if (modeObj.hasOwnProperty(prop2)) { + modeObj["_" + prop2] = modeObj[prop2]; + } + modeObj[prop2] = exts[prop2]; + } + } + modeObj.name = spec.name; + if (spec.helperType) { + modeObj.helperType = spec.helperType; + } + if (spec.modeProps) { + for (var prop$1 in spec.modeProps) { + modeObj[prop$1] = spec.modeProps[prop$1]; + } + } + return modeObj; + } + var modeExtensions = {}; + function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) + ? modeExtensions[mode] + : (modeExtensions[mode] = {}); + copyObj(properties, exts); + } + function copyState(mode, state) { + if (state === true) { + return state; + } + if (mode.copyState) { + return mode.copyState(state); + } + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) { + val = val.concat([]); + } + nstate[n] = val; + } + return nstate; + } + function innerMode(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) { + break; + } + state = info.state; + mode = info.mode; + } + return ( + info || { + mode, + state, + } + ); + } + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + var StringStream = function (string, tabSize, lineOracle) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.lineOracle = lineOracle; + }; + StringStream.prototype.eol = function () { + return this.pos >= this.string.length; + }; + StringStream.prototype.sol = function () { + return this.pos == this.lineStart; + }; + StringStream.prototype.peek = function () { + return this.string.charAt(this.pos) || void 0; + }; + StringStream.prototype.next = function () { + if (this.pos < this.string.length) { + return this.string.charAt(this.pos++); + } + }; + StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos); + var ok; + if (typeof match == "string") { + ok = ch == match; + } else { + ok = ch && (match.test ? match.test(ch) : match(ch)); + } + if (ok) { + ++this.pos; + return ch; + } + }; + StringStream.prototype.eatWhile = function (match) { + var start = this.pos; + while (this.eat(match)) {} + return this.pos > start; + }; + StringStream.prototype.eatSpace = function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { + ++this.pos; + } + return this.pos > start; + }; + StringStream.prototype.skipToEnd = function () { + this.pos = this.string.length; + }; + StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) { + this.pos = found; + return true; + } + }; + StringStream.prototype.backUp = function (n) { + this.pos -= n; + }; + StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn( + this.string, + this.start, + this.tabSize, + this.lastColumnPos, + this.lastColumnValue + ); + this.lastColumnPos = this.start; + } + return ( + this.lastColumnValue - + (this.lineStart + ? countColumn(this.string, this.lineStart, this.tabSize) + : 0) + ); + }; + StringStream.prototype.indentation = function () { + return ( + countColumn(this.string, null, this.tabSize) - + (this.lineStart + ? countColumn(this.string, this.lineStart, this.tabSize) + : 0) + ); + }; + StringStream.prototype.match = function ( + pattern, + consume, + caseInsensitive + ) { + if (typeof pattern == "string") { + var cased = function (str) { + return caseInsensitive ? str.toLowerCase() : str; + }; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) { + this.pos += pattern.length; + } + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) { + return null; + } + if (match && consume !== false) { + this.pos += match[0].length; + } + return match; + } + }; + StringStream.prototype.current = function () { + return this.string.slice(this.start, this.pos); + }; + StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n; + try { + return inner(); + } finally { + this.lineStart -= n; + } + }; + StringStream.prototype.lookAhead = function (n) { + var oracle = this.lineOracle; + return oracle && oracle.lookAhead(n); + }; + StringStream.prototype.baseToken = function () { + var oracle = this.lineOracle; + return oracle && oracle.baseToken(this.pos); + }; + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) { + throw new Error( + "There is no line " + (n + doc.first) + " in the document." + ); + } + var chunk = doc; + while (!chunk.lines) { + for (var i2 = 0; ; ++i2) { + var child = chunk.children[i2], + sz = child.chunkSize(); + if (n < sz) { + chunk = child; + break; + } + n -= sz; + } + } + return chunk.lines[n]; + } + function getBetween(doc, start, end) { + var out = [], + n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) { + text = text.slice(0, end.ch); + } + if (n == start.line) { + text = text.slice(start.ch); + } + out.push(text); + ++n; + }); + return out; + } + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function (line) { + out.push(line.text); + }); + return out; + } + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) { + for (var n = line; n; n = n.parent) { + n.height += diff; + } + } + } + function lineNo(line) { + if (line.parent == null) { + return null; + } + var cur = line.parent, + no = indexOf(cur.lines, line); + for ( + var chunk = cur.parent; + chunk; + cur = chunk, chunk = chunk.parent + ) { + for (var i2 = 0; ; ++i2) { + if (chunk.children[i2] == cur) { + break; + } + no += chunk.children[i2].chunkSize(); + } + } + return no + cur.first; + } + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) { + var child = chunk.children[i$12], + ch = child.height; + if (h < ch) { + chunk = child; + continue outer; + } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + var i2 = 0; + for (; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2], + lh = line.height; + if (h < lh) { + break; + } + h -= lh; + } + return n + i2; + } + function isLine(doc, l) { + return l >= doc.first && l < doc.first + doc.size; + } + function lineNumberFor(options, i2) { + return String( + options.lineNumberFormatter(i2 + options.firstLineNumber) + ); + } + function Pos(line, ch, sticky) { + if (sticky === void 0) sticky = null; + if (!(this instanceof Pos)) { + return new Pos(line, ch, sticky); + } + this.line = line; + this.ch = ch; + this.sticky = sticky; + } + function cmp(a, b) { + return a.line - b.line || a.ch - b.ch; + } + function equalCursorPos(a, b) { + return a.sticky == b.sticky && cmp(a, b) == 0; + } + function copyPos(x) { + return Pos(x.line, x.ch); + } + function maxPos(a, b) { + return cmp(a, b) < 0 ? b : a; + } + function minPos(a, b) { + return cmp(a, b) < 0 ? a : b; + } + function clipLine(doc, n) { + return Math.max( + doc.first, + Math.min(n, doc.first + doc.size - 1) + ); + } + function clipPos(doc, pos) { + if (pos.line < doc.first) { + return Pos(doc.first, 0); + } + var last = doc.first + doc.size - 1; + if (pos.line > last) { + return Pos(last, getLine(doc, last).text.length); + } + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) { + return Pos(pos.line, linelen); + } else if (ch < 0) { + return Pos(pos.line, 0); + } else { + return pos; + } + } + function clipPosArray(doc, array) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = clipPos(doc, array[i2]); + } + return out; + } + var SavedContext = function (state, lookAhead) { + this.state = state; + this.lookAhead = lookAhead; + }; + var Context = function (doc, state, line, lookAhead) { + this.state = state; + this.doc = doc; + this.line = line; + this.maxLookAhead = lookAhead || 0; + this.baseTokens = null; + this.baseTokenPos = 1; + }; + Context.prototype.lookAhead = function (n) { + var line = this.doc.getLine(this.line + n); + if (line != null && n > this.maxLookAhead) { + this.maxLookAhead = n; + } + return line; + }; + Context.prototype.baseToken = function (n) { + if (!this.baseTokens) { + return null; + } + while (this.baseTokens[this.baseTokenPos] <= n) { + this.baseTokenPos += 2; + } + var type = this.baseTokens[this.baseTokenPos + 1]; + return { + type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n, + }; + }; + Context.prototype.nextLine = function () { + this.line++; + if (this.maxLookAhead > 0) { + this.maxLookAhead--; + } + }; + Context.fromSaved = function (doc, saved, line) { + if (saved instanceof SavedContext) { + return new Context( + doc, + copyState(doc.mode, saved.state), + line, + saved.lookAhead + ); + } else { + return new Context(doc, copyState(doc.mode, saved), line); + } + }; + Context.prototype.save = function (copy) { + var state = + copy !== false + ? copyState(this.doc.mode, this.state) + : this.state; + return this.maxLookAhead > 0 + ? new SavedContext(state, this.maxLookAhead) + : state; + }; + function highlightLine(cm, line, context, forceToEnd) { + var st = [cm.state.modeGen], + lineClasses = {}; + runMode( + cm, + line.text, + cm.doc.mode, + context, + function (end, style) { + return st.push(end, style); + }, + lineClasses, + forceToEnd + ); + var state = context.state; + var loop = function (o2) { + context.baseTokens = st; + var overlay = cm.state.overlays[o2], + i2 = 1, + at = 0; + context.state = true; + runMode( + cm, + line.text, + overlay.mode, + context, + function (end, style) { + var start = i2; + while (at < end) { + var i_end = st[i2]; + if (i_end > end) { + st.splice(i2, 1, end, st[i2 + 1], i_end); + } + i2 += 2; + at = Math.min(end, i_end); + } + if (!style) { + return; + } + if (overlay.opaque) { + st.splice(start, i2 - start, end, "overlay " + style); + i2 = start + 2; + } else { + for (; start < i2; start += 2) { + var cur = st[start + 1]; + st[start + 1] = + (cur ? cur + " " : "") + "overlay " + style; + } + } + }, + lineClasses + ); + context.state = state; + context.baseTokens = null; + context.baseTokenPos = 1; + }; + for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); + return { + styles: st, + classes: + lineClasses.bgClass || lineClasses.textClass + ? lineClasses + : null, + }; + } + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)); + var resetState = + line.text.length > cm.options.maxHighlightLength && + copyState(cm.doc.mode, context.state); + var result = highlightLine(cm, line, context); + if (resetState) { + context.state = resetState; + } + line.stateAfter = context.save(!resetState); + line.styles = result.styles; + if (result.classes) { + line.styleClasses = result.classes; + } else if (line.styleClasses) { + line.styleClasses = null; + } + if (updateFrontier === cm.doc.highlightFrontier) { + cm.doc.modeFrontier = Math.max( + cm.doc.modeFrontier, + ++cm.doc.highlightFrontier + ); + } + } + return line.styles; + } + function getContextBefore(cm, n, precise) { + var doc = cm.doc, + display = cm.display; + if (!doc.mode.startState) { + return new Context(doc, true, n); + } + var start = findStartLine(cm, n, precise); + var saved = + start > doc.first && getLine(doc, start - 1).stateAfter; + var context = saved + ? Context.fromSaved(doc, saved, start) + : new Context(doc, startState(doc.mode), start); + doc.iter(start, n, function (line) { + processLine(cm, line.text, context); + var pos = context.line; + line.stateAfter = + pos == n - 1 || + pos % 5 == 0 || + (pos >= display.viewFrom && pos < display.viewTo) + ? context.save() + : null; + context.nextLine(); + }); + if (precise) { + doc.modeFrontier = context.line; + } + return context; + } + function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream( + text, + cm.options.tabSize, + context + ); + stream.start = stream.pos = startAt || 0; + if (text == "") { + callBlankLine(mode, context.state); + } + while (!stream.eol()) { + readToken(mode, stream, context.state); + stream.start = stream.pos; + } + } + function callBlankLine(mode, state) { + if (mode.blankLine) { + return mode.blankLine(state); + } + if (!mode.innerMode) { + return; + } + var inner = innerMode(mode, state); + if (inner.mode.blankLine) { + return inner.mode.blankLine(inner.state); + } + } + function readToken(mode, stream, state, inner) { + for (var i2 = 0; i2 < 10; i2++) { + if (inner) { + inner[0] = innerMode(mode, state).mode; + } + var style = mode.token(stream, state); + if (stream.pos > stream.start) { + return style; + } + } + throw new Error( + "Mode " + mode.name + " failed to advance stream." + ); + } + var Token = function (stream, type, state) { + this.start = stream.start; + this.end = stream.pos; + this.string = stream.current(); + this.type = type || null; + this.state = state; + }; + function takeToken(cm, pos, precise, asArray) { + var doc = cm.doc, + mode = doc.mode, + style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), + context = getContextBefore(cm, pos.line, precise); + var stream = new StringStream( + line.text, + cm.options.tabSize, + context + ), + tokens; + if (asArray) { + tokens = []; + } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, context.state); + if (asArray) { + tokens.push( + new Token( + stream, + style, + copyState(doc.mode, context.state) + ) + ); + } + } + return asArray + ? tokens + : new Token(stream, style, context.state); + } + function extractLineClasses(type, output) { + if (type) { + for (;;) { + var lineClass = type.match( + /(?:^|\s+)line-(background-)?(\S+)/ + ); + if (!lineClass) { + break; + } + type = + type.slice(0, lineClass.index) + + type.slice(lineClass.index + lineClass[0].length); + var prop2 = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop2] == null) { + output[prop2] = lineClass[2]; + } else if ( + !new RegExp( + "(?:^|\\s)" + lineClass[2] + "(?:$|\\s)" + ).test(output[prop2]) + ) { + output[prop2] += " " + lineClass[2]; + } + } + } + return type; + } + function runMode( + cm, + text, + mode, + context, + f, + lineClasses, + forceToEnd + ) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) { + flattenSpans = cm.options.flattenSpans; + } + var curStart = 0, + curStyle = null; + var stream = new StringStream( + text, + cm.options.tabSize, + context + ), + style; + var inner = cm.options.addModeClass && [null]; + if (text == "") { + extractLineClasses( + callBlankLine(mode, context.state), + lineClasses + ); + } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) { + processLine(cm, text, context, stream.pos); + } + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses( + readToken(mode, stream, context.state, inner), + lineClasses + ); + } + if (inner) { + var mName = inner[0].name; + if (mName) { + style = "m-" + (style ? mName + " " + style : mName); + } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5e3); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + var pos = Math.min(stream.pos, curStart + 5e3); + f(pos, curStyle); + curStart = pos; + } + } + function findStartLine(cm, n, precise) { + var minindent, + minline, + doc = cm.doc; + var lim = precise + ? -1 + : n - (cm.doc.mode.innerMode ? 1e3 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) { + return doc.first; + } + var line = getLine(doc, search - 1), + after = line.stateAfter; + if ( + after && + (!precise || + search + + (after instanceof SavedContext ? after.lookAhead : 0) <= + doc.modeFrontier) + ) { + return search; + } + var indented = countColumn( + line.text, + null, + cm.options.tabSize + ); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n); + if (doc.highlightFrontier < n - 10) { + return; + } + var start = doc.first; + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc, line).stateAfter; + if ( + saved && + (!(saved instanceof SavedContext) || + line + saved.lookAhead < n) + ) { + start = line + 1; + break; + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start); + } + var sawReadOnlySpans = false, + sawCollapsedSpans = false; + function seeReadOnlySpans() { + sawReadOnlySpans = true; + } + function seeCollapsedSpans() { + sawCollapsedSpans = true; + } + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; + this.to = to; + } + function getMarkedSpanFor(spans, marker) { + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.marker == marker) { + return span; + } + } + } + } + function removeMarkedSpan(spans, span) { + var r; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2] != span) { + (r || (r = [])).push(spans[i2]); + } + } + return r; + } + function addMarkedSpan(line, span, op) { + var inThisOp = + op && + window.WeakSet && + (op.markedSpans || + (op.markedSpans = /* @__PURE__ */ new WeakSet())); + if ( + inThisOp && + line.markedSpans && + inThisOp.has(line.markedSpans) + ) { + line.markedSpans.push(span); + } else { + line.markedSpans = line.markedSpans + ? line.markedSpans.concat([span]) + : [span]; + if (inThisOp) { + inThisOp.add(line.markedSpans); + } + } + span.marker.attachLine(line); + } + function markedSpansBefore(old, startCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], + marker = span.marker; + var startsBefore = + span.from == null || + (marker.inclusiveLeft + ? span.from <= startCh + : span.from < startCh); + if ( + startsBefore || + (span.from == startCh && + marker.type == "bookmark" && + (!isInsert || !span.marker.insertLeft)) + ) { + var endsAfter = + span.to == null || + (marker.inclusiveRight + ? span.to >= startCh + : span.to > startCh); + (nw || (nw = [])).push( + new MarkedSpan( + marker, + span.from, + endsAfter ? null : span.to + ) + ); + } + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], + marker = span.marker; + var endsAfter = + span.to == null || + (marker.inclusiveRight + ? span.to >= endCh + : span.to > endCh); + if ( + endsAfter || + (span.from == endCh && + marker.type == "bookmark" && + (!isInsert || span.marker.insertLeft)) + ) { + var startsBefore = + span.from == null || + (marker.inclusiveLeft + ? span.from <= endCh + : span.from < endCh); + (nw || (nw = [])).push( + new MarkedSpan( + marker, + startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh + ) + ); + } + } + } + return nw; + } + function stretchSpansOverChange(doc, change) { + if (change.full) { + return null; + } + var oldFirst = + isLine(doc, change.from.line) && + getLine(doc, change.from.line).markedSpans; + var oldLast = + isLine(doc, change.to.line) && + getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) { + return null; + } + var startCh = change.from.ch, + endCh = change.to.ch, + isInsert = cmp(change.from, change.to) == 0; + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + var sameLine = change.text.length == 1, + offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + for (var i2 = 0; i2 < first.length; ++i2) { + var span = first[i2]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) { + span.to = startCh; + } else if (sameLine) { + span.to = found.to == null ? null : found.to + offset; + } + } + } + } + if (last) { + for (var i$12 = 0; i$12 < last.length; ++i$12) { + var span$1 = last[i$12]; + if (span$1.to != null) { + span$1.to += offset; + } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker); + if (!found$1) { + span$1.from = offset; + if (sameLine) { + (first || (first = [])).push(span$1); + } + } + } else { + span$1.from += offset; + if (sameLine) { + (first || (first = [])).push(span$1); + } + } + } + } + if (first) { + first = clearEmptySpans(first); + } + if (last && last != first) { + last = clearEmptySpans(last); + } + var newMarkers = [first]; + if (!sameLine) { + var gap = change.text.length - 2, + gapMarkers; + if (gap > 0 && first) { + for (var i$22 = 0; i$22 < first.length; ++i$22) { + if (first[i$22].to == null) { + (gapMarkers || (gapMarkers = [])).push( + new MarkedSpan(first[i$22].marker, null, null) + ); + } + } + } + for (var i$3 = 0; i$3 < gap; ++i$3) { + newMarkers.push(gapMarkers); + } + newMarkers.push(last); + } + return newMarkers; + } + function clearEmptySpans(spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if ( + span.from != null && + span.from == span.to && + span.marker.clearWhenEmpty !== false + ) { + spans.splice(i2--, 1); + } + } + if (!spans.length) { + return null; + } + return spans; + } + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { + for (var i3 = 0; i3 < line.markedSpans.length; ++i3) { + var mark = line.markedSpans[i3].marker; + if ( + mark.readOnly && + (!markers || indexOf(markers, mark) == -1) + ) { + (markers || (markers = [])).push(mark); + } + } + } + }); + if (!markers) { + return null; + } + var parts = [ + { + from, + to, + }, + ]; + for (var i2 = 0; i2 < markers.length; ++i2) { + var mk = markers[i2], + m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { + continue; + } + var newParts = [j, 1], + dfrom = cmp(p.from, m.from), + dto = cmp(p.to, m.to); + if (dfrom < 0 || (!mk.inclusiveLeft && !dfrom)) { + newParts.push({ + from: p.from, + to: m.from, + }); + } + if (dto > 0 || (!mk.inclusiveRight && !dto)) { + newParts.push({ + from: m.to, + to: p.to, + }); + } + parts.splice.apply(parts, newParts); + j += newParts.length - 3; + } + } + return parts; + } + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.detachLine(line); + } + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.attachLine(line); + } + line.markedSpans = spans; + } + function extraLeft(marker) { + return marker.inclusiveLeft ? -1 : 0; + } + function extraRight(marker) { + return marker.inclusiveRight ? 1 : 0; + } + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) { + return lenDiff; + } + var aPos = a.find(), + bPos = b.find(); + var fromCmp = + cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) { + return -fromCmp; + } + var toCmp = + cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) { + return toCmp; + } + return b.id - a.id; + } + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, + found; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if ( + sp.marker.collapsed && + (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0) + ) { + found = sp.marker; + } + } + } + return found; + } + function collapsedSpanAtStart(line) { + return collapsedSpanAtSide(line, true); + } + function collapsedSpanAtEnd(line) { + return collapsedSpanAtSide(line, false); + } + function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, + found; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if ( + sp.marker.collapsed && + (sp.from == null || sp.from < ch) && + (sp.to == null || sp.to > ch) && + (!found || compareCollapsedMarkers(found, sp.marker) < 0) + ) { + found = sp.marker; + } + } + } + return found; + } + function conflictingCollapsedRange( + doc, + lineNo2, + from, + to, + marker + ) { + var line = getLine(doc, lineNo2); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; + } + var found = sp.marker.find(0); + var fromCmp = + cmp(found.from, from) || + extraLeft(sp.marker) - extraLeft(marker); + var toCmp = + cmp(found.to, to) || + extraRight(sp.marker) - extraRight(marker); + if ( + (fromCmp >= 0 && toCmp <= 0) || + (fromCmp <= 0 && toCmp >= 0) + ) { + continue; + } + if ( + (fromCmp <= 0 && + (sp.marker.inclusiveRight && marker.inclusiveLeft + ? cmp(found.to, from) >= 0 + : cmp(found.to, from) > 0)) || + (fromCmp >= 0 && + (sp.marker.inclusiveRight && marker.inclusiveLeft + ? cmp(found.from, to) <= 0 + : cmp(found.from, to) < 0)) + ) { + return true; + } + } + } + } + function visualLine(line) { + var merged; + while ((merged = collapsedSpanAtStart(line))) { + line = merged.find(-1, true).line; + } + return line; + } + function visualLineEnd(line) { + var merged; + while ((merged = collapsedSpanAtEnd(line))) { + line = merged.find(1, true).line; + } + return line; + } + function visualLineContinued(line) { + var merged, lines; + while ((merged = collapsedSpanAtEnd(line))) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), + vis = visualLine(line); + if (line == vis) { + return lineN; + } + return lineNo(vis); + } + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { + return lineN; + } + var line = getLine(doc, lineN), + merged; + if (!lineIsHidden(doc, line)) { + return lineN; + } + while ((merged = collapsedSpanAtEnd(line))) { + line = merged.find(1, true).line; + } + return lineNo(line) + 1; + } + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; + } + if (sp.from == null) { + return true; + } + if (sp.marker.widgetNode) { + continue; + } + if ( + sp.from == 0 && + sp.marker.inclusiveLeft && + lineIsHiddenInner(doc, line, sp) + ) { + return true; + } + } + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner( + doc, + end.line, + getMarkedSpanFor(end.line.markedSpans, span.marker) + ); + } + if (span.marker.inclusiveRight && span.to == line.text.length) { + return true; + } + for ( + var sp = void 0, i2 = 0; + i2 < line.markedSpans.length; + ++i2 + ) { + sp = line.markedSpans[i2]; + if ( + sp.marker.collapsed && + !sp.marker.widgetNode && + sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp) + ) { + return true; + } + } + } + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + var h = 0, + chunk = lineObj.parent; + for (var i2 = 0; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2]; + if (line == lineObj) { + break; + } else { + h += line.height; + } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$12 = 0; i$12 < p.children.length; ++i$12) { + var cur = p.children[i$12]; + if (cur == chunk) { + break; + } else { + h += cur.height; + } + } + } + return h; + } + function lineLength(line) { + if (line.height == 0) { + return 0; + } + var len = line.text.length, + merged, + cur = line; + while ((merged = collapsedSpanAtStart(cur))) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while ((merged = collapsedSpanAtEnd(cur))) { + var found$1 = merged.find(0, true); + len -= cur.text.length - found$1.from.ch; + cur = found$1.to.line; + len += cur.text.length - found$1.to.ch; + } + return len; + } + function findMaxLine(cm) { + var d = cm.display, + doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + var Line = function (text, markedSpans, estimateHeight2) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight2 ? estimateHeight2(this) : 1; + }; + Line.prototype.lineNo = function () { + return lineNo(this); + }; + eventMixin(Line); + function updateLine(line, text, markedSpans, estimateHeight2) { + line.text = text; + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + if (line.order != null) { + line.order = null; + } + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight2 ? estimateHeight2(line) : 1; + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + } + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + var styleToClassCache = {}, + styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { + return null; + } + var cache = options.addModeClass + ? styleToClassCacheWithMode + : styleToClassCache; + return ( + cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) + ); + } + function buildLineContent(cm, lineView) { + var content = eltP( + "span", + null, + null, + webkit ? "padding-right: .1px" : null + ); + var builder = { + pre: eltP("pre", [content], "CodeMirror-line"), + content, + col: 0, + pos: 0, + cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping"), + }; + lineView.measure = {}; + for ( + var i2 = 0; + i2 <= (lineView.rest ? lineView.rest.length : 0); + i2++ + ) { + var line = i2 ? lineView.rest[i2 - 1] : lineView.line, + order = void 0; + builder.pos = 0; + builder.addToken = buildToken; + if ( + hasBadBidiRects(cm.display.measure) && + (order = getOrder(line, cm.doc.direction)) + ) { + builder.addToken = buildTokenBadBidi( + builder.addToken, + order + ); + } + builder.map = []; + var allowFrontierUpdate = + lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent( + line, + builder, + getLineStyles(cm, line, allowFrontierUpdate) + ); + if (line.styleClasses) { + if (line.styleClasses.bgClass) { + builder.bgClass = joinClasses( + line.styleClasses.bgClass, + builder.bgClass || "" + ); + } + if (line.styleClasses.textClass) { + builder.textClass = joinClasses( + line.styleClasses.textClass, + builder.textClass || "" + ); + } + } + if (builder.map.length == 0) { + builder.map.push( + 0, + 0, + builder.content.appendChild( + zeroWidthElement(cm.display.measure) + ) + ); + } + if (i2 == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + ( + lineView.measure.maps || (lineView.measure.maps = []) + ).push(builder.map); + ( + lineView.measure.caches || (lineView.measure.caches = []) + ).push({}); + } + } + if (webkit) { + var last = builder.content.lastChild; + if ( + /\bcm-tab\b/.test(last.className) || + (last.querySelector && last.querySelector(".cm-tab")) + ) { + builder.content.className = "cm-tab-wrap-hack"; + } + } + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) { + builder.textClass = joinClasses( + builder.pre.className, + builder.textClass || "" + ); + } + return builder; + } + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "•", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + function buildToken( + builder, + text, + style, + startStyle, + endStyle, + css, + attributes + ) { + if (!text) { + return; + } + var displayText = builder.splitSpaces + ? splitSpaces(text, builder.trailingSpace) + : text; + var special = builder.cm.state.specialChars, + mustWrap = false; + var content; + if (!special.test(text)) { + builder.col += text.length; + content = document.createTextNode(displayText); + builder.map.push( + builder.pos, + builder.pos + text.length, + content + ); + if (ie && ie_version < 9) { + mustWrap = true; + } + builder.pos += text.length; + } else { + content = document.createDocumentFragment(); + var pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode( + displayText.slice(pos, pos + skipped) + ); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt])); + } else { + content.appendChild(txt); + } + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) { + break; + } + pos += skipped + 1; + var txt$1 = void 0; + if (m[0] == " ") { + var tabSize = builder.cm.options.tabSize, + tabWidth = tabSize - (builder.col % tabSize); + txt$1 = content.appendChild( + elt("span", spaceStr(tabWidth), "cm-tab") + ); + txt$1.setAttribute("role", "presentation"); + txt$1.setAttribute("cm-text", " "); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild( + elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar") + ); + txt$1.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); + txt$1.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt$1])); + } else { + content.appendChild(txt$1); + } + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt$1); + builder.pos++; + } + } + builder.trailingSpace = + displayText.charCodeAt(text.length - 1) == 32; + if ( + style || + startStyle || + endStyle || + mustWrap || + css || + attributes + ) { + var fullStyle = style || ""; + if (startStyle) { + fullStyle += startStyle; + } + if (endStyle) { + fullStyle += endStyle; + } + var token = elt("span", [content], fullStyle, css); + if (attributes) { + for (var attr in attributes) { + if ( + attributes.hasOwnProperty(attr) && + attr != "style" && + attr != "class" + ) { + token.setAttribute(attr, attributes[attr]); + } + } + } + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { + return text; + } + var spaceBefore = trailingBefore, + result = ""; + for (var i2 = 0; i2 < text.length; i2++) { + var ch = text.charAt(i2); + if ( + ch == " " && + spaceBefore && + (i2 == text.length - 1 || text.charCodeAt(i2 + 1) == 32) + ) { + ch = " "; + } + result += ch; + spaceBefore = ch == " "; + } + return result; + } + function buildTokenBadBidi(inner, order) { + return function ( + builder, + text, + style, + startStyle, + endStyle, + css, + attributes + ) { + style = style + ? style + " cm-force-border" + : "cm-force-border"; + var start = builder.pos, + end = start + text.length; + for (;;) { + var part = void 0; + for (var i2 = 0; i2 < order.length; i2++) { + part = order[i2]; + if (part.to > start && part.from <= start) { + break; + } + } + if (part.to >= end) { + return inner( + builder, + text, + style, + startStyle, + endStyle, + css, + attributes + ); + } + inner( + builder, + text.slice(0, part.to - start), + style, + startStyle, + null, + css, + attributes + ); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) { + builder.map.push(builder.pos, builder.pos + size, widget); + } + if ( + !ignoreWidget && + builder.cm.display.input.needsContentAttribute + ) { + if (!widget) { + widget = builder.content.appendChild( + document.createElement("span") + ); + } + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + builder.trailingSpace = false; + } + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, + allText = line.text, + at = 0; + if (!spans) { + for (var i$12 = 1; i$12 < styles.length; i$12 += 2) { + builder.addToken( + builder, + allText.slice(at, (at = styles[i$12])), + interpretTokenStyle(styles[i$12 + 1], builder.cm.options) + ); + } + return; + } + var len = allText.length, + pos = 0, + i2 = 1, + text = "", + style, + css; + var nextChange = 0, + spanStyle, + spanEndStyle, + spanStartStyle, + collapsed, + attributes; + for (;;) { + if (nextChange == pos) { + spanStyle = spanEndStyle = spanStartStyle = css = ""; + attributes = null; + collapsed = null; + nextChange = Infinity; + var foundBookmarks = [], + endStyles = void 0; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], + m = sp.marker; + if ( + m.type == "bookmark" && + sp.from == pos && + m.widgetNode + ) { + foundBookmarks.push(m); + } else if ( + sp.from <= pos && + (sp.to == null || + sp.to > pos || + (m.collapsed && sp.to == pos && sp.from == pos)) + ) { + if ( + sp.to != null && + sp.to != pos && + nextChange > sp.to + ) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) { + spanStyle += " " + m.className; + } + if (m.css) { + css = (css ? css + ";" : "") + m.css; + } + if (m.startStyle && sp.from == pos) { + spanStartStyle += " " + m.startStyle; + } + if (m.endStyle && sp.to == nextChange) { + (endStyles || (endStyles = [])).push( + m.endStyle, + sp.to + ); + } + if (m.title) { + (attributes || (attributes = {})).title = m.title; + } + if (m.attributes) { + for (var attr in m.attributes) { + (attributes || (attributes = {}))[attr] = + m.attributes[attr]; + } + } + if ( + m.collapsed && + (!collapsed || + compareCollapsedMarkers(collapsed.marker, m) < 0) + ) { + collapsed = sp; + } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (endStyles) { + for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { + if (endStyles[j$1 + 1] == nextChange) { + spanEndStyle += " " + endStyles[j$1]; + } + } + } + if (!collapsed || collapsed.from == pos) { + for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { + buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan( + builder, + (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, + collapsed.from == null + ); + if (collapsed.to == null) { + return; + } + if (collapsed.to == pos) { + collapsed = false; + } + } + } + if (pos >= len) { + break; + } + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = + end > upto ? text.slice(0, upto - pos) : text; + builder.addToken( + builder, + tokenText, + style ? style + spanStyle : spanStyle, + spanStartStyle, + pos + tokenText.length == nextChange + ? spanEndStyle + : "", + css, + attributes + ); + } + if (end >= upto) { + text = text.slice(upto - pos); + pos = upto; + break; + } + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, (at = styles[i2++])); + style = interpretTokenStyle( + styles[i2++], + builder.cm.options + ); + } + } + } + function LineView(doc, line, lineN) { + this.line = line; + this.rest = visualLineContinued(line); + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + function buildViewArray(cm, from, to) { + var array = [], + nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + var operationGroup = null; + function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op); + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [], + }; + } + } + function fireCallbacksForOps(group) { + var callbacks = group.delayedCallbacks, + i2 = 0; + do { + for (; i2 < callbacks.length; i2++) { + callbacks[i2].call(null); + } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while ( + op.cursorActivityCalled < + op.cursorActivityHandlers.length + ) { + op.cursorActivityHandlers[ + op.cursorActivityCalled++ + ].call(null, op.cm); + } + } + } + } while (i2 < callbacks.length); + } + function finishOperation(op, endCb) { + var group = op.ownsGroup; + if (!group) { + return; + } + try { + fireCallbacksForOps(group); + } finally { + operationGroup = null; + endCb(group); + } + } + var orphanDelayedCallbacks = null; + function signalLater(emitter, type) { + var arr = getHandlers(emitter, type); + if (!arr.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2), + list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + var loop = function (i3) { + list.push(function () { + return arr[i3].apply(null, args); + }); + }; + for (var i2 = 0; i2 < arr.length; ++i2) loop(i2); + } + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i2 = 0; i2 < delayed.length; ++i2) { + delayed[i2](); + } + } + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") { + updateLineText(cm, lineView); + } else if (type == "gutter") { + updateLineGutter(cm, lineView, lineN, dims); + } else if (type == "class") { + updateLineClasses(cm, lineView); + } else if (type == "widget") { + updateLineWidgets(cm, lineView, dims); + } + } + lineView.changes = null; + } + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) { + lineView.text.parentNode.replaceChild( + lineView.node, + lineView.text + ); + } + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) { + lineView.node.style.zIndex = 2; + } + } + return lineView.node; + } + function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass + ? lineView.bgClass + " " + (lineView.line.bgClass || "") + : lineView.line.bgClass; + if (cls) { + cls += " CodeMirror-linebackground"; + } + if (lineView.background) { + if (cls) { + lineView.background.className = cls; + } else { + lineView.background.parentNode.removeChild( + lineView.background + ); + lineView.background = null; + } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore( + elt("div", null, cls), + wrap.firstChild + ); + cm.display.input.setUneditable(lineView.background); + } + } + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) { + lineView.node = built.pre; + } + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if ( + built.bgClass != lineView.bgClass || + built.textClass != lineView.textClass + ) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(cm, lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView); + if (lineView.line.wrapClass) { + ensureLineWrapped(lineView).className = + lineView.line.wrapClass; + } else if (lineView.node != lineView.text) { + lineView.node.className = ""; + } + var textClass = lineView.textClass + ? lineView.textClass + " " + (lineView.line.textClass || "") + : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt( + "div", + null, + "CodeMirror-gutter-background " + lineView.line.gutterClass, + "left: " + + (cm.options.fixedGutter + ? dims.fixedPos + : -dims.gutterTotalWidth) + + "px; width: " + + dims.gutterTotalWidth + + "px" + ); + cm.display.input.setUneditable(lineView.gutterBackground); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView); + var gutterWrap = (lineView.gutter = elt( + "div", + null, + "CodeMirror-gutter-wrapper", + "left: " + + (cm.options.fixedGutter + ? dims.fixedPos + : -dims.gutterTotalWidth) + + "px" + )); + gutterWrap.setAttribute("aria-hidden", "true"); + cm.display.input.setUneditable(gutterWrap); + wrap$1.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) { + gutterWrap.className += " " + lineView.line.gutterClass; + } + if ( + cm.options.lineNumbers && + (!markers || !markers["CodeMirror-linenumbers"]) + ) { + lineView.lineNumber = gutterWrap.appendChild( + elt( + "div", + lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + + dims.gutterLeft["CodeMirror-linenumbers"] + + "px; width: " + + cm.display.lineNumInnerWidth + + "px" + ) + ); + } + if (markers) { + for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { + var id = cm.display.gutterSpecs[k].className, + found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild( + elt( + "div", + [found], + "CodeMirror-gutter-elt", + "left: " + + dims.gutterLeft[id] + + "px; width: " + + dims.gutterWidth[id] + + "px" + ) + ); + } + } + } + } + } + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { + lineView.alignable = null; + } + var isWidget = classTest("CodeMirror-linewidget"); + for ( + var node = lineView.node.firstChild, next = void 0; + node; + node = next + ) { + next = node.nextSibling; + if (isWidget.test(node.className)) { + lineView.node.removeChild(node); + } + } + insertLineWidgets(cm, lineView, dims); + } + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) { + lineView.bgClass = built.bgClass; + } + if (built.textClass) { + lineView.textClass = built.textClass; + } + updateLineClasses(cm, lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + insertLineWidgetsFor( + cm, + lineView.rest[i2], + lineView, + dims, + false + ); + } + } + } + function insertLineWidgetsFor( + cm, + line, + lineView, + dims, + allowAbove + ) { + if (!line.widgets) { + return; + } + var wrap = ensureLineWrapped(lineView); + for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) { + var widget = ws[i2], + node = elt( + "div", + [widget.node], + "CodeMirror-linewidget" + + (widget.className ? " " + widget.className : "") + ); + if (!widget.handleMouseEvents) { + node.setAttribute("cm-ignore-events", "true"); + } + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) { + wrap.insertBefore(node, lineView.gutter || lineView.text); + } else { + wrap.appendChild(node); + } + signalLater(widget, "redraw"); + } + } + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) { + node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + } + function widgetHeight(widget) { + if (widget.height != null) { + return widget.height; + } + var cm = widget.doc.cm; + if (!cm) { + return 0; + } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) { + parentStyle += + "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; + } + if (widget.noHScroll) { + parentStyle += + "width: " + cm.display.wrapper.clientWidth + "px;"; + } + removeChildrenAndAdd( + cm.display.measure, + elt("div", [widget.node], null, parentStyle) + ); + } + return (widget.height = widget.node.parentNode.offsetHeight); + } + function eventInWidget(display, e) { + for ( + var n = e_target(e); + n != display.wrapper; + n = n.parentNode + ) { + if ( + !n || + (n.nodeType == 1 && + n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover) + ) { + return true; + } + } + } + function paddingTop(display) { + return display.lineSpace.offsetTop; + } + function paddingVert(display) { + return ( + display.mover.offsetHeight - display.lineSpace.offsetHeight + ); + } + function paddingH(display) { + if (display.cachedPaddingH) { + return display.cachedPaddingH; + } + var e = removeChildrenAndAdd( + display.measure, + elt("pre", "x", "CodeMirror-line-like") + ); + var style = window.getComputedStyle + ? window.getComputedStyle(e) + : e.currentStyle; + var data = { + left: parseInt(style.paddingLeft), + right: parseInt(style.paddingRight), + }; + if (!isNaN(data.left) && !isNaN(data.right)) { + display.cachedPaddingH = data; + } + return data; + } + function scrollGap(cm) { + return scrollerGap - cm.display.nativeBarWidth; + } + function displayWidth(cm) { + return ( + cm.display.scroller.clientWidth - + scrollGap(cm) - + cm.display.barWidth + ); + } + function displayHeight(cm) { + return ( + cm.display.scroller.clientHeight - + scrollGap(cm) - + cm.display.barHeight + ); + } + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if ( + !lineView.measure.heights || + (wrapping && lineView.measure.width != curWidth) + ) { + var heights = (lineView.measure.heights = []); + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i2 = 0; i2 < rects.length - 1; i2++) { + var cur = rects[i2], + next = rects[i2 + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) { + heights.push((cur.bottom + next.top) / 2 - rect.top); + } + } + } + heights.push(rect.bottom - rect.top); + } + } + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) { + return { + map: lineView.measure.map, + cache: lineView.measure.cache, + }; + } + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + if (lineView.rest[i2] == line) { + return { + map: lineView.measure.maps[i2], + cache: lineView.measure.caches[i2], + }; + } + } + for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) { + if (lineNo(lineView.rest[i$12]) > lineN) { + return { + map: lineView.measure.maps[i$12], + cache: lineView.measure.caches[i$12], + before: true, + }; + } + } + } + } + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = (cm.display.externalMeasured = new LineView( + cm.doc, + line, + lineN + )); + view.lineN = lineN; + var built = (view.built = buildLineContent(cm, view)); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + function measureChar(cm, line, ch, bias) { + return measureCharPrepared( + cm, + prepareMeasureForLine(cm, line), + ch, + bias + ); + } + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { + return cm.display.view[findViewIndex(cm, lineN)]; + } + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { + return ext; + } + } + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) { + view = updateExternalMeasurement(cm, line); + } + var info = mapFromLineView(view, line, lineN); + return { + line, + view, + rect: null, + map: info.map, + cache: info.cache, + before: info.before, + hasHeights: false, + }; + } + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { + ch = -1; + } + var key = ch + (bias || ""), + found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) { + prepared.rect = prepared.view.text.getBoundingClientRect(); + } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) { + prepared.cache[key] = found; + } + } + return { + left: found.left, + right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom, + }; + } + var nullRect = { + left: 0, + right: 0, + top: 0, + bottom: 0, + }; + function nodeAndOffsetInLineMap(map2, ch, bias) { + var node, start, end, collapse, mStart, mEnd; + for (var i2 = 0; i2 < map2.length; i2 += 3) { + mStart = map2[i2]; + mEnd = map2[i2 + 1]; + if (ch < mStart) { + start = 0; + end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if ( + i2 == map2.length - 3 || + (ch == mEnd && map2[i2 + 3] > ch) + ) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) { + collapse = "right"; + } + } + if (start != null) { + node = map2[i2 + 2]; + if ( + mStart == mEnd && + bias == (node.insertLeft ? "left" : "right") + ) { + collapse = bias; + } + if (bias == "left" && start == 0) { + while ( + i2 && + map2[i2 - 2] == map2[i2 - 3] && + map2[i2 - 1].insertLeft + ) { + node = map2[(i2 -= 3) + 2]; + collapse = "left"; + } + } + if (bias == "right" && start == mEnd - mStart) { + while ( + i2 < map2.length - 3 && + map2[i2 + 3] == map2[i2 + 4] && + !map2[i2 + 5].insertLeft + ) { + node = map2[(i2 += 3) + 2]; + collapse = "right"; + } + } + break; + } + } + return { + node, + start, + end, + collapse, + coverStart: mStart, + coverEnd: mEnd, + }; + } + function getUsefulRect(rects, bias) { + var rect = nullRect; + if (bias == "left") { + for (var i2 = 0; i2 < rects.length; i2++) { + if ((rect = rects[i2]).left != rect.right) { + break; + } + } + } else { + for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) { + if ((rect = rects[i$12]).left != rect.right) { + break; + } + } + } + return rect; + } + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, + start = place.start, + end = place.end, + collapse = place.collapse; + var rect; + if (node.nodeType == 3) { + for (var i$12 = 0; i$12 < 4; i$12++) { + while ( + start && + isExtendingChar( + prepared.line.text.charAt(place.coverStart + start) + ) + ) { + --start; + } + while ( + place.coverStart + end < place.coverEnd && + isExtendingChar( + prepared.line.text.charAt(place.coverStart + end) + ) + ) { + ++end; + } + if ( + ie && + ie_version < 9 && + start == 0 && + end == place.coverEnd - place.coverStart + ) { + rect = node.parentNode.getBoundingClientRect(); + } else { + rect = getUsefulRect( + range(node, start, end).getClientRects(), + bias + ); + } + if (rect.left || rect.right || start == 0) { + break; + } + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) { + rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } + } else { + if (start > 0) { + collapse = bias = "right"; + } + var rects; + if ( + cm.options.lineWrapping && + (rects = node.getClientRects()).length > 1 + ) { + rect = rects[bias == "right" ? rects.length - 1 : 0]; + } else { + rect = node.getBoundingClientRect(); + } + } + if ( + ie && + ie_version < 9 && + !start && + (!rect || (!rect.left && !rect.right)) + ) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) { + rect = { + left: rSpan.left, + right: rSpan.left + charWidth(cm.display), + top: rSpan.top, + bottom: rSpan.bottom, + }; + } else { + rect = nullRect; + } + } + var rtop = rect.top - prepared.rect.top, + rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + var i2 = 0; + for (; i2 < heights.length - 1; i2++) { + if (mid < heights[i2]) { + break; + } + } + var top = i2 ? heights[i2 - 1] : 0, + bot = heights[i2]; + var result = { + left: + (collapse == "right" ? rect.right : rect.left) - + prepared.rect.left, + right: + (collapse == "left" ? rect.left : rect.right) - + prepared.rect.left, + top, + bottom: bot, + }; + if (!rect.left && !rect.right) { + result.bogus = true; + } + if (!cm.options.singleCursorHeightPerLine) { + result.rtop = rtop; + result.rbottom = rbot; + } + return result; + } + function maybeUpdateRectForZooming(measure, rect) { + if ( + !window.screen || + screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || + !hasBadZoomedRects(measure) + ) { + return rect; + } + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return { + left: rect.left * scaleX, + right: rect.right * scaleX, + top: rect.top * scaleY, + bottom: rect.bottom * scaleY, + }; + } + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + lineView.measure.caches[i2] = {}; + } + } + } + } + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + clearLineMeasurementCacheFor(cm.display.view[i2]); + } + } + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = + cm.display.cachedTextHeight = + cm.display.cachedPaddingH = + null; + if (!cm.options.lineWrapping) { + cm.display.maxLineChanged = true; + } + cm.display.lineNumChars = null; + } + function pageScrollX() { + if (chrome && android) { + return -( + document.body.getBoundingClientRect().left - + parseInt(getComputedStyle(document.body).marginLeft) + ); + } + return ( + window.pageXOffset || + (document.documentElement || document.body).scrollLeft + ); + } + function pageScrollY() { + if (chrome && android) { + return -( + document.body.getBoundingClientRect().top - + parseInt(getComputedStyle(document.body).marginTop) + ); + } + return ( + window.pageYOffset || + (document.documentElement || document.body).scrollTop + ); + } + function widgetTopHeight(lineObj) { + var ref = visualLine(lineObj); + var widgets = ref.widgets; + var height = 0; + if (widgets) { + for (var i2 = 0; i2 < widgets.length; ++i2) { + if (widgets[i2].above) { + height += widgetHeight(widgets[i2]); + } + } + } + return height; + } + function intoCoordSystem( + cm, + lineObj, + rect, + context, + includeWidgets + ) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj); + rect.top += height; + rect.bottom += height; + } + if (context == "line") { + return rect; + } + if (!context) { + context = "local"; + } + var yOff = heightAtLine(lineObj); + if (context == "local") { + yOff += paddingTop(cm.display); + } else { + yOff -= cm.display.viewOffset; + } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = + lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; + rect.right += xOff; + } + rect.top += yOff; + rect.bottom += yOff; + return rect; + } + function fromCoordSystem(cm, coords, context) { + if (context == "div") { + return coords; + } + var left = coords.left, + top = coords.top; + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return { + left: left - lineSpaceBox.left, + top: top - lineSpaceBox.top, + }; + } + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { + lineObj = getLine(cm.doc, pos.line); + } + return intoCoordSystem( + cm, + lineObj, + measureChar(cm, lineObj, pos.ch, bias), + context + ); + } + function cursorCoords( + cm, + pos, + context, + lineObj, + preparedMeasure, + varHeight + ) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + function get(ch2, right) { + var m = measureCharPrepared( + cm, + preparedMeasure, + ch2, + right ? "right" : "left", + varHeight + ); + if (right) { + m.left = m.right; + } else { + m.right = m.left; + } + return intoCoordSystem(cm, lineObj, m, context); + } + var order = getOrder(lineObj, cm.doc.direction), + ch = pos.ch, + sticky = pos.sticky; + if (ch >= lineObj.text.length) { + ch = lineObj.text.length; + sticky = "before"; + } else if (ch <= 0) { + ch = 0; + sticky = "after"; + } + if (!order) { + return get( + sticky == "before" ? ch - 1 : ch, + sticky == "before" + ); + } + function getBidi(ch2, partPos2, invert) { + var part = order[partPos2], + right = part.level == 1; + return get(invert ? ch2 - 1 : ch2, right != invert); + } + var partPos = getBidiPartAt(order, ch, sticky); + var other = bidiOther; + var val = getBidi(ch, partPos, sticky == "before"); + if (other != null) { + val.other = getBidi(ch, other, sticky != "before"); + } + return val; + } + function estimateCoords(cm, pos) { + var left = 0; + pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) { + left = charWidth(cm.display) * pos.ch; + } + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return { + left, + right: left, + top, + bottom: top + lineObj.height, + }; + } + function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky); + pos.xRel = xRel; + if (outside) { + pos.outside = outside; + } + return pos; + } + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) { + return PosWithInfo(doc.first, 0, null, -1, -1); + } + var lineN = lineAtHeight(doc, y), + last = doc.first + doc.size - 1; + if (lineN > last) { + return PosWithInfo( + doc.first + doc.size - 1, + getLine(doc, last).text.length, + null, + 1, + 1 + ); + } + if (x < 0) { + x = 0; + } + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var collapsed = collapsedSpanAround( + lineObj, + found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0) + ); + if (!collapsed) { + return found; + } + var rangeEnd = collapsed.find(1); + if (rangeEnd.line == lineN) { + return rangeEnd; + } + lineObj = getLine(doc, (lineN = rangeEnd.line)); + } + } + function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj); + var end = lineObj.text.length; + var begin = findFirst( + function (ch) { + return ( + measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= + y + ); + }, + end, + 0 + ); + end = findFirst( + function (ch) { + return measureCharPrepared(cm, preparedMeasure, ch).top > y; + }, + begin, + end + ); + return { + begin, + end, + }; + } + function wrappedLineExtentChar( + cm, + lineObj, + preparedMeasure, + target + ) { + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + var targetTop = intoCoordSystem( + cm, + lineObj, + measureCharPrepared(cm, preparedMeasure, target), + "line" + ).top; + return wrappedLineExtent( + cm, + lineObj, + preparedMeasure, + targetTop + ); + } + function boxIsAfter(box, x, y, left) { + return box.bottom <= y + ? false + : box.top > y + ? true + : (left ? box.left : box.right) > x; + } + function coordsCharInner(cm, lineObj, lineNo2, x, y) { + y -= heightAtLine(lineObj); + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + var widgetHeight2 = widgetTopHeight(lineObj); + var begin = 0, + end = lineObj.text.length, + ltr = true; + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = ( + cm.options.lineWrapping + ? coordsBidiPartWrapped + : coordsBidiPart + )(cm, lineObj, lineNo2, preparedMeasure, order, x, y); + ltr = part.level != 1; + begin = ltr ? part.from : part.to - 1; + end = ltr ? part.to : part.from - 1; + } + var chAround = null, + boxAround = null; + var ch = findFirst( + function (ch2) { + var box = measureCharPrepared(cm, preparedMeasure, ch2); + box.top += widgetHeight2; + box.bottom += widgetHeight2; + if (!boxIsAfter(box, x, y, false)) { + return false; + } + if (box.top <= y && box.left <= x) { + chAround = ch2; + boxAround = box; + } + return true; + }, + begin, + end + ); + var baseX, + sticky, + outside = false; + if (boxAround) { + var atLeft = x - boxAround.left < boxAround.right - x, + atStart = atLeft == ltr; + ch = chAround + (atStart ? 0 : 1); + sticky = atStart ? "after" : "before"; + baseX = atLeft ? boxAround.left : boxAround.right; + } else { + if (!ltr && (ch == end || ch == begin)) { + ch++; + } + sticky = + ch == 0 + ? "after" + : ch == lineObj.text.length + ? "before" + : measureCharPrepared( + cm, + preparedMeasure, + ch - (ltr ? 1 : 0) + ).bottom + + widgetHeight2 <= + y == + ltr + ? "after" + : "before"; + var coords = cursorCoords( + cm, + Pos(lineNo2, ch, sticky), + "line", + lineObj, + preparedMeasure + ); + baseX = coords.left; + outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + } + ch = skipExtendingChars(lineObj.text, ch, 1); + return PosWithInfo(lineNo2, ch, sticky, outside, x - baseX); + } + function coordsBidiPart( + cm, + lineObj, + lineNo2, + preparedMeasure, + order, + x, + y + ) { + var index = findFirst( + function (i2) { + var part2 = order[i2], + ltr2 = part2.level != 1; + return boxIsAfter( + cursorCoords( + cm, + Pos( + lineNo2, + ltr2 ? part2.to : part2.from, + ltr2 ? "before" : "after" + ), + "line", + lineObj, + preparedMeasure + ), + x, + y, + true + ); + }, + 0, + order.length - 1 + ); + var part = order[index]; + if (index > 0) { + var ltr = part.level != 1; + var start = cursorCoords( + cm, + Pos( + lineNo2, + ltr ? part.from : part.to, + ltr ? "after" : "before" + ), + "line", + lineObj, + preparedMeasure + ); + if (boxIsAfter(start, x, y, true) && start.top > y) { + part = order[index - 1]; + } + } + return part; + } + function coordsBidiPartWrapped( + cm, + lineObj, + _lineNo, + preparedMeasure, + order, + x, + y + ) { + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { + end--; + } + var part = null, + closestDist = null; + for (var i2 = 0; i2 < order.length; i2++) { + var p = order[i2]; + if (p.from >= end || p.to <= begin) { + continue; + } + var ltr = p.level != 1; + var endX = measureCharPrepared( + cm, + preparedMeasure, + ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from) + ).right; + var dist = endX < x ? x - endX + 1e9 : endX - x; + if (!part || closestDist > dist) { + part = p; + closestDist = dist; + } + } + if (!part) { + part = order[order.length - 1]; + } + if (part.from < begin) { + part = { + from: begin, + to: part.to, + level: part.level, + }; + } + if (part.to > end) { + part = { + from: part.from, + to: end, + level: part.level, + }; + } + return part; + } + var measureText; + function textHeight(display) { + if (display.cachedTextHeight != null) { + return display.cachedTextHeight; + } + if (measureText == null) { + measureText = elt("pre", null, "CodeMirror-line-like"); + for (var i2 = 0; i2 < 49; ++i2) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) { + display.cachedTextHeight = height; + } + removeChildren(display.measure); + return height || 1; + } + function charWidth(display) { + if (display.cachedCharWidth != null) { + return display.cachedCharWidth; + } + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor], "CodeMirror-line-like"); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), + width = (rect.right - rect.left) / 10; + if (width > 2) { + display.cachedCharWidth = width; + } + return width || 10; + } + function getDimensions(cm) { + var d = cm.display, + left = {}, + width = {}; + var gutterLeft = d.gutters.clientLeft; + for ( + var n = d.gutters.firstChild, i2 = 0; + n; + n = n.nextSibling, ++i2 + ) { + var id = cm.display.gutterSpecs[i2].className; + left[id] = n.offsetLeft + n.clientLeft + gutterLeft; + width[id] = n.clientWidth; + } + return { + fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth, + }; + } + function compensateForHScroll(display) { + return ( + display.scroller.getBoundingClientRect().left - + display.sizer.getBoundingClientRect().left + ); + } + function estimateHeight(cm) { + var th = textHeight(cm.display), + wrapping = cm.options.lineWrapping; + var perLine = + wrapping && + Math.max( + 5, + cm.display.scroller.clientWidth / charWidth(cm.display) - 3 + ); + return function (line) { + if (lineIsHidden(cm.doc, line)) { + return 0; + } + var widgetsHeight = 0; + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].height) { + widgetsHeight += line.widgets[i2].height; + } + } + } + if (wrapping) { + return ( + widgetsHeight + + (Math.ceil(line.text.length / perLine) || 1) * th + ); + } else { + return widgetsHeight + th; + } + }; + } + function estimateLineHeights(cm) { + var doc = cm.doc, + est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + }); + } + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if ( + !liberal && + e_target(e).getAttribute("cm-not-content") == "true" + ) { + return null; + } + var x, + y, + space = display.lineSpace.getBoundingClientRect(); + try { + x = e.clientX - space.left; + y = e.clientY - space.top; + } catch (e$1) { + return null; + } + var coords = coordsChar(cm, x, y), + line; + if ( + forRect && + coords.xRel > 0 && + (line = getLine(cm.doc, coords.line).text).length == coords.ch + ) { + var colDiff = + countColumn(line, line.length, cm.options.tabSize) - + line.length; + coords = Pos( + coords.line, + Math.max( + 0, + Math.round( + (x - paddingH(cm.display).left) / charWidth(cm.display) + ) - colDiff + ) + ); + } + return coords; + } + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { + return null; + } + n -= cm.display.viewFrom; + if (n < 0) { + return null; + } + var view = cm.display.view; + for (var i2 = 0; i2 < view.length; i2++) { + n -= view[i2].size; + if (n < 0) { + return i2; + } + } + } + function regChange(cm, from, to, lendiff) { + if (from == null) { + from = cm.doc.first; + } + if (to == null) { + to = cm.doc.first + cm.doc.size; + } + if (!lendiff) { + lendiff = 0; + } + var display = cm.display; + if ( + lendiff && + to < display.viewTo && + (display.updateLineNumbers == null || + display.updateLineNumbers > from) + ) { + display.updateLineNumbers = from; + } + cm.curOp.viewChanged = true; + if (from >= display.viewTo) { + if ( + sawCollapsedSpans && + visualLineNo(cm.doc, from) < display.viewTo + ) { + resetView(cm); + } + } else if (to <= display.viewFrom) { + if ( + sawCollapsedSpans && + visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom + ) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { + resetView(cm); + } else if (from <= display.viewFrom) { + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { + var cut$1 = viewCuttingPoint(cm, from, from, -1); + if (cut$1) { + display.view = display.view.slice(0, cut$1.index); + display.viewTo = cut$1.lineN; + } else { + resetView(cm); + } + } else { + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view + .slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) { + ext.lineN += lendiff; + } else if (from < ext.lineN + ext.size) { + display.externalMeasured = null; + } + } + } + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, + ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { + display.externalMeasured = null; + } + if (line < display.viewFrom || line >= display.viewTo) { + return; + } + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) { + return; + } + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) { + arr.push(type); + } + } + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), + diff, + view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { + return { + index, + lineN: newN, + }; + } + var n = cm.display.viewFrom; + for (var i2 = 0; i2 < index; i2++) { + n += view[i2].size; + } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { + return null; + } + diff = n + view[index].size - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; + newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { + return null; + } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return { + index, + lineN: newN, + }; + } + function adjustView(cm, from, to) { + var display = cm.display, + view = display.view; + if ( + view.length == 0 || + from >= display.viewTo || + to <= display.viewFrom + ) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) { + display.view = buildViewArray( + cm, + from, + display.viewFrom + ).concat(display.view); + } else if (display.viewFrom < from) { + display.view = display.view.slice(findViewIndex(cm, from)); + } + display.viewFrom = from; + if (display.viewTo < to) { + display.view = display.view.concat( + buildViewArray(cm, display.viewTo, to) + ); + } else if (display.viewTo > to) { + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + } + display.viewTo = to; + } + function countDirtyView(cm) { + var view = cm.display.view, + dirty = 0; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if ( + !lineView.hidden && + (!lineView.node || lineView.changes) + ) { + ++dirty; + } + } + return dirty; + } + function updateSelection(cm) { + cm.display.input.showSelection( + cm.display.input.prepareSelection() + ); + } + function prepareSelection(cm, primary) { + if (primary === void 0) primary = true; + var doc = cm.doc, + result = {}; + var curFragment = (result.cursors = + document.createDocumentFragment()); + var selFragment = (result.selection = + document.createDocumentFragment()); + var customCursor = cm.options.$customCursor; + if (customCursor) { + primary = true; + } + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + if (!primary && i2 == doc.sel.primIndex) { + continue; + } + var range2 = doc.sel.ranges[i2]; + if ( + range2.from().line >= cm.display.viewTo || + range2.to().line < cm.display.viewFrom + ) { + continue; + } + var collapsed = range2.empty(); + if (customCursor) { + var head = customCursor(cm, range2); + if (head) { + drawSelectionCursor(cm, head, curFragment); + } + } else if (collapsed || cm.options.showCursorWhenSelecting) { + drawSelectionCursor(cm, range2.head, curFragment); + } + if (!collapsed) { + drawSelectionRange(cm, range2, selFragment); + } + } + return result; + } + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords( + cm, + head, + "div", + null, + null, + !cm.options.singleCursorHeightPerLine + ); + var cursor = output.appendChild( + elt("div", " ", "CodeMirror-cursor") + ); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = + Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + + "px"; + if ( + /\bcm-fat-cursor\b/.test(cm.getWrapperElement().className) + ) { + var charPos = charCoords(cm, head, "div", null, null); + var width = charPos.right - charPos.left; + cursor.style.width = + (width > 0 ? width : cm.defaultCharWidth()) + "px"; + } + if (pos.other) { + var otherCursor = output.appendChild( + elt( + "div", + " ", + "CodeMirror-cursor CodeMirror-secondarycursor" + ) + ); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = + (pos.other.bottom - pos.other.top) * 0.85 + "px"; + } + } + function cmpCoords(a, b) { + return a.top - b.top || a.left - b.left; + } + function drawSelectionRange(cm, range2, output) { + var display = cm.display, + doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), + leftSide = padding.left; + var rightSide = + Math.max( + display.sizerWidth, + displayWidth(cm) - display.sizer.offsetLeft + ) - padding.right; + var docLTR = doc.direction == "ltr"; + function add(left, top, width, bottom) { + if (top < 0) { + top = 0; + } + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild( + elt( + "div", + null, + "CodeMirror-selected", + "position: absolute; left: " + + left + + "px;\n top: " + + top + + "px; width: " + + (width == null ? rightSide - left : width) + + "px;\n height: " + + (bottom - top) + + "px" + ) + ); + } + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos); + var prop2 = + (dir == "ltr") == (side == "after") ? "left" : "right"; + var ch = + side == "after" + ? extent.begin + : extent.end - + (/\s/.test(lineObj.text.charAt(extent.end - 1)) + ? 2 + : 1); + return coords(ch, prop2)[prop2]; + } + var order = getOrder(lineObj, doc.direction); + iterateBidiSections( + order, + fromArg || 0, + toArg == null ? lineLen : toArg, + function (from, to, dir, i2) { + var ltr = dir == "ltr"; + var fromPos = coords(from, ltr ? "left" : "right"); + var toPos = coords(to - 1, ltr ? "right" : "left"); + var openStart = fromArg == null && from == 0, + openEnd = toArg == null && to == lineLen; + var first = i2 == 0, + last = !order || i2 == order.length - 1; + if (toPos.top - fromPos.top <= 3) { + var openLeft = (docLTR ? openStart : openEnd) && first; + var openRight = (docLTR ? openEnd : openStart) && last; + var left = openLeft + ? leftSide + : (ltr ? fromPos : toPos).left; + var right = openRight + ? rightSide + : (ltr ? toPos : fromPos).right; + add(left, fromPos.top, right - left, fromPos.bottom); + } else { + var topLeft, topRight, botLeft, botRight; + if (ltr) { + topLeft = + docLTR && openStart && first + ? leftSide + : fromPos.left; + topRight = docLTR + ? rightSide + : wrapX(from, dir, "before"); + botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); + botRight = + docLTR && openEnd && last ? rightSide : toPos.right; + } else { + topLeft = !docLTR + ? leftSide + : wrapX(from, dir, "before"); + topRight = + !docLTR && openStart && first + ? rightSide + : fromPos.right; + botLeft = + !docLTR && openEnd && last ? leftSide : toPos.left; + botRight = !docLTR + ? rightSide + : wrapX(to, dir, "after"); + } + add( + topLeft, + fromPos.top, + topRight - topLeft, + fromPos.bottom + ); + if (fromPos.bottom < toPos.top) { + add(leftSide, fromPos.bottom, null, toPos.top); + } + add( + botLeft, + toPos.top, + botRight - botLeft, + toPos.bottom + ); + } + if (!start || cmpCoords(fromPos, start) < 0) { + start = fromPos; + } + if (cmpCoords(toPos, start) < 0) { + start = toPos; + } + if (!end || cmpCoords(fromPos, end) < 0) { + end = fromPos; + } + if (cmpCoords(toPos, end) < 0) { + end = toPos; + } + } + ); + return { + start, + end, + }; + } + var sFrom = range2.from(), + sTo = range2.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), + toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine( + sFrom.line, + sFrom.ch, + singleVLine ? fromLine.text.length + 1 : null + ).end; + var rightStart = drawForLine( + sTo.line, + singleVLine ? 0 : null, + sTo.ch + ).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add( + leftSide, + rightStart.top, + rightStart.left, + rightStart.bottom + ); + } else { + add( + leftEnd.right, + leftEnd.top, + rightStart.left - leftEnd.right, + leftEnd.bottom + ); + } + } + if (leftEnd.bottom < rightStart.top) { + add(leftSide, leftEnd.bottom, null, rightStart.top); + } + } + output.appendChild(fragment); + } + function restartBlink(cm) { + if (!cm.state.focused) { + return; + } + var display = cm.display; + clearInterval(display.blinker); + var on2 = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function () { + if (!cm.hasFocus()) { + onBlur(cm); + } + display.cursorDiv.style.visibility = (on2 = !on2) + ? "" + : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) { + display.cursorDiv.style.visibility = "hidden"; + } + } + function ensureFocus(cm) { + if (!cm.hasFocus()) { + cm.display.input.focus(); + if (!cm.state.focused) { + onFocus(cm); + } + } + } + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + if (cm.state.focused) { + onBlur(cm); + } + } + }, 100); + } + function onFocus(cm, e) { + if (cm.state.delayingBlurEvent && !cm.state.draggingText) { + cm.state.delayingBlurEvent = false; + } + if (cm.options.readOnly == "nocursor") { + return; + } + if (!cm.state.focused) { + signal(cm, "focus", cm, e); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) { + setTimeout(function () { + return cm.display.input.reset(true); + }, 20); + } + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { + return; + } + if (cm.state.focused) { + signal(cm, "blur", cm, e); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () { + if (!cm.state.focused) { + cm.display.shift = false; + } + }, 150); + } + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + var viewTop = Math.max( + 0, + display.scroller.getBoundingClientRect().top + ); + var oldHeight = display.lineDiv.getBoundingClientRect().top; + var mustScroll = 0; + for (var i2 = 0; i2 < display.view.length; i2++) { + var cur = display.view[i2], + wrapping = cm.options.lineWrapping; + var height = void 0, + width = 0; + if (cur.hidden) { + continue; + } + oldHeight += cur.line.height; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + if (!wrapping && cur.text.firstChild) { + width = + cur.text.firstChild.getBoundingClientRect().right - + box.left - + 1; + } + } + var diff = cur.line.height - height; + if (diff > 5e-3 || diff < -5e-3) { + if (oldHeight < viewTop) { + mustScroll -= diff; + } + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) { + updateWidgetHeight(cur.rest[j]); + } + } + } + if (width > cm.display.sizerWidth) { + var chWidth = Math.ceil(width / charWidth(cm.display)); + if (chWidth > cm.display.maxLineLength) { + cm.display.maxLineLength = chWidth; + cm.display.maxLine = cur.line; + cm.display.maxLineChanged = true; + } + } + } + if (Math.abs(mustScroll) > 2) { + display.scroller.scrollTop += mustScroll; + } + } + function updateWidgetHeight(line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; ++i2) { + var w = line.widgets[i2], + parent = w.node.parentNode; + if (parent) { + w.height = parent.offsetHeight; + } + } + } + } + function visibleLines(display, doc, viewport) { + var top = + viewport && viewport.top != null + ? Math.max(0, viewport.top) + : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = + viewport && viewport.bottom != null + ? viewport.bottom + : top + display.wrapper.clientHeight; + var from = lineAtHeight(doc, top), + to = lineAtHeight(doc, bottom); + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, + ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight( + doc, + heightAtLine(getLine(doc, ensureFrom)) + + display.wrapper.clientHeight + ); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight( + doc, + heightAtLine(getLine(doc, ensureTo)) - + display.wrapper.clientHeight + ); + to = ensureTo; + } + } + return { + from, + to: Math.max(to, from + 1), + }; + } + function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { + return; + } + var display = cm.display, + box = display.sizer.getBoundingClientRect(), + doScroll = null; + if (rect.top + box.top < 0) { + doScroll = true; + } else if ( + rect.bottom + box.top > + (window.innerHeight || document.documentElement.clientHeight) + ) { + doScroll = false; + } + if (doScroll != null && !phantom) { + var scrollNode = elt( + "div", + "​", + null, + "position: absolute;\n top: " + + (rect.top - display.viewOffset - paddingTop(cm.display)) + + "px;\n height: " + + (rect.bottom - + rect.top + + scrollGap(cm) + + display.barHeight) + + "px;\n left: " + + rect.left + + "px; width: " + + Math.max(2, rect.right - rect.left) + + "px;" + ); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { + margin = 0; + } + var rect; + if (!cm.options.lineWrapping && pos == end) { + end = + pos.sticky == "before" + ? Pos(pos.line, pos.ch + 1, "before") + : pos; + pos = pos.ch + ? Pos( + pos.line, + pos.sticky == "before" ? pos.ch - 1 : pos.ch, + "after" + ) + : pos; + } + for (var limit = 0; limit < 5; limit++) { + var changed = false; + var coords = cursorCoords(cm, pos); + var endCoords = + !end || end == pos ? coords : cursorCoords(cm, end); + rect = { + left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin, + }; + var scrollPos = calculateScrollPos(cm, rect); + var startTop = cm.doc.scrollTop, + startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { + changed = true; + } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { + changed = true; + } + } + if (!changed) { + break; + } + } + return rect; + } + function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect); + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + } + } + function calculateScrollPos(cm, rect) { + var display = cm.display, + snapMargin = textHeight(cm.display); + if (rect.top < 0) { + rect.top = 0; + } + var screentop = + cm.curOp && cm.curOp.scrollTop != null + ? cm.curOp.scrollTop + : display.scroller.scrollTop; + var screen2 = displayHeight(cm), + result = {}; + if (rect.bottom - rect.top > screen2) { + rect.bottom = rect.top + screen2; + } + var docBottom = cm.doc.height + paddingVert(display); + var atTop = rect.top < snapMargin, + atBottom = rect.bottom > docBottom - snapMargin; + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top; + } else if (rect.bottom > screentop + screen2) { + var newTop = Math.min( + rect.top, + (atBottom ? docBottom : rect.bottom) - screen2 + ); + if (newTop != screentop) { + result.scrollTop = newTop; + } + } + var gutterSpace = cm.options.fixedGutter + ? 0 + : display.gutters.offsetWidth; + var screenleft = + cm.curOp && cm.curOp.scrollLeft != null + ? cm.curOp.scrollLeft + : display.scroller.scrollLeft - gutterSpace; + var screenw = displayWidth(cm) - display.gutters.offsetWidth; + var tooWide = rect.right - rect.left > screenw; + if (tooWide) { + rect.right = rect.left + screenw; + } + if (rect.left < 10) { + result.scrollLeft = 0; + } else if (rect.left < screenleft) { + result.scrollLeft = Math.max( + 0, + rect.left + gutterSpace - (tooWide ? 0 : 10) + ); + } else if (rect.right > screenw + screenleft - 3) { + result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; + } + return result; + } + function addToScrollTop(cm, top) { + if (top == null) { + return; + } + resolveScrollToPos(cm); + cm.curOp.scrollTop = + (cm.curOp.scrollTop == null + ? cm.doc.scrollTop + : cm.curOp.scrollTop) + top; + } + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(); + cm.curOp.scrollToPos = { + from: cur, + to: cur, + margin: cm.options.cursorScrollMargin, + }; + } + function scrollToCoords(cm, x, y) { + if (x != null || y != null) { + resolveScrollToPos(cm); + } + if (x != null) { + cm.curOp.scrollLeft = x; + } + if (y != null) { + cm.curOp.scrollTop = y; + } + } + function scrollToRange(cm, range2) { + resolveScrollToPos(cm); + cm.curOp.scrollToPos = range2; + } + function resolveScrollToPos(cm) { + var range2 = cm.curOp.scrollToPos; + if (range2) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range2.from), + to = estimateCoords(cm, range2.to); + scrollToCoordsRange(cm, from, to, range2.margin); + } + } + function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin, + }); + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); + } + function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { + return; + } + if (!gecko) { + updateDisplaySimple(cm, { + top: val, + }); + } + setScrollTop(cm, val, true); + if (gecko) { + updateDisplaySimple(cm); + } + startWorker(cm, 100); + } + function setScrollTop(cm, val, forceScroll) { + val = Math.max( + 0, + Math.min( + cm.display.scroller.scrollHeight - + cm.display.scroller.clientHeight, + val + ) + ); + if (cm.display.scroller.scrollTop == val && !forceScroll) { + return; + } + cm.doc.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (cm.display.scroller.scrollTop != val) { + cm.display.scroller.scrollTop = val; + } + } + function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.max( + 0, + Math.min( + val, + cm.display.scroller.scrollWidth - + cm.display.scroller.clientWidth + ) + ); + if ( + (isScroller + ? val == cm.doc.scrollLeft + : Math.abs(cm.doc.scrollLeft - val) < 2) && + !forceScroll + ) { + return; + } + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) { + cm.display.scroller.scrollLeft = val; + } + cm.display.scrollbars.setScrollLeft(val); + } + function measureForScrollbars(cm) { + var d = cm.display, + gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, + clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW, + }; + } + var NativeScrollbars = function (place, scroll, cm) { + this.cm = cm; + var vert = (this.vert = elt( + "div", + [elt("div", null, null, "min-width: 1px")], + "CodeMirror-vscrollbar" + )); + var horiz = (this.horiz = elt( + "div", + [elt("div", null, null, "height: 100%; min-height: 1px")], + "CodeMirror-hscrollbar" + )); + vert.tabIndex = horiz.tabIndex = -1; + place(vert); + place(horiz); + on(vert, "scroll", function () { + if (vert.clientHeight) { + scroll(vert.scrollTop, "vertical"); + } + }); + on(horiz, "scroll", function () { + if (horiz.clientWidth) { + scroll(horiz.scrollLeft, "horizontal"); + } + }); + this.checkedZeroWidth = false; + if (ie && ie_version < 8) { + this.horiz.style.minHeight = this.vert.style.minWidth = + "18px"; + } + }; + NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + this.vert.firstChild.style.height = + Math.max( + 0, + measure.scrollHeight - measure.clientHeight + totalHeight + ) + "px"; + } else { + this.vert.scrollTop = 0; + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = + measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + Math.max( + 0, + measure.scrollWidth - measure.clientWidth + totalWidth + ) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { + this.zeroWidthHack(); + } + this.checkedZeroWidth = true; + } + return { + right: needsV ? sWidth : 0, + bottom: needsH ? sWidth : 0, + }; + }; + NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { + this.horiz.scrollLeft = pos; + } + if (this.disableHoriz) { + this.enableZeroWidthBar( + this.horiz, + this.disableHoriz, + "horiz" + ); + } + }; + NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { + this.vert.scrollTop = pos; + } + if (this.disableVert) { + this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); + } + }; + NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = + "none"; + this.disableHoriz = new Delayed(); + this.disableVert = new Delayed(); + }; + NativeScrollbars.prototype.enableZeroWidthBar = function ( + bar, + delay, + type + ) { + bar.style.pointerEvents = "auto"; + function maybeDisable() { + var box = bar.getBoundingClientRect(); + var elt2 = + type == "vert" + ? document.elementFromPoint( + box.right - 1, + (box.top + box.bottom) / 2 + ) + : document.elementFromPoint( + (box.right + box.left) / 2, + box.bottom - 1 + ); + if (elt2 != bar) { + bar.style.pointerEvents = "none"; + } else { + delay.set(1e3, maybeDisable); + } + } + delay.set(1e3, maybeDisable); + }; + NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + }; + var NullScrollbars = function () {}; + NullScrollbars.prototype.update = function () { + return { + bottom: 0, + right: 0, + }; + }; + NullScrollbars.prototype.setScrollLeft = function () {}; + NullScrollbars.prototype.setScrollTop = function () {}; + NullScrollbars.prototype.clear = function () {}; + function updateScrollbars(cm, measure) { + if (!measure) { + measure = measureForScrollbars(cm); + } + var startWidth = cm.display.barWidth, + startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for ( + var i2 = 0; + (i2 < 4 && startWidth != cm.display.barWidth) || + startHeight != cm.display.barHeight; + i2++ + ) { + if ( + startWidth != cm.display.barWidth && + cm.options.lineWrapping + ) { + updateHeightsInViewport(cm); + } + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; + startHeight = cm.display.barHeight; + } + } + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = + (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = + sizes.bottom + "px solid transparent"; + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else { + d.scrollbarFiller.style.display = ""; + } + if ( + sizes.bottom && + cm.options.coverGutterNextToScrollbar && + cm.options.fixedGutter + ) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else { + d.gutterFiller.style.display = ""; + } + } + var scrollbarModel = { + native: NativeScrollbars, + null: NullScrollbars, + }; + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) { + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + cm.display.scrollbars = new scrollbarModel[ + cm.options.scrollbarStyle + ]( + function (node) { + cm.display.wrapper.insertBefore( + node, + cm.display.scrollbarFiller + ); + on(node, "mousedown", function () { + if (cm.state.focused) { + setTimeout(function () { + return cm.display.input.focus(); + }, 0); + } + }); + node.setAttribute("cm-not-content", "true"); + }, + function (pos, axis) { + if (axis == "horizontal") { + setScrollLeft(cm, pos); + } else { + updateScrollTop(cm, pos); + } + }, + cm + ); + if (cm.display.scrollbars.addClass) { + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + var nextOpId = 0; + function startOperation(cm) { + cm.curOp = { + cm, + viewChanged: false, + // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, + // Used to detect need to update scrollbar + forceUpdate: false, + // Used to force a redraw + updateInput: 0, + // Whether to reset the input textarea + typing: false, + // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, + // Accumulated changes, for firing change events + cursorActivityHandlers: null, + // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, + // Tracks which cursorActivity handlers have been called already + selectionChanged: false, + // Whether the selection needs to be redrawn + updateMaxLine: false, + // Set when the widest line needs to be determined anew + scrollLeft: null, + scrollTop: null, + // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, + // Used to scroll to a specific position + focus: false, + id: ++nextOpId, + // Unique ID + markArrays: null, + // Used by addMarkedSpan + }; + pushOperation(cm.curOp); + } + function endOperation(cm) { + var op = cm.curOp; + if (op) { + finishOperation(op, function (group) { + for (var i2 = 0; i2 < group.ops.length; i2++) { + group.ops[i2].cm.curOp = null; + } + endOperations(group); + }); + } + } + function endOperations(group) { + var ops = group.ops; + for (var i2 = 0; i2 < ops.length; i2++) { + endOperation_R1(ops[i2]); + } + for (var i$12 = 0; i$12 < ops.length; i$12++) { + endOperation_W1(ops[i$12]); + } + for (var i$22 = 0; i$22 < ops.length; i$22++) { + endOperation_R2(ops[i$22]); + } + for (var i$3 = 0; i$3 < ops.length; i$3++) { + endOperation_W2(ops[i$3]); + } + for (var i$4 = 0; i$4 < ops.length; i$4++) { + endOperation_finish(ops[i$4]); + } + } + function endOperation_R1(op) { + var cm = op.cm, + display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) { + findMaxLine(cm); + } + op.mustUpdate = + op.viewChanged || + op.forceUpdate || + op.scrollTop != null || + (op.scrollToPos && + (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo)) || + (display.maxLineChanged && cm.options.lineWrapping); + op.update = + op.mustUpdate && + new DisplayUpdate( + cm, + op.mustUpdate && { + top: op.scrollTop, + ensure: op.scrollToPos, + }, + op.forceUpdate + ); + } + function endOperation_W1(op) { + op.updatedDisplay = + op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + function endOperation_R2(op) { + var cm = op.cm, + display = cm.display; + if (op.updatedDisplay) { + updateHeightsInViewport(cm); + } + op.barMeasure = measureForScrollbars(cm); + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = + measureChar( + cm, + display.maxLine, + display.maxLine.text.length + ).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = Math.max( + display.scroller.clientWidth, + display.sizer.offsetLeft + + op.adjustWidthTo + + scrollGap(cm) + + cm.display.barWidth + ); + op.maxScrollLeft = Math.max( + 0, + display.sizer.offsetLeft + + op.adjustWidthTo - + displayWidth(cm) + ); + } + if (op.updatedDisplay || op.selectionChanged) { + op.preparedSelection = display.input.prepareSelection(); + } + } + function endOperation_W2(op) { + var cm = op.cm; + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) { + setScrollLeft( + cm, + Math.min( + cm.display.scroller.scrollLeft, + op.maxScrollLeft + ), + true + ); + } + cm.display.maxLineChanged = false; + } + var takeFocus = op.focus && op.focus == activeElt(); + if (op.preparedSelection) { + cm.display.input.showSelection( + op.preparedSelection, + takeFocus + ); + } + if (op.updatedDisplay || op.startHeight != cm.doc.height) { + updateScrollbars(cm, op.barMeasure); + } + if (op.updatedDisplay) { + setDocumentHeight(cm, op.barMeasure); + } + if (op.selectionChanged) { + restartBlink(cm); + } + if (cm.state.focused && op.updateInput) { + cm.display.input.reset(op.typing); + } + if (takeFocus) { + ensureFocus(op.cm); + } + } + function endOperation_finish(op) { + var cm = op.cm, + display = cm.display, + doc = cm.doc; + if (op.updatedDisplay) { + postUpdateDisplay(cm, op.update); + } + if ( + display.wheelStartX != null && + (op.scrollTop != null || + op.scrollLeft != null || + op.scrollToPos) + ) { + display.wheelStartX = display.wheelStartY = null; + } + if (op.scrollTop != null) { + setScrollTop(cm, op.scrollTop, op.forceScroll); + } + if (op.scrollLeft != null) { + setScrollLeft(cm, op.scrollLeft, true, true); + } + if (op.scrollToPos) { + var rect = scrollPosIntoView( + cm, + clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), + op.scrollToPos.margin + ); + maybeScrollWindow(cm, rect); + } + var hidden = op.maybeHiddenMarkers, + unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i2 = 0; i2 < hidden.length; ++i2) { + if (!hidden[i2].lines.length) { + signal(hidden[i2], "hide"); + } + } + } + if (unhidden) { + for (var i$12 = 0; i$12 < unhidden.length; ++i$12) { + if (unhidden[i$12].lines.length) { + signal(unhidden[i$12], "unhide"); + } + } + } + if (display.wrapper.offsetHeight) { + doc.scrollTop = cm.display.scroller.scrollTop; + } + if (op.changeObjs) { + signal(cm, "changes", cm, op.changeObjs); + } + if (op.update) { + op.update.finish(); + } + } + function runInOp(cm, f) { + if (cm.curOp) { + return f(); + } + startOperation(cm); + try { + return f(); + } finally { + endOperation(cm); + } + } + function operation(cm, f) { + return function () { + if (cm.curOp) { + return f.apply(cm, arguments); + } + startOperation(cm); + try { + return f.apply(cm, arguments); + } finally { + endOperation(cm); + } + }; + } + function methodOp(f) { + return function () { + if (this.curOp) { + return f.apply(this, arguments); + } + startOperation(this); + try { + return f.apply(this, arguments); + } finally { + endOperation(this); + } + }; + } + function docMethodOp(f) { + return function () { + var cm = this.cm; + if (!cm || cm.curOp) { + return f.apply(this, arguments); + } + startOperation(cm); + try { + return f.apply(this, arguments); + } finally { + endOperation(cm); + } + }; + } + function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) { + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } + } + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.highlightFrontier >= cm.display.viewTo) { + return; + } + var end = +(/* @__PURE__ */ new Date()) + cm.options.workTime; + var context = getContextBefore(cm, doc.highlightFrontier); + var changedLines = []; + doc.iter( + context.line, + Math.min(doc.first + doc.size, cm.display.viewTo + 500), + function (line) { + if (context.line >= cm.display.viewFrom) { + var oldStyles = line.styles; + var resetState = + line.text.length > cm.options.maxHighlightLength + ? copyState(doc.mode, context.state) + : null; + var highlighted = highlightLine(cm, line, context, true); + if (resetState) { + context.state = resetState; + } + line.styles = highlighted.styles; + var oldCls = line.styleClasses, + newCls = highlighted.classes; + if (newCls) { + line.styleClasses = newCls; + } else if (oldCls) { + line.styleClasses = null; + } + var ischange = + !oldStyles || + oldStyles.length != line.styles.length || + (oldCls != newCls && + (!oldCls || + !newCls || + oldCls.bgClass != newCls.bgClass || + oldCls.textClass != newCls.textClass)); + for ( + var i2 = 0; + !ischange && i2 < oldStyles.length; + ++i2 + ) { + ischange = oldStyles[i2] != line.styles[i2]; + } + if (ischange) { + changedLines.push(context.line); + } + line.stateAfter = context.save(); + context.nextLine(); + } else { + if (line.text.length <= cm.options.maxHighlightLength) { + processLine(cm, line.text, context); + } + line.stateAfter = + context.line % 5 == 0 ? context.save() : null; + context.nextLine(); + } + if (+(/* @__PURE__ */ new Date()) > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + } + ); + doc.highlightFrontier = context.line; + doc.modeFrontier = Math.max(doc.modeFrontier, context.line); + if (changedLines.length) { + runInOp(cm, function () { + for (var i2 = 0; i2 < changedLines.length; i2++) { + regLineChange(cm, changedLines[i2], "text"); + } + }); + } + } + var DisplayUpdate = function (cm, viewport, force) { + var display = cm.display; + this.viewport = viewport; + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + }; + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) { + this.events.push(arguments); + } + }; + DisplayUpdate.prototype.finish = function () { + for (var i2 = 0; i2 < this.events.length; i2++) { + signal.apply(null, this.events[i2]); + } + }; + function maybeClipScrollbars(cm) { + var display = cm.display; + if ( + !display.scrollbarsClipped && + display.scroller.offsetWidth + ) { + display.nativeBarWidth = + display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = + -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + function selectionSnapshot(cm) { + if (cm.hasFocus()) { + return null; + } + var active = activeElt(); + if (!active || !contains(cm.display.lineDiv, active)) { + return null; + } + var result = { + activeElt: active, + }; + if (window.getSelection) { + var sel = window.getSelection(); + if ( + sel.anchorNode && + sel.extend && + contains(cm.display.lineDiv, sel.anchorNode) + ) { + result.anchorNode = sel.anchorNode; + result.anchorOffset = sel.anchorOffset; + result.focusNode = sel.focusNode; + result.focusOffset = sel.focusOffset; + } + } + return result; + } + function restoreSelection(snapshot) { + if ( + !snapshot || + !snapshot.activeElt || + snapshot.activeElt == activeElt() + ) { + return; + } + snapshot.activeElt.focus(); + if ( + !/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && + snapshot.anchorNode && + contains(document.body, snapshot.anchorNode) && + contains(document.body, snapshot.focusNode) + ) { + var sel = window.getSelection(), + range2 = document.createRange(); + range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset); + range2.collapse(false); + sel.removeAllRanges(); + sel.addRange(range2); + sel.extend(snapshot.focusNode, snapshot.focusOffset); + } + } + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, + doc = cm.doc; + if (update.editorIsHidden) { + resetView(cm); + return false; + } + if ( + !update.force && + update.visible.from >= display.viewFrom && + update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || + display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && + countDirtyView(cm) == 0 + ) { + return false; + } + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + var end = doc.first + doc.size; + var from = Math.max( + update.visible.from - cm.options.viewportMargin, + doc.first + ); + var to = Math.min( + end, + update.visible.to + cm.options.viewportMargin + ); + if (display.viewFrom < from && from - display.viewFrom < 20) { + from = Math.max(doc.first, display.viewFrom); + } + if (display.viewTo > to && display.viewTo - to < 20) { + to = Math.min(end, display.viewTo); + } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + var different = + from != display.viewFrom || + to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || + display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + display.viewOffset = heightAtLine( + getLine(cm.doc, display.viewFrom) + ); + cm.display.mover.style.top = display.viewOffset + "px"; + var toUpdate = countDirtyView(cm); + if ( + !different && + toUpdate == 0 && + !update.force && + display.renderedView == display.view && + (display.updateLineNumbers == null || + display.updateLineNumbers >= display.viewTo) + ) { + return false; + } + var selSnapshot = selectionSnapshot(cm); + if (toUpdate > 4) { + display.lineDiv.style.display = "none"; + } + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) { + display.lineDiv.style.display = ""; + } + display.renderedView = display.view; + restoreSelection(selSnapshot); + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = + display.sizer.style.minHeight = 0; + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + display.updateLineNumbers = null; + return true; + } + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + for (var first = true; ; first = false) { + if ( + !first || + !cm.options.lineWrapping || + update.oldDisplayWidth == displayWidth(cm) + ) { + if (viewport && viewport.top != null) { + viewport = { + top: Math.min( + cm.doc.height + + paddingVert(cm.display) - + displayHeight(cm), + viewport.top + ), + }; + } + update.visible = visibleLines(cm.display, cm.doc, viewport); + if ( + update.visible.from >= cm.display.viewFrom && + update.visible.to <= cm.display.viewTo + ) { + break; + } + } else if (first) { + update.visible = visibleLines(cm.display, cm.doc, viewport); + } + if (!updateDisplayIfNeeded(cm, update)) { + break; + } + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.force = false; + } + update.signal(cm, "update", cm); + if ( + cm.display.viewFrom != cm.display.reportedViewFrom || + cm.display.viewTo != cm.display.reportedViewTo + ) { + update.signal( + cm, + "viewportChange", + cm, + cm.display.viewFrom, + cm.display.viewTo + ); + cm.display.reportedViewFrom = cm.display.viewFrom; + cm.display.reportedViewTo = cm.display.viewTo; + } + } + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, + lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, + cur = container.firstChild; + function rm(node2) { + var next = node2.nextSibling; + if (webkit && mac && cm.display.currentWheelTarget == node2) { + node2.style.display = "none"; + } else { + node2.parentNode.removeChild(node2); + } + return next; + } + var view = display.view, + lineN = display.viewFrom; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (lineView.hidden); + else if ( + !lineView.node || + lineView.node.parentNode != container + ) { + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { + while (cur != lineView.node) { + cur = rm(cur); + } + var updateNumber = + lineNumbers && + updateNumbersFrom != null && + updateNumbersFrom <= lineN && + lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { + updateNumber = false; + } + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild( + document.createTextNode( + lineNumberFor(cm.options, lineN) + ) + ); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) { + cur = rm(cur); + } + } + function updateGutterSpace(display) { + var width = display.gutters.offsetWidth; + display.sizer.style.marginLeft = width + "px"; + signalLater(display, "gutterChanged", display); + } + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = + measure.docHeight + + cm.display.barHeight + + scrollGap(cm) + + "px"; + } + function alignHorizontally(cm) { + var display = cm.display, + view = display.view; + if ( + !display.alignWidgets && + (!display.gutters.firstChild || !cm.options.fixedGutter) + ) { + return; + } + var comp = + compensateForHScroll(display) - + display.scroller.scrollLeft + + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, + left = comp + "px"; + for (var i2 = 0; i2 < view.length; i2++) { + if (!view[i2].hidden) { + if (cm.options.fixedGutter) { + if (view[i2].gutter) { + view[i2].gutter.style.left = left; + } + if (view[i2].gutterBackground) { + view[i2].gutterBackground.style.left = left; + } + } + var align = view[i2].alignable; + if (align) { + for (var j = 0; j < align.length; j++) { + align[j].style.left = left; + } + } + } + } + if (cm.options.fixedGutter) { + display.gutters.style.left = comp + gutterW + "px"; + } + } + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { + return false; + } + var doc = cm.doc, + last = lineNumberFor(cm.options, doc.first + doc.size - 1), + display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild( + elt( + "div", + [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt" + ) + ); + var innerW = test.firstChild.offsetWidth, + padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = + Math.max(innerW, display.lineGutter.offsetWidth - padding) + + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth + ? last.length + : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm.display); + return true; + } + return false; + } + function getGutters(gutters, lineNumbers) { + var result = [], + sawLineNumbers = false; + for (var i2 = 0; i2 < gutters.length; i2++) { + var name = gutters[i2], + style = null; + if (typeof name != "string") { + style = name.style; + name = name.className; + } + if (name == "CodeMirror-linenumbers") { + if (!lineNumbers) { + continue; + } else { + sawLineNumbers = true; + } + } + result.push({ + className: name, + style, + }); + } + if (lineNumbers && !sawLineNumbers) { + result.push({ + className: "CodeMirror-linenumbers", + style: null, + }); + } + return result; + } + function renderGutters(display) { + var gutters = display.gutters, + specs = display.gutterSpecs; + removeChildren(gutters); + display.lineGutter = null; + for (var i2 = 0; i2 < specs.length; ++i2) { + var ref = specs[i2]; + var className = ref.className; + var style = ref.style; + var gElt = gutters.appendChild( + elt("div", null, "CodeMirror-gutter " + className) + ); + if (style) { + gElt.style.cssText = style; + } + if (className == "CodeMirror-linenumbers") { + display.lineGutter = gElt; + gElt.style.width = (display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = specs.length ? "" : "none"; + updateGutterSpace(display); + } + function updateGutters(cm) { + renderGutters(cm.display); + regChange(cm); + alignHorizontally(cm); + } + function Display(place, doc, input, options) { + var d = this; + this.input = input; + d.scrollbarFiller = elt( + "div", + null, + "CodeMirror-scrollbar-filler" + ); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + d.lineDiv = eltP("div", null, "CodeMirror-code"); + d.selectionDiv = elt( + "div", + null, + null, + "position: relative; z-index: 1" + ); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + d.measure = elt("div", null, "CodeMirror-measure"); + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + d.lineSpace = eltP( + "div", + [ + d.measure, + d.lineMeasure, + d.selectionDiv, + d.cursorDiv, + d.lineDiv, + ], + null, + "position: relative; outline: none" + ); + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); + d.mover = elt("div", [lines], null, "position: relative"); + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + d.heightForcer = elt( + "div", + null, + null, + "position: absolute; height: " + + scrollerGap + + "px; width: 1px;" + ); + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + d.scroller = elt( + "div", + [d.sizer, d.heightForcer, d.gutters], + "CodeMirror-scroll" + ); + d.scroller.setAttribute("tabIndex", "-1"); + d.wrapper = elt( + "div", + [d.scrollbarFiller, d.gutterFiller, d.scroller], + "CodeMirror" + ); + d.wrapper.setAttribute("translate", "no"); + if (ie && ie_version < 8) { + d.gutters.style.zIndex = -1; + d.scroller.style.paddingRight = 0; + } + if (!webkit && !(gecko && mobile)) { + d.scroller.draggable = true; + } + if (place) { + if (place.appendChild) { + place.appendChild(d.wrapper); + } else { + place(d.wrapper); + } + } + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + d.view = []; + d.renderedView = null; + d.externalMeasured = null; + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + d.alignWidgets = false; + d.cachedCharWidth = + d.cachedTextHeight = + d.cachedPaddingH = + null; + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + d.shift = false; + d.selForContextMenu = null; + d.activeTouch = null; + d.gutterSpecs = getGutters( + options.gutters, + options.lineNumbers + ); + renderGutters(d); + input.init(d); + } + var wheelSamples = 0, + wheelPixelsPerUnit = null; + if (ie) { + wheelPixelsPerUnit = -0.53; + } else if (gecko) { + wheelPixelsPerUnit = 15; + } else if (chrome) { + wheelPixelsPerUnit = -0.7; + } else if (safari) { + wheelPixelsPerUnit = -1 / 3; + } + function wheelEventDelta(e) { + var dx = e.wheelDeltaX, + dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { + dx = e.detail; + } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { + dy = e.detail; + } else if (dy == null) { + dy = e.wheelDelta; + } + return { + x: dx, + y: dy, + }; + } + function wheelEventPixels(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + } + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), + dx = delta.x, + dy = delta.y; + var pixelsPerUnit = wheelPixelsPerUnit; + if (e.deltaMode === 0) { + dx = e.deltaX; + dy = e.deltaY; + pixelsPerUnit = 1; + } + var display = cm.display, + scroll = display.scroller; + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!((dx && canScrollX) || (dy && canScrollY))) { + return; + } + if (dy && mac && webkit) { + outer: for ( + var cur = e.target, view = display.view; + cur != scroll; + cur = cur.parentNode + ) { + for (var i2 = 0; i2 < view.length; i2++) { + if (view[i2].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + if (dx && !gecko && !presto && pixelsPerUnit != null) { + if (dy && canScrollY) { + updateScrollTop( + cm, + Math.max(0, scroll.scrollTop + dy * pixelsPerUnit) + ); + } + setScrollLeft( + cm, + Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit) + ); + if (!dy || (dy && canScrollY)) { + e_preventDefault(e); + } + display.wheelStartX = null; + return; + } + if (dy && pixelsPerUnit != null) { + var pixels = dy * pixelsPerUnit; + var top = cm.doc.scrollTop, + bot = top + display.wrapper.clientHeight; + if (pixels < 0) { + top = Math.max(0, top + pixels - 50); + } else { + bot = Math.min(cm.doc.height, bot + pixels + 50); + } + updateDisplaySimple(cm, { + top, + bottom: bot, + }); + } + if (wheelSamples < 20 && e.deltaMode !== 0) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; + display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; + display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) { + return; + } + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = + (movedY && + display.wheelDY && + movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) { + return; + } + wheelPixelsPerUnit = + (wheelPixelsPerUnit * wheelSamples + sample) / + (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; + display.wheelDY += dy; + } + } + } + var Selection = function (ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + }; + Selection.prototype.primary = function () { + return this.ranges[this.primIndex]; + }; + Selection.prototype.equals = function (other) { + if (other == this) { + return true; + } + if ( + other.primIndex != this.primIndex || + other.ranges.length != this.ranges.length + ) { + return false; + } + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var here = this.ranges[i2], + there = other.ranges[i2]; + if ( + !equalCursorPos(here.anchor, there.anchor) || + !equalCursorPos(here.head, there.head) + ) { + return false; + } + } + return true; + }; + Selection.prototype.deepCopy = function () { + var out = []; + for (var i2 = 0; i2 < this.ranges.length; i2++) { + out[i2] = new Range( + copyPos(this.ranges[i2].anchor), + copyPos(this.ranges[i2].head) + ); + } + return new Selection(out, this.primIndex); + }; + Selection.prototype.somethingSelected = function () { + for (var i2 = 0; i2 < this.ranges.length; i2++) { + if (!this.ranges[i2].empty()) { + return true; + } + } + return false; + }; + Selection.prototype.contains = function (pos, end) { + if (!end) { + end = pos; + } + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var range2 = this.ranges[i2]; + if ( + cmp(end, range2.from()) >= 0 && + cmp(pos, range2.to()) <= 0 + ) { + return i2; + } + } + return -1; + }; + var Range = function (anchor, head) { + this.anchor = anchor; + this.head = head; + }; + Range.prototype.from = function () { + return minPos(this.anchor, this.head); + }; + Range.prototype.to = function () { + return maxPos(this.anchor, this.head); + }; + Range.prototype.empty = function () { + return ( + this.head.line == this.anchor.line && + this.head.ch == this.anchor.ch + ); + }; + function normalizeSelection(cm, ranges, primIndex) { + var mayTouch = cm && cm.options.selectionsMayTouch; + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { + return cmp(a.from(), b.from()); + }); + primIndex = indexOf(ranges, prim); + for (var i2 = 1; i2 < ranges.length; i2++) { + var cur = ranges[i2], + prev = ranges[i2 - 1]; + var diff = cmp(prev.to(), cur.from()); + if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { + var from = minPos(prev.from(), cur.from()), + to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() + ? cur.from() == cur.head + : prev.from() == prev.head; + if (i2 <= primIndex) { + --primIndex; + } + ranges.splice( + --i2, + 2, + new Range(inv ? to : from, inv ? from : to) + ); + } + } + return new Selection(ranges, primIndex); + } + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + function changeEnd(change) { + if (!change.text) { + return change.to; + } + return Pos( + change.from.line + change.text.length - 1, + lst(change.text).length + + (change.text.length == 1 ? change.from.ch : 0) + ); + } + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { + return pos; + } + if (cmp(pos, change.to) <= 0) { + return changeEnd(change); + } + var line = + pos.line + + change.text.length - + (change.to.line - change.from.line) - + 1, + ch = pos.ch; + if (pos.line == change.to.line) { + ch += changeEnd(change).ch - change.to.ch; + } + return Pos(line, ch); + } + function computeSelAfterChange(doc, change) { + var out = []; + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + var range2 = doc.sel.ranges[i2]; + out.push( + new Range( + adjustForChange(range2.anchor, change), + adjustForChange(range2.head, change) + ) + ); + } + return normalizeSelection(doc.cm, out, doc.sel.primIndex); + } + function offsetPos(pos, old, nw) { + if (pos.line == old.line) { + return Pos(nw.line, pos.ch - old.ch + nw.ch); + } else { + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + } + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), + newPrev = oldPrev; + for (var i2 = 0; i2 < changes.length; i2++) { + var change = changes[i2]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range2 = doc.sel.ranges[i2], + inv = cmp(range2.head, range2.anchor) < 0; + out[i2] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i2] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + }); + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) { + regChange(cm); + } + } + function isWholeLineUpdate(doc, change) { + return ( + change.from.ch == 0 && + change.to.ch == 0 && + lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) + ); + } + function updateDoc(doc, change, markedSpans, estimateHeight2) { + function spansFor(n) { + return markedSpans ? markedSpans[n] : null; + } + function update(line, text2, spans) { + updateLine(line, text2, spans, estimateHeight2); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + var result = []; + for (var i2 = start; i2 < end; ++i2) { + result.push( + new Line(text[i2], spansFor(i2), estimateHeight2) + ); + } + return result; + } + var from = change.from, + to = change.to, + text = change.text; + var firstLine = getLine(doc, from.line), + lastLine = getLine(doc, to.line); + var lastText = lst(text), + lastSpans = spansFor(text.length - 1), + nlines = to.line - from.line; + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) { + doc.remove(from.line, nlines); + } + if (added.length) { + doc.insert(from.line, added); + } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update( + firstLine, + firstLine.text.slice(0, from.ch) + + lastText + + firstLine.text.slice(to.ch), + lastSpans + ); + } else { + var added$1 = linesFor(1, text.length - 1); + added$1.push( + new Line( + lastText + firstLine.text.slice(to.ch), + lastSpans, + estimateHeight2 + ) + ); + update( + firstLine, + firstLine.text.slice(0, from.ch) + text[0], + spansFor(0) + ); + doc.insert(from.line + 1, added$1); + } + } else if (text.length == 1) { + update( + firstLine, + firstLine.text.slice(0, from.ch) + + text[0] + + lastLine.text.slice(to.ch), + spansFor(0) + ); + doc.remove(from.line + 1, nlines); + } else { + update( + firstLine, + firstLine.text.slice(0, from.ch) + text[0], + spansFor(0) + ); + update( + lastLine, + lastText + lastLine.text.slice(to.ch), + lastSpans + ); + var added$2 = linesFor(1, text.length - 1); + if (nlines > 1) { + doc.remove(from.line + 1, nlines - 1); + } + doc.insert(from.line + 1, added$2); + } + signalLater(doc, "change", doc, change); + } + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc2, skip, sharedHist) { + if (doc2.linked) { + for (var i2 = 0; i2 < doc2.linked.length; ++i2) { + var rel = doc2.linked[i2]; + if (rel.doc == skip) { + continue; + } + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) { + continue; + } + f(rel.doc, shared); + propagate(rel.doc, doc2, shared); + } + } + } + propagate(doc, null, true); + } + function attachDoc(cm, doc) { + if (doc.cm) { + throw new Error("This document is already in use."); + } + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + setDirectionClass(cm); + cm.options.direction = doc.direction; + if (!cm.options.lineWrapping) { + findMaxLine(cm); + } + cm.options.mode = doc.modeOption; + regChange(cm); + } + function setDirectionClass(cm) { + (cm.doc.direction == "rtl" + ? addClass + : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); + } + function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm); + regChange(cm); + }); + } + function History(prev) { + this.done = []; + this.undone = []; + this.undoDepth = prev ? prev.undoDepth : Infinity; + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + this.generation = this.maxGeneration = prev + ? prev.maxGeneration + : 1; + } + function historyChangeFromChange(doc, change) { + var histChange = { + from: copyPos(change.from), + to: changeEnd(change), + text: getBetween(doc, change.from, change.to), + }; + attachLocalSpans( + doc, + histChange, + change.from.line, + change.to.line + 1 + ); + linkedDocs( + doc, + function (doc2) { + return attachLocalSpans( + doc2, + histChange, + change.from.line, + change.to.line + 1 + ); + }, + true + ); + return histChange; + } + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) { + array.pop(); + } else { + break; + } + } + } + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if ( + hist.done.length > 1 && + !hist.done[hist.done.length - 2].ranges + ) { + hist.done.pop(); + return lst(hist.done); + } + } + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +(/* @__PURE__ */ new Date()), + cur; + var last; + if ( + (hist.lastOp == opId || + (hist.lastOrigin == change.origin && + change.origin && + ((change.origin.charAt(0) == "+" && + hist.lastModTime > + time - + (doc.cm + ? doc.cm.options.historyEventDelay + : 500)) || + change.origin.charAt(0) == "*"))) && + (cur = lastChangeEvent(hist, hist.lastOp == opId)) + ) { + last = lst(cur.changes); + if ( + cmp(change.from, change.to) == 0 && + cmp(change.from, last.to) == 0 + ) { + last.to = changeEnd(change); + } else { + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + var before = lst(hist.done); + if (!before || !before.ranges) { + pushSelectionToHistory(doc.sel, hist.done); + } + cur = { + changes: [historyChangeFromChange(doc, change)], + generation: hist.generation, + }; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) { + hist.done.shift(); + } + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + if (!last) { + signal(doc, "historyAdded"); + } + } + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ( + ch == "*" || + (ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + /* @__PURE__ */ new Date() - doc.history.lastSelTime <= + (doc.cm ? doc.cm.options.historyEventDelay : 500)) + ); + } + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, + origin = options && options.origin; + if ( + opId == hist.lastSelOp || + (origin && + hist.lastSelOrigin == origin && + ((hist.lastModTime == hist.lastSelTime && + hist.lastOrigin == origin) || + selectionEventCanBeMerged( + doc, + origin, + lst(hist.done), + sel + ))) + ) { + hist.done[hist.done.length - 1] = sel; + } else { + pushSelectionToHistory(sel, hist.done); + } + hist.lastSelTime = +(/* @__PURE__ */ new Date()); + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) { + clearSelectionEvents(hist.undone); + } + } + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) { + dest.push(sel); + } + } + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], + n = 0; + doc.iter( + Math.max(doc.first, from), + Math.min(doc.first + doc.size, to), + function (line) { + if (line.markedSpans) { + (existing || (existing = change["spans_" + doc.id] = {}))[ + n + ] = line.markedSpans; + } + ++n; + } + ); + } + function removeClearedSpans(spans) { + if (!spans) { + return null; + } + var out; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2].marker.explicitlyCleared) { + if (!out) { + out = spans.slice(0, i2); + } + } else if (out) { + out.push(spans[i2]); + } + } + return !out ? spans : out.length ? out : null; + } + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) { + return null; + } + var nw = []; + for (var i2 = 0; i2 < change.text.length; ++i2) { + nw.push(removeClearedSpans(found[i2])); + } + return nw; + } + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) { + return stretched; + } + if (!stretched) { + return old; + } + for (var i2 = 0; i2 < old.length; ++i2) { + var oldCur = old[i2], + stretchCur = stretched[i2]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) { + if (oldCur[k].marker == span.marker) { + continue spans; + } + } + oldCur.push(span); + } + } else if (stretchCur) { + old[i2] = stretchCur; + } + } + return old; + } + function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = []; + for (var i2 = 0; i2 < events.length; ++i2) { + var event = events[i2]; + if (event.ranges) { + copy.push( + instantiateSel + ? Selection.prototype.deepCopy.call(event) + : event + ); + continue; + } + var changes = event.changes, + newChanges = []; + copy.push({ + changes: newChanges, + }); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], + m = void 0; + newChanges.push({ + from: change.from, + to: change.to, + text: change.text, + }); + if (newGroup) { + for (var prop2 in change) { + if ((m = prop2.match(/^spans_(\d+)$/))) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop2] = change[prop2]; + delete change[prop2]; + } + } + } + } + } + } + return copy; + } + function extendRange(range2, head, other, extend) { + if (extend) { + var anchor = range2.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != cmp(other, anchor) < 0) { + anchor = head; + head = other; + } else if (posBefore != cmp(head, other) < 0) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); + } + } + function extendSelection(doc, head, other, options, extend) { + if (extend == null) { + extend = doc.cm && (doc.cm.display.shift || doc.extend); + } + setSelection( + doc, + new Selection( + [extendRange(doc.sel.primary(), head, other, extend)], + 0 + ), + options + ); + } + function extendSelections(doc, heads, options) { + var out = []; + var extend = doc.cm && (doc.cm.display.shift || doc.extend); + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + out[i2] = extendRange( + doc.sel.ranges[i2], + heads[i2], + null, + extend + ); + } + var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + function replaceOneSelection(doc, i2, range2, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i2] = range2; + setSelection( + doc, + normalizeSelection(doc.cm, ranges, doc.sel.primIndex), + options + ); + } + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function (ranges) { + this.ranges = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + this.ranges[i2] = new Range( + clipPos(doc, ranges[i2].anchor), + clipPos(doc, ranges[i2].head) + ); + } + }, + origin: options && options.origin, + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) { + signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + } + if (obj.ranges != sel.ranges) { + return normalizeSelection( + doc.cm, + obj.ranges, + obj.ranges.length - 1 + ); + } else { + return sel; + } + } + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, + last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory( + doc, + doc.sel, + doc.cm ? doc.cm.curOp.id : NaN, + options + ); + } + function setSelectionNoUndo(doc, sel, options) { + if ( + hasHandler(doc, "beforeSelectionChange") || + (doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + ) { + sel = filterSelectionChange(doc, sel, options); + } + var bias = + (options && options.bias) || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 + ? -1 + : 1); + setSelectionInner( + doc, + skipAtomicInSelection(doc, sel, bias, true) + ); + if ( + !(options && options.scroll === false) && + doc.cm && + doc.cm.getOption("readOnly") != "nocursor" + ) { + ensureCursorVisible(doc.cm); + } + } + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { + return; + } + doc.sel = sel; + if (doc.cm) { + doc.cm.curOp.updateInput = 1; + doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + function reCheckSelection(doc) { + setSelectionInner( + doc, + skipAtomicInSelection(doc, doc.sel, null, false) + ); + } + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + var old = + sel.ranges.length == doc.sel.ranges.length && + doc.sel.ranges[i2]; + var newAnchor = skipAtomic( + doc, + range2.anchor, + old && old.anchor, + bias, + mayClear + ); + var newHead = skipAtomic( + doc, + range2.head, + old && old.head, + bias, + mayClear + ); + if ( + out || + newAnchor != range2.anchor || + newHead != range2.head + ) { + if (!out) { + out = sel.ranges.slice(0, i2); + } + out[i2] = new Range(newAnchor, newHead); + } + } + return out + ? normalizeSelection(doc.cm, out, sel.primIndex) + : sel; + } + function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line); + if (line.markedSpans) { + for (var i2 = 0; i2 < line.markedSpans.length; ++i2) { + var sp = line.markedSpans[i2], + m = sp.marker; + var preventCursorLeft = + "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; + var preventCursorRight = + "selectRight" in m ? !m.selectRight : m.inclusiveRight; + if ( + (sp.from == null || + (preventCursorLeft + ? sp.from <= pos.ch + : sp.from < pos.ch)) && + (sp.to == null || + (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch)) + ) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) { + break; + } else { + --i2; + continue; + } + } + } + if (!m.atomic) { + continue; + } + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), + diff = void 0; + if (dir < 0 ? preventCursorRight : preventCursorLeft) { + near = movePos( + doc, + near, + -dir, + near && near.line == pos.line ? line : null + ); + } + if ( + near && + near.line == pos.line && + (diff = cmp(near, oldPos)) && + (dir < 0 ? diff < 0 : diff > 0) + ) { + return skipAtomicInner(doc, near, pos, dir, mayClear); + } + } + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? preventCursorLeft : preventCursorRight) { + far = movePos( + doc, + far, + dir, + far.line == pos.line ? line : null + ); + } + return far + ? skipAtomicInner(doc, far, pos, dir, mayClear) + : null; + } + } + } + return pos; + } + function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = + skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); + if (!found) { + doc.cantEdit = true; + return Pos(doc.first, 0); + } + return found; + } + function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { + return clipPos(doc, Pos(pos.line - 1)); + } else { + return null; + } + } else if ( + dir > 0 && + pos.ch == (line || getLine(doc, pos.line)).text.length + ) { + if (pos.line < doc.first + doc.size - 1) { + return Pos(pos.line + 1, 0); + } else { + return null; + } + } else { + return new Pos(pos.line, pos.ch + dir); + } + } + function selectAll(cm) { + cm.setSelection( + Pos(cm.firstLine(), 0), + Pos(cm.lastLine()), + sel_dontScroll + ); + } + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { + return (obj.canceled = true); + }, + }; + if (update) { + obj.update = function (from, to, text, origin) { + if (from) { + obj.from = clipPos(doc, from); + } + if (to) { + obj.to = clipPos(doc, to); + } + if (text) { + obj.text = text; + } + if (origin !== void 0) { + obj.origin = origin; + } + }; + } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) { + signal(doc.cm, "beforeChange", doc.cm, obj); + } + if (obj.canceled) { + if (doc.cm) { + doc.cm.curOp.updateInput = 2; + } + return null; + } + return { + from: obj.from, + to: obj.to, + text: obj.text, + origin: obj.origin, + }; + } + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { + return operation(doc.cm, makeChange)( + doc, + change, + ignoreReadOnly + ); + } + if (doc.cm.state.suppressEdits) { + return; + } + } + if ( + hasHandler(doc, "beforeChange") || + (doc.cm && hasHandler(doc.cm, "beforeChange")) + ) { + change = filterChange(doc, change, true); + if (!change) { + return; + } + } + var split = + sawReadOnlySpans && + !ignoreReadOnly && + removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i2 = split.length - 1; i2 >= 0; --i2) { + makeChangeInner(doc, { + from: split[i2].from, + to: split[i2].to, + text: i2 ? [""] : change.text, + origin: change.origin, + }); + } + } else { + makeChangeInner(doc, change); + } + } + function makeChangeInner(doc, change) { + if ( + change.text.length == 1 && + change.text[0] == "" && + cmp(change.from, change.to) == 0 + ) { + return; + } + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory( + doc, + change, + selAfter, + doc.cm ? doc.cm.curOp.id : NaN + ); + makeChangeSingleDoc( + doc, + change, + selAfter, + stretchSpansOverChange(doc, change) + ); + var rebased = []; + linkedDocs(doc, function (doc2, sharedHist) { + if (!sharedHist && indexOf(rebased, doc2.history) == -1) { + rebaseHist(doc2.history, change); + rebased.push(doc2.history); + } + makeChangeSingleDoc( + doc2, + change, + null, + stretchSpansOverChange(doc2, change) + ); + }); + } + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + var suppress = doc.cm && doc.cm.state.suppressEdits; + if (suppress && !allowSelectionOnly) { + return; + } + var hist = doc.history, + event, + selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, + dest = type == "undo" ? hist.undone : hist.done; + var i2 = 0; + for (; i2 < source.length; i2++) { + event = source[i2]; + if ( + allowSelectionOnly + ? event.ranges && !event.equals(doc.sel) + : !event.ranges + ) { + break; + } + } + if (i2 == source.length) { + return; + } + hist.lastOrigin = hist.lastSelOrigin = null; + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, { + clearRedo: false, + }); + return; + } + selAfter = event; + } else if (suppress) { + source.push(event); + return; + } else { + break; + } + } + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({ + changes: antiChanges, + generation: hist.generation, + }); + hist.generation = event.generation || ++hist.maxGeneration; + var filter = + hasHandler(doc, "beforeChange") || + (doc.cm && hasHandler(doc.cm, "beforeChange")); + var loop = function (i3) { + var change = event.changes[i3]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return {}; + } + antiChanges.push(historyChangeFromChange(doc, change)); + var after = i3 + ? computeSelAfterChange(doc, change) + : lst(source); + makeChangeSingleDoc( + doc, + change, + after, + mergeOldSpans(doc, change) + ); + if (!i3 && doc.cm) { + doc.cm.scrollIntoView({ + from: change.from, + to: changeEnd(change), + }); + } + var rebased = []; + linkedDocs(doc, function (doc2, sharedHist) { + if (!sharedHist && indexOf(rebased, doc2.history) == -1) { + rebaseHist(doc2.history, change); + rebased.push(doc2.history); + } + makeChangeSingleDoc( + doc2, + change, + null, + mergeOldSpans(doc2, change) + ); + }); + }; + for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) { + var returned = loop(i$12); + if (returned) return returned.v; + } + } + function shiftDoc(doc, distance) { + if (distance == 0) { + return; + } + doc.first += distance; + doc.sel = new Selection( + map(doc.sel.ranges, function (range2) { + return new Range( + Pos(range2.anchor.line + distance, range2.anchor.ch), + Pos(range2.head.line + distance, range2.head.ch) + ); + }), + doc.sel.primIndex + ); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for ( + var d = doc.cm.display, l = d.viewFrom; + l < d.viewTo; + l++ + ) { + regLineChange(doc.cm, l, "gutter"); + } + } + } + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) { + return operation(doc.cm, makeChangeSingleDoc)( + doc, + change, + selAfter, + spans + ); + } + if (change.to.line < doc.first) { + shiftDoc( + doc, + change.text.length - 1 - (change.to.line - change.from.line) + ); + return; + } + if (change.from.line > doc.lastLine()) { + return; + } + if (change.from.line < doc.first) { + var shift = + change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = { + from: Pos(doc.first, 0), + to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], + origin: change.origin, + }; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = { + from: change.from, + to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], + origin: change.origin, + }; + } + change.removed = getBetween(doc, change.from, change.to); + if (!selAfter) { + selAfter = computeSelAfterChange(doc, change); + } + if (doc.cm) { + makeChangeSingleDocInEditor(doc.cm, change, spans); + } else { + updateDoc(doc, change, spans); + } + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { + doc.cantEdit = false; + } + } + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, + display = cm.display, + from = change.from, + to = change.to; + var recomputeMaxLength = false, + checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + if (doc.sel.contains(change.from, change.to) > -1) { + signalCursorActivity(cm); + } + updateDoc(doc, change, spans, estimateHeight(cm)); + if (!cm.options.lineWrapping) { + doc.iter( + checkWidthStart, + from.line + change.text.length, + function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + } + ); + if (recomputeMaxLength) { + cm.curOp.updateMaxLine = true; + } + } + retreatFrontier(doc, from.line); + startWorker(cm, 400); + var lendiff = change.text.length - (to.line - from.line) - 1; + if (change.full) { + regChange(cm); + } else if ( + from.line == to.line && + change.text.length == 1 && + !isWholeLineUpdate(cm.doc, change) + ) { + regLineChange(cm, from.line, "text"); + } else { + regChange(cm, from.line, to.line + 1, lendiff); + } + var changesHandler = hasHandler(cm, "changes"), + changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from, + to, + text: change.text, + removed: change.removed, + origin: change.origin, + }; + if (changeHandler) { + signalLater(cm, "change", cm, obj); + } + if (changesHandler) { + (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push( + obj + ); + } + } + cm.display.selForContextMenu = null; + } + function replaceRange(doc, code, from, to, origin) { + var assign; + if (!to) { + to = from; + } + if (cmp(to, from) < 0) { + (assign = [to, from]), (from = assign[0]), (to = assign[1]); + } + if (typeof code == "string") { + code = doc.splitLines(code); + } + makeChange(doc, { + from, + to, + text: code, + origin, + }); + } + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + function rebaseHistArray(array, from, to, diff) { + for (var i2 = 0; i2 < array.length; ++i2) { + var sub = array[i2], + ok = true; + if (sub.ranges) { + if (!sub.copied) { + sub = array[i2] = sub.deepCopy(); + sub.copied = true; + } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i2 + 1); + i2 = 0; + } + } + } + function rebaseHist(hist, change) { + var from = change.from.line, + to = change.to.line, + diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + function changeLine(doc, handle, changeType, op) { + var no = handle, + line = handle; + if (typeof handle == "number") { + line = getLine(doc, clipLine(doc, handle)); + } else { + no = lineNo(handle); + } + if (no == null) { + return null; + } + if (op(line, no) && doc.cm) { + regLineChange(doc.cm, no, changeType); + } + return line; + } + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; + height += lines[i2].height; + } + this.height = height; + } + LeafChunk.prototype = { + chunkSize: function () { + return this.lines.length; + }, + // Remove the n lines at offset 'at'. + removeInner: function (at, n) { + for (var i2 = at, e = at + n; i2 < e; ++i2) { + var line = this.lines[i2]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function (lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function (at, lines, height) { + this.height += height; + this.lines = this.lines + .slice(0, at) + .concat(lines) + .concat(this.lines.slice(at)); + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; + } + }, + // Used to iterate over a part of the tree. + iterN: function (at, n, op) { + for (var e = at + n; at < e; ++at) { + if (op(this.lines[at])) { + return true; + } + } + }, + }; + function BranchChunk(children) { + this.children = children; + var size = 0, + height = 0; + for (var i2 = 0; i2 < children.length; ++i2) { + var ch = children[i2]; + size += ch.chunkSize(); + height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + BranchChunk.prototype = { + chunkSize: function () { + return this.size; + }, + removeInner: function (at, n) { + this.size -= n; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), + oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { + this.children.splice(i2--, 1); + child.parent = null; + } + if ((n -= rm) == 0) { + break; + } + at = 0; + } else { + at -= sz; + } + } + if ( + this.size - n < 25 && + (this.children.length > 1 || + !(this.children[0] instanceof LeafChunk)) + ) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function (lines) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + this.children[i2].collapse(lines); + } + }, + insertInner: function (at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + var remaining = (child.lines.length % 25) + 25; + for (var pos = remaining; pos < child.lines.length; ) { + var leaf = new LeafChunk( + child.lines.slice(pos, (pos += 25)) + ); + child.height -= leaf.height; + this.children.splice(++i2, 0, leaf); + leaf.parent = this; + } + child.lines = child.lines.slice(0, remaining); + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function () { + if (this.children.length <= 10) { + return; + } + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function (at, n, op) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) { + return true; + } + if ((n -= used) == 0) { + break; + } + at = 0; + } else { + at -= sz; + } + } + }, + }; + var LineWidget = function (doc, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) { + this[opt] = options[opt]; + } + } + } + this.doc = doc; + this.node = node; + }; + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, + ws = this.line.widgets, + line = this.line, + no = lineNo(line); + if (no == null || !ws) { + return; + } + for (var i2 = 0; i2 < ws.length; ++i2) { + if (ws[i2] == this) { + ws.splice(i2--, 1); + } + } + if (!ws.length) { + line.widgets = null; + } + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + signalLater(cm, "lineWidgetCleared", cm, this, no); + } + }; + LineWidget.prototype.changed = function () { + var this$1$1 = this; + var oldH = this.height, + cm = this.doc.cm, + line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) { + return; + } + if (!lineIsHidden(this.doc, line)) { + updateLineHeight(line, line.height + diff); + } + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + signalLater( + cm, + "lineWidgetChanged", + cm, + this$1$1, + lineNo(line) + ); + }); + } + }; + eventMixin(LineWidget); + function adjustScrollWhenAboveVisible(cm, line, diff) { + if ( + heightAtLine(line) < + ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop) + ) { + addToScrollTop(cm, diff); + } + } + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) { + cm.display.alignWidgets = true; + } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) { + widgets.push(widget); + } else { + widgets.splice( + Math.min(widgets.length, Math.max(0, widget.insertAt)), + 0, + widget + ); + } + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) { + addToScrollTop(cm, widget.height); + } + cm.curOp.forceUpdate = true; + } + return true; + }); + if (cm) { + signalLater( + cm, + "lineWidgetAdded", + cm, + widget, + typeof handle == "number" ? handle : lineNo(handle) + ); + } + return widget; + } + var nextMarkerId = 0; + var TextMarker = function (doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { + return; + } + var cm = this.doc.cm, + withOp = cm && !cm.curOp; + if (withOp) { + startOperation(cm); + } + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) { + signalLater(this, "clear", found.from, found.to); + } + } + var min = null, + max = null; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) { + regLineChange(cm, lineNo(line), "text"); + } else if (cm) { + if (span.to != null) { + max = lineNo(line); + } + if (span.from != null) { + min = lineNo(line); + } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if ( + span.from == null && + this.collapsed && + !lineIsHidden(this.doc, line) && + cm + ) { + updateLineHeight(line, textHeight(cm.display)); + } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i$12 = 0; i$12 < this.lines.length; ++i$12) { + var visual = visualLine(this.lines[i$12]), + len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + } + if (min != null && cm && this.collapsed) { + regChange(cm, min, max + 1); + } + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) { + reCheckSelection(cm.doc); + } + } + if (cm) { + signalLater(cm, "markerCleared", cm, this, min, max); + } + if (withOp) { + endOperation(cm); + } + if (this.parent) { + this.parent.clear(); + } + }; + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") { + side = 1; + } + var from, to; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) { + return from; + } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) { + return to; + } + } + } + return ( + from && { + from, + to, + } + ); + }; + TextMarker.prototype.changed = function () { + var this$1$1 = this; + var pos = this.find(-1, true), + widget = this, + cm = this.doc.cm; + if (!pos || !cm) { + return; + } + runInOp(cm, function () { + var line = pos.line, + lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if ( + !lineIsHidden(widget.doc, line) && + widget.height != null + ) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) { + updateLineHeight(line, line.height + dHeight); + } + } + signalLater(cm, "markerChanged", cm, this$1$1); + }); + }; + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if ( + !op.maybeHiddenMarkers || + indexOf(op.maybeHiddenMarkers, this) == -1 + ) { + ( + op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = []) + ).push(this); + } + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push( + this + ); + } + }; + eventMixin(TextMarker); + function markText(doc, from, to, options, type) { + if (options && options.shared) { + return markTextShared(doc, from, to, options, type); + } + if (doc.cm && !doc.cm.curOp) { + return operation(doc.cm, markText)( + doc, + from, + to, + options, + type + ); + } + var marker = new TextMarker(doc, type), + diff = cmp(from, to); + if (options) { + copyObj(options, marker, false); + } + if ( + diff > 0 || + (diff == 0 && marker.clearWhenEmpty !== false) + ) { + return marker; + } + if (marker.replacedWith) { + marker.collapsed = true; + marker.widgetNode = eltP( + "span", + [marker.replacedWith], + "CodeMirror-widget" + ); + if (!options.handleMouseEvents) { + marker.widgetNode.setAttribute("cm-ignore-events", "true"); + } + if (options.insertLeft) { + marker.widgetNode.insertLeft = true; + } + } + if (marker.collapsed) { + if ( + conflictingCollapsedRange( + doc, + from.line, + from, + to, + marker + ) || + (from.line != to.line && + conflictingCollapsedRange(doc, to.line, from, to, marker)) + ) { + throw new Error( + "Inserting collapsed marker partially overlapping an existing one" + ); + } + seeCollapsedSpans(); + } + if (marker.addToHistory) { + addChangeToHistory( + doc, + { + from, + to, + origin: "markText", + }, + doc.sel, + NaN + ); + } + var curLine = from.line, + cm = doc.cm, + updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if ( + cm && + marker.collapsed && + !cm.options.lineWrapping && + visualLine(line) == cm.display.maxLine + ) { + updateMaxLine = true; + } + if (marker.collapsed && curLine != from.line) { + updateLineHeight(line, 0); + } + addMarkedSpan( + line, + new MarkedSpan( + marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null + ), + doc.cm && doc.cm.curOp + ); + ++curLine; + }); + if (marker.collapsed) { + doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { + updateLineHeight(line, 0); + } + }); + } + if (marker.clearOnEnter) { + on(marker, "beforeCursorEnter", function () { + return marker.clear(); + }); + } + if (marker.readOnly) { + seeReadOnlySpans(); + if (doc.history.done.length || doc.history.undone.length) { + doc.clearHistory(); + } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + if (updateMaxLine) { + cm.curOp.updateMaxLine = true; + } + if (marker.collapsed) { + regChange(cm, from.line, to.line + 1); + } else if ( + marker.className || + marker.startStyle || + marker.endStyle || + marker.css || + marker.attributes || + marker.title + ) { + for (var i2 = from.line; i2 <= to.line; i2++) { + regLineChange(cm, i2, "text"); + } + } + if (marker.atomic) { + reCheckSelection(cm.doc); + } + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + var SharedTextMarker = function (markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i2 = 0; i2 < markers.length; ++i2) { + markers[i2].parent = this; + } + }; + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { + return; + } + this.explicitlyCleared = true; + for (var i2 = 0; i2 < this.markers.length; ++i2) { + this.markers[i2].clear(); + } + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj); + }; + eventMixin(SharedTextMarker); + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], + primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc2) { + if (widget) { + options.widgetNode = widget.cloneNode(true); + } + markers.push( + markText( + doc2, + clipPos(doc2, from), + clipPos(doc2, to), + options, + type + ) + ); + for (var i2 = 0; i2 < doc2.linked.length; ++i2) { + if (doc2.linked[i2].isParent) { + return; + } + } + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + function findSharedMarkers(doc) { + return doc.findMarks( + Pos(doc.first, 0), + doc.clipPos(Pos(doc.lastLine())), + function (m) { + return m.parent; + } + ); + } + function copySharedMarkers(doc, markers) { + for (var i2 = 0; i2 < markers.length; i2++) { + var marker = markers[i2], + pos = marker.find(); + var mFrom = doc.clipPos(pos.from), + mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText( + doc, + mFrom, + mTo, + marker.primary, + marker.primary.type + ); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + function detachSharedMarkers(markers) { + var loop = function (i3) { + var marker = markers[i3], + linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { + return linked.push(d); + }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + }; + for (var i2 = 0; i2 < markers.length; i2++) loop(i2); + } + var nextDocId = 0; + var Doc = function (text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { + return new Doc(text, mode, firstLine, lineSep, direction); + } + if (firstLine == null) { + firstLine = 0; + } + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.modeFrontier = this.highlightFrontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.direction = direction == "rtl" ? "rtl" : "ltr"; + this.extend = false; + if (typeof text == "string") { + text = this.splitLines(text); + } + updateDoc(this, { + from: start, + to: start, + text, + }); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function (from, to, op) { + if (op) { + this.iterN(from - this.first, to - from, op); + } else { + this.iterN(this.first, this.first + this.size, from); + } + }, + // Non-public interface for adding and removing lines. + insert: function (at, lines) { + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + height += lines[i2].height; + } + this.insertInner(at - this.first, lines, height); + }, + remove: function (at, n) { + this.removeInner(at - this.first, n); + }, + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + getValue: function (lineSep) { + var lines = getLines( + this, + this.first, + this.first + this.size + ); + if (lineSep === false) { + return lines; + } + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function (code) { + var top = Pos(this.first, 0), + last = this.first + this.size - 1; + makeChange( + this, + { + from: top, + to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), + origin: "setValue", + full: true, + }, + true + ); + if (this.cm) { + scrollToCoords(this.cm, 0, 0); + } + setSelection(this, simpleSelection(top), sel_dontScroll); + }), + replaceRange: function (code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function (from, to, lineSep) { + var lines = getBetween( + this, + clipPos(this, from), + clipPos(this, to) + ); + if (lineSep === false) { + return lines; + } + if (lineSep === "") { + return lines.join(""); + } + return lines.join(lineSep || this.lineSeparator()); + }, + getLine: function (line) { + var l = this.getLineHandle(line); + return l && l.text; + }, + getLineHandle: function (line) { + if (isLine(this, line)) { + return getLine(this, line); + } + }, + getLineNumber: function (line) { + return lineNo(line); + }, + getLineHandleVisualStart: function (line) { + if (typeof line == "number") { + line = getLine(this, line); + } + return visualLine(line); + }, + lineCount: function () { + return this.size; + }, + firstLine: function () { + return this.first; + }, + lastLine: function () { + return this.first + this.size - 1; + }, + clipPos: function (pos) { + return clipPos(this, pos); + }, + getCursor: function (start) { + var range2 = this.sel.primary(), + pos; + if (start == null || start == "head") { + pos = range2.head; + } else if (start == "anchor") { + pos = range2.anchor; + } else if ( + start == "end" || + start == "to" || + start === false + ) { + pos = range2.to(); + } else { + pos = range2.from(); + } + return pos; + }, + listSelections: function () { + return this.sel.ranges; + }, + somethingSelected: function () { + return this.sel.somethingSelected(); + }, + setCursor: docMethodOp(function (line, ch, options) { + setSimpleSelection( + this, + clipPos( + this, + typeof line == "number" ? Pos(line, ch || 0) : line + ), + null, + options + ); + }), + setSelection: docMethodOp(function (anchor, head, options) { + setSimpleSelection( + this, + clipPos(this, anchor), + clipPos(this, head || anchor), + options + ); + }), + extendSelection: docMethodOp(function (head, other, options) { + extendSelection( + this, + clipPos(this, head), + other && clipPos(this, other), + options + ); + }), + extendSelections: docMethodOp(function (heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function (f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function (ranges, primary, options) { + if (!ranges.length) { + return; + } + var out = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + out[i2] = new Range( + clipPos(this, ranges[i2].anchor), + clipPos(this, ranges[i2].head || ranges[i2].anchor) + ); + } + if (primary == null) { + primary = Math.min(ranges.length - 1, this.sel.primIndex); + } + setSelection( + this, + normalizeSelection(this.cm, out, primary), + options + ); + }), + addSelection: docMethodOp(function (anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push( + new Range( + clipPos(this, anchor), + clipPos(this, head || anchor) + ) + ); + setSelection( + this, + normalizeSelection(this.cm, ranges, ranges.length - 1), + options + ); + }), + getSelection: function (lineSep) { + var ranges = this.sel.ranges, + lines; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween( + this, + ranges[i2].from(), + ranges[i2].to() + ); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) { + return lines; + } else { + return lines.join(lineSep || this.lineSeparator()); + } + }, + getSelections: function (lineSep) { + var parts = [], + ranges = this.sel.ranges; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween( + this, + ranges[i2].from(), + ranges[i2].to() + ); + if (lineSep !== false) { + sel = sel.join(lineSep || this.lineSeparator()); + } + parts[i2] = sel; + } + return parts; + }, + replaceSelection: function (code, collapse, origin) { + var dup = []; + for (var i2 = 0; i2 < this.sel.ranges.length; i2++) { + dup[i2] = code; + } + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function ( + code, + collapse, + origin + ) { + var changes = [], + sel = this.sel; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + changes[i2] = { + from: range2.from(), + to: range2.to(), + text: this.splitLines(code[i2]), + origin, + }; + } + var newSel = + collapse && + collapse != "end" && + computeReplacedSel(this, changes, collapse); + for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) { + makeChange(this, changes[i$12]); + } + if (newSel) { + setSelectionReplaceHistory(this, newSel); + } else if (this.cm) { + ensureCursorVisible(this.cm); + } + }), + undo: docMethodOp(function () { + makeChangeFromHistory(this, "undo"); + }), + redo: docMethodOp(function () { + makeChangeFromHistory(this, "redo"); + }), + undoSelection: docMethodOp(function () { + makeChangeFromHistory(this, "undo", true); + }), + redoSelection: docMethodOp(function () { + makeChangeFromHistory(this, "redo", true); + }), + setExtending: function (val) { + this.extend = val; + }, + getExtending: function () { + return this.extend; + }, + historySize: function () { + var hist = this.history, + done = 0, + undone = 0; + for (var i2 = 0; i2 < hist.done.length; i2++) { + if (!hist.done[i2].ranges) { + ++done; + } + } + for (var i$12 = 0; i$12 < hist.undone.length; i$12++) { + if (!hist.undone[i$12].ranges) { + ++undone; + } + } + return { + undo: done, + redo: undone, + }; + }, + clearHistory: function () { + var this$1$1 = this; + this.history = new History(this.history); + linkedDocs( + this, + function (doc) { + return (doc.history = this$1$1.history); + }, + true + ); + }, + markClean: function () { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function (forceSplit) { + if (forceSplit) { + this.history.lastOp = + this.history.lastSelOp = + this.history.lastOrigin = + null; + } + return this.history.generation; + }, + isClean: function (gen) { + return ( + this.history.generation == (gen || this.cleanGeneration) + ); + }, + getHistory: function () { + return { + done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone), + }; + }, + setHistory: function (histData) { + var hist = (this.history = new History(this.history)); + hist.done = copyHistoryArray( + histData.done.slice(0), + null, + true + ); + hist.undone = copyHistoryArray( + histData.undone.slice(0), + null, + true + ); + }, + setGutterMarker: docMethodOp(function (line, gutterID, value) { + return changeLine(this, line, "gutter", function (line2) { + var markers = + line2.gutterMarkers || (line2.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) { + line2.gutterMarkers = null; + } + return true; + }); + }), + clearGutter: docMethodOp(function (gutterID) { + var this$1$1 = this; + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null; + if (isEmpty(line.gutterMarkers)) { + line.gutterMarkers = null; + } + return true; + }); + } + }); + }), + lineInfo: function (line) { + var n; + if (typeof line == "number") { + if (!isLine(this, line)) { + return null; + } + n = line; + line = getLine(this, line); + if (!line) { + return null; + } + } else { + n = lineNo(line); + if (n == null) { + return null; + } + } + return { + line: n, + handle: line, + text: line.text, + gutterMarkers: line.gutterMarkers, + textClass: line.textClass, + bgClass: line.bgClass, + wrapClass: line.wrapClass, + widgets: line.widgets, + }; + }, + addLineClass: docMethodOp(function (handle, where, cls) { + return changeLine( + this, + handle, + where == "gutter" ? "gutter" : "class", + function (line) { + var prop2 = + where == "text" + ? "textClass" + : where == "background" + ? "bgClass" + : where == "gutter" + ? "gutterClass" + : "wrapClass"; + if (!line[prop2]) { + line[prop2] = cls; + } else if (classTest(cls).test(line[prop2])) { + return false; + } else { + line[prop2] += " " + cls; + } + return true; + } + ); + }), + removeLineClass: docMethodOp(function (handle, where, cls) { + return changeLine( + this, + handle, + where == "gutter" ? "gutter" : "class", + function (line) { + var prop2 = + where == "text" + ? "textClass" + : where == "background" + ? "bgClass" + : where == "gutter" + ? "gutterClass" + : "wrapClass"; + var cur = line[prop2]; + if (!cur) { + return false; + } else if (cls == null) { + line[prop2] = null; + } else { + var found = cur.match(classTest(cls)); + if (!found) { + return false; + } + var end = found.index + found[0].length; + line[prop2] = + cur.slice(0, found.index) + + (!found.index || end == cur.length ? "" : " ") + + cur.slice(end) || null; + } + return true; + } + ); + }), + addLineWidget: docMethodOp(function (handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function (widget) { + widget.clear(); + }, + markText: function (from, to, options) { + return markText( + this, + clipPos(this, from), + clipPos(this, to), + options, + (options && options.type) || "range" + ); + }, + setBookmark: function (pos, options) { + var realOpts = { + replacedWith: + options && + (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, + shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents, + }; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function (pos) { + pos = clipPos(this, pos); + var markers = [], + spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if ( + (span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch) + ) { + markers.push(span.marker.parent || span.marker); + } + } + } + return markers; + }, + findMarks: function (from, to, filter) { + from = clipPos(this, from); + to = clipPos(this, to); + var found = [], + lineNo2 = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; i2++) { + var span = spans[i2]; + if ( + !( + (span.to != null && + lineNo2 == from.line && + from.ch >= span.to) || + (span.from == null && lineNo2 != from.line) || + (span.from != null && + lineNo2 == to.line && + span.from >= to.ch) + ) && + (!filter || filter(span.marker)) + ) { + found.push(span.marker.parent || span.marker); + } + } + } + ++lineNo2; + }); + return found; + }, + getAllMarks: function () { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + if (sps[i2].from != null) { + markers.push(sps[i2].marker); + } + } + } + }); + return markers; + }, + posFromIndex: function (off2) { + var ch, + lineNo2 = this.first, + sepSize = this.lineSeparator().length; + this.iter(function (line) { + var sz = line.text.length + sepSize; + if (sz > off2) { + ch = off2; + return true; + } + off2 -= sz; + ++lineNo2; + }); + return clipPos(this, Pos(lineNo2, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) { + return 0; + } + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + sepSize; + }); + return index; + }, + copy: function (copyHistory) { + var doc = new Doc( + getLines(this, this.first, this.first + this.size), + this.modeOption, + this.first, + this.lineSep, + this.direction + ); + doc.scrollTop = this.scrollTop; + doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + linkedDoc: function (options) { + if (!options) { + options = {}; + } + var from = this.first, + to = this.first + this.size; + if (options.from != null && options.from > from) { + from = options.from; + } + if (options.to != null && options.to < to) { + to = options.to; + } + var copy = new Doc( + getLines(this, from, to), + options.mode || this.modeOption, + from, + this.lineSep, + this.direction + ); + if (options.sharedHist) { + copy.history = this.history; + } + (this.linked || (this.linked = [])).push({ + doc: copy, + sharedHist: options.sharedHist, + }); + copy.linked = [ + { + doc: this, + isParent: true, + sharedHist: options.sharedHist, + }, + ]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function (other) { + if (other instanceof CodeMirror) { + other = other.doc; + } + if (this.linked) { + for (var i2 = 0; i2 < this.linked.length; ++i2) { + var link = this.linked[i2]; + if (link.doc != other) { + continue; + } + this.linked.splice(i2, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + } + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs( + other, + function (doc) { + return splitIds.push(doc.id); + }, + true + ); + other.history = new History(null); + other.history.done = copyHistoryArray( + this.history.done, + splitIds + ); + other.history.undone = copyHistoryArray( + this.history.undone, + splitIds + ); + } + }, + iterLinkedDocs: function (f) { + linkedDocs(this, f); + }, + getMode: function () { + return this.mode; + }, + getEditor: function () { + return this.cm; + }, + splitLines: function (str) { + if (this.lineSep) { + return str.split(this.lineSep); + } + return splitLinesAuto(str); + }, + lineSeparator: function () { + return this.lineSep || "\n"; + }, + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { + dir = "ltr"; + } + if (dir == this.direction) { + return; + } + this.direction = dir; + this.iter(function (line) { + return (line.order = null); + }); + if (this.cm) { + directionChanged(this.cm); + } + }), + }); + Doc.prototype.eachLine = Doc.prototype.iter; + var lastDrop = 0; + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e_preventDefault(e); + if (ie) { + lastDrop = +(/* @__PURE__ */ new Date()); + } + var pos = posFromMouse(cm, e, true), + files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) { + return; + } + if (files && files.length && window.FileReader && window.File) { + var n = files.length, + text = Array(n), + read = 0; + var markAsReadAndPasteIfAllFilesAreRead = function () { + if (++read == n) { + operation(cm, function () { + pos = clipPos(cm.doc, pos); + var change = { + from: pos, + to: pos, + text: cm.doc.splitLines( + text + .filter(function (t) { + return t != null; + }) + .join(cm.doc.lineSeparator()) + ), + origin: "paste", + }; + makeChange(cm.doc, change); + setSelectionReplaceHistory( + cm.doc, + simpleSelection( + clipPos(cm.doc, pos), + clipPos(cm.doc, changeEnd(change)) + ) + ); + })(); + } + }; + var readTextFromFile = function (file, i3) { + if ( + cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1 + ) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + var reader = new FileReader(); + reader.onerror = function () { + return markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.onload = function () { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + text[i3] = content; + markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.readAsText(file); + }; + for (var i2 = 0; i2 < files.length; i2++) { + readTextFromFile(files[i2], i2); + } + } else { + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + setTimeout(function () { + return cm.display.input.focus(); + }, 20); + return; + } + try { + var text$1 = e.dataTransfer.getData("Text"); + if (text$1) { + var selected; + if ( + cm.state.draggingText && + !cm.state.draggingText.copy + ) { + selected = cm.listSelections(); + } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i$12 = 0; i$12 < selected.length; ++i$12) { + replaceRange( + cm.doc, + "", + selected[i$12].anchor, + selected[i$12].head, + "drag" + ); + } + } + cm.replaceSelection(text$1, "around", "paste"); + cm.display.input.focus(); + } + } catch (e$1) {} + } + } + function onDragStart(cm, e) { + if ( + ie && + (!cm.state.draggingText || + +(/* @__PURE__ */ new Date()) - lastDrop < 100) + ) { + e_stop(e); + return; + } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove"; + if (e.dataTransfer.setDragImage && !safari) { + var img = elt( + "img", + null, + null, + "position: fixed; left: 0; top: 0;" + ); + img.src = + "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) { + img.parentNode.removeChild(img); + } + } + } + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) { + return; + } + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt( + "div", + null, + "CodeMirror-cursors CodeMirror-dragcursors" + ); + cm.display.lineSpace.insertBefore( + cm.display.dragCursor, + cm.display.cursorDiv + ); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { + return; + } + var byClass = document.getElementsByClassName("CodeMirror"), + editors = []; + for (var i2 = 0; i2 < byClass.length; i2++) { + var cm = byClass[i2].CodeMirror; + if (cm) { + editors.push(cm); + } + } + if (editors.length) { + editors[0].operation(function () { + for (var i3 = 0; i3 < editors.length; i3++) { + f(editors[i3]); + } + }); + } + } + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) { + return; + } + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { + resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + } + }); + on(window, "blur", function () { + return forEachCodeMirror(onBlur); + }); + } + function onResize(cm) { + var d = cm.display; + d.cachedCharWidth = + d.cachedTextHeight = + d.cachedPaddingH = + null; + d.scrollbarsClipped = false; + cm.setSize(); + } + var keyNames = { + 3: "Pause", + 8: "Backspace", + 9: "Tab", + 13: "Enter", + 16: "Shift", + 17: "Ctrl", + 18: "Alt", + 19: "Pause", + 20: "CapsLock", + 27: "Esc", + 32: "Space", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "Left", + 38: "Up", + 39: "Right", + 40: "Down", + 44: "PrintScrn", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Mod", + 92: "Mod", + 93: "Mod", + 106: "*", + 107: "=", + 109: "-", + 110: ".", + 111: "/", + 145: "ScrollLock", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'", + 224: "Mod", + 63232: "Up", + 63233: "Down", + 63234: "Left", + 63235: "Right", + 63272: "Delete", + 63273: "Home", + 63275: "End", + 63276: "PageUp", + 63277: "PageDown", + 63302: "Insert", + }; + for (var i = 0; i < 10; i++) { + keyNames[i + 48] = keyNames[i + 96] = String(i); + } + for (var i$1 = 65; i$1 <= 90; i$1++) { + keyNames[i$1] = String.fromCharCode(i$1); + } + for (var i$2 = 1; i$2 <= 12; i$2++) { + keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; + } + var keyMap = {}; + keyMap.basic = { + Left: "goCharLeft", + Right: "goCharRight", + Up: "goLineUp", + Down: "goLineDown", + End: "goLineEnd", + Home: "goLineStartSmart", + PageUp: "goPageUp", + PageDown: "goPageDown", + Delete: "delCharAfter", + Backspace: "delCharBefore", + "Shift-Backspace": "delCharBefore", + Tab: "defaultTab", + "Shift-Tab": "indentAuto", + Enter: "newlineAndIndent", + Insert: "toggleOverwrite", + Esc: "singleSelection", + }; + keyMap.pcDefault = { + "Ctrl-A": "selectAll", + "Ctrl-D": "deleteLine", + "Ctrl-Z": "undo", + "Shift-Ctrl-Z": "redo", + "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", + "Ctrl-End": "goDocEnd", + "Ctrl-Up": "goLineUp", + "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", + "Ctrl-Right": "goGroupRight", + "Alt-Left": "goLineStart", + "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", + "Ctrl-Delete": "delGroupAfter", + "Ctrl-S": "save", + "Ctrl-F": "find", + "Ctrl-G": "findNext", + "Shift-Ctrl-G": "findPrev", + "Shift-Ctrl-F": "replace", + "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", + "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", + "Shift-Ctrl-U": "redoSelection", + "Alt-U": "redoSelection", + fallthrough: "basic", + }; + keyMap.emacsy = { + "Ctrl-F": "goCharRight", + "Ctrl-B": "goCharLeft", + "Ctrl-P": "goLineUp", + "Ctrl-N": "goLineDown", + "Ctrl-A": "goLineStart", + "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", + "Shift-Ctrl-V": "goPageUp", + "Ctrl-D": "delCharAfter", + "Ctrl-H": "delCharBefore", + "Alt-Backspace": "delWordBefore", + "Ctrl-K": "killLine", + "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine", + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", + "Cmd-D": "deleteLine", + "Cmd-Z": "undo", + "Shift-Cmd-Z": "redo", + "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", + "Cmd-Up": "goDocStart", + "Cmd-End": "goDocEnd", + "Cmd-Down": "goDocEnd", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", + "Cmd-Left": "goLineLeft", + "Cmd-Right": "goLineRight", + "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", + "Alt-Delete": "delGroupAfter", + "Cmd-S": "save", + "Cmd-F": "find", + "Cmd-G": "findNext", + "Shift-Cmd-G": "findPrev", + "Cmd-Alt-F": "replace", + "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", + "Cmd-]": "indentMore", + "Cmd-Backspace": "delWrappedLineLeft", + "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", + "Shift-Cmd-U": "redoSelection", + "Ctrl-Up": "goDocStart", + "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"], + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/); + name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i2 = 0; i2 < parts.length - 1; i2++) { + var mod = parts[i2]; + if (/^(cmd|meta|m)$/i.test(mod)) { + cmd = true; + } else if (/^a(lt)?$/i.test(mod)) { + alt = true; + } else if (/^(c|ctrl|control)$/i.test(mod)) { + ctrl = true; + } else if (/^s(hift)?$/i.test(mod)) { + shift = true; + } else { + throw new Error("Unrecognized modifier name: " + mod); + } + } + if (alt) { + name = "Alt-" + name; + } + if (ctrl) { + name = "Ctrl-" + name; + } + if (cmd) { + name = "Cmd-" + name; + } + if (shift) { + name = "Shift-" + name; + } + return name; + } + function normalizeKeyMap(keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { + continue; + } + if (value == "...") { + delete keymap[keyname]; + continue; + } + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i2 = 0; i2 < keys.length; i2++) { + var val = void 0, + name = void 0; + if (i2 == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i2 + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) { + copy[name] = val; + } else if (prev != val) { + throw new Error("Inconsistent bindings for " + name); + } + } + delete keymap[keyname]; + } + } + for (var prop2 in copy) { + keymap[prop2] = copy[prop2]; + } + return keymap; + } + function lookupKey(key, map2, handle, context) { + map2 = getKeyMap(map2); + var found = map2.call ? map2.call(key, context) : map2[key]; + if (found === false) { + return "nothing"; + } + if (found === "...") { + return "multi"; + } + if (found != null && handle(found)) { + return "handled"; + } + if (map2.fallthrough) { + if ( + Object.prototype.toString.call(map2.fallthrough) != + "[object Array]" + ) { + return lookupKey(key, map2.fallthrough, handle, context); + } + for (var i2 = 0; i2 < map2.fallthrough.length; i2++) { + var result = lookupKey( + key, + map2.fallthrough[i2], + handle, + context + ); + if (result) { + return result; + } + } + } + } + function isModifierKey(value) { + var name = + typeof value == "string" ? value : keyNames[value.keyCode]; + return ( + name == "Ctrl" || + name == "Alt" || + name == "Shift" || + name == "Mod" + ); + } + function addModifierNames(name, event, noShift) { + var base = name; + if (event.altKey && base != "Alt") { + name = "Alt-" + name; + } + if ( + (flipCtrlCmd ? event.metaKey : event.ctrlKey) && + base != "Ctrl" + ) { + name = "Ctrl-" + name; + } + if ( + (flipCtrlCmd ? event.ctrlKey : event.metaKey) && + base != "Mod" + ) { + name = "Cmd-" + name; + } + if (!noShift && event.shiftKey && base != "Shift") { + name = "Shift-" + name; + } + return name; + } + function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { + return false; + } + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) { + return false; + } + if (event.keyCode == 3 && event.code) { + name = event.code; + } + return addModifierNames(name, event, noShift); + } + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, + kill = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + var toKill = compute(ranges[i2]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + runInOp(cm, function () { + for (var i3 = kill.length - 1; i3 >= 0; i3--) { + replaceRange( + cm.doc, + "", + kill[i3].from, + kill[i3].to, + "+delete" + ); + } + ensureCursorVisible(cm); + }); + } + function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir); + return target < 0 || target > line.text.length ? null : target; + } + function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir); + return ch == null + ? null + : new Pos(start.line, ch, dir < 0 ? "after" : "before"); + } + function endOfLine(visually, cm, lineObj, lineNo2, dir) { + if (visually) { + if (cm.doc.direction == "rtl") { + dir = -dir; + } + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = dir < 0 ? lst(order) : order[0]; + var moveInStorageOrder = dir < 0 == (part.level == 1); + var sticky = moveInStorageOrder ? "after" : "before"; + var ch; + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj); + ch = dir < 0 ? lineObj.text.length - 1 : 0; + var targetTop = measureCharPrepared(cm, prep, ch).top; + ch = findFirst( + function (ch2) { + return ( + measureCharPrepared(cm, prep, ch2).top == targetTop + ); + }, + dir < 0 == (part.level == 1) ? part.from : part.to - 1, + ch + ); + if (sticky == "before") { + ch = moveCharLogically(lineObj, ch, 1); + } + } else { + ch = dir < 0 ? part.to : part.from; + } + return new Pos(lineNo2, ch, sticky); + } + } + return new Pos( + lineNo2, + dir < 0 ? lineObj.text.length : 0, + dir < 0 ? "before" : "after" + ); + } + function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction); + if (!bidi) { + return moveLogically(line, start, dir); + } + if (start.ch >= line.text.length) { + start.ch = line.text.length; + start.sticky = "before"; + } else if (start.ch <= 0) { + start.ch = 0; + start.sticky = "after"; + } + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), + part = bidi[partPos]; + if ( + cm.doc.direction == "ltr" && + part.level % 2 == 0 && + (dir > 0 ? part.to > start.ch : part.from < start.ch) + ) { + return moveLogically(line, start, dir); + } + var mv = function (pos, dir2) { + return moveCharLogically( + line, + pos instanceof Pos ? pos.ch : pos, + dir2 + ); + }; + var prep; + var getWrappedLineExtent = function (ch2) { + if (!cm.options.lineWrapping) { + return { + begin: 0, + end: line.text.length, + }; + } + prep = prep || prepareMeasureForLine(cm, line); + return wrappedLineExtentChar(cm, line, prep, ch2); + }; + var wrappedLineExtent2 = getWrappedLineExtent( + start.sticky == "before" ? mv(start, -1) : start.ch + ); + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = (part.level == 1) == dir < 0; + var ch = mv(start, moveInStorageOrder ? 1 : -1); + if ( + ch != null && + (!moveInStorageOrder + ? ch >= part.from && ch >= wrappedLineExtent2.begin + : ch <= part.to && ch <= wrappedLineExtent2.end) + ) { + var sticky = moveInStorageOrder ? "before" : "after"; + return new Pos(start.line, ch, sticky); + } + } + var searchInVisualLine = function ( + partPos2, + dir2, + wrappedLineExtent3 + ) { + var getRes = function (ch3, moveInStorageOrder3) { + return moveInStorageOrder3 + ? new Pos(start.line, mv(ch3, 1), "before") + : new Pos(start.line, ch3, "after"); + }; + for ( + ; + partPos2 >= 0 && partPos2 < bidi.length; + partPos2 += dir2 + ) { + var part2 = bidi[partPos2]; + var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1); + var ch2 = moveInStorageOrder2 + ? wrappedLineExtent3.begin + : mv(wrappedLineExtent3.end, -1); + if (part2.from <= ch2 && ch2 < part2.to) { + return getRes(ch2, moveInStorageOrder2); + } + ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1); + if ( + wrappedLineExtent3.begin <= ch2 && + ch2 < wrappedLineExtent3.end + ) { + return getRes(ch2, moveInStorageOrder2); + } + } + }; + var res = searchInVisualLine( + partPos + dir, + dir, + wrappedLineExtent2 + ); + if (res) { + return res; + } + var nextCh = + dir > 0 + ? wrappedLineExtent2.end + : mv(wrappedLineExtent2.begin, -1); + if ( + nextCh != null && + !(dir > 0 && nextCh == line.text.length) + ) { + res = searchInVisualLine( + dir > 0 ? 0 : bidi.length - 1, + dir, + getWrappedLineExtent(nextCh) + ); + if (res) { + return res; + } + } + return null; + } + var commands = { + selectAll, + singleSelection: function (cm) { + return cm.setSelection( + cm.getCursor("anchor"), + cm.getCursor("head"), + sel_dontScroll + ); + }, + killLine: function (cm) { + return deleteNearSelection(cm, function (range2) { + if (range2.empty()) { + var len = getLine(cm.doc, range2.head.line).text.length; + if ( + range2.head.ch == len && + range2.head.line < cm.lastLine() + ) { + return { + from: range2.head, + to: Pos(range2.head.line + 1, 0), + }; + } else { + return { + from: range2.head, + to: Pos(range2.head.line, len), + }; + } + } else { + return { + from: range2.from(), + to: range2.to(), + }; + } + }); + }, + deleteLine: function (cm) { + return deleteNearSelection(cm, function (range2) { + return { + from: Pos(range2.from().line, 0), + to: clipPos(cm.doc, Pos(range2.to().line + 1, 0)), + }; + }); + }, + delLineLeft: function (cm) { + return deleteNearSelection(cm, function (range2) { + return { + from: Pos(range2.from().line, 0), + to: range2.from(), + }; + }); + }, + delWrappedLineLeft: function (cm) { + return deleteNearSelection(cm, function (range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var leftPos = cm.coordsChar( + { + left: 0, + top, + }, + "div" + ); + return { + from: leftPos, + to: range2.from(), + }; + }); + }, + delWrappedLineRight: function (cm) { + return deleteNearSelection(cm, function (range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var rightPos = cm.coordsChar( + { + left: cm.display.lineDiv.offsetWidth + 100, + top, + }, + "div" + ); + return { + from: range2.from(), + to: rightPos, + }; + }); + }, + undo: function (cm) { + return cm.undo(); + }, + redo: function (cm) { + return cm.redo(); + }, + undoSelection: function (cm) { + return cm.undoSelection(); + }, + redoSelection: function (cm) { + return cm.redoSelection(); + }, + goDocStart: function (cm) { + return cm.extendSelection(Pos(cm.firstLine(), 0)); + }, + goDocEnd: function (cm) { + return cm.extendSelection(Pos(cm.lastLine())); + }, + goLineStart: function (cm) { + return cm.extendSelectionsBy( + function (range2) { + return lineStart(cm, range2.head.line); + }, + { + origin: "+move", + bias: 1, + } + ); + }, + goLineStartSmart: function (cm) { + return cm.extendSelectionsBy( + function (range2) { + return lineStartSmart(cm, range2.head); + }, + { + origin: "+move", + bias: 1, + } + ); + }, + goLineEnd: function (cm) { + return cm.extendSelectionsBy( + function (range2) { + return lineEnd(cm, range2.head.line); + }, + { + origin: "+move", + bias: -1, + } + ); + }, + goLineRight: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar( + { + left: cm.display.lineDiv.offsetWidth + 100, + top, + }, + "div" + ); + }, sel_move); + }, + goLineLeft: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar( + { + left: 0, + top, + }, + "div" + ); + }, sel_move); + }, + goLineLeftSmart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + var pos = cm.coordsChar( + { + left: 0, + top, + }, + "div" + ); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { + return lineStartSmart(cm, range2.head); + } + return pos; + }, sel_move); + }, + goLineUp: function (cm) { + return cm.moveV(-1, "line"); + }, + goLineDown: function (cm) { + return cm.moveV(1, "line"); + }, + goPageUp: function (cm) { + return cm.moveV(-1, "page"); + }, + goPageDown: function (cm) { + return cm.moveV(1, "page"); + }, + goCharLeft: function (cm) { + return cm.moveH(-1, "char"); + }, + goCharRight: function (cm) { + return cm.moveH(1, "char"); + }, + goColumnLeft: function (cm) { + return cm.moveH(-1, "column"); + }, + goColumnRight: function (cm) { + return cm.moveH(1, "column"); + }, + goWordLeft: function (cm) { + return cm.moveH(-1, "word"); + }, + goGroupRight: function (cm) { + return cm.moveH(1, "group"); + }, + goGroupLeft: function (cm) { + return cm.moveH(-1, "group"); + }, + goWordRight: function (cm) { + return cm.moveH(1, "word"); + }, + delCharBefore: function (cm) { + return cm.deleteH(-1, "codepoint"); + }, + delCharAfter: function (cm) { + return cm.deleteH(1, "char"); + }, + delWordBefore: function (cm) { + return cm.deleteH(-1, "word"); + }, + delWordAfter: function (cm) { + return cm.deleteH(1, "word"); + }, + delGroupBefore: function (cm) { + return cm.deleteH(-1, "group"); + }, + delGroupAfter: function (cm) { + return cm.deleteH(1, "group"); + }, + indentAuto: function (cm) { + return cm.indentSelection("smart"); + }, + indentMore: function (cm) { + return cm.indentSelection("add"); + }, + indentLess: function (cm) { + return cm.indentSelection("subtract"); + }, + insertTab: function (cm) { + return cm.replaceSelection(" "); + }, + insertSoftTab: function (cm) { + var spaces = [], + ranges = cm.listSelections(), + tabSize = cm.options.tabSize; + for (var i2 = 0; i2 < ranges.length; i2++) { + var pos = ranges[i2].from(); + var col = countColumn( + cm.getLine(pos.line), + pos.ch, + tabSize + ); + spaces.push(spaceStr(tabSize - (col % tabSize))); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { + cm.indentSelection("add"); + } else { + cm.execCommand("insertTab"); + } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { + return runInOp(cm, function () { + var ranges = cm.listSelections(), + newSel = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + if (!ranges[i2].empty()) { + continue; + } + var cur = ranges[i2].head, + line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) { + cur = new Pos(cur.line, cur.ch - 1); + } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange( + line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), + cur, + "+transpose" + ); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cur = new Pos(cur.line, 1); + cm.replaceRange( + line.charAt(0) + + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), + cur, + "+transpose" + ); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function (cm) { + return runInOp(cm, function () { + var sels = cm.listSelections(); + for (var i2 = sels.length - 1; i2 >= 0; i2--) { + cm.replaceRange( + cm.doc.lineSeparator(), + sels[i2].anchor, + sels[i2].head, + "+input" + ); + } + sels = cm.listSelections(); + for (var i$12 = 0; i$12 < sels.length; i$12++) { + cm.indentLine(sels[i$12].from().line, null, true); + } + ensureCursorVisible(cm); + }); + }, + openLine: function (cm) { + return cm.replaceSelection("\n", "start"); + }, + toggleOverwrite: function (cm) { + return cm.toggleOverwrite(); + }, + }; + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, visual, lineN, 1); + } + function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLineEnd(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, line, lineN, -1); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line, cm.doc.direction); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); + var inWS = + pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); + } + return start; + } + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) { + return false; + } + } + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, + done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; + } + if (dropShift) { + cm.display.shift = false; + } + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + function lookupKeyForEditor(cm, name, handle) { + for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) { + var result = lookupKey( + name, + cm.state.keyMaps[i2], + handle, + cm + ); + if (result) { + return result; + } + } + return ( + (cm.options.extraKeys && + lookupKey(name, cm.options.extraKeys, handle, cm)) || + lookupKey(name, cm.options.keyMap, handle, cm) + ); + } + var stopSeq = new Delayed(); + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) { + return "handled"; + } + if (/\'$/.test(name)) { + cm.state.keySeq = null; + } else { + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + } + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { + return true; + } + } + return dispatchKeyInner(cm, name, e, handle); + } + function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle); + if (result == "multi") { + cm.state.keySeq = name; + } + if (result == "handled") { + signalLater(cm, "keyHandled", cm, name, e); + } + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + return !!result; + } + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) { + return false; + } + if (e.shiftKey && !cm.state.keySeq) { + return ( + dispatchKey(cm, "Shift-" + name, e, function (b) { + return doHandleBinding(cm, b, true); + }) || + dispatchKey(cm, name, e, function (b) { + if ( + typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion + ) { + return doHandleBinding(cm, b); + } + }) + ); + } else { + return dispatchKey(cm, name, e, function (b) { + return doHandleBinding(cm, b); + }); + } + } + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { + return doHandleBinding(cm, b, true); + }); + } + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; + } + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) { + return; + } + if (ie && ie_version < 11 && e.keyCode == 27) { + e.returnValue = false; + } + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + if ( + !handled && + code == 88 && + !hasCopyEvent && + (mac ? e.metaKey : e.ctrlKey) + ) { + cm.replaceSelection("", null, "cut"); + } + } + if ( + gecko && + !mac && + !handled && + code == 46 && + e.shiftKey && + !e.ctrlKey && + document.execCommand + ) { + document.execCommand("cut"); + } + if ( + code == 18 && + !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className) + ) { + showCrossHair(cm); + } + } + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + function onKeyUp(e) { + if (e.keyCode == 16) { + this.doc.sel.shift = false; + } + signalDOMEvent(this, e); + } + function onKeyPress(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; + } + if ( + eventInWidget(cm.display, e) || + signalDOMEvent(cm, e) || + (e.ctrlKey && !e.altKey) || + (mac && e.metaKey) + ) { + return; + } + var keyCode = e.keyCode, + charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) { + lastStoppedKey = null; + e_preventDefault(e); + return; + } + if ( + presto && + (!e.which || e.which < 10) && + handleKeyBinding(cm, e) + ) { + return; + } + var ch = String.fromCharCode( + charCode == null ? keyCode : charCode + ); + if (ch == "\b") { + return; + } + if (handleCharBinding(cm, e, ch)) { + return; + } + cm.display.input.onKeyPress(e); + } + var DOUBLECLICK_DELAY = 400; + var PastClick = function (time, pos, button) { + this.time = time; + this.pos = pos; + this.button = button; + }; + PastClick.prototype.compare = function (time, pos, button) { + return ( + this.time + DOUBLECLICK_DELAY > time && + cmp(pos, this.pos) == 0 && + button == this.button + ); + }; + var lastClick, lastDoubleClick; + function clickRepeat(pos, button) { + var now = +(/* @__PURE__ */ new Date()); + if ( + lastDoubleClick && + lastDoubleClick.compare(now, pos, button) + ) { + lastClick = lastDoubleClick = null; + return "triple"; + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button); + lastClick = null; + return "double"; + } else { + lastClick = new PastClick(now, pos, button); + lastDoubleClick = null; + return "single"; + } + } + function onMouseDown(e) { + var cm = this, + display = cm.display; + if ( + signalDOMEvent(cm, e) || + (display.activeTouch && display.input.supportsTouch()) + ) { + return; + } + display.input.ensurePolled(); + display.shift = e.shiftKey; + if (eventInWidget(display, e)) { + if (!webkit) { + display.scroller.draggable = false; + setTimeout(function () { + return (display.scroller.draggable = true); + }, 100); + } + return; + } + if (clickInGutter(cm, e)) { + return; + } + var pos = posFromMouse(cm, e), + button = e_button(e), + repeat = pos ? clickRepeat(pos, button) : "single"; + window.focus(); + if (button == 1 && cm.state.selectingText) { + cm.state.selectingText(e); + } + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { + return; + } + if (button == 1) { + if (pos) { + leftButtonDown(cm, pos, repeat, e); + } else if (e_target(e) == display.scroller) { + e_preventDefault(e); + } + } else if (button == 2) { + if (pos) { + extendSelection(cm.doc, pos); + } + setTimeout(function () { + return display.input.focus(); + }, 20); + } else if (button == 3) { + if (captureRightClick) { + cm.display.input.onContextMenu(e); + } else { + delayBlurEvent(cm); + } + } + } + function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click"; + if (repeat == "double") { + name = "Double" + name; + } else if (repeat == "triple") { + name = "Triple" + name; + } + name = + (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + + name; + return dispatchKey( + cm, + addModifierNames(name, event), + event, + function (bound) { + if (typeof bound == "string") { + bound = commands[bound]; + } + if (!bound) { + return false; + } + var done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; + } + done = bound(cm, pos) != Pass; + } finally { + cm.state.suppressEdits = false; + } + return done; + } + ); + } + function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse"); + var value = option ? option(cm, repeat, event) : {}; + if (value.unit == null) { + var rect = chromeOS + ? event.shiftKey && event.metaKey + : event.altKey; + value.unit = rect + ? "rectangle" + : repeat == "single" + ? "char" + : repeat == "double" + ? "word" + : "line"; + } + if (value.extend == null || cm.doc.extend) { + value.extend = cm.doc.extend || event.shiftKey; + } + if (value.addNew == null) { + value.addNew = mac ? event.metaKey : event.ctrlKey; + } + if (value.moveOnDrag == null) { + value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); + } + return value; + } + function leftButtonDown(cm, pos, repeat, event) { + if (ie) { + setTimeout(bind(ensureFocus, cm), 0); + } else { + cm.curOp.focus = activeElt(); + } + var behavior = configureMouse(cm, repeat, event); + var sel = cm.doc.sel, + contained; + if ( + cm.options.dragDrop && + dragAndDrop && + !cm.isReadOnly() && + repeat == "single" && + (contained = sel.contains(pos)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || + pos.xRel > 0) && + (cmp(contained.to(), pos) > 0 || pos.xRel < 0) + ) { + leftButtonStartDrag(cm, event, pos, behavior); + } else { + leftButtonSelect(cm, event, pos, behavior); + } + } + function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, + moved = false; + var dragEnd = operation(cm, function (e) { + if (webkit) { + display.scroller.draggable = false; + } + cm.state.draggingText = false; + if (cm.state.delayingBlurEvent) { + if (cm.hasFocus()) { + cm.state.delayingBlurEvent = false; + } else { + delayBlurEvent(cm); + } + } + off(display.wrapper.ownerDocument, "mouseup", dragEnd); + off(display.wrapper.ownerDocument, "mousemove", mouseMove); + off(display.scroller, "dragstart", dragStart); + off(display.scroller, "drop", dragEnd); + if (!moved) { + e_preventDefault(e); + if (!behavior.addNew) { + extendSelection(cm.doc, pos, null, null, behavior.extend); + } + if ((webkit && !safari) || (ie && ie_version == 9)) { + setTimeout(function () { + display.wrapper.ownerDocument.body.focus({ + preventScroll: true, + }); + display.input.focus(); + }, 20); + } else { + display.input.focus(); + } + } + }); + var mouseMove = function (e2) { + moved = + moved || + Math.abs(event.clientX - e2.clientX) + + Math.abs(event.clientY - e2.clientY) >= + 10; + }; + var dragStart = function () { + return (moved = true); + }; + if (webkit) { + display.scroller.draggable = true; + } + cm.state.draggingText = dragEnd; + dragEnd.copy = !behavior.moveOnDrag; + on(display.wrapper.ownerDocument, "mouseup", dragEnd); + on(display.wrapper.ownerDocument, "mousemove", mouseMove); + on(display.scroller, "dragstart", dragStart); + on(display.scroller, "drop", dragEnd); + cm.state.delayingBlurEvent = true; + setTimeout(function () { + return display.input.focus(); + }, 20); + if (display.scroller.dragDrop) { + display.scroller.dragDrop(); + } + } + function rangeForUnit(cm, pos, unit) { + if (unit == "char") { + return new Range(pos, pos); + } + if (unit == "word") { + return cm.findWordAt(pos); + } + if (unit == "line") { + return new Range( + Pos(pos.line, 0), + clipPos(cm.doc, Pos(pos.line + 1, 0)) + ); + } + var result = unit(cm, pos); + return new Range(result.from, result.to); + } + function leftButtonSelect(cm, event, start, behavior) { + if (ie) { + delayBlurEvent(cm); + } + var display = cm.display, + doc = cm.doc; + e_preventDefault(event); + var ourRange, + ourIndex, + startSel = doc.sel, + ranges = startSel.ranges; + if (behavior.addNew && !behavior.extend) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) { + ourRange = ranges[ourIndex]; + } else { + ourRange = new Range(start, start); + } + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { + ourRange = new Range(start, start); + } + start = posFromMouse(cm, event, true, true); + ourIndex = -1; + } else { + var range2 = rangeForUnit(cm, start, behavior.unit); + if (behavior.extend) { + ourRange = extendRange( + ourRange, + range2.anchor, + range2.head, + behavior.extend + ); + } else { + ourRange = range2; + } + } + if (!behavior.addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection( + doc, + normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), + { + scroll: false, + origin: "*mouse", + } + ); + } else if ( + ranges.length > 1 && + ranges[ourIndex].empty() && + behavior.unit == "char" && + !behavior.extend + ) { + setSelection( + doc, + normalizeSelection( + cm, + ranges + .slice(0, ourIndex) + .concat(ranges.slice(ourIndex + 1)), + 0 + ), + { + scroll: false, + origin: "*mouse", + } + ); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { + return; + } + lastPos = pos; + if (behavior.unit == "rectangle") { + var ranges2 = [], + tabSize = cm.options.tabSize; + var startCol = countColumn( + getLine(doc, start.line).text, + start.ch, + tabSize + ); + var posCol = countColumn( + getLine(doc, pos.line).text, + pos.ch, + tabSize + ); + var left = Math.min(startCol, posCol), + right = Math.max(startCol, posCol); + for ( + var line = Math.min(start.line, pos.line), + end = Math.min( + cm.lastLine(), + Math.max(start.line, pos.line) + ); + line <= end; + line++ + ) { + var text = getLine(doc, line).text, + leftPos = findColumn(text, left, tabSize); + if (left == right) { + ranges2.push( + new Range(Pos(line, leftPos), Pos(line, leftPos)) + ); + } else if (text.length > leftPos) { + ranges2.push( + new Range( + Pos(line, leftPos), + Pos(line, findColumn(text, right, tabSize)) + ) + ); + } + } + if (!ranges2.length) { + ranges2.push(new Range(start, start)); + } + setSelection( + doc, + normalizeSelection( + cm, + startSel.ranges.slice(0, ourIndex).concat(ranges2), + ourIndex + ), + { + origin: "*mouse", + scroll: false, + } + ); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var range3 = rangeForUnit(cm, pos, behavior.unit); + var anchor = oldRange.anchor, + head; + if (cmp(range3.anchor, anchor) > 0) { + head = range3.head; + anchor = minPos(oldRange.from(), range3.anchor); + } else { + head = range3.anchor; + anchor = maxPos(oldRange.to(), range3.head); + } + var ranges$1 = startSel.ranges.slice(0); + ranges$1[ourIndex] = bidiSimplify( + cm, + new Range(clipPos(doc, anchor), head) + ); + setSelection( + doc, + normalizeSelection(cm, ranges$1, ourIndex), + sel_mouse + ); + } + } + var editorSize = display.wrapper.getBoundingClientRect(); + var counter = 0; + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse( + cm, + e, + true, + behavior.unit == "rectangle" + ); + if (!cur) { + return; + } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) { + setTimeout( + operation(cm, function () { + if (counter == curCount) { + extend(e); + } + }), + 150 + ); + } + } else { + var outside = + e.clientY < editorSize.top + ? -20 + : e.clientY > editorSize.bottom + ? 20 + : 0; + if (outside) { + setTimeout( + operation(cm, function () { + if (counter != curCount) { + return; + } + display.scroller.scrollTop += outside; + extend(e); + }), + 50 + ); + } + } + } + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + if (e) { + e_preventDefault(e); + display.input.focus(); + } + off(display.wrapper.ownerDocument, "mousemove", move); + off(display.wrapper.ownerDocument, "mouseup", up); + doc.history.lastSelOrigin = null; + } + var move = operation(cm, function (e) { + if (e.buttons === 0 || !e_button(e)) { + done(e); + } else { + extend(e); + } + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(display.wrapper.ownerDocument, "mousemove", move); + on(display.wrapper.ownerDocument, "mouseup", up); + } + function bidiSimplify(cm, range2) { + var anchor = range2.anchor; + var head = range2.head; + var anchorLine = getLine(cm.doc, anchor.line); + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { + return range2; + } + var order = getOrder(anchorLine); + if (!order) { + return range2; + } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), + part = order[index]; + if (part.from != anchor.ch && part.to != anchor.ch) { + return range2; + } + var boundary = + index + + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); + if (boundary == 0 || boundary == order.length) { + return range2; + } + var leftSide; + if (head.line != anchor.line) { + leftSide = + (head.line - anchor.line) * + (cm.doc.direction == "ltr" ? 1 : -1) > + 0; + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky); + var dir = + headIndex - index || + (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); + if (headIndex == boundary - 1 || headIndex == boundary) { + leftSide = dir < 0; + } else { + leftSide = dir > 0; + } + } + var usePart = order[boundary + (leftSide ? -1 : 0)]; + var from = leftSide == (usePart.level == 1); + var ch = from ? usePart.from : usePart.to, + sticky = from ? "after" : "before"; + return anchor.ch == ch && anchor.sticky == sticky + ? range2 + : new Range(new Pos(anchor.line, ch, sticky), head); + } + function gutterEvent(cm, e, type, prevent) { + var mX, mY; + if (e.touches) { + mX = e.touches[0].clientX; + mY = e.touches[0].clientY; + } else { + try { + mX = e.clientX; + mY = e.clientY; + } catch (e$1) { + return false; + } + } + if ( + mX >= + Math.floor(cm.display.gutters.getBoundingClientRect().right) + ) { + return false; + } + if (prevent) { + e_preventDefault(e); + } + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + if (mY > lineBox.bottom || !hasHandler(cm, type)) { + return e_defaultPrevented(e); + } + mY -= lineBox.top - display.viewOffset; + for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) { + var g = display.gutters.childNodes[i2]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.display.gutterSpecs[i2]; + signal(cm, type, cm, line, gutter.className, e); + return e_defaultPrevented(e); + } + } + } + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true); + } + function onContextMenu(cm, e) { + if ( + eventInWidget(cm.display, e) || + contextMenuInGutter(cm, e) + ) { + return; + } + if (signalDOMEvent(cm, e, "contextmenu")) { + return; + } + if (!captureRightClick) { + cm.display.input.onContextMenu(e); + } + } + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { + return false; + } + return gutterEvent(cm, e, "gutterContextMenu", false); + } + function themeChanged(cm) { + cm.display.wrapper.className = + cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + var Init = { + toString: function () { + return "CodeMirror.Init"; + }, + }; + var defaults = {}; + var optionHandlers = {}; + function defineOptions(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + function option(name, deflt, handle, notOnInit) { + CodeMirror2.defaults[name] = deflt; + if (handle) { + optionHandlers2[name] = notOnInit + ? function (cm, val, old) { + if (old != Init) { + handle(cm, val, old); + } + } + : handle; + } + } + CodeMirror2.defineOption = option; + CodeMirror2.Init = Init; + option( + "value", + "", + function (cm, val) { + return cm.setValue(val); + }, + true + ); + option( + "mode", + null, + function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, + true + ); + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option( + "tabSize", + 4, + function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, + true + ); + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val; + if (!val) { + return; + } + var newBreaks = [], + lineNo2 = cm.doc.first; + cm.doc.iter(function (line) { + for (var pos = 0; ; ) { + var found = line.text.indexOf(val, pos); + if (found == -1) { + break; + } + pos = found + val.length; + newBreaks.push(Pos(lineNo2, found)); + } + lineNo2++; + }); + for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) { + replaceRange( + cm.doc, + val, + newBreaks[i2], + Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length) + ); + } + }); + option( + "specialChars", + /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, + function (cm, val, old) { + cm.state.specialChars = new RegExp( + val.source + (val.test(" ") ? "" : "| "), + "g" + ); + if (old != Init) { + cm.refresh(); + } + } + ); + option( + "specialCharPlaceholder", + defaultSpecialCharPlaceholder, + function (cm) { + return cm.refresh(); + }, + true + ); + option("electricChars", true); + option( + "inputStyle", + mobile ? "contenteditable" : "textarea", + function () { + throw new Error( + "inputStyle can not (yet) be changed in a running editor" + ); + }, + true + ); + option( + "spellcheck", + false, + function (cm, val) { + return (cm.getInputField().spellcheck = val); + }, + true + ); + option( + "autocorrect", + false, + function (cm, val) { + return (cm.getInputField().autocorrect = val); + }, + true + ); + option( + "autocapitalize", + false, + function (cm, val) { + return (cm.getInputField().autocapitalize = val); + }, + true + ); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + option( + "theme", + "default", + function (cm) { + themeChanged(cm); + updateGutters(cm); + }, + true + ); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != Init && getKeyMap(old); + if (prev && prev.detach) { + prev.detach(cm, next); + } + if (next.attach) { + next.attach(cm, prev || null); + } + }); + option("extraKeys", null); + option("configureMouse", null); + option("lineWrapping", false, wrappingChanged, true); + option( + "gutters", + [], + function (cm, val) { + cm.display.gutterSpecs = getGutters( + val, + cm.options.lineNumbers + ); + updateGutters(cm); + }, + true + ); + option( + "fixedGutter", + true, + function (cm, val) { + cm.display.gutters.style.left = val + ? compensateForHScroll(cm.display) + "px" + : "0"; + cm.refresh(); + }, + true + ); + option( + "coverGutterNextToScrollbar", + false, + function (cm) { + return updateScrollbars(cm); + }, + true + ); + option( + "scrollbarStyle", + "native", + function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, + true + ); + option( + "lineNumbers", + false, + function (cm, val) { + cm.display.gutterSpecs = getGutters( + cm.options.gutters, + val + ); + updateGutters(cm); + }, + true + ); + option("firstLineNumber", 1, updateGutters, true); + option( + "lineNumberFormatter", + function (integer) { + return integer; + }, + updateGutters, + true + ); + option("showCursorWhenSelecting", false, updateSelection, true); + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + option("selectionsMayTouch", false); + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + } + cm.display.input.readOnlyChanged(val); + }); + option("screenReaderLabel", null, function (cm, val) { + val = val === "" ? null : val; + cm.display.input.screenReaderLabelChanged(val); + }); + option( + "disableInput", + false, + function (cm, val) { + if (!val) { + cm.display.input.reset(); + } + }, + true + ); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option( + "singleCursorHeightPerLine", + true, + updateSelection, + true + ); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) { + return (cm.doc.history.undoDepth = val); + }); + option("historyEventDelay", 1250); + option( + "viewportMargin", + 10, + function (cm) { + return cm.refresh(); + }, + true + ); + option("maxHighlightLength", 1e4, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { + cm.display.input.resetPosition(); + } + }); + option("tabindex", null, function (cm, val) { + return (cm.display.input.getField().tabIndex = val || ""); + }); + option("autofocus", null); + option( + "direction", + "ltr", + function (cm, val) { + return cm.doc.setDirection(val); + }, + true + ); + option("phrases", null); + } + function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () { + return updateScrollbars(cm); + }, 100); + } + function CodeMirror(place, options) { + var this$1$1 = this; + if (!(this instanceof CodeMirror)) { + return new CodeMirror(place, options); + } + this.options = options = options ? copyObj(options) : {}; + copyObj(defaults, options, false); + var doc = options.value; + if (typeof doc == "string") { + doc = new Doc( + doc, + options.mode, + null, + options.lineSeparator, + options.direction + ); + } else if (options.mode) { + doc.modeOption = options.mode; + } + this.doc = doc; + var input = new CodeMirror.inputStyles[options.inputStyle]( + this + ); + var display = (this.display = new Display( + place, + doc, + input, + options + )); + display.wrapper.CodeMirror = this; + themeChanged(this); + if (options.lineWrapping) { + this.display.wrapper.className += " CodeMirror-wrap"; + } + initScrollbars(this); + this.state = { + keyMaps: [], + // stores maps added by addKeyMap + overlays: [], + // highlighting overlays, as added by addOverlay + modeGen: 0, + // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, + // used to disable editing during key handlers when in readOnly mode + pasteIncoming: -1, + cutIncoming: -1, + // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), + // stores highlight worker timeout + keySeq: null, + // Unfinished key sequence + specialChars: null, + }; + if (options.autofocus && !mobile) { + display.input.focus(); + } + if (ie && ie_version < 11) { + setTimeout(function () { + return this$1$1.display.input.reset(true); + }, 20); + } + registerEventHandlers(this); + ensureGlobalHandlers(); + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + if ((options.autofocus && !mobile) || this.hasFocus()) { + setTimeout(function () { + if (this$1$1.hasFocus() && !this$1$1.state.focused) { + onFocus(this$1$1); + } + }, 20); + } else { + onBlur(this); + } + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) { + optionHandlers[opt](this, options[opt], Init); + } + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) { + options.finishInit(this); + } + for (var i2 = 0; i2 < initHooks.length; ++i2) { + initHooks[i2](this); + } + endOperation(this); + if ( + webkit && + options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == + "optimizelegibility" + ) { + display.lineDiv.style.textRendering = "auto"; + } + } + CodeMirror.defaults = defaults; + CodeMirror.optionHandlers = optionHandlers; + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + if (ie && ie_version < 11) { + on( + d.scroller, + "dblclick", + operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { + return; + } + var pos = posFromMouse(cm, e); + if ( + !pos || + clickInGutter(cm, e) || + eventInWidget(cm.display, e) + ) { + return; + } + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + }) + ); + } else { + on(d.scroller, "dblclick", function (e) { + return signalDOMEvent(cm, e) || e_preventDefault(e); + }); + } + on(d.scroller, "contextmenu", function (e) { + return onContextMenu(cm, e); + }); + on(d.input.getField(), "contextmenu", function (e) { + if (!d.scroller.contains(e.target)) { + onContextMenu(cm, e); + } + }); + var touchFinished, + prevTouch = { + end: 0, + }; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { + return (d.activeTouch = null); + }, 1e3); + prevTouch = d.activeTouch; + prevTouch.end = +(/* @__PURE__ */ new Date()); + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { + return false; + } + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway(touch, other) { + if (other.left == null) { + return true; + } + var dx = other.left - touch.left, + dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function (e) { + if ( + !signalDOMEvent(cm, e) && + !isMouseLikeTouchEvent(e) && + !clickInGutter(cm, e) + ) { + d.input.ensurePolled(); + clearTimeout(touchFinished); + var now = +(/* @__PURE__ */ new Date()); + d.activeTouch = { + start: now, + moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null, + }; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { + d.activeTouch.moved = true; + } + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if ( + touch && + !eventInWidget(d, e) && + touch.left != null && + !touch.moved && + /* @__PURE__ */ new Date() - touch.start < 300 + ) { + var pos = cm.coordsChar(d.activeTouch, "page"), + range2; + if (!touch.prev || farAway(touch, touch.prev)) { + range2 = new Range(pos, pos); + } else if ( + !touch.prev.prev || + farAway(touch, touch.prev.prev) + ) { + range2 = cm.findWordAt(pos); + } else { + range2 = new Range( + Pos(pos.line, 0), + clipPos(cm.doc, Pos(pos.line + 1, 0)) + ); + } + cm.setSelection(range2.anchor, range2.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + on(d.scroller, "mousewheel", function (e) { + return onScrollWheel(cm, e); + }); + on(d.scroller, "DOMMouseScroll", function (e) { + return onScrollWheel(cm, e); + }); + on(d.wrapper, "scroll", function () { + return (d.wrapper.scrollTop = d.wrapper.scrollLeft = 0); + }); + d.dragFunctions = { + enter: function (e) { + if (!signalDOMEvent(cm, e)) { + e_stop(e); + } + }, + over: function (e) { + if (!signalDOMEvent(cm, e)) { + onDragOver(cm, e); + e_stop(e); + } + }, + start: function (e) { + return onDragStart(cm, e); + }, + drop: operation(cm, onDrop), + leave: function (e) { + if (!signalDOMEvent(cm, e)) { + clearDragCursor(cm); + } + }, + }; + var inp = d.input.getField(); + on(inp, "keyup", function (e) { + return onKeyUp.call(cm, e); + }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", function (e) { + return onFocus(cm, e); + }); + on(inp, "blur", function (e) { + return onBlur(cm, e); + }); + } + var initHooks = []; + CodeMirror.defineInitHook = function (f) { + return initHooks.push(f); + }; + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, + state; + if (how == null) { + how = "add"; + } + if (how == "smart") { + if (!doc.mode.indent) { + how = "prev"; + } else { + state = getContextBefore(cm, n).state; + } + } + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), + curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) { + line.stateAfter = null; + } + var curSpaceString = line.text.match(/^\s*/)[0], + indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent( + state, + line.text.slice(curSpaceString.length), + line.text + ); + if (indentation == Pass || indentation > 150) { + if (!aggressive) { + return; + } + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) { + indentation = countColumn( + getLine(doc, n - 1).text, + null, + tabSize + ); + } else { + indentation = 0; + } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + var indentString = "", + pos = 0; + if (cm.options.indentWithTabs) { + for (var i2 = Math.floor(indentation / tabSize); i2; --i2) { + pos += tabSize; + indentString += " "; + } + } + if (pos < indentation) { + indentString += spaceStr(indentation - pos); + } + if (indentString != curSpaceString) { + replaceRange( + doc, + indentString, + Pos(n, 0), + Pos(n, curSpaceString.length), + "+input" + ); + line.stateAfter = null; + return true; + } else { + for (var i$12 = 0; i$12 < doc.sel.ranges.length; i$12++) { + var range2 = doc.sel.ranges[i$12]; + if ( + range2.head.line == n && + range2.head.ch < curSpaceString.length + ) { + var pos$1 = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i$12, new Range(pos$1, pos$1)); + break; + } + } + } + } + var lastCopied = null; + function setLastCopied(newLastCopied) { + lastCopied = newLastCopied; + } + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) { + sel = doc.sel; + } + var recent = +(/* @__PURE__ */ new Date()) - 200; + var paste = + origin == "paste" || cm.state.pasteIncoming > recent; + var textLines = splitLinesAuto(inserted), + multiPaste = null; + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i2 = 0; i2 < lastCopied.text.length; i2++) { + multiPaste.push(doc.splitLines(lastCopied.text[i2])); + } + } + } else if ( + textLines.length == sel.ranges.length && + cm.options.pasteLinesPerSelection + ) { + multiPaste = map(textLines, function (l) { + return [l]; + }); + } + } + var updateInput = cm.curOp.updateInput; + for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) { + var range2 = sel.ranges[i$12]; + var from = range2.from(), + to = range2.to(); + if (range2.empty()) { + if (deleted && deleted > 0) { + from = Pos(from.line, from.ch - deleted); + } else if (cm.state.overwrite && !paste) { + to = Pos( + to.line, + Math.min( + getLine(doc, to.line).text.length, + to.ch + lst(textLines).length + ) + ); + } else if ( + paste && + lastCopied && + lastCopied.lineWise && + lastCopied.text.join("\n") == textLines.join("\n") + ) { + from = to = Pos(from.line, 0); + } + } + var changeEvent = { + from, + to, + text: multiPaste + ? multiPaste[i$12 % multiPaste.length] + : textLines, + origin: + origin || + (paste + ? "paste" + : cm.state.cutIncoming > recent + ? "cut" + : "+input"), + }; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) { + triggerElectric(cm, inserted); + } + ensureCursorVisible(cm); + if (cm.curOp.updateInput < 2) { + cm.curOp.updateInput = updateInput; + } + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = -1; + } + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput) { + runInOp(cm, function () { + return applyTextInput(cm, pasted, 0, null, "paste"); + }); + } + return true; + } + } + function triggerElectric(cm, inserted) { + if (!cm.options.electricChars || !cm.options.smartIndent) { + return; + } + var sel = cm.doc.sel; + for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { + var range2 = sel.ranges[i2]; + if ( + range2.head.ch > 100 || + (i2 && sel.ranges[i2 - 1].head.line == range2.head.line) + ) { + continue; + } + var mode = cm.getModeAt(range2.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range2.head.line, "smart"); + break; + } + } + } else if (mode.electricInput) { + if ( + mode.electricInput.test( + getLine(cm.doc, range2.head.line).text.slice( + 0, + range2.head.ch + ) + ) + ) { + indented = indentLine(cm, range2.head.line, "smart"); + } + } + if (indented) { + signalLater(cm, "electricInput", cm, range2.head.line); + } + } + } + function copyableRanges(cm) { + var text = [], + ranges = []; + for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { + var line = cm.doc.sel.ranges[i2].head.line; + var lineRange = { + anchor: Pos(line, 0), + head: Pos(line + 1, 0), + }; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return { + text, + ranges, + }; + } + function disableBrowserMagic( + field, + spellcheck, + autocorrect, + autocapitalize + ) { + field.setAttribute("autocorrect", autocorrect ? "" : "off"); + field.setAttribute( + "autocapitalize", + autocapitalize ? "" : "off" + ); + field.setAttribute("spellcheck", !!spellcheck); + } + function hiddenTextarea() { + var te = elt( + "textarea", + null, + null, + "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none" + ); + var div = elt( + "div", + [te], + null, + "overflow: hidden; position: relative; width: 3px; height: 0px;" + ); + if (webkit) { + te.style.width = "1000px"; + } else { + te.setAttribute("wrap", "off"); + } + if (ios) { + te.style.border = "1px solid black"; + } + disableBrowserMagic(te); + return div; + } + function addEditorMethods(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + var helpers = (CodeMirror2.helpers = {}); + CodeMirror2.prototype = { + constructor: CodeMirror2, + focus: function () { + window.focus(); + this.display.input.focus(); + }, + setOption: function (option, value) { + var options = this.options, + old = options[option]; + if (options[option] == value && option != "mode") { + return; + } + options[option] = value; + if (optionHandlers2.hasOwnProperty(option)) { + operation(this, optionHandlers2[option])( + this, + value, + old + ); + } + signal(this, "optionChange", this, option); + }, + getOption: function (option) { + return this.options[option]; + }, + getDoc: function () { + return this.doc; + }, + addKeyMap: function (map2, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"]( + getKeyMap(map2) + ); + }, + removeKeyMap: function (map2) { + var maps = this.state.keyMaps; + for (var i2 = 0; i2 < maps.length; ++i2) { + if (maps[i2] == map2 || maps[i2].name == map2) { + maps.splice(i2, 1); + return true; + } + } + }, + addOverlay: methodOp(function (spec, options) { + var mode = spec.token + ? spec + : CodeMirror2.getMode(this.options, spec); + if (mode.startState) { + throw new Error("Overlays may not be stateful."); + } + insertSorted( + this.state.overlays, + { + mode, + modeSpec: spec, + opaque: options && options.opaque, + priority: (options && options.priority) || 0, + }, + function (overlay) { + return overlay.priority; + } + ); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function (spec) { + var overlays = this.state.overlays; + for (var i2 = 0; i2 < overlays.length; ++i2) { + var cur = overlays[i2].modeSpec; + if ( + cur == spec || + (typeof spec == "string" && cur.name == spec) + ) { + overlays.splice(i2, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + indentLine: methodOp(function (n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { + dir = this.options.smartIndent ? "smart" : "prev"; + } else { + dir = dir ? "add" : "subtract"; + } + } + if (isLine(this.doc, n)) { + indentLine(this, n, dir, aggressive); + } + }), + indentSelection: methodOp(function (how) { + var ranges = this.doc.sel.ranges, + end = -1; + for (var i2 = 0; i2 < ranges.length; i2++) { + var range2 = ranges[i2]; + if (!range2.empty()) { + var from = range2.from(), + to = range2.to(); + var start = Math.max(end, from.line); + end = + Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + + 1; + for (var j = start; j < end; ++j) { + indentLine(this, j, how); + } + var newRanges = this.doc.sel.ranges; + if ( + from.ch == 0 && + ranges.length == newRanges.length && + newRanges[i2].from().ch > 0 + ) { + replaceOneSelection( + this.doc, + i2, + new Range(from, newRanges[i2].to()), + sel_dontScroll + ); + } + } else if (range2.head.line > end) { + indentLine(this, range2.head.line, how, true); + end = range2.head.line; + if (i2 == this.doc.sel.primIndex) { + ensureCursorVisible(this); + } + } + } + }), + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function (pos, precise) { + return takeToken(this, pos, precise); + }, + getLineTokens: function (line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + getTokenTypeAt: function (pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles( + this, + getLine(this.doc, pos.line) + ); + var before = 0, + after = (styles.length - 1) / 2, + ch = pos.ch; + var type; + if (ch == 0) { + type = styles[2]; + } else { + for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { + after = mid; + } else if (styles[mid * 2 + 1] < ch) { + before = mid + 1; + } else { + type = styles[mid * 2 + 2]; + break; + } + } + } + var cut = type ? type.indexOf("overlay ") : -1; + return cut < 0 + ? type + : cut == 0 + ? null + : type.slice(0, cut - 1); + }, + getModeAt: function (pos) { + var mode = this.doc.mode; + if (!mode.innerMode) { + return mode; + } + return CodeMirror2.innerMode( + mode, + this.getTokenAt(pos).state + ).mode; + }, + getHelper: function (pos, type) { + return this.getHelpers(pos, type)[0]; + }, + getHelpers: function (pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) { + return found; + } + var help = helpers[type], + mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) { + found.push(help[mode[type]]); + } + } else if (mode[type]) { + for (var i2 = 0; i2 < mode[type].length; i2++) { + var val = help[mode[type][i2]]; + if (val) { + found.push(val); + } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i$12 = 0; i$12 < help._global.length; i$12++) { + var cur = help._global[i$12]; + if ( + cur.pred(mode, this) && + indexOf(found, cur.val) == -1 + ) { + found.push(cur.val); + } + } + return found; + }, + getStateAfter: function (line, precise) { + var doc = this.doc; + line = clipLine( + doc, + line == null ? doc.first + doc.size - 1 : line + ); + return getContextBefore(this, line + 1, precise).state; + }, + cursorCoords: function (start, mode) { + var pos, + range2 = this.doc.sel.primary(); + if (start == null) { + pos = range2.head; + } else if (typeof start == "object") { + pos = clipPos(this.doc, start); + } else { + pos = start ? range2.from() : range2.to(); + } + return cursorCoords(this, pos, mode || "page"); + }, + charCoords: function (pos, mode) { + return charCoords( + this, + clipPos(this.doc, pos), + mode || "page" + ); + }, + coordsChar: function (coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + lineAtHeight: function (height, mode) { + height = fromCoordSystem( + this, + { + top: height, + left: 0, + }, + mode || "page" + ).top; + return lineAtHeight( + this.doc, + height + this.display.viewOffset + ); + }, + heightAtLine: function (line, mode, includeWidgets) { + var end = false, + lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) { + line = this.doc.first; + } else if (line > last) { + line = last; + end = true; + } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return ( + intoCoordSystem( + this, + lineObj, + { + top: 0, + left: 0, + }, + mode || "page", + includeWidgets || end + ).top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) + ); + }, + defaultTextHeight: function () { + return textHeight(this.display); + }, + defaultCharWidth: function () { + return charWidth(this.display); + }, + getViewport: function () { + return { + from: this.display.viewFrom, + to: this.display.viewTo, + }; + }, + addWidget: function (pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, + left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max( + display.wrapper.clientHeight, + this.doc.height + ), + hspace = Math.max( + display.sizer.clientWidth, + display.lineSpace.clientWidth + ); + if ( + (vert == "above" || + pos.bottom + node.offsetHeight > vspace) && + pos.top > node.offsetHeight + ) { + top = pos.top - node.offsetHeight; + } else if (pos.bottom + node.offsetHeight <= vspace) { + top = pos.bottom; + } + if (left + node.offsetWidth > hspace) { + left = hspace - node.offsetWidth; + } + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") { + left = 0; + } else if (horiz == "middle") { + left = + (display.sizer.clientWidth - node.offsetWidth) / 2; + } + node.style.left = left + "px"; + } + if (scroll) { + scrollIntoView(this, { + left, + top, + right: left + node.offsetWidth, + bottom: top + node.offsetHeight, + }); + } + }, + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + execCommand: function (cmd) { + if (commands.hasOwnProperty(cmd)) { + return commands[cmd].call(null, this); + } + }, + triggerElectric: methodOp(function (text) { + triggerElectric(this, text); + }), + findPosH: function (from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveH: methodOp(function (dir, unit) { + var this$1$1 = this; + this.extendSelectionsBy(function (range2) { + if ( + this$1$1.display.shift || + this$1$1.doc.extend || + range2.empty() + ) { + return findPosH( + this$1$1.doc, + range2.head, + dir, + unit, + this$1$1.options.rtlMoveVisually + ); + } else { + return dir < 0 ? range2.from() : range2.to(); + } + }, sel_move); + }), + deleteH: methodOp(function (dir, unit) { + var sel = this.doc.sel, + doc = this.doc; + if (sel.somethingSelected()) { + doc.replaceSelection("", null, "+delete"); + } else { + deleteNearSelection(this, function (range2) { + var other = findPosH( + doc, + range2.head, + dir, + unit, + false + ); + return dir < 0 + ? { + from: other, + to: range2.head, + } + : { + from: range2.head, + to: other, + }; + }); + } + }), + findPosV: function (from, amount, unit, goalColumn) { + var dir = 1, + x = goalColumn; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) { + x = coords.left; + } else { + coords.left = x; + } + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveV: methodOp(function (dir, unit) { + var this$1$1 = this; + var doc = this.doc, + goals = []; + var collapse = + !this.display.shift && + !doc.extend && + doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range2) { + if (collapse) { + return dir < 0 ? range2.from() : range2.to(); + } + var headPos = cursorCoords(this$1$1, range2.head, "div"); + if (range2.goalColumn != null) { + headPos.left = range2.goalColumn; + } + goals.push(headPos.left); + var pos = findPosV(this$1$1, headPos, dir, unit); + if (unit == "page" && range2 == doc.sel.primary()) { + addToScrollTop( + this$1$1, + charCoords(this$1$1, pos, "div").top - headPos.top + ); + } + return pos; + }, sel_move); + if (goals.length) { + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + doc.sel.ranges[i2].goalColumn = goals[i2]; + } + } + }), + // Find the word at the given position (as returned by coordsChar). + findWordAt: function (pos) { + var doc = this.doc, + line = getLine(doc, pos.line).text; + var start = pos.ch, + end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ( + (pos.sticky == "before" || end == line.length) && + start + ) { + --start; + } else { + ++end; + } + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function (ch) { + return isWordChar(ch, helper); + } + : /\s/.test(startChar) + ? function (ch) { + return /\s/.test(ch); + } + : function (ch) { + return !/\s/.test(ch) && !isWordChar(ch); + }; + while (start > 0 && check(line.charAt(start - 1))) { + --start; + } + while (end < line.length && check(line.charAt(end))) { + ++end; + } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + toggleOverwrite: function (value) { + if (value != null && value == this.state.overwrite) { + return; + } + if ((this.state.overwrite = !this.state.overwrite)) { + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); + } else { + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); + } + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function () { + return this.display.input.getField() == activeElt(); + }, + isReadOnly: function () { + return !!(this.options.readOnly || this.doc.cantEdit); + }, + scrollTo: methodOp(function (x, y) { + scrollToCoords(this, x, y); + }), + getScrollInfo: function () { + var scroller = this.display.scroller; + return { + left: scroller.scrollLeft, + top: scroller.scrollTop, + height: + scroller.scrollHeight - + scrollGap(this) - + this.display.barHeight, + width: + scroller.scrollWidth - + scrollGap(this) - + this.display.barWidth, + clientHeight: displayHeight(this), + clientWidth: displayWidth(this), + }; + }, + scrollIntoView: methodOp(function (range2, margin) { + if (range2 == null) { + range2 = { + from: this.doc.sel.primary().head, + to: null, + }; + if (margin == null) { + margin = this.options.cursorScrollMargin; + } + } else if (typeof range2 == "number") { + range2 = { + from: Pos(range2, 0), + to: null, + }; + } else if (range2.from == null) { + range2 = { + from: range2, + to: null, + }; + } + if (!range2.to) { + range2.to = range2.from; + } + range2.margin = margin || 0; + if (range2.from.line != null) { + scrollToRange(this, range2); + } else { + scrollToCoordsRange( + this, + range2.from, + range2.to, + range2.margin + ); + } + }), + setSize: methodOp(function (width, height) { + var this$1$1 = this; + var interpret = function (val) { + return typeof val == "number" || /^\d+$/.test(String(val)) + ? val + "px" + : val; + }; + if (width != null) { + this.display.wrapper.style.width = interpret(width); + } + if (height != null) { + this.display.wrapper.style.height = interpret(height); + } + if (this.options.lineWrapping) { + clearLineMeasurementCache(this); + } + var lineNo2 = this.display.viewFrom; + this.doc.iter( + lineNo2, + this.display.viewTo, + function (line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].noHScroll) { + regLineChange(this$1$1, lineNo2, "widget"); + break; + } + } + } + ++lineNo2; + } + ); + this.curOp.forceUpdate = true; + signal(this, "refresh", this); + }), + operation: function (f) { + return runInOp(this, f); + }, + startOperation: function () { + return startOperation(this); + }, + endOperation: function () { + return endOperation(this); + }, + refresh: methodOp(function () { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + scrollToCoords( + this, + this.doc.scrollLeft, + this.doc.scrollTop + ); + updateGutterSpace(this.display); + if ( + oldHeight == null || + Math.abs(oldHeight - textHeight(this.display)) > 0.5 || + this.options.lineWrapping + ) { + estimateLineHeights(this); + } + signal(this, "refresh", this); + }), + swapDoc: methodOp(function (doc) { + var old = this.doc; + old.cm = null; + if (this.state.selectingText) { + this.state.selectingText(); + } + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + scrollToCoords(this, doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + phrase: function (phraseText) { + var phrases = this.options.phrases; + return phrases && + Object.prototype.hasOwnProperty.call(phrases, phraseText) + ? phrases[phraseText] + : phraseText; + }, + getInputField: function () { + return this.display.input.getField(); + }, + getWrapperElement: function () { + return this.display.wrapper; + }, + getScrollerElement: function () { + return this.display.scroller; + }, + getGutterElement: function () { + return this.display.gutters; + }, + }; + eventMixin(CodeMirror2); + CodeMirror2.registerHelper = function (type, name, value) { + if (!helpers.hasOwnProperty(type)) { + helpers[type] = CodeMirror2[type] = { + _global: [], + }; + } + helpers[type][name] = value; + }; + CodeMirror2.registerGlobalHelper = function ( + type, + name, + predicate, + value + ) { + CodeMirror2.registerHelper(type, name, value); + helpers[type]._global.push({ + pred: predicate, + val: value, + }); + }; + } + function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos; + var origDir = dir; + var lineObj = getLine(doc, pos.line); + var lineDir = visually && doc.direction == "rtl" ? -dir : dir; + function findNextLine() { + var l = pos.line + lineDir; + if (l < doc.first || l >= doc.first + doc.size) { + return false; + } + pos = new Pos(l, pos.ch, pos.sticky); + return (lineObj = getLine(doc, l)); + } + function moveOnce(boundToLine) { + var next; + if (unit == "codepoint") { + var ch = lineObj.text.charCodeAt( + pos.ch + (dir > 0 ? 0 : -1) + ); + if (isNaN(ch)) { + next = null; + } else { + var astral = + dir > 0 + ? ch >= 55296 && ch < 56320 + : ch >= 56320 && ch < 57343; + next = new Pos( + pos.line, + Math.max( + 0, + Math.min( + lineObj.text.length, + pos.ch + dir * (astral ? 2 : 1) + ) + ), + -dir + ); + } + } else if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir); + } else { + next = moveLogically(lineObj, pos, dir); + } + if (next == null) { + if (!boundToLine && findNextLine()) { + pos = endOfLine( + visually, + doc.cm, + lineObj, + pos.line, + lineDir + ); + } else { + return false; + } + } else { + pos = next; + } + return true; + } + if (unit == "char" || unit == "codepoint") { + moveOnce(); + } else if (unit == "column") { + moveOnce(true); + } else if (unit == "word" || unit == "group") { + var sawType = null, + group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true; ; first = false) { + if (dir < 0 && !moveOnce(!first)) { + break; + } + var cur = lineObj.text.charAt(pos.ch) || "\n"; + var type = isWordChar(cur, helper) + ? "w" + : group && cur == "\n" + ? "n" + : !group || /\s/.test(cur) + ? null + : "p"; + if (group && !first && !type) { + type = "s"; + } + if (sawType && sawType != type) { + if (dir < 0) { + dir = 1; + moveOnce(); + pos.sticky = "after"; + } + break; + } + if (type) { + sawType = type; + } + if (dir > 0 && !moveOnce(!first)) { + break; + } + } + } + var result = skipAtomic(doc, pos, oldPos, origDir, true); + if (equalCursorPos(oldPos, result)) { + result.hitSide = true; + } + return result; + } + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, + x = pos.left, + y; + if (unit == "page") { + var pageSize = Math.min( + cm.display.wrapper.clientHeight, + window.innerHeight || document.documentElement.clientHeight + ); + var moveAmount = Math.max( + pageSize - 0.5 * textHeight(cm.display), + 3 + ); + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + var target; + for (;;) { + target = coordsChar(cm, x, y); + if (!target.outside) { + break; + } + if (dir < 0 ? y <= 0 : y >= doc.height) { + target.hitSide = true; + break; + } + y += dir * 5; + } + return target; + } + var ContentEditableInput = function (cm) { + this.cm = cm; + this.lastAnchorNode = + this.lastAnchorOffset = + this.lastFocusNode = + this.lastFocusOffset = + null; + this.polling = new Delayed(); + this.composing = null; + this.gracePeriod = false; + this.readDOMTimeout = null; + }; + ContentEditableInput.prototype.init = function (display) { + var this$1$1 = this; + var input = this, + cm = input.cm; + var div = (input.div = display.lineDiv); + div.contentEditable = true; + disableBrowserMagic( + div, + cm.options.spellcheck, + cm.options.autocorrect, + cm.options.autocapitalize + ); + function belongsToInput(e) { + for (var t = e.target; t; t = t.parentNode) { + if (t == div) { + return true; + } + if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { + break; + } + } + return false; + } + on(div, "paste", function (e) { + if ( + !belongsToInput(e) || + signalDOMEvent(cm, e) || + handlePaste(e, cm) + ) { + return; + } + if (ie_version <= 11) { + setTimeout( + operation(cm, function () { + return this$1$1.updateFromDOM(); + }), + 20 + ); + } + }); + on(div, "compositionstart", function (e) { + this$1$1.composing = { + data: e.data, + done: false, + }; + }); + on(div, "compositionupdate", function (e) { + if (!this$1$1.composing) { + this$1$1.composing = { + data: e.data, + done: false, + }; + } + }); + on(div, "compositionend", function (e) { + if (this$1$1.composing) { + if (e.data != this$1$1.composing.data) { + this$1$1.readFromDOMSoon(); + } + this$1$1.composing.done = true; + } + }); + on(div, "touchstart", function () { + return input.forceCompositionEnd(); + }); + on(div, "input", function () { + if (!this$1$1.composing) { + this$1$1.readFromDOMSoon(); + } + }); + function onCopyCut(e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ + lineWise: false, + text: cm.getSelections(), + }); + if (e.type == "cut") { + cm.replaceSelection("", null, "cut"); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ + lineWise: true, + text: ranges.text, + }); + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + if (e.clipboardData) { + e.clipboardData.clearData(); + var content = lastCopied.text.join("\n"); + e.clipboardData.setData("Text", content); + if (e.clipboardData.getData("Text") == content) { + e.preventDefault(); + return; + } + } + var kludge = hiddenTextarea(), + te = kludge.firstChild; + cm.display.lineSpace.insertBefore( + kludge, + cm.display.lineSpace.firstChild + ); + te.value = lastCopied.text.join("\n"); + var hadFocus = activeElt(); + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + if (hadFocus == div) { + input.showPrimarySelection(); + } + }, 50); + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }; + ContentEditableInput.prototype.screenReaderLabelChanged = + function (label) { + if (label) { + this.div.setAttribute("aria-label", label); + } else { + this.div.removeAttribute("aria-label"); + } + }; + ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false); + result.focus = activeElt() == this.div; + return result; + }; + ContentEditableInput.prototype.showSelection = function ( + info, + takeFocus + ) { + if (!info || !this.cm.display.view.length) { + return; + } + if (info.focus || takeFocus) { + this.showPrimarySelection(); + } + this.showMultipleSelections(info); + }; + ContentEditableInput.prototype.getSelection = function () { + return this.cm.display.wrapper.ownerDocument.getSelection(); + }; + ContentEditableInput.prototype.showPrimarySelection = + function () { + var sel = this.getSelection(), + cm = this.cm, + prim = cm.doc.sel.primary(); + var from = prim.from(), + to = prim.to(); + if ( + cm.display.viewTo == cm.display.viewFrom || + from.line >= cm.display.viewTo || + to.line < cm.display.viewFrom + ) { + sel.removeAllRanges(); + return; + } + var curAnchor = domToPos( + cm, + sel.anchorNode, + sel.anchorOffset + ); + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); + if ( + curAnchor && + !curAnchor.bad && + curFocus && + !curFocus.bad && + cmp(minPos(curAnchor, curFocus), from) == 0 && + cmp(maxPos(curAnchor, curFocus), to) == 0 + ) { + return; + } + var view = cm.display.view; + var start = (from.line >= cm.display.viewFrom && + posToDOM(cm, from)) || { + node: view[0].measure.map[2], + offset: 0, + }; + var end = to.line < cm.display.viewTo && posToDOM(cm, to); + if (!end) { + var measure = view[view.length - 1].measure; + var map2 = measure.maps + ? measure.maps[measure.maps.length - 1] + : measure.map; + end = { + node: map2[map2.length - 1], + offset: map2[map2.length - 2] - map2[map2.length - 3], + }; + } + if (!start || !end) { + sel.removeAllRanges(); + return; + } + var old = sel.rangeCount && sel.getRangeAt(0), + rng; + try { + rng = range(start.node, start.offset, end.offset, end.node); + } catch (e) {} + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) { + sel.removeAllRanges(); + sel.addRange(rng); + } + } else { + sel.removeAllRanges(); + sel.addRange(rng); + } + if (old && sel.anchorNode == null) { + sel.addRange(old); + } else if (gecko) { + this.startGracePeriod(); + } + } + this.rememberSelection(); + }; + ContentEditableInput.prototype.startGracePeriod = function () { + var this$1$1 = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + this$1$1.gracePeriod = false; + if (this$1$1.selectionChanged()) { + this$1$1.cm.operation(function () { + return (this$1$1.cm.curOp.selectionChanged = true); + }); + } + }, 20); + }; + ContentEditableInput.prototype.showMultipleSelections = function ( + info + ) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd( + this.cm.display.selectionDiv, + info.selection + ); + }; + ContentEditableInput.prototype.rememberSelection = function () { + var sel = this.getSelection(); + this.lastAnchorNode = sel.anchorNode; + this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; + this.lastFocusOffset = sel.focusOffset; + }; + ContentEditableInput.prototype.selectionInEditor = function () { + var sel = this.getSelection(); + if (!sel.rangeCount) { + return false; + } + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }; + ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor() || activeElt() != this.div) { + this.showSelection(this.prepareSelection(), true); + } + this.div.focus(); + } + }; + ContentEditableInput.prototype.blur = function () { + this.div.blur(); + }; + ContentEditableInput.prototype.getField = function () { + return this.div; + }; + ContentEditableInput.prototype.supportsTouch = function () { + return true; + }; + ContentEditableInput.prototype.receivedFocus = function () { + var this$1$1 = this; + var input = this; + if (this.selectionInEditor()) { + setTimeout(function () { + return this$1$1.pollSelection(); + }, 20); + } else { + runInOp(this.cm, function () { + return (input.cm.curOp.selectionChanged = true); + }); + } + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }; + ContentEditableInput.prototype.selectionChanged = function () { + var sel = this.getSelection(); + return ( + sel.anchorNode != this.lastAnchorNode || + sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || + sel.focusOffset != this.lastFocusOffset + ); + }; + ContentEditableInput.prototype.pollSelection = function () { + if ( + this.readDOMTimeout != null || + this.gracePeriod || + !this.selectionChanged() + ) { + return; + } + var sel = this.getSelection(), + cm = this.cm; + if ( + android && + chrome && + this.cm.display.gutterSpecs.length && + isInGutter(sel.anchorNode) + ) { + this.cm.triggerOnKeyDown({ + type: "keydown", + keyCode: 8, + preventDefault: Math.abs, + }); + this.blur(); + this.focus(); + return; + } + if (this.composing) { + return; + } + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function () { + setSelection( + cm.doc, + simpleSelection(anchor, head), + sel_dontScroll + ); + if (anchor.bad || head.bad) { + cm.curOp.selectionChanged = true; + } + }); + } + }; + ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout); + this.readDOMTimeout = null; + } + var cm = this.cm, + display = cm.display, + sel = cm.doc.sel.primary(); + var from = sel.from(), + to = sel.to(); + if (from.ch == 0 && from.line > cm.firstLine()) { + from = Pos( + from.line - 1, + getLine(cm.doc, from.line - 1).length + ); + } + if ( + to.ch == getLine(cm.doc, to.line).text.length && + to.line < cm.lastLine() + ) { + to = Pos(to.line + 1, 0); + } + if ( + from.line < display.viewFrom || + to.line > display.viewTo - 1 + ) { + return false; + } + var fromIndex, fromLine, fromNode; + if ( + from.line == display.viewFrom || + (fromIndex = findViewIndex(cm, from.line)) == 0 + ) { + fromLine = lineNo(display.view[0].line); + fromNode = display.view[0].node; + } else { + fromLine = lineNo(display.view[fromIndex].line); + fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + var toLine, toNode; + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1; + toNode = display.lineDiv.lastChild; + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1; + toNode = display.view[toIndex + 1].node.previousSibling; + } + if (!fromNode) { + return false; + } + var newText = cm.doc.splitLines( + domTextBetween(cm, fromNode, toNode, fromLine, toLine) + ); + var oldText = getBetween( + cm.doc, + Pos(fromLine, 0), + Pos(toLine, getLine(cm.doc, toLine).text.length) + ); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { + newText.pop(); + oldText.pop(); + toLine--; + } else if (newText[0] == oldText[0]) { + newText.shift(); + oldText.shift(); + fromLine++; + } else { + break; + } + } + var cutFront = 0, + cutEnd = 0; + var newTop = newText[0], + oldTop = oldText[0], + maxCutFront = Math.min(newTop.length, oldTop.length); + while ( + cutFront < maxCutFront && + newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront) + ) { + ++cutFront; + } + var newBot = lst(newText), + oldBot = lst(oldText); + var maxCutEnd = Math.min( + newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0) + ); + while ( + cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == + oldBot.charCodeAt(oldBot.length - cutEnd - 1) + ) { + ++cutEnd; + } + if ( + newText.length == 1 && + oldText.length == 1 && + fromLine == from.line + ) { + while ( + cutFront && + cutFront > from.ch && + newBot.charCodeAt(newBot.length - cutEnd - 1) == + oldBot.charCodeAt(oldBot.length - cutEnd - 1) + ) { + cutFront--; + cutEnd++; + } + } + newText[newText.length - 1] = newBot + .slice(0, newBot.length - cutEnd) + .replace(/^\u200b+/, ""); + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos( + toLine, + oldText.length ? lst(oldText).length - cutEnd : 0 + ); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }; + ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { + return; + } + clearTimeout(this.readDOMTimeout); + this.composing = null; + this.updateFromDOM(); + this.div.blur(); + this.div.focus(); + }; + ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1$1 = this; + if (this.readDOMTimeout != null) { + return; + } + this.readDOMTimeout = setTimeout(function () { + this$1$1.readDOMTimeout = null; + if (this$1$1.composing) { + if (this$1$1.composing.done) { + this$1$1.composing = null; + } else { + return; + } + } + this$1$1.updateFromDOM(); + }, 80); + }; + ContentEditableInput.prototype.updateFromDOM = function () { + var this$1$1 = this; + if (this.cm.isReadOnly() || !this.pollContent()) { + runInOp(this.cm, function () { + return regChange(this$1$1.cm); + }); + } + }; + ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false"; + }; + ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0 || this.composing) { + return; + } + e.preventDefault(); + if (!this.cm.isReadOnly()) { + operation(this.cm, applyTextInput)( + this.cm, + String.fromCharCode( + e.charCode == null ? e.keyCode : e.charCode + ), + 0 + ); + } + }; + ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor"); + }; + ContentEditableInput.prototype.onContextMenu = function () {}; + ContentEditableInput.prototype.resetPosition = function () {}; + ContentEditableInput.prototype.needsContentAttribute = true; + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) { + return null; + } + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + var order = getOrder(line, cm.doc.direction), + side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = + result.collapse == "right" ? result.end : result.start; + return result; + } + function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) { + if (/CodeMirror-gutter-wrapper/.test(scan.className)) { + return true; + } + } + return false; + } + function badPos(pos, bad) { + if (bad) { + pos.bad = true; + } + return pos; + } + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", + closing = false, + lineSep = cm.doc.lineSeparator(), + extraLinebreak = false; + function recognizeMarker(id) { + return function (marker) { + return marker.id == id; + }; + } + function close() { + if (closing) { + text += lineSep; + if (extraLinebreak) { + text += lineSep; + } + closing = extraLinebreak = false; + } + } + function addText(str) { + if (str) { + close(); + text += str; + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText) { + addText(cmText); + return; + } + var markerID = node.getAttribute("cm-marker"), + range2; + if (markerID) { + var found = cm.findMarks( + Pos(fromLine, 0), + Pos(toLine + 1, 0), + recognizeMarker(+markerID) + ); + if (found.length && (range2 = found[0].find(0))) { + addText( + getBetween(cm.doc, range2.from, range2.to).join( + lineSep + ) + ); + } + return; + } + if (node.getAttribute("contenteditable") == "false") { + return; + } + var isBlock = /^(pre|div|p|li|table|br)$/i.test( + node.nodeName + ); + if ( + !/^br$/i.test(node.nodeName) && + node.textContent.length == 0 + ) { + return; + } + if (isBlock) { + close(); + } + for (var i2 = 0; i2 < node.childNodes.length; i2++) { + walk(node.childNodes[i2]); + } + if (/^(pre|p)$/i.test(node.nodeName)) { + extraLinebreak = true; + } + if (isBlock) { + closing = true; + } + } else if (node.nodeType == 3) { + addText( + node.nodeValue + .replace(/\u200b/g, "") + .replace(/\u00a0/g, " ") + ); + } + } + for (;;) { + walk(from); + if (from == to) { + break; + } + from = from.nextSibling; + extraLinebreak = false; + } + return text; + } + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) { + return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + } + node = null; + offset = 0; + } else { + for (lineNode = node; ; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { + return null; + } + if ( + lineNode.parentNode && + lineNode.parentNode == cm.display.lineDiv + ) { + break; + } + } + } + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + var lineView = cm.display.view[i2]; + if (lineView.node == lineNode) { + return locateNodeInLineView(lineView, node, offset); + } + } + } + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, + bad = false; + if (!node || !contains(wrapper, node)) { + return badPos(Pos(lineNo(lineView.line), 0), true); + } + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest + ? lst(lineView.rest) + : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + var textNode = node.nodeType == 3 ? node : null, + topNode = node; + if ( + !textNode && + node.childNodes.length == 1 && + node.firstChild.nodeType == 3 + ) { + textNode = node.firstChild; + if (offset) { + offset = textNode.nodeValue.length; + } + } + while (topNode.parentNode != wrapper) { + topNode = topNode.parentNode; + } + var measure = lineView.measure, + maps = measure.maps; + function find(textNode2, topNode2, offset2) { + for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { + var map2 = i2 < 0 ? measure.map : maps[i2]; + for (var j = 0; j < map2.length; j += 3) { + var curNode = map2[j + 2]; + if (curNode == textNode2 || curNode == topNode2) { + var line2 = lineNo( + i2 < 0 ? lineView.line : lineView.rest[i2] + ); + var ch = map2[j] + offset2; + if (offset2 < 0 || curNode != textNode2) { + ch = map2[j + (offset2 ? 1 : 0)]; + } + return Pos(line2, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) { + return badPos(found, bad); + } + for ( + var after = topNode.nextSibling, + dist = textNode ? textNode.nodeValue.length - offset : 0; + after; + after = after.nextSibling + ) { + found = find(after, after.firstChild, 0); + if (found) { + return badPos(Pos(found.line, found.ch - dist), bad); + } else { + dist += after.textContent.length; + } + } + for ( + var before = topNode.previousSibling, dist$1 = offset; + before; + before = before.previousSibling + ) { + found = find(before, before.firstChild, -1); + if (found) { + return badPos(Pos(found.line, found.ch + dist$1), bad); + } else { + dist$1 += before.textContent.length; + } + } + } + var TextareaInput = function (cm) { + this.cm = cm; + this.prevInput = ""; + this.pollingFast = false; + this.polling = new Delayed(); + this.hasSelection = false; + this.composing = null; + }; + TextareaInput.prototype.init = function (display) { + var this$1$1 = this; + var input = this, + cm = this.cm; + this.createField(display); + var te = this.textarea; + display.wrapper.insertBefore( + this.wrapper, + display.wrapper.firstChild + ); + if (ios) { + te.style.width = "0px"; + } + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1$1.hasSelection) { + this$1$1.hasSelection = null; + } + input.poll(); + }); + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; + } + cm.state.pasteIncoming = +(/* @__PURE__ */ new Date()); + input.fastPoll(); + }); + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ + lineWise: false, + text: cm.getSelections(), + }); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ + lineWise: true, + text: ranges.text, + }); + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") { + cm.state.cutIncoming = +(/* @__PURE__ */ new Date()); + } + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { + return; + } + if (!te.dispatchEvent) { + cm.state.pasteIncoming = +(/* @__PURE__ */ new Date()); + input.focus(); + return; + } + var event = new Event("paste"); + event.clipboardData = e.clipboardData; + te.dispatchEvent(event); + }); + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { + e_preventDefault(e); + } + }); + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + if (input.composing) { + input.composing.range.clear(); + } + input.composing = { + start, + range: cm.markText(start, cm.getCursor("to"), { + className: "CodeMirror-composing", + }), + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }; + TextareaInput.prototype.createField = function (_display) { + this.wrapper = hiddenTextarea(); + this.textarea = this.wrapper.firstChild; + }; + TextareaInput.prototype.screenReaderLabelChanged = function ( + label + ) { + if (label) { + this.textarea.setAttribute("aria-label", label); + } else { + this.textarea.removeAttribute("aria-label"); + } + }; + TextareaInput.prototype.prepareSelection = function () { + var cm = this.cm, + display = cm.display, + doc = cm.doc; + var result = prepareSelection(cm); + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), + lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max( + 0, + Math.min( + display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top + ) + ); + result.teLeft = Math.max( + 0, + Math.min( + display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left + ) + ); + } + return result; + }; + TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, + display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }; + TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending || this.composing) { + return; + } + var cm = this.cm; + if (cm.somethingSelected()) { + this.prevInput = ""; + var content = cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) { + selectInput(this.textarea); + } + if (ie && ie_version >= 9) { + this.hasSelection = content; + } + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) { + this.hasSelection = null; + } + } + }; + TextareaInput.prototype.getField = function () { + return this.textarea; + }; + TextareaInput.prototype.supportsTouch = function () { + return false; + }; + TextareaInput.prototype.focus = function () { + if ( + this.cm.options.readOnly != "nocursor" && + (!mobile || activeElt() != this.textarea) + ) { + try { + this.textarea.focus(); + } catch (e) {} + } + }; + TextareaInput.prototype.blur = function () { + this.textarea.blur(); + }; + TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }; + TextareaInput.prototype.receivedFocus = function () { + this.slowPoll(); + }; + TextareaInput.prototype.slowPoll = function () { + var this$1$1 = this; + if (this.pollingFast) { + return; + } + this.polling.set(this.cm.options.pollInterval, function () { + this$1$1.poll(); + if (this$1$1.cm.state.focused) { + this$1$1.slowPoll(); + } + }); + }; + TextareaInput.prototype.fastPoll = function () { + var missed = false, + input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) { + missed = true; + input.polling.set(60, p); + } else { + input.pollingFast = false; + input.slowPoll(); + } + } + input.polling.set(20, p); + }; + TextareaInput.prototype.poll = function () { + var this$1$1 = this; + var cm = this.cm, + input = this.textarea, + prevInput = this.prevInput; + if ( + this.contextMenuPending || + !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || + cm.options.disableInput || + cm.state.keySeq + ) { + return false; + } + var text = input.value; + if (text == prevInput && !cm.somethingSelected()) { + return false; + } + if ( + (ie && ie_version >= 9 && this.hasSelection === text) || + (mac && /[\uf700-\uf7ff]/.test(text)) + ) { + cm.display.input.reset(); + return false; + } + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 8203 && !prevInput) { + prevInput = "​"; + } + if (first == 8666) { + this.reset(); + return this.cm.execCommand("undo"); + } + } + var same = 0, + l = Math.min(prevInput.length, text.length); + while ( + same < l && + prevInput.charCodeAt(same) == text.charCodeAt(same) + ) { + ++same; + } + runInOp(cm, function () { + applyTextInput( + cm, + text.slice(same), + prevInput.length - same, + null, + this$1$1.composing ? "*compose" : null + ); + if (text.length > 1e3 || text.indexOf("\n") > -1) { + input.value = this$1$1.prevInput = ""; + } else { + this$1$1.prevInput = text; + } + if (this$1$1.composing) { + this$1$1.composing.range.clear(); + this$1$1.composing.range = cm.markText( + this$1$1.composing.start, + cm.getCursor("to"), + { + className: "CodeMirror-composing", + } + ); + } + }); + return true; + }; + TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { + this.pollingFast = false; + } + }; + TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { + this.hasSelection = null; + } + this.fastPoll(); + }; + TextareaInput.prototype.onContextMenu = function (e) { + var input = this, + cm = input.cm, + display = cm.display, + te = input.textarea; + if (input.contextMenuPending) { + input.contextMenuPending(); + } + var pos = posFromMouse(cm, e), + scrollPos = display.scroller.scrollTop; + if (!pos || presto) { + return; + } + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) { + operation(cm, setSelection)( + cm.doc, + simpleSelection(pos), + sel_dontScroll + ); + } + var oldCSS = te.style.cssText, + oldWrapperCSS = input.wrapper.style.cssText; + var wrapperBox = + input.wrapper.offsetParent.getBoundingClientRect(); + input.wrapper.style.cssText = "position: static"; + te.style.cssText = + "position: absolute; width: 30px; height: 30px;\n top: " + + (e.clientY - wrapperBox.top - 5) + + "px; left: " + + (e.clientX - wrapperBox.left - 5) + + "px;\n z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + var oldScrollY; + if (webkit) { + oldScrollY = window.scrollY; + } + display.input.focus(); + if (webkit) { + window.scrollTo(null, oldScrollY); + } + display.input.reset(); + if (!cm.somethingSelected()) { + te.value = input.prevInput = " "; + } + input.contextMenuPending = rehide; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "​" + (selected ? te.value : ""); + te.value = "⇚"; + te.value = extval; + input.prevInput = selected ? "" : "​"; + te.selectionStart = 1; + te.selectionEnd = extval.length; + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + if (input.contextMenuPending != rehide) { + return; + } + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) { + display.scrollbars.setScrollTop( + (display.scroller.scrollTop = scrollPos) + ); + } + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { + prepareSelectAllHack(); + } + var i2 = 0, + poll = function () { + if ( + display.selForContextMenu == cm.doc.sel && + te.selectionStart == 0 && + te.selectionEnd > 0 && + input.prevInput == "​" + ) { + operation(cm, selectAll)(cm); + } else if (i2++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500); + } else { + display.selForContextMenu = null; + display.input.reset(); + } + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + if (ie && ie_version >= 9) { + prepareSelectAllHack(); + } + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }; + TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { + this.reset(); + } + this.textarea.disabled = val == "nocursor"; + this.textarea.readOnly = !!val; + }; + TextareaInput.prototype.setUneditable = function () {}; + TextareaInput.prototype.needsContentAttribute = false; + function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) { + options.tabindex = textarea.tabIndex; + } + if (!options.placeholder && textarea.placeholder) { + options.placeholder = textarea.placeholder; + } + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = + hasFocus == textarea || + (textarea.getAttribute("autofocus") != null && + hasFocus == document.body); + } + function save() { + textarea.value = cm.getValue(); + } + var realSubmit; + if (textarea.form) { + on(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form; + realSubmit = form.submit; + try { + var wrappedSubmit = (form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }); + } catch (e) {} + } + } + options.finishInit = function (cm2) { + cm2.save = save; + cm2.getTextArea = function () { + return textarea; + }; + cm2.toTextArea = function () { + cm2.toTextArea = isNaN; + save(); + textarea.parentNode.removeChild(cm2.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if ( + !options.leaveSubmitMethodAlone && + typeof textarea.form.submit == "function" + ) { + textarea.form.submit = realSubmit; + } + } + }; + }; + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { + return textarea.parentNode.insertBefore( + node, + textarea.nextSibling + ); + }, options); + return cm; + } + function addLegacyProps(CodeMirror2) { + CodeMirror2.off = off; + CodeMirror2.on = on; + CodeMirror2.wheelEventPixels = wheelEventPixels; + CodeMirror2.Doc = Doc; + CodeMirror2.splitLines = splitLinesAuto; + CodeMirror2.countColumn = countColumn; + CodeMirror2.findColumn = findColumn; + CodeMirror2.isWordChar = isWordCharBasic; + CodeMirror2.Pass = Pass; + CodeMirror2.signal = signal; + CodeMirror2.Line = Line; + CodeMirror2.changeEnd = changeEnd; + CodeMirror2.scrollbarModel = scrollbarModel; + CodeMirror2.Pos = Pos; + CodeMirror2.cmpPos = cmp; + CodeMirror2.modes = modes; + CodeMirror2.mimeModes = mimeModes; + CodeMirror2.resolveMode = resolveMode; + CodeMirror2.getMode = getMode; + CodeMirror2.modeExtensions = modeExtensions; + CodeMirror2.extendMode = extendMode; + CodeMirror2.copyState = copyState; + CodeMirror2.startState = startState; + CodeMirror2.innerMode = innerMode; + CodeMirror2.commands = commands; + CodeMirror2.keyMap = keyMap; + CodeMirror2.keyName = keyName; + CodeMirror2.isModifierKey = isModifierKey; + CodeMirror2.lookupKey = lookupKey; + CodeMirror2.normalizeKeyMap = normalizeKeyMap; + CodeMirror2.StringStream = StringStream; + CodeMirror2.SharedTextMarker = SharedTextMarker; + CodeMirror2.TextMarker = TextMarker; + CodeMirror2.LineWidget = LineWidget; + CodeMirror2.e_preventDefault = e_preventDefault; + CodeMirror2.e_stopPropagation = e_stopPropagation; + CodeMirror2.e_stop = e_stop; + CodeMirror2.addClass = addClass; + CodeMirror2.contains = contains; + CodeMirror2.rmClass = rmClass; + CodeMirror2.keyNames = keyNames; + } + defineOptions(CodeMirror); + addEditorMethods(CodeMirror); + var dontDelegate = + "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if ( + Doc.prototype.hasOwnProperty(prop) && + indexOf(dontDelegate, prop) < 0 + ) { + CodeMirror.prototype[prop] = /* @__PURE__ */ (function ( + method + ) { + return function () { + return method.apply(this.doc, arguments); + }; + })(Doc.prototype[prop]); + } + } + eventMixin(Doc); + CodeMirror.inputStyles = { + textarea: TextareaInput, + contenteditable: ContentEditableInput, + }; + CodeMirror.defineMode = function (name) { + if (!CodeMirror.defaults.mode && name != "null") { + CodeMirror.defaults.mode = name; + } + defineMode.apply(this, arguments); + }; + CodeMirror.defineMIME = defineMIME; + CodeMirror.defineMode("null", function () { + return { + token: function (stream) { + return stream.skipToEnd(); + }, + }; + }); + CodeMirror.defineMIME("text/plain", "null"); + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.fromTextArea = fromTextArea; + addLegacyProps(CodeMirror); + CodeMirror.version = "5.65.3"; + return CodeMirror; }); - } + })(codemirror); + return codemirror.exports; } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var codemirrorExports = codemirror$1.requireCodemirror(); -const CodeMirror = /* @__PURE__ */codemirror$1.getDefaultExportFromCjs(codemirrorExports); -const codemirror = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: CodeMirror -}, [codemirrorExports]); -exports.CodeMirror = CodeMirror; -exports.codemirror = codemirror; - -/***/ }), - -/***/ "../../graphiql-react/dist/codemirror.cjs2.js": -/*!****************************************************!*\ - !*** ../../graphiql-react/dist/codemirror.cjs2.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - + exports.getDefaultExportFromCjs = getDefaultExportFromCjs; + exports.requireCodemirror = requireCodemirror; + /***/ + }, -var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : {}; -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; -} -var codemirror = { - exports: {} -}; -var hasRequiredCodemirror; -function requireCodemirror() { - if (hasRequiredCodemirror) return codemirror.exports; - hasRequiredCodemirror = 1; - (function (module2, exports2) { - (function (global2, factory) { - module2.exports = factory(); - })(commonjsGlobal, function () { - var userAgent = navigator.userAgent; - var platform = navigator.platform; - var gecko = /gecko\/\d/i.test(userAgent); - var ie_upto10 = /MSIE \d/.test(userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); - var edge = /Edge\/(\d+)/.exec(userAgent); - var ie = ie_upto10 || ie_11up || edge; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); - var webkit = !edge && /WebKit\//.test(userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); - var chrome = !edge && /Chrome\//.test(userAgent); - var presto = /Opera\//.test(userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); - var phantom = /PhantomJS/.test(userAgent); - var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); - var android = /Android/.test(userAgent); - var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); - var mac = ios || /Mac/.test(platform); - var chromeOS = /\bCrOS\b/.test(userAgent); - var windows = /win/i.test(platform); - var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) { - presto_version = Number(presto_version[1]); - } - if (presto_version && presto_version >= 15) { - presto = false; - webkit = true; - } - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || ie && ie_version >= 9; - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - var rmClass = function (node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) { - e.removeChild(e.firstChild); - } - return e; - } - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) { - e.className = className; - } - if (style) { - e.style.cssText = style; - } - if (typeof content == "string") { - e.appendChild(document.createTextNode(content)); - } else if (content) { - for (var i2 = 0; i2 < content.length; ++i2) { - e.appendChild(content[i2]); - } - } - return e; - } - function eltP(tag, content, className, style) { - var e = elt(tag, content, className, style); - e.setAttribute("role", "presentation"); - return e; - } - var range; - if (document.createRange) { - range = function (node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - } else { - range = function (node, start, end) { - var r = document.body.createTextRange(); - try { - r.moveToElementText(node.parentNode); - } catch (e) { - return r; - } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - } - function contains(parent, child) { - if (child.nodeType == 3) { - child = child.parentNode; - } - if (parent.contains) { - return parent.contains(child); - } - do { - if (child.nodeType == 11) { - child = child.host; - } - if (child == parent) { - return true; - } - } while (child = child.parentNode); - } - function activeElt() { - var activeElement; - try { - activeElement = document.activeElement; - } catch (e) { - activeElement = document.body || null; - } - while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { - activeElement = activeElement.shadowRoot.activeElement; - } - return activeElement; - } - function addClass(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) { - node.className += (current ? " " : "") + cls; - } - } - function joinClasses(a, b) { - var as = a.split(" "); - for (var i2 = 0; i2 < as.length; i2++) { - if (as[i2] && !classTest(as[i2]).test(b)) { - b += " " + as[i2]; + /***/ "../../graphiql-react/dist/comment.cjs.js": + /*!************************************************!*\ + !*** ../../graphiql-react/dist/comment.cjs.js ***! + \************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } + } } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - return b; - } - var selectInput = function (node) { - node.select(); - }; - if (ios) { - selectInput = function (node) { - node.selectionStart = 0; - node.selectionEnd = node.value.length; - }; - } else if (ie) { - selectInput = function (node) { - try { - node.select(); - } catch (_e) {} + var comment$2 = { + exports: {}, }; - } - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return f.apply(null, args); - }; - } - function copyObj(obj, target, overwrite) { - if (!target) { - target = {}; - } - for (var prop2 in obj) { - if (obj.hasOwnProperty(prop2) && (overwrite !== false || !target.hasOwnProperty(prop2))) { - target[prop2] = obj[prop2]; - } - } - return target; - } - function countColumn(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) { - end = string.length; - } - } - for (var i2 = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf(" ", i2); - if (nextTab < 0 || nextTab >= end) { - return n + (end - i2); - } - n += nextTab - i2; - n += tabSize - n % tabSize; - i2 = nextTab + 1; - } - } - var Delayed = function () { - this.id = null; - this.f = null; - this.time = 0; - this.handler = bind(this.onTimeout, this); - }; - Delayed.prototype.onTimeout = function (self2) { - self2.id = 0; - if (self2.time <= + /* @__PURE__ */new Date()) { - self2.f(); - } else { - setTimeout(self2.handler, self2.time - + /* @__PURE__ */new Date()); - } - }; - Delayed.prototype.set = function (ms, f) { - this.f = f; - var time = + /* @__PURE__ */new Date() + ms; - if (!this.id || time < this.time) { - clearTimeout(this.id); - this.id = setTimeout(this.handler, ms); - this.time = time; - } - }; - function indexOf(array, elt2) { - for (var i2 = 0; i2 < array.length; ++i2) { - if (array[i2] == elt2) { - return i2; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var noOptions = {}; + var nonWS = /[^\s\u00a0]/; + var Pos = CodeMirror.Pos, + cmp = CodeMirror.cmpPos; + function firstNonWS(str) { + var found = str.search(nonWS); + return found == -1 ? 0 : found; + } + CodeMirror.commands.toggleComment = function (cm) { + cm.toggleComment(); + }; + CodeMirror.defineExtension("toggleComment", function (options) { + if (!options) options = noOptions; + var cm = this; + var minLine = Infinity, + ranges = this.listSelections(), + mode = null; + for (var i = ranges.length - 1; i >= 0; i--) { + var from = ranges[i].from(), + to = ranges[i].to(); + if (from.line >= minLine) continue; + if (to.line >= minLine) to = Pos(minLine, 0); + minLine = from.line; + if (mode == null) { + if (cm.uncomment(from, to, options)) mode = "un"; + else { + cm.lineComment(from, to, options); + mode = "line"; + } + } else if (mode == "un") { + cm.uncomment(from, to, options); + } else { + cm.lineComment(from, to, options); + } + } + }); + function probablyInsideString(cm, pos, line) { + return ( + /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && + !/^[\'\"\`]/.test(line) + ); + } + function getMode(cm, pos) { + var mode = cm.getMode(); + return mode.useInnerComments === false || !mode.innerMode + ? mode + : cm.getModeAt(pos); + } + CodeMirror.defineExtension( + "lineComment", + function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var firstLine = self.getLine(from.line); + if ( + firstLine == null || + probablyInsideString(self, from, firstLine) + ) + return; + var commentString = options.lineComment || mode.lineComment; + if (!commentString) { + if (options.blockCommentStart || mode.blockCommentStart) { + options.fullLines = true; + self.blockComment(from, to, options); + } + return; + } + var end = Math.min( + to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, + self.lastLine() + 1 + ); + var pad = options.padding == null ? " " : options.padding; + var blankLines = + options.commentBlankLines || from.line == to.line; + self.operation(function () { + if (options.indent) { + var baseString = null; + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i); + var whitespace = line.slice(0, firstNonWS(line)); + if ( + baseString == null || + baseString.length > whitespace.length + ) { + baseString = whitespace; + } + } + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i), + cut = baseString.length; + if (!blankLines && !nonWS.test(line)) continue; + if (line.slice(0, cut) != baseString) + cut = firstNonWS(line); + self.replaceRange( + baseString + commentString + pad, + Pos(i, 0), + Pos(i, cut) + ); + } + } else { + for (var i = from.line; i < end; ++i) { + if (blankLines || nonWS.test(self.getLine(i))) + self.replaceRange(commentString + pad, Pos(i, 0)); + } + } + }); + } + ); + CodeMirror.defineExtension( + "blockComment", + function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var startString = + options.blockCommentStart || mode.blockCommentStart; + var endString = options.blockCommentEnd || mode.blockCommentEnd; + if (!startString || !endString) { + if ( + (options.lineComment || mode.lineComment) && + options.fullLines != false + ) + self.lineComment(from, to, options); + return; + } + if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) + return; + var end = Math.min(to.line, self.lastLine()); + if ( + end != from.line && + to.ch == 0 && + nonWS.test(self.getLine(end)) + ) + --end; + var pad = options.padding == null ? " " : options.padding; + if (from.line > end) return; + self.operation(function () { + if (options.fullLines != false) { + var lastLineHasText = nonWS.test(self.getLine(end)); + self.replaceRange(pad + endString, Pos(end)); + self.replaceRange(startString + pad, Pos(from.line, 0)); + var lead = + options.blockCommentLead || mode.blockCommentLead; + if (lead != null) { + for (var i = from.line + 1; i <= end; ++i) + if (i != end || lastLineHasText) + self.replaceRange(lead + pad, Pos(i, 0)); + } + } else { + var atCursor = cmp(self.getCursor("to"), to) == 0, + empty = !self.somethingSelected(); + self.replaceRange(endString, to); + if (atCursor) + self.setSelection( + empty ? to : self.getCursor("from"), + to + ); + self.replaceRange(startString, from); + } + }); + } + ); + CodeMirror.defineExtension( + "uncomment", + function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var end = Math.min( + to.ch != 0 || to.line == from.line ? to.line : to.line - 1, + self.lastLine() + ), + start = Math.min(from.line, end); + var lineString = options.lineComment || mode.lineComment, + lines = []; + var pad = options.padding == null ? " " : options.padding, + didSomething; + lineComment: { + if (!lineString) break lineComment; + for (var i = start; i <= end; ++i) { + var line = self.getLine(i); + var found = line.indexOf(lineString); + if ( + found > -1 && + !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1))) + ) + found = -1; + if (found == -1 && nonWS.test(line)) break lineComment; + if (found > -1 && nonWS.test(line.slice(0, found))) + break lineComment; + lines.push(line); + } + self.operation(function () { + for (var i2 = start; i2 <= end; ++i2) { + var line2 = lines[i2 - start]; + var pos = line2.indexOf(lineString), + endPos = pos + lineString.length; + if (pos < 0) continue; + if (line2.slice(endPos, endPos + pad.length) == pad) + endPos += pad.length; + didSomething = true; + self.replaceRange("", Pos(i2, pos), Pos(i2, endPos)); + } + }); + if (didSomething) return true; + } + var startString = + options.blockCommentStart || mode.blockCommentStart; + var endString = options.blockCommentEnd || mode.blockCommentEnd; + if (!startString || !endString) return false; + var lead = options.blockCommentLead || mode.blockCommentLead; + var startLine = self.getLine(start), + open = startLine.indexOf(startString); + if (open == -1) return false; + var endLine = end == start ? startLine : self.getLine(end); + var close = endLine.indexOf( + endString, + end == start ? open + startString.length : 0 + ); + var insideStart = Pos(start, open + 1), + insideEnd = Pos(end, close + 1); + if ( + close == -1 || + !/comment/.test(self.getTokenTypeAt(insideStart)) || + !/comment/.test(self.getTokenTypeAt(insideEnd)) || + self + .getRange(insideStart, insideEnd, "\n") + .indexOf(endString) > -1 + ) + return false; + var lastStart = startLine.lastIndexOf(startString, from.ch); + var firstEnd = + lastStart == -1 + ? -1 + : startLine + .slice(0, from.ch) + .indexOf(endString, lastStart + startString.length); + if ( + lastStart != -1 && + firstEnd != -1 && + firstEnd + endString.length != from.ch + ) + return false; + firstEnd = endLine.indexOf(endString, to.ch); + var almostLastStart = endLine + .slice(to.ch) + .lastIndexOf(startString, firstEnd - to.ch); + lastStart = + firstEnd == -1 || almostLastStart == -1 + ? -1 + : to.ch + almostLastStart; + if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) + return false; + self.operation(function () { + self.replaceRange( + "", + Pos( + end, + close - + (pad && endLine.slice(close - pad.length, close) == pad + ? pad.length + : 0) + ), + Pos(end, close + endString.length) + ); + var openEnd = open + startString.length; + if ( + pad && + startLine.slice(openEnd, openEnd + pad.length) == pad + ) + openEnd += pad.length; + self.replaceRange("", Pos(start, open), Pos(start, openEnd)); + if (lead) + for (var i2 = start + 1; i2 <= end; ++i2) { + var line2 = self.getLine(i2), + found2 = line2.indexOf(lead); + if (found2 == -1 || nonWS.test(line2.slice(0, found2))) + continue; + var foundEnd = found2 + lead.length; + if ( + pad && + line2.slice(foundEnd, foundEnd + pad.length) == pad + ) + foundEnd += pad.length; + self.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd)); + } + }); + return true; + } + ); + }); + })(); + var commentExports = comment$2.exports; + const comment = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(commentExports); + const comment$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: comment, + }, + [commentExports] + ); + exports.comment = comment$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/dialog.cjs.js": + /*!***********************************************!*\ + !*** ../../graphiql-react/dist/dialog.cjs.js ***! + \***********************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } + } } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - return -1; - } - var scrollerGap = 50; - var Pass = { - toString: function () { - return "CodeMirror.Pass"; - } - }; - var sel_dontScroll = { - scroll: false - }, - sel_mouse = { - origin: "*mouse" - }, - sel_move = { - origin: "+move" + var dialog$2 = { + exports: {}, }; - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf(" ", pos); - if (nextTab == -1) { - nextTab = string.length; - } - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) { - return pos + Math.min(skipped, goal - col); - } - col += nextTab - pos; - col += tabSize - col % tabSize; - pos = nextTab + 1; - if (col >= goal) { - return pos; - } - } - } - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) { - spaceStrs.push(lst(spaceStrs) + " "); - } - return spaceStrs[n]; - } - function lst(arr) { - return arr[arr.length - 1]; - } - function map(array, f) { - var out = []; - for (var i2 = 0; i2 < array.length; i2++) { - out[i2] = f(array[i2], i2); - } - return out; - } - function insertSorted(array, value, score) { - var pos = 0, - priority = score(value); - while (pos < array.length && score(array[pos]) <= priority) { - pos++; - } - array.splice(pos, 0, value); - } - function nothing() {} - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) { - copyObj(props, inst); - } - return inst; - } - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - function isWordCharBasic(ch) { - return /\w/.test(ch) || ch > "€" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - } - function isWordChar(ch, helper) { - if (!helper) { - return isWordCharBasic(ch); - } - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { - return true; - } - return helper.test(ch); - } - function isEmpty(obj) { - for (var n in obj) { - if (obj.hasOwnProperty(n) && obj[n]) { - return false; - } - } - return true; - } - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { - return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); - } - function skipExtendingChars(str, pos, dir) { - while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { - pos += dir; - } - return pos; - } - function findFirst(pred, from, to) { - var dir = from > to ? -1 : 1; - for (;;) { - if (from == to) { - return from; - } - var midF = (from + to) / 2, - mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); - if (mid == from) { - return pred(mid) ? from : to; - } - if (pred(mid)) { - to = mid; - } else { - from = mid + dir; - } - } - } - function iterateBidiSections(order, from, to, f) { - if (!order) { - return f(from, to, "ltr", 0); - } - var found = false; - for (var i2 = 0; i2 < order.length; ++i2) { - var part = order[i2]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2); - found = true; - } - } - if (!found) { - f(from, to, "ltr"); - } - } - var bidiOther = null; - function getBidiPartAt(order, ch, sticky) { - var found; - bidiOther = null; - for (var i2 = 0; i2 < order.length; ++i2) { - var cur = order[i2]; - if (cur.from < ch && cur.to > ch) { - return i2; - } - if (cur.to == ch) { - if (cur.from != cur.to && sticky == "before") { - found = i2; - } else { - bidiOther = i2; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function dialogDiv(cm, template, bottom) { + var wrap = cm.getWrapperElement(); + var dialog2; + dialog2 = wrap.appendChild(document.createElement("div")); + if (bottom) + dialog2.className = + "CodeMirror-dialog CodeMirror-dialog-bottom"; + else + dialog2.className = "CodeMirror-dialog CodeMirror-dialog-top"; + if (typeof template == "string") { + dialog2.innerHTML = template; + } else { + dialog2.appendChild(template); + } + CodeMirror.addClass(wrap, "dialog-opened"); + return dialog2; } - } - if (cur.from == ch) { - if (cur.from != cur.to && sticky != "before") { - found = i2; - } else { - bidiOther = i2; + function closeNotification(cm, newVal) { + if (cm.state.currentNotificationClose) + cm.state.currentNotificationClose(); + cm.state.currentNotificationClose = newVal; + } + CodeMirror.defineExtension( + "openDialog", + function (template, callback, options) { + if (!options) options = {}; + closeNotification(this, null); + var dialog2 = dialogDiv(this, template, options.bottom); + var closed = false, + me = this; + function close(newVal) { + if (typeof newVal == "string") { + inp.value = newVal; + } else { + if (closed) return; + closed = true; + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + me.focus(); + if (options.onClose) options.onClose(dialog2); + } + } + var inp = dialog2.getElementsByTagName("input")[0], + button; + if (inp) { + inp.focus(); + if (options.value) { + inp.value = options.value; + if (options.selectValueOnOpen !== false) { + inp.select(); + } + } + if (options.onInput) + CodeMirror.on(inp, "input", function (e) { + options.onInput(e, inp.value, close); + }); + if (options.onKeyUp) + CodeMirror.on(inp, "keyup", function (e) { + options.onKeyUp(e, inp.value, close); + }); + CodeMirror.on(inp, "keydown", function (e) { + if ( + options && + options.onKeyDown && + options.onKeyDown(e, inp.value, close) + ) { + return; + } + if ( + e.keyCode == 27 || + (options.closeOnEnter !== false && e.keyCode == 13) + ) { + inp.blur(); + CodeMirror.e_stop(e); + close(); + } + if (e.keyCode == 13) callback(inp.value, e); + }); + if (options.closeOnBlur !== false) + CodeMirror.on(dialog2, "focusout", function (evt) { + if (evt.relatedTarget !== null) close(); + }); + } else if ( + (button = dialog2.getElementsByTagName("button")[0]) + ) { + CodeMirror.on(button, "click", function () { + close(); + me.focus(); + }); + if (options.closeOnBlur !== false) + CodeMirror.on(button, "blur", close); + button.focus(); + } + return close; + } + ); + CodeMirror.defineExtension( + "openConfirm", + function (template, callbacks, options) { + closeNotification(this, null); + var dialog2 = dialogDiv( + this, + template, + options && options.bottom + ); + var buttons = dialog2.getElementsByTagName("button"); + var closed = false, + me = this, + blurring = 1; + function close() { + if (closed) return; + closed = true; + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + me.focus(); + } + buttons[0].focus(); + for (var i = 0; i < buttons.length; ++i) { + var b = buttons[i]; + (function (callback) { + CodeMirror.on(b, "click", function (e) { + CodeMirror.e_preventDefault(e); + close(); + if (callback) callback(me); + }); + })(callbacks[i]); + CodeMirror.on(b, "blur", function () { + --blurring; + setTimeout(function () { + if (blurring <= 0) close(); + }, 200); + }); + CodeMirror.on(b, "focus", function () { + ++blurring; + }); + } + } + ); + CodeMirror.defineExtension( + "openNotification", + function (template, options) { + closeNotification(this, close); + var dialog2 = dialogDiv( + this, + template, + options && options.bottom + ); + var closed = false, + doneTimer; + var duration = + options && typeof options.duration !== "undefined" + ? options.duration + : 5e3; + function close() { + if (closed) return; + closed = true; + clearTimeout(doneTimer); + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + } + CodeMirror.on(dialog2, "click", function (e) { + CodeMirror.e_preventDefault(e); + close(); + }); + if (duration) doneTimer = setTimeout(close, duration); + return close; + } + ); + }); + })(); + var dialogExports = dialog$2.exports; + const dialog = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(dialogExports); + const dialog$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: dialog, + }, + [dialogExports] + ); + exports.dialog = dialog$1; + exports.dialogExports = dialogExports; + + /***/ + }, + + /***/ "../../graphiql-react/dist/foldgutter.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/foldgutter.cjs.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } } } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - return found != null ? found : bidiOther; - } - var bidiOrdering = /* @__PURE__ */function () { - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; - function charType(code) { - if (code <= 247) { - return lowTypes.charAt(code); - } else if (1424 <= code && code <= 1524) { - return "R"; - } else if (1536 <= code && code <= 1785) { - return arabicTypes.charAt(code - 1536); - } else if (1774 <= code && code <= 2220) { - return "r"; - } else if (8192 <= code && code <= 8203) { - return "w"; - } else if (code == 8204) { - return "b"; - } else { - return "L"; - } - } - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, - isStrong = /[LRr]/, - countsAsLeft = /[Lb1n]/, - countsAsNum = /[1n]/; - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; - this.to = to; - } - return function (str, direction) { - var outerType = direction == "ltr" ? "L" : "R"; - if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { - return false; - } - var len = str.length, - types = []; - for (var i2 = 0; i2 < len; ++i2) { - types.push(charType(str.charCodeAt(i2))); - } - for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) { - var type = types[i$12]; - if (type == "m") { - types[i$12] = prev; - } else { - prev = type; - } - } - for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) { - var type$1 = types[i$22]; - if (type$1 == "1" && cur == "r") { - types[i$22] = "n"; - } else if (isStrong.test(type$1)) { - cur = type$1; - if (type$1 == "r") { - types[i$22] = "R"; - } - } - } - for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { - var type$2 = types[i$3]; - if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { - types[i$3] = "1"; - } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) { - types[i$3] = prev$1; - } - prev$1 = type$2; - } - for (var i$4 = 0; i$4 < len; ++i$4) { - var type$3 = types[i$4]; - if (type$3 == ",") { - types[i$4] = "N"; - } else if (type$3 == "%") { - var end = void 0; - for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} - var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N"; - for (var j = i$4; j < end; ++j) { - types[j] = replace; - } - i$4 = end - 1; - } - } - for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { - var type$4 = types[i$5]; - if (cur$1 == "L" && type$4 == "1") { - types[i$5] = "L"; - } else if (isStrong.test(type$4)) { - cur$1 = type$4; - } - } - for (var i$6 = 0; i$6 < len; ++i$6) { - if (isNeutral.test(types[i$6])) { - var end$1 = void 0; - for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} - var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; - var after = (end$1 < len ? types[end$1] : outerType) == "L"; - var replace$1 = before == after ? before ? "L" : "R" : outerType; - for (var j$1 = i$6; j$1 < end$1; ++j$1) { - types[j$1] = replace$1; - } - i$6 = end$1 - 1; - } - } - var order = [], - m; - for (var i$7 = 0; i$7 < len;) { - if (countsAsLeft.test(types[i$7])) { - var start = i$7; - for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} - order.push(new BidiSpan(0, start, i$7)); - } else { - var pos = i$7, - at = order.length, - isRTL = direction == "rtl" ? 1 : 0; - for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} - for (var j$2 = pos; j$2 < i$7;) { - if (countsAsNum.test(types[j$2])) { - if (pos < j$2) { - order.splice(at, 0, new BidiSpan(1, pos, j$2)); - at += isRTL; - } - var nstart = j$2; - for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} - order.splice(at, 0, new BidiSpan(2, nstart, j$2)); - at += isRTL; - pos = j$2; + var foldgutter$2 = { + exports: {}, + }; + var foldcode = { + exports: {}, + }; + var hasRequiredFoldcode; + function requireFoldcode() { + if (hasRequiredFoldcode) return foldcode.exports; + hasRequiredFoldcode = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function doFold(cm, pos, options, force) { + if (options && options.call) { + var finder = options; + options = null; } else { - ++j$2; + var finder = getOption(cm, options, "rangeFinder"); + } + if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); + var minSize = getOption(cm, options, "minFoldSize"); + function getRange(allowFolded) { + var range2 = finder(cm, pos); + if (!range2 || range2.to.line - range2.from.line < minSize) + return null; + if (force === "fold") return range2; + var marks = cm.findMarksAt(range2.from); + for (var i = 0; i < marks.length; ++i) { + if (marks[i].__isFold) { + if (!allowFolded) return null; + range2.cleared = true; + marks[i].clear(); + } + } + return range2; + } + var range = getRange(true); + if (getOption(cm, options, "scanUp")) + while (!range && pos.line > cm.firstLine()) { + pos = CodeMirror.Pos(pos.line - 1, 0); + range = getRange(false); + } + if (!range || range.cleared || force === "unfold") return; + var myWidget = makeWidget(cm, options, range); + CodeMirror.on(myWidget, "mousedown", function (e) { + myRange.clear(); + CodeMirror.e_preventDefault(e); + }); + var myRange = cm.markText(range.from, range.to, { + replacedWith: myWidget, + clearOnEnter: getOption(cm, options, "clearOnEnter"), + __isFold: true, + }); + myRange.on("clear", function (from, to) { + CodeMirror.signal(cm, "unfold", cm, from, to); + }); + CodeMirror.signal(cm, "fold", cm, range.from, range.to); + } + function makeWidget(cm, options, range) { + var widget = getOption(cm, options, "widget"); + if (typeof widget == "function") { + widget = widget(range.from, range.to); + } + if (typeof widget == "string") { + var text = document.createTextNode(widget); + widget = document.createElement("span"); + widget.appendChild(text); + widget.className = "CodeMirror-foldmarker"; + } else if (widget) { + widget = widget.cloneNode(true); + } + return widget; + } + CodeMirror.newFoldFunction = function (rangeFinder, widget) { + return function (cm, pos) { + doFold(cm, pos, { + rangeFinder, + widget, + }); + }; + }; + CodeMirror.defineExtension( + "foldCode", + function (pos, options, force) { + doFold(this, pos, options, force); + } + ); + CodeMirror.defineExtension("isFolded", function (pos) { + var marks = this.findMarksAt(pos); + for (var i = 0; i < marks.length; ++i) + if (marks[i].__isFold) return true; + }); + CodeMirror.commands.toggleFold = function (cm) { + cm.foldCode(cm.getCursor()); + }; + CodeMirror.commands.fold = function (cm) { + cm.foldCode(cm.getCursor(), null, "fold"); + }; + CodeMirror.commands.unfold = function (cm) { + cm.foldCode( + cm.getCursor(), + { + scanUp: false, + }, + "unfold" + ); + }; + CodeMirror.commands.foldAll = function (cm) { + cm.operation(function () { + for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) + cm.foldCode( + CodeMirror.Pos(i, 0), + { + scanUp: false, + }, + "fold" + ); + }); + }; + CodeMirror.commands.unfoldAll = function (cm) { + cm.operation(function () { + for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) + cm.foldCode( + CodeMirror.Pos(i, 0), + { + scanUp: false, + }, + "unfold" + ); + }); + }; + CodeMirror.registerHelper("fold", "combine", function () { + var funcs = Array.prototype.slice.call(arguments, 0); + return function (cm, start) { + for (var i = 0; i < funcs.length; ++i) { + var found = funcs[i](cm, start); + if (found) return found; + } + }; + }); + CodeMirror.registerHelper("fold", "auto", function (cm, start) { + var helpers = cm.getHelpers(start, "fold"); + for (var i = 0; i < helpers.length; i++) { + var cur = helpers[i](cm, start); + if (cur) return cur; } + }); + var defaultOptions = { + rangeFinder: CodeMirror.fold.auto, + widget: "↔", + minFoldSize: 0, + scanUp: false, + clearOnEnter: true, + }; + CodeMirror.defineOption("foldOptions", null); + function getOption(cm, options, name) { + if (options && options[name] !== void 0) return options[name]; + var editorOptions = cm.options.foldOptions; + if (editorOptions && editorOptions[name] !== void 0) + return editorOptions[name]; + return defaultOptions[name]; } - if (pos < i$7) { - order.splice(at, 0, new BidiSpan(1, pos, i$7)); + CodeMirror.defineExtension( + "foldOption", + function (options, name) { + return getOption(this, options, name); + } + ); + }); + })(); + return foldcode.exports; + } + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), requireFoldcode()); + })(function (CodeMirror) { + CodeMirror.defineOption( + "foldGutter", + false, + function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.clearGutter(cm.state.foldGutter.options.gutter); + cm.state.foldGutter = null; + cm.off("gutterClick", onGutterClick); + cm.off("changes", onChange); + cm.off("viewportChange", onViewportChange); + cm.off("fold", onFold); + cm.off("unfold", onFold); + cm.off("swapDoc", onChange); + } + if (val) { + cm.state.foldGutter = new State(parseOptions(val)); + updateInViewport(cm); + cm.on("gutterClick", onGutterClick); + cm.on("changes", onChange); + cm.on("viewportChange", onViewportChange); + cm.on("fold", onFold); + cm.on("unfold", onFold); + cm.on("swapDoc", onChange); + } } + ); + var Pos = CodeMirror.Pos; + function State(options) { + this.options = options; + this.from = this.to = 0; } - } - if (direction == "ltr") { - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); + function parseOptions(opts) { + if (opts === true) opts = {}; + if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; + if (opts.indicatorOpen == null) + opts.indicatorOpen = "CodeMirror-foldgutter-open"; + if (opts.indicatorFolded == null) + opts.indicatorFolded = "CodeMirror-foldgutter-folded"; + return opts; } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); + function isFolded(cm, line) { + var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); + for (var i = 0; i < marks.length; ++i) { + if (marks[i].__isFold) { + var fromPos = marks[i].find(-1); + if (fromPos && fromPos.line === line) return marks[i]; + } + } } - } - return direction == "rtl" ? order.reverse() : order; - }; - }(); - function getOrder(line, direction) { - var order = line.order; - if (order == null) { - order = line.order = bidiOrdering(line.text, direction); - } - return order; - } - var noHandlers = []; - var on = function (emitter, type, f) { - if (emitter.addEventListener) { - emitter.addEventListener(type, f, false); - } else if (emitter.attachEvent) { - emitter.attachEvent("on" + type, f); - } else { - var map2 = emitter._handlers || (emitter._handlers = {}); - map2[type] = (map2[type] || noHandlers).concat(f); - } - }; - function getHandlers(emitter, type) { - return emitter._handlers && emitter._handlers[type] || noHandlers; - } - function off(emitter, type, f) { - if (emitter.removeEventListener) { - emitter.removeEventListener(type, f, false); - } else if (emitter.detachEvent) { - emitter.detachEvent("on" + type, f); - } else { - var map2 = emitter._handlers, - arr = map2 && map2[type]; - if (arr) { - var index = indexOf(arr, f); - if (index > -1) { - map2[type] = arr.slice(0, index).concat(arr.slice(index + 1)); + function marker(spec) { + if (typeof spec == "string") { + var elt = document.createElement("div"); + elt.className = spec + " CodeMirror-guttermarker-subtle"; + return elt; + } else { + return spec.cloneNode(true); + } } - } - } - } - function signal(emitter, type) { - var handlers = getHandlers(emitter, type); - if (!handlers.length) { - return; - } - var args = Array.prototype.slice.call(arguments, 2); - for (var i2 = 0; i2 < handlers.length; ++i2) { - handlers[i2].apply(null, args); - } - } - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") { - e = { - type: e, - preventDefault: function () { - this.defaultPrevented = true; + function updateFoldInfo(cm, from, to) { + var opts = cm.state.foldGutter.options, + cur = from - 1; + var minSize = cm.foldOption(opts, "minFoldSize"); + var func = cm.foldOption(opts, "rangeFinder"); + var clsFolded = + typeof opts.indicatorFolded == "string" && + classTest(opts.indicatorFolded); + var clsOpen = + typeof opts.indicatorOpen == "string" && + classTest(opts.indicatorOpen); + cm.eachLine(from, to, function (line) { + ++cur; + var mark = null; + var old = line.gutterMarkers; + if (old) old = old[opts.gutter]; + if (isFolded(cm, cur)) { + if (clsFolded && old && clsFolded.test(old.className)) return; + mark = marker(opts.indicatorFolded); + } else { + var pos = Pos(cur, 0); + var range = func && func(cm, pos); + if (range && range.to.line - range.from.line >= minSize) { + if (clsOpen && old && clsOpen.test(old.className)) return; + mark = marker(opts.indicatorOpen); + } + } + if (!mark && !old) return; + cm.setGutterMarker(line, opts.gutter, mark); + }); } - }; - } - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) { - return; - } - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i2 = 0; i2 < arr.length; ++i2) { - if (indexOf(set, arr[i2]) == -1) { - set.push(arr[i2]); - } - } - } - function hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0; - } - function eventMixin(ctor) { - ctor.prototype.on = function (type, f) { - on(this, type, f); - }; - ctor.prototype.off = function (type, f) { - off(this, type, f); - }; - } - function e_preventDefault(e) { - if (e.preventDefault) { - e.preventDefault(); - } else { - e.returnValue = false; - } - } - function e_stopPropagation(e) { - if (e.stopPropagation) { - e.stopPropagation(); - } else { - e.cancelBubble = true; - } - } - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - function e_stop(e) { - e_preventDefault(e); - e_stopPropagation(e); - } - function e_target(e) { - return e.target || e.srcElement; - } - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) { - b = 1; - } else if (e.button & 2) { - b = 3; - } else if (e.button & 4) { - b = 2; - } - } - if (mac && e.ctrlKey && b == 1) { - b = 3; - } - return b; - } - var dragAndDrop = function () { - if (ie && ie_version < 9) { - return false; - } - var div = elt("div"); - return "draggable" in div || "dragDrop" in div; - }(); - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "​"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) { - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - } - var node = zwspSupported ? elt("span", "​") : elt("span", " ", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) { - return badBidiRects; - } - var txt = removeChildrenAndAdd(measure, document.createTextNode("AخA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - var r1 = range(txt, 1, 2).getBoundingClientRect(); - removeChildren(measure); - if (!r0 || r0.left == r0.right) { - return false; - } - return badBidiRects = r1.right - r0.right < 3; - } - var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { - var pos = 0, - result = [], - l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) { - nl = string.length; - } - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function (string) { - return string.split(/\r\n?|\n/); - }; - var hasSelection = window.getSelection ? function (te) { - try { - return te.selectionStart != te.selectionEnd; - } catch (e) { - return false; - } - } : function (te) { - var range2; - try { - range2 = te.ownerDocument.selection.createRange(); - } catch (e) {} - if (!range2 || range2.parentElement() != te) { - return false; - } - return range2.compareEndPoints("StartToEnd", range2) != 0; - }; - var hasCopyEvent = function () { - var e = elt("div"); - if ("oncopy" in e) { - return true; - } - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - }(); - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) { - return badZoomedRects; - } - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - var modes = {}, - mimeModes = {}; - function defineMode(name, mode) { - if (arguments.length > 2) { - mode.dependencies = Array.prototype.slice.call(arguments, 2); - } - modes[name] = mode; - } - function defineMIME(mime, spec) { - mimeModes[mime] = spec; - } - function resolveMode(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") { - found = { - name: found - }; - } - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return resolveMode("application/xml"); - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { - return resolveMode("application/json"); - } - if (typeof spec == "string") { - return { - name: spec - }; - } else { - return spec || { - name: "null" - }; - } - } - function getMode(options, spec) { - spec = resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) { - return getMode(options, "text/plain"); - } - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop2 in exts) { - if (!exts.hasOwnProperty(prop2)) { - continue; + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } - if (modeObj.hasOwnProperty(prop2)) { - modeObj["_" + prop2] = modeObj[prop2]; + function updateInViewport(cm) { + var vp = cm.getViewport(), + state = cm.state.foldGutter; + if (!state) return; + cm.operation(function () { + updateFoldInfo(cm, vp.from, vp.to); + }); + state.from = vp.from; + state.to = vp.to; } - modeObj[prop2] = exts[prop2]; - } - } - modeObj.name = spec.name; - if (spec.helperType) { - modeObj.helperType = spec.helperType; - } - if (spec.modeProps) { - for (var prop$1 in spec.modeProps) { - modeObj[prop$1] = spec.modeProps[prop$1]; - } - } - return modeObj; - } - var modeExtensions = {}; - function extendMode(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {}; - copyObj(properties, exts); - } - function copyState(mode, state) { - if (state === true) { - return state; - } - if (mode.copyState) { - return mode.copyState(state); - } - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) { - val = val.concat([]); - } - nstate[n] = val; - } - return nstate; - } - function innerMode(mode, state) { - var info; - while (mode.innerMode) { - info = mode.innerMode(state); - if (!info || info.mode == mode) { - break; - } - state = info.state; - mode = info.mode; - } - return info || { - mode, - state - }; - } - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - } - var StringStream = function (string, tabSize, lineOracle) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - this.lineOracle = lineOracle; - }; - StringStream.prototype.eol = function () { - return this.pos >= this.string.length; - }; - StringStream.prototype.sol = function () { - return this.pos == this.lineStart; - }; - StringStream.prototype.peek = function () { - return this.string.charAt(this.pos) || void 0; - }; - StringStream.prototype.next = function () { - if (this.pos < this.string.length) { - return this.string.charAt(this.pos++); - } - }; - StringStream.prototype.eat = function (match) { - var ch = this.string.charAt(this.pos); - var ok; - if (typeof match == "string") { - ok = ch == match; - } else { - ok = ch && (match.test ? match.test(ch) : match(ch)); - } - if (ok) { - ++this.pos; - return ch; - } - }; - StringStream.prototype.eatWhile = function (match) { - var start = this.pos; - while (this.eat(match)) {} - return this.pos > start; - }; - StringStream.prototype.eatSpace = function () { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { - ++this.pos; - } - return this.pos > start; - }; - StringStream.prototype.skipToEnd = function () { - this.pos = this.string.length; - }; - StringStream.prototype.skipTo = function (ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) { - this.pos = found; - return true; - } - }; - StringStream.prototype.backUp = function (n) { - this.pos -= n; - }; - StringStream.prototype.column = function () { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }; - StringStream.prototype.indentation = function () { - return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }; - StringStream.prototype.match = function (pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function (str) { - return caseInsensitive ? str.toLowerCase() : str; - }; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) { - this.pos += pattern.length; + function onGutterClick(cm, line, gutter) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + if (gutter != opts.gutter) return; + var folded = isFolded(cm, line); + if (folded) folded.clear(); + else cm.foldCode(Pos(line, 0), opts); } - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) { - return null; - } - if (match && consume !== false) { - this.pos += match[0].length; - } - return match; - } - }; - StringStream.prototype.current = function () { - return this.string.slice(this.start, this.pos); - }; - StringStream.prototype.hideFirstChars = function (n, inner) { - this.lineStart += n; - try { - return inner(); - } finally { - this.lineStart -= n; - } - }; - StringStream.prototype.lookAhead = function (n) { - var oracle = this.lineOracle; - return oracle && oracle.lookAhead(n); - }; - StringStream.prototype.baseToken = function () { - var oracle = this.lineOracle; - return oracle && oracle.baseToken(this.pos); - }; - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) { - throw new Error("There is no line " + (n + doc.first) + " in the document."); - } - var chunk = doc; - while (!chunk.lines) { - for (var i2 = 0;; ++i2) { - var child = chunk.children[i2], - sz = child.chunkSize(); - if (n < sz) { - chunk = child; - break; + function onChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + state.from = state.to = 0; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function () { + updateInViewport(cm); + }, opts.foldOnChangeTimeSpan || 600); } - n -= sz; - } - } - return chunk.lines[n]; - } - function getBetween(doc, start, end) { - var out = [], - n = start.line; - doc.iter(start.line, end.line + 1, function (line) { - var text = line.text; - if (n == end.line) { - text = text.slice(0, end.ch); - } - if (n == start.line) { - text = text.slice(start.ch); - } - out.push(text); - ++n; - }); - return out; - } - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function (line) { - out.push(line.text); - }); - return out; - } - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) { - for (var n = line; n; n = n.parent) { - n.height += diff; - } - } - } - function lineNo(line) { - if (line.parent == null) { - return null; - } - var cur = line.parent, - no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i2 = 0;; ++i2) { - if (chunk.children[i2] == cur) { - break; + function onViewportChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function () { + var vp = cm.getViewport(); + if ( + state.from == state.to || + vp.from - state.to > 20 || + state.from - vp.to > 20 + ) { + updateInViewport(cm); + } else { + cm.operation(function () { + if (vp.from < state.from) { + updateFoldInfo(cm, vp.from, state.from); + state.from = vp.from; + } + if (vp.to > state.to) { + updateFoldInfo(cm, state.to, vp.to); + state.to = vp.to; + } + }); + } + }, opts.updateViewportTimeSpan || 400); } - no += chunk.children[i2].chunkSize(); - } - } - return no + cur.first; - } - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) { - var child = chunk.children[i$12], - ch = child.height; - if (h < ch) { - chunk = child; - continue outer; - } - h -= ch; - n += child.chunkSize(); + function onFold(cm, from) { + var state = cm.state.foldGutter; + if (!state) return; + var line = from.line; + if (line >= state.from && line < state.to) + updateFoldInfo(cm, line, line + 1); + } + }); + })(); + var foldgutterExports = foldgutter$2.exports; + const foldgutter = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(foldgutterExports); + const foldgutter$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: foldgutter, + }, + [foldgutterExports] + ); + exports.foldgutter = foldgutter$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/forEachState.cjs.js": + /*!*****************************************************!*\ + !*** ../../graphiql-react/dist/forEachState.cjs.js ***! + \*****************************************************/ + /***/ function (__unused_webpack_module, exports) { + function forEachState(stack, fn) { + const reverseStateStack = []; + let state = stack; + while (state === null || state === void 0 ? void 0 : state.kind) { + reverseStateStack.push(state); + state = state.prevState; } - return n; - } while (!chunk.lines); - var i2 = 0; - for (; i2 < chunk.lines.length; ++i2) { - var line = chunk.lines[i2], - lh = line.height; - if (h < lh) { - break; + for (let i = reverseStateStack.length - 1; i >= 0; i--) { + fn(reverseStateStack[i]); } - h -= lh; - } - return n + i2; - } - function isLine(doc, l) { - return l >= doc.first && l < doc.first + doc.size; - } - function lineNumberFor(options, i2) { - return String(options.lineNumberFormatter(i2 + options.firstLineNumber)); - } - function Pos(line, ch, sticky) { - if (sticky === void 0) sticky = null; - if (!(this instanceof Pos)) { - return new Pos(line, ch, sticky); - } - this.line = line; - this.ch = ch; - this.sticky = sticky; - } - function cmp(a, b) { - return a.line - b.line || a.ch - b.ch; - } - function equalCursorPos(a, b) { - return a.sticky == b.sticky && cmp(a, b) == 0; - } - function copyPos(x) { - return Pos(x.line, x.ch); - } - function maxPos(a, b) { - return cmp(a, b) < 0 ? b : a; - } - function minPos(a, b) { - return cmp(a, b) < 0 ? a : b; - } - function clipLine(doc, n) { - return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)); - } - function clipPos(doc, pos) { - if (pos.line < doc.first) { - return Pos(doc.first, 0); - } - var last = doc.first + doc.size - 1; - if (pos.line > last) { - return Pos(last, getLine(doc, last).text.length); - } - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) { - return Pos(pos.line, linelen); - } else if (ch < 0) { - return Pos(pos.line, 0); - } else { - return pos; - } - } - function clipPosArray(doc, array) { - var out = []; - for (var i2 = 0; i2 < array.length; i2++) { - out[i2] = clipPos(doc, array[i2]); - } - return out; - } - var SavedContext = function (state, lookAhead) { - this.state = state; - this.lookAhead = lookAhead; - }; - var Context = function (doc, state, line, lookAhead) { - this.state = state; - this.doc = doc; - this.line = line; - this.maxLookAhead = lookAhead || 0; - this.baseTokens = null; - this.baseTokenPos = 1; - }; - Context.prototype.lookAhead = function (n) { - var line = this.doc.getLine(this.line + n); - if (line != null && n > this.maxLookAhead) { - this.maxLookAhead = n; - } - return line; - }; - Context.prototype.baseToken = function (n) { - if (!this.baseTokens) { - return null; - } - while (this.baseTokens[this.baseTokenPos] <= n) { - this.baseTokenPos += 2; - } - var type = this.baseTokens[this.baseTokenPos + 1]; - return { - type: type && type.replace(/( |^)overlay .*/, ""), - size: this.baseTokens[this.baseTokenPos] - n - }; - }; - Context.prototype.nextLine = function () { - this.line++; - if (this.maxLookAhead > 0) { - this.maxLookAhead--; - } - }; - Context.fromSaved = function (doc, saved, line) { - if (saved instanceof SavedContext) { - return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead); - } else { - return new Context(doc, copyState(doc.mode, saved), line); - } - }; - Context.prototype.save = function (copy) { - var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; - return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state; - }; - function highlightLine(cm, line, context, forceToEnd) { - var st = [cm.state.modeGen], - lineClasses = {}; - runMode(cm, line.text, cm.doc.mode, context, function (end, style) { - return st.push(end, style); - }, lineClasses, forceToEnd); - var state = context.state; - var loop = function (o2) { - context.baseTokens = st; - var overlay = cm.state.overlays[o2], - i2 = 1, - at = 0; - context.state = true; - runMode(cm, line.text, overlay.mode, context, function (end, style) { - var start = i2; - while (at < end) { - var i_end = st[i2]; - if (i_end > end) { - st.splice(i2, 1, end, st[i2 + 1], i_end); - } - i2 += 2; - at = Math.min(end, i_end); - } - if (!style) { - return; - } - if (overlay.opaque) { - st.splice(start, i2 - start, end, "overlay " + style); - i2 = start + 2; - } else { - for (; start < i2; start += 2) { - var cur = st[start + 1]; - st[start + 1] = (cur ? cur + " " : "") + "overlay " + style; - } - } - }, lineClasses); - context.state = state; - context.baseTokens = null; - context.baseTokenPos = 1; - }; - for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); - return { - styles: st, - classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null - }; - } - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var context = getContextBefore(cm, lineNo(line)); - var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); - var result = highlightLine(cm, line, context); - if (resetState) { - context.state = resetState; - } - line.stateAfter = context.save(!resetState); - line.styles = result.styles; - if (result.classes) { - line.styleClasses = result.classes; - } else if (line.styleClasses) { - line.styleClasses = null; - } - if (updateFrontier === cm.doc.highlightFrontier) { - cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); - } - } - return line.styles; - } - function getContextBefore(cm, n, precise) { - var doc = cm.doc, - display = cm.display; - if (!doc.mode.startState) { - return new Context(doc, true, n); - } - var start = findStartLine(cm, n, precise); - var saved = start > doc.first && getLine(doc, start - 1).stateAfter; - var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); - doc.iter(start, n, function (line) { - processLine(cm, line.text, context); - var pos = context.line; - line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; - context.nextLine(); - }); - if (precise) { - doc.modeFrontier = context.line; - } - return context; - } - function processLine(cm, text, context, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize, context); - stream.start = stream.pos = startAt || 0; - if (text == "") { - callBlankLine(mode, context.state); - } - while (!stream.eol()) { - readToken(mode, stream, context.state); - stream.start = stream.pos; - } - } - function callBlankLine(mode, state) { - if (mode.blankLine) { - return mode.blankLine(state); - } - if (!mode.innerMode) { - return; - } - var inner = innerMode(mode, state); - if (inner.mode.blankLine) { - return inner.mode.blankLine(inner.state); } - } - function readToken(mode, stream, state, inner) { - for (var i2 = 0; i2 < 10; i2++) { - if (inner) { - inner[0] = innerMode(mode, state).mode; + exports.forEachState = forEachState; + + /***/ + }, + + /***/ "../../graphiql-react/dist/hint.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/hint.cjs.js ***! + \*********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + __webpack_require__( + /*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js" + ); + const graphqlLanguageService = __webpack_require__( + /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" + ); + codemirror.CodeMirror.registerHelper( + "hint", + "graphql", + (editor, options) => { + const { schema, externalFragments, autocompleteOptions } = options; + if (!schema) { + return; + } + const cur = editor.getCursor(); + const token = editor.getTokenAt(cur); + const tokenStart = + token.type !== null && /"|\w/.test(token.string[0]) + ? token.start + : token.end; + const position = new graphqlLanguageService.Position( + cur.line, + tokenStart + ); + const rawResults = + graphqlLanguageService.getAutocompleteSuggestions( + schema, + editor.getValue(), + position, + token, + externalFragments, + autocompleteOptions + ); + const results = { + list: rawResults.map((item) => { + var _a; + return { + text: + (_a = + item === null || item === void 0 + ? void 0 + : item.rawInsert) !== null && _a !== void 0 + ? _a + : item.label, + type: item.type, + description: item.documentation, + isDeprecated: item.isDeprecated, + deprecationReason: item.deprecationReason, + }; + }), + from: { + line: cur.line, + ch: tokenStart, + }, + to: { + line: cur.line, + ch: token.end, + }, + }; + if ( + (results === null || results === void 0 + ? void 0 + : results.list) && + results.list.length > 0 + ) { + results.from = codemirror.CodeMirror.Pos( + results.from.line, + results.from.ch + ); + results.to = codemirror.CodeMirror.Pos( + results.to.line, + results.to.ch + ); + codemirror.CodeMirror.signal( + editor, + "hasCompletion", + editor, + results, + token + ); + } + return results; } - var style = mode.token(stream, state); - if (stream.pos > stream.start) { - return style; + ); + + /***/ + }, + + /***/ "../../graphiql-react/dist/hint.cjs2.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/hint.cjs2.js ***! + \**********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const forEachState = __webpack_require__( + /*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js" + ); + function hintList(cursor, token, list) { + const hints = filterAndSortList(list, normalizeText(token.string)); + if (!hints) { + return; } + const tokenStart = + token.type !== null && /"|\w/.test(token.string[0]) + ? token.start + : token.end; + return { + list: hints, + from: { + line: cursor.line, + ch: tokenStart, + }, + to: { + line: cursor.line, + ch: token.end, + }, + }; } - throw new Error("Mode " + mode.name + " failed to advance stream."); - } - var Token = function (stream, type, state) { - this.start = stream.start; - this.end = stream.pos; - this.string = stream.current(); - this.type = type || null; - this.state = state; - }; - function takeToken(cm, pos, precise, asArray) { - var doc = cm.doc, - mode = doc.mode, - style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), - context = getContextBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize, context), - tokens; - if (asArray) { - tokens = []; - } - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, context.state); - if (asArray) { - tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); - } - } - return asArray ? tokens : new Token(stream, style, context.state); - } - function extractLineClasses(type, output) { - if (type) { - for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) { - break; + function filterAndSortList(list, text) { + if (!text) { + return filterNonEmpty(list, (entry) => !entry.isDeprecated); + } + const byProximity = list.map((entry) => ({ + proximity: getProximity(normalizeText(entry.text), text), + entry, + })); + const conciseMatches = filterNonEmpty( + filterNonEmpty(byProximity, (pair) => pair.proximity <= 2), + (pair) => !pair.entry.isDeprecated + ); + const sortedMatches = conciseMatches.sort( + (a, b) => + (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || + a.proximity - b.proximity || + a.entry.text.length - b.entry.text.length + ); + return sortedMatches.map((pair) => pair.entry); + } + function filterNonEmpty(array, predicate) { + const filtered = array.filter(predicate); + return filtered.length === 0 ? array : filtered; + } + function normalizeText(text) { + return text.toLowerCase().replaceAll(/\W/g, ""); + } + function getProximity(suggestion, text) { + let proximity = lexicalDistance(text, suggestion); + if (suggestion.length > text.length) { + proximity -= suggestion.length - text.length - 1; + proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + } + return proximity; + } + function lexicalDistance(a, b) { + let i; + let j; + const d = []; + const aLength = a.length; + const bLength = b.length; + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min( + d[i - 1][j] + 1, + d[i][j - 1] + 1, + d[i - 1][j - 1] + cost + ); + if ( + i > 1 && + j > 1 && + a[i - 1] === b[j - 2] && + a[i - 2] === b[j - 1] + ) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } } - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop2 = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop2] == null) { - output[prop2] = lineClass[2]; - } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop2])) { - output[prop2] += " " + lineClass[2]; + } + return d[aLength][bLength]; + } + codemirror.CodeMirror.registerHelper( + "hint", + "graphql-variables", + (editor, options) => { + const cur = editor.getCursor(); + const token = editor.getTokenAt(cur); + const results = getVariablesHint(cur, token, options); + if ( + (results === null || results === void 0 + ? void 0 + : results.list) && + results.list.length > 0 + ) { + results.from = codemirror.CodeMirror.Pos( + results.from.line, + results.from.ch + ); + results.to = codemirror.CodeMirror.Pos( + results.to.line, + results.to.ch + ); + codemirror.CodeMirror.signal( + editor, + "hasCompletion", + editor, + results, + token + ); } + return results; } - } - return type; - } - function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) { - flattenSpans = cm.options.flattenSpans; - } - var curStart = 0, - curStyle = null; - var stream = new StringStream(text, cm.options.tabSize, context), - style; - var inner = cm.options.addModeClass && [null]; - if (text == "") { - extractLineClasses(callBlankLine(mode, context.state), lineClasses); - } - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) { - processLine(cm, text, context, stream.pos); - } - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); + ); + function getVariablesHint(cur, token, options) { + const state = + token.state.kind === "Invalid" + ? token.state.prevState + : token.state; + const { kind, step } = state; + if (kind === "Document" && step === 0) { + return hintList(cur, token, [ + { + text: "{", + }, + ]); } - if (inner) { - var mName = inner[0].name; - if (mName) { - style = "m-" + (style ? mName + " " + style : mName); - } + const { variableToType } = options; + if (!variableToType) { + return; + } + const typeInfo = getTypeInfo(variableToType, token.state); + if (kind === "Document" || (kind === "Variable" && step === 0)) { + const variableNames = Object.keys(variableToType); + return hintList( + cur, + token, + variableNames.map((name) => ({ + text: `"${name}": `, + type: variableToType[name], + })) + ); + } + if ( + (kind === "ObjectValue" || + (kind === "ObjectField" && step === 0)) && + typeInfo.fields + ) { + const inputFields = Object.keys(typeInfo.fields).map( + (fieldName) => typeInfo.fields[fieldName] + ); + return hintList( + cur, + token, + inputFields.map((field) => ({ + text: `"${field.name}": `, + type: field.type, + description: field.description, + })) + ); } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 5e3); - f(curStart, curStyle); + if ( + kind === "StringValue" || + kind === "NumberValue" || + kind === "BooleanValue" || + kind === "NullValue" || + (kind === "ListValue" && step === 1) || + (kind === "ObjectField" && step === 2) || + (kind === "Variable" && step === 2) + ) { + const namedInputType = typeInfo.type + ? graphql.getNamedType(typeInfo.type) + : void 0; + if (namedInputType instanceof graphql.GraphQLInputObjectType) { + return hintList(cur, token, [ + { + text: "{", + }, + ]); + } + if (namedInputType instanceof graphql.GraphQLEnumType) { + const values = namedInputType.getValues(); + return hintList( + cur, + token, + values.map((value) => ({ + text: `"${value.name}"`, + type: namedInputType, + description: value.description, + })) + ); + } + if (namedInputType === graphql.GraphQLBoolean) { + return hintList(cur, token, [ + { + text: "true", + type: graphql.GraphQLBoolean, + description: "Not false.", + }, + { + text: "false", + type: graphql.GraphQLBoolean, + description: "Not true.", + }, + ]); } - curStyle = style; } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - var pos = Math.min(stream.pos, curStart + 5e3); - f(pos, curStyle); - curStart = pos; - } - } - function findStartLine(cm, n, precise) { - var minindent, - minline, - doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) { - return doc.first; - } - var line = getLine(doc, search - 1), - after = line.stateAfter; - if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { - return search; - } - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - function retreatFrontier(doc, n) { - doc.modeFrontier = Math.min(doc.modeFrontier, n); - if (doc.highlightFrontier < n - 10) { - return; } - var start = doc.first; - for (var line = n - 1; line > start; line--) { - var saved = getLine(doc, line).stateAfter; - if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { - start = line + 1; - break; - } + function getTypeInfo(variableToType, tokenState) { + const info = { + type: null, + fields: null, + }; + forEachState.forEachState(tokenState, (state) => { + switch (state.kind) { + case "Variable": { + info.type = variableToType[state.name]; + break; + } + case "ListValue": { + const nullableType = info.type + ? graphql.getNullableType(info.type) + : void 0; + info.type = + nullableType instanceof graphql.GraphQLList + ? nullableType.ofType + : null; + break; + } + case "ObjectValue": { + const objectType = info.type + ? graphql.getNamedType(info.type) + : void 0; + info.fields = + objectType instanceof graphql.GraphQLInputObjectType + ? objectType.getFields() + : null; + break; + } + case "ObjectField": { + const objectField = + state.name && info.fields ? info.fields[state.name] : null; + info.type = + objectField === null || objectField === void 0 + ? void 0 + : objectField.type; + break; + } + } + }); + return info; } - doc.highlightFrontier = Math.min(doc.highlightFrontier, start); - } - var sawReadOnlySpans = false, - sawCollapsedSpans = false; - function seeReadOnlySpans() { - sawReadOnlySpans = true; - } - function seeCollapsedSpans() { - sawCollapsedSpans = true; - } - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; - this.to = to; - } - function getMarkedSpanFor(spans, marker) { - if (spans) { - for (var i2 = 0; i2 < spans.length; ++i2) { - var span = spans[i2]; - if (span.marker == marker) { - return span; + + /***/ + }, + + /***/ "../../graphiql-react/dist/index.js": + /*!******************************************!*\ + !*** ../../graphiql-react/dist/index.js ***! + \******************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, Symbol.toStringTag, { + value: "Module", + }); + const jsxRuntime = __webpack_require__( + /*! react/jsx-runtime */ "../../../node_modules/react/jsx-runtime.js" + ); + const React = __webpack_require__(/*! react */ "react"); + const clsx = __webpack_require__( + /*! clsx */ "../../../node_modules/clsx/dist/clsx.m.js" + ); + const graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const toolkit = __webpack_require__( + /*! @graphiql/toolkit */ "../../graphiql-toolkit/esm/index.js" + ); + const graphqlLanguageService = __webpack_require__( + /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" + ); + const setValue = __webpack_require__( + /*! set-value */ "../../../node_modules/set-value/index.js" + ); + const copyToClipboard = __webpack_require__( + /*! copy-to-clipboard */ "../../../node_modules/copy-to-clipboard/index.js" + ); + const D = __webpack_require__( + /*! @radix-ui/react-dialog */ "../../../node_modules/@radix-ui/react-dialog/dist/index.js" + ); + const reactVisuallyHidden = __webpack_require__( + /*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js" + ); + const reactDropdownMenu = __webpack_require__( + /*! @radix-ui/react-dropdown-menu */ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js" + ); + const MarkdownIt = __webpack_require__( + /*! markdown-it */ "../node_modules/markdown-it/dist/index.cjs.js" + ); + const framerMotion = __webpack_require__( + /*! framer-motion */ "../../../node_modules/framer-motion/dist/cjs/index.js" + ); + const T = __webpack_require__( + /*! @radix-ui/react-tooltip */ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js" + ); + const react = __webpack_require__( + /*! @headlessui/react */ "../../../node_modules/@headlessui/react/dist/index.cjs" + ); + const ReactDOM = __webpack_require__(/*! react-dom */ "react-dom"); + function _interopNamespaceDefault(e) { + const n = Object.create(null, { + [Symbol.toStringTag]: { + value: "Module", + }, + }); + if (e) { + for (const k in e) { + if (k !== "default") { + const d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } } } + n.default = e; + return Object.freeze(n); } - } - function removeMarkedSpan(spans, span) { - var r; - for (var i2 = 0; i2 < spans.length; ++i2) { - if (spans[i2] != span) { - (r || (r = [])).push(spans[i2]); - } + const React__namespace = + /* @__PURE__ */ _interopNamespaceDefault(React); + const D__namespace = /* @__PURE__ */ _interopNamespaceDefault(D); + const T__namespace = /* @__PURE__ */ _interopNamespaceDefault(T); + function createNullableContext(name) { + const context = React.createContext(null); + context.displayName = name; + return context; } - return r; - } - function addMarkedSpan(line, span, op) { - var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = /* @__PURE__ */new WeakSet())); - if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { - line.markedSpans.push(span); - } else { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - if (inThisOp) { - inThisOp.add(line.markedSpans); + function createContextHook(context) { + function useGivenContext(options) { + var _a; + const value = React.useContext(context); + if ( + value === null && + (options == null ? void 0 : options.nonNull) + ) { + throw new Error( + `Tried to use \`${ + ((_a = options.caller) == null ? void 0 : _a.name) || + useGivenContext.caller.name + }\` without the necessary context. Make sure to render the \`${ + context.displayName + }Provider\` component higher up the tree.` + ); + } + return value; } + Object.defineProperty(useGivenContext, "name", { + value: `use${context.displayName}`, + }); + return useGivenContext; } - span.marker.attachLine(line); - } - function markedSpansBefore(old, startCh, isInsert) { - var nw; - if (old) { - for (var i2 = 0; i2 < old.length; ++i2) { - var span = old[i2], - marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + const StorageContext = createNullableContext("StorageContext"); + function StorageContextProvider(props) { + const isInitialRender = React.useRef(true); + const [storage, setStorage] = React.useState( + new toolkit.StorageAPI(props.storage) + ); + React.useEffect(() => { + if (isInitialRender.current) { + isInitialRender.current = false; + } else { + setStorage(new toolkit.StorageAPI(props.storage)); } + }, [props.storage]); + return /* @__PURE__ */ jsxRuntime.jsx(StorageContext.Provider, { + value: storage, + children: props.children, + }); + } + const useStorageContext = createContextHook(StorageContext); + const SvgArgument = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 6, + y: 6, + width: 2, + height: 2, + rx: 1, + fill: "currentColor", + }) + ); + const SvgChevronDown = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 9", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M1 1L7 7L13 1", + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgChevronLeft = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 7 10", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M6 1.04819L2 5.04819L6 9.04819", + stroke: "currentColor", + strokeWidth: 1.75, + }) + ); + const SvgChevronUp = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 9", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M13 8L7 2L1 8", + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgClose = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 14", + stroke: "currentColor", + strokeWidth: 3, + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M1 1L12.9998 12.9997", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M13 1L1.00079 13.0003", + }) + ); + const SvgCopy = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "-2 -2 22 22", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M11.25 14.2105V15.235C11.25 16.3479 10.3479 17.25 9.23501 17.25H2.76499C1.65214 17.25 0.75 16.3479 0.75 15.235L0.75 8.76499C0.75 7.65214 1.65214 6.75 2.76499 6.75L3.78947 6.75", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 6.75, + y: 0.75, + width: 10.5, + height: 10.5, + rx: 2.2069, + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgDeprecatedArgument = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M5 9L9 5", + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M5 5L9 9", + stroke: "currentColor", + strokeWidth: 1.2, + }) + ); + const SvgDeprecatedEnumValue = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4 8L8 4", + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4 4L8 8", + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", + fill: "currentColor", + }) + ); + const SvgDeprecatedField = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 10.8, + height: 10.8, + rx: 3.4, + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4 8L8 4", + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4 4L8 8", + stroke: "currentColor", + strokeWidth: 1.2, + }) + ); + const SvgDirective = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0.5 12 12", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 7, + y: 5.5, + width: 2, + height: 2, + rx: 1, + transform: "rotate(90 7 5.5)", + fill: "currentColor", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M10.8 9L10.8 9.5C10.8 10.4941 9.99411 11.3 9 11.3L3 11.3C2.00589 11.3 1.2 10.4941 1.2 9.5L1.2 9L-3.71547e-07 9L-3.93402e-07 9.5C-4.65826e-07 11.1569 1.34314 12.5 3 12.5L9 12.5C10.6569 12.5 12 11.1569 12 9.5L12 9L10.8 9ZM10.8 4L12 4L12 3.5C12 1.84315 10.6569 0.5 9 0.5L3 0.5C1.34315 0.5 -5.87117e-08 1.84315 -1.31135e-07 3.5L-1.5299e-07 4L1.2 4L1.2 3.5C1.2 2.50589 2.00589 1.7 3 1.7L9 1.7C9.99411 1.7 10.8 2.50589 10.8 3.5L10.8 4Z", + fill: "currentColor", + }) + ); + const SvgDocsFilled = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 20 24", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H17.25C17.8023 0.75 18.25 1.19772 18.25 1.75V5.25", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H18.25C18.8023 5.25 19.25 5.69771 19.25 6.25V22.25C19.25 22.8023 18.8023 23.25 18.25 23.25H3C1.75736 23.25 0.75 22.2426 0.75 21V3Z", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M3 5.25C1.75736 5.25 0.75 4.24264 0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H3ZM13 11L6 11V12.5L13 12.5V11Z", + fill: "currentColor", + }) + ); + const SvgDocs = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 20 24", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H17.25M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H16.25C16.8023 0.75 17.25 1.19772 17.25 1.75V5.25M0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H17.25", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("line", { + x1: 13, + y1: 11.75, + x2: 6, + y2: 11.75, + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgEnumValue = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 5, + y: 5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", + fill: "currentColor", + }) + ); + const SvgField = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 12 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 0.6, + y: 1.1, + width: 10.8, + height: 10.8, + rx: 2.4, + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 5, + y: 5.5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor", + }) + ); + const SvgHistory = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 24 20", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M1.59375 9.52344L4.87259 12.9944L8.07872 9.41249", + stroke: "currentColor", + strokeWidth: 1.5, + strokeLinecap: "square", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M13.75 5.25V10.75H18.75", + stroke: "currentColor", + strokeWidth: 1.5, + strokeLinecap: "square", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4.95427 11.9332C4.55457 10.0629 4.74441 8.11477 5.49765 6.35686C6.25089 4.59894 7.5305 3.11772 9.16034 2.11709C10.7902 1.11647 12.6901 0.645626 14.5986 0.769388C16.5071 0.893151 18.3303 1.60543 19.8172 2.80818C21.3042 4.01093 22.3818 5.64501 22.9017 7.48548C23.4216 9.32595 23.3582 11.2823 22.7203 13.0853C22.0824 14.8883 20.9013 16.4492 19.3396 17.5532C17.778 18.6572 15.9125 19.25 14 19.25", + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgImplements = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("circle", { + cx: 6, + cy: 6, + r: 5.4, + stroke: "currentColor", + strokeWidth: 1.2, + strokeDasharray: "4.241025 4.241025", + transform: "rotate(22.5)", + "transform-origin": "center", + }), + /* @__PURE__ */ React__namespace.createElement("circle", { + cx: 6, + cy: 6, + r: 1, + fill: "currentColor", + }) + ); + const SvgKeyboardShortcut = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 19 18", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M1.5 14.5653C1.5 15.211 1.75652 15.8303 2.21314 16.2869C2.66975 16.7435 3.28905 17 3.9348 17C4.58054 17 5.19984 16.7435 5.65646 16.2869C6.11307 15.8303 6.36959 15.211 6.36959 14.5653V12.1305H3.9348C3.28905 12.1305 2.66975 12.387 2.21314 12.8437C1.75652 13.3003 1.5 13.9195 1.5 14.5653Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M3.9348 1.00063C3.28905 1.00063 2.66975 1.25715 2.21314 1.71375C1.75652 2.17035 1.5 2.78964 1.5 3.43537C1.5 4.0811 1.75652 4.70038 2.21314 5.15698C2.66975 5.61358 3.28905 5.8701 3.9348 5.8701H6.36959V3.43537C6.36959 2.78964 6.11307 2.17035 5.65646 1.71375C5.19984 1.25715 4.58054 1.00063 3.9348 1.00063Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M15.0652 12.1305H12.6304V14.5653C12.6304 15.0468 12.7732 15.5175 13.0407 15.9179C13.3083 16.3183 13.6885 16.6304 14.1334 16.8147C14.5783 16.9989 15.0679 17.0472 15.5402 16.9532C16.0125 16.8593 16.4464 16.6274 16.7869 16.2869C17.1274 15.9464 17.3593 15.5126 17.4532 15.0403C17.5472 14.568 17.4989 14.0784 17.3147 13.6335C17.1304 13.1886 16.8183 12.8084 16.4179 12.5409C16.0175 12.2733 15.5468 12.1305 15.0652 12.1305Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M12.6318 5.86775H6.36955V12.1285H12.6318V5.86775Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M17.5 3.43473C17.5 2.789 17.2435 2.16972 16.7869 1.71312C16.3303 1.25652 15.711 1 15.0652 1C14.4195 1 13.8002 1.25652 13.3435 1.71312C12.8869 2.16972 12.6304 2.789 12.6304 3.43473V5.86946H15.0652C15.711 5.86946 16.3303 5.61295 16.7869 5.15635C17.2435 4.69975 17.5 4.08046 17.5 3.43473Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round", + }) + ); + const SvgMagnifyingGlass = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("circle", { + cx: 5, + cy: 5, + r: 4.35, + stroke: "currentColor", + strokeWidth: 1.3, + }), + /* @__PURE__ */ React__namespace.createElement("line", { + x1: 8.45962, + y1: 8.54038, + x2: 11.7525, + y2: 11.8333, + stroke: "currentColor", + strokeWidth: 1.3, + }) + ); + const SvgMerge = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "-2 -2 22 22", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M17.2492 6V2.9569C17.2492 1.73806 16.2611 0.75 15.0423 0.75L2.9569 0.75C1.73806 0.75 0.75 1.73806 0.75 2.9569L0.75 6", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M0.749873 12V15.0431C0.749873 16.2619 1.73794 17.25 2.95677 17.25H15.0421C16.261 17.25 17.249 16.2619 17.249 15.0431V12", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M6 4.5L9 7.5L12 4.5", + stroke: "currentColor", + strokeWidth: 1.5, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M12 13.5L9 10.5L6 13.5", + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgPen = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M0.75 13.25L0.0554307 12.967C-0.0593528 13.2488 0.00743073 13.5719 0.224488 13.7851C0.441545 13.9983 0.765869 14.0592 1.04549 13.9393L0.75 13.25ZM12.8214 1.83253L12.2911 2.36286L12.2911 2.36286L12.8214 1.83253ZM12.8214 3.90194L13.3517 4.43227L12.8214 3.90194ZM10.0981 1.17859L9.56773 0.648259L10.0981 1.17859ZM12.1675 1.17859L12.6978 0.648258L12.6978 0.648257L12.1675 1.17859ZM2.58049 8.75697L3.27506 9.03994L2.58049 8.75697ZM2.70066 8.57599L3.23099 9.10632L2.70066 8.57599ZM5.2479 11.4195L4.95355 10.7297L5.2479 11.4195ZM5.42036 11.303L4.89003 10.7727L5.42036 11.303ZM4.95355 10.7297C4.08882 11.0987 3.41842 11.362 2.73535 11.6308C2.05146 11.9 1.35588 12.1743 0.454511 12.5607L1.04549 13.9393C1.92476 13.5624 2.60256 13.2951 3.28469 13.0266C3.96762 12.7578 4.65585 12.4876 5.54225 12.1093L4.95355 10.7297ZM1.44457 13.533L3.27506 9.03994L1.88592 8.474L0.0554307 12.967L1.44457 13.533ZM3.23099 9.10632L10.6284 1.70892L9.56773 0.648259L2.17033 8.04566L3.23099 9.10632ZM11.6371 1.70892L12.2911 2.36286L13.3517 1.3022L12.6978 0.648258L11.6371 1.70892ZM12.2911 3.37161L4.89003 10.7727L5.95069 11.8333L13.3517 4.43227L12.2911 3.37161ZM12.2911 2.36286C12.5696 2.64142 12.5696 3.09305 12.2911 3.37161L13.3517 4.43227C14.2161 3.56792 14.2161 2.16654 13.3517 1.3022L12.2911 2.36286ZM10.6284 1.70892C10.9069 1.43036 11.3586 1.43036 11.6371 1.70892L12.6978 0.648257C11.8335 -0.216088 10.4321 -0.216084 9.56773 0.648259L10.6284 1.70892ZM3.27506 9.03994C3.26494 9.06479 3.24996 9.08735 3.23099 9.10632L2.17033 8.04566C2.04793 8.16806 1.95123 8.31369 1.88592 8.474L3.27506 9.03994ZM5.54225 12.1093C5.69431 12.0444 5.83339 11.9506 5.95069 11.8333L4.89003 10.7727C4.90863 10.7541 4.92988 10.7398 4.95355 10.7297L5.54225 12.1093Z", + fill: "currentColor", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M11.5 4.5L9.5 2.5", + stroke: "currentColor", + strokeWidth: 1.4026, + strokeLinecap: "round", + strokeLinejoin: "round", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M5.5 10.5L3.5 8.5", + stroke: "currentColor", + strokeWidth: 1.4026, + strokeLinecap: "round", + strokeLinejoin: "round", + }) + ); + const SvgPlay = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 16 18", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M1.32226e-07 1.6609C7.22332e-08 0.907329 0.801887 0.424528 1.46789 0.777117L15.3306 8.11621C16.0401 8.49182 16.0401 9.50818 15.3306 9.88379L1.46789 17.2229C0.801886 17.5755 1.36076e-06 17.0927 1.30077e-06 16.3391L1.32226e-07 1.6609Z", + fill: "currentColor", + }) + ); + const SvgPlus = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 10 16", + fill: "currentColor", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M4.25 9.25V13.5H5.75V9.25L10 9.25V7.75L5.75 7.75V3.5H4.25V7.75L0 7.75V9.25L4.25 9.25Z", + }) + ); + const SvgPrettify = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + width: 25, + height: 25, + viewBox: "0 0 25 25", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M10.2852 24.0745L13.7139 18.0742", + stroke: "currentColor", + strokeWidth: 1.5625, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M14.5742 24.0749L17.1457 19.7891", + stroke: "currentColor", + strokeWidth: 1.5625, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M19.4868 24.0735L20.7229 21.7523C21.3259 20.6143 21.5457 19.3122 21.3496 18.0394C21.1535 16.7666 20.5519 15.591 19.6342 14.6874L23.7984 6.87853C24.0123 6.47728 24.0581 6.00748 23.9256 5.57249C23.7932 5.1375 23.4933 4.77294 23.0921 4.55901C22.6908 4.34509 22.221 4.29932 21.7861 4.43178C21.3511 4.56424 20.9865 4.86408 20.7726 5.26533L16.6084 13.0742C15.3474 12.8142 14.0362 12.9683 12.8699 13.5135C11.7035 14.0586 10.7443 14.9658 10.135 16.1L6 24.0735", + stroke: "currentColor", + strokeWidth: 1.5625, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4 15L5 13L7 12L5 11L4 9L3 11L1 12L3 13L4 15Z", + stroke: "currentColor", + strokeWidth: 1.5625, + strokeLinejoin: "round", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M11.5 8L12.6662 5.6662L15 4.5L12.6662 3.3338L11.5 1L10.3338 3.3338L8 4.5L10.3338 5.6662L11.5 8Z", + stroke: "currentColor", + strokeWidth: 1.5625, + strokeLinejoin: "round", + }) + ); + const SvgReload = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 16 16", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4.75 9.25H1.25V12.75", + stroke: "currentColor", + strokeWidth: 1, + strokeLinecap: "square", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M11.25 6.75H14.75V3.25", + stroke: "currentColor", + strokeWidth: 1, + strokeLinecap: "square", + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M14.1036 6.65539C13.8 5.27698 13.0387 4.04193 11.9437 3.15131C10.8487 2.26069 9.48447 1.76694 8.0731 1.75043C6.66173 1.73392 5.28633 2.19563 4.17079 3.0604C3.05526 3.92516 2.26529 5.14206 1.92947 6.513", + stroke: "currentColor", + strokeWidth: 1, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M1.89635 9.34461C2.20001 10.723 2.96131 11.9581 4.05631 12.8487C5.15131 13.7393 6.51553 14.2331 7.9269 14.2496C9.33827 14.2661 10.7137 13.8044 11.8292 12.9396C12.9447 12.0748 13.7347 10.8579 14.0705 9.487", + stroke: "currentColor", + strokeWidth: 1, + }) + ); + const SvgRootType = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 11.8, + height: 11.8, + rx: 5.9, + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M4.25 7.5C4.25 6 5.75 5 6.5 6.5C7.25 8 8.75 7 8.75 5.5", + stroke: "currentColor", + strokeWidth: 1.2, + }) + ); + const SvgSettings = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 21 20", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M9.29186 1.92702C9.06924 1.82745 8.87014 1.68202 8.70757 1.50024L7.86631 0.574931C7.62496 0.309957 7.30773 0.12592 6.95791 0.0479385C6.60809 -0.0300431 6.24274 0.00182978 5.91171 0.139208C5.58068 0.276585 5.3001 0.512774 5.10828 0.815537C4.91645 1.1183 4.82272 1.47288 4.83989 1.83089L4.90388 3.08019C4.91612 3.32348 4.87721 3.56662 4.78968 3.79394C4.70215 4.02126 4.56794 4.2277 4.39571 4.39994C4.22347 4.57219 4.01704 4.7064 3.78974 4.79394C3.56243 4.88147 3.3193 4.92038 3.07603 4.90814L1.8308 4.84414C1.47162 4.82563 1.11553 4.91881 0.811445 5.11086C0.507359 5.30292 0.270203 5.58443 0.132561 5.91671C-0.00508149 6.249 -0.0364554 6.61576 0.0427496 6.9666C0.121955 7.31744 0.307852 7.63514 0.5749 7.87606L1.50016 8.71204C1.68193 8.87461 1.82735 9.07373 1.92692 9.29636C2.02648 9.51898 2.07794 9.76012 2.07794 10.004C2.07794 10.2479 2.02648 10.489 1.92692 10.7116C1.82735 10.9343 1.68193 11.1334 1.50016 11.296L0.5749 12.1319C0.309856 12.3729 0.125575 12.6898 0.0471809 13.0393C-0.0312128 13.3888 9.64098e-05 13.754 0.13684 14.0851C0.273583 14.4162 0.509106 14.6971 0.811296 14.8894C1.11349 15.0817 1.46764 15.1762 1.82546 15.1599L3.0707 15.0959C3.31397 15.0836 3.5571 15.1225 3.7844 15.2101C4.01171 15.2976 4.21814 15.4318 4.39037 15.6041C4.56261 15.7763 4.69682 15.9827 4.78435 16.2101C4.87188 16.4374 4.91078 16.6805 4.89855 16.9238L4.83455 18.1691C4.81605 18.5283 4.90921 18.8844 5.10126 19.1885C5.2933 19.4926 5.5748 19.7298 5.90707 19.8674C6.23934 20.0051 6.60608 20.0365 6.9569 19.9572C7.30772 19.878 7.6254 19.6921 7.86631 19.4251L8.7129 18.4998C8.87547 18.318 9.07458 18.1725 9.29719 18.073C9.51981 17.9734 9.76093 17.9219 10.0048 17.9219C10.2487 17.9219 10.4898 17.9734 10.7124 18.073C10.935 18.1725 11.1341 18.318 11.2967 18.4998L12.1326 19.4251C12.3735 19.6921 12.6912 19.878 13.042 19.9572C13.3929 20.0365 13.7596 20.0051 14.0919 19.8674C14.4241 19.7298 14.7056 19.4926 14.8977 19.1885C15.0897 18.8844 15.1829 18.5283 15.1644 18.1691L15.1004 16.9238C15.0882 16.6805 15.1271 16.4374 15.2146 16.2101C15.3021 15.9827 15.4363 15.7763 15.6086 15.6041C15.7808 15.4318 15.9872 15.2976 16.2145 15.2101C16.4418 15.1225 16.685 15.0836 16.9282 15.0959L18.1735 15.1599C18.5326 15.1784 18.8887 15.0852 19.1928 14.8931C19.4969 14.7011 19.7341 14.4196 19.8717 14.0873C20.0093 13.755 20.0407 13.3882 19.9615 13.0374C19.8823 12.6866 19.6964 12.3689 19.4294 12.1279L18.5041 11.292C18.3223 11.1294 18.1769 10.9303 18.0774 10.7076C17.9778 10.485 17.9263 10.2439 17.9263 10C17.9263 9.75612 17.9778 9.51499 18.0774 9.29236C18.1769 9.06973 18.3223 8.87062 18.5041 8.70804L19.4294 7.87206C19.6964 7.63114 19.8823 7.31344 19.9615 6.9626C20.0407 6.61176 20.0093 6.245 19.8717 5.91271C19.7341 5.58043 19.4969 5.29892 19.1928 5.10686C18.8887 4.91481 18.5326 4.82163 18.1735 4.84014L16.9282 4.90414C16.685 4.91638 16.4418 4.87747 16.2145 4.78994C15.9872 4.7024 15.7808 4.56818 15.6086 4.39594C15.4363 4.2237 15.3021 4.01726 15.2146 3.78994C15.1271 3.56262 15.0882 3.31948 15.1004 3.07619L15.1644 1.83089C15.1829 1.4717 15.0897 1.11559 14.8977 0.811487C14.7056 0.507385 14.4241 0.270217 14.0919 0.132568C13.7596 -0.00508182 13.3929 -0.0364573 13.042 0.0427519C12.6912 0.121961 12.3735 0.307869 12.1326 0.574931L11.2914 1.50024C11.1288 1.68202 10.9297 1.82745 10.7071 1.92702C10.4845 2.02659 10.2433 2.07805 9.99947 2.07805C9.7556 2.07805 9.51448 2.02659 9.29186 1.92702ZM14.3745 10C14.3745 12.4162 12.4159 14.375 9.99977 14.375C7.58365 14.375 5.625 12.4162 5.625 10C5.625 7.58375 7.58365 5.625 9.99977 5.625C12.4159 5.625 14.3745 7.58375 14.3745 10Z", + fill: "currentColor", + }) + ); + const SvgStarFilled = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", + fill: "currentColor", + stroke: "currentColor", + }) + ); + const SvgStar = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", + stroke: "currentColor", + strokeWidth: 1.5, + }) + ); + const SvgStop = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 16 16", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + width: 16, + height: 16, + rx: 2, + fill: "currentColor", + }) + ); + const SvgTrash = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + width: "1em", + height: "5em", + xmlns: "http://www.w3.org/2000/svg", + fillRule: "evenodd", + "aria-hidden": "true", + viewBox: "0 0 23 23", + style: { + height: "1.5em", + }, + clipRule: "evenodd", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("path", { + d: "M19 24h-14c-1.104 0-2-.896-2-2v-17h-1v-2h6v-1.5c0-.827.673-1.5 1.5-1.5h5c.825 0 1.5.671 1.5 1.5v1.5h6v2h-1v17c0 1.104-.896 2-2 2zm0-19h-14v16.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-16.5zm-7 7.586l3.293-3.293 1.414 1.414-3.293 3.293 3.293 3.293-1.414 1.414-3.293-3.293-3.293 3.293-1.414-1.414 3.293-3.293-3.293-3.293 1.414-1.414 3.293 3.293zm2-10.586h-4v1h4v-1z", + fill: "currentColor", + strokeWidth: 0.25, + stroke: "currentColor", + }) + ); + const SvgType = ({ title, titleId, ...props }) => + /* @__PURE__ */ React__namespace.createElement( + "svg", + { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props, + }, + title + ? /* @__PURE__ */ React__namespace.createElement( + "title", + { + id: titleId, + }, + title + ) + : null, + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 11.8, + height: 11.8, + rx: 5.9, + stroke: "currentColor", + strokeWidth: 1.2, + }), + /* @__PURE__ */ React__namespace.createElement("rect", { + x: 5.5, + y: 5.5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor", + }) + ); + const ArgumentIcon = generateIcon(SvgArgument); + const ChevronDownIcon = generateIcon(SvgChevronDown); + const ChevronLeftIcon = generateIcon(SvgChevronLeft); + const ChevronUpIcon = generateIcon(SvgChevronUp); + const CloseIcon = generateIcon(SvgClose); + const CopyIcon = generateIcon(SvgCopy); + const DeprecatedArgumentIcon = generateIcon(SvgDeprecatedArgument); + const DeprecatedEnumValueIcon = generateIcon(SvgDeprecatedEnumValue); + const DeprecatedFieldIcon = generateIcon(SvgDeprecatedField); + const DirectiveIcon = generateIcon(SvgDirective); + const DocsFilledIcon = generateIcon(SvgDocsFilled); + const DocsIcon = generateIcon(SvgDocs); + const EnumValueIcon = generateIcon(SvgEnumValue); + const FieldIcon = generateIcon(SvgField); + const HistoryIcon = generateIcon(SvgHistory); + const ImplementsIcon = generateIcon(SvgImplements); + const KeyboardShortcutIcon = generateIcon(SvgKeyboardShortcut); + const MagnifyingGlassIcon = generateIcon(SvgMagnifyingGlass); + const MergeIcon = generateIcon(SvgMerge); + const PenIcon = generateIcon(SvgPen); + const PlayIcon = generateIcon(SvgPlay); + const PlusIcon = generateIcon(SvgPlus); + const PrettifyIcon = generateIcon(SvgPrettify); + const ReloadIcon = generateIcon(SvgReload); + const RootTypeIcon = generateIcon(SvgRootType); + const SettingsIcon = generateIcon(SvgSettings); + const StarFilledIcon = generateIcon(SvgStarFilled); + const StarIcon = generateIcon(SvgStar); + const StopIcon = generateIcon(SvgStop); + const TrashIcon = generateIcon(SvgTrash); + const TypeIcon = generateIcon(SvgType); + function generateIcon(RawComponent) { + const title = + RawComponent.name + .replace("Svg", "") + .replaceAll(/([A-Z])/g, " $1") + .trimStart() + .toLowerCase() + " icon"; + function IconComponent(props) { + return /* @__PURE__ */ jsxRuntime.jsx(RawComponent, { + title, + ...props, + }); } + IconComponent.displayName = RawComponent.name; + return IconComponent; } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - var nw; - if (old) { - for (var i2 = 0; i2 < old.length; ++i2) { - var span = old[i2], - marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); - } - } + const UnStyledButton = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-un-styled", props.className), + }) + ); + UnStyledButton.displayName = "UnStyledButton"; + const Button$1 = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx( + "graphiql-button", + { + success: "graphiql-button-success", + error: "graphiql-button-error", + }[props.state], + props.className + ), + }) + ); + Button$1.displayName = "Button"; + const ButtonGroup = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx("graphiql-button-group", props.className), + }) + ); + ButtonGroup.displayName = "ButtonGroup"; + const createComponentGroup = (root, children) => + Object.entries(children).reduce((r, [key, value]) => { + r[key] = value; + return r; + }, root); + const DialogClose = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Close, { + asChild: true, + children: /* @__PURE__ */ jsxRuntime.jsxs(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-dialog-close", props.className), + children: [ + /* @__PURE__ */ jsxRuntime.jsx(reactVisuallyHidden.Root, { + children: "Close dialog", + }), + /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}), + ], + }), + }) + ); + DialogClose.displayName = "Dialog.Close"; + function DialogRoot({ children, ...props }) { + return /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Root, { + ...props, + children: /* @__PURE__ */ jsxRuntime.jsxs(D__namespace.Portal, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Overlay, { + className: "graphiql-dialog-overlay", + }), + /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Content, { + className: "graphiql-dialog", + children, + }), + ], + }), + }); } - return nw; - } - function stretchSpansOverChange(doc, change) { - if (change.full) { - return null; + const Dialog = createComponentGroup(DialogRoot, { + Close: DialogClose, + Title: D__namespace.Title, + Trigger: D__namespace.Trigger, + Description: D__namespace.Description, + }); + const Button = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx(reactDropdownMenu.Trigger, { + asChild: true, + children: /* @__PURE__ */ jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-un-styled", props.className), + }), + }) + ); + Button.displayName = "DropdownMenuButton"; + function Content({ + children, + align = "start", + sideOffset = 5, + className, + ...props + }) { + return /* @__PURE__ */ jsxRuntime.jsx(reactDropdownMenu.Portal, { + children: /* @__PURE__ */ jsxRuntime.jsx( + reactDropdownMenu.Content, + { + align, + sideOffset, + className: clsx.clsx("graphiql-dropdown-content", className), + ...props, + children, + } + ), + }); } - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) { - return null; + const Item = ({ className, children, ...props }) => + /* @__PURE__ */ jsxRuntime.jsx(reactDropdownMenu.Item, { + className: clsx.clsx("graphiql-dropdown-item", className), + ...props, + children, + }); + const DropdownMenu = createComponentGroup(reactDropdownMenu.Root, { + Button, + Item, + Content, + }); + const markdown = new MarkdownIt({ + breaks: true, + linkify: true, + }); + const MarkdownContent = React.forwardRef( + ({ children, onlyShowFirstChild, type, ...props }, ref) => + /* @__PURE__ */ jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx( + `graphiql-markdown-${type}`, + onlyShowFirstChild && "graphiql-markdown-preview", + props.className + ), + dangerouslySetInnerHTML: { + __html: markdown.render(children), + }, + }) + ); + MarkdownContent.displayName = "MarkdownContent"; + const Spinner = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx("graphiql-spinner", props.className), + }) + ); + Spinner.displayName = "Spinner"; + function TooltipRoot({ + children, + align = "start", + side = "bottom", + sideOffset = 5, + label, + }) { + return /* @__PURE__ */ jsxRuntime.jsxs(T__namespace.Root, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx(T__namespace.Trigger, { + asChild: true, + children, + }), + /* @__PURE__ */ jsxRuntime.jsx(T__namespace.Portal, { + children: /* @__PURE__ */ jsxRuntime.jsx(T__namespace.Content, { + className: "graphiql-tooltip", + align, + side, + sideOffset, + children: label, + }), + }), + ], + }); } - var startCh = change.from.ch, - endCh = change.to.ch, - isInsert = cmp(change.from, change.to) == 0; - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - var sameLine = change.text.length == 1, - offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - for (var i2 = 0; i2 < first.length; ++i2) { - var span = first[i2]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) { - span.to = startCh; - } else if (sameLine) { - span.to = found.to == null ? null : found.to + offset; - } - } - } + const Tooltip = createComponentGroup(TooltipRoot, { + Provider: T__namespace.Provider, + }); + const TabRoot = React.forwardRef( + ({ isActive, value, children, className, ...props }, ref) => + /* @__PURE__ */ jsxRuntime.jsx(framerMotion.Reorder.Item, { + ...props, + ref, + value, + "aria-selected": isActive ? "true" : void 0, + role: "tab", + className: clsx.clsx( + "graphiql-tab", + isActive && "graphiql-tab-active", + className + ), + children, + }) + ); + TabRoot.displayName = "Tab"; + const TabButton = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-tab-button", props.className), + children: props.children, + }) + ); + TabButton.displayName = "Tab.Button"; + const TabClose = React.forwardRef((props, ref) => + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label: "Close Tab", + children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + "aria-label": "Close Tab", + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-tab-close", props.className), + children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}), + }), + }) + ); + TabClose.displayName = "Tab.Close"; + const Tab = createComponentGroup(TabRoot, { + Button: TabButton, + Close: TabClose, + }); + const Tabs = React.forwardRef( + ({ values, onReorder, children, className, ...props }, ref) => + /* @__PURE__ */ jsxRuntime.jsx(framerMotion.Reorder.Group, { + ...props, + ref, + values, + onReorder, + axis: "x", + role: "tablist", + className: clsx.clsx("graphiql-tabs", className), + children, + }) + ); + Tabs.displayName = "Tabs"; + const HistoryContext = createNullableContext("HistoryContext"); + function HistoryContextProvider(props) { + var _a; + const storage = useStorageContext(); + const historyStore = React.useRef( + new toolkit.HistoryStore( + // Fall back to a noop storage when the StorageContext is empty + storage || new toolkit.StorageAPI(null), + props.maxHistoryLength || DEFAULT_HISTORY_LENGTH + ) + ); + const [items, setItems] = React.useState( + ((_a = historyStore.current) == null ? void 0 : _a.queries) || [] + ); + const addToHistory = React.useCallback((operation) => { + var _a2; + (_a2 = historyStore.current) == null + ? void 0 + : _a2.updateHistory(operation); + setItems(historyStore.current.queries); + }, []); + const editLabel = React.useCallback((operation, index) => { + historyStore.current.editLabel(operation, index); + setItems(historyStore.current.queries); + }, []); + const toggleFavorite = React.useCallback((operation) => { + historyStore.current.toggleFavorite(operation); + setItems(historyStore.current.queries); + }, []); + const setActive = React.useCallback((item) => { + return item; + }, []); + const deleteFromHistory = React.useCallback( + (item, clearFavorites = false) => { + historyStore.current.deleteHistory(item, clearFavorites); + setItems(historyStore.current.queries); + }, + [] + ); + const value = React.useMemo( + () => ({ + addToHistory, + editLabel, + items, + toggleFavorite, + setActive, + deleteFromHistory, + }), + [ + addToHistory, + editLabel, + items, + toggleFavorite, + setActive, + deleteFromHistory, + ] + ); + return /* @__PURE__ */ jsxRuntime.jsx(HistoryContext.Provider, { + value, + children: props.children, + }); } - if (last) { - for (var i$12 = 0; i$12 < last.length; ++i$12) { - var span$1 = last[i$12]; - if (span$1.to != null) { - span$1.to += offset; + const useHistoryContext = createContextHook(HistoryContext); + const DEFAULT_HISTORY_LENGTH = 20; + function History() { + const { items: all, deleteFromHistory } = useHistoryContext({ + nonNull: true, + }); + let items = all + .slice() + .map((item, i) => ({ + ...item, + index: i, + })) + .reverse(); + const favorites = items.filter((item) => item.favorite); + if (favorites.length) { + items = items.filter((item) => !item.favorite); + } + const [clearStatus, setClearStatus] = React.useState(null); + React.useEffect(() => { + if (clearStatus) { + setTimeout(() => { + setClearStatus(null); + }, 2e3); } - if (span$1.from == null) { - var found$1 = getMarkedSpanFor(first, span$1.marker); - if (!found$1) { - span$1.from = offset; - if (sameLine) { - (first || (first = [])).push(span$1); - } - } - } else { - span$1.from += offset; - if (sameLine) { - (first || (first = [])).push(span$1); + }, [clearStatus]); + const handleClearStatus = React.useCallback(() => { + try { + for (const item of items) { + deleteFromHistory(item, true); } + setClearStatus("success"); + } catch { + setClearStatus("error"); } - } - } - if (first) { - first = clearEmptySpans(first); - } - if (last && last != first) { - last = clearEmptySpans(last); + }, [deleteFromHistory, items]); + return /* @__PURE__ */ jsxRuntime.jsxs("section", { + "aria-label": "History", + className: "graphiql-history", + children: [ + /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-history-header", + children: [ + "History", + (clearStatus || items.length > 0) && + /* @__PURE__ */ jsxRuntime.jsx(Button$1, { + type: "button", + state: clearStatus || void 0, + disabled: !items.length, + onClick: handleClearStatus, + children: + { + success: "Cleared", + error: "Failed to Clear", + }[clearStatus] || "Clear", + }), + ], + }), + Boolean(favorites.length) && + /* @__PURE__ */ jsxRuntime.jsx("ul", { + className: "graphiql-history-items", + children: favorites.map((item) => + /* @__PURE__ */ jsxRuntime.jsx( + HistoryItem, + { + item, + }, + item.index + ) + ), + }), + Boolean(favorites.length) && + Boolean(items.length) && + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-history-item-spacer", + }), + Boolean(items.length) && + /* @__PURE__ */ jsxRuntime.jsx("ul", { + className: "graphiql-history-items", + children: items.map((item) => + /* @__PURE__ */ jsxRuntime.jsx( + HistoryItem, + { + item, + }, + item.index + ) + ), + }), + ], + }); } - var newMarkers = [first]; - if (!sameLine) { - var gap = change.text.length - 2, - gapMarkers; - if (gap > 0 && first) { - for (var i$22 = 0; i$22 < first.length; ++i$22) { - if (first[i$22].to == null) { - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null)); - } + function HistoryItem(props) { + const { editLabel, toggleFavorite, deleteFromHistory, setActive } = + useHistoryContext({ + nonNull: true, + caller: HistoryItem, + }); + const { headerEditor, queryEditor, variableEditor } = + useEditorContext({ + nonNull: true, + caller: HistoryItem, + }); + const inputRef = React.useRef(null); + const buttonRef = React.useRef(null); + const [isEditable, setIsEditable] = React.useState(false); + React.useEffect(() => { + var _a; + if (isEditable) { + (_a = inputRef.current) == null ? void 0 : _a.focus(); } - } - for (var i$3 = 0; i$3 < gap; ++i$3) { - newMarkers.push(gapMarkers); - } - newMarkers.push(last); + }, [isEditable]); + const displayName = + props.item.label || + props.item.operationName || + formatQuery(props.item.query); + const handleSave = React.useCallback(() => { + var _a; + setIsEditable(false); + const { index, ...item } = props.item; + editLabel( + { + ...item, + label: (_a = inputRef.current) == null ? void 0 : _a.value, + }, + index + ); + }, [editLabel, props.item]); + const handleClose = React.useCallback(() => { + setIsEditable(false); + }, []); + const handleEditLabel = React.useCallback((e) => { + e.stopPropagation(); + setIsEditable(true); + }, []); + const handleHistoryItemClick = React.useCallback(() => { + const { query, variables, headers } = props.item; + queryEditor == null + ? void 0 + : queryEditor.setValue( + query !== null && query !== void 0 ? query : "" + ); + variableEditor == null + ? void 0 + : variableEditor.setValue( + variables !== null && variables !== void 0 ? variables : "" + ); + headerEditor == null + ? void 0 + : headerEditor.setValue( + headers !== null && headers !== void 0 ? headers : "" + ); + setActive(props.item); + }, [ + headerEditor, + props.item, + queryEditor, + setActive, + variableEditor, + ]); + const handleDeleteItemFromHistory = React.useCallback( + (e) => { + e.stopPropagation(); + deleteFromHistory(props.item); + }, + [props.item, deleteFromHistory] + ); + const handleToggleFavorite = React.useCallback( + (e) => { + e.stopPropagation(); + toggleFavorite(props.item); + }, + [props.item, toggleFavorite] + ); + return /* @__PURE__ */ jsxRuntime.jsx("li", { + className: clsx.clsx( + "graphiql-history-item", + isEditable && "editable" + ), + children: isEditable + ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("input", { + type: "text", + defaultValue: props.item.label, + ref: inputRef, + onKeyDown: (e) => { + if (e.key === "Esc") { + setIsEditable(false); + } else if (e.key === "Enter") { + setIsEditable(false); + editLabel({ + ...props.item, + label: e.currentTarget.value, + }); + } + }, + placeholder: "Type a label", + }), + /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + type: "button", + ref: buttonRef, + onClick: handleSave, + children: "Save", + }), + /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + type: "button", + ref: buttonRef, + onClick: handleClose, + children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}), + }), + ], + }) + : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label: "Set active", + children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-label", + onClick: handleHistoryItemClick, + "aria-label": "Set active", + children: displayName, + }), + }), + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label: "Edit label", + children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleEditLabel, + "aria-label": "Edit label", + children: /* @__PURE__ */ jsxRuntime.jsx(PenIcon, { + "aria-hidden": "true", + }), + }), + }), + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label: props.item.favorite + ? "Remove favorite" + : "Add favorite", + children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleToggleFavorite, + "aria-label": props.item.favorite + ? "Remove favorite" + : "Add favorite", + children: props.item.favorite + ? /* @__PURE__ */ jsxRuntime.jsx(StarFilledIcon, { + "aria-hidden": "true", + }) + : /* @__PURE__ */ jsxRuntime.jsx(StarIcon, { + "aria-hidden": "true", + }), + }), + }), + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label: "Delete from history", + children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleDeleteItemFromHistory, + "aria-label": "Delete from history", + children: /* @__PURE__ */ jsxRuntime.jsx(TrashIcon, { + "aria-hidden": "true", + }), + }), + }), + ], + }), + }); } - return newMarkers; - } - function clearEmptySpans(spans) { - for (var i2 = 0; i2 < spans.length; ++i2) { - var span = spans[i2]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { - spans.splice(i2--, 1); + function formatQuery(query) { + return query == null + ? void 0 + : query + .split("\n") + .map((line) => line.replace(/#(.*)/, "")) + .join(" ") + .replaceAll("{", " { ") + .replaceAll("}", " } ") + .replaceAll(/[\s]{2,}/g, " "); + } + const ExecutionContext = createNullableContext("ExecutionContext"); + function ExecutionContextProvider({ + fetcher, + getDefaultFieldNames, + children, + operationName, + }) { + if (!fetcher) { + throw new TypeError( + "The `ExecutionContextProvider` component requires a `fetcher` function to be passed as prop." + ); } - } - if (!spans.length) { - return null; - } - return spans; - } - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function (line) { - if (line.markedSpans) { - for (var i3 = 0; i3 < line.markedSpans.length; ++i3) { - var mark = line.markedSpans[i3].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { - (markers || (markers = [])).push(mark); - } + const { + externalFragments, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + updateActiveTabValues, + } = useEditorContext({ + nonNull: true, + caller: ExecutionContextProvider, + }); + const history = useHistoryContext(); + const autoCompleteLeafs = useAutoCompleteLeafs({ + getDefaultFieldNames, + caller: ExecutionContextProvider, + }); + const [isFetching, setIsFetching] = React.useState(false); + const [subscription, setSubscription] = React.useState(null); + const queryIdRef = React.useRef(0); + const stop = React.useCallback(() => { + subscription == null ? void 0 : subscription.unsubscribe(); + setIsFetching(false); + setSubscription(null); + }, [subscription]); + const run = React.useCallback(async () => { + var _ref; + if (!queryEditor || !responseEditor) { + return; } - } - }); - if (!markers) { - return null; - } - var parts = [{ - from, - to - }]; - for (var i2 = 0; i2 < markers.length; ++i2) { - var mk = markers[i2], - m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { - continue; + if (subscription) { + stop(); + return; } - var newParts = [j, 1], - dfrom = cmp(p.from, m.from), - dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { - newParts.push({ - from: p.from, - to: m.from + const setResponse = (value2) => { + responseEditor.setValue(value2); + updateActiveTabValues({ + response: value2, }); - } - if (dto > 0 || !mk.inclusiveRight && !dto) { - newParts.push({ - from: m.to, - to: p.to + }; + queryIdRef.current += 1; + const queryId = queryIdRef.current; + let query = autoCompleteLeafs() || queryEditor.getValue(); + const variablesString = + variableEditor == null ? void 0 : variableEditor.getValue(); + let variables; + try { + variables = tryParseJsonObject({ + json: variablesString, + errorMessageParse: "Variables are invalid JSON", + errorMessageType: "Variables are not a JSON object.", }); + } catch (error) { + setResponse(error instanceof Error ? error.message : `${error}`); + return; } - parts.splice.apply(parts, newParts); - j += newParts.length - 3; - } - } - return parts; - } - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) { - return; - } - for (var i2 = 0; i2 < spans.length; ++i2) { - spans[i2].marker.detachLine(line); - } - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) { - return; - } - for (var i2 = 0; i2 < spans.length; ++i2) { - spans[i2].marker.attachLine(line); - } - line.markedSpans = spans; - } - function extraLeft(marker) { - return marker.inclusiveLeft ? -1 : 0; - } - function extraRight(marker) { - return marker.inclusiveRight ? 1 : 0; - } - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) { - return lenDiff; - } - var aPos = a.find(), - bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) { - return -fromCmp; - } - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) { - return toCmp; - } - return b.id - a.id; - } - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, - found; - if (sps) { - for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { - sp = sps[i2]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { - found = sp.marker; - } - } - } - return found; - } - function collapsedSpanAtStart(line) { - return collapsedSpanAtSide(line, true); - } - function collapsedSpanAtEnd(line) { - return collapsedSpanAtSide(line, false); - } - function collapsedSpanAround(line, ch) { - var sps = sawCollapsedSpans && line.markedSpans, - found; - if (sps) { - for (var i2 = 0; i2 < sps.length; ++i2) { - var sp = sps[i2]; - if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { - found = sp.marker; - } - } - } - return found; - } - function conflictingCollapsedRange(doc, lineNo2, from, to, marker) { - var line = getLine(doc, lineNo2); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { - for (var i2 = 0; i2 < sps.length; ++i2) { - var sp = sps[i2]; - if (!sp.marker.collapsed) { - continue; - } - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { - continue; - } - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { - return true; - } - } - } - } - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) { - line = merged.find(-1, true).line; - } - return line; - } - function visualLineEnd(line) { - var merged; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - } - return line; - } - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), - vis = visualLine(line); - if (line == vis) { - return lineN; - } - return lineNo(vis); - } - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) { - return lineN; - } - var line = getLine(doc, lineN), - merged; - if (!lineIsHidden(doc, line)) { - return lineN; - } - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - } - return lineNo(line) + 1; - } - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { - for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { - sp = sps[i2]; - if (!sp.marker.collapsed) { - continue; - } - if (sp.from == null) { - return true; - } - if (sp.marker.widgetNode) { - continue; - } - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { - return true; - } - } - } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) { - return true; - } - for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) { - sp = line.markedSpans[i2]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { - return true; - } - } - } - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - var h = 0, - chunk = lineObj.parent; - for (var i2 = 0; i2 < chunk.lines.length; ++i2) { - var line = chunk.lines[i2]; - if (line == lineObj) { - break; - } else { - h += line.height; - } - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i$12 = 0; i$12 < p.children.length; ++i$12) { - var cur = p.children[i$12]; - if (cur == chunk) { - break; - } else { - h += cur.height; - } - } - } - return h; - } - function lineLength(line) { - if (line.height == 0) { - return 0; - } - var len = line.text.length, - merged, - cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found$1 = merged.find(0, true); - len -= cur.text.length - found$1.from.ch; - cur = found$1.to.line; - len += cur.text.length - found$1.to.ch; - } - return len; - } - function findMaxLine(cm) { - var d = cm.display, - doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function (line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - var Line = function (text, markedSpans, estimateHeight2) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight2 ? estimateHeight2(this) : 1; - }; - Line.prototype.lineNo = function () { - return lineNo(this); - }; - eventMixin(Line); - function updateLine(line, text, markedSpans, estimateHeight2) { - line.text = text; - if (line.stateAfter) { - line.stateAfter = null; - } - if (line.styles) { - line.styles = null; - } - if (line.order != null) { - line.order = null; - } - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight2 ? estimateHeight2(line) : 1; - if (estHeight != line.height) { - updateLineHeight(line, estHeight); - } - } - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - var styleToClassCache = {}, - styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) { - return null; - } - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - function buildLineContent(cm, lineView) { - var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = { - pre: eltP("pre", [content], "CodeMirror-line"), - content, - col: 0, - pos: 0, - cm, - trailingSpace: false, - splitSpaces: cm.getOption("lineWrapping") - }; - lineView.measure = {}; - for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) { - var line = i2 ? lineView.rest[i2 - 1] : lineView.line, - order = void 0; - builder.pos = 0; - builder.addToken = buildToken; - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { - builder.addToken = buildTokenBadBidi(builder.addToken, order); - } - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) { - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - } - if (line.styleClasses.textClass) { - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - } - if (builder.map.length == 0) { - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - } - if (i2 == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - if (webkit) { - var last = builder.content.lastChild; - if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) { - builder.content.className = "cm-tab-wrap-hack"; - } - } - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) { - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - } - return builder; - } - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "•", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { - if (!text) { - return; - } - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; - var special = builder.cm.state.specialChars, - mustWrap = false; - var content; - if (!special.test(text)) { - builder.col += text.length; - content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) { - mustWrap = true; - } - builder.pos += text.length; - } else { - content = document.createDocumentFragment(); - var pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) { - content.appendChild(elt("span", [txt])); - } else { - content.appendChild(txt); - } - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) { - break; + const headersString = + headerEditor == null ? void 0 : headerEditor.getValue(); + let headers; + try { + headers = tryParseJsonObject({ + json: headersString, + errorMessageParse: "Headers are invalid JSON", + errorMessageType: "Headers are not a JSON object.", + }); + } catch (error) { + setResponse(error instanceof Error ? error.message : `${error}`); + return; } - pos += skipped + 1; - var txt$1 = void 0; - if (m[0] == " ") { - var tabSize = builder.cm.options.tabSize, - tabWidth = tabSize - builder.col % tabSize; - txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt$1.setAttribute("role", "presentation"); - txt$1.setAttribute("cm-text", " "); - builder.col += tabWidth; - } else if (m[0] == "\r" || m[0] == "\n") { - txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar")); - txt$1.setAttribute("cm-text", m[0]); - builder.col += 1; - } else { - txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); - txt$1.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) { - content.appendChild(elt("span", [txt$1])); - } else { - content.appendChild(txt$1); + if (externalFragments) { + const fragmentDependencies = queryEditor.documentAST + ? graphqlLanguageService.getFragmentDependenciesForAST( + queryEditor.documentAST, + externalFragments + ) + : []; + if (fragmentDependencies.length > 0) { + query += + "\n" + + fragmentDependencies + .map((node) => graphql.print(node)) + .join("\n"); } - builder.col += 1; } - builder.map.push(builder.pos, builder.pos + 1, txt$1); - builder.pos++; - } - } - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; - if (style || startStyle || endStyle || mustWrap || css || attributes) { - var fullStyle = style || ""; - if (startStyle) { - fullStyle += startStyle; - } - if (endStyle) { - fullStyle += endStyle; - } - var token = elt("span", [content], fullStyle, css); - if (attributes) { - for (var attr in attributes) { - if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { - token.setAttribute(attr, attributes[attr]); + setResponse(""); + setIsFetching(true); + const opName = + (_ref = + operationName !== null && operationName !== void 0 + ? operationName + : queryEditor.operationName) !== null && _ref !== void 0 + ? _ref + : void 0; + history == null + ? void 0 + : history.addToHistory({ + query, + variables: variablesString, + headers: headersString, + operationName: opName, + }); + try { + var _headers, _queryEditor$document; + const fullResponse = {}; + const handleResponse = (result) => { + if (queryId !== queryIdRef.current) { + return; + } + let maybeMultipart = Array.isArray(result) ? result : false; + if ( + !maybeMultipart && + typeof result === "object" && + result !== null && + "hasNext" in result + ) { + maybeMultipart = [result]; + } + if (maybeMultipart) { + for (const part of maybeMultipart) { + mergeIncrementalResult(fullResponse, part); + } + setIsFetching(false); + setResponse(toolkit.formatResult(fullResponse)); + } else { + const response = toolkit.formatResult(result); + setIsFetching(false); + setResponse(response); + } + }; + const fetch2 = fetcher( + { + query, + variables, + operationName: opName, + }, + { + headers: + (_headers = headers) !== null && _headers !== void 0 + ? _headers + : void 0, + documentAST: + (_queryEditor$document = queryEditor.documentAST) !== + null && _queryEditor$document !== void 0 + ? _queryEditor$document + : void 0, + } + ); + const value2 = await Promise.resolve(fetch2); + if (toolkit.isObservable(value2)) { + setSubscription( + value2.subscribe({ + next(result) { + handleResponse(result); + }, + error(error) { + setIsFetching(false); + if (error) { + setResponse(toolkit.formatError(error)); + } + setSubscription(null); + }, + complete() { + setIsFetching(false); + setSubscription(null); + }, + }) + ); + } else if (toolkit.isAsyncIterable(value2)) { + setSubscription({ + unsubscribe: () => { + var _a, _b; + return (_b = (_a = value2[Symbol.asyncIterator]()) + .return) == null + ? void 0 + : _b.call(_a); + }, + }); + for await (const result of value2) { + handleResponse(result); + } + setIsFetching(false); + setSubscription(null); + } else { + handleResponse(value2); } + } catch (error) { + setIsFetching(false); + setResponse(toolkit.formatError(error)); + setSubscription(null); } - } - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - function splitSpaces(text, trailingBefore) { - if (text.length > 1 && !/ /.test(text)) { - return text; + }, [ + autoCompleteLeafs, + externalFragments, + fetcher, + headerEditor, + history, + operationName, + queryEditor, + responseEditor, + stop, + subscription, + updateActiveTabValues, + variableEditor, + ]); + const isSubscribed = Boolean(subscription); + const value = React.useMemo( + () => ({ + isFetching, + isSubscribed, + operationName: + operationName !== null && operationName !== void 0 + ? operationName + : null, + run, + stop, + }), + [isFetching, isSubscribed, operationName, run, stop] + ); + return /* @__PURE__ */ jsxRuntime.jsx(ExecutionContext.Provider, { + value, + children, + }); } - var spaceBefore = trailingBefore, - result = ""; - for (var i2 = 0; i2 < text.length; i2++) { - var ch = text.charAt(i2); - if (ch == " " && spaceBefore && (i2 == text.length - 1 || text.charCodeAt(i2 + 1) == 32)) { - ch = " "; + const useExecutionContext = createContextHook(ExecutionContext); + function tryParseJsonObject({ + json, + errorMessageParse, + errorMessageType, + }) { + let parsed; + try { + parsed = json && json.trim() !== "" ? JSON.parse(json) : void 0; + } catch (error) { + throw new Error( + `${errorMessageParse}: ${ + error instanceof Error ? error.message : error + }.` + ); } - result += ch; - spaceBefore = ch == " "; - } - return result; - } - function buildTokenBadBidi(inner, order) { - return function (builder, text, style, startStyle, endStyle, css, attributes) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, - end = start + text.length; - for (;;) { - var part = void 0; - for (var i2 = 0; i2 < order.length; i2++) { - part = order[i2]; - if (part.to > start && part.from <= start) { - break; - } - } - if (part.to >= end) { - return inner(builder, text, style, startStyle, endStyle, css, attributes); + const isObject = + typeof parsed === "object" && + parsed !== null && + !Array.isArray(parsed); + if (parsed !== void 0 && !isObject) { + throw new Error(errorMessageType); + } + return parsed; + } + function mergeIncrementalResult(executionResult, incrementalResult) { + var _incrementalResult$pa; + const path = [ + "data", + ...((_incrementalResult$pa = incrementalResult.path) !== null && + _incrementalResult$pa !== void 0 + ? _incrementalResult$pa + : []), + ]; + if (incrementalResult.items) { + for (const item of incrementalResult.items) { + setValue(executionResult, path.join("."), item); + path[path.length - 1]++; } - inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) { - builder.map.push(builder.pos, builder.pos + size, widget); - } - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) { - widget = builder.content.appendChild(document.createElement("span")); - } - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - builder.trailingSpace = false; - } - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, - allText = line.text, - at = 0; - if (!spans) { - for (var i$12 = 1; i$12 < styles.length; i$12 += 2) { - builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options)); } - return; - } - var len = allText.length, - pos = 0, - i2 = 1, - text = "", - style, - css; - var nextChange = 0, - spanStyle, - spanEndStyle, - spanStartStyle, - collapsed, - attributes; - for (;;) { - if (nextChange == pos) { - spanStyle = spanEndStyle = spanStartStyle = css = ""; - attributes = null; - collapsed = null; - nextChange = Infinity; - var foundBookmarks = [], - endStyles = void 0; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], - m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) { - spanStyle += " " + m.className; - } - if (m.css) { - css = (css ? css + ";" : "") + m.css; - } - if (m.startStyle && sp.from == pos) { - spanStartStyle += " " + m.startStyle; - } - if (m.endStyle && sp.to == nextChange) { - (endStyles || (endStyles = [])).push(m.endStyle, sp.to); - } - if (m.title) { - (attributes || (attributes = {})).title = m.title; - } - if (m.attributes) { - for (var attr in m.attributes) { - (attributes || (attributes = {}))[attr] = m.attributes[attr]; - } - } - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { - collapsed = sp; - } - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (endStyles) { - for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { - if (endStyles[j$1 + 1] == nextChange) { - spanEndStyle += " " + endStyles[j$1]; - } - } - } - if (!collapsed || collapsed.from == pos) { - for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { - buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); - } - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); - if (collapsed.to == null) { - return; - } - if (collapsed.to == pos) { - collapsed = false; - } - } + if (incrementalResult.data) { + setValue(executionResult, path.join("."), incrementalResult.data, { + merge: true, + }); } - if (pos >= len) { - break; + if (incrementalResult.errors) { + executionResult.errors || (executionResult.errors = []); + executionResult.errors.push(...incrementalResult.errors); } - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); - } - if (end >= upto) { - text = text.slice(upto - pos); - pos = upto; - break; + if (incrementalResult.extensions) { + setValue( + executionResult, + "extensions", + incrementalResult.extensions, + { + merge: true, } - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i2++]); - style = interpretTokenStyle(styles[i2++], builder.cm.options); - } - } - } - function LineView(doc, line, lineN) { - this.line = line; - this.rest = visualLineContinued(line); - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - function buildViewArray(cm, from, to) { - var array = [], - nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array; - } - var operationGroup = null; - function pushOperation(op) { - if (operationGroup) { - operationGroup.ops.push(op); - } else { - op.ownsGroup = operationGroup = { - ops: [op], - delayedCallbacks: [] - }; - } - } - function fireCallbacksForOps(group) { - var callbacks = group.delayedCallbacks, - i2 = 0; - do { - for (; i2 < callbacks.length; i2++) { - callbacks[i2].call(null); + ); } - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) { - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { - op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); - } + if (incrementalResult.incremental) { + for (const incrementalSubResult of incrementalResult.incremental) { + mergeIncrementalResult(executionResult, incrementalSubResult); } } - } while (i2 < callbacks.length); - } - function finishOperation(op, endCb) { - var group = op.ownsGroup; - if (!group) { - return; - } - try { - fireCallbacksForOps(group); - } finally { - operationGroup = null; - endCb(group); } - } - var orphanDelayedCallbacks = null; - function signalLater(emitter, type) { - var arr = getHandlers(emitter, type); - if (!arr.length) { - return; - } - var args = Array.prototype.slice.call(arguments, 2), - list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - var loop = function (i3) { - list.push(function () { - return arr[i3].apply(null, args); - }); + const DEFAULT_EDITOR_THEME = "graphiql"; + const DEFAULT_KEY_MAP = "sublime"; + let isMacOs = false; + if (typeof window === "object") { + isMacOs = + window.navigator.platform.toLowerCase().indexOf("mac") === 0; + } + const commonKeys = { + // Persistent search box in Query Editor + [isMacOs ? "Cmd-F" : "Ctrl-F"]: "findPersistent", + "Cmd-G": "findPersistent", + "Ctrl-G": "findPersistent", + // Editor improvements + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", }; - for (var i2 = 0; i2 < arr.length; ++i2) loop(i2); - } - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i2 = 0; i2 < delayed.length; ++i2) { - delayed[i2](); - } - } - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") { - updateLineText(cm, lineView); - } else if (type == "gutter") { - updateLineGutter(cm, lineView, lineN, dims); - } else if (type == "class") { - updateLineClasses(cm, lineView); - } else if (type == "widget") { - updateLineWidgets(cm, lineView, dims); - } - } - lineView.changes = null; - } - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) { - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - } - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) { - lineView.node.style.zIndex = 2; - } - } - return lineView.node; - } - function updateLineBackground(cm, lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) { - cls += " CodeMirror-linebackground"; - } - if (lineView.background) { - if (cls) { - lineView.background.className = cls; - } else { - lineView.background.parentNode.removeChild(lineView.background); - lineView.background = null; - } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - cm.display.input.setUneditable(lineView.background); - } - } - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) { - lineView.node = built.pre; - } - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(cm, lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - function updateLineClasses(cm, lineView) { - updateLineBackground(cm, lineView); - if (lineView.line.wrapClass) { - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - } else if (lineView.node != lineView.text) { - lineView.node.className = ""; - } - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - if (lineView.gutterBackground) { - lineView.node.removeChild(lineView.gutterBackground); - lineView.gutterBackground = null; - } - if (lineView.line.gutterClass) { - var wrap = ensureLineWrapped(lineView); - lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px"); - cm.display.input.setUneditable(lineView.gutterBackground); - wrap.insertBefore(lineView.gutterBackground, lineView.text); - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap$1 = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); - gutterWrap.setAttribute("aria-hidden", "true"); - cm.display.input.setUneditable(gutterWrap); - wrap$1.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) { - gutterWrap.className += " " + lineView.line.gutterClass; - } - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { - lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px")); - } - if (markers) { - for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { - var id = cm.display.gutterSpecs[k].className, - found = markers.hasOwnProperty(id) && markers[id]; - if (found) { - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); - } - } - } - } - } - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) { - lineView.alignable = null; - } - var isWidget = classTest("CodeMirror-linewidget"); - for (var node = lineView.node.firstChild, next = void 0; node; node = next) { - next = node.nextSibling; - if (isWidget.test(node.className)) { - lineView.node.removeChild(node); - } - } - insertLineWidgets(cm, lineView, dims); - } - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) { - lineView.bgClass = built.bgClass; - } - if (built.textClass) { - lineView.textClass = built.textClass; - } - updateLineClasses(cm, lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; - } - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) { - for (var i2 = 0; i2 < lineView.rest.length; i2++) { - insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false); - } - } - } - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) { - return; - } - var wrap = ensureLineWrapped(lineView); - for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) { - var widget = ws[i2], - node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); - if (!widget.handleMouseEvents) { - node.setAttribute("cm-ignore-events", "true"); - } - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) { - wrap.insertBefore(node, lineView.gutter || lineView.text); - } else { - wrap.appendChild(node); - } - signalLater(widget, "redraw"); - } - } - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; + async function importCodeMirror(addons, options) { + const CodeMirror = await Promise.resolve() + .then(() => + __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ) + ) + .then((n) => n.codemirror) + .then((c) => + // Depending on bundler and settings the dynamic import either returns a + // function (e.g. parcel) or an object containing a `default` property + typeof c === "function" ? c : c.default + ); + await Promise.all( + (options == null ? void 0 : options.useCommonAddons) === false + ? addons + : [ + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js" + ) + ) + .then((n) => n.showHint), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./matchbrackets.cjs.js */ "../../graphiql-react/dist/matchbrackets.cjs.js" + ) + ) + .then((n) => n.matchbrackets), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./closebrackets.cjs.js */ "../../graphiql-react/dist/closebrackets.cjs.js" + ) + ) + .then((n) => n.closebrackets), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js" + ) + ) + .then((n) => n.braceFold), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js" + ) + ) + .then((n) => n.foldgutter), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./lint.cjs.js */ "../../graphiql-react/dist/lint.cjs.js" + ) + ) + .then((n) => n.lint), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js" + ) + ) + .then((n) => n.searchcursor), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js" + ) + ) + .then((n) => n.jumpToLine), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" + ) + ) + .then((n) => n.dialog), + // @ts-expect-error + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js" + ) + ) + .then((n) => n.sublime), + ...addons, + ] + ); + return CodeMirror; } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) { - node.style.marginLeft = -dims.gutterTotalWidth + "px"; + const printDefault = (ast) => { + if (!ast) { + return ""; } - } - } - function widgetHeight(widget) { - if (widget.height != null) { - return widget.height; - } - var cm = widget.doc.cm; - if (!cm) { - return 0; - } - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) { - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; + return graphql.print(ast); + }; + function DefaultValue({ field }) { + if (!("defaultValue" in field) || field.defaultValue === void 0) { + return null; } - if (widget.noHScroll) { - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + const ast = graphql.astFromValue(field.defaultValue, field.type); + if (!ast) { + return null; } - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + " = ", + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-default-value", + children: printDefault(ast), + }), + ], + }); } - return widget.height = widget.node.parentNode.offsetHeight; - } - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) { - return true; + const SchemaContext = createNullableContext("SchemaContext"); + function SchemaContextProvider(props) { + if (!props.fetcher) { + throw new TypeError( + "The `SchemaContextProvider` component requires a `fetcher` function to be passed as prop." + ); } - } - } - function paddingTop(display) { - return display.lineSpace.offsetTop; - } - function paddingVert(display) { - return display.mover.offsetHeight - display.lineSpace.offsetHeight; - } - function paddingH(display) { - if (display.cachedPaddingH) { - return display.cachedPaddingH; - } - var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = { - left: parseInt(style.paddingLeft), - right: parseInt(style.paddingRight) - }; - if (!isNaN(data.left) && !isNaN(data.right)) { - display.cachedPaddingH = data; - } - return data; - } - function scrollGap(cm) { - return scrollerGap - cm.display.nativeBarWidth; - } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; - } - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i2 = 0; i2 < rects.length - 1; i2++) { - var cur = rects[i2], - next = rects[i2 + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) { - heights.push((cur.bottom + next.top) / 2 - rect.top); - } + const { initialHeaders, headerEditor } = useEditorContext({ + nonNull: true, + caller: SchemaContextProvider, + }); + const [schema, setSchema] = React.useState(); + const [isFetching, setIsFetching] = React.useState(false); + const [fetchError, setFetchError] = React.useState(null); + const counterRef = React.useRef(0); + React.useEffect(() => { + setSchema( + graphql.isSchema(props.schema) || + props.schema === null || + props.schema === void 0 + ? props.schema + : void 0 + ); + counterRef.current++; + }, [props.schema]); + const headersRef = React.useRef(initialHeaders); + React.useEffect(() => { + if (headerEditor) { + headersRef.current = headerEditor.getValue(); } - } - heights.push(rect.bottom - rect.top); - } - } - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) { - return { - map: lineView.measure.map, - cache: lineView.measure.cache - }; - } - if (lineView.rest) { - for (var i2 = 0; i2 < lineView.rest.length; i2++) { - if (lineView.rest[i2] == line) { - return { - map: lineView.measure.maps[i2], - cache: lineView.measure.caches[i2] - }; + }); + const { + introspectionQuery, + introspectionQueryName, + introspectionQuerySansSubscriptions, + } = useIntrospectionQuery({ + inputValueDeprecation: props.inputValueDeprecation, + introspectionQueryName: props.introspectionQueryName, + schemaDescription: props.schemaDescription, + }); + const { + fetcher, + onSchemaChange, + dangerouslyAssumeSchemaIsValid, + children, + } = props; + const introspect = React.useCallback(() => { + if (graphql.isSchema(props.schema) || props.schema === null) { + return; } - } - for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) { - if (lineNo(lineView.rest[i$12]) > lineN) { - return { - map: lineView.measure.maps[i$12], - cache: lineView.measure.caches[i$12], - before: true - }; + const counter = ++counterRef.current; + const maybeIntrospectionData = props.schema; + async function fetchIntrospectionData() { + if (maybeIntrospectionData) { + return maybeIntrospectionData; + } + const parsedHeaders = parseHeaderString(headersRef.current); + if (!parsedHeaders.isValidJSON) { + setFetchError("Introspection failed as headers are invalid."); + return; + } + const fetcherOpts = parsedHeaders.headers + ? { + headers: parsedHeaders.headers, + } + : {}; + const fetch2 = toolkit.fetcherReturnToPromise( + fetcher( + { + query: introspectionQuery, + operationName: introspectionQueryName, + }, + fetcherOpts + ) + ); + if (!toolkit.isPromise(fetch2)) { + setFetchError( + "Fetcher did not return a Promise for introspection." + ); + return; + } + setIsFetching(true); + setFetchError(null); + let result = await fetch2; + if ( + typeof result !== "object" || + result === null || + !("data" in result) + ) { + const fetch22 = toolkit.fetcherReturnToPromise( + fetcher( + { + query: introspectionQuerySansSubscriptions, + operationName: introspectionQueryName, + }, + fetcherOpts + ) + ); + if (!toolkit.isPromise(fetch22)) { + throw new Error( + "Fetcher did not return a Promise for introspection." + ); + } + result = await fetch22; + } + setIsFetching(false); + if ( + (result == null ? void 0 : result.data) && + "__schema" in result.data + ) { + return result.data; + } + const responseString = + typeof result === "string" + ? result + : toolkit.formatResult(result); + setFetchError(responseString); } - } - } - } - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { - return cm.display.view[findViewIndex(cm, lineN)]; - } - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { - return ext; - } - } - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) { - view = null; - } else if (view && view.changes) { - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - cm.curOp.forceUpdate = true; - } - if (!view) { - view = updateExternalMeasurement(cm, line); - } - var info = mapFromLineView(view, line, lineN); - return { - line, - view, - rect: null, - map: info.map, - cache: info.cache, - before: info.before, - hasHeights: false - }; - } - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) { - ch = -1; - } - var key = ch + (bias || ""), - found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) { - prepared.rect = prepared.view.text.getBoundingClientRect(); - } - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) { - prepared.cache[key] = found; - } - } - return { - left: found.left, - right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom - }; - } - var nullRect = { - left: 0, - right: 0, - top: 0, - bottom: 0 - }; - function nodeAndOffsetInLineMap(map2, ch, bias) { - var node, start, end, collapse, mStart, mEnd; - for (var i2 = 0; i2 < map2.length; i2 += 3) { - mStart = map2[i2]; - mEnd = map2[i2 + 1]; - if (ch < mStart) { - start = 0; - end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i2 == map2.length - 3 || ch == mEnd && map2[i2 + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) { - collapse = "right"; - } - } - if (start != null) { - node = map2[i2 + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { - collapse = bias; - } - if (bias == "left" && start == 0) { - while (i2 && map2[i2 - 2] == map2[i2 - 3] && map2[i2 - 1].insertLeft) { - node = map2[(i2 -= 3) + 2]; - collapse = "left"; - } - } - if (bias == "right" && start == mEnd - mStart) { - while (i2 < map2.length - 3 && map2[i2 + 3] == map2[i2 + 4] && !map2[i2 + 5].insertLeft) { - node = map2[(i2 += 3) + 2]; - collapse = "right"; + fetchIntrospectionData() + .then((introspectionData) => { + if (counter !== counterRef.current || !introspectionData) { + return; + } + try { + const newSchema = + graphql.buildClientSchema(introspectionData); + setSchema(newSchema); + onSchemaChange == null ? void 0 : onSchemaChange(newSchema); + } catch (error) { + setFetchError(toolkit.formatError(error)); + } + }) + .catch((error) => { + if (counter !== counterRef.current) { + return; + } + setFetchError(toolkit.formatError(error)); + setIsFetching(false); + }); + }, [ + fetcher, + introspectionQueryName, + introspectionQuery, + introspectionQuerySansSubscriptions, + onSchemaChange, + props.schema, + ]); + React.useEffect(() => { + introspect(); + }, [introspect]); + React.useEffect(() => { + function triggerIntrospection(event) { + if (event.ctrlKey && event.key === "R") { + introspect(); } } - break; - } + window.addEventListener("keydown", triggerIntrospection); + return () => + window.removeEventListener("keydown", triggerIntrospection); + }); + const validationErrors = React.useMemo(() => { + if (!schema || dangerouslyAssumeSchemaIsValid) { + return []; + } + return graphql.validateSchema(schema); + }, [schema, dangerouslyAssumeSchemaIsValid]); + const value = React.useMemo( + () => ({ + fetchError, + introspect, + isFetching, + schema, + validationErrors, + }), + [fetchError, introspect, isFetching, schema, validationErrors] + ); + return /* @__PURE__ */ jsxRuntime.jsx(SchemaContext.Provider, { + value, + children, + }); } - return { - node, - start, - end, - collapse, - coverStart: mStart, - coverEnd: mEnd - }; - } - function getUsefulRect(rects, bias) { - var rect = nullRect; - if (bias == "left") { - for (var i2 = 0; i2 < rects.length; i2++) { - if ((rect = rects[i2]).left != rect.right) { - break; + const useSchemaContext = createContextHook(SchemaContext); + function useIntrospectionQuery({ + inputValueDeprecation, + introspectionQueryName, + schemaDescription, + }) { + return React.useMemo(() => { + const queryName = introspectionQueryName || "IntrospectionQuery"; + let query = graphql.getIntrospectionQuery({ + inputValueDeprecation, + schemaDescription, + }); + if (introspectionQueryName) { + query = query.replace( + "query IntrospectionQuery", + `query ${queryName}` + ); } - } - } else { - for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) { - if ((rect = rects[i$12]).left != rect.right) { - break; + const querySansSubscriptions = query.replace( + "subscriptionType { name }", + "" + ); + return { + introspectionQueryName: queryName, + introspectionQuery: query, + introspectionQuerySansSubscriptions: querySansSubscriptions, + }; + }, [ + inputValueDeprecation, + introspectionQueryName, + schemaDescription, + ]); + } + function parseHeaderString(headersString) { + let headers = null; + let isValidJSON = true; + try { + if (headersString) { + headers = JSON.parse(headersString); } + } catch { + isValidJSON = false; } + return { + headers, + isValidJSON, + }; } - return rect; - } - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, - start = place.start, - end = place.end, - collapse = place.collapse; - var rect; - if (node.nodeType == 3) { - for (var i$12 = 0; i$12 < 4; i$12++) { - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { - --start; - } - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { - ++end; - } - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { - rect = node.parentNode.getBoundingClientRect(); + const initialNavStackItem = { + name: "Docs", + }; + const ExplorerContext = createNullableContext("ExplorerContext"); + function ExplorerContextProvider(props) { + const { schema, validationErrors } = useSchemaContext({ + nonNull: true, + caller: ExplorerContextProvider, + }); + const [navStack, setNavStack] = React.useState([initialNavStackItem]); + const push = React.useCallback((item) => { + setNavStack((currentState) => { + const lastItem = currentState.at(-1); + return lastItem.def === item.def + ? // Avoid pushing duplicate items + currentState + : [...currentState, item]; + }); + }, []); + const pop = React.useCallback(() => { + setNavStack((currentState) => + currentState.length > 1 ? currentState.slice(0, -1) : currentState + ); + }, []); + const reset = React.useCallback(() => { + setNavStack((currentState) => + currentState.length === 1 ? currentState : [initialNavStackItem] + ); + }, []); + React.useEffect(() => { + if (schema == null || validationErrors.length > 0) { + reset(); } else { - rect = getUsefulRect(range(node, start, end).getClientRects(), bias); - } - if (rect.left || rect.right || start == 0) { - break; + setNavStack((oldNavStack) => { + if (oldNavStack.length === 1) { + return oldNavStack; + } + const newNavStack = [initialNavStackItem]; + let lastEntity = null; + for (const item of oldNavStack) { + if (item === initialNavStackItem) { + continue; + } + if (item.def) { + if (graphql.isNamedType(item.def)) { + const newType = schema.getType(item.def.name); + if (newType) { + newNavStack.push({ + name: item.name, + def: newType, + }); + lastEntity = newType; + } else { + break; + } + } else if (lastEntity === null) { + break; + } else if ( + graphql.isObjectType(lastEntity) || + graphql.isInputObjectType(lastEntity) + ) { + const field = lastEntity.getFields()[item.name]; + if (field) { + newNavStack.push({ + name: item.name, + def: field, + }); + } else { + break; + } + } else if ( + graphql.isScalarType(lastEntity) || + graphql.isEnumType(lastEntity) || + graphql.isInterfaceType(lastEntity) || + graphql.isUnionType(lastEntity) + ) { + break; + } else { + const field = lastEntity; + const arg = field.args.find((a) => a.name === item.name); + if (arg) { + newNavStack.push({ + name: item.name, + def: field, + }); + } else { + break; + } + } + } else { + lastEntity = null; + newNavStack.push(item); + } + } + return newNavStack; + }); } - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) { - rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } - } else { - if (start > 0) { - collapse = bias = "right"; - } - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { - rect = rects[bias == "right" ? rects.length - 1 : 0]; - } else { - rect = node.getBoundingClientRect(); - } - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) { - rect = { - left: rSpan.left, - right: rSpan.left + charWidth(cm.display), - top: rSpan.top, - bottom: rSpan.bottom - }; - } else { - rect = nullRect; - } + }, [reset, schema, validationErrors]); + const value = React.useMemo( + () => ({ + explorerNavStack: navStack, + push, + pop, + reset, + }), + [navStack, push, pop, reset] + ); + return /* @__PURE__ */ jsxRuntime.jsx(ExplorerContext.Provider, { + value, + children: props.children, + }); } - var rtop = rect.top - prepared.rect.top, - rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - var i2 = 0; - for (; i2 < heights.length - 1; i2++) { - if (mid < heights[i2]) { - break; + const useExplorerContext = createContextHook(ExplorerContext); + function renderType(type, renderNamedType) { + if (graphql.isNonNullType(type)) { + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [renderType(type.ofType, renderNamedType), "!"], + }); } - } - var top = i2 ? heights[i2 - 1] : 0, - bot = heights[i2]; - var result = { - left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top, - bottom: bot - }; - if (!rect.left && !rect.right) { - result.bogus = true; - } - if (!cm.options.singleCursorHeightPerLine) { - result.rtop = rtop; - result.rbottom = rbot; - } - return result; - } - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { - return rect; - } - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return { - left: rect.left * scaleX, - right: rect.right * scaleX, - top: rect.top * scaleY, - bottom: rect.bottom * scaleY - }; - } - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) { - for (var i2 = 0; i2 < lineView.rest.length; i2++) { - lineView.measure.caches[i2] = {}; - } + if (graphql.isListType(type)) { + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["[", renderType(type.ofType, renderNamedType), "]"], + }); } + return renderNamedType(type); } - } - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i2 = 0; i2 < cm.display.view.length; i2++) { - clearLineMeasurementCacheFor(cm.display.view[i2]); - } - } - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) { - cm.display.maxLineChanged = true; - } - cm.display.lineNumChars = null; - } - function pageScrollX() { - if (chrome && android) { - return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)); - } - return window.pageXOffset || (document.documentElement || document.body).scrollLeft; - } - function pageScrollY() { - if (chrome && android) { - return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)); - } - return window.pageYOffset || (document.documentElement || document.body).scrollTop; - } - function widgetTopHeight(lineObj) { - var ref = visualLine(lineObj); - var widgets = ref.widgets; - var height = 0; - if (widgets) { - for (var i2 = 0; i2 < widgets.length; ++i2) { - if (widgets[i2].above) { - height += widgetHeight(widgets[i2]); - } + function TypeLink(props) { + const { push } = useExplorerContext({ + nonNull: true, + caller: TypeLink, + }); + if (!props.type) { + return null; } + return renderType(props.type, (namedType) => + /* @__PURE__ */ jsxRuntime.jsx("a", { + className: "graphiql-doc-explorer-type-name", + onClick: (event) => { + event.preventDefault(); + push({ + name: namedType.name, + def: namedType, + }); + }, + href: "#", + children: namedType.name, + }) + ); } - return height; - } - function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { - if (!includeWidgets) { - var height = widgetTopHeight(lineObj); - rect.top += height; - rect.bottom += height; - } - if (context == "line") { - return rect; + function Argument({ arg, showDefaultValue, inline }) { + const definition = /* @__PURE__ */ jsxRuntime.jsxs("span", { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-argument-name", + children: arg.name, + }), + ": ", + /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: arg.type, + }), + showDefaultValue !== false && + /* @__PURE__ */ jsxRuntime.jsx(DefaultValue, { + field: arg, + }), + ], + }); + if (inline) { + return definition; + } + return /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-argument", + children: [ + definition, + arg.description + ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: arg.description, + }) + : null, + arg.deprecationReason + ? /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-argument-deprecation", + children: [ + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: + "graphiql-doc-explorer-argument-deprecation-label", + children: "Deprecated", + }), + /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + children: arg.deprecationReason, + }), + ], + }) + : null, + ], + }); } - if (!context) { - context = "local"; + function DeprecationReason(props) { + var _props$preview; + return props.children + ? /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-deprecation", + children: [ + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-deprecation-label", + children: "Deprecated", + }), + /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + onlyShowFirstChild: + (_props$preview = props.preview) !== null && + _props$preview !== void 0 + ? _props$preview + : true, + children: props.children, + }), + ], + }) + : null; } - var yOff = heightAtLine(lineObj); - if (context == "local") { - yOff += paddingTop(cm.display); - } else { - yOff -= cm.display.viewOffset; - } - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; - rect.right += xOff; - } - rect.top += yOff; - rect.bottom += yOff; - return rect; - } - function fromCoordSystem(cm, coords, context) { - if (context == "div") { - return coords; + function Directive({ directive }) { + return /* @__PURE__ */ jsxRuntime.jsxs("span", { + className: "graphiql-doc-explorer-directive", + children: ["@", directive.name.value], + }); } - var left = coords.left, - top = coords.top; - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return { - left: left - lineSpaceBox.left, - top: top - lineSpaceBox.top - }; - } - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) { - lineObj = getLine(cm.doc, pos.line); + function ExplorerSection(props) { + const Icon2 = TYPE_TO_ICON[props.title]; + return /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-section-title", + children: [ + /* @__PURE__ */ jsxRuntime.jsx(Icon2, {}), + props.title, + ], + }), + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-section-content", + children: props.children, + }), + ], + }); } - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) { - preparedMeasure = prepareMeasureForLine(cm, lineObj); - } - function get(ch2, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch2, right ? "right" : "left", varHeight); - if (right) { - m.left = m.right; - } else { - m.right = m.left; - } - return intoCoordSystem(cm, lineObj, m, context); - } - var order = getOrder(lineObj, cm.doc.direction), - ch = pos.ch, - sticky = pos.sticky; - if (ch >= lineObj.text.length) { - ch = lineObj.text.length; - sticky = "before"; - } else if (ch <= 0) { - ch = 0; - sticky = "after"; - } - if (!order) { - return get(sticky == "before" ? ch - 1 : ch, sticky == "before"); - } - function getBidi(ch2, partPos2, invert) { - var part = order[partPos2], - right = part.level == 1; - return get(invert ? ch2 - 1 : ch2, right != invert); - } - var partPos = getBidiPartAt(order, ch, sticky); - var other = bidiOther; - var val = getBidi(ch, partPos, sticky == "before"); - if (other != null) { - val.other = getBidi(ch, other, sticky != "before"); - } - return val; - } - function estimateCoords(cm, pos) { - var left = 0; - pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) { - left = charWidth(cm.display) * pos.ch; - } - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return { - left, - right: left, - top, - bottom: top + lineObj.height + const TYPE_TO_ICON = { + Arguments: ArgumentIcon, + "Deprecated Arguments": DeprecatedArgumentIcon, + "Deprecated Enum Values": DeprecatedEnumValueIcon, + "Deprecated Fields": DeprecatedFieldIcon, + Directives: DirectiveIcon, + "Enum Values": EnumValueIcon, + Fields: FieldIcon, + Implements: ImplementsIcon, + Implementations: TypeIcon, + "Possible Types": TypeIcon, + "Root Types": RootTypeIcon, + Type: TypeIcon, + "All Schema Types": TypeIcon, }; - } - function PosWithInfo(line, ch, sticky, outside, xRel) { - var pos = Pos(line, ch, sticky); - pos.xRel = xRel; - if (outside) { - pos.outside = outside; - } - return pos; - } - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) { - return PosWithInfo(doc.first, 0, null, -1, -1); - } - var lineN = lineAtHeight(doc, y), - last = doc.first + doc.size - 1; - if (lineN > last) { - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1); - } - if (x < 0) { - x = 0; + function FieldDocumentation(props) { + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + props.field.description + ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.field.description, + }) + : null, + /* @__PURE__ */ jsxRuntime.jsx(DeprecationReason, { + preview: false, + children: props.field.deprecationReason, + }), + /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Type", + children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: props.field.type, + }), + }), + /* @__PURE__ */ jsxRuntime.jsx(Arguments, { + field: props.field, + }), + /* @__PURE__ */ jsxRuntime.jsx(Directives, { + field: props.field, + }), + ], + }); } - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); - if (!collapsed) { - return found; + function Arguments({ field }) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!("args" in field)) { + return null; } - var rangeEnd = collapsed.find(1); - if (rangeEnd.line == lineN) { - return rangeEnd; + const args = []; + const deprecatedArgs = []; + for (const argument of field.args) { + if (argument.deprecationReason) { + deprecatedArgs.push(argument); + } else { + args.push(argument); + } } - lineObj = getLine(doc, lineN = rangeEnd.line); - } - } - function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { - y -= widgetTopHeight(lineObj); - var end = lineObj.text.length; - var begin = findFirst(function (ch) { - return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; - }, end, 0); - end = findFirst(function (ch) { - return measureCharPrepared(cm, preparedMeasure, ch).top > y; - }, begin, end); - return { - begin, - end - }; - } - function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { - if (!preparedMeasure) { - preparedMeasure = prepareMeasureForLine(cm, lineObj); + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + args.length > 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Arguments", + children: args.map((arg) => + /* @__PURE__ */ jsxRuntime.jsx( + Argument, + { + arg, + }, + arg.name + ) + ), + }) + : null, + deprecatedArgs.length > 0 + ? showDeprecated || args.length === 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Arguments", + children: deprecatedArgs.map((arg) => + /* @__PURE__ */ jsxRuntime.jsx( + Argument, + { + arg, + }, + arg.name + ) + ), + }) + : /* @__PURE__ */ jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Arguments", + }) + : null, + ], + }); } - var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; - return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop); - } - function boxIsAfter(box, x, y, left) { - return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x; - } - function coordsCharInner(cm, lineObj, lineNo2, x, y) { - y -= heightAtLine(lineObj); - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - var widgetHeight2 = widgetTopHeight(lineObj); - var begin = 0, - end = lineObj.text.length, - ltr = true; - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x, y); - ltr = part.level != 1; - begin = ltr ? part.from : part.to - 1; - end = ltr ? part.to : part.from - 1; - } - var chAround = null, - boxAround = null; - var ch = findFirst(function (ch2) { - var box = measureCharPrepared(cm, preparedMeasure, ch2); - box.top += widgetHeight2; - box.bottom += widgetHeight2; - if (!boxIsAfter(box, x, y, false)) { - return false; - } - if (box.top <= y && box.left <= x) { - chAround = ch2; - boxAround = box; - } - return true; - }, begin, end); - var baseX, - sticky, - outside = false; - if (boxAround) { - var atLeft = x - boxAround.left < boxAround.right - x, - atStart = atLeft == ltr; - ch = chAround + (atStart ? 0 : 1); - sticky = atStart ? "after" : "before"; - baseX = atLeft ? boxAround.left : boxAround.right; - } else { - if (!ltr && (ch == end || ch == begin)) { - ch++; + function Directives({ field }) { + var _a; + const directives = + ((_a = field.astNode) == null ? void 0 : _a.directives) || []; + if (!directives || directives.length === 0) { + return null; } - sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y == ltr ? "after" : "before"; - var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure); - baseX = coords.left; - outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + return /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Directives", + children: directives.map((directive) => + /* @__PURE__ */ jsxRuntime.jsx( + "div", + { + children: /* @__PURE__ */ jsxRuntime.jsx(Directive, { + directive, + }), + }, + directive.name.value + ) + ), + }); } - ch = skipExtendingChars(lineObj.text, ch, 1); - return PosWithInfo(lineNo2, ch, sticky, outside, x - baseX); - } - function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x, y) { - var index = findFirst(function (i2) { - var part2 = order[i2], - ltr2 = part2.level != 1; - return boxIsAfter(cursorCoords(cm, Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true); - }, 0, order.length - 1); - var part = order[index]; - if (index > 0) { - var ltr = part.level != 1; - var start = cursorCoords(cm, Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); - if (boxIsAfter(start, x, y, true) && start.top > y) { - part = order[index - 1]; - } - } - return part; - } - function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { - var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); - var begin = ref.begin; - var end = ref.end; - if (/\s/.test(lineObj.text.charAt(end - 1))) { - end--; - } - var part = null, - closestDist = null; - for (var i2 = 0; i2 < order.length; i2++) { - var p = order[i2]; - if (p.from >= end || p.to <= begin) { - continue; - } - var ltr = p.level != 1; - var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; - var dist = endX < x ? x - endX + 1e9 : endX - x; - if (!part || closestDist > dist) { - part = p; - closestDist = dist; - } - } - if (!part) { - part = order[order.length - 1]; - } - if (part.from < begin) { - part = { - from: begin, - to: part.to, - level: part.level - }; + function SchemaDocumentation(props) { + var _a, _b, _c, _d; + const queryType = props.schema.getQueryType(); + const mutationType = + (_b = (_a = props.schema).getMutationType) == null + ? void 0 + : _b.call(_a); + const subscriptionType = + (_d = (_c = props.schema).getSubscriptionType) == null + ? void 0 + : _d.call(_c); + const typeMap = props.schema.getTypeMap(); + const ignoreTypesInAllSchema = [ + queryType == null ? void 0 : queryType.name, + mutationType == null ? void 0 : mutationType.name, + subscriptionType == null ? void 0 : subscriptionType.name, + ]; + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: + props.schema.description || + "A GraphQL schema provides a root type for each kind of operation.", + }), + /* @__PURE__ */ jsxRuntime.jsxs(ExplorerSection, { + title: "Root Types", + children: [ + queryType + ? /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "query", + }), + ": ", + /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: queryType, + }), + ], + }) + : null, + mutationType && + /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "mutation", + }), + ": ", + /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: mutationType, + }), + ], + }), + subscriptionType && + /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "subscription", + }), + ": ", + /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: subscriptionType, + }), + ], + }), + ], + }), + /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "All Schema Types", + children: + typeMap && + /* @__PURE__ */ jsxRuntime.jsx("div", { + children: Object.values(typeMap).map((type) => { + if ( + ignoreTypesInAllSchema.includes(type.name) || + type.name.startsWith("__") + ) { + return null; + } + return /* @__PURE__ */ jsxRuntime.jsx( + "div", + { + children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type, + }), + }, + type.name + ); + }), + }), + }), + ], + }); } - if (part.to > end) { - part = { - from: part.from, - to: end, - level: part.level + function debounce(duration, fn) { + let timeout; + return function (...args) { + if (timeout) { + window.clearTimeout(timeout); + } + timeout = window.setTimeout(() => { + timeout = null; + fn(...args); + }, duration); }; } - return part; - } - var measureText; - function textHeight(display) { - if (display.cachedTextHeight != null) { - return display.cachedTextHeight; - } - if (measureText == null) { - measureText = elt("pre", null, "CodeMirror-line-like"); - for (var i2 = 0; i2 < 49; ++i2) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) { - display.cachedTextHeight = height; - } - removeChildren(display.measure); - return height || 1; - } - function charWidth(display) { - if (display.cachedCharWidth != null) { - return display.cachedCharWidth; - } - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor], "CodeMirror-line-like"); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), - width = (rect.right - rect.left) / 10; - if (width > 2) { - display.cachedCharWidth = width; - } - return width || 10; - } - function getDimensions(cm) { - var d = cm.display, - left = {}, - width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) { - var id = cm.display.gutterSpecs[i2].className; - left[id] = n.offsetLeft + n.clientLeft + gutterLeft; - width[id] = n.clientWidth; - } - return { - fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth - }; - } - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - function estimateHeight(cm) { - var th = textHeight(cm.display), - wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function (line) { - if (lineIsHidden(cm.doc, line)) { - return 0; - } - var widgetsHeight = 0; - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; i2++) { - if (line.widgets[i2].height) { - widgetsHeight += line.widgets[i2].height; + function Search() { + const { explorerNavStack, push } = useExplorerContext({ + nonNull: true, + caller: Search, + }); + const inputRef = React.useRef(null); + const getSearchResults = useSearchResults(); + const [searchValue, setSearchValue] = React.useState(""); + const [results, setResults] = React.useState( + getSearchResults(searchValue) + ); + const debouncedGetSearchResults = React.useMemo( + () => + debounce(200, (search) => { + setResults(getSearchResults(search)); + }), + [getSearchResults] + ); + React.useEffect(() => { + debouncedGetSearchResults(searchValue); + }, [debouncedGetSearchResults, searchValue]); + React.useEffect(() => { + function handleKeyDown(event) { + var _a; + if (event.metaKey && event.key === "k") { + (_a = inputRef.current) == null ? void 0 : _a.focus(); } } + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, []); + const navItem = explorerNavStack.at(-1); + const onSelect = React.useCallback( + (def) => { + push( + "field" in def + ? { + name: def.field.name, + def: def.field, + } + : { + name: def.type.name, + def: def.type, + } + ); + }, + [push] + ); + const isFocused = React.useRef(false); + const handleFocus = React.useCallback((e) => { + isFocused.current = e.type === "focus"; + }, []); + const shouldSearchBoxAppear = + explorerNavStack.length === 1 || + graphql.isObjectType(navItem.def) || + graphql.isInterfaceType(navItem.def) || + graphql.isInputObjectType(navItem.def); + if (!shouldSearchBoxAppear) { + return null; } - if (wrapping) { - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; - } else { - return widgetsHeight + th; - } - }; - } - function estimateLineHeights(cm) { - var doc = cm.doc, - est = estimateHeight(cm); - doc.iter(function (line) { - var estHeight = est(line); - if (estHeight != line.height) { - updateLineHeight(line, estHeight); - } - }); - } - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { - return null; - } - var x, - y, - space = display.lineSpace.getBoundingClientRect(); - try { - x = e.clientX - space.left; - y = e.clientY - space.top; - } catch (e$1) { - return null; - } - var coords = coordsChar(cm, x, y), - line; - if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) { - return null; + return /* @__PURE__ */ jsxRuntime.jsxs(react.Combobox, { + as: "div", + className: "graphiql-doc-explorer-search", + onChange: onSelect, + "data-state": isFocused ? void 0 : "idle", + "aria-label": `Search ${navItem.name}...`, + children: [ + /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-search-input", + onClick: () => { + var _a; + (_a = inputRef.current) == null ? void 0 : _a.focus(); + }, + children: [ + /* @__PURE__ */ jsxRuntime.jsx(MagnifyingGlassIcon, {}), + /* @__PURE__ */ jsxRuntime.jsx(react.Combobox.Input, { + autoComplete: "off", + onFocus: handleFocus, + onBlur: handleFocus, + onChange: (event) => setSearchValue(event.target.value), + placeholder: "⌘ K", + ref: inputRef, + value: searchValue, + "data-cy": "doc-explorer-input", + }), + ], + }), + isFocused.current && + /* @__PURE__ */ jsxRuntime.jsxs(react.Combobox.Options, { + "data-cy": "doc-explorer-list", + children: [ + results.within.length + + results.types.length + + results.fields.length === + 0 + ? /* @__PURE__ */ jsxRuntime.jsx("li", { + className: "graphiql-doc-explorer-search-empty", + children: "No results found", + }) + : results.within.map((result, i) => + /* @__PURE__ */ jsxRuntime.jsx( + react.Combobox.Option, + { + value: result, + "data-cy": "doc-explorer-option", + children: /* @__PURE__ */ jsxRuntime.jsx( + Field$1, + { + field: result.field, + argument: result.argument, + } + ), + }, + `within-${i}` + ) + ), + results.within.length > 0 && + results.types.length + results.fields.length > 0 + ? /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-search-divider", + children: "Other results", + }) + : null, + results.types.map((result, i) => + /* @__PURE__ */ jsxRuntime.jsx( + react.Combobox.Option, + { + value: result, + "data-cy": "doc-explorer-option", + children: /* @__PURE__ */ jsxRuntime.jsx(Type, { + type: result.type, + }), + }, + `type-${i}` + ) + ), + results.fields.map((result, i) => + /* @__PURE__ */ jsxRuntime.jsxs( + react.Combobox.Option, + { + value: result, + "data-cy": "doc-explorer-option", + children: [ + /* @__PURE__ */ jsxRuntime.jsx(Type, { + type: result.type, + }), + ".", + /* @__PURE__ */ jsxRuntime.jsx(Field$1, { + field: result.field, + argument: result.argument, + }), + ], + }, + `field-${i}` + ) + ), + ], + }), + ], + }); } - n -= cm.display.viewFrom; - if (n < 0) { - return null; + function useSearchResults(caller) { + const { explorerNavStack } = useExplorerContext({ + nonNull: true, + caller: caller || useSearchResults, + }); + const { schema } = useSchemaContext({ + nonNull: true, + caller: caller || useSearchResults, + }); + const navItem = explorerNavStack.at(-1); + return React.useCallback( + (searchValue) => { + const matches = { + within: [], + types: [], + fields: [], + }; + if (!schema) { + return matches; + } + const withinType = navItem.def; + const typeMap = schema.getTypeMap(); + let typeNames = Object.keys(typeMap); + if (withinType) { + typeNames = typeNames.filter((n) => n !== withinType.name); + typeNames.unshift(withinType.name); + } + for (const typeName of typeNames) { + if ( + matches.within.length + + matches.types.length + + matches.fields.length >= + 100 + ) { + break; + } + const type = typeMap[typeName]; + if (withinType !== type && isMatch(typeName, searchValue)) { + matches.types.push({ + type, + }); + } + if ( + !graphql.isObjectType(type) && + !graphql.isInterfaceType(type) && + !graphql.isInputObjectType(type) + ) { + continue; + } + const fields = type.getFields(); + for (const fieldName in fields) { + const field = fields[fieldName]; + let matchingArgs; + if (!isMatch(fieldName, searchValue)) { + if ("args" in field) { + matchingArgs = field.args.filter((arg) => + isMatch(arg.name, searchValue) + ); + if (matchingArgs.length === 0) { + continue; + } + } else { + continue; + } + } + matches[withinType === type ? "within" : "fields"].push( + ...(matchingArgs + ? matchingArgs.map((argument) => ({ + type, + field, + argument, + })) + : [ + { + type, + field, + }, + ]) + ); + } + } + return matches; + }, + [navItem.def, schema] + ); } - var view = cm.display.view; - for (var i2 = 0; i2 < view.length; i2++) { - n -= view[i2].size; - if (n < 0) { - return i2; + function isMatch(sourceText, searchValue) { + try { + const escaped = searchValue.replaceAll( + /[^_0-9A-Za-z]/g, + (ch) => "\\" + ch + ); + return sourceText.search(new RegExp(escaped, "i")) !== -1; + } catch { + return sourceText.toLowerCase().includes(searchValue.toLowerCase()); } } - } - function regChange(cm, from, to, lendiff) { - if (from == null) { - from = cm.doc.first; + function Type(props) { + return /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-type", + children: props.type.name, + }); } - if (to == null) { - to = cm.doc.first + cm.doc.size; + function Field$1({ field, argument }) { + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-field", + children: field.name, + }), + argument + ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + "(", + /* @__PURE__ */ jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-argument", + children: argument.name, + }), + ":", + " ", + renderType(argument.type, (namedType) => + /* @__PURE__ */ jsxRuntime.jsx(Type, { + type: namedType, + }) + ), + ")", + ], + }) + : null, + ], + }); } - if (!lendiff) { - lendiff = 0; + function FieldLink(props) { + const { push } = useExplorerContext({ + nonNull: true, + }); + return /* @__PURE__ */ jsxRuntime.jsx("a", { + className: "graphiql-doc-explorer-field-name", + onClick: (event) => { + event.preventDefault(); + push({ + name: props.field.name, + def: props.field, + }); + }, + href: "#", + children: props.field.name, + }); } - var display = cm.display; - if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { - display.updateLineNumbers = from; + function TypeDocumentation(props) { + return graphql.isNamedType(props.type) + ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + props.type.description + ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.type.description, + }) + : null, + /* @__PURE__ */ jsxRuntime.jsx(ImplementsInterfaces, { + type: props.type, + }), + /* @__PURE__ */ jsxRuntime.jsx(Fields, { + type: props.type, + }), + /* @__PURE__ */ jsxRuntime.jsx(EnumValues, { + type: props.type, + }), + /* @__PURE__ */ jsxRuntime.jsx(PossibleTypes, { + type: props.type, + }), + ], + }) + : null; } - cm.curOp.viewChanged = true; - if (from >= display.viewTo) { - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { - resetView(cm); - } - } else if (to <= display.viewFrom) { - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { - resetView(cm); - } else if (from <= display.viewFrom) { - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { - var cut$1 = viewCuttingPoint(cm, from, from, -1); - if (cut$1) { - display.view = display.view.slice(0, cut$1.index); - display.viewTo = cut$1.lineN; - } else { - resetView(cm); + function ImplementsInterfaces({ type }) { + if (!graphql.isObjectType(type)) { + return null; } - } else { - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); + const interfaces = type.getInterfaces(); + return interfaces.length > 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Implements", + children: type.getInterfaces().map((implementedInterface) => + /* @__PURE__ */ jsxRuntime.jsx( + "div", + { + children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: implementedInterface, + }), + }, + implementedInterface.name + ) + ), + }) + : null; + } + function Fields({ type }) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if ( + !graphql.isObjectType(type) && + !graphql.isInterfaceType(type) && + !graphql.isInputObjectType(type) + ) { + return null; } - } - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) { - ext.lineN += lendiff; - } else if (from < ext.lineN + ext.size) { - display.externalMeasured = null; + const fieldMap = type.getFields(); + const fields = []; + const deprecatedFields = []; + for (const field of Object.keys(fieldMap).map( + (name) => fieldMap[name] + )) { + if (field.deprecationReason) { + deprecatedFields.push(field); + } else { + fields.push(field); + } } + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + fields.length > 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Fields", + children: fields.map((field) => + /* @__PURE__ */ jsxRuntime.jsx( + Field, + { + field, + }, + field.name + ) + ), + }) + : null, + deprecatedFields.length > 0 + ? showDeprecated || fields.length === 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Fields", + children: deprecatedFields.map((field) => + /* @__PURE__ */ jsxRuntime.jsx( + Field, + { + field, + }, + field.name + ) + ), + }) + : /* @__PURE__ */ jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Fields", + }) + : null, + ], + }); } - } - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, - ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { - display.externalMeasured = null; - } - if (line < display.viewFrom || line >= display.viewTo) { - return; - } - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) { - return; - } - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) { - arr.push(type); - } - } - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), - diff, - view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { - return { - index, - lineN: newN - }; - } - var n = cm.display.viewFrom; - for (var i2 = 0; i2 < index; i2++) { - n += view[i2].size; + function Field({ field }) { + const args = + "args" in field + ? field.args.filter((arg) => !arg.deprecationReason) + : []; + return /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-item", + children: [ + /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + /* @__PURE__ */ jsxRuntime.jsx(FieldLink, { + field, + }), + args.length > 0 + ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + "(", + /* @__PURE__ */ jsxRuntime.jsx("span", { + children: args.map((arg) => + args.length === 1 + ? /* @__PURE__ */ jsxRuntime.jsx( + Argument, + { + arg, + inline: true, + }, + arg.name + ) + : /* @__PURE__ */ jsxRuntime.jsx( + "div", + { + className: + "graphiql-doc-explorer-argument-multiple", + children: /* @__PURE__ */ jsxRuntime.jsx( + Argument, + { + arg, + inline: true, + } + ), + }, + arg.name + ) + ), + }), + ")", + ], + }) + : null, + ": ", + /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: field.type, + }), + /* @__PURE__ */ jsxRuntime.jsx(DefaultValue, { + field, + }), + ], + }), + field.description + ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "description", + onlyShowFirstChild: true, + children: field.description, + }) + : null, + /* @__PURE__ */ jsxRuntime.jsx(DeprecationReason, { + children: field.deprecationReason, + }), + ], + }); } - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) { - return null; + function EnumValues({ type }) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!graphql.isEnumType(type)) { + return null; + } + const values = []; + const deprecatedValues = []; + for (const value of type.getValues()) { + if (value.deprecationReason) { + deprecatedValues.push(value); + } else { + values.push(value); } - diff = n + view[index].size - oldN; - index++; - } else { - diff = n - oldN; } - oldN += diff; - newN += diff; + return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [ + values.length > 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Enum Values", + children: values.map((value) => + /* @__PURE__ */ jsxRuntime.jsx( + EnumValue, + { + value, + }, + value.name + ) + ), + }) + : null, + deprecatedValues.length > 0 + ? showDeprecated || values.length === 0 + ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Enum Values", + children: deprecatedValues.map((value) => + /* @__PURE__ */ jsxRuntime.jsx( + EnumValue, + { + value, + }, + value.name + ) + ), + }) + : /* @__PURE__ */ jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Values", + }) + : null, + ], + }); } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) { - return null; - } - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; + function EnumValue({ value }) { + return /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-item", + children: [ + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-enum-value", + children: value.name, + }), + value.description + ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: value.description, + }) + : null, + value.deprecationReason + ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + children: value.deprecationReason, + }) + : null, + ], + }); } - return { - index, - lineN: newN - }; - } - function adjustView(cm, from, to) { - var display = cm.display, - view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) { - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - } else if (display.viewFrom < from) { - display.view = display.view.slice(findViewIndex(cm, from)); - } - display.viewFrom = from; - if (display.viewTo < to) { - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - } else if (display.viewTo > to) { - display.view = display.view.slice(0, findViewIndex(cm, to)); + function PossibleTypes({ type }) { + const { schema } = useSchemaContext({ + nonNull: true, + }); + if (!schema || !graphql.isAbstractType(type)) { + return null; } + return /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { + title: graphql.isInterfaceType(type) + ? "Implementations" + : "Possible Types", + children: schema.getPossibleTypes(type).map((possibleType) => + /* @__PURE__ */ jsxRuntime.jsx( + "div", + { + children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { + type: possibleType, + }), + }, + possibleType.name + ) + ), + }); } - display.viewTo = to; - } - function countDirtyView(cm) { - var view = cm.display.view, - dirty = 0; - for (var i2 = 0; i2 < view.length; i2++) { - var lineView = view[i2]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) { - ++dirty; + function DocExplorer() { + const { fetchError, isFetching, schema, validationErrors } = + useSchemaContext({ + nonNull: true, + caller: DocExplorer, + }); + const { explorerNavStack, pop } = useExplorerContext({ + nonNull: true, + caller: DocExplorer, + }); + const navItem = explorerNavStack.at(-1); + let content = null; + if (fetchError) { + content = /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-error", + children: "Error fetching schema", + }); + } else if (validationErrors.length > 0) { + content = /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-error", + children: ["Schema is invalid: ", validationErrors[0].message], + }); + } else if (isFetching) { + content = /* @__PURE__ */ jsxRuntime.jsx(Spinner, {}); + } else if (!schema) { + content = /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-error", + children: "No GraphQL schema available", + }); + } else if (explorerNavStack.length === 1) { + content = /* @__PURE__ */ jsxRuntime.jsx(SchemaDocumentation, { + schema, + }); + } else if (graphql.isType(navItem.def)) { + content = /* @__PURE__ */ jsxRuntime.jsx(TypeDocumentation, { + type: navItem.def, + }); + } else if (navItem.def) { + content = /* @__PURE__ */ jsxRuntime.jsx(FieldDocumentation, { + field: navItem.def, + }); } + let prevName; + if (explorerNavStack.length > 1) { + prevName = explorerNavStack.at(-2).name; + } + return /* @__PURE__ */ jsxRuntime.jsxs("section", { + className: "graphiql-doc-explorer", + "aria-label": "Documentation Explorer", + children: [ + /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-header", + children: [ + /* @__PURE__ */ jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-header-content", + children: [ + prevName && + /* @__PURE__ */ jsxRuntime.jsxs("a", { + href: "#", + className: "graphiql-doc-explorer-back", + onClick: (event) => { + event.preventDefault(); + pop(); + }, + "aria-label": `Go back to ${prevName}`, + children: [ + /* @__PURE__ */ jsxRuntime.jsx(ChevronLeftIcon, {}), + prevName, + ], + }), + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-title", + children: navItem.name, + }), + ], + }), + /* @__PURE__ */ jsxRuntime.jsx(Search, {}, navItem.name), + ], + }), + /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-content", + children: content, + }), + ], + }); } - return dirty; - } - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - function prepareSelection(cm, primary) { - if (primary === void 0) primary = true; - var doc = cm.doc, - result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - var customCursor = cm.options.$customCursor; - if (customCursor) { - primary = true; - } - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - if (!primary && i2 == doc.sel.primIndex) { - continue; - } - var range2 = doc.sel.ranges[i2]; - if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) { - continue; - } - var collapsed = range2.empty(); - if (customCursor) { - var head = customCursor(cm, range2); - if (head) { - drawSelectionCursor(cm, head, curFragment); - } - } else if (collapsed || cm.options.showCursorWhenSelecting) { - drawSelectionCursor(cm, range2.head, curFragment); - } - if (!collapsed) { - drawSelectionRange(cm, range2, selFragment); - } - } - return result; - } - function drawSelectionCursor(cm, head, output) { - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); - var cursor = output.appendChild(elt("div", " ", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { - var charPos = charCoords(cm, head, "div", null, null); - var width = charPos.right - charPos.left; - cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; - } - if (pos.other) { - var otherCursor = output.appendChild(elt("div", " ", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px"; - } - } - function cmpCoords(a, b) { - return a.top - b.top || a.left - b.left; - } - function drawSelectionRange(cm, range2, output) { - var display = cm.display, - doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), - leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - var docLTR = doc.direction == "ltr"; - function add(left, top, width, bottom) { - if (top < 0) { - top = 0; - } - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")); - } - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } - function wrapX(pos, dir, side) { - var extent = wrappedLineExtentChar(cm, lineObj, null, pos); - var prop2 = dir == "ltr" == (side == "after") ? "left" : "right"; - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); - return coords(ch, prop2)[prop2]; - } - var order = getOrder(lineObj, doc.direction); - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i2) { - var ltr = dir == "ltr"; - var fromPos = coords(from, ltr ? "left" : "right"); - var toPos = coords(to - 1, ltr ? "right" : "left"); - var openStart = fromArg == null && from == 0, - openEnd = toArg == null && to == lineLen; - var first = i2 == 0, - last = !order || i2 == order.length - 1; - if (toPos.top - fromPos.top <= 3) { - var openLeft = (docLTR ? openStart : openEnd) && first; - var openRight = (docLTR ? openEnd : openStart) && last; - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; - add(left, fromPos.top, right - left, fromPos.bottom); - } else { - var topLeft, topRight, botLeft, botRight; - if (ltr) { - topLeft = docLTR && openStart && first ? leftSide : fromPos.left; - topRight = docLTR ? rightSide : wrapX(from, dir, "before"); - botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); - botRight = docLTR && openEnd && last ? rightSide : toPos.right; - } else { - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); - topRight = !docLTR && openStart && first ? rightSide : fromPos.right; - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; - botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); - } - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); - if (fromPos.bottom < toPos.top) { - add(leftSide, fromPos.bottom, null, toPos.top); - } - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); + const DOC_EXPLORER_PLUGIN = { + title: "Documentation Explorer", + icon: function Icon() { + const pluginContext = usePluginContext(); + return (pluginContext == null + ? void 0 + : pluginContext.visiblePlugin) === DOC_EXPLORER_PLUGIN + ? /* @__PURE__ */ jsxRuntime.jsx(DocsFilledIcon, {}) + : /* @__PURE__ */ jsxRuntime.jsx(DocsIcon, {}); + }, + content: DocExplorer, + }; + const HISTORY_PLUGIN = { + title: "History", + icon: HistoryIcon, + content: History, + }; + const PluginContext = createNullableContext("PluginContext"); + function PluginContextProvider(props) { + const storage = useStorageContext(); + const explorerContext = useExplorerContext(); + const historyContext = useHistoryContext(); + const hasExplorerContext = Boolean(explorerContext); + const hasHistoryContext = Boolean(historyContext); + const plugins = React.useMemo(() => { + const pluginList = []; + const pluginTitles = {}; + if (hasExplorerContext) { + pluginList.push(DOC_EXPLORER_PLUGIN); + pluginTitles[DOC_EXPLORER_PLUGIN.title] = true; } - if (!start || cmpCoords(fromPos, start) < 0) { - start = fromPos; + if (hasHistoryContext) { + pluginList.push(HISTORY_PLUGIN); + pluginTitles[HISTORY_PLUGIN.title] = true; } - if (cmpCoords(toPos, start) < 0) { - start = toPos; + for (const plugin of props.plugins || []) { + if (typeof plugin.title !== "string" || !plugin.title) { + throw new Error( + "All GraphiQL plugins must have a unique title" + ); + } + if (pluginTitles[plugin.title]) { + throw new Error( + `All GraphiQL plugins must have a unique title, found two plugins with the title '${plugin.title}'` + ); + } else { + pluginList.push(plugin); + pluginTitles[plugin.title] = true; + } } - if (!end || cmpCoords(fromPos, end) < 0) { - end = fromPos; + return pluginList; + }, [hasExplorerContext, hasHistoryContext, props.plugins]); + const [visiblePlugin, internalSetVisiblePlugin] = React.useState( + () => { + const storedValue = + storage == null ? void 0 : storage.get(STORAGE_KEY$4); + const pluginForStoredValue = plugins.find( + (plugin) => plugin.title === storedValue + ); + if (pluginForStoredValue) { + return pluginForStoredValue; + } + if (storedValue) { + storage == null ? void 0 : storage.set(STORAGE_KEY$4, ""); + } + if (!props.visiblePlugin) { + return null; + } + return ( + plugins.find( + (plugin) => + (typeof props.visiblePlugin === "string" + ? plugin.title + : plugin) === props.visiblePlugin + ) || null + ); } - if (cmpCoords(toPos, end) < 0) { - end = toPos; + ); + const { onTogglePluginVisibility, children } = props; + const setVisiblePlugin = React.useCallback( + (plugin) => { + const newVisiblePlugin = plugin + ? plugins.find( + (p) => (typeof plugin === "string" ? p.title : p) === plugin + ) || null + : null; + internalSetVisiblePlugin((current) => { + if (newVisiblePlugin === current) { + return current; + } + onTogglePluginVisibility == null + ? void 0 + : onTogglePluginVisibility(newVisiblePlugin); + return newVisiblePlugin; + }); + }, + [onTogglePluginVisibility, plugins] + ); + React.useEffect(() => { + if (props.visiblePlugin) { + setVisiblePlugin(props.visiblePlugin); } + }, [plugins, props.visiblePlugin, setVisiblePlugin]); + const value = React.useMemo( + () => ({ + plugins, + setVisiblePlugin, + visiblePlugin, + }), + [plugins, setVisiblePlugin, visiblePlugin] + ); + return /* @__PURE__ */ jsxRuntime.jsx(PluginContext.Provider, { + value, + children, }); - return { - start, - end - }; - } - var sFrom = range2.from(), - sTo = range2.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), - toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) { - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - } - output.appendChild(fragment); - } - function restartBlink(cm) { - if (!cm.state.focused) { - return; } - var display = cm.display; - clearInterval(display.blinker); - var on2 = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) { - display.blinker = setInterval(function () { - if (!cm.hasFocus()) { - onBlur(cm); - } - display.cursorDiv.style.visibility = (on2 = !on2) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - } else if (cm.options.cursorBlinkRate < 0) { - display.cursorDiv.style.visibility = "hidden"; - } - } - function ensureFocus(cm) { - if (!cm.hasFocus()) { - cm.display.input.focus(); - if (!cm.state.focused) { - onFocus(cm); - } - } - } - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function () { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - if (cm.state.focused) { - onBlur(cm); + const usePluginContext = createContextHook(PluginContext); + const STORAGE_KEY$4 = "visiblePlugin"; + function onHasCompletion( + _cm, + data, + schema, + explorer, + plugin, + callback + ) { + void importCodeMirror([], { + useCommonAddons: false, + }).then((CodeMirror) => { + let information; + let fieldName; + let typeNamePill; + let typeNamePrefix; + let typeName; + let typeNameSuffix; + let description; + let deprecation; + let deprecationReason; + CodeMirror.on( + data, + "select", + // @ts-expect-error + (ctx, el) => { + if (!information) { + const hintsUl = el.parentNode; + information = document.createElement("div"); + information.className = "CodeMirror-hint-information"; + hintsUl.append(information); + const header = document.createElement("header"); + header.className = "CodeMirror-hint-information-header"; + information.append(header); + fieldName = document.createElement("span"); + fieldName.className = + "CodeMirror-hint-information-field-name"; + header.append(fieldName); + typeNamePill = document.createElement("span"); + typeNamePill.className = + "CodeMirror-hint-information-type-name-pill"; + header.append(typeNamePill); + typeNamePrefix = document.createElement("span"); + typeNamePill.append(typeNamePrefix); + typeName = document.createElement("a"); + typeName.className = "CodeMirror-hint-information-type-name"; + typeName.href = "javascript:void 0"; + typeName.addEventListener("click", onClickHintInformation); + typeNamePill.append(typeName); + typeNameSuffix = document.createElement("span"); + typeNamePill.append(typeNameSuffix); + description = document.createElement("div"); + description.className = + "CodeMirror-hint-information-description"; + information.append(description); + deprecation = document.createElement("div"); + deprecation.className = + "CodeMirror-hint-information-deprecation"; + information.append(deprecation); + const deprecationLabel = document.createElement("span"); + deprecationLabel.className = + "CodeMirror-hint-information-deprecation-label"; + deprecationLabel.textContent = "Deprecated"; + deprecation.append(deprecationLabel); + deprecationReason = document.createElement("div"); + deprecationReason.className = + "CodeMirror-hint-information-deprecation-reason"; + deprecation.append(deprecationReason); + const defaultInformationPadding = + parseInt( + window + .getComputedStyle(information) + .paddingBottom.replace(/px$/, ""), + 10 + ) || 0; + const defaultInformationMaxHeight = + parseInt( + window + .getComputedStyle(information) + .maxHeight.replace(/px$/, ""), + 10 + ) || 0; + const handleScroll = () => { + if (information) { + information.style.paddingTop = + hintsUl.scrollTop + defaultInformationPadding + "px"; + information.style.maxHeight = + hintsUl.scrollTop + defaultInformationMaxHeight + "px"; + } + }; + hintsUl.addEventListener("scroll", handleScroll); + let onRemoveFn; + hintsUl.addEventListener( + "DOMNodeRemoved", + (onRemoveFn = (event) => { + if (event.target !== hintsUl) { + return; + } + hintsUl.removeEventListener("scroll", handleScroll); + hintsUl.removeEventListener("DOMNodeRemoved", onRemoveFn); + if (information) { + information.removeEventListener( + "click", + onClickHintInformation + ); + } + information = null; + fieldName = null; + typeNamePill = null; + typeNamePrefix = null; + typeName = null; + typeNameSuffix = null; + description = null; + deprecation = null; + deprecationReason = null; + onRemoveFn = null; + }) + ); + } + if (fieldName) { + fieldName.textContent = ctx.text; + } + if ( + typeNamePill && + typeNamePrefix && + typeName && + typeNameSuffix + ) { + if (ctx.type) { + typeNamePill.style.display = "inline"; + const renderType2 = (type) => { + if (graphql.isNonNullType(type)) { + typeNameSuffix.textContent = + "!" + typeNameSuffix.textContent; + renderType2(type.ofType); + } else if (graphql.isListType(type)) { + typeNamePrefix.textContent += "["; + typeNameSuffix.textContent = + "]" + typeNameSuffix.textContent; + renderType2(type.ofType); + } else { + typeName.textContent = type.name; + } + }; + typeNamePrefix.textContent = ""; + typeNameSuffix.textContent = ""; + renderType2(ctx.type); + } else { + typeNamePrefix.textContent = ""; + typeName.textContent = ""; + typeNameSuffix.textContent = ""; + typeNamePill.style.display = "none"; + } + } + if (description) { + if (ctx.description) { + description.style.display = "block"; + description.innerHTML = markdown.render(ctx.description); + } else { + description.style.display = "none"; + description.innerHTML = ""; + } + } + if (deprecation && deprecationReason) { + if (ctx.deprecationReason) { + deprecation.style.display = "block"; + deprecationReason.innerHTML = markdown.render( + ctx.deprecationReason + ); + } else { + deprecation.style.display = "none"; + deprecationReason.innerHTML = ""; + } + } + } + ); + }); + function onClickHintInformation(event) { + if ( + !schema || + !explorer || + !plugin || + !(event.currentTarget instanceof HTMLElement) + ) { + return; } - } - }, 100); - } - function onFocus(cm, e) { - if (cm.state.delayingBlurEvent && !cm.state.draggingText) { - cm.state.delayingBlurEvent = false; - } - if (cm.options.readOnly == "nocursor") { - return; - } - if (!cm.state.focused) { - signal(cm, "focus", cm, e); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) { - setTimeout(function () { - return cm.display.input.reset(true); - }, 20); + const typeName = event.currentTarget.textContent || ""; + const type = schema.getType(typeName); + if (type) { + plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); + explorer.push({ + name: type.name, + def: type, + }); + callback == null ? void 0 : callback(type); } } - cm.display.input.receivedFocus(); } - restartBlink(cm); - } - function onBlur(cm, e) { - if (cm.state.delayingBlurEvent) { - return; - } - if (cm.state.focused) { - signal(cm, "blur", cm, e); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); + function useSynchronizeValue(editor, value) { + React.useEffect(() => { + if ( + editor && + typeof value === "string" && + value !== editor.getValue() + ) { + editor.setValue(value); + } + }, [editor, value]); } - clearInterval(cm.display.blinker); - setTimeout(function () { - if (!cm.state.focused) { - cm.display.shift = false; - } - }, 150); - } - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); - var oldHeight = display.lineDiv.getBoundingClientRect().top; - var mustScroll = 0; - for (var i2 = 0; i2 < display.view.length; i2++) { - var cur = display.view[i2], - wrapping = cm.options.lineWrapping; - var height = void 0, - width = 0; - if (cur.hidden) { - continue; - } - oldHeight += cur.line.height; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - if (!wrapping && cur.text.firstChild) { - width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; + function useSynchronizeOption(editor, option, value) { + React.useEffect(() => { + if (editor) { + editor.setOption(option, value); } - } - var diff = cur.line.height - height; - if (diff > 5e-3 || diff < -5e-3) { - if (oldHeight < viewTop) { - mustScroll -= diff; + }, [editor, option, value]); + } + function useChangeHandler( + editor, + callback, + storageKey, + tabProperty, + caller + ) { + const { updateActiveTabValues } = useEditorContext({ + nonNull: true, + caller, + }); + const storage = useStorageContext(); + React.useEffect(() => { + if (!editor) { + return; } - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) { - for (var j = 0; j < cur.rest.length; j++) { - updateWidgetHeight(cur.rest[j]); + const store = debounce(500, (value) => { + if (!storage || storageKey === null) { + return; + } + storage.set(storageKey, value); + }); + const updateTab = debounce(100, (value) => { + updateActiveTabValues({ + [tabProperty]: value, + }); + }); + const handleChange = (editorInstance, changeObj) => { + if (!changeObj) { + return; } + const newValue = editorInstance.getValue(); + store(newValue); + updateTab(newValue); + callback == null ? void 0 : callback(newValue); + }; + editor.on("change", handleChange); + return () => editor.off("change", handleChange); + }, [ + callback, + editor, + storage, + storageKey, + tabProperty, + updateActiveTabValues, + ]); + } + function useCompletion(editor, callback, caller) { + const { schema } = useSchemaContext({ + nonNull: true, + caller, + }); + const explorer = useExplorerContext(); + const plugin = usePluginContext(); + React.useEffect(() => { + if (!editor) { + return; } - } - if (width > cm.display.sizerWidth) { - var chWidth = Math.ceil(width / charWidth(cm.display)); - if (chWidth > cm.display.maxLineLength) { - cm.display.maxLineLength = chWidth; - cm.display.maxLine = cur.line; - cm.display.maxLineChanged = true; + const handleCompletion = (instance, changeObj) => { + onHasCompletion( + instance, + changeObj, + schema, + explorer, + plugin, + (type) => { + callback == null + ? void 0 + : callback({ + kind: "Type", + type, + schema: schema || void 0, + }); + } + ); + }; + editor.on( + // @ts-expect-error @TODO additional args for hasCompletion event + "hasCompletion", + handleCompletion + ); + return () => + editor.off( + // @ts-expect-error @TODO additional args for hasCompletion event + "hasCompletion", + handleCompletion + ); + }, [callback, editor, explorer, plugin, schema]); + } + function useKeyMap(editor, keys, callback) { + React.useEffect(() => { + if (!editor) { + return; } - } - } - if (Math.abs(mustScroll) > 2) { - display.scroller.scrollTop += mustScroll; - } - } - function updateWidgetHeight(line) { - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; ++i2) { - var w = line.widgets[i2], - parent = w.node.parentNode; - if (parent) { - w.height = parent.offsetHeight; + for (const key of keys) { + editor.removeKeyMap(key); } - } - } - } - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - var from = lineAtHeight(doc, top), - to = lineAtHeight(doc, bottom); - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, - ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return { - from, - to: Math.max(to, from + 1) - }; - } - function maybeScrollWindow(cm, rect) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) { - return; - } - var display = cm.display, - box = display.sizer.getBoundingClientRect(), - doScroll = null; - if (rect.top + box.top < 0) { - doScroll = true; - } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { - doScroll = false; - } - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "​", null, "position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); + if (callback) { + const keyMap = {}; + for (const key of keys) { + keyMap[key] = () => callback(); + } + editor.addKeyMap(keyMap); + } + }, [editor, keys, callback]); } - } - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) { - margin = 0; - } - var rect; - if (!cm.options.lineWrapping && pos == end) { - end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; - pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; - } - for (var limit = 0; limit < 5; limit++) { - var changed = false; - var coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - rect = { - left: Math.min(coords.left, endCoords.left), - top: Math.min(coords.top, endCoords.top) - margin, - right: Math.max(coords.left, endCoords.left), - bottom: Math.max(coords.bottom, endCoords.bottom) + margin - }; - var scrollPos = calculateScrollPos(cm, rect); - var startTop = cm.doc.scrollTop, - startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) { - changed = true; + function useCopyQuery({ caller, onCopyQuery } = {}) { + const { queryEditor } = useEditorContext({ + nonNull: true, + caller: caller || useCopyQuery, + }); + return React.useCallback(() => { + if (!queryEditor) { + return; } - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { - changed = true; + const query = queryEditor.getValue(); + copyToClipboard(query); + onCopyQuery == null ? void 0 : onCopyQuery(query); + }, [queryEditor, onCopyQuery]); + } + function useMergeQuery({ caller } = {}) { + const { queryEditor } = useEditorContext({ + nonNull: true, + caller: caller || useMergeQuery, + }); + const { schema } = useSchemaContext({ + nonNull: true, + caller: useMergeQuery, + }); + return React.useCallback(() => { + const documentAST = + queryEditor == null ? void 0 : queryEditor.documentAST; + const query = queryEditor == null ? void 0 : queryEditor.getValue(); + if (!documentAST || !query) { + return; } - } - if (!changed) { - break; - } - } - return rect; - } - function scrollIntoView(cm, rect) { - var scrollPos = calculateScrollPos(cm, rect); - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - } - } - function calculateScrollPos(cm, rect) { - var display = cm.display, - snapMargin = textHeight(cm.display); - if (rect.top < 0) { - rect.top = 0; - } - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen2 = displayHeight(cm), - result = {}; - if (rect.bottom - rect.top > screen2) { - rect.bottom = rect.top + screen2; - } - var docBottom = cm.doc.height + paddingVert(display); - var atTop = rect.top < snapMargin, - atBottom = rect.bottom > docBottom - snapMargin; - if (rect.top < screentop) { - result.scrollTop = atTop ? 0 : rect.top; - } else if (rect.bottom > screentop + screen2) { - var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2); - if (newTop != screentop) { - result.scrollTop = newTop; - } - } - var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; - var screenw = displayWidth(cm) - display.gutters.offsetWidth; - var tooWide = rect.right - rect.left > screenw; - if (tooWide) { - rect.right = rect.left + screenw; - } - if (rect.left < 10) { - result.scrollLeft = 0; - } else if (rect.left < screenleft) { - result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); - } else if (rect.right > screenw + screenleft - 3) { - result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; - } - return result; - } - function addToScrollTop(cm, top) { - if (top == null) { - return; - } - resolveScrollToPos(cm); - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(); - cm.curOp.scrollToPos = { - from: cur, - to: cur, - margin: cm.options.cursorScrollMargin - }; - } - function scrollToCoords(cm, x, y) { - if (x != null || y != null) { - resolveScrollToPos(cm); - } - if (x != null) { - cm.curOp.scrollLeft = x; - } - if (y != null) { - cm.curOp.scrollTop = y; - } - } - function scrollToRange(cm, range2) { - resolveScrollToPos(cm); - cm.curOp.scrollToPos = range2; - } - function resolveScrollToPos(cm) { - var range2 = cm.curOp.scrollToPos; - if (range2) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range2.from), - to = estimateCoords(cm, range2.to); - scrollToCoordsRange(cm, from, to, range2.margin); + queryEditor.setValue( + graphql.print(toolkit.mergeAst(documentAST, schema)) + ); + }, [queryEditor, schema]); } - } - function scrollToCoordsRange(cm, from, to, margin) { - var sPos = calculateScrollPos(cm, { - left: Math.min(from.left, to.left), - top: Math.min(from.top, to.top) - margin, - right: Math.max(from.right, to.right), - bottom: Math.max(from.bottom, to.bottom) + margin - }); - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); - } - function updateScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) { - return; + function usePrettifyEditors({ caller } = {}) { + const { queryEditor, headerEditor, variableEditor } = + useEditorContext({ + nonNull: true, + caller: caller || usePrettifyEditors, + }); + return React.useCallback(() => { + if (variableEditor) { + const variableEditorContent = variableEditor.getValue(); + try { + const prettifiedVariableEditorContent = JSON.stringify( + JSON.parse(variableEditorContent), + null, + 2 + ); + if (prettifiedVariableEditorContent !== variableEditorContent) { + variableEditor.setValue(prettifiedVariableEditorContent); + } + } catch {} + } + if (headerEditor) { + const headerEditorContent = headerEditor.getValue(); + try { + const prettifiedHeaderEditorContent = JSON.stringify( + JSON.parse(headerEditorContent), + null, + 2 + ); + if (prettifiedHeaderEditorContent !== headerEditorContent) { + headerEditor.setValue(prettifiedHeaderEditorContent); + } + } catch {} + } + if (queryEditor) { + const editorContent = queryEditor.getValue(); + const prettifiedEditorContent = graphql.print( + graphql.parse(editorContent) + ); + if (prettifiedEditorContent !== editorContent) { + queryEditor.setValue(prettifiedEditorContent); + } + } + }, [queryEditor, variableEditor, headerEditor]); } - if (!gecko) { - updateDisplaySimple(cm, { - top: val + function useAutoCompleteLeafs({ getDefaultFieldNames, caller } = {}) { + const { schema } = useSchemaContext({ + nonNull: true, + caller: caller || useAutoCompleteLeafs, }); + const { queryEditor } = useEditorContext({ + nonNull: true, + caller: caller || useAutoCompleteLeafs, + }); + return React.useCallback(() => { + if (!queryEditor) { + return; + } + const query = queryEditor.getValue(); + const { insertions, result } = toolkit.fillLeafs( + schema, + query, + getDefaultFieldNames + ); + if (insertions && insertions.length > 0) { + queryEditor.operation(() => { + const cursor = queryEditor.getCursor(); + const cursorIndex = queryEditor.indexFromPos(cursor); + queryEditor.setValue(result || ""); + let added = 0; + const markers = insertions.map(({ index, string }) => + queryEditor.markText( + queryEditor.posFromIndex(index + added), + queryEditor.posFromIndex(index + (added += string.length)), + { + className: "auto-inserted-leaf", + clearOnEnter: true, + title: "Automatically added leaf fields", + } + ) + ); + setTimeout(() => { + for (const marker of markers) { + marker.clear(); + } + }, 7e3); + let newCursorIndex = cursorIndex; + for (const { index, string } of insertions) { + if (index < cursorIndex) { + newCursorIndex += string.length; + } + } + queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex)); + }); + } + return result; + }, [getDefaultFieldNames, queryEditor, schema]); } - setScrollTop(cm, val, true); - if (gecko) { - updateDisplaySimple(cm); - } - startWorker(cm, 100); - } - function setScrollTop(cm, val, forceScroll) { - val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); - if (cm.display.scroller.scrollTop == val && !forceScroll) { - return; - } - cm.doc.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (cm.display.scroller.scrollTop != val) { - cm.display.scroller.scrollTop = val; - } - } - function setScrollLeft(cm, val, isScroller, forceScroll) { - val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); - if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { - return; - } - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) { - cm.display.scroller.scrollLeft = val; - } - cm.display.scrollbars.setScrollLeft(val); - } - function measureForScrollbars(cm) { - var d = cm.display, - gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, - clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW + const useEditorState = (editor) => { + var _ref2; + const context = useEditorContext({ + nonNull: true, + }); + const editorInstance = context[`${editor}Editor`]; + let valueString = ""; + const editorValue = + (_ref2 = + editorInstance == null ? void 0 : editorInstance.getValue()) !== + null && _ref2 !== void 0 + ? _ref2 + : false; + if (editorValue && editorValue.length > 0) { + valueString = editorValue; + } + const handleEditorValue = React.useCallback( + (value) => + editorInstance == null ? void 0 : editorInstance.setValue(value), + [editorInstance] + ); + return React.useMemo( + () => [valueString, handleEditorValue], + [valueString, handleEditorValue] + ); }; - } - var NativeScrollbars = function (place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - vert.tabIndex = horiz.tabIndex = -1; - place(vert); - place(horiz); - on(vert, "scroll", function () { - if (vert.clientHeight) { - scroll(vert.scrollTop, "vertical"); - } - }); - on(horiz, "scroll", function () { - if (horiz.clientWidth) { - scroll(horiz.scrollLeft, "horizontal"); - } - }); - this.checkedZeroWidth = false; - if (ie && ie_version < 8) { - this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - }; - NativeScrollbars.prototype.update = function (measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.scrollTop = 0; - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) { - this.zeroWidthHack(); - } - this.checkedZeroWidth = true; - } - return { - right: needsV ? sWidth : 0, - bottom: needsH ? sWidth : 0 + const useOperationsEditorState = () => { + return useEditorState("query"); }; - }; - NativeScrollbars.prototype.setScrollLeft = function (pos) { - if (this.horiz.scrollLeft != pos) { - this.horiz.scrollLeft = pos; - } - if (this.disableHoriz) { - this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); - } - }; - NativeScrollbars.prototype.setScrollTop = function (pos) { - if (this.vert.scrollTop != pos) { - this.vert.scrollTop = pos; - } - if (this.disableVert) { - this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); - } - }; - NativeScrollbars.prototype.zeroWidthHack = function () { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.height = this.vert.style.width = w; - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; - this.disableHoriz = new Delayed(); - this.disableVert = new Delayed(); - }; - NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { - bar.style.pointerEvents = "auto"; - function maybeDisable() { - var box = bar.getBoundingClientRect(); - var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); - if (elt2 != bar) { - bar.style.pointerEvents = "none"; - } else { - delay.set(1e3, maybeDisable); - } - } - delay.set(1e3, maybeDisable); - }; - NativeScrollbars.prototype.clear = function () { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - }; - var NullScrollbars = function () {}; - NullScrollbars.prototype.update = function () { - return { - bottom: 0, - right: 0 + const useVariablesEditorState = () => { + return useEditorState("variable"); }; - }; - NullScrollbars.prototype.setScrollLeft = function () {}; - NullScrollbars.prototype.setScrollTop = function () {}; - NullScrollbars.prototype.clear = function () {}; - function updateScrollbars(cm, measure) { - if (!measure) { - measure = measureForScrollbars(cm); - } - var startWidth = cm.display.barWidth, - startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { - updateHeightsInViewport(cm); - } - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; - startHeight = cm.display.barHeight; - } - } - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else { - d.scrollbarFiller.style.display = ""; - } - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else { - d.gutterFiller.style.display = ""; - } - } - var scrollbarModel = { - "native": NativeScrollbars, - "null": NullScrollbars - }; - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) { - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - } - cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - on(node, "mousedown", function () { - if (cm.state.focused) { - setTimeout(function () { - return cm.display.input.focus(); - }, 0); - } - }); - node.setAttribute("cm-not-content", "true"); - }, function (pos, axis) { - if (axis == "horizontal") { - setScrollLeft(cm, pos); - } else { - updateScrollTop(cm, pos); - } - }, cm); - if (cm.display.scrollbars.addClass) { - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - } - var nextOpId = 0; - function startOperation(cm) { - cm.curOp = { - cm, - viewChanged: false, - // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, - // Used to detect need to update scrollbar - forceUpdate: false, - // Used to force a redraw - updateInput: 0, - // Whether to reset the input textarea - typing: false, - // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, - // Accumulated changes, for firing change events - cursorActivityHandlers: null, - // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, - // Tracks which cursorActivity handlers have been called already - selectionChanged: false, - // Whether the selection needs to be redrawn - updateMaxLine: false, - // Set when the widest line needs to be determined anew - scrollLeft: null, - scrollTop: null, - // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, - // Used to scroll to a specific position - focus: false, - id: ++nextOpId, - // Unique ID - markArrays: null - // Used by addMarkedSpan + const useHeadersEditorState = () => { + return useEditorState("header"); }; - pushOperation(cm.curOp); - } - function endOperation(cm) { - var op = cm.curOp; - if (op) { - finishOperation(op, function (group) { - for (var i2 = 0; i2 < group.ops.length; i2++) { - group.ops[i2].cm.curOp = null; - } - endOperations(group); + function useOptimisticState([upstreamState, upstreamSetState]) { + const lastStateRef = React.useRef({ + /** The last thing that we sent upstream; we're expecting this back */ + pending: null, + /** The last thing we received from upstream */ + last: upstreamState, }); + const [state, setOperationsText] = React.useState(upstreamState); + React.useEffect(() => { + if (lastStateRef.current.last === upstreamState); + else { + lastStateRef.current.last = upstreamState; + if (lastStateRef.current.pending === null) { + setOperationsText(upstreamState); + } else if (lastStateRef.current.pending === upstreamState) { + lastStateRef.current.pending = null; + if (upstreamState !== state) { + lastStateRef.current.pending = state; + upstreamSetState(state); + } + } else { + lastStateRef.current.pending = null; + setOperationsText(upstreamState); + } + } + }, [upstreamState, state, upstreamSetState]); + const setState = React.useCallback( + (newState) => { + setOperationsText(newState); + if ( + lastStateRef.current.pending === null && + lastStateRef.current.last !== newState + ) { + lastStateRef.current.pending = newState; + upstreamSetState(newState); + } + }, + [upstreamSetState] + ); + return React.useMemo(() => [state, setState], [state, setState]); } - } - function endOperations(group) { - var ops = group.ops; - for (var i2 = 0; i2 < ops.length; i2++) { - endOperation_R1(ops[i2]); - } - for (var i$12 = 0; i$12 < ops.length; i$12++) { - endOperation_W1(ops[i$12]); - } - for (var i$22 = 0; i$22 < ops.length; i$22++) { - endOperation_R2(ops[i$22]); - } - for (var i$3 = 0; i$3 < ops.length; i$3++) { - endOperation_W2(ops[i$3]); + function useHeaderEditor( + { + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onEdit, + readOnly = false, + } = {}, + caller + ) { + const { + initialHeaders, + headerEditor, + setHeaderEditor, + shouldPersistHeaders, + } = useEditorContext({ + nonNull: true, + caller: caller || useHeaderEditor, + }); + const executionContext = useExecutionContext(); + const merge = useMergeQuery({ + caller: caller || useHeaderEditor, + }); + const prettify = usePrettifyEditors({ + caller: caller || useHeaderEditor, + }); + const ref = React.useRef(null); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([ + // @ts-expect-error + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./javascript.cjs.js */ "../../graphiql-react/dist/javascript.cjs.js" + ) + ) + .then((n) => n.javascript), + ]).then((CodeMirror) => { + if (!isActive) { + return; + } + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialHeaders, + lineNumbers: true, + tabSize: 2, + mode: { + name: "javascript", + json: true, + }, + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: commonKeys, + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + "Alt-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + }); + newEditor.on("keyup", (editorInstance, event) => { + const { code, key, shiftKey } = event; + const isLetter = code.startsWith("Key"); + const isNumber = !shiftKey && code.startsWith("Digit"); + if (isLetter || isNumber || key === "_" || key === '"') { + editorInstance.execCommand("autocomplete"); + } + }); + setHeaderEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialHeaders, readOnly, setHeaderEditor]); + useSynchronizeOption(headerEditor, "keyMap", keyMap); + useChangeHandler( + headerEditor, + onEdit, + shouldPersistHeaders ? STORAGE_KEY$3 : null, + "headers", + useHeaderEditor + ); + useKeyMap( + headerEditor, + ["Cmd-Enter", "Ctrl-Enter"], + executionContext == null ? void 0 : executionContext.run + ); + useKeyMap(headerEditor, ["Shift-Ctrl-P"], prettify); + useKeyMap(headerEditor, ["Shift-Ctrl-M"], merge); + return ref; } - for (var i$4 = 0; i$4 < ops.length; i$4++) { - endOperation_finish(ops[i$4]); + const STORAGE_KEY$3 = "headers"; + const invalidCharacters = Array.from( + { + length: 11, + }, + (_, i) => { + return String.fromCharCode(8192 + i); + } + ).concat(["\u2028", "\u2029", " ", " "]); + const sanitizeRegex = new RegExp( + "[" + invalidCharacters.join("") + "]", + "g" + ); + function normalizeWhitespace(line) { + return line.replace(sanitizeRegex, " "); } - } - function endOperation_R1(op) { - var cm = op.cm, - display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) { - findMaxLine(cm); - } - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { - top: op.scrollTop, - ensure: op.scrollToPos - }, op.forceUpdate); - } - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } - function endOperation_R2(op) { - var cm = op.cm, - display = cm.display; - if (op.updatedDisplay) { - updateHeightsInViewport(cm); - } - op.barMeasure = measureForScrollbars(cm); - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - if (op.updatedDisplay || op.selectionChanged) { - op.preparedSelection = display.input.prepareSelection(); + function useQueryEditor( + { + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onClickReference, + onCopyQuery, + onEdit, + readOnly = false, + } = {}, + caller + ) { + const { schema } = useSchemaContext({ + nonNull: true, + caller: caller || useQueryEditor, + }); + const { + externalFragments, + initialQuery, + queryEditor, + setOperationName, + setQueryEditor, + validationRules, + variableEditor, + updateActiveTabValues, + } = useEditorContext({ + nonNull: true, + caller: caller || useQueryEditor, + }); + const executionContext = useExecutionContext(); + const storage = useStorageContext(); + const explorer = useExplorerContext(); + const plugin = usePluginContext(); + const copy = useCopyQuery({ + caller: caller || useQueryEditor, + onCopyQuery, + }); + const merge = useMergeQuery({ + caller: caller || useQueryEditor, + }); + const prettify = usePrettifyEditors({ + caller: caller || useQueryEditor, + }); + const ref = React.useRef(null); + const codeMirrorRef = React.useRef(); + const onClickReferenceRef = React.useRef(() => {}); + React.useEffect(() => { + onClickReferenceRef.current = (reference) => { + if (!explorer || !plugin) { + return; + } + plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); + switch (reference.kind) { + case "Type": { + explorer.push({ + name: reference.type.name, + def: reference.type, + }); + break; + } + case "Field": { + explorer.push({ + name: reference.field.name, + def: reference.field, + }); + break; + } + case "Argument": { + if (reference.field) { + explorer.push({ + name: reference.field.name, + def: reference.field, + }); + } + break; + } + case "EnumValue": { + if (reference.type) { + explorer.push({ + name: reference.type.name, + def: reference.type, + }); + } + break; + } + } + onClickReference == null ? void 0 : onClickReference(reference); + }; + }, [explorer, onClickReference, plugin]); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([ + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./comment.cjs.js */ "../../graphiql-react/dist/comment.cjs.js" + ) + ) + .then((n) => n.comment), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js" + ) + ) + .then((n) => n.search), + Promise.resolve().then(() => + __webpack_require__( + /*! ./hint.cjs.js */ "../../graphiql-react/dist/hint.cjs.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./lint.cjs2.js */ "../../graphiql-react/dist/lint.cjs2.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./info.cjs.js */ "../../graphiql-react/dist/info.cjs.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./jump.cjs.js */ "../../graphiql-react/dist/jump.cjs.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./mode.cjs.js */ "../../graphiql-react/dist/mode.cjs.js" + ) + ), + ]).then((CodeMirror) => { + if (!isActive) { + return; + } + codeMirrorRef.current = CodeMirror; + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialQuery, + lineNumbers: true, + tabSize: 2, + foldGutter: true, + mode: "graphql", + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + lint: { + // @ts-expect-error + schema: void 0, + validationRules: null, + // linting accepts string or FragmentDefinitionNode[] + externalFragments: void 0, + }, + hintOptions: { + // @ts-expect-error + schema: void 0, + closeOnUnfocus: false, + completeSingle: false, + container, + externalFragments: void 0, + autocompleteOptions: { + // for the query editor, restrict to executable type definitions + mode: graphqlLanguageService.GraphQLDocumentMode.EXECUTABLE, + }, + }, + info: { + schema: void 0, + renderDescription: (text) => markdown.render(text), + onClick(reference) { + onClickReferenceRef.current(reference); + }, + }, + jump: { + schema: void 0, + onClick(reference) { + onClickReferenceRef.current(reference); + }, + }, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: { + ...commonKeys, + "Cmd-S"() {}, + "Ctrl-S"() {}, + }, + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: true, + container, + }); + }, + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: true, + container, + }); + }, + "Alt-Space"() { + newEditor.showHint({ + completeSingle: true, + container, + }); + }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: true, + container, + }); + }, + "Shift-Alt-Space"() { + newEditor.showHint({ + completeSingle: true, + container, + }); + }, + }); + newEditor.on("keyup", (editorInstance, event) => { + if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { + editorInstance.execCommand("autocomplete"); + } + }); + let showingHints = false; + newEditor.on("startCompletion", () => { + showingHints = true; + }); + newEditor.on("endCompletion", () => { + showingHints = false; + }); + newEditor.on("keydown", (editorInstance, event) => { + if (event.key === "Escape" && showingHints) { + event.stopPropagation(); + } + }); + newEditor.on("beforeChange", (editorInstance, change) => { + var _a; + if (change.origin === "paste") { + const text = change.text.map(normalizeWhitespace); + (_a = change.update) == null + ? void 0 + : _a.call(change, change.from, change.to, text); + } + }); + newEditor.documentAST = null; + newEditor.operationName = null; + newEditor.operations = null; + newEditor.variableToType = null; + setQueryEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialQuery, readOnly, setQueryEditor]); + useSynchronizeOption(queryEditor, "keyMap", keyMap); + React.useEffect(() => { + if (!queryEditor) { + return; + } + function getAndUpdateOperationFacts(editorInstance) { + var _editorInstance$opera, _editorInstance$opera2, _ref3, _ref4; + var _a; + const operationFacts = graphqlLanguageService.getOperationFacts( + schema, + editorInstance.getValue() + ); + const operationName = toolkit.getSelectedOperationName( + (_editorInstance$opera = editorInstance.operations) !== null && + _editorInstance$opera !== void 0 + ? _editorInstance$opera + : void 0, + (_editorInstance$opera2 = editorInstance.operationName) !== + null && _editorInstance$opera2 !== void 0 + ? _editorInstance$opera2 + : void 0, + operationFacts == null ? void 0 : operationFacts.operations + ); + editorInstance.documentAST = + (_ref3 = + operationFacts == null + ? void 0 + : operationFacts.documentAST) !== null && _ref3 !== void 0 + ? _ref3 + : null; + editorInstance.operationName = + operationName !== null && operationName !== void 0 + ? operationName + : null; + editorInstance.operations = + (_ref4 = + operationFacts == null + ? void 0 + : operationFacts.operations) !== null && _ref4 !== void 0 + ? _ref4 + : null; + if (variableEditor) { + variableEditor.state.lint.linterOptions.variableToType = + operationFacts == null + ? void 0 + : operationFacts.variableToType; + variableEditor.options.lint.variableToType = + operationFacts == null + ? void 0 + : operationFacts.variableToType; + variableEditor.options.hintOptions.variableToType = + operationFacts == null + ? void 0 + : operationFacts.variableToType; + (_a = codeMirrorRef.current) == null + ? void 0 + : _a.signal(variableEditor, "change", variableEditor); + } + return operationFacts + ? { + ...operationFacts, + operationName, + } + : null; + } + const handleChange = debounce(100, (editorInstance) => { + var _ref5; + const query = editorInstance.getValue(); + storage == null ? void 0 : storage.set(STORAGE_KEY_QUERY, query); + const currentOperationName = editorInstance.operationName; + const operationFacts = getAndUpdateOperationFacts(editorInstance); + if ( + (operationFacts == null + ? void 0 + : operationFacts.operationName) !== void 0 + ) { + storage == null + ? void 0 + : storage.set( + STORAGE_KEY_OPERATION_NAME, + operationFacts.operationName + ); + } + onEdit == null + ? void 0 + : onEdit( + query, + operationFacts == null ? void 0 : operationFacts.documentAST + ); + if ( + (operationFacts == null + ? void 0 + : operationFacts.operationName) && + currentOperationName !== operationFacts.operationName + ) { + setOperationName(operationFacts.operationName); + } + updateActiveTabValues({ + query, + operationName: + (_ref5 = + operationFacts == null + ? void 0 + : operationFacts.operationName) !== null && + _ref5 !== void 0 + ? _ref5 + : null, + }); + }); + getAndUpdateOperationFacts(queryEditor); + queryEditor.on("change", handleChange); + return () => queryEditor.off("change", handleChange); + }, [ + onEdit, + queryEditor, + schema, + setOperationName, + storage, + variableEditor, + updateActiveTabValues, + ]); + useSynchronizeSchema( + queryEditor, + schema !== null && schema !== void 0 ? schema : null, + codeMirrorRef + ); + useSynchronizeValidationRules( + queryEditor, + validationRules !== null && validationRules !== void 0 + ? validationRules + : null, + codeMirrorRef + ); + useSynchronizeExternalFragments( + queryEditor, + externalFragments, + codeMirrorRef + ); + useCompletion(queryEditor, onClickReference || null, useQueryEditor); + const run = executionContext == null ? void 0 : executionContext.run; + const runAtCursor = React.useCallback(() => { + var _a; + if ( + !run || + !queryEditor || + !queryEditor.operations || + !queryEditor.hasFocus() + ) { + run == null ? void 0 : run(); + return; + } + const cursorIndex = queryEditor.indexFromPos( + queryEditor.getCursor() + ); + let operationName; + for (const operation of queryEditor.operations) { + if ( + operation.loc && + operation.loc.start <= cursorIndex && + operation.loc.end >= cursorIndex + ) { + operationName = + (_a = operation.name) == null ? void 0 : _a.value; + } + } + if (operationName && operationName !== queryEditor.operationName) { + setOperationName(operationName); + } + run(); + }, [queryEditor, run, setOperationName]); + useKeyMap(queryEditor, ["Cmd-Enter", "Ctrl-Enter"], runAtCursor); + useKeyMap(queryEditor, ["Shift-Ctrl-C"], copy); + useKeyMap( + queryEditor, + [ + "Shift-Ctrl-P", + // Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to prettify + "Shift-Ctrl-F", + ], + prettify + ); + useKeyMap(queryEditor, ["Shift-Ctrl-M"], merge); + return ref; } - } - function endOperation_W2(op) { - var cm = op.cm; - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) { - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); + function useSynchronizeSchema(editor, schema, codeMirrorRef) { + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = editor.options.lint.schema !== schema; + editor.state.lint.linterOptions.schema = schema; + editor.options.lint.schema = schema; + editor.options.hintOptions.schema = schema; + editor.options.info.schema = schema; + editor.options.jump.schema = schema; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, schema, codeMirrorRef]); + } + function useSynchronizeValidationRules( + editor, + validationRules, + codeMirrorRef + ) { + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = + editor.options.lint.validationRules !== validationRules; + editor.state.lint.linterOptions.validationRules = validationRules; + editor.options.lint.validationRules = validationRules; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, validationRules, codeMirrorRef]); + } + function useSynchronizeExternalFragments( + editor, + externalFragments, + codeMirrorRef + ) { + const externalFragmentList = React.useMemo( + () => [...externalFragments.values()], + [externalFragments] + ); + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = + editor.options.lint.externalFragments !== externalFragmentList; + editor.state.lint.linterOptions.externalFragments = + externalFragmentList; + editor.options.lint.externalFragments = externalFragmentList; + editor.options.hintOptions.externalFragments = externalFragmentList; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, externalFragmentList, codeMirrorRef]); + } + const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/; + const STORAGE_KEY_QUERY = "query"; + const STORAGE_KEY_OPERATION_NAME = "operationName"; + function getDefaultTabState({ + defaultQuery, + defaultHeaders, + headers, + defaultTabs, + query, + variables, + storage, + shouldPersistHeaders, + }) { + const storedState = + storage == null ? void 0 : storage.get(STORAGE_KEY$2); + try { + if (!storedState) { + throw new Error("Storage for tabs is empty"); + } + const parsed = JSON.parse(storedState); + const headersForHash = shouldPersistHeaders ? headers : void 0; + if (isTabsState(parsed)) { + const expectedHash = hashFromTabContents({ + query, + variables, + headers: headersForHash, + }); + let matchingTabIndex = -1; + for (let index = 0; index < parsed.tabs.length; index++) { + const tab = parsed.tabs[index]; + tab.hash = hashFromTabContents({ + query: tab.query, + variables: tab.variables, + headers: tab.headers, + }); + if (tab.hash === expectedHash) { + matchingTabIndex = index; + } + } + if (matchingTabIndex >= 0) { + parsed.activeTabIndex = matchingTabIndex; + } else { + const operationName = query + ? fuzzyExtractOperationName(query) + : null; + parsed.tabs.push({ + id: guid(), + hash: expectedHash, + title: operationName || DEFAULT_TITLE, + query, + variables, + headers, + operationName, + response: null, + }); + parsed.activeTabIndex = parsed.tabs.length - 1; + } + return parsed; + } + throw new Error("Storage for tabs is invalid"); + } catch { + return { + activeTabIndex: 0, + tabs: ( + defaultTabs || [ + { + query: + query !== null && query !== void 0 ? query : defaultQuery, + variables, + headers: + headers !== null && headers !== void 0 + ? headers + : defaultHeaders, + }, + ] + ).map(createTab), + }; } - cm.display.maxLineChanged = false; } - var takeFocus = op.focus && op.focus == activeElt(); - if (op.preparedSelection) { - cm.display.input.showSelection(op.preparedSelection, takeFocus); + function isTabsState(obj) { + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + hasNumberKey(obj, "activeTabIndex") && + "tabs" in obj && + Array.isArray(obj.tabs) && + obj.tabs.every(isTabState) + ); } - if (op.updatedDisplay || op.startHeight != cm.doc.height) { - updateScrollbars(cm, op.barMeasure); + function isTabState(obj) { + return ( + obj && + typeof obj === "object" && + !Array.isArray(obj) && + hasStringKey(obj, "id") && + hasStringKey(obj, "title") && + hasStringOrNullKey(obj, "query") && + hasStringOrNullKey(obj, "variables") && + hasStringOrNullKey(obj, "headers") && + hasStringOrNullKey(obj, "operationName") && + hasStringOrNullKey(obj, "response") + ); } - if (op.updatedDisplay) { - setDocumentHeight(cm, op.barMeasure); + function hasNumberKey(obj, key) { + return key in obj && typeof obj[key] === "number"; } - if (op.selectionChanged) { - restartBlink(cm); + function hasStringKey(obj, key) { + return key in obj && typeof obj[key] === "string"; } - if (cm.state.focused && op.updateInput) { - cm.display.input.reset(op.typing); + function hasStringOrNullKey(obj, key) { + return ( + key in obj && (typeof obj[key] === "string" || obj[key] === null) + ); } - if (takeFocus) { - ensureFocus(op.cm); + function useSynchronizeActiveTabValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor, + }) { + return React.useCallback( + (state) => { + var _ref6, _ref7, _ref8, _ref9, _ref10; + const query = + (_ref6 = + queryEditor == null ? void 0 : queryEditor.getValue()) !== + null && _ref6 !== void 0 + ? _ref6 + : null; + const variables = + (_ref7 = + variableEditor == null + ? void 0 + : variableEditor.getValue()) !== null && _ref7 !== void 0 + ? _ref7 + : null; + const headers = + (_ref8 = + headerEditor == null ? void 0 : headerEditor.getValue()) !== + null && _ref8 !== void 0 + ? _ref8 + : null; + const operationName = + (_ref9 = + queryEditor == null ? void 0 : queryEditor.operationName) !== + null && _ref9 !== void 0 + ? _ref9 + : null; + const response = + (_ref10 = + responseEditor == null + ? void 0 + : responseEditor.getValue()) !== null && _ref10 !== void 0 + ? _ref10 + : null; + return setPropertiesInActiveTab(state, { + query, + variables, + headers, + response, + operationName, + }); + }, + [queryEditor, variableEditor, headerEditor, responseEditor] + ); } - } - function endOperation_finish(op) { - var cm = op.cm, - display = cm.display, - doc = cm.doc; - if (op.updatedDisplay) { - postUpdateDisplay(cm, op.update); + function serializeTabState(tabState, shouldPersistHeaders = false) { + return JSON.stringify(tabState, (key, value) => + key === "hash" || + key === "response" || + (!shouldPersistHeaders && key === "headers") + ? null + : value + ); } - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { - display.wheelStartX = display.wheelStartY = null; + function useStoreTabs({ storage, shouldPersistHeaders }) { + const store = React.useMemo( + () => + debounce(500, (value) => { + storage == null ? void 0 : storage.set(STORAGE_KEY$2, value); + }), + [storage] + ); + return React.useCallback( + (currentState) => { + store(serializeTabState(currentState, shouldPersistHeaders)); + }, + [shouldPersistHeaders, store] + ); } - if (op.scrollTop != null) { - setScrollTop(cm, op.scrollTop, op.forceScroll); + function useSetEditorValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor, + }) { + return React.useCallback( + ({ query, variables, headers, response }) => { + queryEditor == null + ? void 0 + : queryEditor.setValue( + query !== null && query !== void 0 ? query : "" + ); + variableEditor == null + ? void 0 + : variableEditor.setValue( + variables !== null && variables !== void 0 ? variables : "" + ); + headerEditor == null + ? void 0 + : headerEditor.setValue( + headers !== null && headers !== void 0 ? headers : "" + ); + responseEditor == null + ? void 0 + : responseEditor.setValue( + response !== null && response !== void 0 ? response : "" + ); + }, + [headerEditor, queryEditor, responseEditor, variableEditor] + ); } - if (op.scrollLeft != null) { - setScrollLeft(cm, op.scrollLeft, true, true); + function createTab({ + query = null, + variables = null, + headers = null, + } = {}) { + return { + id: guid(), + hash: hashFromTabContents({ + query, + variables, + headers, + }), + title: (query && fuzzyExtractOperationName(query)) || DEFAULT_TITLE, + query, + variables, + headers, + operationName: null, + response: null, + }; } - if (op.scrollToPos) { - var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - maybeScrollWindow(cm, rect); + function setPropertiesInActiveTab(state, partialTab) { + return { + ...state, + tabs: state.tabs.map((tab, index) => { + if (index !== state.activeTabIndex) { + return tab; + } + const newTab = { + ...tab, + ...partialTab, + }; + return { + ...newTab, + hash: hashFromTabContents(newTab), + title: + newTab.operationName || + (newTab.query + ? fuzzyExtractOperationName(newTab.query) + : void 0) || + DEFAULT_TITLE, + }; + }), + }; } - var hidden = op.maybeHiddenMarkers, - unhidden = op.maybeUnhiddenMarkers; - if (hidden) { - for (var i2 = 0; i2 < hidden.length; ++i2) { - if (!hidden[i2].lines.length) { - signal(hidden[i2], "hide"); + function guid() { + const s4 = () => { + return Math.floor((1 + Math.random()) * 65536) + .toString(16) + .slice(1); + }; + return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; + } + function hashFromTabContents(args) { + var _args$query, _args$variables, _args$headers; + return [ + (_args$query = args.query) !== null && _args$query !== void 0 + ? _args$query + : "", + (_args$variables = args.variables) !== null && + _args$variables !== void 0 + ? _args$variables + : "", + (_args$headers = args.headers) !== null && _args$headers !== void 0 + ? _args$headers + : "", + ].join("|"); + } + function fuzzyExtractOperationName(str) { + var _ref11; + const regex = + /^(?!#).*(query|subscription|mutation)\s+([a-zA-Z0-9_]+)/m; + const match = regex.exec(str); + return (_ref11 = match == null ? void 0 : match[2]) !== null && + _ref11 !== void 0 + ? _ref11 + : null; + } + function clearHeadersFromTabs(storage) { + const persistedTabs = + storage == null ? void 0 : storage.get(STORAGE_KEY$2); + if (persistedTabs) { + const parsedTabs = JSON.parse(persistedTabs); + storage == null + ? void 0 + : storage.set( + STORAGE_KEY$2, + JSON.stringify(parsedTabs, (key, value) => + key === "headers" ? null : value + ) + ); + } + } + const DEFAULT_TITLE = ""; + const STORAGE_KEY$2 = "tabState"; + function useVariableEditor( + { + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onClickReference, + onEdit, + readOnly = false, + } = {}, + caller + ) { + const { initialVariables, variableEditor, setVariableEditor } = + useEditorContext({ + nonNull: true, + caller: caller || useVariableEditor, + }); + const executionContext = useExecutionContext(); + const merge = useMergeQuery({ + caller: caller || useVariableEditor, + }); + const prettify = usePrettifyEditors({ + caller: caller || useVariableEditor, + }); + const ref = React.useRef(null); + const codeMirrorRef = React.useRef(); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([ + Promise.resolve().then(() => + __webpack_require__( + /*! ./hint.cjs2.js */ "../../graphiql-react/dist/hint.cjs2.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./lint.cjs3.js */ "../../graphiql-react/dist/lint.cjs3.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./mode.cjs2.js */ "../../graphiql-react/dist/mode.cjs2.js" + ) + ), + ]).then((CodeMirror) => { + if (!isActive) { + return; + } + codeMirrorRef.current = CodeMirror; + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialVariables, + lineNumbers: true, + tabSize: 2, + mode: "graphql-variables", + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + foldGutter: true, + lint: { + // @ts-expect-error + variableToType: void 0, + }, + hintOptions: { + closeOnUnfocus: false, + completeSingle: false, + container, + // @ts-expect-error + variableToType: void 0, + }, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: commonKeys, + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + "Alt-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: false, + container, + }); + }, + }); + newEditor.on("keyup", (editorInstance, event) => { + const { code, key, shiftKey } = event; + const isLetter = code.startsWith("Key"); + const isNumber = !shiftKey && code.startsWith("Digit"); + if (isLetter || isNumber || key === "_" || key === '"') { + editorInstance.execCommand("autocomplete"); + } + }); + setVariableEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialVariables, readOnly, setVariableEditor]); + useSynchronizeOption(variableEditor, "keyMap", keyMap); + useChangeHandler( + variableEditor, + onEdit, + STORAGE_KEY$1, + "variables", + useVariableEditor + ); + useCompletion( + variableEditor, + onClickReference || null, + useVariableEditor + ); + useKeyMap( + variableEditor, + ["Cmd-Enter", "Ctrl-Enter"], + executionContext == null ? void 0 : executionContext.run + ); + useKeyMap(variableEditor, ["Shift-Ctrl-P"], prettify); + useKeyMap(variableEditor, ["Shift-Ctrl-M"], merge); + return ref; + } + const STORAGE_KEY$1 = "variables"; + const EditorContext = createNullableContext("EditorContext"); + function EditorContextProvider(props) { + const storage = useStorageContext(); + const [headerEditor, setHeaderEditor] = React.useState(null); + const [queryEditor, setQueryEditor] = React.useState(null); + const [responseEditor, setResponseEditor] = React.useState(null); + const [variableEditor, setVariableEditor] = React.useState(null); + const [shouldPersistHeaders, setShouldPersistHeadersInternal] = + React.useState(() => { + const isStored = + (storage == null + ? void 0 + : storage.get(PERSIST_HEADERS_STORAGE_KEY)) !== null; + return props.shouldPersistHeaders !== false && isStored + ? (storage == null + ? void 0 + : storage.get(PERSIST_HEADERS_STORAGE_KEY)) === "true" + : Boolean(props.shouldPersistHeaders); + }); + useSynchronizeValue(headerEditor, props.headers); + useSynchronizeValue(queryEditor, props.query); + useSynchronizeValue(responseEditor, props.response); + useSynchronizeValue(variableEditor, props.variables); + const storeTabs = useStoreTabs({ + storage, + shouldPersistHeaders, + }); + const [initialState] = React.useState(() => { + var _ref12, + _props$query, + _ref13, + _props$variables, + _ref14, + _props$headers, + _props$response, + _ref15, + _ref16; + const query = + (_ref12 = + (_props$query = props.query) !== null && _props$query !== void 0 + ? _props$query + : storage == null + ? void 0 + : storage.get(STORAGE_KEY_QUERY)) !== null && + _ref12 !== void 0 + ? _ref12 + : null; + const variables = + (_ref13 = + (_props$variables = props.variables) !== null && + _props$variables !== void 0 + ? _props$variables + : storage == null + ? void 0 + : storage.get(STORAGE_KEY$1)) !== null && _ref13 !== void 0 + ? _ref13 + : null; + const headers = + (_ref14 = + (_props$headers = props.headers) !== null && + _props$headers !== void 0 + ? _props$headers + : storage == null + ? void 0 + : storage.get(STORAGE_KEY$3)) !== null && _ref14 !== void 0 + ? _ref14 + : null; + const response = + (_props$response = props.response) !== null && + _props$response !== void 0 + ? _props$response + : ""; + const tabState2 = getDefaultTabState({ + query, + variables, + headers, + defaultTabs: props.defaultTabs, + defaultQuery: props.defaultQuery || DEFAULT_QUERY, + defaultHeaders: props.defaultHeaders, + storage, + shouldPersistHeaders, + }); + storeTabs(tabState2); + return { + query: + (_ref15 = + query !== null && query !== void 0 + ? query + : tabState2.activeTabIndex === 0 + ? tabState2.tabs[0].query + : null) !== null && _ref15 !== void 0 + ? _ref15 + : "", + variables: + variables !== null && variables !== void 0 ? variables : "", + headers: + (_ref16 = + headers !== null && headers !== void 0 + ? headers + : props.defaultHeaders) !== null && _ref16 !== void 0 + ? _ref16 + : "", + response, + tabState: tabState2, + }; + }); + const [tabState, setTabState] = React.useState(initialState.tabState); + const setShouldPersistHeaders = React.useCallback( + (persist) => { + if (persist) { + var _ref17; + storage == null + ? void 0 + : storage.set( + STORAGE_KEY$3, + (_ref17 = + headerEditor == null + ? void 0 + : headerEditor.getValue()) !== null && + _ref17 !== void 0 + ? _ref17 + : "" + ); + const serializedTabs = serializeTabState(tabState, true); + storage == null + ? void 0 + : storage.set(STORAGE_KEY$2, serializedTabs); + } else { + storage == null ? void 0 : storage.set(STORAGE_KEY$3, ""); + clearHeadersFromTabs(storage); + } + setShouldPersistHeadersInternal(persist); + storage == null + ? void 0 + : storage.set(PERSIST_HEADERS_STORAGE_KEY, persist.toString()); + }, + [storage, tabState, headerEditor] + ); + const lastShouldPersistHeadersProp = React.useRef(); + React.useEffect(() => { + const propValue = Boolean(props.shouldPersistHeaders); + if ( + (lastShouldPersistHeadersProp == null + ? void 0 + : lastShouldPersistHeadersProp.current) !== propValue + ) { + setShouldPersistHeaders(propValue); + lastShouldPersistHeadersProp.current = propValue; } - } - } - if (unhidden) { - for (var i$12 = 0; i$12 < unhidden.length; ++i$12) { - if (unhidden[i$12].lines.length) { - signal(unhidden[i$12], "unhide"); + }, [props.shouldPersistHeaders, setShouldPersistHeaders]); + const synchronizeActiveTabValues = useSynchronizeActiveTabValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor, + }); + const setEditorValues = useSetEditorValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor, + }); + const { onTabChange, defaultHeaders, children } = props; + const addTab = React.useCallback(() => { + setTabState((current) => { + const updatedValues = synchronizeActiveTabValues(current); + const updated = { + tabs: [ + ...updatedValues.tabs, + createTab({ + headers: defaultHeaders, + }), + ], + activeTabIndex: updatedValues.tabs.length, + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [ + defaultHeaders, + onTabChange, + setEditorValues, + storeTabs, + synchronizeActiveTabValues, + ]); + const changeTab = React.useCallback( + (index) => { + setTabState((current) => { + const updated = { + ...current, + activeTabIndex: index, + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, + [onTabChange, setEditorValues, storeTabs] + ); + const moveTab = React.useCallback( + (newOrder) => { + setTabState((current) => { + const activeTab = current.tabs[current.activeTabIndex]; + const updated = { + tabs: newOrder, + activeTabIndex: newOrder.indexOf(activeTab), + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, + [onTabChange, setEditorValues, storeTabs] + ); + const closeTab = React.useCallback( + (index) => { + setTabState((current) => { + const updated = { + tabs: current.tabs.filter((_tab, i) => index !== i), + activeTabIndex: Math.max(current.activeTabIndex - 1, 0), + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, + [onTabChange, setEditorValues, storeTabs] + ); + const updateActiveTabValues = React.useCallback( + (partialTab) => { + setTabState((current) => { + const updated = setPropertiesInActiveTab(current, partialTab); + storeTabs(updated); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, + [onTabChange, storeTabs] + ); + const { onEditOperationName } = props; + const setOperationName = React.useCallback( + (operationName) => { + if (!queryEditor) { + return; + } + queryEditor.operationName = operationName; + updateActiveTabValues({ + operationName, + }); + onEditOperationName == null + ? void 0 + : onEditOperationName(operationName); + }, + [onEditOperationName, queryEditor, updateActiveTabValues] + ); + const externalFragments = React.useMemo(() => { + const map = /* @__PURE__ */ new Map(); + if (Array.isArray(props.externalFragments)) { + for (const fragment of props.externalFragments) { + map.set(fragment.name.value, fragment); + } + } else if (typeof props.externalFragments === "string") { + graphql.visit(graphql.parse(props.externalFragments, {}), { + FragmentDefinition(fragment) { + map.set(fragment.name.value, fragment); + }, + }); + } else if (props.externalFragments) { + throw new Error( + "The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects." + ); } - } - } - if (display.wrapper.offsetHeight) { - doc.scrollTop = cm.display.scroller.scrollTop; - } - if (op.changeObjs) { - signal(cm, "changes", cm, op.changeObjs); - } - if (op.update) { - op.update.finish(); + return map; + }, [props.externalFragments]); + const validationRules = React.useMemo( + () => props.validationRules || [], + [props.validationRules] + ); + const value = React.useMemo( + () => ({ + ...tabState, + addTab, + changeTab, + moveTab, + closeTab, + updateActiveTabValues, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + setHeaderEditor, + setQueryEditor, + setResponseEditor, + setVariableEditor, + setOperationName, + initialQuery: initialState.query, + initialVariables: initialState.variables, + initialHeaders: initialState.headers, + initialResponse: initialState.response, + externalFragments, + validationRules, + shouldPersistHeaders, + setShouldPersistHeaders, + }), + [ + tabState, + addTab, + changeTab, + moveTab, + closeTab, + updateActiveTabValues, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + setOperationName, + initialState, + externalFragments, + validationRules, + shouldPersistHeaders, + setShouldPersistHeaders, + ] + ); + return /* @__PURE__ */ jsxRuntime.jsx(EditorContext.Provider, { + value, + children, + }); } - } - function runInOp(cm, f) { - if (cm.curOp) { - return f(); + const useEditorContext = createContextHook(EditorContext); + const PERSIST_HEADERS_STORAGE_KEY = "shouldPersistHeaders"; + const DEFAULT_QUERY = `# Welcome to GraphiQL +# +# GraphiQL is an in-browser tool for writing, validating, and +# testing GraphQL queries. +# +# Type queries into this side of the screen, and you will see intelligent +# typeaheads aware of the current GraphQL type schema and live syntax and +# validation errors highlighted within the text. +# +# GraphQL queries typically start with a "{" character. Lines that start +# with a # are ignored. +# +# An example GraphQL query might look like: +# +# { +# field(arg: "value") { +# subField +# } +# } +# +# Keyboard shortcuts: +# +# Prettify query: Shift-Ctrl-P (or press the prettify button) +# +# Merge fragments: Shift-Ctrl-M (or press the merge button) +# +# Run Query: Ctrl-Enter (or press the play button) +# +# Auto Complete: Ctrl-Space (or just start typing) +# + +`; + function HeaderEditor({ isHidden, ...hookArgs }) { + const { headerEditor } = useEditorContext({ + nonNull: true, + caller: HeaderEditor, + }); + const ref = useHeaderEditor(hookArgs, HeaderEditor); + React.useEffect(() => { + if (!isHidden) { + headerEditor == null ? void 0 : headerEditor.refresh(); + } + }, [headerEditor, isHidden]); + return /* @__PURE__ */ jsxRuntime.jsx("div", { + className: clsx.clsx("graphiql-editor", isHidden && "hidden"), + ref, + }); } - startOperation(cm); - try { - return f(); - } finally { - endOperation(cm); + function ImagePreview(props) { + var _a; + const [dimensions, setDimensions] = React.useState({ + width: null, + height: null, + }); + const [mime, setMime] = React.useState(null); + const ref = React.useRef(null); + const src = (_a = tokenToURL(props.token)) == null ? void 0 : _a.href; + React.useEffect(() => { + if (!ref.current) { + return; + } + if (!src) { + setDimensions({ + width: null, + height: null, + }); + setMime(null); + return; + } + fetch(src, { + method: "HEAD", + }) + .then((response) => { + setMime(response.headers.get("Content-Type")); + }) + .catch(() => { + setMime(null); + }); + }, [src]); + const dims = + dimensions.width !== null && dimensions.height !== null + ? /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + dimensions.width, + "x", + dimensions.height, + mime === null ? null : " " + mime, + ], + }) + : null; + return /* @__PURE__ */ jsxRuntime.jsxs("div", { + children: [ + /* @__PURE__ */ jsxRuntime.jsx("img", { + onLoad: () => { + var _ref18, _ref19; + var _a2, _b; + setDimensions({ + width: + (_ref18 = + (_a2 = ref.current) == null + ? void 0 + : _a2.naturalWidth) !== null && _ref18 !== void 0 + ? _ref18 + : null, + height: + (_ref19 = + (_b = ref.current) == null + ? void 0 + : _b.naturalHeight) !== null && _ref19 !== void 0 + ? _ref19 + : null, + }); + }, + ref, + src, + }), + dims, + ], + }); } - } - function operation(cm, f) { - return function () { - if (cm.curOp) { - return f.apply(cm, arguments); - } - startOperation(cm); - try { - return f.apply(cm, arguments); - } finally { - endOperation(cm); - } - }; - } - function methodOp(f) { - return function () { - if (this.curOp) { - return f.apply(this, arguments); - } - startOperation(this); - try { - return f.apply(this, arguments); - } finally { - endOperation(this); - } + ImagePreview.shouldRender = function shouldRender(token) { + const url = tokenToURL(token); + return url ? isImageURL(url) : false; }; - } - function docMethodOp(f) { - return function () { - var cm = this.cm; - if (!cm || cm.curOp) { - return f.apply(this, arguments); + function tokenToURL(token) { + if (token.type !== "string") { + return; } - startOperation(cm); + const value = token.string.slice(1).slice(0, -1).trim(); try { - return f.apply(this, arguments); - } finally { - endOperation(cm); + const { location } = window; + return new URL(value, location.protocol + "//" + location.host); + } catch { + return; } - }; - } - function startWorker(cm, time) { - if (cm.doc.highlightFrontier < cm.display.viewTo) { - cm.state.highlight.set(time, bind(highlightWorker, cm)); } - } - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.highlightFrontier >= cm.display.viewTo) { - return; + function isImageURL(url) { + return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname); } - var end = + /* @__PURE__ */new Date() + cm.options.workTime; - var context = getContextBefore(cm, doc.highlightFrontier); - var changedLines = []; - doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { - if (context.line >= cm.display.viewFrom) { - var oldStyles = line.styles; - var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; - var highlighted = highlightLine(cm, line, context, true); - if (resetState) { - context.state = resetState; - } - line.styles = highlighted.styles; - var oldCls = line.styleClasses, - newCls = highlighted.classes; - if (newCls) { - line.styleClasses = newCls; - } else if (oldCls) { - line.styleClasses = null; - } - var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) { - ischange = oldStyles[i2] != line.styles[i2]; - } - if (ischange) { - changedLines.push(context.line); - } - line.stateAfter = context.save(); - context.nextLine(); - } else { - if (line.text.length <= cm.options.maxHighlightLength) { - processLine(cm, line.text, context); + function QueryEditor(props) { + const ref = useQueryEditor(props, QueryEditor); + return /* @__PURE__ */ jsxRuntime.jsx("div", { + className: "graphiql-editor", + ref, + }); + } + function useResponseEditor( + { + responseTooltip, + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + } = {}, + caller + ) { + const { fetchError, validationErrors } = useSchemaContext({ + nonNull: true, + caller: caller || useResponseEditor, + }); + const { initialResponse, responseEditor, setResponseEditor } = + useEditorContext({ + nonNull: true, + caller: caller || useResponseEditor, + }); + const ref = React.useRef(null); + const responseTooltipRef = React.useRef(responseTooltip); + React.useEffect(() => { + responseTooltipRef.current = responseTooltip; + }, [responseTooltip]); + React.useEffect(() => { + let isActive = true; + void importCodeMirror( + [ + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js" + ) + ) + .then((n) => n.foldgutter), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js" + ) + ) + .then((n) => n.braceFold), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" + ) + ) + .then((n) => n.dialog), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js" + ) + ) + .then((n) => n.search), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js" + ) + ) + .then((n) => n.searchcursor), + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js" + ) + ) + .then((n) => n.jumpToLine), + // @ts-expect-error + Promise.resolve() + .then(() => + __webpack_require__( + /*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js" + ) + ) + .then((n) => n.sublime), + Promise.resolve().then(() => + __webpack_require__( + /*! ./mode.cjs3.js */ "../../graphiql-react/dist/mode.cjs3.js" + ) + ), + Promise.resolve().then(() => + __webpack_require__( + /*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js" + ) + ), + ], + { + useCommonAddons: false, + } + ).then((CodeMirror) => { + if (!isActive) { + return; + } + const tooltipDiv = document.createElement("div"); + CodeMirror.registerHelper( + "info", + "graphql-results", + (token, _options, _cm, pos) => { + const infoElements = []; + const ResponseTooltipComponent = responseTooltipRef.current; + if (ResponseTooltipComponent) { + infoElements.push( + /* @__PURE__ */ jsxRuntime.jsx(ResponseTooltipComponent, { + pos, + token, + }) + ); + } + if (ImagePreview.shouldRender(token)) { + infoElements.push( + /* @__PURE__ */ jsxRuntime.jsx( + ImagePreview, + { + token, + }, + "image-preview" + ) + ); + } + if (!infoElements.length) { + ReactDOM.unmountComponentAtNode(tooltipDiv); + return null; + } + ReactDOM.render(infoElements, tooltipDiv); + return tooltipDiv; + } + ); + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialResponse, + lineWrapping: true, + readOnly: true, + theme: editorTheme, + mode: "graphql-results", + foldGutter: true, + gutters: ["CodeMirror-foldgutter"], + // @ts-expect-error + info: true, + extraKeys: commonKeys, + }); + setResponseEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialResponse, setResponseEditor]); + useSynchronizeOption(responseEditor, "keyMap", keyMap); + React.useEffect(() => { + if (fetchError) { + responseEditor == null + ? void 0 + : responseEditor.setValue(fetchError); } - line.stateAfter = context.line % 5 == 0 ? context.save() : null; - context.nextLine(); - } - if (+ /* @__PURE__ */new Date() > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - doc.highlightFrontier = context.line; - doc.modeFrontier = Math.max(doc.modeFrontier, context.line); - if (changedLines.length) { - runInOp(cm, function () { - for (var i2 = 0; i2 < changedLines.length; i2++) { - regLineChange(cm, changedLines[i2], "text"); + if (validationErrors.length > 0) { + responseEditor == null + ? void 0 + : responseEditor.setValue( + toolkit.formatError(validationErrors) + ); } + }, [responseEditor, fetchError, validationErrors]); + return ref; + } + function ResponseEditor(props) { + const ref = useResponseEditor(props, ResponseEditor); + return /* @__PURE__ */ jsxRuntime.jsx("section", { + className: "result-window", + "aria-label": "Result Window", + "aria-live": "polite", + "aria-atomic": "true", + ref, }); } - } - var DisplayUpdate = function (cm, viewport, force) { - var display = cm.display; - this.viewport = viewport; - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - }; - DisplayUpdate.prototype.signal = function (emitter, type) { - if (hasHandler(emitter, type)) { - this.events.push(arguments); - } - }; - DisplayUpdate.prototype.finish = function () { - for (var i2 = 0; i2 < this.events.length; i2++) { - signal.apply(null, this.events[i2]); - } - }; - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - function selectionSnapshot(cm) { - if (cm.hasFocus()) { - return null; - } - var active = activeElt(); - if (!active || !contains(cm.display.lineDiv, active)) { - return null; - } - var result = { - activeElt: active - }; - if (window.getSelection) { - var sel = window.getSelection(); - if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { - result.anchorNode = sel.anchorNode; - result.anchorOffset = sel.anchorOffset; - result.focusNode = sel.focusNode; - result.focusOffset = sel.focusOffset; - } - } - return result; - } - function restoreSelection(snapshot) { - if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { - return; - } - snapshot.activeElt.focus(); - if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { - var sel = window.getSelection(), - range2 = document.createRange(); - range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset); - range2.collapse(false); - sel.removeAllRanges(); - sel.addRange(range2); - sel.extend(snapshot.focusNode, snapshot.focusOffset); - } - } - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, - doc = cm.doc; - if (update.editorIsHidden) { - resetView(cm); - return false; - } - if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { - return false; + function VariableEditor({ isHidden, ...hookArgs }) { + const { variableEditor } = useEditorContext({ + nonNull: true, + caller: VariableEditor, + }); + const ref = useVariableEditor(hookArgs, VariableEditor); + React.useEffect(() => { + if (variableEditor && !isHidden) { + variableEditor.refresh(); + } + }, [variableEditor, isHidden]); + return /* @__PURE__ */ jsxRuntime.jsx("div", { + className: clsx.clsx("graphiql-editor", isHidden && "hidden"), + ref, + }); } - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); - } - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) { - from = Math.max(doc.first, display.viewFrom); - } - if (display.viewTo > to && display.viewTo - to < 20) { - to = Math.min(end, display.viewTo); - } - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); - } - var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - cm.display.mover.style.top = display.viewOffset + "px"; - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { - return false; + function GraphiQLProvider({ + children, + dangerouslyAssumeSchemaIsValid, + defaultQuery, + defaultHeaders, + defaultTabs, + externalFragments, + fetcher, + getDefaultFieldNames, + headers, + inputValueDeprecation, + introspectionQueryName, + maxHistoryLength, + onEditOperationName, + onSchemaChange, + onTabChange, + onTogglePluginVisibility, + operationName, + plugins, + query, + response, + schema, + schemaDescription, + shouldPersistHeaders, + storage, + validationRules, + variables, + visiblePlugin, + }) { + return /* @__PURE__ */ jsxRuntime.jsx(StorageContextProvider, { + storage, + children: /* @__PURE__ */ jsxRuntime.jsx(HistoryContextProvider, { + maxHistoryLength, + children: /* @__PURE__ */ jsxRuntime.jsx(EditorContextProvider, { + defaultQuery, + defaultHeaders, + defaultTabs, + externalFragments, + headers, + onEditOperationName, + onTabChange, + query, + response, + shouldPersistHeaders, + validationRules, + variables, + children: /* @__PURE__ */ jsxRuntime.jsx( + SchemaContextProvider, + { + dangerouslyAssumeSchemaIsValid, + fetcher, + inputValueDeprecation, + introspectionQueryName, + onSchemaChange, + schema, + schemaDescription, + children: /* @__PURE__ */ jsxRuntime.jsx( + ExecutionContextProvider, + { + getDefaultFieldNames, + fetcher, + operationName, + children: /* @__PURE__ */ jsxRuntime.jsx( + ExplorerContextProvider, + { + children: /* @__PURE__ */ jsxRuntime.jsx( + PluginContextProvider, + { + onTogglePluginVisibility, + plugins, + visiblePlugin, + children, + } + ), + } + ), + } + ), + } + ), + }), + }), + }); } - var selSnapshot = selectionSnapshot(cm); - if (toUpdate > 4) { - display.lineDiv.style.display = "none"; - } - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) { - display.lineDiv.style.display = ""; - } - display.renderedView = display.view; - restoreSelection(selSnapshot); - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = display.sizer.style.minHeight = 0; - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - display.updateLineNumbers = null; - return true; - } - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - if (viewport && viewport.top != null) { - viewport = { - top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) - }; + function useTheme() { + const storageContext = useStorageContext(); + const [theme, setThemeInternal] = React.useState(() => { + if (!storageContext) { + return null; } - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { - break; + const stored = storageContext.get(STORAGE_KEY); + switch (stored) { + case "light": + return "light"; + case "dark": + return "dark"; + default: + if (typeof stored === "string") { + storageContext.set(STORAGE_KEY, ""); + } + return null; } - } else if (first) { - update.visible = visibleLines(cm.display, cm.doc, viewport); - } - if (!updateDisplayIfNeeded(cm, update)) { - break; - } - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.force = false; - } - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; - cm.display.reportedViewTo = cm.display.viewTo; - } - } - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.finish(); - } - } - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, - lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, - cur = container.firstChild; - function rm(node2) { - var next = node2.nextSibling; - if (webkit && mac && cm.display.currentWheelTarget == node2) { - node2.style.display = "none"; - } else { - node2.parentNode.removeChild(node2); - } - return next; + }); + React.useLayoutEffect(() => { + if (typeof window === "undefined") { + return; + } + document.body.classList.remove("graphiql-light", "graphiql-dark"); + if (theme) { + document.body.classList.add(`graphiql-${theme}`); + } + }, [theme]); + const setTheme = React.useCallback( + (newTheme) => { + storageContext == null + ? void 0 + : storageContext.set(STORAGE_KEY, newTheme || ""); + setThemeInternal(newTheme); + }, + [storageContext] + ); + return React.useMemo( + () => ({ + theme, + setTheme, + }), + [theme, setTheme] + ); } - var view = display.view, - lineN = display.viewFrom; - for (var i2 = 0; i2 < view.length; i2++) { - var lineView = view[i2]; - if (lineView.hidden) ;else if (!lineView.node || lineView.node.parentNode != container) { - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { - while (cur != lineView.node) { - cur = rm(cur); + const STORAGE_KEY = "theme"; + function useDragResize({ + defaultSizeRelation = DEFAULT_FLEX, + direction, + initiallyHidden, + onHiddenElementChange, + sizeThresholdFirst = 100, + sizeThresholdSecond = 100, + storageKey, + }) { + const storage = useStorageContext(); + const store = React.useMemo( + () => + debounce(500, (value) => { + if (storageKey) { + storage == null ? void 0 : storage.set(storageKey, value); + } + }), + [storage, storageKey] + ); + const [hiddenElement, setHiddenElement] = React.useState(() => { + const storedValue = + storageKey && + (storage == null ? void 0 : storage.get(storageKey)); + if (storedValue === HIDE_FIRST || initiallyHidden === "first") { + return "first"; + } + if (storedValue === HIDE_SECOND || initiallyHidden === "second") { + return "second"; } - var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) { - updateNumber = false; + return null; + }); + const setHiddenElementWithCallback = React.useCallback( + (element) => { + if (element !== hiddenElement) { + setHiddenElement(element); + onHiddenElementChange == null + ? void 0 + : onHiddenElementChange(element); } - updateLineForChanges(cm, lineView, lineN, dims); + }, + [hiddenElement, onHiddenElementChange] + ); + const firstRef = React.useRef(null); + const dragBarRef = React.useRef(null); + const secondRef = React.useRef(null); + const defaultFlexRef = React.useRef(`${defaultSizeRelation}`); + React.useLayoutEffect(() => { + const storedValue = + (storageKey && + (storage == null ? void 0 : storage.get(storageKey))) || + defaultFlexRef.current; + if (firstRef.current) { + firstRef.current.style.display = "flex"; + firstRef.current.style.flex = + storedValue === HIDE_FIRST || storedValue === HIDE_SECOND + ? defaultFlexRef.current + : storedValue; } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + if (secondRef.current) { + secondRef.current.style.display = "flex"; + secondRef.current.style.flex = "1"; } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) { - cur = rm(cur); - } - } - function updateGutterSpace(display) { - var width = display.gutters.offsetWidth; - display.sizer.style.marginLeft = width + "px"; - signalLater(display, "gutterChanged", display); - } - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - cm.display.heightForcer.style.top = measure.docHeight + "px"; - cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px"; - } - function alignHorizontally(cm) { - var display = cm.display, - view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { - return; - } - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, - left = comp + "px"; - for (var i2 = 0; i2 < view.length; i2++) { - if (!view[i2].hidden) { - if (cm.options.fixedGutter) { - if (view[i2].gutter) { - view[i2].gutter.style.left = left; - } - if (view[i2].gutterBackground) { - view[i2].gutterBackground.style.left = left; + if (dragBarRef.current) { + dragBarRef.current.style.display = "flex"; + } + }, [direction, storage, storageKey]); + const hide = React.useCallback((resizableElement) => { + const element = + resizableElement === "first" + ? firstRef.current + : secondRef.current; + if (!element) { + return; + } + element.style.left = "-1000px"; + element.style.position = "absolute"; + element.style.opacity = "0"; + element.style.height = "500px"; + element.style.width = "500px"; + if (firstRef.current) { + const flex = parseFloat(firstRef.current.style.flex); + if (!Number.isFinite(flex) || flex < 1) { + firstRef.current.style.flex = "1"; } } - var align = view[i2].alignable; - if (align) { - for (var j = 0; j < align.length; j++) { - align[j].style.left = left; + }, []); + const show = React.useCallback( + (resizableElement) => { + const element = + resizableElement === "first" + ? firstRef.current + : secondRef.current; + if (!element) { + return; + } + element.style.width = ""; + element.style.height = ""; + element.style.opacity = ""; + element.style.position = ""; + element.style.left = ""; + if (storage && storageKey) { + const storedValue = storage.get(storageKey); + if ( + firstRef.current && + storedValue !== HIDE_FIRST && + storedValue !== HIDE_SECOND + ) { + firstRef.current.style.flex = + storedValue || defaultFlexRef.current; + } } + }, + [storage, storageKey] + ); + React.useLayoutEffect(() => { + if (hiddenElement === "first") { + hide("first"); + } else { + show("first"); } - } - } - if (cm.options.fixedGutter) { - display.gutters.style.left = comp + gutterW + "px"; - } - } - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) { - return false; - } - var doc = cm.doc, - last = lineNumberFor(cm.options, doc.first + doc.size - 1), - display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, - padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm.display); - return true; - } - return false; - } - function getGutters(gutters, lineNumbers) { - var result = [], - sawLineNumbers = false; - for (var i2 = 0; i2 < gutters.length; i2++) { - var name = gutters[i2], - style = null; - if (typeof name != "string") { - style = name.style; - name = name.className; - } - if (name == "CodeMirror-linenumbers") { - if (!lineNumbers) { - continue; + if (hiddenElement === "second") { + hide("second"); } else { - sawLineNumbers = true; + show("second"); } - } - result.push({ - className: name, - style - }); - } - if (lineNumbers && !sawLineNumbers) { - result.push({ - className: "CodeMirror-linenumbers", - style: null - }); - } - return result; - } - function renderGutters(display) { - var gutters = display.gutters, - specs = display.gutterSpecs; - removeChildren(gutters); - display.lineGutter = null; - for (var i2 = 0; i2 < specs.length; ++i2) { - var ref = specs[i2]; - var className = ref.className; - var style = ref.style; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); - if (style) { - gElt.style.cssText = style; - } - if (className == "CodeMirror-linenumbers") { - display.lineGutter = gElt; - gElt.style.width = (display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = specs.length ? "" : "none"; - updateGutterSpace(display); - } - function updateGutters(cm) { - renderGutters(cm.display); - regChange(cm); - alignHorizontally(cm); - } - function Display(place, doc, input, options) { - var d = this; - this.input = input; - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - d.lineDiv = eltP("div", null, "CodeMirror-code"); - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - d.measure = elt("div", null, "CodeMirror-measure"); - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); - var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); - d.mover = elt("div", [lines], null, "position: relative"); - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - d.wrapper.setAttribute("translate", "no"); - if (ie && ie_version < 8) { - d.gutters.style.zIndex = -1; - d.scroller.style.paddingRight = 0; - } - if (!webkit && !(gecko && mobile)) { - d.scroller.draggable = true; - } - if (place) { - if (place.appendChild) { - place.appendChild(d.wrapper); - } else { - place(d.wrapper); - } - } - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - d.view = []; - d.renderedView = null; - d.externalMeasured = null; - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - d.alignWidgets = false; - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - d.shift = false; - d.selForContextMenu = null; - d.activeTouch = null; - d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); - renderGutters(d); - input.init(d); - } - var wheelSamples = 0, - wheelPixelsPerUnit = null; - if (ie) { - wheelPixelsPerUnit = -0.53; - } else if (gecko) { - wheelPixelsPerUnit = 15; - } else if (chrome) { - wheelPixelsPerUnit = -0.7; - } else if (safari) { - wheelPixelsPerUnit = -1 / 3; - } - function wheelEventDelta(e) { - var dx = e.wheelDeltaX, - dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { - dx = e.detail; - } - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { - dy = e.detail; - } else if (dy == null) { - dy = e.wheelDelta; - } - return { - x: dx, - y: dy - }; - } - function wheelEventPixels(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - } - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), - dx = delta.x, - dy = delta.y; - var pixelsPerUnit = wheelPixelsPerUnit; - if (e.deltaMode === 0) { - dx = e.deltaX; - dy = e.deltaY; - pixelsPerUnit = 1; - } - var display = cm.display, - scroll = display.scroller; - var canScrollX = scroll.scrollWidth > scroll.clientWidth; - var canScrollY = scroll.scrollHeight > scroll.clientHeight; - if (!(dx && canScrollX || dy && canScrollY)) { - return; - } - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { - for (var i2 = 0; i2 < view.length; i2++) { - if (view[i2].node == cur) { - cm.display.currentWheelTarget = cur; - break outer; - } + }, [hiddenElement, hide, show]); + React.useEffect(() => { + if ( + !dragBarRef.current || + !firstRef.current || + !secondRef.current + ) { + return; } - } - } - if (dx && !gecko && !presto && pixelsPerUnit != null) { - if (dy && canScrollY) { - updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); - } - setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); - if (!dy || dy && canScrollY) { - e_preventDefault(e); - } - display.wheelStartX = null; - return; - } - if (dy && pixelsPerUnit != null) { - var pixels = dy * pixelsPerUnit; - var top = cm.doc.scrollTop, - bot = top + display.wrapper.clientHeight; - if (pixels < 0) { - top = Math.max(0, top + pixels - 50); - } else { - bot = Math.min(cm.doc.height, bot + pixels + 50); - } - updateDisplaySimple(cm, { - top, - bottom: bot - }); - } - if (wheelSamples < 20 && e.deltaMode !== 0) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; - display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; - display.wheelDY = dy; - setTimeout(function () { - if (display.wheelStartX == null) { - return; + const dragBarContainer = dragBarRef.current; + const firstContainer = firstRef.current; + const wrapper = firstContainer.parentElement; + const eventProperty = + direction === "horizontal" ? "clientX" : "clientY"; + const rectProperty = direction === "horizontal" ? "left" : "top"; + const adjacentRectProperty = + direction === "horizontal" ? "right" : "bottom"; + const sizeProperty = + direction === "horizontal" ? "clientWidth" : "clientHeight"; + function handleMouseDown(downEvent) { + downEvent.preventDefault(); + const offset = + downEvent[eventProperty] - + dragBarContainer.getBoundingClientRect()[rectProperty]; + function handleMouseMove(moveEvent) { + if (moveEvent.buttons === 0) { + return handleMouseUp(); + } + const firstSize = + moveEvent[eventProperty] - + wrapper.getBoundingClientRect()[rectProperty] - + offset; + const secondSize = + wrapper.getBoundingClientRect()[adjacentRectProperty] - + moveEvent[eventProperty] + + offset - + dragBarContainer[sizeProperty]; + if (firstSize < sizeThresholdFirst) { + setHiddenElementWithCallback("first"); + store(HIDE_FIRST); + } else if (secondSize < sizeThresholdSecond) { + setHiddenElementWithCallback("second"); + store(HIDE_SECOND); + } else { + setHiddenElementWithCallback(null); + const newFlex = `${firstSize / secondSize}`; + firstContainer.style.flex = newFlex; + store(newFlex); + } } - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX; - display.wheelStartX = display.wheelStartY = null; - if (!sample) { - return; + function handleMouseUp() { + document.removeEventListener("mousemove", handleMouseMove); + document.removeEventListener("mouseup", handleMouseUp); } - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; - display.wheelDY += dy; - } - } - } - var Selection = function (ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - }; - Selection.prototype.primary = function () { - return this.ranges[this.primIndex]; - }; - Selection.prototype.equals = function (other) { - if (other == this) { - return true; - } - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { - return false; - } - for (var i2 = 0; i2 < this.ranges.length; i2++) { - var here = this.ranges[i2], - there = other.ranges[i2]; - if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { - return false; - } - } - return true; - }; - Selection.prototype.deepCopy = function () { - var out = []; - for (var i2 = 0; i2 < this.ranges.length; i2++) { - out[i2] = new Range(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head)); - } - return new Selection(out, this.primIndex); - }; - Selection.prototype.somethingSelected = function () { - for (var i2 = 0; i2 < this.ranges.length; i2++) { - if (!this.ranges[i2].empty()) { - return true; - } - } - return false; - }; - Selection.prototype.contains = function (pos, end) { - if (!end) { - end = pos; - } - for (var i2 = 0; i2 < this.ranges.length; i2++) { - var range2 = this.ranges[i2]; - if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) { - return i2; - } - } - return -1; - }; - var Range = function (anchor, head) { - this.anchor = anchor; - this.head = head; - }; - Range.prototype.from = function () { - return minPos(this.anchor, this.head); - }; - Range.prototype.to = function () { - return maxPos(this.anchor, this.head); - }; - Range.prototype.empty = function () { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - }; - function normalizeSelection(cm, ranges, primIndex) { - var mayTouch = cm && cm.options.selectionsMayTouch; - var prim = ranges[primIndex]; - ranges.sort(function (a, b) { - return cmp(a.from(), b.from()); - }); - primIndex = indexOf(ranges, prim); - for (var i2 = 1; i2 < ranges.length; i2++) { - var cur = ranges[i2], - prev = ranges[i2 - 1]; - var diff = cmp(prev.to(), cur.from()); - if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { - var from = minPos(prev.from(), cur.from()), - to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i2 <= primIndex) { - --primIndex; - } - ranges.splice(--i2, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex); - } - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - function changeEnd(change) { - if (!change.text) { - return change.to; - } - return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - } - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) { - return pos; - } - if (cmp(pos, change.to) <= 0) { - return changeEnd(change); - } - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, - ch = pos.ch; - if (pos.line == change.to.line) { - ch += changeEnd(change).ch - change.to.ch; - } - return Pos(line, ch); - } - function computeSelAfterChange(doc, change) { - var out = []; - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - var range2 = doc.sel.ranges[i2]; - out.push(new Range(adjustForChange(range2.anchor, change), adjustForChange(range2.head, change))); - } - return normalizeSelection(doc.cm, out, doc.sel.primIndex); - } - function offsetPos(pos, old, nw) { - if (pos.line == old.line) { - return Pos(nw.line, pos.ch - old.ch + nw.ch); - } else { - return Pos(nw.line + (pos.line - old.line), pos.ch); + document.addEventListener("mousemove", handleMouseMove); + document.addEventListener("mouseup", handleMouseUp); + } + dragBarContainer.addEventListener("mousedown", handleMouseDown); + function reset() { + if (firstRef.current) { + firstRef.current.style.flex = defaultFlexRef.current; + } + store(defaultFlexRef.current); + setHiddenElementWithCallback(null); + } + dragBarContainer.addEventListener("dblclick", reset); + return () => { + dragBarContainer.removeEventListener( + "mousedown", + handleMouseDown + ); + dragBarContainer.removeEventListener("dblclick", reset); + }; + }, [ + direction, + setHiddenElementWithCallback, + sizeThresholdFirst, + sizeThresholdSecond, + store, + ]); + return React.useMemo( + () => ({ + dragBarRef, + hiddenElement, + firstRef, + setHiddenElement, + secondRef, + }), + [hiddenElement, setHiddenElement] + ); } - } - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), - newPrev = oldPrev; - for (var i2 = 0; i2 < changes.length; i2++) { - var change = changes[i2]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range2 = doc.sel.ranges[i2], - inv = cmp(range2.head, range2.anchor) < 0; - out[i2] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i2] = new Range(from, from); + const DEFAULT_FLEX = 1; + const HIDE_FIRST = "hide-first"; + const HIDE_SECOND = "hide-second"; + const ToolbarButton = React.forwardRef( + ({ label, onClick, ...props }, ref) => { + const [error, setError] = React.useState(null); + const handleClick = React.useCallback( + (event) => { + try { + onClick == null ? void 0 : onClick(event); + setError(null); + } catch (err) { + setError( + err instanceof Error + ? err + : new Error(`Toolbar button click failed: ${err}`) + ); + } + }, + [onClick] + ); + return /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx( + "graphiql-toolbar-button", + error && "error", + props.className + ), + onClick: handleClick, + "aria-label": error ? error.message : label, + "aria-invalid": error ? "true" : props["aria-invalid"], + }), + }); } + ); + ToolbarButton.displayName = "ToolbarButton"; + function ExecuteButton() { + const { queryEditor, setOperationName } = useEditorContext({ + nonNull: true, + caller: ExecuteButton, + }); + const { isFetching, isSubscribed, operationName, run, stop } = + useExecutionContext({ + nonNull: true, + caller: ExecuteButton, + }); + const operations = + (queryEditor == null ? void 0 : queryEditor.operations) || []; + const hasOptions = + operations.length > 1 && typeof operationName !== "string"; + const isRunning = isFetching || isSubscribed; + const label = `${isRunning ? "Stop" : "Execute"} query (Ctrl-Enter)`; + const buttonProps = { + type: "button", + className: "graphiql-execute-button", + children: isRunning + ? /* @__PURE__ */ jsxRuntime.jsx(StopIcon, {}) + : /* @__PURE__ */ jsxRuntime.jsx(PlayIcon, {}), + "aria-label": label, + }; + return hasOptions && !isRunning + ? /* @__PURE__ */ jsxRuntime.jsxs(DropdownMenu, { + children: [ + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */ jsxRuntime.jsx( + DropdownMenu.Button, + { + ...buttonProps, + } + ), + }), + /* @__PURE__ */ jsxRuntime.jsx(DropdownMenu.Content, { + children: operations.map((operation, i) => { + const opName = operation.name + ? operation.name.value + : ``; + return /* @__PURE__ */ jsxRuntime.jsx( + DropdownMenu.Item, + { + onSelect: () => { + var _a; + const selectedOperationName = + (_a = operation.name) == null ? void 0 : _a.value; + if ( + queryEditor && + selectedOperationName && + selectedOperationName !== + queryEditor.operationName + ) { + setOperationName(selectedOperationName); + } + run(); + }, + children: opName, + }, + `${opName}-${i}` + ); + }), + }), + ], + }) + : /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */ jsxRuntime.jsx("button", { + ...buttonProps, + onClick: () => { + if (isRunning) { + stop(); + } else { + run(); + } + }, + }), + }); } - return new Selection(out, doc.sel.primIndex); - } - function loadMode(cm) { - cm.doc.mode = getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - function resetModeState(cm) { - cm.doc.iter(function (line) { - if (line.stateAfter) { - line.stateAfter = null; - } - if (line.styles) { - line.styles = null; - } + const ToolbarMenuRoot = ({ button, children, label, ...props }) => + /* @__PURE__ */ jsxRuntime.jsxs(DropdownMenu, { + ...props, + children: [ + /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */ jsxRuntime.jsx(DropdownMenu.Button, { + className: clsx.clsx( + "graphiql-un-styled graphiql-toolbar-menu", + props.className + ), + "aria-label": label, + children: button, + }), + }), + /* @__PURE__ */ jsxRuntime.jsx(DropdownMenu.Content, { + children, + }), + ], + }); + const ToolbarMenu = createComponentGroup(ToolbarMenuRoot, { + Item: DropdownMenu.Item, }); - cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) { - regChange(cm); - } - } - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - function updateDoc(doc, change, markedSpans, estimateHeight2) { - function spansFor(n) { - return markedSpans ? markedSpans[n] : null; + exports.Argument = Argument; + exports.ArgumentIcon = ArgumentIcon; + exports.Button = Button$1; + exports.ButtonGroup = ButtonGroup; + exports.ChevronDownIcon = ChevronDownIcon; + exports.ChevronLeftIcon = ChevronLeftIcon; + exports.ChevronUpIcon = ChevronUpIcon; + exports.CloseIcon = CloseIcon; + exports.CopyIcon = CopyIcon; + exports.DOC_EXPLORER_PLUGIN = DOC_EXPLORER_PLUGIN; + exports.DefaultValue = DefaultValue; + exports.DeprecatedArgumentIcon = DeprecatedArgumentIcon; + exports.DeprecatedEnumValueIcon = DeprecatedEnumValueIcon; + exports.DeprecatedFieldIcon = DeprecatedFieldIcon; + exports.DeprecationReason = DeprecationReason; + exports.Dialog = Dialog; + exports.DialogRoot = DialogRoot; + exports.Directive = Directive; + exports.DirectiveIcon = DirectiveIcon; + exports.DocExplorer = DocExplorer; + exports.DocsFilledIcon = DocsFilledIcon; + exports.DocsIcon = DocsIcon; + exports.DropdownMenu = DropdownMenu; + exports.EditorContext = EditorContext; + exports.EditorContextProvider = EditorContextProvider; + exports.EnumValueIcon = EnumValueIcon; + exports.ExecuteButton = ExecuteButton; + exports.ExecutionContext = ExecutionContext; + exports.ExecutionContextProvider = ExecutionContextProvider; + exports.ExplorerContext = ExplorerContext; + exports.ExplorerContextProvider = ExplorerContextProvider; + exports.ExplorerSection = ExplorerSection; + exports.FieldDocumentation = FieldDocumentation; + exports.FieldIcon = FieldIcon; + exports.FieldLink = FieldLink; + exports.GraphiQLProvider = GraphiQLProvider; + exports.HISTORY_PLUGIN = HISTORY_PLUGIN; + exports.HeaderEditor = HeaderEditor; + exports.History = History; + exports.HistoryContext = HistoryContext; + exports.HistoryContextProvider = HistoryContextProvider; + exports.HistoryIcon = HistoryIcon; + exports.ImagePreview = ImagePreview; + exports.ImplementsIcon = ImplementsIcon; + exports.KeyboardShortcutIcon = KeyboardShortcutIcon; + exports.MagnifyingGlassIcon = MagnifyingGlassIcon; + exports.MarkdownContent = MarkdownContent; + exports.MergeIcon = MergeIcon; + exports.PenIcon = PenIcon; + exports.PlayIcon = PlayIcon; + exports.PluginContext = PluginContext; + exports.PluginContextProvider = PluginContextProvider; + exports.PlusIcon = PlusIcon; + exports.PrettifyIcon = PrettifyIcon; + exports.QueryEditor = QueryEditor; + exports.ReloadIcon = ReloadIcon; + exports.ResponseEditor = ResponseEditor; + exports.RootTypeIcon = RootTypeIcon; + exports.SchemaContext = SchemaContext; + exports.SchemaContextProvider = SchemaContextProvider; + exports.SchemaDocumentation = SchemaDocumentation; + exports.Search = Search; + exports.SettingsIcon = SettingsIcon; + exports.Spinner = Spinner; + exports.StarFilledIcon = StarFilledIcon; + exports.StarIcon = StarIcon; + exports.StopIcon = StopIcon; + exports.StorageContext = StorageContext; + exports.StorageContextProvider = StorageContextProvider; + exports.Tab = Tab; + exports.Tabs = Tabs; + exports.ToolbarButton = ToolbarButton; + exports.ToolbarMenu = ToolbarMenu; + exports.Tooltip = Tooltip; + exports.TooltipRoot = TooltipRoot; + exports.TrashIcon = TrashIcon; + exports.TypeDocumentation = TypeDocumentation; + exports.TypeIcon = TypeIcon; + exports.TypeLink = TypeLink; + exports.UnStyledButton = UnStyledButton; + exports.VariableEditor = VariableEditor; + exports.useAutoCompleteLeafs = useAutoCompleteLeafs; + exports.useCopyQuery = useCopyQuery; + exports.useDragResize = useDragResize; + exports.useEditorContext = useEditorContext; + exports.useEditorState = useEditorState; + exports.useExecutionContext = useExecutionContext; + exports.useExplorerContext = useExplorerContext; + exports.useHeaderEditor = useHeaderEditor; + exports.useHeadersEditorState = useHeadersEditorState; + exports.useHistoryContext = useHistoryContext; + exports.useMergeQuery = useMergeQuery; + exports.useOperationsEditorState = useOperationsEditorState; + exports.useOptimisticState = useOptimisticState; + exports.usePluginContext = usePluginContext; + exports.usePrettifyEditors = usePrettifyEditors; + exports.useQueryEditor = useQueryEditor; + exports.useResponseEditor = useResponseEditor; + exports.useSchemaContext = useSchemaContext; + exports.useStorageContext = useStorageContext; + exports.useTheme = useTheme; + exports.useVariableEditor = useVariableEditor; + exports.useVariablesEditorState = useVariablesEditorState; + + /***/ + }, + + /***/ "../../graphiql-react/dist/info-addon.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/info-addon.cjs.js ***! + \***************************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + codemirror.CodeMirror.defineOption( + "info", + false, + (cm, options, old) => { + if (old && old !== codemirror.CodeMirror.Init) { + const oldOnMouseOver = cm.state.info.onMouseOver; + codemirror.CodeMirror.off( + cm.getWrapperElement(), + "mouseover", + oldOnMouseOver + ); + clearTimeout(cm.state.info.hoverTimeout); + delete cm.state.info; + } + if (options) { + const state = (cm.state.info = createState(options)); + state.onMouseOver = onMouseOver.bind(null, cm); + codemirror.CodeMirror.on( + cm.getWrapperElement(), + "mouseover", + state.onMouseOver + ); + } + } + ); + function createState(options) { + return { + options: + options instanceof Function + ? { + render: options, + } + : options === true + ? {} + : options, + }; } - function update(line, text2, spans) { - updateLine(line, text2, spans, estimateHeight2); - signalLater(line, "change", line, change); + function getHoverTime(cm) { + const { options } = cm.state.info; + return ( + (options === null || options === void 0 + ? void 0 + : options.hoverTime) || 500 + ); } - function linesFor(start, end) { - var result = []; - for (var i2 = start; i2 < end; ++i2) { - result.push(new Line(text[i2], spansFor(i2), estimateHeight2)); + function onMouseOver(cm, e) { + const state = cm.state.info; + const target = e.target || e.srcElement; + if (!(target instanceof HTMLElement)) { + return; } - return result; - } - var from = change.from, - to = change.to, - text = change.text; - var firstLine = getLine(doc, from.line), - lastLine = getLine(doc, to.line); - var lastText = lst(text), - lastSpans = spansFor(text.length - 1), - nlines = to.line - from.line; - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) { - doc.remove(from.line, nlines); - } - if (added.length) { - doc.insert(from.line, added); - } - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added$1 = linesFor(1, text.length - 1); - added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added$1); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added$2 = linesFor(1, text.length - 1); - if (nlines > 1) { - doc.remove(from.line + 1, nlines - 1); + if (target.nodeName !== "SPAN" || state.hoverTimeout !== void 0) { + return; } - doc.insert(from.line + 1, added$2); + const box = target.getBoundingClientRect(); + const onMouseMove = function () { + clearTimeout(state.hoverTimeout); + state.hoverTimeout = setTimeout(onHover, hoverTime); + }; + const onMouseOut = function () { + codemirror.CodeMirror.off(document, "mousemove", onMouseMove); + codemirror.CodeMirror.off( + cm.getWrapperElement(), + "mouseout", + onMouseOut + ); + clearTimeout(state.hoverTimeout); + state.hoverTimeout = void 0; + }; + const onHover = function () { + codemirror.CodeMirror.off(document, "mousemove", onMouseMove); + codemirror.CodeMirror.off( + cm.getWrapperElement(), + "mouseout", + onMouseOut + ); + state.hoverTimeout = void 0; + onMouseHover(cm, box); + }; + const hoverTime = getHoverTime(cm); + state.hoverTimeout = setTimeout(onHover, hoverTime); + codemirror.CodeMirror.on(document, "mousemove", onMouseMove); + codemirror.CodeMirror.on( + cm.getWrapperElement(), + "mouseout", + onMouseOut + ); } - signalLater(doc, "change", doc, change); - } - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc2, skip, sharedHist) { - if (doc2.linked) { - for (var i2 = 0; i2 < doc2.linked.length; ++i2) { - var rel = doc2.linked[i2]; - if (rel.doc == skip) { - continue; - } - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) { - continue; + function onMouseHover(cm, box) { + const pos = cm.coordsChar( + { + left: (box.left + box.right) / 2, + top: (box.top + box.bottom) / 2, + }, + "window" + ); + const state = cm.state.info; + const { options } = state; + const render = options.render || cm.getHelper(pos, "info"); + if (render) { + const token = cm.getTokenAt(pos, true); + if (token) { + const info = render(token, options, cm, pos); + if (info) { + showPopup(cm, box, info); } - f(rel.doc, shared); - propagate(rel.doc, doc2, shared); } } } - propagate(doc, null, true); - } - function attachDoc(cm, doc) { - if (doc.cm) { - throw new Error("This document is already in use."); - } - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - setDirectionClass(cm); - cm.options.direction = doc.direction; - if (!cm.options.lineWrapping) { - findMaxLine(cm); - } - cm.options.mode = doc.modeOption; - regChange(cm); - } - function setDirectionClass(cm) { - (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); - } - function directionChanged(cm) { - runInOp(cm, function () { - setDirectionClass(cm); - regChange(cm); - }); - } - function History(prev) { - this.done = []; - this.undone = []; - this.undoDepth = prev ? prev.undoDepth : Infinity; - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; - } - function historyChangeFromChange(doc, change) { - var histChange = { - from: copyPos(change.from), - to: changeEnd(change), - text: getBetween(doc, change.from, change.to) - }; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function (doc2) { - return attachLocalSpans(doc2, histChange, change.from.line, change.to.line + 1); - }, true); - return histChange; - } - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) { - array.pop(); - } else { - break; - } - } - } - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = + /* @__PURE__ */new Date(), - cur; - var last; - if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - last.to = changeEnd(change); - } else { - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - var before = lst(hist.done); - if (!before || !before.ranges) { - pushSelectionToHistory(doc.sel, hist.done); - } - cur = { - changes: [historyChangeFromChange(doc, change)], - generation: hist.generation + function showPopup(cm, box, info) { + const popup = document.createElement("div"); + popup.className = "CodeMirror-info"; + popup.append(info); + document.body.append(popup); + const popupBox = popup.getBoundingClientRect(); + const popupStyle = window.getComputedStyle(popup); + const popupWidth = + popupBox.right - + popupBox.left + + parseFloat(popupStyle.marginLeft) + + parseFloat(popupStyle.marginRight); + const popupHeight = + popupBox.bottom - + popupBox.top + + parseFloat(popupStyle.marginTop) + + parseFloat(popupStyle.marginBottom); + let topPos = box.bottom; + if ( + popupHeight > window.innerHeight - box.bottom - 15 && + box.top > window.innerHeight - box.bottom + ) { + topPos = box.top - popupHeight; + } + if (topPos < 0) { + topPos = box.bottom; + } + let leftPos = Math.max(0, window.innerWidth - popupWidth - 15); + if (leftPos > box.left) { + leftPos = box.left; + } + popup.style.opacity = "1"; + popup.style.top = topPos + "px"; + popup.style.left = leftPos + "px"; + let popupTimeout; + const onMouseOverPopup = function () { + clearTimeout(popupTimeout); + }; + const onMouseOut = function () { + clearTimeout(popupTimeout); + popupTimeout = setTimeout(hidePopup, 200); + }; + const hidePopup = function () { + codemirror.CodeMirror.off(popup, "mouseover", onMouseOverPopup); + codemirror.CodeMirror.off(popup, "mouseout", onMouseOut); + codemirror.CodeMirror.off( + cm.getWrapperElement(), + "mouseout", + onMouseOut + ); + if (popup.style.opacity) { + popup.style.opacity = "0"; + setTimeout(() => { + if (popup.parentNode) { + popup.remove(); + } + }, 600); + } else if (popup.parentNode) { + popup.remove(); + } }; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) { - hist.done.shift(); + codemirror.CodeMirror.on(popup, "mouseover", onMouseOverPopup); + codemirror.CodeMirror.on(popup, "mouseout", onMouseOut); + codemirror.CodeMirror.on( + cm.getWrapperElement(), + "mouseout", + onMouseOut + ); + } + + /***/ + }, + + /***/ "../../graphiql-react/dist/info.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/info.cjs.js ***! + \*********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const SchemaReference = __webpack_require__( + /*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js" + ); + __webpack_require__( + /*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js" + ); + codemirror.CodeMirror.registerHelper( + "info", + "graphql", + (token, options) => { + var _a; + if (!options.schema || !token.state) { + return; + } + const { kind, step } = token.state; + const typeInfo = SchemaReference.getTypeInfo( + options.schema, + token.state + ); + if ( + (kind === "Field" && step === 0 && typeInfo.fieldDef) || + (kind === "AliasedField" && step === 2 && typeInfo.fieldDef) || + (kind === "ObjectField" && step === 0 && typeInfo.fieldDef) + ) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderField(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.fieldDef); + return into; + } + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderDirective(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.directiveDef); + return into; + } + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderArg(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.argDef); + return into; + } + if ( + kind === "EnumValue" && + ((_a = typeInfo.enumValue) === null || _a === void 0 + ? void 0 + : _a.description) + ) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderEnumValue(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.enumValue); + return into; + } + if ( + kind === "NamedType" && + typeInfo.type && + typeInfo.type.description + ) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderType(header, typeInfo, options, typeInfo.type); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.type); + return into; } } + ); + function renderField(into, typeInfo, options) { + renderQualifiedField(into, typeInfo, options); + renderTypeAnnotation(into, typeInfo, options, typeInfo.type); } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - if (!last) { - signal(doc, "historyAdded"); + function renderQualifiedField(into, typeInfo, options) { + var _a; + const fieldName = + ((_a = typeInfo.fieldDef) === null || _a === void 0 + ? void 0 + : _a.name) || ""; + text( + into, + fieldName, + "field-name", + options, + SchemaReference.getFieldReference(typeInfo) + ); } - } - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && /* @__PURE__ */new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, - origin = options && options.origin; - if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) { - hist.done[hist.done.length - 1] = sel; - } else { - pushSelectionToHistory(sel, hist.done); + function renderDirective(into, typeInfo, options) { + var _a; + const name = + "@" + + (((_a = typeInfo.directiveDef) === null || _a === void 0 + ? void 0 + : _a.name) || ""); + text( + into, + name, + "directive-name", + options, + SchemaReference.getDirectiveReference(typeInfo) + ); } - hist.lastSelTime = + /* @__PURE__ */new Date(); - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) { - clearSelectionEvents(hist.undone); + function renderArg(into, typeInfo, options) { + var _a; + const name = + ((_a = typeInfo.argDef) === null || _a === void 0 + ? void 0 + : _a.name) || ""; + text( + into, + name, + "arg-name", + options, + SchemaReference.getArgumentReference(typeInfo) + ); + renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); } - } - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) { - dest.push(sel); + function renderEnumValue(into, typeInfo, options) { + var _a; + const name = + ((_a = typeInfo.enumValue) === null || _a === void 0 + ? void 0 + : _a.name) || ""; + renderType(into, typeInfo, options, typeInfo.inputType); + text(into, "."); + text( + into, + name, + "enum-value", + options, + SchemaReference.getEnumValueReference(typeInfo) + ); } - } - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], - n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { - if (line.markedSpans) { - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + function renderTypeAnnotation(into, typeInfo, options, t) { + const typeSpan = document.createElement("span"); + typeSpan.className = "type-name-pill"; + if (t instanceof graphql.GraphQLNonNull) { + renderType(typeSpan, typeInfo, options, t.ofType); + text(typeSpan, "!"); + } else if (t instanceof graphql.GraphQLList) { + text(typeSpan, "["); + renderType(typeSpan, typeInfo, options, t.ofType); + text(typeSpan, "]"); + } else { + text( + typeSpan, + (t === null || t === void 0 ? void 0 : t.name) || "", + "type-name", + options, + SchemaReference.getTypeReference(typeInfo, t) + ); } - ++n; - }); - } - function removeClearedSpans(spans) { - if (!spans) { - return null; + into.append(typeSpan); } - var out; - for (var i2 = 0; i2 < spans.length; ++i2) { - if (spans[i2].marker.explicitlyCleared) { - if (!out) { - out = spans.slice(0, i2); - } - } else if (out) { - out.push(spans[i2]); + function renderType(into, typeInfo, options, t) { + if (t instanceof graphql.GraphQLNonNull) { + renderType(into, typeInfo, options, t.ofType); + text(into, "!"); + } else if (t instanceof graphql.GraphQLList) { + text(into, "["); + renderType(into, typeInfo, options, t.ofType); + text(into, "]"); + } else { + text( + into, + (t === null || t === void 0 ? void 0 : t.name) || "", + "type-name", + options, + SchemaReference.getTypeReference(typeInfo, t) + ); } } - return !out ? spans : out.length ? out : null; - } - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) { - return null; - } - var nw = []; - for (var i2 = 0; i2 < change.text.length; ++i2) { - nw.push(removeClearedSpans(found[i2])); - } - return nw; - } - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) { - return stretched; - } - if (!stretched) { - return old; + function renderDescription(into, options, def) { + const { description } = def; + if (description) { + const descriptionDiv = document.createElement("div"); + descriptionDiv.className = "info-description"; + if (options.renderDescription) { + descriptionDiv.innerHTML = options.renderDescription(description); + } else { + descriptionDiv.append(document.createTextNode(description)); + } + into.append(descriptionDiv); + } + renderDeprecation(into, options, def); + } + function renderDeprecation(into, options, def) { + const reason = def.deprecationReason; + if (reason) { + const deprecationDiv = document.createElement("div"); + deprecationDiv.className = "info-deprecation"; + into.append(deprecationDiv); + const label = document.createElement("span"); + label.className = "info-deprecation-label"; + label.append(document.createTextNode("Deprecated")); + deprecationDiv.append(label); + const reasonDiv = document.createElement("div"); + reasonDiv.className = "info-deprecation-reason"; + if (options.renderDescription) { + reasonDiv.innerHTML = options.renderDescription(reason); + } else { + reasonDiv.append(document.createTextNode(reason)); + } + deprecationDiv.append(reasonDiv); + } } - for (var i2 = 0; i2 < old.length; ++i2) { - var oldCur = old[i2], - stretchCur = stretched[i2]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) { - if (oldCur[k].marker == span.marker) { - continue spans; - } - } - oldCur.push(span); + function text( + into, + content, + className = "", + options = { + onClick: null, + }, + ref = null + ) { + if (className) { + const { onClick } = options; + let node; + if (onClick) { + node = document.createElement("a"); + node.href = "javascript:void 0"; + node.addEventListener("click", (e) => { + e.preventDefault(); + onClick(ref, e); + }); + } else { + node = document.createElement("span"); } - } else if (stretchCur) { - old[i2] = stretchCur; + node.className = className; + node.append(document.createTextNode(content)); + into.append(node); + } else { + into.append(document.createTextNode(content)); } } - return old; - } - function copyHistoryArray(events, newGroup, instantiateSel) { - var copy = []; - for (var i2 = 0; i2 < events.length; ++i2) { - var event = events[i2]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, - newChanges = []; - copy.push({ - changes: newChanges - }); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], - m = void 0; - newChanges.push({ - from: change.from, - to: change.to, - text: change.text - }); - if (newGroup) { - for (var prop2 in change) { - if (m = prop2.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop2] = change[prop2]; - delete change[prop2]; + + /***/ + }, + + /***/ "../../graphiql-react/dist/javascript.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/javascript.cjs.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); } } } } } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - return copy; - } - function extendRange(range2, head, other, extend) { - if (extend) { - var anchor = range2.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != cmp(other, anchor) < 0) { - anchor = head; - head = other; - } else if (posBefore != cmp(head, other) < 0) { - head = other; - } - } - return new Range(anchor, head); - } else { - return new Range(other || head, head); - } - } - function extendSelection(doc, head, other, options, extend) { - if (extend == null) { - extend = doc.cm && (doc.cm.display.shift || doc.extend); - } - setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); - } - function extendSelections(doc, heads, options) { - var out = []; - var extend = doc.cm && (doc.cm.display.shift || doc.extend); - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - out[i2] = extendRange(doc.sel.ranges[i2], heads[i2], null, extend); - } - var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - function replaceOneSelection(doc, i2, range2, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i2] = range2; - setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); - } - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - function filterSelectionChange(doc, sel, options) { - var obj = { - ranges: sel.ranges, - update: function (ranges) { - this.ranges = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - this.ranges[i2] = new Range(clipPos(doc, ranges[i2].anchor), clipPos(doc, ranges[i2].head)); - } - }, - origin: options && options.origin + var javascript$2 = { + exports: {}, }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) { - signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - } - if (obj.ranges != sel.ranges) { - return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1); - } else { - return sel; - } - } - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, - last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); - } - } - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { - sel = filterSelectionChange(doc, sel, options); - } - var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") { - ensureCursorVisible(doc.cm); - } - } - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) { - return; - } - doc.sel = sel; - if (doc.cm) { - doc.cm.curOp.updateInput = 1; - doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); - } - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i2 = 0; i2 < sel.ranges.length; i2++) { - var range2 = sel.ranges[i2]; - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i2]; - var newAnchor = skipAtomic(doc, range2.anchor, old && old.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range2.head, old && old.head, bias, mayClear); - if (out || newAnchor != range2.anchor || newHead != range2.head) { - if (!out) { - out = sel.ranges.slice(0, i2); - } - out[i2] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel; - } - function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { - var line = getLine(doc, pos.line); - if (line.markedSpans) { - for (var i2 = 0; i2 < line.markedSpans.length; ++i2) { - var sp = line.markedSpans[i2], - m = sp.marker; - var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; - var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight; - if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) { - break; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + CodeMirror.defineMode( + "javascript", + function (config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var trackScope = parserConfig.trackScope !== false; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + var keywords = (function () { + function kw(type2) { + return { + type: type2, + style: "keyword", + }; + } + var A = kw("keyword a"), + B = kw("keyword b"), + C = kw("keyword c"), + D = kw("keyword d"); + var operator = kw("operator"), + atom = { + type: "atom", + style: "atom", + }; + return { + if: kw("if"), + while: A, + with: A, + else: B, + do: B, + try: B, + finally: B, + return: D, + break: D, + continue: D, + new: kw("new"), + delete: C, + void: C, + throw: C, + debugger: kw("debugger"), + var: kw("var"), + const: kw("var"), + let: kw("var"), + function: kw("function"), + catch: kw("catch"), + for: kw("for"), + switch: kw("switch"), + case: kw("case"), + default: kw("default"), + in: operator, + typeof: operator, + instanceof: operator, + true: atom, + false: atom, + null: atom, + undefined: atom, + NaN: atom, + Infinity: atom, + this: kw("this"), + class: kw("class"), + super: kw("atom"), + yield: C, + export: kw("export"), + import: kw("import"), + extends: C, + await: C, + }; + })(); + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = + /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + function readRegexp(stream) { + var escaped = false, + next, + inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + var type, content; + function ret(tp, style, cont2) { + type = tp; + content = cont2; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if ( + ch == "." && + stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/) + ) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if ( + ch == "0" && + stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/) + ) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match( + /^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/ + ); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#" && stream.peek() == "!") { + stream.skipToEnd(); + return ret("meta", "meta"); + } else if (ch == "#" && stream.eatWhile(wordRE)) { + return ret("variable", "property"); + } else if ( + (ch == "<" && stream.match("!--")) || + (ch == "-" && + stream.match("->") && + !/\S/.test(stream.string.slice(0, stream.start))) + ) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (isOperatorChar.test(ch)) { + if ( + ch != ">" || + !state.lexical || + state.lexical.type != ">" + ) { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("="); + } else if (/[<>*+\-|&?]/.test(ch)) { + stream.eat(ch); + if (ch == ">") stream.eat(ch); + } + } + if (ch == "?" && stream.eat(".")) return ret("."); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(); + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word]; + return ret(kw.type, kw.style, word); + } + if ( + word == "async" && + stream.match( + /^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, + false + ) + ) + return ret("async", "keyword", word); + } + return ret("variable", "variable", word); + } + } + function tokenString(quote) { + return function (stream, state) { + var escaped = false, + next; + if ( + jsonldMode && + stream.peek() == "@" && + stream.match(isJsonldKeyword) + ) { + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, + ch; + while ((ch = stream.next())) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = ch == "*"; + } + return ret("comment", "comment"); + } + function tokenQuasi(stream, state) { + var escaped = false, + next; + while ((next = stream.next()) != null) { + if ( + !escaped && + (next == "`" || (next == "$" && stream.eat("{"))) + ) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + var brackets = "([{}])"; + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + if (isTS) { + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec( + stream.string.slice(stream.start, arrow) + ); + if (m) arrow = m.index; + } + var depth = 0, + sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { + ++pos; + break; + } + if (--depth == 0) { + if (ch == "(") sawSomething = true; + break; + } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (; ; --pos) { + if (pos == 0) return; + var next = stream.string.charAt(pos - 1); + if ( + next == ch && + stream.string.charAt(pos - 2) != "\\" + ) { + pos--; + break; + } + } + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + var atomicTypes = { + atom: true, + number: true, + variable: true, + string: true, + regexp: true, + this: true, + import: true, + "jsonld-keyword": true, + }; + function JSLexical(indented, column, type2, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type2; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + function inScope(state, varname) { + if (!trackScope) return false; + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx2 = state.context; cx2; cx2 = cx2.prev) { + for (var v = cx2.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + function parseJS(state, style, type2, content2, stream) { + var cc = state.cc; + cx.state = state; + cx.stream = stream; + (cx.marked = null), (cx.cc = cc); + cx.style = style; + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + while (true) { + var combinator = cc.length + ? cc.pop() + : jsonMode + ? expression + : statement; + if (combinator(type2, content2)) { + while (cc.length && cc[cc.length - 1].lex) cc.pop()(); + if (cx.marked) return cx.marked; + if (type2 == "variable" && inScope(state, content2)) + return "variable-2"; + return style; + } + } + } + var cx = { + state: null, + column: null, + marked: null, + cc: null, + }; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) + cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) + if (v.name == name) return true; + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (!trackScope) return; + if (state.context) { + if ( + state.lexical.info == "var" && + state.context && + state.context.block + ) { + var newContext = registerVarScoped( + varname, + state.context + ); + if (newContext != null) { + state.context = newContext; + return; + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars); + return; + } + } + if ( + parserConfig.globalVars && + !inList(varname, state.globalVars) + ) + state.globalVars = new Var(varname, state.globalVars); + } + function registerVarScoped(varname, context) { + if (!context) { + return null; + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev); + if (!inner) return null; + if (inner == context.prev) return context; + return new Context(inner, context.vars, true); + } else if (inList(varname, context.vars)) { + return context; } else { - --i2; - continue; + return new Context( + context.prev, + new Var(varname, context.vars), + false + ); + } + } + function isModifier(name) { + return ( + name == "public" || + name == "private" || + name == "protected" || + name == "abstract" || + name == "readonly" + ); + } + function Context(prev, vars, block2) { + this.prev = prev; + this.vars = vars; + this.block = block2; + } + function Var(name, next) { + this.name = name; + this.next = next; + } + var defaultVars = new Var("this", new Var("arguments", null)); + function pushcontext() { + cx.state.context = new Context( + cx.state.context, + cx.state.localVars, + false + ); + cx.state.localVars = defaultVars; + } + function pushblockcontext() { + cx.state.context = new Context( + cx.state.context, + cx.state.localVars, + true + ); + cx.state.localVars = null; + } + pushcontext.lex = pushblockcontext.lex = true; + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + popcontext.lex = true; + function pushlex(type2, info) { + var result = function () { + var state = cx.state, + indent = state.indented; + if (state.lexical.type == "stat") + indent = state.lexical.indented; + else + for ( + var outer = state.lexical; + outer && outer.type == ")" && outer.align; + outer = outer.prev + ) + indent = outer.indented; + state.lexical = new JSLexical( + indent, + cx.stream.column(), + type2, + null, + state.lexical, + info + ); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + function expect(wanted) { + function exp(type2) { + if (type2 == wanted) return cont(); + else if ( + wanted == ";" || + type2 == "}" || + type2 == ")" || + type2 == "]" + ) + return pass(); + else return cont(exp); + } + return exp; + } + function statement(type2, value) { + if (type2 == "var") + return cont( + pushlex("vardef", value), + vardef, + expect(";"), + poplex + ); + if (type2 == "keyword a") + return cont(pushlex("form"), parenExpr, statement, poplex); + if (type2 == "keyword b") + return cont(pushlex("form"), statement, poplex); + if (type2 == "keyword d") + return cx.stream.match(/^\s*$/, false) + ? cont() + : cont( + pushlex("stat"), + maybeexpression, + expect(";"), + poplex + ); + if (type2 == "debugger") return cont(expect(";")); + if (type2 == "{") + return cont( + pushlex("}"), + pushblockcontext, + block, + poplex, + popcontext + ); + if (type2 == ";") return cont(); + if (type2 == "if") { + if ( + cx.state.lexical.info == "else" && + cx.state.cc[cx.state.cc.length - 1] == poplex + ) + cx.state.cc.pop()(); + return cont( + pushlex("form"), + parenExpr, + statement, + poplex, + maybeelse + ); + } + if (type2 == "function") return cont(functiondef); + if (type2 == "for") + return cont( + pushlex("form"), + pushblockcontext, + forspec, + statement, + popcontext, + poplex + ); + if (type2 == "class" || (isTS && value == "interface")) { + cx.marked = "keyword"; + return cont( + pushlex("form", type2 == "class" ? type2 : value), + className, + poplex + ); + } + if (type2 == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword"; + return cont(statement); + } else if ( + isTS && + (value == "module" || + value == "enum" || + value == "type") && + cx.stream.match(/^\s*\w/, false) + ) { + cx.marked = "keyword"; + if (value == "enum") return cont(enumdef); + else if (value == "type") + return cont( + typename, + expect("operator"), + typeexpr, + expect(";") + ); + else + return cont( + pushlex("form"), + pattern, + expect("{"), + pushlex("}"), + block, + poplex, + poplex + ); + } else if (isTS && value == "namespace") { + cx.marked = "keyword"; + return cont( + pushlex("form"), + expression, + statement, + poplex + ); + } else if (isTS && value == "abstract") { + cx.marked = "keyword"; + return cont(statement); + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type2 == "switch") + return cont( + pushlex("form"), + parenExpr, + expect("{"), + pushlex("}", "switch"), + pushblockcontext, + block, + poplex, + poplex, + popcontext + ); + if (type2 == "case") return cont(expression, expect(":")); + if (type2 == "default") return cont(expect(":")); + if (type2 == "catch") + return cont( + pushlex("form"), + pushcontext, + maybeCatchBinding, + statement, + poplex, + popcontext + ); + if (type2 == "export") + return cont(pushlex("stat"), afterExport, poplex); + if (type2 == "import") + return cont(pushlex("stat"), afterImport, poplex); + if (type2 == "async") return cont(statement); + if (value == "@") return cont(expression, statement); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type2) { + if (type2 == "(") return cont(funarg, expect(")")); + } + function expression(type2, value) { + return expressionInner(type2, value, false); + } + function expressionNoComma(type2, value) { + return expressionInner(type2, value, true); + } + function parenExpr(type2) { + if (type2 != "(") return pass(); + return cont( + pushlex(")"), + maybeexpression, + expect(")"), + poplex + ); + } + function expressionInner(type2, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type2 == "(") + return cont( + pushcontext, + pushlex(")"), + commasep(funarg, ")"), + poplex, + expect("=>"), + body, + popcontext + ); + else if (type2 == "variable") + return pass( + pushcontext, + pattern, + expect("=>"), + body, + popcontext + ); + } + var maybeop = noComma + ? maybeoperatorNoComma + : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); + if (type2 == "function") return cont(functiondef, maybeop); + if (type2 == "class" || (isTS && value == "interface")) { + cx.marked = "keyword"; + return cont(pushlex("form"), classExpression, poplex); + } + if (type2 == "keyword c" || type2 == "async") + return cont(noComma ? expressionNoComma : expression); + if (type2 == "(") + return cont( + pushlex(")"), + maybeexpression, + expect(")"), + poplex, + maybeop + ); + if (type2 == "operator" || type2 == "spread") + return cont(noComma ? expressionNoComma : expression); + if (type2 == "[") + return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type2 == "{") + return contCommasep(objprop, "}", null, maybeop); + if (type2 == "quasi") return pass(quasi, maybeop); + if (type2 == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type2) { + if (type2.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + function maybeoperatorComma(type2, value) { + if (type2 == ",") return cont(maybeexpression); + return maybeoperatorNoComma(type2, value, false); + } + function maybeoperatorNoComma(type2, value, noComma) { + var me = + noComma == false + ? maybeoperatorComma + : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type2 == "=>") + return cont( + pushcontext, + noComma ? arrowBodyNoComma : arrowBody, + popcontext + ); + if (type2 == "operator") { + if (/\+\+|--/.test(value) || (isTS && value == "!")) + return cont(me); + if ( + isTS && + value == "<" && + cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false) + ) + return cont( + pushlex(">"), + commasep(typeexpr, ">"), + poplex, + me + ); + if (value == "?") + return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type2 == "quasi") { + return pass(quasi, me); + } + if (type2 == ";") return; + if (type2 == "(") + return contCommasep(expressionNoComma, ")", "call", me); + if (type2 == ".") return cont(property, me); + if (type2 == "[") + return cont( + pushlex("]"), + maybeexpression, + expect("]"), + poplex, + me + ); + if (isTS && value == "as") { + cx.marked = "keyword"; + return cont(typeexpr, me); + } + if (type2 == "regexp") { + cx.state.lastType = cx.marked = "operator"; + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); + return cont(expr); + } + } + function quasi(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(maybeexpression, continueQuasi); + } + function continueQuasi(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expression); + } + function arrowBodyNoComma(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function (type2) { + if (type2 == ".") + return cont(noComma ? targetNoComma : target); + else if (type2 == "variable" && isTS) + return cont( + maybeTypeArgs, + noComma ? maybeoperatorNoComma : maybeoperatorComma + ); + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorComma); + } + } + function targetNoComma(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorNoComma); + } + } + function maybelabel(type2) { + if (type2 == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type2) { + if (type2 == "variable") { + cx.marked = "property"; + return cont(); + } + } + function objprop(type2, value) { + if (type2 == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") + return cont(getterSetter); + var m; + if ( + isTS && + cx.state.fatArrowAt == cx.stream.start && + (m = cx.stream.match(/^\s*:\s*/, false)) + ) + cx.state.fatArrowAt = cx.stream.pos + m[0].length; + return cont(afterprop); + } else if (type2 == "number" || type2 == "string") { + cx.marked = jsonldMode + ? "property" + : cx.style + " property"; + return cont(afterprop); + } else if (type2 == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type2 == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == ":") { + return pass(afterprop); + } + } + function getterSetter(type2) { + if (type2 != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type2) { + if (type2 == ":") return cont(expressionNoComma); + if (type2 == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type2, value) { + if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function (type3, value2) { + if (type3 == end || value2 == end) return pass(); + return pass(what); + }, proceed); + } + if (type2 == end || value == end) return cont(); + if (sep && sep.indexOf(";") > -1) return pass(what); + return cont(expect(end)); + } + return function (type2, value) { + if (type2 == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type2) { + if (type2 == "}") return cont(); + return pass(statement, block); + } + function maybetype(type2, value) { + if (isTS) { + if (type2 == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function maybetypeOrIn(type2, value) { + if (isTS && (type2 == ":" || value == "in")) + return cont(typeexpr); + } + function mayberettype(type2) { + if (isTS && type2 == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) + return cont(expression, isKW, typeexpr); + else return cont(typeexpr); + } + } + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword"; + return cont(); + } + } + function typeexpr(type2, value) { + if ( + value == "keyof" || + value == "typeof" || + value == "infer" || + value == "readonly" + ) { + cx.marked = "keyword"; + return cont( + value == "typeof" ? expressionNoComma : typeexpr + ); + } + if (type2 == "variable" || value == "void") { + cx.marked = "type"; + return cont(afterType); + } + if (value == "|" || value == "&") return cont(typeexpr); + if (type2 == "string" || type2 == "number" || type2 == "atom") + return cont(afterType); + if (type2 == "[") + return cont( + pushlex("]"), + commasep(typeexpr, "]", ","), + poplex, + afterType + ); + if (type2 == "{") + return cont(pushlex("}"), typeprops, poplex, afterType); + if (type2 == "(") + return cont( + commasep(typearg, ")"), + maybeReturnType, + afterType + ); + if (type2 == "<") + return cont(commasep(typeexpr, ">"), typeexpr); + if (type2 == "quasi") { + return pass(quasiType, afterType); + } + } + function maybeReturnType(type2) { + if (type2 == "=>") return cont(typeexpr); + } + function typeprops(type2) { + if (type2.match(/[\}\)\]]/)) return cont(); + if (type2 == "," || type2 == ";") return cont(typeprops); + return pass(typeprop, typeprops); + } + function typeprop(type2, value) { + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(typeprop); + } else if ( + value == "?" || + type2 == "number" || + type2 == "string" + ) { + return cont(typeprop); + } else if (type2 == ":") { + return cont(typeexpr); + } else if (type2 == "[") { + return cont( + expect("variable"), + maybetypeOrIn, + expect("]"), + typeprop + ); + } else if (type2 == "(") { + return pass(functiondecl, typeprop); + } else if (!type2.match(/[;\}\)\],]/)) { + return cont(); + } + } + function quasiType(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") + return cont(quasiType); + return cont(typeexpr, continueQuasiType); + } + function continueQuasiType(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasiType); + } + } + function typearg(type2, value) { + if ( + (type2 == "variable" && + cx.stream.match(/^\s*[?:]/, false)) || + value == "?" + ) + return cont(typearg); + if (type2 == ":") return cont(typeexpr); + if (type2 == "spread") return cont(typearg); + return pass(typeexpr); + } + function afterType(type2, value) { + if (value == "<") + return cont( + pushlex(">"), + commasep(typeexpr, ">"), + poplex, + afterType + ); + if (value == "|" || type2 == "." || value == "&") + return cont(typeexpr); + if (type2 == "[") + return cont(typeexpr, expect("]"), afterType); + if (value == "extends" || value == "implements") { + cx.marked = "keyword"; + return cont(typeexpr); + } + if (value == "?") + return cont(typeexpr, expect(":"), typeexpr); + } + function maybeTypeArgs(_, value) { + if (value == "<") + return cont( + pushlex(">"), + commasep(typeexpr, ">"), + poplex, + afterType + ); + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault); + } + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr); + } + function vardef(_, value) { + if (value == "enum") { + cx.marked = "keyword"; + return cont(enumdef); + } + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type2, value) { + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(pattern); + } + if (type2 == "variable") { + register(value); + return cont(); + } + if (type2 == "spread") return cont(pattern); + if (type2 == "[") return contCommasep(eltpattern, "]"); + if (type2 == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type2, value) { + if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type2 == "variable") cx.marked = "property"; + if (type2 == "spread") return cont(pattern); + if (type2 == "}") return pass(); + if (type2 == "[") + return cont( + expression, + expect("]"), + expect(":"), + proppattern + ); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign); + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type2) { + if (type2 == ",") return cont(vardef); + } + function maybeelse(type2, value) { + if (type2 == "keyword b" && value == "else") + return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type2, value) { + if (value == "await") return cont(forspec); + if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type2) { + if (type2 == "var") return cont(vardef, forspec2); + if (type2 == "variable") return cont(forspec2); + return pass(forspec2); + } + function forspec2(type2, value) { + if (type2 == ")") return cont(); + if (type2 == ";") return cont(forspec2); + if (value == "in" || value == "of") { + cx.marked = "keyword"; + return cont(expression, forspec2); + } + return pass(expression, forspec2); + } + function functiondef(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondef); + } + if (type2 == "variable") { + register(value); + return cont(functiondef); + } + if (type2 == "(") + return cont( + pushcontext, + pushlex(")"), + commasep(funarg, ")"), + poplex, + mayberettype, + statement, + popcontext + ); + if (isTS && value == "<") + return cont( + pushlex(">"), + commasep(typeparam, ">"), + poplex, + functiondef + ); + } + function functiondecl(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondecl); + } + if (type2 == "variable") { + register(value); + return cont(functiondecl); + } + if (type2 == "(") + return cont( + pushcontext, + pushlex(")"), + commasep(funarg, ")"), + poplex, + mayberettype, + popcontext + ); + if (isTS && value == "<") + return cont( + pushlex(">"), + commasep(typeparam, ">"), + poplex, + functiondecl + ); + } + function typename(type2, value) { + if (type2 == "keyword" || type2 == "variable") { + cx.marked = "type"; + return cont(typename); + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex); + } + } + function funarg(type2, value) { + if (value == "@") cont(expression, funarg); + if (type2 == "spread") return cont(funarg); + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(funarg); + } + if (isTS && type2 == "this") + return cont(maybetype, maybeAssign); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type2, value) { + if (type2 == "variable") return className(type2, value); + return classNameAfter(type2, value); + } + function className(type2, value) { + if (type2 == "variable") { + register(value); + return cont(classNameAfter); + } + } + function classNameAfter(type2, value) { + if (value == "<") + return cont( + pushlex(">"), + commasep(typeparam, ">"), + poplex, + classNameAfter + ); + if ( + value == "extends" || + value == "implements" || + (isTS && type2 == ",") + ) { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type2 == "{") + return cont(pushlex("}"), classBody, poplex); + } + function classBody(type2, value) { + if ( + type2 == "async" || + (type2 == "variable" && + (value == "static" || + value == "get" || + value == "set" || + (isTS && isModifier(value))) && + cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) + ) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(classfield, classBody); + } + if (type2 == "number" || type2 == "string") + return cont(classfield, classBody); + if (type2 == "[") + return cont( + expression, + maybetype, + expect("]"), + classfield, + classBody + ); + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type2 == "(") + return pass(functiondecl, classBody); + if (type2 == ";" || type2 == ",") return cont(classBody); + if (type2 == "}") return cont(); + if (value == "@") return cont(expression, classBody); + } + function classfield(type2, value) { + if (value == "!") return cont(classfield); + if (value == "?") return cont(classfield); + if (type2 == ":") return cont(typeexpr, maybeAssign); + if (value == "=") return cont(expressionNoComma); + var context = cx.state.lexical.prev, + isInterface = context && context.info == "interface"; + return pass(isInterface ? functiondecl : functiondef); + } + function afterExport(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(maybeFrom, expect(";")); + } + if (value == "default") { + cx.marked = "keyword"; + return cont(expression, expect(";")); + } + if (type2 == "{") + return cont( + commasep(exportField, "}"), + maybeFrom, + expect(";") + ); + return pass(statement); + } + function exportField(type2, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(expect("variable")); + } + if (type2 == "variable") + return pass(expressionNoComma, exportField); + } + function afterImport(type2) { + if (type2 == "string") return cont(); + if (type2 == "(") return pass(expression); + if (type2 == ".") return pass(maybeoperatorComma); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type2, value) { + if (type2 == "{") return contCommasep(importSpec, "}"); + if (type2 == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type2) { + if (type2 == ",") return cont(importSpec, maybeMoreImports); + } + function maybeAs(_type, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(importSpec); + } + } + function maybeFrom(_type, value) { + if (value == "from") { + cx.marked = "keyword"; + return cont(expression); + } + } + function arrayLiteral(type2) { + if (type2 == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass( + pushlex("form"), + pattern, + expect("{"), + pushlex("}"), + commasep(enummember, "}"), + poplex, + poplex + ); + } + function enummember() { + return pass(pattern, maybeAssign); + } + function isContinuedStatement(state, textAfter) { + return ( + state.lastType == "operator" || + state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)) + ); + } + function expressionAllowed(stream, state, backUp) { + return ( + (state.tokenize == tokenBase && + /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test( + state.lastType + )) || + (state.lastType == "quasi" && + /\{\s*$/.test( + stream.string.slice(0, stream.pos - (backUp || 0)) + )) + ); + } + return { + startState: function (basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical( + (basecolumn || 0) - indentUnit, + 0, + "block", + false + ), + localVars: parserConfig.localVars, + context: + parserConfig.localVars && + new Context(null, null, false), + indented: basecolumn || 0, + }; + if ( + parserConfig.globalVars && + typeof parserConfig.globalVars == "object" + ) + state.globalVars = parserConfig.globalVars; + return state; + }, + token: function (stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) + return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = + type == "operator" && (content == "++" || content == "--") + ? "incdec" + : type; + return parseJS(state, style, type, content, stream); + }, + indent: function (state, textAfter) { + if ( + state.tokenize == tokenComment || + state.tokenize == tokenQuasi + ) + return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), + lexical = state.lexical, + top; + if (!/^\s*else\b/.test(textAfter)) + for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse && c != popcontext) break; + } + while ( + (lexical.type == "stat" || lexical.type == "form") && + (firstChar == "}" || + ((top = state.cc[state.cc.length - 1]) && + (top == maybeoperatorComma || + top == maybeoperatorNoComma) && + !/^[,\.=+\-*:?[\(]/.test(textAfter))) + ) + lexical = lexical.prev; + if ( + statementIndent && + lexical.type == ")" && + lexical.prev.type == "stat" + ) + lexical = lexical.prev; + var type2 = lexical.type, + closing = firstChar == type2; + if (type2 == "vardef") + return ( + lexical.indented + + (state.lastType == "operator" || state.lastType == "," + ? lexical.info.length + 1 + : 0) + ); + else if (type2 == "form" && firstChar == "{") + return lexical.indented; + else if (type2 == "form") + return lexical.indented + indentUnit; + else if (type2 == "stat") + return ( + lexical.indented + + (isContinuedStatement(state, textAfter) + ? statementIndent || indentUnit + : 0) + ); + else if ( + lexical.info == "switch" && + !closing && + parserConfig.doubleIndentSwitch != false + ) + return ( + lexical.indented + + (/^(?:case|default)\b/.test(textAfter) + ? indentUnit + : 2 * indentUnit) + ); + else if (lexical.align) + return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + helperType: jsonMode ? "json" : "javascript", + jsonldMode, + jsonMode, + expressionAllowed, + skipExpression: function (state) { + parseJS( + state, + "atom", + "atom", + "true", + new CodeMirror.StringStream("", 2, null) + ); + }, + }; + } + ); + CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + CodeMirror.defineMIME("text/javascript", "javascript"); + CodeMirror.defineMIME("text/ecmascript", "javascript"); + CodeMirror.defineMIME("application/javascript", "javascript"); + CodeMirror.defineMIME("application/x-javascript", "javascript"); + CodeMirror.defineMIME("application/ecmascript", "javascript"); + CodeMirror.defineMIME("application/json", { + name: "javascript", + json: true, + }); + CodeMirror.defineMIME("application/x-json", { + name: "javascript", + json: true, + }); + CodeMirror.defineMIME("application/manifest+json", { + name: "javascript", + json: true, + }); + CodeMirror.defineMIME("application/ld+json", { + name: "javascript", + jsonld: true, + }); + CodeMirror.defineMIME("text/typescript", { + name: "javascript", + typescript: true, + }); + CodeMirror.defineMIME("application/typescript", { + name: "javascript", + typescript: true, + }); + }); + })(); + var javascriptExports = javascript$2.exports; + const javascript = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(javascriptExports); + const javascript$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: javascript, + }, + [javascriptExports] + ); + exports.javascript = javascript$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/jump-to-line.cjs.js": + /*!*****************************************************!*\ + !*** ../../graphiql-react/dist/jump-to-line.cjs.js ***! + \*****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + const dialog = __webpack_require__( + /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); } } } - if (!m.atomic) { - continue; - } - if (oldPos) { - var near = m.find(dir < 0 ? 1 : -1), - diff = void 0; - if (dir < 0 ? preventCursorRight : preventCursorLeft) { - near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); - } - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { - return skipAtomicInner(doc, near, pos, dir, mayClear); - } - } - var far = m.find(dir < 0 ? -1 : 1); - if (dir < 0 ? preventCursorLeft : preventCursorRight) { - far = movePos(doc, far, dir, far.line == pos.line ? line : null); - } - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; - } - } - } - return pos; - } - function skipAtomic(doc, pos, oldPos, bias, mayClear) { - var dir = bias || 1; - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true); - if (!found) { - doc.cantEdit = true; - return Pos(doc.first, 0); - } - return found; - } - function movePos(doc, pos, dir, line) { - if (dir < 0 && pos.ch == 0) { - if (pos.line > doc.first) { - return clipPos(doc, Pos(pos.line - 1)); - } else { - return null; - } - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { - if (pos.line < doc.first + doc.size - 1) { - return Pos(pos.line + 1, 0); - } else { - return null; - } - } else { - return new Pos(pos.line, pos.ch + dir); - } - } - function selectAll(cm) { - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); - } - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function () { - return obj.canceled = true; - } - }; - if (update) { - obj.update = function (from, to, text, origin) { - if (from) { - obj.from = clipPos(doc, from); - } - if (to) { - obj.to = clipPos(doc, to); } - if (text) { - obj.text = text; - } - if (origin !== void 0) { - obj.origin = origin; - } - }; - } - signal(doc, "beforeChange", doc, obj); - if (doc.cm) { - signal(doc.cm, "beforeChange", doc.cm, obj); - } - if (obj.canceled) { - if (doc.cm) { - doc.cm.curOp.updateInput = 2; } - return null; + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - return { - from: obj.from, - to: obj.to, - text: obj.text, - origin: obj.origin + var jumpToLine$2 = { + exports: {}, }; - } - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) { - return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); - } - if (doc.cm.state.suppressEdits) { - return; - } - } - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) { - return; - } - } - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i2 = split.length - 1; i2 >= 0; --i2) { - makeChangeInner(doc, { - from: split[i2].from, - to: split[i2].to, - text: i2 ? [""] : change.text, - origin: change.origin - }); - } - } else { - makeChangeInner(doc, change); - } - } - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { - return; - } - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - linkedDocs(doc, function (doc2, sharedHist) { - if (!sharedHist && indexOf(rebased, doc2.history) == -1) { - rebaseHist(doc2.history, change); - rebased.push(doc2.history); - } - makeChangeSingleDoc(doc2, change, null, stretchSpansOverChange(doc2, change)); - }); - } - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - var suppress = doc.cm && doc.cm.state.suppressEdits; - if (suppress && !allowSelectionOnly) { - return; - } - var hist = doc.history, - event, - selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, - dest = type == "undo" ? hist.undone : hist.done; - var i2 = 0; - for (; i2 < source.length; i2++) { - event = source[i2]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { - break; - } - } - if (i2 == source.length) { - return; - } - hist.lastOrigin = hist.lastSelOrigin = null; - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, { - clearRedo: false - }); - return; - } - selAfter = event; - } else if (suppress) { - source.push(event); - return; - } else { - break; - } - } - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({ - changes: antiChanges, - generation: hist.generation - }); - hist.generation = event.generation || ++hist.maxGeneration; - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - var loop = function (i3) { - var change = event.changes[i3]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return {}; - } - antiChanges.push(historyChangeFromChange(doc, change)); - var after = i3 ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i3 && doc.cm) { - doc.cm.scrollIntoView({ - from: change.from, - to: changeEnd(change) + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), dialog.dialogExports); + })(function (CodeMirror) { + CodeMirror.defineOption("search", { + bottom: false, }); - } - var rebased = []; - linkedDocs(doc, function (doc2, sharedHist) { - if (!sharedHist && indexOf(rebased, doc2.history) == -1) { - rebaseHist(doc2.history, change); - rebased.push(doc2.history); + function dialog2(cm, text, shortText, deflt, f) { + if (cm.openDialog) + cm.openDialog(text, f, { + value: deflt, + selectValueOnOpen: true, + bottom: cm.options.search.bottom, + }); + else f(prompt(shortText, deflt)); } - makeChangeSingleDoc(doc2, change, null, mergeOldSpans(doc2, change)); - }); - }; - for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) { - var returned = loop(i$12); - if (returned) return returned.v; - } - } - function shiftDoc(doc, distance) { - if (distance == 0) { - return; - } - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function (range2) { - return new Range(Pos(range2.anchor.line + distance, range2.anchor.ch), Pos(range2.head.line + distance, range2.head.ch)); - }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { - regLineChange(doc.cm, l, "gutter"); - } - } - } - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) { - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - } - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) { - return; - } - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = { - from: Pos(doc.first, 0), - to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], - origin: change.origin - }; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = { - from: change.from, - to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], - origin: change.origin - }; - } - change.removed = getBetween(doc, change.from, change.to); - if (!selAfter) { - selAfter = computeSelAfterChange(doc, change); - } - if (doc.cm) { - makeChangeSingleDocInEditor(doc.cm, change, spans); - } else { - updateDoc(doc, change, spans); - } - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { - doc.cantEdit = false; - } - } - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, - display = cm.display, - from = change.from, - to = change.to; - var recomputeMaxLength = false, - checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function (line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; + function getJumpDialog(cm) { + return ( + cm.phrase("Jump to line:") + + ' ' + + cm.phrase("(Use line:column or scroll% syntax)") + + "" + ); } - }); - } - if (doc.sel.contains(change.from, change.to) > -1) { - signalCursorActivity(cm); - } - updateDoc(doc, change, spans, estimateHeight(cm)); - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function (line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; + function interpretLine(cm, string) { + var num = Number(string); + if (/^[-+]/.test(string)) return cm.getCursor().line + num; + else return num - 1; } + CodeMirror.commands.jumpToLine = function (cm) { + var cur = cm.getCursor(); + dialog2( + cm, + getJumpDialog(cm), + cm.phrase("Jump to line:"), + cur.line + 1 + ":" + cur.ch, + function (posStr) { + if (!posStr) return; + var match; + if ( + (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) + ) { + cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); + } else if ( + (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) + ) { + var line = Math.round( + (cm.lineCount() * Number(match[1])) / 100 + ); + if (/^[-+]/.test(match[1])) line = cur.line + line + 1; + cm.setCursor(line - 1, cur.ch); + } else if ( + (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) + ) { + cm.setCursor(interpretLine(cm, match[1]), cur.ch); + } + } + ); + }; + CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; }); - if (recomputeMaxLength) { - cm.curOp.updateMaxLine = true; - } - } - retreatFrontier(doc, from.line); - startWorker(cm, 400); - var lendiff = change.text.length - (to.line - from.line) - 1; - if (change.full) { - regChange(cm); - } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { - regLineChange(cm, from.line, "text"); - } else { - regChange(cm, from.line, to.line + 1, lendiff); - } - var changesHandler = hasHandler(cm, "changes"), - changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from, - to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) { - signalLater(cm, "change", cm, obj); - } - if (changesHandler) { - (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - } - cm.display.selForContextMenu = null; - } - function replaceRange(doc, code, from, to, origin) { - var assign; - if (!to) { - to = from; - } - if (cmp(to, from) < 0) { - assign = [to, from], from = assign[0], to = assign[1]; - } - if (typeof code == "string") { - code = doc.splitLines(code); - } - makeChange(doc, { - from, - to, - text: code, - origin - }); - } - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - function rebaseHistArray(array, from, to, diff) { - for (var i2 = 0; i2 < array.length; ++i2) { - var sub = array[i2], - ok = true; - if (sub.ranges) { - if (!sub.copied) { - sub = array[i2] = sub.deepCopy(); - sub.copied = true; - } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue; - } - for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { - var cur = sub.changes[j$1]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!ok) { - array.splice(0, i2 + 1); - i2 = 0; - } - } - } - function rebaseHist(hist, change) { - var from = change.from.line, - to = change.to.line, - diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - function changeLine(doc, handle, changeType, op) { - var no = handle, - line = handle; - if (typeof handle == "number") { - line = getLine(doc, clipLine(doc, handle)); - } else { - no = lineNo(handle); - } - if (no == null) { - return null; - } - if (op(line, no) && doc.cm) { - regLineChange(doc.cm, no, changeType); - } - return line; - } - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - var height = 0; - for (var i2 = 0; i2 < lines.length; ++i2) { - lines[i2].parent = this; - height += lines[i2].height; - } - this.height = height; - } - LeafChunk.prototype = { - chunkSize: function () { - return this.lines.length; - }, - // Remove the n lines at offset 'at'. - removeInner: function (at, n) { - for (var i2 = at, e = at + n; i2 < e; ++i2) { - var line = this.lines[i2]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function (lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function (at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i2 = 0; i2 < lines.length; ++i2) { - lines[i2].parent = this; - } - }, - // Used to iterate over a part of the tree. - iterN: function (at, n, op) { - for (var e = at + n; at < e; ++at) { - if (op(this.lines[at])) { - return true; + })(); + var jumpToLineExports = jumpToLine$2.exports; + const jumpToLine = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(jumpToLineExports); + const jumpToLine$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: jumpToLine, + }, + [jumpToLineExports] + ); + exports.jumpToLine = jumpToLine$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/jump.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/jump.cjs.js ***! + \*********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const SchemaReference = __webpack_require__( + /*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js" + ); + codemirror.CodeMirror.defineOption( + "jump", + false, + (cm, options, old) => { + if (old && old !== codemirror.CodeMirror.Init) { + const oldOnMouseOver = cm.state.jump.onMouseOver; + codemirror.CodeMirror.off( + cm.getWrapperElement(), + "mouseover", + oldOnMouseOver + ); + const oldOnMouseOut = cm.state.jump.onMouseOut; + codemirror.CodeMirror.off( + cm.getWrapperElement(), + "mouseout", + oldOnMouseOut + ); + codemirror.CodeMirror.off( + document, + "keydown", + cm.state.jump.onKeyDown + ); + delete cm.state.jump; } - } - } - }; - function BranchChunk(children) { - this.children = children; - var size = 0, - height = 0; - for (var i2 = 0; i2 < children.length; ++i2) { - var ch = children[i2]; - size += ch.chunkSize(); - height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - BranchChunk.prototype = { - chunkSize: function () { - return this.size; - }, - removeInner: function (at, n) { - this.size -= n; - for (var i2 = 0; i2 < this.children.length; ++i2) { - var child = this.children[i2], - sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), - oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { - this.children.splice(i2--, 1); - child.parent = null; - } - if ((n -= rm) == 0) { - break; - } - at = 0; - } else { - at -= sz; - } - } - if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function (lines) { - for (var i2 = 0; i2 < this.children.length; ++i2) { - this.children[i2].collapse(lines); - } - }, - insertInner: function (at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i2 = 0; i2 < this.children.length; ++i2) { - var child = this.children[i2], - sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - var remaining = child.lines.length % 25 + 25; - for (var pos = remaining; pos < child.lines.length;) { - var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); - child.height -= leaf.height; - this.children.splice(++i2, 0, leaf); - leaf.parent = this; - } - child.lines = child.lines.slice(0, remaining); - this.maybeSpill(); - } - break; + if (options) { + const state = (cm.state.jump = { + options, + onMouseOver: onMouseOver.bind(null, cm), + onMouseOut: onMouseOut.bind(null, cm), + onKeyDown: onKeyDown.bind(null, cm), + }); + codemirror.CodeMirror.on( + cm.getWrapperElement(), + "mouseover", + state.onMouseOver + ); + codemirror.CodeMirror.on( + cm.getWrapperElement(), + "mouseout", + state.onMouseOut + ); + codemirror.CodeMirror.on(document, "keydown", state.onKeyDown); } - at -= sz; } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function () { - if (this.children.length <= 10) { + ); + function onMouseOver(cm, event) { + const target = event.target || event.srcElement; + if (!(target instanceof HTMLElement)) { return; } - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function (at, n, op) { - for (var i2 = 0; i2 < this.children.length; ++i2) { - var child = this.children[i2], - sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) { - return true; - } - if ((n -= used) == 0) { - break; - } - at = 0; - } else { - at -= sz; - } - } - } - }; - var LineWidget = function (doc, node, options) { - if (options) { - for (var opt in options) { - if (options.hasOwnProperty(opt)) { - this[opt] = options[opt]; - } - } - } - this.doc = doc; - this.node = node; - }; - LineWidget.prototype.clear = function () { - var cm = this.doc.cm, - ws = this.line.widgets, - line = this.line, - no = lineNo(line); - if (no == null || !ws) { - return; - } - for (var i2 = 0; i2 < ws.length; ++i2) { - if (ws[i2] == this) { - ws.splice(i2--, 1); - } - } - if (!ws.length) { - line.widgets = null; - } - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) { - runInOp(cm, function () { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - signalLater(cm, "lineWidgetCleared", cm, this, no); - } - }; - LineWidget.prototype.changed = function () { - var this$1$1 = this; - var oldH = this.height, - cm = this.doc.cm, - line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) { - return; - } - if (!lineIsHidden(this.doc, line)) { - updateLineHeight(line, line.height + diff); - } - if (cm) { - runInOp(cm, function () { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line)); - }); - } - }; - eventMixin(LineWidget); - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) { - addToScrollTop(cm, diff); - } - } - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) { - cm.display.alignWidgets = true; - } - changeLine(doc, handle, "widget", function (line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) { - widgets.push(widget); - } else { - widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); - } - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) { - addToScrollTop(cm, widget.height); - } - cm.curOp.forceUpdate = true; - } - return true; - }); - if (cm) { - signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); - } - return widget; - } - var nextMarkerId = 0; - var TextMarker = function (doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - TextMarker.prototype.clear = function () { - if (this.explicitlyCleared) { - return; - } - var cm = this.doc.cm, - withOp = cm && !cm.curOp; - if (withOp) { - startOperation(cm); - } - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) { - signalLater(this, "clear", found.from, found.to); - } - } - var min = null, - max = null; - for (var i2 = 0; i2 < this.lines.length; ++i2) { - var line = this.lines[i2]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) { - regLineChange(cm, lineNo(line), "text"); - } else if (cm) { - if (span.to != null) { - max = lineNo(line); - } - if (span.from != null) { - min = lineNo(line); - } - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { - updateLineHeight(line, textHeight(cm.display)); - } - } - if (cm && this.collapsed && !cm.options.lineWrapping) { - for (var i$12 = 0; i$12 < this.lines.length; ++i$12) { - var visual = visualLine(this.lines[i$12]), - len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - } - if (min != null && cm && this.collapsed) { - regChange(cm, min, max + 1); - } - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) { - reCheckSelection(cm.doc); - } - } - if (cm) { - signalLater(cm, "markerCleared", cm, this, min, max); - } - if (withOp) { - endOperation(cm); - } - if (this.parent) { - this.parent.clear(); - } - }; - TextMarker.prototype.find = function (side, lineObj) { - if (side == null && this.type == "bookmark") { - side = 1; - } - var from, to; - for (var i2 = 0; i2 < this.lines.length; ++i2) { - var line = this.lines[i2]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) { - return from; - } - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) { - return to; - } - } - } - return from && { - from, - to - }; - }; - TextMarker.prototype.changed = function () { - var this$1$1 = this; - var pos = this.find(-1, true), - widget = this, - cm = this.doc.cm; - if (!pos || !cm) { - return; - } - runInOp(cm, function () { - var line = pos.line, - lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) { - updateLineHeight(line, line.height + dHeight); - } - } - signalLater(cm, "markerChanged", cm, this$1$1); - }); - }; - TextMarker.prototype.attachLine = function (line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function (line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - eventMixin(TextMarker); - function markText(doc, from, to, options, type) { - if (options && options.shared) { - return markTextShared(doc, from, to, options, type); - } - if (doc.cm && !doc.cm.curOp) { - return operation(doc.cm, markText)(doc, from, to, options, type); - } - var marker = new TextMarker(doc, type), - diff = cmp(from, to); - if (options) { - copyObj(options, marker, false); - } - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { - return marker; - } - if (marker.replacedWith) { - marker.collapsed = true; - marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) { - marker.widgetNode.setAttribute("cm-ignore-events", "true"); - } - if (options.insertLeft) { - marker.widgetNode.insertLeft = true; - } - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { - throw new Error("Inserting collapsed marker partially overlapping an existing one"); - } - seeCollapsedSpans(); - } - if (marker.addToHistory) { - addChangeToHistory(doc, { - from, - to, - origin: "markText" - }, doc.sel, NaN); - } - var curLine = from.line, - cm = doc.cm, - updateMaxLine; - doc.iter(curLine, to.line + 1, function (line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { - updateMaxLine = true; - } - if (marker.collapsed && curLine != from.line) { - updateLineHeight(line, 0); - } - addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); - ++curLine; - }); - if (marker.collapsed) { - doc.iter(from.line, to.line + 1, function (line) { - if (lineIsHidden(doc, line)) { - updateLineHeight(line, 0); - } - }); - } - if (marker.clearOnEnter) { - on(marker, "beforeCursorEnter", function () { - return marker.clear(); - }); - } - if (marker.readOnly) { - seeReadOnlySpans(); - if (doc.history.done.length || doc.history.undone.length) { - doc.clearHistory(); - } - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - if (updateMaxLine) { - cm.curOp.updateMaxLine = true; - } - if (marker.collapsed) { - regChange(cm, from.line, to.line + 1); - } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { - for (var i2 = from.line; i2 <= to.line; i2++) { - regLineChange(cm, i2, "text"); - } - } - if (marker.atomic) { - reCheckSelection(cm.doc); - } - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - var SharedTextMarker = function (markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i2 = 0; i2 < markers.length; ++i2) { - markers[i2].parent = this; - } - }; - SharedTextMarker.prototype.clear = function () { - if (this.explicitlyCleared) { - return; - } - this.explicitlyCleared = true; - for (var i2 = 0; i2 < this.markers.length; ++i2) { - this.markers[i2].clear(); - } - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function (side, lineObj) { - return this.primary.find(side, lineObj); - }; - eventMixin(SharedTextMarker); - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], - primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function (doc2) { - if (widget) { - options.widgetNode = widget.cloneNode(true); - } - markers.push(markText(doc2, clipPos(doc2, from), clipPos(doc2, to), options, type)); - for (var i2 = 0; i2 < doc2.linked.length; ++i2) { - if (doc2.linked[i2].isParent) { - return; - } + if ( + (target === null || target === void 0 + ? void 0 + : target.nodeName) !== "SPAN" + ) { + return; } - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { - return m.parent; - }); - } - function copySharedMarkers(doc, markers) { - for (var i2 = 0; i2 < markers.length; i2++) { - var marker = markers[i2], - pos = marker.find(); - var mFrom = doc.clipPos(pos.from), - mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; + const box = target.getBoundingClientRect(); + const cursor = { + left: (box.left + box.right) / 2, + top: (box.top + box.bottom) / 2, + }; + cm.state.jump.cursor = cursor; + if (cm.state.jump.isHoldingModifier) { + enableJumpMode(cm); } } - } - function detachSharedMarkers(markers) { - var loop = function (i3) { - var marker = markers[i3], - linked = [marker.primary.doc]; - linkedDocs(marker.primary.doc, function (d) { - return linked.push(d); - }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } + function onMouseOut(cm) { + if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) { + cm.state.jump.cursor = null; + return; } - }; - for (var i2 = 0; i2 < markers.length; i2++) loop(i2); - } - var nextDocId = 0; - var Doc = function (text, mode, firstLine, lineSep, direction) { - if (!(this instanceof Doc)) { - return new Doc(text, mode, firstLine, lineSep, direction); - } - if (firstLine == null) { - firstLine = 0; - } - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.modeFrontier = this.highlightFrontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - this.lineSep = lineSep; - this.direction = direction == "rtl" ? "rtl" : "ltr"; - this.extend = false; - if (typeof text == "string") { - text = this.splitLines(text); - } - updateDoc(this, { - from: start, - to: start, - text - }); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function (from, to, op) { - if (op) { - this.iterN(from - this.first, to - from, op); - } else { - this.iterN(this.first, this.first + this.size, from); - } - }, - // Non-public interface for adding and removing lines. - insert: function (at, lines) { - var height = 0; - for (var i2 = 0; i2 < lines.length; ++i2) { - height += lines[i2].height; - } - this.insertInner(at - this.first, lines, height); - }, - remove: function (at, n) { - this.removeInner(at - this.first, n); - }, - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - getValue: function (lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) { - return lines; - } - return lines.join(lineSep || this.lineSeparator()); - }, - setValue: docMethodOp(function (code) { - var top = Pos(this.first, 0), - last = this.first + this.size - 1; - makeChange(this, { - from: top, - to: Pos(last, getLine(this, last).text.length), - text: this.splitLines(code), - origin: "setValue", - full: true - }, true); - if (this.cm) { - scrollToCoords(this.cm, 0, 0); - } - setSelection(this, simpleSelection(top), sel_dontScroll); - }), - replaceRange: function (code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function (from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) { - return lines; - } - if (lineSep === "") { - return lines.join(""); - } - return lines.join(lineSep || this.lineSeparator()); - }, - getLine: function (line) { - var l = this.getLineHandle(line); - return l && l.text; - }, - getLineHandle: function (line) { - if (isLine(this, line)) { - return getLine(this, line); - } - }, - getLineNumber: function (line) { - return lineNo(line); - }, - getLineHandleVisualStart: function (line) { - if (typeof line == "number") { - line = getLine(this, line); - } - return visualLine(line); - }, - lineCount: function () { - return this.size; - }, - firstLine: function () { - return this.first; - }, - lastLine: function () { - return this.first + this.size - 1; - }, - clipPos: function (pos) { - return clipPos(this, pos); - }, - getCursor: function (start) { - var range2 = this.sel.primary(), - pos; - if (start == null || start == "head") { - pos = range2.head; - } else if (start == "anchor") { - pos = range2.anchor; - } else if (start == "end" || start == "to" || start === false) { - pos = range2.to(); - } else { - pos = range2.from(); + if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) { + disableJumpMode(cm); } - return pos; - }, - listSelections: function () { - return this.sel.ranges; - }, - somethingSelected: function () { - return this.sel.somethingSelected(); - }, - setCursor: docMethodOp(function (line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function (anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function (head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function (heads, options) { - extendSelections(this, clipPosArray(this, heads), options); - }), - extendSelectionsBy: docMethodOp(function (f, options) { - var heads = map(this.sel.ranges, f); - extendSelections(this, clipPosArray(this, heads), options); - }), - setSelections: docMethodOp(function (ranges, primary, options) { - if (!ranges.length) { + } + function onKeyDown(cm, event) { + if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) { return; } - var out = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - out[i2] = new Range(clipPos(this, ranges[i2].anchor), clipPos(this, ranges[i2].head || ranges[i2].anchor)); - } - if (primary == null) { - primary = Math.min(ranges.length - 1, this.sel.primIndex); - } - setSelection(this, normalizeSelection(this.cm, out, primary), options); - }), - addSelection: docMethodOp(function (anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); - }), - getSelection: function (lineSep) { - var ranges = this.sel.ranges, - lines; - for (var i2 = 0; i2 < ranges.length; i2++) { - var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) { - return lines; - } else { - return lines.join(lineSep || this.lineSeparator()); + cm.state.jump.isHoldingModifier = true; + if (cm.state.jump.cursor) { + enableJumpMode(cm); } - }, - getSelections: function (lineSep) { - var parts = [], - ranges = this.sel.ranges; - for (var i2 = 0; i2 < ranges.length; i2++) { - var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); - if (lineSep !== false) { - sel = sel.join(lineSep || this.lineSeparator()); + const onKeyUp = (upEvent) => { + if (upEvent.code !== event.code) { + return; } - parts[i2] = sel; - } - return parts; - }, - replaceSelection: function (code, collapse, origin) { - var dup = []; - for (var i2 = 0; i2 < this.sel.ranges.length; i2++) { - dup[i2] = code; - } - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function (code, collapse, origin) { - var changes = [], - sel = this.sel; - for (var i2 = 0; i2 < sel.ranges.length; i2++) { - var range2 = sel.ranges[i2]; - changes[i2] = { - from: range2.from(), - to: range2.to(), - text: this.splitLines(code[i2]), - origin - }; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) { - makeChange(this, changes[i$12]); - } - if (newSel) { - setSelectionReplaceHistory(this, newSel); - } else if (this.cm) { - ensureCursorVisible(this.cm); - } - }), - undo: docMethodOp(function () { - makeChangeFromHistory(this, "undo"); - }), - redo: docMethodOp(function () { - makeChangeFromHistory(this, "redo"); - }), - undoSelection: docMethodOp(function () { - makeChangeFromHistory(this, "undo", true); - }), - redoSelection: docMethodOp(function () { - makeChangeFromHistory(this, "redo", true); - }), - setExtending: function (val) { - this.extend = val; - }, - getExtending: function () { - return this.extend; - }, - historySize: function () { - var hist = this.history, - done = 0, - undone = 0; - for (var i2 = 0; i2 < hist.done.length; i2++) { - if (!hist.done[i2].ranges) { - ++done; - } - } - for (var i$12 = 0; i$12 < hist.undone.length; i$12++) { - if (!hist.undone[i$12].ranges) { - ++undone; + cm.state.jump.isHoldingModifier = false; + if (cm.state.jump.marker) { + disableJumpMode(cm); } - } - return { - undo: done, - redo: undone + codemirror.CodeMirror.off(document, "keyup", onKeyUp); + codemirror.CodeMirror.off(document, "click", onClick); + cm.off("mousedown", onMouseDown); }; - }, - clearHistory: function () { - var this$1$1 = this; - this.history = new History(this.history); - linkedDocs(this, function (doc) { - return doc.history = this$1$1.history; - }, true); - }, - markClean: function () { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function (forceSplit) { - if (forceSplit) { - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - } - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - getHistory: function () { - return { - done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone) + const onClick = (clickEvent) => { + const { destination, options } = cm.state.jump; + if (destination) { + options.onClick(destination, clickEvent); + } }; - }, - setHistory: function (histData) { - var hist = this.history = new History(this.history); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - setGutterMarker: docMethodOp(function (line, gutterID, value) { - return changeLine(this, line, "gutter", function (line2) { - var markers = line2.gutterMarkers || (line2.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) { - line2.gutterMarkers = null; + const onMouseDown = (_, downEvent) => { + if (cm.state.jump.destination) { + downEvent.codemirrorIgnore = true; } - return true; - }); - }), - clearGutter: docMethodOp(function (gutterID) { - var this$1$1 = this; - this.iter(function (line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - changeLine(this$1$1, line, "gutter", function () { - line.gutterMarkers[gutterID] = null; - if (isEmpty(line.gutterMarkers)) { - line.gutterMarkers = null; + }; + codemirror.CodeMirror.on(document, "keyup", onKeyUp); + codemirror.CodeMirror.on(document, "click", onClick); + cm.on("mousedown", onMouseDown); + } + const isMac = + typeof navigator !== "undefined" && + (navigator === null || navigator === void 0 + ? void 0 + : navigator.appVersion.includes("Mac")); + function isJumpModifier(key) { + return key === (isMac ? "Meta" : "Control"); + } + function enableJumpMode(cm) { + if (cm.state.jump.marker) { + return; + } + const { cursor, options } = cm.state.jump; + const pos = cm.coordsChar(cursor); + const token = cm.getTokenAt(pos, true); + const getDestination = + options.getDestination || cm.getHelper(pos, "jump"); + if (getDestination) { + const destination = getDestination(token, options, cm); + if (destination) { + const marker = cm.markText( + { + line: pos.line, + ch: token.start, + }, + { + line: pos.line, + ch: token.end, + }, + { + className: "CodeMirror-jump-token", } - return true; - }); + ); + cm.state.jump.marker = marker; + cm.state.jump.destination = destination; } - }); - }), - lineInfo: function (line) { - var n; - if (typeof line == "number") { - if (!isLine(this, line)) { - return null; + } + } + function disableJumpMode(cm) { + const { marker } = cm.state.jump; + cm.state.jump.marker = null; + cm.state.jump.destination = null; + marker.clear(); + } + codemirror.CodeMirror.registerHelper( + "jump", + "graphql", + (token, options) => { + if (!options.schema || !options.onClick || !token.state) { + return; } - n = line; - line = getLine(this, line); - if (!line) { - return null; + const { state } = token; + const { kind, step } = state; + const typeInfo = SchemaReference.getTypeInfo(options.schema, state); + if ( + (kind === "Field" && step === 0 && typeInfo.fieldDef) || + (kind === "AliasedField" && step === 2 && typeInfo.fieldDef) + ) { + return SchemaReference.getFieldReference(typeInfo); } - } else { - n = lineNo(line); - if (n == null) { - return null; + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + return SchemaReference.getDirectiveReference(typeInfo); } - } - return { - line: n, - handle: line, - text: line.text, - gutterMarkers: line.gutterMarkers, - textClass: line.textClass, - bgClass: line.bgClass, - wrapClass: line.wrapClass, - widgets: line.widgets - }; - }, - addLineClass: docMethodOp(function (handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop2]) { - line[prop2] = cls; - } else if (classTest(cls).test(line[prop2])) { - return false; - } else { - line[prop2] += " " + cls; + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + return SchemaReference.getArgumentReference(typeInfo); } - return true; - }); - }), - removeLineClass: docMethodOp(function (handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop2]; - if (!cur) { - return false; - } else if (cls == null) { - line[prop2] = null; - } else { - var found = cur.match(classTest(cls)); - if (!found) { - return false; - } - var end = found.index + found[0].length; - line[prop2] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + if (kind === "EnumValue" && typeInfo.enumValue) { + return SchemaReference.getEnumValueReference(typeInfo); } - return true; - }); - }), - addLineWidget: docMethodOp(function (handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - removeLineWidget: function (widget) { - widget.clear(); - }, - markText: function (from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); - }, - setBookmark: function (pos, options) { - var realOpts = { - replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, - shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents - }; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function (pos) { - pos = clipPos(this, pos); - var markers = [], - spans = getLine(this, pos.line).markedSpans; - if (spans) { - for (var i2 = 0; i2 < spans.length; ++i2) { - var span = spans[i2]; - if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { - markers.push(span.marker.parent || span.marker); - } - } - } - return markers; - }, - findMarks: function (from, to, filter) { - from = clipPos(this, from); - to = clipPos(this, to); - var found = [], - lineNo2 = from.line; - this.iter(from.line, to.line + 1, function (line) { - var spans = line.markedSpans; - if (spans) { - for (var i2 = 0; i2 < spans.length; i2++) { - var span = spans[i2]; - if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { - found.push(span.marker.parent || span.marker); - } - } - } - ++lineNo2; - }); - return found; - }, - getAllMarks: function () { - var markers = []; - this.iter(function (line) { - var sps = line.markedSpans; - if (sps) { - for (var i2 = 0; i2 < sps.length; ++i2) { - if (sps[i2].from != null) { - markers.push(sps[i2].marker); - } - } - } - }); - return markers; - }, - posFromIndex: function (off2) { - var ch, - lineNo2 = this.first, - sepSize = this.lineSeparator().length; - this.iter(function (line) { - var sz = line.text.length + sepSize; - if (sz > off2) { - ch = off2; - return true; + if (kind === "NamedType" && typeInfo.type) { + return SchemaReference.getTypeReference(typeInfo); } - off2 -= sz; - ++lineNo2; - }); - return clipPos(this, Pos(lineNo2, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) { - return 0; - } - var sepSize = this.lineSeparator().length; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + sepSize; - }); - return index; - }, - copy: function (copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); - doc.scrollTop = this.scrollTop; - doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - linkedDoc: function (options) { - if (!options) { - options = {}; } - var from = this.first, - to = this.first + this.size; - if (options.from != null && options.from > from) { - from = options.from; - } - if (options.to != null && options.to < to) { - to = options.to; - } - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); - if (options.sharedHist) { - copy.history = this.history; - } - (this.linked || (this.linked = [])).push({ - doc: copy, - sharedHist: options.sharedHist - }); - copy.linked = [{ - doc: this, - isParent: true, - sharedHist: options.sharedHist - }]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function (other) { - if (other instanceof CodeMirror) { - other = other.doc; - } - if (this.linked) { - for (var i2 = 0; i2 < this.linked.length; ++i2) { - var link = this.linked[i2]; - if (link.doc != other) { - continue; + ); + + /***/ + }, + + /***/ "../../graphiql-react/dist/lint.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs.js ***! + \*********************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } } - this.linked.splice(i2, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; } } - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function (doc) { - return splitIds.push(doc.id); - }, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function (f) { - linkedDocs(this, f); - }, - getMode: function () { - return this.mode; - }, - getEditor: function () { - return this.cm; - }, - splitLines: function (str) { - if (this.lineSep) { - return str.split(this.lineSep); - } - return splitLinesAuto(str); - }, - lineSeparator: function () { - return this.lineSep || "\n"; - }, - setDirection: docMethodOp(function (dir) { - if (dir != "rtl") { - dir = "ltr"; - } - if (dir == this.direction) { - return; - } - this.direction = dir; - this.iter(function (line) { - return line.order = null; - }); - if (this.cm) { - directionChanged(this.cm); - } - }) - }); - Doc.prototype.eachLine = Doc.prototype.iter; - var lastDrop = 0; - function onDrop(e) { - var cm = this; - clearDragCursor(cm); - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e_preventDefault(e); - if (ie) { - lastDrop = + /* @__PURE__ */new Date(); - } - var pos = posFromMouse(cm, e, true), - files = e.dataTransfer.files; - if (!pos || cm.isReadOnly()) { - return; + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - if (files && files.length && window.FileReader && window.File) { - var n = files.length, - text = Array(n), - read = 0; - var markAsReadAndPasteIfAllFilesAreRead = function () { - if (++read == n) { - operation(cm, function () { - pos = clipPos(cm.doc, pos); - var change = { - from: pos, - to: pos, - text: cm.doc.splitLines(text.filter(function (t) { - return t != null; - }).join(cm.doc.lineSeparator())), - origin: "paste" - }; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); - })(); + var lint$2 = { + exports: {}, + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var GUTTER_ID = "CodeMirror-lint-markers"; + var LINT_LINE_ID = "CodeMirror-lint-line-"; + function showTooltip(cm, e, content) { + var tt = document.createElement("div"); + tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; + tt.appendChild(content.cloneNode(true)); + if (cm.state.lint.options.selfContain) + cm.getWrapperElement().appendChild(tt); + else document.body.appendChild(tt); + function position(e2) { + if (!tt.parentNode) + return CodeMirror.off(document, "mousemove", position); + tt.style.top = + Math.max(0, e2.clientY - tt.offsetHeight - 5) + "px"; + tt.style.left = e2.clientX + 5 + "px"; + } + CodeMirror.on(document, "mousemove", position); + position(e); + if (tt.style.opacity != null) tt.style.opacity = 1; + return tt; } - }; - var readTextFromFile = function (file, i3) { - if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { - markAsReadAndPasteIfAllFilesAreRead(); - return; + function rm(elt) { + if (elt.parentNode) elt.parentNode.removeChild(elt); } - var reader = new FileReader(); - reader.onerror = function () { - return markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.onload = function () { - var content = reader.result; - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { - markAsReadAndPasteIfAllFilesAreRead(); - return; + function hideTooltip(tt) { + if (!tt.parentNode) return; + if (tt.style.opacity == null) rm(tt); + tt.style.opacity = 0; + setTimeout(function () { + rm(tt); + }, 600); + } + function showTooltipFor(cm, e, content, node) { + var tooltip = showTooltip(cm, e, content); + function hide() { + CodeMirror.off(node, "mouseout", hide); + if (tooltip) { + hideTooltip(tooltip); + tooltip = null; + } + } + var poll = setInterval(function () { + if (tooltip) + for (var n = node; ; n = n.parentNode) { + if (n && n.nodeType == 11) n = n.host; + if (n == document.body) return; + if (!n) { + hide(); + break; + } + } + if (!tooltip) return clearInterval(poll); + }, 400); + CodeMirror.on(node, "mouseout", hide); + } + function LintState(cm, conf, hasGutter) { + this.marked = []; + if (conf instanceof Function) + conf = { + getAnnotations: conf, + }; + if (!conf || conf === true) conf = {}; + this.options = {}; + this.linterOptions = conf.options || {}; + for (var prop in defaults) this.options[prop] = defaults[prop]; + for (var prop in conf) { + if (defaults.hasOwnProperty(prop)) { + if (conf[prop] != null) this.options[prop] = conf[prop]; + } else if (!conf.options) { + this.linterOptions[prop] = conf[prop]; + } } - text[i3] = content; - markAsReadAndPasteIfAllFilesAreRead(); + this.timeout = null; + this.hasGutter = hasGutter; + this.onMouseOver = function (e) { + onMouseOver(cm, e); + }; + this.waitingFor = 0; + } + var defaults = { + highlightLines: false, + tooltips: true, + delay: 500, + lintOnChange: true, + getAnnotations: null, + async: false, + selfContain: null, + formatAnnotation: null, + onUpdateLinting: null, }; - reader.readAsText(file); - }; - for (var i2 = 0; i2 < files.length; i2++) { - readTextFromFile(files[i2], i2); - } - } else { - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - setTimeout(function () { - return cm.display.input.focus(); - }, 20); - return; - } - try { - var text$1 = e.dataTransfer.getData("Text"); - if (text$1) { - var selected; - if (cm.state.draggingText && !cm.state.draggingText.copy) { - selected = cm.listSelections(); + function clearMarks(cm) { + var state = cm.state.lint; + if (state.hasGutter) cm.clearGutter(GUTTER_ID); + if (state.options.highlightLines) clearErrorLines(cm); + for (var i = 0; i < state.marked.length; ++i) + state.marked[i].clear(); + state.marked.length = 0; + } + function clearErrorLines(cm) { + cm.eachLine(function (line) { + var has = + line.wrapClass && + /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); + if (has) cm.removeLineClass(line, "wrap", has[0]); + }); + } + function makeMarker(cm, labels, severity, multiple, tooltips) { + var marker = document.createElement("div"), + inner = marker; + marker.className = + "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; + if (multiple) { + inner = marker.appendChild(document.createElement("div")); + inner.className = + "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; + } + if (tooltips != false) + CodeMirror.on(inner, "mouseover", function (e) { + showTooltipFor(cm, e, labels, inner); + }); + return marker; + } + function getMaxSeverity(a, b) { + if (a == "error") return a; + else return b; + } + function groupByLine(annotations) { + var lines = []; + for (var i = 0; i < annotations.length; ++i) { + var ann = annotations[i], + line = ann.from.line; + (lines[line] || (lines[line] = [])).push(ann); + } + return lines; + } + function annotationTooltip(ann) { + var severity = ann.severity; + if (!severity) severity = "error"; + var tip = document.createElement("div"); + tip.className = + "CodeMirror-lint-message CodeMirror-lint-message-" + severity; + if (typeof ann.messageHTML != "undefined") { + tip.innerHTML = ann.messageHTML; + } else { + tip.appendChild(document.createTextNode(ann.message)); + } + return tip; + } + function lintAsync(cm, getAnnotations) { + var state = cm.state.lint; + var id = ++state.waitingFor; + function abort() { + id = -1; + cm.off("change", abort); } - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) { - for (var i$12 = 0; i$12 < selected.length; ++i$12) { - replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag"); + cm.on("change", abort); + getAnnotations( + cm.getValue(), + function (annotations, arg2) { + cm.off("change", abort); + if (state.waitingFor != id) return; + if (arg2 && annotations instanceof CodeMirror) + annotations = arg2; + cm.operation(function () { + updateLinting(cm, annotations); + }); + }, + state.linterOptions, + cm + ); + } + function startLinting(cm) { + var state = cm.state.lint; + if (!state) return; + var options = state.options; + var getAnnotations = + options.getAnnotations || + cm.getHelper(CodeMirror.Pos(0, 0), "lint"); + if (!getAnnotations) return; + if (options.async || getAnnotations.async) { + lintAsync(cm, getAnnotations); + } else { + var annotations = getAnnotations( + cm.getValue(), + state.linterOptions, + cm + ); + if (!annotations) return; + if (annotations.then) + annotations.then(function (issues) { + cm.operation(function () { + updateLinting(cm, issues); + }); + }); + else + cm.operation(function () { + updateLinting(cm, annotations); + }); + } + } + function updateLinting(cm, annotationsNotSorted) { + var state = cm.state.lint; + if (!state) return; + var options = state.options; + clearMarks(cm); + var annotations = groupByLine(annotationsNotSorted); + for (var line = 0; line < annotations.length; ++line) { + var anns = annotations[line]; + if (!anns) continue; + var message = []; + anns = anns.filter(function (item) { + return message.indexOf(item.message) > -1 + ? false + : message.push(item.message); + }); + var maxSeverity = null; + var tipLabel = + state.hasGutter && document.createDocumentFragment(); + for (var i = 0; i < anns.length; ++i) { + var ann = anns[i]; + var severity = ann.severity; + if (!severity) severity = "error"; + maxSeverity = getMaxSeverity(maxSeverity, severity); + if (options.formatAnnotation) + ann = options.formatAnnotation(ann); + if (state.hasGutter) + tipLabel.appendChild(annotationTooltip(ann)); + if (ann.to) + state.marked.push( + cm.markText(ann.from, ann.to, { + className: + "CodeMirror-lint-mark CodeMirror-lint-mark-" + + severity, + __annotation: ann, + }) + ); } + if (state.hasGutter) + cm.setGutterMarker( + line, + GUTTER_ID, + makeMarker( + cm, + tipLabel, + maxSeverity, + annotations[line].length > 1, + options.tooltips + ) + ); + if (options.highlightLines) + cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); } - cm.replaceSelection(text$1, "around", "paste"); - cm.display.input.focus(); + if (options.onUpdateLinting) + options.onUpdateLinting(annotationsNotSorted, annotations, cm); } - } catch (e$1) {} - } - } - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || + /* @__PURE__ */new Date() - lastDrop < 100)) { - e_stop(e); - return; - } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove"; - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - img._top = img.offsetTop; + function onChange(cm) { + var state = cm.state.lint; + if (!state) return; + clearTimeout(state.timeout); + state.timeout = setTimeout(function () { + startLinting(cm); + }, state.options.delay); + } + function popupTooltips(cm, annotations, e) { + var target = e.target || e.srcElement; + var tooltip = document.createDocumentFragment(); + for (var i = 0; i < annotations.length; i++) { + var ann = annotations[i]; + tooltip.appendChild(annotationTooltip(ann)); + } + showTooltipFor(cm, e, tooltip, target); + } + function onMouseOver(cm, e) { + var target = e.target || e.srcElement; + if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; + var box = target.getBoundingClientRect(), + x = (box.left + box.right) / 2, + y = (box.top + box.bottom) / 2; + var spans = cm.findMarksAt( + cm.coordsChar( + { + left: x, + top: y, + }, + "client" + ) + ); + var annotations = []; + for (var i = 0; i < spans.length; ++i) { + var ann = spans[i].__annotation; + if (ann) annotations.push(ann); + } + if (annotations.length) popupTooltips(cm, annotations, e); + } + CodeMirror.defineOption("lint", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + clearMarks(cm); + if (cm.state.lint.options.lintOnChange !== false) + cm.off("change", onChange); + CodeMirror.off( + cm.getWrapperElement(), + "mouseover", + cm.state.lint.onMouseOver + ); + clearTimeout(cm.state.lint.timeout); + delete cm.state.lint; + } + if (val) { + var gutters = cm.getOption("gutters"), + hasLintGutter = false; + for (var i = 0; i < gutters.length; ++i) + if (gutters[i] == GUTTER_ID) hasLintGutter = true; + var state = (cm.state.lint = new LintState( + cm, + val, + hasLintGutter + )); + if (state.options.lintOnChange) cm.on("change", onChange); + if ( + state.options.tooltips != false && + state.options.tooltips != "gutter" + ) + CodeMirror.on( + cm.getWrapperElement(), + "mouseover", + state.onMouseOver + ); + startLinting(cm); + } + }); + CodeMirror.defineExtension("performLint", function () { + startLinting(this); + }); + }); + })(); + var lintExports = lint$2.exports; + const lint = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(lintExports); + const lint$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: lint, + }, + [lintExports] + ); + exports.lint = lint$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/lint.cjs2.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs2.js ***! + \**********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const graphqlLanguageService = __webpack_require__( + /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" + ); + const SEVERITY = ["error", "warning", "information", "hint"]; + const TYPE = { + "GraphQL: Validation": "validation", + "GraphQL: Deprecation": "deprecation", + "GraphQL: Syntax": "syntax", + }; + codemirror.CodeMirror.registerHelper( + "lint", + "graphql", + (text, options) => { + const { schema, validationRules, externalFragments } = options; + const rawResults = graphqlLanguageService.getDiagnostics( + text, + schema, + validationRules, + void 0, + externalFragments + ); + const results = rawResults.map((error) => ({ + message: error.message, + severity: error.severity + ? SEVERITY[error.severity - 1] + : SEVERITY[0], + type: error.source ? TYPE[error.source] : void 0, + from: codemirror.CodeMirror.Pos( + error.range.start.line, + error.range.start.character + ), + to: codemirror.CodeMirror.Pos( + error.range.end.line, + error.range.end.character + ), + })); + return results; } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) { - img.parentNode.removeChild(img); + ); + + /***/ + }, + + /***/ "../../graphiql-react/dist/lint.cjs3.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs3.js ***! + \**********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function jsonParse(str) { + string = str; + strLen = str.length; + start = end = lastEnd = -1; + ch(); + lex(); + const ast = parseObj(); + expect("EOF"); + return ast; + } + let string; + let strLen; + let start; + let end; + let lastEnd; + let code; + let kind; + function parseObj() { + const nodeStart = start; + const members = []; + expect("{"); + if (!skip("}")) { + do { + members.push(parseMember()); + } while (skip(",")); + expect("}"); } + return { + kind: "Object", + start: nodeStart, + end: lastEnd, + members, + }; } - } - function onDragOver(cm, e) { - var pos = posFromMouse(cm, e); - if (!pos) { - return; - } - var frag = document.createDocumentFragment(); - drawSelectionCursor(cm, pos, frag); - if (!cm.display.dragCursor) { - cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); - cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); - } - removeChildrenAndAdd(cm.display.dragCursor, frag); - } - function clearDragCursor(cm) { - if (cm.display.dragCursor) { - cm.display.lineSpace.removeChild(cm.display.dragCursor); - cm.display.dragCursor = null; - } - } - function forEachCodeMirror(f) { - if (!document.getElementsByClassName) { - return; + function parseMember() { + const nodeStart = start; + const key = kind === "String" ? curToken() : null; + expect("String"); + expect(":"); + const value = parseVal(); + return { + kind: "Member", + start: nodeStart, + end: lastEnd, + key, + value, + }; } - var byClass = document.getElementsByClassName("CodeMirror"), - editors = []; - for (var i2 = 0; i2 < byClass.length; i2++) { - var cm = byClass[i2].CodeMirror; - if (cm) { - editors.push(cm); + function parseArr() { + const nodeStart = start; + const values = []; + expect("["); + if (!skip("]")) { + do { + values.push(parseVal()); + } while (skip(",")); + expect("]"); } + return { + kind: "Array", + start: nodeStart, + end: lastEnd, + values, + }; } - if (editors.length) { - editors[0].operation(function () { - for (var i3 = 0; i3 < editors.length; i3++) { - f(editors[i3]); - } - }); - } - } - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) { - return; + function parseVal() { + switch (kind) { + case "[": + return parseArr(); + case "{": + return parseObj(); + case "String": + case "Number": + case "Boolean": + case "Null": + const token = curToken(); + lex(); + return token; + } + expect("Value"); + } + function curToken() { + return { + kind, + start, + end, + value: JSON.parse(string.slice(start, end)), + }; } - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - var resizeTimer; - on(window, "resize", function () { - if (resizeTimer == null) { - resizeTimer = setTimeout(function () { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); + function expect(str) { + if (kind === str) { + lex(); + return; } - }); - on(window, "blur", function () { - return forEachCodeMirror(onBlur); - }); - } - function onResize(cm) { - var d = cm.display; - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - var keyNames = { - 3: "Pause", - 8: "Backspace", - 9: "Tab", - 13: "Enter", - 16: "Shift", - 17: "Ctrl", - 18: "Alt", - 19: "Pause", - 20: "CapsLock", - 27: "Esc", - 32: "Space", - 33: "PageUp", - 34: "PageDown", - 35: "End", - 36: "Home", - 37: "Left", - 38: "Up", - 39: "Right", - 40: "Down", - 44: "PrintScrn", - 45: "Insert", - 46: "Delete", - 59: ";", - 61: "=", - 91: "Mod", - 92: "Mod", - 93: "Mod", - 106: "*", - 107: "=", - 109: "-", - 110: ".", - 111: "/", - 145: "ScrollLock", - 173: "-", - 186: ";", - 187: "=", - 188: ",", - 189: "-", - 190: ".", - 191: "/", - 192: "`", - 219: "[", - 220: "\\", - 221: "]", - 222: "'", - 224: "Mod", - 63232: "Up", - 63233: "Down", - 63234: "Left", - 63235: "Right", - 63272: "Delete", - 63273: "Home", - 63275: "End", - 63276: "PageUp", - 63277: "PageDown", - 63302: "Insert" - }; - for (var i = 0; i < 10; i++) { - keyNames[i + 48] = keyNames[i + 96] = String(i); - } - for (var i$1 = 65; i$1 <= 90; i$1++) { - keyNames[i$1] = String.fromCharCode(i$1); - } - for (var i$2 = 1; i$2 <= 12; i$2++) { - keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; - } - var keyMap = {}; - keyMap.basic = { - "Left": "goCharLeft", - "Right": "goCharRight", - "Up": "goLineUp", - "Down": "goLineDown", - "End": "goLineEnd", - "Home": "goLineStartSmart", - "PageUp": "goPageUp", - "PageDown": "goPageDown", - "Delete": "delCharAfter", - "Backspace": "delCharBefore", - "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", - "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", - "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - keyMap.pcDefault = { - "Ctrl-A": "selectAll", - "Ctrl-D": "deleteLine", - "Ctrl-Z": "undo", - "Shift-Ctrl-Z": "redo", - "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", - "Ctrl-End": "goDocEnd", - "Ctrl-Up": "goLineUp", - "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", - "Ctrl-Right": "goGroupRight", - "Alt-Left": "goLineStart", - "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", - "Ctrl-Delete": "delGroupAfter", - "Ctrl-S": "save", - "Ctrl-F": "find", - "Ctrl-G": "findNext", - "Shift-Ctrl-G": "findPrev", - "Shift-Ctrl-F": "replace", - "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", - "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", - "Shift-Ctrl-U": "redoSelection", - "Alt-U": "redoSelection", - "fallthrough": "basic" - }; - keyMap.emacsy = { - "Ctrl-F": "goCharRight", - "Ctrl-B": "goCharLeft", - "Ctrl-P": "goLineUp", - "Ctrl-N": "goLineDown", - "Ctrl-A": "goLineStart", - "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", - "Shift-Ctrl-V": "goPageUp", - "Ctrl-D": "delCharAfter", - "Ctrl-H": "delCharBefore", - "Alt-Backspace": "delWordBefore", - "Ctrl-K": "killLine", - "Ctrl-T": "transposeChars", - "Ctrl-O": "openLine" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", - "Cmd-D": "deleteLine", - "Cmd-Z": "undo", - "Shift-Cmd-Z": "redo", - "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", - "Cmd-Up": "goDocStart", - "Cmd-End": "goDocEnd", - "Cmd-Down": "goDocEnd", - "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", - "Cmd-Left": "goLineLeft", - "Cmd-Right": "goLineRight", - "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", - "Alt-Delete": "delGroupAfter", - "Cmd-S": "save", - "Cmd-F": "find", - "Cmd-G": "findNext", - "Shift-Cmd-G": "findPrev", - "Cmd-Alt-F": "replace", - "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", - "Cmd-]": "indentMore", - "Cmd-Backspace": "delWrappedLineLeft", - "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", - "Shift-Cmd-U": "redoSelection", - "Ctrl-Up": "goDocStart", - "Ctrl-Down": "goDocEnd", - "fallthrough": ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/); - name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i2 = 0; i2 < parts.length - 1; i2++) { - var mod = parts[i2]; - if (/^(cmd|meta|m)$/i.test(mod)) { - cmd = true; - } else if (/^a(lt)?$/i.test(mod)) { - alt = true; - } else if (/^(c|ctrl|control)$/i.test(mod)) { - ctrl = true; - } else if (/^s(hift)?$/i.test(mod)) { - shift = true; + let found; + if (kind === "EOF") { + found = "[end of file]"; + } else if (end - start > 1) { + found = "`" + string.slice(start, end) + "`"; } else { - throw new Error("Unrecognized modifier name: " + mod); + const match = string.slice(start).match(/^.+?\b/); + found = "`" + (match ? match[0] : string[start]) + "`"; } + throw syntaxError(`Expected ${str} but found ${found}.`); } - if (alt) { - name = "Alt-" + name; - } - if (ctrl) { - name = "Ctrl-" + name; - } - if (cmd) { - name = "Cmd-" + name; - } - if (shift) { - name = "Shift-" + name; - } - return name; - } - function normalizeKeyMap(keymap) { - var copy = {}; - for (var keyname in keymap) { - if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { - continue; - } - if (value == "...") { - delete keymap[keyname]; - continue; - } - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i2 = 0; i2 < keys.length; i2++) { - var val = void 0, - name = void 0; - if (i2 == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i2 + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) { - copy[name] = val; - } else if (prev != val) { - throw new Error("Inconsistent bindings for " + name); - } - } - delete keymap[keyname]; + class JSONSyntaxError extends Error { + constructor(message, position) { + super(message); + this.position = position; } } - for (var prop2 in copy) { - keymap[prop2] = copy[prop2]; - } - return keymap; - } - function lookupKey(key, map2, handle, context) { - map2 = getKeyMap(map2); - var found = map2.call ? map2.call(key, context) : map2[key]; - if (found === false) { - return "nothing"; + function syntaxError(message) { + return new JSONSyntaxError(message, { + start, + end, + }); } - if (found === "...") { - return "multi"; + function skip(k) { + if (kind === k) { + lex(); + return true; + } } - if (found != null && handle(found)) { - return "handled"; + function ch() { + if (end < strLen) { + end++; + code = end === strLen ? 0 : string.charCodeAt(end); + } + return code; } - if (map2.fallthrough) { - if (Object.prototype.toString.call(map2.fallthrough) != "[object Array]") { - return lookupKey(key, map2.fallthrough, handle, context); + function lex() { + lastEnd = end; + while (code === 9 || code === 10 || code === 13 || code === 32) { + ch(); } - for (var i2 = 0; i2 < map2.fallthrough.length; i2++) { - var result = lookupKey(key, map2.fallthrough[i2], handle, context); - if (result) { - return result; - } + if (code === 0) { + kind = "EOF"; + return; } - } - } - function isModifierKey(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - } - function addModifierNames(name, event, noShift) { - var base = name; - if (event.altKey && base != "Alt") { - name = "Alt-" + name; - } - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { - name = "Ctrl-" + name; - } - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { - name = "Cmd-" + name; - } - if (!noShift && event.shiftKey && base != "Shift") { - name = "Shift-" + name; - } - return name; - } - function keyName(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) { - return false; - } - var name = keyNames[event.keyCode]; - if (name == null || event.altGraphKey) { - return false; - } - if (event.keyCode == 3 && event.code) { - name = event.code; - } - return addModifierNames(name, event, noShift); - } - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; - } - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, - kill = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - var toKill = compute(ranges[i2]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break; - } + start = end; + switch (code) { + case 34: + kind = "String"; + return readString(); + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + kind = "Number"; + return readNumber(); + case 102: + if (string.slice(start, start + 5) !== "false") { + break; + } + end += 4; + ch(); + kind = "Boolean"; + return; + case 110: + if (string.slice(start, start + 4) !== "null") { + break; + } + end += 3; + ch(); + kind = "Null"; + return; + case 116: + if (string.slice(start, start + 4) !== "true") { + break; + } + end += 3; + ch(); + kind = "Boolean"; + return; } - kill.push(toKill); + kind = string[start]; + ch(); } - runInOp(cm, function () { - for (var i3 = kill.length - 1; i3 >= 0; i3--) { - replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete"); - } - ensureCursorVisible(cm); - }); - } - function moveCharLogically(line, ch, dir) { - var target = skipExtendingChars(line.text, ch + dir, dir); - return target < 0 || target > line.text.length ? null : target; - } - function moveLogically(line, start, dir) { - var ch = moveCharLogically(line, start.ch, dir); - return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before"); - } - function endOfLine(visually, cm, lineObj, lineNo2, dir) { - if (visually) { - if (cm.doc.direction == "rtl") { - dir = -dir; - } - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = dir < 0 ? lst(order) : order[0]; - var moveInStorageOrder = dir < 0 == (part.level == 1); - var sticky = moveInStorageOrder ? "after" : "before"; - var ch; - if (part.level > 0 || cm.doc.direction == "rtl") { - var prep = prepareMeasureForLine(cm, lineObj); - ch = dir < 0 ? lineObj.text.length - 1 : 0; - var targetTop = measureCharPrepared(cm, prep, ch).top; - ch = findFirst(function (ch2) { - return measureCharPrepared(cm, prep, ch2).top == targetTop; - }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch); - if (sticky == "before") { - ch = moveCharLogically(lineObj, ch, 1); + function readString() { + ch(); + while (code !== 34 && code > 31) { + if (code === 92) { + code = ch(); + switch (code) { + case 34: + case 47: + case 92: + case 98: + case 102: + case 110: + case 114: + case 116: + ch(); + break; + case 117: + ch(); + readHex(); + readHex(); + readHex(); + readHex(); + break; + default: + throw syntaxError("Bad character escape sequence."); } + } else if (end === strLen) { + throw syntaxError("Unterminated string."); } else { - ch = dir < 0 ? part.to : part.from; + ch(); } - return new Pos(lineNo2, ch, sticky); } + if (code === 34) { + ch(); + return; + } + throw syntaxError("Unterminated string."); } - return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after"); - } - function moveVisually(cm, line, start, dir) { - var bidi = getOrder(line, cm.doc.direction); - if (!bidi) { - return moveLogically(line, start, dir); - } - if (start.ch >= line.text.length) { - start.ch = line.text.length; - start.sticky = "before"; - } else if (start.ch <= 0) { - start.ch = 0; - start.sticky = "after"; - } - var partPos = getBidiPartAt(bidi, start.ch, start.sticky), - part = bidi[partPos]; - if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { - return moveLogically(line, start, dir); - } - var mv = function (pos, dir2) { - return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2); - }; - var prep; - var getWrappedLineExtent = function (ch2) { - if (!cm.options.lineWrapping) { - return { - begin: 0, - end: line.text.length - }; + function readHex() { + if ( + (code >= 48 && code <= 57) || + (code >= 65 && code <= 70) || + (code >= 97 && code <= 102) + ) { + return ch(); } - prep = prep || prepareMeasureForLine(cm, line); - return wrappedLineExtentChar(cm, line, prep, ch2); - }; - var wrappedLineExtent2 = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); - if (cm.doc.direction == "rtl" || part.level == 1) { - var moveInStorageOrder = part.level == 1 == dir < 0; - var ch = mv(start, moveInStorageOrder ? 1 : -1); - if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) { - var sticky = moveInStorageOrder ? "before" : "after"; - return new Pos(start.line, ch, sticky); - } - } - var searchInVisualLine = function (partPos2, dir2, wrappedLineExtent3) { - var getRes = function (ch3, moveInStorageOrder3) { - return moveInStorageOrder3 ? new Pos(start.line, mv(ch3, 1), "before") : new Pos(start.line, ch3, "after"); - }; - for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) { - var part2 = bidi[partPos2]; - var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1); - var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1); - if (part2.from <= ch2 && ch2 < part2.to) { - return getRes(ch2, moveInStorageOrder2); - } - ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1); - if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) { - return getRes(ch2, moveInStorageOrder2); + throw syntaxError("Expected hexadecimal digit."); + } + function readNumber() { + if (code === 45) { + ch(); + } + if (code === 48) { + ch(); + } else { + readDigits(); + } + if (code === 46) { + ch(); + readDigits(); + } + if (code === 69 || code === 101) { + code = ch(); + if (code === 43 || code === 45) { + ch(); } + readDigits(); } - }; - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2); - if (res) { - return res; } - var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1); - if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { - res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); - if (res) { - return res; + function readDigits() { + if (code < 48 || code > 57) { + throw syntaxError("Expected decimal digit."); } - } - return null; - } - var commands = { - selectAll, - singleSelection: function (cm) { - return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function (cm) { - return deleteNearSelection(cm, function (range2) { - if (range2.empty()) { - var len = getLine(cm.doc, range2.head.line).text.length; - if (range2.head.ch == len && range2.head.line < cm.lastLine()) { - return { - from: range2.head, - to: Pos(range2.head.line + 1, 0) - }; - } else { - return { - from: range2.head, - to: Pos(range2.head.line, len) - }; + do { + ch(); + } while (code >= 48 && code <= 57); + } + codemirror.CodeMirror.registerHelper( + "lint", + "graphql-variables", + (text, options, editor) => { + if (!text) { + return []; + } + let ast; + try { + ast = jsonParse(text); + } catch (error) { + if (error instanceof JSONSyntaxError) { + return [lintError(editor, error.position, error.message)]; } - } else { - return { - from: range2.from(), - to: range2.to() - }; + throw error; } - }); - }, - deleteLine: function (cm) { - return deleteNearSelection(cm, function (range2) { - return { - from: Pos(range2.from().line, 0), - to: clipPos(cm.doc, Pos(range2.to().line + 1, 0)) - }; - }); - }, - delLineLeft: function (cm) { - return deleteNearSelection(cm, function (range2) { - return { - from: Pos(range2.from().line, 0), - to: range2.from() - }; - }); - }, - delWrappedLineLeft: function (cm) { - return deleteNearSelection(cm, function (range2) { - var top = cm.charCoords(range2.head, "div").top + 5; - var leftPos = cm.coordsChar({ - left: 0, - top - }, "div"); - return { - from: leftPos, - to: range2.from() - }; - }); - }, - delWrappedLineRight: function (cm) { - return deleteNearSelection(cm, function (range2) { - var top = cm.charCoords(range2.head, "div").top + 5; - var rightPos = cm.coordsChar({ - left: cm.display.lineDiv.offsetWidth + 100, - top - }, "div"); - return { - from: range2.from(), - to: rightPos - }; - }); - }, - undo: function (cm) { - return cm.undo(); - }, - redo: function (cm) { - return cm.redo(); - }, - undoSelection: function (cm) { - return cm.undoSelection(); - }, - redoSelection: function (cm) { - return cm.redoSelection(); - }, - goDocStart: function (cm) { - return cm.extendSelection(Pos(cm.firstLine(), 0)); - }, - goDocEnd: function (cm) { - return cm.extendSelection(Pos(cm.lastLine())); - }, - goLineStart: function (cm) { - return cm.extendSelectionsBy(function (range2) { - return lineStart(cm, range2.head.line); - }, { - origin: "+move", - bias: 1 - }); - }, - goLineStartSmart: function (cm) { - return cm.extendSelectionsBy(function (range2) { - return lineStartSmart(cm, range2.head); - }, { - origin: "+move", - bias: 1 - }); - }, - goLineEnd: function (cm) { - return cm.extendSelectionsBy(function (range2) { - return lineEnd(cm, range2.head.line); - }, { - origin: "+move", - bias: -1 - }); - }, - goLineRight: function (cm) { - return cm.extendSelectionsBy(function (range2) { - var top = cm.cursorCoords(range2.head, "div").top + 5; - return cm.coordsChar({ - left: cm.display.lineDiv.offsetWidth + 100, - top - }, "div"); - }, sel_move); - }, - goLineLeft: function (cm) { - return cm.extendSelectionsBy(function (range2) { - var top = cm.cursorCoords(range2.head, "div").top + 5; - return cm.coordsChar({ - left: 0, - top - }, "div"); - }, sel_move); - }, - goLineLeftSmart: function (cm) { - return cm.extendSelectionsBy(function (range2) { - var top = cm.cursorCoords(range2.head, "div").top + 5; - var pos = cm.coordsChar({ - left: 0, - top - }, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) { - return lineStartSmart(cm, range2.head); + const { variableToType } = options; + if (!variableToType) { + return []; } - return pos; - }, sel_move); - }, - goLineUp: function (cm) { - return cm.moveV(-1, "line"); - }, - goLineDown: function (cm) { - return cm.moveV(1, "line"); - }, - goPageUp: function (cm) { - return cm.moveV(-1, "page"); - }, - goPageDown: function (cm) { - return cm.moveV(1, "page"); - }, - goCharLeft: function (cm) { - return cm.moveH(-1, "char"); - }, - goCharRight: function (cm) { - return cm.moveH(1, "char"); - }, - goColumnLeft: function (cm) { - return cm.moveH(-1, "column"); - }, - goColumnRight: function (cm) { - return cm.moveH(1, "column"); - }, - goWordLeft: function (cm) { - return cm.moveH(-1, "word"); - }, - goGroupRight: function (cm) { - return cm.moveH(1, "group"); - }, - goGroupLeft: function (cm) { - return cm.moveH(-1, "group"); - }, - goWordRight: function (cm) { - return cm.moveH(1, "word"); - }, - delCharBefore: function (cm) { - return cm.deleteH(-1, "codepoint"); - }, - delCharAfter: function (cm) { - return cm.deleteH(1, "char"); - }, - delWordBefore: function (cm) { - return cm.deleteH(-1, "word"); - }, - delWordAfter: function (cm) { - return cm.deleteH(1, "word"); - }, - delGroupBefore: function (cm) { - return cm.deleteH(-1, "group"); - }, - delGroupAfter: function (cm) { - return cm.deleteH(1, "group"); - }, - indentAuto: function (cm) { - return cm.indentSelection("smart"); - }, - indentMore: function (cm) { - return cm.indentSelection("add"); - }, - indentLess: function (cm) { - return cm.indentSelection("subtract"); - }, - insertTab: function (cm) { - return cm.replaceSelection(" "); - }, - insertSoftTab: function (cm) { - var spaces = [], - ranges = cm.listSelections(), - tabSize = cm.options.tabSize; - for (var i2 = 0; i2 < ranges.length; i2++) { - var pos = ranges[i2].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(spaceStr(tabSize - col % tabSize)); - } - cm.replaceSelections(spaces); - }, - defaultTab: function (cm) { - if (cm.somethingSelected()) { - cm.indentSelection("add"); - } else { - cm.execCommand("insertTab"); + return validateVariables(editor, variableToType, ast); } - }, - // Swap the two chars left and right of each selection's head. - // Move cursor behind the two swapped characters afterwards. - // - // Doesn't consider line feeds a character. - // Doesn't scan more than one line above to find a character. - // Doesn't do anything on an empty line. - // Doesn't do anything with non-empty selections. - transposeChars: function (cm) { - return runInOp(cm, function () { - var ranges = cm.listSelections(), - newSel = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - if (!ranges[i2].empty()) { - continue; - } - var cur = ranges[i2].head, - line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) { - cur = new Pos(cur.line, cur.ch - 1); - } - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) { - cur = new Pos(cur.line, 1); - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); - } + ); + function validateVariables(editor, variableToType, variablesAST) { + var _a; + const errors = []; + for (const member of variablesAST.members) { + if (member) { + const variableName = + (_a = member.key) === null || _a === void 0 ? void 0 : _a.value; + const type = variableToType[variableName]; + if (type) { + for (const [node, message] of validateValue( + type, + member.value + )) { + errors.push(lintError(editor, node, message)); } + } else { + errors.push( + lintError( + editor, + member.key, + `Variable "$${variableName}" does not appear in any GraphQL query.` + ) + ); } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function (cm) { - return runInOp(cm, function () { - var sels = cm.listSelections(); - for (var i2 = sels.length - 1; i2 >= 0; i2--) { - cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input"); } - sels = cm.listSelections(); - for (var i$12 = 0; i$12 < sels.length; i$12++) { - cm.indentLine(sels[i$12].from().line, null, true); - } - ensureCursorVisible(cm); - }); - }, - openLine: function (cm) { - return cm.replaceSelection("\n", "start"); - }, - toggleOverwrite: function (cm) { - return cm.toggleOverwrite(); - } - }; - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) { - lineN = lineNo(visual); - } - return endOfLine(true, cm, visual, lineN, 1); - } - function lineEnd(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLineEnd(line); - if (visual != line) { - lineN = lineNo(visual); - } - return endOfLine(true, cm, line, lineN, -1); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line, cm.doc.direction); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); - } - return start; - } - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) { - return false; } + return errors; } - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, - done = false; - try { - if (cm.isReadOnly()) { - cm.state.suppressEdits = true; + function validateValue(type, valueAST) { + if (!type || !valueAST) { + return []; } - if (dropShift) { - cm.display.shift = false; + if (type instanceof graphql.GraphQLNonNull) { + if (valueAST.kind === "Null") { + return [ + [ + valueAST, + `Type "${type}" is non-nullable and cannot be null.`, + ], + ]; + } + return validateValue(type.ofType, valueAST); } - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - function lookupKeyForEditor(cm, name, handle) { - for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) { - var result = lookupKey(name, cm.state.keyMaps[i2], handle, cm); - if (result) { - return result; + if (valueAST.kind === "Null") { + return []; } - } - return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm); - } - var stopSeq = new Delayed(); - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) { - return "handled"; - } - if (/\'$/.test(name)) { - cm.state.keySeq = null; - } else { - stopSeq.set(50, function () { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); + if (type instanceof graphql.GraphQLList) { + const itemType = type.ofType; + if (valueAST.kind === "Array") { + const values = valueAST.values || []; + return mapCat(values, (item) => validateValue(itemType, item)); + } + return validateValue(itemType, valueAST); + } + if (type instanceof graphql.GraphQLInputObjectType) { + if (valueAST.kind !== "Object") { + return [[valueAST, `Type "${type}" must be an Object.`]]; + } + const providedFields = /* @__PURE__ */ Object.create(null); + const fieldErrors = mapCat(valueAST.members, (member) => { + var _a; + const fieldName = + (_a = + member === null || member === void 0 + ? void 0 + : member.key) === null || _a === void 0 + ? void 0 + : _a.value; + providedFields[fieldName] = true; + const inputField = type.getFields()[fieldName]; + if (!inputField) { + return [ + [ + member.key, + `Type "${type}" does not have a field "${fieldName}".`, + ], + ]; } + const fieldType = inputField ? inputField.type : void 0; + return validateValue(fieldType, member.value); }); - } - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { - return true; - } - } - return dispatchKeyInner(cm, name, e, handle); - } - function dispatchKeyInner(cm, name, e, handle) { - var result = lookupKeyForEditor(cm, name, handle); - if (result == "multi") { - cm.state.keySeq = name; - } - if (result == "handled") { - signalLater(cm, "keyHandled", cm, name, e); - } - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - return !!result; - } - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) { - return false; - } - if (e.shiftKey && !cm.state.keySeq) { - return dispatchKey(cm, "Shift-" + name, e, function (b) { - return doHandleBinding(cm, b, true); - }) || dispatchKey(cm, name, e, function (b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { - return doHandleBinding(cm, b); + for (const fieldName of Object.keys(type.getFields())) { + const field = type.getFields()[fieldName]; + if ( + !providedFields[fieldName] && + field.type instanceof graphql.GraphQLNonNull && + !field.defaultValue + ) { + fieldErrors.push([ + valueAST, + `Object of type "${type}" is missing required field "${fieldName}".`, + ]); + } } - }); - } else { - return dispatchKey(cm, name, e, function (b) { - return doHandleBinding(cm, b); - }); - } - } - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, function (b) { - return doHandleBinding(cm, b, true); - }); - } - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - if (e.target && e.target != cm.display.input.getField()) { - return; - } - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) { - return; - } - if (ie && ie_version < 11 && e.keyCode == 27) { - e.returnValue = false; - } - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { - cm.replaceSelection("", null, "cut"); - } - } - if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { - document.execCommand("cut"); - } - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { - showCrossHair(cm); - } - } - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - function onKeyUp(e) { - if (e.keyCode == 16) { - this.doc.sel.shift = false; - } - signalDOMEvent(this, e); - } - function onKeyPress(e) { - var cm = this; - if (e.target && e.target != cm.display.input.getField()) { - return; - } - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { - return; - } - var keyCode = e.keyCode, - charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) { - lastStoppedKey = null; - e_preventDefault(e); - return; - } - if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) { - return; - } - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (ch == "\b") { - return; - } - if (handleCharBinding(cm, e, ch)) { - return; - } - cm.display.input.onKeyPress(e); - } - var DOUBLECLICK_DELAY = 400; - var PastClick = function (time, pos, button) { - this.time = time; - this.pos = pos; - this.button = button; - }; - PastClick.prototype.compare = function (time, pos, button) { - return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button; - }; - var lastClick, lastDoubleClick; - function clickRepeat(pos, button) { - var now = + /* @__PURE__ */new Date(); - if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { - lastClick = lastDoubleClick = null; - return "triple"; - } else if (lastClick && lastClick.compare(now, pos, button)) { - lastDoubleClick = new PastClick(now, pos, button); - lastClick = null; - return "double"; - } else { - lastClick = new PastClick(now, pos, button); - lastDoubleClick = null; - return "single"; - } - } - function onMouseDown(e) { - var cm = this, - display = cm.display; - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { - return; - } - display.input.ensurePolled(); - display.shift = e.shiftKey; - if (eventInWidget(display, e)) { - if (!webkit) { - display.scroller.draggable = false; - setTimeout(function () { - return display.scroller.draggable = true; - }, 100); - } - return; - } - if (clickInGutter(cm, e)) { - return; - } - var pos = posFromMouse(cm, e), - button = e_button(e), - repeat = pos ? clickRepeat(pos, button) : "single"; - window.focus(); - if (button == 1 && cm.state.selectingText) { - cm.state.selectingText(e); + return fieldErrors; + } + if ( + (type.name === "Boolean" && valueAST.kind !== "Boolean") || + (type.name === "String" && valueAST.kind !== "String") || + (type.name === "ID" && + valueAST.kind !== "Number" && + valueAST.kind !== "String") || + (type.name === "Float" && valueAST.kind !== "Number") || + (type.name === "Int" && + (valueAST.kind !== "Number" || + (valueAST.value | 0) !== valueAST.value)) + ) { + return [[valueAST, `Expected value of type "${type}".`]]; + } + if ( + (type instanceof graphql.GraphQLEnumType || + type instanceof graphql.GraphQLScalarType) && + ((valueAST.kind !== "String" && + valueAST.kind !== "Number" && + valueAST.kind !== "Boolean" && + valueAST.kind !== "Null") || + isNullish(type.parseValue(valueAST.value))) + ) { + return [[valueAST, `Expected value of type "${type}".`]]; + } + return []; + } + function lintError(editor, node, message) { + return { + message, + severity: "error", + type: "validation", + from: editor.posFromIndex(node.start), + to: editor.posFromIndex(node.end), + }; } - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { - return; + function isNullish(value) { + return value === null || value === void 0 || value !== value; } - if (button == 1) { - if (pos) { - leftButtonDown(cm, pos, repeat, e); - } else if (e_target(e) == display.scroller) { - e_preventDefault(e); - } - } else if (button == 2) { - if (pos) { - extendSelection(cm.doc, pos); - } - setTimeout(function () { - return display.input.focus(); - }, 20); - } else if (button == 3) { - if (captureRightClick) { - cm.display.input.onContextMenu(e); - } else { - delayBlurEvent(cm); - } + function mapCat(array, mapper) { + return Array.prototype.concat.apply([], array.map(mapper)); } - } - function handleMappedButton(cm, button, pos, repeat, event) { - var name = "Click"; - if (repeat == "double") { - name = "Double" + name; - } else if (repeat == "triple") { - name = "Triple" + name; - } - name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; - return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { - if (typeof bound == "string") { - bound = commands[bound]; - } - if (!bound) { - return false; - } - var done = false; - try { - if (cm.isReadOnly()) { - cm.state.suppressEdits = true; + + /***/ + }, + + /***/ "../../graphiql-react/dist/matchbrackets.cjs.js": + /*!******************************************************!*\ + !*** ../../graphiql-react/dist/matchbrackets.cjs.js ***! + \******************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + const matchbrackets$2 = __webpack_require__( + /*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } } - done = bound(cm, pos) != Pass; - } finally { - cm.state.suppressEdits = false; } - return done; - }); - } - function configureMouse(cm, repeat, event) { - var option = cm.getOption("configureMouse"); - var value = option ? option(cm, repeat, event) : {}; - if (value.unit == null) { - var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; - value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; - } - if (value.extend == null || cm.doc.extend) { - value.extend = cm.doc.extend || event.shiftKey; - } - if (value.addNew == null) { - value.addNew = mac ? event.metaKey : event.ctrlKey; - } - if (value.moveOnDrag == null) { - value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - return value; - } - function leftButtonDown(cm, pos, repeat, event) { - if (ie) { - setTimeout(bind(ensureFocus, cm), 0); - } else { - cm.curOp.focus = activeElt(); + var matchbracketsExports = matchbrackets$2.requireMatchbrackets(); + const matchbrackets = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs( + matchbracketsExports + ); + const matchbrackets$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: matchbrackets, + }, + [matchbracketsExports] + ); + exports.matchbrackets = matchbrackets$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/matchbrackets.cjs2.js": + /*!*******************************************************!*\ + !*** ../../graphiql-react/dist/matchbrackets.cjs2.js ***! + \*******************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + var matchbrackets = { + exports: {}, + }; + var hasRequiredMatchbrackets; + function requireMatchbrackets() { + if (hasRequiredMatchbrackets) return matchbrackets.exports; + hasRequiredMatchbrackets = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var ie_lt8 = + /MSIE \d/.test(navigator.userAgent) && + (document.documentMode == null || document.documentMode < 8); + var Pos = CodeMirror.Pos; + var matching = { + "(": ")>", + ")": "(<", + "[": "]>", + "]": "[<", + "{": "}>", + "}": "{<", + "<": ">>", + ">": "<<", + }; + function bracketRegex(config) { + return (config && config.bracketRegex) || /[(){}[\]]/; + } + function findMatchingBracket(cm, where, config) { + var line = cm.getLineHandle(where.line), + pos = where.ch - 1; + var afterCursor = config && config.afterCursor; + if (afterCursor == null) + afterCursor = /(^| )cm-fat-cursor($| )/.test( + cm.getWrapperElement().className + ); + var re = bracketRegex(config); + var match = + (!afterCursor && + pos >= 0 && + re.test(line.text.charAt(pos)) && + matching[line.text.charAt(pos)]) || + (re.test(line.text.charAt(pos + 1)) && + matching[line.text.charAt(++pos)]); + if (!match) return null; + var dir = match.charAt(1) == ">" ? 1 : -1; + if (config && config.strict && dir > 0 != (pos == where.ch)) + return null; + var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); + var found = scanForBracket( + cm, + Pos(where.line, pos + (dir > 0 ? 1 : 0)), + dir, + style, + config + ); + if (found == null) return null; + return { + from: Pos(where.line, pos), + to: found && found.pos, + match: found && found.ch == match.charAt(0), + forward: dir > 0, + }; + } + function scanForBracket(cm, where, dir, style, config) { + var maxScanLen = (config && config.maxScanLineLength) || 1e4; + var maxScanLines = (config && config.maxScanLines) || 1e3; + var stack = []; + var re = bracketRegex(config); + var lineEnd = + dir > 0 + ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) + : Math.max(cm.firstLine() - 1, where.line - maxScanLines); + for ( + var lineNo = where.line; + lineNo != lineEnd; + lineNo += dir + ) { + var line = cm.getLine(lineNo); + if (!line) continue; + var pos = dir > 0 ? 0 : line.length - 1, + end = dir > 0 ? line.length : -1; + if (line.length > maxScanLen) continue; + if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); + for (; pos != end; pos += dir) { + var ch = line.charAt(pos); + if ( + re.test(ch) && + (style === void 0 || + (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == + (style || "")) + ) { + var match = matching[ch]; + if (match && (match.charAt(1) == ">") == dir > 0) + stack.push(ch); + else if (!stack.length) + return { + pos: Pos(lineNo, pos), + ch, + }; + else stack.pop(); + } + } + } + return lineNo - dir == + (dir > 0 ? cm.lastLine() : cm.firstLine()) + ? false + : null; + } + function matchBrackets(cm, autoclear, config) { + var maxHighlightLen = + cm.state.matchBrackets.maxHighlightLineLength || 1e3, + highlightNonMatching = config && config.highlightNonMatching; + var marks = [], + ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var match = + ranges[i].empty() && + findMatchingBracket(cm, ranges[i].head, config); + if ( + match && + (match.match || highlightNonMatching !== false) && + cm.getLine(match.from.line).length <= maxHighlightLen + ) { + var style = match.match + ? "CodeMirror-matchingbracket" + : "CodeMirror-nonmatchingbracket"; + marks.push( + cm.markText( + match.from, + Pos(match.from.line, match.from.ch + 1), + { + className: style, + } + ) + ); + if ( + match.to && + cm.getLine(match.to.line).length <= maxHighlightLen + ) + marks.push( + cm.markText( + match.to, + Pos(match.to.line, match.to.ch + 1), + { + className: style, + } + ) + ); + } + } + if (marks.length) { + if (ie_lt8 && cm.state.focused) cm.focus(); + var clear = function () { + cm.operation(function () { + for (var i2 = 0; i2 < marks.length; i2++) + marks[i2].clear(); + }); + }; + if (autoclear) setTimeout(clear, 800); + else return clear; + } + } + function doMatchBrackets(cm) { + cm.operation(function () { + if (cm.state.matchBrackets.currentlyHighlighted) { + cm.state.matchBrackets.currentlyHighlighted(); + cm.state.matchBrackets.currentlyHighlighted = null; + } + cm.state.matchBrackets.currentlyHighlighted = matchBrackets( + cm, + false, + cm.state.matchBrackets + ); + }); + } + function clearHighlighted(cm) { + if ( + cm.state.matchBrackets && + cm.state.matchBrackets.currentlyHighlighted + ) { + cm.state.matchBrackets.currentlyHighlighted(); + cm.state.matchBrackets.currentlyHighlighted = null; + } + } + CodeMirror.defineOption( + "matchBrackets", + false, + function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.off("cursorActivity", doMatchBrackets); + cm.off("focus", doMatchBrackets); + cm.off("blur", clearHighlighted); + clearHighlighted(cm); + } + if (val) { + cm.state.matchBrackets = typeof val == "object" ? val : {}; + cm.on("cursorActivity", doMatchBrackets); + cm.on("focus", doMatchBrackets); + cm.on("blur", clearHighlighted); + } + } + ); + CodeMirror.defineExtension("matchBrackets", function () { + matchBrackets(this, true); + }); + CodeMirror.defineExtension( + "findMatchingBracket", + function (pos, config, oldConfig) { + if (oldConfig || typeof config == "boolean") { + if (!oldConfig) { + config = config + ? { + strict: true, + } + : null; + } else { + oldConfig.strict = config; + config = oldConfig; + } + } + return findMatchingBracket(this, pos, config); + } + ); + CodeMirror.defineExtension( + "scanForBracket", + function (pos, dir, style, config) { + return scanForBracket(this, pos, dir, style, config); + } + ); + }); + })(); + return matchbrackets.exports; } - var behavior = configureMouse(cm, repeat, event); - var sel = cm.doc.sel, - contained; - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { - leftButtonStartDrag(cm, event, pos, behavior); - } else { - leftButtonSelect(cm, event, pos, behavior); + exports.requireMatchbrackets = requireMatchbrackets; + + /***/ + }, + + /***/ "../../graphiql-react/dist/mode-indent.cjs.js": + /*!****************************************************!*\ + !*** ../../graphiql-react/dist/mode-indent.cjs.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports) { + function indent(state, textAfter) { + var _a, _b; + const { levels, indentLevel } = state; + const level = + !levels || levels.length === 0 + ? indentLevel + : levels.at(-1) - + (( + (_a = this.electricInput) === null || _a === void 0 + ? void 0 + : _a.test(textAfter) + ) + ? 1 + : 0); + return ( + (level || 0) * + (((_b = this.config) === null || _b === void 0 + ? void 0 + : _b.indentUnit) || 0) + ); } - } - function leftButtonStartDrag(cm, event, pos, behavior) { - var display = cm.display, - moved = false; - var dragEnd = operation(cm, function (e) { - if (webkit) { - display.scroller.draggable = false; - } - cm.state.draggingText = false; - if (cm.state.delayingBlurEvent) { - if (cm.hasFocus()) { - cm.state.delayingBlurEvent = false; - } else { - delayBlurEvent(cm); - } - } - off(display.wrapper.ownerDocument, "mouseup", dragEnd); - off(display.wrapper.ownerDocument, "mousemove", mouseMove); - off(display.scroller, "dragstart", dragStart); - off(display.scroller, "drop", dragEnd); - if (!moved) { - e_preventDefault(e); - if (!behavior.addNew) { - extendSelection(cm.doc, pos, null, null, behavior.extend); - } - if (webkit && !safari || ie && ie_version == 9) { - setTimeout(function () { - display.wrapper.ownerDocument.body.focus({ - preventScroll: true - }); - display.input.focus(); - }, 20); - } else { - display.input.focus(); - } - } + exports.indent = indent; + + /***/ + }, + + /***/ "../../graphiql-react/dist/mode.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs.js ***! + \*********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const graphqlLanguageService = __webpack_require__( + /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" + ); + const modeIndent = __webpack_require__( + /*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js" + ); + const graphqlModeFactory = (config) => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: (stream) => + stream.eatWhile(graphqlLanguageService.isIgnored), + lexRules: graphqlLanguageService.LexRules, + parseRules: graphqlLanguageService.ParseRules, + editorConfig: { + tabSize: config.tabSize, + }, + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[})\]]/, + fold: "brace", + lineComment: "#", + closeBrackets: { + pairs: '()[]{}""', + explode: "()[]{}", + }, + }; + }; + codemirror.CodeMirror.defineMode("graphql", graphqlModeFactory); + + /***/ + }, + + /***/ "../../graphiql-react/dist/mode.cjs2.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs2.js ***! + \**********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const graphqlLanguageService = __webpack_require__( + /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" + ); + const modeIndent = __webpack_require__( + /*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js" + ); + codemirror.CodeMirror.defineMode("graphql-variables", (config) => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: (stream) => stream.eatSpace(), + lexRules: LexRules, + parseRules: ParseRules, + editorConfig: { + tabSize: config.tabSize, + }, + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[}\]]/, + fold: "brace", + closeBrackets: { + pairs: '[]{}""', + explode: "[]{}", + }, + }; }); - var mouseMove = function (e2) { - moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; + const LexRules = { + Punctuation: /^\[|]|\{|\}|:|,/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, + Keyword: /^true|false|null/, }; - var dragStart = function () { - return moved = true; + const ParseRules = { + Document: [ + graphqlLanguageService.p("{"), + graphqlLanguageService.list( + "Variable", + graphqlLanguageService.opt(graphqlLanguageService.p(",")) + ), + graphqlLanguageService.p("}"), + ], + Variable: [ + namedKey("variable"), + graphqlLanguageService.p(":"), + "Value", + ], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; + } + return null; + case "Keyword": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + case "null": + return "NullValue"; + } + return null; + } + }, + NumberValue: [graphqlLanguageService.t("Number", "number")], + StringValue: [graphqlLanguageService.t("String", "string")], + BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], + NullValue: [graphqlLanguageService.t("Keyword", "keyword")], + ListValue: [ + graphqlLanguageService.p("["), + graphqlLanguageService.list( + "Value", + graphqlLanguageService.opt(graphqlLanguageService.p(",")) + ), + graphqlLanguageService.p("]"), + ], + ObjectValue: [ + graphqlLanguageService.p("{"), + graphqlLanguageService.list( + "ObjectField", + graphqlLanguageService.opt(graphqlLanguageService.p(",")) + ), + graphqlLanguageService.p("}"), + ], + ObjectField: [ + namedKey("attribute"), + graphqlLanguageService.p(":"), + "Value", + ], }; - if (webkit) { - display.scroller.draggable = true; - } - cm.state.draggingText = dragEnd; - dragEnd.copy = !behavior.moveOnDrag; - on(display.wrapper.ownerDocument, "mouseup", dragEnd); - on(display.wrapper.ownerDocument, "mousemove", mouseMove); - on(display.scroller, "dragstart", dragStart); - on(display.scroller, "drop", dragEnd); - cm.state.delayingBlurEvent = true; - setTimeout(function () { - return display.input.focus(); - }, 20); - if (display.scroller.dragDrop) { - display.scroller.dragDrop(); - } - } - function rangeForUnit(cm, pos, unit) { - if (unit == "char") { - return new Range(pos, pos); - } - if (unit == "word") { - return cm.findWordAt(pos); - } - if (unit == "line") { - return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - } - var result = unit(cm, pos); - return new Range(result.from, result.to); - } - function leftButtonSelect(cm, event, start, behavior) { - if (ie) { - delayBlurEvent(cm); - } - var display = cm.display, - doc = cm.doc; - e_preventDefault(event); - var ourRange, - ourIndex, - startSel = doc.sel, - ranges = startSel.ranges; - if (behavior.addNew && !behavior.extend) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) { - ourRange = ranges[ourIndex]; - } else { - ourRange = new Range(start, start); - } - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - if (behavior.unit == "rectangle") { - if (!behavior.addNew) { - ourRange = new Range(start, start); - } - start = posFromMouse(cm, event, true, true); - ourIndex = -1; - } else { - var range2 = rangeForUnit(cm, start, behavior.unit); - if (behavior.extend) { - ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend); - } else { - ourRange = range2; - } + function namedKey(style) { + return { + style, + match: (token) => token.kind === "String", + update(state, token) { + state.name = token.value.slice(1, -1); + }, + }; } - if (!behavior.addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), { - scroll: false, - origin: "*mouse" - }); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { - setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), { - scroll: false, - origin: "*mouse" + + /***/ + }, + + /***/ "../../graphiql-react/dist/mode.cjs3.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs3.js ***! + \**********************************************/ + /***/ function ( + __unused_webpack_module, + __unused_webpack_exports, + __webpack_require__ + ) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" + ); + const graphqlLanguageService = __webpack_require__( + /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" + ); + const modeIndent = __webpack_require__( + /*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js" + ); + codemirror.CodeMirror.defineMode("graphql-results", (config) => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: (stream) => stream.eatSpace(), + lexRules: LexRules, + parseRules: ParseRules, + editorConfig: { + tabSize: config.tabSize, + }, }); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) { - return; - } - lastPos = pos; - if (behavior.unit == "rectangle") { - var ranges2 = [], - tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), - right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { - var text = getLine(doc, line).text, - leftPos = findColumn(text, left, tabSize); - if (left == right) { - ranges2.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - } else if (text.length > leftPos) { - ranges2.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - } - if (!ranges2.length) { - ranges2.push(new Range(start, start)); - } - setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex), { - origin: "*mouse", - scroll: false - }); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var range3 = rangeForUnit(cm, pos, behavior.unit); - var anchor = oldRange.anchor, - head; - if (cmp(range3.anchor, anchor) > 0) { - head = range3.head; - anchor = minPos(oldRange.from(), range3.anchor); - } else { - head = range3.anchor; - anchor = maxPos(oldRange.to(), range3.head); - } - var ranges$1 = startSel.ranges.slice(0); - ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); - setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); - } - } - var editorSize = display.wrapper.getBoundingClientRect(); - var counter = 0; - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); - if (!cur) { - return; - } - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) { - setTimeout(operation(cm, function () { - if (counter == curCount) { - extend(e); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[}\]]/, + fold: "brace", + closeBrackets: { + pairs: '[]{}""', + explode: "[]{}", + }, + }; + }); + const LexRules = { + Punctuation: /^\[|]|\{|\}|:|,/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, + Keyword: /^true|false|null/, + }; + const ParseRules = { + Document: [ + graphqlLanguageService.p("{"), + graphqlLanguageService.list("Entry", graphqlLanguageService.p(",")), + graphqlLanguageService.p("}"), + ], + Entry: [ + graphqlLanguageService.t("String", "def"), + graphqlLanguageService.p(":"), + "Value", + ], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; } - }), 150); + return null; + case "Keyword": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + case "null": + return "NullValue"; + } + return null; } - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) { - setTimeout(operation(cm, function () { - if (counter != curCount) { - return; + }, + NumberValue: [graphqlLanguageService.t("Number", "number")], + StringValue: [graphqlLanguageService.t("String", "string")], + BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], + NullValue: [graphqlLanguageService.t("Keyword", "keyword")], + ListValue: [ + graphqlLanguageService.p("["), + graphqlLanguageService.list("Value", graphqlLanguageService.p(",")), + graphqlLanguageService.p("]"), + ], + ObjectValue: [ + graphqlLanguageService.p("{"), + graphqlLanguageService.list( + "ObjectField", + graphqlLanguageService.p(",") + ), + graphqlLanguageService.p("}"), + ], + ObjectField: [ + graphqlLanguageService.t("String", "property"), + graphqlLanguageService.p(":"), + "Value", + ], + }; + + /***/ + }, + + /***/ "../../graphiql-react/dist/search.cjs.js": + /*!***********************************************!*\ + !*** ../../graphiql-react/dist/search.cjs.js ***! + \***********************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + const searchcursor = __webpack_require__( + /*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js" + ); + const dialog = __webpack_require__( + /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } } - display.scroller.scrollTop += outside; - extend(e); - }), 50); + } } } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - if (e) { - e_preventDefault(e); - display.input.focus(); - } - off(display.wrapper.ownerDocument, "mousemove", move); - off(display.wrapper.ownerDocument, "mouseup", up); - doc.history.lastSelOrigin = null; - } - var move = operation(cm, function (e) { - if (e.buttons === 0 || !e_button(e)) { - done(e); - } else { - extend(e); - } - }); - var up = operation(cm, done); - cm.state.selectingText = up; - on(display.wrapper.ownerDocument, "mousemove", move); - on(display.wrapper.ownerDocument, "mouseup", up); - } - function bidiSimplify(cm, range2) { - var anchor = range2.anchor; - var head = range2.head; - var anchorLine = getLine(cm.doc, anchor.line); - if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { - return range2; - } - var order = getOrder(anchorLine); - if (!order) { - return range2; - } - var index = getBidiPartAt(order, anchor.ch, anchor.sticky), - part = order[index]; - if (part.from != anchor.ch && part.to != anchor.ch) { - return range2; - } - var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1); - if (boundary == 0 || boundary == order.length) { - return range2; - } - var leftSide; - if (head.line != anchor.line) { - leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; - } else { - var headIndex = getBidiPartAt(order, head.ch, head.sticky); - var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); - if (headIndex == boundary - 1 || headIndex == boundary) { - leftSide = dir < 0; - } else { - leftSide = dir > 0; - } - } - var usePart = order[boundary + (leftSide ? -1 : 0)]; - var from = leftSide == (usePart.level == 1); - var ch = from ? usePart.from : usePart.to, - sticky = from ? "after" : "before"; - return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range(new Pos(anchor.line, ch, sticky), head); - } - function gutterEvent(cm, e, type, prevent) { - var mX, mY; - if (e.touches) { - mX = e.touches[0].clientX; - mY = e.touches[0].clientY; - } else { - try { - mX = e.clientX; - mY = e.clientY; - } catch (e$1) { - return false; - } - } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { - return false; - } - if (prevent) { - e_preventDefault(e); - } - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - if (mY > lineBox.bottom || !hasHandler(cm, type)) { - return e_defaultPrevented(e); - } - mY -= lineBox.top - display.viewOffset; - for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) { - var g = display.gutters.childNodes[i2]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.display.gutterSpecs[i2]; - signal(cm, type, cm, line, gutter.className, e); - return e_defaultPrevented(e); - } - } - } - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true); - } - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { - return; - } - if (signalDOMEvent(cm, e, "contextmenu")) { - return; - } - if (!captureRightClick) { - cm.display.input.onContextMenu(e); - } - } - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) { - return false; - } - return gutterEvent(cm, e, "gutterContextMenu", false); - } - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - var Init = { - toString: function () { - return "CodeMirror.Init"; - } - }; - var defaults = {}; - var optionHandlers = {}; - function defineOptions(CodeMirror2) { - var optionHandlers2 = CodeMirror2.optionHandlers; - function option(name, deflt, handle, notOnInit) { - CodeMirror2.defaults[name] = deflt; - if (handle) { - optionHandlers2[name] = notOnInit ? function (cm, val, old) { - if (old != Init) { - handle(cm, val, old); - } - } : handle; - } - } - CodeMirror2.defineOption = option; - CodeMirror2.Init = Init; - option("value", "", function (cm, val) { - return cm.setValue(val); - }, true); - option("mode", null, function (cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function (cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("lineSeparator", null, function (cm, val) { - cm.doc.lineSep = val; - if (!val) { - return; - } - var newBreaks = [], - lineNo2 = cm.doc.first; - cm.doc.iter(function (line) { - for (var pos = 0;;) { - var found = line.text.indexOf(val, pos); - if (found == -1) { - break; - } - pos = found + val.length; - newBreaks.push(Pos(lineNo2, found)); - } - lineNo2++; - }); - for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) { - replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length)); - } - }); - option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test(" ") ? "" : "| "), "g"); - if (old != Init) { - cm.refresh(); - } - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { - return cm.refresh(); - }, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function () { - throw new Error("inputStyle can not (yet) be changed in a running editor"); - }, true); - option("spellcheck", false, function (cm, val) { - return cm.getInputField().spellcheck = val; - }, true); - option("autocorrect", false, function (cm, val) { - return cm.getInputField().autocorrect = val; - }, true); - option("autocapitalize", false, function (cm, val) { - return cm.getInputField().autocapitalize = val; - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - option("theme", "default", function (cm) { - themeChanged(cm); - updateGutters(cm); - }, true); - option("keyMap", "default", function (cm, val, old) { - var next = getKeyMap(val); - var prev = old != Init && getKeyMap(old); - if (prev && prev.detach) { - prev.detach(cm, next); - } - if (next.attach) { - next.attach(cm, prev || null); - } - }); - option("extraKeys", null); - option("configureMouse", null); - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function (cm, val) { - cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); - updateGutters(cm); - }, true); - option("fixedGutter", true, function (cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function (cm) { - return updateScrollbars(cm); - }, true); - option("scrollbarStyle", "native", function (cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function (cm, val) { - cm.display.gutterSpecs = getGutters(cm.options.gutters, val); - updateGutters(cm); - }, true); - option("firstLineNumber", 1, updateGutters, true); - option("lineNumberFormatter", function (integer) { - return integer; - }, updateGutters, true); - option("showCursorWhenSelecting", false, updateSelection, true); - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - option("pasteLinesPerSelection", true); - option("selectionsMayTouch", false); - option("readOnly", false, function (cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - } - cm.display.input.readOnlyChanged(val); - }); - option("screenReaderLabel", null, function (cm, val) { - val = val === "" ? null : val; - cm.display.input.screenReaderLabelChanged(val); - }); - option("disableInput", false, function (cm, val) { - if (!val) { - cm.display.input.reset(); - } - }, true); - option("dragDrop", true, dragDropChanged); - option("allowDropFileTypes", null); - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function (cm, val) { - return cm.doc.history.undoDepth = val; - }); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function (cm) { - return cm.refresh(); - }, true); - option("maxHighlightLength", 1e4, resetModeState, true); - option("moveInputWithCursor", true, function (cm, val) { - if (!val) { - cm.display.input.resetPosition(); - } - }); - option("tabindex", null, function (cm, val) { - return cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - option("direction", "ltr", function (cm, val) { - return cm.doc.setDirection(val); - }, true); - option("phrases", null); - } - function dragDropChanged(cm, value, old) { - var wasOn = old && old != Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.enter); - toggle(cm.display.scroller, "dragover", funcs.over); - toggle(cm.display.scroller, "dragleave", funcs.leave); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function () { - return updateScrollbars(cm); - }, 100); - } - function CodeMirror(place, options) { - var this$1$1 = this; - if (!(this instanceof CodeMirror)) { - return new CodeMirror(place, options); - } - this.options = options = options ? copyObj(options) : {}; - copyObj(defaults, options, false); - var doc = options.value; - if (typeof doc == "string") { - doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); - } else if (options.mode) { - doc.modeOption = options.mode; - } - this.doc = doc; - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input, options); - display.wrapper.CodeMirror = this; - themeChanged(this); - if (options.lineWrapping) { - this.display.wrapper.className += " CodeMirror-wrap"; - } - initScrollbars(this); - this.state = { - keyMaps: [], - // stores maps added by addKeyMap - overlays: [], - // highlighting overlays, as added by addOverlay - modeGen: 0, - // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, - // used to disable editing during key handlers when in readOnly mode - pasteIncoming: -1, - cutIncoming: -1, - // help recognize paste/cut edits in input.poll - selectingText: false, - draggingText: false, - highlight: new Delayed(), - // stores highlight worker timeout - keySeq: null, - // Unfinished key sequence - specialChars: null + var search$2 = { + exports: {}, }; - if (options.autofocus && !mobile) { - display.input.focus(); - } - if (ie && ie_version < 11) { - setTimeout(function () { - return this$1$1.display.input.reset(true); - }, 20); - } - registerEventHandlers(this); - ensureGlobalHandlers(); - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - if (options.autofocus && !mobile || this.hasFocus()) { - setTimeout(function () { - if (this$1$1.hasFocus() && !this$1$1.state.focused) { - onFocus(this$1$1); - } - }, 20); - } else { - onBlur(this); - } - for (var opt in optionHandlers) { - if (optionHandlers.hasOwnProperty(opt)) { - optionHandlers[opt](this, options[opt], Init); - } - } - maybeUpdateLineNumberWidth(this); - if (options.finishInit) { - options.finishInit(this); - } - for (var i2 = 0; i2 < initHooks.length; ++i2) { - initHooks[i2](this); - } - endOperation(this); - if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { - display.lineDiv.style.textRendering = "auto"; - } - } - CodeMirror.defaults = defaults; - CodeMirror.optionHandlers = optionHandlers; - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - if (ie && ie_version < 11) { - on(d.scroller, "dblclick", operation(cm, function (e) { - if (signalDOMEvent(cm, e)) { - return; + (function (module2, exports2) { + (function (mod) { + mod( + codemirror.requireCodemirror(), + searchcursor.requireSearchcursor(), + dialog.dialogExports + ); + })(function (CodeMirror) { + CodeMirror.defineOption("search", { + bottom: false, + }); + function searchOverlay(query, caseInsensitive) { + if (typeof query == "string") + query = new RegExp( + query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), + caseInsensitive ? "gi" : "g" + ); + else if (!query.global) + query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); + return { + token: function (stream) { + query.lastIndex = stream.pos; + var match = query.exec(stream.string); + if (match && match.index == stream.pos) { + stream.pos += match[0].length || 1; + return "searching"; + } else if (match) { + stream.pos = match.index; + } else { + stream.skipToEnd(); + } + }, + }; } - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { - return; + function SearchState() { + this.posFrom = this.posTo = this.lastQuery = this.query = null; + this.overlay = null; } - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - } else { - on(d.scroller, "dblclick", function (e) { - return signalDOMEvent(cm, e) || e_preventDefault(e); - }); - } - on(d.scroller, "contextmenu", function (e) { - return onContextMenu(cm, e); - }); - on(d.input.getField(), "contextmenu", function (e) { - if (!d.scroller.contains(e.target)) { - onContextMenu(cm, e); - } - }); - var touchFinished, - prevTouch = { - end: 0 - }; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function () { - return d.activeTouch = null; - }, 1e3); - prevTouch = d.activeTouch; - prevTouch.end = + /* @__PURE__ */new Date(); - } - } - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) { - return false; - } - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; - } - function farAway(touch, other) { - if (other.left == null) { - return true; - } - var dx = other.left - touch.left, - dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function (e) { - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { - d.input.ensurePolled(); - clearTimeout(touchFinished); - var now = + /* @__PURE__ */new Date(); - d.activeTouch = { - start: now, - moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null - }; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; + function getSearchState(cm) { + return cm.state.search || (cm.state.search = new SearchState()); } - } - }); - on(d.scroller, "touchmove", function () { - if (d.activeTouch) { - d.activeTouch.moved = true; - } - }); - on(d.scroller, "touchend", function (e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && /* @__PURE__ */new Date() - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), - range2; - if (!touch.prev || farAway(touch, touch.prev)) { - range2 = new Range(pos, pos); - } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) { - range2 = cm.findWordAt(pos); - } else { - range2 = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + function queryCaseInsensitive(query) { + return typeof query == "string" && query == query.toLowerCase(); } - cm.setSelection(range2.anchor, range2.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - on(d.scroller, "scroll", function () { - if (d.scroller.clientHeight) { - updateScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); - on(d.scroller, "mousewheel", function (e) { - return onScrollWheel(cm, e); - }); - on(d.scroller, "DOMMouseScroll", function (e) { - return onScrollWheel(cm, e); - }); - on(d.wrapper, "scroll", function () { - return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; - }); - d.dragFunctions = { - enter: function (e) { - if (!signalDOMEvent(cm, e)) { - e_stop(e); + function getSearchCursor(cm, query, pos) { + return cm.getSearchCursor(query, pos, { + caseFold: queryCaseInsensitive(query), + multiline: true, + }); } - }, - over: function (e) { - if (!signalDOMEvent(cm, e)) { - onDragOver(cm, e); - e_stop(e); + function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { + cm.openDialog(text, onEnter, { + value: deflt, + selectValueOnOpen: true, + closeOnEnter: false, + onClose: function () { + clearSearch(cm); + }, + onKeyDown, + bottom: cm.options.search.bottom, + }); } - }, - start: function (e) { - return onDragStart(cm, e); - }, - drop: operation(cm, onDrop), - leave: function (e) { - if (!signalDOMEvent(cm, e)) { - clearDragCursor(cm); + function dialog2(cm, text, shortText, deflt, f) { + if (cm.openDialog) + cm.openDialog(text, f, { + value: deflt, + selectValueOnOpen: true, + bottom: cm.options.search.bottom, + }); + else f(prompt(shortText, deflt)); } - } - }; - var inp = d.input.getField(); - on(inp, "keyup", function (e) { - return onKeyUp.call(cm, e); - }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", function (e) { - return onFocus(cm, e); - }); - on(inp, "blur", function (e) { - return onBlur(cm, e); - }); - } - var initHooks = []; - CodeMirror.defineInitHook = function (f) { - return initHooks.push(f); - }; - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, - state; - if (how == null) { - how = "add"; - } - if (how == "smart") { - if (!doc.mode.indent) { - how = "prev"; - } else { - state = getContextBefore(cm, n).state; - } - } - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), - curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) { - line.stateAfter = null; - } - var curSpaceString = line.text.match(/^\s*/)[0], - indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) { - return; + function confirmDialog(cm, text, shortText, fs) { + if (cm.openConfirm) cm.openConfirm(text, fs); + else if (confirm(shortText)) fs[0](); } - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) { - indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); - } else { - indentation = 0; - } - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - var indentString = "", - pos = 0; - if (cm.options.indentWithTabs) { - for (var i2 = Math.floor(indentation / tabSize); i2; --i2) { - pos += tabSize; - indentString += " "; - } - } - if (pos < indentation) { - indentString += spaceStr(indentation - pos); - } - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - for (var i$12 = 0; i$12 < doc.sel.ranges.length; i$12++) { - var range2 = doc.sel.ranges[i$12]; - if (range2.head.line == n && range2.head.ch < curSpaceString.length) { - var pos$1 = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i$12, new Range(pos$1, pos$1)); - break; + function parseString(string) { + return string.replace(/\\([nrt\\])/g, function (match, ch) { + if (ch == "n") return "\n"; + if (ch == "r") return "\r"; + if (ch == "t") return " "; + if (ch == "\\") return "\\"; + return match; + }); + } + function parseQuery(query) { + var isRE = query.match(/^\/(.*)\/([a-z]*)$/); + if (isRE) { + try { + query = new RegExp( + isRE[1], + isRE[2].indexOf("i") == -1 ? "" : "i" + ); + } catch (e) {} + } else { + query = parseString(query); + } + if (typeof query == "string" ? query == "" : query.test("")) + query = /x^/; + return query; + } + function startSearch(cm, state, query) { + state.queryText = query; + state.query = parseQuery(query); + cm.removeOverlay( + state.overlay, + queryCaseInsensitive(state.query) + ); + state.overlay = searchOverlay( + state.query, + queryCaseInsensitive(state.query) + ); + cm.addOverlay(state.overlay); + if (cm.showMatchesOnScrollbar) { + if (state.annotate) { + state.annotate.clear(); + state.annotate = null; + } + state.annotate = cm.showMatchesOnScrollbar( + state.query, + queryCaseInsensitive(state.query) + ); + } + } + function doSearch(cm, rev, persistent, immediate) { + var state = getSearchState(cm); + if (state.query) return findNext(cm, rev); + var q = cm.getSelection() || state.lastQuery; + if (q instanceof RegExp && q.source == "x^") q = null; + if (persistent && cm.openDialog) { + var hiding = null; + var searchNext = function (query, event) { + CodeMirror.e_stop(event); + if (!query) return; + if (query != state.queryText) { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + } + if (hiding) hiding.style.opacity = 1; + findNext(cm, event.shiftKey, function (_, to) { + var dialog3; + if ( + to.line < 3 && + document.querySelector && + (dialog3 = + cm.display.wrapper.querySelector( + ".CodeMirror-dialog" + )) && + dialog3.getBoundingClientRect().bottom - 4 > + cm.cursorCoords(to, "window").top + ) + (hiding = dialog3).style.opacity = 0.4; + }); + }; + persistentDialog( + cm, + getQueryDialog(cm), + q, + searchNext, + function (event, query) { + var keyName = CodeMirror.keyName(event); + var extra = cm.getOption("extraKeys"), + cmd = + (extra && extra[keyName]) || + CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; + if ( + cmd == "findNext" || + cmd == "findPrev" || + cmd == "findPersistentNext" || + cmd == "findPersistentPrev" + ) { + CodeMirror.e_stop(event); + startSearch(cm, getSearchState(cm), query); + cm.execCommand(cmd); + } else if (cmd == "find" || cmd == "findPersistent") { + CodeMirror.e_stop(event); + searchNext(query, event); + } + } + ); + if (immediate && q) { + startSearch(cm, state, q); + findNext(cm, rev); + } + } else { + dialog2( + cm, + getQueryDialog(cm), + "Search for:", + q, + function (query) { + if (query && !state.query) + cm.operation(function () { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + findNext(cm, rev); + }); + } + ); + } + } + function findNext(cm, rev, callback) { + cm.operation(function () { + var state = getSearchState(cm); + var cursor = getSearchCursor( + cm, + state.query, + rev ? state.posFrom : state.posTo + ); + if (!cursor.find(rev)) { + cursor = getSearchCursor( + cm, + state.query, + rev + ? CodeMirror.Pos(cm.lastLine()) + : CodeMirror.Pos(cm.firstLine(), 0) + ); + if (!cursor.find(rev)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView( + { + from: cursor.from(), + to: cursor.to(), + }, + 20 + ); + state.posFrom = cursor.from(); + state.posTo = cursor.to(); + if (callback) callback(cursor.from(), cursor.to()); + }); + } + function clearSearch(cm) { + cm.operation(function () { + var state = getSearchState(cm); + state.lastQuery = state.query; + if (!state.query) return; + state.query = state.queryText = null; + cm.removeOverlay(state.overlay); + if (state.annotate) { + state.annotate.clear(); + state.annotate = null; + } + }); + } + function el(tag, attrs) { + var element = tag + ? document.createElement(tag) + : document.createDocumentFragment(); + for (var key in attrs) { + element[key] = attrs[key]; + } + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + element.appendChild( + typeof child == "string" + ? document.createTextNode(child) + : child + ); + } + return element; + } + function getQueryDialog(cm) { + return el( + "", + null, + el( + "span", + { + className: "CodeMirror-search-label", + }, + cm.phrase("Search:") + ), + " ", + el("input", { + type: "text", + style: "width: 10em", + className: "CodeMirror-search-field", + }), + " ", + el( + "span", + { + style: "color: #888", + className: "CodeMirror-search-hint", + }, + cm.phrase("(Use /re/ syntax for regexp search)") + ) + ); + } + function getReplaceQueryDialog(cm) { + return el( + "", + null, + " ", + el("input", { + type: "text", + style: "width: 10em", + className: "CodeMirror-search-field", + }), + " ", + el( + "span", + { + style: "color: #888", + className: "CodeMirror-search-hint", + }, + cm.phrase("(Use /re/ syntax for regexp search)") + ) + ); + } + function getReplacementQueryDialog(cm) { + return el( + "", + null, + el( + "span", + { + className: "CodeMirror-search-label", + }, + cm.phrase("With:") + ), + " ", + el("input", { + type: "text", + style: "width: 10em", + className: "CodeMirror-search-field", + }) + ); + } + function getDoReplaceConfirm(cm) { + return el( + "", + null, + el( + "span", + { + className: "CodeMirror-search-label", + }, + cm.phrase("Replace?") + ), + " ", + el("button", {}, cm.phrase("Yes")), + " ", + el("button", {}, cm.phrase("No")), + " ", + el("button", {}, cm.phrase("All")), + " ", + el("button", {}, cm.phrase("Stop")) + ); + } + function replaceAll(cm, query, text) { + cm.operation(function () { + for ( + var cursor = getSearchCursor(cm, query); + cursor.findNext(); + + ) { + if (typeof query != "string") { + var match = cm + .getRange(cursor.from(), cursor.to()) + .match(query); + cursor.replace( + text.replace(/\$(\d)/g, function (_, i) { + return match[i]; + }) + ); + } else cursor.replace(text); + } + }); + } + function replace(cm, all) { + if (cm.getOption("readOnly")) return; + var query = cm.getSelection() || getSearchState(cm).lastQuery; + var dialogText = all + ? cm.phrase("Replace all:") + : cm.phrase("Replace:"); + var fragment = el( + "", + null, + el( + "span", + { + className: "CodeMirror-search-label", + }, + dialogText + ), + getReplaceQueryDialog(cm) + ); + dialog2(cm, fragment, dialogText, query, function (query2) { + if (!query2) return; + query2 = parseQuery(query2); + dialog2( + cm, + getReplacementQueryDialog(cm), + cm.phrase("Replace with:"), + "", + function (text) { + text = parseString(text); + if (all) { + replaceAll(cm, query2, text); + } else { + clearSearch(cm); + var cursor = getSearchCursor( + cm, + query2, + cm.getCursor("from") + ); + var advance = function () { + var start = cursor.from(), + match; + if (!(match = cursor.findNext())) { + cursor = getSearchCursor(cm, query2); + if ( + !(match = cursor.findNext()) || + (start && + cursor.from().line == start.line && + cursor.from().ch == start.ch) + ) + return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({ + from: cursor.from(), + to: cursor.to(), + }); + confirmDialog( + cm, + getDoReplaceConfirm(cm), + cm.phrase("Replace?"), + [ + function () { + doReplace(match); + }, + advance, + function () { + replaceAll(cm, query2, text); + }, + ] + ); + }; + var doReplace = function (match) { + cursor.replace( + typeof query2 == "string" + ? text + : text.replace(/\$(\d)/g, function (_, i) { + return match[i]; + }) + ); + advance(); + }; + advance(); + } + } + ); + }); + } + CodeMirror.commands.find = function (cm) { + clearSearch(cm); + doSearch(cm); + }; + CodeMirror.commands.findPersistent = function (cm) { + clearSearch(cm); + doSearch(cm, false, true); + }; + CodeMirror.commands.findPersistentNext = function (cm) { + doSearch(cm, false, true, true); + }; + CodeMirror.commands.findPersistentPrev = function (cm) { + doSearch(cm, true, true, true); + }; + CodeMirror.commands.findNext = doSearch; + CodeMirror.commands.findPrev = function (cm) { + doSearch(cm, true); + }; + CodeMirror.commands.clearSearch = clearSearch; + CodeMirror.commands.replace = replace; + CodeMirror.commands.replaceAll = function (cm) { + replace(cm, true); + }; + }); + })(); + var searchExports = search$2.exports; + const search = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(searchExports); + const search$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: search, + }, + [searchExports] + ); + exports.search = search$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/searchcursor.cjs.js": + /*!*****************************************************!*\ + !*** ../../graphiql-react/dist/searchcursor.cjs.js ***! + \*****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + const searchcursor$2 = __webpack_require__( + /*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } + } } } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - } - var lastCopied = null; - function setLastCopied(newLastCopied) { - lastCopied = newLastCopied; - } - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) { - sel = doc.sel; - } - var recent = + /* @__PURE__ */new Date() - 200; - var paste = origin == "paste" || cm.state.pasteIncoming > recent; - var textLines = splitLinesAuto(inserted), - multiPaste = null; - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.text.join("\n") == inserted) { - if (sel.ranges.length % lastCopied.text.length == 0) { - multiPaste = []; - for (var i2 = 0; i2 < lastCopied.text.length; i2++) { - multiPaste.push(doc.splitLines(lastCopied.text[i2])); - } - } - } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { - multiPaste = map(textLines, function (l) { - return [l]; - }); - } - } - var updateInput = cm.curOp.updateInput; - for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) { - var range2 = sel.ranges[i$12]; - var from = range2.from(), - to = range2.to(); - if (range2.empty()) { - if (deleted && deleted > 0) { - from = Pos(from.line, from.ch - deleted); - } else if (cm.state.overwrite && !paste) { - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { - from = to = Pos(from.line, 0); - } - } - var changeEvent = { - from, - to, - text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input") - }; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) { - triggerElectric(cm, inserted); - } - ensureCursorVisible(cm); - if (cm.curOp.updateInput < 2) { - cm.curOp.updateInput = updateInput; - } - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = -1; - } - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) { - runInOp(cm, function () { - return applyTextInput(cm, pasted, 0, null, "paste"); + var searchcursorExports = searchcursor$2.requireSearchcursor(); + const searchcursor = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs( + searchcursorExports + ); + const searchcursor$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: searchcursor, + }, + [searchcursorExports] + ); + exports.searchcursor = searchcursor$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/searchcursor.cjs2.js": + /*!******************************************************!*\ + !*** ../../graphiql-react/dist/searchcursor.cjs2.js ***! + \******************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + var searchcursor = { + exports: {}, + }; + var hasRequiredSearchcursor; + function requireSearchcursor() { + if (hasRequiredSearchcursor) return searchcursor.exports; + hasRequiredSearchcursor = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var Pos = CodeMirror.Pos; + function regexpFlags(regexp) { + var flags = regexp.flags; + return flags != null + ? flags + : (regexp.ignoreCase ? "i" : "") + + (regexp.global ? "g" : "") + + (regexp.multiline ? "m" : ""); + } + function ensureFlags(regexp, flags) { + var current = regexpFlags(regexp), + target = current; + for (var i = 0; i < flags.length; i++) + if (target.indexOf(flags.charAt(i)) == -1) + target += flags.charAt(i); + return current == target + ? regexp + : new RegExp(regexp.source, target); + } + function maybeMultiline(regexp) { + return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); + } + function searchRegexpForward(doc, regexp, start) { + regexp = ensureFlags(regexp, "g"); + for ( + var line = start.line, ch = start.ch, last = doc.lastLine(); + line <= last; + line++, ch = 0 + ) { + regexp.lastIndex = ch; + var string = doc.getLine(line), + match = regexp.exec(string); + if (match) + return { + from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match, + }; + } + } + function searchRegexpForwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) + return searchRegexpForward(doc, regexp, start); + regexp = ensureFlags(regexp, "gm"); + var string, + chunk = 1; + for ( + var line = start.line, last = doc.lastLine(); + line <= last; + + ) { + for (var i = 0; i < chunk; i++) { + if (line > last) break; + var curLine = doc.getLine(line++); + string = string == null ? curLine : string + "\n" + curLine; + } + chunk = chunk * 2; + regexp.lastIndex = start.ch; + var match = regexp.exec(string); + if (match) { + var before = string.slice(0, match.index).split("\n"), + inside = match[0].split("\n"); + var startLine = start.line + before.length - 1, + startCh = before[before.length - 1].length; + return { + from: Pos(startLine, startCh), + to: Pos( + startLine + inside.length - 1, + inside.length == 1 + ? startCh + inside[0].length + : inside[inside.length - 1].length + ), + match, + }; + } + } + } + function lastMatchIn(string, regexp, endMargin) { + var match, + from = 0; + while (from <= string.length) { + regexp.lastIndex = from; + var newMatch = regexp.exec(string); + if (!newMatch) break; + var end = newMatch.index + newMatch[0].length; + if (end > string.length - endMargin) break; + if (!match || end > match.index + match[0].length) + match = newMatch; + from = newMatch.index + 1; + } + return match; + } + function searchRegexpBackward(doc, regexp, start) { + regexp = ensureFlags(regexp, "g"); + for ( + var line = start.line, ch = start.ch, first = doc.firstLine(); + line >= first; + line--, ch = -1 + ) { + var string = doc.getLine(line); + var match = lastMatchIn( + string, + regexp, + ch < 0 ? 0 : string.length - ch + ); + if (match) + return { + from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match, + }; + } + } + function searchRegexpBackwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) + return searchRegexpBackward(doc, regexp, start); + regexp = ensureFlags(regexp, "gm"); + var string, + chunkSize = 1, + endMargin = doc.getLine(start.line).length - start.ch; + for ( + var line = start.line, first = doc.firstLine(); + line >= first; + + ) { + for (var i = 0; i < chunkSize && line >= first; i++) { + var curLine = doc.getLine(line--); + string = string == null ? curLine : curLine + "\n" + string; + } + chunkSize *= 2; + var match = lastMatchIn(string, regexp, endMargin); + if (match) { + var before = string.slice(0, match.index).split("\n"), + inside = match[0].split("\n"); + var startLine = line + before.length, + startCh = before[before.length - 1].length; + return { + from: Pos(startLine, startCh), + to: Pos( + startLine + inside.length - 1, + inside.length == 1 + ? startCh + inside[0].length + : inside[inside.length - 1].length + ), + match, + }; + } + } + } + var doFold, noFold; + if (String.prototype.normalize) { + doFold = function (str) { + return str.normalize("NFD").toLowerCase(); + }; + noFold = function (str) { + return str.normalize("NFD"); + }; + } else { + doFold = function (str) { + return str.toLowerCase(); + }; + noFold = function (str) { + return str; + }; + } + function adjustPos(orig, folded, pos, foldFunc) { + if (orig.length == folded.length) return pos; + for ( + var min = 0, + max = pos + Math.max(0, orig.length - folded.length); + ; + + ) { + if (min == max) return min; + var mid = (min + max) >> 1; + var len = foldFunc(orig.slice(0, mid)).length; + if (len == pos) return mid; + else if (len > pos) max = mid; + else min = mid + 1; + } + } + function searchStringForward(doc, query, start, caseFold) { + if (!query.length) return null; + var fold = caseFold ? doFold : noFold; + var lines = fold(query).split(/\r|\n\r?/); + search: for ( + var line = start.line, + ch = start.ch, + last = doc.lastLine() + 1 - lines.length; + line <= last; + line++, ch = 0 + ) { + var orig = doc.getLine(line).slice(ch), + string = fold(orig); + if (lines.length == 1) { + var found = string.indexOf(lines[0]); + if (found == -1) continue search; + var start = adjustPos(orig, string, found, fold) + ch; + return { + from: Pos( + line, + adjustPos(orig, string, found, fold) + ch + ), + to: Pos( + line, + adjustPos(orig, string, found + lines[0].length, fold) + + ch + ), + }; + } else { + var cutFrom = string.length - lines[0].length; + if (string.slice(cutFrom) != lines[0]) continue search; + for (var i = 1; i < lines.length - 1; i++) + if (fold(doc.getLine(line + i)) != lines[i]) + continue search; + var end = doc.getLine(line + lines.length - 1), + endString = fold(end), + lastLine = lines[lines.length - 1]; + if (endString.slice(0, lastLine.length) != lastLine) + continue search; + return { + from: Pos( + line, + adjustPos(orig, string, cutFrom, fold) + ch + ), + to: Pos( + line + lines.length - 1, + adjustPos(end, endString, lastLine.length, fold) + ), + }; + } + } + } + function searchStringBackward(doc, query, start, caseFold) { + if (!query.length) return null; + var fold = caseFold ? doFold : noFold; + var lines = fold(query).split(/\r|\n\r?/); + search: for ( + var line = start.line, + ch = start.ch, + first = doc.firstLine() - 1 + lines.length; + line >= first; + line--, ch = -1 + ) { + var orig = doc.getLine(line); + if (ch > -1) orig = orig.slice(0, ch); + var string = fold(orig); + if (lines.length == 1) { + var found = string.lastIndexOf(lines[0]); + if (found == -1) continue search; + return { + from: Pos(line, adjustPos(orig, string, found, fold)), + to: Pos( + line, + adjustPos(orig, string, found + lines[0].length, fold) + ), + }; + } else { + var lastLine = lines[lines.length - 1]; + if (string.slice(0, lastLine.length) != lastLine) + continue search; + for ( + var i = 1, start = line - lines.length + 1; + i < lines.length - 1; + i++ + ) + if (fold(doc.getLine(start + i)) != lines[i]) + continue search; + var top = doc.getLine(line + 1 - lines.length), + topString = fold(top); + if ( + topString.slice(topString.length - lines[0].length) != + lines[0] + ) + continue search; + return { + from: Pos( + line + 1 - lines.length, + adjustPos( + top, + topString, + top.length - lines[0].length, + fold + ) + ), + to: Pos( + line, + adjustPos(orig, string, lastLine.length, fold) + ), + }; + } + } + } + function SearchCursor(doc, query, pos, options) { + this.atOccurrence = false; + this.afterEmptyMatch = false; + this.doc = doc; + pos = pos ? doc.clipPos(pos) : Pos(0, 0); + this.pos = { + from: pos, + to: pos, + }; + var caseFold; + if (typeof options == "object") { + caseFold = options.caseFold; + } else { + caseFold = options; + options = null; + } + if (typeof query == "string") { + if (caseFold == null) caseFold = false; + this.matches = function (reverse, pos2) { + return ( + reverse ? searchStringBackward : searchStringForward + )(doc, query, pos2, caseFold); + }; + } else { + query = ensureFlags(query, "gm"); + if (!options || options.multiline !== false) + this.matches = function (reverse, pos2) { + return ( + reverse + ? searchRegexpBackwardMultiline + : searchRegexpForwardMultiline + )(doc, query, pos2); + }; + else + this.matches = function (reverse, pos2) { + return ( + reverse ? searchRegexpBackward : searchRegexpForward + )(doc, query, pos2); + }; + } + } + SearchCursor.prototype = { + findNext: function () { + return this.find(false); + }, + findPrevious: function () { + return this.find(true); + }, + find: function (reverse) { + var head = this.doc.clipPos( + reverse ? this.pos.from : this.pos.to + ); + if (this.afterEmptyMatch && this.atOccurrence) { + head = Pos(head.line, head.ch); + if (reverse) { + head.ch--; + if (head.ch < 0) { + head.line--; + head.ch = (this.doc.getLine(head.line) || "").length; + } + } else { + head.ch++; + if ( + head.ch > (this.doc.getLine(head.line) || "").length + ) { + head.ch = 0; + head.line++; + } + } + if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { + return (this.atOccurrence = false); + } + } + var result = this.matches(reverse, head); + this.afterEmptyMatch = + result && CodeMirror.cmpPos(result.from, result.to) == 0; + if (result) { + this.pos = result; + this.atOccurrence = true; + return this.pos.match || true; + } else { + var end = Pos( + reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, + 0 + ); + this.pos = { + from: end, + to: end, + }; + return (this.atOccurrence = false); + } + }, + from: function () { + if (this.atOccurrence) return this.pos.from; + }, + to: function () { + if (this.atOccurrence) return this.pos.to; + }, + replace: function (newText, origin) { + if (!this.atOccurrence) return; + var lines = CodeMirror.splitLines(newText); + this.doc.replaceRange( + lines, + this.pos.from, + this.pos.to, + origin + ); + this.pos.to = Pos( + this.pos.from.line + lines.length - 1, + lines[lines.length - 1].length + + (lines.length == 1 ? this.pos.from.ch : 0) + ); + }, + }; + CodeMirror.defineExtension( + "getSearchCursor", + function (query, pos, caseFold) { + return new SearchCursor(this.doc, query, pos, caseFold); + } + ); + CodeMirror.defineDocExtension( + "getSearchCursor", + function (query, pos, caseFold) { + return new SearchCursor(this, query, pos, caseFold); + } + ); + CodeMirror.defineExtension( + "selectMatches", + function (query, caseFold) { + var ranges = []; + var cur = this.getSearchCursor( + query, + this.getCursor("from"), + caseFold + ); + while (cur.findNext()) { + if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) + break; + ranges.push({ + anchor: cur.from(), + head: cur.to(), + }); + } + if (ranges.length) this.setSelections(ranges, 0); + } + ); }); - } - return true; + })(); + return searchcursor.exports; } - } - function triggerElectric(cm, inserted) { - if (!cm.options.electricChars || !cm.options.smartIndent) { - return; - } - var sel = cm.doc.sel; - for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { - var range2 = sel.ranges[i2]; - if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) { - continue; - } - var mode = cm.getModeAt(range2.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) { - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range2.head.line, "smart"); - break; + exports.requireSearchcursor = requireSearchcursor; + + /***/ + }, + + /***/ "../../graphiql-react/dist/show-hint.cjs.js": + /*!**************************************************!*\ + !*** ../../graphiql-react/dist/show-hint.cjs.js ***! + \**************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } } } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) { - indented = indentLine(cm, range2.head.line, "smart"); - } - } - if (indented) { - signalLater(cm, "electricInput", cm, range2.head.line); } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); } - } - function copyableRanges(cm) { - var text = [], - ranges = []; - for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { - var line = cm.doc.sel.ranges[i2].head.line; - var lineRange = { - anchor: Pos(line, 0), - head: Pos(line + 1, 0) - }; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return { - text, - ranges + var showHint$2 = { + exports: {}, }; - } - function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { - field.setAttribute("autocorrect", autocorrect ? "" : "off"); - field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); - field.setAttribute("spellcheck", !!spellcheck); - } - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - if (webkit) { - te.style.width = "1000px"; - } else { - te.setAttribute("wrap", "off"); - } - if (ios) { - te.style.border = "1px solid black"; - } - disableBrowserMagic(te); - return div; - } - function addEditorMethods(CodeMirror2) { - var optionHandlers2 = CodeMirror2.optionHandlers; - var helpers = CodeMirror2.helpers = {}; - CodeMirror2.prototype = { - constructor: CodeMirror2, - focus: function () { - window.focus(); - this.display.input.focus(); - }, - setOption: function (option, value) { - var options = this.options, - old = options[option]; - if (options[option] == value && option != "mode") { - return; - } - options[option] = value; - if (optionHandlers2.hasOwnProperty(option)) { - operation(this, optionHandlers2[option])(this, value, old); - } - signal(this, "optionChange", this, option); - }, - getOption: function (option) { - return this.options[option]; - }, - getDoc: function () { - return this.doc; - }, - addKeyMap: function (map2, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map2)); - }, - removeKeyMap: function (map2) { - var maps = this.state.keyMaps; - for (var i2 = 0; i2 < maps.length; ++i2) { - if (maps[i2] == map2 || maps[i2].name == map2) { - maps.splice(i2, 1); - return true; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var HINT_ELEMENT_CLASS = "CodeMirror-hint"; + var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; + CodeMirror.showHint = function (cm, getHints, options) { + if (!getHints) return cm.showHint(options); + if (options && options.async) getHints.async = true; + var newOpts = { + hint: getHints, + }; + if (options) + for (var prop in options) newOpts[prop] = options[prop]; + return cm.showHint(newOpts); + }; + CodeMirror.defineExtension("showHint", function (options) { + options = parseOptions(this, this.getCursor("start"), options); + var selections = this.listSelections(); + if (selections.length > 1) return; + if (this.somethingSelected()) { + if (!options.hint.supportsSelection) return; + for (var i = 0; i < selections.length; i++) + if (selections[i].head.line != selections[i].anchor.line) + return; } - } - }, - addOverlay: methodOp(function (spec, options) { - var mode = spec.token ? spec : CodeMirror2.getMode(this.options, spec); - if (mode.startState) { - throw new Error("Overlays may not be stateful."); - } - insertSorted(this.state.overlays, { - mode, - modeSpec: spec, - opaque: options && options.opaque, - priority: options && options.priority || 0 - }, function (overlay) { - return overlay.priority; + if (this.state.completionActive) + this.state.completionActive.close(); + var completion = (this.state.completionActive = new Completion( + this, + options + )); + if (!completion.options.hint) return; + CodeMirror.signal(this, "startCompletion", this); + completion.update(true); }); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function (spec) { - var overlays = this.state.overlays; - for (var i2 = 0; i2 < overlays.length; ++i2) { - var cur = overlays[i2].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i2, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - indentLine: methodOp(function (n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) { - dir = this.options.smartIndent ? "smart" : "prev"; - } else { - dir = dir ? "add" : "subtract"; + CodeMirror.defineExtension("closeHint", function () { + if (this.state.completionActive) + this.state.completionActive.close(); + }); + function Completion(cm, options) { + this.cm = cm; + this.options = options; + this.widget = null; + this.debounce = 0; + this.tick = 0; + this.startPos = this.cm.getCursor("start"); + this.startLen = + this.cm.getLine(this.startPos.line).length - + this.cm.getSelection().length; + if (this.options.updateOnCursorActivity) { + var self = this; + cm.on( + "cursorActivity", + (this.activityFunc = function () { + self.cursorActivity(); + }) + ); } } - if (isLine(this.doc, n)) { - indentLine(this, n, dir, aggressive); - } - }), - indentSelection: methodOp(function (how) { - var ranges = this.doc.sel.ranges, - end = -1; - for (var i2 = 0; i2 < ranges.length; i2++) { - var range2 = ranges[i2]; - if (!range2.empty()) { - var from = range2.from(), - to = range2.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) { - indentLine(this, j, how); - } - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) { - replaceOneSelection(this.doc, i2, new Range(from, newRanges[i2].to()), sel_dontScroll); - } - } else if (range2.head.line > end) { - indentLine(this, range2.head.line, how, true); - end = range2.head.line; - if (i2 == this.doc.sel.primIndex) { - ensureCursorVisible(this); + var requestAnimationFrame = + window.requestAnimationFrame || + function (fn) { + return setTimeout(fn, 1e3 / 60); + }; + var cancelAnimationFrame = + window.cancelAnimationFrame || clearTimeout; + Completion.prototype = { + close: function () { + if (!this.active()) return; + this.cm.state.completionActive = null; + this.tick = null; + if (this.options.updateOnCursorActivity) { + this.cm.off("cursorActivity", this.activityFunc); } - } - } - }), - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function (pos, precise) { - return takeToken(this, pos, precise); - }, - getLineTokens: function (line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - getTokenTypeAt: function (pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, - after = (styles.length - 1) / 2, - ch = pos.ch; - var type; - if (ch == 0) { - type = styles[2]; - } else { - for (;;) { - var mid = before + after >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { - after = mid; - } else if (styles[mid * 2 + 1] < ch) { - before = mid + 1; + if (this.widget && this.data) + CodeMirror.signal(this.data, "close"); + if (this.widget) this.widget.close(); + CodeMirror.signal(this.cm, "endCompletion", this.cm); + }, + active: function () { + return this.cm.state.completionActive == this; + }, + pick: function (data, i) { + var completion = data.list[i], + self = this; + this.cm.operation(function () { + if (completion.hint) + completion.hint(self.cm, data, completion); + else + self.cm.replaceRange( + getText(completion), + completion.from || data.from, + completion.to || data.to, + "complete" + ); + CodeMirror.signal(data, "pick", completion); + self.cm.scrollIntoView(); + }); + if (this.options.closeOnPick) { + this.close(); + } + }, + cursorActivity: function () { + if (this.debounce) { + cancelAnimationFrame(this.debounce); + this.debounce = 0; + } + var identStart = this.startPos; + if (this.data) { + identStart = this.data.from; + } + var pos = this.cm.getCursor(), + line = this.cm.getLine(pos.line); + if ( + pos.line != this.startPos.line || + line.length - pos.ch != this.startLen - this.startPos.ch || + pos.ch < identStart.ch || + this.cm.somethingSelected() || + !pos.ch || + this.options.closeCharacters.test(line.charAt(pos.ch - 1)) + ) { + this.close(); } else { - type = styles[mid * 2 + 2]; - break; + var self = this; + this.debounce = requestAnimationFrame(function () { + self.update(); + }); + if (this.widget) this.widget.disable(); + } + }, + update: function (first) { + if (this.tick == null) return; + var self = this, + myTick = ++this.tick; + fetchHints( + this.options.hint, + this.cm, + this.options, + function (data) { + if (self.tick == myTick) self.finishUpdate(data, first); + } + ); + }, + finishUpdate: function (data, first) { + if (this.data) CodeMirror.signal(this.data, "update"); + var picked = + (this.widget && this.widget.picked) || + (first && this.options.completeSingle); + if (this.widget) this.widget.close(); + this.data = data; + if (data && data.list.length) { + if (picked && data.list.length == 1) { + this.pick(data, 0); + } else { + this.widget = new Widget(this, data); + CodeMirror.signal(data, "shown"); + } } + }, + }; + function parseOptions(cm, pos, options) { + var editor = cm.options.hintOptions; + var out = {}; + for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; + if (editor) { + for (var prop in editor) + if (editor[prop] !== void 0) out[prop] = editor[prop]; } + if (options) { + for (var prop in options) + if (options[prop] !== void 0) out[prop] = options[prop]; + } + if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); + return out; } - var cut = type ? type.indexOf("overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - getModeAt: function (pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { - return mode; - } - return CodeMirror2.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - getHelper: function (pos, type) { - return this.getHelpers(pos, type)[0]; - }, - getHelpers: function (pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) { - return found; + function getText(completion) { + if (typeof completion == "string") return completion; + else return completion.text; } - var help = helpers[type], - mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) { - found.push(help[mode[type]]); + function buildKeyMap(completion, handle) { + var baseMap = { + Up: function () { + handle.moveFocus(-1); + }, + Down: function () { + handle.moveFocus(1); + }, + PageUp: function () { + handle.moveFocus(-handle.menuSize() + 1, true); + }, + PageDown: function () { + handle.moveFocus(handle.menuSize() - 1, true); + }, + Home: function () { + handle.setFocus(0); + }, + End: function () { + handle.setFocus(handle.length - 1); + }, + Enter: handle.pick, + Tab: handle.pick, + Esc: handle.close, + }; + var mac = /Mac/.test(navigator.platform); + if (mac) { + baseMap["Ctrl-P"] = function () { + handle.moveFocus(-1); + }; + baseMap["Ctrl-N"] = function () { + handle.moveFocus(1); + }; } - } else if (mode[type]) { - for (var i2 = 0; i2 < mode[type].length; i2++) { - var val = help[mode[type][i2]]; - if (val) { - found.push(val); - } + var custom = completion.options.customKeys; + var ourMap = custom ? {} : baseMap; + function addBinding(key2, val) { + var bound; + if (typeof val != "string") + bound = function (cm) { + return val(cm, handle); + }; + else if (baseMap.hasOwnProperty(val)) bound = baseMap[val]; + else bound = val; + ourMap[key2] = bound; } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i$12 = 0; i$12 < help._global.length; i$12++) { - var cur = help._global[i$12]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { - found.push(cur.val); + if (custom) { + for (var key in custom) + if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); + } + var extra = completion.options.extraKeys; + if (extra) { + for (var key in extra) + if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); } + return ourMap; } - return found; - }, - getStateAfter: function (line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); - return getContextBefore(this, line + 1, precise).state; - }, - cursorCoords: function (start, mode) { - var pos, - range2 = this.doc.sel.primary(); - if (start == null) { - pos = range2.head; - } else if (typeof start == "object") { - pos = clipPos(this.doc, start); - } else { - pos = start ? range2.from() : range2.to(); - } - return cursorCoords(this, pos, mode || "page"); - }, - charCoords: function (pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - coordsChar: function (coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - lineAtHeight: function (height, mode) { - height = fromCoordSystem(this, { - top: height, - left: 0 - }, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function (line, mode, includeWidgets) { - var end = false, - lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) { - line = this.doc.first; - } else if (line > last) { - line = last; - end = true; - } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; + function getHintElement(hintsElement, el) { + while (el && el != hintsElement) { + if ( + el.nodeName.toUpperCase() === "LI" && + el.parentNode == hintsElement + ) + return el; + el = el.parentNode; + } } - return intoCoordSystem(this, lineObj, { - top: 0, - left: 0 - }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, - defaultTextHeight: function () { - return textHeight(this.display); - }, - defaultCharWidth: function () { - return charWidth(this.display); - }, - getViewport: function () { - return { - from: this.display.viewFrom, - to: this.display.viewTo - }; - }, - addWidget: function (pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, - left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { - top = pos.top - node.offsetHeight; - } else if (pos.bottom + node.offsetHeight <= vspace) { - top = pos.bottom; - } - if (left + node.offsetWidth > hspace) { - left = hspace - node.offsetWidth; - } - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") { - left = 0; - } else if (horiz == "middle") { - left = (display.sizer.clientWidth - node.offsetWidth) / 2; - } - node.style.left = left + "px"; - } - if (scroll) { - scrollIntoView(this, { - left, - top, - right: left + node.offsetWidth, - bottom: top + node.offsetHeight + function Widget(completion, data) { + this.id = "cm-complete-" + Math.floor(Math.random(1e6)); + this.completion = completion; + this.data = data; + this.picked = false; + var widget = this, + cm = completion.cm; + var ownerDocument = cm.getInputField().ownerDocument; + var parentWindow = + ownerDocument.defaultView || ownerDocument.parentWindow; + var hints = (this.hints = ownerDocument.createElement("ul")); + hints.setAttribute("role", "listbox"); + hints.setAttribute("aria-expanded", "true"); + hints.id = this.id; + var theme = completion.cm.options.theme; + hints.className = "CodeMirror-hints " + theme; + this.selectedHint = data.selectedHint || 0; + var completions = data.list; + for (var i = 0; i < completions.length; ++i) { + var elt = hints.appendChild(ownerDocument.createElement("li")), + cur = completions[i]; + var className = + HINT_ELEMENT_CLASS + + (i != this.selectedHint + ? "" + : " " + ACTIVE_HINT_ELEMENT_CLASS); + if (cur.className != null) + className = cur.className + " " + className; + elt.className = className; + if (i == this.selectedHint) + elt.setAttribute("aria-selected", "true"); + elt.id = this.id + "-" + i; + elt.setAttribute("role", "option"); + if (cur.render) cur.render(elt, data, cur); + else + elt.appendChild( + ownerDocument.createTextNode( + cur.displayText || getText(cur) + ) + ); + elt.hintId = i; + } + var container = + completion.options.container || ownerDocument.body; + var pos = cm.cursorCoords( + completion.options.alignWithWord ? data.from : null + ); + var left = pos.left, + top = pos.bottom, + below = true; + var offsetLeft = 0, + offsetTop = 0; + if (container !== ownerDocument.body) { + var isContainerPositioned = + ["absolute", "relative", "fixed"].indexOf( + parentWindow.getComputedStyle(container).position + ) !== -1; + var offsetParent = isContainerPositioned + ? container + : container.offsetParent; + var offsetParentPosition = offsetParent.getBoundingClientRect(); + var bodyPosition = ownerDocument.body.getBoundingClientRect(); + offsetLeft = + offsetParentPosition.left - + bodyPosition.left - + offsetParent.scrollLeft; + offsetTop = + offsetParentPosition.top - + bodyPosition.top - + offsetParent.scrollTop; + } + hints.style.left = left - offsetLeft + "px"; + hints.style.top = top - offsetTop + "px"; + var winW = + parentWindow.innerWidth || + Math.max( + ownerDocument.body.offsetWidth, + ownerDocument.documentElement.offsetWidth + ); + var winH = + parentWindow.innerHeight || + Math.max( + ownerDocument.body.offsetHeight, + ownerDocument.documentElement.offsetHeight + ); + container.appendChild(hints); + cm.getInputField().setAttribute("aria-autocomplete", "list"); + cm.getInputField().setAttribute("aria-owns", this.id); + cm.getInputField().setAttribute( + "aria-activedescendant", + this.id + "-" + this.selectedHint + ); + var box = completion.options.moveOnOverlap + ? hints.getBoundingClientRect() + : new DOMRect(); + var scrolls = completion.options.paddingForScrollbar + ? hints.scrollHeight > hints.clientHeight + 1 + : false; + var startScroll; + setTimeout(function () { + startScroll = cm.getScrollInfo(); + }); + var overlapY = box.bottom - winH; + if (overlapY > 0) { + var height = box.bottom - box.top, + curTop = pos.top - (pos.bottom - box.top); + if (curTop - height > 0) { + hints.style.top = (top = pos.top - height - offsetTop) + "px"; + below = false; + } else if (height > winH) { + hints.style.height = winH - 5 + "px"; + hints.style.top = + (top = pos.bottom - box.top - offsetTop) + "px"; + var cursor = cm.getCursor(); + if (data.from.ch != cursor.ch) { + pos = cm.cursorCoords(cursor); + hints.style.left = (left = pos.left - offsetLeft) + "px"; + box = hints.getBoundingClientRect(); + } + } + } + var overlapX = box.right - winW; + if (scrolls) overlapX += cm.display.nativeBarWidth; + if (overlapX > 0) { + if (box.right - box.left > winW) { + hints.style.width = winW - 5 + "px"; + overlapX -= box.right - box.left - winW; + } + hints.style.left = + (left = pos.left - overlapX - offsetLeft) + "px"; + } + if (scrolls) + for (var node = hints.firstChild; node; node = node.nextSibling) + node.style.paddingRight = cm.display.nativeBarWidth + "px"; + cm.addKeyMap( + (this.keyMap = buildKeyMap(completion, { + moveFocus: function (n, avoidWrap) { + widget.changeActive(widget.selectedHint + n, avoidWrap); + }, + setFocus: function (n) { + widget.changeActive(n); + }, + menuSize: function () { + return widget.screenAmount(); + }, + length: completions.length, + close: function () { + completion.close(); + }, + pick: function () { + widget.pick(); + }, + data, + })) + ); + if (completion.options.closeOnUnfocus) { + var closingOnBlur; + cm.on( + "blur", + (this.onBlur = function () { + closingOnBlur = setTimeout(function () { + completion.close(); + }, 100); + }) + ); + cm.on( + "focus", + (this.onFocus = function () { + clearTimeout(closingOnBlur); + }) + ); + } + cm.on( + "scroll", + (this.onScroll = function () { + var curScroll = cm.getScrollInfo(), + editor = cm.getWrapperElement().getBoundingClientRect(); + if (!startScroll) startScroll = cm.getScrollInfo(); + var newTop = top + startScroll.top - curScroll.top; + var point = + newTop - + (parentWindow.pageYOffset || + (ownerDocument.documentElement || ownerDocument.body) + .scrollTop); + if (!below) point += hints.offsetHeight; + if (point <= editor.top || point >= editor.bottom) + return completion.close(); + hints.style.top = newTop + "px"; + hints.style.left = + left + startScroll.left - curScroll.left + "px"; + }) + ); + CodeMirror.on(hints, "dblclick", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + widget.pick(); + } + }); + CodeMirror.on(hints, "click", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + if (completion.options.completeOnSingleClick) widget.pick(); + } }); + CodeMirror.on(hints, "mousedown", function () { + setTimeout(function () { + cm.focus(); + }, 20); + }); + var selectedHintRange = this.getSelectedHintRange(); + if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { + this.scrollToActive(); + } + CodeMirror.signal( + data, + "select", + completions[this.selectedHint], + hints.childNodes[this.selectedHint] + ); + return true; } - }, - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - execCommand: function (cmd) { - if (commands.hasOwnProperty(cmd)) { - return commands[cmd].call(null, this); + Widget.prototype = { + close: function () { + if (this.completion.widget != this) return; + this.completion.widget = null; + if (this.hints.parentNode) + this.hints.parentNode.removeChild(this.hints); + this.completion.cm.removeKeyMap(this.keyMap); + var input = this.completion.cm.getInputField(); + input.removeAttribute("aria-activedescendant"); + input.removeAttribute("aria-owns"); + var cm = this.completion.cm; + if (this.completion.options.closeOnUnfocus) { + cm.off("blur", this.onBlur); + cm.off("focus", this.onFocus); + } + cm.off("scroll", this.onScroll); + }, + disable: function () { + this.completion.cm.removeKeyMap(this.keyMap); + var widget = this; + this.keyMap = { + Enter: function () { + widget.picked = true; + }, + }; + this.completion.cm.addKeyMap(this.keyMap); + }, + pick: function () { + this.completion.pick(this.data, this.selectedHint); + }, + changeActive: function (i, avoidWrap) { + if (i >= this.data.list.length) + i = avoidWrap ? this.data.list.length - 1 : 0; + else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; + if (this.selectedHint == i) return; + var node = this.hints.childNodes[this.selectedHint]; + if (node) { + node.className = node.className.replace( + " " + ACTIVE_HINT_ELEMENT_CLASS, + "" + ); + node.removeAttribute("aria-selected"); + } + node = this.hints.childNodes[(this.selectedHint = i)]; + node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; + node.setAttribute("aria-selected", "true"); + this.completion.cm + .getInputField() + .setAttribute("aria-activedescendant", node.id); + this.scrollToActive(); + CodeMirror.signal( + this.data, + "select", + this.data.list[this.selectedHint], + node + ); + }, + scrollToActive: function () { + var selectedHintRange = this.getSelectedHintRange(); + var node1 = this.hints.childNodes[selectedHintRange.from]; + var node2 = this.hints.childNodes[selectedHintRange.to]; + var firstNode = this.hints.firstChild; + if (node1.offsetTop < this.hints.scrollTop) + this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop; + else if ( + node2.offsetTop + node2.offsetHeight > + this.hints.scrollTop + this.hints.clientHeight + ) + this.hints.scrollTop = + node2.offsetTop + + node2.offsetHeight - + this.hints.clientHeight + + firstNode.offsetTop; + }, + screenAmount: function () { + return ( + Math.floor( + this.hints.clientHeight / this.hints.firstChild.offsetHeight + ) || 1 + ); + }, + getSelectedHintRange: function () { + var margin = this.completion.options.scrollMargin || 0; + return { + from: Math.max(0, this.selectedHint - margin), + to: Math.min( + this.data.list.length - 1, + this.selectedHint + margin + ), + }; + }, + }; + function applicableHelpers(cm, helpers) { + if (!cm.somethingSelected()) return helpers; + var result = []; + for (var i = 0; i < helpers.length; i++) + if (helpers[i].supportsSelection) result.push(helpers[i]); + return result; } - }, - triggerElectric: methodOp(function (text) { - triggerElectric(this, text); - }), - findPosH: function (from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i2 = 0; i2 < amount; ++i2) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) { - break; + function fetchHints(hint, cm, options, callback) { + if (hint.async) { + hint(cm, callback, options); + } else { + var result = hint(cm, options); + if (result && result.then) result.then(callback); + else callback(result); } } - return cur; - }, - moveH: methodOp(function (dir, unit) { - var this$1$1 = this; - this.extendSelectionsBy(function (range2) { - if (this$1$1.display.shift || this$1$1.doc.extend || range2.empty()) { - return findPosH(this$1$1.doc, range2.head, dir, unit, this$1$1.options.rtlMoveVisually); + function resolveAutoHints(cm, pos) { + var helpers = cm.getHelpers(pos, "hint"), + words; + if (helpers.length) { + var resolved = function (cm2, callback, options) { + var app = applicableHelpers(cm2, helpers); + function run(i) { + if (i == app.length) return callback(null); + fetchHints(app[i], cm2, options, function (result) { + if (result && result.list.length > 0) callback(result); + else run(i + 1); + }); + } + run(0); + }; + resolved.async = true; + resolved.supportsSelection = true; + return resolved; + } else if ((words = cm.getHelper(cm.getCursor(), "hintWords"))) { + return function (cm2) { + return CodeMirror.hint.fromList(cm2, { + words, + }); + }; + } else if (CodeMirror.hint.anyword) { + return function (cm2, options) { + return CodeMirror.hint.anyword(cm2, options); + }; } else { - return dir < 0 ? range2.from() : range2.to(); + return function () {}; } - }, sel_move); - }), - deleteH: methodOp(function (dir, unit) { - var sel = this.doc.sel, - doc = this.doc; - if (sel.somethingSelected()) { - doc.replaceSelection("", null, "+delete"); - } else { - deleteNearSelection(this, function (range2) { - var other = findPosH(doc, range2.head, dir, unit, false); - return dir < 0 ? { - from: other, - to: range2.head - } : { - from: range2.head, - to: other - }; - }); } - }), - findPosV: function (from, amount, unit, goalColumn) { - var dir = 1, - x = goalColumn; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i2 = 0; i2 < amount; ++i2) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) { - x = coords.left; - } else { - coords.left = x; + CodeMirror.registerHelper("hint", "auto", { + resolve: resolveAutoHints, + }); + CodeMirror.registerHelper( + "hint", + "fromList", + function (cm, options) { + var cur = cm.getCursor(), + token = cm.getTokenAt(cur); + var term, + from = CodeMirror.Pos(cur.line, token.start), + to = cur; + if ( + token.start < cur.ch && + /\w/.test(token.string.charAt(cur.ch - token.start - 1)) + ) { + term = token.string.substr(0, cur.ch - token.start); + } else { + term = ""; + from = cur; + } + var found = []; + for (var i = 0; i < options.words.length; i++) { + var word = options.words[i]; + if (word.slice(0, term.length) == term) found.push(word); + } + if (found.length) + return { + list: found, + from, + to, + }; } - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) { - break; + ); + CodeMirror.commands.autocomplete = CodeMirror.showHint; + var defaultOptions = { + hint: CodeMirror.hint.auto, + completeSingle: true, + alignWithWord: true, + closeCharacters: /[\s()\[\]{};:>,]/, + closeOnPick: true, + closeOnUnfocus: true, + updateOnCursorActivity: true, + completeOnSingleClick: true, + container: null, + customKeys: null, + extraKeys: null, + paddingForScrollbar: true, + moveOnOverlap: true, + }; + CodeMirror.defineOption("hintOptions", null); + }); + })(); + var showHintExports = showHint$2.exports; + const showHint = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(showHintExports); + const showHint$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: showHint, + }, + [showHintExports] + ); + exports.showHint = showHint$1; + + /***/ + }, + + /***/ "../../graphiql-react/dist/sublime.cjs.js": + /*!************************************************!*\ + !*** ../../graphiql-react/dist/sublime.cjs.js ***! + \************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + const codemirror = __webpack_require__( + /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" + ); + const searchcursor = __webpack_require__( + /*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js" + ); + const matchbrackets = __webpack_require__( + /*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js" + ); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: () => e[k], + } + ); + } + } } } - return cur; - }, - moveV: methodOp(function (dir, unit) { - var this$1$1 = this; - var doc = this.doc, - goals = []; - var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function (range2) { - if (collapse) { - return dir < 0 ? range2.from() : range2.to(); + } + return Object.freeze( + Object.defineProperty(n, Symbol.toStringTag, { + value: "Module", + }) + ); + } + var sublime$2 = { + exports: {}, + }; + (function (module2, exports2) { + (function (mod) { + mod( + codemirror.requireCodemirror(), + searchcursor.requireSearchcursor(), + matchbrackets.requireMatchbrackets() + ); + })(function (CodeMirror) { + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) + return doc.clipPos(Pos(start.line - 1)); + var line = doc.getLine(start.line); + if (dir > 0 && start.ch >= line.length) + return doc.clipPos(Pos(start.line + 1, 0)); + var state = "start", + type, + startPos = start.ch; + for ( + var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; + pos != e; + pos += dir, i++ + ) { + var next = line.charAt(dir < 0 ? pos - 1 : pos); + var cat = + next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { + state = "in"; + type = cat; + } else startPos = pos + dir; + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { + if (pos == startPos + 1) { + type = "w"; + continue; + } else pos--; + } + break; + } + } + } + return Pos(start.line, pos); + } + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function (range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosSubword(cm.doc, range.head, dir); + else return dir < 0 ? range.from() : range.to(); + }); + } + cmds.goSubwordLeft = function (cm) { + moveSubword(cm, -1); + }; + cmds.goSubwordRight = function (cm) { + moveSubword(cm, 1); + }; + cmds.scrollLineUp = function (cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight( + info.top + info.clientHeight, + "local" + ); + if (cm.getCursor().line >= visibleBottomLine) + cm.execCommand("goLineUp"); } - var headPos = cursorCoords(this$1$1, range2.head, "div"); - if (range2.goalColumn != null) { - headPos.left = range2.goalColumn; + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds.scrollLineDown = function (cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; + if (cm.getCursor().line <= visibleTopLine) + cm.execCommand("goLineDown"); } - goals.push(headPos.left); - var pos = findPosV(this$1$1, headPos, dir, unit); - if (unit == "page" && range2 == doc.sel.primary()) { - addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top); + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + cmds.splitSelectionByLine = function (cm) { + var ranges = cm.listSelections(), + lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), + to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) + if (!(to.line > from.line && line == to.line && to.ch == 0)) + lineRanges.push({ + anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line), + }); } - return pos; - }, sel_move); - if (goals.length) { - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - doc.sel.ranges[i2].goalColumn = goals[i2]; + cm.setSelections(lineRanges, 0); + }; + cmds.singleSelectionTop = function (cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, { + scroll: false, + }); + }; + cmds.selectLine = function (cm) { + var ranges = cm.listSelections(), + extended = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + extended.push({ + anchor: Pos(range.from().line, 0), + head: Pos(range.to().line + 1, 0), + }); } + cm.setSelections(extended); + }; + function insertLine(cm, above) { + if (cm.isReadOnly()) return CodeMirror.Pass; + cm.operation(function () { + var len = cm.listSelections().length, + newSelection = [], + last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({ + head: at, + anchor: at, + }); + last = head.line + 1; + } + cm.setSelections(newSelection); + }); + cm.execCommand("indentAuto"); } - }), - // Find the word at the given position (as returned by coordsChar). - findWordAt: function (pos) { - var doc = this.doc, - line = getLine(doc, pos.line).text; - var start = pos.ch, - end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.sticky == "before" || end == line.length) && start) { + cmds.insertLineAfter = function (cm) { + return insertLine(cm, false); + }; + cmds.insertLineBefore = function (cm) { + return insertLine(cm, true); + }; + function wordAt(cm, pos) { + var start = pos.ch, + end = start, + line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; - } else { + while ( + end < line.length && + CodeMirror.isWordChar(line.charAt(end)) + ) ++end; - } - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) ? function (ch) { - return isWordChar(ch, helper); - } : /\s/.test(startChar) ? function (ch) { - return /\s/.test(ch); - } : function (ch) { - return !/\s/.test(ch) && !isWordChar(ch); + return { + from: Pos(pos.line, start), + to: Pos(pos.line, end), + word: line.slice(start, end), }; - while (start > 0 && check(line.charAt(start - 1))) { - --start; + } + cmds.selectNextOccurrence = function (cm) { + var from = cm.getCursor("from"), + to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + var found = cur.findNext(); + if (!found) { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + found = cur.findNext(); + } + if ( + !found || + isSelectedRange(cm.listSelections(), cur.from(), cur.to()) + ) + return; + cm.addSelection(cur.from(), cur.to()); } - while (end < line.length && check(line.charAt(end))) { - ++end; + if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; + }; + cmds.skipAndSelectNextOccurrence = function (cm) { + var prevAnchor = cm.getCursor("anchor"), + prevHead = cm.getCursor("head"); + cmds.selectNextOccurrence(cm); + if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { + cm.doc.setSelections( + cm.doc.listSelections().filter(function (sel) { + return sel.anchor != prevAnchor || sel.head != prevHead; + }) + ); } - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - toggleOverwrite: function (value) { - if (value != null && value == this.state.overwrite) { - return; - } - if (this.state.overwrite = !this.state.overwrite) { - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } else { - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function () { - return this.display.input.getField() == activeElt(); - }, - isReadOnly: function () { - return !!(this.options.readOnly || this.doc.cantEdit); - }, - scrollTo: methodOp(function (x, y) { - scrollToCoords(this, x, y); - }), - getScrollInfo: function () { - var scroller = this.display.scroller; - return { - left: scroller.scrollLeft, - top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), - clientWidth: displayWidth(this) }; - }, - scrollIntoView: methodOp(function (range2, margin) { - if (range2 == null) { - range2 = { - from: this.doc.sel.primary().head, - to: null - }; - if (margin == null) { - margin = this.options.cursorScrollMargin; + function addCursorToSelection(cm, dir) { + var ranges = cm.listSelections(), + newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var newAnchor = cm.findPosV( + range.anchor, + dir, + "line", + range.anchor.goalColumn + ); + var newHead = cm.findPosV( + range.head, + dir, + "line", + range.head.goalColumn + ); + newAnchor.goalColumn = + range.anchor.goalColumn != null + ? range.anchor.goalColumn + : cm.cursorCoords(range.anchor, "div").left; + newHead.goalColumn = + range.head.goalColumn != null + ? range.head.goalColumn + : cm.cursorCoords(range.head, "div").left; + var newRange = { + anchor: newAnchor, + head: newHead, + }; + newRanges.push(range); + newRanges.push(newRange); } - } else if (typeof range2 == "number") { - range2 = { - from: Pos(range2, 0), - to: null - }; - } else if (range2.from == null) { - range2 = { - from: range2, - to: null - }; - } - if (!range2.to) { - range2.to = range2.from; - } - range2.margin = margin || 0; - if (range2.from.line != null) { - scrollToRange(this, range2); - } else { - scrollToCoordsRange(this, range2.from, range2.to, range2.margin); + cm.setSelections(newRanges); } - }), - setSize: methodOp(function (width, height) { - var this$1$1 = this; - var interpret = function (val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + cmds.addCursorToPrevLine = function (cm) { + addCursorToSelection(cm, -1); }; - if (width != null) { - this.display.wrapper.style.width = interpret(width); - } - if (height != null) { - this.display.wrapper.style.height = interpret(height); - } - if (this.options.lineWrapping) { - clearLineMeasurementCache(this); - } - var lineNo2 = this.display.viewFrom; - this.doc.iter(lineNo2, this.display.viewTo, function (line) { - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; i2++) { - if (line.widgets[i2].noHScroll) { - regLineChange(this$1$1, lineNo2, "widget"); - break; - } - } - } - ++lineNo2; - }); - this.curOp.forceUpdate = true; - signal(this, "refresh", this); - }), - operation: function (f) { - return runInOp(this, f); - }, - startOperation: function () { - return startOperation(this); - }, - endOperation: function () { - return endOperation(this); - }, - refresh: methodOp(function () { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this.display); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) { - estimateLineHeights(this); - } - signal(this, "refresh", this); - }), - swapDoc: methodOp(function (doc) { - var old = this.doc; - old.cm = null; - if (this.state.selectingText) { - this.state.selectingText(); - } - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - scrollToCoords(this, doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - phrase: function (phraseText) { - var phrases = this.options.phrases; - return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText; - }, - getInputField: function () { - return this.display.input.getField(); - }, - getWrapperElement: function () { - return this.display.wrapper; - }, - getScrollerElement: function () { - return this.display.scroller; - }, - getGutterElement: function () { - return this.display.gutters; - } - }; - eventMixin(CodeMirror2); - CodeMirror2.registerHelper = function (type, name, value) { - if (!helpers.hasOwnProperty(type)) { - helpers[type] = CodeMirror2[type] = { - _global: [] + cmds.addCursorToNextLine = function (cm) { + addCursorToSelection(cm, 1); }; - } - helpers[type][name] = value; - }; - CodeMirror2.registerGlobalHelper = function (type, name, predicate, value) { - CodeMirror2.registerHelper(type, name, value); - helpers[type]._global.push({ - pred: predicate, - val: value - }); - }; - } - function findPosH(doc, pos, dir, unit, visually) { - var oldPos = pos; - var origDir = dir; - var lineObj = getLine(doc, pos.line); - var lineDir = visually && doc.direction == "rtl" ? -dir : dir; - function findNextLine() { - var l = pos.line + lineDir; - if (l < doc.first || l >= doc.first + doc.size) { - return false; - } - pos = new Pos(l, pos.ch, pos.sticky); - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next; - if (unit == "codepoint") { - var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); - if (isNaN(ch)) { - next = null; - } else { - var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343; - next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); - } - } else if (visually) { - next = moveVisually(doc.cm, lineObj, pos, dir); - } else { - next = moveLogically(lineObj, pos, dir); - } - if (next == null) { - if (!boundToLine && findNextLine()) { - pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); - } else { + function isSelectedRange(ranges, from, to) { + for (var i = 0; i < ranges.length; i++) + if ( + CodeMirror.cmpPos(ranges[i].from(), from) == 0 && + CodeMirror.cmpPos(ranges[i].to(), to) == 0 + ) + return true; return false; } - } else { - pos = next; - } - return true; - } - if (unit == "char" || unit == "codepoint") { - moveOnce(); - } else if (unit == "column") { - moveOnce(true); - } else if (unit == "word" || unit == "group") { - var sawType = null, - group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) { - break; - } - var cur = lineObj.text.charAt(pos.ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; - if (group && !first && !type) { - type = "s"; - } - if (sawType && sawType != type) { - if (dir < 0) { - dir = 1; - moveOnce(); - pos.sticky = "after"; + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var ranges = cm.listSelections(), + newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + pos = range.head, + opening = cm.scanForBracket(pos, -1); + if (!opening) return false; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return false; + if ( + closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1) + ) { + var startPos = Pos(opening.pos.line, opening.pos.ch + 1); + if ( + CodeMirror.cmpPos(startPos, range.from()) == 0 && + CodeMirror.cmpPos(closing.pos, range.to()) == 0 + ) { + opening = cm.scanForBracket(opening.pos, -1); + if (!opening) return false; + } else { + newRanges.push({ + anchor: startPos, + head: closing.pos, + }); + break; + } + } + pos = Pos(closing.pos.line, closing.pos.ch + 1); + } } - break; - } - if (type) { - sawType = type; - } - if (dir > 0 && !moveOnce(!first)) { - break; - } - } - } - var result = skipAtomic(doc, pos, oldPos, origDir, true); - if (equalCursorPos(oldPos, result)) { - result.hitSide = true; - } - return result; - } - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, - x = pos.left, - y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - var target; - for (;;) { - target = coordsChar(cm, x, y); - if (!target.outside) { - break; - } - if (dir < 0 ? y <= 0 : y >= doc.height) { - target.hitSide = true; - break; - } - y += dir * 5; - } - return target; - } - var ContentEditableInput = function (cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.composing = null; - this.gracePeriod = false; - this.readDOMTimeout = null; - }; - ContentEditableInput.prototype.init = function (display) { - var this$1$1 = this; - var input = this, - cm = input.cm; - var div = input.div = display.lineDiv; - div.contentEditable = true; - disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); - function belongsToInput(e) { - for (var t = e.target; t; t = t.parentNode) { - if (t == div) { + cm.setSelections(newRanges); return true; } - if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { - break; - } - } - return false; - } - on(div, "paste", function (e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; - } - if (ie_version <= 11) { - setTimeout(operation(cm, function () { - return this$1$1.updateFromDOM(); - }), 20); - } - }); - on(div, "compositionstart", function (e) { - this$1$1.composing = { - data: e.data, - done: false - }; - }); - on(div, "compositionupdate", function (e) { - if (!this$1$1.composing) { - this$1$1.composing = { - data: e.data, - done: false + cmds.selectScope = function (cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); }; - } - }); - on(div, "compositionend", function (e) { - if (this$1$1.composing) { - if (e.data != this$1$1.composing.data) { - this$1$1.readFromDOMSoon(); - } - this$1$1.composing.done = true; - } - }); - on(div, "touchstart", function () { - return input.forceCompositionEnd(); - }); - on(div, "input", function () { - if (!this$1$1.composing) { - this$1$1.readFromDOMSoon(); - } - }); - function onCopyCut(e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e)) { - return; - } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections() - }); - if (e.type == "cut") { - cm.replaceSelection("", null, "cut"); + cmds.selectBetweenBrackets = function (cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + function puncType(type) { + return !type + ? null + : /\bpunctuation\b/.test(type) + ? type + : void 0; } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text - }); - if (e.type == "cut") { + cmds.goToBracket = function (cm) { + cm.extendSelectionsBy(function (range) { + var next = cm.scanForBracket( + range.head, + 1, + puncType(cm.getTokenTypeAt(range.head)) + ); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) + return next.pos; + var prev = cm.scanForBracket( + range.head, + -1, + puncType( + cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)) + ) + ); + return ( + (prev && Pos(prev.pos.line, prev.pos.ch + 1)) || range.head + ); + }); + }; + cmds.swapLineUp = function (cm) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + linesToMove = [], + at = cm.firstLine() - 1, + newSels = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + from = range.from().line - 1, + to = range.to().line; + newSels.push({ + anchor: Pos(range.anchor.line - 1, range.anchor.ch), + head: Pos(range.head.line - 1, range.head.ch), + }); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to); + else if (linesToMove.length) + linesToMove[linesToMove.length - 1] = to; + at = to; + } cm.operation(function () { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); + for (var i2 = 0; i2 < linesToMove.length; i2 += 2) { + var from2 = linesToMove[i2], + to2 = linesToMove[i2 + 1]; + var line = cm.getLine(from2); + cm.replaceRange( + "", + Pos(from2, 0), + Pos(from2 + 1, 0), + "+swapLine" + ); + if (to2 > cm.lastLine()) + cm.replaceRange( + "\n" + line, + Pos(cm.lastLine()), + null, + "+swapLine" + ); + else + cm.replaceRange( + line + "\n", + Pos(to2, 0), + null, + "+swapLine" + ); + } + cm.setSelections(newSels); + cm.scrollIntoView(); }); - } - } - if (e.clipboardData) { - e.clipboardData.clearData(); - var content = lastCopied.text.join("\n"); - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return; - } - } - var kludge = hiddenTextarea(), - te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.text.join("\n"); - var hadFocus = activeElt(); - selectInput(te); - setTimeout(function () { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) { - input.showPrimarySelection(); - } - }, 50); - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }; - ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { - if (label) { - this.div.setAttribute("aria-label", label); - } else { - this.div.removeAttribute("aria-label"); - } - }; - ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = activeElt() == this.div; - return result; - }; - ContentEditableInput.prototype.showSelection = function (info, takeFocus) { - if (!info || !this.cm.display.view.length) { - return; - } - if (info.focus || takeFocus) { - this.showPrimarySelection(); - } - this.showMultipleSelections(info); - }; - ContentEditableInput.prototype.getSelection = function () { - return this.cm.display.wrapper.ownerDocument.getSelection(); - }; - ContentEditableInput.prototype.showPrimarySelection = function () { - var sel = this.getSelection(), - cm = this.cm, - prim = cm.doc.sel.primary(); - var from = prim.from(), - to = prim.to(); - if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { - sel.removeAllRanges(); - return; - } - var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { - return; - } - var view = cm.display.view; - var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { - node: view[0].measure.map[2], - offset: 0 - }; - var end = to.line < cm.display.viewTo && posToDOM(cm, to); - if (!end) { - var measure = view[view.length - 1].measure; - var map2 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = { - node: map2[map2.length - 1], - offset: map2[map2.length - 2] - map2[map2.length - 3] - }; - } - if (!start || !end) { - sel.removeAllRanges(); - return; - } - var old = sel.rangeCount && sel.getRangeAt(0), - rng; - try { - rng = range(start.node, start.offset, end.offset, end.node); - } catch (e) {} - if (rng) { - if (!gecko && cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) { - sel.removeAllRanges(); - sel.addRange(rng); - } - } else { - sel.removeAllRanges(); - sel.addRange(rng); - } - if (old && sel.anchorNode == null) { - sel.addRange(old); - } else if (gecko) { - this.startGracePeriod(); - } - } - this.rememberSelection(); - }; - ContentEditableInput.prototype.startGracePeriod = function () { - var this$1$1 = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function () { - this$1$1.gracePeriod = false; - if (this$1$1.selectionChanged()) { - this$1$1.cm.operation(function () { - return this$1$1.cm.curOp.selectionChanged = true; - }); - } - }, 20); - }; - ContentEditableInput.prototype.showMultipleSelections = function (info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }; - ContentEditableInput.prototype.rememberSelection = function () { - var sel = this.getSelection(); - this.lastAnchorNode = sel.anchorNode; - this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; - this.lastFocusOffset = sel.focusOffset; - }; - ContentEditableInput.prototype.selectionInEditor = function () { - var sel = this.getSelection(); - if (!sel.rangeCount) { - return false; - } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }; - ContentEditableInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor") { - if (!this.selectionInEditor() || activeElt() != this.div) { - this.showSelection(this.prepareSelection(), true); - } - this.div.focus(); - } - }; - ContentEditableInput.prototype.blur = function () { - this.div.blur(); - }; - ContentEditableInput.prototype.getField = function () { - return this.div; - }; - ContentEditableInput.prototype.supportsTouch = function () { - return true; - }; - ContentEditableInput.prototype.receivedFocus = function () { - var this$1$1 = this; - var input = this; - if (this.selectionInEditor()) { - setTimeout(function () { - return this$1$1.pollSelection(); - }, 20); - } else { - runInOp(this.cm, function () { - return input.cm.curOp.selectionChanged = true; - }); - } - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }; - ContentEditableInput.prototype.selectionChanged = function () { - var sel = this.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }; - ContentEditableInput.prototype.pollSelection = function () { - if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { - return; - } - var sel = this.getSelection(), - cm = this.cm; - if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { - this.cm.triggerOnKeyDown({ - type: "keydown", - keyCode: 8, - preventDefault: Math.abs - }); - this.blur(); - this.focus(); - return; - } - if (this.composing) { - return; - } - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) { - runInOp(cm, function () { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) { - cm.curOp.selectionChanged = true; - } - }); - } - }; - ContentEditableInput.prototype.pollContent = function () { - if (this.readDOMTimeout != null) { - clearTimeout(this.readDOMTimeout); - this.readDOMTimeout = null; - } - var cm = this.cm, - display = cm.display, - sel = cm.doc.sel.primary(); - var from = sel.from(), - to = sel.to(); - if (from.ch == 0 && from.line > cm.firstLine()) { - from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); - } - if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { - to = Pos(to.line + 1, 0); - } - if (from.line < display.viewFrom || to.line > display.viewTo - 1) { - return false; - } - var fromIndex, fromLine, fromNode; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - fromLine = lineNo(display.view[0].line); - fromNode = display.view[0].node; - } else { - fromLine = lineNo(display.view[fromIndex].line); - fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - var toLine, toNode; - if (toIndex == display.view.length - 1) { - toLine = display.viewTo - 1; - toNode = display.lineDiv.lastChild; - } else { - toLine = lineNo(display.view[toIndex + 1].line) - 1; - toNode = display.view[toIndex + 1].node.previousSibling; - } - if (!fromNode) { - return false; - } - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { - newText.pop(); - oldText.pop(); - toLine--; - } else if (newText[0] == oldText[0]) { - newText.shift(); - oldText.shift(); - fromLine++; - } else { - break; - } - } - var cutFront = 0, - cutEnd = 0; - var newTop = newText[0], - oldTop = oldText[0], - maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { - ++cutFront; - } - var newBot = lst(newText), - oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - ++cutEnd; - } - if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { - while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - cutFront--; - cutEnd++; - } - } - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; - } - }; - ContentEditableInput.prototype.ensurePolled = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.reset = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.forceCompositionEnd = function () { - if (!this.composing) { - return; - } - clearTimeout(this.readDOMTimeout); - this.composing = null; - this.updateFromDOM(); - this.div.blur(); - this.div.focus(); - }; - ContentEditableInput.prototype.readFromDOMSoon = function () { - var this$1$1 = this; - if (this.readDOMTimeout != null) { - return; - } - this.readDOMTimeout = setTimeout(function () { - this$1$1.readDOMTimeout = null; - if (this$1$1.composing) { - if (this$1$1.composing.done) { - this$1$1.composing = null; - } else { - return; - } - } - this$1$1.updateFromDOM(); - }, 80); - }; - ContentEditableInput.prototype.updateFromDOM = function () { - var this$1$1 = this; - if (this.cm.isReadOnly() || !this.pollContent()) { - runInOp(this.cm, function () { - return regChange(this$1$1.cm); - }); - } - }; - ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; - }; - ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { - return; - } - e.preventDefault(); - if (!this.cm.isReadOnly()) { - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); - } - }; - ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); - }; - ContentEditableInput.prototype.onContextMenu = function () {}; - ContentEditableInput.prototype.resetPosition = function () {}; - ContentEditableInput.prototype.needsContentAttribute = true; - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) { - return null; - } - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - var order = getOrder(line, cm.doc.direction), - side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; - } - function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) { - if (/CodeMirror-gutter-wrapper/.test(scan.className)) { - return true; - } - } - return false; - } - function badPos(pos, bad) { - if (bad) { - pos.bad = true; - } - return pos; - } - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", - closing = false, - lineSep = cm.doc.lineSeparator(), - extraLinebreak = false; - function recognizeMarker(id) { - return function (marker) { - return marker.id == id; - }; - } - function close() { - if (closing) { - text += lineSep; - if (extraLinebreak) { - text += lineSep; - } - closing = extraLinebreak = false; - } - } - function addText(str) { - if (str) { - close(); - text += str; - } - } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText) { - addText(cmText); - return; - } - var markerID = node.getAttribute("cm-marker"), - range2; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range2 = found[0].find(0))) { - addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep)); + }; + cmds.swapLineDown = function (cm) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + linesToMove = [], + at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], + from = range.to().line + 1, + to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to); + else if (linesToMove.length) + linesToMove[linesToMove.length - 1] = to; + at = to; } - return; - } - if (node.getAttribute("contenteditable") == "false") { - return; - } - var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); - if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { - return; - } - if (isBlock) { - close(); - } - for (var i2 = 0; i2 < node.childNodes.length; i2++) { - walk(node.childNodes[i2]); - } - if (/^(pre|p)$/i.test(node.nodeName)) { - extraLinebreak = true; - } - if (isBlock) { - closing = true; - } - } else if (node.nodeType == 3) { - addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); - } - } - for (;;) { - walk(from); - if (from == to) { - break; - } - from = from.nextSibling; - extraLinebreak = false; - } - return text; - } - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) { - return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - } - node = null; - offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) { - return null; - } - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { - break; - } - } - } - for (var i2 = 0; i2 < cm.display.view.length; i2++) { - var lineView = cm.display.view[i2]; - if (lineView.node == lineNode) { - return locateNodeInLineView(lineView, node, offset); - } - } - } - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, - bad = false; - if (!node || !contains(wrapper, node)) { - return badPos(Pos(lineNo(lineView.line), 0), true); - } - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); - } - } - var textNode = node.nodeType == 3 ? node : null, - topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) { - offset = textNode.nodeValue.length; - } - } - while (topNode.parentNode != wrapper) { - topNode = topNode.parentNode; - } - var measure = lineView.measure, - maps = measure.maps; - function find(textNode2, topNode2, offset2) { - for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { - var map2 = i2 < 0 ? measure.map : maps[i2]; - for (var j = 0; j < map2.length; j += 3) { - var curNode = map2[j + 2]; - if (curNode == textNode2 || curNode == topNode2) { - var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]); - var ch = map2[j] + offset2; - if (offset2 < 0 || curNode != textNode2) { - ch = map2[j + (offset2 ? 1 : 0)]; + cm.operation(function () { + for (var i2 = linesToMove.length - 2; i2 >= 0; i2 -= 2) { + var from2 = linesToMove[i2], + to2 = linesToMove[i2 + 1]; + var line = cm.getLine(from2); + if (from2 == cm.lastLine()) + cm.replaceRange( + "", + Pos(from2 - 1), + Pos(from2), + "+swapLine" + ); + else + cm.replaceRange( + "", + Pos(from2, 0), + Pos(from2 + 1, 0), + "+swapLine" + ); + cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + cmds.toggleCommentIndented = function (cm) { + cm.toggleComment({ + indent: true, + }); + }; + cmds.joinLines = function (cm) { + var ranges = cm.listSelections(), + joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + from = range.from(); + var start = from.line, + end = range.to().line; + while ( + i < ranges.length - 1 && + ranges[i + 1].from().line == end + ) + end = ranges[++i].to().line; + joined.push({ + start, + end, + anchor: !range.empty() && from, + }); + } + cm.operation(function () { + var offset = 0, + ranges2 = []; + for (var i2 = 0; i2 < joined.length; i2++) { + var obj = joined[i2]; + var anchor = + obj.anchor && + Pos(obj.anchor.line - offset, obj.anchor.ch), + head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (line == obj.end) + head = Pos(actual, cm.getLine(actual).length + 1); + if (actual < cm.lastLine()) { + cm.replaceRange( + " ", + Pos(actual), + Pos( + actual + 1, + /^\s*/.exec(cm.getLine(actual + 1))[0].length + ) + ); + ++offset; + } + } + ranges2.push({ + anchor: anchor || head, + head, + }); + } + cm.setSelections(ranges2, 0); + }); + }; + cmds.duplicateLine = function (cm) { + cm.operation(function () { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) + cm.replaceRange( + cm.getLine(range.head.line) + "\n", + Pos(range.head.line, 0) + ); + else + cm.replaceRange( + cm.getRange(range.from(), range.to()), + range.from() + ); } - return Pos(line2, ch); + cm.scrollIntoView(); + }); + }; + function sortLines(cm, caseSensitive, direction) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + toSort = [], + selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, + to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) + to = ranges[++i].to().line; + if (!ranges[i].to().ch) to--; + toSort.push(from, to); } + if (toSort.length) selected = true; + else toSort.push(cm.firstLine(), cm.lastLine()); + cm.operation(function () { + var ranges2 = []; + for (var i2 = 0; i2 < toSort.length; i2 += 2) { + var from2 = toSort[i2], + to2 = toSort[i2 + 1]; + var start = Pos(from2, 0), + end = Pos(to2); + var lines = cm.getRange(start, end, false); + if (caseSensitive) + lines.sort(function (a, b) { + return a < b ? -direction : a == b ? 0 : direction; + }); + else + lines.sort(function (a, b) { + var au = a.toUpperCase(), + bu = b.toUpperCase(); + if (au != bu) { + a = au; + b = bu; + } + return a < b ? -direction : a == b ? 0 : direction; + }); + cm.replaceRange(lines, start, end); + if (selected) + ranges2.push({ + anchor: start, + head: Pos(to2 + 1, 0), + }); + } + if (selected) cm.setSelections(ranges2, 0); + }); } - } - } - var found = find(textNode, topNode, offset); - if (found) { - return badPos(found, bad); - } - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) { - return badPos(Pos(found.line, found.ch - dist), bad); - } else { - dist += after.textContent.length; - } - } - for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) { - return badPos(Pos(found.line, found.ch + dist$1), bad); - } else { - dist$1 += before.textContent.length; - } - } - } - var TextareaInput = function (cm) { - this.cm = cm; - this.prevInput = ""; - this.pollingFast = false; - this.polling = new Delayed(); - this.hasSelection = false; - this.composing = null; - }; - TextareaInput.prototype.init = function (display) { - var this$1$1 = this; - var input = this, - cm = this.cm; - this.createField(display); - var te = this.textarea; - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); - if (ios) { - te.style.width = "0px"; - } - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1$1.hasSelection) { - this$1$1.hasSelection = null; - } - input.poll(); - }); - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; - } - cm.state.pasteIncoming = + /* @__PURE__ */new Date(); - input.fastPoll(); - }); - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) { - return; - } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections() - }); - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text - }); - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); + cmds.sortLines = function (cm) { + sortLines(cm, true, 1); + }; + cmds.reverseSortLines = function (cm) { + sortLines(cm, true, -1); + }; + cmds.sortLinesInsensitive = function (cm) { + sortLines(cm, false, 1); + }; + cmds.reverseSortLinesInsensitive = function (cm) { + sortLines(cm, false, -1); + }; + cmds.nextBookmark = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) + while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); + } + } + }; + cmds.prevBookmark = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) + while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) marks.pop(); + else return cm.setSelection(found.from, found.to); + } + }; + cmds.toggleBookmark = function (cm) { + var ranges = cm.listSelections(); + var marks = + cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), + to = ranges[i].to(); + var found = ranges[i].empty() + ? cm.findMarksAt(from) + : cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) + if (marks[k] == found[j]) marks.splice(k--, 1); + break; + } + } + if (j == found.length) + marks.push( + cm.markText(from, to, { + sublimeBookmark: true, + clearWhenEmpty: false, + }) + ); + } + }; + cmds.clearBookmarks = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) + for (var i = 0; i < marks.length; i++) marks[i].clear(); + marks.length = 0; + }; + cmds.selectBookmarks = function (cm) { + var marks = cm.state.sublimeBookmarks, + ranges = []; + if (marks) + for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) marks.splice(i--, 0); + else + ranges.push({ + anchor: found.from, + head: found.to, + }); + } + if (ranges.length) cm.setSelections(ranges, 0); + }; + function modifyWordOrSelection(cm, mod) { + cm.operation(function () { + var ranges = cm.listSelections(), + indices = [], + replacements = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) { + indices.push(i); + replacements.push(""); + } else + replacements.push( + mod(cm.getRange(range.from(), range.to())) + ); + } + cm.replaceSelections(replacements, "around", "case"); + for (var i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); } - } - if (e.type == "cut") { - cm.state.cutIncoming = + /* @__PURE__ */new Date(); - } - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - on(display.scroller, "paste", function (e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { - return; - } - if (!te.dispatchEvent) { - cm.state.pasteIncoming = + /* @__PURE__ */new Date(); - input.focus(); - return; - } - var event = new Event("paste"); - event.clipboardData = e.clipboardData; - te.dispatchEvent(event); - }); - on(display.lineSpace, "selectstart", function (e) { - if (!eventInWidget(display, e)) { - e_preventDefault(e); - } - }); - on(te, "compositionstart", function () { - var start = cm.getCursor("from"); - if (input.composing) { - input.composing.range.clear(); - } - input.composing = { - start, - range: cm.markText(start, cm.getCursor("to"), { - className: "CodeMirror-composing" - }) - }; - }); - on(te, "compositionend", function () { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }; - TextareaInput.prototype.createField = function (_display) { - this.wrapper = hiddenTextarea(); - this.textarea = this.wrapper.firstChild; - }; - TextareaInput.prototype.screenReaderLabelChanged = function (label) { - if (label) { - this.textarea.setAttribute("aria-label", label); - } else { - this.textarea.removeAttribute("aria-label"); - } - }; - TextareaInput.prototype.prepareSelection = function () { - var cm = this.cm, - display = cm.display, - doc = cm.doc; - var result = prepareSelection(cm); - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), - lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); - } - return result; - }; - TextareaInput.prototype.showSelection = function (drawn) { - var cm = this.cm, - display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }; - TextareaInput.prototype.reset = function (typing) { - if (this.contextMenuPending || this.composing) { - return; - } - var cm = this.cm; - if (cm.somethingSelected()) { - this.prevInput = ""; - var content = cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) { - selectInput(this.textarea); - } - if (ie && ie_version >= 9) { - this.hasSelection = content; - } - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) { - this.hasSelection = null; - } - } - }; - TextareaInput.prototype.getField = function () { - return this.textarea; - }; - TextareaInput.prototype.supportsTouch = function () { - return false; - }; - TextareaInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { - this.textarea.focus(); - } catch (e) {} - } - }; - TextareaInput.prototype.blur = function () { - this.textarea.blur(); - }; - TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; - }; - TextareaInput.prototype.receivedFocus = function () { - this.slowPoll(); - }; - TextareaInput.prototype.slowPoll = function () { - var this$1$1 = this; - if (this.pollingFast) { - return; - } - this.polling.set(this.cm.options.pollInterval, function () { - this$1$1.poll(); - if (this$1$1.cm.state.focused) { - this$1$1.slowPoll(); - } - }); - }; - TextareaInput.prototype.fastPoll = function () { - var missed = false, - input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) { - missed = true; - input.polling.set(60, p); - } else { - input.pollingFast = false; - input.slowPoll(); - } - } - input.polling.set(20, p); - }; - TextareaInput.prototype.poll = function () { - var this$1$1 = this; - var cm = this.cm, - input = this.textarea, - prevInput = this.prevInput; - if (this.contextMenuPending || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { - return false; - } - var text = input.value; - if (text == prevInput && !cm.somethingSelected()) { - return false; - } - if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; - } - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 8203 && !prevInput) { - prevInput = "​"; - } - if (first == 8666) { - this.reset(); - return this.cm.execCommand("undo"); - } - } - var same = 0, - l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { - ++same; - } - runInOp(cm, function () { - applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1$1.composing ? "*compose" : null); - if (text.length > 1e3 || text.indexOf("\n") > -1) { - input.value = this$1$1.prevInput = ""; - } else { - this$1$1.prevInput = text; - } - if (this$1$1.composing) { - this$1$1.composing.range.clear(); - this$1$1.composing.range = cm.markText(this$1$1.composing.start, cm.getCursor("to"), { - className: "CodeMirror-composing" - }); - } - }); - return true; - }; - TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { - this.pollingFast = false; - } - }; - TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { - this.hasSelection = null; - } - this.fastPoll(); - }; - TextareaInput.prototype.onContextMenu = function (e) { - var input = this, - cm = input.cm, - display = cm.display, - te = input.textarea; - if (input.contextMenuPending) { - input.contextMenuPending(); - } - var pos = posFromMouse(cm, e), - scrollPos = display.scroller.scrollTop; - if (!pos || presto) { - return; - } - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) { - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); - } - var oldCSS = te.style.cssText, - oldWrapperCSS = input.wrapper.style.cssText; - var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); - input.wrapper.style.cssText = "position: static"; - te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - var oldScrollY; - if (webkit) { - oldScrollY = window.scrollY; - } - display.input.focus(); - if (webkit) { - window.scrollTo(null, oldScrollY); - } - display.input.reset(); - if (!cm.somethingSelected()) { - te.value = input.prevInput = " "; - } - input.contextMenuPending = rehide; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "​" + (selected ? te.value : ""); - te.value = "⇚"; - te.value = extval; - input.prevInput = selected ? "" : "​"; - te.selectionStart = 1; - te.selectionEnd = extval.length; - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - if (input.contextMenuPending != rehide) { - return; - } - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) { - display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - } - if (te.selectionStart != null) { - if (!ie || ie && ie_version < 9) { - prepareSelectAllHack(); - } - var i2 = 0, - poll = function () { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "​") { - operation(cm, selectAll)(cm); - } else if (i2++ < 10) { - display.detectingSelectAll = setTimeout(poll, 500); - } else { - display.selForContextMenu = null; - display.input.reset(); + cmds.smartBackspace = function (cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + cm.operation(function () { + var cursors = cm.listSelections(); + var indentUnit = cm.getOption("indentUnit"); + for (var i = cursors.length - 1; i >= 0; i--) { + var cursor = cursors[i].head; + var toStartOfLine = cm.getRange( + { + line: cursor.line, + ch: 0, + }, + cursor + ); + var column = CodeMirror.countColumn( + toStartOfLine, + null, + cm.getOption("tabSize") + ); + var deletePos = cm.findPosH(cursor, -1, "char", false); + if ( + toStartOfLine && + !/\S/.test(toStartOfLine) && + column % indentUnit == 0 + ) { + var prevIndent = new Pos( + cursor.line, + CodeMirror.findColumn( + toStartOfLine, + column - indentUnit, + indentUnit + ) + ); + if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + } + cm.replaceRange("", deletePos, cursor, "+delete"); } + }); + }; + cmds.delLineRight = function (cm) { + cm.operation(function () { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) + cm.replaceRange( + "", + ranges[i].anchor, + Pos(ranges[i].to().line), + "+delete" + ); + cm.scrollIntoView(); + }); + }; + cmds.upcaseAtCursor = function (cm) { + modifyWordOrSelection(cm, function (str) { + return str.toUpperCase(); + }); + }; + cmds.downcaseAtCursor = function (cm) { + modifyWordOrSelection(cm, function (str) { + return str.toLowerCase(); + }); + }; + cmds.setSublimeMark = function (cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds.selectToSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds.deleteToSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + var from = cm.getCursor(), + to = found; + if (CodeMirror.cmpPos(from, to) > 0) { + var tmp = to; + to = from; + from = tmp; + } + cm.state.sublimeKilled = cm.getRange(from, to); + cm.replaceRange("", from, to); + } + }; + cmds.swapWithSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + cm.setCursor(found); + } + }; + cmds.sublimeYank = function (cm) { + if (cm.state.sublimeKilled != null) + cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + cmds.showInCenter = function (cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo( + null, + (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2 + ); + }; + function getTarget(cm) { + var from = cm.getCursor("from"), + to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + from = word.from; + to = word.to; + } + return { + from, + to, + query: cm.getRange(from, to), + word, }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - if (ie && ie_version >= 9) { - prepareSelectAllHack(); - } - if (captureRightClick) { - e_stop(e); - var mouseup = function () { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }; - TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { - this.reset(); - } - this.textarea.disabled = val == "nocursor"; - this.textarea.readOnly = !!val; - }; - TextareaInput.prototype.setUneditable = function () {}; - TextareaInput.prototype.needsContentAttribute = false; - function fromTextArea(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) { - options.tabindex = textarea.tabIndex; - } - if (!options.placeholder && textarea.placeholder) { - options.placeholder = textarea.placeholder; - } - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - function save() { - textarea.value = cm.getValue(); - } - var realSubmit; - if (textarea.form) { - on(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form; - realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function () { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch (e) {} - } - } - options.finishInit = function (cm2) { - cm2.save = save; - cm2.getTextArea = function () { - return textarea; - }; - cm2.toTextArea = function () { - cm2.toTextArea = isNaN; - save(); - textarea.parentNode.removeChild(cm2.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { - textarea.form.submit = realSubmit; + } + function findAndGoTo(cm, forward) { + var target = getTarget(cm); + if (!target) return; + var query = target.query; + var cur = cm.getSearchCursor( + query, + forward ? target.to : target.from + ); + if (forward ? cur.findNext() : cur.findPrevious()) { + cm.setSelection(cur.from(), cur.to()); + } else { + cur = cm.getSearchCursor( + query, + forward + ? Pos(cm.firstLine(), 0) + : cm.clipPos(Pos(cm.lastLine())) + ); + if (forward ? cur.findNext() : cur.findPrevious()) + cm.setSelection(cur.from(), cur.to()); + else if (target.word) cm.setSelection(target.from, target.to); } } - }; - }; - textarea.style.display = "none"; - var cm = CodeMirror(function (node) { - return textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - } - function addLegacyProps(CodeMirror2) { - CodeMirror2.off = off; - CodeMirror2.on = on; - CodeMirror2.wheelEventPixels = wheelEventPixels; - CodeMirror2.Doc = Doc; - CodeMirror2.splitLines = splitLinesAuto; - CodeMirror2.countColumn = countColumn; - CodeMirror2.findColumn = findColumn; - CodeMirror2.isWordChar = isWordCharBasic; - CodeMirror2.Pass = Pass; - CodeMirror2.signal = signal; - CodeMirror2.Line = Line; - CodeMirror2.changeEnd = changeEnd; - CodeMirror2.scrollbarModel = scrollbarModel; - CodeMirror2.Pos = Pos; - CodeMirror2.cmpPos = cmp; - CodeMirror2.modes = modes; - CodeMirror2.mimeModes = mimeModes; - CodeMirror2.resolveMode = resolveMode; - CodeMirror2.getMode = getMode; - CodeMirror2.modeExtensions = modeExtensions; - CodeMirror2.extendMode = extendMode; - CodeMirror2.copyState = copyState; - CodeMirror2.startState = startState; - CodeMirror2.innerMode = innerMode; - CodeMirror2.commands = commands; - CodeMirror2.keyMap = keyMap; - CodeMirror2.keyName = keyName; - CodeMirror2.isModifierKey = isModifierKey; - CodeMirror2.lookupKey = lookupKey; - CodeMirror2.normalizeKeyMap = normalizeKeyMap; - CodeMirror2.StringStream = StringStream; - CodeMirror2.SharedTextMarker = SharedTextMarker; - CodeMirror2.TextMarker = TextMarker; - CodeMirror2.LineWidget = LineWidget; - CodeMirror2.e_preventDefault = e_preventDefault; - CodeMirror2.e_stopPropagation = e_stopPropagation; - CodeMirror2.e_stop = e_stop; - CodeMirror2.addClass = addClass; - CodeMirror2.contains = contains; - CodeMirror2.rmClass = rmClass; - CodeMirror2.keyNames = keyNames; - } - defineOptions(CodeMirror); - addEditorMethods(CodeMirror); - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) { - if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { - CodeMirror.prototype[prop] = /* @__PURE__ */function (method) { - return function () { - return method.apply(this.doc, arguments); + cmds.findUnder = function (cm) { + findAndGoTo(cm, true); }; - }(Doc.prototype[prop]); - } - } - eventMixin(Doc); - CodeMirror.inputStyles = { - "textarea": TextareaInput, - "contenteditable": ContentEditableInput - }; - CodeMirror.defineMode = function (name) { - if (!CodeMirror.defaults.mode && name != "null") { - CodeMirror.defaults.mode = name; - } - defineMode.apply(this, arguments); - }; - CodeMirror.defineMIME = defineMIME; - CodeMirror.defineMode("null", function () { - return { - token: function (stream) { - return stream.skipToEnd(); - } - }; - }); - CodeMirror.defineMIME("text/plain", "null"); - CodeMirror.defineExtension = function (name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.fromTextArea = fromTextArea; - addLegacyProps(CodeMirror); - CodeMirror.version = "5.65.3"; - return CodeMirror; - }); - })(codemirror); - return codemirror.exports; -} -exports.getDefaultExportFromCjs = getDefaultExportFromCjs; -exports.requireCodemirror = requireCodemirror; + cmds.findUnderPrevious = function (cm) { + findAndGoTo(cm, false); + }; + cmds.findAllUnder = function (cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({ + anchor: cur.from(), + head: cur.to(), + }); + if ( + cur.from().line <= target.from.line && + cur.from().ch <= target.from.ch + ) + primaryIndex++; + } + cm.setSelections(matches, primaryIndex); + }; + var keyMap = CodeMirror.keyMap; + keyMap.macSublime = { + "Cmd-Left": "goLineStartSmart", + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Ctrl-Alt-Up": "scrollLineUp", + "Ctrl-Alt-Down": "scrollLineDown", + "Cmd-L": "selectLine", + "Shift-Cmd-L": "splitSelectionByLine", + Esc: "singleSelectionTop", + "Cmd-Enter": "insertLineAfter", + "Shift-Cmd-Enter": "insertLineBefore", + "Cmd-D": "selectNextOccurrence", + "Shift-Cmd-Space": "selectScope", + "Shift-Cmd-M": "selectBetweenBrackets", + "Cmd-M": "goToBracket", + "Cmd-Ctrl-Up": "swapLineUp", + "Cmd-Ctrl-Down": "swapLineDown", + "Cmd-/": "toggleCommentIndented", + "Cmd-J": "joinLines", + "Shift-Cmd-D": "duplicateLine", + F5: "sortLines", + "Shift-F5": "reverseSortLines", + "Cmd-F5": "sortLinesInsensitive", + "Shift-Cmd-F5": "reverseSortLinesInsensitive", + F2: "nextBookmark", + "Shift-F2": "prevBookmark", + "Cmd-F2": "toggleBookmark", + "Shift-Cmd-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + Backspace: "smartBackspace", + "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", + "Cmd-K Cmd-K": "delLineRight", + "Cmd-K Cmd-U": "upcaseAtCursor", + "Cmd-K Cmd-L": "downcaseAtCursor", + "Cmd-K Cmd-Space": "setSublimeMark", + "Cmd-K Cmd-A": "selectToSublimeMark", + "Cmd-K Cmd-W": "deleteToSublimeMark", + "Cmd-K Cmd-X": "swapWithSublimeMark", + "Cmd-K Cmd-Y": "sublimeYank", + "Cmd-K Cmd-C": "showInCenter", + "Cmd-K Cmd-G": "clearBookmarks", + "Cmd-K Cmd-Backspace": "delLineLeft", + "Cmd-K Cmd-1": "foldAll", + "Cmd-K Cmd-0": "unfoldAll", + "Cmd-K Cmd-J": "unfoldAll", + "Ctrl-Shift-Up": "addCursorToPrevLine", + "Ctrl-Shift-Down": "addCursorToNextLine", + "Cmd-F3": "findUnder", + "Shift-Cmd-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Cmd-[": "fold", + "Shift-Cmd-]": "unfold", + "Cmd-I": "findIncremental", + "Shift-Cmd-I": "findIncrementalReverse", + "Cmd-H": "replace", + F3: "findNext", + "Shift-F3": "findPrev", + fallthrough: "macDefault", + }; + CodeMirror.normalizeKeyMap(keyMap.macSublime); + keyMap.pcSublime = { + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-T": "transposeChars", + "Alt-Left": "goSubwordLeft", + "Alt-Right": "goSubwordRight", + "Ctrl-Up": "scrollLineUp", + "Ctrl-Down": "scrollLineDown", + "Ctrl-L": "selectLine", + "Shift-Ctrl-L": "splitSelectionByLine", + Esc: "singleSelectionTop", + "Ctrl-Enter": "insertLineAfter", + "Shift-Ctrl-Enter": "insertLineBefore", + "Ctrl-D": "selectNextOccurrence", + "Shift-Ctrl-Space": "selectScope", + "Shift-Ctrl-M": "selectBetweenBrackets", + "Ctrl-M": "goToBracket", + "Shift-Ctrl-Up": "swapLineUp", + "Shift-Ctrl-Down": "swapLineDown", + "Ctrl-/": "toggleCommentIndented", + "Ctrl-J": "joinLines", + "Shift-Ctrl-D": "duplicateLine", + F9: "sortLines", + "Shift-F9": "reverseSortLines", + "Ctrl-F9": "sortLinesInsensitive", + "Shift-Ctrl-F9": "reverseSortLinesInsensitive", + F2: "nextBookmark", + "Shift-F2": "prevBookmark", + "Ctrl-F2": "toggleBookmark", + "Shift-Ctrl-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + Backspace: "smartBackspace", + "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", + "Ctrl-K Ctrl-K": "delLineRight", + "Ctrl-K Ctrl-U": "upcaseAtCursor", + "Ctrl-K Ctrl-L": "downcaseAtCursor", + "Ctrl-K Ctrl-Space": "setSublimeMark", + "Ctrl-K Ctrl-A": "selectToSublimeMark", + "Ctrl-K Ctrl-W": "deleteToSublimeMark", + "Ctrl-K Ctrl-X": "swapWithSublimeMark", + "Ctrl-K Ctrl-Y": "sublimeYank", + "Ctrl-K Ctrl-C": "showInCenter", + "Ctrl-K Ctrl-G": "clearBookmarks", + "Ctrl-K Ctrl-Backspace": "delLineLeft", + "Ctrl-K Ctrl-1": "foldAll", + "Ctrl-K Ctrl-0": "unfoldAll", + "Ctrl-K Ctrl-J": "unfoldAll", + "Ctrl-Alt-Up": "addCursorToPrevLine", + "Ctrl-Alt-Down": "addCursorToNextLine", + "Ctrl-F3": "findUnder", + "Shift-Ctrl-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Ctrl-[": "fold", + "Shift-Ctrl-]": "unfold", + "Ctrl-I": "findIncremental", + "Shift-Ctrl-I": "findIncrementalReverse", + "Ctrl-H": "replace", + F3: "findNext", + "Shift-F3": "findPrev", + fallthrough: "pcDefault", + }; + CodeMirror.normalizeKeyMap(keyMap.pcSublime); + var mac = keyMap.default == keyMap.macDefault; + keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; + }); + })(); + var sublimeExports = sublime$2.exports; + const sublime = + /* @__PURE__ */ codemirror.getDefaultExportFromCjs(sublimeExports); + const sublime$1 = /* @__PURE__ */ _mergeNamespaces( + { + __proto__: null, + default: sublime, + }, + [sublimeExports] + ); + exports.sublime = sublime$1; -/***/ }), + /***/ + }, -/***/ "../../graphiql-react/dist/comment.cjs.js": -/*!************************************************!*\ - !*** ../../graphiql-react/dist/comment.cjs.js ***! - \************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var comment$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var noOptions = {}; - var nonWS = /[^\s\u00a0]/; - var Pos = CodeMirror.Pos, - cmp = CodeMirror.cmpPos; - function firstNonWS(str) { - var found = str.search(nonWS); - return found == -1 ? 0 : found; - } - CodeMirror.commands.toggleComment = function (cm) { - cm.toggleComment(); - }; - CodeMirror.defineExtension("toggleComment", function (options) { - if (!options) options = noOptions; - var cm = this; - var minLine = Infinity, - ranges = this.listSelections(), - mode = null; - for (var i = ranges.length - 1; i >= 0; i--) { - var from = ranges[i].from(), - to = ranges[i].to(); - if (from.line >= minLine) continue; - if (to.line >= minLine) to = Pos(minLine, 0); - minLine = from.line; - if (mode == null) { - if (cm.uncomment(from, to, options)) mode = "un";else { - cm.lineComment(from, to, options); - mode = "line"; - } - } else if (mode == "un") { - cm.uncomment(from, to, options); - } else { - cm.lineComment(from, to, options); - } - } - }); - function probablyInsideString(cm, pos, line) { - return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line); - } - function getMode(cm, pos) { - var mode = cm.getMode(); - return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos); - } - CodeMirror.defineExtension("lineComment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var firstLine = self.getLine(from.line); - if (firstLine == null || probablyInsideString(self, from, firstLine)) return; - var commentString = options.lineComment || mode.lineComment; - if (!commentString) { - if (options.blockCommentStart || mode.blockCommentStart) { - options.fullLines = true; - self.blockComment(from, to, options); - } - return; - } - var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); - var pad = options.padding == null ? " " : options.padding; - var blankLines = options.commentBlankLines || from.line == to.line; - self.operation(function () { - if (options.indent) { - var baseString = null; - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i); - var whitespace = line.slice(0, firstNonWS(line)); - if (baseString == null || baseString.length > whitespace.length) { - baseString = whitespace; - } - } - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i), - cut = baseString.length; - if (!blankLines && !nonWS.test(line)) continue; - if (line.slice(0, cut) != baseString) cut = firstNonWS(line); - self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); - } - } else { - for (var i = from.line; i < end; ++i) { - if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); - } - } - }); - }); - CodeMirror.defineExtension("blockComment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var startString = options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) { - if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); - return; - } - if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return; - var end = Math.min(to.line, self.lastLine()); - if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; - var pad = options.padding == null ? " " : options.padding; - if (from.line > end) return; - self.operation(function () { - if (options.fullLines != false) { - var lastLineHasText = nonWS.test(self.getLine(end)); - self.replaceRange(pad + endString, Pos(end)); - self.replaceRange(startString + pad, Pos(from.line, 0)); - var lead = options.blockCommentLead || mode.blockCommentLead; - if (lead != null) { - for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); - } - } else { - var atCursor = cmp(self.getCursor("to"), to) == 0, - empty = !self.somethingSelected(); - self.replaceRange(endString, to); - if (atCursor) self.setSelection(empty ? to : self.getCursor("from"), to); - self.replaceRange(startString, from); - } - }); - }); - CodeMirror.defineExtension("uncomment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), - start = Math.min(from.line, end); - var lineString = options.lineComment || mode.lineComment, - lines = []; - var pad = options.padding == null ? " " : options.padding, - didSomething; - lineComment: { - if (!lineString) break lineComment; - for (var i = start; i <= end; ++i) { - var line = self.getLine(i); - var found = line.indexOf(lineString); - if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; - if (found == -1 && nonWS.test(line)) break lineComment; - if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; - lines.push(line); - } - self.operation(function () { - for (var i2 = start; i2 <= end; ++i2) { - var line2 = lines[i2 - start]; - var pos = line2.indexOf(lineString), - endPos = pos + lineString.length; - if (pos < 0) continue; - if (line2.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; - didSomething = true; - self.replaceRange("", Pos(i2, pos), Pos(i2, endPos)); - } - }); - if (didSomething) return true; - } - var startString = options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) return false; - var lead = options.blockCommentLead || mode.blockCommentLead; - var startLine = self.getLine(start), - open = startLine.indexOf(startString); - if (open == -1) return false; - var endLine = end == start ? startLine : self.getLine(end); - var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); - var insideStart = Pos(start, open + 1), - insideEnd = Pos(end, close + 1); - if (close == -1 || !/comment/.test(self.getTokenTypeAt(insideStart)) || !/comment/.test(self.getTokenTypeAt(insideEnd)) || self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1) return false; - var lastStart = startLine.lastIndexOf(startString, from.ch); - var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); - if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; - firstEnd = endLine.indexOf(endString, to.ch); - var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); - lastStart = firstEnd == -1 || almostLastStart == -1 ? -1 : to.ch + almostLastStart; - if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; - self.operation(function () { - self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); - var openEnd = open + startString.length; - if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; - self.replaceRange("", Pos(start, open), Pos(start, openEnd)); - if (lead) for (var i2 = start + 1; i2 <= end; ++i2) { - var line2 = self.getLine(i2), - found2 = line2.indexOf(lead); - if (found2 == -1 || nonWS.test(line2.slice(0, found2))) continue; - var foundEnd = found2 + lead.length; - if (pad && line2.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; - self.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd)); - } - }); - return true; - }); - }); -})(); -var commentExports = comment$2.exports; -const comment = /* @__PURE__ */codemirror.getDefaultExportFromCjs(commentExports); -const comment$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: comment -}, [commentExports]); -exports.comment = comment$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/dialog.cjs.js": -/*!***********************************************!*\ - !*** ../../graphiql-react/dist/dialog.cjs.js ***! - \***********************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var dialog$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function dialogDiv(cm, template, bottom) { - var wrap = cm.getWrapperElement(); - var dialog2; - dialog2 = wrap.appendChild(document.createElement("div")); - if (bottom) dialog2.className = "CodeMirror-dialog CodeMirror-dialog-bottom";else dialog2.className = "CodeMirror-dialog CodeMirror-dialog-top"; - if (typeof template == "string") { - dialog2.innerHTML = template; - } else { - dialog2.appendChild(template); - } - CodeMirror.addClass(wrap, "dialog-opened"); - return dialog2; - } - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - CodeMirror.defineExtension("openDialog", function (template, callback, options) { - if (!options) options = {}; - closeNotification(this, null); - var dialog2 = dialogDiv(this, template, options.bottom); - var closed = false, - me = this; - function close(newVal) { - if (typeof newVal == "string") { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - me.focus(); - if (options.onClose) options.onClose(dialog2); - } - } - var inp = dialog2.getElementsByTagName("input")[0], - button; - if (inp) { - inp.focus(); - if (options.value) { - inp.value = options.value; - if (options.selectValueOnOpen !== false) { - inp.select(); - } - } - if (options.onInput) CodeMirror.on(inp, "input", function (e) { - options.onInput(e, inp.value, close); - }); - if (options.onKeyUp) CodeMirror.on(inp, "keyup", function (e) { - options.onKeyUp(e, inp.value, close); - }); - CodeMirror.on(inp, "keydown", function (e) { - if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { - return; - } - if (e.keyCode == 27 || options.closeOnEnter !== false && e.keyCode == 13) { - inp.blur(); - CodeMirror.e_stop(e); - close(); - } - if (e.keyCode == 13) callback(inp.value, e); - }); - if (options.closeOnBlur !== false) CodeMirror.on(dialog2, "focusout", function (evt) { - if (evt.relatedTarget !== null) close(); - }); - } else if (button = dialog2.getElementsByTagName("button")[0]) { - CodeMirror.on(button, "click", function () { - close(); - me.focus(); - }); - if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); - button.focus(); - } - return close; - }); - CodeMirror.defineExtension("openConfirm", function (template, callbacks, options) { - closeNotification(this, null); - var dialog2 = dialogDiv(this, template, options && options.bottom); - var buttons = dialog2.getElementsByTagName("button"); - var closed = false, - me = this, - blurring = 1; - function close() { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - me.focus(); - } - buttons[0].focus(); - for (var i = 0; i < buttons.length; ++i) { - var b = buttons[i]; - (function (callback) { - CodeMirror.on(b, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - if (callback) callback(me); - }); - })(callbacks[i]); - CodeMirror.on(b, "blur", function () { - --blurring; - setTimeout(function () { - if (blurring <= 0) close(); - }, 200); - }); - CodeMirror.on(b, "focus", function () { - ++blurring; + /***/ "../../graphiql-toolkit/esm/async-helpers/index.js": + /*!*********************************************************!*\ + !*** ../../graphiql-toolkit/esm/async-helpers/index.js ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - }); - CodeMirror.defineExtension("openNotification", function (template, options) { - closeNotification(this, close); - var dialog2 = dialogDiv(this, template, options && options.bottom); - var closed = false, - doneTimer; - var duration = options && typeof options.duration !== "undefined" ? options.duration : 5e3; - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - } - CodeMirror.on(dialog2, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - }); - if (duration) doneTimer = setTimeout(close, duration); - return close; - }); - }); -})(); -var dialogExports = dialog$2.exports; -const dialog = /* @__PURE__ */codemirror.getDefaultExportFromCjs(dialogExports); -const dialog$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: dialog -}, [dialogExports]); -exports.dialog = dialog$1; -exports.dialogExports = dialogExports; - -/***/ }), - -/***/ "../../graphiql-react/dist/foldgutter.cjs.js": -/*!***************************************************!*\ - !*** ../../graphiql-react/dist/foldgutter.cjs.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] + exports.fetcherReturnToPromise = fetcherReturnToPromise; + exports.isAsyncIterable = isAsyncIterable; + exports.isObservable = isObservable; + exports.isPromise = isPromise; + var __awaiter = + (void 0 && (void 0).__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; + function isPromise(value) { + return ( + typeof value === "object" && + value !== null && + typeof value.then === "function" + ); + } + function observableToPromise(observable) { + return new Promise((resolve, reject) => { + const subscription = observable.subscribe({ + next(v) { + resolve(v); + subscription.unsubscribe(); + }, + error: reject, + complete() { + reject(new Error("no value resolved")); + }, }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var foldgutter$2 = { - exports: {} -}; -var foldcode = { - exports: {} -}; -var hasRequiredFoldcode; -function requireFoldcode() { - if (hasRequiredFoldcode) return foldcode.exports; - hasRequiredFoldcode = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function doFold(cm, pos, options, force) { - if (options && options.call) { - var finder = options; - options = null; - } else { - var finder = getOption(cm, options, "rangeFinder"); - } - if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); - var minSize = getOption(cm, options, "minFoldSize"); - function getRange(allowFolded) { - var range2 = finder(cm, pos); - if (!range2 || range2.to.line - range2.from.line < minSize) return null; - if (force === "fold") return range2; - var marks = cm.findMarksAt(range2.from); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - if (!allowFolded) return null; - range2.cleared = true; - marks[i].clear(); - } - } - return range2; - } - var range = getRange(true); - if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) { - pos = CodeMirror.Pos(pos.line - 1, 0); - range = getRange(false); - } - if (!range || range.cleared || force === "unfold") return; - var myWidget = makeWidget(cm, options, range); - CodeMirror.on(myWidget, "mousedown", function (e) { - myRange.clear(); - CodeMirror.e_preventDefault(e); - }); - var myRange = cm.markText(range.from, range.to, { - replacedWith: myWidget, - clearOnEnter: getOption(cm, options, "clearOnEnter"), - __isFold: true - }); - myRange.on("clear", function (from, to) { - CodeMirror.signal(cm, "unfold", cm, from, to); - }); - CodeMirror.signal(cm, "fold", cm, range.from, range.to); - } - function makeWidget(cm, options, range) { - var widget = getOption(cm, options, "widget"); - if (typeof widget == "function") { - widget = widget(range.from, range.to); - } - if (typeof widget == "string") { - var text = document.createTextNode(widget); - widget = document.createElement("span"); - widget.appendChild(text); - widget.className = "CodeMirror-foldmarker"; - } else if (widget) { - widget = widget.cloneNode(true); - } - return widget; - } - CodeMirror.newFoldFunction = function (rangeFinder, widget) { - return function (cm, pos) { - doFold(cm, pos, { - rangeFinder, - widget }); - }; - }; - CodeMirror.defineExtension("foldCode", function (pos, options, force) { - doFold(this, pos, options, force); - }); - CodeMirror.defineExtension("isFolded", function (pos) { - var marks = this.findMarksAt(pos); - for (var i = 0; i < marks.length; ++i) if (marks[i].__isFold) return true; - }); - CodeMirror.commands.toggleFold = function (cm) { - cm.foldCode(cm.getCursor()); - }; - CodeMirror.commands.fold = function (cm) { - cm.foldCode(cm.getCursor(), null, "fold"); - }; - CodeMirror.commands.unfold = function (cm) { - cm.foldCode(cm.getCursor(), { - scanUp: false - }, "unfold"); - }; - CodeMirror.commands.foldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { - scanUp: false - }, "fold"); - }); - }; - CodeMirror.commands.unfoldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { - scanUp: false - }, "unfold"); - }); - }; - CodeMirror.registerHelper("fold", "combine", function () { - var funcs = Array.prototype.slice.call(arguments, 0); - return function (cm, start) { - for (var i = 0; i < funcs.length; ++i) { - var found = funcs[i](cm, start); - if (found) return found; - } - }; - }); - CodeMirror.registerHelper("fold", "auto", function (cm, start) { - var helpers = cm.getHelpers(start, "fold"); - for (var i = 0; i < helpers.length; i++) { - var cur = helpers[i](cm, start); - if (cur) return cur; - } - }); - var defaultOptions = { - rangeFinder: CodeMirror.fold.auto, - widget: "↔", - minFoldSize: 0, - scanUp: false, - clearOnEnter: true - }; - CodeMirror.defineOption("foldOptions", null); - function getOption(cm, options, name) { - if (options && options[name] !== void 0) return options[name]; - var editorOptions = cm.options.foldOptions; - if (editorOptions && editorOptions[name] !== void 0) return editorOptions[name]; - return defaultOptions[name]; - } - CodeMirror.defineExtension("foldOption", function (options, name) { - return getOption(this, options, name); - }); - }); - })(); - return foldcode.exports; -} -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), requireFoldcode()); - })(function (CodeMirror) { - CodeMirror.defineOption("foldGutter", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.clearGutter(cm.state.foldGutter.options.gutter); - cm.state.foldGutter = null; - cm.off("gutterClick", onGutterClick); - cm.off("changes", onChange); - cm.off("viewportChange", onViewportChange); - cm.off("fold", onFold); - cm.off("unfold", onFold); - cm.off("swapDoc", onChange); - } - if (val) { - cm.state.foldGutter = new State(parseOptions(val)); - updateInViewport(cm); - cm.on("gutterClick", onGutterClick); - cm.on("changes", onChange); - cm.on("viewportChange", onViewportChange); - cm.on("fold", onFold); - cm.on("unfold", onFold); - cm.on("swapDoc", onChange); - } - }); - var Pos = CodeMirror.Pos; - function State(options) { - this.options = options; - this.from = this.to = 0; - } - function parseOptions(opts) { - if (opts === true) opts = {}; - if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; - if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; - if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; - return opts; - } - function isFolded(cm, line) { - var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - var fromPos = marks[i].find(-1); - if (fromPos && fromPos.line === line) return marks[i]; } - } - } - function marker(spec) { - if (typeof spec == "string") { - var elt = document.createElement("div"); - elt.className = spec + " CodeMirror-guttermarker-subtle"; - return elt; - } else { - return spec.cloneNode(true); - } - } - function updateFoldInfo(cm, from, to) { - var opts = cm.state.foldGutter.options, - cur = from - 1; - var minSize = cm.foldOption(opts, "minFoldSize"); - var func = cm.foldOption(opts, "rangeFinder"); - var clsFolded = typeof opts.indicatorFolded == "string" && classTest(opts.indicatorFolded); - var clsOpen = typeof opts.indicatorOpen == "string" && classTest(opts.indicatorOpen); - cm.eachLine(from, to, function (line) { - ++cur; - var mark = null; - var old = line.gutterMarkers; - if (old) old = old[opts.gutter]; - if (isFolded(cm, cur)) { - if (clsFolded && old && clsFolded.test(old.className)) return; - mark = marker(opts.indicatorFolded); - } else { - var pos = Pos(cur, 0); - var range = func && func(cm, pos); - if (range && range.to.line - range.from.line >= minSize) { - if (clsOpen && old && clsOpen.test(old.className)) return; - mark = marker(opts.indicatorOpen); - } + function isObservable(value) { + return ( + typeof value === "object" && + value !== null && + "subscribe" in value && + typeof value.subscribe === "function" + ); } - if (!mark && !old) return; - cm.setGutterMarker(line, opts.gutter, mark); - }); - } - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - function updateInViewport(cm) { - var vp = cm.getViewport(), - state = cm.state.foldGutter; - if (!state) return; - cm.operation(function () { - updateFoldInfo(cm, vp.from, vp.to); - }); - state.from = vp.from; - state.to = vp.to; - } - function onGutterClick(cm, line, gutter) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - if (gutter != opts.gutter) return; - var folded = isFolded(cm, line); - if (folded) folded.clear();else cm.foldCode(Pos(line, 0), opts); - } - function onChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - state.from = state.to = 0; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - updateInViewport(cm); - }, opts.foldOnChangeTimeSpan || 600); - } - function onViewportChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - var vp = cm.getViewport(); - if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { - updateInViewport(cm); - } else { - cm.operation(function () { - if (vp.from < state.from) { - updateFoldInfo(cm, vp.from, state.from); - state.from = vp.from; + function isAsyncIterable(input) { + return ( + typeof input === "object" && + input !== null && + (input[Symbol.toStringTag] === "AsyncGenerator" || + Symbol.asyncIterator in input) + ); + } + function asyncIterableToPromise(input) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const iteratorReturn = + (_a = ("return" in input ? input : input[Symbol.asyncIterator]()) + .return) === null || _a === void 0 + ? void 0 + : _a.bind(input); + const iteratorNext = ( + "next" in input ? input : input[Symbol.asyncIterator]() + ).next.bind(input); + const result = yield iteratorNext(); + void (iteratorReturn === null || iteratorReturn === void 0 + ? void 0 + : iteratorReturn()); + return result.value; + }); + } + function fetcherReturnToPromise(fetcherResult) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield fetcherResult; + if (isAsyncIterable(result)) { + return asyncIterableToPromise(result); } - if (vp.to > state.to) { - updateFoldInfo(cm, state.to, vp.to); - state.to = vp.to; + if (isObservable(result)) { + return observableToPromise(result); } + return result; }); } - }, opts.updateViewportTimeSpan || 400); - } - function onFold(cm, from) { - var state = cm.state.foldGutter; - if (!state) return; - var line = from.line; - if (line >= state.from && line < state.to) updateFoldInfo(cm, line, line + 1); - } - }); -})(); -var foldgutterExports = foldgutter$2.exports; -const foldgutter = /* @__PURE__ */codemirror.getDefaultExportFromCjs(foldgutterExports); -const foldgutter$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: foldgutter -}, [foldgutterExports]); -exports.foldgutter = foldgutter$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/forEachState.cjs.js": -/*!*****************************************************!*\ - !*** ../../graphiql-react/dist/forEachState.cjs.js ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -function forEachState(stack, fn) { - const reverseStateStack = []; - let state = stack; - while (state === null || state === void 0 ? void 0 : state.kind) { - reverseStateStack.push(state); - state = state.prevState; - } - for (let i = reverseStateStack.length - 1; i >= 0; i--) { - fn(reverseStateStack[i]); - } -} -exports.forEachState = forEachState; - -/***/ }), - -/***/ "../../graphiql-react/dist/hint.cjs.js": -/*!*********************************************!*\ - !*** ../../graphiql-react/dist/hint.cjs.js ***! - \*********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -__webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js"); -const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); -codemirror.CodeMirror.registerHelper("hint", "graphql", (editor, options) => { - const { - schema, - externalFragments, - autocompleteOptions - } = options; - if (!schema) { - return; - } - const cur = editor.getCursor(); - const token = editor.getTokenAt(cur); - const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; - const position = new graphqlLanguageService.Position(cur.line, tokenStart); - const rawResults = graphqlLanguageService.getAutocompleteSuggestions(schema, editor.getValue(), position, token, externalFragments, autocompleteOptions); - const results = { - list: rawResults.map(item => { - var _a; - return { - text: (_a = item === null || item === void 0 ? void 0 : item.rawInsert) !== null && _a !== void 0 ? _a : item.label, - type: item.type, - description: item.documentation, - isDeprecated: item.isDeprecated, - deprecationReason: item.deprecationReason - }; - }), - from: { - line: cur.line, - ch: tokenStart - }, - to: { - line: cur.line, - ch: token.end - } - }; - if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { - results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); - results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); - codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); - } - return results; -}); - -/***/ }), - -/***/ "../../graphiql-react/dist/hint.cjs2.js": -/*!**********************************************!*\ - !*** ../../graphiql-react/dist/hint.cjs2.js ***! - \**********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - + /***/ + }, -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); -function hintList(cursor, token, list) { - const hints = filterAndSortList(list, normalizeText(token.string)); - if (!hints) { - return; - } - const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; - return { - list: hints, - from: { - line: cursor.line, - ch: tokenStart - }, - to: { - line: cursor.line, - ch: token.end - } - }; -} -function filterAndSortList(list, text) { - if (!text) { - return filterNonEmpty(list, entry => !entry.isDeprecated); - } - const byProximity = list.map(entry => ({ - proximity: getProximity(normalizeText(entry.text), text), - entry - })); - const conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated); - const sortedMatches = conciseMatches.sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.text.length - b.entry.text.length); - return sortedMatches.map(pair => pair.entry); -} -function filterNonEmpty(array, predicate) { - const filtered = array.filter(predicate); - return filtered.length === 0 ? array : filtered; -} -function normalizeText(text) { - return text.toLowerCase().replaceAll(/\W/g, ""); -} -function getProximity(suggestion, text) { - let proximity = lexicalDistance(text, suggestion); - if (suggestion.length > text.length) { - proximity -= suggestion.length - text.length - 1; - proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; - } - return proximity; -} -function lexicalDistance(a, b) { - let i; - let j; - const d = []; - const aLength = a.length; - const bLength = b.length; - for (i = 0; i <= aLength; i++) { - d[i] = [i]; - } - for (j = 1; j <= bLength; j++) { - d[0][j] = j; - } - for (i = 1; i <= aLength; i++) { - for (j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); - } - } - } - return d[aLength][bLength]; -} -codemirror.CodeMirror.registerHelper("hint", "graphql-variables", (editor, options) => { - const cur = editor.getCursor(); - const token = editor.getTokenAt(cur); - const results = getVariablesHint(cur, token, options); - if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { - results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); - results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); - codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); - } - return results; -}); -function getVariablesHint(cur, token, options) { - const state = token.state.kind === "Invalid" ? token.state.prevState : token.state; - const { - kind, - step - } = state; - if (kind === "Document" && step === 0) { - return hintList(cur, token, [{ - text: "{" - }]); - } - const { - variableToType - } = options; - if (!variableToType) { - return; - } - const typeInfo = getTypeInfo(variableToType, token.state); - if (kind === "Document" || kind === "Variable" && step === 0) { - const variableNames = Object.keys(variableToType); - return hintList(cur, token, variableNames.map(name => ({ - text: `"${name}": `, - type: variableToType[name] - }))); - } - if ((kind === "ObjectValue" || kind === "ObjectField" && step === 0) && typeInfo.fields) { - const inputFields = Object.keys(typeInfo.fields).map(fieldName => typeInfo.fields[fieldName]); - return hintList(cur, token, inputFields.map(field => ({ - text: `"${field.name}": `, - type: field.type, - description: field.description - }))); - } - if (kind === "StringValue" || kind === "NumberValue" || kind === "BooleanValue" || kind === "NullValue" || kind === "ListValue" && step === 1 || kind === "ObjectField" && step === 2 || kind === "Variable" && step === 2) { - const namedInputType = typeInfo.type ? graphql.getNamedType(typeInfo.type) : void 0; - if (namedInputType instanceof graphql.GraphQLInputObjectType) { - return hintList(cur, token, [{ - text: "{" - }]); - } - if (namedInputType instanceof graphql.GraphQLEnumType) { - const values = namedInputType.getValues(); - return hintList(cur, token, values.map(value => ({ - text: `"${value.name}"`, - type: namedInputType, - description: value.description - }))); - } - if (namedInputType === graphql.GraphQLBoolean) { - return hintList(cur, token, [{ - text: "true", - type: graphql.GraphQLBoolean, - description: "Not false." - }, { - text: "false", - type: graphql.GraphQLBoolean, - description: "Not true." - }]); - } - } -} -function getTypeInfo(variableToType, tokenState) { - const info = { - type: null, - fields: null - }; - forEachState.forEachState(tokenState, state => { - switch (state.kind) { - case "Variable": - { - info.type = variableToType[state.name]; - break; - } - case "ListValue": - { - const nullableType = info.type ? graphql.getNullableType(info.type) : void 0; - info.type = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; - break; - } - case "ObjectValue": - { - const objectType = info.type ? graphql.getNamedType(info.type) : void 0; - info.fields = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; - break; - } - case "ObjectField": - { - const objectField = state.name && info.fields ? info.fields[state.name] : null; - info.type = objectField === null || objectField === void 0 ? void 0 : objectField.type; - break; + /***/ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js": + /*!******************************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/createFetcher.js ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createGraphiQLFetcher = createGraphiQLFetcher; + var _lib = __webpack_require__( + /*! ./lib */ "../../graphiql-toolkit/esm/create-fetcher/lib.js" + ); + function createGraphiQLFetcher(options) { + let httpFetch; + if (typeof window !== "undefined" && window.fetch) { + httpFetch = window.fetch; + } + if ( + (options === null || options === void 0 + ? void 0 + : options.enableIncrementalDelivery) === null || + options.enableIncrementalDelivery !== false + ) { + options.enableIncrementalDelivery = true; + } + if (options.fetch) { + httpFetch = options.fetch; + } + if (!httpFetch) { + throw new Error("No valid fetcher implementation available"); + } + const simpleFetcher = (0, _lib.createSimpleFetcher)( + options, + httpFetch + ); + const httpFetcher = options.enableIncrementalDelivery + ? (0, _lib.createMultipartFetcher)(options, httpFetch) + : simpleFetcher; + return (graphQLParams, fetcherOpts) => { + if (graphQLParams.operationName === "IntrospectionQuery") { + return (options.schemaFetcher || simpleFetcher)( + graphQLParams, + fetcherOpts + ); + } + const isSubscription = ( + fetcherOpts === null || fetcherOpts === void 0 + ? void 0 + : fetcherOpts.documentAST + ) + ? (0, _lib.isSubscriptionWithName)( + fetcherOpts.documentAST, + graphQLParams.operationName || undefined + ) + : false; + if (isSubscription) { + const wsFetcher = (0, _lib.getWsFetcher)(options, fetcherOpts); + if (!wsFetcher) { + throw new Error( + `Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${ + options.subscriptionUrl + ? `Provided URL ${options.subscriptionUrl} failed` + : "Please provide subscriptionUrl, wsClient or legacyClient option first." + }` + ); + } + return wsFetcher(graphQLParams); + } + return httpFetcher(graphQLParams, fetcherOpts); + }; } - } - }); - return info; -} -/***/ }), + /***/ + }, -/***/ "../../graphiql-react/dist/index.js": -/*!******************************************!*\ - !*** ../../graphiql-react/dist/index.js ***! - \******************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, Symbol.toStringTag, { - value: "Module" -}); -const jsxRuntime = __webpack_require__(/*! react/jsx-runtime */ "../../../node_modules/react/jsx-runtime.js"); -const React = __webpack_require__(/*! react */ "react"); -const clsx = __webpack_require__(/*! clsx */ "../../../node_modules/clsx/dist/clsx.m.js"); -const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const toolkit = __webpack_require__(/*! @graphiql/toolkit */ "../../graphiql-toolkit/esm/index.js"); -const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); -const setValue = __webpack_require__(/*! set-value */ "../../../node_modules/set-value/index.js"); -const copyToClipboard = __webpack_require__(/*! copy-to-clipboard */ "../../../node_modules/copy-to-clipboard/index.js"); -const D = __webpack_require__(/*! @radix-ui/react-dialog */ "../../../node_modules/@radix-ui/react-dialog/dist/index.js"); -const reactVisuallyHidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); -const reactDropdownMenu = __webpack_require__(/*! @radix-ui/react-dropdown-menu */ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js"); -const MarkdownIt = __webpack_require__(/*! markdown-it */ "../node_modules/markdown-it/dist/index.cjs.js"); -const framerMotion = __webpack_require__(/*! framer-motion */ "../../../node_modules/framer-motion/dist/cjs/index.js"); -const T = __webpack_require__(/*! @radix-ui/react-tooltip */ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js"); -const react = __webpack_require__(/*! @headlessui/react */ "../../../node_modules/@headlessui/react/dist/index.cjs"); -const ReactDOM = __webpack_require__(/*! react-dom */ "react-dom"); -function _interopNamespaceDefault(e) { - const n = Object.create(null, { - [Symbol.toStringTag]: { - value: "Module" - } - }); - if (e) { - for (const k in e) { - if (k !== "default") { - const d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] + /***/ "../../graphiql-toolkit/esm/create-fetcher/index.js": + /*!**********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/index.js ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - } - } - n.default = e; - return Object.freeze(n); -} -const React__namespace = /* @__PURE__ */_interopNamespaceDefault(React); -const D__namespace = /* @__PURE__ */_interopNamespaceDefault(D); -const T__namespace = /* @__PURE__ */_interopNamespaceDefault(T); -function createNullableContext(name) { - const context = React.createContext(null); - context.displayName = name; - return context; -} -function createContextHook(context) { - function useGivenContext(options) { - var _a; - const value = React.useContext(context); - if (value === null && (options == null ? void 0 : options.nonNull)) { - throw new Error(`Tried to use \`${((_a = options.caller) == null ? void 0 : _a.name) || useGivenContext.caller.name}\` without the necessary context. Make sure to render the \`${context.displayName}Provider\` component higher up the tree.`); - } - return value; - } - Object.defineProperty(useGivenContext, "name", { - value: `use${context.displayName}` - }); - return useGivenContext; -} -const StorageContext = createNullableContext("StorageContext"); -function StorageContextProvider(props) { - const isInitialRender = React.useRef(true); - const [storage, setStorage] = React.useState(new toolkit.StorageAPI(props.storage)); - React.useEffect(() => { - if (isInitialRender.current) { - isInitialRender.current = false; - } else { - setStorage(new toolkit.StorageAPI(props.storage)); - } - }, [props.storage]); - return /* @__PURE__ */jsxRuntime.jsx(StorageContext.Provider, { - value: storage, - children: props.children - }); -} -const useStorageContext = createContextHook(StorageContext); -const SvgArgument = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("rect", { - x: 6, - y: 6, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" -})); -const SvgChevronDown = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 9", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1 1L7 7L13 1", - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgChevronLeft = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 7 10", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M6 1.04819L2 5.04819L6 9.04819", - stroke: "currentColor", - strokeWidth: 1.75 -})); -const SvgChevronUp = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 9", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M13 8L7 2L1 8", - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgClose = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - stroke: "currentColor", - strokeWidth: 3, - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1 1L12.9998 12.9997" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M13 1L1.00079 13.0003" -})); -const SvgCopy = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "-2 -2 22 22", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.25 14.2105V15.235C11.25 16.3479 10.3479 17.25 9.23501 17.25H2.76499C1.65214 17.25 0.75 16.3479 0.75 15.235L0.75 8.76499C0.75 7.65214 1.65214 6.75 2.76499 6.75L3.78947 6.75", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("rect", { - x: 6.75, - y: 0.75, - width: 10.5, - height: 10.5, - rx: 2.2069, - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgDeprecatedArgument = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M5 9L9 5", - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M5 5L9 9", - stroke: "currentColor", - strokeWidth: 1.2 -})); -const SvgDeprecatedEnumValue = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 8L8 4", - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 4L8 8", - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", - fill: "currentColor" -})); -const SvgDeprecatedField = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 10.8, - height: 10.8, - rx: 3.4, - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 8L8 4", - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 4L8 8", - stroke: "currentColor", - strokeWidth: 1.2 -})); -const SvgDirective = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0.5 12 12", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 7, - y: 5.5, - width: 2, - height: 2, - rx: 1, - transform: "rotate(90 7 5.5)", - fill: "currentColor" -}), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M10.8 9L10.8 9.5C10.8 10.4941 9.99411 11.3 9 11.3L3 11.3C2.00589 11.3 1.2 10.4941 1.2 9.5L1.2 9L-3.71547e-07 9L-3.93402e-07 9.5C-4.65826e-07 11.1569 1.34314 12.5 3 12.5L9 12.5C10.6569 12.5 12 11.1569 12 9.5L12 9L10.8 9ZM10.8 4L12 4L12 3.5C12 1.84315 10.6569 0.5 9 0.5L3 0.5C1.34315 0.5 -5.87117e-08 1.84315 -1.31135e-07 3.5L-1.5299e-07 4L1.2 4L1.2 3.5C1.2 2.50589 2.00589 1.7 3 1.7L9 1.7C9.99411 1.7 10.8 2.50589 10.8 3.5L10.8 4Z", - fill: "currentColor" -})); -const SvgDocsFilled = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 20 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H17.25C17.8023 0.75 18.25 1.19772 18.25 1.75V5.25", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H18.25C18.8023 5.25 19.25 5.69771 19.25 6.25V22.25C19.25 22.8023 18.8023 23.25 18.25 23.25H3C1.75736 23.25 0.75 22.2426 0.75 21V3Z", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M3 5.25C1.75736 5.25 0.75 4.24264 0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H3ZM13 11L6 11V12.5L13 12.5V11Z", - fill: "currentColor" -})); -const SvgDocs = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 20 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H17.25M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H16.25C16.8023 0.75 17.25 1.19772 17.25 1.75V5.25M0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H17.25", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("line", { - x1: 13, - y1: 11.75, - x2: 6, - y2: 11.75, - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgEnumValue = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 5, - y: 5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" -}), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", - fill: "currentColor" -})); -const SvgField = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 1.1, - width: 10.8, - height: 10.8, - rx: 2.4, - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("rect", { - x: 5, - y: 5.5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" -})); -const SvgHistory = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 24 20", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.59375 9.52344L4.87259 12.9944L8.07872 9.41249", - stroke: "currentColor", - strokeWidth: 1.5, - strokeLinecap: "square" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M13.75 5.25V10.75H18.75", - stroke: "currentColor", - strokeWidth: 1.5, - strokeLinecap: "square" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4.95427 11.9332C4.55457 10.0629 4.74441 8.11477 5.49765 6.35686C6.25089 4.59894 7.5305 3.11772 9.16034 2.11709C10.7902 1.11647 12.6901 0.645626 14.5986 0.769388C16.5071 0.893151 18.3303 1.60543 19.8172 2.80818C21.3042 4.01093 22.3818 5.64501 22.9017 7.48548C23.4216 9.32595 23.3582 11.2823 22.7203 13.0853C22.0824 14.8883 20.9013 16.4492 19.3396 17.5532C17.778 18.6572 15.9125 19.25 14 19.25", - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgImplements = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { - cx: 6, - cy: 6, - r: 5.4, - stroke: "currentColor", - strokeWidth: 1.2, - strokeDasharray: "4.241025 4.241025", - transform: "rotate(22.5)", - "transform-origin": "center" -}), /* @__PURE__ */React__namespace.createElement("circle", { - cx: 6, - cy: 6, - r: 1, - fill: "currentColor" -})); -const SvgKeyboardShortcut = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 19 18", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.5 14.5653C1.5 15.211 1.75652 15.8303 2.21314 16.2869C2.66975 16.7435 3.28905 17 3.9348 17C4.58054 17 5.19984 16.7435 5.65646 16.2869C6.11307 15.8303 6.36959 15.211 6.36959 14.5653V12.1305H3.9348C3.28905 12.1305 2.66975 12.387 2.21314 12.8437C1.75652 13.3003 1.5 13.9195 1.5 14.5653Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M3.9348 1.00063C3.28905 1.00063 2.66975 1.25715 2.21314 1.71375C1.75652 2.17035 1.5 2.78964 1.5 3.43537C1.5 4.0811 1.75652 4.70038 2.21314 5.15698C2.66975 5.61358 3.28905 5.8701 3.9348 5.8701H6.36959V3.43537C6.36959 2.78964 6.11307 2.17035 5.65646 1.71375C5.19984 1.25715 4.58054 1.00063 3.9348 1.00063Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M15.0652 12.1305H12.6304V14.5653C12.6304 15.0468 12.7732 15.5175 13.0407 15.9179C13.3083 16.3183 13.6885 16.6304 14.1334 16.8147C14.5783 16.9989 15.0679 17.0472 15.5402 16.9532C16.0125 16.8593 16.4464 16.6274 16.7869 16.2869C17.1274 15.9464 17.3593 15.5126 17.4532 15.0403C17.5472 14.568 17.4989 14.0784 17.3147 13.6335C17.1304 13.1886 16.8183 12.8084 16.4179 12.5409C16.0175 12.2733 15.5468 12.1305 15.0652 12.1305Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M12.6318 5.86775H6.36955V12.1285H12.6318V5.86775Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M17.5 3.43473C17.5 2.789 17.2435 2.16972 16.7869 1.71312C16.3303 1.25652 15.711 1 15.0652 1C14.4195 1 13.8002 1.25652 13.3435 1.71312C12.8869 2.16972 12.6304 2.789 12.6304 3.43473V5.86946H15.0652C15.711 5.86946 16.3303 5.61295 16.7869 5.15635C17.2435 4.69975 17.5 4.08046 17.5 3.43473Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" -})); -const SvgMagnifyingGlass = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { - cx: 5, - cy: 5, - r: 4.35, - stroke: "currentColor", - strokeWidth: 1.3 -}), /* @__PURE__ */React__namespace.createElement("line", { - x1: 8.45962, - y1: 8.54038, - x2: 11.7525, - y2: 11.8333, - stroke: "currentColor", - strokeWidth: 1.3 -})); -const SvgMerge = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "-2 -2 22 22", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M17.2492 6V2.9569C17.2492 1.73806 16.2611 0.75 15.0423 0.75L2.9569 0.75C1.73806 0.75 0.75 1.73806 0.75 2.9569L0.75 6", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.749873 12V15.0431C0.749873 16.2619 1.73794 17.25 2.95677 17.25H15.0421C16.261 17.25 17.249 16.2619 17.249 15.0431V12", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M6 4.5L9 7.5L12 4.5", - stroke: "currentColor", - strokeWidth: 1.5 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M12 13.5L9 10.5L6 13.5", - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgPen = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 13.25L0.0554307 12.967C-0.0593528 13.2488 0.00743073 13.5719 0.224488 13.7851C0.441545 13.9983 0.765869 14.0592 1.04549 13.9393L0.75 13.25ZM12.8214 1.83253L12.2911 2.36286L12.2911 2.36286L12.8214 1.83253ZM12.8214 3.90194L13.3517 4.43227L12.8214 3.90194ZM10.0981 1.17859L9.56773 0.648259L10.0981 1.17859ZM12.1675 1.17859L12.6978 0.648258L12.6978 0.648257L12.1675 1.17859ZM2.58049 8.75697L3.27506 9.03994L2.58049 8.75697ZM2.70066 8.57599L3.23099 9.10632L2.70066 8.57599ZM5.2479 11.4195L4.95355 10.7297L5.2479 11.4195ZM5.42036 11.303L4.89003 10.7727L5.42036 11.303ZM4.95355 10.7297C4.08882 11.0987 3.41842 11.362 2.73535 11.6308C2.05146 11.9 1.35588 12.1743 0.454511 12.5607L1.04549 13.9393C1.92476 13.5624 2.60256 13.2951 3.28469 13.0266C3.96762 12.7578 4.65585 12.4876 5.54225 12.1093L4.95355 10.7297ZM1.44457 13.533L3.27506 9.03994L1.88592 8.474L0.0554307 12.967L1.44457 13.533ZM3.23099 9.10632L10.6284 1.70892L9.56773 0.648259L2.17033 8.04566L3.23099 9.10632ZM11.6371 1.70892L12.2911 2.36286L13.3517 1.3022L12.6978 0.648258L11.6371 1.70892ZM12.2911 3.37161L4.89003 10.7727L5.95069 11.8333L13.3517 4.43227L12.2911 3.37161ZM12.2911 2.36286C12.5696 2.64142 12.5696 3.09305 12.2911 3.37161L13.3517 4.43227C14.2161 3.56792 14.2161 2.16654 13.3517 1.3022L12.2911 2.36286ZM10.6284 1.70892C10.9069 1.43036 11.3586 1.43036 11.6371 1.70892L12.6978 0.648257C11.8335 -0.216088 10.4321 -0.216084 9.56773 0.648259L10.6284 1.70892ZM3.27506 9.03994C3.26494 9.06479 3.24996 9.08735 3.23099 9.10632L2.17033 8.04566C2.04793 8.16806 1.95123 8.31369 1.88592 8.474L3.27506 9.03994ZM5.54225 12.1093C5.69431 12.0444 5.83339 11.9506 5.95069 11.8333L4.89003 10.7727C4.90863 10.7541 4.92988 10.7398 4.95355 10.7297L5.54225 12.1093Z", - fill: "currentColor" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.5 4.5L9.5 2.5", - stroke: "currentColor", - strokeWidth: 1.4026, - strokeLinecap: "round", - strokeLinejoin: "round" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M5.5 10.5L3.5 8.5", - stroke: "currentColor", - strokeWidth: 1.4026, - strokeLinecap: "round", - strokeLinejoin: "round" -})); -const SvgPlay = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 16 18", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.32226e-07 1.6609C7.22332e-08 0.907329 0.801887 0.424528 1.46789 0.777117L15.3306 8.11621C16.0401 8.49182 16.0401 9.50818 15.3306 9.88379L1.46789 17.2229C0.801886 17.5755 1.36076e-06 17.0927 1.30077e-06 16.3391L1.32226e-07 1.6609Z", - fill: "currentColor" -})); -const SvgPlus = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 10 16", - fill: "currentColor", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M4.25 9.25V13.5H5.75V9.25L10 9.25V7.75L5.75 7.75V3.5H4.25V7.75L0 7.75V9.25L4.25 9.25Z" -})); -const SvgPrettify = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - width: 25, - height: 25, - viewBox: "0 0 25 25", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M10.2852 24.0745L13.7139 18.0742", - stroke: "currentColor", - strokeWidth: 1.5625 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M14.5742 24.0749L17.1457 19.7891", - stroke: "currentColor", - strokeWidth: 1.5625 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M19.4868 24.0735L20.7229 21.7523C21.3259 20.6143 21.5457 19.3122 21.3496 18.0394C21.1535 16.7666 20.5519 15.591 19.6342 14.6874L23.7984 6.87853C24.0123 6.47728 24.0581 6.00748 23.9256 5.57249C23.7932 5.1375 23.4933 4.77294 23.0921 4.55901C22.6908 4.34509 22.221 4.29932 21.7861 4.43178C21.3511 4.56424 20.9865 4.86408 20.7726 5.26533L16.6084 13.0742C15.3474 12.8142 14.0362 12.9683 12.8699 13.5135C11.7035 14.0586 10.7443 14.9658 10.135 16.1L6 24.0735", - stroke: "currentColor", - strokeWidth: 1.5625 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 15L5 13L7 12L5 11L4 9L3 11L1 12L3 13L4 15Z", - stroke: "currentColor", - strokeWidth: 1.5625, - strokeLinejoin: "round" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.5 8L12.6662 5.6662L15 4.5L12.6662 3.3338L11.5 1L10.3338 3.3338L8 4.5L10.3338 5.6662L11.5 8Z", - stroke: "currentColor", - strokeWidth: 1.5625, - strokeLinejoin: "round" -})); -const SvgReload = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 16 16", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M4.75 9.25H1.25V12.75", - stroke: "currentColor", - strokeWidth: 1, - strokeLinecap: "square" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.25 6.75H14.75V3.25", - stroke: "currentColor", - strokeWidth: 1, - strokeLinecap: "square" -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M14.1036 6.65539C13.8 5.27698 13.0387 4.04193 11.9437 3.15131C10.8487 2.26069 9.48447 1.76694 8.0731 1.75043C6.66173 1.73392 5.28633 2.19563 4.17079 3.0604C3.05526 3.92516 2.26529 5.14206 1.92947 6.513", - stroke: "currentColor", - strokeWidth: 1 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.89635 9.34461C2.20001 10.723 2.96131 11.9581 4.05631 12.8487C5.15131 13.7393 6.51553 14.2331 7.9269 14.2496C9.33827 14.2661 10.7137 13.8044 11.8292 12.9396C12.9447 12.0748 13.7347 10.8579 14.0705 9.487", - stroke: "currentColor", - strokeWidth: 1 -})); -const SvgRootType = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 11.8, - height: 11.8, - rx: 5.9, - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4.25 7.5C4.25 6 5.75 5 6.5 6.5C7.25 8 8.75 7 8.75 5.5", - stroke: "currentColor", - strokeWidth: 1.2 -})); -const SvgSettings = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 21 20", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M9.29186 1.92702C9.06924 1.82745 8.87014 1.68202 8.70757 1.50024L7.86631 0.574931C7.62496 0.309957 7.30773 0.12592 6.95791 0.0479385C6.60809 -0.0300431 6.24274 0.00182978 5.91171 0.139208C5.58068 0.276585 5.3001 0.512774 5.10828 0.815537C4.91645 1.1183 4.82272 1.47288 4.83989 1.83089L4.90388 3.08019C4.91612 3.32348 4.87721 3.56662 4.78968 3.79394C4.70215 4.02126 4.56794 4.2277 4.39571 4.39994C4.22347 4.57219 4.01704 4.7064 3.78974 4.79394C3.56243 4.88147 3.3193 4.92038 3.07603 4.90814L1.8308 4.84414C1.47162 4.82563 1.11553 4.91881 0.811445 5.11086C0.507359 5.30292 0.270203 5.58443 0.132561 5.91671C-0.00508149 6.249 -0.0364554 6.61576 0.0427496 6.9666C0.121955 7.31744 0.307852 7.63514 0.5749 7.87606L1.50016 8.71204C1.68193 8.87461 1.82735 9.07373 1.92692 9.29636C2.02648 9.51898 2.07794 9.76012 2.07794 10.004C2.07794 10.2479 2.02648 10.489 1.92692 10.7116C1.82735 10.9343 1.68193 11.1334 1.50016 11.296L0.5749 12.1319C0.309856 12.3729 0.125575 12.6898 0.0471809 13.0393C-0.0312128 13.3888 9.64098e-05 13.754 0.13684 14.0851C0.273583 14.4162 0.509106 14.6971 0.811296 14.8894C1.11349 15.0817 1.46764 15.1762 1.82546 15.1599L3.0707 15.0959C3.31397 15.0836 3.5571 15.1225 3.7844 15.2101C4.01171 15.2976 4.21814 15.4318 4.39037 15.6041C4.56261 15.7763 4.69682 15.9827 4.78435 16.2101C4.87188 16.4374 4.91078 16.6805 4.89855 16.9238L4.83455 18.1691C4.81605 18.5283 4.90921 18.8844 5.10126 19.1885C5.2933 19.4926 5.5748 19.7298 5.90707 19.8674C6.23934 20.0051 6.60608 20.0365 6.9569 19.9572C7.30772 19.878 7.6254 19.6921 7.86631 19.4251L8.7129 18.4998C8.87547 18.318 9.07458 18.1725 9.29719 18.073C9.51981 17.9734 9.76093 17.9219 10.0048 17.9219C10.2487 17.9219 10.4898 17.9734 10.7124 18.073C10.935 18.1725 11.1341 18.318 11.2967 18.4998L12.1326 19.4251C12.3735 19.6921 12.6912 19.878 13.042 19.9572C13.3929 20.0365 13.7596 20.0051 14.0919 19.8674C14.4241 19.7298 14.7056 19.4926 14.8977 19.1885C15.0897 18.8844 15.1829 18.5283 15.1644 18.1691L15.1004 16.9238C15.0882 16.6805 15.1271 16.4374 15.2146 16.2101C15.3021 15.9827 15.4363 15.7763 15.6086 15.6041C15.7808 15.4318 15.9872 15.2976 16.2145 15.2101C16.4418 15.1225 16.685 15.0836 16.9282 15.0959L18.1735 15.1599C18.5326 15.1784 18.8887 15.0852 19.1928 14.8931C19.4969 14.7011 19.7341 14.4196 19.8717 14.0873C20.0093 13.755 20.0407 13.3882 19.9615 13.0374C19.8823 12.6866 19.6964 12.3689 19.4294 12.1279L18.5041 11.292C18.3223 11.1294 18.1769 10.9303 18.0774 10.7076C17.9778 10.485 17.9263 10.2439 17.9263 10C17.9263 9.75612 17.9778 9.51499 18.0774 9.29236C18.1769 9.06973 18.3223 8.87062 18.5041 8.70804L19.4294 7.87206C19.6964 7.63114 19.8823 7.31344 19.9615 6.9626C20.0407 6.61176 20.0093 6.245 19.8717 5.91271C19.7341 5.58043 19.4969 5.29892 19.1928 5.10686C18.8887 4.91481 18.5326 4.82163 18.1735 4.84014L16.9282 4.90414C16.685 4.91638 16.4418 4.87747 16.2145 4.78994C15.9872 4.7024 15.7808 4.56818 15.6086 4.39594C15.4363 4.2237 15.3021 4.01726 15.2146 3.78994C15.1271 3.56262 15.0882 3.31948 15.1004 3.07619L15.1644 1.83089C15.1829 1.4717 15.0897 1.11559 14.8977 0.811487C14.7056 0.507385 14.4241 0.270217 14.0919 0.132568C13.7596 -0.00508182 13.3929 -0.0364573 13.042 0.0427519C12.6912 0.121961 12.3735 0.307869 12.1326 0.574931L11.2914 1.50024C11.1288 1.68202 10.9297 1.82745 10.7071 1.92702C10.4845 2.02659 10.2433 2.07805 9.99947 2.07805C9.7556 2.07805 9.51448 2.02659 9.29186 1.92702ZM14.3745 10C14.3745 12.4162 12.4159 14.375 9.99977 14.375C7.58365 14.375 5.625 12.4162 5.625 10C5.625 7.58375 7.58365 5.625 9.99977 5.625C12.4159 5.625 14.3745 7.58375 14.3745 10Z", - fill: "currentColor" -})); -const SvgStarFilled = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", - fill: "currentColor", - stroke: "currentColor" -})); -const SvgStar = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", - stroke: "currentColor", - strokeWidth: 1.5 -})); -const SvgStop = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 16 16", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - width: 16, - height: 16, - rx: 2, - fill: "currentColor" -})); -const SvgTrash = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - width: "1em", - height: "5em", - xmlns: "http://www.w3.org/2000/svg", - fillRule: "evenodd", - "aria-hidden": "true", - viewBox: "0 0 23 23", - style: { - height: "1.5em" - }, - clipRule: "evenodd", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M19 24h-14c-1.104 0-2-.896-2-2v-17h-1v-2h6v-1.5c0-.827.673-1.5 1.5-1.5h5c.825 0 1.5.671 1.5 1.5v1.5h6v2h-1v17c0 1.104-.896 2-2 2zm0-19h-14v16.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-16.5zm-7 7.586l3.293-3.293 1.414 1.414-3.293 3.293 3.293 3.293-1.414 1.414-3.293-3.293-3.293 3.293-1.414-1.414 3.293-3.293-3.293-3.293 1.414-1.414 3.293 3.293zm2-10.586h-4v1h4v-1z", - fill: "currentColor", - strokeWidth: 0.25, - stroke: "currentColor" -})); -const SvgType = ({ - title, - titleId, - ...props -}) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props -}, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId -}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 11.8, - height: 11.8, - rx: 5.9, - stroke: "currentColor", - strokeWidth: 1.2 -}), /* @__PURE__ */React__namespace.createElement("rect", { - x: 5.5, - y: 5.5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" -})); -const ArgumentIcon = generateIcon(SvgArgument); -const ChevronDownIcon = generateIcon(SvgChevronDown); -const ChevronLeftIcon = generateIcon(SvgChevronLeft); -const ChevronUpIcon = generateIcon(SvgChevronUp); -const CloseIcon = generateIcon(SvgClose); -const CopyIcon = generateIcon(SvgCopy); -const DeprecatedArgumentIcon = generateIcon(SvgDeprecatedArgument); -const DeprecatedEnumValueIcon = generateIcon(SvgDeprecatedEnumValue); -const DeprecatedFieldIcon = generateIcon(SvgDeprecatedField); -const DirectiveIcon = generateIcon(SvgDirective); -const DocsFilledIcon = generateIcon(SvgDocsFilled); -const DocsIcon = generateIcon(SvgDocs); -const EnumValueIcon = generateIcon(SvgEnumValue); -const FieldIcon = generateIcon(SvgField); -const HistoryIcon = generateIcon(SvgHistory); -const ImplementsIcon = generateIcon(SvgImplements); -const KeyboardShortcutIcon = generateIcon(SvgKeyboardShortcut); -const MagnifyingGlassIcon = generateIcon(SvgMagnifyingGlass); -const MergeIcon = generateIcon(SvgMerge); -const PenIcon = generateIcon(SvgPen); -const PlayIcon = generateIcon(SvgPlay); -const PlusIcon = generateIcon(SvgPlus); -const PrettifyIcon = generateIcon(SvgPrettify); -const ReloadIcon = generateIcon(SvgReload); -const RootTypeIcon = generateIcon(SvgRootType); -const SettingsIcon = generateIcon(SvgSettings); -const StarFilledIcon = generateIcon(SvgStarFilled); -const StarIcon = generateIcon(SvgStar); -const StopIcon = generateIcon(SvgStop); -const TrashIcon = generateIcon(SvgTrash); -const TypeIcon = generateIcon(SvgType); -function generateIcon(RawComponent) { - const title = RawComponent.name.replace("Svg", "").replaceAll(/([A-Z])/g, " $1").trimStart().toLowerCase() + " icon"; - function IconComponent(props) { - return /* @__PURE__ */jsxRuntime.jsx(RawComponent, { - title, - ...props - }); - } - IconComponent.displayName = RawComponent.name; - return IconComponent; -} -const UnStyledButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-un-styled", props.className) -})); -UnStyledButton.displayName = "UnStyledButton"; -const Button$1 = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-button", { - success: "graphiql-button-success", - error: "graphiql-button-error" - }[props.state], props.className) -})); -Button$1.displayName = "Button"; -const ButtonGroup = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx("graphiql-button-group", props.className) -})); -ButtonGroup.displayName = "ButtonGroup"; -const createComponentGroup = (root, children) => Object.entries(children).reduce((r, [key, value]) => { - r[key] = value; - return r; -}, root); -const DialogClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(D__namespace.Close, { - asChild: true, - children: /* @__PURE__ */jsxRuntime.jsxs(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-dialog-close", props.className), - children: [/* @__PURE__ */jsxRuntime.jsx(reactVisuallyHidden.Root, { - children: "Close dialog" - }), /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {})] - }) -})); -DialogClose.displayName = "Dialog.Close"; -function DialogRoot({ - children, - ...props -}) { - return /* @__PURE__ */jsxRuntime.jsx(D__namespace.Root, { - ...props, - children: /* @__PURE__ */jsxRuntime.jsxs(D__namespace.Portal, { - children: [/* @__PURE__ */jsxRuntime.jsx(D__namespace.Overlay, { - className: "graphiql-dialog-overlay" - }), /* @__PURE__ */jsxRuntime.jsx(D__namespace.Content, { - className: "graphiql-dialog", - children - })] - }) - }); -} -const Dialog = createComponentGroup(DialogRoot, { - Close: DialogClose, - Title: D__namespace.Title, - Trigger: D__namespace.Trigger, - Description: D__namespace.Description -}); -const Button = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Trigger, { - asChild: true, - children: /* @__PURE__ */jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-un-styled", props.className) - }) -})); -Button.displayName = "DropdownMenuButton"; -function Content({ - children, - align = "start", - sideOffset = 5, - className, - ...props -}) { - return /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Portal, { - children: /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Content, { - align, - sideOffset, - className: clsx.clsx("graphiql-dropdown-content", className), - ...props, - children - }) - }); -} -const Item = ({ - className, - children, - ...props -}) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Item, { - className: clsx.clsx("graphiql-dropdown-item", className), - ...props, - children -}); -const DropdownMenu = createComponentGroup(reactDropdownMenu.Root, { - Button, - Item, - Content -}); -const markdown = new MarkdownIt({ - breaks: true, - linkify: true -}); -const MarkdownContent = React.forwardRef(({ - children, - onlyShowFirstChild, - type, - ...props -}, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx(`graphiql-markdown-${type}`, onlyShowFirstChild && "graphiql-markdown-preview", props.className), - dangerouslySetInnerHTML: { - __html: markdown.render(children) - } -})); -MarkdownContent.displayName = "MarkdownContent"; -const Spinner = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx("graphiql-spinner", props.className) -})); -Spinner.displayName = "Spinner"; -function TooltipRoot({ - children, - align = "start", - side = "bottom", - sideOffset = 5, - label -}) { - return /* @__PURE__ */jsxRuntime.jsxs(T__namespace.Root, { - children: [/* @__PURE__ */jsxRuntime.jsx(T__namespace.Trigger, { - asChild: true, - children - }), /* @__PURE__ */jsxRuntime.jsx(T__namespace.Portal, { - children: /* @__PURE__ */jsxRuntime.jsx(T__namespace.Content, { - className: "graphiql-tooltip", - align, - side, - sideOffset, - children: label - }) - })] - }); -} -const Tooltip = createComponentGroup(TooltipRoot, { - Provider: T__namespace.Provider -}); -const TabRoot = React.forwardRef(({ - isActive, - value, - children, - className, - ...props -}, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Item, { - ...props, - ref, - value, - "aria-selected": isActive ? "true" : void 0, - role: "tab", - className: clsx.clsx("graphiql-tab", isActive && "graphiql-tab-active", className), - children -})); -TabRoot.displayName = "Tab"; -const TabButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-tab-button", props.className), - children: props.children -})); -TabButton.displayName = "Tab.Button"; -const TabClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Close Tab", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - "aria-label": "Close Tab", - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-tab-close", props.className), - children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) - }) -})); -TabClose.displayName = "Tab.Close"; -const Tab = createComponentGroup(TabRoot, { - Button: TabButton, - Close: TabClose -}); -const Tabs = React.forwardRef(({ - values, - onReorder, - children, - className, - ...props -}, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Group, { - ...props, - ref, - values, - onReorder, - axis: "x", - role: "tablist", - className: clsx.clsx("graphiql-tabs", className), - children -})); -Tabs.displayName = "Tabs"; -const HistoryContext = createNullableContext("HistoryContext"); -function HistoryContextProvider(props) { - var _a; - const storage = useStorageContext(); - const historyStore = React.useRef(new toolkit.HistoryStore( - // Fall back to a noop storage when the StorageContext is empty - storage || new toolkit.StorageAPI(null), props.maxHistoryLength || DEFAULT_HISTORY_LENGTH)); - const [items, setItems] = React.useState(((_a = historyStore.current) == null ? void 0 : _a.queries) || []); - const addToHistory = React.useCallback(operation => { - var _a2; - (_a2 = historyStore.current) == null ? void 0 : _a2.updateHistory(operation); - setItems(historyStore.current.queries); - }, []); - const editLabel = React.useCallback((operation, index) => { - historyStore.current.editLabel(operation, index); - setItems(historyStore.current.queries); - }, []); - const toggleFavorite = React.useCallback(operation => { - historyStore.current.toggleFavorite(operation); - setItems(historyStore.current.queries); - }, []); - const setActive = React.useCallback(item => { - return item; - }, []); - const deleteFromHistory = React.useCallback((item, clearFavorites = false) => { - historyStore.current.deleteHistory(item, clearFavorites); - setItems(historyStore.current.queries); - }, []); - const value = React.useMemo(() => ({ - addToHistory, - editLabel, - items, - toggleFavorite, - setActive, - deleteFromHistory - }), [addToHistory, editLabel, items, toggleFavorite, setActive, deleteFromHistory]); - return /* @__PURE__ */jsxRuntime.jsx(HistoryContext.Provider, { - value, - children: props.children - }); -} -const useHistoryContext = createContextHook(HistoryContext); -const DEFAULT_HISTORY_LENGTH = 20; -function History() { - const { - items: all, - deleteFromHistory - } = useHistoryContext({ - nonNull: true - }); - let items = all.slice().map((item, i) => ({ - ...item, - index: i - })).reverse(); - const favorites = items.filter(item => item.favorite); - if (favorites.length) { - items = items.filter(item => !item.favorite); - } - const [clearStatus, setClearStatus] = React.useState(null); - React.useEffect(() => { - if (clearStatus) { - setTimeout(() => { - setClearStatus(null); - }, 2e3); - } - }, [clearStatus]); - const handleClearStatus = React.useCallback(() => { - try { - for (const item of items) { - deleteFromHistory(item, true); - } - setClearStatus("success"); - } catch { - setClearStatus("error"); - } - }, [deleteFromHistory, items]); - return /* @__PURE__ */jsxRuntime.jsxs("section", { - "aria-label": "History", - className: "graphiql-history", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-history-header", - children: ["History", (clearStatus || items.length > 0) && /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - state: clearStatus || void 0, - disabled: !items.length, - onClick: handleClearStatus, - children: { - success: "Cleared", - error: "Failed to Clear" - }[clearStatus] || "Clear" - })] - }), Boolean(favorites.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { - className: "graphiql-history-items", - children: favorites.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { - item - }, item.index)) - }), Boolean(favorites.length) && Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-history-item-spacer" - }), Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { - className: "graphiql-history-items", - children: items.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { - item - }, item.index)) - })] - }); -} -function HistoryItem(props) { - const { - editLabel, - toggleFavorite, - deleteFromHistory, - setActive - } = useHistoryContext({ - nonNull: true, - caller: HistoryItem - }); - const { - headerEditor, - queryEditor, - variableEditor - } = useEditorContext({ - nonNull: true, - caller: HistoryItem - }); - const inputRef = React.useRef(null); - const buttonRef = React.useRef(null); - const [isEditable, setIsEditable] = React.useState(false); - React.useEffect(() => { - var _a; - if (isEditable) { - (_a = inputRef.current) == null ? void 0 : _a.focus(); - } - }, [isEditable]); - const displayName = props.item.label || props.item.operationName || formatQuery(props.item.query); - const handleSave = React.useCallback(() => { - var _a; - setIsEditable(false); - const { - index, - ...item - } = props.item; - editLabel({ - ...item, - label: (_a = inputRef.current) == null ? void 0 : _a.value - }, index); - }, [editLabel, props.item]); - const handleClose = React.useCallback(() => { - setIsEditable(false); - }, []); - const handleEditLabel = React.useCallback(e => { - e.stopPropagation(); - setIsEditable(true); - }, []); - const handleHistoryItemClick = React.useCallback(() => { - const { - query, - variables, - headers - } = props.item; - queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); - variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); - headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); - setActive(props.item); - }, [headerEditor, props.item, queryEditor, setActive, variableEditor]); - const handleDeleteItemFromHistory = React.useCallback(e => { - e.stopPropagation(); - deleteFromHistory(props.item); - }, [props.item, deleteFromHistory]); - const handleToggleFavorite = React.useCallback(e => { - e.stopPropagation(); - toggleFavorite(props.item); - }, [props.item, toggleFavorite]); - return /* @__PURE__ */jsxRuntime.jsx("li", { - className: clsx.clsx("graphiql-history-item", isEditable && "editable"), - children: isEditable ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx("input", { - type: "text", - defaultValue: props.item.label, - ref: inputRef, - onKeyDown: e => { - if (e.key === "Esc") { - setIsEditable(false); - } else if (e.key === "Enter") { - setIsEditable(false); - editLabel({ - ...props.item, - label: e.currentTarget.value - }); - } - }, - placeholder: "Type a label" - }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - ref: buttonRef, - onClick: handleSave, - children: "Save" - }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - ref: buttonRef, - onClick: handleClose, - children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) - })] - }) : /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Set active", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-label", - onClick: handleHistoryItemClick, - "aria-label": "Set active", - children: displayName - }) - }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Edit label", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleEditLabel, - "aria-label": "Edit label", - children: /* @__PURE__ */jsxRuntime.jsx(PenIcon, { - "aria-hidden": "true" - }) - }) - }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: props.item.favorite ? "Remove favorite" : "Add favorite", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleToggleFavorite, - "aria-label": props.item.favorite ? "Remove favorite" : "Add favorite", - children: props.item.favorite ? /* @__PURE__ */jsxRuntime.jsx(StarFilledIcon, { - "aria-hidden": "true" - }) : /* @__PURE__ */jsxRuntime.jsx(StarIcon, { - "aria-hidden": "true" - }) - }) - }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Delete from history", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleDeleteItemFromHistory, - "aria-label": "Delete from history", - children: /* @__PURE__ */jsxRuntime.jsx(TrashIcon, { - "aria-hidden": "true" - }) - }) - })] - }) - }); -} -function formatQuery(query) { - return query == null ? void 0 : query.split("\n").map(line => line.replace(/#(.*)/, "")).join(" ").replaceAll("{", " { ").replaceAll("}", " } ").replaceAll(/[\s]{2,}/g, " "); -} -const ExecutionContext = createNullableContext("ExecutionContext"); -function ExecutionContextProvider({ - fetcher, - getDefaultFieldNames, - children, - operationName -}) { - if (!fetcher) { - throw new TypeError("The `ExecutionContextProvider` component requires a `fetcher` function to be passed as prop."); - } - const { - externalFragments, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - updateActiveTabValues - } = useEditorContext({ - nonNull: true, - caller: ExecutionContextProvider - }); - const history = useHistoryContext(); - const autoCompleteLeafs = useAutoCompleteLeafs({ - getDefaultFieldNames, - caller: ExecutionContextProvider - }); - const [isFetching, setIsFetching] = React.useState(false); - const [subscription, setSubscription] = React.useState(null); - const queryIdRef = React.useRef(0); - const stop = React.useCallback(() => { - subscription == null ? void 0 : subscription.unsubscribe(); - setIsFetching(false); - setSubscription(null); - }, [subscription]); - const run = React.useCallback(async () => { - var _ref; - if (!queryEditor || !responseEditor) { - return; - } - if (subscription) { - stop(); - return; - } - const setResponse = value2 => { - responseEditor.setValue(value2); - updateActiveTabValues({ - response: value2 - }); - }; - queryIdRef.current += 1; - const queryId = queryIdRef.current; - let query = autoCompleteLeafs() || queryEditor.getValue(); - const variablesString = variableEditor == null ? void 0 : variableEditor.getValue(); - let variables; - try { - variables = tryParseJsonObject({ - json: variablesString, - errorMessageParse: "Variables are invalid JSON", - errorMessageType: "Variables are not a JSON object." - }); - } catch (error) { - setResponse(error instanceof Error ? error.message : `${error}`); - return; - } - const headersString = headerEditor == null ? void 0 : headerEditor.getValue(); - let headers; - try { - headers = tryParseJsonObject({ - json: headersString, - errorMessageParse: "Headers are invalid JSON", - errorMessageType: "Headers are not a JSON object." - }); - } catch (error) { - setResponse(error instanceof Error ? error.message : `${error}`); - return; - } - if (externalFragments) { - const fragmentDependencies = queryEditor.documentAST ? graphqlLanguageService.getFragmentDependenciesForAST(queryEditor.documentAST, externalFragments) : []; - if (fragmentDependencies.length > 0) { - query += "\n" + fragmentDependencies.map(node => graphql.print(node)).join("\n"); - } - } - setResponse(""); - setIsFetching(true); - const opName = (_ref = operationName !== null && operationName !== void 0 ? operationName : queryEditor.operationName) !== null && _ref !== void 0 ? _ref : void 0; - history == null ? void 0 : history.addToHistory({ - query, - variables: variablesString, - headers: headersString, - operationName: opName - }); - try { - var _headers, _queryEditor$document; - const fullResponse = {}; - const handleResponse = result => { - if (queryId !== queryIdRef.current) { - return; - } - let maybeMultipart = Array.isArray(result) ? result : false; - if (!maybeMultipart && typeof result === "object" && result !== null && "hasNext" in result) { - maybeMultipart = [result]; - } - if (maybeMultipart) { - for (const part of maybeMultipart) { - mergeIncrementalResult(fullResponse, part); - } - setIsFetching(false); - setResponse(toolkit.formatResult(fullResponse)); - } else { - const response = toolkit.formatResult(result); - setIsFetching(false); - setResponse(response); - } - }; - const fetch2 = fetcher({ - query, - variables, - operationName: opName - }, { - headers: (_headers = headers) !== null && _headers !== void 0 ? _headers : void 0, - documentAST: (_queryEditor$document = queryEditor.documentAST) !== null && _queryEditor$document !== void 0 ? _queryEditor$document : void 0 - }); - const value2 = await Promise.resolve(fetch2); - if (toolkit.isObservable(value2)) { - setSubscription(value2.subscribe({ - next(result) { - handleResponse(result); - }, - error(error) { - setIsFetching(false); - if (error) { - setResponse(toolkit.formatError(error)); - } - setSubscription(null); + var _exportNames = { + createGraphiQLFetcher: true, + }; + Object.defineProperty(exports, "createGraphiQLFetcher", { + enumerable: true, + get: function () { + return _createFetcher.createGraphiQLFetcher; }, - complete() { - setIsFetching(false); - setSubscription(null); - } - })); - } else if (toolkit.isAsyncIterable(value2)) { - setSubscription({ - unsubscribe: () => { - var _a, _b; - return (_b = (_a = value2[Symbol.asyncIterator]()).return) == null ? void 0 : _b.call(_a); - } }); - for await (const result of value2) { - handleResponse(result); - } - setIsFetching(false); - setSubscription(null); - } else { - handleResponse(value2); - } - } catch (error) { - setIsFetching(false); - setResponse(toolkit.formatError(error)); - setSubscription(null); - } - }, [autoCompleteLeafs, externalFragments, fetcher, headerEditor, history, operationName, queryEditor, responseEditor, stop, subscription, updateActiveTabValues, variableEditor]); - const isSubscribed = Boolean(subscription); - const value = React.useMemo(() => ({ - isFetching, - isSubscribed, - operationName: operationName !== null && operationName !== void 0 ? operationName : null, - run, - stop - }), [isFetching, isSubscribed, operationName, run, stop]); - return /* @__PURE__ */jsxRuntime.jsx(ExecutionContext.Provider, { - value, - children - }); -} -const useExecutionContext = createContextHook(ExecutionContext); -function tryParseJsonObject({ - json, - errorMessageParse, - errorMessageType -}) { - let parsed; - try { - parsed = json && json.trim() !== "" ? JSON.parse(json) : void 0; - } catch (error) { - throw new Error(`${errorMessageParse}: ${error instanceof Error ? error.message : error}.`); - } - const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed); - if (parsed !== void 0 && !isObject) { - throw new Error(errorMessageType); - } - return parsed; -} -function mergeIncrementalResult(executionResult, incrementalResult) { - var _incrementalResult$pa; - const path = ["data", ...((_incrementalResult$pa = incrementalResult.path) !== null && _incrementalResult$pa !== void 0 ? _incrementalResult$pa : [])]; - if (incrementalResult.items) { - for (const item of incrementalResult.items) { - setValue(executionResult, path.join("."), item); - path[path.length - 1]++; - } - } - if (incrementalResult.data) { - setValue(executionResult, path.join("."), incrementalResult.data, { - merge: true - }); - } - if (incrementalResult.errors) { - executionResult.errors || (executionResult.errors = []); - executionResult.errors.push(...incrementalResult.errors); - } - if (incrementalResult.extensions) { - setValue(executionResult, "extensions", incrementalResult.extensions, { - merge: true - }); - } - if (incrementalResult.incremental) { - for (const incrementalSubResult of incrementalResult.incremental) { - mergeIncrementalResult(executionResult, incrementalSubResult); - } - } -} -const DEFAULT_EDITOR_THEME = "graphiql"; -const DEFAULT_KEY_MAP = "sublime"; -let isMacOs = false; -if (typeof window === "object") { - isMacOs = window.navigator.platform.toLowerCase().indexOf("mac") === 0; -} -const commonKeys = { - // Persistent search box in Query Editor - [isMacOs ? "Cmd-F" : "Ctrl-F"]: "findPersistent", - "Cmd-G": "findPersistent", - "Ctrl-G": "findPersistent", - // Editor improvements - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight" -}; -async function importCodeMirror(addons, options) { - const CodeMirror = await Promise.resolve().then(() => __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js")).then(n => n.codemirror).then(c => - // Depending on bundler and settings the dynamic import either returns a - // function (e.g. parcel) or an object containing a `default` property - typeof c === "function" ? c : c.default); - await Promise.all((options == null ? void 0 : options.useCommonAddons) === false ? addons : [Promise.resolve().then(() => __webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js")).then(n => n.showHint), Promise.resolve().then(() => __webpack_require__(/*! ./matchbrackets.cjs.js */ "../../graphiql-react/dist/matchbrackets.cjs.js")).then(n => n.matchbrackets), Promise.resolve().then(() => __webpack_require__(/*! ./closebrackets.cjs.js */ "../../graphiql-react/dist/closebrackets.cjs.js")).then(n => n.closebrackets), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs.js */ "../../graphiql-react/dist/lint.cjs.js")).then(n => n.lint), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), - // @ts-expect-error - Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), ...addons]); - return CodeMirror; -} -const printDefault = ast => { - if (!ast) { - return ""; - } - return graphql.print(ast); -}; -function DefaultValue({ - field -}) { - if (!("defaultValue" in field) || field.defaultValue === void 0) { - return null; - } - const ast = graphql.astFromValue(field.defaultValue, field.type); - if (!ast) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [" = ", /* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-default-value", - children: printDefault(ast) - })] - }); -} -const SchemaContext = createNullableContext("SchemaContext"); -function SchemaContextProvider(props) { - if (!props.fetcher) { - throw new TypeError("The `SchemaContextProvider` component requires a `fetcher` function to be passed as prop."); - } - const { - initialHeaders, - headerEditor - } = useEditorContext({ - nonNull: true, - caller: SchemaContextProvider - }); - const [schema, setSchema] = React.useState(); - const [isFetching, setIsFetching] = React.useState(false); - const [fetchError, setFetchError] = React.useState(null); - const counterRef = React.useRef(0); - React.useEffect(() => { - setSchema(graphql.isSchema(props.schema) || props.schema === null || props.schema === void 0 ? props.schema : void 0); - counterRef.current++; - }, [props.schema]); - const headersRef = React.useRef(initialHeaders); - React.useEffect(() => { - if (headerEditor) { - headersRef.current = headerEditor.getValue(); - } - }); - const { - introspectionQuery, - introspectionQueryName, - introspectionQuerySansSubscriptions - } = useIntrospectionQuery({ - inputValueDeprecation: props.inputValueDeprecation, - introspectionQueryName: props.introspectionQueryName, - schemaDescription: props.schemaDescription - }); - const { - fetcher, - onSchemaChange, - dangerouslyAssumeSchemaIsValid, - children - } = props; - const introspect = React.useCallback(() => { - if (graphql.isSchema(props.schema) || props.schema === null) { - return; - } - const counter = ++counterRef.current; - const maybeIntrospectionData = props.schema; - async function fetchIntrospectionData() { - if (maybeIntrospectionData) { - return maybeIntrospectionData; - } - const parsedHeaders = parseHeaderString(headersRef.current); - if (!parsedHeaders.isValidJSON) { - setFetchError("Introspection failed as headers are invalid."); - return; - } - const fetcherOpts = parsedHeaders.headers ? { - headers: parsedHeaders.headers - } : {}; - const fetch2 = toolkit.fetcherReturnToPromise(fetcher({ - query: introspectionQuery, - operationName: introspectionQueryName - }, fetcherOpts)); - if (!toolkit.isPromise(fetch2)) { - setFetchError("Fetcher did not return a Promise for introspection."); - return; - } - setIsFetching(true); - setFetchError(null); - let result = await fetch2; - if (typeof result !== "object" || result === null || !("data" in result)) { - const fetch22 = toolkit.fetcherReturnToPromise(fetcher({ - query: introspectionQuerySansSubscriptions, - operationName: introspectionQueryName - }, fetcherOpts)); - if (!toolkit.isPromise(fetch22)) { - throw new Error("Fetcher did not return a Promise for introspection."); - } - result = await fetch22; - } - setIsFetching(false); - if ((result == null ? void 0 : result.data) && "__schema" in result.data) { - return result.data; - } - const responseString = typeof result === "string" ? result : toolkit.formatResult(result); - setFetchError(responseString); - } - fetchIntrospectionData().then(introspectionData => { - if (counter !== counterRef.current || !introspectionData) { - return; - } - try { - const newSchema = graphql.buildClientSchema(introspectionData); - setSchema(newSchema); - onSchemaChange == null ? void 0 : onSchemaChange(newSchema); - } catch (error) { - setFetchError(toolkit.formatError(error)); - } - }).catch(error => { - if (counter !== counterRef.current) { - return; - } - setFetchError(toolkit.formatError(error)); - setIsFetching(false); - }); - }, [fetcher, introspectionQueryName, introspectionQuery, introspectionQuerySansSubscriptions, onSchemaChange, props.schema]); - React.useEffect(() => { - introspect(); - }, [introspect]); - React.useEffect(() => { - function triggerIntrospection(event) { - if (event.ctrlKey && event.key === "R") { - introspect(); - } - } - window.addEventListener("keydown", triggerIntrospection); - return () => window.removeEventListener("keydown", triggerIntrospection); - }); - const validationErrors = React.useMemo(() => { - if (!schema || dangerouslyAssumeSchemaIsValid) { - return []; - } - return graphql.validateSchema(schema); - }, [schema, dangerouslyAssumeSchemaIsValid]); - const value = React.useMemo(() => ({ - fetchError, - introspect, - isFetching, - schema, - validationErrors - }), [fetchError, introspect, isFetching, schema, validationErrors]); - return /* @__PURE__ */jsxRuntime.jsx(SchemaContext.Provider, { - value, - children - }); -} -const useSchemaContext = createContextHook(SchemaContext); -function useIntrospectionQuery({ - inputValueDeprecation, - introspectionQueryName, - schemaDescription -}) { - return React.useMemo(() => { - const queryName = introspectionQueryName || "IntrospectionQuery"; - let query = graphql.getIntrospectionQuery({ - inputValueDeprecation, - schemaDescription - }); - if (introspectionQueryName) { - query = query.replace("query IntrospectionQuery", `query ${queryName}`); - } - const querySansSubscriptions = query.replace("subscriptionType { name }", ""); - return { - introspectionQueryName: queryName, - introspectionQuery: query, - introspectionQuerySansSubscriptions: querySansSubscriptions - }; - }, [inputValueDeprecation, introspectionQueryName, schemaDescription]); -} -function parseHeaderString(headersString) { - let headers = null; - let isValidJSON = true; - try { - if (headersString) { - headers = JSON.parse(headersString); - } - } catch { - isValidJSON = false; - } - return { - headers, - isValidJSON - }; -} -const initialNavStackItem = { - name: "Docs" -}; -const ExplorerContext = createNullableContext("ExplorerContext"); -function ExplorerContextProvider(props) { - const { - schema, - validationErrors - } = useSchemaContext({ - nonNull: true, - caller: ExplorerContextProvider - }); - const [navStack, setNavStack] = React.useState([initialNavStackItem]); - const push = React.useCallback(item => { - setNavStack(currentState => { - const lastItem = currentState.at(-1); - return lastItem.def === item.def ? - // Avoid pushing duplicate items - currentState : [...currentState, item]; - }); - }, []); - const pop = React.useCallback(() => { - setNavStack(currentState => currentState.length > 1 ? currentState.slice(0, -1) : currentState); - }, []); - const reset = React.useCallback(() => { - setNavStack(currentState => currentState.length === 1 ? currentState : [initialNavStackItem]); - }, []); - React.useEffect(() => { - if (schema == null || validationErrors.length > 0) { - reset(); - } else { - setNavStack(oldNavStack => { - if (oldNavStack.length === 1) { - return oldNavStack; - } - const newNavStack = [initialNavStackItem]; - let lastEntity = null; - for (const item of oldNavStack) { - if (item === initialNavStackItem) { - continue; - } - if (item.def) { - if (graphql.isNamedType(item.def)) { - const newType = schema.getType(item.def.name); - if (newType) { - newNavStack.push({ - name: item.name, - def: newType - }); - lastEntity = newType; - } else { - break; + var _types = __webpack_require__( + /*! ./types */ "../../graphiql-toolkit/esm/create-fetcher/types.js" + ); + Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + }, + }); + }); + var _createFetcher = __webpack_require__( + /*! ./createFetcher */ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js" + ); + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/create-fetcher/lib.js": + /*!********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/lib.js ***! + \********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isSubscriptionWithName = + exports.getWsFetcher = + exports.createWebsocketsFetcherFromUrl = + exports.createWebsocketsFetcherFromClient = + exports.createSimpleFetcher = + exports.createMultipartFetcher = + exports.createLegacyWebsocketsFetcher = + void 0; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _meros = __webpack_require__( + /*! meros */ "../../../node_modules/meros/browser/index.js" + ); + var _pushPullAsyncIterableIterator = __webpack_require__( + /*! @n1ru4l/push-pull-async-iterable-iterator */ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js" + ); + var __awaiter = + (void 0 && (void 0).__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); + } } - } else if (lastEntity === null) { - break; - } else if (graphql.isObjectType(lastEntity) || graphql.isInputObjectType(lastEntity)) { - const field = lastEntity.getFields()[item.name]; - if (field) { - newNavStack.push({ - name: item.name, - def: field + 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 __await = + (void 0 && (void 0).__await) || + function (v) { + return this instanceof __await + ? ((this.v = v), this) + : new __await(v); + }; + var __asyncValues = + (void 0 && (void 0).__asyncValues) || + function (o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" + ? __values(o) + : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d, }); - } else { - break; + }, reject); + } + }; + var __asyncGenerator = + (void 0 && (void 0).__asyncGenerator) || + function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function verb(n) { + if (g[n]) + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); } - } else if (graphql.isScalarType(lastEntity) || graphql.isEnumType(lastEntity) || graphql.isInterfaceType(lastEntity) || graphql.isUnionType(lastEntity)) { - break; - } else { - const field = lastEntity; - const arg = field.args.find(a => a.name === item.name); - if (arg) { - newNavStack.push({ - name: item.name, - def: field - }); - } else { - break; + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } + }; + const errorHasCode = (err) => { + return typeof err === "object" && err !== null && "code" in err; + }; + const isSubscriptionWithName = (document, name) => { + let isSubscription = false; + (0, _graphql.visit)(document, { + OperationDefinition(node) { + var _a; + if ( + name === + ((_a = node.name) === null || _a === void 0 + ? void 0 + : _a.value) && + node.operation === "subscription" + ) { + isSubscription = true; } + }, + }); + return isSubscription; + }; + exports.isSubscriptionWithName = isSubscriptionWithName; + const createSimpleFetcher = + (options, httpFetch) => (graphQLParams, fetcherOpts) => + __awaiter(void 0, void 0, void 0, function* () { + const data = yield httpFetch(options.url, { + method: "POST", + body: JSON.stringify(graphQLParams), + headers: Object.assign( + Object.assign( + { + "content-type": "application/json", + }, + options.headers + ), + fetcherOpts === null || fetcherOpts === void 0 + ? void 0 + : fetcherOpts.headers + ), + }); + return data.json(); + }); + exports.createSimpleFetcher = createSimpleFetcher; + const createWebsocketsFetcherFromUrl = (url, connectionParams) => { + let wsClient; + try { + const { createClient } = __webpack_require__( + /*! graphql-ws */ "../../../node_modules/graphql-ws/lib/index.js" + ); + wsClient = createClient({ + url, + connectionParams, + }); + return createWebsocketsFetcherFromClient(wsClient); + } catch (err) { + if (errorHasCode(err) && err.code === "MODULE_NOT_FOUND") { + throw new Error( + "You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'" + ); } - } else { - lastEntity = null; - newNavStack.push(item); + console.error(`Error creating websocket client for ${url}`, err); } - } - return newNavStack; - }); - } - }, [reset, schema, validationErrors]); - const value = React.useMemo(() => ({ - explorerNavStack: navStack, - push, - pop, - reset - }), [navStack, push, pop, reset]); - return /* @__PURE__ */jsxRuntime.jsx(ExplorerContext.Provider, { - value, - children: props.children - }); -} -const useExplorerContext = createContextHook(ExplorerContext); -function renderType(type, renderNamedType) { - if (graphql.isNonNullType(type)) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [renderType(type.ofType, renderNamedType), "!"] - }); - } - if (graphql.isListType(type)) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["[", renderType(type.ofType, renderNamedType), "]"] - }); - } - return renderNamedType(type); -} -function TypeLink(props) { - const { - push - } = useExplorerContext({ - nonNull: true, - caller: TypeLink - }); - if (!props.type) { - return null; - } - return renderType(props.type, namedType => /* @__PURE__ */jsxRuntime.jsx("a", { - className: "graphiql-doc-explorer-type-name", - onClick: event => { - event.preventDefault(); - push({ - name: namedType.name, - def: namedType - }); - }, - href: "#", - children: namedType.name - })); -} -function Argument({ - arg, - showDefaultValue, - inline -}) { - const definition = /* @__PURE__ */jsxRuntime.jsxs("span", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-argument-name", - children: arg.name - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: arg.type - }), showDefaultValue !== false && /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { - field: arg - })] - }); - if (inline) { - return definition; - } - return /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-argument", - children: [definition, arg.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: arg.description - }) : null, arg.deprecationReason ? /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-argument-deprecation", - children: [/* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-argument-deprecation-label", - children: "Deprecated" - }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - children: arg.deprecationReason - })] - }) : null] - }); -} -function DeprecationReason(props) { - var _props$preview; - return props.children ? /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-deprecation", - children: [/* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-deprecation-label", - children: "Deprecated" - }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - onlyShowFirstChild: (_props$preview = props.preview) !== null && _props$preview !== void 0 ? _props$preview : true, - children: props.children - })] - }) : null; -} -function Directive({ - directive -}) { - return /* @__PURE__ */jsxRuntime.jsxs("span", { - className: "graphiql-doc-explorer-directive", - children: ["@", directive.name.value] - }); -} -function ExplorerSection(props) { - const Icon2 = TYPE_TO_ICON[props.title]; - return /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-section-title", - children: [/* @__PURE__ */jsxRuntime.jsx(Icon2, {}), props.title] - }), /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-section-content", - children: props.children - })] - }); -} -const TYPE_TO_ICON = { - Arguments: ArgumentIcon, - "Deprecated Arguments": DeprecatedArgumentIcon, - "Deprecated Enum Values": DeprecatedEnumValueIcon, - "Deprecated Fields": DeprecatedFieldIcon, - Directives: DirectiveIcon, - "Enum Values": EnumValueIcon, - Fields: FieldIcon, - Implements: ImplementsIcon, - Implementations: TypeIcon, - "Possible Types": TypeIcon, - "Root Types": RootTypeIcon, - Type: TypeIcon, - "All Schema Types": TypeIcon -}; -function FieldDocumentation(props) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [props.field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.field.description - }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { - preview: false, - children: props.field.deprecationReason - }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Type", - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: props.field.type - }) - }), /* @__PURE__ */jsxRuntime.jsx(Arguments, { - field: props.field - }), /* @__PURE__ */jsxRuntime.jsx(Directives, { - field: props.field - })] - }); -} -function Arguments({ - field -}) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!("args" in field)) { - return null; - } - const args = []; - const deprecatedArgs = []; - for (const argument of field.args) { - if (argument.deprecationReason) { - deprecatedArgs.push(argument); - } else { - args.push(argument); - } - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [args.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Arguments", - children: args.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg - }, arg.name)) - }) : null, deprecatedArgs.length > 0 ? showDeprecated || args.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Arguments", - children: deprecatedArgs.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg - }, arg.name)) - }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Arguments" - }) : null] - }); -} -function Directives({ - field -}) { - var _a; - const directives = ((_a = field.astNode) == null ? void 0 : _a.directives) || []; - if (!directives || directives.length === 0) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Directives", - children: directives.map(directive => /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(Directive, { - directive - }) - }, directive.name.value)) - }); -} -function SchemaDocumentation(props) { - var _a, _b, _c, _d; - const queryType = props.schema.getQueryType(); - const mutationType = (_b = (_a = props.schema).getMutationType) == null ? void 0 : _b.call(_a); - const subscriptionType = (_d = (_c = props.schema).getSubscriptionType) == null ? void 0 : _d.call(_c); - const typeMap = props.schema.getTypeMap(); - const ignoreTypesInAllSchema = [queryType == null ? void 0 : queryType.name, mutationType == null ? void 0 : mutationType.name, subscriptionType == null ? void 0 : subscriptionType.name]; - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.schema.description || "A GraphQL schema provides a root type for each kind of operation." - }), /* @__PURE__ */jsxRuntime.jsxs(ExplorerSection, { - title: "Root Types", - children: [queryType ? /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "query" - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: queryType - })] - }) : null, mutationType && /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "mutation" - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: mutationType - })] - }), subscriptionType && /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "subscription" - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: subscriptionType - })] - })] - }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "All Schema Types", - children: typeMap && /* @__PURE__ */jsxRuntime.jsx("div", { - children: Object.values(typeMap).map(type => { - if (ignoreTypesInAllSchema.includes(type.name) || type.name.startsWith("__")) { - return null; + }; + exports.createWebsocketsFetcherFromUrl = createWebsocketsFetcherFromUrl; + const createWebsocketsFetcherFromClient = + (wsClient) => (graphQLParams) => + (0, + _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)( + (sink) => + wsClient.subscribe( + graphQLParams, + Object.assign(Object.assign({}, sink), { + error(err) { + if (err instanceof CloseEvent) { + sink.error( + new Error( + `Socket closed with event ${err.code} ${ + err.reason || "" + }`.trim() + ) + ); + } else { + sink.error(err); + } + }, + }) + ) + ); + exports.createWebsocketsFetcherFromClient = + createWebsocketsFetcherFromClient; + const createLegacyWebsocketsFetcher = + (legacyWsClient) => (graphQLParams) => { + const observable = legacyWsClient.request(graphQLParams); + return (0, + _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)( + (sink) => observable.subscribe(sink).unsubscribe + ); + }; + exports.createLegacyWebsocketsFetcher = createLegacyWebsocketsFetcher; + const createMultipartFetcher = (options, httpFetch) => + function (graphQLParams, fetcherOpts) { + return __asyncGenerator(this, arguments, function* () { + var e_1, _a; + const response = yield __await( + httpFetch(options.url, { + method: "POST", + body: JSON.stringify(graphQLParams), + headers: Object.assign( + Object.assign( + { + "content-type": "application/json", + accept: "application/json, multipart/mixed", + }, + options.headers + ), + fetcherOpts === null || fetcherOpts === void 0 + ? void 0 + : fetcherOpts.headers + ), + }).then((r) => + (0, _meros.meros)(r, { + multiple: true, + }) + ) + ); + if ( + !(0, _pushPullAsyncIterableIterator.isAsyncIterable)(response) + ) { + return yield __await(yield yield __await(response.json())); + } + try { + for ( + var response_1 = __asyncValues(response), response_1_1; + (response_1_1 = yield __await(response_1.next())), + !response_1_1.done; + + ) { + const chunk = response_1_1.value; + if (chunk.some((part) => !part.json)) { + const message = chunk.map( + (part) => + `Headers::\n${part.headers}\n\nBody::\n${part.body}` + ); + throw new Error( + `Expected multipart chunks to be of json type. got:\n${message}` + ); + } + yield yield __await(chunk.map((part) => part.body)); + } + } catch (e_1_1) { + e_1 = { + error: e_1_1, + }; + } finally { + try { + if ( + response_1_1 && + !response_1_1.done && + (_a = response_1.return) + ) + yield __await(_a.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + }; + exports.createMultipartFetcher = createMultipartFetcher; + const getWsFetcher = (options, fetcherOpts) => { + if (options.wsClient) { + return createWebsocketsFetcherFromClient(options.wsClient); + } + if (options.subscriptionUrl) { + return createWebsocketsFetcherFromUrl( + options.subscriptionUrl, + Object.assign( + Object.assign({}, options.wsConnectionParams), + fetcherOpts === null || fetcherOpts === void 0 + ? void 0 + : fetcherOpts.headers + ) + ); } - return /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type - }) - }, type.name); - }) - }) - })] - }); -} -function debounce(duration, fn) { - let timeout; - return function (...args) { - if (timeout) { - window.clearTimeout(timeout); - } - timeout = window.setTimeout(() => { - timeout = null; - fn(...args); - }, duration); - }; -} -function Search() { - const { - explorerNavStack, - push - } = useExplorerContext({ - nonNull: true, - caller: Search - }); - const inputRef = React.useRef(null); - const getSearchResults = useSearchResults(); - const [searchValue, setSearchValue] = React.useState(""); - const [results, setResults] = React.useState(getSearchResults(searchValue)); - const debouncedGetSearchResults = React.useMemo(() => debounce(200, search => { - setResults(getSearchResults(search)); - }), [getSearchResults]); - React.useEffect(() => { - debouncedGetSearchResults(searchValue); - }, [debouncedGetSearchResults, searchValue]); - React.useEffect(() => { - function handleKeyDown(event) { - var _a; - if (event.metaKey && event.key === "k") { - (_a = inputRef.current) == null ? void 0 : _a.focus(); - } - } - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, []); - const navItem = explorerNavStack.at(-1); - const onSelect = React.useCallback(def => { - push("field" in def ? { - name: def.field.name, - def: def.field - } : { - name: def.type.name, - def: def.type - }); - }, [push]); - const isFocused = React.useRef(false); - const handleFocus = React.useCallback(e => { - isFocused.current = e.type === "focus"; - }, []); - const shouldSearchBoxAppear = explorerNavStack.length === 1 || graphql.isObjectType(navItem.def) || graphql.isInterfaceType(navItem.def) || graphql.isInputObjectType(navItem.def); - if (!shouldSearchBoxAppear) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsxs(react.Combobox, { - as: "div", - className: "graphiql-doc-explorer-search", - onChange: onSelect, - "data-state": isFocused ? void 0 : "idle", - "aria-label": `Search ${navItem.name}...`, - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-search-input", - onClick: () => { - var _a; - (_a = inputRef.current) == null ? void 0 : _a.focus(); + const legacyWebsocketsClient = + options.legacyClient || options.legacyWsClient; + if (legacyWebsocketsClient) { + return createLegacyWebsocketsFetcher(legacyWebsocketsClient); + } + }; + exports.getWsFetcher = getWsFetcher; + + /***/ }, - children: [/* @__PURE__ */jsxRuntime.jsx(MagnifyingGlassIcon, {}), /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Input, { - autoComplete: "off", - onFocus: handleFocus, - onBlur: handleFocus, - onChange: event => setSearchValue(event.target.value), - placeholder: "⌘ K", - ref: inputRef, - value: searchValue, - "data-cy": "doc-explorer-input" - })] - }), isFocused.current && /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Options, { - "data-cy": "doc-explorer-list", - children: [results.within.length + results.types.length + results.fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx("li", { - className: "graphiql-doc-explorer-search-empty", - children: "No results found" - }) : results.within.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { - value: result, - "data-cy": "doc-explorer-option", - children: /* @__PURE__ */jsxRuntime.jsx(Field$1, { - field: result.field, - argument: result.argument - }) - }, `within-${i}`)), results.within.length > 0 && results.types.length + results.fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-search-divider", - children: "Other results" - }) : null, results.types.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { - value: result, - "data-cy": "doc-explorer-option", - children: /* @__PURE__ */jsxRuntime.jsx(Type, { - type: result.type - }) - }, `type-${i}`)), results.fields.map((result, i) => /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Option, { - value: result, - "data-cy": "doc-explorer-option", - children: [/* @__PURE__ */jsxRuntime.jsx(Type, { - type: result.type - }), ".", /* @__PURE__ */jsxRuntime.jsx(Field$1, { - field: result.field, - argument: result.argument - })] - }, `field-${i}`))] - })] - }); -} -function useSearchResults(caller) { - const { - explorerNavStack - } = useExplorerContext({ - nonNull: true, - caller: caller || useSearchResults - }); - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: caller || useSearchResults - }); - const navItem = explorerNavStack.at(-1); - return React.useCallback(searchValue => { - const matches = { - within: [], - types: [], - fields: [] - }; - if (!schema) { - return matches; - } - const withinType = navItem.def; - const typeMap = schema.getTypeMap(); - let typeNames = Object.keys(typeMap); - if (withinType) { - typeNames = typeNames.filter(n => n !== withinType.name); - typeNames.unshift(withinType.name); - } - for (const typeName of typeNames) { - if (matches.within.length + matches.types.length + matches.fields.length >= 100) { - break; - } - const type = typeMap[typeName]; - if (withinType !== type && isMatch(typeName, searchValue)) { - matches.types.push({ - type + + /***/ "../../graphiql-toolkit/esm/create-fetcher/types.js": + /*!**********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/types.js ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { - continue; - } - const fields = type.getFields(); - for (const fieldName in fields) { - const field = fields[fieldName]; - let matchingArgs; - if (!isMatch(fieldName, searchValue)) { - if ("args" in field) { - matchingArgs = field.args.filter(arg => isMatch(arg.name, searchValue)); - if (matchingArgs.length === 0) { - continue; - } - } else { - continue; - } + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/format/index.js": + /*!**************************************************!*\ + !*** ../../graphiql-toolkit/esm/format/index.js ***! + \**************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.formatError = formatError; + exports.formatResult = formatResult; + function stringify(obj) { + return JSON.stringify(obj, null, 2); + } + function formatSingleError(error) { + return Object.assign(Object.assign({}, error), { + message: error.message, + stack: error.stack, + }); } - matches[withinType === type ? "within" : "fields"].push(...(matchingArgs ? matchingArgs.map(argument => ({ - type, - field, - argument - })) : [{ - type, - field - }])); - } - } - return matches; - }, [navItem.def, schema]); -} -function isMatch(sourceText, searchValue) { - try { - const escaped = searchValue.replaceAll(/[^_0-9A-Za-z]/g, ch => "\\" + ch); - return sourceText.search(new RegExp(escaped, "i")) !== -1; - } catch { - return sourceText.toLowerCase().includes(searchValue.toLowerCase()); - } -} -function Type(props) { - return /* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-type", - children: props.type.name - }); -} -function Field$1({ - field, - argument -}) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-field", - children: field.name - }), argument ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-argument", - children: argument.name - }), ":", " ", renderType(argument.type, namedType => /* @__PURE__ */jsxRuntime.jsx(Type, { - type: namedType - })), ")"] - }) : null] - }); -} -function FieldLink(props) { - const { - push - } = useExplorerContext({ - nonNull: true - }); - return /* @__PURE__ */jsxRuntime.jsx("a", { - className: "graphiql-doc-explorer-field-name", - onClick: event => { - event.preventDefault(); - push({ - name: props.field.name, - def: props.field - }); - }, - href: "#", - children: props.field.name - }); -} -function TypeDocumentation(props) { - return graphql.isNamedType(props.type) ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [props.type.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.type.description - }) : null, /* @__PURE__ */jsxRuntime.jsx(ImplementsInterfaces, { - type: props.type - }), /* @__PURE__ */jsxRuntime.jsx(Fields, { - type: props.type - }), /* @__PURE__ */jsxRuntime.jsx(EnumValues, { - type: props.type - }), /* @__PURE__ */jsxRuntime.jsx(PossibleTypes, { - type: props.type - })] - }) : null; -} -function ImplementsInterfaces({ - type -}) { - if (!graphql.isObjectType(type)) { - return null; - } - const interfaces = type.getInterfaces(); - return interfaces.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Implements", - children: type.getInterfaces().map(implementedInterface => /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: implementedInterface - }) - }, implementedInterface.name)) - }) : null; -} -function Fields({ - type -}) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { - return null; - } - const fieldMap = type.getFields(); - const fields = []; - const deprecatedFields = []; - for (const field of Object.keys(fieldMap).map(name => fieldMap[name])) { - if (field.deprecationReason) { - deprecatedFields.push(field); - } else { - fields.push(field); - } - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Fields", - children: fields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { - field - }, field.name)) - }) : null, deprecatedFields.length > 0 ? showDeprecated || fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Fields", - children: deprecatedFields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { - field - }, field.name)) - }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Fields" - }) : null] - }); -} -function Field({ - field -}) { - const args = "args" in field ? field.args.filter(arg => !arg.deprecationReason) : []; - return /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-item", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx(FieldLink, { - field - }), args.length > 0 ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { - children: args.map(arg => args.length === 1 ? /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg, - inline: true - }, arg.name) : /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-argument-multiple", - children: /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg, - inline: true - }) - }, arg.name)) - }), ")"] - }) : null, ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: field.type - }), /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { - field - })] - }), field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - onlyShowFirstChild: true, - children: field.description - }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { - children: field.deprecationReason - })] - }); -} -function EnumValues({ - type -}) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!graphql.isEnumType(type)) { - return null; - } - const values = []; - const deprecatedValues = []; - for (const value of type.getValues()) { - if (value.deprecationReason) { - deprecatedValues.push(value); - } else { - values.push(value); - } - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [values.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Enum Values", - children: values.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { - value - }, value.name)) - }) : null, deprecatedValues.length > 0 ? showDeprecated || values.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Enum Values", - children: deprecatedValues.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { - value - }, value.name)) - }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Values" - }) : null] - }); -} -function EnumValue({ - value -}) { - return /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-item", - children: [/* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-enum-value", - children: value.name - }), value.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: value.description - }) : null, value.deprecationReason ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - children: value.deprecationReason - }) : null] - }); -} -function PossibleTypes({ - type -}) { - const { - schema - } = useSchemaContext({ - nonNull: true - }); - if (!schema || !graphql.isAbstractType(type)) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: graphql.isInterfaceType(type) ? "Implementations" : "Possible Types", - children: schema.getPossibleTypes(type).map(possibleType => /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: possibleType - }) - }, possibleType.name)) - }); -} -function DocExplorer() { - const { - fetchError, - isFetching, - schema, - validationErrors - } = useSchemaContext({ - nonNull: true, - caller: DocExplorer - }); - const { - explorerNavStack, - pop - } = useExplorerContext({ - nonNull: true, - caller: DocExplorer - }); - const navItem = explorerNavStack.at(-1); - let content = null; - if (fetchError) { - content = /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-error", - children: "Error fetching schema" - }); - } else if (validationErrors.length > 0) { - content = /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-error", - children: ["Schema is invalid: ", validationErrors[0].message] - }); - } else if (isFetching) { - content = /* @__PURE__ */jsxRuntime.jsx(Spinner, {}); - } else if (!schema) { - content = /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-error", - children: "No GraphQL schema available" - }); - } else if (explorerNavStack.length === 1) { - content = /* @__PURE__ */jsxRuntime.jsx(SchemaDocumentation, { - schema - }); - } else if (graphql.isType(navItem.def)) { - content = /* @__PURE__ */jsxRuntime.jsx(TypeDocumentation, { - type: navItem.def - }); - } else if (navItem.def) { - content = /* @__PURE__ */jsxRuntime.jsx(FieldDocumentation, { - field: navItem.def - }); - } - let prevName; - if (explorerNavStack.length > 1) { - prevName = explorerNavStack.at(-2).name; - } - return /* @__PURE__ */jsxRuntime.jsxs("section", { - className: "graphiql-doc-explorer", - "aria-label": "Documentation Explorer", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-header", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-header-content", - children: [prevName && /* @__PURE__ */jsxRuntime.jsxs("a", { - href: "#", - className: "graphiql-doc-explorer-back", - onClick: event => { - event.preventDefault(); - pop(); - }, - "aria-label": `Go back to ${prevName}`, - children: [/* @__PURE__ */jsxRuntime.jsx(ChevronLeftIcon, {}), prevName] - }), /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-title", - children: navItem.name - })] - }), /* @__PURE__ */jsxRuntime.jsx(Search, {}, navItem.name)] - }), /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-content", - children: content - })] - }); -} -const DOC_EXPLORER_PLUGIN = { - title: "Documentation Explorer", - icon: function Icon() { - const pluginContext = usePluginContext(); - return (pluginContext == null ? void 0 : pluginContext.visiblePlugin) === DOC_EXPLORER_PLUGIN ? /* @__PURE__ */jsxRuntime.jsx(DocsFilledIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(DocsIcon, {}); - }, - content: DocExplorer -}; -const HISTORY_PLUGIN = { - title: "History", - icon: HistoryIcon, - content: History -}; -const PluginContext = createNullableContext("PluginContext"); -function PluginContextProvider(props) { - const storage = useStorageContext(); - const explorerContext = useExplorerContext(); - const historyContext = useHistoryContext(); - const hasExplorerContext = Boolean(explorerContext); - const hasHistoryContext = Boolean(historyContext); - const plugins = React.useMemo(() => { - const pluginList = []; - const pluginTitles = {}; - if (hasExplorerContext) { - pluginList.push(DOC_EXPLORER_PLUGIN); - pluginTitles[DOC_EXPLORER_PLUGIN.title] = true; - } - if (hasHistoryContext) { - pluginList.push(HISTORY_PLUGIN); - pluginTitles[HISTORY_PLUGIN.title] = true; - } - for (const plugin of props.plugins || []) { - if (typeof plugin.title !== "string" || !plugin.title) { - throw new Error("All GraphiQL plugins must have a unique title"); - } - if (pluginTitles[plugin.title]) { - throw new Error(`All GraphiQL plugins must have a unique title, found two plugins with the title '${plugin.title}'`); - } else { - pluginList.push(plugin); - pluginTitles[plugin.title] = true; - } - } - return pluginList; - }, [hasExplorerContext, hasHistoryContext, props.plugins]); - const [visiblePlugin, internalSetVisiblePlugin] = React.useState(() => { - const storedValue = storage == null ? void 0 : storage.get(STORAGE_KEY$4); - const pluginForStoredValue = plugins.find(plugin => plugin.title === storedValue); - if (pluginForStoredValue) { - return pluginForStoredValue; - } - if (storedValue) { - storage == null ? void 0 : storage.set(STORAGE_KEY$4, ""); - } - if (!props.visiblePlugin) { - return null; - } - return plugins.find(plugin => (typeof props.visiblePlugin === "string" ? plugin.title : plugin) === props.visiblePlugin) || null; - }); - const { - onTogglePluginVisibility, - children - } = props; - const setVisiblePlugin = React.useCallback(plugin => { - const newVisiblePlugin = plugin ? plugins.find(p => (typeof plugin === "string" ? p.title : p) === plugin) || null : null; - internalSetVisiblePlugin(current => { - if (newVisiblePlugin === current) { - return current; - } - onTogglePluginVisibility == null ? void 0 : onTogglePluginVisibility(newVisiblePlugin); - return newVisiblePlugin; - }); - }, [onTogglePluginVisibility, plugins]); - React.useEffect(() => { - if (props.visiblePlugin) { - setVisiblePlugin(props.visiblePlugin); - } - }, [plugins, props.visiblePlugin, setVisiblePlugin]); - const value = React.useMemo(() => ({ - plugins, - setVisiblePlugin, - visiblePlugin - }), [plugins, setVisiblePlugin, visiblePlugin]); - return /* @__PURE__ */jsxRuntime.jsx(PluginContext.Provider, { - value, - children - }); -} -const usePluginContext = createContextHook(PluginContext); -const STORAGE_KEY$4 = "visiblePlugin"; -function onHasCompletion(_cm, data, schema, explorer, plugin, callback) { - void importCodeMirror([], { - useCommonAddons: false - }).then(CodeMirror => { - let information; - let fieldName; - let typeNamePill; - let typeNamePrefix; - let typeName; - let typeNameSuffix; - let description; - let deprecation; - let deprecationReason; - CodeMirror.on(data, "select", - // @ts-expect-error - (ctx, el) => { - if (!information) { - const hintsUl = el.parentNode; - information = document.createElement("div"); - information.className = "CodeMirror-hint-information"; - hintsUl.append(information); - const header = document.createElement("header"); - header.className = "CodeMirror-hint-information-header"; - information.append(header); - fieldName = document.createElement("span"); - fieldName.className = "CodeMirror-hint-information-field-name"; - header.append(fieldName); - typeNamePill = document.createElement("span"); - typeNamePill.className = "CodeMirror-hint-information-type-name-pill"; - header.append(typeNamePill); - typeNamePrefix = document.createElement("span"); - typeNamePill.append(typeNamePrefix); - typeName = document.createElement("a"); - typeName.className = "CodeMirror-hint-information-type-name"; - typeName.href = "javascript:void 0"; - typeName.addEventListener("click", onClickHintInformation); - typeNamePill.append(typeName); - typeNameSuffix = document.createElement("span"); - typeNamePill.append(typeNameSuffix); - description = document.createElement("div"); - description.className = "CodeMirror-hint-information-description"; - information.append(description); - deprecation = document.createElement("div"); - deprecation.className = "CodeMirror-hint-information-deprecation"; - information.append(deprecation); - const deprecationLabel = document.createElement("span"); - deprecationLabel.className = "CodeMirror-hint-information-deprecation-label"; - deprecationLabel.textContent = "Deprecated"; - deprecation.append(deprecationLabel); - deprecationReason = document.createElement("div"); - deprecationReason.className = "CodeMirror-hint-information-deprecation-reason"; - deprecation.append(deprecationReason); - const defaultInformationPadding = parseInt(window.getComputedStyle(information).paddingBottom.replace(/px$/, ""), 10) || 0; - const defaultInformationMaxHeight = parseInt(window.getComputedStyle(information).maxHeight.replace(/px$/, ""), 10) || 0; - const handleScroll = () => { - if (information) { - information.style.paddingTop = hintsUl.scrollTop + defaultInformationPadding + "px"; - information.style.maxHeight = hintsUl.scrollTop + defaultInformationMaxHeight + "px"; + function handleSingleError(error) { + if (error instanceof Error) { + return formatSingleError(error); } - }; - hintsUl.addEventListener("scroll", handleScroll); - let onRemoveFn; - hintsUl.addEventListener("DOMNodeRemoved", onRemoveFn = event => { - if (event.target !== hintsUl) { - return; + return error; + } + function formatError(error) { + if (Array.isArray(error)) { + return stringify({ + errors: error.map((e) => handleSingleError(e)), + }); } - hintsUl.removeEventListener("scroll", handleScroll); - hintsUl.removeEventListener("DOMNodeRemoved", onRemoveFn); - if (information) { - information.removeEventListener("click", onClickHintInformation); - } - information = null; - fieldName = null; - typeNamePill = null; - typeNamePrefix = null; - typeName = null; - typeNameSuffix = null; - description = null; - deprecation = null; - deprecationReason = null; - onRemoveFn = null; + return stringify({ + errors: [handleSingleError(error)], + }); + } + function formatResult(result) { + return stringify(result); + } + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js": + /*!*******************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js ***! + \*******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - } - if (fieldName) { - fieldName.textContent = ctx.text; - } - if (typeNamePill && typeNamePrefix && typeName && typeNameSuffix) { - if (ctx.type) { - typeNamePill.style.display = "inline"; - const renderType2 = type => { - if (graphql.isNonNullType(type)) { - typeNameSuffix.textContent = "!" + typeNameSuffix.textContent; - renderType2(type.ofType); - } else if (graphql.isListType(type)) { - typeNamePrefix.textContent += "["; - typeNameSuffix.textContent = "]" + typeNameSuffix.textContent; - renderType2(type.ofType); - } else { - typeName.textContent = type.name; - } + exports.fillLeafs = fillLeafs; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function fillLeafs(schema, docString, getDefaultFieldNames) { + const insertions = []; + if (!schema || !docString) { + return { + insertions, + result: docString, + }; + } + let ast; + try { + ast = (0, _graphql.parse)(docString); + } catch (_a) { + return { + insertions, + result: docString, + }; + } + const fieldNameFn = + getDefaultFieldNames || defaultGetDefaultFieldNames; + const typeInfo = new _graphql.TypeInfo(schema); + (0, _graphql.visit)(ast, { + leave(node) { + typeInfo.leave(node); + }, + enter(node) { + typeInfo.enter(node); + if (node.kind === "Field" && !node.selectionSet) { + const fieldType = typeInfo.getType(); + const selectionSet = buildSelectionSet( + isFieldType(fieldType), + fieldNameFn + ); + if (selectionSet && node.loc) { + const indent = getIndentation(docString, node.loc.start); + insertions.push({ + index: node.loc.end, + string: + " " + + (0, _graphql.print)(selectionSet).replaceAll( + "\n", + "\n" + indent + ), + }); + } + } + }, + }); + return { + insertions, + result: withInsertions(docString, insertions), }; - typeNamePrefix.textContent = ""; - typeNameSuffix.textContent = ""; - renderType2(ctx.type); - } else { - typeNamePrefix.textContent = ""; - typeName.textContent = ""; - typeNameSuffix.textContent = ""; - typeNamePill.style.display = "none"; - } - } - if (description) { - if (ctx.description) { - description.style.display = "block"; - description.innerHTML = markdown.render(ctx.description); - } else { - description.style.display = "none"; - description.innerHTML = ""; } - } - if (deprecation && deprecationReason) { - if (ctx.deprecationReason) { - deprecation.style.display = "block"; - deprecationReason.innerHTML = markdown.render(ctx.deprecationReason); - } else { - deprecation.style.display = "none"; - deprecationReason.innerHTML = ""; + function defaultGetDefaultFieldNames(type) { + if (!("getFields" in type)) { + return []; + } + const fields = type.getFields(); + if (fields.id) { + return ["id"]; + } + if (fields.edges) { + return ["edges"]; + } + if (fields.node) { + return ["node"]; + } + const leafFieldNames = []; + for (const fieldName of Object.keys(fields)) { + if ((0, _graphql.isLeafType)(fields[fieldName].type)) { + leafFieldNames.push(fieldName); + } + } + return leafFieldNames; } - } - }); - }); - function onClickHintInformation(event) { - if (!schema || !explorer || !plugin || !(event.currentTarget instanceof HTMLElement)) { - return; - } - const typeName = event.currentTarget.textContent || ""; - const type = schema.getType(typeName); - if (type) { - plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); - explorer.push({ - name: type.name, - def: type - }); - callback == null ? void 0 : callback(type); - } - } -} -function useSynchronizeValue(editor, value) { - React.useEffect(() => { - if (editor && typeof value === "string" && value !== editor.getValue()) { - editor.setValue(value); - } - }, [editor, value]); -} -function useSynchronizeOption(editor, option, value) { - React.useEffect(() => { - if (editor) { - editor.setOption(option, value); - } - }, [editor, option, value]); -} -function useChangeHandler(editor, callback, storageKey, tabProperty, caller) { - const { - updateActiveTabValues - } = useEditorContext({ - nonNull: true, - caller - }); - const storage = useStorageContext(); - React.useEffect(() => { - if (!editor) { - return; - } - const store = debounce(500, value => { - if (!storage || storageKey === null) { - return; - } - storage.set(storageKey, value); - }); - const updateTab = debounce(100, value => { - updateActiveTabValues({ - [tabProperty]: value - }); - }); - const handleChange = (editorInstance, changeObj) => { - if (!changeObj) { - return; - } - const newValue = editorInstance.getValue(); - store(newValue); - updateTab(newValue); - callback == null ? void 0 : callback(newValue); - }; - editor.on("change", handleChange); - return () => editor.off("change", handleChange); - }, [callback, editor, storage, storageKey, tabProperty, updateActiveTabValues]); -} -function useCompletion(editor, callback, caller) { - const { - schema - } = useSchemaContext({ - nonNull: true, - caller - }); - const explorer = useExplorerContext(); - const plugin = usePluginContext(); - React.useEffect(() => { - if (!editor) { - return; - } - const handleCompletion = (instance, changeObj) => { - onHasCompletion(instance, changeObj, schema, explorer, plugin, type => { - callback == null ? void 0 : callback({ - kind: "Type", - type, - schema: schema || void 0 - }); - }); - }; - editor.on( - // @ts-expect-error @TODO additional args for hasCompletion event - "hasCompletion", handleCompletion); - return () => editor.off( - // @ts-expect-error @TODO additional args for hasCompletion event - "hasCompletion", handleCompletion); - }, [callback, editor, explorer, plugin, schema]); -} -function useKeyMap(editor, keys, callback) { - React.useEffect(() => { - if (!editor) { - return; - } - for (const key of keys) { - editor.removeKeyMap(key); - } - if (callback) { - const keyMap = {}; - for (const key of keys) { - keyMap[key] = () => callback(); - } - editor.addKeyMap(keyMap); - } - }, [editor, keys, callback]); -} -function useCopyQuery({ - caller, - onCopyQuery -} = {}) { - const { - queryEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useCopyQuery - }); - return React.useCallback(() => { - if (!queryEditor) { - return; - } - const query = queryEditor.getValue(); - copyToClipboard(query); - onCopyQuery == null ? void 0 : onCopyQuery(query); - }, [queryEditor, onCopyQuery]); -} -function useMergeQuery({ - caller -} = {}) { - const { - queryEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useMergeQuery - }); - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: useMergeQuery - }); - return React.useCallback(() => { - const documentAST = queryEditor == null ? void 0 : queryEditor.documentAST; - const query = queryEditor == null ? void 0 : queryEditor.getValue(); - if (!documentAST || !query) { - return; - } - queryEditor.setValue(graphql.print(toolkit.mergeAst(documentAST, schema))); - }, [queryEditor, schema]); -} -function usePrettifyEditors({ - caller -} = {}) { - const { - queryEditor, - headerEditor, - variableEditor - } = useEditorContext({ - nonNull: true, - caller: caller || usePrettifyEditors - }); - return React.useCallback(() => { - if (variableEditor) { - const variableEditorContent = variableEditor.getValue(); - try { - const prettifiedVariableEditorContent = JSON.stringify(JSON.parse(variableEditorContent), null, 2); - if (prettifiedVariableEditorContent !== variableEditorContent) { - variableEditor.setValue(prettifiedVariableEditorContent); - } - } catch {} - } - if (headerEditor) { - const headerEditorContent = headerEditor.getValue(); - try { - const prettifiedHeaderEditorContent = JSON.stringify(JSON.parse(headerEditorContent), null, 2); - if (prettifiedHeaderEditorContent !== headerEditorContent) { - headerEditor.setValue(prettifiedHeaderEditorContent); - } - } catch {} - } - if (queryEditor) { - const editorContent = queryEditor.getValue(); - const prettifiedEditorContent = graphql.print(graphql.parse(editorContent)); - if (prettifiedEditorContent !== editorContent) { - queryEditor.setValue(prettifiedEditorContent); - } - } - }, [queryEditor, variableEditor, headerEditor]); -} -function useAutoCompleteLeafs({ - getDefaultFieldNames, - caller -} = {}) { - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: caller || useAutoCompleteLeafs - }); - const { - queryEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useAutoCompleteLeafs - }); - return React.useCallback(() => { - if (!queryEditor) { - return; - } - const query = queryEditor.getValue(); - const { - insertions, - result - } = toolkit.fillLeafs(schema, query, getDefaultFieldNames); - if (insertions && insertions.length > 0) { - queryEditor.operation(() => { - const cursor = queryEditor.getCursor(); - const cursorIndex = queryEditor.indexFromPos(cursor); - queryEditor.setValue(result || ""); - let added = 0; - const markers = insertions.map(({ - index, - string - }) => queryEditor.markText(queryEditor.posFromIndex(index + added), queryEditor.posFromIndex(index + (added += string.length)), { - className: "auto-inserted-leaf", - clearOnEnter: true, - title: "Automatically added leaf fields" - })); - setTimeout(() => { - for (const marker of markers) { - marker.clear(); - } - }, 7e3); - let newCursorIndex = cursorIndex; - for (const { - index, - string - } of insertions) { - if (index < cursorIndex) { - newCursorIndex += string.length; - } - } - queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex)); - }); - } - return result; - }, [getDefaultFieldNames, queryEditor, schema]); -} -const useEditorState = editor => { - var _ref2; - const context = useEditorContext({ - nonNull: true - }); - const editorInstance = context[`${editor}Editor`]; - let valueString = ""; - const editorValue = (_ref2 = editorInstance == null ? void 0 : editorInstance.getValue()) !== null && _ref2 !== void 0 ? _ref2 : false; - if (editorValue && editorValue.length > 0) { - valueString = editorValue; - } - const handleEditorValue = React.useCallback(value => editorInstance == null ? void 0 : editorInstance.setValue(value), [editorInstance]); - return React.useMemo(() => [valueString, handleEditorValue], [valueString, handleEditorValue]); -}; -const useOperationsEditorState = () => { - return useEditorState("query"); -}; -const useVariablesEditorState = () => { - return useEditorState("variable"); -}; -const useHeadersEditorState = () => { - return useEditorState("header"); -}; -function useOptimisticState([upstreamState, upstreamSetState]) { - const lastStateRef = React.useRef({ - /** The last thing that we sent upstream; we're expecting this back */ - pending: null, - /** The last thing we received from upstream */ - last: upstreamState - }); - const [state, setOperationsText] = React.useState(upstreamState); - React.useEffect(() => { - if (lastStateRef.current.last === upstreamState) ;else { - lastStateRef.current.last = upstreamState; - if (lastStateRef.current.pending === null) { - setOperationsText(upstreamState); - } else if (lastStateRef.current.pending === upstreamState) { - lastStateRef.current.pending = null; - if (upstreamState !== state) { - lastStateRef.current.pending = state; - upstreamSetState(state); - } - } else { - lastStateRef.current.pending = null; - setOperationsText(upstreamState); - } - } - }, [upstreamState, state, upstreamSetState]); - const setState = React.useCallback(newState => { - setOperationsText(newState); - if (lastStateRef.current.pending === null && lastStateRef.current.last !== newState) { - lastStateRef.current.pending = newState; - upstreamSetState(newState); - } - }, [upstreamSetState]); - return React.useMemo(() => [state, setState], [state, setState]); -} -function useHeaderEditor({ - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onEdit, - readOnly = false -} = {}, caller) { - const { - initialHeaders, - headerEditor, - setHeaderEditor, - shouldPersistHeaders - } = useEditorContext({ - nonNull: true, - caller: caller || useHeaderEditor - }); - const executionContext = useExecutionContext(); - const merge = useMergeQuery({ - caller: caller || useHeaderEditor - }); - const prettify = usePrettifyEditors({ - caller: caller || useHeaderEditor - }); - const ref = React.useRef(null); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([ - // @ts-expect-error - Promise.resolve().then(() => __webpack_require__(/*! ./javascript.cjs.js */ "../../graphiql-react/dist/javascript.cjs.js")).then(n => n.javascript)]).then(CodeMirror => { - if (!isActive) { - return; - } - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialHeaders, - lineNumbers: true, - tabSize: 2, - mode: { - name: "javascript", - json: true - }, - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - foldGutter: true, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: commonKeys - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: false, - container + function buildSelectionSet(type, getDefaultFieldNames) { + const namedType = (0, _graphql.getNamedType)(type); + if (!type || (0, _graphql.isLeafType)(type)) { + return; + } + const fieldNames = getDefaultFieldNames(namedType); + if ( + !Array.isArray(fieldNames) || + fieldNames.length === 0 || + !("getFields" in namedType) + ) { + return; + } + return { + kind: _graphql.Kind.SELECTION_SET, + selections: fieldNames.map((fieldName) => { + const fieldDef = namedType.getFields()[fieldName]; + const fieldType = fieldDef ? fieldDef.type : null; + return { + kind: _graphql.Kind.FIELD, + name: { + kind: _graphql.Kind.NAME, + value: fieldName, + }, + selectionSet: buildSelectionSet( + fieldType, + getDefaultFieldNames + ), + }; + }), + }; + } + function withInsertions(initial, insertions) { + if (insertions.length === 0) { + return initial; + } + let edited = ""; + let prevIndex = 0; + for (const { index, string } of insertions) { + edited += initial.slice(prevIndex, index) + string; + prevIndex = index; + } + edited += initial.slice(prevIndex); + return edited; + } + function getIndentation(str, index) { + let indentStart = index; + let indentEnd = index; + while (indentStart) { + const c = str.charCodeAt(indentStart - 1); + if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { + break; + } + indentStart--; + if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { + indentEnd = indentStart; + } + } + return str.slice(indentStart, indentEnd); + } + function isFieldType(fieldType) { + if (fieldType) { + return fieldType; + } + } + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/index.js": + /*!***********************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/index.js ***! + \***********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + var _autoComplete = __webpack_require__( + /*! ./auto-complete */ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js" + ); + Object.keys(_autoComplete).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _autoComplete[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _autoComplete[key]; + }, }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: false, - container + }); + var _mergeAst = __webpack_require__( + /*! ./merge-ast */ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js" + ); + Object.keys(_mergeAst).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _mergeAst[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _mergeAst[key]; + }, }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: false, - container + }); + var _operationName = __webpack_require__( + /*! ./operation-name */ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js" + ); + Object.keys(_operationName).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _operationName[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _operationName[key]; + }, }); - } - }); - newEditor.on("keyup", (editorInstance, event) => { - const { - code, - key, - shiftKey - } = event; - const isLetter = code.startsWith("Key"); - const isNumber = !shiftKey && code.startsWith("Digit"); - if (isLetter || isNumber || key === "_" || key === '"') { - editorInstance.execCommand("autocomplete"); - } - }); - setHeaderEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialHeaders, readOnly, setHeaderEditor]); - useSynchronizeOption(headerEditor, "keyMap", keyMap); - useChangeHandler(headerEditor, onEdit, shouldPersistHeaders ? STORAGE_KEY$3 : null, "headers", useHeaderEditor); - useKeyMap(headerEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); - useKeyMap(headerEditor, ["Shift-Ctrl-P"], prettify); - useKeyMap(headerEditor, ["Shift-Ctrl-M"], merge); - return ref; -} -const STORAGE_KEY$3 = "headers"; -const invalidCharacters = Array.from({ - length: 11 -}, (_, i) => { - return String.fromCharCode(8192 + i); -}).concat(["\u2028", "\u2029", " ", " "]); -const sanitizeRegex = new RegExp("[" + invalidCharacters.join("") + "]", "g"); -function normalizeWhitespace(line) { - return line.replace(sanitizeRegex, " "); -} -function useQueryEditor({ - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onClickReference, - onCopyQuery, - onEdit, - readOnly = false -} = {}, caller) { - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: caller || useQueryEditor - }); - const { - externalFragments, - initialQuery, - queryEditor, - setOperationName, - setQueryEditor, - validationRules, - variableEditor, - updateActiveTabValues - } = useEditorContext({ - nonNull: true, - caller: caller || useQueryEditor - }); - const executionContext = useExecutionContext(); - const storage = useStorageContext(); - const explorer = useExplorerContext(); - const plugin = usePluginContext(); - const copy = useCopyQuery({ - caller: caller || useQueryEditor, - onCopyQuery - }); - const merge = useMergeQuery({ - caller: caller || useQueryEditor - }); - const prettify = usePrettifyEditors({ - caller: caller || useQueryEditor - }); - const ref = React.useRef(null); - const codeMirrorRef = React.useRef(); - const onClickReferenceRef = React.useRef(() => {}); - React.useEffect(() => { - onClickReferenceRef.current = reference => { - if (!explorer || !plugin) { - return; - } - plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); - switch (reference.kind) { - case "Type": - { - explorer.push({ - name: reference.type.name, - def: reference.type - }); - break; + }); + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js": + /*!***************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js ***! + \***************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.mergeAst = mergeAst; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function uniqueBy(array, iteratee) { + var _a; + const FilteredMap = new Map(); + const result = []; + for (const item of array) { + if (item.kind === "Field") { + const uniqueValue = iteratee(item); + const existing = FilteredMap.get(uniqueValue); + if ( + (_a = item.directives) === null || _a === void 0 + ? void 0 + : _a.length + ) { + const itemClone = Object.assign({}, item); + result.push(itemClone); + } else if ( + (existing === null || existing === void 0 + ? void 0 + : existing.selectionSet) && + item.selectionSet + ) { + existing.selectionSet.selections = [ + ...existing.selectionSet.selections, + ...item.selectionSet.selections, + ]; + } else if (!existing) { + const itemClone = Object.assign({}, item); + FilteredMap.set(uniqueValue, itemClone); + result.push(itemClone); + } + } else { + result.push(item); + } } - case "Field": - { - explorer.push({ - name: reference.field.name, - def: reference.field - }); - break; + return result; + } + function inlineRelevantFragmentSpreads( + fragmentDefinitions, + selections, + selectionSetType + ) { + var _a; + const selectionSetTypeName = selectionSetType + ? (0, _graphql.getNamedType)(selectionSetType).name + : null; + const outputSelections = []; + const seenSpreads = []; + for (let selection of selections) { + if (selection.kind === "FragmentSpread") { + const fragmentName = selection.name.value; + if (!selection.directives || selection.directives.length === 0) { + if (seenSpreads.includes(fragmentName)) { + continue; + } else { + seenSpreads.push(fragmentName); + } + } + const fragmentDefinition = + fragmentDefinitions[selection.name.value]; + if (fragmentDefinition) { + const { typeCondition, directives, selectionSet } = + fragmentDefinition; + selection = { + kind: _graphql.Kind.INLINE_FRAGMENT, + typeCondition, + directives, + selectionSet, + }; + } + } + if ( + selection.kind === _graphql.Kind.INLINE_FRAGMENT && + (!selection.directives || + ((_a = selection.directives) === null || _a === void 0 + ? void 0 + : _a.length) === 0) + ) { + const fragmentTypeName = selection.typeCondition + ? selection.typeCondition.name.value + : null; + if ( + !fragmentTypeName || + fragmentTypeName === selectionSetTypeName + ) { + outputSelections.push( + ...inlineRelevantFragmentSpreads( + fragmentDefinitions, + selection.selectionSet.selections, + selectionSetType + ) + ); + continue; + } + } + outputSelections.push(selection); } - case "Argument": - { - if (reference.field) { - explorer.push({ - name: reference.field.name, - def: reference.field - }); + return outputSelections; + } + function mergeAst(documentAST, schema) { + const typeInfo = schema ? new _graphql.TypeInfo(schema) : null; + const fragmentDefinitions = Object.create(null); + for (const definition of documentAST.definitions) { + if (definition.kind === _graphql.Kind.FRAGMENT_DEFINITION) { + fragmentDefinitions[definition.name.value] = definition; } - break; } - case "EnumValue": - { - if (reference.type) { - explorer.push({ - name: reference.type.name, - def: reference.type + const flattenVisitors = { + SelectionSet(node) { + const selectionSetType = typeInfo + ? typeInfo.getParentType() + : null; + let { selections } = node; + selections = inlineRelevantFragmentSpreads( + fragmentDefinitions, + selections, + selectionSetType + ); + return Object.assign(Object.assign({}, node), { + selections, + }); + }, + FragmentDefinition() { + return null; + }, + }; + const flattenedAST = (0, _graphql.visit)( + documentAST, + typeInfo + ? (0, _graphql.visitWithTypeInfo)(typeInfo, flattenVisitors) + : flattenVisitors + ); + const deduplicateVisitors = { + SelectionSet(node) { + let { selections } = node; + selections = uniqueBy(selections, (selection) => + selection.alias ? selection.alias.value : selection.name.value + ); + return Object.assign(Object.assign({}, node), { + selections, }); + }, + FragmentDefinition() { + return null; + }, + }; + return (0, _graphql.visit)(flattenedAST, deduplicateVisitors); + } + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js": + /*!********************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/operation-name.js ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getSelectedOperationName = getSelectedOperationName; + function getSelectedOperationName( + prevOperations, + prevSelectedOperationName, + operations + ) { + if (!operations || operations.length < 1) { + return; + } + const names = operations.map((op) => { + var _a; + return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; + }); + if ( + prevSelectedOperationName && + names.includes(prevSelectedOperationName) + ) { + return prevSelectedOperationName; + } + if (prevSelectedOperationName && prevOperations) { + const prevNames = prevOperations.map((op) => { + var _a; + return (_a = op.name) === null || _a === void 0 + ? void 0 + : _a.value; + }); + const prevIndex = prevNames.indexOf(prevSelectedOperationName); + if (prevIndex !== -1 && prevIndex < names.length) { + return names[prevIndex]; } - break; } - } - onClickReference == null ? void 0 : onClickReference(reference); - }; - }, [explorer, onClickReference, plugin]); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./comment.cjs.js */ "../../graphiql-react/dist/comment.cjs.js")).then(n => n.comment), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs.js */ "../../graphiql-react/dist/hint.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs2.js */ "../../graphiql-react/dist/lint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info.cjs.js */ "../../graphiql-react/dist/info.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./jump.cjs.js */ "../../graphiql-react/dist/jump.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs.js */ "../../graphiql-react/dist/mode.cjs.js"))]).then(CodeMirror => { - if (!isActive) { - return; - } - codeMirrorRef.current = CodeMirror; - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialQuery, - lineNumbers: true, - tabSize: 2, - foldGutter: true, - mode: "graphql", - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - lint: { - // @ts-expect-error - schema: void 0, - validationRules: null, - // linting accepts string or FragmentDefinitionNode[] - externalFragments: void 0 - }, - hintOptions: { - // @ts-expect-error - schema: void 0, - closeOnUnfocus: false, - completeSingle: false, - container, - externalFragments: void 0, - autocompleteOptions: { - // for the query editor, restrict to executable type definitions - mode: graphqlLanguageService.GraphQLDocumentMode.EXECUTABLE - } - }, - info: { - schema: void 0, - renderDescription: text => markdown.render(text), - onClick(reference) { - onClickReferenceRef.current(reference); - } - }, - jump: { - schema: void 0, - onClick(reference) { - onClickReferenceRef.current(reference); - } - }, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: { - ...commonKeys, - "Cmd-S"() {}, - "Ctrl-S"() {} - } - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: true, - container + return names[0]; + } + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/index.js": + /*!*******************************************!*\ + !*** ../../graphiql-toolkit/esm/index.js ***! + \*******************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + var _asyncHelpers = __webpack_require__( + /*! ./async-helpers */ "../../graphiql-toolkit/esm/async-helpers/index.js" + ); + Object.keys(_asyncHelpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _asyncHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _asyncHelpers[key]; + }, }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: true, - container + }); + var _createFetcher = __webpack_require__( + /*! ./create-fetcher */ "../../graphiql-toolkit/esm/create-fetcher/index.js" + ); + Object.keys(_createFetcher).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _createFetcher[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _createFetcher[key]; + }, }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: true, - container + }); + var _format = __webpack_require__( + /*! ./format */ "../../graphiql-toolkit/esm/format/index.js" + ); + Object.keys(_format).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _format[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _format[key]; + }, }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: true, - container + }); + var _graphqlHelpers = __webpack_require__( + /*! ./graphql-helpers */ "../../graphiql-toolkit/esm/graphql-helpers/index.js" + ); + Object.keys(_graphqlHelpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _graphqlHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _graphqlHelpers[key]; + }, }); - }, - "Shift-Alt-Space"() { - newEditor.showHint({ - completeSingle: true, - container + }); + var _storage = __webpack_require__( + /*! ./storage */ "../../graphiql-toolkit/esm/storage/index.js" + ); + Object.keys(_storage).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _storage[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _storage[key]; + }, }); + }); + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/storage/base.js": + /*!**************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/base.js ***! + \**************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.StorageAPI = void 0; + function isQuotaError(storage, e) { + return ( + e instanceof DOMException && + (e.code === 22 || + e.code === 1014 || + e.name === "QuotaExceededError" || + e.name === "NS_ERROR_DOM_QUOTA_REACHED") && + storage.length !== 0 + ); } - }); - newEditor.on("keyup", (editorInstance, event) => { - if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { - editorInstance.execCommand("autocomplete"); - } - }); - let showingHints = false; - newEditor.on("startCompletion", () => { - showingHints = true; - }); - newEditor.on("endCompletion", () => { - showingHints = false; - }); - newEditor.on("keydown", (editorInstance, event) => { - if (event.key === "Escape" && showingHints) { - event.stopPropagation(); - } - }); - newEditor.on("beforeChange", (editorInstance, change) => { - var _a; - if (change.origin === "paste") { - const text = change.text.map(normalizeWhitespace); - (_a = change.update) == null ? void 0 : _a.call(change, change.from, change.to, text); - } - }); - newEditor.documentAST = null; - newEditor.operationName = null; - newEditor.operations = null; - newEditor.variableToType = null; - setQueryEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialQuery, readOnly, setQueryEditor]); - useSynchronizeOption(queryEditor, "keyMap", keyMap); - React.useEffect(() => { - if (!queryEditor) { - return; - } - function getAndUpdateOperationFacts(editorInstance) { - var _editorInstance$opera, _editorInstance$opera2, _ref3, _ref4; - var _a; - const operationFacts = graphqlLanguageService.getOperationFacts(schema, editorInstance.getValue()); - const operationName = toolkit.getSelectedOperationName((_editorInstance$opera = editorInstance.operations) !== null && _editorInstance$opera !== void 0 ? _editorInstance$opera : void 0, (_editorInstance$opera2 = editorInstance.operationName) !== null && _editorInstance$opera2 !== void 0 ? _editorInstance$opera2 : void 0, operationFacts == null ? void 0 : operationFacts.operations); - editorInstance.documentAST = (_ref3 = operationFacts == null ? void 0 : operationFacts.documentAST) !== null && _ref3 !== void 0 ? _ref3 : null; - editorInstance.operationName = operationName !== null && operationName !== void 0 ? operationName : null; - editorInstance.operations = (_ref4 = operationFacts == null ? void 0 : operationFacts.operations) !== null && _ref4 !== void 0 ? _ref4 : null; - if (variableEditor) { - variableEditor.state.lint.linterOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; - variableEditor.options.lint.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; - variableEditor.options.hintOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; - (_a = codeMirrorRef.current) == null ? void 0 : _a.signal(variableEditor, "change", variableEditor); - } - return operationFacts ? { - ...operationFacts, - operationName - } : null; - } - const handleChange = debounce(100, editorInstance => { - var _ref5; - const query = editorInstance.getValue(); - storage == null ? void 0 : storage.set(STORAGE_KEY_QUERY, query); - const currentOperationName = editorInstance.operationName; - const operationFacts = getAndUpdateOperationFacts(editorInstance); - if ((operationFacts == null ? void 0 : operationFacts.operationName) !== void 0) { - storage == null ? void 0 : storage.set(STORAGE_KEY_OPERATION_NAME, operationFacts.operationName); - } - onEdit == null ? void 0 : onEdit(query, operationFacts == null ? void 0 : operationFacts.documentAST); - if ((operationFacts == null ? void 0 : operationFacts.operationName) && currentOperationName !== operationFacts.operationName) { - setOperationName(operationFacts.operationName); - } - updateActiveTabValues({ - query, - operationName: (_ref5 = operationFacts == null ? void 0 : operationFacts.operationName) !== null && _ref5 !== void 0 ? _ref5 : null - }); - }); - getAndUpdateOperationFacts(queryEditor); - queryEditor.on("change", handleChange); - return () => queryEditor.off("change", handleChange); - }, [onEdit, queryEditor, schema, setOperationName, storage, variableEditor, updateActiveTabValues]); - useSynchronizeSchema(queryEditor, schema !== null && schema !== void 0 ? schema : null, codeMirrorRef); - useSynchronizeValidationRules(queryEditor, validationRules !== null && validationRules !== void 0 ? validationRules : null, codeMirrorRef); - useSynchronizeExternalFragments(queryEditor, externalFragments, codeMirrorRef); - useCompletion(queryEditor, onClickReference || null, useQueryEditor); - const run = executionContext == null ? void 0 : executionContext.run; - const runAtCursor = React.useCallback(() => { - var _a; - if (!run || !queryEditor || !queryEditor.operations || !queryEditor.hasFocus()) { - run == null ? void 0 : run(); - return; - } - const cursorIndex = queryEditor.indexFromPos(queryEditor.getCursor()); - let operationName; - for (const operation of queryEditor.operations) { - if (operation.loc && operation.loc.start <= cursorIndex && operation.loc.end >= cursorIndex) { - operationName = (_a = operation.name) == null ? void 0 : _a.value; - } - } - if (operationName && operationName !== queryEditor.operationName) { - setOperationName(operationName); - } - run(); - }, [queryEditor, run, setOperationName]); - useKeyMap(queryEditor, ["Cmd-Enter", "Ctrl-Enter"], runAtCursor); - useKeyMap(queryEditor, ["Shift-Ctrl-C"], copy); - useKeyMap(queryEditor, ["Shift-Ctrl-P", - // Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to prettify - "Shift-Ctrl-F"], prettify); - useKeyMap(queryEditor, ["Shift-Ctrl-M"], merge); - return ref; -} -function useSynchronizeSchema(editor, schema, codeMirrorRef) { - React.useEffect(() => { - if (!editor) { - return; - } - const didChange = editor.options.lint.schema !== schema; - editor.state.lint.linterOptions.schema = schema; - editor.options.lint.schema = schema; - editor.options.hintOptions.schema = schema; - editor.options.info.schema = schema; - editor.options.jump.schema = schema; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, schema, codeMirrorRef]); -} -function useSynchronizeValidationRules(editor, validationRules, codeMirrorRef) { - React.useEffect(() => { - if (!editor) { - return; - } - const didChange = editor.options.lint.validationRules !== validationRules; - editor.state.lint.linterOptions.validationRules = validationRules; - editor.options.lint.validationRules = validationRules; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, validationRules, codeMirrorRef]); -} -function useSynchronizeExternalFragments(editor, externalFragments, codeMirrorRef) { - const externalFragmentList = React.useMemo(() => [...externalFragments.values()], [externalFragments]); - React.useEffect(() => { - if (!editor) { - return; - } - const didChange = editor.options.lint.externalFragments !== externalFragmentList; - editor.state.lint.linterOptions.externalFragments = externalFragmentList; - editor.options.lint.externalFragments = externalFragmentList; - editor.options.hintOptions.externalFragments = externalFragmentList; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, externalFragmentList, codeMirrorRef]); -} -const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/; -const STORAGE_KEY_QUERY = "query"; -const STORAGE_KEY_OPERATION_NAME = "operationName"; -function getDefaultTabState({ - defaultQuery, - defaultHeaders, - headers, - defaultTabs, - query, - variables, - storage, - shouldPersistHeaders -}) { - const storedState = storage == null ? void 0 : storage.get(STORAGE_KEY$2); - try { - if (!storedState) { - throw new Error("Storage for tabs is empty"); - } - const parsed = JSON.parse(storedState); - const headersForHash = shouldPersistHeaders ? headers : void 0; - if (isTabsState(parsed)) { - const expectedHash = hashFromTabContents({ - query, - variables, - headers: headersForHash - }); - let matchingTabIndex = -1; - for (let index = 0; index < parsed.tabs.length; index++) { - const tab = parsed.tabs[index]; - tab.hash = hashFromTabContents({ - query: tab.query, - variables: tab.variables, - headers: tab.headers - }); - if (tab.hash === expectedHash) { - matchingTabIndex = index; + class StorageAPI { + constructor(storage) { + if (storage) { + this.storage = storage; + } else if (storage === null) { + this.storage = null; + } else if (typeof window === "undefined") { + this.storage = null; + } else { + this.storage = { + getItem: localStorage.getItem.bind(localStorage), + setItem: localStorage.setItem.bind(localStorage), + removeItem: localStorage.removeItem.bind(localStorage), + get length() { + let keys = 0; + for (const key in localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + keys += 1; + } + } + return keys; + }, + clear() { + for (const key in localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + localStorage.removeItem(key); + } + } + }, + }; + } + } + get(name) { + if (!this.storage) { + return null; + } + const key = `${STORAGE_NAMESPACE}:${name}`; + const value = this.storage.getItem(key); + if (value === "null" || value === "undefined") { + this.storage.removeItem(key); + return null; + } + return value || null; + } + set(name, value) { + let quotaError = false; + let error = null; + if (this.storage) { + const key = `${STORAGE_NAMESPACE}:${name}`; + if (value) { + try { + this.storage.setItem(key, value); + } catch (e) { + error = e instanceof Error ? e : new Error(`${e}`); + quotaError = isQuotaError(this.storage, e); + } + } else { + this.storage.removeItem(key); + } + } + return { + isQuotaError: quotaError, + error, + }; + } + clear() { + if (this.storage) { + this.storage.clear(); + } + } } - } - if (matchingTabIndex >= 0) { - parsed.activeTabIndex = matchingTabIndex; - } else { - const operationName = query ? fuzzyExtractOperationName(query) : null; - parsed.tabs.push({ - id: guid(), - hash: expectedHash, - title: operationName || DEFAULT_TITLE, - query, - variables, - headers, - operationName, - response: null + exports.StorageAPI = StorageAPI; + const STORAGE_NAMESPACE = "graphiql"; + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/storage/custom.js": + /*!****************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/custom.js ***! + \****************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.createLocalStorage = createLocalStorage; + function createLocalStorage({ namespace }) { + const storageKeyPrefix = `${namespace}:`; + const getStorageKey = (key) => `${storageKeyPrefix}${key}`; + const storage = { + setItem: (key, value) => + localStorage.setItem(getStorageKey(key), value), + getItem: (key) => localStorage.getItem(getStorageKey(key)), + removeItem: (key) => localStorage.removeItem(getStorageKey(key)), + get length() { + let keys = 0; + for (const key in localStorage) { + if (key.indexOf(storageKeyPrefix) === 0) { + keys += 1; + } + } + return keys; + }, + clear() { + for (const key in localStorage) { + if (key.indexOf(storageKeyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }, + }; + return storage; + } + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/storage/history.js": + /*!*****************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/history.js ***! + \*****************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.HistoryStore = void 0; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _query = __webpack_require__( + /*! ./query */ "../../graphiql-toolkit/esm/storage/query.js" + ); + const MAX_QUERY_SIZE = 100000; + class HistoryStore { + constructor(storage, maxHistoryLength) { + this.storage = storage; + this.maxHistoryLength = maxHistoryLength; + this.updateHistory = ({ + query, + variables, + headers, + operationName, + }) => { + if ( + !this.shouldSaveQuery( + query, + variables, + headers, + this.history.fetchRecent() + ) + ) { + return; + } + this.history.push({ + query, + variables, + headers, + operationName, + }); + const historyQueries = this.history.items; + const favoriteQueries = this.favorite.items; + this.queries = historyQueries.concat(favoriteQueries); + }; + this.deleteHistory = ( + { query, variables, headers, operationName, favorite }, + clearFavorites = false + ) => { + function deleteFromStore(store) { + const found = store.items.find( + (x) => + x.query === query && + x.variables === variables && + x.headers === headers && + x.operationName === operationName + ); + if (found) { + store.delete(found); + } + } + if (favorite || clearFavorites) { + deleteFromStore(this.favorite); + } + if (!favorite || clearFavorites) { + deleteFromStore(this.history); + } + this.queries = [...this.history.items, ...this.favorite.items]; + }; + this.history = new _query.QueryStore( + "queries", + this.storage, + this.maxHistoryLength + ); + this.favorite = new _query.QueryStore( + "favorites", + this.storage, + null + ); + this.queries = [ + ...this.history.fetchAll(), + ...this.favorite.fetchAll(), + ]; + } + shouldSaveQuery(query, variables, headers, lastQuerySaved) { + if (!query) { + return false; + } + try { + (0, _graphql.parse)(query); + } catch (_a) { + return false; + } + if (query.length > MAX_QUERY_SIZE) { + return false; + } + if (!lastQuerySaved) { + return true; + } + if ( + JSON.stringify(query) === JSON.stringify(lastQuerySaved.query) + ) { + if ( + JSON.stringify(variables) === + JSON.stringify(lastQuerySaved.variables) + ) { + if ( + JSON.stringify(headers) === + JSON.stringify(lastQuerySaved.headers) + ) { + return false; + } + if (headers && !lastQuerySaved.headers) { + return false; + } + } + if (variables && !lastQuerySaved.variables) { + return false; + } + } + return true; + } + toggleFavorite({ + query, + variables, + headers, + operationName, + label, + favorite, + }) { + const item = { + query, + variables, + headers, + operationName, + label, + }; + if (favorite) { + item.favorite = false; + this.favorite.delete(item); + this.history.push(item); + } else { + item.favorite = true; + this.favorite.push(item); + this.history.delete(item); + } + this.queries = [...this.history.items, ...this.favorite.items]; + } + editLabel( + { query, variables, headers, operationName, label, favorite }, + index + ) { + const item = { + query, + variables, + headers, + operationName, + label, + }; + if (favorite) { + this.favorite.edit( + Object.assign(Object.assign({}, item), { + favorite, + }), + index + ); + } else { + this.history.edit(item, index); + } + this.queries = [...this.history.items, ...this.favorite.items]; + } + } + exports.HistoryStore = HistoryStore; + + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/storage/index.js": + /*!***************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/index.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, }); - parsed.activeTabIndex = parsed.tabs.length - 1; - } - return parsed; - } - throw new Error("Storage for tabs is invalid"); - } catch { - return { - activeTabIndex: 0, - tabs: (defaultTabs || [{ - query: query !== null && query !== void 0 ? query : defaultQuery, - variables, - headers: headers !== null && headers !== void 0 ? headers : defaultHeaders - }]).map(createTab) - }; - } -} -function isTabsState(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj) && hasNumberKey(obj, "activeTabIndex") && "tabs" in obj && Array.isArray(obj.tabs) && obj.tabs.every(isTabState); -} -function isTabState(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj) && hasStringKey(obj, "id") && hasStringKey(obj, "title") && hasStringOrNullKey(obj, "query") && hasStringOrNullKey(obj, "variables") && hasStringOrNullKey(obj, "headers") && hasStringOrNullKey(obj, "operationName") && hasStringOrNullKey(obj, "response"); -} -function hasNumberKey(obj, key) { - return key in obj && typeof obj[key] === "number"; -} -function hasStringKey(obj, key) { - return key in obj && typeof obj[key] === "string"; -} -function hasStringOrNullKey(obj, key) { - return key in obj && (typeof obj[key] === "string" || obj[key] === null); -} -function useSynchronizeActiveTabValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor -}) { - return React.useCallback(state => { - var _ref6, _ref7, _ref8, _ref9, _ref10; - const query = (_ref6 = queryEditor == null ? void 0 : queryEditor.getValue()) !== null && _ref6 !== void 0 ? _ref6 : null; - const variables = (_ref7 = variableEditor == null ? void 0 : variableEditor.getValue()) !== null && _ref7 !== void 0 ? _ref7 : null; - const headers = (_ref8 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref8 !== void 0 ? _ref8 : null; - const operationName = (_ref9 = queryEditor == null ? void 0 : queryEditor.operationName) !== null && _ref9 !== void 0 ? _ref9 : null; - const response = (_ref10 = responseEditor == null ? void 0 : responseEditor.getValue()) !== null && _ref10 !== void 0 ? _ref10 : null; - return setPropertiesInActiveTab(state, { - query, - variables, - headers, - response, - operationName - }); - }, [queryEditor, variableEditor, headerEditor, responseEditor]); -} -function serializeTabState(tabState, shouldPersistHeaders = false) { - return JSON.stringify(tabState, (key, value) => key === "hash" || key === "response" || !shouldPersistHeaders && key === "headers" ? null : value); -} -function useStoreTabs({ - storage, - shouldPersistHeaders -}) { - const store = React.useMemo(() => debounce(500, value => { - storage == null ? void 0 : storage.set(STORAGE_KEY$2, value); - }), [storage]); - return React.useCallback(currentState => { - store(serializeTabState(currentState, shouldPersistHeaders)); - }, [shouldPersistHeaders, store]); -} -function useSetEditorValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor -}) { - return React.useCallback(({ - query, - variables, - headers, - response - }) => { - queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); - variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); - headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); - responseEditor == null ? void 0 : responseEditor.setValue(response !== null && response !== void 0 ? response : ""); - }, [headerEditor, queryEditor, responseEditor, variableEditor]); -} -function createTab({ - query = null, - variables = null, - headers = null -} = {}) { - return { - id: guid(), - hash: hashFromTabContents({ - query, - variables, - headers - }), - title: query && fuzzyExtractOperationName(query) || DEFAULT_TITLE, - query, - variables, - headers, - operationName: null, - response: null - }; -} -function setPropertiesInActiveTab(state, partialTab) { - return { - ...state, - tabs: state.tabs.map((tab, index) => { - if (index !== state.activeTabIndex) { - return tab; - } - const newTab = { - ...tab, - ...partialTab - }; - return { - ...newTab, - hash: hashFromTabContents(newTab), - title: newTab.operationName || (newTab.query ? fuzzyExtractOperationName(newTab.query) : void 0) || DEFAULT_TITLE - }; - }) - }; -} -function guid() { - const s4 = () => { - return Math.floor((1 + Math.random()) * 65536).toString(16).slice(1); - }; - return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; -} -function hashFromTabContents(args) { - var _args$query, _args$variables, _args$headers; - return [(_args$query = args.query) !== null && _args$query !== void 0 ? _args$query : "", (_args$variables = args.variables) !== null && _args$variables !== void 0 ? _args$variables : "", (_args$headers = args.headers) !== null && _args$headers !== void 0 ? _args$headers : ""].join("|"); -} -function fuzzyExtractOperationName(str) { - var _ref11; - const regex = /^(?!#).*(query|subscription|mutation)\s+([a-zA-Z0-9_]+)/m; - const match = regex.exec(str); - return (_ref11 = match == null ? void 0 : match[2]) !== null && _ref11 !== void 0 ? _ref11 : null; -} -function clearHeadersFromTabs(storage) { - const persistedTabs = storage == null ? void 0 : storage.get(STORAGE_KEY$2); - if (persistedTabs) { - const parsedTabs = JSON.parse(persistedTabs); - storage == null ? void 0 : storage.set(STORAGE_KEY$2, JSON.stringify(parsedTabs, (key, value) => key === "headers" ? null : value)); - } -} -const DEFAULT_TITLE = ""; -const STORAGE_KEY$2 = "tabState"; -function useVariableEditor({ - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onClickReference, - onEdit, - readOnly = false -} = {}, caller) { - const { - initialVariables, - variableEditor, - setVariableEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useVariableEditor - }); - const executionContext = useExecutionContext(); - const merge = useMergeQuery({ - caller: caller || useVariableEditor - }); - const prettify = usePrettifyEditors({ - caller: caller || useVariableEditor - }); - const ref = React.useRef(null); - const codeMirrorRef = React.useRef(); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs2.js */ "../../graphiql-react/dist/hint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs3.js */ "../../graphiql-react/dist/lint.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs2.js */ "../../graphiql-react/dist/mode.cjs2.js"))]).then(CodeMirror => { - if (!isActive) { - return; - } - codeMirrorRef.current = CodeMirror; - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialVariables, - lineNumbers: true, - tabSize: 2, - mode: "graphql-variables", - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - foldGutter: true, - lint: { - // @ts-expect-error - variableToType: void 0 - }, - hintOptions: { - closeOnUnfocus: false, - completeSingle: false, - container, - // @ts-expect-error - variableToType: void 0 - }, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: commonKeys - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: false, - container + var _base = __webpack_require__( + /*! ./base */ "../../graphiql-toolkit/esm/storage/base.js" + ); + Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _base[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _base[key]; + }, }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: false, - container + }); + var _history = __webpack_require__( + /*! ./history */ "../../graphiql-toolkit/esm/storage/history.js" + ); + Object.keys(_history).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _history[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _history[key]; + }, }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: false, - container + }); + var _query = __webpack_require__( + /*! ./query */ "../../graphiql-toolkit/esm/storage/query.js" + ); + Object.keys(_query).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _query[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _query[key]; + }, }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: false, - container + }); + var _custom = __webpack_require__( + /*! ./custom */ "../../graphiql-toolkit/esm/storage/custom.js" + ); + Object.keys(_custom).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _custom[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _custom[key]; + }, }); - } - }); - newEditor.on("keyup", (editorInstance, event) => { - const { - code, - key, - shiftKey - } = event; - const isLetter = code.startsWith("Key"); - const isNumber = !shiftKey && code.startsWith("Digit"); - if (isLetter || isNumber || key === "_" || key === '"') { - editorInstance.execCommand("autocomplete"); - } - }); - setVariableEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialVariables, readOnly, setVariableEditor]); - useSynchronizeOption(variableEditor, "keyMap", keyMap); - useChangeHandler(variableEditor, onEdit, STORAGE_KEY$1, "variables", useVariableEditor); - useCompletion(variableEditor, onClickReference || null, useVariableEditor); - useKeyMap(variableEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); - useKeyMap(variableEditor, ["Shift-Ctrl-P"], prettify); - useKeyMap(variableEditor, ["Shift-Ctrl-M"], merge); - return ref; -} -const STORAGE_KEY$1 = "variables"; -const EditorContext = createNullableContext("EditorContext"); -function EditorContextProvider(props) { - const storage = useStorageContext(); - const [headerEditor, setHeaderEditor] = React.useState(null); - const [queryEditor, setQueryEditor] = React.useState(null); - const [responseEditor, setResponseEditor] = React.useState(null); - const [variableEditor, setVariableEditor] = React.useState(null); - const [shouldPersistHeaders, setShouldPersistHeadersInternal] = React.useState(() => { - const isStored = (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) !== null; - return props.shouldPersistHeaders !== false && isStored ? (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) === "true" : Boolean(props.shouldPersistHeaders); - }); - useSynchronizeValue(headerEditor, props.headers); - useSynchronizeValue(queryEditor, props.query); - useSynchronizeValue(responseEditor, props.response); - useSynchronizeValue(variableEditor, props.variables); - const storeTabs = useStoreTabs({ - storage, - shouldPersistHeaders - }); - const [initialState] = React.useState(() => { - var _ref12, _props$query, _ref13, _props$variables, _ref14, _props$headers, _props$response, _ref15, _ref16; - const query = (_ref12 = (_props$query = props.query) !== null && _props$query !== void 0 ? _props$query : storage == null ? void 0 : storage.get(STORAGE_KEY_QUERY)) !== null && _ref12 !== void 0 ? _ref12 : null; - const variables = (_ref13 = (_props$variables = props.variables) !== null && _props$variables !== void 0 ? _props$variables : storage == null ? void 0 : storage.get(STORAGE_KEY$1)) !== null && _ref13 !== void 0 ? _ref13 : null; - const headers = (_ref14 = (_props$headers = props.headers) !== null && _props$headers !== void 0 ? _props$headers : storage == null ? void 0 : storage.get(STORAGE_KEY$3)) !== null && _ref14 !== void 0 ? _ref14 : null; - const response = (_props$response = props.response) !== null && _props$response !== void 0 ? _props$response : ""; - const tabState2 = getDefaultTabState({ - query, - variables, - headers, - defaultTabs: props.defaultTabs, - defaultQuery: props.defaultQuery || DEFAULT_QUERY, - defaultHeaders: props.defaultHeaders, - storage, - shouldPersistHeaders - }); - storeTabs(tabState2); - return { - query: (_ref15 = query !== null && query !== void 0 ? query : tabState2.activeTabIndex === 0 ? tabState2.tabs[0].query : null) !== null && _ref15 !== void 0 ? _ref15 : "", - variables: variables !== null && variables !== void 0 ? variables : "", - headers: (_ref16 = headers !== null && headers !== void 0 ? headers : props.defaultHeaders) !== null && _ref16 !== void 0 ? _ref16 : "", - response, - tabState: tabState2 - }; - }); - const [tabState, setTabState] = React.useState(initialState.tabState); - const setShouldPersistHeaders = React.useCallback(persist => { - if (persist) { - var _ref17; - storage == null ? void 0 : storage.set(STORAGE_KEY$3, (_ref17 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref17 !== void 0 ? _ref17 : ""); - const serializedTabs = serializeTabState(tabState, true); - storage == null ? void 0 : storage.set(STORAGE_KEY$2, serializedTabs); - } else { - storage == null ? void 0 : storage.set(STORAGE_KEY$3, ""); - clearHeadersFromTabs(storage); - } - setShouldPersistHeadersInternal(persist); - storage == null ? void 0 : storage.set(PERSIST_HEADERS_STORAGE_KEY, persist.toString()); - }, [storage, tabState, headerEditor]); - const lastShouldPersistHeadersProp = React.useRef(); - React.useEffect(() => { - const propValue = Boolean(props.shouldPersistHeaders); - if ((lastShouldPersistHeadersProp == null ? void 0 : lastShouldPersistHeadersProp.current) !== propValue) { - setShouldPersistHeaders(propValue); - lastShouldPersistHeadersProp.current = propValue; - } - }, [props.shouldPersistHeaders, setShouldPersistHeaders]); - const synchronizeActiveTabValues = useSynchronizeActiveTabValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor - }); - const setEditorValues = useSetEditorValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor - }); - const { - onTabChange, - defaultHeaders, - children - } = props; - const addTab = React.useCallback(() => { - setTabState(current => { - const updatedValues = synchronizeActiveTabValues(current); - const updated = { - tabs: [...updatedValues.tabs, createTab({ - headers: defaultHeaders - })], - activeTabIndex: updatedValues.tabs.length - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [defaultHeaders, onTabChange, setEditorValues, storeTabs, synchronizeActiveTabValues]); - const changeTab = React.useCallback(index => { - setTabState(current => { - const updated = { - ...current, - activeTabIndex: index - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, setEditorValues, storeTabs]); - const moveTab = React.useCallback(newOrder => { - setTabState(current => { - const activeTab = current.tabs[current.activeTabIndex]; - const updated = { - tabs: newOrder, - activeTabIndex: newOrder.indexOf(activeTab) - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, setEditorValues, storeTabs]); - const closeTab = React.useCallback(index => { - setTabState(current => { - const updated = { - tabs: current.tabs.filter((_tab, i) => index !== i), - activeTabIndex: Math.max(current.activeTabIndex - 1, 0) - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, setEditorValues, storeTabs]); - const updateActiveTabValues = React.useCallback(partialTab => { - setTabState(current => { - const updated = setPropertiesInActiveTab(current, partialTab); - storeTabs(updated); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, storeTabs]); - const { - onEditOperationName - } = props; - const setOperationName = React.useCallback(operationName => { - if (!queryEditor) { - return; - } - queryEditor.operationName = operationName; - updateActiveTabValues({ - operationName - }); - onEditOperationName == null ? void 0 : onEditOperationName(operationName); - }, [onEditOperationName, queryEditor, updateActiveTabValues]); - const externalFragments = React.useMemo(() => { - const map = /* @__PURE__ */new Map(); - if (Array.isArray(props.externalFragments)) { - for (const fragment of props.externalFragments) { - map.set(fragment.name.value, fragment); - } - } else if (typeof props.externalFragments === "string") { - graphql.visit(graphql.parse(props.externalFragments, {}), { - FragmentDefinition(fragment) { - map.set(fragment.name.value, fragment); - } - }); - } else if (props.externalFragments) { - throw new Error("The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects."); - } - return map; - }, [props.externalFragments]); - const validationRules = React.useMemo(() => props.validationRules || [], [props.validationRules]); - const value = React.useMemo(() => ({ - ...tabState, - addTab, - changeTab, - moveTab, - closeTab, - updateActiveTabValues, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - setHeaderEditor, - setQueryEditor, - setResponseEditor, - setVariableEditor, - setOperationName, - initialQuery: initialState.query, - initialVariables: initialState.variables, - initialHeaders: initialState.headers, - initialResponse: initialState.response, - externalFragments, - validationRules, - shouldPersistHeaders, - setShouldPersistHeaders - }), [tabState, addTab, changeTab, moveTab, closeTab, updateActiveTabValues, headerEditor, queryEditor, responseEditor, variableEditor, setOperationName, initialState, externalFragments, validationRules, shouldPersistHeaders, setShouldPersistHeaders]); - return /* @__PURE__ */jsxRuntime.jsx(EditorContext.Provider, { - value, - children - }); -} -const useEditorContext = createContextHook(EditorContext); -const PERSIST_HEADERS_STORAGE_KEY = "shouldPersistHeaders"; -const DEFAULT_QUERY = `# Welcome to GraphiQL -# -# GraphiQL is an in-browser tool for writing, validating, and -# testing GraphQL queries. -# -# Type queries into this side of the screen, and you will see intelligent -# typeaheads aware of the current GraphQL type schema and live syntax and -# validation errors highlighted within the text. -# -# GraphQL queries typically start with a "{" character. Lines that start -# with a # are ignored. -# -# An example GraphQL query might look like: -# -# { -# field(arg: "value") { -# subField -# } -# } -# -# Keyboard shortcuts: -# -# Prettify query: Shift-Ctrl-P (or press the prettify button) -# -# Merge fragments: Shift-Ctrl-M (or press the merge button) -# -# Run Query: Ctrl-Enter (or press the play button) -# -# Auto Complete: Ctrl-Space (or just start typing) -# + }); -`; -function HeaderEditor({ - isHidden, - ...hookArgs -}) { - const { - headerEditor - } = useEditorContext({ - nonNull: true, - caller: HeaderEditor - }); - const ref = useHeaderEditor(hookArgs, HeaderEditor); - React.useEffect(() => { - if (!isHidden) { - headerEditor == null ? void 0 : headerEditor.refresh(); - } - }, [headerEditor, isHidden]); - return /* @__PURE__ */jsxRuntime.jsx("div", { - className: clsx.clsx("graphiql-editor", isHidden && "hidden"), - ref - }); -} -function ImagePreview(props) { - var _a; - const [dimensions, setDimensions] = React.useState({ - width: null, - height: null - }); - const [mime, setMime] = React.useState(null); - const ref = React.useRef(null); - const src = (_a = tokenToURL(props.token)) == null ? void 0 : _a.href; - React.useEffect(() => { - if (!ref.current) { - return; - } - if (!src) { - setDimensions({ - width: null, - height: null - }); - setMime(null); - return; - } - fetch(src, { - method: "HEAD" - }).then(response => { - setMime(response.headers.get("Content-Type")); - }).catch(() => { - setMime(null); - }); - }, [src]); - const dims = dimensions.width !== null && dimensions.height !== null ? /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [dimensions.width, "x", dimensions.height, mime === null ? null : " " + mime] - }) : null; - return /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("img", { - onLoad: () => { - var _ref18, _ref19; - var _a2, _b; - setDimensions({ - width: (_ref18 = (_a2 = ref.current) == null ? void 0 : _a2.naturalWidth) !== null && _ref18 !== void 0 ? _ref18 : null, - height: (_ref19 = (_b = ref.current) == null ? void 0 : _b.naturalHeight) !== null && _ref19 !== void 0 ? _ref19 : null + /***/ + }, + + /***/ "../../graphiql-toolkit/esm/storage/query.js": + /*!***************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/query.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, }); + exports.QueryStore = void 0; + class QueryStore { + constructor(key, storage, maxSize = null) { + this.key = key; + this.storage = storage; + this.maxSize = maxSize; + this.items = this.fetchAll(); + } + get length() { + return this.items.length; + } + contains(item) { + return this.items.some( + (x) => + x.query === item.query && + x.variables === item.variables && + x.headers === item.headers && + x.operationName === item.operationName + ); + } + edit(item, index) { + if (typeof index === "number" && this.items[index]) { + const found = this.items[index]; + if ( + found.query === item.query && + found.variables === item.variables && + found.headers === item.headers && + found.operationName === item.operationName + ) { + this.items.splice(index, 1, item); + this.save(); + return; + } + } + const itemIndex = this.items.findIndex( + (x) => + x.query === item.query && + x.variables === item.variables && + x.headers === item.headers && + x.operationName === item.operationName + ); + if (itemIndex !== -1) { + this.items.splice(itemIndex, 1, item); + this.save(); + } + } + delete(item) { + const itemIndex = this.items.findIndex( + (x) => + x.query === item.query && + x.variables === item.variables && + x.headers === item.headers && + x.operationName === item.operationName + ); + if (itemIndex !== -1) { + this.items.splice(itemIndex, 1); + this.save(); + } + } + fetchRecent() { + return this.items.at(-1); + } + fetchAll() { + const raw = this.storage.get(this.key); + if (raw) { + return JSON.parse(raw)[this.key]; + } + return []; + } + push(item) { + const items = [...this.items, item]; + if (this.maxSize && items.length > this.maxSize) { + items.shift(); + } + for (let attempts = 0; attempts < 5; attempts++) { + const response = this.storage.set( + this.key, + JSON.stringify({ + [this.key]: items, + }) + ); + if ( + !(response === null || response === void 0 + ? void 0 + : response.error) + ) { + this.items = items; + } else if (response.isQuotaError && this.maxSize) { + items.shift(); + } else { + return; + } + } + } + save() { + this.storage.set( + this.key, + JSON.stringify({ + [this.key]: this.items, + }) + ); + } + } + exports.QueryStore = QueryStore; + + /***/ }, - ref, - src - }), dims] - }); -} -ImagePreview.shouldRender = function shouldRender(token) { - const url = tokenToURL(token); - return url ? isImageURL(url) : false; -}; -function tokenToURL(token) { - if (token.type !== "string") { - return; - } - const value = token.string.slice(1).slice(0, -1).trim(); - try { - const { - location - } = window; - return new URL(value, location.protocol + "//" + location.host); - } catch { - return; - } -} -function isImageURL(url) { - return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname); -} -function QueryEditor(props) { - const ref = useQueryEditor(props, QueryEditor); - return /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-editor", - ref - }); -} -function useResponseEditor({ - responseTooltip, - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP -} = {}, caller) { - const { - fetchError, - validationErrors - } = useSchemaContext({ - nonNull: true, - caller: caller || useResponseEditor - }); - const { - initialResponse, - responseEditor, - setResponseEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useResponseEditor - }); - const ref = React.useRef(null); - const responseTooltipRef = React.useRef(responseTooltip); - React.useEffect(() => { - responseTooltipRef.current = responseTooltip; - }, [responseTooltip]); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), - // @ts-expect-error - Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs3.js */ "../../graphiql-react/dist/mode.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"))], { - useCommonAddons: false - }).then(CodeMirror => { - if (!isActive) { - return; - } - const tooltipDiv = document.createElement("div"); - CodeMirror.registerHelper("info", "graphql-results", (token, _options, _cm, pos) => { - const infoElements = []; - const ResponseTooltipComponent = responseTooltipRef.current; - if (ResponseTooltipComponent) { - infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ResponseTooltipComponent, { - pos, - token - })); + + /***/ "../node_modules/linkify-it/build/index.cjs.js": + /*!*****************************************************!*\ + !*** ../node_modules/linkify-it/build/index.cjs.js ***! + \*****************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var uc_micro = __webpack_require__( + /*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js" + ); + function reFactory(opts) { + const re = {}; + opts = opts || {}; + re.src_Any = uc_micro.Any.source; + re.src_Cc = uc_micro.Cc.source; + re.src_Z = uc_micro.Z.source; + re.src_P = uc_micro.P.source; + + // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) + re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join("|"); + + // \p{\Z\Cc} (white spaces + control) + re.src_ZCc = [re.src_Z, re.src_Cc].join("|"); + + // Experimental. List of chars, completely prohibited in links + // because can separate it from other part of text + const text_separators = "[><\uff5c]"; + + // All possible word characters (everything without punctuation, spaces & controls) + // Defined via punctuation & spaces to save space + // Should be something like \p{\L\N\S\M} (\w but without `_`) + re.src_pseudo_letter = + "(?:(?!" + + text_separators + + "|" + + re.src_ZPCc + + ")" + + re.src_Any + + ")"; + // The same as abothe but without [0-9] + // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; + + re.src_ip4 = + "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; + + // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. + re.src_auth = "(?:(?:(?!" + re.src_ZCc + "|[@/\\[\\]()]).)+@)?"; + re.src_port = + "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?"; + re.src_host_terminator = + "(?=$|" + + text_separators + + "|" + + re.src_ZPCc + + ")" + + "(?!" + + (opts["---"] ? "-(?!--)|" : "-|") + + "_|:\\d|\\.-|\\.(?!$|" + + re.src_ZPCc + + "))"; + re.src_path = + "(?:" + + "[/?#]" + + "(?:" + + "(?!" + + re.src_ZCc + + "|" + + text_separators + + "|[()[\\]{}.,\"'?!\\-;]).|" + + "\\[(?:(?!" + + re.src_ZCc + + "|\\]).)*\\]|" + + "\\((?:(?!" + + re.src_ZCc + + "|[)]).)*\\)|" + + "\\{(?:(?!" + + re.src_ZCc + + "|[}]).)*\\}|" + + '\\"(?:(?!' + + re.src_ZCc + + '|["]).)+\\"|' + + "\\'(?:(?!" + + re.src_ZCc + + "|[']).)+\\'|" + + // allow `I'm_king` if no pair found + "\\'(?=" + + re.src_pseudo_letter + + "|[-])|" + + // google has many dots in "google search" links (#66, #81). + // github has ... in commit range links, + // Restrict to + // - english + // - percent-encoded + // - parts of file path + // - params separator + // until more examples found. + "\\.{2,}[a-zA-Z0-9%/&]|" + + "\\.(?!" + + re.src_ZCc + + "|[.]|$)|" + + (opts["---"] + ? "\\-(?!--(?:[^-]|$))(?:-*)|" // `---` => long dash, terminate + : "\\-+|") + + // allow `,,,` in paths + ",(?!" + + re.src_ZCc + + "|$)|" + + // allow `;` if not followed by space-like char + ";(?!" + + re.src_ZCc + + "|$)|" + + // allow `!!!` in paths, but not at the end + "\\!+(?!" + + re.src_ZCc + + "|[!]|$)|" + + "\\?(?!" + + re.src_ZCc + + "|[?]|$)" + + ")+" + + "|\\/" + + ")?"; + + // Allow anything in markdown spec, forbid quote (") at the first position + // because emails enclosed in quotes are far more common + re.src_email_name = + '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; + re.src_xn = "xn--[a-z0-9\\-]{1,59}"; + + // More to read about domain names + // http://serverfault.com/questions/638260/ + + re.src_domain_root = + // Allow letters & digits (http://test1) + "(?:" + re.src_xn + "|" + re.src_pseudo_letter + "{1,63}" + ")"; + re.src_domain = + "(?:" + + re.src_xn + + "|" + + "(?:" + + re.src_pseudo_letter + + ")" + + "|" + + "(?:" + + re.src_pseudo_letter + + "(?:-|" + + re.src_pseudo_letter + + "){0,61}" + + re.src_pseudo_letter + + ")" + + ")"; + re.src_host = + "(?:" + + // Don't need IP check, because digits are already allowed in normal domain names + // src_ip4 + + // '|' + + "(?:(?:(?:" + + re.src_domain + + ")\\.)*" + + re.src_domain /* _root */ + + ")" + + ")"; + re.tpl_host_fuzzy = + "(?:" + + re.src_ip4 + + "|" + + "(?:(?:(?:" + + re.src_domain + + ")\\.)+(?:%TLDS%))" + + ")"; + re.tpl_host_no_ip_fuzzy = + "(?:(?:(?:" + re.src_domain + ")\\.)+(?:%TLDS%))"; + re.src_host_strict = re.src_host + re.src_host_terminator; + re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; + re.src_host_port_strict = + re.src_host + re.src_port + re.src_host_terminator; + re.tpl_host_port_fuzzy_strict = + re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; + re.tpl_host_port_no_ip_fuzzy_strict = + re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; + + // + // Main rules + // + + // Rude test fuzzy links by host, for quick deny + re.tpl_host_fuzzy_test = + "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + + re.src_ZPCc + + "|>|$))"; + re.tpl_email_fuzzy = + "(^|" + + text_separators + + '|"|\\(|' + + re.src_ZCc + + ")" + + "(" + + re.src_email_name + + "@" + + re.tpl_host_fuzzy_strict + + ")"; + re.tpl_link_fuzzy = + // Fuzzy link can't be prepended with .:/\- and non punctuation. + // but can start with > (markdown blockquote) + "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|" + + re.src_ZPCc + + "))" + + "((?![$+<=>^`|\uff5c])" + + re.tpl_host_port_fuzzy_strict + + re.src_path + + ")"; + re.tpl_link_no_ip_fuzzy = + // Fuzzy link can't be prepended with .:/\- and non punctuation. + // but can start with > (markdown blockquote) + "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|" + + re.src_ZPCc + + "))" + + "((?![$+<=>^`|\uff5c])" + + re.tpl_host_port_no_ip_fuzzy_strict + + re.src_path + + ")"; + return re; } - if (ImagePreview.shouldRender(token)) { - infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ImagePreview, { - token - }, "image-preview")); + + // + // Helpers + // + + // Merge objects + // + function assign(obj /* from1, from2, from3, ... */) { + const sources = Array.prototype.slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) { + return; + } + Object.keys(source).forEach(function (key) { + obj[key] = source[key]; + }); + }); + return obj; } - if (!infoElements.length) { - ReactDOM.unmountComponentAtNode(tooltipDiv); - return null; + function _class(obj) { + return Object.prototype.toString.call(obj); } - ReactDOM.render(infoElements, tooltipDiv); - return tooltipDiv; - }); - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialResponse, - lineWrapping: true, - readOnly: true, - theme: editorTheme, - mode: "graphql-results", - foldGutter: true, - gutters: ["CodeMirror-foldgutter"], - // @ts-expect-error - info: true, - extraKeys: commonKeys - }); - setResponseEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialResponse, setResponseEditor]); - useSynchronizeOption(responseEditor, "keyMap", keyMap); - React.useEffect(() => { - if (fetchError) { - responseEditor == null ? void 0 : responseEditor.setValue(fetchError); - } - if (validationErrors.length > 0) { - responseEditor == null ? void 0 : responseEditor.setValue(toolkit.formatError(validationErrors)); - } - }, [responseEditor, fetchError, validationErrors]); - return ref; -} -function ResponseEditor(props) { - const ref = useResponseEditor(props, ResponseEditor); - return /* @__PURE__ */jsxRuntime.jsx("section", { - className: "result-window", - "aria-label": "Result Window", - "aria-live": "polite", - "aria-atomic": "true", - ref - }); -} -function VariableEditor({ - isHidden, - ...hookArgs -}) { - const { - variableEditor - } = useEditorContext({ - nonNull: true, - caller: VariableEditor - }); - const ref = useVariableEditor(hookArgs, VariableEditor); - React.useEffect(() => { - if (variableEditor && !isHidden) { - variableEditor.refresh(); - } - }, [variableEditor, isHidden]); - return /* @__PURE__ */jsxRuntime.jsx("div", { - className: clsx.clsx("graphiql-editor", isHidden && "hidden"), - ref - }); -} -function GraphiQLProvider({ - children, - dangerouslyAssumeSchemaIsValid, - defaultQuery, - defaultHeaders, - defaultTabs, - externalFragments, - fetcher, - getDefaultFieldNames, - headers, - inputValueDeprecation, - introspectionQueryName, - maxHistoryLength, - onEditOperationName, - onSchemaChange, - onTabChange, - onTogglePluginVisibility, - operationName, - plugins, - query, - response, - schema, - schemaDescription, - shouldPersistHeaders, - storage, - validationRules, - variables, - visiblePlugin -}) { - return /* @__PURE__ */jsxRuntime.jsx(StorageContextProvider, { - storage, - children: /* @__PURE__ */jsxRuntime.jsx(HistoryContextProvider, { - maxHistoryLength, - children: /* @__PURE__ */jsxRuntime.jsx(EditorContextProvider, { - defaultQuery, - defaultHeaders, - defaultTabs, - externalFragments, - headers, - onEditOperationName, - onTabChange, - query, - response, - shouldPersistHeaders, - validationRules, - variables, - children: /* @__PURE__ */jsxRuntime.jsx(SchemaContextProvider, { - dangerouslyAssumeSchemaIsValid, - fetcher, - inputValueDeprecation, - introspectionQueryName, - onSchemaChange, - schema, - schemaDescription, - children: /* @__PURE__ */jsxRuntime.jsx(ExecutionContextProvider, { - getDefaultFieldNames, - fetcher, - operationName, - children: /* @__PURE__ */jsxRuntime.jsx(ExplorerContextProvider, { - children: /* @__PURE__ */jsxRuntime.jsx(PluginContextProvider, { - onTogglePluginVisibility, - plugins, - visiblePlugin, - children - }) - }) - }) - }) - }) - }) - }); -} -function useTheme() { - const storageContext = useStorageContext(); - const [theme, setThemeInternal] = React.useState(() => { - if (!storageContext) { - return null; - } - const stored = storageContext.get(STORAGE_KEY); - switch (stored) { - case "light": - return "light"; - case "dark": - return "dark"; - default: - if (typeof stored === "string") { - storageContext.set(STORAGE_KEY, ""); - } - return null; - } - }); - React.useLayoutEffect(() => { - if (typeof window === "undefined") { - return; - } - document.body.classList.remove("graphiql-light", "graphiql-dark"); - if (theme) { - document.body.classList.add(`graphiql-${theme}`); - } - }, [theme]); - const setTheme = React.useCallback(newTheme => { - storageContext == null ? void 0 : storageContext.set(STORAGE_KEY, newTheme || ""); - setThemeInternal(newTheme); - }, [storageContext]); - return React.useMemo(() => ({ - theme, - setTheme - }), [theme, setTheme]); -} -const STORAGE_KEY = "theme"; -function useDragResize({ - defaultSizeRelation = DEFAULT_FLEX, - direction, - initiallyHidden, - onHiddenElementChange, - sizeThresholdFirst = 100, - sizeThresholdSecond = 100, - storageKey -}) { - const storage = useStorageContext(); - const store = React.useMemo(() => debounce(500, value => { - if (storageKey) { - storage == null ? void 0 : storage.set(storageKey, value); - } - }), [storage, storageKey]); - const [hiddenElement, setHiddenElement] = React.useState(() => { - const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)); - if (storedValue === HIDE_FIRST || initiallyHidden === "first") { - return "first"; - } - if (storedValue === HIDE_SECOND || initiallyHidden === "second") { - return "second"; - } - return null; - }); - const setHiddenElementWithCallback = React.useCallback(element => { - if (element !== hiddenElement) { - setHiddenElement(element); - onHiddenElementChange == null ? void 0 : onHiddenElementChange(element); - } - }, [hiddenElement, onHiddenElementChange]); - const firstRef = React.useRef(null); - const dragBarRef = React.useRef(null); - const secondRef = React.useRef(null); - const defaultFlexRef = React.useRef(`${defaultSizeRelation}`); - React.useLayoutEffect(() => { - const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)) || defaultFlexRef.current; - if (firstRef.current) { - firstRef.current.style.display = "flex"; - firstRef.current.style.flex = storedValue === HIDE_FIRST || storedValue === HIDE_SECOND ? defaultFlexRef.current : storedValue; - } - if (secondRef.current) { - secondRef.current.style.display = "flex"; - secondRef.current.style.flex = "1"; - } - if (dragBarRef.current) { - dragBarRef.current.style.display = "flex"; - } - }, [direction, storage, storageKey]); - const hide = React.useCallback(resizableElement => { - const element = resizableElement === "first" ? firstRef.current : secondRef.current; - if (!element) { - return; - } - element.style.left = "-1000px"; - element.style.position = "absolute"; - element.style.opacity = "0"; - element.style.height = "500px"; - element.style.width = "500px"; - if (firstRef.current) { - const flex = parseFloat(firstRef.current.style.flex); - if (!Number.isFinite(flex) || flex < 1) { - firstRef.current.style.flex = "1"; - } - } - }, []); - const show = React.useCallback(resizableElement => { - const element = resizableElement === "first" ? firstRef.current : secondRef.current; - if (!element) { - return; - } - element.style.width = ""; - element.style.height = ""; - element.style.opacity = ""; - element.style.position = ""; - element.style.left = ""; - if (storage && storageKey) { - const storedValue = storage.get(storageKey); - if (firstRef.current && storedValue !== HIDE_FIRST && storedValue !== HIDE_SECOND) { - firstRef.current.style.flex = storedValue || defaultFlexRef.current; - } - } - }, [storage, storageKey]); - React.useLayoutEffect(() => { - if (hiddenElement === "first") { - hide("first"); - } else { - show("first"); - } - if (hiddenElement === "second") { - hide("second"); - } else { - show("second"); - } - }, [hiddenElement, hide, show]); - React.useEffect(() => { - if (!dragBarRef.current || !firstRef.current || !secondRef.current) { - return; - } - const dragBarContainer = dragBarRef.current; - const firstContainer = firstRef.current; - const wrapper = firstContainer.parentElement; - const eventProperty = direction === "horizontal" ? "clientX" : "clientY"; - const rectProperty = direction === "horizontal" ? "left" : "top"; - const adjacentRectProperty = direction === "horizontal" ? "right" : "bottom"; - const sizeProperty = direction === "horizontal" ? "clientWidth" : "clientHeight"; - function handleMouseDown(downEvent) { - downEvent.preventDefault(); - const offset = downEvent[eventProperty] - dragBarContainer.getBoundingClientRect()[rectProperty]; - function handleMouseMove(moveEvent) { - if (moveEvent.buttons === 0) { - return handleMouseUp(); - } - const firstSize = moveEvent[eventProperty] - wrapper.getBoundingClientRect()[rectProperty] - offset; - const secondSize = wrapper.getBoundingClientRect()[adjacentRectProperty] - moveEvent[eventProperty] + offset - dragBarContainer[sizeProperty]; - if (firstSize < sizeThresholdFirst) { - setHiddenElementWithCallback("first"); - store(HIDE_FIRST); - } else if (secondSize < sizeThresholdSecond) { - setHiddenElementWithCallback("second"); - store(HIDE_SECOND); - } else { - setHiddenElementWithCallback(null); - const newFlex = `${firstSize / secondSize}`; - firstContainer.style.flex = newFlex; - store(newFlex); + function isString(obj) { + return _class(obj) === "[object String]"; } - } - function handleMouseUp() { - document.removeEventListener("mousemove", handleMouseMove); - document.removeEventListener("mouseup", handleMouseUp); - } - document.addEventListener("mousemove", handleMouseMove); - document.addEventListener("mouseup", handleMouseUp); - } - dragBarContainer.addEventListener("mousedown", handleMouseDown); - function reset() { - if (firstRef.current) { - firstRef.current.style.flex = defaultFlexRef.current; - } - store(defaultFlexRef.current); - setHiddenElementWithCallback(null); - } - dragBarContainer.addEventListener("dblclick", reset); - return () => { - dragBarContainer.removeEventListener("mousedown", handleMouseDown); - dragBarContainer.removeEventListener("dblclick", reset); - }; - }, [direction, setHiddenElementWithCallback, sizeThresholdFirst, sizeThresholdSecond, store]); - return React.useMemo(() => ({ - dragBarRef, - hiddenElement, - firstRef, - setHiddenElement, - secondRef - }), [hiddenElement, setHiddenElement]); -} -const DEFAULT_FLEX = 1; -const HIDE_FIRST = "hide-first"; -const HIDE_SECOND = "hide-second"; -const ToolbarButton = React.forwardRef(({ - label, - onClick, - ...props -}, ref) => { - const [error, setError] = React.useState(null); - const handleClick = React.useCallback(event => { - try { - onClick == null ? void 0 : onClick(event); - setError(null); - } catch (err) { - setError(err instanceof Error ? err : new Error(`Toolbar button click failed: ${err}`)); - } - }, [onClick]); - return /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-toolbar-button", error && "error", props.className), - onClick: handleClick, - "aria-label": error ? error.message : label, - "aria-invalid": error ? "true" : props["aria-invalid"] - }) - }); -}); -ToolbarButton.displayName = "ToolbarButton"; -function ExecuteButton() { - const { - queryEditor, - setOperationName - } = useEditorContext({ - nonNull: true, - caller: ExecuteButton - }); - const { - isFetching, - isSubscribed, - operationName, - run, - stop - } = useExecutionContext({ - nonNull: true, - caller: ExecuteButton - }); - const operations = (queryEditor == null ? void 0 : queryEditor.operations) || []; - const hasOptions = operations.length > 1 && typeof operationName !== "string"; - const isRunning = isFetching || isSubscribed; - const label = `${isRunning ? "Stop" : "Execute"} query (Ctrl-Enter)`; - const buttonProps = { - type: "button", - className: "graphiql-execute-button", - children: isRunning ? /* @__PURE__ */jsxRuntime.jsx(StopIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(PlayIcon, {}), - "aria-label": label - }; - return hasOptions && !isRunning ? /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { - children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { - ...buttonProps - }) - }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { - children: operations.map((operation, i) => { - const opName = operation.name ? operation.name.value : ``; - return /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Item, { - onSelect: () => { - var _a; - const selectedOperationName = (_a = operation.name) == null ? void 0 : _a.value; - if (queryEditor && selectedOperationName && selectedOperationName !== queryEditor.operationName) { - setOperationName(selectedOperationName); - } - run(); + function isObject(obj) { + return _class(obj) === "[object Object]"; + } + function isRegExp(obj) { + return _class(obj) === "[object RegExp]"; + } + function isFunction(obj) { + return _class(obj) === "[object Function]"; + } + function escapeRE(str) { + return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"); + } + + // + + const defaultOptions = { + fuzzyLink: true, + fuzzyEmail: true, + fuzzyIP: false, + }; + function isOptionsObj(obj) { + return Object.keys(obj || {}).reduce(function (acc, k) { + /* eslint-disable-next-line no-prototype-builtins */ + return acc || defaultOptions.hasOwnProperty(k); + }, false); + } + const defaultSchemas = { + "http:": { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.http) { + // compile lazily, because "host"-containing variables can change on tlds update. + self.re.http = new RegExp( + "^\\/\\/" + + self.re.src_auth + + self.re.src_host_port_strict + + self.re.src_path, + "i" + ); + } + if (self.re.http.test(tail)) { + return tail.match(self.re.http)[0].length; + } + return 0; + }, }, - children: opName - }, `${opName}-${i}`); - }) - })] - }) : /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx("button", { - ...buttonProps, - onClick: () => { - if (isRunning) { - stop(); - } else { - run(); + "https:": "http:", + "ftp:": "http:", + "//": { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.no_http) { + // compile lazily, because "host"-containing variables can change on tlds update. + self.re.no_http = new RegExp( + "^" + + self.re.src_auth + + // Don't allow single-level domains, because of false positives like '//test' + // with code comments + "(?:localhost|(?:(?:" + + self.re.src_domain + + ")\\.)+" + + self.re.src_domain_root + + ")" + + self.re.src_port + + self.re.src_host_terminator + + self.re.src_path, + "i" + ); + } + if (self.re.no_http.test(tail)) { + // should not be `://` & `///`, that protects from errors in protocol name + if (pos >= 3 && text[pos - 3] === ":") { + return 0; + } + if (pos >= 3 && text[pos - 3] === "/") { + return 0; + } + return tail.match(self.re.no_http)[0].length; + } + return 0; + }, + }, + "mailto:": { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.mailto) { + self.re.mailto = new RegExp( + "^" + self.re.src_email_name + "@" + self.re.src_host_strict, + "i" + ); + } + if (self.re.mailto.test(tail)) { + return tail.match(self.re.mailto)[0].length; + } + return 0; + }, + }, + }; + + // RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) + /* eslint-disable-next-line max-len */ + const tlds_2ch_src_re = + "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"; + + // DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead + const tlds_default = + "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split( + "|" + ); + function resetScanCache(self) { + self.__index__ = -1; + self.__text_cache__ = ""; + } + function createValidator(re) { + return function (text, pos) { + const tail = text.slice(pos); + if (re.test(tail)) { + return tail.match(re)[0].length; + } + return 0; + }; + } + function createNormalizer() { + return function (match, self) { + self.normalize(match); + }; } - } - }) - }); -} -const ToolbarMenuRoot = ({ - button, - children, - label, - ...props -}) => /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { - ...props, - children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { - className: clsx.clsx("graphiql-un-styled graphiql-toolbar-menu", props.className), - "aria-label": label, - children: button - }) - }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { - children - })] -}); -const ToolbarMenu = createComponentGroup(ToolbarMenuRoot, { - Item: DropdownMenu.Item -}); -exports.Argument = Argument; -exports.ArgumentIcon = ArgumentIcon; -exports.Button = Button$1; -exports.ButtonGroup = ButtonGroup; -exports.ChevronDownIcon = ChevronDownIcon; -exports.ChevronLeftIcon = ChevronLeftIcon; -exports.ChevronUpIcon = ChevronUpIcon; -exports.CloseIcon = CloseIcon; -exports.CopyIcon = CopyIcon; -exports.DOC_EXPLORER_PLUGIN = DOC_EXPLORER_PLUGIN; -exports.DefaultValue = DefaultValue; -exports.DeprecatedArgumentIcon = DeprecatedArgumentIcon; -exports.DeprecatedEnumValueIcon = DeprecatedEnumValueIcon; -exports.DeprecatedFieldIcon = DeprecatedFieldIcon; -exports.DeprecationReason = DeprecationReason; -exports.Dialog = Dialog; -exports.DialogRoot = DialogRoot; -exports.Directive = Directive; -exports.DirectiveIcon = DirectiveIcon; -exports.DocExplorer = DocExplorer; -exports.DocsFilledIcon = DocsFilledIcon; -exports.DocsIcon = DocsIcon; -exports.DropdownMenu = DropdownMenu; -exports.EditorContext = EditorContext; -exports.EditorContextProvider = EditorContextProvider; -exports.EnumValueIcon = EnumValueIcon; -exports.ExecuteButton = ExecuteButton; -exports.ExecutionContext = ExecutionContext; -exports.ExecutionContextProvider = ExecutionContextProvider; -exports.ExplorerContext = ExplorerContext; -exports.ExplorerContextProvider = ExplorerContextProvider; -exports.ExplorerSection = ExplorerSection; -exports.FieldDocumentation = FieldDocumentation; -exports.FieldIcon = FieldIcon; -exports.FieldLink = FieldLink; -exports.GraphiQLProvider = GraphiQLProvider; -exports.HISTORY_PLUGIN = HISTORY_PLUGIN; -exports.HeaderEditor = HeaderEditor; -exports.History = History; -exports.HistoryContext = HistoryContext; -exports.HistoryContextProvider = HistoryContextProvider; -exports.HistoryIcon = HistoryIcon; -exports.ImagePreview = ImagePreview; -exports.ImplementsIcon = ImplementsIcon; -exports.KeyboardShortcutIcon = KeyboardShortcutIcon; -exports.MagnifyingGlassIcon = MagnifyingGlassIcon; -exports.MarkdownContent = MarkdownContent; -exports.MergeIcon = MergeIcon; -exports.PenIcon = PenIcon; -exports.PlayIcon = PlayIcon; -exports.PluginContext = PluginContext; -exports.PluginContextProvider = PluginContextProvider; -exports.PlusIcon = PlusIcon; -exports.PrettifyIcon = PrettifyIcon; -exports.QueryEditor = QueryEditor; -exports.ReloadIcon = ReloadIcon; -exports.ResponseEditor = ResponseEditor; -exports.RootTypeIcon = RootTypeIcon; -exports.SchemaContext = SchemaContext; -exports.SchemaContextProvider = SchemaContextProvider; -exports.SchemaDocumentation = SchemaDocumentation; -exports.Search = Search; -exports.SettingsIcon = SettingsIcon; -exports.Spinner = Spinner; -exports.StarFilledIcon = StarFilledIcon; -exports.StarIcon = StarIcon; -exports.StopIcon = StopIcon; -exports.StorageContext = StorageContext; -exports.StorageContextProvider = StorageContextProvider; -exports.Tab = Tab; -exports.Tabs = Tabs; -exports.ToolbarButton = ToolbarButton; -exports.ToolbarMenu = ToolbarMenu; -exports.Tooltip = Tooltip; -exports.TooltipRoot = TooltipRoot; -exports.TrashIcon = TrashIcon; -exports.TypeDocumentation = TypeDocumentation; -exports.TypeIcon = TypeIcon; -exports.TypeLink = TypeLink; -exports.UnStyledButton = UnStyledButton; -exports.VariableEditor = VariableEditor; -exports.useAutoCompleteLeafs = useAutoCompleteLeafs; -exports.useCopyQuery = useCopyQuery; -exports.useDragResize = useDragResize; -exports.useEditorContext = useEditorContext; -exports.useEditorState = useEditorState; -exports.useExecutionContext = useExecutionContext; -exports.useExplorerContext = useExplorerContext; -exports.useHeaderEditor = useHeaderEditor; -exports.useHeadersEditorState = useHeadersEditorState; -exports.useHistoryContext = useHistoryContext; -exports.useMergeQuery = useMergeQuery; -exports.useOperationsEditorState = useOperationsEditorState; -exports.useOptimisticState = useOptimisticState; -exports.usePluginContext = usePluginContext; -exports.usePrettifyEditors = usePrettifyEditors; -exports.useQueryEditor = useQueryEditor; -exports.useResponseEditor = useResponseEditor; -exports.useSchemaContext = useSchemaContext; -exports.useStorageContext = useStorageContext; -exports.useTheme = useTheme; -exports.useVariableEditor = useVariableEditor; -exports.useVariablesEditorState = useVariablesEditorState; - -/***/ }), - -/***/ "../../graphiql-react/dist/info-addon.cjs.js": -/*!***************************************************!*\ - !*** ../../graphiql-react/dist/info-addon.cjs.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + // Schemas compiler. Build regexps. + // + function compile(self) { + // Load & clone RE patterns. + const re = (self.re = reFactory(self.__opts__)); + + // Define dynamic patterns + const tlds = self.__tlds__.slice(); + self.onCompile(); + if (!self.__tlds_replaced__) { + tlds.push(tlds_2ch_src_re); + } + tlds.push(re.src_xn); + re.src_tlds = tlds.join("|"); + function untpl(tpl) { + return tpl.replace("%TLDS%", re.src_tlds); + } + re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), "i"); + re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), "i"); + re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), "i"); + re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), "i"); + // + // Compile each schema + // -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -codemirror.CodeMirror.defineOption("info", false, (cm, options, old) => { - if (old && old !== codemirror.CodeMirror.Init) { - const oldOnMouseOver = cm.state.info.onMouseOver; - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); - clearTimeout(cm.state.info.hoverTimeout); - delete cm.state.info; - } - if (options) { - const state = cm.state.info = createState(options); - state.onMouseOver = onMouseOver.bind(null, cm); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - } -}); -function createState(options) { - return { - options: options instanceof Function ? { - render: options - } : options === true ? {} : options - }; -} -function getHoverTime(cm) { - const { - options - } = cm.state.info; - return (options === null || options === void 0 ? void 0 : options.hoverTime) || 500; -} -function onMouseOver(cm, e) { - const state = cm.state.info; - const target = e.target || e.srcElement; - if (!(target instanceof HTMLElement)) { - return; - } - if (target.nodeName !== "SPAN" || state.hoverTimeout !== void 0) { - return; - } - const box = target.getBoundingClientRect(); - const onMouseMove = function () { - clearTimeout(state.hoverTimeout); - state.hoverTimeout = setTimeout(onHover, hoverTime); - }; - const onMouseOut = function () { - codemirror.CodeMirror.off(document, "mousemove", onMouseMove); - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); - clearTimeout(state.hoverTimeout); - state.hoverTimeout = void 0; - }; - const onHover = function () { - codemirror.CodeMirror.off(document, "mousemove", onMouseMove); - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); - state.hoverTimeout = void 0; - onMouseHover(cm, box); - }; - const hoverTime = getHoverTime(cm); - state.hoverTimeout = setTimeout(onHover, hoverTime); - codemirror.CodeMirror.on(document, "mousemove", onMouseMove); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); -} -function onMouseHover(cm, box) { - const pos = cm.coordsChar({ - left: (box.left + box.right) / 2, - top: (box.top + box.bottom) / 2 - }, "window"); - const state = cm.state.info; - const { - options - } = state; - const render = options.render || cm.getHelper(pos, "info"); - if (render) { - const token = cm.getTokenAt(pos, true); - if (token) { - const info = render(token, options, cm, pos); - if (info) { - showPopup(cm, box, info); - } - } - } -} -function showPopup(cm, box, info) { - const popup = document.createElement("div"); - popup.className = "CodeMirror-info"; - popup.append(info); - document.body.append(popup); - const popupBox = popup.getBoundingClientRect(); - const popupStyle = window.getComputedStyle(popup); - const popupWidth = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight); - const popupHeight = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom); - let topPos = box.bottom; - if (popupHeight > window.innerHeight - box.bottom - 15 && box.top > window.innerHeight - box.bottom) { - topPos = box.top - popupHeight; - } - if (topPos < 0) { - topPos = box.bottom; - } - let leftPos = Math.max(0, window.innerWidth - popupWidth - 15); - if (leftPos > box.left) { - leftPos = box.left; - } - popup.style.opacity = "1"; - popup.style.top = topPos + "px"; - popup.style.left = leftPos + "px"; - let popupTimeout; - const onMouseOverPopup = function () { - clearTimeout(popupTimeout); - }; - const onMouseOut = function () { - clearTimeout(popupTimeout); - popupTimeout = setTimeout(hidePopup, 200); - }; - const hidePopup = function () { - codemirror.CodeMirror.off(popup, "mouseover", onMouseOverPopup); - codemirror.CodeMirror.off(popup, "mouseout", onMouseOut); - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); - if (popup.style.opacity) { - popup.style.opacity = "0"; - setTimeout(() => { - if (popup.parentNode) { - popup.remove(); - } - }, 600); - } else if (popup.parentNode) { - popup.remove(); - } - }; - codemirror.CodeMirror.on(popup, "mouseover", onMouseOverPopup); - codemirror.CodeMirror.on(popup, "mouseout", onMouseOut); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); -} + const aliases = []; + self.__compiled__ = {}; // Reset compiled data -/***/ }), + function schemaError(name, val) { + throw new Error( + '(LinkifyIt) Invalid schema "' + name + '": ' + val + ); + } + Object.keys(self.__schemas__).forEach(function (name) { + const val = self.__schemas__[name]; -/***/ "../../graphiql-react/dist/info.cjs.js": -/*!*********************************************!*\ - !*** ../../graphiql-react/dist/info.cjs.js ***! - \*********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + // skip disabled methods + if (val === null) { + return; + } + const compiled = { + validate: null, + link: null, + }; + self.__compiled__[name] = compiled; + if (isObject(val)) { + if (isRegExp(val.validate)) { + compiled.validate = createValidator(val.validate); + } else if (isFunction(val.validate)) { + compiled.validate = val.validate; + } else { + schemaError(name, val); + } + if (isFunction(val.normalize)) { + compiled.normalize = val.normalize; + } else if (!val.normalize) { + compiled.normalize = createNormalizer(); + } else { + schemaError(name, val); + } + return; + } + if (isString(val)) { + aliases.push(name); + return; + } + schemaError(name, val); + }); + // + // Compile postponed aliases + // + aliases.forEach(function (alias) { + if (!self.__compiled__[self.__schemas__[alias]]) { + // Silently fail on missed schemas to avoid errons on disable. + // schemaError(alias, self.__schemas__[alias]); + return; + } + self.__compiled__[alias].validate = + self.__compiled__[self.__schemas__[alias]].validate; + self.__compiled__[alias].normalize = + self.__compiled__[self.__schemas__[alias]].normalize; + }); -const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); -__webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"); -codemirror.CodeMirror.registerHelper("info", "graphql", (token, options) => { - var _a; - if (!options.schema || !token.state) { - return; - } - const { - kind, - step - } = token.state; - const typeInfo = SchemaReference.getTypeInfo(options.schema, token.state); - if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef || kind === "ObjectField" && step === 0 && typeInfo.fieldDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderField(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.fieldDef); - return into; - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderDirective(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.directiveDef); - return into; - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderArg(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.argDef); - return into; - } - if (kind === "EnumValue" && ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.description)) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderEnumValue(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.enumValue); - return into; - } - if (kind === "NamedType" && typeInfo.type && typeInfo.type.description) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderType(header, typeInfo, options, typeInfo.type); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.type); - return into; - } -}); -function renderField(into, typeInfo, options) { - renderQualifiedField(into, typeInfo, options); - renderTypeAnnotation(into, typeInfo, options, typeInfo.type); -} -function renderQualifiedField(into, typeInfo, options) { - var _a; - const fieldName = ((_a = typeInfo.fieldDef) === null || _a === void 0 ? void 0 : _a.name) || ""; - text(into, fieldName, "field-name", options, SchemaReference.getFieldReference(typeInfo)); -} -function renderDirective(into, typeInfo, options) { - var _a; - const name = "@" + (((_a = typeInfo.directiveDef) === null || _a === void 0 ? void 0 : _a.name) || ""); - text(into, name, "directive-name", options, SchemaReference.getDirectiveReference(typeInfo)); -} -function renderArg(into, typeInfo, options) { - var _a; - const name = ((_a = typeInfo.argDef) === null || _a === void 0 ? void 0 : _a.name) || ""; - text(into, name, "arg-name", options, SchemaReference.getArgumentReference(typeInfo)); - renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); -} -function renderEnumValue(into, typeInfo, options) { - var _a; - const name = ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.name) || ""; - renderType(into, typeInfo, options, typeInfo.inputType); - text(into, "."); - text(into, name, "enum-value", options, SchemaReference.getEnumValueReference(typeInfo)); -} -function renderTypeAnnotation(into, typeInfo, options, t) { - const typeSpan = document.createElement("span"); - typeSpan.className = "type-name-pill"; - if (t instanceof graphql.GraphQLNonNull) { - renderType(typeSpan, typeInfo, options, t.ofType); - text(typeSpan, "!"); - } else if (t instanceof graphql.GraphQLList) { - text(typeSpan, "["); - renderType(typeSpan, typeInfo, options, t.ofType); - text(typeSpan, "]"); - } else { - text(typeSpan, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); - } - into.append(typeSpan); -} -function renderType(into, typeInfo, options, t) { - if (t instanceof graphql.GraphQLNonNull) { - renderType(into, typeInfo, options, t.ofType); - text(into, "!"); - } else if (t instanceof graphql.GraphQLList) { - text(into, "["); - renderType(into, typeInfo, options, t.ofType); - text(into, "]"); - } else { - text(into, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); - } -} -function renderDescription(into, options, def) { - const { - description - } = def; - if (description) { - const descriptionDiv = document.createElement("div"); - descriptionDiv.className = "info-description"; - if (options.renderDescription) { - descriptionDiv.innerHTML = options.renderDescription(description); - } else { - descriptionDiv.append(document.createTextNode(description)); - } - into.append(descriptionDiv); - } - renderDeprecation(into, options, def); -} -function renderDeprecation(into, options, def) { - const reason = def.deprecationReason; - if (reason) { - const deprecationDiv = document.createElement("div"); - deprecationDiv.className = "info-deprecation"; - into.append(deprecationDiv); - const label = document.createElement("span"); - label.className = "info-deprecation-label"; - label.append(document.createTextNode("Deprecated")); - deprecationDiv.append(label); - const reasonDiv = document.createElement("div"); - reasonDiv.className = "info-deprecation-reason"; - if (options.renderDescription) { - reasonDiv.innerHTML = options.renderDescription(reason); - } else { - reasonDiv.append(document.createTextNode(reason)); - } - deprecationDiv.append(reasonDiv); - } -} -function text(into, content, className = "", options = { - onClick: null -}, ref = null) { - if (className) { - const { - onClick - } = options; - let node; - if (onClick) { - node = document.createElement("a"); - node.href = "javascript:void 0"; - node.addEventListener("click", e => { - e.preventDefault(); - onClick(ref, e); - }); - } else { - node = document.createElement("span"); - } - node.className = className; - node.append(document.createTextNode(content)); - into.append(node); - } else { - into.append(document.createTextNode(content)); - } -} + // + // Fake record for guessed links + // + self.__compiled__[""] = { + validate: null, + normalize: createNormalizer(), + }; -/***/ }), + // + // Build schema condition + // + const slist = Object.keys(self.__compiled__) + .filter(function (name) { + // Filter disabled & fake schemas + return name.length > 0 && self.__compiled__[name]; + }) + .map(escapeRE) + .join("|"); + // (?!_) cause 1.5x slowdown + self.re.schema_test = RegExp( + "(^|(?!_)(?:[><\uff5c]|" + re.src_ZPCc + "))(" + slist + ")", + "i" + ); + self.re.schema_search = RegExp( + "(^|(?!_)(?:[><\uff5c]|" + re.src_ZPCc + "))(" + slist + ")", + "ig" + ); + self.re.schema_at_start = RegExp( + "^" + self.re.schema_search.source, + "i" + ); + self.re.pretest = RegExp( + "(" + + self.re.schema_test.source + + ")|(" + + self.re.host_fuzzy_test.source + + ")|@", + "i" + ); -/***/ "../../graphiql-react/dist/javascript.cjs.js": -/*!***************************************************!*\ - !*** ../../graphiql-react/dist/javascript.cjs.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } + // + // Cleanup + // + + resetScanCache(self); } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var javascript$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - CodeMirror.defineMode("javascript", function (config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var trackScope = parserConfig.trackScope !== false; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - var keywords = function () { - function kw(type2) { - return { - type: type2, - style: "keyword" - }; + + /** + * class Match + * + * Match result. Single element of array, returned by [[LinkifyIt#match]] + **/ + function Match(self, shift) { + const start = self.__index__; + const end = self.__last_index__; + const text = self.__text_cache__.slice(start, end); + + /** + * Match#schema -> String + * + * Prefix (protocol) for matched string. + **/ + this.schema = self.__schema__.toLowerCase(); + /** + * Match#index -> Number + * + * First position of matched string. + **/ + this.index = start + shift; + /** + * Match#lastIndex -> Number + * + * Next position after matched string. + **/ + this.lastIndex = end + shift; + /** + * Match#raw -> String + * + * Matched string. + **/ + this.raw = text; + /** + * Match#text -> String + * + * Notmalized text of matched string. + **/ + this.text = text; + /** + * Match#url -> String + * + * Normalized url of matched string. + **/ + this.url = text; + } + function createMatch(self, shift) { + const match = new Match(self, shift); + self.__compiled__[match.schema].normalize(match, self); + return match; } - var A = kw("keyword a"), - B = kw("keyword b"), - C = kw("keyword c"), - D = kw("keyword d"); - var operator = kw("operator"), - atom = { - type: "atom", - style: "atom" - }; - return { - "if": kw("if"), - "while": A, - "with": A, - "else": B, - "do": B, - "try": B, - "finally": B, - "return": D, - "break": D, - "continue": D, - "new": kw("new"), - "delete": C, - "void": C, - "throw": C, - "debugger": kw("debugger"), - "var": kw("var"), - "const": kw("var"), - "let": kw("var"), - "function": kw("function"), - "catch": kw("catch"), - "for": kw("for"), - "switch": kw("switch"), - "case": kw("case"), - "default": kw("default"), - "in": operator, - "typeof": operator, - "instanceof": operator, - "true": atom, - "false": atom, - "null": atom, - "undefined": atom, - "NaN": atom, - "Infinity": atom, - "this": kw("this"), - "class": kw("class"), - "super": kw("atom"), - "yield": C, - "export": kw("export"), - "import": kw("import"), - "extends": C, - "await": C + + /** + * class LinkifyIt + **/ + + /** + * new LinkifyIt(schemas, options) + * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) + * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } + * + * Creates new linkifier instance with optional additional schemas. + * Can be called without `new` keyword for convenience. + * + * By default understands: + * + * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links + * - "fuzzy" links and emails (example.com, foo@bar.com). + * + * `schemas` is an object, where each key/value describes protocol/rule: + * + * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` + * for example). `linkify-it` makes shure that prefix is not preceeded with + * alphanumeric char and symbols. Only whitespaces and punctuation allowed. + * - __value__ - rule to check tail after link prefix + * - _String_ - just alias to existing rule + * - _Object_ + * - _validate_ - validator function (should return matched length on success), + * or `RegExp`. + * - _normalize_ - optional function to normalize text & url of matched result + * (for example, for @twitter mentions). + * + * `options`: + * + * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. + * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts + * like version numbers. Default `false`. + * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. + * + **/ + function LinkifyIt(schemas, options) { + if (!(this instanceof LinkifyIt)) { + return new LinkifyIt(schemas, options); + } + if (!options) { + if (isOptionsObj(schemas)) { + options = schemas; + schemas = {}; + } + } + this.__opts__ = assign({}, defaultOptions, options); + + // Cache last tested result. Used to skip repeating steps on next `match` call. + this.__index__ = -1; + this.__last_index__ = -1; // Next scan position + this.__schema__ = ""; + this.__text_cache__ = ""; + this.__schemas__ = assign({}, defaultSchemas, schemas); + this.__compiled__ = {}; + this.__tlds__ = tlds_default; + this.__tlds_replaced__ = false; + this.re = {}; + compile(this); + } + + /** chainable + * LinkifyIt#add(schema, definition) + * - schema (String): rule name (fixed pattern prefix) + * - definition (String|RegExp|Object): schema definition + * + * Add new rule definition. See constructor description for details. + **/ + LinkifyIt.prototype.add = function add(schema, definition) { + this.__schemas__[schema] = definition; + compile(this); + return this; }; - }(); - var isOperatorChar = /[+\-*&%=<>!?|~^@]/; - var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - function readRegexp(stream) { - var escaped = false, - next, - inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true;else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; - } - } - var type, content; - function ret(tp, style, cont2) { - type = tp; - content = cont2; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (expressionAllowed(stream, state, 1)) { - readRegexp(stream); - stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); - return ret("regexp", "string-2"); - } else { - stream.eat("="); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#" && stream.peek() == "!") { - stream.skipToEnd(); - return ret("meta", "meta"); - } else if (ch == "#" && stream.eatWhile(wordRE)) { - return ret("variable", "property"); - } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (isOperatorChar.test(ch)) { - if (ch != ">" || !state.lexical || state.lexical.type != ">") { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("="); - } else if (/[<>*+\-|&?]/.test(ch)) { - stream.eat(ch); - if (ch == ">") stream.eat(ch); - } - } - if (ch == "?" && stream.eat(".")) return ret("."); - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current(); - if (state.lastType != ".") { - if (keywords.propertyIsEnumerable(word)) { - var kw = keywords[word]; - return ret(kw.type, kw.style, word); - } - if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word); - } - return ret("variable", "variable", word); - } - } - function tokenString(quote) { - return function (stream, state) { - var escaped = false, - next; - if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); + + /** chainable + * LinkifyIt#set(options) + * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } + * + * Set recognition options for links without schema. + **/ + LinkifyIt.prototype.set = function set(options) { + this.__opts__ = assign(this.__opts__, options); + return this; }; - } - function tokenComment(stream, state) { - var maybeEnd = false, - ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = ch == "*"; - } - return ret("comment", "comment"); - } - function tokenQuasi(stream, state) { - var escaped = false, - next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; + + /** + * LinkifyIt#test(text) -> Boolean + * + * Searches linkifiable pattern and returns `true` on success or `false` on fail. + **/ + LinkifyIt.prototype.test = function test(text) { + // Reset scan cache + this.__text_cache__ = text; + this.__index__ = -1; + if (!text.length) { + return false; } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - var brackets = "([{}])"; - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - if (isTS) { - var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)); - if (m) arrow = m.index; - } - var depth = 0, - sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { - ++pos; - break; - } - if (--depth == 0) { - if (ch == "(") sawSomething = true; - break; - } - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/`]/.test(ch)) { - for (;; --pos) { - if (pos == 0) return; - var next = stream.string.charAt(pos - 1); - if (next == ch && stream.string.charAt(pos - 2) != "\\") { - pos--; + let m, ml, me, len, shift, next, re, tld_pos, at_pos; + + // try to scan for link with schema - that's the most simple rule + if (this.re.schema_test.test(text)) { + re = this.re.schema_search; + re.lastIndex = 0; + while ((m = re.exec(text)) !== null) { + len = this.testSchemaAt(text, m[2], re.lastIndex); + if (len) { + this.__schema__ = m[2]; + this.__index__ = m.index + m[1].length; + this.__last_index__ = m.index + m[0].length + len; break; } } - } else if (sawSomething && !depth) { - ++pos; - break; } - } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - var atomicTypes = { - "atom": true, - "number": true, - "variable": true, - "string": true, - "regexp": true, - "this": true, - "import": true, - "jsonld-keyword": true - }; - function JSLexical(indented, column, type2, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type2; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - function inScope(state, varname) { - if (!trackScope) return false; - for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; - for (var cx2 = state.context; cx2; cx2 = cx2.prev) { - for (var v = cx2.vars; v; v = v.next) if (v.name == varname) return true; - } - } - function parseJS(state, style, type2, content2, stream) { - var cc = state.cc; - cx.state = state; - cx.stream = stream; - cx.marked = null, cx.cc = cc; - cx.style = style; - if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; - while (true) { - var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; - if (combinator(type2, content2)) { - while (cc.length && cc[cc.length - 1].lex) cc.pop()(); - if (cx.marked) return cx.marked; - if (type2 == "variable" && inScope(state, content2)) return "variable-2"; - return style; + if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) { + // guess schemaless links + tld_pos = text.search(this.re.host_fuzzy_test); + if (tld_pos >= 0) { + // if tld is located after found link - no need to check fuzzy pattern + if (this.__index__ < 0 || tld_pos < this.__index__) { + if ( + (ml = text.match( + this.__opts__.fuzzyIP + ? this.re.link_fuzzy + : this.re.link_no_ip_fuzzy + )) !== null + ) { + shift = ml.index + ml[1].length; + if (this.__index__ < 0 || shift < this.__index__) { + this.__schema__ = ""; + this.__index__ = shift; + this.__last_index__ = ml.index + ml[0].length; + } + } + } + } } - } - } - var cx = { - state: null, - column: null, - marked: null, - cc: null - }; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - function inList(name, list) { - for (var v = list; v; v = v.next) if (v.name == name) return true; - return false; - } - function register(varname) { - var state = cx.state; - cx.marked = "def"; - if (!trackScope) return; - if (state.context) { - if (state.lexical.info == "var" && state.context && state.context.block) { - var newContext = registerVarScoped(varname, state.context); - if (newContext != null) { - state.context = newContext; - return; + if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) { + // guess schemaless emails + at_pos = text.indexOf("@"); + if (at_pos >= 0) { + // We can't skip this check, because this cases are possible: + // 192.168.1.1@gmail.com, my.in@example.com + if ((me = text.match(this.re.email_fuzzy)) !== null) { + shift = me.index + me[1].length; + next = me.index + me[0].length; + if ( + this.__index__ < 0 || + shift < this.__index__ || + (shift === this.__index__ && next > this.__last_index__) + ) { + this.__schema__ = "mailto:"; + this.__index__ = shift; + this.__last_index__ = next; + } + } } - } else if (!inList(varname, state.localVars)) { - state.localVars = new Var(varname, state.localVars); - return; } - } - if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars); - } - function registerVarScoped(varname, context) { - if (!context) { + return this.__index__ >= 0; + }; + + /** + * LinkifyIt#pretest(text) -> Boolean + * + * Very quick check, that can give false positives. Returns true if link MAY BE + * can exists. Can be used for speed optimization, when you need to check that + * link NOT exists. + **/ + LinkifyIt.prototype.pretest = function pretest(text) { + return this.re.pretest.test(text); + }; + + /** + * LinkifyIt#testSchemaAt(text, name, position) -> Number + * - text (String): text to scan + * - name (String): rule (schema) name + * - position (Number): text offset to check from + * + * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly + * at given position. Returns length of found pattern (0 on fail). + **/ + LinkifyIt.prototype.testSchemaAt = function testSchemaAt( + text, + schema, + pos + ) { + // If not supported schema check requested - terminate + if (!this.__compiled__[schema.toLowerCase()]) { + return 0; + } + return this.__compiled__[schema.toLowerCase()].validate( + text, + pos, + this + ); + }; + + /** + * LinkifyIt#match(text) -> Array|null + * + * Returns array of found link descriptions or `null` on fail. We strongly + * recommend to use [[LinkifyIt#test]] first, for best speed. + * + * ##### Result match description + * + * - __schema__ - link schema, can be empty for fuzzy links, or `//` for + * protocol-neutral links. + * - __index__ - offset of matched text + * - __lastIndex__ - index of next char after mathch end + * - __raw__ - matched text + * - __text__ - normalized text + * - __url__ - link, generated from matched text + **/ + LinkifyIt.prototype.match = function match(text) { + const result = []; + let shift = 0; + + // Try to take previous element from cache, if .test() called before + if (this.__index__ >= 0 && this.__text_cache__ === text) { + result.push(createMatch(this, shift)); + shift = this.__last_index__; + } + + // Cut head if cache was used + let tail = shift ? text.slice(shift) : text; + + // Scan string until end reached + while (this.test(tail)) { + result.push(createMatch(this, shift)); + tail = tail.slice(this.__last_index__); + shift += this.__last_index__; + } + if (result.length) { + return result; + } return null; - } else if (context.block) { - var inner = registerVarScoped(varname, context.prev); - if (!inner) return null; - if (inner == context.prev) return context; - return new Context(inner, context.vars, true); - } else if (inList(varname, context.vars)) { - return context; - } else { - return new Context(context.prev, new Var(varname, context.vars), false); - } - } - function isModifier(name) { - return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; - } - function Context(prev, vars, block2) { - this.prev = prev; - this.vars = vars; - this.block = block2; - } - function Var(name, next) { - this.name = name; - this.next = next; - } - var defaultVars = new Var("this", new Var("arguments", null)); - function pushcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, false); - cx.state.localVars = defaultVars; - } - function pushblockcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, true); - cx.state.localVars = null; - } - pushcontext.lex = pushblockcontext.lex = true; - function popcontext() { - cx.state.localVars = cx.state.context.vars; - cx.state.context = cx.state.context.prev; - } - popcontext.lex = true; - function pushlex(type2, info) { - var result = function () { - var state = cx.state, - indent = state.indented; - if (state.lexical.type == "stat") indent = state.lexical.indented;else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; - state.lexical = new JSLexical(indent, cx.stream.column(), type2, null, state.lexical, info); }; - result.lex = true; - return result; - } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - function expect(wanted) { - function exp(type2) { - if (type2 == wanted) return cont();else if (wanted == ";" || type2 == "}" || type2 == ")" || type2 == "]") return pass();else return cont(exp); - } - return exp; - } - function statement(type2, value) { - if (type2 == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); - if (type2 == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); - if (type2 == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type2 == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); - if (type2 == "debugger") return cont(expect(";")); - if (type2 == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); - if (type2 == ";") return cont(); - if (type2 == "if") { - if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); - return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); - } - if (type2 == "function") return cont(functiondef); - if (type2 == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); - if (type2 == "class" || isTS && value == "interface") { - cx.marked = "keyword"; - return cont(pushlex("form", type2 == "class" ? type2 : value), className, poplex); - } - if (type2 == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword"; - return cont(statement); - } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { - cx.marked = "keyword"; - if (value == "enum") return cont(enumdef);else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); - } else if (isTS && value == "namespace") { - cx.marked = "keyword"; - return cont(pushlex("form"), expression, statement, poplex); - } else if (isTS && value == "abstract") { - cx.marked = "keyword"; - return cont(statement); - } else { - return cont(pushlex("stat"), maybelabel); - } - } - if (type2 == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); - if (type2 == "case") return cont(expression, expect(":")); - if (type2 == "default") return cont(expect(":")); - if (type2 == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); - if (type2 == "export") return cont(pushlex("stat"), afterExport, poplex); - if (type2 == "import") return cont(pushlex("stat"), afterImport, poplex); - if (type2 == "async") return cont(statement); - if (value == "@") return cont(expression, statement); - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function maybeCatchBinding(type2) { - if (type2 == "(") return cont(funarg, expect(")")); - } - function expression(type2, value) { - return expressionInner(type2, value, false); - } - function expressionNoComma(type2, value) { - return expressionInner(type2, value, true); - } - function parenExpr(type2) { - if (type2 != "(") return pass(); - return cont(pushlex(")"), maybeexpression, expect(")"), poplex); - } - function expressionInner(type2, value, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);else if (type2 == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); - } - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); - if (type2 == "function") return cont(functiondef, maybeop); - if (type2 == "class" || isTS && value == "interface") { - cx.marked = "keyword"; - return cont(pushlex("form"), classExpression, poplex); - } - if (type2 == "keyword c" || type2 == "async") return cont(noComma ? expressionNoComma : expression); - if (type2 == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); - if (type2 == "operator" || type2 == "spread") return cont(noComma ? expressionNoComma : expression); - if (type2 == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type2 == "{") return contCommasep(objprop, "}", null, maybeop); - if (type2 == "quasi") return pass(quasi, maybeop); - if (type2 == "new") return cont(maybeTarget(noComma)); - return cont(); - } - function maybeexpression(type2) { - if (type2.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - function maybeoperatorComma(type2, value) { - if (type2 == ",") return cont(maybeexpression); - return maybeoperatorNoComma(type2, value, false); - } - function maybeoperatorNoComma(type2, value, noComma) { - var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type2 == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); - if (type2 == "operator") { - if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); - if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); - if (value == "?") return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type2 == "quasi") { - return pass(quasi, me); - } - if (type2 == ";") return; - if (type2 == "(") return contCommasep(expressionNoComma, ")", "call", me); - if (type2 == ".") return cont(property, me); - if (type2 == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); - if (isTS && value == "as") { - cx.marked = "keyword"; - return cont(typeexpr, me); - } - if (type2 == "regexp") { - cx.state.lastType = cx.marked = "operator"; - cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); - return cont(expr); - } - } - function quasi(type2, value) { - if (type2 != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(maybeexpression, continueQuasi); - } - function continueQuasi(type2) { - if (type2 == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); - } - } - function arrowBody(type2) { - findFatArrow(cx.stream, cx.state); - return pass(type2 == "{" ? statement : expression); - } - function arrowBodyNoComma(type2) { - findFatArrow(cx.stream, cx.state); - return pass(type2 == "{" ? statement : expressionNoComma); - } - function maybeTarget(noComma) { - return function (type2) { - if (type2 == ".") return cont(noComma ? targetNoComma : target);else if (type2 == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);else return pass(noComma ? expressionNoComma : expression); + + /** + * LinkifyIt#matchAtStart(text) -> Match|null + * + * Returns fully-formed (not fuzzy) link if it starts at the beginning + * of the string, and null otherwise. + **/ + LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { + // Reset scan cache + this.__text_cache__ = text; + this.__index__ = -1; + if (!text.length) return null; + const m = this.re.schema_at_start.exec(text); + if (!m) return null; + const len = this.testSchemaAt(text, m[2], m[0].length); + if (!len) return null; + this.__schema__ = m[2]; + this.__index__ = m.index + m[1].length; + this.__last_index__ = m.index + m[0].length + len; + return createMatch(this, 0); }; - } - function target(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorComma); - } - } - function targetNoComma(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorNoComma); - } - } - function maybelabel(type2) { - if (type2 == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type2) { - if (type2 == "variable") { - cx.marked = "property"; - return cont(); - } - } - function objprop(type2, value) { - if (type2 == "async") { - cx.marked = "property"; - return cont(objprop); - } else if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(getterSetter); - var m; - if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length; - return cont(afterprop); - } else if (type2 == "number" || type2 == "string") { - cx.marked = jsonldMode ? "property" : cx.style + " property"; - return cont(afterprop); - } else if (type2 == "jsonld-keyword") { - return cont(afterprop); - } else if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(objprop); - } else if (type2 == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type2 == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } else if (type2 == ":") { - return pass(afterprop); + + /** chainable + * LinkifyIt#tlds(list [, keepOld]) -> this + * - list (Array): list of tlds + * - keepOld (Boolean): merge with current list if `true` (`false` by default) + * + * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) + * to avoid false positives. By default this algorythm used: + * + * - hostname with any 2-letter root zones are ok. + * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф + * are ok. + * - encoded (`xn--...`) root zones are ok. + * + * If list is replaced, then exact match for 2-chars root zones will be checked. + **/ + LinkifyIt.prototype.tlds = function tlds(list, keepOld) { + list = Array.isArray(list) ? list : [list]; + if (!keepOld) { + this.__tlds__ = list.slice(); + this.__tlds_replaced__ = true; + compile(this); + return this; + } + this.__tlds__ = this.__tlds__ + .concat(list) + .sort() + .filter(function (el, idx, arr) { + return el !== arr[idx - 1]; + }) + .reverse(); + compile(this); + return this; + }; + + /** + * LinkifyIt#normalize(match) + * + * Default normalizer (if schema does not define it's own). + **/ + LinkifyIt.prototype.normalize = function normalize(match) { + // Do minimal possible changes by default. Need to collect feedback prior + // to move forward https://github.com/markdown-it/linkify-it/issues/1 + + if (!match.schema) { + match.url = "http://" + match.url; + } + if (match.schema === "mailto:" && !/^mailto:/i.test(match.url)) { + match.url = "mailto:" + match.url; + } + }; + + /** + * LinkifyIt#onCompile() + * + * Override to modify basic RegExp-s. + **/ + LinkifyIt.prototype.onCompile = function onCompile() {}; + module.exports = LinkifyIt; + + /***/ + }, + + /***/ "../node_modules/markdown-it/dist/index.cjs.js": + /*!*****************************************************!*\ + !*** ../node_modules/markdown-it/dist/index.cjs.js ***! + \*****************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var mdurl = __webpack_require__( + /*! mdurl */ "../node_modules/mdurl/build/index.cjs.js" + ); + var ucmicro = __webpack_require__( + /*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js" + ); + var entities = __webpack_require__( + /*! entities */ "../../../node_modules/entities/lib/index.js" + ); + var LinkifyIt = __webpack_require__( + /*! linkify-it */ "../node_modules/linkify-it/build/index.cjs.js" + ); + var punycode = __webpack_require__( + /*! punycode.js */ "../../../node_modules/punycode.js/punycode.es6.js" + ); + function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== "default") { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: function () { + return e[k]; + }, + } + ); + } + }); + } + n.default = e; + return Object.freeze(n); } - } - function getterSetter(type2) { - if (type2 != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type2) { - if (type2 == ":") return cont(expressionNoComma); - if (type2 == "(") return pass(functiondef); - } - function commasep(what, end, sep) { - function proceed(type2, value) { - if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(function (type3, value2) { - if (type3 == end || value2 == end) return pass(); - return pass(what); - }, proceed); - } - if (type2 == end || value == end) return cont(); - if (sep && sep.indexOf(";") > -1) return pass(what); - return cont(expect(end)); - } - return function (type2, value) { - if (type2 == end || value == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type2) { - if (type2 == "}") return cont(); - return pass(statement, block); - } - function maybetype(type2, value) { - if (isTS) { - if (type2 == ":") return cont(typeexpr); - if (value == "?") return cont(maybetype); + var mdurl__namespace = /*#__PURE__*/ _interopNamespaceDefault(mdurl); + var ucmicro__namespace = + /*#__PURE__*/ _interopNamespaceDefault(ucmicro); + + // Utilities + // + + function _class(obj) { + return Object.prototype.toString.call(obj); } - } - function maybetypeOrIn(type2, value) { - if (isTS && (type2 == ":" || value == "in")) return cont(typeexpr); - } - function mayberettype(type2) { - if (isTS && type2 == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);else return cont(typeexpr); + function isString(obj) { + return _class(obj) === "[object String]"; } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword"; - return cont(); + const _hasOwnProperty = Object.prototype.hasOwnProperty; + function has(object, key) { + return _hasOwnProperty.call(object, key); } - } - function typeexpr(type2, value) { - if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { - cx.marked = "keyword"; - return cont(value == "typeof" ? expressionNoComma : typeexpr); - } - if (type2 == "variable" || value == "void") { - cx.marked = "type"; - return cont(afterType); - } - if (value == "|" || value == "&") return cont(typeexpr); - if (type2 == "string" || type2 == "number" || type2 == "atom") return cont(afterType); - if (type2 == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); - if (type2 == "{") return cont(pushlex("}"), typeprops, poplex, afterType); - if (type2 == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType); - if (type2 == "<") return cont(commasep(typeexpr, ">"), typeexpr); - if (type2 == "quasi") { - return pass(quasiType, afterType); + + // Merge objects + // + function assign(obj /* from1, from2, from3, ... */) { + const sources = Array.prototype.slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) { + return; + } + if (typeof source !== "object") { + throw new TypeError(source + "must be object"); + } + Object.keys(source).forEach(function (key) { + obj[key] = source[key]; + }); + }); + return obj; } - } - function maybeReturnType(type2) { - if (type2 == "=>") return cont(typeexpr); - } - function typeprops(type2) { - if (type2.match(/[\}\)\]]/)) return cont(); - if (type2 == "," || type2 == ";") return cont(typeprops); - return pass(typeprop, typeprops); - } - function typeprop(type2, value) { - if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(typeprop); - } else if (value == "?" || type2 == "number" || type2 == "string") { - return cont(typeprop); - } else if (type2 == ":") { - return cont(typeexpr); - } else if (type2 == "[") { - return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); - } else if (type2 == "(") { - return pass(functiondecl, typeprop); - } else if (!type2.match(/[;\}\)\],]/)) { - return cont(); + + // Remove element from array and put another array at those position. + // Useful for some operations with tokens + function arrayReplaceAt(src, pos, newElements) { + return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); } - } - function quasiType(type2, value) { - if (type2 != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasiType); - return cont(typeexpr, continueQuasiType); - } - function continueQuasiType(type2) { - if (type2 == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasiType); + function isValidEntityCode(c) { + /* eslint no-bitwise:0 */ + // broken sequence + if (c >= 0xd800 && c <= 0xdfff) { + return false; + } + // never used + if (c >= 0xfdd0 && c <= 0xfdef) { + return false; + } + if ((c & 0xffff) === 0xffff || (c & 0xffff) === 0xfffe) { + return false; + } + // control codes + if (c >= 0x00 && c <= 0x08) { + return false; + } + if (c === 0x0b) { + return false; + } + if (c >= 0x0e && c <= 0x1f) { + return false; + } + if (c >= 0x7f && c <= 0x9f) { + return false; + } + // out of range + if (c > 0x10ffff) { + return false; + } + return true; } - } - function typearg(type2, value) { - if (type2 == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg); - if (type2 == ":") return cont(typeexpr); - if (type2 == "spread") return cont(typearg); - return pass(typeexpr); - } - function afterType(type2, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); - if (value == "|" || type2 == "." || value == "&") return cont(typeexpr); - if (type2 == "[") return cont(typeexpr, expect("]"), afterType); - if (value == "extends" || value == "implements") { - cx.marked = "keyword"; - return cont(typeexpr); - } - if (value == "?") return cont(typeexpr, expect(":"), typeexpr); - } - function maybeTypeArgs(_, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault); - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr); - } - function vardef(_, value) { - if (value == "enum") { - cx.marked = "keyword"; - return cont(enumdef); + function fromCodePoint(c) { + /* eslint no-bitwise:0 */ + if (c > 0xffff) { + c -= 0x10000; + const surrogate1 = 0xd800 + (c >> 10); + const surrogate2 = 0xdc00 + (c & 0x3ff); + return String.fromCharCode(surrogate1, surrogate2); + } + return String.fromCharCode(c); + } + const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g; + const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; + const UNESCAPE_ALL_RE = new RegExp( + UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, + "gi" + ); + const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i; + function replaceEntityPattern(match, name) { + if ( + name.charCodeAt(0) === 0x23 /* # */ && + DIGITAL_ENTITY_TEST_RE.test(name) + ) { + const code = + name[1].toLowerCase() === "x" + ? parseInt(name.slice(2), 16) + : parseInt(name.slice(1), 10); + if (isValidEntityCode(code)) { + return fromCodePoint(code); + } + return match; + } + const decoded = entities.decodeHTML(match); + if (decoded !== match) { + return decoded; + } + return match; } - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type2, value) { - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(pattern); - } - if (type2 == "variable") { - register(value); - return cont(); - } - if (type2 == "spread") return cont(pattern); - if (type2 == "[") return contCommasep(eltpattern, "]"); - if (type2 == "{") return contCommasep(proppattern, "}"); - } - function proppattern(type2, value) { - if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type2 == "variable") cx.marked = "property"; - if (type2 == "spread") return cont(pattern); - if (type2 == "}") return pass(); - if (type2 == "[") return cont(expression, expect("]"), expect(":"), proppattern); - return cont(expect(":"), pattern, maybeAssign); - } - function eltpattern() { - return pass(pattern, maybeAssign); - } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); - } - function vardefCont(type2) { - if (type2 == ",") return cont(vardef); - } - function maybeelse(type2, value) { - if (type2 == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); - } - function forspec(type2, value) { - if (value == "await") return cont(forspec); - if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); - } - function forspec1(type2) { - if (type2 == "var") return cont(vardef, forspec2); - if (type2 == "variable") return cont(forspec2); - return pass(forspec2); - } - function forspec2(type2, value) { - if (type2 == ")") return cont(); - if (type2 == ";") return cont(forspec2); - if (value == "in" || value == "of") { - cx.marked = "keyword"; - return cont(expression, forspec2); - } - return pass(expression, forspec2); - } - function functiondef(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondef); + + /* function replaceEntities(str) { + if (str.indexOf('&') < 0) { return str; } + + return str.replace(ENTITY_RE, replaceEntityPattern); +} */ + + function unescapeMd(str) { + if (str.indexOf("\\") < 0) { + return str; + } + return str.replace(UNESCAPE_MD_RE, "$1"); } - if (type2 == "variable") { - register(value); - return cont(functiondef); + function unescapeAll(str) { + if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) { + return str; + } + return str.replace( + UNESCAPE_ALL_RE, + function (match, escaped, entity) { + if (escaped) { + return escaped; + } + return replaceEntityPattern(match, entity); + } + ); } - if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); - } - function functiondecl(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondecl); + const HTML_ESCAPE_TEST_RE = /[&<>"]/; + const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; + const HTML_REPLACEMENTS = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + }; + function replaceUnsafeChar(ch) { + return HTML_REPLACEMENTS[ch]; } - if (type2 == "variable") { - register(value); - return cont(functiondecl); + function escapeHtml(str) { + if (HTML_ESCAPE_TEST_RE.test(str)) { + return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); + } + return str; } - if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); - } - function typename(type2, value) { - if (type2 == "keyword" || type2 == "variable") { - cx.marked = "type"; - return cont(typename); - } else if (value == "<") { - return cont(pushlex(">"), commasep(typeparam, ">"), poplex); + const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; + function escapeRE(str) { + return str.replace(REGEXP_ESCAPE_RE, "\\$&"); } - } - function funarg(type2, value) { - if (value == "@") cont(expression, funarg); - if (type2 == "spread") return cont(funarg); - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(funarg); - } - if (isTS && type2 == "this") return cont(maybetype, maybeAssign); - return pass(pattern, maybetype, maybeAssign); - } - function classExpression(type2, value) { - if (type2 == "variable") return className(type2, value); - return classNameAfter(type2, value); - } - function className(type2, value) { - if (type2 == "variable") { - register(value); - return cont(classNameAfter); + function isSpace(code) { + switch (code) { + case 0x09: + case 0x20: + return true; + } + return false; } - } - function classNameAfter(type2, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); - if (value == "extends" || value == "implements" || isTS && type2 == ",") { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); + + // Zs (unicode class) || [\t\f\v\r\n] + function isWhitespace(code) { + if (code >= 0x2000 && code <= 0x200a) { + return true; + } + switch (code) { + case 0x09: // \t + case 0x0a: // \n + case 0x0b: // \v + case 0x0c: // \f + case 0x0d: // \r + case 0x20: + case 0xa0: + case 0x1680: + case 0x202f: + case 0x205f: + case 0x3000: + return true; + } + return false; } - if (type2 == "{") return cont(pushlex("}"), classBody, poplex); - } - function classBody(type2, value) { - if (type2 == "async" || type2 == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { - cx.marked = "keyword"; - return cont(classBody); - } - if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(classfield, classBody); - } - if (type2 == "number" || type2 == "string") return cont(classfield, classBody); - if (type2 == "[") return cont(expression, maybetype, expect("]"), classfield, classBody); - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (isTS && type2 == "(") return pass(functiondecl, classBody); - if (type2 == ";" || type2 == ",") return cont(classBody); - if (type2 == "}") return cont(); - if (value == "@") return cont(expression, classBody); - } - function classfield(type2, value) { - if (value == "!") return cont(classfield); - if (value == "?") return cont(classfield); - if (type2 == ":") return cont(typeexpr, maybeAssign); - if (value == "=") return cont(expressionNoComma); - var context = cx.state.lexical.prev, - isInterface = context && context.info == "interface"; - return pass(isInterface ? functiondecl : functiondef); - } - function afterExport(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(maybeFrom, expect(";")); + + /* eslint-disable max-len */ + + // Currently without astral characters support. + function isPunctChar(ch) { + return ucmicro__namespace.P.test(ch) || ucmicro__namespace.S.test(ch); } - if (value == "default") { - cx.marked = "keyword"; - return cont(expression, expect(";")); + + // Markdown ASCII punctuation characters. + // + // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ + // http://spec.commonmark.org/0.15/#ascii-punctuation-character + // + // Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. + // + function isMdAsciiPunct(ch) { + switch (ch) { + case 0x21 /* ! */: + case 0x22 /* " */: + case 0x23 /* # */: + case 0x24 /* $ */: + case 0x25 /* % */: + case 0x26 /* & */: + case 0x27 /* ' */: + case 0x28 /* ( */: + case 0x29 /* ) */: + case 0x2a /* * */: + case 0x2b /* + */: + case 0x2c /* , */: + case 0x2d /* - */: + case 0x2e /* . */: + case 0x2f /* / */: + case 0x3a /* : */: + case 0x3b /* ; */: + case 0x3c /* < */: + case 0x3d /* = */: + case 0x3e /* > */: + case 0x3f /* ? */: + case 0x40 /* @ */: + case 0x5b /* [ */: + case 0x5c /* \ */: + case 0x5d /* ] */: + case 0x5e /* ^ */: + case 0x5f /* _ */: + case 0x60 /* ` */: + case 0x7b /* { */: + case 0x7c /* | */: + case 0x7d /* } */: + case 0x7e /* ~ */: + return true; + default: + return false; + } } - if (type2 == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); - return pass(statement); - } - function exportField(type2, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(expect("variable")); + + // Hepler to unify [reference labels]. + // + function normalizeReference(str) { + // Trim and collapse whitespace + // + str = str.trim().replace(/\s+/g, " "); + + // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug + // fixed in v12 (couldn't find any details). + // + // So treat this one as a special case + // (remove this when node v10 is no longer supported). + // + if ("ẞ".toLowerCase() === "Ṿ") { + str = str.replace(/ẞ/g, "ß"); + } + + // .toLowerCase().toUpperCase() should get rid of all differences + // between letter variants. + // + // Simple .toLowerCase() doesn't normalize 125 code points correctly, + // and .toUpperCase doesn't normalize 6 of them (list of exceptions: + // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently + // uppercased versions). + // + // Here's an example showing how it happens. Lets take greek letter omega: + // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) + // + // Unicode entries: + // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; + // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 + // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 + // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; + // + // Case-insensitive comparison should treat all of them as equivalent. + // + // But .toLowerCase() doesn't change ϑ (it's already lowercase), + // and .toUpperCase() doesn't change ϴ (already uppercase). + // + // Applying first lower then upper case normalizes any character: + // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' + // + // Note: this is equivalent to unicode case folding; unicode normalization + // is a different step that is not required here. + // + // Final result should be uppercased, because it's later stored in an object + // (this avoid a conflict with Object.prototype members, + // most notably, `__proto__`) + // + return str.toLowerCase().toUpperCase(); } - if (type2 == "variable") return pass(expressionNoComma, exportField); - } - function afterImport(type2) { - if (type2 == "string") return cont(); - if (type2 == "(") return pass(expression); - if (type2 == ".") return pass(maybeoperatorComma); - return pass(importSpec, maybeMoreImports, maybeFrom); - } - function importSpec(type2, value) { - if (type2 == "{") return contCommasep(importSpec, "}"); - if (type2 == "variable") register(value); - if (value == "*") cx.marked = "keyword"; - return cont(maybeAs); - } - function maybeMoreImports(type2) { - if (type2 == ",") return cont(importSpec, maybeMoreImports); - } - function maybeAs(_type, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(importSpec); + + // Re-export libraries commonly used in both markdown-it and its plugins, + // so plugins won't have to depend on them explicitly, which reduces their + // bundled size (e.g. a browser build). + // + const lib = { + mdurl: mdurl__namespace, + ucmicro: ucmicro__namespace, + }; + var utils = /*#__PURE__*/ Object.freeze({ + __proto__: null, + arrayReplaceAt: arrayReplaceAt, + assign: assign, + escapeHtml: escapeHtml, + escapeRE: escapeRE, + fromCodePoint: fromCodePoint, + has: has, + isMdAsciiPunct: isMdAsciiPunct, + isPunctChar: isPunctChar, + isSpace: isSpace, + isString: isString, + isValidEntityCode: isValidEntityCode, + isWhitespace: isWhitespace, + lib: lib, + normalizeReference: normalizeReference, + unescapeAll: unescapeAll, + unescapeMd: unescapeMd, + }); + + // Parse link label + // + // this function assumes that first character ("[") already matches; + // returns the end of the label + // + + function parseLinkLabel(state, start, disableNested) { + let level, found, marker, prevPos; + const max = state.posMax; + const oldPos = state.pos; + state.pos = start + 1; + level = 1; + while (state.pos < max) { + marker = state.src.charCodeAt(state.pos); + if (marker === 0x5d /* ] */) { + level--; + if (level === 0) { + found = true; + break; + } + } + prevPos = state.pos; + state.md.inline.skipToken(state); + if (marker === 0x5b /* [ */) { + if (prevPos === state.pos - 1) { + // increase level if we find text `[`, which is not a part of any token + level++; + } else if (disableNested) { + state.pos = oldPos; + return -1; + } + } + } + let labelEnd = -1; + if (found) { + labelEnd = state.pos; + } + + // restore old state + state.pos = oldPos; + return labelEnd; } - } - function maybeFrom(_type, value) { - if (value == "from") { - cx.marked = "keyword"; - return cont(expression); + + // Parse link destination + // + + function parseLinkDestination(str, start, max) { + let code; + let pos = start; + const result = { + ok: false, + pos: 0, + str: "", + }; + if (str.charCodeAt(pos) === 0x3c /* < */) { + pos++; + while (pos < max) { + code = str.charCodeAt(pos); + if (code === 0x0a /* \n */) { + return result; + } + if (code === 0x3c /* < */) { + return result; + } + if (code === 0x3e /* > */) { + result.pos = pos + 1; + result.str = unescapeAll(str.slice(start + 1, pos)); + result.ok = true; + return result; + } + if (code === 0x5c /* \ */ && pos + 1 < max) { + pos += 2; + continue; + } + pos++; + } + + // no closing '>' + return result; + } + + // this should be ... } else { ... branch + + let level = 0; + while (pos < max) { + code = str.charCodeAt(pos); + if (code === 0x20) { + break; + } + + // ascii control characters + if (code < 0x20 || code === 0x7f) { + break; + } + if (code === 0x5c /* \ */ && pos + 1 < max) { + if (str.charCodeAt(pos + 1) === 0x20) { + break; + } + pos += 2; + continue; + } + if (code === 0x28 /* ( */) { + level++; + if (level > 32) { + return result; + } + } + if (code === 0x29 /* ) */) { + if (level === 0) { + break; + } + level--; + } + pos++; + } + if (start === pos) { + return result; + } + if (level !== 0) { + return result; + } + result.str = unescapeAll(str.slice(start, pos)); + result.pos = pos; + result.ok = true; + return result; } - } - function arrayLiteral(type2) { - if (type2 == "]") return cont(); - return pass(commasep(expressionNoComma, "]")); - } - function enumdef() { - return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); - } - function enummember() { - return pass(pattern, maybeAssign); - } - function isContinuedStatement(state, textAfter) { - return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); - } - function expressionAllowed(stream, state, backUp) { - return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); - } - return { - startState: function (basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && new Context(null, null, false), - indented: basecolumn || 0 + + // Parse link title + // + + // Parse link title within `str` in [start, max] range, + // or continue previous parsing if `prev_state` is defined (equal to result of last execution). + // + function parseLinkTitle(str, start, max, prev_state) { + let code; + let pos = start; + const state = { + // if `true`, this is a valid link title + ok: false, + // if `true`, this link can be continued on the next line + can_continue: false, + // if `ok`, it's the position of the first character after the closing marker + pos: 0, + // if `ok`, it's the unescaped title + str: "", + // expected closing marker character code + marker: 0, }; - if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; - return state; - }, - token: function (stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; - return parseJS(state, style, type, content, stream); - }, - indent: function (state, textAfter) { - if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), - lexical = state.lexical, - top; - if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev;else if (c != maybeelse && c != popcontext) break; - } - while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) lexical = lexical.prev; - if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; - var type2 = lexical.type, - closing = firstChar == type2; - if (type2 == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);else if (type2 == "form" && firstChar == "{") return lexical.indented;else if (type2 == "form") return lexical.indented + indentUnit;else if (type2 == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);else if (lexical.align) return lexical.column + (closing ? 0 : 1);else return lexical.indented + (closing ? 0 : indentUnit); - }, - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - blockCommentContinue: jsonMode ? null : " * ", - lineComment: jsonMode ? null : "//", - fold: "brace", - closeBrackets: "()[]{}''\"\"``", - helperType: jsonMode ? "json" : "javascript", - jsonldMode, - jsonMode, - expressionAllowed, - skipExpression: function (state) { - parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); - } - }; - }); - CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - CodeMirror.defineMIME("text/javascript", "javascript"); - CodeMirror.defineMIME("text/ecmascript", "javascript"); - CodeMirror.defineMIME("application/javascript", "javascript"); - CodeMirror.defineMIME("application/x-javascript", "javascript"); - CodeMirror.defineMIME("application/ecmascript", "javascript"); - CodeMirror.defineMIME("application/json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/x-json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/manifest+json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/ld+json", { - name: "javascript", - jsonld: true - }); - CodeMirror.defineMIME("text/typescript", { - name: "javascript", - typescript: true - }); - CodeMirror.defineMIME("application/typescript", { - name: "javascript", - typescript: true - }); - }); -})(); -var javascriptExports = javascript$2.exports; -const javascript = /* @__PURE__ */codemirror.getDefaultExportFromCjs(javascriptExports); -const javascript$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: javascript -}, [javascriptExports]); -exports.javascript = javascript$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/jump-to-line.cjs.js": -/*!*****************************************************!*\ - !*** ../../graphiql-react/dist/jump-to-line.cjs.js ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + if (prev_state) { + // this is a continuation of a previous parseLinkTitle call on the next line, + // used in reference links only + state.str = prev_state.str; + state.marker = prev_state.marker; + } else { + if (pos >= max) { + return state; + } + let marker = str.charCodeAt(pos); + if ( + marker !== 0x22 /* " */ && + marker !== 0x27 /* ' */ && + marker !== 0x28 /* ( */ + ) { + return state; + } + start++; + pos++; + + // if opening marker is "(", switch it to closing marker ")" + if (marker === 0x28) { + marker = 0x29; + } + state.marker = marker; + } + while (pos < max) { + code = str.charCodeAt(pos); + if (code === state.marker) { + state.pos = pos + 1; + state.str += unescapeAll(str.slice(start, pos)); + state.ok = true; + return state; + } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) { + return state; + } else if (code === 0x5c /* \ */ && pos + 1 < max) { + pos++; + } + pos++; } + + // no closing marker found, but this link title may continue on the next line (for references) + state.can_continue = true; + state.str += unescapeAll(str.slice(start, pos)); + return state; } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var jumpToLine$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), dialog.dialogExports); - })(function (CodeMirror) { - CodeMirror.defineOption("search", { - bottom: false - }); - function dialog2(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom - });else f(prompt(shortText, deflt)); - } - function getJumpDialog(cm) { - return cm.phrase("Jump to line:") + ' ' + cm.phrase("(Use line:column or scroll% syntax)") + ""; - } - function interpretLine(cm, string) { - var num = Number(string); - if (/^[-+]/.test(string)) return cm.getCursor().line + num;else return num - 1; - } - CodeMirror.commands.jumpToLine = function (cm) { - var cur = cm.getCursor(); - dialog2(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), cur.line + 1 + ":" + cur.ch, function (posStr) { - if (!posStr) return; - var match; - if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) { - cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); - } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) { - var line = Math.round(cm.lineCount() * Number(match[1]) / 100); - if (/^[-+]/.test(match[1])) line = cur.line + line + 1; - cm.setCursor(line - 1, cur.ch); - } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) { - cm.setCursor(interpretLine(cm, match[1]), cur.ch); - } - }); - }; - CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; - }); -})(); -var jumpToLineExports = jumpToLine$2.exports; -const jumpToLine = /* @__PURE__ */codemirror.getDefaultExportFromCjs(jumpToLineExports); -const jumpToLine$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: jumpToLine -}, [jumpToLineExports]); -exports.jumpToLine = jumpToLine$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/jump.cjs.js": -/*!*********************************************!*\ - !*** ../../graphiql-react/dist/jump.cjs.js ***! - \*********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + // Just a shortcut for bulk export + + var helpers = /*#__PURE__*/ Object.freeze({ + __proto__: null, + parseLinkDestination: parseLinkDestination, + parseLinkLabel: parseLinkLabel, + parseLinkTitle: parseLinkTitle, + }); + + /** + * class Renderer + * + * Generates HTML from parsed token stream. Each instance has independent + * copy of rules. Those can be rewritten with ease. Also, you can add new + * rules if you create plugin and adds new token types. + **/ + + const default_rules = {}; + default_rules.code_inline = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + return ( + "" + + escapeHtml(token.content) + + "" + ); + }; + default_rules.code_block = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + return ( + "" + + escapeHtml(tokens[idx].content) + + "\n" + ); + }; + default_rules.fence = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + const info = token.info ? unescapeAll(token.info).trim() : ""; + let langName = ""; + let langAttrs = ""; + if (info) { + const arr = info.split(/(\s+)/g); + langName = arr[0]; + langAttrs = arr.slice(2).join(""); + } + let highlighted; + if (options.highlight) { + highlighted = + options.highlight(token.content, langName, langAttrs) || + escapeHtml(token.content); + } else { + highlighted = escapeHtml(token.content); + } + if (highlighted.indexOf("${highlighted}\n`; + } + return `
${highlighted}
\n`; + }; + default_rules.image = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + + // "alt" attr MUST be set, even if empty. Because it's mandatory and + // should be placed on proper position for tests. + // + // Replace content with actual value + + token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText( + token.children, + options, + env + ); + return slf.renderToken(tokens, idx, options); + }; + default_rules.hardbreak = function (tokens, idx, options /*, env */) { + return options.xhtmlOut ? "
\n" : "
\n"; + }; + default_rules.softbreak = function (tokens, idx, options /*, env */) { + return options.breaks + ? options.xhtmlOut + ? "
\n" + : "
\n" + : "\n"; + }; + default_rules.text = function (tokens, idx /*, options, env */) { + return escapeHtml(tokens[idx].content); + }; + default_rules.html_block = function (tokens, idx /*, options, env */) { + return tokens[idx].content; + }; + default_rules.html_inline = function (tokens, idx /*, options, env */) { + return tokens[idx].content; + }; + + /** + * new Renderer() + * + * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. + **/ + function Renderer() { + /** + * Renderer#rules -> Object + * + * Contains render rules for tokens. Can be updated and extended. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.renderer.rules.strong_open = function () { return ''; }; + * md.renderer.rules.strong_close = function () { return ''; }; + * + * var result = md.renderInline(...); + * ``` + * + * Each rule is called as independent static function with fixed signature: + * + * ```javascript + * function my_token_render(tokens, idx, options, env, renderer) { + * // ... + * return renderedHTML; + * } + * ``` + * + * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs) + * for more details and examples. + **/ + this.rules = assign({}, default_rules); + } + /** + * Renderer.renderAttrs(token) -> String + * + * Render token attributes to string. + **/ + Renderer.prototype.renderAttrs = function renderAttrs(token) { + let i, l, result; + if (!token.attrs) { + return ""; + } + result = ""; + for (i = 0, l = token.attrs.length; i < l; i++) { + result += + " " + + escapeHtml(token.attrs[i][0]) + + '="' + + escapeHtml(token.attrs[i][1]) + + '"'; + } + return result; + }; -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); -codemirror.CodeMirror.defineOption("jump", false, (cm, options, old) => { - if (old && old !== codemirror.CodeMirror.Init) { - const oldOnMouseOver = cm.state.jump.onMouseOver; - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); - const oldOnMouseOut = cm.state.jump.onMouseOut; - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", oldOnMouseOut); - codemirror.CodeMirror.off(document, "keydown", cm.state.jump.onKeyDown); - delete cm.state.jump; - } - if (options) { - const state = cm.state.jump = { - options, - onMouseOver: onMouseOver.bind(null, cm), - onMouseOut: onMouseOut.bind(null, cm), - onKeyDown: onKeyDown.bind(null, cm) - }; - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", state.onMouseOut); - codemirror.CodeMirror.on(document, "keydown", state.onKeyDown); - } -}); -function onMouseOver(cm, event) { - const target = event.target || event.srcElement; - if (!(target instanceof HTMLElement)) { - return; - } - if ((target === null || target === void 0 ? void 0 : target.nodeName) !== "SPAN") { - return; - } - const box = target.getBoundingClientRect(); - const cursor = { - left: (box.left + box.right) / 2, - top: (box.top + box.bottom) / 2 - }; - cm.state.jump.cursor = cursor; - if (cm.state.jump.isHoldingModifier) { - enableJumpMode(cm); - } -} -function onMouseOut(cm) { - if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) { - cm.state.jump.cursor = null; - return; - } - if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) { - disableJumpMode(cm); - } -} -function onKeyDown(cm, event) { - if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) { - return; - } - cm.state.jump.isHoldingModifier = true; - if (cm.state.jump.cursor) { - enableJumpMode(cm); - } - const onKeyUp = upEvent => { - if (upEvent.code !== event.code) { - return; - } - cm.state.jump.isHoldingModifier = false; - if (cm.state.jump.marker) { - disableJumpMode(cm); - } - codemirror.CodeMirror.off(document, "keyup", onKeyUp); - codemirror.CodeMirror.off(document, "click", onClick); - cm.off("mousedown", onMouseDown); - }; - const onClick = clickEvent => { - const { - destination, - options - } = cm.state.jump; - if (destination) { - options.onClick(destination, clickEvent); - } - }; - const onMouseDown = (_, downEvent) => { - if (cm.state.jump.destination) { - downEvent.codemirrorIgnore = true; - } - }; - codemirror.CodeMirror.on(document, "keyup", onKeyUp); - codemirror.CodeMirror.on(document, "click", onClick); - cm.on("mousedown", onMouseDown); -} -const isMac = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.appVersion.includes("Mac")); -function isJumpModifier(key) { - return key === (isMac ? "Meta" : "Control"); -} -function enableJumpMode(cm) { - if (cm.state.jump.marker) { - return; - } - const { - cursor, - options - } = cm.state.jump; - const pos = cm.coordsChar(cursor); - const token = cm.getTokenAt(pos, true); - const getDestination = options.getDestination || cm.getHelper(pos, "jump"); - if (getDestination) { - const destination = getDestination(token, options, cm); - if (destination) { - const marker = cm.markText({ - line: pos.line, - ch: token.start - }, { - line: pos.line, - ch: token.end - }, { - className: "CodeMirror-jump-token" - }); - cm.state.jump.marker = marker; - cm.state.jump.destination = destination; - } - } -} -function disableJumpMode(cm) { - const { - marker - } = cm.state.jump; - cm.state.jump.marker = null; - cm.state.jump.destination = null; - marker.clear(); -} -codemirror.CodeMirror.registerHelper("jump", "graphql", (token, options) => { - if (!options.schema || !options.onClick || !token.state) { - return; - } - const { - state - } = token; - const { - kind, - step - } = state; - const typeInfo = SchemaReference.getTypeInfo(options.schema, state); - if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef) { - return SchemaReference.getFieldReference(typeInfo); - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - return SchemaReference.getDirectiveReference(typeInfo); - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - return SchemaReference.getArgumentReference(typeInfo); - } - if (kind === "EnumValue" && typeInfo.enumValue) { - return SchemaReference.getEnumValueReference(typeInfo); - } - if (kind === "NamedType" && typeInfo.type) { - return SchemaReference.getTypeReference(typeInfo); - } -}); + /** + * Renderer.renderToken(tokens, idx, options) -> String + * - tokens (Array): list of tokens + * - idx (Numbed): token index to render + * - options (Object): params of parser instance + * + * Default token renderer. Can be overriden by custom function + * in [[Renderer#rules]]. + **/ + Renderer.prototype.renderToken = function renderToken( + tokens, + idx, + options + ) { + const token = tokens[idx]; + let result = ""; + + // Tight list paragraphs + if (token.hidden) { + return ""; + } + + // Insert a newline between hidden paragraph and subsequent opening + // block-level tag. + // + // For example, here we should insert a newline before blockquote: + // - a + // > + // + if ( + token.block && + token.nesting !== -1 && + idx && + tokens[idx - 1].hidden + ) { + result += "\n"; + } + + // Add token name, e.g. ``. + // + needLf = false; + } + } + } + } + result += needLf ? ">\n" : ">"; + return result; + }; -/***/ }), + /** + * Renderer.renderInline(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * The same as [[Renderer.render]], but for single token of `inline` type. + **/ + Renderer.prototype.renderInline = function (tokens, options, env) { + let result = ""; + const rules = this.rules; + for (let i = 0, len = tokens.length; i < len; i++) { + const type = tokens[i].type; + if (typeof rules[type] !== "undefined") { + result += rules[type](tokens, i, options, env, this); + } else { + result += this.renderToken(tokens, i, options); + } + } + return result; + }; -/***/ "../../graphiql-react/dist/lint.cjs.js": -/*!*********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs.js ***! - \*********************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + /** internal + * Renderer.renderInlineAsText(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * Special kludge for image `alt` attributes to conform CommonMark spec. + * Don't try to use it! Spec requires to show `alt` content with stripped markup, + * instead of simple escaping. + **/ + Renderer.prototype.renderInlineAsText = function ( + tokens, + options, + env + ) { + let result = ""; + for (let i = 0, len = tokens.length; i < len; i++) { + switch (tokens[i].type) { + case "text": + result += tokens[i].content; + break; + case "image": + result += this.renderInlineAsText( + tokens[i].children, + options, + env + ); + break; + case "html_inline": + case "html_block": + result += tokens[i].content; + break; + case "softbreak": + case "hardbreak": + result += "\n"; + break; + // all other tokens are skipped + } } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var lint$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var GUTTER_ID = "CodeMirror-lint-markers"; - var LINT_LINE_ID = "CodeMirror-lint-line-"; - function showTooltip(cm, e, content) { - var tt = document.createElement("div"); - tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; - tt.appendChild(content.cloneNode(true)); - if (cm.state.lint.options.selfContain) cm.getWrapperElement().appendChild(tt);else document.body.appendChild(tt); - function position(e2) { - if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); - tt.style.top = Math.max(0, e2.clientY - tt.offsetHeight - 5) + "px"; - tt.style.left = e2.clientX + 5 + "px"; - } - CodeMirror.on(document, "mousemove", position); - position(e); - if (tt.style.opacity != null) tt.style.opacity = 1; - return tt; - } - function rm(elt) { - if (elt.parentNode) elt.parentNode.removeChild(elt); - } - function hideTooltip(tt) { - if (!tt.parentNode) return; - if (tt.style.opacity == null) rm(tt); - tt.style.opacity = 0; - setTimeout(function () { - rm(tt); - }, 600); - } - function showTooltipFor(cm, e, content, node) { - var tooltip = showTooltip(cm, e, content); - function hide() { - CodeMirror.off(node, "mouseout", hide); - if (tooltip) { - hideTooltip(tooltip); - tooltip = null; - } - } - var poll = setInterval(function () { - if (tooltip) for (var n = node;; n = n.parentNode) { - if (n && n.nodeType == 11) n = n.host; - if (n == document.body) return; - if (!n) { - hide(); - break; + return result; + }; + + /** + * Renderer.render(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * Takes token stream and generates HTML. Probably, you will never need to call + * this method directly. + **/ + Renderer.prototype.render = function (tokens, options, env) { + let result = ""; + const rules = this.rules; + for (let i = 0, len = tokens.length; i < len; i++) { + const type = tokens[i].type; + if (type === "inline") { + result += this.renderInline(tokens[i].children, options, env); + } else if (typeof rules[type] !== "undefined") { + result += rules[type](tokens, i, options, env, this); + } else { + result += this.renderToken(tokens, i, options, env); + } } + return result; + }; + + /** + * class Ruler + * + * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and + * [[MarkdownIt#inline]] to manage sequences of functions (rules): + * + * - keep rules in defined order + * - assign the name to each rule + * - enable/disable rules + * - add/replace rules + * - allow assign rules to additional named chains (in the same) + * - cacheing lists of active rules + * + * You will not need use this class directly until write plugins. For simple + * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and + * [[MarkdownIt.use]]. + **/ + + /** + * new Ruler() + **/ + function Ruler() { + // List of added rules. Each element is: + // + // { + // name: XXX, + // enabled: Boolean, + // fn: Function(), + // alt: [ name2, name3 ] + // } + // + this.__rules__ = []; + + // Cached rule chains. + // + // First level - chain name, '' for default. + // Second level - diginal anchor for fast filtering by charcodes. + // + this.__cache__ = null; } - if (!tooltip) return clearInterval(poll); - }, 400); - CodeMirror.on(node, "mouseout", hide); - } - function LintState(cm, conf, hasGutter) { - this.marked = []; - if (conf instanceof Function) conf = { - getAnnotations: conf - }; - if (!conf || conf === true) conf = {}; - this.options = {}; - this.linterOptions = conf.options || {}; - for (var prop in defaults) this.options[prop] = defaults[prop]; - for (var prop in conf) { - if (defaults.hasOwnProperty(prop)) { - if (conf[prop] != null) this.options[prop] = conf[prop]; - } else if (!conf.options) { - this.linterOptions[prop] = conf[prop]; - } - } - this.timeout = null; - this.hasGutter = hasGutter; - this.onMouseOver = function (e) { - onMouseOver(cm, e); - }; - this.waitingFor = 0; - } - var defaults = { - highlightLines: false, - tooltips: true, - delay: 500, - lintOnChange: true, - getAnnotations: null, - async: false, - selfContain: null, - formatAnnotation: null, - onUpdateLinting: null - }; - function clearMarks(cm) { - var state = cm.state.lint; - if (state.hasGutter) cm.clearGutter(GUTTER_ID); - if (state.options.highlightLines) clearErrorLines(cm); - for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); - state.marked.length = 0; - } - function clearErrorLines(cm) { - cm.eachLine(function (line) { - var has = line.wrapClass && /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); - if (has) cm.removeLineClass(line, "wrap", has[0]); - }); - } - function makeMarker(cm, labels, severity, multiple, tooltips) { - var marker = document.createElement("div"), - inner = marker; - marker.className = "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; - if (multiple) { - inner = marker.appendChild(document.createElement("div")); - inner.className = "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; - } - if (tooltips != false) CodeMirror.on(inner, "mouseover", function (e) { - showTooltipFor(cm, e, labels, inner); - }); - return marker; - } - function getMaxSeverity(a, b) { - if (a == "error") return a;else return b; - } - function groupByLine(annotations) { - var lines = []; - for (var i = 0; i < annotations.length; ++i) { - var ann = annotations[i], - line = ann.from.line; - (lines[line] || (lines[line] = [])).push(ann); - } - return lines; - } - function annotationTooltip(ann) { - var severity = ann.severity; - if (!severity) severity = "error"; - var tip = document.createElement("div"); - tip.className = "CodeMirror-lint-message CodeMirror-lint-message-" + severity; - if (typeof ann.messageHTML != "undefined") { - tip.innerHTML = ann.messageHTML; - } else { - tip.appendChild(document.createTextNode(ann.message)); - } - return tip; - } - function lintAsync(cm, getAnnotations) { - var state = cm.state.lint; - var id = ++state.waitingFor; - function abort() { - id = -1; - cm.off("change", abort); - } - cm.on("change", abort); - getAnnotations(cm.getValue(), function (annotations, arg2) { - cm.off("change", abort); - if (state.waitingFor != id) return; - if (arg2 && annotations instanceof CodeMirror) annotations = arg2; - cm.operation(function () { - updateLinting(cm, annotations); - }); - }, state.linterOptions, cm); - } - function startLinting(cm) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint"); - if (!getAnnotations) return; - if (options.async || getAnnotations.async) { - lintAsync(cm, getAnnotations); - } else { - var annotations = getAnnotations(cm.getValue(), state.linterOptions, cm); - if (!annotations) return; - if (annotations.then) annotations.then(function (issues) { - cm.operation(function () { - updateLinting(cm, issues); - }); - });else cm.operation(function () { - updateLinting(cm, annotations); - }); - } - } - function updateLinting(cm, annotationsNotSorted) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - clearMarks(cm); - var annotations = groupByLine(annotationsNotSorted); - for (var line = 0; line < annotations.length; ++line) { - var anns = annotations[line]; - if (!anns) continue; - var message = []; - anns = anns.filter(function (item) { - return message.indexOf(item.message) > -1 ? false : message.push(item.message); - }); - var maxSeverity = null; - var tipLabel = state.hasGutter && document.createDocumentFragment(); - for (var i = 0; i < anns.length; ++i) { - var ann = anns[i]; - var severity = ann.severity; - if (!severity) severity = "error"; - maxSeverity = getMaxSeverity(maxSeverity, severity); - if (options.formatAnnotation) ann = options.formatAnnotation(ann); - if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); - if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { - className: "CodeMirror-lint-mark CodeMirror-lint-mark-" + severity, - __annotation: ann - })); - } - if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(cm, tipLabel, maxSeverity, annotations[line].length > 1, options.tooltips)); - if (options.highlightLines) cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); - } - if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm); - } - function onChange(cm) { - var state = cm.state.lint; - if (!state) return; - clearTimeout(state.timeout); - state.timeout = setTimeout(function () { - startLinting(cm); - }, state.options.delay); - } - function popupTooltips(cm, annotations, e) { - var target = e.target || e.srcElement; - var tooltip = document.createDocumentFragment(); - for (var i = 0; i < annotations.length; i++) { - var ann = annotations[i]; - tooltip.appendChild(annotationTooltip(ann)); - } - showTooltipFor(cm, e, tooltip, target); - } - function onMouseOver(cm, e) { - var target = e.target || e.srcElement; - if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; - var box = target.getBoundingClientRect(), - x = (box.left + box.right) / 2, - y = (box.top + box.bottom) / 2; - var spans = cm.findMarksAt(cm.coordsChar({ - left: x, - top: y - }, "client")); - var annotations = []; - for (var i = 0; i < spans.length; ++i) { - var ann = spans[i].__annotation; - if (ann) annotations.push(ann); - } - if (annotations.length) popupTooltips(cm, annotations, e); - } - CodeMirror.defineOption("lint", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - clearMarks(cm); - if (cm.state.lint.options.lintOnChange !== false) cm.off("change", onChange); - CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver); - clearTimeout(cm.state.lint.timeout); - delete cm.state.lint; - } - if (val) { - var gutters = cm.getOption("gutters"), - hasLintGutter = false; - for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; - var state = cm.state.lint = new LintState(cm, val, hasLintGutter); - if (state.options.lintOnChange) cm.on("change", onChange); - if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - startLinting(cm); - } - }); - CodeMirror.defineExtension("performLint", function () { - startLinting(this); - }); - }); -})(); -var lintExports = lint$2.exports; -const lint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(lintExports); -const lint$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: lint -}, [lintExports]); -exports.lint = lint$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/lint.cjs2.js": -/*!**********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs2.js ***! - \**********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + // Helper methods, should not be used directly + // Find rule index by name + // + Ruler.prototype.__find__ = function (name) { + for (let i = 0; i < this.__rules__.length; i++) { + if (this.__rules__[i].name === name) { + return i; + } + } + return -1; + }; -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); -const SEVERITY = ["error", "warning", "information", "hint"]; -const TYPE = { - "GraphQL: Validation": "validation", - "GraphQL: Deprecation": "deprecation", - "GraphQL: Syntax": "syntax" -}; -codemirror.CodeMirror.registerHelper("lint", "graphql", (text, options) => { - const { - schema, - validationRules, - externalFragments - } = options; - const rawResults = graphqlLanguageService.getDiagnostics(text, schema, validationRules, void 0, externalFragments); - const results = rawResults.map(error => ({ - message: error.message, - severity: error.severity ? SEVERITY[error.severity - 1] : SEVERITY[0], - type: error.source ? TYPE[error.source] : void 0, - from: codemirror.CodeMirror.Pos(error.range.start.line, error.range.start.character), - to: codemirror.CodeMirror.Pos(error.range.end.line, error.range.end.character) - })); - return results; -}); - -/***/ }), - -/***/ "../../graphiql-react/dist/lint.cjs3.js": -/*!**********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs3.js ***! - \**********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function jsonParse(str) { - string = str; - strLen = str.length; - start = end = lastEnd = -1; - ch(); - lex(); - const ast = parseObj(); - expect("EOF"); - return ast; -} -let string; -let strLen; -let start; -let end; -let lastEnd; -let code; -let kind; -function parseObj() { - const nodeStart = start; - const members = []; - expect("{"); - if (!skip("}")) { - do { - members.push(parseMember()); - } while (skip(",")); - expect("}"); - } - return { - kind: "Object", - start: nodeStart, - end: lastEnd, - members - }; -} -function parseMember() { - const nodeStart = start; - const key = kind === "String" ? curToken() : null; - expect("String"); - expect(":"); - const value = parseVal(); - return { - kind: "Member", - start: nodeStart, - end: lastEnd, - key, - value - }; -} -function parseArr() { - const nodeStart = start; - const values = []; - expect("["); - if (!skip("]")) { - do { - values.push(parseVal()); - } while (skip(",")); - expect("]"); - } - return { - kind: "Array", - start: nodeStart, - end: lastEnd, - values - }; -} -function parseVal() { - switch (kind) { - case "[": - return parseArr(); - case "{": - return parseObj(); - case "String": - case "Number": - case "Boolean": - case "Null": - const token = curToken(); - lex(); - return token; - } - expect("Value"); -} -function curToken() { - return { - kind, - start, - end, - value: JSON.parse(string.slice(start, end)) - }; -} -function expect(str) { - if (kind === str) { - lex(); - return; - } - let found; - if (kind === "EOF") { - found = "[end of file]"; - } else if (end - start > 1) { - found = "`" + string.slice(start, end) + "`"; - } else { - const match = string.slice(start).match(/^.+?\b/); - found = "`" + (match ? match[0] : string[start]) + "`"; - } - throw syntaxError(`Expected ${str} but found ${found}.`); -} -class JSONSyntaxError extends Error { - constructor(message, position) { - super(message); - this.position = position; - } -} -function syntaxError(message) { - return new JSONSyntaxError(message, { - start, - end - }); -} -function skip(k) { - if (kind === k) { - lex(); - return true; - } -} -function ch() { - if (end < strLen) { - end++; - code = end === strLen ? 0 : string.charCodeAt(end); - } - return code; -} -function lex() { - lastEnd = end; - while (code === 9 || code === 10 || code === 13 || code === 32) { - ch(); - } - if (code === 0) { - kind = "EOF"; - return; - } - start = end; - switch (code) { - case 34: - kind = "String"; - return readString(); - case 45: - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - kind = "Number"; - return readNumber(); - case 102: - if (string.slice(start, start + 5) !== "false") { - break; - } - end += 4; - ch(); - kind = "Boolean"; - return; - case 110: - if (string.slice(start, start + 4) !== "null") { - break; - } - end += 3; - ch(); - kind = "Null"; - return; - case 116: - if (string.slice(start, start + 4) !== "true") { - break; - } - end += 3; - ch(); - kind = "Boolean"; - return; - } - kind = string[start]; - ch(); -} -function readString() { - ch(); - while (code !== 34 && code > 31) { - if (code === 92) { - code = ch(); - switch (code) { - case 34: - case 47: - case 92: - case 98: - case 102: - case 110: - case 114: - case 116: - ch(); - break; - case 117: - ch(); - readHex(); - readHex(); - readHex(); - readHex(); - break; - default: - throw syntaxError("Bad character escape sequence."); - } - } else if (end === strLen) { - throw syntaxError("Unterminated string."); - } else { - ch(); - } - } - if (code === 34) { - ch(); - return; - } - throw syntaxError("Unterminated string."); -} -function readHex() { - if (code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102) { - return ch(); - } - throw syntaxError("Expected hexadecimal digit."); -} -function readNumber() { - if (code === 45) { - ch(); - } - if (code === 48) { - ch(); - } else { - readDigits(); - } - if (code === 46) { - ch(); - readDigits(); - } - if (code === 69 || code === 101) { - code = ch(); - if (code === 43 || code === 45) { - ch(); - } - readDigits(); - } -} -function readDigits() { - if (code < 48 || code > 57) { - throw syntaxError("Expected decimal digit."); - } - do { - ch(); - } while (code >= 48 && code <= 57); -} -codemirror.CodeMirror.registerHelper("lint", "graphql-variables", (text, options, editor) => { - if (!text) { - return []; - } - let ast; - try { - ast = jsonParse(text); - } catch (error) { - if (error instanceof JSONSyntaxError) { - return [lintError(editor, error.position, error.message)]; - } - throw error; - } - const { - variableToType - } = options; - if (!variableToType) { - return []; - } - return validateVariables(editor, variableToType, ast); -}); -function validateVariables(editor, variableToType, variablesAST) { - var _a; - const errors = []; - for (const member of variablesAST.members) { - if (member) { - const variableName = (_a = member.key) === null || _a === void 0 ? void 0 : _a.value; - const type = variableToType[variableName]; - if (type) { - for (const [node, message] of validateValue(type, member.value)) { - errors.push(lintError(editor, node, message)); - } - } else { - errors.push(lintError(editor, member.key, `Variable "$${variableName}" does not appear in any GraphQL query.`)); - } - } - } - return errors; -} -function validateValue(type, valueAST) { - if (!type || !valueAST) { - return []; - } - if (type instanceof graphql.GraphQLNonNull) { - if (valueAST.kind === "Null") { - return [[valueAST, `Type "${type}" is non-nullable and cannot be null.`]]; - } - return validateValue(type.ofType, valueAST); - } - if (valueAST.kind === "Null") { - return []; - } - if (type instanceof graphql.GraphQLList) { - const itemType = type.ofType; - if (valueAST.kind === "Array") { - const values = valueAST.values || []; - return mapCat(values, item => validateValue(itemType, item)); - } - return validateValue(itemType, valueAST); - } - if (type instanceof graphql.GraphQLInputObjectType) { - if (valueAST.kind !== "Object") { - return [[valueAST, `Type "${type}" must be an Object.`]]; - } - const providedFields = /* @__PURE__ */Object.create(null); - const fieldErrors = mapCat(valueAST.members, member => { - var _a; - const fieldName = (_a = member === null || member === void 0 ? void 0 : member.key) === null || _a === void 0 ? void 0 : _a.value; - providedFields[fieldName] = true; - const inputField = type.getFields()[fieldName]; - if (!inputField) { - return [[member.key, `Type "${type}" does not have a field "${fieldName}".`]]; - } - const fieldType = inputField ? inputField.type : void 0; - return validateValue(fieldType, member.value); - }); - for (const fieldName of Object.keys(type.getFields())) { - const field = type.getFields()[fieldName]; - if (!providedFields[fieldName] && field.type instanceof graphql.GraphQLNonNull && !field.defaultValue) { - fieldErrors.push([valueAST, `Object of type "${type}" is missing required field "${fieldName}".`]); - } - } - return fieldErrors; - } - if (type.name === "Boolean" && valueAST.kind !== "Boolean" || type.name === "String" && valueAST.kind !== "String" || type.name === "ID" && valueAST.kind !== "Number" && valueAST.kind !== "String" || type.name === "Float" && valueAST.kind !== "Number" || type.name === "Int" && (valueAST.kind !== "Number" || (valueAST.value | 0) !== valueAST.value)) { - return [[valueAST, `Expected value of type "${type}".`]]; - } - if ((type instanceof graphql.GraphQLEnumType || type instanceof graphql.GraphQLScalarType) && (valueAST.kind !== "String" && valueAST.kind !== "Number" && valueAST.kind !== "Boolean" && valueAST.kind !== "Null" || isNullish(type.parseValue(valueAST.value)))) { - return [[valueAST, `Expected value of type "${type}".`]]; - } - return []; -} -function lintError(editor, node, message) { - return { - message, - severity: "error", - type: "validation", - from: editor.posFromIndex(node.start), - to: editor.posFromIndex(node.end) - }; -} -function isNullish(value) { - return value === null || value === void 0 || value !== value; -} -function mapCat(array, mapper) { - return Array.prototype.concat.apply([], array.map(mapper)); -} - -/***/ }), - -/***/ "../../graphiql-react/dist/matchbrackets.cjs.js": -/*!******************************************************!*\ - !*** ../../graphiql-react/dist/matchbrackets.cjs.js ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -const matchbrackets$2 = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] + // Build rules lookup cache + // + Ruler.prototype.__compile__ = function () { + const self = this; + const chains = [""]; + + // collect unique names + self.__rules__.forEach(function (rule) { + if (!rule.enabled) { + return; + } + rule.alt.forEach(function (altName) { + if (chains.indexOf(altName) < 0) { + chains.push(altName); + } }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var matchbracketsExports = matchbrackets$2.requireMatchbrackets(); -const matchbrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(matchbracketsExports); -const matchbrackets$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: matchbrackets -}, [matchbracketsExports]); -exports.matchbrackets = matchbrackets$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/matchbrackets.cjs2.js": -/*!*******************************************************!*\ - !*** ../../graphiql-react/dist/matchbrackets.cjs2.js ***! - \*******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + }); + self.__cache__ = {}; + chains.forEach(function (chain) { + self.__cache__[chain] = []; + self.__rules__.forEach(function (rule) { + if (!rule.enabled) { + return; + } + if (chain && rule.alt.indexOf(chain) < 0) { + return; + } + self.__cache__[chain].push(rule.fn); + }); + }); + }; + + /** + * Ruler.at(name, fn [, options]) + * - name (String): rule name to replace. + * - fn (Function): new rule function. + * - options (Object): new rule options (not mandatory). + * + * Replace rule by name with new function & options. Throws error if name not + * found. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * Replace existing typographer replacement rule with new one: + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.core.ruler.at('replacements', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.at = function (name, fn, options) { + const index = this.__find__(name); + const opt = options || {}; + if (index === -1) { + throw new Error("Parser rule not found: " + name); + } + this.__rules__[index].fn = fn; + this.__rules__[index].alt = opt.alt || []; + this.__cache__ = null; + }; + + /** + * Ruler.before(beforeName, ruleName, fn [, options]) + * - beforeName (String): new rule will be added before this one. + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Add new rule to chain before one with given name. See also + * [[Ruler.after]], [[Ruler.push]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.before = function (beforeName, ruleName, fn, options) { + const index = this.__find__(beforeName); + const opt = options || {}; + if (index === -1) { + throw new Error("Parser rule not found: " + beforeName); + } + this.__rules__.splice(index, 0, { + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [], + }); + this.__cache__ = null; + }; + + /** + * Ruler.after(afterName, ruleName, fn [, options]) + * - afterName (String): new rule will be added after this one. + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Add new rule to chain after one with given name. See also + * [[Ruler.before]], [[Ruler.push]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.inline.ruler.after('text', 'my_rule', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.after = function (afterName, ruleName, fn, options) { + const index = this.__find__(afterName); + const opt = options || {}; + if (index === -1) { + throw new Error("Parser rule not found: " + afterName); + } + this.__rules__.splice(index + 1, 0, { + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [], + }); + this.__cache__ = null; + }; + /** + * Ruler.push(ruleName, fn [, options]) + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Push new rule to the end of chain. See also + * [[Ruler.before]], [[Ruler.after]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.core.ruler.push('my_rule', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.push = function (ruleName, fn, options) { + const opt = options || {}; + this.__rules__.push({ + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [], + }); + this.__cache__ = null; + }; + /** + * Ruler.enable(list [, ignoreInvalid]) -> Array + * - list (String|Array): list of rule names to enable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable rules with given names. If any rule name not found - throw Error. + * Errors can be disabled by second param. + * + * Returns list of found rule names (if no exception happened). + * + * See also [[Ruler.disable]], [[Ruler.enableOnly]]. + **/ + Ruler.prototype.enable = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + const result = []; + + // Search by name and enable + list.forEach(function (name) { + const idx = this.__find__(name); + if (idx < 0) { + if (ignoreInvalid) { + return; + } + throw new Error("Rules manager: invalid rule name " + name); + } + this.__rules__[idx].enabled = true; + result.push(name); + }, this); + this.__cache__ = null; + return result; + }; -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -var matchbrackets = { - exports: {} -}; -var hasRequiredMatchbrackets; -function requireMatchbrackets() { - if (hasRequiredMatchbrackets) return matchbrackets.exports; - hasRequiredMatchbrackets = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); - var Pos = CodeMirror.Pos; - var matching = { - "(": ")>", - ")": "(<", - "[": "]>", - "]": "[<", - "{": "}>", - "}": "{<", - "<": ">>", - ">": "<<" - }; - function bracketRegex(config) { - return config && config.bracketRegex || /[(){}[\]]/; - } - function findMatchingBracket(cm, where, config) { - var line = cm.getLineHandle(where.line), - pos = where.ch - 1; - var afterCursor = config && config.afterCursor; - if (afterCursor == null) afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className); - var re = bracketRegex(config); - var match = !afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)] || re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (config && config.strict && dir > 0 != (pos == where.ch)) return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config); - if (found == null) return null; - return { - from: Pos(where.line, pos), - to: found && found.pos, - match: found && found.ch == match.charAt(0), - forward: dir > 0 + /** + * Ruler.enableOnly(list [, ignoreInvalid]) + * - list (String|Array): list of rule names to enable (whitelist). + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable rules with given names, and disable everything else. If any rule name + * not found - throw Error. Errors can be disabled by second param. + * + * See also [[Ruler.disable]], [[Ruler.enable]]. + **/ + Ruler.prototype.enableOnly = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + this.__rules__.forEach(function (rule) { + rule.enabled = false; + }); + this.enable(list, ignoreInvalid); }; - } - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = config && config.maxScanLineLength || 1e4; - var maxScanLines = config && config.maxScanLines || 1e3; - var stack = []; - var re = bracketRegex(config); - var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, - end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if (re.test(ch) && (style === void 0 || (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) { - var match = matching[ch]; - if (match && match.charAt(1) == ">" == dir > 0) stack.push(ch);else if (!stack.length) return { - pos: Pos(lineNo, pos), - ch - };else stack.pop(); - } - } - } - return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; - } - function matchBrackets(cm, autoclear, config) { - var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1e3, - highlightNonMatching = config && config.highlightNonMatching; - var marks = [], - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); - if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) { - var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), { - className: style - })); - if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), { - className: style - })); + + /** + * Ruler.disable(list [, ignoreInvalid]) -> Array + * - list (String|Array): list of rule names to disable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Disable rules with given names. If any rule name not found - throw Error. + * Errors can be disabled by second param. + * + * Returns list of found rule names (if no exception happened). + * + * See also [[Ruler.enable]], [[Ruler.enableOnly]]. + **/ + Ruler.prototype.disable = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + const result = []; + + // Search by name and disable + list.forEach(function (name) { + const idx = this.__find__(name); + if (idx < 0) { + if (ignoreInvalid) { + return; + } + throw new Error("Rules manager: invalid rule name " + name); + } + this.__rules__[idx].enabled = false; + result.push(name); + }, this); + this.__cache__ = null; + return result; + }; + + /** + * Ruler.getRules(chainName) -> Array + * + * Return array of active functions (rules) for given chain name. It analyzes + * rules configuration, compiles caches if not exists and returns result. + * + * Default chain name is `''` (empty string). It can't be skipped. That's + * done intentionally, to keep signature monomorphic for high speed. + **/ + Ruler.prototype.getRules = function (chainName) { + if (this.__cache__ === null) { + this.__compile__(); } + + // Chain can be empty, if rules disabled. But we still have to return Array. + return this.__cache__[chainName] || []; + }; + + // Token class + + /** + * class Token + **/ + + /** + * new Token(type, tag, nesting) + * + * Create new token and fill passed properties. + **/ + function Token(type, tag, nesting) { + /** + * Token#type -> String + * + * Type of the token (string, e.g. "paragraph_open") + **/ + this.type = type; + + /** + * Token#tag -> String + * + * html tag name, e.g. "p" + **/ + this.tag = tag; + + /** + * Token#attrs -> Array + * + * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` + **/ + this.attrs = null; + + /** + * Token#map -> Array + * + * Source map info. Format: `[ line_begin, line_end ]` + **/ + this.map = null; + + /** + * Token#nesting -> Number + * + * Level change (number in {-1, 0, 1} set), where: + * + * - `1` means the tag is opening + * - `0` means the tag is self-closing + * - `-1` means the tag is closing + **/ + this.nesting = nesting; + + /** + * Token#level -> Number + * + * nesting level, the same as `state.level` + **/ + this.level = 0; + + /** + * Token#children -> Array + * + * An array of child nodes (inline and img tokens) + **/ + this.children = null; + + /** + * Token#content -> String + * + * In a case of self-closing tag (code, html, fence, etc.), + * it has contents of this tag. + **/ + this.content = ""; + + /** + * Token#markup -> String + * + * '*' or '_' for emphasis, fence string for fence, etc. + **/ + this.markup = ""; + + /** + * Token#info -> String + * + * Additional information: + * + * - Info string for "fence" tokens + * - The value "auto" for autolink "link_open" and "link_close" tokens + * - The string value of the item marker for ordered-list "list_item_open" tokens + **/ + this.info = ""; + + /** + * Token#meta -> Object + * + * A place for plugins to store an arbitrary data + **/ + this.meta = null; + + /** + * Token#block -> Boolean + * + * True for block-level tokens, false for inline tokens. + * Used in renderer to calculate line breaks + **/ + this.block = false; + + /** + * Token#hidden -> Boolean + * + * If it's true, ignore this element when rendering. Used for tight lists + * to hide paragraphs. + **/ + this.hidden = false; } - if (marks.length) { - if (ie_lt8 && cm.state.focused) cm.focus(); - var clear = function () { - cm.operation(function () { - for (var i2 = 0; i2 < marks.length; i2++) marks[i2].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800);else return clear; - } - } - function doMatchBrackets(cm) { - cm.operation(function () { - if (cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; + + /** + * Token.attrIndex(name) -> Number + * + * Search attribute index by name. + **/ + Token.prototype.attrIndex = function attrIndex(name) { + if (!this.attrs) { + return -1; + } + const attrs = this.attrs; + for (let i = 0, len = attrs.length; i < len; i++) { + if (attrs[i][0] === name) { + return i; + } } - cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); - }); - } - function clearHighlighted(cm) { - if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - } - CodeMirror.defineOption("matchBrackets", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.off("cursorActivity", doMatchBrackets); - cm.off("focus", doMatchBrackets); - cm.off("blur", clearHighlighted); - clearHighlighted(cm); - } - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - cm.on("focus", doMatchBrackets); - cm.on("blur", clearHighlighted); - } - }); - CodeMirror.defineExtension("matchBrackets", function () { - matchBrackets(this, true); - }); - CodeMirror.defineExtension("findMatchingBracket", function (pos, config, oldConfig) { - if (oldConfig || typeof config == "boolean") { - if (!oldConfig) { - config = config ? { - strict: true - } : null; + return -1; + }; + + /** + * Token.attrPush(attrData) + * + * Add `[ name, value ]` attribute to list. Init attrs if necessary + **/ + Token.prototype.attrPush = function attrPush(attrData) { + if (this.attrs) { + this.attrs.push(attrData); } else { - oldConfig.strict = config; - config = oldConfig; + this.attrs = [attrData]; } - } - return findMatchingBracket(this, pos, config); - }); - CodeMirror.defineExtension("scanForBracket", function (pos, dir, style, config) { - return scanForBracket(this, pos, dir, style, config); - }); - }); - })(); - return matchbrackets.exports; -} -exports.requireMatchbrackets = requireMatchbrackets; + }; -/***/ }), + /** + * Token.attrSet(name, value) + * + * Set `name` attribute to `value`. Override old value if exists. + **/ + Token.prototype.attrSet = function attrSet(name, value) { + const idx = this.attrIndex(name); + const attrData = [name, value]; + if (idx < 0) { + this.attrPush(attrData); + } else { + this.attrs[idx] = attrData; + } + }; -/***/ "../../graphiql-react/dist/mode-indent.cjs.js": -/*!****************************************************!*\ - !*** ../../graphiql-react/dist/mode-indent.cjs.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /** + * Token.attrGet(name) + * + * Get the value of attribute `name`, or null if it does not exist. + **/ + Token.prototype.attrGet = function attrGet(name) { + const idx = this.attrIndex(name); + let value = null; + if (idx >= 0) { + value = this.attrs[idx][1]; + } + return value; + }; + /** + * Token.attrJoin(name, value) + * + * Join value to existing attribute via space. Or create new attribute if not + * exists. Useful to operate with token classes. + **/ + Token.prototype.attrJoin = function attrJoin(name, value) { + const idx = this.attrIndex(name); + if (idx < 0) { + this.attrPush([name, value]); + } else { + this.attrs[idx][1] = this.attrs[idx][1] + " " + value; + } + }; + // Core state object + // -function indent(state, textAfter) { - var _a, _b; - const { - levels, - indentLevel - } = state; - const level = !levels || levels.length === 0 ? indentLevel : levels.at(-1) - (((_a = this.electricInput) === null || _a === void 0 ? void 0 : _a.test(textAfter)) ? 1 : 0); - return (level || 0) * (((_b = this.config) === null || _b === void 0 ? void 0 : _b.indentUnit) || 0); -} -exports.indent = indent; + function StateCore(src, md, env) { + this.src = src; + this.env = env; + this.tokens = []; + this.inlineMode = false; + this.md = md; // link to parser instance + } -/***/ }), + // re-export Token class to use in core rules + StateCore.prototype.Token = Token; -/***/ "../../graphiql-react/dist/mode.cjs.js": -/*!*********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs.js ***! - \*********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + // Normalize input string + // https://spec.commonmark.org/0.29/#line-ending + const NEWLINES_RE = /\r\n?|\n/g; + const NULL_RE = /\0/g; + function normalize(state) { + let str; + // Normalize newlines + str = state.src.replace(NEWLINES_RE, "\n"); -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); -const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); -const graphqlModeFactory = config => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: stream => stream.eatWhile(graphqlLanguageService.isIgnored), - lexRules: graphqlLanguageService.LexRules, - parseRules: graphqlLanguageService.ParseRules, - editorConfig: { - tabSize: config.tabSize - } - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[})\]]/, - fold: "brace", - lineComment: "#", - closeBrackets: { - pairs: '()[]{}""', - explode: "()[]{}" - } - }; -}; -codemirror.CodeMirror.defineMode("graphql", graphqlModeFactory); + // Replace NULL characters + str = str.replace(NULL_RE, "\uFFFD"); + state.src = str; + } + function block(state) { + let token; + if (state.inlineMode) { + token = new state.Token("inline", "", 0); + token.content = state.src; + token.map = [0, 1]; + token.children = []; + state.tokens.push(token); + } else { + state.md.block.parse(state.src, state.md, state.env, state.tokens); + } + } + function inline(state) { + const tokens = state.tokens; + + // Parse inlines + for (let i = 0, l = tokens.length; i < l; i++) { + const tok = tokens[i]; + if (tok.type === "inline") { + state.md.inline.parse( + tok.content, + state.md, + state.env, + tok.children + ); + } + } + } -/***/ }), + // Replace link-like texts with link nodes. + // + // Currently restricted by `md.validateLink()` to http/https/ftp + // -/***/ "../../graphiql-react/dist/mode.cjs2.js": -/*!**********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs2.js ***! - \**********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + function isLinkOpen$1(str) { + return /^\s]/i.test(str); + } + function isLinkClose$1(str) { + return /^<\/a\s*>/i.test(str); + } + function linkify$1(state) { + const blockTokens = state.tokens; + if (!state.md.options.linkify) { + return; + } + for (let j = 0, l = blockTokens.length; j < l; j++) { + if ( + blockTokens[j].type !== "inline" || + !state.md.linkify.pretest(blockTokens[j].content) + ) { + continue; + } + let tokens = blockTokens[j].children; + let htmlLinkLevel = 0; + + // We scan from the end, to keep position when new tags added. + // Use reversed logic in links start/end match + for (let i = tokens.length - 1; i >= 0; i--) { + const currentToken = tokens[i]; + + // Skip content of markdown links + if (currentToken.type === "link_close") { + i--; + while ( + tokens[i].level !== currentToken.level && + tokens[i].type !== "link_open" + ) { + i--; + } + continue; + } + // Skip content of html tag links + if (currentToken.type === "html_inline") { + if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) { + htmlLinkLevel--; + } + if (isLinkClose$1(currentToken.content)) { + htmlLinkLevel++; + } + } + if (htmlLinkLevel > 0) { + continue; + } + if ( + currentToken.type === "text" && + state.md.linkify.test(currentToken.content) + ) { + const text = currentToken.content; + let links = state.md.linkify.match(text); + + // Now split string to nodes + const nodes = []; + let level = currentToken.level; + let lastPos = 0; + + // forbid escape sequence at the start of the string, + // this avoids http\://example.com/ from being linkified as + // http://example.com/ + if ( + links.length > 0 && + links[0].index === 0 && + i > 0 && + tokens[i - 1].type === "text_special" + ) { + links = links.slice(1); + } + for (let ln = 0; ln < links.length; ln++) { + const url = links[ln].url; + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) { + continue; + } + let urlText = links[ln].text; + + // Linkifier might send raw hostnames like "example.com", where url + // starts with domain name. So we prepend http:// in those cases, + // and remove it afterwards. + // + if (!links[ln].schema) { + urlText = state.md + .normalizeLinkText("http://" + urlText) + .replace(/^http:\/\//, ""); + } else if ( + links[ln].schema === "mailto:" && + !/^mailto:/i.test(urlText) + ) { + urlText = state.md + .normalizeLinkText("mailto:" + urlText) + .replace(/^mailto:/, ""); + } else { + urlText = state.md.normalizeLinkText(urlText); + } + const pos = links[ln].index; + if (pos > lastPos) { + const token = new state.Token("text", "", 0); + token.content = text.slice(lastPos, pos); + token.level = level; + nodes.push(token); + } + const token_o = new state.Token("link_open", "a", 1); + token_o.attrs = [["href", fullUrl]]; + token_o.level = level++; + token_o.markup = "linkify"; + token_o.info = "auto"; + nodes.push(token_o); + const token_t = new state.Token("text", "", 0); + token_t.content = urlText; + token_t.level = level; + nodes.push(token_t); + const token_c = new state.Token("link_close", "a", -1); + token_c.level = --level; + token_c.markup = "linkify"; + token_c.info = "auto"; + nodes.push(token_c); + lastPos = links[ln].lastIndex; + } + if (lastPos < text.length) { + const token = new state.Token("text", "", 0); + token.content = text.slice(lastPos); + token.level = level; + nodes.push(token); + } + // replace current node + blockTokens[j].children = tokens = arrayReplaceAt( + tokens, + i, + nodes + ); + } + } + } + } -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); -const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); -codemirror.CodeMirror.defineMode("graphql-variables", config => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: stream => stream.eatSpace(), - lexRules: LexRules, - parseRules: ParseRules, - editorConfig: { - tabSize: config.tabSize - } - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[}\]]/, - fold: "brace", - closeBrackets: { - pairs: '[]{}""', - explode: "[]{}" - } - }; -}); -const LexRules = { - Punctuation: /^\[|]|\{|\}|:|,/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, - Keyword: /^true|false|null/ -}; -const ParseRules = { - Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Variable", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], - Variable: [namedKey("variable"), graphqlLanguageService.p(":"), "Value"], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; - } - return null; - case "Keyword": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - case "null": - return "NullValue"; - } - return null; - } - }, - NumberValue: [graphqlLanguageService.t("Number", "number")], - StringValue: [graphqlLanguageService.t("String", "string")], - BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], - NullValue: [graphqlLanguageService.t("Keyword", "keyword")], - ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("]")], - ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], - ObjectField: [namedKey("attribute"), graphqlLanguageService.p(":"), "Value"] -}; -function namedKey(style) { - return { - style, - match: token => token.kind === "String", - update(state, token) { - state.name = token.value.slice(1, -1); - } - }; -} + // Simple typographic replacements + // + // (c) (C) → © + // (tm) (TM) → ™ + // (r) (R) → ® + // +- → ± + // ... → … (also ?.... → ?.., !.... → !..) + // ???????? → ???, !!!!! → !!!, `,,` → `,` + // -- → –, --- → — + // -/***/ }), + // TODO: + // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ + // - multiplications 2 x 4 -> 2 × 4 -/***/ "../../graphiql-react/dist/mode.cjs3.js": -/*!**********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs3.js ***! - \**********************************************/ -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; + // Workaround for phantomjs - need regex without /g flag, + // or root check will fail every second time + const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; + const SCOPED_ABBR_RE = /\((c|tm|r)\)/gi; + const SCOPED_ABBR = { + c: "©", + r: "®", + tm: "™", + }; + function replaceFn(match, name) { + return SCOPED_ABBR[name.toLowerCase()]; + } + function replace_scoped(inlineTokens) { + let inside_autolink = 0; + for (let i = inlineTokens.length - 1; i >= 0; i--) { + const token = inlineTokens[i]; + if (token.type === "text" && !inside_autolink) { + token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); + } + if (token.type === "link_open" && token.info === "auto") { + inside_autolink--; + } + if (token.type === "link_close" && token.info === "auto") { + inside_autolink++; + } + } + } + function replace_rare(inlineTokens) { + let inside_autolink = 0; + for (let i = inlineTokens.length - 1; i >= 0; i--) { + const token = inlineTokens[i]; + if (token.type === "text" && !inside_autolink) { + if (RARE_RE.test(token.content)) { + token.content = token.content + .replace(/\+-/g, "±") + // .., ..., ....... -> … + // but ?..... & !..... -> ?.. & !.. + .replace(/\.{2,}/g, "…") + .replace(/([?!])…/g, "$1..") + .replace(/([?!]){4,}/g, "$1$1$1") + .replace(/,{2,}/g, ",") + // em-dash + .replace(/(^|[^-])---(?=[^-]|$)/gm, "$1\u2014") + // en-dash + .replace(/(^|\s)--(?=\s|$)/gm, "$1\u2013") + .replace(/(^|[^-\s])--(?=[^-\s]|$)/gm, "$1\u2013"); + } + } + if (token.type === "link_open" && token.info === "auto") { + inside_autolink--; + } + if (token.type === "link_close" && token.info === "auto") { + inside_autolink++; + } + } + } + function replace(state) { + let blkIdx; + if (!state.md.options.typographer) { + return; + } + for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { + if (state.tokens[blkIdx].type !== "inline") { + continue; + } + if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { + replace_scoped(state.tokens[blkIdx].children); + } + if (RARE_RE.test(state.tokens[blkIdx].content)) { + replace_rare(state.tokens[blkIdx].children); + } + } + } + // Convert straight quotation marks to typographic ones + // -const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); -const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); -const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); -codemirror.CodeMirror.defineMode("graphql-results", config => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: stream => stream.eatSpace(), - lexRules: LexRules, - parseRules: ParseRules, - editorConfig: { - tabSize: config.tabSize - } - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[}\]]/, - fold: "brace", - closeBrackets: { - pairs: '[]{}""', - explode: "[]{}" - } - }; -}); -const LexRules = { - Punctuation: /^\[|]|\{|\}|:|,/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, - Keyword: /^true|false|null/ -}; -const ParseRules = { - Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Entry", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], - Entry: [graphqlLanguageService.t("String", "def"), graphqlLanguageService.p(":"), "Value"], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; - } - return null; - case "Keyword": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - case "null": - return "NullValue"; - } - return null; - } - }, - NumberValue: [graphqlLanguageService.t("Number", "number")], - StringValue: [graphqlLanguageService.t("String", "string")], - BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], - NullValue: [graphqlLanguageService.t("Keyword", "keyword")], - ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.p(",")), graphqlLanguageService.p("]")], - ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], - ObjectField: [graphqlLanguageService.t("String", "property"), graphqlLanguageService.p(":"), "Value"] -}; + const QUOTE_TEST_RE = /['"]/; + const QUOTE_RE = /['"]/g; + const APOSTROPHE = "\u2019"; /* ’ */ + + function replaceAt(str, index, ch) { + return str.slice(0, index) + ch + str.slice(index + 1); + } + function process_inlines(tokens, state) { + let j; + const stack = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const thisLevel = tokens[i].level; + for (j = stack.length - 1; j >= 0; j--) { + if (stack[j].level <= thisLevel) { + break; + } + } + stack.length = j + 1; + if (token.type !== "text") { + continue; + } + let text = token.content; + let pos = 0; + let max = text.length; + + /* eslint no-labels:0,block-scoped-var:0 */ + OUTER: while (pos < max) { + QUOTE_RE.lastIndex = pos; + const t = QUOTE_RE.exec(text); + if (!t) { + break; + } + let canOpen = true; + let canClose = true; + pos = t.index + 1; + const isSingle = t[0] === "'"; + + // Find previous character, + // default to space if it's the beginning of the line + // + let lastChar = 0x20; + if (t.index - 1 >= 0) { + lastChar = text.charCodeAt(t.index - 1); + } else { + for (j = i - 1; j >= 0; j--) { + if ( + tokens[j].type === "softbreak" || + tokens[j].type === "hardbreak" + ) + break; // lastChar defaults to 0x20 + if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + + lastChar = tokens[j].content.charCodeAt( + tokens[j].content.length - 1 + ); + break; + } + } + + // Find next character, + // default to space if it's the end of the line + // + let nextChar = 0x20; + if (pos < max) { + nextChar = text.charCodeAt(pos); + } else { + for (j = i + 1; j < tokens.length; j++) { + if ( + tokens[j].type === "softbreak" || + tokens[j].type === "hardbreak" + ) + break; // nextChar defaults to 0x20 + if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + + nextChar = tokens[j].content.charCodeAt(0); + break; + } + } + const isLastPunctChar = + isMdAsciiPunct(lastChar) || + isPunctChar(String.fromCharCode(lastChar)); + const isNextPunctChar = + isMdAsciiPunct(nextChar) || + isPunctChar(String.fromCharCode(nextChar)); + const isLastWhitespace = isWhitespace(lastChar); + const isNextWhitespace = isWhitespace(nextChar); + if (isNextWhitespace) { + canOpen = false; + } else if (isNextPunctChar) { + if (!(isLastWhitespace || isLastPunctChar)) { + canOpen = false; + } + } + if (isLastWhitespace) { + canClose = false; + } else if (isLastPunctChar) { + if (!(isNextWhitespace || isNextPunctChar)) { + canClose = false; + } + } + if (nextChar === 0x22 /* " */ && t[0] === '"') { + if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { + // special case: 1"" - count first quote as an inch + canClose = canOpen = false; + } + } + if (canOpen && canClose) { + // Replace quotes in the middle of punctuation sequence, but not + // in the middle of the words, i.e.: + // + // 1. foo " bar " baz - not replaced + // 2. foo-"-bar-"-baz - replaced + // 3. foo"bar"baz - not replaced + // + canOpen = isLastPunctChar; + canClose = isNextPunctChar; + } + if (!canOpen && !canClose) { + // middle of word + if (isSingle) { + token.content = replaceAt(token.content, t.index, APOSTROPHE); + } + continue; + } + if (canClose) { + // this could be a closing quote, rewind the stack to get a match + for (j = stack.length - 1; j >= 0; j--) { + let item = stack[j]; + if (stack[j].level < thisLevel) { + break; + } + if ( + item.single === isSingle && + stack[j].level === thisLevel + ) { + item = stack[j]; + let openQuote; + let closeQuote; + if (isSingle) { + openQuote = state.md.options.quotes[2]; + closeQuote = state.md.options.quotes[3]; + } else { + openQuote = state.md.options.quotes[0]; + closeQuote = state.md.options.quotes[1]; + } + + // replace token.content *before* tokens[item.token].content, + // because, if they are pointing at the same token, replaceAt + // could mess up indices when quote length != 1 + token.content = replaceAt( + token.content, + t.index, + closeQuote + ); + tokens[item.token].content = replaceAt( + tokens[item.token].content, + item.pos, + openQuote + ); + pos += closeQuote.length - 1; + if (item.token === i) { + pos += openQuote.length - 1; + } + text = token.content; + max = text.length; + stack.length = j; + continue OUTER; + } + } + } + if (canOpen) { + stack.push({ + token: i, + pos: t.index, + single: isSingle, + level: thisLevel, + }); + } else if (canClose && isSingle) { + token.content = replaceAt(token.content, t.index, APOSTROPHE); + } + } + } + } + function smartquotes(state) { + /* eslint max-depth:0 */ + if (!state.md.options.typographer) { + return; + } + for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { + if ( + state.tokens[blkIdx].type !== "inline" || + !QUOTE_TEST_RE.test(state.tokens[blkIdx].content) + ) { + continue; + } + process_inlines(state.tokens[blkIdx].children, state); + } + } + + // Join raw text tokens with the rest of the text + // + // This is set as a separate rule to provide an opportunity for plugins + // to run text replacements after text join, but before escape join. + // + // For example, `\:)` shouldn't be replaced with an emoji. + // + + function text_join(state) { + let curr, last; + const blockTokens = state.tokens; + const l = blockTokens.length; + for (let j = 0; j < l; j++) { + if (blockTokens[j].type !== "inline") continue; + const tokens = blockTokens[j].children; + const max = tokens.length; + for (curr = 0; curr < max; curr++) { + if (tokens[curr].type === "text_special") { + tokens[curr].type = "text"; + } + } + for (curr = last = 0; curr < max; curr++) { + if ( + tokens[curr].type === "text" && + curr + 1 < max && + tokens[curr + 1].type === "text" + ) { + // collapse two adjacent text nodes + tokens[curr + 1].content = + tokens[curr].content + tokens[curr + 1].content; + } else { + if (curr !== last) { + tokens[last] = tokens[curr]; + } + last++; + } + } + if (curr !== last) { + tokens.length = last; + } + } + } -/***/ }), + /** internal + * class Core + * + * Top-level rules executor. Glues block/inline parsers and does intermediate + * transformations. + **/ + + const _rules$2 = [ + ["normalize", normalize], + ["block", block], + ["inline", inline], + ["linkify", linkify$1], + ["replacements", replace], + ["smartquotes", smartquotes], + // `text_join` finds `text_special` tokens (for escape sequences) + // and joins them with the rest of the text + ["text_join", text_join], + ]; -/***/ "../../graphiql-react/dist/search.cjs.js": -/*!***********************************************!*\ - !*** ../../graphiql-react/dist/search.cjs.js ***! - \***********************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); -const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + /** + * new Core() + **/ + function Core() { + /** + * Core#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of core rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules$2.length; i++) { + this.ruler.push(_rules$2[i][0], _rules$2[i][1]); } } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var search$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), dialog.dialogExports); - })(function (CodeMirror) { - CodeMirror.defineOption("search", { - bottom: false - }); - function searchOverlay(query, caseInsensitive) { - if (typeof query == "string") query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");else if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); - return { - token: function (stream) { - query.lastIndex = stream.pos; - var match = query.exec(stream.string); - if (match && match.index == stream.pos) { - stream.pos += match[0].length || 1; - return "searching"; - } else if (match) { - stream.pos = match.index; - } else { - stream.skipToEnd(); + + /** + * Core.process(state) + * + * Executes core chain rules. + **/ + Core.prototype.process = function (state) { + const rules = this.ruler.getRules(""); + for (let i = 0, l = rules.length; i < l; i++) { + rules[i](state); } - } - }; - } - function SearchState() { - this.posFrom = this.posTo = this.lastQuery = this.query = null; - this.overlay = null; - } - function getSearchState(cm) { - return cm.state.search || (cm.state.search = new SearchState()); - } - function queryCaseInsensitive(query) { - return typeof query == "string" && query == query.toLowerCase(); - } - function getSearchCursor(cm, query, pos) { - return cm.getSearchCursor(query, pos, { - caseFold: queryCaseInsensitive(query), - multiline: true - }); - } - function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { - cm.openDialog(text, onEnter, { - value: deflt, - selectValueOnOpen: true, - closeOnEnter: false, - onClose: function () { - clearSearch(cm); - }, - onKeyDown, - bottom: cm.options.search.bottom - }); - } - function dialog2(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom - });else f(prompt(shortText, deflt)); - } - function confirmDialog(cm, text, shortText, fs) { - if (cm.openConfirm) cm.openConfirm(text, fs);else if (confirm(shortText)) fs[0](); - } - function parseString(string) { - return string.replace(/\\([nrt\\])/g, function (match, ch) { - if (ch == "n") return "\n"; - if (ch == "r") return "\r"; - if (ch == "t") return " "; - if (ch == "\\") return "\\"; - return match; - }); - } - function parseQuery(query) { - var isRE = query.match(/^\/(.*)\/([a-z]*)$/); - if (isRE) { - try { - query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); - } catch (e) {} - } else { - query = parseString(query); - } - if (typeof query == "string" ? query == "" : query.test("")) query = /x^/; - return query; - } - function startSearch(cm, state, query) { - state.queryText = query; - state.query = parseQuery(query); - cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); - state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); - cm.addOverlay(state.overlay); - if (cm.showMatchesOnScrollbar) { - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; - } - state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); - } - } - function doSearch(cm, rev, persistent, immediate) { - var state = getSearchState(cm); - if (state.query) return findNext(cm, rev); - var q = cm.getSelection() || state.lastQuery; - if (q instanceof RegExp && q.source == "x^") q = null; - if (persistent && cm.openDialog) { - var hiding = null; - var searchNext = function (query, event) { - CodeMirror.e_stop(event); - if (!query) return; - if (query != state.queryText) { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - } - if (hiding) hiding.style.opacity = 1; - findNext(cm, event.shiftKey, function (_, to) { - var dialog3; - if (to.line < 3 && document.querySelector && (dialog3 = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && dialog3.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) (hiding = dialog3).style.opacity = 0.4; - }); }; - persistentDialog(cm, getQueryDialog(cm), q, searchNext, function (event, query) { - var keyName = CodeMirror.keyName(event); - var extra = cm.getOption("extraKeys"), - cmd = extra && extra[keyName] || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; - if (cmd == "findNext" || cmd == "findPrev" || cmd == "findPersistentNext" || cmd == "findPersistentPrev") { - CodeMirror.e_stop(event); - startSearch(cm, getSearchState(cm), query); - cm.execCommand(cmd); - } else if (cmd == "find" || cmd == "findPersistent") { - CodeMirror.e_stop(event); - searchNext(query, event); - } - }); - if (immediate && q) { - startSearch(cm, state, q); - findNext(cm, rev); - } - } else { - dialog2(cm, getQueryDialog(cm), "Search for:", q, function (query) { - if (query && !state.query) cm.operation(function () { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - findNext(cm, rev); - }); - }); - } - } - function findNext(cm, rev, callback) { - cm.operation(function () { - var state = getSearchState(cm); - var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); - if (!cursor.find(rev)) { - cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); - if (!cursor.find(rev)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to() - }, 20); - state.posFrom = cursor.from(); - state.posTo = cursor.to(); - if (callback) callback(cursor.from(), cursor.to()); - }); - } - function clearSearch(cm) { - cm.operation(function () { - var state = getSearchState(cm); - state.lastQuery = state.query; - if (!state.query) return; - state.query = state.queryText = null; - cm.removeOverlay(state.overlay); - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; - } - }); - } - function el(tag, attrs) { - var element = tag ? document.createElement(tag) : document.createDocumentFragment(); - for (var key in attrs) { - element[key] = attrs[key]; - } - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - element.appendChild(typeof child == "string" ? document.createTextNode(child) : child); - } - return element; - } - function getQueryDialog(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("Search:")), " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - }), " ", el("span", { - style: "color: #888", - className: "CodeMirror-search-hint" - }, cm.phrase("(Use /re/ syntax for regexp search)"))); - } - function getReplaceQueryDialog(cm) { - return el("", null, " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - }), " ", el("span", { - style: "color: #888", - className: "CodeMirror-search-hint" - }, cm.phrase("(Use /re/ syntax for regexp search)"))); - } - function getReplacementQueryDialog(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("With:")), " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - })); - } - function getDoReplaceConfirm(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("Replace?")), " ", el("button", {}, cm.phrase("Yes")), " ", el("button", {}, cm.phrase("No")), " ", el("button", {}, cm.phrase("All")), " ", el("button", {}, cm.phrase("Stop"))); - } - function replaceAll(cm, query, text) { - cm.operation(function () { - for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { - if (typeof query != "string") { - var match = cm.getRange(cursor.from(), cursor.to()).match(query); - cursor.replace(text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - })); - } else cursor.replace(text); - } - }); - } - function replace(cm, all) { - if (cm.getOption("readOnly")) return; - var query = cm.getSelection() || getSearchState(cm).lastQuery; - var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:"); - var fragment = el("", null, el("span", { - className: "CodeMirror-search-label" - }, dialogText), getReplaceQueryDialog(cm)); - dialog2(cm, fragment, dialogText, query, function (query2) { - if (!query2) return; - query2 = parseQuery(query2); - dialog2(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function (text) { - text = parseString(text); - if (all) { - replaceAll(cm, query2, text); - } else { - clearSearch(cm); - var cursor = getSearchCursor(cm, query2, cm.getCursor("from")); - var advance = function () { - var start = cursor.from(), - match; - if (!(match = cursor.findNext())) { - cursor = getSearchCursor(cm, query2); - if (!(match = cursor.findNext()) || start && cursor.from().line == start.line && cursor.from().ch == start.ch) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to() - }); - confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"), [function () { - doReplace(match); - }, advance, function () { - replaceAll(cm, query2, text); - }]); - }; - var doReplace = function (match) { - cursor.replace(typeof query2 == "string" ? text : text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - })); - advance(); - }; - advance(); - } - }); - }); - } - CodeMirror.commands.find = function (cm) { - clearSearch(cm); - doSearch(cm); - }; - CodeMirror.commands.findPersistent = function (cm) { - clearSearch(cm); - doSearch(cm, false, true); - }; - CodeMirror.commands.findPersistentNext = function (cm) { - doSearch(cm, false, true, true); - }; - CodeMirror.commands.findPersistentPrev = function (cm) { - doSearch(cm, true, true, true); - }; - CodeMirror.commands.findNext = doSearch; - CodeMirror.commands.findPrev = function (cm) { - doSearch(cm, true); - }; - CodeMirror.commands.clearSearch = clearSearch; - CodeMirror.commands.replace = replace; - CodeMirror.commands.replaceAll = function (cm) { - replace(cm, true); - }; - }); -})(); -var searchExports = search$2.exports; -const search = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchExports); -const search$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: search -}, [searchExports]); -exports.search = search$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/searchcursor.cjs.js": -/*!*****************************************************!*\ - !*** ../../graphiql-react/dist/searchcursor.cjs.js ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -const searchcursor$2 = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var searchcursorExports = searchcursor$2.requireSearchcursor(); -const searchcursor = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchcursorExports); -const searchcursor$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: searchcursor -}, [searchcursorExports]); -exports.searchcursor = searchcursor$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/searchcursor.cjs2.js": -/*!******************************************************!*\ - !*** ../../graphiql-react/dist/searchcursor.cjs2.js ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + Core.prototype.State = StateCore; + // Parser state class + function StateBlock(src, md, env, tokens) { + this.src = src; -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -var searchcursor = { - exports: {} -}; -var hasRequiredSearchcursor; -function requireSearchcursor() { - if (hasRequiredSearchcursor) return searchcursor.exports; - hasRequiredSearchcursor = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var Pos = CodeMirror.Pos; - function regexpFlags(regexp) { - var flags = regexp.flags; - return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : ""); - } - function ensureFlags(regexp, flags) { - var current = regexpFlags(regexp), - target = current; - for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) target += flags.charAt(i); - return current == target ? regexp : new RegExp(regexp.source, target); - } - function maybeMultiline(regexp) { - return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); - } - function searchRegexpForward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { - regexp.lastIndex = ch; - var string = doc.getLine(line), - match = regexp.exec(string); - if (match) return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match - }; - } - } - function searchRegexpForwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunk = 1; - for (var line = start.line, last = doc.lastLine(); line <= last;) { - for (var i = 0; i < chunk; i++) { - if (line > last) break; - var curLine = doc.getLine(line++); - string = string == null ? curLine : string + "\n" + curLine; - } - chunk = chunk * 2; - regexp.lastIndex = start.ch; - var match = regexp.exec(string); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = start.line + before.length - 1, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match - }; + // link to parser instance + this.md = md; + this.env = env; + + // + // Internal state vartiables + // + + this.tokens = tokens; + this.bMarks = []; // line begin offsets for fast jumps + this.eMarks = []; // line end offsets for fast jumps + this.tShift = []; // offsets of the first non-space characters (tabs not expanded) + this.sCount = []; // indents for each line (tabs expanded) + + // An amount of virtual spaces (tabs expanded) between beginning + // of each line (bMarks) and real beginning of that line. + // + // It exists only as a hack because blockquotes override bMarks + // losing information in the process. + // + // It's used only when expanding tabs, you can think about it as + // an initial tab length, e.g. bsCount=21 applied to string `\t123` + // means first tab should be expanded to 4-21%4 === 3 spaces. + // + this.bsCount = []; + + // block parser variables + + // required block content indent (for example, if we are + // inside a list, it would be positioned after list marker) + this.blkIndent = 0; + this.line = 0; // line index in src + this.lineMax = 0; // lines count + this.tight = false; // loose/tight mode for lists + this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) + this.listIndent = -1; // indent of the current list block (-1 if there isn't any) + + // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' + // used in lists to determine if they interrupt a paragraph + this.parentType = "root"; + this.level = 0; + + // Create caches + // Generate markers. + const s = this.src; + for ( + let start = 0, + pos = 0, + indent = 0, + offset = 0, + len = s.length, + indent_found = false; + pos < len; + pos++ + ) { + const ch = s.charCodeAt(pos); + if (!indent_found) { + if (isSpace(ch)) { + indent++; + if (ch === 0x09) { + offset += 4 - (offset % 4); + } else { + offset++; + } + continue; + } else { + indent_found = true; + } + } + if (ch === 0x0a || pos === len - 1) { + if (ch !== 0x0a) { + pos++; + } + this.bMarks.push(start); + this.eMarks.push(pos); + this.tShift.push(indent); + this.sCount.push(offset); + this.bsCount.push(0); + indent_found = false; + indent = 0; + offset = 0; + start = pos + 1; + } } + + // Push fake entry to simplify cache bounds checks + this.bMarks.push(s.length); + this.eMarks.push(s.length); + this.tShift.push(0); + this.sCount.push(0); + this.bsCount.push(0); + this.lineMax = this.bMarks.length - 1; // don't count last fake line } - } - function lastMatchIn(string, regexp, endMargin) { - var match, - from = 0; - while (from <= string.length) { - regexp.lastIndex = from; - var newMatch = regexp.exec(string); - if (!newMatch) break; - var end = newMatch.index + newMatch[0].length; - if (end > string.length - endMargin) break; - if (!match || end > match.index + match[0].length) match = newMatch; - from = newMatch.index + 1; - } - return match; - } - function searchRegexpBackward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { - var string = doc.getLine(line); - var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch); - if (match) return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match - }; - } - } - function searchRegexpBackwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunkSize = 1, - endMargin = doc.getLine(start.line).length - start.ch; - for (var line = start.line, first = doc.firstLine(); line >= first;) { - for (var i = 0; i < chunkSize && line >= first; i++) { - var curLine = doc.getLine(line--); - string = string == null ? curLine : curLine + "\n" + string; - } - chunkSize *= 2; - var match = lastMatchIn(string, regexp, endMargin); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = line + before.length, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match - }; + + // Push new token to "stream". + // + StateBlock.prototype.push = function (type, tag, nesting) { + const token = new Token(type, tag, nesting); + token.block = true; + if (nesting < 0) this.level--; // closing tag + token.level = this.level; + if (nesting > 0) this.level++; // opening tag + + this.tokens.push(token); + return token; + }; + StateBlock.prototype.isEmpty = function isEmpty(line) { + return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; + }; + StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { + for (let max = this.lineMax; from < max; from++) { + if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { + break; + } } - } - } - var doFold, noFold; - if (String.prototype.normalize) { - doFold = function (str) { - return str.normalize("NFD").toLowerCase(); + return from; }; - noFold = function (str) { - return str.normalize("NFD"); + + // Skip spaces from given position. + StateBlock.prototype.skipSpaces = function skipSpaces(pos) { + for (let max = this.src.length; pos < max; pos++) { + const ch = this.src.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } + } + return pos; }; - } else { - doFold = function (str) { - return str.toLowerCase(); + + // Skip spaces from given position in reverse. + StateBlock.prototype.skipSpacesBack = function skipSpacesBack( + pos, + min + ) { + if (pos <= min) { + return pos; + } + while (pos > min) { + if (!isSpace(this.src.charCodeAt(--pos))) { + return pos + 1; + } + } + return pos; }; - noFold = function (str) { - return str; + + // Skip char codes from given position + StateBlock.prototype.skipChars = function skipChars(pos, code) { + for (let max = this.src.length; pos < max; pos++) { + if (this.src.charCodeAt(pos) !== code) { + break; + } + } + return pos; }; - } - function adjustPos(orig, folded, pos, foldFunc) { - if (orig.length == folded.length) return pos; - for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { - if (min == max) return min; - var mid = min + max >> 1; - var len = foldFunc(orig.slice(0, mid)).length; - if (len == pos) return mid;else if (len > pos) max = mid;else min = mid + 1; - } - } - function searchStringForward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { - var orig = doc.getLine(line).slice(ch), - string = fold(orig); - if (lines.length == 1) { - var found = string.indexOf(lines[0]); - if (found == -1) continue search; - var start = adjustPos(orig, string, found, fold) + ch; - return { - from: Pos(line, adjustPos(orig, string, found, fold) + ch), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch) - }; - } else { - var cutFrom = string.length - lines[0].length; - if (string.slice(cutFrom) != lines[0]) continue search; - for (var i = 1; i < lines.length - 1; i++) if (fold(doc.getLine(line + i)) != lines[i]) continue search; - var end = doc.getLine(line + lines.length - 1), - endString = fold(end), - lastLine = lines[lines.length - 1]; - if (endString.slice(0, lastLine.length) != lastLine) continue search; - return { - from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), - to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold)) - }; + + // Skip char codes reverse from given position - 1 + StateBlock.prototype.skipCharsBack = function skipCharsBack( + pos, + code, + min + ) { + if (pos <= min) { + return pos; } - } - } - function searchStringBackward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { - var orig = doc.getLine(line); - if (ch > -1) orig = orig.slice(0, ch); - var string = fold(orig); - if (lines.length == 1) { - var found = string.lastIndexOf(lines[0]); - if (found == -1) continue search; - return { - from: Pos(line, adjustPos(orig, string, found, fold)), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold)) - }; - } else { - var lastLine = lines[lines.length - 1]; - if (string.slice(0, lastLine.length) != lastLine) continue search; - for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) if (fold(doc.getLine(start + i)) != lines[i]) continue search; - var top = doc.getLine(line + 1 - lines.length), - topString = fold(top); - if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search; - return { - from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), - to: Pos(line, adjustPos(orig, string, lastLine.length, fold)) - }; + while (pos > min) { + if (code !== this.src.charCodeAt(--pos)) { + return pos + 1; + } } - } - } - function SearchCursor(doc, query, pos, options) { - this.atOccurrence = false; - this.afterEmptyMatch = false; - this.doc = doc; - pos = pos ? doc.clipPos(pos) : Pos(0, 0); - this.pos = { - from: pos, - to: pos + return pos; }; - var caseFold; - if (typeof options == "object") { - caseFold = options.caseFold; - } else { - caseFold = options; - options = null; - } - if (typeof query == "string") { - if (caseFold == null) caseFold = false; - this.matches = function (reverse, pos2) { - return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos2, caseFold); - }; - } else { - query = ensureFlags(query, "gm"); - if (!options || options.multiline !== false) this.matches = function (reverse, pos2) { - return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos2); - };else this.matches = function (reverse, pos2) { - return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos2); - }; - } - } - SearchCursor.prototype = { - findNext: function () { - return this.find(false); - }, - findPrevious: function () { - return this.find(true); - }, - find: function (reverse) { - var head = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); - if (this.afterEmptyMatch && this.atOccurrence) { - head = Pos(head.line, head.ch); - if (reverse) { - head.ch--; - if (head.ch < 0) { - head.line--; - head.ch = (this.doc.getLine(head.line) || "").length; - } + + // cut lines range from source. + StateBlock.prototype.getLines = function getLines( + begin, + end, + indent, + keepLastLF + ) { + if (begin >= end) { + return ""; + } + const queue = new Array(end - begin); + for (let i = 0, line = begin; line < end; line++, i++) { + let lineIndent = 0; + const lineStart = this.bMarks[line]; + let first = lineStart; + let last; + if (line + 1 < end || keepLastLF) { + // No need for bounds check because we have fake entry on tail. + last = this.eMarks[line] + 1; } else { - head.ch++; - if (head.ch > (this.doc.getLine(head.line) || "").length) { - head.ch = 0; - head.line++; + last = this.eMarks[line]; + } + while (first < last && lineIndent < indent) { + const ch = this.src.charCodeAt(first); + if (isSpace(ch)) { + if (ch === 0x09) { + lineIndent += 4 - ((lineIndent + this.bsCount[line]) % 4); + } else { + lineIndent++; + } + } else if (first - lineStart < this.tShift[line]) { + // patched tShift masked characters to look like spaces (blockquotes, list markers) + lineIndent++; + } else { + break; } + first++; } - if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { - return this.atOccurrence = false; + if (lineIndent > indent) { + // partially expanding tabs in code blocks, e.g '\t\tfoobar' + // with indent=2 becomes ' \tfoobar' + queue[i] = + new Array(lineIndent - indent + 1).join(" ") + + this.src.slice(first, last); + } else { + queue[i] = this.src.slice(first, last); } } - var result = this.matches(reverse, head); - this.afterEmptyMatch = result && CodeMirror.cmpPos(result.from, result.to) == 0; - if (result) { - this.pos = result; - this.atOccurrence = true; - return this.pos.match || true; - } else { - var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0); - this.pos = { - from: end, - to: end - }; - return this.atOccurrence = false; - } - }, - from: function () { - if (this.atOccurrence) return this.pos.from; - }, - to: function () { - if (this.atOccurrence) return this.pos.to; - }, - replace: function (newText, origin) { - if (!this.atOccurrence) return; - var lines = CodeMirror.splitLines(newText); - this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin); - this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); - } - }; - CodeMirror.defineExtension("getSearchCursor", function (query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold); - }); - CodeMirror.defineDocExtension("getSearchCursor", function (query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold); - }); - CodeMirror.defineExtension("selectMatches", function (query, caseFold) { - var ranges = []; - var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); - while (cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; - ranges.push({ - anchor: cur.from(), - head: cur.to() - }); - } - if (ranges.length) this.setSelections(ranges, 0); - }); - }); - })(); - return searchcursor.exports; -} -exports.requireSearchcursor = requireSearchcursor; + return queue.join(""); + }; -/***/ }), + // re-export Token class to use in block rules + StateBlock.prototype.Token = Token; -/***/ "../../graphiql-react/dist/show-hint.cjs.js": -/*!**************************************************!*\ - !*** ../../graphiql-react/dist/show-hint.cjs.js ***! - \**************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + // GFM table, https://github.github.com/gfm/#tables-extension- + + // Limit the amount of empty autocompleted cells in a table, + // see https://github.com/markdown-it/markdown-it/issues/1000, + // + // Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. + // We set it to 65k, which can expand user input by a factor of x370 + // (256x256 square is 1.8kB expanded into 650kB). + const MAX_AUTOCOMPLETED_CELLS = 0x10000; + function getLine(state, line) { + const pos = state.bMarks[line] + state.tShift[line]; + const max = state.eMarks[line]; + return state.src.slice(pos, max); + } + function escapedSplit(str) { + const result = []; + const max = str.length; + let pos = 0; + let ch = str.charCodeAt(pos); + let isEscaped = false; + let lastPos = 0; + let current = ""; + while (pos < max) { + if (ch === 0x7c /* | */) { + if (!isEscaped) { + // pipe separating cells, '|' + result.push(current + str.substring(lastPos, pos)); + current = ""; + lastPos = pos + 1; + } else { + // escaped pipe, '\|' + current += str.substring(lastPos, pos - 1); + lastPos = pos; + } + } + isEscaped = ch === 0x5c /* \ */; + pos++; + ch = str.charCodeAt(pos); } + result.push(current + str.substring(lastPos)); + return result; } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var showHint$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var HINT_ELEMENT_CLASS = "CodeMirror-hint"; - var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; - CodeMirror.showHint = function (cm, getHints, options) { - if (!getHints) return cm.showHint(options); - if (options && options.async) getHints.async = true; - var newOpts = { - hint: getHints - }; - if (options) for (var prop in options) newOpts[prop] = options[prop]; - return cm.showHint(newOpts); - }; - CodeMirror.defineExtension("showHint", function (options) { - options = parseOptions(this, this.getCursor("start"), options); - var selections = this.listSelections(); - if (selections.length > 1) return; - if (this.somethingSelected()) { - if (!options.hint.supportsSelection) return; - for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; - } - if (this.state.completionActive) this.state.completionActive.close(); - var completion = this.state.completionActive = new Completion(this, options); - if (!completion.options.hint) return; - CodeMirror.signal(this, "startCompletion", this); - completion.update(true); - }); - CodeMirror.defineExtension("closeHint", function () { - if (this.state.completionActive) this.state.completionActive.close(); - }); - function Completion(cm, options) { - this.cm = cm; - this.options = options; - this.widget = null; - this.debounce = 0; - this.tick = 0; - this.startPos = this.cm.getCursor("start"); - this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; - if (this.options.updateOnCursorActivity) { - var self = this; - cm.on("cursorActivity", this.activityFunc = function () { - self.cursorActivity(); - }); - } - } - var requestAnimationFrame = window.requestAnimationFrame || function (fn) { - return setTimeout(fn, 1e3 / 60); - }; - var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; - Completion.prototype = { - close: function () { - if (!this.active()) return; - this.cm.state.completionActive = null; - this.tick = null; - if (this.options.updateOnCursorActivity) { - this.cm.off("cursorActivity", this.activityFunc); - } - if (this.widget && this.data) CodeMirror.signal(this.data, "close"); - if (this.widget) this.widget.close(); - CodeMirror.signal(this.cm, "endCompletion", this.cm); - }, - active: function () { - return this.cm.state.completionActive == this; - }, - pick: function (data, i) { - var completion = data.list[i], - self = this; - this.cm.operation(function () { - if (completion.hint) completion.hint(self.cm, data, completion);else self.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); - CodeMirror.signal(data, "pick", completion); - self.cm.scrollIntoView(); - }); - if (this.options.closeOnPick) { - this.close(); - } - }, - cursorActivity: function () { - if (this.debounce) { - cancelAnimationFrame(this.debounce); - this.debounce = 0; - } - var identStart = this.startPos; - if (this.data) { - identStart = this.data.from; - } - var pos = this.cm.getCursor(), - line = this.cm.getLine(pos.line); - if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < identStart.ch || this.cm.somethingSelected() || !pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1))) { - this.close(); - } else { - var self = this; - this.debounce = requestAnimationFrame(function () { - self.update(); - }); - if (this.widget) this.widget.disable(); - } - }, - update: function (first) { - if (this.tick == null) return; - var self = this, - myTick = ++this.tick; - fetchHints(this.options.hint, this.cm, this.options, function (data) { - if (self.tick == myTick) self.finishUpdate(data, first); - }); - }, - finishUpdate: function (data, first) { - if (this.data) CodeMirror.signal(this.data, "update"); - var picked = this.widget && this.widget.picked || first && this.options.completeSingle; - if (this.widget) this.widget.close(); - this.data = data; - if (data && data.list.length) { - if (picked && data.list.length == 1) { - this.pick(data, 0); - } else { - this.widget = new Widget(this, data); - CodeMirror.signal(data, "shown"); + function table(state, startLine, endLine, silent) { + // should have at least two lines + if (startLine + 2 > endLine) { + return false; } - } - } - }; - function parseOptions(cm, pos, options) { - var editor = cm.options.hintOptions; - var out = {}; - for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) { - for (var prop in editor) if (editor[prop] !== void 0) out[prop] = editor[prop]; - } - if (options) { - for (var prop in options) if (options[prop] !== void 0) out[prop] = options[prop]; - } - if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); - return out; - } - function getText(completion) { - if (typeof completion == "string") return completion;else return completion.text; - } - function buildKeyMap(completion, handle) { - var baseMap = { - Up: function () { - handle.moveFocus(-1); - }, - Down: function () { - handle.moveFocus(1); - }, - PageUp: function () { - handle.moveFocus(-handle.menuSize() + 1, true); - }, - PageDown: function () { - handle.moveFocus(handle.menuSize() - 1, true); - }, - Home: function () { - handle.setFocus(0); - }, - End: function () { - handle.setFocus(handle.length - 1); - }, - Enter: handle.pick, - Tab: handle.pick, - Esc: handle.close - }; - var mac = /Mac/.test(navigator.platform); - if (mac) { - baseMap["Ctrl-P"] = function () { - handle.moveFocus(-1); - }; - baseMap["Ctrl-N"] = function () { - handle.moveFocus(1); - }; - } - var custom = completion.options.customKeys; - var ourMap = custom ? {} : baseMap; - function addBinding(key2, val) { - var bound; - if (typeof val != "string") bound = function (cm) { - return val(cm, handle); - };else if (baseMap.hasOwnProperty(val)) bound = baseMap[val];else bound = val; - ourMap[key2] = bound; - } - if (custom) { - for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); - } - var extra = completion.options.extraKeys; - if (extra) { - for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); - } - return ourMap; - } - function getHintElement(hintsElement, el) { - while (el && el != hintsElement) { - if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; - el = el.parentNode; - } - } - function Widget(completion, data) { - this.id = "cm-complete-" + Math.floor(Math.random(1e6)); - this.completion = completion; - this.data = data; - this.picked = false; - var widget = this, - cm = completion.cm; - var ownerDocument = cm.getInputField().ownerDocument; - var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow; - var hints = this.hints = ownerDocument.createElement("ul"); - hints.setAttribute("role", "listbox"); - hints.setAttribute("aria-expanded", "true"); - hints.id = this.id; - var theme = completion.cm.options.theme; - hints.className = "CodeMirror-hints " + theme; - this.selectedHint = data.selectedHint || 0; - var completions = data.list; - for (var i = 0; i < completions.length; ++i) { - var elt = hints.appendChild(ownerDocument.createElement("li")), - cur = completions[i]; - var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); - if (cur.className != null) className = cur.className + " " + className; - elt.className = className; - if (i == this.selectedHint) elt.setAttribute("aria-selected", "true"); - elt.id = this.id + "-" + i; - elt.setAttribute("role", "option"); - if (cur.render) cur.render(elt, data, cur);else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur))); - elt.hintId = i; - } - var container = completion.options.container || ownerDocument.body; - var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); - var left = pos.left, - top = pos.bottom, - below = true; - var offsetLeft = 0, - offsetTop = 0; - if (container !== ownerDocument.body) { - var isContainerPositioned = ["absolute", "relative", "fixed"].indexOf(parentWindow.getComputedStyle(container).position) !== -1; - var offsetParent = isContainerPositioned ? container : container.offsetParent; - var offsetParentPosition = offsetParent.getBoundingClientRect(); - var bodyPosition = ownerDocument.body.getBoundingClientRect(); - offsetLeft = offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft; - offsetTop = offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop; - } - hints.style.left = left - offsetLeft + "px"; - hints.style.top = top - offsetTop + "px"; - var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth); - var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight); - container.appendChild(hints); - cm.getInputField().setAttribute("aria-autocomplete", "list"); - cm.getInputField().setAttribute("aria-owns", this.id); - cm.getInputField().setAttribute("aria-activedescendant", this.id + "-" + this.selectedHint); - var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect(); - var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false; - var startScroll; - setTimeout(function () { - startScroll = cm.getScrollInfo(); - }); - var overlapY = box.bottom - winH; - if (overlapY > 0) { - var height = box.bottom - box.top, - curTop = pos.top - (pos.bottom - box.top); - if (curTop - height > 0) { - hints.style.top = (top = pos.top - height - offsetTop) + "px"; - below = false; - } else if (height > winH) { - hints.style.height = winH - 5 + "px"; - hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px"; - var cursor = cm.getCursor(); - if (data.from.ch != cursor.ch) { - pos = cm.cursorCoords(cursor); - hints.style.left = (left = pos.left - offsetLeft) + "px"; - box = hints.getBoundingClientRect(); + let nextLine = startLine + 1; + if (state.sCount[nextLine] < state.blkIndent) { + return false; + } + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + return false; + } + + // first character of the second line should be '|', '-', ':', + // and no other characters are allowed but spaces; + // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp + + let pos = state.bMarks[nextLine] + state.tShift[nextLine]; + if (pos >= state.eMarks[nextLine]) { + return false; + } + const firstCh = state.src.charCodeAt(pos++); + if ( + firstCh !== 0x7c /* | */ && + firstCh !== 0x2d /* - */ && + firstCh !== 0x3a /* : */ + ) { + return false; + } + if (pos >= state.eMarks[nextLine]) { + return false; + } + const secondCh = state.src.charCodeAt(pos++); + if ( + secondCh !== 0x7c /* | */ && + secondCh !== 0x2d /* - */ && + secondCh !== 0x3a /* : */ && + !isSpace(secondCh) + ) { + return false; + } + + // if first character is '-', then second character must not be a space + // (due to parsing ambiguity with list) + if (firstCh === 0x2d /* - */ && isSpace(secondCh)) { + return false; + } + while (pos < state.eMarks[nextLine]) { + const ch = state.src.charCodeAt(pos); + if ( + ch !== 0x7c /* | */ && + ch !== 0x2d /* - */ && + ch !== 0x3a /* : */ && + !isSpace(ch) + ) { + return false; + } + pos++; + } + let lineText = getLine(state, startLine + 1); + let columns = lineText.split("|"); + const aligns = []; + for (let i = 0; i < columns.length; i++) { + const t = columns[i].trim(); + if (!t) { + // allow empty columns before and after table, but not in between columns; + // e.g. allow ` |---| `, disallow ` ---||--- ` + if (i === 0 || i === columns.length - 1) { + continue; + } else { + return false; + } + } + if (!/^:?-+:?$/.test(t)) { + return false; + } + if (t.charCodeAt(t.length - 1) === 0x3a /* : */) { + aligns.push( + t.charCodeAt(0) === 0x3a /* : */ ? "center" : "right" + ); + } else if (t.charCodeAt(0) === 0x3a /* : */) { + aligns.push("left"); + } else { + aligns.push(""); + } } - } - } - var overlapX = box.right - winW; - if (scrolls) overlapX += cm.display.nativeBarWidth; - if (overlapX > 0) { - if (box.right - box.left > winW) { - hints.style.width = winW - 5 + "px"; - overlapX -= box.right - box.left - winW; - } - hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px"; - } - if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling) node.style.paddingRight = cm.display.nativeBarWidth + "px"; - cm.addKeyMap(this.keyMap = buildKeyMap(completion, { - moveFocus: function (n, avoidWrap) { - widget.changeActive(widget.selectedHint + n, avoidWrap); - }, - setFocus: function (n) { - widget.changeActive(n); - }, - menuSize: function () { - return widget.screenAmount(); - }, - length: completions.length, - close: function () { - completion.close(); - }, - pick: function () { - widget.pick(); - }, - data - })); - if (completion.options.closeOnUnfocus) { - var closingOnBlur; - cm.on("blur", this.onBlur = function () { - closingOnBlur = setTimeout(function () { - completion.close(); - }, 100); - }); - cm.on("focus", this.onFocus = function () { - clearTimeout(closingOnBlur); - }); - } - cm.on("scroll", this.onScroll = function () { - var curScroll = cm.getScrollInfo(), - editor = cm.getWrapperElement().getBoundingClientRect(); - if (!startScroll) startScroll = cm.getScrollInfo(); - var newTop = top + startScroll.top - curScroll.top; - var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop); - if (!below) point += hints.offsetHeight; - if (point <= editor.top || point >= editor.bottom) return completion.close(); - hints.style.top = newTop + "px"; - hints.style.left = left + startScroll.left - curScroll.left + "px"; - }); - CodeMirror.on(hints, "dblclick", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - widget.pick(); - } - }); - CodeMirror.on(hints, "click", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - if (completion.options.completeOnSingleClick) widget.pick(); - } - }); - CodeMirror.on(hints, "mousedown", function () { - setTimeout(function () { - cm.focus(); - }, 20); - }); - var selectedHintRange = this.getSelectedHintRange(); - if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { - this.scrollToActive(); - } - CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]); - return true; - } - Widget.prototype = { - close: function () { - if (this.completion.widget != this) return; - this.completion.widget = null; - if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints); - this.completion.cm.removeKeyMap(this.keyMap); - var input = this.completion.cm.getInputField(); - input.removeAttribute("aria-activedescendant"); - input.removeAttribute("aria-owns"); - var cm = this.completion.cm; - if (this.completion.options.closeOnUnfocus) { - cm.off("blur", this.onBlur); - cm.off("focus", this.onFocus); - } - cm.off("scroll", this.onScroll); - }, - disable: function () { - this.completion.cm.removeKeyMap(this.keyMap); - var widget = this; - this.keyMap = { - Enter: function () { - widget.picked = true; + lineText = getLine(state, startLine).trim(); + if (lineText.indexOf("|") === -1) { + return false; } - }; - this.completion.cm.addKeyMap(this.keyMap); - }, - pick: function () { - this.completion.pick(this.data, this.selectedHint); - }, - changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0;else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; - if (this.selectedHint == i) return; - var node = this.hints.childNodes[this.selectedHint]; - if (node) { - node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); - node.removeAttribute("aria-selected"); - } - node = this.hints.childNodes[this.selectedHint = i]; - node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - node.setAttribute("aria-selected", "true"); - this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id); - this.scrollToActive(); - CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); - }, - scrollToActive: function () { - var selectedHintRange = this.getSelectedHintRange(); - var node1 = this.hints.childNodes[selectedHintRange.from]; - var node2 = this.hints.childNodes[selectedHintRange.to]; - var firstNode = this.hints.firstChild; - if (node1.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop; - }, - screenAmount: function () { - return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; - }, - getSelectedHintRange: function () { - var margin = this.completion.options.scrollMargin || 0; - return { - from: Math.max(0, this.selectedHint - margin), - to: Math.min(this.data.list.length - 1, this.selectedHint + margin) - }; - } - }; - function applicableHelpers(cm, helpers) { - if (!cm.somethingSelected()) return helpers; - var result = []; - for (var i = 0; i < helpers.length; i++) if (helpers[i].supportsSelection) result.push(helpers[i]); - return result; - } - function fetchHints(hint, cm, options, callback) { - if (hint.async) { - hint(cm, callback, options); - } else { - var result = hint(cm, options); - if (result && result.then) result.then(callback);else callback(result); - } - } - function resolveAutoHints(cm, pos) { - var helpers = cm.getHelpers(pos, "hint"), - words; - if (helpers.length) { - var resolved = function (cm2, callback, options) { - var app = applicableHelpers(cm2, helpers); - function run(i) { - if (i == app.length) return callback(null); - fetchHints(app[i], cm2, options, function (result) { - if (result && result.list.length > 0) callback(result);else run(i + 1); - }); + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; } - run(0); - }; - resolved.async = true; - resolved.supportsSelection = true; - return resolved; - } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { - return function (cm2) { - return CodeMirror.hint.fromList(cm2, { - words - }); - }; - } else if (CodeMirror.hint.anyword) { - return function (cm2, options) { - return CodeMirror.hint.anyword(cm2, options); - }; - } else { - return function () {}; - } - } - CodeMirror.registerHelper("hint", "auto", { - resolve: resolveAutoHints - }); - CodeMirror.registerHelper("hint", "fromList", function (cm, options) { - var cur = cm.getCursor(), - token = cm.getTokenAt(cur); - var term, - from = CodeMirror.Pos(cur.line, token.start), - to = cur; - if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) { - term = token.string.substr(0, cur.ch - token.start); - } else { - term = ""; - from = cur; - } - var found = []; - for (var i = 0; i < options.words.length; i++) { - var word = options.words[i]; - if (word.slice(0, term.length) == term) found.push(word); - } - if (found.length) return { - list: found, - from, - to - }; - }); - CodeMirror.commands.autocomplete = CodeMirror.showHint; - var defaultOptions = { - hint: CodeMirror.hint.auto, - completeSingle: true, - alignWithWord: true, - closeCharacters: /[\s()\[\]{};:>,]/, - closeOnPick: true, - closeOnUnfocus: true, - updateOnCursorActivity: true, - completeOnSingleClick: true, - container: null, - customKeys: null, - extraKeys: null, - paddingForScrollbar: true, - moveOnOverlap: true - }; - CodeMirror.defineOption("hintOptions", null); - }); -})(); -var showHintExports = showHint$2.exports; -const showHint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(showHintExports); -const showHint$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: showHint -}, [showHintExports]); -exports.showHint = showHint$1; - -/***/ }), - -/***/ "../../graphiql-react/dist/sublime.cjs.js": -/*!************************************************!*\ - !*** ../../graphiql-react/dist/sublime.cjs.js ***! - \************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); -const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); -const matchbrackets = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); -function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + columns = escapedSplit(lineText); + if (columns.length && columns[0] === "") columns.shift(); + if (columns.length && columns[columns.length - 1] === "") + columns.pop(); + + // header row will define an amount of columns in the entire table, + // and align row should be exactly the same (the rest of the rows can differ) + const columnCount = columns.length; + if (columnCount === 0 || columnCount !== aligns.length) { + return false; + } + if (silent) { + return true; + } + const oldParentType = state.parentType; + state.parentType = "table"; + + // use 'blockquote' lists for termination because it's + // the most similar to tables + const terminatorRules = state.md.block.ruler.getRules("blockquote"); + const token_to = state.push("table_open", "table", 1); + const tableLines = [startLine, 0]; + token_to.map = tableLines; + const token_tho = state.push("thead_open", "thead", 1); + token_tho.map = [startLine, startLine + 1]; + const token_htro = state.push("tr_open", "tr", 1); + token_htro.map = [startLine, startLine + 1]; + for (let i = 0; i < columns.length; i++) { + const token_ho = state.push("th_open", "th", 1); + if (aligns[i]) { + token_ho.attrs = [["style", "text-align:" + aligns[i]]]; + } + const token_il = state.push("inline", "", 0); + token_il.content = columns[i].trim(); + token_il.children = []; + state.push("th_close", "th", -1); + } + state.push("tr_close", "tr", -1); + state.push("thead_close", "thead", -1); + let tbodyLines; + let autocompletedCells = 0; + for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { + if (state.sCount[nextLine] < state.blkIndent) { + break; + } + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + break; + } + lineText = getLine(state, nextLine).trim(); + if (!lineText) { + break; + } + if (state.sCount[nextLine] - state.blkIndent >= 4) { + break; + } + columns = escapedSplit(lineText); + if (columns.length && columns[0] === "") columns.shift(); + if (columns.length && columns[columns.length - 1] === "") + columns.pop(); + + // note: autocomplete count can be negative if user specifies more columns than header, + // but that does not affect intended use (which is limiting expansion) + autocompletedCells += columnCount - columns.length; + if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) { + break; + } + if (nextLine === startLine + 2) { + const token_tbo = state.push("tbody_open", "tbody", 1); + token_tbo.map = tbodyLines = [startLine + 2, 0]; + } + const token_tro = state.push("tr_open", "tr", 1); + token_tro.map = [nextLine, nextLine + 1]; + for (let i = 0; i < columnCount; i++) { + const token_tdo = state.push("td_open", "td", 1); + if (aligns[i]) { + token_tdo.attrs = [["style", "text-align:" + aligns[i]]]; + } + const token_il = state.push("inline", "", 0); + token_il.content = columns[i] ? columns[i].trim() : ""; + token_il.children = []; + state.push("td_close", "td", -1); + } + state.push("tr_close", "tr", -1); } + if (tbodyLines) { + state.push("tbody_close", "tbody", -1); + tbodyLines[1] = nextLine; + } + state.push("table_close", "table", -1); + tableLines[1] = nextLine; + state.parentType = oldParentType; + state.line = nextLine; + return true; } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); -} -var sublime$2 = { - exports: {} -}; -(function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), matchbrackets.requireMatchbrackets()); - })(function (CodeMirror) { - var cmds = CodeMirror.commands; - var Pos = CodeMirror.Pos; - function findPosSubword(doc, start, dir) { - if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); - var line = doc.getLine(start.line); - if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); - var state = "start", - type, - startPos = start.ch; - for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { - var next = line.charAt(dir < 0 ? pos - 1 : pos); - var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; - if (cat == "w" && next.toUpperCase() == next) cat = "W"; - if (state == "start") { - if (cat != "o") { - state = "in"; - type = cat; - } else startPos = pos + dir; - } else if (state == "in") { - if (type != cat) { - if (type == "w" && cat == "W" && dir < 0) pos--; - if (type == "W" && cat == "w" && dir > 0) { - if (pos == startPos + 1) { - type = "w"; - continue; - } else pos--; + + // Code block (4 spaces padded) + + function code(state, startLine, endLine /*, silent */) { + if (state.sCount[startLine] - state.blkIndent < 4) { + return false; + } + let nextLine = startLine + 1; + let last = nextLine; + while (nextLine < endLine) { + if (state.isEmpty(nextLine)) { + nextLine++; + continue; + } + if (state.sCount[nextLine] - state.blkIndent >= 4) { + nextLine++; + last = nextLine; + continue; } break; } + state.line = last; + const token = state.push("code_block", "code", 0); + token.content = + state.getLines(startLine, last, 4 + state.blkIndent, false) + "\n"; + token.map = [startLine, state.line]; + return true; } - } - return Pos(start.line, pos); - } - function moveSubword(cm, dir) { - cm.extendSelectionsBy(function (range) { - if (cm.display.shift || cm.doc.extend || range.empty()) return findPosSubword(cm.doc, range.head, dir);else return dir < 0 ? range.from() : range.to(); - }); - } - cmds.goSubwordLeft = function (cm) { - moveSubword(cm, -1); - }; - cmds.goSubwordRight = function (cm) { - moveSubword(cm, 1); - }; - cmds.scrollLineUp = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); - if (cm.getCursor().line >= visibleBottomLine) cm.execCommand("goLineUp"); - } - cm.scrollTo(null, info.top - cm.defaultTextHeight()); - }; - cmds.scrollLineDown = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; - if (cm.getCursor().line <= visibleTopLine) cm.execCommand("goLineDown"); - } - cm.scrollTo(null, info.top + cm.defaultTextHeight()); - }; - cmds.splitSelectionByLine = function (cm) { - var ranges = cm.listSelections(), - lineRanges = []; - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - for (var line = from.line; line <= to.line; ++line) if (!(to.line > from.line && line == to.line && to.ch == 0)) lineRanges.push({ - anchor: line == from.line ? from : Pos(line, 0), - head: line == to.line ? to : Pos(line) - }); - } - cm.setSelections(lineRanges, 0); - }; - cmds.singleSelectionTop = function (cm) { - var range = cm.listSelections()[0]; - cm.setSelection(range.anchor, range.head, { - scroll: false - }); - }; - cmds.selectLine = function (cm) { - var ranges = cm.listSelections(), - extended = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - extended.push({ - anchor: Pos(range.from().line, 0), - head: Pos(range.to().line + 1, 0) - }); - } - cm.setSelections(extended); - }; - function insertLine(cm, above) { - if (cm.isReadOnly()) return CodeMirror.Pass; - cm.operation(function () { - var len = cm.listSelections().length, - newSelection = [], - last = -1; - for (var i = 0; i < len; i++) { - var head = cm.listSelections()[i].head; - if (head.line <= last) continue; - var at = Pos(head.line + (above ? 0 : 1), 0); - cm.replaceRange("\n", at, null, "+insertLine"); - cm.indentLine(at.line, null, true); - newSelection.push({ - head: at, - anchor: at - }); - last = head.line + 1; - } - cm.setSelections(newSelection); - }); - cm.execCommand("indentAuto"); - } - cmds.insertLineAfter = function (cm) { - return insertLine(cm, false); - }; - cmds.insertLineBefore = function (cm) { - return insertLine(cm, true); - }; - function wordAt(cm, pos) { - var start = pos.ch, - end = start, - line = cm.getLine(pos.line); - while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; - while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; - return { - from: Pos(pos.line, start), - to: Pos(pos.line, end), - word: line.slice(start, end) - }; - } - cmds.selectNextOccurrence = function (cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - cm.setSelection(word.from, word.to); - fullWord = true; - } else { - var text = cm.getRange(from, to); - var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; - var cur = cm.getSearchCursor(query, to); - var found = cur.findNext(); - if (!found) { - cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); - found = cur.findNext(); - } - if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return; - cm.addSelection(cur.from(), cur.to()); - } - if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; - }; - cmds.skipAndSelectNextOccurrence = function (cm) { - var prevAnchor = cm.getCursor("anchor"), - prevHead = cm.getCursor("head"); - cmds.selectNextOccurrence(cm); - if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { - cm.doc.setSelections(cm.doc.listSelections().filter(function (sel) { - return sel.anchor != prevAnchor || sel.head != prevHead; - })); - } - }; - function addCursorToSelection(cm, dir) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var newAnchor = cm.findPosV(range.anchor, dir, "line", range.anchor.goalColumn); - var newHead = cm.findPosV(range.head, dir, "line", range.head.goalColumn); - newAnchor.goalColumn = range.anchor.goalColumn != null ? range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left; - newHead.goalColumn = range.head.goalColumn != null ? range.head.goalColumn : cm.cursorCoords(range.head, "div").left; - var newRange = { - anchor: newAnchor, - head: newHead - }; - newRanges.push(range); - newRanges.push(newRange); - } - cm.setSelections(newRanges); - } - cmds.addCursorToPrevLine = function (cm) { - addCursorToSelection(cm, -1); - }; - cmds.addCursorToNextLine = function (cm) { - addCursorToSelection(cm, 1); - }; - function isSelectedRange(ranges, from, to) { - for (var i = 0; i < ranges.length; i++) if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 && CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true; - return false; - } - var mirror = "(){}[]"; - function selectBetweenBrackets(cm) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - pos = range.head, - opening = cm.scanForBracket(pos, -1); - if (!opening) return false; - for (;;) { - var closing = cm.scanForBracket(pos, 1); - if (!closing) return false; - if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { - var startPos = Pos(opening.pos.line, opening.pos.ch + 1); - if (CodeMirror.cmpPos(startPos, range.from()) == 0 && CodeMirror.cmpPos(closing.pos, range.to()) == 0) { - opening = cm.scanForBracket(opening.pos, -1); - if (!opening) return false; - } else { - newRanges.push({ - anchor: startPos, - head: closing.pos - }); + + // fences (``` lang, ~~~ lang) + + function fence(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (pos + 3 > max) { + return false; + } + const marker = state.src.charCodeAt(pos); + if (marker !== 0x7e /* ~ */ && marker !== 0x60 /* ` */) { + return false; + } + + // scan marker length + let mem = pos; + pos = state.skipChars(pos, marker); + let len = pos - mem; + if (len < 3) { + return false; + } + const markup = state.src.slice(mem, pos); + const params = state.src.slice(pos, max); + if (marker === 0x60 /* ` */) { + if (params.indexOf(String.fromCharCode(marker)) >= 0) { + return false; + } + } + + // Since start is found, we can report success here in validation mode + if (silent) { + return true; + } + + // search end of block + let nextLine = startLine; + let haveEndMarker = false; + for (;;) { + nextLine++; + if (nextLine >= endLine) { + // unclosed block should be autoclosed by end of document. + // also block seems to be autoclosed by end of parent + break; + } + pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + if (pos < max && state.sCount[nextLine] < state.blkIndent) { + // non-empty line with negative indent should stop the list: + // - ``` + // test break; } + if (state.src.charCodeAt(pos) !== marker) { + continue; + } + if (state.sCount[nextLine] - state.blkIndent >= 4) { + // closing fence should be indented less than 4 spaces + continue; + } + pos = state.skipChars(pos, marker); + + // closing code fence must be at least as long as the opening one + if (pos - mem < len) { + continue; + } + + // make sure tail has spaces only + pos = state.skipSpaces(pos); + if (pos < max) { + continue; + } + haveEndMarker = true; + // found! + break; } - pos = Pos(closing.pos.line, closing.pos.ch + 1); - } - } - cm.setSelections(newRanges); - return true; - } - cmds.selectScope = function (cm) { - selectBetweenBrackets(cm) || cm.execCommand("selectAll"); - }; - cmds.selectBetweenBrackets = function (cm) { - if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; - }; - function puncType(type) { - return !type ? null : /\bpunctuation\b/.test(type) ? type : void 0; - } - cmds.goToBracket = function (cm) { - cm.extendSelectionsBy(function (range) { - var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head))); - if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; - var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)))); - return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; - }); - }; - cmds.swapLineUp = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.firstLine() - 1, - newSels = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from().line - 1, - to = range.to().line; - newSels.push({ - anchor: Pos(range.anchor.line - 1, range.anchor.ch), - head: Pos(range.head.line - 1, range.head.ch) - }); - if (range.to().ch == 0 && !range.empty()) --to; - if (from > at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i2 = 0; i2 < linesToMove.length; i2 += 2) { - var from2 = linesToMove[i2], - to2 = linesToMove[i2 + 1]; - var line = cm.getLine(from2); - cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); - if (to2 > cm.lastLine()) cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");else cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); - } - cm.setSelections(newSels); - cm.scrollIntoView(); - }); - }; - cmds.swapLineDown = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.lastLine() + 1; - for (var i = ranges.length - 1; i >= 0; i--) { - var range = ranges[i], - from = range.to().line + 1, - to = range.from().line; - if (range.to().ch == 0 && !range.empty()) from--; - if (from < at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i2 = linesToMove.length - 2; i2 >= 0; i2 -= 2) { - var from2 = linesToMove[i2], - to2 = linesToMove[i2 + 1]; - var line = cm.getLine(from2); - if (from2 == cm.lastLine()) cm.replaceRange("", Pos(from2 - 1), Pos(from2), "+swapLine");else cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); - cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); - } - cm.scrollIntoView(); - }); - }; - cmds.toggleCommentIndented = function (cm) { - cm.toggleComment({ - indent: true - }); - }; - cmds.joinLines = function (cm) { - var ranges = cm.listSelections(), - joined = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from(); - var start = from.line, - end = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == end) end = ranges[++i].to().line; - joined.push({ - start, - end, - anchor: !range.empty() && from - }); - } - cm.operation(function () { - var offset = 0, - ranges2 = []; - for (var i2 = 0; i2 < joined.length; i2++) { - var obj = joined[i2]; - var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), - head; - for (var line = obj.start; line <= obj.end; line++) { - var actual = line - offset; - if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); - if (actual < cm.lastLine()) { - cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); - ++offset; - } - } - ranges2.push({ - anchor: anchor || head, - head - }); - } - cm.setSelections(ranges2, 0); - }); - }; - cmds.duplicateLine = function (cm) { - cm.operation(function () { - var rangeCount = cm.listSelections().length; - for (var i = 0; i < rangeCount; i++) { - var range = cm.listSelections()[i]; - if (range.empty()) cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));else cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); - } - cm.scrollIntoView(); - }); - }; - function sortLines(cm, caseSensitive, direction) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - toSort = [], - selected; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) continue; - var from = range.from().line, - to = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == to) to = ranges[++i].to().line; - if (!ranges[i].to().ch) to--; - toSort.push(from, to); - } - if (toSort.length) selected = true;else toSort.push(cm.firstLine(), cm.lastLine()); - cm.operation(function () { - var ranges2 = []; - for (var i2 = 0; i2 < toSort.length; i2 += 2) { - var from2 = toSort[i2], - to2 = toSort[i2 + 1]; - var start = Pos(from2, 0), - end = Pos(to2); - var lines = cm.getRange(start, end, false); - if (caseSensitive) lines.sort(function (a, b) { - return a < b ? -direction : a == b ? 0 : direction; - });else lines.sort(function (a, b) { - var au = a.toUpperCase(), - bu = b.toUpperCase(); - if (au != bu) { - a = au; - b = bu; - } - return a < b ? -direction : a == b ? 0 : direction; - }); - cm.replaceRange(lines, start, end); - if (selected) ranges2.push({ - anchor: start, - head: Pos(to2 + 1, 0) - }); - } - if (selected) cm.setSelections(ranges2, 0); - }); - } - cmds.sortLines = function (cm) { - sortLines(cm, true, 1); - }; - cmds.reverseSortLines = function (cm) { - sortLines(cm, true, -1); - }; - cmds.sortLinesInsensitive = function (cm) { - sortLines(cm, false, 1); - }; - cmds.reverseSortLinesInsensitive = function (cm) { - sortLines(cm, false, -1); - }; - cmds.nextBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) while (marks.length) { - var current = marks.shift(); - var found = current.find(); - if (found) { - marks.push(current); - return cm.setSelection(found.from, found.to); + + // If a fence has heading spaces, they should be removed from its inner block + len = state.sCount[startLine]; + state.line = nextLine + (haveEndMarker ? 1 : 0); + const token = state.push("fence", "code", 0); + token.info = params; + token.content = state.getLines(startLine + 1, nextLine, len, true); + token.markup = markup; + token.map = [startLine, state.line]; + return true; } - } - }; - cmds.prevBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) while (marks.length) { - marks.unshift(marks.pop()); - var found = marks[marks.length - 1].find(); - if (!found) marks.pop();else return cm.setSelection(found.from, found.to); - } - }; - cmds.toggleBookmark = function (cm) { - var ranges = cm.listSelections(); - var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to); - for (var j = 0; j < found.length; j++) { - if (found[j].sublimeBookmark) { - found[j].clear(); - for (var k = 0; k < marks.length; k++) if (marks[k] == found[j]) marks.splice(k--, 1); - break; + + // Block quotes + + function blockquote(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + const oldLineMax = state.lineMax; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + + // check the block quote marker + if (state.src.charCodeAt(pos) !== 0x3e /* > */) { + return false; + } + + // we know that it's going to be a valid blockquote, + // so no point trying to find the end of it in silent mode + if (silent) { + return true; } + const oldBMarks = []; + const oldBSCount = []; + const oldSCount = []; + const oldTShift = []; + const terminatorRules = state.md.block.ruler.getRules("blockquote"); + const oldParentType = state.parentType; + state.parentType = "blockquote"; + let lastLineEmpty = false; + let nextLine; + + // Search the end of the block + // + // Block ends with either: + // 1. an empty line outside: + // ``` + // > test + // + // ``` + // 2. an empty line inside: + // ``` + // > + // test + // ``` + // 3. another tag: + // ``` + // > test + // - - - + // ``` + for (nextLine = startLine; nextLine < endLine; nextLine++) { + // check if it's outdented, i.e. it's inside list item and indented + // less than said list item: + // + // ``` + // 1. anything + // > current blockquote + // 2. checking this line + // ``` + const isOutdented = state.sCount[nextLine] < state.blkIndent; + pos = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + if (pos >= max) { + // Case 1: line is not inside the blockquote, and this line is empty. + break; + } + if (state.src.charCodeAt(pos++) === 0x3e /* > */ && !isOutdented) { + // This line is inside the blockquote. + + // set offset past spaces and ">" + let initial = state.sCount[nextLine] + 1; + let spaceAfterMarker; + let adjustTab; + + // skip one optional space after '>' + if (state.src.charCodeAt(pos) === 0x20 /* space */) { + // ' > test ' + // ^ -- position start of line here: + pos++; + initial++; + adjustTab = false; + spaceAfterMarker = true; + } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { + spaceAfterMarker = true; + if ((state.bsCount[nextLine] + initial) % 4 === 3) { + // ' >\t test ' + // ^ -- position start of line here (tab has width===1) + pos++; + initial++; + adjustTab = false; + } else { + // ' >\t test ' + // ^ -- position start of line here + shift bsCount slightly + // to make extra space appear + adjustTab = true; + } + } else { + spaceAfterMarker = false; + } + let offset = initial; + oldBMarks.push(state.bMarks[nextLine]); + state.bMarks[nextLine] = pos; + while (pos < max) { + const ch = state.src.charCodeAt(pos); + if (isSpace(ch)) { + if (ch === 0x09) { + offset += + 4 - + ((offset + + state.bsCount[nextLine] + + (adjustTab ? 1 : 0)) % + 4); + } else { + offset++; + } + } else { + break; + } + pos++; + } + lastLineEmpty = pos >= max; + oldBSCount.push(state.bsCount[nextLine]); + state.bsCount[nextLine] = + state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); + oldSCount.push(state.sCount[nextLine]); + state.sCount[nextLine] = offset - initial; + oldTShift.push(state.tShift[nextLine]); + state.tShift[nextLine] = pos - state.bMarks[nextLine]; + continue; + } + + // Case 2: line is not inside the blockquote, and the last line was empty. + if (lastLineEmpty) { + break; + } + + // Case 3: another tag found. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + // Quirk to enforce "hard termination mode" for paragraphs; + // normally if you call `tokenize(state, startLine, nextLine)`, + // paragraphs will look below nextLine for paragraph continuation, + // but if blockquote is terminated by another tag, they shouldn't + state.lineMax = nextLine; + if (state.blkIndent !== 0) { + // state.blkIndent was non-zero, we now set it to zero, + // so we need to re-calculate all offsets to appear as + // if indent wasn't changed + oldBMarks.push(state.bMarks[nextLine]); + oldBSCount.push(state.bsCount[nextLine]); + oldTShift.push(state.tShift[nextLine]); + oldSCount.push(state.sCount[nextLine]); + state.sCount[nextLine] -= state.blkIndent; + } + break; + } + oldBMarks.push(state.bMarks[nextLine]); + oldBSCount.push(state.bsCount[nextLine]); + oldTShift.push(state.tShift[nextLine]); + oldSCount.push(state.sCount[nextLine]); + + // A negative indentation means that this is a paragraph continuation + // + state.sCount[nextLine] = -1; + } + const oldIndent = state.blkIndent; + state.blkIndent = 0; + const token_o = state.push("blockquote_open", "blockquote", 1); + token_o.markup = ">"; + const lines = [startLine, 0]; + token_o.map = lines; + state.md.block.tokenize(state, startLine, nextLine); + const token_c = state.push("blockquote_close", "blockquote", -1); + token_c.markup = ">"; + state.lineMax = oldLineMax; + state.parentType = oldParentType; + lines[1] = state.line; + + // Restore original tShift; this might not be necessary since the parser + // has already been here, but just to make sure we can do that. + for (let i = 0; i < oldTShift.length; i++) { + state.bMarks[i + startLine] = oldBMarks[i]; + state.tShift[i + startLine] = oldTShift[i]; + state.sCount[i + startLine] = oldSCount[i]; + state.bsCount[i + startLine] = oldBSCount[i]; + } + state.blkIndent = oldIndent; + return true; } - if (j == found.length) marks.push(cm.markText(from, to, { - sublimeBookmark: true, - clearWhenEmpty: false - })); - } - }; - cmds.clearBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); - marks.length = 0; - }; - cmds.selectBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks, - ranges = []; - if (marks) for (var i = 0; i < marks.length; i++) { - var found = marks[i].find(); - if (!found) marks.splice(i--, 0);else ranges.push({ - anchor: found.from, - head: found.to - }); - } - if (ranges.length) cm.setSelections(ranges, 0); - }; - function modifyWordOrSelection(cm, mod) { - cm.operation(function () { - var ranges = cm.listSelections(), - indices = [], - replacements = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) { - indices.push(i); - replacements.push(""); - } else replacements.push(mod(cm.getRange(range.from(), range.to()))); - } - cm.replaceSelections(replacements, "around", "case"); - for (var i = indices.length - 1, at; i >= 0; i--) { - var range = ranges[indices[i]]; - if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; - var word = wordAt(cm, range.head); - at = word.from; - cm.replaceRange(mod(word.word), word.from, word.to); - } - }); - } - cmds.smartBackspace = function (cm) { - if (cm.somethingSelected()) return CodeMirror.Pass; - cm.operation(function () { - var cursors = cm.listSelections(); - var indentUnit = cm.getOption("indentUnit"); - for (var i = cursors.length - 1; i >= 0; i--) { - var cursor = cursors[i].head; - var toStartOfLine = cm.getRange({ - line: cursor.line, - ch: 0 - }, cursor); - var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); - var deletePos = cm.findPosH(cursor, -1, "char", false); - if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { - var prevIndent = new Pos(cursor.line, CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); - if (prevIndent.ch != cursor.ch) deletePos = prevIndent; - } - cm.replaceRange("", deletePos, cursor, "+delete"); - } - }); - }; - cmds.delLineRight = function (cm) { - cm.operation(function () { - var ranges = cm.listSelections(); - for (var i = ranges.length - 1; i >= 0; i--) cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); - cm.scrollIntoView(); - }); - }; - cmds.upcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toUpperCase(); - }); - }; - cmds.downcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toLowerCase(); - }); - }; - cmds.setSublimeMark = function (cm) { - if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - }; - cmds.selectToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) cm.setSelection(cm.getCursor(), found); - }; - cmds.deleteToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - var from = cm.getCursor(), - to = found; - if (CodeMirror.cmpPos(from, to) > 0) { - var tmp = to; - to = from; - from = tmp; - } - cm.state.sublimeKilled = cm.getRange(from, to); - cm.replaceRange("", from, to); - } - }; - cmds.swapWithSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - cm.setCursor(found); - } - }; - cmds.sublimeYank = function (cm) { - if (cm.state.sublimeKilled != null) cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); - }; - cmds.showInCenter = function (cm) { - var pos = cm.cursorCoords(null, "local"); - cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); - }; - function getTarget(cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - from = word.from; - to = word.to; - } - return { - from, - to, - query: cm.getRange(from, to), - word - }; - } - function findAndGoTo(cm, forward) { - var target = getTarget(cm); - if (!target) return; - var query = target.query; - var cur = cm.getSearchCursor(query, forward ? target.to : target.from); - if (forward ? cur.findNext() : cur.findPrevious()) { - cm.setSelection(cur.from(), cur.to()); - } else { - cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) : cm.clipPos(Pos(cm.lastLine()))); - if (forward ? cur.findNext() : cur.findPrevious()) cm.setSelection(cur.from(), cur.to());else if (target.word) cm.setSelection(target.from, target.to); - } - } - cmds.findUnder = function (cm) { - findAndGoTo(cm, true); - }; - cmds.findUnderPrevious = function (cm) { - findAndGoTo(cm, false); - }; - cmds.findAllUnder = function (cm) { - var target = getTarget(cm); - if (!target) return; - var cur = cm.getSearchCursor(target.query); - var matches = []; - var primaryIndex = -1; - while (cur.findNext()) { - matches.push({ - anchor: cur.from(), - head: cur.to() - }); - if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) primaryIndex++; - } - cm.setSelections(matches, primaryIndex); - }; - var keyMap = CodeMirror.keyMap; - keyMap.macSublime = { - "Cmd-Left": "goLineStartSmart", - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Ctrl-Alt-Up": "scrollLineUp", - "Ctrl-Alt-Down": "scrollLineDown", - "Cmd-L": "selectLine", - "Shift-Cmd-L": "splitSelectionByLine", - "Esc": "singleSelectionTop", - "Cmd-Enter": "insertLineAfter", - "Shift-Cmd-Enter": "insertLineBefore", - "Cmd-D": "selectNextOccurrence", - "Shift-Cmd-Space": "selectScope", - "Shift-Cmd-M": "selectBetweenBrackets", - "Cmd-M": "goToBracket", - "Cmd-Ctrl-Up": "swapLineUp", - "Cmd-Ctrl-Down": "swapLineDown", - "Cmd-/": "toggleCommentIndented", - "Cmd-J": "joinLines", - "Shift-Cmd-D": "duplicateLine", - "F5": "sortLines", - "Shift-F5": "reverseSortLines", - "Cmd-F5": "sortLinesInsensitive", - "Shift-Cmd-F5": "reverseSortLinesInsensitive", - "F2": "nextBookmark", - "Shift-F2": "prevBookmark", - "Cmd-F2": "toggleBookmark", - "Shift-Cmd-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - "Backspace": "smartBackspace", - "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", - "Cmd-K Cmd-K": "delLineRight", - "Cmd-K Cmd-U": "upcaseAtCursor", - "Cmd-K Cmd-L": "downcaseAtCursor", - "Cmd-K Cmd-Space": "setSublimeMark", - "Cmd-K Cmd-A": "selectToSublimeMark", - "Cmd-K Cmd-W": "deleteToSublimeMark", - "Cmd-K Cmd-X": "swapWithSublimeMark", - "Cmd-K Cmd-Y": "sublimeYank", - "Cmd-K Cmd-C": "showInCenter", - "Cmd-K Cmd-G": "clearBookmarks", - "Cmd-K Cmd-Backspace": "delLineLeft", - "Cmd-K Cmd-1": "foldAll", - "Cmd-K Cmd-0": "unfoldAll", - "Cmd-K Cmd-J": "unfoldAll", - "Ctrl-Shift-Up": "addCursorToPrevLine", - "Ctrl-Shift-Down": "addCursorToNextLine", - "Cmd-F3": "findUnder", - "Shift-Cmd-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Cmd-[": "fold", - "Shift-Cmd-]": "unfold", - "Cmd-I": "findIncremental", - "Shift-Cmd-I": "findIncrementalReverse", - "Cmd-H": "replace", - "F3": "findNext", - "Shift-F3": "findPrev", - "fallthrough": "macDefault" - }; - CodeMirror.normalizeKeyMap(keyMap.macSublime); - keyMap.pcSublime = { - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-T": "transposeChars", - "Alt-Left": "goSubwordLeft", - "Alt-Right": "goSubwordRight", - "Ctrl-Up": "scrollLineUp", - "Ctrl-Down": "scrollLineDown", - "Ctrl-L": "selectLine", - "Shift-Ctrl-L": "splitSelectionByLine", - "Esc": "singleSelectionTop", - "Ctrl-Enter": "insertLineAfter", - "Shift-Ctrl-Enter": "insertLineBefore", - "Ctrl-D": "selectNextOccurrence", - "Shift-Ctrl-Space": "selectScope", - "Shift-Ctrl-M": "selectBetweenBrackets", - "Ctrl-M": "goToBracket", - "Shift-Ctrl-Up": "swapLineUp", - "Shift-Ctrl-Down": "swapLineDown", - "Ctrl-/": "toggleCommentIndented", - "Ctrl-J": "joinLines", - "Shift-Ctrl-D": "duplicateLine", - "F9": "sortLines", - "Shift-F9": "reverseSortLines", - "Ctrl-F9": "sortLinesInsensitive", - "Shift-Ctrl-F9": "reverseSortLinesInsensitive", - "F2": "nextBookmark", - "Shift-F2": "prevBookmark", - "Ctrl-F2": "toggleBookmark", - "Shift-Ctrl-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - "Backspace": "smartBackspace", - "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", - "Ctrl-K Ctrl-K": "delLineRight", - "Ctrl-K Ctrl-U": "upcaseAtCursor", - "Ctrl-K Ctrl-L": "downcaseAtCursor", - "Ctrl-K Ctrl-Space": "setSublimeMark", - "Ctrl-K Ctrl-A": "selectToSublimeMark", - "Ctrl-K Ctrl-W": "deleteToSublimeMark", - "Ctrl-K Ctrl-X": "swapWithSublimeMark", - "Ctrl-K Ctrl-Y": "sublimeYank", - "Ctrl-K Ctrl-C": "showInCenter", - "Ctrl-K Ctrl-G": "clearBookmarks", - "Ctrl-K Ctrl-Backspace": "delLineLeft", - "Ctrl-K Ctrl-1": "foldAll", - "Ctrl-K Ctrl-0": "unfoldAll", - "Ctrl-K Ctrl-J": "unfoldAll", - "Ctrl-Alt-Up": "addCursorToPrevLine", - "Ctrl-Alt-Down": "addCursorToNextLine", - "Ctrl-F3": "findUnder", - "Shift-Ctrl-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Ctrl-[": "fold", - "Shift-Ctrl-]": "unfold", - "Ctrl-I": "findIncremental", - "Shift-Ctrl-I": "findIncrementalReverse", - "Ctrl-H": "replace", - "F3": "findNext", - "Shift-F3": "findPrev", - "fallthrough": "pcDefault" - }; - CodeMirror.normalizeKeyMap(keyMap.pcSublime); - var mac = keyMap.default == keyMap.macDefault; - keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; - }); -})(); -var sublimeExports = sublime$2.exports; -const sublime = /* @__PURE__ */codemirror.getDefaultExportFromCjs(sublimeExports); -const sublime$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: sublime -}, [sublimeExports]); -exports.sublime = sublime$1; - -/***/ }), - -/***/ "../../graphiql-toolkit/esm/async-helpers/index.js": -/*!*********************************************************!*\ - !*** ../../graphiql-toolkit/esm/async-helpers/index.js ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports) { + // Horizontal rule + + function hr(state, startLine, endLine, silent) { + const max = state.eMarks[startLine]; + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + let pos = state.bMarks[startLine] + state.tShift[startLine]; + const marker = state.src.charCodeAt(pos++); + + // Check hr marker + if ( + marker !== 0x2a /* * */ && + marker !== 0x2d /* - */ && + marker !== 0x5f /* _ */ + ) { + return false; + } + + // markers can be mixed with spaces, but there should be at least 3 of them + + let cnt = 1; + while (pos < max) { + const ch = state.src.charCodeAt(pos++); + if (ch !== marker && !isSpace(ch)) { + return false; + } + if (ch === marker) { + cnt++; + } + } + if (cnt < 3) { + return false; + } + if (silent) { + return true; + } + state.line = startLine + 1; + const token = state.push("hr", "hr", 0); + token.map = [startLine, state.line]; + token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); + return true; + } + // Lists + + // Search `[-+*][\n ]`, returns next pos after marker on success + // or -1 on fail. + function skipBulletListMarker(state, startLine) { + const max = state.eMarks[startLine]; + let pos = state.bMarks[startLine] + state.tShift[startLine]; + const marker = state.src.charCodeAt(pos++); + // Check bullet + if ( + marker !== 0x2a /* * */ && + marker !== 0x2d /* - */ && + marker !== 0x2b /* + */ + ) { + return -1; + } + if (pos < max) { + const ch = state.src.charCodeAt(pos); + if (!isSpace(ch)) { + // " -test " - is not a list item + return -1; + } + } + return pos; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.fetcherReturnToPromise = fetcherReturnToPromise; -exports.isAsyncIterable = isAsyncIterable; -exports.isObservable = isObservable; -exports.isPromise = isPromise; -var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -function isPromise(value) { - return typeof value === 'object' && value !== null && typeof value.then === 'function'; -} -function observableToPromise(observable) { - return new Promise((resolve, reject) => { - const subscription = observable.subscribe({ - next(v) { - resolve(v); - subscription.unsubscribe(); - }, - error: reject, - complete() { - reject(new Error('no value resolved')); - } - }); - }); -} -function isObservable(value) { - return typeof value === 'object' && value !== null && 'subscribe' in value && typeof value.subscribe === 'function'; -} -function isAsyncIterable(input) { - return typeof input === 'object' && input !== null && (input[Symbol.toStringTag] === 'AsyncGenerator' || Symbol.asyncIterator in input); -} -function asyncIterableToPromise(input) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const iteratorReturn = (_a = ('return' in input ? input : input[Symbol.asyncIterator]()).return) === null || _a === void 0 ? void 0 : _a.bind(input); - const iteratorNext = ('next' in input ? input : input[Symbol.asyncIterator]()).next.bind(input); - const result = yield iteratorNext(); - void (iteratorReturn === null || iteratorReturn === void 0 ? void 0 : iteratorReturn()); - return result.value; - }); -} -function fetcherReturnToPromise(fetcherResult) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield fetcherResult; - if (isAsyncIterable(result)) { - return asyncIterableToPromise(result); - } - if (isObservable(result)) { - return observableToPromise(result); - } - return result; - }); -} + // Search `\d+[.)][\n ]`, returns next pos after marker on success + // or -1 on fail. + function skipOrderedListMarker(state, startLine) { + const start = state.bMarks[startLine] + state.tShift[startLine]; + const max = state.eMarks[startLine]; + let pos = start; -/***/ }), + // List marker should have at least 2 chars (digit + dot) + if (pos + 1 >= max) { + return -1; + } + let ch = state.src.charCodeAt(pos++); + if (ch < 0x30 /* 0 */ || ch > 0x39 /* 9 */) { + return -1; + } + for (;;) { + // EOL -> fail + if (pos >= max) { + return -1; + } + ch = state.src.charCodeAt(pos++); + if (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) { + // List marker should have no more than 9 digits + // (prevents integer overflow in browsers) + if (pos - start >= 10) { + return -1; + } + continue; + } -/***/ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js": -/*!******************************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/createFetcher.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // found valid marker + if (ch === 0x29 /* ) */ || ch === 0x2e /* . */) { + break; + } + return -1; + } + if (pos < max) { + ch = state.src.charCodeAt(pos); + if (!isSpace(ch)) { + // " 1.test " - is not a list item + return -1; + } + } + return pos; + } + function markTightParagraphs(state, idx) { + const level = state.level + 2; + for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) { + if ( + state.tokens[i].level === level && + state.tokens[i].type === "paragraph_open" + ) { + state.tokens[i + 2].hidden = true; + state.tokens[i].hidden = true; + i += 2; + } + } + } + function list(state, startLine, endLine, silent) { + let max, pos, start, token; + let nextLine = startLine; + let tight = true; + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + return false; + } + // Special case: + // - item 1 + // - item 2 + // - item 3 + // - item 4 + // - this one is a paragraph continuation + if ( + state.listIndent >= 0 && + state.sCount[nextLine] - state.listIndent >= 4 && + state.sCount[nextLine] < state.blkIndent + ) { + return false; + } + let isTerminatingParagraph = false; + + // limit conditions when list can interrupt + // a paragraph (validation mode only) + if (silent && state.parentType === "paragraph") { + // Next list item should still terminate previous list item; + // + // This code can fail if plugins use blkIndent as well as lists, + // but I hope the spec gets fixed long before that happens. + // + if (state.sCount[nextLine] >= state.blkIndent) { + isTerminatingParagraph = true; + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createGraphiQLFetcher = createGraphiQLFetcher; -var _lib = __webpack_require__(/*! ./lib */ "../../graphiql-toolkit/esm/create-fetcher/lib.js"); -function createGraphiQLFetcher(options) { - let httpFetch; - if (typeof window !== 'undefined' && window.fetch) { - httpFetch = window.fetch; - } - if ((options === null || options === void 0 ? void 0 : options.enableIncrementalDelivery) === null || options.enableIncrementalDelivery !== false) { - options.enableIncrementalDelivery = true; - } - if (options.fetch) { - httpFetch = options.fetch; - } - if (!httpFetch) { - throw new Error('No valid fetcher implementation available'); - } - const simpleFetcher = (0, _lib.createSimpleFetcher)(options, httpFetch); - const httpFetcher = options.enableIncrementalDelivery ? (0, _lib.createMultipartFetcher)(options, httpFetch) : simpleFetcher; - return (graphQLParams, fetcherOpts) => { - if (graphQLParams.operationName === 'IntrospectionQuery') { - return (options.schemaFetcher || simpleFetcher)(graphQLParams, fetcherOpts); - } - const isSubscription = (fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.documentAST) ? (0, _lib.isSubscriptionWithName)(fetcherOpts.documentAST, graphQLParams.operationName || undefined) : false; - if (isSubscription) { - const wsFetcher = (0, _lib.getWsFetcher)(options, fetcherOpts); - if (!wsFetcher) { - throw new Error(`Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${options.subscriptionUrl ? `Provided URL ${options.subscriptionUrl} failed` : 'Please provide subscriptionUrl, wsClient or legacyClient option first.'}`); - } - return wsFetcher(graphQLParams); - } - return httpFetcher(graphQLParams, fetcherOpts); - }; -} + // Detect list type and position after marker + let isOrdered; + let markerValue; + let posAfterMarker; + if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) { + isOrdered = true; + start = state.bMarks[nextLine] + state.tShift[nextLine]; + markerValue = Number(state.src.slice(start, posAfterMarker - 1)); + + // If we're starting a new ordered list right after + // a paragraph, it should start with 1. + if (isTerminatingParagraph && markerValue !== 1) return false; + } else if ( + (posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0 + ) { + isOrdered = false; + } else { + return false; + } -/***/ }), + // If we're starting a new unordered list right after + // a paragraph, first line should not be empty. + if (isTerminatingParagraph) { + if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) + return false; + } -/***/ "../../graphiql-toolkit/esm/create-fetcher/index.js": -/*!**********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/index.js ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // For validation mode we can terminate immediately + if (silent) { + return true; + } + // We should terminate list on style change. Remember first one to compare. + const markerCharCode = state.src.charCodeAt(posAfterMarker - 1); + // Start list + const listTokIdx = state.tokens.length; + if (isOrdered) { + token = state.push("ordered_list_open", "ol", 1); + if (markerValue !== 1) { + token.attrs = [["start", markerValue]]; + } + } else { + token = state.push("bullet_list_open", "ul", 1); + } + const listLines = [nextLine, 0]; + token.map = listLines; + token.markup = String.fromCharCode(markerCharCode); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _exportNames = { - createGraphiQLFetcher: true -}; -Object.defineProperty(exports, "createGraphiQLFetcher", ({ - enumerable: true, - get: function () { - return _createFetcher.createGraphiQLFetcher; - } -})); -var _types = __webpack_require__(/*! ./types */ "../../graphiql-toolkit/esm/create-fetcher/types.js"); -Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _types[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _types[key]; - } - }); -}); -var _createFetcher = __webpack_require__(/*! ./createFetcher */ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js"); + // + // Iterate list items + // -/***/ }), + let prevEmptyEnd = false; + const terminatorRules = state.md.block.ruler.getRules("list"); + const oldParentType = state.parentType; + state.parentType = "list"; + while (nextLine < endLine) { + pos = posAfterMarker; + max = state.eMarks[nextLine]; + const initial = + state.sCount[nextLine] + + posAfterMarker - + (state.bMarks[nextLine] + state.tShift[nextLine]); + let offset = initial; + while (pos < max) { + const ch = state.src.charCodeAt(pos); + if (ch === 0x09) { + offset += 4 - ((offset + state.bsCount[nextLine]) % 4); + } else if (ch === 0x20) { + offset++; + } else { + break; + } + pos++; + } + const contentStart = pos; + let indentAfterMarker; + if (contentStart >= max) { + // trimming space in "- \n 3" case, indent is 1 here + indentAfterMarker = 1; + } else { + indentAfterMarker = offset - initial; + } -/***/ "../../graphiql-toolkit/esm/create-fetcher/lib.js": -/*!********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/lib.js ***! - \********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // If we have more than 4 spaces, the indent is 1 + // (the rest is just indented code block) + if (indentAfterMarker > 4) { + indentAfterMarker = 1; + } + // " - test" + // ^^^^^ - calculating total length of this thing + const indent = initial + indentAfterMarker; + + // Run subparser & write tokens + token = state.push("list_item_open", "li", 1); + token.markup = String.fromCharCode(markerCharCode); + const itemLines = [nextLine, 0]; + token.map = itemLines; + if (isOrdered) { + token.info = state.src.slice(start, posAfterMarker - 1); + } + // change current state, then restore it after parser subcall + const oldTight = state.tight; + const oldTShift = state.tShift[nextLine]; + const oldSCount = state.sCount[nextLine]; + + // - example list + // ^ listIndent position will be here + // ^ blkIndent position will be here + // + const oldListIndent = state.listIndent; + state.listIndent = state.blkIndent; + state.blkIndent = indent; + state.tight = true; + state.tShift[nextLine] = contentStart - state.bMarks[nextLine]; + state.sCount[nextLine] = offset; + if (contentStart >= max && state.isEmpty(nextLine + 1)) { + // workaround for this case + // (list item is empty, list terminates before "foo"): + // ~~~~~~~~ + // - + // + // foo + // ~~~~~~~~ + state.line = Math.min(state.line + 2, endLine); + } else { + state.md.block.tokenize(state, nextLine, endLine, true); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isSubscriptionWithName = exports.getWsFetcher = exports.createWebsocketsFetcherFromUrl = exports.createWebsocketsFetcherFromClient = exports.createSimpleFetcher = exports.createMultipartFetcher = exports.createLegacyWebsocketsFetcher = void 0; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _meros = __webpack_require__(/*! meros */ "../../../node_modules/meros/browser/index.js"); -var _pushPullAsyncIterableIterator = __webpack_require__(/*! @n1ru4l/push-pull-async-iterable-iterator */ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js"); -var __awaiter = void 0 && (void 0).__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 __await = void 0 && (void 0).__await || function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -}; -var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function (v) { - return new Promise(function (resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } -}; -var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -}; -const errorHasCode = err => { - return typeof err === 'object' && err !== null && 'code' in err; -}; -const isSubscriptionWithName = (document, name) => { - let isSubscription = false; - (0, _graphql.visit)(document, { - OperationDefinition(node) { - var _a; - if (name === ((_a = node.name) === null || _a === void 0 ? void 0 : _a.value) && node.operation === 'subscription') { - isSubscription = true; - } - } - }); - return isSubscription; -}; -exports.isSubscriptionWithName = isSubscriptionWithName; -const createSimpleFetcher = (options, httpFetch) => (graphQLParams, fetcherOpts) => __awaiter(void 0, void 0, void 0, function* () { - const data = yield httpFetch(options.url, { - method: 'POST', - body: JSON.stringify(graphQLParams), - headers: Object.assign(Object.assign({ - 'content-type': 'application/json' - }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) - }); - return data.json(); -}); -exports.createSimpleFetcher = createSimpleFetcher; -const createWebsocketsFetcherFromUrl = (url, connectionParams) => { - let wsClient; - try { - const { - createClient - } = __webpack_require__(/*! graphql-ws */ "../../../node_modules/graphql-ws/lib/index.js"); - wsClient = createClient({ - url, - connectionParams - }); - return createWebsocketsFetcherFromClient(wsClient); - } catch (err) { - if (errorHasCode(err) && err.code === 'MODULE_NOT_FOUND') { - throw new Error("You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'"); - } - console.error(`Error creating websocket client for ${url}`, err); - } -}; -exports.createWebsocketsFetcherFromUrl = createWebsocketsFetcherFromUrl; -const createWebsocketsFetcherFromClient = wsClient => graphQLParams => (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => wsClient.subscribe(graphQLParams, Object.assign(Object.assign({}, sink), { - error(err) { - if (err instanceof CloseEvent) { - sink.error(new Error(`Socket closed with event ${err.code} ${err.reason || ''}`.trim())); - } else { - sink.error(err); - } - } -}))); -exports.createWebsocketsFetcherFromClient = createWebsocketsFetcherFromClient; -const createLegacyWebsocketsFetcher = legacyWsClient => graphQLParams => { - const observable = legacyWsClient.request(graphQLParams); - return (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => observable.subscribe(sink).unsubscribe); -}; -exports.createLegacyWebsocketsFetcher = createLegacyWebsocketsFetcher; -const createMultipartFetcher = (options, httpFetch) => function (graphQLParams, fetcherOpts) { - return __asyncGenerator(this, arguments, function* () { - var e_1, _a; - const response = yield __await(httpFetch(options.url, { - method: 'POST', - body: JSON.stringify(graphQLParams), - headers: Object.assign(Object.assign({ - 'content-type': 'application/json', - accept: 'application/json, multipart/mixed' - }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) - }).then(r => (0, _meros.meros)(r, { - multiple: true - }))); - if (!(0, _pushPullAsyncIterableIterator.isAsyncIterable)(response)) { - return yield __await(yield yield __await(response.json())); - } - try { - for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = yield __await(response_1.next()), !response_1_1.done;) { - const chunk = response_1_1.value; - if (chunk.some(part => !part.json)) { - const message = chunk.map(part => `Headers::\n${part.headers}\n\nBody::\n${part.body}`); - throw new Error(`Expected multipart chunks to be of json type. got:\n${message}`); - } - yield yield __await(chunk.map(part => part.body)); - } - } catch (e_1_1) { - e_1 = { - error: e_1_1 - }; - } finally { - try { - if (response_1_1 && !response_1_1.done && (_a = response_1.return)) yield __await(_a.call(response_1)); - } finally { - if (e_1) throw e_1.error; - } - } - }); -}; -exports.createMultipartFetcher = createMultipartFetcher; -const getWsFetcher = (options, fetcherOpts) => { - if (options.wsClient) { - return createWebsocketsFetcherFromClient(options.wsClient); - } - if (options.subscriptionUrl) { - return createWebsocketsFetcherFromUrl(options.subscriptionUrl, Object.assign(Object.assign({}, options.wsConnectionParams), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers)); - } - const legacyWebsocketsClient = options.legacyClient || options.legacyWsClient; - if (legacyWebsocketsClient) { - return createLegacyWebsocketsFetcher(legacyWebsocketsClient); - } -}; -exports.getWsFetcher = getWsFetcher; + // If any of list item is tight, mark list as tight + if (!state.tight || prevEmptyEnd) { + tight = false; + } + // Item become loose if finish with empty line, + // but we should filter last element, because it means list finish + prevEmptyEnd = + state.line - nextLine > 1 && state.isEmpty(state.line - 1); + state.blkIndent = state.listIndent; + state.listIndent = oldListIndent; + state.tShift[nextLine] = oldTShift; + state.sCount[nextLine] = oldSCount; + state.tight = oldTight; + token = state.push("list_item_close", "li", -1); + token.markup = String.fromCharCode(markerCharCode); + nextLine = state.line; + itemLines[1] = nextLine; + if (nextLine >= endLine) { + break; + } -/***/ }), + // + // Try to check if list is terminated or continued. + // + if (state.sCount[nextLine] < state.blkIndent) { + break; + } -/***/ "../../graphiql-toolkit/esm/create-fetcher/types.js": -/*!**********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/types.js ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports) { + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + break; + } + // fail if terminating block found + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + break; + } + // fail if list has another type + if (isOrdered) { + posAfterMarker = skipOrderedListMarker(state, nextLine); + if (posAfterMarker < 0) { + break; + } + start = state.bMarks[nextLine] + state.tShift[nextLine]; + } else { + posAfterMarker = skipBulletListMarker(state, nextLine); + if (posAfterMarker < 0) { + break; + } + } + if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { + break; + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); + // Finalize list + if (isOrdered) { + token = state.push("ordered_list_close", "ol", -1); + } else { + token = state.push("bullet_list_close", "ul", -1); + } + token.markup = String.fromCharCode(markerCharCode); + listLines[1] = nextLine; + state.line = nextLine; + state.parentType = oldParentType; -/***/ }), + // mark paragraphs tight if needed + if (tight) { + markTightParagraphs(state, listTokIdx); + } + return true; + } + function reference(state, startLine, _endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + let nextLine = startLine + 1; -/***/ "../../graphiql-toolkit/esm/format/index.js": -/*!**************************************************!*\ - !*** ../../graphiql-toolkit/esm/format/index.js ***! - \**************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.formatError = formatError; -exports.formatResult = formatResult; -function stringify(obj) { - return JSON.stringify(obj, null, 2); -} -function formatSingleError(error) { - return Object.assign(Object.assign({}, error), { - message: error.message, - stack: error.stack - }); -} -function handleSingleError(error) { - if (error instanceof Error) { - return formatSingleError(error); - } - return error; -} -function formatError(error) { - if (Array.isArray(error)) { - return stringify({ - errors: error.map(e => handleSingleError(e)) - }); - } - return stringify({ - errors: [handleSingleError(error)] - }); -} -function formatResult(result) { - return stringify(result); -} + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (state.src.charCodeAt(pos) !== 0x5b /* [ */) { + return false; + } + function getNextLine(nextLine) { + const endLine = state.lineMax; + if (nextLine >= endLine || state.isEmpty(nextLine)) { + // empty line or end of input + return null; + } + let isContinuation = false; -/***/ }), + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + isContinuation = true; + } -/***/ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js": -/*!*******************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js ***! - \*******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + isContinuation = true; + } + if (!isContinuation) { + const terminatorRules = + state.md.block.ruler.getRules("reference"); + const oldParentType = state.parentType; + state.parentType = "reference"; + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + state.parentType = oldParentType; + if (terminate) { + // terminated by another block + return null; + } + } + const pos = state.bMarks[nextLine] + state.tShift[nextLine]; + const max = state.eMarks[nextLine]; + // max + 1 explicitly includes the newline + return state.src.slice(pos, max + 1); + } + let str = state.src.slice(pos, max + 1); + max = str.length; + let labelEnd = -1; + for (pos = 1; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x5b /* [ */) { + return false; + } else if (ch === 0x5d /* ] */) { + labelEnd = pos; + break; + } else if (ch === 0x0a /* \n */) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } + } else if (ch === 0x5c /* \ */) { + pos++; + if (pos < max && str.charCodeAt(pos) === 0x0a) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } + } + } + } + if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3a /* : */) { + return false; + } + // [label]: destination 'title' + // ^^^ skip optional whitespace here + for (pos = labelEnd + 2; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x0a) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } + } else if (isSpace(ch)); + else { + break; + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.fillLeafs = fillLeafs; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function fillLeafs(schema, docString, getDefaultFieldNames) { - const insertions = []; - if (!schema || !docString) { - return { - insertions, - result: docString - }; - } - let ast; - try { - ast = (0, _graphql.parse)(docString); - } catch (_a) { - return { - insertions, - result: docString - }; - } - const fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames; - const typeInfo = new _graphql.TypeInfo(schema); - (0, _graphql.visit)(ast, { - leave(node) { - typeInfo.leave(node); - }, - enter(node) { - typeInfo.enter(node); - if (node.kind === 'Field' && !node.selectionSet) { - const fieldType = typeInfo.getType(); - const selectionSet = buildSelectionSet(isFieldType(fieldType), fieldNameFn); - if (selectionSet && node.loc) { - const indent = getIndentation(docString, node.loc.start); - insertions.push({ - index: node.loc.end, - string: ' ' + (0, _graphql.print)(selectionSet).replaceAll('\n', '\n' + indent) - }); - } - } - } - }); - return { - insertions, - result: withInsertions(docString, insertions) - }; -} -function defaultGetDefaultFieldNames(type) { - if (!('getFields' in type)) { - return []; - } - const fields = type.getFields(); - if (fields.id) { - return ['id']; - } - if (fields.edges) { - return ['edges']; - } - if (fields.node) { - return ['node']; - } - const leafFieldNames = []; - for (const fieldName of Object.keys(fields)) { - if ((0, _graphql.isLeafType)(fields[fieldName].type)) { - leafFieldNames.push(fieldName); - } - } - return leafFieldNames; -} -function buildSelectionSet(type, getDefaultFieldNames) { - const namedType = (0, _graphql.getNamedType)(type); - if (!type || (0, _graphql.isLeafType)(type)) { - return; - } - const fieldNames = getDefaultFieldNames(namedType); - if (!Array.isArray(fieldNames) || fieldNames.length === 0 || !('getFields' in namedType)) { - return; - } - return { - kind: _graphql.Kind.SELECTION_SET, - selections: fieldNames.map(fieldName => { - const fieldDef = namedType.getFields()[fieldName]; - const fieldType = fieldDef ? fieldDef.type : null; - return { - kind: _graphql.Kind.FIELD, - name: { - kind: _graphql.Kind.NAME, - value: fieldName - }, - selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames) - }; - }) - }; -} -function withInsertions(initial, insertions) { - if (insertions.length === 0) { - return initial; - } - let edited = ''; - let prevIndex = 0; - for (const { - index, - string - } of insertions) { - edited += initial.slice(prevIndex, index) + string; - prevIndex = index; - } - edited += initial.slice(prevIndex); - return edited; -} -function getIndentation(str, index) { - let indentStart = index; - let indentEnd = index; - while (indentStart) { - const c = str.charCodeAt(indentStart - 1); - if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { - break; - } - indentStart--; - if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { - indentEnd = indentStart; - } - } - return str.slice(indentStart, indentEnd); -} -function isFieldType(fieldType) { - if (fieldType) { - return fieldType; - } -} + // [label]: destination 'title' + // ^^^^^^^^^^^ parse this + const destRes = state.md.helpers.parseLinkDestination(str, pos, max); + if (!destRes.ok) { + return false; + } + const href = state.md.normalizeLink(destRes.str); + if (!state.md.validateLink(href)) { + return false; + } + pos = destRes.pos; + + // save cursor state, we could require to rollback later + const destEndPos = pos; + const destEndLineNo = nextLine; + + // [label]: destination 'title' + // ^^^ skipping those spaces + const start = pos; + for (; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x0a) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } + } else if (isSpace(ch)); + else { + break; + } + } -/***/ }), + // [label]: destination 'title' + // ^^^^^^^ parse this + let titleRes = state.md.helpers.parseLinkTitle(str, pos, max); + while (titleRes.can_continue) { + const lineContent = getNextLine(nextLine); + if (lineContent === null) break; + str += lineContent; + pos = max; + max = str.length; + nextLine++; + titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes); + } + let title; + if (pos < max && start !== pos && titleRes.ok) { + title = titleRes.str; + pos = titleRes.pos; + } else { + title = ""; + pos = destEndPos; + nextLine = destEndLineNo; + } -/***/ "../../graphiql-toolkit/esm/graphql-helpers/index.js": -/*!***********************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/index.js ***! - \***********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // skip trailing spaces until the rest of the line + while (pos < max) { + const ch = str.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } + pos++; + } + if (pos < max && str.charCodeAt(pos) !== 0x0a) { + if (title) { + // garbage at the end of the line after title, + // but it could still be a valid reference if we roll back + title = ""; + pos = destEndPos; + nextLine = destEndLineNo; + while (pos < max) { + const ch = str.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } + pos++; + } + } + } + if (pos < max && str.charCodeAt(pos) !== 0x0a) { + // garbage at the end of the line + return false; + } + const label = normalizeReference(str.slice(1, labelEnd)); + if (!label) { + // CommonMark 0.20 disallows empty labels + return false; + } + // Reference can not terminate anything. This check is for safety only. + /* istanbul ignore if */ + if (silent) { + return true; + } + if (typeof state.env.references === "undefined") { + state.env.references = {}; + } + if (typeof state.env.references[label] === "undefined") { + state.env.references[label] = { + title, + href, + }; + } + state.line = nextLine; + return true; + } + // List of valid html blocks names, according to commonmark spec + // https://spec.commonmark.org/0.30/#html-blocks + + var block_names = [ + "address", + "article", + "aside", + "base", + "basefont", + "blockquote", + "body", + "caption", + "center", + "col", + "colgroup", + "dd", + "details", + "dialog", + "dir", + "div", + "dl", + "dt", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hr", + "html", + "iframe", + "legend", + "li", + "link", + "main", + "menu", + "menuitem", + "nav", + "noframes", + "ol", + "optgroup", + "option", + "p", + "param", + "search", + "section", + "summary", + "table", + "tbody", + "td", + "tfoot", + "th", + "thead", + "title", + "tr", + "track", + "ul", + ]; + + // Regexps to match html elements + + const attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*"; + const unquoted = "[^\"'=<>`\\x00-\\x20]+"; + const single_quoted = "'[^']*'"; + const double_quoted = '"[^"]*"'; + const attr_value = + "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")"; + const attribute = + "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)"; + const open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>"; + const close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>"; + const comment = ""; + const processing = "<[?][\\s\\S]*?[?]>"; + const declaration = "]*>"; + const cdata = ""; + const HTML_TAG_RE = new RegExp( + "^(?:" + + open_tag + + "|" + + close_tag + + "|" + + comment + + "|" + + processing + + "|" + + declaration + + "|" + + cdata + + ")" + ); + const HTML_OPEN_CLOSE_TAG_RE = new RegExp( + "^(?:" + open_tag + "|" + close_tag + ")" + ); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _autoComplete = __webpack_require__(/*! ./auto-complete */ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js"); -Object.keys(_autoComplete).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _autoComplete[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _autoComplete[key]; - } - }); -}); -var _mergeAst = __webpack_require__(/*! ./merge-ast */ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js"); -Object.keys(_mergeAst).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _mergeAst[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _mergeAst[key]; - } - }); -}); -var _operationName = __webpack_require__(/*! ./operation-name */ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js"); -Object.keys(_operationName).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _operationName[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _operationName[key]; - } - }); -}); + // HTML block -/***/ }), + // An array of opening and corresponding closing sequences for html tags, + // last argument defines whether it can terminate a paragraph or not + // + const HTML_SEQUENCES = [ + [ + /^<(script|pre|style|textarea)(?=(\s|>|$))/i, + /<\/(script|pre|style|textarea)>/i, + true, + ], + [/^/, true], + [/^<\?/, /\?>/, true], + [/^/, true], + [/^/, true], + [ + new RegExp( + "^|$))", + "i" + ), + /^$/, + true, + ], + [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false], + ]; + function html_block(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (!state.md.options.html) { + return false; + } + if (state.src.charCodeAt(pos) !== 0x3c /* < */) { + return false; + } + let lineText = state.src.slice(pos, max); + let i = 0; + for (; i < HTML_SEQUENCES.length; i++) { + if (HTML_SEQUENCES[i][0].test(lineText)) { + break; + } + } + if (i === HTML_SEQUENCES.length) { + return false; + } + if (silent) { + // true if this sequence can be a terminator, false otherwise + return HTML_SEQUENCES[i][2]; + } + let nextLine = startLine + 1; -/***/ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js": -/*!***************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js ***! - \***************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.mergeAst = mergeAst; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function uniqueBy(array, iteratee) { - var _a; - const FilteredMap = new Map(); - const result = []; - for (const item of array) { - if (item.kind === 'Field') { - const uniqueValue = iteratee(item); - const existing = FilteredMap.get(uniqueValue); - if ((_a = item.directives) === null || _a === void 0 ? void 0 : _a.length) { - const itemClone = Object.assign({}, item); - result.push(itemClone); - } else if ((existing === null || existing === void 0 ? void 0 : existing.selectionSet) && item.selectionSet) { - existing.selectionSet.selections = [...existing.selectionSet.selections, ...item.selectionSet.selections]; - } else if (!existing) { - const itemClone = Object.assign({}, item); - FilteredMap.set(uniqueValue, itemClone); - result.push(itemClone); - } - } else { - result.push(item); - } - } - return result; -} -function inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType) { - var _a; - const selectionSetTypeName = selectionSetType ? (0, _graphql.getNamedType)(selectionSetType).name : null; - const outputSelections = []; - const seenSpreads = []; - for (let selection of selections) { - if (selection.kind === 'FragmentSpread') { - const fragmentName = selection.name.value; - if (!selection.directives || selection.directives.length === 0) { - if (seenSpreads.includes(fragmentName)) { - continue; - } else { - seenSpreads.push(fragmentName); + // If we are here - we detected HTML block. + // Let's roll down till block end. + if (!HTML_SEQUENCES[i][1].test(lineText)) { + for (; nextLine < endLine; nextLine++) { + if (state.sCount[nextLine] < state.blkIndent) { + break; + } + pos = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + lineText = state.src.slice(pos, max); + if (HTML_SEQUENCES[i][1].test(lineText)) { + if (lineText.length !== 0) { + nextLine++; + } + break; + } + } + } + state.line = nextLine; + const token = state.push("html_block", "", 0); + token.map = [startLine, nextLine]; + token.content = state.getLines( + startLine, + nextLine, + state.blkIndent, + true + ); + return true; } - } - const fragmentDefinition = fragmentDefinitions[selection.name.value]; - if (fragmentDefinition) { - const { - typeCondition, - directives, - selectionSet - } = fragmentDefinition; - selection = { - kind: _graphql.Kind.INLINE_FRAGMENT, - typeCondition, - directives, - selectionSet - }; - } - } - if (selection.kind === _graphql.Kind.INLINE_FRAGMENT && (!selection.directives || ((_a = selection.directives) === null || _a === void 0 ? void 0 : _a.length) === 0)) { - const fragmentTypeName = selection.typeCondition ? selection.typeCondition.name.value : null; - if (!fragmentTypeName || fragmentTypeName === selectionSetTypeName) { - outputSelections.push(...inlineRelevantFragmentSpreads(fragmentDefinitions, selection.selectionSet.selections, selectionSetType)); - continue; - } - } - outputSelections.push(selection); - } - return outputSelections; -} -function mergeAst(documentAST, schema) { - const typeInfo = schema ? new _graphql.TypeInfo(schema) : null; - const fragmentDefinitions = Object.create(null); - for (const definition of documentAST.definitions) { - if (definition.kind === _graphql.Kind.FRAGMENT_DEFINITION) { - fragmentDefinitions[definition.name.value] = definition; - } - } - const flattenVisitors = { - SelectionSet(node) { - const selectionSetType = typeInfo ? typeInfo.getParentType() : null; - let { - selections - } = node; - selections = inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType); - return Object.assign(Object.assign({}, node), { - selections - }); - }, - FragmentDefinition() { - return null; - } - }; - const flattenedAST = (0, _graphql.visit)(documentAST, typeInfo ? (0, _graphql.visitWithTypeInfo)(typeInfo, flattenVisitors) : flattenVisitors); - const deduplicateVisitors = { - SelectionSet(node) { - let { - selections - } = node; - selections = uniqueBy(selections, selection => selection.alias ? selection.alias.value : selection.name.value); - return Object.assign(Object.assign({}, node), { - selections - }); - }, - FragmentDefinition() { - return null; - } - }; - return (0, _graphql.visit)(flattenedAST, deduplicateVisitors); -} -/***/ }), + // heading (#, ##, ...) -/***/ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js": -/*!********************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/operation-name.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + function heading(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + let ch = state.src.charCodeAt(pos); + if (ch !== 0x23 /* # */ || pos >= max) { + return false; + } + // count heading level + let level = 1; + ch = state.src.charCodeAt(++pos); + while (ch === 0x23 /* # */ && pos < max && level <= 6) { + level++; + ch = state.src.charCodeAt(++pos); + } + if (level > 6 || (pos < max && !isSpace(ch))) { + return false; + } + if (silent) { + return true; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getSelectedOperationName = getSelectedOperationName; -function getSelectedOperationName(prevOperations, prevSelectedOperationName, operations) { - if (!operations || operations.length < 1) { - return; - } - const names = operations.map(op => { - var _a; - return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; - }); - if (prevSelectedOperationName && names.includes(prevSelectedOperationName)) { - return prevSelectedOperationName; - } - if (prevSelectedOperationName && prevOperations) { - const prevNames = prevOperations.map(op => { - var _a; - return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; - }); - const prevIndex = prevNames.indexOf(prevSelectedOperationName); - if (prevIndex !== -1 && prevIndex < names.length) { - return names[prevIndex]; - } - } - return names[0]; -} + // Let's cut tails like ' ### ' from the end of string -/***/ }), + max = state.skipSpacesBack(max, pos); + const tmp = state.skipCharsBack(max, 0x23, pos); // # + if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { + max = tmp; + } + state.line = startLine + 1; + const token_o = state.push("heading_open", "h" + String(level), 1); + token_o.markup = "########".slice(0, level); + token_o.map = [startLine, state.line]; + const token_i = state.push("inline", "", 0); + token_i.content = state.src.slice(pos, max).trim(); + token_i.map = [startLine, state.line]; + token_i.children = []; + const token_c = state.push("heading_close", "h" + String(level), -1); + token_c.markup = "########".slice(0, level); + return true; + } -/***/ "../../graphiql-toolkit/esm/index.js": -/*!*******************************************!*\ - !*** ../../graphiql-toolkit/esm/index.js ***! - \*******************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // lheading (---, ===) + function lheading(state, startLine, endLine /*, silent */) { + const terminatorRules = state.md.block.ruler.getRules("paragraph"); + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + const oldParentType = state.parentType; + state.parentType = "paragraph"; // use paragraph to match terminatorRules + + // jump line-by-line until empty one or EOF + let level = 0; + let marker; + let nextLine = startLine + 1; + for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + continue; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _asyncHelpers = __webpack_require__(/*! ./async-helpers */ "../../graphiql-toolkit/esm/async-helpers/index.js"); -Object.keys(_asyncHelpers).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _asyncHelpers[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _asyncHelpers[key]; - } - }); -}); -var _createFetcher = __webpack_require__(/*! ./create-fetcher */ "../../graphiql-toolkit/esm/create-fetcher/index.js"); -Object.keys(_createFetcher).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _createFetcher[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _createFetcher[key]; - } - }); -}); -var _format = __webpack_require__(/*! ./format */ "../../graphiql-toolkit/esm/format/index.js"); -Object.keys(_format).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _format[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _format[key]; - } - }); -}); -var _graphqlHelpers = __webpack_require__(/*! ./graphql-helpers */ "../../graphiql-toolkit/esm/graphql-helpers/index.js"); -Object.keys(_graphqlHelpers).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _graphqlHelpers[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _graphqlHelpers[key]; - } - }); -}); -var _storage = __webpack_require__(/*! ./storage */ "../../graphiql-toolkit/esm/storage/index.js"); -Object.keys(_storage).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _storage[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _storage[key]; - } - }); -}); + // + // Check for underline in setext header + // + if (state.sCount[nextLine] >= state.blkIndent) { + let pos = state.bMarks[nextLine] + state.tShift[nextLine]; + const max = state.eMarks[nextLine]; + if (pos < max) { + marker = state.src.charCodeAt(pos); + if (marker === 0x2d /* - */ || marker === 0x3d /* = */) { + pos = state.skipChars(pos, marker); + pos = state.skipSpaces(pos); + if (pos >= max) { + level = marker === 0x3d /* = */ ? 1 : 2; + break; + } + } + } + } -/***/ }), + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + continue; + } -/***/ "../../graphiql-toolkit/esm/storage/base.js": -/*!**************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/base.js ***! - \**************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.StorageAPI = void 0; -function isQuotaError(storage, e) { - return e instanceof DOMException && (e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && storage.length !== 0; -} -class StorageAPI { - constructor(storage) { - if (storage) { - this.storage = storage; - } else if (storage === null) { - this.storage = null; - } else if (typeof window === 'undefined') { - this.storage = null; - } else { - this.storage = { - getItem: localStorage.getItem.bind(localStorage), - setItem: localStorage.setItem.bind(localStorage), - removeItem: localStorage.removeItem.bind(localStorage), - get length() { - let keys = 0; - for (const key in localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - keys += 1; - } - } - return keys; - }, - clear() { - for (const key in localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - localStorage.removeItem(key); - } - } - } - }; - } - } - get(name) { - if (!this.storage) { - return null; - } - const key = `${STORAGE_NAMESPACE}:${name}`; - const value = this.storage.getItem(key); - if (value === 'null' || value === 'undefined') { - this.storage.removeItem(key); - return null; - } - return value || null; - } - set(name, value) { - let quotaError = false; - let error = null; - if (this.storage) { - const key = `${STORAGE_NAMESPACE}:${name}`; - if (value) { - try { - this.storage.setItem(key, value); - } catch (e) { - error = e instanceof Error ? e : new Error(`${e}`); - quotaError = isQuotaError(this.storage, e); + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + break; + } + } + if (!level) { + // Didn't find valid underline + return false; + } + const content = state + .getLines(startLine, nextLine, state.blkIndent, false) + .trim(); + state.line = nextLine + 1; + const token_o = state.push("heading_open", "h" + String(level), 1); + token_o.markup = String.fromCharCode(marker); + token_o.map = [startLine, state.line]; + const token_i = state.push("inline", "", 0); + token_i.content = content; + token_i.map = [startLine, state.line - 1]; + token_i.children = []; + const token_c = state.push("heading_close", "h" + String(level), -1); + token_c.markup = String.fromCharCode(marker); + state.parentType = oldParentType; + return true; } - } else { - this.storage.removeItem(key); - } - } - return { - isQuotaError: quotaError, - error - }; - } - clear() { - if (this.storage) { - this.storage.clear(); - } - } -} -exports.StorageAPI = StorageAPI; -const STORAGE_NAMESPACE = 'graphiql'; -/***/ }), - -/***/ "../../graphiql-toolkit/esm/storage/custom.js": -/*!****************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/custom.js ***! - \****************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.createLocalStorage = createLocalStorage; -function createLocalStorage({ - namespace -}) { - const storageKeyPrefix = `${namespace}:`; - const getStorageKey = key => `${storageKeyPrefix}${key}`; - const storage = { - setItem: (key, value) => localStorage.setItem(getStorageKey(key), value), - getItem: key => localStorage.getItem(getStorageKey(key)), - removeItem: key => localStorage.removeItem(getStorageKey(key)), - get length() { - let keys = 0; - for (const key in localStorage) { - if (key.indexOf(storageKeyPrefix) === 0) { - keys += 1; - } - } - return keys; - }, - clear() { - for (const key in localStorage) { - if (key.indexOf(storageKeyPrefix) === 0) { - localStorage.removeItem(key); - } - } - } - }; - return storage; -} + // Paragraph -/***/ }), + function paragraph(state, startLine, endLine) { + const terminatorRules = state.md.block.ruler.getRules("paragraph"); + const oldParentType = state.parentType; + let nextLine = startLine + 1; + state.parentType = "paragraph"; -/***/ "../../graphiql-toolkit/esm/storage/history.js": -/*!*****************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/history.js ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.HistoryStore = void 0; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); -const MAX_QUERY_SIZE = 100000; -class HistoryStore { - constructor(storage, maxHistoryLength) { - this.storage = storage; - this.maxHistoryLength = maxHistoryLength; - this.updateHistory = ({ - query, - variables, - headers, - operationName - }) => { - if (!this.shouldSaveQuery(query, variables, headers, this.history.fetchRecent())) { - return; - } - this.history.push({ - query, - variables, - headers, - operationName - }); - const historyQueries = this.history.items; - const favoriteQueries = this.favorite.items; - this.queries = historyQueries.concat(favoriteQueries); - }; - this.deleteHistory = ({ - query, - variables, - headers, - operationName, - favorite - }, clearFavorites = false) => { - function deleteFromStore(store) { - const found = store.items.find(x => x.query === query && x.variables === variables && x.headers === headers && x.operationName === operationName); - if (found) { - store.delete(found); - } - } - if (favorite || clearFavorites) { - deleteFromStore(this.favorite); - } - if (!favorite || clearFavorites) { - deleteFromStore(this.history); - } - this.queries = [...this.history.items, ...this.favorite.items]; - }; - this.history = new _query.QueryStore('queries', this.storage, this.maxHistoryLength); - this.favorite = new _query.QueryStore('favorites', this.storage, null); - this.queries = [...this.history.fetchAll(), ...this.favorite.fetchAll()]; - } - shouldSaveQuery(query, variables, headers, lastQuerySaved) { - if (!query) { - return false; - } - try { - (0, _graphql.parse)(query); - } catch (_a) { - return false; - } - if (query.length > MAX_QUERY_SIZE) { - return false; - } - if (!lastQuerySaved) { - return true; - } - if (JSON.stringify(query) === JSON.stringify(lastQuerySaved.query)) { - if (JSON.stringify(variables) === JSON.stringify(lastQuerySaved.variables)) { - if (JSON.stringify(headers) === JSON.stringify(lastQuerySaved.headers)) { - return false; - } - if (headers && !lastQuerySaved.headers) { - return false; - } - } - if (variables && !lastQuerySaved.variables) { - return false; - } - } - return true; - } - toggleFavorite({ - query, - variables, - headers, - operationName, - label, - favorite - }) { - const item = { - query, - variables, - headers, - operationName, - label - }; - if (favorite) { - item.favorite = false; - this.favorite.delete(item); - this.history.push(item); - } else { - item.favorite = true; - this.favorite.push(item); - this.history.delete(item); - } - this.queries = [...this.history.items, ...this.favorite.items]; - } - editLabel({ - query, - variables, - headers, - operationName, - label, - favorite - }, index) { - const item = { - query, - variables, - headers, - operationName, - label - }; - if (favorite) { - this.favorite.edit(Object.assign(Object.assign({}, item), { - favorite - }), index); - } else { - this.history.edit(item, index); - } - this.queries = [...this.history.items, ...this.favorite.items]; - } -} -exports.HistoryStore = HistoryStore; + // jump line-by-line until empty one or EOF + for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + continue; + } -/***/ }), + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + continue; + } -/***/ "../../graphiql-toolkit/esm/storage/index.js": -/*!***************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/index.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + break; + } + } + const content = state + .getLines(startLine, nextLine, state.blkIndent, false) + .trim(); + state.line = nextLine; + const token_o = state.push("paragraph_open", "p", 1); + token_o.map = [startLine, state.line]; + const token_i = state.push("inline", "", 0); + token_i.content = content; + token_i.map = [startLine, state.line]; + token_i.children = []; + state.push("paragraph_close", "p", -1); + state.parentType = oldParentType; + return true; + } + /** internal + * class ParserBlock + * + * Block-level tokenizer. + **/ + + const _rules$1 = [ + // First 2 params - rule name & source. Secondary array - list of rules, + // which can be terminated by this one. + ["table", table, ["paragraph", "reference"]], + ["code", code], + ["fence", fence, ["paragraph", "reference", "blockquote", "list"]], + [ + "blockquote", + blockquote, + ["paragraph", "reference", "blockquote", "list"], + ], + ["hr", hr, ["paragraph", "reference", "blockquote", "list"]], + ["list", list, ["paragraph", "reference", "blockquote"]], + ["reference", reference], + ["html_block", html_block, ["paragraph", "reference", "blockquote"]], + ["heading", heading, ["paragraph", "reference", "blockquote"]], + ["lheading", lheading], + ["paragraph", paragraph], + ]; + /** + * new ParserBlock() + **/ + function ParserBlock() { + /** + * ParserBlock#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of block rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules$1.length; i++) { + this.ruler.push(_rules$1[i][0], _rules$1[i][1], { + alt: (_rules$1[i][2] || []).slice(), + }); + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _base = __webpack_require__(/*! ./base */ "../../graphiql-toolkit/esm/storage/base.js"); -Object.keys(_base).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _base[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _base[key]; - } - }); -}); -var _history = __webpack_require__(/*! ./history */ "../../graphiql-toolkit/esm/storage/history.js"); -Object.keys(_history).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _history[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _history[key]; - } - }); -}); -var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); -Object.keys(_query).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _query[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _query[key]; - } - }); -}); -var _custom = __webpack_require__(/*! ./custom */ "../../graphiql-toolkit/esm/storage/custom.js"); -Object.keys(_custom).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _custom[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _custom[key]; - } - }); -}); + // Generate tokens for input range + // + ParserBlock.prototype.tokenize = function (state, startLine, endLine) { + const rules = this.ruler.getRules(""); + const len = rules.length; + const maxNesting = state.md.options.maxNesting; + let line = startLine; + let hasEmptyLines = false; + while (line < endLine) { + state.line = line = state.skipEmptyLines(line); + if (line >= endLine) { + break; + } -/***/ }), + // Termination condition for nested calls. + // Nested calls currently used for blockquotes & lists + if (state.sCount[line] < state.blkIndent) { + break; + } -/***/ "../../graphiql-toolkit/esm/storage/query.js": -/*!***************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/query.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports) { + // If nesting level exceeded - skip tail to the end. That's not ordinary + // situation and we should not care about content. + if (state.level >= maxNesting) { + state.line = endLine; + break; + } + // Try all possible rules. + // On success, rule should: + // + // - update `state.line` + // - update `state.tokens` + // - return true + const prevLine = state.line; + let ok = false; + for (let i = 0; i < len; i++) { + ok = rules[i](state, line, endLine, false); + if (ok) { + if (prevLine >= state.line) { + throw new Error("block rule didn't increment state.line"); + } + break; + } + } + // this can only happen if user disables paragraph rule + if (!ok) throw new Error("none of the block rules matched"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.QueryStore = void 0; -class QueryStore { - constructor(key, storage, maxSize = null) { - this.key = key; - this.storage = storage; - this.maxSize = maxSize; - this.items = this.fetchAll(); - } - get length() { - return this.items.length; - } - contains(item) { - return this.items.some(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); - } - edit(item, index) { - if (typeof index === 'number' && this.items[index]) { - const found = this.items[index]; - if (found.query === item.query && found.variables === item.variables && found.headers === item.headers && found.operationName === item.operationName) { - this.items.splice(index, 1, item); - this.save(); - return; - } - } - const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); - if (itemIndex !== -1) { - this.items.splice(itemIndex, 1, item); - this.save(); - } - } - delete(item) { - const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); - if (itemIndex !== -1) { - this.items.splice(itemIndex, 1); - this.save(); - } - } - fetchRecent() { - return this.items.at(-1); - } - fetchAll() { - const raw = this.storage.get(this.key); - if (raw) { - return JSON.parse(raw)[this.key]; - } - return []; - } - push(item) { - const items = [...this.items, item]; - if (this.maxSize && items.length > this.maxSize) { - items.shift(); - } - for (let attempts = 0; attempts < 5; attempts++) { - const response = this.storage.set(this.key, JSON.stringify({ - [this.key]: items - })); - if (!(response === null || response === void 0 ? void 0 : response.error)) { - this.items = items; - } else if (response.isQuotaError && this.maxSize) { - items.shift(); - } else { - return; - } - } - } - save() { - this.storage.set(this.key, JSON.stringify({ - [this.key]: this.items - })); - } -} -exports.QueryStore = QueryStore; + // set state.tight if we had an empty line before current tag + // i.e. latest empty line should not count + state.tight = !hasEmptyLines; -/***/ }), + // paragraph might "eat" one newline after it in nested lists + if (state.isEmpty(state.line - 1)) { + hasEmptyLines = true; + } + line = state.line; + if (line < endLine && state.isEmpty(line)) { + hasEmptyLines = true; + line++; + state.line = line; + } + } + }; -/***/ "../node_modules/linkify-it/build/index.cjs.js": -/*!*****************************************************!*\ - !*** ../node_modules/linkify-it/build/index.cjs.js ***! - \*****************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - -var uc_micro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); -function reFactory(opts) { - const re = {}; - opts = opts || {}; - re.src_Any = uc_micro.Any.source; - re.src_Cc = uc_micro.Cc.source; - re.src_Z = uc_micro.Z.source; - re.src_P = uc_micro.P.source; - - // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) - re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join('|'); - - // \p{\Z\Cc} (white spaces + control) - re.src_ZCc = [re.src_Z, re.src_Cc].join('|'); - - // Experimental. List of chars, completely prohibited in links - // because can separate it from other part of text - const text_separators = '[><\uff5c]'; - - // All possible word characters (everything without punctuation, spaces & controls) - // Defined via punctuation & spaces to save space - // Should be something like \p{\L\N\S\M} (\w but without `_`) - re.src_pseudo_letter = '(?:(?!' + text_separators + '|' + re.src_ZPCc + ')' + re.src_Any + ')'; - // The same as abothe but without [0-9] - // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; - - re.src_ip4 = '(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'; - - // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. - re.src_auth = '(?:(?:(?!' + re.src_ZCc + '|[@/\\[\\]()]).)+@)?'; - re.src_port = '(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?'; - re.src_host_terminator = '(?=$|' + text_separators + '|' + re.src_ZPCc + ')' + '(?!' + (opts['---'] ? '-(?!--)|' : '-|') + '_|:\\d|\\.-|\\.(?!$|' + re.src_ZPCc + '))'; - re.src_path = '(?:' + '[/?#]' + '(?:' + '(?!' + re.src_ZCc + '|' + text_separators + '|[()[\\]{}.,"\'?!\\-;]).|' + '\\[(?:(?!' + re.src_ZCc + '|\\]).)*\\]|' + '\\((?:(?!' + re.src_ZCc + '|[)]).)*\\)|' + '\\{(?:(?!' + re.src_ZCc + '|[}]).)*\\}|' + '\\"(?:(?!' + re.src_ZCc + '|["]).)+\\"|' + "\\'(?:(?!" + re.src_ZCc + "|[']).)+\\'|" + - // allow `I'm_king` if no pair found - "\\'(?=" + re.src_pseudo_letter + '|[-])|' + - // google has many dots in "google search" links (#66, #81). - // github has ... in commit range links, - // Restrict to - // - english - // - percent-encoded - // - parts of file path - // - params separator - // until more examples found. - '\\.{2,}[a-zA-Z0-9%/&]|' + '\\.(?!' + re.src_ZCc + '|[.]|$)|' + (opts['---'] ? '\\-(?!--(?:[^-]|$))(?:-*)|' // `---` => long dash, terminate - : '\\-+|') + - // allow `,,,` in paths - ',(?!' + re.src_ZCc + '|$)|' + - // allow `;` if not followed by space-like char - ';(?!' + re.src_ZCc + '|$)|' + - // allow `!!!` in paths, but not at the end - '\\!+(?!' + re.src_ZCc + '|[!]|$)|' + '\\?(?!' + re.src_ZCc + '|[?]|$)' + ')+' + '|\\/' + ')?'; - - // Allow anything in markdown spec, forbid quote (") at the first position - // because emails enclosed in quotes are far more common - re.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; - re.src_xn = 'xn--[a-z0-9\\-]{1,59}'; - - // More to read about domain names - // http://serverfault.com/questions/638260/ - - re.src_domain_root = - // Allow letters & digits (http://test1) - '(?:' + re.src_xn + '|' + re.src_pseudo_letter + '{1,63}' + ')'; - re.src_domain = '(?:' + re.src_xn + '|' + '(?:' + re.src_pseudo_letter + ')' + '|' + '(?:' + re.src_pseudo_letter + '(?:-|' + re.src_pseudo_letter + '){0,61}' + re.src_pseudo_letter + ')' + ')'; - re.src_host = '(?:' + - // Don't need IP check, because digits are already allowed in normal domain names - // src_ip4 + - // '|' + - '(?:(?:(?:' + re.src_domain + ')\\.)*' + re.src_domain /* _root */ + ')' + ')'; - re.tpl_host_fuzzy = '(?:' + re.src_ip4 + '|' + '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))' + ')'; - re.tpl_host_no_ip_fuzzy = '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))'; - re.src_host_strict = re.src_host + re.src_host_terminator; - re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; - re.src_host_port_strict = re.src_host + re.src_port + re.src_host_terminator; - re.tpl_host_port_fuzzy_strict = re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; - re.tpl_host_port_no_ip_fuzzy_strict = re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; - - // - // Main rules - // - - // Rude test fuzzy links by host, for quick deny - re.tpl_host_fuzzy_test = 'localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:' + re.src_ZPCc + '|>|$))'; - re.tpl_email_fuzzy = '(^|' + text_separators + '|"|\\(|' + re.src_ZCc + ')' + '(' + re.src_email_name + '@' + re.tpl_host_fuzzy_strict + ')'; - re.tpl_link_fuzzy = - // Fuzzy link can't be prepended with .:/\- and non punctuation. - // but can start with > (markdown blockquote) - '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_fuzzy_strict + re.src_path + ')'; - re.tpl_link_no_ip_fuzzy = - // Fuzzy link can't be prepended with .:/\- and non punctuation. - // but can start with > (markdown blockquote) - '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_no_ip_fuzzy_strict + re.src_path + ')'; - return re; -} - -// -// Helpers -// - -// Merge objects -// -function assign(obj /* from1, from2, from3, ... */) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; - } - Object.keys(source).forEach(function (key) { - obj[key] = source[key]; - }); - }); - return obj; -} -function _class(obj) { - return Object.prototype.toString.call(obj); -} -function isString(obj) { - return _class(obj) === '[object String]'; -} -function isObject(obj) { - return _class(obj) === '[object Object]'; -} -function isRegExp(obj) { - return _class(obj) === '[object RegExp]'; -} -function isFunction(obj) { - return _class(obj) === '[object Function]'; -} -function escapeRE(str) { - return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); -} - -// - -const defaultOptions = { - fuzzyLink: true, - fuzzyEmail: true, - fuzzyIP: false -}; -function isOptionsObj(obj) { - return Object.keys(obj || {}).reduce(function (acc, k) { - /* eslint-disable-next-line no-prototype-builtins */ - return acc || defaultOptions.hasOwnProperty(k); - }, false); -} -const defaultSchemas = { - 'http:': { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.http) { - // compile lazily, because "host"-containing variables can change on tlds update. - self.re.http = new RegExp('^\\/\\/' + self.re.src_auth + self.re.src_host_port_strict + self.re.src_path, 'i'); - } - if (self.re.http.test(tail)) { - return tail.match(self.re.http)[0].length; - } - return 0; - } - }, - 'https:': 'http:', - 'ftp:': 'http:', - '//': { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.no_http) { - // compile lazily, because "host"-containing variables can change on tlds update. - self.re.no_http = new RegExp('^' + self.re.src_auth + - // Don't allow single-level domains, because of false positives like '//test' - // with code comments - '(?:localhost|(?:(?:' + self.re.src_domain + ')\\.)+' + self.re.src_domain_root + ')' + self.re.src_port + self.re.src_host_terminator + self.re.src_path, 'i'); - } - if (self.re.no_http.test(tail)) { - // should not be `://` & `///`, that protects from errors in protocol name - if (pos >= 3 && text[pos - 3] === ':') { - return 0; - } - if (pos >= 3 && text[pos - 3] === '/') { - return 0; - } - return tail.match(self.re.no_http)[0].length; - } - return 0; - } - }, - 'mailto:': { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.mailto) { - self.re.mailto = new RegExp('^' + self.re.src_email_name + '@' + self.re.src_host_strict, 'i'); - } - if (self.re.mailto.test(tail)) { - return tail.match(self.re.mailto)[0].length; - } - return 0; - } - } -}; + /** + * ParserBlock.parse(str, md, env, outTokens) + * + * Process input string and push block tokens into `outTokens` + **/ + ParserBlock.prototype.parse = function (src, md, env, outTokens) { + if (!src) { + return; + } + const state = new this.State(src, md, env, outTokens); + this.tokenize(state, state.line, state.lineMax); + }; + ParserBlock.prototype.State = StateBlock; -// RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) -/* eslint-disable-next-line max-len */ -const tlds_2ch_src_re = 'a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]'; - -// DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead -const tlds_default = 'biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф'.split('|'); -function resetScanCache(self) { - self.__index__ = -1; - self.__text_cache__ = ''; -} -function createValidator(re) { - return function (text, pos) { - const tail = text.slice(pos); - if (re.test(tail)) { - return tail.match(re)[0].length; - } - return 0; - }; -} -function createNormalizer() { - return function (match, self) { - self.normalize(match); - }; -} - -// Schemas compiler. Build regexps. -// -function compile(self) { - // Load & clone RE patterns. - const re = self.re = reFactory(self.__opts__); - - // Define dynamic patterns - const tlds = self.__tlds__.slice(); - self.onCompile(); - if (!self.__tlds_replaced__) { - tlds.push(tlds_2ch_src_re); - } - tlds.push(re.src_xn); - re.src_tlds = tlds.join('|'); - function untpl(tpl) { - return tpl.replace('%TLDS%', re.src_tlds); - } - re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i'); - re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i'); - re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i'); - re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i'); + // Inline parser state - // - // Compile each schema - // + function StateInline(src, md, env, outTokens) { + this.src = src; + this.env = env; + this.md = md; + this.tokens = outTokens; + this.tokens_meta = Array(outTokens.length); + this.pos = 0; + this.posMax = this.src.length; + this.level = 0; + this.pending = ""; + this.pendingLevel = 0; - const aliases = []; - self.__compiled__ = {}; // Reset compiled data + // Stores { start: end } pairs. Useful for backtrack + // optimization of pairs parse (emphasis, strikes). + this.cache = {}; - function schemaError(name, val) { - throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val); - } - Object.keys(self.__schemas__).forEach(function (name) { - const val = self.__schemas__[name]; + // List of emphasis-like delimiters for current tag + this.delimiters = []; - // skip disabled methods - if (val === null) { - return; - } - const compiled = { - validate: null, - link: null - }; - self.__compiled__[name] = compiled; - if (isObject(val)) { - if (isRegExp(val.validate)) { - compiled.validate = createValidator(val.validate); - } else if (isFunction(val.validate)) { - compiled.validate = val.validate; - } else { - schemaError(name, val); - } - if (isFunction(val.normalize)) { - compiled.normalize = val.normalize; - } else if (!val.normalize) { - compiled.normalize = createNormalizer(); - } else { - schemaError(name, val); - } - return; - } - if (isString(val)) { - aliases.push(name); - return; - } - schemaError(name, val); - }); + // Stack of delimiter lists for upper level tags + this._prev_delimiters = []; - // - // Compile postponed aliases - // + // backtick length => last seen position + this.backticks = {}; + this.backticksScanned = false; - aliases.forEach(function (alias) { - if (!self.__compiled__[self.__schemas__[alias]]) { - // Silently fail on missed schemas to avoid errons on disable. - // schemaError(alias, self.__schemas__[alias]); - return; - } - self.__compiled__[alias].validate = self.__compiled__[self.__schemas__[alias]].validate; - self.__compiled__[alias].normalize = self.__compiled__[self.__schemas__[alias]].normalize; - }); + // Counter used to disable inline linkify-it execution + // inside and markdown links + this.linkLevel = 0; + } - // - // Fake record for guessed links - // - self.__compiled__[''] = { - validate: null, - normalize: createNormalizer() - }; + // Flush pending text + // + StateInline.prototype.pushPending = function () { + const token = new Token("text", "", 0); + token.content = this.pending; + token.level = this.pendingLevel; + this.tokens.push(token); + this.pending = ""; + return token; + }; - // - // Build schema condition - // - const slist = Object.keys(self.__compiled__).filter(function (name) { - // Filter disabled & fake schemas - return name.length > 0 && self.__compiled__[name]; - }).map(escapeRE).join('|'); - // (?!_) cause 1.5x slowdown - self.re.schema_test = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i'); - self.re.schema_search = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig'); - self.re.schema_at_start = RegExp('^' + self.re.schema_search.source, 'i'); - self.re.pretest = RegExp('(' + self.re.schema_test.source + ')|(' + self.re.host_fuzzy_test.source + ')|@', 'i'); - - // - // Cleanup - // - - resetScanCache(self); -} - -/** - * class Match - * - * Match result. Single element of array, returned by [[LinkifyIt#match]] - **/ -function Match(self, shift) { - const start = self.__index__; - const end = self.__last_index__; - const text = self.__text_cache__.slice(start, end); - - /** - * Match#schema -> String - * - * Prefix (protocol) for matched string. - **/ - this.schema = self.__schema__.toLowerCase(); - /** - * Match#index -> Number - * - * First position of matched string. - **/ - this.index = start + shift; - /** - * Match#lastIndex -> Number - * - * Next position after matched string. - **/ - this.lastIndex = end + shift; - /** - * Match#raw -> String - * - * Matched string. - **/ - this.raw = text; - /** - * Match#text -> String - * - * Notmalized text of matched string. - **/ - this.text = text; - /** - * Match#url -> String - * - * Normalized url of matched string. - **/ - this.url = text; -} -function createMatch(self, shift) { - const match = new Match(self, shift); - self.__compiled__[match.schema].normalize(match, self); - return match; -} - -/** - * class LinkifyIt - **/ - -/** - * new LinkifyIt(schemas, options) - * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) - * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } - * - * Creates new linkifier instance with optional additional schemas. - * Can be called without `new` keyword for convenience. - * - * By default understands: - * - * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links - * - "fuzzy" links and emails (example.com, foo@bar.com). - * - * `schemas` is an object, where each key/value describes protocol/rule: - * - * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` - * for example). `linkify-it` makes shure that prefix is not preceeded with - * alphanumeric char and symbols. Only whitespaces and punctuation allowed. - * - __value__ - rule to check tail after link prefix - * - _String_ - just alias to existing rule - * - _Object_ - * - _validate_ - validator function (should return matched length on success), - * or `RegExp`. - * - _normalize_ - optional function to normalize text & url of matched result - * (for example, for @twitter mentions). - * - * `options`: - * - * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. - * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts - * like version numbers. Default `false`. - * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. - * - **/ -function LinkifyIt(schemas, options) { - if (!(this instanceof LinkifyIt)) { - return new LinkifyIt(schemas, options); - } - if (!options) { - if (isOptionsObj(schemas)) { - options = schemas; - schemas = {}; - } - } - this.__opts__ = assign({}, defaultOptions, options); - - // Cache last tested result. Used to skip repeating steps on next `match` call. - this.__index__ = -1; - this.__last_index__ = -1; // Next scan position - this.__schema__ = ''; - this.__text_cache__ = ''; - this.__schemas__ = assign({}, defaultSchemas, schemas); - this.__compiled__ = {}; - this.__tlds__ = tlds_default; - this.__tlds_replaced__ = false; - this.re = {}; - compile(this); -} - -/** chainable - * LinkifyIt#add(schema, definition) - * - schema (String): rule name (fixed pattern prefix) - * - definition (String|RegExp|Object): schema definition - * - * Add new rule definition. See constructor description for details. - **/ -LinkifyIt.prototype.add = function add(schema, definition) { - this.__schemas__[schema] = definition; - compile(this); - return this; -}; + // Push new token to "stream". + // If pending text exists - flush it as text token + // + StateInline.prototype.push = function (type, tag, nesting) { + if (this.pending) { + this.pushPending(); + } + const token = new Token(type, tag, nesting); + let token_meta = null; + if (nesting < 0) { + // closing tag + this.level--; + this.delimiters = this._prev_delimiters.pop(); + } + token.level = this.level; + if (nesting > 0) { + // opening tag + this.level++; + this._prev_delimiters.push(this.delimiters); + this.delimiters = []; + token_meta = { + delimiters: this.delimiters, + }; + } + this.pendingLevel = this.level; + this.tokens.push(token); + this.tokens_meta.push(token_meta); + return token; + }; -/** chainable - * LinkifyIt#set(options) - * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } - * - * Set recognition options for links without schema. - **/ -LinkifyIt.prototype.set = function set(options) { - this.__opts__ = assign(this.__opts__, options); - return this; -}; + // Scan a sequence of emphasis-like markers, and determine whether + // it can start an emphasis sequence or end an emphasis sequence. + // + // - start - position to scan from (it should point at a valid marker); + // - canSplitWord - determine if these markers can be found inside a word + // + StateInline.prototype.scanDelims = function (start, canSplitWord) { + const max = this.posMax; + const marker = this.src.charCodeAt(start); + + // treat beginning of the line as a whitespace + const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; + let pos = start; + while (pos < max && this.src.charCodeAt(pos) === marker) { + pos++; + } + const count = pos - start; + + // treat end of the line as a whitespace + const nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; + const isLastPunctChar = + isMdAsciiPunct(lastChar) || + isPunctChar(String.fromCharCode(lastChar)); + const isNextPunctChar = + isMdAsciiPunct(nextChar) || + isPunctChar(String.fromCharCode(nextChar)); + const isLastWhitespace = isWhitespace(lastChar); + const isNextWhitespace = isWhitespace(nextChar); + const left_flanking = + !isNextWhitespace && + (!isNextPunctChar || isLastWhitespace || isLastPunctChar); + const right_flanking = + !isLastWhitespace && + (!isLastPunctChar || isNextWhitespace || isNextPunctChar); + const can_open = + left_flanking && + (canSplitWord || !right_flanking || isLastPunctChar); + const can_close = + right_flanking && + (canSplitWord || !left_flanking || isNextPunctChar); + return { + can_open, + can_close, + length: count, + }; + }; -/** - * LinkifyIt#test(text) -> Boolean - * - * Searches linkifiable pattern and returns `true` on success or `false` on fail. - **/ -LinkifyIt.prototype.test = function test(text) { - // Reset scan cache - this.__text_cache__ = text; - this.__index__ = -1; - if (!text.length) { - return false; - } - let m, ml, me, len, shift, next, re, tld_pos, at_pos; - - // try to scan for link with schema - that's the most simple rule - if (this.re.schema_test.test(text)) { - re = this.re.schema_search; - re.lastIndex = 0; - while ((m = re.exec(text)) !== null) { - len = this.testSchemaAt(text, m[2], re.lastIndex); - if (len) { - this.__schema__ = m[2]; - this.__index__ = m.index + m[1].length; - this.__last_index__ = m.index + m[0].length + len; - break; - } - } - } - if (this.__opts__.fuzzyLink && this.__compiled__['http:']) { - // guess schemaless links - tld_pos = text.search(this.re.host_fuzzy_test); - if (tld_pos >= 0) { - // if tld is located after found link - no need to check fuzzy pattern - if (this.__index__ < 0 || tld_pos < this.__index__) { - if ((ml = text.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) { - shift = ml.index + ml[1].length; - if (this.__index__ < 0 || shift < this.__index__) { - this.__schema__ = ''; - this.__index__ = shift; - this.__last_index__ = ml.index + ml[0].length; + // re-export Token class to use in block rules + StateInline.prototype.Token = Token; + + // Skip text characters for text token, place those to pending buffer + // and increment current pos + + // Rule to skip pure text + // '{}$%@~+=:' reserved for extentions + + // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ + + // !!!! Don't confuse with "Markdown ASCII Punctuation" chars + // http://spec.commonmark.org/0.15/#ascii-punctuation-character + function isTerminatorChar(ch) { + switch (ch) { + case 0x0a /* \n */: + case 0x21 /* ! */: + case 0x23 /* # */: + case 0x24 /* $ */: + case 0x25 /* % */: + case 0x26 /* & */: + case 0x2a /* * */: + case 0x2b /* + */: + case 0x2d /* - */: + case 0x3a /* : */: + case 0x3c /* < */: + case 0x3d /* = */: + case 0x3e /* > */: + case 0x40 /* @ */: + case 0x5b /* [ */: + case 0x5c /* \ */: + case 0x5d /* ] */: + case 0x5e /* ^ */: + case 0x5f /* _ */: + case 0x60 /* ` */: + case 0x7b /* { */: + case 0x7d /* } */: + case 0x7e /* ~ */: + return true; + default: + return false; } } - } - } - } - if (this.__opts__.fuzzyEmail && this.__compiled__['mailto:']) { - // guess schemaless emails - at_pos = text.indexOf('@'); - if (at_pos >= 0) { - // We can't skip this check, because this cases are possible: - // 192.168.1.1@gmail.com, my.in@example.com - if ((me = text.match(this.re.email_fuzzy)) !== null) { - shift = me.index + me[1].length; - next = me.index + me[0].length; - if (this.__index__ < 0 || shift < this.__index__ || shift === this.__index__ && next > this.__last_index__) { - this.__schema__ = 'mailto:'; - this.__index__ = shift; - this.__last_index__ = next; + function text(state, silent) { + let pos = state.pos; + while ( + pos < state.posMax && + !isTerminatorChar(state.src.charCodeAt(pos)) + ) { + pos++; + } + if (pos === state.pos) { + return false; + } + if (!silent) { + state.pending += state.src.slice(state.pos, pos); + } + state.pos = pos; + return true; } - } - } - } - return this.__index__ >= 0; -}; -/** - * LinkifyIt#pretest(text) -> Boolean - * - * Very quick check, that can give false positives. Returns true if link MAY BE - * can exists. Can be used for speed optimization, when you need to check that - * link NOT exists. - **/ -LinkifyIt.prototype.pretest = function pretest(text) { - return this.re.pretest.test(text); -}; + // Alternative implementation, for memory. + // + // It costs 10% of performance, but allows extend terminators list, if place it + // to `ParserInline` property. Probably, will switch to it sometime, such + // flexibility required. -/** - * LinkifyIt#testSchemaAt(text, name, position) -> Number - * - text (String): text to scan - * - name (String): rule (schema) name - * - position (Number): text offset to check from - * - * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly - * at given position. Returns length of found pattern (0 on fail). - **/ -LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text, schema, pos) { - // If not supported schema check requested - terminate - if (!this.__compiled__[schema.toLowerCase()]) { - return 0; - } - return this.__compiled__[schema.toLowerCase()].validate(text, pos, this); -}; + /* +var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; -/** - * LinkifyIt#match(text) -> Array|null - * - * Returns array of found link descriptions or `null` on fail. We strongly - * recommend to use [[LinkifyIt#test]] first, for best speed. - * - * ##### Result match description - * - * - __schema__ - link schema, can be empty for fuzzy links, or `//` for - * protocol-neutral links. - * - __index__ - offset of matched text - * - __lastIndex__ - index of next char after mathch end - * - __raw__ - matched text - * - __text__ - normalized text - * - __url__ - link, generated from matched text - **/ -LinkifyIt.prototype.match = function match(text) { - const result = []; - let shift = 0; - - // Try to take previous element from cache, if .test() called before - if (this.__index__ >= 0 && this.__text_cache__ === text) { - result.push(createMatch(this, shift)); - shift = this.__last_index__; - } +module.exports = function text(state, silent) { + var pos = state.pos, + idx = state.src.slice(pos).search(TERMINATOR_RE); - // Cut head if cache was used - let tail = shift ? text.slice(shift) : text; + // first char is terminator -> empty text + if (idx === 0) { return false; } - // Scan string until end reached - while (this.test(tail)) { - result.push(createMatch(this, shift)); - tail = tail.slice(this.__last_index__); - shift += this.__last_index__; - } - if (result.length) { - return result; + // no terminator -> text till end of string + if (idx < 0) { + if (!silent) { state.pending += state.src.slice(pos); } + state.pos = state.src.length; + return true; } - return null; -}; -/** - * LinkifyIt#matchAtStart(text) -> Match|null - * - * Returns fully-formed (not fuzzy) link if it starts at the beginning - * of the string, and null otherwise. - **/ -LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { - // Reset scan cache - this.__text_cache__ = text; - this.__index__ = -1; - if (!text.length) return null; - const m = this.re.schema_at_start.exec(text); - if (!m) return null; - const len = this.testSchemaAt(text, m[2], m[0].length); - if (!len) return null; - this.__schema__ = m[2]; - this.__index__ = m.index + m[1].length; - this.__last_index__ = m.index + m[0].length + len; - return createMatch(this, 0); -}; + if (!silent) { state.pending += state.src.slice(pos, pos + idx); } -/** chainable - * LinkifyIt#tlds(list [, keepOld]) -> this - * - list (Array): list of tlds - * - keepOld (Boolean): merge with current list if `true` (`false` by default) - * - * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) - * to avoid false positives. By default this algorythm used: - * - * - hostname with any 2-letter root zones are ok. - * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф - * are ok. - * - encoded (`xn--...`) root zones are ok. - * - * If list is replaced, then exact match for 2-chars root zones will be checked. - **/ -LinkifyIt.prototype.tlds = function tlds(list, keepOld) { - list = Array.isArray(list) ? list : [list]; - if (!keepOld) { - this.__tlds__ = list.slice(); - this.__tlds_replaced__ = true; - compile(this); - return this; - } - this.__tlds__ = this.__tlds__.concat(list).sort().filter(function (el, idx, arr) { - return el !== arr[idx - 1]; - }).reverse(); - compile(this); - return this; -}; + state.pos += idx; -/** - * LinkifyIt#normalize(match) - * - * Default normalizer (if schema does not define it's own). - **/ -LinkifyIt.prototype.normalize = function normalize(match) { - // Do minimal possible changes by default. Need to collect feedback prior - // to move forward https://github.com/markdown-it/linkify-it/issues/1 - - if (!match.schema) { - match.url = 'http://' + match.url; - } - if (match.schema === 'mailto:' && !/^mailto:/i.test(match.url)) { - match.url = 'mailto:' + match.url; - } -}; + return true; +}; */ -/** - * LinkifyIt#onCompile() - * - * Override to modify basic RegExp-s. - **/ -LinkifyIt.prototype.onCompile = function onCompile() {}; -module.exports = LinkifyIt; + // Process links like https://example.org/ + + // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; + function linkify(state, silent) { + if (!state.md.options.linkify) return false; + if (state.linkLevel > 0) return false; + const pos = state.pos; + const max = state.posMax; + if (pos + 3 > max) return false; + if (state.src.charCodeAt(pos) !== 0x3a /* : */) return false; + if (state.src.charCodeAt(pos + 1) !== 0x2f /* / */) return false; + if (state.src.charCodeAt(pos + 2) !== 0x2f /* / */) return false; + const match = state.pending.match(SCHEME_RE); + if (!match) return false; + const proto = match[1]; + const link = state.md.linkify.matchAtStart( + state.src.slice(pos - proto.length) + ); + if (!link) return false; + let url = link.url; -/***/ }), + // invalid link, but still detected by linkify somehow; + // need to check to prevent infinite loop below + if (url.length <= proto.length) return false; -/***/ "../node_modules/markdown-it/dist/index.cjs.js": -/*!*****************************************************!*\ - !*** ../node_modules/markdown-it/dist/index.cjs.js ***! - \*****************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // disallow '*' at the end of the link (conflicts with emphasis) + url = url.replace(/\*+$/, ""); + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) return false; + if (!silent) { + state.pending = state.pending.slice(0, -proto.length); + const token_o = state.push("link_open", "a", 1); + token_o.attrs = [["href", fullUrl]]; + token_o.markup = "linkify"; + token_o.info = "auto"; + const token_t = state.push("text", "", 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push("link_close", "a", -1); + token_c.markup = "linkify"; + token_c.info = "auto"; + } + state.pos += url.length - proto.length; + return true; + } + // Proceess '\n' + function newline(state, silent) { + let pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x0a /* \n */) { + return false; + } + const pmax = state.pending.length - 1; + const max = state.posMax; + + // ' \n' -> hardbreak + // Lookup in pending chars is bad practice! Don't copy to other rules! + // Pending string is stored in concat mode, indexed lookups will cause + // convertion to flat mode. + if (!silent) { + if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { + if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { + // Find whitespaces tail of pending chars. + let ws = pmax - 1; + while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) + ws--; + state.pending = state.pending.slice(0, ws); + state.push("hardbreak", "br", 0); + } else { + state.pending = state.pending.slice(0, -1); + state.push("softbreak", "br", 0); + } + } else { + state.push("softbreak", "br", 0); + } + } + pos++; -var mdurl = __webpack_require__(/*! mdurl */ "../node_modules/mdurl/build/index.cjs.js"); -var ucmicro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); -var entities = __webpack_require__(/*! entities */ "../../../node_modules/entities/lib/index.js"); -var LinkifyIt = __webpack_require__(/*! linkify-it */ "../node_modules/linkify-it/build/index.cjs.js"); -var punycode = __webpack_require__(/*! punycode.js */ "../../../node_modules/punycode.js/punycode.es6.js"); -function _interopNamespaceDefault(e) { - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { - return e[k]; + // skip heading spaces for next line + while (pos < max && isSpace(state.src.charCodeAt(pos))) { + pos++; } - }); - } - }); - } - n.default = e; - return Object.freeze(n); -} -var mdurl__namespace = /*#__PURE__*/_interopNamespaceDefault(mdurl); -var ucmicro__namespace = /*#__PURE__*/_interopNamespaceDefault(ucmicro); - -// Utilities -// - -function _class(obj) { - return Object.prototype.toString.call(obj); -} -function isString(obj) { - return _class(obj) === '[object String]'; -} -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function has(object, key) { - return _hasOwnProperty.call(object, key); -} - -// Merge objects -// -function assign(obj /* from1, from2, from3, ... */) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; - } - if (typeof source !== 'object') { - throw new TypeError(source + 'must be object'); - } - Object.keys(source).forEach(function (key) { - obj[key] = source[key]; - }); - }); - return obj; -} - -// Remove element from array and put another array at those position. -// Useful for some operations with tokens -function arrayReplaceAt(src, pos, newElements) { - return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); -} -function isValidEntityCode(c) { - /* eslint no-bitwise:0 */ - // broken sequence - if (c >= 0xD800 && c <= 0xDFFF) { - return false; - } - // never used - if (c >= 0xFDD0 && c <= 0xFDEF) { - return false; - } - if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { - return false; - } - // control codes - if (c >= 0x00 && c <= 0x08) { - return false; - } - if (c === 0x0B) { - return false; - } - if (c >= 0x0E && c <= 0x1F) { - return false; - } - if (c >= 0x7F && c <= 0x9F) { - return false; - } - // out of range - if (c > 0x10FFFF) { - return false; - } - return true; -} -function fromCodePoint(c) { - /* eslint no-bitwise:0 */ - if (c > 0xffff) { - c -= 0x10000; - const surrogate1 = 0xd800 + (c >> 10); - const surrogate2 = 0xdc00 + (c & 0x3ff); - return String.fromCharCode(surrogate1, surrogate2); - } - return String.fromCharCode(c); -} -const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g; -const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; -const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi'); -const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i; -function replaceEntityPattern(match, name) { - if (name.charCodeAt(0) === 0x23 /* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) { - const code = name[1].toLowerCase() === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10); - if (isValidEntityCode(code)) { - return fromCodePoint(code); - } - return match; - } - const decoded = entities.decodeHTML(match); - if (decoded !== match) { - return decoded; - } - return match; -} + state.pos = pos; + return true; + } -/* function replaceEntities(str) { - if (str.indexOf('&') < 0) { return str; } + // Process escaped chars and hardbreaks - return str.replace(ENTITY_RE, replaceEntityPattern); -} */ + const ESCAPED = []; + for (let i = 0; i < 256; i++) { + ESCAPED.push(0); + } + "\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function (ch) { + ESCAPED[ch.charCodeAt(0)] = 1; + }); + function escape(state, silent) { + let pos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(pos) !== 0x5c /* \ */) return false; + pos++; -function unescapeMd(str) { - if (str.indexOf('\\') < 0) { - return str; - } - return str.replace(UNESCAPE_MD_RE, '$1'); -} -function unescapeAll(str) { - if (str.indexOf('\\') < 0 && str.indexOf('&') < 0) { - return str; - } - return str.replace(UNESCAPE_ALL_RE, function (match, escaped, entity) { - if (escaped) { - return escaped; - } - return replaceEntityPattern(match, entity); - }); -} -const HTML_ESCAPE_TEST_RE = /[&<>"]/; -const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; -const HTML_REPLACEMENTS = { - '&': '&', - '<': '<', - '>': '>', - '"': '"' -}; -function replaceUnsafeChar(ch) { - return HTML_REPLACEMENTS[ch]; -} -function escapeHtml(str) { - if (HTML_ESCAPE_TEST_RE.test(str)) { - return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); - } - return str; -} -const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; -function escapeRE(str) { - return str.replace(REGEXP_ESCAPE_RE, '\\$&'); -} -function isSpace(code) { - switch (code) { - case 0x09: - case 0x20: - return true; - } - return false; -} + // '\' at the end of the inline block + if (pos >= max) return false; + let ch1 = state.src.charCodeAt(pos); + if (ch1 === 0x0a) { + if (!silent) { + state.push("hardbreak", "br", 0); + } + pos++; + // skip leading whitespaces from next line + while (pos < max) { + ch1 = state.src.charCodeAt(pos); + if (!isSpace(ch1)) break; + pos++; + } + state.pos = pos; + return true; + } + let escapedStr = state.src[pos]; + if (ch1 >= 0xd800 && ch1 <= 0xdbff && pos + 1 < max) { + const ch2 = state.src.charCodeAt(pos + 1); + if (ch2 >= 0xdc00 && ch2 <= 0xdfff) { + escapedStr += state.src[pos + 1]; + pos++; + } + } + const origStr = "\\" + escapedStr; + if (!silent) { + const token = state.push("text_special", "", 0); + if (ch1 < 256 && ESCAPED[ch1] !== 0) { + token.content = escapedStr; + } else { + token.content = origStr; + } + token.markup = origStr; + token.info = "escape"; + } + state.pos = pos + 1; + return true; + } -// Zs (unicode class) || [\t\f\v\r\n] -function isWhiteSpace(code) { - if (code >= 0x2000 && code <= 0x200A) { - return true; - } - switch (code) { - case 0x09: // \t - case 0x0A: // \n - case 0x0B: // \v - case 0x0C: // \f - case 0x0D: // \r - case 0x20: - case 0xA0: - case 0x1680: - case 0x202F: - case 0x205F: - case 0x3000: - return true; - } - return false; -} - -/* eslint-disable max-len */ - -// Currently without astral characters support. -function isPunctChar(ch) { - return ucmicro__namespace.P.test(ch) || ucmicro__namespace.S.test(ch); -} - -// Markdown ASCII punctuation characters. -// -// !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ -// http://spec.commonmark.org/0.15/#ascii-punctuation-character -// -// Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. -// -function isMdAsciiPunct(ch) { - switch (ch) { - case 0x21 /* ! */: - case 0x22 /* " */: - case 0x23 /* # */: - case 0x24 /* $ */: - case 0x25 /* % */: - case 0x26 /* & */: - case 0x27 /* ' */: - case 0x28 /* ( */: - case 0x29 /* ) */: - case 0x2A /* * */: - case 0x2B /* + */: - case 0x2C /* , */: - case 0x2D /* - */: - case 0x2E /* . */: - case 0x2F /* / */: - case 0x3A /* : */: - case 0x3B /* ; */: - case 0x3C /* < */: - case 0x3D /* = */: - case 0x3E /* > */: - case 0x3F /* ? */: - case 0x40 /* @ */: - case 0x5B /* [ */: - case 0x5C /* \ */: - case 0x5D /* ] */: - case 0x5E /* ^ */: - case 0x5F /* _ */: - case 0x60 /* ` */: - case 0x7B /* { */: - case 0x7C /* | */: - case 0x7D /* } */: - case 0x7E /* ~ */: - return true; - default: - return false; - } -} - -// Hepler to unify [reference labels]. -// -function normalizeReference(str) { - // Trim and collapse whitespace - // - str = str.trim().replace(/\s+/g, ' '); - - // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug - // fixed in v12 (couldn't find any details). - // - // So treat this one as a special case - // (remove this when node v10 is no longer supported). - // - if ('ẞ'.toLowerCase() === 'Ṿ') { - str = str.replace(/ẞ/g, 'ß'); - } + // Parse backticks - // .toLowerCase().toUpperCase() should get rid of all differences - // between letter variants. - // - // Simple .toLowerCase() doesn't normalize 125 code points correctly, - // and .toUpperCase doesn't normalize 6 of them (list of exceptions: - // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently - // uppercased versions). - // - // Here's an example showing how it happens. Lets take greek letter omega: - // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) - // - // Unicode entries: - // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; - // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 - // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 - // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; - // - // Case-insensitive comparison should treat all of them as equivalent. - // - // But .toLowerCase() doesn't change ϑ (it's already lowercase), - // and .toUpperCase() doesn't change ϴ (already uppercase). - // - // Applying first lower then upper case normalizes any character: - // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' - // - // Note: this is equivalent to unicode case folding; unicode normalization - // is a different step that is not required here. - // - // Final result should be uppercased, because it's later stored in an object - // (this avoid a conflict with Object.prototype members, - // most notably, `__proto__`) - // - return str.toLowerCase().toUpperCase(); -} - -// Re-export libraries commonly used in both markdown-it and its plugins, -// so plugins won't have to depend on them explicitly, which reduces their -// bundled size (e.g. a browser build). -// -const lib = { - mdurl: mdurl__namespace, - ucmicro: ucmicro__namespace -}; -var utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - arrayReplaceAt: arrayReplaceAt, - assign: assign, - escapeHtml: escapeHtml, - escapeRE: escapeRE, - fromCodePoint: fromCodePoint, - has: has, - isMdAsciiPunct: isMdAsciiPunct, - isPunctChar: isPunctChar, - isSpace: isSpace, - isString: isString, - isValidEntityCode: isValidEntityCode, - isWhiteSpace: isWhiteSpace, - lib: lib, - normalizeReference: normalizeReference, - unescapeAll: unescapeAll, - unescapeMd: unescapeMd -}); - -// Parse link label -// -// this function assumes that first character ("[") already matches; -// returns the end of the label -// - -function parseLinkLabel(state, start, disableNested) { - let level, found, marker, prevPos; - const max = state.posMax; - const oldPos = state.pos; - state.pos = start + 1; - level = 1; - while (state.pos < max) { - marker = state.src.charCodeAt(state.pos); - if (marker === 0x5D /* ] */) { - level--; - if (level === 0) { - found = true; - break; - } - } - prevPos = state.pos; - state.md.inline.skipToken(state); - if (marker === 0x5B /* [ */) { - if (prevPos === state.pos - 1) { - // increase level if we find text `[`, which is not a part of any token - level++; - } else if (disableNested) { - state.pos = oldPos; - return -1; - } - } - } - let labelEnd = -1; - if (found) { - labelEnd = state.pos; - } + function backtick(state, silent) { + let pos = state.pos; + const ch = state.src.charCodeAt(pos); + if (ch !== 0x60 /* ` */) { + return false; + } + const start = pos; + pos++; + const max = state.posMax; + + // scan marker length + while (pos < max && state.src.charCodeAt(pos) === 0x60 /* ` */) { + pos++; + } + const marker = state.src.slice(start, pos); + const openerLength = marker.length; + if ( + state.backticksScanned && + (state.backticks[openerLength] || 0) <= start + ) { + if (!silent) state.pending += marker; + state.pos += openerLength; + return true; + } + let matchEnd = pos; + let matchStart; - // restore old state - state.pos = oldPos; - return labelEnd; -} - -// Parse link destination -// - -function parseLinkDestination(str, start, max) { - let code; - let pos = start; - const result = { - ok: false, - pos: 0, - str: '' - }; - if (str.charCodeAt(pos) === 0x3C /* < */) { - pos++; - while (pos < max) { - code = str.charCodeAt(pos); - if (code === 0x0A /* \n */) { - return result; - } - if (code === 0x3C /* < */) { - return result; - } - if (code === 0x3E /* > */) { - result.pos = pos + 1; - result.str = unescapeAll(str.slice(start + 1, pos)); - result.ok = true; - return result; - } - if (code === 0x5C /* \ */ && pos + 1 < max) { - pos += 2; - continue; - } - pos++; - } + // Nothing found in the cache, scan until the end of the line (or until marker is found) + while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) { + matchEnd = matchStart + 1; - // no closing '>' - return result; - } + // scan marker length + while ( + matchEnd < max && + state.src.charCodeAt(matchEnd) === 0x60 /* ` */ + ) { + matchEnd++; + } + const closerLength = matchEnd - matchStart; + if (closerLength === openerLength) { + // Found matching closer length. + if (!silent) { + const token = state.push("code_inline", "code", 0); + token.markup = marker; + token.content = state.src + .slice(pos, matchStart) + .replace(/\n/g, " ") + .replace(/^ (.+) $/, "$1"); + } + state.pos = matchEnd; + return true; + } - // this should be ... } else { ... branch + // Some different length found, put it in cache as upper limit of where closer can be found + state.backticks[closerLength] = matchStart; + } - let level = 0; - while (pos < max) { - code = str.charCodeAt(pos); - if (code === 0x20) { - break; - } + // Scanned through the end, didn't find anything + state.backticksScanned = true; + if (!silent) state.pending += marker; + state.pos += openerLength; + return true; + } - // ascii control characters - if (code < 0x20 || code === 0x7F) { - break; - } - if (code === 0x5C /* \ */ && pos + 1 < max) { - if (str.charCodeAt(pos + 1) === 0x20) { - break; - } - pos += 2; - continue; - } - if (code === 0x28 /* ( */) { - level++; - if (level > 32) { - return result; - } - } - if (code === 0x29 /* ) */) { - if (level === 0) { - break; - } - level--; - } - pos++; - } - if (start === pos) { - return result; - } - if (level !== 0) { - return result; - } - result.str = unescapeAll(str.slice(start, pos)); - result.pos = pos; - result.ok = true; - return result; -} - -// Parse link title -// - -// Parse link title within `str` in [start, max] range, -// or continue previous parsing if `prev_state` is defined (equal to result of last execution). -// -function parseLinkTitle(str, start, max, prev_state) { - let code; - let pos = start; - const state = { - // if `true`, this is a valid link title - ok: false, - // if `true`, this link can be continued on the next line - can_continue: false, - // if `ok`, it's the position of the first character after the closing marker - pos: 0, - // if `ok`, it's the unescaped title - str: '', - // expected closing marker character code - marker: 0 - }; - if (prev_state) { - // this is a continuation of a previous parseLinkTitle call on the next line, - // used in reference links only - state.str = prev_state.str; - state.marker = prev_state.marker; - } else { - if (pos >= max) { - return state; - } - let marker = str.charCodeAt(pos); - if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { - return state; - } - start++; - pos++; + // ~~strike through~~ + // - // if opening marker is "(", switch it to closing marker ")" - if (marker === 0x28) { - marker = 0x29; - } - state.marker = marker; - } - while (pos < max) { - code = str.charCodeAt(pos); - if (code === state.marker) { - state.pos = pos + 1; - state.str += unescapeAll(str.slice(start, pos)); - state.ok = true; - return state; - } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) { - return state; - } else if (code === 0x5C /* \ */ && pos + 1 < max) { - pos++; - } - pos++; - } + // Insert each marker as a separate text token, and add it to delimiter list + // + function strikethrough_tokenize(state, silent) { + const start = state.pos; + const marker = state.src.charCodeAt(start); + if (silent) { + return false; + } + if (marker !== 0x7e /* ~ */) { + return false; + } + const scanned = state.scanDelims(state.pos, true); + let len = scanned.length; + const ch = String.fromCharCode(marker); + if (len < 2) { + return false; + } + let token; + if (len % 2) { + token = state.push("text", "", 0); + token.content = ch; + len--; + } + for (let i = 0; i < len; i += 2) { + token = state.push("text", "", 0); + token.content = ch + ch; + state.delimiters.push({ + marker, + length: 0, + // disable "rule of 3" length checks meant for emphasis + token: state.tokens.length - 1, + end: -1, + open: scanned.can_open, + close: scanned.can_close, + }); + } + state.pos += scanned.length; + return true; + } + function postProcess$1(state, delimiters) { + let token; + const loneMarkers = []; + const max = delimiters.length; + for (let i = 0; i < max; i++) { + const startDelim = delimiters[i]; + if (startDelim.marker !== 0x7e /* ~ */) { + continue; + } + if (startDelim.end === -1) { + continue; + } + const endDelim = delimiters[startDelim.end]; + token = state.tokens[startDelim.token]; + token.type = "s_open"; + token.tag = "s"; + token.nesting = 1; + token.markup = "~~"; + token.content = ""; + token = state.tokens[endDelim.token]; + token.type = "s_close"; + token.tag = "s"; + token.nesting = -1; + token.markup = "~~"; + token.content = ""; + if ( + state.tokens[endDelim.token - 1].type === "text" && + state.tokens[endDelim.token - 1].content === "~" + ) { + loneMarkers.push(endDelim.token - 1); + } + } - // no closing marker found, but this link title may continue on the next line (for references) - state.can_continue = true; - state.str += unescapeAll(str.slice(start, pos)); - return state; -} - -// Just a shortcut for bulk export - -var helpers = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseLinkDestination: parseLinkDestination, - parseLinkLabel: parseLinkLabel, - parseLinkTitle: parseLinkTitle -}); - -/** - * class Renderer - * - * Generates HTML from parsed token stream. Each instance has independent - * copy of rules. Those can be rewritten with ease. Also, you can add new - * rules if you create plugin and adds new token types. - **/ - -const default_rules = {}; -default_rules.code_inline = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - return '' + escapeHtml(token.content) + ''; -}; -default_rules.code_block = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - return '' + escapeHtml(tokens[idx].content) + '\n'; -}; -default_rules.fence = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - const info = token.info ? unescapeAll(token.info).trim() : ''; - let langName = ''; - let langAttrs = ''; - if (info) { - const arr = info.split(/(\s+)/g); - langName = arr[0]; - langAttrs = arr.slice(2).join(''); - } - let highlighted; - if (options.highlight) { - highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content); - } else { - highlighted = escapeHtml(token.content); - } - if (highlighted.indexOf(' `~` + `~~` + `~~`, leaving one marker at the + // start of the sequence. + // + // So, we have to move all those markers after subsequent s_close tags. + // + while (loneMarkers.length) { + const i = loneMarkers.pop(); + let j = i + 1; + while ( + j < state.tokens.length && + state.tokens[j].type === "s_close" + ) { + j++; + } + j--; + if (i !== j) { + token = state.tokens[j]; + state.tokens[j] = state.tokens[i]; + state.tokens[i] = token; + } + } + } - // If language exists, inject class gently, without modifying original token. - // May be, one day we will add .deepClone() for token and simplify this part, but - // now we prefer to keep things local. - if (info) { - const i = token.attrIndex('class'); - const tmpAttrs = token.attrs ? token.attrs.slice() : []; - if (i < 0) { - tmpAttrs.push(['class', options.langPrefix + langName]); - } else { - tmpAttrs[i] = tmpAttrs[i].slice(); - tmpAttrs[i][1] += ' ' + options.langPrefix + langName; - } + // Walk through delimiter list and replace text tokens with tags + // + function strikethrough_postProcess(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + postProcess$1(state, state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + postProcess$1(state, tokens_meta[curr].delimiters); + } + } + } + var r_strikethrough = { + tokenize: strikethrough_tokenize, + postProcess: strikethrough_postProcess, + }; - // Fake token just to render attributes - const tmpToken = { - attrs: tmpAttrs - }; - return `
${highlighted}
\n`; - } - return `
${highlighted}
\n`; -}; -default_rules.image = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; + // Process *this* and _that_ + // + + // Insert each marker as a separate text token, and add it to delimiter list + // + function emphasis_tokenize(state, silent) { + const start = state.pos; + const marker = state.src.charCodeAt(start); + if (silent) { + return false; + } + if (marker !== 0x5f /* _ */ && marker !== 0x2a /* * */) { + return false; + } + const scanned = state.scanDelims(state.pos, marker === 0x2a); + for (let i = 0; i < scanned.length; i++) { + const token = state.push("text", "", 0); + token.content = String.fromCharCode(marker); + state.delimiters.push({ + // Char code of the starting marker (number). + // + marker, + // Total length of these series of delimiters. + // + length: scanned.length, + // A position of the token this delimiter corresponds to. + // + token: state.tokens.length - 1, + // If this delimiter is matched as a valid opener, `end` will be + // equal to its position, otherwise it's `-1`. + // + end: -1, + // Boolean flags that determine if this delimiter could open or close + // an emphasis. + // + open: scanned.can_open, + close: scanned.can_close, + }); + } + state.pos += scanned.length; + return true; + } + function postProcess(state, delimiters) { + const max = delimiters.length; + for (let i = max - 1; i >= 0; i--) { + const startDelim = delimiters[i]; + if ( + startDelim.marker !== 0x5f /* _ */ && + startDelim.marker !== 0x2a /* * */ + ) { + continue; + } - // "alt" attr MUST be set, even if empty. Because it's mandatory and - // should be placed on proper position for tests. - // - // Replace content with actual value + // Process only opening markers + if (startDelim.end === -1) { + continue; + } + const endDelim = delimiters[startDelim.end]; + + // If the previous delimiter has the same marker and is adjacent to this one, + // merge those into one strong delimiter. + // + // `whatever` -> `whatever` + // + const isStrong = + i > 0 && + delimiters[i - 1].end === startDelim.end + 1 && + // check that first two markers match and adjacent + delimiters[i - 1].marker === startDelim.marker && + delimiters[i - 1].token === startDelim.token - 1 && + // check that last two markers are adjacent (we can safely assume they match) + delimiters[startDelim.end + 1].token === endDelim.token + 1; + const ch = String.fromCharCode(startDelim.marker); + const token_o = state.tokens[startDelim.token]; + token_o.type = isStrong ? "strong_open" : "em_open"; + token_o.tag = isStrong ? "strong" : "em"; + token_o.nesting = 1; + token_o.markup = isStrong ? ch + ch : ch; + token_o.content = ""; + const token_c = state.tokens[endDelim.token]; + token_c.type = isStrong ? "strong_close" : "em_close"; + token_c.tag = isStrong ? "strong" : "em"; + token_c.nesting = -1; + token_c.markup = isStrong ? ch + ch : ch; + token_c.content = ""; + if (isStrong) { + state.tokens[delimiters[i - 1].token].content = ""; + state.tokens[delimiters[startDelim.end + 1].token].content = ""; + i--; + } + } + } - token.attrs[token.attrIndex('alt')][1] = slf.renderInlineAsText(token.children, options, env); - return slf.renderToken(tokens, idx, options); -}; -default_rules.hardbreak = function (tokens, idx, options /*, env */) { - return options.xhtmlOut ? '
\n' : '
\n'; -}; -default_rules.softbreak = function (tokens, idx, options /*, env */) { - return options.breaks ? options.xhtmlOut ? '
\n' : '
\n' : '\n'; -}; -default_rules.text = function (tokens, idx /*, options, env */) { - return escapeHtml(tokens[idx].content); -}; -default_rules.html_block = function (tokens, idx /*, options, env */) { - return tokens[idx].content; -}; -default_rules.html_inline = function (tokens, idx /*, options, env */) { - return tokens[idx].content; -}; + // Walk through delimiter list and replace text tokens with tags + // + function emphasis_post_process(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + postProcess(state, state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + postProcess(state, tokens_meta[curr].delimiters); + } + } + } + var r_emphasis = { + tokenize: emphasis_tokenize, + postProcess: emphasis_post_process, + }; -/** - * new Renderer() - * - * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. - **/ -function Renderer() { - /** - * Renderer#rules -> Object - * - * Contains render rules for tokens. Can be updated and extended. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.renderer.rules.strong_open = function () { return ''; }; - * md.renderer.rules.strong_close = function () { return ''; }; - * - * var result = md.renderInline(...); - * ``` - * - * Each rule is called as independent static function with fixed signature: - * - * ```javascript - * function my_token_render(tokens, idx, options, env, renderer) { - * // ... - * return renderedHTML; - * } - * ``` - * - * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs) - * for more details and examples. - **/ - this.rules = assign({}, default_rules); -} - -/** - * Renderer.renderAttrs(token) -> String - * - * Render token attributes to string. - **/ -Renderer.prototype.renderAttrs = function renderAttrs(token) { - let i, l, result; - if (!token.attrs) { - return ''; - } - result = ''; - for (i = 0, l = token.attrs.length; i < l; i++) { - result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"'; - } - return result; -}; + // Process [link]( "stuff") -/** - * Renderer.renderToken(tokens, idx, options) -> String - * - tokens (Array): list of tokens - * - idx (Numbed): token index to render - * - options (Object): params of parser instance - * - * Default token renderer. Can be overriden by custom function - * in [[Renderer#rules]]. - **/ -Renderer.prototype.renderToken = function renderToken(tokens, idx, options) { - const token = tokens[idx]; - let result = ''; - - // Tight list paragraphs - if (token.hidden) { - return ''; - } + function link(state, silent) { + let code, label, res, ref; + let href = ""; + let title = ""; + let start = state.pos; + let parseReference = true; + if (state.src.charCodeAt(state.pos) !== 0x5b /* [ */) { + return false; + } + const oldPos = state.pos; + const max = state.posMax; + const labelStart = state.pos + 1; + const labelEnd = state.md.helpers.parseLinkLabel( + state, + state.pos, + true + ); - // Insert a newline between hidden paragraph and subsequent opening - // block-level tag. - // - // For example, here we should insert a newline before blockquote: - // - a - // > - // - if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) { - result += '\n'; - } + // parser failed to find ']', so it's not a valid link + if (labelEnd < 0) { + return false; + } + let pos = labelEnd + 1; + if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { + // + // Inline link + // + + // might have found a valid shortcut link, disable reference parsing + parseReference = false; + + // [link]( "title" ) + // ^^ skipping these spaces + pos++; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0a) { + break; + } + } + if (pos >= max) { + return false; + } - // Add token name, e.g. ` "title" ) + // ^^^^^^ parsing link destination + start = pos; + res = state.md.helpers.parseLinkDestination( + state.src, + pos, + state.posMax + ); + if (res.ok) { + href = state.md.normalizeLink(res.str); + if (state.md.validateLink(href)) { + pos = res.pos; + } else { + href = ""; + } - // Encode attributes, e.g. ` "title" ) + // ^^ skipping these spaces + start = pos; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0a) { + break; + } + } - // Add a slash for self-closing tags, e.g. ` "title" ) + // ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle( + state.src, + pos, + state.posMax + ); + if (pos < max && start !== pos && res.ok) { + title = res.str; + pos = res.pos; + + // [link]( "title" ) + // ^^ skipping these spaces + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0a) { + break; + } + } + } + } + if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { + // parsing a valid shortcut link failed, fallback to reference + parseReference = true; + } + pos++; + } + if (parseReference) { + // + // Link reference + // + if (typeof state.env.references === "undefined") { + return false; + } + if (pos < max && state.src.charCodeAt(pos) === 0x5b /* [ */) { + start = pos + 1; + pos = state.md.helpers.parseLinkLabel(state, pos); + if (pos >= 0) { + label = state.src.slice(start, pos++); + } else { + pos = labelEnd + 1; + } + } else { + pos = labelEnd + 1; + } + + // covers label === '' and label === undefined + // (collapsed reference link and shortcut reference link respectively) + if (!label) { + label = state.src.slice(labelStart, labelEnd); + } + ref = state.env.references[normalizeReference(label)]; + if (!ref) { + state.pos = oldPos; + return false; + } + href = ref.href; + title = ref.title; + } - // Check if we need to add a newline after this tag - let needLf = false; - if (token.block) { - needLf = true; - if (token.nesting === 1) { - if (idx + 1 < tokens.length) { - const nextToken = tokens[idx + 1]; - if (nextToken.type === 'inline' || nextToken.hidden) { - // Block-level tag containing an inline tag. // - needLf = false; - } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) { - // Opening tag + closing tag of the same type. E.g. `
  • `. + // We found the end of the link, and know for a fact it's a valid link; + // so all that's left to do is to call tokenizer. // - needLf = false; + if (!silent) { + state.pos = labelStart; + state.posMax = labelEnd; + const token_o = state.push("link_open", "a", 1); + const attrs = [["href", href]]; + token_o.attrs = attrs; + if (title) { + attrs.push(["title", title]); + } + state.linkLevel++; + state.md.inline.tokenize(state); + state.linkLevel--; + state.push("link_close", "a", -1); + } + state.pos = pos; + state.posMax = max; + return true; } - } - } - } - result += needLf ? '>\n' : '>'; - return result; -}; -/** - * Renderer.renderInline(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * The same as [[Renderer.render]], but for single token of `inline` type. - **/ -Renderer.prototype.renderInline = function (tokens, options, env) { - let result = ''; - const rules = this.rules; - for (let i = 0, len = tokens.length; i < len; i++) { - const type = tokens[i].type; - if (typeof rules[type] !== 'undefined') { - result += rules[type](tokens, i, options, env, this); - } else { - result += this.renderToken(tokens, i, options); - } - } - return result; -}; + // Process ![image]( "title") -/** internal - * Renderer.renderInlineAsText(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * Special kludge for image `alt` attributes to conform CommonMark spec. - * Don't try to use it! Spec requires to show `alt` content with stripped markup, - * instead of simple escaping. - **/ -Renderer.prototype.renderInlineAsText = function (tokens, options, env) { - let result = ''; - for (let i = 0, len = tokens.length; i < len; i++) { - switch (tokens[i].type) { - case 'text': - result += tokens[i].content; - break; - case 'image': - result += this.renderInlineAsText(tokens[i].children, options, env); - break; - case 'html_inline': - case 'html_block': - result += tokens[i].content; - break; - case 'softbreak': - case 'hardbreak': - result += '\n'; - break; - // all other tokens are skipped - } - } - return result; -}; + function image(state, silent) { + let code, content, label, pos, ref, res, title, start; + let href = ""; + const oldPos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(state.pos) !== 0x21 /* ! */) { + return false; + } + if (state.src.charCodeAt(state.pos + 1) !== 0x5b /* [ */) { + return false; + } + const labelStart = state.pos + 2; + const labelEnd = state.md.helpers.parseLinkLabel( + state, + state.pos + 1, + false + ); -/** - * Renderer.render(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * Takes token stream and generates HTML. Probably, you will never need to call - * this method directly. - **/ -Renderer.prototype.render = function (tokens, options, env) { - let result = ''; - const rules = this.rules; - for (let i = 0, len = tokens.length; i < len; i++) { - const type = tokens[i].type; - if (type === 'inline') { - result += this.renderInline(tokens[i].children, options, env); - } else if (typeof rules[type] !== 'undefined') { - result += rules[type](tokens, i, options, env, this); - } else { - result += this.renderToken(tokens, i, options, env); - } - } - return result; -}; + // parser failed to find ']', so it's not a valid link + if (labelEnd < 0) { + return false; + } + pos = labelEnd + 1; + if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { + // + // Inline link + // + + // [link]( "title" ) + // ^^ skipping these spaces + pos++; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0a) { + break; + } + } + if (pos >= max) { + return false; + } -/** - * class Ruler - * - * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and - * [[MarkdownIt#inline]] to manage sequences of functions (rules): - * - * - keep rules in defined order - * - assign the name to each rule - * - enable/disable rules - * - add/replace rules - * - allow assign rules to additional named chains (in the same) - * - cacheing lists of active rules - * - * You will not need use this class directly until write plugins. For simple - * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and - * [[MarkdownIt.use]]. - **/ - -/** - * new Ruler() - **/ -function Ruler() { - // List of added rules. Each element is: - // - // { - // name: XXX, - // enabled: Boolean, - // fn: Function(), - // alt: [ name2, name3 ] - // } - // - this.__rules__ = []; - - // Cached rule chains. - // - // First level - chain name, '' for default. - // Second level - diginal anchor for fast filtering by charcodes. - // - this.__cache__ = null; -} - -// Helper methods, should not be used directly - -// Find rule index by name -// -Ruler.prototype.__find__ = function (name) { - for (let i = 0; i < this.__rules__.length; i++) { - if (this.__rules__[i].name === name) { - return i; - } - } - return -1; -}; + // [link]( "title" ) + // ^^^^^^ parsing link destination + start = pos; + res = state.md.helpers.parseLinkDestination( + state.src, + pos, + state.posMax + ); + if (res.ok) { + href = state.md.normalizeLink(res.str); + if (state.md.validateLink(href)) { + pos = res.pos; + } else { + href = ""; + } + } -// Build rules lookup cache -// -Ruler.prototype.__compile__ = function () { - const self = this; - const chains = ['']; + // [link]( "title" ) + // ^^ skipping these spaces + start = pos; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0a) { + break; + } + } - // collect unique names - self.__rules__.forEach(function (rule) { - if (!rule.enabled) { - return; - } - rule.alt.forEach(function (altName) { - if (chains.indexOf(altName) < 0) { - chains.push(altName); - } - }); - }); - self.__cache__ = {}; - chains.forEach(function (chain) { - self.__cache__[chain] = []; - self.__rules__.forEach(function (rule) { - if (!rule.enabled) { - return; - } - if (chain && rule.alt.indexOf(chain) < 0) { - return; - } - self.__cache__[chain].push(rule.fn); - }); - }); -}; + // [link]( "title" ) + // ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); + if (pos < max && start !== pos && res.ok) { + title = res.str; + pos = res.pos; + + // [link]( "title" ) + // ^^ skipping these spaces + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0a) { + break; + } + } + } else { + title = ""; + } + if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { + state.pos = oldPos; + return false; + } + pos++; + } else { + // + // Link reference + // + if (typeof state.env.references === "undefined") { + return false; + } + if (pos < max && state.src.charCodeAt(pos) === 0x5b /* [ */) { + start = pos + 1; + pos = state.md.helpers.parseLinkLabel(state, pos); + if (pos >= 0) { + label = state.src.slice(start, pos++); + } else { + pos = labelEnd + 1; + } + } else { + pos = labelEnd + 1; + } -/** - * Ruler.at(name, fn [, options]) - * - name (String): rule name to replace. - * - fn (Function): new rule function. - * - options (Object): new rule options (not mandatory). - * - * Replace rule by name with new function & options. Throws error if name not - * found. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * Replace existing typographer replacement rule with new one: - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.core.ruler.at('replacements', function replace(state) { - * //... - * }); - * ``` - **/ -Ruler.prototype.at = function (name, fn, options) { - const index = this.__find__(name); - const opt = options || {}; - if (index === -1) { - throw new Error('Parser rule not found: ' + name); - } - this.__rules__[index].fn = fn; - this.__rules__[index].alt = opt.alt || []; - this.__cache__ = null; -}; + // covers label === '' and label === undefined + // (collapsed reference link and shortcut reference link respectively) + if (!label) { + label = state.src.slice(labelStart, labelEnd); + } + ref = state.env.references[normalizeReference(label)]; + if (!ref) { + state.pos = oldPos; + return false; + } + href = ref.href; + title = ref.title; + } -/** - * Ruler.before(beforeName, ruleName, fn [, options]) - * - beforeName (String): new rule will be added before this one. - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Add new rule to chain before one with given name. See also - * [[Ruler.after]], [[Ruler.push]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { - * //... - * }); - * ``` - **/ -Ruler.prototype.before = function (beforeName, ruleName, fn, options) { - const index = this.__find__(beforeName); - const opt = options || {}; - if (index === -1) { - throw new Error('Parser rule not found: ' + beforeName); - } - this.__rules__.splice(index, 0, { - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [] - }); - this.__cache__ = null; -}; + // + // We found the end of the link, and know for a fact it's a valid link; + // so all that's left to do is to call tokenizer. + // + if (!silent) { + content = state.src.slice(labelStart, labelEnd); + const tokens = []; + state.md.inline.parse(content, state.md, state.env, tokens); + const token = state.push("image", "img", 0); + const attrs = [ + ["src", href], + ["alt", ""], + ]; + token.attrs = attrs; + token.children = tokens; + token.content = content; + if (title) { + attrs.push(["title", title]); + } + } + state.pos = pos; + state.posMax = max; + return true; + } -/** - * Ruler.after(afterName, ruleName, fn [, options]) - * - afterName (String): new rule will be added after this one. - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Add new rule to chain after one with given name. See also - * [[Ruler.before]], [[Ruler.push]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.inline.ruler.after('text', 'my_rule', function replace(state) { - * //... - * }); - * ``` - **/ -Ruler.prototype.after = function (afterName, ruleName, fn, options) { - const index = this.__find__(afterName); - const opt = options || {}; - if (index === -1) { - throw new Error('Parser rule not found: ' + afterName); - } - this.__rules__.splice(index + 1, 0, { - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [] - }); - this.__cache__ = null; -}; + // Process autolinks '' -/** - * Ruler.push(ruleName, fn [, options]) - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Push new rule to the end of chain. See also - * [[Ruler.before]], [[Ruler.after]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.core.ruler.push('my_rule', function replace(state) { - * //... - * }); - * ``` - **/ -Ruler.prototype.push = function (ruleName, fn, options) { - const opt = options || {}; - this.__rules__.push({ - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [] - }); - this.__cache__ = null; -}; + /* eslint max-len:0 */ + const EMAIL_RE = + /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; + /* eslint-disable-next-line no-control-regex */ + const AUTOLINK_RE = + /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/; + function autolink(state, silent) { + let pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x3c /* < */) { + return false; + } + const start = state.pos; + const max = state.posMax; + for (;;) { + if (++pos >= max) return false; + const ch = state.src.charCodeAt(pos); + if (ch === 0x3c /* < */) return false; + if (ch === 0x3e /* > */) break; + } + const url = state.src.slice(start + 1, pos); + if (AUTOLINK_RE.test(url)) { + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) { + return false; + } + if (!silent) { + const token_o = state.push("link_open", "a", 1); + token_o.attrs = [["href", fullUrl]]; + token_o.markup = "autolink"; + token_o.info = "auto"; + const token_t = state.push("text", "", 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push("link_close", "a", -1); + token_c.markup = "autolink"; + token_c.info = "auto"; + } + state.pos += url.length + 2; + return true; + } + if (EMAIL_RE.test(url)) { + const fullUrl = state.md.normalizeLink("mailto:" + url); + if (!state.md.validateLink(fullUrl)) { + return false; + } + if (!silent) { + const token_o = state.push("link_open", "a", 1); + token_o.attrs = [["href", fullUrl]]; + token_o.markup = "autolink"; + token_o.info = "auto"; + const token_t = state.push("text", "", 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push("link_close", "a", -1); + token_c.markup = "autolink"; + token_c.info = "auto"; + } + state.pos += url.length + 2; + return true; + } + return false; + } -/** - * Ruler.enable(list [, ignoreInvalid]) -> Array - * - list (String|Array): list of rule names to enable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable rules with given names. If any rule name not found - throw Error. - * Errors can be disabled by second param. - * - * Returns list of found rule names (if no exception happened). - * - * See also [[Ruler.disable]], [[Ruler.enableOnly]]. - **/ -Ruler.prototype.enable = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; - } - const result = []; - - // Search by name and enable - list.forEach(function (name) { - const idx = this.__find__(name); - if (idx < 0) { - if (ignoreInvalid) { - return; - } - throw new Error('Rules manager: invalid rule name ' + name); - } - this.__rules__[idx].enabled = true; - result.push(name); - }, this); - this.__cache__ = null; - return result; -}; + // Process html tags -/** - * Ruler.enableOnly(list [, ignoreInvalid]) - * - list (String|Array): list of rule names to enable (whitelist). - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable rules with given names, and disable everything else. If any rule name - * not found - throw Error. Errors can be disabled by second param. - * - * See also [[Ruler.disable]], [[Ruler.enable]]. - **/ -Ruler.prototype.enableOnly = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; - } - this.__rules__.forEach(function (rule) { - rule.enabled = false; - }); - this.enable(list, ignoreInvalid); -}; + function isLinkOpen(str) { + return /^\s]/i.test(str); + } + function isLinkClose(str) { + return /^<\/a\s*>/i.test(str); + } + function isLetter(ch) { + /* eslint no-bitwise:0 */ + const lc = ch | 0x20; // to lower case + return lc >= 0x61 /* a */ && lc <= 0x7a /* z */; + } + function html_inline(state, silent) { + if (!state.md.options.html) { + return false; + } -/** - * Ruler.disable(list [, ignoreInvalid]) -> Array - * - list (String|Array): list of rule names to disable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Disable rules with given names. If any rule name not found - throw Error. - * Errors can be disabled by second param. - * - * Returns list of found rule names (if no exception happened). - * - * See also [[Ruler.enable]], [[Ruler.enableOnly]]. - **/ -Ruler.prototype.disable = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; - } - const result = []; - - // Search by name and disable - list.forEach(function (name) { - const idx = this.__find__(name); - if (idx < 0) { - if (ignoreInvalid) { - return; - } - throw new Error('Rules manager: invalid rule name ' + name); - } - this.__rules__[idx].enabled = false; - result.push(name); - }, this); - this.__cache__ = null; - return result; -}; + // Check start + const max = state.posMax; + const pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x3c /* < */ || pos + 2 >= max) { + return false; + } -/** - * Ruler.getRules(chainName) -> Array - * - * Return array of active functions (rules) for given chain name. It analyzes - * rules configuration, compiles caches if not exists and returns result. - * - * Default chain name is `''` (empty string). It can't be skipped. That's - * done intentionally, to keep signature monomorphic for high speed. - **/ -Ruler.prototype.getRules = function (chainName) { - if (this.__cache__ === null) { - this.__compile__(); - } + // Quick fail on second char + const ch = state.src.charCodeAt(pos + 1); + if ( + ch !== 0x21 /* ! */ && + ch !== 0x3f /* ? */ && + ch !== 0x2f /* / */ && + !isLetter(ch) + ) { + return false; + } + const match = state.src.slice(pos).match(HTML_TAG_RE); + if (!match) { + return false; + } + if (!silent) { + const token = state.push("html_inline", "", 0); + token.content = match[0]; + if (isLinkOpen(token.content)) state.linkLevel++; + if (isLinkClose(token.content)) state.linkLevel--; + } + state.pos += match[0].length; + return true; + } - // Chain can be empty, if rules disabled. But we still have to return Array. - return this.__cache__[chainName] || []; -}; + // Process html entity - {, ¯, ", ... + + const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; + const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; + function entity(state, silent) { + const pos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(pos) !== 0x26 /* & */) return false; + if (pos + 1 >= max) return false; + const ch = state.src.charCodeAt(pos + 1); + if (ch === 0x23 /* # */) { + const match = state.src.slice(pos).match(DIGITAL_RE); + if (match) { + if (!silent) { + const code = + match[1][0].toLowerCase() === "x" + ? parseInt(match[1].slice(1), 16) + : parseInt(match[1], 10); + const token = state.push("text_special", "", 0); + token.content = isValidEntityCode(code) + ? fromCodePoint(code) + : fromCodePoint(0xfffd); + token.markup = match[0]; + token.info = "entity"; + } + state.pos += match[0].length; + return true; + } + } else { + const match = state.src.slice(pos).match(NAMED_RE); + if (match) { + const decoded = entities.decodeHTML(match[0]); + if (decoded !== match[0]) { + if (!silent) { + const token = state.push("text_special", "", 0); + token.content = decoded; + token.markup = match[0]; + token.info = "entity"; + } + state.pos += match[0].length; + return true; + } + } + } + return false; + } -// Token class - -/** - * class Token - **/ - -/** - * new Token(type, tag, nesting) - * - * Create new token and fill passed properties. - **/ -function Token(type, tag, nesting) { - /** - * Token#type -> String - * - * Type of the token (string, e.g. "paragraph_open") - **/ - this.type = type; - - /** - * Token#tag -> String - * - * html tag name, e.g. "p" - **/ - this.tag = tag; - - /** - * Token#attrs -> Array - * - * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` - **/ - this.attrs = null; - - /** - * Token#map -> Array - * - * Source map info. Format: `[ line_begin, line_end ]` - **/ - this.map = null; - - /** - * Token#nesting -> Number - * - * Level change (number in {-1, 0, 1} set), where: - * - * - `1` means the tag is opening - * - `0` means the tag is self-closing - * - `-1` means the tag is closing - **/ - this.nesting = nesting; - - /** - * Token#level -> Number - * - * nesting level, the same as `state.level` - **/ - this.level = 0; - - /** - * Token#children -> Array - * - * An array of child nodes (inline and img tokens) - **/ - this.children = null; - - /** - * Token#content -> String - * - * In a case of self-closing tag (code, html, fence, etc.), - * it has contents of this tag. - **/ - this.content = ''; - - /** - * Token#markup -> String - * - * '*' or '_' for emphasis, fence string for fence, etc. - **/ - this.markup = ''; - - /** - * Token#info -> String - * - * Additional information: - * - * - Info string for "fence" tokens - * - The value "auto" for autolink "link_open" and "link_close" tokens - * - The string value of the item marker for ordered-list "list_item_open" tokens - **/ - this.info = ''; - - /** - * Token#meta -> Object - * - * A place for plugins to store an arbitrary data - **/ - this.meta = null; - - /** - * Token#block -> Boolean - * - * True for block-level tokens, false for inline tokens. - * Used in renderer to calculate line breaks - **/ - this.block = false; - - /** - * Token#hidden -> Boolean - * - * If it's true, ignore this element when rendering. Used for tight lists - * to hide paragraphs. - **/ - this.hidden = false; -} - -/** - * Token.attrIndex(name) -> Number - * - * Search attribute index by name. - **/ -Token.prototype.attrIndex = function attrIndex(name) { - if (!this.attrs) { - return -1; - } - const attrs = this.attrs; - for (let i = 0, len = attrs.length; i < len; i++) { - if (attrs[i][0] === name) { - return i; - } - } - return -1; -}; + // For each opening emphasis-like marker find a matching closing one + // -/** - * Token.attrPush(attrData) - * - * Add `[ name, value ]` attribute to list. Init attrs if necessary - **/ -Token.prototype.attrPush = function attrPush(attrData) { - if (this.attrs) { - this.attrs.push(attrData); - } else { - this.attrs = [attrData]; - } -}; + function processDelimiters(delimiters) { + const openersBottom = {}; + const max = delimiters.length; + if (!max) return; + + // headerIdx is the first delimiter of the current (where closer is) delimiter run + let headerIdx = 0; + let lastTokenIdx = -2; // needs any value lower than -1 + const jumps = []; + for (let closerIdx = 0; closerIdx < max; closerIdx++) { + const closer = delimiters[closerIdx]; + jumps.push(0); + + // markers belong to same delimiter run if: + // - they have adjacent tokens + // - AND markers are the same + // + if ( + delimiters[headerIdx].marker !== closer.marker || + lastTokenIdx !== closer.token - 1 + ) { + headerIdx = closerIdx; + } + lastTokenIdx = closer.token; + + // Length is only used for emphasis-specific "rule of 3", + // if it's not defined (in strikethrough or 3rd party plugins), + // we can default it to 0 to disable those checks. + // + closer.length = closer.length || 0; + if (!closer.close) continue; + + // Previously calculated lower bounds (previous fails) + // for each marker, each delimiter length modulo 3, + // and for whether this closer can be an opener; + // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 + /* eslint-disable-next-line no-prototype-builtins */ + if (!openersBottom.hasOwnProperty(closer.marker)) { + openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]; + } + const minOpenerIdx = + openersBottom[closer.marker][ + (closer.open ? 3 : 0) + (closer.length % 3) + ]; + let openerIdx = headerIdx - jumps[headerIdx] - 1; + let newMinOpenerIdx = openerIdx; + for ( + ; + openerIdx > minOpenerIdx; + openerIdx -= jumps[openerIdx] + 1 + ) { + const opener = delimiters[openerIdx]; + if (opener.marker !== closer.marker) continue; + if (opener.open && opener.end < 0) { + let isOddMatch = false; + + // from spec: + // + // If one of the delimiters can both open and close emphasis, then the + // sum of the lengths of the delimiter runs containing the opening and + // closing delimiters must not be a multiple of 3 unless both lengths + // are multiples of 3. + // + if (opener.close || closer.open) { + if ((opener.length + closer.length) % 3 === 0) { + if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { + isOddMatch = true; + } + } + } + if (!isOddMatch) { + // If previous delimiter cannot be an opener, we can safely skip + // the entire sequence in future checks. This is required to make + // sure algorithm has linear complexity (see *_*_*_*_*_... case). + // + const lastJump = + openerIdx > 0 && !delimiters[openerIdx - 1].open + ? jumps[openerIdx - 1] + 1 + : 0; + jumps[closerIdx] = closerIdx - openerIdx + lastJump; + jumps[openerIdx] = lastJump; + closer.open = false; + opener.end = closerIdx; + opener.close = false; + newMinOpenerIdx = -1; + // treat next token as start of run, + // it optimizes skips in **<...>**a**<...>** pathological case + lastTokenIdx = -2; + break; + } + } + } + if (newMinOpenerIdx !== -1) { + // If match for this delimiter run failed, we want to set lower bound for + // future lookups. This is required to make sure algorithm has linear + // complexity. + // + // See details here: + // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 + // + openersBottom[closer.marker][ + (closer.open ? 3 : 0) + ((closer.length || 0) % 3) + ] = newMinOpenerIdx; + } + } + } + function link_pairs(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + processDelimiters(state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + processDelimiters(tokens_meta[curr].delimiters); + } + } + } -/** - * Token.attrSet(name, value) - * - * Set `name` attribute to `value`. Override old value if exists. - **/ -Token.prototype.attrSet = function attrSet(name, value) { - const idx = this.attrIndex(name); - const attrData = [name, value]; - if (idx < 0) { - this.attrPush(attrData); - } else { - this.attrs[idx] = attrData; - } -}; + // Clean up tokens after emphasis and strikethrough postprocessing: + // merge adjacent text nodes into one and re-calculate all token levels + // + // This is necessary because initially emphasis delimiter markers (*, _, ~) + // are treated as their own separate text tokens. Then emphasis rule either + // leaves them as text (needed to merge with adjacent text) or turns them + // into opening/closing tags (which messes up levels inside). + // -/** - * Token.attrGet(name) - * - * Get the value of attribute `name`, or null if it does not exist. - **/ -Token.prototype.attrGet = function attrGet(name) { - const idx = this.attrIndex(name); - let value = null; - if (idx >= 0) { - value = this.attrs[idx][1]; - } - return value; -}; + function fragments_join(state) { + let curr, last; + let level = 0; + const tokens = state.tokens; + const max = state.tokens.length; + for (curr = last = 0; curr < max; curr++) { + // re-calculate levels after emphasis/strikethrough turns some text nodes + // into opening/closing tags + if (tokens[curr].nesting < 0) level--; // closing tag + tokens[curr].level = level; + if (tokens[curr].nesting > 0) level++; // opening tag + + if ( + tokens[curr].type === "text" && + curr + 1 < max && + tokens[curr + 1].type === "text" + ) { + // collapse two adjacent text nodes + tokens[curr + 1].content = + tokens[curr].content + tokens[curr + 1].content; + } else { + if (curr !== last) { + tokens[last] = tokens[curr]; + } + last++; + } + } + if (curr !== last) { + tokens.length = last; + } + } -/** - * Token.attrJoin(name, value) - * - * Join value to existing attribute via space. Or create new attribute if not - * exists. Useful to operate with token classes. - **/ -Token.prototype.attrJoin = function attrJoin(name, value) { - const idx = this.attrIndex(name); - if (idx < 0) { - this.attrPush([name, value]); - } else { - this.attrs[idx][1] = this.attrs[idx][1] + ' ' + value; - } -}; + /** internal + * class ParserInline + * + * Tokenizes paragraph content. + **/ + + // Parser rules + + const _rules = [ + ["text", text], + ["linkify", linkify], + ["newline", newline], + ["escape", escape], + ["backticks", backtick], + ["strikethrough", r_strikethrough.tokenize], + ["emphasis", r_emphasis.tokenize], + ["link", link], + ["image", image], + ["autolink", autolink], + ["html_inline", html_inline], + ["entity", entity], + ]; + + // `rule2` ruleset was created specifically for emphasis/strikethrough + // post-processing and may be changed in the future. + // + // Don't use this for anything except pairs (plugins working with `balance_pairs`). + // + const _rules2 = [ + ["balance_pairs", link_pairs], + ["strikethrough", r_strikethrough.postProcess], + ["emphasis", r_emphasis.postProcess], + // rules for pairs separate '**' into its own text tokens, which may be left unused, + // rule below merges unused segments back with the rest of the text + ["fragments_join", fragments_join], + ]; -// Core state object -// - -function StateCore(src, md, env) { - this.src = src; - this.env = env; - this.tokens = []; - this.inlineMode = false; - this.md = md; // link to parser instance -} - -// re-export Token class to use in core rules -StateCore.prototype.Token = Token; - -// Normalize input string - -// https://spec.commonmark.org/0.29/#line-ending -const NEWLINES_RE = /\r\n?|\n/g; -const NULL_RE = /\0/g; -function normalize(state) { - let str; - - // Normalize newlines - str = state.src.replace(NEWLINES_RE, '\n'); - - // Replace NULL characters - str = str.replace(NULL_RE, '\uFFFD'); - state.src = str; -} -function block(state) { - let token; - if (state.inlineMode) { - token = new state.Token('inline', '', 0); - token.content = state.src; - token.map = [0, 1]; - token.children = []; - state.tokens.push(token); - } else { - state.md.block.parse(state.src, state.md, state.env, state.tokens); - } -} -function inline(state) { - const tokens = state.tokens; - - // Parse inlines - for (let i = 0, l = tokens.length; i < l; i++) { - const tok = tokens[i]; - if (tok.type === 'inline') { - state.md.inline.parse(tok.content, state.md, state.env, tok.children); - } - } -} - -// Replace link-like texts with link nodes. -// -// Currently restricted by `md.validateLink()` to http/https/ftp -// - -function isLinkOpen$1(str) { - return /^\s]/i.test(str); -} -function isLinkClose$1(str) { - return /^<\/a\s*>/i.test(str); -} -function linkify$1(state) { - const blockTokens = state.tokens; - if (!state.md.options.linkify) { - return; - } - for (let j = 0, l = blockTokens.length; j < l; j++) { - if (blockTokens[j].type !== 'inline' || !state.md.linkify.pretest(blockTokens[j].content)) { - continue; - } - let tokens = blockTokens[j].children; - let htmlLinkLevel = 0; + /** + * new ParserInline() + **/ + function ParserInline() { + /** + * ParserInline#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of inline rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules.length; i++) { + this.ruler.push(_rules[i][0], _rules[i][1]); + } + + /** + * ParserInline#ruler2 -> Ruler + * + * [[Ruler]] instance. Second ruler used for post-processing + * (e.g. in emphasis-like rules). + **/ + this.ruler2 = new Ruler(); + for (let i = 0; i < _rules2.length; i++) { + this.ruler2.push(_rules2[i][0], _rules2[i][1]); + } + } + + // Skip single token by running all rules in validation mode; + // returns `true` if any rule reported success + // + ParserInline.prototype.skipToken = function (state) { + const pos = state.pos; + const rules = this.ruler.getRules(""); + const len = rules.length; + const maxNesting = state.md.options.maxNesting; + const cache = state.cache; + if (typeof cache[pos] !== "undefined") { + state.pos = cache[pos]; + return; + } + let ok = false; + if (state.level < maxNesting) { + for (let i = 0; i < len; i++) { + // Increment state.level and decrement it later to limit recursion. + // It's harmless to do here, because no tokens are created. But ideally, + // we'd need a separate private state variable for this purpose. + // + state.level++; + ok = rules[i](state, true); + state.level--; + if (ok) { + if (pos >= state.pos) { + throw new Error("inline rule didn't increment state.pos"); + } + break; + } + } + } else { + // Too much nesting, just skip until the end of the paragraph. + // + // NOTE: this will cause links to behave incorrectly in the following case, + // when an amount of `[` is exactly equal to `maxNesting + 1`: + // + // [[[[[[[[[[[[[[[[[[[[[foo]() + // + // TODO: remove this workaround when CM standard will allow nested links + // (we can replace it by preventing links from being parsed in + // validation mode) + // + state.pos = state.posMax; + } + if (!ok) { + state.pos++; + } + cache[pos] = state.pos; + }; + + // Generate tokens for input range + // + ParserInline.prototype.tokenize = function (state) { + const rules = this.ruler.getRules(""); + const len = rules.length; + const end = state.posMax; + const maxNesting = state.md.options.maxNesting; + while (state.pos < end) { + // Try all possible rules. + // On success, rule should: + // + // - update `state.pos` + // - update `state.tokens` + // - return true + const prevPos = state.pos; + let ok = false; + if (state.level < maxNesting) { + for (let i = 0; i < len; i++) { + ok = rules[i](state, false); + if (ok) { + if (prevPos >= state.pos) { + throw new Error("inline rule didn't increment state.pos"); + } + break; + } + } + } + if (ok) { + if (state.pos >= end) { + break; + } + continue; + } + state.pending += state.src[state.pos++]; + } + if (state.pending) { + state.pushPending(); + } + }; - // We scan from the end, to keep position when new tags added. - // Use reversed logic in links start/end match - for (let i = tokens.length - 1; i >= 0; i--) { - const currentToken = tokens[i]; + /** + * ParserInline.parse(str, md, env, outTokens) + * + * Process input string and push inline tokens into `outTokens` + **/ + ParserInline.prototype.parse = function (str, md, env, outTokens) { + const state = new this.State(str, md, env, outTokens); + this.tokenize(state); + const rules = this.ruler2.getRules(""); + const len = rules.length; + for (let i = 0; i < len; i++) { + rules[i](state); + } + }; + ParserInline.prototype.State = StateInline; + + // markdown-it default options + + var cfg_default = { + options: { + // Enable HTML tags in source + html: false, + // Use '/' to close single tags (
    ) + xhtmlOut: false, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: "language-", + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: "\u201c\u201d\u2018\u2019", + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with ) + xhtmlOut: false, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: "language-", + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: "\u201c\u201d\u2018\u2019", + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with 0) { - htmlLinkLevel--; - } - if (isLinkClose$1(currentToken.content)) { - htmlLinkLevel++; - } - } - if (htmlLinkLevel > 0) { - continue; - } - if (currentToken.type === 'text' && state.md.linkify.test(currentToken.content)) { - const text = currentToken.content; - let links = state.md.linkify.match(text); - - // Now split string to nodes - const nodes = []; - let level = currentToken.level; - let lastPos = 0; - - // forbid escape sequence at the start of the string, - // this avoids http\://example.com/ from being linkified as - // http:
    //example.com/ - if (links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === 'text_special') { - links = links.slice(1); - } - for (let ln = 0; ln < links.length; ln++) { - const url = links[ln].url; - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) { - continue; - } - let urlText = links[ln].text; + // Commonmark default options + + var cfg_commonmark = { + options: { + // Enable HTML tags in source + html: true, + // Use '/' to close single tags (
    ) + xhtmlOut: true, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: "language-", + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: "\u201c\u201d\u2018\u2019", + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with lastPos) { - const token = new state.Token('text', '', 0); - token.content = text.slice(lastPos, pos); - token.level = level; - nodes.push(token); - } - const token_o = new state.Token('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.level = level++; - token_o.markup = 'linkify'; - token_o.info = 'auto'; - nodes.push(token_o); - const token_t = new state.Token('text', '', 0); - token_t.content = urlText; - token_t.level = level; - nodes.push(token_t); - const token_c = new state.Token('link_close', 'a', -1); - token_c.level = --level; - token_c.markup = 'linkify'; - token_c.info = 'auto'; - nodes.push(token_c); - lastPos = links[ln].lastIndex; - } - if (lastPos < text.length) { - const token = new state.Token('text', '', 0); - token.content = text.slice(lastPos); - token.level = level; - nodes.push(token); - } - - // replace current node - blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes); - } - } - } -} - -// Simple typographic replacements -// -// (c) (C) → © -// (tm) (TM) → ™ -// (r) (R) → ® -// +- → ± -// ... → … (also ?.... → ?.., !.... → !..) -// ???????? → ???, !!!!! → !!!, `,,` → `,` -// -- → –, --- → — -// - -// TODO: -// - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ -// - multiplications 2 x 4 -> 2 × 4 - -const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; - -// Workaround for phantomjs - need regex without /g flag, -// or root check will fail every second time -const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; -const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig; -const SCOPED_ABBR = { - c: '©', - r: '®', - tm: '™' -}; -function replaceFn(match, name) { - return SCOPED_ABBR[name.toLowerCase()]; -} -function replace_scoped(inlineTokens) { - let inside_autolink = 0; - for (let i = inlineTokens.length - 1; i >= 0; i--) { - const token = inlineTokens[i]; - if (token.type === 'text' && !inside_autolink) { - token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); - } - if (token.type === 'link_open' && token.info === 'auto') { - inside_autolink--; - } - if (token.type === 'link_close' && token.info === 'auto') { - inside_autolink++; - } - } -} -function replace_rare(inlineTokens) { - let inside_autolink = 0; - for (let i = inlineTokens.length - 1; i >= 0; i--) { - const token = inlineTokens[i]; - if (token.type === 'text' && !inside_autolink) { - if (RARE_RE.test(token.content)) { - token.content = token.content.replace(/\+-/g, '±') - // .., ..., ....... -> … - // but ?..... & !..... -> ?.. & !.. - .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..').replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',') - // em-dash - .replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014') - // en-dash - .replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013').replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013'); - } - } - if (token.type === 'link_open' && token.info === 'auto') { - inside_autolink--; - } - if (token.type === 'link_close' && token.info === 'auto') { - inside_autolink++; - } - } -} -function replace(state) { - let blkIdx; - if (!state.md.options.typographer) { - return; - } - for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { - if (state.tokens[blkIdx].type !== 'inline') { - continue; - } - if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { - replace_scoped(state.tokens[blkIdx].children); - } - if (RARE_RE.test(state.tokens[blkIdx].content)) { - replace_rare(state.tokens[blkIdx].children); - } - } -} - -// Convert straight quotation marks to typographic ones -// - -const QUOTE_TEST_RE = /['"]/; -const QUOTE_RE = /['"]/g; -const APOSTROPHE = '\u2019'; /* ’ */ - -function replaceAt(str, index, ch) { - return str.slice(0, index) + ch + str.slice(index + 1); -} -function process_inlines(tokens, state) { - let j; - const stack = []; - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - const thisLevel = tokens[i].level; - for (j = stack.length - 1; j >= 0; j--) { - if (stack[j].level <= thisLevel) { - break; - } - } - stack.length = j + 1; - if (token.type !== 'text') { - continue; - } - let text = token.content; - let pos = 0; - let max = text.length; - - /* eslint no-labels:0,block-scoped-var:0 */ - OUTER: while (pos < max) { - QUOTE_RE.lastIndex = pos; - const t = QUOTE_RE.exec(text); - if (!t) { - break; - } - let canOpen = true; - let canClose = true; - pos = t.index + 1; - const isSingle = t[0] === "'"; - - // Find previous character, - // default to space if it's the beginning of the line - // - let lastChar = 0x20; - if (t.index - 1 >= 0) { - lastChar = text.charCodeAt(t.index - 1); - } else { - for (j = i - 1; j >= 0; j--) { - if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // lastChar defaults to 0x20 - if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' - - lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1); - break; - } - } + // Main parser class - // Find next character, - // default to space if it's the end of the line - // - let nextChar = 0x20; - if (pos < max) { - nextChar = text.charCodeAt(pos); - } else { - for (j = i + 1; j < tokens.length; j++) { - if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // nextChar defaults to 0x20 - if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + const config = { + default: cfg_default, + zero: cfg_zero, + commonmark: cfg_commonmark, + }; - nextChar = tokens[j].content.charCodeAt(0); - break; - } - } - const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); - const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); - const isLastWhiteSpace = isWhiteSpace(lastChar); - const isNextWhiteSpace = isWhiteSpace(nextChar); - if (isNextWhiteSpace) { - canOpen = false; - } else if (isNextPunctChar) { - if (!(isLastWhiteSpace || isLastPunctChar)) { - canOpen = false; - } - } - if (isLastWhiteSpace) { - canClose = false; - } else if (isLastPunctChar) { - if (!(isNextWhiteSpace || isNextPunctChar)) { - canClose = false; - } - } - if (nextChar === 0x22 /* " */ && t[0] === '"') { - if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { - // special case: 1"" - count first quote as an inch - canClose = canOpen = false; - } - } - if (canOpen && canClose) { - // Replace quotes in the middle of punctuation sequence, but not - // in the middle of the words, i.e.: // - // 1. foo " bar " baz - not replaced - // 2. foo-"-bar-"-baz - replaced - // 3. foo"bar"baz - not replaced + // This validator can prohibit more than really needed to prevent XSS. It's a + // tradeoff to keep code simple and to be secure by default. + // + // If you need different setup - override validator method as you wish. Or + // replace it with dummy function and use external sanitizer. // - canOpen = isLastPunctChar; - canClose = isNextPunctChar; - } - if (!canOpen && !canClose) { - // middle of word - if (isSingle) { - token.content = replaceAt(token.content, t.index, APOSTROPHE); - } - continue; - } - if (canClose) { - // this could be a closing quote, rewind the stack to get a match - for (j = stack.length - 1; j >= 0; j--) { - let item = stack[j]; - if (stack[j].level < thisLevel) { - break; - } - if (item.single === isSingle && stack[j].level === thisLevel) { - item = stack[j]; - let openQuote; - let closeQuote; - if (isSingle) { - openQuote = state.md.options.quotes[2]; - closeQuote = state.md.options.quotes[3]; - } else { - openQuote = state.md.options.quotes[0]; - closeQuote = state.md.options.quotes[1]; - } - // replace token.content *before* tokens[item.token].content, - // because, if they are pointing at the same token, replaceAt - // could mess up indices when quote length != 1 - token.content = replaceAt(token.content, t.index, closeQuote); - tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, openQuote); - pos += closeQuote.length - 1; - if (item.token === i) { - pos += openQuote.length - 1; + const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/; + const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/; + function validateLink(url) { + // url should be normalized at this point, and existing entities are decoded + const str = url.trim().toLowerCase(); + return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true; + } + const RECODE_HOSTNAME_FOR = ["http:", "https:", "mailto:"]; + function normalizeLink(url) { + const parsed = mdurl__namespace.parse(url, true); + if (parsed.hostname) { + // Encode hostnames in urls like: + // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + // + // We don't encode unknown schemas, because it's likely that we encode + // something we shouldn't (e.g. `skype:name` treated as `skype:host`) + // + if ( + !parsed.protocol || + RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0 + ) { + try { + parsed.hostname = punycode.toASCII(parsed.hostname); + } catch (er) { + /**/ + } } - text = token.content; - max = text.length; - stack.length = j; - continue OUTER; } + return mdurl__namespace.encode(mdurl__namespace.format(parsed)); + } + function normalizeLinkText(url) { + const parsed = mdurl__namespace.parse(url, true); + if (parsed.hostname) { + // Encode hostnames in urls like: + // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + // + // We don't encode unknown schemas, because it's likely that we encode + // something we shouldn't (e.g. `skype:name` treated as `skype:host`) + // + if ( + !parsed.protocol || + RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0 + ) { + try { + parsed.hostname = punycode.toUnicode(parsed.hostname); + } catch (er) { + /**/ + } + } + } + + // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 + return mdurl__namespace.decode( + mdurl__namespace.format(parsed), + mdurl__namespace.decode.defaultChars + "%" + ); } - } - if (canOpen) { - stack.push({ - token: i, - pos: t.index, - single: isSingle, - level: thisLevel - }); - } else if (canClose && isSingle) { - token.content = replaceAt(token.content, t.index, APOSTROPHE); - } - } - } -} -function smartquotes(state) { - /* eslint max-depth:0 */ - if (!state.md.options.typographer) { - return; - } - for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { - if (state.tokens[blkIdx].type !== 'inline' || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) { - continue; - } - process_inlines(state.tokens[blkIdx].children, state); - } -} - -// Join raw text tokens with the rest of the text -// -// This is set as a separate rule to provide an opportunity for plugins -// to run text replacements after text join, but before escape join. -// -// For example, `\:)` shouldn't be replaced with an emoji. -// - -function text_join(state) { - let curr, last; - const blockTokens = state.tokens; - const l = blockTokens.length; - for (let j = 0; j < l; j++) { - if (blockTokens[j].type !== 'inline') continue; - const tokens = blockTokens[j].children; - const max = tokens.length; - for (curr = 0; curr < max; curr++) { - if (tokens[curr].type === 'text_special') { - tokens[curr].type = 'text'; - } - } - for (curr = last = 0; curr < max; curr++) { - if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { - // collapse two adjacent text nodes - tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; - } else { - if (curr !== last) { - tokens[last] = tokens[curr]; - } - last++; - } - } - if (curr !== last) { - tokens.length = last; - } - } -} - -/** internal - * class Core - * - * Top-level rules executor. Glues block/inline parsers and does intermediate - * transformations. - **/ - -const _rules$2 = [['normalize', normalize], ['block', block], ['inline', inline], ['linkify', linkify$1], ['replacements', replace], ['smartquotes', smartquotes], -// `text_join` finds `text_special` tokens (for escape sequences) -// and joins them with the rest of the text -['text_join', text_join]]; - -/** - * new Core() - **/ -function Core() { - /** - * Core#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of core rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules$2.length; i++) { - this.ruler.push(_rules$2[i][0], _rules$2[i][1]); - } -} - -/** - * Core.process(state) - * - * Executes core chain rules. - **/ -Core.prototype.process = function (state) { - const rules = this.ruler.getRules(''); - for (let i = 0, l = rules.length; i < l; i++) { - rules[i](state); - } -}; -Core.prototype.State = StateCore; - -// Parser state class - -function StateBlock(src, md, env, tokens) { - this.src = src; - - // link to parser instance - this.md = md; - this.env = env; - - // - // Internal state vartiables - // - - this.tokens = tokens; - this.bMarks = []; // line begin offsets for fast jumps - this.eMarks = []; // line end offsets for fast jumps - this.tShift = []; // offsets of the first non-space characters (tabs not expanded) - this.sCount = []; // indents for each line (tabs expanded) - - // An amount of virtual spaces (tabs expanded) between beginning - // of each line (bMarks) and real beginning of that line. - // - // It exists only as a hack because blockquotes override bMarks - // losing information in the process. - // - // It's used only when expanding tabs, you can think about it as - // an initial tab length, e.g. bsCount=21 applied to string `\t123` - // means first tab should be expanded to 4-21%4 === 3 spaces. - // - this.bsCount = []; - - // block parser variables - - // required block content indent (for example, if we are - // inside a list, it would be positioned after list marker) - this.blkIndent = 0; - this.line = 0; // line index in src - this.lineMax = 0; // lines count - this.tight = false; // loose/tight mode for lists - this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) - this.listIndent = -1; // indent of the current list block (-1 if there isn't any) - - // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' - // used in lists to determine if they interrupt a paragraph - this.parentType = 'root'; - this.level = 0; - - // Create caches - // Generate markers. - const s = this.src; - for (let start = 0, pos = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos < len; pos++) { - const ch = s.charCodeAt(pos); - if (!indent_found) { - if (isSpace(ch)) { - indent++; - if (ch === 0x09) { - offset += 4 - offset % 4; - } else { - offset++; - } - continue; - } else { - indent_found = true; - } - } - if (ch === 0x0A || pos === len - 1) { - if (ch !== 0x0A) { - pos++; - } - this.bMarks.push(start); - this.eMarks.push(pos); - this.tShift.push(indent); - this.sCount.push(offset); - this.bsCount.push(0); - indent_found = false; - indent = 0; - offset = 0; - start = pos + 1; - } - } - // Push fake entry to simplify cache bounds checks - this.bMarks.push(s.length); - this.eMarks.push(s.length); - this.tShift.push(0); - this.sCount.push(0); - this.bsCount.push(0); - this.lineMax = this.bMarks.length - 1; // don't count last fake line -} - -// Push new token to "stream". -// -StateBlock.prototype.push = function (type, tag, nesting) { - const token = new Token(type, tag, nesting); - token.block = true; - if (nesting < 0) this.level--; // closing tag - token.level = this.level; - if (nesting > 0) this.level++; // opening tag - - this.tokens.push(token); - return token; -}; -StateBlock.prototype.isEmpty = function isEmpty(line) { - return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; -}; -StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { - for (let max = this.lineMax; from < max; from++) { - if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { - break; - } - } - return from; -}; + /** + * class MarkdownIt + * + * Main parser/renderer class. + * + * ##### Usage + * + * ```javascript + * // node.js, "classic" way: + * var MarkdownIt = require('markdown-it'), + * md = new MarkdownIt(); + * var result = md.render('# markdown-it rulezz!'); + * + * // node.js, the same, but with sugar: + * var md = require('markdown-it')(); + * var result = md.render('# markdown-it rulezz!'); + * + * // browser without AMD, added to "window" on script load + * // Note, there are no dash. + * var md = window.markdownit(); + * var result = md.render('# markdown-it rulezz!'); + * ``` + * + * Single line rendering, without paragraph wrap: + * + * ```javascript + * var md = require('markdown-it')(); + * var result = md.renderInline('__markdown-it__ rulezz!'); + * ``` + **/ -// Skip spaces from given position. -StateBlock.prototype.skipSpaces = function skipSpaces(pos) { - for (let max = this.src.length; pos < max; pos++) { - const ch = this.src.charCodeAt(pos); - if (!isSpace(ch)) { - break; - } - } - return pos; -}; + /** + * new MarkdownIt([presetName, options]) + * - presetName (String): optional, `commonmark` / `zero` + * - options (Object) + * + * Creates parser instanse with given config. Can be called without `new`. + * + * ##### presetName + * + * MarkdownIt provides named presets as a convenience to quickly + * enable/disable active syntax rules and options for common use cases. + * + * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.mjs) - + * configures parser to strict [CommonMark](http://commonmark.org/) mode. + * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.mjs) - + * similar to GFM, used when no preset name given. Enables all available rules, + * but still without html, typographer & autolinker. + * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.mjs) - + * all rules disabled. Useful to quickly setup your config via `.enable()`. + * For example, when you need only `bold` and `italic` markup and nothing else. + * + * ##### options: + * + * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! + * That's not safe! You may need external sanitizer to protect output from XSS. + * It's better to extend features via plugins, instead of enabling HTML. + * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags + * (`
    `). This is needed only for full CommonMark compatibility. In real + * world you will need HTML output. + * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
    `. + * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. + * Can be useful for external highlighters. + * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. + * - __typographer__ - `false`. Set `true` to enable [some language-neutral + * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs) + + * quotes beautification (smartquotes). + * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement + * pairs, when typographer enabled and smartquotes on. For example, you can + * use `'«»„“'` for Russian, `'„“‚‘'` for German, and + * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). + * - __highlight__ - `null`. Highlighter function for fenced code blocks. + * Highlighter `function (str, lang)` should return escaped HTML. It can also + * return empty string if the source was not changed and should be escaped + * externaly. If result starts with ` or ``): + * + * ```javascript + * var hljs = require('highlight.js') // https://highlightjs.org/ + * + * // Actual default values + * var md = require('markdown-it')({ + * highlight: function (str, lang) { + * if (lang && hljs.getLanguage(lang)) { + * try { + * return '
    ' +
    +         *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
    +         *                '
    '; + * } catch (__) {} + * } + * + * return '
    ' + md.utils.escapeHtml(str) + '
    '; + * } + * }); + * ``` + * + **/ + function MarkdownIt(presetName, options) { + if (!(this instanceof MarkdownIt)) { + return new MarkdownIt(presetName, options); + } + if (!options) { + if (!isString(presetName)) { + options = presetName || {}; + presetName = "default"; + } + } -// Skip spaces from given position in reverse. -StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) { - if (pos <= min) { - return pos; - } - while (pos > min) { - if (!isSpace(this.src.charCodeAt(--pos))) { - return pos + 1; - } - } - return pos; -}; + /** + * MarkdownIt#inline -> ParserInline + * + * Instance of [[ParserInline]]. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.inline = new ParserInline(); -// Skip char codes from given position -StateBlock.prototype.skipChars = function skipChars(pos, code) { - for (let max = this.src.length; pos < max; pos++) { - if (this.src.charCodeAt(pos) !== code) { - break; - } - } - return pos; -}; + /** + * MarkdownIt#block -> ParserBlock + * + * Instance of [[ParserBlock]]. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.block = new ParserBlock(); -// Skip char codes reverse from given position - 1 -StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) { - if (pos <= min) { - return pos; - } - while (pos > min) { - if (code !== this.src.charCodeAt(--pos)) { - return pos + 1; - } - } - return pos; -}; + /** + * MarkdownIt#core -> Core + * + * Instance of [[Core]] chain executor. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.core = new Core(); -// cut lines range from source. -StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) { - if (begin >= end) { - return ''; - } - const queue = new Array(end - begin); - for (let i = 0, line = begin; line < end; line++, i++) { - let lineIndent = 0; - const lineStart = this.bMarks[line]; - let first = lineStart; - let last; - if (line + 1 < end || keepLastLF) { - // No need for bounds check because we have fake entry on tail. - last = this.eMarks[line] + 1; - } else { - last = this.eMarks[line]; - } - while (first < last && lineIndent < indent) { - const ch = this.src.charCodeAt(first); - if (isSpace(ch)) { - if (ch === 0x09) { - lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4; - } else { - lineIndent++; - } - } else if (first - lineStart < this.tShift[line]) { - // patched tShift masked characters to look like spaces (blockquotes, list markers) - lineIndent++; - } else { - break; - } - first++; - } - if (lineIndent > indent) { - // partially expanding tabs in code blocks, e.g '\t\tfoobar' - // with indent=2 becomes ' \tfoobar' - queue[i] = new Array(lineIndent - indent + 1).join(' ') + this.src.slice(first, last); - } else { - queue[i] = this.src.slice(first, last); - } - } - return queue.join(''); -}; + /** + * MarkdownIt#renderer -> Renderer + * + * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering + * rules for new token types, generated by plugins. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * function myToken(tokens, idx, options, env, self) { + * //... + * return result; + * }; + * + * md.renderer.rules['my_token'] = myToken + * ``` + * + * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs). + **/ + this.renderer = new Renderer(); -// re-export Token class to use in block rules -StateBlock.prototype.Token = Token; - -// GFM table, https://github.github.com/gfm/#tables-extension- - -// Limit the amount of empty autocompleted cells in a table, -// see https://github.com/markdown-it/markdown-it/issues/1000, -// -// Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. -// We set it to 65k, which can expand user input by a factor of x370 -// (256x256 square is 1.8kB expanded into 650kB). -const MAX_AUTOCOMPLETED_CELLS = 0x10000; -function getLine(state, line) { - const pos = state.bMarks[line] + state.tShift[line]; - const max = state.eMarks[line]; - return state.src.slice(pos, max); -} -function escapedSplit(str) { - const result = []; - const max = str.length; - let pos = 0; - let ch = str.charCodeAt(pos); - let isEscaped = false; - let lastPos = 0; - let current = ''; - while (pos < max) { - if (ch === 0x7c /* | */) { - if (!isEscaped) { - // pipe separating cells, '|' - result.push(current + str.substring(lastPos, pos)); - current = ''; - lastPos = pos + 1; - } else { - // escaped pipe, '\|' - current += str.substring(lastPos, pos - 1); - lastPos = pos; - } - } - isEscaped = ch === 0x5c /* \ */; - pos++; - ch = str.charCodeAt(pos); - } - result.push(current + str.substring(lastPos)); - return result; -} -function table(state, startLine, endLine, silent) { - // should have at least two lines - if (startLine + 2 > endLine) { - return false; - } - let nextLine = startLine + 1; - if (state.sCount[nextLine] < state.blkIndent) { - return false; - } + /** + * MarkdownIt#linkify -> LinkifyIt + * + * [linkify-it](https://github.com/markdown-it/linkify-it) instance. + * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs) + * rule. + **/ + this.linkify = new LinkifyIt(); - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - return false; - } + /** + * MarkdownIt#validateLink(url) -> Boolean + * + * Link validation function. CommonMark allows too much in links. By default + * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas + * except some embedded image types. + * + * You can change this behaviour: + * + * ```javascript + * var md = require('markdown-it')(); + * // enable everything + * md.validateLink = function () { return true; } + * ``` + **/ + this.validateLink = validateLink; - // first character of the second line should be '|', '-', ':', - // and no other characters are allowed but spaces; - // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp + /** + * MarkdownIt#normalizeLink(url) -> String + * + * Function used to encode link url to a machine-readable format, + * which includes url-encoding, punycode, etc. + **/ + this.normalizeLink = normalizeLink; - let pos = state.bMarks[nextLine] + state.tShift[nextLine]; - if (pos >= state.eMarks[nextLine]) { - return false; - } - const firstCh = state.src.charCodeAt(pos++); - if (firstCh !== 0x7C /* | */ && firstCh !== 0x2D /* - */ && firstCh !== 0x3A /* : */) { - return false; - } - if (pos >= state.eMarks[nextLine]) { - return false; - } - const secondCh = state.src.charCodeAt(pos++); - if (secondCh !== 0x7C /* | */ && secondCh !== 0x2D /* - */ && secondCh !== 0x3A /* : */ && !isSpace(secondCh)) { - return false; - } + /** + * MarkdownIt#normalizeLinkText(url) -> String + * + * Function used to decode link url to a human-readable format` + **/ + this.normalizeLinkText = normalizeLinkText; - // if first character is '-', then second character must not be a space - // (due to parsing ambiguity with list) - if (firstCh === 0x2D /* - */ && isSpace(secondCh)) { - return false; - } - while (pos < state.eMarks[nextLine]) { - const ch = state.src.charCodeAt(pos); - if (ch !== 0x7C /* | */ && ch !== 0x2D /* - */ && ch !== 0x3A /* : */ && !isSpace(ch)) { - return false; - } - pos++; - } - let lineText = getLine(state, startLine + 1); - let columns = lineText.split('|'); - const aligns = []; - for (let i = 0; i < columns.length; i++) { - const t = columns[i].trim(); - if (!t) { - // allow empty columns before and after table, but not in between columns; - // e.g. allow ` |---| `, disallow ` ---||--- ` - if (i === 0 || i === columns.length - 1) { - continue; - } else { - return false; - } - } - if (!/^:?-+:?$/.test(t)) { - return false; - } - if (t.charCodeAt(t.length - 1) === 0x3A /* : */) { - aligns.push(t.charCodeAt(0) === 0x3A /* : */ ? 'center' : 'right'); - } else if (t.charCodeAt(0) === 0x3A /* : */) { - aligns.push('left'); - } else { - aligns.push(''); - } - } - lineText = getLine(state, startLine).trim(); - if (lineText.indexOf('|') === -1) { - return false; - } - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - columns = escapedSplit(lineText); - if (columns.length && columns[0] === '') columns.shift(); - if (columns.length && columns[columns.length - 1] === '') columns.pop(); - - // header row will define an amount of columns in the entire table, - // and align row should be exactly the same (the rest of the rows can differ) - const columnCount = columns.length; - if (columnCount === 0 || columnCount !== aligns.length) { - return false; - } - if (silent) { - return true; - } - const oldParentType = state.parentType; - state.parentType = 'table'; - - // use 'blockquote' lists for termination because it's - // the most similar to tables - const terminatorRules = state.md.block.ruler.getRules('blockquote'); - const token_to = state.push('table_open', 'table', 1); - const tableLines = [startLine, 0]; - token_to.map = tableLines; - const token_tho = state.push('thead_open', 'thead', 1); - token_tho.map = [startLine, startLine + 1]; - const token_htro = state.push('tr_open', 'tr', 1); - token_htro.map = [startLine, startLine + 1]; - for (let i = 0; i < columns.length; i++) { - const token_ho = state.push('th_open', 'th', 1); - if (aligns[i]) { - token_ho.attrs = [['style', 'text-align:' + aligns[i]]]; - } - const token_il = state.push('inline', '', 0); - token_il.content = columns[i].trim(); - token_il.children = []; - state.push('th_close', 'th', -1); - } - state.push('tr_close', 'tr', -1); - state.push('thead_close', 'thead', -1); - let tbodyLines; - let autocompletedCells = 0; - for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { - if (state.sCount[nextLine] < state.blkIndent) { - break; - } - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } - } - if (terminate) { - break; - } - lineText = getLine(state, nextLine).trim(); - if (!lineText) { - break; - } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - break; - } - columns = escapedSplit(lineText); - if (columns.length && columns[0] === '') columns.shift(); - if (columns.length && columns[columns.length - 1] === '') columns.pop(); - - // note: autocomplete count can be negative if user specifies more columns than header, - // but that does not affect intended use (which is limiting expansion) - autocompletedCells += columnCount - columns.length; - if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) { - break; - } - if (nextLine === startLine + 2) { - const token_tbo = state.push('tbody_open', 'tbody', 1); - token_tbo.map = tbodyLines = [startLine + 2, 0]; - } - const token_tro = state.push('tr_open', 'tr', 1); - token_tro.map = [nextLine, nextLine + 1]; - for (let i = 0; i < columnCount; i++) { - const token_tdo = state.push('td_open', 'td', 1); - if (aligns[i]) { - token_tdo.attrs = [['style', 'text-align:' + aligns[i]]]; - } - const token_il = state.push('inline', '', 0); - token_il.content = columns[i] ? columns[i].trim() : ''; - token_il.children = []; - state.push('td_close', 'td', -1); - } - state.push('tr_close', 'tr', -1); - } - if (tbodyLines) { - state.push('tbody_close', 'tbody', -1); - tbodyLines[1] = nextLine; - } - state.push('table_close', 'table', -1); - tableLines[1] = nextLine; - state.parentType = oldParentType; - state.line = nextLine; - return true; -} + // Expose utils & helpers for easy acces from plugins -// Code block (4 spaces padded) + /** + * MarkdownIt#utils -> utils + * + * Assorted utility functions, useful to write plugins. See details + * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs). + **/ + this.utils = utils; -function code(state, startLine, endLine /*, silent */) { - if (state.sCount[startLine] - state.blkIndent < 4) { - return false; - } - let nextLine = startLine + 1; - let last = nextLine; - while (nextLine < endLine) { - if (state.isEmpty(nextLine)) { - nextLine++; - continue; - } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - nextLine++; - last = nextLine; - continue; - } - break; - } - state.line = last; - const token = state.push('code_block', 'code', 0); - token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + '\n'; - token.map = [startLine, state.line]; - return true; -} + /** + * MarkdownIt#helpers -> helpers + * + * Link components parser functions, useful to write plugins. See details + * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). + **/ + this.helpers = assign({}, helpers); + this.options = {}; + this.configure(presetName); + if (options) { + this.set(options); + } + } -// fences (``` lang, ~~~ lang) + /** chainable + * MarkdownIt.set(options) + * + * Set parser options (in the same format as in constructor). Probably, you + * will never need it, but you can change options after constructor call. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')() + * .set({ html: true, breaks: true }) + * .set({ typographer, true }); + * ``` + * + * __Note:__ To achieve the best possible performance, don't modify a + * `markdown-it` instance options on the fly. If you need multiple configurations + * it's best to create multiple instances and initialize each with separate + * config. + **/ + MarkdownIt.prototype.set = function (options) { + assign(this.options, options); + return this; + }; -function fence(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; + /** chainable, internal + * MarkdownIt.configure(presets) + * + * Batch load of all options and compenent settings. This is internal method, + * and you probably will not need it. But if you will - see available presets + * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) + * + * We strongly recommend to use presets instead of direct config loads. That + * will give better compatibility with next versions. + **/ + MarkdownIt.prototype.configure = function (presets) { + const self = this; + if (isString(presets)) { + const presetName = presets; + presets = config[presetName]; + if (!presets) { + throw new Error( + 'Wrong `markdown-it` preset "' + presetName + '", check name' + ); + } + } + if (!presets) { + throw new Error("Wrong `markdown-it` preset, can't be empty"); + } + if (presets.options) { + self.set(presets.options); + } + if (presets.components) { + Object.keys(presets.components).forEach(function (name) { + if (presets.components[name].rules) { + self[name].ruler.enableOnly(presets.components[name].rules); + } + if (presets.components[name].rules2) { + self[name].ruler2.enableOnly(presets.components[name].rules2); + } + }); + } + return this; + }; - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (pos + 3 > max) { - return false; - } - const marker = state.src.charCodeAt(pos); - if (marker !== 0x7E /* ~ */ && marker !== 0x60 /* ` */) { - return false; - } + /** chainable + * MarkdownIt.enable(list, ignoreInvalid) + * - list (String|Array): rule name or list of rule names to enable + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable list or rules. It will automatically find appropriate components, + * containing rules with given names. If rule not found, and `ignoreInvalid` + * not set - throws exception. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')() + * .enable(['sub', 'sup']) + * .disable('smartquotes'); + * ``` + **/ + MarkdownIt.prototype.enable = function (list, ignoreInvalid) { + let result = []; + if (!Array.isArray(list)) { + list = [list]; + } + ["core", "block", "inline"].forEach(function (chain) { + result = result.concat(this[chain].ruler.enable(list, true)); + }, this); + result = result.concat(this.inline.ruler2.enable(list, true)); + const missed = list.filter(function (name) { + return result.indexOf(name) < 0; + }); + if (missed.length && !ignoreInvalid) { + throw new Error( + "MarkdownIt. Failed to enable unknown rule(s): " + missed + ); + } + return this; + }; - // scan marker length - let mem = pos; - pos = state.skipChars(pos, marker); - let len = pos - mem; - if (len < 3) { - return false; - } - const markup = state.src.slice(mem, pos); - const params = state.src.slice(pos, max); - if (marker === 0x60 /* ` */) { - if (params.indexOf(String.fromCharCode(marker)) >= 0) { - return false; - } - } + /** chainable + * MarkdownIt.disable(list, ignoreInvalid) + * - list (String|Array): rule name or list of rule names to disable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * The same as [[MarkdownIt.enable]], but turn specified rules off. + **/ + MarkdownIt.prototype.disable = function (list, ignoreInvalid) { + let result = []; + if (!Array.isArray(list)) { + list = [list]; + } + ["core", "block", "inline"].forEach(function (chain) { + result = result.concat(this[chain].ruler.disable(list, true)); + }, this); + result = result.concat(this.inline.ruler2.disable(list, true)); + const missed = list.filter(function (name) { + return result.indexOf(name) < 0; + }); + if (missed.length && !ignoreInvalid) { + throw new Error( + "MarkdownIt. Failed to disable unknown rule(s): " + missed + ); + } + return this; + }; - // Since start is found, we can report success here in validation mode - if (silent) { - return true; - } + /** chainable + * MarkdownIt.use(plugin, params) + * + * Load specified plugin with given params into current parser instance. + * It's just a sugar to call `plugin(md, params)` with curring. + * + * ##### Example + * + * ```javascript + * var iterator = require('markdown-it-for-inline'); + * var md = require('markdown-it')() + * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { + * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); + * }); + * ``` + **/ + MarkdownIt.prototype.use = function (plugin /*, params, ... */) { + const args = [this].concat(Array.prototype.slice.call(arguments, 1)); + plugin.apply(plugin, args); + return this; + }; - // search end of block - let nextLine = startLine; - let haveEndMarker = false; - for (;;) { - nextLine++; - if (nextLine >= endLine) { - // unclosed block should be autoclosed by end of document. - // also block seems to be autoclosed by end of parent - break; - } - pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - if (pos < max && state.sCount[nextLine] < state.blkIndent) { - // non-empty line with negative indent should stop the list: - // - ``` - // test - break; - } - if (state.src.charCodeAt(pos) !== marker) { - continue; - } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - // closing fence should be indented less than 4 spaces - continue; - } - pos = state.skipChars(pos, marker); + /** internal + * MarkdownIt.parse(src, env) -> Array + * - src (String): source string + * - env (Object): environment sandbox + * + * Parse input string and return list of block tokens (special token type + * "inline" will contain list of inline tokens). You should not call this + * method directly, until you write custom renderer (for example, to produce + * AST). + * + * `env` is used to pass data between "distributed" rules and return additional + * metadata like reference info, needed for the renderer. It also can be used to + * inject data in specific cases. Usually, you will be ok to pass `{}`, + * and then pass updated object to renderer. + **/ + MarkdownIt.prototype.parse = function (src, env) { + if (typeof src !== "string") { + throw new Error("Input data should be a String"); + } + const state = new this.core.State(src, this, env); + this.core.process(state); + return state.tokens; + }; - // closing code fence must be at least as long as the opening one - if (pos - mem < len) { - continue; - } + /** + * MarkdownIt.render(src [, env]) -> String + * - src (String): source string + * - env (Object): environment sandbox + * + * Render markdown string into html. It does all magic for you :). + * + * `env` can be used to inject additional metadata (`{}` by default). + * But you will not need it with high probability. See also comment + * in [[MarkdownIt.parse]]. + **/ + MarkdownIt.prototype.render = function (src, env) { + env = env || {}; + return this.renderer.render(this.parse(src, env), this.options, env); + }; - // make sure tail has spaces only - pos = state.skipSpaces(pos); - if (pos < max) { - continue; - } - haveEndMarker = true; - // found! - break; - } + /** internal + * MarkdownIt.parseInline(src, env) -> Array + * - src (String): source string + * - env (Object): environment sandbox + * + * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the + * block tokens list with the single `inline` element, containing parsed inline + * tokens in `children` property. Also updates `env` object. + **/ + MarkdownIt.prototype.parseInline = function (src, env) { + const state = new this.core.State(src, this, env); + state.inlineMode = true; + this.core.process(state); + return state.tokens; + }; - // If a fence has heading spaces, they should be removed from its inner block - len = state.sCount[startLine]; - state.line = nextLine + (haveEndMarker ? 1 : 0); - const token = state.push('fence', 'code', 0); - token.info = params; - token.content = state.getLines(startLine + 1, nextLine, len, true); - token.markup = markup; - token.map = [startLine, state.line]; - return true; -} + /** + * MarkdownIt.renderInline(src [, env]) -> String + * - src (String): source string + * - env (Object): environment sandbox + * + * Similar to [[MarkdownIt.render]] but for single paragraph content. Result + * will NOT be wrapped into `

    ` tags. + **/ + MarkdownIt.prototype.renderInline = function (src, env) { + env = env || {}; + return this.renderer.render( + this.parseInline(src, env), + this.options, + env + ); + }; + module.exports = MarkdownIt; -// Block quotes + /***/ + }, -function blockquote(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - const oldLineMax = state.lineMax; + /***/ "../node_modules/mdurl/build/index.cjs.js": + /*!************************************************!*\ + !*** ../node_modules/mdurl/build/index.cjs.js ***! + \************************************************/ + /***/ function (__unused_webpack_module, exports) { + /* eslint-disable no-bitwise */ + const decodeCache = {}; + function getDecodeCache(exclude) { + let cache = decodeCache[exclude]; + if (cache) { + return cache; + } + cache = decodeCache[exclude] = []; + for (let i = 0; i < 128; i++) { + const ch = String.fromCharCode(i); + cache.push(ch); + } + for (let i = 0; i < exclude.length; i++) { + const ch = exclude.charCodeAt(i); + cache[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2); + } + return cache; + } - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } + // Decode percent-encoded string. + // + function decode(string, exclude) { + if (typeof exclude !== "string") { + exclude = decode.defaultChars; + } + const cache = getDecodeCache(exclude); + return string.replace(/(%[a-f0-9]{2})+/gi, function (seq) { + let result = ""; + for (let i = 0, l = seq.length; i < l; i += 3) { + const b1 = parseInt(seq.slice(i + 1, i + 3), 16); + if (b1 < 0x80) { + result += cache[b1]; + continue; + } + if ((b1 & 0xe0) === 0xc0 && i + 3 < l) { + // 110xxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + if ((b2 & 0xc0) === 0x80) { + const chr = ((b1 << 6) & 0x7c0) | (b2 & 0x3f); + if (chr < 0x80) { + result += "\ufffd\ufffd"; + } else { + result += String.fromCharCode(chr); + } + i += 3; + continue; + } + } + if ((b1 & 0xf0) === 0xe0 && i + 6 < l) { + // 1110xxxx 10xxxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + const b3 = parseInt(seq.slice(i + 7, i + 9), 16); + if ((b2 & 0xc0) === 0x80 && (b3 & 0xc0) === 0x80) { + const chr = + ((b1 << 12) & 0xf000) | ((b2 << 6) & 0xfc0) | (b3 & 0x3f); + if (chr < 0x800 || (chr >= 0xd800 && chr <= 0xdfff)) { + result += "\ufffd\ufffd\ufffd"; + } else { + result += String.fromCharCode(chr); + } + i += 6; + continue; + } + } + if ((b1 & 0xf8) === 0xf0 && i + 9 < l) { + // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + const b3 = parseInt(seq.slice(i + 7, i + 9), 16); + const b4 = parseInt(seq.slice(i + 10, i + 12), 16); + if ( + (b2 & 0xc0) === 0x80 && + (b3 & 0xc0) === 0x80 && + (b4 & 0xc0) === 0x80 + ) { + let chr = + ((b1 << 18) & 0x1c0000) | + ((b2 << 12) & 0x3f000) | + ((b3 << 6) & 0xfc0) | + (b4 & 0x3f); + if (chr < 0x10000 || chr > 0x10ffff) { + result += "\ufffd\ufffd\ufffd\ufffd"; + } else { + chr -= 0x10000; + result += String.fromCharCode( + 0xd800 + (chr >> 10), + 0xdc00 + (chr & 0x3ff) + ); + } + i += 9; + continue; + } + } + result += "\ufffd"; + } + return result; + }); + } + decode.defaultChars = ";/?:@&=+$,#"; + decode.componentChars = ""; + const encodeCache = {}; - // check the block quote marker - if (state.src.charCodeAt(pos) !== 0x3E /* > */) { - return false; - } + // Create a lookup array where anything but characters in `chars` string + // and alphanumeric chars is percent-encoded. + // + function getEncodeCache(exclude) { + let cache = encodeCache[exclude]; + if (cache) { + return cache; + } + cache = encodeCache[exclude] = []; + for (let i = 0; i < 128; i++) { + const ch = String.fromCharCode(i); + if (/^[0-9a-z]$/i.test(ch)) { + // always allow unencoded alphanumeric characters + cache.push(ch); + } else { + cache.push("%" + ("0" + i.toString(16).toUpperCase()).slice(-2)); + } + } + for (let i = 0; i < exclude.length; i++) { + cache[exclude.charCodeAt(i)] = exclude[i]; + } + return cache; + } - // we know that it's going to be a valid blockquote, - // so no point trying to find the end of it in silent mode - if (silent) { - return true; - } - const oldBMarks = []; - const oldBSCount = []; - const oldSCount = []; - const oldTShift = []; - const terminatorRules = state.md.block.ruler.getRules('blockquote'); - const oldParentType = state.parentType; - state.parentType = 'blockquote'; - let lastLineEmpty = false; - let nextLine; - - // Search the end of the block - // - // Block ends with either: - // 1. an empty line outside: - // ``` - // > test - // - // ``` - // 2. an empty line inside: - // ``` - // > - // test - // ``` - // 3. another tag: - // ``` - // > test - // - - - - // ``` - for (nextLine = startLine; nextLine < endLine; nextLine++) { - // check if it's outdented, i.e. it's inside list item and indented - // less than said list item: - // - // ``` - // 1. anything - // > current blockquote - // 2. checking this line - // ``` - const isOutdented = state.sCount[nextLine] < state.blkIndent; - pos = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - if (pos >= max) { - // Case 1: line is not inside the blockquote, and this line is empty. - break; - } - if (state.src.charCodeAt(pos++) === 0x3E /* > */ && !isOutdented) { - // This line is inside the blockquote. - - // set offset past spaces and ">" - let initial = state.sCount[nextLine] + 1; - let spaceAfterMarker; - let adjustTab; - - // skip one optional space after '>' - if (state.src.charCodeAt(pos) === 0x20 /* space */) { - // ' > test ' - // ^ -- position start of line here: - pos++; - initial++; - adjustTab = false; - spaceAfterMarker = true; - } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { - spaceAfterMarker = true; - if ((state.bsCount[nextLine] + initial) % 4 === 3) { - // ' >\t test ' - // ^ -- position start of line here (tab has width===1) - pos++; - initial++; - adjustTab = false; - } else { - // ' >\t test ' - // ^ -- position start of line here + shift bsCount slightly - // to make extra space appear - adjustTab = true; + // Encode unsafe characters with percent-encoding, skipping already + // encoded sequences. + // + // - string - string to encode + // - exclude - list of characters to ignore (in addition to a-zA-Z0-9) + // - keepEscaped - don't encode '%' in a correct escape sequence (default: true) + // + function encode(string, exclude, keepEscaped) { + if (typeof exclude !== "string") { + // encode(string, keepEscaped) + keepEscaped = exclude; + exclude = encode.defaultChars; + } + if (typeof keepEscaped === "undefined") { + keepEscaped = true; + } + const cache = getEncodeCache(exclude); + let result = ""; + for (let i = 0, l = string.length; i < l; i++) { + const code = string.charCodeAt(i); + if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { + if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { + result += string.slice(i, i + 3); + i += 2; + continue; + } + } + if (code < 128) { + result += cache[code]; + continue; + } + if (code >= 0xd800 && code <= 0xdfff) { + if (code >= 0xd800 && code <= 0xdbff && i + 1 < l) { + const nextCode = string.charCodeAt(i + 1); + if (nextCode >= 0xdc00 && nextCode <= 0xdfff) { + result += encodeURIComponent(string[i] + string[i + 1]); + i++; + continue; + } + } + result += "%EF%BF%BD"; + continue; + } + result += encodeURIComponent(string[i]); + } + return result; } - } else { - spaceAfterMarker = false; - } - let offset = initial; - oldBMarks.push(state.bMarks[nextLine]); - state.bMarks[nextLine] = pos; - while (pos < max) { - const ch = state.src.charCodeAt(pos); - if (isSpace(ch)) { - if (ch === 0x09) { - offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4; + encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; + encode.componentChars = "-_.!~*'()"; + function format(url) { + let result = ""; + result += url.protocol || ""; + result += url.slashes ? "//" : ""; + result += url.auth ? url.auth + "@" : ""; + if (url.hostname && url.hostname.indexOf(":") !== -1) { + // ipv6 address + result += "[" + url.hostname + "]"; } else { - offset++; + result += url.hostname || ""; } - } else { - break; + result += url.port ? ":" + url.port : ""; + result += url.pathname || ""; + result += url.search || ""; + result += url.hash || ""; + return result; } - pos++; - } - lastLineEmpty = pos >= max; - oldBSCount.push(state.bsCount[nextLine]); - state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); - oldSCount.push(state.sCount[nextLine]); - state.sCount[nextLine] = offset - initial; - oldTShift.push(state.tShift[nextLine]); - state.tShift[nextLine] = pos - state.bMarks[nextLine]; - continue; - } - - // Case 2: line is not inside the blockquote, and the last line was empty. - if (lastLineEmpty) { - break; - } - // Case 3: another tag found. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } - } - if (terminate) { - // Quirk to enforce "hard termination mode" for paragraphs; - // normally if you call `tokenize(state, startLine, nextLine)`, - // paragraphs will look below nextLine for paragraph continuation, - // but if blockquote is terminated by another tag, they shouldn't - state.lineMax = nextLine; - if (state.blkIndent !== 0) { - // state.blkIndent was non-zero, we now set it to zero, - // so we need to re-calculate all offsets to appear as - // if indent wasn't changed - oldBMarks.push(state.bMarks[nextLine]); - oldBSCount.push(state.bsCount[nextLine]); - oldTShift.push(state.tShift[nextLine]); - oldSCount.push(state.sCount[nextLine]); - state.sCount[nextLine] -= state.blkIndent; - } - break; - } - oldBMarks.push(state.bMarks[nextLine]); - oldBSCount.push(state.bsCount[nextLine]); - oldTShift.push(state.tShift[nextLine]); - oldSCount.push(state.sCount[nextLine]); - - // A negative indentation means that this is a paragraph continuation - // - state.sCount[nextLine] = -1; - } - const oldIndent = state.blkIndent; - state.blkIndent = 0; - const token_o = state.push('blockquote_open', 'blockquote', 1); - token_o.markup = '>'; - const lines = [startLine, 0]; - token_o.map = lines; - state.md.block.tokenize(state, startLine, nextLine); - const token_c = state.push('blockquote_close', 'blockquote', -1); - token_c.markup = '>'; - state.lineMax = oldLineMax; - state.parentType = oldParentType; - lines[1] = state.line; - - // Restore original tShift; this might not be necessary since the parser - // has already been here, but just to make sure we can do that. - for (let i = 0; i < oldTShift.length; i++) { - state.bMarks[i + startLine] = oldBMarks[i]; - state.tShift[i + startLine] = oldTShift[i]; - state.sCount[i + startLine] = oldSCount[i]; - state.bsCount[i + startLine] = oldBSCount[i]; - } - state.blkIndent = oldIndent; - return true; -} + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. -// Horizontal rule + // + // Changes from joyent/node: + // + // 1. No leading slash in paths, + // e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` + // + // 2. Backslashes are not replaced with slashes, + // so `http:\\example.org\` is treated like a relative path + // + // 3. Trailing colon is treated like a part of the path, + // i.e. in `http://example.org:foo` pathname is `:foo` + // + // 4. Nothing is URL-encoded in the resulting object, + // (in joyent/node some chars in auth and paths are encoded) + // + // 5. `url.parse()` does not have `parseQueryString` argument + // + // 6. Removed extraneous result properties: `host`, `path`, `query`, etc., + // which can be constructed using other parts of the url. + // -function hr(state, startLine, endLine, silent) { - const max = state.eMarks[startLine]; - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - let pos = state.bMarks[startLine] + state.tShift[startLine]; - const marker = state.src.charCodeAt(pos++); + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + const protocolPattern = /^([a-z0-9.+-]+:)/i; + const portPattern = /:[0-9]*$/; + + // Special case for a simple path URL + /* eslint-disable-next-line no-useless-escape */ + const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + const delims = ["<", ">", '"', "`", " ", "\r", "\n", "\t"]; + + // RFC 2396: characters not allowed for various reasons. + const unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims); + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + const autoEscape = ["'"].concat(unwise); + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + const nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape); + const hostEndingChars = ["/", "?", "#"]; + const hostnameMaxLen = 255; + const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; + const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; + // protocols that can allow "unsafe" and "unwise" chars. + // protocols that never have a hostname. + const hostlessProtocol = { + javascript: true, + "javascript:": true, + }; + // protocols that always contain a // bit. + const slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + "http:": true, + "https:": true, + "ftp:": true, + "gopher:": true, + "file:": true, + }; + function urlParse(url, slashesDenoteHost) { + if (url && url instanceof Url) return url; + const u = new Url(); + u.parse(url, slashesDenoteHost); + return u; + } + Url.prototype.parse = function (url, slashesDenoteHost) { + let lowerProto, hec, slashes; + let rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + if (!slashesDenoteHost && url.split("#").length === 1) { + // Try fast path regexp + const simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + } + return this; + } + } + let proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + lowerProto = proto.toLowerCase(); + this.protocol = proto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + /* eslint-disable-next-line no-useless-escape */ + if ( + slashesDenoteHost || + proto || + rest.match(/^\/\/[^@\/]+@[^@\/]+/) + ) { + slashes = rest.substr(0, 2) === "//"; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + if ( + !hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto])) + ) { + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + let hostEnd = -1; + for (let i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; + } + } - // Check hr marker - if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x5F /* _ */) { - return false; - } + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + let auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf("@"); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf("@", hostEnd); + } - // markers can be mixed with spaces, but there should be at least 3 of them + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = auth; + } - let cnt = 1; - while (pos < max) { - const ch = state.src.charCodeAt(pos++); - if (ch !== marker && !isSpace(ch)) { - return false; - } - if (ch === marker) { - cnt++; - } - } - if (cnt < 3) { - return false; - } - if (silent) { - return true; - } - state.line = startLine + 1; - const token = state.push('hr', 'hr', 0); - token.map = [startLine, state.line]; - token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); - return true; -} - -// Lists - -// Search `[-+*][\n ]`, returns next pos after marker on success -// or -1 on fail. -function skipBulletListMarker(state, startLine) { - const max = state.eMarks[startLine]; - let pos = state.bMarks[startLine] + state.tShift[startLine]; - const marker = state.src.charCodeAt(pos++); - // Check bullet - if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x2B /* + */) { - return -1; - } - if (pos < max) { - const ch = state.src.charCodeAt(pos); - if (!isSpace(ch)) { - // " -test " - is not a list item - return -1; - } - } - return pos; -} - -// Search `\d+[.)][\n ]`, returns next pos after marker on success -// or -1 on fail. -function skipOrderedListMarker(state, startLine) { - const start = state.bMarks[startLine] + state.tShift[startLine]; - const max = state.eMarks[startLine]; - let pos = start; - - // List marker should have at least 2 chars (digit + dot) - if (pos + 1 >= max) { - return -1; - } - let ch = state.src.charCodeAt(pos++); - if (ch < 0x30 /* 0 */ || ch > 0x39 /* 9 */) { - return -1; - } - for (;;) { - // EOL -> fail - if (pos >= max) { - return -1; - } - ch = state.src.charCodeAt(pos++); - if (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) { - // List marker should have no more than 9 digits - // (prevents integer overflow in browsers) - if (pos - start >= 10) { - return -1; - } - continue; - } + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (let i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; + } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { + hostEnd = rest.length; + } + if (rest[hostEnd - 1] === ":") { + hostEnd--; + } + const host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(host); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ""; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + const ipv6Hostname = + this.hostname[0] === "[" && + this.hostname[this.hostname.length - 1] === "]"; + + // validate a little. + if (!ipv6Hostname) { + const hostparts = this.hostname.split(/\./); + for (let i = 0, l = hostparts.length; i < l; i++) { + const part = hostparts[i]; + if (!part) { + continue; + } + if (!part.match(hostnamePartPattern)) { + let newpart = ""; + for (let j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += "x"; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + const validParts = hostparts.slice(0, i); + const notHost = hostparts.slice(i + 1); + const bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = notHost.join(".") + rest; + } + this.hostname = validParts.join("."); + break; + } + } + } + } + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ""; + } - // found valid marker - if (ch === 0x29 /* ) */ || ch === 0x2e /* . */) { - break; - } - return -1; - } - if (pos < max) { - ch = state.src.charCodeAt(pos); - if (!isSpace(ch)) { - // " 1.test " - is not a list item - return -1; - } - } - return pos; -} -function markTightParagraphs(state, idx) { - const level = state.level + 2; - for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) { - if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') { - state.tokens[i + 2].hidden = true; - state.tokens[i].hidden = true; - i += 2; - } - } -} -function list(state, startLine, endLine, silent) { - let max, pos, start, token; - let nextLine = startLine; - let tight = true; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - return false; - } + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + } + } - // Special case: - // - item 1 - // - item 2 - // - item 3 - // - item 4 - // - this one is a paragraph continuation - if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) { - return false; - } - let isTerminatingParagraph = false; - - // limit conditions when list can interrupt - // a paragraph (validation mode only) - if (silent && state.parentType === 'paragraph') { - // Next list item should still terminate previous list item; - // - // This code can fail if plugins use blkIndent as well as lists, - // but I hope the spec gets fixed long before that happens. - // - if (state.sCount[nextLine] >= state.blkIndent) { - isTerminatingParagraph = true; - } - } + // chop off from the tail first. + const hash = rest.indexOf("#"); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + const qm = rest.indexOf("?"); + if (qm !== -1) { + this.search = rest.substr(qm); + rest = rest.slice(0, qm); + } + if (rest) { + this.pathname = rest; + } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = ""; + } + return this; + }; + Url.prototype.parseHost = function (host) { + let port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ":") { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { + this.hostname = host; + } + }; + exports.decode = decode; + exports.encode = encode; + exports.format = format; + exports.parse = urlParse; - // Detect list type and position after marker - let isOrdered; - let markerValue; - let posAfterMarker; - if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) { - isOrdered = true; - start = state.bMarks[nextLine] + state.tShift[nextLine]; - markerValue = Number(state.src.slice(start, posAfterMarker - 1)); - - // If we're starting a new ordered list right after - // a paragraph, it should start with 1. - if (isTerminatingParagraph && markerValue !== 1) return false; - } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) { - isOrdered = false; - } else { - return false; - } + /***/ + }, - // If we're starting a new unordered list right after - // a paragraph, first line should not be empty. - if (isTerminatingParagraph) { - if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false; - } + /***/ "../node_modules/uc.micro/build/index.cjs.js": + /*!***************************************************!*\ + !*** ../node_modules/uc.micro/build/index.cjs.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports) { + var regex$5 = + /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var regex$4 = /[\0-\x1F\x7F-\x9F]/; + var regex$3 = + /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/; + var regex$2 = + /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/; + var regex$1 = + /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/; + var regex = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; + exports.Any = regex$5; + exports.Cc = regex$4; + exports.Cf = regex$3; + exports.P = regex$2; + exports.S = regex$1; + exports.Z = regex; + + /***/ + }, - // For validation mode we can terminate immediately - if (silent) { - return true; - } + /***/ "./components/GraphiQL.tsx": + /*!*********************************!*\ + !*** ./components/GraphiQL.tsx ***! + \*********************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.GraphiQL = GraphiQL; + exports.GraphiQLInterface = GraphiQLInterface; + var _react = _interopRequireWildcard( + __webpack_require__(/*! react */ "react") + ); + var _react2 = __webpack_require__( + /*! @graphiql/react */ "../../graphiql-react/dist/index.js" + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } + function _extends() { + _extends = Object.assign + ? Object.assign.bind() + : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); + } + /** + * Copyright (c) 2020 GraphQL Contributors. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + const majorVersion = parseInt(_react.default.version.slice(0, 2), 10); + if (majorVersion < 16) { + throw new Error( + [ + "GraphiQL 0.18.0 and after is not compatible with React 15 or below.", + "If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:", + "https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49", + ].join("\n") + ); + } - // We should terminate list on style change. Remember first one to compare. - const markerCharCode = state.src.charCodeAt(posAfterMarker - 1); + /** + * API docs for this live here: + * + * https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops + */ - // Start list - const listTokIdx = state.tokens.length; - if (isOrdered) { - token = state.push('ordered_list_open', 'ol', 1); - if (markerValue !== 1) { - token.attrs = [['start', markerValue]]; - } - } else { - token = state.push('bullet_list_open', 'ul', 1); - } - const listLines = [nextLine, 0]; - token.map = listLines; - token.markup = String.fromCharCode(markerCharCode); - - // - // Iterate list items - // - - let prevEmptyEnd = false; - const terminatorRules = state.md.block.ruler.getRules('list'); - const oldParentType = state.parentType; - state.parentType = 'list'; - while (nextLine < endLine) { - pos = posAfterMarker; - max = state.eMarks[nextLine]; - const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]); - let offset = initial; - while (pos < max) { - const ch = state.src.charCodeAt(pos); - if (ch === 0x09) { - offset += 4 - (offset + state.bsCount[nextLine]) % 4; - } else if (ch === 0x20) { - offset++; - } else { - break; - } - pos++; - } - const contentStart = pos; - let indentAfterMarker; - if (contentStart >= max) { - // trimming space in "- \n 3" case, indent is 1 here - indentAfterMarker = 1; - } else { - indentAfterMarker = offset - initial; - } + /** + * The top-level React component for GraphiQL, intended to encompass the entire + * browser viewport. + * + * @see https://github.com/graphql/graphiql#usage + */ - // If we have more than 4 spaces, the indent is 1 - // (the rest is just indented code block) - if (indentAfterMarker > 4) { - indentAfterMarker = 1; - } + function GraphiQL({ + dangerouslyAssumeSchemaIsValid, + defaultQuery, + defaultTabs, + externalFragments, + fetcher, + getDefaultFieldNames, + headers, + inputValueDeprecation, + introspectionQueryName, + maxHistoryLength, + onEditOperationName, + onSchemaChange, + onTabChange, + onTogglePluginVisibility, + operationName, + plugins, + query, + response, + schema, + schemaDescription, + shouldPersistHeaders, + storage, + validationRules, + variables, + visiblePlugin, + defaultHeaders, + ...props + }) { + var _props$disableTabs; + // Ensure props are correct + if (typeof fetcher !== "function") { + throw new TypeError( + "The `GraphiQL` component requires a `fetcher` function to be passed as prop." + ); + } + return /*#__PURE__*/ _react.default.createElement( + _react2.GraphiQLProvider, + { + getDefaultFieldNames: getDefaultFieldNames, + dangerouslyAssumeSchemaIsValid: dangerouslyAssumeSchemaIsValid, + defaultQuery: defaultQuery, + defaultHeaders: defaultHeaders, + defaultTabs: defaultTabs, + externalFragments: externalFragments, + fetcher: fetcher, + headers: headers, + inputValueDeprecation: inputValueDeprecation, + introspectionQueryName: introspectionQueryName, + maxHistoryLength: maxHistoryLength, + onEditOperationName: onEditOperationName, + onSchemaChange: onSchemaChange, + onTabChange: onTabChange, + onTogglePluginVisibility: onTogglePluginVisibility, + plugins: plugins, + visiblePlugin: visiblePlugin, + operationName: operationName, + query: query, + response: response, + schema: schema, + schemaDescription: schemaDescription, + shouldPersistHeaders: shouldPersistHeaders, + storage: storage, + validationRules: validationRules, + variables: variables, + }, + /*#__PURE__*/ _react.default.createElement( + GraphiQLInterface, + _extends( + { + showPersistHeadersSettings: shouldPersistHeaders !== false, + disableTabs: + (_props$disableTabs = props.disableTabs) !== null && + _props$disableTabs !== void 0 + ? _props$disableTabs + : false, + forcedTheme: props.forcedTheme, + }, + props + ) + ) + ); + } - // " - test" - // ^^^^^ - calculating total length of this thing - const indent = initial + indentAfterMarker; - - // Run subparser & write tokens - token = state.push('list_item_open', 'li', 1); - token.markup = String.fromCharCode(markerCharCode); - const itemLines = [nextLine, 0]; - token.map = itemLines; - if (isOrdered) { - token.info = state.src.slice(start, posAfterMarker - 1); - } + // Export main windows/panes to be used separately if desired. + GraphiQL.Logo = GraphiQLLogo; + GraphiQL.Toolbar = GraphiQLToolbar; + GraphiQL.Footer = GraphiQLFooter; + const THEMES = ["light", "dark", "system"]; + function GraphiQLInterface(props) { + var _props$isHeadersEdito, + _pluginContext$visibl, + _props$toolbar, + _props$toolbar2; + const isHeadersEditorEnabled = + (_props$isHeadersEdito = props.isHeadersEditorEnabled) !== null && + _props$isHeadersEdito !== void 0 + ? _props$isHeadersEdito + : true; + const editorContext = (0, _react2.useEditorContext)({ + nonNull: true, + }); + const executionContext = (0, _react2.useExecutionContext)({ + nonNull: true, + }); + const schemaContext = (0, _react2.useSchemaContext)({ + nonNull: true, + }); + const storageContext = (0, _react2.useStorageContext)(); + const pluginContext = (0, _react2.usePluginContext)(); + const forcedTheme = (0, _react.useMemo)( + () => + props.forcedTheme && THEMES.includes(props.forcedTheme) + ? props.forcedTheme + : undefined, + [props.forcedTheme] + ); + const copy = (0, _react2.useCopyQuery)({ + onCopyQuery: props.onCopyQuery, + }); + const merge = (0, _react2.useMergeQuery)(); + const prettify = (0, _react2.usePrettifyEditors)(); + const { theme, setTheme } = (0, _react2.useTheme)(); + (0, _react.useEffect)(() => { + if (forcedTheme === "system") { + setTheme(null); + } else if (forcedTheme === "light" || forcedTheme === "dark") { + setTheme(forcedTheme); + } + }, [forcedTheme, setTheme]); + const PluginContent = + pluginContext === null || pluginContext === void 0 + ? void 0 + : (_pluginContext$visibl = pluginContext.visiblePlugin) === + null || _pluginContext$visibl === void 0 + ? void 0 + : _pluginContext$visibl.content; + const pluginResize = (0, _react2.useDragResize)({ + defaultSizeRelation: 1 / 3, + direction: "horizontal", + initiallyHidden: + pluginContext !== null && + pluginContext !== void 0 && + pluginContext.visiblePlugin + ? undefined + : "first", + onHiddenElementChange(resizableElement) { + if (resizableElement === "first") { + pluginContext === null || pluginContext === void 0 + ? void 0 + : pluginContext.setVisiblePlugin(null); + } + }, + sizeThresholdSecond: 200, + storageKey: "docExplorerFlex", + }); + const editorResize = (0, _react2.useDragResize)({ + direction: "horizontal", + storageKey: "editorFlex", + }); + const editorToolsResize = (0, _react2.useDragResize)({ + defaultSizeRelation: 3, + direction: "vertical", + initiallyHidden: (() => { + if ( + props.defaultEditorToolsVisibility === "variables" || + props.defaultEditorToolsVisibility === "headers" + ) { + return; + } + if (typeof props.defaultEditorToolsVisibility === "boolean") { + return props.defaultEditorToolsVisibility + ? undefined + : "second"; + } + return editorContext.initialVariables || + editorContext.initialHeaders + ? undefined + : "second"; + })(), + sizeThresholdSecond: 60, + storageKey: "secondaryEditorFlex", + }); + const [activeSecondaryEditor, setActiveSecondaryEditor] = (0, + _react.useState)(() => { + if ( + props.defaultEditorToolsVisibility === "variables" || + props.defaultEditorToolsVisibility === "headers" + ) { + return props.defaultEditorToolsVisibility; + } + return !editorContext.initialVariables && + editorContext.initialHeaders && + isHeadersEditorEnabled + ? "headers" + : "variables"; + }); + const [showDialog, setShowDialog] = (0, _react.useState)(null); + const [clearStorageStatus, setClearStorageStatus] = (0, + _react.useState)(null); + const children = _react.default.Children.toArray(props.children); + const logo = + children.find((child) => + isChildComponentType(child, GraphiQL.Logo) + ) || + /*#__PURE__*/ _react.default.createElement(GraphiQL.Logo, null); + const toolbar = + children.find((child) => + isChildComponentType(child, GraphiQL.Toolbar) + ) || + /*#__PURE__*/ _react.default.createElement( + _react.default.Fragment, + null, + /*#__PURE__*/ _react.default.createElement( + _react2.ToolbarButton, + { + onClick: prettify, + label: "Prettify query (Shift-Ctrl-P)", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.PrettifyIcon, + { + className: "graphiql-toolbar-icon", + "aria-hidden": "true", + } + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.ToolbarButton, + { + onClick: merge, + label: "Merge fragments into query (Shift-Ctrl-M)", + }, + /*#__PURE__*/ _react.default.createElement(_react2.MergeIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true", + }) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.ToolbarButton, + { + onClick: copy, + label: "Copy query (Shift-Ctrl-C)", + }, + /*#__PURE__*/ _react.default.createElement(_react2.CopyIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true", + }) + ), + (_props$toolbar = props.toolbar) === null || + _props$toolbar === void 0 + ? void 0 + : _props$toolbar.additionalContent, + ((_props$toolbar2 = props.toolbar) === null || + _props$toolbar2 === void 0 + ? void 0 + : _props$toolbar2.additionalComponent) && + /*#__PURE__*/ _react.default.createElement( + props.toolbar.additionalComponent, + null + ) + ); + const footer = children.find((child) => + isChildComponentType(child, GraphiQL.Footer) + ); + const onClickReference = (0, _react.useCallback)(() => { + if (pluginResize.hiddenElement === "first") { + pluginResize.setHiddenElement(null); + } + }, [pluginResize]); + const handleClearData = (0, _react.useCallback)(() => { + try { + storageContext === null || storageContext === void 0 + ? void 0 + : storageContext.clear(); + setClearStorageStatus("success"); + } catch { + setClearStorageStatus("error"); + } + }, [storageContext]); + const handlePersistHeaders = (0, _react.useCallback)( + (event) => { + editorContext.setShouldPersistHeaders( + event.currentTarget.dataset.value === "true" + ); + }, + [editorContext] + ); + const handleChangeTheme = (0, _react.useCallback)( + (event) => { + const selectedTheme = event.currentTarget.dataset.theme; + setTheme(selectedTheme || null); + }, + [setTheme] + ); + const handleAddTab = editorContext.addTab; + const handleRefetchSchema = schemaContext.introspect; + const handleReorder = editorContext.moveTab; + const handleShowDialog = (0, _react.useCallback)((event) => { + setShowDialog(event.currentTarget.dataset.value); + }, []); + const handlePluginClick = (0, _react.useCallback)( + (e) => { + const context = pluginContext; + const pluginIndex = Number(e.currentTarget.dataset.index); + const plugin = context.plugins.find( + (_, index) => pluginIndex === index + ); + const isVisible = plugin === context.visiblePlugin; + if (isVisible) { + context.setVisiblePlugin(null); + pluginResize.setHiddenElement("first"); + } else { + context.setVisiblePlugin(plugin); + pluginResize.setHiddenElement(null); + } + }, + [pluginContext, pluginResize] + ); + const handleToolsTabClick = (0, _react.useCallback)( + (event) => { + if (editorToolsResize.hiddenElement === "second") { + editorToolsResize.setHiddenElement(null); + } + setActiveSecondaryEditor(event.currentTarget.dataset.name); + }, + [editorToolsResize] + ); + const toggleEditorTools = (0, _react.useCallback)(() => { + editorToolsResize.setHiddenElement( + editorToolsResize.hiddenElement === "second" ? null : "second" + ); + }, [editorToolsResize]); + const handleOpenShortKeysDialog = (0, _react.useCallback)( + (isOpen) => { + if (!isOpen) { + setShowDialog(null); + } + }, + [] + ); + const handleOpenSettingsDialog = (0, _react.useCallback)((isOpen) => { + if (!isOpen) { + setShowDialog(null); + setClearStorageStatus(null); + } + }, []); + const addTab = /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip, + { + label: "Add tab", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + className: "graphiql-tab-add", + onClick: handleAddTab, + "aria-label": "Add tab", + }, + /*#__PURE__*/ _react.default.createElement(_react2.PlusIcon, { + "aria-hidden": "true", + }) + ) + ); + const className = props.className ? ` ${props.className}` : ""; + return /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip.Provider, + null, + /*#__PURE__*/ _react.default.createElement( + "div", + { + "data-testid": "graphiql-container", + className: `graphiql-container${className}`, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-sidebar", + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-sidebar-section", + }, + pluginContext === null || pluginContext === void 0 + ? void 0 + : pluginContext.plugins.map((plugin, index) => { + const isVisible = + plugin === pluginContext.visiblePlugin; + const label = `${isVisible ? "Hide" : "Show"} ${ + plugin.title + }`; + const Icon = plugin.icon; + return /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip, + { + key: plugin.title, + label: label, + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + className: isVisible ? "active" : "", + onClick: handlePluginClick, + "data-index": index, + "aria-label": label, + }, + /*#__PURE__*/ _react.default.createElement(Icon, { + "aria-hidden": "true", + }) + ) + ); + }) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-sidebar-section", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip, + { + label: "Re-fetch GraphQL schema", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + disabled: schemaContext.isFetching, + onClick: handleRefetchSchema, + "aria-label": "Re-fetch GraphQL schema", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.ReloadIcon, + { + className: schemaContext.isFetching + ? "graphiql-spin" + : "", + "aria-hidden": "true", + } + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip, + { + label: "Open short keys dialog", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + "data-value": "short-keys", + onClick: handleShowDialog, + "aria-label": "Open short keys dialog", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.KeyboardShortcutIcon, + { + "aria-hidden": "true", + } + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip, + { + label: "Open settings dialog", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + "data-value": "settings", + onClick: handleShowDialog, + "aria-label": "Open settings dialog", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.SettingsIcon, + { + "aria-hidden": "true", + } + ) + ) + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-main", + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: pluginResize.firstRef, + style: { + // Make sure the container shrinks when containing long + // non-breaking texts + minWidth: "200px", + }, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-plugin", + }, + PluginContent + ? /*#__PURE__*/ _react.default.createElement( + PluginContent, + null + ) + : null + ) + ), + (pluginContext === null || pluginContext === void 0 + ? void 0 + : pluginContext.visiblePlugin) && + /*#__PURE__*/ _react.default.createElement("div", { + className: "graphiql-horizontal-drag-bar", + ref: pluginResize.dragBarRef, + }), + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: pluginResize.secondRef, + className: "graphiql-sessions", + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-session-header", + }, + !props.disableTabs && + /*#__PURE__*/ _react.default.createElement( + _react2.Tabs, + { + values: editorContext.tabs, + onReorder: handleReorder, + "aria-label": "Select active operation", + }, + editorContext.tabs.length > 1 && + /*#__PURE__*/ _react.default.createElement( + _react.default.Fragment, + null, + editorContext.tabs.map((tab, index) => + /*#__PURE__*/ _react.default.createElement( + _react2.Tab, + { + key: tab.id, + value: tab, + isActive: + index === editorContext.activeTabIndex, + }, + /*#__PURE__*/ _react.default.createElement( + _react2.Tab.Button, + { + "aria-controls": "graphiql-session", + id: `graphiql-session-tab-${index}`, + onClick: () => { + executionContext.stop(); + editorContext.changeTab(index); + }, + }, + tab.title + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Tab.Close, + { + onClick: () => { + if ( + editorContext.activeTabIndex === index + ) { + executionContext.stop(); + } + editorContext.closeTab(index); + }, + } + ) + ) + ), + addTab + ) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-session-header-right", + }, + editorContext.tabs.length === 1 && addTab, + logo + ) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + role: "tabpanel", + id: "graphiql-session", + className: "graphiql-session", + "aria-labelledby": `graphiql-session-tab-${editorContext.activeTabIndex}`, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: editorResize.firstRef, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: `graphiql-editors${ + editorContext.tabs.length === 1 + ? " full-height" + : "" + }`, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: editorToolsResize.firstRef, + }, + /*#__PURE__*/ _react.default.createElement( + "section", + { + className: "graphiql-query-editor", + "aria-label": "Query Editor", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.QueryEditor, + { + editorTheme: props.editorTheme, + keyMap: props.keyMap, + onClickReference: onClickReference, + onCopyQuery: props.onCopyQuery, + onEdit: props.onEditQuery, + readOnly: props.readOnly, + } + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-toolbar", + role: "toolbar", + "aria-label": "Editor Commands", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.ExecuteButton, + null + ), + toolbar + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: editorToolsResize.dragBarRef, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-editor-tools", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + className: + activeSecondaryEditor === "variables" && + editorToolsResize.hiddenElement !== "second" + ? "active" + : "", + onClick: handleToolsTabClick, + "data-name": "variables", + }, + "Variables" + ), + isHeadersEditorEnabled && + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + className: + activeSecondaryEditor === "headers" && + editorToolsResize.hiddenElement !== "second" + ? "active" + : "", + onClick: handleToolsTabClick, + "data-name": "headers", + }, + "Headers" + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Tooltip, + { + label: + editorToolsResize.hiddenElement === "second" + ? "Show editor tools" + : "Hide editor tools", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.UnStyledButton, + { + type: "button", + onClick: toggleEditorTools, + "aria-label": + editorToolsResize.hiddenElement === "second" + ? "Show editor tools" + : "Hide editor tools", + className: "graphiql-toggle-editor-tools", + }, + editorToolsResize.hiddenElement === "second" + ? /*#__PURE__*/ _react.default.createElement( + _react2.ChevronUpIcon, + { + className: "graphiql-chevron-icon", + "aria-hidden": "true", + } + ) + : /*#__PURE__*/ _react.default.createElement( + _react2.ChevronDownIcon, + { + className: "graphiql-chevron-icon", + "aria-hidden": "true", + } + ) + ) + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: editorToolsResize.secondRef, + }, + /*#__PURE__*/ _react.default.createElement( + "section", + { + className: "graphiql-editor-tool", + "aria-label": + activeSecondaryEditor === "variables" + ? "Variables" + : "Headers", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.VariableEditor, + { + editorTheme: props.editorTheme, + isHidden: activeSecondaryEditor !== "variables", + keyMap: props.keyMap, + onEdit: props.onEditVariables, + onClickReference: onClickReference, + readOnly: props.readOnly, + } + ), + isHeadersEditorEnabled && + /*#__PURE__*/ _react.default.createElement( + _react2.HeaderEditor, + { + editorTheme: props.editorTheme, + isHidden: activeSecondaryEditor !== "headers", + keyMap: props.keyMap, + onEdit: props.onEditHeaders, + readOnly: props.readOnly, + } + ) + ) + ) + ) + ), + /*#__PURE__*/ _react.default.createElement("div", { + className: "graphiql-horizontal-drag-bar", + ref: editorResize.dragBarRef, + }), + /*#__PURE__*/ _react.default.createElement( + "div", + { + ref: editorResize.secondRef, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-response", + }, + executionContext.isFetching + ? /*#__PURE__*/ _react.default.createElement( + _react2.Spinner, + null + ) + : null, + /*#__PURE__*/ _react.default.createElement( + _react2.ResponseEditor, + { + editorTheme: props.editorTheme, + responseTooltip: props.responseTooltip, + keyMap: props.keyMap, + } + ), + footer + ) + ) + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Dialog, + { + open: showDialog === "short-keys", + onOpenChange: handleOpenShortKeysDialog, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-header", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.Dialog.Title, + { + className: "graphiql-dialog-title", + }, + "Short Keys" + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Dialog.Close, + null + ) + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section", + }, + /*#__PURE__*/ _react.default.createElement(ShortKeys, { + keyMap: props.keyMap || "sublime", + }) + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Dialog, + { + open: showDialog === "settings", + onOpenChange: handleOpenSettingsDialog, + }, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-header", + }, + /*#__PURE__*/ _react.default.createElement( + _react2.Dialog.Title, + { + className: "graphiql-dialog-title", + }, + "Settings" + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Dialog.Close, + null + ) + ), + props.showPersistHeadersSettings + ? /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section", + }, + /*#__PURE__*/ _react.default.createElement( + "div", + null, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section-title", + }, + "Persist headers" + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section-caption", + }, + "Save headers upon reloading.", + " ", + /*#__PURE__*/ _react.default.createElement( + "span", + { + className: "graphiql-warning-text", + }, + "Only enable if you trust this device." + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.ButtonGroup, + null, + /*#__PURE__*/ _react.default.createElement( + _react2.Button, + { + type: "button", + id: "enable-persist-headers", + className: editorContext.shouldPersistHeaders + ? "active" + : "", + "data-value": "true", + onClick: handlePersistHeaders, + }, + "On" + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Button, + { + type: "button", + id: "disable-persist-headers", + className: editorContext.shouldPersistHeaders + ? "" + : "active", + onClick: handlePersistHeaders, + }, + "Off" + ) + ) + ) + : null, + !forcedTheme && + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section", + }, + /*#__PURE__*/ _react.default.createElement( + "div", + null, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section-title", + }, + "Theme" + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section-caption", + }, + "Adjust how the interface appears." + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.ButtonGroup, + null, + /*#__PURE__*/ _react.default.createElement( + _react2.Button, + { + type: "button", + className: theme === null ? "active" : "", + onClick: handleChangeTheme, + }, + "System" + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Button, + { + type: "button", + className: theme === "light" ? "active" : "", + "data-theme": "light", + onClick: handleChangeTheme, + }, + "Light" + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Button, + { + type: "button", + className: theme === "dark" ? "active" : "", + "data-theme": "dark", + onClick: handleChangeTheme, + }, + "Dark" + ) + ) + ), + storageContext + ? /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section", + }, + /*#__PURE__*/ _react.default.createElement( + "div", + null, + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section-title", + }, + "Clear storage" + ), + /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-dialog-section-caption", + }, + "Remove all locally stored data and start fresh." + ) + ), + /*#__PURE__*/ _react.default.createElement( + _react2.Button, + { + type: "button", + state: clearStorageStatus || undefined, + disabled: clearStorageStatus === "success", + onClick: handleClearData, + }, + { + success: "Cleared data", + error: "Failed", + }[clearStorageStatus] || "Clear data" + ) + ) + : null + ) + ) + ); + } + const modifier = + typeof window !== "undefined" && + window.navigator.platform.toLowerCase().indexOf("mac") === 0 + ? "Cmd" + : "Ctrl"; + const SHORT_KEYS = Object.entries({ + "Search in editor": [modifier, "F"], + "Search in documentation": [modifier, "K"], + "Execute query": [modifier, "Enter"], + "Prettify editors": ["Ctrl", "Shift", "P"], + "Merge fragments definitions into operation definition": [ + "Ctrl", + "Shift", + "M", + ], + "Copy query": ["Ctrl", "Shift", "C"], + "Re-fetch schema using introspection": ["Ctrl", "Shift", "R"], + }); + function ShortKeys({ keyMap }) { + return /*#__PURE__*/ _react.default.createElement( + "div", + null, + /*#__PURE__*/ _react.default.createElement( + "table", + { + className: "graphiql-table", + }, + /*#__PURE__*/ _react.default.createElement( + "thead", + null, + /*#__PURE__*/ _react.default.createElement( + "tr", + null, + /*#__PURE__*/ _react.default.createElement( + "th", + null, + "Short Key" + ), + /*#__PURE__*/ _react.default.createElement( + "th", + null, + "Function" + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + "tbody", + null, + SHORT_KEYS.map(([title, keys]) => + /*#__PURE__*/ _react.default.createElement( + "tr", + { + key: title, + }, + /*#__PURE__*/ _react.default.createElement( + "td", + null, + keys.map((key, index, array) => + /*#__PURE__*/ _react.default.createElement( + _react.Fragment, + { + key: key, + }, + /*#__PURE__*/ _react.default.createElement( + "code", + { + className: "graphiql-key", + }, + key + ), + index !== array.length - 1 && " + " + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + "td", + null, + title + ) + ) + ) + ) + ), + /*#__PURE__*/ _react.default.createElement( + "p", + null, + "The editors use", + " ", + /*#__PURE__*/ _react.default.createElement( + "a", + { + href: "https://codemirror.net/5/doc/manual.html#keymaps", + target: "_blank", + rel: "noopener noreferrer", + }, + "CodeMirror Key Maps" + ), + " ", + "that add more short keys. This instance of Graph", + /*#__PURE__*/ _react.default.createElement("em", null, "i"), + "QL uses", + " ", + /*#__PURE__*/ _react.default.createElement("code", null, keyMap), + "." + ) + ); + } - // change current state, then restore it after parser subcall - const oldTight = state.tight; - const oldTShift = state.tShift[nextLine]; - const oldSCount = state.sCount[nextLine]; - - // - example list - // ^ listIndent position will be here - // ^ blkIndent position will be here - // - const oldListIndent = state.listIndent; - state.listIndent = state.blkIndent; - state.blkIndent = indent; - state.tight = true; - state.tShift[nextLine] = contentStart - state.bMarks[nextLine]; - state.sCount[nextLine] = offset; - if (contentStart >= max && state.isEmpty(nextLine + 1)) { - // workaround for this case - // (list item is empty, list terminates before "foo"): - // ~~~~~~~~ - // - - // - // foo - // ~~~~~~~~ - state.line = Math.min(state.line + 2, endLine); - } else { - state.md.block.tokenize(state, nextLine, endLine, true); - } + // Configure the UI by providing this Component as a child of GraphiQL. + function GraphiQLLogo(props) { + return /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-logo", + }, + props.children || + /*#__PURE__*/ _react.default.createElement( + "a", + { + className: "graphiql-logo-link", + href: "https://github.com/graphql/graphiql", + target: "_blank", + rel: "noreferrer", + }, + "Graph", + /*#__PURE__*/ _react.default.createElement("em", null, "i"), + "QL" + ) + ); + } + GraphiQLLogo.displayName = "GraphiQLLogo"; - // If any of list item is tight, mark list as tight - if (!state.tight || prevEmptyEnd) { - tight = false; - } - // Item become loose if finish with empty line, - // but we should filter last element, because it means list finish - prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1); - state.blkIndent = state.listIndent; - state.listIndent = oldListIndent; - state.tShift[nextLine] = oldTShift; - state.sCount[nextLine] = oldSCount; - state.tight = oldTight; - token = state.push('list_item_close', 'li', -1); - token.markup = String.fromCharCode(markerCharCode); - nextLine = state.line; - itemLines[1] = nextLine; - if (nextLine >= endLine) { - break; - } + // Configure the UI by providing this Component as a child of GraphiQL. + function GraphiQLToolbar(props) { + // eslint-disable-next-line react/jsx-no-useless-fragment + return /*#__PURE__*/ _react.default.createElement( + _react.default.Fragment, + null, + props.children + ); + } + GraphiQLToolbar.displayName = "GraphiQLToolbar"; - // - // Try to check if list is terminated or continued. - // - if (state.sCount[nextLine] < state.blkIndent) { - break; - } + // Configure the UI by providing this Component as a child of GraphiQL. + function GraphiQLFooter(props) { + return /*#__PURE__*/ _react.default.createElement( + "div", + { + className: "graphiql-footer", + }, + props.children + ); + } + GraphiQLFooter.displayName = "GraphiQLFooter"; + + // Determines if the React child is of the same type of the provided React component + function isChildComponentType(child, component) { + var _child$type; + if ( + child !== null && + child !== void 0 && + (_child$type = child.type) !== null && + _child$type !== void 0 && + _child$type.displayName && + child.type.displayName === component.displayName + ) { + return true; + } + return child.type === component; + } - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - break; - } + /***/ + }, - // fail if terminating block found - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } - } - if (terminate) { - break; - } + /***/ "../../graphql-language-service/esm/index.js": + /*!***************************************************!*\ + !*** ../../graphql-language-service/esm/index.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "CharacterStream", { + enumerable: true, + get: function () { + return _parser.CharacterStream; + }, + }); + Object.defineProperty(exports, "CompletionItemKind", { + enumerable: true, + get: function () { + return _types.CompletionItemKind; + }, + }); + Object.defineProperty(exports, "DIAGNOSTIC_SEVERITY", { + enumerable: true, + get: function () { + return _interface.DIAGNOSTIC_SEVERITY; + }, + }); + Object.defineProperty(exports, "FileChangeTypeKind", { + enumerable: true, + get: function () { + return _types.FileChangeTypeKind; + }, + }); + Object.defineProperty(exports, "GraphQLDocumentMode", { + enumerable: true, + get: function () { + return _parser.GraphQLDocumentMode; + }, + }); + Object.defineProperty(exports, "LexRules", { + enumerable: true, + get: function () { + return _parser.LexRules; + }, + }); + Object.defineProperty(exports, "ParseRules", { + enumerable: true, + get: function () { + return _parser.ParseRules; + }, + }); + Object.defineProperty(exports, "Position", { + enumerable: true, + get: function () { + return _utils.Position; + }, + }); + Object.defineProperty(exports, "Range", { + enumerable: true, + get: function () { + return _utils.Range; + }, + }); + Object.defineProperty(exports, "RuleKinds", { + enumerable: true, + get: function () { + return _parser.RuleKinds; + }, + }); + Object.defineProperty(exports, "SEVERITY", { + enumerable: true, + get: function () { + return _interface.SEVERITY; + }, + }); + Object.defineProperty(exports, "SuggestionCommand", { + enumerable: true, + get: function () { + return _interface.SuggestionCommand; + }, + }); + Object.defineProperty(exports, "canUseDirective", { + enumerable: true, + get: function () { + return _interface.canUseDirective; + }, + }); + Object.defineProperty(exports, "collectVariables", { + enumerable: true, + get: function () { + return _utils.collectVariables; + }, + }); + Object.defineProperty(exports, "getASTNodeAtPosition", { + enumerable: true, + get: function () { + return _utils.getASTNodeAtPosition; + }, + }); + Object.defineProperty(exports, "getAutocompleteSuggestions", { + enumerable: true, + get: function () { + return _interface.getAutocompleteSuggestions; + }, + }); + Object.defineProperty(exports, "getDefinitionQueryResultForArgument", { + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForArgument; + }, + }); + Object.defineProperty( + exports, + "getDefinitionQueryResultForDefinitionNode", + { + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForDefinitionNode; + }, + } + ); + Object.defineProperty(exports, "getDefinitionQueryResultForField", { + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForField; + }, + }); + Object.defineProperty( + exports, + "getDefinitionQueryResultForFragmentSpread", + { + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForFragmentSpread; + }, + } + ); + Object.defineProperty(exports, "getDefinitionQueryResultForNamedType", { + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForNamedType; + }, + }); + Object.defineProperty(exports, "getDefinitionState", { + enumerable: true, + get: function () { + return _parser.getDefinitionState; + }, + }); + Object.defineProperty(exports, "getDiagnostics", { + enumerable: true, + get: function () { + return _interface.getDiagnostics; + }, + }); + Object.defineProperty(exports, "getFieldDef", { + enumerable: true, + get: function () { + return _parser.getFieldDef; + }, + }); + Object.defineProperty(exports, "getFragmentDefinitions", { + enumerable: true, + get: function () { + return _interface.getFragmentDefinitions; + }, + }); + Object.defineProperty(exports, "getFragmentDependencies", { + enumerable: true, + get: function () { + return _utils.getFragmentDependencies; + }, + }); + Object.defineProperty(exports, "getFragmentDependenciesForAST", { + enumerable: true, + get: function () { + return _utils.getFragmentDependenciesForAST; + }, + }); + Object.defineProperty(exports, "getHoverInformation", { + enumerable: true, + get: function () { + return _interface.getHoverInformation; + }, + }); + Object.defineProperty(exports, "getOperationASTFacts", { + enumerable: true, + get: function () { + return _utils.getOperationASTFacts; + }, + }); + Object.defineProperty(exports, "getOperationFacts", { + enumerable: true, + get: function () { + return _utils.getOperationFacts; + }, + }); + Object.defineProperty(exports, "getOutline", { + enumerable: true, + get: function () { + return _interface.getOutline; + }, + }); + Object.defineProperty(exports, "getQueryFacts", { + enumerable: true, + get: function () { + return _utils.getQueryFacts; + }, + }); + Object.defineProperty(exports, "getRange", { + enumerable: true, + get: function () { + return _interface.getRange; + }, + }); + Object.defineProperty(exports, "getTokenAtPosition", { + enumerable: true, + get: function () { + return _parser.getTokenAtPosition; + }, + }); + Object.defineProperty(exports, "getTypeInfo", { + enumerable: true, + get: function () { + return _interface.getTypeInfo; + }, + }); + Object.defineProperty(exports, "getVariableCompletions", { + enumerable: true, + get: function () { + return _interface.getVariableCompletions; + }, + }); + Object.defineProperty(exports, "getVariablesJSONSchema", { + enumerable: true, + get: function () { + return _utils.getVariablesJSONSchema; + }, + }); + Object.defineProperty(exports, "isIgnored", { + enumerable: true, + get: function () { + return _parser.isIgnored; + }, + }); + Object.defineProperty(exports, "list", { + enumerable: true, + get: function () { + return _parser.list; + }, + }); + Object.defineProperty(exports, "offsetToPosition", { + enumerable: true, + get: function () { + return _utils.offsetToPosition; + }, + }); + Object.defineProperty(exports, "onlineParser", { + enumerable: true, + get: function () { + return _parser.onlineParser; + }, + }); + Object.defineProperty(exports, "opt", { + enumerable: true, + get: function () { + return _parser.opt; + }, + }); + Object.defineProperty(exports, "p", { + enumerable: true, + get: function () { + return _parser.p; + }, + }); + Object.defineProperty(exports, "pointToOffset", { + enumerable: true, + get: function () { + return _utils.pointToOffset; + }, + }); + Object.defineProperty(exports, "t", { + enumerable: true, + get: function () { + return _parser.t; + }, + }); + Object.defineProperty(exports, "validateQuery", { + enumerable: true, + get: function () { + return _interface.validateQuery; + }, + }); + Object.defineProperty(exports, "validateWithCustomRules", { + enumerable: true, + get: function () { + return _utils.validateWithCustomRules; + }, + }); + var _interface = __webpack_require__( + /*! ./interface */ "../../graphql-language-service/esm/interface/index.js" + ); + var _parser = __webpack_require__( + /*! ./parser */ "../../graphql-language-service/esm/parser/index.js" + ); + var _types = __webpack_require__( + /*! ./types */ "../../graphql-language-service/esm/types.js" + ); + var _utils = __webpack_require__( + /*! ./utils */ "../../graphql-language-service/esm/utils/index.js" + ); - // fail if list has another type - if (isOrdered) { - posAfterMarker = skipOrderedListMarker(state, nextLine); - if (posAfterMarker < 0) { - break; - } - start = state.bMarks[nextLine] + state.tShift[nextLine]; - } else { - posAfterMarker = skipBulletListMarker(state, nextLine); - if (posAfterMarker < 0) { - break; - } - } - if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { - break; - } - } + /***/ + }, - // Finalize list - if (isOrdered) { - token = state.push('ordered_list_close', 'ol', -1); - } else { - token = state.push('bullet_list_close', 'ul', -1); - } - token.markup = String.fromCharCode(markerCharCode); - listLines[1] = nextLine; - state.line = nextLine; - state.parentType = oldParentType; - - // mark paragraphs tight if needed - if (tight) { - markTightParagraphs(state, listTokIdx); - } - return true; -} -function reference(state, startLine, _endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - let nextLine = startLine + 1; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (state.src.charCodeAt(pos) !== 0x5B /* [ */) { - return false; - } - function getNextLine(nextLine) { - const endLine = state.lineMax; - if (nextLine >= endLine || state.isEmpty(nextLine)) { - // empty line or end of input - return null; - } - let isContinuation = false; + /***/ "../../graphql-language-service/esm/interface/autocompleteUtils.js": + /*!*************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/autocompleteUtils.js ***! + \*************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getInsertText = + exports.getInputInsertText = + exports.getFieldInsertText = + void 0; + exports.hintList = hintList; + exports.objectValues = objectValues; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function objectValues(object) { + const keys = Object.keys(object); + const len = keys.length; + const values = new Array(len); + for (let i = 0; i < len; ++i) { + values[i] = object[keys[i]]; + } + return values; + } + function hintList(token, list) { + return filterAndSortList(list, normalizeText(token.string)); + } + function filterAndSortList(list, text) { + if ( + !text || + text.trim() === "" || + text.trim() === ":" || + text.trim() === "{" + ) { + return filterNonEmpty(list, (entry) => !entry.isDeprecated); + } + const byProximity = list.map((entry) => ({ + proximity: getProximity(normalizeText(entry.label), text), + entry, + })); + return filterNonEmpty( + filterNonEmpty(byProximity, (pair) => pair.proximity <= 2), + (pair) => !pair.entry.isDeprecated + ) + .sort( + (a, b) => + (a.entry.isDeprecated ? 1 : 0) - + (b.entry.isDeprecated ? 1 : 0) || + a.proximity - b.proximity || + a.entry.label.length - b.entry.label.length + ) + .map((pair) => pair.entry); + } + function filterNonEmpty(array, predicate) { + const filtered = array.filter(predicate); + return filtered.length === 0 ? array : filtered; + } + function normalizeText(text) { + return text.toLowerCase().replaceAll(/\W/g, ""); + } + function getProximity(suggestion, text) { + let proximity = lexicalDistance(text, suggestion); + if (suggestion.length > text.length) { + proximity -= suggestion.length - text.length - 1; + proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + } + return proximity; + } + function lexicalDistance(a, b) { + let i; + let j; + const d = []; + const aLength = a.length; + const bLength = b.length; + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min( + d[i - 1][j] + 1, + d[i][j - 1] + 1, + d[i - 1][j - 1] + cost + ); + if ( + i > 1 && + j > 1 && + a[i - 1] === b[j - 2] && + a[i - 2] === b[j - 1] + ) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + return d[aLength][bLength]; + } + const insertSuffix = (n) => + ` {\n $${n !== null && n !== void 0 ? n : 1}\n}`; + const getInsertText = (prefix, type, fallback) => { + if (!type) { + return fallback !== null && fallback !== void 0 ? fallback : prefix; + } + const namedType = (0, _graphql.getNamedType)(type); + if ( + (0, _graphql.isObjectType)(namedType) || + (0, _graphql.isInputObjectType)(namedType) || + (0, _graphql.isListType)(namedType) || + (0, _graphql.isAbstractType)(namedType) + ) { + return prefix + insertSuffix(); + } + return fallback !== null && fallback !== void 0 ? fallback : prefix; + }; + exports.getInsertText = getInsertText; + const getInputInsertText = (prefix, type, fallback) => { + if ((0, _graphql.isListType)(type)) { + const baseType = (0, _graphql.getNamedType)(type.ofType); + return prefix + `[${getInsertText("", baseType, "$1")}]`; + } + return getInsertText(prefix, type, fallback); + }; + exports.getInputInsertText = getInputInsertText; + const getFieldInsertText = (field) => { + const requiredArgs = field.args.filter((arg) => + arg.type.toString().endsWith("!") + ); + if (!requiredArgs.length) { + return; + } + return ( + field.name + + `(${requiredArgs.map( + (arg, i) => `${arg.name}: $${i + 1}` + )}) ${getInsertText("", field.type, "\n")}` + ); + }; + exports.getFieldInsertText = getFieldInsertText; - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - isContinuation = true; - } + /***/ + }, - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - isContinuation = true; - } - if (!isContinuation) { - const terminatorRules = state.md.block.ruler.getRules('reference'); - const oldParentType = state.parentType; - state.parentType = 'reference'; - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; + /***/ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js": + /*!**********************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js ***! + \**********************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.SuggestionCommand = void 0; + exports.canUseDirective = canUseDirective; + exports.getAutocompleteSuggestions = getAutocompleteSuggestions; + exports.getFragmentDefinitions = getFragmentDefinitions; + Object.defineProperty(exports, "getTypeInfo", { + enumerable: true, + get: function () { + return _parser.getTypeInfo; + }, + }); + exports.getVariableCompletions = getVariableCompletions; + Object.defineProperty(exports, "runOnlineParser", { + enumerable: true, + get: function () { + return _parser.runOnlineParser; + }, + }); + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _types = __webpack_require__( + /*! ../types */ "../../graphql-language-service/esm/types.js" + ); + var _parser = __webpack_require__( + /*! ../parser */ "../../graphql-language-service/esm/parser/index.js" + ); + var _autocompleteUtils = __webpack_require__( + /*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js" + ); + var _vscodeLanguageserverTypes = __webpack_require__( + /*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js" + ); + const SuggestionCommand = (exports.SuggestionCommand = { + command: "editor.action.triggerSuggest", + title: "Suggestions", + }); + const collectFragmentDefs = (op) => { + const externalFragments = []; + if (op) { + try { + (0, _graphql.visit)((0, _graphql.parse)(op), { + FragmentDefinition(def) { + externalFragments.push(def); + }, + }); + } catch (_a) { + return []; + } + } + return externalFragments; + }; + function getAutocompleteSuggestions( + schema, + queryText, + cursor, + contextToken, + fragmentDefs, + options + ) { + var _a; + const opts = Object.assign(Object.assign({}, options), { + schema, + }); + const context = (0, _parser.getContextAtPosition)( + queryText, + cursor, + schema, + contextToken, + options + ); + if (!context) { + return []; + } + const { state, typeInfo, mode, token } = context; + const { kind, step, prevState } = state; + if (kind === _parser.RuleKinds.DOCUMENT) { + if (mode === _parser.GraphQLDocumentMode.TYPE_SYSTEM) { + return getSuggestionsForTypeSystemDefinitions(token); + } + if (mode === _parser.GraphQLDocumentMode.EXECUTABLE) { + return getSuggestionsForExecutableDefinitions(token); + } + return getSuggestionsForUnknownDocumentMode(token); + } + if (kind === _parser.RuleKinds.EXTEND_DEF) { + return getSuggestionsForExtensionDefinitions(token); + } + if ( + ((_a = + prevState === null || prevState === void 0 + ? void 0 + : prevState.prevState) === null || _a === void 0 + ? void 0 + : _a.kind) === _parser.RuleKinds.EXTENSION_DEFINITION && + state.name + ) { + return (0, _autocompleteUtils.hintList)(token, []); + } + if ( + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _graphql.Kind.SCALAR_TYPE_EXTENSION + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter(_graphql.isScalarType) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + })) + ); + } + if ( + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _graphql.Kind.OBJECT_TYPE_EXTENSION + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter( + (type) => + (0, _graphql.isObjectType)(type) && + !type.name.startsWith("__") + ) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + })) + ); + } + if ( + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _graphql.Kind.INTERFACE_TYPE_EXTENSION + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter(_graphql.isInterfaceType) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + })) + ); + } + if ( + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _graphql.Kind.UNION_TYPE_EXTENSION + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter(_graphql.isUnionType) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + })) + ); + } + if ( + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _graphql.Kind.ENUM_TYPE_EXTENSION + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter( + (type) => + (0, _graphql.isEnumType)(type) && + !type.name.startsWith("__") + ) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + })) + ); + } + if ( + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter(_graphql.isInputObjectType) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + })) + ); + } + if ( + kind === _parser.RuleKinds.IMPLEMENTS || + (kind === _parser.RuleKinds.NAMED_TYPE && + (prevState === null || prevState === void 0 + ? void 0 + : prevState.kind) === _parser.RuleKinds.IMPLEMENTS) + ) { + return getSuggestionsForImplements( + token, + state, + schema, + queryText, + typeInfo + ); + } + if ( + kind === _parser.RuleKinds.SELECTION_SET || + kind === _parser.RuleKinds.FIELD || + kind === _parser.RuleKinds.ALIASED_FIELD + ) { + return getSuggestionsForFieldNames(token, typeInfo, opts); + } + if ( + kind === _parser.RuleKinds.ARGUMENTS || + (kind === _parser.RuleKinds.ARGUMENT && step === 0) + ) { + const { argDefs } = typeInfo; + if (argDefs) { + return (0, _autocompleteUtils.hintList)( + token, + argDefs.map((argDef) => { + var _a; + return { + label: argDef.name, + insertText: (0, _autocompleteUtils.getInputInsertText)( + argDef.name + ": ", + argDef.type + ), + insertTextMode: + _vscodeLanguageserverTypes.InsertTextMode + .adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + command: SuggestionCommand, + labelDetails: { + detail: " " + String(argDef.type), + }, + documentation: + (_a = argDef.description) !== null && _a !== void 0 + ? _a + : undefined, + kind: _types.CompletionItemKind.Variable, + type: argDef.type, + }; + }) + ); + } + } + if ( + (kind === _parser.RuleKinds.OBJECT_VALUE || + (kind === _parser.RuleKinds.OBJECT_FIELD && step === 0)) && + typeInfo.objectFieldDefs + ) { + const objectFields = (0, _autocompleteUtils.objectValues)( + typeInfo.objectFieldDefs + ); + const completionKind = + kind === _parser.RuleKinds.OBJECT_VALUE + ? _types.CompletionItemKind.Value + : _types.CompletionItemKind.Field; + return (0, _autocompleteUtils.hintList)( + token, + objectFields.map((field) => { + var _a; + return { + label: field.name, + detail: String(field.type), + documentation: + (_a = + field === null || field === void 0 + ? void 0 + : field.description) !== null && _a !== void 0 + ? _a + : undefined, + kind: completionKind, + type: field.type, + insertText: (0, _autocompleteUtils.getInputInsertText)( + field.name + ": ", + field.type + ), + insertTextMode: + _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + command: SuggestionCommand, + }; + }) + ); + } + if ( + kind === _parser.RuleKinds.ENUM_VALUE || + (kind === _parser.RuleKinds.LIST_VALUE && step === 1) || + (kind === _parser.RuleKinds.OBJECT_FIELD && step === 2) || + (kind === _parser.RuleKinds.ARGUMENT && step === 2) + ) { + return getSuggestionsForInputValues( + token, + typeInfo, + queryText, + schema + ); + } + if (kind === _parser.RuleKinds.VARIABLE && step === 1) { + const namedInputType = (0, _graphql.getNamedType)( + typeInfo.inputType + ); + const variableDefinitions = getVariableCompletions( + queryText, + schema, + token + ); + return (0, _autocompleteUtils.hintList)( + token, + variableDefinitions.filter( + (v) => + v.detail === + (namedInputType === null || namedInputType === void 0 + ? void 0 + : namedInputType.name) + ) + ); + } + if ( + (kind === _parser.RuleKinds.TYPE_CONDITION && step === 1) || + (kind === _parser.RuleKinds.NAMED_TYPE && + prevState != null && + prevState.kind === _parser.RuleKinds.TYPE_CONDITION) + ) { + return getSuggestionsForFragmentTypeConditions( + token, + typeInfo, + schema, + kind + ); + } + if (kind === _parser.RuleKinds.FRAGMENT_SPREAD && step === 1) { + return getSuggestionsForFragmentSpread( + token, + typeInfo, + schema, + queryText, + Array.isArray(fragmentDefs) + ? fragmentDefs + : collectFragmentDefs(fragmentDefs) + ); + } + const unwrappedState = unwrapType(state); + if (unwrappedState.kind === _parser.RuleKinds.FIELD_DEF) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter( + (type) => + (0, _graphql.isOutputType)(type) && + !type.name.startsWith("__") + ) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + insertText: ( + options === null || options === void 0 + ? void 0 + : options.fillLeafsOnComplete + ) + ? type.name + "\n" + : type.name, + insertTextMode: + _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + })) + ); + } + if ( + unwrappedState.kind === _parser.RuleKinds.INPUT_VALUE_DEF && + step === 2 + ) { + return (0, _autocompleteUtils.hintList)( + token, + Object.values(schema.getTypeMap()) + .filter( + (type) => + (0, _graphql.isInputType)(type) && + !type.name.startsWith("__") + ) + .map((type) => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + insertText: ( + options === null || options === void 0 + ? void 0 + : options.fillLeafsOnComplete + ) + ? type.name + "\n$1" + : type.name, + insertTextMode: + _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + })) + ); + } + if ( + (kind === _parser.RuleKinds.VARIABLE_DEFINITION && step === 2) || + (kind === _parser.RuleKinds.LIST_TYPE && step === 1) || + (kind === _parser.RuleKinds.NAMED_TYPE && + prevState && + (prevState.kind === _parser.RuleKinds.VARIABLE_DEFINITION || + prevState.kind === _parser.RuleKinds.LIST_TYPE || + prevState.kind === _parser.RuleKinds.NON_NULL_TYPE)) + ) { + return getSuggestionsForVariableDefinition(token, schema, kind); + } + if (kind === _parser.RuleKinds.DIRECTIVE) { + return getSuggestionsForDirective(token, state, schema, kind); + } + if (kind === _parser.RuleKinds.DIRECTIVE_DEF) { + return getSuggestionsForDirectiveArguments( + token, + state, + schema, + kind + ); + } + return []; } - } - state.parentType = oldParentType; - if (terminate) { - // terminated by another block - return null; - } - } - const pos = state.bMarks[nextLine] + state.tShift[nextLine]; - const max = state.eMarks[nextLine]; - - // max + 1 explicitly includes the newline - return state.src.slice(pos, max + 1); - } - let str = state.src.slice(pos, max + 1); - max = str.length; - let labelEnd = -1; - for (pos = 1; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x5B /* [ */) { - return false; - } else if (ch === 0x5D /* ] */) { - labelEnd = pos; - break; - } else if (ch === 0x0A /* \n */) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; - } - } else if (ch === 0x5C /* \ */) { - pos++; - if (pos < max && str.charCodeAt(pos) === 0x0A) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + const typeSystemCompletionItems = [ + { + label: "type", + kind: _types.CompletionItemKind.Function, + }, + { + label: "interface", + kind: _types.CompletionItemKind.Function, + }, + { + label: "union", + kind: _types.CompletionItemKind.Function, + }, + { + label: "input", + kind: _types.CompletionItemKind.Function, + }, + { + label: "scalar", + kind: _types.CompletionItemKind.Function, + }, + { + label: "schema", + kind: _types.CompletionItemKind.Function, + }, + ]; + const executableCompletionItems = [ + { + label: "query", + kind: _types.CompletionItemKind.Function, + }, + { + label: "mutation", + kind: _types.CompletionItemKind.Function, + }, + { + label: "subscription", + kind: _types.CompletionItemKind.Function, + }, + { + label: "fragment", + kind: _types.CompletionItemKind.Function, + }, + { + label: "{", + kind: _types.CompletionItemKind.Constructor, + }, + ]; + function getSuggestionsForTypeSystemDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, [ + { + label: "extend", + kind: _types.CompletionItemKind.Function, + }, + ...typeSystemCompletionItems, + ]); } - } - } - } - if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A /* : */) { - return false; - } - - // [label]: destination 'title' - // ^^^ skip optional whitespace here - for (pos = labelEnd + 2; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x0A) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; - } - } else if (isSpace(ch)) ;else { - break; - } - } - - // [label]: destination 'title' - // ^^^^^^^^^^^ parse this - const destRes = state.md.helpers.parseLinkDestination(str, pos, max); - if (!destRes.ok) { - return false; - } - const href = state.md.normalizeLink(destRes.str); - if (!state.md.validateLink(href)) { - return false; - } - pos = destRes.pos; - - // save cursor state, we could require to rollback later - const destEndPos = pos; - const destEndLineNo = nextLine; - - // [label]: destination 'title' - // ^^^ skipping those spaces - const start = pos; - for (; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x0A) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; - } - } else if (isSpace(ch)) ;else { - break; - } - } - - // [label]: destination 'title' - // ^^^^^^^ parse this - let titleRes = state.md.helpers.parseLinkTitle(str, pos, max); - while (titleRes.can_continue) { - const lineContent = getNextLine(nextLine); - if (lineContent === null) break; - str += lineContent; - pos = max; - max = str.length; - nextLine++; - titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes); - } - let title; - if (pos < max && start !== pos && titleRes.ok) { - title = titleRes.str; - pos = titleRes.pos; - } else { - title = ''; - pos = destEndPos; - nextLine = destEndLineNo; - } - - // skip trailing spaces until the rest of the line - while (pos < max) { - const ch = str.charCodeAt(pos); - if (!isSpace(ch)) { - break; - } - pos++; - } - if (pos < max && str.charCodeAt(pos) !== 0x0A) { - if (title) { - // garbage at the end of the line after title, - // but it could still be a valid reference if we roll back - title = ''; - pos = destEndPos; - nextLine = destEndLineNo; - while (pos < max) { - const ch = str.charCodeAt(pos); - if (!isSpace(ch)) { - break; - } - pos++; - } - } - } - if (pos < max && str.charCodeAt(pos) !== 0x0A) { - // garbage at the end of the line - return false; - } - const label = normalizeReference(str.slice(1, labelEnd)); - if (!label) { - // CommonMark 0.20 disallows empty labels - return false; - } - - // Reference can not terminate anything. This check is for safety only. - /* istanbul ignore if */ - if (silent) { - return true; - } - if (typeof state.env.references === 'undefined') { - state.env.references = {}; - } - if (typeof state.env.references[label] === 'undefined') { - state.env.references[label] = { - title, - href - }; - } - state.line = nextLine; - return true; -} - -// List of valid html blocks names, according to commonmark spec -// https://spec.commonmark.org/0.30/#html-blocks - -var block_names = ['address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu', 'menuitem', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'search', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul']; - -// Regexps to match html elements - -const attr_name = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; -const unquoted = '[^"\'=<>`\\x00-\\x20]+'; -const single_quoted = "'[^']*'"; -const double_quoted = '"[^"]*"'; -const attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')'; -const attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)'; -const open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; -const close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; -const comment = ''; -const processing = '<[?][\\s\\S]*?[?]>'; -const declaration = ']*>'; -const cdata = ''; -const HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment + '|' + processing + '|' + declaration + '|' + cdata + ')'); -const HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')'); - -// HTML block - -// An array of opening and corresponding closing sequences for html tags, -// last argument defines whether it can terminate a paragraph or not -// -const HTML_SEQUENCES = [[/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true], [/^/, true], [/^<\?/, /\?>/, true], [/^/, true], [/^/, true], [new RegExp('^|$))', 'i'), /^$/, true], [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false]]; -function html_block(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (!state.md.options.html) { - return false; - } - if (state.src.charCodeAt(pos) !== 0x3C /* < */) { - return false; - } - let lineText = state.src.slice(pos, max); - let i = 0; - for (; i < HTML_SEQUENCES.length; i++) { - if (HTML_SEQUENCES[i][0].test(lineText)) { - break; - } - } - if (i === HTML_SEQUENCES.length) { - return false; - } - if (silent) { - // true if this sequence can be a terminator, false otherwise - return HTML_SEQUENCES[i][2]; - } - let nextLine = startLine + 1; - - // If we are here - we detected HTML block. - // Let's roll down till block end. - if (!HTML_SEQUENCES[i][1].test(lineText)) { - for (; nextLine < endLine; nextLine++) { - if (state.sCount[nextLine] < state.blkIndent) { - break; - } - pos = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - lineText = state.src.slice(pos, max); - if (HTML_SEQUENCES[i][1].test(lineText)) { - if (lineText.length !== 0) { - nextLine++; - } - break; - } - } - } - state.line = nextLine; - const token = state.push('html_block', '', 0); - token.map = [startLine, nextLine]; - token.content = state.getLines(startLine, nextLine, state.blkIndent, true); - return true; -} - -// heading (#, ##, ...) - -function heading(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - let ch = state.src.charCodeAt(pos); - if (ch !== 0x23 /* # */ || pos >= max) { - return false; - } - - // count heading level - let level = 1; - ch = state.src.charCodeAt(++pos); - while (ch === 0x23 /* # */ && pos < max && level <= 6) { - level++; - ch = state.src.charCodeAt(++pos); - } - if (level > 6 || pos < max && !isSpace(ch)) { - return false; - } - if (silent) { - return true; - } - - // Let's cut tails like ' ### ' from the end of string - - max = state.skipSpacesBack(max, pos); - const tmp = state.skipCharsBack(max, 0x23, pos); // # - if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { - max = tmp; - } - state.line = startLine + 1; - const token_o = state.push('heading_open', 'h' + String(level), 1); - token_o.markup = '########'.slice(0, level); - token_o.map = [startLine, state.line]; - const token_i = state.push('inline', '', 0); - token_i.content = state.src.slice(pos, max).trim(); - token_i.map = [startLine, state.line]; - token_i.children = []; - const token_c = state.push('heading_close', 'h' + String(level), -1); - token_c.markup = '########'.slice(0, level); - return true; -} - -// lheading (---, ===) - -function lheading(state, startLine, endLine /*, silent */) { - const terminatorRules = state.md.block.ruler.getRules('paragraph'); - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - const oldParentType = state.parentType; - state.parentType = 'paragraph'; // use paragraph to match terminatorRules - - // jump line-by-line until empty one or EOF - let level = 0; - let marker; - let nextLine = startLine + 1; - for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - continue; - } - - // - // Check for underline in setext header - // - if (state.sCount[nextLine] >= state.blkIndent) { - let pos = state.bMarks[nextLine] + state.tShift[nextLine]; - const max = state.eMarks[nextLine]; - if (pos < max) { - marker = state.src.charCodeAt(pos); - if (marker === 0x2D /* - */ || marker === 0x3D /* = */) { - pos = state.skipChars(pos, marker); - pos = state.skipSpaces(pos); - if (pos >= max) { - level = marker === 0x3D /* = */ ? 1 : 2; - break; + function getSuggestionsForExecutableDefinitions(token) { + return (0, _autocompleteUtils.hintList)( + token, + executableCompletionItems + ); + } + function getSuggestionsForUnknownDocumentMode(token) { + return (0, _autocompleteUtils.hintList)(token, [ + { + label: "extend", + kind: _types.CompletionItemKind.Function, + }, + ...executableCompletionItems, + ...typeSystemCompletionItems, + ]); + } + function getSuggestionsForExtensionDefinitions(token) { + return (0, _autocompleteUtils.hintList)( + token, + typeSystemCompletionItems + ); + } + function getSuggestionsForFieldNames(token, typeInfo, options) { + var _a; + if (typeInfo.parentType) { + const { parentType } = typeInfo; + let fields = []; + if ("getFields" in parentType) { + fields = (0, _autocompleteUtils.objectValues)( + parentType.getFields() + ); + } + if ((0, _graphql.isCompositeType)(parentType)) { + fields.push(_graphql.TypeNameMetaFieldDef); + } + if ( + parentType === + ((_a = + options === null || options === void 0 + ? void 0 + : options.schema) === null || _a === void 0 + ? void 0 + : _a.getQueryType()) + ) { + fields.push( + _graphql.SchemaMetaFieldDef, + _graphql.TypeMetaFieldDef + ); + } + return (0, _autocompleteUtils.hintList)( + token, + fields.map((field, index) => { + var _a; + const suggestion = { + sortText: String(index) + field.name, + label: field.name, + detail: String(field.type), + documentation: + (_a = field.description) !== null && _a !== void 0 + ? _a + : undefined, + deprecated: Boolean(field.deprecationReason), + isDeprecated: Boolean(field.deprecationReason), + deprecationReason: field.deprecationReason, + kind: _types.CompletionItemKind.Field, + labelDetails: { + detail: " " + field.type.toString(), + }, + type: field.type, + }; + if ( + options === null || options === void 0 + ? void 0 + : options.fillLeafsOnComplete + ) { + suggestion.insertText = (0, + _autocompleteUtils.getFieldInsertText)(field); + if (!suggestion.insertText) { + suggestion.insertText = (0, + _autocompleteUtils.getInsertText)( + field.name, + field.type, + field.name + (token.state.needsAdvance ? "" : "\n") + ); + } + if (suggestion.insertText) { + suggestion.insertTextFormat = + _types.InsertTextFormat.Snippet; + suggestion.insertTextMode = + _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation; + suggestion.command = SuggestionCommand; + } + } + return suggestion; + }) + ); + } + return []; + } + function getSuggestionsForInputValues( + token, + typeInfo, + queryText, + schema + ) { + const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); + const queryVariables = getVariableCompletions( + queryText, + schema, + token + ).filter( + (v) => + v.detail === + (namedInputType === null || namedInputType === void 0 + ? void 0 + : namedInputType.name) + ); + if (namedInputType instanceof _graphql.GraphQLEnumType) { + const values = namedInputType.getValues(); + return (0, _autocompleteUtils.hintList)( + token, + values + .map((value) => { + var _a; + return { + label: value.name, + detail: String(namedInputType), + documentation: + (_a = value.description) !== null && _a !== void 0 + ? _a + : undefined, + deprecated: Boolean(value.deprecationReason), + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + kind: _types.CompletionItemKind.EnumMember, + type: namedInputType, + }; + }) + .concat(queryVariables) + ); + } + if (namedInputType === _graphql.GraphQLBoolean) { + return (0, _autocompleteUtils.hintList)( + token, + queryVariables.concat([ + { + label: "true", + detail: String(_graphql.GraphQLBoolean), + documentation: "Not false.", + kind: _types.CompletionItemKind.Variable, + type: _graphql.GraphQLBoolean, + }, + { + label: "false", + detail: String(_graphql.GraphQLBoolean), + documentation: "Not true.", + kind: _types.CompletionItemKind.Variable, + type: _graphql.GraphQLBoolean, + }, + ]) + ); + } + return queryVariables; + } + function getSuggestionsForImplements( + token, + tokenState, + schema, + documentText, + typeInfo + ) { + if (tokenState.needsSeparator) { + return []; + } + const typeMap = schema.getTypeMap(); + const schemaInterfaces = (0, _autocompleteUtils.objectValues)( + typeMap + ).filter(_graphql.isInterfaceType); + const schemaInterfaceNames = schemaInterfaces.map(({ name }) => name); + const inlineInterfaces = new Set(); + (0, _parser.runOnlineParser)(documentText, (_, state) => { + var _a, _b, _c, _d, _e; + if (state.name) { + if ( + state.kind === _parser.RuleKinds.INTERFACE_DEF && + !schemaInterfaceNames.includes(state.name) + ) { + inlineInterfaces.add(state.name); + } + if ( + state.kind === _parser.RuleKinds.NAMED_TYPE && + ((_a = state.prevState) === null || _a === void 0 + ? void 0 + : _a.kind) === _parser.RuleKinds.IMPLEMENTS + ) { + if (typeInfo.interfaceDef) { + const existingType = + (_b = typeInfo.interfaceDef) === null || _b === void 0 + ? void 0 + : _b + .getInterfaces() + .find(({ name }) => name === state.name); + if (existingType) { + return; + } + const type = schema.getType(state.name); + const interfaceConfig = + (_c = typeInfo.interfaceDef) === null || _c === void 0 + ? void 0 + : _c.toConfig(); + typeInfo.interfaceDef = new _graphql.GraphQLInterfaceType( + Object.assign(Object.assign({}, interfaceConfig), { + interfaces: [ + ...interfaceConfig.interfaces, + type || + new _graphql.GraphQLInterfaceType({ + name: state.name, + fields: {}, + }), + ], + }) + ); + } else if (typeInfo.objectTypeDef) { + const existingType = + (_d = typeInfo.objectTypeDef) === null || _d === void 0 + ? void 0 + : _d + .getInterfaces() + .find(({ name }) => name === state.name); + if (existingType) { + return; + } + const type = schema.getType(state.name); + const objectTypeConfig = + (_e = typeInfo.objectTypeDef) === null || _e === void 0 + ? void 0 + : _e.toConfig(); + typeInfo.objectTypeDef = new _graphql.GraphQLObjectType( + Object.assign(Object.assign({}, objectTypeConfig), { + interfaces: [ + ...objectTypeConfig.interfaces, + type || + new _graphql.GraphQLInterfaceType({ + name: state.name, + fields: {}, + }), + ], + }) + ); + } + } + } + }); + const currentTypeToExtend = + typeInfo.interfaceDef || typeInfo.objectTypeDef; + const siblingInterfaces = + (currentTypeToExtend === null || currentTypeToExtend === void 0 + ? void 0 + : currentTypeToExtend.getInterfaces()) || []; + const siblingInterfaceNames = siblingInterfaces.map( + ({ name }) => name + ); + const possibleInterfaces = schemaInterfaces + .concat( + [...inlineInterfaces].map((name) => ({ + name, + })) + ) + .filter( + ({ name }) => + name !== + (currentTypeToExtend === null || + currentTypeToExtend === void 0 + ? void 0 + : currentTypeToExtend.name) && + !siblingInterfaceNames.includes(name) + ); + return (0, _autocompleteUtils.hintList)( + token, + possibleInterfaces.map((type) => { + const result = { + label: type.name, + kind: _types.CompletionItemKind.Interface, + type, + }; + if ( + type === null || type === void 0 ? void 0 : type.description + ) { + result.documentation = type.description; + } + return result; + }) + ); + } + function getSuggestionsForFragmentTypeConditions( + token, + typeInfo, + schema, + _kind + ) { + let possibleTypes; + if (typeInfo.parentType) { + if ((0, _graphql.isAbstractType)(typeInfo.parentType)) { + const abstractType = (0, _graphql.assertAbstractType)( + typeInfo.parentType + ); + const possibleObjTypes = schema.getPossibleTypes(abstractType); + const possibleIfaceMap = Object.create(null); + for (const type of possibleObjTypes) { + for (const iface of type.getInterfaces()) { + possibleIfaceMap[iface.name] = iface; + } + } + possibleTypes = possibleObjTypes.concat( + (0, _autocompleteUtils.objectValues)(possibleIfaceMap) + ); + } else { + possibleTypes = [typeInfo.parentType]; + } + } else { + const typeMap = schema.getTypeMap(); + possibleTypes = (0, _autocompleteUtils.objectValues)( + typeMap + ).filter( + (type) => + (0, _graphql.isCompositeType)(type) && + !type.name.startsWith("__") + ); } + return (0, _autocompleteUtils.hintList)( + token, + possibleTypes.map((type) => { + const namedType = (0, _graphql.getNamedType)(type); + return { + label: String(type), + documentation: + (namedType === null || namedType === void 0 + ? void 0 + : namedType.description) || "", + kind: _types.CompletionItemKind.Field, + }; + }) + ); + } + function getSuggestionsForFragmentSpread( + token, + typeInfo, + schema, + queryText, + fragmentDefs + ) { + if (!queryText) { + return []; + } + const typeMap = schema.getTypeMap(); + const defState = (0, _parser.getDefinitionState)(token.state); + const fragments = getFragmentDefinitions(queryText); + if (fragmentDefs && fragmentDefs.length > 0) { + fragments.push(...fragmentDefs); + } + const relevantFrags = fragments.filter( + (frag) => + typeMap[frag.typeCondition.name.value] && + !( + defState && + defState.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && + defState.name === frag.name.value + ) && + (0, _graphql.isCompositeType)(typeInfo.parentType) && + (0, _graphql.isCompositeType)( + typeMap[frag.typeCondition.name.value] + ) && + (0, _graphql.doTypesOverlap)( + schema, + typeInfo.parentType, + typeMap[frag.typeCondition.name.value] + ) + ); + return (0, _autocompleteUtils.hintList)( + token, + relevantFrags.map((frag) => ({ + label: frag.name.value, + detail: String(typeMap[frag.typeCondition.name.value]), + documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, + labelDetails: { + detail: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, + }, + kind: _types.CompletionItemKind.Field, + type: typeMap[frag.typeCondition.name.value], + })) + ); + } + const getParentDefinition = (state, kind) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + if ( + ((_a = state.prevState) === null || _a === void 0 + ? void 0 + : _a.kind) === kind + ) { + return state.prevState; + } + if ( + ((_c = + (_b = state.prevState) === null || _b === void 0 + ? void 0 + : _b.prevState) === null || _c === void 0 + ? void 0 + : _c.kind) === kind + ) { + return state.prevState.prevState; + } + if ( + ((_f = + (_e = + (_d = state.prevState) === null || _d === void 0 + ? void 0 + : _d.prevState) === null || _e === void 0 + ? void 0 + : _e.prevState) === null || _f === void 0 + ? void 0 + : _f.kind) === kind + ) { + return state.prevState.prevState.prevState; + } + if ( + ((_k = + (_j = + (_h = + (_g = state.prevState) === null || _g === void 0 + ? void 0 + : _g.prevState) === null || _h === void 0 + ? void 0 + : _h.prevState) === null || _j === void 0 + ? void 0 + : _j.prevState) === null || _k === void 0 + ? void 0 + : _k.kind) === kind + ) { + return state.prevState.prevState.prevState.prevState; + } + }; + function getVariableCompletions(queryText, schema, token) { + let variableName = null; + let variableType; + const definitions = Object.create({}); + (0, _parser.runOnlineParser)(queryText, (_, state) => { + var _a; + if ( + (state === null || state === void 0 ? void 0 : state.kind) === + _parser.RuleKinds.VARIABLE && + state.name + ) { + variableName = state.name; + } + if ( + (state === null || state === void 0 ? void 0 : state.kind) === + _parser.RuleKinds.NAMED_TYPE && + variableName + ) { + const parentDefinition = getParentDefinition( + state, + _parser.RuleKinds.TYPE + ); + if ( + parentDefinition === null || parentDefinition === void 0 + ? void 0 + : parentDefinition.type + ) { + variableType = schema.getType( + parentDefinition === null || parentDefinition === void 0 + ? void 0 + : parentDefinition.type + ); + } + } + if (variableName && variableType && !definitions[variableName]) { + const replaceString = + token.string === "$" || + ((_a = + token === null || token === void 0 ? void 0 : token.state) === + null || _a === void 0 + ? void 0 + : _a.kind) === "Variable" + ? variableName + : "$" + variableName; + definitions[variableName] = { + detail: variableType.toString(), + insertText: replaceString, + label: "$" + variableName, + rawInsert: replaceString, + type: variableType, + kind: _types.CompletionItemKind.Variable, + }; + variableName = null; + variableType = null; + } + }); + return (0, _autocompleteUtils.objectValues)(definitions); + } + function getFragmentDefinitions(queryText) { + const fragmentDefs = []; + (0, _parser.runOnlineParser)(queryText, (_, state) => { + if ( + state.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && + state.name && + state.type + ) { + fragmentDefs.push({ + kind: _parser.RuleKinds.FRAGMENT_DEFINITION, + name: { + kind: _graphql.Kind.NAME, + value: state.name, + }, + selectionSet: { + kind: _parser.RuleKinds.SELECTION_SET, + selections: [], + }, + typeCondition: { + kind: _parser.RuleKinds.NAMED_TYPE, + name: { + kind: _graphql.Kind.NAME, + value: state.type, + }, + }, + }); + } + }); + return fragmentDefs; + } + function getSuggestionsForVariableDefinition(token, schema, _kind) { + const inputTypeMap = schema.getTypeMap(); + const inputTypes = (0, _autocompleteUtils.objectValues)( + inputTypeMap + ).filter(_graphql.isInputType); + return (0, _autocompleteUtils.hintList)( + token, + inputTypes.map((type) => ({ + label: type.name, + documentation: + (type === null || type === void 0 + ? void 0 + : type.description) || "", + kind: _types.CompletionItemKind.Variable, + })) + ); + } + function getSuggestionsForDirective(token, state, schema, _kind) { + var _a; + if ( + (_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind + ) { + const directives = schema + .getDirectives() + .filter((directive) => + canUseDirective(state.prevState, directive) + ); + return (0, _autocompleteUtils.hintList)( + token, + directives.map((directive) => ({ + label: directive.name, + documentation: + (directive === null || directive === void 0 + ? void 0 + : directive.description) || "", + kind: _types.CompletionItemKind.Function, + })) + ); + } + return []; + } + function getSuggestionsForDirectiveArguments( + token, + state, + schema, + _kind + ) { + const directive = schema + .getDirectives() + .find((d) => d.name === state.name); + return (0, _autocompleteUtils.hintList)( + token, + (directive === null || directive === void 0 + ? void 0 + : directive.args.map((arg) => ({ + label: arg.name, + documentation: arg.description || "", + kind: _types.CompletionItemKind.Field, + }))) || [] + ); + } + function canUseDirective(state, directive) { + if (!(state === null || state === void 0 ? void 0 : state.kind)) { + return false; + } + const { kind, prevState } = state; + const { locations } = directive; + switch (kind) { + case _parser.RuleKinds.QUERY: + return locations.includes(_graphql.DirectiveLocation.QUERY); + case _parser.RuleKinds.MUTATION: + return locations.includes(_graphql.DirectiveLocation.MUTATION); + case _parser.RuleKinds.SUBSCRIPTION: + return locations.includes( + _graphql.DirectiveLocation.SUBSCRIPTION + ); + case _parser.RuleKinds.FIELD: + case _parser.RuleKinds.ALIASED_FIELD: + return locations.includes(_graphql.DirectiveLocation.FIELD); + case _parser.RuleKinds.FRAGMENT_DEFINITION: + return locations.includes( + _graphql.DirectiveLocation.FRAGMENT_DEFINITION + ); + case _parser.RuleKinds.FRAGMENT_SPREAD: + return locations.includes( + _graphql.DirectiveLocation.FRAGMENT_SPREAD + ); + case _parser.RuleKinds.INLINE_FRAGMENT: + return locations.includes( + _graphql.DirectiveLocation.INLINE_FRAGMENT + ); + case _parser.RuleKinds.SCHEMA_DEF: + return locations.includes(_graphql.DirectiveLocation.SCHEMA); + case _parser.RuleKinds.SCALAR_DEF: + return locations.includes(_graphql.DirectiveLocation.SCALAR); + case _parser.RuleKinds.OBJECT_TYPE_DEF: + return locations.includes(_graphql.DirectiveLocation.OBJECT); + case _parser.RuleKinds.FIELD_DEF: + return locations.includes( + _graphql.DirectiveLocation.FIELD_DEFINITION + ); + case _parser.RuleKinds.INTERFACE_DEF: + return locations.includes(_graphql.DirectiveLocation.INTERFACE); + case _parser.RuleKinds.UNION_DEF: + return locations.includes(_graphql.DirectiveLocation.UNION); + case _parser.RuleKinds.ENUM_DEF: + return locations.includes(_graphql.DirectiveLocation.ENUM); + case _parser.RuleKinds.ENUM_VALUE: + return locations.includes(_graphql.DirectiveLocation.ENUM_VALUE); + case _parser.RuleKinds.INPUT_DEF: + return locations.includes( + _graphql.DirectiveLocation.INPUT_OBJECT + ); + case _parser.RuleKinds.INPUT_VALUE_DEF: + const prevStateKind = + prevState === null || prevState === void 0 + ? void 0 + : prevState.kind; + switch (prevStateKind) { + case _parser.RuleKinds.ARGUMENTS_DEF: + return locations.includes( + _graphql.DirectiveLocation.ARGUMENT_DEFINITION + ); + case _parser.RuleKinds.INPUT_DEF: + return locations.includes( + _graphql.DirectiveLocation.INPUT_FIELD_DEFINITION + ); + } + } + return false; + } + function unwrapType(state) { + if ( + state.prevState && + state.kind && + [ + _parser.RuleKinds.NAMED_TYPE, + _parser.RuleKinds.LIST_TYPE, + _parser.RuleKinds.TYPE, + _parser.RuleKinds.NON_NULL_TYPE, + ].includes(state.kind) + ) { + return unwrapType(state.prevState); + } + return state; } - } - } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - continue; - } - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } - } - if (terminate) { - break; - } - } - if (!level) { - // Didn't find valid underline - return false; - } - const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); - state.line = nextLine + 1; - const token_o = state.push('heading_open', 'h' + String(level), 1); - token_o.markup = String.fromCharCode(marker); - token_o.map = [startLine, state.line]; - const token_i = state.push('inline', '', 0); - token_i.content = content; - token_i.map = [startLine, state.line - 1]; - token_i.children = []; - const token_c = state.push('heading_close', 'h' + String(level), -1); - token_c.markup = String.fromCharCode(marker); - state.parentType = oldParentType; - return true; -} - -// Paragraph - -function paragraph(state, startLine, endLine) { - const terminatorRules = state.md.block.ruler.getRules('paragraph'); - const oldParentType = state.parentType; - let nextLine = startLine + 1; - state.parentType = 'paragraph'; - - // jump line-by-line until empty one or EOF - for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - continue; - } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - continue; - } - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } - } - if (terminate) { - break; - } - } - const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); - state.line = nextLine; - const token_o = state.push('paragraph_open', 'p', 1); - token_o.map = [startLine, state.line]; - const token_i = state.push('inline', '', 0); - token_i.content = content; - token_i.map = [startLine, state.line]; - token_i.children = []; - state.push('paragraph_close', 'p', -1); - state.parentType = oldParentType; - return true; -} - -/** internal - * class ParserBlock - * - * Block-level tokenizer. - **/ - -const _rules$1 = [ -// First 2 params - rule name & source. Secondary array - list of rules, -// which can be terminated by this one. -['table', table, ['paragraph', 'reference']], ['code', code], ['fence', fence, ['paragraph', 'reference', 'blockquote', 'list']], ['blockquote', blockquote, ['paragraph', 'reference', 'blockquote', 'list']], ['hr', hr, ['paragraph', 'reference', 'blockquote', 'list']], ['list', list, ['paragraph', 'reference', 'blockquote']], ['reference', reference], ['html_block', html_block, ['paragraph', 'reference', 'blockquote']], ['heading', heading, ['paragraph', 'reference', 'blockquote']], ['lheading', lheading], ['paragraph', paragraph]]; - -/** - * new ParserBlock() - **/ -function ParserBlock() { - /** - * ParserBlock#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of block rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules$1.length; i++) { - this.ruler.push(_rules$1[i][0], _rules$1[i][1], { - alt: (_rules$1[i][2] || []).slice() - }); - } -} - -// Generate tokens for input range -// -ParserBlock.prototype.tokenize = function (state, startLine, endLine) { - const rules = this.ruler.getRules(''); - const len = rules.length; - const maxNesting = state.md.options.maxNesting; - let line = startLine; - let hasEmptyLines = false; - while (line < endLine) { - state.line = line = state.skipEmptyLines(line); - if (line >= endLine) { - break; - } - - // Termination condition for nested calls. - // Nested calls currently used for blockquotes & lists - if (state.sCount[line] < state.blkIndent) { - break; - } - - // If nesting level exceeded - skip tail to the end. That's not ordinary - // situation and we should not care about content. - if (state.level >= maxNesting) { - state.line = endLine; - break; - } - - // Try all possible rules. - // On success, rule should: - // - // - update `state.line` - // - update `state.tokens` - // - return true - const prevLine = state.line; - let ok = false; - for (let i = 0; i < len; i++) { - ok = rules[i](state, line, endLine, false); - if (ok) { - if (prevLine >= state.line) { - throw new Error("block rule didn't increment state.line"); - } - break; - } - } - - // this can only happen if user disables paragraph rule - if (!ok) throw new Error('none of the block rules matched'); - - // set state.tight if we had an empty line before current tag - // i.e. latest empty line should not count - state.tight = !hasEmptyLines; - - // paragraph might "eat" one newline after it in nested lists - if (state.isEmpty(state.line - 1)) { - hasEmptyLines = true; - } - line = state.line; - if (line < endLine && state.isEmpty(line)) { - hasEmptyLines = true; - line++; - state.line = line; - } - } -}; - -/** - * ParserBlock.parse(str, md, env, outTokens) - * - * Process input string and push block tokens into `outTokens` - **/ -ParserBlock.prototype.parse = function (src, md, env, outTokens) { - if (!src) { - return; - } - const state = new this.State(src, md, env, outTokens); - this.tokenize(state, state.line, state.lineMax); -}; -ParserBlock.prototype.State = StateBlock; - -// Inline parser state - -function StateInline(src, md, env, outTokens) { - this.src = src; - this.env = env; - this.md = md; - this.tokens = outTokens; - this.tokens_meta = Array(outTokens.length); - this.pos = 0; - this.posMax = this.src.length; - this.level = 0; - this.pending = ''; - this.pendingLevel = 0; - - // Stores { start: end } pairs. Useful for backtrack - // optimization of pairs parse (emphasis, strikes). - this.cache = {}; - - // List of emphasis-like delimiters for current tag - this.delimiters = []; - - // Stack of delimiter lists for upper level tags - this._prev_delimiters = []; - - // backtick length => last seen position - this.backticks = {}; - this.backticksScanned = false; - - // Counter used to disable inline linkify-it execution - // inside and markdown links - this.linkLevel = 0; -} - -// Flush pending text -// -StateInline.prototype.pushPending = function () { - const token = new Token('text', '', 0); - token.content = this.pending; - token.level = this.pendingLevel; - this.tokens.push(token); - this.pending = ''; - return token; -}; - -// Push new token to "stream". -// If pending text exists - flush it as text token -// -StateInline.prototype.push = function (type, tag, nesting) { - if (this.pending) { - this.pushPending(); - } - const token = new Token(type, tag, nesting); - let token_meta = null; - if (nesting < 0) { - // closing tag - this.level--; - this.delimiters = this._prev_delimiters.pop(); - } - token.level = this.level; - if (nesting > 0) { - // opening tag - this.level++; - this._prev_delimiters.push(this.delimiters); - this.delimiters = []; - token_meta = { - delimiters: this.delimiters - }; - } - this.pendingLevel = this.level; - this.tokens.push(token); - this.tokens_meta.push(token_meta); - return token; -}; - -// Scan a sequence of emphasis-like markers, and determine whether -// it can start an emphasis sequence or end an emphasis sequence. -// -// - start - position to scan from (it should point at a valid marker); -// - canSplitWord - determine if these markers can be found inside a word -// -StateInline.prototype.scanDelims = function (start, canSplitWord) { - const max = this.posMax; - const marker = this.src.charCodeAt(start); - - // treat beginning of the line as a whitespace - const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; - let pos = start; - while (pos < max && this.src.charCodeAt(pos) === marker) { - pos++; - } - const count = pos - start; - - // treat end of the line as a whitespace - const nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; - const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); - const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); - const isLastWhiteSpace = isWhiteSpace(lastChar); - const isNextWhiteSpace = isWhiteSpace(nextChar); - const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar); - const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar); - const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar); - const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar); - return { - can_open, - can_close, - length: count - }; -}; - -// re-export Token class to use in block rules -StateInline.prototype.Token = Token; - -// Skip text characters for text token, place those to pending buffer -// and increment current pos - -// Rule to skip pure text -// '{}$%@~+=:' reserved for extentions - -// !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ - -// !!!! Don't confuse with "Markdown ASCII Punctuation" chars -// http://spec.commonmark.org/0.15/#ascii-punctuation-character -function isTerminatorChar(ch) { - switch (ch) { - case 0x0A /* \n */: - case 0x21 /* ! */: - case 0x23 /* # */: - case 0x24 /* $ */: - case 0x25 /* % */: - case 0x26 /* & */: - case 0x2A /* * */: - case 0x2B /* + */: - case 0x2D /* - */: - case 0x3A /* : */: - case 0x3C /* < */: - case 0x3D /* = */: - case 0x3E /* > */: - case 0x40 /* @ */: - case 0x5B /* [ */: - case 0x5C /* \ */: - case 0x5D /* ] */: - case 0x5E /* ^ */: - case 0x5F /* _ */: - case 0x60 /* ` */: - case 0x7B /* { */: - case 0x7D /* } */: - case 0x7E /* ~ */: - return true; - default: - return false; - } -} -function text(state, silent) { - let pos = state.pos; - while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) { - pos++; - } - if (pos === state.pos) { - return false; - } - if (!silent) { - state.pending += state.src.slice(state.pos, pos); - } - state.pos = pos; - return true; -} - -// Alternative implementation, for memory. -// -// It costs 10% of performance, but allows extend terminators list, if place it -// to `ParserInline` property. Probably, will switch to it sometime, such -// flexibility required. - -/* -var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; - -module.exports = function text(state, silent) { - var pos = state.pos, - idx = state.src.slice(pos).search(TERMINATOR_RE); - - // first char is terminator -> empty text - if (idx === 0) { return false; } - - // no terminator -> text till end of string - if (idx < 0) { - if (!silent) { state.pending += state.src.slice(pos); } - state.pos = state.src.length; - return true; - } - - if (!silent) { state.pending += state.src.slice(pos, pos + idx); } - - state.pos += idx; - - return true; -}; */ - -// Process links like https://example.org/ - -// RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) -const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; -function linkify(state, silent) { - if (!state.md.options.linkify) return false; - if (state.linkLevel > 0) return false; - const pos = state.pos; - const max = state.posMax; - if (pos + 3 > max) return false; - if (state.src.charCodeAt(pos) !== 0x3A /* : */) return false; - if (state.src.charCodeAt(pos + 1) !== 0x2F /* / */) return false; - if (state.src.charCodeAt(pos + 2) !== 0x2F /* / */) return false; - const match = state.pending.match(SCHEME_RE); - if (!match) return false; - const proto = match[1]; - const link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length)); - if (!link) return false; - let url = link.url; - - // invalid link, but still detected by linkify somehow; - // need to check to prevent infinite loop below - if (url.length <= proto.length) return false; - - // disallow '*' at the end of the link (conflicts with emphasis) - url = url.replace(/\*+$/, ''); - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) return false; - if (!silent) { - state.pending = state.pending.slice(0, -proto.length); - const token_o = state.push('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.markup = 'linkify'; - token_o.info = 'auto'; - const token_t = state.push('text', '', 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push('link_close', 'a', -1); - token_c.markup = 'linkify'; - token_c.info = 'auto'; - } - state.pos += url.length - proto.length; - return true; -} -// Proceess '\n' + /***/ + }, -function newline(state, silent) { - let pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x0A /* \n */) { - return false; - } - const pmax = state.pending.length - 1; - const max = state.posMax; - - // ' \n' -> hardbreak - // Lookup in pending chars is bad practice! Don't copy to other rules! - // Pending string is stored in concat mode, indexed lookups will cause - // convertion to flat mode. - if (!silent) { - if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { - if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { - // Find whitespaces tail of pending chars. - let ws = pmax - 1; - while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) ws--; - state.pending = state.pending.slice(0, ws); - state.push('hardbreak', 'br', 0); - } else { - state.pending = state.pending.slice(0, -1); - state.push('softbreak', 'br', 0); - } - } else { - state.push('softbreak', 'br', 0); - } - } - pos++; + /***/ "../../graphql-language-service/esm/interface/getDefinition.js": + /*!*********************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getDefinition.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.LANGUAGE = void 0; + exports.getDefinitionQueryResultForArgument = + getDefinitionQueryResultForArgument; + exports.getDefinitionQueryResultForDefinitionNode = + getDefinitionQueryResultForDefinitionNode; + exports.getDefinitionQueryResultForField = + getDefinitionQueryResultForField; + exports.getDefinitionQueryResultForFragmentSpread = + getDefinitionQueryResultForFragmentSpread; + exports.getDefinitionQueryResultForNamedType = + getDefinitionQueryResultForNamedType; + var _utils = __webpack_require__( + /*! ../utils */ "../../graphql-language-service/esm/utils/index.js" + ); + var __awaiter = + (void 0 && (void 0).__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; + const LANGUAGE = (exports.LANGUAGE = "GraphQL"); + function assert(value, message) { + if (!value) { + throw new Error(message); + } + } + function getRange(text, node) { + const location = node.loc; + assert(location, "Expected ASTNode to have a location."); + return (0, _utils.locToRange)(text, location); + } + function getPosition(text, node) { + const location = node.loc; + assert(location, "Expected ASTNode to have a location."); + return (0, _utils.offsetToPosition)(text, location.start); + } + function getDefinitionQueryResultForNamedType( + text, + node, + dependencies + ) { + return __awaiter(this, void 0, void 0, function* () { + const name = node.name.value; + const defNodes = dependencies.filter( + ({ definition }) => + definition.name && definition.name.value === name + ); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL type ${name}`); + } + const definitions = defNodes.map( + ({ filePath, content, definition }) => + getDefinitionForNodeDefinition( + filePath || "", + content, + definition + ) + ); + return { + definitions, + queryRange: definitions.map((_) => getRange(text, node)), + printedName: name, + }; + }); + } + function getDefinitionQueryResultForField( + fieldName, + typeName, + dependencies + ) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const defNodes = dependencies.filter( + ({ definition }) => + definition.name && definition.name.value === typeName + ); + if (defNodes.length === 0) { + throw new Error( + `Definition not found for GraphQL type ${typeName}` + ); + } + const definitions = []; + for (const { filePath, content, definition } of defNodes) { + const fieldDefinition = + (_a = definition.fields) === null || _a === void 0 + ? void 0 + : _a.find((item) => item.name.value === fieldName); + if (fieldDefinition == null) { + continue; + } + definitions.push( + getDefinitionForFieldDefinition( + filePath || "", + content, + fieldDefinition + ) + ); + } + return { + definitions, + queryRange: [], + printedName: [typeName, fieldName].join("."), + }; + }); + } + function getDefinitionQueryResultForArgument( + argumentName, + fieldName, + typeName, + dependencies + ) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const definitions = []; + for (const { filePath, content, definition } of dependencies) { + const argDefinition = + (_c = + (_b = + (_a = definition.fields) === null || _a === void 0 + ? void 0 + : _a.find((item) => item.name.value === fieldName)) === + null || _b === void 0 + ? void 0 + : _b.arguments) === null || _c === void 0 + ? void 0 + : _c.find((item) => item.name.value === argumentName); + if (argDefinition == null) { + continue; + } + definitions.push( + getDefinitionForArgumentDefinition( + filePath || "", + content, + argDefinition + ) + ); + } + return { + definitions, + queryRange: [], + printedName: `${[typeName, fieldName].join( + "." + )}(${argumentName})`, + }; + }); + } + function getDefinitionQueryResultForFragmentSpread( + text, + fragment, + dependencies + ) { + return __awaiter(this, void 0, void 0, function* () { + const name = fragment.name.value; + const defNodes = dependencies.filter( + ({ definition }) => definition.name.value === name + ); + if (defNodes.length === 0) { + throw new Error( + `Definition not found for GraphQL fragment ${name}` + ); + } + const definitions = defNodes.map( + ({ filePath, content, definition }) => + getDefinitionForFragmentDefinition( + filePath || "", + content, + definition + ) + ); + return { + definitions, + queryRange: definitions.map((_) => getRange(text, fragment)), + printedName: name, + }; + }); + } + function getDefinitionQueryResultForDefinitionNode( + path, + text, + definition + ) { + var _a; + return { + definitions: [ + getDefinitionForFragmentDefinition(path, text, definition), + ], + queryRange: definition.name + ? [getRange(text, definition.name)] + : [], + printedName: + (_a = definition.name) === null || _a === void 0 + ? void 0 + : _a.value, + }; + } + function getDefinitionForFragmentDefinition(path, text, definition) { + const { name } = definition; + if (!name) { + throw new Error("Expected ASTNode to have a Name."); + } + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || "", + language: LANGUAGE, + projectRoot: path, + }; + } + function getDefinitionForNodeDefinition(path, text, definition) { + const { name } = definition; + assert(name, "Expected ASTNode to have a Name."); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || "", + language: LANGUAGE, + projectRoot: path, + }; + } + function getDefinitionForFieldDefinition(path, text, definition) { + const { name } = definition; + assert(name, "Expected ASTNode to have a Name."); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || "", + language: LANGUAGE, + projectRoot: path, + }; + } + function getDefinitionForArgumentDefinition(path, text, definition) { + const { name } = definition; + assert(name, "Expected ASTNode to have a Name."); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || "", + language: LANGUAGE, + projectRoot: path, + }; + } - // skip heading spaces for next line - while (pos < max && isSpace(state.src.charCodeAt(pos))) { - pos++; - } - state.pos = pos; - return true; -} - -// Process escaped chars and hardbreaks - -const ESCAPED = []; -for (let i = 0; i < 256; i++) { - ESCAPED.push(0); -} -'\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'.split('').forEach(function (ch) { - ESCAPED[ch.charCodeAt(0)] = 1; -}); -function escape(state, silent) { - let pos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(pos) !== 0x5C /* \ */) return false; - pos++; - - // '\' at the end of the inline block - if (pos >= max) return false; - let ch1 = state.src.charCodeAt(pos); - if (ch1 === 0x0A) { - if (!silent) { - state.push('hardbreak', 'br', 0); - } - pos++; - // skip leading whitespaces from next line - while (pos < max) { - ch1 = state.src.charCodeAt(pos); - if (!isSpace(ch1)) break; - pos++; - } - state.pos = pos; - return true; - } - let escapedStr = state.src[pos]; - if (ch1 >= 0xD800 && ch1 <= 0xDBFF && pos + 1 < max) { - const ch2 = state.src.charCodeAt(pos + 1); - if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { - escapedStr += state.src[pos + 1]; - pos++; - } - } - const origStr = '\\' + escapedStr; - if (!silent) { - const token = state.push('text_special', '', 0); - if (ch1 < 256 && ESCAPED[ch1] !== 0) { - token.content = escapedStr; - } else { - token.content = origStr; - } - token.markup = origStr; - token.info = 'escape'; - } - state.pos = pos + 1; - return true; -} + /***/ + }, -// Parse backticks + /***/ "../../graphql-language-service/esm/interface/getDiagnostics.js": + /*!**********************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getDiagnostics.js ***! + \**********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.SEVERITY = exports.DIAGNOSTIC_SEVERITY = void 0; + exports.getDiagnostics = getDiagnostics; + exports.getRange = getRange; + exports.validateQuery = validateQuery; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _parser = __webpack_require__( + /*! ../parser */ "../../graphql-language-service/esm/parser/index.js" + ); + var _utils = __webpack_require__( + /*! ../utils */ "../../graphql-language-service/esm/utils/index.js" + ); + const SEVERITY = (exports.SEVERITY = { + Error: "Error", + Warning: "Warning", + Information: "Information", + Hint: "Hint", + }); + const DIAGNOSTIC_SEVERITY = (exports.DIAGNOSTIC_SEVERITY = { + [SEVERITY.Error]: 1, + [SEVERITY.Warning]: 2, + [SEVERITY.Information]: 3, + [SEVERITY.Hint]: 4, + }); + const invariant = (condition, message) => { + if (!condition) { + throw new Error(message); + } + }; + function getDiagnostics( + query, + schema = null, + customRules, + isRelayCompatMode, + externalFragments + ) { + var _a, _b; + let ast = null; + let fragments = ""; + if (externalFragments) { + fragments = + typeof externalFragments === "string" + ? externalFragments + : externalFragments.reduce( + (acc, node) => acc + (0, _graphql.print)(node) + "\n\n", + "" + ); + } + const enhancedQuery = fragments ? `${query}\n\n${fragments}` : query; + try { + ast = (0, _graphql.parse)(enhancedQuery); + } catch (error) { + if (error instanceof _graphql.GraphQLError) { + const range = getRange( + (_b = + (_a = error.locations) === null || _a === void 0 + ? void 0 + : _a[0]) !== null && _b !== void 0 + ? _b + : { + line: 0, + column: 0, + }, + enhancedQuery + ); + return [ + { + severity: DIAGNOSTIC_SEVERITY.Error, + message: error.message, + source: "GraphQL: Syntax", + range, + }, + ]; + } + throw error; + } + return validateQuery(ast, schema, customRules, isRelayCompatMode); + } + function validateQuery( + ast, + schema = null, + customRules, + isRelayCompatMode + ) { + if (!schema) { + return []; + } + const validationErrorAnnotations = (0, + _utils.validateWithCustomRules)( + schema, + ast, + customRules, + isRelayCompatMode + ).flatMap((error) => + annotations(error, DIAGNOSTIC_SEVERITY.Error, "Validation") + ); + const deprecationWarningAnnotations = (0, _graphql.validate)( + schema, + ast, + [_graphql.NoDeprecatedCustomRule] + ).flatMap((error) => + annotations(error, DIAGNOSTIC_SEVERITY.Warning, "Deprecation") + ); + return validationErrorAnnotations.concat( + deprecationWarningAnnotations + ); + } + function annotations(error, severity, type) { + if (!error.nodes) { + return []; + } + const highlightedNodes = []; + for (const [i, node] of error.nodes.entries()) { + const highlightNode = + node.kind !== "Variable" && + "name" in node && + node.name !== undefined + ? node.name + : "variable" in node && node.variable !== undefined + ? node.variable + : node; + if (highlightNode) { + invariant( + error.locations, + "GraphQL validation error requires locations." + ); + const loc = error.locations[i]; + const highlightLoc = getLocation(highlightNode); + const end = loc.column + (highlightLoc.end - highlightLoc.start); + highlightedNodes.push({ + source: `GraphQL: ${type}`, + message: error.message, + severity, + range: new _utils.Range( + new _utils.Position(loc.line - 1, loc.column - 1), + new _utils.Position(loc.line - 1, end) + ), + }); + } + } + return highlightedNodes; + } + function getRange(location, queryText) { + const parser = (0, _parser.onlineParser)(); + const state = parser.startState(); + const lines = queryText.split("\n"); + invariant( + lines.length >= location.line, + "Query text must have more lines than where the error happened" + ); + let stream = null; + for (let i = 0; i < location.line; i++) { + stream = new _parser.CharacterStream(lines[i]); + while (!stream.eol()) { + const style = parser.token(stream, state); + if (style === "invalidchar") { + break; + } + } + } + invariant(stream, "Expected Parser stream to be available."); + const line = location.line - 1; + const start = stream.getStartOfToken(); + const end = stream.getCurrentPosition(); + return new _utils.Range( + new _utils.Position(line, start), + new _utils.Position(line, end) + ); + } + function getLocation(node) { + const typeCastedNode = node; + const location = typeCastedNode.loc; + invariant(location, "Expected ASTNode to have a location."); + return location; + } -function backtick(state, silent) { - let pos = state.pos; - const ch = state.src.charCodeAt(pos); - if (ch !== 0x60 /* ` */) { - return false; - } - const start = pos; - pos++; - const max = state.posMax; + /***/ + }, - // scan marker length - while (pos < max && state.src.charCodeAt(pos) === 0x60 /* ` */) { - pos++; - } - const marker = state.src.slice(start, pos); - const openerLength = marker.length; - if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) { - if (!silent) state.pending += marker; - state.pos += openerLength; - return true; - } - let matchEnd = pos; - let matchStart; + /***/ "../../graphql-language-service/esm/interface/getHoverInformation.js": + /*!***************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getHoverInformation.js ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getHoverInformation = getHoverInformation; + exports.renderArg = renderArg; + exports.renderDirective = renderDirective; + exports.renderEnumValue = renderEnumValue; + exports.renderField = renderField; + exports.renderType = renderType; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _parser = __webpack_require__( + /*! ../parser */ "../../graphql-language-service/esm/parser/index.js" + ); + function getHoverInformation( + schema, + queryText, + cursor, + contextToken, + config + ) { + const options = Object.assign(Object.assign({}, config), { + schema, + }); + const context = (0, _parser.getContextAtPosition)( + queryText, + cursor, + schema, + contextToken + ); + if (!context) { + return ""; + } + const { typeInfo, token } = context; + const { kind, step } = token.state; + if ( + (kind === "Field" && step === 0 && typeInfo.fieldDef) || + (kind === "AliasedField" && step === 2 && typeInfo.fieldDef) || + (kind === "ObjectField" && step === 0 && typeInfo.fieldDef) + ) { + const into = []; + renderMdCodeStart(into, options); + renderField(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.fieldDef); + return into.join("").trim(); + } + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + const into = []; + renderMdCodeStart(into, options); + renderDirective(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.directiveDef); + return into.join("").trim(); + } + if (kind === "Variable" && typeInfo.type) { + const into = []; + renderMdCodeStart(into, options); + renderType(into, typeInfo, options, typeInfo.type); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.type); + return into.join("").trim(); + } + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + const into = []; + renderMdCodeStart(into, options); + renderArg(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.argDef); + return into.join("").trim(); + } + if ( + kind === "EnumValue" && + typeInfo.enumValue && + "description" in typeInfo.enumValue + ) { + const into = []; + renderMdCodeStart(into, options); + renderEnumValue(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.enumValue); + return into.join("").trim(); + } + if ( + kind === "NamedType" && + typeInfo.type && + "description" in typeInfo.type + ) { + const into = []; + renderMdCodeStart(into, options); + renderType(into, typeInfo, options, typeInfo.type); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.type); + return into.join("").trim(); + } + return ""; + } + function renderMdCodeStart(into, options) { + if (options.useMarkdown) { + text(into, "```graphql\n"); + } + } + function renderMdCodeEnd(into, options) { + if (options.useMarkdown) { + text(into, "\n```"); + } + } + function renderField(into, typeInfo, options) { + renderQualifiedField(into, typeInfo, options); + renderTypeAnnotation(into, typeInfo, options, typeInfo.type); + } + function renderQualifiedField(into, typeInfo, options) { + if (!typeInfo.fieldDef) { + return; + } + const fieldName = typeInfo.fieldDef.name; + if (fieldName.slice(0, 2) !== "__") { + renderType(into, typeInfo, options, typeInfo.parentType); + text(into, "."); + } + text(into, fieldName); + } + function renderDirective(into, typeInfo, _options) { + if (!typeInfo.directiveDef) { + return; + } + const name = "@" + typeInfo.directiveDef.name; + text(into, name); + } + function renderArg(into, typeInfo, options) { + if (typeInfo.directiveDef) { + renderDirective(into, typeInfo, options); + } else if (typeInfo.fieldDef) { + renderQualifiedField(into, typeInfo, options); + } + if (!typeInfo.argDef) { + return; + } + const { name } = typeInfo.argDef; + text(into, "("); + text(into, name); + renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); + text(into, ")"); + } + function renderTypeAnnotation(into, typeInfo, options, t) { + text(into, ": "); + renderType(into, typeInfo, options, t); + } + function renderEnumValue(into, typeInfo, options) { + if (!typeInfo.enumValue) { + return; + } + const { name } = typeInfo.enumValue; + renderType(into, typeInfo, options, typeInfo.inputType); + text(into, "."); + text(into, name); + } + function renderType(into, typeInfo, options, t) { + if (!t) { + return; + } + if (t instanceof _graphql.GraphQLNonNull) { + renderType(into, typeInfo, options, t.ofType); + text(into, "!"); + } else if (t instanceof _graphql.GraphQLList) { + text(into, "["); + renderType(into, typeInfo, options, t.ofType); + text(into, "]"); + } else { + text(into, t.name); + } + } + function renderDescription(into, options, def) { + if (!def) { + return; + } + const description = + typeof def.description === "string" ? def.description : null; + if (description) { + text(into, "\n\n"); + text(into, description); + } + renderDeprecation(into, options, def); + } + function renderDeprecation(into, _options, def) { + if (!def) { + return; + } + const reason = def.deprecationReason || null; + if (!reason) { + return; + } + text(into, "\n\n"); + text(into, "Deprecated: "); + text(into, reason); + } + function text(into, content) { + into.push(content); + } - // Nothing found in the cache, scan until the end of the line (or until marker is found) - while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { - matchEnd = matchStart + 1; + /***/ + }, - // scan marker length - while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60 /* ` */) { - matchEnd++; - } - const closerLength = matchEnd - matchStart; - if (closerLength === openerLength) { - // Found matching closer length. - if (!silent) { - const token = state.push('code_inline', 'code', 0); - token.markup = marker; - token.content = state.src.slice(pos, matchStart).replace(/\n/g, ' ').replace(/^ (.+) $/, '$1'); - } - state.pos = matchEnd; - return true; - } + /***/ "../../graphql-language-service/esm/interface/getOutline.js": + /*!******************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getOutline.js ***! + \******************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getOutline = getOutline; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _utils = __webpack_require__( + /*! ../utils */ "../../graphql-language-service/esm/utils/index.js" + ); + const { INLINE_FRAGMENT } = _graphql.Kind; + const OUTLINEABLE_KINDS = { + Field: true, + OperationDefinition: true, + Document: true, + SelectionSet: true, + Name: true, + FragmentDefinition: true, + FragmentSpread: true, + InlineFragment: true, + ObjectTypeDefinition: true, + InputObjectTypeDefinition: true, + InterfaceTypeDefinition: true, + EnumTypeDefinition: true, + EnumValueDefinition: true, + InputValueDefinition: true, + FieldDefinition: true, + }; + function getOutline(documentText) { + let ast; + try { + ast = (0, _graphql.parse)(documentText); + } catch (_a) { + return null; + } + const visitorFns = outlineTreeConverter(documentText); + const outlineTrees = (0, _graphql.visit)(ast, { + leave(node) { + if (visitorFns !== undefined && node.kind in visitorFns) { + return visitorFns[node.kind](node); + } + return null; + }, + }); + return { + outlineTrees, + }; + } + function outlineTreeConverter(docText) { + const meta = (node) => { + return { + representativeName: node.name, + startPosition: (0, _utils.offsetToPosition)( + docText, + node.loc.start + ), + endPosition: (0, _utils.offsetToPosition)(docText, node.loc.end), + kind: node.kind, + children: + node.selectionSet || + node.fields || + node.values || + node.arguments || + [], + }; + }; + return { + Field(node) { + const tokenizedText = node.alias + ? [buildToken("plain", node.alias), buildToken("plain", ": ")] + : []; + tokenizedText.push(buildToken("plain", node.name)); + return Object.assign( + { + tokenizedText, + }, + meta(node) + ); + }, + OperationDefinition: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("keyword", node.operation), + buildToken("whitespace", " "), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + Document: (node) => node.definitions, + SelectionSet: (node) => + concatMap(node.selections, (child) => { + return child.kind === INLINE_FRAGMENT + ? child.selectionSet + : child; + }), + Name: (node) => node.value, + FragmentDefinition: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("keyword", "fragment"), + buildToken("whitespace", " "), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + InterfaceTypeDefinition: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("keyword", "interface"), + buildToken("whitespace", " "), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + EnumTypeDefinition: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("keyword", "enum"), + buildToken("whitespace", " "), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + EnumValueDefinition: (node) => + Object.assign( + { + tokenizedText: [buildToken("plain", node.name)], + }, + meta(node) + ), + ObjectTypeDefinition: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("keyword", "type"), + buildToken("whitespace", " "), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + InputObjectTypeDefinition: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("keyword", "input"), + buildToken("whitespace", " "), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + FragmentSpread: (node) => + Object.assign( + { + tokenizedText: [ + buildToken("plain", "..."), + buildToken("class-name", node.name), + ], + }, + meta(node) + ), + InputValueDefinition(node) { + return Object.assign( + { + tokenizedText: [buildToken("plain", node.name)], + }, + meta(node) + ); + }, + FieldDefinition(node) { + return Object.assign( + { + tokenizedText: [buildToken("plain", node.name)], + }, + meta(node) + ); + }, + InlineFragment: (node) => node.selectionSet, + }; + } + function buildToken(kind, value) { + return { + kind, + value, + }; + } + function concatMap(arr, fn) { + const res = []; + for (let i = 0; i < arr.length; i++) { + const x = fn(arr[i], i); + if (Array.isArray(x)) { + res.push(...x); + } else { + res.push(x); + } + } + return res; + } - // Some different length found, put it in cache as upper limit of where closer can be found - state.backticks[closerLength] = matchStart; - } + /***/ + }, - // Scanned through the end, didn't find anything - state.backticksScanned = true; - if (!silent) state.pending += marker; - state.pos += openerLength; - return true; -} - -// ~~strike through~~ -// - -// Insert each marker as a separate text token, and add it to delimiter list -// -function strikethrough_tokenize(state, silent) { - const start = state.pos; - const marker = state.src.charCodeAt(start); - if (silent) { - return false; - } - if (marker !== 0x7E /* ~ */) { - return false; - } - const scanned = state.scanDelims(state.pos, true); - let len = scanned.length; - const ch = String.fromCharCode(marker); - if (len < 2) { - return false; - } - let token; - if (len % 2) { - token = state.push('text', '', 0); - token.content = ch; - len--; - } - for (let i = 0; i < len; i += 2) { - token = state.push('text', '', 0); - token.content = ch + ch; - state.delimiters.push({ - marker, - length: 0, - // disable "rule of 3" length checks meant for emphasis - token: state.tokens.length - 1, - end: -1, - open: scanned.can_open, - close: scanned.can_close - }); - } - state.pos += scanned.length; - return true; -} -function postProcess$1(state, delimiters) { - let token; - const loneMarkers = []; - const max = delimiters.length; - for (let i = 0; i < max; i++) { - const startDelim = delimiters[i]; - if (startDelim.marker !== 0x7E /* ~ */) { - continue; - } - if (startDelim.end === -1) { - continue; - } - const endDelim = delimiters[startDelim.end]; - token = state.tokens[startDelim.token]; - token.type = 's_open'; - token.tag = 's'; - token.nesting = 1; - token.markup = '~~'; - token.content = ''; - token = state.tokens[endDelim.token]; - token.type = 's_close'; - token.tag = 's'; - token.nesting = -1; - token.markup = '~~'; - token.content = ''; - if (state.tokens[endDelim.token - 1].type === 'text' && state.tokens[endDelim.token - 1].content === '~') { - loneMarkers.push(endDelim.token - 1); - } - } + /***/ "../../graphql-language-service/esm/interface/index.js": + /*!*************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/index.js ***! + \*************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + var _exportNames = { + getOutline: true, + getHoverInformation: true, + }; + Object.defineProperty(exports, "getHoverInformation", { + enumerable: true, + get: function () { + return _getHoverInformation.getHoverInformation; + }, + }); + Object.defineProperty(exports, "getOutline", { + enumerable: true, + get: function () { + return _getOutline.getOutline; + }, + }); + var _autocompleteUtils = __webpack_require__( + /*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js" + ); + Object.keys(_autocompleteUtils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _autocompleteUtils[key]) + return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _autocompleteUtils[key]; + }, + }); + }); + var _getAutocompleteSuggestions = __webpack_require__( + /*! ./getAutocompleteSuggestions */ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js" + ); + Object.keys(_getAutocompleteSuggestions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if ( + key in exports && + exports[key] === _getAutocompleteSuggestions[key] + ) + return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getAutocompleteSuggestions[key]; + }, + }); + }); + var _getDefinition = __webpack_require__( + /*! ./getDefinition */ "../../graphql-language-service/esm/interface/getDefinition.js" + ); + Object.keys(_getDefinition).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getDefinition[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getDefinition[key]; + }, + }); + }); + var _getDiagnostics = __webpack_require__( + /*! ./getDiagnostics */ "../../graphql-language-service/esm/interface/getDiagnostics.js" + ); + Object.keys(_getDiagnostics).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getDiagnostics[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getDiagnostics[key]; + }, + }); + }); + var _getOutline = __webpack_require__( + /*! ./getOutline */ "../../graphql-language-service/esm/interface/getOutline.js" + ); + var _getHoverInformation = __webpack_require__( + /*! ./getHoverInformation */ "../../graphql-language-service/esm/interface/getHoverInformation.js" + ); - // If a marker sequence has an odd number of characters, it's splitted - // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the - // start of the sequence. - // - // So, we have to move all those markers after subsequent s_close tags. - // - while (loneMarkers.length) { - const i = loneMarkers.pop(); - let j = i + 1; - while (j < state.tokens.length && state.tokens[j].type === 's_close') { - j++; - } - j--; - if (i !== j) { - token = state.tokens[j]; - state.tokens[j] = state.tokens[i]; - state.tokens[i] = token; - } - } -} - -// Walk through delimiter list and replace text tokens with tags -// -function strikethrough_postProcess(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - postProcess$1(state, state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - postProcess$1(state, tokens_meta[curr].delimiters); - } - } -} -var r_strikethrough = { - tokenize: strikethrough_tokenize, - postProcess: strikethrough_postProcess -}; + /***/ + }, -// Process *this* and _that_ -// + /***/ "../../graphql-language-service/esm/parser/CharacterStream.js": + /*!********************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/CharacterStream.js ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = void 0; + class CharacterStream { + constructor(sourceText) { + this._start = 0; + this._pos = 0; + this.getStartOfToken = () => this._start; + this.getCurrentPosition = () => this._pos; + this.eol = () => this._sourceText.length === this._pos; + this.sol = () => this._pos === 0; + this.peek = () => { + return this._sourceText.charAt(this._pos) || null; + }; + this.next = () => { + const char = this._sourceText.charAt(this._pos); + this._pos++; + return char; + }; + this.eat = (pattern) => { + const isMatched = this._testNextCharacter(pattern); + if (isMatched) { + this._start = this._pos; + this._pos++; + return this._sourceText.charAt(this._pos - 1); + } + return undefined; + }; + this.eatWhile = (match) => { + let isMatched = this._testNextCharacter(match); + let didEat = false; + if (isMatched) { + didEat = isMatched; + this._start = this._pos; + } + while (isMatched) { + this._pos++; + isMatched = this._testNextCharacter(match); + didEat = true; + } + return didEat; + }; + this.eatSpace = () => this.eatWhile(/[\s\u00a0]/); + this.skipToEnd = () => { + this._pos = this._sourceText.length; + }; + this.skipTo = (position) => { + this._pos = position; + }; + this.match = (pattern, consume = true, caseFold = false) => { + let token = null; + let match = null; + if (typeof pattern === "string") { + const regex = new RegExp(pattern, caseFold ? "i" : "g"); + match = regex.test( + this._sourceText.slice(this._pos, this._pos + pattern.length) + ); + token = pattern; + } else if (pattern instanceof RegExp) { + match = this._sourceText.slice(this._pos).match(pattern); + token = match === null || match === void 0 ? void 0 : match[0]; + } + if ( + match != null && + (typeof pattern === "string" || + (match instanceof Array && + this._sourceText.startsWith(match[0], this._pos))) + ) { + if (consume) { + this._start = this._pos; + if (token && token.length) { + this._pos += token.length; + } + } + return match; + } + return false; + }; + this.backUp = (num) => { + this._pos -= num; + }; + this.column = () => this._pos; + this.indentation = () => { + const match = this._sourceText.match(/\s*/); + let indent = 0; + if (match && match.length !== 0) { + const whiteSpaces = match[0]; + let pos = 0; + while (whiteSpaces.length > pos) { + if (whiteSpaces.charCodeAt(pos) === 9) { + indent += 2; + } else { + indent++; + } + pos++; + } + } + return indent; + }; + this.current = () => this._sourceText.slice(this._start, this._pos); + this._sourceText = sourceText; + } + _testNextCharacter(pattern) { + const character = this._sourceText.charAt(this._pos); + let isMatched = false; + if (typeof pattern === "string") { + isMatched = character === pattern; + } else { + isMatched = + pattern instanceof RegExp + ? pattern.test(character) + : pattern(character); + } + return isMatched; + } + } + exports["default"] = CharacterStream; -// Insert each marker as a separate text token, and add it to delimiter list -// -function emphasis_tokenize(state, silent) { - const start = state.pos; - const marker = state.src.charCodeAt(start); - if (silent) { - return false; - } - if (marker !== 0x5F /* _ */ && marker !== 0x2A /* * */) { - return false; - } - const scanned = state.scanDelims(state.pos, marker === 0x2A); - for (let i = 0; i < scanned.length; i++) { - const token = state.push('text', '', 0); - token.content = String.fromCharCode(marker); - state.delimiters.push({ - // Char code of the starting marker (number). - // - marker, - // Total length of these series of delimiters. - // - length: scanned.length, - // A position of the token this delimiter corresponds to. - // - token: state.tokens.length - 1, - // If this delimiter is matched as a valid opener, `end` will be - // equal to its position, otherwise it's `-1`. - // - end: -1, - // Boolean flags that determine if this delimiter could open or close - // an emphasis. - // - open: scanned.can_open, - close: scanned.can_close - }); - } - state.pos += scanned.length; - return true; -} -function postProcess(state, delimiters) { - const max = delimiters.length; - for (let i = max - 1; i >= 0; i--) { - const startDelim = delimiters[i]; - if (startDelim.marker !== 0x5F /* _ */ && startDelim.marker !== 0x2A /* * */) { - continue; - } + /***/ + }, - // Process only opening markers - if (startDelim.end === -1) { - continue; - } - const endDelim = delimiters[startDelim.end]; - - // If the previous delimiter has the same marker and is adjacent to this one, - // merge those into one strong delimiter. - // - // `whatever` -> `whatever` - // - const isStrong = i > 0 && delimiters[i - 1].end === startDelim.end + 1 && - // check that first two markers match and adjacent - delimiters[i - 1].marker === startDelim.marker && delimiters[i - 1].token === startDelim.token - 1 && - // check that last two markers are adjacent (we can safely assume they match) - delimiters[startDelim.end + 1].token === endDelim.token + 1; - const ch = String.fromCharCode(startDelim.marker); - const token_o = state.tokens[startDelim.token]; - token_o.type = isStrong ? 'strong_open' : 'em_open'; - token_o.tag = isStrong ? 'strong' : 'em'; - token_o.nesting = 1; - token_o.markup = isStrong ? ch + ch : ch; - token_o.content = ''; - const token_c = state.tokens[endDelim.token]; - token_c.type = isStrong ? 'strong_close' : 'em_close'; - token_c.tag = isStrong ? 'strong' : 'em'; - token_c.nesting = -1; - token_c.markup = isStrong ? ch + ch : ch; - token_c.content = ''; - if (isStrong) { - state.tokens[delimiters[i - 1].token].content = ''; - state.tokens[delimiters[startDelim.end + 1].token].content = ''; - i--; - } - } -} - -// Walk through delimiter list and replace text tokens with tags -// -function emphasis_post_process(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - postProcess(state, state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - postProcess(state, tokens_meta[curr].delimiters); - } - } -} -var r_emphasis = { - tokenize: emphasis_tokenize, - postProcess: emphasis_post_process -}; + /***/ "../../graphql-language-service/esm/parser/RuleHelpers.js": + /*!****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/RuleHelpers.js ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.butNot = butNot; + exports.list = list; + exports.opt = opt; + exports.p = p; + exports.t = t; + function opt(ofRule) { + return { + ofRule, + }; + } + function list(ofRule, separator) { + return { + ofRule, + isList: true, + separator, + }; + } + function butNot(rule, exclusions) { + const ruleMatch = rule.match; + rule.match = (token) => { + let check = false; + if (ruleMatch) { + check = ruleMatch(token); + } + return ( + check && + exclusions.every( + (exclusion) => exclusion.match && !exclusion.match(token) + ) + ); + }; + return rule; + } + function t(kind, style) { + return { + style, + match: (token) => token.kind === kind, + }; + } + function p(value, style) { + return { + style: style || "punctuation", + match: (token) => + token.kind === "Punctuation" && token.value === value, + }; + } -// Process [link]( "stuff") + /***/ + }, -function link(state, silent) { - let code, label, res, ref; - let href = ''; - let title = ''; - let start = state.pos; - let parseReference = true; - if (state.src.charCodeAt(state.pos) !== 0x5B /* [ */) { - return false; - } - const oldPos = state.pos; - const max = state.posMax; - const labelStart = state.pos + 1; - const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true); - - // parser failed to find ']', so it's not a valid link - if (labelEnd < 0) { - return false; - } - let pos = labelEnd + 1; - if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { - // - // Inline link - // - - // might have found a valid shortcut link, disable reference parsing - parseReference = false; - - // [link]( "title" ) - // ^^ skipping these spaces - pos++; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; - } - } - if (pos >= max) { - return false; - } + /***/ "../../graphql-language-service/esm/parser/Rules.js": + /*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/Rules.js ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.isIgnored = exports.ParseRules = exports.LexRules = void 0; + var _RuleHelpers = __webpack_require__( + /*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js" + ); + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const isIgnored = (ch) => + ch === " " || + ch === "\t" || + ch === "," || + ch === "\n" || + ch === "\r" || + ch === "\uFEFF" || + ch === "\u00A0"; + exports.isIgnored = isIgnored; + const LexRules = (exports.LexRules = { + Name: /^[_A-Za-z][_0-9A-Za-z]*/, + Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|&|@|\[|]|\{|\||\})/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: + /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/, + Comment: /^#.*/, + }); + const ParseRules = (exports.ParseRules = { + Document: [(0, _RuleHelpers.list)("Definition")], + Definition(token) { + switch (token.value) { + case "{": + return "ShortQuery"; + case "query": + return "Query"; + case "mutation": + return "Mutation"; + case "subscription": + return "Subscription"; + case "fragment": + return _graphql.Kind.FRAGMENT_DEFINITION; + case "schema": + return "SchemaDef"; + case "scalar": + return "ScalarDef"; + case "type": + return "ObjectTypeDef"; + case "interface": + return "InterfaceDef"; + case "union": + return "UnionDef"; + case "enum": + return "EnumDef"; + case "input": + return "InputDef"; + case "extend": + return "ExtendDef"; + case "directive": + return "DirectiveDef"; + } + }, + ShortQuery: ["SelectionSet"], + Query: [ + word("query"), + (0, _RuleHelpers.opt)(name("def")), + (0, _RuleHelpers.opt)("VariableDefinitions"), + (0, _RuleHelpers.list)("Directive"), + "SelectionSet", + ], + Mutation: [ + word("mutation"), + (0, _RuleHelpers.opt)(name("def")), + (0, _RuleHelpers.opt)("VariableDefinitions"), + (0, _RuleHelpers.list)("Directive"), + "SelectionSet", + ], + Subscription: [ + word("subscription"), + (0, _RuleHelpers.opt)(name("def")), + (0, _RuleHelpers.opt)("VariableDefinitions"), + (0, _RuleHelpers.list)("Directive"), + "SelectionSet", + ], + VariableDefinitions: [ + (0, _RuleHelpers.p)("("), + (0, _RuleHelpers.list)("VariableDefinition"), + (0, _RuleHelpers.p)(")"), + ], + VariableDefinition: [ + "Variable", + (0, _RuleHelpers.p)(":"), + "Type", + (0, _RuleHelpers.opt)("DefaultValue"), + ], + Variable: [(0, _RuleHelpers.p)("$", "variable"), name("variable")], + DefaultValue: [(0, _RuleHelpers.p)("="), "Value"], + SelectionSet: [ + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("Selection"), + (0, _RuleHelpers.p)("}"), + ], + Selection(token, stream) { + return token.value === "..." + ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) + ? "InlineFragment" + : "FragmentSpread" + : stream.match(/[\s\u00a0,]*:/, false) + ? "AliasedField" + : "Field"; + }, + AliasedField: [ + name("property"), + (0, _RuleHelpers.p)(":"), + name("qualifier"), + (0, _RuleHelpers.opt)("Arguments"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.opt)("SelectionSet"), + ], + Field: [ + name("property"), + (0, _RuleHelpers.opt)("Arguments"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.opt)("SelectionSet"), + ], + Arguments: [ + (0, _RuleHelpers.p)("("), + (0, _RuleHelpers.list)("Argument"), + (0, _RuleHelpers.p)(")"), + ], + Argument: [name("attribute"), (0, _RuleHelpers.p)(":"), "Value"], + FragmentSpread: [ + (0, _RuleHelpers.p)("..."), + name("def"), + (0, _RuleHelpers.list)("Directive"), + ], + InlineFragment: [ + (0, _RuleHelpers.p)("..."), + (0, _RuleHelpers.opt)("TypeCondition"), + (0, _RuleHelpers.list)("Directive"), + "SelectionSet", + ], + FragmentDefinition: [ + word("fragment"), + (0, _RuleHelpers.opt)( + (0, _RuleHelpers.butNot)(name("def"), [word("on")]) + ), + "TypeCondition", + (0, _RuleHelpers.list)("Directive"), + "SelectionSet", + ], + TypeCondition: [word("on"), "NamedType"], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; + case "$": + return "Variable"; + case "&": + return "NamedType"; + } + return null; + case "Name": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + } + if (token.value === "null") { + return "NullValue"; + } + return "EnumValue"; + } + }, + NumberValue: [(0, _RuleHelpers.t)("Number", "number")], + StringValue: [ + { + style: "string", + match: (token) => token.kind === "String", + update(state, token) { + if (token.value.startsWith('"""')) { + state.inBlockstring = !token.value.slice(3).endsWith('"""'); + } + }, + }, + ], + BooleanValue: [(0, _RuleHelpers.t)("Name", "builtin")], + NullValue: [(0, _RuleHelpers.t)("Name", "keyword")], + EnumValue: [name("string-2")], + ListValue: [ + (0, _RuleHelpers.p)("["), + (0, _RuleHelpers.list)("Value"), + (0, _RuleHelpers.p)("]"), + ], + ObjectValue: [ + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("ObjectField"), + (0, _RuleHelpers.p)("}"), + ], + ObjectField: [name("attribute"), (0, _RuleHelpers.p)(":"), "Value"], + Type(token) { + return token.value === "[" ? "ListType" : "NonNullType"; + }, + ListType: [ + (0, _RuleHelpers.p)("["), + "Type", + (0, _RuleHelpers.p)("]"), + (0, _RuleHelpers.opt)((0, _RuleHelpers.p)("!")), + ], + NonNullType: [ + "NamedType", + (0, _RuleHelpers.opt)((0, _RuleHelpers.p)("!")), + ], + NamedType: [type("atom")], + Directive: [ + (0, _RuleHelpers.p)("@", "meta"), + name("meta"), + (0, _RuleHelpers.opt)("Arguments"), + ], + DirectiveDef: [ + word("directive"), + (0, _RuleHelpers.p)("@", "meta"), + name("meta"), + (0, _RuleHelpers.opt)("ArgumentsDef"), + word("on"), + (0, _RuleHelpers.list)( + "DirectiveLocation", + (0, _RuleHelpers.p)("|") + ), + ], + InterfaceDef: [ + word("interface"), + name("atom"), + (0, _RuleHelpers.opt)("Implements"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("FieldDef"), + (0, _RuleHelpers.p)("}"), + ], + Implements: [ + word("implements"), + (0, _RuleHelpers.list)("NamedType", (0, _RuleHelpers.p)("&")), + ], + DirectiveLocation: [name("string-2")], + SchemaDef: [ + word("schema"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("OperationTypeDef"), + (0, _RuleHelpers.p)("}"), + ], + OperationTypeDef: [ + name("keyword"), + (0, _RuleHelpers.p)(":"), + name("atom"), + ], + ScalarDef: [ + word("scalar"), + name("atom"), + (0, _RuleHelpers.list)("Directive"), + ], + ObjectTypeDef: [ + word("type"), + name("atom"), + (0, _RuleHelpers.opt)("Implements"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("FieldDef"), + (0, _RuleHelpers.p)("}"), + ], + FieldDef: [ + name("property"), + (0, _RuleHelpers.opt)("ArgumentsDef"), + (0, _RuleHelpers.p)(":"), + "Type", + (0, _RuleHelpers.list)("Directive"), + ], + ArgumentsDef: [ + (0, _RuleHelpers.p)("("), + (0, _RuleHelpers.list)("InputValueDef"), + (0, _RuleHelpers.p)(")"), + ], + InputValueDef: [ + name("attribute"), + (0, _RuleHelpers.p)(":"), + "Type", + (0, _RuleHelpers.opt)("DefaultValue"), + (0, _RuleHelpers.list)("Directive"), + ], + UnionDef: [ + word("union"), + name("atom"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.p)("="), + (0, _RuleHelpers.list)("UnionMember", (0, _RuleHelpers.p)("|")), + ], + UnionMember: ["NamedType"], + EnumDef: [ + word("enum"), + name("atom"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("EnumValueDef"), + (0, _RuleHelpers.p)("}"), + ], + EnumValueDef: [name("string-2"), (0, _RuleHelpers.list)("Directive")], + InputDef: [ + word("input"), + name("atom"), + (0, _RuleHelpers.list)("Directive"), + (0, _RuleHelpers.p)("{"), + (0, _RuleHelpers.list)("InputValueDef"), + (0, _RuleHelpers.p)("}"), + ], + ExtendDef: [word("extend"), "ExtensionDefinition"], + ExtensionDefinition(token) { + switch (token.value) { + case "schema": + return _graphql.Kind.SCHEMA_EXTENSION; + case "scalar": + return _graphql.Kind.SCALAR_TYPE_EXTENSION; + case "type": + return _graphql.Kind.OBJECT_TYPE_EXTENSION; + case "interface": + return _graphql.Kind.INTERFACE_TYPE_EXTENSION; + case "union": + return _graphql.Kind.UNION_TYPE_EXTENSION; + case "enum": + return _graphql.Kind.ENUM_TYPE_EXTENSION; + case "input": + return _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + }, + [_graphql.Kind.SCHEMA_EXTENSION]: ["SchemaDef"], + [_graphql.Kind.SCALAR_TYPE_EXTENSION]: ["ScalarDef"], + [_graphql.Kind.OBJECT_TYPE_EXTENSION]: ["ObjectTypeDef"], + [_graphql.Kind.INTERFACE_TYPE_EXTENSION]: ["InterfaceDef"], + [_graphql.Kind.UNION_TYPE_EXTENSION]: ["UnionDef"], + [_graphql.Kind.ENUM_TYPE_EXTENSION]: ["EnumDef"], + [_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]: ["InputDef"], + }); + function word(value) { + return { + style: "keyword", + match: (token) => token.kind === "Name" && token.value === value, + }; + } + function name(style) { + return { + style, + match: (token) => token.kind === "Name", + update(state, token) { + state.name = token.value; + }, + }; + } + function type(style) { + return { + style, + match: (token) => token.kind === "Name", + update(state, token) { + var _a; + if ( + (_a = state.prevState) === null || _a === void 0 + ? void 0 + : _a.prevState + ) { + state.name = token.value; + state.prevState.prevState.type = token.value; + } + }, + }; + } - // [link]( "title" ) - // ^^^^^^ parsing link destination - start = pos; - res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); - if (res.ok) { - href = state.md.normalizeLink(res.str); - if (state.md.validateLink(href)) { - pos = res.pos; - } else { - href = ''; - } + /***/ + }, - // [link]( "title" ) - // ^^ skipping these spaces - start = pos; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + /***/ "../../graphql-language-service/esm/parser/api.js": + /*!********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/api.js ***! + \********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.TYPE_SYSTEM_KINDS = exports.GraphQLDocumentMode = void 0; + exports.getContextAtPosition = getContextAtPosition; + exports.getDocumentMode = getDocumentMode; + exports.getTokenAtPosition = getTokenAtPosition; + exports.runOnlineParser = runOnlineParser; + var _ = __webpack_require__( + /*! . */ "../../graphql-language-service/esm/parser/index.js" + ); + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function runOnlineParser(queryText, callback) { + const lines = queryText.split("\n"); + const parser = (0, _.onlineParser)(); + let state = parser.startState(); + let style = ""; + let stream = new _.CharacterStream(""); + for (let i = 0; i < lines.length; i++) { + stream = new _.CharacterStream(lines[i]); + while (!stream.eol()) { + style = parser.token(stream, state); + const code = callback(stream, state, style, i); + if (code === "BREAK") { + break; + } + } + callback(stream, state, style, i); + if (!state.kind) { + state = parser.startState(); + } + } + return { + start: stream.getStartOfToken(), + end: stream.getCurrentPosition(), + string: stream.current(), + state, + style, + }; } - } - - // [link]( "title" ) - // ^^^^^^^ parsing link title - res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); - if (pos < max && start !== pos && res.ok) { - title = res.str; - pos = res.pos; - - // [link]( "title" ) - // ^^ skipping these spaces - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + var GraphQLDocumentMode; + (function (GraphQLDocumentMode) { + GraphQLDocumentMode["TYPE_SYSTEM"] = "TYPE_SYSTEM"; + GraphQLDocumentMode["EXECUTABLE"] = "EXECUTABLE"; + GraphQLDocumentMode["UNKNOWN"] = "UNKNOWN"; + })( + GraphQLDocumentMode || + (exports.GraphQLDocumentMode = GraphQLDocumentMode = {}) + ); + const TYPE_SYSTEM_KINDS = (exports.TYPE_SYSTEM_KINDS = [ + _graphql.Kind.SCHEMA_DEFINITION, + _graphql.Kind.OPERATION_TYPE_DEFINITION, + _graphql.Kind.SCALAR_TYPE_DEFINITION, + _graphql.Kind.OBJECT_TYPE_DEFINITION, + _graphql.Kind.INTERFACE_TYPE_DEFINITION, + _graphql.Kind.UNION_TYPE_DEFINITION, + _graphql.Kind.ENUM_TYPE_DEFINITION, + _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION, + _graphql.Kind.DIRECTIVE_DEFINITION, + _graphql.Kind.SCHEMA_EXTENSION, + _graphql.Kind.SCALAR_TYPE_EXTENSION, + _graphql.Kind.OBJECT_TYPE_EXTENSION, + _graphql.Kind.INTERFACE_TYPE_EXTENSION, + _graphql.Kind.UNION_TYPE_EXTENSION, + _graphql.Kind.ENUM_TYPE_EXTENSION, + _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION, + ]); + const getParsedMode = (sdl) => { + let mode = GraphQLDocumentMode.UNKNOWN; + if (sdl) { + try { + (0, _graphql.visit)((0, _graphql.parse)(sdl), { + enter(node) { + if (node.kind === "Document") { + mode = GraphQLDocumentMode.EXECUTABLE; + return; + } + if (TYPE_SYSTEM_KINDS.includes(node.kind)) { + mode = GraphQLDocumentMode.TYPE_SYSTEM; + return _graphql.BREAK; + } + return false; + }, + }); + } catch (_a) { + return mode; + } + } + return mode; + }; + function getDocumentMode(documentText, uri) { + if ( + uri === null || uri === void 0 ? void 0 : uri.endsWith(".graphqls") + ) { + return GraphQLDocumentMode.TYPE_SYSTEM; + } + return getParsedMode(documentText); + } + function getTokenAtPosition(queryText, cursor, offset = 0) { + let styleAtCursor = null; + let stateAtCursor = null; + let stringAtCursor = null; + const token = runOnlineParser( + queryText, + (stream, state, style, index) => { + if ( + index !== cursor.line || + stream.getCurrentPosition() + offset < cursor.character + 1 + ) { + return; + } + styleAtCursor = style; + stateAtCursor = Object.assign({}, state); + stringAtCursor = stream.current(); + return "BREAK"; + } + ); + return { + start: token.start, + end: token.end, + string: stringAtCursor || token.string, + state: stateAtCursor || token.state, + style: styleAtCursor || token.style, + }; + } + function getContextAtPosition( + queryText, + cursor, + schema, + contextToken, + options + ) { + const token = + contextToken || getTokenAtPosition(queryText, cursor, 1); + if (!token) { + return null; + } + const state = + token.state.kind === "Invalid" + ? token.state.prevState + : token.state; + if (!state) { + return null; } + const typeInfo = (0, _.getTypeInfo)(schema, token.state); + const mode = + (options === null || options === void 0 ? void 0 : options.mode) || + getDocumentMode( + queryText, + options === null || options === void 0 ? void 0 : options.uri + ); + return { + token, + state, + typeInfo, + mode, + }; } - } - } - if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { - // parsing a valid shortcut link failed, fallback to reference - parseReference = true; - } - pos++; - } - if (parseReference) { - // - // Link reference - // - if (typeof state.env.references === 'undefined') { - return false; - } - if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { - start = pos + 1; - pos = state.md.helpers.parseLinkLabel(state, pos); - if (pos >= 0) { - label = state.src.slice(start, pos++); - } else { - pos = labelEnd + 1; - } - } else { - pos = labelEnd + 1; - } - - // covers label === '' and label === undefined - // (collapsed reference link and shortcut reference link respectively) - if (!label) { - label = state.src.slice(labelStart, labelEnd); - } - ref = state.env.references[normalizeReference(label)]; - if (!ref) { - state.pos = oldPos; - return false; - } - href = ref.href; - title = ref.title; - } - - // - // We found the end of the link, and know for a fact it's a valid link; - // so all that's left to do is to call tokenizer. - // - if (!silent) { - state.pos = labelStart; - state.posMax = labelEnd; - const token_o = state.push('link_open', 'a', 1); - const attrs = [['href', href]]; - token_o.attrs = attrs; - if (title) { - attrs.push(['title', title]); - } - state.linkLevel++; - state.md.inline.tokenize(state); - state.linkLevel--; - state.push('link_close', 'a', -1); - } - state.pos = pos; - state.posMax = max; - return true; -} - -// Process ![image]( "title") -function image(state, silent) { - let code, content, label, pos, ref, res, title, start; - let href = ''; - const oldPos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(state.pos) !== 0x21 /* ! */) { - return false; - } - if (state.src.charCodeAt(state.pos + 1) !== 0x5B /* [ */) { - return false; - } - const labelStart = state.pos + 2; - const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false); + /***/ + }, - // parser failed to find ']', so it's not a valid link - if (labelEnd < 0) { - return false; - } - pos = labelEnd + 1; - if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { - // - // Inline link - // - - // [link]( "title" ) - // ^^ skipping these spaces - pos++; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; - } - } - if (pos >= max) { - return false; - } + /***/ "../../graphql-language-service/esm/parser/getTypeInfo.js": + /*!****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/getTypeInfo.js ***! + \****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.forEachState = forEachState; + exports.getDefinitionState = getDefinitionState; + exports.getFieldDef = getFieldDef; + exports.getTypeInfo = getTypeInfo; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _ = __webpack_require__( + /*! . */ "../../graphql-language-service/esm/parser/index.js" + ); + function getFieldDef(schema, type, fieldName) { + if ( + fieldName === _graphql.SchemaMetaFieldDef.name && + schema.getQueryType() === type + ) { + return _graphql.SchemaMetaFieldDef; + } + if ( + fieldName === _graphql.TypeMetaFieldDef.name && + schema.getQueryType() === type + ) { + return _graphql.TypeMetaFieldDef; + } + if ( + fieldName === _graphql.TypeNameMetaFieldDef.name && + (0, _graphql.isCompositeType)(type) + ) { + return _graphql.TypeNameMetaFieldDef; + } + if ("getFields" in type) { + return type.getFields()[fieldName]; + } + return null; + } + function forEachState(stack, fn) { + const reverseStateStack = []; + let state = stack; + while (state === null || state === void 0 ? void 0 : state.kind) { + reverseStateStack.push(state); + state = state.prevState; + } + for (let i = reverseStateStack.length - 1; i >= 0; i--) { + fn(reverseStateStack[i]); + } + } + function getDefinitionState(tokenState) { + let definitionState; + forEachState(tokenState, (state) => { + switch (state.kind) { + case "Query": + case "ShortQuery": + case "Mutation": + case "Subscription": + case "FragmentDefinition": + definitionState = state; + break; + } + }); + return definitionState; + } + function getTypeInfo(schema, tokenState) { + let argDef; + let argDefs; + let directiveDef; + let enumValue; + let fieldDef; + let inputType; + let objectTypeDef; + let objectFieldDefs; + let parentType; + let type; + let interfaceDef; + forEachState(tokenState, (state) => { + var _a; + switch (state.kind) { + case _.RuleKinds.QUERY: + case "ShortQuery": + type = schema.getQueryType(); + break; + case _.RuleKinds.MUTATION: + type = schema.getMutationType(); + break; + case _.RuleKinds.SUBSCRIPTION: + type = schema.getSubscriptionType(); + break; + case _.RuleKinds.INLINE_FRAGMENT: + case _.RuleKinds.FRAGMENT_DEFINITION: + if (state.type) { + type = schema.getType(state.type); + } + break; + case _.RuleKinds.FIELD: + case _.RuleKinds.ALIASED_FIELD: { + if (!type || !state.name) { + fieldDef = null; + } else { + fieldDef = parentType + ? getFieldDef(schema, parentType, state.name) + : null; + type = fieldDef ? fieldDef.type : null; + } + break; + } + case _.RuleKinds.SELECTION_SET: + parentType = (0, _graphql.getNamedType)(type); + break; + case _.RuleKinds.DIRECTIVE: + directiveDef = state.name + ? schema.getDirective(state.name) + : null; + break; + case _.RuleKinds.INTERFACE_DEF: + if (state.name) { + objectTypeDef = null; + interfaceDef = new _graphql.GraphQLInterfaceType({ + name: state.name, + interfaces: [], + fields: {}, + }); + } + break; + case _.RuleKinds.OBJECT_TYPE_DEF: + if (state.name) { + interfaceDef = null; + objectTypeDef = new _graphql.GraphQLObjectType({ + name: state.name, + interfaces: [], + fields: {}, + }); + } + break; + case _.RuleKinds.ARGUMENTS: { + if (state.prevState) { + switch (state.prevState.kind) { + case _.RuleKinds.FIELD: + argDefs = fieldDef && fieldDef.args; + break; + case _.RuleKinds.DIRECTIVE: + argDefs = directiveDef && directiveDef.args; + break; + case _.RuleKinds.ALIASED_FIELD: { + const name = + (_a = state.prevState) === null || _a === void 0 + ? void 0 + : _a.name; + if (!name) { + argDefs = null; + break; + } + const field = parentType + ? getFieldDef(schema, parentType, name) + : null; + if (!field) { + argDefs = null; + break; + } + argDefs = field.args; + break; + } + default: + argDefs = null; + break; + } + } else { + argDefs = null; + } + break; + } + case _.RuleKinds.ARGUMENT: + if (argDefs) { + for (let i = 0; i < argDefs.length; i++) { + if (argDefs[i].name === state.name) { + argDef = argDefs[i]; + break; + } + } + } + inputType = + argDef === null || argDef === void 0 ? void 0 : argDef.type; + break; + case _.RuleKinds.VARIABLE_DEFINITION: + case _.RuleKinds.VARIABLE: + type = inputType; + break; + case _.RuleKinds.ENUM_VALUE: + const enumType = (0, _graphql.getNamedType)(inputType); + enumValue = + enumType instanceof _graphql.GraphQLEnumType + ? enumType + .getValues() + .find((val) => val.value === state.name) + : null; + break; + case _.RuleKinds.LIST_VALUE: + const nullableType = (0, _graphql.getNullableType)(inputType); + inputType = + nullableType instanceof _graphql.GraphQLList + ? nullableType.ofType + : null; + break; + case _.RuleKinds.OBJECT_VALUE: + const objectType = (0, _graphql.getNamedType)(inputType); + objectFieldDefs = + objectType instanceof _graphql.GraphQLInputObjectType + ? objectType.getFields() + : null; + break; + case _.RuleKinds.OBJECT_FIELD: + const objectField = + state.name && objectFieldDefs + ? objectFieldDefs[state.name] + : null; + inputType = + objectField === null || objectField === void 0 + ? void 0 + : objectField.type; + fieldDef = objectField; + type = fieldDef ? fieldDef.type : null; + break; + case _.RuleKinds.NAMED_TYPE: + if (state.name) { + type = schema.getType(state.name); + } + break; + } + }); + return { + argDef, + argDefs, + directiveDef, + enumValue, + fieldDef, + inputType, + objectFieldDefs, + parentType, + type, + interfaceDef, + objectTypeDef, + }; + } - // [link]( "title" ) - // ^^^^^^ parsing link destination - start = pos; - res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); - if (res.ok) { - href = state.md.normalizeLink(res.str); - if (state.md.validateLink(href)) { - pos = res.pos; - } else { - href = ''; - } - } + /***/ + }, - // [link]( "title" ) - // ^^ skipping these spaces - start = pos; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; - } - } + /***/ "../../graphql-language-service/esm/parser/index.js": + /*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/index.js ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + var _exportNames = { + CharacterStream: true, + LexRules: true, + ParseRules: true, + isIgnored: true, + butNot: true, + list: true, + opt: true, + p: true, + t: true, + onlineParser: true, + runOnlineParser: true, + getTokenAtPosition: true, + getContextAtPosition: true, + GraphQLDocumentMode: true, + getDocumentMode: true, + getTypeInfo: true, + getDefinitionState: true, + getFieldDef: true, + }; + Object.defineProperty(exports, "CharacterStream", { + enumerable: true, + get: function () { + return _CharacterStream.default; + }, + }); + Object.defineProperty(exports, "GraphQLDocumentMode", { + enumerable: true, + get: function () { + return _api.GraphQLDocumentMode; + }, + }); + Object.defineProperty(exports, "LexRules", { + enumerable: true, + get: function () { + return _Rules.LexRules; + }, + }); + Object.defineProperty(exports, "ParseRules", { + enumerable: true, + get: function () { + return _Rules.ParseRules; + }, + }); + Object.defineProperty(exports, "butNot", { + enumerable: true, + get: function () { + return _RuleHelpers.butNot; + }, + }); + Object.defineProperty(exports, "getContextAtPosition", { + enumerable: true, + get: function () { + return _api.getContextAtPosition; + }, + }); + Object.defineProperty(exports, "getDefinitionState", { + enumerable: true, + get: function () { + return _getTypeInfo.getDefinitionState; + }, + }); + Object.defineProperty(exports, "getDocumentMode", { + enumerable: true, + get: function () { + return _api.getDocumentMode; + }, + }); + Object.defineProperty(exports, "getFieldDef", { + enumerable: true, + get: function () { + return _getTypeInfo.getFieldDef; + }, + }); + Object.defineProperty(exports, "getTokenAtPosition", { + enumerable: true, + get: function () { + return _api.getTokenAtPosition; + }, + }); + Object.defineProperty(exports, "getTypeInfo", { + enumerable: true, + get: function () { + return _getTypeInfo.getTypeInfo; + }, + }); + Object.defineProperty(exports, "isIgnored", { + enumerable: true, + get: function () { + return _Rules.isIgnored; + }, + }); + Object.defineProperty(exports, "list", { + enumerable: true, + get: function () { + return _RuleHelpers.list; + }, + }); + Object.defineProperty(exports, "onlineParser", { + enumerable: true, + get: function () { + return _onlineParser.default; + }, + }); + Object.defineProperty(exports, "opt", { + enumerable: true, + get: function () { + return _RuleHelpers.opt; + }, + }); + Object.defineProperty(exports, "p", { + enumerable: true, + get: function () { + return _RuleHelpers.p; + }, + }); + Object.defineProperty(exports, "runOnlineParser", { + enumerable: true, + get: function () { + return _api.runOnlineParser; + }, + }); + Object.defineProperty(exports, "t", { + enumerable: true, + get: function () { + return _RuleHelpers.t; + }, + }); + var _CharacterStream = _interopRequireDefault( + __webpack_require__( + /*! ./CharacterStream */ "../../graphql-language-service/esm/parser/CharacterStream.js" + ) + ); + var _Rules = __webpack_require__( + /*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js" + ); + var _RuleHelpers = __webpack_require__( + /*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js" + ); + var _onlineParser = _interopRequireDefault( + __webpack_require__( + /*! ./onlineParser */ "../../graphql-language-service/esm/parser/onlineParser.js" + ) + ); + var _api = __webpack_require__( + /*! ./api */ "../../graphql-language-service/esm/parser/api.js" + ); + var _getTypeInfo = __webpack_require__( + /*! ./getTypeInfo */ "../../graphql-language-service/esm/parser/getTypeInfo.js" + ); + var _types = __webpack_require__( + /*! ./types */ "../../graphql-language-service/esm/parser/types.js" + ); + Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + }, + }); + }); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - // [link]( "title" ) - // ^^^^^^^ parsing link title - res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); - if (pos < max && start !== pos && res.ok) { - title = res.str; - pos = res.pos; + /***/ + }, - // [link]( "title" ) - // ^^ skipping these spaces - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + /***/ "../../graphql-language-service/esm/parser/onlineParser.js": + /*!*****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/onlineParser.js ***! + \*****************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = onlineParser; + var _Rules = __webpack_require__( + /*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js" + ); + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function onlineParser( + options = { + eatWhitespace: (stream) => stream.eatWhile(_Rules.isIgnored), + lexRules: _Rules.LexRules, + parseRules: _Rules.ParseRules, + editorConfig: {}, + } + ) { + return { + startState() { + const initialState = { + level: 0, + step: 0, + name: null, + kind: null, + type: null, + rule: null, + needsSeparator: false, + prevState: null, + }; + pushRule( + options.parseRules, + initialState, + _graphql.Kind.DOCUMENT + ); + return initialState; + }, + token(stream, state) { + return getToken(stream, state, options); + }, + }; + } + function getToken(stream, state, options) { + var _a; + if (state.inBlockstring) { + if (stream.match(/.*"""/)) { + state.inBlockstring = false; + return "string"; + } + stream.skipToEnd(); + return "string"; + } + const { lexRules, parseRules, eatWhitespace, editorConfig } = options; + if (state.rule && state.rule.length === 0) { + popRule(state); + } else if (state.needsAdvance) { + state.needsAdvance = false; + advanceRule(state, true); + } + if (stream.sol()) { + const tabSize = + (editorConfig === null || editorConfig === void 0 + ? void 0 + : editorConfig.tabSize) || 2; + state.indentLevel = Math.floor(stream.indentation() / tabSize); + } + if (eatWhitespace(stream)) { + return "ws"; + } + const token = lex(lexRules, stream); + if (!token) { + const matchedSomething = stream.match(/\S+/); + if (!matchedSomething) { + stream.match(/\s/); + } + pushRule(SpecialParseRules, state, "Invalid"); + return "invalidchar"; + } + if (token.kind === "Comment") { + pushRule(SpecialParseRules, state, "Comment"); + return "comment"; + } + const backupState = assign({}, state); + if (token.kind === "Punctuation") { + if (/^[{([]/.test(token.value)) { + if (state.indentLevel !== undefined) { + state.levels = (state.levels || []).concat( + state.indentLevel + 1 + ); + } + } else if (/^[})\]]/.test(token.value)) { + const levels = (state.levels = (state.levels || []).slice(0, -1)); + if ( + state.indentLevel && + levels.length > 0 && + levels.at(-1) < state.indentLevel + ) { + state.indentLevel = levels.at(-1); + } + } + } + while (state.rule) { + let expected = + typeof state.rule === "function" + ? state.step === 0 + ? state.rule(token, stream) + : null + : state.rule[state.step]; + if (state.needsSeparator) { + expected = + expected === null || expected === void 0 + ? void 0 + : expected.separator; + } + if (expected) { + if (expected.ofRule) { + expected = expected.ofRule; + } + if (typeof expected === "string") { + pushRule(parseRules, state, expected); + continue; + } + if ( + (_a = expected.match) === null || _a === void 0 + ? void 0 + : _a.call(expected, token) + ) { + if (expected.update) { + expected.update(state, token); + } + if (token.kind === "Punctuation") { + advanceRule(state, true); + } else { + state.needsAdvance = true; + } + return expected.style; + } + } + unsuccessful(state); + } + assign(state, backupState); + pushRule(SpecialParseRules, state, "Invalid"); + return "invalidchar"; + } + function assign(to, from) { + const keys = Object.keys(from); + for (let i = 0; i < keys.length; i++) { + to[keys[i]] = from[keys[i]]; + } + return to; } - } - } else { - title = ''; - } - if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { - state.pos = oldPos; - return false; - } - pos++; - } else { - // - // Link reference - // - if (typeof state.env.references === 'undefined') { - return false; - } - if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { - start = pos + 1; - pos = state.md.helpers.parseLinkLabel(state, pos); - if (pos >= 0) { - label = state.src.slice(start, pos++); - } else { - pos = labelEnd + 1; - } - } else { - pos = labelEnd + 1; - } - - // covers label === '' and label === undefined - // (collapsed reference link and shortcut reference link respectively) - if (!label) { - label = state.src.slice(labelStart, labelEnd); - } - ref = state.env.references[normalizeReference(label)]; - if (!ref) { - state.pos = oldPos; - return false; - } - href = ref.href; - title = ref.title; - } - - // - // We found the end of the link, and know for a fact it's a valid link; - // so all that's left to do is to call tokenizer. - // - if (!silent) { - content = state.src.slice(labelStart, labelEnd); - const tokens = []; - state.md.inline.parse(content, state.md, state.env, tokens); - const token = state.push('image', 'img', 0); - const attrs = [['src', href], ['alt', '']]; - token.attrs = attrs; - token.children = tokens; - token.content = content; - if (title) { - attrs.push(['title', title]); - } - } - state.pos = pos; - state.posMax = max; - return true; -} - -// Process autolinks '' - -/* eslint max-len:0 */ -const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; -/* eslint-disable-next-line no-control-regex */ -const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/; -function autolink(state, silent) { - let pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x3C /* < */) { - return false; - } - const start = state.pos; - const max = state.posMax; - for (;;) { - if (++pos >= max) return false; - const ch = state.src.charCodeAt(pos); - if (ch === 0x3C /* < */) return false; - if (ch === 0x3E /* > */) break; - } - const url = state.src.slice(start + 1, pos); - if (AUTOLINK_RE.test(url)) { - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) { - return false; - } - if (!silent) { - const token_o = state.push('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.markup = 'autolink'; - token_o.info = 'auto'; - const token_t = state.push('text', '', 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push('link_close', 'a', -1); - token_c.markup = 'autolink'; - token_c.info = 'auto'; - } - state.pos += url.length + 2; - return true; - } - if (EMAIL_RE.test(url)) { - const fullUrl = state.md.normalizeLink('mailto:' + url); - if (!state.md.validateLink(fullUrl)) { - return false; - } - if (!silent) { - const token_o = state.push('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.markup = 'autolink'; - token_o.info = 'auto'; - const token_t = state.push('text', '', 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push('link_close', 'a', -1); - token_c.markup = 'autolink'; - token_c.info = 'auto'; - } - state.pos += url.length + 2; - return true; - } - return false; -} - -// Process html tags - -function isLinkOpen(str) { - return /^\s]/i.test(str); -} -function isLinkClose(str) { - return /^<\/a\s*>/i.test(str); -} -function isLetter(ch) { - /* eslint no-bitwise:0 */ - const lc = ch | 0x20; // to lower case - return lc >= 0x61 /* a */ && lc <= 0x7a /* z */; -} -function html_inline(state, silent) { - if (!state.md.options.html) { - return false; - } - - // Check start - const max = state.posMax; - const pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x3C /* < */ || pos + 2 >= max) { - return false; - } - - // Quick fail on second char - const ch = state.src.charCodeAt(pos + 1); - if (ch !== 0x21 /* ! */ && ch !== 0x3F /* ? */ && ch !== 0x2F /* / */ && !isLetter(ch)) { - return false; - } - const match = state.src.slice(pos).match(HTML_TAG_RE); - if (!match) { - return false; - } - if (!silent) { - const token = state.push('html_inline', '', 0); - token.content = match[0]; - if (isLinkOpen(token.content)) state.linkLevel++; - if (isLinkClose(token.content)) state.linkLevel--; - } - state.pos += match[0].length; - return true; -} - -// Process html entity - {, ¯, ", ... - -const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; -const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; -function entity(state, silent) { - const pos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(pos) !== 0x26 /* & */) return false; - if (pos + 1 >= max) return false; - const ch = state.src.charCodeAt(pos + 1); - if (ch === 0x23 /* # */) { - const match = state.src.slice(pos).match(DIGITAL_RE); - if (match) { - if (!silent) { - const code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10); - const token = state.push('text_special', '', 0); - token.content = isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD); - token.markup = match[0]; - token.info = 'entity'; - } - state.pos += match[0].length; - return true; - } - } else { - const match = state.src.slice(pos).match(NAMED_RE); - if (match) { - const decoded = entities.decodeHTML(match[0]); - if (decoded !== match[0]) { - if (!silent) { - const token = state.push('text_special', '', 0); - token.content = decoded; - token.markup = match[0]; - token.info = 'entity'; - } - state.pos += match[0].length; - return true; - } - } - } - return false; -} - -// For each opening emphasis-like marker find a matching closing one -// - -function processDelimiters(delimiters) { - const openersBottom = {}; - const max = delimiters.length; - if (!max) return; - - // headerIdx is the first delimiter of the current (where closer is) delimiter run - let headerIdx = 0; - let lastTokenIdx = -2; // needs any value lower than -1 - const jumps = []; - for (let closerIdx = 0; closerIdx < max; closerIdx++) { - const closer = delimiters[closerIdx]; - jumps.push(0); - - // markers belong to same delimiter run if: - // - they have adjacent tokens - // - AND markers are the same - // - if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) { - headerIdx = closerIdx; - } - lastTokenIdx = closer.token; - - // Length is only used for emphasis-specific "rule of 3", - // if it's not defined (in strikethrough or 3rd party plugins), - // we can default it to 0 to disable those checks. - // - closer.length = closer.length || 0; - if (!closer.close) continue; - - // Previously calculated lower bounds (previous fails) - // for each marker, each delimiter length modulo 3, - // and for whether this closer can be an opener; - // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 - /* eslint-disable-next-line no-prototype-builtins */ - if (!openersBottom.hasOwnProperty(closer.marker)) { - openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]; - } - const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3]; - let openerIdx = headerIdx - jumps[headerIdx] - 1; - let newMinOpenerIdx = openerIdx; - for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) { - const opener = delimiters[openerIdx]; - if (opener.marker !== closer.marker) continue; - if (opener.open && opener.end < 0) { - let isOddMatch = false; - - // from spec: - // - // If one of the delimiters can both open and close emphasis, then the - // sum of the lengths of the delimiter runs containing the opening and - // closing delimiters must not be a multiple of 3 unless both lengths - // are multiples of 3. - // - if (opener.close || closer.open) { - if ((opener.length + closer.length) % 3 === 0) { - if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { - isOddMatch = true; + const SpecialParseRules = { + Invalid: [], + Comment: [], + }; + function pushRule(rules, state, ruleKind) { + if (!rules[ruleKind]) { + throw new TypeError("Unknown rule: " + ruleKind); + } + state.prevState = Object.assign({}, state); + state.kind = ruleKind; + state.name = null; + state.type = null; + state.rule = rules[ruleKind]; + state.step = 0; + state.needsSeparator = false; + } + function popRule(state) { + if (!state.prevState) { + return; + } + state.kind = state.prevState.kind; + state.name = state.prevState.name; + state.type = state.prevState.type; + state.rule = state.prevState.rule; + state.step = state.prevState.step; + state.needsSeparator = state.prevState.needsSeparator; + state.prevState = state.prevState.prevState; + } + function advanceRule(state, successful) { + var _a; + if (isList(state) && state.rule) { + const step = state.rule[state.step]; + if (step.separator) { + const { separator } = step; + state.needsSeparator = !state.needsSeparator; + if (!state.needsSeparator && separator.ofRule) { + return; + } + } + if (successful) { + return; + } + } + state.needsSeparator = false; + state.step++; + while ( + state.rule && + !(Array.isArray(state.rule) && state.step < state.rule.length) + ) { + popRule(state); + if (state.rule) { + if (isList(state)) { + if ( + (_a = state.rule) === null || _a === void 0 + ? void 0 + : _a[state.step].separator + ) { + state.needsSeparator = !state.needsSeparator; + } + } else { + state.needsSeparator = false; + state.step++; + } } } } - if (!isOddMatch) { - // If previous delimiter cannot be an opener, we can safely skip - // the entire sequence in future checks. This is required to make - // sure algorithm has linear complexity (see *_*_*_*_*_... case). - // - const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0; - jumps[closerIdx] = closerIdx - openerIdx + lastJump; - jumps[openerIdx] = lastJump; - closer.open = false; - opener.end = closerIdx; - opener.close = false; - newMinOpenerIdx = -1; - // treat next token as start of run, - // it optimizes skips in **<...>**a**<...>** pathological case - lastTokenIdx = -2; - break; + function isList(state) { + const step = + Array.isArray(state.rule) && + typeof state.rule[state.step] !== "string" && + state.rule[state.step]; + return step && step.isList; } - } - } - if (newMinOpenerIdx !== -1) { - // If match for this delimiter run failed, we want to set lower bound for - // future lookups. This is required to make sure algorithm has linear - // complexity. - // - // See details here: - // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 - // - openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx; - } - } -} -function link_pairs(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - processDelimiters(state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - processDelimiters(tokens_meta[curr].delimiters); - } - } -} - -// Clean up tokens after emphasis and strikethrough postprocessing: -// merge adjacent text nodes into one and re-calculate all token levels -// -// This is necessary because initially emphasis delimiter markers (*, _, ~) -// are treated as their own separate text tokens. Then emphasis rule either -// leaves them as text (needed to merge with adjacent text) or turns them -// into opening/closing tags (which messes up levels inside). -// - -function fragments_join(state) { - let curr, last; - let level = 0; - const tokens = state.tokens; - const max = state.tokens.length; - for (curr = last = 0; curr < max; curr++) { - // re-calculate levels after emphasis/strikethrough turns some text nodes - // into opening/closing tags - if (tokens[curr].nesting < 0) level--; // closing tag - tokens[curr].level = level; - if (tokens[curr].nesting > 0) level++; // opening tag - - if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { - // collapse two adjacent text nodes - tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; - } else { - if (curr !== last) { - tokens[last] = tokens[curr]; - } - last++; - } - } - if (curr !== last) { - tokens.length = last; - } -} - -/** internal - * class ParserInline - * - * Tokenizes paragraph content. - **/ - -// Parser rules - -const _rules = [['text', text], ['linkify', linkify], ['newline', newline], ['escape', escape], ['backticks', backtick], ['strikethrough', r_strikethrough.tokenize], ['emphasis', r_emphasis.tokenize], ['link', link], ['image', image], ['autolink', autolink], ['html_inline', html_inline], ['entity', entity]]; - -// `rule2` ruleset was created specifically for emphasis/strikethrough -// post-processing and may be changed in the future. -// -// Don't use this for anything except pairs (plugins working with `balance_pairs`). -// -const _rules2 = [['balance_pairs', link_pairs], ['strikethrough', r_strikethrough.postProcess], ['emphasis', r_emphasis.postProcess], -// rules for pairs separate '**' into its own text tokens, which may be left unused, -// rule below merges unused segments back with the rest of the text -['fragments_join', fragments_join]]; - -/** - * new ParserInline() - **/ -function ParserInline() { - /** - * ParserInline#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of inline rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules.length; i++) { - this.ruler.push(_rules[i][0], _rules[i][1]); - } - - /** - * ParserInline#ruler2 -> Ruler - * - * [[Ruler]] instance. Second ruler used for post-processing - * (e.g. in emphasis-like rules). - **/ - this.ruler2 = new Ruler(); - for (let i = 0; i < _rules2.length; i++) { - this.ruler2.push(_rules2[i][0], _rules2[i][1]); - } -} - -// Skip single token by running all rules in validation mode; -// returns `true` if any rule reported success -// -ParserInline.prototype.skipToken = function (state) { - const pos = state.pos; - const rules = this.ruler.getRules(''); - const len = rules.length; - const maxNesting = state.md.options.maxNesting; - const cache = state.cache; - if (typeof cache[pos] !== 'undefined') { - state.pos = cache[pos]; - return; - } - let ok = false; - if (state.level < maxNesting) { - for (let i = 0; i < len; i++) { - // Increment state.level and decrement it later to limit recursion. - // It's harmless to do here, because no tokens are created. But ideally, - // we'd need a separate private state variable for this purpose. - // - state.level++; - ok = rules[i](state, true); - state.level--; - if (ok) { - if (pos >= state.pos) { - throw new Error("inline rule didn't increment state.pos"); - } - break; - } - } - } else { - // Too much nesting, just skip until the end of the paragraph. - // - // NOTE: this will cause links to behave incorrectly in the following case, - // when an amount of `[` is exactly equal to `maxNesting + 1`: - // - // [[[[[[[[[[[[[[[[[[[[[foo]() - // - // TODO: remove this workaround when CM standard will allow nested links - // (we can replace it by preventing links from being parsed in - // validation mode) - // - state.pos = state.posMax; - } - if (!ok) { - state.pos++; - } - cache[pos] = state.pos; -}; - -// Generate tokens for input range -// -ParserInline.prototype.tokenize = function (state) { - const rules = this.ruler.getRules(''); - const len = rules.length; - const end = state.posMax; - const maxNesting = state.md.options.maxNesting; - while (state.pos < end) { - // Try all possible rules. - // On success, rule should: - // - // - update `state.pos` - // - update `state.tokens` - // - return true - const prevPos = state.pos; - let ok = false; - if (state.level < maxNesting) { - for (let i = 0; i < len; i++) { - ok = rules[i](state, false); - if (ok) { - if (prevPos >= state.pos) { - throw new Error("inline rule didn't increment state.pos"); - } - break; + function unsuccessful(state) { + while ( + state.rule && + !(Array.isArray(state.rule) && state.rule[state.step].ofRule) + ) { + popRule(state); + } + if (state.rule) { + advanceRule(state, false); + } + } + function lex(lexRules, stream) { + const kinds = Object.keys(lexRules); + for (let i = 0; i < kinds.length; i++) { + const match = stream.match(lexRules[kinds[i]]); + if (match && match instanceof Array) { + return { + kind: kinds[i], + value: match[0], + }; + } + } } - } - } - if (ok) { - if (state.pos >= end) { - break; - } - continue; - } - state.pending += state.src[state.pos++]; - } - if (state.pending) { - state.pushPending(); - } -}; - -/** - * ParserInline.parse(str, md, env, outTokens) - * - * Process input string and push inline tokens into `outTokens` - **/ -ParserInline.prototype.parse = function (str, md, env, outTokens) { - const state = new this.State(str, md, env, outTokens); - this.tokenize(state); - const rules = this.ruler2.getRules(''); - const len = rules.length; - for (let i = 0; i < len; i++) { - rules[i](state); - } -}; -ParserInline.prototype.State = StateInline; - -// markdown-it default options - -var cfg_default = { - options: { - // Enable HTML tags in source - html: false, - // Use '/' to close single tags (
    ) - xhtmlOut: false, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: 'language-', - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: '\u201c\u201d\u2018\u2019', - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with ) - xhtmlOut: false, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: 'language-', - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: '\u201c\u201d\u2018\u2019', - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with ) - xhtmlOut: true, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: 'language-', - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: '\u201c\u201d\u2018\u2019', - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with = 0) { - try { - parsed.hostname = punycode.toASCII(parsed.hostname); - } catch (er) {/**/} - } - } - return mdurl__namespace.encode(mdurl__namespace.format(parsed)); -} -function normalizeLinkText(url) { - const parsed = mdurl__namespace.parse(url, true); - if (parsed.hostname) { - // Encode hostnames in urls like: - // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` - // - // We don't encode unknown schemas, because it's likely that we encode - // something we shouldn't (e.g. `skype:name` treated as `skype:host`) - // - if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { - try { - parsed.hostname = punycode.toUnicode(parsed.hostname); - } catch (er) {/**/} - } - } - - // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 - return mdurl__namespace.decode(mdurl__namespace.format(parsed), mdurl__namespace.decode.defaultChars + '%'); -} - -/** - * class MarkdownIt - * - * Main parser/renderer class. - * - * ##### Usage - * - * ```javascript - * // node.js, "classic" way: - * var MarkdownIt = require('markdown-it'), - * md = new MarkdownIt(); - * var result = md.render('# markdown-it rulezz!'); - * - * // node.js, the same, but with sugar: - * var md = require('markdown-it')(); - * var result = md.render('# markdown-it rulezz!'); - * - * // browser without AMD, added to "window" on script load - * // Note, there are no dash. - * var md = window.markdownit(); - * var result = md.render('# markdown-it rulezz!'); - * ``` - * - * Single line rendering, without paragraph wrap: - * - * ```javascript - * var md = require('markdown-it')(); - * var result = md.renderInline('__markdown-it__ rulezz!'); - * ``` - **/ - -/** - * new MarkdownIt([presetName, options]) - * - presetName (String): optional, `commonmark` / `zero` - * - options (Object) - * - * Creates parser instanse with given config. Can be called without `new`. - * - * ##### presetName - * - * MarkdownIt provides named presets as a convenience to quickly - * enable/disable active syntax rules and options for common use cases. - * - * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.mjs) - - * configures parser to strict [CommonMark](http://commonmark.org/) mode. - * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.mjs) - - * similar to GFM, used when no preset name given. Enables all available rules, - * but still without html, typographer & autolinker. - * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.mjs) - - * all rules disabled. Useful to quickly setup your config via `.enable()`. - * For example, when you need only `bold` and `italic` markup and nothing else. - * - * ##### options: - * - * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! - * That's not safe! You may need external sanitizer to protect output from XSS. - * It's better to extend features via plugins, instead of enabling HTML. - * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags - * (`
    `). This is needed only for full CommonMark compatibility. In real - * world you will need HTML output. - * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
    `. - * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. - * Can be useful for external highlighters. - * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. - * - __typographer__ - `false`. Set `true` to enable [some language-neutral - * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs) + - * quotes beautification (smartquotes). - * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement - * pairs, when typographer enabled and smartquotes on. For example, you can - * use `'«»„“'` for Russian, `'„“‚‘'` for German, and - * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). - * - __highlight__ - `null`. Highlighter function for fenced code blocks. - * Highlighter `function (str, lang)` should return escaped HTML. It can also - * return empty string if the source was not changed and should be escaped - * externaly. If result starts with ` or ``): - * - * ```javascript - * var hljs = require('highlight.js') // https://highlightjs.org/ - * - * // Actual default values - * var md = require('markdown-it')({ - * highlight: function (str, lang) { - * if (lang && hljs.getLanguage(lang)) { - * try { - * return '

    ' +
    - *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
    - *                '
    '; - * } catch (__) {} - * } - * - * return '
    ' + md.utils.escapeHtml(str) + '
    '; - * } - * }); - * ``` - * - **/ -function MarkdownIt(presetName, options) { - if (!(this instanceof MarkdownIt)) { - return new MarkdownIt(presetName, options); - } - if (!options) { - if (!isString(presetName)) { - options = presetName || {}; - presetName = 'default'; - } - } - /** - * MarkdownIt#inline -> ParserInline - * - * Instance of [[ParserInline]]. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.inline = new ParserInline(); - - /** - * MarkdownIt#block -> ParserBlock - * - * Instance of [[ParserBlock]]. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.block = new ParserBlock(); - - /** - * MarkdownIt#core -> Core - * - * Instance of [[Core]] chain executor. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.core = new Core(); - - /** - * MarkdownIt#renderer -> Renderer - * - * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering - * rules for new token types, generated by plugins. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * function myToken(tokens, idx, options, env, self) { - * //... - * return result; - * }; - * - * md.renderer.rules['my_token'] = myToken - * ``` - * - * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs). - **/ - this.renderer = new Renderer(); - - /** - * MarkdownIt#linkify -> LinkifyIt - * - * [linkify-it](https://github.com/markdown-it/linkify-it) instance. - * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs) - * rule. - **/ - this.linkify = new LinkifyIt(); - - /** - * MarkdownIt#validateLink(url) -> Boolean - * - * Link validation function. CommonMark allows too much in links. By default - * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas - * except some embedded image types. - * - * You can change this behaviour: - * - * ```javascript - * var md = require('markdown-it')(); - * // enable everything - * md.validateLink = function () { return true; } - * ``` - **/ - this.validateLink = validateLink; - - /** - * MarkdownIt#normalizeLink(url) -> String - * - * Function used to encode link url to a machine-readable format, - * which includes url-encoding, punycode, etc. - **/ - this.normalizeLink = normalizeLink; - - /** - * MarkdownIt#normalizeLinkText(url) -> String - * - * Function used to decode link url to a human-readable format` - **/ - this.normalizeLinkText = normalizeLinkText; - - // Expose utils & helpers for easy acces from plugins - - /** - * MarkdownIt#utils -> utils - * - * Assorted utility functions, useful to write plugins. See details - * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs). - **/ - this.utils = utils; - - /** - * MarkdownIt#helpers -> helpers - * - * Link components parser functions, useful to write plugins. See details - * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). - **/ - this.helpers = assign({}, helpers); - this.options = {}; - this.configure(presetName); - if (options) { - this.set(options); - } -} - -/** chainable - * MarkdownIt.set(options) - * - * Set parser options (in the same format as in constructor). Probably, you - * will never need it, but you can change options after constructor call. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')() - * .set({ html: true, breaks: true }) - * .set({ typographer, true }); - * ``` - * - * __Note:__ To achieve the best possible performance, don't modify a - * `markdown-it` instance options on the fly. If you need multiple configurations - * it's best to create multiple instances and initialize each with separate - * config. - **/ -MarkdownIt.prototype.set = function (options) { - assign(this.options, options); - return this; -}; + /***/ + }, -/** chainable, internal - * MarkdownIt.configure(presets) - * - * Batch load of all options and compenent settings. This is internal method, - * and you probably will not need it. But if you will - see available presets - * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) - * - * We strongly recommend to use presets instead of direct config loads. That - * will give better compatibility with next versions. - **/ -MarkdownIt.prototype.configure = function (presets) { - const self = this; - if (isString(presets)) { - const presetName = presets; - presets = config[presetName]; - if (!presets) { - throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name'); - } - } - if (!presets) { - throw new Error('Wrong `markdown-it` preset, can\'t be empty'); - } - if (presets.options) { - self.set(presets.options); - } - if (presets.components) { - Object.keys(presets.components).forEach(function (name) { - if (presets.components[name].rules) { - self[name].ruler.enableOnly(presets.components[name].rules); - } - if (presets.components[name].rules2) { - self[name].ruler2.enableOnly(presets.components[name].rules2); - } - }); - } - return this; -}; + /***/ "../../graphql-language-service/esm/parser/types.js": + /*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/types.js ***! + \**********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.RuleKinds = exports.AdditionalRuleKinds = void 0; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const AdditionalRuleKinds = (exports.AdditionalRuleKinds = { + ALIASED_FIELD: "AliasedField", + ARGUMENTS: "Arguments", + SHORT_QUERY: "ShortQuery", + QUERY: "Query", + MUTATION: "Mutation", + SUBSCRIPTION: "Subscription", + TYPE_CONDITION: "TypeCondition", + INVALID: "Invalid", + COMMENT: "Comment", + SCHEMA_DEF: "SchemaDef", + SCALAR_DEF: "ScalarDef", + OBJECT_TYPE_DEF: "ObjectTypeDef", + OBJECT_VALUE: "ObjectValue", + LIST_VALUE: "ListValue", + INTERFACE_DEF: "InterfaceDef", + UNION_DEF: "UnionDef", + ENUM_DEF: "EnumDef", + ENUM_VALUE: "EnumValue", + FIELD_DEF: "FieldDef", + INPUT_DEF: "InputDef", + INPUT_VALUE_DEF: "InputValueDef", + ARGUMENTS_DEF: "ArgumentsDef", + EXTEND_DEF: "ExtendDef", + EXTENSION_DEFINITION: "ExtensionDefinition", + DIRECTIVE_DEF: "DirectiveDef", + IMPLEMENTS: "Implements", + VARIABLE_DEFINITIONS: "VariableDefinitions", + TYPE: "Type", + VARIABLE: "Variable", + }); + const RuleKinds = (exports.RuleKinds = Object.assign( + Object.assign({}, _graphql.Kind), + AdditionalRuleKinds + )); -/** chainable - * MarkdownIt.enable(list, ignoreInvalid) - * - list (String|Array): rule name or list of rule names to enable - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable list or rules. It will automatically find appropriate components, - * containing rules with given names. If rule not found, and `ignoreInvalid` - * not set - throws exception. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')() - * .enable(['sub', 'sup']) - * .disable('smartquotes'); - * ``` - **/ -MarkdownIt.prototype.enable = function (list, ignoreInvalid) { - let result = []; - if (!Array.isArray(list)) { - list = [list]; - } - ['core', 'block', 'inline'].forEach(function (chain) { - result = result.concat(this[chain].ruler.enable(list, true)); - }, this); - result = result.concat(this.inline.ruler2.enable(list, true)); - const missed = list.filter(function (name) { - return result.indexOf(name) < 0; - }); - if (missed.length && !ignoreInvalid) { - throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed); - } - return this; -}; + /***/ + }, -/** chainable - * MarkdownIt.disable(list, ignoreInvalid) - * - list (String|Array): rule name or list of rule names to disable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * The same as [[MarkdownIt.enable]], but turn specified rules off. - **/ -MarkdownIt.prototype.disable = function (list, ignoreInvalid) { - let result = []; - if (!Array.isArray(list)) { - list = [list]; - } - ['core', 'block', 'inline'].forEach(function (chain) { - result = result.concat(this[chain].ruler.disable(list, true)); - }, this); - result = result.concat(this.inline.ruler2.disable(list, true)); - const missed = list.filter(function (name) { - return result.indexOf(name) < 0; - }); - if (missed.length && !ignoreInvalid) { - throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed); - } - return this; -}; + /***/ "../../graphql-language-service/esm/types.js": + /*!***************************************************!*\ + !*** ../../graphql-language-service/esm/types.js ***! + \***************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.FileChangeTypeKind = exports.CompletionItemKind = void 0; + Object.defineProperty(exports, "GraphQLDocumentMode", { + enumerable: true, + get: function () { + return _parser.GraphQLDocumentMode; + }, + }); + Object.defineProperty(exports, "InsertTextFormat", { + enumerable: true, + get: function () { + return _vscodeLanguageserverTypes.InsertTextFormat; + }, + }); + var _vscodeLanguageserverTypes = __webpack_require__( + /*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js" + ); + var _parser = __webpack_require__( + /*! ./parser */ "../../graphql-language-service/esm/parser/index.js" + ); + const FileChangeTypeKind = (exports.FileChangeTypeKind = { + Created: 1, + Changed: 2, + Deleted: 3, + }); + var CompletionItemKind; + (function (CompletionItemKind) { + CompletionItemKind.Text = 1; + CompletionItemKind.Method = 2; + CompletionItemKind.Function = 3; + CompletionItemKind.Constructor = 4; + CompletionItemKind.Field = 5; + CompletionItemKind.Variable = 6; + CompletionItemKind.Class = 7; + CompletionItemKind.Interface = 8; + CompletionItemKind.Module = 9; + CompletionItemKind.Property = 10; + CompletionItemKind.Unit = 11; + CompletionItemKind.Value = 12; + CompletionItemKind.Enum = 13; + CompletionItemKind.Keyword = 14; + CompletionItemKind.Snippet = 15; + CompletionItemKind.Color = 16; + CompletionItemKind.File = 17; + CompletionItemKind.Reference = 18; + CompletionItemKind.Folder = 19; + CompletionItemKind.EnumMember = 20; + CompletionItemKind.Constant = 21; + CompletionItemKind.Struct = 22; + CompletionItemKind.Event = 23; + CompletionItemKind.Operator = 24; + CompletionItemKind.TypeParameter = 25; + })( + CompletionItemKind || + (exports.CompletionItemKind = CompletionItemKind = {}) + ); -/** chainable - * MarkdownIt.use(plugin, params) - * - * Load specified plugin with given params into current parser instance. - * It's just a sugar to call `plugin(md, params)` with curring. - * - * ##### Example - * - * ```javascript - * var iterator = require('markdown-it-for-inline'); - * var md = require('markdown-it')() - * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { - * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); - * }); - * ``` - **/ -MarkdownIt.prototype.use = function (plugin /*, params, ... */) { - const args = [this].concat(Array.prototype.slice.call(arguments, 1)); - plugin.apply(plugin, args); - return this; -}; + /***/ + }, -/** internal - * MarkdownIt.parse(src, env) -> Array - * - src (String): source string - * - env (Object): environment sandbox - * - * Parse input string and return list of block tokens (special token type - * "inline" will contain list of inline tokens). You should not call this - * method directly, until you write custom renderer (for example, to produce - * AST). - * - * `env` is used to pass data between "distributed" rules and return additional - * metadata like reference info, needed for the renderer. It also can be used to - * inject data in specific cases. Usually, you will be ok to pass `{}`, - * and then pass updated object to renderer. - **/ -MarkdownIt.prototype.parse = function (src, env) { - if (typeof src !== 'string') { - throw new Error('Input data should be a String'); - } - const state = new this.core.State(src, this, env); - this.core.process(state); - return state.tokens; -}; + /***/ "../../graphql-language-service/esm/utils/Range.js": + /*!*********************************************************!*\ + !*** ../../graphql-language-service/esm/utils/Range.js ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.Range = exports.Position = void 0; + exports.locToRange = locToRange; + exports.offsetToPosition = offsetToPosition; + class Range { + constructor(start, end) { + this.containsPosition = (position) => { + if (this.start.line === position.line) { + return this.start.character <= position.character; + } + if (this.end.line === position.line) { + return this.end.character >= position.character; + } + return ( + this.start.line <= position.line && + this.end.line >= position.line + ); + }; + this.start = start; + this.end = end; + } + setStart(line, character) { + this.start = new Position(line, character); + } + setEnd(line, character) { + this.end = new Position(line, character); + } + } + exports.Range = Range; + class Position { + constructor(line, character) { + this.lessThanOrEqualTo = (position) => + this.line < position.line || + (this.line === position.line && + this.character <= position.character); + this.line = line; + this.character = character; + } + setLine(line) { + this.line = line; + } + setCharacter(character) { + this.character = character; + } + } + exports.Position = Position; + function offsetToPosition(text, loc) { + const EOL = "\n"; + const buf = text.slice(0, loc); + const lines = buf.split(EOL).length - 1; + const lastLineIndex = buf.lastIndexOf(EOL); + return new Position(lines, loc - lastLineIndex - 1); + } + function locToRange(text, loc) { + const start = offsetToPosition(text, loc.start); + const end = offsetToPosition(text, loc.end); + return new Range(start, end); + } -/** - * MarkdownIt.render(src [, env]) -> String - * - src (String): source string - * - env (Object): environment sandbox - * - * Render markdown string into html. It does all magic for you :). - * - * `env` can be used to inject additional metadata (`{}` by default). - * But you will not need it with high probability. See also comment - * in [[MarkdownIt.parse]]. - **/ -MarkdownIt.prototype.render = function (src, env) { - env = env || {}; - return this.renderer.render(this.parse(src, env), this.options, env); -}; + /***/ + }, -/** internal - * MarkdownIt.parseInline(src, env) -> Array - * - src (String): source string - * - env (Object): environment sandbox - * - * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the - * block tokens list with the single `inline` element, containing parsed inline - * tokens in `children` property. Also updates `env` object. - **/ -MarkdownIt.prototype.parseInline = function (src, env) { - const state = new this.core.State(src, this, env); - state.inlineMode = true; - this.core.process(state); - return state.tokens; -}; + /***/ "../../graphql-language-service/esm/utils/collectVariables.js": + /*!********************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/collectVariables.js ***! + \********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.collectVariables = collectVariables; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function collectVariables(schema, documentAST) { + const variableToType = Object.create(null); + for (const definition of documentAST.definitions) { + if (definition.kind === "OperationDefinition") { + const { variableDefinitions } = definition; + if (variableDefinitions) { + for (const { variable, type } of variableDefinitions) { + const inputType = (0, _graphql.typeFromAST)(schema, type); + if (inputType) { + variableToType[variable.name.value] = inputType; + } else if ( + type.kind === _graphql.Kind.NAMED_TYPE && + type.name.value === "Float" + ) { + variableToType[variable.name.value] = _graphql.GraphQLFloat; + } + } + } + } + } + return variableToType; + } -/** - * MarkdownIt.renderInline(src [, env]) -> String - * - src (String): source string - * - env (Object): environment sandbox - * - * Similar to [[MarkdownIt.render]] but for single paragraph content. Result - * will NOT be wrapped into `

    ` tags. - **/ -MarkdownIt.prototype.renderInline = function (src, env) { - env = env || {}; - return this.renderer.render(this.parseInline(src, env), this.options, env); -}; -module.exports = MarkdownIt; + /***/ + }, -/***/ }), + /***/ "../../graphql-language-service/esm/utils/fragmentDependencies.js": + /*!************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/fragmentDependencies.js ***! + \************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getFragmentDependenciesForAST = + exports.getFragmentDependencies = void 0; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _nullthrows = _interopRequireDefault( + __webpack_require__( + /*! nullthrows */ "../../../node_modules/nullthrows/nullthrows.js" + ) + ); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + const getFragmentDependencies = ( + operationString, + fragmentDefinitions + ) => { + if (!fragmentDefinitions) { + return []; + } + let parsedOperation; + try { + parsedOperation = (0, _graphql.parse)(operationString); + } catch (_a) { + return []; + } + return getFragmentDependenciesForAST( + parsedOperation, + fragmentDefinitions + ); + }; + exports.getFragmentDependencies = getFragmentDependencies; + const getFragmentDependenciesForAST = ( + parsedOperation, + fragmentDefinitions + ) => { + if (!fragmentDefinitions) { + return []; + } + const existingFrags = new Map(); + const referencedFragNames = new Set(); + (0, _graphql.visit)(parsedOperation, { + FragmentDefinition(node) { + existingFrags.set(node.name.value, true); + }, + FragmentSpread(node) { + if (!referencedFragNames.has(node.name.value)) { + referencedFragNames.add(node.name.value); + } + }, + }); + const asts = new Set(); + for (const name of referencedFragNames) { + if (!existingFrags.has(name) && fragmentDefinitions.has(name)) { + asts.add((0, _nullthrows.default)(fragmentDefinitions.get(name))); + } + } + const referencedFragments = []; + for (const ast of asts) { + (0, _graphql.visit)(ast, { + FragmentSpread(node) { + if ( + !referencedFragNames.has(node.name.value) && + fragmentDefinitions.get(node.name.value) + ) { + asts.add( + (0, _nullthrows.default)( + fragmentDefinitions.get(node.name.value) + ) + ); + referencedFragNames.add(node.name.value); + } + }, + }); + if (!existingFrags.has(ast.name.value)) { + referencedFragments.push(ast); + } + } + return referencedFragments; + }; + exports.getFragmentDependenciesForAST = getFragmentDependenciesForAST; -/***/ "../node_modules/mdurl/build/index.cjs.js": -/*!************************************************!*\ - !*** ../node_modules/mdurl/build/index.cjs.js ***! - \************************************************/ -/***/ (function(__unused_webpack_module, exports) { + /***/ + }, + /***/ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js": + /*!************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getASTNodeAtPosition.js ***! + \************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.getASTNodeAtPosition = getASTNodeAtPosition; + exports.pointToOffset = pointToOffset; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + function getASTNodeAtPosition(query, ast, point) { + const offset = pointToOffset(query, point); + let nodeContainingPosition; + (0, _graphql.visit)(ast, { + enter(node) { + if ( + node.kind !== "Name" && + node.loc && + node.loc.start <= offset && + offset <= node.loc.end + ) { + nodeContainingPosition = node; + } else { + return false; + } + }, + leave(node) { + if ( + node.loc && + node.loc.start <= offset && + offset <= node.loc.end + ) { + return false; + } + }, + }); + return nodeContainingPosition; + } + function pointToOffset(text, point) { + const linesUntilPosition = text.split("\n").slice(0, point.line); + return ( + point.character + + linesUntilPosition + .map((line) => line.length + 1) + .reduce((a, b) => a + b, 0) + ); + } + /***/ + }, -/* eslint-disable no-bitwise */ -const decodeCache = {}; -function getDecodeCache(exclude) { - let cache = decodeCache[exclude]; - if (cache) { - return cache; - } - cache = decodeCache[exclude] = []; - for (let i = 0; i < 128; i++) { - const ch = String.fromCharCode(i); - cache.push(ch); - } - for (let i = 0; i < exclude.length; i++) { - const ch = exclude.charCodeAt(i); - cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2); - } - return cache; -} - -// Decode percent-encoded string. -// -function decode(string, exclude) { - if (typeof exclude !== 'string') { - exclude = decode.defaultChars; - } - const cache = getDecodeCache(exclude); - return string.replace(/(%[a-f0-9]{2})+/gi, function (seq) { - let result = ''; - for (let i = 0, l = seq.length; i < l; i += 3) { - const b1 = parseInt(seq.slice(i + 1, i + 3), 16); - if (b1 < 0x80) { - result += cache[b1]; - continue; - } - if ((b1 & 0xE0) === 0xC0 && i + 3 < l) { - // 110xxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - if ((b2 & 0xC0) === 0x80) { - const chr = b1 << 6 & 0x7C0 | b2 & 0x3F; - if (chr < 0x80) { - result += '\ufffd\ufffd'; - } else { - result += String.fromCharCode(chr); - } - i += 3; - continue; + /***/ "../../graphql-language-service/esm/utils/getOperationFacts.js": + /*!*********************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getOperationFacts.js ***! + \*********************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports["default"] = getOperationFacts; + exports.getOperationASTFacts = getOperationASTFacts; + exports.getQueryFacts = void 0; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + var _collectVariables = __webpack_require__( + /*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js" + ); + function getOperationASTFacts(documentAST, schema) { + const variableToType = schema + ? (0, _collectVariables.collectVariables)(schema, documentAST) + : undefined; + const operations = []; + (0, _graphql.visit)(documentAST, { + OperationDefinition(node) { + operations.push(node); + }, + }); + return { + variableToType, + operations, + }; } - } - if ((b1 & 0xF0) === 0xE0 && i + 6 < l) { - // 1110xxxx 10xxxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - const b3 = parseInt(seq.slice(i + 7, i + 9), 16); - if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { - const chr = b1 << 12 & 0xF000 | b2 << 6 & 0xFC0 | b3 & 0x3F; - if (chr < 0x800 || chr >= 0xD800 && chr <= 0xDFFF) { - result += '\ufffd\ufffd\ufffd'; - } else { - result += String.fromCharCode(chr); + function getOperationFacts(schema, documentString) { + if (!documentString) { + return; + } + try { + const documentAST = (0, _graphql.parse)(documentString); + return Object.assign( + Object.assign({}, getOperationASTFacts(documentAST, schema)), + { + documentAST, + } + ); + } catch (_a) { + return; } - i += 6; - continue; } - } - if ((b1 & 0xF8) === 0xF0 && i + 9 < l) { - // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - const b3 = parseInt(seq.slice(i + 7, i + 9), 16); - const b4 = parseInt(seq.slice(i + 10, i + 12), 16); - if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) { - let chr = b1 << 18 & 0x1C0000 | b2 << 12 & 0x3F000 | b3 << 6 & 0xFC0 | b4 & 0x3F; - if (chr < 0x10000 || chr > 0x10FFFF) { - result += '\ufffd\ufffd\ufffd\ufffd'; + const getQueryFacts = (exports.getQueryFacts = getOperationFacts); + + /***/ + }, + + /***/ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js": + /*!**************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getVariablesJSONSchema.js ***! + \**************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.defaultJSONSchemaOptions = void 0; + exports.getVariablesJSONSchema = getVariablesJSONSchema; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const defaultJSONSchemaOptions = (exports.defaultJSONSchemaOptions = { + useMarkdownDescription: false, + }); + function text(into, newText) { + into.push(newText); + } + function renderType(into, t) { + if ((0, _graphql.isNonNullType)(t)) { + renderType(into, t.ofType); + text(into, "!"); + } else if ((0, _graphql.isListType)(t)) { + text(into, "["); + renderType(into, t.ofType); + text(into, "]"); } else { - chr -= 0x10000; - result += String.fromCharCode(0xD800 + (chr >> 10), 0xDC00 + (chr & 0x3FF)); + text(into, t.name); + } + } + function renderDefinitionDescription(t, useMarkdown, description) { + const into = []; + const type = "type" in t ? t.type : t; + if ("type" in t && t.description) { + text(into, t.description); + text(into, "\n\n"); + } + text(into, renderTypeToString(type, useMarkdown)); + if (description) { + text(into, "\n"); + text(into, description); + } else if ( + !(0, _graphql.isScalarType)(type) && + "description" in type && + type.description + ) { + text(into, "\n"); + text(into, type.description); + } else if ( + "ofType" in type && + !(0, _graphql.isScalarType)(type.ofType) && + "description" in type.ofType && + type.ofType.description + ) { + text(into, "\n"); + text(into, type.ofType.description); + } + return into.join(""); + } + function renderTypeToString(t, useMarkdown) { + const into = []; + if (useMarkdown) { + text(into, "```graphql\n"); + } + renderType(into, t); + if (useMarkdown) { + text(into, "\n```"); + } + return into.join(""); + } + const defaultScalarTypesMap = { + Int: { + type: "integer", + }, + String: { + type: "string", + }, + Float: { + type: "number", + }, + ID: { + type: "string", + }, + Boolean: { + type: "boolean", + }, + DateTime: { + type: "string", + }, + }; + class Marker { + constructor() { + this.set = new Set(); + } + mark(name) { + if (this.set.has(name)) { + return false; + } + this.set.add(name); + return true; } - i += 9; - continue; - } - } - result += '\ufffd'; - } - return result; - }); -} -decode.defaultChars = ';/?:@&=+$,#'; -decode.componentChars = ''; -const encodeCache = {}; - -// Create a lookup array where anything but characters in `chars` string -// and alphanumeric chars is percent-encoded. -// -function getEncodeCache(exclude) { - let cache = encodeCache[exclude]; - if (cache) { - return cache; - } - cache = encodeCache[exclude] = []; - for (let i = 0; i < 128; i++) { - const ch = String.fromCharCode(i); - if (/^[0-9a-z]$/i.test(ch)) { - // always allow unencoded alphanumeric characters - cache.push(ch); - } else { - cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2)); - } - } - for (let i = 0; i < exclude.length; i++) { - cache[exclude.charCodeAt(i)] = exclude[i]; - } - return cache; -} - -// Encode unsafe characters with percent-encoding, skipping already -// encoded sequences. -// -// - string - string to encode -// - exclude - list of characters to ignore (in addition to a-zA-Z0-9) -// - keepEscaped - don't encode '%' in a correct escape sequence (default: true) -// -function encode(string, exclude, keepEscaped) { - if (typeof exclude !== 'string') { - // encode(string, keepEscaped) - keepEscaped = exclude; - exclude = encode.defaultChars; - } - if (typeof keepEscaped === 'undefined') { - keepEscaped = true; - } - const cache = getEncodeCache(exclude); - let result = ''; - for (let i = 0, l = string.length; i < l; i++) { - const code = string.charCodeAt(i); - if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { - if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { - result += string.slice(i, i + 3); - i += 2; - continue; - } - } - if (code < 128) { - result += cache[code]; - continue; - } - if (code >= 0xD800 && code <= 0xDFFF) { - if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) { - const nextCode = string.charCodeAt(i + 1); - if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) { - result += encodeURIComponent(string[i] + string[i + 1]); - i++; - continue; } - } - result += '%EF%BF%BD'; - continue; - } - result += encodeURIComponent(string[i]); - } - return result; -} -encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; -encode.componentChars = "-_.!~*'()"; -function format(url) { - let result = ''; - result += url.protocol || ''; - result += url.slashes ? '//' : ''; - result += url.auth ? url.auth + '@' : ''; - if (url.hostname && url.hostname.indexOf(':') !== -1) { - // ipv6 address - result += '[' + url.hostname + ']'; - } else { - result += url.hostname || ''; - } - result += url.port ? ':' + url.port : ''; - result += url.pathname || ''; - result += url.search || ''; - result += url.hash || ''; - return result; -} - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// -// Changes from joyent/node: -// -// 1. No leading slash in paths, -// e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` -// -// 2. Backslashes are not replaced with slashes, -// so `http:\\example.org\` is treated like a relative path -// -// 3. Trailing colon is treated like a part of the path, -// i.e. in `http://example.org:foo` pathname is `:foo` -// -// 4. Nothing is URL-encoded in the resulting object, -// (in joyent/node some chars in auth and paths are encoded) -// -// 5. `url.parse()` does not have `parseQueryString` argument -// -// 6. Removed extraneous result properties: `host`, `path`, `query`, etc., -// which can be constructed using other parts of the url. -// - -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -const protocolPattern = /^([a-z0-9.+-]+:)/i; -const portPattern = /:[0-9]*$/; - -// Special case for a simple path URL -/* eslint-disable-next-line no-useless-escape */ -const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; - -// RFC 2396: characters reserved for delimiting URLs. -// We actually just auto-escape these. -const delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t']; - -// RFC 2396: characters not allowed for various reasons. -const unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims); - -// Allowed by RFCs, but cause of XSS attacks. Always escape these. -const autoEscape = ['\''].concat(unwise); -// Characters that are never ever allowed in a hostname. -// Note that any invalid chars are also handled, but these -// are the ones that are *expected* to be seen, so we fast-path -// them. -const nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape); -const hostEndingChars = ['/', '?', '#']; -const hostnameMaxLen = 255; -const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; -const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; -// protocols that can allow "unsafe" and "unwise" chars. -// protocols that never have a hostname. -const hostlessProtocol = { - javascript: true, - 'javascript:': true -}; -// protocols that always contain a // bit. -const slashedProtocol = { - http: true, - https: true, - ftp: true, - gopher: true, - file: true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true -}; -function urlParse(url, slashesDenoteHost) { - if (url && url instanceof Url) return url; - const u = new Url(); - u.parse(url, slashesDenoteHost); - return u; -} -Url.prototype.parse = function (url, slashesDenoteHost) { - let lowerProto, hec, slashes; - let rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - const simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - } - return this; - } - } - let proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - lowerProto = proto.toLowerCase(); - this.protocol = proto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - /* eslint-disable-next-line no-useless-escape */ - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) { - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - let hostEnd = -1; - for (let i = 0; i < hostEndingChars.length; i++) { - hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { - hostEnd = hec; - } - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - let auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = auth; - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (let i = 0; i < nonHostChars.length; i++) { - hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { - hostEnd = hec; - } - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) { - hostEnd = rest.length; - } - if (rest[hostEnd - 1] === ':') { - hostEnd--; - } - const host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(host); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - const ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - const hostparts = this.hostname.split(/\./); - for (let i = 0, l = hostparts.length; i < l; i++) { - const part = hostparts[i]; - if (!part) { - continue; - } - if (!part.match(hostnamePartPattern)) { - let newpart = ''; - for (let j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; + function getJSONSchemaFromGraphQLType(fieldOrType, options) { + var _a, _b; + let definition = Object.create(null); + const definitions = Object.create(null); + const isField = "type" in fieldOrType; + const type = isField ? fieldOrType.type : fieldOrType; + const baseType = (0, _graphql.isNonNullType)(type) + ? type.ofType + : type; + const required = (0, _graphql.isNonNullType)(type); + if ((0, _graphql.isScalarType)(baseType)) { + if ( + (_a = + options === null || options === void 0 + ? void 0 + : options.scalarSchemas) === null || _a === void 0 + ? void 0 + : _a[baseType.name] + ) { + definition = JSON.parse( + JSON.stringify(options.scalarSchemas[baseType.name]) + ); } else { - newpart += part[j]; + definition.type = ["string", "number", "boolean", "integer"]; } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - const validParts = hostparts.slice(0, i); - const notHost = hostparts.slice(i + 1); - const bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); + if (!required) { + if (Array.isArray(definition.type)) { + definition.type.push("null"); + } else if (definition.type) { + definition.type = [definition.type, "null"]; + } else if (definition.enum) { + definition.enum.push(null); + } else if (definition.oneOf) { + definition.oneOf.push({ + type: "null", + }); + } else { + definition = { + oneOf: [ + definition, + { + type: "null", + }, + ], + }; + } } - if (notHost.length) { - rest = notHost.join('.') + rest; + } else if ((0, _graphql.isEnumType)(baseType)) { + definition.enum = baseType.getValues().map((val) => val.name); + if (!required) { + definition.enum.push(null); } - this.hostname = validParts.join('.'); - break; + } else if ((0, _graphql.isListType)(baseType)) { + if (required) { + definition.type = "array"; + } else { + definition.type = ["array", "null"]; + } + const { definition: def, definitions: defs } = + getJSONSchemaFromGraphQLType(baseType.ofType, options); + definition.items = def; + if (defs) { + for (const defName of Object.keys(defs)) { + definitions[defName] = defs[defName]; + } + } + } else if ((0, _graphql.isInputObjectType)(baseType)) { + if (required) { + definition.$ref = `#/definitions/${baseType.name}`; + } else { + definition.oneOf = [ + { + $ref: `#/definitions/${baseType.name}`, + }, + { + type: "null", + }, + ]; + } + if ( + (_b = + options === null || options === void 0 + ? void 0 + : options.definitionMarker) === null || _b === void 0 + ? void 0 + : _b.mark(baseType.name) + ) { + const fields = baseType.getFields(); + const fieldDef = { + type: "object", + properties: {}, + required: [], + }; + fieldDef.description = renderDefinitionDescription(baseType); + if ( + options === null || options === void 0 + ? void 0 + : options.useMarkdownDescription + ) { + fieldDef.markdownDescription = renderDefinitionDescription( + baseType, + true + ); + } + for (const fieldName of Object.keys(fields)) { + const field = fields[fieldName]; + const { + required: fieldRequired, + definition: fieldDefinition, + definitions: typeDefinitions, + } = getJSONSchemaFromGraphQLType(field, options); + fieldDef.properties[fieldName] = fieldDefinition; + if (fieldRequired) { + fieldDef.required.push(fieldName); + } + if (typeDefinitions) { + for (const [defName, value] of Object.entries( + typeDefinitions + )) { + definitions[defName] = value; + } + } + } + definitions[baseType.name] = fieldDef; + } + } + if ( + "defaultValue" in fieldOrType && + fieldOrType.defaultValue !== undefined + ) { + definition.default = fieldOrType.defaultValue; + } + const { description } = definition; + definition.description = renderDefinitionDescription( + fieldOrType, + false, + description + ); + if ( + options === null || options === void 0 + ? void 0 + : options.useMarkdownDescription + ) { + definition.markdownDescription = renderDefinitionDescription( + fieldOrType, + true, + description + ); } + return { + required, + definition, + definitions, + }; + } + function getVariablesJSONSchema(variableToType, options) { + var _a; + const jsonSchema = { + $schema: "http://json-schema.org/draft-04/schema", + type: "object", + properties: {}, + required: [], + }; + const runtimeOptions = Object.assign(Object.assign({}, options), { + definitionMarker: new Marker(), + scalarSchemas: Object.assign( + Object.assign({}, defaultScalarTypesMap), + options === null || options === void 0 + ? void 0 + : options.scalarSchemas + ), + }); + if (variableToType) { + for (const [variableName, type] of Object.entries(variableToType)) { + const { definition, required, definitions } = + getJSONSchemaFromGraphQLType(type, runtimeOptions); + jsonSchema.properties[variableName] = definition; + if (required) { + (_a = jsonSchema.required) === null || _a === void 0 + ? void 0 + : _a.push(variableName); + } + if (definitions) { + jsonSchema.definitions = Object.assign( + Object.assign( + {}, + jsonSchema === null || jsonSchema === void 0 + ? void 0 + : jsonSchema.definitions + ), + definitions + ); + } + } + } + return jsonSchema; } - } - } - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - } - } - - // chop off from the tail first. - const hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - const qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - rest = rest.slice(0, qm); - } - if (rest) { - this.pathname = rest; - } - if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { - this.pathname = ''; - } - return this; -}; -Url.prototype.parseHost = function (host) { - let port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) { - this.hostname = host; - } -}; -exports.decode = decode; -exports.encode = encode; -exports.format = format; -exports.parse = urlParse; - -/***/ }), - -/***/ "../node_modules/uc.micro/build/index.cjs.js": -/*!***************************************************!*\ - !*** ../node_modules/uc.micro/build/index.cjs.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -var regex$5 = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var regex$4 = /[\0-\x1F\x7F-\x9F]/; -var regex$3 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/; -var regex$2 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/; -var regex$1 = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/; -var regex = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; -exports.Any = regex$5; -exports.Cc = regex$4; -exports.Cf = regex$3; -exports.P = regex$2; -exports.S = regex$1; -exports.Z = regex; - -/***/ }), - -/***/ "./components/GraphiQL.tsx": -/*!*********************************!*\ - !*** ./components/GraphiQL.tsx ***! - \*********************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.GraphiQL = GraphiQL; -exports.GraphiQLInterface = GraphiQLInterface; -var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); -var _react2 = __webpack_require__(/*! @graphiql/react */ "../../graphiql-react/dist/index.js"); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } -function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** - * Copyright (c) 2020 GraphQL Contributors. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -const majorVersion = parseInt(_react.default.version.slice(0, 2), 10); -if (majorVersion < 16) { - throw new Error(['GraphiQL 0.18.0 and after is not compatible with React 15 or below.', 'If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:', 'https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49'].join('\n')); -} - -/** - * API docs for this live here: - * - * https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops - */ - -/** - * The top-level React component for GraphiQL, intended to encompass the entire - * browser viewport. - * - * @see https://github.com/graphql/graphiql#usage - */ - -function GraphiQL({ - dangerouslyAssumeSchemaIsValid, - defaultQuery, - defaultTabs, - externalFragments, - fetcher, - getDefaultFieldNames, - headers, - inputValueDeprecation, - introspectionQueryName, - maxHistoryLength, - onEditOperationName, - onSchemaChange, - onTabChange, - onTogglePluginVisibility, - operationName, - plugins, - query, - response, - schema, - schemaDescription, - shouldPersistHeaders, - storage, - validationRules, - variables, - visiblePlugin, - defaultHeaders, - ...props -}) { - var _props$disableTabs; - // Ensure props are correct - if (typeof fetcher !== 'function') { - throw new TypeError('The `GraphiQL` component requires a `fetcher` function to be passed as prop.'); - } - return /*#__PURE__*/_react.default.createElement(_react2.GraphiQLProvider, { - getDefaultFieldNames: getDefaultFieldNames, - dangerouslyAssumeSchemaIsValid: dangerouslyAssumeSchemaIsValid, - defaultQuery: defaultQuery, - defaultHeaders: defaultHeaders, - defaultTabs: defaultTabs, - externalFragments: externalFragments, - fetcher: fetcher, - headers: headers, - inputValueDeprecation: inputValueDeprecation, - introspectionQueryName: introspectionQueryName, - maxHistoryLength: maxHistoryLength, - onEditOperationName: onEditOperationName, - onSchemaChange: onSchemaChange, - onTabChange: onTabChange, - onTogglePluginVisibility: onTogglePluginVisibility, - plugins: plugins, - visiblePlugin: visiblePlugin, - operationName: operationName, - query: query, - response: response, - schema: schema, - schemaDescription: schemaDescription, - shouldPersistHeaders: shouldPersistHeaders, - storage: storage, - validationRules: validationRules, - variables: variables - }, /*#__PURE__*/_react.default.createElement(GraphiQLInterface, _extends({ - showPersistHeadersSettings: shouldPersistHeaders !== false, - disableTabs: (_props$disableTabs = props.disableTabs) !== null && _props$disableTabs !== void 0 ? _props$disableTabs : false, - forcedTheme: props.forcedTheme - }, props))); -} - -// Export main windows/panes to be used separately if desired. -GraphiQL.Logo = GraphiQLLogo; -GraphiQL.Toolbar = GraphiQLToolbar; -GraphiQL.Footer = GraphiQLFooter; -const THEMES = ['light', 'dark', 'system']; -function GraphiQLInterface(props) { - var _props$isHeadersEdito, _pluginContext$visibl, _props$toolbar, _props$toolbar2; - const isHeadersEditorEnabled = (_props$isHeadersEdito = props.isHeadersEditorEnabled) !== null && _props$isHeadersEdito !== void 0 ? _props$isHeadersEdito : true; - const editorContext = (0, _react2.useEditorContext)({ - nonNull: true - }); - const executionContext = (0, _react2.useExecutionContext)({ - nonNull: true - }); - const schemaContext = (0, _react2.useSchemaContext)({ - nonNull: true - }); - const storageContext = (0, _react2.useStorageContext)(); - const pluginContext = (0, _react2.usePluginContext)(); - const forcedTheme = (0, _react.useMemo)(() => props.forcedTheme && THEMES.includes(props.forcedTheme) ? props.forcedTheme : undefined, [props.forcedTheme]); - const copy = (0, _react2.useCopyQuery)({ - onCopyQuery: props.onCopyQuery - }); - const merge = (0, _react2.useMergeQuery)(); - const prettify = (0, _react2.usePrettifyEditors)(); - const { - theme, - setTheme - } = (0, _react2.useTheme)(); - (0, _react.useEffect)(() => { - if (forcedTheme === 'system') { - setTheme(null); - } else if (forcedTheme === 'light' || forcedTheme === 'dark') { - setTheme(forcedTheme); - } - }, [forcedTheme, setTheme]); - const PluginContent = pluginContext === null || pluginContext === void 0 ? void 0 : (_pluginContext$visibl = pluginContext.visiblePlugin) === null || _pluginContext$visibl === void 0 ? void 0 : _pluginContext$visibl.content; - const pluginResize = (0, _react2.useDragResize)({ - defaultSizeRelation: 1 / 3, - direction: 'horizontal', - initiallyHidden: pluginContext !== null && pluginContext !== void 0 && pluginContext.visiblePlugin ? undefined : 'first', - onHiddenElementChange(resizableElement) { - if (resizableElement === 'first') { - pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.setVisiblePlugin(null); - } - }, - sizeThresholdSecond: 200, - storageKey: 'docExplorerFlex' - }); - const editorResize = (0, _react2.useDragResize)({ - direction: 'horizontal', - storageKey: 'editorFlex' - }); - const editorToolsResize = (0, _react2.useDragResize)({ - defaultSizeRelation: 3, - direction: 'vertical', - initiallyHidden: (() => { - if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { - return; - } - if (typeof props.defaultEditorToolsVisibility === 'boolean') { - return props.defaultEditorToolsVisibility ? undefined : 'second'; - } - return editorContext.initialVariables || editorContext.initialHeaders ? undefined : 'second'; - })(), - sizeThresholdSecond: 60, - storageKey: 'secondaryEditorFlex' - }); - const [activeSecondaryEditor, setActiveSecondaryEditor] = (0, _react.useState)(() => { - if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { - return props.defaultEditorToolsVisibility; - } - return !editorContext.initialVariables && editorContext.initialHeaders && isHeadersEditorEnabled ? 'headers' : 'variables'; - }); - const [showDialog, setShowDialog] = (0, _react.useState)(null); - const [clearStorageStatus, setClearStorageStatus] = (0, _react.useState)(null); - const children = _react.default.Children.toArray(props.children); - const logo = children.find(child => isChildComponentType(child, GraphiQL.Logo)) || /*#__PURE__*/_react.default.createElement(GraphiQL.Logo, null); - const toolbar = children.find(child => isChildComponentType(child, GraphiQL.Toolbar)) || /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { - onClick: prettify, - label: "Prettify query (Shift-Ctrl-P)" - }, /*#__PURE__*/_react.default.createElement(_react2.PrettifyIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true" - })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { - onClick: merge, - label: "Merge fragments into query (Shift-Ctrl-M)" - }, /*#__PURE__*/_react.default.createElement(_react2.MergeIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true" - })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { - onClick: copy, - label: "Copy query (Shift-Ctrl-C)" - }, /*#__PURE__*/_react.default.createElement(_react2.CopyIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true" - })), (_props$toolbar = props.toolbar) === null || _props$toolbar === void 0 ? void 0 : _props$toolbar.additionalContent, ((_props$toolbar2 = props.toolbar) === null || _props$toolbar2 === void 0 ? void 0 : _props$toolbar2.additionalComponent) && /*#__PURE__*/_react.default.createElement(props.toolbar.additionalComponent, null)); - const footer = children.find(child => isChildComponentType(child, GraphiQL.Footer)); - const onClickReference = (0, _react.useCallback)(() => { - if (pluginResize.hiddenElement === 'first') { - pluginResize.setHiddenElement(null); - } - }, [pluginResize]); - const handleClearData = (0, _react.useCallback)(() => { - try { - storageContext === null || storageContext === void 0 ? void 0 : storageContext.clear(); - setClearStorageStatus('success'); - } catch { - setClearStorageStatus('error'); - } - }, [storageContext]); - const handlePersistHeaders = (0, _react.useCallback)(event => { - editorContext.setShouldPersistHeaders(event.currentTarget.dataset.value === 'true'); - }, [editorContext]); - const handleChangeTheme = (0, _react.useCallback)(event => { - const selectedTheme = event.currentTarget.dataset.theme; - setTheme(selectedTheme || null); - }, [setTheme]); - const handleAddTab = editorContext.addTab; - const handleRefetchSchema = schemaContext.introspect; - const handleReorder = editorContext.moveTab; - const handleShowDialog = (0, _react.useCallback)(event => { - setShowDialog(event.currentTarget.dataset.value); - }, []); - const handlePluginClick = (0, _react.useCallback)(e => { - const context = pluginContext; - const pluginIndex = Number(e.currentTarget.dataset.index); - const plugin = context.plugins.find((_, index) => pluginIndex === index); - const isVisible = plugin === context.visiblePlugin; - if (isVisible) { - context.setVisiblePlugin(null); - pluginResize.setHiddenElement('first'); - } else { - context.setVisiblePlugin(plugin); - pluginResize.setHiddenElement(null); - } - }, [pluginContext, pluginResize]); - const handleToolsTabClick = (0, _react.useCallback)(event => { - if (editorToolsResize.hiddenElement === 'second') { - editorToolsResize.setHiddenElement(null); - } - setActiveSecondaryEditor(event.currentTarget.dataset.name); - }, [editorToolsResize]); - const toggleEditorTools = (0, _react.useCallback)(() => { - editorToolsResize.setHiddenElement(editorToolsResize.hiddenElement === 'second' ? null : 'second'); - }, [editorToolsResize]); - const handleOpenShortKeysDialog = (0, _react.useCallback)(isOpen => { - if (!isOpen) { - setShowDialog(null); - } - }, []); - const handleOpenSettingsDialog = (0, _react.useCallback)(isOpen => { - if (!isOpen) { - setShowDialog(null); - setClearStorageStatus(null); - } - }, []); - const addTab = /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Add tab" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: "graphiql-tab-add", - onClick: handleAddTab, - "aria-label": "Add tab" - }, /*#__PURE__*/_react.default.createElement(_react2.PlusIcon, { - "aria-hidden": "true" - }))); - const className = props.className ? ` ${props.className}` : ''; - return /*#__PURE__*/_react.default.createElement(_react2.Tooltip.Provider, null, /*#__PURE__*/_react.default.createElement("div", { - "data-testid": "graphiql-container", - className: `graphiql-container${className}` - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-sidebar" - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-sidebar-section" - }, pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.plugins.map((plugin, index) => { - const isVisible = plugin === pluginContext.visiblePlugin; - const label = `${isVisible ? 'Hide' : 'Show'} ${plugin.title}`; - const Icon = plugin.icon; - return /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - key: plugin.title, - label: label - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: isVisible ? 'active' : '', - onClick: handlePluginClick, - "data-index": index, - "aria-label": label - }, /*#__PURE__*/_react.default.createElement(Icon, { - "aria-hidden": "true" - }))); - })), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-sidebar-section" - }, /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Re-fetch GraphQL schema" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - disabled: schemaContext.isFetching, - onClick: handleRefetchSchema, - "aria-label": "Re-fetch GraphQL schema" - }, /*#__PURE__*/_react.default.createElement(_react2.ReloadIcon, { - className: schemaContext.isFetching ? 'graphiql-spin' : '', - "aria-hidden": "true" - }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Open short keys dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - "data-value": "short-keys", - onClick: handleShowDialog, - "aria-label": "Open short keys dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.KeyboardShortcutIcon, { - "aria-hidden": "true" - }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Open settings dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - "data-value": "settings", - onClick: handleShowDialog, - "aria-label": "Open settings dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.SettingsIcon, { - "aria-hidden": "true" - }))))), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-main" - }, /*#__PURE__*/_react.default.createElement("div", { - ref: pluginResize.firstRef, - style: { - // Make sure the container shrinks when containing long - // non-breaking texts - minWidth: '200px' - } - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-plugin" - }, PluginContent ? /*#__PURE__*/_react.default.createElement(PluginContent, null) : null)), (pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.visiblePlugin) && /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-horizontal-drag-bar", - ref: pluginResize.dragBarRef - }), /*#__PURE__*/_react.default.createElement("div", { - ref: pluginResize.secondRef, - className: "graphiql-sessions" - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-session-header" - }, !props.disableTabs && /*#__PURE__*/_react.default.createElement(_react2.Tabs, { - values: editorContext.tabs, - onReorder: handleReorder, - "aria-label": "Select active operation" - }, editorContext.tabs.length > 1 && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, editorContext.tabs.map((tab, index) => /*#__PURE__*/_react.default.createElement(_react2.Tab, { - key: tab.id, - value: tab, - isActive: index === editorContext.activeTabIndex - }, /*#__PURE__*/_react.default.createElement(_react2.Tab.Button, { - "aria-controls": "graphiql-session", - id: `graphiql-session-tab-${index}`, - onClick: () => { - executionContext.stop(); - editorContext.changeTab(index); - } - }, tab.title), /*#__PURE__*/_react.default.createElement(_react2.Tab.Close, { - onClick: () => { - if (editorContext.activeTabIndex === index) { - executionContext.stop(); - } - editorContext.closeTab(index); - } - }))), addTab)), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-session-header-right" - }, editorContext.tabs.length === 1 && addTab, logo)), /*#__PURE__*/_react.default.createElement("div", { - role: "tabpanel", - id: "graphiql-session", - className: "graphiql-session", - "aria-labelledby": `graphiql-session-tab-${editorContext.activeTabIndex}` - }, /*#__PURE__*/_react.default.createElement("div", { - ref: editorResize.firstRef - }, /*#__PURE__*/_react.default.createElement("div", { - className: `graphiql-editors${editorContext.tabs.length === 1 ? ' full-height' : ''}` - }, /*#__PURE__*/_react.default.createElement("div", { - ref: editorToolsResize.firstRef - }, /*#__PURE__*/_react.default.createElement("section", { - className: "graphiql-query-editor", - "aria-label": "Query Editor" - }, /*#__PURE__*/_react.default.createElement(_react2.QueryEditor, { - editorTheme: props.editorTheme, - keyMap: props.keyMap, - onClickReference: onClickReference, - onCopyQuery: props.onCopyQuery, - onEdit: props.onEditQuery, - readOnly: props.readOnly - }), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-toolbar", - role: "toolbar", - "aria-label": "Editor Commands" - }, /*#__PURE__*/_react.default.createElement(_react2.ExecuteButton, null), toolbar))), /*#__PURE__*/_react.default.createElement("div", { - ref: editorToolsResize.dragBarRef - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-editor-tools" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: activeSecondaryEditor === 'variables' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', - onClick: handleToolsTabClick, - "data-name": "variables" - }, "Variables"), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: activeSecondaryEditor === 'headers' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', - onClick: handleToolsTabClick, - "data-name": "headers" - }, "Headers"), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools' - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - onClick: toggleEditorTools, - "aria-label": editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools', - className: "graphiql-toggle-editor-tools" - }, editorToolsResize.hiddenElement === 'second' ? /*#__PURE__*/_react.default.createElement(_react2.ChevronUpIcon, { - className: "graphiql-chevron-icon", - "aria-hidden": "true" - }) : /*#__PURE__*/_react.default.createElement(_react2.ChevronDownIcon, { - className: "graphiql-chevron-icon", - "aria-hidden": "true" - }))))), /*#__PURE__*/_react.default.createElement("div", { - ref: editorToolsResize.secondRef - }, /*#__PURE__*/_react.default.createElement("section", { - className: "graphiql-editor-tool", - "aria-label": activeSecondaryEditor === 'variables' ? 'Variables' : 'Headers' - }, /*#__PURE__*/_react.default.createElement(_react2.VariableEditor, { - editorTheme: props.editorTheme, - isHidden: activeSecondaryEditor !== 'variables', - keyMap: props.keyMap, - onEdit: props.onEditVariables, - onClickReference: onClickReference, - readOnly: props.readOnly - }), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.HeaderEditor, { - editorTheme: props.editorTheme, - isHidden: activeSecondaryEditor !== 'headers', - keyMap: props.keyMap, - onEdit: props.onEditHeaders, - readOnly: props.readOnly - }))))), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-horizontal-drag-bar", - ref: editorResize.dragBarRef - }), /*#__PURE__*/_react.default.createElement("div", { - ref: editorResize.secondRef - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-response" - }, executionContext.isFetching ? /*#__PURE__*/_react.default.createElement(_react2.Spinner, null) : null, /*#__PURE__*/_react.default.createElement(_react2.ResponseEditor, { - editorTheme: props.editorTheme, - responseTooltip: props.responseTooltip, - keyMap: props.keyMap - }), footer))))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { - open: showDialog === 'short-keys', - onOpenChange: handleOpenShortKeysDialog - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-header" - }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { - className: "graphiql-dialog-title" - }, "Short Keys"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement(ShortKeys, { - keyMap: props.keyMap || 'sublime' - }))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { - open: showDialog === 'settings', - onOpenChange: handleOpenSettingsDialog - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-header" - }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { - className: "graphiql-dialog-title" - }, "Settings"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), props.showPersistHeadersSettings ? /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-title" - }, "Persist headers"), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-caption" - }, "Save headers upon reloading.", ' ', /*#__PURE__*/_react.default.createElement("span", { - className: "graphiql-warning-text" - }, "Only enable if you trust this device."))), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - id: "enable-persist-headers", - className: editorContext.shouldPersistHeaders ? 'active' : '', - "data-value": "true", - onClick: handlePersistHeaders - }, "On"), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - id: "disable-persist-headers", - className: editorContext.shouldPersistHeaders ? '' : 'active', - onClick: handlePersistHeaders - }, "Off"))) : null, !forcedTheme && /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-title" - }, "Theme"), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-caption" - }, "Adjust how the interface appears.")), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - className: theme === null ? 'active' : '', - onClick: handleChangeTheme - }, "System"), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - className: theme === 'light' ? 'active' : '', - "data-theme": "light", - onClick: handleChangeTheme - }, "Light"), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - className: theme === 'dark' ? 'active' : '', - "data-theme": "dark", - onClick: handleChangeTheme - }, "Dark"))), storageContext ? /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-title" - }, "Clear storage"), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-caption" - }, "Remove all locally stored data and start fresh.")), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - state: clearStorageStatus || undefined, - disabled: clearStorageStatus === 'success', - onClick: handleClearData - }, { - success: 'Cleared data', - error: 'Failed' - }[clearStorageStatus] || 'Clear data')) : null))); -} -const modifier = typeof window !== 'undefined' && window.navigator.platform.toLowerCase().indexOf('mac') === 0 ? 'Cmd' : 'Ctrl'; -const SHORT_KEYS = Object.entries({ - 'Search in editor': [modifier, 'F'], - 'Search in documentation': [modifier, 'K'], - 'Execute query': [modifier, 'Enter'], - 'Prettify editors': ['Ctrl', 'Shift', 'P'], - 'Merge fragments definitions into operation definition': ['Ctrl', 'Shift', 'M'], - 'Copy query': ['Ctrl', 'Shift', 'C'], - 'Re-fetch schema using introspection': ['Ctrl', 'Shift', 'R'] -}); -function ShortKeys({ - keyMap -}) { - return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("table", { - className: "graphiql-table" - }, /*#__PURE__*/_react.default.createElement("thead", null, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("th", null, "Short Key"), /*#__PURE__*/_react.default.createElement("th", null, "Function"))), /*#__PURE__*/_react.default.createElement("tbody", null, SHORT_KEYS.map(([title, keys]) => /*#__PURE__*/_react.default.createElement("tr", { - key: title - }, /*#__PURE__*/_react.default.createElement("td", null, keys.map((key, index, array) => /*#__PURE__*/_react.default.createElement(_react.Fragment, { - key: key - }, /*#__PURE__*/_react.default.createElement("code", { - className: "graphiql-key" - }, key), index !== array.length - 1 && ' + '))), /*#__PURE__*/_react.default.createElement("td", null, title))))), /*#__PURE__*/_react.default.createElement("p", null, "The editors use", ' ', /*#__PURE__*/_react.default.createElement("a", { - href: "https://codemirror.net/5/doc/manual.html#keymaps", - target: "_blank", - rel: "noopener noreferrer" - }, "CodeMirror Key Maps"), ' ', "that add more short keys. This instance of Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL uses", ' ', /*#__PURE__*/_react.default.createElement("code", null, keyMap), ".")); -} - -// Configure the UI by providing this Component as a child of GraphiQL. -function GraphiQLLogo(props) { - return /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-logo" - }, props.children || /*#__PURE__*/_react.default.createElement("a", { - className: "graphiql-logo-link", - href: "https://github.com/graphql/graphiql", - target: "_blank", - rel: "noreferrer" - }, "Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL")); -} -GraphiQLLogo.displayName = 'GraphiQLLogo'; - -// Configure the UI by providing this Component as a child of GraphiQL. -function GraphiQLToolbar(props) { - // eslint-disable-next-line react/jsx-no-useless-fragment - return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, props.children); -} -GraphiQLToolbar.displayName = 'GraphiQLToolbar'; - -// Configure the UI by providing this Component as a child of GraphiQL. -function GraphiQLFooter(props) { - return /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-footer" - }, props.children); -} -GraphiQLFooter.displayName = 'GraphiQLFooter'; - -// Determines if the React child is of the same type of the provided React component -function isChildComponentType(child, component) { - var _child$type; - if (child !== null && child !== void 0 && (_child$type = child.type) !== null && _child$type !== void 0 && _child$type.displayName && child.type.displayName === component.displayName) { - return true; - } - return child.type === component; -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/index.js": -/*!***************************************************!*\ - !*** ../../graphql-language-service/esm/index.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "CharacterStream", ({ - enumerable: true, - get: function () { - return _parser.CharacterStream; - } -})); -Object.defineProperty(exports, "CompletionItemKind", ({ - enumerable: true, - get: function () { - return _types.CompletionItemKind; - } -})); -Object.defineProperty(exports, "DIAGNOSTIC_SEVERITY", ({ - enumerable: true, - get: function () { - return _interface.DIAGNOSTIC_SEVERITY; - } -})); -Object.defineProperty(exports, "FileChangeTypeKind", ({ - enumerable: true, - get: function () { - return _types.FileChangeTypeKind; - } -})); -Object.defineProperty(exports, "GraphQLDocumentMode", ({ - enumerable: true, - get: function () { - return _parser.GraphQLDocumentMode; - } -})); -Object.defineProperty(exports, "LexRules", ({ - enumerable: true, - get: function () { - return _parser.LexRules; - } -})); -Object.defineProperty(exports, "ParseRules", ({ - enumerable: true, - get: function () { - return _parser.ParseRules; - } -})); -Object.defineProperty(exports, "Position", ({ - enumerable: true, - get: function () { - return _utils.Position; - } -})); -Object.defineProperty(exports, "Range", ({ - enumerable: true, - get: function () { - return _utils.Range; - } -})); -Object.defineProperty(exports, "RuleKinds", ({ - enumerable: true, - get: function () { - return _parser.RuleKinds; - } -})); -Object.defineProperty(exports, "SEVERITY", ({ - enumerable: true, - get: function () { - return _interface.SEVERITY; - } -})); -Object.defineProperty(exports, "SuggestionCommand", ({ - enumerable: true, - get: function () { - return _interface.SuggestionCommand; - } -})); -Object.defineProperty(exports, "canUseDirective", ({ - enumerable: true, - get: function () { - return _interface.canUseDirective; - } -})); -Object.defineProperty(exports, "collectVariables", ({ - enumerable: true, - get: function () { - return _utils.collectVariables; - } -})); -Object.defineProperty(exports, "getASTNodeAtPosition", ({ - enumerable: true, - get: function () { - return _utils.getASTNodeAtPosition; - } -})); -Object.defineProperty(exports, "getAutocompleteSuggestions", ({ - enumerable: true, - get: function () { - return _interface.getAutocompleteSuggestions; - } -})); -Object.defineProperty(exports, "getDefinitionQueryResultForArgument", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForArgument; - } -})); -Object.defineProperty(exports, "getDefinitionQueryResultForDefinitionNode", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForDefinitionNode; - } -})); -Object.defineProperty(exports, "getDefinitionQueryResultForField", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForField; - } -})); -Object.defineProperty(exports, "getDefinitionQueryResultForFragmentSpread", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForFragmentSpread; - } -})); -Object.defineProperty(exports, "getDefinitionQueryResultForNamedType", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForNamedType; - } -})); -Object.defineProperty(exports, "getDefinitionState", ({ - enumerable: true, - get: function () { - return _parser.getDefinitionState; - } -})); -Object.defineProperty(exports, "getDiagnostics", ({ - enumerable: true, - get: function () { - return _interface.getDiagnostics; - } -})); -Object.defineProperty(exports, "getFieldDef", ({ - enumerable: true, - get: function () { - return _parser.getFieldDef; - } -})); -Object.defineProperty(exports, "getFragmentDefinitions", ({ - enumerable: true, - get: function () { - return _interface.getFragmentDefinitions; - } -})); -Object.defineProperty(exports, "getFragmentDependencies", ({ - enumerable: true, - get: function () { - return _utils.getFragmentDependencies; - } -})); -Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ - enumerable: true, - get: function () { - return _utils.getFragmentDependenciesForAST; - } -})); -Object.defineProperty(exports, "getHoverInformation", ({ - enumerable: true, - get: function () { - return _interface.getHoverInformation; - } -})); -Object.defineProperty(exports, "getOperationASTFacts", ({ - enumerable: true, - get: function () { - return _utils.getOperationASTFacts; - } -})); -Object.defineProperty(exports, "getOperationFacts", ({ - enumerable: true, - get: function () { - return _utils.getOperationFacts; - } -})); -Object.defineProperty(exports, "getOutline", ({ - enumerable: true, - get: function () { - return _interface.getOutline; - } -})); -Object.defineProperty(exports, "getQueryFacts", ({ - enumerable: true, - get: function () { - return _utils.getQueryFacts; - } -})); -Object.defineProperty(exports, "getRange", ({ - enumerable: true, - get: function () { - return _interface.getRange; - } -})); -Object.defineProperty(exports, "getTokenAtPosition", ({ - enumerable: true, - get: function () { - return _parser.getTokenAtPosition; - } -})); -Object.defineProperty(exports, "getTypeInfo", ({ - enumerable: true, - get: function () { - return _interface.getTypeInfo; - } -})); -Object.defineProperty(exports, "getVariableCompletions", ({ - enumerable: true, - get: function () { - return _interface.getVariableCompletions; - } -})); -Object.defineProperty(exports, "getVariablesJSONSchema", ({ - enumerable: true, - get: function () { - return _utils.getVariablesJSONSchema; - } -})); -Object.defineProperty(exports, "isIgnored", ({ - enumerable: true, - get: function () { - return _parser.isIgnored; - } -})); -Object.defineProperty(exports, "list", ({ - enumerable: true, - get: function () { - return _parser.list; - } -})); -Object.defineProperty(exports, "offsetToPosition", ({ - enumerable: true, - get: function () { - return _utils.offsetToPosition; - } -})); -Object.defineProperty(exports, "onlineParser", ({ - enumerable: true, - get: function () { - return _parser.onlineParser; - } -})); -Object.defineProperty(exports, "opt", ({ - enumerable: true, - get: function () { - return _parser.opt; - } -})); -Object.defineProperty(exports, "p", ({ - enumerable: true, - get: function () { - return _parser.p; - } -})); -Object.defineProperty(exports, "pointToOffset", ({ - enumerable: true, - get: function () { - return _utils.pointToOffset; - } -})); -Object.defineProperty(exports, "t", ({ - enumerable: true, - get: function () { - return _parser.t; - } -})); -Object.defineProperty(exports, "validateQuery", ({ - enumerable: true, - get: function () { - return _interface.validateQuery; - } -})); -Object.defineProperty(exports, "validateWithCustomRules", ({ - enumerable: true, - get: function () { - return _utils.validateWithCustomRules; - } -})); -var _interface = __webpack_require__(/*! ./interface */ "../../graphql-language-service/esm/interface/index.js"); -var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); -var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/types.js"); -var _utils = __webpack_require__(/*! ./utils */ "../../graphql-language-service/esm/utils/index.js"); + /***/ "../../graphql-language-service/esm/utils/index.js": + /*!*********************************************************!*\ + !*** ../../graphql-language-service/esm/utils/index.js ***! + \*********************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + Object.defineProperty(exports, "Position", { + enumerable: true, + get: function () { + return _Range.Position; + }, + }); + Object.defineProperty(exports, "Range", { + enumerable: true, + get: function () { + return _Range.Range; + }, + }); + Object.defineProperty(exports, "collectVariables", { + enumerable: true, + get: function () { + return _collectVariables.collectVariables; + }, + }); + Object.defineProperty(exports, "getASTNodeAtPosition", { + enumerable: true, + get: function () { + return _getASTNodeAtPosition.getASTNodeAtPosition; + }, + }); + Object.defineProperty(exports, "getFragmentDependencies", { + enumerable: true, + get: function () { + return _fragmentDependencies.getFragmentDependencies; + }, + }); + Object.defineProperty(exports, "getFragmentDependenciesForAST", { + enumerable: true, + get: function () { + return _fragmentDependencies.getFragmentDependenciesForAST; + }, + }); + Object.defineProperty(exports, "getOperationASTFacts", { + enumerable: true, + get: function () { + return _getOperationFacts.getOperationASTFacts; + }, + }); + Object.defineProperty(exports, "getOperationFacts", { + enumerable: true, + get: function () { + return _getOperationFacts.default; + }, + }); + Object.defineProperty(exports, "getQueryFacts", { + enumerable: true, + get: function () { + return _getOperationFacts.getQueryFacts; + }, + }); + Object.defineProperty(exports, "getVariablesJSONSchema", { + enumerable: true, + get: function () { + return _getVariablesJSONSchema.getVariablesJSONSchema; + }, + }); + Object.defineProperty(exports, "locToRange", { + enumerable: true, + get: function () { + return _Range.locToRange; + }, + }); + Object.defineProperty(exports, "offsetToPosition", { + enumerable: true, + get: function () { + return _Range.offsetToPosition; + }, + }); + Object.defineProperty(exports, "pointToOffset", { + enumerable: true, + get: function () { + return _getASTNodeAtPosition.pointToOffset; + }, + }); + Object.defineProperty(exports, "validateWithCustomRules", { + enumerable: true, + get: function () { + return _validateWithCustomRules.validateWithCustomRules; + }, + }); + var _fragmentDependencies = __webpack_require__( + /*! ./fragmentDependencies */ "../../graphql-language-service/esm/utils/fragmentDependencies.js" + ); + var _getVariablesJSONSchema = __webpack_require__( + /*! ./getVariablesJSONSchema */ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js" + ); + var _getASTNodeAtPosition = __webpack_require__( + /*! ./getASTNodeAtPosition */ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js" + ); + var _Range = __webpack_require__( + /*! ./Range */ "../../graphql-language-service/esm/utils/Range.js" + ); + var _validateWithCustomRules = __webpack_require__( + /*! ./validateWithCustomRules */ "../../graphql-language-service/esm/utils/validateWithCustomRules.js" + ); + var _collectVariables = __webpack_require__( + /*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js" + ); + var _getOperationFacts = _interopRequireWildcard( + __webpack_require__( + /*! ./getOperationFacts */ "../../graphql-language-service/esm/utils/getOperationFacts.js" + ) + ); + function _getRequireWildcardCache(e) { + if ("function" != typeof WeakMap) return null; + var r = new WeakMap(), + t = new WeakMap(); + return (_getRequireWildcardCache = function (e) { + return e ? t : r; + })(e); + } + function _interopRequireWildcard(e, r) { + if (!r && e && e.__esModule) return e; + if (null === e || ("object" != typeof e && "function" != typeof e)) + return { default: e }; + var t = _getRequireWildcardCache(r); + if (t && t.has(e)) return t.get(e); + var n = { __proto__: null }, + a = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var u in e) + if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { + var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; + i && (i.get || i.set) + ? Object.defineProperty(n, u, i) + : (n[u] = e[u]); + } + return (n.default = e), t && t.set(e, n), n; + } -/***/ }), + /***/ + }, -/***/ "../../graphql-language-service/esm/interface/autocompleteUtils.js": -/*!*************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/autocompleteUtils.js ***! - \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getInsertText = exports.getInputInsertText = exports.getFieldInsertText = void 0; -exports.hintList = hintList; -exports.objectValues = objectValues; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function objectValues(object) { - const keys = Object.keys(object); - const len = keys.length; - const values = new Array(len); - for (let i = 0; i < len; ++i) { - values[i] = object[keys[i]]; - } - return values; -} -function hintList(token, list) { - return filterAndSortList(list, normalizeText(token.string)); -} -function filterAndSortList(list, text) { - if (!text || text.trim() === '' || text.trim() === ':' || text.trim() === '{') { - return filterNonEmpty(list, entry => !entry.isDeprecated); - } - const byProximity = list.map(entry => ({ - proximity: getProximity(normalizeText(entry.label), text), - entry - })); - return filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated).sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.label.length - b.entry.label.length).map(pair => pair.entry); -} -function filterNonEmpty(array, predicate) { - const filtered = array.filter(predicate); - return filtered.length === 0 ? array : filtered; -} -function normalizeText(text) { - return text.toLowerCase().replaceAll(/\W/g, ''); -} -function getProximity(suggestion, text) { - let proximity = lexicalDistance(text, suggestion); - if (suggestion.length > text.length) { - proximity -= suggestion.length - text.length - 1; - proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; - } - return proximity; -} -function lexicalDistance(a, b) { - let i; - let j; - const d = []; - const aLength = a.length; - const bLength = b.length; - for (i = 0; i <= aLength; i++) { - d[i] = [i]; - } - for (j = 1; j <= bLength; j++) { - d[0][j] = j; - } - for (i = 1; i <= aLength; i++) { - for (j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); - } - } - } - return d[aLength][bLength]; -} -const insertSuffix = n => ` {\n $${n !== null && n !== void 0 ? n : 1}\n}`; -const getInsertText = (prefix, type, fallback) => { - if (!type) { - return fallback !== null && fallback !== void 0 ? fallback : prefix; - } - const namedType = (0, _graphql.getNamedType)(type); - if ((0, _graphql.isObjectType)(namedType) || (0, _graphql.isInputObjectType)(namedType) || (0, _graphql.isListType)(namedType) || (0, _graphql.isAbstractType)(namedType)) { - return prefix + insertSuffix(); - } - return fallback !== null && fallback !== void 0 ? fallback : prefix; -}; -exports.getInsertText = getInsertText; -const getInputInsertText = (prefix, type, fallback) => { - if ((0, _graphql.isListType)(type)) { - const baseType = (0, _graphql.getNamedType)(type.ofType); - return prefix + `[${getInsertText('', baseType, '$1')}]`; - } - return getInsertText(prefix, type, fallback); -}; -exports.getInputInsertText = getInputInsertText; -const getFieldInsertText = field => { - const requiredArgs = field.args.filter(arg => arg.type.toString().endsWith('!')); - if (!requiredArgs.length) { - return; - } - return field.name + `(${requiredArgs.map((arg, i) => `${arg.name}: $${i + 1}`)}) ${getInsertText('', field.type, '\n')}`; -}; -exports.getFieldInsertText = getFieldInsertText; + /***/ "../../graphql-language-service/esm/utils/validateWithCustomRules.js": + /*!***************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/validateWithCustomRules.js ***! + \***************************************************************************/ + /***/ function (__unused_webpack_module, exports, __webpack_require__) { + Object.defineProperty(exports, "__esModule", { + value: true, + }); + exports.validateWithCustomRules = validateWithCustomRules; + var _graphql = __webpack_require__( + /*! graphql */ "../../../node_modules/graphql/index.mjs" + ); + const specifiedSDLRules = [ + _graphql.LoneSchemaDefinitionRule, + _graphql.UniqueOperationTypesRule, + _graphql.UniqueTypeNamesRule, + _graphql.UniqueEnumValueNamesRule, + _graphql.UniqueFieldDefinitionNamesRule, + _graphql.UniqueDirectiveNamesRule, + _graphql.KnownTypeNamesRule, + _graphql.KnownDirectivesRule, + _graphql.UniqueDirectivesPerLocationRule, + _graphql.PossibleTypeExtensionsRule, + _graphql.UniqueArgumentNamesRule, + _graphql.UniqueInputFieldNamesRule, + _graphql.UniqueVariableNamesRule, + _graphql.FragmentsOnCompositeTypesRule, + _graphql.ProvidedRequiredArgumentsRule, + ]; + function validateWithCustomRules( + schema, + ast, + customRules, + isRelayCompatMode, + isSchemaDocument + ) { + const rules = _graphql.specifiedRules.filter((rule) => { + if ( + rule === _graphql.NoUnusedFragmentsRule || + rule === _graphql.ExecutableDefinitionsRule + ) { + return false; + } + if (isRelayCompatMode && rule === _graphql.KnownFragmentNamesRule) { + return false; + } + return true; + }); + if (customRules) { + Array.prototype.push.apply(rules, customRules); + } + if (isSchemaDocument) { + Array.prototype.push.apply(rules, specifiedSDLRules); + } + const errors = (0, _graphql.validate)(schema, ast, rules); + return errors.filter((error) => { + if (error.message.includes("Unknown directive") && error.nodes) { + const node = error.nodes[0]; + if (node && node.kind === _graphql.Kind.DIRECTIVE) { + const name = node.name.value; + if (name === "arguments" || name === "argumentDefinitions") { + return false; + } + } + } + return true; + }); + } -/***/ }), + /***/ + }, -/***/ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js": -/*!**********************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /***/ "./style.css": + /*!*******************!*\ + !*** ./style.css ***! + \*******************/ + /***/ function ( + __unused_webpack_module, + __webpack_exports__, + __webpack_require__ + ) { + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + /***/ + }, + /***/ "../../graphiql-react/dist/style.css": + /*!*******************************************!*\ + !*** ../../graphiql-react/dist/style.css ***! + \*******************************************/ + /***/ function ( + __unused_webpack_module, + __webpack_exports__, + __webpack_require__ + ) { + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + /***/ + }, + /***/ "../../graphiql-react/font/fira-code.css": + /*!***********************************************!*\ + !*** ../../graphiql-react/font/fira-code.css ***! + \***********************************************/ + /***/ function ( + __unused_webpack_module, + __webpack_exports__, + __webpack_require__ + ) { + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + /***/ + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.SuggestionCommand = void 0; -exports.canUseDirective = canUseDirective; -exports.getAutocompleteSuggestions = getAutocompleteSuggestions; -exports.getFragmentDefinitions = getFragmentDefinitions; -Object.defineProperty(exports, "getTypeInfo", ({ - enumerable: true, - get: function () { - return _parser.getTypeInfo; - } -})); -exports.getVariableCompletions = getVariableCompletions; -Object.defineProperty(exports, "runOnlineParser", ({ - enumerable: true, - get: function () { - return _parser.runOnlineParser; - } -})); -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _types = __webpack_require__(/*! ../types */ "../../graphql-language-service/esm/types.js"); -var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); -var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); -var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); -const SuggestionCommand = exports.SuggestionCommand = { - command: 'editor.action.triggerSuggest', - title: 'Suggestions' -}; -const collectFragmentDefs = op => { - const externalFragments = []; - if (op) { - try { - (0, _graphql.visit)((0, _graphql.parse)(op), { - FragmentDefinition(def) { - externalFragments.push(def); - } - }); - } catch (_a) { - return []; - } - } - return externalFragments; -}; -function getAutocompleteSuggestions(schema, queryText, cursor, contextToken, fragmentDefs, options) { - var _a; - const opts = Object.assign(Object.assign({}, options), { - schema - }); - const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken, options); - if (!context) { - return []; - } - const { - state, - typeInfo, - mode, - token - } = context; - const { - kind, - step, - prevState - } = state; - if (kind === _parser.RuleKinds.DOCUMENT) { - if (mode === _parser.GraphQLDocumentMode.TYPE_SYSTEM) { - return getSuggestionsForTypeSystemDefinitions(token); - } - if (mode === _parser.GraphQLDocumentMode.EXECUTABLE) { - return getSuggestionsForExecutableDefinitions(token); - } - return getSuggestionsForUnknownDocumentMode(token); - } - if (kind === _parser.RuleKinds.EXTEND_DEF) { - return getSuggestionsForExtensionDefinitions(token); - } - if (((_a = prevState === null || prevState === void 0 ? void 0 : prevState.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.EXTENSION_DEFINITION && state.name) { - return (0, _autocompleteUtils.hintList)(token, []); - } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.SCALAR_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isScalarType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); - } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.OBJECT_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isObjectType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); - } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INTERFACE_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInterfaceType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); - } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.UNION_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isUnionType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); - } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.ENUM_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isEnumType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); - } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInputObjectType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); - } - if (kind === _parser.RuleKinds.IMPLEMENTS || kind === _parser.RuleKinds.NAMED_TYPE && (prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _parser.RuleKinds.IMPLEMENTS) { - return getSuggestionsForImplements(token, state, schema, queryText, typeInfo); - } - if (kind === _parser.RuleKinds.SELECTION_SET || kind === _parser.RuleKinds.FIELD || kind === _parser.RuleKinds.ALIASED_FIELD) { - return getSuggestionsForFieldNames(token, typeInfo, opts); - } - if (kind === _parser.RuleKinds.ARGUMENTS || kind === _parser.RuleKinds.ARGUMENT && step === 0) { - const { - argDefs - } = typeInfo; - if (argDefs) { - return (0, _autocompleteUtils.hintList)(token, argDefs.map(argDef => { - var _a; - return { - label: argDef.name, - insertText: (0, _autocompleteUtils.getInputInsertText)(argDef.name + ': ', argDef.type), - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - command: SuggestionCommand, - labelDetails: { - detail: ' ' + String(argDef.type) - }, - documentation: (_a = argDef.description) !== null && _a !== void 0 ? _a : undefined, - kind: _types.CompletionItemKind.Variable, - type: argDef.type - }; - })); - } - } - if ((kind === _parser.RuleKinds.OBJECT_VALUE || kind === _parser.RuleKinds.OBJECT_FIELD && step === 0) && typeInfo.objectFieldDefs) { - const objectFields = (0, _autocompleteUtils.objectValues)(typeInfo.objectFieldDefs); - const completionKind = kind === _parser.RuleKinds.OBJECT_VALUE ? _types.CompletionItemKind.Value : _types.CompletionItemKind.Field; - return (0, _autocompleteUtils.hintList)(token, objectFields.map(field => { - var _a; - return { - label: field.name, - detail: String(field.type), - documentation: (_a = field === null || field === void 0 ? void 0 : field.description) !== null && _a !== void 0 ? _a : undefined, - kind: completionKind, - type: field.type, - insertText: (0, _autocompleteUtils.getInputInsertText)(field.name + ': ', field.type), - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - command: SuggestionCommand - }; - })); - } - if (kind === _parser.RuleKinds.ENUM_VALUE || kind === _parser.RuleKinds.LIST_VALUE && step === 1 || kind === _parser.RuleKinds.OBJECT_FIELD && step === 2 || kind === _parser.RuleKinds.ARGUMENT && step === 2) { - return getSuggestionsForInputValues(token, typeInfo, queryText, schema); - } - if (kind === _parser.RuleKinds.VARIABLE && step === 1) { - const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); - const variableDefinitions = getVariableCompletions(queryText, schema, token); - return (0, _autocompleteUtils.hintList)(token, variableDefinitions.filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name))); - } - if (kind === _parser.RuleKinds.TYPE_CONDITION && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState != null && prevState.kind === _parser.RuleKinds.TYPE_CONDITION) { - return getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, kind); - } - if (kind === _parser.RuleKinds.FRAGMENT_SPREAD && step === 1) { - return getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, Array.isArray(fragmentDefs) ? fragmentDefs : collectFragmentDefs(fragmentDefs)); - } - const unwrappedState = unwrapType(state); - if (unwrappedState.kind === _parser.RuleKinds.FIELD_DEF) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isOutputType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n' : type.name, - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation - }))); - } - if (unwrappedState.kind === _parser.RuleKinds.INPUT_VALUE_DEF && step === 2) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isInputType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n$1' : type.name, - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet - }))); - } - if (kind === _parser.RuleKinds.VARIABLE_DEFINITION && step === 2 || kind === _parser.RuleKinds.LIST_TYPE && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState && (prevState.kind === _parser.RuleKinds.VARIABLE_DEFINITION || prevState.kind === _parser.RuleKinds.LIST_TYPE || prevState.kind === _parser.RuleKinds.NON_NULL_TYPE)) { - return getSuggestionsForVariableDefinition(token, schema, kind); - } - if (kind === _parser.RuleKinds.DIRECTIVE) { - return getSuggestionsForDirective(token, state, schema, kind); - } - if (kind === _parser.RuleKinds.DIRECTIVE_DEF) { - return getSuggestionsForDirectiveArguments(token, state, schema, kind); - } - return []; -} -const typeSystemCompletionItems = [{ - label: 'type', - kind: _types.CompletionItemKind.Function -}, { - label: 'interface', - kind: _types.CompletionItemKind.Function -}, { - label: 'union', - kind: _types.CompletionItemKind.Function -}, { - label: 'input', - kind: _types.CompletionItemKind.Function -}, { - label: 'scalar', - kind: _types.CompletionItemKind.Function -}, { - label: 'schema', - kind: _types.CompletionItemKind.Function -}]; -const executableCompletionItems = [{ - label: 'query', - kind: _types.CompletionItemKind.Function -}, { - label: 'mutation', - kind: _types.CompletionItemKind.Function -}, { - label: 'subscription', - kind: _types.CompletionItemKind.Function -}, { - label: 'fragment', - kind: _types.CompletionItemKind.Function -}, { - label: '{', - kind: _types.CompletionItemKind.Constructor -}]; -function getSuggestionsForTypeSystemDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, [{ - label: 'extend', - kind: _types.CompletionItemKind.Function - }, ...typeSystemCompletionItems]); -} -function getSuggestionsForExecutableDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, executableCompletionItems); -} -function getSuggestionsForUnknownDocumentMode(token) { - return (0, _autocompleteUtils.hintList)(token, [{ - label: 'extend', - kind: _types.CompletionItemKind.Function - }, ...executableCompletionItems, ...typeSystemCompletionItems]); -} -function getSuggestionsForExtensionDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, typeSystemCompletionItems); -} -function getSuggestionsForFieldNames(token, typeInfo, options) { - var _a; - if (typeInfo.parentType) { - const { - parentType - } = typeInfo; - let fields = []; - if ('getFields' in parentType) { - fields = (0, _autocompleteUtils.objectValues)(parentType.getFields()); - } - if ((0, _graphql.isCompositeType)(parentType)) { - fields.push(_graphql.TypeNameMetaFieldDef); - } - if (parentType === ((_a = options === null || options === void 0 ? void 0 : options.schema) === null || _a === void 0 ? void 0 : _a.getQueryType())) { - fields.push(_graphql.SchemaMetaFieldDef, _graphql.TypeMetaFieldDef); - } - return (0, _autocompleteUtils.hintList)(token, fields.map((field, index) => { - var _a; - const suggestion = { - sortText: String(index) + field.name, - label: field.name, - detail: String(field.type), - documentation: (_a = field.description) !== null && _a !== void 0 ? _a : undefined, - deprecated: Boolean(field.deprecationReason), - isDeprecated: Boolean(field.deprecationReason), - deprecationReason: field.deprecationReason, - kind: _types.CompletionItemKind.Field, - labelDetails: { - detail: ' ' + field.type.toString() - }, - type: field.type - }; - if (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) { - suggestion.insertText = (0, _autocompleteUtils.getFieldInsertText)(field); - if (!suggestion.insertText) { - suggestion.insertText = (0, _autocompleteUtils.getInsertText)(field.name, field.type, field.name + (token.state.needsAdvance ? '' : '\n')); - } - if (suggestion.insertText) { - suggestion.insertTextFormat = _types.InsertTextFormat.Snippet; - suggestion.insertTextMode = _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation; - suggestion.command = SuggestionCommand; - } - } - return suggestion; - })); - } - return []; -} -function getSuggestionsForInputValues(token, typeInfo, queryText, schema) { - const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); - const queryVariables = getVariableCompletions(queryText, schema, token).filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name)); - if (namedInputType instanceof _graphql.GraphQLEnumType) { - const values = namedInputType.getValues(); - return (0, _autocompleteUtils.hintList)(token, values.map(value => { - var _a; - return { - label: value.name, - detail: String(namedInputType), - documentation: (_a = value.description) !== null && _a !== void 0 ? _a : undefined, - deprecated: Boolean(value.deprecationReason), - isDeprecated: Boolean(value.deprecationReason), - deprecationReason: value.deprecationReason, - kind: _types.CompletionItemKind.EnumMember, - type: namedInputType - }; - }).concat(queryVariables)); - } - if (namedInputType === _graphql.GraphQLBoolean) { - return (0, _autocompleteUtils.hintList)(token, queryVariables.concat([{ - label: 'true', - detail: String(_graphql.GraphQLBoolean), - documentation: 'Not false.', - kind: _types.CompletionItemKind.Variable, - type: _graphql.GraphQLBoolean - }, { - label: 'false', - detail: String(_graphql.GraphQLBoolean), - documentation: 'Not true.', - kind: _types.CompletionItemKind.Variable, - type: _graphql.GraphQLBoolean - }])); - } - return queryVariables; -} -function getSuggestionsForImplements(token, tokenState, schema, documentText, typeInfo) { - if (tokenState.needsSeparator) { - return []; - } - const typeMap = schema.getTypeMap(); - const schemaInterfaces = (0, _autocompleteUtils.objectValues)(typeMap).filter(_graphql.isInterfaceType); - const schemaInterfaceNames = schemaInterfaces.map(({ - name - }) => name); - const inlineInterfaces = new Set(); - (0, _parser.runOnlineParser)(documentText, (_, state) => { - var _a, _b, _c, _d, _e; - if (state.name) { - if (state.kind === _parser.RuleKinds.INTERFACE_DEF && !schemaInterfaceNames.includes(state.name)) { - inlineInterfaces.add(state.name); - } - if (state.kind === _parser.RuleKinds.NAMED_TYPE && ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.IMPLEMENTS) { - if (typeInfo.interfaceDef) { - const existingType = (_b = typeInfo.interfaceDef) === null || _b === void 0 ? void 0 : _b.getInterfaces().find(({ - name - }) => name === state.name); - if (existingType) { - return; - } - const type = schema.getType(state.name); - const interfaceConfig = (_c = typeInfo.interfaceDef) === null || _c === void 0 ? void 0 : _c.toConfig(); - typeInfo.interfaceDef = new _graphql.GraphQLInterfaceType(Object.assign(Object.assign({}, interfaceConfig), { - interfaces: [...interfaceConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ - name: state.name, - fields: {} - })] - })); - } else if (typeInfo.objectTypeDef) { - const existingType = (_d = typeInfo.objectTypeDef) === null || _d === void 0 ? void 0 : _d.getInterfaces().find(({ - name - }) => name === state.name); - if (existingType) { - return; - } - const type = schema.getType(state.name); - const objectTypeConfig = (_e = typeInfo.objectTypeDef) === null || _e === void 0 ? void 0 : _e.toConfig(); - typeInfo.objectTypeDef = new _graphql.GraphQLObjectType(Object.assign(Object.assign({}, objectTypeConfig), { - interfaces: [...objectTypeConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ - name: state.name, - fields: {} - })] - })); - } - } - } - }); - const currentTypeToExtend = typeInfo.interfaceDef || typeInfo.objectTypeDef; - const siblingInterfaces = (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.getInterfaces()) || []; - const siblingInterfaceNames = siblingInterfaces.map(({ - name - }) => name); - const possibleInterfaces = schemaInterfaces.concat([...inlineInterfaces].map(name => ({ - name - }))).filter(({ - name - }) => name !== (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.name) && !siblingInterfaceNames.includes(name)); - return (0, _autocompleteUtils.hintList)(token, possibleInterfaces.map(type => { - const result = { - label: type.name, - kind: _types.CompletionItemKind.Interface, - type - }; - if (type === null || type === void 0 ? void 0 : type.description) { - result.documentation = type.description; - } - return result; - })); -} -function getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, _kind) { - let possibleTypes; - if (typeInfo.parentType) { - if ((0, _graphql.isAbstractType)(typeInfo.parentType)) { - const abstractType = (0, _graphql.assertAbstractType)(typeInfo.parentType); - const possibleObjTypes = schema.getPossibleTypes(abstractType); - const possibleIfaceMap = Object.create(null); - for (const type of possibleObjTypes) { - for (const iface of type.getInterfaces()) { - possibleIfaceMap[iface.name] = iface; - } - } - possibleTypes = possibleObjTypes.concat((0, _autocompleteUtils.objectValues)(possibleIfaceMap)); - } else { - possibleTypes = [typeInfo.parentType]; - } - } else { - const typeMap = schema.getTypeMap(); - possibleTypes = (0, _autocompleteUtils.objectValues)(typeMap).filter(type => (0, _graphql.isCompositeType)(type) && !type.name.startsWith('__')); - } - return (0, _autocompleteUtils.hintList)(token, possibleTypes.map(type => { - const namedType = (0, _graphql.getNamedType)(type); - return { - label: String(type), - documentation: (namedType === null || namedType === void 0 ? void 0 : namedType.description) || '', - kind: _types.CompletionItemKind.Field - }; - })); -} -function getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, fragmentDefs) { - if (!queryText) { - return []; - } - const typeMap = schema.getTypeMap(); - const defState = (0, _parser.getDefinitionState)(token.state); - const fragments = getFragmentDefinitions(queryText); - if (fragmentDefs && fragmentDefs.length > 0) { - fragments.push(...fragmentDefs); - } - const relevantFrags = fragments.filter(frag => typeMap[frag.typeCondition.name.value] && !(defState && defState.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && defState.name === frag.name.value) && (0, _graphql.isCompositeType)(typeInfo.parentType) && (0, _graphql.isCompositeType)(typeMap[frag.typeCondition.name.value]) && (0, _graphql.doTypesOverlap)(schema, typeInfo.parentType, typeMap[frag.typeCondition.name.value])); - return (0, _autocompleteUtils.hintList)(token, relevantFrags.map(frag => ({ - label: frag.name.value, - detail: String(typeMap[frag.typeCondition.name.value]), - documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, - labelDetails: { - detail: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}` - }, - kind: _types.CompletionItemKind.Field, - type: typeMap[frag.typeCondition.name.value] - }))); -} -const getParentDefinition = (state, kind) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - if (((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === kind) { - return state.prevState; - } - if (((_c = (_b = state.prevState) === null || _b === void 0 ? void 0 : _b.prevState) === null || _c === void 0 ? void 0 : _c.kind) === kind) { - return state.prevState.prevState; - } - if (((_f = (_e = (_d = state.prevState) === null || _d === void 0 ? void 0 : _d.prevState) === null || _e === void 0 ? void 0 : _e.prevState) === null || _f === void 0 ? void 0 : _f.kind) === kind) { - return state.prevState.prevState.prevState; - } - if (((_k = (_j = (_h = (_g = state.prevState) === null || _g === void 0 ? void 0 : _g.prevState) === null || _h === void 0 ? void 0 : _h.prevState) === null || _j === void 0 ? void 0 : _j.prevState) === null || _k === void 0 ? void 0 : _k.kind) === kind) { - return state.prevState.prevState.prevState.prevState; - } -}; -function getVariableCompletions(queryText, schema, token) { - let variableName = null; - let variableType; - const definitions = Object.create({}); - (0, _parser.runOnlineParser)(queryText, (_, state) => { - var _a; - if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.VARIABLE && state.name) { - variableName = state.name; - } - if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.NAMED_TYPE && variableName) { - const parentDefinition = getParentDefinition(state, _parser.RuleKinds.TYPE); - if (parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type) { - variableType = schema.getType(parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type); - } - } - if (variableName && variableType && !definitions[variableName]) { - const replaceString = token.string === '$' || ((_a = token === null || token === void 0 ? void 0 : token.state) === null || _a === void 0 ? void 0 : _a.kind) === 'Variable' ? variableName : '$' + variableName; - definitions[variableName] = { - detail: variableType.toString(), - insertText: replaceString, - label: '$' + variableName, - rawInsert: replaceString, - type: variableType, - kind: _types.CompletionItemKind.Variable - }; - variableName = null; - variableType = null; - } - }); - return (0, _autocompleteUtils.objectValues)(definitions); -} -function getFragmentDefinitions(queryText) { - const fragmentDefs = []; - (0, _parser.runOnlineParser)(queryText, (_, state) => { - if (state.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && state.name && state.type) { - fragmentDefs.push({ - kind: _parser.RuleKinds.FRAGMENT_DEFINITION, - name: { - kind: _graphql.Kind.NAME, - value: state.name - }, - selectionSet: { - kind: _parser.RuleKinds.SELECTION_SET, - selections: [] - }, - typeCondition: { - kind: _parser.RuleKinds.NAMED_TYPE, - name: { - kind: _graphql.Kind.NAME, - value: state.type - } - } - }); - } - }); - return fragmentDefs; -} -function getSuggestionsForVariableDefinition(token, schema, _kind) { - const inputTypeMap = schema.getTypeMap(); - const inputTypes = (0, _autocompleteUtils.objectValues)(inputTypeMap).filter(_graphql.isInputType); - return (0, _autocompleteUtils.hintList)(token, inputTypes.map(type => ({ - label: type.name, - documentation: (type === null || type === void 0 ? void 0 : type.description) || '', - kind: _types.CompletionItemKind.Variable - }))); -} -function getSuggestionsForDirective(token, state, schema, _kind) { - var _a; - if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) { - const directives = schema.getDirectives().filter(directive => canUseDirective(state.prevState, directive)); - return (0, _autocompleteUtils.hintList)(token, directives.map(directive => ({ - label: directive.name, - documentation: (directive === null || directive === void 0 ? void 0 : directive.description) || '', - kind: _types.CompletionItemKind.Function - }))); - } - return []; -} -function getSuggestionsForDirectiveArguments(token, state, schema, _kind) { - const directive = schema.getDirectives().find(d => d.name === state.name); - return (0, _autocompleteUtils.hintList)(token, (directive === null || directive === void 0 ? void 0 : directive.args.map(arg => ({ - label: arg.name, - documentation: arg.description || '', - kind: _types.CompletionItemKind.Field - }))) || []); -} -function canUseDirective(state, directive) { - if (!(state === null || state === void 0 ? void 0 : state.kind)) { - return false; - } - const { - kind, - prevState - } = state; - const { - locations - } = directive; - switch (kind) { - case _parser.RuleKinds.QUERY: - return locations.includes(_graphql.DirectiveLocation.QUERY); - case _parser.RuleKinds.MUTATION: - return locations.includes(_graphql.DirectiveLocation.MUTATION); - case _parser.RuleKinds.SUBSCRIPTION: - return locations.includes(_graphql.DirectiveLocation.SUBSCRIPTION); - case _parser.RuleKinds.FIELD: - case _parser.RuleKinds.ALIASED_FIELD: - return locations.includes(_graphql.DirectiveLocation.FIELD); - case _parser.RuleKinds.FRAGMENT_DEFINITION: - return locations.includes(_graphql.DirectiveLocation.FRAGMENT_DEFINITION); - case _parser.RuleKinds.FRAGMENT_SPREAD: - return locations.includes(_graphql.DirectiveLocation.FRAGMENT_SPREAD); - case _parser.RuleKinds.INLINE_FRAGMENT: - return locations.includes(_graphql.DirectiveLocation.INLINE_FRAGMENT); - case _parser.RuleKinds.SCHEMA_DEF: - return locations.includes(_graphql.DirectiveLocation.SCHEMA); - case _parser.RuleKinds.SCALAR_DEF: - return locations.includes(_graphql.DirectiveLocation.SCALAR); - case _parser.RuleKinds.OBJECT_TYPE_DEF: - return locations.includes(_graphql.DirectiveLocation.OBJECT); - case _parser.RuleKinds.FIELD_DEF: - return locations.includes(_graphql.DirectiveLocation.FIELD_DEFINITION); - case _parser.RuleKinds.INTERFACE_DEF: - return locations.includes(_graphql.DirectiveLocation.INTERFACE); - case _parser.RuleKinds.UNION_DEF: - return locations.includes(_graphql.DirectiveLocation.UNION); - case _parser.RuleKinds.ENUM_DEF: - return locations.includes(_graphql.DirectiveLocation.ENUM); - case _parser.RuleKinds.ENUM_VALUE: - return locations.includes(_graphql.DirectiveLocation.ENUM_VALUE); - case _parser.RuleKinds.INPUT_DEF: - return locations.includes(_graphql.DirectiveLocation.INPUT_OBJECT); - case _parser.RuleKinds.INPUT_VALUE_DEF: - const prevStateKind = prevState === null || prevState === void 0 ? void 0 : prevState.kind; - switch (prevStateKind) { - case _parser.RuleKinds.ARGUMENTS_DEF: - return locations.includes(_graphql.DirectiveLocation.ARGUMENT_DEFINITION); - case _parser.RuleKinds.INPUT_DEF: - return locations.includes(_graphql.DirectiveLocation.INPUT_FIELD_DEFINITION); - } - } - return false; -} -function unwrapType(state) { - if (state.prevState && state.kind && [_parser.RuleKinds.NAMED_TYPE, _parser.RuleKinds.LIST_TYPE, _parser.RuleKinds.TYPE, _parser.RuleKinds.NON_NULL_TYPE].includes(state.kind)) { - return unwrapType(state.prevState); - } - return state; -} + /***/ "../../graphiql-react/font/roboto.css": + /*!********************************************!*\ + !*** ../../graphiql-react/font/roboto.css ***! + \********************************************/ + /***/ function ( + __unused_webpack_module, + __webpack_exports__, + __webpack_require__ + ) { + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + /***/ + }, -/***/ }), + /***/ react: + /*!************************!*\ + !*** external "React" ***! + \************************/ + /***/ function (module) { + module.exports = window["React"]; -/***/ "../../graphql-language-service/esm/interface/getDefinition.js": -/*!*********************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getDefinition.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.LANGUAGE = void 0; -exports.getDefinitionQueryResultForArgument = getDefinitionQueryResultForArgument; -exports.getDefinitionQueryResultForDefinitionNode = getDefinitionQueryResultForDefinitionNode; -exports.getDefinitionQueryResultForField = getDefinitionQueryResultForField; -exports.getDefinitionQueryResultForFragmentSpread = getDefinitionQueryResultForFragmentSpread; -exports.getDefinitionQueryResultForNamedType = getDefinitionQueryResultForNamedType; -var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); -var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const LANGUAGE = exports.LANGUAGE = 'GraphQL'; -function assert(value, message) { - if (!value) { - throw new Error(message); - } -} -function getRange(text, node) { - const location = node.loc; - assert(location, 'Expected ASTNode to have a location.'); - return (0, _utils.locToRange)(text, location); -} -function getPosition(text, node) { - const location = node.loc; - assert(location, 'Expected ASTNode to have a location.'); - return (0, _utils.offsetToPosition)(text, location.start); -} -function getDefinitionQueryResultForNamedType(text, node, dependencies) { - return __awaiter(this, void 0, void 0, function* () { - const name = node.name.value; - const defNodes = dependencies.filter(({ - definition - }) => definition.name && definition.name.value === name); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL type ${name}`); - } - const definitions = defNodes.map(({ - filePath, - content, - definition - }) => getDefinitionForNodeDefinition(filePath || '', content, definition)); - return { - definitions, - queryRange: definitions.map(_ => getRange(text, node)), - printedName: name - }; - }); -} -function getDefinitionQueryResultForField(fieldName, typeName, dependencies) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const defNodes = dependencies.filter(({ - definition - }) => definition.name && definition.name.value === typeName); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL type ${typeName}`); - } - const definitions = []; - for (const { - filePath, - content, - definition - } of defNodes) { - const fieldDefinition = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName); - if (fieldDefinition == null) { - continue; - } - definitions.push(getDefinitionForFieldDefinition(filePath || '', content, fieldDefinition)); - } - return { - definitions, - queryRange: [], - printedName: [typeName, fieldName].join('.') - }; - }); -} -function getDefinitionQueryResultForArgument(argumentName, fieldName, typeName, dependencies) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const definitions = []; - for (const { - filePath, - content, - definition - } of dependencies) { - const argDefinition = (_c = (_b = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName)) === null || _b === void 0 ? void 0 : _b.arguments) === null || _c === void 0 ? void 0 : _c.find(item => item.name.value === argumentName); - if (argDefinition == null) { - continue; - } - definitions.push(getDefinitionForArgumentDefinition(filePath || '', content, argDefinition)); - } - return { - definitions, - queryRange: [], - printedName: `${[typeName, fieldName].join('.')}(${argumentName})` - }; - }); -} -function getDefinitionQueryResultForFragmentSpread(text, fragment, dependencies) { - return __awaiter(this, void 0, void 0, function* () { - const name = fragment.name.value; - const defNodes = dependencies.filter(({ - definition - }) => definition.name.value === name); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL fragment ${name}`); - } - const definitions = defNodes.map(({ - filePath, - content, - definition - }) => getDefinitionForFragmentDefinition(filePath || '', content, definition)); - return { - definitions, - queryRange: definitions.map(_ => getRange(text, fragment)), - printedName: name - }; - }); -} -function getDefinitionQueryResultForDefinitionNode(path, text, definition) { - var _a; - return { - definitions: [getDefinitionForFragmentDefinition(path, text, definition)], - queryRange: definition.name ? [getRange(text, definition.name)] : [], - printedName: (_a = definition.name) === null || _a === void 0 ? void 0 : _a.value - }; -} -function getDefinitionForFragmentDefinition(path, text, definition) { - const { - name - } = definition; - if (!name) { - throw new Error('Expected ASTNode to have a Name.'); - } - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; -} -function getDefinitionForNodeDefinition(path, text, definition) { - const { - name - } = definition; - assert(name, 'Expected ASTNode to have a Name.'); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; -} -function getDefinitionForFieldDefinition(path, text, definition) { - const { - name - } = definition; - assert(name, 'Expected ASTNode to have a Name.'); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; -} -function getDefinitionForArgumentDefinition(path, text, definition) { - const { - name - } = definition; - assert(name, 'Expected ASTNode to have a Name.'); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; -} + /***/ + }, -/***/ }), + /***/ "react-dom": + /*!***************************!*\ + !*** external "ReactDOM" ***! + \***************************/ + /***/ function (module) { + module.exports = window["ReactDOM"]; -/***/ "../../graphql-language-service/esm/interface/getDiagnostics.js": -/*!**********************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getDiagnostics.js ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.SEVERITY = exports.DIAGNOSTIC_SEVERITY = void 0; -exports.getDiagnostics = getDiagnostics; -exports.getRange = getRange; -exports.validateQuery = validateQuery; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); -var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); -const SEVERITY = exports.SEVERITY = { - Error: 'Error', - Warning: 'Warning', - Information: 'Information', - Hint: 'Hint' -}; -const DIAGNOSTIC_SEVERITY = exports.DIAGNOSTIC_SEVERITY = { - [SEVERITY.Error]: 1, - [SEVERITY.Warning]: 2, - [SEVERITY.Information]: 3, - [SEVERITY.Hint]: 4 -}; -const invariant = (condition, message) => { - if (!condition) { - throw new Error(message); - } -}; -function getDiagnostics(query, schema = null, customRules, isRelayCompatMode, externalFragments) { - var _a, _b; - let ast = null; - let fragments = ''; - if (externalFragments) { - fragments = typeof externalFragments === 'string' ? externalFragments : externalFragments.reduce((acc, node) => acc + (0, _graphql.print)(node) + '\n\n', ''); - } - const enhancedQuery = fragments ? `${query}\n\n${fragments}` : query; - try { - ast = (0, _graphql.parse)(enhancedQuery); - } catch (error) { - if (error instanceof _graphql.GraphQLError) { - const range = getRange((_b = (_a = error.locations) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : { - line: 0, - column: 0 - }, enhancedQuery); - return [{ - severity: DIAGNOSTIC_SEVERITY.Error, - message: error.message, - source: 'GraphQL: Syntax', - range - }]; - } - throw error; - } - return validateQuery(ast, schema, customRules, isRelayCompatMode); -} -function validateQuery(ast, schema = null, customRules, isRelayCompatMode) { - if (!schema) { - return []; - } - const validationErrorAnnotations = (0, _utils.validateWithCustomRules)(schema, ast, customRules, isRelayCompatMode).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Error, 'Validation')); - const deprecationWarningAnnotations = (0, _graphql.validate)(schema, ast, [_graphql.NoDeprecatedCustomRule]).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Warning, 'Deprecation')); - return validationErrorAnnotations.concat(deprecationWarningAnnotations); -} -function annotations(error, severity, type) { - if (!error.nodes) { - return []; - } - const highlightedNodes = []; - for (const [i, node] of error.nodes.entries()) { - const highlightNode = node.kind !== 'Variable' && 'name' in node && node.name !== undefined ? node.name : 'variable' in node && node.variable !== undefined ? node.variable : node; - if (highlightNode) { - invariant(error.locations, 'GraphQL validation error requires locations.'); - const loc = error.locations[i]; - const highlightLoc = getLocation(highlightNode); - const end = loc.column + (highlightLoc.end - highlightLoc.start); - highlightedNodes.push({ - source: `GraphQL: ${type}`, - message: error.message, - severity, - range: new _utils.Range(new _utils.Position(loc.line - 1, loc.column - 1), new _utils.Position(loc.line - 1, end)) - }); - } - } - return highlightedNodes; -} -function getRange(location, queryText) { - const parser = (0, _parser.onlineParser)(); - const state = parser.startState(); - const lines = queryText.split('\n'); - invariant(lines.length >= location.line, 'Query text must have more lines than where the error happened'); - let stream = null; - for (let i = 0; i < location.line; i++) { - stream = new _parser.CharacterStream(lines[i]); - while (!stream.eol()) { - const style = parser.token(stream, state); - if (style === 'invalidchar') { - break; - } - } - } - invariant(stream, 'Expected Parser stream to be available.'); - const line = location.line - 1; - const start = stream.getStartOfToken(); - const end = stream.getCurrentPosition(); - return new _utils.Range(new _utils.Position(line, start), new _utils.Position(line, end)); -} -function getLocation(node) { - const typeCastedNode = node; - const location = typeCastedNode.loc; - invariant(location, 'Expected ASTNode to have a location.'); - return location; -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/interface/getHoverInformation.js": -/*!***************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getHoverInformation.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getHoverInformation = getHoverInformation; -exports.renderArg = renderArg; -exports.renderDirective = renderDirective; -exports.renderEnumValue = renderEnumValue; -exports.renderField = renderField; -exports.renderType = renderType; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); -function getHoverInformation(schema, queryText, cursor, contextToken, config) { - const options = Object.assign(Object.assign({}, config), { - schema - }); - const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken); - if (!context) { - return ''; - } - const { - typeInfo, - token - } = context; - const { - kind, - step - } = token.state; - if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef || kind === 'ObjectField' && step === 0 && typeInfo.fieldDef) { - const into = []; - renderMdCodeStart(into, options); - renderField(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.fieldDef); - return into.join('').trim(); - } - if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) { - const into = []; - renderMdCodeStart(into, options); - renderDirective(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.directiveDef); - return into.join('').trim(); - } - if (kind === 'Variable' && typeInfo.type) { - const into = []; - renderMdCodeStart(into, options); - renderType(into, typeInfo, options, typeInfo.type); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.type); - return into.join('').trim(); - } - if (kind === 'Argument' && step === 0 && typeInfo.argDef) { - const into = []; - renderMdCodeStart(into, options); - renderArg(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.argDef); - return into.join('').trim(); - } - if (kind === 'EnumValue' && typeInfo.enumValue && 'description' in typeInfo.enumValue) { - const into = []; - renderMdCodeStart(into, options); - renderEnumValue(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.enumValue); - return into.join('').trim(); - } - if (kind === 'NamedType' && typeInfo.type && 'description' in typeInfo.type) { - const into = []; - renderMdCodeStart(into, options); - renderType(into, typeInfo, options, typeInfo.type); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.type); - return into.join('').trim(); - } - return ''; -} -function renderMdCodeStart(into, options) { - if (options.useMarkdown) { - text(into, '```graphql\n'); - } -} -function renderMdCodeEnd(into, options) { - if (options.useMarkdown) { - text(into, '\n```'); - } -} -function renderField(into, typeInfo, options) { - renderQualifiedField(into, typeInfo, options); - renderTypeAnnotation(into, typeInfo, options, typeInfo.type); -} -function renderQualifiedField(into, typeInfo, options) { - if (!typeInfo.fieldDef) { - return; - } - const fieldName = typeInfo.fieldDef.name; - if (fieldName.slice(0, 2) !== '__') { - renderType(into, typeInfo, options, typeInfo.parentType); - text(into, '.'); - } - text(into, fieldName); -} -function renderDirective(into, typeInfo, _options) { - if (!typeInfo.directiveDef) { - return; - } - const name = '@' + typeInfo.directiveDef.name; - text(into, name); -} -function renderArg(into, typeInfo, options) { - if (typeInfo.directiveDef) { - renderDirective(into, typeInfo, options); - } else if (typeInfo.fieldDef) { - renderQualifiedField(into, typeInfo, options); - } - if (!typeInfo.argDef) { - return; - } - const { - name - } = typeInfo.argDef; - text(into, '('); - text(into, name); - renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); - text(into, ')'); -} -function renderTypeAnnotation(into, typeInfo, options, t) { - text(into, ': '); - renderType(into, typeInfo, options, t); -} -function renderEnumValue(into, typeInfo, options) { - if (!typeInfo.enumValue) { - return; - } - const { - name - } = typeInfo.enumValue; - renderType(into, typeInfo, options, typeInfo.inputType); - text(into, '.'); - text(into, name); -} -function renderType(into, typeInfo, options, t) { - if (!t) { - return; - } - if (t instanceof _graphql.GraphQLNonNull) { - renderType(into, typeInfo, options, t.ofType); - text(into, '!'); - } else if (t instanceof _graphql.GraphQLList) { - text(into, '['); - renderType(into, typeInfo, options, t.ofType); - text(into, ']'); - } else { - text(into, t.name); - } -} -function renderDescription(into, options, def) { - if (!def) { - return; - } - const description = typeof def.description === 'string' ? def.description : null; - if (description) { - text(into, '\n\n'); - text(into, description); - } - renderDeprecation(into, options, def); -} -function renderDeprecation(into, _options, def) { - if (!def) { - return; - } - const reason = def.deprecationReason || null; - if (!reason) { - return; - } - text(into, '\n\n'); - text(into, 'Deprecated: '); - text(into, reason); -} -function text(into, content) { - into.push(content); -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/interface/getOutline.js": -/*!******************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getOutline.js ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getOutline = getOutline; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); -const { - INLINE_FRAGMENT -} = _graphql.Kind; -const OUTLINEABLE_KINDS = { - Field: true, - OperationDefinition: true, - Document: true, - SelectionSet: true, - Name: true, - FragmentDefinition: true, - FragmentSpread: true, - InlineFragment: true, - ObjectTypeDefinition: true, - InputObjectTypeDefinition: true, - InterfaceTypeDefinition: true, - EnumTypeDefinition: true, - EnumValueDefinition: true, - InputValueDefinition: true, - FieldDefinition: true -}; -function getOutline(documentText) { - let ast; - try { - ast = (0, _graphql.parse)(documentText); - } catch (_a) { - return null; - } - const visitorFns = outlineTreeConverter(documentText); - const outlineTrees = (0, _graphql.visit)(ast, { - leave(node) { - if (visitorFns !== undefined && node.kind in visitorFns) { - return visitorFns[node.kind](node); - } - return null; - } - }); - return { - outlineTrees - }; -} -function outlineTreeConverter(docText) { - const meta = node => { - return { - representativeName: node.name, - startPosition: (0, _utils.offsetToPosition)(docText, node.loc.start), - endPosition: (0, _utils.offsetToPosition)(docText, node.loc.end), - kind: node.kind, - children: node.selectionSet || node.fields || node.values || node.arguments || [] - }; - }; - return { - Field(node) { - const tokenizedText = node.alias ? [buildToken('plain', node.alias), buildToken('plain', ': ')] : []; - tokenizedText.push(buildToken('plain', node.name)); - return Object.assign({ - tokenizedText - }, meta(node)); - }, - OperationDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', node.operation), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - Document: node => node.definitions, - SelectionSet: node => concatMap(node.selections, child => { - return child.kind === INLINE_FRAGMENT ? child.selectionSet : child; - }), - Name: node => node.value, - FragmentDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'fragment'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - InterfaceTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'interface'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - EnumTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'enum'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - EnumValueDefinition: node => Object.assign({ - tokenizedText: [buildToken('plain', node.name)] - }, meta(node)), - ObjectTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'type'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - InputObjectTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'input'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - FragmentSpread: node => Object.assign({ - tokenizedText: [buildToken('plain', '...'), buildToken('class-name', node.name)] - }, meta(node)), - InputValueDefinition(node) { - return Object.assign({ - tokenizedText: [buildToken('plain', node.name)] - }, meta(node)); - }, - FieldDefinition(node) { - return Object.assign({ - tokenizedText: [buildToken('plain', node.name)] - }, meta(node)); - }, - InlineFragment: node => node.selectionSet - }; -} -function buildToken(kind, value) { - return { - kind, - value - }; -} -function concatMap(arr, fn) { - const res = []; - for (let i = 0; i < arr.length; i++) { - const x = fn(arr[i], i); - if (Array.isArray(x)) { - res.push(...x); - } else { - res.push(x); - } - } - return res; -} + /***/ + }, -/***/ }), + /***/ "../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs": + /*!***********************************************************************!*\ + !*** ../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs ***! + \***********************************************************************/ + /***/ function (module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __defNormalProp = (obj, key, value) => + key in obj + ? __defProp(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value, + }) + : (obj[key] = value); + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if ( + (from && typeof from === "object") || + typeof from === "function" + ) { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { + get: () => from[key], + enumerable: + !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => ( + (target = mod != null ? __create(__getProtoOf(mod)) : {}), + __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule + ? __defProp(target, "default", { value: mod, enumerable: true }) + : target, + mod + ) + ); + var __toCommonJS = (mod) => + __copyProps(__defProp({}, "__esModule", { value: true }), mod); + var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; -/***/ "../../graphql-language-service/esm/interface/index.js": -/*!*************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/index.js ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // src/index.ts + var src_exports = {}; + __export(src_exports, { + Combobox: () => Combobox, + Dialog: () => Dialog, + Disclosure: () => Disclosure, + FocusTrap: () => FocusTrap, + Listbox: () => Listbox, + Menu: () => Menu, + Popover: () => Popover, + Portal: () => Portal, + RadioGroup: () => RadioGroup, + Switch: () => Switch, + Tab: () => Tab, + Transition: () => Transition, + }); + module.exports = __toCommonJS(src_exports); + // src/components/combobox/combobox.tsx + var import_react19 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + // src/hooks/use-computed.ts + var import_react3 = __webpack_require__(/*! react */ "react"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _exportNames = { - getOutline: true, - getHoverInformation: true -}; -Object.defineProperty(exports, "getHoverInformation", ({ - enumerable: true, - get: function () { - return _getHoverInformation.getHoverInformation; - } -})); -Object.defineProperty(exports, "getOutline", ({ - enumerable: true, - get: function () { - return _getOutline.getOutline; - } -})); -var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); -Object.keys(_autocompleteUtils).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _autocompleteUtils[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _autocompleteUtils[key]; - } - }); -}); -var _getAutocompleteSuggestions = __webpack_require__(/*! ./getAutocompleteSuggestions */ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js"); -Object.keys(_getAutocompleteSuggestions).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getAutocompleteSuggestions[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getAutocompleteSuggestions[key]; - } - }); -}); -var _getDefinition = __webpack_require__(/*! ./getDefinition */ "../../graphql-language-service/esm/interface/getDefinition.js"); -Object.keys(_getDefinition).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getDefinition[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getDefinition[key]; - } - }); -}); -var _getDiagnostics = __webpack_require__(/*! ./getDiagnostics */ "../../graphql-language-service/esm/interface/getDiagnostics.js"); -Object.keys(_getDiagnostics).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getDiagnostics[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getDiagnostics[key]; - } - }); -}); -var _getOutline = __webpack_require__(/*! ./getOutline */ "../../graphql-language-service/esm/interface/getOutline.js"); -var _getHoverInformation = __webpack_require__(/*! ./getHoverInformation */ "../../graphql-language-service/esm/interface/getHoverInformation.js"); + // src/hooks/use-iso-morphic-effect.ts + var import_react = __webpack_require__(/*! react */ "react"); -/***/ }), + // src/utils/env.ts + var Env = class { + constructor() { + __publicField(this, "current", this.detect()); + __publicField(this, "handoffState", "pending"); + __publicField(this, "currentId", 0); + } + set(env2) { + if (this.current === env2) return; + this.handoffState = "pending"; + this.currentId = 0; + this.current = env2; + } + reset() { + this.set(this.detect()); + } + nextId() { + return ++this.currentId; + } + get isServer() { + return this.current === "server"; + } + get isClient() { + return this.current === "client"; + } + detect() { + if ( + typeof window === "undefined" || + typeof document === "undefined" + ) { + return "server"; + } + return "client"; + } + handoff() { + if (this.handoffState === "pending") { + this.handoffState = "complete"; + } + } + get isHandoffComplete() { + return this.handoffState === "complete"; + } + }; + var env = new Env(); -/***/ "../../graphql-language-service/esm/parser/CharacterStream.js": -/*!********************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/CharacterStream.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -class CharacterStream { - constructor(sourceText) { - this._start = 0; - this._pos = 0; - this.getStartOfToken = () => this._start; - this.getCurrentPosition = () => this._pos; - this.eol = () => this._sourceText.length === this._pos; - this.sol = () => this._pos === 0; - this.peek = () => { - return this._sourceText.charAt(this._pos) || null; - }; - this.next = () => { - const char = this._sourceText.charAt(this._pos); - this._pos++; - return char; - }; - this.eat = pattern => { - const isMatched = this._testNextCharacter(pattern); - if (isMatched) { - this._start = this._pos; - this._pos++; - return this._sourceText.charAt(this._pos - 1); - } - return undefined; - }; - this.eatWhile = match => { - let isMatched = this._testNextCharacter(match); - let didEat = false; - if (isMatched) { - didEat = isMatched; - this._start = this._pos; - } - while (isMatched) { - this._pos++; - isMatched = this._testNextCharacter(match); - didEat = true; - } - return didEat; - }; - this.eatSpace = () => this.eatWhile(/[\s\u00a0]/); - this.skipToEnd = () => { - this._pos = this._sourceText.length; - }; - this.skipTo = position => { - this._pos = position; - }; - this.match = (pattern, consume = true, caseFold = false) => { - let token = null; - let match = null; - if (typeof pattern === 'string') { - const regex = new RegExp(pattern, caseFold ? 'i' : 'g'); - match = regex.test(this._sourceText.slice(this._pos, this._pos + pattern.length)); - token = pattern; - } else if (pattern instanceof RegExp) { - match = this._sourceText.slice(this._pos).match(pattern); - token = match === null || match === void 0 ? void 0 : match[0]; - } - if (match != null && (typeof pattern === 'string' || match instanceof Array && this._sourceText.startsWith(match[0], this._pos))) { - if (consume) { - this._start = this._pos; - if (token && token.length) { - this._pos += token.length; + // src/hooks/use-iso-morphic-effect.ts + var useIsoMorphicEffect = (effect, deps) => { + if (env.isServer) { + (0, import_react.useEffect)(effect, deps); + } else { + (0, import_react.useLayoutEffect)(effect, deps); } + }; + + // src/hooks/use-latest-value.ts + var import_react2 = __webpack_require__(/*! react */ "react"); + function useLatestValue(value) { + let cache = (0, import_react2.useRef)(value); + useIsoMorphicEffect(() => { + cache.current = value; + }, [value]); + return cache; + } + + // src/hooks/use-computed.ts + function useComputed(cb, dependencies) { + let [value, setValue] = (0, import_react3.useState)(cb); + let cbRef = useLatestValue(cb); + useIsoMorphicEffect( + () => setValue(cbRef.current), + [cbRef, setValue, ...dependencies] + ); + return value; } - return match; - } - return false; - }; - this.backUp = num => { - this._pos -= num; - }; - this.column = () => this._pos; - this.indentation = () => { - const match = this._sourceText.match(/\s*/); - let indent = 0; - if (match && match.length !== 0) { - const whiteSpaces = match[0]; - let pos = 0; - while (whiteSpaces.length > pos) { - if (whiteSpaces.charCodeAt(pos) === 9) { - indent += 2; + + // src/hooks/use-disposables.ts + var import_react4 = __webpack_require__(/*! react */ "react"); + + // src/utils/micro-task.ts + function microTask(cb) { + if (typeof queueMicrotask === "function") { + queueMicrotask(cb); } else { - indent++; - } - pos++; + Promise.resolve() + .then(cb) + .catch((e) => + setTimeout(() => { + throw e; + }) + ); + } + } + + // src/utils/disposables.ts + function disposables() { + let _disposables = []; + let api = { + addEventListener(element, name, listener, options) { + element.addEventListener(name, listener, options); + return api.add(() => + element.removeEventListener(name, listener, options) + ); + }, + requestAnimationFrame(...args) { + let raf = requestAnimationFrame(...args); + return api.add(() => cancelAnimationFrame(raf)); + }, + nextFrame(...args) { + return api.requestAnimationFrame(() => { + return api.requestAnimationFrame(...args); + }); + }, + setTimeout(...args) { + let timer = setTimeout(...args); + return api.add(() => clearTimeout(timer)); + }, + microTask(...args) { + let task = { current: true }; + microTask(() => { + if (task.current) { + args[0](); + } + }); + return api.add(() => { + task.current = false; + }); + }, + style(node, property, value) { + let previous = node.style.getPropertyValue(property); + Object.assign(node.style, { [property]: value }); + return this.add(() => { + Object.assign(node.style, { [property]: previous }); + }); + }, + group(cb) { + let d = disposables(); + cb(d); + return this.add(() => d.dispose()); + }, + add(cb) { + _disposables.push(cb); + return () => { + let idx = _disposables.indexOf(cb); + if (idx >= 0) { + for (let dispose of _disposables.splice(idx, 1)) { + dispose(); + } + } + }; + }, + dispose() { + for (let dispose of _disposables.splice(0)) { + dispose(); + } + }, + }; + return api; } - } - return indent; - }; - this.current = () => this._sourceText.slice(this._start, this._pos); - this._sourceText = sourceText; - } - _testNextCharacter(pattern) { - const character = this._sourceText.charAt(this._pos); - let isMatched = false; - if (typeof pattern === 'string') { - isMatched = character === pattern; - } else { - isMatched = pattern instanceof RegExp ? pattern.test(character) : pattern(character); - } - return isMatched; - } -} -exports["default"] = CharacterStream; -/***/ }), + // src/hooks/use-disposables.ts + function useDisposables() { + let [d] = (0, import_react4.useState)(disposables); + (0, import_react4.useEffect)(() => () => d.dispose(), [d]); + return d; + } -/***/ "../../graphql-language-service/esm/parser/RuleHelpers.js": -/*!****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/RuleHelpers.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports) { + // src/hooks/use-event.ts + var import_react5 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var useEvent = + // TODO: Add React.useEvent ?? once the useEvent hook is available + function useEvent2(cb) { + let cache = useLatestValue(cb); + return import_react5.default.useCallback( + (...args) => cache.current(...args), + [cache] + ); + }; + // src/hooks/use-id.ts + var import_react7 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + // src/hooks/use-server-handoff-complete.ts + var import_react6 = __webpack_require__(/*! react */ "react"); + function useServerHandoffComplete() { + let [complete, setComplete] = (0, import_react6.useState)( + env.isHandoffComplete + ); + if (complete && env.isHandoffComplete === false) { + setComplete(false); + } + (0, import_react6.useEffect)(() => { + if (complete === true) return; + setComplete(true); + }, [complete]); + (0, import_react6.useEffect)(() => env.handoff(), []); + return complete; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.butNot = butNot; -exports.list = list; -exports.opt = opt; -exports.p = p; -exports.t = t; -function opt(ofRule) { - return { - ofRule - }; -} -function list(ofRule, separator) { - return { - ofRule, - isList: true, - separator - }; -} -function butNot(rule, exclusions) { - const ruleMatch = rule.match; - rule.match = token => { - let check = false; - if (ruleMatch) { - check = ruleMatch(token); - } - return check && exclusions.every(exclusion => exclusion.match && !exclusion.match(token)); - }; - return rule; -} -function t(kind, style) { - return { - style, - match: token => token.kind === kind - }; -} -function p(value, style) { - return { - style: style || 'punctuation', - match: token => token.kind === 'Punctuation' && token.value === value - }; -} + // src/hooks/use-id.ts + var _a; + var useId = + // Prefer React's `useId` if it's available. + // @ts-expect-error - `useId` doesn't exist in React < 18. + (_a = import_react7.default.useId) != null + ? _a + : function useId2() { + let ready = useServerHandoffComplete(); + let [id, setId] = import_react7.default.useState( + ready ? () => env.nextId() : null + ); + useIsoMorphicEffect(() => { + if (id === null) setId(env.nextId()); + }, [id]); + return id != null ? "" + id : void 0; + }; + + // src/hooks/use-outside-click.ts + var import_react10 = __webpack_require__(/*! react */ "react"); + + // src/utils/match.ts + function match(value, lookup, ...args) { + if (value in lookup) { + let returnValue = lookup[value]; + return typeof returnValue === "function" + ? returnValue(...args) + : returnValue; + } + let error = new Error( + `Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys( + lookup + ) + .map((key) => `"${key}"`) + .join(", ")}.` + ); + if (Error.captureStackTrace) Error.captureStackTrace(error, match); + throw error; + } + + // src/utils/owner.ts + function getOwnerDocument(element) { + if (env.isServer) return null; + if (element instanceof Node) return element.ownerDocument; + if (element == null ? void 0 : element.hasOwnProperty("current")) { + if (element.current instanceof Node) + return element.current.ownerDocument; + } + return document; + } + + // src/utils/focus-management.ts + var focusableSelector = [ + "[contentEditable=true]", + "[tabindex]", + "a[href]", + "area[href]", + "button:not([disabled])", + "iframe", + "input:not([disabled])", + "select:not([disabled])", + "textarea:not([disabled])", + ] + .map( + false + ? // TODO: Remove this once JSDOM fixes the issue where an element that is + // "hidden" can be the document.activeElement, because this is not possible + // in real browsers. + 0 + : (selector) => `${selector}:not([tabindex='-1'])` + ) + .join(","); + function getFocusableElements(container = document.body) { + if (container == null) return []; + return Array.from(container.querySelectorAll(focusableSelector)).sort( + // We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well. + (a, z) => + Math.sign( + (a.tabIndex || Number.MAX_SAFE_INTEGER) - + (z.tabIndex || Number.MAX_SAFE_INTEGER) + ) + ); + } + function isFocusableElement(element, mode = 0 /* Strict */) { + var _a3; + if ( + element === + ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body) + ) + return false; + return match(mode, { + [0 /* Strict */]() { + return element.matches(focusableSelector); + }, + [1 /* Loose */]() { + let next = element; + while (next !== null) { + if (next.matches(focusableSelector)) return true; + next = next.parentElement; + } + return false; + }, + }); + } + function restoreFocusIfNecessary(element) { + let ownerDocument = getOwnerDocument(element); + disposables().nextFrame(() => { + if ( + ownerDocument && + !isFocusableElement(ownerDocument.activeElement, 0 /* Strict */) + ) { + focusElement(element); + } + }); + } + if (typeof window !== "undefined" && typeof document !== "undefined") { + document.addEventListener( + "keydown", + (event) => { + if (event.metaKey || event.altKey || event.ctrlKey) { + return; + } + document.documentElement.dataset.headlessuiFocusVisible = ""; + }, + true + ); + document.addEventListener( + "click", + (event) => { + if (event.detail === 1 /* Mouse */) { + delete document.documentElement.dataset.headlessuiFocusVisible; + } else if (event.detail === 0 /* Keyboard */) { + document.documentElement.dataset.headlessuiFocusVisible = ""; + } + }, + true + ); + } + function focusElement(element) { + element == null ? void 0 : element.focus({ preventScroll: true }); + } + var selectableSelector = ["textarea", "input"].join(","); + function isSelectableElement(element) { + var _a3, _b; + return (_b = + (_a3 = element == null ? void 0 : element.matches) == null + ? void 0 + : _a3.call(element, selectableSelector)) != null + ? _b + : false; + } + function sortByDomNode(nodes, resolveKey = (i) => i) { + return nodes.slice().sort((aItem, zItem) => { + let a = resolveKey(aItem); + let z = resolveKey(zItem); + if (a === null || z === null) return 0; + let position = a.compareDocumentPosition(z); + if (position & Node.DOCUMENT_POSITION_FOLLOWING) return -1; + if (position & Node.DOCUMENT_POSITION_PRECEDING) return 1; + return 0; + }); + } + function focusFrom(current, focus) { + return focusIn(getFocusableElements(), focus, { + relativeTo: current, + }); + } + function focusIn( + container, + focus, + { sorted = true, relativeTo = null, skipElements = [] } = {} + ) { + let ownerDocument = Array.isArray(container) + ? container.length > 0 + ? container[0].ownerDocument + : document + : container.ownerDocument; + let elements = Array.isArray(container) + ? sorted + ? sortByDomNode(container) + : container + : getFocusableElements(container); + if (skipElements.length > 0 && elements.length > 1) { + elements = elements.filter((x) => !skipElements.includes(x)); + } + relativeTo = + relativeTo != null ? relativeTo : ownerDocument.activeElement; + let direction = (() => { + if (focus & (1 /* First */ | 4) /* Next */) return 1 /* Next */; + if (focus & (2 /* Previous */ | 8) /* Last */) + return -1 /* Previous */; + throw new Error( + "Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last" + ); + })(); + let startIndex = (() => { + if (focus & 1 /* First */) return 0; + if (focus & 2 /* Previous */) + return Math.max(0, elements.indexOf(relativeTo)) - 1; + if (focus & 4 /* Next */) + return Math.max(0, elements.indexOf(relativeTo)) + 1; + if (focus & 8 /* Last */) return elements.length - 1; + throw new Error( + "Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last" + ); + })(); + let focusOptions = + focus & 32 /* NoScroll */ ? { preventScroll: true } : {}; + let offset = 0; + let total = elements.length; + let next = void 0; + do { + if (offset >= total || offset + total <= 0) return 0 /* Error */; + let nextIdx = startIndex + offset; + if (focus & 16 /* WrapAround */) { + nextIdx = (nextIdx + total) % total; + } else { + if (nextIdx < 0) return 3 /* Underflow */; + if (nextIdx >= total) return 1 /* Overflow */; + } + next = elements[nextIdx]; + next == null ? void 0 : next.focus(focusOptions); + offset += direction; + } while (next !== ownerDocument.activeElement); + if ( + focus & (4 /* Next */ | 2) /* Previous */ && + isSelectableElement(next) + ) { + next.select(); + } + return 2 /* Success */; + } + + // src/hooks/use-document-event.ts + var import_react8 = __webpack_require__(/*! react */ "react"); + function useDocumentEvent(type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react8.useEffect)(() => { + function handler(event) { + listenerRef.current(event); + } + document.addEventListener(type, handler, options); + return () => document.removeEventListener(type, handler, options); + }, [type, options]); + } + + // src/hooks/use-window-event.ts + var import_react9 = __webpack_require__(/*! react */ "react"); + function useWindowEvent(type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react9.useEffect)(() => { + function handler(event) { + listenerRef.current(event); + } + window.addEventListener(type, handler, options); + return () => window.removeEventListener(type, handler, options); + }, [type, options]); + } + + // src/hooks/use-outside-click.ts + function useOutsideClick(containers, cb, enabled = true) { + let enabledRef = (0, import_react10.useRef)(false); + (0, import_react10.useEffect)( + false + ? 0 + : () => { + requestAnimationFrame(() => { + enabledRef.current = enabled; + }); + }, + [enabled] + ); + function handleOutsideClick(event, resolveTarget) { + if (!enabledRef.current) return; + if (event.defaultPrevented) return; + let target = resolveTarget(event); + if (target === null) { + return; + } + if (!target.getRootNode().contains(target)) return; + let _containers = (function resolve(containers2) { + if (typeof containers2 === "function") { + return resolve(containers2()); + } + if (Array.isArray(containers2)) { + return containers2; + } + if (containers2 instanceof Set) { + return containers2; + } + return [containers2]; + })(containers); + for (let container of _containers) { + if (container === null) continue; + let domNode = + container instanceof HTMLElement + ? container + : container.current; + if (domNode == null ? void 0 : domNode.contains(target)) { + return; + } + if (event.composed && event.composedPath().includes(domNode)) { + return; + } + } + if ( + // This check alllows us to know whether or not we clicked on a "focusable" element like a + // button or an input. This is a backwards compatibility check so that you can open a

    and click on another which should close Menu A and open Menu B. We might + // revisit that so that you will require 2 clicks instead. + !isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1} to make it + // unfocusable via the keyboard so that tabbing to the next item from the input doesn't + // first go to the button. + target.tabIndex !== -1 + ) { + event.preventDefault(); + } + return cb(event, target); + } + let initialClickTarget = (0, import_react10.useRef)(null); + useDocumentEvent( + "mousedown", + (event) => { + var _a3, _b; + if (enabledRef.current) { + initialClickTarget.current = + ((_b = + (_a3 = event.composedPath) == null + ? void 0 + : _a3.call(event)) == null + ? void 0 + : _b[0]) || event.target; + } + }, + true + ); + useDocumentEvent( + "click", + (event) => { + if (!initialClickTarget.current) { + return; + } + handleOutsideClick(event, () => { + return initialClickTarget.current; + }); + initialClickTarget.current = null; + }, + // We will use the `capture` phase so that layers in between with `event.stopPropagation()` + // don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu` + // is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However, + // the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this. + true + ); + useWindowEvent( + "blur", + (event) => + handleOutsideClick(event, () => + window.document.activeElement instanceof HTMLIFrameElement + ? window.document.activeElement + : null + ), + true + ); + } -/***/ }), + // src/hooks/use-resolve-button-type.ts + var import_react11 = __webpack_require__(/*! react */ "react"); + function resolveType(props) { + var _a3; + if (props.type) return props.type; + let tag = (_a3 = props.as) != null ? _a3 : "button"; + if (typeof tag === "string" && tag.toLowerCase() === "button") + return "button"; + return void 0; + } + function useResolveButtonType(props, ref) { + let [type, setType] = (0, import_react11.useState)(() => + resolveType(props) + ); + useIsoMorphicEffect(() => { + setType(resolveType(props)); + }, [props.type, props.as]); + useIsoMorphicEffect(() => { + if (type) return; + if (!ref.current) return; + if ( + ref.current instanceof HTMLButtonElement && + !ref.current.hasAttribute("type") + ) { + setType("button"); + } + }, [type, ref]); + return type; + } + + // src/hooks/use-sync-refs.ts + var import_react12 = __webpack_require__(/*! react */ "react"); + var Optional = Symbol(); + function optionalRef(cb, isOptional = true) { + return Object.assign(cb, { [Optional]: isOptional }); + } + function useSyncRefs(...refs) { + let cache = (0, import_react12.useRef)(refs); + (0, import_react12.useEffect)(() => { + cache.current = refs; + }, [refs]); + let syncRefs = useEvent((value) => { + for (let ref of cache.current) { + if (ref == null) continue; + if (typeof ref === "function") ref(value); + else ref.current = value; + } + }); + return refs.every( + (ref) => + ref == null || // @ts-expect-error + (ref == null ? void 0 : ref[Optional]) + ) + ? void 0 + : syncRefs; + } + + // src/hooks/use-tree-walker.ts + var import_react13 = __webpack_require__(/*! react */ "react"); + function useTreeWalker({ container, accept, walk, enabled = true }) { + let acceptRef = (0, import_react13.useRef)(accept); + let walkRef = (0, import_react13.useRef)(walk); + (0, import_react13.useEffect)(() => { + acceptRef.current = accept; + walkRef.current = walk; + }, [accept, walk]); + useIsoMorphicEffect(() => { + if (!container) return; + if (!enabled) return; + let ownerDocument = getOwnerDocument(container); + if (!ownerDocument) return; + let accept2 = acceptRef.current; + let walk2 = walkRef.current; + let acceptNode = Object.assign((node) => accept2(node), { + acceptNode: accept2, + }); + let walker = ownerDocument.createTreeWalker( + container, + NodeFilter.SHOW_ELEMENT, + acceptNode, + // @ts-expect-error This `false` is a simple small fix for older browsers + false + ); + while (walker.nextNode()) walk2(walker.currentNode); + }, [container, enabled, acceptRef, walkRef]); + } + + // src/utils/calculate-active-index.ts + function assertNever(x) { + throw new Error("Unexpected object: " + x); + } + function calculateActiveIndex(action, resolvers) { + let items = resolvers.resolveItems(); + if (items.length <= 0) return null; + let currentActiveIndex = resolvers.resolveActiveIndex(); + let activeIndex = + currentActiveIndex != null ? currentActiveIndex : -1; + let nextActiveIndex = (() => { + switch (action.focus) { + case 0 /* First */: + return items.findIndex( + (item) => !resolvers.resolveDisabled(item) + ); + case 1 /* Previous */: { + let idx = items + .slice() + .reverse() + .findIndex((item, idx2, all) => { + if ( + activeIndex !== -1 && + all.length - idx2 - 1 >= activeIndex + ) + return false; + return !resolvers.resolveDisabled(item); + }); + if (idx === -1) return idx; + return items.length - 1 - idx; + } + case 2 /* Next */: + return items.findIndex((item, idx) => { + if (idx <= activeIndex) return false; + return !resolvers.resolveDisabled(item); + }); + case 3 /* Last */: { + let idx = items + .slice() + .reverse() + .findIndex((item) => !resolvers.resolveDisabled(item)); + if (idx === -1) return idx; + return items.length - 1 - idx; + } + case 4 /* Specific */: + return items.findIndex( + (item) => resolvers.resolveId(item) === action.id + ); + case 5 /* Nothing */: + return null; + default: + assertNever(action); + } + })(); + return nextActiveIndex === -1 ? currentActiveIndex : nextActiveIndex; + } -/***/ "../../graphql-language-service/esm/parser/Rules.js": -/*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/Rules.js ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isIgnored = exports.ParseRules = exports.LexRules = void 0; -var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const isIgnored = ch => ch === ' ' || ch === '\t' || ch === ',' || ch === '\n' || ch === '\r' || ch === '\uFEFF' || ch === '\u00A0'; -exports.isIgnored = isIgnored; -const LexRules = exports.LexRules = { - Name: /^[_A-Za-z][_0-9A-Za-z]*/, - Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|&|@|\[|]|\{|\||\})/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/, - Comment: /^#.*/ -}; -const ParseRules = exports.ParseRules = { - Document: [(0, _RuleHelpers.list)('Definition')], - Definition(token) { - switch (token.value) { - case '{': - return 'ShortQuery'; - case 'query': - return 'Query'; - case 'mutation': - return 'Mutation'; - case 'subscription': - return 'Subscription'; - case 'fragment': - return _graphql.Kind.FRAGMENT_DEFINITION; - case 'schema': - return 'SchemaDef'; - case 'scalar': - return 'ScalarDef'; - case 'type': - return 'ObjectTypeDef'; - case 'interface': - return 'InterfaceDef'; - case 'union': - return 'UnionDef'; - case 'enum': - return 'EnumDef'; - case 'input': - return 'InputDef'; - case 'extend': - return 'ExtendDef'; - case 'directive': - return 'DirectiveDef'; - } - }, - ShortQuery: ['SelectionSet'], - Query: [word('query'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - Mutation: [word('mutation'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - Subscription: [word('subscription'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - VariableDefinitions: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('VariableDefinition'), (0, _RuleHelpers.p)(')')], - VariableDefinition: ['Variable', (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue')], - Variable: [(0, _RuleHelpers.p)('$', 'variable'), name('variable')], - DefaultValue: [(0, _RuleHelpers.p)('='), 'Value'], - SelectionSet: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Selection'), (0, _RuleHelpers.p)('}')], - Selection(token, stream) { - return token.value === '...' ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field'; - }, - AliasedField: [name('property'), (0, _RuleHelpers.p)(':'), name('qualifier'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], - Field: [name('property'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], - Arguments: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('Argument'), (0, _RuleHelpers.p)(')')], - Argument: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], - FragmentSpread: [(0, _RuleHelpers.p)('...'), name('def'), (0, _RuleHelpers.list)('Directive')], - InlineFragment: [(0, _RuleHelpers.p)('...'), (0, _RuleHelpers.opt)('TypeCondition'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - FragmentDefinition: [word('fragment'), (0, _RuleHelpers.opt)((0, _RuleHelpers.butNot)(name('def'), [word('on')])), 'TypeCondition', (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - TypeCondition: [word('on'), 'NamedType'], - Value(token) { - switch (token.kind) { - case 'Number': - return 'NumberValue'; - case 'String': - return 'StringValue'; - case 'Punctuation': - switch (token.value) { - case '[': - return 'ListValue'; - case '{': - return 'ObjectValue'; - case '$': - return 'Variable'; - case '&': - return 'NamedType'; - } - return null; - case 'Name': - switch (token.value) { - case 'true': - case 'false': - return 'BooleanValue'; - } - if (token.value === 'null') { - return 'NullValue'; - } - return 'EnumValue'; - } - }, - NumberValue: [(0, _RuleHelpers.t)('Number', 'number')], - StringValue: [{ - style: 'string', - match: token => token.kind === 'String', - update(state, token) { - if (token.value.startsWith('"""')) { - state.inBlockstring = !token.value.slice(3).endsWith('"""'); - } - } - }], - BooleanValue: [(0, _RuleHelpers.t)('Name', 'builtin')], - NullValue: [(0, _RuleHelpers.t)('Name', 'keyword')], - EnumValue: [name('string-2')], - ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value'), (0, _RuleHelpers.p)(']')], - ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField'), (0, _RuleHelpers.p)('}')], - ObjectField: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], - Type(token) { - return token.value === '[' ? 'ListType' : 'NonNullType'; - }, - ListType: [(0, _RuleHelpers.p)('['), 'Type', (0, _RuleHelpers.p)(']'), (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], - NonNullType: ['NamedType', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], - NamedType: [type('atom')], - Directive: [(0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('Arguments')], - DirectiveDef: [word('directive'), (0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('ArgumentsDef'), word('on'), (0, _RuleHelpers.list)('DirectiveLocation', (0, _RuleHelpers.p)('|'))], - InterfaceDef: [word('interface'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], - Implements: [word('implements'), (0, _RuleHelpers.list)('NamedType', (0, _RuleHelpers.p)('&'))], - DirectiveLocation: [name('string-2')], - SchemaDef: [word('schema'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('OperationTypeDef'), (0, _RuleHelpers.p)('}')], - OperationTypeDef: [name('keyword'), (0, _RuleHelpers.p)(':'), name('atom')], - ScalarDef: [word('scalar'), name('atom'), (0, _RuleHelpers.list)('Directive')], - ObjectTypeDef: [word('type'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], - FieldDef: [name('property'), (0, _RuleHelpers.opt)('ArgumentsDef'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.list)('Directive')], - ArgumentsDef: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)(')')], - InputValueDef: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue'), (0, _RuleHelpers.list)('Directive')], - UnionDef: [word('union'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('='), (0, _RuleHelpers.list)('UnionMember', (0, _RuleHelpers.p)('|'))], - UnionMember: ['NamedType'], - EnumDef: [word('enum'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('EnumValueDef'), (0, _RuleHelpers.p)('}')], - EnumValueDef: [name('string-2'), (0, _RuleHelpers.list)('Directive')], - InputDef: [word('input'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)('}')], - ExtendDef: [word('extend'), 'ExtensionDefinition'], - ExtensionDefinition(token) { - switch (token.value) { - case 'schema': - return _graphql.Kind.SCHEMA_EXTENSION; - case 'scalar': - return _graphql.Kind.SCALAR_TYPE_EXTENSION; - case 'type': - return _graphql.Kind.OBJECT_TYPE_EXTENSION; - case 'interface': - return _graphql.Kind.INTERFACE_TYPE_EXTENSION; - case 'union': - return _graphql.Kind.UNION_TYPE_EXTENSION; - case 'enum': - return _graphql.Kind.ENUM_TYPE_EXTENSION; - case 'input': - return _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION; - } - }, - [_graphql.Kind.SCHEMA_EXTENSION]: ['SchemaDef'], - [_graphql.Kind.SCALAR_TYPE_EXTENSION]: ['ScalarDef'], - [_graphql.Kind.OBJECT_TYPE_EXTENSION]: ['ObjectTypeDef'], - [_graphql.Kind.INTERFACE_TYPE_EXTENSION]: ['InterfaceDef'], - [_graphql.Kind.UNION_TYPE_EXTENSION]: ['UnionDef'], - [_graphql.Kind.ENUM_TYPE_EXTENSION]: ['EnumDef'], - [_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]: ['InputDef'] -}; -function word(value) { - return { - style: 'keyword', - match: token => token.kind === 'Name' && token.value === value - }; -} -function name(style) { - return { - style, - match: token => token.kind === 'Name', - update(state, token) { - state.name = token.value; - } - }; -} -function type(style) { - return { - style, - match: token => token.kind === 'Name', - update(state, token) { - var _a; - if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.prevState) { - state.name = token.value; - state.prevState.prevState.type = token.value; - } - } - }; -} + // src/utils/render.ts + var import_react14 = __webpack_require__(/*! react */ "react"); -/***/ }), + // src/utils/class-names.ts + function classNames(...classes) { + return classes.filter(Boolean).join(" "); + } -/***/ "../../graphql-language-service/esm/parser/api.js": -/*!********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/api.js ***! - \********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.TYPE_SYSTEM_KINDS = exports.GraphQLDocumentMode = void 0; -exports.getContextAtPosition = getContextAtPosition; -exports.getDocumentMode = getDocumentMode; -exports.getTokenAtPosition = getTokenAtPosition; -exports.runOnlineParser = runOnlineParser; -var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function runOnlineParser(queryText, callback) { - const lines = queryText.split('\n'); - const parser = (0, _.onlineParser)(); - let state = parser.startState(); - let style = ''; - let stream = new _.CharacterStream(''); - for (let i = 0; i < lines.length; i++) { - stream = new _.CharacterStream(lines[i]); - while (!stream.eol()) { - style = parser.token(stream, state); - const code = callback(stream, state, style, i); - if (code === 'BREAK') { - break; - } - } - callback(stream, state, style, i); - if (!state.kind) { - state = parser.startState(); - } - } - return { - start: stream.getStartOfToken(), - end: stream.getCurrentPosition(), - string: stream.current(), - state, - style - }; -} -var GraphQLDocumentMode; -(function (GraphQLDocumentMode) { - GraphQLDocumentMode["TYPE_SYSTEM"] = "TYPE_SYSTEM"; - GraphQLDocumentMode["EXECUTABLE"] = "EXECUTABLE"; - GraphQLDocumentMode["UNKNOWN"] = "UNKNOWN"; -})(GraphQLDocumentMode || (exports.GraphQLDocumentMode = GraphQLDocumentMode = {})); -const TYPE_SYSTEM_KINDS = exports.TYPE_SYSTEM_KINDS = [_graphql.Kind.SCHEMA_DEFINITION, _graphql.Kind.OPERATION_TYPE_DEFINITION, _graphql.Kind.SCALAR_TYPE_DEFINITION, _graphql.Kind.OBJECT_TYPE_DEFINITION, _graphql.Kind.INTERFACE_TYPE_DEFINITION, _graphql.Kind.UNION_TYPE_DEFINITION, _graphql.Kind.ENUM_TYPE_DEFINITION, _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION, _graphql.Kind.DIRECTIVE_DEFINITION, _graphql.Kind.SCHEMA_EXTENSION, _graphql.Kind.SCALAR_TYPE_EXTENSION, _graphql.Kind.OBJECT_TYPE_EXTENSION, _graphql.Kind.INTERFACE_TYPE_EXTENSION, _graphql.Kind.UNION_TYPE_EXTENSION, _graphql.Kind.ENUM_TYPE_EXTENSION, _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]; -const getParsedMode = sdl => { - let mode = GraphQLDocumentMode.UNKNOWN; - if (sdl) { - try { - (0, _graphql.visit)((0, _graphql.parse)(sdl), { - enter(node) { - if (node.kind === 'Document') { - mode = GraphQLDocumentMode.EXECUTABLE; - return; + // src/utils/render.ts + function render({ + ourProps, + theirProps, + slot, + defaultTag, + features, + visible = true, + name, + }) { + let props = mergeProps(theirProps, ourProps); + if (visible) return _render(props, slot, defaultTag, name); + let featureFlags = features != null ? features : 0; /* None */ + if (featureFlags & 2 /* Static */) { + let { static: isStatic = false, ...rest } = props; + if (isStatic) return _render(rest, slot, defaultTag, name); + } + if (featureFlags & 1 /* RenderStrategy */) { + let { unmount = true, ...rest } = props; + let strategy = unmount ? 0 /* Unmount */ : 1; /* Hidden */ + return match(strategy, { + [0 /* Unmount */]() { + return null; + }, + [1 /* Hidden */]() { + return _render( + { ...rest, ...{ hidden: true, style: { display: "none" } } }, + slot, + defaultTag, + name + ); + }, + }); } - if (TYPE_SYSTEM_KINDS.includes(node.kind)) { - mode = GraphQLDocumentMode.TYPE_SYSTEM; - return _graphql.BREAK; + return _render(props, slot, defaultTag, name); + } + function _render(props, slot = {}, tag, name) { + let { + as: Component = tag, + children, + refName = "ref", + ...rest + } = omit(props, ["unmount", "static"]); + let refRelatedProps = + props.ref !== void 0 ? { [refName]: props.ref } : {}; + let resolvedChildren = + typeof children === "function" ? children(slot) : children; + if ( + "className" in rest && + rest.className && + typeof rest.className === "function" + ) { + rest.className = rest.className(slot); + } + let dataAttributes = {}; + if (slot) { + let exposeState = false; + let states = []; + for (let [k, v] of Object.entries(slot)) { + if (typeof v === "boolean") { + exposeState = true; + } + if (v === true) { + states.push(k); + } + } + if (exposeState) + dataAttributes[`data-headlessui-state`] = states.join(" "); + } + if (Component === import_react14.Fragment) { + if (Object.keys(compact(rest)).length > 0) { + if ( + !(0, import_react14.isValidElement)(resolvedChildren) || + (Array.isArray(resolvedChildren) && resolvedChildren.length > 1) + ) { + throw new Error( + [ + 'Passing props on "Fragment"!', + "", + `The current component <${name} /> is rendering a "Fragment".`, + `However we need to passthrough the following props:`, + Object.keys(rest) + .map((line) => ` - ${line}`) + .join("\n"), + "", + "You can apply a few solutions:", + [ + 'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', + "Render a single element as the child so that we can forward the props onto that element.", + ] + .map((line) => ` - ${line}`) + .join("\n"), + ].join("\n") + ); + } + let childProps = resolvedChildren.props; + let newClassName = + typeof (childProps == null ? void 0 : childProps.className) === + "function" + ? (...args) => + classNames( + childProps == null + ? void 0 + : childProps.className(...args), + rest.className + ) + : classNames( + childProps == null ? void 0 : childProps.className, + rest.className + ); + let classNameProps = newClassName + ? { className: newClassName } + : {}; + return (0, import_react14.cloneElement)( + resolvedChildren, + Object.assign( + {}, + // Filter out undefined values so that they don't override the existing values + mergeProps( + resolvedChildren.props, + compact(omit(rest, ["ref"])) + ), + dataAttributes, + refRelatedProps, + mergeRefs(resolvedChildren.ref, refRelatedProps.ref), + classNameProps + ) + ); + } } - return false; + return (0, import_react14.createElement)( + Component, + Object.assign( + {}, + omit(rest, ["ref"]), + Component !== import_react14.Fragment && refRelatedProps, + Component !== import_react14.Fragment && dataAttributes + ), + resolvedChildren + ); } - }); - } catch (_a) { - return mode; - } - } - return mode; -}; -function getDocumentMode(documentText, uri) { - if (uri === null || uri === void 0 ? void 0 : uri.endsWith('.graphqls')) { - return GraphQLDocumentMode.TYPE_SYSTEM; - } - return getParsedMode(documentText); -} -function getTokenAtPosition(queryText, cursor, offset = 0) { - let styleAtCursor = null; - let stateAtCursor = null; - let stringAtCursor = null; - const token = runOnlineParser(queryText, (stream, state, style, index) => { - if (index !== cursor.line || stream.getCurrentPosition() + offset < cursor.character + 1) { - return; - } - styleAtCursor = style; - stateAtCursor = Object.assign({}, state); - stringAtCursor = stream.current(); - return 'BREAK'; - }); - return { - start: token.start, - end: token.end, - string: stringAtCursor || token.string, - state: stateAtCursor || token.state, - style: styleAtCursor || token.style - }; -} -function getContextAtPosition(queryText, cursor, schema, contextToken, options) { - const token = contextToken || getTokenAtPosition(queryText, cursor, 1); - if (!token) { - return null; - } - const state = token.state.kind === 'Invalid' ? token.state.prevState : token.state; - if (!state) { - return null; - } - const typeInfo = (0, _.getTypeInfo)(schema, token.state); - const mode = (options === null || options === void 0 ? void 0 : options.mode) || getDocumentMode(queryText, options === null || options === void 0 ? void 0 : options.uri); - return { - token, - state, - typeInfo, - mode - }; -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/parser/getTypeInfo.js": -/*!****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/getTypeInfo.js ***! - \****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.forEachState = forEachState; -exports.getDefinitionState = getDefinitionState; -exports.getFieldDef = getFieldDef; -exports.getTypeInfo = getTypeInfo; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); -function getFieldDef(schema, type, fieldName) { - if (fieldName === _graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { - return _graphql.SchemaMetaFieldDef; - } - if (fieldName === _graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { - return _graphql.TypeMetaFieldDef; - } - if (fieldName === _graphql.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) { - return _graphql.TypeNameMetaFieldDef; - } - if ('getFields' in type) { - return type.getFields()[fieldName]; - } - return null; -} -function forEachState(stack, fn) { - const reverseStateStack = []; - let state = stack; - while (state === null || state === void 0 ? void 0 : state.kind) { - reverseStateStack.push(state); - state = state.prevState; - } - for (let i = reverseStateStack.length - 1; i >= 0; i--) { - fn(reverseStateStack[i]); - } -} -function getDefinitionState(tokenState) { - let definitionState; - forEachState(tokenState, state => { - switch (state.kind) { - case 'Query': - case 'ShortQuery': - case 'Mutation': - case 'Subscription': - case 'FragmentDefinition': - definitionState = state; - break; - } - }); - return definitionState; -} -function getTypeInfo(schema, tokenState) { - let argDef; - let argDefs; - let directiveDef; - let enumValue; - let fieldDef; - let inputType; - let objectTypeDef; - let objectFieldDefs; - let parentType; - let type; - let interfaceDef; - forEachState(tokenState, state => { - var _a; - switch (state.kind) { - case _.RuleKinds.QUERY: - case 'ShortQuery': - type = schema.getQueryType(); - break; - case _.RuleKinds.MUTATION: - type = schema.getMutationType(); - break; - case _.RuleKinds.SUBSCRIPTION: - type = schema.getSubscriptionType(); - break; - case _.RuleKinds.INLINE_FRAGMENT: - case _.RuleKinds.FRAGMENT_DEFINITION: - if (state.type) { - type = schema.getType(state.type); - } - break; - case _.RuleKinds.FIELD: - case _.RuleKinds.ALIASED_FIELD: - { - if (!type || !state.name) { - fieldDef = null; - } else { - fieldDef = parentType ? getFieldDef(schema, parentType, state.name) : null; - type = fieldDef ? fieldDef.type : null; - } - break; - } - case _.RuleKinds.SELECTION_SET: - parentType = (0, _graphql.getNamedType)(type); - break; - case _.RuleKinds.DIRECTIVE: - directiveDef = state.name ? schema.getDirective(state.name) : null; - break; - case _.RuleKinds.INTERFACE_DEF: - if (state.name) { - objectTypeDef = null; - interfaceDef = new _graphql.GraphQLInterfaceType({ - name: state.name, - interfaces: [], - fields: {} - }); - } - break; - case _.RuleKinds.OBJECT_TYPE_DEF: - if (state.name) { - interfaceDef = null; - objectTypeDef = new _graphql.GraphQLObjectType({ - name: state.name, - interfaces: [], - fields: {} - }); - } - break; - case _.RuleKinds.ARGUMENTS: - { - if (state.prevState) { - switch (state.prevState.kind) { - case _.RuleKinds.FIELD: - argDefs = fieldDef && fieldDef.args; - break; - case _.RuleKinds.DIRECTIVE: - argDefs = directiveDef && directiveDef.args; - break; - case _.RuleKinds.ALIASED_FIELD: - { - const name = (_a = state.prevState) === null || _a === void 0 ? void 0 : _a.name; - if (!name) { - argDefs = null; - break; + function mergeRefs(...refs) { + return { + ref: refs.every((ref) => ref == null) + ? void 0 + : (value) => { + for (let ref of refs) { + if (ref == null) continue; + if (typeof ref === "function") ref(value); + else ref.current = value; } - const field = parentType ? getFieldDef(schema, parentType, name) : null; - if (!field) { - argDefs = null; - break; + }, + }; + } + function mergeProps(...listOfProps) { + var _a3; + if (listOfProps.length === 0) return {}; + if (listOfProps.length === 1) return listOfProps[0]; + let target = {}; + let eventHandlers = {}; + for (let props of listOfProps) { + for (let prop in props) { + if (prop.startsWith("on") && typeof props[prop] === "function") { + (_a3 = eventHandlers[prop]) != null + ? _a3 + : (eventHandlers[prop] = []); + eventHandlers[prop].push(props[prop]); + } else { + target[prop] = props[prop]; + } + } + } + if (target.disabled || target["aria-disabled"]) { + return Object.assign( + target, + // Set all event listeners that we collected to `undefined`. This is + // important because of the `cloneElement` from above, which merges the + // existing and new props, they don't just override therefore we have to + // explicitly nullify them. + Object.fromEntries( + Object.keys(eventHandlers).map((eventName) => [ + eventName, + void 0, + ]) + ) + ); + } + for (let eventName in eventHandlers) { + Object.assign(target, { + [eventName](event, ...args) { + let handlers = eventHandlers[eventName]; + for (let handler of handlers) { + if ( + (event instanceof Event || + (event == null ? void 0 : event.nativeEvent) instanceof + Event) && + event.defaultPrevented + ) { + return; } - argDefs = field.args; - break; + handler(event, ...args); } - default: - argDefs = null; - break; + }, + }); + } + return target; + } + function forwardRefWithAs(component) { + var _a3; + return Object.assign((0, import_react14.forwardRef)(component), { + displayName: + (_a3 = component.displayName) != null ? _a3 : component.name, + }); + } + function compact(object) { + let clone = Object.assign({}, object); + for (let key in clone) { + if (clone[key] === void 0) delete clone[key]; + } + return clone; + } + function omit(object, keysToOmit = []) { + let clone = Object.assign({}, object); + for (let key of keysToOmit) { + if (key in clone) delete clone[key]; + } + return clone; + } + + // src/utils/bugs.ts + function isDisabledReactIssue7711(element) { + let parent = element.parentElement; + let legend = null; + while (parent && !(parent instanceof HTMLFieldSetElement)) { + if (parent instanceof HTMLLegendElement) legend = parent; + parent = parent.parentElement; + } + let isParentDisabled = + (parent == null ? void 0 : parent.getAttribute("disabled")) === ""; + if (isParentDisabled && isFirstLegend(legend)) return false; + return isParentDisabled; + } + function isFirstLegend(element) { + if (!element) return false; + let previous = element.previousElementSibling; + while (previous !== null) { + if (previous instanceof HTMLLegendElement) return false; + previous = previous.previousElementSibling; + } + return true; + } + + // src/utils/form.ts + function objectToFormEntries( + source = {}, + parentKey = null, + entries = [] + ) { + for (let [key, value] of Object.entries(source)) { + append(entries, composeKey(parentKey, key), value); + } + return entries; + } + function composeKey(parent, key) { + return parent ? parent + "[" + key + "]" : key; + } + function append(entries, key, value) { + if (Array.isArray(value)) { + for (let [subkey, subvalue] of value.entries()) { + append(entries, composeKey(key, subkey.toString()), subvalue); } + } else if (value instanceof Date) { + entries.push([key, value.toISOString()]); + } else if (typeof value === "boolean") { + entries.push([key, value ? "1" : "0"]); + } else if (typeof value === "string") { + entries.push([key, value]); + } else if (typeof value === "number") { + entries.push([key, `${value}`]); + } else if (value === null || value === void 0) { + entries.push([key, ""]); } else { - argDefs = null; + objectToFormEntries(value, key, entries); } - break; } - case _.RuleKinds.ARGUMENT: - if (argDefs) { - for (let i = 0; i < argDefs.length; i++) { - if (argDefs[i].name === state.name) { - argDef = argDefs[i]; - break; + function attemptSubmit(element) { + var _a3; + let form = + (_a3 = element == null ? void 0 : element.form) != null + ? _a3 + : element.closest("form"); + if (!form) return; + for (let element2 of form.elements) { + if ( + (element2.tagName === "INPUT" && element2.type === "submit") || + (element2.tagName === "BUTTON" && element2.type === "submit") || + (element2.nodeName === "INPUT" && element2.type === "image") + ) { + element2.click(); + return; } } } - inputType = argDef === null || argDef === void 0 ? void 0 : argDef.type; - break; - case _.RuleKinds.VARIABLE_DEFINITION: - case _.RuleKinds.VARIABLE: - type = inputType; - break; - case _.RuleKinds.ENUM_VALUE: - const enumType = (0, _graphql.getNamedType)(inputType); - enumValue = enumType instanceof _graphql.GraphQLEnumType ? enumType.getValues().find(val => val.value === state.name) : null; - break; - case _.RuleKinds.LIST_VALUE: - const nullableType = (0, _graphql.getNullableType)(inputType); - inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null; - break; - case _.RuleKinds.OBJECT_VALUE: - const objectType = (0, _graphql.getNamedType)(inputType); - objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null; - break; - case _.RuleKinds.OBJECT_FIELD: - const objectField = state.name && objectFieldDefs ? objectFieldDefs[state.name] : null; - inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; - fieldDef = objectField; - type = fieldDef ? fieldDef.type : null; - break; - case _.RuleKinds.NAMED_TYPE: - if (state.name) { - type = schema.getType(state.name); - } - break; - } - }); - return { - argDef, - argDefs, - directiveDef, - enumValue, - fieldDef, - inputType, - objectFieldDefs, - parentType, - type, - interfaceDef, - objectTypeDef - }; -} -/***/ }), + // src/internal/hidden.tsx + var DEFAULT_VISUALLY_HIDDEN_TAG = "div"; + function VisuallyHidden(props, ref) { + let { features = 1 /* None */, ...theirProps } = props; + let ourProps = { + ref, + "aria-hidden": + (features & 2) /* Focusable */ === 2 /* Focusable */ + ? true + : void 0, + style: { + position: "fixed", + top: 1, + left: 1, + width: 1, + height: 0, + padding: 0, + margin: -1, + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + borderWidth: "0", + ...((features & 4) /* Hidden */ === 4 /* Hidden */ && + !(((features & 2) /* Focusable */ === 2) /* Focusable */) && { + display: "none", + }), + }, + }; + return render({ + ourProps, + theirProps, + slot: {}, + defaultTag: DEFAULT_VISUALLY_HIDDEN_TAG, + name: "Hidden", + }); + } + var Hidden = forwardRefWithAs(VisuallyHidden); -/***/ "../../graphql-language-service/esm/parser/index.js": -/*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/index.js ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -var _exportNames = { - CharacterStream: true, - LexRules: true, - ParseRules: true, - isIgnored: true, - butNot: true, - list: true, - opt: true, - p: true, - t: true, - onlineParser: true, - runOnlineParser: true, - getTokenAtPosition: true, - getContextAtPosition: true, - GraphQLDocumentMode: true, - getDocumentMode: true, - getTypeInfo: true, - getDefinitionState: true, - getFieldDef: true -}; -Object.defineProperty(exports, "CharacterStream", ({ - enumerable: true, - get: function () { - return _CharacterStream.default; - } -})); -Object.defineProperty(exports, "GraphQLDocumentMode", ({ - enumerable: true, - get: function () { - return _api.GraphQLDocumentMode; - } -})); -Object.defineProperty(exports, "LexRules", ({ - enumerable: true, - get: function () { - return _Rules.LexRules; - } -})); -Object.defineProperty(exports, "ParseRules", ({ - enumerable: true, - get: function () { - return _Rules.ParseRules; - } -})); -Object.defineProperty(exports, "butNot", ({ - enumerable: true, - get: function () { - return _RuleHelpers.butNot; - } -})); -Object.defineProperty(exports, "getContextAtPosition", ({ - enumerable: true, - get: function () { - return _api.getContextAtPosition; - } -})); -Object.defineProperty(exports, "getDefinitionState", ({ - enumerable: true, - get: function () { - return _getTypeInfo.getDefinitionState; - } -})); -Object.defineProperty(exports, "getDocumentMode", ({ - enumerable: true, - get: function () { - return _api.getDocumentMode; - } -})); -Object.defineProperty(exports, "getFieldDef", ({ - enumerable: true, - get: function () { - return _getTypeInfo.getFieldDef; - } -})); -Object.defineProperty(exports, "getTokenAtPosition", ({ - enumerable: true, - get: function () { - return _api.getTokenAtPosition; - } -})); -Object.defineProperty(exports, "getTypeInfo", ({ - enumerable: true, - get: function () { - return _getTypeInfo.getTypeInfo; - } -})); -Object.defineProperty(exports, "isIgnored", ({ - enumerable: true, - get: function () { - return _Rules.isIgnored; - } -})); -Object.defineProperty(exports, "list", ({ - enumerable: true, - get: function () { - return _RuleHelpers.list; - } -})); -Object.defineProperty(exports, "onlineParser", ({ - enumerable: true, - get: function () { - return _onlineParser.default; - } -})); -Object.defineProperty(exports, "opt", ({ - enumerable: true, - get: function () { - return _RuleHelpers.opt; - } -})); -Object.defineProperty(exports, "p", ({ - enumerable: true, - get: function () { - return _RuleHelpers.p; - } -})); -Object.defineProperty(exports, "runOnlineParser", ({ - enumerable: true, - get: function () { - return _api.runOnlineParser; - } -})); -Object.defineProperty(exports, "t", ({ - enumerable: true, - get: function () { - return _RuleHelpers.t; - } -})); -var _CharacterStream = _interopRequireDefault(__webpack_require__(/*! ./CharacterStream */ "../../graphql-language-service/esm/parser/CharacterStream.js")); -var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); -var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); -var _onlineParser = _interopRequireDefault(__webpack_require__(/*! ./onlineParser */ "../../graphql-language-service/esm/parser/onlineParser.js")); -var _api = __webpack_require__(/*! ./api */ "../../graphql-language-service/esm/parser/api.js"); -var _getTypeInfo = __webpack_require__(/*! ./getTypeInfo */ "../../graphql-language-service/esm/parser/getTypeInfo.js"); -var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/parser/types.js"); -Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _types[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _types[key]; - } - }); -}); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // src/internal/open-closed.tsx + var import_react15 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var Context = (0, import_react15.createContext)(null); + Context.displayName = "OpenClosedContext"; + function useOpenClosed() { + return (0, import_react15.useContext)(Context); + } + function OpenClosedProvider({ value, children }) { + return /* @__PURE__ */ import_react15.default.createElement( + Context.Provider, + { value }, + children + ); + } -/***/ }), + // src/hooks/use-controllable.ts + var import_react16 = __webpack_require__(/*! react */ "react"); + function useControllable(controlledValue, onChange, defaultValue) { + let [internalValue, setInternalValue] = (0, import_react16.useState)( + defaultValue + ); + let isControlled = controlledValue !== void 0; + let wasControlled = (0, import_react16.useRef)(isControlled); + let didWarnOnUncontrolledToControlled = (0, import_react16.useRef)( + false + ); + let didWarnOnControlledToUncontrolled = (0, import_react16.useRef)( + false + ); + if ( + isControlled && + !wasControlled.current && + !didWarnOnUncontrolledToControlled.current + ) { + didWarnOnUncontrolledToControlled.current = true; + wasControlled.current = isControlled; + console.error( + "A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen." + ); + } else if ( + !isControlled && + wasControlled.current && + !didWarnOnControlledToUncontrolled.current + ) { + didWarnOnControlledToUncontrolled.current = true; + wasControlled.current = isControlled; + console.error( + "A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen." + ); + } + return [ + isControlled ? controlledValue : internalValue, + useEvent((value) => { + if (isControlled) { + return onChange == null ? void 0 : onChange(value); + } else { + setInternalValue(value); + return onChange == null ? void 0 : onChange(value); + } + }), + ]; + } + + // src/hooks/use-watch.ts + var import_react17 = __webpack_require__(/*! react */ "react"); + function useWatch(cb, dependencies) { + let track = (0, import_react17.useRef)([]); + let action = useEvent(cb); + (0, import_react17.useEffect)(() => { + let oldValues = [...track.current]; + for (let [idx, value] of dependencies.entries()) { + if (track.current[idx] !== value) { + let returnValue = action(dependencies, oldValues); + track.current = dependencies; + return returnValue; + } + } + }, [action, ...dependencies]); + } -/***/ "../../graphql-language-service/esm/parser/onlineParser.js": -/*!*****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/onlineParser.js ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = onlineParser; -var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function onlineParser(options = { - eatWhitespace: stream => stream.eatWhile(_Rules.isIgnored), - lexRules: _Rules.LexRules, - parseRules: _Rules.ParseRules, - editorConfig: {} -}) { - return { - startState() { - const initialState = { - level: 0, - step: 0, - name: null, - kind: null, - type: null, - rule: null, - needsSeparator: false, - prevState: null - }; - pushRule(options.parseRules, initialState, _graphql.Kind.DOCUMENT); - return initialState; - }, - token(stream, state) { - return getToken(stream, state, options); - } - }; -} -function getToken(stream, state, options) { - var _a; - if (state.inBlockstring) { - if (stream.match(/.*"""/)) { - state.inBlockstring = false; - return 'string'; - } - stream.skipToEnd(); - return 'string'; - } - const { - lexRules, - parseRules, - eatWhitespace, - editorConfig - } = options; - if (state.rule && state.rule.length === 0) { - popRule(state); - } else if (state.needsAdvance) { - state.needsAdvance = false; - advanceRule(state, true); - } - if (stream.sol()) { - const tabSize = (editorConfig === null || editorConfig === void 0 ? void 0 : editorConfig.tabSize) || 2; - state.indentLevel = Math.floor(stream.indentation() / tabSize); - } - if (eatWhitespace(stream)) { - return 'ws'; - } - const token = lex(lexRules, stream); - if (!token) { - const matchedSomething = stream.match(/\S+/); - if (!matchedSomething) { - stream.match(/\s/); - } - pushRule(SpecialParseRules, state, 'Invalid'); - return 'invalidchar'; - } - if (token.kind === 'Comment') { - pushRule(SpecialParseRules, state, 'Comment'); - return 'comment'; - } - const backupState = assign({}, state); - if (token.kind === 'Punctuation') { - if (/^[{([]/.test(token.value)) { - if (state.indentLevel !== undefined) { - state.levels = (state.levels || []).concat(state.indentLevel + 1); - } - } else if (/^[})\]]/.test(token.value)) { - const levels = state.levels = (state.levels || []).slice(0, -1); - if (state.indentLevel && levels.length > 0 && levels.at(-1) < state.indentLevel) { - state.indentLevel = levels.at(-1); - } - } - } - while (state.rule) { - let expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step]; - if (state.needsSeparator) { - expected = expected === null || expected === void 0 ? void 0 : expected.separator; - } - if (expected) { - if (expected.ofRule) { - expected = expected.ofRule; - } - if (typeof expected === 'string') { - pushRule(parseRules, state, expected); - continue; - } - if ((_a = expected.match) === null || _a === void 0 ? void 0 : _a.call(expected, token)) { - if (expected.update) { - expected.update(state, token); + // src/hooks/use-tracked-pointer.ts + var import_react18 = __webpack_require__(/*! react */ "react"); + function eventToPosition(evt) { + return [evt.screenX, evt.screenY]; + } + function useTrackedPointer() { + let lastPos = (0, import_react18.useRef)([-1, -1]); + return { + wasMoved(evt) { + if (false) { + } + let newPos = eventToPosition(evt); + if ( + lastPos.current[0] === newPos[0] && + lastPos.current[1] === newPos[1] + ) { + return false; + } + lastPos.current = newPos; + return true; + }, + update(evt) { + lastPos.current = eventToPosition(evt); + }, + }; + } + + // src/utils/platform.ts + function isIOS() { + return ( + // Check if it is an iPhone + /iPhone/gi.test(window.navigator.platform) || // Check if it is an iPad. iPad reports itself as "MacIntel", but we can check if it is a touch + // screen. Let's hope that Apple doesn't release a touch screen Mac (or maybe this would then + // work as expected 🤔). + (/Mac/gi.test(window.navigator.platform) && + window.navigator.maxTouchPoints > 0) + ); + } + function isAndroid() { + return /Android/gi.test(window.navigator.userAgent); + } + function isMobile() { + return isIOS() || isAndroid(); + } + + // src/components/combobox/combobox.tsx + function adjustOrderedState(state, adjustment = (i) => i) { + let currentActiveOption = + state.activeOptionIndex !== null + ? state.options[state.activeOptionIndex] + : null; + let sortedOptions = sortByDomNode( + adjustment(state.options.slice()), + (option) => option.dataRef.current.domRef.current + ); + let adjustedActiveOptionIndex = currentActiveOption + ? sortedOptions.indexOf(currentActiveOption) + : null; + if (adjustedActiveOptionIndex === -1) { + adjustedActiveOptionIndex = null; + } + return { + options: sortedOptions, + activeOptionIndex: adjustedActiveOptionIndex, + }; + } + var reducers = { + [1 /* CloseCombobox */](state) { + var _a3; + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) + return state; + if (state.comboboxState === 1 /* Closed */) return state; + return { + ...state, + activeOptionIndex: null, + comboboxState: 1 /* Closed */, + }; + }, + [0 /* OpenCombobox */](state) { + var _a3; + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) + return state; + if (state.comboboxState === 0 /* Open */) return state; + let activeOptionIndex = state.activeOptionIndex; + if (state.dataRef.current) { + let { isSelected } = state.dataRef.current; + let optionIdx = state.options.findIndex((option) => + isSelected(option.dataRef.current.value) + ); + if (optionIdx !== -1) { + activeOptionIndex = optionIdx; + } + } + return { ...state, comboboxState: 0 /* Open */, activeOptionIndex }; + }, + [2 /* GoToOption */](state, action) { + var _a3, _b, _c, _d; + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) + return state; + if ( + ((_b = state.dataRef.current) == null + ? void 0 + : _b.optionsRef.current) && + !((_c = state.dataRef.current) == null + ? void 0 + : _c.optionsPropsRef.current.static) && + state.comboboxState === 1 /* Closed */ + ) { + return state; + } + let adjustedState = adjustOrderedState(state); + if (adjustedState.activeOptionIndex === null) { + let localActiveOptionIndex = adjustedState.options.findIndex( + (option) => !option.dataRef.current.disabled + ); + if (localActiveOptionIndex !== -1) { + adjustedState.activeOptionIndex = localActiveOptionIndex; + } + } + let activeOptionIndex = calculateActiveIndex(action, { + resolveItems: () => adjustedState.options, + resolveActiveIndex: () => adjustedState.activeOptionIndex, + resolveId: (item) => item.id, + resolveDisabled: (item) => item.dataRef.current.disabled, + }); + return { + ...state, + ...adjustedState, + activeOptionIndex, + activationTrigger: + (_d = action.trigger) != null ? _d : 1 /* Other */, + }; + }, + [3 /* RegisterOption */]: (state, action) => { + var _a3, _b; + let option = { id: action.id, dataRef: action.dataRef }; + let adjustedState = adjustOrderedState(state, (options) => [ + ...options, + option, + ]); + if (state.activeOptionIndex === null) { + if ( + (_a3 = state.dataRef.current) == null + ? void 0 + : _a3.isSelected(action.dataRef.current.value) + ) { + adjustedState.activeOptionIndex = + adjustedState.options.indexOf(option); + } + } + let nextState = { + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */, + }; + if ( + ((_b = state.dataRef.current) == null ? void 0 : _b.__demoMode) && + state.dataRef.current.value === void 0 + ) { + nextState.activeOptionIndex = 0; + } + return nextState; + }, + [4 /* UnregisterOption */]: (state, action) => { + let adjustedState = adjustOrderedState(state, (options) => { + let idx = options.findIndex((a) => a.id === action.id); + if (idx !== -1) options.splice(idx, 1); + return options; + }); + return { + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */, + }; + }, + [5 /* RegisterLabel */]: (state, action) => { + return { + ...state, + labelId: action.id, + }; + }, + }; + var ComboboxActionsContext = (0, import_react19.createContext)(null); + ComboboxActionsContext.displayName = "ComboboxActionsContext"; + function useActions(component) { + let context = (0, import_react19.useContext)(ComboboxActionsContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useActions); + throw err; + } + return context; + } + var ComboboxDataContext = (0, import_react19.createContext)(null); + ComboboxDataContext.displayName = "ComboboxDataContext"; + function useData(component) { + let context = (0, import_react19.useContext)(ComboboxDataContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) Error.captureStackTrace(err, useData); + throw err; + } + return context; + } + function stateReducer(state, action) { + return match(action.type, reducers, state, action); + } + var DEFAULT_COMBOBOX_TAG = import_react19.Fragment; + function ComboboxFn(props, ref) { + let { + value: controlledValue, + defaultValue, + onChange: controlledOnChange, + form: formName, + name, + by = (a, z) => a === z, + disabled = false, + __demoMode = false, + nullable = false, + multiple = false, + ...theirProps + } = props; + let [value = multiple ? [] : void 0, theirOnChange] = useControllable( + controlledValue, + controlledOnChange, + defaultValue + ); + let [state, dispatch] = (0, import_react19.useReducer)(stateReducer, { + dataRef: (0, import_react19.createRef)(), + comboboxState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + options: [], + activeOptionIndex: null, + activationTrigger: 1 /* Other */, + labelId: null, + }); + let defaultToFirstOption = (0, import_react19.useRef)(false); + let optionsPropsRef = (0, import_react19.useRef)({ + static: false, + hold: false, + }); + let labelRef = (0, import_react19.useRef)(null); + let inputRef = (0, import_react19.useRef)(null); + let buttonRef = (0, import_react19.useRef)(null); + let optionsRef = (0, import_react19.useRef)(null); + let compare = useEvent( + // @ts-expect-error Eventually we'll want to tackle this, but for now this will do. + typeof by === "string" + ? (a, z) => { + let property = by; + return ( + (a == null ? void 0 : a[property]) === + (z == null ? void 0 : z[property]) + ); + } + : by + ); + let isSelected = (0, import_react19.useCallback)( + (compareValue) => + match(data.mode, { + [1 /* Multi */]: () => + value.some((option) => compare(option, compareValue)), + [0 /* Single */]: () => compare(value, compareValue), + }), + [value] + ); + let data = (0, import_react19.useMemo)( + () => ({ + ...state, + optionsPropsRef, + labelRef, + inputRef, + buttonRef, + optionsRef, + value, + defaultValue, + disabled, + mode: multiple ? 1 /* Multi */ : 0 /* Single */, + get activeOptionIndex() { + if ( + defaultToFirstOption.current && + state.activeOptionIndex === null && + state.options.length > 0 + ) { + let localActiveOptionIndex = state.options.findIndex( + (option) => !option.dataRef.current.disabled + ); + if (localActiveOptionIndex !== -1) { + return localActiveOptionIndex; + } + } + return state.activeOptionIndex; + }, + compare, + isSelected, + nullable, + __demoMode, + }), + [ + value, + defaultValue, + disabled, + multiple, + nullable, + __demoMode, + state, + ] + ); + let lastActiveOption = (0, import_react19.useRef)( + data.activeOptionIndex !== null + ? data.options[data.activeOptionIndex] + : null + ); + (0, import_react19.useEffect)(() => { + let currentActiveOption = + data.activeOptionIndex !== null + ? data.options[data.activeOptionIndex] + : null; + if (lastActiveOption.current !== currentActiveOption) { + lastActiveOption.current = currentActiveOption; + } + }); + useIsoMorphicEffect(() => { + state.dataRef.current = data; + }, [data]); + useOutsideClick( + [data.buttonRef, data.inputRef, data.optionsRef], + () => actions.closeCombobox(), + data.comboboxState === 0 /* Open */ + ); + let slot = (0, import_react19.useMemo)( + () => ({ + open: data.comboboxState === 0 /* Open */, + disabled, + activeIndex: data.activeOptionIndex, + activeOption: + data.activeOptionIndex === null + ? null + : data.options[data.activeOptionIndex].dataRef.current.value, + value, + }), + [data, disabled, value] + ); + let selectOption = useEvent((id) => { + let option = data.options.find((item) => item.id === id); + if (!option) return; + onChange(option.dataRef.current.value); + }); + let selectActiveOption = useEvent(() => { + if (data.activeOptionIndex !== null) { + let { dataRef, id } = data.options[data.activeOptionIndex]; + onChange(dataRef.current.value); + actions.goToOption(4 /* Specific */, id); + } + }); + let openCombobox = useEvent(() => { + dispatch({ type: 0 /* OpenCombobox */ }); + defaultToFirstOption.current = true; + }); + let closeCombobox = useEvent(() => { + dispatch({ type: 1 /* CloseCombobox */ }); + defaultToFirstOption.current = false; + }); + let goToOption = useEvent((focus, id, trigger) => { + defaultToFirstOption.current = false; + if (focus === 4 /* Specific */) { + return dispatch({ + type: 2 /* GoToOption */, + focus: 4 /* Specific */, + id, + trigger, + }); + } + return dispatch({ type: 2 /* GoToOption */, focus, trigger }); + }); + let registerOption = useEvent((id, dataRef) => { + dispatch({ type: 3 /* RegisterOption */, id, dataRef }); + return () => { + var _a3; + if ( + ((_a3 = lastActiveOption.current) == null ? void 0 : _a3.id) === + id + ) { + defaultToFirstOption.current = true; + } + dispatch({ type: 4 /* UnregisterOption */, id }); + }; + }); + let registerLabel = useEvent((id) => { + dispatch({ type: 5 /* RegisterLabel */, id }); + return () => dispatch({ type: 5 /* RegisterLabel */, id: null }); + }); + let onChange = useEvent((value2) => { + return match(data.mode, { + [0 /* Single */]() { + return theirOnChange == null ? void 0 : theirOnChange(value2); + }, + [1 /* Multi */]() { + let copy = data.value.slice(); + let idx = copy.findIndex((item) => compare(item, value2)); + if (idx === -1) { + copy.push(value2); + } else { + copy.splice(idx, 1); + } + return theirOnChange == null ? void 0 : theirOnChange(copy); + }, + }); + }); + let actions = (0, import_react19.useMemo)( + () => ({ + onChange, + registerOption, + registerLabel, + goToOption, + closeCombobox, + openCombobox, + selectActiveOption, + selectOption, + }), + [] + ); + let ourProps = ref === null ? {} : { ref }; + let form = (0, import_react19.useRef)(null); + let d = useDisposables(); + (0, import_react19.useEffect)(() => { + if (!form.current) return; + if (defaultValue === void 0) return; + d.addEventListener(form.current, "reset", () => { + onChange(defaultValue); + }); + }, [ + form, + onChange, + /* Explicitly ignoring `defaultValue` */ + ]); + return /* @__PURE__ */ import_react19.default.createElement( + ComboboxActionsContext.Provider, + { value: actions }, + /* @__PURE__ */ import_react19.default.createElement( + ComboboxDataContext.Provider, + { value: data }, + /* @__PURE__ */ import_react19.default.createElement( + OpenClosedProvider, + { + value: match(data.comboboxState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */, + }), + }, + name != null && + value != null && + objectToFormEntries({ [name]: value }).map( + ([name2, value2], idx) => + /* @__PURE__ */ import_react19.default.createElement( + Hidden, + { + features: 4 /* Hidden */, + ref: + idx === 0 + ? (element) => { + var _a3; + form.current = + (_a3 = + element == null + ? void 0 + : element.closest("form")) != null + ? _a3 + : null; + } + : void 0, + ...compact({ + key: name2, + as: "input", + type: "hidden", + hidden: true, + readOnly: true, + form: formName, + name: name2, + value: value2, + }), + } + ) + ), + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_COMBOBOX_TAG, + name: "Combobox", + }) + ) + ) + ); + } + var DEFAULT_INPUT_TAG = "input"; + function InputFn(props, ref) { + var _a3, _b, _c, _d; + let internalId = useId(); + let { + id = `headlessui-combobox-input-${internalId}`, + onChange, + displayValue, + // @ts-ignore: We know this MAY NOT exist for a given tag but we only care when it _does_ exist. + type = "text", + ...theirProps + } = props; + let data = useData("Combobox.Input"); + let actions = useActions("Combobox.Input"); + let inputRef = useSyncRefs(data.inputRef, ref); + let isTyping = (0, import_react19.useRef)(false); + let d = useDisposables(); + let currentDisplayValue = (function () { + var _a4; + if (typeof displayValue === "function" && data.value !== void 0) { + return (_a4 = displayValue(data.value)) != null ? _a4 : ""; + } else if (typeof data.value === "string") { + return data.value; + } else { + return ""; + } + })(); + useWatch( + ( + [currentDisplayValue2, state], + [oldCurrentDisplayValue, oldState] + ) => { + if (isTyping.current) return; + if (!data.inputRef.current) return; + if (oldState === 0 /* Open */ && state === 1 /* Closed */) { + data.inputRef.current.value = currentDisplayValue2; + } else if (currentDisplayValue2 !== oldCurrentDisplayValue) { + data.inputRef.current.value = currentDisplayValue2; + } + }, + [currentDisplayValue, data.comboboxState] + ); + useWatch( + ([newState], [oldState]) => { + if (newState === 0 /* Open */ && oldState === 1 /* Closed */) { + let input = data.inputRef.current; + if (!input) return; + let currentValue = input.value; + let { selectionStart, selectionEnd, selectionDirection } = + input; + input.value = ""; + input.value = currentValue; + if (selectionDirection !== null) { + input.setSelectionRange( + selectionStart, + selectionEnd, + selectionDirection + ); + } else { + input.setSelectionRange(selectionStart, selectionEnd); + } + } + }, + [data.comboboxState] + ); + let isComposing = (0, import_react19.useRef)(false); + let composedChangeEvent = (0, import_react19.useRef)(null); + let handleCompositionStart = useEvent(() => { + isComposing.current = true; + }); + let handleCompositionEnd = useEvent(() => { + d.nextFrame(() => { + isComposing.current = false; + if (composedChangeEvent.current) { + actions.openCombobox(); + onChange == null + ? void 0 + : onChange(composedChangeEvent.current); + composedChangeEvent.current = null; + } + }); + }); + let handleKeyDown = useEvent((event) => { + isTyping.current = true; + switch (event.key) { + case "Backspace" /* Backspace */: + case "Delete" /* Delete */: + if (data.mode !== 0 /* Single */) return; + if (!data.nullable) return; + let input = event.currentTarget; + d.requestAnimationFrame(() => { + if (input.value === "") { + actions.onChange(null); + if (data.optionsRef.current) { + data.optionsRef.current.scrollTop = 0; + } + actions.goToOption(5 /* Nothing */); + } + }); + break; + case "Enter" /* Enter */: + isTyping.current = false; + if (data.comboboxState !== 0 /* Open */) return; + if (isComposing.current) return; + event.preventDefault(); + event.stopPropagation(); + if (data.activeOptionIndex === null) { + actions.closeCombobox(); + return; + } + actions.selectActiveOption(); + if (data.mode === 0 /* Single */) { + actions.closeCombobox(); + } + break; + case "ArrowDown" /* ArrowDown */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return match(data.comboboxState, { + [0 /* Open */]: () => { + actions.goToOption(2 /* Next */); + }, + [1 /* Closed */]: () => { + actions.openCombobox(); + }, + }); + case "ArrowUp" /* ArrowUp */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return match(data.comboboxState, { + [0 /* Open */]: () => { + actions.goToOption(1 /* Previous */); + }, + [1 /* Closed */]: () => { + actions.openCombobox(); + d.nextFrame(() => { + if (!data.value) { + actions.goToOption(3 /* Last */); + } + }); + }, + }); + case "Home" /* Home */: + if (event.shiftKey) { + break; + } + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(0 /* First */); + case "PageUp" /* PageUp */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(0 /* First */); + case "End" /* End */: + if (event.shiftKey) { + break; + } + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(3 /* Last */); + case "PageDown" /* PageDown */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(3 /* Last */); + case "Escape" /* Escape */: + isTyping.current = false; + if (data.comboboxState !== 0 /* Open */) return; + event.preventDefault(); + if ( + data.optionsRef.current && + !data.optionsPropsRef.current.static + ) { + event.stopPropagation(); + } + return actions.closeCombobox(); + case "Tab" /* Tab */: + isTyping.current = false; + if (data.comboboxState !== 0 /* Open */) return; + if (data.mode === 0 /* Single */) actions.selectActiveOption(); + actions.closeCombobox(); + break; + } + }); + let handleChange = useEvent((event) => { + if (isComposing.current) { + composedChangeEvent.current = event; + return; + } + actions.openCombobox(); + onChange == null ? void 0 : onChange(event); + }); + let handleBlur = useEvent(() => { + isTyping.current = false; + }); + let labelledby = useComputed(() => { + if (!data.labelId) return void 0; + return [data.labelId].join(" "); + }, [data.labelId]); + let slot = (0, import_react19.useMemo)( + () => ({ + open: data.comboboxState === 0 /* Open */, + disabled: data.disabled, + }), + [data] + ); + let ourProps = { + ref: inputRef, + id, + role: "combobox", + type, + "aria-controls": + (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": data.disabled + ? void 0 + : data.comboboxState === 0 /* Open */, + "aria-activedescendant": + data.activeOptionIndex === null + ? void 0 + : (_b = data.options[data.activeOptionIndex]) == null + ? void 0 + : _b.id, + "aria-labelledby": labelledby, + "aria-autocomplete": "list", + defaultValue: + (_d = + (_c = props.defaultValue) != null + ? _c + : data.defaultValue !== void 0 + ? displayValue == null + ? void 0 + : displayValue(data.defaultValue) + : null) != null + ? _d + : data.defaultValue, + disabled: data.disabled, + onCompositionStart: handleCompositionStart, + onCompositionEnd: handleCompositionEnd, + onKeyDown: handleKeyDown, + onChange: handleChange, + onBlur: handleBlur, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_INPUT_TAG, + name: "Combobox.Input", + }); + } + var DEFAULT_BUTTON_TAG = "button"; + function ButtonFn(props, ref) { + var _a3; + let data = useData("Combobox.Button"); + let actions = useActions("Combobox.Button"); + let buttonRef = useSyncRefs(data.buttonRef, ref); + let internalId = useId(); + let { + id = `headlessui-combobox-button-${internalId}`, + ...theirProps + } = props; + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + if (data.comboboxState === 1 /* Closed */) { + actions.openCombobox(); + } + return d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + if (data.comboboxState === 1 /* Closed */) { + actions.openCombobox(); + d.nextFrame(() => { + if (!data.value) { + actions.goToOption(3 /* Last */); + } + }); + } + return d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + case "Escape" /* Escape */: + if (data.comboboxState !== 0 /* Open */) return; + event.preventDefault(); + if ( + data.optionsRef.current && + !data.optionsPropsRef.current.static + ) { + event.stopPropagation(); + } + actions.closeCombobox(); + return d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + default: + return; + } + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (data.comboboxState === 0 /* Open */) { + actions.closeCombobox(); + } else { + event.preventDefault(); + actions.openCombobox(); + } + d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + }); + let labelledby = useComputed(() => { + if (!data.labelId) return void 0; + return [data.labelId, id].join(" "); + }, [data.labelId, id]); + let slot = (0, import_react19.useMemo)( + () => ({ + open: data.comboboxState === 0 /* Open */, + disabled: data.disabled, + value: data.value, + }), + [data] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, data.buttonRef), + tabIndex: -1, + "aria-haspopup": "listbox", + "aria-controls": + (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": data.disabled + ? void 0 + : data.comboboxState === 0 /* Open */, + "aria-labelledby": labelledby, + disabled: data.disabled, + onClick: handleClick, + onKeyDown: handleKeyDown, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG, + name: "Combobox.Button", + }); } - if (token.kind === 'Punctuation') { - advanceRule(state, true); - } else { - state.needsAdvance = true; + var DEFAULT_LABEL_TAG = "label"; + function LabelFn(props, ref) { + let internalId = useId(); + let { + id = `headlessui-combobox-label-${internalId}`, + ...theirProps + } = props; + let data = useData("Combobox.Label"); + let actions = useActions("Combobox.Label"); + let labelRef = useSyncRefs(data.labelRef, ref); + useIsoMorphicEffect(() => actions.registerLabel(id), [id]); + let handleClick = useEvent(() => { + var _a3; + return (_a3 = data.inputRef.current) == null + ? void 0 + : _a3.focus({ preventScroll: true }); + }); + let slot = (0, import_react19.useMemo)( + () => ({ + open: data.comboboxState === 0 /* Open */, + disabled: data.disabled, + }), + [data] + ); + let ourProps = { ref: labelRef, id, onClick: handleClick }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_LABEL_TAG, + name: "Combobox.Label", + }); } - return expected.style; - } - } - unsuccessful(state); - } - assign(state, backupState); - pushRule(SpecialParseRules, state, 'Invalid'); - return 'invalidchar'; -} -function assign(to, from) { - const keys = Object.keys(from); - for (let i = 0; i < keys.length; i++) { - to[keys[i]] = from[keys[i]]; - } - return to; -} -const SpecialParseRules = { - Invalid: [], - Comment: [] -}; -function pushRule(rules, state, ruleKind) { - if (!rules[ruleKind]) { - throw new TypeError('Unknown rule: ' + ruleKind); - } - state.prevState = Object.assign({}, state); - state.kind = ruleKind; - state.name = null; - state.type = null; - state.rule = rules[ruleKind]; - state.step = 0; - state.needsSeparator = false; -} -function popRule(state) { - if (!state.prevState) { - return; - } - state.kind = state.prevState.kind; - state.name = state.prevState.name; - state.type = state.prevState.type; - state.rule = state.prevState.rule; - state.step = state.prevState.step; - state.needsSeparator = state.prevState.needsSeparator; - state.prevState = state.prevState.prevState; -} -function advanceRule(state, successful) { - var _a; - if (isList(state) && state.rule) { - const step = state.rule[state.step]; - if (step.separator) { - const { - separator - } = step; - state.needsSeparator = !state.needsSeparator; - if (!state.needsSeparator && separator.ofRule) { - return; - } - } - if (successful) { - return; - } - } - state.needsSeparator = false; - state.step++; - while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) { - popRule(state); - if (state.rule) { - if (isList(state)) { - if ((_a = state.rule) === null || _a === void 0 ? void 0 : _a[state.step].separator) { - state.needsSeparator = !state.needsSeparator; - } - } else { - state.needsSeparator = false; - state.step++; - } - } - } -} -function isList(state) { - const step = Array.isArray(state.rule) && typeof state.rule[state.step] !== 'string' && state.rule[state.step]; - return step && step.isList; -} -function unsuccessful(state) { - while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) { - popRule(state); - } - if (state.rule) { - advanceRule(state, false); - } -} -function lex(lexRules, stream) { - const kinds = Object.keys(lexRules); - for (let i = 0; i < kinds.length; i++) { - const match = stream.match(lexRules[kinds[i]]); - if (match && match instanceof Array) { - return { - kind: kinds[i], - value: match[0] - }; - } - } -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/parser/types.js": -/*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/types.js ***! - \**********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.RuleKinds = exports.AdditionalRuleKinds = void 0; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const AdditionalRuleKinds = exports.AdditionalRuleKinds = { - ALIASED_FIELD: 'AliasedField', - ARGUMENTS: 'Arguments', - SHORT_QUERY: 'ShortQuery', - QUERY: 'Query', - MUTATION: 'Mutation', - SUBSCRIPTION: 'Subscription', - TYPE_CONDITION: 'TypeCondition', - INVALID: 'Invalid', - COMMENT: 'Comment', - SCHEMA_DEF: 'SchemaDef', - SCALAR_DEF: 'ScalarDef', - OBJECT_TYPE_DEF: 'ObjectTypeDef', - OBJECT_VALUE: 'ObjectValue', - LIST_VALUE: 'ListValue', - INTERFACE_DEF: 'InterfaceDef', - UNION_DEF: 'UnionDef', - ENUM_DEF: 'EnumDef', - ENUM_VALUE: 'EnumValue', - FIELD_DEF: 'FieldDef', - INPUT_DEF: 'InputDef', - INPUT_VALUE_DEF: 'InputValueDef', - ARGUMENTS_DEF: 'ArgumentsDef', - EXTEND_DEF: 'ExtendDef', - EXTENSION_DEFINITION: 'ExtensionDefinition', - DIRECTIVE_DEF: 'DirectiveDef', - IMPLEMENTS: 'Implements', - VARIABLE_DEFINITIONS: 'VariableDefinitions', - TYPE: 'Type', - VARIABLE: 'Variable' -}; -const RuleKinds = exports.RuleKinds = Object.assign(Object.assign({}, _graphql.Kind), AdditionalRuleKinds); - -/***/ }), - -/***/ "../../graphql-language-service/esm/types.js": -/*!***************************************************!*\ - !*** ../../graphql-language-service/esm/types.js ***! - \***************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.FileChangeTypeKind = exports.CompletionItemKind = void 0; -Object.defineProperty(exports, "GraphQLDocumentMode", ({ - enumerable: true, - get: function () { - return _parser.GraphQLDocumentMode; - } -})); -Object.defineProperty(exports, "InsertTextFormat", ({ - enumerable: true, - get: function () { - return _vscodeLanguageserverTypes.InsertTextFormat; - } -})); -var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); -var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); -const FileChangeTypeKind = exports.FileChangeTypeKind = { - Created: 1, - Changed: 2, - Deleted: 3 -}; -var CompletionItemKind; -(function (CompletionItemKind) { - CompletionItemKind.Text = 1; - CompletionItemKind.Method = 2; - CompletionItemKind.Function = 3; - CompletionItemKind.Constructor = 4; - CompletionItemKind.Field = 5; - CompletionItemKind.Variable = 6; - CompletionItemKind.Class = 7; - CompletionItemKind.Interface = 8; - CompletionItemKind.Module = 9; - CompletionItemKind.Property = 10; - CompletionItemKind.Unit = 11; - CompletionItemKind.Value = 12; - CompletionItemKind.Enum = 13; - CompletionItemKind.Keyword = 14; - CompletionItemKind.Snippet = 15; - CompletionItemKind.Color = 16; - CompletionItemKind.File = 17; - CompletionItemKind.Reference = 18; - CompletionItemKind.Folder = 19; - CompletionItemKind.EnumMember = 20; - CompletionItemKind.Constant = 21; - CompletionItemKind.Struct = 22; - CompletionItemKind.Event = 23; - CompletionItemKind.Operator = 24; - CompletionItemKind.TypeParameter = 25; -})(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); - -/***/ }), - -/***/ "../../graphql-language-service/esm/utils/Range.js": -/*!*********************************************************!*\ - !*** ../../graphql-language-service/esm/utils/Range.js ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Range = exports.Position = void 0; -exports.locToRange = locToRange; -exports.offsetToPosition = offsetToPosition; -class Range { - constructor(start, end) { - this.containsPosition = position => { - if (this.start.line === position.line) { - return this.start.character <= position.character; - } - if (this.end.line === position.line) { - return this.end.character >= position.character; - } - return this.start.line <= position.line && this.end.line >= position.line; - }; - this.start = start; - this.end = end; - } - setStart(line, character) { - this.start = new Position(line, character); - } - setEnd(line, character) { - this.end = new Position(line, character); - } -} -exports.Range = Range; -class Position { - constructor(line, character) { - this.lessThanOrEqualTo = position => this.line < position.line || this.line === position.line && this.character <= position.character; - this.line = line; - this.character = character; - } - setLine(line) { - this.line = line; - } - setCharacter(character) { - this.character = character; - } -} -exports.Position = Position; -function offsetToPosition(text, loc) { - const EOL = '\n'; - const buf = text.slice(0, loc); - const lines = buf.split(EOL).length - 1; - const lastLineIndex = buf.lastIndexOf(EOL); - return new Position(lines, loc - lastLineIndex - 1); -} -function locToRange(text, loc) { - const start = offsetToPosition(text, loc.start); - const end = offsetToPosition(text, loc.end); - return new Range(start, end); -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/utils/collectVariables.js": -/*!********************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/collectVariables.js ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.collectVariables = collectVariables; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function collectVariables(schema, documentAST) { - const variableToType = Object.create(null); - for (const definition of documentAST.definitions) { - if (definition.kind === 'OperationDefinition') { - const { - variableDefinitions - } = definition; - if (variableDefinitions) { - for (const { - variable, - type - } of variableDefinitions) { - const inputType = (0, _graphql.typeFromAST)(schema, type); - if (inputType) { - variableToType[variable.name.value] = inputType; - } else if (type.kind === _graphql.Kind.NAMED_TYPE && type.name.value === 'Float') { - variableToType[variable.name.value] = _graphql.GraphQLFloat; - } + var DEFAULT_OPTIONS_TAG = "ul"; + var OptionsRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ + function OptionsFn(props, ref) { + let internalId = useId(); + let { + id = `headlessui-combobox-options-${internalId}`, + hold = false, + ...theirProps + } = props; + let data = useData("Combobox.Options"); + let optionsRef = useSyncRefs(data.optionsRef, ref); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; + } + return data.comboboxState === 0 /* Open */; + })(); + useIsoMorphicEffect(() => { + var _a3; + data.optionsPropsRef.current.static = + (_a3 = props.static) != null ? _a3 : false; + }, [data.optionsPropsRef, props.static]); + useIsoMorphicEffect(() => { + data.optionsPropsRef.current.hold = hold; + }, [data.optionsPropsRef, hold]); + useTreeWalker({ + container: data.optionsRef.current, + enabled: data.comboboxState === 0 /* Open */, + accept(node) { + if (node.getAttribute("role") === "option") + return NodeFilter.FILTER_REJECT; + if (node.hasAttribute("role")) return NodeFilter.FILTER_SKIP; + return NodeFilter.FILTER_ACCEPT; + }, + walk(node) { + node.setAttribute("role", "none"); + }, + }); + let labelledby = useComputed(() => { + var _a3, _b; + return (_b = data.labelId) != null + ? _b + : (_a3 = data.buttonRef.current) == null + ? void 0 + : _a3.id; + }, [data.labelId, data.buttonRef.current]); + let slot = (0, import_react19.useMemo)( + () => ({ open: data.comboboxState === 0 /* Open */ }), + [data] + ); + let ourProps = { + "aria-labelledby": labelledby, + role: "listbox", + "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, + id, + ref: optionsRef, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTIONS_TAG, + features: OptionsRenderFeatures, + visible, + name: "Combobox.Options", + }); } - } - } - } - return variableToType; -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/utils/fragmentDependencies.js": -/*!************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/fragmentDependencies.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getFragmentDependenciesForAST = exports.getFragmentDependencies = void 0; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _nullthrows = _interopRequireDefault(__webpack_require__(/*! nullthrows */ "../../../node_modules/nullthrows/nullthrows.js")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const getFragmentDependencies = (operationString, fragmentDefinitions) => { - if (!fragmentDefinitions) { - return []; - } - let parsedOperation; - try { - parsedOperation = (0, _graphql.parse)(operationString); - } catch (_a) { - return []; - } - return getFragmentDependenciesForAST(parsedOperation, fragmentDefinitions); -}; -exports.getFragmentDependencies = getFragmentDependencies; -const getFragmentDependenciesForAST = (parsedOperation, fragmentDefinitions) => { - if (!fragmentDefinitions) { - return []; - } - const existingFrags = new Map(); - const referencedFragNames = new Set(); - (0, _graphql.visit)(parsedOperation, { - FragmentDefinition(node) { - existingFrags.set(node.name.value, true); - }, - FragmentSpread(node) { - if (!referencedFragNames.has(node.name.value)) { - referencedFragNames.add(node.name.value); - } - } - }); - const asts = new Set(); - for (const name of referencedFragNames) { - if (!existingFrags.has(name) && fragmentDefinitions.has(name)) { - asts.add((0, _nullthrows.default)(fragmentDefinitions.get(name))); - } - } - const referencedFragments = []; - for (const ast of asts) { - (0, _graphql.visit)(ast, { - FragmentSpread(node) { - if (!referencedFragNames.has(node.name.value) && fragmentDefinitions.get(node.name.value)) { - asts.add((0, _nullthrows.default)(fragmentDefinitions.get(node.name.value))); - referencedFragNames.add(node.name.value); + var DEFAULT_OPTION_TAG = "li"; + function OptionFn(props, ref) { + var _a3, _b; + let internalId = useId(); + let { + id = `headlessui-combobox-option-${internalId}`, + disabled = false, + value, + ...theirProps + } = props; + let data = useData("Combobox.Option"); + let actions = useActions("Combobox.Option"); + let active = + data.activeOptionIndex !== null + ? data.options[data.activeOptionIndex].id === id + : false; + let selected = data.isSelected(value); + let internalOptionRef = (0, import_react19.useRef)(null); + let bag = useLatestValue({ + disabled, + value, + domRef: internalOptionRef, + textValue: + (_b = + (_a3 = internalOptionRef.current) == null + ? void 0 + : _a3.textContent) == null + ? void 0 + : _b.toLowerCase(), + }); + let optionRef = useSyncRefs(ref, internalOptionRef); + let select = useEvent(() => actions.selectOption(id)); + useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); + let enableScrollIntoView = (0, import_react19.useRef)( + data.__demoMode ? false : true + ); + useIsoMorphicEffect(() => { + if (!data.__demoMode) return; + let d = disposables(); + d.requestAnimationFrame(() => { + enableScrollIntoView.current = true; + }); + return d.dispose; + }, []); + useIsoMorphicEffect(() => { + if (data.comboboxState !== 0 /* Open */) return; + if (!active) return; + if (!enableScrollIntoView.current) return; + if (data.activationTrigger === 0 /* Pointer */) return; + let d = disposables(); + d.requestAnimationFrame(() => { + var _a4, _b2; + (_b2 = + (_a4 = internalOptionRef.current) == null + ? void 0 + : _a4.scrollIntoView) == null + ? void 0 + : _b2.call(_a4, { block: "nearest" }); + }); + return d.dispose; + }, [ + internalOptionRef, + active, + data.comboboxState, + data.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + data.activeOptionIndex, + ]); + let handleClick = useEvent((event) => { + if (disabled) return event.preventDefault(); + select(); + if (data.mode === 0 /* Single */) { + actions.closeCombobox(); + } + if (!isMobile()) { + requestAnimationFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null + ? void 0 + : _a4.focus(); + }); + } + }); + let handleFocus = useEvent(() => { + if (disabled) return actions.goToOption(5 /* Nothing */); + actions.goToOption(4 /* Specific */, id); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) return; + if (disabled) return; + if (active) return; + actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) return; + if (disabled) return; + if (!active) return; + if (data.optionsPropsRef.current.hold) return; + actions.goToOption(5 /* Nothing */); + }); + let slot = (0, import_react19.useMemo)( + () => ({ active, selected, disabled }), + [active, selected, disabled] + ); + let ourProps = { + id, + ref: optionRef, + role: "option", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + // According to the WAI-ARIA best practices, we should use aria-checked for + // multi-select,but Voice-Over disagrees. So we use aria-checked instead for + // both single and multi-select. + "aria-selected": selected, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTION_TAG, + name: "Combobox.Option", + }); } - } - }); - if (!existingFrags.has(ast.name.value)) { - referencedFragments.push(ast); - } - } - return referencedFragments; -}; -exports.getFragmentDependenciesForAST = getFragmentDependenciesForAST; - -/***/ }), - -/***/ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js": -/*!************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getASTNodeAtPosition.js ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getASTNodeAtPosition = getASTNodeAtPosition; -exports.pointToOffset = pointToOffset; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -function getASTNodeAtPosition(query, ast, point) { - const offset = pointToOffset(query, point); - let nodeContainingPosition; - (0, _graphql.visit)(ast, { - enter(node) { - if (node.kind !== 'Name' && node.loc && node.loc.start <= offset && offset <= node.loc.end) { - nodeContainingPosition = node; - } else { - return false; - } - }, - leave(node) { - if (node.loc && node.loc.start <= offset && offset <= node.loc.end) { - return false; - } - } - }); - return nodeContainingPosition; -} -function pointToOffset(text, point) { - const linesUntilPosition = text.split('\n').slice(0, point.line); - return point.character + linesUntilPosition.map(line => line.length + 1).reduce((a, b) => a + b, 0); -} + var ComboboxRoot = forwardRefWithAs(ComboboxFn); + var Button = forwardRefWithAs(ButtonFn); + var Input = forwardRefWithAs(InputFn); + var Label = forwardRefWithAs(LabelFn); + var Options = forwardRefWithAs(OptionsFn); + var Option = forwardRefWithAs(OptionFn); + var Combobox = Object.assign(ComboboxRoot, { + Input, + Button, + Label, + Options, + Option, + }); -/***/ }), + // src/components/dialog/dialog.tsx + var import_react31 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); -/***/ "../../graphql-language-service/esm/utils/getOperationFacts.js": -/*!*********************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getOperationFacts.js ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = getOperationFacts; -exports.getOperationASTFacts = getOperationASTFacts; -exports.getQueryFacts = void 0; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); -function getOperationASTFacts(documentAST, schema) { - const variableToType = schema ? (0, _collectVariables.collectVariables)(schema, documentAST) : undefined; - const operations = []; - (0, _graphql.visit)(documentAST, { - OperationDefinition(node) { - operations.push(node); - } - }); - return { - variableToType, - operations - }; -} -function getOperationFacts(schema, documentString) { - if (!documentString) { - return; - } - try { - const documentAST = (0, _graphql.parse)(documentString); - return Object.assign(Object.assign({}, getOperationASTFacts(documentAST, schema)), { - documentAST - }); - } catch (_a) { - return; - } -} -const getQueryFacts = exports.getQueryFacts = getOperationFacts; + // src/components/focus-trap/focus-trap.tsx + var import_react25 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); -/***/ }), + // src/hooks/use-tab-direction.ts + var import_react20 = __webpack_require__(/*! react */ "react"); + function useTabDirection() { + let direction = (0, import_react20.useRef)(0 /* Forwards */); + useWindowEvent( + "keydown", + (event) => { + if (event.key === "Tab") { + direction.current = event.shiftKey + ? 1 /* Backwards */ + : 0 /* Forwards */; + } + }, + true + ); + return direction; + } -/***/ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js": -/*!**************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getVariablesJSONSchema.js ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // src/hooks/use-is-mounted.ts + var import_react21 = __webpack_require__(/*! react */ "react"); + function useIsMounted() { + let mounted = (0, import_react21.useRef)(false); + useIsoMorphicEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + return mounted; + } + // src/hooks/use-owner.ts + var import_react22 = __webpack_require__(/*! react */ "react"); + function useOwnerDocument(...args) { + return (0, import_react22.useMemo)( + () => getOwnerDocument(...args), + [...args] + ); + } + // src/hooks/use-event-listener.ts + var import_react23 = __webpack_require__(/*! react */ "react"); + function useEventListener(element, type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react23.useEffect)(() => { + element = element != null ? element : window; + function handler(event) { + listenerRef.current(event); + } + element.addEventListener(type, handler, options); + return () => element.removeEventListener(type, handler, options); + }, [element, type, options]); + } + + // src/utils/document-ready.ts + function onDocumentReady(cb) { + function check() { + if (document.readyState === "loading") return; + cb(); + document.removeEventListener("DOMContentLoaded", check); + } + if ( + typeof window !== "undefined" && + typeof document !== "undefined" + ) { + document.addEventListener("DOMContentLoaded", check); + check(); + } + } + + // src/hooks/use-on-unmount.ts + var import_react24 = __webpack_require__(/*! react */ "react"); + function useOnUnmount(cb) { + let stableCb = useEvent(cb); + let trulyUnmounted = (0, import_react24.useRef)(false); + (0, import_react24.useEffect)(() => { + trulyUnmounted.current = false; + return () => { + trulyUnmounted.current = true; + microTask(() => { + if (!trulyUnmounted.current) return; + stableCb(); + }); + }; + }, [stableCb]); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.defaultJSONSchemaOptions = void 0; -exports.getVariablesJSONSchema = getVariablesJSONSchema; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const defaultJSONSchemaOptions = exports.defaultJSONSchemaOptions = { - useMarkdownDescription: false -}; -function text(into, newText) { - into.push(newText); -} -function renderType(into, t) { - if ((0, _graphql.isNonNullType)(t)) { - renderType(into, t.ofType); - text(into, '!'); - } else if ((0, _graphql.isListType)(t)) { - text(into, '['); - renderType(into, t.ofType); - text(into, ']'); - } else { - text(into, t.name); - } -} -function renderDefinitionDescription(t, useMarkdown, description) { - const into = []; - const type = 'type' in t ? t.type : t; - if ('type' in t && t.description) { - text(into, t.description); - text(into, '\n\n'); - } - text(into, renderTypeToString(type, useMarkdown)); - if (description) { - text(into, '\n'); - text(into, description); - } else if (!(0, _graphql.isScalarType)(type) && 'description' in type && type.description) { - text(into, '\n'); - text(into, type.description); - } else if ('ofType' in type && !(0, _graphql.isScalarType)(type.ofType) && 'description' in type.ofType && type.ofType.description) { - text(into, '\n'); - text(into, type.ofType.description); - } - return into.join(''); -} -function renderTypeToString(t, useMarkdown) { - const into = []; - if (useMarkdown) { - text(into, '```graphql\n'); - } - renderType(into, t); - if (useMarkdown) { - text(into, '\n```'); - } - return into.join(''); -} -const defaultScalarTypesMap = { - Int: { - type: 'integer' - }, - String: { - type: 'string' - }, - Float: { - type: 'number' - }, - ID: { - type: 'string' - }, - Boolean: { - type: 'boolean' - }, - DateTime: { - type: 'string' - } -}; -class Marker { - constructor() { - this.set = new Set(); - } - mark(name) { - if (this.set.has(name)) { - return false; - } - this.set.add(name); - return true; - } -} -function getJSONSchemaFromGraphQLType(fieldOrType, options) { - var _a, _b; - let definition = Object.create(null); - const definitions = Object.create(null); - const isField = ('type' in fieldOrType); - const type = isField ? fieldOrType.type : fieldOrType; - const baseType = (0, _graphql.isNonNullType)(type) ? type.ofType : type; - const required = (0, _graphql.isNonNullType)(type); - if ((0, _graphql.isScalarType)(baseType)) { - if ((_a = options === null || options === void 0 ? void 0 : options.scalarSchemas) === null || _a === void 0 ? void 0 : _a[baseType.name]) { - definition = JSON.parse(JSON.stringify(options.scalarSchemas[baseType.name])); - } else { - definition.type = ['string', 'number', 'boolean', 'integer']; - } - if (!required) { - if (Array.isArray(definition.type)) { - definition.type.push('null'); - } else if (definition.type) { - definition.type = [definition.type, 'null']; - } else if (definition.enum) { - definition.enum.push(null); - } else if (definition.oneOf) { - definition.oneOf.push({ - type: 'null' - }); - } else { - definition = { - oneOf: [definition, { - type: 'null' - }] - }; - } - } - } else if ((0, _graphql.isEnumType)(baseType)) { - definition.enum = baseType.getValues().map(val => val.name); - if (!required) { - definition.enum.push(null); - } - } else if ((0, _graphql.isListType)(baseType)) { - if (required) { - definition.type = 'array'; - } else { - definition.type = ['array', 'null']; - } - const { - definition: def, - definitions: defs - } = getJSONSchemaFromGraphQLType(baseType.ofType, options); - definition.items = def; - if (defs) { - for (const defName of Object.keys(defs)) { - definitions[defName] = defs[defName]; - } - } - } else if ((0, _graphql.isInputObjectType)(baseType)) { - if (required) { - definition.$ref = `#/definitions/${baseType.name}`; - } else { - definition.oneOf = [{ - $ref: `#/definitions/${baseType.name}` - }, { - type: 'null' - }]; - } - if ((_b = options === null || options === void 0 ? void 0 : options.definitionMarker) === null || _b === void 0 ? void 0 : _b.mark(baseType.name)) { - const fields = baseType.getFields(); - const fieldDef = { - type: 'object', - properties: {}, - required: [] - }; - fieldDef.description = renderDefinitionDescription(baseType); - if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { - fieldDef.markdownDescription = renderDefinitionDescription(baseType, true); - } - for (const fieldName of Object.keys(fields)) { - const field = fields[fieldName]; - const { - required: fieldRequired, - definition: fieldDefinition, - definitions: typeDefinitions - } = getJSONSchemaFromGraphQLType(field, options); - fieldDef.properties[fieldName] = fieldDefinition; - if (fieldRequired) { - fieldDef.required.push(fieldName); - } - if (typeDefinitions) { - for (const [defName, value] of Object.entries(typeDefinitions)) { - definitions[defName] = value; + // src/components/focus-trap/focus-trap.tsx + function resolveContainers(containers) { + if (!containers) return /* @__PURE__ */ new Set(); + if (typeof containers === "function") return new Set(containers()); + let all = /* @__PURE__ */ new Set(); + for (let container of containers.current) { + if (container.current instanceof HTMLElement) { + all.add(container.current); + } } + return all; + } + var DEFAULT_FOCUS_TRAP_TAG = "div"; + var Features3 = /* @__PURE__ */ ((Features4) => { + Features4[(Features4["None"] = 1)] = "None"; + Features4[(Features4["InitialFocus"] = 2)] = "InitialFocus"; + Features4[(Features4["TabLock"] = 4)] = "TabLock"; + Features4[(Features4["FocusLock"] = 8)] = "FocusLock"; + Features4[(Features4["RestoreFocus"] = 16)] = "RestoreFocus"; + Features4[(Features4["All"] = 30)] = "All"; + return Features4; + })(Features3 || {}); + function FocusTrapFn(props, ref) { + let container = (0, import_react25.useRef)(null); + let focusTrapRef = useSyncRefs(container, ref); + let { + initialFocus, + containers, + features = 30 /* All */, + ...theirProps + } = props; + if (!useServerHandoffComplete()) { + features = 1 /* None */; + } + let ownerDocument = useOwnerDocument(container); + useRestoreFocus( + { ownerDocument }, + Boolean(features & 16 /* RestoreFocus */) + ); + let previousActiveElement = useInitialFocus( + { ownerDocument, container, initialFocus }, + Boolean(features & 2 /* InitialFocus */) + ); + useFocusLock( + { ownerDocument, container, containers, previousActiveElement }, + Boolean(features & 8 /* FocusLock */) + ); + let direction = useTabDirection(); + let handleFocus = useEvent((e) => { + let el = container.current; + if (!el) return; + let wrapper = false ? 0 : (cb) => cb(); + wrapper(() => { + match(direction.current, { + [0 /* Forwards */]: () => { + focusIn(el, 1 /* First */, { + skipElements: [e.relatedTarget], + }); + }, + [1 /* Backwards */]: () => { + focusIn(el, 8 /* Last */, { + skipElements: [e.relatedTarget], + }); + }, + }); + }); + }); + let d = useDisposables(); + let recentlyUsedTabKey = (0, import_react25.useRef)(false); + let ourProps = { + ref: focusTrapRef, + onKeyDown(e) { + if (e.key == "Tab") { + recentlyUsedTabKey.current = true; + d.requestAnimationFrame(() => { + recentlyUsedTabKey.current = false; + }); + } + }, + onBlur(e) { + let allContainers = resolveContainers(containers); + if (container.current instanceof HTMLElement) + allContainers.add(container.current); + let relatedTarget = e.relatedTarget; + if (!(relatedTarget instanceof HTMLElement)) return; + if (relatedTarget.dataset.headlessuiFocusGuard === "true") { + return; + } + if (!contains(allContainers, relatedTarget)) { + if (recentlyUsedTabKey.current) { + focusIn( + container.current, + match(direction.current, { + [0 /* Forwards */]: () => 4 /* Next */, + [1 /* Backwards */]: () => 2 /* Previous */, + }) | 16 /* WrapAround */, + { relativeTo: e.target } + ); + } else if (e.target instanceof HTMLElement) { + focusElement(e.target); + } + } + }, + }; + return /* @__PURE__ */ import_react25.default.createElement( + import_react25.default.Fragment, + null, + Boolean(features & 4 /* TabLock */) && + /* @__PURE__ */ import_react25.default.createElement(Hidden, { + as: "button", + type: "button", + "data-headlessui-focus-guard": true, + onFocus: handleFocus, + features: 2 /* Focusable */, + }), + render({ + ourProps, + theirProps, + defaultTag: DEFAULT_FOCUS_TRAP_TAG, + name: "FocusTrap", + }), + Boolean(features & 4 /* TabLock */) && + /* @__PURE__ */ import_react25.default.createElement(Hidden, { + as: "button", + type: "button", + "data-headlessui-focus-guard": true, + onFocus: handleFocus, + features: 2 /* Focusable */, + }) + ); } - } - definitions[baseType.name] = fieldDef; - } - } - if ('defaultValue' in fieldOrType && fieldOrType.defaultValue !== undefined) { - definition.default = fieldOrType.defaultValue; - } - const { - description - } = definition; - definition.description = renderDefinitionDescription(fieldOrType, false, description); - if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { - definition.markdownDescription = renderDefinitionDescription(fieldOrType, true, description); - } - return { - required, - definition, - definitions - }; -} -function getVariablesJSONSchema(variableToType, options) { - var _a; - const jsonSchema = { - $schema: 'http://json-schema.org/draft-04/schema', - type: 'object', - properties: {}, - required: [] - }; - const runtimeOptions = Object.assign(Object.assign({}, options), { - definitionMarker: new Marker(), - scalarSchemas: Object.assign(Object.assign({}, defaultScalarTypesMap), options === null || options === void 0 ? void 0 : options.scalarSchemas) - }); - if (variableToType) { - for (const [variableName, type] of Object.entries(variableToType)) { - const { - definition, - required, - definitions - } = getJSONSchemaFromGraphQLType(type, runtimeOptions); - jsonSchema.properties[variableName] = definition; - if (required) { - (_a = jsonSchema.required) === null || _a === void 0 ? void 0 : _a.push(variableName); - } - if (definitions) { - jsonSchema.definitions = Object.assign(Object.assign({}, jsonSchema === null || jsonSchema === void 0 ? void 0 : jsonSchema.definitions), definitions); - } - } - } - return jsonSchema; -} - -/***/ }), - -/***/ "../../graphql-language-service/esm/utils/index.js": -/*!*********************************************************!*\ - !*** ../../graphql-language-service/esm/utils/index.js ***! - \*********************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "Position", ({ - enumerable: true, - get: function () { - return _Range.Position; - } -})); -Object.defineProperty(exports, "Range", ({ - enumerable: true, - get: function () { - return _Range.Range; - } -})); -Object.defineProperty(exports, "collectVariables", ({ - enumerable: true, - get: function () { - return _collectVariables.collectVariables; - } -})); -Object.defineProperty(exports, "getASTNodeAtPosition", ({ - enumerable: true, - get: function () { - return _getASTNodeAtPosition.getASTNodeAtPosition; - } -})); -Object.defineProperty(exports, "getFragmentDependencies", ({ - enumerable: true, - get: function () { - return _fragmentDependencies.getFragmentDependencies; - } -})); -Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ - enumerable: true, - get: function () { - return _fragmentDependencies.getFragmentDependenciesForAST; - } -})); -Object.defineProperty(exports, "getOperationASTFacts", ({ - enumerable: true, - get: function () { - return _getOperationFacts.getOperationASTFacts; - } -})); -Object.defineProperty(exports, "getOperationFacts", ({ - enumerable: true, - get: function () { - return _getOperationFacts.default; - } -})); -Object.defineProperty(exports, "getQueryFacts", ({ - enumerable: true, - get: function () { - return _getOperationFacts.getQueryFacts; - } -})); -Object.defineProperty(exports, "getVariablesJSONSchema", ({ - enumerable: true, - get: function () { - return _getVariablesJSONSchema.getVariablesJSONSchema; - } -})); -Object.defineProperty(exports, "locToRange", ({ - enumerable: true, - get: function () { - return _Range.locToRange; - } -})); -Object.defineProperty(exports, "offsetToPosition", ({ - enumerable: true, - get: function () { - return _Range.offsetToPosition; - } -})); -Object.defineProperty(exports, "pointToOffset", ({ - enumerable: true, - get: function () { - return _getASTNodeAtPosition.pointToOffset; - } -})); -Object.defineProperty(exports, "validateWithCustomRules", ({ - enumerable: true, - get: function () { - return _validateWithCustomRules.validateWithCustomRules; - } -})); -var _fragmentDependencies = __webpack_require__(/*! ./fragmentDependencies */ "../../graphql-language-service/esm/utils/fragmentDependencies.js"); -var _getVariablesJSONSchema = __webpack_require__(/*! ./getVariablesJSONSchema */ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js"); -var _getASTNodeAtPosition = __webpack_require__(/*! ./getASTNodeAtPosition */ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js"); -var _Range = __webpack_require__(/*! ./Range */ "../../graphql-language-service/esm/utils/Range.js"); -var _validateWithCustomRules = __webpack_require__(/*! ./validateWithCustomRules */ "../../graphql-language-service/esm/utils/validateWithCustomRules.js"); -var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); -var _getOperationFacts = _interopRequireWildcard(__webpack_require__(/*! ./getOperationFacts */ "../../graphql-language-service/esm/utils/getOperationFacts.js")); -function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } -function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - -/***/ }), - -/***/ "../../graphql-language-service/esm/utils/validateWithCustomRules.js": -/*!***************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/validateWithCustomRules.js ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.validateWithCustomRules = validateWithCustomRules; -var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); -const specifiedSDLRules = [_graphql.LoneSchemaDefinitionRule, _graphql.UniqueOperationTypesRule, _graphql.UniqueTypeNamesRule, _graphql.UniqueEnumValueNamesRule, _graphql.UniqueFieldDefinitionNamesRule, _graphql.UniqueDirectiveNamesRule, _graphql.KnownTypeNamesRule, _graphql.KnownDirectivesRule, _graphql.UniqueDirectivesPerLocationRule, _graphql.PossibleTypeExtensionsRule, _graphql.UniqueArgumentNamesRule, _graphql.UniqueInputFieldNamesRule, _graphql.UniqueVariableNamesRule, _graphql.FragmentsOnCompositeTypesRule, _graphql.ProvidedRequiredArgumentsRule]; -function validateWithCustomRules(schema, ast, customRules, isRelayCompatMode, isSchemaDocument) { - const rules = _graphql.specifiedRules.filter(rule => { - if (rule === _graphql.NoUnusedFragmentsRule || rule === _graphql.ExecutableDefinitionsRule) { - return false; - } - if (isRelayCompatMode && rule === _graphql.KnownFragmentNamesRule) { - return false; - } - return true; - }); - if (customRules) { - Array.prototype.push.apply(rules, customRules); - } - if (isSchemaDocument) { - Array.prototype.push.apply(rules, specifiedSDLRules); - } - const errors = (0, _graphql.validate)(schema, ast, rules); - return errors.filter(error => { - if (error.message.includes('Unknown directive') && error.nodes) { - const node = error.nodes[0]; - if (node && node.kind === _graphql.Kind.DIRECTIVE) { - const name = node.name.value; - if (name === 'arguments' || name === 'argumentDefinitions') { + var FocusTrapRoot = forwardRefWithAs(FocusTrapFn); + var FocusTrap = Object.assign(FocusTrapRoot, { + features: Features3, + }); + var history = []; + onDocumentReady(() => { + function handle(e) { + if (!(e.target instanceof HTMLElement)) return; + if (e.target === document.body) return; + if (history[0] === e.target) return; + history.unshift(e.target); + history = history.filter((x) => x != null && x.isConnected); + history.splice(10); + } + window.addEventListener("click", handle, { capture: true }); + window.addEventListener("mousedown", handle, { capture: true }); + window.addEventListener("focus", handle, { capture: true }); + document.body.addEventListener("click", handle, { capture: true }); + document.body.addEventListener("mousedown", handle, { + capture: true, + }); + document.body.addEventListener("focus", handle, { capture: true }); + }); + function useRestoreElement(enabled = true) { + let localHistory = (0, import_react25.useRef)(history.slice()); + useWatch( + ([newEnabled], [oldEnabled]) => { + if (oldEnabled === true && newEnabled === false) { + microTask(() => { + localHistory.current.splice(0); + }); + } + if (oldEnabled === false && newEnabled === true) { + localHistory.current = history.slice(); + } + }, + [enabled, history, localHistory] + ); + return useEvent(() => { + var _a3; + return (_a3 = localHistory.current.find( + (x) => x != null && x.isConnected + )) != null + ? _a3 + : null; + }); + } + function useRestoreFocus({ ownerDocument }, enabled) { + let getRestoreElement = useRestoreElement(enabled); + useWatch(() => { + if (enabled) return; + if ( + (ownerDocument == null ? void 0 : ownerDocument.activeElement) === + (ownerDocument == null ? void 0 : ownerDocument.body) + ) { + focusElement(getRestoreElement()); + } + }, [enabled]); + useOnUnmount(() => { + if (!enabled) return; + focusElement(getRestoreElement()); + }); + } + function useInitialFocus( + { ownerDocument, container, initialFocus }, + enabled + ) { + let previousActiveElement = (0, import_react25.useRef)(null); + let mounted = useIsMounted(); + useWatch(() => { + if (!enabled) return; + let containerElement = container.current; + if (!containerElement) return; + microTask(() => { + if (!mounted.current) { + return; + } + let activeElement = + ownerDocument == null ? void 0 : ownerDocument.activeElement; + if (initialFocus == null ? void 0 : initialFocus.current) { + if ( + (initialFocus == null ? void 0 : initialFocus.current) === + activeElement + ) { + previousActiveElement.current = activeElement; + return; + } + } else if (containerElement.contains(activeElement)) { + previousActiveElement.current = activeElement; + return; + } + if (initialFocus == null ? void 0 : initialFocus.current) { + focusElement(initialFocus.current); + } else { + if ( + focusIn(containerElement, 1 /* First */) === 0 /* Error */ + ) { + console.warn( + "There are no focusable elements inside the " + ); + } + } + previousActiveElement.current = + ownerDocument == null ? void 0 : ownerDocument.activeElement; + }); + }, [enabled]); + return previousActiveElement; + } + function useFocusLock( + { ownerDocument, container, containers, previousActiveElement }, + enabled + ) { + let mounted = useIsMounted(); + useEventListener( + ownerDocument == null ? void 0 : ownerDocument.defaultView, + "focus", + (event) => { + if (!enabled) return; + if (!mounted.current) return; + let allContainers = resolveContainers(containers); + if (container.current instanceof HTMLElement) + allContainers.add(container.current); + let previous = previousActiveElement.current; + if (!previous) return; + let toElement = event.target; + if (toElement && toElement instanceof HTMLElement) { + if (!contains(allContainers, toElement)) { + event.preventDefault(); + event.stopPropagation(); + focusElement(previous); + } else { + previousActiveElement.current = toElement; + focusElement(toElement); + } + } else { + focusElement(previousActiveElement.current); + } + }, + true + ); + } + function contains(containers, element) { + for (let container of containers) { + if (container.contains(element)) return true; + } return false; } - } - } - return true; - }); -} - -/***/ }), - -/***/ "./style.css": -/*!*******************!*\ - !*** ./style.css ***! - \*******************/ -/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { - -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin - - -/***/ }), - -/***/ "../../graphiql-react/dist/style.css": -/*!*******************************************!*\ - !*** ../../graphiql-react/dist/style.css ***! - \*******************************************/ -/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { - -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin + // src/components/portal/portal.tsx + var import_react27 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var import_react_dom = __webpack_require__( + /*! react-dom */ "react-dom" + ); -/***/ }), + // src/internal/portal-force-root.tsx + var import_react26 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var ForcePortalRootContext = (0, import_react26.createContext)(false); + function usePortalRoot() { + return (0, import_react26.useContext)(ForcePortalRootContext); + } + function ForcePortalRoot(props) { + return /* @__PURE__ */ import_react26.default.createElement( + ForcePortalRootContext.Provider, + { value: props.force }, + props.children + ); + } -/***/ "../../graphiql-react/font/fira-code.css": -/*!***********************************************!*\ - !*** ../../graphiql-react/font/fira-code.css ***! - \***********************************************/ -/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + // src/components/portal/portal.tsx + function usePortalTarget(ref) { + let forceInRoot = usePortalRoot(); + let groupTarget = (0, import_react27.useContext)(PortalGroupContext); + let ownerDocument = useOwnerDocument(ref); + let [target, setTarget] = (0, import_react27.useState)(() => { + if (!forceInRoot && groupTarget !== null) return null; + if (env.isServer) return null; + let existingRoot = + ownerDocument == null + ? void 0 + : ownerDocument.getElementById("headlessui-portal-root"); + if (existingRoot) return existingRoot; + if (ownerDocument === null) return null; + let root = ownerDocument.createElement("div"); + root.setAttribute("id", "headlessui-portal-root"); + return ownerDocument.body.appendChild(root); + }); + (0, import_react27.useEffect)(() => { + if (target === null) return; + if ( + !(ownerDocument == null + ? void 0 + : ownerDocument.body.contains(target)) + ) { + ownerDocument == null + ? void 0 + : ownerDocument.body.appendChild(target); + } + }, [target, ownerDocument]); + (0, import_react27.useEffect)(() => { + if (forceInRoot) return; + if (groupTarget === null) return; + setTarget(groupTarget.current); + }, [groupTarget, setTarget, forceInRoot]); + return target; + } + var DEFAULT_PORTAL_TAG = import_react27.Fragment; + function PortalFn(props, ref) { + let theirProps = props; + let internalPortalRootRef = (0, import_react27.useRef)(null); + let portalRef = useSyncRefs( + optionalRef((ref2) => { + internalPortalRootRef.current = ref2; + }), + ref + ); + let ownerDocument = useOwnerDocument(internalPortalRootRef); + let target = usePortalTarget(internalPortalRootRef); + let [element] = (0, import_react27.useState)(() => { + var _a3; + return env.isServer + ? null + : (_a3 = + ownerDocument == null + ? void 0 + : ownerDocument.createElement("div")) != null + ? _a3 + : null; + }); + let parent = (0, import_react27.useContext)(PortalParentContext); + let ready = useServerHandoffComplete(); + useIsoMorphicEffect(() => { + if (!target || !element) return; + if (!target.contains(element)) { + element.setAttribute("data-headlessui-portal", ""); + target.appendChild(element); + } + }, [target, element]); + useIsoMorphicEffect(() => { + if (!element) return; + if (!parent) return; + return parent.register(element); + }, [parent, element]); + useOnUnmount(() => { + var _a3; + if (!target || !element) return; + if (element instanceof Node && target.contains(element)) { + target.removeChild(element); + } + if (target.childNodes.length <= 0) { + (_a3 = target.parentElement) == null + ? void 0 + : _a3.removeChild(target); + } + }); + if (!ready) return null; + let ourProps = { ref: portalRef }; + return !target || !element + ? null + : (0, import_react_dom.createPortal)( + render({ + ourProps, + theirProps, + defaultTag: DEFAULT_PORTAL_TAG, + name: "Portal", + }), + element + ); + } + var DEFAULT_GROUP_TAG = import_react27.Fragment; + var PortalGroupContext = (0, import_react27.createContext)(null); + function GroupFn(props, ref) { + let { target, ...theirProps } = props; + let groupRef = useSyncRefs(ref); + let ourProps = { ref: groupRef }; + return /* @__PURE__ */ import_react27.default.createElement( + PortalGroupContext.Provider, + { value: target }, + render({ + ourProps, + theirProps, + defaultTag: DEFAULT_GROUP_TAG, + name: "Popover.Group", + }) + ); + } + var PortalParentContext = (0, import_react27.createContext)(null); + function useNestedPortals() { + let parent = (0, import_react27.useContext)(PortalParentContext); + let portals = (0, import_react27.useRef)([]); + let register = useEvent((portal) => { + portals.current.push(portal); + if (parent) parent.register(portal); + return () => unregister(portal); + }); + let unregister = useEvent((portal) => { + let idx = portals.current.indexOf(portal); + if (idx !== -1) portals.current.splice(idx, 1); + if (parent) parent.unregister(portal); + }); + let api = (0, import_react27.useMemo)( + () => ({ register, unregister, portals }), + [register, unregister, portals] + ); + return [ + portals, + (0, import_react27.useMemo)(() => { + return function PortalWrapper({ children }) { + return /* @__PURE__ */ import_react27.default.createElement( + PortalParentContext.Provider, + { value: api }, + children + ); + }; + }, [api]), + ]; + } + var PortalRoot = forwardRefWithAs(PortalFn); + var Group = forwardRefWithAs(GroupFn); + var Portal = Object.assign(PortalRoot, { Group }); -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin + // src/components/description/description.tsx + var import_react28 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var DescriptionContext = (0, import_react28.createContext)(null); + function useDescriptionContext() { + let context = (0, import_react28.useContext)(DescriptionContext); + if (context === null) { + let err = new Error( + "You used a component, but it is not inside a relevant parent." + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDescriptionContext); + throw err; + } + return context; + } + function useDescriptions() { + let [descriptionIds, setDescriptionIds] = (0, + import_react28.useState)([]); + return [ + // The actual id's as string or undefined + descriptionIds.length > 0 ? descriptionIds.join(" ") : void 0, + // The provider component + (0, import_react28.useMemo)(() => { + return function DescriptionProvider(props) { + let register = useEvent((value) => { + setDescriptionIds((existing) => [...existing, value]); + return () => + setDescriptionIds((existing) => { + let clone = existing.slice(); + let idx = clone.indexOf(value); + if (idx !== -1) clone.splice(idx, 1); + return clone; + }); + }); + let contextBag = (0, import_react28.useMemo)( + () => ({ + register, + slot: props.slot, + name: props.name, + props: props.props, + }), + [register, props.slot, props.name, props.props] + ); + return /* @__PURE__ */ import_react28.default.createElement( + DescriptionContext.Provider, + { value: contextBag }, + props.children + ); + }; + }, [setDescriptionIds]), + ]; + } + var DEFAULT_DESCRIPTION_TAG = "p"; + function DescriptionFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-description-${internalId}`, ...theirProps } = + props; + let context = useDescriptionContext(); + let descriptionRef = useSyncRefs(ref); + useIsoMorphicEffect( + () => context.register(id), + [id, context.register] + ); + let ourProps = { ref: descriptionRef, ...context.props, id }; + return render({ + ourProps, + theirProps, + slot: context.slot || {}, + defaultTag: DEFAULT_DESCRIPTION_TAG, + name: context.name || "Description", + }); + } + var DescriptionRoot = forwardRefWithAs(DescriptionFn); + var Description = Object.assign(DescriptionRoot, { + // + }); + // src/internal/stack-context.tsx + var import_react29 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var StackContext = (0, import_react29.createContext)(() => {}); + StackContext.displayName = "StackContext"; + function useStackContext() { + return (0, import_react29.useContext)(StackContext); + } + function StackProvider({ children, onUpdate, type, element, enabled }) { + let parentUpdate = useStackContext(); + let notify = useEvent((...args) => { + onUpdate == null ? void 0 : onUpdate(...args); + parentUpdate(...args); + }); + useIsoMorphicEffect(() => { + let shouldNotify = enabled === void 0 || enabled === true; + shouldNotify && notify(0 /* Add */, type, element); + return () => { + shouldNotify && notify(1 /* Remove */, type, element); + }; + }, [notify, type, element, enabled]); + return /* @__PURE__ */ import_react29.default.createElement( + StackContext.Provider, + { value: notify }, + children + ); + } -/***/ }), + // src/use-sync-external-store-shim/index.ts + var React11 = __toESM(__webpack_require__(/*! react */ "react"), 1); -/***/ "../../graphiql-react/font/roboto.css": -/*!********************************************!*\ - !*** ../../graphiql-react/font/roboto.css ***! - \********************************************/ -/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + // src/use-sync-external-store-shim/useSyncExternalStoreShimClient.ts + var React10 = __toESM(__webpack_require__(/*! react */ "react"), 1); + function isPolyfill(x, y) { + return ( + (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) + ); + } + var is = typeof Object.is === "function" ? Object.is : isPolyfill; + var { + useState: useState8, + useEffect: useEffect14, + useLayoutEffect: useLayoutEffect2, + useDebugValue, + } = React10; + var didWarnOld18Alpha = false; + var didWarnUncachedGetSnapshot = false; + function useSyncExternalStore( + subscribe, + getSnapshot, + getServerSnapshot + ) { + if (true) { + if (!didWarnOld18Alpha) { + if ("startTransition" in React10) { + didWarnOld18Alpha = true; + console.error( + "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." + ); + } + } + } + const value = getSnapshot(); + if (true) { + if (!didWarnUncachedGetSnapshot) { + const cachedValue = getSnapshot(); + if (!is(value, cachedValue)) { + console.error( + "The result of getSnapshot should be cached to avoid an infinite loop" + ); + didWarnUncachedGetSnapshot = true; + } + } + } + const [{ inst }, forceUpdate] = useState8({ + inst: { value, getSnapshot }, + }); + useLayoutEffect2(() => { + inst.value = value; + inst.getSnapshot = getSnapshot; + if (checkIfSnapshotChanged(inst)) { + forceUpdate({ inst }); + } + }, [subscribe, value, getSnapshot]); + useEffect14(() => { + if (checkIfSnapshotChanged(inst)) { + forceUpdate({ inst }); + } + const handleStoreChange = () => { + if (checkIfSnapshotChanged(inst)) { + forceUpdate({ inst }); + } + }; + return subscribe(handleStoreChange); + }, [subscribe]); + useDebugValue(value); + return value; + } + function checkIfSnapshotChanged(inst) { + const latestGetSnapshot = inst.getSnapshot; + const prevValue = inst.value; + try { + const nextValue = latestGetSnapshot(); + return !is(prevValue, nextValue); + } catch (error) { + return true; + } + } -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin + // src/use-sync-external-store-shim/useSyncExternalStoreShimServer.ts + function useSyncExternalStore2( + subscribe, + getSnapshot, + getServerSnapshot + ) { + return getSnapshot(); + } + // src/use-sync-external-store-shim/index.ts + var canUseDOM = !!( + typeof window !== "undefined" && + typeof window.document !== "undefined" && + typeof window.document.createElement !== "undefined" + ); + var isServerEnvironment = !canUseDOM; + var shim = isServerEnvironment + ? useSyncExternalStore2 + : useSyncExternalStore; + var useSyncExternalStore3 = + "useSyncExternalStore" in React11 + ? ((r) => r.useSyncExternalStore)(React11) + : shim; + + // src/hooks/use-store.ts + function useStore(store) { + return useSyncExternalStore3( + store.subscribe, + store.getSnapshot, + store.getSnapshot + ); + } -/***/ }), + // src/utils/store.ts + function createStore(initial, actions) { + let state = initial(); + let listeners = /* @__PURE__ */ new Set(); + return { + getSnapshot() { + return state; + }, + subscribe(onChange) { + listeners.add(onChange); + return () => listeners.delete(onChange); + }, + dispatch(key, ...args) { + let newState = actions[key].call(state, ...args); + if (newState) { + state = newState; + listeners.forEach((listener) => listener()); + } + }, + }; + } -/***/ "react": -/*!************************!*\ - !*** external "React" ***! - \************************/ -/***/ (function(module) { + // src/hooks/document-overflow/adjust-scrollbar-padding.ts + function adjustScrollbarPadding() { + let scrollbarWidthBefore; + return { + before({ doc }) { + var _a3; + let documentElement = doc.documentElement; + let ownerWindow = (_a3 = doc.defaultView) != null ? _a3 : window; + scrollbarWidthBefore = + ownerWindow.innerWidth - documentElement.clientWidth; + }, + after({ doc, d }) { + let documentElement = doc.documentElement; + let scrollbarWidthAfter = + documentElement.clientWidth - documentElement.offsetWidth; + let scrollbarWidth = scrollbarWidthBefore - scrollbarWidthAfter; + d.style(documentElement, "paddingRight", `${scrollbarWidth}px`); + }, + }; + } -module.exports = window["React"]; + // src/hooks/document-overflow/handle-ios-locking.ts + function handleIOSLocking() { + if (!isIOS()) { + return {}; + } + let scrollPosition; + return { + before() { + scrollPosition = window.pageYOffset; + }, + after({ doc, d, meta }) { + function inAllowedContainer(el) { + return meta.containers + .flatMap((resolve) => resolve()) + .some((container) => container.contains(el)); + } + d.style(doc.body, "marginTop", `-${scrollPosition}px`); + window.scrollTo(0, 0); + let scrollToElement = null; + d.addEventListener( + doc, + "click", + (e) => { + if (!(e.target instanceof HTMLElement)) { + return; + } + try { + let anchor = e.target.closest("a"); + if (!anchor) return; + let { hash } = new URL(anchor.href); + let el = doc.querySelector(hash); + if (el && !inAllowedContainer(el)) { + scrollToElement = el; + } + } catch (err) {} + }, + true + ); + d.addEventListener( + doc, + "touchmove", + (e) => { + if ( + e.target instanceof HTMLElement && + !inAllowedContainer(e.target) + ) { + e.preventDefault(); + } + }, + { passive: false } + ); + d.add(() => { + window.scrollTo(0, window.pageYOffset + scrollPosition); + if (scrollToElement && scrollToElement.isConnected) { + scrollToElement.scrollIntoView({ block: "nearest" }); + scrollToElement = null; + } + }); + }, + }; + } -/***/ }), + // src/hooks/document-overflow/prevent-scroll.ts + function preventScroll() { + return { + before({ doc, d }) { + d.style(doc.documentElement, "overflow", "hidden"); + }, + }; + } -/***/ "react-dom": -/*!***************************!*\ - !*** external "ReactDOM" ***! - \***************************/ -/***/ (function(module) { + // src/hooks/document-overflow/overflow-store.ts + function buildMeta(fns) { + let tmp = {}; + for (let fn of fns) { + Object.assign(tmp, fn(tmp)); + } + return tmp; + } + var overflows = createStore(() => /* @__PURE__ */ new Map(), { + PUSH(doc, meta) { + var _a3; + let entry = + (_a3 = this.get(doc)) != null + ? _a3 + : { + doc, + count: 0, + d: disposables(), + meta: /* @__PURE__ */ new Set(), + }; + entry.count++; + entry.meta.add(meta); + this.set(doc, entry); + return this; + }, + POP(doc, meta) { + let entry = this.get(doc); + if (entry) { + entry.count--; + entry.meta.delete(meta); + } + return this; + }, + SCROLL_PREVENT({ doc, d, meta }) { + let ctx = { + doc, + d, + meta: buildMeta(meta), + }; + let steps = [ + handleIOSLocking(), + adjustScrollbarPadding(), + preventScroll(), + ]; + steps.forEach(({ before }) => + before == null ? void 0 : before(ctx) + ); + steps.forEach(({ after }) => (after == null ? void 0 : after(ctx))); + }, + SCROLL_ALLOW({ d }) { + d.dispose(); + }, + TEARDOWN({ doc }) { + this.delete(doc); + }, + }); + overflows.subscribe(() => { + let docs = overflows.getSnapshot(); + let styles = /* @__PURE__ */ new Map(); + for (let [doc] of docs) { + styles.set(doc, doc.documentElement.style.overflow); + } + for (let entry of docs.values()) { + let isHidden = styles.get(entry.doc) === "hidden"; + let isLocked = entry.count !== 0; + let willChange = (isLocked && !isHidden) || (!isLocked && isHidden); + if (willChange) { + overflows.dispatch( + entry.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", + entry + ); + } + if (entry.count === 0) { + overflows.dispatch("TEARDOWN", entry); + } + } + }); -module.exports = window["ReactDOM"]; + // src/hooks/document-overflow/use-document-overflow.ts + function useDocumentOverflowLockedEffect(doc, shouldBeLocked, meta) { + let store = useStore(overflows); + let entry = doc ? store.get(doc) : void 0; + let locked = entry ? entry.count > 0 : false; + useIsoMorphicEffect(() => { + if (!doc || !shouldBeLocked) { + return; + } + overflows.dispatch("PUSH", doc, meta); + return () => overflows.dispatch("POP", doc, meta); + }, [shouldBeLocked, doc]); + return locked; + } + + // src/hooks/use-inert.tsx + var originals = /* @__PURE__ */ new Map(); + var counts = /* @__PURE__ */ new Map(); + function useInert(node, enabled = true) { + useIsoMorphicEffect(() => { + var _a3; + if (!enabled) return; + let element = typeof node === "function" ? node() : node.current; + if (!element) return; + function cleanup() { + var _a4; + if (!element) return; + let count2 = (_a4 = counts.get(element)) != null ? _a4 : 1; + if (count2 === 1) counts.delete(element); + else counts.set(element, count2 - 1); + if (count2 !== 1) return; + let original = originals.get(element); + if (!original) return; + if (original["aria-hidden"] === null) + element.removeAttribute("aria-hidden"); + else element.setAttribute("aria-hidden", original["aria-hidden"]); + element.inert = original.inert; + originals.delete(element); + } + let count = (_a3 = counts.get(element)) != null ? _a3 : 0; + counts.set(element, count + 1); + if (count !== 0) return cleanup; + originals.set(element, { + "aria-hidden": element.getAttribute("aria-hidden"), + inert: element.inert, + }); + element.setAttribute("aria-hidden", "true"); + element.inert = true; + return cleanup; + }, [node, enabled]); + } -/***/ }), + // src/hooks/use-root-containers.tsx + var import_react30 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + function useRootContainers({ defaultContainers = [], portals } = {}) { + let mainTreeNodeRef = (0, import_react30.useRef)(null); + let ownerDocument = useOwnerDocument(mainTreeNodeRef); + let resolveContainers2 = useEvent(() => { + var _a3; + let containers = []; + for (let container of defaultContainers) { + if (container === null) continue; + if (container instanceof HTMLElement) { + containers.push(container); + } else if ( + "current" in container && + container.current instanceof HTMLElement + ) { + containers.push(container.current); + } + } + if (portals == null ? void 0 : portals.current) { + for (let portal of portals.current) { + containers.push(portal); + } + } + for (let container of (_a3 = + ownerDocument == null + ? void 0 + : ownerDocument.querySelectorAll("html > *, body > *")) != null + ? _a3 + : []) { + if (container === document.body) continue; + if (container === document.head) continue; + if (!(container instanceof HTMLElement)) continue; + if (container.id === "headlessui-portal-root") continue; + if (container.contains(mainTreeNodeRef.current)) continue; + if ( + containers.some((defaultContainer) => + container.contains(defaultContainer) + ) + ) + continue; + containers.push(container); + } + return containers; + }); + return { + resolveContainers: resolveContainers2, + contains: useEvent((element) => + resolveContainers2().some((container) => + container.contains(element) + ) + ), + mainTreeNodeRef, + MainTreeNode: (0, import_react30.useMemo)(() => { + return function MainTreeNode() { + return /* @__PURE__ */ import_react30.default.createElement( + Hidden, + { features: 4 /* Hidden */, ref: mainTreeNodeRef } + ); + }; + }, [mainTreeNodeRef]), + }; + } -/***/ "../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs": -/*!***********************************************************************!*\ - !*** ../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs ***! - \***********************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; + // src/components/dialog/dialog.tsx + var reducers2 = { + [0 /* SetTitleId */](state, action) { + if (state.titleId === action.id) return state; + return { ...state, titleId: action.id }; + }, + }; + var DialogContext = (0, import_react31.createContext)(null); + DialogContext.displayName = "DialogContext"; + function useDialogContext(component) { + let context = (0, import_react31.useContext)(DialogContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDialogContext); + throw err; + } + return context; + } + function useScrollLock( + ownerDocument, + enabled, + resolveAllowedContainers = () => [document.body] + ) { + useDocumentOverflowLockedEffect(ownerDocument, enabled, (meta) => { + var _a3; + return { + containers: [ + ...((_a3 = meta.containers) != null ? _a3 : []), + resolveAllowedContainers, + ], + }; + }); + } + function stateReducer2(state, action) { + return match(action.type, reducers2, state, action); + } + var DEFAULT_DIALOG_TAG = "div"; + var DialogRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ + function DialogFn(props, ref) { + var _a3; + let internalId = useId(); + let { + id = `headlessui-dialog-${internalId}`, + open, + onClose, + initialFocus, + __demoMode = false, + ...theirProps + } = props; + let [nestedDialogCount, setNestedDialogCount] = (0, + import_react31.useState)(0); + let usesOpenClosedState = useOpenClosed(); + if (open === void 0 && usesOpenClosedState !== null) { + open = (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; + } + let internalDialogRef = (0, import_react31.useRef)(null); + let dialogRef = useSyncRefs(internalDialogRef, ref); + let ownerDocument = useOwnerDocument(internalDialogRef); + let hasOpen = + props.hasOwnProperty("open") || usesOpenClosedState !== null; + let hasOnClose = props.hasOwnProperty("onClose"); + if (!hasOpen && !hasOnClose) { + throw new Error( + `You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.` + ); + } + if (!hasOpen) { + throw new Error( + `You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.` + ); + } + if (!hasOnClose) { + throw new Error( + `You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.` + ); + } + if (typeof open !== "boolean") { + throw new Error( + `You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${open}` + ); + } + if (typeof onClose !== "function") { + throw new Error( + `You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${onClose}` + ); + } + let dialogState = open ? 0 /* Open */ : 1; /* Closed */ + let [state, dispatch] = (0, import_react31.useReducer)( + stateReducer2, + { + titleId: null, + descriptionId: null, + panelRef: (0, import_react31.createRef)(), + } + ); + let close = useEvent(() => onClose(false)); + let setTitleId = useEvent((id2) => + dispatch({ type: 0 /* SetTitleId */, id: id2 }) + ); + let ready = useServerHandoffComplete(); + let enabled = ready + ? __demoMode + ? false + : dialogState === 0 /* Open */ + : false; + let hasNestedDialogs = nestedDialogCount > 1; + let hasParentDialog = + (0, import_react31.useContext)(DialogContext) !== null; + let [portals, PortalWrapper] = useNestedPortals(); + let { + resolveContainers: resolveRootContainers, + mainTreeNodeRef, + MainTreeNode, + } = useRootContainers({ + portals, + defaultContainers: [ + (_a3 = state.panelRef.current) != null + ? _a3 + : internalDialogRef.current, + ], + }); + let position = !hasNestedDialogs ? "leaf" : "parent"; + let isClosing = + usesOpenClosedState !== null + ? (usesOpenClosedState & 4) /* Closing */ === 4 /* Closing */ + : false; + let inertOthersEnabled = (() => { + if (hasParentDialog) return false; + if (isClosing) return false; + return enabled; + })(); + let resolveRootOfMainTreeNode = (0, + import_react31.useCallback)(() => { + var _a4, _b; + return (_b = Array.from( + (_a4 = + ownerDocument == null + ? void 0 + : ownerDocument.querySelectorAll("body > *")) != null + ? _a4 + : [] + ).find((root) => { + if (root.id === "headlessui-portal-root") return false; + return ( + root.contains(mainTreeNodeRef.current) && + root instanceof HTMLElement + ); + })) != null + ? _b + : null; + }, [mainTreeNodeRef]); + useInert(resolveRootOfMainTreeNode, inertOthersEnabled); + let inertParentDialogs = (() => { + if (hasNestedDialogs) return true; + return enabled; + })(); + let resolveRootOfParentDialog = (0, + import_react31.useCallback)(() => { + var _a4, _b; + return (_b = Array.from( + (_a4 = + ownerDocument == null + ? void 0 + : ownerDocument.querySelectorAll( + "[data-headlessui-portal]" + )) != null + ? _a4 + : [] + ).find( + (root) => + root.contains(mainTreeNodeRef.current) && + root instanceof HTMLElement + )) != null + ? _b + : null; + }, [mainTreeNodeRef]); + useInert(resolveRootOfParentDialog, inertParentDialogs); + let outsideClickEnabled = (() => { + if (!enabled) return false; + if (hasNestedDialogs) return false; + return true; + })(); + useOutsideClick(resolveRootContainers, close, outsideClickEnabled); + let escapeToCloseEnabled = (() => { + if (hasNestedDialogs) return false; + if (dialogState !== 0 /* Open */) return false; + return true; + })(); + useEventListener( + ownerDocument == null ? void 0 : ownerDocument.defaultView, + "keydown", + (event) => { + if (!escapeToCloseEnabled) return; + if (event.defaultPrevented) return; + if (event.key !== "Escape" /* Escape */) return; + event.preventDefault(); + event.stopPropagation(); + close(); + } + ); + let scrollLockEnabled = (() => { + if (isClosing) return false; + if (dialogState !== 0 /* Open */) return false; + if (hasParentDialog) return false; + return true; + })(); + useScrollLock( + ownerDocument, + scrollLockEnabled, + resolveRootContainers + ); + (0, import_react31.useEffect)(() => { + if (dialogState !== 0 /* Open */) return; + if (!internalDialogRef.current) return; + let observer = new ResizeObserver((entries) => { + for (let entry of entries) { + let rect = entry.target.getBoundingClientRect(); + if ( + rect.x === 0 && + rect.y === 0 && + rect.width === 0 && + rect.height === 0 + ) { + close(); + } + } + }); + observer.observe(internalDialogRef.current); + return () => observer.disconnect(); + }, [dialogState, internalDialogRef, close]); + let [describedby, DescriptionProvider] = useDescriptions(); + let contextBag = (0, import_react31.useMemo)( + () => [{ dialogState, close, setTitleId }, state], + [dialogState, state, close, setTitleId] + ); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { + ref: dialogRef, + id, + role: "dialog", + "aria-modal": dialogState === 0 /* Open */ ? true : void 0, + "aria-labelledby": state.titleId, + "aria-describedby": describedby, + }; + return /* @__PURE__ */ import_react31.default.createElement( + StackProvider, + { + type: "Dialog", + enabled: dialogState === 0 /* Open */, + element: internalDialogRef, + onUpdate: useEvent((message, type) => { + if (type !== "Dialog") return; + match(message, { + [0 /* Add */]: () => + setNestedDialogCount((count) => count + 1), + [1 /* Remove */]: () => + setNestedDialogCount((count) => count - 1), + }); + }), + }, + /* @__PURE__ */ import_react31.default.createElement( + ForcePortalRoot, + { force: true }, + /* @__PURE__ */ import_react31.default.createElement( + Portal, + null, + /* @__PURE__ */ import_react31.default.createElement( + DialogContext.Provider, + { value: contextBag }, + /* @__PURE__ */ import_react31.default.createElement( + Portal.Group, + { target: internalDialogRef }, + /* @__PURE__ */ import_react31.default.createElement( + ForcePortalRoot, + { force: false }, + /* @__PURE__ */ import_react31.default.createElement( + DescriptionProvider, + { slot, name: "Dialog.Description" }, + /* @__PURE__ */ import_react31.default.createElement( + FocusTrap, + { + initialFocus, + containers: resolveRootContainers, + features: enabled + ? match(position, { + parent: FocusTrap.features.RestoreFocus, + leaf: + FocusTrap.features.All & + ~FocusTrap.features.FocusLock, + }) + : FocusTrap.features.None, + }, + /* @__PURE__ */ import_react31.default.createElement( + PortalWrapper, + null, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_DIALOG_TAG, + features: DialogRenderFeatures, + visible: dialogState === 0 /* Open */, + name: "Dialog", + }) + ) + ) + ) + ) + ) + ) + ) + ), + /* @__PURE__ */ import_react31.default.createElement( + MainTreeNode, + null + ) + ); + } + var DEFAULT_OVERLAY_TAG = "div"; + function OverlayFn(props, ref) { + let internalId = useId(); + let { + id = `headlessui-dialog-overlay-${internalId}`, + ...theirProps + } = props; + let [{ dialogState, close }] = useDialogContext("Dialog.Overlay"); + let overlayRef = useSyncRefs(ref); + let handleClick = useEvent((event) => { + if (event.target !== event.currentTarget) return; + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + event.preventDefault(); + event.stopPropagation(); + close(); + }); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { + ref: overlayRef, + id, + "aria-hidden": true, + onClick: handleClick, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OVERLAY_TAG, + name: "Dialog.Overlay", + }); + } + var DEFAULT_BACKDROP_TAG = "div"; + function BackdropFn(props, ref) { + let internalId = useId(); + let { + id = `headlessui-dialog-backdrop-${internalId}`, + ...theirProps + } = props; + let [{ dialogState }, state] = useDialogContext("Dialog.Backdrop"); + let backdropRef = useSyncRefs(ref); + (0, import_react31.useEffect)(() => { + if (state.panelRef.current === null) { + throw new Error( + `A component is being used, but a component is missing.` + ); + } + }, [state.panelRef]); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { + ref: backdropRef, + id, + "aria-hidden": true, + }; + return /* @__PURE__ */ import_react31.default.createElement( + ForcePortalRoot, + { force: true }, + /* @__PURE__ */ import_react31.default.createElement( + Portal, + null, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BACKDROP_TAG, + name: "Dialog.Backdrop", + }) + ) + ); + } + var DEFAULT_PANEL_TAG = "div"; + function PanelFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-dialog-panel-${internalId}`, ...theirProps } = + props; + let [{ dialogState }, state] = useDialogContext("Dialog.Panel"); + let panelRef = useSyncRefs(ref, state.panelRef); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let handleClick = useEvent((event) => { + event.stopPropagation(); + }); + let ourProps = { + ref: panelRef, + id, + onClick: handleClick, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG, + name: "Dialog.Panel", + }); + } + var DEFAULT_TITLE_TAG = "h2"; + function TitleFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-dialog-title-${internalId}`, ...theirProps } = + props; + let [{ dialogState, setTitleId }] = useDialogContext("Dialog.Title"); + let titleRef = useSyncRefs(ref); + (0, import_react31.useEffect)(() => { + setTitleId(id); + return () => setTitleId(null); + }, [id, setTitleId]); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { ref: titleRef, id }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_TITLE_TAG, + name: "Dialog.Title", + }); + } + var DialogRoot = forwardRefWithAs(DialogFn); + var Backdrop = forwardRefWithAs(BackdropFn); + var Panel = forwardRefWithAs(PanelFn); + var Overlay = forwardRefWithAs(OverlayFn); + var Title = forwardRefWithAs(TitleFn); + var Dialog = Object.assign(DialogRoot, { + Backdrop, + Panel, + Overlay, + Title, + Description, + }); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Combobox: () => Combobox, - Dialog: () => Dialog, - Disclosure: () => Disclosure, - FocusTrap: () => FocusTrap, - Listbox: () => Listbox, - Menu: () => Menu, - Popover: () => Popover, - Portal: () => Portal, - RadioGroup: () => RadioGroup, - Switch: () => Switch, - Tab: () => Tab, - Transition: () => Transition -}); -module.exports = __toCommonJS(src_exports); - -// src/components/combobox/combobox.tsx -var import_react19 = __toESM(__webpack_require__(/*! react */ "react"), 1); - -// src/hooks/use-computed.ts -var import_react3 = __webpack_require__(/*! react */ "react"); - -// src/hooks/use-iso-morphic-effect.ts -var import_react = __webpack_require__(/*! react */ "react"); - -// src/utils/env.ts -var Env = class { - constructor() { - __publicField(this, "current", this.detect()); - __publicField(this, "handoffState", "pending"); - __publicField(this, "currentId", 0); - } - set(env2) { - if (this.current === env2) - return; - this.handoffState = "pending"; - this.currentId = 0; - this.current = env2; - } - reset() { - this.set(this.detect()); - } - nextId() { - return ++this.currentId; - } - get isServer() { - return this.current === "server"; - } - get isClient() { - return this.current === "client"; - } - detect() { - if (typeof window === "undefined" || typeof document === "undefined") { - return "server"; - } - return "client"; - } - handoff() { - if (this.handoffState === "pending") { - this.handoffState = "complete"; - } - } - get isHandoffComplete() { - return this.handoffState === "complete"; - } -}; -var env = new Env(); - -// src/hooks/use-iso-morphic-effect.ts -var useIsoMorphicEffect = (effect, deps) => { - if (env.isServer) { - (0, import_react.useEffect)(effect, deps); - } else { - (0, import_react.useLayoutEffect)(effect, deps); - } -}; + // src/components/disclosure/disclosure.tsx + var import_react33 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); -// src/hooks/use-latest-value.ts -var import_react2 = __webpack_require__(/*! react */ "react"); -function useLatestValue(value) { - let cache = (0, import_react2.useRef)(value); - useIsoMorphicEffect(() => { - cache.current = value; - }, [value]); - return cache; -} - -// src/hooks/use-computed.ts -function useComputed(cb, dependencies) { - let [value, setValue] = (0, import_react3.useState)(cb); - let cbRef = useLatestValue(cb); - useIsoMorphicEffect(() => setValue(cbRef.current), [cbRef, setValue, ...dependencies]); - return value; -} - -// src/hooks/use-disposables.ts -var import_react4 = __webpack_require__(/*! react */ "react"); - -// src/utils/micro-task.ts -function microTask(cb) { - if (typeof queueMicrotask === "function") { - queueMicrotask(cb); - } else { - Promise.resolve().then(cb).catch( - (e) => setTimeout(() => { - throw e; - }) - ); - } -} - -// src/utils/disposables.ts -function disposables() { - let _disposables = []; - let api = { - addEventListener(element, name, listener, options) { - element.addEventListener(name, listener, options); - return api.add(() => element.removeEventListener(name, listener, options)); - }, - requestAnimationFrame(...args) { - let raf = requestAnimationFrame(...args); - return api.add(() => cancelAnimationFrame(raf)); - }, - nextFrame(...args) { - return api.requestAnimationFrame(() => { - return api.requestAnimationFrame(...args); - }); - }, - setTimeout(...args) { - let timer = setTimeout(...args); - return api.add(() => clearTimeout(timer)); - }, - microTask(...args) { - let task = { current: true }; - microTask(() => { - if (task.current) { - args[0](); - } - }); - return api.add(() => { - task.current = false; - }); - }, - style(node, property, value) { - let previous = node.style.getPropertyValue(property); - Object.assign(node.style, { [property]: value }); - return this.add(() => { - Object.assign(node.style, { [property]: previous }); - }); - }, - group(cb) { - let d = disposables(); - cb(d); - return this.add(() => d.dispose()); - }, - add(cb) { - _disposables.push(cb); - return () => { - let idx = _disposables.indexOf(cb); - if (idx >= 0) { - for (let dispose of _disposables.splice(idx, 1)) { - dispose(); - } - } - }; - }, - dispose() { - for (let dispose of _disposables.splice(0)) { - dispose(); - } - } - }; - return api; -} - -// src/hooks/use-disposables.ts -function useDisposables() { - let [d] = (0, import_react4.useState)(disposables); - (0, import_react4.useEffect)(() => () => d.dispose(), [d]); - return d; -} - -// src/hooks/use-event.ts -var import_react5 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var useEvent = ( - // TODO: Add React.useEvent ?? once the useEvent hook is available - function useEvent2(cb) { - let cache = useLatestValue(cb); - return import_react5.default.useCallback((...args) => cache.current(...args), [cache]); - } -); + // src/utils/start-transition.ts + var import_react32 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var _a2; + var startTransition = + // Prefer React's `startTransition` if it's available. + // @ts-expect-error - `startTransition` doesn't exist in React < 18. + (_a2 = import_react32.default.startTransition) != null + ? _a2 + : function startTransition2(cb) { + cb(); + }; -// src/hooks/use-id.ts -var import_react7 = __toESM(__webpack_require__(/*! react */ "react"), 1); + // src/components/disclosure/disclosure.tsx + var reducers3 = { + [0 /* ToggleDisclosure */]: (state) => ({ + ...state, + disclosureState: match(state.disclosureState, { + [0 /* Open */]: 1 /* Closed */, + [1 /* Closed */]: 0 /* Open */, + }), + }), + [1 /* CloseDisclosure */]: (state) => { + if (state.disclosureState === 1 /* Closed */) return state; + return { ...state, disclosureState: 1 /* Closed */ }; + }, + [4 /* LinkPanel */](state) { + if (state.linkedPanel === true) return state; + return { ...state, linkedPanel: true }; + }, + [5 /* UnlinkPanel */](state) { + if (state.linkedPanel === false) return state; + return { ...state, linkedPanel: false }; + }, + [2 /* SetButtonId */](state, action) { + if (state.buttonId === action.buttonId) return state; + return { ...state, buttonId: action.buttonId }; + }, + [3 /* SetPanelId */](state, action) { + if (state.panelId === action.panelId) return state; + return { ...state, panelId: action.panelId }; + }, + }; + var DisclosureContext = (0, import_react33.createContext)(null); + DisclosureContext.displayName = "DisclosureContext"; + function useDisclosureContext(component) { + let context = (0, import_react33.useContext)(DisclosureContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDisclosureContext); + throw err; + } + return context; + } + var DisclosureAPIContext = (0, import_react33.createContext)(null); + DisclosureAPIContext.displayName = "DisclosureAPIContext"; + function useDisclosureAPIContext(component) { + let context = (0, import_react33.useContext)(DisclosureAPIContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDisclosureAPIContext); + throw err; + } + return context; + } + var DisclosurePanelContext = (0, import_react33.createContext)(null); + DisclosurePanelContext.displayName = "DisclosurePanelContext"; + function useDisclosurePanelContext() { + return (0, import_react33.useContext)(DisclosurePanelContext); + } + function stateReducer3(state, action) { + return match(action.type, reducers3, state, action); + } + var DEFAULT_DISCLOSURE_TAG = import_react33.Fragment; + function DisclosureFn(props, ref) { + let { defaultOpen = false, ...theirProps } = props; + let internalDisclosureRef = (0, import_react33.useRef)(null); + let disclosureRef = useSyncRefs( + ref, + optionalRef( + (ref2) => { + internalDisclosureRef.current = ref2; + }, + props.as === void 0 || // @ts-expect-error The `as` prop _can_ be a Fragment + props.as === import_react33.Fragment + ) + ); + let panelRef = (0, import_react33.useRef)(null); + let buttonRef = (0, import_react33.useRef)(null); + let reducerBag = (0, import_react33.useReducer)(stateReducer3, { + disclosureState: defaultOpen ? 0 /* Open */ : 1 /* Closed */, + linkedPanel: false, + buttonRef, + panelRef, + buttonId: null, + panelId: null, + }); + let [{ disclosureState, buttonId }, dispatch] = reducerBag; + let close = useEvent((focusableElement) => { + dispatch({ type: 1 /* CloseDisclosure */ }); + let ownerDocument = getOwnerDocument(internalDisclosureRef); + if (!ownerDocument) return; + if (!buttonId) return; + let restoreElement = (() => { + if (!focusableElement) + return ownerDocument.getElementById(buttonId); + if (focusableElement instanceof HTMLElement) + return focusableElement; + if (focusableElement.current instanceof HTMLElement) + return focusableElement.current; + return ownerDocument.getElementById(buttonId); + })(); + restoreElement == null ? void 0 : restoreElement.focus(); + }); + let api = (0, import_react33.useMemo)(() => ({ close }), [close]); + let slot = (0, import_react33.useMemo)( + () => ({ open: disclosureState === 0 /* Open */, close }), + [disclosureState, close] + ); + let ourProps = { + ref: disclosureRef, + }; + return /* @__PURE__ */ import_react33.default.createElement( + DisclosureContext.Provider, + { value: reducerBag }, + /* @__PURE__ */ import_react33.default.createElement( + DisclosureAPIContext.Provider, + { value: api }, + /* @__PURE__ */ import_react33.default.createElement( + OpenClosedProvider, + { + value: match(disclosureState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */, + }), + }, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_DISCLOSURE_TAG, + name: "Disclosure", + }) + ) + ) + ); + } + var DEFAULT_BUTTON_TAG2 = "button"; + function ButtonFn2(props, ref) { + let internalId = useId(); + let { + id = `headlessui-disclosure-button-${internalId}`, + ...theirProps + } = props; + let [state, dispatch] = useDisclosureContext("Disclosure.Button"); + let panelContext = useDisclosurePanelContext(); + let isWithinPanel = + panelContext === null ? false : panelContext === state.panelId; + let internalButtonRef = (0, import_react33.useRef)(null); + let buttonRef = useSyncRefs( + internalButtonRef, + ref, + !isWithinPanel ? state.buttonRef : null + ); + (0, import_react33.useEffect)(() => { + if (isWithinPanel) return; + dispatch({ type: 2 /* SetButtonId */, buttonId: id }); + return () => { + dispatch({ type: 2 /* SetButtonId */, buttonId: null }); + }; + }, [id, dispatch, isWithinPanel]); + let handleKeyDown = useEvent((event) => { + var _a3; + if (isWithinPanel) { + if (state.disclosureState === 1 /* Closed */) return; + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* ToggleDisclosure */ }); + (_a3 = state.buttonRef.current) == null + ? void 0 + : _a3.focus(); + break; + } + } else { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* ToggleDisclosure */ }); + break; + } + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + var _a3; + if (isDisabledReactIssue7711(event.currentTarget)) return; + if (props.disabled) return; + if (isWithinPanel) { + dispatch({ type: 0 /* ToggleDisclosure */ }); + (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); + } else { + dispatch({ type: 0 /* ToggleDisclosure */ }); + } + }); + let slot = (0, import_react33.useMemo)( + () => ({ open: state.disclosureState === 0 /* Open */ }), + [state] + ); + let type = useResolveButtonType(props, internalButtonRef); + let ourProps = isWithinPanel + ? { + ref: buttonRef, + type, + onKeyDown: handleKeyDown, + onClick: handleClick, + } + : { + ref: buttonRef, + id, + type, + "aria-expanded": props.disabled + ? void 0 + : state.disclosureState === 0 /* Open */, + "aria-controls": state.linkedPanel ? state.panelId : void 0, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG2, + name: "Disclosure.Button", + }); + } + var DEFAULT_PANEL_TAG2 = "div"; + var PanelRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ + function PanelFn2(props, ref) { + let internalId = useId(); + let { + id = `headlessui-disclosure-panel-${internalId}`, + ...theirProps + } = props; + let [state, dispatch] = useDisclosureContext("Disclosure.Panel"); + let { close } = useDisclosureAPIContext("Disclosure.Panel"); + let panelRef = useSyncRefs(ref, state.panelRef, (el) => { + startTransition(() => + dispatch({ type: el ? 4 /* LinkPanel */ : 5 /* UnlinkPanel */ }) + ); + }); + (0, import_react33.useEffect)(() => { + dispatch({ type: 3 /* SetPanelId */, panelId: id }); + return () => { + dispatch({ type: 3 /* SetPanelId */, panelId: null }); + }; + }, [id, dispatch]); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; + } + return state.disclosureState === 0 /* Open */; + })(); + let slot = (0, import_react33.useMemo)( + () => ({ open: state.disclosureState === 0 /* Open */, close }), + [state, close] + ); + let ourProps = { + ref: panelRef, + id, + }; + return /* @__PURE__ */ import_react33.default.createElement( + DisclosurePanelContext.Provider, + { value: state.panelId }, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG2, + features: PanelRenderFeatures, + visible, + name: "Disclosure.Panel", + }) + ); + } + var DisclosureRoot = forwardRefWithAs(DisclosureFn); + var Button2 = forwardRefWithAs(ButtonFn2); + var Panel2 = forwardRefWithAs(PanelFn2); + var Disclosure = Object.assign(DisclosureRoot, { + Button: Button2, + Panel: Panel2, + }); -// src/hooks/use-server-handoff-complete.ts -var import_react6 = __webpack_require__(/*! react */ "react"); -function useServerHandoffComplete() { - let [complete, setComplete] = (0, import_react6.useState)(env.isHandoffComplete); - if (complete && env.isHandoffComplete === false) { - setComplete(false); - } - (0, import_react6.useEffect)(() => { - if (complete === true) - return; - setComplete(true); - }, [complete]); - (0, import_react6.useEffect)(() => env.handoff(), []); - return complete; -} - -// src/hooks/use-id.ts -var _a; -var useId = ( - // Prefer React's `useId` if it's available. - // @ts-expect-error - `useId` doesn't exist in React < 18. - (_a = import_react7.default.useId) != null ? _a : function useId2() { - let ready = useServerHandoffComplete(); - let [id, setId] = import_react7.default.useState(ready ? () => env.nextId() : null); - useIsoMorphicEffect(() => { - if (id === null) - setId(env.nextId()); - }, [id]); - return id != null ? "" + id : void 0; - } -); + // src/components/listbox/listbox.tsx + var import_react35 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); -// src/hooks/use-outside-click.ts -var import_react10 = __webpack_require__(/*! react */ "react"); + // src/hooks/use-text-value.ts + var import_react34 = __webpack_require__(/*! react */ "react"); + + // src/utils/get-text-value.ts + var emojiRegex = + /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; + function getTextContents(element) { + var _a3, _b; + let currentInnerText = (_a3 = element.innerText) != null ? _a3 : ""; + let copy = element.cloneNode(true); + if (!(copy instanceof HTMLElement)) { + return currentInnerText; + } + let dropped = false; + for (let child of copy.querySelectorAll( + '[hidden],[aria-hidden],[role="img"]' + )) { + child.remove(); + dropped = true; + } + let value = dropped + ? (_b = copy.innerText) != null + ? _b + : "" + : currentInnerText; + if (emojiRegex.test(value)) { + value = value.replace(emojiRegex, ""); + } + return value; + } + function getTextValue(element) { + let label = element.getAttribute("aria-label"); + if (typeof label === "string") return label.trim(); + let labelledby = element.getAttribute("aria-labelledby"); + if (labelledby) { + let labels = labelledby + .split(" ") + .map((labelledby2) => { + let labelEl = document.getElementById(labelledby2); + if (labelEl) { + let label2 = labelEl.getAttribute("aria-label"); + if (typeof label2 === "string") return label2.trim(); + return getTextContents(labelEl).trim(); + } + return null; + }) + .filter(Boolean); + if (labels.length > 0) return labels.join(", "); + } + return getTextContents(element).trim(); + } + + // src/hooks/use-text-value.ts + function useTextValue(element) { + let cacheKey = (0, import_react34.useRef)(""); + let cacheValue = (0, import_react34.useRef)(""); + return useEvent(() => { + let el = element.current; + if (!el) return ""; + let currentKey = el.innerText; + if (cacheKey.current === currentKey) { + return cacheValue.current; + } + let value = getTextValue(el).trim().toLowerCase(); + cacheKey.current = currentKey; + cacheValue.current = value; + return value; + }); + } -// src/utils/match.ts -function match(value, lookup, ...args) { - if (value in lookup) { - let returnValue = lookup[value]; - return typeof returnValue === "function" ? returnValue(...args) : returnValue; - } - let error = new Error( - `Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys( - lookup - ).map((key) => `"${key}"`).join(", ")}.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(error, match); - throw error; -} - -// src/utils/owner.ts -function getOwnerDocument(element) { - if (env.isServer) - return null; - if (element instanceof Node) - return element.ownerDocument; - if (element == null ? void 0 : element.hasOwnProperty("current")) { - if (element.current instanceof Node) - return element.current.ownerDocument; - } - return document; -} - -// src/utils/focus-management.ts -var focusableSelector = [ - "[contentEditable=true]", - "[tabindex]", - "a[href]", - "area[href]", - "button:not([disabled])", - "iframe", - "input:not([disabled])", - "select:not([disabled])", - "textarea:not([disabled])" -].map( - false ? ( - // TODO: Remove this once JSDOM fixes the issue where an element that is - // "hidden" can be the document.activeElement, because this is not possible - // in real browsers. - 0 - ) : (selector) => `${selector}:not([tabindex='-1'])` -).join(","); -function getFocusableElements(container = document.body) { - if (container == null) - return []; - return Array.from(container.querySelectorAll(focusableSelector)).sort( - // We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well. - (a, z) => Math.sign((a.tabIndex || Number.MAX_SAFE_INTEGER) - (z.tabIndex || Number.MAX_SAFE_INTEGER)) - ); -} -function isFocusableElement(element, mode = 0 /* Strict */) { - var _a3; - if (element === ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body)) - return false; - return match(mode, { - [0 /* Strict */]() { - return element.matches(focusableSelector); - }, - [1 /* Loose */]() { - let next = element; - while (next !== null) { - if (next.matches(focusableSelector)) - return true; - next = next.parentElement; - } - return false; - } - }); -} -function restoreFocusIfNecessary(element) { - let ownerDocument = getOwnerDocument(element); - disposables().nextFrame(() => { - if (ownerDocument && !isFocusableElement(ownerDocument.activeElement, 0 /* Strict */)) { - focusElement(element); - } - }); -} -if (typeof window !== "undefined" && typeof document !== "undefined") { - document.addEventListener( - "keydown", - (event) => { - if (event.metaKey || event.altKey || event.ctrlKey) { - return; - } - document.documentElement.dataset.headlessuiFocusVisible = ""; - }, - true - ); - document.addEventListener( - "click", - (event) => { - if (event.detail === 1 /* Mouse */) { - delete document.documentElement.dataset.headlessuiFocusVisible; - } else if (event.detail === 0 /* Keyboard */) { - document.documentElement.dataset.headlessuiFocusVisible = ""; - } - }, - true - ); -} -function focusElement(element) { - element == null ? void 0 : element.focus({ preventScroll: true }); -} -var selectableSelector = ["textarea", "input"].join(","); -function isSelectableElement(element) { - var _a3, _b; - return (_b = (_a3 = element == null ? void 0 : element.matches) == null ? void 0 : _a3.call(element, selectableSelector)) != null ? _b : false; -} -function sortByDomNode(nodes, resolveKey = (i) => i) { - return nodes.slice().sort((aItem, zItem) => { - let a = resolveKey(aItem); - let z = resolveKey(zItem); - if (a === null || z === null) - return 0; - let position = a.compareDocumentPosition(z); - if (position & Node.DOCUMENT_POSITION_FOLLOWING) - return -1; - if (position & Node.DOCUMENT_POSITION_PRECEDING) - return 1; - return 0; - }); -} -function focusFrom(current, focus) { - return focusIn(getFocusableElements(), focus, { relativeTo: current }); -} -function focusIn(container, focus, { - sorted = true, - relativeTo = null, - skipElements = [] -} = {}) { - let ownerDocument = Array.isArray(container) ? container.length > 0 ? container[0].ownerDocument : document : container.ownerDocument; - let elements = Array.isArray(container) ? sorted ? sortByDomNode(container) : container : getFocusableElements(container); - if (skipElements.length > 0 && elements.length > 1) { - elements = elements.filter((x) => !skipElements.includes(x)); - } - relativeTo = relativeTo != null ? relativeTo : ownerDocument.activeElement; - let direction = (() => { - if (focus & (1 /* First */ | 4 /* Next */)) - return 1 /* Next */; - if (focus & (2 /* Previous */ | 8 /* Last */)) - return -1 /* Previous */; - throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); - })(); - let startIndex = (() => { - if (focus & 1 /* First */) - return 0; - if (focus & 2 /* Previous */) - return Math.max(0, elements.indexOf(relativeTo)) - 1; - if (focus & 4 /* Next */) - return Math.max(0, elements.indexOf(relativeTo)) + 1; - if (focus & 8 /* Last */) - return elements.length - 1; - throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); - })(); - let focusOptions = focus & 32 /* NoScroll */ ? { preventScroll: true } : {}; - let offset = 0; - let total = elements.length; - let next = void 0; - do { - if (offset >= total || offset + total <= 0) - return 0 /* Error */; - let nextIdx = startIndex + offset; - if (focus & 16 /* WrapAround */) { - nextIdx = (nextIdx + total) % total; - } else { - if (nextIdx < 0) - return 3 /* Underflow */; - if (nextIdx >= total) - return 1 /* Overflow */; - } - next = elements[nextIdx]; - next == null ? void 0 : next.focus(focusOptions); - offset += direction; - } while (next !== ownerDocument.activeElement); - if (focus & (4 /* Next */ | 2 /* Previous */) && isSelectableElement(next)) { - next.select(); - } - return 2 /* Success */; -} - -// src/hooks/use-document-event.ts -var import_react8 = __webpack_require__(/*! react */ "react"); -function useDocumentEvent(type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react8.useEffect)(() => { - function handler(event) { - listenerRef.current(event); - } - document.addEventListener(type, handler, options); - return () => document.removeEventListener(type, handler, options); - }, [type, options]); -} - -// src/hooks/use-window-event.ts -var import_react9 = __webpack_require__(/*! react */ "react"); -function useWindowEvent(type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react9.useEffect)(() => { - function handler(event) { - listenerRef.current(event); - } - window.addEventListener(type, handler, options); - return () => window.removeEventListener(type, handler, options); - }, [type, options]); -} - -// src/hooks/use-outside-click.ts -function useOutsideClick(containers, cb, enabled = true) { - let enabledRef = (0, import_react10.useRef)(false); - (0, import_react10.useEffect)( - false ? 0 : () => { - requestAnimationFrame(() => { - enabledRef.current = enabled; - }); - }, - [enabled] - ); - function handleOutsideClick(event, resolveTarget) { - if (!enabledRef.current) - return; - if (event.defaultPrevented) - return; - let target = resolveTarget(event); - if (target === null) { - return; - } - if (!target.getRootNode().contains(target)) - return; - let _containers = function resolve(containers2) { - if (typeof containers2 === "function") { - return resolve(containers2()); - } - if (Array.isArray(containers2)) { - return containers2; - } - if (containers2 instanceof Set) { - return containers2; - } - return [containers2]; - }(containers); - for (let container of _containers) { - if (container === null) - continue; - let domNode = container instanceof HTMLElement ? container : container.current; - if (domNode == null ? void 0 : domNode.contains(target)) { - return; - } - if (event.composed && event.composedPath().includes(domNode)) { - return; - } - } - if ( - // This check alllows us to know whether or not we clicked on a "focusable" element like a - // button or an input. This is a backwards compatibility check so that you can open a and click on another which should close Menu A and open Menu B. We might - // revisit that so that you will require 2 clicks instead. - !isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1} to make it - // unfocusable via the keyboard so that tabbing to the next item from the input doesn't - // first go to the button. - target.tabIndex !== -1 - ) { - event.preventDefault(); - } - return cb(event, target); - } - let initialClickTarget = (0, import_react10.useRef)(null); - useDocumentEvent( - "mousedown", - (event) => { - var _a3, _b; - if (enabledRef.current) { - initialClickTarget.current = ((_b = (_a3 = event.composedPath) == null ? void 0 : _a3.call(event)) == null ? void 0 : _b[0]) || event.target; - } - }, - true - ); - useDocumentEvent( - "click", - (event) => { - if (!initialClickTarget.current) { - return; - } - handleOutsideClick(event, () => { - return initialClickTarget.current; - }); - initialClickTarget.current = null; - }, - // We will use the `capture` phase so that layers in between with `event.stopPropagation()` - // don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu` - // is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However, - // the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this. - true - ); - useWindowEvent( - "blur", - (event) => handleOutsideClick( - event, - () => window.document.activeElement instanceof HTMLIFrameElement ? window.document.activeElement : null - ), - true - ); -} - -// src/hooks/use-resolve-button-type.ts -var import_react11 = __webpack_require__(/*! react */ "react"); -function resolveType(props) { - var _a3; - if (props.type) - return props.type; - let tag = (_a3 = props.as) != null ? _a3 : "button"; - if (typeof tag === "string" && tag.toLowerCase() === "button") - return "button"; - return void 0; -} -function useResolveButtonType(props, ref) { - let [type, setType] = (0, import_react11.useState)(() => resolveType(props)); - useIsoMorphicEffect(() => { - setType(resolveType(props)); - }, [props.type, props.as]); - useIsoMorphicEffect(() => { - if (type) - return; - if (!ref.current) - return; - if (ref.current instanceof HTMLButtonElement && !ref.current.hasAttribute("type")) { - setType("button"); - } - }, [type, ref]); - return type; -} - -// src/hooks/use-sync-refs.ts -var import_react12 = __webpack_require__(/*! react */ "react"); -var Optional = Symbol(); -function optionalRef(cb, isOptional = true) { - return Object.assign(cb, { [Optional]: isOptional }); -} -function useSyncRefs(...refs) { - let cache = (0, import_react12.useRef)(refs); - (0, import_react12.useEffect)(() => { - cache.current = refs; - }, [refs]); - let syncRefs = useEvent((value) => { - for (let ref of cache.current) { - if (ref == null) - continue; - if (typeof ref === "function") - ref(value); - else - ref.current = value; - } - }); - return refs.every( - (ref) => ref == null || // @ts-expect-error - (ref == null ? void 0 : ref[Optional]) - ) ? void 0 : syncRefs; -} - -// src/hooks/use-tree-walker.ts -var import_react13 = __webpack_require__(/*! react */ "react"); -function useTreeWalker({ - container, - accept, - walk, - enabled = true -}) { - let acceptRef = (0, import_react13.useRef)(accept); - let walkRef = (0, import_react13.useRef)(walk); - (0, import_react13.useEffect)(() => { - acceptRef.current = accept; - walkRef.current = walk; - }, [accept, walk]); - useIsoMorphicEffect(() => { - if (!container) - return; - if (!enabled) - return; - let ownerDocument = getOwnerDocument(container); - if (!ownerDocument) - return; - let accept2 = acceptRef.current; - let walk2 = walkRef.current; - let acceptNode = Object.assign((node) => accept2(node), { acceptNode: accept2 }); - let walker = ownerDocument.createTreeWalker( - container, - NodeFilter.SHOW_ELEMENT, - acceptNode, - // @ts-expect-error This `false` is a simple small fix for older browsers - false - ); - while (walker.nextNode()) - walk2(walker.currentNode); - }, [container, enabled, acceptRef, walkRef]); -} - -// src/utils/calculate-active-index.ts -function assertNever(x) { - throw new Error("Unexpected object: " + x); -} -function calculateActiveIndex(action, resolvers) { - let items = resolvers.resolveItems(); - if (items.length <= 0) - return null; - let currentActiveIndex = resolvers.resolveActiveIndex(); - let activeIndex = currentActiveIndex != null ? currentActiveIndex : -1; - let nextActiveIndex = (() => { - switch (action.focus) { - case 0 /* First */: - return items.findIndex((item) => !resolvers.resolveDisabled(item)); - case 1 /* Previous */: { - let idx = items.slice().reverse().findIndex((item, idx2, all) => { - if (activeIndex !== -1 && all.length - idx2 - 1 >= activeIndex) - return false; - return !resolvers.resolveDisabled(item); - }); - if (idx === -1) - return idx; - return items.length - 1 - idx; - } - case 2 /* Next */: - return items.findIndex((item, idx) => { - if (idx <= activeIndex) - return false; - return !resolvers.resolveDisabled(item); + // src/components/listbox/listbox.tsx + function adjustOrderedState2(state, adjustment = (i) => i) { + let currentActiveOption = + state.activeOptionIndex !== null + ? state.options[state.activeOptionIndex] + : null; + let sortedOptions = sortByDomNode( + adjustment(state.options.slice()), + (option) => option.dataRef.current.domRef.current + ); + let adjustedActiveOptionIndex = currentActiveOption + ? sortedOptions.indexOf(currentActiveOption) + : null; + if (adjustedActiveOptionIndex === -1) { + adjustedActiveOptionIndex = null; + } + return { + options: sortedOptions, + activeOptionIndex: adjustedActiveOptionIndex, + }; + } + var reducers4 = { + [1 /* CloseListbox */](state) { + if (state.dataRef.current.disabled) return state; + if (state.listboxState === 1 /* Closed */) return state; + return { + ...state, + activeOptionIndex: null, + listboxState: 1 /* Closed */, + }; + }, + [0 /* OpenListbox */](state) { + if (state.dataRef.current.disabled) return state; + if (state.listboxState === 0 /* Open */) return state; + let activeOptionIndex = state.activeOptionIndex; + let { isSelected } = state.dataRef.current; + let optionIdx = state.options.findIndex((option) => + isSelected(option.dataRef.current.value) + ); + if (optionIdx !== -1) { + activeOptionIndex = optionIdx; + } + return { ...state, listboxState: 0 /* Open */, activeOptionIndex }; + }, + [2 /* GoToOption */](state, action) { + var _a3; + if (state.dataRef.current.disabled) return state; + if (state.listboxState === 1 /* Closed */) return state; + let adjustedState = adjustOrderedState2(state); + let activeOptionIndex = calculateActiveIndex(action, { + resolveItems: () => adjustedState.options, + resolveActiveIndex: () => adjustedState.activeOptionIndex, + resolveId: (option) => option.id, + resolveDisabled: (option) => option.dataRef.current.disabled, + }); + return { + ...state, + ...adjustedState, + searchQuery: "", + activeOptionIndex, + activationTrigger: + (_a3 = action.trigger) != null ? _a3 : 1 /* Other */, + }; + }, + [3 /* Search */]: (state, action) => { + if (state.dataRef.current.disabled) return state; + if (state.listboxState === 1 /* Closed */) return state; + let wasAlreadySearching = state.searchQuery !== ""; + let offset = wasAlreadySearching ? 0 : 1; + let searchQuery = state.searchQuery + action.value.toLowerCase(); + let reOrderedOptions = + state.activeOptionIndex !== null + ? state.options + .slice(state.activeOptionIndex + offset) + .concat( + state.options.slice(0, state.activeOptionIndex + offset) + ) + : state.options; + let matchingOption = reOrderedOptions.find((option) => { + var _a3; + return ( + !option.dataRef.current.disabled && + ((_a3 = option.dataRef.current.textValue) == null + ? void 0 + : _a3.startsWith(searchQuery)) + ); + }); + let matchIdx = matchingOption + ? state.options.indexOf(matchingOption) + : -1; + if (matchIdx === -1 || matchIdx === state.activeOptionIndex) + return { ...state, searchQuery }; + return { + ...state, + searchQuery, + activeOptionIndex: matchIdx, + activationTrigger: 1 /* Other */, + }; + }, + [4 /* ClearSearch */](state) { + if (state.dataRef.current.disabled) return state; + if (state.listboxState === 1 /* Closed */) return state; + if (state.searchQuery === "") return state; + return { ...state, searchQuery: "" }; + }, + [5 /* RegisterOption */]: (state, action) => { + let option = { id: action.id, dataRef: action.dataRef }; + let adjustedState = adjustOrderedState2(state, (options) => [ + ...options, + option, + ]); + if (state.activeOptionIndex === null) { + if ( + state.dataRef.current.isSelected(action.dataRef.current.value) + ) { + adjustedState.activeOptionIndex = + adjustedState.options.indexOf(option); + } + } + return { ...state, ...adjustedState }; + }, + [6 /* UnregisterOption */]: (state, action) => { + let adjustedState = adjustOrderedState2(state, (options) => { + let idx = options.findIndex((a) => a.id === action.id); + if (idx !== -1) options.splice(idx, 1); + return options; + }); + return { + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */, + }; + }, + [7 /* RegisterLabel */]: (state, action) => { + return { + ...state, + labelId: action.id, + }; + }, + }; + var ListboxActionsContext = (0, import_react35.createContext)(null); + ListboxActionsContext.displayName = "ListboxActionsContext"; + function useActions2(component) { + let context = (0, import_react35.useContext)(ListboxActionsContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useActions2); + throw err; + } + return context; + } + var ListboxDataContext = (0, import_react35.createContext)(null); + ListboxDataContext.displayName = "ListboxDataContext"; + function useData2(component) { + let context = (0, import_react35.useContext)(ListboxDataContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) Error.captureStackTrace(err, useData2); + throw err; + } + return context; + } + function stateReducer4(state, action) { + return match(action.type, reducers4, state, action); + } + var DEFAULT_LISTBOX_TAG = import_react35.Fragment; + function ListboxFn(props, ref) { + let { + value: controlledValue, + defaultValue, + form: formName, + name, + onChange: controlledOnChange, + by = (a, z) => a === z, + disabled = false, + horizontal = false, + multiple = false, + ...theirProps + } = props; + const orientation = horizontal ? "horizontal" : "vertical"; + let listboxRef = useSyncRefs(ref); + let [value = multiple ? [] : void 0, theirOnChange] = useControllable( + controlledValue, + controlledOnChange, + defaultValue + ); + let [state, dispatch] = (0, import_react35.useReducer)( + stateReducer4, + { + dataRef: (0, import_react35.createRef)(), + listboxState: 1 /* Closed */, + options: [], + searchQuery: "", + labelId: null, + activeOptionIndex: null, + activationTrigger: 1 /* Other */, + } + ); + let optionsPropsRef = (0, import_react35.useRef)({ + static: false, + hold: false, + }); + let labelRef = (0, import_react35.useRef)(null); + let buttonRef = (0, import_react35.useRef)(null); + let optionsRef = (0, import_react35.useRef)(null); + let compare = useEvent( + typeof by === "string" + ? (a, z) => { + let property = by; + return ( + (a == null ? void 0 : a[property]) === + (z == null ? void 0 : z[property]) + ); + } + : by + ); + let isSelected = (0, import_react35.useCallback)( + (compareValue) => + match(data.mode, { + [1 /* Multi */]: () => + value.some((option) => compare(option, compareValue)), + [0 /* Single */]: () => compare(value, compareValue), + }), + [value] + ); + let data = (0, import_react35.useMemo)( + () => ({ + ...state, + value, + disabled, + mode: multiple ? 1 /* Multi */ : 0 /* Single */, + orientation, + compare, + isSelected, + optionsPropsRef, + labelRef, + buttonRef, + optionsRef, + }), + [value, disabled, multiple, state] + ); + useIsoMorphicEffect(() => { + state.dataRef.current = data; + }, [data]); + useOutsideClick( + [data.buttonRef, data.optionsRef], + (event, target) => { + var _a3; + dispatch({ type: 1 /* CloseListbox */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus(); + } + }, + data.listboxState === 0 /* Open */ + ); + let slot = (0, import_react35.useMemo)( + () => ({ + open: data.listboxState === 0 /* Open */, + disabled, + value, + }), + [data, disabled, value] + ); + let selectOption = useEvent((id) => { + let option = data.options.find((item) => item.id === id); + if (!option) return; + onChange(option.dataRef.current.value); + }); + let selectActiveOption = useEvent(() => { + if (data.activeOptionIndex !== null) { + let { dataRef, id } = data.options[data.activeOptionIndex]; + onChange(dataRef.current.value); + dispatch({ + type: 2 /* GoToOption */, + focus: 4 /* Specific */, + id, + }); + } + }); + let openListbox = useEvent(() => + dispatch({ type: 0 /* OpenListbox */ }) + ); + let closeListbox = useEvent(() => + dispatch({ type: 1 /* CloseListbox */ }) + ); + let goToOption = useEvent((focus, id, trigger) => { + if (focus === 4 /* Specific */) { + return dispatch({ + type: 2 /* GoToOption */, + focus: 4 /* Specific */, + id, + trigger, + }); + } + return dispatch({ type: 2 /* GoToOption */, focus, trigger }); + }); + let registerOption = useEvent((id, dataRef) => { + dispatch({ type: 5 /* RegisterOption */, id, dataRef }); + return () => dispatch({ type: 6 /* UnregisterOption */, id }); + }); + let registerLabel = useEvent((id) => { + dispatch({ type: 7 /* RegisterLabel */, id }); + return () => dispatch({ type: 7 /* RegisterLabel */, id: null }); + }); + let onChange = useEvent((value2) => { + return match(data.mode, { + [0 /* Single */]() { + return theirOnChange == null ? void 0 : theirOnChange(value2); + }, + [1 /* Multi */]() { + let copy = data.value.slice(); + let idx = copy.findIndex((item) => compare(item, value2)); + if (idx === -1) { + copy.push(value2); + } else { + copy.splice(idx, 1); + } + return theirOnChange == null ? void 0 : theirOnChange(copy); + }, + }); + }); + let search = useEvent((value2) => + dispatch({ type: 3 /* Search */, value: value2 }) + ); + let clearSearch = useEvent(() => + dispatch({ type: 4 /* ClearSearch */ }) + ); + let actions = (0, import_react35.useMemo)( + () => ({ + onChange, + registerOption, + registerLabel, + goToOption, + closeListbox, + openListbox, + selectActiveOption, + selectOption, + search, + clearSearch, + }), + [] + ); + let ourProps = { ref: listboxRef }; + let form = (0, import_react35.useRef)(null); + let d = useDisposables(); + (0, import_react35.useEffect)(() => { + if (!form.current) return; + if (defaultValue === void 0) return; + d.addEventListener(form.current, "reset", () => { + onChange(defaultValue); + }); + }, [ + form, + onChange, + /* Explicitly ignoring `defaultValue` */ + ]); + return /* @__PURE__ */ import_react35.default.createElement( + ListboxActionsContext.Provider, + { value: actions }, + /* @__PURE__ */ import_react35.default.createElement( + ListboxDataContext.Provider, + { value: data }, + /* @__PURE__ */ import_react35.default.createElement( + OpenClosedProvider, + { + value: match(data.listboxState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */, + }), + }, + name != null && + value != null && + objectToFormEntries({ [name]: value }).map( + ([name2, value2], idx) => + /* @__PURE__ */ import_react35.default.createElement( + Hidden, + { + features: 4 /* Hidden */, + ref: + idx === 0 + ? (element) => { + var _a3; + form.current = + (_a3 = + element == null + ? void 0 + : element.closest("form")) != null + ? _a3 + : null; + } + : void 0, + ...compact({ + key: name2, + as: "input", + type: "hidden", + hidden: true, + readOnly: true, + form: formName, + name: name2, + value: value2, + }), + } + ) + ), + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_LISTBOX_TAG, + name: "Listbox", + }) + ) + ) + ); + } + var DEFAULT_BUTTON_TAG3 = "button"; + function ButtonFn3(props, ref) { + var _a3; + let internalId = useId(); + let { + id = `headlessui-listbox-button-${internalId}`, + ...theirProps + } = props; + let data = useData2("Listbox.Button"); + let actions = useActions2("Listbox.Button"); + let buttonRef = useSyncRefs(data.buttonRef, ref); + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + actions.openListbox(); + d.nextFrame(() => { + if (!data.value) actions.goToOption(0 /* First */); + }); + break; + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + actions.openListbox(); + d.nextFrame(() => { + if (!data.value) actions.goToOption(3 /* Last */); + }); + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (data.listboxState === 0 /* Open */) { + actions.closeListbox(); + d.nextFrame(() => { + var _a4; + return (_a4 = data.buttonRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + } else { + event.preventDefault(); + actions.openListbox(); + } + }); + let labelledby = useComputed(() => { + if (!data.labelId) return void 0; + return [data.labelId, id].join(" "); + }, [data.labelId, id]); + let slot = (0, import_react35.useMemo)( + () => ({ + open: data.listboxState === 0 /* Open */, + disabled: data.disabled, + value: data.value, + }), + [data] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, data.buttonRef), + "aria-haspopup": "listbox", + "aria-controls": + (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": data.disabled + ? void 0 + : data.listboxState === 0 /* Open */, + "aria-labelledby": labelledby, + disabled: data.disabled, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG3, + name: "Listbox.Button", + }); + } + var DEFAULT_LABEL_TAG2 = "label"; + function LabelFn2(props, ref) { + let internalId = useId(); + let { id = `headlessui-listbox-label-${internalId}`, ...theirProps } = + props; + let data = useData2("Listbox.Label"); + let actions = useActions2("Listbox.Label"); + let labelRef = useSyncRefs(data.labelRef, ref); + useIsoMorphicEffect(() => actions.registerLabel(id), [id]); + let handleClick = useEvent(() => { + var _a3; + return (_a3 = data.buttonRef.current) == null + ? void 0 + : _a3.focus({ preventScroll: true }); + }); + let slot = (0, import_react35.useMemo)( + () => ({ + open: data.listboxState === 0 /* Open */, + disabled: data.disabled, + }), + [data] + ); + let ourProps = { ref: labelRef, id, onClick: handleClick }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_LABEL_TAG2, + name: "Listbox.Label", + }); + } + var DEFAULT_OPTIONS_TAG2 = "ul"; + var OptionsRenderFeatures2 = 1 /* RenderStrategy */ | 2; /* Static */ + function OptionsFn2(props, ref) { + var _a3; + let internalId = useId(); + let { + id = `headlessui-listbox-options-${internalId}`, + ...theirProps + } = props; + let data = useData2("Listbox.Options"); + let actions = useActions2("Listbox.Options"); + let optionsRef = useSyncRefs(data.optionsRef, ref); + let d = useDisposables(); + let searchDisposables = useDisposables(); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; + } + return data.listboxState === 0 /* Open */; + })(); + (0, import_react35.useEffect)(() => { + var _a4; + let container = data.optionsRef.current; + if (!container) return; + if (data.listboxState !== 0 /* Open */) return; + if ( + container === + ((_a4 = getOwnerDocument(container)) == null + ? void 0 + : _a4.activeElement) + ) + return; + container.focus({ preventScroll: true }); + }, [data.listboxState, data.optionsRef]); + let handleKeyDown = useEvent((event) => { + searchDisposables.dispose(); + switch (event.key) { + case " " /* Space */: + if (data.searchQuery !== "") { + event.preventDefault(); + event.stopPropagation(); + return actions.search(event.key); + } + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + if (data.activeOptionIndex !== null) { + let { dataRef } = data.options[data.activeOptionIndex]; + actions.onChange(dataRef.current.value); + } + if (data.mode === 0 /* Single */) { + actions.closeListbox(); + disposables().nextFrame(() => { + var _a4; + return (_a4 = data.buttonRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + } + break; + case match(data.orientation, { + vertical: "ArrowDown" /* ArrowDown */, + horizontal: "ArrowRight" /* ArrowRight */, + }): + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(2 /* Next */); + case match(data.orientation, { + vertical: "ArrowUp" /* ArrowUp */, + horizontal: "ArrowLeft" /* ArrowLeft */, + }): + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(1 /* Previous */); + case "Home" /* Home */: + case "PageUp" /* PageUp */: + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(0 /* First */); + case "End" /* End */: + case "PageDown" /* PageDown */: + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(3 /* Last */); + case "Escape" /* Escape */: + event.preventDefault(); + event.stopPropagation(); + actions.closeListbox(); + return d.nextFrame(() => { + var _a4; + return (_a4 = data.buttonRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + case "Tab" /* Tab */: + event.preventDefault(); + event.stopPropagation(); + break; + default: + if (event.key.length === 1) { + actions.search(event.key); + searchDisposables.setTimeout( + () => actions.clearSearch(), + 350 + ); + } + break; + } + }); + let labelledby = useComputed(() => { + var _a4, _b, _c; + return (_c = + (_a4 = data.labelRef.current) == null ? void 0 : _a4.id) != null + ? _c + : (_b = data.buttonRef.current) == null + ? void 0 + : _b.id; + }, [data.labelRef.current, data.buttonRef.current]); + let slot = (0, import_react35.useMemo)( + () => ({ open: data.listboxState === 0 /* Open */ }), + [data] + ); + let ourProps = { + "aria-activedescendant": + data.activeOptionIndex === null + ? void 0 + : (_a3 = data.options[data.activeOptionIndex]) == null + ? void 0 + : _a3.id, + "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, + "aria-labelledby": labelledby, + "aria-orientation": data.orientation, + id, + onKeyDown: handleKeyDown, + role: "listbox", + tabIndex: 0, + ref: optionsRef, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTIONS_TAG2, + features: OptionsRenderFeatures2, + visible, + name: "Listbox.Options", + }); + } + var DEFAULT_OPTION_TAG2 = "li"; + function OptionFn2(props, ref) { + let internalId = useId(); + let { + id = `headlessui-listbox-option-${internalId}`, + disabled = false, + value, + ...theirProps + } = props; + let data = useData2("Listbox.Option"); + let actions = useActions2("Listbox.Option"); + let active = + data.activeOptionIndex !== null + ? data.options[data.activeOptionIndex].id === id + : false; + let selected = data.isSelected(value); + let internalOptionRef = (0, import_react35.useRef)(null); + let getTextValue2 = useTextValue(internalOptionRef); + let bag = useLatestValue({ + disabled, + value, + domRef: internalOptionRef, + get textValue() { + return getTextValue2(); + }, + }); + let optionRef = useSyncRefs(ref, internalOptionRef); + useIsoMorphicEffect(() => { + if (data.listboxState !== 0 /* Open */) return; + if (!active) return; + if (data.activationTrigger === 0 /* Pointer */) return; + let d = disposables(); + d.requestAnimationFrame(() => { + var _a3, _b; + (_b = + (_a3 = internalOptionRef.current) == null + ? void 0 + : _a3.scrollIntoView) == null + ? void 0 + : _b.call(_a3, { block: "nearest" }); + }); + return d.dispose; + }, [ + internalOptionRef, + active, + data.listboxState, + data.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + data.activeOptionIndex, + ]); + useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); + let handleClick = useEvent((event) => { + if (disabled) return event.preventDefault(); + actions.onChange(value); + if (data.mode === 0 /* Single */) { + actions.closeListbox(); + disposables().nextFrame(() => { + var _a3; + return (_a3 = data.buttonRef.current) == null + ? void 0 + : _a3.focus({ preventScroll: true }); + }); + } + }); + let handleFocus = useEvent(() => { + if (disabled) return actions.goToOption(5 /* Nothing */); + actions.goToOption(4 /* Specific */, id); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) return; + if (disabled) return; + if (active) return; + actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) return; + if (disabled) return; + if (!active) return; + actions.goToOption(5 /* Nothing */); + }); + let slot = (0, import_react35.useMemo)( + () => ({ active, selected, disabled }), + [active, selected, disabled] + ); + let ourProps = { + id, + ref: optionRef, + role: "option", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + // According to the WAI-ARIA best practices, we should use aria-checked for + // multi-select,but Voice-Over disagrees. So we use aria-checked instead for + // both single and multi-select. + "aria-selected": selected, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTION_TAG2, + name: "Listbox.Option", + }); + } + var ListboxRoot = forwardRefWithAs(ListboxFn); + var Button3 = forwardRefWithAs(ButtonFn3); + var Label2 = forwardRefWithAs(LabelFn2); + var Options2 = forwardRefWithAs(OptionsFn2); + var Option2 = forwardRefWithAs(OptionFn2); + var Listbox = Object.assign(ListboxRoot, { + Button: Button3, + Label: Label2, + Options: Options2, + Option: Option2, }); - case 3 /* Last */: { - let idx = items.slice().reverse().findIndex((item) => !resolvers.resolveDisabled(item)); - if (idx === -1) - return idx; - return items.length - 1 - idx; - } - case 4 /* Specific */: - return items.findIndex((item) => resolvers.resolveId(item) === action.id); - case 5 /* Nothing */: - return null; - default: - assertNever(action); - } - })(); - return nextActiveIndex === -1 ? currentActiveIndex : nextActiveIndex; -} - -// src/utils/render.ts -var import_react14 = __webpack_require__(/*! react */ "react"); - -// src/utils/class-names.ts -function classNames(...classes) { - return classes.filter(Boolean).join(" "); -} - -// src/utils/render.ts -function render({ - ourProps, - theirProps, - slot, - defaultTag, - features, - visible = true, - name -}) { - let props = mergeProps(theirProps, ourProps); - if (visible) - return _render(props, slot, defaultTag, name); - let featureFlags = features != null ? features : 0 /* None */; - if (featureFlags & 2 /* Static */) { - let { static: isStatic = false, ...rest } = props; - if (isStatic) - return _render(rest, slot, defaultTag, name); - } - if (featureFlags & 1 /* RenderStrategy */) { - let { unmount = true, ...rest } = props; - let strategy = unmount ? 0 /* Unmount */ : 1 /* Hidden */; - return match(strategy, { - [0 /* Unmount */]() { - return null; - }, - [1 /* Hidden */]() { - return _render( - { ...rest, ...{ hidden: true, style: { display: "none" } } }, - slot, - defaultTag, - name - ); - } - }); - } - return _render(props, slot, defaultTag, name); -} -function _render(props, slot = {}, tag, name) { - let { - as: Component = tag, - children, - refName = "ref", - ...rest - } = omit(props, ["unmount", "static"]); - let refRelatedProps = props.ref !== void 0 ? { [refName]: props.ref } : {}; - let resolvedChildren = typeof children === "function" ? children(slot) : children; - if ("className" in rest && rest.className && typeof rest.className === "function") { - rest.className = rest.className(slot); - } - let dataAttributes = {}; - if (slot) { - let exposeState = false; - let states = []; - for (let [k, v] of Object.entries(slot)) { - if (typeof v === "boolean") { - exposeState = true; - } - if (v === true) { - states.push(k); - } - } - if (exposeState) - dataAttributes[`data-headlessui-state`] = states.join(" "); - } - if (Component === import_react14.Fragment) { - if (Object.keys(compact(rest)).length > 0) { - if (!(0, import_react14.isValidElement)(resolvedChildren) || Array.isArray(resolvedChildren) && resolvedChildren.length > 1) { - throw new Error( - [ - 'Passing props on "Fragment"!', - "", - `The current component <${name} /> is rendering a "Fragment".`, - `However we need to passthrough the following props:`, - Object.keys(rest).map((line) => ` - ${line}`).join("\n"), - "", - "You can apply a few solutions:", - [ - 'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', - "Render a single element as the child so that we can forward the props onto that element." - ].map((line) => ` - ${line}`).join("\n") - ].join("\n") + + // src/components/menu/menu.tsx + var import_react36 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 ); - } - let childProps = resolvedChildren.props; - let newClassName = typeof (childProps == null ? void 0 : childProps.className) === "function" ? (...args) => classNames(childProps == null ? void 0 : childProps.className(...args), rest.className) : classNames(childProps == null ? void 0 : childProps.className, rest.className); - let classNameProps = newClassName ? { className: newClassName } : {}; - return (0, import_react14.cloneElement)( - resolvedChildren, - Object.assign( - {}, - // Filter out undefined values so that they don't override the existing values - mergeProps(resolvedChildren.props, compact(omit(rest, ["ref"]))), - dataAttributes, - refRelatedProps, - mergeRefs(resolvedChildren.ref, refRelatedProps.ref), - classNameProps - ) - ); - } - } - return (0, import_react14.createElement)( - Component, - Object.assign( - {}, - omit(rest, ["ref"]), - Component !== import_react14.Fragment && refRelatedProps, - Component !== import_react14.Fragment && dataAttributes - ), - resolvedChildren - ); -} -function mergeRefs(...refs) { - return { - ref: refs.every((ref) => ref == null) ? void 0 : (value) => { - for (let ref of refs) { - if (ref == null) - continue; - if (typeof ref === "function") - ref(value); - else - ref.current = value; - } - } - }; -} -function mergeProps(...listOfProps) { - var _a3; - if (listOfProps.length === 0) - return {}; - if (listOfProps.length === 1) - return listOfProps[0]; - let target = {}; - let eventHandlers = {}; - for (let props of listOfProps) { - for (let prop in props) { - if (prop.startsWith("on") && typeof props[prop] === "function") { - (_a3 = eventHandlers[prop]) != null ? _a3 : eventHandlers[prop] = []; - eventHandlers[prop].push(props[prop]); - } else { - target[prop] = props[prop]; - } - } - } - if (target.disabled || target["aria-disabled"]) { - return Object.assign( - target, - // Set all event listeners that we collected to `undefined`. This is - // important because of the `cloneElement` from above, which merges the - // existing and new props, they don't just override therefore we have to - // explicitly nullify them. - Object.fromEntries(Object.keys(eventHandlers).map((eventName) => [eventName, void 0])) - ); - } - for (let eventName in eventHandlers) { - Object.assign(target, { - [eventName](event, ...args) { - let handlers = eventHandlers[eventName]; - for (let handler of handlers) { - if ((event instanceof Event || (event == null ? void 0 : event.nativeEvent) instanceof Event) && event.defaultPrevented) { - return; + function adjustOrderedState3(state, adjustment = (i) => i) { + let currentActiveItem = + state.activeItemIndex !== null + ? state.items[state.activeItemIndex] + : null; + let sortedItems = sortByDomNode( + adjustment(state.items.slice()), + (item) => item.dataRef.current.domRef.current + ); + let adjustedActiveItemIndex = currentActiveItem + ? sortedItems.indexOf(currentActiveItem) + : null; + if (adjustedActiveItemIndex === -1) { + adjustedActiveItemIndex = null; } - handler(event, ...args); + return { + items: sortedItems, + activeItemIndex: adjustedActiveItemIndex, + }; } - } - }); - } - return target; -} -function forwardRefWithAs(component) { - var _a3; - return Object.assign((0, import_react14.forwardRef)(component), { - displayName: (_a3 = component.displayName) != null ? _a3 : component.name - }); -} -function compact(object) { - let clone = Object.assign({}, object); - for (let key in clone) { - if (clone[key] === void 0) - delete clone[key]; - } - return clone; -} -function omit(object, keysToOmit = []) { - let clone = Object.assign({}, object); - for (let key of keysToOmit) { - if (key in clone) - delete clone[key]; - } - return clone; -} - -// src/utils/bugs.ts -function isDisabledReactIssue7711(element) { - let parent = element.parentElement; - let legend = null; - while (parent && !(parent instanceof HTMLFieldSetElement)) { - if (parent instanceof HTMLLegendElement) - legend = parent; - parent = parent.parentElement; - } - let isParentDisabled = (parent == null ? void 0 : parent.getAttribute("disabled")) === ""; - if (isParentDisabled && isFirstLegend(legend)) - return false; - return isParentDisabled; -} -function isFirstLegend(element) { - if (!element) - return false; - let previous = element.previousElementSibling; - while (previous !== null) { - if (previous instanceof HTMLLegendElement) - return false; - previous = previous.previousElementSibling; - } - return true; -} + var reducers5 = { + [1 /* CloseMenu */](state) { + if (state.menuState === 1 /* Closed */) return state; + return { + ...state, + activeItemIndex: null, + menuState: 1 /* Closed */, + }; + }, + [0 /* OpenMenu */](state) { + if (state.menuState === 0 /* Open */) return state; + return { + ...state, + /* We can turn off demo mode once we re-open the `Menu` */ + __demoMode: false, + menuState: 0 /* Open */, + }; + }, + [2 /* GoToItem */]: (state, action) => { + var _a3; + let adjustedState = adjustOrderedState3(state); + let activeItemIndex = calculateActiveIndex(action, { + resolveItems: () => adjustedState.items, + resolveActiveIndex: () => adjustedState.activeItemIndex, + resolveId: (item) => item.id, + resolveDisabled: (item) => item.dataRef.current.disabled, + }); + return { + ...state, + ...adjustedState, + searchQuery: "", + activeItemIndex, + activationTrigger: + (_a3 = action.trigger) != null ? _a3 : 1 /* Other */, + }; + }, + [3 /* Search */]: (state, action) => { + let wasAlreadySearching = state.searchQuery !== ""; + let offset = wasAlreadySearching ? 0 : 1; + let searchQuery = state.searchQuery + action.value.toLowerCase(); + let reOrderedItems = + state.activeItemIndex !== null + ? state.items + .slice(state.activeItemIndex + offset) + .concat( + state.items.slice(0, state.activeItemIndex + offset) + ) + : state.items; + let matchingItem = reOrderedItems.find((item) => { + var _a3; + return ( + ((_a3 = item.dataRef.current.textValue) == null + ? void 0 + : _a3.startsWith(searchQuery)) && + !item.dataRef.current.disabled + ); + }); + let matchIdx = matchingItem + ? state.items.indexOf(matchingItem) + : -1; + if (matchIdx === -1 || matchIdx === state.activeItemIndex) + return { ...state, searchQuery }; + return { + ...state, + searchQuery, + activeItemIndex: matchIdx, + activationTrigger: 1 /* Other */, + }; + }, + [4 /* ClearSearch */](state) { + if (state.searchQuery === "") return state; + return { ...state, searchQuery: "", searchActiveItemIndex: null }; + }, + [5 /* RegisterItem */]: (state, action) => { + let adjustedState = adjustOrderedState3(state, (items) => [ + ...items, + { id: action.id, dataRef: action.dataRef }, + ]); + return { ...state, ...adjustedState }; + }, + [6 /* UnregisterItem */]: (state, action) => { + let adjustedState = adjustOrderedState3(state, (items) => { + let idx = items.findIndex((a) => a.id === action.id); + if (idx !== -1) items.splice(idx, 1); + return items; + }); + return { + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */, + }; + }, + }; + var MenuContext = (0, import_react36.createContext)(null); + MenuContext.displayName = "MenuContext"; + function useMenuContext(component) { + let context = (0, import_react36.useContext)(MenuContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useMenuContext); + throw err; + } + return context; + } + function stateReducer5(state, action) { + return match(action.type, reducers5, state, action); + } + var DEFAULT_MENU_TAG = import_react36.Fragment; + function MenuFn(props, ref) { + let { __demoMode = false, ...theirProps } = props; + let reducerBag = (0, import_react36.useReducer)(stateReducer5, { + __demoMode, + menuState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + buttonRef: (0, import_react36.createRef)(), + itemsRef: (0, import_react36.createRef)(), + items: [], + searchQuery: "", + activeItemIndex: null, + activationTrigger: 1 /* Other */, + }); + let [{ menuState, itemsRef, buttonRef }, dispatch] = reducerBag; + let menuRef = useSyncRefs(ref); + useOutsideClick( + [buttonRef, itemsRef], + (event, target) => { + var _a3; + dispatch({ type: 1 /* CloseMenu */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + (_a3 = buttonRef.current) == null ? void 0 : _a3.focus(); + } + }, + menuState === 0 /* Open */ + ); + let close = useEvent(() => { + dispatch({ type: 1 /* CloseMenu */ }); + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: menuState === 0 /* Open */, close }), + [menuState, close] + ); + let ourProps = { ref: menuRef }; + return /* @__PURE__ */ import_react36.default.createElement( + MenuContext.Provider, + { value: reducerBag }, + /* @__PURE__ */ import_react36.default.createElement( + OpenClosedProvider, + { + value: match(menuState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */, + }), + }, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_MENU_TAG, + name: "Menu", + }) + ) + ); + } + var DEFAULT_BUTTON_TAG4 = "button"; + function ButtonFn4(props, ref) { + var _a3; + let internalId = useId(); + let { id = `headlessui-menu-button-${internalId}`, ...theirProps } = + props; + let [state, dispatch] = useMenuContext("Menu.Button"); + let buttonRef = useSyncRefs(state.buttonRef, ref); + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* OpenMenu */ }); + d.nextFrame(() => + dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ }) + ); + break; + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* OpenMenu */ }); + d.nextFrame(() => + dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ }) + ); + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (props.disabled) return; + if (state.menuState === 0 /* Open */) { + dispatch({ type: 1 /* CloseMenu */ }); + d.nextFrame(() => { + var _a4; + return (_a4 = state.buttonRef.current) == null + ? void 0 + : _a4.focus({ preventScroll: true }); + }); + } else { + event.preventDefault(); + dispatch({ type: 0 /* OpenMenu */ }); + } + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: state.menuState === 0 /* Open */ }), + [state] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, state.buttonRef), + "aria-haspopup": "menu", + "aria-controls": + (_a3 = state.itemsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": props.disabled + ? void 0 + : state.menuState === 0 /* Open */, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG4, + name: "Menu.Button", + }); + } + var DEFAULT_ITEMS_TAG = "div"; + var ItemsRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ + function ItemsFn(props, ref) { + var _a3, _b; + let internalId = useId(); + let { id = `headlessui-menu-items-${internalId}`, ...theirProps } = + props; + let [state, dispatch] = useMenuContext("Menu.Items"); + let itemsRef = useSyncRefs(state.itemsRef, ref); + let ownerDocument = useOwnerDocument(state.itemsRef); + let searchDisposables = useDisposables(); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; + } + return state.menuState === 0 /* Open */; + })(); + (0, import_react36.useEffect)(() => { + let container = state.itemsRef.current; + if (!container) return; + if (state.menuState !== 0 /* Open */) return; + if ( + container === + (ownerDocument == null ? void 0 : ownerDocument.activeElement) + ) + return; + container.focus({ preventScroll: true }); + }, [state.menuState, state.itemsRef, ownerDocument]); + useTreeWalker({ + container: state.itemsRef.current, + enabled: state.menuState === 0 /* Open */, + accept(node) { + if (node.getAttribute("role") === "menuitem") + return NodeFilter.FILTER_REJECT; + if (node.hasAttribute("role")) return NodeFilter.FILTER_SKIP; + return NodeFilter.FILTER_ACCEPT; + }, + walk(node) { + node.setAttribute("role", "none"); + }, + }); + let handleKeyDown = useEvent((event) => { + var _a4, _b2; + searchDisposables.dispose(); + switch (event.key) { + case " " /* Space */: + if (state.searchQuery !== "") { + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 3 /* Search */, value: event.key }); + } + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + if (state.activeItemIndex !== null) { + let { dataRef } = state.items[state.activeItemIndex]; + (_b2 = + (_a4 = dataRef.current) == null + ? void 0 + : _a4.domRef.current) == null + ? void 0 + : _b2.click(); + } + restoreFocusIfNecessary(state.buttonRef.current); + break; + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ + type: 2 /* GoToItem */, + focus: 2 /* Next */, + }); + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ + type: 2 /* GoToItem */, + focus: 1 /* Previous */, + }); + case "Home" /* Home */: + case "PageUp" /* PageUp */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ + type: 2 /* GoToItem */, + focus: 0 /* First */, + }); + case "End" /* End */: + case "PageDown" /* PageDown */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ + type: 2 /* GoToItem */, + focus: 3 /* Last */, + }); + case "Escape" /* Escape */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + disposables().nextFrame(() => { + var _a5; + return (_a5 = state.buttonRef.current) == null + ? void 0 + : _a5.focus({ preventScroll: true }); + }); + break; + case "Tab" /* Tab */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + disposables().nextFrame(() => { + focusFrom( + state.buttonRef.current, + event.shiftKey ? 2 /* Previous */ : 4 /* Next */ + ); + }); + break; + default: + if (event.key.length === 1) { + dispatch({ type: 3 /* Search */, value: event.key }); + searchDisposables.setTimeout( + () => dispatch({ type: 4 /* ClearSearch */ }), + 350 + ); + } + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: state.menuState === 0 /* Open */ }), + [state] + ); + let ourProps = { + "aria-activedescendant": + state.activeItemIndex === null + ? void 0 + : (_a3 = state.items[state.activeItemIndex]) == null + ? void 0 + : _a3.id, + "aria-labelledby": + (_b = state.buttonRef.current) == null ? void 0 : _b.id, + id, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + role: "menu", + tabIndex: 0, + ref: itemsRef, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_ITEMS_TAG, + features: ItemsRenderFeatures, + visible, + name: "Menu.Items", + }); + } + var DEFAULT_ITEM_TAG = import_react36.Fragment; + function ItemFn(props, ref) { + let internalId = useId(); + let { + id = `headlessui-menu-item-${internalId}`, + disabled = false, + ...theirProps + } = props; + let [state, dispatch] = useMenuContext("Menu.Item"); + let active = + state.activeItemIndex !== null + ? state.items[state.activeItemIndex].id === id + : false; + let internalItemRef = (0, import_react36.useRef)(null); + let itemRef = useSyncRefs(ref, internalItemRef); + useIsoMorphicEffect(() => { + if (state.__demoMode) return; + if (state.menuState !== 0 /* Open */) return; + if (!active) return; + if (state.activationTrigger === 0 /* Pointer */) return; + let d = disposables(); + d.requestAnimationFrame(() => { + var _a3, _b; + (_b = + (_a3 = internalItemRef.current) == null + ? void 0 + : _a3.scrollIntoView) == null + ? void 0 + : _b.call(_a3, { block: "nearest" }); + }); + return d.dispose; + }, [ + state.__demoMode, + internalItemRef, + active, + state.menuState, + state.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + state.activeItemIndex, + ]); + let getTextValue2 = useTextValue(internalItemRef); + let bag = (0, import_react36.useRef)({ + disabled, + domRef: internalItemRef, + get textValue() { + return getTextValue2(); + }, + }); + useIsoMorphicEffect(() => { + bag.current.disabled = disabled; + }, [bag, disabled]); + useIsoMorphicEffect(() => { + dispatch({ type: 5 /* RegisterItem */, id, dataRef: bag }); + return () => dispatch({ type: 6 /* UnregisterItem */, id }); + }, [bag, id]); + let close = useEvent(() => { + dispatch({ type: 1 /* CloseMenu */ }); + }); + let handleClick = useEvent((event) => { + if (disabled) return event.preventDefault(); + dispatch({ type: 1 /* CloseMenu */ }); + restoreFocusIfNecessary(state.buttonRef.current); + }); + let handleFocus = useEvent(() => { + if (disabled) + return dispatch({ + type: 2 /* GoToItem */, + focus: 5 /* Nothing */, + }); + dispatch({ type: 2 /* GoToItem */, focus: 4 /* Specific */, id }); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) return; + if (disabled) return; + if (active) return; + dispatch({ + type: 2 /* GoToItem */, + focus: 4 /* Specific */, + id, + trigger: 0 /* Pointer */, + }); + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) return; + if (disabled) return; + if (!active) return; + dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); + }); + let slot = (0, import_react36.useMemo)( + () => ({ active, disabled, close }), + [active, disabled, close] + ); + let ourProps = { + id, + ref: itemRef, + role: "menuitem", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_ITEM_TAG, + name: "Menu.Item", + }); + } + var MenuRoot = forwardRefWithAs(MenuFn); + var Button4 = forwardRefWithAs(ButtonFn4); + var Items = forwardRefWithAs(ItemsFn); + var Item = forwardRefWithAs(ItemFn); + var Menu = Object.assign(MenuRoot, { Button: Button4, Items, Item }); -// src/utils/form.ts -function objectToFormEntries(source = {}, parentKey = null, entries = []) { - for (let [key, value] of Object.entries(source)) { - append(entries, composeKey(parentKey, key), value); - } - return entries; -} -function composeKey(parent, key) { - return parent ? parent + "[" + key + "]" : key; -} -function append(entries, key, value) { - if (Array.isArray(value)) { - for (let [subkey, subvalue] of value.entries()) { - append(entries, composeKey(key, subkey.toString()), subvalue); - } - } else if (value instanceof Date) { - entries.push([key, value.toISOString()]); - } else if (typeof value === "boolean") { - entries.push([key, value ? "1" : "0"]); - } else if (typeof value === "string") { - entries.push([key, value]); - } else if (typeof value === "number") { - entries.push([key, `${value}`]); - } else if (value === null || value === void 0) { - entries.push([key, ""]); - } else { - objectToFormEntries(value, key, entries); - } -} -function attemptSubmit(element) { - var _a3; - let form = (_a3 = element == null ? void 0 : element.form) != null ? _a3 : element.closest("form"); - if (!form) - return; - for (let element2 of form.elements) { - if (element2.tagName === "INPUT" && element2.type === "submit" || element2.tagName === "BUTTON" && element2.type === "submit" || element2.nodeName === "INPUT" && element2.type === "image") { - element2.click(); - return; - } - } -} - -// src/internal/hidden.tsx -var DEFAULT_VISUALLY_HIDDEN_TAG = "div"; -function VisuallyHidden(props, ref) { - let { features = 1 /* None */, ...theirProps } = props; - let ourProps = { - ref, - "aria-hidden": (features & 2 /* Focusable */) === 2 /* Focusable */ ? true : void 0, - style: { - position: "fixed", - top: 1, - left: 1, - width: 1, - height: 0, - padding: 0, - margin: -1, - overflow: "hidden", - clip: "rect(0, 0, 0, 0)", - whiteSpace: "nowrap", - borderWidth: "0", - ...(features & 4 /* Hidden */) === 4 /* Hidden */ && !((features & 2 /* Focusable */) === 2 /* Focusable */) && { display: "none" } - } - }; - return render({ - ourProps, - theirProps, - slot: {}, - defaultTag: DEFAULT_VISUALLY_HIDDEN_TAG, - name: "Hidden" - }); -} -var Hidden = forwardRefWithAs(VisuallyHidden); - -// src/internal/open-closed.tsx -var import_react15 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var Context = (0, import_react15.createContext)(null); -Context.displayName = "OpenClosedContext"; -function useOpenClosed() { - return (0, import_react15.useContext)(Context); -} -function OpenClosedProvider({ value, children }) { - return /* @__PURE__ */ import_react15.default.createElement(Context.Provider, { value }, children); -} - -// src/hooks/use-controllable.ts -var import_react16 = __webpack_require__(/*! react */ "react"); -function useControllable(controlledValue, onChange, defaultValue) { - let [internalValue, setInternalValue] = (0, import_react16.useState)(defaultValue); - let isControlled = controlledValue !== void 0; - let wasControlled = (0, import_react16.useRef)(isControlled); - let didWarnOnUncontrolledToControlled = (0, import_react16.useRef)(false); - let didWarnOnControlledToUncontrolled = (0, import_react16.useRef)(false); - if (isControlled && !wasControlled.current && !didWarnOnUncontrolledToControlled.current) { - didWarnOnUncontrolledToControlled.current = true; - wasControlled.current = isControlled; - console.error( - "A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen." - ); - } else if (!isControlled && wasControlled.current && !didWarnOnControlledToUncontrolled.current) { - didWarnOnControlledToUncontrolled.current = true; - wasControlled.current = isControlled; - console.error( - "A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen." - ); - } - return [ - isControlled ? controlledValue : internalValue, - useEvent((value) => { - if (isControlled) { - return onChange == null ? void 0 : onChange(value); - } else { - setInternalValue(value); - return onChange == null ? void 0 : onChange(value); - } - }) - ]; -} - -// src/hooks/use-watch.ts -var import_react17 = __webpack_require__(/*! react */ "react"); -function useWatch(cb, dependencies) { - let track = (0, import_react17.useRef)([]); - let action = useEvent(cb); - (0, import_react17.useEffect)(() => { - let oldValues = [...track.current]; - for (let [idx, value] of dependencies.entries()) { - if (track.current[idx] !== value) { - let returnValue = action(dependencies, oldValues); - track.current = dependencies; - return returnValue; - } - } - }, [action, ...dependencies]); -} - -// src/hooks/use-tracked-pointer.ts -var import_react18 = __webpack_require__(/*! react */ "react"); -function eventToPosition(evt) { - return [evt.screenX, evt.screenY]; -} -function useTrackedPointer() { - let lastPos = (0, import_react18.useRef)([-1, -1]); - return { - wasMoved(evt) { - if (false) {} - let newPos = eventToPosition(evt); - if (lastPos.current[0] === newPos[0] && lastPos.current[1] === newPos[1]) { - return false; - } - lastPos.current = newPos; - return true; - }, - update(evt) { - lastPos.current = eventToPosition(evt); - } - }; -} - -// src/utils/platform.ts -function isIOS() { - return ( - // Check if it is an iPhone - /iPhone/gi.test(window.navigator.platform) || // Check if it is an iPad. iPad reports itself as "MacIntel", but we can check if it is a touch - // screen. Let's hope that Apple doesn't release a touch screen Mac (or maybe this would then - // work as expected 🤔). - /Mac/gi.test(window.navigator.platform) && window.navigator.maxTouchPoints > 0 - ); -} -function isAndroid() { - return /Android/gi.test(window.navigator.userAgent); -} -function isMobile() { - return isIOS() || isAndroid(); -} - -// src/components/combobox/combobox.tsx -function adjustOrderedState(state, adjustment = (i) => i) { - let currentActiveOption = state.activeOptionIndex !== null ? state.options[state.activeOptionIndex] : null; - let sortedOptions = sortByDomNode( - adjustment(state.options.slice()), - (option) => option.dataRef.current.domRef.current - ); - let adjustedActiveOptionIndex = currentActiveOption ? sortedOptions.indexOf(currentActiveOption) : null; - if (adjustedActiveOptionIndex === -1) { - adjustedActiveOptionIndex = null; - } - return { - options: sortedOptions, - activeOptionIndex: adjustedActiveOptionIndex - }; -} -var reducers = { - [1 /* CloseCombobox */](state) { - var _a3; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (state.comboboxState === 1 /* Closed */) - return state; - return { ...state, activeOptionIndex: null, comboboxState: 1 /* Closed */ }; - }, - [0 /* OpenCombobox */](state) { - var _a3; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (state.comboboxState === 0 /* Open */) - return state; - let activeOptionIndex = state.activeOptionIndex; - if (state.dataRef.current) { - let { isSelected } = state.dataRef.current; - let optionIdx = state.options.findIndex((option) => isSelected(option.dataRef.current.value)); - if (optionIdx !== -1) { - activeOptionIndex = optionIdx; - } - } - return { ...state, comboboxState: 0 /* Open */, activeOptionIndex }; - }, - [2 /* GoToOption */](state, action) { - var _a3, _b, _c, _d; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (((_b = state.dataRef.current) == null ? void 0 : _b.optionsRef.current) && !((_c = state.dataRef.current) == null ? void 0 : _c.optionsPropsRef.current.static) && state.comboboxState === 1 /* Closed */) { - return state; - } - let adjustedState = adjustOrderedState(state); - if (adjustedState.activeOptionIndex === null) { - let localActiveOptionIndex = adjustedState.options.findIndex( - (option) => !option.dataRef.current.disabled - ); - if (localActiveOptionIndex !== -1) { - adjustedState.activeOptionIndex = localActiveOptionIndex; - } - } - let activeOptionIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.options, - resolveActiveIndex: () => adjustedState.activeOptionIndex, - resolveId: (item) => item.id, - resolveDisabled: (item) => item.dataRef.current.disabled - }); - return { - ...state, - ...adjustedState, - activeOptionIndex, - activationTrigger: (_d = action.trigger) != null ? _d : 1 /* Other */ - }; - }, - [3 /* RegisterOption */]: (state, action) => { - var _a3, _b; - let option = { id: action.id, dataRef: action.dataRef }; - let adjustedState = adjustOrderedState(state, (options) => [...options, option]); - if (state.activeOptionIndex === null) { - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.isSelected(action.dataRef.current.value)) { - adjustedState.activeOptionIndex = adjustedState.options.indexOf(option); - } - } - let nextState = { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; - if (((_b = state.dataRef.current) == null ? void 0 : _b.__demoMode) && state.dataRef.current.value === void 0) { - nextState.activeOptionIndex = 0; - } - return nextState; - }, - [4 /* UnregisterOption */]: (state, action) => { - let adjustedState = adjustOrderedState(state, (options) => { - let idx = options.findIndex((a) => a.id === action.id); - if (idx !== -1) - options.splice(idx, 1); - return options; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; - }, - [5 /* RegisterLabel */]: (state, action) => { - return { - ...state, - labelId: action.id - }; - } -}; -var ComboboxActionsContext = (0, import_react19.createContext)(null); -ComboboxActionsContext.displayName = "ComboboxActionsContext"; -function useActions(component) { - let context = (0, import_react19.useContext)(ComboboxActionsContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useActions); - throw err; - } - return context; -} -var ComboboxDataContext = (0, import_react19.createContext)(null); -ComboboxDataContext.displayName = "ComboboxDataContext"; -function useData(component) { - let context = (0, import_react19.useContext)(ComboboxDataContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useData); - throw err; - } - return context; -} -function stateReducer(state, action) { - return match(action.type, reducers, state, action); -} -var DEFAULT_COMBOBOX_TAG = import_react19.Fragment; -function ComboboxFn(props, ref) { - let { - value: controlledValue, - defaultValue, - onChange: controlledOnChange, - form: formName, - name, - by = (a, z) => a === z, - disabled = false, - __demoMode = false, - nullable = false, - multiple = false, - ...theirProps - } = props; - let [value = multiple ? [] : void 0, theirOnChange] = useControllable( - controlledValue, - controlledOnChange, - defaultValue - ); - let [state, dispatch] = (0, import_react19.useReducer)(stateReducer, { - dataRef: (0, import_react19.createRef)(), - comboboxState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - options: [], - activeOptionIndex: null, - activationTrigger: 1 /* Other */, - labelId: null - }); - let defaultToFirstOption = (0, import_react19.useRef)(false); - let optionsPropsRef = (0, import_react19.useRef)({ static: false, hold: false }); - let labelRef = (0, import_react19.useRef)(null); - let inputRef = (0, import_react19.useRef)(null); - let buttonRef = (0, import_react19.useRef)(null); - let optionsRef = (0, import_react19.useRef)(null); - let compare = useEvent( - // @ts-expect-error Eventually we'll want to tackle this, but for now this will do. - typeof by === "string" ? (a, z) => { - let property = by; - return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]); - } : by - ); - let isSelected = (0, import_react19.useCallback)( - (compareValue) => match(data.mode, { - [1 /* Multi */]: () => value.some((option) => compare(option, compareValue)), - [0 /* Single */]: () => compare(value, compareValue) - }), - [value] - ); - let data = (0, import_react19.useMemo)( - () => ({ - ...state, - optionsPropsRef, - labelRef, - inputRef, - buttonRef, - optionsRef, - value, - defaultValue, - disabled, - mode: multiple ? 1 /* Multi */ : 0 /* Single */, - get activeOptionIndex() { - if (defaultToFirstOption.current && state.activeOptionIndex === null && state.options.length > 0) { - let localActiveOptionIndex = state.options.findIndex( - (option) => !option.dataRef.current.disabled - ); - if (localActiveOptionIndex !== -1) { - return localActiveOptionIndex; - } - } - return state.activeOptionIndex; - }, - compare, - isSelected, - nullable, - __demoMode - }), - [value, defaultValue, disabled, multiple, nullable, __demoMode, state] - ); - let lastActiveOption = (0, import_react19.useRef)( - data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null - ); - (0, import_react19.useEffect)(() => { - let currentActiveOption = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null; - if (lastActiveOption.current !== currentActiveOption) { - lastActiveOption.current = currentActiveOption; - } - }); - useIsoMorphicEffect(() => { - state.dataRef.current = data; - }, [data]); - useOutsideClick( - [data.buttonRef, data.inputRef, data.optionsRef], - () => actions.closeCombobox(), - data.comboboxState === 0 /* Open */ - ); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled, - activeIndex: data.activeOptionIndex, - activeOption: data.activeOptionIndex === null ? null : data.options[data.activeOptionIndex].dataRef.current.value, - value - }), - [data, disabled, value] - ); - let selectOption = useEvent((id) => { - let option = data.options.find((item) => item.id === id); - if (!option) - return; - onChange(option.dataRef.current.value); - }); - let selectActiveOption = useEvent(() => { - if (data.activeOptionIndex !== null) { - let { dataRef, id } = data.options[data.activeOptionIndex]; - onChange(dataRef.current.value); - actions.goToOption(4 /* Specific */, id); - } - }); - let openCombobox = useEvent(() => { - dispatch({ type: 0 /* OpenCombobox */ }); - defaultToFirstOption.current = true; - }); - let closeCombobox = useEvent(() => { - dispatch({ type: 1 /* CloseCombobox */ }); - defaultToFirstOption.current = false; - }); - let goToOption = useEvent((focus, id, trigger) => { - defaultToFirstOption.current = false; - if (focus === 4 /* Specific */) { - return dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id, trigger }); - } - return dispatch({ type: 2 /* GoToOption */, focus, trigger }); - }); - let registerOption = useEvent((id, dataRef) => { - dispatch({ type: 3 /* RegisterOption */, id, dataRef }); - return () => { - var _a3; - if (((_a3 = lastActiveOption.current) == null ? void 0 : _a3.id) === id) { - defaultToFirstOption.current = true; - } - dispatch({ type: 4 /* UnregisterOption */, id }); - }; - }); - let registerLabel = useEvent((id) => { - dispatch({ type: 5 /* RegisterLabel */, id }); - return () => dispatch({ type: 5 /* RegisterLabel */, id: null }); - }); - let onChange = useEvent((value2) => { - return match(data.mode, { - [0 /* Single */]() { - return theirOnChange == null ? void 0 : theirOnChange(value2); - }, - [1 /* Multi */]() { - let copy = data.value.slice(); - let idx = copy.findIndex((item) => compare(item, value2)); - if (idx === -1) { - copy.push(value2); - } else { - copy.splice(idx, 1); + // src/components/popover/popover.tsx + var import_react37 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var reducers6 = { + [0 /* TogglePopover */]: (state) => { + let nextState = { + ...state, + popoverState: match(state.popoverState, { + [0 /* Open */]: 1 /* Closed */, + [1 /* Closed */]: 0 /* Open */, + }), + }; + if (nextState.popoverState === 0 /* Open */) { + nextState.__demoMode = false; + } + return nextState; + }, + [1 /* ClosePopover */](state) { + if (state.popoverState === 1 /* Closed */) return state; + return { ...state, popoverState: 1 /* Closed */ }; + }, + [2 /* SetButton */](state, action) { + if (state.button === action.button) return state; + return { ...state, button: action.button }; + }, + [3 /* SetButtonId */](state, action) { + if (state.buttonId === action.buttonId) return state; + return { ...state, buttonId: action.buttonId }; + }, + [4 /* SetPanel */](state, action) { + if (state.panel === action.panel) return state; + return { ...state, panel: action.panel }; + }, + [5 /* SetPanelId */](state, action) { + if (state.panelId === action.panelId) return state; + return { ...state, panelId: action.panelId }; + }, + }; + var PopoverContext = (0, import_react37.createContext)(null); + PopoverContext.displayName = "PopoverContext"; + function usePopoverContext(component) { + let context = (0, import_react37.useContext)(PopoverContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, usePopoverContext); + throw err; + } + return context; } - return theirOnChange == null ? void 0 : theirOnChange(copy); - } - }); - }); - let actions = (0, import_react19.useMemo)( - () => ({ - onChange, - registerOption, - registerLabel, - goToOption, - closeCombobox, - openCombobox, - selectActiveOption, - selectOption - }), - [] - ); - let ourProps = ref === null ? {} : { ref }; - let form = (0, import_react19.useRef)(null); - let d = useDisposables(); - (0, import_react19.useEffect)(() => { - if (!form.current) - return; - if (defaultValue === void 0) - return; - d.addEventListener(form.current, "reset", () => { - onChange(defaultValue); - }); - }, [ - form, - onChange - /* Explicitly ignoring `defaultValue` */ - ]); - return /* @__PURE__ */ import_react19.default.createElement(ComboboxActionsContext.Provider, { value: actions }, /* @__PURE__ */ import_react19.default.createElement(ComboboxDataContext.Provider, { value: data }, /* @__PURE__ */ import_react19.default.createElement( - OpenClosedProvider, - { - value: match(data.comboboxState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - name != null && value != null && objectToFormEntries({ [name]: value }).map(([name2, value2], idx) => /* @__PURE__ */ import_react19.default.createElement( - Hidden, - { - features: 4 /* Hidden */, - ref: idx === 0 ? (element) => { + var PopoverAPIContext = (0, import_react37.createContext)(null); + PopoverAPIContext.displayName = "PopoverAPIContext"; + function usePopoverAPIContext(component) { + let context = (0, import_react37.useContext)(PopoverAPIContext); + if (context === null) { + let err = new Error( + `<${component} /> is missing a parent component.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(err, usePopoverAPIContext); + throw err; + } + return context; + } + var PopoverGroupContext = (0, import_react37.createContext)(null); + PopoverGroupContext.displayName = "PopoverGroupContext"; + function usePopoverGroupContext() { + return (0, import_react37.useContext)(PopoverGroupContext); + } + var PopoverPanelContext = (0, import_react37.createContext)(null); + PopoverPanelContext.displayName = "PopoverPanelContext"; + function usePopoverPanelContext() { + return (0, import_react37.useContext)(PopoverPanelContext); + } + function stateReducer6(state, action) { + return match(action.type, reducers6, state, action); + } + var DEFAULT_POPOVER_TAG = "div"; + function PopoverFn(props, ref) { var _a3; - form.current = (_a3 = element == null ? void 0 : element.closest("form")) != null ? _a3 : null; - } : void 0, - ...compact({ - key: name2, - as: "input", - type: "hidden", - hidden: true, - readOnly: true, - form: formName, - name: name2, - value: value2 - }) - } - )), - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_COMBOBOX_TAG, - name: "Combobox" - }) - ))); -} -var DEFAULT_INPUT_TAG = "input"; -function InputFn(props, ref) { - var _a3, _b, _c, _d; - let internalId = useId(); - let { - id = `headlessui-combobox-input-${internalId}`, - onChange, - displayValue, - // @ts-ignore: We know this MAY NOT exist for a given tag but we only care when it _does_ exist. - type = "text", - ...theirProps - } = props; - let data = useData("Combobox.Input"); - let actions = useActions("Combobox.Input"); - let inputRef = useSyncRefs(data.inputRef, ref); - let isTyping = (0, import_react19.useRef)(false); - let d = useDisposables(); - let currentDisplayValue = function() { - var _a4; - if (typeof displayValue === "function" && data.value !== void 0) { - return (_a4 = displayValue(data.value)) != null ? _a4 : ""; - } else if (typeof data.value === "string") { - return data.value; - } else { - return ""; - } - }(); - useWatch( - ([currentDisplayValue2, state], [oldCurrentDisplayValue, oldState]) => { - if (isTyping.current) - return; - if (!data.inputRef.current) - return; - if (oldState === 0 /* Open */ && state === 1 /* Closed */) { - data.inputRef.current.value = currentDisplayValue2; - } else if (currentDisplayValue2 !== oldCurrentDisplayValue) { - data.inputRef.current.value = currentDisplayValue2; - } - }, - [currentDisplayValue, data.comboboxState] - ); - useWatch( - ([newState], [oldState]) => { - if (newState === 0 /* Open */ && oldState === 1 /* Closed */) { - let input = data.inputRef.current; - if (!input) - return; - let currentValue = input.value; - let { selectionStart, selectionEnd, selectionDirection } = input; - input.value = ""; - input.value = currentValue; - if (selectionDirection !== null) { - input.setSelectionRange(selectionStart, selectionEnd, selectionDirection); - } else { - input.setSelectionRange(selectionStart, selectionEnd); + let { __demoMode = false, ...theirProps } = props; + let internalPopoverRef = (0, import_react37.useRef)(null); + let popoverRef = useSyncRefs( + ref, + optionalRef((ref2) => { + internalPopoverRef.current = ref2; + }) + ); + let buttons = (0, import_react37.useRef)([]); + let reducerBag = (0, import_react37.useReducer)(stateReducer6, { + __demoMode, + popoverState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + buttons, + button: null, + buttonId: null, + panel: null, + panelId: null, + beforePanelSentinel: (0, import_react37.createRef)(), + afterPanelSentinel: (0, import_react37.createRef)(), + }); + let [ + { + popoverState, + button, + buttonId, + panel, + panelId, + beforePanelSentinel, + afterPanelSentinel, + }, + dispatch, + ] = reducerBag; + let ownerDocument = useOwnerDocument( + (_a3 = internalPopoverRef.current) != null ? _a3 : button + ); + let isPortalled = (0, import_react37.useMemo)(() => { + if (!button) return false; + if (!panel) return false; + for (let root2 of document.querySelectorAll("body > *")) { + if ( + Number(root2 == null ? void 0 : root2.contains(button)) ^ + Number(root2 == null ? void 0 : root2.contains(panel)) + ) { + return true; + } + } + let elements = getFocusableElements(); + let buttonIdx = elements.indexOf(button); + let beforeIdx = (buttonIdx + elements.length - 1) % elements.length; + let afterIdx = (buttonIdx + 1) % elements.length; + let beforeElement = elements[beforeIdx]; + let afterElement = elements[afterIdx]; + if ( + !panel.contains(beforeElement) && + !panel.contains(afterElement) + ) { + return true; + } + return false; + }, [button, panel]); + let buttonIdRef = useLatestValue(buttonId); + let panelIdRef = useLatestValue(panelId); + let registerBag = (0, import_react37.useMemo)( + () => ({ + buttonId: buttonIdRef, + panelId: panelIdRef, + close: () => dispatch({ type: 1 /* ClosePopover */ }), + }), + [buttonIdRef, panelIdRef, dispatch] + ); + let groupContext = usePopoverGroupContext(); + let registerPopover = + groupContext == null ? void 0 : groupContext.registerPopover; + let isFocusWithinPopoverGroup = useEvent(() => { + var _a4; + return (_a4 = + groupContext == null + ? void 0 + : groupContext.isFocusWithinPopoverGroup()) != null + ? _a4 + : (ownerDocument == null + ? void 0 + : ownerDocument.activeElement) && + ((button == null + ? void 0 + : button.contains(ownerDocument.activeElement)) || + (panel == null + ? void 0 + : panel.contains(ownerDocument.activeElement))); + }); + (0, import_react37.useEffect)( + () => + registerPopover == null ? void 0 : registerPopover(registerBag), + [registerPopover, registerBag] + ); + let [portals, PortalWrapper] = useNestedPortals(); + let root = useRootContainers({ + portals, + defaultContainers: [button, panel], + }); + useEventListener( + ownerDocument == null ? void 0 : ownerDocument.defaultView, + "focus", + (event) => { + var _a4, _b, _c, _d; + if (event.target === window) return; + if (!(event.target instanceof HTMLElement)) return; + if (popoverState !== 0 /* Open */) return; + if (isFocusWithinPopoverGroup()) return; + if (!button) return; + if (!panel) return; + if (root.contains(event.target)) return; + if ( + (_b = + (_a4 = beforePanelSentinel.current) == null + ? void 0 + : _a4.contains) == null + ? void 0 + : _b.call(_a4, event.target) + ) + return; + if ( + (_d = + (_c = afterPanelSentinel.current) == null + ? void 0 + : _c.contains) == null + ? void 0 + : _d.call(_c, event.target) + ) + return; + dispatch({ type: 1 /* ClosePopover */ }); + }, + true + ); + useOutsideClick( + root.resolveContainers, + (event, target) => { + dispatch({ type: 1 /* ClosePopover */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + button == null ? void 0 : button.focus(); + } + }, + popoverState === 0 /* Open */ + ); + let close = useEvent((focusableElement) => { + dispatch({ type: 1 /* ClosePopover */ }); + let restoreElement = (() => { + if (!focusableElement) return button; + if (focusableElement instanceof HTMLElement) + return focusableElement; + if ( + "current" in focusableElement && + focusableElement.current instanceof HTMLElement + ) + return focusableElement.current; + return button; + })(); + restoreElement == null ? void 0 : restoreElement.focus(); + }); + let api = (0, import_react37.useMemo)( + () => ({ close, isPortalled }), + [close, isPortalled] + ); + let slot = (0, import_react37.useMemo)( + () => ({ open: popoverState === 0 /* Open */, close }), + [popoverState, close] + ); + let ourProps = { ref: popoverRef }; + return /* @__PURE__ */ import_react37.default.createElement( + PopoverPanelContext.Provider, + { value: null }, + /* @__PURE__ */ import_react37.default.createElement( + PopoverContext.Provider, + { value: reducerBag }, + /* @__PURE__ */ import_react37.default.createElement( + PopoverAPIContext.Provider, + { value: api }, + /* @__PURE__ */ import_react37.default.createElement( + OpenClosedProvider, + { + value: match(popoverState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */, + }), + }, + /* @__PURE__ */ import_react37.default.createElement( + PortalWrapper, + null, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_POPOVER_TAG, + name: "Popover", + }), + /* @__PURE__ */ import_react37.default.createElement( + root.MainTreeNode, + null + ) + ) + ) + ) + ) + ); } - } - }, - [data.comboboxState] - ); - let isComposing = (0, import_react19.useRef)(false); - let composedChangeEvent = (0, import_react19.useRef)(null); - let handleCompositionStart = useEvent(() => { - isComposing.current = true; - }); - let handleCompositionEnd = useEvent(() => { - d.nextFrame(() => { - isComposing.current = false; - if (composedChangeEvent.current) { - actions.openCombobox(); - onChange == null ? void 0 : onChange(composedChangeEvent.current); - composedChangeEvent.current = null; - } - }); - }); - let handleKeyDown = useEvent((event) => { - isTyping.current = true; - switch (event.key) { - case "Backspace" /* Backspace */: - case "Delete" /* Delete */: - if (data.mode !== 0 /* Single */) - return; - if (!data.nullable) - return; - let input = event.currentTarget; - d.requestAnimationFrame(() => { - if (input.value === "") { - actions.onChange(null); - if (data.optionsRef.current) { - data.optionsRef.current.scrollTop = 0; + var DEFAULT_BUTTON_TAG5 = "button"; + function ButtonFn5(props, ref) { + let internalId = useId(); + let { + id = `headlessui-popover-button-${internalId}`, + ...theirProps + } = props; + let [state, dispatch] = usePopoverContext("Popover.Button"); + let { isPortalled } = usePopoverAPIContext("Popover.Button"); + let internalButtonRef = (0, import_react37.useRef)(null); + let sentinelId = `headlessui-focus-sentinel-${useId()}`; + let groupContext = usePopoverGroupContext(); + let closeOthers = + groupContext == null ? void 0 : groupContext.closeOthers; + let panelContext = usePopoverPanelContext(); + let isWithinPanel = panelContext !== null; + (0, import_react37.useEffect)(() => { + if (isWithinPanel) return; + dispatch({ type: 3 /* SetButtonId */, buttonId: id }); + return () => { + dispatch({ type: 3 /* SetButtonId */, buttonId: null }); + }; + }, [isWithinPanel, id, dispatch]); + let [uniqueIdentifier] = (0, import_react37.useState)(() => Symbol()); + let buttonRef = useSyncRefs( + internalButtonRef, + ref, + isWithinPanel + ? null + : (button) => { + if (button) { + state.buttons.current.push(uniqueIdentifier); + } else { + let idx = state.buttons.current.indexOf(uniqueIdentifier); + if (idx !== -1) state.buttons.current.splice(idx, 1); + } + if (state.buttons.current.length > 1) { + console.warn( + "You are already using a but only 1 is supported." + ); + } + button && dispatch({ type: 2 /* SetButton */, button }); + } + ); + let withinPanelButtonRef = useSyncRefs(internalButtonRef, ref); + let ownerDocument = useOwnerDocument(internalButtonRef); + let handleKeyDown = useEvent((event) => { + var _a3, _b, _c; + if (isWithinPanel) { + if (state.popoverState === 1 /* Closed */) return; + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + (_b = (_a3 = event.target).click) == null + ? void 0 + : _b.call(_a3); + dispatch({ type: 1 /* ClosePopover */ }); + (_c = state.button) == null ? void 0 : _c.focus(); + break; + } + } else { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + if (state.popoverState === 1 /* Closed */) + closeOthers == null ? void 0 : closeOthers(state.buttonId); + dispatch({ type: 0 /* TogglePopover */ }); + break; + case "Escape" /* Escape */: + if (state.popoverState !== 0 /* Open */) + return closeOthers == null + ? void 0 + : closeOthers(state.buttonId); + if (!internalButtonRef.current) return; + if ( + (ownerDocument == null + ? void 0 + : ownerDocument.activeElement) && + !internalButtonRef.current.contains( + ownerDocument.activeElement + ) + ) { + return; + } + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* ClosePopover */ }); + break; + } } - actions.goToOption(5 /* Nothing */); - } - }); - break; - case "Enter" /* Enter */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) - return; - if (isComposing.current) - return; - event.preventDefault(); - event.stopPropagation(); - if (data.activeOptionIndex === null) { - actions.closeCombobox(); - return; - } - actions.selectActiveOption(); - if (data.mode === 0 /* Single */) { - actions.closeCombobox(); - } - break; - case "ArrowDown" /* ArrowDown */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return match(data.comboboxState, { - [0 /* Open */]: () => { - actions.goToOption(2 /* Next */); - }, - [1 /* Closed */]: () => { - actions.openCombobox(); - } - }); - case "ArrowUp" /* ArrowUp */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return match(data.comboboxState, { - [0 /* Open */]: () => { - actions.goToOption(1 /* Previous */); - }, - [1 /* Closed */]: () => { - actions.openCombobox(); - d.nextFrame(() => { - if (!data.value) { - actions.goToOption(3 /* Last */); + }); + let handleKeyUp = useEvent((event) => { + if (isWithinPanel) return; + if (event.key === " " /* Space */) { + event.preventDefault(); + } + }); + let handleClick = useEvent((event) => { + var _a3, _b; + if (isDisabledReactIssue7711(event.currentTarget)) return; + if (props.disabled) return; + if (isWithinPanel) { + dispatch({ type: 1 /* ClosePopover */ }); + (_a3 = state.button) == null ? void 0 : _a3.focus(); + } else { + event.preventDefault(); + event.stopPropagation(); + if (state.popoverState === 1 /* Closed */) + closeOthers == null ? void 0 : closeOthers(state.buttonId); + dispatch({ type: 0 /* TogglePopover */ }); + (_b = state.button) == null ? void 0 : _b.focus(); + } + }); + let handleMouseDown = useEvent((event) => { + event.preventDefault(); + event.stopPropagation(); + }); + let visible = state.popoverState === 0; /* Open */ + let slot = (0, import_react37.useMemo)( + () => ({ open: visible }), + [visible] + ); + let type = useResolveButtonType(props, internalButtonRef); + let ourProps = isWithinPanel + ? { + ref: withinPanelButtonRef, + type, + onKeyDown: handleKeyDown, + onClick: handleClick, } - }); - } - }); - case "Home" /* Home */: - if (event.shiftKey) { - break; - } - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "PageUp" /* PageUp */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "End" /* End */: - if (event.shiftKey) { - break; - } - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "PageDown" /* PageDown */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "Escape" /* Escape */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) - return; - event.preventDefault(); - if (data.optionsRef.current && !data.optionsPropsRef.current.static) { - event.stopPropagation(); - } - return actions.closeCombobox(); - case "Tab" /* Tab */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) - return; - if (data.mode === 0 /* Single */) - actions.selectActiveOption(); - actions.closeCombobox(); - break; - } - }); - let handleChange = useEvent((event) => { - if (isComposing.current) { - composedChangeEvent.current = event; - return; - } - actions.openCombobox(); - onChange == null ? void 0 : onChange(event); - }); - let handleBlur = useEvent(() => { - isTyping.current = false; - }); - let labelledby = useComputed(() => { - if (!data.labelId) - return void 0; - return [data.labelId].join(" "); - }, [data.labelId]); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */, disabled: data.disabled }), - [data] - ); - let ourProps = { - ref: inputRef, - id, - role: "combobox", - type, - "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled ? void 0 : data.comboboxState === 0 /* Open */, - "aria-activedescendant": data.activeOptionIndex === null ? void 0 : (_b = data.options[data.activeOptionIndex]) == null ? void 0 : _b.id, - "aria-labelledby": labelledby, - "aria-autocomplete": "list", - defaultValue: (_d = (_c = props.defaultValue) != null ? _c : data.defaultValue !== void 0 ? displayValue == null ? void 0 : displayValue(data.defaultValue) : null) != null ? _d : data.defaultValue, - disabled: data.disabled, - onCompositionStart: handleCompositionStart, - onCompositionEnd: handleCompositionEnd, - onKeyDown: handleKeyDown, - onChange: handleChange, - onBlur: handleBlur - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_INPUT_TAG, - name: "Combobox.Input" - }); -} -var DEFAULT_BUTTON_TAG = "button"; -function ButtonFn(props, ref) { - var _a3; - let data = useData("Combobox.Button"); - let actions = useActions("Combobox.Button"); - let buttonRef = useSyncRefs(data.buttonRef, ref); - let internalId = useId(); - let { id = `headlessui-combobox-button-${internalId}`, ...theirProps } = props; - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - if (data.comboboxState === 1 /* Closed */) { - actions.openCombobox(); - } - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - if (data.comboboxState === 1 /* Closed */) { - actions.openCombobox(); - d.nextFrame(() => { - if (!data.value) { - actions.goToOption(3 /* Last */); + : { + ref: buttonRef, + id: state.buttonId, + type, + "aria-expanded": props.disabled + ? void 0 + : state.popoverState === 0 /* Open */, + "aria-controls": state.panel ? state.panelId : void 0, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick, + onMouseDown: handleMouseDown, + }; + let direction = useTabDirection(); + let handleFocus = useEvent(() => { + let el = state.panel; + if (!el) return; + function run() { + let result = match(direction.current, { + [0 /* Forwards */]: () => focusIn(el, 1 /* First */), + [1 /* Backwards */]: () => focusIn(el, 8 /* Last */), + }); + if (result === 0 /* Error */) { + focusIn( + getFocusableElements().filter( + (el2) => el2.dataset.headlessuiFocusGuard !== "true" + ), + match(direction.current, { + [0 /* Forwards */]: 4 /* Next */, + [1 /* Backwards */]: 2 /* Previous */, + }), + { relativeTo: state.button } + ); + } + } + if (false) { + } else { + run(); } }); + return /* @__PURE__ */ import_react37.default.createElement( + import_react37.default.Fragment, + null, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG5, + name: "Popover.Button", + }), + visible && + !isWithinPanel && + isPortalled && + /* @__PURE__ */ import_react37.default.createElement(Hidden, { + id: sentinelId, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleFocus, + }) + ); } - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - case "Escape" /* Escape */: - if (data.comboboxState !== 0 /* Open */) - return; - event.preventDefault(); - if (data.optionsRef.current && !data.optionsPropsRef.current.static) { - event.stopPropagation(); - } - actions.closeCombobox(); - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - default: - return; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (data.comboboxState === 0 /* Open */) { - actions.closeCombobox(); - } else { - event.preventDefault(); - actions.openCombobox(); - } - d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - }); - let labelledby = useComputed(() => { - if (!data.labelId) - return void 0; - return [data.labelId, id].join(" "); - }, [data.labelId, id]); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled: data.disabled, - value: data.value - }), - [data] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, data.buttonRef), - tabIndex: -1, - "aria-haspopup": "listbox", - "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled ? void 0 : data.comboboxState === 0 /* Open */, - "aria-labelledby": labelledby, - disabled: data.disabled, - onClick: handleClick, - onKeyDown: handleKeyDown - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG, - name: "Combobox.Button" - }); -} -var DEFAULT_LABEL_TAG = "label"; -function LabelFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-combobox-label-${internalId}`, ...theirProps } = props; - let data = useData("Combobox.Label"); - let actions = useActions("Combobox.Label"); - let labelRef = useSyncRefs(data.labelRef, ref); - useIsoMorphicEffect(() => actions.registerLabel(id), [id]); - let handleClick = useEvent(() => { - var _a3; - return (_a3 = data.inputRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); - }); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */, disabled: data.disabled }), - [data] - ); - let ourProps = { ref: labelRef, id, onClick: handleClick }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_LABEL_TAG, - name: "Combobox.Label" - }); -} -var DEFAULT_OPTIONS_TAG = "ul"; -var OptionsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; -function OptionsFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-combobox-options-${internalId}`, hold = false, ...theirProps } = props; - let data = useData("Combobox.Options"); - let optionsRef = useSyncRefs(data.optionsRef, ref); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return data.comboboxState === 0 /* Open */; - })(); - useIsoMorphicEffect(() => { - var _a3; - data.optionsPropsRef.current.static = (_a3 = props.static) != null ? _a3 : false; - }, [data.optionsPropsRef, props.static]); - useIsoMorphicEffect(() => { - data.optionsPropsRef.current.hold = hold; - }, [data.optionsPropsRef, hold]); - useTreeWalker({ - container: data.optionsRef.current, - enabled: data.comboboxState === 0 /* Open */, - accept(node) { - if (node.getAttribute("role") === "option") - return NodeFilter.FILTER_REJECT; - if (node.hasAttribute("role")) - return NodeFilter.FILTER_SKIP; - return NodeFilter.FILTER_ACCEPT; - }, - walk(node) { - node.setAttribute("role", "none"); - } - }); - let labelledby = useComputed( - () => { - var _a3, _b; - return (_b = data.labelId) != null ? _b : (_a3 = data.buttonRef.current) == null ? void 0 : _a3.id; - }, - [data.labelId, data.buttonRef.current] - ); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */ }), - [data] - ); - let ourProps = { - "aria-labelledby": labelledby, - role: "listbox", - "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, - id, - ref: optionsRef - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTIONS_TAG, - features: OptionsRenderFeatures, - visible, - name: "Combobox.Options" - }); -} -var DEFAULT_OPTION_TAG = "li"; -function OptionFn(props, ref) { - var _a3, _b; - let internalId = useId(); - let { - id = `headlessui-combobox-option-${internalId}`, - disabled = false, - value, - ...theirProps - } = props; - let data = useData("Combobox.Option"); - let actions = useActions("Combobox.Option"); - let active = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex].id === id : false; - let selected = data.isSelected(value); - let internalOptionRef = (0, import_react19.useRef)(null); - let bag = useLatestValue({ - disabled, - value, - domRef: internalOptionRef, - textValue: (_b = (_a3 = internalOptionRef.current) == null ? void 0 : _a3.textContent) == null ? void 0 : _b.toLowerCase() - }); - let optionRef = useSyncRefs(ref, internalOptionRef); - let select = useEvent(() => actions.selectOption(id)); - useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); - let enableScrollIntoView = (0, import_react19.useRef)(data.__demoMode ? false : true); - useIsoMorphicEffect(() => { - if (!data.__demoMode) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - enableScrollIntoView.current = true; - }); - return d.dispose; - }, []); - useIsoMorphicEffect(() => { - if (data.comboboxState !== 0 /* Open */) - return; - if (!active) - return; - if (!enableScrollIntoView.current) - return; - if (data.activationTrigger === 0 /* Pointer */) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a4, _b2; - (_b2 = (_a4 = internalOptionRef.current) == null ? void 0 : _a4.scrollIntoView) == null ? void 0 : _b2.call(_a4, { block: "nearest" }); - }); - return d.dispose; - }, [ - internalOptionRef, - active, - data.comboboxState, - data.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - data.activeOptionIndex - ]); - let handleClick = useEvent((event) => { - if (disabled) - return event.preventDefault(); - select(); - if (data.mode === 0 /* Single */) { - actions.closeCombobox(); - } - if (!isMobile()) { - requestAnimationFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus(); - }); - } - }); - let handleFocus = useEvent(() => { - if (disabled) - return actions.goToOption(5 /* Nothing */); - actions.goToOption(4 /* Specific */, id); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (active) - return; - actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (!active) - return; - if (data.optionsPropsRef.current.hold) - return; - actions.goToOption(5 /* Nothing */); - }); - let slot = (0, import_react19.useMemo)( - () => ({ active, selected, disabled }), - [active, selected, disabled] - ); - let ourProps = { - id, - ref: optionRef, - role: "option", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - // According to the WAI-ARIA best practices, we should use aria-checked for - // multi-select,but Voice-Over disagrees. So we use aria-checked instead for - // both single and multi-select. - "aria-selected": selected, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTION_TAG, - name: "Combobox.Option" - }); -} -var ComboboxRoot = forwardRefWithAs(ComboboxFn); -var Button = forwardRefWithAs(ButtonFn); -var Input = forwardRefWithAs(InputFn); -var Label = forwardRefWithAs(LabelFn); -var Options = forwardRefWithAs(OptionsFn); -var Option = forwardRefWithAs(OptionFn); -var Combobox = Object.assign(ComboboxRoot, { Input, Button, Label, Options, Option }); - -// src/components/dialog/dialog.tsx -var import_react31 = __toESM(__webpack_require__(/*! react */ "react"), 1); - -// src/components/focus-trap/focus-trap.tsx -var import_react25 = __toESM(__webpack_require__(/*! react */ "react"), 1); - -// src/hooks/use-tab-direction.ts -var import_react20 = __webpack_require__(/*! react */ "react"); -function useTabDirection() { - let direction = (0, import_react20.useRef)(0 /* Forwards */); - useWindowEvent( - "keydown", - (event) => { - if (event.key === "Tab") { - direction.current = event.shiftKey ? 1 /* Backwards */ : 0 /* Forwards */; - } - }, - true - ); - return direction; -} - -// src/hooks/use-is-mounted.ts -var import_react21 = __webpack_require__(/*! react */ "react"); -function useIsMounted() { - let mounted = (0, import_react21.useRef)(false); - useIsoMorphicEffect(() => { - mounted.current = true; - return () => { - mounted.current = false; - }; - }, []); - return mounted; -} - -// src/hooks/use-owner.ts -var import_react22 = __webpack_require__(/*! react */ "react"); -function useOwnerDocument(...args) { - return (0, import_react22.useMemo)(() => getOwnerDocument(...args), [...args]); -} - -// src/hooks/use-event-listener.ts -var import_react23 = __webpack_require__(/*! react */ "react"); -function useEventListener(element, type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react23.useEffect)(() => { - element = element != null ? element : window; - function handler(event) { - listenerRef.current(event); - } - element.addEventListener(type, handler, options); - return () => element.removeEventListener(type, handler, options); - }, [element, type, options]); -} - -// src/utils/document-ready.ts -function onDocumentReady(cb) { - function check() { - if (document.readyState === "loading") - return; - cb(); - document.removeEventListener("DOMContentLoaded", check); - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - document.addEventListener("DOMContentLoaded", check); - check(); - } -} - -// src/hooks/use-on-unmount.ts -var import_react24 = __webpack_require__(/*! react */ "react"); -function useOnUnmount(cb) { - let stableCb = useEvent(cb); - let trulyUnmounted = (0, import_react24.useRef)(false); - (0, import_react24.useEffect)(() => { - trulyUnmounted.current = false; - return () => { - trulyUnmounted.current = true; - microTask(() => { - if (!trulyUnmounted.current) - return; - stableCb(); - }); - }; - }, [stableCb]); -} - -// src/components/focus-trap/focus-trap.tsx -function resolveContainers(containers) { - if (!containers) - return /* @__PURE__ */ new Set(); - if (typeof containers === "function") - return new Set(containers()); - let all = /* @__PURE__ */ new Set(); - for (let container of containers.current) { - if (container.current instanceof HTMLElement) { - all.add(container.current); - } - } - return all; -} -var DEFAULT_FOCUS_TRAP_TAG = "div"; -var Features3 = /* @__PURE__ */ ((Features4) => { - Features4[Features4["None"] = 1] = "None"; - Features4[Features4["InitialFocus"] = 2] = "InitialFocus"; - Features4[Features4["TabLock"] = 4] = "TabLock"; - Features4[Features4["FocusLock"] = 8] = "FocusLock"; - Features4[Features4["RestoreFocus"] = 16] = "RestoreFocus"; - Features4[Features4["All"] = 30] = "All"; - return Features4; -})(Features3 || {}); -function FocusTrapFn(props, ref) { - let container = (0, import_react25.useRef)(null); - let focusTrapRef = useSyncRefs(container, ref); - let { initialFocus, containers, features = 30 /* All */, ...theirProps } = props; - if (!useServerHandoffComplete()) { - features = 1 /* None */; - } - let ownerDocument = useOwnerDocument(container); - useRestoreFocus({ ownerDocument }, Boolean(features & 16 /* RestoreFocus */)); - let previousActiveElement = useInitialFocus( - { ownerDocument, container, initialFocus }, - Boolean(features & 2 /* InitialFocus */) - ); - useFocusLock( - { ownerDocument, container, containers, previousActiveElement }, - Boolean(features & 8 /* FocusLock */) - ); - let direction = useTabDirection(); - let handleFocus = useEvent((e) => { - let el = container.current; - if (!el) - return; - let wrapper = false ? 0 : (cb) => cb(); - wrapper(() => { - match(direction.current, { - [0 /* Forwards */]: () => { - focusIn(el, 1 /* First */, { skipElements: [e.relatedTarget] }); - }, - [1 /* Backwards */]: () => { - focusIn(el, 8 /* Last */, { skipElements: [e.relatedTarget] }); - } - }); - }); - }); - let d = useDisposables(); - let recentlyUsedTabKey = (0, import_react25.useRef)(false); - let ourProps = { - ref: focusTrapRef, - onKeyDown(e) { - if (e.key == "Tab") { - recentlyUsedTabKey.current = true; - d.requestAnimationFrame(() => { - recentlyUsedTabKey.current = false; - }); - } - }, - onBlur(e) { - let allContainers = resolveContainers(containers); - if (container.current instanceof HTMLElement) - allContainers.add(container.current); - let relatedTarget = e.relatedTarget; - if (!(relatedTarget instanceof HTMLElement)) - return; - if (relatedTarget.dataset.headlessuiFocusGuard === "true") { - return; - } - if (!contains(allContainers, relatedTarget)) { - if (recentlyUsedTabKey.current) { - focusIn( - container.current, - match(direction.current, { - [0 /* Forwards */]: () => 4 /* Next */, - [1 /* Backwards */]: () => 2 /* Previous */ - }) | 16 /* WrapAround */, - { relativeTo: e.target } - ); - } else if (e.target instanceof HTMLElement) { - focusElement(e.target); - } - } - } - }; - return /* @__PURE__ */ import_react25.default.createElement(import_react25.default.Fragment, null, Boolean(features & 4 /* TabLock */) && /* @__PURE__ */ import_react25.default.createElement( - Hidden, - { - as: "button", - type: "button", - "data-headlessui-focus-guard": true, - onFocus: handleFocus, - features: 2 /* Focusable */ - } - ), render({ - ourProps, - theirProps, - defaultTag: DEFAULT_FOCUS_TRAP_TAG, - name: "FocusTrap" - }), Boolean(features & 4 /* TabLock */) && /* @__PURE__ */ import_react25.default.createElement( - Hidden, - { - as: "button", - type: "button", - "data-headlessui-focus-guard": true, - onFocus: handleFocus, - features: 2 /* Focusable */ - } - )); -} -var FocusTrapRoot = forwardRefWithAs(FocusTrapFn); -var FocusTrap = Object.assign(FocusTrapRoot, { - features: Features3 -}); -var history = []; -onDocumentReady(() => { - function handle(e) { - if (!(e.target instanceof HTMLElement)) - return; - if (e.target === document.body) - return; - if (history[0] === e.target) - return; - history.unshift(e.target); - history = history.filter((x) => x != null && x.isConnected); - history.splice(10); - } - window.addEventListener("click", handle, { capture: true }); - window.addEventListener("mousedown", handle, { capture: true }); - window.addEventListener("focus", handle, { capture: true }); - document.body.addEventListener("click", handle, { capture: true }); - document.body.addEventListener("mousedown", handle, { capture: true }); - document.body.addEventListener("focus", handle, { capture: true }); -}); -function useRestoreElement(enabled = true) { - let localHistory = (0, import_react25.useRef)(history.slice()); - useWatch( - ([newEnabled], [oldEnabled]) => { - if (oldEnabled === true && newEnabled === false) { - microTask(() => { - localHistory.current.splice(0); - }); - } - if (oldEnabled === false && newEnabled === true) { - localHistory.current = history.slice(); - } - }, - [enabled, history, localHistory] - ); - return useEvent(() => { - var _a3; - return (_a3 = localHistory.current.find((x) => x != null && x.isConnected)) != null ? _a3 : null; - }); -} -function useRestoreFocus({ ownerDocument }, enabled) { - let getRestoreElement = useRestoreElement(enabled); - useWatch(() => { - if (enabled) - return; - if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) === (ownerDocument == null ? void 0 : ownerDocument.body)) { - focusElement(getRestoreElement()); - } - }, [enabled]); - useOnUnmount(() => { - if (!enabled) - return; - focusElement(getRestoreElement()); - }); -} -function useInitialFocus({ - ownerDocument, - container, - initialFocus -}, enabled) { - let previousActiveElement = (0, import_react25.useRef)(null); - let mounted = useIsMounted(); - useWatch(() => { - if (!enabled) - return; - let containerElement = container.current; - if (!containerElement) - return; - microTask(() => { - if (!mounted.current) { - return; - } - let activeElement = ownerDocument == null ? void 0 : ownerDocument.activeElement; - if (initialFocus == null ? void 0 : initialFocus.current) { - if ((initialFocus == null ? void 0 : initialFocus.current) === activeElement) { - previousActiveElement.current = activeElement; - return; - } - } else if (containerElement.contains(activeElement)) { - previousActiveElement.current = activeElement; - return; - } - if (initialFocus == null ? void 0 : initialFocus.current) { - focusElement(initialFocus.current); - } else { - if (focusIn(containerElement, 1 /* First */) === 0 /* Error */) { - console.warn("There are no focusable elements inside the "); - } - } - previousActiveElement.current = ownerDocument == null ? void 0 : ownerDocument.activeElement; - }); - }, [enabled]); - return previousActiveElement; -} -function useFocusLock({ - ownerDocument, - container, - containers, - previousActiveElement -}, enabled) { - let mounted = useIsMounted(); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "focus", - (event) => { - if (!enabled) - return; - if (!mounted.current) - return; - let allContainers = resolveContainers(containers); - if (container.current instanceof HTMLElement) - allContainers.add(container.current); - let previous = previousActiveElement.current; - if (!previous) - return; - let toElement = event.target; - if (toElement && toElement instanceof HTMLElement) { - if (!contains(allContainers, toElement)) { - event.preventDefault(); - event.stopPropagation(); - focusElement(previous); - } else { - previousActiveElement.current = toElement; - focusElement(toElement); + var DEFAULT_OVERLAY_TAG2 = "div"; + var OverlayRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ + function OverlayFn2(props, ref) { + let internalId = useId(); + let { + id = `headlessui-popover-overlay-${internalId}`, + ...theirProps + } = props; + let [{ popoverState }, dispatch] = + usePopoverContext("Popover.Overlay"); + let overlayRef = useSyncRefs(ref); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; + } + return popoverState === 0 /* Open */; + })(); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + dispatch({ type: 1 /* ClosePopover */ }); + }); + let slot = (0, import_react37.useMemo)( + () => ({ open: popoverState === 0 /* Open */ }), + [popoverState] + ); + let ourProps = { + ref: overlayRef, + id, + "aria-hidden": true, + onClick: handleClick, + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OVERLAY_TAG2, + features: OverlayRenderFeatures, + visible, + name: "Popover.Overlay", + }); } - } else { - focusElement(previousActiveElement.current); - } - }, - true - ); -} -function contains(containers, element) { - for (let container of containers) { - if (container.contains(element)) - return true; - } - return false; -} - -// src/components/portal/portal.tsx -var import_react27 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var import_react_dom = __webpack_require__(/*! react-dom */ "react-dom"); - -// src/internal/portal-force-root.tsx -var import_react26 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var ForcePortalRootContext = (0, import_react26.createContext)(false); -function usePortalRoot() { - return (0, import_react26.useContext)(ForcePortalRootContext); -} -function ForcePortalRoot(props) { - return /* @__PURE__ */ import_react26.default.createElement(ForcePortalRootContext.Provider, { value: props.force }, props.children); -} - -// src/components/portal/portal.tsx -function usePortalTarget(ref) { - let forceInRoot = usePortalRoot(); - let groupTarget = (0, import_react27.useContext)(PortalGroupContext); - let ownerDocument = useOwnerDocument(ref); - let [target, setTarget] = (0, import_react27.useState)(() => { - if (!forceInRoot && groupTarget !== null) - return null; - if (env.isServer) - return null; - let existingRoot = ownerDocument == null ? void 0 : ownerDocument.getElementById("headlessui-portal-root"); - if (existingRoot) - return existingRoot; - if (ownerDocument === null) - return null; - let root = ownerDocument.createElement("div"); - root.setAttribute("id", "headlessui-portal-root"); - return ownerDocument.body.appendChild(root); - }); - (0, import_react27.useEffect)(() => { - if (target === null) - return; - if (!(ownerDocument == null ? void 0 : ownerDocument.body.contains(target))) { - ownerDocument == null ? void 0 : ownerDocument.body.appendChild(target); - } - }, [target, ownerDocument]); - (0, import_react27.useEffect)(() => { - if (forceInRoot) - return; - if (groupTarget === null) - return; - setTarget(groupTarget.current); - }, [groupTarget, setTarget, forceInRoot]); - return target; -} -var DEFAULT_PORTAL_TAG = import_react27.Fragment; -function PortalFn(props, ref) { - let theirProps = props; - let internalPortalRootRef = (0, import_react27.useRef)(null); - let portalRef = useSyncRefs( - optionalRef((ref2) => { - internalPortalRootRef.current = ref2; - }), - ref - ); - let ownerDocument = useOwnerDocument(internalPortalRootRef); - let target = usePortalTarget(internalPortalRootRef); - let [element] = (0, import_react27.useState)( - () => { - var _a3; - return env.isServer ? null : (_a3 = ownerDocument == null ? void 0 : ownerDocument.createElement("div")) != null ? _a3 : null; - } - ); - let parent = (0, import_react27.useContext)(PortalParentContext); - let ready = useServerHandoffComplete(); - useIsoMorphicEffect(() => { - if (!target || !element) - return; - if (!target.contains(element)) { - element.setAttribute("data-headlessui-portal", ""); - target.appendChild(element); - } - }, [target, element]); - useIsoMorphicEffect(() => { - if (!element) - return; - if (!parent) - return; - return parent.register(element); - }, [parent, element]); - useOnUnmount(() => { - var _a3; - if (!target || !element) - return; - if (element instanceof Node && target.contains(element)) { - target.removeChild(element); - } - if (target.childNodes.length <= 0) { - (_a3 = target.parentElement) == null ? void 0 : _a3.removeChild(target); - } - }); - if (!ready) - return null; - let ourProps = { ref: portalRef }; - return !target || !element ? null : (0, import_react_dom.createPortal)( - render({ - ourProps, - theirProps, - defaultTag: DEFAULT_PORTAL_TAG, - name: "Portal" - }), - element - ); -} -var DEFAULT_GROUP_TAG = import_react27.Fragment; -var PortalGroupContext = (0, import_react27.createContext)(null); -function GroupFn(props, ref) { - let { target, ...theirProps } = props; - let groupRef = useSyncRefs(ref); - let ourProps = { ref: groupRef }; - return /* @__PURE__ */ import_react27.default.createElement(PortalGroupContext.Provider, { value: target }, render({ - ourProps, - theirProps, - defaultTag: DEFAULT_GROUP_TAG, - name: "Popover.Group" - })); -} -var PortalParentContext = (0, import_react27.createContext)(null); -function useNestedPortals() { - let parent = (0, import_react27.useContext)(PortalParentContext); - let portals = (0, import_react27.useRef)([]); - let register = useEvent((portal) => { - portals.current.push(portal); - if (parent) - parent.register(portal); - return () => unregister(portal); - }); - let unregister = useEvent((portal) => { - let idx = portals.current.indexOf(portal); - if (idx !== -1) - portals.current.splice(idx, 1); - if (parent) - parent.unregister(portal); - }); - let api = (0, import_react27.useMemo)( - () => ({ register, unregister, portals }), - [register, unregister, portals] - ); - return [ - portals, - (0, import_react27.useMemo)(() => { - return function PortalWrapper({ children }) { - return /* @__PURE__ */ import_react27.default.createElement(PortalParentContext.Provider, { value: api }, children); - }; - }, [api]) - ]; -} -var PortalRoot = forwardRefWithAs(PortalFn); -var Group = forwardRefWithAs(GroupFn); -var Portal = Object.assign(PortalRoot, { Group }); - -// src/components/description/description.tsx -var import_react28 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var DescriptionContext = (0, import_react28.createContext)(null); -function useDescriptionContext() { - let context = (0, import_react28.useContext)(DescriptionContext); - if (context === null) { - let err = new Error( - "You used a component, but it is not inside a relevant parent." - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDescriptionContext); - throw err; - } - return context; -} -function useDescriptions() { - let [descriptionIds, setDescriptionIds] = (0, import_react28.useState)([]); - return [ - // The actual id's as string or undefined - descriptionIds.length > 0 ? descriptionIds.join(" ") : void 0, - // The provider component - (0, import_react28.useMemo)(() => { - return function DescriptionProvider(props) { - let register = useEvent((value) => { - setDescriptionIds((existing) => [...existing, value]); - return () => setDescriptionIds((existing) => { - let clone = existing.slice(); - let idx = clone.indexOf(value); - if (idx !== -1) - clone.splice(idx, 1); - return clone; - }); - }); - let contextBag = (0, import_react28.useMemo)( - () => ({ register, slot: props.slot, name: props.name, props: props.props }), - [register, props.slot, props.name, props.props] - ); - return /* @__PURE__ */ import_react28.default.createElement(DescriptionContext.Provider, { value: contextBag }, props.children); - }; - }, [setDescriptionIds]) - ]; -} -var DEFAULT_DESCRIPTION_TAG = "p"; -function DescriptionFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-description-${internalId}`, ...theirProps } = props; - let context = useDescriptionContext(); - let descriptionRef = useSyncRefs(ref); - useIsoMorphicEffect(() => context.register(id), [id, context.register]); - let ourProps = { ref: descriptionRef, ...context.props, id }; - return render({ - ourProps, - theirProps, - slot: context.slot || {}, - defaultTag: DEFAULT_DESCRIPTION_TAG, - name: context.name || "Description" - }); -} -var DescriptionRoot = forwardRefWithAs(DescriptionFn); -var Description = Object.assign(DescriptionRoot, { - // -}); - -// src/internal/stack-context.tsx -var import_react29 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var StackContext = (0, import_react29.createContext)(() => { -}); -StackContext.displayName = "StackContext"; -function useStackContext() { - return (0, import_react29.useContext)(StackContext); -} -function StackProvider({ - children, - onUpdate, - type, - element, - enabled -}) { - let parentUpdate = useStackContext(); - let notify = useEvent((...args) => { - onUpdate == null ? void 0 : onUpdate(...args); - parentUpdate(...args); - }); - useIsoMorphicEffect(() => { - let shouldNotify = enabled === void 0 || enabled === true; - shouldNotify && notify(0 /* Add */, type, element); - return () => { - shouldNotify && notify(1 /* Remove */, type, element); - }; - }, [notify, type, element, enabled]); - return /* @__PURE__ */ import_react29.default.createElement(StackContext.Provider, { value: notify }, children); -} - -// src/use-sync-external-store-shim/index.ts -var React11 = __toESM(__webpack_require__(/*! react */ "react"), 1); - -// src/use-sync-external-store-shim/useSyncExternalStoreShimClient.ts -var React10 = __toESM(__webpack_require__(/*! react */ "react"), 1); -function isPolyfill(x, y) { - return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; -} -var is = typeof Object.is === "function" ? Object.is : isPolyfill; -var { useState: useState8, useEffect: useEffect14, useLayoutEffect: useLayoutEffect2, useDebugValue } = React10; -var didWarnOld18Alpha = false; -var didWarnUncachedGetSnapshot = false; -function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - if (true) { - if (!didWarnOld18Alpha) { - if ("startTransition" in React10) { - didWarnOld18Alpha = true; - console.error( - "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." - ); - } - } - } - const value = getSnapshot(); - if (true) { - if (!didWarnUncachedGetSnapshot) { - const cachedValue = getSnapshot(); - if (!is(value, cachedValue)) { - console.error("The result of getSnapshot should be cached to avoid an infinite loop"); - didWarnUncachedGetSnapshot = true; - } - } - } - const [{ inst }, forceUpdate] = useState8({ inst: { value, getSnapshot } }); - useLayoutEffect2(() => { - inst.value = value; - inst.getSnapshot = getSnapshot; - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - }, [subscribe, value, getSnapshot]); - useEffect14(() => { - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - const handleStoreChange = () => { - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - }; - return subscribe(handleStoreChange); - }, [subscribe]); - useDebugValue(value); - return value; -} -function checkIfSnapshotChanged(inst) { - const latestGetSnapshot = inst.getSnapshot; - const prevValue = inst.value; - try { - const nextValue = latestGetSnapshot(); - return !is(prevValue, nextValue); - } catch (error) { - return true; - } -} - -// src/use-sync-external-store-shim/useSyncExternalStoreShimServer.ts -function useSyncExternalStore2(subscribe, getSnapshot, getServerSnapshot) { - return getSnapshot(); -} - -// src/use-sync-external-store-shim/index.ts -var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); -var isServerEnvironment = !canUseDOM; -var shim = isServerEnvironment ? useSyncExternalStore2 : useSyncExternalStore; -var useSyncExternalStore3 = "useSyncExternalStore" in React11 ? ((r) => r.useSyncExternalStore)(React11) : shim; - -// src/hooks/use-store.ts -function useStore(store) { - return useSyncExternalStore3(store.subscribe, store.getSnapshot, store.getSnapshot); -} - -// src/utils/store.ts -function createStore(initial, actions) { - let state = initial(); - let listeners = /* @__PURE__ */ new Set(); - return { - getSnapshot() { - return state; - }, - subscribe(onChange) { - listeners.add(onChange); - return () => listeners.delete(onChange); - }, - dispatch(key, ...args) { - let newState = actions[key].call(state, ...args); - if (newState) { - state = newState; - listeners.forEach((listener) => listener()); - } - } - }; -} - -// src/hooks/document-overflow/adjust-scrollbar-padding.ts -function adjustScrollbarPadding() { - let scrollbarWidthBefore; - return { - before({ doc }) { - var _a3; - let documentElement = doc.documentElement; - let ownerWindow = (_a3 = doc.defaultView) != null ? _a3 : window; - scrollbarWidthBefore = ownerWindow.innerWidth - documentElement.clientWidth; - }, - after({ doc, d }) { - let documentElement = doc.documentElement; - let scrollbarWidthAfter = documentElement.clientWidth - documentElement.offsetWidth; - let scrollbarWidth = scrollbarWidthBefore - scrollbarWidthAfter; - d.style(documentElement, "paddingRight", `${scrollbarWidth}px`); - } - }; -} - -// src/hooks/document-overflow/handle-ios-locking.ts -function handleIOSLocking() { - if (!isIOS()) { - return {}; - } - let scrollPosition; - return { - before() { - scrollPosition = window.pageYOffset; - }, - after({ doc, d, meta }) { - function inAllowedContainer(el) { - return meta.containers.flatMap((resolve) => resolve()).some((container) => container.contains(el)); - } - d.style(doc.body, "marginTop", `-${scrollPosition}px`); - window.scrollTo(0, 0); - let scrollToElement = null; - d.addEventListener( - doc, - "click", - (e) => { - if (!(e.target instanceof HTMLElement)) { - return; - } - try { - let anchor = e.target.closest("a"); - if (!anchor) - return; - let { hash } = new URL(anchor.href); - let el = doc.querySelector(hash); - if (el && !inAllowedContainer(el)) { - scrollToElement = el; + var DEFAULT_PANEL_TAG3 = "div"; + var PanelRenderFeatures2 = 1 /* RenderStrategy */ | 2; /* Static */ + function PanelFn3(props, ref) { + let internalId = useId(); + let { + id = `headlessui-popover-panel-${internalId}`, + focus = false, + ...theirProps + } = props; + let [state, dispatch] = usePopoverContext("Popover.Panel"); + let { close, isPortalled } = usePopoverAPIContext("Popover.Panel"); + let beforePanelSentinelId = `headlessui-focus-sentinel-before-${useId()}`; + let afterPanelSentinelId = `headlessui-focus-sentinel-after-${useId()}`; + let internalPanelRef = (0, import_react37.useRef)(null); + let panelRef = useSyncRefs(internalPanelRef, ref, (panel) => { + dispatch({ type: 4 /* SetPanel */, panel }); + }); + let ownerDocument = useOwnerDocument(internalPanelRef); + useIsoMorphicEffect(() => { + dispatch({ type: 5 /* SetPanelId */, panelId: id }); + return () => { + dispatch({ type: 5 /* SetPanelId */, panelId: null }); + }; + }, [id, dispatch]); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; } - } catch (err) { - } - }, - true - ); - d.addEventListener( - doc, - "touchmove", - (e) => { - if (e.target instanceof HTMLElement && !inAllowedContainer(e.target)) { - e.preventDefault(); - } - }, - { passive: false } - ); - d.add(() => { - window.scrollTo(0, window.pageYOffset + scrollPosition); - if (scrollToElement && scrollToElement.isConnected) { - scrollToElement.scrollIntoView({ block: "nearest" }); - scrollToElement = null; - } - }); - } - }; -} - -// src/hooks/document-overflow/prevent-scroll.ts -function preventScroll() { - return { - before({ doc, d }) { - d.style(doc.documentElement, "overflow", "hidden"); - } - }; -} - -// src/hooks/document-overflow/overflow-store.ts -function buildMeta(fns) { - let tmp = {}; - for (let fn of fns) { - Object.assign(tmp, fn(tmp)); - } - return tmp; -} -var overflows = createStore(() => /* @__PURE__ */ new Map(), { - PUSH(doc, meta) { - var _a3; - let entry = (_a3 = this.get(doc)) != null ? _a3 : { - doc, - count: 0, - d: disposables(), - meta: /* @__PURE__ */ new Set() - }; - entry.count++; - entry.meta.add(meta); - this.set(doc, entry); - return this; - }, - POP(doc, meta) { - let entry = this.get(doc); - if (entry) { - entry.count--; - entry.meta.delete(meta); - } - return this; - }, - SCROLL_PREVENT({ doc, d, meta }) { - let ctx = { - doc, - d, - meta: buildMeta(meta) - }; - let steps = [ - handleIOSLocking(), - adjustScrollbarPadding(), - preventScroll() - ]; - steps.forEach(({ before }) => before == null ? void 0 : before(ctx)); - steps.forEach(({ after }) => after == null ? void 0 : after(ctx)); - }, - SCROLL_ALLOW({ d }) { - d.dispose(); - }, - TEARDOWN({ doc }) { - this.delete(doc); - } -}); -overflows.subscribe(() => { - let docs = overflows.getSnapshot(); - let styles = /* @__PURE__ */ new Map(); - for (let [doc] of docs) { - styles.set(doc, doc.documentElement.style.overflow); - } - for (let entry of docs.values()) { - let isHidden = styles.get(entry.doc) === "hidden"; - let isLocked = entry.count !== 0; - let willChange = isLocked && !isHidden || !isLocked && isHidden; - if (willChange) { - overflows.dispatch(entry.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", entry); - } - if (entry.count === 0) { - overflows.dispatch("TEARDOWN", entry); - } - } -}); - -// src/hooks/document-overflow/use-document-overflow.ts -function useDocumentOverflowLockedEffect(doc, shouldBeLocked, meta) { - let store = useStore(overflows); - let entry = doc ? store.get(doc) : void 0; - let locked = entry ? entry.count > 0 : false; - useIsoMorphicEffect(() => { - if (!doc || !shouldBeLocked) { - return; - } - overflows.dispatch("PUSH", doc, meta); - return () => overflows.dispatch("POP", doc, meta); - }, [shouldBeLocked, doc]); - return locked; -} - -// src/hooks/use-inert.tsx -var originals = /* @__PURE__ */ new Map(); -var counts = /* @__PURE__ */ new Map(); -function useInert(node, enabled = true) { - useIsoMorphicEffect(() => { - var _a3; - if (!enabled) - return; - let element = typeof node === "function" ? node() : node.current; - if (!element) - return; - function cleanup() { - var _a4; - if (!element) - return; - let count2 = (_a4 = counts.get(element)) != null ? _a4 : 1; - if (count2 === 1) - counts.delete(element); - else - counts.set(element, count2 - 1); - if (count2 !== 1) - return; - let original = originals.get(element); - if (!original) - return; - if (original["aria-hidden"] === null) - element.removeAttribute("aria-hidden"); - else - element.setAttribute("aria-hidden", original["aria-hidden"]); - element.inert = original.inert; - originals.delete(element); - } - let count = (_a3 = counts.get(element)) != null ? _a3 : 0; - counts.set(element, count + 1); - if (count !== 0) - return cleanup; - originals.set(element, { - "aria-hidden": element.getAttribute("aria-hidden"), - inert: element.inert - }); - element.setAttribute("aria-hidden", "true"); - element.inert = true; - return cleanup; - }, [node, enabled]); -} - -// src/hooks/use-root-containers.tsx -var import_react30 = __toESM(__webpack_require__(/*! react */ "react"), 1); -function useRootContainers({ - defaultContainers = [], - portals -} = {}) { - let mainTreeNodeRef = (0, import_react30.useRef)(null); - let ownerDocument = useOwnerDocument(mainTreeNodeRef); - let resolveContainers2 = useEvent(() => { - var _a3; - let containers = []; - for (let container of defaultContainers) { - if (container === null) - continue; - if (container instanceof HTMLElement) { - containers.push(container); - } else if ("current" in container && container.current instanceof HTMLElement) { - containers.push(container.current); - } - } - if (portals == null ? void 0 : portals.current) { - for (let portal of portals.current) { - containers.push(portal); - } - } - for (let container of (_a3 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("html > *, body > *")) != null ? _a3 : []) { - if (container === document.body) - continue; - if (container === document.head) - continue; - if (!(container instanceof HTMLElement)) - continue; - if (container.id === "headlessui-portal-root") - continue; - if (container.contains(mainTreeNodeRef.current)) - continue; - if (containers.some((defaultContainer) => container.contains(defaultContainer))) - continue; - containers.push(container); - } - return containers; - }); - return { - resolveContainers: resolveContainers2, - contains: useEvent( - (element) => resolveContainers2().some((container) => container.contains(element)) - ), - mainTreeNodeRef, - MainTreeNode: (0, import_react30.useMemo)(() => { - return function MainTreeNode() { - return /* @__PURE__ */ import_react30.default.createElement(Hidden, { features: 4 /* Hidden */, ref: mainTreeNodeRef }); - }; - }, [mainTreeNodeRef]) - }; -} - -// src/components/dialog/dialog.tsx -var reducers2 = { - [0 /* SetTitleId */](state, action) { - if (state.titleId === action.id) - return state; - return { ...state, titleId: action.id }; - } -}; -var DialogContext = (0, import_react31.createContext)(null); -DialogContext.displayName = "DialogContext"; -function useDialogContext(component) { - let context = (0, import_react31.useContext)(DialogContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDialogContext); - throw err; - } - return context; -} -function useScrollLock(ownerDocument, enabled, resolveAllowedContainers = () => [document.body]) { - useDocumentOverflowLockedEffect(ownerDocument, enabled, (meta) => { - var _a3; - return { - containers: [...(_a3 = meta.containers) != null ? _a3 : [], resolveAllowedContainers] - }; - }); -} -function stateReducer2(state, action) { - return match(action.type, reducers2, state, action); -} -var DEFAULT_DIALOG_TAG = "div"; -var DialogRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; -function DialogFn(props, ref) { - var _a3; - let internalId = useId(); - let { - id = `headlessui-dialog-${internalId}`, - open, - onClose, - initialFocus, - __demoMode = false, - ...theirProps - } = props; - let [nestedDialogCount, setNestedDialogCount] = (0, import_react31.useState)(0); - let usesOpenClosedState = useOpenClosed(); - if (open === void 0 && usesOpenClosedState !== null) { - open = (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - let internalDialogRef = (0, import_react31.useRef)(null); - let dialogRef = useSyncRefs(internalDialogRef, ref); - let ownerDocument = useOwnerDocument(internalDialogRef); - let hasOpen = props.hasOwnProperty("open") || usesOpenClosedState !== null; - let hasOnClose = props.hasOwnProperty("onClose"); - if (!hasOpen && !hasOnClose) { - throw new Error( - `You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.` - ); - } - if (!hasOpen) { - throw new Error( - `You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.` - ); - } - if (!hasOnClose) { - throw new Error( - `You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.` - ); - } - if (typeof open !== "boolean") { - throw new Error( - `You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${open}` - ); - } - if (typeof onClose !== "function") { - throw new Error( - `You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${onClose}` - ); - } - let dialogState = open ? 0 /* Open */ : 1 /* Closed */; - let [state, dispatch] = (0, import_react31.useReducer)(stateReducer2, { - titleId: null, - descriptionId: null, - panelRef: (0, import_react31.createRef)() - }); - let close = useEvent(() => onClose(false)); - let setTitleId = useEvent((id2) => dispatch({ type: 0 /* SetTitleId */, id: id2 })); - let ready = useServerHandoffComplete(); - let enabled = ready ? __demoMode ? false : dialogState === 0 /* Open */ : false; - let hasNestedDialogs = nestedDialogCount > 1; - let hasParentDialog = (0, import_react31.useContext)(DialogContext) !== null; - let [portals, PortalWrapper] = useNestedPortals(); - let { - resolveContainers: resolveRootContainers, - mainTreeNodeRef, - MainTreeNode - } = useRootContainers({ - portals, - defaultContainers: [(_a3 = state.panelRef.current) != null ? _a3 : internalDialogRef.current] - }); - let position = !hasNestedDialogs ? "leaf" : "parent"; - let isClosing = usesOpenClosedState !== null ? (usesOpenClosedState & 4 /* Closing */) === 4 /* Closing */ : false; - let inertOthersEnabled = (() => { - if (hasParentDialog) - return false; - if (isClosing) - return false; - return enabled; - })(); - let resolveRootOfMainTreeNode = (0, import_react31.useCallback)(() => { - var _a4, _b; - return (_b = Array.from((_a4 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("body > *")) != null ? _a4 : []).find((root) => { - if (root.id === "headlessui-portal-root") - return false; - return root.contains(mainTreeNodeRef.current) && root instanceof HTMLElement; - })) != null ? _b : null; - }, [mainTreeNodeRef]); - useInert(resolveRootOfMainTreeNode, inertOthersEnabled); - let inertParentDialogs = (() => { - if (hasNestedDialogs) - return true; - return enabled; - })(); - let resolveRootOfParentDialog = (0, import_react31.useCallback)(() => { - var _a4, _b; - return (_b = Array.from((_a4 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("[data-headlessui-portal]")) != null ? _a4 : []).find( - (root) => root.contains(mainTreeNodeRef.current) && root instanceof HTMLElement - )) != null ? _b : null; - }, [mainTreeNodeRef]); - useInert(resolveRootOfParentDialog, inertParentDialogs); - let outsideClickEnabled = (() => { - if (!enabled) - return false; - if (hasNestedDialogs) - return false; - return true; - })(); - useOutsideClick(resolveRootContainers, close, outsideClickEnabled); - let escapeToCloseEnabled = (() => { - if (hasNestedDialogs) - return false; - if (dialogState !== 0 /* Open */) - return false; - return true; - })(); - useEventListener(ownerDocument == null ? void 0 : ownerDocument.defaultView, "keydown", (event) => { - if (!escapeToCloseEnabled) - return; - if (event.defaultPrevented) - return; - if (event.key !== "Escape" /* Escape */) - return; - event.preventDefault(); - event.stopPropagation(); - close(); - }); - let scrollLockEnabled = (() => { - if (isClosing) - return false; - if (dialogState !== 0 /* Open */) - return false; - if (hasParentDialog) - return false; - return true; - })(); - useScrollLock(ownerDocument, scrollLockEnabled, resolveRootContainers); - (0, import_react31.useEffect)(() => { - if (dialogState !== 0 /* Open */) - return; - if (!internalDialogRef.current) - return; - let observer = new ResizeObserver((entries) => { - for (let entry of entries) { - let rect = entry.target.getBoundingClientRect(); - if (rect.x === 0 && rect.y === 0 && rect.width === 0 && rect.height === 0) { - close(); + return state.popoverState === 0 /* Open */; + })(); + let handleKeyDown = useEvent((event) => { + var _a3; + switch (event.key) { + case "Escape" /* Escape */: + if (state.popoverState !== 0 /* Open */) return; + if (!internalPanelRef.current) return; + if ( + (ownerDocument == null + ? void 0 + : ownerDocument.activeElement) && + !internalPanelRef.current.contains( + ownerDocument.activeElement + ) + ) { + return; + } + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* ClosePopover */ }); + (_a3 = state.button) == null ? void 0 : _a3.focus(); + break; + } + }); + (0, import_react37.useEffect)(() => { + var _a3; + if (props.static) return; + if ( + state.popoverState === 1 /* Closed */ && + ((_a3 = props.unmount) != null ? _a3 : true) + ) { + dispatch({ type: 4 /* SetPanel */, panel: null }); + } + }, [state.popoverState, props.unmount, props.static, dispatch]); + (0, import_react37.useEffect)(() => { + if (state.__demoMode) return; + if (!focus) return; + if (state.popoverState !== 0 /* Open */) return; + if (!internalPanelRef.current) return; + let activeElement = + ownerDocument == null ? void 0 : ownerDocument.activeElement; + if (internalPanelRef.current.contains(activeElement)) return; + focusIn(internalPanelRef.current, 1 /* First */); + }, [state.__demoMode, focus, internalPanelRef, state.popoverState]); + let slot = (0, import_react37.useMemo)( + () => ({ open: state.popoverState === 0 /* Open */, close }), + [state, close] + ); + let ourProps = { + ref: panelRef, + id, + onKeyDown: handleKeyDown, + onBlur: + focus && state.popoverState === 0 /* Open */ + ? (event) => { + var _a3, _b, _c, _d, _e; + let el = event.relatedTarget; + if (!el) return; + if (!internalPanelRef.current) return; + if ( + (_a3 = internalPanelRef.current) == null + ? void 0 + : _a3.contains(el) + ) + return; + dispatch({ type: 1 /* ClosePopover */ }); + if ( + ((_c = + (_b = state.beforePanelSentinel.current) == null + ? void 0 + : _b.contains) == null + ? void 0 + : _c.call(_b, el)) || + ((_e = + (_d = state.afterPanelSentinel.current) == null + ? void 0 + : _d.contains) == null + ? void 0 + : _e.call(_d, el)) + ) { + el.focus({ preventScroll: true }); + } + } + : void 0, + tabIndex: -1, + }; + let direction = useTabDirection(); + let handleBeforeFocus = useEvent(() => { + let el = internalPanelRef.current; + if (!el) return; + function run() { + match(direction.current, { + [0 /* Forwards */]: () => { + var _a3; + let result = focusIn(el, 1 /* First */); + if (result === 0 /* Error */) { + (_a3 = state.afterPanelSentinel.current) == null + ? void 0 + : _a3.focus(); + } + }, + [1 /* Backwards */]: () => { + var _a3; + (_a3 = state.button) == null + ? void 0 + : _a3.focus({ preventScroll: true }); + }, + }); + } + if (false) { + } else { + run(); + } + }); + let handleAfterFocus = useEvent(() => { + let el = internalPanelRef.current; + if (!el) return; + function run() { + match(direction.current, { + [0 /* Forwards */]: () => { + var _a3; + if (!state.button) return; + let elements = getFocusableElements(); + let idx = elements.indexOf(state.button); + let before = elements.slice(0, idx + 1); + let after = elements.slice(idx + 1); + let combined = [...after, ...before]; + for (let element of combined.slice()) { + if ( + element.dataset.headlessuiFocusGuard === "true" || + ((_a3 = state.panel) == null + ? void 0 + : _a3.contains(element)) + ) { + let idx2 = combined.indexOf(element); + if (idx2 !== -1) combined.splice(idx2, 1); + } + } + focusIn(combined, 1 /* First */, { sorted: false }); + }, + [1 /* Backwards */]: () => { + var _a3; + let result = focusIn(el, 2 /* Previous */); + if (result === 0 /* Error */) { + (_a3 = state.button) == null ? void 0 : _a3.focus(); + } + }, + }); + } + if (false) { + } else { + run(); + } + }); + return /* @__PURE__ */ import_react37.default.createElement( + PopoverPanelContext.Provider, + { value: id }, + visible && + isPortalled && + /* @__PURE__ */ import_react37.default.createElement(Hidden, { + id: beforePanelSentinelId, + ref: state.beforePanelSentinel, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleBeforeFocus, + }), + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG3, + features: PanelRenderFeatures2, + visible, + name: "Popover.Panel", + }), + visible && + isPortalled && + /* @__PURE__ */ import_react37.default.createElement(Hidden, { + id: afterPanelSentinelId, + ref: state.afterPanelSentinel, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleAfterFocus, + }) + ); + } + var DEFAULT_GROUP_TAG2 = "div"; + function GroupFn2(props, ref) { + let internalGroupRef = (0, import_react37.useRef)(null); + let groupRef = useSyncRefs(internalGroupRef, ref); + let [popovers, setPopovers] = (0, import_react37.useState)([]); + let unregisterPopover = useEvent((registerbag) => { + setPopovers((existing) => { + let idx = existing.indexOf(registerbag); + if (idx !== -1) { + let clone = existing.slice(); + clone.splice(idx, 1); + return clone; + } + return existing; + }); + }); + let registerPopover = useEvent((registerbag) => { + setPopovers((existing) => [...existing, registerbag]); + return () => unregisterPopover(registerbag); + }); + let isFocusWithinPopoverGroup = useEvent(() => { + var _a3; + let ownerDocument = getOwnerDocument(internalGroupRef); + if (!ownerDocument) return false; + let element = ownerDocument.activeElement; + if ( + (_a3 = internalGroupRef.current) == null + ? void 0 + : _a3.contains(element) + ) + return true; + return popovers.some((bag) => { + var _a4, _b; + return ( + ((_a4 = ownerDocument.getElementById(bag.buttonId.current)) == + null + ? void 0 + : _a4.contains(element)) || + ((_b = ownerDocument.getElementById(bag.panelId.current)) == + null + ? void 0 + : _b.contains(element)) + ); + }); + }); + let closeOthers = useEvent((buttonId) => { + for (let popover of popovers) { + if (popover.buttonId.current !== buttonId) popover.close(); + } + }); + let contextBag = (0, import_react37.useMemo)( + () => ({ + registerPopover, + unregisterPopover, + isFocusWithinPopoverGroup, + closeOthers, + }), + [ + registerPopover, + unregisterPopover, + isFocusWithinPopoverGroup, + closeOthers, + ] + ); + let slot = (0, import_react37.useMemo)(() => ({}), []); + let theirProps = props; + let ourProps = { ref: groupRef }; + return /* @__PURE__ */ import_react37.default.createElement( + PopoverGroupContext.Provider, + { value: contextBag }, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_GROUP_TAG2, + name: "Popover.Group", + }) + ); } - } - }); - observer.observe(internalDialogRef.current); - return () => observer.disconnect(); - }, [dialogState, internalDialogRef, close]); - let [describedby, DescriptionProvider] = useDescriptions(); - let contextBag = (0, import_react31.useMemo)( - () => [{ dialogState, close, setTitleId }, state], - [dialogState, state, close, setTitleId] - ); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: dialogRef, - id, - role: "dialog", - "aria-modal": dialogState === 0 /* Open */ ? true : void 0, - "aria-labelledby": state.titleId, - "aria-describedby": describedby - }; - return /* @__PURE__ */ import_react31.default.createElement( - StackProvider, - { - type: "Dialog", - enabled: dialogState === 0 /* Open */, - element: internalDialogRef, - onUpdate: useEvent((message, type) => { - if (type !== "Dialog") - return; - match(message, { - [0 /* Add */]: () => setNestedDialogCount((count) => count + 1), - [1 /* Remove */]: () => setNestedDialogCount((count) => count - 1) - }); - }) - }, - /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: true }, /* @__PURE__ */ import_react31.default.createElement(Portal, null, /* @__PURE__ */ import_react31.default.createElement(DialogContext.Provider, { value: contextBag }, /* @__PURE__ */ import_react31.default.createElement(Portal.Group, { target: internalDialogRef }, /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: false }, /* @__PURE__ */ import_react31.default.createElement(DescriptionProvider, { slot, name: "Dialog.Description" }, /* @__PURE__ */ import_react31.default.createElement( - FocusTrap, - { - initialFocus, - containers: resolveRootContainers, - features: enabled ? match(position, { - parent: FocusTrap.features.RestoreFocus, - leaf: FocusTrap.features.All & ~FocusTrap.features.FocusLock - }) : FocusTrap.features.None - }, - /* @__PURE__ */ import_react31.default.createElement(PortalWrapper, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_DIALOG_TAG, - features: DialogRenderFeatures, - visible: dialogState === 0 /* Open */, - name: "Dialog" - })) - ))))))), - /* @__PURE__ */ import_react31.default.createElement(MainTreeNode, null) - ); -} -var DEFAULT_OVERLAY_TAG = "div"; -function OverlayFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-overlay-${internalId}`, ...theirProps } = props; - let [{ dialogState, close }] = useDialogContext("Dialog.Overlay"); - let overlayRef = useSyncRefs(ref); - let handleClick = useEvent((event) => { - if (event.target !== event.currentTarget) - return; - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - event.preventDefault(); - event.stopPropagation(); - close(); - }); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: overlayRef, - id, - "aria-hidden": true, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OVERLAY_TAG, - name: "Dialog.Overlay" - }); -} -var DEFAULT_BACKDROP_TAG = "div"; -function BackdropFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-backdrop-${internalId}`, ...theirProps } = props; - let [{ dialogState }, state] = useDialogContext("Dialog.Backdrop"); - let backdropRef = useSyncRefs(ref); - (0, import_react31.useEffect)(() => { - if (state.panelRef.current === null) { - throw new Error( - `A component is being used, but a component is missing.` - ); - } - }, [state.panelRef]); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: backdropRef, - id, - "aria-hidden": true - }; - return /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: true }, /* @__PURE__ */ import_react31.default.createElement(Portal, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BACKDROP_TAG, - name: "Dialog.Backdrop" - }))); -} -var DEFAULT_PANEL_TAG = "div"; -function PanelFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-panel-${internalId}`, ...theirProps } = props; - let [{ dialogState }, state] = useDialogContext("Dialog.Panel"); - let panelRef = useSyncRefs(ref, state.panelRef); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let handleClick = useEvent((event) => { - event.stopPropagation(); - }); - let ourProps = { - ref: panelRef, - id, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG, - name: "Dialog.Panel" - }); -} -var DEFAULT_TITLE_TAG = "h2"; -function TitleFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-title-${internalId}`, ...theirProps } = props; - let [{ dialogState, setTitleId }] = useDialogContext("Dialog.Title"); - let titleRef = useSyncRefs(ref); - (0, import_react31.useEffect)(() => { - setTitleId(id); - return () => setTitleId(null); - }, [id, setTitleId]); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { ref: titleRef, id }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_TITLE_TAG, - name: "Dialog.Title" - }); -} -var DialogRoot = forwardRefWithAs(DialogFn); -var Backdrop = forwardRefWithAs(BackdropFn); -var Panel = forwardRefWithAs(PanelFn); -var Overlay = forwardRefWithAs(OverlayFn); -var Title = forwardRefWithAs(TitleFn); -var Dialog = Object.assign(DialogRoot, { - Backdrop, - Panel, - Overlay, - Title, - Description -}); - -// src/components/disclosure/disclosure.tsx -var import_react33 = __toESM(__webpack_require__(/*! react */ "react"), 1); - -// src/utils/start-transition.ts -var import_react32 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var _a2; -var startTransition = ( - // Prefer React's `startTransition` if it's available. - // @ts-expect-error - `startTransition` doesn't exist in React < 18. - (_a2 = import_react32.default.startTransition) != null ? _a2 : function startTransition2(cb) { - cb(); - } -); - -// src/components/disclosure/disclosure.tsx -var reducers3 = { - [0 /* ToggleDisclosure */]: (state) => ({ - ...state, - disclosureState: match(state.disclosureState, { - [0 /* Open */]: 1 /* Closed */, - [1 /* Closed */]: 0 /* Open */ - }) - }), - [1 /* CloseDisclosure */]: (state) => { - if (state.disclosureState === 1 /* Closed */) - return state; - return { ...state, disclosureState: 1 /* Closed */ }; - }, - [4 /* LinkPanel */](state) { - if (state.linkedPanel === true) - return state; - return { ...state, linkedPanel: true }; - }, - [5 /* UnlinkPanel */](state) { - if (state.linkedPanel === false) - return state; - return { ...state, linkedPanel: false }; - }, - [2 /* SetButtonId */](state, action) { - if (state.buttonId === action.buttonId) - return state; - return { ...state, buttonId: action.buttonId }; - }, - [3 /* SetPanelId */](state, action) { - if (state.panelId === action.panelId) - return state; - return { ...state, panelId: action.panelId }; - } -}; -var DisclosureContext = (0, import_react33.createContext)(null); -DisclosureContext.displayName = "DisclosureContext"; -function useDisclosureContext(component) { - let context = (0, import_react33.useContext)(DisclosureContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDisclosureContext); - throw err; - } - return context; -} -var DisclosureAPIContext = (0, import_react33.createContext)(null); -DisclosureAPIContext.displayName = "DisclosureAPIContext"; -function useDisclosureAPIContext(component) { - let context = (0, import_react33.useContext)(DisclosureAPIContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDisclosureAPIContext); - throw err; - } - return context; -} -var DisclosurePanelContext = (0, import_react33.createContext)(null); -DisclosurePanelContext.displayName = "DisclosurePanelContext"; -function useDisclosurePanelContext() { - return (0, import_react33.useContext)(DisclosurePanelContext); -} -function stateReducer3(state, action) { - return match(action.type, reducers3, state, action); -} -var DEFAULT_DISCLOSURE_TAG = import_react33.Fragment; -function DisclosureFn(props, ref) { - let { defaultOpen = false, ...theirProps } = props; - let internalDisclosureRef = (0, import_react33.useRef)(null); - let disclosureRef = useSyncRefs( - ref, - optionalRef( - (ref2) => { - internalDisclosureRef.current = ref2; - }, - props.as === void 0 || // @ts-expect-error The `as` prop _can_ be a Fragment - props.as === import_react33.Fragment - ) - ); - let panelRef = (0, import_react33.useRef)(null); - let buttonRef = (0, import_react33.useRef)(null); - let reducerBag = (0, import_react33.useReducer)(stateReducer3, { - disclosureState: defaultOpen ? 0 /* Open */ : 1 /* Closed */, - linkedPanel: false, - buttonRef, - panelRef, - buttonId: null, - panelId: null - }); - let [{ disclosureState, buttonId }, dispatch] = reducerBag; - let close = useEvent((focusableElement) => { - dispatch({ type: 1 /* CloseDisclosure */ }); - let ownerDocument = getOwnerDocument(internalDisclosureRef); - if (!ownerDocument) - return; - if (!buttonId) - return; - let restoreElement = (() => { - if (!focusableElement) - return ownerDocument.getElementById(buttonId); - if (focusableElement instanceof HTMLElement) - return focusableElement; - if (focusableElement.current instanceof HTMLElement) - return focusableElement.current; - return ownerDocument.getElementById(buttonId); - })(); - restoreElement == null ? void 0 : restoreElement.focus(); - }); - let api = (0, import_react33.useMemo)(() => ({ close }), [close]); - let slot = (0, import_react33.useMemo)( - () => ({ open: disclosureState === 0 /* Open */, close }), - [disclosureState, close] - ); - let ourProps = { - ref: disclosureRef - }; - return /* @__PURE__ */ import_react33.default.createElement(DisclosureContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react33.default.createElement(DisclosureAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react33.default.createElement( - OpenClosedProvider, - { - value: match(disclosureState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_DISCLOSURE_TAG, - name: "Disclosure" - }) - ))); -} -var DEFAULT_BUTTON_TAG2 = "button"; -function ButtonFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-disclosure-button-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useDisclosureContext("Disclosure.Button"); - let panelContext = useDisclosurePanelContext(); - let isWithinPanel = panelContext === null ? false : panelContext === state.panelId; - let internalButtonRef = (0, import_react33.useRef)(null); - let buttonRef = useSyncRefs(internalButtonRef, ref, !isWithinPanel ? state.buttonRef : null); - (0, import_react33.useEffect)(() => { - if (isWithinPanel) - return; - dispatch({ type: 2 /* SetButtonId */, buttonId: id }); - return () => { - dispatch({ type: 2 /* SetButtonId */, buttonId: null }); - }; - }, [id, dispatch, isWithinPanel]); - let handleKeyDown = useEvent((event) => { - var _a3; - if (isWithinPanel) { - if (state.disclosureState === 1 /* Closed */) - return; - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* ToggleDisclosure */ }); - (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); - break; - } - } else { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* ToggleDisclosure */ }); - break; - } - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - var _a3; - if (isDisabledReactIssue7711(event.currentTarget)) - return; - if (props.disabled) - return; - if (isWithinPanel) { - dispatch({ type: 0 /* ToggleDisclosure */ }); - (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); - } else { - dispatch({ type: 0 /* ToggleDisclosure */ }); - } - }); - let slot = (0, import_react33.useMemo)( - () => ({ open: state.disclosureState === 0 /* Open */ }), - [state] - ); - let type = useResolveButtonType(props, internalButtonRef); - let ourProps = isWithinPanel ? { ref: buttonRef, type, onKeyDown: handleKeyDown, onClick: handleClick } : { - ref: buttonRef, - id, - type, - "aria-expanded": props.disabled ? void 0 : state.disclosureState === 0 /* Open */, - "aria-controls": state.linkedPanel ? state.panelId : void 0, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG2, - name: "Disclosure.Button" - }); -} -var DEFAULT_PANEL_TAG2 = "div"; -var PanelRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; -function PanelFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-disclosure-panel-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useDisclosureContext("Disclosure.Panel"); - let { close } = useDisclosureAPIContext("Disclosure.Panel"); - let panelRef = useSyncRefs(ref, state.panelRef, (el) => { - startTransition(() => dispatch({ type: el ? 4 /* LinkPanel */ : 5 /* UnlinkPanel */ })); - }); - (0, import_react33.useEffect)(() => { - dispatch({ type: 3 /* SetPanelId */, panelId: id }); - return () => { - dispatch({ type: 3 /* SetPanelId */, panelId: null }); - }; - }, [id, dispatch]); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return state.disclosureState === 0 /* Open */; - })(); - let slot = (0, import_react33.useMemo)( - () => ({ open: state.disclosureState === 0 /* Open */, close }), - [state, close] - ); - let ourProps = { - ref: panelRef, - id - }; - return /* @__PURE__ */ import_react33.default.createElement(DisclosurePanelContext.Provider, { value: state.panelId }, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG2, - features: PanelRenderFeatures, - visible, - name: "Disclosure.Panel" - })); -} -var DisclosureRoot = forwardRefWithAs(DisclosureFn); -var Button2 = forwardRefWithAs(ButtonFn2); -var Panel2 = forwardRefWithAs(PanelFn2); -var Disclosure = Object.assign(DisclosureRoot, { Button: Button2, Panel: Panel2 }); - -// src/components/listbox/listbox.tsx -var import_react35 = __toESM(__webpack_require__(/*! react */ "react"), 1); - -// src/hooks/use-text-value.ts -var import_react34 = __webpack_require__(/*! react */ "react"); - -// src/utils/get-text-value.ts -var emojiRegex = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; -function getTextContents(element) { - var _a3, _b; - let currentInnerText = (_a3 = element.innerText) != null ? _a3 : ""; - let copy = element.cloneNode(true); - if (!(copy instanceof HTMLElement)) { - return currentInnerText; - } - let dropped = false; - for (let child of copy.querySelectorAll('[hidden],[aria-hidden],[role="img"]')) { - child.remove(); - dropped = true; - } - let value = dropped ? (_b = copy.innerText) != null ? _b : "" : currentInnerText; - if (emojiRegex.test(value)) { - value = value.replace(emojiRegex, ""); - } - return value; -} -function getTextValue(element) { - let label = element.getAttribute("aria-label"); - if (typeof label === "string") - return label.trim(); - let labelledby = element.getAttribute("aria-labelledby"); - if (labelledby) { - let labels = labelledby.split(" ").map((labelledby2) => { - let labelEl = document.getElementById(labelledby2); - if (labelEl) { - let label2 = labelEl.getAttribute("aria-label"); - if (typeof label2 === "string") - return label2.trim(); - return getTextContents(labelEl).trim(); - } - return null; - }).filter(Boolean); - if (labels.length > 0) - return labels.join(", "); - } - return getTextContents(element).trim(); -} - -// src/hooks/use-text-value.ts -function useTextValue(element) { - let cacheKey = (0, import_react34.useRef)(""); - let cacheValue = (0, import_react34.useRef)(""); - return useEvent(() => { - let el = element.current; - if (!el) - return ""; - let currentKey = el.innerText; - if (cacheKey.current === currentKey) { - return cacheValue.current; - } - let value = getTextValue(el).trim().toLowerCase(); - cacheKey.current = currentKey; - cacheValue.current = value; - return value; - }); -} - -// src/components/listbox/listbox.tsx -function adjustOrderedState2(state, adjustment = (i) => i) { - let currentActiveOption = state.activeOptionIndex !== null ? state.options[state.activeOptionIndex] : null; - let sortedOptions = sortByDomNode( - adjustment(state.options.slice()), - (option) => option.dataRef.current.domRef.current - ); - let adjustedActiveOptionIndex = currentActiveOption ? sortedOptions.indexOf(currentActiveOption) : null; - if (adjustedActiveOptionIndex === -1) { - adjustedActiveOptionIndex = null; - } - return { - options: sortedOptions, - activeOptionIndex: adjustedActiveOptionIndex - }; -} -var reducers4 = { - [1 /* CloseListbox */](state) { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - return { ...state, activeOptionIndex: null, listboxState: 1 /* Closed */ }; - }, - [0 /* OpenListbox */](state) { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 0 /* Open */) - return state; - let activeOptionIndex = state.activeOptionIndex; - let { isSelected } = state.dataRef.current; - let optionIdx = state.options.findIndex((option) => isSelected(option.dataRef.current.value)); - if (optionIdx !== -1) { - activeOptionIndex = optionIdx; - } - return { ...state, listboxState: 0 /* Open */, activeOptionIndex }; - }, - [2 /* GoToOption */](state, action) { - var _a3; - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - let adjustedState = adjustOrderedState2(state); - let activeOptionIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.options, - resolveActiveIndex: () => adjustedState.activeOptionIndex, - resolveId: (option) => option.id, - resolveDisabled: (option) => option.dataRef.current.disabled - }); - return { - ...state, - ...adjustedState, - searchQuery: "", - activeOptionIndex, - activationTrigger: (_a3 = action.trigger) != null ? _a3 : 1 /* Other */ - }; - }, - [3 /* Search */]: (state, action) => { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - let wasAlreadySearching = state.searchQuery !== ""; - let offset = wasAlreadySearching ? 0 : 1; - let searchQuery = state.searchQuery + action.value.toLowerCase(); - let reOrderedOptions = state.activeOptionIndex !== null ? state.options.slice(state.activeOptionIndex + offset).concat(state.options.slice(0, state.activeOptionIndex + offset)) : state.options; - let matchingOption = reOrderedOptions.find( - (option) => { - var _a3; - return !option.dataRef.current.disabled && ((_a3 = option.dataRef.current.textValue) == null ? void 0 : _a3.startsWith(searchQuery)); - } - ); - let matchIdx = matchingOption ? state.options.indexOf(matchingOption) : -1; - if (matchIdx === -1 || matchIdx === state.activeOptionIndex) - return { ...state, searchQuery }; - return { - ...state, - searchQuery, - activeOptionIndex: matchIdx, - activationTrigger: 1 /* Other */ - }; - }, - [4 /* ClearSearch */](state) { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - if (state.searchQuery === "") - return state; - return { ...state, searchQuery: "" }; - }, - [5 /* RegisterOption */]: (state, action) => { - let option = { id: action.id, dataRef: action.dataRef }; - let adjustedState = adjustOrderedState2(state, (options) => [...options, option]); - if (state.activeOptionIndex === null) { - if (state.dataRef.current.isSelected(action.dataRef.current.value)) { - adjustedState.activeOptionIndex = adjustedState.options.indexOf(option); - } - } - return { ...state, ...adjustedState }; - }, - [6 /* UnregisterOption */]: (state, action) => { - let adjustedState = adjustOrderedState2(state, (options) => { - let idx = options.findIndex((a) => a.id === action.id); - if (idx !== -1) - options.splice(idx, 1); - return options; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; - }, - [7 /* RegisterLabel */]: (state, action) => { - return { - ...state, - labelId: action.id - }; - } -}; -var ListboxActionsContext = (0, import_react35.createContext)(null); -ListboxActionsContext.displayName = "ListboxActionsContext"; -function useActions2(component) { - let context = (0, import_react35.useContext)(ListboxActionsContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useActions2); - throw err; - } - return context; -} -var ListboxDataContext = (0, import_react35.createContext)(null); -ListboxDataContext.displayName = "ListboxDataContext"; -function useData2(component) { - let context = (0, import_react35.useContext)(ListboxDataContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useData2); - throw err; - } - return context; -} -function stateReducer4(state, action) { - return match(action.type, reducers4, state, action); -} -var DEFAULT_LISTBOX_TAG = import_react35.Fragment; -function ListboxFn(props, ref) { - let { - value: controlledValue, - defaultValue, - form: formName, - name, - onChange: controlledOnChange, - by = (a, z) => a === z, - disabled = false, - horizontal = false, - multiple = false, - ...theirProps - } = props; - const orientation = horizontal ? "horizontal" : "vertical"; - let listboxRef = useSyncRefs(ref); - let [value = multiple ? [] : void 0, theirOnChange] = useControllable( - controlledValue, - controlledOnChange, - defaultValue - ); - let [state, dispatch] = (0, import_react35.useReducer)(stateReducer4, { - dataRef: (0, import_react35.createRef)(), - listboxState: 1 /* Closed */, - options: [], - searchQuery: "", - labelId: null, - activeOptionIndex: null, - activationTrigger: 1 /* Other */ - }); - let optionsPropsRef = (0, import_react35.useRef)({ static: false, hold: false }); - let labelRef = (0, import_react35.useRef)(null); - let buttonRef = (0, import_react35.useRef)(null); - let optionsRef = (0, import_react35.useRef)(null); - let compare = useEvent( - typeof by === "string" ? (a, z) => { - let property = by; - return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]); - } : by - ); - let isSelected = (0, import_react35.useCallback)( - (compareValue) => match(data.mode, { - [1 /* Multi */]: () => value.some((option) => compare(option, compareValue)), - [0 /* Single */]: () => compare(value, compareValue) - }), - [value] - ); - let data = (0, import_react35.useMemo)( - () => ({ - ...state, - value, - disabled, - mode: multiple ? 1 /* Multi */ : 0 /* Single */, - orientation, - compare, - isSelected, - optionsPropsRef, - labelRef, - buttonRef, - optionsRef - }), - [value, disabled, multiple, state] - ); - useIsoMorphicEffect(() => { - state.dataRef.current = data; - }, [data]); - useOutsideClick( - [data.buttonRef, data.optionsRef], - (event, target) => { - var _a3; - dispatch({ type: 1 /* CloseListbox */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus(); - } - }, - data.listboxState === 0 /* Open */ - ); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */, disabled, value }), - [data, disabled, value] - ); - let selectOption = useEvent((id) => { - let option = data.options.find((item) => item.id === id); - if (!option) - return; - onChange(option.dataRef.current.value); - }); - let selectActiveOption = useEvent(() => { - if (data.activeOptionIndex !== null) { - let { dataRef, id } = data.options[data.activeOptionIndex]; - onChange(dataRef.current.value); - dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id }); - } - }); - let openListbox = useEvent(() => dispatch({ type: 0 /* OpenListbox */ })); - let closeListbox = useEvent(() => dispatch({ type: 1 /* CloseListbox */ })); - let goToOption = useEvent((focus, id, trigger) => { - if (focus === 4 /* Specific */) { - return dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id, trigger }); - } - return dispatch({ type: 2 /* GoToOption */, focus, trigger }); - }); - let registerOption = useEvent((id, dataRef) => { - dispatch({ type: 5 /* RegisterOption */, id, dataRef }); - return () => dispatch({ type: 6 /* UnregisterOption */, id }); - }); - let registerLabel = useEvent((id) => { - dispatch({ type: 7 /* RegisterLabel */, id }); - return () => dispatch({ type: 7 /* RegisterLabel */, id: null }); - }); - let onChange = useEvent((value2) => { - return match(data.mode, { - [0 /* Single */]() { - return theirOnChange == null ? void 0 : theirOnChange(value2); - }, - [1 /* Multi */]() { - let copy = data.value.slice(); - let idx = copy.findIndex((item) => compare(item, value2)); - if (idx === -1) { - copy.push(value2); - } else { - copy.splice(idx, 1); + var PopoverRoot = forwardRefWithAs(PopoverFn); + var Button5 = forwardRefWithAs(ButtonFn5); + var Overlay2 = forwardRefWithAs(OverlayFn2); + var Panel3 = forwardRefWithAs(PanelFn3); + var Group2 = forwardRefWithAs(GroupFn2); + var Popover = Object.assign(PopoverRoot, { + Button: Button5, + Overlay: Overlay2, + Panel: Panel3, + Group: Group2, + }); + + // src/components/radio-group/radio-group.tsx + var import_react40 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + + // src/hooks/use-flags.ts + var import_react38 = __webpack_require__(/*! react */ "react"); + function useFlags(initialFlags = 0) { + let [flags, setFlags] = (0, import_react38.useState)(initialFlags); + let mounted = useIsMounted(); + let addFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) return; + setFlags((flags2) => flags2 | flag); + }, + [flags, mounted] + ); + let hasFlag = (0, import_react38.useCallback)( + (flag) => Boolean(flags & flag), + [flags] + ); + let removeFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) return; + setFlags((flags2) => flags2 & ~flag); + }, + [setFlags, mounted] + ); + let toggleFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) return; + setFlags((flags2) => flags2 ^ flag); + }, + [setFlags] + ); + return { flags, addFlag, hasFlag, removeFlag, toggleFlag }; } - return theirOnChange == null ? void 0 : theirOnChange(copy); - } - }); - }); - let search = useEvent((value2) => dispatch({ type: 3 /* Search */, value: value2 })); - let clearSearch = useEvent(() => dispatch({ type: 4 /* ClearSearch */ })); - let actions = (0, import_react35.useMemo)( - () => ({ - onChange, - registerOption, - registerLabel, - goToOption, - closeListbox, - openListbox, - selectActiveOption, - selectOption, - search, - clearSearch - }), - [] - ); - let ourProps = { ref: listboxRef }; - let form = (0, import_react35.useRef)(null); - let d = useDisposables(); - (0, import_react35.useEffect)(() => { - if (!form.current) - return; - if (defaultValue === void 0) - return; - d.addEventListener(form.current, "reset", () => { - onChange(defaultValue); - }); - }, [ - form, - onChange - /* Explicitly ignoring `defaultValue` */ - ]); - return /* @__PURE__ */ import_react35.default.createElement(ListboxActionsContext.Provider, { value: actions }, /* @__PURE__ */ import_react35.default.createElement(ListboxDataContext.Provider, { value: data }, /* @__PURE__ */ import_react35.default.createElement( - OpenClosedProvider, - { - value: match(data.listboxState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - name != null && value != null && objectToFormEntries({ [name]: value }).map(([name2, value2], idx) => /* @__PURE__ */ import_react35.default.createElement( - Hidden, - { - features: 4 /* Hidden */, - ref: idx === 0 ? (element) => { - var _a3; - form.current = (_a3 = element == null ? void 0 : element.closest("form")) != null ? _a3 : null; - } : void 0, - ...compact({ - key: name2, - as: "input", - type: "hidden", - hidden: true, - readOnly: true, - form: formName, - name: name2, - value: value2 - }) - } - )), - render({ ourProps, theirProps, slot, defaultTag: DEFAULT_LISTBOX_TAG, name: "Listbox" }) - ))); -} -var DEFAULT_BUTTON_TAG3 = "button"; -function ButtonFn3(props, ref) { - var _a3; - let internalId = useId(); - let { id = `headlessui-listbox-button-${internalId}`, ...theirProps } = props; - let data = useData2("Listbox.Button"); - let actions = useActions2("Listbox.Button"); - let buttonRef = useSyncRefs(data.buttonRef, ref); - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - actions.openListbox(); - d.nextFrame(() => { - if (!data.value) - actions.goToOption(0 /* First */); - }); - break; - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - actions.openListbox(); - d.nextFrame(() => { - if (!data.value) - actions.goToOption(3 /* Last */); - }); - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (data.listboxState === 0 /* Open */) { - actions.closeListbox(); - d.nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - } else { - event.preventDefault(); - actions.openListbox(); - } - }); - let labelledby = useComputed(() => { - if (!data.labelId) - return void 0; - return [data.labelId, id].join(" "); - }, [data.labelId, id]); - let slot = (0, import_react35.useMemo)( - () => ({ - open: data.listboxState === 0 /* Open */, - disabled: data.disabled, - value: data.value - }), - [data] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, data.buttonRef), - "aria-haspopup": "listbox", - "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled ? void 0 : data.listboxState === 0 /* Open */, - "aria-labelledby": labelledby, - disabled: data.disabled, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG3, - name: "Listbox.Button" - }); -} -var DEFAULT_LABEL_TAG2 = "label"; -function LabelFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-listbox-label-${internalId}`, ...theirProps } = props; - let data = useData2("Listbox.Label"); - let actions = useActions2("Listbox.Label"); - let labelRef = useSyncRefs(data.labelRef, ref); - useIsoMorphicEffect(() => actions.registerLabel(id), [id]); - let handleClick = useEvent(() => { - var _a3; - return (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); - }); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */, disabled: data.disabled }), - [data] - ); - let ourProps = { ref: labelRef, id, onClick: handleClick }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_LABEL_TAG2, - name: "Listbox.Label" - }); -} -var DEFAULT_OPTIONS_TAG2 = "ul"; -var OptionsRenderFeatures2 = 1 /* RenderStrategy */ | 2 /* Static */; -function OptionsFn2(props, ref) { - var _a3; - let internalId = useId(); - let { id = `headlessui-listbox-options-${internalId}`, ...theirProps } = props; - let data = useData2("Listbox.Options"); - let actions = useActions2("Listbox.Options"); - let optionsRef = useSyncRefs(data.optionsRef, ref); - let d = useDisposables(); - let searchDisposables = useDisposables(); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return data.listboxState === 0 /* Open */; - })(); - (0, import_react35.useEffect)(() => { - var _a4; - let container = data.optionsRef.current; - if (!container) - return; - if (data.listboxState !== 0 /* Open */) - return; - if (container === ((_a4 = getOwnerDocument(container)) == null ? void 0 : _a4.activeElement)) - return; - container.focus({ preventScroll: true }); - }, [data.listboxState, data.optionsRef]); - let handleKeyDown = useEvent((event) => { - searchDisposables.dispose(); - switch (event.key) { - case " " /* Space */: - if (data.searchQuery !== "") { - event.preventDefault(); - event.stopPropagation(); - return actions.search(event.key); - } - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - if (data.activeOptionIndex !== null) { - let { dataRef } = data.options[data.activeOptionIndex]; - actions.onChange(dataRef.current.value); - } - if (data.mode === 0 /* Single */) { - actions.closeListbox(); - disposables().nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - } - break; - case match(data.orientation, { vertical: "ArrowDown" /* ArrowDown */, horizontal: "ArrowRight" /* ArrowRight */ }): - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(2 /* Next */); - case match(data.orientation, { vertical: "ArrowUp" /* ArrowUp */, horizontal: "ArrowLeft" /* ArrowLeft */ }): - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(1 /* Previous */); - case "Home" /* Home */: - case "PageUp" /* PageUp */: - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "End" /* End */: - case "PageDown" /* PageDown */: - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "Escape" /* Escape */: - event.preventDefault(); - event.stopPropagation(); - actions.closeListbox(); - return d.nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - case "Tab" /* Tab */: - event.preventDefault(); - event.stopPropagation(); - break; - default: - if (event.key.length === 1) { - actions.search(event.key); - searchDisposables.setTimeout(() => actions.clearSearch(), 350); - } - break; - } - }); - let labelledby = useComputed( - () => { - var _a4, _b, _c; - return (_c = (_a4 = data.labelRef.current) == null ? void 0 : _a4.id) != null ? _c : (_b = data.buttonRef.current) == null ? void 0 : _b.id; - }, - [data.labelRef.current, data.buttonRef.current] - ); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */ }), - [data] - ); - let ourProps = { - "aria-activedescendant": data.activeOptionIndex === null ? void 0 : (_a3 = data.options[data.activeOptionIndex]) == null ? void 0 : _a3.id, - "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, - "aria-labelledby": labelledby, - "aria-orientation": data.orientation, - id, - onKeyDown: handleKeyDown, - role: "listbox", - tabIndex: 0, - ref: optionsRef - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTIONS_TAG2, - features: OptionsRenderFeatures2, - visible, - name: "Listbox.Options" - }); -} -var DEFAULT_OPTION_TAG2 = "li"; -function OptionFn2(props, ref) { - let internalId = useId(); - let { - id = `headlessui-listbox-option-${internalId}`, - disabled = false, - value, - ...theirProps - } = props; - let data = useData2("Listbox.Option"); - let actions = useActions2("Listbox.Option"); - let active = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex].id === id : false; - let selected = data.isSelected(value); - let internalOptionRef = (0, import_react35.useRef)(null); - let getTextValue2 = useTextValue(internalOptionRef); - let bag = useLatestValue({ - disabled, - value, - domRef: internalOptionRef, - get textValue() { - return getTextValue2(); - } - }); - let optionRef = useSyncRefs(ref, internalOptionRef); - useIsoMorphicEffect(() => { - if (data.listboxState !== 0 /* Open */) - return; - if (!active) - return; - if (data.activationTrigger === 0 /* Pointer */) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a3, _b; - (_b = (_a3 = internalOptionRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); - }); - return d.dispose; - }, [ - internalOptionRef, - active, - data.listboxState, - data.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - data.activeOptionIndex - ]); - useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); - let handleClick = useEvent((event) => { - if (disabled) - return event.preventDefault(); - actions.onChange(value); - if (data.mode === 0 /* Single */) { - actions.closeListbox(); - disposables().nextFrame(() => { - var _a3; - return (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); - }); - } - }); - let handleFocus = useEvent(() => { - if (disabled) - return actions.goToOption(5 /* Nothing */); - actions.goToOption(4 /* Specific */, id); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (active) - return; - actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (!active) - return; - actions.goToOption(5 /* Nothing */); - }); - let slot = (0, import_react35.useMemo)( - () => ({ active, selected, disabled }), - [active, selected, disabled] - ); - let ourProps = { - id, - ref: optionRef, - role: "option", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - // According to the WAI-ARIA best practices, we should use aria-checked for - // multi-select,but Voice-Over disagrees. So we use aria-checked instead for - // both single and multi-select. - "aria-selected": selected, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTION_TAG2, - name: "Listbox.Option" - }); -} -var ListboxRoot = forwardRefWithAs(ListboxFn); -var Button3 = forwardRefWithAs(ButtonFn3); -var Label2 = forwardRefWithAs(LabelFn2); -var Options2 = forwardRefWithAs(OptionsFn2); -var Option2 = forwardRefWithAs(OptionFn2); -var Listbox = Object.assign(ListboxRoot, { Button: Button3, Label: Label2, Options: Options2, Option: Option2 }); - -// src/components/menu/menu.tsx -var import_react36 = __toESM(__webpack_require__(/*! react */ "react"), 1); -function adjustOrderedState3(state, adjustment = (i) => i) { - let currentActiveItem = state.activeItemIndex !== null ? state.items[state.activeItemIndex] : null; - let sortedItems = sortByDomNode( - adjustment(state.items.slice()), - (item) => item.dataRef.current.domRef.current - ); - let adjustedActiveItemIndex = currentActiveItem ? sortedItems.indexOf(currentActiveItem) : null; - if (adjustedActiveItemIndex === -1) { - adjustedActiveItemIndex = null; - } - return { - items: sortedItems, - activeItemIndex: adjustedActiveItemIndex - }; -} -var reducers5 = { - [1 /* CloseMenu */](state) { - if (state.menuState === 1 /* Closed */) - return state; - return { ...state, activeItemIndex: null, menuState: 1 /* Closed */ }; - }, - [0 /* OpenMenu */](state) { - if (state.menuState === 0 /* Open */) - return state; - return { - ...state, - /* We can turn off demo mode once we re-open the `Menu` */ - __demoMode: false, - menuState: 0 /* Open */ - }; - }, - [2 /* GoToItem */]: (state, action) => { - var _a3; - let adjustedState = adjustOrderedState3(state); - let activeItemIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.items, - resolveActiveIndex: () => adjustedState.activeItemIndex, - resolveId: (item) => item.id, - resolveDisabled: (item) => item.dataRef.current.disabled - }); - return { - ...state, - ...adjustedState, - searchQuery: "", - activeItemIndex, - activationTrigger: (_a3 = action.trigger) != null ? _a3 : 1 /* Other */ - }; - }, - [3 /* Search */]: (state, action) => { - let wasAlreadySearching = state.searchQuery !== ""; - let offset = wasAlreadySearching ? 0 : 1; - let searchQuery = state.searchQuery + action.value.toLowerCase(); - let reOrderedItems = state.activeItemIndex !== null ? state.items.slice(state.activeItemIndex + offset).concat(state.items.slice(0, state.activeItemIndex + offset)) : state.items; - let matchingItem = reOrderedItems.find( - (item) => { - var _a3; - return ((_a3 = item.dataRef.current.textValue) == null ? void 0 : _a3.startsWith(searchQuery)) && !item.dataRef.current.disabled; - } - ); - let matchIdx = matchingItem ? state.items.indexOf(matchingItem) : -1; - if (matchIdx === -1 || matchIdx === state.activeItemIndex) - return { ...state, searchQuery }; - return { - ...state, - searchQuery, - activeItemIndex: matchIdx, - activationTrigger: 1 /* Other */ - }; - }, - [4 /* ClearSearch */](state) { - if (state.searchQuery === "") - return state; - return { ...state, searchQuery: "", searchActiveItemIndex: null }; - }, - [5 /* RegisterItem */]: (state, action) => { - let adjustedState = adjustOrderedState3(state, (items) => [ - ...items, - { id: action.id, dataRef: action.dataRef } - ]); - return { ...state, ...adjustedState }; - }, - [6 /* UnregisterItem */]: (state, action) => { - let adjustedState = adjustOrderedState3(state, (items) => { - let idx = items.findIndex((a) => a.id === action.id); - if (idx !== -1) - items.splice(idx, 1); - return items; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; - } -}; -var MenuContext = (0, import_react36.createContext)(null); -MenuContext.displayName = "MenuContext"; -function useMenuContext(component) { - let context = (0, import_react36.useContext)(MenuContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useMenuContext); - throw err; - } - return context; -} -function stateReducer5(state, action) { - return match(action.type, reducers5, state, action); -} -var DEFAULT_MENU_TAG = import_react36.Fragment; -function MenuFn(props, ref) { - let { __demoMode = false, ...theirProps } = props; - let reducerBag = (0, import_react36.useReducer)(stateReducer5, { - __demoMode, - menuState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - buttonRef: (0, import_react36.createRef)(), - itemsRef: (0, import_react36.createRef)(), - items: [], - searchQuery: "", - activeItemIndex: null, - activationTrigger: 1 /* Other */ - }); - let [{ menuState, itemsRef, buttonRef }, dispatch] = reducerBag; - let menuRef = useSyncRefs(ref); - useOutsideClick( - [buttonRef, itemsRef], - (event, target) => { - var _a3; - dispatch({ type: 1 /* CloseMenu */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - (_a3 = buttonRef.current) == null ? void 0 : _a3.focus(); - } - }, - menuState === 0 /* Open */ - ); - let close = useEvent(() => { - dispatch({ type: 1 /* CloseMenu */ }); - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: menuState === 0 /* Open */, close }), - [menuState, close] - ); - let ourProps = { ref: menuRef }; - return /* @__PURE__ */ import_react36.default.createElement(MenuContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react36.default.createElement( - OpenClosedProvider, - { - value: match(menuState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_MENU_TAG, - name: "Menu" - }) - )); -} -var DEFAULT_BUTTON_TAG4 = "button"; -function ButtonFn4(props, ref) { - var _a3; - let internalId = useId(); - let { id = `headlessui-menu-button-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useMenuContext("Menu.Button"); - let buttonRef = useSyncRefs(state.buttonRef, ref); - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* OpenMenu */ }); - d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ })); - break; - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* OpenMenu */ }); - d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ })); - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (props.disabled) - return; - if (state.menuState === 0 /* Open */) { - dispatch({ type: 1 /* CloseMenu */ }); - d.nextFrame(() => { - var _a4; - return (_a4 = state.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - } else { - event.preventDefault(); - dispatch({ type: 0 /* OpenMenu */ }); - } - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: state.menuState === 0 /* Open */ }), - [state] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, state.buttonRef), - "aria-haspopup": "menu", - "aria-controls": (_a3 = state.itemsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": props.disabled ? void 0 : state.menuState === 0 /* Open */, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG4, - name: "Menu.Button" - }); -} -var DEFAULT_ITEMS_TAG = "div"; -var ItemsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; -function ItemsFn(props, ref) { - var _a3, _b; - let internalId = useId(); - let { id = `headlessui-menu-items-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useMenuContext("Menu.Items"); - let itemsRef = useSyncRefs(state.itemsRef, ref); - let ownerDocument = useOwnerDocument(state.itemsRef); - let searchDisposables = useDisposables(); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return state.menuState === 0 /* Open */; - })(); - (0, import_react36.useEffect)(() => { - let container = state.itemsRef.current; - if (!container) - return; - if (state.menuState !== 0 /* Open */) - return; - if (container === (ownerDocument == null ? void 0 : ownerDocument.activeElement)) - return; - container.focus({ preventScroll: true }); - }, [state.menuState, state.itemsRef, ownerDocument]); - useTreeWalker({ - container: state.itemsRef.current, - enabled: state.menuState === 0 /* Open */, - accept(node) { - if (node.getAttribute("role") === "menuitem") - return NodeFilter.FILTER_REJECT; - if (node.hasAttribute("role")) - return NodeFilter.FILTER_SKIP; - return NodeFilter.FILTER_ACCEPT; - }, - walk(node) { - node.setAttribute("role", "none"); - } - }); - let handleKeyDown = useEvent((event) => { - var _a4, _b2; - searchDisposables.dispose(); - switch (event.key) { - case " " /* Space */: - if (state.searchQuery !== "") { - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 3 /* Search */, value: event.key }); - } - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - if (state.activeItemIndex !== null) { - let { dataRef } = state.items[state.activeItemIndex]; - (_b2 = (_a4 = dataRef.current) == null ? void 0 : _a4.domRef.current) == null ? void 0 : _b2.click(); - } - restoreFocusIfNecessary(state.buttonRef.current); - break; - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 2 /* Next */ }); - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 1 /* Previous */ }); - case "Home" /* Home */: - case "PageUp" /* PageUp */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ }); - case "End" /* End */: - case "PageDown" /* PageDown */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ }); - case "Escape" /* Escape */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - disposables().nextFrame(() => { - var _a5; - return (_a5 = state.buttonRef.current) == null ? void 0 : _a5.focus({ preventScroll: true }); - }); - break; - case "Tab" /* Tab */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - disposables().nextFrame(() => { - focusFrom( - state.buttonRef.current, - event.shiftKey ? 2 /* Previous */ : 4 /* Next */ - ); - }); - break; - default: - if (event.key.length === 1) { - dispatch({ type: 3 /* Search */, value: event.key }); - searchDisposables.setTimeout(() => dispatch({ type: 4 /* ClearSearch */ }), 350); - } - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: state.menuState === 0 /* Open */ }), - [state] - ); - let ourProps = { - "aria-activedescendant": state.activeItemIndex === null ? void 0 : (_a3 = state.items[state.activeItemIndex]) == null ? void 0 : _a3.id, - "aria-labelledby": (_b = state.buttonRef.current) == null ? void 0 : _b.id, - id, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - role: "menu", - tabIndex: 0, - ref: itemsRef - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_ITEMS_TAG, - features: ItemsRenderFeatures, - visible, - name: "Menu.Items" - }); -} -var DEFAULT_ITEM_TAG = import_react36.Fragment; -function ItemFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-menu-item-${internalId}`, disabled = false, ...theirProps } = props; - let [state, dispatch] = useMenuContext("Menu.Item"); - let active = state.activeItemIndex !== null ? state.items[state.activeItemIndex].id === id : false; - let internalItemRef = (0, import_react36.useRef)(null); - let itemRef = useSyncRefs(ref, internalItemRef); - useIsoMorphicEffect(() => { - if (state.__demoMode) - return; - if (state.menuState !== 0 /* Open */) - return; - if (!active) - return; - if (state.activationTrigger === 0 /* Pointer */) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a3, _b; - (_b = (_a3 = internalItemRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); - }); - return d.dispose; - }, [ - state.__demoMode, - internalItemRef, - active, - state.menuState, - state.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - state.activeItemIndex - ]); - let getTextValue2 = useTextValue(internalItemRef); - let bag = (0, import_react36.useRef)({ - disabled, - domRef: internalItemRef, - get textValue() { - return getTextValue2(); - } - }); - useIsoMorphicEffect(() => { - bag.current.disabled = disabled; - }, [bag, disabled]); - useIsoMorphicEffect(() => { - dispatch({ type: 5 /* RegisterItem */, id, dataRef: bag }); - return () => dispatch({ type: 6 /* UnregisterItem */, id }); - }, [bag, id]); - let close = useEvent(() => { - dispatch({ type: 1 /* CloseMenu */ }); - }); - let handleClick = useEvent((event) => { - if (disabled) - return event.preventDefault(); - dispatch({ type: 1 /* CloseMenu */ }); - restoreFocusIfNecessary(state.buttonRef.current); - }); - let handleFocus = useEvent(() => { - if (disabled) - return dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); - dispatch({ type: 2 /* GoToItem */, focus: 4 /* Specific */, id }); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (active) - return; - dispatch({ - type: 2 /* GoToItem */, - focus: 4 /* Specific */, - id, - trigger: 0 /* Pointer */ - }); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (!active) - return; - dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); - }); - let slot = (0, import_react36.useMemo)( - () => ({ active, disabled, close }), - [active, disabled, close] - ); - let ourProps = { - id, - ref: itemRef, - role: "menuitem", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_ITEM_TAG, - name: "Menu.Item" - }); -} -var MenuRoot = forwardRefWithAs(MenuFn); -var Button4 = forwardRefWithAs(ButtonFn4); -var Items = forwardRefWithAs(ItemsFn); -var Item = forwardRefWithAs(ItemFn); -var Menu = Object.assign(MenuRoot, { Button: Button4, Items, Item }); - -// src/components/popover/popover.tsx -var import_react37 = __toESM(__webpack_require__(/*! react */ "react"), 1); -var reducers6 = { - [0 /* TogglePopover */]: (state) => { - let nextState = { - ...state, - popoverState: match(state.popoverState, { - [0 /* Open */]: 1 /* Closed */, - [1 /* Closed */]: 0 /* Open */ - }) - }; - if (nextState.popoverState === 0 /* Open */) { - nextState.__demoMode = false; - } - return nextState; - }, - [1 /* ClosePopover */](state) { - if (state.popoverState === 1 /* Closed */) - return state; - return { ...state, popoverState: 1 /* Closed */ }; - }, - [2 /* SetButton */](state, action) { - if (state.button === action.button) - return state; - return { ...state, button: action.button }; - }, - [3 /* SetButtonId */](state, action) { - if (state.buttonId === action.buttonId) - return state; - return { ...state, buttonId: action.buttonId }; - }, - [4 /* SetPanel */](state, action) { - if (state.panel === action.panel) - return state; - return { ...state, panel: action.panel }; - }, - [5 /* SetPanelId */](state, action) { - if (state.panelId === action.panelId) - return state; - return { ...state, panelId: action.panelId }; - } -}; -var PopoverContext = (0, import_react37.createContext)(null); -PopoverContext.displayName = "PopoverContext"; -function usePopoverContext(component) { - let context = (0, import_react37.useContext)(PopoverContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, usePopoverContext); - throw err; - } - return context; -} -var PopoverAPIContext = (0, import_react37.createContext)(null); -PopoverAPIContext.displayName = "PopoverAPIContext"; -function usePopoverAPIContext(component) { - let context = (0, import_react37.useContext)(PopoverAPIContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, usePopoverAPIContext); - throw err; - } - return context; -} -var PopoverGroupContext = (0, import_react37.createContext)(null); -PopoverGroupContext.displayName = "PopoverGroupContext"; -function usePopoverGroupContext() { - return (0, import_react37.useContext)(PopoverGroupContext); -} -var PopoverPanelContext = (0, import_react37.createContext)(null); -PopoverPanelContext.displayName = "PopoverPanelContext"; -function usePopoverPanelContext() { - return (0, import_react37.useContext)(PopoverPanelContext); -} -function stateReducer6(state, action) { - return match(action.type, reducers6, state, action); -} -var DEFAULT_POPOVER_TAG = "div"; -function PopoverFn(props, ref) { - var _a3; - let { __demoMode = false, ...theirProps } = props; - let internalPopoverRef = (0, import_react37.useRef)(null); - let popoverRef = useSyncRefs( - ref, - optionalRef((ref2) => { - internalPopoverRef.current = ref2; - }) - ); - let buttons = (0, import_react37.useRef)([]); - let reducerBag = (0, import_react37.useReducer)(stateReducer6, { - __demoMode, - popoverState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - buttons, - button: null, - buttonId: null, - panel: null, - panelId: null, - beforePanelSentinel: (0, import_react37.createRef)(), - afterPanelSentinel: (0, import_react37.createRef)() - }); - let [ - { popoverState, button, buttonId, panel, panelId, beforePanelSentinel, afterPanelSentinel }, - dispatch - ] = reducerBag; - let ownerDocument = useOwnerDocument((_a3 = internalPopoverRef.current) != null ? _a3 : button); - let isPortalled = (0, import_react37.useMemo)(() => { - if (!button) - return false; - if (!panel) - return false; - for (let root2 of document.querySelectorAll("body > *")) { - if (Number(root2 == null ? void 0 : root2.contains(button)) ^ Number(root2 == null ? void 0 : root2.contains(panel))) { - return true; - } - } - let elements = getFocusableElements(); - let buttonIdx = elements.indexOf(button); - let beforeIdx = (buttonIdx + elements.length - 1) % elements.length; - let afterIdx = (buttonIdx + 1) % elements.length; - let beforeElement = elements[beforeIdx]; - let afterElement = elements[afterIdx]; - if (!panel.contains(beforeElement) && !panel.contains(afterElement)) { - return true; - } - return false; - }, [button, panel]); - let buttonIdRef = useLatestValue(buttonId); - let panelIdRef = useLatestValue(panelId); - let registerBag = (0, import_react37.useMemo)( - () => ({ - buttonId: buttonIdRef, - panelId: panelIdRef, - close: () => dispatch({ type: 1 /* ClosePopover */ }) - }), - [buttonIdRef, panelIdRef, dispatch] - ); - let groupContext = usePopoverGroupContext(); - let registerPopover = groupContext == null ? void 0 : groupContext.registerPopover; - let isFocusWithinPopoverGroup = useEvent(() => { - var _a4; - return (_a4 = groupContext == null ? void 0 : groupContext.isFocusWithinPopoverGroup()) != null ? _a4 : (ownerDocument == null ? void 0 : ownerDocument.activeElement) && ((button == null ? void 0 : button.contains(ownerDocument.activeElement)) || (panel == null ? void 0 : panel.contains(ownerDocument.activeElement))); - }); - (0, import_react37.useEffect)(() => registerPopover == null ? void 0 : registerPopover(registerBag), [registerPopover, registerBag]); - let [portals, PortalWrapper] = useNestedPortals(); - let root = useRootContainers({ - portals, - defaultContainers: [button, panel] - }); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "focus", - (event) => { - var _a4, _b, _c, _d; - if (event.target === window) - return; - if (!(event.target instanceof HTMLElement)) - return; - if (popoverState !== 0 /* Open */) - return; - if (isFocusWithinPopoverGroup()) - return; - if (!button) - return; - if (!panel) - return; - if (root.contains(event.target)) - return; - if ((_b = (_a4 = beforePanelSentinel.current) == null ? void 0 : _a4.contains) == null ? void 0 : _b.call(_a4, event.target)) - return; - if ((_d = (_c = afterPanelSentinel.current) == null ? void 0 : _c.contains) == null ? void 0 : _d.call(_c, event.target)) - return; - dispatch({ type: 1 /* ClosePopover */ }); - }, - true - ); - useOutsideClick( - root.resolveContainers, - (event, target) => { - dispatch({ type: 1 /* ClosePopover */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - button == null ? void 0 : button.focus(); - } - }, - popoverState === 0 /* Open */ - ); - let close = useEvent( - (focusableElement) => { - dispatch({ type: 1 /* ClosePopover */ }); - let restoreElement = (() => { - if (!focusableElement) - return button; - if (focusableElement instanceof HTMLElement) - return focusableElement; - if ("current" in focusableElement && focusableElement.current instanceof HTMLElement) - return focusableElement.current; - return button; - })(); - restoreElement == null ? void 0 : restoreElement.focus(); - } - ); - let api = (0, import_react37.useMemo)( - () => ({ close, isPortalled }), - [close, isPortalled] - ); - let slot = (0, import_react37.useMemo)( - () => ({ open: popoverState === 0 /* Open */, close }), - [popoverState, close] - ); - let ourProps = { ref: popoverRef }; - return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: null }, /* @__PURE__ */ import_react37.default.createElement(PopoverContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react37.default.createElement(PopoverAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react37.default.createElement( - OpenClosedProvider, - { - value: match(popoverState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - /* @__PURE__ */ import_react37.default.createElement(PortalWrapper, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_POPOVER_TAG, - name: "Popover" - }), /* @__PURE__ */ import_react37.default.createElement(root.MainTreeNode, null)) - )))); -} -var DEFAULT_BUTTON_TAG5 = "button"; -function ButtonFn5(props, ref) { - let internalId = useId(); - let { id = `headlessui-popover-button-${internalId}`, ...theirProps } = props; - let [state, dispatch] = usePopoverContext("Popover.Button"); - let { isPortalled } = usePopoverAPIContext("Popover.Button"); - let internalButtonRef = (0, import_react37.useRef)(null); - let sentinelId = `headlessui-focus-sentinel-${useId()}`; - let groupContext = usePopoverGroupContext(); - let closeOthers = groupContext == null ? void 0 : groupContext.closeOthers; - let panelContext = usePopoverPanelContext(); - let isWithinPanel = panelContext !== null; - (0, import_react37.useEffect)(() => { - if (isWithinPanel) - return; - dispatch({ type: 3 /* SetButtonId */, buttonId: id }); - return () => { - dispatch({ type: 3 /* SetButtonId */, buttonId: null }); - }; - }, [isWithinPanel, id, dispatch]); - let [uniqueIdentifier] = (0, import_react37.useState)(() => Symbol()); - let buttonRef = useSyncRefs( - internalButtonRef, - ref, - isWithinPanel ? null : (button) => { - if (button) { - state.buttons.current.push(uniqueIdentifier); - } else { - let idx = state.buttons.current.indexOf(uniqueIdentifier); - if (idx !== -1) - state.buttons.current.splice(idx, 1); - } - if (state.buttons.current.length > 1) { - console.warn( - "You are already using a but only 1 is supported." + + // src/components/label/label.tsx + var import_react39 = __toESM( + __webpack_require__(/*! react */ "react"), + 1 + ); + var LabelContext = (0, import_react39.createContext)(null); + function useLabelContext() { + let context = (0, import_react39.useContext)(LabelContext); + if (context === null) { + let err = new Error( + "You used a - - - - + + + + + + + ); }; diff --git a/js_modules/dagster-ui/packages/ui-components/src/components/__stories__/useSuggestionsForString.stories.tsx b/js_modules/dagster-ui/packages/ui-components/src/components/__stories__/useSuggestionsForString.stories.tsx index aa716cdf47404..6084c1967594c 100644 --- a/js_modules/dagster-ui/packages/ui-components/src/components/__stories__/useSuggestionsForString.stories.tsx +++ b/js_modules/dagster-ui/packages/ui-components/src/components/__stories__/useSuggestionsForString.stories.tsx @@ -59,7 +59,7 @@ export const Example = () => { {suggestions.map((suggestion) => (
    ) => { + onMouseDown={(e: React.MouseEvent) => { e.preventDefault(); setValue(onSelectSuggestion(suggestion)); }} diff --git a/js_modules/dagster-ui/packages/ui-core/client.json b/js_modules/dagster-ui/packages/ui-core/client.json index 1099c2eb311a0..4c62310e025b4 100644 --- a/js_modules/dagster-ui/packages/ui-core/client.json +++ b/js_modules/dagster-ui/packages/ui-core/client.json @@ -35,8 +35,8 @@ "LaunchAssetCheckUpstreamQuery": "afb78499f0bf86942fc7f1ff7261c34caec2bd1e4aabb05c95a2db6acc811aaa", "OverduePopoverQuery": "3c8359e1adfab8237e4b26508489f07c09b24069373064c6c94d645312ae9296", "RunningBackfillsNoticeQuery": "edaaca1d6474672ae342eb3887f2aed16fbb502b704a603986d21f14bc10ee53", - "AssetCheckDetailsQuery": "7380d168a78d6cdc049c41434d80385f47955b21a368612cde00450983bf16cd", - "AssetChecksQuery": "ed071f864343935794bcbd3986de1b466c73783303bc45a7a1e3506b2fa89d7b", + "AssetCheckDetailsQuery": "c448858a73cd66132c2d6f232497570d217ece793897c47aaa1155b15c7ef8e9", + "AssetChecksQuery": "2487c52958999bb33e5daa6c0caa0eea46ab200cb7d5d2294a8290e8e1ad3025", "AssetDaemonTicksQuery": "399ac77e660d40eba32c2ab06db2a2936a71e660d93ec108364eec1fdfc16788", "AssetColumnLineage": "bcb70460f77b88bbbfaec90982f3e99f522d9a4e270e63832684cfde169fabc7", "GetAutoMaterializePausedQuery": "50f74183f54031274136ab855701d01f26642a6d958d7452ae13aa6c40ca349d", diff --git a/js_modules/dagster-ui/packages/ui-core/package.json b/js_modules/dagster-ui/packages/ui-core/package.json index 3490e3d788d4e..6bfba2b374840 100644 --- a/js_modules/dagster-ui/packages/ui-core/package.json +++ b/js_modules/dagster-ui/packages/ui-core/package.json @@ -16,6 +16,7 @@ "generate-perms": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generatePermissions.ts", "generate-asset-selection": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generateAssetSelection.ts && eslint src/asset-selection/generated/ --fix -c .eslintrc.js", "generate-selection-autocomplete": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generateSelection.ts && eslint src/selection/generated/ --fix -c .eslintrc.js", + "generate-run-selection": "ts-node -O '{\"module\": \"commonjs\"}' ./src/scripts/generateRunSelection.ts && eslint src/run-selection/generated/ --fix -c .eslintrc.js", "storybook": "storybook dev -p 6006", "build-storybook": "storybook build" }, @@ -30,9 +31,11 @@ "react-router": "^5.2.1", "react-router-dom": "^5.3.0", "react-router-dom-v5-compat": "^6.3.0", - "styled-components": "^5.3.3" + "styled-components": "^6", + "stylis": "^4" }, "dependencies": { + "@emotion/is-prop-valid": "^1.3.1", "@koale/useworker": "^4.0.2", "@tanstack/react-virtual": "^3.0.1", "@testing-library/react-hooks": "^7.0.2", @@ -122,10 +125,9 @@ "@types/mdx-js__react": "^1", "@types/qs": "^6.9.6", "@types/react": "^18.3.9", - "@types/react-dom": "^18.3.0", + "@types/react-dom": "^18.3.1", "@types/react-router": "^5.1.17", "@types/react-router-dom": "^5.3.3", - "@types/styled-components": "^5.1.26", "@types/testing-library__jest-dom": "^5.14.2", "@types/ws": "^6.0.3", "@typescript-eslint/eslint-plugin": "^8.9.0", @@ -158,7 +160,8 @@ "react-router-dom-v5-compat": "^6.3.0", "resize-observer-polyfill": "^1.5.1", "storybook": "^8.2.7", - "styled-components": "^5.3.3", + "styled-components": "^6", + "stylis": "^4", "ts-node": "9.1.1", "ts-prune": "0.10.3", "typescript": "5.5.4", diff --git a/js_modules/dagster-ui/packages/ui-core/src/app/AppProvider.tsx b/js_modules/dagster-ui/packages/ui-core/src/app/AppProvider.tsx index f92823501710b..284588acd0c7b 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/app/AppProvider.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/app/AppProvider.tsx @@ -2,10 +2,12 @@ import {RetryLink} from '@apollo/client/link/retry'; import {WebSocketLink} from '@apollo/client/link/ws'; import {getMainDefinition, isMutationOperation} from '@apollo/client/utilities'; import {CustomTooltipProvider} from '@dagster-io/ui-components'; +import isPropValid from '@emotion/is-prop-valid'; import * as React from 'react'; import {useContext} from 'react'; import {BrowserRouter} from 'react-router-dom'; import {CompatRouter} from 'react-router-dom-v5-compat'; +import {StyleSheetManager, WebTarget} from 'styled-components'; import {SubscriptionClient} from 'subscriptions-transport-ws'; import {v4 as uuidv4} from 'uuid'; @@ -186,31 +188,33 @@ export const AppProvider = (props: AppProviderProps) => { - - - - - - - - - - - - {props.children} - - - - - - - - - - - - - + + + + + + + + + + + + + {props.children} + + + + + + + + + + + + + + @@ -219,6 +223,20 @@ export const AppProvider = (props: AppProviderProps) => { ); }; +// This implements the default behavior from styled-components v5. +// If we can ensure that all styled-components props are migrated to transient +// props (myProp -> -$myProp), we can remove this function. +// https://styled-components.com/docs/faqs#shouldforwardprop-is-no-longer-provided-by-default +function shouldForwardProp(propName: string, target: WebTarget) { + if (typeof target === 'string') { + // For HTML elements, forward the prop if it is a valid HTML attribute + return isPropValid(propName); + } + + // For other elements, forward all props + return true; +} + export const usePrefixedCacheKey = (key: string) => { const {localCacheIdPrefix} = useContext(AppContext); return `${localCacheIdPrefix}/${key}`; diff --git a/js_modules/dagster-ui/packages/ui-core/src/app/AppTopNav/AppTopNav.tsx b/js_modules/dagster-ui/packages/ui-core/src/app/AppTopNav/AppTopNav.tsx index c7bcbe54c1157..1ec1bdfbd54dd 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/app/AppTopNav/AppTopNav.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/app/AppTopNav/AppTopNav.tsx @@ -177,18 +177,18 @@ export const TopNavLink = styled(NavLink)` padding: 24px 0; text-decoration: none; - :hover { + &:hover { color: ${Colors.navTextHover()}; text-decoration: none; } - :active, + &:active, &.active { color: ${Colors.navTextSelected()}; text-decoration: none; } - :focus { + &:focus { outline: none !important; color: ${Colors.navTextSelected()}; } @@ -234,15 +234,15 @@ const NavButton = styled.button` transition: background 100ms linear; } - :hover ${IconWrapper} { + &:hover ${IconWrapper} { background: ${Colors.navTextHover()}; } - :active ${IconWrapper} { + &:active ${IconWrapper} { background: ${Colors.navTextHover()}; } - :focus { + &:focus { background: ${Colors.navButton()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/app/FeatureFlags.oss.tsx b/js_modules/dagster-ui/packages/ui-core/src/app/FeatureFlags.oss.tsx index 7995d5e5ca4d3..5a4a7512fb851 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/app/FeatureFlags.oss.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/app/FeatureFlags.oss.tsx @@ -5,6 +5,7 @@ export enum FeatureFlag { flagDisableAutoLoadDefaults = 'flagDisableAutoLoadDefaults', flagLegacyRunsPage = 'flagLegacyRunsPage', flagAssetSelectionSyntax = 'flagAssetSelectionSyntax', + flagRunSelectionSyntax = 'flagRunSelectionSyntax', // Flags for tests __TestFlagDefaultNone = '__TestFlagDefaultNone', diff --git a/js_modules/dagster-ui/packages/ui-core/src/app/GlobalStyleProvider.tsx b/js_modules/dagster-ui/packages/ui-core/src/app/GlobalStyleProvider.tsx index 5465daa552df3..d67a9893c4ba8 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/app/GlobalStyleProvider.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/app/GlobalStyleProvider.tsx @@ -68,16 +68,16 @@ const GlobalStyle = createGlobalStyle` font-variant-ligatures: none; } - :focus-visible { + &:focus-visible { outline: ${Colors.focusRing()} auto 1px; } - :focus:not(:focus-visible) { + &:focus:not(:focus-visible) { outline: none; } - :not(a):focus, - :not(a):focus-visible { + &:not(a):focus, + &:not(a):focus-visible { outline-offset: 1px; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/app/TopNavButton.tsx b/js_modules/dagster-ui/packages/ui-core/src/app/TopNavButton.tsx index 4b11f5e7b876f..e0f14c9393d77 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/app/TopNavButton.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/app/TopNavButton.tsx @@ -11,12 +11,12 @@ export const TopNavButton = styled(UnstyledButton)` align-items: center; justify-content: center; - :hover, - :focus { + &:hover, + &:focus { background-color: ${Colors.navButtonHover()}; } - :focus:not(:active) { + &:focus:not(:active) { outline: ${Colors.focusRing()} auto 1px; } @@ -25,7 +25,7 @@ export const TopNavButton = styled(UnstyledButton)` transition: background-color 100ms linear; } - :focus ${IconWrapper}, :hover ${IconWrapper} { + &:focus ${IconWrapper}, &:hover ${IconWrapper} { background-color: ${Colors.navTextHover()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts index 8ecf6b03fc28e..d39434b2d0201 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelection.ts @@ -14,7 +14,7 @@ import {AssetSelectionParser} from './generated/AssetSelectionParser'; import {featureEnabled} from '../app/Flags'; import {filterByQuery} from '../app/GraphQueryImpl'; -class AntlrInputErrorListener implements ANTLRErrorListener { +export class AntlrInputErrorListener implements ANTLRErrorListener { syntaxError( recognizer: Recognizer, offendingSymbol: any, @@ -38,27 +38,31 @@ type AssetSelectionQueryResult = { export const parseAssetSelectionQuery = ( all_assets: AssetGraphQueryItem[], query: string, -): AssetSelectionQueryResult => { - const lexer = new AssetSelectionLexer(CharStreams.fromString(query)); - lexer.removeErrorListeners(); - lexer.addErrorListener(new AntlrInputErrorListener()); +): AssetSelectionQueryResult | Error => { + try { + const lexer = new AssetSelectionLexer(CharStreams.fromString(query)); + lexer.removeErrorListeners(); + lexer.addErrorListener(new AntlrInputErrorListener()); - const tokenStream = new CommonTokenStream(lexer); + const tokenStream = new CommonTokenStream(lexer); - const parser = new AssetSelectionParser(tokenStream); - parser.removeErrorListeners(); - parser.addErrorListener(new AntlrInputErrorListener()); + const parser = new AssetSelectionParser(tokenStream); + parser.removeErrorListeners(); + parser.addErrorListener(new AntlrInputErrorListener()); - const tree = parser.start(); + const tree = parser.start(); - const visitor = new AntlrAssetSelectionVisitor(all_assets); - const all_selection = visitor.visit(tree); - const focus_selection = visitor.focus_assets; + const visitor = new AntlrAssetSelectionVisitor(all_assets); + const all_selection = visitor.visit(tree); + const focus_selection = visitor.focus_assets; - return { - all: Array.from(all_selection), - focus: Array.from(focus_selection), - }; + return { + all: Array.from(all_selection), + focus: Array.from(focus_selection), + }; + } catch (e) { + return e as Error; + } }; export const filterAssetSelectionByQuery = ( @@ -66,9 +70,12 @@ export const filterAssetSelectionByQuery = ( query: string, ): AssetSelectionQueryResult => { if (featureEnabled(FeatureFlag.flagAssetSelectionSyntax)) { - try { - return parseAssetSelectionQuery(all_assets, query); - } catch {} + const result = parseAssetSelectionQuery(all_assets, query); + if (result instanceof Error) { + // fall back to old behavior + return filterByQuery(all_assets, query); + } + return result; } return filterByQuery(all_assets, query); }; diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelectionVisitor.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelectionVisitor.ts index 1ce8cd6869cce..de82e2f95c28f 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelectionVisitor.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/AntlrAssetSelectionVisitor.ts @@ -29,7 +29,7 @@ import {GraphTraverser} from '../app/GraphQueryImpl'; import {AssetGraphQueryItem} from '../asset-graph/useAssetGraphData'; import {buildRepoPathForHuman} from '../workspace/buildRepoAddress'; -function getTraversalDepth(ctx: TraversalContext): number { +export function getTraversalDepth(ctx: TraversalContext): number { if (ctx.STAR()) { return Number.MAX_SAFE_INTEGER; } @@ -39,7 +39,7 @@ function getTraversalDepth(ctx: TraversalContext): number { throw new Error('Invalid traversal'); } -function getFunctionName(ctx: FunctionNameContext): string { +export function getFunctionName(ctx: FunctionNameContext): string { if (ctx.SINKS()) { return 'sinks'; } @@ -49,7 +49,7 @@ function getFunctionName(ctx: FunctionNameContext): string { throw new Error('Invalid function name'); } -function getValue(ctx: ValueContext): string { +export function getValue(ctx: ValueContext): string { if (ctx.QUOTED_STRING()) { return ctx.text.slice(1, -1); } diff --git a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/__tests__/AntlrAssetSelection.test.ts b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/__tests__/AntlrAssetSelection.test.ts index f27c4238980f0..bac998097a71f 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/asset-selection/__tests__/AntlrAssetSelection.test.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/asset-selection/__tests__/AntlrAssetSelection.test.ts @@ -87,7 +87,8 @@ describe('parseAssetSelectionQuery', () => { }); it('should parse key_substring query', () => { - assertQueryResult('key:A', ['A']); + assertQueryResult('key_substring:A', ['A']); + assertQueryResult('key_substring:B', ['B', 'B2']); }); it('should parse and query', () => { diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AllIndividualEventsButton.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AllIndividualEventsButton.tsx index d9f420cdc8810..0825b50f14273 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AllIndividualEventsButton.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AllIndividualEventsButton.tsx @@ -389,7 +389,7 @@ const DisclosureTriangleButton = styled.button<{$open: boolean}>` opacity: 0.25; } - :focus { + &:focus { outline: none; ${IconWrapper} { diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AssetEventList.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AssetEventList.tsx index bc3585f50b4c4..96334fab099fb 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AssetEventList.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AssetEventList.tsx @@ -137,9 +137,9 @@ export const AssetListRow = styled(Row)<{$focused: boolean}>` cursor: pointer; user-select: none; - :focus, - :active, - :hover { + &:focus, + &:active, + &:hover { outline: none; background: ${Colors.backgroundLight()}; } @@ -147,7 +147,7 @@ export const AssetListRow = styled(Row)<{$focused: boolean}>` p.$focused && `background: ${Colors.backgroundBlue()}; color: ${Colors.textBlue()}; - :hover { + &:hover { background: ${Colors.backgroundBlue()}; } `} diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AssetPageHeader.oss.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AssetPageHeader.oss.tsx index fad106e3612ab..9b5d41ce4f444 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AssetPageHeader.oss.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AssetPageHeader.oss.tsx @@ -129,7 +129,7 @@ const CopyButton = styled.button` padding: 3px; margin-top: 2px; - :focus { + &:focus { outline: none; } @@ -137,7 +137,7 @@ const CopyButton = styled.button` transition: background-color 100ms linear; } - :hover ${IconWrapper} { + &:hover ${IconWrapper} { background-color: ${Colors.accentGrayHover()}; } `; @@ -181,8 +181,8 @@ const BreadcrumbLink = styled(Link)` color: ${Colors.textLight()}; white-space: nowrap; - :hover, - :active { + &:hover, + &:active { color: ${Colors.textLight()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/AutomaterializeRequestedPartitionsLink.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/AutomaterializeRequestedPartitionsLink.tsx index e0fb1d2fe7905..85ceaa0dad5f4 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/AutomaterializeRequestedPartitionsLink.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/AutomaterializeRequestedPartitionsLink.tsx @@ -305,7 +305,7 @@ export const RUN_STATUS_AND_PARTITION_KEY = gql` `; const TagLink = styled(Link)` - :focus { + &:focus { outline: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/CollapsibleSection.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/CollapsibleSection.tsx index 9f713fee970fd..068da3e3dfb4d 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/CollapsibleSection.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/CollapsibleSection.tsx @@ -72,7 +72,7 @@ const SectionHeader = styled.button` padding: 0; margin: 0; - :focus { + &:focus { outline: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/PartitionSubsetList.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/PartitionSubsetList.tsx index 1f5527acc6b72..09efcdb99187d 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/PartitionSubsetList.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/PartitionSubsetList.tsx @@ -195,7 +195,7 @@ const PartitionStatusDot = styled.div<{$color: string; $hoverColor: string}>` border-radius: 50%; transition: background-color 100ms linear; - :hover { + &:hover { background-color: ${({$hoverColor}) => $hoverColor}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/VirtualizedAssetPartitionListForDialog.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/VirtualizedAssetPartitionListForDialog.tsx index 8299b10bc0fb0..3919e271fbc7e 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/VirtualizedAssetPartitionListForDialog.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/AutoMaterializePolicyPage/VirtualizedAssetPartitionListForDialog.tsx @@ -138,7 +138,7 @@ const PartitionNameButton = styled.button` align-items: center; gap: 8px; - :focus { + &:focus { outline: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/assets/asset-checks/AssetCheckDetailModal.tsx b/js_modules/dagster-ui/packages/ui-core/src/assets/asset-checks/AssetCheckDetailModal.tsx index 7fd71dd2cc5ba..6d0220b408f86 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/assets/asset-checks/AssetCheckDetailModal.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/assets/asset-checks/AssetCheckDetailModal.tsx @@ -6,6 +6,7 @@ import { Dialog, DialogBody, DialogFooter, + FontFamily, Mono, NonIdealState, } from '@dagster-io/ui-components'; @@ -34,10 +35,12 @@ export function MetadataCell({metadataEntries}: {metadataEntries?: MetadataEntry onClose={() => setShowMetadata(false)} canOutsideClickClose canEscapeKeyClose - style={{width: '80%', minWidth: '800px'}} + style={{width: '80vw', minWidth: '600px', maxWidth: '800px'}} > - +
    + +
    - -
    + + + ); }; @@ -79,12 +73,13 @@ interface InnerProps { } const TickDetailsDialogImpl = ({tickId, tickResultType, instigationSelector}: InnerProps) => { - const [activeTab, setActiveTab] = useState<'result' | 'logs'>('result'); - - const {data} = useQuery(JOB_SELECTED_TICK_QUERY, { - variables: {instigationSelector, tickId: tickId || ''}, - skip: !tickId, - }); + const {data, loading} = useQuery( + JOB_SELECTED_TICK_QUERY, + { + variables: {instigationSelector, tickId: tickId || ''}, + skip: !tickId, + }, + ); const tick = data?.instigationStateOrError.__typename === 'InstigationState' @@ -105,11 +100,29 @@ const TickDetailsDialogImpl = ({tickId, tickResultType, instigationSelector}: In return [added, deleted]; }, [tick?.dynamicPartitionsRequestResults]); + if (loading) { + return ( + <> + + + + + + ); + } + if (!tick) { return ( - - - + <> + + + + + ); } @@ -117,25 +130,20 @@ const TickDetailsDialogImpl = ({tickId, tickResultType, instigationSelector}: In <> + <> + Tick for {instigationSelector.name}: + + } /> - - - - - - - {tickResultType === 'materializations' && activeTab === 'result' ? ( - - ) : null} - {tickResultType === 'runs' && activeTab === 'result' ? ( + {tickResultType === 'materializations' ? : null} + {tickResultType === 'runs' ? (
    {tick.runIds.length ? ( <> @@ -175,9 +183,6 @@ const TickDetailsDialogImpl = ({tickId, tickResultType, instigationSelector}: In ) : null}
    ) : null} - {activeTab === 'logs' ? ( - - ) : null} ); }; diff --git a/js_modules/dagster-ui/packages/ui-core/src/instigation/TickHistory.tsx b/js_modules/dagster-ui/packages/ui-core/src/instigation/TickHistory.tsx index 6e539740f4fe5..e3c5a1b806ea4 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/instigation/TickHistory.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/instigation/TickHistory.tsx @@ -12,6 +12,7 @@ import { IconWrapper, Menu, MenuItem, + MiddleTruncate, NonIdealState, Select, Spinner, @@ -22,6 +23,7 @@ import { import {Chart} from 'chart.js'; import zoomPlugin from 'chartjs-plugin-zoom'; import * as React from 'react'; +import {useState} from 'react'; import styled from 'styled-components'; import {TICK_TAG_FRAGMENT} from './InstigationTick'; @@ -30,7 +32,7 @@ import {LiveTickTimeline} from './LiveTickTimeline2'; import {TickDetailsDialog} from './TickDetailsDialog'; import {HistoryTickFragment} from './types/InstigationUtils.types'; import {TickHistoryQuery, TickHistoryQueryVariables} from './types/TickHistory.types'; -import {countPartitionsAddedOrDeleted, isStuckStartedTick, truncate} from './util'; +import {countPartitionsAddedOrDeleted, isStuckStartedTick} from './util'; import {gql, useQuery} from '../apollo-client'; import {showSharedToaster} from '../app/DomUtils'; import {PYTHON_ERROR_FRAGMENT} from '../app/PythonErrorFragment'; @@ -95,6 +97,9 @@ export const TicksTable = ({ defaults: {status: TickStatusDisplay.ALL}, }); + const [showDetailsForTick, setShowDetailsForTick] = useState(null); + const [showLogsForTick, setShowLogsForTick] = useState(null); + const instigationSelector = {...repoAddressToSelector(repoAddress), name}; const statuses = React.useMemo( () => STATUS_DISPLAY_MAP[tickStatus] || STATUS_DISPLAY_MAP[TickStatusDisplay.ALL], @@ -163,7 +168,6 @@ export const TicksTable = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [ticks, queryResult.loading, paginationProps.hasPrevCursor]); - const [logTick, setLogTick] = React.useState(); const {data} = queryResult; if (!data) { @@ -194,13 +198,6 @@ export const TicksTable = ({ return ( <> - {logTick ? ( - setLogTick(undefined)} - /> - ) : null} {tabs} @@ -220,6 +217,7 @@ export const TicksTable = ({ Cursor ) : null} Result + Logs @@ -230,6 +228,8 @@ export const TicksTable = ({ tickResultType={tickResultType} instigationSelector={instigationSelector} index={index} + onShowDetails={setShowDetailsForTick} + onShowLogs={setShowLogsForTick} /> ))} @@ -244,6 +244,20 @@ export const TicksTable = ({
    ) : null} + setShowDetailsForTick(null)} + /> + setShowLogsForTick(null)} + /> ); }; @@ -407,16 +421,18 @@ export const TickHistoryTimeline = ({ function TickRow({ tick, tickResultType, - instigationSelector, index, + onShowDetails, + onShowLogs, }: { tick: HistoryTickFragment; tickResultType: TickResultType; instigationSelector: InstigationSelector; index: number; + onShowDetails: (tick: HistoryTickFragment) => void; + onShowLogs: (tick: HistoryTickFragment) => void; }) { const copyToClipboard = useCopyToClipboard(); - const [showResults, setShowResults] = React.useState(false); const [addedPartitions, deletedPartitions] = React.useMemo(() => { const requests = tick.dynamicPartitionsRequestResults; @@ -459,11 +475,18 @@ function TickRow({ )} {tick.instigationType === InstigationType.SENSOR ? ( - + {tick.cursor ? ( -
    - {truncate(tick.cursor || '')} +
    +
    { @@ -486,7 +509,7 @@ function TickRow({ {tickResultType === 'runs' ? ( - setShowResults(true)}> + onShowDetails(tick)}> {tick.runIds.length === 1 ? '1 run requested' : `${tick.runIds.length} runs requested`} @@ -501,7 +524,7 @@ function TickRow({ ) : ( - setShowResults(true)}> + onShowDetails(tick)}> {tick.requestedAssetMaterializationCount === 1 ? '1 materialization requested' : `${tick.requestedAssetMaterializationCount} materializations requested`} @@ -525,17 +548,11 @@ function TickRow({ ) ) : null} - { - setShowResults(false); - }} - /> + + + ); } @@ -589,11 +606,11 @@ const CopyButton = styled.button` transition: background-color 100ms; } - :hover ${IconWrapper} { + &:hover ${IconWrapper} { background-color: ${Colors.accentGrayHover()}; } - :focus ${IconWrapper} { + &:focus ${IconWrapper} { background-color: ${Colors.linkDefault()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/launchpad/ConfigEditorConfigPicker.tsx b/js_modules/dagster-ui/packages/ui-core/src/launchpad/ConfigEditorConfigPicker.tsx index 40d453f9c8a05..7cefd83813dff 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/launchpad/ConfigEditorConfigPicker.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/launchpad/ConfigEditorConfigPicker.tsx @@ -445,11 +445,11 @@ export const SortButton = styled.button` border-radius: 4px; transition: background-color 100ms; - :focus { + &:focus { background-color: ${Colors.backgroundLighterHover()}; outline: none; } - :hover { + &:hover { ${IconWrapper} { background-color: ${Colors.backgroundLight()}; } diff --git a/js_modules/dagster-ui/packages/ui-core/src/nav/LeftNavItem.tsx b/js_modules/dagster-ui/packages/ui-core/src/nav/LeftNavItem.tsx index df739a14ca3c0..2131314d42d31 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/nav/LeftNavItem.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/nav/LeftNavItem.tsx @@ -221,9 +221,9 @@ const SensorScheduleDialogButton = styled.button` border: 0; cursor: pointer; - :focus, - :active, - :hover { + &:focus, + &:active, + &:hover { outline: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/nav/RepoNavItem.tsx b/js_modules/dagster-ui/packages/ui-core/src/nav/RepoNavItem.tsx index 9dbf021527916..af6748936b896 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/nav/RepoNavItem.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/nav/RepoNavItem.tsx @@ -198,7 +198,7 @@ const ReloadButton = styled.button` padding: 8px; margin: -8px; - :focus:not(:focus-visible) { + &:focus:not(:focus-visible) { outline: none; } @@ -206,7 +206,7 @@ const ReloadButton = styled.button` transition: color 0.1s ease-in-out; } - :hover ${IconWrapper} { + &:hover ${IconWrapper} { color: ${Colors.accentBlue()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/nav/RepoSelector.tsx b/js_modules/dagster-ui/packages/ui-core/src/nav/RepoSelector.tsx index 12ae651ef8e62..e4f37d2017419 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/nav/RepoSelector.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/nav/RepoSelector.tsx @@ -129,12 +129,12 @@ const RepoLabel = styled.label` user-select: none; white-space: nowrap; - :focus, - :active { + &:focus, + &:active { outline: none; } - :hover { + &:hover { filter: opacity(0.8); } `; @@ -188,11 +188,11 @@ const ReloadButtonInner = styled.button` margin: -6px; outline: none; - :disabled { + &:disabled { cursor: default; } - :disabled ${IconWrapper} { + &:disabled ${IconWrapper} { background-color: ${Colors.textDisabled()}; transition: background-color 100ms; } @@ -202,11 +202,11 @@ const ReloadButtonInner = styled.button` transition: background-color 100ms; } - :hover:not(:disabled) ${IconWrapper} { + &:hover:not(:disabled) ${IconWrapper} { background-color: ${Colors.textLighter()}; } - :focus ${IconWrapper} { + &:focus ${IconWrapper} { background-color: ${Colors.linkDefault()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/nav/RepositoryLink.tsx b/js_modules/dagster-ui/packages/ui-core/src/nav/RepositoryLink.tsx index 1e4f42a30f9f7..94841be55c6bd 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/nav/RepositoryLink.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/nav/RepositoryLink.tsx @@ -95,11 +95,11 @@ const StyledButton = styled.button` padding: 0; margin: 0; - :disabled { + &:disabled { cursor: default; } - :focus:not(:focus-visible) { + &:focus:not(:focus-visible) { outline: none; } @@ -108,7 +108,7 @@ const StyledButton = styled.button` transition: color 100ms linear; } - :hover ${IconWrapper} { + &:hover ${IconWrapper} { color: ${Colors.accentBlue()}; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewSensors.tsx b/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewSensors.tsx index e62362c0b88a3..2e5ec5d1dd472 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewSensors.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewSensors.tsx @@ -285,6 +285,9 @@ export const OverviewSensors = () => { }; const showSearchSpinner = queryLoading && !data; + const sensorDaemonStatus = data?.instance.daemonHealth.allDaemonStatuses.find( + (status) => status.daemonType === 'SENSOR', + ); return ( <> @@ -341,7 +344,7 @@ export const OverviewSensors = () => { ) : ( <> diff --git a/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewTabs.tsx b/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewTabs.tsx index 6fe7e563a27de..4955214c43e60 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewTabs.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/overview/OverviewTabs.tsx @@ -25,9 +25,9 @@ export const OverviewTabs = >(props: Props - {enableAssetHealthOverviewPreview && ( + {enableAssetHealthOverviewPreview ? ( - )} + ) : null} {automaterializeSensorsFlagState === 'has-global-amp' ? ( { + try { + const lexer = new RunSelectionLexer(CharStreams.fromString(query)); + lexer.removeErrorListeners(); + lexer.addErrorListener(new AntlrInputErrorListener()); + + const tokenStream = new CommonTokenStream(lexer); + + const parser = new RunSelectionParser(tokenStream); + parser.removeErrorListeners(); + parser.addErrorListener(new AntlrInputErrorListener()); + + const tree = parser.start(); + + const visitor = new AntlrRunSelectionVisitor(all_runs); + const all_selection = visitor.visit(tree); + const focus_selection = visitor.focus_runs; + + return { + all: Array.from(all_selection), + focus: Array.from(focus_selection), + }; + } catch (e) { + return e as Error; + } +}; + +export const filterRunSelectionByQuery = ( + all_runs: RunGraphQueryItem[], + query: string, +): RunSelectionQueryResult => { + if (featureEnabled(FeatureFlag.flagRunSelectionSyntax)) { + const result = parseRunSelectionQuery(all_runs, query); + if (result instanceof Error) { + // fall back to old behavior + return filterByQuery(all_runs, query); + } + return result; + } + return filterByQuery(all_runs, query); +}; diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/AntlrRunSelectionVisitor.ts b/js_modules/dagster-ui/packages/ui-core/src/run-selection/AntlrRunSelectionVisitor.ts new file mode 100644 index 0000000000000..c1f457693062a --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/AntlrRunSelectionVisitor.ts @@ -0,0 +1,165 @@ +import {AbstractParseTreeVisitor} from 'antlr4ts/tree/AbstractParseTreeVisitor'; + +import {GraphTraverser} from '../app/GraphQueryImpl'; +import {RunGraphQueryItem} from '../gantt/toGraphQueryItems'; +import { + AllExpressionContext, + AndExpressionContext, + AttributeExpressionContext, + DownTraversalExpressionContext, + FunctionCallExpressionContext, + NameExprContext, + NameSubstringExprContext, + NotExpressionContext, + OrExpressionContext, + ParenthesizedExpressionContext, + StartContext, + StatusAttributeExprContext, + TraversalAllowedExpressionContext, + UpAndDownTraversalExpressionContext, + UpTraversalExpressionContext, +} from './generated/RunSelectionParser'; +import {RunSelectionVisitor} from './generated/RunSelectionVisitor'; +import { + getFunctionName, + getTraversalDepth, + getValue, +} from '../asset-selection/AntlrAssetSelectionVisitor'; + +export class AntlrRunSelectionVisitor + extends AbstractParseTreeVisitor> + implements RunSelectionVisitor> +{ + all_runs: Set; + focus_runs: Set; + traverser: GraphTraverser; + + protected defaultResult() { + return new Set(); + } + + constructor(all_runs: RunGraphQueryItem[]) { + super(); + this.all_runs = new Set(all_runs); + this.focus_runs = new Set(); + this.traverser = new GraphTraverser(all_runs); + } + + visitStart(ctx: StartContext) { + return this.visit(ctx.expr()); + } + + visitTraversalAllowedExpression(ctx: TraversalAllowedExpressionContext) { + return this.visit(ctx.traversalAllowedExpr()); + } + + visitUpAndDownTraversalExpression(ctx: UpAndDownTraversalExpressionContext) { + const selection = this.visit(ctx.traversalAllowedExpr()); + const up_depth: number = getTraversalDepth(ctx.traversal(0)); + const down_depth: number = getTraversalDepth(ctx.traversal(1)); + const selection_copy = new Set(selection); + for (const item of selection_copy) { + this.traverser.fetchUpstream(item, up_depth).forEach((i) => selection.add(i)); + this.traverser.fetchDownstream(item, down_depth).forEach((i) => selection.add(i)); + } + return selection; + } + + visitUpTraversalExpression(ctx: UpTraversalExpressionContext) { + const selection = this.visit(ctx.traversalAllowedExpr()); + const traversal_depth: number = getTraversalDepth(ctx.traversal()); + const selection_copy = new Set(selection); + for (const item of selection_copy) { + this.traverser.fetchUpstream(item, traversal_depth).forEach((i) => selection.add(i)); + } + return selection; + } + + visitDownTraversalExpression(ctx: DownTraversalExpressionContext) { + const selection = this.visit(ctx.traversalAllowedExpr()); + const traversal_depth: number = getTraversalDepth(ctx.traversal()); + const selection_copy = new Set(selection); + for (const item of selection_copy) { + this.traverser.fetchDownstream(item, traversal_depth).forEach((i) => selection.add(i)); + } + return selection; + } + + visitNotExpression(ctx: NotExpressionContext) { + const selection = this.visit(ctx.expr()); + return new Set([...this.all_runs].filter((i) => !selection.has(i))); + } + + visitAndExpression(ctx: AndExpressionContext) { + const left = this.visit(ctx.expr(0)); + const right = this.visit(ctx.expr(1)); + return new Set([...left].filter((i) => right.has(i))); + } + + visitOrExpression(ctx: OrExpressionContext) { + const left = this.visit(ctx.expr(0)); + const right = this.visit(ctx.expr(1)); + return new Set([...left, ...right]); + } + + visitAllExpression(_ctx: AllExpressionContext) { + return this.all_runs; + } + + visitAttributeExpression(ctx: AttributeExpressionContext) { + return this.visit(ctx.attributeExpr()); + } + + visitFunctionCallExpression(ctx: FunctionCallExpressionContext) { + const function_name: string = getFunctionName(ctx.functionName()); + const selection = this.visit(ctx.expr()); + if (function_name === 'sinks') { + const sinks = new Set(); + for (const item of selection) { + const downstream = this.traverser + .fetchDownstream(item, Number.MAX_VALUE) + .filter((i) => selection.has(i)); + if (downstream.length === 0 || (downstream.length === 1 && downstream[0] === item)) { + sinks.add(item); + } + } + return sinks; + } + if (function_name === 'roots') { + const roots = new Set(); + for (const item of selection) { + const upstream = this.traverser + .fetchUpstream(item, Number.MAX_VALUE) + .filter((i) => selection.has(i)); + if (upstream.length === 0 || (upstream.length === 1 && upstream[0] === item)) { + roots.add(item); + } + } + return roots; + } + throw new Error(`Unknown function: ${function_name}`); + } + + visitParenthesizedExpression(ctx: ParenthesizedExpressionContext) { + return this.visit(ctx.expr()); + } + + visitNameExpr(ctx: NameExprContext) { + const value: string = getValue(ctx.value()); + const selection = [...this.all_runs].filter((i) => i.name === value); + selection.forEach((i) => this.focus_runs.add(i)); + return new Set(selection); + } + + visitNameSubstringExpr(ctx: NameSubstringExprContext) { + const value: string = getValue(ctx.value()); + const selection = [...this.all_runs].filter((i) => i.name.includes(value)); + selection.forEach((i) => this.focus_runs.add(i)); + return new Set(selection); + } + + visitStatusAttributeExpr(ctx: StatusAttributeExprContext) { + const state: string = getValue(ctx.value()).toLowerCase(); + return new Set([...this.all_runs].filter((i) => i.metadata?.state === state)); + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 b/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 new file mode 100644 index 0000000000000..abef6e04c81c1 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 @@ -0,0 +1,76 @@ +grammar RunSelection; + +start: expr EOF; + +// Root rule for parsing expressions +expr + : traversalAllowedExpr # TraversalAllowedExpression + | traversal traversalAllowedExpr traversal # UpAndDownTraversalExpression + | traversal traversalAllowedExpr # UpTraversalExpression + | traversalAllowedExpr traversal # DownTraversalExpression + | NOT expr # NotExpression + | expr AND expr # AndExpression + | expr OR expr # OrExpression + | STAR # AllExpression + ; + +// Allowed expressions for traversals +traversalAllowedExpr + : attributeExpr # AttributeExpression + | functionName LPAREN expr RPAREN # FunctionCallExpression + | LPAREN expr RPAREN # ParenthesizedExpression + ; + +// Traversal operators +traversal + : STAR + | PLUS+ + ; + +// Function names as tokens +functionName + : SINKS + | ROOTS + ; + +// Attribute expressions for specific attributes +attributeExpr + : NAME COLON value # NameExpr + | NAME_SUBSTRING COLON value # NameSubstringExpr + | STATUS COLON value # StatusAttributeExpr + ; + +// Value can be a quoted or unquoted string +value + : QUOTED_STRING + | UNQUOTED_STRING + ; + +// Tokens for operators and keywords +AND : 'and'; +OR : 'or'; +NOT : 'not'; + +STAR : '*'; +PLUS : '+'; + +COLON : ':'; + +LPAREN : '('; +RPAREN : ')'; + +// Tokens for attributes +NAME : 'name'; +NAME_SUBSTRING : 'name_substring'; +STATUS : 'status'; + +// Tokens for function names +SINKS : 'sinks'; +ROOTS : 'roots'; + +// Tokens for strings +QUOTED_STRING : '"' (~["\\\r\n])* '"' ; +UNQUOTED_STRING : [a-zA-Z_][a-zA-Z0-9_]*; + +// Whitespace +WS : [ \t\r\n]+ -> skip ; \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/__tests__/AntlrRunSelection.test.ts b/js_modules/dagster-ui/packages/ui-core/src/run-selection/__tests__/AntlrRunSelection.test.ts new file mode 100644 index 0000000000000..8f573934ae8ae --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/__tests__/AntlrRunSelection.test.ts @@ -0,0 +1,152 @@ +/* eslint-disable jest/expect-expect */ + +import {RunGraphQueryItem} from '../../gantt/toGraphQueryItems'; +import {IStepMetadata, IStepState} from '../../runs/RunMetadataProvider'; +import {parseRunSelectionQuery} from '../AntlrRunSelection'; + +function buildMetadata(state: IStepState): IStepMetadata { + return { + state, + attempts: [], + markers: [], + transitions: [], + }; +} + +const TEST_GRAPH: RunGraphQueryItem[] = [ + // Top Layer + { + name: 'A', + metadata: buildMetadata(IStepState.SUCCEEDED), + inputs: [{dependsOn: []}], + outputs: [{dependedBy: [{solid: {name: 'B'}}, {solid: {name: 'B2'}}]}], + }, + // Second Layer + { + name: 'B', + metadata: buildMetadata(IStepState.FAILED), + inputs: [{dependsOn: [{solid: {name: 'A'}}]}], + outputs: [{dependedBy: [{solid: {name: 'C'}}]}], + }, + { + name: 'B2', + metadata: buildMetadata(IStepState.SKIPPED), + inputs: [{dependsOn: [{solid: {name: 'A'}}]}], + outputs: [{dependedBy: [{solid: {name: 'C'}}]}], + }, + // Third Layer + { + name: 'C', + metadata: buildMetadata(IStepState.RUNNING), + inputs: [{dependsOn: [{solid: {name: 'B'}}, {solid: {name: 'B2'}}]}], + outputs: [{dependedBy: []}], + }, +]; + +function assertQueryResult(query: string, expectedNames: string[]) { + const result = parseRunSelectionQuery(TEST_GRAPH, query); + expect(result).not.toBeInstanceOf(Error); + if (result instanceof Error) { + throw result; + } + expect(result.all.length).toBe(expectedNames.length); + expect(new Set(result.all.map((run) => run.name))).toEqual(new Set(expectedNames)); +} + +// Most tests copied from AntlrAssetSelection.test.ts +describe('parseRunSelectionQuery', () => { + describe('invalid queries', () => { + it('should throw on invalid queries', () => { + expect(parseRunSelectionQuery(TEST_GRAPH, 'A')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'name:A name:B')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'not')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'and')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'name:A and')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'sinks')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'notafunction()')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'tag:foo=')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'owner')).toBeInstanceOf(Error); + expect(parseRunSelectionQuery(TEST_GRAPH, 'owner:owner@owner.com')).toBeInstanceOf(Error); + }); + }); + + describe('valid queries', () => { + it('should parse star query', () => { + assertQueryResult('*', ['A', 'B', 'B2', 'C']); + }); + + it('should parse name query', () => { + assertQueryResult('name:A', ['A']); + }); + + it('should parse name_substring query', () => { + assertQueryResult('name_substring:A', ['A']); + assertQueryResult('name_substring:B', ['B', 'B2']); + }); + + it('should parse and query', () => { + assertQueryResult('name:A and name:B', []); + assertQueryResult('name:A and name:B and name:C', []); + }); + + it('should parse or query', () => { + assertQueryResult('name:A or name:B', ['A', 'B']); + assertQueryResult('name:A or name:B or name:C', ['A', 'B', 'C']); + assertQueryResult('(name:A or name:B) and (name:B or name:C)', ['B']); + }); + + it('should parse upstream plus query', () => { + assertQueryResult('+name:A', ['A']); + assertQueryResult('+name:B', ['A', 'B']); + assertQueryResult('+name:C', ['B', 'B2', 'C']); + assertQueryResult('++name:C', ['A', 'B', 'B2', 'C']); + }); + + it('should parse downstream plus query', () => { + assertQueryResult('name:A+', ['A', 'B', 'B2']); + assertQueryResult('name:A++', ['A', 'B', 'B2', 'C']); + assertQueryResult('name:C+', ['C']); + assertQueryResult('name:B+', ['B', 'C']); + }); + + it('should parse upstream star query', () => { + assertQueryResult('*name:A', ['A']); + assertQueryResult('*name:B', ['A', 'B']); + assertQueryResult('*name:C', ['A', 'B', 'B2', 'C']); + }); + + it('should parse downstream star query', () => { + assertQueryResult('name:A*', ['A', 'B', 'B2', 'C']); + assertQueryResult('name:B*', ['B', 'C']); + assertQueryResult('name:C*', ['C']); + }); + + it('should parse up and down traversal queries', () => { + assertQueryResult('name:A* and *name:C', ['A', 'B', 'B2', 'C']); + assertQueryResult('*name:B*', ['A', 'B', 'C']); + assertQueryResult('name:A* and *name:C and *name:B*', ['A', 'B', 'C']); + assertQueryResult('name:A* and *name:B* and *name:C', ['A', 'B', 'C']); + }); + + it('should parse sinks query', () => { + assertQueryResult('sinks(*)', ['C']); + assertQueryResult('sinks(name:A)', ['A']); + assertQueryResult('sinks(name:A or name:B)', ['B']); + }); + + it('should parse roots query', () => { + assertQueryResult('roots(*)', ['A']); + assertQueryResult('roots(name:C)', ['C']); + assertQueryResult('roots(name:A or name:B)', ['A']); + }); + + it('should parse status query', () => { + assertQueryResult('status:succeeded', ['A']); + assertQueryResult('status:SUCCEEDED', ['A']); + assertQueryResult('status:failed', ['B']); + assertQueryResult('status:skipped', ['B2']); + assertQueryResult('status:"running"', ['C']); + assertQueryResult('status:not_a_status', []); + }); + }); +}); diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelection.interp b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelection.interp new file mode 100644 index 0000000000000..14cfa1eb8e790 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelection.interp @@ -0,0 +1,50 @@ +token literal names: +null +'and' +'or' +'not' +'*' +'+' +':' +'(' +')' +'name' +'name_substring' +'status' +'sinks' +'roots' +null +null +null + +token symbolic names: +null +AND +OR +NOT +STAR +PLUS +COLON +LPAREN +RPAREN +NAME +NAME_SUBSTRING +STATUS +SINKS +ROOTS +QUOTED_STRING +UNQUOTED_STRING +WS + +rule names: +start +expr +traversalAllowedExpr +traversal +functionName +attributeExpr +value + + +atn: +[3, 51485, 51898, 1421, 44986, 20307, 1543, 60043, 49729, 3, 18, 83, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 3, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 3, 35, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 43, 10, 3, 12, 3, 14, 3, 46, 11, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 58, 10, 4, 3, 5, 3, 5, 6, 5, 62, 10, 5, 13, 5, 14, 5, 63, 5, 5, 66, 10, 5, 3, 6, 3, 6, 3, 7, 3, 7, 3, 7, 3, 7, 3, 7, 3, 7, 3, 7, 3, 7, 3, 7, 5, 7, 79, 10, 7, 3, 8, 3, 8, 3, 8, 2, 2, 3, 4, 9, 2, 2, 4, 2, 6, 2, 8, 2, 10, 2, 12, 2, 14, 2, 2, 4, 3, 2, 14, 15, 3, 2, 16, 17, 2, 88, 2, 16, 3, 2, 2, 2, 4, 34, 3, 2, 2, 2, 6, 57, 3, 2, 2, 2, 8, 65, 3, 2, 2, 2, 10, 67, 3, 2, 2, 2, 12, 78, 3, 2, 2, 2, 14, 80, 3, 2, 2, 2, 16, 17, 5, 4, 3, 2, 17, 18, 7, 2, 2, 3, 18, 3, 3, 2, 2, 2, 19, 20, 8, 3, 1, 2, 20, 35, 5, 6, 4, 2, 21, 22, 5, 8, 5, 2, 22, 23, 5, 6, 4, 2, 23, 24, 5, 8, 5, 2, 24, 35, 3, 2, 2, 2, 25, 26, 5, 8, 5, 2, 26, 27, 5, 6, 4, 2, 27, 35, 3, 2, 2, 2, 28, 29, 5, 6, 4, 2, 29, 30, 5, 8, 5, 2, 30, 35, 3, 2, 2, 2, 31, 32, 7, 5, 2, 2, 32, 35, 5, 4, 3, 6, 33, 35, 7, 6, 2, 2, 34, 19, 3, 2, 2, 2, 34, 21, 3, 2, 2, 2, 34, 25, 3, 2, 2, 2, 34, 28, 3, 2, 2, 2, 34, 31, 3, 2, 2, 2, 34, 33, 3, 2, 2, 2, 35, 44, 3, 2, 2, 2, 36, 37, 12, 5, 2, 2, 37, 38, 7, 3, 2, 2, 38, 43, 5, 4, 3, 6, 39, 40, 12, 4, 2, 2, 40, 41, 7, 4, 2, 2, 41, 43, 5, 4, 3, 5, 42, 36, 3, 2, 2, 2, 42, 39, 3, 2, 2, 2, 43, 46, 3, 2, 2, 2, 44, 42, 3, 2, 2, 2, 44, 45, 3, 2, 2, 2, 45, 5, 3, 2, 2, 2, 46, 44, 3, 2, 2, 2, 47, 58, 5, 12, 7, 2, 48, 49, 5, 10, 6, 2, 49, 50, 7, 9, 2, 2, 50, 51, 5, 4, 3, 2, 51, 52, 7, 10, 2, 2, 52, 58, 3, 2, 2, 2, 53, 54, 7, 9, 2, 2, 54, 55, 5, 4, 3, 2, 55, 56, 7, 10, 2, 2, 56, 58, 3, 2, 2, 2, 57, 47, 3, 2, 2, 2, 57, 48, 3, 2, 2, 2, 57, 53, 3, 2, 2, 2, 58, 7, 3, 2, 2, 2, 59, 66, 7, 6, 2, 2, 60, 62, 7, 7, 2, 2, 61, 60, 3, 2, 2, 2, 62, 63, 3, 2, 2, 2, 63, 61, 3, 2, 2, 2, 63, 64, 3, 2, 2, 2, 64, 66, 3, 2, 2, 2, 65, 59, 3, 2, 2, 2, 65, 61, 3, 2, 2, 2, 66, 9, 3, 2, 2, 2, 67, 68, 9, 2, 2, 2, 68, 11, 3, 2, 2, 2, 69, 70, 7, 11, 2, 2, 70, 71, 7, 8, 2, 2, 71, 79, 5, 14, 8, 2, 72, 73, 7, 12, 2, 2, 73, 74, 7, 8, 2, 2, 74, 79, 5, 14, 8, 2, 75, 76, 7, 13, 2, 2, 76, 77, 7, 8, 2, 2, 77, 79, 5, 14, 8, 2, 78, 69, 3, 2, 2, 2, 78, 72, 3, 2, 2, 2, 78, 75, 3, 2, 2, 2, 79, 13, 3, 2, 2, 2, 80, 81, 9, 3, 2, 2, 81, 15, 3, 2, 2, 2, 9, 34, 42, 44, 57, 63, 65, 78] \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelection.tokens b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelection.tokens new file mode 100644 index 0000000000000..bbc43b16643d9 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelection.tokens @@ -0,0 +1,29 @@ +AND=1 +OR=2 +NOT=3 +STAR=4 +PLUS=5 +COLON=6 +LPAREN=7 +RPAREN=8 +NAME=9 +NAME_SUBSTRING=10 +STATUS=11 +SINKS=12 +ROOTS=13 +QUOTED_STRING=14 +UNQUOTED_STRING=15 +WS=16 +'and'=1 +'or'=2 +'not'=3 +'*'=4 +'+'=5 +':'=6 +'('=7 +')'=8 +'name'=9 +'name_substring'=10 +'status'=11 +'sinks'=12 +'roots'=13 diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.interp b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.interp new file mode 100644 index 0000000000000..c7fa923217617 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.interp @@ -0,0 +1,65 @@ +token literal names: +null +'and' +'or' +'not' +'*' +'+' +':' +'(' +')' +'name' +'name_substring' +'status' +'sinks' +'roots' +null +null +null + +token symbolic names: +null +AND +OR +NOT +STAR +PLUS +COLON +LPAREN +RPAREN +NAME +NAME_SUBSTRING +STATUS +SINKS +ROOTS +QUOTED_STRING +UNQUOTED_STRING +WS + +rule names: +AND +OR +NOT +STAR +PLUS +COLON +LPAREN +RPAREN +NAME +NAME_SUBSTRING +STATUS +SINKS +ROOTS +QUOTED_STRING +UNQUOTED_STRING +WS + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[3, 51485, 51898, 1421, 44986, 20307, 1543, 60043, 49729, 2, 18, 118, 8, 1, 4, 2, 9, 2, 4, 3, 9, 3, 4, 4, 9, 4, 4, 5, 9, 5, 4, 6, 9, 6, 4, 7, 9, 7, 4, 8, 9, 8, 4, 9, 9, 9, 4, 10, 9, 10, 4, 11, 9, 11, 4, 12, 9, 12, 4, 13, 9, 13, 4, 14, 9, 14, 4, 15, 9, 15, 4, 16, 9, 16, 4, 17, 9, 17, 3, 2, 3, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 3, 3, 4, 3, 4, 3, 4, 3, 4, 3, 5, 3, 5, 3, 6, 3, 6, 3, 7, 3, 7, 3, 8, 3, 8, 3, 9, 3, 9, 3, 10, 3, 10, 3, 10, 3, 10, 3, 10, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 11, 3, 12, 3, 12, 3, 12, 3, 12, 3, 12, 3, 12, 3, 12, 3, 13, 3, 13, 3, 13, 3, 13, 3, 13, 3, 13, 3, 14, 3, 14, 3, 14, 3, 14, 3, 14, 3, 14, 3, 15, 3, 15, 7, 15, 98, 10, 15, 12, 15, 14, 15, 101, 11, 15, 3, 15, 3, 15, 3, 16, 3, 16, 7, 16, 107, 10, 16, 12, 16, 14, 16, 110, 11, 16, 3, 17, 6, 17, 113, 10, 17, 13, 17, 14, 17, 114, 3, 17, 3, 17, 2, 2, 2, 18, 3, 2, 3, 5, 2, 4, 7, 2, 5, 9, 2, 6, 11, 2, 7, 13, 2, 8, 15, 2, 9, 17, 2, 10, 19, 2, 11, 21, 2, 12, 23, 2, 13, 25, 2, 14, 27, 2, 15, 29, 2, 16, 31, 2, 17, 33, 2, 18, 3, 2, 6, 6, 2, 12, 12, 15, 15, 36, 36, 94, 94, 5, 2, 67, 92, 97, 97, 99, 124, 6, 2, 50, 59, 67, 92, 97, 97, 99, 124, 5, 2, 11, 12, 15, 15, 34, 34, 2, 120, 2, 3, 3, 2, 2, 2, 2, 5, 3, 2, 2, 2, 2, 7, 3, 2, 2, 2, 2, 9, 3, 2, 2, 2, 2, 11, 3, 2, 2, 2, 2, 13, 3, 2, 2, 2, 2, 15, 3, 2, 2, 2, 2, 17, 3, 2, 2, 2, 2, 19, 3, 2, 2, 2, 2, 21, 3, 2, 2, 2, 2, 23, 3, 2, 2, 2, 2, 25, 3, 2, 2, 2, 2, 27, 3, 2, 2, 2, 2, 29, 3, 2, 2, 2, 2, 31, 3, 2, 2, 2, 2, 33, 3, 2, 2, 2, 3, 35, 3, 2, 2, 2, 5, 39, 3, 2, 2, 2, 7, 42, 3, 2, 2, 2, 9, 46, 3, 2, 2, 2, 11, 48, 3, 2, 2, 2, 13, 50, 3, 2, 2, 2, 15, 52, 3, 2, 2, 2, 17, 54, 3, 2, 2, 2, 19, 56, 3, 2, 2, 2, 21, 61, 3, 2, 2, 2, 23, 76, 3, 2, 2, 2, 25, 83, 3, 2, 2, 2, 27, 89, 3, 2, 2, 2, 29, 95, 3, 2, 2, 2, 31, 104, 3, 2, 2, 2, 33, 112, 3, 2, 2, 2, 35, 36, 7, 99, 2, 2, 36, 37, 7, 112, 2, 2, 37, 38, 7, 102, 2, 2, 38, 4, 3, 2, 2, 2, 39, 40, 7, 113, 2, 2, 40, 41, 7, 116, 2, 2, 41, 6, 3, 2, 2, 2, 42, 43, 7, 112, 2, 2, 43, 44, 7, 113, 2, 2, 44, 45, 7, 118, 2, 2, 45, 8, 3, 2, 2, 2, 46, 47, 7, 44, 2, 2, 47, 10, 3, 2, 2, 2, 48, 49, 7, 45, 2, 2, 49, 12, 3, 2, 2, 2, 50, 51, 7, 60, 2, 2, 51, 14, 3, 2, 2, 2, 52, 53, 7, 42, 2, 2, 53, 16, 3, 2, 2, 2, 54, 55, 7, 43, 2, 2, 55, 18, 3, 2, 2, 2, 56, 57, 7, 112, 2, 2, 57, 58, 7, 99, 2, 2, 58, 59, 7, 111, 2, 2, 59, 60, 7, 103, 2, 2, 60, 20, 3, 2, 2, 2, 61, 62, 7, 112, 2, 2, 62, 63, 7, 99, 2, 2, 63, 64, 7, 111, 2, 2, 64, 65, 7, 103, 2, 2, 65, 66, 7, 97, 2, 2, 66, 67, 7, 117, 2, 2, 67, 68, 7, 119, 2, 2, 68, 69, 7, 100, 2, 2, 69, 70, 7, 117, 2, 2, 70, 71, 7, 118, 2, 2, 71, 72, 7, 116, 2, 2, 72, 73, 7, 107, 2, 2, 73, 74, 7, 112, 2, 2, 74, 75, 7, 105, 2, 2, 75, 22, 3, 2, 2, 2, 76, 77, 7, 117, 2, 2, 77, 78, 7, 118, 2, 2, 78, 79, 7, 99, 2, 2, 79, 80, 7, 118, 2, 2, 80, 81, 7, 119, 2, 2, 81, 82, 7, 117, 2, 2, 82, 24, 3, 2, 2, 2, 83, 84, 7, 117, 2, 2, 84, 85, 7, 107, 2, 2, 85, 86, 7, 112, 2, 2, 86, 87, 7, 109, 2, 2, 87, 88, 7, 117, 2, 2, 88, 26, 3, 2, 2, 2, 89, 90, 7, 116, 2, 2, 90, 91, 7, 113, 2, 2, 91, 92, 7, 113, 2, 2, 92, 93, 7, 118, 2, 2, 93, 94, 7, 117, 2, 2, 94, 28, 3, 2, 2, 2, 95, 99, 7, 36, 2, 2, 96, 98, 10, 2, 2, 2, 97, 96, 3, 2, 2, 2, 98, 101, 3, 2, 2, 2, 99, 97, 3, 2, 2, 2, 99, 100, 3, 2, 2, 2, 100, 102, 3, 2, 2, 2, 101, 99, 3, 2, 2, 2, 102, 103, 7, 36, 2, 2, 103, 30, 3, 2, 2, 2, 104, 108, 9, 3, 2, 2, 105, 107, 9, 4, 2, 2, 106, 105, 3, 2, 2, 2, 107, 110, 3, 2, 2, 2, 108, 106, 3, 2, 2, 2, 108, 109, 3, 2, 2, 2, 109, 32, 3, 2, 2, 2, 110, 108, 3, 2, 2, 2, 111, 113, 9, 5, 2, 2, 112, 111, 3, 2, 2, 2, 113, 114, 3, 2, 2, 2, 114, 112, 3, 2, 2, 2, 114, 115, 3, 2, 2, 2, 115, 116, 3, 2, 2, 2, 116, 117, 8, 17, 2, 2, 117, 34, 3, 2, 2, 2, 6, 2, 99, 108, 114, 3, 8, 2, 2] \ No newline at end of file diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.tokens b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.tokens new file mode 100644 index 0000000000000..bbc43b16643d9 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.tokens @@ -0,0 +1,29 @@ +AND=1 +OR=2 +NOT=3 +STAR=4 +PLUS=5 +COLON=6 +LPAREN=7 +RPAREN=8 +NAME=9 +NAME_SUBSTRING=10 +STATUS=11 +SINKS=12 +ROOTS=13 +QUOTED_STRING=14 +UNQUOTED_STRING=15 +WS=16 +'and'=1 +'or'=2 +'not'=3 +'*'=4 +'+'=5 +':'=6 +'('=7 +')'=8 +'name'=9 +'name_substring'=10 +'status'=11 +'sinks'=12 +'roots'=13 diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.ts b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.ts new file mode 100644 index 0000000000000..4b2c88ec0da25 --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionLexer.ts @@ -0,0 +1,191 @@ +// Generated from /Users/briantu/repos/dagster/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 by ANTLR 4.9.0-SNAPSHOT + +import {CharStream} from 'antlr4ts/CharStream'; +import {Lexer} from 'antlr4ts/Lexer'; +import {Vocabulary} from 'antlr4ts/Vocabulary'; +import {VocabularyImpl} from 'antlr4ts/VocabularyImpl'; +import {ATN} from 'antlr4ts/atn/ATN'; +import {ATNDeserializer} from 'antlr4ts/atn/ATNDeserializer'; +import {LexerATNSimulator} from 'antlr4ts/atn/LexerATNSimulator'; +import * as Utils from 'antlr4ts/misc/Utils'; + +export class RunSelectionLexer extends Lexer { + public static readonly AND = 1; + public static readonly OR = 2; + public static readonly NOT = 3; + public static readonly STAR = 4; + public static readonly PLUS = 5; + public static readonly COLON = 6; + public static readonly LPAREN = 7; + public static readonly RPAREN = 8; + public static readonly NAME = 9; + public static readonly NAME_SUBSTRING = 10; + public static readonly STATUS = 11; + public static readonly SINKS = 12; + public static readonly ROOTS = 13; + public static readonly QUOTED_STRING = 14; + public static readonly UNQUOTED_STRING = 15; + public static readonly WS = 16; + + // tslint:disable:no-trailing-whitespace + public static readonly channelNames: string[] = ['DEFAULT_TOKEN_CHANNEL', 'HIDDEN']; + + // tslint:disable:no-trailing-whitespace + public static readonly modeNames: string[] = ['DEFAULT_MODE']; + + public static readonly ruleNames: string[] = [ + 'AND', + 'OR', + 'NOT', + 'STAR', + 'PLUS', + 'COLON', + 'LPAREN', + 'RPAREN', + 'NAME', + 'NAME_SUBSTRING', + 'STATUS', + 'SINKS', + 'ROOTS', + 'QUOTED_STRING', + 'UNQUOTED_STRING', + 'WS', + ]; + + private static readonly _LITERAL_NAMES: Array = [ + undefined, + "'and'", + "'or'", + "'not'", + "'*'", + "'+'", + "':'", + "'('", + "')'", + "'name'", + "'name_substring'", + "'status'", + "'sinks'", + "'roots'", + ]; + private static readonly _SYMBOLIC_NAMES: Array = [ + undefined, + 'AND', + 'OR', + 'NOT', + 'STAR', + 'PLUS', + 'COLON', + 'LPAREN', + 'RPAREN', + 'NAME', + 'NAME_SUBSTRING', + 'STATUS', + 'SINKS', + 'ROOTS', + 'QUOTED_STRING', + 'UNQUOTED_STRING', + 'WS', + ]; + public static readonly VOCABULARY: Vocabulary = new VocabularyImpl( + RunSelectionLexer._LITERAL_NAMES, + RunSelectionLexer._SYMBOLIC_NAMES, + [], + ); + + // @Override + // @NotNull + public get vocabulary(): Vocabulary { + return RunSelectionLexer.VOCABULARY; + } + // tslint:enable:no-trailing-whitespace + + constructor(input: CharStream) { + super(input); + this._interp = new LexerATNSimulator(RunSelectionLexer._ATN, this); + } + + // @Override + public get grammarFileName(): string { + return 'RunSelection.g4'; + } + + // @Override + public get ruleNames(): string[] { + return RunSelectionLexer.ruleNames; + } + + // @Override + public get serializedATN(): string { + return RunSelectionLexer._serializedATN; + } + + // @Override + public get channelNames(): string[] { + return RunSelectionLexer.channelNames; + } + + // @Override + public get modeNames(): string[] { + return RunSelectionLexer.modeNames; + } + + public static readonly _serializedATN: string = + '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02\x12v\b\x01\x04' + + '\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04' + + '\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r' + + '\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x03\x02\x03\x02' + + '\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x04\x03\x04\x03\x04\x03\x04' + + '\x03\x05\x03\x05\x03\x06\x03\x06\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03' + + '\t\x03\n\x03\n\x03\n\x03\n\x03\n\x03\v\x03\v\x03\v\x03\v\x03\v\x03\v\x03' + + '\v\x03\v\x03\v\x03\v\x03\v\x03\v\x03\v\x03\v\x03\v\x03\f\x03\f\x03\f\x03' + + '\f\x03\f\x03\f\x03\f\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03\x0E\x03\x0E' + + '\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0F\x03\x0F\x07\x0Fb\n\x0F\f\x0F' + + '\x0E\x0Fe\v\x0F\x03\x0F\x03\x0F\x03\x10\x03\x10\x07\x10k\n\x10\f\x10\x0E' + + '\x10n\v\x10\x03\x11\x06\x11q\n\x11\r\x11\x0E\x11r\x03\x11\x03\x11\x02' + + '\x02\x02\x12\x03\x02\x03\x05\x02\x04\x07\x02\x05\t\x02\x06\v\x02\x07\r' + + '\x02\b\x0F\x02\t\x11\x02\n\x13\x02\v\x15\x02\f\x17\x02\r\x19\x02\x0E\x1B' + + '\x02\x0F\x1D\x02\x10\x1F\x02\x11!\x02\x12\x03\x02\x06\x06\x02\f\f\x0F' + + '\x0F$$^^\x05\x02C\\aac|\x06\x022;C\\aac|\x05\x02\v\f\x0F\x0F""\x02x' + + '\x02\x03\x03\x02\x02\x02\x02\x05\x03\x02\x02\x02\x02\x07\x03\x02\x02\x02' + + '\x02\t\x03\x02\x02\x02\x02\v\x03\x02\x02\x02\x02\r\x03\x02\x02\x02\x02' + + '\x0F\x03\x02\x02\x02\x02\x11\x03\x02\x02\x02\x02\x13\x03\x02\x02\x02\x02' + + '\x15\x03\x02\x02\x02\x02\x17\x03\x02\x02\x02\x02\x19\x03\x02\x02\x02\x02' + + '\x1B\x03\x02\x02\x02\x02\x1D\x03\x02\x02\x02\x02\x1F\x03\x02\x02\x02\x02' + + "!\x03\x02\x02\x02\x03#\x03\x02\x02\x02\x05'\x03\x02\x02\x02\x07*\x03" + + '\x02\x02\x02\t.\x03\x02\x02\x02\v0\x03\x02\x02\x02\r2\x03\x02\x02\x02' + + '\x0F4\x03\x02\x02\x02\x116\x03\x02\x02\x02\x138\x03\x02\x02\x02\x15=\x03' + + '\x02\x02\x02\x17L\x03\x02\x02\x02\x19S\x03\x02\x02\x02\x1BY\x03\x02\x02' + + '\x02\x1D_\x03\x02\x02\x02\x1Fh\x03\x02\x02\x02!p\x03\x02\x02\x02#$\x07' + + "c\x02\x02$%\x07p\x02\x02%&\x07f\x02\x02&\x04\x03\x02\x02\x02'(\x07q\x02" + + '\x02()\x07t\x02\x02)\x06\x03\x02\x02\x02*+\x07p\x02\x02+,\x07q\x02\x02' + + ',-\x07v\x02\x02-\b\x03\x02\x02\x02./\x07,\x02\x02/\n\x03\x02\x02\x020' + + '1\x07-\x02\x021\f\x03\x02\x02\x0223\x07<\x02\x023\x0E\x03\x02\x02\x02' + + '45\x07*\x02\x025\x10\x03\x02\x02\x0267\x07+\x02\x027\x12\x03\x02\x02\x02' + + '89\x07p\x02\x029:\x07c\x02\x02:;\x07o\x02\x02;<\x07g\x02\x02<\x14\x03' + + '\x02\x02\x02=>\x07p\x02\x02>?\x07c\x02\x02?@\x07o\x02\x02@A\x07g\x02\x02' + + 'AB\x07a\x02\x02BC\x07u\x02\x02CD\x07w\x02\x02DE\x07d\x02\x02EF\x07u\x02' + + '\x02FG\x07v\x02\x02GH\x07t\x02\x02HI\x07k\x02\x02IJ\x07p\x02\x02JK\x07' + + 'i\x02\x02K\x16\x03\x02\x02\x02LM\x07u\x02\x02MN\x07v\x02\x02NO\x07c\x02' + + '\x02OP\x07v\x02\x02PQ\x07w\x02\x02QR\x07u\x02\x02R\x18\x03\x02\x02\x02' + + 'ST\x07u\x02\x02TU\x07k\x02\x02UV\x07p\x02\x02VW\x07m\x02\x02WX\x07u\x02' + + '\x02X\x1A\x03\x02\x02\x02YZ\x07t\x02\x02Z[\x07q\x02\x02[\\\x07q\x02\x02' + + '\\]\x07v\x02\x02]^\x07u\x02\x02^\x1C\x03\x02\x02\x02_c\x07$\x02\x02`b' + + '\n\x02\x02\x02a`\x03\x02\x02\x02be\x03\x02\x02\x02ca\x03\x02\x02\x02c' + + 'd\x03\x02\x02\x02df\x03\x02\x02\x02ec\x03\x02\x02\x02fg\x07$\x02\x02g' + + '\x1E\x03\x02\x02\x02hl\t\x03\x02\x02ik\t\x04\x02\x02ji\x03\x02\x02\x02' + + 'kn\x03\x02\x02\x02lj\x03\x02\x02\x02lm\x03\x02\x02\x02m \x03\x02\x02\x02' + + 'nl\x03\x02\x02\x02oq\t\x05\x02\x02po\x03\x02\x02\x02qr\x03\x02\x02\x02' + + 'rp\x03\x02\x02\x02rs\x03\x02\x02\x02st\x03\x02\x02\x02tu\b\x11\x02\x02' + + 'u"\x03\x02\x02\x02\x06\x02clr\x03\b\x02\x02'; + public static __ATN: ATN; + public static get _ATN(): ATN { + if (!RunSelectionLexer.__ATN) { + RunSelectionLexer.__ATN = new ATNDeserializer().deserialize( + Utils.toCharArray(RunSelectionLexer._serializedATN), + ); + } + + return RunSelectionLexer.__ATN; + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionListener.ts b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionListener.ts new file mode 100644 index 0000000000000..8582a20a208df --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionListener.ts @@ -0,0 +1,292 @@ +// Generated from /Users/briantu/repos/dagster/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 by ANTLR 4.9.0-SNAPSHOT + +import {ParseTreeListener} from 'antlr4ts/tree/ParseTreeListener'; + +import { + AllExpressionContext, + AndExpressionContext, + AttributeExprContext, + AttributeExpressionContext, + DownTraversalExpressionContext, + ExprContext, + FunctionCallExpressionContext, + FunctionNameContext, + NameExprContext, + NameSubstringExprContext, + NotExpressionContext, + OrExpressionContext, + ParenthesizedExpressionContext, + StartContext, + StatusAttributeExprContext, + TraversalAllowedExprContext, + TraversalAllowedExpressionContext, + TraversalContext, + UpAndDownTraversalExpressionContext, + UpTraversalExpressionContext, + ValueContext, +} from './RunSelectionParser'; + +/** + * This interface defines a complete listener for a parse tree produced by + * `RunSelectionParser`. + */ +export interface RunSelectionListener extends ParseTreeListener { + /** + * Enter a parse tree produced by the `TraversalAllowedExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterTraversalAllowedExpression?: (ctx: TraversalAllowedExpressionContext) => void; + /** + * Exit a parse tree produced by the `TraversalAllowedExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitTraversalAllowedExpression?: (ctx: TraversalAllowedExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UpAndDownTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterUpAndDownTraversalExpression?: (ctx: UpAndDownTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `UpAndDownTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitUpAndDownTraversalExpression?: (ctx: UpAndDownTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `UpTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterUpTraversalExpression?: (ctx: UpTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `UpTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitUpTraversalExpression?: (ctx: UpTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `DownTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterDownTraversalExpression?: (ctx: DownTraversalExpressionContext) => void; + /** + * Exit a parse tree produced by the `DownTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitDownTraversalExpression?: (ctx: DownTraversalExpressionContext) => void; + + /** + * Enter a parse tree produced by the `NotExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterNotExpression?: (ctx: NotExpressionContext) => void; + /** + * Exit a parse tree produced by the `NotExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitNotExpression?: (ctx: NotExpressionContext) => void; + + /** + * Enter a parse tree produced by the `AndExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterAndExpression?: (ctx: AndExpressionContext) => void; + /** + * Exit a parse tree produced by the `AndExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitAndExpression?: (ctx: AndExpressionContext) => void; + + /** + * Enter a parse tree produced by the `OrExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterOrExpression?: (ctx: OrExpressionContext) => void; + /** + * Exit a parse tree produced by the `OrExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitOrExpression?: (ctx: OrExpressionContext) => void; + + /** + * Enter a parse tree produced by the `AllExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterAllExpression?: (ctx: AllExpressionContext) => void; + /** + * Exit a parse tree produced by the `AllExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitAllExpression?: (ctx: AllExpressionContext) => void; + + /** + * Enter a parse tree produced by the `NameExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + enterNameExpr?: (ctx: NameExprContext) => void; + /** + * Exit a parse tree produced by the `NameExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + exitNameExpr?: (ctx: NameExprContext) => void; + + /** + * Enter a parse tree produced by the `NameSubstringExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + enterNameSubstringExpr?: (ctx: NameSubstringExprContext) => void; + /** + * Exit a parse tree produced by the `NameSubstringExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + exitNameSubstringExpr?: (ctx: NameSubstringExprContext) => void; + + /** + * Enter a parse tree produced by the `StatusAttributeExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + enterStatusAttributeExpr?: (ctx: StatusAttributeExprContext) => void; + /** + * Exit a parse tree produced by the `StatusAttributeExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + exitStatusAttributeExpr?: (ctx: StatusAttributeExprContext) => void; + + /** + * Enter a parse tree produced by the `AttributeExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterAttributeExpression?: (ctx: AttributeExpressionContext) => void; + /** + * Exit a parse tree produced by the `AttributeExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitAttributeExpression?: (ctx: AttributeExpressionContext) => void; + + /** + * Enter a parse tree produced by the `FunctionCallExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => void; + /** + * Exit a parse tree produced by the `FunctionCallExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => void; + + /** + * Enter a parse tree produced by the `ParenthesizedExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => void; + /** + * Exit a parse tree produced by the `ParenthesizedExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.start`. + * @param ctx the parse tree + */ + enterStart?: (ctx: StartContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.start`. + * @param ctx the parse tree + */ + exitStart?: (ctx: StartContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + enterExpr?: (ctx: ExprContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.expr`. + * @param ctx the parse tree + */ + exitExpr?: (ctx: ExprContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + enterTraversalAllowedExpr?: (ctx: TraversalAllowedExprContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + */ + exitTraversalAllowedExpr?: (ctx: TraversalAllowedExprContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.traversal`. + * @param ctx the parse tree + */ + enterTraversal?: (ctx: TraversalContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.traversal`. + * @param ctx the parse tree + */ + exitTraversal?: (ctx: TraversalContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.functionName`. + * @param ctx the parse tree + */ + enterFunctionName?: (ctx: FunctionNameContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.functionName`. + * @param ctx the parse tree + */ + exitFunctionName?: (ctx: FunctionNameContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + enterAttributeExpr?: (ctx: AttributeExprContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + */ + exitAttributeExpr?: (ctx: AttributeExprContext) => void; + + /** + * Enter a parse tree produced by `RunSelectionParser.value`. + * @param ctx the parse tree + */ + enterValue?: (ctx: ValueContext) => void; + /** + * Exit a parse tree produced by `RunSelectionParser.value`. + * @param ctx the parse tree + */ + exitValue?: (ctx: ValueContext) => void; +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionParser.ts b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionParser.ts new file mode 100644 index 0000000000000..7465534d8362a --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionParser.ts @@ -0,0 +1,1302 @@ +// Generated from /Users/briantu/repos/dagster/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 by ANTLR 4.9.0-SNAPSHOT + +import {FailedPredicateException} from 'antlr4ts/FailedPredicateException'; +import {NoViableAltException} from 'antlr4ts/NoViableAltException'; +import {Parser} from 'antlr4ts/Parser'; +import {ParserRuleContext} from 'antlr4ts/ParserRuleContext'; +import {RecognitionException} from 'antlr4ts/RecognitionException'; +import {RuleContext} from 'antlr4ts/RuleContext'; +//import { RuleVersion } from "antlr4ts/RuleVersion"; +import {Token} from 'antlr4ts/Token'; +import {TokenStream} from 'antlr4ts/TokenStream'; +import {Vocabulary} from 'antlr4ts/Vocabulary'; +import {VocabularyImpl} from 'antlr4ts/VocabularyImpl'; +import {ATN} from 'antlr4ts/atn/ATN'; +import {ATNDeserializer} from 'antlr4ts/atn/ATNDeserializer'; +import {ParserATNSimulator} from 'antlr4ts/atn/ParserATNSimulator'; +import * as Utils from 'antlr4ts/misc/Utils'; +import {TerminalNode} from 'antlr4ts/tree/TerminalNode'; + +import {RunSelectionListener} from './RunSelectionListener'; +import {RunSelectionVisitor} from './RunSelectionVisitor'; + +export class RunSelectionParser extends Parser { + public static readonly AND = 1; + public static readonly OR = 2; + public static readonly NOT = 3; + public static readonly STAR = 4; + public static readonly PLUS = 5; + public static readonly COLON = 6; + public static readonly LPAREN = 7; + public static readonly RPAREN = 8; + public static readonly NAME = 9; + public static readonly NAME_SUBSTRING = 10; + public static readonly STATUS = 11; + public static readonly SINKS = 12; + public static readonly ROOTS = 13; + public static readonly QUOTED_STRING = 14; + public static readonly UNQUOTED_STRING = 15; + public static readonly WS = 16; + public static readonly RULE_start = 0; + public static readonly RULE_expr = 1; + public static readonly RULE_traversalAllowedExpr = 2; + public static readonly RULE_traversal = 3; + public static readonly RULE_functionName = 4; + public static readonly RULE_attributeExpr = 5; + public static readonly RULE_value = 6; + // tslint:disable:no-trailing-whitespace + public static readonly ruleNames: string[] = [ + 'start', + 'expr', + 'traversalAllowedExpr', + 'traversal', + 'functionName', + 'attributeExpr', + 'value', + ]; + + private static readonly _LITERAL_NAMES: Array = [ + undefined, + "'and'", + "'or'", + "'not'", + "'*'", + "'+'", + "':'", + "'('", + "')'", + "'name'", + "'name_substring'", + "'status'", + "'sinks'", + "'roots'", + ]; + private static readonly _SYMBOLIC_NAMES: Array = [ + undefined, + 'AND', + 'OR', + 'NOT', + 'STAR', + 'PLUS', + 'COLON', + 'LPAREN', + 'RPAREN', + 'NAME', + 'NAME_SUBSTRING', + 'STATUS', + 'SINKS', + 'ROOTS', + 'QUOTED_STRING', + 'UNQUOTED_STRING', + 'WS', + ]; + public static readonly VOCABULARY: Vocabulary = new VocabularyImpl( + RunSelectionParser._LITERAL_NAMES, + RunSelectionParser._SYMBOLIC_NAMES, + [], + ); + + // @Override + // @NotNull + public get vocabulary(): Vocabulary { + return RunSelectionParser.VOCABULARY; + } + // tslint:enable:no-trailing-whitespace + + // @Override + public get grammarFileName(): string { + return 'RunSelection.g4'; + } + + // @Override + public get ruleNames(): string[] { + return RunSelectionParser.ruleNames; + } + + // @Override + public get serializedATN(): string { + return RunSelectionParser._serializedATN; + } + + protected createFailedPredicateException( + predicate?: string, + message?: string, + ): FailedPredicateException { + return new FailedPredicateException(this, predicate, message); + } + + constructor(input: TokenStream) { + super(input); + this._interp = new ParserATNSimulator(RunSelectionParser._ATN, this); + } + // @RuleVersion(0) + public start(): StartContext { + const _localctx: StartContext = new StartContext(this._ctx, this.state); + this.enterRule(_localctx, 0, RunSelectionParser.RULE_start); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 14; + this.expr(0); + this.state = 15; + this.match(RunSelectionParser.EOF); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + + public expr(): ExprContext; + public expr(_p: number): ExprContext; + // @RuleVersion(0) + public expr(_p?: number): ExprContext { + if (_p === undefined) { + _p = 0; + } + + const _parentctx: ParserRuleContext = this._ctx; + const _parentState: number = this.state; + let _localctx: ExprContext = new ExprContext(this._ctx, _parentState); + let _prevctx: ExprContext = _localctx; + const _startState: number = 2; + this.enterRecursionRule(_localctx, 2, RunSelectionParser.RULE_expr, _p); + try { + let _alt: number; + this.enterOuterAlt(_localctx, 1); + { + this.state = 32; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 0, this._ctx)) { + case 1: + { + _localctx = new TraversalAllowedExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + + this.state = 18; + this.traversalAllowedExpr(); + } + break; + + case 2: + { + _localctx = new UpAndDownTraversalExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 19; + this.traversal(); + this.state = 20; + this.traversalAllowedExpr(); + this.state = 21; + this.traversal(); + } + break; + + case 3: + { + _localctx = new UpTraversalExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 23; + this.traversal(); + this.state = 24; + this.traversalAllowedExpr(); + } + break; + + case 4: + { + _localctx = new DownTraversalExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 26; + this.traversalAllowedExpr(); + this.state = 27; + this.traversal(); + } + break; + + case 5: + { + _localctx = new NotExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 29; + this.match(RunSelectionParser.NOT); + this.state = 30; + this.expr(4); + } + break; + + case 6: + { + _localctx = new AllExpressionContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 31; + this.match(RunSelectionParser.STAR); + } + break; + } + this._ctx._stop = this._input.tryLT(-1); + this.state = 42; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); + while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + if (this._parseListeners != null) { + this.triggerExitRuleEvent(); + } + _prevctx = _localctx; + { + this.state = 40; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 1, this._ctx)) { + case 1: + { + _localctx = new AndExpressionContext(new ExprContext(_parentctx, _parentState)); + this.pushNewRecursionContext( + _localctx, + _startState, + RunSelectionParser.RULE_expr, + ); + this.state = 34; + if (!this.precpred(this._ctx, 3)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 3)'); + } + this.state = 35; + this.match(RunSelectionParser.AND); + this.state = 36; + this.expr(4); + } + break; + + case 2: + { + _localctx = new OrExpressionContext(new ExprContext(_parentctx, _parentState)); + this.pushNewRecursionContext( + _localctx, + _startState, + RunSelectionParser.RULE_expr, + ); + this.state = 37; + if (!this.precpred(this._ctx, 2)) { + throw this.createFailedPredicateException('this.precpred(this._ctx, 2)'); + } + this.state = 38; + this.match(RunSelectionParser.OR); + this.state = 39; + this.expr(3); + } + break; + } + } + } + this.state = 44; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.unrollRecursionContexts(_parentctx); + } + return _localctx; + } + // @RuleVersion(0) + public traversalAllowedExpr(): TraversalAllowedExprContext { + let _localctx: TraversalAllowedExprContext = new TraversalAllowedExprContext( + this._ctx, + this.state, + ); + this.enterRule(_localctx, 4, RunSelectionParser.RULE_traversalAllowedExpr); + try { + this.state = 55; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case RunSelectionParser.NAME: + case RunSelectionParser.NAME_SUBSTRING: + case RunSelectionParser.STATUS: + _localctx = new AttributeExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 45; + this.attributeExpr(); + } + break; + case RunSelectionParser.SINKS: + case RunSelectionParser.ROOTS: + _localctx = new FunctionCallExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 2); + { + this.state = 46; + this.functionName(); + this.state = 47; + this.match(RunSelectionParser.LPAREN); + this.state = 48; + this.expr(0); + this.state = 49; + this.match(RunSelectionParser.RPAREN); + } + break; + case RunSelectionParser.LPAREN: + _localctx = new ParenthesizedExpressionContext(_localctx); + this.enterOuterAlt(_localctx, 3); + { + this.state = 51; + this.match(RunSelectionParser.LPAREN); + this.state = 52; + this.expr(0); + this.state = 53; + this.match(RunSelectionParser.RPAREN); + } + break; + default: + throw new NoViableAltException(this); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public traversal(): TraversalContext { + const _localctx: TraversalContext = new TraversalContext(this._ctx, this.state); + this.enterRule(_localctx, 6, RunSelectionParser.RULE_traversal); + try { + let _alt: number; + this.state = 63; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case RunSelectionParser.STAR: + this.enterOuterAlt(_localctx, 1); + { + this.state = 57; + this.match(RunSelectionParser.STAR); + } + break; + case RunSelectionParser.PLUS: + this.enterOuterAlt(_localctx, 2); + { + this.state = 59; + this._errHandler.sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + this.state = 58; + this.match(RunSelectionParser.PLUS); + } + } + break; + default: + throw new NoViableAltException(this); + } + this.state = 61; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 4, this._ctx); + } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); + } + break; + default: + throw new NoViableAltException(this); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public functionName(): FunctionNameContext { + const _localctx: FunctionNameContext = new FunctionNameContext(this._ctx, this.state); + this.enterRule(_localctx, 8, RunSelectionParser.RULE_functionName); + let _la: number; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 65; + _la = this._input.LA(1); + if (!(_la === RunSelectionParser.SINKS || _la === RunSelectionParser.ROOTS)) { + this._errHandler.recoverInline(this); + } else { + if (this._input.LA(1) === Token.EOF) { + this.matchedEOF = true; + } + + this._errHandler.reportMatch(this); + this.consume(); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public attributeExpr(): AttributeExprContext { + let _localctx: AttributeExprContext = new AttributeExprContext(this._ctx, this.state); + this.enterRule(_localctx, 10, RunSelectionParser.RULE_attributeExpr); + try { + this.state = 76; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case RunSelectionParser.NAME: + _localctx = new NameExprContext(_localctx); + this.enterOuterAlt(_localctx, 1); + { + this.state = 67; + this.match(RunSelectionParser.NAME); + this.state = 68; + this.match(RunSelectionParser.COLON); + this.state = 69; + this.value(); + } + break; + case RunSelectionParser.NAME_SUBSTRING: + _localctx = new NameSubstringExprContext(_localctx); + this.enterOuterAlt(_localctx, 2); + { + this.state = 70; + this.match(RunSelectionParser.NAME_SUBSTRING); + this.state = 71; + this.match(RunSelectionParser.COLON); + this.state = 72; + this.value(); + } + break; + case RunSelectionParser.STATUS: + _localctx = new StatusAttributeExprContext(_localctx); + this.enterOuterAlt(_localctx, 3); + { + this.state = 73; + this.match(RunSelectionParser.STATUS); + this.state = 74; + this.match(RunSelectionParser.COLON); + this.state = 75; + this.value(); + } + break; + default: + throw new NoViableAltException(this); + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + public value(): ValueContext { + const _localctx: ValueContext = new ValueContext(this._ctx, this.state); + this.enterRule(_localctx, 12, RunSelectionParser.RULE_value); + let _la: number; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 78; + _la = this._input.LA(1); + if ( + !(_la === RunSelectionParser.QUOTED_STRING || _la === RunSelectionParser.UNQUOTED_STRING) + ) { + this._errHandler.recoverInline(this); + } else { + if (this._input.LA(1) === Token.EOF) { + this.matchedEOF = true; + } + + this._errHandler.reportMatch(this); + this.consume(); + } + } + } catch (re) { + if (re instanceof RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } else { + throw re; + } + } finally { + this.exitRule(); + } + return _localctx; + } + + public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { + switch (ruleIndex) { + case 1: + return this.expr_sempred(_localctx as ExprContext, predIndex); + } + return true; + } + private expr_sempred(_localctx: ExprContext, predIndex: number): boolean { + switch (predIndex) { + case 0: + return this.precpred(this._ctx, 3); + + case 1: + return this.precpred(this._ctx, 2); + } + return true; + } + + public static readonly _serializedATN: string = + '\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x12S\x04\x02' + + '\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07' + + '\t\x07\x04\b\t\b\x03\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x03\x03\x05\x03#\n\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03' + + '\x03\x03\x07\x03+\n\x03\f\x03\x0E\x03.\v\x03\x03\x04\x03\x04\x03\x04\x03' + + '\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x05\x04:\n\x04\x03' + + '\x05\x03\x05\x06\x05>\n\x05\r\x05\x0E\x05?\x05\x05B\n\x05\x03\x06\x03' + + '\x06\x03\x07\x03\x07\x03\x07\x03\x07\x03\x07\x03\x07\x03\x07\x03\x07\x03' + + '\x07\x05\x07O\n\x07\x03\b\x03\b\x03\b\x02\x02\x03\x04\t\x02\x02\x04\x02' + + '\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x02\x04\x03\x02\x0E\x0F\x03\x02\x10' + + '\x11\x02X\x02\x10\x03\x02\x02\x02\x04"\x03\x02\x02\x02\x069\x03\x02\x02' + + '\x02\bA\x03\x02\x02\x02\nC\x03\x02\x02\x02\fN\x03\x02\x02\x02\x0EP\x03' + + '\x02\x02\x02\x10\x11\x05\x04\x03\x02\x11\x12\x07\x02\x02\x03\x12\x03\x03' + + '\x02\x02\x02\x13\x14\b\x03\x01\x02\x14#\x05\x06\x04\x02\x15\x16\x05\b' + + '\x05\x02\x16\x17\x05\x06\x04\x02\x17\x18\x05\b\x05\x02\x18#\x03\x02\x02' + + '\x02\x19\x1A\x05\b\x05\x02\x1A\x1B\x05\x06\x04\x02\x1B#\x03\x02\x02\x02' + + '\x1C\x1D\x05\x06\x04\x02\x1D\x1E\x05\b\x05\x02\x1E#\x03\x02\x02\x02\x1F' + + ' \x07\x05\x02\x02 #\x05\x04\x03\x06!#\x07\x06\x02\x02"\x13\x03\x02\x02' + + '\x02"\x15\x03\x02\x02\x02"\x19\x03\x02\x02\x02"\x1C\x03\x02\x02\x02' + + '"\x1F\x03\x02\x02\x02"!\x03\x02\x02\x02#,\x03\x02\x02\x02$%\f\x05\x02' + + "\x02%&\x07\x03\x02\x02&+\x05\x04\x03\x06'(\f\x04\x02\x02()\x07\x04\x02" + + "\x02)+\x05\x04\x03\x05*$\x03\x02\x02\x02*'\x03\x02\x02\x02+.\x03\x02" + + '\x02\x02,*\x03\x02\x02\x02,-\x03\x02\x02\x02-\x05\x03\x02\x02\x02.,\x03' + + '\x02\x02\x02/:\x05\f\x07\x0201\x05\n\x06\x0212\x07\t\x02\x0223\x05\x04' + + '\x03\x0234\x07\n\x02\x024:\x03\x02\x02\x0256\x07\t\x02\x0267\x05\x04\x03' + + '\x0278\x07\n\x02\x028:\x03\x02\x02\x029/\x03\x02\x02\x0290\x03\x02\x02' + + '\x0295\x03\x02\x02\x02:\x07\x03\x02\x02\x02;B\x07\x06\x02\x02<>\x07\x07' + + '\x02\x02=<\x03\x02\x02\x02>?\x03\x02\x02\x02?=\x03\x02\x02\x02?@\x03\x02' + + '\x02\x02@B\x03\x02\x02\x02A;\x03\x02\x02\x02A=\x03\x02\x02\x02B\t\x03' + + '\x02\x02\x02CD\t\x02\x02\x02D\v\x03\x02\x02\x02EF\x07\v\x02\x02FG\x07' + + '\b\x02\x02GO\x05\x0E\b\x02HI\x07\f\x02\x02IJ\x07\b\x02\x02JO\x05\x0E\b' + + '\x02KL\x07\r\x02\x02LM\x07\b\x02\x02MO\x05\x0E\b\x02NE\x03\x02\x02\x02' + + 'NH\x03\x02\x02\x02NK\x03\x02\x02\x02O\r\x03\x02\x02\x02PQ\t\x03\x02\x02' + + 'Q\x0F\x03\x02\x02\x02\t"*,9?AN'; + public static __ATN: ATN; + public static get _ATN(): ATN { + if (!RunSelectionParser.__ATN) { + RunSelectionParser.__ATN = new ATNDeserializer().deserialize( + Utils.toCharArray(RunSelectionParser._serializedATN), + ); + } + + return RunSelectionParser.__ATN; + } +} + +export class StartContext extends ParserRuleContext { + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public EOF(): TerminalNode { + return this.getToken(RunSelectionParser.EOF, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_start; + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterStart) { + listener.enterStart(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitStart) { + listener.exitStart(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitStart) { + return visitor.visitStart(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_expr; + } + public copyFrom(ctx: ExprContext): void { + super.copyFrom(ctx); + } +} +export class TraversalAllowedExpressionContext extends ExprContext { + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterTraversalAllowedExpression) { + listener.enterTraversalAllowedExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitTraversalAllowedExpression) { + listener.exitTraversalAllowedExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitTraversalAllowedExpression) { + return visitor.visitTraversalAllowedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UpAndDownTraversalExpressionContext extends ExprContext { + public traversal(): TraversalContext[]; + public traversal(i: number): TraversalContext; + public traversal(i?: number): TraversalContext | TraversalContext[] { + if (i === undefined) { + return this.getRuleContexts(TraversalContext); + } else { + return this.getRuleContext(i, TraversalContext); + } + } + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterUpAndDownTraversalExpression) { + listener.enterUpAndDownTraversalExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitUpAndDownTraversalExpression) { + listener.exitUpAndDownTraversalExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitUpAndDownTraversalExpression) { + return visitor.visitUpAndDownTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class UpTraversalExpressionContext extends ExprContext { + public traversal(): TraversalContext { + return this.getRuleContext(0, TraversalContext); + } + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterUpTraversalExpression) { + listener.enterUpTraversalExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitUpTraversalExpression) { + listener.exitUpTraversalExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitUpTraversalExpression) { + return visitor.visitUpTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class DownTraversalExpressionContext extends ExprContext { + public traversalAllowedExpr(): TraversalAllowedExprContext { + return this.getRuleContext(0, TraversalAllowedExprContext); + } + public traversal(): TraversalContext { + return this.getRuleContext(0, TraversalContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterDownTraversalExpression) { + listener.enterDownTraversalExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitDownTraversalExpression) { + listener.exitDownTraversalExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitDownTraversalExpression) { + return visitor.visitDownTraversalExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class NotExpressionContext extends ExprContext { + public NOT(): TerminalNode { + return this.getToken(RunSelectionParser.NOT, 0); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterNotExpression) { + listener.enterNotExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitNotExpression) { + listener.exitNotExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitNotExpression) { + return visitor.visitNotExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class AndExpressionContext extends ExprContext { + public expr(): ExprContext[]; + public expr(i: number): ExprContext; + public expr(i?: number): ExprContext | ExprContext[] { + if (i === undefined) { + return this.getRuleContexts(ExprContext); + } else { + return this.getRuleContext(i, ExprContext); + } + } + public AND(): TerminalNode { + return this.getToken(RunSelectionParser.AND, 0); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterAndExpression) { + listener.enterAndExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitAndExpression) { + listener.exitAndExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitAndExpression) { + return visitor.visitAndExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class OrExpressionContext extends ExprContext { + public expr(): ExprContext[]; + public expr(i: number): ExprContext; + public expr(i?: number): ExprContext | ExprContext[] { + if (i === undefined) { + return this.getRuleContexts(ExprContext); + } else { + return this.getRuleContext(i, ExprContext); + } + } + public OR(): TerminalNode { + return this.getToken(RunSelectionParser.OR, 0); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterOrExpression) { + listener.enterOrExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitOrExpression) { + listener.exitOrExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitOrExpression) { + return visitor.visitOrExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class AllExpressionContext extends ExprContext { + public STAR(): TerminalNode { + return this.getToken(RunSelectionParser.STAR, 0); + } + constructor(ctx: ExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterAllExpression) { + listener.enterAllExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitAllExpression) { + listener.exitAllExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitAllExpression) { + return visitor.visitAllExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class TraversalAllowedExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_traversalAllowedExpr; + } + public copyFrom(ctx: TraversalAllowedExprContext): void { + super.copyFrom(ctx); + } +} +export class AttributeExpressionContext extends TraversalAllowedExprContext { + public attributeExpr(): AttributeExprContext { + return this.getRuleContext(0, AttributeExprContext); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterAttributeExpression) { + listener.enterAttributeExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitAttributeExpression) { + listener.exitAttributeExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitAttributeExpression) { + return visitor.visitAttributeExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class FunctionCallExpressionContext extends TraversalAllowedExprContext { + public functionName(): FunctionNameContext { + return this.getRuleContext(0, FunctionNameContext); + } + public LPAREN(): TerminalNode { + return this.getToken(RunSelectionParser.LPAREN, 0); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public RPAREN(): TerminalNode { + return this.getToken(RunSelectionParser.RPAREN, 0); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterFunctionCallExpression) { + listener.enterFunctionCallExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitFunctionCallExpression) { + listener.exitFunctionCallExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitFunctionCallExpression) { + return visitor.visitFunctionCallExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class ParenthesizedExpressionContext extends TraversalAllowedExprContext { + public LPAREN(): TerminalNode { + return this.getToken(RunSelectionParser.LPAREN, 0); + } + public expr(): ExprContext { + return this.getRuleContext(0, ExprContext); + } + public RPAREN(): TerminalNode { + return this.getToken(RunSelectionParser.RPAREN, 0); + } + constructor(ctx: TraversalAllowedExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterParenthesizedExpression) { + listener.enterParenthesizedExpression(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitParenthesizedExpression) { + listener.exitParenthesizedExpression(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitParenthesizedExpression) { + return visitor.visitParenthesizedExpression(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class TraversalContext extends ParserRuleContext { + public STAR(): TerminalNode | undefined { + return this.tryGetToken(RunSelectionParser.STAR, 0); + } + public PLUS(): TerminalNode[]; + public PLUS(i: number): TerminalNode; + public PLUS(i?: number): TerminalNode | TerminalNode[] { + if (i === undefined) { + return this.getTokens(RunSelectionParser.PLUS); + } else { + return this.getToken(RunSelectionParser.PLUS, i); + } + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_traversal; + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterTraversal) { + listener.enterTraversal(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitTraversal) { + listener.exitTraversal(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitTraversal) { + return visitor.visitTraversal(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class FunctionNameContext extends ParserRuleContext { + public SINKS(): TerminalNode | undefined { + return this.tryGetToken(RunSelectionParser.SINKS, 0); + } + public ROOTS(): TerminalNode | undefined { + return this.tryGetToken(RunSelectionParser.ROOTS, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_functionName; + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterFunctionName) { + listener.enterFunctionName(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitFunctionName) { + listener.exitFunctionName(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitFunctionName) { + return visitor.visitFunctionName(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class AttributeExprContext extends ParserRuleContext { + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_attributeExpr; + } + public copyFrom(ctx: AttributeExprContext): void { + super.copyFrom(ctx); + } +} +export class NameExprContext extends AttributeExprContext { + public NAME(): TerminalNode { + return this.getToken(RunSelectionParser.NAME, 0); + } + public COLON(): TerminalNode { + return this.getToken(RunSelectionParser.COLON, 0); + } + public value(): ValueContext { + return this.getRuleContext(0, ValueContext); + } + constructor(ctx: AttributeExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterNameExpr) { + listener.enterNameExpr(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitNameExpr) { + listener.exitNameExpr(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitNameExpr) { + return visitor.visitNameExpr(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class NameSubstringExprContext extends AttributeExprContext { + public NAME_SUBSTRING(): TerminalNode { + return this.getToken(RunSelectionParser.NAME_SUBSTRING, 0); + } + public COLON(): TerminalNode { + return this.getToken(RunSelectionParser.COLON, 0); + } + public value(): ValueContext { + return this.getRuleContext(0, ValueContext); + } + constructor(ctx: AttributeExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterNameSubstringExpr) { + listener.enterNameSubstringExpr(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitNameSubstringExpr) { + listener.exitNameSubstringExpr(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitNameSubstringExpr) { + return visitor.visitNameSubstringExpr(this); + } else { + return visitor.visitChildren(this); + } + } +} +export class StatusAttributeExprContext extends AttributeExprContext { + public STATUS(): TerminalNode { + return this.getToken(RunSelectionParser.STATUS, 0); + } + public COLON(): TerminalNode { + return this.getToken(RunSelectionParser.COLON, 0); + } + public value(): ValueContext { + return this.getRuleContext(0, ValueContext); + } + constructor(ctx: AttributeExprContext) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterStatusAttributeExpr) { + listener.enterStatusAttributeExpr(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitStatusAttributeExpr) { + listener.exitStatusAttributeExpr(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitStatusAttributeExpr) { + return visitor.visitStatusAttributeExpr(this); + } else { + return visitor.visitChildren(this); + } + } +} + +export class ValueContext extends ParserRuleContext { + public QUOTED_STRING(): TerminalNode | undefined { + return this.tryGetToken(RunSelectionParser.QUOTED_STRING, 0); + } + public UNQUOTED_STRING(): TerminalNode | undefined { + return this.tryGetToken(RunSelectionParser.UNQUOTED_STRING, 0); + } + constructor(parent: ParserRuleContext | undefined, invokingState: number) { + super(parent, invokingState); + } + // @Override + public get ruleIndex(): number { + return RunSelectionParser.RULE_value; + } + // @Override + public enterRule(listener: RunSelectionListener): void { + if (listener.enterValue) { + listener.enterValue(this); + } + } + // @Override + public exitRule(listener: RunSelectionListener): void { + if (listener.exitValue) { + listener.exitValue(this); + } + } + // @Override + public accept(visitor: RunSelectionVisitor): Result { + if (visitor.visitValue) { + return visitor.visitValue(this); + } else { + return visitor.visitChildren(this); + } + } +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionVisitor.ts b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionVisitor.ts new file mode 100644 index 0000000000000..f3b9fbde7220d --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/run-selection/generated/RunSelectionVisitor.ts @@ -0,0 +1,197 @@ +// Generated from /Users/briantu/repos/dagster/js_modules/dagster-ui/packages/ui-core/src/run-selection/RunSelection.g4 by ANTLR 4.9.0-SNAPSHOT + +import {ParseTreeVisitor} from 'antlr4ts/tree/ParseTreeVisitor'; + +import { + AllExpressionContext, + AndExpressionContext, + AttributeExprContext, + AttributeExpressionContext, + DownTraversalExpressionContext, + ExprContext, + FunctionCallExpressionContext, + FunctionNameContext, + NameExprContext, + NameSubstringExprContext, + NotExpressionContext, + OrExpressionContext, + ParenthesizedExpressionContext, + StartContext, + StatusAttributeExprContext, + TraversalAllowedExprContext, + TraversalAllowedExpressionContext, + TraversalContext, + UpAndDownTraversalExpressionContext, + UpTraversalExpressionContext, + ValueContext, +} from './RunSelectionParser'; + +/** + * This interface defines a complete generic visitor for a parse tree produced + * by `RunSelectionParser`. + * + * @param The return type of the visit operation. Use `void` for + * operations with no return type. + */ +export interface RunSelectionVisitor extends ParseTreeVisitor { + /** + * Visit a parse tree produced by the `TraversalAllowedExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitTraversalAllowedExpression?: (ctx: TraversalAllowedExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UpAndDownTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUpAndDownTraversalExpression?: (ctx: UpAndDownTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `UpTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitUpTraversalExpression?: (ctx: UpTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `DownTraversalExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitDownTraversalExpression?: (ctx: DownTraversalExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `NotExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitNotExpression?: (ctx: NotExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `AndExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAndExpression?: (ctx: AndExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `OrExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitOrExpression?: (ctx: OrExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `AllExpression` + * labeled alternative in `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAllExpression?: (ctx: AllExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `NameExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitNameExpr?: (ctx: NameExprContext) => Result; + + /** + * Visit a parse tree produced by the `NameSubstringExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitNameSubstringExpr?: (ctx: NameSubstringExprContext) => Result; + + /** + * Visit a parse tree produced by the `StatusAttributeExpr` + * labeled alternative in `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitStatusAttributeExpr?: (ctx: StatusAttributeExprContext) => Result; + + /** + * Visit a parse tree produced by the `AttributeExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAttributeExpression?: (ctx: AttributeExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `FunctionCallExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitFunctionCallExpression?: (ctx: FunctionCallExpressionContext) => Result; + + /** + * Visit a parse tree produced by the `ParenthesizedExpression` + * labeled alternative in `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.start`. + * @param ctx the parse tree + * @return the visitor result + */ + visitStart?: (ctx: StartContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.expr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitExpr?: (ctx: ExprContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.traversalAllowedExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitTraversalAllowedExpr?: (ctx: TraversalAllowedExprContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.traversal`. + * @param ctx the parse tree + * @return the visitor result + */ + visitTraversal?: (ctx: TraversalContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.functionName`. + * @param ctx the parse tree + * @return the visitor result + */ + visitFunctionName?: (ctx: FunctionNameContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.attributeExpr`. + * @param ctx the parse tree + * @return the visitor result + */ + visitAttributeExpr?: (ctx: AttributeExprContext) => Result; + + /** + * Visit a parse tree produced by `RunSelectionParser.value`. + * @param ctx the parse tree + * @return the visitor result + */ + visitValue?: (ctx: ValueContext) => Result; +} diff --git a/js_modules/dagster-ui/packages/ui-core/src/runs/RawLogContent.tsx b/js_modules/dagster-ui/packages/ui-core/src/runs/RawLogContent.tsx index 38d7010a5231f..2ad237f6b8b1b 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/runs/RawLogContent.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/runs/RawLogContent.tsx @@ -74,7 +74,7 @@ export const RawLogContent = React.memo((props: Props) => { return ( <> - + {showScrollToTop ? ( { ) : null} - {location ? {location} : null} + {location ? {location} : null} ); }); @@ -350,16 +350,16 @@ const ContentContainer = styled.div` background-color: ${Colors.backgroundLight()}; `; -const FileContainer = styled.div` +const FileContainer = styled.div<{$isVisible: boolean}>` flex: 1; height: 100%; position: relative; display: flex; flex-direction: column; - ${({isVisible}: {isVisible: boolean}) => (isVisible ? null : 'display: none;')} + ${({$isVisible}) => ($isVisible ? null : 'display: none;')} `; -const FileFooter = styled.div` +const FileFooter = styled.div<{$isVisible: boolean}>` display: flex; flex-direction: row; align-items: center; @@ -369,7 +369,7 @@ const FileFooter = styled.div` color: ${Colors.textLight()}; padding: 2px 5px; font-size: 0.85em; - ${({isVisible}: {isVisible: boolean}) => (isVisible ? null : 'display: none;')} + ${({$isVisible}) => ($isVisible ? null : 'display: none;')} `; const FileContent = styled.div` @@ -434,7 +434,7 @@ const ScrollToTop = styled.button` cursor: pointer; transition: background-color 100ms linear; - :hover { + &:hover { background-color: ${Colors.backgroundLighterHover()}; border-color: ${Colors.borderHover()}; } diff --git a/js_modules/dagster-ui/packages/ui-core/src/runs/RunStatusPez.tsx b/js_modules/dagster-ui/packages/ui-core/src/runs/RunStatusPez.tsx index c872313221cc8..6d607cf1d0850 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/runs/RunStatusPez.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/runs/RunStatusPez.tsx @@ -126,7 +126,7 @@ const SummaryContainer = styled.div` white-space: nowrap; padding: 4px 8px 8px; - :empty { + &:empty { display: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/runs/RunTimeline.tsx b/js_modules/dagster-ui/packages/ui-core/src/runs/RunTimeline.tsx index 558f4173e8edc..d5e19eeeaf4cc 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/runs/RunTimeline.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/runs/RunTimeline.tsx @@ -530,7 +530,7 @@ const DividerLabels = styled.div` width: 100%; overflow: hidden; - :first-child { + &:first-child { box-shadow: inset 1px 0 0 ${Colors.keylineDefault()}, inset -1px 0 0 ${Colors.keylineDefault()}; @@ -542,7 +542,7 @@ const DateLabel = styled.div` padding: 8px 0; white-space: nowrap; - :not(:first-child) { + &:not(:first-child) { box-shadow: inset 1px 0 0 ${Colors.keylineDefault()}; } `; @@ -740,7 +740,7 @@ export const TimelineRowContainer = styled.div.attrs(({$height, $start overflow: hidden; transition: background-color 100ms linear; - :hover { + &:hover { background-color: ${Colors.backgroundDefaultHover()}; } `; @@ -784,7 +784,7 @@ export const RunChunk = styled.div` opacity 200ms linear, width 200ms ease-in-out; - :hover { + &:hover { opacity: 0.7; } .chunk-popover-target { diff --git a/js_modules/dagster-ui/packages/ui-core/src/runs/TickTagForRun.tsx b/js_modules/dagster-ui/packages/ui-core/src/runs/TickTagForRun.tsx index fd78700d8c04b..7ca0019eff593 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/runs/TickTagForRun.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/runs/TickTagForRun.tsx @@ -1,9 +1,13 @@ -import {Box, ButtonLink, MiddleTruncate, Tag} from '@dagster-io/ui-components'; +import {Box, MiddleTruncate, Tag} from '@dagster-io/ui-components'; import {useState} from 'react'; import {DagsterTag} from './RunTag'; import {InstigationSelector} from '../graphql/types'; import {TickDetailsDialog} from '../instigation/TickDetailsDialog'; +import {TickLogDialog} from '../ticks/TickLogDialog'; +import {TagActionsPopover} from '../ui/TagActions'; +import {buildRepoAddress} from '../workspace/buildRepoAddress'; +import {workspacePathFromAddress} from '../workspace/workspacePath'; interface Props { instigationSelector: InstigationSelector; @@ -12,26 +16,52 @@ interface Props { } export const TickTagForRun = ({instigationSelector, instigationType, tickId}: Props) => { - const [isOpen, setIsOpen] = useState(false); + const [showDetails, setShowDetails] = useState(false); + const [showLogs, setShowLogs] = useState(false); const icon = instigationType === DagsterTag.ScheduleName ? 'schedule' : 'sensors'; - const {name} = instigationSelector; + const {name, repositoryName, repositoryLocationName} = instigationSelector; + const repoAddress = buildRepoAddress(repositoryName, repositoryLocationName); + + const actions = [ + { + label: `View ${instigationType === DagsterTag.ScheduleName ? 'schedule' : 'sensor'}`, + to: workspacePathFromAddress( + repoAddress, + `${instigationType === DagsterTag.ScheduleName ? '/schedules' : '/sensors'}/${name}`, + ), + }, + { + label: 'View tick details', + onClick: () => setShowDetails(true), + }, + { + label: 'View tick logs', + onClick: () => setShowLogs(true), + }, + ]; return ( <> - - - Launched by  - setIsOpen(true)}> + + + + Launched by 
    -
    -
    -
    +
    + + setIsOpen(false)} + onClose={() => setShowDetails(false)} + instigationSelector={instigationSelector} + tickId={tickId} + /> + setShowLogs(false)} instigationSelector={instigationSelector} tickId={tickId} /> diff --git a/js_modules/dagster-ui/packages/ui-core/src/schedules/CronTag.tsx b/js_modules/dagster-ui/packages/ui-core/src/schedules/CronTag.tsx index a9032489b0cf9..27f3c982b1fe2 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/schedules/CronTag.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/schedules/CronTag.tsx @@ -53,7 +53,7 @@ const Container = styled.div` .bp5-popover-target { max-width: 100%; - :focus { + &:focus { outline: none; } } diff --git a/js_modules/dagster-ui/packages/ui-core/src/scripts/generateRunSelection.ts b/js_modules/dagster-ui/packages/ui-core/src/scripts/generateRunSelection.ts new file mode 100644 index 0000000000000..62f0631223b4b --- /dev/null +++ b/js_modules/dagster-ui/packages/ui-core/src/scripts/generateRunSelection.ts @@ -0,0 +1,16 @@ +import {execSync} from 'child_process'; +import path from 'path'; + +const RUN_SELECTION_GRAMMAR_FILE_PATH = path.resolve('./src/run-selection/RunSelection.g4'); +execSync(`antlr4ts -visitor -o ./src/run-selection/generated ${RUN_SELECTION_GRAMMAR_FILE_PATH}`); + +const files = [ + 'RunSelectionLexer.ts', + 'RunSelectionListener.ts', + 'RunSelectionParser.ts', + 'RunSelectionVisitor.ts', +]; + +files.forEach((file) => { + execSync(`yarn prettier ./src/run-selection/generated/${file} --write`); +}); diff --git a/js_modules/dagster-ui/packages/ui-core/src/search/SearchDialog.tsx b/js_modules/dagster-ui/packages/ui-core/src/search/SearchDialog.tsx index 5f50a72c81fed..e9855337ff37c 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/search/SearchDialog.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/search/SearchDialog.tsx @@ -260,7 +260,7 @@ export const SearchBox = styled.div` padding: 12px 20px 12px 12px; transition: all 100ms linear; - :hover { + &:hover { box-shadow: ${({$hasQueryString}) => $hasQueryString ? Colors.keylineDefault() : Colors.borderHover()} 0 0 0 1px inset; diff --git a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts index 4d9601757ca72..f810f35464a8a 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts +++ b/js_modules/dagster-ui/packages/ui-core/src/selection/SelectionAutoCompleteHighlighter.ts @@ -98,7 +98,7 @@ export class SyntaxHighlightingVisitor } visitAllExpression(ctx: AllExpressionContext) { - this.addClass(ctx, 'expression'); + this.addClass(ctx, 'expression value'); this.visitChildren(ctx); } visitIncompleteLeftQuotedStringValue(ctx: ParserRuleContext) { diff --git a/js_modules/dagster-ui/packages/ui-core/src/sensors/SensorPageAutomaterialize.tsx b/js_modules/dagster-ui/packages/ui-core/src/sensors/SensorPageAutomaterialize.tsx index 747d5e3600db5..c5c86a569183d 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/sensors/SensorPageAutomaterialize.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/sensors/SensorPageAutomaterialize.tsx @@ -167,7 +167,7 @@ export const SensorPageAutomaterialize = (props: Props) => { return ( <> - + Evaluation timeline diff --git a/js_modules/dagster-ui/packages/ui-core/src/ticks/TickLogDialog.tsx b/js_modules/dagster-ui/packages/ui-core/src/ticks/TickLogDialog.tsx index ea712305a0ca6..980cc804c5f49 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ticks/TickLogDialog.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ticks/TickLogDialog.tsx @@ -3,78 +3,74 @@ import { Button, Colors, Dialog, - DialogBody, DialogFooter, ExternalAnchorButton, Icon, NonIdealState, + SpinnerWithText, } from '@dagster-io/ui-components'; import {INSTIGATION_EVENT_LOG_FRAGMENT, InstigationEventLogTable} from './InstigationEventLogTable'; import {gql, useQuery} from '../apollo-client'; import {TickLogEventsQuery, TickLogEventsQueryVariables} from './types/TickLogDialog.types'; import {InstigationSelector} from '../graphql/types'; -import {HistoryTickFragment} from '../instigation/types/InstigationUtils.types'; import {TimestampDisplay} from '../schedules/TimestampDisplay'; export const TickLogDialog = ({ - tick, + tickId, + timestamp, instigationSelector, + isOpen, onClose, }: { - tick: HistoryTickFragment; + tickId: string | null; + timestamp?: number; instigationSelector: InstigationSelector; + isOpen: boolean; onClose: () => void; }) => { - const {data} = useQuery(TICK_LOG_EVENTS_QUERY, { - variables: {instigationSelector, tickId: tick.tickId}, - notifyOnNetworkStatusChange: true, - }); - - const events = - data?.instigationStateOrError.__typename === 'InstigationState' && - data?.instigationStateOrError.tick - ? data?.instigationStateOrError.tick.logEvents.events - : undefined; - return ( : null} + style={{width: '70vw', maxWidth: '1200px', minWidth: '800px'}} + title={ + + {timestamp ? ( + + Logs for {instigationSelector.name}: + + + ) : ( + Logs for {instigationSelector.name} + )} + + } > - - {events && events.length ? ( - - ) : ( - - No logs available - - )} - - - - + {tickId ? ( + + ) : null} + {/* Use z-index to force the footer to sit above the lines of the logs table */} + + + + + ); }; interface TickLogTableProps { - tick: HistoryTickFragment; + tickId: string; instigationSelector: InstigationSelector; } -export const QueryfulTickLogsTable = ({instigationSelector, tick}: TickLogTableProps) => { +export const QueryfulTickLogsTable = ({instigationSelector, tickId}: TickLogTableProps) => { const {data, loading} = useQuery( TICK_LOG_EVENTS_QUERY, { - variables: {instigationSelector, tickId: tick.tickId}, + variables: {instigationSelector, tickId}, + notifyOnNetworkStatusChange: true, }, ); @@ -84,6 +80,14 @@ export const QueryfulTickLogsTable = ({instigationSelector, tick}: TickLogTableP ? data?.instigationStateOrError.tick.logEvents.events : undefined; + if (loading) { + return ( + + + + ); + } + if (events && events.length) { return ( @@ -113,41 +117,37 @@ export const QueryfulTickLogsTable = ({instigationSelector, tick}: TickLogTableP flex={{justifyContent: 'center', alignItems: 'center'}} padding={{vertical: 48}} > - {loading ? ( - 'Loading logs…' - ) : ( - -
    - Your evaluation did not emit any logs. To learn how to emit logs in your evaluation, - visit the documentation for more information. -
    - {tickStatus === 'FAILURE' && ( - <> -
    - For failed evaluations, logs will only be displayed if your Dagster and Dagster - Cloud agent versions 1.5.14 or higher. -
    -
    Upgrade your Dagster versions to view logs for failed evaluations.
    - - )} -
    - } - action={ - instigationLoggingDocsUrl && ( - } - > - View documentation - - ) - } - /> - )} + +
    + Your evaluation did not emit any logs. To learn how to emit logs in your evaluation, + visit the documentation for more information. +
    + {tickStatus === 'FAILURE' && ( + <> +
    + For failed evaluations, logs will only be displayed if your Dagster and Dagster + Cloud agent versions 1.5.14 or higher. +
    +
    Upgrade your Dagster versions to view logs for failed evaluations.
    + + )} + + } + action={ + instigationLoggingDocsUrl && ( + } + > + View documentation + + ) + } + /> ); }; diff --git a/js_modules/dagster-ui/packages/ui-core/src/typeexplorer/TypeWithTooltip.tsx b/js_modules/dagster-ui/packages/ui-core/src/typeexplorer/TypeWithTooltip.tsx index 5ab6582a83de1..4e0c094cd8d7f 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/typeexplorer/TypeWithTooltip.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/typeexplorer/TypeWithTooltip.tsx @@ -36,7 +36,7 @@ export const DAGSTER_TYPE_WITH_TOOLTIP_FRAGMENT = gql` `; const TypeLink = styled(Link)` - :hover { + &:hover { text-decoration: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/ui/BaseFilters/FilterDropdown.tsx b/js_modules/dagster-ui/packages/ui-core/src/ui/BaseFilters/FilterDropdown.tsx index 48f72748e91c3..8633111ac972f 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ui/BaseFilters/FilterDropdown.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ui/BaseFilters/FilterDropdown.tsx @@ -400,9 +400,9 @@ const TextInputWrapper = styled.div` padding: 12px 16px; &, - :focus, - :active, - :hover { + &:focus, + &:active, + &:hover { box-shadow: none; background-color: ${Colors.popoverBackground()}; } diff --git a/js_modules/dagster-ui/packages/ui-core/src/ui/ClearButton.tsx b/js_modules/dagster-ui/packages/ui-core/src/ui/ClearButton.tsx index 415ad954c9e21..d0a0f7a6f3470 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ui/ClearButton.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ui/ClearButton.tsx @@ -13,15 +13,15 @@ export const ClearButton = styled.button` transition: background-color 100ms linear; } - :hover ${IconWrapper}, :focus ${IconWrapper} { + &:hover ${IconWrapper}, &:focus ${IconWrapper} { background-color: ${Colors.accentGrayHover()}; } - :active ${IconWrapper} { + &:active ${IconWrapper} { background-color: ${Colors.textDefault()}; } - :focus { + &:focus { outline: none; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/ui/SectionedLeftNav.tsx b/js_modules/dagster-ui/packages/ui-core/src/ui/SectionedLeftNav.tsx index 3952f2d14b291..b408c4d03380d 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ui/SectionedLeftNav.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ui/SectionedLeftNav.tsx @@ -507,22 +507,22 @@ const SectionHeader = styled.button<{ box-shadow: inset 0px 1px 0 ${Colors.keylineDefault()}, inset 0px -1px 0 ${Colors.keylineDefault()}; - :disabled { + &:disabled { cursor: default; } - :hover, - :active { + &:hover, + &:active { background-color: ${Colors.backgroundLightHover()}; } - :disabled:hover, - :disabled:active { + &:disabled:hover, + &:disabled:active { background-color: ${Colors.backgroundDisabled()}; } - :focus, - :active { + &:focus, + &:active { outline: none; } @@ -531,7 +531,7 @@ const SectionHeader = styled.button<{ ${({$open}) => ($open ? null : `transform: rotate(-90deg);`)} } - :disabled ${IconWrapper} { + &:disabled ${IconWrapper} { background-color: ${Colors.textDisabled()}; } @@ -540,11 +540,11 @@ const SectionHeader = styled.button<{ margin-left: 6px; } - :not(:disabled) ${StyledTag} { + &:not(:disabled) ${StyledTag} { cursor: pointer; } - :disabled ${StyledTag} { + &:disabled ${StyledTag} { color: ${Colors.textDisabled()}; } }`; diff --git a/js_modules/dagster-ui/packages/ui-core/src/ui/SideNavItem.tsx b/js_modules/dagster-ui/packages/ui-core/src/ui/SideNavItem.tsx index 126da6c56a51f..47619de7a1768 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ui/SideNavItem.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ui/SideNavItem.tsx @@ -76,14 +76,14 @@ const sharedSideNavItemStyle = css<{$active: boolean}>` user-select: none; width: 100%; - :focus { + &:focus { outline: none; background-color: ${({$active}) => $active ? Colors.backgroundBlue() : Colors.backgroundLight()}; } - :hover, - :active { + &:hover, + &:active { background-color: ${({$active}) => $active ? Colors.backgroundBlue() : Colors.backgroundLightHover()}; color: ${({$active}) => ($active ? Colors.textBlue() : Colors.textDefault())}; diff --git a/js_modules/dagster-ui/packages/ui-core/src/ui/TagActions.tsx b/js_modules/dagster-ui/packages/ui-core/src/ui/TagActions.tsx index 6a4e2a726d69a..493f3148bbbe1 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ui/TagActions.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ui/TagActions.tsx @@ -1,7 +1,7 @@ import {Box, Caption, Colors, Popover} from '@dagster-io/ui-components'; import * as React from 'react'; import {Link} from 'react-router-dom'; -import styled from 'styled-components'; +import styled, {css} from 'styled-components'; import {TagType} from '../runs/RunTag'; @@ -19,11 +19,9 @@ export const TagActions = ({data, actions}: {data: TagType; actions: TagAction[] {actions.map((action, ii) => 'to' in action ? ( - - - {action.label} - - + + {action.label} + ) : ( action.onClick(data)}> {action.label} @@ -63,7 +61,7 @@ const ActionContainer = styled(Box)` overflow: hidden; `; -const TagButton = styled.button` +const TagButtonSharedStyles = css` border: none; background: ${Colors.tooltipBackground()}; color: ${Colors.tooltipText()}; @@ -73,15 +71,29 @@ const TagButton = styled.button` opacity: 0.85; transition: opacity 50ms linear; - :not(:last-child) { + &:not(:last-child) { box-shadow: -1px 0 0 inset ${Colors.borderHover()}; } - :focus { + &:focus { outline: none; } +`; + +const TagButton = styled.button` + ${TagButtonSharedStyles} + + &:hover { + opacity: 1; + } +`; + +const TagButtonLink = styled(Link)` + ${TagButtonSharedStyles} :hover { + color: ${Colors.tooltipText()}; + text-decoration: none; opacity: 1; } `; diff --git a/js_modules/dagster-ui/packages/ui-core/src/ui/VirtualizedTable.tsx b/js_modules/dagster-ui/packages/ui-core/src/ui/VirtualizedTable.tsx index d29c096b1b7f2..c5c87886ac7e8 100644 --- a/js_modules/dagster-ui/packages/ui-core/src/ui/VirtualizedTable.tsx +++ b/js_modules/dagster-ui/packages/ui-core/src/ui/VirtualizedTable.tsx @@ -42,7 +42,7 @@ export const HeaderCell = ({ ...rest }: React.ComponentProps) => { // no text select - const clickStyle = onClick ? {cursor: 'pointer', userSelect: 'none'} : {}; + const clickStyle = onClick ? {cursor: 'pointer', userSelect: 'none' as const} : {}; return ( ` height: ${SECTION_HEADER_HEIGHT}px; text-align: left; - :focus, - :active { + &:focus, + &:active { outline: none; } - :hover { + &:hover { background-color: ${Colors.backgroundLightHover()}; } - ${IconWrapper}[aria-label="arrow_drop_down"] { + ${IconWrapper}[aria-label='arrow_drop_down'] { transition: transform 100ms linear; ${({$open}) => ($open ? null : `transform: rotate(-90deg);`)} } diff --git a/js_modules/dagster-ui/yarn.lock b/js_modules/dagster-ui/yarn.lock index 31c77e01dd912..cc614aadaf3b3 100644 --- a/js_modules/dagster-ui/yarn.lock +++ b/js_modules/dagster-ui/yarn.lock @@ -353,18 +353,6 @@ __metadata: languageName: node linkType: hard -"@babel/generator@npm:^7.25.6": - version: 7.25.6 - resolution: "@babel/generator@npm:7.25.6" - dependencies: - "@babel/types": "npm:^7.25.6" - "@jridgewell/gen-mapping": "npm:^0.3.5" - "@jridgewell/trace-mapping": "npm:^0.3.25" - jsesc: "npm:^2.5.1" - checksum: 10/541e4fbb6ea7806f44232d70f25bf09dee9a57fe43d559e375536870ca5261ebb4647fec3af40dcbb3325ea2a49aff040e12a4e6f88609eaa88f10c4e27e31f8 - languageName: node - linkType: hard - "@babel/helper-annotate-as-pure@npm:^7.18.6, @babel/helper-annotate-as-pure@npm:^7.22.5": version: 7.22.5 resolution: "@babel/helper-annotate-as-pure@npm:7.22.5" @@ -640,16 +628,6 @@ __metadata: languageName: node linkType: hard -"@babel/helper-module-imports@npm:^7.0.0, @babel/helper-module-imports@npm:^7.24.7": - version: 7.24.7 - resolution: "@babel/helper-module-imports@npm:7.24.7" - dependencies: - "@babel/traverse": "npm:^7.24.7" - "@babel/types": "npm:^7.24.7" - checksum: 10/df8bfb2bb18413aa151ecd63b7d5deb0eec102f924f9de6bc08022ced7ed8ca7fed914562d2f6fa5b59b74a5d6e255dc35612b2bc3b8abf361e13f61b3704770 - languageName: node - linkType: hard - "@babel/helper-module-imports@npm:^7.10.4, @babel/helper-module-imports@npm:^7.22.5": version: 7.22.5 resolution: "@babel/helper-module-imports@npm:7.22.5" @@ -668,6 +646,16 @@ __metadata: languageName: node linkType: hard +"@babel/helper-module-imports@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/helper-module-imports@npm:7.24.7" + dependencies: + "@babel/traverse": "npm:^7.24.7" + "@babel/types": "npm:^7.24.7" + checksum: 10/df8bfb2bb18413aa151ecd63b7d5deb0eec102f924f9de6bc08022ced7ed8ca7fed914562d2f6fa5b59b74a5d6e255dc35612b2bc3b8abf361e13f61b3704770 + languageName: node + linkType: hard + "@babel/helper-module-transforms@npm:^7.22.5, @babel/helper-module-transforms@npm:^7.22.9": version: 7.22.9 resolution: "@babel/helper-module-transforms@npm:7.22.9" @@ -874,13 +862,6 @@ __metadata: languageName: node linkType: hard -"@babel/helper-string-parser@npm:^7.24.8": - version: 7.24.8 - resolution: "@babel/helper-string-parser@npm:7.24.8" - checksum: 10/6d1bf8f27dd725ce02bdc6dffca3c95fb9ab8a06adc2edbd9c1c9d68500274230d1a609025833ed81981eff560045b6b38f7b4c6fb1ab19fc90e5004e3932535 - languageName: node - linkType: hard - "@babel/helper-validator-identifier@npm:^7.22.20": version: 7.22.20 resolution: "@babel/helper-validator-identifier@npm:7.22.20" @@ -1106,17 +1087,6 @@ __metadata: languageName: node linkType: hard -"@babel/parser@npm:^7.25.0, @babel/parser@npm:^7.25.6": - version: 7.25.6 - resolution: "@babel/parser@npm:7.25.6" - dependencies: - "@babel/types": "npm:^7.25.6" - bin: - parser: ./bin/babel-parser.js - checksum: 10/830aab72116aa14eb8d61bfa8f9d69fc8f3a43d909ce993cb4350ae14d3af1a2f740a54410a22d821c48a253263643dfecbc094f9608e6a70ce9ff3c0bbfe91a - languageName: node - linkType: hard - "@babel/plugin-bugfix-firefox-class-in-computed-class-key@npm:^7.24.7": version: 7.24.7 resolution: "@babel/plugin-bugfix-firefox-class-in-computed-class-key@npm:7.24.7" @@ -3301,17 +3271,6 @@ __metadata: languageName: node linkType: hard -"@babel/template@npm:^7.25.0": - version: 7.25.0 - resolution: "@babel/template@npm:7.25.0" - dependencies: - "@babel/code-frame": "npm:^7.24.7" - "@babel/parser": "npm:^7.25.0" - "@babel/types": "npm:^7.25.0" - checksum: 10/07ebecf6db8b28244b7397628e09c99e7a317b959b926d90455c7253c88df3677a5a32d1501d9749fe292a263ff51a4b6b5385bcabd5dadd3a48036f4d4949e0 - languageName: node - linkType: hard - "@babel/traverse@npm:^7.1.6, @babel/traverse@npm:^7.14.0, @babel/traverse@npm:^7.16.8, @babel/traverse@npm:^7.22.10, @babel/traverse@npm:^7.22.6, @babel/traverse@npm:^7.22.8": version: 7.23.2 resolution: "@babel/traverse@npm:7.23.2" @@ -3366,21 +3325,6 @@ __metadata: languageName: node linkType: hard -"@babel/traverse@npm:^7.4.5": - version: 7.25.6 - resolution: "@babel/traverse@npm:7.25.6" - dependencies: - "@babel/code-frame": "npm:^7.24.7" - "@babel/generator": "npm:^7.25.6" - "@babel/parser": "npm:^7.25.6" - "@babel/template": "npm:^7.25.0" - "@babel/types": "npm:^7.25.6" - debug: "npm:^4.3.1" - globals: "npm:^11.1.0" - checksum: 10/de75a918299bc27a44ec973e3f2fa8c7902bbd67bd5d39a0be656f3c1127f33ebc79c12696fbc8170a0b0e1072a966d4a2126578d7ea2e241b0aeb5d16edc738 - languageName: node - linkType: hard - "@babel/types@npm:^7.0.0, @babel/types@npm:^7.1.6, @babel/types@npm:^7.16.8, @babel/types@npm:^7.18.13, @babel/types@npm:^7.20.7, @babel/types@npm:^7.22.5, @babel/types@npm:^7.3.3, @babel/types@npm:^7.4.4, @babel/types@npm:^7.8.3": version: 7.22.5 resolution: "@babel/types@npm:7.22.5" @@ -3447,17 +3391,6 @@ __metadata: languageName: node linkType: hard -"@babel/types@npm:^7.25.0, @babel/types@npm:^7.25.6": - version: 7.25.6 - resolution: "@babel/types@npm:7.25.6" - dependencies: - "@babel/helper-string-parser": "npm:^7.24.8" - "@babel/helper-validator-identifier": "npm:^7.24.7" - to-fast-properties: "npm:^2.0.0" - checksum: 10/7b54665e1b51f525fe0f451efdd9fe7a4a6dfba3fd4956c3530bc77336b66ffe3d78c093796ed044119b5d213176af7cf326f317a2057c538d575c6cefcb3562 - languageName: node - linkType: hard - "@base2/pretty-print-object@npm:1.0.1": version: 1.0.1 resolution: "@base2/pretty-print-object@npm:1.0.1" @@ -3592,8 +3525,7 @@ __metadata: "@types/jest": "npm:^29.5.11" "@types/node": "npm:^16.11.20" "@types/react": "npm:^18.3.9" - "@types/react-dom": "npm:^18.3.0" - "@types/styled-components": "npm:^5.1.26" + "@types/react-dom": "npm:^18.3.1" "@types/uuid": "npm:^8.3.4" "@types/validator": "npm:^13" "@types/webpack-bundle-analyzer": "npm:^4" @@ -3617,7 +3549,8 @@ __metadata: react-router-dom: "npm:^5.3.0" react-router-dom-v5-compat: "npm:^6.3.0" recoil: "npm:^0.7.7" - styled-components: "npm:^5.3.3" + styled-components: "npm:^6" + stylis: "npm:^4" typescript: "npm:5.5.4" uuid: "npm:^9.0.0" validator: "npm:^13.7.0" @@ -3706,9 +3639,8 @@ __metadata: "@types/mdx-js__react": "npm:^1" "@types/react": "npm:^18.3.9" "@types/react-dates": "npm:^21.8.0" - "@types/react-dom": "npm:^18.3.0" + "@types/react-dom": "npm:^18.3.1" "@types/react-is": "npm:^18.3.0" - "@types/styled-components": "npm:^5.1.26" "@types/testing-library__jest-dom": "npm:^5.14.2" amator: "npm:^1.1.0" babel-jest: "npm:^27.4.6" @@ -3742,7 +3674,8 @@ __metadata: react: ^18.3.1 react-dom: ^18.3.1 react-is: ^18.3.1 - styled-components: ^5.3.3 + styled-components: ^6 + stylis: ^4 languageName: unknown linkType: soft @@ -3767,6 +3700,7 @@ __metadata: "@chromatic-com/storybook": "npm:^1.6.1" "@dagster-io/eslint-config": "workspace:*" "@dagster-io/ui-components": "workspace:*" + "@emotion/is-prop-valid": "npm:^1.3.1" "@graphql-codegen/add": "npm:^5.0.2" "@graphql-codegen/cli": "npm:^5.0.2" "@graphql-codegen/near-operation-file-preset": "npm:^3.0.0" @@ -3800,10 +3734,9 @@ __metadata: "@types/mdx-js__react": "npm:^1" "@types/qs": "npm:^6.9.6" "@types/react": "npm:^18.3.9" - "@types/react-dom": "npm:^18.3.0" + "@types/react-dom": "npm:^18.3.1" "@types/react-router": "npm:^5.1.17" "@types/react-router-dom": "npm:^5.3.3" - "@types/styled-components": "npm:^5.1.26" "@types/testing-library__jest-dom": "npm:^5.14.2" "@types/ws": "npm:^6.0.3" "@typescript-eslint/eslint-plugin": "npm:^8.9.0" @@ -3870,7 +3803,8 @@ __metadata: resize-observer-polyfill: "npm:^1.5.1" storybook: "npm:^8.2.7" strip-markdown: "npm:^6.0.0" - styled-components: "npm:^5.3.3" + styled-components: "npm:^6" + stylis: "npm:^4" subscriptions-transport-ws: "npm:^0.9.15" ts-node: "npm:9.1.1" ts-prune: "npm:0.10.3" @@ -3889,7 +3823,8 @@ __metadata: react-router: ^5.2.1 react-router-dom: ^5.3.0 react-router-dom-v5-compat: ^6.3.0 - styled-components: ^5.3.3 + styled-components: ^6 + stylis: ^4 languageName: unknown linkType: soft @@ -3909,7 +3844,16 @@ __metadata: languageName: node linkType: hard -"@emotion/is-prop-valid@npm:^1.1.0": +"@emotion/is-prop-valid@npm:1.2.2": + version: 1.2.2 + resolution: "@emotion/is-prop-valid@npm:1.2.2" + dependencies: + "@emotion/memoize": "npm:^0.8.1" + checksum: 10/0fa3960abfbe845d40cc230ab8c9408e1f33d3c03b321980359911c7212133cdcb0344d249e9dab23342b304567eece7a10ec44b986f7230e0640ba00049dceb + languageName: node + linkType: hard + +"@emotion/is-prop-valid@npm:^1.3.1": version: 1.3.1 resolution: "@emotion/is-prop-valid@npm:1.3.1" dependencies: @@ -3918,6 +3862,13 @@ __metadata: languageName: node linkType: hard +"@emotion/memoize@npm:^0.8.1": + version: 0.8.1 + resolution: "@emotion/memoize@npm:0.8.1" + checksum: 10/a19cc01a29fcc97514948eaab4dc34d8272e934466ed87c07f157887406bc318000c69ae6f813a9001c6a225364df04249842a50e692ef7a9873335fbcc141b0 + languageName: node + linkType: hard + "@emotion/memoize@npm:^0.9.0": version: 0.9.0 resolution: "@emotion/memoize@npm:0.9.0" @@ -3925,17 +3876,10 @@ __metadata: languageName: node linkType: hard -"@emotion/stylis@npm:^0.8.4": - version: 0.8.5 - resolution: "@emotion/stylis@npm:0.8.5" - checksum: 10/ceaa673457f501a393cb52873b2bc34dbe35ef0fb8faa4b943d73ecbbb42bc3cea53b87cbf482038b7b9b1f95859be3d8b58d508422b4d15aec5b62314cc3c1e - languageName: node - linkType: hard - -"@emotion/unitless@npm:^0.7.4": - version: 0.7.5 - resolution: "@emotion/unitless@npm:0.7.5" - checksum: 10/f976e5345b53fae9414a7b2e7a949aa6b52f8bdbcc84458b1ddc0729e77ba1d1dfdff9960e0da60183877873d3a631fa24d9695dd714ed94bcd3ba5196586a6b +"@emotion/unitless@npm:0.8.1": + version: 0.8.1 + resolution: "@emotion/unitless@npm:0.8.1" + checksum: 10/918f73c46ac0b7161e3c341cc07d651ce87e31ab1695e74b12adb7da6bb98dfbff8c69cf68a4e40d9eb3d820ca055dc1267aeb3007927ce88f98b885bf729b63 languageName: node linkType: hard @@ -7263,16 +7207,6 @@ __metadata: languageName: node linkType: hard -"@types/hoist-non-react-statics@npm:*": - version: 3.3.5 - resolution: "@types/hoist-non-react-statics@npm:3.3.5" - dependencies: - "@types/react": "npm:*" - hoist-non-react-statics: "npm:^3.3.0" - checksum: 10/b645b062a20cce6ab1245ada8274051d8e2e0b2ee5c6bd58215281d0ec6dae2f26631af4e2e7c8abe238cdcee73fcaededc429eef569e70908f82d0cc0ea31d7 - languageName: node - linkType: hard - "@types/html-minifier-terser@npm:^6.0.0": version: 6.1.0 resolution: "@types/html-minifier-terser@npm:6.1.0" @@ -7511,7 +7445,7 @@ __metadata: languageName: node linkType: hard -"@types/react-dom@npm:>=16.9.0, @types/react-dom@npm:^18.3.0": +"@types/react-dom@npm:>=16.9.0": version: 18.3.0 resolution: "@types/react-dom@npm:18.3.0" dependencies: @@ -7520,6 +7454,15 @@ __metadata: languageName: node linkType: hard +"@types/react-dom@npm:^18.3.1": + version: 18.3.1 + resolution: "@types/react-dom@npm:18.3.1" + dependencies: + "@types/react": "npm:*" + checksum: 10/33f9ba79b26641ddf00a8699c30066b7e3573ab254e97475bf08f82fab83a6d3ce8d4ebad86afeb49bb8df3374390a9ba93125cece33badc4b3e8f7eac3c84d8 + languageName: node + linkType: hard + "@types/react-is@npm:^18.3.0": version: 18.3.0 resolution: "@types/react-is@npm:18.3.0" @@ -7568,23 +7511,13 @@ __metadata: languageName: node linkType: hard -"@types/react@npm:*, @types/react@npm:>=16.9.0, @types/react@npm:^18.3.9": - version: 18.3.9 - resolution: "@types/react@npm:18.3.9" - dependencies: - "@types/prop-types": "npm:*" - csstype: "npm:^3.0.2" - checksum: 10/d1321e874e6523b0a944d4ce514c071cbe44501b04591e17c0b265c9a03fb3e4486337ae1bec74541b72a41f34beef157342205dd07b31d116f4d06fa39cf32f - languageName: node - linkType: hard - -"@types/react@npm:^16.8.0 || ^17.0.0 || ^18.0.0": - version: 18.3.3 - resolution: "@types/react@npm:18.3.3" +"@types/react@npm:*, @types/react@npm:>=16.9.0, @types/react@npm:^16.8.0 || ^17.0.0 || ^18.0.0, @types/react@npm:^18.3.9": + version: 18.3.12 + resolution: "@types/react@npm:18.3.12" dependencies: "@types/prop-types": "npm:*" csstype: "npm:^3.0.2" - checksum: 10/68e203b7f1f91d6cf21f33fc7af9d6d228035a26c83f514981e54aa3da695d0ec6af10c277c6336de1dd76c4adbe9563f3a21f80c4462000f41e5f370b46e96c + checksum: 10/c9bbdfeacd5347d2240e0d2cb5336bc57dbc1b9ff557b6c4024b49df83419e4955553518169d3736039f1b62608e15b35762a6c03d49bd86e33add4b43b19033 languageName: node linkType: hard @@ -7639,14 +7572,10 @@ __metadata: languageName: node linkType: hard -"@types/styled-components@npm:^5.1.26": - version: 5.1.34 - resolution: "@types/styled-components@npm:5.1.34" - dependencies: - "@types/hoist-non-react-statics": "npm:*" - "@types/react": "npm:*" - csstype: "npm:^3.0.2" - checksum: 10/3da291b46f03d378a0176c9d034deee7ee0684c5d62e1c5ce82f3be0972918eaa806f45c62e9a4f1c8d24c5ba6571c260caba2493fc7e82b528ac7d15903e2c1 +"@types/stylis@npm:4.2.5": + version: 4.2.5 + resolution: "@types/stylis@npm:4.2.5" + checksum: 10/f8dde326432a7047b6684b96442f0e2ade2cfe8c29bf56217fb8cbbe4763997051fa9dc0f8dba4aeed2fddb794b4bc91feba913b780666b3adc28198ac7c63d4 languageName: node linkType: hard @@ -9409,21 +9338,6 @@ __metadata: languageName: node linkType: hard -"babel-plugin-styled-components@npm:>= 1.12.0": - version: 2.1.4 - resolution: "babel-plugin-styled-components@npm:2.1.4" - dependencies: - "@babel/helper-annotate-as-pure": "npm:^7.22.5" - "@babel/helper-module-imports": "npm:^7.22.5" - "@babel/plugin-syntax-jsx": "npm:^7.22.5" - lodash: "npm:^4.17.21" - picomatch: "npm:^2.3.1" - peerDependencies: - styled-components: ">= 2" - checksum: 10/34f10dd4d44cf1c8605097dd4796e2d1443266ebc686f10a9f56b5d1492b5c3de9c13d7e30b075756610adf592ed807cc8145189d00b4454f6af9879a19a5e0b - languageName: node - linkType: hard - "babel-plugin-syntax-trailing-function-commas@npm:^7.0.0-beta.0": version: 7.0.0-beta.0 resolution: "babel-plugin-syntax-trailing-function-commas@npm:7.0.0-beta.0" @@ -10013,31 +9927,10 @@ __metadata: languageName: node linkType: hard -"caniuse-lite@npm:^1.0.0, caniuse-lite@npm:^1.0.30001517, caniuse-lite@npm:^1.0.30001565": - version: 1.0.30001606 - resolution: "caniuse-lite@npm:1.0.30001606" - checksum: 10/55ee377f9b5e09d290d2a60d339aa1fbab949d3086cfd0546d2896bc57f4df693cf69e9a0c828cb9622df039403927c66ec2d6a7ff4b7580f38846314bdb4800 - languageName: node - linkType: hard - -"caniuse-lite@npm:^1.0.30001579": - version: 1.0.30001617 - resolution: "caniuse-lite@npm:1.0.30001617" - checksum: 10/eac442b9ad12801086be19f6dc17056827fe398f1c05983357e2531c8183ee890ffc8fb973d54519ad7114a2fd47de8f33ec66d98565b995fef1c6ba02b5bc5b - languageName: node - linkType: hard - -"caniuse-lite@npm:^1.0.30001629": - version: 1.0.30001636 - resolution: "caniuse-lite@npm:1.0.30001636" - checksum: 10/9e6c5ab4c20df31df36720dda77cf6a781549ac2ad844bc0a416b327a793da21486358a1f85fdd6c39e22d336f70aac3b0e232f5f228cdff0ceb6e3e1c5e98fd - languageName: node - linkType: hard - -"caniuse-lite@npm:^1.0.30001646": - version: 1.0.30001653 - resolution: "caniuse-lite@npm:1.0.30001653" - checksum: 10/cd9b1c0fe03249e593789a11a9ef14f987b385e60441748945916b19e74e7bc5c82c40d4836496a647586651898741aed1598ae0792114a9f0d7d7fdb2b7deb0 +"caniuse-lite@npm:^1.0.0, caniuse-lite@npm:^1.0.30001517, caniuse-lite@npm:^1.0.30001565, caniuse-lite@npm:^1.0.30001579, caniuse-lite@npm:^1.0.30001629, caniuse-lite@npm:^1.0.30001646": + version: 1.0.30001686 + resolution: "caniuse-lite@npm:1.0.30001686" + checksum: 10/dc34d4daa992256b94def2894e478ba4d9786581dff3b180d642d74c7578f7d8958be985d9da5d08f09b81dd9811b653e4980616bae26b1896968cfdf8d535da languageName: node linkType: hard @@ -10997,7 +10890,7 @@ __metadata: languageName: node linkType: hard -"css-to-react-native@npm:^3.0.0": +"css-to-react-native@npm:3.2.0": version: 3.2.0 resolution: "css-to-react-native@npm:3.2.0" dependencies: @@ -11141,6 +11034,13 @@ __metadata: languageName: node linkType: hard +"csstype@npm:3.1.3": + version: 3.1.3 + resolution: "csstype@npm:3.1.3" + checksum: 10/f593cce41ff5ade23f44e77521e3a1bcc2c64107041e1bf6c3c32adc5187d0d60983292fda326154d20b01079e24931aa5b08e4467cc488b60bb1e7f6d478ade + languageName: node + linkType: hard + "csstype@npm:^3.0.2": version: 3.1.2 resolution: "csstype@npm:3.1.2" @@ -14521,7 +14421,7 @@ __metadata: languageName: node linkType: hard -"hoist-non-react-statics@npm:^3.0.0, hoist-non-react-statics@npm:^3.1.0, hoist-non-react-statics@npm:^3.2.1, hoist-non-react-statics@npm:^3.3.0, hoist-non-react-statics@npm:^3.3.2": +"hoist-non-react-statics@npm:^3.1.0, hoist-non-react-statics@npm:^3.2.1, hoist-non-react-statics@npm:^3.3.2": version: 3.3.2 resolution: "hoist-non-react-statics@npm:3.3.2" dependencies: @@ -19363,7 +19263,7 @@ __metadata: languageName: node linkType: hard -"postcss@npm:^8.2.14, postcss@npm:^8.4.33, postcss@npm:^8.4.38": +"postcss@npm:8.4.38, postcss@npm:^8.2.14, postcss@npm:^8.4.33, postcss@npm:^8.4.38": version: 8.4.38 resolution: "postcss@npm:8.4.38" dependencies: @@ -21262,7 +21162,7 @@ __metadata: languageName: node linkType: hard -"shallowequal@npm:^1.1.0": +"shallowequal@npm:1.1.0": version: 1.1.0 resolution: "shallowequal@npm:1.1.0" checksum: 10/f4c1de0837f106d2dbbfd5d0720a5d059d1c66b42b580965c8f06bb1db684be8783538b684092648c981294bf817869f743a066538771dbecb293df78f765e00 @@ -22048,25 +21948,23 @@ __metadata: languageName: node linkType: hard -"styled-components@npm:^5.3.3": - version: 5.3.11 - resolution: "styled-components@npm:5.3.11" +"styled-components@npm:^6": + version: 6.1.13 + resolution: "styled-components@npm:6.1.13" dependencies: - "@babel/helper-module-imports": "npm:^7.0.0" - "@babel/traverse": "npm:^7.4.5" - "@emotion/is-prop-valid": "npm:^1.1.0" - "@emotion/stylis": "npm:^0.8.4" - "@emotion/unitless": "npm:^0.7.4" - babel-plugin-styled-components: "npm:>= 1.12.0" - css-to-react-native: "npm:^3.0.0" - hoist-non-react-statics: "npm:^3.0.0" - shallowequal: "npm:^1.1.0" - supports-color: "npm:^5.5.0" + "@emotion/is-prop-valid": "npm:1.2.2" + "@emotion/unitless": "npm:0.8.1" + "@types/stylis": "npm:4.2.5" + css-to-react-native: "npm:3.2.0" + csstype: "npm:3.1.3" + postcss: "npm:8.4.38" + shallowequal: "npm:1.1.0" + stylis: "npm:4.3.2" + tslib: "npm:2.6.2" peerDependencies: react: ">= 16.8.0" react-dom: ">= 16.8.0" - react-is: ">= 16.8.0" - checksum: 10/7e1baee0f7b4479fe1a4064e4ae87e40f1ba583030d04827cef73fa7b36d3a91ed552dc76164d319216039f906af42a5229648c023482280fa4b5f71f00eef2d + checksum: 10/8be7bcb156945e876f560b1bef4f2e5a6a214e53fa6e7f98cd7294c83f3cfb2d712c4561d175abcd6d331a65ef5b9b2004c916aa035ddec9633f0661d9c8205c languageName: node linkType: hard @@ -22098,6 +21996,20 @@ __metadata: languageName: node linkType: hard +"stylis@npm:4.3.2": + version: 4.3.2 + resolution: "stylis@npm:4.3.2" + checksum: 10/4d3e3cb5cbfc7abdf14e424c8631a15fd15cbf0357ffc641c319587e00c2d1036b1a71cb88b42411bc3ce10d7730ad3fb9789b034d11365e8a19d23f56486c77 + languageName: node + linkType: hard + +"stylis@npm:^4": + version: 4.3.4 + resolution: "stylis@npm:4.3.4" + checksum: 10/69b902a3c9fc3329c8ddb18d422f8130068356dd4d4a20ae245953679cc88ae08d49c55e32b0b57c8fe8a76f2ed7f32697240b8db4d368a25fc2db045ebaeba8 + languageName: node + linkType: hard + "subscriptions-transport-ws@npm:^0.9.15": version: 0.9.19 resolution: "subscriptions-transport-ws@npm:0.9.19" @@ -22113,7 +22025,7 @@ __metadata: languageName: node linkType: hard -"supports-color@npm:^5.3.0, supports-color@npm:^5.5.0": +"supports-color@npm:^5.3.0": version: 5.5.0 resolution: "supports-color@npm:5.5.0" dependencies: @@ -22703,6 +22615,13 @@ __metadata: languageName: node linkType: hard +"tslib@npm:2.6.2, tslib@npm:^2.6.2, tslib@npm:~2.6.0": + version: 2.6.2 + resolution: "tslib@npm:2.6.2" + checksum: 10/bd26c22d36736513980091a1e356378e8b662ded04204453d353a7f34a4c21ed0afc59b5f90719d4ba756e581a162ecbf93118dc9c6be5acf70aa309188166ca + languageName: node + linkType: hard + "tslib@npm:^1.13.0, tslib@npm:^1.8.1": version: 1.14.1 resolution: "tslib@npm:1.14.1" @@ -22717,13 +22636,6 @@ __metadata: languageName: node linkType: hard -"tslib@npm:^2.6.2, tslib@npm:~2.6.0": - version: 2.6.2 - resolution: "tslib@npm:2.6.2" - checksum: 10/bd26c22d36736513980091a1e356378e8b662ded04204453d353a7f34a4c21ed0afc59b5f90719d4ba756e581a162ecbf93118dc9c6be5acf70aa309188166ca - languageName: node - linkType: hard - "tslib@npm:~2.4.0": version: 2.4.1 resolution: "tslib@npm:2.4.1" diff --git a/pyright/alt-1/requirements-pinned.txt b/pyright/alt-1/requirements-pinned.txt index 175aaddb0d49d..8867511a8d496 100644 --- a/pyright/alt-1/requirements-pinned.txt +++ b/pyright/alt-1/requirements-pinned.txt @@ -1,8 +1,8 @@ agate==1.9.1 aiobotocore==2.15.2 aiofile==3.9.0 -aiohappyeyeballs==2.4.3 -aiohttp==3.11.7 +aiohappyeyeballs==2.4.4 +aiohttp==3.11.9 aioitertools==0.12.0 aiosignal==1.3.1 alembic==1.14.0 @@ -16,7 +16,7 @@ arrow==1.3.0 asn1crypto==1.5.1 -e examples/assets_pandas_type_metadata astroid==3.3.5 -asttokens==2.4.1 +asttokens==3.0.0 async-lru==2.0.4 attrs==24.2.0 babel==2.16.0 @@ -25,9 +25,9 @@ backports-tarfile==1.2.0 beautifulsoup4==4.12.3 bleach==6.2.0 boto3==1.35.36 -boto3-stubs-lite==1.35.68 +boto3-stubs-lite==1.35.70 botocore==1.35.36 -botocore-stubs==1.35.68 +botocore-stubs==1.35.72 buildkite-test-collector==0.1.9 cachetools==5.5.0 caio==0.9.17 @@ -42,7 +42,7 @@ comm==0.2.2 contourpy==1.3.1 coverage==7.6.8 croniter==3.0.4 -cryptography==43.0.3 +cryptography==44.0.0 cycler==0.12.1 daff==1.3.46 -e python_modules/dagster @@ -78,7 +78,7 @@ decopatch==1.4.10 decorator==5.1.1 deepdiff==8.0.1 defusedxml==0.7.1 -deltalake==0.22.0 +deltalake==0.22.2 dill==0.3.9 distlib==0.3.9 docker==7.1.0 @@ -86,7 +86,7 @@ docstring-parser==0.16 duckdb==1.1.3 execnet==2.1.1 executing==2.1.0 -fastjsonschema==2.20.0 +fastjsonschema==2.21.1 filelock==3.16.1 flaky==3.8.1 fonttools==4.55.0 @@ -109,7 +109,7 @@ gql==3.5.0 graphene==3.4.3 graphql-core==3.2.5 graphql-relay==3.2.0 -grpcio==1.68.0 +grpcio==1.68.1 grpcio-health-checking==1.62.3 grpcio-status==1.62.3 grpcio-tools==1.62.3 @@ -117,14 +117,14 @@ h11==0.14.0 httpcore==1.0.7 httplib2==0.22.0 httptools==0.6.4 -httpx==0.27.2 +httpx==0.28.0 humanfriendly==10.0 -hypothesis==6.119.4 +hypothesis==6.122.1 idna==3.10 importlib-metadata==6.11.0 iniconfig==2.0.0 ipykernel==6.29.5 -ipython==8.29.0 +ipython==8.30.0 isodate==0.6.1 isoduration==20.11.0 isort==5.13.2 @@ -135,7 +135,7 @@ jedi==0.19.2 jinja2==3.1.4 jmespath==1.0.1 joblib==1.4.2 -json5==0.9.28 +json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 @@ -157,7 +157,7 @@ mako==1.3.6 markdown-it-py==3.0.0 markupsafe==3.0.2 mashumaro==3.15 -matplotlib==3.9.2 +matplotlib==3.9.3 matplotlib-inline==0.1.7 mccabe==0.7.0 mdurl==0.1.2 @@ -169,15 +169,15 @@ msgpack==1.1.0 multidict==6.1.0 multimethod==1.12 mypy==1.13.0 -mypy-boto3-ecs==1.35.66 +mypy-boto3-ecs==1.35.72 mypy-boto3-emr==1.35.68 mypy-boto3-emr-serverless==1.35.25 mypy-boto3-glue==1.35.65 -mypy-boto3-logs==1.35.67 -mypy-boto3-s3==1.35.67 +mypy-boto3-logs==1.35.72 +mypy-boto3-s3==1.35.72 mypy-extensions==1.0.0 mypy-protobuf==3.6.0 -nbclient==0.10.0 +nbclient==0.10.1 nbconvert==7.16.4 nbformat==5.10.4 nest-asyncio==1.6.0 @@ -193,7 +193,7 @@ orjson==3.10.12 overrides==7.7.0 packaging==24.2 pandas==2.2.3 -pandas-stubs==2.2.3.241009 +pandas-stubs==2.2.3.241126 pandera==0.21.0 pandocfilters==1.5.1 parsedatetime==2.6 @@ -204,11 +204,11 @@ pillow==11.0.0 pip==24.3.1 platformdirs==4.3.6 pluggy==1.5.0 -polars==1.14.0 +polars==1.16.0 -e examples/project_fully_featured prometheus-client==0.21.0 prompt-toolkit==3.0.48 -propcache==0.2.0 +propcache==0.2.1 proto-plus==1.25.0 protobuf==4.25.5 psutil==6.1.0 @@ -216,21 +216,21 @@ psycopg2-binary==2.9.10 ptyprocess==0.7.0 pure-eval==0.2.3 py4j==0.10.9.7 -pyarrow==18.0.0 +pyarrow==18.1.0 pyasn1==0.6.1 pyasn1-modules==0.4.1 pycparser==2.22 pydantic==2.9.2 pydantic-core==2.23.4 pygments==2.18.0 -pyjwt==2.10.0 -pylint==3.3.1 -pyopenssl==24.2.1 +pyjwt==2.10.1 +pylint==3.3.2 +pyopenssl==24.3.0 pyparsing==3.2.0 pyproject-api==1.8.0 pyright==1.1.379 pyspark==3.5.3 -pytest==8.3.3 +pytest==8.3.4 pytest-asyncio==0.24.0 pytest-cases==3.8.6 pytest-cov==5.0.0 @@ -253,7 +253,7 @@ responses==0.23.1 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rich==13.9.4 -rpds-py==0.21.0 +rpds-py==0.22.0 rsa==4.9 s3fs==2024.3.0 s3transfer==0.10.4 @@ -271,7 +271,7 @@ snowflake-sqlalchemy==1.5.1 sortedcontainers==2.4.0 soupsieve==2.6 sqlalchemy==1.4.54 -sqlglot==25.32.0 +sqlglot==25.32.1 sqlglotrs==0.3.0 sqlparse==0.5.2 stack-data==0.6.3 @@ -283,7 +283,7 @@ terminado==0.18.1 text-unidecode==1.3 threadpoolctl==3.5.0 tinycss2==1.4.0 -tomli==2.1.0 +tomli==2.2.1 tomlkit==0.13.2 toposort==1.10 tornado==6.4.2 @@ -291,8 +291,8 @@ tox==4.23.2 tqdm==4.67.1 traitlets==5.14.3 typeguard==4.4.1 -typer==0.13.1 -types-awscrt==0.23.0 +typer==0.14.0 +types-awscrt==0.23.1 types-backports==0.1.3 types-certifi==2021.10.8.3 types-cffi==1.16.0.20240331 @@ -308,7 +308,7 @@ types-pytz==2024.2.0.20241003 types-pyyaml==6.0.12.20240917 types-requests==2.32.0.20241016 types-s3transfer==0.10.4 -types-setuptools==75.5.0.20241122 +types-setuptools==75.6.0.20241126 types-simplejson==3.19.0.20240801 types-six==1.16.21.20241105 types-tabulate==0.9.0.20240106 @@ -324,7 +324,7 @@ uritemplate==4.1.1 urllib3==2.2.3 uvicorn==0.32.1 uvloop==0.21.0 -virtualenv==20.27.1 +virtualenv==20.28.0 watchdog==5.0.3 watchfiles==1.0.0 wcwidth==0.2.13 @@ -334,5 +334,5 @@ websocket-client==1.8.0 websockets==14.1 wheel==0.45.1 wrapt==1.17.0 -yarl==1.18.0 +yarl==1.18.3 zipp==3.21.0 diff --git a/pyright/master/requirements-pinned.txt b/pyright/master/requirements-pinned.txt index 1413ed42f3325..33f6886e59df3 100644 --- a/pyright/master/requirements-pinned.txt +++ b/pyright/master/requirements-pinned.txt @@ -2,7 +2,7 @@ acryl-datahub==0.14.1.12 agate==1.9.1 aiofile==3.9.0 aiofiles==24.1.0 -aiohappyeyeballs==2.4.3 +aiohappyeyeballs==2.4.4 aiohttp==3.10.11 aiohttp-retry==2.8.3 aioresponses==0.7.7 @@ -36,8 +36,7 @@ asgiref==3.8.1 asn1crypto==1.5.1 -e examples/assets_dynamic_partitions -e examples/assets_pandas_pyspark -asttokens==2.4.1 -astunparse==1.6.3 +asttokens==3.0.0 async-lru==2.0.4 attrs==24.2.0 autodocsumm==0.2.14 @@ -53,16 +52,17 @@ azure-storage-blob==12.24.0 azure-storage-file-datalake==12.18.0 babel==2.16.0 backoff==2.2.1 +backports-tarfile==1.2.0 bcrypt==4.2.1 beautifulsoup4==4.12.3 billiard==4.2.1 bleach==6.2.0 blinker==1.9.0 bokeh==3.6.1 -boto3==1.35.68 -boto3-stubs-lite==1.35.68 -botocore==1.35.68 -botocore-stubs==1.35.68 +boto3==1.35.72 +boto3-stubs-lite==1.35.70 +botocore==1.35.72 +botocore-stubs==1.35.72 buildkite-test-collector==0.1.9 cachecontrol==0.14.1 cached-property==2.0.1 @@ -74,7 +74,7 @@ cattrs==23.1.2 celery==5.4.0 certifi==2024.8.30 cffi==1.17.1 -cfn-lint==1.20.0 +cfn-lint==1.20.1 chardet==5.2.0 charset-normalizer==3.4.0 click==8.1.7 @@ -96,7 +96,7 @@ contourpy==1.3.1 coverage==7.6.8 cron-descriptor==1.4.5 croniter==3.0.4 -cryptography==43.0.3 +cryptography==44.0.0 cssutils==2.11.1 cycler==0.12.1 daff==1.3.46 @@ -112,6 +112,7 @@ daff==1.3.46 -e python_modules/libraries/dagster-celery-docker -e python_modules/libraries/dagster-celery-k8s -e python_modules/libraries/dagster-census +-e examples/experimental/dagster-components -e python_modules/libraries/dagster-dask -e python_modules/libraries/dagster-databricks -e python_modules/libraries/dagster-datadog @@ -202,7 +203,7 @@ distlib==0.3.9 distributed==2024.11.2 distro==1.9.0 -e examples/experimental/dagster-dlift/kitchen-sink -dlt==1.4.0 +dlt==1.4.1 dnspython==2.7.0 docker==7.1.0 docker-image-py==0.1.13 @@ -220,7 +221,7 @@ executing==2.1.0 expandvars==0.12.0 faiss-cpu==1.8.0 fastavro==1.9.7 -fastjsonschema==2.20.0 +fastjsonschema==2.21.1 -e examples/feature_graph_backed_assets filelock==3.16.1 flaky==3.8.1 @@ -230,7 +231,7 @@ flask-babel==2.0.0 flask-caching==2.3.0 flask-cors==5.0.0 flask-jwt-extended==4.7.1 -flask-limiter==3.8.0 +flask-limiter==3.9.2 flask-login==0.6.3 flask-session==0.5.0 flask-sqlalchemy==2.5.1 @@ -261,7 +262,7 @@ graphql-core==3.2.5 graphql-relay==3.2.0 graphviz==0.20.3 great-expectations==0.18.22 -grpcio==1.68.0 +grpcio==1.68.1 grpcio-health-checking==1.62.3 grpcio-status==1.62.3 grpcio-tools==1.62.3 @@ -272,11 +273,11 @@ html5lib==1.1 httpcore==1.0.7 httplib2==0.22.0 httptools==0.6.4 -httpx==0.27.2 +httpx==0.28.0 httpx-sse==0.4.0 humanfriendly==10.0 humanize==4.11.0 -hypothesis==6.119.4 +hypothesis==6.122.1 idna==3.10 ijson==3.3.0 imagesize==1.4.1 @@ -285,19 +286,22 @@ importlib-resources==6.4.5 inflection==0.5.1 iniconfig==2.0.0 ipykernel==6.29.5 -ipython==8.29.0 +ipython==8.30.0 ipython-genutils==0.2.0 ipywidgets==8.1.5 iso8601==2.1.0 isodate==0.6.1 isoduration==20.11.0 itsdangerous==2.2.0 +jaraco-classes==3.4.0 +jaraco-context==6.0.1 +jaraco-functools==4.1.0 jedi==0.19.2 jinja2==3.1.4 -jiter==0.7.1 +jiter==0.8.0 jmespath==1.0.1 joblib==1.4.2 -json5==0.9.28 +json5==0.10.0 jsondiff==2.2.1 jsonpatch==1.33 jsonpath-ng==1.7.0 @@ -316,6 +320,7 @@ jupyterlab==4.2.6 jupyterlab-pygments==0.3.0 jupyterlab-server==2.27.3 jupyterlab-widgets==3.0.13 +keyring==25.5.0 -e python_modules/libraries/dagster-airlift/kitchen-sink kiwisolver==1.4.7 kombu==5.4.2 @@ -327,10 +332,10 @@ langchain-community==0.3.5 langchain-core==0.3.21 langchain-openai==0.2.5 langchain-text-splitters==0.3.2 -langsmith==0.1.146 +langsmith==0.1.147 lazy-object-proxy==1.10.0 leather==0.4.0 -limits==3.13.0 +limits==3.14.1 linkify-it-py==2.0.3 lkml==1.3.6 locket==1.0.0 @@ -346,7 +351,7 @@ marshmallow==3.23.1 marshmallow-oneofschema==3.1.1 marshmallow-sqlalchemy==0.26.1 mashumaro==3.15 -matplotlib==3.9.2 +matplotlib==3.9.3 matplotlib-inline==0.1.3 mbstrdecoder==1.1.3 mdit-py-plugins==0.4.2 @@ -364,22 +369,22 @@ msal-extensions==1.2.0 msgpack==1.1.0 multidict==6.1.0 multimethod==1.12 -mypy-boto3-ecs==1.35.66 +mypy-boto3-ecs==1.35.72 mypy-boto3-emr==1.35.68 mypy-boto3-emr-serverless==1.35.25 mypy-boto3-glue==1.35.65 -mypy-boto3-logs==1.35.67 -mypy-boto3-s3==1.35.67 +mypy-boto3-logs==1.35.72 +mypy-boto3-s3==1.35.72 mypy-extensions==1.0.0 mypy-protobuf==3.6.0 mysql-connector-python==9.1.0 natsort==8.4.0 -nbclient==0.10.0 +nbclient==0.10.1 nbconvert==7.16.4 nbformat==5.10.4 nest-asyncio==1.6.0 networkx==3.4.2 -nh3==0.2.18 +nh3==0.2.19 nodeenv==1.9.1 notebook==7.2.2 notebook-shim==0.2.4 @@ -390,7 +395,7 @@ objgraph==3.6.2 onnx==1.17.0 onnxconverter-common==1.13.0 onnxruntime==1.20.1 -openai==1.55.1 +openai==1.56.0 openapi-schema-validator==0.6.2 openapi-spec-validator==0.7.1 opentelemetry-api==1.28.2 @@ -408,7 +413,7 @@ overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandas-gbq==0.24.0 -pandas-stubs==2.2.3.241009 +pandas-stubs==2.2.3.241126 pandera==0.21.0 pandocfilters==1.5.1 papermill==2.6.0 @@ -425,19 +430,19 @@ pendulum==2.1.2 pexpect==4.9.0 pillow==11.0.0 pip==24.3.1 -pkginfo==1.11.2 +pkginfo==1.12.0 platformdirs==4.3.6 plotly==5.24.1 pluggy==1.5.0 ply==3.11 -polars==1.14.0 +polars==1.16.0 portalocker==2.10.1 prison==0.2.1 progressbar2==4.5.0 prometheus-client==0.21.0 prometheus-flask-exporter==0.23.1 prompt-toolkit==3.0.48 -propcache==0.2.0 +propcache==0.2.1 proto-plus==1.25.0 protobuf==4.25.5 psutil==6.1.0 @@ -446,7 +451,7 @@ ptyprocess==0.7.0 pure-eval==0.2.3 py-partiql-parser==0.5.0 py4j==0.10.9.7 -pyarrow==18.0.0 +pyarrow==18.1.0 pyarrow-hotfix==0.6 pyasn1==0.6.1 pyasn1-modules==0.4.1 @@ -457,10 +462,10 @@ pydantic-settings==2.6.1 pydata-google-auth==1.9.0 pyflakes==3.2.0 pygments==2.18.0 -pyjwt==2.10.0 +pyjwt==2.10.1 pymdown-extensions==10.12 pynacl==1.5.0 -pyopenssl==24.2.1 +pyopenssl==24.3.0 pyparsing==3.2.0 pypd==1.1.0 pyproject-api==1.8.0 @@ -468,23 +473,23 @@ pyright==1.1.379 pysocks==1.7.1 pyspark==3.5.3 pytablereader==0.31.4 -pytest==8.3.3 +pytest==8.3.4 pytest-asyncio==0.24.0 pytest-cases==3.8.6 pytest-cov==5.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 -python-daemon==3.1.0 +python-daemon==3.1.1 python-dateutil==2.9.0.post0 python-dotenv==1.0.1 python-frontmatter==1.1.0 python-jose==3.3.0 python-json-logger==2.0.7 python-liquid==1.12.1 -python-multipart==0.0.17 +python-multipart==0.0.19 python-nvd3==0.16.0 python-slugify==8.0.4 -python-utils==3.9.0 +python-utils==3.9.1 pytimeparse==1.1.8 pytz==2024.2 pytzdata==2020.1 @@ -503,21 +508,22 @@ requests-toolbelt==1.0.0 requirements-parser==0.11.0 responses==0.23.1 rfc3339-validator==0.1.4 +rfc3986==2.0.0 rfc3986-validator==0.1.1 rich==13.9.4 rich-argparse==1.6.0 -rpds-py==0.21.0 +rpds-py==0.22.0 rsa==4.9 ruamel-yaml==0.17.40 ruamel-yaml-clib==0.2.12 -ruff==0.8.0 +ruff==0.8.1 s3transfer==0.10.4 scikit-learn==1.5.2 scipy==1.14.1 scrapbook==0.5.0 sdf-cli==0.3.23 seaborn==0.13.2 -selenium==4.27.0 +selenium==4.27.1 semver==3.0.2 send2trash==1.8.3 sentry-sdk==2.19.0 @@ -529,8 +535,8 @@ six==1.16.0 skein==0.8.2 skl2onnx==1.17.0 slack-sdk==3.33.4 -sling==1.2.23 -sling-linux-amd64==1.2.23 +sling==1.3.1 +sling-mac-arm64==1.3.1 smmap==5.0.1 sniffio==1.3.1 snowballstemmer==2.2.0 @@ -553,7 +559,7 @@ sphinxcontrib-serializinghtml==2.0.0 sqlalchemy==1.4.54 sqlalchemy-jsonfield==1.0.2 sqlalchemy-utils==0.41.2 -sqlglot==25.32.0 +sqlglot==25.32.1 sqlglotrs==0.3.0 sqlparse==0.5.2 sshpubkeys==3.3.1 @@ -561,7 +567,7 @@ sshtunnel==0.4.0 stack-data==0.6.3 starlette==0.41.3 structlog==24.4.0 -sympy==1.13.3 +sympy==1.13.1 syrupy==4.8.0 tableauserverclient==0.34 tabledata==1.3.3 @@ -575,14 +581,14 @@ threadpoolctl==3.5.0 tiktoken==0.8.0 tinycss2==1.4.0 toml==0.10.2 -tomli==2.1.0 +tomli==2.2.1 tomlkit==0.13.2 toolz==1.0.0 toposort==1.10 -torch==2.4.1 -torchvision==0.19.1 +torch==2.5.1 +torchvision==0.20.1 tornado==6.4.2 -tox==4.15.1 +tox==4.23.2 tqdm==4.67.1 traitlets==5.14.3 trio==0.27.0 @@ -590,11 +596,11 @@ trio-websocket==0.11.1 -e examples/airlift-migration-tutorial -e examples/tutorial_notebook_assets twilio==9.3.7 -twine==1.15.0 +twine==6.0.1 typeguard==4.4.1 typepy==1.3.2 -typer==0.13.1 -types-awscrt==0.23.0 +typer==0.14.0 +types-awscrt==0.23.1 types-backports==0.1.3 types-certifi==2021.10.8.3 types-cffi==1.16.0.20240331 @@ -610,7 +616,7 @@ types-pytz==2024.2.0.20241003 types-pyyaml==6.0.12.20240917 types-requests==2.32.0.20241016 types-s3transfer==0.10.4 -types-setuptools==75.5.0.20241122 +types-setuptools==75.6.0.20241126 types-simplejson==3.19.0.20240801 types-six==1.16.21.20241105 types-sqlalchemy==1.4.53.34 @@ -631,7 +637,7 @@ urllib3==2.2.3 uvicorn==0.32.1 uvloop==0.21.0 vine==5.1.0 -virtualenv==20.25.0 +virtualenv==20.28.0 wandb==0.18.7 watchdog==5.0.3 watchfiles==1.0.0 @@ -652,9 +658,9 @@ wordcloud==1.9.4 wrapt==1.17.0 wsproto==1.2.0 wtforms==3.0.1 -xgboost==2.1.2 +xgboost==2.1.3 xmltodict==0.12.0 xyzservices==2024.9.0 -yarl==1.18.0 +yarl==1.18.3 zict==3.0.0 zipp==3.21.0 diff --git a/pyright/master/requirements.txt b/pyright/master/requirements.txt index 5a83b47ab4e58..1daab4c5485d9 100644 --- a/pyright/master/requirements.txt +++ b/pyright/master/requirements.txt @@ -134,6 +134,7 @@ types-sqlalchemy==1.4.53.34 -e examples/with_wandb -e examples/experimental/dagster-blueprints -e python_modules/libraries/dagster-airlift[mwaa,dbt,test] # (includes airflow dependencies) +-e examples/experimental/dagster-components -e examples/experimental/dagster-dlift -e examples/starlift-demo -e python_modules/libraries/dagster-airlift/kitchen-sink diff --git a/python_modules/automation/setup.py b/python_modules/automation/setup.py index 4b60e78c662bc..534a0ba6ee551 100644 --- a/python_modules/automation/setup.py +++ b/python_modules/automation/setup.py @@ -22,8 +22,8 @@ "pandas", "pytablereader", "requests", - "twine==1.15.0", - "virtualenv==20.25.0", + "twine>=1.15.0", + "virtualenv>=20.27.0", "urllib3", ], extras_require={ diff --git a/python_modules/dagster-graphql/dagster_graphql/test/utils.py b/python_modules/dagster-graphql/dagster_graphql/test/utils.py index 27a051ea6de7a..cb52d1c34c646 100644 --- a/python_modules/dagster-graphql/dagster_graphql/test/utils.py +++ b/python_modules/dagster-graphql/dagster_graphql/test/utils.py @@ -165,7 +165,7 @@ def infer_repository(graphql_context: WorkspaceRequestContext) -> RemoteReposito assert len(repositories) == 1 return next(iter(repositories.values())) - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) return code_location.get_repository("test_repo") @@ -177,7 +177,7 @@ def infer_repository_selector(graphql_context: WorkspaceRequestContext) -> Selec assert len(repositories) == 1 repository = next(iter(repositories.values())) else: - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") return { diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py b/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py index 1fa645a7f2174..0eecd4e5a4bc8 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py @@ -2,6 +2,7 @@ import pytest from dagster_graphql import DagsterGraphQLClientError, ReloadRepositoryLocationStatus +from dagster_graphql.test.utils import main_repo_location_name from dagster_graphql_tests.client_tests.conftest import MockClient, python_client_test_suite from dagster_graphql_tests.graphql.graphql_context_test_suite import ( @@ -96,6 +97,6 @@ def test_failure_with_query_error(mock_client: MockClient): class TestReloadRepositoryLocationWithClient(BaseTestSuite): def test_reload_location_real(self, graphql_client): assert ( - graphql_client.reload_repository_location("test").status + graphql_client.reload_repository_location(main_repo_location_name()).status == ReloadRepositoryLocationStatus.SUCCESS ) diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_shutdown_repository_location.py b/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_shutdown_repository_location.py index aab0b1cf8f769..94caba8239772 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_shutdown_repository_location.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_shutdown_repository_location.py @@ -4,7 +4,7 @@ from dagster._core.errors import DagsterUserCodeUnreachableError from dagster_graphql import ShutdownRepositoryLocationStatus from dagster_graphql.client.client_queries import SHUTDOWN_REPOSITORY_LOCATION_MUTATION -from dagster_graphql.test.utils import execute_dagster_graphql +from dagster_graphql.test.utils import execute_dagster_graphql, main_repo_location_name from dagster_graphql_tests.graphql.graphql_context_test_suite import ( GraphQLContextVariant, @@ -22,7 +22,7 @@ def test_shutdown_repository_location_permission_failure(self, graphql_context): result = execute_dagster_graphql( graphql_context, SHUTDOWN_REPOSITORY_LOCATION_MUTATION, - {"repositoryLocationName": "test"}, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -36,7 +36,7 @@ def test_shutdown_repository_location(self, graphql_client, graphql_context): origin = next(iter(graphql_context.get_code_location_entries().values())).origin origin.create_client().heartbeat() - result = graphql_client.shutdown_repository_location("test") + result = graphql_client.shutdown_repository_location(main_repo_location_name()) assert result.status == ShutdownRepositoryLocationStatus.SUCCESS, result.message diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/__snapshots__/test_assets.ambr b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/__snapshots__/test_assets.ambr index 6e59d4895372a..e4613783e7ada 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/__snapshots__/test_assets.ambr +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/__snapshots__/test_assets.ambr @@ -14,7 +14,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_1"]', + 'id': 'test_location.test_repo.["asset_1"]', 'key': dict({ 'path': list([ 'asset_1', @@ -22,7 +22,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_2"]', + 'id': 'test_location.test_repo.["asset_2"]', 'key': dict({ 'path': list([ 'asset_2', @@ -30,7 +30,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_3"]', + 'id': 'test_location.test_repo.["asset_3"]', 'key': dict({ 'path': list([ 'asset_3', @@ -38,7 +38,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_one"]', + 'id': 'test_location.test_repo.["asset_one"]', 'key': dict({ 'path': list([ 'asset_one', @@ -46,7 +46,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_two"]', + 'id': 'test_location.test_repo.["asset_two"]', 'key': dict({ 'path': list([ 'asset_two', @@ -54,7 +54,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_with_automation_condition"]', + 'id': 'test_location.test_repo.["asset_with_automation_condition"]', 'key': dict({ 'path': list([ 'asset_with_automation_condition', @@ -62,7 +62,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_with_custom_automation_condition"]', + 'id': 'test_location.test_repo.["asset_with_custom_automation_condition"]', 'key': dict({ 'path': list([ 'asset_with_custom_automation_condition', @@ -70,7 +70,7 @@ }), }), dict({ - 'id': 'test.test_repo.["asset_yields_observation"]', + 'id': 'test_location.test_repo.["asset_yields_observation"]', 'key': dict({ 'path': list([ 'asset_yields_observation', @@ -86,7 +86,7 @@ }), }), dict({ - 'id': 'test.test_repo.["bar"]', + 'id': 'test_location.test_repo.["bar"]', 'key': dict({ 'path': list([ 'bar', @@ -94,7 +94,7 @@ }), }), dict({ - 'id': 'test.test_repo.["baz"]', + 'id': 'test_location.test_repo.["baz"]', 'key': dict({ 'path': list([ 'baz', @@ -110,7 +110,7 @@ }), }), dict({ - 'id': 'test.test_repo.["check_in_op_asset"]', + 'id': 'test_location.test_repo.["check_in_op_asset"]', 'key': dict({ 'path': list([ 'check_in_op_asset', @@ -118,7 +118,7 @@ }), }), dict({ - 'id': 'test.test_repo.["diamond_source"]', + 'id': 'test_location.test_repo.["diamond_source"]', 'key': dict({ 'path': list([ 'diamond_source', @@ -126,7 +126,7 @@ }), }), dict({ - 'id': 'test.test_repo.["downstream_asset"]', + 'id': 'test_location.test_repo.["downstream_asset"]', 'key': dict({ 'path': list([ 'downstream_asset', @@ -134,7 +134,7 @@ }), }), dict({ - 'id': 'test.test_repo.["downstream_dynamic_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_dynamic_partitioned_asset"]', 'key': dict({ 'path': list([ 'downstream_dynamic_partitioned_asset', @@ -142,7 +142,7 @@ }), }), dict({ - 'id': 'test.test_repo.["downstream_static_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_static_partitioned_asset"]', 'key': dict({ 'path': list([ 'downstream_static_partitioned_asset', @@ -150,7 +150,7 @@ }), }), dict({ - 'id': 'test.test_repo.["downstream_time_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_time_partitioned_asset"]', 'key': dict({ 'path': list([ 'downstream_time_partitioned_asset', @@ -158,7 +158,7 @@ }), }), dict({ - 'id': 'test.test_repo.["downstream_weekly_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_weekly_partitioned_asset"]', 'key': dict({ 'path': list([ 'downstream_weekly_partitioned_asset', @@ -166,7 +166,7 @@ }), }), dict({ - 'id': 'test.test_repo.["dummy_source_asset"]', + 'id': 'test_location.test_repo.["dummy_source_asset"]', 'key': dict({ 'path': list([ 'dummy_source_asset', @@ -174,7 +174,7 @@ }), }), dict({ - 'id': 'test.test_repo.["dynamic_in_multipartitions_fail"]', + 'id': 'test_location.test_repo.["dynamic_in_multipartitions_fail"]', 'key': dict({ 'path': list([ 'dynamic_in_multipartitions_fail', @@ -182,7 +182,7 @@ }), }), dict({ - 'id': 'test.test_repo.["dynamic_in_multipartitions_success"]', + 'id': 'test_location.test_repo.["dynamic_in_multipartitions_success"]', 'key': dict({ 'path': list([ 'dynamic_in_multipartitions_success', @@ -190,7 +190,7 @@ }), }), dict({ - 'id': 'test.test_repo.["executable_asset"]', + 'id': 'test_location.test_repo.["executable_asset"]', 'key': dict({ 'path': list([ 'executable_asset', @@ -198,7 +198,7 @@ }), }), dict({ - 'id': 'test.test_repo.["fail_partition_materialization"]', + 'id': 'test_location.test_repo.["fail_partition_materialization"]', 'key': dict({ 'path': list([ 'fail_partition_materialization', @@ -206,7 +206,7 @@ }), }), dict({ - 'id': 'test.test_repo.["first_asset"]', + 'id': 'test_location.test_repo.["first_asset"]', 'key': dict({ 'path': list([ 'first_asset', @@ -214,7 +214,7 @@ }), }), dict({ - 'id': 'test.test_repo.["first_kinds_key"]', + 'id': 'test_location.test_repo.["first_kinds_key"]', 'key': dict({ 'path': list([ 'first_kinds_key', @@ -222,7 +222,7 @@ }), }), dict({ - 'id': 'test.test_repo.["foo"]', + 'id': 'test_location.test_repo.["foo"]', 'key': dict({ 'path': list([ 'foo', @@ -230,7 +230,7 @@ }), }), dict({ - 'id': 'test.test_repo.["foo_bar"]', + 'id': 'test_location.test_repo.["foo_bar"]', 'key': dict({ 'path': list([ 'foo_bar', @@ -238,7 +238,7 @@ }), }), dict({ - 'id': 'test.test_repo.["fourth_kinds_key"]', + 'id': 'test_location.test_repo.["fourth_kinds_key"]', 'key': dict({ 'path': list([ 'fourth_kinds_key', @@ -246,7 +246,7 @@ }), }), dict({ - 'id': 'test.test_repo.["fresh_diamond_bottom"]', + 'id': 'test_location.test_repo.["fresh_diamond_bottom"]', 'key': dict({ 'path': list([ 'fresh_diamond_bottom', @@ -254,7 +254,7 @@ }), }), dict({ - 'id': 'test.test_repo.["fresh_diamond_left"]', + 'id': 'test_location.test_repo.["fresh_diamond_left"]', 'key': dict({ 'path': list([ 'fresh_diamond_left', @@ -262,7 +262,7 @@ }), }), dict({ - 'id': 'test.test_repo.["fresh_diamond_right"]', + 'id': 'test_location.test_repo.["fresh_diamond_right"]', 'key': dict({ 'path': list([ 'fresh_diamond_right', @@ -270,7 +270,7 @@ }), }), dict({ - 'id': 'test.test_repo.["fresh_diamond_top"]', + 'id': 'test_location.test_repo.["fresh_diamond_top"]', 'key': dict({ 'path': list([ 'fresh_diamond_top', @@ -278,7 +278,7 @@ }), }), dict({ - 'id': 'test.test_repo.["grouped_asset_1"]', + 'id': 'test_location.test_repo.["grouped_asset_1"]', 'key': dict({ 'path': list([ 'grouped_asset_1', @@ -286,7 +286,7 @@ }), }), dict({ - 'id': 'test.test_repo.["grouped_asset_2"]', + 'id': 'test_location.test_repo.["grouped_asset_2"]', 'key': dict({ 'path': list([ 'grouped_asset_2', @@ -294,7 +294,7 @@ }), }), dict({ - 'id': 'test.test_repo.["grouped_asset_4"]', + 'id': 'test_location.test_repo.["grouped_asset_4"]', 'key': dict({ 'path': list([ 'grouped_asset_4', @@ -302,7 +302,7 @@ }), }), dict({ - 'id': 'test.test_repo.["hanging_asset"]', + 'id': 'test_location.test_repo.["hanging_asset"]', 'key': dict({ 'path': list([ 'hanging_asset', @@ -310,7 +310,7 @@ }), }), dict({ - 'id': 'test.test_repo.["hanging_graph"]', + 'id': 'test_location.test_repo.["hanging_graph"]', 'key': dict({ 'path': list([ 'hanging_graph', @@ -318,7 +318,7 @@ }), }), dict({ - 'id': 'test.test_repo.["hanging_partition_asset"]', + 'id': 'test_location.test_repo.["hanging_partition_asset"]', 'key': dict({ 'path': list([ 'hanging_partition_asset', @@ -326,7 +326,7 @@ }), }), dict({ - 'id': 'test.test_repo.["int_asset"]', + 'id': 'test_location.test_repo.["int_asset"]', 'key': dict({ 'path': list([ 'int_asset', @@ -334,7 +334,7 @@ }), }), dict({ - 'id': 'test.test_repo.["integers_asset"]', + 'id': 'test_location.test_repo.["integers_asset"]', 'key': dict({ 'path': list([ 'integers_asset', @@ -342,7 +342,7 @@ }), }), dict({ - 'id': 'test.test_repo.["middle_static_partitioned_asset_1"]', + 'id': 'test_location.test_repo.["middle_static_partitioned_asset_1"]', 'key': dict({ 'path': list([ 'middle_static_partitioned_asset_1', @@ -350,7 +350,7 @@ }), }), dict({ - 'id': 'test.test_repo.["middle_static_partitioned_asset_2"]', + 'id': 'test_location.test_repo.["middle_static_partitioned_asset_2"]', 'key': dict({ 'path': list([ 'middle_static_partitioned_asset_2', @@ -358,7 +358,7 @@ }), }), dict({ - 'id': 'test.test_repo.["multi_run_backfill_policy_asset"]', + 'id': 'test_location.test_repo.["multi_run_backfill_policy_asset"]', 'key': dict({ 'path': list([ 'multi_run_backfill_policy_asset', @@ -366,7 +366,7 @@ }), }), dict({ - 'id': 'test.test_repo.["multipartitions_1"]', + 'id': 'test_location.test_repo.["multipartitions_1"]', 'key': dict({ 'path': list([ 'multipartitions_1', @@ -374,7 +374,7 @@ }), }), dict({ - 'id': 'test.test_repo.["multipartitions_2"]', + 'id': 'test_location.test_repo.["multipartitions_2"]', 'key': dict({ 'path': list([ 'multipartitions_2', @@ -382,7 +382,7 @@ }), }), dict({ - 'id': 'test.test_repo.["multipartitions_fail"]', + 'id': 'test_location.test_repo.["multipartitions_fail"]', 'key': dict({ 'path': list([ 'multipartitions_fail', @@ -390,7 +390,7 @@ }), }), dict({ - 'id': 'test.test_repo.["never_runs_asset"]', + 'id': 'test_location.test_repo.["never_runs_asset"]', 'key': dict({ 'path': list([ 'never_runs_asset', @@ -398,7 +398,7 @@ }), }), dict({ - 'id': 'test.test_repo.["no_multipartitions_1"]', + 'id': 'test_location.test_repo.["no_multipartitions_1"]', 'key': dict({ 'path': list([ 'no_multipartitions_1', @@ -406,7 +406,7 @@ }), }), dict({ - 'id': 'test.test_repo.["not_included_asset"]', + 'id': 'test_location.test_repo.["not_included_asset"]', 'key': dict({ 'path': list([ 'not_included_asset', @@ -414,7 +414,7 @@ }), }), dict({ - 'id': 'test.test_repo.["one"]', + 'id': 'test_location.test_repo.["one"]', 'key': dict({ 'path': list([ 'one', @@ -422,7 +422,7 @@ }), }), dict({ - 'id': 'test.test_repo.["output_then_hang_asset"]', + 'id': 'test_location.test_repo.["output_then_hang_asset"]', 'key': dict({ 'path': list([ 'output_then_hang_asset', @@ -430,7 +430,7 @@ }), }), dict({ - 'id': 'test.test_repo.["second_kinds_key"]', + 'id': 'test_location.test_repo.["second_kinds_key"]', 'key': dict({ 'path': list([ 'second_kinds_key', @@ -438,7 +438,7 @@ }), }), dict({ - 'id': 'test.test_repo.["single_run_backfill_policy_asset"]', + 'id': 'test_location.test_repo.["single_run_backfill_policy_asset"]', 'key': dict({ 'path': list([ 'single_run_backfill_policy_asset', @@ -446,7 +446,7 @@ }), }), dict({ - 'id': 'test.test_repo.["str_asset"]', + 'id': 'test_location.test_repo.["str_asset"]', 'key': dict({ 'path': list([ 'str_asset', @@ -454,7 +454,7 @@ }), }), dict({ - 'id': 'test.test_repo.["third_kinds_key"]', + 'id': 'test_location.test_repo.["third_kinds_key"]', 'key': dict({ 'path': list([ 'third_kinds_key', @@ -462,7 +462,7 @@ }), }), dict({ - 'id': 'test.test_repo.["two"]', + 'id': 'test_location.test_repo.["two"]', 'key': dict({ 'path': list([ 'two', @@ -470,7 +470,7 @@ }), }), dict({ - 'id': 'test.test_repo.["typed_asset"]', + 'id': 'test_location.test_repo.["typed_asset"]', 'key': dict({ 'path': list([ 'typed_asset', @@ -478,7 +478,7 @@ }), }), dict({ - 'id': 'test.test_repo.["unconnected"]', + 'id': 'test_location.test_repo.["unconnected"]', 'key': dict({ 'path': list([ 'unconnected', @@ -486,7 +486,7 @@ }), }), dict({ - 'id': 'test.test_repo.["unexecutable_asset"]', + 'id': 'test_location.test_repo.["unexecutable_asset"]', 'key': dict({ 'path': list([ 'unexecutable_asset', @@ -494,7 +494,7 @@ }), }), dict({ - 'id': 'test.test_repo.["ungrouped_asset_3"]', + 'id': 'test_location.test_repo.["ungrouped_asset_3"]', 'key': dict({ 'path': list([ 'ungrouped_asset_3', @@ -502,7 +502,7 @@ }), }), dict({ - 'id': 'test.test_repo.["ungrouped_asset_5"]', + 'id': 'test_location.test_repo.["ungrouped_asset_5"]', 'key': dict({ 'path': list([ 'ungrouped_asset_5', @@ -510,7 +510,7 @@ }), }), dict({ - 'id': 'test.test_repo.["unpartitioned_upstream_of_partitioned"]', + 'id': 'test_location.test_repo.["unpartitioned_upstream_of_partitioned"]', 'key': dict({ 'path': list([ 'unpartitioned_upstream_of_partitioned', @@ -518,7 +518,7 @@ }), }), dict({ - 'id': 'test.test_repo.["untyped_asset"]', + 'id': 'test_location.test_repo.["untyped_asset"]', 'key': dict({ 'path': list([ 'untyped_asset', @@ -526,7 +526,7 @@ }), }), dict({ - 'id': 'test.test_repo.["upstream_daily_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_daily_partitioned_asset"]', 'key': dict({ 'path': list([ 'upstream_daily_partitioned_asset', @@ -534,7 +534,7 @@ }), }), dict({ - 'id': 'test.test_repo.["upstream_dynamic_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_dynamic_partitioned_asset"]', 'key': dict({ 'path': list([ 'upstream_dynamic_partitioned_asset', @@ -542,7 +542,7 @@ }), }), dict({ - 'id': 'test.test_repo.["upstream_static_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_static_partitioned_asset"]', 'key': dict({ 'path': list([ 'upstream_static_partitioned_asset', @@ -550,7 +550,7 @@ }), }), dict({ - 'id': 'test.test_repo.["upstream_time_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_time_partitioned_asset"]', 'key': dict({ 'path': list([ 'upstream_time_partitioned_asset', @@ -558,7 +558,7 @@ }), }), dict({ - 'id': 'test.test_repo.["yield_partition_materialization"]', + 'id': 'test_location.test_repo.["yield_partition_materialization"]', 'key': dict({ 'path': list([ 'yield_partition_materialization', @@ -597,137 +597,137 @@ dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_1"]', + 'id': 'test_location.test_repo.["asset_1"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_2"]', + 'id': 'test_location.test_repo.["asset_2"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_3"]', + 'id': 'test_location.test_repo.["asset_3"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_one"]', + 'id': 'test_location.test_repo.["asset_one"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_two"]', + 'id': 'test_location.test_repo.["asset_two"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_with_automation_condition"]', + 'id': 'test_location.test_repo.["asset_with_automation_condition"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_with_custom_automation_condition"]', + 'id': 'test_location.test_repo.["asset_with_custom_automation_condition"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["asset_yields_observation"]', + 'id': 'test_location.test_repo.["asset_yields_observation"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["bar"]', + 'id': 'test_location.test_repo.["bar"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["baz"]', + 'id': 'test_location.test_repo.["baz"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["check_in_op_asset"]', + 'id': 'test_location.test_repo.["check_in_op_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["diamond_source"]', + 'id': 'test_location.test_repo.["diamond_source"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["downstream_asset"]', + 'id': 'test_location.test_repo.["downstream_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["downstream_dynamic_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_dynamic_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["downstream_static_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_static_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["downstream_time_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_time_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["downstream_weekly_partitioned_asset"]', + 'id': 'test_location.test_repo.["downstream_weekly_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["dummy_source_asset"]', + 'id': 'test_location.test_repo.["dummy_source_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["dynamic_in_multipartitions_fail"]', + 'id': 'test_location.test_repo.["dynamic_in_multipartitions_fail"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["dynamic_in_multipartitions_success"]', + 'id': 'test_location.test_repo.["dynamic_in_multipartitions_success"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["executable_asset"]', + 'id': 'test_location.test_repo.["executable_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["fail_partition_materialization"]', + 'id': 'test_location.test_repo.["fail_partition_materialization"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["first_asset"]', + 'id': 'test_location.test_repo.["first_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["first_kinds_key"]', + 'id': 'test_location.test_repo.["first_kinds_key"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["foo"]', + 'id': 'test_location.test_repo.["foo"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["foo_bar"]', + 'id': 'test_location.test_repo.["foo_bar"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["fourth_kinds_key"]', + 'id': 'test_location.test_repo.["fourth_kinds_key"]', }), dict({ 'freshnessInfo': dict({ @@ -738,202 +738,202 @@ 'cronSchedule': None, 'maximumLagMinutes': 30.0, }), - 'id': 'test.test_repo.["fresh_diamond_bottom"]', + 'id': 'test_location.test_repo.["fresh_diamond_bottom"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["fresh_diamond_left"]', + 'id': 'test_location.test_repo.["fresh_diamond_left"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["fresh_diamond_right"]', + 'id': 'test_location.test_repo.["fresh_diamond_right"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["fresh_diamond_top"]', + 'id': 'test_location.test_repo.["fresh_diamond_top"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["grouped_asset_1"]', + 'id': 'test_location.test_repo.["grouped_asset_1"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["grouped_asset_2"]', + 'id': 'test_location.test_repo.["grouped_asset_2"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["grouped_asset_4"]', + 'id': 'test_location.test_repo.["grouped_asset_4"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["hanging_asset"]', + 'id': 'test_location.test_repo.["hanging_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["hanging_graph"]', + 'id': 'test_location.test_repo.["hanging_graph"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["hanging_partition_asset"]', + 'id': 'test_location.test_repo.["hanging_partition_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["int_asset"]', + 'id': 'test_location.test_repo.["int_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["integers_asset"]', + 'id': 'test_location.test_repo.["integers_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["middle_static_partitioned_asset_1"]', + 'id': 'test_location.test_repo.["middle_static_partitioned_asset_1"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["middle_static_partitioned_asset_2"]', + 'id': 'test_location.test_repo.["middle_static_partitioned_asset_2"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["multi_run_backfill_policy_asset"]', + 'id': 'test_location.test_repo.["multi_run_backfill_policy_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["multipartitions_1"]', + 'id': 'test_location.test_repo.["multipartitions_1"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["multipartitions_2"]', + 'id': 'test_location.test_repo.["multipartitions_2"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["multipartitions_fail"]', + 'id': 'test_location.test_repo.["multipartitions_fail"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["never_runs_asset"]', + 'id': 'test_location.test_repo.["never_runs_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["no_multipartitions_1"]', + 'id': 'test_location.test_repo.["no_multipartitions_1"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["not_included_asset"]', + 'id': 'test_location.test_repo.["not_included_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["one"]', + 'id': 'test_location.test_repo.["one"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["output_then_hang_asset"]', + 'id': 'test_location.test_repo.["output_then_hang_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["second_kinds_key"]', + 'id': 'test_location.test_repo.["second_kinds_key"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["single_run_backfill_policy_asset"]', + 'id': 'test_location.test_repo.["single_run_backfill_policy_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["str_asset"]', + 'id': 'test_location.test_repo.["str_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["third_kinds_key"]', + 'id': 'test_location.test_repo.["third_kinds_key"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["two"]', + 'id': 'test_location.test_repo.["two"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["typed_asset"]', + 'id': 'test_location.test_repo.["typed_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["unconnected"]', + 'id': 'test_location.test_repo.["unconnected"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["unexecutable_asset"]', + 'id': 'test_location.test_repo.["unexecutable_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["ungrouped_asset_3"]', + 'id': 'test_location.test_repo.["ungrouped_asset_3"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["ungrouped_asset_5"]', + 'id': 'test_location.test_repo.["ungrouped_asset_5"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["unpartitioned_upstream_of_partitioned"]', + 'id': 'test_location.test_repo.["unpartitioned_upstream_of_partitioned"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["untyped_asset"]', + 'id': 'test_location.test_repo.["untyped_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["upstream_daily_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_daily_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["upstream_dynamic_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_dynamic_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["upstream_static_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_static_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["upstream_time_partitioned_asset"]', + 'id': 'test_location.test_repo.["upstream_time_partitioned_asset"]', }), dict({ 'freshnessInfo': None, 'freshnessPolicy': None, - 'id': 'test.test_repo.["yield_partition_materialization"]', + 'id': 'test_location.test_repo.["yield_partition_materialization"]', }), ]), }) diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py index 5fc86d5f0822a..9f9df41a02b64 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py @@ -270,7 +270,7 @@ def _sqlite_asset_instance(): class EnvironmentManagers: @staticmethod - def managed_grpc(target=None, location_name="test"): + def managed_grpc(target=None, location_name="test_location"): @contextmanager def _mgr_fn(instance, read_only): """Relies on webserver to load the code location in a subprocess and manage its lifecyle.""" @@ -302,7 +302,7 @@ def _mgr_fn(instance, read_only): return MarkedManager(_mgr_fn, [Marks.managed_grpc_env]) @staticmethod - def deployed_grpc(target=None, location_name="test"): + def deployed_grpc(target=None, location_name="test_location"): """Launches a code server in a "dagster api grpc" subprocess.""" @contextmanager @@ -332,7 +332,7 @@ def _mgr_fn(instance, read_only): return MarkedManager(_mgr_fn, [Marks.deployed_grpc_env]) @staticmethod - def code_server_cli_grpc(target=None, location_name="test"): + def code_server_cli_grpc(target=None, location_name="test_location"): """Launches a code server in a "dagster code-server start" subprocess (which will in turn open up a `dagster api grpc` subprocess that actually loads the code location). """ @@ -399,7 +399,7 @@ def _mgr_fn(instance, read_only): python_file=file_relative_path(__file__, "repo.py"), attribute="test_dict_repo", working_directory=None, - location_name="test", + location_name="test_location", ), version="", read_only=read_only, @@ -518,7 +518,9 @@ def sqlite_with_queued_run_coordinator_managed_grpc_env(): ) @staticmethod - def sqlite_with_default_run_launcher_managed_grpc_env(target=None, location_name="test"): + def sqlite_with_default_run_launcher_managed_grpc_env( + target=None, location_name="test_location" + ): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.managed_grpc(target, location_name), @@ -535,7 +537,9 @@ def sqlite_read_only_with_default_run_launcher_managed_grpc_env(): ) @staticmethod - def sqlite_with_default_run_launcher_deployed_grpc_env(target=None, location_name="test"): + def sqlite_with_default_run_launcher_deployed_grpc_env( + target=None, location_name="test_location" + ): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.deployed_grpc(target, location_name), @@ -543,7 +547,9 @@ def sqlite_with_default_run_launcher_deployed_grpc_env(target=None, location_nam ) @staticmethod - def sqlite_with_default_run_launcher_code_server_cli_env(target=None, location_name="test"): + def sqlite_with_default_run_launcher_code_server_cli_env( + target=None, location_name="test_location" + ): return GraphQLContextVariant( InstanceManagers.sqlite_instance_with_default_run_launcher(), EnvironmentManagers.code_server_cli_grpc(target, location_name), @@ -551,7 +557,9 @@ def sqlite_with_default_run_launcher_code_server_cli_env(target=None, location_n ) @staticmethod - def postgres_with_default_run_launcher_managed_grpc_env(target=None, location_name="test"): + def postgres_with_default_run_launcher_managed_grpc_env( + target=None, location_name="test_location" + ): return GraphQLContextVariant( InstanceManagers.postgres_instance_with_default_run_launcher(), EnvironmentManagers.managed_grpc(target, location_name), @@ -559,7 +567,9 @@ def postgres_with_default_run_launcher_managed_grpc_env(target=None, location_na ) @staticmethod - def postgres_with_default_run_launcher_deployed_grpc_env(target=None, location_name="test"): + def postgres_with_default_run_launcher_deployed_grpc_env( + target=None, location_name="test_location" + ): return GraphQLContextVariant( InstanceManagers.postgres_instance_with_default_run_launcher(), EnvironmentManagers.deployed_grpc(target, location_name), @@ -655,7 +665,7 @@ def all_variants(): ] @staticmethod - def all_executing_variants(target=None, location_name="test"): + def all_executing_variants(target=None, location_name="test_location"): return [ GraphQLContextVariant.sqlite_with_default_run_launcher_managed_grpc_env( target, location_name diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/multi_location.yaml b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/multi_location.yaml index c1561f56259ac..59f462386aa75 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/multi_location.yaml +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/multi_location.yaml @@ -6,4 +6,4 @@ load_from: - python_file: relative_path: repo.py attribute: test_repo - location_name: test + location_name: test_location diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_assets.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_assets.py index f6e18b05942c0..0901f0b9af9da 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_assets.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_assets.py @@ -38,6 +38,7 @@ execute_dagster_graphql, infer_job_selector, infer_repository_selector, + main_repo_location_name, ) from dagster_graphql_tests.graphql.graphql_context_test_suite import ( @@ -1241,7 +1242,7 @@ def test_asset_node_in_pipeline(self, graphql_context: WorkspaceRequestContext): assert len(result.data["assetNodes"]) == 1 asset_node = result.data["assetNodes"][0] - assert asset_node["id"] == 'test.test_repo.["asset_one"]' + assert asset_node["id"] == f'{main_repo_location_name()}.test_repo.["asset_one"]' assert asset_node["hasMaterializePermission"] assert asset_node["hasReportRunlessAssetEventPermission"] @@ -1256,7 +1257,7 @@ def test_asset_node_in_pipeline(self, graphql_context: WorkspaceRequestContext): assert len(result.data["assetNodes"]) == 2 asset_node = result.data["assetNodes"][0] - assert asset_node["id"] == 'test.test_repo.["asset_one"]' + assert asset_node["id"] == f'{main_repo_location_name()}.test_repo.["asset_one"]' def test_asset_node_is_executable(self, graphql_context: WorkspaceRequestContext): result = execute_dagster_graphql( @@ -2126,7 +2127,7 @@ def test_reexecute_subset(self, graphql_context: WorkspaceRequestContext): def test_named_groups(self, graphql_context: WorkspaceRequestContext): _create_run(graphql_context, "named_groups_job") selector = { - "repositoryLocationName": "test", + "repositoryLocationName": main_repo_location_name(), "repositoryName": "test_repo", } @@ -2640,7 +2641,7 @@ def test_auto_materialize_policy(self, graphql_context: WorkspaceRequestContext) fresh_diamond_bottom = [ a for a in result.data["assetNodes"] - if a["id"] == 'test.test_repo.["fresh_diamond_bottom"]' + if a["id"] == f'{main_repo_location_name()}.test_repo.["fresh_diamond_bottom"]' ] assert len(fresh_diamond_bottom) == 1 assert fresh_diamond_bottom[0]["autoMaterializePolicy"]["policyType"] == "LAZY" @@ -2654,7 +2655,8 @@ def test_automation_condition(self, graphql_context: WorkspaceRequestContext): automation_condition_asset = [ a for a in result.data["assetNodes"] - if a["id"] == 'test.test_repo.["asset_with_automation_condition"]' + if a["id"] + == f'{main_repo_location_name()}.test_repo.["asset_with_automation_condition"]' ] assert len(automation_condition_asset) == 1 condition = automation_condition_asset[0]["automationCondition"] @@ -2664,7 +2666,8 @@ def test_automation_condition(self, graphql_context: WorkspaceRequestContext): custom_automation_condition_asset = [ a for a in result.data["assetNodes"] - if a["id"] == 'test.test_repo.["asset_with_custom_automation_condition"]' + if a["id"] + == f'{main_repo_location_name()}.test_repo.["asset_with_custom_automation_condition"]' ] assert len(custom_automation_condition_asset) == 1 condition = custom_automation_condition_asset[0]["automationCondition"] @@ -3084,7 +3087,7 @@ def test_asset_unstarted_after_materialization(self, graphql_context: WorkspaceR ) # Create two enqueued runs - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") job = repository.get_full_job("hanging_job") diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_graph.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_graph.py index 904c4bd608328..f21deae63d660 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_graph.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_graph.py @@ -1,5 +1,9 @@ from dagster._core.workspace.context import WorkspaceRequestContext -from dagster_graphql.test.utils import execute_dagster_graphql, infer_repository_selector +from dagster_graphql.test.utils import ( + execute_dagster_graphql, + infer_repository_selector, + main_repo_location_name, +) from dagster_graphql_tests.graphql.graphql_context_test_suite import ( NonLaunchableGraphQLContextTestMatrix, @@ -74,12 +78,17 @@ def test_basic_jobs(self, graphql_context: WorkspaceRequestContext): repo_locations = { blob["name"]: blob for blob in result.data["workspaceOrError"]["locationEntries"] } - assert "test" in repo_locations - assert repo_locations["test"]["locationOrLoadError"]["__typename"] == "RepositoryLocation" + assert main_repo_location_name() in repo_locations + assert ( + repo_locations[main_repo_location_name()]["locationOrLoadError"]["__typename"] + == "RepositoryLocation" + ) jobs = { blob["name"]: blob - for blob in repo_locations["test"]["locationOrLoadError"]["repositories"][0]["jobs"] + for blob in repo_locations[main_repo_location_name()]["locationOrLoadError"][ + "repositories" + ][0]["jobs"] } assert "simple_job_a" in jobs diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py index f645ec05d7c71..8d12e2e0c9f5f 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py @@ -43,6 +43,7 @@ execute_dagster_graphql_and_finish_runs, infer_job_selector, infer_repository_selector, + main_repo_location_name, ) from dagster_graphql_tests.graphql.graphql_context_test_suite import ( @@ -324,7 +325,7 @@ def dummy_asset(): class TestPartitionBackillReadonlyFailure(ReadonlyGraphQLContextTestMatrix): def _create_backfill(self, graphql_context): - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") backfill = PartitionBackfill( @@ -656,7 +657,7 @@ def test_cancel_asset_backfill(self, graphql_context): # Update asset backfill data to contain requested partition, but does not execute side effects, # since launching the run will cause test process will hang forever. - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph _execute_asset_backfill_iteration_no_side_effects(graphql_context, backfill_id, asset_graph) @@ -686,10 +687,13 @@ def test_cancel_asset_backfill(self, graphql_context): assert not result.errors assert result.data + assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" # ensure the execution has happened + start = time.time() while not os.path.exists(path): time.sleep(0.1) + assert time.time() - start < 60, "timed out waiting for file" result = execute_dagster_graphql( graphql_context, @@ -732,7 +736,7 @@ def test_cancel_then_retry_asset_backfill(self, graphql_context): # Update asset backfill data to contain requested partition, but does not execute side effects, # since launching the run will cause test process will hang forever. - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph _execute_asset_backfill_iteration_no_side_effects(graphql_context, backfill_id, asset_graph) @@ -762,10 +766,13 @@ def test_cancel_then_retry_asset_backfill(self, graphql_context): assert not result.errors assert result.data + assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" # ensure the execution has happened + start = time.time() while not os.path.exists(path): time.sleep(0.1) + assert time.time() - start < 60, "timed out waiting for file" result = execute_dagster_graphql( graphql_context, @@ -1043,7 +1050,7 @@ def test_asset_backfill_partition_stats(self, graphql_context): assert result.data["launchPartitionBackfill"]["__typename"] == "LaunchBackfillSuccess" backfill_id = result.data["launchPartitionBackfill"]["backfillId"] - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph @@ -1086,7 +1093,7 @@ def test_asset_backfill_partition_stats(self, graphql_context): assert asset_partition_status_counts[0]["numPartitionsFailed"] == 2 def test_asset_backfill_status_with_upstream_failure(self, graphql_context): - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph @@ -1557,7 +1564,7 @@ def test_launch_backfill_with_all_partitions_flag(self, graphql_context): assert len(result.data["partitionBackfillOrError"]["partitionNames"]) == 10 def test_reexecute_asset_backfill_from_failure(self, graphql_context): - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph @@ -1654,7 +1661,7 @@ def test_reexecute_asset_backfill_from_failure(self, graphql_context): assert retried_backfill.tags.get(ROOT_BACKFILL_ID_TAG) == backfill_id def test_reexecute_successful_asset_backfill(self, graphql_context): - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph @@ -1741,7 +1748,7 @@ def test_reexecute_successful_asset_backfill(self, graphql_context): assert retried_backfill.tags.get(ROOT_BACKFILL_ID_TAG) == backfill_id def test_reexecute_asset_backfill_still_in_progress(self, graphql_context): - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph @@ -1865,7 +1872,7 @@ def test_reexecute_asset_backfill_still_in_progress(self, graphql_context): assert retried_backfill.tags.get(ROOT_BACKFILL_ID_TAG) == backfill_id def test_reexecute_asset_backfill_twice(self, graphql_context): - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") asset_graph = repository.asset_graph diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py index cd7928bd61058..801c23152d52a 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py @@ -9,7 +9,7 @@ from dagster._core.types.loadable_target_origin import LoadableTargetOrigin from dagster._core.workspace.load import location_origins_from_yaml_paths from dagster._grpc.types import ListRepositoriesResponse -from dagster_graphql.test.utils import execute_dagster_graphql +from dagster_graphql.test.utils import execute_dagster_graphql, main_repo_location_name from dagster_graphql_tests.graphql.graphql_context_test_suite import ( GraphQLContextVariant, @@ -252,7 +252,9 @@ def test_reload_workspace(self, graphql_context): class TestReloadRepositoriesReadOnly(ReadonlyGraphQLContextTestMatrix): def test_reload_repository_permission_failure(self, graphql_context): result = execute_dagster_graphql( - graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, {"repositoryLocationName": "test"} + graphql_context, + RELOAD_REPOSITORY_LOCATION_QUERY, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -264,14 +266,16 @@ def test_reload_repository_permission_failure(self, graphql_context): class TestReloadRepositoriesOutOfProcess(OutOfProcessTestSuite): def test_out_of_process_reload_location(self, graphql_context): result = execute_dagster_graphql( - graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, {"repositoryLocationName": "test"} + graphql_context, + RELOAD_REPOSITORY_LOCATION_QUERY, + {"repositoryLocationName": main_repo_location_name()}, ) assert result assert result.data assert result.data["reloadRepositoryLocation"] assert result.data["reloadRepositoryLocation"]["__typename"] == "WorkspaceLocationEntry" - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() repositories = result.data["reloadRepositoryLocation"]["locationOrLoadError"][ "repositories" ] @@ -315,7 +319,7 @@ def new_repo(): result = execute_dagster_graphql( graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, - {"repositoryLocationName": "test"}, + {"repositoryLocationName": main_repo_location_name()}, ) assert cli_command_mock.call_count == 1 @@ -329,7 +333,9 @@ def new_repo(): def test_reload_failure(self, graphql_context): result = execute_dagster_graphql( - graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, {"repositoryLocationName": "test"} + graphql_context, + RELOAD_REPOSITORY_LOCATION_QUERY, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -339,7 +345,7 @@ def test_reload_failure(self, graphql_context): result.data["reloadRepositoryLocation"]["locationOrLoadError"]["__typename"] == "RepositoryLocation" ) - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() repositories = result.data["reloadRepositoryLocation"]["locationOrLoadError"][ "repositories" ] @@ -361,7 +367,7 @@ def test_reload_failure(self, graphql_context): result = execute_dagster_graphql( graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, - {"repositoryLocationName": "test"}, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -371,7 +377,7 @@ def test_reload_failure(self, graphql_context): result.data["reloadRepositoryLocation"]["locationOrLoadError"]["__typename"] == "PythonError" ) - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() assert ( "Mocked repository load failure" in result.data["reloadRepositoryLocation"]["locationOrLoadError"]["message"] @@ -381,7 +387,7 @@ def test_reload_failure(self, graphql_context): result = execute_dagster_graphql( graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, - {"repositoryLocationName": "test"}, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -391,7 +397,7 @@ def test_reload_failure(self, graphql_context): result.data["reloadRepositoryLocation"]["locationOrLoadError"]["__typename"] == "PythonError" ) - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() assert ( "Mocked repository load failure" in result.data["reloadRepositoryLocation"]["locationOrLoadError"]["message"] @@ -401,7 +407,7 @@ def test_reload_failure(self, graphql_context): result = execute_dagster_graphql( graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, - {"repositoryLocationName": "test"}, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -411,7 +417,7 @@ def test_reload_failure(self, graphql_context): result.data["reloadRepositoryLocation"]["locationOrLoadError"]["__typename"] == "RepositoryLocation" ) - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() assert result.data["reloadRepositoryLocation"]["loadStatus"] == "LOADED" repositories = result.data["reloadRepositoryLocation"]["locationOrLoadError"][ "repositories" @@ -427,7 +433,9 @@ def test_reload_failure(self, graphql_context): class TestReloadRepositoriesManagedGrpc(ManagedTestSuite): def test_managed_grpc_reload_location(self, graphql_context): result = execute_dagster_graphql( - graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, {"repositoryLocationName": "test"} + graphql_context, + RELOAD_REPOSITORY_LOCATION_QUERY, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -437,7 +445,7 @@ def test_managed_grpc_reload_location(self, graphql_context): result.data["reloadRepositoryLocation"]["locationOrLoadError"]["__typename"] == "RepositoryLocation" ) - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() assert result.data["reloadRepositoryLocation"]["loadStatus"] == "LOADED" repositories = result.data["reloadRepositoryLocation"]["locationOrLoadError"][ @@ -465,12 +473,12 @@ class TestReloadLocationCodeServerCliGrpc(CodeServerCliTestSuite): def test_code_server_cli_reload_location(self, graphql_context): # server_id before - old_server_id = graphql_context.get_code_location("test").server_id + old_server_id = graphql_context.get_code_location(main_repo_location_name()).server_id result = execute_dagster_graphql( graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, - {"repositoryLocationName": "test"}, + {"repositoryLocationName": main_repo_location_name()}, ) assert result @@ -480,12 +488,12 @@ def test_code_server_cli_reload_location(self, graphql_context): result.data["reloadRepositoryLocation"]["locationOrLoadError"]["__typename"] == "RepositoryLocation" ) - assert result.data["reloadRepositoryLocation"]["name"] == "test" + assert result.data["reloadRepositoryLocation"]["name"] == main_repo_location_name() assert result.data["reloadRepositoryLocation"]["loadStatus"] == "LOADED" new_location = ( graphql_context.process_context.get_workspace_snapshot() - .code_location_entries["test"] + .code_location_entries[main_repo_location_name()] .code_location ) diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_retry_execution.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_retry_execution.py index 0442242d02619..9d51a84c69147 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_retry_execution.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_retry_execution.py @@ -18,6 +18,7 @@ execute_dagster_graphql, execute_dagster_graphql_and_finish_runs, infer_job_selector, + main_repo_location_name, ) from dagster_graphql_tests.graphql.graphql_context_test_suite import ( @@ -69,7 +70,7 @@ class TestRetryExecutionReadonly(ReadonlyGraphQLContextTestMatrix): def test_retry_execution_permission_failure(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "eventually_successful") - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") remote_job_origin = repository.get_full_job("eventually_successful").get_remote_origin() diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_runs_feed.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_runs_feed.py index 2455e716759f6..b6bc8d9ff5003 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_runs_feed.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_runs_feed.py @@ -12,7 +12,7 @@ from dagster._core.utils import make_new_backfill_id from dagster._time import get_current_timestamp from dagster_graphql.implementation.fetch_runs import RunsFeedCursor -from dagster_graphql.test.utils import execute_dagster_graphql +from dagster_graphql.test.utils import execute_dagster_graphql, main_repo_location_name from dagster_graphql_tests.graphql.graphql_context_test_suite import ( ExecutingGraphQLContextTestMatrix, @@ -951,7 +951,7 @@ def test_get_runs_feed_filter_create_time(self, graphql_context): def test_get_runs_feed_filter_job_name(self, graphql_context): if not self.supports_filtering(): return pytest.skip("storage does not support filtering backfills by job_name") - code_location = graphql_context.get_code_location("test") + code_location = graphql_context.get_code_location(main_repo_location_name()) repository = code_location.get_repository("test_repo") partition_set_origin = RemotePartitionSetOrigin( diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_workspace.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_workspace.py index 69b78b26918e7..6fb588b26e34f 100644 --- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_workspace.py +++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_workspace.py @@ -11,7 +11,7 @@ from dagster._core.types.loadable_target_origin import LoadableTargetOrigin from dagster._core.workspace.load import location_origins_from_yaml_paths from dagster.version import __version__ as dagster_version -from dagster_graphql.test.utils import execute_dagster_graphql +from dagster_graphql.test.utils import execute_dagster_graphql, main_repo_location_name from dagster_graphql.version import __version__ as dagster_graphql_version from dagster_graphql_tests.graphql.graphql_context_test_suite import ( @@ -329,7 +329,9 @@ def test_load_workspace_masked(self, graphql_context, enable_masking_user_code_e ) def test_workspace_entry_by_name(self, graphql_context) -> None: - result = execute_dagster_graphql(graphql_context, LOCATION_ENTRY_QUERY, {"name": "test"}) + result = execute_dagster_graphql( + graphql_context, LOCATION_ENTRY_QUERY, {"name": main_repo_location_name()} + ) assert result assert result.data["workspaceLocationEntryOrError"] assert ( @@ -352,7 +354,7 @@ def test_workspace_entry_by_name(self, graphql_context) -> None: mock_fetch.side_effect = Exception("boom") result = execute_dagster_graphql( - graphql_context, LOCATION_ENTRY_QUERY, {"name": "test"} + graphql_context, LOCATION_ENTRY_QUERY, {"name": main_repo_location_name()} ) assert result assert result.data["workspaceLocationEntryOrError"] diff --git a/python_modules/dagster/dagster/_cli/asset.py b/python_modules/dagster/dagster/_cli/asset.py index 8d7166909e06a..0ac3fc36cab26 100644 --- a/python_modules/dagster/dagster/_cli/asset.py +++ b/python_modules/dagster/dagster/_cli/asset.py @@ -31,7 +31,7 @@ def asset_cli(): @asset_cli.command(name="materialize", help="Execute a run to materialize a selection of assets") @python_origin_target_argument -@click.option("--select", help="Asset selection to target", required=True) +@click.option("--select", help="Comma-separated Asset selection to target", required=True) @click.option("--partition", help="Asset partition to target", required=False) @click.option( "--partition-range", diff --git a/python_modules/dagster/dagster/_components/__init__.py b/python_modules/dagster/dagster/_components/__init__.py deleted file mode 100644 index 1dd743fb3fe39..0000000000000 --- a/python_modules/dagster/dagster/_components/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -from dagster._components.core.component import ( - Component as Component, - ComponentLoadContext as ComponentLoadContext, - ComponentRegistry as ComponentRegistry, -) -from dagster._components.core.component_defs_builder import ( - build_defs_from_toplevel_components_folder as build_defs_from_toplevel_components_folder, -) diff --git a/python_modules/dagster/dagster/_components/cli/__init__.py b/python_modules/dagster/dagster/_components/cli/__init__.py deleted file mode 100644 index 34fdd17211667..0000000000000 --- a/python_modules/dagster/dagster/_components/cli/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -import click - -from dagster._components.cli.generate import generate_cli -from dagster.version import __version__ - - -def create_dagster_components_cli(): - commands = { - "generate": generate_cli, - } - - @click.group( - commands=commands, - context_settings={"max_content_width": 120, "help_option_names": ["-h", "--help"]}, - ) - @click.version_option(__version__, "--version", "-v") - def group(): - """CLI tools for working with Dagster.""" - - return group - - -ENV_PREFIX = "DG_CLI" -cli = create_dagster_components_cli() - - -def main(): - cli(auto_envvar_prefix=ENV_PREFIX) diff --git a/python_modules/dagster/dagster/_components/cli/generate.py b/python_modules/dagster/dagster/_components/cli/generate.py deleted file mode 100644 index 26be318d803ec..0000000000000 --- a/python_modules/dagster/dagster/_components/cli/generate.py +++ /dev/null @@ -1,104 +0,0 @@ -import os -import sys -from pathlib import Path - -import click - -from dagster._components.core.component import ComponentRegistry -from dagster._components.core.deployment import ( - CodeLocationProjectContext, - DeploymentProjectContext, - is_inside_code_location_project, - is_inside_deployment_project, -) -from dagster._generate.generate import ( - generate_code_location, - generate_component_instance, - generate_component_type, - generate_deployment, -) - - -@click.group(name="generate") -def generate_cli() -> None: - """Commands for generating Dagster components and related entities.""" - - -@generate_cli.command(name="deployment") -@click.argument("path", type=str) -def generate_deployment_command(path: str) -> None: - """Generate a Dagster deployment instance.""" - dir_abspath = os.path.abspath(path) - if os.path.exists(dir_abspath): - click.echo( - click.style(f"A file or directory at {dir_abspath} already exists. ", fg="red") - + "\nPlease delete the contents of this path or choose another location." - ) - sys.exit(1) - generate_deployment(path) - - -@generate_cli.command(name="code-location") -@click.argument("name", type=str) -def generate_code_location_command(name: str) -> None: - """Generate a Dagster code location inside a component.""" - if not is_inside_deployment_project(Path(".")): - click.echo( - click.style("This command must be run inside a Dagster deployment project.", fg="red") - ) - sys.exit(1) - - context = DeploymentProjectContext.from_path(Path.cwd()) - if context.has_code_location(name): - click.echo(click.style(f"A code location named {name} already exists.", fg="red")) - sys.exit(1) - - code_location_path = os.path.join(context.code_location_root_path, name) - generate_code_location(code_location_path) - - -@generate_cli.command(name="component-type") -@click.argument("name", type=str) -def generate_component_type_command(name: str) -> None: - """Generate a Dagster component instance.""" - if not is_inside_code_location_project(Path(".")): - click.echo( - click.style( - "This command must be run inside a Dagster code location project.", fg="red" - ) - ) - sys.exit(1) - - context = CodeLocationProjectContext.from_path(Path.cwd(), ComponentRegistry.empty()) - if context.has_component_type(name): - click.echo(click.style(f"A component type named `{name}` already exists.", fg="red")) - sys.exit(1) - - generate_component_type(context.component_types_root_path, name) - - -@generate_cli.command(name="component") -@click.argument("component-type", type=str) -@click.argument("name", type=str) -def generate_component_command(component_type: str, name: str) -> None: - """Generate a Dagster component instance.""" - if not is_inside_code_location_project(Path(".")): - click.echo( - click.style( - "This command must be run inside a Dagster code location project.", fg="red" - ) - ) - sys.exit(1) - - context = CodeLocationProjectContext.from_path(Path.cwd(), ComponentRegistry.empty()) - if not context.has_component_type(component_type): - click.echo( - click.style(f"No component type `{component_type}` could be resolved.", fg="red") - ) - sys.exit(1) - elif context.has_component_instance(name): - click.echo(click.style(f"A component instance named `{name}` already exists.", fg="red")) - sys.exit(1) - - component_type_cls = context.get_component_type(component_type) - generate_component_instance(context.component_instances_root_path, name, component_type_cls) diff --git a/python_modules/dagster/dagster/_components/core/__init__.py b/python_modules/dagster/dagster/_components/core/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_components/core/component.py b/python_modules/dagster/dagster/_components/core/component.py deleted file mode 100644 index 60a58c2d8822e..0000000000000 --- a/python_modules/dagster/dagster/_components/core/component.py +++ /dev/null @@ -1,90 +0,0 @@ -from abc import ABC, abstractmethod -from types import ModuleType -from typing import TYPE_CHECKING, ClassVar, Dict, Iterable, Mapping, Optional, Type - -from typing_extensions import Self - -from dagster._core.errors import DagsterError -from dagster._utils import snakecase - -if TYPE_CHECKING: - from dagster._core.definitions.definitions_class import Definitions - - -class ComponentDeclNode: ... - - -class Component(ABC): - name: ClassVar[Optional[str]] = None - - @classmethod - def registered_name(cls) -> str: - return cls.name or snakecase(cls.__name__) - - @classmethod - def generate_files(cls) -> None: - raise NotImplementedError() - - @abstractmethod - def build_defs(self, context: "ComponentLoadContext") -> "Definitions": ... - - @classmethod - @abstractmethod - def from_decl_node( - cls, context: "ComponentLoadContext", decl_node: "ComponentDeclNode" - ) -> Self: ... - - -class ComponentRegistry: - def __init__(self, components: Dict[str, Type[Component]]): - self._components: Dict[str, Type[Component]] = components - - @staticmethod - def empty() -> "ComponentRegistry": - return ComponentRegistry({}) - - def register(self, name: str, component: Type[Component]) -> None: - if name in self._components: - raise DagsterError(f"There is an existing component registered under {name}") - self._components[name] = component - - def has(self, name: str) -> bool: - return name in self._components - - def get(self, name: str) -> Type[Component]: - return self._components[name] - - def keys(self) -> Iterable[str]: - return self._components.keys() - - def __repr__(self) -> str: - return f"" - - -def register_components_in_module(registry: ComponentRegistry, root_module: ModuleType) -> None: - from dagster._core.definitions.load_assets_from_modules import ( - find_modules_in_package, - find_subclasses_in_module, - ) - - for module in find_modules_in_package(root_module): - for component in find_subclasses_in_module(module, (Component,)): - if component is Component: - continue - registry.register(component.registered_name(), component) - - -class ComponentLoadContext: - def __init__(self, *, resources: Mapping[str, object], registry: ComponentRegistry): - self.registry = registry - self.resources = resources - - @staticmethod - def for_test( - *, - resources: Optional[Mapping[str, object]] = None, - registry: Optional[ComponentRegistry] = None, - ) -> "ComponentLoadContext": - return ComponentLoadContext( - resources=resources or {}, registry=registry or ComponentRegistry.empty() - ) diff --git a/python_modules/dagster/dagster/_components/core/component_decl_builder.py b/python_modules/dagster/dagster/_components/core/component_decl_builder.py deleted file mode 100644 index 659b632584a56..0000000000000 --- a/python_modules/dagster/dagster/_components/core/component_decl_builder.py +++ /dev/null @@ -1,50 +0,0 @@ -from pathlib import Path -from typing import Any, Mapping, Optional, Sequence, Union - -from pydantic import BaseModel - -from dagster._components.core.component import ComponentDeclNode -from dagster._record import record -from dagster._utils.pydantic_yaml import parse_yaml_file_to_pydantic - - -class DefsFileModel(BaseModel): - component_type: str - component_params: Optional[Mapping[str, Any]] = None - - -@record -class YamlComponentDecl(ComponentDeclNode): - path: Path - defs_file_model: DefsFileModel - - -@record -class ComponentFolder(ComponentDeclNode): - path: Path - sub_decls: Sequence[Union[YamlComponentDecl, "ComponentFolder"]] - - -def find_component_decl(path: Path) -> Optional[ComponentDeclNode]: - # right now, we only support two types of components, both of which are folders - # if the folder contains a defs.yml file, it's a component instance - # otherwise, it's a folder containing sub-components - - if not path.is_dir(): - return None - - defs_path = path / "defs.yml" - - if defs_path.exists(): - defs_file_model = parse_yaml_file_to_pydantic( - DefsFileModel, defs_path.read_text(), str(path) - ) - return YamlComponentDecl(path=path, defs_file_model=defs_file_model) - - subs = [] - for subpath in path.iterdir(): - component = find_component_decl(subpath) - if component: - subs.append(component) - - return ComponentFolder(path=path, sub_decls=subs) if subs else None diff --git a/python_modules/dagster/dagster/_components/core/component_defs_builder.py b/python_modules/dagster/dagster/_components/core/component_defs_builder.py deleted file mode 100644 index d2c693478bd7c..0000000000000 --- a/python_modules/dagster/dagster/_components/core/component_defs_builder.py +++ /dev/null @@ -1,87 +0,0 @@ -from pathlib import Path -from typing import TYPE_CHECKING, List, Mapping, Optional, Sequence - -from dagster._components.core.component import Component, ComponentLoadContext, ComponentRegistry -from dagster._components.core.component_decl_builder import ( - ComponentFolder, - YamlComponentDecl, - find_component_decl, -) -from dagster._components.core.deployment import CodeLocationProjectContext - -if TYPE_CHECKING: - from dagster._core.definitions.definitions_class import Definitions - - -def build_component_hierarchy( - context: ComponentLoadContext, component_folder: ComponentFolder -) -> Sequence[Component]: - to_return = [] - for decl_node in component_folder.sub_decls: - if isinstance(decl_node, YamlComponentDecl): - parsed_defs = decl_node.defs_file_model - component_type = context.registry.get(parsed_defs.component_type) - to_return.append(component_type.from_decl_node(context, decl_node)) - elif isinstance(decl_node, ComponentFolder): - to_return.extend(build_component_hierarchy(context, decl_node)) - else: - raise NotImplementedError(f"Unknown component type {decl_node}") - return to_return - - -def build_components_from_component_folder( - context: ComponentLoadContext, - path: Path, -) -> Sequence[Component]: - component_folder = find_component_decl(path) - assert isinstance(component_folder, ComponentFolder) - return build_component_hierarchy(context, component_folder) - - -def build_defs_from_component_folder( - path: Path, - registry: ComponentRegistry, - resources: Mapping[str, object], -) -> "Definitions": - """Build a definitions object from a folder within the components hierarchy.""" - component_folder = find_component_decl(path=path) - assert isinstance(component_folder, ComponentFolder) - context = ComponentLoadContext(resources=resources, registry=registry) - components = build_components_from_component_folder(context=context, path=path) - return defs_from_components(resources=resources, context=context, components=components) - - -def defs_from_components( - *, - context: ComponentLoadContext, - components: Sequence[Component], - resources: Mapping[str, object], -) -> "Definitions": - from dagster._core.definitions.definitions_class import Definitions - - return Definitions.merge_internal( - [*[c.build_defs(context) for c in components], Definitions(resources=resources)] - ) - - -# Public method so optional Nones are fine -def build_defs_from_toplevel_components_folder( - path: Path, - resources: Optional[Mapping[str, object]] = None, - registry: Optional["ComponentRegistry"] = None, -) -> "Definitions": - """Build a Definitions object from an entire component hierarchy.""" - from dagster._core.definitions.definitions_class import Definitions - - context = CodeLocationProjectContext.from_path(path, registry or ComponentRegistry.empty()) - - all_defs: List[Definitions] = [] - for component in context.component_instances: - component_path = Path(context.get_component_instance_path(component)) - defs = build_defs_from_component_folder( - path=component_path, - registry=context.component_registry, - resources=resources or {}, - ) - all_defs.append(defs) - return Definitions.merge_internal(all_defs) diff --git a/python_modules/dagster/dagster/_components/core/deployment.py b/python_modules/dagster/dagster/_components/core/deployment.py deleted file mode 100644 index 73216b8058881..0000000000000 --- a/python_modules/dagster/dagster/_components/core/deployment.py +++ /dev/null @@ -1,163 +0,0 @@ -import importlib.util -import os -import sys -from pathlib import Path -from typing import Final, Iterable, Type - -from typing_extensions import Self - -from dagster._components.core.component import ( - Component, - ComponentRegistry, - register_components_in_module, -) -from dagster._core.errors import DagsterError - - -def is_inside_deployment_project(path: Path) -> bool: - try: - _resolve_deployment_root_path(path) - return True - except DagsterError: - return False - - -def _resolve_deployment_root_path(path: Path) -> str: - current_path = os.path.abspath(path) - while not _is_deployment_root(current_path): - current_path = os.path.dirname(current_path) - if current_path == "/": - raise DagsterError("Cannot find deployment root") - return current_path - - -def is_inside_code_location_project(path: Path) -> bool: - try: - _resolve_code_location_root_path(path) - return True - except DagsterError: - return False - - -def _resolve_code_location_root_path(path: Path) -> str: - current_path = os.path.abspath(path) - while not _is_code_location_root(current_path): - current_path = os.path.dirname(current_path) - if current_path == "/": - raise DagsterError("Cannot find code location root") - return current_path - - -def _is_deployment_root(path: str) -> bool: - return os.path.exists(os.path.join(path, "code_locations")) - - -def _is_code_location_root(path: str) -> bool: - return os.path.basename(os.path.dirname(path)) == "code_locations" - - -# Deployment -_DEPLOYMENT_CODE_LOCATIONS_DIR: Final = "code_locations" - -# Code location -_CODE_LOCATION_CUSTOM_COMPONENTS_DIR: Final = "lib" -_CODE_LOCATION_COMPONENT_INSTANCES_DIR: Final = "components" - - -class DeploymentProjectContext: - @classmethod - def from_path(cls, path: Path) -> Self: - return cls(root_path=_resolve_deployment_root_path(path)) - - def __init__(self, root_path: str): - self._root_path = root_path - - @property - def deployment_root(self) -> str: - return self._root_path - - @property - def code_location_root_path(self) -> str: - return os.path.join(self._root_path, _DEPLOYMENT_CODE_LOCATIONS_DIR) - - def has_code_location(self, name: str) -> bool: - return os.path.exists(os.path.join(self._root_path, "code_locations", name)) - - -class CodeLocationProjectContext: - @classmethod - def from_path(cls, path: Path, component_registry: "ComponentRegistry") -> Self: - root_path = _resolve_code_location_root_path(path) - name = os.path.basename(root_path) - - # TODO: Rm when a more robust solution is implemented - # Make sure we can import from the cwd - if sys.path[0] != "": - sys.path.insert(0, "") - - components_lib_module = f"{name}.{_CODE_LOCATION_CUSTOM_COMPONENTS_DIR}" - module = importlib.import_module(components_lib_module) - register_components_in_module(component_registry, module) - - return cls( - deployment_context=DeploymentProjectContext.from_path(path), - root_path=root_path, - name=os.path.basename(root_path), - component_registry=component_registry, - ) - - def __init__( - self, - deployment_context: DeploymentProjectContext, - root_path: str, - name: str, - component_registry: "ComponentRegistry", - ): - self._deployment_context = deployment_context - self._root_path = root_path - self._name = name - self._component_registry = component_registry - - @property - def deployment_context(self) -> DeploymentProjectContext: - return self._deployment_context - - @property - def component_types_root_path(self) -> str: - return os.path.join(self._root_path, self._name, _CODE_LOCATION_CUSTOM_COMPONENTS_DIR) - - @property - def component_types_root_module(self) -> str: - return f"{self._name}.{_CODE_LOCATION_CUSTOM_COMPONENTS_DIR}" - - @property - def component_registry(self) -> "ComponentRegistry": - return self._component_registry - - def has_component_type(self, name: str) -> bool: - return self._component_registry.has(name) - - def get_component_type(self, name: str) -> Type[Component]: - if not self.has_component_type(name): - raise DagsterError(f"No component type named {name}") - return self._component_registry.get(name) - - def get_component_instance_path(self, name: str) -> str: - if name not in self.component_instances: - raise DagsterError(f"No component instance named {name}") - return os.path.join(self.component_instances_root_path, name) - - @property - def component_instances_root_path(self) -> str: - return os.path.join(self._root_path, self._name, _CODE_LOCATION_COMPONENT_INSTANCES_DIR) - - @property - def component_instances(self) -> Iterable[str]: - return os.listdir( - os.path.join(self._root_path, self._name, _CODE_LOCATION_COMPONENT_INSTANCES_DIR) - ) - - def has_component_instance(self, name: str) -> bool: - return os.path.exists( - os.path.join(self._root_path, self._name, _CODE_LOCATION_COMPONENT_INSTANCES_DIR, name) - ) diff --git a/python_modules/dagster/dagster/_components/core/registry.py b/python_modules/dagster/dagster/_components/core/registry.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_components/impls/__init__.py b/python_modules/dagster/dagster/_components/impls/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_components/impls/pipes_subprocess_script_collection.py b/python_modules/dagster/dagster/_components/impls/pipes_subprocess_script_collection.py deleted file mode 100644 index 817d39b1ae139..0000000000000 --- a/python_modules/dagster/dagster/_components/impls/pipes_subprocess_script_collection.py +++ /dev/null @@ -1,100 +0,0 @@ -import shutil -import warnings -from pathlib import Path -from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence - -from pydantic import BaseModel, TypeAdapter - -from dagster._components.core.component import Component, ComponentDeclNode, ComponentLoadContext -from dagster._components.core.component_decl_builder import YamlComponentDecl -from dagster._core.definitions.asset_key import AssetKey -from dagster._core.definitions.asset_spec import AssetSpec -from dagster._core.definitions.assets import AssetsDefinition -from dagster._core.definitions.decorators.asset_decorator import multi_asset -from dagster._core.execution.context.asset_execution_context import AssetExecutionContext -from dagster._core.pipes.subprocess import PipesSubprocessClient -from dagster._utils.warnings import ExperimentalWarning - -if TYPE_CHECKING: - from dagster._core.definitions.definitions_class import Definitions - - -class AssetSpecModel(BaseModel): - key: str - deps: Sequence[str] = [] - description: Optional[str] = None - metadata: Mapping[str, Any] = {} - group_name: Optional[str] = None - skippable: bool = False - code_version: Optional[str] = None - owners: Sequence[str] = [] - tags: Mapping[str, str] = {} - - def to_asset_spec(self) -> AssetSpec: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=ExperimentalWarning) - return AssetSpec( - **{ - **self.__dict__, - "key": AssetKey.from_user_string(self.key), - }, - ) - - -class PipesSubprocessScriptParams(BaseModel): - path: str - assets: Sequence[AssetSpecModel] - - -class PipesSubprocessScriptCollectionParams(BaseModel): - scripts: Sequence[PipesSubprocessScriptParams] - - -class PipesSubprocessScriptCollection(Component): - params_schema = PipesSubprocessScriptCollectionParams - - def __init__(self, dirpath: Path, path_specs: Mapping[Path, Sequence[AssetSpec]]): - self.dirpath = dirpath - # mapping from the script name (e.g. /path/to/script_abc.py -> script_abc) - # to the specs it produces - self.path_specs = path_specs - - @staticmethod - def introspect_from_path(path: Path) -> "PipesSubprocessScriptCollection": - path_specs = {path: [AssetSpec(path.stem)] for path in list(path.rglob("*.py"))} - return PipesSubprocessScriptCollection(dirpath=path, path_specs=path_specs) - - @classmethod - def from_decl_node( - cls, load_context: ComponentLoadContext, component_decl: ComponentDeclNode - ) -> "PipesSubprocessScriptCollection": - assert isinstance(component_decl, YamlComponentDecl) - loaded_params = TypeAdapter(cls.params_schema).validate_python( - component_decl.defs_file_model.component_params - ) - - path_specs = {} - for script in loaded_params.scripts: - script_path = component_decl.path / script.path - if not script_path.exists(): - raise FileNotFoundError(f"Script {script_path} does not exist") - path_specs[script_path] = [spec.to_asset_spec() for spec in script.assets] - - return cls(dirpath=component_decl.path, path_specs=path_specs) - - def build_defs(self, load_context: "ComponentLoadContext") -> "Definitions": - from dagster._core.definitions.definitions_class import Definitions - - return Definitions( - assets=[self._create_asset_def(path, specs) for path, specs in self.path_specs.items()], - resources={"pipes_client": PipesSubprocessClient()}, - ) - - def _create_asset_def(self, path: Path, specs: Sequence[AssetSpec]) -> AssetsDefinition: - # TODO: allow name paraeterization - @multi_asset(specs=specs, name=f"script_{path.stem}") - def _asset(context: AssetExecutionContext, pipes_client: PipesSubprocessClient): - cmd = [shutil.which("python"), path] - return pipes_client.run(command=cmd, context=context).get_results() - - return _asset diff --git a/python_modules/dagster/dagster/_core/definitions/definitions_class.py b/python_modules/dagster/dagster/_core/definitions/definitions_class.py index 0910c669bd59f..bf527d142f232 100644 --- a/python_modules/dagster/dagster/_core/definitions/definitions_class.py +++ b/python_modules/dagster/dagster/_core/definitions/definitions_class.py @@ -635,11 +635,6 @@ def merge(*def_sets: "Definitions") -> "Definitions": Returns: Definitions: The merged definitions. """ - check.sequence_param(def_sets, "def_sets", of_type=Definitions) - return Definitions.merge_internal(def_sets) - - @staticmethod - def merge_internal(def_sets: Sequence["Definitions"]) -> "Definitions": check.sequence_param(def_sets, "def_sets", of_type=Definitions) assets = [] schedules = [] diff --git a/python_modules/dagster/dagster/_core/definitions/schedule_definition.py b/python_modules/dagster/dagster/_core/definitions/schedule_definition.py index 2e5357b862f38..d9e0c7fc80a63 100644 --- a/python_modules/dagster/dagster/_core/definitions/schedule_definition.py +++ b/python_modules/dagster/dagster/_core/definitions/schedule_definition.py @@ -543,7 +543,7 @@ def with_updated_job(self, new_job: ExecutableDefinition) -> "ScheduleDefinition """Returns a copy of this schedule with the job replaced. Args: - job (ExecutableDefinition): The job that should execute when this + new_job (ExecutableDefinition): The job that should execute when this schedule runs. """ return ScheduleDefinition.dagster_internal_init( @@ -557,9 +557,14 @@ def with_updated_job(self, new_job: ExecutableDefinition) -> "ScheduleDefinition default_status=self.default_status, environment_vars=self._environment_vars, required_resource_keys=self._raw_required_resource_keys, - run_config=None, # run_config, tags, should_execute encapsulated in execution_fn + # run_config, run_config_fn, tags_fn, should_execute are not copied because the schedule constructor + # incorporates them into the execution_fn defined in the constructor. Since we are + # copying the execution_fn, we don't need to copy these, and it would actually be an + # error to do so (since you can't pass an execution_fn and any of these values + # simultaneously). + run_config=None, run_config_fn=None, - tags=None, + tags=self.tags, tags_fn=None, metadata=self.metadata, should_execute=None, diff --git a/python_modules/dagster/dagster/_core/storage/upath_io_manager.py b/python_modules/dagster/dagster/_core/storage/upath_io_manager.py index 5801c7f671a86..08a704f5e03e5 100644 --- a/python_modules/dagster/dagster/_core/storage/upath_io_manager.py +++ b/python_modules/dagster/dagster/_core/storage/upath_io_manager.py @@ -434,7 +434,8 @@ def handle_output(self, context: OutputContext, obj: Any): f"The current IO manager {type(self)} does not support persisting an output" " associated with multiple partitions. This error is likely occurring because a" " backfill was launched using the 'single run' option. Instead, launch the" - " backfill with the 'multiple runs' option.", + " backfill with a multi-run backfill policy. You can also avoid this error by" + " opting out of IO managers entirely by setting the return type of your asset/op to `None`.", ) path = next(iter(paths.values())) diff --git a/python_modules/dagster/dagster/_generate/generate.py b/python_modules/dagster/dagster/_generate/generate.py index 41066f487b766..3bb623512c0fa 100644 --- a/python_modules/dagster/dagster/_generate/generate.py +++ b/python_modules/dagster/dagster/_generate/generate.py @@ -1,12 +1,10 @@ import os import posixpath -from typing import Any, List, Optional, Type +from typing import Any, List, Optional import click import jinja2 -from dagster._components.core.component import Component -from dagster._utils import camelcase, pushd from dagster.version import __version__ as dagster_version DEFAULT_EXCLUDES: List[str] = [ @@ -22,59 +20,6 @@ PROJECT_NAME_PLACEHOLDER = "PROJECT_NAME_PLACEHOLDER" -def generate_deployment(path: str) -> None: - click.echo(f"Creating a Dagster deployment at {path}.") - - generate_project( - path=path, - name_placeholder="DEPLOYMENT_NAME_PLACEHOLDER", - templates_path=os.path.join( - os.path.dirname(__file__), "templates", "DEPLOYMENT_NAME_PLACEHOLDER" - ), - ) - - -def generate_code_location(path: str) -> None: - click.echo(f"Creating a Dagster code location at {path}.") - - generate_project( - path=path, - name_placeholder="CODE_LOCATION_NAME_PLACEHOLDER", - templates_path=os.path.join( - os.path.dirname(__file__), "templates", "CODE_LOCATION_NAME_PLACEHOLDER" - ), - ) - - -def generate_component_type(root_path: str, name: str) -> None: - click.echo(f"Creating a Dagster component type at {root_path}/{name}.py.") - - generate_project( - path=root_path, - name_placeholder="COMPONENT_TYPE_NAME_PLACEHOLDER", - templates_path=os.path.join(os.path.dirname(__file__), "templates", "COMPONENT_TYPE"), - project_name=name, - component_type_class_name=camelcase(name), - ) - - -def generate_component_instance(root_path: str, name: str, component_type: Type[Component]) -> None: - click.echo(f"Creating a Dagster component instance at {root_path}/{name}.py.") - - component_instance_root_path = os.path.join(root_path, name) - generate_project( - path=component_instance_root_path, - name_placeholder="COMPONENT_INSTANCE_NAME_PLACEHOLDER", - templates_path=os.path.join( - os.path.dirname(__file__), "templates", "COMPONENT_INSTANCE_NAME_PLACEHOLDER" - ), - project_name=name, - component_type=component_type.registered_name(), - ) - with pushd(component_instance_root_path): - component_type.generate_files() - - def generate_repository(path: str): REPO_NAME_PLACEHOLDER = "REPO_NAME_PLACEHOLDER" diff --git a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/__init__.py b/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/components/.gitkeep b/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/components/.gitkeep deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py b/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py deleted file mode 100644 index 97f7f39c8562f..0000000000000 --- a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py +++ /dev/null @@ -1,9 +0,0 @@ -from pathlib import Path - -from dagster._components.core.component_defs_builder import ( - build_defs_from_toplevel_components_folder, -) - -defs = build_defs_from_toplevel_components_folder( - path=Path(__file__).parent, -) diff --git a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/lib/__init__.py b/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/lib/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER_tests/__init__.py b/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER_tests/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja b/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja deleted file mode 100644 index 0fa5131cb4abc..0000000000000 --- a/python_modules/dagster/dagster/_generate/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja +++ /dev/null @@ -1,19 +0,0 @@ -[project] -name = "{{ project_name }}" -requires-python = ">=3.9,<3.13" -version = "0.1.0" -dependencies = [] - -[project.optional-dependencies] -dev = [] - -[build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" - -[tool.dagster] -module_name = "{{ project_name }}.definitions" -project_name = "{{ project_name }}" - -[tool.setuptools.packages.find] -exclude=["{{ project_name }}_tests"] diff --git a/python_modules/dagster/dagster/_generate/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja b/python_modules/dagster/dagster/_generate/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja deleted file mode 100644 index 500448661af63..0000000000000 --- a/python_modules/dagster/dagster/_generate/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja +++ /dev/null @@ -1,16 +0,0 @@ -from dagster import Definitions -from dagster._components import ( - Component, - ComponentRegistry, - ComponentLoadContext, - build_defs_from_toplevel_components_folder, -) - -class {{ component_type_class_name }}(Component): - - @classmethod - def generate_files(cls) -> None: - ... - - def build_defs(self, load_context: ComponentLoadContext) -> Definitions: - ... diff --git a/python_modules/dagster/dagster/_generate/templates/DEPLOYMENT_NAME_PLACEHOLDER/.github/workflows/dagster-cloud-deploy.yaml.jinja b/python_modules/dagster/dagster/_generate/templates/DEPLOYMENT_NAME_PLACEHOLDER/.github/workflows/dagster-cloud-deploy.yaml.jinja deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_generate/templates/DEPLOYMENT_NAME_PLACEHOLDER/code_locations/.gitkeep b/python_modules/dagster/dagster/_generate/templates/DEPLOYMENT_NAME_PLACEHOLDER/code_locations/.gitkeep deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_generate/templates/DEPLOYMENT_NAME_PLACEHOLDER/dagster_cloud.yaml.jinja b/python_modules/dagster/dagster/_generate/templates/DEPLOYMENT_NAME_PLACEHOLDER/dagster_cloud.yaml.jinja deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster/_utils/schedules.py b/python_modules/dagster/dagster/_utils/schedules.py index d1132e8a7bd5c..b51cec36abf99 100644 --- a/python_modules/dagster/dagster/_utils/schedules.py +++ b/python_modules/dagster/dagster/_utils/schedules.py @@ -53,11 +53,20 @@ def _is_simple_cron( def is_valid_cron_string(cron_string: str) -> bool: if not CroniterShim.is_valid(cron_string): return False + # Croniter < 1.4 returns 2 items # Croniter >= 1.4 returns 3 items expanded, *_ = CroniterShim.expand(cron_string) + # dagster only recognizes cron strings that resolve to 5 parts (e.g. not seconds resolution) - return len(expanded) == 5 + if len(expanded) != 5: + return False + + if len(expanded[3]) == 1 and expanded[3][0] == 2: # February + if len(expanded[2]) == 1 and expanded[2][0] in {30, 31}: # 30th or 31st of February + return False + + return True def is_valid_cron_schedule(cron_schedule: Union[str, Sequence[str]]) -> bool: diff --git a/python_modules/dagster/dagster_tests/cli_tests/test_generate_commands.py b/python_modules/dagster/dagster_tests/cli_tests/test_generate_commands.py deleted file mode 100644 index 50dcce6694672..0000000000000 --- a/python_modules/dagster/dagster_tests/cli_tests/test_generate_commands.py +++ /dev/null @@ -1,204 +0,0 @@ -import importlib -import inspect -import os -import sys -import textwrap -from contextlib import contextmanager -from pathlib import Path -from typing import Iterator - -from click.testing import CliRunner -from dagster._components.cli.generate import ( - generate_code_location_command, - generate_component_command, - generate_component_type_command, - generate_deployment_command, -) -from dagster._components.core.component import ComponentRegistry -from dagster._components.core.deployment import CodeLocationProjectContext -from dagster._utils import pushd - - -def _ensure_cwd_on_sys_path(): - if sys.path[0] != "": - sys.path.insert(0, "") - - -def _assert_module_imports(module_name: str): - _ensure_cwd_on_sys_path() - assert importlib.import_module(module_name) - - -# This is a holder for code that is intended to be written to a file -def _example_component_type_baz(): - from dagster import AssetExecutionContext, Definitions, PipesSubprocessClient, asset - from dagster._components import Component, ComponentLoadContext - - _SAMPLE_PIPES_SCRIPT = """ - from dagster_pipes import open_dagster_pipes - - context = open_dagster_pipes() - context.report_asset_materialization({"alpha": "beta"}) - """ - - class Baz(Component): - @classmethod - def generate_files(cls): - with open("sample.py", "w") as f: - f.write(_SAMPLE_PIPES_SCRIPT) - - def build_defs(self, context: ComponentLoadContext) -> Definitions: - @asset - def foo(context: AssetExecutionContext, client: PipesSubprocessClient): - client.run(context=context, command=["python", "sample.py"]) - - return Definitions(assets=[foo], resources={"client": PipesSubprocessClient()}) - - -@contextmanager -def isolated_example_deployment_foo(runner: CliRunner) -> Iterator[None]: - with runner.isolated_filesystem(): - runner.invoke(generate_deployment_command, ["foo"]) - with pushd("foo"): - yield - - -@contextmanager -def isolated_example_code_location_bar(runner: CliRunner) -> Iterator[None]: - with isolated_example_deployment_foo(runner), clean_module_cache("bar"): - runner.invoke(generate_code_location_command, ["bar"]) - with pushd("code_locations/bar"): - yield - - -@contextmanager -def isolated_example_code_location_bar_with_component_type_baz(runner: CliRunner) -> Iterator[None]: - with isolated_example_code_location_bar(runner): - with open("bar/lib/baz.py", "w") as f: - component_type_source = textwrap.dedent( - inspect.getsource(_example_component_type_baz).split("\n", 1)[1] - ) - f.write(component_type_source) - yield - - -@contextmanager -def clean_module_cache(module_name: str): - prefix = f"{module_name}." - keys_to_del = { - key for key in sys.modules.keys() if key == module_name or key.startswith(prefix) - } - for key in keys_to_del: - del sys.modules[key] - yield - - -def test_generate_deployment_command_success() -> None: - runner = CliRunner() - with runner.isolated_filesystem(): - result = runner.invoke(generate_deployment_command, ["foo"]) - assert result.exit_code == 0 - assert Path("foo").exists() - assert Path("foo/.github").exists() - assert Path("foo/.github/workflows").exists() - assert Path("foo/.github/workflows/dagster-cloud-deploy.yaml").exists() - assert Path("foo/dagster_cloud.yaml").exists() - assert Path("foo/code_locations").exists() - - -def test_generate_deployment_command_already_exists_fails() -> None: - runner = CliRunner() - with runner.isolated_filesystem(): - os.mkdir("foo") - result = runner.invoke(generate_deployment_command, ["foo"]) - assert result.exit_code != 0 - assert "already exists" in result.output - - -def test_generate_code_location_success() -> None: - runner = CliRunner() - with isolated_example_deployment_foo(runner): - result = runner.invoke(generate_code_location_command, ["bar"]) - assert result.exit_code == 0 - assert Path("code_locations/bar").exists() - assert Path("code_locations/bar/bar").exists() - assert Path("code_locations/bar/bar/lib").exists() - assert Path("code_locations/bar/bar/components").exists() - assert Path("code_locations/bar/bar_tests").exists() - assert Path("code_locations/bar/pyproject.toml").exists() - - -def test_generate_code_location_outside_deployment_fails() -> None: - runner = CliRunner() - with runner.isolated_filesystem(): - result = runner.invoke(generate_code_location_command, ["bar"]) - assert result.exit_code != 0 - assert "must be run inside a Dagster deployment project" in result.output - - -def test_generate_code_location_already_exists_fails() -> None: - runner = CliRunner() - with isolated_example_deployment_foo(runner): - result = runner.invoke(generate_code_location_command, ["bar"]) - assert result.exit_code == 0 - result = runner.invoke(generate_code_location_command, ["bar"]) - assert result.exit_code != 0 - assert "already exists" in result.output - - -def test_generate_component_type_success() -> None: - runner = CliRunner() - with isolated_example_code_location_bar(runner): - result = runner.invoke(generate_component_type_command, ["baz"]) - assert result.exit_code == 0 - assert Path("bar/lib/baz.py").exists() - _assert_module_imports("bar.lib.baz") - context = CodeLocationProjectContext.from_path(Path.cwd(), ComponentRegistry.empty()) - assert context.has_component_type("baz") - - -def test_generate_component_type_outside_code_location_fails() -> None: - runner = CliRunner() - with isolated_example_deployment_foo(runner): - result = runner.invoke(generate_component_type_command, ["baz"]) - assert result.exit_code != 0 - assert "must be run inside a Dagster code location project" in result.output - - -def test_generate_component_type_already_exists_fails() -> None: - runner = CliRunner() - with isolated_example_code_location_bar(runner): - result = runner.invoke(generate_component_type_command, ["baz"]) - assert result.exit_code == 0 - result = runner.invoke(generate_component_type_command, ["baz"]) - assert result.exit_code != 0 - assert "already exists" in result.output - - -def test_generate_component_success() -> None: - runner = CliRunner() - _ensure_cwd_on_sys_path() - with isolated_example_code_location_bar_with_component_type_baz(runner): - result = runner.invoke(generate_component_command, ["baz", "qux"]) - assert result.exit_code == 0 - assert Path("bar/components/qux").exists() - assert Path("bar/components/qux/sample.py").exists() - - -def test_generate_component_outside_code_location_fails() -> None: - runner = CliRunner() - with isolated_example_deployment_foo(runner): - result = runner.invoke(generate_component_command, ["baz", "qux"]) - assert result.exit_code != 0 - assert "must be run inside a Dagster code location project" in result.output - - -def test_generate_component_already_exists_fails() -> None: - runner = CliRunner() - _ensure_cwd_on_sys_path() - with isolated_example_code_location_bar_with_component_type_baz(runner): - result = runner.invoke(generate_component_command, ["baz", "qux"]) - assert result.exit_code == 0 - result = runner.invoke(generate_component_command, ["baz", "qux"]) - assert result.exit_code != 0 - assert "already exists" in result.output diff --git a/python_modules/dagster/dagster_tests/components_tests/__init__.py b/python_modules/dagster/dagster_tests/components_tests/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/__init__.py b/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/__init__.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/defs.yml b/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/defs.yml deleted file mode 100644 index 3fda5a1194652..0000000000000 --- a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/defs.yml +++ /dev/null @@ -1,15 +0,0 @@ -component_type: pipes_subprocess_script_collection - -component_params: - scripts: - - path: script_one.py - assets: - - key: a - - key: b - deps: [up1, up2] - - path: script_two.py - assets: - - key: c - - path: subdir/script_three.py - assets: - - key: override_key diff --git a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/script_one.py b/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/script_one.py deleted file mode 100644 index 7cd95eb3907aa..0000000000000 --- a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/script_one.py +++ /dev/null @@ -1,6 +0,0 @@ -def do_thing() -> None: - pass - - -if __name__ == "__main__": - do_thing() diff --git a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/script_two.py b/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/script_two.py deleted file mode 100644 index 7cd95eb3907aa..0000000000000 --- a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/script_two.py +++ /dev/null @@ -1,6 +0,0 @@ -def do_thing() -> None: - pass - - -if __name__ == "__main__": - do_thing() diff --git a/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/subdir/script_three.py b/python_modules/dagster/dagster_tests/components_tests/code_locations/python_script_location/components/scripts/subdir/script_three.py deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/python_modules/dagster/dagster_tests/components_tests/test_pipes_subprocess_script_collection.py b/python_modules/dagster/dagster_tests/components_tests/test_pipes_subprocess_script_collection.py deleted file mode 100644 index 05f7a5bac7c52..0000000000000 --- a/python_modules/dagster/dagster_tests/components_tests/test_pipes_subprocess_script_collection.py +++ /dev/null @@ -1,108 +0,0 @@ -from pathlib import Path - -from dagster import AssetKey -from dagster._components.core.component import Component, ComponentLoadContext, ComponentRegistry -from dagster._components.core.component_decl_builder import DefsFileModel -from dagster._components.core.component_defs_builder import ( - YamlComponentDecl, - build_components_from_component_folder, - defs_from_components, -) -from dagster._components.impls.pipes_subprocess_script_collection import ( - PipesSubprocessScriptCollection, -) - -LOCATION_PATH = Path(__file__).parent / "code_locations" / "python_script_location" - - -def registry() -> ComponentRegistry: - return ComponentRegistry( - {"pipes_subprocess_script_collection": PipesSubprocessScriptCollection} - ) - - -def script_load_context() -> ComponentLoadContext: - return ComponentLoadContext(registry=registry(), resources={}) - - -def _asset_keys(component: Component) -> set[AssetKey]: - return { - key - for key in component.build_defs(ComponentLoadContext.for_test()) - .get_asset_graph() - .get_all_asset_keys() - } - - -def _assert_assets(component: Component, expected_assets: int) -> None: - defs = component.build_defs(ComponentLoadContext.for_test()) - assert len(defs.get_asset_graph().get_all_asset_keys()) == expected_assets - result = defs.get_implicit_global_asset_job_def().execute_in_process() - assert result.success - - -def test_python_native() -> None: - component = PipesSubprocessScriptCollection.introspect_from_path( - LOCATION_PATH / "components" / "scripts" - ) - _assert_assets(component, 3) - - -def test_python_params() -> None: - component = PipesSubprocessScriptCollection.from_decl_node( - load_context=script_load_context(), - component_decl=YamlComponentDecl( - path=LOCATION_PATH / "components" / "scripts", - defs_file_model=DefsFileModel( - component_type="pipes_subprocess_script_collection", - component_params={ - "scripts": [ - { - "path": "script_one.py", - "assets": [{"key": "a"}, {"key": "b", "deps": ["up1", "up2"]}], - }, - {"path": "subdir/script_three.py", "assets": [{"key": "key_override"}]}, - ] - }, - ), - ), - ) - assert _asset_keys(component) == { - AssetKey("a"), - AssetKey("b"), - AssetKey("up1"), - AssetKey("up2"), - AssetKey("key_override"), - } - - -def test_load_from_path() -> None: - components = build_components_from_component_folder( - script_load_context(), LOCATION_PATH / "components" - ) - assert len(components) == 1 - assert _asset_keys(components[0]) == { - AssetKey("a"), - AssetKey("b"), - AssetKey("c"), - AssetKey("up1"), - AssetKey("up2"), - AssetKey("override_key"), - } - - _assert_assets(components[0], 6) - - defs = defs_from_components( - context=script_load_context(), - components=components, - resources={}, - ) - - assert defs.get_asset_graph().get_all_asset_keys() == { - AssetKey("a"), - AssetKey("b"), - AssetKey("c"), - AssetKey("up1"), - AssetKey("up2"), - AssetKey("override_key"), - } diff --git a/python_modules/dagster/dagster_tests/definitions_tests/test_schedule.py b/python_modules/dagster/dagster_tests/definitions_tests/test_schedule.py index 5498c9901a571..04b222f822eb3 100644 --- a/python_modules/dagster/dagster_tests/definitions_tests/test_schedule.py +++ b/python_modules/dagster/dagster_tests/definitions_tests/test_schedule.py @@ -2,9 +2,16 @@ from datetime import datetime import pytest -from dagster import DagsterInvalidDefinitionError, ScheduleDefinition, build_schedule_context, graph -from dagster._core.definitions.decorators.op_decorator import op +from dagster import ( + DagsterInvalidDefinitionError, + ScheduleDefinition, + build_schedule_context, + graph, + job, + op, +) from dagster._core.definitions.job_definition import JobDefinition +from dagster._core.definitions.metadata.metadata_value import MetadataValue from dagster._core.definitions.run_config import RunConfig from dagster._core.definitions.run_request import RunRequest @@ -165,3 +172,28 @@ def test_tag_transfer_to_run_request(): assert ( "foo" not in tags_and_exec_fn_schedule.evaluate_tick(context_with_time).run_requests[0].tags ) + + +def test_with_updated_job(): + @op + def my_op(): + pass + + @job + def my_job_1(): + my_op() + + @job + def my_job_2(): + my_op() + + my_schedule_1 = ScheduleDefinition( + job=my_job_1, cron_schedule="@daily", tags={"foo": "bar"}, metadata={"baz": "qux"} + ) + + my_schedule_2 = my_schedule_1.with_updated_job(my_job_2) + + assert my_schedule_2.job.name == "my_job_2" + assert my_schedule_2.cron_schedule == "@daily" + assert my_schedule_2.tags == {"foo": "bar"} + assert my_schedule_2.metadata == {"baz": MetadataValue.text("qux")} diff --git a/python_modules/dagster/dagster_tests/scheduler_tests/test_cron_string_iterator.py b/python_modules/dagster/dagster_tests/scheduler_tests/test_cron_string_iterator.py index c914adf2471a6..690ee891948f9 100644 --- a/python_modules/dagster/dagster_tests/scheduler_tests/test_cron_string_iterator.py +++ b/python_modules/dagster/dagster_tests/scheduler_tests/test_cron_string_iterator.py @@ -6,6 +6,7 @@ from dagster._utils.schedules import ( _croniter_string_iterator, cron_string_iterator, + is_valid_cron_string, reverse_cron_string_iterator, ) @@ -645,3 +646,21 @@ def test_weekend_cron_schedule_with_sunday_as_7(): for i in range(len(expected_datetimes)): assert next(cron_iter) == expected_datetimes[-(i + 1)] + + +def test_invalid_cron_strings(): + assert is_valid_cron_string("0 0 27 2 *") + assert is_valid_cron_string("0 0 28 2 *") + assert is_valid_cron_string("0 0 29 2 *") + assert is_valid_cron_string("0 0 29 2 3") + + assert not is_valid_cron_string("0 0 30 2 *") + assert not is_valid_cron_string("0 0 30 2 3") + + assert not is_valid_cron_string("0 0 31 2 *") + assert not is_valid_cron_string("0 0 31 2 3") + + assert not is_valid_cron_string("0 0 32 2 *") + + assert is_valid_cron_string("0 0 31 1 *") + assert not is_valid_cron_string("0 0 32 1 *") diff --git a/python_modules/dagster/dagster_tests/storage_tests/utils/event_log_storage.py b/python_modules/dagster/dagster_tests/storage_tests/utils/event_log_storage.py index 6831b55aca3de..010278fcad892 100644 --- a/python_modules/dagster/dagster_tests/storage_tests/utils/event_log_storage.py +++ b/python_modules/dagster/dagster_tests/storage_tests/utils/event_log_storage.py @@ -5118,20 +5118,16 @@ def _occupy_slot(key: str): time.sleep(0.05) storage.free_concurrency_slot_for_step(run_id, key) - start = time.time() with ThreadPoolExecutor() as executor: - futures = [executor.submit(_occupy_slot, str(i)) for i in range(100)] - while not all(f.done() for f in futures) and time.time() < start + TOTAL_TIMEOUT_TIME: - time.sleep(0.1) - + list( + executor.map(_occupy_slot, [str(i) for i in range(100)], timeout=TOTAL_TIMEOUT_TIME) + ) foo_info = storage.get_concurrency_info("foo") assert foo_info.slot_count == 5 assert foo_info.active_slot_count == 0 assert foo_info.pending_step_count == 0 assert foo_info.assigned_step_count == 0 - assert all(f.done() for f in futures) - def test_zero_concurrency(self, storage: EventLogStorage): assert storage if not storage.supports_global_concurrency_limits: diff --git a/python_modules/dagster/setup.py b/python_modules/dagster/setup.py index 2c79ba826eff2..62c5322540faf 100644 --- a/python_modules/dagster/setup.py +++ b/python_modules/dagster/setup.py @@ -87,8 +87,8 @@ def get_version() -> str: f"grpcio>={GRPC_VERSION_FLOOR}", f"grpcio-health-checking>={GRPC_VERSION_FLOOR}", "packaging>=20.9", - "protobuf>=3.20.0,<5; python_version<'3.11'", # min protobuf version to be compatible with both protobuf 3 and 4 - "protobuf>=4,<5; python_version>='3.11'", + "protobuf>=3.20.0,<6; python_version<'3.11'", # min protobuf version to be compatible with both protobuf 3 and greater + "protobuf>=4,<6; python_version>='3.11'", "python-dotenv", "pytz", "requests", @@ -108,8 +108,7 @@ def get_version() -> str: "docstring-parser", "universal_pathlib; python_version<'3.12'", "universal_pathlib>=0.2.0; python_version>='3.12'", - # https://github.com/pydantic/pydantic/issues/5821 - "pydantic>=2,<2.10", + "pydantic>=2,<3.0.0", "rich", "filelock", f"dagster-pipes{pin}", @@ -167,7 +166,6 @@ def get_version() -> str: "console_scripts": [ "dagster = dagster.cli:main", "dagster-daemon = dagster.daemon.cli:main", - "dg = dagster._components.cli:main", ] }, ) diff --git a/python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/test_pipes.py b/python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/test_pipes.py index daa7aba661383..d1fb44a3a058c 100644 --- a/python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/test_pipes.py +++ b/python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/test_pipes.py @@ -457,6 +457,8 @@ def test_cloudwatch_logs_reader(cloudwatch_client: "CloudWatchLogsClient", capsy logEvents=[{"timestamp": int(datetime.now().timestamp() * 1000), "message": "1"}], ) + time.sleep(0.1) + assert reader.target_is_readable( {"log_group": log_group, "log_stream": log_stream} ), "Should be able to read after the stream is created" @@ -474,6 +476,8 @@ def test_cloudwatch_logs_reader(cloudwatch_client: "CloudWatchLogsClient", capsy ], ) + time.sleep(0.1) + cloudwatch_client.put_log_events( logGroupName=log_group, logStreamName=log_stream, @@ -485,6 +489,8 @@ def test_cloudwatch_logs_reader(cloudwatch_client: "CloudWatchLogsClient", capsy ], ) + time.sleep(0.1) + is_session_closed.set() time.sleep(1) diff --git a/python_modules/libraries/dagster-dbt/dagster_dbt/asset_utils.py b/python_modules/libraries/dagster-dbt/dagster_dbt/asset_utils.py index 3500cf38a185f..5b2d8f9cb7d5b 100644 --- a/python_modules/libraries/dagster-dbt/dagster_dbt/asset_utils.py +++ b/python_modules/libraries/dagster-dbt/dagster_dbt/asset_utils.py @@ -613,12 +613,12 @@ def default_asset_check_fn( ) -def default_code_version_fn(dbt_resource_props: Mapping[str, Any]) -> str: - return hashlib.sha1( - (dbt_resource_props.get("raw_sql") or dbt_resource_props.get("raw_code", "")).encode( - "utf-8" - ) - ).hexdigest() +def default_code_version_fn(dbt_resource_props: Mapping[str, Any]) -> Optional[str]: + code: Optional[str] = dbt_resource_props.get("raw_sql") or dbt_resource_props.get("raw_code") + if code: + return hashlib.sha1(code.encode("utf-8")).hexdigest() + + return dbt_resource_props.get("checksum", {}).get("checksum") def _attach_sql_model_code_reference( diff --git a/python_modules/libraries/dagster-dbt/dagster_dbt_tests/core/test_asset_decorator.py b/python_modules/libraries/dagster-dbt/dagster_dbt_tests/core/test_asset_decorator.py index 6bac1ae090fab..1d5e7998a46a8 100644 --- a/python_modules/libraries/dagster-dbt/dagster_dbt_tests/core/test_asset_decorator.py +++ b/python_modules/libraries/dagster-dbt/dagster_dbt_tests/core/test_asset_decorator.py @@ -691,6 +691,17 @@ def my_dbt_assets(): ... assert code_version == expected_code_version +def test_all_assets_have_a_distinct_code_version(test_jaffle_shop_manifest: Dict[str, Any]) -> None: + @dbt_assets( + manifest=test_jaffle_shop_manifest, + dagster_dbt_translator=DagsterDbtTranslator(), + ) + def my_dbt_assets(): ... + + code_versions = list(my_dbt_assets.code_versions_by_key.values()) + assert len(code_versions) == len(set(code_versions)) + + def test_with_freshness_policy_replacements(test_jaffle_shop_manifest: Dict[str, Any]) -> None: expected_freshness_policy = FreshnessPolicy(maximum_lag_minutes=60) diff --git a/python_modules/libraries/dagster-embedded-elt/dagster_embedded_elt_tests/dlt_tests/dlt_test_sources/duckdb_with_transformer.py b/python_modules/libraries/dagster-embedded-elt/dagster_embedded_elt_tests/dlt_tests/dlt_test_sources/duckdb_with_transformer.py index 186fe286c5ceb..9b42a8e0b64cf 100644 --- a/python_modules/libraries/dagster-embedded-elt/dagster_embedded_elt_tests/dlt_tests/dlt_test_sources/duckdb_with_transformer.py +++ b/python_modules/libraries/dagster-embedded-elt/dagster_embedded_elt_tests/dlt_tests/dlt_test_sources/duckdb_with_transformer.py @@ -52,8 +52,6 @@ def repos(): primary_key=["repo_id", "issue_id"], write_disposition="merge", data_from=repos, - # Test the case where source identifier 'Repo__Issues' differs from destination identifier 'repo_issues'. - table_name="Repo__Issues", ) def repo_issues(repo): """Extracted list of issues from repositories.""" diff --git a/python_modules/libraries/dagster-mlflow/setup.py b/python_modules/libraries/dagster-mlflow/setup.py index 1d7dc2ed21dff..b95fa88657bf4 100644 --- a/python_modules/libraries/dagster-mlflow/setup.py +++ b/python_modules/libraries/dagster-mlflow/setup.py @@ -32,6 +32,11 @@ def get_version() -> str: packages=find_packages(exclude=["dagster_mlflow_tests*"]), include_package_data=True, python_requires=">=3.9,<3.13", - install_requires=[f"dagster{pin}", "mlflow", "pandas"], + install_requires=[ + f"dagster{pin}", + "mlflow", + "pandas", + "protobuf!=5.29.0", # https://github.com/protocolbuffers/protobuf/issues/19430 + ], zip_safe=False, ) diff --git a/python_modules/libraries/dagster-tableau/dagster_tableau/translator.py b/python_modules/libraries/dagster-tableau/dagster_tableau/translator.py index ca9bd7f47c869..a562cd6ca13cb 100644 --- a/python_modules/libraries/dagster-tableau/dagster_tableau/translator.py +++ b/python_modules/libraries/dagster-tableau/dagster_tableau/translator.py @@ -113,7 +113,7 @@ def workspace_data(self) -> TableauWorkspaceData: @deprecated( breaking_version="1.10", - additional_warn_text="Use `DagsterTableauTranslator.get_asset_spec().key` instead", + additional_warn_text="Use `DagsterTableauTranslator.get_asset_spec(...).key` instead", ) def get_asset_key(self, data: TableauContentData) -> AssetKey: return self.get_asset_spec(data).key @@ -128,7 +128,10 @@ def get_asset_spec(self, data: TableauContentData) -> AssetSpec: else: check.assert_never(data.content_type) - @deprecated(breaking_version="1.10") + @deprecated( + breaking_version="1.10", + additional_warn_text="Use `DagsterTableauTranslator.get_asset_spec(...).key` instead", + ) def get_sheet_asset_key(self, data: TableauContentData) -> AssetKey: return self.get_sheet_spec(data).key @@ -166,7 +169,10 @@ def get_sheet_spec(self, data: TableauContentData) -> AssetSpec: }, ) - @deprecated(breaking_version="1.10") + @deprecated( + breaking_version="1.10", + additional_warn_text="Use `DagsterTableauTranslator.get_asset_spec(...).key` instead", + ) def get_dashboard_asset_key(self, data: TableauContentData) -> AssetKey: return self.get_dashboard_spec(data).key @@ -200,7 +206,10 @@ def get_dashboard_spec(self, data: TableauContentData) -> AssetSpec: }, ) - @deprecated(breaking_version="1.10") + @deprecated( + breaking_version="1.10", + additional_warn_text="Use `DagsterTableauTranslator.get_asset_spec(...).key` instead", + ) def get_data_source_asset_key(self, data: TableauContentData) -> AssetKey: return self.get_data_source_spec(data).key From 126c4d7a1eca3b048c4cf722f5cb511d9985bc69 Mon Sep 17 00:00:00 2001 From: Marco Salazar Date: Thu, 5 Dec 2024 11:46:00 -0500 Subject: [PATCH 06/13] . --- .../deployment/code-locations/index.md | 240 ++++++++++ .../deployment/dagster-plus-settings.md | 7 + .../deployment/deployment-settings.md | 9 + .../environment-variables/index.mdx | 12 + .../deployment/hybrid/agents/index.mdx | 11 + .../dagster-plus/deployment/hybrid/index.md | 65 +++ .../deployment/migration/index.mdx | 11 + .../migration/self-hosted-to-dagster-plus.md | 5 + .../dagster-plus/deployment/multi-tenancy.md | 7 + .../deployment/serverless/index.md | 43 ++ .../deployment/user-agent-tokens.md | 8 + .../docs/dagster-plus/features/alerts/cli.md | 7 + .../dagster-plus/features/alerts/email.md | 7 + .../dagster-plus/features/alerts/index.md | 322 +++++++++++++ .../features/alerts/microsoft-teams.md | 8 + .../dagster-plus/features/alerts/pagerduty.md | 8 + .../dagster-plus/features/alerts/slack.md | 8 + .../docs/dagster-plus/features/alerts/ui.md | 8 + .../index.mdx | 11 + .../rbac/audit-logs.md | 68 +++ .../rbac/index.mdx | 11 + .../rbac/teams.md | 78 +++ .../rbac/user-roles-permissions.md | 211 +++++++++ .../rbac/users.md | 93 ++++ .../scim/azure-active-directory.md | 10 + .../scim/index.mdx | 11 + .../scim/okta-scim.md | 8 + .../sso/authentication.md | 8 + .../sso/azure-ad-sso.md | 96 ++++ .../sso/google-workspace-sso.md | 111 +++++ .../sso/index.mdx | 11 + .../sso/okta-sso.md | 95 ++++ .../sso/onelogin-sso.md | 92 ++++ .../sso/pingone-sso.md | 121 +++++ .../branch-deployments/change-tracking.md | 9 + .../branch-deployments/dagster-cloud-cli.md | 9 + .../features/branch-deployments/index.mdx | 11 + .../setting-up-branch-deployments.md | 448 ++++++++++++++++++ .../features/branch-deployments/testing.md | 7 + .../dagster-plus/features/data-catalog.md | 7 + .../features/insights/asset-metadata.md | 58 +++ .../features/insights/export-metrics.md | 8 + .../features/insights/google-bigquery.md | 76 +++ .../dagster-plus/features/insights/index.md | 72 +++ .../features/insights/snowflake.md | 84 ++++ .../docs/dagster-plus/features/saved-views.md | 69 +++ docs/docs-beta/docs/dagster-plus/index.md | 37 ++ .../docs/getting-started/glossary.md | 19 + .../docs/guides/automate/about-automation.md | 67 +++ .../docs/guides/automate/asset-sensors.md | 105 ++++ .../guides/automate/declarative-automation.md | 6 + docs/docs-beta/docs/guides/automate/index.md | 237 +++++++++ .../docs/guides/automate/schedules.md | 64 +++ .../docs-beta/docs/guides/automate/sensors.md | 81 ++++ .../assets-concepts/asset-dependencies.md | 119 +++++ .../asset-factories-with-deps.md | 36 ++ .../assets-concepts/asset-materialization.md | 7 + .../build/assets-concepts/asset-metadata.md | 7 + .../guides/build/assets-concepts/index.md | 11 + .../build/assets-concepts/selection-syntax.md | 352 ++++++++++++++ docs/docs-beta/docs/guides/build/backfill.md | 6 + .../docs/guides/build/configure/apis.md | 70 +++ .../guides/build/configure/asset-factories.md | 72 +++ .../guides/build/configure/authentication.md | 5 + .../build/configure/configuring-assets.md | 48 ++ .../docs/guides/build/configure/databases.md | 63 +++ .../docs/guides/build/configure/index.mdx | 9 + .../guides/build/configure/io-managers.md | 88 ++++ .../build/configure/managing-concurrency.md | 172 +++++++ .../docs/guides/build/configure/resources.md | 8 + .../build/create-a-pipeline/data-assets.md | 76 +++ .../create-a-pipeline/external-assets.md | 111 +++++ .../guides/build/create-a-pipeline/index.md | 55 +++ .../build/create-a-pipeline/metadata.md | 160 +++++++ .../partition-dependencies.md | 82 ++++ .../build/create-a-pipeline/partitioning.md | 70 +++ docs/docs-beta/docs/guides/build/index.md | 7 + .../guides/build/integrate/build-your-own.md | 5 + .../guides/build/integrate/cloud-services.md | 5 + .../docs/guides/build/integrate/index.mdx | 8 + .../guides/build/integrate/ingesting-data.md | 52 ++ .../docs/guides/build/integrate/non-python.md | 84 ++++ .../docs/guides/build/integrate/pipes.md | 38 ++ .../guides/build/integrate/transform-dbt.md | 78 +++ .../docs/guides/build/ops-jobs/index.md | 10 + .../build/ops-jobs/job-configuration.md | 7 + .../guides/build/ops-jobs/ops-vs-assets.md | 7 + .../docs/guides/build/project-structure.md | 157 ++++++ .../guides/deploy/code-locations/index.mdx | 8 + .../code-locations/managing-code-locations.md | 6 + .../deploy/code-locations/workspace-yaml.md | 120 +++++ .../docs/guides/deploy/dagster-yaml.md | 346 ++++++++++++++ .../deployment-options/amazon-web-services.md | 5 + .../deployment-options/dagster-service.md | 118 +++++ .../deploy/deployment-options/docker.md | 175 +++++++ .../google-cloud-platform.md | 5 + .../deploy/deployment-options/index.mdx | 8 + .../deploy/deployment-options/kubernetes.md | 201 ++++++++ .../deployment-options/microsoft-azure.md | 5 + .../running-local-ui-development.md | 77 +++ .../guides/deploy/execution/dagster-daemon.md | 7 + .../docs/guides/deploy/execution/index.mdx | 8 + .../deploy/execution/run-coordinators.md | 7 + .../guides/deploy/execution/run-executors.md | 7 + .../guides/deploy/execution/run-launchers.md | 7 + docs/docs-beta/docs/guides/deploy/index.md | 15 + docs/docs-beta/docs/guides/deploy/secrets.md | 5 + .../docs-beta/docs/guides/monitor/alerting.md | 13 + docs/docs-beta/docs/guides/monitor/index.md | 7 + .../guides/monitor/logging/custom-logging.md | 136 ++++++ .../monitor/logging/custom-metrics-logs.md | 5 + .../docs/guides/monitor/logging/index.mdx | 8 + .../docs/guides/test/asset-checks.md | 84 ++++ .../guides/test/data-freshness-testing.md | 81 ++++ docs/docs-beta/docs/guides/test/index.md | 7 + .../guides/test/unit-tests-assets-and-ops.md | 111 +++++ .../experimental/dagster-components/LICENSE | 201 ++++++++ .../dagster-components/MANIFEST.in | 3 + .../experimental/dagster-components/README.md | 4 + .../dagster_components/__init__.py | 17 + .../dagster_components/cli/__init__.py | 28 ++ .../dagster_components/cli/generate.py | 108 +++++ .../dagster_components/core/__init__.py | 0 .../dagster_components/core/component.py | 90 ++++ .../core/component_decl_builder.py | 50 ++ .../core/component_defs_builder.py | 91 ++++ .../dagster_components/core/deployment.py | 163 +++++++ .../dagster_components/core/registry.py | 0 .../dagster_components/generate.py | 61 +++ .../dagster_components/impls/__init__.py | 0 .../pipes_subprocess_script_collection.py | 98 ++++ .../impls/sling_replication.py | 48 ++ .../__init__.py | 0 .../components/.gitkeep | 0 .../definitions.py | 9 + .../lib/__init__.py | 0 .../__init__.py | 0 .../pyproject.toml.jinja | 19 + .../defs.yml.jinja | 1 + .../COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja | 16 + .../workflows/dagster-cloud-deploy.yaml.jinja | 0 .../code_locations/.gitkeep | 0 .../dagster_cloud.yaml.jinja | 0 .../dagster_components/version.py | 1 + .../dagster_components_tests/__init__.py | 0 .../cli_tests/test_generate_commands.py | 220 +++++++++ .../python_script_location/__init__.py | 0 .../components/scripts/defs.yml | 15 + .../components/scripts/script_one.py | 6 + .../components/scripts/script_two.py | 6 + .../components/scripts/subdir/script_three.py | 0 .../sling_location/components/ingest/defs.yml | 7 + .../components/ingest/replication.yaml | 14 + .../sling_location/input.csv | 4 + ...test_pipes_subprocess_script_collection.py | 83 ++++ .../test_sling_replication.py | 91 ++++ .../dagster_components_tests/utils.py | 37 ++ .../experimental/dagster-components/setup.cfg | 9 + .../experimental/dagster-components/setup.py | 50 ++ .../experimental/dagster-components/tox.ini | 22 + 160 files changed, 8534 insertions(+) create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/code-locations/index.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/dagster-plus-settings.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/deployment-settings.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/environment-variables/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/hybrid/agents/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/hybrid/index.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/migration/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/migration/self-hosted-to-dagster-plus.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/multi-tenancy.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/serverless/index.md create mode 100644 docs/docs-beta/docs/dagster-plus/deployment/user-agent-tokens.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/cli.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/email.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/index.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/microsoft-teams.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/pagerduty.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/slack.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/alerts/ui.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/audit-logs.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/teams.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/users.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/azure-active-directory.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/okta-scim.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/authentication.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/azure-ad-sso.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/google-workspace-sso.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/okta-sso.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/onelogin-sso.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/pingone-sso.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/branch-deployments/change-tracking.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/branch-deployments/dagster-cloud-cli.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/branch-deployments/index.mdx create mode 100644 docs/docs-beta/docs/dagster-plus/features/branch-deployments/setting-up-branch-deployments.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/branch-deployments/testing.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/data-catalog.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/insights/asset-metadata.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/insights/export-metrics.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/insights/google-bigquery.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/insights/index.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/insights/snowflake.md create mode 100644 docs/docs-beta/docs/dagster-plus/features/saved-views.md create mode 100644 docs/docs-beta/docs/dagster-plus/index.md create mode 100644 docs/docs-beta/docs/getting-started/glossary.md create mode 100644 docs/docs-beta/docs/guides/automate/about-automation.md create mode 100644 docs/docs-beta/docs/guides/automate/asset-sensors.md create mode 100644 docs/docs-beta/docs/guides/automate/declarative-automation.md create mode 100644 docs/docs-beta/docs/guides/automate/index.md create mode 100644 docs/docs-beta/docs/guides/automate/schedules.md create mode 100644 docs/docs-beta/docs/guides/automate/sensors.md create mode 100644 docs/docs-beta/docs/guides/build/assets-concepts/asset-dependencies.md create mode 100644 docs/docs-beta/docs/guides/build/assets-concepts/asset-factories-with-deps.md create mode 100644 docs/docs-beta/docs/guides/build/assets-concepts/asset-materialization.md create mode 100644 docs/docs-beta/docs/guides/build/assets-concepts/asset-metadata.md create mode 100644 docs/docs-beta/docs/guides/build/assets-concepts/index.md create mode 100644 docs/docs-beta/docs/guides/build/assets-concepts/selection-syntax.md create mode 100644 docs/docs-beta/docs/guides/build/backfill.md create mode 100644 docs/docs-beta/docs/guides/build/configure/apis.md create mode 100644 docs/docs-beta/docs/guides/build/configure/asset-factories.md create mode 100644 docs/docs-beta/docs/guides/build/configure/authentication.md create mode 100644 docs/docs-beta/docs/guides/build/configure/configuring-assets.md create mode 100644 docs/docs-beta/docs/guides/build/configure/databases.md create mode 100644 docs/docs-beta/docs/guides/build/configure/index.mdx create mode 100644 docs/docs-beta/docs/guides/build/configure/io-managers.md create mode 100644 docs/docs-beta/docs/guides/build/configure/managing-concurrency.md create mode 100644 docs/docs-beta/docs/guides/build/configure/resources.md create mode 100644 docs/docs-beta/docs/guides/build/create-a-pipeline/data-assets.md create mode 100644 docs/docs-beta/docs/guides/build/create-a-pipeline/external-assets.md create mode 100644 docs/docs-beta/docs/guides/build/create-a-pipeline/index.md create mode 100644 docs/docs-beta/docs/guides/build/create-a-pipeline/metadata.md create mode 100644 docs/docs-beta/docs/guides/build/create-a-pipeline/partition-dependencies.md create mode 100644 docs/docs-beta/docs/guides/build/create-a-pipeline/partitioning.md create mode 100644 docs/docs-beta/docs/guides/build/index.md create mode 100644 docs/docs-beta/docs/guides/build/integrate/build-your-own.md create mode 100644 docs/docs-beta/docs/guides/build/integrate/cloud-services.md create mode 100644 docs/docs-beta/docs/guides/build/integrate/index.mdx create mode 100644 docs/docs-beta/docs/guides/build/integrate/ingesting-data.md create mode 100644 docs/docs-beta/docs/guides/build/integrate/non-python.md create mode 100644 docs/docs-beta/docs/guides/build/integrate/pipes.md create mode 100644 docs/docs-beta/docs/guides/build/integrate/transform-dbt.md create mode 100644 docs/docs-beta/docs/guides/build/ops-jobs/index.md create mode 100644 docs/docs-beta/docs/guides/build/ops-jobs/job-configuration.md create mode 100644 docs/docs-beta/docs/guides/build/ops-jobs/ops-vs-assets.md create mode 100644 docs/docs-beta/docs/guides/build/project-structure.md create mode 100644 docs/docs-beta/docs/guides/deploy/code-locations/index.mdx create mode 100644 docs/docs-beta/docs/guides/deploy/code-locations/managing-code-locations.md create mode 100644 docs/docs-beta/docs/guides/deploy/code-locations/workspace-yaml.md create mode 100644 docs/docs-beta/docs/guides/deploy/dagster-yaml.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/amazon-web-services.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/dagster-service.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/docker.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/google-cloud-platform.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/index.mdx create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/kubernetes.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/microsoft-azure.md create mode 100644 docs/docs-beta/docs/guides/deploy/deployment-options/running-local-ui-development.md create mode 100644 docs/docs-beta/docs/guides/deploy/execution/dagster-daemon.md create mode 100644 docs/docs-beta/docs/guides/deploy/execution/index.mdx create mode 100644 docs/docs-beta/docs/guides/deploy/execution/run-coordinators.md create mode 100644 docs/docs-beta/docs/guides/deploy/execution/run-executors.md create mode 100644 docs/docs-beta/docs/guides/deploy/execution/run-launchers.md create mode 100644 docs/docs-beta/docs/guides/deploy/index.md create mode 100644 docs/docs-beta/docs/guides/deploy/secrets.md create mode 100644 docs/docs-beta/docs/guides/monitor/alerting.md create mode 100644 docs/docs-beta/docs/guides/monitor/index.md create mode 100644 docs/docs-beta/docs/guides/monitor/logging/custom-logging.md create mode 100644 docs/docs-beta/docs/guides/monitor/logging/custom-metrics-logs.md create mode 100644 docs/docs-beta/docs/guides/monitor/logging/index.mdx create mode 100644 docs/docs-beta/docs/guides/test/asset-checks.md create mode 100644 docs/docs-beta/docs/guides/test/data-freshness-testing.md create mode 100644 docs/docs-beta/docs/guides/test/index.md create mode 100644 docs/docs-beta/docs/guides/test/unit-tests-assets-and-ops.md create mode 100644 examples/experimental/dagster-components/LICENSE create mode 100644 examples/experimental/dagster-components/MANIFEST.in create mode 100644 examples/experimental/dagster-components/README.md create mode 100644 examples/experimental/dagster-components/dagster_components/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/cli/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/cli/generate.py create mode 100644 examples/experimental/dagster-components/dagster_components/core/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/core/component.py create mode 100644 examples/experimental/dagster-components/dagster_components/core/component_decl_builder.py create mode 100644 examples/experimental/dagster-components/dagster_components/core/component_defs_builder.py create mode 100644 examples/experimental/dagster-components/dagster_components/core/deployment.py create mode 100644 examples/experimental/dagster-components/dagster_components/core/registry.py create mode 100644 examples/experimental/dagster-components/dagster_components/generate.py create mode 100644 examples/experimental/dagster-components/dagster_components/impls/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/impls/pipes_subprocess_script_collection.py create mode 100644 examples/experimental/dagster-components/dagster_components/impls/sling_replication.py create mode 100644 examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/components/.gitkeep create mode 100644 examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py create mode 100644 examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/lib/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER_tests/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja create mode 100644 examples/experimental/dagster-components/dagster_components/templates/COMPONENT_INSTANCE_NAME_PLACEHOLDER/defs.yml.jinja create mode 100644 examples/experimental/dagster-components/dagster_components/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja create mode 100644 examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/.github/workflows/dagster-cloud-deploy.yaml.jinja create mode 100644 examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/code_locations/.gitkeep create mode 100644 examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/dagster_cloud.yaml.jinja create mode 100644 examples/experimental/dagster-components/dagster_components/version.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/cli_tests/test_generate_commands.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/__init__.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/defs.yml create mode 100644 examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_one.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_two.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/subdir/script_three.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/defs.yml create mode 100644 examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/replication.yaml create mode 100644 examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/input.csv create mode 100644 examples/experimental/dagster-components/dagster_components_tests/test_pipes_subprocess_script_collection.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/test_sling_replication.py create mode 100644 examples/experimental/dagster-components/dagster_components_tests/utils.py create mode 100644 examples/experimental/dagster-components/setup.cfg create mode 100644 examples/experimental/dagster-components/setup.py create mode 100644 examples/experimental/dagster-components/tox.ini diff --git a/docs/docs-beta/docs/dagster-plus/deployment/code-locations/index.md b/docs/docs-beta/docs/dagster-plus/deployment/code-locations/index.md new file mode 100644 index 0000000000000..ad60593d0bfb4 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/code-locations/index.md @@ -0,0 +1,240 @@ +--- +title: "Code locations" +displayed_sidebar: "dagsterPlus" +sidebar_position: 50 +--- + +# Code locations + +Separate code locations allow you to deploy different projects that still roll up into a single Dagster+ deployment with one global lineage graph. + +This guide will cover three options for adding a new code location: +- Adding a code location manually +- Adding a code location in a new Git repository +- Adding a new code location to an existing Git monorepo + +
    +Prerequisites + +1. An existing Dagster project. Refer to the [recommended project structure](/tutorial/create-new-project) and [code requirements](/dagster-plus/deployment/code-requirements) pages for more information. + +2. Editor, Admin, or Organization Admin permissions in Dagster+. + +3. To know your Dagster+ deployment type. An administrator can help find this information, or you can locate it by clicking *Deployment > Agents tab* in the Dagster UI. Dagster+ Serverless organizations will have a *Managed by Dagster+* label next to the agent. + +
    + +Adding a code location follows two steps: +- For Dagster+ Hybrid, ensuring the Dagster code is in a place accessible by your agent, usually by building a Docker image with your code that's pushed to a registry. For Dagster+ Serverless you can skip this step. +- Notifying Dagster+ of the new or updated code location. This will be done by using the Dagster+ Python client. + +Often these two steps are handled by CI/CD connected to your Git repository. + + +## Add a new code location manually + +Start by installing the `dagster-cloud` Python client: + +``` +pip install dagster-cloud +``` + +Next you will want need to authenticate this Python client: + +1. In the Dagster+ UI, click the user icon in the upper right corner. +2. Click **Organization settings**, then the **Tokens** tab. +3. Click the **Create user token** button. +4. Copy the token. +5. Set the following environment variables: + + ```bash + export DAGSTER_CLOUD_ORGANIZATION="organization-name" # if your URL is https://acme.dagster.plus your organization name is "acme" + export DAGSTER_CLOUD_API_TOKEN="your-token" + ``` + +Now add the code location. The following example assumes you are running the command from the top-level working directory of your Dagster project with a project named "quickstart" structured as a Python module named "quickstart". + +```bash +/quickstart + setup.py + pyproject.toml + /quickstart + __init__.py + /assets + /resources +``` + +The commands below take two main arguments: +- `module_name` is determined by your code structure +- `location_name` is the unique label for this code location used in Dagster+ + + + + +If you are using Dagster+ Serverless, run the following command to add a code location: + +```bash +dagster-cloud serverless deploy-python-executable --deployment prod --location-name quickstart --module-name quickstart +``` + +Running the command multiple times with the same location name will *update* the code location. Running the command with a new location name will *add* a code location. + + + +If you are using Dagster+ Hybrid, make sure you have deployed the code appropriately by [building a Docker image and pushing it to an image registry](https://github.com/dagster-io/dagster-cloud-hybrid-quickstart). Then run this command, using the image URI which is available from your registry: + +```bash +dagster-cloud deployment add-location --deployment prod --location-name quickstart --module-name quickstart --image 764506304434.dkr.ecr.us-west-2.amazonaws.com/hooli-data-science-prod:latest +``` + + + +After running the command you can verify the code location was deployed by navigating to the *Deployments* tab on Dagster+. + +## Adding a code location in a new Git repository + +Adding a code location to a Git repository follows the same steps as adding a code location manually, but automates those steps by running them through CI/CD. + +To get started, review the appropriate example repository and then create your Git repository with the same structure. + +- [GitHub repository with Dagster+ Serverless](https://github.com/dagster-io/dagster-cloud-serverless-quickstart/) +- [GitHub repository with Dagster+ Hybrid](https://github.com/dagster-io/dagster-cloud-hybrid-quickstart/) +- [GitLab CI/CD for Dagster+ Serverless](https://github.com/dagster-io/dagster-cloud-action/blob/main/gitlab/serverless-ci.yml) +- [GitLab CI/CD for Dagster+ Hybrid](https://github.com/dagster-io/dagster-cloud-action/blob/main/gitlab/hybrid-ci.yml) + + +Overall, the Git repository should contain: + +1. Your Dagster code, structured as a Python module. For Dagter+ Hybrid you may need a [Dockerfile](https://github.com/dagster-io/dagster-cloud-hybrid-quickstart/blob/main/Dockerfile) as well. The repository might look like this: + + ```bash + README.md + dagster_cloud.yaml + Dockerfile + /.github + /workflows + dagster-cloud-deploy.yml + setup.py + pyproject.toml + /quickstart + __init__.py + definitions.py + /assets + ... + /resources + ... + ``` + +2. A [`dagster_cloud.yaml` file](/todo) with the settings for your code location. Here is an example: + + ```yaml title="dagster_cloud.yaml + locations: + - location_name: quickstart + code_source: + package_name: quickstart + ``` + +3. A CI/CD workflow file that contains the steps for adding your code location. These are the same steps outlined in the preceding section. Here is a minimal example workflow file for a Dagster+ Hybrid organization based on [this GitLab template](https://github.com/dagster-io/dagster-cloud-action/blob/main/gitlab/hybrid-ci.yml). + + ```yaml + variables: + DAGSTER_CLOUD_ORGANIZATION: + DAGSTER_PROJECT_DIR: . + IMAGE_REGISTRY: .dkr.ecr.us-west-2.amazonaws.com/ + IMAGE_TAG: $CI_COMMIT_SHORT_SHA-$CI_PIPELINE_ID + + stages: + - build + - deploy + + build: + stage: build + image: docker:latest + services: + - docker:dind + before_script: + # # For Gitlab Container Registry + # - echo $CI_JOB_TOKEN | docker login --username $CI_REGISTRY_USER --password-stdin $REGISTRY_URL + # # For DockerHub + # - echo $DOCKERHUB_TOKEN | docker login --username $DOCKERHUB_USERNAME --password-stdin $REGISTRY_URL + # # For AWS Elastic Container Registry (ECR) + # - apk add --no-cache curl jq python3 py3-pip + # - pip install awscli + # - echo $AWS_ECR_PASSWORD | docker login --username AWS --password-stdin $IMAGE_REGISTRY + # # For Google Container Registry (GCR) + # - echo $GCR_JSON_KEY | docker login --username _json_key --password-stdin $REGISTRY_URL + script: + - docker build . -t $IMAGE_REGISTRY:$IMAGE_TAG + - docker push $IMAGE_REGISTRY:$IMAGE_TAG + + deploy: + stage: deploy + dependencies: + - build + image: ghcr.io/dagster-io/dagster-cloud-action:0.1.43 + script: + - dagster-cloud deployment add-location --deployment prod --image + $IMAGE_REGISTRY:$IMAGE_TAG --location-name quickstart --package-name quickstart + ``` + +Once your Git repository has this structure, you will want to run your CI/CD process. The CI/CD process will add the code location to Dagster+ which can be verified by viewing the *Deployments* tab. + +## Adding a new code location to a Git monorepo + +Many organizations use a Git monorepo to contain multiple Dagster projects. Here is an example of DagsterLab's own [internal data engineering Git repository](https://github.com/dagster-io/dagster-open-platform). + +To add a new code location to a monorepo, create a new directory that contains your Dagster project. The final repository structure might look like this: + +``` +README.md +dagster_cloud.yaml +/.github + ... +/shared + setup.py + pyproject.toml + /shared + __init__.py + utilities.py +/core + setup.py + pyproject.toml + Dockerfile + /core + definitions.py + __init__.py + /assets +/new-code-location + setup.py + pyproject.toml + Dockerfile + /new-code-location + definitions.py + __init__.py + /assets +``` + +Then update the `dagster_cloud.yaml` file in the root of the Git repository, adding a location section for your project including the location name, code source, and build directory. For Dagster+ Hybrid, include the registry. If you don't know the registry, consult your administrator or the team that set up CI/CD for the Git repository. + +```yaml +locations: + - location_name: core + code_source: + package_name: core + build: + directory: ./core + registry: your-registry/image # eg 764506304434.dkr.ecr.us-west-2.amazonaws.com/core + - location_name: new + code_source: + package_name: new + build: + directory: ./new + registry: your-registry/image # eg 764506304434.dkr.ecr.us-west-2.amazonaws.com/new +``` + +The monorepo should have CI/CD configured to deploy your changes and add or update your new code location. After adding your code and updating the `dagster_cloud.yaml` file, trigger the CI/CD process to add your code location to Dagster+. Navigate to the *Deployments* tab in Dagster+ to confirm your code location was added. + +## Next steps + +- After adding a code location, you may want to setup access controls +- You may want to add additional configuration to your code location. This configuration will vary by agent type, but see examples for [setting default resource limits for Kubernetes](/dagster-plus/deployment/hybrid/agents/kubernetes) or [changing the IAM role for ECS](/todo). diff --git a/docs/docs-beta/docs/dagster-plus/deployment/dagster-plus-settings.md b/docs/docs-beta/docs/dagster-plus/deployment/dagster-plus-settings.md new file mode 100644 index 0000000000000..0d7330cf5a6a9 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/dagster-plus-settings.md @@ -0,0 +1,7 @@ +--- +title: "Dagster+ settings" +unlisted: true +sidebar_position: 200 +--- + +# Dagster+ settings diff --git a/docs/docs-beta/docs/dagster-plus/deployment/deployment-settings.md b/docs/docs-beta/docs/dagster-plus/deployment/deployment-settings.md new file mode 100644 index 0000000000000..bbfa62beba985 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/deployment-settings.md @@ -0,0 +1,9 @@ +--- +title: "Deployment settings" +displayed_sidebar: "dagsterPlus" +sidebar_label: "Deployment settings" +unlisted: true +sidebar_position: 300 +--- + +# Deployment settings diff --git a/docs/docs-beta/docs/dagster-plus/deployment/environment-variables/index.mdx b/docs/docs-beta/docs/dagster-plus/deployment/environment-variables/index.mdx new file mode 100644 index 0000000000000..6184b57ef8d88 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/environment-variables/index.mdx @@ -0,0 +1,12 @@ +--- +title: "Environment variables" +displayed_sidebar: "dagsterPlus" +unlisted: true +sidebar_position: 40 +--- + +# Environment variables + +import DocCardList from '@theme/DocCardList'; + + diff --git a/docs/docs-beta/docs/dagster-plus/deployment/hybrid/agents/index.mdx b/docs/docs-beta/docs/dagster-plus/deployment/hybrid/agents/index.mdx new file mode 100644 index 0000000000000..2bd0168cc8167 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/hybrid/agents/index.mdx @@ -0,0 +1,11 @@ +--- +title: "Agents" +displayed_sidebar: "dagsterPlus" +sidebar_class_name: hidden +--- + +# Agents + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/deployment/hybrid/index.md b/docs/docs-beta/docs/dagster-plus/deployment/hybrid/index.md new file mode 100644 index 0000000000000..5a7836ad79bcd --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/hybrid/index.md @@ -0,0 +1,65 @@ +--- +title: "Hybrid deployment" +displayed_sidebar: "dagsterPlus" +sidebar_position: 20 +--- + +# Hybrid deployment + +In a Dagster+ Hybrid deployment, the orchestration control plane is run by Dagster+ while your Dagster code is executed within your environment. + +[comment]: <> (TODO: Architecture diagram) + +## Get started + +To get started with a Hybrid deployment you'll need to: + +1. Create a [Dagster+ organization](https://dagster.cloud/signup) +2. Install a Dagster+ Hybrid Agent +3. [Add a code location](/dagster-plus/deployment/code-locations), typically using a Git repository and CI/CD + +## Dagster+ Hybrid agents + +The Dagster+ agent is a long-lived process that polls Dagster+'s API servers for new work. + +See the following guides for setting up an agent: + - [Kubernetes](/dagster-plus/deployment/hybrid/agents/kubernetes) + - [AWS ECS](/dagster-plus/deployment/hybrid/agents/amazon-ecs-new-vpc) + - [Docker](/dagster-plus/deployment/hybrid/agents/docker) + - [Locally](/dagster-plus/deployment/hybrid/agents/local) + + +## What you'll see in your environment + +### Code location servers + +Dagster+ runs your Dagster projects through code locations. To get started, follow this guide for [adding a code location](/dagster-plus/deployment/code-locations). + +When you inform Dagster+ about a new code location, we enqueue instructions for your agent to launch a new code server. The agent uses your container image to launch a code server that interacts with your Dagster definitions. The agent will run one long-standing code server for each code location. Once the code server is running, the agent will send Dagster+ metadata about your Dagster definitions that Dagster+ uses to make orchestration decisions. + + +### Runs + +Your definitions might include [automations](/guides/automate) that launch runs or materialize assets. Or your developers might launch runs directly with the web UI. + +When a run needs to be launched, Dagster+ enqueues instructions for your agent to launch a new run. The next time your agent polls Dagster+ for new work, it will see instructions about how to launch your run. It will delegate those instructions to your code server and your code server will launch a run - a new run will typically require its own container. + +Your agent will send Dagster+ metadata letting us know the run has been launched. Your run's container will also send Dagster+ metadata informing us of how the run is progressing. The Dagster+ backend services will monitor this stream of metadata to make additional orchestration decisions, monitor for failure, or send alerts. + +## Security + +Dagster+ hybrid relies on a shared security model. + +The Dagster+ control plane is SOC 2 Type II certified and follows best practices such as: +- encrypting data at rest (AES 256) and in transit (TLS 1.2+) +- highly available, with disaster recovery and backup strategies +- only manages metadata such as pipeline names, execution status, and run duration + +The execution environment is managed by the customer: +- your code never leaves your environment +- all connections to databases, file systems, and other resources are made from your environment +- the execution environment only requires egress access to Dagster+ + +Common security considerations in Dagster+ hybrid include: +- [disabling log forwarding](/todo) +- [managing tokens](/todo) diff --git a/docs/docs-beta/docs/dagster-plus/deployment/migration/index.mdx b/docs/docs-beta/docs/dagster-plus/deployment/migration/index.mdx new file mode 100644 index 0000000000000..83ccdabe3b421 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/migration/index.mdx @@ -0,0 +1,11 @@ +--- +title: Migration +displayed_sidebar: "dagsterPlus" +sidebar_position: 30 +--- + +# Migration + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/deployment/migration/self-hosted-to-dagster-plus.md b/docs/docs-beta/docs/dagster-plus/deployment/migration/self-hosted-to-dagster-plus.md new file mode 100644 index 0000000000000..daee67878b339 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/migration/self-hosted-to-dagster-plus.md @@ -0,0 +1,5 @@ +--- +title: "Migrate from self-hosted to Dagster+" +sidebar_position: 100 +unlisted: true +--- diff --git a/docs/docs-beta/docs/dagster-plus/deployment/multi-tenancy.md b/docs/docs-beta/docs/dagster-plus/deployment/multi-tenancy.md new file mode 100644 index 0000000000000..28b41d6d7f9d3 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/multi-tenancy.md @@ -0,0 +1,7 @@ +--- +title: "Multi-tenancy" +unlisted: true +sidebar_position: 500 +--- + +# Dagster+ multi-tenancy diff --git a/docs/docs-beta/docs/dagster-plus/deployment/serverless/index.md b/docs/docs-beta/docs/dagster-plus/deployment/serverless/index.md new file mode 100644 index 0000000000000..0684a378be624 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/serverless/index.md @@ -0,0 +1,43 @@ +--- +title: 'Serverless deployment' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 10 +--- + +# Serverless deployment + +Dagster+ Serverless is a fully managed version of Dagster+ and is the easiest way to get started with Dagster. With a Serverless deployment, you can run your Dagster jobs without spinning up any infrastructure yourself. + +--- + +## When to choose Serverless \{#when-to-choose-serverless} + +Serverless works best with workloads that primarily orchestrate other services or perform light computation. Most workloads fit into this category, especially those that orchestrate third-party SaaS products like cloud data warehouses and ETL tools. + +If any of the following are applicable, you should select [Hybrid deployment](/dagster-plus/deployment/hybrid): + +- You require substantial computational resources. For example, training a large machine learning (ML) model in-process +- Your dataset is too large to fit in memory. For example, training a large ML model in-process on a terabyte of data +- You need to distribute computation across many nodes for a single run. Dagster+ runs currently execute on a single node with 4 CPUs +- You don't want to add Dagster Labs as a data processor + +--- + +## Limitations \{#limitations} + +Serverless is subject to the following limitations: + +- Maximum of 100 GB of bandwidth per day +- Maximum of 4500 step-minutes per day +- Runs receive 4 vCPU cores, 16 GB of RAM, and 128 GB of ephemeral disk +- Code locations receive 0.25 vCPU cores and 1 GB of RAM +- All Serverless jobs run in the United States +- Infrastructure cannot be customized or extended, such as using additional containers + +Dagster+ Pro customers may request a quota increase by [contacting Sales](https://dagster.io/contact). + +--- + +## Next steps + +To start using Dagster+ Serverless, follow our [Getting started with Dagster+](/dagster-plus/getting-started) guide. diff --git a/docs/docs-beta/docs/dagster-plus/deployment/user-agent-tokens.md b/docs/docs-beta/docs/dagster-plus/deployment/user-agent-tokens.md new file mode 100644 index 0000000000000..8a1b94d891046 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/deployment/user-agent-tokens.md @@ -0,0 +1,8 @@ +--- +title: "Tokens" +displayed_sidebar: "dagsterPlus" +unlisted: true +sidebar_position: 600 +--- + +# Managing user and agent tokens in Dagster+ diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/cli.md b/docs/docs-beta/docs/dagster-plus/features/alerts/cli.md new file mode 100644 index 0000000000000..71e28ce328c5e --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/cli.md @@ -0,0 +1,7 @@ +--- +title: "Dagster+ alerts with the CLI" +unlisted: true +sidebar_position: 200 +--- + +# Alerts with the CLI diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/email.md b/docs/docs-beta/docs/dagster-plus/features/alerts/email.md new file mode 100644 index 0000000000000..2b516c6b73bac --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/email.md @@ -0,0 +1,7 @@ +--- +title: "Dagster+ email alerts" +unlisted: true +sidebar_position: 300 +--- + +# Dagster+ email alerts diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/index.md b/docs/docs-beta/docs/dagster-plus/features/alerts/index.md new file mode 100644 index 0000000000000..b869009c354d0 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/index.md @@ -0,0 +1,322 @@ +--- +title: Setting up alerts on Dagster+ +sidebar_label: "Dagster+ Alerts" +sidebar_position: 30 +--- +[comment]: <> (This file is automatically generated by `dagster-plus/deployment/alerts/generate_alerts_doc.py`) + +Dagster+ allows you to configure alerts to automatically fire in response to a range of events. These alerts can be sent to a variety of different services, depending on your organization's needs. + +These alerts can be configured in the Dagster+ UI, or using the `dagster-cloud` CLI tool. + +
    +Prerequisites +- **Organization**, **Admin**, or **Editor** permissions on Dagster+ +
    + +## Configuring a notification service + +To start, you'll need to configure a service to send alerts. Dagster+ current supports sending alerts through email, Microsoft Teams, PagerDuty, and Slack. + + + + No additional configuration is required to send emails from Dagster+. + +All alert emails will be sent by `"no-reply@dagster.cloud"` or `"no-reply@.dagster.cloud"`. Alerts can be configured to be sent to any number of emails. + + + Create an incoming webhook by following the [Microsoft Teams documentation](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook?tabs=newteams%2Cdotnet). + +This will provide you with a **webhook URL** which will be required when configuring alerts in the UI (after selecting "Microsoft Teams" as your Notification Service) or using the CLI (in the `notification_service` configuration). + + + + :::note +You will need sufficient permissions in PagerDuty to add or edit services. +::: + +In PagerDuty, you can either: + +- [Create a new service](https://support.pagerduty.com/main/docs/services-and-integrations#create-a-service), and add Dagster+ as an integration, or +- [Edit an existing service](https://support.pagerduty.com/main/docs/services-and-integrations#edit-service-settings) to include Dagster+ as an integration + +When configuring the integration, choose **Dagster+** as the integration type, and choose an integration name in the format `dagster-plus-{your_service_name}`. + +After adding your new integration, you will be taken to a screen containing an **Integration Key**. This value will be required when configuring alerts in the UI (after selecting "PagerDuty" as your Notification Service) or using the CLI (in the `notification_service` configuration). + + + + :::note +You will need sufficient permissions in Slack to add apps to your workspace. +::: +Navigate to **Deployment > Alerts** in the Dagster+ UI and click **Connect to Slack**. From there, you can complete the installation process. + +When setting up an alert, you can choose a Slack channel to send those alerts to. Make sure to invite the `@Dagster+` bot to any channel that you'd like to receive an alert in. + + + + +## Alerting when a run fails +You can set up alerts to notify you when a run fails. + +By default, these alerts will target all runs in the deployment, but they can be scoped to runs with a specific tag. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Run alert** from the dropdown. + +5. Select **Job failure**. + +If desired, add **tags** in the format `{key}:{value}` to filter the runs that will be considered. + + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + + +## Alerting when a run is taking too long to complete +You can set up alerts to notify you whenever a run takes more than some threshold amount of time. + + By default, these alerts will target all runs in the deployment, but they can be scoped to runs with a specific tag. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Run alert** from the dropdown. + +5. Select **Job running over** and how many hours to alert after. + +If desired, add **tags** in the format `{key}:{value}` to filter the runs that will be considered. + + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + + +## Alerting when an asset fails to materialize +You can set up alerts to notify you when an asset materialization attempt fails. + +By default, these alerts will target all assets in the deployment, but they can be scoped to a specific asset or group of assets. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Asset alert** from the dropdown. + +5. Select **Failure** under the **Materializations** heading. + +If desired, select a **target** from the dropdown menu to scope this alert to a specific asset or group. + + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + + +## Alerting when an asset check fails +You can set up alerts to notify you when an asset check on an asset fails. + +By default, these alerts will target all assets in the deployment, but they can be scoped to checks on a specific asset or group of assets. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Asset alert** from the dropdown. + +5. Select **Failed (ERROR)** under the **Asset Checks** heading. + +If desired, select a **target** from the dropdown menu to scope this alert to a specific asset or group. + + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + + +## Alerting when a schedule or sensor tick fails +You can set up alerts to fire when any schedule or sensor tick across your entire deployment fails. + +Alerts are sent only when a schedule/sensor transitions from **success** to **failure**, so only the initial failure will trigger the alert. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Schedule/Sensor alert** from the dropdown. + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + + +## Alerting when a code location fails to load +You can set up alerts to fire when any code location fails to load due to an error. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Code location error alert** from the dropdown. + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + + +## Alerting when a Hybrid agent becomes unavailable +:::note +This is only available for [Hybrid](/todo) deployments. +::: + +You can set up alerts to fire if your Hybrid agent hasn't sent a heartbeat in the last 5 minutes. + + + 1. In the Dagster UI, click **Deployment**. +2. Click the **Alerts** tab. +3. Click **Add alert policy**. +4. Select **Code location error alert** from the dropdown. + + + Execute the following command to sync the configured alert policy to your Dagster+ deployment. + + ```bash + dagster-cloud deployment alert-policies sync -a /path/to/alert_policies.yaml + ``` + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/microsoft-teams.md b/docs/docs-beta/docs/dagster-plus/features/alerts/microsoft-teams.md new file mode 100644 index 0000000000000..7c66b3e2dae8b --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/microsoft-teams.md @@ -0,0 +1,8 @@ +--- +title: "Dagster+ Microsoft Teams alerts" +unlisted: true +sidebar_label: "Microsoft Teams" +sidebar_position: 400 +--- + +# Dagster+ Microsoft Teams alerts diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/pagerduty.md b/docs/docs-beta/docs/dagster-plus/features/alerts/pagerduty.md new file mode 100644 index 0000000000000..c8a32645e592f --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/pagerduty.md @@ -0,0 +1,8 @@ +--- +title: "Dagster+ PagerDuty alerts" +unlisted: true +sidebar_label: "PagerDuty" +sidebar_position: 500 +--- + +# Dagster+ PagerDuty alerts diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/slack.md b/docs/docs-beta/docs/dagster-plus/features/alerts/slack.md new file mode 100644 index 0000000000000..3d9f5423dd890 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/slack.md @@ -0,0 +1,8 @@ +--- +title: "Dagster+ Slack alerts" +unlisted: true +sidebar_label: "Slack" +sidebar_position: 600 +--- + +# Dagster+ Slack alerts diff --git a/docs/docs-beta/docs/dagster-plus/features/alerts/ui.md b/docs/docs-beta/docs/dagster-plus/features/alerts/ui.md new file mode 100644 index 0000000000000..b613282af846e --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/alerts/ui.md @@ -0,0 +1,8 @@ +--- +title: "Dagster+ alerts in the UI" +unlisted: true +sidebar_label: "UI" +sidebar_position: 100 +--- + +# Alerts in the UI diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/index.mdx b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/index.mdx new file mode 100644 index 0000000000000..a17a4992483d4 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/index.mdx @@ -0,0 +1,11 @@ +--- +title: "Authentication and access control" +displayed_sidebar: "dagsterPlus" +sidebar_position: 40 +--- + +# Authentication and access control + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/audit-logs.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/audit-logs.md new file mode 100644 index 0000000000000..cfc6c1cd81337 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/audit-logs.md @@ -0,0 +1,68 @@ +--- +title: "Audit logs" +displayed_sidebar: "dagsterPlus" +sidebar_position: 300 +--- + +# Audit logs + +The Dagster+ audit log enables Dagster+ Pro organizations to track and attribute changes to their Dagster deployment. + +For large organizations, tracking down when and by whom changes were made can be crucial for maintaining security and compliance. The audit log is also valuable + for tracking operational history, including sensor and schedule updates. + +This guide walks through how to access the audit log and details the interactions which are tracked in the audit log. + +
    +Prerequisites +- A Dagster+ Pro organization +- An [Organization Admin](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) role in your Dagster+ organization +
    + +## View audit logs + +To access the audit logs: + +1. Click your user icon at the top right corner of the page. +2. Click **Organization settings**. +3. Click the **Audit log** tab. + +:::warning + +Add screenshot + +::: + +Each entry in the audit log indicates when an action was taken, the user who performed the action, the action taken, and the deployment which the action affected. To view additional details for an action, click the **Show** button. + +## Filter the audit log + +The **Filter** button near the top left of the page can be used to filter the list of logs. You can filter to a combination of user, event type, affected deployment, or time frame. + +## Audit log entry types + +| Event type | Description | Additional details | +|--------------------------------|---------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------| +| Log in | A user logs in to the Dagster+ organization | | +| Update sensor | A user toggles a sensor on or off | The sensor name, code location, and cursor | +| Update schedule | A user toggles a schedule on or off | The schedule name, code location, and cursor | +| Update alert policy | A user modifies an [alert policy](/dagster-plus/features/alerts/ui) | The new configuration for the alert policy | +| Create deployment | A user creates a new deployment | Whether the deployment is a branch deployment | +| Delete deployment | A user removes an existing deployment | Whether the deployment is a branch deployment | +| Create user token | A user creates a new user token | | +| Revoke user token | A user revokes an existing user token | | +| Change user permissions | A user alters [permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) for another user | The permission grant and targeted deployment | +| Create agent token | A user creates a new agent token | | +| Revoke agent token | A user revokes an existing agent token | | +| Update agent token permissions | A user alters [permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) for an agent token | The permission grant and targeted deployment | +| Create secret | A user creates a new [environment variable](/dagster-plus/deployment/environment-variables/dagster-ui) | The created variable name | +| Update secret | A user modifies an existing [environment variable](/dagster-plus/deployment/environment-variables/dagster-ui) | The previous and current variable names and whether the value was changed | +| Delete secret | A user removes an [environment variable](/dagster-plus/deployment/environment-variables/dagster-ui) | The deleted variable name | +| Update subscription | A user modifies the selected Dagster+ subscription for the organization | The previous and current plan types | + +## Programmatic access to audit logs + +Audit logs can be accessed programmatically over the Dagster+ GraphQL API. You can access a visual GraphiQL interface +by navigating to `https://.dagster.cloud//graphql` in your browser. You can also query the API directly using the Python client. + + diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/index.mdx b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/index.mdx new file mode 100644 index 0000000000000..1443bd749b3b4 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/index.mdx @@ -0,0 +1,11 @@ +--- +title: "Role-based access control" +displayed_sidebar: "dagsterPlus" +sidebar_position: 10 +--- + +# Role-based access control + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/teams.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/teams.md new file mode 100644 index 0000000000000..dff5866950069 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/teams.md @@ -0,0 +1,78 @@ +--- +title: "Team management" +displayed_sidebar: "dagsterPlus" +sidebar_position: 100 +--- + +# Team management in Dagster+ + +As part of [role-based access control (RBAC)](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions), Dagster+ supports the ability to assign users to teams. A team is a group of users with a set of default deployment, code location, and Branch Deployment user roles. + +
    + Prerequisites + +To complete the steps in this guide, you'll need: + +- A Dagster+ Pro plan +- Dagster+ [Organization Admin permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions): + - In your organization, and + - For the deployments where you want to manage teams + +
    + + +## Adding teams + +1. In the Dagster+ UI, click the **user menu (your icon) > Organization Settings**. +2. Click the **Teams** tab. +3. Click the **Create a team** button. +4. In the window that displays, enter a name in the **Team name** field. +5. Click **Create team**. + +After the team is created, you can [add team members](#adding-team-members) and [assign user roles to deployments](#managing-team-roles). + +## Adding team members + +Navigate to the **Organization Settings > Teams** tab and locate the team you want to add team members to. Then: + +1. Click the **Edit** button in the **Actions** column. +2. In the **Members** tab, use the search bar to locate a user in your organization. +3. Once located, click the user. +4. Click **Add user to team**. +5. Repeat as needed, clicking **Done** when finished. + +## Removing team members + +Navigate to the **Organization Settings > Teams** tab and locate the team you want to remove team members from. Then: + +1. Click the **Edit** button in the **Actions** column. +2. In the **Members** tab, locate the user in the list of team members. +3. Click **Remove from team**. +4. Repeat as needed, clicking **Done** when finished. + +## Managing team roles + +Navigate to the **Organization Settings > Teams** tab and locate the team you want to manage roles for. Then: + +1. Click the **Edit** button in the **Actions** column. +2. In the **Roles** tab, click the **Edit team role** button next to the deployment where you want to modify the team's role. +3. In the window that displays, select the team role for the deployment. This [role](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) will be used as the default for this team for all code locations in the deployment. +4. Click **Save**. +5. To set permissions for individual [code locations](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) in a deployment: + 1. Click the toggle to the left of the deployment to open a list of code locations. + 2. Next to a code location, click **Edit team role**. + 3. Select the team role for the code location. + 4. Click **Save**. + +## Removing teams + +Navigate to the **Organization Settings > Teams** tab and locate the team you want to remove. Then: + +1. Click the **Edit** button in the **Actions** column. +2. In the modal that displays, click the **Delete team** button. +3. When prompted, confirm the deletion. + +## Next steps + +- Learn more about RBAC in [Understanding User Roles & Permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) +- Learn more about how to manage users in Dagster+ in [Understanding User Management in Dagster+](/dagster-plus/features/authentication-and-access-control/rbac/users) diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions.md new file mode 100644 index 0000000000000..6281ae236cd9e --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions.md @@ -0,0 +1,211 @@ +--- +title: 'User roles & permissions' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 200 +--- + +# Understanding user roles & permissions in Dagster+ + +Role-based access control (RBAC) enables you to grant specific permissions to users in your organization, ensuring that Dagster users have access to what they require in Dagster+, and no more. + +In this guide, we'll cover how RBAC works in Dagster+, how to assign roles to users, and the granular permissions for each user role. + +
    + Prerequisites + +To complete the steps in this guide, you'll need: + +- A Dagster+ account + - Additionally, in certain cases listed below, a Dagster+ Pro plan + +
    + +## Dagster+ user roles + +Dagster+ uses a hierarchical model for RBAC, meaning that the most permissive roles include permissions from the roles beneath them. The following user roles are currently supported, in order from the **most** permissive to the **least** permissive: + +- Organization Admin +- Admin +- Editor +- Launcher (Pro plans only) +- Viewer + +For example, the **Admin** user role includes permissions specific to this role and all permissions in the **Editor**, **Launcher**, and **Viewer** user roles. Refer to the [User permissions reference](#user-permissions-reference) for the full list of user permissions in Dagster+. + +### User role enforcement + +All user roles are enforced both in Dagster+ and the GraphQL API. + +### Teams + +Dagster+ Pro users can create teams of users and assign default permission sets. Refer to the [Managing teams in Dagster+](/dagster-plus/features/authentication-and-access-control/rbac/teams) guide for more info. + +## Assigning user and team roles + +With the exception of the **Organization Admin** role, user and team roles are set on a per-deployment basis. + +Organization Admins have access to the entire organization, including all [deployments](/todo), [code locations](/dagster-plus/deployment/code-locations), and [Branch Deployments](dagster-plus/features/branch-deployments/index.mdx). + +| Level | Plan | Description | +| ------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Deployment | All plans | Defines the level of access for a given deployment. Roles set at this level will be the default role for the user or team for all code locations in the deployment.

    Note: Granting access to a deployment grants a minimum of Viewer access to all code locations. Preventing access for specific code locations isn't currently supported. Additionally, having access to a deployment doesn't grant access to Branch Deployments - those permissions must be granted separately. | +| Code location | Pro | Defines the level of access for a given code location in a deployment.

    Dagster+ Pro users can [override the default deployment-level role for individual code locations](/dagster-plus/deployment/code-locations). For example, if the Deployment role is Launcher, you could override this role with a more permissive role, such as Editor or Admin.

    For non-Pro users, users will have the same level of access for all code locations in a deployment. | +| Branch deployments | All plans | Defines the level of access for all Branch Deployments in the code locations the user or team has access to. | + +### Applying role overrides + +As previously mentioned, you can define individual user roles for users in your organization. + +Dagster+ Pro users can also apply permission overrides to grant specific exceptions. + +Overrides may be used to apply a **more permissive** role. If, for example, the default role is **Admin** or **Organization Admin**, overrides will be disabled as these are the most permissive roles. + +#### Code locations + +To override a code location role for an individual user: + +1. Locate the user in the list of users. +2. Click **Edit**. +3. Click the toggle to the left of the deployment to open a list of code locations. +4. Next to a code location, click **Edit user role**. +5. Select the user role for the code location: + - TODO: add picture previously at "/images/dagster-cloud/user-token-management/code-location-override.png" +6. Click **Save**. + +#### Team members + +Users in your organization can belong to one or more [teams](/dagster-plus/features/authentication-and-access-control/rbac/teams). When determining a user's level of access, Dagster+ will use the **most permissive** role assigned to the user between all of their team memberships and any individual role grants. + +For example, let's look at a user with the following roles for our `dev` deployment: + +- **Team 1**: Launcher +- **Team 2**: Viewer +- **Individual**: Viewer + +In this example, the user would have **Launcher** access to the `prod` deployment. This is because the Launcher role is more permissive than Viewer. + +The above also applies to code locations and Branch Deployment roles. + +#### Viewing overrides + +To view deployment-level overrides for a specific user, locate the user on the **Users** page and hover over a deployment: + +TODO: add picture previously at "/images/dagster-cloud/user-token-management/user-overrides-popup.png" + +If there are code location-level overrides, a small **N override(s)** link will display beneath the user's deployment role. Hover over it to display the list of overrides: + +TODO: add picture previously at "/images/dagster-cloud/user-token-management/code-location-override-popup.png" + +#### Removing overrides + +1. Locate the user in the list of users. +2. Click **Edit**. +3. To remove an override: + - **For a deployment**, click **Edit user role** next to the deployment. + - **For a code location**, click the toggle next to the deployment to display a list of code locations. Click **Edit user role** next to the code location. +4. Click the **Remove override** button. +5. Click **Save**. + +## User permissions reference + +### General + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| ------------------------------------------------------------------------ | ------ | -------- | ------ | ----- | ------------------------ | +| View runs of [jobs](/guides/build/ops-jobs) | ✅ | ✅ | ✅ | ✅ | ✅ | +| Launch, re-execute, terminate, and delete runs of jobs | ❌ | ✅ | ✅ | ✅ | ✅ | +| Start and stop [schedules](/guides/automate/schedules) | ❌ | ❌ | ✅ | ✅ | ✅ | +| Start and stop [schedules](/guides/automate/sensors) | ❌ | ❌ | ✅ | ✅ | ✅ | +| Wipe assets | ❌ | ❌ | ✅ | ✅ | ✅ | +| Launch and cancel [schedules](/guides/build/backfill) | ❌ | ✅ | ✅ | ✅ | ✅ | +| Add dynamic partitions | ❌ | ❌ | ✅ | ✅ | ✅ | + +### Deployments + +Deployment settings are accessed in the UI by navigating to **user menu (your icon) > Organization Settings > Deployments**. + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +|----------------------------------------------------------------------------------------------|-------|-----------|--------|-------|-------------------------------| +| View [deployments](/todo) | ✅ | ✅ | ✅ | ✅ | ✅ | +| Modify [deployment](/todo) settings | ❌ | ❌ | ✅ | ✅ | ✅ | +| Create, edit, delete [environment variables](/dagster-plus/deployment/environment-variables) | ❌ | ❌ | ✅ | ✅ | ✅ | +| View [environment variable](/dagster-plus/deployment/environment-variables) values | ❌ | ❌ | ✅ | ✅ | ✅ | +| Export [environment variables](/dagster-plus/deployment/environment-variables) | ❌ | ❌ | ✅ | ✅ | ✅ | +| Create and delete [deployments](/todo) | ❌ | ❌ | ❌ | ❌ | ✅ | +| Create [Branch Deployments](dagster-plus/features/branch-deployments/index.mdx) | ❌ | ❌ | ✅ | ✅ | ✅ | + +### Code locations + +Code locations are accessed in the UI by navigating to **Deployment > Code locations**. + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| ------------------------------------------------------------------------------- | ------ | -------- | ------ | ----- | ------------------------ | +| View [code locations](/dagster-plus/deployment/code-locations) | ✅ | ✅ | ✅ | ✅ | ✅ | +| Create and remove [code locations](/dagster-plus/deployment/code-locations) | ❌ | ❌ | ✅ | ✅ | ✅ | +| Reload [code locations](/dagster-plus/deployment/code-locations) and workspaces | ❌ | ❌ | ✅ | ✅ | ✅ | + +### Agent tokens + +Agent tokens are accessed in the UI by navigating to **user menu (your icon) > Organization Settings > Tokens**. + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| ----------------------------------------------------------- | ------ | -------- | ------ | ----- | ------------------------ | +| View [agent tokens](/dagster-plus/deployment/hybrid/tokens) | ❌ | ❌ | ❌ | ❌ | ✅ | +| Create agent tokens | ❌ | ❌ | ❌ | ❌ | ✅ | +| Edit agent tokens | ❌ | ❌ | ❌ | ❌ | ✅ | +| Revoke agent tokens | ❌ | ❌ | ❌ | ❌ | ✅ | + +### User tokens + +User tokens are accessed in the UI by navigating to **user menu (your icon) > Organization Settings > Tokens**. + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| ---------------------------------------- | ------ | -------- | ------ | ----- | ------------------------ | +| View and create own [user tokens](/todo) | ✅ | ✅ | ✅ | ✅ | ✅ | +| List all user tokens | ❌ | ❌ | ❌ | ❌ | ✅ | +| Revoke all user tokens | ❌ | ❌ | ❌ | ❌ | ✅ | + +### Users + +User management is accessed in the UI by navigating to **user menu (your icon) > Organization Settings > Users**. + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| --------------------------------------------- | ------ | -------- | ------ | ----- | ------------------------ | +| [View users](/dagster-plus/features/authentication-and-access-control/rbac/users) | ✅ | ✅ | ✅ | ✅ | ✅ | +| Add users | ❌ | ❌ | ❌ | ✅ | ✅ | +| Edit user roles | ❌ | ❌ | ❌ | ❌ | ✅ | +| Remove users | ❌ | ❌ | ❌ | ❌ | ✅ | + +### Teams + +Team management is accessed in the UI by navigating to **user menu (your icon) > Organization Settings > Teams**. + +**Note**: Admin users can modify teams only in deployments where they're an Admin. + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| --------------------------------------------- | ------ | -------- | ------ | ----- | ------------------------ | +| [View teams](/dagster-plus/features/authentication-and-access-control/rbac/teams) | ✅ | ✅ | ✅ | ✅ | ✅ | +| Modify team permissions | ❌ | ❌ | ❌ | ✅ | ✅ | +| Create teams | ❌ | ❌ | ❌ | ❌ | ✅ | +| Re-name teams | ❌ | ❌ | ❌ | ❌ | ✅ | +| Add/remove team members | ❌ | ❌ | ❌ | ❌ | ✅ | +| Remove teams | ❌ | ❌ | ❌ | ❌ | ✅ | + +### Workspace administration + +| | Viewer | Launcher | Editor | Admin | Organization
    admin | +| ------------------------------------------------------ | ------ | -------- | ------ | ----- | ------------------------ | +| Manage [alerts](/dagster-plus/features/alerts) | ❌ | ❌ | ✅ | ✅ | ✅ | +| Edit workspace | ❌ | ❌ | ✅ | ✅ | ✅ | +| [Administer SAML](/dagster-plus/features/authentication-and-access-control/sso/authentication) | ❌ | ❌ | ❌ | ❌ | ✅ | +| [Manage SCIM](/todo) | ❌ | ❌ | ❌ | ❌ | ✅ | +| View usage | ❌ | ❌ | ❌ | ❌ | ✅ | +| Manage billing | ❌ | ❌ | ❌ | ❌ | ✅ | +| View audit logs | ❌ | ❌ | ❌ | ❌ | ✅ | + +## Next steps + +- Learn more about how to manage users in Dagster+ in [Understanding User Management in Dagster+](/dagster-plus/features/authentication-and-access-control/rbac/users) +- Learn more about how to manage teams in Dagster+ in [Understanding Team Management in Dagster+](/dagster-plus/features/authentication-and-access-control/rbac/teams) +- Learn more about SCIM provisioning in [Understanding SCIM Provisioning](/dagster-plus/features/authentication-and-access-control/scim/index.mdx) +- Learn more about authentication in [Understanding Authentication](/dagster-plus/features/authentication-and-access-control/sso/authentication) diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/users.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/users.md new file mode 100644 index 0000000000000..61c3a2f55401f --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/rbac/users.md @@ -0,0 +1,93 @@ +--- +title: "Managing users in Dagster+" +displayed_sidebar: "dagsterPlus" +sidebar_label: "User management" +sidebar_position: 400 +--- + +Dagster+ allows you to grant specific permissions to your organization's users, ensuring that Dagster users have access only to what they require. + +In this guide, you'll learn how to manage users and their permissions using the Dagster+ UI. + +
    +Prerequisites + +- A Dagster+ account +- The required [Dagster+ permissions](/todo): + - **Organization Admins** can add, manage, and remove users + - **Admins** can add users + +
    + +## Before you start + +- **If System for Cross-domain Identity Management specification (SCIM) provisioning is enabled,** you'll need to add new users in your identity provider (IdP). Adding users will be disabled in Dagster+. +- **If using Google for Single sign-on (SSO)**, users must be added in Dagster+ before they can log in. +- **If using an Identity Provider (IdP) like Okta for SSO**, users must be assigned to the Dagster app in the IdP to be able to log in to Dagster+. Refer to the [SSO setup guides](/todo) for setup instructions for each of our supported IdP solutions. + +By default, users will be granted Viewer permissions on each deployment. The default role can be adjusted by modifying the [`sso_default_role` deployment setting](/todo). + +## Adding users to Dagster+ + +1. Sign in to your Dagster+ account. +2. Click the **user menu (your icon) > Organization Settings**. +3. Click the **Users** tab. +4. Click **Add new user.** +5. In the **User email** field, enter the user's email address. +6. Click **Add user**. + +After the user is created, they will be notified via email, and you can [add the user to teams](#teams) and [assign user roles for each deployment](#user-roles). + +![Screenshot of assigning roles to a user](/img/placeholder.svg) + +## Adding users to teams \{#teams} + +:::note +Teams are a Dagster+ Pro feature. +::: + +Teams are useful for centralizing permission sets for different types of users. Refer to [Managing teams](/todo) for more information about creating and managing teams. + +![Screenshot of Managing teams page](/img/placeholder.svg) + +:::note +When determining a user's level of access, Dagster+ will use the **most permissive** role assigned to the user between all of their team memberships and any individual role grants. Refer to [Managing user roles and permissions](/todo) for more information. +::: + +## Assigning user roles \{#user-roles} + +In the **Roles** section, you can assign a [user role](/todo) for each deployment, granting them a set of permissions that controls their access to various features and functionalities within the platform. + +1. Next to a deployment, click **Edit user role**. +2. Select the user role for the deployment. This [user role](/todo) will be used as the default for all code locations in the deployment. +3. Click **Save**. +4. **Pro only**: To set permissions for individual [code locations](/todo) in a deployment: + 1. Click the toggle to the left of the deployment to open a list of code locations. + 2. Next to a code location, click **Edit user role**. + 3. Select the user role for the code location. + 4. Click **Save**. +5. Repeat the previous steps for each deployment. +6. **Optional**: To change the user's permissions for branch deployments: + 1. Next to **All branch deployments**, click **Edit user role**. + 2. Select the user role to use for all branch deployments. + 3. Click **Save**. +7. Click **Done**. + +## Removing users + +Removing a user removes them from the organization. **Note**: If using a SAML-based SSO solution like Okta, you'll also need to remove the user from the IdP. Removing the user in Dagster+ doesn't remove them from the IdP. + +1. Sign in to your Dagster+ account. +2. Click the **user menu (your icon) > Organization Settings**. +3. Click the **Users** tab. +4. Locate the user in the user list. +5. Click **Edit**. +6. Click **Remove user**. +7. When prompted, confirm the removal. + +## Next steps + +- Learn more about role-based access control (RBAC) in [Understanding User Roles & Permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) +- Learn more about how to manage teams in Dagster+ in [Understanding Team Management in Dagster+](/dagster-plus/features/authentication-and-access-control/rbac/teams) +- Learn more about SCIM provisioning in [SCIM Provisioning](/dagster-plus/features/authentication-and-access-control/scim) +- Learn more about authentication in [Understanding Authentication](/dagster-plus/features/authentication-and-access-control/sso/authentication) diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/azure-active-directory.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/azure-active-directory.md new file mode 100644 index 0000000000000..28fd1473a5e56 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/azure-active-directory.md @@ -0,0 +1,10 @@ +--- +title: 'Azure Active Directory' +displayed_sidebar: 'dagsterPlus' +unlisted: true +sidebar_position: 200 +--- + +# Azure Active Directory + +See the [Dagster Cloud provisioning tutorial](https://learn.microsoft.com/en-us/azure/active-directory/saas-apps/dagster-cloud-provisioning-tutorial). diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/index.mdx b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/index.mdx new file mode 100644 index 0000000000000..19ee9983dc77d --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/index.mdx @@ -0,0 +1,11 @@ +--- +title: "SCIM provisioning" +displayed_sidebar: "dagsterPlus" +sidebar_position: 30 +--- + +# SCIM provisioning + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/okta-scim.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/okta-scim.md new file mode 100644 index 0000000000000..a1dd29b1bf275 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/scim/okta-scim.md @@ -0,0 +1,8 @@ +--- +title: 'Okta SCIM provisioning' +displayed_sidebar: 'dagsterPlus' +unlisted: true +sidebar_position: 100 +--- + +# Okta SCIM provisioning diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/authentication.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/authentication.md new file mode 100644 index 0000000000000..2c626adac16d8 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/authentication.md @@ -0,0 +1,8 @@ +--- +title: "Authentication" +displayed_sidebar: "dagsterPlus" +unlisted: true +sidebar_position: 100 +--- + +# Authentication diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/azure-ad-sso.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/azure-ad-sso.md new file mode 100644 index 0000000000000..5921d30d4d995 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/azure-ad-sso.md @@ -0,0 +1,96 @@ +--- +title: 'Azure Active Directory SSO' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 200 +--- + +# Setting up Azure Active Directory SSO for Dagster+ + +In this guide, you'll configure Azure Active Directory (AD) to use single sign-on (SSO) with your Dagster+ organization. + +
    + Prerequisites + +To complete the steps in this guide, you'll need: + +- **An existing Azure AD account** +- **To install the [`dagster-cloud` CLI](/todo)** +- **The following in Dagster+:** + - A Pro plan + - [Access to a user token](/todo) + - [Organization Admin permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) in your organization + +
    + +## Step 1: add the Dagster+ app in Azure AD \{#dagster-app} + +In this step, you'll add the Dagster+ app to your list of managed SaaS apps in Azure AD. + +1. Sign in to the Azure portal. +2. On the left navigation pane, click the **Azure Active Directory** service. +3. Navigate to **Enterprise Applications** and then **All Applications**. +4. Click **New application**. +5. In the **Add from the gallery** section, type **Dagster+** in the search box. +6. Select **Dagster+** from the results panel and then add the app. Wait a few seconds while the app is added to your tenant. + +## Step 2: configure SSO in Azure AD \{#configure-sso} + +In this step, you'll configure and enable SSO for Azure AD in your Azure portal. + +1. On the **Dagster+** application integration page, locate the **Manage** section and select **single sign-on**. +2. On the **Select a single sign-on method** page, select **SAML**. +3. On the **Set up single sign-on with SAML** page, click the pencil icon for **Basic SAML Configuration** to edit the settings. + ![Settings Dropdown](/img/placeholder.svg) +4. In the **Basic SAML Configuration** section, fill in the **Identifier** and **Reply URL** fields as follows: + + Copy and paste the following URL, replacing `` with your Dagster+ organization name: + + ``` + https://.dagster.cloud/auth/saml/consume + ``` + +5. Click **Set additional URLs**. +6. In the **Sign-on URL** field, copy and paste the URL you entered in the **Identifier** and **Reply URL** fields. +7. Next, you'll configure the SAML assertions. In addition to the default attributes, Dagster+ requires the following: + + - `FirstName` - `user.givenname` + - `LastName` - `user.surname` + - `Email` - `user.userprincipalname` + + Add these attribute mappings to the SAML assertion. +8. On the **Set up single sign-on with SAML** page: + 1. Locate the **SAML Signing Certificate** section. + 2. Next to **Federation Metadata XML**, click **Download**: + + ![Download SAML Certificate](/img/placeholder.svg) + + When prompted, save the SAML metadata file to your computer. + +## Step 3: upload the SAML metadata to Dagster+ \{#upload-saml} + +After you've downloaded the SAML metadata file, upload it to Dagster+ using the `dagster-cloud` CLI: + +```shell +dagster-cloud organization settings saml upload-identity-provider-metadata \ + --api-token= \ + --url https://.dagster.cloud +``` + +## Step 4: create a test user \{#test-user} + +In this section, you'll create a test user in the Azure portal. + +1. From the left pane in the Azure portal, click **Azure Active Directory**. +2. Click **Users > All users**. +3. Click **New user** at the top of the screen. +4. In **User** properties, fill in the following fields: + - **Name**: Enter `B.Simon`. + - **User name**: Enter `B.Simon@contoso.com`. + - Select the **Show password** checkbox and write down the value displayed in the **Password** box. +5. Click **Create**. + +import TestSSO from '../../../../partials/\_TestSSO.md'; + + + +Click **Test this application** in the Azure portal. If successful, you'll be automatically signed into your Dagster+ organization. diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/google-workspace-sso.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/google-workspace-sso.md new file mode 100644 index 0000000000000..49727f24ad5c2 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/google-workspace-sso.md @@ -0,0 +1,111 @@ +--- +title: 'Google Workspace SSO' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 300 +--- + +# Setting up Google Workspace SSO for Dagster+ + +In this guide, you'll configure Google Workspace to use single sign-on (SSO) with your Dagster+ organization. + +
    + Prerequisites + +To complete the steps in this guide, you'll need: + +- **The following in Google**: + - An existing Google account + - [Workspace Admin permissions](https://support.google.com/a/answer/6365252?hl=en&ref_topic=4388346) +- **To install the [`dagster-cloud` CLI](/todo)** +- **The following in Dagster+:** + - A Pro plan + - [Access to a user token](/todo) + - [Organization Admin permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) in your organization + +
    + +## Step 1: Add the Dagster+ app in Google Workspace \{#dagster-app} + +1. Navigate to your [Google Admin Console](https://admin.google.com). +2. Using the sidebar, navigate to **Apps > Web and mobile apps**: + + ![Google Workspace Sidebar](/img/placeholder.svg) + +3. On the **Web and mobile apps** page, click **Add App > Add custom SAML app**: + ![Add App](/img/placeholder.svg) + This opens a new page for adding app details. + +## Step 2: Configure SSO in Google Workspace \{#configure-sso} + +1. On the **App details** page: + 1. Fill in the **App name** field. + 2. Fill in the **Description** field. + + The page should look similar to the following: + + ![Application Details](/img/placeholder.svg) + + 3. Click **Continue**. + +2. On the **Google Identity Provider details** page, click **Continue**. No action is required for this page. +3. On the **Service provider details** page: + 1. In the **ACS URL** and **Entity ID** fields: + + Copy and paste the following URL, replacing `` with your Dagster+ organization name: + + ``` + https://.dagster.cloud/auth/saml/consume + ``` + + 2. Check the **Signed Response** box. The page should look similar to the image below. In this example, the organization's name is `hooli` and the Dagster+ domain is `https://hooli.dagster.cloud`: + + ![Service Provider Details](/img/placeholder.svg) + + 3. When finished, click **Continue**. +4. On the **Attributes** page: + 1. Click **Add mapping** to add and configure the following attributes: + + - **Basic Information > First Name** - `FirstName` + - **Basic Information > Last Name** - `LastName` + - **Basic Information > Email** - `Email` + + The page should look like the following image: + + ![Attribute Mapping](/img/placeholder.svg) + + 2. Click **Finish**. + +## Step 3: Upload the SAML metadata to Dagster+ \{#upload-saml} + +Next, you'll save and upload the application's SAML metadata to Dagster+. This will enable single sign-on. + +1. In your Google Workspace, open the Dagster+ application you added in [Step 2](#configure-sso). +2. Click **Download metadata**: + + ![SAML Metadata](/img/placeholder.svg) + +3. In the modal that displays, click **Download metadata** to start the download. Save the file to your computer. +4. After you've downloaded the SAML metadata file, upload it to Dagster+ using the `dagster-cloud` CLI: + + ```shell + dagster-cloud organization settings saml upload-identity-provider-metadata \ + --api-token= \ + --url https://.dagster.cloud + ``` + +## Step 4: Grant access to users \{#grant-access} + +In this step, you'll assign users in your Google Workspace to the Dagster+ application. This allows members of the workspace to log in to Dagster+ using their credentials when the single sign-on flow is initiated. + +1. In the Google Workspace Dagster+ application, click **User access**. +2. Select an organizational unit. +3. Click **ON for everyone**. +4. Click **Save**. + + ![Assign New Login](/img/placeholder.svg) + +import TestSSO from '../../../../partials/\_TestSSO.md'; + + + +In the Google Workspace portal, click the **Dagster+ icon**. If successful, you'll be automatically signed into your Dagster+ organization. diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/index.mdx b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/index.mdx new file mode 100644 index 0000000000000..fe5219e36a95f --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/index.mdx @@ -0,0 +1,11 @@ +--- +title: "Single sign-on" +displayed_sidebar: "dagsterPlus" +sidebar_position: 20 +--- + +# Single sign-on + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/okta-sso.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/okta-sso.md new file mode 100644 index 0000000000000..2b9d01f0aeda1 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/okta-sso.md @@ -0,0 +1,95 @@ +--- +title: 'Okta SSO' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 400 +--- + +# Setting up Okta SSO for Dagster+ + +In this guide, you'll configure Okta to use single sign-on (SSO) with your Dagster+ organization. + +
    + Prerequisites + +To complete the steps in this guide, you'll need: + +- **An existing Okta account** +- **To install the [`dagster-cloud` CLI](/todo)** +- **The following in Dagster+:** + - A Pro plan + - [Access to a user token](/todo) + - [Organization Admin permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) in your organization + +
    + + +## Step 1: Add the Dagster+ app in Okta \{#dagster-app} + +1. Sign in to your Okta Admin Dashboard. +2. Using the sidebar, click **Applications > Applications**. +3. On the **Applications** page, click **Browse App Catalog**. +4. On the **Browse App Integration Catalog** page, search for `Dagster Cloud`. +5. Add and save the application. + + +## Step 2: Configure SSO in Okta \{#configure-sso} + +1. In Okta, open the Dagster Cloud application and navigate to its **Sign On Settings**. +2. Scroll down to the **Advanced Sign-on settings** section. +3. In the **Organization** field, enter your Dagster+ organization name. This is used to route the SAML response to the correct Dagster+ subdomain. + + For example, your organization name is `hooli` and your Dagster+ domain is `https://hooli.dagster.cloud`. To configure this correctly, you'd enter `hooli` into the **Organization** field: + + ![Okta Subdomain Configuration](/img/placeholder.svg) + +4. When finished, click **Done**. + + +## Step 3: Upload the SAML metadata to Dagster+ \{#upload-saml} + +Next, you'll save and upload the application's SAML metadata to Dagster+. This will enable single sign-on. + +1. In the **Sign On Settings**, navigate to the **SAML Signing Certificates** section. +2. Click the **Actions** button of the **Active** certificate. +3. Click **View IdP metadata**: + + ![Okta IdP metadata options](/img/placeholder.svg) + + This will open a new page in your browser with the IdP metadata in XML format. + +4. Right-click the page and use **Save As** or **Save Page As**: + + ![Save IdP metadata as XML](/img/placeholder.svg) + + In Chrome and Edge, the file will be downloaded as an XML file. In Firefox, choose **Save Page As > Save as type**, then select **All files**. + + :::note + Copying and pasting the metadata can cause formatting issues that will prevent successful setup. Saving the page directly from the browser will avoid this. + ::: + +5. After you've downloaded the metadata file, upload it to Dagster+ using the `dagster-cloud` CLI: + + ```shell + dagster-cloud organization settings saml upload-identity-provider-metadata \ + --api-token= \ + --url https://.dagster.cloud + ``` + + +## Step 4: Grant access to users \{#grant-access} + +Next, you'll assign users to the Dagster+ application in Okta. This will allow them to log in using their Okta credentials when the single sign-on flow is initiated. + +1. In the Dagster+ application, navigate to **Assignments**. +2. Click **Assign > Assign to People**. +3. For each user you want to have access to Dagster+, click **Assign** then **Save and Go Back**. + +import TestSSO from '../../../../partials/\_TestSSO.md'; + + + +In the Okta **Applications** page, click the **Dagster+** icon: + +![Okta idP Login](/img/placeholder.svg) + +If successful, you'll be automatically signed into your Dagster+ organization. diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/onelogin-sso.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/onelogin-sso.md new file mode 100644 index 0000000000000..4b9c10a57c1a7 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/onelogin-sso.md @@ -0,0 +1,92 @@ +--- +title: 'OneLogin SSO' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 500 +--- + +# OneLogin SSO + +In this guide, you'll configure OneLogin to use single sign-on (SSO) with your Dagster+ organization. + + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- **The following in OneLogin:** + - An existing OneLogin account + - Admin permissions +- **To install the [`dagster-cloud` CLI](/todo)** +- **The following in Dagster+:** + - A Pro plan + - [Access to a user token](/todo) + - [Organization Admin permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) in your organization + +
    + + +## Step 1: Add the Dagster+ app in OneLogin \{#dagster-app} + +1. Sign into your OneLogin portal. +2. Navigate to **Administration > Applications**. +3. On the **Applications** page, click **Add App**. +4. On the **Find Applications** page, search for `Dagster+`: + + ![Find Applications in OneLogin](/img/placeholder.svg) + +5. Add and save the application. + + + +## Step 2: Configure SSO in OneLogin \{#configure-sso} + +1. In OneLogin, open the application and navigate to its **Configuration**. +2. In the **Dagster+ organisation name** field, enter your Dagster+ organization name. This is used to route the SAML response to the correct Dagster+ subdomain. + + For example, your organization name is `hooli` and your Dagster+ domain is `https://hooli.dagster.cloud`. To configure this correctly, you'd enter `hooli` into the **Subdomain** field. +3. When finished, click **Done**. + + + +## Step 3: Upload the SAML metadata to Dagster+ \{#upload-saml} + +Next, you'll save and upload the application's SAML metadata to Dagster+. This will enable single sign-on. + +1. In OneLogin, open the Dagster+ application. +2. Navigate to **More Actions > SAML Metadata**. +3. When prompted, save the file to your computer. +4. After you've downloaded the SAML metadata file, upload it to Dagster+ using the `dagster-cloud` CLI: + + ```shell + dagster-cloud organization settings saml upload-identity-provider-metadata \ + --api-token= \ + --url https://.dagster.cloud + ``` + + +## Step 4: Grant access to users \{#grant-access} + +Next, you'll assign users to the Dagster+ application in OneLogin. This will allow them to log in using their OneLogin credentials with the sign in flow is initiated. + +1. In Okta, navigate to **Users**. +2. Select a user. +3. On the user's page, click **Applications**. +4. Assign the user to Dagster+. In the following image, the user `Test D'Test` has been assigned to Dagster+: + + ![Screenshot of Assign New Login in OneLogin](/img/placeholder.svg) + +5. Click **Continue**. +6. Click **Save User.** +7. Repeat steps 2-6 for every user you want to access Dagster+. + + +import TestSSO from '../../../../partials/\_TestSSO.md'; + + + +In the OneLogin portal, click the Dagster+ icon: + +![Screenshot of the Dagster+ icon in OneLogin](/img/placeholder.svg) + +If successful, you'll be automatically signed into your Dagster+ organization. diff --git a/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/pingone-sso.md b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/pingone-sso.md new file mode 100644 index 0000000000000..2c766cb1cfc70 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/authentication-and-access-control/sso/pingone-sso.md @@ -0,0 +1,121 @@ +--- +title: 'PingOne SSO' +displayed_sidebar: 'dagsterPlus' +sidebar_position: 600 +--- + +# Setting up PingOne SSO for Dagster+ + +In this guide, you'll configure PingOne to use single sign-on (SSO) with your Dagster+ organization. + +
    + Prerequisites + +To complete the steps in this guide, you'll need: + +- **The following in PingOne:** + - An existing PingOne account + - Organization admin permissions +- **To install the [`dagster-cloud` CLI](/todo)** +- **The following in Dagster+:** + - A Pro plan + - [Access to a user token](/todo) + - [Organization Admin permissions](/dagster-plus/features/authentication-and-access-control/rbac/user-roles-permissions) in your organization + +
    + +## Step 1: Add the Dagster+ app in PingOne \{#dagster-app} + +1. Sign into your PingOne Console. +2. Using the sidebar, click **Connections > Applications**. + + ![PingOne Sidebar](/img/placeholder.svg) + +3. On the **Applications** page, add an application. +4. In **Select an application type**, click **Web app**. +5. Click **SAML > Configure**: + + ![Add App](/img/placeholder.svg) + +## Step 2: Configure SSO in PingOne \{#configure-sso} + +1. In the **Create App Profile** page: + + 1. Add an application name, description, and icon: + + ![Application Details](/img/placeholder.svg) + + 2. When finished, click **Save and Continue.** + +2. In the **Configure SAML** page: + + 1. Fill in the following: + + - **ACS URLs** and **Entity ID**: Copy and paste the following URL, replacing `` with your Dagster+ organization name: + + ``` + https://.dagster.cloud/auth/saml/consume + ``` + + - **Assertion Validity Duration**: Type `60`. + In the following example, the organization's name is `hooli` and the Dagster+ domain is `https://hooli.dagster.cloud`: + + ![Service Provider Details](/img/placeholder.svg) + + 2. When finished, click **Save and Continue.** + +3. In the **Map Attributes** page: + + 1. Configure the following attributes: + + | Application attribute | Outgoing value | + | --------------------- | -------------- | + | Email | Email Address | + | FirstName | Given Name | + | LastName | Family Name | + + The page should look similar to the following: + + ![Attribute Mapping](/img/placeholder.svg) + + 2. When finished, click **Save and Continue.** + +## Step 3: Upload the SAML metadata to Dagster+ \{#upload-saml} + +Next, you'll save and upload the application's SAML metadata to Dagster+. This will enable single sign-on. + +1. In PingOne, open the Dagster+ application. +2. Click the **Configuration** tab. +3. In the **Connection Details** section, click **Download Metadata**: + + ![SAML Metadata](/img/placeholder.svg) + +4. When prompted, save the file to your computer. +5. After you've downloaded the SAML metadata file, upload it to Dagster+ using the `dagster-cloud` CLI: + + ```shell + dagster-cloud organization settings saml upload-identity-provider-metadata \ + --api-token= \ + --url https://.dagster.cloud + ``` + +## Step 4: Grant access to users \{#grant-access} + +Next, you'll assign users to the Dagster+ application in PingOne. This will allow them to log in using their PingOne credentials when the single sign-on flow is initiated. + +1. In the Dagster+ application, click the **Access** tab. +2. Click the **pencil icon** to edit the **Group membership policy**: + + ![Assign New Login](/img/placeholder.svg) + +3. Edit the policy as needed to grant users access to the application. + +import TestSSO from '../../../../partials/\_TestSSO.md'; + + + +In the PingOne application portal, click the **Dagster+** icon: + +![Identity Provider Login](/img/placeholder.svg) + +If successful, you'll be automatically signed in to your Dagster+ organization. diff --git a/docs/docs-beta/docs/dagster-plus/features/branch-deployments/change-tracking.md b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/change-tracking.md new file mode 100644 index 0000000000000..40b5a837ae8d6 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/change-tracking.md @@ -0,0 +1,9 @@ +--- +title: "Change tracking in branch deployments" +displayed_sidebar: "dagsterPlus" +sidebar_position: 200 +sidebar_label: "Change tracking" +unlisted: true +--- + +# Change tracking in branch deployments diff --git a/docs/docs-beta/docs/dagster-plus/features/branch-deployments/dagster-cloud-cli.md b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/dagster-cloud-cli.md new file mode 100644 index 0000000000000..76615d4e4ad5d --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/dagster-cloud-cli.md @@ -0,0 +1,9 @@ +--- +title: "Branch deployments & the dagster-cloud CLI" +displayed_sidebar: "dagsterPlus" +sidebar_position: 300 +sidebar_label: "dagster-cloud CLI" +unlisted: true +--- + +# Use branch deployments with the dagster-cloud CLI diff --git a/docs/docs-beta/docs/dagster-plus/features/branch-deployments/index.mdx b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/index.mdx new file mode 100644 index 0000000000000..bdb1ae1d19be9 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/index.mdx @@ -0,0 +1,11 @@ +--- +title: "Branch deployments (CI)" +displayed_sidebar: "dagsterPlus" +sidebar_position: 20 +--- + +# Branch deployments (CI) + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/branch-deployments/setting-up-branch-deployments.md b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/setting-up-branch-deployments.md new file mode 100644 index 0000000000000..39ef33b1362cb --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/setting-up-branch-deployments.md @@ -0,0 +1,448 @@ +--- +title: "Setting up branch deployments" +displayed_sidebar: "dagsterPlus" +sidebar_position: 100 +sidebar_label: "Setting up branch deployments" +--- + +In this guide, we'll walk you through setting up Branch Deployments for a code location. Once you're finished, any time a PR is created or updated in your repository, it will automatically create or update an associated branch deployment in Dagster+. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- **Organization Admin** permissions in Dagster+ +- The ability to run a new agent in your infrastructure (only if you are using a **Hybrid deployment**) + +
    + +## Step 1: Choose a method + +Choose a method for setting up branch deployments: + + + + +You can set up GitHub to automatically create branch deployments for new PRs, using GitHub Actions. + +Using this approach to branch deployments may be a good fit if: + +- You use **GitHub** for version control +- You want Dagster to fully automate Branch Deployments + +This approach is simplified if you use the [GitHub integration](/todo) to import your project into Dagster+. + + + + +You can set up GitLab to automatically create branch deployments for new PRs, using GitLab's CI/CD workflow. + +Using this approach to branch deployments may be a good fit if: + +- You use **GitLab** for version control +- You want Dagster to fully automate Branch Deployments + +This approach is simplified if you use the [GitLab integration](/todo) to import your project into Dagster+. + + + + +You can manually execute dagster-cloud CLI commands to deploy and manage branch deployments. + +Using this approach to branch deployments may be a good fit if: + +- You don't use GitHub or GitLab for version control +- You use an alternative CI platform +- You want full control over Branch Deployment configuration + +This is a more advanced option than the other methods. + + + + +## Step 2: Generate a Dagster+ agent token + +In this step, you'll generate a token for the Dagster+ agent. The Dagster+ agent will use this to authenticate to the agent API. + +1. Sign in to your Dagster+ instance. +2. Click the **user menu (your icon) > Organization Settings**. +3. In the **Organization Settings** page, click the **Tokens** tab. +4. Click the **Create agent token** button. +5. After the token has been created, click **Reveal token**. + +Keep the token somewhere handy - you'll need it to complete the setup. + +## Step 3: Create and configure an agent + +:::note +If using [Serverless deployment](/dagster-plus/deployment/serverless), this step can be skipped. +::: + +While you can use your existing production agent, we recommend creating a dedicated branch deployment agent. This ensures that your production instance isn't negatively impacted by the workload associated with branch deployments. + + + + + 1. **Deploy an ECS agent to serve your branch deployments**. Follow the [ECS agent](/dagster-plus/deployment/hybrid/agents/amazon-ecs-new-vpc) setup guide, making sure to set the **Enable Branch Deployments** parameter if using the CloudFormation template. If you are running an existing agent, follow the [upgrade guide](/dagster-plus/deployment/hybrid/agents/amazon-ecs-existing-vpc) to ensure your template is up-to-date. Then, turn on the **Enable Branch Deployments** parameter. + + 2. **Create a private [Amazon Elastic Registry (ECR) repository](https://console.aws.amazon.com/ecr/repositories).** Refer to the [AWS ECR documentation](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html) for instructions. + + After the repository has been created, navigate back to the list of [ECR repositories](https://console.aws.amazon.com/ecr/repositories). + + In the list, locate the repository and its **URI**: + + ![Show this in the UI](/img/placeholder.svg) + + Keep this around, as you'll need it in a later step. + + 3. [**Create an IAM user.**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html) This user must: + + - Have push access to the ECR repository, and + - Have programmatic access to AWS using an [access key](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) + + After the user is created, save the **Access key ID** and **Secret access key** values shown on the confirmation page: + + ![Show this in the UI](/img/placeholder.svg) + + + + + 1. Set up a new Docker agent. Refer to the [Docker agent setup guide](/dagster-plus/deployment/hybrid/agents/docker) for instructions. + 2. After the agent is set up, modify the `dagster.yaml` file as follows: + + - Set the `dagster_cloud_api.branch_deployments` field to `true` + - Remove any `deployment` field(s) + + For example: + + + + + + + 1. Set up a new Kubernetes agent. Refer to the [Kubernetes agent setup guide](/dagster-plus/deployment/hybrid/agents/kubernetes) for instructions. + + 2. After the agent is set up, modify your Helm values file to include the following: + + + + + + +## Step 4: Set up branch deployments + + + + +### Step 4.1: Add GitHub CI/CD script to your project +:::note +If you used the GitHub app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-github-action-runs) +::: + +Copy the following files to your project, and **replace** all references to `quickstart-etl` with the name of your project: + +- [`dagster_cloud.yaml`](https://github.com/dagster-io/dagster-cloud-hybrid-quickstart/blob/main/dagster_cloud.yaml) +- [`.github/workflows/dagster-cloud-deploy.yml`](https://github.com/dagster-io/dagster-cloud-hybrid-quickstart/blob/main/.github/workflows/dagster-cloud-deploy.yml) (for **Hybrid** deployments) +- [`.github/workflows/branch_deployments.yml`](https://github.com/dagster-io/dagster-cloud-serverless-quickstart/blob/main/.github/workflows/branch_deployments.yml) (for **Serverless** deployments) + +In the next step, you'll modify these files to work with your Dagster+ setup. + +### Step 4.2: Add the agent registry to dagster_cloud.yaml + +:::note +If you used the GitHub app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-github-action-runs) +::: + +In the `dagster_cloud.yaml` file, replace `build.registry` with the registry used by the [agent you created in Step 2](#step-2-generate-a-dagster-agent-token). + +For example: + + + +### Step 4.3: Configure GitHub Action secrets + +:::note +If you used the GitHub app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-github-action-runs) +::: + +1. In your GitHub repository, click the **Settings** tab. +2. In the **Security** section of the sidebar, click **Secrets > Actions**. +3. Click **New repository secret**. +4. In the **Name** field, enter the name of the secret. For example, `DAGSTER_CLOUD_API_TOKEN` +5. In the **Value** field, paste the value of the secret. +6. Click **Add secret**. + +Repeat steps 3-6 for each of the secrets required for the registry used by the agent you created in Step 2. See below for more details: + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) +- `DOCKERHUB_USERNAME` - Your DockerHub username +- `DOCKERHUB_TOKEN` - A DockerHub [access token](https://docs.docker.com/docker-hub/access-tokens/#create-an-access-token) + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) +- `AWS_ACCESS_KEY` - The **Access key ID** of the AWS IAM user you created in [Step 3](#step-3-create-and-configure-an-agent) +- `AWS_SECRET_ACCESS_KEY` - The **Secret access key** of the AWS IAM user you created in [Step 3](#step-3-create-and-configure-an-agent) +- `AWS_REGION` - The AWS region where your ECR registry is located + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) +- `GCR_JSON_KEY` - Your GCR JSON credentials + + + + + +### Step 4.4: Configure GitHub Action + +:::note +If you used the GitHub app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-github-action-runs) +::: + +In this step, you'll update the GitHub workflow files in your repository to set up Docker registry access. + +In the `.github/workflows/dagster-cloud-deploy.yml` file, un-comment the `step` associated with your registry. For example, for an Amazon ECR registry, you'd un-comment the following portion of the workflow file: + +```yaml +jobs: + dagster-cloud-deploy: + steps: + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v1 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ secrets.AWS_REGION }} +``` + +Save and commit the file to your repository. + +### Step 4.5: Verify GitHub action runs + +The last step is to verify that the GitHub Action runs successfully. + +1. In the repository, click the **Actions** tab. +2. In the list of workflows, locate the latest branch deployment run. For example: + +![Show this in the UI](/img/placeholder.svg) + + + + +### Step 4.1: add GitLab CI/CD script to your project + +:::note +If you used the GitLab app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-gitlab-pipeline-runs) +::: + +Copy the following files to your project, and **replace** all references to `quickstart-etl` with the name of your project: + +- [`dagster_cloud.yaml`](https://github.com/dagster-io/dagster-cloud-hybrid-quickstart/blob/main/dagster_cloud.yaml) +- [`.gitlab-ci.yml`](https://github.com/dagster-io/dagster-cloud-action/blob/main/gitlab/hybrid-ci.yml) (for **Hybrid** deployments) +- [`.gitlab-ci.yml`](https://github.com/dagster-io/dagster-cloud-action/blob/main/gitlab/serverless-ci.yml) (for **Serverless** deployments) + +In the next step, you'll modify these files to work with your Dagster+ setup. + +### Step 4.2: add the agent registry to dagster_cloud.yaml + +:::note +If you used the GitLab app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-gitlab-pipeline-runs) +::: + + +In the `dagster_cloud.yaml` file, replace `build.registry` with the registry used by the [agent you created in Step 2](#step-2-generate-a-dagster-agent-token). + +For example: + + + +### Step 4.3: configure GitLab CI/CD variables + +:::note +If you used the GitLab app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-gitlab-pipeline-runs) +::: + + +1. In your project, click the **Settings** tab. +2. In the **CI/CD** section of the sidebar, expand **Variables**. +3. Click **Add variable**. +4. In the **Key** field, enter the name of the variable. For example, `DAGSTER_CLOUD_API_TOKEN` +5. In the **Value** field, paste the value of the variable. +6. Click **Add variable**. + +Repeat steps 3-6 for each of the secrets required for your registry type: + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) +- `DOCKERHUB_USERNAME` - Your DockerHub username +- `DOCKERHUB_TOKEN` - A DockerHub [access token](https://docs.docker.com/docker-hub/access-tokens/#create-an-access-token) + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) +- `AWS_ACCESS_KEY` - The **Access key ID** of the AWS IAM user you created in [Step 3](#step-3-create-and-configure-an-agent) +- `AWS_SECRET_ACCESS_KEY` - The **Secret access key** of the AWS IAM user you created in [Step 3](#step-3-create-and-configure-an-agent) +- `AWS_REGION` - The AWS region where your ECR registry is located + + + + + +- `DAGSTER_CLOUD_API_TOKEN` - The Dagster+ agent token you created in [Step 2](#step-2-generate-a-dagster-agent-token) +- `DAGSTER_CLOUD_URL` - Your Dagster+ base URL (`https://my_org.dagster.cloud`) +- `GCR_JSON_KEY` - Your GCR JSON credentials + + + + + +### Step 4.4: configure GitLab CI/CD script + +:::note +If you used the GitLab app to configure you're repository, this step isn't required. [Skip ahead to Step 4.5](#step-45-verify-gitlab-pipeline-runs) +::: + +In this step, you'll update the GitLab CI/CD config to set up Docker registry access. + +In the `.gitlab-ci.yml` file, un-comment the `step` associated with your registry. For example, for the GitLab container registry, you'd un-comment the following portion of the `.gitlab-ci.yml` file: + +```yaml +build-image: + ... + before_script: + # For GitLab Container Registry + - echo $CI_JOB_TOKEN | docker login --username $CI_REGISTRY_USER --password-stdin $REGISTRY_URL +``` + +Save and commit the files to the project. + +### Step 4.5: verify GitLab pipeline runs + +The last step is to verify that the GitLab pipeline runs successfully. + +1. On the project page, click the **CI/CD** tab. +2. In the list of pipelines, locate the latest branch deployment run. For example: + +![Show this in the UI](/img/placeholder.svg) + + + + +Whenever the state of your branch is updated, Dagster+ expects the following steps to occur: + +1. A new image containing your code and requirements is built on the branch. Refer to [Managing code locations](/todo) to learn more. + +2. The new image is pushed to a Docker registry accessible to your agent. + +The details of how this is accomplished depend on your specific CI/CD solution. + +:::note + +The following examples assume the registry URL and image tag are stored in the `LOCATION_REGISTRY_URL` and `IMAGE_TAG` environment variables. + +::: + +### Step 4.1 Create a branch deployment associated with the branch + +Execute the following command within your CI/CD process: + + ```shell + BRANCH_DEPLOYMENT_NAME=$( + dagster-cloud branch-deployment create-or-update \ + --organization $ORGANIZATION_NAME \ + --api-token $DAGSTER_CLOUD_API_TOKEN \ # Agent token from Step 1 + --git-repo-name $REPOSITORY_NAME \ # Git repository name + --branch-name $BRANCH_NAME \ # Git branch name + --commit-hash $COMMIT_SHA \ # Latest commit SHA on the branch + --timestamp $TIMESTAMP # UTC unixtime timestamp of the latest commit + ) + ``` + +One or more additional parameters can optionally be supplied to the `create-or-update` command to enhance the Branch Deployments UI in Dagster+: + +```shell +BRANCH_DEPLOYMENT_NAME=$( + dagster-cloud branch-deployment create-or-update \ + --organization $ORGANIZATION_NAME \ + --api-token $DAGSTER_CLOUD_API_TOKEN \ + --git-repo-name $REPOSITORY_NAME \ + --branch-name $BRANCH_NAME \ + --commit-hash $COMMIT_SHA \ + --timestamp $TIMESTAMP + --code-review-url $PR_URL \ # URL to review the given changes, e.g. + # Pull Request or Merge Request + --code-review-id $INPUT_PR \ # Alphanumeric ID for the given set of changes + --pull-request-status $PR_STATUS \ # A status, one of `OPEN`, `CLOSED`, + # or `MERGED`, that describes the set of changes + --commit-message $MESSAGE \ # The message associated with the latest commit + --author-name $NAME \ # A display name for the latest commit's author + --author-email $EMAIL \ # An email for the latest commit's author + --author-avatar-url $AVATAR_URL # An avatar URL for the latest commit's author + --base-deployment-name $BASE_DEPLOYMENT_NAME # The main deployment that will be compared against. Default is 'prod' +) +``` + +If the command is being executed from the context of the git repository, you can alternatively pull this metadata from the repository itself: + +```shell +BRANCH_DEPLOYMENT_NAME=$( + dagster-cloud branch-deployment create-or-update \ + --organization $ORGANIZATION_NAME \ + --api-token $DAGSTER_CLOUD_API_TOKEN \ + --git-repo-name $REPOSITORY_NAME \ + --branch-name $BRANCH_NAME \ + --read-git-state # Equivalent to passing --commit-hash, --timestamp + # --commit-message, --author-name, --author-email +) +``` + +### Step 4.2 Deploy your code to the branch deployment + +Execute the following command within your CI/CD process: + +```shell +dagster-cloud deployment add-location \ + --organization $ORGANIZATION_NAME \ + --deployment $BRANCH_DEPLOYMENT_NAME \ + --api-token $DAGSTER_CLOUD_API_TOKEN \ + --location-file $LOCATION_FILE \ + --location-name $LOCATION_NAME \ + --image "${LOCATION_REGISTRY_URL}:${IMAGE_TAG}" \ + --commit-hash "${COMMIT_SHA}" \ + --git-url "${GIT_URL}" +``` + + + + +## Next steps + +- Learn more about [Branch Deployments](/dagster-plus/features/branch-deployments/index.mdx) +- Learn how to [Track changes on a Branch Deployment](/dagster-plus/features/branch-deployments/change-tracking) diff --git a/docs/docs-beta/docs/dagster-plus/features/branch-deployments/testing.md b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/testing.md new file mode 100644 index 0000000000000..aaf141806d021 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/branch-deployments/testing.md @@ -0,0 +1,7 @@ +--- +title: "Testing against production with branch deployments" +unlisted: true +sidebar_position: 400 +--- + +# Testing against production with branch deployments \ No newline at end of file diff --git a/docs/docs-beta/docs/dagster-plus/features/data-catalog.md b/docs/docs-beta/docs/dagster-plus/features/data-catalog.md new file mode 100644 index 0000000000000..41afe2b6a7bed --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/data-catalog.md @@ -0,0 +1,7 @@ +--- +title: "Data catalog" +unlisted: true +sidebar_position: 200 +--- + +# Dagster+ data catalog diff --git a/docs/docs-beta/docs/dagster-plus/features/insights/asset-metadata.md b/docs/docs-beta/docs/dagster-plus/features/insights/asset-metadata.md new file mode 100644 index 0000000000000..ba05db163f29d --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/insights/asset-metadata.md @@ -0,0 +1,58 @@ +--- +title: "Integrate asset metadata into Dagster+ Insights" +sidebar_label: "Integrate asset metadata" +sidebar_position: 100 +--- + +Out of the box, Dagster+ Insights gives you visibility into a variety of common metrics across your data platform. +By creating custom metrics from asset metadata, you can use Insights to perform historical aggregation on any +data your assets can emit. + +
    + Prerequisites + +To follow the steps in this guide, you'll need a Dagster+ account on the Pro plan. + +
    + +## Step 1: Emit numeric metadata on your assets at runtime + +You'll need one or more assets that emit the same metadata key at run time. Insights metrics +are most valuable when you have multiple assets that emit the same kind of metadata, such as +such as the number of rows processed or the size of a file uploaded to object storage. + +Follow [the metadata guide](/guides/build/create-a-pipeline/metadata#runtime-metadata) to add numeric metadata +to your asset materializations. + +## Step 2: Enable viewing your metadata in Dagster+ Insights + +Once your assets are emitting numeric metadata values, you'll be able to enable viewing them in the Insights UI. + +To add your metadata key to the list of metrics shown in Insights, click **Edit** in the sidebar next to the **User provided metrics** header: + +![Viewing the Insights tab in the Dagster+ UI](/img/placeholder.svg) +{/* + + + + + + + + +## Tracking usage with dagster-dbt + +If you use `dagster-dbt` to manage a dbt project that targets Google BigQuery, you can emit usage metrics to the Dagster+ API with the `DbtCliResource`. + +First, add a `.with_insights()` call to your `dbt.cli()` command(s). + + + + + + + + + + +Then, add the following to your `dbt_project.yml`: + + + + + + + + + + +This adds a comment to each query, which is used by Dagster+ to attribute cost metrics to the correct assets. diff --git a/docs/docs-beta/docs/dagster-plus/features/insights/index.md b/docs/docs-beta/docs/dagster-plus/features/insights/index.md new file mode 100644 index 0000000000000..a36a2e9513a76 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/insights/index.md @@ -0,0 +1,72 @@ +--- +title: 'Insights' +description: 'Visiblity into historical usage, cost, and metadata.' +sidebar_position: 10 +--- + +# Dagster+ Insights + +Using Dagster+ Insights, you can gain visibility into historical usage and cost metrics such as Dagster+ run duration, credit usage, and failures. You can also define your own custom metrics, such as the number of rows processed by an asset. + +Visualizations are built into the Dagster+ UI, allowing you to explore metrics from Dagster and external systems, such as Google BigQuery, in one place. + +### With Insights, you can + +- [Explore usage trends in your Dagster pipelines](#explore-dagsters-built-in-metrics) +- [Integrate additional metrics](#integrate-metrics), like data warehouse cost or your own custom metadata +- [Export metrics](#export-metrics) from Dagster+ +- [Create alerts](/dagster-plus/features/alerts) based off of Insights metrics TODO: write this alerts section + +
    + Prerequisites + +To use Insights, you'll need a Dagster+ account. + +
    + +## Explore Dagster's built-in metrics + +To access Insights, click **Insights** in the top navigation bar in the UI: + +![Viewing the Insights tab in the Dagster+ UI](/img/placeholder.svg) + +The left navigation panel on this page contains a list of available metrics. For each metric, the daily, weekly, or monthly aggregated values are displayed in the graph. + +Use the tabs above the charts to view metrics for **Assets**, **Asset groups**, **Jobs**, and **Deployments**. + +These metrics are updated on a daily basis. Refer to the [Built-in metrics](#built-in-metrics) section for more information about what Dagster provides out of the box. + +## Working with Insights metrics \{#insights-metrics} + +### Data retention + +How long historical Insights data is retained depends on your Dagster+ plan: + +- **Dagster+ Pro** - 120 days +- **All other plans** - 30 days + +### Built-in metrics + +| Metric | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Dagster credits | The Dagster credit cost associated with computing this object. Dagster credits are charged for every step that's run, and for every asset that's materialized. For more information, [refer to the pricing FAQ](https://dagster.io/pricing#faq). | +| Compute duration | The time spent computing steps. For jobs that run steps in parallel, the compute duration may be longer than the wall clock time it takes for the run to complete. | +| Materializations | The number of asset materializations associated with computing this object. | +| Observations | The number of [asset observations](/todo) associated with computing this object. | +| Step failures | The number of times steps failed when computing this object. **Note**: Steps that retry and succeed aren't included in this metric. | +| Step retries | The number of times steps were retried when computing this object. | +| Asset check warnings | The number of [asset checks](/todo) that produced warnings. | +| Asset check errors | The number of [asset checks](/todo) that produced errors. | +| Retry compute | The time spent computing steps, including time spent retrying failed steps. For jobs that run steps in parallel, the compute duration may be longer than the wall clock time it takes for the run to complete. | + +### Integrate other metrics \{#integrate-metrics} + +Users on the Pro plan can integration other metrics into Insights, such as asset materialization metadata or Snowflake credits. Insights supports the following additional metrics: + +- **Asset materialization metadata.** Refer to the [Using asset metadata with Dagster+ Insights guide](/dagster-plus/features/insights/asset-metadata) for more info. +- [**Google BigQuery usage**](/dagster-plus/features/insights/google-bigquery) generated by either queries made to BigQuery resources or using dbt to materialize tables +- [**Snowflake usage**](/dagster-plus/features/insights/snowflake) generated by either queries made to Snowflake resources or using dbt to materialize tables + +### Export metrics + +Metrics in Dagster+ Insights can be exported using a GraphQL API endpoint. Refer to the [Exporting Insights metrics from Dagster+ guide](/dagster-plus/features/insights/export-metrics) for details. diff --git a/docs/docs-beta/docs/dagster-plus/features/insights/snowflake.md b/docs/docs-beta/docs/dagster-plus/features/insights/snowflake.md new file mode 100644 index 0000000000000..ae4af2b9f1777 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/insights/snowflake.md @@ -0,0 +1,84 @@ +--- +title: "Track Snowflake usage with Dagster+ Insights" +sidebar_label: "Snowflake" +sidebar_position: 300 +--- + +Dagster allows you to track external metrics, such as Snowflake usage, in the Insights UI. Out of the box integrations are provided to capture query runtime and billed usage, and associate them with the relevant assets or jobs. + +## Requirements + +To use these features, you will need: + +- A Dagster+ account on the **Pro** plan +- Access to the [Dagster+ Insights feature](/dagster-plus/features/insights) +- Snowflake credentials which have access to the **`snowflake.account_usage.query_history`**. + - For more information, see the [Snowflake Documentation](https://docs.snowflake.com/en/sql-reference/account-usage#enabling-the-snowflake-database-usage-for-other-roles) +- The following packages installed: + +```bash +pip install dagster dagster-cloud dagster-snowflake +``` + +## Limitations + +- Up to two million individual data points may be added to Insights, per month +- External metrics data will be retained for 120 days +- Insights data may take up to 24 hours to appear in the UI + +## Tracking usage with the SnowflakeResource + +The `dagster-cloud` package provides an `InsightsSnowflakeResource`, which is a drop-in replacement for the `SnowflakeResource` provided by `dagster-snowflake`. + +This resource will emit Snowflake usage metrics to the Dagster+ Insights API whenever it makes a query. + +To enable this behavior, replace usage of `SnowflakeResource` with `InsightsSnowflakeResource`, and add Snowflake-specific insights definitions to your code using `create_snowflake_insights_asset_and_schedule`. + +These additional definitions are required because Snowflake usage information is only available after a delay. These definitions automatically handle running a computation on a schedule to ingest Snowflake usage information from the previous hour. + +:::note +Only use `create_snowflake_insights_asset_and_schedule` in a single code location per deployment, as this will handle ingesting usage data from your entire deployment. +::: + + + + + + + + + + +## Tracking usage with dagster-dbt + +If you use `dagster-dbt` to manage a dbt project that targets Snowflake, you can emit usage metrics to the Dagster+ API with the `DbtCliResource`. + +First, add a `.with_insights()` call to your `dbt.cli()` command(s), and add Snowflake-specific insights definitions to your code using `create_snowflake_insights_asset_and_schedule`. + +These additional definitions are required because Snowflake usage information is only available after a delay. These definitions automatically handle running a computation on a schedule to ingest Snowflake usage information from the previous hour. + +:::note +Only use `create_snowflake_insights_asset_and_schedule` in a single code location per deployment, as this will handle ingesting usage data from your entire deployment. +::: + + + + + + + + + + +Then, add the following to your `dbt_project.yml`: + + + + + + + + This adds a comment to each query, which is used by Dagster+ to attribute cost metrics to the correct assets. + + + diff --git a/docs/docs-beta/docs/dagster-plus/features/saved-views.md b/docs/docs-beta/docs/dagster-plus/features/saved-views.md new file mode 100644 index 0000000000000..fc06f04032485 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/features/saved-views.md @@ -0,0 +1,69 @@ +--- +title: "Saving asset filters as catalog views" +displayed_sidebar: "dagsterPlus" +sidebar_position: 100 +--- + +# Saving asset filters as catalog views + +Catalog views enable you to filter down your view of the Dagster Asset catalog in Dagster+, allowing you to toggle between sets of assets that you care about most. + +You can save catalog views for your own use or share them with your team. For example, you could create views that: + +- Filter assets based on ownership to only show those owned by your team +- Filter assets based on the asset kind to give insight into the status of your ELT ingestion +- Display assets with a "gold" medallion tag, showing only refined, high-quality data that analysts can use with confidence analysts can use with confidence + +In this guide, you'll learn how to create, access, and share catalog views with others. + +
    +Prerequisites + +- **Organization Admin**, **Admin**, or **Editor** permissions on Dagster+ +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx and [Asset metadata](/guides/build/create-a-pipeline/metadata) + +
    + + + + +## Create catalog views + +To view the Dagster+ Asset catalog, use the **Catalog** button on the top navigation. + +In any Dagster+ catalog page, you can access the current catalog view, or create a new catalog view with the catalog view button on the top left of the screen. By default, this button is labeled **All assets**, and has a globe icon. + +![Screenshot of the catalog view dropdown](/img/placeholder.svg) + +To create a new catalog view, you have two options: +1. Create a new catalog view from scratch, from the catalog view menu. +2. Create a new catalog view from your current set of filters. + +### Create a new catalog view from scratch + +1. Click the catalog view button to open the catalog view menu. From here, click the **New** button. +2. Give the view a name and optionally, a description and icon. +3. Click **Add filters** to select filters to apply to the view. Filters can select a subset of assets based on their metadata, tags, kinds, owners, asset groups, or other properties. +4. To make the view shareable, toggle the **Public view** switch. +5. Click **Create view** to create the view. + +![Screenshot of catalog view customization UI](/img/placeholder.svg) + +Give your view a name and optionally a description and icon. Next, you can select one or more filters to apply to your view by clicking the "Add filters" button. Filters can select a subset of assets based on their metadata, tags, kinds, owners, asset groups, or other properties. + +### Create a new catalog view from your current set of filters + +When viewing the global asset lineage or asset list, you can create a new catalog view from your current set of filters. + +1. On these pages, select one or more asset filters. +2. Click **Create new catalog view**, located near the top right of the page. This will open the catalog view creation dialog with your current filters pre-populated. +3. Give the view a name and optionally, a description and icon. +4. To make the view shareable, toggle the **Public view** switch. +5. Click **Create view** to create the view. + +## Edit, duplicate, or delete catalog views + +1. Click the catalog view button to open the catalog view menu. +2. Search for the view you want to edit, duplicate, or delete. +3. Click the **three dot menu** to the right of the view to display available options. +4. If modifying the view, note that any active filters will automatically be included in the set of changes. You can also change the view's name, description, icon, and sharing settings. 5. When finished, click **Save changes**. diff --git a/docs/docs-beta/docs/dagster-plus/index.md b/docs/docs-beta/docs/dagster-plus/index.md new file mode 100644 index 0000000000000..295a68941b406 --- /dev/null +++ b/docs/docs-beta/docs/dagster-plus/index.md @@ -0,0 +1,37 @@ +--- +title: "About Dagster+" +displayed_sidebar: 'dagsterPlus' +sidebar_position: 1 +--- + +# About Dagster+ + +Dagster+ is a managed orchestration platform built on top of Dagster's open source engine. + +Dagster+ is built to be the most performant, reliable, and cost effective way for data engineering teams to run Dagster in production. Dagster+ is also great for students, researchers, or individuals who want to explore Dagster with minimal overhead. + +Dagster+ comes in two flavors: a fully [Serverless](/dagster-plus/deployment/serverless) offering and a [Hybrid](/dagster-plus/deployment/hybrid) offering. In both cases, Dagster+ does the hard work of managing your data orchestration control plane. Compared to a [Dagster open source deployment](/guides/), Dagster+ manages: + +- Dagster's web UI at https://dagster.plus +- Metadata stores for data cataloging and cost insights +- Backend services for orchestration, alerting, and more + +Dagster+ Serverless is fully managed and your Dagster code executes in our environment. In Dagster+ Hybrid, you run an execution environment that connects to the Dagster+ control plane. + +In addition to managed infrastructure, Dagster+ also adds core capabilities on top of Dagster open source to enable teams building data platforms: + +- [Insights](/dagster-plus/features/insights), a powerful tool for identifying trends in your data platform overtime, optimizing cost, and answering questions like "Why does it feel like our pipelines are taking longer this month?". +- [Alerts](/dagster-plus/features/alerts) to a variety of services like Slack, PagerDuty, and email to notify your team of failed runs, data quality issues, and violated SLAs. +- Authentication, [Role Based Access Control](/dagster-plus/features/authentication-and-access-control/rbac), and [Audit Logs](/dagster-plus/features/authentication-and-access-control/rbac/audit-logs) which help teams implement data mesh strategies while remaining compliant. +- [Data Catalog](/dagster-plus/features/data-catalog), a powerful search-first experience that builds off of Dagster's best-in-class lineage graph to include searching for assets, metadata, column lineage, and more. +- [Branch Deployments](/dagster-plus/features/branch-deployments/index.mdx) + +Ready to [get started](/dagster-plus/getting-started)? + +## Other resources + +- Learn more about Dagster+ [pricing and plan types](https://dagster.io/pricing) or [contact the Dagster team](https://dagster.io/contact) +- Dagster+ includes support, [click here](https://dagster.io/support) to learn more. +- Dagster+ is HIPAA compliant, SOC 2 Type II certified, and meets GDPR requirements. Learn more about Dagster+[ security](https://dagster.io/security). +- Migrate [from a Dagster open source deployment to Dagster+](/dagster-plus/deployment/migration/self-hosted-to-dagster-plus) +- Dagster+ [status page](https://dagstercloud.statuspage.io/) diff --git a/docs/docs-beta/docs/getting-started/glossary.md b/docs/docs-beta/docs/getting-started/glossary.md new file mode 100644 index 0000000000000..8d0b5a8038b65 --- /dev/null +++ b/docs/docs-beta/docs/getting-started/glossary.md @@ -0,0 +1,19 @@ +--- +title: Glossary +sidebar_position: 30 +sidebar_label: Glossary +unlisted: true +--- + +# Glossary + +TODO - link to conceptual content about the following (and other key concepts if needed): + +* Assets +* Definitions +* Partitions (and backfills) +* Resources +* Schedules +* Sensors +* I/O managers? +* Ops and jobs (and graphs?) diff --git a/docs/docs-beta/docs/guides/automate/about-automation.md b/docs/docs-beta/docs/guides/automate/about-automation.md new file mode 100644 index 0000000000000..70f0f94643e50 --- /dev/null +++ b/docs/docs-beta/docs/guides/automate/about-automation.md @@ -0,0 +1,67 @@ +--- +title: About Automation +unlisted: true +--- + +There are several ways to automate the execution of your data pipelines with Dagster. + +The first system, and the most basic, is the [Schedule](/guides/automate/schedules), which responds to time. + +[Sensors](/guides/automate/sensors) are like schedules, but they respond to an external event defined by the user. + +[Asset Sensors](/guides/automate/asset-sensors) are a special case of sensor that responds to changes in asset materialization +as reported by the Event Log. + +Finally, the Declarative Automation system is a +more complex system that uses conditions on the assets to determine when to execute. + +## Schedules + +In Dagster, a schedule is defined by the `ScheduleDefinition` class, or through the `@schedule` decorator. The `@schedule` +decorator is more flexible than the `ScheduleDefinition` class, allowing you to configure job behavior or emit log messages +as the schedule is processed. + +Schedules were one of the first types of automation in Dagster, created before the introduction of Software-Defined Assets. +As such, you may find that many of the examples can seem foreign if you are used to only working within the asset framework. + +For more on how assets and ops inter-relate, read about [Assets and Ops](/guides/build/assets-concepts#assets-and-ops) + +The `dagster-daemon` process is responsible for submitting runs by checking each schedule at a regular interval to determine +if it's time to execute the underlying job. + +A schedule can be thought of as a wrapper around two pieces: + +- A `JobDefinition`, which is a set of assets to materialize or ops to execute. +- A `cron` string, which describes the schedule. + +### Define a schedule using `ScheduleDefinition` + +```python +ecommerce_schedule = ScheduleDefinition( + job=ecommerce_job, + cron_schedule="15 5 * * 1-5", +) +``` + +By default, schedules aren't enabled. You can enable them by visiting the Automation tab and toggling the schedule, +or set a default status to `RUNNING` when you define the schedule. + +```python +ecommerce_schedule = ScheduleDefinition( + job=ecommerce_job, + cron_schedule="15 5 * * 1-5", + default_status=DefaultScheduleStatus.RUNNING, +) +``` + +### Define a schedule using `@schedule` + +If you want more control over the schedule, you can use the `@schedule` decorator. In doing so, you are then responsible for either +emitting a `RunRequest` or a `SkipReason`. You can also emit logs, which will be visible in the Dagster UI for a given schedule's tick history. + +```python +@schedule(cron_schedule="15 5 * * 1-5") +def ecommerce_schedule(context): + context.log.info("This log message will be visible in the Dagster UI.") + return RunRequest() +``` diff --git a/docs/docs-beta/docs/guides/automate/asset-sensors.md b/docs/docs-beta/docs/guides/automate/asset-sensors.md new file mode 100644 index 0000000000000..2c71bdaca5bd3 --- /dev/null +++ b/docs/docs-beta/docs/guides/automate/asset-sensors.md @@ -0,0 +1,105 @@ +--- +title: Triggering cross-job dependencies with Asset Sensors +sidebar_position: 300 +sidebar_label: Cross-job dependencies +--- + +Asset sensors in Dagster provide a powerful mechanism for monitoring asset materializations and triggering downstream computations or notifications based on those events. + +This guide covers the most common use cases for asset sensors, such as defining cross-job and cross-code location dependencies. + +
    +Prerequisites + +To follow this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +- Familiarity with [Ops and Jobs](/guides/build/ops-jobs) + +
    + +## Getting started + +Asset sensors monitor an asset for new materialization events and target a job when a new materialization occurs. + +Typically, asset sensors return a `RunRequest` when a new job is to be triggered. However, they may provide a `SkipReason` if the asset materialization doesn't trigger a job. + +For example, you may wish to monitor an asset that's materialized daily, but don't want to trigger jobs on holidays. + +## Cross-job and cross-code location dependencies + +Asset sensors enable dependencies across different jobs and different code locations. This flexibility allows for modular and decoupled workflows. + +```mermaid +graph LR; + +AssetToWatch(AssetToWatch) --> AssetSensor(AssetSensor); +AssetSensor--> Job(Job); +Job --> Asset1(Asset1); +Job --> Asset2(Asset1); + +subgraph CodeLocationA + AssetToWatch +end + +subgraph CodeLocationB + AssetSensor + Job + Asset1 + Asset2 +end +``` + +This is an example of an asset sensor that triggers a job when an asset is materialized. The `daily_sales_data` asset is in the same code location as the job and other asset for this example, but the same pattern can be applied to assets in different code locations. + + + +## Customize evaluation logic + +You can customize the evaluation function of an asset sensor to include specific logic for deciding when to trigger a run. This allows for fine-grained control over the conditions under which downstream jobs are executed. + +```mermaid +stateDiagram-v2 + direction LR + + classDef userDefined fill: lightblue + + [*] --> AssetMaterialization + AssetMaterialization --> [*] + + AssetMaterialization --> UserEvaluationFunction:::userDefined + UserEvaluationFunction: User Evaluation Function + + UserEvaluationFunction --> RunRequest + UserEvaluationFunction --> SkipReason + SkipReason --> [*] + RunRequest --> [*] + + class UserEvaluationFunction userDefined + classDef userDefined fill: var(--theme-color-accent-lavendar) +``` + +In the following example, the `@asset_sensor` decorator defines a custom evaluation function that returns a `RunRequest` object when the asset is materialized and certain metadata is present, otherwise it skips the run. + + + +## Trigger a job with configuration + +By providing a configuration to the `RunRequest` object, you can trigger a job with a specific configuration. This is useful when you want to trigger a job with custom parameters based on custom logic you define. + +For example, you might use a sensor to trigger a job when an asset is materialized, but also pass metadata about that materialization to the job: + + + +## Monitor multiple assets + +When building a pipeline, you may want to monitor multiple assets with a single sensor. This can be accomplished with a multi-asset sensor. + +The following example uses a `@multi_asset_sensor` to monitor multiple assets and trigger a job when any of the assets are materialized: + + + +## Next steps + +- Learn more about asset sensors in [Understanding Automation](/guides/automate) +- Explore [Declarative Automation](/guides/automate/declarative-automation) as an alternative to asset sensors diff --git a/docs/docs-beta/docs/guides/automate/declarative-automation.md b/docs/docs-beta/docs/guides/automate/declarative-automation.md new file mode 100644 index 0000000000000..9a26ff8d2a427 --- /dev/null +++ b/docs/docs-beta/docs/guides/automate/declarative-automation.md @@ -0,0 +1,6 @@ +--- +title: "Declarative automation" +sidebar_label: "Declarative automation" +unlisted: true +sidebar_position: 400 +--- diff --git a/docs/docs-beta/docs/guides/automate/index.md b/docs/docs-beta/docs/guides/automate/index.md new file mode 100644 index 0000000000000..a10399054e850 --- /dev/null +++ b/docs/docs-beta/docs/guides/automate/index.md @@ -0,0 +1,237 @@ +--- +title: "Automating pipelines" +description: Learn how to automate your data pipelines. +sidebar_position: 40 +sidebar_class_name: hidden +--- + +Automation is key to building reliable, efficient data pipelines. This guide provides a simplified overview of the main ways to automate processes in Dagster, helping you choose the right method for your needs. You will find links to more detailed guides for each method below. + +
    + Prerequisites + +Before continuing, you should be familiar with: + +- [Asset definitions](/guides/build/assets-concepts/index.mdx +- [Jobs](/guides/build/ops-jobs) + +
    + +## Automation methods overview + +Dagster offers several ways to automate pipeline execution: + +1. [Schedules](#schedules) - Run jobs at specified times +2. [Sensors](#sensors) - Trigger runs based on events +3. [Asset Sensors](#asset-sensors) - Trigger jobs when specific assets materialize +4. [GraphQL Endpoint](#graphql-endpoint) - Trigger materializations and jobs from the GraphQL endpoint + +## How to choose the right automation method + +Consider these factors when selecting an automation method: + +1. **Pipeline Structure**: Are you working primarily with assets, ops, or a mix? +2. **Timing Requirements**: Do you need regular updates or event-driven processing? +3. **Data Characteristics**: Is your data partitioned? Do you need to update historical data? +4. **System Integration**: Do you need to react to external events or systems? + +Use this table to help guide your decision: + +| Method | Best For | Works With | +| ---------------------- | -------------------------------------- | ------------------- | +| Schedules | Regular, time-based job runs | Assets, Ops, Graphs | +| Sensors | Event-driven automation | Assets, Ops, Graphs | +| Declarative Automation | Asset-centric, condition-based updates | Assets only | +| Asset Sensors | Cross-job/location asset dependencies | Assets only | +| GraphQL Triggers | Event triggers from external systems | Assets, Ops, Jobs | + +## Schedules + +Schedules allow you to run jobs at specified times, like "every Monday at 9 AM" or "daily at midnight." +A schedule combines a selection of assets, known as a [Job](/guides/build/ops-jobs), and a [cron expression](https://en.wikipedia.org/wiki/Cron) +to define when the job should be run. + +To make creating cron expressions easier, you can use an online tool like [Crontab Guru](https://crontab.guru/). + +### When to use schedules + +- You need to run jobs at regular intervals +- You want basic time-based automation + +For examples of how to create schedules, see [How-To Use Schedules](/guides/automate/schedules). + +For more information about how Schedules work, see [About Schedules](/guides/automate/schedules). + +## Sensors + +Sensors allow you to trigger runs based on events or conditions that you define, like a new file arriving or an external system status change. + +You must provide a function that the sensor will use to determine if it should trigger a run. + +Like schedules, sensors operate on a selection of assets, known as [Jobs](/guides/build/ops-jobs) and can either start a pipeline through a Run or log a reason for not starting a pipeline using a SkipReason. + +### When to use sensors + +- You need event-driven automation +- You want to react to changes in external systems + +For more examples of how to create sensors, see the [How-To Use Sensors](/guides/automate/sensors) guide. + +For more information about how sensors work, see the [About Sensors](/guides/automate/sensors) concept page. + +## Asset sensors + +Asset Sensors trigger jobs when specified assets are materialized, allowing you to create dependencies between jobs or code locations. + +### When to use Asset sensors + +- You need to trigger jobs based on asset materializations +- You want to create dependencies between different jobs or code locations + +For more examples of how to create asset sensors, see the [How-To Use Asset Sensors](/guides/automate/asset-sensors) guide. + +## Declarative Automation + +{/* TODO: add content */} + + +## GraphQL Endpoint + +It is possible to trigger asset materializations in a job from external services using the GraphQL endpoint. + +### When to use the GraphQL endpoint + +- You want to integrate Dagster with an external system or tool +- You need to trigger a materialization or job over an HTTP endpoint +- You are creating a custom script for batching operations + +### Triggering a job + +To trigger a job to run using the GraphQL endpoint in Dagster, you can use the `launchRun` mutation. Here's an example using the `requests` library: + +```python +import requests + + +graphql_endpoint = "http://localhost:3000/graphql" + +query = """ +mutation LaunchRunMutation( + $repositoryLocationName: String! + $repositoryName: String! + $jobName: String! + $runConfigData: RunConfigData! +) { + launchRun( + executionParams: { + selector: { + repositoryLocationName: $repositoryLocationName + repositoryName: $repositoryName + jobName: $jobName + } + runConfigData: $runConfigData + } + ) { + __typename + ... on LaunchRunSuccess { + run { + runId + } + } + ... on RunConfigValidationInvalid { + errors { + message + reason + } + } + ... on PythonError { + message + } + } +} +""" + +response = requests.post( + graphql_endpoint, + json={ + "query": query, + "variables": { + "repositoryLocationName": "", + "repositoryName": "__repository__", # default if using `Definitions` + "jobName": "", + "runConfigData": {}, + }, + }, +) +``` + +### Triggering an asset materialization + +To trigger an asset materialization using the GraphQL endpoint in Dagster, you can use the `LaunchPipelineExecution` mutation. Here's an example using the `requests` library: + +```python +import requests + + +graphql_endpoint = "http://localhost:3000/graphql" + +query = """ +mutation LaunchPipelineExecution( + $executionParams: ExecutionParams! +) { + launchPipelineExecution(executionParams: $executionParams) { + ... on LaunchRunSuccess { + run { + id + pipelineName + __typename + } + __typename + } + ... on PipelineNotFoundError { + message + __typename + } + ... on InvalidSubsetError { + message + __typename + } + ... on RunConfigValidationInvalid { + errors { + message + __typename + } + __typename + } + } +} +""" + +response = requests.post( + graphql_endpoint, + json={ + "query": query, + "variables": { + "executionParams": { + "mode": "default", + "runConfigData": "{}", + "selector": { + "assetCheckSelection": [], + "assetSelection": [{"path": [""]}], + "pipelineName": "__ASSET_JOB", + "repositoryLocationName": "", + "repositoryName": "__repository__", + }, + } + }, + }, +) +``` + +## Next steps + +- Learn more about [advanced scheduling patterns] - {/* TODO ADD LINK */} +- Explore [complex sensor examples] - {/* TODO ADD LINK */} +- Dive into [Declarative Automation best practices] - {/* TODO ADD LINK */} + +By understanding and effectively using these automation methods, you can build more efficient data pipelines that respond to your specific needs and constraints. diff --git a/docs/docs-beta/docs/guides/automate/schedules.md b/docs/docs-beta/docs/guides/automate/schedules.md new file mode 100644 index 0000000000000..3d749758ecb87 --- /dev/null +++ b/docs/docs-beta/docs/guides/automate/schedules.md @@ -0,0 +1,64 @@ +--- +title: "Schedule cron-based pipelines" +sidebar_label: "Schedules" +sidebar_position: 100 +--- + +Schedules enable automated execution of jobs at specified intervals. These intervals can range from common frequencies like hourly, daily, or weekly, to more intricate patterns defined using cron expressions. + +
    +Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +- Familiarity with [Ops and Jobs](/guides/build/ops-jobs/index.md) +
    + +## Basic schedule + +A basic schedule is defined by a `JobDefinition` and a `cron_schedule` using the `ScheduleDefinition` class. A job can be thought of as a selection of assets or operations executed together. + + + +## Run schedules in a different timezone + +By default, schedules without a timezone will run in Coordinated Universal Time (UTC). To run a schedule in a different timezone, set the `timezone` parameter: + +```python +daily_schedule = ScheduleDefinition( + job=daily_refresh_job, + cron_schedule="0 0 * * *", + # highlight-next-line + timezone="America/Los_Angeles", +) +``` + +## Create schedules from partitions + +If using partitions and jobs, you can create a schedule using the partition with `build_schedule_from_partitioned_job`. The schedule will execute at the same cadence specified by the partition definition. + + + + +If you have a [partitioned asset](/guides/build/create-a-pipeline/partitioning) and job: + + + + + + +If you have a partitioned op job: + + + + + + +## Next steps + +By understanding and effectively using these automation methods, you can build more efficient data pipelines that respond to your specific needs and constraints: + +- Learn more about schedules in [Understanding automation](/guides/automate/index.md) +- React to events with [sensors](/guides/automate/sensors) +- Explore [Declarative Automation](/guides/automate/declarative-automation) as an alternative to schedules diff --git a/docs/docs-beta/docs/guides/automate/sensors.md b/docs/docs-beta/docs/guides/automate/sensors.md new file mode 100644 index 0000000000000..71be08e940220 --- /dev/null +++ b/docs/docs-beta/docs/guides/automate/sensors.md @@ -0,0 +1,81 @@ +--- +title: Creating event-based pipelines with sensors +sidebar_label: Event triggers +sidebar_position: 200 +--- + +Sensors enable you to trigger Dagster runs in response to events from external systems. They run at regular intervals, either triggering a run or explaining why a run was skipped. For example, you can trigger a run when a new file is added to an Amazon S3 bucket or when a database row is updated. + +:::tip +An alternative to polling with sensors is to push events to Dagster using the [Dagster API](/guides/automate#graphql-endpoint). +::: + +
    +Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +- Familiarity with [Ops and Jobs](/guides/build/ops-jobs) +
    + +## Basic sensor + +Sensors are defined with the `@sensor` decorator. The following example includes a `check_for_new_files` function that simulates finding new files. In a real scenario, this function would check an actual system or directory. + +If the sensor finds new files, it starts a run of `my_job`. If not, it skips the run and logs `No new files found` in the Dagster UI. + + + +:::tip +Unless a sensor has a `default_status` of `DefaultSensorStatus.RUNNING`, it won't be enabled when first deployed to a Dagster instance. To find and enable the sensor, click **Automation > Sensors** in the Dagster UI. +::: + +## Customizing intervals between evaluations + +The `minimum_interval_seconds` argument allows you to specify the minimum number of seconds that will elapse between sensor evaluations. This means that the sensor won't be evaluated more frequently than the specified interval. + +It's important to note that this interval represents a minimum interval between runs of the sensor and not the exact frequency the sensor runs. If a sensor takes longer to complete than the specified interval, the next evaluation will be delayed accordingly. + +```python +# Sensor will be evaluated at least every 30 seconds +@dg.sensor(job=my_job, minimum_interval_seconds=30) +def new_file_sensor(): + ... +``` + +In this example, if the `new_file_sensor`'s evaluation function takes less than a second to run, you can expect the sensor to run consistently around every 30 seconds. However, if the evaluation function takes longer, the interval between evaluations will be longer. + +## Preventing duplicate runs + +To prevent duplicate runs, you can use run keys to uniquely identify each `RunRequest`. In the [previous example](#basic-sensor), the `RunRequest` was constructed with a `run_key`: + +``` +yield dg.RunRequest(run_key=filename) +``` + +For a given sensor, a single run is created for each `RunRequest` with a unique `run_key`. Dagster will skip processing requests with previously used run keys, ensuring that duplicate runs won't be created. + +## Cursors and high volume events + +When dealing with a large number of events, you may want to implement a cursor to optimize sensor performance. Unlike run keys, cursors allow you to implement custom logic that manages state. + +The following example demonstrates how you might use a cursor to only create `RunRequests` for files in a directory that have been updated since the last time the sensor ran. + + + +For sensors that consume multiple event streams, you may need to serialize and deserialize a more complex data structure in and out of the cursor string to keep track of the sensor's progress over the multiple streams. + +:::note +The preceding example uses both a `run_key` and a cursor, which means that if the cursor is reset but the files don't change, new runs won't be launched. This is because the run keys associated with the files won't change. + +If you want to be able to reset a sensor's cursor, don't set `run_key`s on `RunRequest`s. +::: + +## Next steps + +By understanding and effectively using these automation methods, you can build more efficient data pipelines that respond to your specific needs and constraints. + +- Run pipelines on a [schedule](/guides/automate/schedules) +- Trigger cross-job dependencies with [asset sensors](/guides/automate/asset-sensors) +- Explore [Declarative Automation](/guides/automate/declarative-automation) as an alternative to sensors diff --git a/docs/docs-beta/docs/guides/build/assets-concepts/asset-dependencies.md b/docs/docs-beta/docs/guides/build/assets-concepts/asset-dependencies.md new file mode 100644 index 0000000000000..20495ba819d7f --- /dev/null +++ b/docs/docs-beta/docs/guides/build/assets-concepts/asset-dependencies.md @@ -0,0 +1,119 @@ +--- +title: Pass data between assets +description: Learn how to pass data between assets in Dagster +sidebar_position: 200 +--- + +In Dagster, assets are the building blocks of your data pipeline and it's common to want to pass data between them. This guide will help you understand how to pass data between assets. + +There are three ways of passing data between assets: + +- Explicitly managing data, by using external storage +- Implicitly managing data, using I/O managers +- Avoiding passing data between assets altogether by combining several tasks into a single asset + +This guide walks through all three methods. + +--- + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- A basic understanding of Dagster concepts such as assets and resources +- Dagster and the `dagster-duckdb-pandas` package installed +
    + +--- + +## Move data assets explicitly using external storage + +A common and recommended approach to passing data between assets is explicitly managing data using external storage. This example pipeline uses a SQLite database as external storage: + + + +In this example, the first asset opens a connection to the SQLite database and writes data to it. The second asset opens a connection to the same database and reads data from it. The dependency between the first asset and the second asset is made explicit through the asset's `deps` argument. + +The benefits of this approach are: + +- It's explicit and easy to understand how data is stored and retrieved +- You have maximum flexibility in terms of how and where data is stored, for example, based on environment + +The downsides of this approach are: + +- You need to manage connections and transactions manually +- You need to handle errors and edge cases, for example, if the database is down or if a connection is closed + +## Move data between assets implicitly using I/O managers + +Dagster's I/O managers are a powerful feature that manages data between assets by defining how data is read from and written to external storage. They help separate business logic from I/O operations, reducing boilerplate code and making it easier to change where data is stored. + +I/O managers handle: + +1. **Input**: Reading data from storage and loading it into memory for use by dependent assets. +2. **Output**: Writing data to the configured storage location. + +For a deeper understanding of I/O managers, check out the [Understanding I/O managers](/guides/build/configure/io-managers) guide. + + + +In this example, a `DuckDBPandasIOManager` is instantiated to run using a local file. The I/O manager handles both reading and writing to the database. + +:::warning + +This example works for local development, but in a production environment +each step would execute in a separate environment and would not have access to the same file system. Consider a cloud-hosted environment for production purposes. + +::: + +The `people()` and `birds()` assets both write their dataframes to DuckDB +for persistent storage. The `combined_data()` asset requests data from both assets by adding them as parameters to the function, and the I/O manager handles the reading them from DuckDB and making them available to the `combined_data` function as dataframes. **Note**: When you use I/O managers you don't need to manually add the asset's dependencies through the `deps` argument. + +The benefits of this approach are: + +- The reading and writing of data is handled by the I/O manager, reducing boilerplate code +- It's easy to swap out different I/O managers based on environments without changing the underlying asset computation + +The downsides of this approach are: + +- The I/O manager approach is less flexible should you need to customize how data is read or written to storage +- Some decisions may be made by the I/O manager for you, such as naming conventions that can be hard to override. + +## Avoid passing data between assets by combining assets + +In some cases, you may find that you can avoid passing data between assets by +carefully considering how you have modeled your pipeline: + +Consider this example: + + + +This example downloads a zip file from Google Drive, unzips it, and loads the data into a Pandas DataFrame. It relies on each asset running on the same file system to perform these operations. + +The assets are modeled as tasks, rather than as data assets. For more information on the difference between tasks and data assets, check out the [assets guide](/guides/build/assets-concepts/index.md). + +In this refactor, the `download_files`, `unzip_files`, and `load_data` assets are combined into a single asset, `my_dataset`. This asset downloads the files, unzips them, and loads the data into a data warehouse. + + + +This approach still handles passing data explicitly, but no longer does it across assets, +instead within a single asset. This pipeline still assumes enough disk and +memory available to handle the data, but for smaller datasets, it can work well. + +The benefits of this approach are: + +- All the computation that defines how an asset is created is contained within a single asset, making it easier to understand and maintain +- It can be faster than relying on external storage, and doesn't require the overhead of setting up additional compute instances. + +The downsides of this approach are: + +- It makes certain assumptions about how much data is being processed +- It can be difficult to reuse functions across assets, since they're tightly coupled to the data they produce +- It may not always be possible to swap functionality based on the environment you are running in. For example, if you are running in a cloud environment, you may not have access to the local file system. + +--- + +## Related resources + +{/* TODO: add links to relevant API documentation here. */} diff --git a/docs/docs-beta/docs/guides/build/assets-concepts/asset-factories-with-deps.md b/docs/docs-beta/docs/guides/build/assets-concepts/asset-factories-with-deps.md new file mode 100644 index 0000000000000..07de1116baee6 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/assets-concepts/asset-factories-with-deps.md @@ -0,0 +1,36 @@ +--- +title: 'Programmatically defining dependencies using asset factories' +sidebar_position: 400 +sidebar_label: 'Asset Factories (2)' +--- + +In data engineering, it's often helpful to reuse code to define similar assets. For example, you may want to represent every file in a directory as an asset. + +Additionally, you may be serving stakeholders who aren't familiar with Python or Dagster. They may prefer interacting with assets using a domain-specific language (DSL) built on top of a configuration language such as YAML. + +Using an asset factory reduces complexity and creates a pluggable entry point to define additional assets. + +
    + Prerequisites + +This guide builds upon the concepts in the [asset factories](/guides/build/configure/asset-factories) tutorial. +
    + +--- + +## Building an asset factory in Python + +Imagine a data analytics team that maintains a large number of tables. To support analytics needs, the team runs queries and constructs new tables from the results. + +Each table can be represented in YAML by a name, upstream asset dependencies, and a query: + + +Here's how you might add Python logic to define these assets in Dagster. + + + +## Defining dependencies between factory assets and regular assets + +Here's how you might add Python logic to define a Dagster asset downstream of factory assets: + + diff --git a/docs/docs-beta/docs/guides/build/assets-concepts/asset-materialization.md b/docs/docs-beta/docs/guides/build/assets-concepts/asset-materialization.md new file mode 100644 index 0000000000000..4bb472f5c7884 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/assets-concepts/asset-materialization.md @@ -0,0 +1,7 @@ +--- +title: "Asset materialization" +sidebar_position: 300 +unlisted: true +--- + +# Asset materialization diff --git a/docs/docs-beta/docs/guides/build/assets-concepts/asset-metadata.md b/docs/docs-beta/docs/guides/build/assets-concepts/asset-metadata.md new file mode 100644 index 0000000000000..276b764359664 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/assets-concepts/asset-metadata.md @@ -0,0 +1,7 @@ +--- +title: "Asset metadata" +sidebar_position: 100 +unlisted: true +--- + +# Asset metadata diff --git a/docs/docs-beta/docs/guides/build/assets-concepts/index.md b/docs/docs-beta/docs/guides/build/assets-concepts/index.md new file mode 100644 index 0000000000000..9e2f302b468a0 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/assets-concepts/index.md @@ -0,0 +1,11 @@ +--- +title: "Assets concepts" +sidebar_position: 40 +sidebar_class_name: hidden +--- + +TODO + +## Assets and ops + +Assets and ops are two different concepts in Dagster. For more information, see "[Ops vs assets](/guides/build/ops-jobs/ops-vs-assets)". diff --git a/docs/docs-beta/docs/guides/build/assets-concepts/selection-syntax.md b/docs/docs-beta/docs/guides/build/assets-concepts/selection-syntax.md new file mode 100644 index 0000000000000..1676ed5af6a80 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/assets-concepts/selection-syntax.md @@ -0,0 +1,352 @@ +--- +title: 'Asset selection syntax' +sidebar_position: 500 +sidebar_label: 'Asset selection syntax' +--- + +# Asset selection syntax + +This reference contains information about the syntax for asset selections, including a variety of examples for selecting assets and their downstream and upstream dependencies. + +Asset selection may be used to: + +- Define a job that targets a selection of assets +- Select a set of assets to view in the Dagster UI +- Select a set of assets for an adhoc run + +## Syntax usage + +A query includes a list of clauses. Clauses are separated by commas, except in the case of the `selection` parameter of the following methods. In these cases, each clause is a separate element in a list: + +- `define_asset_job` +- `materialize` +- `materialize_to_memory` + +| Clause syntax | Description | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ASSET_KEY` | Selects a single asset by asset key. [See an example](#single-asset). | +| `COMPONENT/COMPONENT` | Selects an asset key with multiple components, such as a prefix, where slashes (`/`) are inserted between components. [See an example](#multiple-key-components). | +| `*ASSET_KEY` | Selects an asset and all of its upstream dependencies. [See an example](#all-upstream). | +| `ASSET_KEY*` | Selects an asset and all of its downstream dependencies. [See an example](#all-downstream). | +| `+ASSET_KEY` | Selects an asset and one layer upstream of the asset. Including multiple `+`s will select that number of upstream layers from the asset. Any number of `+`s is supported. [See an example](#specific-upstream). | +| `ASSET_KEY+` | Selects an asset and one layer downstream of the asset. Including multiple `+`s will select that number of downstream layers from the asset. Any number of `+`s is supported. [See an example](#specific-downstream). | + +## Examples + +The examples in this section use the following asset graph from the [Dagster University Essentials project](https://github.com/dagster-io/project-dagster-university) to demonstrate how to use the selection syntax: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + +### Selecting a single asset \{#single-asset} + +To select a single asset, use the asset's asset key. This example selects the `taxi_zones_file` asset: + + + + +```python +raw_data_job = define_asset_job(name="raw_data_job", selection="taxi_zones_file") +``` + + + + +```shell +dagster asset list --select taxi_zones_file +dagster asset materialize --select taxi_zones_file +``` + + + + +```shell +taxi_zones_file +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +--- + +### Selecting assets with multiple key components \{#multiple-key-components} + +To select an asset with a key containing multiple components, such as a prefix, insert slashes (`/`) between the components. + +This example selects the `manhattan/manhattan_stats` asset, which is defined below: + +```python +@asset( + deps=[AssetKey(["taxi_trips"]), AssetKey(["taxi_zones"])], key_prefix="manhattan" +) +def manhattan_stats(database: DuckDBResource): + ... +``` + + + + +```python +manhattan_job = define_asset_job(name="manhattan_job", selection="manhattan/manhattan_stats") +``` + + + + +```shell +dagster asset list --select manhattan/manhattan_stats +dagster asset materialize --select manhattan/manhattan_stats +``` + + + + +```shell +manhattan/manhattan_stats +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +--- + +### Selecting multiple assets \{#multiple-assets} + +To select multiple assets, use a list of the assets' asset keys. The assets don't have to be dependent on each other. + +This example selects the `taxi_zones_file` and `taxi_trips_file` assets, which are defined below: + + + + +```python +raw_data_job = define_asset_job( + name="taxi_zones_job", selection=["taxi_zones_file", "taxi_trips_file"] +) +``` + + + + +When selecting multiple assets, enclose the list of asset keys in double quotes (`"`) and separate each asset key with a comma: + +```shell +dagster asset list --select "taxi_zones_file,taxi_trips_file" +dagster asset materialize --select "taxi_zones_file,taxi_trips_file" +``` + + + + +```shell +taxi_zones_file taxi_trips_file +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +--- + +### Selecting an asset's entire lineage \{#full-lineage} + +To select an asset's entire lineage, add an asterisk (`*`) before and after the asset key in the query. + +This example selects the entire lineage for the `taxi_zones` asset. + + + + +```python +taxi_zones_job = define_asset_job(name="taxi_zones_job", selection="*taxi_zones*") +``` + + + + +When selecting an asset's entire lineage using the CLI, enclose the asterisk (`*`) and the asset key in double quotes (`"`): + +```shell +dagster asset list --select "*taxi_zones*" +dagster asset materialize --select "*taxi_zones*" +``` + + + + +```shell +*taxi_zones* +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +--- + +### Selecting upstream dependencies + +#### Selecting all upstream dependencies \{#all-upstream} + +To select an asset and all its upstream dependencies, add an asterisk (`*`) before the asset key in the query. + +This example selects the `manhattan_map` asset and all its upstream dependencies. + + + + +```python +manhattan_job = define_asset_job(name="manhattan_job", selection="*manhattan_map") +``` + + + + +When selecting an asset's dependencies using the CLI, enclose the asterisk (`*`) and the asset key in double quotes (`"`): + +```shell +dagster asset list --select "*manhattan_map" +dagster asset materialize --select "*manhattan_map" +``` + + + + +```shell +*manhattan_map +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +#### Selecting a specific number of upstream layers \{#specific-upstream} + +To select an asset and multiple upstream layers, add a plus sign (`+`) for each layer you want to select before the asset key in the query. + +This example selects the `manhattan_map` asset and two upstream layers. + + + + +```python +manhattan_job = define_asset_job(name="manhattan_job", selection="++manhattan_map") +``` + + + + +When selecting an asset's dependencies using the CLI, enclose the plus sign (`+`) and the asset key in double quotes (`"`): + +```shell +dagster asset list --select "++manhattan_map" +dagster asset materialize --select "++manhattan_map" +``` + + + + +```shell +++manhattan_map +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +--- + +### Selecting downstream dependencies + +#### Selecting all downstream dependencies \{#all-downstream} + +To select an asset and all its downstream dependencies, add an asterisk (`*`) after the asset key in the query. + +This example selects the `taxi_zones_file` asset and all its downstream dependencies. + + + + +```python +taxi_zones_job = define_asset_job(name="taxi_zones_job", selection="taxi_zones_file*") +``` + + + + +When selecting an asset's dependencies using the CLI, enclose the asterisk (`*`) and the asset key in double quotes (`"`): + +```shell +dagster asset list --select "taxi_zones_file*" +dagster asset materialize --select "taxi_zones_file*" +``` + + + + +```shell +taxi_zones_file* +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + + +#### Selecting a specific number of downstream layers \{#specific-downstream} + +To select an asset and multiple downstream layers, add plus sign (`+`) for each layer you want to select after the asset key in the query. + +This example selects the `taxi_trips_file` asset and two downstream layers. + + + + +```python +taxi_zones_job = define_asset_job(name="taxi_zones_job", selection="taxi_zones_file++") +``` + + + + +When selecting an asset's dependencies using the CLI, enclose the plus sign (`+`) and the asset key in double quotes (`"`): + +```shell +dagster asset list --select "taxi_zones_file++" +dagster asset materialize --select "taxi_zones_file++" +``` + + + + +```shell +taxi_zones_file++ +``` + +Which would result in the following asset graph: + +![Screenshot of Daggy U project graph](/img/placeholder.svg) + + + diff --git a/docs/docs-beta/docs/guides/build/backfill.md b/docs/docs-beta/docs/guides/build/backfill.md new file mode 100644 index 0000000000000..8dbffbfc8197e --- /dev/null +++ b/docs/docs-beta/docs/guides/build/backfill.md @@ -0,0 +1,6 @@ +--- +title: Backfilling data +sidebar_label: "Backfilling" +unlisted: true +sidebar_position: 200 +--- diff --git a/docs/docs-beta/docs/guides/build/configure/apis.md b/docs/docs-beta/docs/guides/build/configure/apis.md new file mode 100644 index 0000000000000..005a19ae99c50 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/apis.md @@ -0,0 +1,70 @@ +--- +title: Connecting to APIs +sidebar_position: 600 +sidebar_label: API connections +--- + +When building a data pipeline, you'll likely need to connect to several external APIs, each with its own specific configuration and behavior. This guide demonstrates how to standardize your API connections and customize their configuration using Dagster resources. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +- Familiarity with [Resources](/guides/build/configure/resources) +- To install the `requests` library: + ```bash + pip install requests + ``` + +
    + +## Step 1: Write a resource that connects to an API + +This example fetches the sunrise time for a given location from a REST API. + +Using `ConfigurableResource`, define a Dagster resource with a method that returns the sunrise time for a location. In the first version of this resource, the location is hard-coded to San Francisco International Airport. + + + +## Step 2: Use the resource in an asset + +To use the resource, provide it as a parameter to an asset and include it in the `Definitions` object: + + + +When you materialize `sfo_sunrise`, Dagster will provide an initialized `SunResource` to the `sun_resource` parameter. + +## Step 3: Configure the resource + +Many APIs have configuration you can set to customize your usage. The following example updates the resource with configuration to allow for setting the query location: + + + +The configurable resource can be provided to an asset exactly as before. When the resource is initialized, you can pass values for each of the configuration options. + +When you materialize `sfo_sunrise`, Dagster will provide a `SunResource` initialized with the configuration values to the `sun_resource` parameter. + +## Step 4: Source configuration using environment variables + +Resources can also be configured with environment variables. You can use Dagster's built-in `EnvVar` class to source configuration values from environment variables at materialization time. + +In this example, there's a new `home_sunrise` asset. Rather than hard-coding the location of your home, you can set it in environment variables and configure the `SunResource` by reading those values: + + + +When you materialize `home_sunrise`, Dagster will read the values set for the `HOME_LATITUDE`, `HOME_LONGITUDE`, and `HOME_TIMZONE` environment variables and initialize a `SunResource` with those values. + +The initialized `SunResource` will be provided to the `sun_resource` parameter. + +:::note +You can also fetch environment variables using the `os` library. Dagster treats each approach to fetching environment variables differently, such as when they're fetched or how they display in the UI. Refer to the [Environment variables guide](/todo) for more information. +::: + +## Next steps + +- [Authenticate to a resource](/todo) +- [Use different resources in different execution environments](/todo) +- [Set environment variables in Dagster+](/todo) +- Learn what [Dagster-provided resources](/todo) are available diff --git a/docs/docs-beta/docs/guides/build/configure/asset-factories.md b/docs/docs-beta/docs/guides/build/configure/asset-factories.md new file mode 100644 index 0000000000000..9f7c3e687cb37 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/asset-factories.md @@ -0,0 +1,72 @@ +--- +title: 'Creating domain-specific languages with asset factories' +sidebar_position: 300 +sidebar_label: 'Asset factories' +--- + +Often in data engineering, you'll find yourself needing to create a large number of similar assets. For example: + +- A set of database tables all have the same schema +- A set of files in a directory all have the same format + +It's also possible you're serving stakeholders who aren't familiar with Python or Dagster. They may prefer interacting with assets using a domain-specific language (DSL) built on top of a configuration language such as YAML. + +The asset factory pattern can solve both of these problems. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with: + - [Assets](/guides/build/create-a-pipeline/data-assets) + - [Resources](/guides/build/configure/resources) + - SQL, YAML and Amazon Web Services (AWS) S3 + - [Pydantic](https://docs.pydantic.dev/latest/) and [Jinja2](https://jinja.palletsprojects.com/en/3.1.x/) +- A Python virtual environment with the following dependencies installed: + + ```bash + pip install dagster dagster-aws duckdb pyyaml pydantic + ``` +
    + +## Building an asset factory in Python + +Let's imagine a team that often has to perform the same repetitive ETL task: download a CSV file from S3, run a basic SQL query on it, and then upload the result as a new file back to S3. + +To automate this process, you might define an asset factory in Python like the following: + + + +The asset factory pattern is essentially a function that takes in some configuration and returns `dg.Definitions`. + +## Configuring an asset factory with YAML + +Now, the team wants to be able to configure the asset factory using YAML instead of Python, with a file like this: + + + +To implement this, parse the YAML file and use it to create the S3 resource and ETL jobs: + + + +## Improving usability with Pydantic and Jinja + +There are a few problems with the current approach: + +1. **The YAML file isn't type-checked**, so it's easy to make mistakes that will cause cryptic `KeyError`s +2. **The YAML file contains secrets**. Instead, it should reference environment variables. + +To solve these problems, you can use Pydantic to define a schema for the YAML file and Jinja to template the YAML file with environment variables. + +Here's what the new YAML file might look like. Note how Jinja templating is used to reference environment variables: + + + +And the Python implementation: + + + +## Next steps + +TODO diff --git a/docs/docs-beta/docs/guides/build/configure/authentication.md b/docs/docs-beta/docs/guides/build/configure/authentication.md new file mode 100644 index 0000000000000..6dc4fb4c0f305 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/authentication.md @@ -0,0 +1,5 @@ +--- +title: Authenticating to a resource +sidebar_position: 700 +unlisted: true +--- diff --git a/docs/docs-beta/docs/guides/build/configure/configuring-assets.md b/docs/docs-beta/docs/guides/build/configure/configuring-assets.md new file mode 100644 index 0000000000000..da028f5761cc6 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/configuring-assets.md @@ -0,0 +1,48 @@ +--- +title: Configuring assets +sidebar_label: Asset runs +sidebar_position: 100 +--- + +The Dagster UI is commonly used to manually materialize assets, backfill historical data, debug a production issue, or some other one-off task. + +You'll often want to be able to adjust parameters when materializing assets, which can be accomplished with Dagster's asset configuration system. + +
    + Prerequisites + +To follow the steps in this guide, you'll need familiarity with: + +- [Assets](/guides/build/create-a-pipeline/data-assets) +- [Pydantic](https://docs.pydantic.dev/latest/) + +
    + +## Making assets configurable + +For an asset to be configurable, first define a schema that inherits from the Dagster `Config` class. + +For example, you want to allow your team to change the lookback time window for the computation that materializes an asset: + + + +## Specifying config using the Dagster UI + +:::note +Run configurations reference an `op` which is the underlying compute associated with an asset. Refer to the [Ops vs Assets](/guides/build/ops-jobs/ops-vs-assets) guide for more information. +::: + +When launching a run using the Launchpad in the UI, you can provide a run config file as YAML or JSON that overrides the default configuration for your asset. + +On any page with a **Materialize** button, click the **options menu > Open launchpad** to access the Launchpad: + +![Highlighted Open Launchpad option in the Materialize options menu of the Dagster UI](/img/placeholder.svg) + +This will open the Launchpad, where you can scaffold the config, customize its values, and manually materialize the asset: + +![Dagster Launchpad that configures an asset to have a lookback window of 7 days](/img/placeholder.svg) + +## Next steps + +- Learn more about Dagster [assets](/guides/build/assets-concepts/index.mdx +- Connect to external [APIs](/guides/build/configure/apis) and [databases](/guides/build/configure/databases) with resources diff --git a/docs/docs-beta/docs/guides/build/configure/databases.md b/docs/docs-beta/docs/guides/build/configure/databases.md new file mode 100644 index 0000000000000..84132316e9c87 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/databases.md @@ -0,0 +1,63 @@ +--- +title: Connecting to databases +description: How to configure resources to connect to databases +sidebar_position: 500 +sidebar_label: Database connections +--- + +When building a data pipeline, you may need to extract data from or load data into a database. In Dagster, resources can be used to connect to a database by acting as a wrapper around a database client. + +This guide demonstrates how to standardize database connections and customize their configuration using Dagster resources. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/create-a-pipeline/data-assets) + +To run the examples in this guide, you'll need: + +- Connection information for a Snowflake database +- To install the following: + + ```bash + pip install dagster dagster-snowflake pandas + ``` + +
    + +## Step 1: Write a resource \{#step-one} + +This example creates a resource that represents a Snowflake database. Using `SnowflakeResource`, define a Dagster resource that connects to a Snowflake database: + + + +## Step 2: Use the resource in an asset \{#step-two} + +To use the resource, provide it as a parameter to an asset and include it in the `Definitions` object: + + + +When you materialize these assets, Dagster will provide an initialized `SnowflakeResource` to the assets' `iris_db` parameter. + +## Step 3: Source configuration with environment variables \{#step-three} + +Resources can be configured using environment variables, allowing you to connect to environment-specific databases, swap credentials, and so on. You can use Dagster's built-in `EnvVar` class to source configuration values from environment variables at asset materialization time. + +In this example, a second instance of the Snowflake resource, named `production` has been added: + + + +When the assets are materialized, Dagster will use the `deployment_name` environment variable to determine which Snowflake resource to use (`local` or `production`). Then, Dagster will read the values set for each resource's environment variables (ex: `DEV_SNOWFLAKE_PASSWORD`) and initialize a `SnowflakeResource` with those values. + +The initialized `SnowflakeResource` will be provided to the assets' `iris_db` parameter. + +:::note +You can also fetch environment variables using the `os` library. Dagster treats each approach to fetching environment variables differently, such as when they're fetched or how they display in the UI. Refer to the [Environment variables guide](/todo) for more information. +::: + +## Next steps + +- Explore how to use resources for [Connecting to APIs](/guides/build/configure/apis) +- Go deeper into [Understanding Resources](/guides/build/configure/resources) \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/configure/index.mdx b/docs/docs-beta/docs/guides/build/configure/index.mdx new file mode 100644 index 0000000000000..69dae1c64cc29 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/index.mdx @@ -0,0 +1,9 @@ +--- +title: "Configure" +description: "Configure assets, pipelines, and runs" +sidebar_position: 20 +--- + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/configure/io-managers.md b/docs/docs-beta/docs/guides/build/configure/io-managers.md new file mode 100644 index 0000000000000..c64f4a909d995 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/io-managers.md @@ -0,0 +1,88 @@ +--- +title: "Managing stored data with I/O managers" +sidebar_position: 800 +sidebar_label: "I/O managers" +--- + +I/O managers in Dagster allow you to keep the code for data processing separate from the code for reading and writing data. This reduces repetitive code and makes it easier to change where your data is stored. + +In many Dagster pipelines, assets can be broken down as the following steps: + +1. Reading data a some data store into memory +2. Applying in-memory transform +3. Writing the transformed data to a data store + +For assets that follow this pattern, an I/O manager can streamline the code that handles reading and writing data to and from a source. + +
    +Prerequisites + +To follow the steps in this guide, you'll need familiarity with: + +- [Assets](/guides/build/assets-concepts/index.mdx +- [Resources](/guides/build/configure/resources) +
    + +## Before you begin + +**I/O managers aren't required to use Dagster, nor are they the best option in all scenarios.** If you find yourself writing the same code at the start and end of each asset to load and store data, an I/O manager may be useful. For example: + +- You have assets that are stored in the same location and follow a consistent set of rules to determine the storage path +- You have assets that are stored differently in local, staging, and production environments +- You have assets that load upstream dependencies into memory to do the computation + +**I/O managers may not be the best fit if:** + +- You want to run SQL queries that create or update a table in a database +- Your pipeline manages I/O on its own by using other libraries/tools that write to storage +- Your assets won't fit in memory, such as a database table with billions of rows + +As a general rule, if your pipeline becomes more complicated in order to use I/O managers, it's likely that I/O managers aren't a good fit. In these cases you should use `deps` to [define dependencies](/guides/build/assets-concepts/asset-dependencies). + +## Using I/O managers in assets \{#io-in-assets} + +Consider the following example, which contains assets that construct a DuckDB connection object, read data from an upstream table, apply some in-memory transform, and write the result to a new table in DuckDB: + + + +Using an I/O manager would remove the code that reads and writes data from the assets themselves, instead delegating it to the I/O manager. The assets would be left only with the code that applies transformations or retrieves the initial CSV file. + + + +To load upstream assets using an I/O manager, specify the asset as an input parameter to the asset function. In this example, the `DuckDBPandasIOManager` I/O manager will read the DuckDB table with the same name as the upstream asset (`raw_sales_data`) and pass the data to `clean_sales_data` as a Pandas DataFrame. + +To store data using an I/O manager, return the data in the asset function. The returned data must be a valid type. This example uses Pandas DataFrames, which the `DuckDBPandasIOManager` will write to a DuckDB table with the same name as the asset. + +Refer to the individual I/O manager documentation for details on valid types and how they store data. + +## Swapping data stores \{#swap-data-stores} + +With I/O managers, swapping data stores consists of changing the implementation of the I/O manager. The asset definitions, which only contain transformational logic, won't need to change. + +In the following example, a Snowflake I/O manager replaced the DuckDB I/O manager. + + + +## Built-in I/O managers \{#built-in} + +Dagster offers built-in library implementations for I/O managers for popular data stores and in-memory formats. + +| Name | Description | +| ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- | +| | Default I/O manager. Stores outputs as pickle files on the local file system. | +| | Stores outputs in memory. Primarily useful for unit testing. | +| | Stores outputs as pickle files in Amazon Web Services S3. | +| | Stores outputs as pickle files in Azure ADLS2. | +| | Stores outputs as pickle files in Google Cloud Platform GCS. | +| | Stores Pandas DataFrame outputs in Google Cloud Platform BigQuery. | +| | Stores PySpark DataFrame outputs in Google Cloud Platform BigQuery. | +| | Stores Pandas DataFrame outputs in Snowflake. | +| | Stores PySpark DataFrame outputs in Snowflake. | +| | Stores Pandas DataFrame outputs in DuckDB. | +| | Stores PySpark DataFrame outputs in DuckDB. | +| | Stores Polars DataFrame outputs in DuckDB. | | + +## Next steps + +- Learn to [connect databases](/guides/build/configure/databases) with resources +- Learn to [connect APIs](/guides/build/configure/apis) with resources \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/configure/managing-concurrency.md b/docs/docs-beta/docs/guides/build/configure/managing-concurrency.md new file mode 100644 index 0000000000000..59efe3ac2fe5d --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/managing-concurrency.md @@ -0,0 +1,172 @@ +--- +title: Managing concurrency of Dagster assets, jobs, and Dagster instances +sidebar_label: Managing concurrency +description: How to limit the number of runs a job, or assets for an instance of Dagster. +sidebar_position: 900 +--- + +You often want to control the number of concurrent runs for a Dagster job, a specific asset, or for a type of asset or job. Limiting concurrency in your data pipelines can help prevent performance problems and downtime. + + +
    +Prerequisites + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +- Familiarity with [Jobs and Ops](/guides/build/ops-jobs) +
    + + + +## Limit how many jobs can be running at the same time + + +* Dagster Core, add the following to your [dagster.yaml](/todo) +* In Dagster+, add the following to your [deployment settings](/dagster-plus/deployment/deployment-settings) + +```yaml +run_queue: + max_concurrent_runs: 15 +``` + + + + +## Limit how many ops or assets can be running at the same time + +You can control the number of assets or ops that are running concurrently within a job using the `config` argument of `dg.define_asset_job()` or `dg.@job()` for ops. + + + + + + + + + + + + + + +## Limit how many of a certain type of op or asset can run across all runs + +You can a limit for all ops or assets with a specific tag key or key-value pair. Ops or assets above that limit will be queued. Use `tag_concurrency_limits` in the job's config, either in Python or using the Launchpad in the Dagster UI. + +For example, you might want to limit the number of ops or assets that are running with a key of `database` across all runs (to limit the load on that database). + +:::warning +This feature is experimental and is only supported with Postgres/MySQL storage. +::: + + +```yaml +# dagster.yaml for Dagster Core; Deployment Settings for Dagster+ +run_coordinator: + module: dagster.core.run_coordinator + class: QueuedRunCoordinator + config: + tag_concurrency_limits: + - key: "dagster/concurrency_key" + value: "database" + limit: 1 +``` + +To specify a global concurrency limit using the CLI, use: + +``` +dagster instance concurrency set database 1 +``` + +A default concurrency limit can be configured for the instance, for any concurrency keys that don't have an explicit limit set: + +* Dagster+: Use the Dagster+ UI or the dagster-cloud CLI +* Dagster Open Source: Use your instance's dagster.yaml + +To enable this default value, use `concurrency.default_op_concurrency_limit`. For example, the following would set the default concurrency value for the deployment to 1: +```yaml +concurrency: + default_op_concurrency_limit: 1 +``` + + + + + + + + + + + + +You can also limit concurrency for a tag within the job definition, for example to limit the number of specific assets running at the same time *within* that run. + + + + + + + + + + + + +## Override job level concurrency in the Launchpad + +You can override the default job-level settings, such as the value of the `max_concurrent` key for a job, by launching a job in the Launchpad in the Dagster UI. + +Need screenshot here + +## Prevent runs from starting if another run is already occurring (advanced) + +You can use Dagster's rich metadata to use a schedule or a sensor to only start a run when there are no currently running jobs. + + + + +## Troubleshooting + +When limiting concurrency, you might run into some issues until you get the configuration right. + +### Runs going to STARTED status and skipping QUEUED + +:::info +This only applies to Dagster Open Source. +::: + +The `run_queue` key may not be set in your instance's settings. In the Dagster UI, navigate to Deployment > Configuration and verify that the `run_queue` key is set. + +### Runs remaining in QUEUED status + +The possible causes for runs remaining in `QUEUED` status depend on whether you're using Dagster+ or Dagster Open Source. + + + + If runs aren't being dequeued in Dagster+, the root causes could be: + * **If using a [hybrid deployment](/dagster-plus/deployment/hybrid)**, the agent serving the deployment may be down. In this situation, runs will be paused. + * **Dagster+ is experiencing downtime**. Check the [status page](https://dagstercloud.statuspage.io/) for the latest on potential outages. + + + + If runs aren't being dequeued in Dagster Open Source, the root cause is likely an issue with the Dagster daemon or the run queue configuration. + + #### Troubleshoot the Dagster daemon + + * **Verify the Dagster daemon is set up and running.** In the Dagster UI, navigate to **Deployment > Daemons** and verify that the daemon is running. The **Run queue** should also be running. If you used [dagster dev](/guides/deploy/deployment-options/running-local-ui-development) to start the Dagster UI, the daemon should have been started for you. If the daemon isn't running, proceed to step 2. + * **Verify the Dagster daemon can access the same storage as the Dagster webserver process.** Both the webserver process and the Dagster daemon should access the same storage, meaning they should use the same `dagster.yaml`. Locally, this means both processes should have the same set `DAGSTER_HOME` environment variable. If you used dagster dev to start the Dagster UI, both processes should be using the same storage. Refer to the [Dagster Instance docs](/todo) for more information. + + #### Troubleshoot the run queue configuration + If the daemon is running, runs may intentionally be left in the queue due to concurrency rules. To investigate: + * **Check the output logged from the daemon process**, as this will include skipped runs. + * **Check the max_concurrent_runs setting in your instance's dagster.yaml**. If set to 0, this may block the queue. You can check this setting in the Dagster UI by navigating to Deployment > Configuration and locating the run_queue.max_concurrent_runs setting. Refer to the Limiting overall runs section for more info. + * **Check the state of your run queue**. In some cases, the queue may be blocked by some number of in-progress runs. To view the status of your run queue, click **Runs** in the top navigation of the Dagster UI and then open the **Queued** and **In Progress** tabs. + + If there are queued or in-progress runs blocking the queue, you can terminate them to allow other runs to proceed. + + + + +## Next Steps + +Read more in the [concurrency configuration reference](/todo). \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/configure/resources.md b/docs/docs-beta/docs/guides/build/configure/resources.md new file mode 100644 index 0000000000000..632cd296f6091 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/configure/resources.md @@ -0,0 +1,8 @@ +--- +title: Using Resources to manage external systems +sidebar_label: Resources +unlisted: true +sidebar_position: 400 +--- + +Dagster resources are objects that provide access to external systems, databases, or services. Resources are used to manage connections to external systems, and are used by Dagster ops and assets. diff --git a/docs/docs-beta/docs/guides/build/create-a-pipeline/data-assets.md b/docs/docs-beta/docs/guides/build/create-a-pipeline/data-assets.md new file mode 100644 index 0000000000000..5b37ffaaf1ec0 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/create-a-pipeline/data-assets.md @@ -0,0 +1,76 @@ +--- +title: 'Defining data assets with decorators' +sidebar_label: 'Create Assets' +sidebar_position: 100 +--- + +The most common way to create a data asset in Dagster is by annotating a function with an asset decorator. The function computes the contents of the asset, such as a database table or file. + +Dagster supports several ways of creating assets, but this guide will focus on using Python decorators to define data assets. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- To have Dagster installed. Refer to the [Installation](/getting-started/installation) guide for more information. + +
    + +Dagster has four types of asset decorators: + +| Decorator | Description | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `@asset` | Defines a single asset. [See an example](#single-asset). | +| `@multi_asset` | Outputs multiple assets from a single operation. [See an example](#multi-asset). | +| `@graph_asset` | Outputs a single asset from multiple operations without making each operation itself an asset. [See an example](#graph-asset). | +| `@graph_multi_asset` | Outputs multiple assets from multiple operations | + +## Defining operations that create a single asset \{#single-asset} + +The simplest way to define a data asset in Dagster is by using the `@asset` decorator. This decorator marks a Python function as an asset. + + + +In this example, `my_data_asset` is an asset that logs its output. Dagster automatically tracks its dependencies and handles its execution within the pipeline. + +## Defining operations that create multiple assets \{#multi-asset} + +When you need to generate multiple assets from a single operation, you can use the `@multi_asset` decorator. This allows you to output multiple assets while maintaining a single processing function, which could be useful for: + +- Making a single call to an API that updates multiple tables +- Using the same in-memory object to compute multiple assets + +In this example, `my_multi_asset` produces two assets: `asset_one` and `asset_two`. Each is derived from the same function, which makes it easier to handle related data transformations together: + + + +This example could be expressed as: + +```mermaid +flowchart LR + multi(my_multi_asset) --> one(asset_one) + multi(my_multi_asset) --> two(asset_two) +``` + +## Defining multiple operations that create a single asset \{#graph-asset} + +For cases where you need to perform multiple operations to produce a single asset, you can use the `@graph_asset` decorator. This approach encapsulates a series of operations and exposes them as a single asset, allowing you to model complex pipelines while only exposing the final output. + + + +In this example, `complex_asset` is an asset that's the result of two operations: `step_one` and `step_two`. These steps are combined into a single asset, abstracting away the intermediate representations. + +This example could be expressed as: + +```mermaid +flowchart LR + one((step_one)) --> asset(complex_asset) + two((step_two)) --> asset(complex_asset) +``` + +## Next steps + +- Learn to create [dependencies between assets](/guides/build/assets-concepts/asset-dependencies) +- Enrich Dagster's built-in data catalog with [asset metadata](/guides/build/create-a-pipeline/metadata) +- Learn to use a [factory pattern](/guides/build/configure/asset-factories) to create multiple, similar assets diff --git a/docs/docs-beta/docs/guides/build/create-a-pipeline/external-assets.md b/docs/docs-beta/docs/guides/build/create-a-pipeline/external-assets.md new file mode 100644 index 0000000000000..482539981cc84 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/create-a-pipeline/external-assets.md @@ -0,0 +1,111 @@ +--- +title: Representing external data sources with external assets +sidebar_position: 500 +sidebar_label: 'External data sources' +--- + +One of Dagster's goals is to present a single unified lineage of all of the data assets in an organization, even if those assets are orchestrated by systems other than Dagster. + +With **external assets**, you can model assets orchestrated by other systems natively within Dagster, ensuring you have a comprehensive catalog of your organization's data. You can also create new data assets downstream of these external assets. + +Unlike native assets, Dagster can't materialize external assets directly or put them in a schedule. In these cases, an external system must inform Dagster when an external asset is updated. + +For example, external assets could be: + +- Files in a data lake that are populated by a bespoke internal tool +- A CSV file delivered daily by SFTP from a partner +- A table in a data warehouse populated by another orchestrator + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/create-a-pipeline/data-assets) +- Familiarity with [Sensors](/guides/automate/sensors) +
    + +## Defining external assets + +Let's say you have a partner who sends you raw transaction data by SFTP on an almost daily basis. This data is later cleaned and stored in an internal data lake. + +Because the raw transaction data isn't materialized by Dagster, it makes sense to model it as an external asset. The following example accomplishes this by using `AssetSpec`: + + + +Refer to the [`AssetSpec` API docs](/todo) for the parameters you can provide to an external asset. + +## Recording materializations and metadata + +When an external asset is modeled in Dagster, you also need to inform Dagster whenever the external asset is updated. You should also include any relevant metadata about the asset, such as the time it was last updated. + +There are two main ways to do this: + +- Pulling external assets events with sensors +- Pushing external asset events using Dagster's REST API + +### Pulling with sensors + +You can use a Dagster [sensor](/guides/automate/sensors) to regularly poll the external system and pull information about the external asset into Dagster. + +For example, here's how you would poll an external system like an SFTP server to update an external asset whenever the file is changed. + + + +Refer to the [Sensors guide](/guides/automate/sensors) for more information about sensors. + +### Pushing with the REST API + +You can inform Dagster that an external asset has materialized by pushing the event from an external system to the REST API. The following examples demonstrate how to inform Dagster that a materialization of the `raw_transactions` external asset has occurred. + +The required headers for the REST API depend on whether you're using Dagster+ or OSS. Use the tabs to view an example API request for each Dagster type. + + + + +Authentication headers are required if using Dagster+. The request should made to your Dagster+ organization and a specific deployment in the organization. + +```shell +curl \ + -X POST \ + -H 'Content-Type: application/json' \ + -H 'Dagster-Cloud-Api-Token: [YOUR API TOKEN]' \ + 'https://[YOUR ORG NAME].dagster.cloud/[YOUR DEPLOYMENT NAME]/report_asset_materialization/' \ + -d ' +{ + "asset_key": "raw_transactions", + "metadata": { + "file_last_modified_at_ms": 1724614700266 + } +}' +``` + + + + +Authentication headers aren't required if using Dagster OSS. The request should be pointed at your open source URL, which is `http://localhost:3000` in this example. + +```shell +curl \ + -X POST \ + -H 'Content-Type: application/json' \ + 'http://localhost:3000/report_asset_materialization/' \ + -d ' +{ + "asset_key": "raw_transactions", + "metadata": { + "file_last_modified_at_ms": 1724614700266 + } +}' +``` + + + + +Refer to the [External assets REST API documentation](/todo) for more information. + +## Modeling a graph of external assets + +Like regular Dagster assets, external assets can have dependencies. This is useful when you want to model an entire data pipeline orchestrated by another system. + + diff --git a/docs/docs-beta/docs/guides/build/create-a-pipeline/index.md b/docs/docs-beta/docs/guides/build/create-a-pipeline/index.md new file mode 100644 index 0000000000000..db67cd5184f1d --- /dev/null +++ b/docs/docs-beta/docs/guides/build/create-a-pipeline/index.md @@ -0,0 +1,55 @@ +--- +title: "Create a pipeline" +description: "Learn how to create data pipelines using Dagster's asset-based approach" +sidebar_position: 10 +--- + +In Dagster, data pipelines are created using an asset-based approach. This overview will introduce you to the key concepts and steps involved in building a Dagster pipeline. + +
    + Prerequisites + +Before continuing, you should: +- Have Dagster installed. Refer to the [Installation guide](/getting-started/installation) for more information. +- Complete the [Quickstart](/getting-started/quickstart) + +
    + +Dagster uses assets as the building blocks of data pipelines. An asset represents a data object, such as a table, file, or machine learning model, that your pipeline produces or updates. + +As you define multiple assets and their dependencies, Dagster automatically creates an asset graph. This graph represents the structure and flow of your data pipeline. These nodes are not the individual operations that create the assets, but rather the assets themselves. + +```mermaid +flowchart LR + A[Raw Sales Data] --> B[Cleaned Sales Data] + B --> C[Sales Aggregations] + C --> D[Customer Segmentation] + C --> E[Sales Dashboard] + D --> F[Lead Scoring Model] +``` + +## Steps to create a pipeline + +Most Dagster pipelines follow these steps: + +1. **Define data assets**: Start by creating individual assets using the `@asset` decorator. Each asset represents a data object in your pipeline. + +2. **Create dependencies**: Connect your assets by specifying dependencies, allowing Dagster to understand the flow of data through your pipeline. + +3. **Enrich with metadata**: Add context and improve observability by enriching your assets with metadata, such as descriptions, owners, and data quality checks. + +4. **Partition your data**: For large datasets or time-based processing, use Dagster's partitioning feature to efficiently manage and process your data. + +5. **Represent external sources**: Integrate external data sources into your pipeline to create a comprehensive view of your data ecosystem. + +## Next steps + +To start building your Dagster pipeline, dive into the following guides: + +- [Define data assets](/guides/build/create-a-pipeline/data-assets) +- [Create dependencies between assets](/guides/build/assets-concepts/asset-dependencies) +- [Enrich assets with metadata](/guides/build/create-a-pipeline/metadata) +- [Partition assets](/guides/build/create-a-pipeline/partitioning) +- [Represent external data sources](/guides/build/create-a-pipeline/external-assets) + +By following these guides, you'll learn how to create powerful, maintainable data pipelines using Dagster's asset-based approach. diff --git a/docs/docs-beta/docs/guides/build/create-a-pipeline/metadata.md b/docs/docs-beta/docs/guides/build/create-a-pipeline/metadata.md new file mode 100644 index 0000000000000..a271bb38f6335 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/create-a-pipeline/metadata.md @@ -0,0 +1,160 @@ +--- +title: 'Adding tags and metadata to assets' +description: 'Learn how to add tags and metadata to assets to improve observability in Dagster' +sidebar_position: 200 +sidebar_label: 'Add metadata' +--- + +Assets feature prominently in the Dagster UI. Attaching information to assets allows you to understand where they're stored, what they contain, and how they should be organized. + +Using metadata in Dagster, you can: + +- Attach ownership information +- Organize assets with tags +- Attach rich, complex information such as a Markdown description, a table schema, or a time series +- Link assets with their source code + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/create-a-pipeline/data-assets) +
    + +## Adding owners to assets \{#owners} + +In a large organization, it's important to know which individuals and teams are responsible for a given data asset: + + + +`owners` must either be an email address or a team name prefixed by `team:`. + +:::tip +With Dagster+ Pro, you can create asset-based alerts that automatically notify an asset's owners when triggered. Refer to the [Dagster+ alert documentation](/dagster-plus/features/alerts) for more information. +::: + +## Organizing assets with tags \{#tags} + +**Tags** are the primary way to organize assets in Dagster. You can attach several tags to an asset when it's defined, and they will appear in the UI. You can also use tags to search and filter for assets in the [Asset catalog](/todo). They're structured as key-value pairs of strings. + +Here's an example of some tags you might apply to an asset: + +```python +{"domain": "marketing", "pii": "true"} +``` + +Like `owners`, just pass a dictionary of tags to the `tags` argument when defining an asset: + + + +Keep in mind that tags must contain only strings as keys and values. Additionally, the Dagster UI will render tags with the empty string as a "label" rather than a key-value pair. + +## Attaching metadata to assets \{#attaching-metadata} + +**Metadata** allows you to attach rich information to the asset, like a Markdown description, a table schema, or a time series. Metadata is more flexible than tags, as it can store more complex information. + +Metadata can be attached to an asset at definition time, when the code is first imported, or at runtime when an asset is materialized. + +### At definition time \{#definition-time-metadata} + +Using definition metadata to describe assets can make it easy to provide context for you and your team. This metadata could be descriptions of the assets, the types of assets, or links to relevant documentation. + + + +To learn more about the different types of metadata you can attach, see the [`MetadataValue`](/todo) API docs. + +Some metadata keys will be given special treatment in the Dagster UI. See the [Standard metadata types](#standard-metadata-types) section for more information. + +### At runtime \{#runtime-metadata} + +With runtime metadata, you can surface information about an asset's materialization, such as how many records were processed or when the materialization occurred. This allows you to update an asset's information when it changes and track historical metadata as a time series. + + + +Numerical metadata is treated as a time series in the Dagster UI. + +## Standard metadata types \{#standard-metadata-types} + +The following metadata keys are given special treatment in the Dagster UI. + +| Key | Description | +| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `dagster/uri` | **Type:** `str`

    The URI for the asset, for example: "s3://my_bucket/my_object" | +| `dagster/column_schema` | **Type:** [`TableSchema`](/todo)

    For an asset that's a table, the schema of the columns in the table. Refer to the [Table and column metadata](#table-schema) section for details. | +| `dagster/column_lineage` | **Type:** [`TableColumnLineage`](/todo)

    For an asset that's a table, the lineage of column inputs to column outputs for the table. Refer to the [Table and column metadata](#table-schema) section for details. | +| `dagster/row_count` | **Type:** `int`

    For an asset that's a table, the number of rows in the table. Refer to the Table metadata documentation for details. | +| `dagster/partition_row_count` | **Type:** `int`

    For a partition of an asset that's a table, the number of rows in the partition. | +| `dagster/table_name` | **Type:** `str`

    A unique identifier for the table/view, typically fully qualified. For example, my_database.my_schema.my_table | +| `dagster/code_references` | **Type:** [`CodeReferencesMetadataValue`](/todo)

    A list of code references for the asset, such as file locations or references to GitHub URLs. Refer to the [Linking assets with their source code](#source-code) section for details. Should only be provided in definition-level metadata, not materialization metadata. | + +## Table and column metadata \{#table-column} + +Two of the most powerful metadata types are [`TableSchema`](/todo) and [`TableColumnLineage`](/todo). These metadata types allow stakeholders to view the schema of a table right within Dagster, and, in Dagster+, navigate the [Asset catalog](/todo) with the column lineage. + +### Table schema metadata \{#table-schema} + +The following example attaches table and column schema metadata at both definition time and runtime: + + + +There are several data types and constraints available on [`TableColumn`](/todo) objects. Refer to the API documentation for more information. + +### Column lineage metadata \{#column-lineage} + +:::tip +Many integrations such as [dbt](https://docs.dagster.io/integrations/dbt/reference) automatically attach column lineage metadata out-of-the-box. +::: + +Column lineage metadata is a powerful way to track how columns in a table are derived from other columns: + + + +:::tip +Dagster+ provides rich visualization and navigation of column lineage in the Asset catalog. Refer to the [Dagster+ documentation](/dagster-plus) for more information. +::: + +## Linking assets with source code \{#source-code} + +import Experimental from '../../../partials/\_Experimental.md'; + + + +To link assets with their source code, you can attach a **code reference**. Code references are a type of metadata that allow you to easily view those assets' source code from the Dagster UI, both in local development and in production. + +:::tip +Many integrations such as [dbt](https://docs.dagster.io/integrations/dbt/reference#attaching-code-reference-metadata) support this capability out of the box. +::: + +### Attaching Python code references for local development \{#python-references} + +Dagster can automatically attach code references to assets during local development with one line of code: + + + +### Customizing code references \{#custom-references} + +If you want to customize how code references are attached - such as when you are building [domain-specific languages with asset factories](/guides/build/configure/asset-factories) - you can manually add the `dagster/code_references` metadata to asset definitions: + + + +### Attaching code references in production \{#production-references} + + + + +Dagster+ can automatically annotate assets with code references to source control, such as GitHub or GitLab. + + + + + + +If you aren't using Dagster+, you can annotate your assets with code references to source control, but it requires manual mapping: + + + +`link_code_references_to_git` currently supports GitHub and GitLab repositories. It also supports customization of how file paths are mapped; see the `AnchorBasedFilePathMapping` API docs for more information. + + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/create-a-pipeline/partition-dependencies.md b/docs/docs-beta/docs/guides/build/create-a-pipeline/partition-dependencies.md new file mode 100644 index 0000000000000..d6ee59ba03478 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/create-a-pipeline/partition-dependencies.md @@ -0,0 +1,82 @@ +--- +title: Defining dependencies between partitioned assets +description: Learn how to define dependencies between partitioned and unpartitioned assets in Dagster. +sidebar_label: Partition dependencies +sidebar_position: 400 +--- + +Now that you've seen how to model partitioned assets in different ways, you may want to define dependencies between the partitioned assets, or even between unpartitioned assets. + +Partitioned assets in Dagster can have dependencies on other partitioned assets, allowing you to create complex data pipelines where the output of one partitioned asset feeds into another. Here's how it works: + +- A downstream asset can depend on one or more partitions of an upstream asset +- The partitioning schemes don't need to be identical, but they should be compatible + +--- + +
    +Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/create-a-pipeline/data-assets) +- Familiarity with [Partitions](/guides/build/create-a-pipeline/partitioning) + +
    + +## Dependencies between different time-based partitions \{#different-time-dependencies} + +The following example creates two partitions: `daily_sales_data` and `daily_sales_summary`, which can be executed at the same time in a single schedule. + +
    +Show example + + + +
    + +However, sometimes you might want to define dependencies between different time-based partitions. For example, you might want to aggregate daily data into a weekly report. + +Consider the following example: + + + +In this example: + +- We have a `daily_sales_data` asset partitioned by day, which will be executed daily. +- The `weekly_sales_summary` asset depends on the `daily_sales_data` asset, which will be executed weekly. + + - In this asset, the weekly partition depends on all its parent partitions (all seven days of the week). We use `context.asset_partition_key_range_for_input("daily_sales_data")` to get a range of partition keys, which includes the start and end of the week. + +- To automate the execution of these assets: + + - First, we specify `automation_condition=AutomationCondition.eager()` to the `weekly_sales_summary` asset. This ensures it runs weekly after all seven daily partitions of `daily_sales_data` are up-to-date. + - Second, we specify `automation_condition=AutomationCondition.cron(cron_schedule="0 1 * * *")` to the `daily_sales_data` asset. This ensures it runs daily. + +Note: In a simpler example above, we manually set up a daily schedule for asset execution. For more complex dependency logic, it's recommended to use automation conditions instead of schedules. Automation conditions specify when an asset should run, which allows you to define execution criteria without custom scheduling logic. For more details, see [Declarative Automation](/guides/automate/declarative-automation). + +## Dependencies between time-based partitions and un-partitioned assets + +TODO + +## Dependencies between time-based and static partitions + +Combining time-based and static partitions allows you to analyze data across both temporal and categorical dimensions. This is particularly useful for scenarios like regional time series analysis. + +{/* TODO */} + +## Dependencies between time-based and dynamic partitions + +{/* TODO */} + +## Dependencies between time-based partitions and un-partitioned assets + +{/* TODO */} + +## Integrating Dagster partitions with external systems: incremental models and dbt + +{/* TODO */} + +## Next steps + +- Go deeper into [Understanding Partitioning](#) diff --git a/docs/docs-beta/docs/guides/build/create-a-pipeline/partitioning.md b/docs/docs-beta/docs/guides/build/create-a-pipeline/partitioning.md new file mode 100644 index 0000000000000..e82e16a28c601 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/create-a-pipeline/partitioning.md @@ -0,0 +1,70 @@ +--- +title: Partitioning assets +description: Learn how to partition your data in Dagster. +sidebar_label: Partition data +sidebar_position: 300 +--- + +In Dagster, partitioning is a powerful technique for managing large datasets, improving pipeline performance, and enabling incremental processing. This guide will help you understand how to implement data partitioning in your Dagster projects. + +There are several ways to partition your data in Dagster: + +- [Time-based partitioning](#time-based), for processing data in specific time intervals +- [Static partitioning](#static-partitions), for dividing data based on predefined categories +- [Two-dimensional partitioning](#two-dimensional-partitions), for partitioning data along two different axes simultaneously +- [Dynamic partitioning](#dynamic-partitions), for creating partitions based on runtime information + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- Familiarity with [Assets](/guides/build/create-a-pipeline/data-assets) + +
    + +## Time-based partitions \{#time-based} + +A common use case for partitioning is to process data that can be divided into time intervals, such as daily logs or monthly reports. + + + +## Partitions with predefined categories \{#static-partitions} + +Sometimes you have a set of predefined categories for your data. For instance, you might want to process data separately for different regions. + + + +{/* TODO: Link to Backfill page to explain how to backfill regional sales data */} + +## Two-dimensional partitions \{#two-dimensional-partitions} + +Two-dimensional partitioning allows you to partition data along two different axes simultaneously. This is useful when you need to process data that can be categorized in multiple ways. For example: + + + +In this example: + +- Using `MultiPartitionsDefinition`, the `two_dimensional_partitions` is defined with two dimensions: `date` and `region` +- The partition key would be: `2024-08-01|us` +- The `daily_regional_sales_data` and `daily_regional_sales_summary` assets are defined with the same two-dimensional partitioning scheme +- The `daily_regional_sales_schedule` runs daily at 1:00 AM, processing the previous day's data for all regions. It uses `MultiPartitionKey` to specify partition keys for both date and region dimensions, resulting in three runs per day, one for each region. + +## Partitions with dynamic categories \{#dynamic-partitions} + +Sometimes you don't know the partitions in advance. For example, you might want to process new regions that are added in your system. In these cases, you can use dynamic partitioning to create partitions based on runtime information. + +Consider this example: + + + +Because the partition values are unknown in advance, `DynamicPartitionsDefinition` is used to define the partition. Then, the `all_regions_sensor` TODO: incomplete sentence + +In this example: + +- Because the partition values are unknown in advance, `DynamicPartitionsDefinition` is used to define `region_partitions` +- When triggered, the `all_regions_sensor` will dynamically add all regions to the partition set. Once it kicks off runs, it will dynamically kick off runs for all regions. In this example, that would be six times; one for each region. + +## Next steps + +- TODO: Partition dependencies \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/index.md b/docs/docs-beta/docs/guides/build/index.md new file mode 100644 index 0000000000000..9551dba1946eb --- /dev/null +++ b/docs/docs-beta/docs/guides/build/index.md @@ -0,0 +1,7 @@ +--- +title: "Building pipelines" +sidebar_position: 30 +sidebar_class_name: hidden +--- + +This section is about building asset pipelines. \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/integrate/build-your-own.md b/docs/docs-beta/docs/guides/build/integrate/build-your-own.md new file mode 100644 index 0000000000000..6c5e3008a33e7 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/build-your-own.md @@ -0,0 +1,5 @@ +--- +title: "Building an asset integration" +sidebar_position: 400 +unlisted: true +--- diff --git a/docs/docs-beta/docs/guides/build/integrate/cloud-services.md b/docs/docs-beta/docs/guides/build/integrate/cloud-services.md new file mode 100644 index 0000000000000..1fdc39f3d75fd --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/cloud-services.md @@ -0,0 +1,5 @@ +--- +title: Connecting to cloud services +sidebar_position: 600 +unlisted: true +--- diff --git a/docs/docs-beta/docs/guides/build/integrate/index.mdx b/docs/docs-beta/docs/guides/build/integrate/index.mdx new file mode 100644 index 0000000000000..3aa86ed1f629e --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/index.mdx @@ -0,0 +1,8 @@ +--- +title: "Integrate" +sidebar_position: 30 +--- + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/integrate/ingesting-data.md b/docs/docs-beta/docs/guides/build/integrate/ingesting-data.md new file mode 100644 index 0000000000000..a6290c8c37c1d --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/ingesting-data.md @@ -0,0 +1,52 @@ +--- +title: Ingesting data with Dagster +description: Learn how to orchestrate data ingestion with Dagster +sidebar_position: 100 +sidebar_label: Ingest data +--- + +import { Card, CardGroup } from '@site/src/components/Cards'; + +:::note +This guide focuses on batch data ingestion, as streaming data ingestion doesn't typically rely on an orchestrator to kick off or coordinate computations. However, streaming data assets can still be represented in Dagster for lineage purposes. +::: + +Dagster is often used to orchestrate the ingestion of data into a data warehouse or data lake, where it can be queried and transformed. To ingest data with Dagster, you can use pre-built connectors or write your own custom code. + +
    +Prerequisites + +To follow this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +
    + +## How Dagster supports data ingestion + +As a data orchestrator, Dagster helps with data ingestion as it can: + +- **Automatically kick off computations that ingest data**, thus removing the need for manual intervention +- **Coordinate data ingestion with downstream data transformation,** such as rebuilding a set of dbt models after upstream data is updated +- **Represent ingested data assets in an asset graph**, which enables understanding what ingested data exists, how ingested data is used, and where data is ingested from + +## Orchestrating data ingestion tools + +Dagster currently integrates with the following data ingestion tools, enabling you to sync diverse data sources into data warehouse tables using pre-built connectors: + +- [Airbyte](/integrations/airbyte) +- [dlt](/integrations/dlt) +- [Fivetran](/integrations/fivetran) +- [Sling](/integrations/sling) + +## Writing custom data ingestion pipelines + +Using a language like Python to write code for data ingestion into a platform is also a common approach. This is useful when you have unique data ingestion requirements that aren't addressed by existing tools, or when you prefer to keep your platform streamlined without adding new tools. + +For example, imagine there's a CSV file of counties on the internet and you want to load it into your Snowflake data warehouse as a table. To do this, you might define a Dagster asset that represents that table in your warehouse. The asset's materialization function fetches data from the internet and loads it into that table: + + + +## Next steps + +- Transform data using [Dagster's dbt integration](/guides/build/integrate/transform-dbt) +- Use asset checks [to test data quality](/guides/test/asset-checks) and [freshness](/guides/test/data-freshness-testing) \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/build/integrate/non-python.md b/docs/docs-beta/docs/guides/build/integrate/non-python.md new file mode 100644 index 0000000000000..1f2618b62e259 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/non-python.md @@ -0,0 +1,84 @@ +--- +title: "Using Dagster Pipes to execute non-Python languages" +sidebar_label: "Dagster Pipes" +sidebar_position: 300 +--- + +Dagster is written in Python, but that doesn't mean it's that Python is the only language that can be used when materializing assets. With Dagster Pipes, you can run code in other languages and send information back to Dagster. + +This guide covers how to run JavaScript with Dagster using Pipes, however, the same principle will apply to other languages. + +
    +Prerequisites + +To follow this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +- A basic understanding of JavaScript and Node.js + +To run the examples, you'll need to install: + +- [Node.js](https://nodejs.org/en/download/package-manager/) +- The following packages: + + ```bash + pip install dagster dagster-webserver tensorflow + ``` +
    + +## Step 1: Create a script using Tensorflow in JavaScript + +First, you'll create a JavaScript script that reads a CSV file and uses Tensorflow to train a sequential model. + +Create a file named `tensorflow/main.js` with the following contents: + + + +## Step 2: Create a Dagster asset that runs the script + +In Dagster, create an asset that: + +- Uses the `PipesSubprocessClient` resource to run the script with `node` +- Sets the `compute_kind` to `javascript`. This makes it easy to identify that an alternate compute will be used for materialization. + + + +When the asset is materialized, the stdout and stderr will be captured automatically and shown in the asset logs. If the command passed to Pipes returns a successful exit code, Dagster will produce an asset materialization result. + +![Image of captured stdout](/img/placeholder.svg) + +## Step 3: Send and receive data from the script + +To send context to your script or emit events back to Dagster, you can use environment variables provided by the `PipesSubprocessClient`. + + +- `DAGSTER_PIPES_CONTEXT` - Input context +- `DAGSTER_PIPES_MESSAGES` - Output context + +Create a new file with the following helper functions that read the environment variables, decode the data, and write messages back to Dagster: + + + +Both environment variables are base64 encoded, zip compressed JSON objects. Each JSON object contains a path that indicates where to read or write data. + +## Step 4: Emit events and report materializations from your external process + +Using the utility functions to decode the Dagster Pipes environment variables, you can send additional parameters into the JavaScript process. You can also output more information into the asset materializations. + +Update the `tensorflow/main.js` script to: + +- Retrieve the model configuration from the Dagster context, and +- Report an asset materialization back to Dagster with model metadata + + + +## Step 5: Update the asset to provide extra parameters + +Finally, update your Dagster asset to pass in the model information that's used by the script: + + + +## What's next? + +- Schedule your pipeline to run periodically with [Automating Pipelines](/guides/automate/index.md) +- Explore adding asset checks to validate your script with [Understanding Asset Checks](/guides/test/asset-checks) diff --git a/docs/docs-beta/docs/guides/build/integrate/pipes.md b/docs/docs-beta/docs/guides/build/integrate/pipes.md new file mode 100644 index 0000000000000..39a6152f256f2 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/pipes.md @@ -0,0 +1,38 @@ +--- +title: "Executing code outside of Dagster with Pipes" +sidebar_position: 500 +sidebar_label: "External execution with Pipes" +--- + +# Executing code outside of Dagster with Pipes + +Dagster Pipes provides a powerful mechanism for invoking code outside of Dagster, while providing all the benefits of scheduling, reporting, and observability of native Dagster pipelines. + +In this guide, we'll walk you through how to invoke non-Dagster code through Pipes. + +
    +Prerequisites + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +
    + +## Setting up an asset that invokes your external code + +To set up invoking code outside of Dagster, you first need to set up an asset. We can invoke the external code within the asset function by using a Dagster Pipes client resource. + +It's not a requirement that this external code know anything about Dagster. It can even be a process running a different language on a remote machine - the only requirement is that it can be triggered from Python. + +In the following example, our external code is in a Python script that we invoke within a Dagster asset. + + + + +Materializing this asset in Dagster from the UI or from a sensor/schedule will kick off the execution of that external code. + +## Sending logs and metadata back to Dagster from external code + +Dagster Pipes also establishes a protocol for external code to optionally send back log and metadata back to Dagster. A Python client for this protocol is available as part of the `dagster_pipes` package. To send back log and metadata back to Dagster, we can create a `PipesContext` object within our external code: + + + +The logs sent back using the `PipesContext` will be visible in the structured logs of that asset materialization's run, and the materialization metadata will be reflected in the asset history. diff --git a/docs/docs-beta/docs/guides/build/integrate/transform-dbt.md b/docs/docs-beta/docs/guides/build/integrate/transform-dbt.md new file mode 100644 index 0000000000000..55dcf07232edb --- /dev/null +++ b/docs/docs-beta/docs/guides/build/integrate/transform-dbt.md @@ -0,0 +1,78 @@ +--- +title: Transforming data with dbt +sidebar_position: 200 +sidebar_label: Transform data with dbt +--- + +Dagster orchestrates dbt alongside other technologies, so you can schedule dbt with Spark, Python, etc. in a single data pipeline. Dagster's asset-oriented approach allows Dagster to understand dbt at the level of individual dbt models. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- A basic understanding of dbt, DuckDB, and Dagster concepts such as [assets](/todo) and [resources](/todo) +- To install the [dbt](https://docs.getdbt.com/docs/core/installation-overview) and [DuckDB CLIs](https://duckdb.org/docs/api/cli/overview.html) +- To install the following packages: + + ```shell + pip install dagster duckdb plotly dagster-dbt dbt-duckdb + ``` +
    + +## Setting up a basic dbt project + +Start by downloading this basic dbt project, which includes a few models and a DuckDB backend: + +```bash +git clone https://github.com/dagster-io/basic-dbt-project +``` + +The project structure should look like this: + +``` +├── README.md +├── dbt_project.yml +├── profiles.yml +├── models +│ └── example +│ ├── my_first_dbt_model.sql +│ ├── my_second_dbt_model.sql +│ └── schema.yml +``` + +First, you need to point Dagster at the dbt project and ensure Dagster has what it needs to build an asset graph. Create a `definitions.py` in the same directory as the dbt project: + + + +## Adding upstream dependencies + +Oftentimes, you'll want Dagster to generate data that will be used by downstream dbt models. To do this, add an upstream asset that the dbt project will as a source: + + + +Next, you'll add a dbt model that will source the `raw_customers` asset and define the dependency for Dagster. Create the dbt model: + + + +Next, create a `_source.yml` file that points dbt to the upstream `raw_customers` asset: + + + +![Screenshot of dbt lineage](/img/placeholder.svg) + +## Adding downstream dependencies + +You may also have assets that depend on the output of dbt models. Next, create an asset that depends on the result of the new `customers` model. This asset will create a histogram of the first names of the customers: + + + +## Scheduling dbt models + +You can schedule your dbt models by using the `dagster-dbt`'s `build_schedule_from_dbt_selection` function: + + + +## Next steps + +{/* TODO: Add link to dbt partitioning guide */} diff --git a/docs/docs-beta/docs/guides/build/ops-jobs/index.md b/docs/docs-beta/docs/guides/build/ops-jobs/index.md new file mode 100644 index 0000000000000..c03c4a7beccb6 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/ops-jobs/index.md @@ -0,0 +1,10 @@ +--- +unlisted: true +sidebar_position: 50 +--- + +# Ops and jobs + +import DocCardList from '@theme/DocCardList'; + + diff --git a/docs/docs-beta/docs/guides/build/ops-jobs/job-configuration.md b/docs/docs-beta/docs/guides/build/ops-jobs/job-configuration.md new file mode 100644 index 0000000000000..c15ec31bab52e --- /dev/null +++ b/docs/docs-beta/docs/guides/build/ops-jobs/job-configuration.md @@ -0,0 +1,7 @@ +--- +title: "Job configuration" +sidebar_position: 200 +unlisted: true +--- + +# Job configuration diff --git a/docs/docs-beta/docs/guides/build/ops-jobs/ops-vs-assets.md b/docs/docs-beta/docs/guides/build/ops-jobs/ops-vs-assets.md new file mode 100644 index 0000000000000..d39a086dd74f8 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/ops-jobs/ops-vs-assets.md @@ -0,0 +1,7 @@ +--- +title: "Ops vs. assets" +sidebar_position: 100 +unlisted: true +--- + +# Ops vs. assets diff --git a/docs/docs-beta/docs/guides/build/project-structure.md b/docs/docs-beta/docs/guides/build/project-structure.md new file mode 100644 index 0000000000000..6a9d638d05856 --- /dev/null +++ b/docs/docs-beta/docs/guides/build/project-structure.md @@ -0,0 +1,157 @@ +--- +title: "How to structure your Dagster project" +sidebar_position: 200 +--- + +# How to structure your Dagster project + +:::note +Refer to the project scaffolding tutorial to learn how to create a new Dagster project. +::: + +There are many ways to structure your Dagster project, and it can be difficult to know where to start. In this guide, we will walk you through our recommendations for how to organize your Dagster project. As your project grows, you are welcome to deviate from these recommendations. + +## Your initial project structure + +When you first scaffold your project using the Dagster command-line tool, an `assets.py` and `definitions.py` are created in the root of your project. + +```sh +$ dagster project scaffold --name example-dagster-project +``` + +``` +. +├── README.md +├── example_dagster_project +│   ├── __init__.py +│   ├── assets.py +│   └── definitions.py +├── example_dagster_project_tests +│   ├── __init__.py +│   └── test_assets.py +├── pyproject.toml +├── setup.cfg +└── setup.py +``` + +This is a great structure as you are first getting started, however, as you begin to introduce more assets, jobs, resources, sensors, and utility code, you may find that your Python files are growing too large to manage. + +## Restructure your project + +There are several paradigms in which you can structure your project. Choosing one of these structures is often personal preference, and influenced by how you and your team members operate. This guide will outline three possible project structures: + +1. [Option 1: Structured by technology](#option-1-structured-by-technology) +2. [Option 2: Structured by concept](#option-2-structured-by-concept) + + +### Option 1: Structured by technology + +Data engineers often have a strong understanding of the underlying technologies that are used in their data pipelines. Because of that, it's often beneficial to organize your project by technology. This enables engineers to easily navigate the code base and locate files pertaining to the specific technology. + +Within the technology modules, sub-modules can be created to further organize your code. + +``` +. +└── example_dagster_project/ + ├── dbt/ + │ ├── __init__.py + │ ├── assets.py + │ ├── resources.py + │ └── definitions.py + ├── dlt/ + │ ├── __init__.py + │ ├── pipelines/ + │ │ ├── __init__.py + │ │ ├── github.py + │ │ └── hubspot.py + │ ├── assets.py + │ ├── resources.py + │ └── definitions.py + └── definitions.py +``` + +### Option 2: Structured by concept + +It's also possible to introduce a layer of categorization by the overarching data processing concept. For example, whether the job is performing some kind of transformation, ingestion of data, or processing operation. + +This provides additional context to the engineers who may not have as strong of a familiarity with the underlying technologies that are being used. + +``` +. +└── example_dagster_project/ + ├── ingestion/ + │ └── dlt/ + │ ├── assets.py + │ ├── resources.py + │ └── definitions.py + ├── transformation/ + │ ├── dbt/ + │ │ ├── assets.py + │ │ ├── resources.py + │ │ └── partitions.py + │ │ └── definitions.py + │ └── adhoc/ + │ ├── assets.py + │ ├── resources.py + │ └── definitions.py + └── definitions.py +``` + +## Merging definitions objects + +It's possible to define multiple `Definitions` objects, often with one for each sub-module in your project. These definitions can then be merged at the root of your project using the `Definitions.merge` method. + +The benefit of such a structure is that dependencies like resources and partitions can be scoped to their corresponding definitions. + +```py title="example-merge-definitions.py" +from dbt.definitions import dbt_definitions +from dlt.definitions import dlt_definitions + + +defs = Definitions.merge( + dbt_definitions, + dlt_definitions, +) +``` + +## Configuring multiple code locations + +This guide has outlined how to structure a project within a single code location, however, Dagster also allows you to structure a project spanning multiple location. + +In most cases, one code location should be sufficient. A helpful pattern uses multiple code locations to separate conflicting dependencies, where each definition has its own package requirements and deployment specs. + +To include multiple code locations in a single project, you'll need to add a configuration file to your project: + +- **If using Dagster+**, add a `dagster_cloud.yaml` file to the root of your project. +- **If developing locally or deploying to your infrastructure**, add a workspace.yaml file to the root of your project. + +## External projects + +As your data platform evolves, Dagster will enable you to orchestrate other data tools, such as dbt, Sling, or Jupyter notebooks. + +For these projects, it's recommended to store them outside your Dagster project. See the `dbt_project` example below. + +``` +. +├── dbt_project/ +│ ├── config/ +│ │ └── profiles.yml +│ ├── dbt_project.yml +│ ├── macros/ +│ │ ├── aggregate_actions.sql +│ │ └── generate_schema_name.sql +│ ├── models/ +│ │ ├── activity_analytics/ +│ │ │ ├── activity_daily_stats.sql +│ │ │ ├── comment_daily_stats.sql +│ │ │ └── story_daily_stats.sql +│ │ ├── schema.yml +│ │ └── sources.yml +│ └── tests/ +│ └── assert_true.sql +└── example_dagster_project/ +``` + +## Next steps + +- Explore the [Definitions.merge](https://docs.dagster.io/_apidocs/definitions#dagster.Definitions.merge) API docs diff --git a/docs/docs-beta/docs/guides/deploy/code-locations/index.mdx b/docs/docs-beta/docs/guides/deploy/code-locations/index.mdx new file mode 100644 index 0000000000000..7951c9ba3dbdf --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/code-locations/index.mdx @@ -0,0 +1,8 @@ +--- +title: Code locations +sidebar_position: 30 +--- + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/deploy/code-locations/managing-code-locations.md b/docs/docs-beta/docs/guides/deploy/code-locations/managing-code-locations.md new file mode 100644 index 0000000000000..b44a57a85cad4 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/code-locations/managing-code-locations.md @@ -0,0 +1,6 @@ +--- +title: "Managing code locations with Definitions" +unlisted: true +--- + +# Manage code locations diff --git a/docs/docs-beta/docs/guides/deploy/code-locations/workspace-yaml.md b/docs/docs-beta/docs/guides/deploy/code-locations/workspace-yaml.md new file mode 100644 index 0000000000000..4ee95d7f1a0eb --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/code-locations/workspace-yaml.md @@ -0,0 +1,120 @@ +--- +title: "workspace.yaml reference" +--- + +# Workspace file reference + +:::info + This reference is only applicable to Dagster OSS. For Dagster Cloud see [the Dagster Cloud Code Locations guide](/dagster-plus/deployment/code-locations) +::: + +The `workspace.yaml` file is used to configure code locations in Dagster. It tells Dagster where to find your code and how to load it. + +## Location of workspace.yaml + +Dagster command-line tools (like dagster dev, dagster-webserver, or dagster-daemon run) look for workspace files in the current directory when invoked. This allows you to launch from that directory without the need for command line arguments + +To load the workspace.yaml file from a different folder, use the -w argument: + +```bash +dagster dev -w path/to/workspace.yaml +``` + +## File structure + +The `workspace.yaml` file uses the following structure: + +```yaml +load_from: + - : + +``` + +Where `` can be one of: +- `python_file` +- `python_module` +- `grpc_server` + + + +## Loading methods + +We recommend using `python_module` for most use cases. + +### Python module + +Loads a code location from a Python module. + +**Options:** +- `module_name`: Name of the Python module to load. +- Other options are the same as `python_file`. + +**Example:** +```yaml +load_from: + - python_module: + module_name: hello_world_module.definitions +``` + + +### Python file + +Loads a code location from a Python file. + +**Options:** +- `relative_path`: Path to the Python file, relative to the `workspace.yaml` location. +- `attribute` (optional): Name of a specific repository or function returning a `RepositoryDefinition`. +- `working_directory` (optional): Custom working directory for relative imports. +- `executable_path` (optional): Path to a specific Python executable. +- `location_name` (optional): Custom name for the code location. + +**Example:** +```yaml +load_from: + - python_file: + relative_path: hello_world_repository.py + attribute: hello_world_repository + working_directory: my_working_directory/ + executable_path: venvs/path/to/python + location_name: my_location +``` + +### gRPC server + +Configures a gRPC server as a code location. + +**Options:** +- `host`: The host address of the gRPC server. +- `port`: The port number of the gRPC server. +- `location_name`: Custom name for the code location. + +**Example:** +```yaml +load_from: + - grpc_server: + host: localhost + port: 4266 + location_name: "my_grpc_server" +``` + +## Multiple code locations + +You can define multiple code locations in a single `workspace.yaml` file: + +```yaml +load_from: + - python_file: + relative_path: path/to/dataengineering_spark_team.py + location_name: dataengineering_spark_team_py_38_virtual_env + executable_path: venvs/path/to/dataengineering_spark_team/bin/python + - python_file: + relative_path: path/to/team_code_location.py + location_name: ml_team_py_36_virtual_env + executable_path: venvs/path/to/ml_tensorflow/bin/python +``` + +## Notes + +- Each code location is loaded in its own process. +- Code locations can mix and match between `Definitions` objects and `@repository` decorators. +- If a code location is renamed or its configuration is modified, running schedules and sensors in that location need to be stopped and restarted. \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/deploy/dagster-yaml.md b/docs/docs-beta/docs/guides/deploy/dagster-yaml.md new file mode 100644 index 0000000000000..d7f628b9f533a --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/dagster-yaml.md @@ -0,0 +1,346 @@ +--- +title: "dagster.yaml reference" +sidebar_position: 200 +---- + +# dagster.yaml reference + +The `dagster.yaml` file is used to configure the Dagster instance. It defines various settings for storage, run execution, logging, and other aspects of a Dagster deployment. + +## File location + +By default, Dagster looks for the `dagster.yaml` file in the directory specified by the `DAGSTER_HOME` environment variable. + +## Using environment variables + +You can use environment variables to override values in the `dagster.yaml` file. + +```yaml +instance: + module: dagster.core.instance + class: DagsterInstance + config: + some_key: + env: ME_ENV_VAR +``` + +## Full configuration specification + +Here's a comprehensive `dagster.yaml` specification with all available options: + +```yaml +local_artifact_storage: + module: dagster.core.storage.root + class: LocalArtifactStorage + config: + base_dir: '/path/to/dir' + +compute_logs: + module: dagster.core.storage.local_compute_log_manager + class: LocalComputeLogManager + config: + base_dir: /path/to/compute/logs + +# Alternatively, logs can be written to cloud storage providers like S3, GCS, and Azure blog storage. For example: +# compute_logs: +# module: dagster_aws.s3.compute_log_manager +# class: S3ComputeLogManager +# config: +# bucket: "mycorp-dagster-compute-logs" +# prefix: "dagster-test-" + +storage: + sqlite: + base_dir: /path/to/sqlite/storage + # Or use postgres: + # postgres: + # postgres_db: + # hostname: localhost + # username: dagster + # password: dagster + # db_name: dagster + # port: 5432 + +run_queue: + max_concurrent_runs: 15 + tag_concurrency_limits: + - key: 'database' + value: 'redshift' + limit: 4 + - key: 'dagster/backfill' + limit: 10 + +run_storage: + module: dagster.core.storage.runs + class: SqliteRunStorage + config: + base_dir: /path/to/dagster/home/history + +event_log_storage: + module: dagster.core.storage.event_log + class: SqliteEventLogStorage + config: + base_dir: /path/to/dagster/home/history + +schedule_storage: + module: dagster.core.storage.schedules + class: SqliteScheduleStorage + config: + base_dir: /path/to/dagster/home/schedules + +scheduler: + module: dagster.core.scheduler + class: DagsterDaemonScheduler + +run_coordinator: + module: dagster.core.run_coordinator + class: DefaultRunCoordinator + # class: QueuedRunCoordinator + # config: + # max_concurrent_runs: 25 + # tag_concurrency_limits: + # - key: "dagster/backfill" + # value: "true" + # limit: 1 + +run_launcher: + module: dagster.core.launcher + class: DefaultRunLauncher + # module: dagster_docker + # class: DockerRunLauncher + # module: dagster_k8s.launcher + # class: K8sRunLauncher + # config: + # service_account_name: pipeline_run_service_account + # job_image: my_project/dagster_image:latest + # instance_config_map: dagster-instance + # postgres_password_secret: dagster-postgresql-secret + +telemetry: + enabled: true + +run_monitoring: + enabled: true + poll_interval_seconds: 60 + +run_retries: + enabled: true + max_retries: 3 + retry_on_asset_or_op_failure: true + +code_servers: + local_startup_timeout: 360 + +secrets: + my_secret: + env: MY_SECRET_ENV_VAR + +retention: + schedule: + purge_after_days: 90 + sensor: + purge_after_days: + skipped: 7 + failure: 30 + success: -1 + +sensors: + use_threads: true + num_workers: 8 + +schedules: + use_threads: true + num_workers: 8 + +auto_materialize: + enabled: true + minimum_interval_seconds: 3600 + run_tags: + key: 'value' + respect_materialization_data_versions: true + max_tick_retries: 3 + use_sensors: false + use_threads: false + num_workers: 4 +``` + +## Configuration options + +### `storage` + +Configures how job and asset history is persisted. + +```yaml +storage: + sqlite: + base_dir: /path/to/sqlite/storage +``` + +Options: + +- `sqlite`: Use SQLite for storage +- `postgres`: Use PostgreSQL for storage (requires `dagster-postgres` library) +- `mysql`: Use MySQL for storage (requires `dagster-mysql` library) + +### `run_launcher` + +Determines where runs are executed. + +```yaml +run_launcher: + module: dagster.core.launcher + class: DefaultRunLauncher +``` + +Options: + +- `DefaultRunLauncher`: Spawns a new process on the same node as the job's code location +- `DockerRunLauncher`: Allocates a Docker container per run +- `K8sRunLauncher`: Allocates a Kubernetes job per run + +### `run_coordinator` + +Sets prioritization rules and concurrency limits for runs. + +```yaml +run_coordinator: + module: dagster.core.run_coordinator + class: QueuedRunCoordinator + config: + max_concurrent_runs: 25 +``` + +Options: + +- `DefaultRunCoordinator`: Immediately sends runs to the run launcher +- `QueuedRunCoordinator`: Allows setting limits on concurrent runs + +### `compute_logs` + +Controls the capture and persistence of stdout and stderr logs. + +```yaml +compute_logs: + module: dagster.core.storage.local_compute_log_manager + class: LocalComputeLogManager + config: + base_dir: /path/to/compute/logs +``` + +Options: + +- `LocalComputeLogManager`: Writes logs to disk +- `NoOpComputeLogManager`: Does not store logs +- `AzureBlobComputeLogManager`: Writes logs to Azure Blob Storage +- `GCSComputeLogManager`: Writes logs to Google Cloud Storage +- `S3ComputeLogManager`: Writes logs to AWS S3 + +### `local_artifact_storage` + +Configures storage for artifacts that require a local disk or when using the filesystem I/O manager. + +```yaml +local_artifact_storage: + module: dagster.core.storage.root + class: LocalArtifactStorage + config: + base_dir: /path/to/artifact/storage +``` + +### `telemetry` + +Controls whether Dagster collects anonymized usage statistics. + +```yaml +telemetry: + enabled: false +``` + +### `code_servers` + +Configures how Dagster loads code in a code location. + +```yaml +code_servers: + local_startup_timeout: 360 +``` + +### `retention` + +Configures how long Dagster retains certain types of data. + +```yaml +retention: + schedule: + purge_after_days: 90 + sensor: + purge_after_days: + skipped: 7 + failure: 30 + success: -1 +``` + +### `sensors` + +Configures how sensors are evaluated. + +```yaml +sensors: + use_threads: true + num_workers: 8 +``` + +### `schedules` + +Configures how schedules are evaluated. + +```yaml +schedules: + use_threads: true + num_workers: 8 +``` + +### `auto_materialize` + +Configures automatic materialization of assets. + +```yaml +auto_materialize: + enabled: true + minimum_interval_seconds: 3600 + run_tags: + key: 'value' + respect_materialization_data_versions: true + max_tick_retries: 3 + use_sensors: false + use_threads: false + num_workers: 4 +``` + +Options: + +- `enabled`: Whether auto-materialization is enabled (boolean) +- `minimum_interval_seconds`: Minimum interval between materializations (integer) +- `run_tags`: Tags to apply to auto-materialization runs (dictionary) +- `respect_materialization_data_versions`: Whether to respect data versions when materializing (boolean) +- `max_tick_retries`: Maximum number of retries for each auto-materialize tick that raises an error (integer, default: 3) +- `use_sensors`: Whether to use sensors for auto-materialization (boolean) +- `use_threads`: Whether to use threads for processing ticks (boolean, default: false) +- `num_workers`: Number of threads to use for processing ticks from multiple automation policy sensors in parallel (integer) + +### `concurrency` + +Configures default concurrency limits for operations. + +```yaml +concurrency: + default_op_concurrency_limit: 10 +``` + +Options: + +- `default_op_concurrency_limit`: The default maximum number of concurrent operations for an unconfigured concurrency key (integer) + +## References + +- [Dagster Instance Config Source Code](https://github.com/dagster-io/dagster/blob/master/python_modules/dagster/dagster/_core/instance/config.py) diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/amazon-web-services.md b/docs/docs-beta/docs/guides/deploy/deployment-options/amazon-web-services.md new file mode 100644 index 0000000000000..d425e912d4cd3 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/amazon-web-services.md @@ -0,0 +1,5 @@ +--- +title: "Deploy to Amazon Web Services" +unlisted: true +sidebar_position: 500 +--- diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/dagster-service.md b/docs/docs-beta/docs/guides/deploy/deployment-options/dagster-service.md new file mode 100644 index 0000000000000..fcb65fafa58f9 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/dagster-service.md @@ -0,0 +1,118 @@ +--- +title: 'Deploy Dagster as a service' +description: 'Learn how to deploy Dagster as a service on a single machine' +sidebar_position: 200 +--- + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- A Dagster project created +- Working knowledge of containerization and managing services + +
    + +# Deploy Dagster as a service + +This guide will walk you through deploying Dagster as a service on a single machine. It includes instructions for setting up the Dagster webserver and daemon. This approach is suitable for small-scale deployments or for testing purposes. For production environments, consider using containerized deployments or cloud-based solutions + +## Running the Dagster Webserver + +The Dagster webserver is the core component of any Dagster deployment. It serves the Dagster UI and responds to GraphQL queries. + +### Installation + +First, install the Dagster webserver: + +```bash +pip install dagster-webserver +``` + +### Starting the Dagster Webserver + +Before starting the webserver, set the `DAGSTER_HOME` environment variable, which tells Dagster where to store its persistent data and logs. + + + + +```bash +export DAGSTER_HOME="/home/yourusername/dagster_home" +``` + + + + +```powershell +$env:DAGSTER_HOME = "C:\Users\YourUsername\dagster_home" +``` + + + + + +Then, to run the webserver, use the following command: + +```bash +dagster-webserver -h 0.0.0.0 -p 3000 +``` + +This configuration will: + +- Set the `DAGSTER_HOME` environment variable, which tells Dagster where to store its persistent data and logs +- Write execution logs to `$DAGSTER_HOME/logs` +- Listen on `0.0.0.0:3000` + +## Running the Dagster Daemon + +The Dagster daemon is necessary if you're using schedules, sensors, backfills, or want to set limits on the number of runs that can be executed simultaneously. + +### Installation + +Install the Dagster daemon: + +```bash +pip install dagster +``` + +### Starting the Daemon + +Make sure you've set the `DAGSTER_HOME` environment variable, see [Running the Dagster Webserver](#running-the-dagster-webserver) for instructions. +Then, run the Dagster daemon with this command: + +```bash +dagster-daemon run +``` + +The `dagster-daemon` process will periodically check your instance for: + +- New runs to be launched from your run queue +- Runs triggered by your running schedules or sensors + +:::tip +Ensure that the `dagster-daemon` process has access to: + +- Your `dagster.yaml` file +- Your `workspace.yaml` file +- The components defined on your instance +- The repositories defined in your workspace + ::: + +### Monitoring the Daemon + +You can check the status of your `dagster-daemon` process in the Dagster UI: + +1. Navigate to the Instance tab in the left-hand navigation bar +2. View the daemon status + +:::important +A deployment can have multiple instances of `dagster-webserver`, but should include only a single `dagster-daemon` process. +::: + +## Next Steps + +Now that you have Dagster running as a service, you might want to explore: + +- [Configuring your Dagster instance](/todo) +- [Setting up schedules and sensors](/guides/automate/schedules) diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/docker.md b/docs/docs-beta/docs/guides/deploy/deployment-options/docker.md new file mode 100644 index 0000000000000..4247a956771c8 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/docker.md @@ -0,0 +1,175 @@ +--- +title: "Deploying with Docker Compose" +description: A guide to deploying Dagster with Docker Compose. +sidebar_position: 400 +--- + +This guide provides instructions for deploying Dagster using Docker Compose. This is useful when you want to, for example, deploy Dagster on an AWS EC2 host. A typical Dagster Docker deployment includes a several long-running containers: one for the webserver, one for the daemon, and one for each code location. It also typically executes each run in its own container. + +
    + Prerequisites +- Familiarity with Docker and Docker Compose +- Familiarity with `dagster.yaml` instance configuration +- Familiarity with `workspace.yaml` code location configuration +
    + + +## Define a Docker image for the Dagster webserver and daemon + +The Dagster webserver and daemon are the two _host processes_ in a Dagster deployment. They typically each run in their own container, using the same Docker image. This image contains Dagster packages and configuration, but no user code. + +To build this Docker image, use a Dockerfile like the following, with a name like `Dockerfile_dagster`: + +```dockerfile +FROM python:3.10-slim + +RUN pip install \ + dagster \ + dagster-graphql \ + dagster-webserver \ + dagster-postgres \ # Database for Dagster storage + dagster-docker # Enables the Docker run launcher + +# Set $DAGSTER_HOME and copy dagster.yaml and workspace.yaml there +ENV DAGSTER_HOME=/opt/dagster/dagster_home/ + +RUN mkdir -p $DAGSTER_HOME + +COPY dagster.yaml workspace.yaml $DAGSTER_HOME + +WORKDIR $DAGSTER_HOME +``` + +Additionally, the following files should be in the same directory as the Docker file: +- A `workspace.yaml` to tell the webserver and daemon the location of the code servers +- A `dagster.yaml` to configure the Dagster instance + +## Define a Docker image for each code location + +Each code location typically has its own Docker image, and that image is also used for runs launched for that code location. + +To build a Docker image for a code location, use a Dockerfile like the following, with a name like `Dockerfile_code_location_1`: + +```dockerfile +FROM python:3.10-slim + +RUN pip install \ + dagster \ + dagster-postgres \ + dagster-docker + +# Add code location code +WORKDIR /opt/dagster/app +COPY directory/with/your/code/ /opt/dagster/app + +# Run dagster code server on port 4000 +EXPOSE 4000 + +# CMD allows this to be overridden from run launchers or executors to execute runs and steps +CMD ["dagster", "code-server", "start", "-h", "0.0.0.0", "-p", "4000", "-f", "definitions.py"] +``` + +## Write a Docker Compose file + +The following `docker-compose.yaml` defines how to run the webserver container, daemon container, code location containers, and database container: + +```yaml title="docker-compose.yaml" +version: "3.7" + +services: + # This service runs the postgres DB used by dagster for run storage, schedule storage, + # and event log storage. + docker_postgresql: + image: postgres:11 + container_name: docker_postgresql + environment: + POSTGRES_USER: "postgres_user" + POSTGRES_PASSWORD: "postgres_password" + POSTGRES_DB: "postgres_db" + networks: + - docker_network + + # This service runs the code server that loads your user code. + docker_code_location_1: + build: + context: . + dockerfile: ./Dockerfile_code_location_1 + container_name: docker_code_location_1 + image: docker_user_code_image + restart: always + environment: + DAGSTER_POSTGRES_USER: "postgres_user" + DAGSTER_POSTGRES_PASSWORD: "postgres_password" + DAGSTER_POSTGRES_DB: "postgres_db" + DAGSTER_CURRENT_IMAGE: "docker_user_code_image" + networks: + - docker_network + + # This service runs dagster-webserver. + docker_webserver: + build: + context: . + dockerfile: ./Dockerfile_dagster + entrypoint: + - dagster-webserver + - -h + - "0.0.0.0" + - -p + - "3000" + - -w + - workspace.yaml + container_name: docker_webserver + expose: + - "3000" + ports: + - "3000:3000" + environment: + DAGSTER_POSTGRES_USER: "postgres_user" + DAGSTER_POSTGRES_PASSWORD: "postgres_password" + DAGSTER_POSTGRES_DB: "postgres_db" + volumes: # Make docker client accessible so we can terminate containers from the webserver + - /var/run/docker.sock:/var/run/docker.sock + - /tmp/io_manager_storage:/tmp/io_manager_storage + networks: + - docker_network + depends_on: + - docker_postgresql + - docker_code_location_1 + + # This service runs the dagster-daemon process, which is responsible for taking runs + # off of the queue and launching them, as well as creating runs from schedules or sensors. + docker_daemon: + build: + context: . + dockerfile: ./Dockerfile_dagster + entrypoint: + - dagster-daemon + - run + container_name: docker_daemon + restart: on-failure + environment: + DAGSTER_POSTGRES_USER: "postgres_user" + DAGSTER_POSTGRES_PASSWORD: "postgres_password" + DAGSTER_POSTGRES_DB: "postgres_db" + volumes: # Make docker client accessible so we can launch containers using host docker + - /var/run/docker.sock:/var/run/docker.sock + - /tmp/io_manager_storage:/tmp/io_manager_storage + networks: + - docker_network + depends_on: + - docker_postgresql + - docker_code_location_1 + +networks: + docker_network: + driver: bridge + name: docker_network +``` + +## Start your deployment + +To start the deployment, run: + +```shell +docker compose up +``` diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/google-cloud-platform.md b/docs/docs-beta/docs/guides/deploy/deployment-options/google-cloud-platform.md new file mode 100644 index 0000000000000..0cdd2376cb6b5 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/google-cloud-platform.md @@ -0,0 +1,5 @@ +--- +title: "Deploy to Google Cloud Platform" +unlisted: true +sidebar_position: 600 +--- diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/index.mdx b/docs/docs-beta/docs/guides/deploy/deployment-options/index.mdx new file mode 100644 index 0000000000000..757020a9b3852 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/index.mdx @@ -0,0 +1,8 @@ +--- +title: "Deployment options" +sidebar_position: 10 +--- + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/kubernetes.md b/docs/docs-beta/docs/guides/deploy/deployment-options/kubernetes.md new file mode 100644 index 0000000000000..f29729c61072b --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/kubernetes.md @@ -0,0 +1,201 @@ +--- +title: "Deploy to Kubernetes" +sidebar_position: 300 +--- + +This guide will walk you through how to run the Dagster-specific components of a Dagster production deployment on a Kubernetes cluster. This includes the Dagster daemon, a webserver to serve the Dagster UI, a PostgrSQL container, and your Dagster project user code. + +Dagster provides [Helm charts](https://github.com/dagster-io/dagster/tree/master/helm) for deploying Dagster that you can customize for your specific needs. For each Dagster component used by the Helm chart, Dagster publishes a corresponding image to [DockerHub](https://hub.docker.com/u/dagster). + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- **Familiarity with [Docker](https://docs.docker.com/)**, and: + - **To have Docker installed**. [Docker installation guide](https://docs.docker.com/engine/install/) + - **Access to a Docker image registry**, such as Amazon Web Services ECR or DockerHub. If you're following along on your local machine, this isn't required. +- **Familiarity with [Kubernetes](https://kubernetes.io/docs/home/)**, and: + - **To have `kubectl` installed**. [Kubernetes installation guide](https://kubernetes.io/docs/tasks/tools/) + - **An existing Kubernetes cluster**. To follow along on your local machine, [install Docker Desktop](https://docs.docker.com/desktop/kubernetes/) and turn on the included Kubernetes server. +- **Familiarity with [Helm](https://helm.sh/docs/)**, and: + - **To have Helm 3 installed**. [Helm installation guide](https://helm.sh/docs/intro/install/) +- A Dagster project to deploy. You can also use the [example project](/todo): + ```bash + dagster project from-example --example deploy_k8s_beta --name deploy_k8s_beta + ``` + +
    + + +## Step 1: Write and build a Docker image containing your Dagster project +### Step 1.1: Write a Dockerfile +Next, you'll build a Docker image that contains your Dagster project and all of its dependencies. The Dockerfile should: +1. Copy your Dagster project into the image. +2. Install `dagster`, `dagster-postgres`, and `dagster-k8s`, along with any other libraries your project depends on. The example project has a dependency on `pandas` so it's included in the `pip install` in the following example Dockerfile. +3. Expose port 80, which we'll use to set up port-forwarding later. + + + + +### Step 1.2: Build and push a Docker image + +To build your Docker image, run the following command from the directory where your Dockerfile is located: + +```bash +docker build . -t iris_analysis:1 +``` +This builds the Docker image from Step 1.1 and gives it the name `iris_analysis` and tag `1`. You can set custom values for both the name and the tag. We recommend that each time you rebuild your Docker image, you assign a new value for the tag to ensure that the correct image is used when running your code. + + +If you are using a Docker image registry, push the image to your registry. If you are following along on your local machine, you can skip this command. + +```bash +docker push iris_analysis:1 +``` + +If you are pushing your image to an image registry, you can find more information about this process in your registry's documentation: +- [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html) +- [DockerHub](https://docs.docker.com/docker-hub/quickstart/#step-5-build-and-push-a-container-image-to-docker-hub-from-your-computer) + + +## Step 2: Configure `kubectl` to point at a Kubernetes cluster +Before you can deploy Dagster, you need to configure `kubectl` to develop against the Kubernetes cluster where you want Dagster to be deployed. + +If you are using Docker Desktop and the included Kubernetes server, you will need to create a context first. If you already have a Kubernetes cluster and context created for your Dagster deployment you can skip running this command. +```bash +kubectl config set-context dagster --namespace default --cluster docker-desktop --user=docker-desktop +``` + +Ensure that `kubectl` is using the correct context by running: +```bash +kubectl config use-context +``` +Where `` is the name of the context you want to use. For example, if you ran the preceding `kubectl config set-context` command, you will run +```bash +kubectl config use-context dagster +``` + +## Step 3: Add the Dagster Helm chart repository + +Dagster publishes [Helm charts](https://artifacthub.io/packages/helm/dagster/dagster) for deploying Dagster, with a new chart for each Dagster version. + +To install the Dagster Helm charts, run the following command: + +```bash +helm repo add dagster https://dagster-io.github.io/helm +``` + +If you have previously added the Dagster Helm charts, run the following command to update the repository: + +```bash +helm repo update +``` + +## Step 4: Configure the Helm chart for your deployment + +You will need to modify some values in Dagster's Helm chart to deploy your Dagster project. + +### Step 4.1: Copy default Helm chart values into values.yaml + +Run the following command to copy the values installed from the published Helm charts: + +```bash +helm show values dagster/dagster > values.yaml +``` + +### Step 4.2: Modify the `values.yaml` file for your deployment +The `values.yaml` file contains configuration options you can set for your deployment. Different configuration options are explained in [inline comments in `values.yaml`](https://artifacthub.io/packages/helm/dagster/dagster?modal=values). + +To deploy your project, you'll need to set the following options: +- `dagster-user-deployments.deployments.name`, which should be a unique name for your deployment +- `dagster-user-deployments.deployments.image.name` and `dagster-user-deployments.deployments.image.tag`, which should be set to match the Docker image from Step 1 +- `dagster-user-deployments.deployments.dagsterApiGrpcArgs`, which should be set to the arguments you would pass to `dagster api grpc` to [run a gRPC server for your project](https://docs.dagster.io/concepts/code-locations/workspace-files#running-your-own-grpc-server). + +If you are following this guide on your local machine, you will also need to set `pullPolicy: IfNotPresent`. This will use the local version of the image built in Step 1. However, in production use cases when your Docker images are pushed to image registries, this value should remain `pullPolicy: Always`. + + + +In this example, the image `name` and `tag` are set to `iris_analysis` and `1` to match the image that was pushed in Step 1. To run the gPRC server, the path to the Dagster project needs to be specified, so `--python-file` and `/iris_analysis/definitions.py` are set for `dagsterApiGrpcArgs`. + + +## Step 5: Install the Helm chart +Now that you have modified the Helm `values.yaml` file, you can install the changes in your Kubernetes cluster. + +Run the following command to install the Helm chart and create a [release](https://helm.sh/docs/intro/using_helm/#three-big-concepts). + +```bash +helm upgrade --install dagster dagster/dagster -f /path/to/values.yaml +``` + +:::note +If you want to run an older version of the Dagster system components, like the daemon and webserver, pass the `--version` flag to `helm upgrade` with the version of Dagster you are running. For example, if you want to run version `1.7.4` you'll run the command `helm upgrade --install dagster dagster/dagster -f /path/to/values.yaml --version 1.7.4` +::: + +The `helm upgrade` command will launch several pods in your Kubernetes cluster. You can check the status of the pod with the command: + +```bash +kubectl get pods +``` + +It may take a few minutes before all pods are in a `RUNNING` state. If the `helm upgrade` was successful, you should see a `kubectl get pods` output similar to this: + +```bash +$ kubectl get pods +NAME READY STATUS AGE +dagster-daemon-5787ccc868-nsvsg 1/1 Running 3m41s +dagster-webserver-7c5b5c7f5c-rqrf8 1/1 Running 3m41s +dagster-dagster-user-deployments-iris-analysis-564cbcf9f-fbqlw 1/1 Running 3m41s +dagster-postgresql-0 1/1 Running 3m41s +``` + +
    + Debugging failed pods + +If one of the pods is in an error state, you can view the logs using the command + +```bash +kubectl logs +``` + +For example, if the pod `dagster-webserver-7c5b5c7f5c-rqrf8` is in a `CrashLoopBackOff` state, the logs can be viewed with the command + +``` +kubectl logs dagster-webserver-7c5b5c7f5c-rqrf8 +``` + +
    + + +## Step 6: Connect to your Dagster deployment and materialize your assets + +### Step 6.1: Start port-forwarding to the webserver pod +Run the following command to set up port forwarding to the webserver pod: + +```bash +DAGSTER_WEBSERVER_POD_NAME=$(kubectl get pods --namespace default \ + -l "app.kubernetes.io/name=dagster,app.kubernetes.io/instance=dagster,component=dagster-webserver" \ + -o jsonpath="{.items[0].metadata.name}") +kubectl --namespace default port-forward $DAGSTER_WEBSERVER_POD_NAME 8080:80 +``` + +This command gets the full name of the `webserver` pod from the output of `kubectl get pods`, and then sets up port forwarding with the `kubectl port-forward` command. + +### Step 6.2: Visit your Dagster deployment + +The webserver has been port-forwarded to `8080`, so you can visit the Dagster deployment by going to [http://127.0.0.1:8080](http://127.0.0.1:8080). You should see the Dagster landing page + +![Screenshot of Dagster landing page](/img/placeholder.svg) + +### Step 6.3: Materialize an asset +In the Dagster UI, navigate to the Asset catalog and click the **Materialize** button to materialize an asset. Dagster will start a Kubernetes job to materialize the asset. You can introspect on the Kubernetes cluster to see this job: + +```bash +$ kubectl get jobs +NAME COMPLETIONS DURATION AGE +dagster-run-5ee8a0b3-7ca5-44e6-97a6-8f4bd86ee630 1/1 4s 11s +``` + +## Next steps +- Forwarding Dagster logs from a Kubernetes deployment to AWS, Azure, GCP +- Other configuration options for K8s deployment - secrets, diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/microsoft-azure.md b/docs/docs-beta/docs/guides/deploy/deployment-options/microsoft-azure.md new file mode 100644 index 0000000000000..a33096ceb12c0 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/microsoft-azure.md @@ -0,0 +1,5 @@ +--- +title: "Deploy to Microsoft Azure" +unlisted: true +sidebar_position: 700 +--- diff --git a/docs/docs-beta/docs/guides/deploy/deployment-options/running-local-ui-development.md b/docs/docs-beta/docs/guides/deploy/deployment-options/running-local-ui-development.md new file mode 100644 index 0000000000000..f6e84c3fafe95 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/deployment-options/running-local-ui-development.md @@ -0,0 +1,77 @@ +--- +title: Running Dagster locally +description: How to run Dagster on your local machine. +sidebar_position: 100 +--- + +# Running Dagster locally + +In this guide, we'll walk you through how to run Dagster on your local machine using the `dagster dev` command. The `dagster dev` command launches the Dagster UI and the Dagster daemon, allowing you to start a full deployment of Dagster from the command line. + +:::warning +`dagster dev` is intended for local development _only_. If you want to run Dagster for production use cases, see our other [deployment guides](/guides/deploy/deployment-options/index.mdx). +::: + +## Locating your code + +Before starting local development, you need to tell Dagster how to find the Python code containing your assets and jobs. + +For a refresher on how to set up a Dagster project, follow our [Recommended Dagster Project Structure](/todo) guide. + + + + Dagster can load Python modules as code locations. + + We can use the `-m` argument to supply the name of the module to start a Dagster instance loaded with our definitions: + ```shell + dagster dev -m my_module + ``` + + + + To load definitions from a module without supplying the `-m` command line argument, you can use a `pyproject.toml` file. This file, included in all Dagster example projects, contains a `tool.dagster` section where you can supply the `module_name`: + + + + + + Dagster can load a file directly as a code location. + + Given the preceding file, we can use the `-f` argument to supply the name of the file to start a Dagster instance loaded with our definitions: + ```shell + dagster dev -f defs.py + ``` + + :::note + We don't recommend using the `-f` argument for production deployments, to avoid a whole class of Python import errors. + ::: + + + + +## Creating a persistent instance + +Running `dagster dev` without any additional configuration starts an ephemeral instance in a temporary directory. You may see log output indicating as such: +```shell +Using temporary directory /Users/rhendricks/tmpqs_fk8_5 for storage. +``` +This indicates that any runs or materialized assets created during your session won't be persisted once the session ends. + +To designate a more permanent home for your runs and assets, you can set the `DAGSTER_HOME` environment variable to a folder on your filesystem. Dagster will then use the specified folder for storage on all subsequent runs of `dagster dev`. + +```shell +mkdir -p ~/.dagster_home +export DAGSTER_HOME=~/.dagster_home +dagster dev +``` + +## Configuring your instance + +To configure your Dagster instance, you can create a `dagster.yaml` file in your `$DAGSTER_HOME` folder. + +For example, to have your local instance limit the number of concurrent runs, you could configure the following `dagster.yaml`: + + + +For the full list of options that can be set in the `dagster.yaml` file, refer to the [Dagster instance documentation](/todo). + diff --git a/docs/docs-beta/docs/guides/deploy/execution/dagster-daemon.md b/docs/docs-beta/docs/guides/deploy/execution/dagster-daemon.md new file mode 100644 index 0000000000000..85da08fe450d3 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/execution/dagster-daemon.md @@ -0,0 +1,7 @@ +--- +title: "Dagster daemon" +sidebar_position: 100 +unlisted: true +--- + +# Dagster daemon diff --git a/docs/docs-beta/docs/guides/deploy/execution/index.mdx b/docs/docs-beta/docs/guides/deploy/execution/index.mdx new file mode 100644 index 0000000000000..c1bbbc2b8a5e0 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/execution/index.mdx @@ -0,0 +1,8 @@ +--- +title: "Execution" +sidebar_position: 20 +--- + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/deploy/execution/run-coordinators.md b/docs/docs-beta/docs/guides/deploy/execution/run-coordinators.md new file mode 100644 index 0000000000000..48ce80b1690cc --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/execution/run-coordinators.md @@ -0,0 +1,7 @@ +--- +title: "Run coordinators" +sidebar_position: 400 +unlisted: true +--- + +# Run coordinators diff --git a/docs/docs-beta/docs/guides/deploy/execution/run-executors.md b/docs/docs-beta/docs/guides/deploy/execution/run-executors.md new file mode 100644 index 0000000000000..7351a18aefd9d --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/execution/run-executors.md @@ -0,0 +1,7 @@ +--- +title: "Run executors" +sidebar_position: 300 +unlisted: true +--- + +# Run executors diff --git a/docs/docs-beta/docs/guides/deploy/execution/run-launchers.md b/docs/docs-beta/docs/guides/deploy/execution/run-launchers.md new file mode 100644 index 0000000000000..f4982c170a6b3 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/execution/run-launchers.md @@ -0,0 +1,7 @@ +--- +title: "Run launchers" +sidebar_position: 200 +unlisted: true +--- + +# Run launchers diff --git a/docs/docs-beta/docs/guides/deploy/index.md b/docs/docs-beta/docs/guides/deploy/index.md new file mode 100644 index 0000000000000..3a5ec3fb353d1 --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/index.md @@ -0,0 +1,15 @@ +--- +title: "Deploying Dagster" +sidebar_position: 70 +sidebar_class_name: hidden +--- + +# Deploying Dagster + +This section is about self-hosting Dagster. + +:::info +To deploy to Dagster+, see the [Dagster+ getting started guide](/dagster-plus/getting-started). + +To migrate from self-hosted to Dagster+, see [Migrate from self-hosted to Dagster+](/dagster-plus/deployment/migration/self-hosted-to-dagster-plus). +::: diff --git a/docs/docs-beta/docs/guides/deploy/secrets.md b/docs/docs-beta/docs/guides/deploy/secrets.md new file mode 100644 index 0000000000000..5134eb92e17aa --- /dev/null +++ b/docs/docs-beta/docs/guides/deploy/secrets.md @@ -0,0 +1,5 @@ +--- +title: Managing secrets +sidebar_position: 100 +unlisted: true +--- diff --git a/docs/docs-beta/docs/guides/monitor/alerting.md b/docs/docs-beta/docs/guides/monitor/alerting.md new file mode 100644 index 0000000000000..92c409cce7b8a --- /dev/null +++ b/docs/docs-beta/docs/guides/monitor/alerting.md @@ -0,0 +1,13 @@ +--- +title: "Setting up alerts" +sidebar_position: 10 +unlisted: true +--- + +(This will likely be a category) + +Alerting if my pipeline didn't execute +Tracking when a run or sensor fails +Knowing when a pipeline never ran +Knowing if a pipeline is running slow, or an asset is late +Knowing if my Dagster instance is having issues diff --git a/docs/docs-beta/docs/guides/monitor/index.md b/docs/docs-beta/docs/guides/monitor/index.md new file mode 100644 index 0000000000000..aaf06312205dc --- /dev/null +++ b/docs/docs-beta/docs/guides/monitor/index.md @@ -0,0 +1,7 @@ +--- +title: "Monitoring pipelines" +sidebar_position: 50 +sidebar_class_name: hidden +--- + +This section is about monitoring pipelines. \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/monitor/logging/custom-logging.md b/docs/docs-beta/docs/guides/monitor/logging/custom-logging.md new file mode 100644 index 0000000000000..c3bf0380c5621 --- /dev/null +++ b/docs/docs-beta/docs/guides/monitor/logging/custom-logging.md @@ -0,0 +1,136 @@ +--- +title: "Setting up custom logging" +sidebar_position: 100 +--- + +# Custom loggers + +Custom loggers are used to alter the structure of the logs being produced by your Dagster pipelines. For example, JSON logs can be produced to more easily be processed by log management systems. + +
    + Prerequisites + +To follow the steps in this guide, you'll need: + +- A basic understanding of Dagster concepts such as assets, jobs and definitions +- A working knowledge of the Python logging module + +
    + + +## Step 1: Add a prebuilt custom logger to your jobs + +This step shows how to add an existing custom logger, the `json_console_logger`, to your jobs. This will +override the default `colored_console_logger` and produce logs in JSON format. + + +### Add the custom logger to your asset jobs + +The following example shows how to add the custom logger to your code location definitions and configure an asset job to use it. + + + + +### Add the custom logger to your ops-based jobs + +Configuring a ops job to use the custom logger slightly differs from the asset job example. The following example shows how: + + + + +### Expected `json_console_logger` output + +The `json_console_logger` will emit an exhaustive single line JSON document containing the full log record, including the dagster metadata fields. + +Here's an example of the output for reference, formatted for readability: + +```json +{ + "args": [], + "created": 1725455358.2311811, + "dagster_meta": { + "dagster_event": null, + "dagster_event_batch_metadata": null, + "job_name": "hackernews_topstory_ids_job", + "job_tags": { + ".dagster/grpc_info": "{\"host\": \"localhost\", \"socket\": \"/var/folders/5b/t062dlpj3j716l4w1d3yq6vm0000gn/T/tmpds_hvzm9\"}", + "dagster/preset_name": "default", + "dagster/solid_selection": "*" + }, + "log_message_id": "3850cfb8-f9fb-458a-a986-3efd26e4b859", + "log_timestamp": "2024-09-04T13:09:18.225289", + "op_name": "get_hackernews_topstory_ids", + "orig_message": "Compute Logger - Got 500 top stories.", + "resource_fn_name": null, + "resource_name": null, + "run_id": "11528a21-38d5-43e7-8b13-993e47ce7f7d", + "step_key": "get_hackernews_topstory_ids" + }, + "exc_info": null, + "exc_text": null, + "filename": "log_manager.py", + "funcName": "emit", + "levelname": "INFO", + "levelno": 20, + "lineno": 272, + "module": "log_manager", + "msecs": 231.0, + "msg": "hackernews_topstory_ids_job - 11528a21-38d5-43e7-8b13-993e47ce7f7d - get_hackernews_topstory_ids - Compute Logger - Got 500 top stories.", + "name": "dagster", + "pathname": "/home/dagster/workspace/quickstart-etl/.venv/lib/python3.11/site-packages/dagster/_core/log_manager.py", + "process": 35373, + "processName": "SpawnProcess-2:1", + "relativeCreated": 813.4410381317139, + "stack_info": null, + "thread": 8584465408, + "threadName": "MainThread" +} +``` + +### Changing the logger configuration in the Dagster UI + +You can also change the logger configuration in the Dagster UI. This is useful if you want to change the logger configuration without changing the code, to use the custom logger on a manual asset materialization launch, or change the verbosity of the logs. + +```yaml +loggers: + console: + config: + log_level: DEBUG +``` + +## Step 2: Write your custom logger + +In this example, we'll create a logger implementation that produces comma separated values from selected fields in the +log record. Other examples can be found in the codebase, in the built-in loggers such as `json_console_logger`. + + + +Sample output: + +```csv +2024-09-04T09:29:33.643818,dagster,INFO,cc76a116-4c8f-400f-9c4d-c42b66cdee3a,topstory_ids_job,hackernews_topstory_ids,Compute Logger - Got 500 top stories. +``` + +The available fields emitted by the logger are defined in the [`LogRecord`](https://docs.python.org/3/library/logging.html#logrecord-objects) object. +In addition, Dagster specific information can be found in the `dagster_meta` attribute of the log record. The previous +example already some of these attributes. + +It contains the following fields: + +- `dagster_event`: string +- `dagster_event_batch_metadata`: string +- `job_name`: string +- `job_tags`: a dictionary of strings +- `log_message_id`: string +- `log_timestamp`: string +- `op_name`: string +- `run_id`: string +- `step_key`: string + +## Next steps + +Import your own custom logger by modifying the example provided in step 1. + +## Limitations + +It's not currently possible to globally configure the logger for all jobs in a repository. diff --git a/docs/docs-beta/docs/guides/monitor/logging/custom-metrics-logs.md b/docs/docs-beta/docs/guides/monitor/logging/custom-metrics-logs.md new file mode 100644 index 0000000000000..62476124e059c --- /dev/null +++ b/docs/docs-beta/docs/guides/monitor/logging/custom-metrics-logs.md @@ -0,0 +1,5 @@ +--- +title: "Use custom metrics in logs" +sidebar_position: 200 +unlisted: true +--- diff --git a/docs/docs-beta/docs/guides/monitor/logging/index.mdx b/docs/docs-beta/docs/guides/monitor/logging/index.mdx new file mode 100644 index 0000000000000..8de645e227aec --- /dev/null +++ b/docs/docs-beta/docs/guides/monitor/logging/index.mdx @@ -0,0 +1,8 @@ +--- +title: "Logging" +sidebar_position: 20 +--- + +import DocCardList from '@theme/DocCardList'; + + \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/test/asset-checks.md b/docs/docs-beta/docs/guides/test/asset-checks.md new file mode 100644 index 0000000000000..3fddf035591b1 --- /dev/null +++ b/docs/docs-beta/docs/guides/test/asset-checks.md @@ -0,0 +1,84 @@ +--- +title: "Testing assets with Asset checks" +sidebar_position: 100 +sidebar_label: "Asset checks" +--- + +Asset checks are tests that verify specific properties of your data assets, allowing you to execute data quality checks on your data. For example, you can create checks to: + +- Ensure a particular column doesn't contain null values +- Verify that a tabular asset adheres to a specified schema +- Check if an asset's data needs refreshing + +Each asset check should test only a single asset property to keep tests uncomplicated, reusable, and easy to track over time. + +
    +Prerequisites + +To follow this guide, you'll need: + +- Familiarity with [Assets](/guides/build/assets-concepts/index.mdx +
    + +## Getting started + +To get started with asset checks, follow these general steps: + +1. **Define an asset check:** Asset checks are typically defined using the `@asset_check` or `@multi_asset_check` decorator and run either within an asset or separate from the asset. +2. **Pass the asset checks to the `Definitions` object:** Asset checks must be added to `Definitions` for Dagster to recognize them. +3. **Choose how to execute asset checks**: By default, all jobs targeting an asset will also run associated checks, although you can run asset checks through the Dagster UI. +4. **View asset check results in the UI**: Asset check results will appear in the UI and can be customized through the use of metadata and severity levels +5. **Alert on failed asset check results**: If you are using Dagster+, you can choose to alert on asset checks. + +## Defining a single asset check \{#single-check} + +:::tip +Dagster's dbt integration can model existing dbt tests as asset checks. Refer to the [dagster-dbt documentation](/integrations/dbt) for more information. +::: + +A asset check is defined using the `@asset_check` decorator. + +The following example defines an asset check on an asset that fails if the `order_id` column of the asset contains a null value. The asset check will run after the asset has been materialized. + + + +## Defining multiple asset checks \{#multiple-checks} + +In most cases, checking the data quality of an asset will require multiple checks. + +The following example defines two asset checks using the `@multi_asset_check` decorator: + +- One check that fails if the `order_id` column of the asset contains a null value +- Another check that fails if the `item_id` column of the asset contains a null value + +In this example, both asset checks will run in a single operation after the asset has been materialized. + + + +## Programmatically generating asset checks \{#factory-pattern} + +Defining multiple checks can also be done using a factory pattern. The example below defines the same two asset checks as in the previous example, but this time using a factory pattern and the `@multi_asset_check` decorator. + + + +## Blocking downstream materialization + +By default, if a parent's asset check fails during a run, the run will continue and downstream assets will be materialized. To prevent this behavior, set the `blocking` argument to `True` in the `@asset_check` decorator. + +In the example bellow, if the `orders_id_has_no_nulls` check fails, the downstream `augmented_orders` asset won't be materialized. + + + +## Scheduling and monitoring asset checks + +In some cases, running asset checks separately from the job materializing the assets can be useful. For example, running all data quality checks once a day and sending an alert if they fail. This can be achieved using schedules and sensors. + +In the example below, two jobs are defined: one for the asset and another for the asset check. Schedules are defined to materialize the asset and execute the asset check independently. A sensor is defined to send an email alert when the asset check job fails. + + + +## Next steps + +- Learn more about assets in [Understanding Assets](/guides/build/assets-concepts/index.mdx +- Learn more about asset checks in [Understanding Asset Checks](/guides/test/asset-checks) +- Learn how to use [Great Expectations with Dagster](https://dagster.io/blog/ensuring-data-quality-with-dagster-and-great-expectations) diff --git a/docs/docs-beta/docs/guides/test/data-freshness-testing.md b/docs/docs-beta/docs/guides/test/data-freshness-testing.md new file mode 100644 index 0000000000000..a738941c2d8f5 --- /dev/null +++ b/docs/docs-beta/docs/guides/test/data-freshness-testing.md @@ -0,0 +1,81 @@ +--- +title: "Checking for data freshness" +sidebar_position: 200 +sidebar_label: "Data freshness" +--- + +Freshness checks provide a way to identify data assets that are overdue for an update. For example, you can use freshness checks to identify stale assets caused by: + +- The pipeline hitting an error and failing +- Runs not being scheduled +- A backed up run queue +- Runs taking longer than expected to complete + +Freshness checks can also communicate SLAs for their data freshness. For example, downstream asset consumers can determine how often assets are expected to be updated by looking at the defined checks. + +
    + Prerequisites + +To follow the steps in this guide, you'll need familiarity with: + +- [Assets](/guides/build/create-a-pipeline/data-assets) +- [External assets](/guides/build/create-a-pipeline/external-assets) +- [Asset checks](/guides/test/asset-checks) + +
    + +## Getting started + +To get started with freshness checks, follow these general steps: + +1. **Define a freshness check**: Freshness checks are defined using `build_last_update_freshness_checks`, which utilizes an asset's last updated time to determine freshness. + + **If using Dagster+ Pro**, you can also use [`build_anomaly_detection_freshness_checks`](#anomaly-detection) to define a freshness check that uses an anomaly detection model to determine freshness. +2. **Define a schedule or sensor**: Defining a schedule or sensor (`build_sensor_for_freshness_checks`) is required to ensure the freshness check executes. If the check only runs after the asset has been materialized, the check won't be able to detect the times materialization fails. +3. **Pass the freshness check and schedule/sensor to the `Definitions` object**: Freshness checks and the associated schedule or sensor must be added to a `Definitions` object for Dagster to recognize them. +4. **View the freshness check results in the Dagster UI**: Freshness check results will appear in the UI, allowing you to track the results over time. + +## Materializable asset freshness \{#materializable-assets} + +Materializable assets are assets materialized by Dagster. To calculate whether a materializable asset is overdue, Dagster uses the asset's last materialization timestamp. + +The example below defines a freshness check on an asset that fails if the asset's latest materialization occurred more than one hour before the current time. + + + +## External asset freshness \{#external-assets} + +[External assets](/guides/build/create-a-pipeline/external-assets) are assets orchestrated by systems other than Dagster. + +To run freshness checks on external assets, the checks need to know when the external assets were last updated. Emitting these update timestamps as values for the `dagster/last_updated_timestamp` observation metadata key allows Dagster to calculate whether the asset is overdue. + +The example below defines a freshness check and adds a schedule to run the check periodically. + + + +### Testing freshness with anomaly detection \{#anomaly-detection} + +:::note +Anomaly detection is a Dagster+ Pro feature. +::: + +Instead of applying policies on an asset-by-asset basis, Dagster+ Pro users can use `build_anomaly_detection_freshness_checks` to take advantage of a time series anomaly detection model to determine if data arrives later than expected. + + + +:::note +If the asset hasn't been updated enough times, the check will pass with a message indicating that more data is needed to detect anomalies. +::: + +## Alerting on overdue assets + +:::note +Freshness check alerts are a Dagster+ feature. +::: + +In Dagster+, you can set up alerts to notify you when assets are overdue for an update. Refer to the [Dagster+ alerting guide](/dagster-plus/features/alerts) for more information. + +## Next steps + +- Explore more [asset checks](/guides/test/asset-checks) +- Explore how to [raise alerts when assets are overdue](/dagster-plus/features/alerts) (Dagster+ Pro) \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/test/index.md b/docs/docs-beta/docs/guides/test/index.md new file mode 100644 index 0000000000000..6284fc0b252bc --- /dev/null +++ b/docs/docs-beta/docs/guides/test/index.md @@ -0,0 +1,7 @@ +--- +title: "Testing assets" +sidebar_position: 60 +sidebar_class_name: hidden +--- + +This section is about testing assets. \ No newline at end of file diff --git a/docs/docs-beta/docs/guides/test/unit-tests-assets-and-ops.md b/docs/docs-beta/docs/guides/test/unit-tests-assets-and-ops.md new file mode 100644 index 0000000000000..057ef145945bd --- /dev/null +++ b/docs/docs-beta/docs/guides/test/unit-tests-assets-and-ops.md @@ -0,0 +1,111 @@ +--- +title: "Unit testing assets and ops" +sidebar_position: 300 +sidebar_label: "Unit testing" +--- + +Unit testing is essential for ensuring that computations function as intended. In the context of data pipelines, this can be particularly challenging. However, Dagster streamlines the process by enabling direct invocation of computations with specified input values and mocked resources, making it easier to verify that data transformations behave as expected. + +While unit tests can't fully replace integration tests or manual review, they can catch a variety of errors with a significantly faster feedback loop. + +This guide covers how to write unit tests for assets and ops with a variety of different input requirements. + +
    +Prerequisites + +To follow the steps in this guide, you'll need familiarity with: + +- [Assets](/guides/build/assets-concepts/index.mdx +- [Ops and Jobs](/guides/build/ops-jobs) +
    + +## Before you start + +Before you begin implementing unit tests, note that: + +- Testing individual assets or ops is generally recommended over unit testing entire jobs +- Unit testing isn't recommended in cases where most of the business logic is encoded in an external system, such as an asset which directly invokes an external Databricks job. + +## Assets and ops without arguments \{#no-arguments} + +The simplest assets and ops to test are those with no arguments. In these cases, you can directly invoke definitions. + + + + + + + + + + +## Assets and ops with upstream dependencies \{#upstream-dependencies} + +If an asset or op has an upstream dependency, you can directly pass a value for that dependency when invoking the definition. + + + + + + + + + + +## Assets and ops with config \{#config} + +If an asset or op uses config, you can construct an instance of the required config object and pass it in directly. + + + + + + + + + + +## Assets and ops with resources \{#resources} + +If an asset or op uses a resource, it can be useful to create a mock instance of the resource to avoid interacting with external services. + + + + + + + + + + +## Assets and ops with context \{#context} + +If an asset or op uses a `context` argument, you can use `build_asset_context()` or `build_op_context()` to construct a context object. + + + + + + + + + + +## Assets and ops with multiple parameters \{#multiple-parameters} + +If an asset or op has multiple parameters, it's recommended to use keyword arguments for clarity. + + + + + + + + + + +## Next steps + +- Learn more about assets in [Understanding Assets](/guides/build/assets-concepts/index.mdx +- Learn more about ops in [Understanding Ops](/guides/build/ops-jobs) +- Learn more about resources in [Resources](/guides/build/configure/resources) \ No newline at end of file diff --git a/examples/experimental/dagster-components/LICENSE b/examples/experimental/dagster-components/LICENSE new file mode 100644 index 0000000000000..1ba565405dd93 --- /dev/null +++ b/examples/experimental/dagster-components/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Dagster Labs, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/examples/experimental/dagster-components/MANIFEST.in b/examples/experimental/dagster-components/MANIFEST.in new file mode 100644 index 0000000000000..f69623e7f6cb7 --- /dev/null +++ b/examples/experimental/dagster-components/MANIFEST.in @@ -0,0 +1,3 @@ +include README.md +include LICENSE +include dagster_components/py.typed diff --git a/examples/experimental/dagster-components/README.md b/examples/experimental/dagster-components/README.md new file mode 100644 index 0000000000000..885fc94f46adf --- /dev/null +++ b/examples/experimental/dagster-components/README.md @@ -0,0 +1,4 @@ +# dagster-components + +Experimental API for defining Dagster definitions factories ("components"). +Includes the `dg` CLI tool. diff --git a/examples/experimental/dagster-components/dagster_components/__init__.py b/examples/experimental/dagster-components/dagster_components/__init__.py new file mode 100644 index 0000000000000..4438df21a7f13 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/__init__.py @@ -0,0 +1,17 @@ +from dagster_components.core.component import ( + Component as Component, + ComponentLoadContext as ComponentLoadContext, + ComponentRegistry as ComponentRegistry, +) +from dagster_components.core.component_defs_builder import ( + build_defs_from_toplevel_components_folder as build_defs_from_toplevel_components_folder, +) +from dagster_components.impls.pipes_subprocess_script_collection import ( + PipesSubprocessScriptCollection, +) +from dagster_components.impls.sling_replication import SlingReplicationComponent + +__component_registry__ = { + "pipes_subprocess_script_collection": PipesSubprocessScriptCollection, + "sling_replication": SlingReplicationComponent, +} diff --git a/examples/experimental/dagster-components/dagster_components/cli/__init__.py b/examples/experimental/dagster-components/dagster_components/cli/__init__.py new file mode 100644 index 0000000000000..5b179e78098cb --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/cli/__init__.py @@ -0,0 +1,28 @@ +import click +from dagster.version import __version__ + +from dagster_components.cli.generate import generate_cli + + +def create_dagster_components_cli(): + commands = { + "generate": generate_cli, + } + + @click.group( + commands=commands, + context_settings={"max_content_width": 120, "help_option_names": ["-h", "--help"]}, + ) + @click.version_option(__version__, "--version", "-v") + def group(): + """CLI tools for working with Dagster.""" + + return group + + +ENV_PREFIX = "DG_CLI" +cli = create_dagster_components_cli() + + +def main(): + cli(auto_envvar_prefix=ENV_PREFIX) diff --git a/examples/experimental/dagster-components/dagster_components/cli/generate.py b/examples/experimental/dagster-components/dagster_components/cli/generate.py new file mode 100644 index 0000000000000..466fe4061f54b --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/cli/generate.py @@ -0,0 +1,108 @@ +import os +import sys +from pathlib import Path + +import click + +from dagster_components import ComponentRegistry, __component_registry__ +from dagster_components.core.deployment import ( + CodeLocationProjectContext, + DeploymentProjectContext, + is_inside_code_location_project, + is_inside_deployment_project, +) +from dagster_components.generate import ( + generate_code_location, + generate_component_instance, + generate_component_type, + generate_deployment, +) + + +@click.group(name="generate") +def generate_cli() -> None: + """Commands for generating Dagster components and related entities.""" + + +@generate_cli.command(name="deployment") +@click.argument("path", type=str) +def generate_deployment_command(path: str) -> None: + """Generate a Dagster deployment instance.""" + dir_abspath = os.path.abspath(path) + if os.path.exists(dir_abspath): + click.echo( + click.style(f"A file or directory at {dir_abspath} already exists. ", fg="red") + + "\nPlease delete the contents of this path or choose another location." + ) + sys.exit(1) + generate_deployment(path) + + +@generate_cli.command(name="code-location") +@click.argument("name", type=str) +def generate_code_location_command(name: str) -> None: + """Generate a Dagster code location inside a component.""" + if not is_inside_deployment_project(Path(".")): + click.echo( + click.style("This command must be run inside a Dagster deployment project.", fg="red") + ) + sys.exit(1) + + context = DeploymentProjectContext.from_path(Path.cwd()) + if context.has_code_location(name): + click.echo(click.style(f"A code location named {name} already exists.", fg="red")) + sys.exit(1) + + code_location_path = os.path.join(context.code_location_root_path, name) + generate_code_location(code_location_path) + + +@generate_cli.command(name="component-type") +@click.argument("name", type=str) +def generate_component_type_command(name: str) -> None: + """Generate a Dagster component instance.""" + if not is_inside_code_location_project(Path(".")): + click.echo( + click.style( + "This command must be run inside a Dagster code location project.", fg="red" + ) + ) + sys.exit(1) + + context = CodeLocationProjectContext.from_path( + Path.cwd(), ComponentRegistry(__component_registry__) + ) + if context.has_component_type(name): + click.echo(click.style(f"A component type named `{name}` already exists.", fg="red")) + sys.exit(1) + + generate_component_type(context.component_types_root_path, name) + + +@generate_cli.command(name="component") +@click.argument("component-type", type=str) +@click.argument("name", type=str) +def generate_component_command(component_type: str, name: str) -> None: + """Generate a Dagster component instance.""" + if not is_inside_code_location_project(Path(".")): + click.echo( + click.style( + "This command must be run inside a Dagster code location project.", fg="red" + ) + ) + sys.exit(1) + + context = CodeLocationProjectContext.from_path( + Path.cwd(), ComponentRegistry(__component_registry__) + ) + if not context.has_component_type(component_type): + click.echo( + click.style(f"No component type `{component_type}` could be resolved.", fg="red") + ) + sys.exit(1) + elif context.has_component_instance(name): + click.echo(click.style(f"A component instance named `{name}` already exists.", fg="red")) + sys.exit(1) + + component_type_cls = context.get_component_type(component_type) + generate_component_instance(context.component_instances_root_path, name, component_type_cls) diff --git a/examples/experimental/dagster-components/dagster_components/core/__init__.py b/examples/experimental/dagster-components/dagster_components/core/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/core/component.py b/examples/experimental/dagster-components/dagster_components/core/component.py new file mode 100644 index 0000000000000..85e04307385d5 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/core/component.py @@ -0,0 +1,90 @@ +import copy +from abc import ABC, abstractmethod +from types import ModuleType +from typing import TYPE_CHECKING, ClassVar, Dict, Iterable, Mapping, Optional, Type + +from dagster._core.errors import DagsterError +from dagster._utils import snakecase +from typing_extensions import Self + +if TYPE_CHECKING: + from dagster._core.definitions.definitions_class import Definitions + + +class ComponentDeclNode: ... + + +class Component(ABC): + name: ClassVar[Optional[str]] = None + + @classmethod + def registered_name(cls) -> str: + return cls.name or snakecase(cls.__name__) + + @classmethod + def generate_files(cls) -> None: + raise NotImplementedError() + + @abstractmethod + def build_defs(self, context: "ComponentLoadContext") -> "Definitions": ... + + @classmethod + @abstractmethod + def from_decl_node( + cls, context: "ComponentLoadContext", decl_node: "ComponentDeclNode" + ) -> Self: ... + + +class ComponentRegistry: + def __init__(self, components: Dict[str, Type[Component]]): + self._components: Dict[str, Type[Component]] = copy.copy(components) + + @staticmethod + def empty() -> "ComponentRegistry": + return ComponentRegistry({}) + + def register(self, name: str, component: Type[Component]) -> None: + if name in self._components: + raise DagsterError(f"There is an existing component registered under {name}") + self._components[name] = component + + def has(self, name: str) -> bool: + return name in self._components + + def get(self, name: str) -> Type[Component]: + return self._components[name] + + def keys(self) -> Iterable[str]: + return self._components.keys() + + def __repr__(self) -> str: + return f"" + + +def register_components_in_module(registry: ComponentRegistry, root_module: ModuleType) -> None: + from dagster._core.definitions.load_assets_from_modules import ( + find_modules_in_package, + find_subclasses_in_module, + ) + + for module in find_modules_in_package(root_module): + for component in find_subclasses_in_module(module, (Component,)): + if component is Component: + continue + registry.register(component.registered_name(), component) + + +class ComponentLoadContext: + def __init__(self, *, resources: Mapping[str, object], registry: ComponentRegistry): + self.registry = registry + self.resources = resources + + @staticmethod + def for_test( + *, + resources: Optional[Mapping[str, object]] = None, + registry: Optional[ComponentRegistry] = None, + ) -> "ComponentLoadContext": + return ComponentLoadContext( + resources=resources or {}, registry=registry or ComponentRegistry.empty() + ) diff --git a/examples/experimental/dagster-components/dagster_components/core/component_decl_builder.py b/examples/experimental/dagster-components/dagster_components/core/component_decl_builder.py new file mode 100644 index 0000000000000..ef1de0fade467 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/core/component_decl_builder.py @@ -0,0 +1,50 @@ +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence, Union + +from dagster._record import record +from dagster._utils.pydantic_yaml import parse_yaml_file_to_pydantic +from pydantic import BaseModel + +from dagster_components.core.component import ComponentDeclNode + + +class DefsFileModel(BaseModel): + component_type: str + component_params: Optional[Mapping[str, Any]] = None + + +@record +class YamlComponentDecl(ComponentDeclNode): + path: Path + defs_file_model: DefsFileModel + + +@record +class ComponentFolder(ComponentDeclNode): + path: Path + sub_decls: Sequence[Union[YamlComponentDecl, "ComponentFolder"]] + + +def find_component_decl(path: Path) -> Optional[ComponentDeclNode]: + # right now, we only support two types of components, both of which are folders + # if the folder contains a defs.yml file, it's a component instance + # otherwise, it's a folder containing sub-components + + if not path.is_dir(): + return None + + defs_path = path / "defs.yml" + + if defs_path.exists(): + defs_file_model = parse_yaml_file_to_pydantic( + DefsFileModel, defs_path.read_text(), str(path) + ) + return YamlComponentDecl(path=path, defs_file_model=defs_file_model) + + subs = [] + for subpath in path.iterdir(): + component = find_component_decl(subpath) + if component: + subs.append(component) + + return ComponentFolder(path=path, sub_decls=subs) if subs else None diff --git a/examples/experimental/dagster-components/dagster_components/core/component_defs_builder.py b/examples/experimental/dagster-components/dagster_components/core/component_defs_builder.py new file mode 100644 index 0000000000000..d772a477f021a --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/core/component_defs_builder.py @@ -0,0 +1,91 @@ +from pathlib import Path +from typing import TYPE_CHECKING, List, Mapping, Optional, Sequence + +from dagster._utils.warnings import suppress_dagster_warnings + +from dagster_components.core.component import Component, ComponentLoadContext, ComponentRegistry +from dagster_components.core.component_decl_builder import ( + ComponentFolder, + YamlComponentDecl, + find_component_decl, +) +from dagster_components.core.deployment import CodeLocationProjectContext + +if TYPE_CHECKING: + from dagster._core.definitions.definitions_class import Definitions + + +def build_component_hierarchy( + context: ComponentLoadContext, component_folder: ComponentFolder +) -> Sequence[Component]: + to_return = [] + for decl_node in component_folder.sub_decls: + if isinstance(decl_node, YamlComponentDecl): + parsed_defs = decl_node.defs_file_model + component_type = context.registry.get(parsed_defs.component_type) + to_return.append(component_type.from_decl_node(context, decl_node)) + elif isinstance(decl_node, ComponentFolder): + to_return.extend(build_component_hierarchy(context, decl_node)) + else: + raise NotImplementedError(f"Unknown component type {decl_node}") + return to_return + + +def build_components_from_component_folder( + context: ComponentLoadContext, + path: Path, +) -> Sequence[Component]: + component_folder = find_component_decl(path) + assert isinstance(component_folder, ComponentFolder) + return build_component_hierarchy(context, component_folder) + + +def build_defs_from_component_folder( + path: Path, + registry: ComponentRegistry, + resources: Mapping[str, object], +) -> "Definitions": + """Build a definitions object from a folder within the components hierarchy.""" + component_folder = find_component_decl(path=path) + assert isinstance(component_folder, ComponentFolder) + context = ComponentLoadContext(resources=resources, registry=registry) + components = build_components_from_component_folder(context=context, path=path) + return defs_from_components(resources=resources, context=context, components=components) + + +@suppress_dagster_warnings +def defs_from_components( + *, + context: ComponentLoadContext, + components: Sequence[Component], + resources: Mapping[str, object], +) -> "Definitions": + from dagster._core.definitions.definitions_class import Definitions + + return Definitions.merge( + *[*[c.build_defs(context) for c in components], Definitions(resources=resources)] + ) + + +# Public method so optional Nones are fine +@suppress_dagster_warnings +def build_defs_from_toplevel_components_folder( + path: Path, + resources: Optional[Mapping[str, object]] = None, + registry: Optional["ComponentRegistry"] = None, +) -> "Definitions": + """Build a Definitions object from an entire component hierarchy.""" + from dagster._core.definitions.definitions_class import Definitions + + context = CodeLocationProjectContext.from_path(path, registry or ComponentRegistry.empty()) + + all_defs: List[Definitions] = [] + for component in context.component_instances: + component_path = Path(context.get_component_instance_path(component)) + defs = build_defs_from_component_folder( + path=component_path, + registry=context.component_registry, + resources=resources or {}, + ) + all_defs.append(defs) + return Definitions.merge(*all_defs) diff --git a/examples/experimental/dagster-components/dagster_components/core/deployment.py b/examples/experimental/dagster-components/dagster_components/core/deployment.py new file mode 100644 index 0000000000000..64a60cc278188 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/core/deployment.py @@ -0,0 +1,163 @@ +import importlib.util +import os +import sys +from pathlib import Path +from typing import Final, Iterable, Type + +from dagster._core.errors import DagsterError +from typing_extensions import Self + +from dagster_components.core.component import ( + Component, + ComponentRegistry, + register_components_in_module, +) + + +def is_inside_deployment_project(path: Path) -> bool: + try: + _resolve_deployment_root_path(path) + return True + except DagsterError: + return False + + +def _resolve_deployment_root_path(path: Path) -> str: + current_path = os.path.abspath(path) + while not _is_deployment_root(current_path): + current_path = os.path.dirname(current_path) + if current_path == "/": + raise DagsterError("Cannot find deployment root") + return current_path + + +def is_inside_code_location_project(path: Path) -> bool: + try: + _resolve_code_location_root_path(path) + return True + except DagsterError: + return False + + +def _resolve_code_location_root_path(path: Path) -> str: + current_path = os.path.abspath(path) + while not _is_code_location_root(current_path): + current_path = os.path.dirname(current_path) + if current_path == "/": + raise DagsterError("Cannot find code location root") + return current_path + + +def _is_deployment_root(path: str) -> bool: + return os.path.exists(os.path.join(path, "code_locations")) + + +def _is_code_location_root(path: str) -> bool: + return os.path.basename(os.path.dirname(path)) == "code_locations" + + +# Deployment +_DEPLOYMENT_CODE_LOCATIONS_DIR: Final = "code_locations" + +# Code location +_CODE_LOCATION_CUSTOM_COMPONENTS_DIR: Final = "lib" +_CODE_LOCATION_COMPONENT_INSTANCES_DIR: Final = "components" + + +class DeploymentProjectContext: + @classmethod + def from_path(cls, path: Path) -> Self: + return cls(root_path=_resolve_deployment_root_path(path)) + + def __init__(self, root_path: str): + self._root_path = root_path + + @property + def deployment_root(self) -> str: + return self._root_path + + @property + def code_location_root_path(self) -> str: + return os.path.join(self._root_path, _DEPLOYMENT_CODE_LOCATIONS_DIR) + + def has_code_location(self, name: str) -> bool: + return os.path.exists(os.path.join(self._root_path, "code_locations", name)) + + +class CodeLocationProjectContext: + @classmethod + def from_path(cls, path: Path, component_registry: "ComponentRegistry") -> Self: + root_path = _resolve_code_location_root_path(path) + name = os.path.basename(root_path) + + # TODO: Rm when a more robust solution is implemented + # Make sure we can import from the cwd + if sys.path[0] != "": + sys.path.insert(0, "") + + components_lib_module = f"{name}.{_CODE_LOCATION_CUSTOM_COMPONENTS_DIR}" + module = importlib.import_module(components_lib_module) + register_components_in_module(component_registry, module) + + return cls( + deployment_context=DeploymentProjectContext.from_path(path), + root_path=root_path, + name=os.path.basename(root_path), + component_registry=component_registry, + ) + + def __init__( + self, + deployment_context: DeploymentProjectContext, + root_path: str, + name: str, + component_registry: "ComponentRegistry", + ): + self._deployment_context = deployment_context + self._root_path = root_path + self._name = name + self._component_registry = component_registry + + @property + def deployment_context(self) -> DeploymentProjectContext: + return self._deployment_context + + @property + def component_types_root_path(self) -> str: + return os.path.join(self._root_path, self._name, _CODE_LOCATION_CUSTOM_COMPONENTS_DIR) + + @property + def component_types_root_module(self) -> str: + return f"{self._name}.{_CODE_LOCATION_CUSTOM_COMPONENTS_DIR}" + + @property + def component_registry(self) -> "ComponentRegistry": + return self._component_registry + + def has_component_type(self, name: str) -> bool: + return self._component_registry.has(name) + + def get_component_type(self, name: str) -> Type[Component]: + if not self.has_component_type(name): + raise DagsterError(f"No component type named {name}") + return self._component_registry.get(name) + + def get_component_instance_path(self, name: str) -> str: + if name not in self.component_instances: + raise DagsterError(f"No component instance named {name}") + return os.path.join(self.component_instances_root_path, name) + + @property + def component_instances_root_path(self) -> str: + return os.path.join(self._root_path, self._name, _CODE_LOCATION_COMPONENT_INSTANCES_DIR) + + @property + def component_instances(self) -> Iterable[str]: + return os.listdir( + os.path.join(self._root_path, self._name, _CODE_LOCATION_COMPONENT_INSTANCES_DIR) + ) + + def has_component_instance(self, name: str) -> bool: + return os.path.exists( + os.path.join(self._root_path, self._name, _CODE_LOCATION_COMPONENT_INSTANCES_DIR, name) + ) diff --git a/examples/experimental/dagster-components/dagster_components/core/registry.py b/examples/experimental/dagster-components/dagster_components/core/registry.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/generate.py b/examples/experimental/dagster-components/dagster_components/generate.py new file mode 100644 index 0000000000000..b731e6f0dfd01 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/generate.py @@ -0,0 +1,61 @@ +import os +from typing import Type + +import click +from dagster._generate.generate import generate_project +from dagster._utils import camelcase, pushd + +from dagster_components.core.component import Component + + +def generate_deployment(path: str) -> None: + click.echo(f"Creating a Dagster deployment at {path}.") + + generate_project( + path=path, + name_placeholder="DEPLOYMENT_NAME_PLACEHOLDER", + templates_path=os.path.join( + os.path.dirname(__file__), "templates", "DEPLOYMENT_NAME_PLACEHOLDER" + ), + ) + + +def generate_code_location(path: str) -> None: + click.echo(f"Creating a Dagster code location at {path}.") + + generate_project( + path=path, + name_placeholder="CODE_LOCATION_NAME_PLACEHOLDER", + templates_path=os.path.join( + os.path.dirname(__file__), "templates", "CODE_LOCATION_NAME_PLACEHOLDER" + ), + ) + + +def generate_component_type(root_path: str, name: str) -> None: + click.echo(f"Creating a Dagster component type at {root_path}/{name}.py.") + + generate_project( + path=root_path, + name_placeholder="COMPONENT_TYPE_NAME_PLACEHOLDER", + templates_path=os.path.join(os.path.dirname(__file__), "templates", "COMPONENT_TYPE"), + project_name=name, + component_type_class_name=camelcase(name), + ) + + +def generate_component_instance(root_path: str, name: str, component_type: Type[Component]) -> None: + click.echo(f"Creating a Dagster component instance at {root_path}/{name}.py.") + + component_instance_root_path = os.path.join(root_path, name) + generate_project( + path=component_instance_root_path, + name_placeholder="COMPONENT_INSTANCE_NAME_PLACEHOLDER", + templates_path=os.path.join( + os.path.dirname(__file__), "templates", "COMPONENT_INSTANCE_NAME_PLACEHOLDER" + ), + project_name=name, + component_type=component_type.registered_name(), + ) + with pushd(component_instance_root_path): + component_type.generate_files() diff --git a/examples/experimental/dagster-components/dagster_components/impls/__init__.py b/examples/experimental/dagster-components/dagster_components/impls/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/impls/pipes_subprocess_script_collection.py b/examples/experimental/dagster-components/dagster_components/impls/pipes_subprocess_script_collection.py new file mode 100644 index 0000000000000..e43310e534a4c --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/impls/pipes_subprocess_script_collection.py @@ -0,0 +1,98 @@ +import shutil +from pathlib import Path +from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence + +from dagster._core.definitions.asset_key import AssetKey +from dagster._core.definitions.asset_spec import AssetSpec +from dagster._core.definitions.assets import AssetsDefinition +from dagster._core.definitions.decorators.asset_decorator import multi_asset +from dagster._core.execution.context.asset_execution_context import AssetExecutionContext +from dagster._core.pipes.subprocess import PipesSubprocessClient +from dagster._utils.warnings import suppress_dagster_warnings +from pydantic import BaseModel, TypeAdapter + +from dagster_components.core.component import Component, ComponentDeclNode, ComponentLoadContext +from dagster_components.core.component_decl_builder import YamlComponentDecl + +if TYPE_CHECKING: + from dagster._core.definitions.definitions_class import Definitions + + +class AssetSpecModel(BaseModel): + key: str + deps: Sequence[str] = [] + description: Optional[str] = None + metadata: Mapping[str, Any] = {} + group_name: Optional[str] = None + skippable: bool = False + code_version: Optional[str] = None + owners: Sequence[str] = [] + tags: Mapping[str, str] = {} + + @suppress_dagster_warnings + def to_asset_spec(self) -> AssetSpec: + return AssetSpec( + **{ + **self.__dict__, + "key": AssetKey.from_user_string(self.key), + }, + ) + + +class PipesSubprocessScriptParams(BaseModel): + path: str + assets: Sequence[AssetSpecModel] + + +class PipesSubprocessScriptCollectionParams(BaseModel): + scripts: Sequence[PipesSubprocessScriptParams] + + +class PipesSubprocessScriptCollection(Component): + params_schema = PipesSubprocessScriptCollectionParams + + def __init__(self, dirpath: Path, path_specs: Mapping[Path, Sequence[AssetSpec]]): + self.dirpath = dirpath + # mapping from the script name (e.g. /path/to/script_abc.py -> script_abc) + # to the specs it produces + self.path_specs = path_specs + + @staticmethod + def introspect_from_path(path: Path) -> "PipesSubprocessScriptCollection": + path_specs = {path: [AssetSpec(path.stem)] for path in list(path.rglob("*.py"))} + return PipesSubprocessScriptCollection(dirpath=path, path_specs=path_specs) + + @classmethod + def from_decl_node( + cls, load_context: ComponentLoadContext, component_decl: ComponentDeclNode + ) -> "PipesSubprocessScriptCollection": + assert isinstance(component_decl, YamlComponentDecl) + loaded_params = TypeAdapter(cls.params_schema).validate_python( + component_decl.defs_file_model.component_params + ) + + path_specs = {} + for script in loaded_params.scripts: + script_path = component_decl.path / script.path + if not script_path.exists(): + raise FileNotFoundError(f"Script {script_path} does not exist") + path_specs[script_path] = [spec.to_asset_spec() for spec in script.assets] + + return cls(dirpath=component_decl.path, path_specs=path_specs) + + def build_defs(self, load_context: "ComponentLoadContext") -> "Definitions": + from dagster._core.definitions.definitions_class import Definitions + + return Definitions( + assets=[self._create_asset_def(path, specs) for path, specs in self.path_specs.items()], + resources={"pipes_client": PipesSubprocessClient()}, + ) + + def _create_asset_def(self, path: Path, specs: Sequence[AssetSpec]) -> AssetsDefinition: + # TODO: allow name paraeterization + @multi_asset(specs=specs, name=f"script_{path.stem}") + def _asset(context: AssetExecutionContext, pipes_client: PipesSubprocessClient): + cmd = [shutil.which("python"), path] + return pipes_client.run(command=cmd, context=context).get_results() + + return _asset diff --git a/examples/experimental/dagster-components/dagster_components/impls/sling_replication.py b/examples/experimental/dagster-components/dagster_components/impls/sling_replication.py new file mode 100644 index 0000000000000..668f709041e53 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/impls/sling_replication.py @@ -0,0 +1,48 @@ +import os +from pathlib import Path + +import yaml +from dagster._core.definitions.definitions_class import Definitions +from dagster_embedded_elt.sling import SlingResource, sling_assets +from dagster_embedded_elt.sling.resources import AssetExecutionContext +from pydantic import TypeAdapter +from typing_extensions import Self + +from dagster_components import Component, ComponentLoadContext +from dagster_components.core.component_decl_builder import ComponentDeclNode, YamlComponentDecl + + +class SlingReplicationComponent(Component): + params_schema = SlingResource + + def __init__(self, dirpath: Path, resource: SlingResource): + self.dirpath = dirpath + self.resource = resource + + @classmethod + def registered_name(cls) -> str: + return "sling_replication" + + @classmethod + def from_decl_node(cls, context: ComponentLoadContext, decl_node: ComponentDeclNode) -> Self: + assert isinstance(decl_node, YamlComponentDecl) + loaded_params = TypeAdapter(cls.params_schema).validate_python( + decl_node.defs_file_model.component_params + ) + return cls(dirpath=decl_node.path, resource=loaded_params) + + def build_defs(self, context: ComponentLoadContext) -> Definitions: + @sling_assets(replication_config=self.dirpath / "replication.yaml") + def _fn(context: AssetExecutionContext, sling: SlingResource): + yield from sling.replicate(context=context) + + return Definitions(assets=[_fn], resources={"sling": self.resource}) + + @classmethod + def generate_files(cls) -> None: + replication_path = Path(os.getcwd()) / "replication.yaml" + with open(replication_path, "w") as f: + yaml.dump( + {"source": {}, "target": {}, "streams": {}}, + f, + ) diff --git a/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/__init__.py b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/components/.gitkeep b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/components/.gitkeep new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py new file mode 100644 index 0000000000000..928050abfadf2 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/definitions.py @@ -0,0 +1,9 @@ +from pathlib import Path + +from dagster_components.core.component_defs_builder import ( + build_defs_from_toplevel_components_folder, +) + +defs = build_defs_from_toplevel_components_folder( + path=Path(__file__).parent, +) diff --git a/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/lib/__init__.py b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER/lib/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER_tests/__init__.py b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/CODE_LOCATION_NAME_PLACEHOLDER_tests/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja new file mode 100644 index 0000000000000..0fa5131cb4abc --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/templates/CODE_LOCATION_NAME_PLACEHOLDER/pyproject.toml.jinja @@ -0,0 +1,19 @@ +[project] +name = "{{ project_name }}" +requires-python = ">=3.9,<3.13" +version = "0.1.0" +dependencies = [] + +[project.optional-dependencies] +dev = [] + +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[tool.dagster] +module_name = "{{ project_name }}.definitions" +project_name = "{{ project_name }}" + +[tool.setuptools.packages.find] +exclude=["{{ project_name }}_tests"] diff --git a/examples/experimental/dagster-components/dagster_components/templates/COMPONENT_INSTANCE_NAME_PLACEHOLDER/defs.yml.jinja b/examples/experimental/dagster-components/dagster_components/templates/COMPONENT_INSTANCE_NAME_PLACEHOLDER/defs.yml.jinja new file mode 100644 index 0000000000000..494e390a62aa1 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/templates/COMPONENT_INSTANCE_NAME_PLACEHOLDER/defs.yml.jinja @@ -0,0 +1 @@ +component_type: {{ component_type }} \ No newline at end of file diff --git a/examples/experimental/dagster-components/dagster_components/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja b/examples/experimental/dagster-components/dagster_components/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja new file mode 100644 index 0000000000000..a303fd0c12f76 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/templates/COMPONENT_TYPE/COMPONENT_TYPE_NAME_PLACEHOLDER.py.jinja @@ -0,0 +1,16 @@ +from dagster import Definitions +from dagster_components import ( + Component, + ComponentRegistry, + ComponentLoadContext, + build_defs_from_toplevel_components_folder, +) + +class {{ component_type_class_name }}(Component): + + @classmethod + def generate_files(cls) -> None: + ... + + def build_defs(self, load_context: ComponentLoadContext) -> Definitions: + ... diff --git a/examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/.github/workflows/dagster-cloud-deploy.yaml.jinja b/examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/.github/workflows/dagster-cloud-deploy.yaml.jinja new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/code_locations/.gitkeep b/examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/code_locations/.gitkeep new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/dagster_cloud.yaml.jinja b/examples/experimental/dagster-components/dagster_components/templates/DEPLOYMENT_NAME_PLACEHOLDER/dagster_cloud.yaml.jinja new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components/version.py b/examples/experimental/dagster-components/dagster_components/version.py new file mode 100644 index 0000000000000..fe3fd8a8248b6 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components/version.py @@ -0,0 +1 @@ +__version__ = "1!0+dev" diff --git a/examples/experimental/dagster-components/dagster_components_tests/__init__.py b/examples/experimental/dagster-components/dagster_components_tests/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components_tests/cli_tests/test_generate_commands.py b/examples/experimental/dagster-components/dagster_components_tests/cli_tests/test_generate_commands.py new file mode 100644 index 0000000000000..50bf39d692e97 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/cli_tests/test_generate_commands.py @@ -0,0 +1,220 @@ +import importlib +import inspect +import os +import sys +import textwrap +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator + +from click.testing import CliRunner +from dagster._utils import pushd +from dagster_components.cli.generate import ( + generate_code_location_command, + generate_component_command, + generate_component_type_command, + generate_deployment_command, +) +from dagster_components.core.component import ComponentRegistry +from dagster_components.core.deployment import CodeLocationProjectContext + + +def _ensure_cwd_on_sys_path(): + if sys.path[0] != "": + sys.path.insert(0, "") + + +def _assert_module_imports(module_name: str): + _ensure_cwd_on_sys_path() + assert importlib.import_module(module_name) + + +# This is a holder for code that is intended to be written to a file +def _example_component_type_baz(): + from dagster import AssetExecutionContext, Definitions, PipesSubprocessClient, asset + from dagster_components import Component, ComponentLoadContext + + _SAMPLE_PIPES_SCRIPT = """ + from dagster_pipes import open_dagster_pipes + + context = open_dagster_pipes() + context.report_asset_materialization({"alpha": "beta"}) + """ + + class Baz(Component): + @classmethod + def generate_files(cls): + with open("sample.py", "w") as f: + f.write(_SAMPLE_PIPES_SCRIPT) + + def build_defs(self, context: ComponentLoadContext) -> Definitions: + @asset + def foo(context: AssetExecutionContext, client: PipesSubprocessClient): + client.run(context=context, command=["python", "sample.py"]) + + return Definitions(assets=[foo], resources={"client": PipesSubprocessClient()}) + + +@contextmanager +def isolated_example_deployment_foo(runner: CliRunner) -> Iterator[None]: + with runner.isolated_filesystem(): + runner.invoke(generate_deployment_command, ["foo"]) + with pushd("foo"): + yield + + +@contextmanager +def isolated_example_code_location_bar(runner: CliRunner) -> Iterator[None]: + with isolated_example_deployment_foo(runner), clean_module_cache("bar"): + runner.invoke(generate_code_location_command, ["bar"]) + with pushd("code_locations/bar"): + yield + + +@contextmanager +def isolated_example_code_location_bar_with_component_type_baz(runner: CliRunner) -> Iterator[None]: + with isolated_example_code_location_bar(runner): + with open("bar/lib/baz.py", "w") as f: + component_type_source = textwrap.dedent( + inspect.getsource(_example_component_type_baz).split("\n", 1)[1] + ) + f.write(component_type_source) + yield + + +@contextmanager +def clean_module_cache(module_name: str): + prefix = f"{module_name}." + keys_to_del = { + key for key in sys.modules.keys() if key == module_name or key.startswith(prefix) + } + for key in keys_to_del: + del sys.modules[key] + yield + + +def test_generate_deployment_command_success() -> None: + runner = CliRunner() + with runner.isolated_filesystem(): + result = runner.invoke(generate_deployment_command, ["foo"]) + assert result.exit_code == 0 + assert Path("foo").exists() + assert Path("foo/.github").exists() + assert Path("foo/.github/workflows").exists() + assert Path("foo/.github/workflows/dagster-cloud-deploy.yaml").exists() + assert Path("foo/dagster_cloud.yaml").exists() + assert Path("foo/code_locations").exists() + + +def test_generate_deployment_command_already_exists_fails() -> None: + runner = CliRunner() + with runner.isolated_filesystem(): + os.mkdir("foo") + result = runner.invoke(generate_deployment_command, ["foo"]) + assert result.exit_code != 0 + assert "already exists" in result.output + + +def test_generate_code_location_success() -> None: + runner = CliRunner() + with isolated_example_deployment_foo(runner): + result = runner.invoke(generate_code_location_command, ["bar"]) + assert result.exit_code == 0 + assert Path("code_locations/bar").exists() + assert Path("code_locations/bar/bar").exists() + assert Path("code_locations/bar/bar/lib").exists() + assert Path("code_locations/bar/bar/components").exists() + assert Path("code_locations/bar/bar_tests").exists() + assert Path("code_locations/bar/pyproject.toml").exists() + + +def test_generate_code_location_outside_deployment_fails() -> None: + runner = CliRunner() + with runner.isolated_filesystem(): + result = runner.invoke(generate_code_location_command, ["bar"]) + assert result.exit_code != 0 + assert "must be run inside a Dagster deployment project" in result.output + + +def test_generate_code_location_already_exists_fails() -> None: + runner = CliRunner() + with isolated_example_deployment_foo(runner): + result = runner.invoke(generate_code_location_command, ["bar"]) + assert result.exit_code == 0 + result = runner.invoke(generate_code_location_command, ["bar"]) + assert result.exit_code != 0 + assert "already exists" in result.output + + +def test_generate_component_type_success() -> None: + runner = CliRunner() + with isolated_example_code_location_bar(runner): + result = runner.invoke(generate_component_type_command, ["baz"]) + assert result.exit_code == 0 + assert Path("bar/lib/baz.py").exists() + _assert_module_imports("bar.lib.baz") + context = CodeLocationProjectContext.from_path(Path.cwd(), ComponentRegistry.empty()) + assert context.has_component_type("baz") + + +def test_generate_component_type_outside_code_location_fails() -> None: + runner = CliRunner() + with isolated_example_deployment_foo(runner): + result = runner.invoke(generate_component_type_command, ["baz"]) + assert result.exit_code != 0 + assert "must be run inside a Dagster code location project" in result.output + + +def test_generate_component_type_already_exists_fails() -> None: + runner = CliRunner() + with isolated_example_code_location_bar(runner): + result = runner.invoke(generate_component_type_command, ["baz"]) + assert result.exit_code == 0 + result = runner.invoke(generate_component_type_command, ["baz"]) + assert result.exit_code != 0 + assert "already exists" in result.output + + +def test_generate_component_success() -> None: + runner = CliRunner() + _ensure_cwd_on_sys_path() + with isolated_example_code_location_bar_with_component_type_baz(runner): + result = runner.invoke(generate_component_command, ["baz", "qux"]) + assert result.exit_code == 0 + assert Path("bar/components/qux").exists() + assert Path("bar/components/qux/sample.py").exists() + + +def test_generate_component_outside_code_location_fails() -> None: + runner = CliRunner() + with isolated_example_deployment_foo(runner): + result = runner.invoke(generate_component_command, ["baz", "qux"]) + assert result.exit_code != 0 + assert "must be run inside a Dagster code location project" in result.output + + +def test_generate_component_already_exists_fails() -> None: + runner = CliRunner() + _ensure_cwd_on_sys_path() + with isolated_example_code_location_bar_with_component_type_baz(runner): + result = runner.invoke(generate_component_command, ["baz", "qux"]) + assert result.exit_code == 0 + result = runner.invoke(generate_component_command, ["baz", "qux"]) + assert result.exit_code != 0 + assert "already exists" in result.output + + +def test_generate_global_component_instance() -> None: + runner = CliRunner() + with isolated_example_code_location_bar(runner): + result = runner.invoke(generate_component_command, ["sling_replication", "file_ingest"]) + assert result.exit_code == 0 + assert Path("bar/components/file_ingest").exists() + + defs_path = Path("bar/components/file_ingest/defs.yml") + assert defs_path.exists() + assert "component_type: sling_replication" in defs_path.read_text() + + replication_path = Path("bar/components/file_ingest/replication.yaml") + assert replication_path.exists() + assert "source: " in replication_path.read_text() diff --git a/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/__init__.py b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/defs.yml b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/defs.yml new file mode 100644 index 0000000000000..3fda5a1194652 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/defs.yml @@ -0,0 +1,15 @@ +component_type: pipes_subprocess_script_collection + +component_params: + scripts: + - path: script_one.py + assets: + - key: a + - key: b + deps: [up1, up2] + - path: script_two.py + assets: + - key: c + - path: subdir/script_three.py + assets: + - key: override_key diff --git a/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_one.py b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_one.py new file mode 100644 index 0000000000000..7cd95eb3907aa --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_one.py @@ -0,0 +1,6 @@ +def do_thing() -> None: + pass + + +if __name__ == "__main__": + do_thing() diff --git a/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_two.py b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_two.py new file mode 100644 index 0000000000000..7cd95eb3907aa --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/script_two.py @@ -0,0 +1,6 @@ +def do_thing() -> None: + pass + + +if __name__ == "__main__": + do_thing() diff --git a/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/subdir/script_three.py b/examples/experimental/dagster-components/dagster_components_tests/code_locations/python_script_location/components/scripts/subdir/script_three.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/defs.yml b/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/defs.yml new file mode 100644 index 0000000000000..971a51e52ae1b --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/defs.yml @@ -0,0 +1,7 @@ +component_type: sling_replication + +component_params: + connections: + - name: DUCKDB + type: duckdb + instance: \ No newline at end of file diff --git a/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/replication.yaml b/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/replication.yaml new file mode 100644 index 0000000000000..233019c684428 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/components/ingest/replication.yaml @@ -0,0 +1,14 @@ +source: LOCAL +target: DUCKDB + +defaults: + mode: full-refresh + object: "{stream_table}" + +streams: + : + object: "main.tbl" + meta: + dagster: + asset_key: input_duckdb + deps: [input_csv] \ No newline at end of file diff --git a/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/input.csv b/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/input.csv new file mode 100644 index 0000000000000..149d39716442e --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/stub_code_locations/sling_location/input.csv @@ -0,0 +1,4 @@ +SPECIES_CODE,SPECIES_NAME,UPDATED_AT +abcdef,scrubjay,1 +defghi,bluejay,2 +jklnop,blackbird,2 \ No newline at end of file diff --git a/examples/experimental/dagster-components/dagster_components_tests/test_pipes_subprocess_script_collection.py b/examples/experimental/dagster-components/dagster_components_tests/test_pipes_subprocess_script_collection.py new file mode 100644 index 0000000000000..6e579a6102fcc --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/test_pipes_subprocess_script_collection.py @@ -0,0 +1,83 @@ +from pathlib import Path + +from dagster import AssetKey +from dagster_components.core.component_decl_builder import DefsFileModel +from dagster_components.core.component_defs_builder import ( + YamlComponentDecl, + build_components_from_component_folder, + defs_from_components, +) +from dagster_components.impls.pipes_subprocess_script_collection import ( + PipesSubprocessScriptCollection, +) + +from dagster_components_tests.utils import assert_assets, get_asset_keys, script_load_context + +LOCATION_PATH = Path(__file__).parent / "code_locations" / "python_script_location" + + +def test_python_native() -> None: + component = PipesSubprocessScriptCollection.introspect_from_path( + LOCATION_PATH / "components" / "scripts" + ) + assert_assets(component, 3) + + +def test_python_params() -> None: + component = PipesSubprocessScriptCollection.from_decl_node( + load_context=script_load_context(), + component_decl=YamlComponentDecl( + path=LOCATION_PATH / "components" / "scripts", + defs_file_model=DefsFileModel( + component_type="pipes_subprocess_script_collection", + component_params={ + "scripts": [ + { + "path": "script_one.py", + "assets": [{"key": "a"}, {"key": "b", "deps": ["up1", "up2"]}], + }, + {"path": "subdir/script_three.py", "assets": [{"key": "key_override"}]}, + ] + }, + ), + ), + ) + assert get_asset_keys(component) == { + AssetKey("a"), + AssetKey("b"), + AssetKey("up1"), + AssetKey("up2"), + AssetKey("key_override"), + } + + +def test_load_from_path() -> None: + components = build_components_from_component_folder( + script_load_context(), LOCATION_PATH / "components" + ) + assert len(components) == 1 + assert get_asset_keys(components[0]) == { + AssetKey("a"), + AssetKey("b"), + AssetKey("c"), + AssetKey("up1"), + AssetKey("up2"), + AssetKey("override_key"), + } + + assert_assets(components[0], 6) + + defs = defs_from_components( + context=script_load_context(), + components=components, + resources={}, + ) + + assert defs.get_asset_graph().get_all_asset_keys() == { + AssetKey("a"), + AssetKey("b"), + AssetKey("c"), + AssetKey("up1"), + AssetKey("up2"), + AssetKey("override_key"), + } diff --git a/examples/experimental/dagster-components/dagster_components_tests/test_sling_replication.py b/examples/experimental/dagster-components/dagster_components_tests/test_sling_replication.py new file mode 100644 index 0000000000000..d90033baaa187 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/test_sling_replication.py @@ -0,0 +1,91 @@ +import shutil +import tempfile +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Dict, Generator, Mapping + +import pytest +import yaml +from dagster import AssetKey +from dagster._utils.env import environ +from dagster_components.core.component_decl_builder import DefsFileModel +from dagster_components.core.component_defs_builder import ( + YamlComponentDecl, + build_components_from_component_folder, +) +from dagster_components.impls.sling_replication import SlingReplicationComponent + +from dagster_components_tests.utils import assert_assets, get_asset_keys, script_load_context + +STUB_LOCATION_PATH = Path(__file__).parent / "stub_code_locations" / "sling_location" +COMPONENT_RELPATH = "components/ingest" + + +def _update_yaml(path: Path, fn) -> None: + # applies some arbitrary fn to an existing yaml dictionary + with open(path, "r") as f: + data = yaml.safe_load(f) + with open(path, "w") as f: + yaml.dump(fn(data), f) + + +@contextmanager +@pytest.fixture(scope="module") +def sling_path() -> Generator[Path, None, None]: + """Sets up a temporary directory with a replication.yaml and defs.yml file that reference + the proper temp path. + """ + with tempfile.TemporaryDirectory() as temp_dir: + with environ({"HOME": temp_dir}): + shutil.copytree(STUB_LOCATION_PATH, temp_dir, dirs_exist_ok=True) + + # update the replication yaml to reference a CSV file in the tempdir + replication_path = Path(temp_dir) / COMPONENT_RELPATH / "replication.yaml" + + def _update_replication(data: Dict[str, Any]) -> Mapping[str, Any]: + placeholder_data = data["streams"].pop("") + data["streams"][f"file://{temp_dir}/input.csv"] = placeholder_data + return data + + _update_yaml(replication_path, _update_replication) + + # update the defs yaml to add a duckdb instance + defs_path = Path(temp_dir) / COMPONENT_RELPATH / "defs.yml" + + def _update_defs(data: Dict[str, Any]) -> Mapping[str, Any]: + data["component_params"]["connections"][0]["instance"] = f"{temp_dir}/duckdb" + return data + + _update_yaml(defs_path, _update_defs) + + yield Path(temp_dir) + + +def test_python_params(sling_path: Path) -> None: + component = SlingReplicationComponent.from_decl_node( + context=script_load_context(), + decl_node=YamlComponentDecl( + path=sling_path / COMPONENT_RELPATH, + defs_file_model=DefsFileModel( + component_type="sling_replication", + component_params={}, + ), + ), + ) + assert get_asset_keys(component) == { + AssetKey("input_csv"), + AssetKey("input_duckdb"), + } + + +def test_load_from_path(sling_path: Path) -> None: + components = build_components_from_component_folder( + script_load_context(), sling_path / "components" + ) + assert len(components) == 1 + assert get_asset_keys(components[0]) == { + AssetKey("input_csv"), + AssetKey("input_duckdb"), + } + + assert_assets(components[0], 2) diff --git a/examples/experimental/dagster-components/dagster_components_tests/utils.py b/examples/experimental/dagster-components/dagster_components_tests/utils.py new file mode 100644 index 0000000000000..e381616a1fb70 --- /dev/null +++ b/examples/experimental/dagster-components/dagster_components_tests/utils.py @@ -0,0 +1,37 @@ +from dagster import AssetKey, DagsterInstance +from dagster_components.core.component import Component, ComponentLoadContext, ComponentRegistry +from dagster_components.impls.pipes_subprocess_script_collection import ( + PipesSubprocessScriptCollection, +) +from dagster_components.impls.sling_replication import SlingReplicationComponent + + +def registry() -> ComponentRegistry: + return ComponentRegistry( + { + "sling_replication": SlingReplicationComponent, + "pipes_subprocess_script_collection": PipesSubprocessScriptCollection, + } + ) + + +def script_load_context() -> ComponentLoadContext: + return ComponentLoadContext(registry=registry(), resources={}) + + +def get_asset_keys(component: Component) -> set[AssetKey]: + return { + key + for key in component.build_defs(ComponentLoadContext.for_test()) + .get_asset_graph() + .get_all_asset_keys() + } + + +def assert_assets(component: Component, expected_assets: int) -> None: + defs = component.build_defs(ComponentLoadContext.for_test()) + assert len(defs.get_asset_graph().get_all_asset_keys()) == expected_assets + result = defs.get_implicit_global_asset_job_def().execute_in_process( + instance=DagsterInstance.ephemeral() + ) + assert result.success diff --git a/examples/experimental/dagster-components/setup.cfg b/examples/experimental/dagster-components/setup.cfg new file mode 100644 index 0000000000000..0a02bee990038 --- /dev/null +++ b/examples/experimental/dagster-components/setup.cfg @@ -0,0 +1,9 @@ +[metadata] +license_files = LICENSE + +[check-manifest] +ignore = + .coveragerc + tox.ini + pytest.ini + dagster_components_tests/** diff --git a/examples/experimental/dagster-components/setup.py b/examples/experimental/dagster-components/setup.py new file mode 100644 index 0000000000000..cdd2588a083e2 --- /dev/null +++ b/examples/experimental/dagster-components/setup.py @@ -0,0 +1,50 @@ +from pathlib import Path +from typing import Dict + +from setuptools import find_packages, setup + + +def get_version() -> str: + version: Dict[str, str] = {} + with open(Path(__file__).parent / "dagster_components/version.py", encoding="utf8") as fp: + exec(fp.read(), version) + + return version["__version__"] + + +ver = get_version() +# dont pin dev installs to avoid pip dep resolver issues +pin = "" if ver == "1!0+dev" else f"=={ver}" +setup( + name="dagster-components", + version=get_version(), + author="Dagster Labs", + author_email="hello@dagsterlabs.com", + license="Apache-2.0", + description="", # TODO - fill out description + url=( + "https://github.com/dagster-io/dagster/tree/master/examples/experimental/dagster-components/" + "dagster-components" + ), + classifiers=[ + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + ], + packages=find_packages(exclude=["dagster_components_tests*", "examples*"]), + install_requires=[ + f"dagster{pin}", + ], + zip_safe=False, + entry_points={ + "console_scripts": [ + "dg = dagster_components.cli:main", + ] + }, + extras_require={ + "sling": ["dagster-embedded-elt"], + }, +) diff --git a/examples/experimental/dagster-components/tox.ini b/examples/experimental/dagster-components/tox.ini new file mode 100644 index 0000000000000..f4c307393b1a3 --- /dev/null +++ b/examples/experimental/dagster-components/tox.ini @@ -0,0 +1,22 @@ +[tox] +skipsdist = true + +[testenv] +download = True +passenv = + CI_* + COVERALLS_REPO_TOKEN + BUILDKITE* +install_command = uv pip install {opts} {packages} +deps = + -e ../../../python_modules/dagster[test] + -e ../../../python_modules/dagster-test + -e ../../../python_modules/dagster-pipes + -e ../../../python_modules/libraries/dagster-embedded-elt + -e . +allowlist_externals = + /bin/bash + uv +commands = + !windows: /bin/bash -c '! pip list --exclude-editable | grep -e dagster' + pytest -c ../../../pyproject.toml ./dagster_components_tests --snapshot-warn-unused -vv {posargs} From 5de3aee619d358ed27282b6565dd6213d347eaee Mon Sep 17 00:00:00 2001 From: Marco Salazar Date: Thu, 5 Dec 2024 11:59:24 -0500 Subject: [PATCH 07/13] revert random changes --- .../graphiql/graphiql.min.js | 204058 +++++++-------- .../dagster-pyspark/dagster_pyspark/types.py | 4 +- 2 files changed, 89048 insertions(+), 115014 deletions(-) diff --git a/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js b/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js index 359faa88a51ca..9fe250aa19df9 100644 --- a/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js +++ b/python_modules/dagster-webserver/dagster_webserver/graphiql/graphiql.min.js @@ -1,116630 +1,90664 @@ -/******/ (function () { - // webpackBootstrap - /******/ "use strict"; - /******/ var __webpack_modules__ = { - /***/ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js": - /*!**************************************************************************************!*\ +/******/ (function() { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js": +/*!**************************************************************************************!*\ !*** ../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js ***! \**************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports["default"] = void 0; - var _memoize = _interopRequireDefault( - __webpack_require__( - /*! @emotion/memoize */ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js" - ) - ); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - var reactPropsRegex = - /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 - - var index = (0, _memoize.default)( - function (prop) { - return ( - reactPropsRegex.test(prop) || - (prop.charCodeAt(0) === 111 && - /* o */ prop.charCodeAt(1) === 110 && - /* n */ prop.charCodeAt(2) < 91) - ); - } - /* Z+1 */ - ); - var _default = (exports["default"] = index); - - /***/ - }, +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - /***/ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports["default"] = void 0; - function memoize(fn) { - var cache = {}; - return function (arg) { - if (cache[arg] === undefined) cache[arg] = fn(arg); - return cache[arg]; - }; - } - var _default = (exports["default"] = memoize); - /***/ - }, - /***/ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js ***! - \****************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.computePosition = - exports.autoPlacement = - exports.arrow = - void 0; - exports.detectOverflow = detectOverflow; - exports.offset = - exports.limitShift = - exports.inline = - exports.hide = - exports.flip = - void 0; - exports.rectToClientRect = rectToClientRect; - exports.size = exports.shift = void 0; - function getAlignment(placement) { - return placement.split("-")[1]; - } - function getLengthFromAxis(axis) { - return axis === "y" ? "height" : "width"; - } - function getSide(placement) { - return placement.split("-")[0]; - } - function getMainAxisFromPlacement(placement) { - return ["top", "bottom"].includes(getSide(placement)) ? "x" : "y"; - } - function computeCoordsFromPlacement(_ref, placement, rtl) { - let { reference, floating } = _ref; - const commonX = - reference.x + reference.width / 2 - floating.width / 2; - const commonY = - reference.y + reference.height / 2 - floating.height / 2; - const mainAxis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(mainAxis); - const commonAlign = reference[length] / 2 - floating[length] / 2; - const side = getSide(placement); - const isVertical = mainAxis === "x"; - let coords; - switch (side) { - case "top": - coords = { - x: commonX, - y: reference.y - floating.height, - }; - break; - case "bottom": - coords = { - x: commonX, - y: reference.y + reference.height, - }; - break; - case "right": - coords = { - x: reference.x + reference.width, - y: commonY, - }; - break; - case "left": - coords = { - x: reference.x - floating.width, - y: commonY, - }; - break; - default: - coords = { - x: reference.x, - y: reference.y, - }; - } - switch (getAlignment(placement)) { - case "start": - coords[mainAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); - break; - case "end": - coords[mainAxis] += commonAlign * (rtl && isVertical ? -1 : 1); - break; + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = void 0; + var _memoize = _interopRequireDefault(__webpack_require__(/*! @emotion/memoize */ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js")); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|inert|itemProp|itemScope|itemType|itemID|itemRef|on|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23 + + var index = (0, _memoize.default)(function (prop) { + return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111 + /* o */ && prop.charCodeAt(1) === 110 + /* n */ && prop.charCodeAt(2) < 91; + } + /* Z+1 */); + var _default = exports["default"] = index; + + /***/ }), + + /***/ "../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@emotion/memoize/dist/memoize.browser.esm.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = void 0; + function memoize(fn) { + var cache = {}; + return function (arg) { + if (cache[arg] === undefined) cache[arg] = fn(arg); + return cache[arg]; + }; + } + var _default = exports["default"] = memoize; + + /***/ }), + + /***/ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.computePosition = exports.autoPlacement = exports.arrow = void 0; + exports.detectOverflow = detectOverflow; + exports.offset = exports.limitShift = exports.inline = exports.hide = exports.flip = void 0; + exports.rectToClientRect = rectToClientRect; + exports.size = exports.shift = void 0; + function getAlignment(placement) { + return placement.split('-')[1]; + } + function getLengthFromAxis(axis) { + return axis === 'y' ? 'height' : 'width'; + } + function getSide(placement) { + return placement.split('-')[0]; + } + function getMainAxisFromPlacement(placement) { + return ['top', 'bottom'].includes(getSide(placement)) ? 'x' : 'y'; + } + function computeCoordsFromPlacement(_ref, placement, rtl) { + let { + reference, + floating + } = _ref; + const commonX = reference.x + reference.width / 2 - floating.width / 2; + const commonY = reference.y + reference.height / 2 - floating.height / 2; + const mainAxis = getMainAxisFromPlacement(placement); + const length = getLengthFromAxis(mainAxis); + const commonAlign = reference[length] / 2 - floating[length] / 2; + const side = getSide(placement); + const isVertical = mainAxis === 'x'; + let coords; + switch (side) { + case 'top': + coords = { + x: commonX, + y: reference.y - floating.height + }; + break; + case 'bottom': + coords = { + x: commonX, + y: reference.y + reference.height + }; + break; + case 'right': + coords = { + x: reference.x + reference.width, + y: commonY + }; + break; + case 'left': + coords = { + x: reference.x - floating.width, + y: commonY + }; + break; + default: + coords = { + x: reference.x, + y: reference.y + }; + } + switch (getAlignment(placement)) { + case 'start': + coords[mainAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); + break; + case 'end': + coords[mainAxis] += commonAlign * (rtl && isVertical ? -1 : 1); + break; + } + return coords; + } + + /** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a reference element when it is given a certain positioning strategy. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ + const computePosition = async (reference, floating, config) => { + const { + placement = 'bottom', + strategy = 'absolute', + middleware = [], + platform + } = config; + const validMiddleware = middleware.filter(Boolean); + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); + let rects = await platform.getElementRects({ + reference, + floating, + strategy + }); + let { + x, + y + } = computeCoordsFromPlacement(rects, placement, rtl); + let statefulPlacement = placement; + let middlewareData = {}; + let resetCount = 0; + for (let i = 0; i < validMiddleware.length; i++) { + const { + name, + fn + } = validMiddleware[i]; + const { + x: nextX, + y: nextY, + data, + reset + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform, + elements: { + reference, + floating + } + }); + x = nextX != null ? nextX : x; + y = nextY != null ? nextY : y; + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data + } + }; + if (reset && resetCount <= 50) { + resetCount++; + if (typeof reset === 'object') { + if (reset.placement) { + statefulPlacement = reset.placement; + } + if (reset.rects) { + rects = reset.rects === true ? await platform.getElementRects({ + reference, + floating, + strategy + }) : reset.rects; } - return coords; + ({ + x, + y + } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } - - /** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain positioning strategy. - * - * This export does not have any `platform` interface logic. You will need to - * write one for the platform you are using Floating UI with. - */ - const computePosition = async (reference, floating, config) => { - const { - placement = "bottom", - strategy = "absolute", - middleware = [], - platform, - } = config; - const validMiddleware = middleware.filter(Boolean); - const rtl = await (platform.isRTL == null - ? void 0 - : platform.isRTL(floating)); - let rects = await platform.getElementRects({ - reference, - floating, - strategy, - }); - let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); - let statefulPlacement = placement; - let middlewareData = {}; - let resetCount = 0; - for (let i = 0; i < validMiddleware.length; i++) { - const { name, fn } = validMiddleware[i]; - const { - x: nextX, - y: nextY, - data, - reset, - } = await fn({ - x, - y, - initialPlacement: placement, - placement: statefulPlacement, - strategy, - middlewareData, - rects, - platform, - elements: { - reference, - floating, - }, - }); - x = nextX != null ? nextX : x; - y = nextY != null ? nextY : y; - middlewareData = { - ...middlewareData, - [name]: { - ...middlewareData[name], - ...data, - }, - }; - if (reset && resetCount <= 50) { - resetCount++; - if (typeof reset === "object") { - if (reset.placement) { - statefulPlacement = reset.placement; - } - if (reset.rects) { - rects = - reset.rects === true - ? await platform.getElementRects({ - reference, - floating, - strategy, - }) - : reset.rects; - } - ({ x, y } = computeCoordsFromPlacement( - rects, - statefulPlacement, - rtl - )); - } - i = -1; - continue; - } - } + i = -1; + continue; + } + } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData + }; + }; + exports.computePosition = computePosition; + function evaluate(value, param) { + return typeof value === 'function' ? value(param) : value; + } + function expandPaddingObject(padding) { + return { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...padding + }; + } + function getSideObjectFromPadding(padding) { + return typeof padding !== 'number' ? expandPaddingObject(padding) : { + top: padding, + right: padding, + bottom: padding, + left: padding + }; + } + function rectToClientRect(rect) { + return { + ...rect, + top: rect.y, + left: rect.x, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }; + } + + /** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ + async function detectOverflow(state, options) { + var _await$platform$isEle; + if (options === void 0) { + options = {}; + } + const { + x, + y, + platform, + rects, + elements, + strategy + } = state; + const { + boundary = 'clippingAncestors', + rootBoundary = 'viewport', + elementContext = 'floating', + altBoundary = false, + padding = 0 + } = evaluate(options, state); + const paddingObject = getSideObjectFromPadding(padding); + const altContext = elementContext === 'floating' ? 'reference' : 'floating'; + const element = elements[altBoundary ? altContext : elementContext]; + const clippingClientRect = rectToClientRect(await platform.getClippingRect({ + element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy + })); + const rect = elementContext === 'floating' ? { + ...rects.floating, + x, + y + } : rects.reference; + const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); + const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { + x: 1, + y: 1 + } : { + x: 1, + y: 1 + }; + const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ + rect, + offsetParent, + strategy + }) : rect); + return { + top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, + bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, + left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, + right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x + }; + } + const min = Math.min; + const max = Math.max; + function within(min$1, value, max$1) { + return max(min$1, min(value, max$1)); + } + + /** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ + const arrow = options => ({ + name: 'arrow', + options, + async fn(state) { + const { + x, + y, + placement, + rects, + platform, + elements + } = state; + // Since `element` is required, we don't Partial<> the type. + const { + element, + padding = 0 + } = evaluate(options, state) || {}; + if (element == null) { + return {}; + } + const paddingObject = getSideObjectFromPadding(padding); + const coords = { + x, + y + }; + const axis = getMainAxisFromPlacement(placement); + const length = getLengthFromAxis(axis); + const arrowDimensions = await platform.getDimensions(element); + const isYAxis = axis === 'y'; + const minProp = isYAxis ? 'top' : 'left'; + const maxProp = isYAxis ? 'bottom' : 'right'; + const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; + const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; + const startDiff = coords[axis] - rects.reference[axis]; + const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); + let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; + + // DOM platform can return `window` as the `offsetParent`. + if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { + clientSize = elements.floating[clientProp] || rects.floating[length]; + } + const centerToReference = endDiff / 2 - startDiff / 2; + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; + const minPadding = min(paddingObject[minProp], largestPossiblePadding); + const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1 = minPadding; + const max = clientSize - arrowDimensions[length] - maxPadding; + const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; + const offset = within(min$1, center, max); + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. This stops `shift()` from taking action, but can + // be worked around by calling it again after the `arrow()` if desired. + const shouldAddOffset = getAlignment(placement) != null && center != offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; + const alignmentOffset = shouldAddOffset ? center < min$1 ? min$1 - center : max - center : 0; + return { + [axis]: coords[axis] - alignmentOffset, + data: { + [axis]: offset, + centerOffset: center - offset + } + }; + } + }); + exports.arrow = arrow; + const sides = ['top', 'right', 'bottom', 'left']; + const allPlacements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-start", side + "-end"), []); + const oppositeSideMap = { + left: 'right', + right: 'left', + bottom: 'top', + top: 'bottom' + }; + function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); + } + function getAlignmentSides(placement, rects, rtl) { + if (rtl === void 0) { + rtl = false; + } + const alignment = getAlignment(placement); + const mainAxis = getMainAxisFromPlacement(placement); + const length = getLengthFromAxis(mainAxis); + let mainAlignmentSide = mainAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; + if (rects.reference[length] > rects.floating[length]) { + mainAlignmentSide = getOppositePlacement(mainAlignmentSide); + } + return { + main: mainAlignmentSide, + cross: getOppositePlacement(mainAlignmentSide) + }; + } + const oppositeAlignmentMap = { + start: 'end', + end: 'start' + }; + function getOppositeAlignmentPlacement(placement) { + return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); + } + function getPlacementList(alignment, autoAlignment, allowedPlacements) { + const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); + return allowedPlacementsSortedByAlignment.filter(placement => { + if (alignment) { + return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); + } + return true; + }); + } + /** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ + const autoPlacement = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'autoPlacement', + options, + async fn(state) { + var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; + const { + rects, + middlewareData, + placement, + platform, + elements + } = state; + const { + crossAxis = false, + alignment, + allowedPlacements = allPlacements, + autoAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const placements = alignment !== undefined || allowedPlacements === allPlacements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; + const overflow = await detectOverflow(state, detectOverflowOptions); + const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; + const currentPlacement = placements[currentIndex]; + if (currentPlacement == null) { + return {}; + } + const { + main, + cross + } = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); + + // Make `computeCoords` start from the right place. + if (placement !== currentPlacement) { return { - x, - y, - placement: statefulPlacement, - strategy, - middlewareData, + reset: { + placement: placements[0] + } }; - }; - exports.computePosition = computePosition; - function evaluate(value, param) { - return typeof value === "function" ? value(param) : value; } - function expandPaddingObject(padding) { + const currentOverflows = [overflow[getSide(currentPlacement)], overflow[main], overflow[cross]]; + const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { + placement: currentPlacement, + overflows: currentOverflows + }]; + const nextPlacement = placements[currentIndex + 1]; + + // There are more placements to check. + if (nextPlacement) { return { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...padding, + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: nextPlacement + } }; } - function getSideObjectFromPadding(padding) { - return typeof padding !== "number" - ? expandPaddingObject(padding) - : { - top: padding, - right: padding, - bottom: padding, - left: padding, - }; - } - function rectToClientRect(rect) { + const placementsSortedByMostSpace = allOverflows.map(d => { + const alignment = getAlignment(d.placement); + return [d.placement, alignment && crossAxis ? + // Check along the mainAxis and main crossAxis side. + d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : + // Check only the mainAxis. + d.overflows[0], d.overflows]; + }).sort((a, b) => a[1] - b[1]); + const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, + // Aligned placements should not check their opposite crossAxis + // side. + getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); + const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; + if (resetPlacement !== placement) { return { - ...rect, - top: rect.y, - left: rect.x, - right: rect.x + rect.width, - bottom: rect.y + rect.height, + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: resetPlacement + } }; } - - /** - * Resolves with an object of overflow side offsets that determine how much the - * element is overflowing a given clipping boundary on each side. - * - positive = overflowing the boundary by that number of pixels - * - negative = how many pixels left before it will overflow - * - 0 = lies flush with the boundary - * @see https://floating-ui.com/docs/detectOverflow - */ - async function detectOverflow(state, options) { - var _await$platform$isEle; - if (options === void 0) { - options = {}; - } - const { x, y, platform, rects, elements, strategy } = state; + return {}; + } + }; + }; + exports.autoPlacement = autoPlacement; + function getExpandedPlacements(placement) { + const oppositePlacement = getOppositePlacement(placement); + return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; + } + function getSideList(side, isStart, rtl) { + const lr = ['left', 'right']; + const rl = ['right', 'left']; + const tb = ['top', 'bottom']; + const bt = ['bottom', 'top']; + switch (side) { + case 'top': + case 'bottom': + if (rtl) return isStart ? rl : lr; + return isStart ? lr : rl; + case 'left': + case 'right': + return isStart ? tb : bt; + default: + return []; + } + } + function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { + const alignment = getAlignment(placement); + let list = getSideList(getSide(placement), direction === 'start', rtl); + if (alignment) { + list = list.map(side => side + "-" + alignment); + if (flipAlignment) { + list = list.concat(list.map(getOppositeAlignmentPlacement)); + } + } + return list; + } + + /** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ + const flip = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'flip', + options, + async fn(state) { + var _middlewareData$flip; + const { + placement, + middlewareData, + rects, + initialPlacement, + platform, + elements + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = 'bestFit', + fallbackAxisSideDirection = 'none', + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const side = getSide(placement); + const isBasePlacement = getSide(initialPlacement) === initialPlacement; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); + if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') { + fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); + } + const placements = [initialPlacement, ...fallbackPlacements]; + const overflow = await detectOverflow(state, detectOverflowOptions); + const overflows = []; + let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; + if (checkMainAxis) { + overflows.push(overflow[side]); + } + if (checkCrossAxis) { const { - boundary = "clippingAncestors", - rootBoundary = "viewport", - elementContext = "floating", - altBoundary = false, - padding = 0, - } = evaluate(options, state); - const paddingObject = getSideObjectFromPadding(padding); - const altContext = - elementContext === "floating" ? "reference" : "floating"; - const element = elements[altBoundary ? altContext : elementContext]; - const clippingClientRect = rectToClientRect( - await platform.getClippingRect({ - element: ( - (_await$platform$isEle = await (platform.isElement == null - ? void 0 - : platform.isElement(element))) != null - ? _await$platform$isEle - : true - ) - ? element - : element.contextElement || - (await (platform.getDocumentElement == null - ? void 0 - : platform.getDocumentElement(elements.floating))), - boundary, - rootBoundary, - strategy, - }) - ); - const rect = - elementContext === "floating" - ? { - ...rects.floating, - x, - y, - } - : rects.reference; - const offsetParent = await (platform.getOffsetParent == null - ? void 0 - : platform.getOffsetParent(elements.floating)); - const offsetScale = (await (platform.isElement == null - ? void 0 - : platform.isElement(offsetParent))) - ? (await (platform.getScale == null - ? void 0 - : platform.getScale(offsetParent))) || { - x: 1, - y: 1, + main, + cross + } = getAlignmentSides(placement, rects, rtl); + overflows.push(overflow[main], overflow[cross]); + } + overflowsData = [...overflowsData, { + placement, + overflows + }]; + + // One or more sides is overflowing. + if (!overflows.every(side => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter; + const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; + const nextPlacement = placements[nextIndex]; + if (nextPlacement) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData + }, + reset: { + placement: nextPlacement } - : { - x: 1, - y: 1, - }; - const elementClientRect = rectToClientRect( - platform.convertOffsetParentRelativeRectToViewportRelativeRect - ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect( - { - rect, - offsetParent, - strategy, + }; + } + + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case 'bestFit': + { + var _overflowsData$map$so; + const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0]; + if (placement) { + resetPlacement = placement; } - ) - : rect - ); - return { - top: - (clippingClientRect.top - - elementClientRect.top + - paddingObject.top) / - offsetScale.y, - bottom: - (elementClientRect.bottom - - clippingClientRect.bottom + - paddingObject.bottom) / - offsetScale.y, - left: - (clippingClientRect.left - - elementClientRect.left + - paddingObject.left) / - offsetScale.x, - right: - (elementClientRect.right - - clippingClientRect.right + - paddingObject.right) / - offsetScale.x, - }; - } - const min = Math.min; - const max = Math.max; - function within(min$1, value, max$1) { - return max(min$1, min(value, max$1)); + break; + } + case 'initialPlacement': + resetPlacement = initialPlacement; + break; + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement + } + }; + } } - - /** - * Provides data to position an inner element of the floating element so that it - * appears centered to the reference element. - * @see https://floating-ui.com/docs/arrow - */ - const arrow = (options) => ({ - name: "arrow", - options, - async fn(state) { - const { x, y, placement, rects, platform, elements } = state; - // Since `element` is required, we don't Partial<> the type. - const { element, padding = 0 } = evaluate(options, state) || {}; - if (element == null) { + return {}; + } + }; + }; + exports.flip = flip; + function getSideOffsets(overflow, rect) { + return { + top: overflow.top - rect.height, + right: overflow.right - rect.width, + bottom: overflow.bottom - rect.height, + left: overflow.left - rect.width + }; + } + function isAnySideFullyClipped(overflow) { + return sides.some(side => overflow[side] >= 0); + } + /** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ + const hide = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'hide', + options, + async fn(state) { + const { + rects + } = state; + const { + strategy = 'referenceHidden', + ...detectOverflowOptions + } = evaluate(options, state); + switch (strategy) { + case 'referenceHidden': + { + const overflow = await detectOverflow(state, { + ...detectOverflowOptions, + elementContext: 'reference' + }); + const offsets = getSideOffsets(overflow, rects.reference); + return { + data: { + referenceHiddenOffsets: offsets, + referenceHidden: isAnySideFullyClipped(offsets) + } + }; + } + case 'escaped': + { + const overflow = await detectOverflow(state, { + ...detectOverflowOptions, + altBoundary: true + }); + const offsets = getSideOffsets(overflow, rects.floating); + return { + data: { + escapedOffsets: offsets, + escaped: isAnySideFullyClipped(offsets) + } + }; + } + default: + { return {}; } - const paddingObject = getSideObjectFromPadding(padding); - const coords = { - x, - y, - }; - const axis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(axis); - const arrowDimensions = await platform.getDimensions(element); - const isYAxis = axis === "y"; - const minProp = isYAxis ? "top" : "left"; - const maxProp = isYAxis ? "bottom" : "right"; - const clientProp = isYAxis ? "clientHeight" : "clientWidth"; - const endDiff = - rects.reference[length] + - rects.reference[axis] - - coords[axis] - - rects.floating[length]; - const startDiff = coords[axis] - rects.reference[axis]; - const arrowOffsetParent = await (platform.getOffsetParent == null - ? void 0 - : platform.getOffsetParent(element)); - let clientSize = arrowOffsetParent - ? arrowOffsetParent[clientProp] - : 0; - - // DOM platform can return `window` as the `offsetParent`. - if ( - !clientSize || - !(await (platform.isElement == null - ? void 0 - : platform.isElement(arrowOffsetParent))) - ) { - clientSize = - elements.floating[clientProp] || rects.floating[length]; - } - const centerToReference = endDiff / 2 - startDiff / 2; - - // If the padding is large enough that it causes the arrow to no longer be - // centered, modify the padding so that it is centered. - const largestPossiblePadding = - clientSize / 2 - arrowDimensions[length] / 2 - 1; - const minPadding = min( - paddingObject[minProp], - largestPossiblePadding - ); - const maxPadding = min( - paddingObject[maxProp], - largestPossiblePadding - ); - - // Make sure the arrow doesn't overflow the floating element if the center - // point is outside the floating element's bounds. - const min$1 = minPadding; - const max = clientSize - arrowDimensions[length] - maxPadding; - const center = - clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; - const offset = within(min$1, center, max); - - // If the reference is small enough that the arrow's padding causes it to - // to point to nothing for an aligned placement, adjust the offset of the - // floating element itself. This stops `shift()` from taking action, but can - // be worked around by calling it again after the `arrow()` if desired. - const shouldAddOffset = - getAlignment(placement) != null && - center != offset && - rects.reference[length] / 2 - - (center < min$1 ? minPadding : maxPadding) - - arrowDimensions[length] / 2 < - 0; - const alignmentOffset = shouldAddOffset - ? center < min$1 - ? min$1 - center - : max - center - : 0; + } + } + }; + }; + exports.hide = hide; + function getBoundingRect(rects) { + const minX = min(...rects.map(rect => rect.left)); + const minY = min(...rects.map(rect => rect.top)); + const maxX = max(...rects.map(rect => rect.right)); + const maxY = max(...rects.map(rect => rect.bottom)); + return { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY + }; + } + function getRectsByLine(rects) { + const sortedRects = rects.slice().sort((a, b) => a.y - b.y); + const groups = []; + let prevRect = null; + for (let i = 0; i < sortedRects.length; i++) { + const rect = sortedRects[i]; + if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { + groups.push([rect]); + } else { + groups[groups.length - 1].push(rect); + } + prevRect = rect; + } + return groups.map(rect => rectToClientRect(getBoundingRect(rect))); + } + /** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ + const inline = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'inline', + options, + async fn(state) { + const { + placement, + elements, + rects, + platform, + strategy + } = state; + // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a + // ClientRect's bounds, despite the event listener being triggered. A + // padding of 2 seems to handle this issue. + const { + padding = 2, + x, + y + } = evaluate(options, state); + const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); + const clientRects = getRectsByLine(nativeClientRects); + const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); + const paddingObject = getSideObjectFromPadding(padding); + function getBoundingClientRect() { + // There are two rects and they are disjoined. + if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { + // Find the first rect in which the point is fully inside. + return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; + } + + // There are 2 or more connected rects. + if (clientRects.length >= 2) { + if (getMainAxisFromPlacement(placement) === 'x') { + const firstRect = clientRects[0]; + const lastRect = clientRects[clientRects.length - 1]; + const isTop = getSide(placement) === 'top'; + const top = firstRect.top; + const bottom = lastRect.bottom; + const left = isTop ? firstRect.left : lastRect.left; + const right = isTop ? firstRect.right : lastRect.right; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + const isLeftSide = getSide(placement) === 'left'; + const maxRight = max(...clientRects.map(rect => rect.right)); + const minLeft = min(...clientRects.map(rect => rect.left)); + const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); + const top = measureRects[0].top; + const bottom = measureRects[measureRects.length - 1].bottom; + const left = minLeft; + const right = maxRight; + const width = right - left; + const height = bottom - top; return { - [axis]: coords[axis] - alignmentOffset, - data: { - [axis]: offset, - centerOffset: center - offset, - }, + top, + bottom, + left, + right, + width, + height, + x: left, + y: top }; + } + return fallback; + } + const resetRects = await platform.getElementRects({ + reference: { + getBoundingClientRect }, + floating: elements.floating, + strategy }); - exports.arrow = arrow; - const sides = ["top", "right", "bottom", "left"]; - const allPlacements = /*#__PURE__*/ sides.reduce( - (acc, side) => acc.concat(side, side + "-start", side + "-end"), - [] - ); - const oppositeSideMap = { - left: "right", - right: "left", - bottom: "top", - top: "bottom", - }; - function getOppositePlacement(placement) { - return placement.replace( - /left|right|bottom|top/g, - (side) => oppositeSideMap[side] - ); - } - function getAlignmentSides(placement, rects, rtl) { - if (rtl === void 0) { - rtl = false; - } - const alignment = getAlignment(placement); - const mainAxis = getMainAxisFromPlacement(placement); - const length = getLengthFromAxis(mainAxis); - let mainAlignmentSide = - mainAxis === "x" - ? alignment === (rtl ? "end" : "start") - ? "right" - : "left" - : alignment === "start" - ? "bottom" - : "top"; - if (rects.reference[length] > rects.floating[length]) { - mainAlignmentSide = getOppositePlacement(mainAlignmentSide); - } + if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { return { - main: mainAlignmentSide, - cross: getOppositePlacement(mainAlignmentSide), + reset: { + rects: resetRects + } }; } - const oppositeAlignmentMap = { - start: "end", - end: "start", + return {}; + } + }; + }; + exports.inline = inline; + async function convertValueToCoords(state, options) { + const { + placement, + platform, + elements + } = state; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isVertical = getMainAxisFromPlacement(placement) === 'x'; + const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1; + const crossAxisMulti = rtl && isVertical ? -1 : 1; + const rawValue = evaluate(options, state); + + // eslint-disable-next-line prefer-const + let { + mainAxis, + crossAxis, + alignmentAxis + } = typeof rawValue === 'number' ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null + } : { + mainAxis: 0, + crossAxis: 0, + alignmentAxis: null, + ...rawValue + }; + if (alignment && typeof alignmentAxis === 'number') { + crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; + } + return isVertical ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti + } : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti + }; + } + + /** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ + const offset = function (options) { + if (options === void 0) { + options = 0; + } + return { + name: 'offset', + options, + async fn(state) { + const { + x, + y + } = state; + const diffCoords = await convertValueToCoords(state, options); + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: diffCoords }; - function getOppositeAlignmentPlacement(placement) { - return placement.replace( - /start|end/g, - (alignment) => oppositeAlignmentMap[alignment] - ); - } - function getPlacementList(alignment, autoAlignment, allowedPlacements) { - const allowedPlacementsSortedByAlignment = alignment - ? [ - ...allowedPlacements.filter( - (placement) => getAlignment(placement) === alignment - ), - ...allowedPlacements.filter( - (placement) => getAlignment(placement) !== alignment - ), - ] - : allowedPlacements.filter( - (placement) => getSide(placement) === placement - ); - return allowedPlacementsSortedByAlignment.filter((placement) => { - if (alignment) { - return ( - getAlignment(placement) === alignment || - (autoAlignment - ? getOppositeAlignmentPlacement(placement) !== placement - : false) - ); - } - return true; - }); - } - /** - * Optimizes the visibility of the floating element by choosing the placement - * that has the most space available automatically, without needing to specify a - * preferred placement. Alternative to `flip`. - * @see https://floating-ui.com/docs/autoPlacement - */ - const autoPlacement = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: "autoPlacement", - options, - async fn(state) { - var _middlewareData$autoP, - _middlewareData$autoP2, - _placementsThatFitOnE; - const { rects, middlewareData, placement, platform, elements } = - state; - const { - crossAxis = false, - alignment, - allowedPlacements = allPlacements, - autoAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const placements = - alignment !== undefined || allowedPlacements === allPlacements - ? getPlacementList( - alignment || null, - autoAlignment, - allowedPlacements - ) - : allowedPlacements; - const overflow = await detectOverflow( - state, - detectOverflowOptions - ); - const currentIndex = - ((_middlewareData$autoP = middlewareData.autoPlacement) == null - ? void 0 - : _middlewareData$autoP.index) || 0; - const currentPlacement = placements[currentIndex]; - if (currentPlacement == null) { - return {}; - } - const { main, cross } = getAlignmentSides( - currentPlacement, - rects, - await (platform.isRTL == null - ? void 0 - : platform.isRTL(elements.floating)) - ); - - // Make `computeCoords` start from the right place. - if (placement !== currentPlacement) { - return { - reset: { - placement: placements[0], - }, - }; - } - const currentOverflows = [ - overflow[getSide(currentPlacement)], - overflow[main], - overflow[cross], - ]; - const allOverflows = [ - ...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == - null - ? void 0 - : _middlewareData$autoP2.overflows) || []), - { - placement: currentPlacement, - overflows: currentOverflows, - }, - ]; - const nextPlacement = placements[currentIndex + 1]; - - // There are more placements to check. - if (nextPlacement) { - return { - data: { - index: currentIndex + 1, - overflows: allOverflows, - }, - reset: { - placement: nextPlacement, - }, - }; - } - const placementsSortedByMostSpace = allOverflows - .map((d) => { - const alignment = getAlignment(d.placement); - return [ - d.placement, - alignment && crossAxis - ? // Check along the mainAxis and main crossAxis side. - d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) - : // Check only the mainAxis. - d.overflows[0], - d.overflows, - ]; - }) - .sort((a, b) => a[1] - b[1]); - const placementsThatFitOnEachSide = - placementsSortedByMostSpace.filter((d) => - d[2] - .slice( - 0, - // Aligned placements should not check their opposite crossAxis - // side. - getAlignment(d[0]) ? 2 : 3 - ) - .every((v) => v <= 0) - ); - const resetPlacement = - ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == - null - ? void 0 - : _placementsThatFitOnE[0]) || - placementsSortedByMostSpace[0][0]; - if (resetPlacement !== placement) { - return { - data: { - index: currentIndex + 1, - overflows: allOverflows, - }, - reset: { - placement: resetPlacement, - }, - }; - } - return {}; - }, - }; - }; - exports.autoPlacement = autoPlacement; - function getExpandedPlacements(placement) { - const oppositePlacement = getOppositePlacement(placement); - return [ - getOppositeAlignmentPlacement(placement), - oppositePlacement, - getOppositeAlignmentPlacement(oppositePlacement), - ]; - } - function getSideList(side, isStart, rtl) { - const lr = ["left", "right"]; - const rl = ["right", "left"]; - const tb = ["top", "bottom"]; - const bt = ["bottom", "top"]; - switch (side) { - case "top": - case "bottom": - if (rtl) return isStart ? rl : lr; - return isStart ? lr : rl; - case "left": - case "right": - return isStart ? tb : bt; - default: - return []; - } - } - function getOppositeAxisPlacements( - placement, - flipAlignment, - direction, - rtl - ) { - const alignment = getAlignment(placement); - let list = getSideList( - getSide(placement), - direction === "start", - rtl - ); - if (alignment) { - list = list.map((side) => side + "-" + alignment); - if (flipAlignment) { - list = list.concat(list.map(getOppositeAlignmentPlacement)); + } + }; + }; + exports.offset = offset; + function getCrossAxis(axis) { + return axis === 'x' ? 'y' : 'x'; + } + + /** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ + const shift = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'shift', + options, + async fn(state) { + const { + x, + y, + placement + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: _ref => { + let { + x, + y + } = _ref; + return { + x, + y + }; } - } - return list; - } - - /** - * Optimizes the visibility of the floating element by flipping the `placement` - * in order to keep it in view when the preferred placement(s) will overflow the - * clipping boundary. Alternative to `autoPlacement`. - * @see https://floating-ui.com/docs/flip - */ - const flip = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: "flip", - options, - async fn(state) { - var _middlewareData$flip; - const { - placement, - middlewareData, - rects, - initialPlacement, - platform, - elements, - } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true, - fallbackPlacements: specifiedFallbackPlacements, - fallbackStrategy = "bestFit", - fallbackAxisSideDirection = "none", - flipAlignment = true, - ...detectOverflowOptions - } = evaluate(options, state); - const side = getSide(placement); - const isBasePlacement = - getSide(initialPlacement) === initialPlacement; - const rtl = await (platform.isRTL == null - ? void 0 - : platform.isRTL(elements.floating)); - const fallbackPlacements = - specifiedFallbackPlacements || - (isBasePlacement || !flipAlignment - ? [getOppositePlacement(initialPlacement)] - : getExpandedPlacements(initialPlacement)); - if ( - !specifiedFallbackPlacements && - fallbackAxisSideDirection !== "none" - ) { - fallbackPlacements.push( - ...getOppositeAxisPlacements( - initialPlacement, - flipAlignment, - fallbackAxisSideDirection, - rtl - ) - ); - } - const placements = [initialPlacement, ...fallbackPlacements]; - const overflow = await detectOverflow( - state, - detectOverflowOptions - ); - const overflows = []; - let overflowsData = - ((_middlewareData$flip = middlewareData.flip) == null - ? void 0 - : _middlewareData$flip.overflows) || []; - if (checkMainAxis) { - overflows.push(overflow[side]); - } - if (checkCrossAxis) { - const { main, cross } = getAlignmentSides( - placement, - rects, - rtl - ); - overflows.push(overflow[main], overflow[cross]); - } - overflowsData = [ - ...overflowsData, - { - placement, - overflows, - }, - ]; - - // One or more sides is overflowing. - if (!overflows.every((side) => side <= 0)) { - var _middlewareData$flip2, _overflowsData$filter; - const nextIndex = - (((_middlewareData$flip2 = middlewareData.flip) == null - ? void 0 - : _middlewareData$flip2.index) || 0) + 1; - const nextPlacement = placements[nextIndex]; - if (nextPlacement) { - // Try next placement and re-run the lifecycle. - return { - data: { - index: nextIndex, - overflows: overflowsData, - }, - reset: { - placement: nextPlacement, - }, - }; - } - - // First, find the candidates that fit on the mainAxis side of overflow, - // then find the placement that fits the best on the main crossAxis side. - let resetPlacement = - (_overflowsData$filter = overflowsData - .filter((d) => d.overflows[0] <= 0) - .sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null - ? void 0 - : _overflowsData$filter.placement; - - // Otherwise fallback. - if (!resetPlacement) { - switch (fallbackStrategy) { - case "bestFit": { - var _overflowsData$map$so; - const placement = - (_overflowsData$map$so = overflowsData - .map((d) => [ - d.placement, - d.overflows - .filter((overflow) => overflow > 0) - .reduce((acc, overflow) => acc + overflow, 0), - ]) - .sort((a, b) => a[1] - b[1])[0]) == null - ? void 0 - : _overflowsData$map$so[0]; - if (placement) { - resetPlacement = placement; - } - break; - } - case "initialPlacement": - resetPlacement = initialPlacement; - break; - } - } - if (placement !== resetPlacement) { - return { - reset: { - placement: resetPlacement, - }, - }; - } - } - return {}; - }, - }; - }; - exports.flip = flip; - function getSideOffsets(overflow, rect) { - return { - top: overflow.top - rect.height, - right: overflow.right - rect.width, - bottom: overflow.bottom - rect.height, - left: overflow.left - rect.width, - }; - } - function isAnySideFullyClipped(overflow) { - return sides.some((side) => overflow[side] >= 0); - } - /** - * Provides data to hide the floating element in applicable situations, such as - * when it is not in the same clipping context as the reference element. - * @see https://floating-ui.com/docs/hide - */ - const hide = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: "hide", - options, - async fn(state) { - const { rects } = state; - const { strategy = "referenceHidden", ...detectOverflowOptions } = - evaluate(options, state); - switch (strategy) { - case "referenceHidden": { - const overflow = await detectOverflow(state, { - ...detectOverflowOptions, - elementContext: "reference", - }); - const offsets = getSideOffsets(overflow, rects.reference); - return { - data: { - referenceHiddenOffsets: offsets, - referenceHidden: isAnySideFullyClipped(offsets), - }, - }; - } - case "escaped": { - const overflow = await detectOverflow(state, { - ...detectOverflowOptions, - altBoundary: true, - }); - const offsets = getSideOffsets(overflow, rects.floating); - return { - data: { - escapedOffsets: offsets, - escaped: isAnySideFullyClipped(offsets), - }, - }; - } - default: { - return {}; - } - } - }, - }; + }, + ...detectOverflowOptions + } = evaluate(options, state); + const coords = { + x, + y }; - exports.hide = hide; - function getBoundingRect(rects) { - const minX = min(...rects.map((rect) => rect.left)); - const minY = min(...rects.map((rect) => rect.top)); - const maxX = max(...rects.map((rect) => rect.right)); - const maxY = max(...rects.map((rect) => rect.bottom)); - return { - x: minX, - y: minY, - width: maxX - minX, - height: maxY - minY, - }; - } - function getRectsByLine(rects) { - const sortedRects = rects.slice().sort((a, b) => a.y - b.y); - const groups = []; - let prevRect = null; - for (let i = 0; i < sortedRects.length; i++) { - const rect = sortedRects[i]; - if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { - groups.push([rect]); - } else { - groups[groups.length - 1].push(rect); - } - prevRect = rect; - } - return groups.map((rect) => rectToClientRect(getBoundingRect(rect))); - } - /** - * Provides improved positioning for inline reference elements that can span - * over multiple lines, such as hyperlinks or range selections. - * @see https://floating-ui.com/docs/inline - */ - const inline = function (options) { - if (options === void 0) { - options = {}; + const overflow = await detectOverflow(state, detectOverflowOptions); + const mainAxis = getMainAxisFromPlacement(getSide(placement)); + const crossAxis = getCrossAxis(mainAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + if (checkMainAxis) { + const minSide = mainAxis === 'y' ? 'top' : 'left'; + const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; + const min = mainAxisCoord + overflow[minSide]; + const max = mainAxisCoord - overflow[maxSide]; + mainAxisCoord = within(min, mainAxisCoord, max); + } + if (checkCrossAxis) { + const minSide = crossAxis === 'y' ? 'top' : 'left'; + const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; + const min = crossAxisCoord + overflow[minSide]; + const max = crossAxisCoord - overflow[maxSide]; + crossAxisCoord = within(min, crossAxisCoord, max); + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }); + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y } - return { - name: "inline", - options, - async fn(state) { - const { placement, elements, rects, platform, strategy } = state; - // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a - // ClientRect's bounds, despite the event listener being triggered. A - // padding of 2 seems to handle this issue. - const { padding = 2, x, y } = evaluate(options, state); - const nativeClientRects = Array.from( - (await (platform.getClientRects == null - ? void 0 - : platform.getClientRects(elements.reference))) || [] - ); - const clientRects = getRectsByLine(nativeClientRects); - const fallback = rectToClientRect( - getBoundingRect(nativeClientRects) - ); - const paddingObject = getSideObjectFromPadding(padding); - function getBoundingClientRect() { - // There are two rects and they are disjoined. - if ( - clientRects.length === 2 && - clientRects[0].left > clientRects[1].right && - x != null && - y != null - ) { - // Find the first rect in which the point is fully inside. - return ( - clientRects.find( - (rect) => - x > rect.left - paddingObject.left && - x < rect.right + paddingObject.right && - y > rect.top - paddingObject.top && - y < rect.bottom + paddingObject.bottom - ) || fallback - ); - } - - // There are 2 or more connected rects. - if (clientRects.length >= 2) { - if (getMainAxisFromPlacement(placement) === "x") { - const firstRect = clientRects[0]; - const lastRect = clientRects[clientRects.length - 1]; - const isTop = getSide(placement) === "top"; - const top = firstRect.top; - const bottom = lastRect.bottom; - const left = isTop ? firstRect.left : lastRect.left; - const right = isTop ? firstRect.right : lastRect.right; - const width = right - left; - const height = bottom - top; - return { - top, - bottom, - left, - right, - width, - height, - x: left, - y: top, - }; - } - const isLeftSide = getSide(placement) === "left"; - const maxRight = max( - ...clientRects.map((rect) => rect.right) - ); - const minLeft = min(...clientRects.map((rect) => rect.left)); - const measureRects = clientRects.filter((rect) => - isLeftSide ? rect.left === minLeft : rect.right === maxRight - ); - const top = measureRects[0].top; - const bottom = measureRects[measureRects.length - 1].bottom; - const left = minLeft; - const right = maxRight; - const width = right - left; - const height = bottom - top; - return { - top, - bottom, - left, - right, - width, - height, - x: left, - y: top, - }; - } - return fallback; - } - const resetRects = await platform.getElementRects({ - reference: { - getBoundingClientRect, - }, - floating: elements.floating, - strategy, - }); - if ( - rects.reference.x !== resetRects.reference.x || - rects.reference.y !== resetRects.reference.y || - rects.reference.width !== resetRects.reference.width || - rects.reference.height !== resetRects.reference.height - ) { - return { - reset: { - rects: resetRects, - }, - }; - } - return {}; - }, - }; }; - exports.inline = inline; - async function convertValueToCoords(state, options) { - const { placement, platform, elements } = state; - const rtl = await (platform.isRTL == null - ? void 0 - : platform.isRTL(elements.floating)); - const side = getSide(placement); - const alignment = getAlignment(placement); - const isVertical = getMainAxisFromPlacement(placement) === "x"; - const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1; - const crossAxisMulti = rtl && isVertical ? -1 : 1; - const rawValue = evaluate(options, state); - - // eslint-disable-next-line prefer-const - let { mainAxis, crossAxis, alignmentAxis } = - typeof rawValue === "number" - ? { - mainAxis: rawValue, - crossAxis: 0, - alignmentAxis: null, - } - : { - mainAxis: 0, - crossAxis: 0, - alignmentAxis: null, - ...rawValue, - }; - if (alignment && typeof alignmentAxis === "number") { - crossAxis = - alignment === "end" ? alignmentAxis * -1 : alignmentAxis; - } - return isVertical - ? { - x: crossAxis * crossAxisMulti, - y: mainAxis * mainAxisMulti, - } - : { - x: mainAxis * mainAxisMulti, - y: crossAxis * crossAxisMulti, - }; - } - - /** - * Modifies the placement by translating the floating element along the - * specified axes. - * A number (shorthand for `mainAxis` or distance), or an axes configuration - * object may be passed. - * @see https://floating-ui.com/docs/offset - */ - const offset = function (options) { - if (options === void 0) { - options = 0; - } - return { - name: "offset", - options, - async fn(state) { - const { x, y } = state; - const diffCoords = await convertValueToCoords(state, options); - return { - x: x + diffCoords.x, - y: y + diffCoords.y, - data: diffCoords, - }; - }, - }; + } + }; + }; + /** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ + exports.shift = shift; + const limitShift = function (options) { + if (options === void 0) { + options = {}; + } + return { + options, + fn(state) { + const { + x, + y, + placement, + rects, + middlewareData + } = state; + const { + offset = 0, + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true + } = evaluate(options, state); + const coords = { + x, + y }; - exports.offset = offset; - function getCrossAxis(axis) { - return axis === "x" ? "y" : "x"; - } - - /** - * Optimizes the visibility of the floating element by shifting it in order to - * keep it in view when it will overflow the clipping boundary. - * @see https://floating-ui.com/docs/shift - */ - const shift = function (options) { - if (options === void 0) { - options = {}; - } - return { - name: "shift", - options, - async fn(state) { - const { x, y, placement } = state; - const { - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = false, - limiter = { - fn: (_ref) => { - let { x, y } = _ref; - return { - x, - y, - }; - }, - }, - ...detectOverflowOptions - } = evaluate(options, state); - const coords = { - x, - y, - }; - const overflow = await detectOverflow( - state, - detectOverflowOptions - ); - const mainAxis = getMainAxisFromPlacement(getSide(placement)); - const crossAxis = getCrossAxis(mainAxis); - let mainAxisCoord = coords[mainAxis]; - let crossAxisCoord = coords[crossAxis]; - if (checkMainAxis) { - const minSide = mainAxis === "y" ? "top" : "left"; - const maxSide = mainAxis === "y" ? "bottom" : "right"; - const min = mainAxisCoord + overflow[minSide]; - const max = mainAxisCoord - overflow[maxSide]; - mainAxisCoord = within(min, mainAxisCoord, max); - } - if (checkCrossAxis) { - const minSide = crossAxis === "y" ? "top" : "left"; - const maxSide = crossAxis === "y" ? "bottom" : "right"; - const min = crossAxisCoord + overflow[minSide]; - const max = crossAxisCoord - overflow[maxSide]; - crossAxisCoord = within(min, crossAxisCoord, max); - } - const limitedCoords = limiter.fn({ - ...state, - [mainAxis]: mainAxisCoord, - [crossAxis]: crossAxisCoord, - }); - return { - ...limitedCoords, - data: { - x: limitedCoords.x - x, - y: limitedCoords.y - y, - }, - }; - }, - }; + const mainAxis = getMainAxisFromPlacement(placement); + const crossAxis = getCrossAxis(mainAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + const rawOffset = evaluate(offset, state); + const computedOffset = typeof rawOffset === 'number' ? { + mainAxis: rawOffset, + crossAxis: 0 + } : { + mainAxis: 0, + crossAxis: 0, + ...rawOffset }; - /** - * Built-in `limiter` that will stop `shift()` at a certain point. - */ - exports.shift = shift; - const limitShift = function (options) { - if (options === void 0) { - options = {}; - } - return { - options, - fn(state) { - const { x, y, placement, rects, middlewareData } = state; - const { - offset = 0, - mainAxis: checkMainAxis = true, - crossAxis: checkCrossAxis = true, - } = evaluate(options, state); - const coords = { - x, - y, - }; - const mainAxis = getMainAxisFromPlacement(placement); - const crossAxis = getCrossAxis(mainAxis); - let mainAxisCoord = coords[mainAxis]; - let crossAxisCoord = coords[crossAxis]; - const rawOffset = evaluate(offset, state); - const computedOffset = - typeof rawOffset === "number" - ? { - mainAxis: rawOffset, - crossAxis: 0, - } - : { - mainAxis: 0, - crossAxis: 0, - ...rawOffset, - }; - if (checkMainAxis) { - const len = mainAxis === "y" ? "height" : "width"; - const limitMin = - rects.reference[mainAxis] - - rects.floating[len] + - computedOffset.mainAxis; - const limitMax = - rects.reference[mainAxis] + - rects.reference[len] - - computedOffset.mainAxis; - if (mainAxisCoord < limitMin) { - mainAxisCoord = limitMin; - } else if (mainAxisCoord > limitMax) { - mainAxisCoord = limitMax; - } - } - if (checkCrossAxis) { - var _middlewareData$offse, _middlewareData$offse2; - const len = mainAxis === "y" ? "width" : "height"; - const isOriginSide = ["top", "left"].includes( - getSide(placement) - ); - const limitMin = - rects.reference[crossAxis] - - rects.floating[len] + - (isOriginSide - ? ((_middlewareData$offse = middlewareData.offset) == null - ? void 0 - : _middlewareData$offse[crossAxis]) || 0 - : 0) + - (isOriginSide ? 0 : computedOffset.crossAxis); - const limitMax = - rects.reference[crossAxis] + - rects.reference[len] + - (isOriginSide - ? 0 - : ((_middlewareData$offse2 = middlewareData.offset) == null - ? void 0 - : _middlewareData$offse2[crossAxis]) || 0) - - (isOriginSide ? computedOffset.crossAxis : 0); - if (crossAxisCoord < limitMin) { - crossAxisCoord = limitMin; - } else if (crossAxisCoord > limitMax) { - crossAxisCoord = limitMax; - } - } - return { - [mainAxis]: mainAxisCoord, - [crossAxis]: crossAxisCoord, - }; - }, - }; + if (checkMainAxis) { + const len = mainAxis === 'y' ? 'height' : 'width'; + const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; + const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; + if (mainAxisCoord < limitMin) { + mainAxisCoord = limitMin; + } else if (mainAxisCoord > limitMax) { + mainAxisCoord = limitMax; + } + } + if (checkCrossAxis) { + var _middlewareData$offse, _middlewareData$offse2; + const len = mainAxis === 'y' ? 'width' : 'height'; + const isOriginSide = ['top', 'left'].includes(getSide(placement)); + const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); + const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); + if (crossAxisCoord < limitMin) { + crossAxisCoord = limitMin; + } else if (crossAxisCoord > limitMax) { + crossAxisCoord = limitMax; + } + } + return { + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord }; - - /** - * Provides data that allows you to change the size of the floating element — - * for instance, prevent it from overflowing the clipping boundary or match the - * width of the reference element. - * @see https://floating-ui.com/docs/size - */ - exports.limitShift = limitShift; - const size = function (options) { - if (options === void 0) { - options = {}; + } + }; + }; + + /** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ + exports.limitShift = limitShift; + const size = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'size', + options, + async fn(state) { + const { + placement, + rects, + platform, + elements + } = state; + const { + apply = () => {}, + ...detectOverflowOptions + } = evaluate(options, state); + const overflow = await detectOverflow(state, detectOverflowOptions); + const side = getSide(placement); + const alignment = getAlignment(placement); + const axis = getMainAxisFromPlacement(placement); + const isXAxis = axis === 'x'; + const { + width, + height + } = rects.floating; + let heightSide; + let widthSide; + if (side === 'top' || side === 'bottom') { + heightSide = side; + widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; + } else { + widthSide = side; + heightSide = alignment === 'end' ? 'top' : 'bottom'; + } + const overflowAvailableHeight = height - overflow[heightSide]; + const overflowAvailableWidth = width - overflow[widthSide]; + const noShift = !state.middlewareData.shift; + let availableHeight = overflowAvailableHeight; + let availableWidth = overflowAvailableWidth; + if (isXAxis) { + const maximumClippingWidth = width - overflow.left - overflow.right; + availableWidth = alignment || noShift ? min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth; + } else { + const maximumClippingHeight = height - overflow.top - overflow.bottom; + availableHeight = alignment || noShift ? min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight; + } + if (noShift && !alignment) { + const xMin = max(overflow.left, 0); + const xMax = max(overflow.right, 0); + const yMin = max(overflow.top, 0); + const yMax = max(overflow.bottom, 0); + if (isXAxis) { + availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); + } else { + availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } + } + await apply({ + ...state, + availableWidth, + availableHeight + }); + const nextDimensions = await platform.getDimensions(elements.floating); + if (width !== nextDimensions.width || height !== nextDimensions.height) { return { - name: "size", - options, - async fn(state) { - const { placement, rects, platform, elements } = state; - const { apply = () => {}, ...detectOverflowOptions } = evaluate( - options, - state - ); - const overflow = await detectOverflow( - state, - detectOverflowOptions - ); - const side = getSide(placement); - const alignment = getAlignment(placement); - const axis = getMainAxisFromPlacement(placement); - const isXAxis = axis === "x"; - const { width, height } = rects.floating; - let heightSide; - let widthSide; - if (side === "top" || side === "bottom") { - heightSide = side; - widthSide = - alignment === - ((await (platform.isRTL == null - ? void 0 - : platform.isRTL(elements.floating))) - ? "start" - : "end") - ? "left" - : "right"; - } else { - widthSide = side; - heightSide = alignment === "end" ? "top" : "bottom"; - } - const overflowAvailableHeight = height - overflow[heightSide]; - const overflowAvailableWidth = width - overflow[widthSide]; - const noShift = !state.middlewareData.shift; - let availableHeight = overflowAvailableHeight; - let availableWidth = overflowAvailableWidth; - if (isXAxis) { - const maximumClippingWidth = - width - overflow.left - overflow.right; - availableWidth = - alignment || noShift - ? min(overflowAvailableWidth, maximumClippingWidth) - : maximumClippingWidth; - } else { - const maximumClippingHeight = - height - overflow.top - overflow.bottom; - availableHeight = - alignment || noShift - ? min(overflowAvailableHeight, maximumClippingHeight) - : maximumClippingHeight; - } - if (noShift && !alignment) { - const xMin = max(overflow.left, 0); - const xMax = max(overflow.right, 0); - const yMin = max(overflow.top, 0); - const yMax = max(overflow.bottom, 0); - if (isXAxis) { - availableWidth = - width - - 2 * - (xMin !== 0 || xMax !== 0 - ? xMin + xMax - : max(overflow.left, overflow.right)); - } else { - availableHeight = - height - - 2 * - (yMin !== 0 || yMax !== 0 - ? yMin + yMax - : max(overflow.top, overflow.bottom)); - } - } - await apply({ - ...state, - availableWidth, - availableHeight, - }); - const nextDimensions = await platform.getDimensions( - elements.floating - ); - if ( - width !== nextDimensions.width || - height !== nextDimensions.height - ) { - return { - reset: { - rects: true, - }, - }; - } - return {}; - }, + reset: { + rects: true + } }; - }; - exports.size = size; - - /***/ - }, - - /***/ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "arrow", { - enumerable: true, - get: function () { - return _core.arrow; - }, - }); - Object.defineProperty(exports, "autoPlacement", { - enumerable: true, - get: function () { - return _core.autoPlacement; - }, - }); - exports.autoUpdate = autoUpdate; - exports.computePosition = void 0; - Object.defineProperty(exports, "detectOverflow", { - enumerable: true, - get: function () { - return _core.detectOverflow; - }, - }); - Object.defineProperty(exports, "flip", { - enumerable: true, - get: function () { - return _core.flip; - }, - }); - exports.getOverflowAncestors = getOverflowAncestors; - Object.defineProperty(exports, "hide", { - enumerable: true, - get: function () { - return _core.hide; - }, - }); - Object.defineProperty(exports, "inline", { - enumerable: true, - get: function () { - return _core.inline; - }, - }); - Object.defineProperty(exports, "limitShift", { - enumerable: true, - get: function () { - return _core.limitShift; - }, - }); - Object.defineProperty(exports, "offset", { - enumerable: true, - get: function () { - return _core.offset; - }, - }); - exports.platform = void 0; - Object.defineProperty(exports, "shift", { - enumerable: true, - get: function () { - return _core.shift; - }, - }); - Object.defineProperty(exports, "size", { - enumerable: true, - get: function () { - return _core.size; - }, - }); - var _core = __webpack_require__( - /*! @floating-ui/core */ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js" - ); - function getWindow(node) { - var _node$ownerDocument; - return ( - ((_node$ownerDocument = node.ownerDocument) == null - ? void 0 - : _node$ownerDocument.defaultView) || window - ); - } - function getComputedStyle$1(element) { - return getWindow(element).getComputedStyle(element); - } - function isNode(value) { - return value instanceof getWindow(value).Node; } - function getNodeName(node) { - return isNode(node) ? (node.nodeName || "").toLowerCase() : ""; - } - function isHTMLElement(value) { - return value instanceof getWindow(value).HTMLElement; - } - function isElement(value) { - return value instanceof getWindow(value).Element; - } - function isShadowRoot(node) { - // Browsers without `ShadowRoot` support. - if (typeof ShadowRoot === "undefined") { - return false; - } - const OwnElement = getWindow(node).ShadowRoot; - return node instanceof OwnElement || node instanceof ShadowRoot; - } - function isOverflowElement(element) { - const { overflow, overflowX, overflowY, display } = - getComputedStyle$1(element); - return ( - /auto|scroll|overlay|hidden|clip/.test( - overflow + overflowY + overflowX - ) && !["inline", "contents"].includes(display) - ); - } - function isTableElement(element) { - return ["table", "td", "th"].includes(getNodeName(element)); - } - function isContainingBlock(element) { - const safari = isSafari(); - const css = getComputedStyle$1(element); - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - return ( - css.transform !== "none" || - css.perspective !== "none" || - (!safari && - (css.backdropFilter ? css.backdropFilter !== "none" : false)) || - (!safari && (css.filter ? css.filter !== "none" : false)) || - ["transform", "perspective", "filter"].some((value) => - (css.willChange || "").includes(value) - ) || - ["paint", "layout", "strict", "content"].some((value) => - (css.contain || "").includes(value) - ) - ); - } - function isSafari() { - if (typeof CSS === "undefined" || !CSS.supports) return false; - return CSS.supports("-webkit-backdrop-filter", "none"); - } - function isLastTraversableNode(node) { - return ["html", "body", "#document"].includes(getNodeName(node)); - } - const min = Math.min; - const max = Math.max; - const round = Math.round; - function getCssDimensions(element) { - const css = getComputedStyle$1(element); - // In testing environments, the `width` and `height` properties are empty - // strings for SVG elements, returning NaN. Fallback to `0` in this case. - let width = parseFloat(css.width) || 0; - let height = parseFloat(css.height) || 0; - const hasOffset = isHTMLElement(element); - const offsetWidth = hasOffset ? element.offsetWidth : width; - const offsetHeight = hasOffset ? element.offsetHeight : height; - const shouldFallback = - round(width) !== offsetWidth || round(height) !== offsetHeight; - if (shouldFallback) { - width = offsetWidth; - height = offsetHeight; - } - return { - width, - height, - fallback: shouldFallback, - }; - } - function unwrapElement(element) { - return !isElement(element) ? element.contextElement : element; - } - const FALLBACK_SCALE = { - x: 1, - y: 1, - }; - function getScale(element) { - const domElement = unwrapElement(element); - if (!isHTMLElement(domElement)) { - return FALLBACK_SCALE; - } - const rect = domElement.getBoundingClientRect(); - const { width, height, fallback } = getCssDimensions(domElement); - let x = (fallback ? round(rect.width) : rect.width) / width; - let y = (fallback ? round(rect.height) : rect.height) / height; - - // 0, NaN, or Infinity should always fallback to 1. - - if (!x || !Number.isFinite(x)) { - x = 1; - } - if (!y || !Number.isFinite(y)) { - y = 1; - } - return { - x, - y, - }; - } - const noOffsets = { + return {}; + } + }; + }; + exports.size = size; + + /***/ }), + + /***/ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "arrow", ({ + enumerable: true, + get: function () { + return _core.arrow; + } + })); + Object.defineProperty(exports, "autoPlacement", ({ + enumerable: true, + get: function () { + return _core.autoPlacement; + } + })); + exports.autoUpdate = autoUpdate; + exports.computePosition = void 0; + Object.defineProperty(exports, "detectOverflow", ({ + enumerable: true, + get: function () { + return _core.detectOverflow; + } + })); + Object.defineProperty(exports, "flip", ({ + enumerable: true, + get: function () { + return _core.flip; + } + })); + exports.getOverflowAncestors = getOverflowAncestors; + Object.defineProperty(exports, "hide", ({ + enumerable: true, + get: function () { + return _core.hide; + } + })); + Object.defineProperty(exports, "inline", ({ + enumerable: true, + get: function () { + return _core.inline; + } + })); + Object.defineProperty(exports, "limitShift", ({ + enumerable: true, + get: function () { + return _core.limitShift; + } + })); + Object.defineProperty(exports, "offset", ({ + enumerable: true, + get: function () { + return _core.offset; + } + })); + exports.platform = void 0; + Object.defineProperty(exports, "shift", ({ + enumerable: true, + get: function () { + return _core.shift; + } + })); + Object.defineProperty(exports, "size", ({ + enumerable: true, + get: function () { + return _core.size; + } + })); + var _core = __webpack_require__(/*! @floating-ui/core */ "../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js"); + function getWindow(node) { + var _node$ownerDocument; + return ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; + } + function getComputedStyle$1(element) { + return getWindow(element).getComputedStyle(element); + } + function isNode(value) { + return value instanceof getWindow(value).Node; + } + function getNodeName(node) { + return isNode(node) ? (node.nodeName || '').toLowerCase() : ''; + } + function isHTMLElement(value) { + return value instanceof getWindow(value).HTMLElement; + } + function isElement(value) { + return value instanceof getWindow(value).Element; + } + function isShadowRoot(node) { + // Browsers without `ShadowRoot` support. + if (typeof ShadowRoot === 'undefined') { + return false; + } + const OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; + } + function isOverflowElement(element) { + const { + overflow, + overflowX, + overflowY, + display + } = getComputedStyle$1(element); + return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display); + } + function isTableElement(element) { + return ['table', 'td', 'th'].includes(getNodeName(element)); + } + function isContainingBlock(element) { + const safari = isSafari(); + const css = getComputedStyle$1(element); + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + return css.transform !== 'none' || css.perspective !== 'none' || !safari && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !safari && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value)); + } + function isSafari() { + if (typeof CSS === 'undefined' || !CSS.supports) return false; + return CSS.supports('-webkit-backdrop-filter', 'none'); + } + function isLastTraversableNode(node) { + return ['html', 'body', '#document'].includes(getNodeName(node)); + } + const min = Math.min; + const max = Math.max; + const round = Math.round; + function getCssDimensions(element) { + const css = getComputedStyle$1(element); + // In testing environments, the `width` and `height` properties are empty + // strings for SVG elements, returning NaN. Fallback to `0` in this case. + let width = parseFloat(css.width) || 0; + let height = parseFloat(css.height) || 0; + const hasOffset = isHTMLElement(element); + const offsetWidth = hasOffset ? element.offsetWidth : width; + const offsetHeight = hasOffset ? element.offsetHeight : height; + const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; + if (shouldFallback) { + width = offsetWidth; + height = offsetHeight; + } + return { + width, + height, + fallback: shouldFallback + }; + } + function unwrapElement(element) { + return !isElement(element) ? element.contextElement : element; + } + const FALLBACK_SCALE = { + x: 1, + y: 1 + }; + function getScale(element) { + const domElement = unwrapElement(element); + if (!isHTMLElement(domElement)) { + return FALLBACK_SCALE; + } + const rect = domElement.getBoundingClientRect(); + const { + width, + height, + fallback + } = getCssDimensions(domElement); + let x = (fallback ? round(rect.width) : rect.width) / width; + let y = (fallback ? round(rect.height) : rect.height) / height; + + // 0, NaN, or Infinity should always fallback to 1. + + if (!x || !Number.isFinite(x)) { + x = 1; + } + if (!y || !Number.isFinite(y)) { + y = 1; + } + return { + x, + y + }; + } + const noOffsets = { + x: 0, + y: 0 + }; + function getVisualOffsets(element, isFixed, floatingOffsetParent) { + var _win$visualViewport, _win$visualViewport2; + if (isFixed === void 0) { + isFixed = true; + } + if (!isSafari()) { + return noOffsets; + } + const win = element ? getWindow(element) : window; + if (!floatingOffsetParent || isFixed && floatingOffsetParent !== win) { + return noOffsets; + } + return { + x: ((_win$visualViewport = win.visualViewport) == null ? void 0 : _win$visualViewport.offsetLeft) || 0, + y: ((_win$visualViewport2 = win.visualViewport) == null ? void 0 : _win$visualViewport2.offsetTop) || 0 + }; + } + function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { + if (includeScale === void 0) { + includeScale = false; + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + const clientRect = element.getBoundingClientRect(); + const domElement = unwrapElement(element); + let scale = FALLBACK_SCALE; + if (includeScale) { + if (offsetParent) { + if (isElement(offsetParent)) { + scale = getScale(offsetParent); + } + } else { + scale = getScale(element); + } + } + const visualOffsets = getVisualOffsets(domElement, isFixedStrategy, offsetParent); + let x = (clientRect.left + visualOffsets.x) / scale.x; + let y = (clientRect.top + visualOffsets.y) / scale.y; + let width = clientRect.width / scale.x; + let height = clientRect.height / scale.y; + if (domElement) { + const win = getWindow(domElement); + const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; + let currentIFrame = win.frameElement; + while (currentIFrame && offsetParent && offsetWin !== win) { + const iframeScale = getScale(currentIFrame); + const iframeRect = currentIFrame.getBoundingClientRect(); + const css = getComputedStyle(currentIFrame); + iframeRect.x += (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; + iframeRect.y += (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; + x *= iframeScale.x; + y *= iframeScale.y; + width *= iframeScale.x; + height *= iframeScale.y; + x += iframeRect.x; + y += iframeRect.y; + currentIFrame = getWindow(currentIFrame).frameElement; + } + } + return (0, _core.rectToClientRect)({ + width, + height, + x, + y + }); + } + function getDocumentElement(node) { + return ((isNode(node) ? node.ownerDocument : node.document) || window.document).documentElement; + } + function getNodeScroll(element) { + if (isElement(element)) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop + }; + } + return { + scrollLeft: element.pageXOffset, + scrollTop: element.pageYOffset + }; + } + function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { + let { + rect, + offsetParent, + strategy + } = _ref; + const isOffsetParentAnElement = isHTMLElement(offsetParent); + const documentElement = getDocumentElement(offsetParent); + if (offsetParent === documentElement) { + return rect; + } + let scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + let scale = { + x: 1, + y: 1 + }; + const offsets = { + x: 0, + y: 0 + }; + if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== 'fixed') { + if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + const offsetRect = getBoundingClientRect(offsetParent); + scale = getScale(offsetParent); + offsets.x = offsetRect.x + offsetParent.clientLeft; + offsets.y = offsetRect.y + offsetParent.clientTop; + } + } + return { + width: rect.width * scale.x, + height: rect.height * scale.y, + x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, + y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + }; + } + function getWindowScrollBarX(element) { + // If has a CSS width greater than the viewport, then this will be + // incorrect for RTL. + return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft; + } + + // Gets the entire size of the scrollable document area, even extending outside + // of the `` and `` rect bounds if horizontally scrollable. + function getDocumentRect(element) { + const html = getDocumentElement(element); + const scroll = getNodeScroll(element); + const body = element.ownerDocument.body; + const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); + const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); + let x = -scroll.scrollLeft + getWindowScrollBarX(element); + const y = -scroll.scrollTop; + if (getComputedStyle$1(body).direction === 'rtl') { + x += max(html.clientWidth, body.clientWidth) - width; + } + return { + width, + height, + x, + y + }; + } + function getParentNode(node) { + if (getNodeName(node) === 'html') { + return node; + } + const result = + // Step into the shadow DOM of the parent of a slotted node. + node.assignedSlot || + // DOM Element detected. + node.parentNode || + // ShadowRoot detected. + isShadowRoot(node) && node.host || + // Fallback. + getDocumentElement(node); + return isShadowRoot(result) ? result.host : result; + } + function getNearestOverflowAncestor(node) { + const parentNode = getParentNode(node); + if (isLastTraversableNode(parentNode)) { + // `getParentNode` will never return a `Document` due to the fallback + // check, so it's either the or element. + return parentNode.ownerDocument.body; + } + if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { + return parentNode; + } + return getNearestOverflowAncestor(parentNode); + } + function getOverflowAncestors(node, list) { + var _node$ownerDocument; + if (list === void 0) { + list = []; + } + const scrollableAncestor = getNearestOverflowAncestor(node); + const isBody = scrollableAncestor === ((_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.body); + const win = getWindow(scrollableAncestor); + if (isBody) { + return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : []); + } + return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor)); + } + function getViewportRect(element, strategy) { + const win = getWindow(element); + const html = getDocumentElement(element); + const visualViewport = win.visualViewport; + let width = html.clientWidth; + let height = html.clientHeight; + let x = 0; + let y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + const visualViewportBased = isSafari(); + if (!visualViewportBased || visualViewportBased && strategy === 'fixed') { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + return { + width, + height, + x, + y + }; + } + + // Returns the inner client rect, subtracting scrollbars if present. + function getInnerBoundingClientRect(element, strategy) { + const clientRect = getBoundingClientRect(element, true, strategy === 'fixed'); + const top = clientRect.top + element.clientTop; + const left = clientRect.left + element.clientLeft; + const scale = isHTMLElement(element) ? getScale(element) : { + x: 1, + y: 1 + }; + const width = element.clientWidth * scale.x; + const height = element.clientHeight * scale.y; + const x = left * scale.x; + const y = top * scale.y; + return { + width, + height, + x, + y + }; + } + function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { + let rect; + if (clippingAncestor === 'viewport') { + rect = getViewportRect(element, strategy); + } else if (clippingAncestor === 'document') { + rect = getDocumentRect(getDocumentElement(element)); + } else if (isElement(clippingAncestor)) { + rect = getInnerBoundingClientRect(clippingAncestor, strategy); + } else { + const visualOffsets = getVisualOffsets(element); + rect = { + ...clippingAncestor, + x: clippingAncestor.x - visualOffsets.x, + y: clippingAncestor.y - visualOffsets.y + }; + } + return (0, _core.rectToClientRect)(rect); + } + function hasFixedPositionAncestor(element, stopNode) { + const parentNode = getParentNode(element); + if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { + return false; + } + return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode); + } + + // A "clipping ancestor" is an `overflow` element with the characteristic of + // clipping (or hiding) child elements. This returns all clipping ancestors + // of the given element up the tree. + function getClippingElementAncestors(element, cache) { + const cachedResult = cache.get(element); + if (cachedResult) { + return cachedResult; + } + let result = getOverflowAncestors(element).filter(el => isElement(el) && getNodeName(el) !== 'body'); + let currentContainingBlockComputedStyle = null; + const elementIsFixed = getComputedStyle$1(element).position === 'fixed'; + let currentNode = elementIsFixed ? getParentNode(element) : element; + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { + const computedStyle = getComputedStyle$1(currentNode); + const currentNodeIsContaining = isContainingBlock(currentNode); + if (!currentNodeIsContaining && computedStyle.position === 'fixed') { + currentContainingBlockComputedStyle = null; + } + const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); + if (shouldDropCurrentNode) { + // Drop non-containing blocks. + result = result.filter(ancestor => ancestor !== currentNode); + } else { + // Record last containing block for next iteration. + currentContainingBlockComputedStyle = computedStyle; + } + currentNode = getParentNode(currentNode); + } + cache.set(element, result); + return result; + } + + // Gets the maximum area that the element is visible in due to any number of + // clipping ancestors. + function getClippingRect(_ref) { + let { + element, + boundary, + rootBoundary, + strategy + } = _ref; + const elementClippingAncestors = boundary === 'clippingAncestors' ? getClippingElementAncestors(element, this._c) : [].concat(boundary); + const clippingAncestors = [...elementClippingAncestors, rootBoundary]; + const firstClippingAncestor = clippingAncestors[0]; + const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { + const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); + return { + width: clippingRect.right - clippingRect.left, + height: clippingRect.bottom - clippingRect.top, + x: clippingRect.left, + y: clippingRect.top + }; + } + function getDimensions(element) { + return getCssDimensions(element); + } + function getTrueOffsetParent(element, polyfill) { + if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') { + return null; + } + if (polyfill) { + return polyfill(element); + } + return element.offsetParent; + } + function getContainingBlock(element) { + let currentNode = getParentNode(element); + while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { + if (isContainingBlock(currentNode)) { + return currentNode; + } else { + currentNode = getParentNode(currentNode); + } + } + return null; + } + + // Gets the closest ancestor positioned element. Handles some edge cases, + // such as table ancestors and cross browser bugs. + function getOffsetParent(element, polyfill) { + const window = getWindow(element); + if (!isHTMLElement(element)) { + return window; + } + let offsetParent = getTrueOffsetParent(element, polyfill); + while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') { + offsetParent = getTrueOffsetParent(offsetParent, polyfill); + } + if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static' && !isContainingBlock(offsetParent))) { + return window; + } + return offsetParent || getContainingBlock(element) || window; + } + function getRectRelativeToOffsetParent(element, offsetParent, strategy) { + const isOffsetParentAnElement = isHTMLElement(offsetParent); + const documentElement = getDocumentElement(offsetParent); + const isFixed = strategy === 'fixed'; + const rect = getBoundingClientRect(element, true, isFixed, offsetParent); + let scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + const offsets = { + x: 0, + y: 0 + }; + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); + offsets.x = offsetRect.x + offsetParent.clientLeft; + offsets.y = offsetRect.y + offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; + } + const platform = exports.platform = { + getClippingRect, + convertOffsetParentRelativeRectToViewportRelativeRect, + isElement, + getDimensions, + getOffsetParent, + getDocumentElement, + getScale, + async getElementRects(_ref) { + let { + reference, + floating, + strategy + } = _ref; + const getOffsetParentFn = this.getOffsetParent || getOffsetParent; + const getDimensionsFn = this.getDimensions; + return { + reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy), + floating: { x: 0, y: 0, - }; - function getVisualOffsets(element, isFixed, floatingOffsetParent) { - var _win$visualViewport, _win$visualViewport2; - if (isFixed === void 0) { - isFixed = true; - } - if (!isSafari()) { - return noOffsets; - } - const win = element ? getWindow(element) : window; - if ( - !floatingOffsetParent || - (isFixed && floatingOffsetParent !== win) - ) { - return noOffsets; - } - return { - x: - ((_win$visualViewport = win.visualViewport) == null - ? void 0 - : _win$visualViewport.offsetLeft) || 0, - y: - ((_win$visualViewport2 = win.visualViewport) == null - ? void 0 - : _win$visualViewport2.offsetTop) || 0, - }; + ...(await getDimensionsFn(floating)) } - function getBoundingClientRect( + }; + }, + getClientRects: element => Array.from(element.getClientRects()), + isRTL: element => getComputedStyle$1(element).direction === 'rtl' + }; + + /** + * Automatically updates the position of the floating element when necessary. + * Should only be called when the floating element is mounted on the DOM or + * visible on the screen. + * @returns cleanup function that should be invoked when the floating element is + * removed from the DOM or hidden from the screen. + * @see https://floating-ui.com/docs/autoUpdate + */ + function autoUpdate(reference, floating, update, options) { + if (options === void 0) { + options = {}; + } + const { + ancestorScroll = true, + ancestorResize = true, + elementResize = true, + animationFrame = false + } = options; + const ancestors = ancestorScroll || ancestorResize ? [...(isElement(reference) ? getOverflowAncestors(reference) : reference.contextElement ? getOverflowAncestors(reference.contextElement) : []), ...getOverflowAncestors(floating)] : []; + ancestors.forEach(ancestor => { + // ignores Window, checks for [object VisualViewport] + const isVisualViewport = !isElement(ancestor) && ancestor.toString().includes('V'); + if (ancestorScroll && (animationFrame ? isVisualViewport : true)) { + ancestor.addEventListener('scroll', update, { + passive: true + }); + } + ancestorResize && ancestor.addEventListener('resize', update); + }); + let observer = null; + if (elementResize) { + observer = new ResizeObserver(() => { + update(); + }); + isElement(reference) && !animationFrame && observer.observe(reference); + if (!isElement(reference) && reference.contextElement && !animationFrame) { + observer.observe(reference.contextElement); + } + observer.observe(floating); + } + let frameId; + let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null; + if (animationFrame) { + frameLoop(); + } + function frameLoop() { + const nextRefRect = getBoundingClientRect(reference); + if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) { + update(); + } + prevRefRect = nextRefRect; + frameId = requestAnimationFrame(frameLoop); + } + update(); + return () => { + var _observer; + ancestors.forEach(ancestor => { + ancestorScroll && ancestor.removeEventListener('scroll', update); + ancestorResize && ancestor.removeEventListener('resize', update); + }); + (_observer = observer) == null ? void 0 : _observer.disconnect(); + observer = null; + if (animationFrame) { + cancelAnimationFrame(frameId); + } + }; + } + + /** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a reference element when it is given a certain CSS positioning + * strategy. + */ + const computePosition = (reference, floating, options) => { + // This caches the expensive `getClippingElementAncestors` function so that + // multiple lifecycle resets re-use the same result. It only lives for a + // single call. If other functions become expensive, we can add them as well. + const cache = new Map(); + const mergedOptions = { + platform, + ...options + }; + const platformWithCache = { + ...mergedOptions.platform, + _c: cache + }; + return (0, _core.computePosition)(reference, floating, { + ...mergedOptions, + platform: platformWithCache + }); + }; + exports.computePosition = computePosition; + + /***/ }), + + /***/ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js ***! + \**************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.arrow = void 0; + Object.defineProperty(exports, "autoPlacement", ({ + enumerable: true, + get: function () { + return _dom.autoPlacement; + } + })); + Object.defineProperty(exports, "autoUpdate", ({ + enumerable: true, + get: function () { + return _dom.autoUpdate; + } + })); + Object.defineProperty(exports, "computePosition", ({ + enumerable: true, + get: function () { + return _dom.computePosition; + } + })); + Object.defineProperty(exports, "detectOverflow", ({ + enumerable: true, + get: function () { + return _dom.detectOverflow; + } + })); + Object.defineProperty(exports, "flip", ({ + enumerable: true, + get: function () { + return _dom.flip; + } + })); + Object.defineProperty(exports, "getOverflowAncestors", ({ + enumerable: true, + get: function () { + return _dom.getOverflowAncestors; + } + })); + Object.defineProperty(exports, "hide", ({ + enumerable: true, + get: function () { + return _dom.hide; + } + })); + Object.defineProperty(exports, "inline", ({ + enumerable: true, + get: function () { + return _dom.inline; + } + })); + Object.defineProperty(exports, "limitShift", ({ + enumerable: true, + get: function () { + return _dom.limitShift; + } + })); + Object.defineProperty(exports, "offset", ({ + enumerable: true, + get: function () { + return _dom.offset; + } + })); + Object.defineProperty(exports, "platform", ({ + enumerable: true, + get: function () { + return _dom.platform; + } + })); + Object.defineProperty(exports, "shift", ({ + enumerable: true, + get: function () { + return _dom.shift; + } + })); + Object.defineProperty(exports, "size", ({ + enumerable: true, + get: function () { + return _dom.size; + } + })); + exports.useFloating = useFloating; + var _dom = __webpack_require__(/*! @floating-ui/dom */ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js"); + var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var React = _react; + var ReactDOM = _interopRequireWildcard(__webpack_require__(/*! react-dom */ "react-dom")); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + /** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * This wraps the core `arrow` middleware to allow React refs as the element. + * @see https://floating-ui.com/docs/arrow + */ + const arrow = options => { + function isRef(value) { + return {}.hasOwnProperty.call(value, 'current'); + } + return { + name: 'arrow', + options, + fn(state) { + const { element, - includeScale, - isFixedStrategy, - offsetParent - ) { - if (includeScale === void 0) { - includeScale = false; - } - if (isFixedStrategy === void 0) { - isFixedStrategy = false; - } - const clientRect = element.getBoundingClientRect(); - const domElement = unwrapElement(element); - let scale = FALLBACK_SCALE; - if (includeScale) { - if (offsetParent) { - if (isElement(offsetParent)) { - scale = getScale(offsetParent); - } - } else { - scale = getScale(element); - } - } - const visualOffsets = getVisualOffsets( - domElement, - isFixedStrategy, - offsetParent - ); - let x = (clientRect.left + visualOffsets.x) / scale.x; - let y = (clientRect.top + visualOffsets.y) / scale.y; - let width = clientRect.width / scale.x; - let height = clientRect.height / scale.y; - if (domElement) { - const win = getWindow(domElement); - const offsetWin = - offsetParent && isElement(offsetParent) - ? getWindow(offsetParent) - : offsetParent; - let currentIFrame = win.frameElement; - while (currentIFrame && offsetParent && offsetWin !== win) { - const iframeScale = getScale(currentIFrame); - const iframeRect = currentIFrame.getBoundingClientRect(); - const css = getComputedStyle(currentIFrame); - iframeRect.x += - (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * - iframeScale.x; - iframeRect.y += - (currentIFrame.clientTop + parseFloat(css.paddingTop)) * - iframeScale.y; - x *= iframeScale.x; - y *= iframeScale.y; - width *= iframeScale.x; - height *= iframeScale.y; - x += iframeRect.x; - y += iframeRect.y; - currentIFrame = getWindow(currentIFrame).frameElement; - } - } - return (0, _core.rectToClientRect)({ - width, - height, - x, - y, - }); - } - function getDocumentElement(node) { - return ( - (isNode(node) ? node.ownerDocument : node.document) || - window.document - ).documentElement; - } - function getNodeScroll(element) { - if (isElement(element)) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop, - }; + padding + } = typeof options === 'function' ? options(state) : options; + if (element && isRef(element)) { + if (element.current != null) { + return (0, _dom.arrow)({ + element: element.current, + padding + }).fn(state); } - return { - scrollLeft: element.pageXOffset, - scrollTop: element.pageYOffset, - }; + return {}; + } else if (element) { + return (0, _dom.arrow)({ + element, + padding + }).fn(state); } - function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { - let { rect, offsetParent, strategy } = _ref; - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - if (offsetParent === documentElement) { - return rect; - } - let scroll = { - scrollLeft: 0, - scrollTop: 0, - }; - let scale = { - x: 1, - y: 1, - }; - const offsets = { - x: 0, - y: 0, - }; - if ( - isOffsetParentAnElement || - (!isOffsetParentAnElement && strategy !== "fixed") - ) { - if ( - getNodeName(offsetParent) !== "body" || - isOverflowElement(documentElement) - ) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect(offsetParent); - scale = getScale(offsetParent); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } + return {}; + } + }; + }; + exports.arrow = arrow; + var index = typeof document !== 'undefined' ? _react.useLayoutEffect : _react.useEffect; + + // Fork of `fast-deep-equal` that only does the comparisons we need and compares + // functions + function deepEqual(a, b) { + if (a === b) { + return true; + } + if (typeof a !== typeof b) { + return false; + } + if (typeof a === 'function' && a.toString() === b.toString()) { + return true; + } + let length, i, keys; + if (a && b && typeof a == 'object') { + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) { + if (!deepEqual(a[i], b[i])) { + return false; } - return { - width: rect.width * scale.x, - height: rect.height * scale.y, - x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x, - y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y, - }; - } - function getWindowScrollBarX(element) { - // If has a CSS width greater than the viewport, then this will be - // incorrect for RTL. - return ( - getBoundingClientRect(getDocumentElement(element)).left + - getNodeScroll(element).scrollLeft - ); } - - // Gets the entire size of the scrollable document area, even extending outside - // of the `` and `` rect bounds if horizontally scrollable. - function getDocumentRect(element) { - const html = getDocumentElement(element); - const scroll = getNodeScroll(element); - const body = element.ownerDocument.body; - const width = max( - html.scrollWidth, - html.clientWidth, - body.scrollWidth, - body.clientWidth - ); - const height = max( - html.scrollHeight, - html.clientHeight, - body.scrollHeight, - body.clientHeight - ); - let x = -scroll.scrollLeft + getWindowScrollBarX(element); - const y = -scroll.scrollTop; - if (getComputedStyle$1(body).direction === "rtl") { - x += max(html.clientWidth, body.clientWidth) - width; - } - return { - width, - height, - x, - y, - }; + return true; + } + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) { + return false; + } + for (i = length; i-- !== 0;) { + if (!{}.hasOwnProperty.call(b, keys[i])) { + return false; } - function getParentNode(node) { - if (getNodeName(node) === "html") { - return node; - } - const result = - // Step into the shadow DOM of the parent of a slotted node. - node.assignedSlot || - // DOM Element detected. - node.parentNode || - // ShadowRoot detected. - (isShadowRoot(node) && node.host) || - // Fallback. - getDocumentElement(node); - return isShadowRoot(result) ? result.host : result; - } - function getNearestOverflowAncestor(node) { - const parentNode = getParentNode(node); - if (isLastTraversableNode(parentNode)) { - // `getParentNode` will never return a `Document` due to the fallback - // check, so it's either the or element. - return parentNode.ownerDocument.body; - } - if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { - return parentNode; - } - return getNearestOverflowAncestor(parentNode); - } - function getOverflowAncestors(node, list) { - var _node$ownerDocument; - if (list === void 0) { - list = []; - } - const scrollableAncestor = getNearestOverflowAncestor(node); - const isBody = - scrollableAncestor === - ((_node$ownerDocument = node.ownerDocument) == null - ? void 0 - : _node$ownerDocument.body); - const win = getWindow(scrollableAncestor); - if (isBody) { - return list.concat( - win, - win.visualViewport || [], - isOverflowElement(scrollableAncestor) ? scrollableAncestor : [] - ); - } - return list.concat( - scrollableAncestor, - getOverflowAncestors(scrollableAncestor) - ); + } + for (i = length; i-- !== 0;) { + const key = keys[i]; + if (key === '_owner' && a.$$typeof) { + continue; } - function getViewportRect(element, strategy) { - const win = getWindow(element); - const html = getDocumentElement(element); - const visualViewport = win.visualViewport; - let width = html.clientWidth; - let height = html.clientHeight; - let x = 0; - let y = 0; - if (visualViewport) { - width = visualViewport.width; - height = visualViewport.height; - const visualViewportBased = isSafari(); - if ( - !visualViewportBased || - (visualViewportBased && strategy === "fixed") - ) { - x = visualViewport.offsetLeft; - y = visualViewport.offsetTop; - } - } - return { - width, - height, - x, - y, - }; + if (!deepEqual(a[key], b[key])) { + return false; } - - // Returns the inner client rect, subtracting scrollbars if present. - function getInnerBoundingClientRect(element, strategy) { - const clientRect = getBoundingClientRect( - element, - true, - strategy === "fixed" - ); - const top = clientRect.top + element.clientTop; - const left = clientRect.left + element.clientLeft; - const scale = isHTMLElement(element) - ? getScale(element) - : { - x: 1, - y: 1, - }; - const width = element.clientWidth * scale.x; - const height = element.clientHeight * scale.y; - const x = left * scale.x; - const y = top * scale.y; - return { - width, - height, - x, - y, - }; - } - function getClientRectFromClippingAncestor( - element, - clippingAncestor, - strategy - ) { - let rect; - if (clippingAncestor === "viewport") { - rect = getViewportRect(element, strategy); - } else if (clippingAncestor === "document") { - rect = getDocumentRect(getDocumentElement(element)); - } else if (isElement(clippingAncestor)) { - rect = getInnerBoundingClientRect(clippingAncestor, strategy); - } else { - const visualOffsets = getVisualOffsets(element); - rect = { - ...clippingAncestor, - x: clippingAncestor.x - visualOffsets.x, - y: clippingAncestor.y - visualOffsets.y, - }; - } - return (0, _core.rectToClientRect)(rect); - } - function hasFixedPositionAncestor(element, stopNode) { - const parentNode = getParentNode(element); - if ( - parentNode === stopNode || - !isElement(parentNode) || - isLastTraversableNode(parentNode) - ) { - return false; - } - return ( - getComputedStyle$1(parentNode).position === "fixed" || - hasFixedPositionAncestor(parentNode, stopNode) - ); + } + return true; + } + return a !== a && b !== b; + } + function getDPR(element) { + if (typeof window === 'undefined') { + return 1; + } + const win = element.ownerDocument.defaultView || window; + return win.devicePixelRatio || 1; + } + function roundByDPR(element, value) { + const dpr = getDPR(element); + return Math.round(value * dpr) / dpr; + } + function useLatestRef(value) { + const ref = React.useRef(value); + index(() => { + ref.current = value; + }); + return ref; + } + + /** + * Provides data to position a floating element. + * @see https://floating-ui.com/docs/react + */ + function useFloating(options) { + if (options === void 0) { + options = {}; + } + const { + placement = 'bottom', + strategy = 'absolute', + middleware = [], + platform, + elements: { + reference: externalReference, + floating: externalFloating + } = {}, + transform = true, + whileElementsMounted, + open + } = options; + const [data, setData] = React.useState({ + x: 0, + y: 0, + strategy, + placement, + middlewareData: {}, + isPositioned: false + }); + const [latestMiddleware, setLatestMiddleware] = React.useState(middleware); + if (!deepEqual(latestMiddleware, middleware)) { + setLatestMiddleware(middleware); + } + const [_reference, _setReference] = React.useState(null); + const [_floating, _setFloating] = React.useState(null); + const setReference = React.useCallback(node => { + if (node != referenceRef.current) { + referenceRef.current = node; + _setReference(node); + } + }, [_setReference]); + const setFloating = React.useCallback(node => { + if (node !== floatingRef.current) { + floatingRef.current = node; + _setFloating(node); + } + }, [_setFloating]); + const referenceEl = externalReference || _reference; + const floatingEl = externalFloating || _floating; + const referenceRef = React.useRef(null); + const floatingRef = React.useRef(null); + const dataRef = React.useRef(data); + const whileElementsMountedRef = useLatestRef(whileElementsMounted); + const platformRef = useLatestRef(platform); + const update = React.useCallback(() => { + if (!referenceRef.current || !floatingRef.current) { + return; + } + const config = { + placement, + strategy, + middleware: latestMiddleware + }; + if (platformRef.current) { + config.platform = platformRef.current; + } + (0, _dom.computePosition)(referenceRef.current, floatingRef.current, config).then(data => { + const fullData = { + ...data, + isPositioned: true + }; + if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) { + dataRef.current = fullData; + ReactDOM.flushSync(() => { + setData(fullData); + }); + } + }); + }, [latestMiddleware, placement, strategy, platformRef]); + index(() => { + if (open === false && dataRef.current.isPositioned) { + dataRef.current.isPositioned = false; + setData(data => ({ + ...data, + isPositioned: false + })); + } + }, [open]); + const isMountedRef = React.useRef(false); + index(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + }; + }, []); + index(() => { + if (referenceEl) referenceRef.current = referenceEl; + if (floatingEl) floatingRef.current = floatingEl; + if (referenceEl && floatingEl) { + if (whileElementsMountedRef.current) { + return whileElementsMountedRef.current(referenceEl, floatingEl, update); + } else { + update(); } - - // A "clipping ancestor" is an `overflow` element with the characteristic of - // clipping (or hiding) child elements. This returns all clipping ancestors - // of the given element up the tree. - function getClippingElementAncestors(element, cache) { - const cachedResult = cache.get(element); - if (cachedResult) { - return cachedResult; - } - let result = getOverflowAncestors(element).filter( - (el) => isElement(el) && getNodeName(el) !== "body" - ); - let currentContainingBlockComputedStyle = null; - const elementIsFixed = - getComputedStyle$1(element).position === "fixed"; - let currentNode = elementIsFixed ? getParentNode(element) : element; - - // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - while ( - isElement(currentNode) && - !isLastTraversableNode(currentNode) - ) { - const computedStyle = getComputedStyle$1(currentNode); - const currentNodeIsContaining = isContainingBlock(currentNode); - if ( - !currentNodeIsContaining && - computedStyle.position === "fixed" - ) { - currentContainingBlockComputedStyle = null; - } - const shouldDropCurrentNode = elementIsFixed - ? !currentNodeIsContaining && !currentContainingBlockComputedStyle - : (!currentNodeIsContaining && - computedStyle.position === "static" && - !!currentContainingBlockComputedStyle && - ["absolute", "fixed"].includes( - currentContainingBlockComputedStyle.position - )) || - (isOverflowElement(currentNode) && - !currentNodeIsContaining && - hasFixedPositionAncestor(element, currentNode)); - if (shouldDropCurrentNode) { - // Drop non-containing blocks. - result = result.filter((ancestor) => ancestor !== currentNode); - } else { - // Record last containing block for next iteration. - currentContainingBlockComputedStyle = computedStyle; - } - currentNode = getParentNode(currentNode); - } - cache.set(element, result); - return result; + } + }, [referenceEl, floatingEl, update, whileElementsMountedRef]); + const refs = React.useMemo(() => ({ + reference: referenceRef, + floating: floatingRef, + setReference, + setFloating + }), [setReference, setFloating]); + const elements = React.useMemo(() => ({ + reference: referenceEl, + floating: floatingEl + }), [referenceEl, floatingEl]); + const floatingStyles = React.useMemo(() => { + const initialStyles = { + position: strategy, + left: 0, + top: 0 + }; + if (!elements.floating) { + return initialStyles; + } + const x = roundByDPR(elements.floating, data.x); + const y = roundByDPR(elements.floating, data.y); + if (transform) { + return { + ...initialStyles, + transform: "translate(" + x + "px, " + y + "px)", + ...(getDPR(elements.floating) >= 1.5 && { + willChange: 'transform' + }) + }; + } + return { + position: strategy, + left: x, + top: y + }; + }, [strategy, transform, elements.floating, data.x, data.y]); + return React.useMemo(() => ({ + ...data, + update, + refs, + elements, + floatingStyles + }), [data, update, refs, elements, floatingStyles]); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/animation/dist/Animation.es.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/@motionone/animation/dist/Animation.es.js ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Animation = void 0; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js"); + class Animation { + constructor(output, keyframes = [0, 1], { + easing, + duration: initialDuration = _utils.defaults.duration, + delay = _utils.defaults.delay, + endDelay = _utils.defaults.endDelay, + repeat = _utils.defaults.repeat, + offset, + direction = "normal" + } = {}) { + this.startTime = null; + this.rate = 1; + this.t = 0; + this.cancelTimestamp = null; + this.easing = _utils.noopReturn; + this.duration = 0; + this.totalDuration = 0; + this.repeat = 0; + this.playState = "idle"; + this.finished = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + easing = easing || _utils.defaults.easing; + if ((0, _utils.isEasingGenerator)(easing)) { + const custom = easing.createAnimation(keyframes); + easing = custom.easing; + keyframes = custom.keyframes || keyframes; + initialDuration = custom.duration || initialDuration; + } + this.repeat = repeat; + this.easing = (0, _utils.isEasingList)(easing) ? _utils.noopReturn : (0, _easingEs.getEasingFunction)(easing); + this.updateDuration(initialDuration); + const interpolate$1 = (0, _utils.interpolate)(keyframes, offset, (0, _utils.isEasingList)(easing) ? easing.map(_easingEs.getEasingFunction) : _utils.noopReturn); + this.tick = timestamp => { + var _a; + // TODO: Temporary fix for OptionsResolver typing + delay = delay; + let t = 0; + if (this.pauseTime !== undefined) { + t = this.pauseTime; + } else { + t = (timestamp - this.startTime) * this.rate; } - - // Gets the maximum area that the element is visible in due to any number of - // clipping ancestors. - function getClippingRect(_ref) { - let { element, boundary, rootBoundary, strategy } = _ref; - const elementClippingAncestors = - boundary === "clippingAncestors" - ? getClippingElementAncestors(element, this._c) - : [].concat(boundary); - const clippingAncestors = [...elementClippingAncestors, rootBoundary]; - const firstClippingAncestor = clippingAncestors[0]; - const clippingRect = clippingAncestors.reduce( - (accRect, clippingAncestor) => { - const rect = getClientRectFromClippingAncestor( - element, - clippingAncestor, - strategy - ); - accRect.top = max(rect.top, accRect.top); - accRect.right = min(rect.right, accRect.right); - accRect.bottom = min(rect.bottom, accRect.bottom); - accRect.left = max(rect.left, accRect.left); - return accRect; - }, - getClientRectFromClippingAncestor( - element, - firstClippingAncestor, - strategy - ) - ); - return { - width: clippingRect.right - clippingRect.left, - height: clippingRect.bottom - clippingRect.top, - x: clippingRect.left, - y: clippingRect.top, - }; + this.t = t; + // Convert to seconds + t /= 1000; + // Rebase on delay + t = Math.max(t - delay, 0); + /** + * If this animation has finished, set the current time + * to the total duration. + */ + if (this.playState === "finished" && this.pauseTime === undefined) { + t = this.totalDuration; } - function getDimensions(element) { - return getCssDimensions(element); + /** + * Get the current progress (0-1) of the animation. If t is > + * than duration we'll get values like 2.5 (midway through the + * third iteration) + */ + const progress = t / this.duration; + // TODO progress += iterationStart + /** + * Get the current iteration (0 indexed). For instance the floor of + * 2.5 is 2. + */ + let currentIteration = Math.floor(progress); + /** + * Get the current progress of the iteration by taking the remainder + * so 2.5 is 0.5 through iteration 2 + */ + let iterationProgress = progress % 1.0; + if (!iterationProgress && progress >= 1) { + iterationProgress = 1; } - function getTrueOffsetParent(element, polyfill) { - if ( - !isHTMLElement(element) || - getComputedStyle$1(element).position === "fixed" - ) { - return null; - } - if (polyfill) { - return polyfill(element); - } - return element.offsetParent; + /** + * If iteration progress is 1 we count that as the end + * of the previous iteration. + */ + iterationProgress === 1 && currentIteration--; + /** + * Reverse progress if we're not running in "normal" direction + */ + const iterationIsOdd = currentIteration % 2; + if (direction === "reverse" || direction === "alternate" && iterationIsOdd || direction === "alternate-reverse" && !iterationIsOdd) { + iterationProgress = 1 - iterationProgress; } - function getContainingBlock(element) { - let currentNode = getParentNode(element); - while ( - isHTMLElement(currentNode) && - !isLastTraversableNode(currentNode) - ) { - if (isContainingBlock(currentNode)) { - return currentNode; - } else { - currentNode = getParentNode(currentNode); - } - } - return null; + const p = t >= this.totalDuration ? 1 : Math.min(iterationProgress, 1); + const latest = interpolate$1(this.easing(p)); + output(latest); + const isAnimationFinished = this.pauseTime === undefined && (this.playState === "finished" || t >= this.totalDuration + endDelay); + if (isAnimationFinished) { + this.playState = "finished"; + (_a = this.resolve) === null || _a === void 0 ? void 0 : _a.call(this, latest); + } else if (this.playState !== "idle") { + this.frameRequestId = requestAnimationFrame(this.tick); } - - // Gets the closest ancestor positioned element. Handles some edge cases, - // such as table ancestors and cross browser bugs. - function getOffsetParent(element, polyfill) { - const window = getWindow(element); - if (!isHTMLElement(element)) { - return window; - } - let offsetParent = getTrueOffsetParent(element, polyfill); - while ( - offsetParent && - isTableElement(offsetParent) && - getComputedStyle$1(offsetParent).position === "static" - ) { - offsetParent = getTrueOffsetParent(offsetParent, polyfill); - } - if ( - offsetParent && - (getNodeName(offsetParent) === "html" || - (getNodeName(offsetParent) === "body" && - getComputedStyle$1(offsetParent).position === "static" && - !isContainingBlock(offsetParent))) - ) { - return window; - } - return offsetParent || getContainingBlock(element) || window; - } - function getRectRelativeToOffsetParent( - element, - offsetParent, - strategy - ) { - const isOffsetParentAnElement = isHTMLElement(offsetParent); - const documentElement = getDocumentElement(offsetParent); - const isFixed = strategy === "fixed"; - const rect = getBoundingClientRect( - element, - true, - isFixed, - offsetParent - ); - let scroll = { - scrollLeft: 0, - scrollTop: 0, - }; - const offsets = { - x: 0, - y: 0, - }; - if ( - isOffsetParentAnElement || - (!isOffsetParentAnElement && !isFixed) - ) { - if ( - getNodeName(offsetParent) !== "body" || - isOverflowElement(documentElement) - ) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - const offsetRect = getBoundingClientRect( - offsetParent, - true, - isFixed, - offsetParent - ); - offsets.x = offsetRect.x + offsetParent.clientLeft; - offsets.y = offsetRect.y + offsetParent.clientTop; - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement); - } - } - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height, - }; + }; + this.play(); + } + play() { + const now = performance.now(); + this.playState = "running"; + if (this.pauseTime !== undefined) { + this.startTime = now - this.pauseTime; + } else if (!this.startTime) { + this.startTime = now; + } + this.cancelTimestamp = this.startTime; + this.pauseTime = undefined; + this.frameRequestId = requestAnimationFrame(this.tick); + } + pause() { + this.playState = "paused"; + this.pauseTime = this.t; + } + finish() { + this.playState = "finished"; + this.tick(0); + } + stop() { + var _a; + this.playState = "idle"; + if (this.frameRequestId !== undefined) { + cancelAnimationFrame(this.frameRequestId); + } + (_a = this.reject) === null || _a === void 0 ? void 0 : _a.call(this, false); + } + cancel() { + this.stop(); + this.tick(this.cancelTimestamp); + } + reverse() { + this.rate *= -1; + } + commitStyles() {} + updateDuration(duration) { + this.duration = duration; + this.totalDuration = duration * (this.repeat + 1); + } + get currentTime() { + return this.t; + } + set currentTime(t) { + if (this.pauseTime !== undefined || this.rate === 0) { + this.pauseTime = t; + } else { + this.startTime = performance.now() - t / this.rate; + } + } + get playbackRate() { + return this.rate; + } + set playbackRate(rate) { + this.rate = rate; + } + } + exports.Animation = Animation; + + /***/ }), + + /***/ "../../../node_modules/@motionone/animation/dist/index.es.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@motionone/animation/dist/index.es.js ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "Animation", ({ + enumerable: true, + get: function () { + return _AnimationEs.Animation; + } + })); + Object.defineProperty(exports, "getEasingFunction", ({ + enumerable: true, + get: function () { + return _easingEs.getEasingFunction; + } + })); + var _AnimationEs = __webpack_require__(/*! ./Animation.es.js */ "../../../node_modules/@motionone/animation/dist/Animation.es.js"); + var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js"); + + /***/ }), + + /***/ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/animation/dist/utils/easing.es.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getEasingFunction = getEasingFunction; + var _easing = __webpack_require__(/*! @motionone/easing */ "../../../node_modules/@motionone/easing/dist/index.es.js"); + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + const namedEasings = { + ease: (0, _easing.cubicBezier)(0.25, 0.1, 0.25, 1.0), + "ease-in": (0, _easing.cubicBezier)(0.42, 0.0, 1.0, 1.0), + "ease-in-out": (0, _easing.cubicBezier)(0.42, 0.0, 0.58, 1.0), + "ease-out": (0, _easing.cubicBezier)(0.0, 0.0, 0.58, 1.0) + }; + const functionArgsRegex = /\((.*?)\)/; + function getEasingFunction(definition) { + // If already an easing function, return + if ((0, _utils.isFunction)(definition)) return definition; + // If an easing curve definition, return bezier function + if ((0, _utils.isCubicBezier)(definition)) return (0, _easing.cubicBezier)(...definition); + // If we have a predefined easing function, return + if (namedEasings[definition]) return namedEasings[definition]; + // If this is a steps function, attempt to create easing curve + if (definition.startsWith("steps")) { + const args = functionArgsRegex.exec(definition); + if (args) { + const argsArray = args[1].split(","); + return (0, _easing.steps)(parseFloat(argsArray[0]), argsArray[1].trim()); + } + } + return _utils.noopReturn; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.animateStyle = animateStyle; + var _dataEs = __webpack_require__(/*! ./data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); + var _cssVarEs = __webpack_require__(/*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js"); + var _animation = __webpack_require__(/*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js"); + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _transformsEs = __webpack_require__(/*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); + var _easingEs = __webpack_require__(/*! ./utils/easing.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js"); + var _featureDetectionEs = __webpack_require__(/*! ./utils/feature-detection.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js"); + var _keyframesEs = __webpack_require__(/*! ./utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js"); + var _styleEs = __webpack_require__(/*! ./style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); + var _getStyleNameEs = __webpack_require__(/*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); + var _stopAnimationEs = __webpack_require__(/*! ./utils/stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js"); + function getDevToolsRecord() { + return window.__MOTION_DEV_TOOLS_RECORD; + } + function animateStyle(element, key, keyframesDefinition, options = {}) { + const record = getDevToolsRecord(); + const isRecording = options.record !== false && record; + let animation; + let { + duration = _utils.defaults.duration, + delay = _utils.defaults.delay, + endDelay = _utils.defaults.endDelay, + repeat = _utils.defaults.repeat, + easing = _utils.defaults.easing, + direction, + offset, + allowWebkitAcceleration = false + } = options; + const data = (0, _dataEs.getAnimationData)(element); + let canAnimateNatively = _featureDetectionEs.supports.waapi(); + const valueIsTransform = (0, _transformsEs.isTransform)(key); + /** + * If this is an individual transform, we need to map its + * key to a CSS variable and update the element's transform style + */ + valueIsTransform && (0, _transformsEs.addTransformToElement)(element, key); + const name = (0, _getStyleNameEs.getStyleName)(key); + const motionValue = (0, _dataEs.getMotionValue)(data.values, name); + /** + * Get definition of value, this will be used to convert numerical + * keyframes into the default value type. + */ + const definition = _transformsEs.transformDefinitions.get(name); + /** + * Stop the current animation, if any. Because this will trigger + * commitStyles (DOM writes) and we might later trigger DOM reads, + * this is fired now and we return a factory function to create + * the actual animation that can get called in batch, + */ + (0, _stopAnimationEs.stopAnimation)(motionValue.animation, !((0, _utils.isEasingGenerator)(easing) && motionValue.generator) && options.record !== false); + /** + * Batchable factory function containing all DOM reads. + */ + return () => { + const readInitialValue = () => { + var _a, _b; + return (_b = (_a = _styleEs.style.get(element, name)) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition.initialValue) !== null && _b !== void 0 ? _b : 0; + }; + /** + * Replace null values with the previous keyframe value, or read + * it from the DOM if it's the first keyframe. + */ + let keyframes = (0, _keyframesEs.hydrateKeyframes)((0, _keyframesEs.keyframesList)(keyframesDefinition), readInitialValue); + if ((0, _utils.isEasingGenerator)(easing)) { + const custom = easing.createAnimation(keyframes, readInitialValue, valueIsTransform, name, motionValue); + easing = custom.easing; + if (custom.keyframes !== undefined) keyframes = custom.keyframes; + if (custom.duration !== undefined) duration = custom.duration; + } + /** + * If this is a CSS variable we need to register it with the browser + * before it can be animated natively. We also set it with setProperty + * rather than directly onto the element.style object. + */ + if ((0, _cssVarEs.isCssVar)(name)) { + if (_featureDetectionEs.supports.cssRegisterProperty()) { + (0, _cssVarEs.registerCssVariable)(name); + } else { + canAnimateNatively = false; } - const platform = (exports.platform = { - getClippingRect, - convertOffsetParentRelativeRectToViewportRelativeRect, - isElement, - getDimensions, - getOffsetParent, - getDocumentElement, - getScale, - async getElementRects(_ref) { - let { reference, floating, strategy } = _ref; - const getOffsetParentFn = this.getOffsetParent || getOffsetParent; - const getDimensionsFn = this.getDimensions; - return { - reference: getRectRelativeToOffsetParent( - reference, - await getOffsetParentFn(floating), - strategy - ), - floating: { - x: 0, - y: 0, - ...(await getDimensionsFn(floating)), - }, - }; - }, - getClientRects: (element) => Array.from(element.getClientRects()), - isRTL: (element) => getComputedStyle$1(element).direction === "rtl", - }); - + } + /** + * If we can animate this value with WAAPI, do so. Currently this only + * feature detects CSS.registerProperty but could check WAAPI too. + */ + if (canAnimateNatively) { /** - * Automatically updates the position of the floating element when necessary. - * Should only be called when the floating element is mounted on the DOM or - * visible on the screen. - * @returns cleanup function that should be invoked when the floating element is - * removed from the DOM or hidden from the screen. - * @see https://floating-ui.com/docs/autoUpdate + * Convert numbers to default value types. Currently this only supports + * transforms but it could also support other value types. */ - function autoUpdate(reference, floating, update, options) { - if (options === void 0) { - options = {}; - } - const { - ancestorScroll = true, - ancestorResize = true, - elementResize = true, - animationFrame = false, - } = options; - const ancestors = - ancestorScroll || ancestorResize - ? [ - ...(isElement(reference) - ? getOverflowAncestors(reference) - : reference.contextElement - ? getOverflowAncestors(reference.contextElement) - : []), - ...getOverflowAncestors(floating), - ] - : []; - ancestors.forEach((ancestor) => { - // ignores Window, checks for [object VisualViewport] - const isVisualViewport = - !isElement(ancestor) && ancestor.toString().includes("V"); - if (ancestorScroll && (animationFrame ? isVisualViewport : true)) { - ancestor.addEventListener("scroll", update, { - passive: true, - }); - } - ancestorResize && ancestor.addEventListener("resize", update); - }); - let observer = null; - if (elementResize) { - observer = new ResizeObserver(() => { - update(); - }); - isElement(reference) && - !animationFrame && - observer.observe(reference); - if ( - !isElement(reference) && - reference.contextElement && - !animationFrame - ) { - observer.observe(reference.contextElement); - } - observer.observe(floating); - } - let frameId; - let prevRefRect = animationFrame - ? getBoundingClientRect(reference) - : null; - if (animationFrame) { - frameLoop(); - } - function frameLoop() { - const nextRefRect = getBoundingClientRect(reference); - if ( - prevRefRect && - (nextRefRect.x !== prevRefRect.x || - nextRefRect.y !== prevRefRect.y || - nextRefRect.width !== prevRefRect.width || - nextRefRect.height !== prevRefRect.height) - ) { - update(); - } - prevRefRect = nextRefRect; - frameId = requestAnimationFrame(frameLoop); - } - update(); - return () => { - var _observer; - ancestors.forEach((ancestor) => { - ancestorScroll && ancestor.removeEventListener("scroll", update); - ancestorResize && ancestor.removeEventListener("resize", update); - }); - (_observer = observer) == null ? void 0 : _observer.disconnect(); - observer = null; - if (animationFrame) { - cancelAnimationFrame(frameId); - } - }; + if (definition) { + keyframes = keyframes.map(value => (0, _utils.isNumber)(value) ? definition.toDefaultUnit(value) : value); } - /** - * Computes the `x` and `y` coordinates that will place the floating element - * next to a reference element when it is given a certain CSS positioning - * strategy. + * If this browser doesn't support partial/implicit keyframes we need to + * explicitly provide one. */ - const computePosition = (reference, floating, options) => { - // This caches the expensive `getClippingElementAncestors` function so that - // multiple lifecycle resets re-use the same result. It only lives for a - // single call. If other functions become expensive, we can add them as well. - const cache = new Map(); - const mergedOptions = { - platform, - ...options, - }; - const platformWithCache = { - ...mergedOptions.platform, - _c: cache, - }; - return (0, _core.computePosition)(reference, floating, { - ...mergedOptions, - platform: platformWithCache, - }); - }; - exports.computePosition = computePosition; - - /***/ - }, - - /***/ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js": - /*!**************************************************************************************!*\ - !*** ../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js ***! - \**************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.arrow = void 0; - Object.defineProperty(exports, "autoPlacement", { - enumerable: true, - get: function () { - return _dom.autoPlacement; - }, - }); - Object.defineProperty(exports, "autoUpdate", { - enumerable: true, - get: function () { - return _dom.autoUpdate; - }, - }); - Object.defineProperty(exports, "computePosition", { - enumerable: true, - get: function () { - return _dom.computePosition; - }, - }); - Object.defineProperty(exports, "detectOverflow", { - enumerable: true, - get: function () { - return _dom.detectOverflow; - }, - }); - Object.defineProperty(exports, "flip", { - enumerable: true, - get: function () { - return _dom.flip; - }, - }); - Object.defineProperty(exports, "getOverflowAncestors", { - enumerable: true, - get: function () { - return _dom.getOverflowAncestors; - }, - }); - Object.defineProperty(exports, "hide", { - enumerable: true, - get: function () { - return _dom.hide; - }, - }); - Object.defineProperty(exports, "inline", { - enumerable: true, - get: function () { - return _dom.inline; - }, - }); - Object.defineProperty(exports, "limitShift", { - enumerable: true, - get: function () { - return _dom.limitShift; - }, - }); - Object.defineProperty(exports, "offset", { - enumerable: true, - get: function () { - return _dom.offset; - }, - }); - Object.defineProperty(exports, "platform", { - enumerable: true, - get: function () { - return _dom.platform; - }, - }); - Object.defineProperty(exports, "shift", { - enumerable: true, - get: function () { - return _dom.shift; - }, - }); - Object.defineProperty(exports, "size", { - enumerable: true, - get: function () { - return _dom.size; - }, - }); - exports.useFloating = useFloating; - var _dom = __webpack_require__( - /*! @floating-ui/dom */ "../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js" - ); - var _react = _interopRequireWildcard( - __webpack_require__(/*! react */ "react") - ); - var React = _react; - var ReactDOM = _interopRequireWildcard( - __webpack_require__(/*! react-dom */ "react-dom") - ); - function _getRequireWildcardCache(e) { - if ("function" != typeof WeakMap) return null; - var r = new WeakMap(), - t = new WeakMap(); - return (_getRequireWildcardCache = function (e) { - return e ? t : r; - })(e); - } - function _interopRequireWildcard(e, r) { - if (!r && e && e.__esModule) return e; - if (null === e || ("object" != typeof e && "function" != typeof e)) - return { default: e }; - var t = _getRequireWildcardCache(r); - if (t && t.has(e)) return t.get(e); - var n = { __proto__: null }, - a = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var u in e) - if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { - var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; - i && (i.get || i.set) - ? Object.defineProperty(n, u, i) - : (n[u] = e[u]); - } - return (n.default = e), t && t.set(e, n), n; + if (keyframes.length === 1 && (!_featureDetectionEs.supports.partialKeyframes() || isRecording)) { + keyframes.unshift(readInitialValue()); } + const animationOptions = { + delay: _utils.time.ms(delay), + duration: _utils.time.ms(duration), + endDelay: _utils.time.ms(endDelay), + easing: !(0, _utils.isEasingList)(easing) ? (0, _easingEs.convertEasing)(easing) : undefined, + direction, + iterations: repeat + 1, + fill: "both" + }; + animation = element.animate({ + [name]: keyframes, + offset, + easing: (0, _utils.isEasingList)(easing) ? easing.map(_easingEs.convertEasing) : undefined + }, animationOptions); /** - * Provides data to position an inner element of the floating element so that it - * appears centered to the reference element. - * This wraps the core `arrow` middleware to allow React refs as the element. - * @see https://floating-ui.com/docs/arrow + * Polyfill finished Promise in browsers that don't support it */ - const arrow = (options) => { - function isRef(value) { - return {}.hasOwnProperty.call(value, "current"); - } - return { - name: "arrow", - options, - fn(state) { - const { element, padding } = - typeof options === "function" ? options(state) : options; - if (element && isRef(element)) { - if (element.current != null) { - return (0, _dom.arrow)({ - element: element.current, - padding, - }).fn(state); - } - return {}; - } else if (element) { - return (0, _dom.arrow)({ - element, - padding, - }).fn(state); - } - return {}; - }, - }; - }; - exports.arrow = arrow; - var index = - typeof document !== "undefined" - ? _react.useLayoutEffect - : _react.useEffect; - - // Fork of `fast-deep-equal` that only does the comparisons we need and compares - // functions - function deepEqual(a, b) { - if (a === b) { - return true; - } - if (typeof a !== typeof b) { - return false; - } - if (typeof a === "function" && a.toString() === b.toString()) { - return true; - } - let length, i, keys; - if (a && b && typeof a == "object") { - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) { - if (!deepEqual(a[i], b[i])) { - return false; - } - } - return true; - } - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) { - return false; - } - for (i = length; i-- !== 0; ) { - if (!{}.hasOwnProperty.call(b, keys[i])) { - return false; - } - } - for (i = length; i-- !== 0; ) { - const key = keys[i]; - if (key === "_owner" && a.$$typeof) { - continue; - } - if (!deepEqual(a[key], b[key])) { - return false; - } - } - return true; - } - return a !== a && b !== b; - } - function getDPR(element) { - if (typeof window === "undefined") { - return 1; - } - const win = element.ownerDocument.defaultView || window; - return win.devicePixelRatio || 1; - } - function roundByDPR(element, value) { - const dpr = getDPR(element); - return Math.round(value * dpr) / dpr; - } - function useLatestRef(value) { - const ref = React.useRef(value); - index(() => { - ref.current = value; + if (!animation.finished) { + animation.finished = new Promise((resolve, reject) => { + animation.onfinish = resolve; + animation.oncancel = reject; }); - return ref; } - + const target = keyframes[keyframes.length - 1]; + animation.finished.then(() => { + // Apply styles to target + _styleEs.style.set(element, name, target); + // Ensure fill modes don't persist + animation.cancel(); + }).catch(_utils.noop); /** - * Provides data to position a floating element. - * @see https://floating-ui.com/docs/react + * This forces Webkit to run animations on the main thread by exploiting + * this condition: + * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099 + * + * This fixes Webkit's timing bugs, like accelerated animations falling + * out of sync with main thread animations and massive delays in starting + * accelerated animations in WKWebView. */ - function useFloating(options) { - if (options === void 0) { - options = {}; - } - const { - placement = "bottom", - strategy = "absolute", - middleware = [], - platform, - elements: { - reference: externalReference, - floating: externalFloating, - } = {}, - transform = true, - whileElementsMounted, - open, - } = options; - const [data, setData] = React.useState({ - x: 0, - y: 0, - strategy, - placement, - middlewareData: {}, - isPositioned: false, - }); - const [latestMiddleware, setLatestMiddleware] = - React.useState(middleware); - if (!deepEqual(latestMiddleware, middleware)) { - setLatestMiddleware(middleware); - } - const [_reference, _setReference] = React.useState(null); - const [_floating, _setFloating] = React.useState(null); - const setReference = React.useCallback( - (node) => { - if (node != referenceRef.current) { - referenceRef.current = node; - _setReference(node); - } - }, - [_setReference] - ); - const setFloating = React.useCallback( - (node) => { - if (node !== floatingRef.current) { - floatingRef.current = node; - _setFloating(node); - } - }, - [_setFloating] - ); - const referenceEl = externalReference || _reference; - const floatingEl = externalFloating || _floating; - const referenceRef = React.useRef(null); - const floatingRef = React.useRef(null); - const dataRef = React.useRef(data); - const whileElementsMountedRef = useLatestRef(whileElementsMounted); - const platformRef = useLatestRef(platform); - const update = React.useCallback(() => { - if (!referenceRef.current || !floatingRef.current) { - return; - } - const config = { - placement, - strategy, - middleware: latestMiddleware, - }; - if (platformRef.current) { - config.platform = platformRef.current; - } - (0, _dom.computePosition)( - referenceRef.current, - floatingRef.current, - config - ).then((data) => { - const fullData = { - ...data, - isPositioned: true, - }; - if ( - isMountedRef.current && - !deepEqual(dataRef.current, fullData) - ) { - dataRef.current = fullData; - ReactDOM.flushSync(() => { - setData(fullData); - }); - } - }); - }, [latestMiddleware, placement, strategy, platformRef]); - index(() => { - if (open === false && dataRef.current.isPositioned) { - dataRef.current.isPositioned = false; - setData((data) => ({ - ...data, - isPositioned: false, - })); - } - }, [open]); - const isMountedRef = React.useRef(false); - index(() => { - isMountedRef.current = true; - return () => { - isMountedRef.current = false; - }; - }, []); - index(() => { - if (referenceEl) referenceRef.current = referenceEl; - if (floatingEl) floatingRef.current = floatingEl; - if (referenceEl && floatingEl) { - if (whileElementsMountedRef.current) { - return whileElementsMountedRef.current( - referenceEl, - floatingEl, - update - ); - } else { - update(); - } - } - }, [referenceEl, floatingEl, update, whileElementsMountedRef]); - const refs = React.useMemo( - () => ({ - reference: referenceRef, - floating: floatingRef, - setReference, - setFloating, - }), - [setReference, setFloating] - ); - const elements = React.useMemo( - () => ({ - reference: referenceEl, - floating: floatingEl, - }), - [referenceEl, floatingEl] - ); - const floatingStyles = React.useMemo(() => { - const initialStyles = { - position: strategy, - left: 0, - top: 0, - }; - if (!elements.floating) { - return initialStyles; - } - const x = roundByDPR(elements.floating, data.x); - const y = roundByDPR(elements.floating, data.y); - if (transform) { - return { - ...initialStyles, - transform: "translate(" + x + "px, " + y + "px)", - ...(getDPR(elements.floating) >= 1.5 && { - willChange: "transform", - }), - }; - } - return { - position: strategy, - left: x, - top: y, - }; - }, [strategy, transform, elements.floating, data.x, data.y]); - return React.useMemo( - () => ({ - ...data, - update, - refs, - elements, - floatingStyles, - }), - [data, update, refs, elements, floatingStyles] - ); + if (!allowWebkitAcceleration) animation.playbackRate = 1.000001; + /** + * If we can't animate the value natively then we can fallback to the numbers-only + * polyfill for transforms. + */ + } else if (valueIsTransform) { + /** + * If any keyframe is a string (because we measured it from the DOM), we need to convert + * it into a number before passing to the Animation polyfill. + */ + keyframes = keyframes.map(value => typeof value === "string" ? parseFloat(value) : value); + /** + * If we only have a single keyframe, we need to create an initial keyframe by reading + * the current value from the DOM. + */ + if (keyframes.length === 1) { + keyframes.unshift(parseFloat(readInitialValue())); } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/animation/dist/Animation.es.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/Animation.es.js ***! - \***********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, + const render = latest => { + if (definition) latest = definition.toDefaultUnit(latest); + _styleEs.style.set(element, name, latest); + }; + animation = new _animation.Animation(render, keyframes, Object.assign(Object.assign({}, options), { + duration, + easing + })); + } else { + const target = keyframes[keyframes.length - 1]; + _styleEs.style.set(element, name, definition && (0, _utils.isNumber)(target) ? definition.toDefaultUnit(target) : target); + } + if (isRecording) { + record(element, key, keyframes, { + duration, + delay: delay, + easing, + repeat, + offset + }, "motion-one"); + } + motionValue.setAnimation(animation); + return animation; + }; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/data.es.js": + /*!********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/data.es.js ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getAnimationData = getAnimationData; + exports.getMotionValue = getMotionValue; + var _types = __webpack_require__(/*! @motionone/types */ "../../../node_modules/@motionone/types/dist/index.es.js"); + const data = new WeakMap(); + function getAnimationData(element) { + if (!data.has(element)) { + data.set(element, { + transforms: [], + values: new Map() + }); + } + return data.get(element); + } + function getMotionValue(motionValues, name) { + if (!motionValues.has(name)) { + motionValues.set(name, new _types.MotionValue()); + } + return motionValues.get(name); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/index.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/index.es.js ***! + \*********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.animate = animate; + var _animateStyleEs = __webpack_require__(/*! ./animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); + var _optionsEs = __webpack_require__(/*! ./utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); + var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); + var _controlsEs = __webpack_require__(/*! ./utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); + var _staggerEs = __webpack_require__(/*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); + function animate(elements, keyframes, options = {}) { + elements = (0, _resolveElementsEs.resolveElements)(elements); + const numElements = elements.length; + /** + * Create and start new animations + */ + const animationFactories = []; + for (let i = 0; i < numElements; i++) { + const element = elements[i]; + for (const key in keyframes) { + const valueOptions = (0, _optionsEs.getOptions)(options, key); + valueOptions.delay = (0, _staggerEs.resolveOption)(valueOptions.delay, i, numElements); + const animation = (0, _animateStyleEs.animateStyle)(element, key, keyframes[key], valueOptions); + animationFactories.push(animation); + } + } + return (0, _controlsEs.withControls)(animationFactories, options, + /** + * TODO: + * If easing is set to spring or glide, duration will be dynamically + * generated. Ideally we would dynamically generate this from + * animation.effect.getComputedTiming().duration but this isn't + * supported in iOS13 or our number polyfill. Perhaps it's possible + * to Proxy animations returned from animateStyle that has duration + * as a getter. + */ + options.duration); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/style.es.js": + /*!*********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/style.es.js ***! + \*********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.style = void 0; + var _cssVarEs = __webpack_require__(/*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js"); + var _getStyleNameEs = __webpack_require__(/*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); + var _transformsEs = __webpack_require__(/*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); + const style = exports.style = { + get: (element, name) => { + name = (0, _getStyleNameEs.getStyleName)(name); + let value = (0, _cssVarEs.isCssVar)(name) ? element.style.getPropertyValue(name) : getComputedStyle(element)[name]; + if (!value && value !== 0) { + const definition = _transformsEs.transformDefinitions.get(name); + if (definition) value = definition.initialValue; + } + return value; + }, + set: (element, name, value) => { + name = (0, _getStyleNameEs.getStyleName)(name); + if ((0, _cssVarEs.isCssVar)(name)) { + element.style.setProperty(name, value); + } else { + element.style[name] = value; + } + } + }; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.withControls = exports.controls = void 0; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _stopAnimationEs = __webpack_require__(/*! ./stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js"); + const createAnimation = factory => factory(); + const withControls = (animationFactory, options, duration = _utils.defaults.duration) => { + return new Proxy({ + animations: animationFactory.map(createAnimation).filter(Boolean), + duration, + options + }, controls); + }; + /** + * TODO: + * Currently this returns the first animation, ideally it would return + * the first active animation. + */ + exports.withControls = withControls; + const getActiveAnimation = state => state.animations[0]; + const controls = exports.controls = { + get: (target, key) => { + const activeAnimation = getActiveAnimation(target); + switch (key) { + case "duration": + return target.duration; + case "currentTime": + return _utils.time.s((activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) || 0); + case "playbackRate": + case "playState": + return activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]; + case "finished": + if (!target.finished) { + target.finished = Promise.all(target.animations.map(selectFinished)).catch(_utils.noop); + } + return target.finished; + case "stop": + return () => { + target.animations.forEach(animation => (0, _stopAnimationEs.stopAnimation)(animation)); + }; + case "forEachNative": + /** + * This is for internal use only, fire a callback for each + * underlying animation. + */ + return callback => { + target.animations.forEach(animation => callback(animation, target)); + }; + default: + return typeof (activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) === "undefined" ? undefined : () => target.animations.forEach(animation => animation[key]()); + } + }, + set: (target, key, value) => { + switch (key) { + case "currentTime": + value = _utils.time.ms(value); + case "currentTime": + case "playbackRate": + for (let i = 0; i < target.animations.length; i++) { + target.animations[i][key] = value; + } + return true; + } + return false; + } + }; + const selectFinished = animation => animation.finished; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isCssVar = void 0; + exports.registerCssVariable = registerCssVariable; + exports.registeredProperties = void 0; + var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); + const isCssVar = name => name.startsWith("--"); + exports.isCssVar = isCssVar; + const registeredProperties = exports.registeredProperties = new Set(); + function registerCssVariable(name) { + if (registeredProperties.has(name)) return; + registeredProperties.add(name); + try { + const { + syntax, + initialValue + } = _transformsEs.transformDefinitions.has(name) ? _transformsEs.transformDefinitions.get(name) : {}; + CSS.registerProperty({ + name, + inherits: false, + syntax, + initialValue + }); + } catch (e) {} + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.cubicBezierAsString = exports.convertEasing = void 0; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + const convertEasing = easing => (0, _utils.isCubicBezier)(easing) ? cubicBezierAsString(easing) : easing; + exports.convertEasing = convertEasing; + const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`; + exports.cubicBezierAsString = cubicBezierAsString; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js": + /*!***************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js ***! + \***************************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.supports = void 0; + const testAnimation = keyframes => document.createElement("div").animate(keyframes, { + duration: 0.001 + }); + const featureTests = { + cssRegisterProperty: () => typeof CSS !== "undefined" && Object.hasOwnProperty.call(CSS, "registerProperty"), + waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"), + partialKeyframes: () => { + try { + testAnimation({ + opacity: [1] }); - exports.Animation = void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _easingEs = __webpack_require__( - /*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js" - ); - class Animation { - constructor( - output, - keyframes = [0, 1], - { - easing, - duration: initialDuration = _utils.defaults.duration, - delay = _utils.defaults.delay, - endDelay = _utils.defaults.endDelay, - repeat = _utils.defaults.repeat, - offset, - direction = "normal", - } = {} - ) { - this.startTime = null; - this.rate = 1; - this.t = 0; - this.cancelTimestamp = null; - this.easing = _utils.noopReturn; - this.duration = 0; - this.totalDuration = 0; - this.repeat = 0; - this.playState = "idle"; - this.finished = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - easing = easing || _utils.defaults.easing; - if ((0, _utils.isEasingGenerator)(easing)) { - const custom = easing.createAnimation(keyframes); - easing = custom.easing; - keyframes = custom.keyframes || keyframes; - initialDuration = custom.duration || initialDuration; - } - this.repeat = repeat; - this.easing = (0, _utils.isEasingList)(easing) - ? _utils.noopReturn - : (0, _easingEs.getEasingFunction)(easing); - this.updateDuration(initialDuration); - const interpolate$1 = (0, _utils.interpolate)( - keyframes, - offset, - (0, _utils.isEasingList)(easing) - ? easing.map(_easingEs.getEasingFunction) - : _utils.noopReturn - ); - this.tick = (timestamp) => { - var _a; - // TODO: Temporary fix for OptionsResolver typing - delay = delay; - let t = 0; - if (this.pauseTime !== undefined) { - t = this.pauseTime; - } else { - t = (timestamp - this.startTime) * this.rate; - } - this.t = t; - // Convert to seconds - t /= 1000; - // Rebase on delay - t = Math.max(t - delay, 0); - /** - * If this animation has finished, set the current time - * to the total duration. - */ - if ( - this.playState === "finished" && - this.pauseTime === undefined - ) { - t = this.totalDuration; - } - /** - * Get the current progress (0-1) of the animation. If t is > - * than duration we'll get values like 2.5 (midway through the - * third iteration) - */ - const progress = t / this.duration; - // TODO progress += iterationStart - /** - * Get the current iteration (0 indexed). For instance the floor of - * 2.5 is 2. - */ - let currentIteration = Math.floor(progress); - /** - * Get the current progress of the iteration by taking the remainder - * so 2.5 is 0.5 through iteration 2 - */ - let iterationProgress = progress % 1.0; - if (!iterationProgress && progress >= 1) { - iterationProgress = 1; - } - /** - * If iteration progress is 1 we count that as the end - * of the previous iteration. - */ - iterationProgress === 1 && currentIteration--; + } catch (e) { + return false; + } + return true; + }, + finished: () => Boolean(testAnimation({ + opacity: [0, 1] + }).finished) + }; + const results = {}; + const supports = exports.supports = {}; + for (const key in featureTests) { + supports[key] = () => { + if (results[key] === undefined) results[key] = featureTests[key](); + return results[key]; + }; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js": + /*!************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js ***! + \************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getStyleName = getStyleName; + var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); + function getStyleName(key) { + if (_transformsEs.transformAlias[key]) key = _transformsEs.transformAlias[key]; + return (0, _transformsEs.isTransform)(key) ? (0, _transformsEs.asTransformCssVar)(key) : key; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js": + /*!*******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js ***! + \*******************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.hydrateKeyframes = hydrateKeyframes; + exports.keyframesList = void 0; + function hydrateKeyframes(keyframes, readInitialValue) { + for (let i = 0; i < keyframes.length; i++) { + if (keyframes[i] === null) { + keyframes[i] = i ? keyframes[i - 1] : readInitialValue(); + } + } + return keyframes; + } + const keyframesList = keyframes => Array.isArray(keyframes) ? keyframes : [keyframes]; + exports.keyframesList = keyframesList; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getOptions = void 0; + const getOptions = (options, key) => + /** + * TODO: Make test for this + * Always return a new object otherwise delay is overwritten by results of stagger + * and this results in no stagger + */ + options[key] ? Object.assign(Object.assign({}, options), options[key]) : Object.assign({}, options); + exports.getOptions = getOptions; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js": + /*!************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js ***! + \************************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.stopAnimation = stopAnimation; + function stopAnimation(animation, needsCommit = true) { + if (!animation || animation.playState === "finished") return; + // Suppress error thrown by WAAPI + try { + if (animation.stop) { + animation.stop(); + } else { + needsCommit && animation.commitStyles(); + animation.cancel(); + } + } catch (e) {} + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createStyles = createStyles; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _transformsEs = __webpack_require__(/*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); + function createStyles(keyframes) { + const initialKeyframes = {}; + const transformKeys = []; + for (let key in keyframes) { + const value = keyframes[key]; + if ((0, _transformsEs.isTransform)(key)) { + if (_transformsEs.transformAlias[key]) key = _transformsEs.transformAlias[key]; + transformKeys.push(key); + key = (0, _transformsEs.asTransformCssVar)(key); + } + let initialKeyframe = Array.isArray(value) ? value[0] : value; + /** + * If this is a number and we have a default value type, convert the number + * to this type. + */ + const definition = _transformsEs.transformDefinitions.get(key); + if (definition) { + initialKeyframe = (0, _utils.isNumber)(value) ? definition.toDefaultUnit(value) : value; + } + initialKeyframes[key] = initialKeyframe; + } + if (transformKeys.length) { + initialKeyframes.transform = (0, _transformsEs.buildTransformTemplate)(transformKeys); + } + return initialKeyframes; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createStyleString = createStyleString; + var _styleObjectEs = __webpack_require__(/*! ./style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js"); + const camelLetterToPipeLetter = letter => `-${letter.toLowerCase()}`; + const camelToPipeCase = str => str.replace(/[A-Z]/g, camelLetterToPipeLetter); + function createStyleString(target = {}) { + const styles = (0, _styleObjectEs.createStyles)(target); + let style = ""; + for (const key in styles) { + style += key.startsWith("--") ? key : camelToPipeCase(key); + style += `: ${styles[key]}; `; + } + return style; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js": + /*!********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js ***! + \********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.transformDefinitions = exports.transformAlias = exports.isTransform = exports.compareTransformOrder = exports.buildTransformTemplate = exports.axes = exports.asTransformCssVar = exports.addTransformToElement = void 0; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _dataEs = __webpack_require__(/*! ../data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); + /** + * A list of all transformable axes. We'll use this list to generated a version + * of each axes for each transform. + */ + const axes = exports.axes = ["", "X", "Y", "Z"]; + /** + * An ordered array of each transformable value. By default, transform values + * will be sorted to this order. + */ + const order = ["translate", "scale", "rotate", "skew"]; + const transformAlias = exports.transformAlias = { + x: "translateX", + y: "translateY", + z: "translateZ" + }; + const rotation = { + syntax: "", + initialValue: "0deg", + toDefaultUnit: v => v + "deg" + }; + const baseTransformProperties = { + translate: { + syntax: "", + initialValue: "0px", + toDefaultUnit: v => v + "px" + }, + rotate: rotation, + scale: { + syntax: "", + initialValue: 1, + toDefaultUnit: _utils.noopReturn + }, + skew: rotation + }; + const transformDefinitions = exports.transformDefinitions = new Map(); + const asTransformCssVar = name => `--motion-${name}`; + /** + * Generate a list of every possible transform key + */ + exports.asTransformCssVar = asTransformCssVar; + const transforms = ["x", "y", "z"]; + order.forEach(name => { + axes.forEach(axis => { + transforms.push(name + axis); + transformDefinitions.set(asTransformCssVar(name + axis), baseTransformProperties[name]); + }); + }); + /** + * A function to use with Array.sort to sort transform keys by their default order. + */ + const compareTransformOrder = (a, b) => transforms.indexOf(a) - transforms.indexOf(b); + /** + * Provide a quick way to check if a string is the name of a transform + */ + exports.compareTransformOrder = compareTransformOrder; + const transformLookup = new Set(transforms); + const isTransform = name => transformLookup.has(name); + exports.isTransform = isTransform; + const addTransformToElement = (element, name) => { + // Map x to translateX etc + if (transformAlias[name]) name = transformAlias[name]; + const { + transforms + } = (0, _dataEs.getAnimationData)(element); + (0, _utils.addUniqueItem)(transforms, name); + /** + * TODO: An optimisation here could be to cache the transform in element data + * and only update if this has changed. + */ + element.style.transform = buildTransformTemplate(transforms); + }; + exports.addTransformToElement = addTransformToElement; + const buildTransformTemplate = transforms => transforms.sort(compareTransformOrder).reduce(transformListToString, "").trim(); + exports.buildTransformTemplate = buildTransformTemplate; + const transformListToString = (template, name) => `${template} ${name}(var(${asTransformCssVar(name)}))`; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js ***! + \**************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createGeneratorEasing = createGeneratorEasing; + var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); + function createGeneratorEasing(createGenerator) { + const keyframesCache = new WeakMap(); + return (options = {}) => { + const generatorCache = new Map(); + const getGenerator = (from = 0, to = 100, velocity = 0, isScale = false) => { + const key = `${from}-${to}-${velocity}-${isScale}`; + if (!generatorCache.has(key)) { + generatorCache.set(key, createGenerator(Object.assign({ + from, + to, + velocity, + restSpeed: isScale ? 0.05 : 2, + restDistance: isScale ? 0.01 : 0.5 + }, options))); + } + return generatorCache.get(key); + }; + const getKeyframes = generator => { + if (!keyframesCache.has(generator)) { + keyframesCache.set(generator, (0, _generators.pregenerateKeyframes)(generator)); + } + return keyframesCache.get(generator); + }; + return { + createAnimation: (keyframes, getOrigin, canUseGenerator, name, motionValue) => { + var _a, _b; + let settings; + const numKeyframes = keyframes.length; + let shouldUseGenerator = canUseGenerator && numKeyframes <= 2 && keyframes.every(isNumberOrNull); + if (shouldUseGenerator) { + const target = keyframes[numKeyframes - 1]; + const unresolvedOrigin = numKeyframes === 1 ? null : keyframes[0]; + let velocity = 0; + let origin = 0; + const prevGenerator = motionValue === null || motionValue === void 0 ? void 0 : motionValue.generator; + if (prevGenerator) { /** - * Reverse progress if we're not running in "normal" direction + * If we have a generator for this value we can use it to resolve + * the animations's current value and velocity. */ - const iterationIsOdd = currentIteration % 2; - if ( - direction === "reverse" || - (direction === "alternate" && iterationIsOdd) || - (direction === "alternate-reverse" && !iterationIsOdd) - ) { - iterationProgress = 1 - iterationProgress; - } - const p = - t >= this.totalDuration ? 1 : Math.min(iterationProgress, 1); - const latest = interpolate$1(this.easing(p)); - output(latest); - const isAnimationFinished = - this.pauseTime === undefined && - (this.playState === "finished" || - t >= this.totalDuration + endDelay); - if (isAnimationFinished) { - this.playState = "finished"; - (_a = this.resolve) === null || _a === void 0 - ? void 0 - : _a.call(this, latest); - } else if (this.playState !== "idle") { - this.frameRequestId = requestAnimationFrame(this.tick); + const { + animation, + generatorStartTime + } = motionValue; + const startTime = (animation === null || animation === void 0 ? void 0 : animation.startTime) || generatorStartTime || 0; + const currentTime = (animation === null || animation === void 0 ? void 0 : animation.currentTime) || performance.now() - startTime; + const prevGeneratorCurrent = prevGenerator(currentTime).current; + origin = (_a = unresolvedOrigin) !== null && _a !== void 0 ? _a : prevGeneratorCurrent; + if (numKeyframes === 1 || numKeyframes === 2 && keyframes[0] === null) { + velocity = (0, _generators.calcGeneratorVelocity)(t => prevGenerator(t).current, currentTime, prevGeneratorCurrent); } - }; - this.play(); - } - play() { - const now = performance.now(); - this.playState = "running"; - if (this.pauseTime !== undefined) { - this.startTime = now - this.pauseTime; - } else if (!this.startTime) { - this.startTime = now; - } - this.cancelTimestamp = this.startTime; - this.pauseTime = undefined; - this.frameRequestId = requestAnimationFrame(this.tick); - } - pause() { - this.playState = "paused"; - this.pauseTime = this.t; - } - finish() { - this.playState = "finished"; - this.tick(0); - } - stop() { - var _a; - this.playState = "idle"; - if (this.frameRequestId !== undefined) { - cancelAnimationFrame(this.frameRequestId); - } - (_a = this.reject) === null || _a === void 0 - ? void 0 - : _a.call(this, false); - } - cancel() { - this.stop(); - this.tick(this.cancelTimestamp); - } - reverse() { - this.rate *= -1; - } - commitStyles() {} - updateDuration(duration) { - this.duration = duration; - this.totalDuration = duration * (this.repeat + 1); - } - get currentTime() { - return this.t; - } - set currentTime(t) { - if (this.pauseTime !== undefined || this.rate === 0) { - this.pauseTime = t; } else { - this.startTime = performance.now() - t / this.rate; + origin = (_b = unresolvedOrigin) !== null && _b !== void 0 ? _b : parseFloat(getOrigin()); } - } - get playbackRate() { - return this.rate; - } - set playbackRate(rate) { - this.rate = rate; - } - } - exports.Animation = Animation; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/animation/dist/index.es.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/index.es.js ***! - \*******************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "Animation", { - enumerable: true, - get: function () { - return _AnimationEs.Animation; - }, - }); - Object.defineProperty(exports, "getEasingFunction", { - enumerable: true, - get: function () { - return _easingEs.getEasingFunction; - }, - }); - var _AnimationEs = __webpack_require__( - /*! ./Animation.es.js */ "../../../node_modules/@motionone/animation/dist/Animation.es.js" - ); - var _easingEs = __webpack_require__( - /*! ./utils/easing.es.js */ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js" - ); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/animation/dist/utils/easing.es.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/animation/dist/utils/easing.es.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getEasingFunction = getEasingFunction; - var _easing = __webpack_require__( - /*! @motionone/easing */ "../../../node_modules/@motionone/easing/dist/index.es.js" - ); - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - const namedEasings = { - ease: (0, _easing.cubicBezier)(0.25, 0.1, 0.25, 1.0), - "ease-in": (0, _easing.cubicBezier)(0.42, 0.0, 1.0, 1.0), - "ease-in-out": (0, _easing.cubicBezier)(0.42, 0.0, 0.58, 1.0), - "ease-out": (0, _easing.cubicBezier)(0.0, 0.0, 0.58, 1.0), - }; - const functionArgsRegex = /\((.*?)\)/; - function getEasingFunction(definition) { - // If already an easing function, return - if ((0, _utils.isFunction)(definition)) return definition; - // If an easing curve definition, return bezier function - if ((0, _utils.isCubicBezier)(definition)) - return (0, _easing.cubicBezier)(...definition); - // If we have a predefined easing function, return - if (namedEasings[definition]) return namedEasings[definition]; - // If this is a steps function, attempt to create easing curve - if (definition.startsWith("steps")) { - const args = functionArgsRegex.exec(definition); - if (args) { - const argsArray = args[1].split(","); - return (0, _easing.steps)( - parseFloat(argsArray[0]), - argsArray[1].trim() - ); + const generator = getGenerator(origin, target, velocity, name === null || name === void 0 ? void 0 : name.includes("scale")); + const keyframesMetadata = getKeyframes(generator); + settings = Object.assign(Object.assign({}, keyframesMetadata), { + easing: "linear" + }); + // TODO Add test for this + if (motionValue) { + motionValue.generator = generator; + motionValue.generatorStartTime = performance.now(); } + } else { + const keyframesMetadata = getKeyframes(getGenerator(0, 100)); + settings = { + easing: "ease", + duration: keyframesMetadata.overshootDuration + }; } - return _utils.noopReturn; + return settings; } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.animateStyle = animateStyle; - var _dataEs = __webpack_require__( - /*! ./data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js" - ); - var _cssVarEs = __webpack_require__( - /*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js" - ); - var _animation = __webpack_require__( - /*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js" - ); - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _transformsEs = __webpack_require__( - /*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" - ); - var _easingEs = __webpack_require__( - /*! ./utils/easing.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js" - ); - var _featureDetectionEs = __webpack_require__( - /*! ./utils/feature-detection.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js" - ); - var _keyframesEs = __webpack_require__( - /*! ./utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js" - ); - var _styleEs = __webpack_require__( - /*! ./style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js" - ); - var _getStyleNameEs = __webpack_require__( - /*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js" - ); - var _stopAnimationEs = __webpack_require__( - /*! ./utils/stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js" - ); - function getDevToolsRecord() { - return window.__MOTION_DEV_TOOLS_RECORD; - } - function animateStyle(element, key, keyframesDefinition, options = {}) { - const record = getDevToolsRecord(); - const isRecording = options.record !== false && record; - let animation; - let { - duration = _utils.defaults.duration, - delay = _utils.defaults.delay, - endDelay = _utils.defaults.endDelay, - repeat = _utils.defaults.repeat, - easing = _utils.defaults.easing, - direction, - offset, - allowWebkitAcceleration = false, - } = options; - const data = (0, _dataEs.getAnimationData)(element); - let canAnimateNatively = _featureDetectionEs.supports.waapi(); - const valueIsTransform = (0, _transformsEs.isTransform)(key); - /** - * If this is an individual transform, we need to map its - * key to a CSS variable and update the element's transform style - */ - valueIsTransform && - (0, _transformsEs.addTransformToElement)(element, key); - const name = (0, _getStyleNameEs.getStyleName)(key); - const motionValue = (0, _dataEs.getMotionValue)(data.values, name); - /** - * Get definition of value, this will be used to convert numerical - * keyframes into the default value type. - */ - const definition = _transformsEs.transformDefinitions.get(name); - /** - * Stop the current animation, if any. Because this will trigger - * commitStyles (DOM writes) and we might later trigger DOM reads, - * this is fired now and we return a factory function to create - * the actual animation that can get called in batch, - */ - (0, _stopAnimationEs.stopAnimation)( - motionValue.animation, - !((0, _utils.isEasingGenerator)(easing) && motionValue.generator) && - options.record !== false - ); - /** - * Batchable factory function containing all DOM reads. - */ - return () => { - const readInitialValue = () => { - var _a, _b; - return (_b = - (_a = _styleEs.style.get(element, name)) !== null && - _a !== void 0 - ? _a - : definition === null || definition === void 0 - ? void 0 - : definition.initialValue) !== null && _b !== void 0 - ? _b - : 0; - }; - /** - * Replace null values with the previous keyframe value, or read - * it from the DOM if it's the first keyframe. - */ - let keyframes = (0, _keyframesEs.hydrateKeyframes)( - (0, _keyframesEs.keyframesList)(keyframesDefinition), - readInitialValue - ); - if ((0, _utils.isEasingGenerator)(easing)) { - const custom = easing.createAnimation( - keyframes, - readInitialValue, - valueIsTransform, - name, - motionValue - ); - easing = custom.easing; - if (custom.keyframes !== undefined) keyframes = custom.keyframes; - if (custom.duration !== undefined) duration = custom.duration; - } - /** - * If this is a CSS variable we need to register it with the browser - * before it can be animated natively. We also set it with setProperty - * rather than directly onto the element.style object. - */ - if ((0, _cssVarEs.isCssVar)(name)) { - if (_featureDetectionEs.supports.cssRegisterProperty()) { - (0, _cssVarEs.registerCssVariable)(name); - } else { - canAnimateNatively = false; - } - } - /** - * If we can animate this value with WAAPI, do so. Currently this only - * feature detects CSS.registerProperty but could check WAAPI too. - */ - if (canAnimateNatively) { - /** - * Convert numbers to default value types. Currently this only supports - * transforms but it could also support other value types. - */ - if (definition) { - keyframes = keyframes.map((value) => - (0, _utils.isNumber)(value) - ? definition.toDefaultUnit(value) - : value - ); - } - /** - * If this browser doesn't support partial/implicit keyframes we need to - * explicitly provide one. - */ - if ( - keyframes.length === 1 && - (!_featureDetectionEs.supports.partialKeyframes() || - isRecording) - ) { - keyframes.unshift(readInitialValue()); - } - const animationOptions = { - delay: _utils.time.ms(delay), - duration: _utils.time.ms(duration), - endDelay: _utils.time.ms(endDelay), - easing: !(0, _utils.isEasingList)(easing) - ? (0, _easingEs.convertEasing)(easing) - : undefined, - direction, - iterations: repeat + 1, - fill: "both", - }; - animation = element.animate( - { - [name]: keyframes, - offset, - easing: (0, _utils.isEasingList)(easing) - ? easing.map(_easingEs.convertEasing) - : undefined, - }, - animationOptions - ); - /** - * Polyfill finished Promise in browsers that don't support it - */ - if (!animation.finished) { - animation.finished = new Promise((resolve, reject) => { - animation.onfinish = resolve; - animation.oncancel = reject; - }); - } - const target = keyframes[keyframes.length - 1]; - animation.finished - .then(() => { - // Apply styles to target - _styleEs.style.set(element, name, target); - // Ensure fill modes don't persist - animation.cancel(); - }) - .catch(_utils.noop); - /** - * This forces Webkit to run animations on the main thread by exploiting - * this condition: - * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099 - * - * This fixes Webkit's timing bugs, like accelerated animations falling - * out of sync with main thread animations and massive delays in starting - * accelerated animations in WKWebView. - */ - if (!allowWebkitAcceleration) animation.playbackRate = 1.000001; - /** - * If we can't animate the value natively then we can fallback to the numbers-only - * polyfill for transforms. - */ - } else if (valueIsTransform) { - /** - * If any keyframe is a string (because we measured it from the DOM), we need to convert - * it into a number before passing to the Animation polyfill. - */ - keyframes = keyframes.map((value) => - typeof value === "string" ? parseFloat(value) : value - ); - /** - * If we only have a single keyframe, we need to create an initial keyframe by reading - * the current value from the DOM. - */ - if (keyframes.length === 1) { - keyframes.unshift(parseFloat(readInitialValue())); - } - const render = (latest) => { - if (definition) latest = definition.toDefaultUnit(latest); - _styleEs.style.set(element, name, latest); - }; - animation = new _animation.Animation( - render, - keyframes, - Object.assign(Object.assign({}, options), { - duration, - easing, - }) - ); - } else { - const target = keyframes[keyframes.length - 1]; - _styleEs.style.set( - element, - name, - definition && (0, _utils.isNumber)(target) - ? definition.toDefaultUnit(target) - : target - ); - } - if (isRecording) { - record( - element, - key, - keyframes, - { - duration, - delay: delay, - easing, - repeat, - offset, - }, - "motion-one" - ); - } - motionValue.setAnimation(animation); - return animation; - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/data.es.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/data.es.js ***! - \********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getAnimationData = getAnimationData; - exports.getMotionValue = getMotionValue; - var _types = __webpack_require__( - /*! @motionone/types */ "../../../node_modules/@motionone/types/dist/index.es.js" - ); - const data = new WeakMap(); - function getAnimationData(element) { - if (!data.has(element)) { - data.set(element, { - transforms: [], - values: new Map(), - }); + }; + }; + } + const isNumberOrNull = value => typeof value !== "string"; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.glide = void 0; + var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); + var _createGeneratorEasingEs = __webpack_require__(/*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js"); + const glide = exports.glide = (0, _createGeneratorEasingEs.createGeneratorEasing)(_generators.glide); + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.spring = void 0; + var _generators = __webpack_require__(/*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js"); + var _createGeneratorEasingEs = __webpack_require__(/*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js"); + const spring = exports.spring = (0, _createGeneratorEasingEs.createGeneratorEasing)(_generators.spring); + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.inView = inView; + var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); + const thresholds = { + any: 0, + all: 1 + }; + function inView(elementOrSelector, onStart, { + root, + margin: rootMargin, + amount = "any" + } = {}) { + /** + * If this browser doesn't support IntersectionObserver, return a dummy stop function. + * Default triggering of onStart is tricky - it could be used for starting/stopping + * videos, lazy loading content etc. We could provide an option to enable a fallback, or + * provide a fallback callback option. + */ + if (typeof IntersectionObserver === "undefined") { + return () => {}; + } + const elements = (0, _resolveElementsEs.resolveElements)(elementOrSelector); + const activeIntersections = new WeakMap(); + const onIntersectionChange = entries => { + entries.forEach(entry => { + const onEnd = activeIntersections.get(entry.target); + /** + * If there's no change to the intersection, we don't need to + * do anything here. + */ + if (entry.isIntersecting === Boolean(onEnd)) return; + if (entry.isIntersecting) { + const newOnEnd = onStart(entry); + if (typeof newOnEnd === "function") { + activeIntersections.set(entry.target, newOnEnd); + } else { + observer.unobserve(entry.target); } - return data.get(element); + } else if (onEnd) { + onEnd(entry); + activeIntersections.delete(entry.target); } - function getMotionValue(motionValues, name) { - if (!motionValues.has(name)) { - motionValues.set(name, new _types.MotionValue()); - } - return motionValues.get(name); + }); + }; + const observer = new IntersectionObserver(onIntersectionChange, { + root, + rootMargin, + threshold: typeof amount === "number" ? amount : thresholds[amount] + }); + elements.forEach(element => observer.observe(element)); + return () => observer.disconnect(); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js ***! + \**************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.resizeElement = resizeElement; + var _resolveElementsEs = __webpack_require__(/*! ../../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); + const resizeHandlers = new WeakMap(); + let observer; + function getElementSize(target, borderBoxSize) { + if (borderBoxSize) { + const { + inlineSize, + blockSize + } = borderBoxSize[0]; + return { + width: inlineSize, + height: blockSize + }; + } else if (target instanceof SVGElement && "getBBox" in target) { + return target.getBBox(); + } else { + return { + width: target.offsetWidth, + height: target.offsetHeight + }; + } + } + function notifyTarget({ + target, + contentRect, + borderBoxSize + }) { + var _a; + (_a = resizeHandlers.get(target)) === null || _a === void 0 ? void 0 : _a.forEach(handler => { + handler({ + target, + contentSize: contentRect, + get size() { + return getElementSize(target, borderBoxSize); + } + }); + }); + } + function notifyAll(entries) { + entries.forEach(notifyTarget); + } + function createResizeObserver() { + if (typeof ResizeObserver === "undefined") return; + observer = new ResizeObserver(notifyAll); + } + function resizeElement(target, handler) { + if (!observer) createResizeObserver(); + const elements = (0, _resolveElementsEs.resolveElements)(target); + elements.forEach(element => { + let elementHandlers = resizeHandlers.get(element); + if (!elementHandlers) { + elementHandlers = new Set(); + resizeHandlers.set(element, elementHandlers); + } + elementHandlers.add(handler); + observer === null || observer === void 0 ? void 0 : observer.observe(element); + }); + return () => { + elements.forEach(element => { + const elementHandlers = resizeHandlers.get(element); + elementHandlers === null || elementHandlers === void 0 ? void 0 : elementHandlers.delete(handler); + if (!(elementHandlers === null || elementHandlers === void 0 ? void 0 : elementHandlers.size)) { + observer === null || observer === void 0 ? void 0 : observer.unobserve(element); + } + }); + }; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js ***! + \*************************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.resizeWindow = resizeWindow; + const windowCallbacks = new Set(); + let windowResizeHandler; + function createWindowResizeHandler() { + windowResizeHandler = () => { + const size = { + width: window.innerWidth, + height: window.innerHeight + }; + const info = { + target: window, + size, + contentSize: size + }; + windowCallbacks.forEach(callback => callback(info)); + }; + window.addEventListener("resize", windowResizeHandler); + } + function resizeWindow(callback) { + windowCallbacks.add(callback); + if (!windowResizeHandler) createWindowResizeHandler(); + return () => { + windowCallbacks.delete(callback); + if (!windowCallbacks.size && windowResizeHandler) { + windowResizeHandler = undefined; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.resize = resize; + var _handleElementEs = __webpack_require__(/*! ./handle-element.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js"); + var _handleWindowEs = __webpack_require__(/*! ./handle-window.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js"); + function resize(a, b) { + return typeof a === "function" ? (0, _handleWindowEs.resizeWindow)(a) : (0, _handleElementEs.resizeElement)(a, b); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.scroll = scroll; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var _indexEs = __webpack_require__(/*! ../resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js"); + var _infoEs = __webpack_require__(/*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js"); + var _onScrollHandlerEs = __webpack_require__(/*! ./on-scroll-handler.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js"); + const scrollListeners = new WeakMap(); + const resizeListeners = new WeakMap(); + const onScrollHandlers = new WeakMap(); + const getEventTarget = element => element === document.documentElement ? window : element; + function scroll(onScroll, _a = {}) { + var { + container = document.documentElement + } = _a, + options = (0, _tslib.__rest)(_a, ["container"]); + let containerHandlers = onScrollHandlers.get(container); + /** + * Get the onScroll handlers for this container. + * If one isn't found, create a new one. + */ + if (!containerHandlers) { + containerHandlers = new Set(); + onScrollHandlers.set(container, containerHandlers); + } + /** + * Create a new onScroll handler for the provided callback. + */ + const info = (0, _infoEs.createScrollInfo)(); + const containerHandler = (0, _onScrollHandlerEs.createOnScrollHandler)(container, onScroll, info, options); + containerHandlers.add(containerHandler); + /** + * Check if there's a scroll event listener for this container. + * If not, create one. + */ + if (!scrollListeners.has(container)) { + const listener = () => { + const time = performance.now(); + for (const handler of containerHandlers) handler.measure(); + for (const handler of containerHandlers) handler.update(time); + for (const handler of containerHandlers) handler.notify(); + }; + scrollListeners.set(container, listener); + const target = getEventTarget(container); + window.addEventListener("resize", listener, { + passive: true + }); + if (container !== document.documentElement) { + resizeListeners.set(container, (0, _indexEs.resize)(container, listener)); + } + target.addEventListener("scroll", listener, { + passive: true + }); + } + const listener = scrollListeners.get(container); + const onLoadProcesss = requestAnimationFrame(listener); + return () => { + var _a; + if (typeof onScroll !== "function") onScroll.stop(); + cancelAnimationFrame(onLoadProcesss); + /** + * Check if we even have any handlers for this container. + */ + const containerHandlers = onScrollHandlers.get(container); + if (!containerHandlers) return; + containerHandlers.delete(containerHandler); + if (containerHandlers.size) return; + /** + * If no more handlers, remove the scroll listener too. + */ + const listener = scrollListeners.get(container); + scrollListeners.delete(container); + if (listener) { + getEventTarget(container).removeEventListener("scroll", listener); + (_a = resizeListeners.get(container)) === null || _a === void 0 ? void 0 : _a(); + window.removeEventListener("resize", listener); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createScrollInfo = void 0; + exports.updateScrollInfo = updateScrollInfo; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + /** + * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + */ + const maxElapsed = 50; + const createAxisInfo = () => ({ + current: 0, + offset: [], + progress: 0, + scrollLength: 0, + targetOffset: 0, + targetLength: 0, + containerLength: 0, + velocity: 0 + }); + const createScrollInfo = () => ({ + time: 0, + x: createAxisInfo(), + y: createAxisInfo() + }); + exports.createScrollInfo = createScrollInfo; + const keys = { + x: { + length: "Width", + position: "Left" + }, + y: { + length: "Height", + position: "Top" + } + }; + function updateAxisInfo(element, axisName, info, time) { + const axis = info[axisName]; + const { + length, + position + } = keys[axisName]; + const prev = axis.current; + const prevTime = info.time; + axis.current = element["scroll" + position]; + axis.scrollLength = element["scroll" + length] - element["client" + length]; + axis.offset.length = 0; + axis.offset[0] = 0; + axis.offset[1] = axis.scrollLength; + axis.progress = (0, _utils.progress)(0, axis.scrollLength, axis.current); + const elapsed = time - prevTime; + axis.velocity = elapsed > maxElapsed ? 0 : (0, _utils.velocityPerSecond)(axis.current - prev, elapsed); + } + function updateScrollInfo(element, info, time) { + updateAxisInfo(element, "x", info, time); + updateAxisInfo(element, "y", info, time); + info.time = time; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js": + /*!************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js ***! + \************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.namedEdges = void 0; + exports.resolveEdge = resolveEdge; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + const namedEdges = exports.namedEdges = { + start: 0, + center: 0.5, + end: 1 + }; + function resolveEdge(edge, length, inset = 0) { + let delta = 0; + /** + * If we have this edge defined as a preset, replace the definition + * with the numerical value. + */ + if (namedEdges[edge] !== undefined) { + edge = namedEdges[edge]; + } + /** + * Handle unit values + */ + if ((0, _utils.isString)(edge)) { + const asNumber = parseFloat(edge); + if (edge.endsWith("px")) { + delta = asNumber; + } else if (edge.endsWith("%")) { + edge = asNumber / 100; + } else if (edge.endsWith("vw")) { + delta = asNumber / 100 * document.documentElement.clientWidth; + } else if (edge.endsWith("vh")) { + delta = asNumber / 100 * document.documentElement.clientHeight; + } else { + edge = asNumber; + } + } + /** + * If the edge is defined as a number, handle as a progress value. + */ + if ((0, _utils.isNumber)(edge)) { + delta = length * edge; + } + return inset + delta; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js ***! + \*************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.resolveOffsets = resolveOffsets; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _insetEs = __webpack_require__(/*! ./inset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js"); + var _presetsEs = __webpack_require__(/*! ./presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js"); + var _offsetEs = __webpack_require__(/*! ./offset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js"); + const point = { + x: 0, + y: 0 + }; + function resolveOffsets(container, info, options) { + let { + offset: offsetDefinition = _presetsEs.ScrollOffset.All + } = options; + const { + target = container, + axis = "y" + } = options; + const lengthLabel = axis === "y" ? "height" : "width"; + const inset = target !== container ? (0, _insetEs.calcInset)(target, container) : point; + /** + * Measure the target and container. If they're the same thing then we + * use the container's scrollWidth/Height as the target, from there + * all other calculations can remain the same. + */ + const targetSize = target === container ? { + width: container.scrollWidth, + height: container.scrollHeight + } : { + width: target.clientWidth, + height: target.clientHeight + }; + const containerSize = { + width: container.clientWidth, + height: container.clientHeight + }; + /** + * Reset the length of the resolved offset array rather than creating a new one. + * TODO: More reusable data structures for targetSize/containerSize would also be good. + */ + info[axis].offset.length = 0; + /** + * Populate the offset array by resolving the user's offset definition into + * a list of pixel scroll offets. + */ + let hasChanged = !info[axis].interpolate; + const numOffsets = offsetDefinition.length; + for (let i = 0; i < numOffsets; i++) { + const offset = (0, _offsetEs.resolveOffset)(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]); + if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { + hasChanged = true; + } + info[axis].offset[i] = offset; + } + /** + * If the pixel scroll offsets have changed, create a new interpolator function + * to map scroll value into a progress. + */ + if (hasChanged) { + info[axis].interpolate = (0, _utils.interpolate)((0, _utils.defaultOffset)(numOffsets), info[axis].offset); + info[axis].interpolatorOffsets = [...info[axis].offset]; + } + info[axis].progress = info[axis].interpolate(info[axis].current); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js ***! + \*************************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.calcInset = calcInset; + function calcInset(element, container) { + let inset = { + x: 0, + y: 0 + }; + let current = element; + while (current && current !== container) { + if (current instanceof HTMLElement) { + inset.x += current.offsetLeft; + inset.y += current.offsetTop; + current = current.offsetParent; + } else if (current instanceof SVGGraphicsElement && "getBBox" in current) { + const { + top, + left + } = current.getBBox(); + inset.x += left; + inset.y += top; + /** + * Assign the next parent element as the tag. + */ + while (current && current.tagName !== "svg") { + current = current.parentNode; } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/index.es.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/index.es.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.animate = animate; - var _animateStyleEs = __webpack_require__( - /*! ./animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" - ); - var _optionsEs = __webpack_require__( - /*! ./utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js" - ); - var _resolveElementsEs = __webpack_require__( - /*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" - ); - var _controlsEs = __webpack_require__( - /*! ./utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js" - ); - var _staggerEs = __webpack_require__( - /*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js" - ); - function animate(elements, keyframes, options = {}) { - elements = (0, _resolveElementsEs.resolveElements)(elements); - const numElements = elements.length; - /** - * Create and start new animations - */ - const animationFactories = []; - for (let i = 0; i < numElements; i++) { - const element = elements[i]; - for (const key in keyframes) { - const valueOptions = (0, _optionsEs.getOptions)(options, key); - valueOptions.delay = (0, _staggerEs.resolveOption)( - valueOptions.delay, - i, - numElements - ); - const animation = (0, _animateStyleEs.animateStyle)( - element, - key, - keyframes[key], - valueOptions - ); - animationFactories.push(animation); - } - } - return (0, _controlsEs.withControls)( - animationFactories, - options, - /** - * TODO: - * If easing is set to spring or glide, duration will be dynamically - * generated. Ideally we would dynamically generate this from - * animation.effect.getComputedTiming().duration but this isn't - * supported in iOS13 or our number polyfill. Perhaps it's possible - * to Proxy animations returned from animateStyle that has duration - * as a getter. - */ - options.duration - ); + } + } + return inset; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js ***! + \**************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.resolveOffset = resolveOffset; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _edgeEs = __webpack_require__(/*! ./edge.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js"); + const defaultOffset = [0, 0]; + function resolveOffset(offset, containerLength, targetLength, targetInset) { + let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; + let targetPoint = 0; + let containerPoint = 0; + if ((0, _utils.isNumber)(offset)) { + /** + * If we're provided offset: [0, 0.5, 1] then each number x should become + * [x, x], so we default to the behaviour of mapping 0 => 0 of both target + * and container etc. + */ + offsetDefinition = [offset, offset]; + } else if ((0, _utils.isString)(offset)) { + offset = offset.trim(); + if (offset.includes(" ")) { + offsetDefinition = offset.split(" "); + } else { + /** + * If we're provided a definition like "100px" then we want to apply + * that only to the top of the target point, leaving the container at 0. + * Whereas a named offset like "end" should be applied to both. + */ + offsetDefinition = [offset, _edgeEs.namedEdges[offset] ? offset : `0`]; + } + } + targetPoint = (0, _edgeEs.resolveEdge)(offsetDefinition[0], targetLength, targetInset); + containerPoint = (0, _edgeEs.resolveEdge)(offsetDefinition[1], containerLength); + return targetPoint - containerPoint; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js": + /*!***************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js ***! + \***************************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.ScrollOffset = void 0; + const ScrollOffset = exports.ScrollOffset = { + Enter: [[0, 1], [1, 1]], + Exit: [[0, 0], [1, 0]], + Any: [[1, 0], [0, 1]], + All: [[0, 0], [1, 1]] + }; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js": + /*!*****************************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js ***! + \*****************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createOnScrollHandler = createOnScrollHandler; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _infoEs = __webpack_require__(/*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js"); + var _indexEs = __webpack_require__(/*! ./offsets/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js"); + function measure(container, target = container, info) { + /** + * Find inset of target within scrollable container + */ + info.x.targetOffset = 0; + info.y.targetOffset = 0; + if (target !== container) { + let node = target; + while (node && node != container) { + info.x.targetOffset += node.offsetLeft; + info.y.targetOffset += node.offsetTop; + node = node.offsetParent; + } + } + info.x.targetLength = target === container ? target.scrollWidth : target.clientWidth; + info.y.targetLength = target === container ? target.scrollHeight : target.clientHeight; + info.x.containerLength = container.clientWidth; + info.y.containerLength = container.clientHeight; + } + function createOnScrollHandler(element, onScroll, info, options = {}) { + const axis = options.axis || "y"; + return { + measure: () => measure(element, options.target, info), + update: time => { + (0, _infoEs.updateScrollInfo)(element, info, time); + if (options.offset || options.target) { + (0, _indexEs.resolveOffsets)(element, info, options); } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/style.es.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/style.es.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.style = void 0; - var _cssVarEs = __webpack_require__( - /*! ./utils/css-var.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js" - ); - var _getStyleNameEs = __webpack_require__( - /*! ./utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js" - ); - var _transformsEs = __webpack_require__( - /*! ./utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" - ); - const style = (exports.style = { - get: (element, name) => { - name = (0, _getStyleNameEs.getStyleName)(name); - let value = (0, _cssVarEs.isCssVar)(name) - ? element.style.getPropertyValue(name) - : getComputedStyle(element)[name]; - if (!value && value !== 0) { - const definition = _transformsEs.transformDefinitions.get(name); - if (definition) value = definition.initialValue; - } - return value; - }, - set: (element, name, value) => { - name = (0, _getStyleNameEs.getStyleName)(name); - if ((0, _cssVarEs.isCssVar)(name)) { - element.style.setProperty(name, value); - } else { - element.style[name] = value; - } - }, - }); - - /***/ }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js ***! - \******************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.withControls = exports.controls = void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _stopAnimationEs = __webpack_require__( - /*! ./stop-animation.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js" - ); - const createAnimation = (factory) => factory(); - const withControls = ( - animationFactory, - options, - duration = _utils.defaults.duration - ) => { - return new Proxy( - { - animations: animationFactory.map(createAnimation).filter(Boolean), - duration, - options, - }, - controls - ); - }; - /** - * TODO: - * Currently this returns the first animation, ideally it would return - * the first active animation. - */ - exports.withControls = withControls; - const getActiveAnimation = (state) => state.animations[0]; - const controls = (exports.controls = { - get: (target, key) => { - const activeAnimation = getActiveAnimation(target); - switch (key) { - case "duration": - return target.duration; - case "currentTime": - return _utils.time.s( - (activeAnimation === null || activeAnimation === void 0 - ? void 0 - : activeAnimation[key]) || 0 - ); - case "playbackRate": - case "playState": - return activeAnimation === null || activeAnimation === void 0 - ? void 0 - : activeAnimation[key]; - case "finished": - if (!target.finished) { - target.finished = Promise.all( - target.animations.map(selectFinished) - ).catch(_utils.noop); - } - return target.finished; - case "stop": - return () => { - target.animations.forEach((animation) => - (0, _stopAnimationEs.stopAnimation)(animation) - ); - }; - case "forEachNative": - /** - * This is for internal use only, fire a callback for each - * underlying animation. - */ - return (callback) => { - target.animations.forEach((animation) => - callback(animation, target) - ); - }; - default: - return typeof (activeAnimation === null || - activeAnimation === void 0 - ? void 0 - : activeAnimation[key]) === "undefined" - ? undefined - : () => - target.animations.forEach((animation) => - animation[key]() - ); - } - }, - set: (target, key, value) => { - switch (key) { - case "currentTime": - value = _utils.time.ms(value); - case "currentTime": - case "playbackRate": - for (let i = 0; i < target.animations.length; i++) { - target.animations[i][key] = value; - } - return true; - } - return false; - }, - }); - const selectFinished = (animation) => animation.finished; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/css-var.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isCssVar = void 0; - exports.registerCssVariable = registerCssVariable; - exports.registeredProperties = void 0; - var _transformsEs = __webpack_require__( - /*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" - ); - const isCssVar = (name) => name.startsWith("--"); - exports.isCssVar = isCssVar; - const registeredProperties = (exports.registeredProperties = new Set()); - function registerCssVariable(name) { - if (registeredProperties.has(name)) return; - registeredProperties.add(name); - try { - const { syntax, initialValue } = - _transformsEs.transformDefinitions.has(name) - ? _transformsEs.transformDefinitions.get(name) - : {}; - CSS.registerProperty({ - name, - inherits: false, - syntax, - initialValue, - }); - } catch (e) {} - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/easing.es.js ***! - \****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.cubicBezierAsString = exports.convertEasing = void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - const convertEasing = (easing) => - (0, _utils.isCubicBezier)(easing) - ? cubicBezierAsString(easing) - : easing; - exports.convertEasing = convertEasing; - const cubicBezierAsString = ([a, b, c, d]) => - `cubic-bezier(${a}, ${b}, ${c}, ${d})`; - exports.cubicBezierAsString = cubicBezierAsString; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js": - /*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/feature-detection.es.js ***! - \***************************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.supports = void 0; - const testAnimation = (keyframes) => - document.createElement("div").animate(keyframes, { - duration: 0.001, - }); - const featureTests = { - cssRegisterProperty: () => - typeof CSS !== "undefined" && - Object.hasOwnProperty.call(CSS, "registerProperty"), - waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"), - partialKeyframes: () => { - try { - testAnimation({ - opacity: [1], - }); - } catch (e) { - return false; - } - return true; - }, - finished: () => - Boolean( - testAnimation({ - opacity: [0, 1], - }).finished - ), + notify: typeof onScroll === "function" ? () => onScroll(info) : scrubAnimation(onScroll, info[axis]) + }; + } + function scrubAnimation(controls, axisInfo) { + controls.pause(); + controls.forEachNative((animation, { + easing + }) => { + var _a, _b; + if (animation.updateDuration) { + if (!easing) animation.easing = _utils.noopReturn; + animation.updateDuration(1); + } else { + const timingOptions = { + duration: 1000 }; - const results = {}; - const supports = (exports.supports = {}); - for (const key in featureTests) { - supports[key] = () => { - if (results[key] === undefined) results[key] = featureTests[key](); - return results[key]; + if (!easing) timingOptions.easing = "linear"; + (_b = (_a = animation.effect) === null || _a === void 0 ? void 0 : _a.updateTiming) === null || _b === void 0 ? void 0 : _b.call(_a, timingOptions); + } + }); + return () => { + controls.currentTime = axisInfo.progress; + }; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/index.es.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/index.es.js ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "ScrollOffset", ({ + enumerable: true, + get: function () { + return _presetsEs.ScrollOffset; + } + })); + Object.defineProperty(exports, "animate", ({ + enumerable: true, + get: function () { + return _indexEs.animate; + } + })); + Object.defineProperty(exports, "animateStyle", ({ + enumerable: true, + get: function () { + return _animateStyleEs.animateStyle; + } + })); + Object.defineProperty(exports, "createMotionState", ({ + enumerable: true, + get: function () { + return _indexEs7.createMotionState; + } + })); + Object.defineProperty(exports, "createStyleString", ({ + enumerable: true, + get: function () { + return _styleStringEs.createStyleString; + } + })); + Object.defineProperty(exports, "createStyles", ({ + enumerable: true, + get: function () { + return _styleObjectEs.createStyles; + } + })); + Object.defineProperty(exports, "getAnimationData", ({ + enumerable: true, + get: function () { + return _dataEs.getAnimationData; + } + })); + Object.defineProperty(exports, "getStyleName", ({ + enumerable: true, + get: function () { + return _getStyleNameEs.getStyleName; + } + })); + Object.defineProperty(exports, "glide", ({ + enumerable: true, + get: function () { + return _indexEs4.glide; + } + })); + Object.defineProperty(exports, "inView", ({ + enumerable: true, + get: function () { + return _inViewEs.inView; + } + })); + Object.defineProperty(exports, "mountedStates", ({ + enumerable: true, + get: function () { + return _indexEs7.mountedStates; + } + })); + Object.defineProperty(exports, "resize", ({ + enumerable: true, + get: function () { + return _indexEs5.resize; + } + })); + Object.defineProperty(exports, "scroll", ({ + enumerable: true, + get: function () { + return _indexEs6.scroll; + } + })); + Object.defineProperty(exports, "spring", ({ + enumerable: true, + get: function () { + return _indexEs3.spring; + } + })); + Object.defineProperty(exports, "stagger", ({ + enumerable: true, + get: function () { + return _staggerEs.stagger; + } + })); + Object.defineProperty(exports, "style", ({ + enumerable: true, + get: function () { + return _styleEs.style; + } + })); + Object.defineProperty(exports, "timeline", ({ + enumerable: true, + get: function () { + return _indexEs2.timeline; + } + })); + Object.defineProperty(exports, "withControls", ({ + enumerable: true, + get: function () { + return _controlsEs.withControls; + } + })); + var _indexEs = __webpack_require__(/*! ./animate/index.es.js */ "../../../node_modules/@motionone/dom/dist/animate/index.es.js"); + var _animateStyleEs = __webpack_require__(/*! ./animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); + var _indexEs2 = __webpack_require__(/*! ./timeline/index.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js"); + var _staggerEs = __webpack_require__(/*! ./utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); + var _indexEs3 = __webpack_require__(/*! ./easing/spring/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js"); + var _indexEs4 = __webpack_require__(/*! ./easing/glide/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js"); + var _styleEs = __webpack_require__(/*! ./animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); + var _inViewEs = __webpack_require__(/*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js"); + var _indexEs5 = __webpack_require__(/*! ./gestures/resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js"); + var _indexEs6 = __webpack_require__(/*! ./gestures/scroll/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js"); + var _presetsEs = __webpack_require__(/*! ./gestures/scroll/offsets/presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js"); + var _controlsEs = __webpack_require__(/*! ./animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); + var _dataEs = __webpack_require__(/*! ./animate/data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js"); + var _getStyleNameEs = __webpack_require__(/*! ./animate/utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js"); + var _indexEs7 = __webpack_require__(/*! ./state/index.es.js */ "../../../node_modules/@motionone/dom/dist/state/index.es.js"); + var _styleObjectEs = __webpack_require__(/*! ./animate/utils/style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js"); + var _styleStringEs = __webpack_require__(/*! ./animate/utils/style-string.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js"); + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.hover = void 0; + var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); + const mouseEvent = (element, name, action) => event => { + if (event.pointerType && event.pointerType !== "mouse") return; + action(); + (0, _eventsEs.dispatchPointerEvent)(element, name, event); + }; + const hover = exports.hover = { + isActive: options => Boolean(options.hover), + subscribe: (element, { + enable, + disable + }) => { + const onEnter = mouseEvent(element, "hoverstart", enable); + const onLeave = mouseEvent(element, "hoverend", disable); + element.addEventListener("pointerenter", onEnter); + element.addEventListener("pointerleave", onLeave); + return () => { + element.removeEventListener("pointerenter", onEnter); + element.removeEventListener("pointerleave", onLeave); + }; + } + }; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.inView = void 0; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); + var _inViewEs = __webpack_require__(/*! ../../gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js"); + const inView = exports.inView = { + isActive: options => Boolean(options.inView), + subscribe: (element, { + enable, + disable + }, { + inViewOptions = {} + }) => { + const { + once + } = inViewOptions, + viewOptions = (0, _tslib.__rest)(inViewOptions, ["once"]); + return (0, _inViewEs.inView)(element, enterEntry => { + enable(); + (0, _eventsEs.dispatchViewEvent)(element, "viewenter", enterEntry); + if (!once) { + return leaveEntry => { + disable(); + (0, _eventsEs.dispatchViewEvent)(element, "viewleave", leaveEntry); }; } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js": - /*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js ***! - \************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getStyleName = getStyleName; - var _transformsEs = __webpack_require__( - /*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" - ); - function getStyleName(key) { - if (_transformsEs.transformAlias[key]) - key = _transformsEs.transformAlias[key]; - return (0, _transformsEs.isTransform)(key) - ? (0, _transformsEs.asTransformCssVar)(key) - : key; + }, viewOptions); + } + }; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.press = void 0; + var _eventsEs = __webpack_require__(/*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); + const press = exports.press = { + isActive: options => Boolean(options.press), + subscribe: (element, { + enable, + disable + }) => { + const onPointerUp = event => { + disable(); + (0, _eventsEs.dispatchPointerEvent)(element, "pressend", event); + window.removeEventListener("pointerup", onPointerUp); + }; + const onPointerDown = event => { + enable(); + (0, _eventsEs.dispatchPointerEvent)(element, "pressstart", event); + window.addEventListener("pointerup", onPointerUp); + }; + element.addEventListener("pointerdown", onPointerDown); + return () => { + element.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerup", onPointerUp); + }; + } + }; + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/index.es.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/index.es.js ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createMotionState = createMotionState; + exports.mountedStates = void 0; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var _heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _animateStyleEs = __webpack_require__(/*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); + var _styleEs = __webpack_require__(/*! ../animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js"); + var _optionsEs = __webpack_require__(/*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); + var _hasChangedEs = __webpack_require__(/*! ./utils/has-changed.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js"); + var _resolveVariantEs = __webpack_require__(/*! ./utils/resolve-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js"); + var _scheduleEs = __webpack_require__(/*! ./utils/schedule.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js"); + var _inViewEs = __webpack_require__(/*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js"); + var _hoverEs = __webpack_require__(/*! ./gestures/hover.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js"); + var _pressEs = __webpack_require__(/*! ./gestures/press.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js"); + var _eventsEs = __webpack_require__(/*! ./utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js"); + const gestures = { + inView: _inViewEs.inView, + hover: _hoverEs.hover, + press: _pressEs.press + }; + /** + * A list of state types, in priority order. If a value is defined in + * a righter-most type, it will override any definition in a lefter-most. + */ + const stateTypes = ["initial", "animate", ...Object.keys(gestures), "exit"]; + /** + * A global store of all generated motion states. This can be used to lookup + * a motion state for a given Element. + */ + const mountedStates = exports.mountedStates = new WeakMap(); + function createMotionState(options = {}, parent) { + /** + * The element represented by the motion state. This is an empty reference + * when we create the state to support SSR and allow for later mounting + * in view libraries. + * + * @ts-ignore + */ + let element; + /** + * Calculate a depth that we can use to order motion states by tree depth. + */ + let depth = parent ? parent.getDepth() + 1 : 0; + /** + * Track which states are currently active. + */ + const activeStates = { + initial: true, + animate: true + }; + /** + * A map of functions that, when called, will remove event listeners for + * a given gesture. + */ + const gestureSubscriptions = {}; + /** + * Initialise a context to share through motion states. This + * will be populated by variant names (if any). + */ + const context = {}; + for (const name of stateTypes) { + context[name] = typeof options[name] === "string" ? options[name] : parent === null || parent === void 0 ? void 0 : parent.getContext()[name]; + } + /** + * If initial is set to false we use the animate prop as the initial + * animation state. + */ + const initialVariantSource = options.initial === false ? "animate" : "initial"; + /** + * Destructure an initial target out from the resolved initial variant. + */ + let _a = (0, _resolveVariantEs.resolveVariant)(options[initialVariantSource] || context[initialVariantSource], options.variants) || {}, + target = (0, _tslib.__rest)(_a, ["transition"]); + /** + * The base target is a cached map of values that we'll use to animate + * back to if a value is removed from all active state types. This + * is usually the initial value as read from the DOM, for instance if + * it hasn't been defined in initial. + */ + const baseTarget = Object.assign({}, target); + /** + * A generator that will be processed by the global animation scheduler. + * This yeilds when it switches from reading the DOM to writing to it + * to prevent layout thrashing. + */ + function* animateUpdates() { + var _a, _b; + const prevTarget = target; + target = {}; + const animationOptions = {}; + for (const name of stateTypes) { + if (!activeStates[name]) continue; + const variant = (0, _resolveVariantEs.resolveVariant)(options[name]); + if (!variant) continue; + for (const key in variant) { + if (key === "transition") continue; + target[key] = variant[key]; + animationOptions[key] = (0, _optionsEs.getOptions)((_b = (_a = variant.transition) !== null && _a !== void 0 ? _a : options.transition) !== null && _b !== void 0 ? _b : {}, key); } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js": - /*!*******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js ***! - \*******************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.hydrateKeyframes = hydrateKeyframes; - exports.keyframesList = void 0; - function hydrateKeyframes(keyframes, readInitialValue) { - for (let i = 0; i < keyframes.length; i++) { - if (keyframes[i] === null) { - keyframes[i] = i ? keyframes[i - 1] : readInitialValue(); - } - } - return keyframes; + } + const allTargetKeys = new Set([...Object.keys(target), ...Object.keys(prevTarget)]); + const animationFactories = []; + allTargetKeys.forEach(key => { + var _a; + if (target[key] === undefined) { + target[key] = baseTarget[key]; + } + if ((0, _hasChangedEs.hasChanged)(prevTarget[key], target[key])) { + (_a = baseTarget[key]) !== null && _a !== void 0 ? _a : baseTarget[key] = _styleEs.style.get(element, key); + animationFactories.push((0, _animateStyleEs.animateStyle)(element, key, target[key], animationOptions[key])); + } + }); + // Wait for all animation states to read from the DOM + yield; + const animations = animationFactories.map(factory => factory()).filter(Boolean); + if (!animations.length) return; + const animationTarget = target; + element.dispatchEvent((0, _eventsEs.motionEvent)("motionstart", animationTarget)); + Promise.all(animations.map(animation => animation.finished)).then(() => { + element.dispatchEvent((0, _eventsEs.motionEvent)("motioncomplete", animationTarget)); + }).catch(_utils.noop); + } + const setGesture = (name, isActive) => () => { + activeStates[name] = isActive; + (0, _scheduleEs.scheduleAnimation)(state); + }; + const updateGestureSubscriptions = () => { + for (const name in gestures) { + const isGestureActive = gestures[name].isActive(options); + const remove = gestureSubscriptions[name]; + if (isGestureActive && !remove) { + gestureSubscriptions[name] = gestures[name].subscribe(element, { + enable: setGesture(name, true), + disable: setGesture(name, false) + }, options); + } else if (!isGestureActive && remove) { + remove(); + delete gestureSubscriptions[name]; } - const keyframesList = (keyframes) => - Array.isArray(keyframes) ? keyframes : [keyframes]; - exports.keyframesList = keyframesList; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getOptions = void 0; - const getOptions = (options, key) => - /** - * TODO: Make test for this - * Always return a new object otherwise delay is overwritten by results of stagger - * and this results in no stagger - */ - options[key] - ? Object.assign(Object.assign({}, options), options[key]) - : Object.assign({}, options); - exports.getOptions = getOptions; - - /***/ + } + }; + const state = { + update: newOptions => { + if (!element) return; + options = newOptions; + updateGestureSubscriptions(); + (0, _scheduleEs.scheduleAnimation)(state); }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js": - /*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/stop-animation.es.js ***! - \************************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.stopAnimation = stopAnimation; - function stopAnimation(animation, needsCommit = true) { - if (!animation || animation.playState === "finished") return; - // Suppress error thrown by WAAPI - try { - if (animation.stop) { - animation.stop(); - } else { - needsCommit && animation.commitStyles(); - animation.cancel(); - } - } catch (e) {} - } - - /***/ + setActive: (name, isActive) => { + if (!element) return; + activeStates[name] = isActive; + (0, _scheduleEs.scheduleAnimation)(state); }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js ***! - \**********************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createStyles = createStyles; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _transformsEs = __webpack_require__( - /*! ./transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" - ); - function createStyles(keyframes) { - const initialKeyframes = {}; - const transformKeys = []; - for (let key in keyframes) { - const value = keyframes[key]; - if ((0, _transformsEs.isTransform)(key)) { - if (_transformsEs.transformAlias[key]) - key = _transformsEs.transformAlias[key]; - transformKeys.push(key); - key = (0, _transformsEs.asTransformCssVar)(key); - } - let initialKeyframe = Array.isArray(value) ? value[0] : value; - /** - * If this is a number and we have a default value type, convert the number - * to this type. - */ - const definition = _transformsEs.transformDefinitions.get(key); - if (definition) { - initialKeyframe = (0, _utils.isNumber)(value) - ? definition.toDefaultUnit(value) - : value; - } - initialKeyframes[key] = initialKeyframe; + animateUpdates, + getDepth: () => depth, + getTarget: () => target, + getOptions: () => options, + getContext: () => context, + mount: newElement => { + (0, _heyListen.invariant)(Boolean(newElement), "Animation state must be mounted with valid Element"); + element = newElement; + mountedStates.set(element, state); + updateGestureSubscriptions(); + return () => { + mountedStates.delete(element); + (0, _scheduleEs.unscheduleAnimation)(state); + for (const key in gestureSubscriptions) { + gestureSubscriptions[key](); } - if (transformKeys.length) { - initialKeyframes.transform = (0, - _transformsEs.buildTransformTemplate)(transformKeys); - } - return initialKeyframes; - } - - /***/ + }; }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js ***! - \**********************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createStyleString = createStyleString; - var _styleObjectEs = __webpack_require__( - /*! ./style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js" - ); - const camelLetterToPipeLetter = (letter) => `-${letter.toLowerCase()}`; - const camelToPipeCase = (str) => - str.replace(/[A-Z]/g, camelLetterToPipeLetter); - function createStyleString(target = {}) { - const styles = (0, _styleObjectEs.createStyles)(target); - let style = ""; - for (const key in styles) { - style += key.startsWith("--") ? key : camelToPipeCase(key); - style += `: ${styles[key]}; `; + isMounted: () => Boolean(element) + }; + return state; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/events.es.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.dispatchPointerEvent = dispatchPointerEvent; + exports.dispatchViewEvent = dispatchViewEvent; + exports.motionEvent = void 0; + const motionEvent = (name, target) => new CustomEvent(name, { + detail: { + target + } + }); + exports.motionEvent = motionEvent; + function dispatchPointerEvent(element, name, event) { + element.dispatchEvent(new CustomEvent(name, { + detail: { + originalEvent: event + } + })); + } + function dispatchViewEvent(element, name, entry) { + element.dispatchEvent(new CustomEvent(name, { + detail: { + originalEntry: entry + } + })); + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js": + /*!*******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js ***! + \*******************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.hasChanged = hasChanged; + exports.shallowCompare = shallowCompare; + function hasChanged(a, b) { + if (typeof a !== typeof b) return true; + if (Array.isArray(a) && Array.isArray(b)) return !shallowCompare(a, b); + return a !== b; + } + function shallowCompare(next, prev) { + const prevLength = prev.length; + if (prevLength !== next.length) return false; + for (let i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) return false; + } + return true; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isVariant = isVariant; + function isVariant(definition) { + return typeof definition === "object"; + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.resolveVariant = resolveVariant; + var _isVariantEs = __webpack_require__(/*! ./is-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js"); + function resolveVariant(definition, variants) { + if ((0, _isVariantEs.isVariant)(definition)) { + return definition; + } else if (definition && variants) { + return variants[definition]; + } + } + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.scheduleAnimation = scheduleAnimation; + exports.unscheduleAnimation = unscheduleAnimation; + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + let scheduled = undefined; + function processScheduledAnimations() { + if (!scheduled) return; + const generators = scheduled.sort(compareByDepth).map(fireAnimateUpdates); + generators.forEach(fireNext); + generators.forEach(fireNext); + scheduled = undefined; + } + function scheduleAnimation(state) { + if (!scheduled) { + scheduled = [state]; + requestAnimationFrame(processScheduledAnimations); + } else { + (0, _utils.addUniqueItem)(scheduled, state); + } + } + function unscheduleAnimation(state) { + scheduled && (0, _utils.removeItem)(scheduled, state); + } + const compareByDepth = (a, b) => a.getDepth() - b.getDepth(); + const fireAnimateUpdates = state => state.animateUpdates(); + const fireNext = iterator => iterator.next(); + + /***/ }), + + /***/ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js": + /*!**********************************************************************!*\ + !*** ../../../node_modules/@motionone/dom/dist/timeline/index.es.js ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createAnimationsFromTimeline = createAnimationsFromTimeline; + exports.timeline = timeline; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var _heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); + var _utils = __webpack_require__(/*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js"); + var _staggerEs = __webpack_require__(/*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js"); + var _animateStyleEs = __webpack_require__(/*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js"); + var _controlsEs = __webpack_require__(/*! ../animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js"); + var _keyframesEs = __webpack_require__(/*! ../animate/utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js"); + var _optionsEs = __webpack_require__(/*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js"); + var _resolveElementsEs = __webpack_require__(/*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js"); + var _transformsEs = __webpack_require__(/*! ../animate/utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js"); + var _calcTimeEs = __webpack_require__(/*! ./utils/calc-time.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js"); + var _editEs = __webpack_require__(/*! ./utils/edit.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js"); + var _sortEs = __webpack_require__(/*! ./utils/sort.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js"); + function timeline(definition, options = {}) { + var _a; + const animationDefinitions = createAnimationsFromTimeline(definition, options); + /** + * Create and start animations + */ + const animationFactories = animationDefinitions.map(definition => (0, _animateStyleEs.animateStyle)(...definition)).filter(Boolean); + return (0, _controlsEs.withControls)(animationFactories, options, + // Get the duration from the first animation definition + (_a = animationDefinitions[0]) === null || _a === void 0 ? void 0 : _a[3].duration); + } + function createAnimationsFromTimeline(definition, _a = {}) { + var { + defaultOptions = {} + } = _a, + timelineOptions = (0, _tslib.__rest)(_a, ["defaultOptions"]); + const animationDefinitions = []; + const elementSequences = new Map(); + const elementCache = {}; + const timeLabels = new Map(); + let prevTime = 0; + let currentTime = 0; + let totalDuration = 0; + /** + * Build the timeline by mapping over the definition array and converting + * the definitions into keyframes and offsets with absolute time values. + * These will later get converted into relative offsets in a second pass. + */ + for (let i = 0; i < definition.length; i++) { + const segment = definition[i]; + /** + * If this is a timeline label, mark it and skip the rest of this iteration. + */ + if ((0, _utils.isString)(segment)) { + timeLabels.set(segment, currentTime); + continue; + } else if (!Array.isArray(segment)) { + timeLabels.set(segment.name, (0, _calcTimeEs.calcNextTime)(currentTime, segment.at, prevTime, timeLabels)); + continue; + } + const [elementDefinition, keyframes, options = {}] = segment; + /** + * If a relative or absolute time value has been specified we need to resolve + * it in relation to the currentTime. + */ + if (options.at !== undefined) { + currentTime = (0, _calcTimeEs.calcNextTime)(currentTime, options.at, prevTime, timeLabels); + } + /** + * Keep track of the maximum duration in this definition. This will be + * applied to currentTime once the definition has been parsed. + */ + let maxDuration = 0; + /** + * Find all the elements specified in the definition and parse value + * keyframes from their timeline definitions. + */ + const elements = (0, _resolveElementsEs.resolveElements)(elementDefinition, elementCache); + const numElements = elements.length; + for (let elementIndex = 0; elementIndex < numElements; elementIndex++) { + const element = elements[elementIndex]; + const elementSequence = getElementSequence(element, elementSequences); + for (const key in keyframes) { + const valueSequence = getValueSequence(key, elementSequence); + let valueKeyframes = (0, _keyframesEs.keyframesList)(keyframes[key]); + const valueOptions = (0, _optionsEs.getOptions)(options, key); + let { + duration = defaultOptions.duration || _utils.defaults.duration, + easing = defaultOptions.easing || _utils.defaults.easing + } = valueOptions; + if ((0, _utils.isEasingGenerator)(easing)) { + const valueIsTransform = (0, _transformsEs.isTransform)(key); + (0, _heyListen.invariant)(valueKeyframes.length === 2 || !valueIsTransform, "spring must be provided 2 keyframes within timeline"); + const custom = easing.createAnimation(valueKeyframes, + // TODO We currently only support explicit keyframes + // so this doesn't currently read from the DOM + () => "0", valueIsTransform); + easing = custom.easing; + if (custom.keyframes !== undefined) valueKeyframes = custom.keyframes; + if (custom.duration !== undefined) duration = custom.duration; + } + const delay = (0, _staggerEs.resolveOption)(options.delay, elementIndex, numElements) || 0; + const startTime = currentTime + delay; + const targetTime = startTime + duration; + /** + * + */ + let { + offset = (0, _utils.defaultOffset)(valueKeyframes.length) + } = valueOptions; + /** + * If there's only one offset of 0, fill in a second with length 1 + * + * TODO: Ensure there's a test that covers this removal + */ + if (offset.length === 1 && offset[0] === 0) { + offset[1] = 1; } - return style; + /** + * Fill out if offset if fewer offsets than keyframes + */ + const remainder = length - valueKeyframes.length; + remainder > 0 && (0, _utils.fillOffset)(offset, remainder); + /** + * If only one value has been set, ie [1], push a null to the start of + * the keyframe array. This will let us mark a keyframe at this point + * that will later be hydrated with the previous value. + */ + valueKeyframes.length === 1 && valueKeyframes.unshift(null); + /** + * Add keyframes, mapping offsets to absolute time. + */ + (0, _editEs.addKeyframes)(valueSequence, valueKeyframes, easing, offset, startTime, targetTime); + maxDuration = Math.max(delay + duration, maxDuration); + totalDuration = Math.max(targetTime, totalDuration); } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js": - /*!********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js ***! - \********************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.transformDefinitions = - exports.transformAlias = - exports.isTransform = - exports.compareTransformOrder = - exports.buildTransformTemplate = - exports.axes = - exports.asTransformCssVar = - exports.addTransformToElement = - void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _dataEs = __webpack_require__( - /*! ../data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js" - ); - /** - * A list of all transformable axes. We'll use this list to generated a version - * of each axes for each transform. - */ - const axes = (exports.axes = ["", "X", "Y", "Z"]); - /** - * An ordered array of each transformable value. By default, transform values - * will be sorted to this order. - */ - const order = ["translate", "scale", "rotate", "skew"]; - const transformAlias = (exports.transformAlias = { - x: "translateX", - y: "translateY", - z: "translateZ", - }); - const rotation = { - syntax: "", - initialValue: "0deg", - toDefaultUnit: (v) => v + "deg", - }; - const baseTransformProperties = { - translate: { - syntax: "", - initialValue: "0px", - toDefaultUnit: (v) => v + "px", - }, - rotate: rotation, - scale: { - syntax: "", - initialValue: 1, - toDefaultUnit: _utils.noopReturn, - }, - skew: rotation, - }; - const transformDefinitions = (exports.transformDefinitions = new Map()); - const asTransformCssVar = (name) => `--motion-${name}`; + } + prevTime = currentTime; + currentTime += maxDuration; + } + /** + * For every element and value combination create a new animation. + */ + elementSequences.forEach((valueSequences, element) => { + for (const key in valueSequences) { + const valueSequence = valueSequences[key]; /** - * Generate a list of every possible transform key + * Arrange all the keyframes in ascending time order. */ - exports.asTransformCssVar = asTransformCssVar; - const transforms = ["x", "y", "z"]; - order.forEach((name) => { - axes.forEach((axis) => { - transforms.push(name + axis); - transformDefinitions.set( - asTransformCssVar(name + axis), - baseTransformProperties[name] - ); - }); - }); + valueSequence.sort(_sortEs.compareByTime); + const keyframes = []; + const valueOffset = []; + const valueEasing = []; /** - * A function to use with Array.sort to sort transform keys by their default order. + * For each keyframe, translate absolute times into + * relative offsets based on the total duration of the timeline. */ - const compareTransformOrder = (a, b) => - transforms.indexOf(a) - transforms.indexOf(b); + for (let i = 0; i < valueSequence.length; i++) { + const { + at, + value, + easing + } = valueSequence[i]; + keyframes.push(value); + valueOffset.push((0, _utils.progress)(0, totalDuration, at)); + valueEasing.push(easing || _utils.defaults.easing); + } /** - * Provide a quick way to check if a string is the name of a transform + * If the first keyframe doesn't land on offset: 0 + * provide one by duplicating the initial keyframe. This ensures + * it snaps to the first keyframe when the animation starts. */ - exports.compareTransformOrder = compareTransformOrder; - const transformLookup = new Set(transforms); - const isTransform = (name) => transformLookup.has(name); - exports.isTransform = isTransform; - const addTransformToElement = (element, name) => { - // Map x to translateX etc - if (transformAlias[name]) name = transformAlias[name]; - const { transforms } = (0, _dataEs.getAnimationData)(element); - (0, _utils.addUniqueItem)(transforms, name); - /** - * TODO: An optimisation here could be to cache the transform in element data - * and only update if this has changed. - */ - element.style.transform = buildTransformTemplate(transforms); - }; - exports.addTransformToElement = addTransformToElement; - const buildTransformTemplate = (transforms) => - transforms - .sort(compareTransformOrder) - .reduce(transformListToString, "") - .trim(); - exports.buildTransformTemplate = buildTransformTemplate; - const transformListToString = (template, name) => - `${template} ${name}(var(${asTransformCssVar(name)}))`; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js": - /*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js ***! - \**************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createGeneratorEasing = createGeneratorEasing; - var _generators = __webpack_require__( - /*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js" - ); - function createGeneratorEasing(createGenerator) { - const keyframesCache = new WeakMap(); - return (options = {}) => { - const generatorCache = new Map(); - const getGenerator = ( - from = 0, - to = 100, - velocity = 0, - isScale = false - ) => { - const key = `${from}-${to}-${velocity}-${isScale}`; - if (!generatorCache.has(key)) { - generatorCache.set( - key, - createGenerator( - Object.assign( - { - from, - to, - velocity, - restSpeed: isScale ? 0.05 : 2, - restDistance: isScale ? 0.01 : 0.5, - }, - options - ) - ) - ); - } - return generatorCache.get(key); - }; - const getKeyframes = (generator) => { - if (!keyframesCache.has(generator)) { - keyframesCache.set( - generator, - (0, _generators.pregenerateKeyframes)(generator) - ); - } - return keyframesCache.get(generator); - }; - return { - createAnimation: ( - keyframes, - getOrigin, - canUseGenerator, - name, - motionValue - ) => { - var _a, _b; - let settings; - const numKeyframes = keyframes.length; - let shouldUseGenerator = - canUseGenerator && - numKeyframes <= 2 && - keyframes.every(isNumberOrNull); - if (shouldUseGenerator) { - const target = keyframes[numKeyframes - 1]; - const unresolvedOrigin = - numKeyframes === 1 ? null : keyframes[0]; - let velocity = 0; - let origin = 0; - const prevGenerator = - motionValue === null || motionValue === void 0 - ? void 0 - : motionValue.generator; - if (prevGenerator) { - /** - * If we have a generator for this value we can use it to resolve - * the animations's current value and velocity. - */ - const { animation, generatorStartTime } = motionValue; - const startTime = - (animation === null || animation === void 0 - ? void 0 - : animation.startTime) || - generatorStartTime || - 0; - const currentTime = - (animation === null || animation === void 0 - ? void 0 - : animation.currentTime) || - performance.now() - startTime; - const prevGeneratorCurrent = - prevGenerator(currentTime).current; - origin = - (_a = unresolvedOrigin) !== null && _a !== void 0 - ? _a - : prevGeneratorCurrent; - if ( - numKeyframes === 1 || - (numKeyframes === 2 && keyframes[0] === null) - ) { - velocity = (0, _generators.calcGeneratorVelocity)( - (t) => prevGenerator(t).current, - currentTime, - prevGeneratorCurrent - ); - } - } else { - origin = - (_b = unresolvedOrigin) !== null && _b !== void 0 - ? _b - : parseFloat(getOrigin()); - } - const generator = getGenerator( - origin, - target, - velocity, - name === null || name === void 0 - ? void 0 - : name.includes("scale") - ); - const keyframesMetadata = getKeyframes(generator); - settings = Object.assign( - Object.assign({}, keyframesMetadata), - { - easing: "linear", - } - ); - // TODO Add test for this - if (motionValue) { - motionValue.generator = generator; - motionValue.generatorStartTime = performance.now(); - } - } else { - const keyframesMetadata = getKeyframes(getGenerator(0, 100)); - settings = { - easing: "ease", - duration: keyframesMetadata.overshootDuration, - }; - } - return settings; - }, - }; - }; - } - const isNumberOrNull = (value) => typeof value !== "string"; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.glide = void 0; - var _generators = __webpack_require__( - /*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js" - ); - var _createGeneratorEasingEs = __webpack_require__( - /*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js" - ); - const glide = (exports.glide = (0, - _createGeneratorEasingEs.createGeneratorEasing)(_generators.glide)); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.spring = void 0; - var _generators = __webpack_require__( - /*! @motionone/generators */ "../../../node_modules/@motionone/generators/dist/index.es.js" - ); - var _createGeneratorEasingEs = __webpack_require__( - /*! ../create-generator-easing.es.js */ "../../../node_modules/@motionone/dom/dist/easing/create-generator-easing.es.js" - ); - const spring = (exports.spring = (0, - _createGeneratorEasingEs.createGeneratorEasing)(_generators.spring)); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js ***! - \************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.inView = inView; - var _resolveElementsEs = __webpack_require__( - /*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" - ); - const thresholds = { - any: 0, - all: 1, - }; - function inView( - elementOrSelector, - onStart, - { root, margin: rootMargin, amount = "any" } = {} - ) { - /** - * If this browser doesn't support IntersectionObserver, return a dummy stop function. - * Default triggering of onStart is tricky - it could be used for starting/stopping - * videos, lazy loading content etc. We could provide an option to enable a fallback, or - * provide a fallback callback option. - */ - if (typeof IntersectionObserver === "undefined") { - return () => {}; - } - const elements = (0, _resolveElementsEs.resolveElements)( - elementOrSelector - ); - const activeIntersections = new WeakMap(); - const onIntersectionChange = (entries) => { - entries.forEach((entry) => { - const onEnd = activeIntersections.get(entry.target); - /** - * If there's no change to the intersection, we don't need to - * do anything here. - */ - if (entry.isIntersecting === Boolean(onEnd)) return; - if (entry.isIntersecting) { - const newOnEnd = onStart(entry); - if (typeof newOnEnd === "function") { - activeIntersections.set(entry.target, newOnEnd); - } else { - observer.unobserve(entry.target); - } - } else if (onEnd) { - onEnd(entry); - activeIntersections.delete(entry.target); - } - }); - }; - const observer = new IntersectionObserver(onIntersectionChange, { - root, - rootMargin, - threshold: typeof amount === "number" ? amount : thresholds[amount], - }); - elements.forEach((element) => observer.observe(element)); - return () => observer.disconnect(); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js": - /*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js ***! - \**************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resizeElement = resizeElement; - var _resolveElementsEs = __webpack_require__( - /*! ../../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" - ); - const resizeHandlers = new WeakMap(); - let observer; - function getElementSize(target, borderBoxSize) { - if (borderBoxSize) { - const { inlineSize, blockSize } = borderBoxSize[0]; - return { - width: inlineSize, - height: blockSize, - }; - } else if (target instanceof SVGElement && "getBBox" in target) { - return target.getBBox(); - } else { - return { - width: target.offsetWidth, - height: target.offsetHeight, - }; - } - } - function notifyTarget({ target, contentRect, borderBoxSize }) { - var _a; - (_a = resizeHandlers.get(target)) === null || _a === void 0 - ? void 0 - : _a.forEach((handler) => { - handler({ - target, - contentSize: contentRect, - get size() { - return getElementSize(target, borderBoxSize); - }, - }); - }); - } - function notifyAll(entries) { - entries.forEach(notifyTarget); - } - function createResizeObserver() { - if (typeof ResizeObserver === "undefined") return; - observer = new ResizeObserver(notifyAll); - } - function resizeElement(target, handler) { - if (!observer) createResizeObserver(); - const elements = (0, _resolveElementsEs.resolveElements)(target); - elements.forEach((element) => { - let elementHandlers = resizeHandlers.get(element); - if (!elementHandlers) { - elementHandlers = new Set(); - resizeHandlers.set(element, elementHandlers); - } - elementHandlers.add(handler); - observer === null || observer === void 0 - ? void 0 - : observer.observe(element); - }); - return () => { - elements.forEach((element) => { - const elementHandlers = resizeHandlers.get(element); - elementHandlers === null || elementHandlers === void 0 - ? void 0 - : elementHandlers.delete(handler); - if ( - !(elementHandlers === null || elementHandlers === void 0 - ? void 0 - : elementHandlers.size) - ) { - observer === null || observer === void 0 - ? void 0 - : observer.unobserve(element); - } - }); - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js": - /*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js ***! - \*************************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resizeWindow = resizeWindow; - const windowCallbacks = new Set(); - let windowResizeHandler; - function createWindowResizeHandler() { - windowResizeHandler = () => { - const size = { - width: window.innerWidth, - height: window.innerHeight, - }; - const info = { - target: window, - size, - contentSize: size, - }; - windowCallbacks.forEach((callback) => callback(info)); - }; - window.addEventListener("resize", windowResizeHandler); - } - function resizeWindow(callback) { - windowCallbacks.add(callback); - if (!windowResizeHandler) createWindowResizeHandler(); - return () => { - windowCallbacks.delete(callback); - if (!windowCallbacks.size && windowResizeHandler) { - windowResizeHandler = undefined; - } - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resize = resize; - var _handleElementEs = __webpack_require__( - /*! ./handle-element.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-element.es.js" - ); - var _handleWindowEs = __webpack_require__( - /*! ./handle-window.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/handle-window.es.js" - ); - function resize(a, b) { - return typeof a === "function" - ? (0, _handleWindowEs.resizeWindow)(a) - : (0, _handleElementEs.resizeElement)(a, b); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.scroll = scroll; - var _tslib = __webpack_require__( - /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" - ); - var _indexEs = __webpack_require__( - /*! ../resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js" - ); - var _infoEs = __webpack_require__( - /*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js" - ); - var _onScrollHandlerEs = __webpack_require__( - /*! ./on-scroll-handler.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js" - ); - const scrollListeners = new WeakMap(); - const resizeListeners = new WeakMap(); - const onScrollHandlers = new WeakMap(); - const getEventTarget = (element) => - element === document.documentElement ? window : element; - function scroll(onScroll, _a = {}) { - var { container = document.documentElement } = _a, - options = (0, _tslib.__rest)(_a, ["container"]); - let containerHandlers = onScrollHandlers.get(container); - /** - * Get the onScroll handlers for this container. - * If one isn't found, create a new one. - */ - if (!containerHandlers) { - containerHandlers = new Set(); - onScrollHandlers.set(container, containerHandlers); - } - /** - * Create a new onScroll handler for the provided callback. - */ - const info = (0, _infoEs.createScrollInfo)(); - const containerHandler = (0, - _onScrollHandlerEs.createOnScrollHandler)( - container, - onScroll, - info, - options - ); - containerHandlers.add(containerHandler); - /** - * Check if there's a scroll event listener for this container. - * If not, create one. - */ - if (!scrollListeners.has(container)) { - const listener = () => { - const time = performance.now(); - for (const handler of containerHandlers) handler.measure(); - for (const handler of containerHandlers) handler.update(time); - for (const handler of containerHandlers) handler.notify(); - }; - scrollListeners.set(container, listener); - const target = getEventTarget(container); - window.addEventListener("resize", listener, { - passive: true, - }); - if (container !== document.documentElement) { - resizeListeners.set( - container, - (0, _indexEs.resize)(container, listener) - ); - } - target.addEventListener("scroll", listener, { - passive: true, - }); - } - const listener = scrollListeners.get(container); - const onLoadProcesss = requestAnimationFrame(listener); - return () => { - var _a; - if (typeof onScroll !== "function") onScroll.stop(); - cancelAnimationFrame(onLoadProcesss); - /** - * Check if we even have any handlers for this container. - */ - const containerHandlers = onScrollHandlers.get(container); - if (!containerHandlers) return; - containerHandlers.delete(containerHandler); - if (containerHandlers.size) return; - /** - * If no more handlers, remove the scroll listener too. - */ - const listener = scrollListeners.get(container); - scrollListeners.delete(container); - if (listener) { - getEventTarget(container).removeEventListener("scroll", listener); - (_a = resizeListeners.get(container)) === null || _a === void 0 - ? void 0 - : _a(); - window.removeEventListener("resize", listener); - } - }; + if (valueOffset[0] !== 0) { + valueOffset.unshift(0); + keyframes.unshift(keyframes[0]); + valueEasing.unshift("linear"); } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js ***! - \****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createScrollInfo = void 0; - exports.updateScrollInfo = updateScrollInfo; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); /** - * A time in milliseconds, beyond which we consider the scroll velocity to be 0. + * If the last keyframe doesn't land on offset: 1 + * provide one with a null wildcard value. This will ensure it + * stays static until the end of the animation. */ - const maxElapsed = 50; - const createAxisInfo = () => ({ - current: 0, - offset: [], - progress: 0, - scrollLength: 0, - targetOffset: 0, - targetLength: 0, - containerLength: 0, - velocity: 0, - }); - const createScrollInfo = () => ({ - time: 0, - x: createAxisInfo(), - y: createAxisInfo(), - }); - exports.createScrollInfo = createScrollInfo; - const keys = { - x: { - length: "Width", - position: "Left", - }, - y: { - length: "Height", - position: "Top", - }, - }; - function updateAxisInfo(element, axisName, info, time) { - const axis = info[axisName]; - const { length, position } = keys[axisName]; - const prev = axis.current; - const prevTime = info.time; - axis.current = element["scroll" + position]; - axis.scrollLength = - element["scroll" + length] - element["client" + length]; - axis.offset.length = 0; - axis.offset[0] = 0; - axis.offset[1] = axis.scrollLength; - axis.progress = (0, _utils.progress)( - 0, - axis.scrollLength, - axis.current - ); - const elapsed = time - prevTime; - axis.velocity = - elapsed > maxElapsed - ? 0 - : (0, _utils.velocityPerSecond)(axis.current - prev, elapsed); - } - function updateScrollInfo(element, info, time) { - updateAxisInfo(element, "x", info, time); - updateAxisInfo(element, "y", info, time); - info.time = time; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js": - /*!************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js ***! - \************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.namedEdges = void 0; - exports.resolveEdge = resolveEdge; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - const namedEdges = (exports.namedEdges = { - start: 0, - center: 0.5, - end: 1, - }); - function resolveEdge(edge, length, inset = 0) { - let delta = 0; - /** - * If we have this edge defined as a preset, replace the definition - * with the numerical value. - */ - if (namedEdges[edge] !== undefined) { - edge = namedEdges[edge]; - } - /** - * Handle unit values - */ - if ((0, _utils.isString)(edge)) { - const asNumber = parseFloat(edge); - if (edge.endsWith("px")) { - delta = asNumber; - } else if (edge.endsWith("%")) { - edge = asNumber / 100; - } else if (edge.endsWith("vw")) { - delta = (asNumber / 100) * document.documentElement.clientWidth; - } else if (edge.endsWith("vh")) { - delta = (asNumber / 100) * document.documentElement.clientHeight; - } else { - edge = asNumber; - } - } - /** - * If the edge is defined as a number, handle as a progress value. - */ - if ((0, _utils.isNumber)(edge)) { - delta = length * edge; - } - return inset + delta; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js": - /*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js ***! - \*************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resolveOffsets = resolveOffsets; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _insetEs = __webpack_require__( - /*! ./inset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js" - ); - var _presetsEs = __webpack_require__( - /*! ./presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js" - ); - var _offsetEs = __webpack_require__( - /*! ./offset.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js" - ); - const point = { - x: 0, - y: 0, - }; - function resolveOffsets(container, info, options) { - let { offset: offsetDefinition = _presetsEs.ScrollOffset.All } = - options; - const { target = container, axis = "y" } = options; - const lengthLabel = axis === "y" ? "height" : "width"; - const inset = - target !== container - ? (0, _insetEs.calcInset)(target, container) - : point; - /** - * Measure the target and container. If they're the same thing then we - * use the container's scrollWidth/Height as the target, from there - * all other calculations can remain the same. - */ - const targetSize = - target === container - ? { - width: container.scrollWidth, - height: container.scrollHeight, - } - : { - width: target.clientWidth, - height: target.clientHeight, - }; - const containerSize = { - width: container.clientWidth, - height: container.clientHeight, - }; - /** - * Reset the length of the resolved offset array rather than creating a new one. - * TODO: More reusable data structures for targetSize/containerSize would also be good. - */ - info[axis].offset.length = 0; - /** - * Populate the offset array by resolving the user's offset definition into - * a list of pixel scroll offets. - */ - let hasChanged = !info[axis].interpolate; - const numOffsets = offsetDefinition.length; - for (let i = 0; i < numOffsets; i++) { - const offset = (0, _offsetEs.resolveOffset)( - offsetDefinition[i], - containerSize[lengthLabel], - targetSize[lengthLabel], - inset[axis] - ); - if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) { - hasChanged = true; - } - info[axis].offset[i] = offset; - } - /** - * If the pixel scroll offsets have changed, create a new interpolator function - * to map scroll value into a progress. - */ - if (hasChanged) { - info[axis].interpolate = (0, _utils.interpolate)( - (0, _utils.defaultOffset)(numOffsets), - info[axis].offset - ); - info[axis].interpolatorOffsets = [...info[axis].offset]; - } - info[axis].progress = info[axis].interpolate(info[axis].current); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js": - /*!*************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/inset.es.js ***! - \*************************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.calcInset = calcInset; - function calcInset(element, container) { - let inset = { - x: 0, - y: 0, - }; - let current = element; - while (current && current !== container) { - if (current instanceof HTMLElement) { - inset.x += current.offsetLeft; - inset.y += current.offsetTop; - current = current.offsetParent; - } else if ( - current instanceof SVGGraphicsElement && - "getBBox" in current - ) { - const { top, left } = current.getBBox(); - inset.x += left; - inset.y += top; - /** - * Assign the next parent element as the tag. - */ - while (current && current.tagName !== "svg") { - current = current.parentNode; - } - } - } - return inset; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js": - /*!**************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/offset.es.js ***! - \**************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resolveOffset = resolveOffset; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _edgeEs = __webpack_require__( - /*! ./edge.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/edge.es.js" - ); - const defaultOffset = [0, 0]; - function resolveOffset( - offset, - containerLength, - targetLength, - targetInset - ) { - let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset; - let targetPoint = 0; - let containerPoint = 0; - if ((0, _utils.isNumber)(offset)) { - /** - * If we're provided offset: [0, 0.5, 1] then each number x should become - * [x, x], so we default to the behaviour of mapping 0 => 0 of both target - * and container etc. - */ - offsetDefinition = [offset, offset]; - } else if ((0, _utils.isString)(offset)) { - offset = offset.trim(); - if (offset.includes(" ")) { - offsetDefinition = offset.split(" "); - } else { - /** - * If we're provided a definition like "100px" then we want to apply - * that only to the top of the target point, leaving the container at 0. - * Whereas a named offset like "end" should be applied to both. - */ - offsetDefinition = [ - offset, - _edgeEs.namedEdges[offset] ? offset : `0`, - ]; - } - } - targetPoint = (0, _edgeEs.resolveEdge)( - offsetDefinition[0], - targetLength, - targetInset - ); - containerPoint = (0, _edgeEs.resolveEdge)( - offsetDefinition[1], - containerLength - ); - return targetPoint - containerPoint; + if (valueOffset[valueOffset.length - 1] !== 1) { + valueOffset.push(1); + keyframes.push(null); } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js": - /*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js ***! - \***************************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.ScrollOffset = void 0; - const ScrollOffset = (exports.ScrollOffset = { - Enter: [ - [0, 1], - [1, 1], - ], - Exit: [ - [0, 0], - [1, 0], - ], - Any: [ - [1, 0], - [0, 1], - ], - All: [ - [0, 0], - [1, 1], - ], - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js": - /*!*****************************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/gestures/scroll/on-scroll-handler.es.js ***! - \*****************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createOnScrollHandler = createOnScrollHandler; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _infoEs = __webpack_require__( - /*! ./info.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/info.es.js" - ); - var _indexEs = __webpack_require__( - /*! ./offsets/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/index.es.js" - ); - function measure(container, target = container, info) { - /** - * Find inset of target within scrollable container - */ - info.x.targetOffset = 0; - info.y.targetOffset = 0; - if (target !== container) { - let node = target; - while (node && node != container) { - info.x.targetOffset += node.offsetLeft; - info.y.targetOffset += node.offsetTop; - node = node.offsetParent; - } - } - info.x.targetLength = - target === container ? target.scrollWidth : target.clientWidth; - info.y.targetLength = - target === container ? target.scrollHeight : target.clientHeight; - info.x.containerLength = container.clientWidth; - info.y.containerLength = container.clientHeight; - } - function createOnScrollHandler(element, onScroll, info, options = {}) { - const axis = options.axis || "y"; - return { - measure: () => measure(element, options.target, info), - update: (time) => { - (0, _infoEs.updateScrollInfo)(element, info, time); - if (options.offset || options.target) { - (0, _indexEs.resolveOffsets)(element, info, options); - } - }, - notify: - typeof onScroll === "function" - ? () => onScroll(info) - : scrubAnimation(onScroll, info[axis]), - }; - } - function scrubAnimation(controls, axisInfo) { - controls.pause(); - controls.forEachNative((animation, { easing }) => { - var _a, _b; - if (animation.updateDuration) { - if (!easing) animation.easing = _utils.noopReturn; - animation.updateDuration(1); - } else { - const timingOptions = { - duration: 1000, - }; - if (!easing) timingOptions.easing = "linear"; - (_b = - (_a = animation.effect) === null || _a === void 0 - ? void 0 - : _a.updateTiming) === null || _b === void 0 - ? void 0 - : _b.call(_a, timingOptions); - } - }); - return () => { - controls.currentTime = axisInfo.progress; - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/index.es.js": - /*!*************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/index.es.js ***! - \*************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "ScrollOffset", { - enumerable: true, - get: function () { - return _presetsEs.ScrollOffset; - }, - }); - Object.defineProperty(exports, "animate", { - enumerable: true, - get: function () { - return _indexEs.animate; - }, - }); - Object.defineProperty(exports, "animateStyle", { - enumerable: true, - get: function () { - return _animateStyleEs.animateStyle; - }, - }); - Object.defineProperty(exports, "createMotionState", { - enumerable: true, - get: function () { - return _indexEs7.createMotionState; - }, - }); - Object.defineProperty(exports, "createStyleString", { - enumerable: true, - get: function () { - return _styleStringEs.createStyleString; - }, - }); - Object.defineProperty(exports, "createStyles", { - enumerable: true, - get: function () { - return _styleObjectEs.createStyles; - }, - }); - Object.defineProperty(exports, "getAnimationData", { - enumerable: true, - get: function () { - return _dataEs.getAnimationData; - }, - }); - Object.defineProperty(exports, "getStyleName", { - enumerable: true, - get: function () { - return _getStyleNameEs.getStyleName; - }, - }); - Object.defineProperty(exports, "glide", { - enumerable: true, - get: function () { - return _indexEs4.glide; - }, - }); - Object.defineProperty(exports, "inView", { - enumerable: true, - get: function () { - return _inViewEs.inView; - }, - }); - Object.defineProperty(exports, "mountedStates", { - enumerable: true, - get: function () { - return _indexEs7.mountedStates; - }, - }); - Object.defineProperty(exports, "resize", { - enumerable: true, - get: function () { - return _indexEs5.resize; - }, - }); - Object.defineProperty(exports, "scroll", { - enumerable: true, - get: function () { - return _indexEs6.scroll; - }, - }); - Object.defineProperty(exports, "spring", { - enumerable: true, - get: function () { - return _indexEs3.spring; - }, - }); - Object.defineProperty(exports, "stagger", { - enumerable: true, - get: function () { - return _staggerEs.stagger; - }, - }); - Object.defineProperty(exports, "style", { - enumerable: true, - get: function () { - return _styleEs.style; - }, - }); - Object.defineProperty(exports, "timeline", { - enumerable: true, - get: function () { - return _indexEs2.timeline; - }, - }); - Object.defineProperty(exports, "withControls", { - enumerable: true, - get: function () { - return _controlsEs.withControls; - }, - }); - var _indexEs = __webpack_require__( - /*! ./animate/index.es.js */ "../../../node_modules/@motionone/dom/dist/animate/index.es.js" - ); - var _animateStyleEs = __webpack_require__( - /*! ./animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" - ); - var _indexEs2 = __webpack_require__( - /*! ./timeline/index.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js" - ); - var _staggerEs = __webpack_require__( - /*! ./utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js" - ); - var _indexEs3 = __webpack_require__( - /*! ./easing/spring/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/spring/index.es.js" - ); - var _indexEs4 = __webpack_require__( - /*! ./easing/glide/index.es.js */ "../../../node_modules/@motionone/dom/dist/easing/glide/index.es.js" - ); - var _styleEs = __webpack_require__( - /*! ./animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js" - ); - var _inViewEs = __webpack_require__( - /*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js" - ); - var _indexEs5 = __webpack_require__( - /*! ./gestures/resize/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/resize/index.es.js" - ); - var _indexEs6 = __webpack_require__( - /*! ./gestures/scroll/index.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/index.es.js" - ); - var _presetsEs = __webpack_require__( - /*! ./gestures/scroll/offsets/presets.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/scroll/offsets/presets.es.js" - ); - var _controlsEs = __webpack_require__( - /*! ./animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js" - ); - var _dataEs = __webpack_require__( - /*! ./animate/data.es.js */ "../../../node_modules/@motionone/dom/dist/animate/data.es.js" - ); - var _getStyleNameEs = __webpack_require__( - /*! ./animate/utils/get-style-name.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/get-style-name.es.js" - ); - var _indexEs7 = __webpack_require__( - /*! ./state/index.es.js */ "../../../node_modules/@motionone/dom/dist/state/index.es.js" - ); - var _styleObjectEs = __webpack_require__( - /*! ./animate/utils/style-object.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-object.es.js" - ); - var _styleStringEs = __webpack_require__( - /*! ./animate/utils/style-string.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/style-string.es.js" - ); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js ***! - \****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.hover = void 0; - var _eventsEs = __webpack_require__( - /*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" - ); - const mouseEvent = (element, name, action) => (event) => { - if (event.pointerType && event.pointerType !== "mouse") return; - action(); - (0, _eventsEs.dispatchPointerEvent)(element, name, event); - }; - const hover = (exports.hover = { - isActive: (options) => Boolean(options.hover), - subscribe: (element, { enable, disable }) => { - const onEnter = mouseEvent(element, "hoverstart", enable); - const onLeave = mouseEvent(element, "hoverend", disable); - element.addEventListener("pointerenter", onEnter); - element.addEventListener("pointerleave", onLeave); - return () => { - element.removeEventListener("pointerenter", onEnter); - element.removeEventListener("pointerleave", onLeave); - }; - }, - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js ***! - \******************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.inView = void 0; - var _tslib = __webpack_require__( - /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" - ); - var _eventsEs = __webpack_require__( - /*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" - ); - var _inViewEs = __webpack_require__( - /*! ../../gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/gestures/in-view.es.js" - ); - const inView = (exports.inView = { - isActive: (options) => Boolean(options.inView), - subscribe: (element, { enable, disable }, { inViewOptions = {} }) => { - const { once } = inViewOptions, - viewOptions = (0, _tslib.__rest)(inViewOptions, ["once"]); - return (0, _inViewEs.inView)( - element, - (enterEntry) => { - enable(); - (0, _eventsEs.dispatchViewEvent)( - element, - "viewenter", - enterEntry - ); - if (!once) { - return (leaveEntry) => { - disable(); - (0, _eventsEs.dispatchViewEvent)( - element, - "viewleave", - leaveEntry - ); - }; - } - }, - viewOptions - ); - }, - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js ***! - \****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.press = void 0; - var _eventsEs = __webpack_require__( - /*! ../utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" - ); - const press = (exports.press = { - isActive: (options) => Boolean(options.press), - subscribe: (element, { enable, disable }) => { - const onPointerUp = (event) => { - disable(); - (0, _eventsEs.dispatchPointerEvent)(element, "pressend", event); - window.removeEventListener("pointerup", onPointerUp); - }; - const onPointerDown = (event) => { - enable(); - (0, _eventsEs.dispatchPointerEvent)(element, "pressstart", event); - window.addEventListener("pointerup", onPointerUp); - }; - element.addEventListener("pointerdown", onPointerDown); - return () => { - element.removeEventListener("pointerdown", onPointerDown); - window.removeEventListener("pointerup", onPointerUp); - }; - }, - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/index.es.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/index.es.js ***! - \*******************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createMotionState = createMotionState; - exports.mountedStates = void 0; - var _tslib = __webpack_require__( - /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" - ); - var _heyListen = __webpack_require__( - /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" - ); - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _animateStyleEs = __webpack_require__( - /*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" - ); - var _styleEs = __webpack_require__( - /*! ../animate/style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/style.es.js" - ); - var _optionsEs = __webpack_require__( - /*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js" - ); - var _hasChangedEs = __webpack_require__( - /*! ./utils/has-changed.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js" - ); - var _resolveVariantEs = __webpack_require__( - /*! ./utils/resolve-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js" - ); - var _scheduleEs = __webpack_require__( - /*! ./utils/schedule.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js" - ); - var _inViewEs = __webpack_require__( - /*! ./gestures/in-view.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/in-view.es.js" - ); - var _hoverEs = __webpack_require__( - /*! ./gestures/hover.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/hover.es.js" - ); - var _pressEs = __webpack_require__( - /*! ./gestures/press.es.js */ "../../../node_modules/@motionone/dom/dist/state/gestures/press.es.js" - ); - var _eventsEs = __webpack_require__( - /*! ./utils/events.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js" - ); - const gestures = { - inView: _inViewEs.inView, - hover: _hoverEs.hover, - press: _pressEs.press, - }; - /** - * A list of state types, in priority order. If a value is defined in - * a righter-most type, it will override any definition in a lefter-most. - */ - const stateTypes = [ - "initial", - "animate", - ...Object.keys(gestures), - "exit", - ]; - /** - * A global store of all generated motion states. This can be used to lookup - * a motion state for a given Element. - */ - const mountedStates = (exports.mountedStates = new WeakMap()); - function createMotionState(options = {}, parent) { - /** - * The element represented by the motion state. This is an empty reference - * when we create the state to support SSR and allow for later mounting - * in view libraries. - * - * @ts-ignore - */ - let element; - /** - * Calculate a depth that we can use to order motion states by tree depth. - */ - let depth = parent ? parent.getDepth() + 1 : 0; - /** - * Track which states are currently active. - */ - const activeStates = { - initial: true, - animate: true, - }; - /** - * A map of functions that, when called, will remove event listeners for - * a given gesture. - */ - const gestureSubscriptions = {}; - /** - * Initialise a context to share through motion states. This - * will be populated by variant names (if any). - */ - const context = {}; - for (const name of stateTypes) { - context[name] = - typeof options[name] === "string" - ? options[name] - : parent === null || parent === void 0 - ? void 0 - : parent.getContext()[name]; - } - /** - * If initial is set to false we use the animate prop as the initial - * animation state. - */ - const initialVariantSource = - options.initial === false ? "animate" : "initial"; - /** - * Destructure an initial target out from the resolved initial variant. - */ - let _a = - (0, _resolveVariantEs.resolveVariant)( - options[initialVariantSource] || context[initialVariantSource], - options.variants - ) || {}, - target = (0, _tslib.__rest)(_a, ["transition"]); - /** - * The base target is a cached map of values that we'll use to animate - * back to if a value is removed from all active state types. This - * is usually the initial value as read from the DOM, for instance if - * it hasn't been defined in initial. - */ - const baseTarget = Object.assign({}, target); - /** - * A generator that will be processed by the global animation scheduler. - * This yeilds when it switches from reading the DOM to writing to it - * to prevent layout thrashing. - */ - function* animateUpdates() { - var _a, _b; - const prevTarget = target; - target = {}; - const animationOptions = {}; - for (const name of stateTypes) { - if (!activeStates[name]) continue; - const variant = (0, _resolveVariantEs.resolveVariant)( - options[name] - ); - if (!variant) continue; - for (const key in variant) { - if (key === "transition") continue; - target[key] = variant[key]; - animationOptions[key] = (0, _optionsEs.getOptions)( - (_b = - (_a = variant.transition) !== null && _a !== void 0 - ? _a - : options.transition) !== null && _b !== void 0 - ? _b - : {}, - key - ); - } - } - const allTargetKeys = new Set([ - ...Object.keys(target), - ...Object.keys(prevTarget), - ]); - const animationFactories = []; - allTargetKeys.forEach((key) => { - var _a; - if (target[key] === undefined) { - target[key] = baseTarget[key]; - } - if ((0, _hasChangedEs.hasChanged)(prevTarget[key], target[key])) { - (_a = baseTarget[key]) !== null && _a !== void 0 - ? _a - : (baseTarget[key] = _styleEs.style.get(element, key)); - animationFactories.push( - (0, _animateStyleEs.animateStyle)( - element, - key, - target[key], - animationOptions[key] - ) - ); - } - }); - // Wait for all animation states to read from the DOM - yield; - const animations = animationFactories - .map((factory) => factory()) - .filter(Boolean); - if (!animations.length) return; - const animationTarget = target; - element.dispatchEvent( - (0, _eventsEs.motionEvent)("motionstart", animationTarget) - ); - Promise.all(animations.map((animation) => animation.finished)) - .then(() => { - element.dispatchEvent( - (0, _eventsEs.motionEvent)("motioncomplete", animationTarget) - ); - }) - .catch(_utils.noop); - } - const setGesture = (name, isActive) => () => { - activeStates[name] = isActive; - (0, _scheduleEs.scheduleAnimation)(state); - }; - const updateGestureSubscriptions = () => { - for (const name in gestures) { - const isGestureActive = gestures[name].isActive(options); - const remove = gestureSubscriptions[name]; - if (isGestureActive && !remove) { - gestureSubscriptions[name] = gestures[name].subscribe( - element, - { - enable: setGesture(name, true), - disable: setGesture(name, false), - }, - options - ); - } else if (!isGestureActive && remove) { - remove(); - delete gestureSubscriptions[name]; - } - } - }; - const state = { - update: (newOptions) => { - if (!element) return; - options = newOptions; - updateGestureSubscriptions(); - (0, _scheduleEs.scheduleAnimation)(state); - }, - setActive: (name, isActive) => { - if (!element) return; - activeStates[name] = isActive; - (0, _scheduleEs.scheduleAnimation)(state); - }, - animateUpdates, - getDepth: () => depth, - getTarget: () => target, - getOptions: () => options, - getContext: () => context, - mount: (newElement) => { - (0, _heyListen.invariant)( - Boolean(newElement), - "Animation state must be mounted with valid Element" - ); - element = newElement; - mountedStates.set(element, state); - updateGestureSubscriptions(); - return () => { - mountedStates.delete(element); - (0, _scheduleEs.unscheduleAnimation)(state); - for (const key in gestureSubscriptions) { - gestureSubscriptions[key](); - } - }; - }, - isMounted: () => Boolean(element), - }; - return state; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/utils/events.es.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/events.es.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.dispatchPointerEvent = dispatchPointerEvent; - exports.dispatchViewEvent = dispatchViewEvent; - exports.motionEvent = void 0; - const motionEvent = (name, target) => - new CustomEvent(name, { - detail: { - target, - }, - }); - exports.motionEvent = motionEvent; - function dispatchPointerEvent(element, name, event) { - element.dispatchEvent( - new CustomEvent(name, { - detail: { - originalEvent: event, - }, - }) - ); - } - function dispatchViewEvent(element, name, entry) { - element.dispatchEvent( - new CustomEvent(name, { - detail: { - originalEntry: entry, - }, - }) - ); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js": - /*!*******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/has-changed.es.js ***! - \*******************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.hasChanged = hasChanged; - exports.shallowCompare = shallowCompare; - function hasChanged(a, b) { - if (typeof a !== typeof b) return true; - if (Array.isArray(a) && Array.isArray(b)) - return !shallowCompare(a, b); - return a !== b; - } - function shallowCompare(next, prev) { - const prevLength = prev.length; - if (prevLength !== next.length) return false; - for (let i = 0; i < prevLength; i++) { - if (prev[i] !== next[i]) return false; - } - return true; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js ***! - \******************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isVariant = isVariant; - function isVariant(definition) { - return typeof definition === "object"; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/resolve-variant.es.js ***! - \***********************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resolveVariant = resolveVariant; - var _isVariantEs = __webpack_require__( - /*! ./is-variant.es.js */ "../../../node_modules/@motionone/dom/dist/state/utils/is-variant.es.js" - ); - function resolveVariant(definition, variants) { - if ((0, _isVariantEs.isVariant)(definition)) { - return definition; - } else if (definition && variants) { - return variants[definition]; - } - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/state/utils/schedule.es.js ***! - \****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.scheduleAnimation = scheduleAnimation; - exports.unscheduleAnimation = unscheduleAnimation; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - let scheduled = undefined; - function processScheduledAnimations() { - if (!scheduled) return; - const generators = scheduled - .sort(compareByDepth) - .map(fireAnimateUpdates); - generators.forEach(fireNext); - generators.forEach(fireNext); - scheduled = undefined; - } - function scheduleAnimation(state) { - if (!scheduled) { - scheduled = [state]; - requestAnimationFrame(processScheduledAnimations); - } else { - (0, _utils.addUniqueItem)(scheduled, state); - } - } - function unscheduleAnimation(state) { - scheduled && (0, _utils.removeItem)(scheduled, state); - } - const compareByDepth = (a, b) => a.getDepth() - b.getDepth(); - const fireAnimateUpdates = (state) => state.animateUpdates(); - const fireNext = (iterator) => iterator.next(); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/timeline/index.es.js": - /*!**********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/index.es.js ***! - \**********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createAnimationsFromTimeline = createAnimationsFromTimeline; - exports.timeline = timeline; - var _tslib = __webpack_require__( - /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" - ); - var _heyListen = __webpack_require__( - /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" - ); - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _staggerEs = __webpack_require__( - /*! ../utils/stagger.es.js */ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js" - ); - var _animateStyleEs = __webpack_require__( - /*! ../animate/animate-style.es.js */ "../../../node_modules/@motionone/dom/dist/animate/animate-style.es.js" - ); - var _controlsEs = __webpack_require__( - /*! ../animate/utils/controls.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/controls.es.js" - ); - var _keyframesEs = __webpack_require__( - /*! ../animate/utils/keyframes.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/keyframes.es.js" - ); - var _optionsEs = __webpack_require__( - /*! ../animate/utils/options.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/options.es.js" - ); - var _resolveElementsEs = __webpack_require__( - /*! ../utils/resolve-elements.es.js */ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js" - ); - var _transformsEs = __webpack_require__( - /*! ../animate/utils/transforms.es.js */ "../../../node_modules/@motionone/dom/dist/animate/utils/transforms.es.js" - ); - var _calcTimeEs = __webpack_require__( - /*! ./utils/calc-time.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js" - ); - var _editEs = __webpack_require__( - /*! ./utils/edit.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js" - ); - var _sortEs = __webpack_require__( - /*! ./utils/sort.es.js */ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js" - ); - function timeline(definition, options = {}) { - var _a; - const animationDefinitions = createAnimationsFromTimeline( - definition, - options - ); - /** - * Create and start animations - */ - const animationFactories = animationDefinitions - .map((definition) => - (0, _animateStyleEs.animateStyle)(...definition) - ) - .filter(Boolean); - return (0, _controlsEs.withControls)( - animationFactories, - options, - // Get the duration from the first animation definition - (_a = animationDefinitions[0]) === null || _a === void 0 - ? void 0 - : _a[3].duration - ); - } - function createAnimationsFromTimeline(definition, _a = {}) { - var { defaultOptions = {} } = _a, - timelineOptions = (0, _tslib.__rest)(_a, ["defaultOptions"]); - const animationDefinitions = []; - const elementSequences = new Map(); - const elementCache = {}; - const timeLabels = new Map(); - let prevTime = 0; - let currentTime = 0; - let totalDuration = 0; - /** - * Build the timeline by mapping over the definition array and converting - * the definitions into keyframes and offsets with absolute time values. - * These will later get converted into relative offsets in a second pass. - */ - for (let i = 0; i < definition.length; i++) { - const segment = definition[i]; - /** - * If this is a timeline label, mark it and skip the rest of this iteration. - */ - if ((0, _utils.isString)(segment)) { - timeLabels.set(segment, currentTime); - continue; - } else if (!Array.isArray(segment)) { - timeLabels.set( - segment.name, - (0, _calcTimeEs.calcNextTime)( - currentTime, - segment.at, - prevTime, - timeLabels - ) - ); - continue; - } - const [elementDefinition, keyframes, options = {}] = segment; - /** - * If a relative or absolute time value has been specified we need to resolve - * it in relation to the currentTime. - */ - if (options.at !== undefined) { - currentTime = (0, _calcTimeEs.calcNextTime)( - currentTime, - options.at, - prevTime, - timeLabels - ); - } - /** - * Keep track of the maximum duration in this definition. This will be - * applied to currentTime once the definition has been parsed. - */ - let maxDuration = 0; - /** - * Find all the elements specified in the definition and parse value - * keyframes from their timeline definitions. - */ - const elements = (0, _resolveElementsEs.resolveElements)( - elementDefinition, - elementCache - ); - const numElements = elements.length; - for ( - let elementIndex = 0; - elementIndex < numElements; - elementIndex++ - ) { - const element = elements[elementIndex]; - const elementSequence = getElementSequence( - element, - elementSequences - ); - for (const key in keyframes) { - const valueSequence = getValueSequence(key, elementSequence); - let valueKeyframes = (0, _keyframesEs.keyframesList)( - keyframes[key] - ); - const valueOptions = (0, _optionsEs.getOptions)(options, key); - let { - duration = defaultOptions.duration || - _utils.defaults.duration, - easing = defaultOptions.easing || _utils.defaults.easing, - } = valueOptions; - if ((0, _utils.isEasingGenerator)(easing)) { - const valueIsTransform = (0, _transformsEs.isTransform)(key); - (0, _heyListen.invariant)( - valueKeyframes.length === 2 || !valueIsTransform, - "spring must be provided 2 keyframes within timeline" - ); - const custom = easing.createAnimation( - valueKeyframes, - // TODO We currently only support explicit keyframes - // so this doesn't currently read from the DOM - () => "0", - valueIsTransform - ); - easing = custom.easing; - if (custom.keyframes !== undefined) - valueKeyframes = custom.keyframes; - if (custom.duration !== undefined) duration = custom.duration; - } - const delay = - (0, _staggerEs.resolveOption)( - options.delay, - elementIndex, - numElements - ) || 0; - const startTime = currentTime + delay; - const targetTime = startTime + duration; - /** - * - */ - let { - offset = (0, _utils.defaultOffset)(valueKeyframes.length), - } = valueOptions; - /** - * If there's only one offset of 0, fill in a second with length 1 - * - * TODO: Ensure there's a test that covers this removal - */ - if (offset.length === 1 && offset[0] === 0) { - offset[1] = 1; - } - /** - * Fill out if offset if fewer offsets than keyframes - */ - const remainder = length - valueKeyframes.length; - remainder > 0 && (0, _utils.fillOffset)(offset, remainder); - /** - * If only one value has been set, ie [1], push a null to the start of - * the keyframe array. This will let us mark a keyframe at this point - * that will later be hydrated with the previous value. - */ - valueKeyframes.length === 1 && valueKeyframes.unshift(null); - /** - * Add keyframes, mapping offsets to absolute time. - */ - (0, _editEs.addKeyframes)( - valueSequence, - valueKeyframes, - easing, - offset, - startTime, - targetTime - ); - maxDuration = Math.max(delay + duration, maxDuration); - totalDuration = Math.max(targetTime, totalDuration); - } - } - prevTime = currentTime; - currentTime += maxDuration; - } - /** - * For every element and value combination create a new animation. - */ - elementSequences.forEach((valueSequences, element) => { - for (const key in valueSequences) { - const valueSequence = valueSequences[key]; - /** - * Arrange all the keyframes in ascending time order. - */ - valueSequence.sort(_sortEs.compareByTime); - const keyframes = []; - const valueOffset = []; - const valueEasing = []; - /** - * For each keyframe, translate absolute times into - * relative offsets based on the total duration of the timeline. - */ - for (let i = 0; i < valueSequence.length; i++) { - const { at, value, easing } = valueSequence[i]; - keyframes.push(value); - valueOffset.push((0, _utils.progress)(0, totalDuration, at)); - valueEasing.push(easing || _utils.defaults.easing); - } - /** - * If the first keyframe doesn't land on offset: 0 - * provide one by duplicating the initial keyframe. This ensures - * it snaps to the first keyframe when the animation starts. - */ - if (valueOffset[0] !== 0) { - valueOffset.unshift(0); - keyframes.unshift(keyframes[0]); - valueEasing.unshift("linear"); - } - /** - * If the last keyframe doesn't land on offset: 1 - * provide one with a null wildcard value. This will ensure it - * stays static until the end of the animation. - */ - if (valueOffset[valueOffset.length - 1] !== 1) { - valueOffset.push(1); - keyframes.push(null); - } - animationDefinitions.push([ - element, - key, - keyframes, - Object.assign( - Object.assign(Object.assign({}, defaultOptions), { - duration: totalDuration, - easing: valueEasing, - offset: valueOffset, - }), - timelineOptions - ), - ]); - } - }); - return animationDefinitions; - } - function getElementSequence(element, sequences) { - !sequences.has(element) && sequences.set(element, {}); - return sequences.get(element); - } - function getValueSequence(name, sequences) { - if (!sequences[name]) sequences[name] = []; - return sequences[name]; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js": - /*!********************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/calc-time.es.js ***! - \********************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.calcNextTime = calcNextTime; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - function calcNextTime(current, next, prev, labels) { - var _a; - if ((0, _utils.isNumber)(next)) { - return next; - } else if (next.startsWith("-") || next.startsWith("+")) { - return Math.max(0, current + parseFloat(next)); - } else if (next === "<") { - return prev; - } else { - return (_a = labels.get(next)) !== null && _a !== void 0 - ? _a - : current; - } - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/edit.es.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.addKeyframes = addKeyframes; - exports.eraseKeyframes = eraseKeyframes; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - function eraseKeyframes(sequence, startTime, endTime) { - for (let i = 0; i < sequence.length; i++) { - const keyframe = sequence[i]; - if (keyframe.at > startTime && keyframe.at < endTime) { - (0, _utils.removeItem)(sequence, keyframe); - // If we remove this item we have to push the pointer back one - i--; - } - } - } - function addKeyframes( - sequence, - keyframes, - easing, - offset, - startTime, - endTime - ) { - /** - * Erase every existing value between currentTime and targetTime, - * this will essentially splice this timeline into any currently - * defined ones. - */ - eraseKeyframes(sequence, startTime, endTime); - for (let i = 0; i < keyframes.length; i++) { - sequence.push({ - value: keyframes[i], - at: (0, _utils.mix)(startTime, endTime, offset[i]), - easing: (0, _utils.getEasingForSegment)(easing, i), - }); - } - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/timeline/utils/sort.es.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.compareByTime = compareByTime; - function compareByTime(a, b) { - if (a.at === b.at) { - return a.value === null ? 1 : -1; - } else { - return a.at - b.at; - } - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/utils/resolve-elements.es.js ***! - \******************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.resolveElements = resolveElements; - function resolveElements(elements, selectorCache) { - var _a; - if (typeof elements === "string") { - if (selectorCache) { - (_a = selectorCache[elements]) !== null && _a !== void 0 - ? _a - : (selectorCache[elements] = - document.querySelectorAll(elements)); - elements = selectorCache[elements]; - } else { - elements = document.querySelectorAll(elements); - } - } else if (elements instanceof Element) { - elements = [elements]; - } - /** - * Return an empty array - */ - return Array.from(elements || []); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/dom/dist/utils/stagger.es.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/dom/dist/utils/stagger.es.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getFromIndex = getFromIndex; - exports.resolveOption = resolveOption; - exports.stagger = stagger; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _animation = __webpack_require__( - /*! @motionone/animation */ "../../../node_modules/@motionone/animation/dist/index.es.js" - ); - function stagger(duration = 0.1, { start = 0, from = 0, easing } = {}) { - return (i, total) => { - const fromIndex = (0, _utils.isNumber)(from) - ? from - : getFromIndex(from, total); - const distance = Math.abs(fromIndex - i); - let delay = duration * distance; - if (easing) { - const maxDelay = total * duration; - const easingFunction = (0, _animation.getEasingFunction)(easing); - delay = easingFunction(delay / maxDelay) * maxDelay; - } - return start + delay; - }; - } - function getFromIndex(from, total) { - if (from === "first") { - return 0; - } else { - const lastIndex = total - 1; - return from === "last" ? lastIndex : lastIndex / 2; - } - } - function resolveOption(option, i, total) { - return typeof option === "function" ? option(i, total) : option; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js ***! - \***********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.cubicBezier = cubicBezier; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - /* - Bezier function generator - - This has been modified from Gaëtan Renaudeau's BezierEasing - https://github.com/gre/bezier-easing/blob/master/src/index.js - https://github.com/gre/bezier-easing/blob/master/LICENSE - - I've removed the newtonRaphsonIterate algo because in benchmarking it - wasn't noticiably faster than binarySubdivision, indeed removing it - usually improved times, depending on the curve. - - I also removed the lookup table, as for the added bundle size and loop we're - only cutting ~4 or so subdivision iterations. I bumped the max iterations up - to 12 to compensate and this still tended to be faster for no perceivable - loss in accuracy. - - Usage - const easeOut = cubicBezier(.17,.67,.83,.67); - const x = easeOut(0.5); // returns 0.627... -*/ - // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. - const calcBezier = (t, a1, a2) => - (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + - 3.0 * a1) * - t; - const subdivisionPrecision = 0.0000001; - const subdivisionMaxIterations = 12; - function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { - let currentX; - let currentT; - let i = 0; - do { - currentT = lowerBound + (upperBound - lowerBound) / 2.0; - currentX = calcBezier(currentT, mX1, mX2) - x; - if (currentX > 0.0) { - upperBound = currentT; - } else { - lowerBound = currentT; - } - } while ( - Math.abs(currentX) > subdivisionPrecision && - ++i < subdivisionMaxIterations - ); - return currentT; - } - function cubicBezier(mX1, mY1, mX2, mY2) { - // If this is a linear gradient, return linear easing - if (mX1 === mY1 && mX2 === mY2) return _utils.noopReturn; - const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2); - // If animation is at start/end, return t without easing - return (t) => - t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/easing/dist/index.es.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/index.es.js ***! - \****************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "cubicBezier", { - enumerable: true, - get: function () { - return _cubicBezierEs.cubicBezier; - }, - }); - Object.defineProperty(exports, "steps", { - enumerable: true, - get: function () { - return _stepsEs.steps; - }, - }); - var _cubicBezierEs = __webpack_require__( - /*! ./cubic-bezier.es.js */ "../../../node_modules/@motionone/easing/dist/cubic-bezier.es.js" - ); - var _stepsEs = __webpack_require__( - /*! ./steps.es.js */ "../../../node_modules/@motionone/easing/dist/steps.es.js" - ); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/easing/dist/steps.es.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/easing/dist/steps.es.js ***! - \****************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.steps = void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - const steps = - (steps, direction = "end") => - (progress) => { - progress = - direction === "end" - ? Math.min(progress, 0.999) - : Math.max(progress, 0.001); - const expanded = progress * steps; - const rounded = - direction === "end" ? Math.floor(expanded) : Math.ceil(expanded); - return (0, _utils.clamp)(0, 1, rounded / steps); - }; - exports.steps = steps; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/glide/index.es.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/glide/index.es.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.glide = void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _velocityEs = __webpack_require__( - /*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js" - ); - var _indexEs = __webpack_require__( - /*! ../spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js" - ); - const glide = ({ - from = 0, - velocity = 0.0, - power = 0.8, - decay = 0.325, - bounceDamping, - bounceStiffness, - changeTarget, - min, - max, - restDistance = 0.5, - restSpeed, - }) => { - decay = _utils.time.ms(decay); - const state = { - hasReachedTarget: false, - done: false, - current: from, - target: from, - }; - const isOutOfBounds = (v) => - (min !== undefined && v < min) || (max !== undefined && v > max); - const nearestBoundary = (v) => { - if (min === undefined) return max; - if (max === undefined) return min; - return Math.abs(min - v) < Math.abs(max - v) ? min : max; - }; - let amplitude = power * velocity; - const ideal = from + amplitude; - const target = - changeTarget === undefined ? ideal : changeTarget(ideal); - state.target = target; - /** - * If the target has changed we need to re-calculate the amplitude, otherwise - * the animation will start from the wrong position. - */ - if (target !== ideal) amplitude = target - from; - const calcDelta = (t) => -amplitude * Math.exp(-t / decay); - const calcLatest = (t) => target + calcDelta(t); - const applyFriction = (t) => { - const delta = calcDelta(t); - const latest = calcLatest(t); - state.done = Math.abs(delta) <= restDistance; - state.current = state.done ? target : latest; - }; - /** - * Ideally this would resolve for t in a stateless way, we could - * do that by always precalculating the animation but as we know - * this will be done anyway we can assume that spring will - * be discovered during that. - */ - let timeReachedBoundary; - let spring$1; - const checkCatchBoundary = (t) => { - if (!isOutOfBounds(state.current)) return; - timeReachedBoundary = t; - spring$1 = (0, _indexEs.spring)({ - from: state.current, - to: nearestBoundary(state.current), - velocity: (0, _velocityEs.calcGeneratorVelocity)( - calcLatest, - t, - state.current - ), - damping: bounceDamping, - stiffness: bounceStiffness, - restDistance, - restSpeed, - }); - }; - checkCatchBoundary(0); - return (t) => { - /** - * We need to resolve the friction to figure out if we need a - * spring but we don't want to do this twice per frame. So here - * we flag if we updated for this frame and later if we did - * we can skip doing it again. - */ - let hasUpdatedFrame = false; - if (!spring$1 && timeReachedBoundary === undefined) { - hasUpdatedFrame = true; - applyFriction(t); - checkCatchBoundary(t); - } - /** - * If we have a spring and the provided t is beyond the moment the friction - * animation crossed the min/max boundary, use the spring. - */ - if (timeReachedBoundary !== undefined && t > timeReachedBoundary) { - state.hasReachedTarget = true; - return spring$1(t - timeReachedBoundary); - } else { - state.hasReachedTarget = false; - !hasUpdatedFrame && applyFriction(t); - return state; - } - }; - }; - exports.glide = glide; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/index.es.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/index.es.js ***! - \********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "calcGeneratorVelocity", { - enumerable: true, - get: function () { - return _velocityEs.calcGeneratorVelocity; - }, - }); - Object.defineProperty(exports, "glide", { - enumerable: true, - get: function () { - return _indexEs.glide; - }, - }); - Object.defineProperty(exports, "pregenerateKeyframes", { - enumerable: true, - get: function () { - return _pregenerateKeyframesEs.pregenerateKeyframes; - }, - }); - Object.defineProperty(exports, "spring", { - enumerable: true, - get: function () { - return _indexEs2.spring; - }, - }); - var _indexEs = __webpack_require__( - /*! ./glide/index.es.js */ "../../../node_modules/@motionone/generators/dist/glide/index.es.js" - ); - var _indexEs2 = __webpack_require__( - /*! ./spring/index.es.js */ "../../../node_modules/@motionone/generators/dist/spring/index.es.js" - ); - var _pregenerateKeyframesEs = __webpack_require__( - /*! ./utils/pregenerate-keyframes.es.js */ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js" - ); - var _velocityEs = __webpack_require__( - /*! ./utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js" - ); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/defaults.es.js ***! - \******************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.defaults = void 0; - const defaults = (exports.defaults = { - stiffness: 100.0, - damping: 10.0, - mass: 1.0, - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/spring/index.es.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/index.es.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.spring = void 0; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - var _defaultsEs = __webpack_require__( - /*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js" - ); - var _utilsEs = __webpack_require__( - /*! ./utils.es.js */ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js" - ); - var _hasReachedTargetEs = __webpack_require__( - /*! ../utils/has-reached-target.es.js */ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js" - ); - var _velocityEs = __webpack_require__( - /*! ../utils/velocity.es.js */ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js" - ); - const spring = ({ - stiffness = _defaultsEs.defaults.stiffness, - damping = _defaultsEs.defaults.damping, - mass = _defaultsEs.defaults.mass, - from = 0, - to = 1, - velocity = 0.0, - restSpeed = 2, - restDistance = 0.5, - } = {}) => { - velocity = velocity ? _utils.time.s(velocity) : 0.0; - const state = { - done: false, - hasReachedTarget: false, - current: from, - target: to, - }; - const initialDelta = to - from; - const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; - const dampingRatio = (0, _utilsEs.calcDampingRatio)( - stiffness, - damping, - mass - ); - let resolveSpring; - if (dampingRatio < 1) { - const angularFreq = - undampedAngularFreq * Math.sqrt(1 - dampingRatio * dampingRatio); - // Underdamped spring (bouncy) - resolveSpring = (t) => - to - - Math.exp(-dampingRatio * undampedAngularFreq * t) * - (((-velocity + - dampingRatio * undampedAngularFreq * initialDelta) / - angularFreq) * - Math.sin(angularFreq * t) + - initialDelta * Math.cos(angularFreq * t)); - } else { - // Critically damped spring - resolveSpring = (t) => { - return ( - to - - Math.exp(-undampedAngularFreq * t) * - (initialDelta + - (-velocity + undampedAngularFreq * initialDelta) * t) - ); - }; - } - return (t) => { - state.current = resolveSpring(t); - const currentVelocity = - t === 0 - ? velocity - : (0, _velocityEs.calcGeneratorVelocity)( - resolveSpring, - t, - state.current - ); - const isBelowVelocityThreshold = - Math.abs(currentVelocity) <= restSpeed; - const isBelowDisplacementThreshold = - Math.abs(to - state.current) <= restDistance; - state.done = - isBelowVelocityThreshold && isBelowDisplacementThreshold; - state.hasReachedTarget = (0, _hasReachedTargetEs.hasReachedTarget)( - from, - to, - state.current - ); - return state; - }; - }; - exports.spring = spring; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/spring/utils.es.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/spring/utils.es.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.calcDampingRatio = void 0; - var _defaultsEs = __webpack_require__( - /*! ./defaults.es.js */ "../../../node_modules/@motionone/generators/dist/spring/defaults.es.js" - ); - const calcDampingRatio = ( - stiffness = _defaultsEs.defaults.stiffness, - damping = _defaultsEs.defaults.damping, - mass = _defaultsEs.defaults.mass - ) => damping / (2 * Math.sqrt(stiffness * mass)); - exports.calcDampingRatio = calcDampingRatio; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js": - /*!***************************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/has-reached-target.es.js ***! - \***************************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.hasReachedTarget = hasReachedTarget; - function hasReachedTarget(origin, target, current) { - return ( - (origin < target && current >= target) || - (origin > target && current <= target) - ); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js": - /*!******************************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/pregenerate-keyframes.es.js ***! - \******************************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.pregenerateKeyframes = pregenerateKeyframes; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - const timeStep = 10; - const maxDuration = 10000; - function pregenerateKeyframes(generator, toUnit = _utils.noopReturn) { - let overshootDuration = undefined; - let timestamp = timeStep; - let state = generator(0); - const keyframes = [toUnit(state.current)]; - while (!state.done && timestamp < maxDuration) { - state = generator(timestamp); - keyframes.push(toUnit(state.done ? state.target : state.current)); - if (overshootDuration === undefined && state.hasReachedTarget) { - overshootDuration = timestamp; - } - timestamp += timeStep; - } - const duration = timestamp - timeStep; - /** - * If generating an animation that didn't actually move, - * generate a second keyframe so we have an origin and target. - */ - if (keyframes.length === 1) keyframes.push(state.current); - return { - keyframes, - duration: duration / 1000, - overshootDuration: - (overshootDuration !== null && overshootDuration !== void 0 - ? overshootDuration - : duration) / 1000, - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/generators/dist/utils/velocity.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/generators/dist/utils/velocity.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.calcGeneratorVelocity = calcGeneratorVelocity; - var _utils = __webpack_require__( - /*! @motionone/utils */ "../../../node_modules/@motionone/utils/dist/index.es.js" - ); - const sampleT = 5; // ms - function calcGeneratorVelocity(resolveValue, t, current) { - const prevT = Math.max(t - sampleT, 0); - return (0, _utils.velocityPerSecond)( - current - resolveValue(prevT), - t - prevT - ); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/types/dist/MotionValue.es.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/types/dist/MotionValue.es.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.MotionValue = void 0; - /** - * The MotionValue tracks the state of a single animatable - * value. Currently, updatedAt and current are unused. The - * long term idea is to use this to minimise the number - * of DOM reads, and to abstract the DOM interactions here. - */ - class MotionValue { - setAnimation(animation) { - this.animation = animation; - animation === null || animation === void 0 - ? void 0 - : animation.finished - .then(() => this.clearAnimation()) - .catch(() => {}); - } - clearAnimation() { - this.animation = this.generator = undefined; - } - } - exports.MotionValue = MotionValue; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/types/dist/index.es.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/types/dist/index.es.js ***! - \***************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "MotionValue", { - enumerable: true, - get: function () { - return _MotionValueEs.MotionValue; - }, - }); - var _MotionValueEs = __webpack_require__( - /*! ./MotionValue.es.js */ "../../../node_modules/@motionone/types/dist/MotionValue.es.js" - ); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/array.es.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/array.es.js ***! - \***************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.addUniqueItem = addUniqueItem; - exports.removeItem = removeItem; - function addUniqueItem(array, item) { - array.indexOf(item) === -1 && array.push(item); - } - function removeItem(arr, item) { - const index = arr.indexOf(item); - index > -1 && arr.splice(index, 1); - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/clamp.es.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/clamp.es.js ***! - \***************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.clamp = void 0; - const clamp = (min, max, v) => Math.min(Math.max(v, min), max); - exports.clamp = clamp; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/defaults.es.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/defaults.es.js ***! - \******************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.defaults = void 0; - const defaults = (exports.defaults = { - duration: 0.3, - delay: 0, - endDelay: 0, - repeat: 0, - easing: "ease", - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/easing.es.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/easing.es.js ***! - \****************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getEasingForSegment = getEasingForSegment; - var _isEasingListEs = __webpack_require__( - /*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js" - ); - var _wrapEs = __webpack_require__( - /*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js" - ); - function getEasingForSegment(easing, i) { - return (0, _isEasingListEs.isEasingList)(easing) - ? easing[(0, _wrapEs.wrap)(0, easing.length, i)] - : easing; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/index.es.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/index.es.js ***! - \***************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "addUniqueItem", { - enumerable: true, - get: function () { - return _arrayEs.addUniqueItem; - }, - }); - Object.defineProperty(exports, "clamp", { - enumerable: true, - get: function () { - return _clampEs.clamp; - }, - }); - Object.defineProperty(exports, "defaultOffset", { - enumerable: true, - get: function () { - return _offsetEs.defaultOffset; - }, - }); - Object.defineProperty(exports, "defaults", { - enumerable: true, - get: function () { - return _defaultsEs.defaults; - }, - }); - Object.defineProperty(exports, "fillOffset", { - enumerable: true, - get: function () { - return _offsetEs.fillOffset; - }, - }); - Object.defineProperty(exports, "getEasingForSegment", { - enumerable: true, - get: function () { - return _easingEs.getEasingForSegment; - }, - }); - Object.defineProperty(exports, "interpolate", { - enumerable: true, - get: function () { - return _interpolateEs.interpolate; - }, - }); - Object.defineProperty(exports, "isCubicBezier", { - enumerable: true, - get: function () { - return _isCubicBezierEs.isCubicBezier; - }, - }); - Object.defineProperty(exports, "isEasingGenerator", { - enumerable: true, - get: function () { - return _isEasingGeneratorEs.isEasingGenerator; - }, - }); - Object.defineProperty(exports, "isEasingList", { - enumerable: true, - get: function () { - return _isEasingListEs.isEasingList; - }, - }); - Object.defineProperty(exports, "isFunction", { - enumerable: true, - get: function () { - return _isFunctionEs.isFunction; - }, - }); - Object.defineProperty(exports, "isNumber", { - enumerable: true, - get: function () { - return _isNumberEs.isNumber; - }, - }); - Object.defineProperty(exports, "isString", { - enumerable: true, - get: function () { - return _isStringEs.isString; - }, - }); - Object.defineProperty(exports, "mix", { - enumerable: true, - get: function () { - return _mixEs.mix; - }, - }); - Object.defineProperty(exports, "noop", { - enumerable: true, - get: function () { - return _noopEs.noop; - }, - }); - Object.defineProperty(exports, "noopReturn", { - enumerable: true, - get: function () { - return _noopEs.noopReturn; - }, - }); - Object.defineProperty(exports, "progress", { - enumerable: true, - get: function () { - return _progressEs.progress; - }, - }); - Object.defineProperty(exports, "removeItem", { - enumerable: true, - get: function () { - return _arrayEs.removeItem; - }, - }); - Object.defineProperty(exports, "time", { - enumerable: true, - get: function () { - return _timeEs.time; - }, - }); - Object.defineProperty(exports, "velocityPerSecond", { - enumerable: true, - get: function () { - return _velocityEs.velocityPerSecond; - }, - }); - Object.defineProperty(exports, "wrap", { - enumerable: true, - get: function () { - return _wrapEs.wrap; - }, - }); - var _arrayEs = __webpack_require__( - /*! ./array.es.js */ "../../../node_modules/@motionone/utils/dist/array.es.js" - ); - var _clampEs = __webpack_require__( - /*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js" - ); - var _defaultsEs = __webpack_require__( - /*! ./defaults.es.js */ "../../../node_modules/@motionone/utils/dist/defaults.es.js" - ); - var _easingEs = __webpack_require__( - /*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js" - ); - var _interpolateEs = __webpack_require__( - /*! ./interpolate.es.js */ "../../../node_modules/@motionone/utils/dist/interpolate.es.js" - ); - var _isCubicBezierEs = __webpack_require__( - /*! ./is-cubic-bezier.es.js */ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js" - ); - var _isEasingGeneratorEs = __webpack_require__( - /*! ./is-easing-generator.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js" - ); - var _isEasingListEs = __webpack_require__( - /*! ./is-easing-list.es.js */ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js" - ); - var _isFunctionEs = __webpack_require__( - /*! ./is-function.es.js */ "../../../node_modules/@motionone/utils/dist/is-function.es.js" - ); - var _isNumberEs = __webpack_require__( - /*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js" - ); - var _isStringEs = __webpack_require__( - /*! ./is-string.es.js */ "../../../node_modules/@motionone/utils/dist/is-string.es.js" - ); - var _mixEs = __webpack_require__( - /*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js" - ); - var _noopEs = __webpack_require__( - /*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js" - ); - var _offsetEs = __webpack_require__( - /*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js" - ); - var _progressEs = __webpack_require__( - /*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js" - ); - var _timeEs = __webpack_require__( - /*! ./time.es.js */ "../../../node_modules/@motionone/utils/dist/time.es.js" - ); - var _velocityEs = __webpack_require__( - /*! ./velocity.es.js */ "../../../node_modules/@motionone/utils/dist/velocity.es.js" - ); - var _wrapEs = __webpack_require__( - /*! ./wrap.es.js */ "../../../node_modules/@motionone/utils/dist/wrap.es.js" - ); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/interpolate.es.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/interpolate.es.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.interpolate = interpolate; - var _mixEs = __webpack_require__( - /*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js" - ); - var _noopEs = __webpack_require__( - /*! ./noop.es.js */ "../../../node_modules/@motionone/utils/dist/noop.es.js" - ); - var _offsetEs = __webpack_require__( - /*! ./offset.es.js */ "../../../node_modules/@motionone/utils/dist/offset.es.js" - ); - var _progressEs = __webpack_require__( - /*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js" - ); - var _easingEs = __webpack_require__( - /*! ./easing.es.js */ "../../../node_modules/@motionone/utils/dist/easing.es.js" - ); - var _clampEs = __webpack_require__( - /*! ./clamp.es.js */ "../../../node_modules/@motionone/utils/dist/clamp.es.js" - ); - function interpolate( - output, - input = (0, _offsetEs.defaultOffset)(output.length), - easing = _noopEs.noopReturn - ) { - const length = output.length; - /** - * If the input length is lower than the output we - * fill the input to match. This currently assumes the input - * is an animation progress value so is a good candidate for - * moving outside the function. - */ - const remainder = length - input.length; - remainder > 0 && (0, _offsetEs.fillOffset)(input, remainder); - return (t) => { - let i = 0; - for (; i < length - 2; i++) { - if (t < input[i + 1]) break; - } - let progressInRange = (0, _clampEs.clamp)( - 0, - 1, - (0, _progressEs.progress)(input[i], input[i + 1], t) - ); - const segmentEasing = (0, _easingEs.getEasingForSegment)(easing, i); - progressInRange = segmentEasing(progressInRange); - return (0, _mixEs.mix)(output[i], output[i + 1], progressInRange); - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js": - /*!*************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-cubic-bezier.es.js ***! - \*************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isCubicBezier = void 0; - var _isNumberEs = __webpack_require__( - /*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js" - ); - const isCubicBezier = (easing) => - Array.isArray(easing) && (0, _isNumberEs.isNumber)(easing[0]); - exports.isCubicBezier = isCubicBezier; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-easing-generator.es.js ***! - \*****************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isEasingGenerator = void 0; - const isEasingGenerator = (easing) => - typeof easing === "object" && Boolean(easing.createAnimation); - exports.isEasingGenerator = isEasingGenerator; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/is-easing-list.es.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-easing-list.es.js ***! - \************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isEasingList = void 0; - var _isNumberEs = __webpack_require__( - /*! ./is-number.es.js */ "../../../node_modules/@motionone/utils/dist/is-number.es.js" - ); - const isEasingList = (easing) => - Array.isArray(easing) && !(0, _isNumberEs.isNumber)(easing[0]); - exports.isEasingList = isEasingList; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/is-function.es.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-function.es.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isFunction = void 0; - const isFunction = (value) => typeof value === "function"; - exports.isFunction = isFunction; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/is-number.es.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-number.es.js ***! - \*******************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isNumber = void 0; - const isNumber = (value) => typeof value === "number"; - exports.isNumber = isNumber; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/is-string.es.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/is-string.es.js ***! - \*******************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isString = void 0; - const isString = (value) => typeof value === "string"; - exports.isString = isString; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/mix.es.js": - /*!*************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/mix.es.js ***! - \*************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.mix = void 0; - const mix = (min, max, progress) => - -progress * min + progress * max + min; - exports.mix = mix; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/noop.es.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/noop.es.js ***! - \**************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.noopReturn = exports.noop = void 0; - const noop = () => {}; - exports.noop = noop; - const noopReturn = (v) => v; - exports.noopReturn = noopReturn; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/offset.es.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/offset.es.js ***! - \****************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.defaultOffset = defaultOffset; - exports.fillOffset = fillOffset; - var _mixEs = __webpack_require__( - /*! ./mix.es.js */ "../../../node_modules/@motionone/utils/dist/mix.es.js" - ); - var _progressEs = __webpack_require__( - /*! ./progress.es.js */ "../../../node_modules/@motionone/utils/dist/progress.es.js" - ); - function fillOffset(offset, remaining) { - const min = offset[offset.length - 1]; - for (let i = 1; i <= remaining; i++) { - const offsetProgress = (0, _progressEs.progress)(0, remaining, i); - offset.push((0, _mixEs.mix)(min, 1, offsetProgress)); - } - } - function defaultOffset(length) { - const offset = [0]; - fillOffset(offset, length - 1); - return offset; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/progress.es.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/progress.es.js ***! - \******************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.progress = void 0; - const progress = (min, max, value) => - max - min === 0 ? 1 : (value - min) / (max - min); - exports.progress = progress; - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/time.es.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/time.es.js ***! - \**************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.time = void 0; - const time = (exports.time = { - ms: (seconds) => seconds * 1000, - s: (milliseconds) => milliseconds / 1000, - }); - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/velocity.es.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/velocity.es.js ***! - \******************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.velocityPerSecond = velocityPerSecond; - /* - Convert velocity into velocity per second - - @param [number]: Unit per frame - @param [number]: Frame duration in ms -*/ - function velocityPerSecond(velocity, frameDuration) { - return frameDuration ? velocity * (1000 / frameDuration) : 0; - } - - /***/ - }, - - /***/ "../../../node_modules/@motionone/utils/dist/wrap.es.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/@motionone/utils/dist/wrap.es.js ***! - \**************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.wrap = void 0; - const wrap = (min, max, v) => { - const rangeSize = max - min; - return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min; - }; - exports.wrap = wrap; - - /***/ - }, - - /***/ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js": - /*!********************************************************************************!*\ - !*** ../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js ***! - \********************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - function createDeferred() { - const d = {}; - d.promise = new Promise((resolve, reject) => { - d.resolve = resolve; - d.reject = reject; - }); - return d; - } - const SYMBOL_FINISHED = Symbol(); - const SYMBOL_NEW_VALUE = Symbol(); - /** - * makePushPullAsyncIterableIterator - * - * The iterable will publish values until return or throw is called. - * Afterwards it is in the completed state and cannot be used for publishing any further values. - * It will handle back-pressure and keep pushed values until they are consumed by a source. - */ - function makePushPullAsyncIterableIterator() { - let isRunning = true; - const values = []; - let newValueD = createDeferred(); - const finishedD = createDeferred(); - const asyncIterableIterator = - (async function* PushPullAsyncIterableIterator() { - while (true) { - if (values.length > 0) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield values.shift(); - } else { - const result = await Promise.race([ - newValueD.promise, - finishedD.promise, - ]); - if (result === SYMBOL_FINISHED) { - break; - } - if (result !== SYMBOL_NEW_VALUE) { - throw result; - } - } - } - })(); - function pushValue(value) { - if (isRunning === false) { - // TODO: Should this throw? - return; - } - values.push(value); - newValueD.resolve(SYMBOL_NEW_VALUE); - newValueD = createDeferred(); - } - // We monkey patch the original generator for clean-up - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalReturn = asyncIterableIterator.return.bind( - asyncIterableIterator - ); - asyncIterableIterator.return = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args - ) => { - isRunning = false; - finishedD.resolve(SYMBOL_FINISHED); - return originalReturn(...args); - }; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalThrow = asyncIterableIterator.throw.bind( - asyncIterableIterator - ); - asyncIterableIterator.throw = (err) => { - isRunning = false; - finishedD.resolve(err); - return originalThrow(err); - }; - return { - pushValue, - asyncIterableIterator, - }; - } - const makeAsyncIterableIteratorFromSink = (make) => { - const { pushValue, asyncIterableIterator } = - makePushPullAsyncIterableIterator(); - const dispose = make({ - next: (value) => { - pushValue(value); - }, - complete: () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - asyncIterableIterator.return(); - }, - error: (err) => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - asyncIterableIterator.throw(err); - }, - }); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const originalReturn = asyncIterableIterator.return; - let returnValue = undefined; - asyncIterableIterator.return = () => { - if (returnValue === undefined) { - dispose(); - returnValue = originalReturn(); - } - return returnValue; - }; - return asyncIterableIterator; - }; - function applyAsyncIterableIteratorToSink(asyncIterableIterator, sink) { - const run = async () => { - try { - for await (const value of asyncIterableIterator) { - sink.next(value); - } - sink.complete(); - } catch (err) { - sink.error(err); - } - }; - run(); - return () => { - var _a; - (_a = asyncIterableIterator.return) === null || _a === void 0 - ? void 0 - : _a.call(asyncIterableIterator); - }; - } - function isAsyncIterable(input) { - return ( - typeof input === "object" && - input !== null && - // The AsyncGenerator check is for Safari on iOS which currently does not have - // Symbol.asyncIterator implemented - // That means every custom AsyncIterable must be built using a AsyncGeneratorFunction (async function * () {}) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (input[Symbol.toStringTag] === "AsyncGenerator" || - (Symbol.asyncIterator && Symbol.asyncIterator in input)) - ); - } - exports.applyAsyncIterableIteratorToSink = - applyAsyncIterableIteratorToSink; - exports.isAsyncIterable = isAsyncIterable; - exports.makeAsyncIterableIteratorFromSink = - makeAsyncIterableIteratorFromSink; - exports.makePushPullAsyncIterableIterator = - makePushPullAsyncIterableIterator; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/primitive/dist/index.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/@radix-ui/primitive/dist/index.js ***! - \***************************************************************/ - /***/ function (module) { - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "composeEventHandlers", - () => $1a6a90a521dcd173$export$b9ecd428b558ff10 - ); - function $1a6a90a521dcd173$export$b9ecd428b558ff10( - originalEventHandler, - ourEventHandler, - { checkForDefaultPrevented = true } = {} - ) { - return function handleEvent(event) { - originalEventHandler === null || - originalEventHandler === void 0 || - originalEventHandler(event); - if (checkForDefaultPrevented === false || !event.defaultPrevented) - return ourEventHandler === null || ourEventHandler === void 0 - ? void 0 - : ourEventHandler(event); - }; - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-arrow/dist/index.js": - /*!*****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-arrow/dist/index.js ***! - \*****************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $eQpDd$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $eQpDd$react = __webpack_require__(/*! react */ "react"); - var $eQpDd$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "Arrow", - () => $09f4ad68a9251bc3$export$21b07c8f274aebd5 - ); - $parcel$export( - module.exports, - "Root", - () => $09f4ad68a9251bc3$export$be92b6f5f03c0fe9 - ); - - /* ------------------------------------------------------------------------------------------------- - * Arrow - * -----------------------------------------------------------------------------------------------*/ - const $09f4ad68a9251bc3$var$NAME = "Arrow"; - const $09f4ad68a9251bc3$export$21b07c8f274aebd5 = - /*#__PURE__*/ $eQpDd$react.forwardRef((props, forwardedRef) => { - const { - children: children, - width = 10, - height = 5, - ...arrowProps - } = props; - return /*#__PURE__*/ $eQpDd$react.createElement( - $eQpDd$radixuireactprimitive.Primitive.svg, - $parcel$interopDefault($eQpDd$babelruntimehelpersextends)( - {}, - arrowProps, - { - ref: forwardedRef, - width: width, - height: height, - viewBox: "0 0 30 10", - preserveAspectRatio: "none", - } - ), - props.asChild - ? children - : /*#__PURE__*/ $eQpDd$react.createElement("polygon", { - points: "0,0 30,0 15,10", - }) - ); - }); - /*#__PURE__*/ - Object.assign($09f4ad68a9251bc3$export$21b07c8f274aebd5, { - displayName: $09f4ad68a9251bc3$var$NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - const $09f4ad68a9251bc3$export$be92b6f5f03c0fe9 = - $09f4ad68a9251bc3$export$21b07c8f274aebd5; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-collection/dist/index.js": - /*!**********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-collection/dist/index.js ***! - \**********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $hnlpS$react = __webpack_require__(/*! react */ "react"); - var $hnlpS$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $hnlpS$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $hnlpS$radixuireactslot = __webpack_require__( - /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createCollection", - () => $1a96635ec239608b$export$c74125a8e3af6bb2 - ); - - // We have resorted to returning slots directly rather than exposing primitives that can then - // be slotted like ``. - // This is because we encountered issues with generic types that cannot be statically analysed - // due to creating them dynamically via createCollection. - function $1a96635ec239608b$export$c74125a8e3af6bb2(name) { - /* ----------------------------------------------------------------------------------------------- - * CollectionProvider - * ---------------------------------------------------------------------------------------------*/ - const PROVIDER_NAME = name + "CollectionProvider"; - const [createCollectionContext, createCollectionScope] = - $hnlpS$radixuireactcontext.createContextScope(PROVIDER_NAME); - const [CollectionProviderImpl, useCollectionContext] = - createCollectionContext(PROVIDER_NAME, { - collectionRef: { - current: null, - }, - itemMap: new Map(), - }); - const CollectionProvider = (props) => { - const { scope: scope, children: children } = props; - const ref = $parcel$interopDefault($hnlpS$react).useRef(null); - const itemMap = $parcel$interopDefault($hnlpS$react).useRef( - new Map() - ).current; - return /*#__PURE__*/ $parcel$interopDefault( - $hnlpS$react - ).createElement( - CollectionProviderImpl, - { - scope: scope, - itemMap: itemMap, - collectionRef: ref, - }, - children - ); - }; - /*#__PURE__*/ - Object.assign(CollectionProvider, { - displayName: PROVIDER_NAME, - }); - /* ----------------------------------------------------------------------------------------------- - * CollectionSlot - * ---------------------------------------------------------------------------------------------*/ - const COLLECTION_SLOT_NAME = name + "CollectionSlot"; - const CollectionSlot = /*#__PURE__*/ $parcel$interopDefault( - $hnlpS$react - ).forwardRef((props, forwardedRef) => { - const { scope: scope, children: children } = props; - const context = useCollectionContext(COLLECTION_SLOT_NAME, scope); - const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - context.collectionRef - ); - return /*#__PURE__*/ $parcel$interopDefault( - $hnlpS$react - ).createElement( - $hnlpS$radixuireactslot.Slot, - { - ref: composedRefs, - }, - children - ); - }); - /*#__PURE__*/ - Object.assign(CollectionSlot, { - displayName: COLLECTION_SLOT_NAME, - }); - /* ----------------------------------------------------------------------------------------------- - * CollectionItem - * ---------------------------------------------------------------------------------------------*/ - const ITEM_SLOT_NAME = name + "CollectionItemSlot"; - const ITEM_DATA_ATTR = "data-radix-collection-item"; - const CollectionItemSlot = /*#__PURE__*/ $parcel$interopDefault( - $hnlpS$react - ).forwardRef((props, forwardedRef) => { - const { scope: scope, children: children, ...itemData } = props; - const ref = $parcel$interopDefault($hnlpS$react).useRef(null); - const composedRefs = $hnlpS$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - const context = useCollectionContext(ITEM_SLOT_NAME, scope); - $parcel$interopDefault($hnlpS$react).useEffect(() => { - context.itemMap.set(ref, { - ref: ref, - ...itemData, - }); - return () => void context.itemMap.delete(ref); - }); - return /*#__PURE__*/ $parcel$interopDefault( - $hnlpS$react - ).createElement( - $hnlpS$radixuireactslot.Slot, - { - [ITEM_DATA_ATTR]: "", - ref: composedRefs, - }, - children - ); - }); - /*#__PURE__*/ - Object.assign(CollectionItemSlot, { - displayName: ITEM_SLOT_NAME, - }); - /* ----------------------------------------------------------------------------------------------- - * useCollection - * ---------------------------------------------------------------------------------------------*/ - function useCollection(scope) { - const context = useCollectionContext( - name + "CollectionConsumer", - scope - ); - const getItems = $parcel$interopDefault( - $hnlpS$react - ).useCallback(() => { - const collectionNode = context.collectionRef.current; - if (!collectionNode) return []; - const orderedNodes = Array.from( - collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`) - ); - const items = Array.from(context.itemMap.values()); - const orderedItems = items.sort( - (a, b) => - orderedNodes.indexOf(a.ref.current) - - orderedNodes.indexOf(b.ref.current) - ); - return orderedItems; - }, [context.collectionRef, context.itemMap]); - return getItems; - } - return [ - { - Provider: CollectionProvider, - Slot: CollectionSlot, - ItemSlot: CollectionItemSlot, - }, - useCollection, - createCollectionScope, - ]; - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-compose-refs/dist/index.js ***! - \************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $dJwbH$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "composeRefs", - () => $9c2aaba23466b352$export$43e446d32b3d21af - ); - $parcel$export( - module.exports, - "useComposedRefs", - () => $9c2aaba23466b352$export$c7b2cbe3552a0d05 - ); - - /** - * Set a given ref to a given value - * This utility takes care of different types of refs: callback refs and RefObject(s) - */ - function $9c2aaba23466b352$var$setRef(ref, value) { - if (typeof ref === "function") ref(value); - else if (ref !== null && ref !== undefined) ref.current = value; - } - /** - * A utility to compose multiple refs together - * Accepts callback refs and RefObject(s) - */ - function $9c2aaba23466b352$export$43e446d32b3d21af(...refs) { - return (node) => - refs.forEach((ref) => $9c2aaba23466b352$var$setRef(ref, node)); - } - /** - * A custom hook that composes multiple refs - * Accepts callback refs and RefObject(s) - */ - function $9c2aaba23466b352$export$c7b2cbe3552a0d05(...refs) { - // eslint-disable-next-line react-hooks/exhaustive-deps - return $dJwbH$react.useCallback( - $9c2aaba23466b352$export$43e446d32b3d21af(...refs), - refs - ); - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-context/dist/index.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-context/dist/index.js ***! - \*******************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $4O1Ne$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "createContext", - () => $dec3cc0142d4f286$export$fd42f52fd3ae1109 - ); - $parcel$export( - module.exports, - "createContextScope", - () => $dec3cc0142d4f286$export$50c7b4e9d9f19c1 - ); - function $dec3cc0142d4f286$export$fd42f52fd3ae1109( - rootComponentName, - defaultContext - ) { - const Context = - /*#__PURE__*/ $4O1Ne$react.createContext(defaultContext); - function Provider(props) { - const { children: children, ...context } = props; // Only re-memoize when prop values change - // eslint-disable-next-line react-hooks/exhaustive-deps - const value = $4O1Ne$react.useMemo( - () => context, - Object.values(context) - ); - return /*#__PURE__*/ $4O1Ne$react.createElement( - Context.Provider, - { - value: value, - }, - children - ); - } - function useContext(consumerName) { - const context = $4O1Ne$react.useContext(Context); - if (context) return context; - if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. - throw new Error( - `\`${consumerName}\` must be used within \`${rootComponentName}\`` - ); - } - Provider.displayName = rootComponentName + "Provider"; - return [Provider, useContext]; - } - /* ------------------------------------------------------------------------------------------------- - * createContextScope - * -----------------------------------------------------------------------------------------------*/ - function $dec3cc0142d4f286$export$50c7b4e9d9f19c1( - scopeName, - createContextScopeDeps = [] - ) { - let defaultContexts = []; - /* ----------------------------------------------------------------------------------------------- - * createContext - * ---------------------------------------------------------------------------------------------*/ - function $dec3cc0142d4f286$export$fd42f52fd3ae1109( - rootComponentName, - defaultContext - ) { - const BaseContext = - /*#__PURE__*/ $4O1Ne$react.createContext(defaultContext); - const index = defaultContexts.length; - defaultContexts = [...defaultContexts, defaultContext]; - function Provider(props) { - const { scope: scope, children: children, ...context } = props; - const Context = - (scope === null || scope === void 0 - ? void 0 - : scope[scopeName][index]) || BaseContext; // Only re-memoize when prop values change - // eslint-disable-next-line react-hooks/exhaustive-deps - const value = $4O1Ne$react.useMemo( - () => context, - Object.values(context) - ); - return /*#__PURE__*/ $4O1Ne$react.createElement( - Context.Provider, - { - value: value, - }, - children - ); - } - function useContext(consumerName, scope) { - const Context = - (scope === null || scope === void 0 - ? void 0 - : scope[scopeName][index]) || BaseContext; - const context = $4O1Ne$react.useContext(Context); - if (context) return context; - if (defaultContext !== undefined) return defaultContext; // if a defaultContext wasn't specified, it's a required context. - throw new Error( - `\`${consumerName}\` must be used within \`${rootComponentName}\`` - ); - } - Provider.displayName = rootComponentName + "Provider"; - return [Provider, useContext]; - } - /* ----------------------------------------------------------------------------------------------- - * createScope - * ---------------------------------------------------------------------------------------------*/ - const createScope = () => { - const scopeContexts = defaultContexts.map((defaultContext) => { - return /*#__PURE__*/ $4O1Ne$react.createContext(defaultContext); - }); - return function useScope(scope) { - const contexts = - (scope === null || scope === void 0 - ? void 0 - : scope[scopeName]) || scopeContexts; - return $4O1Ne$react.useMemo( - () => ({ - [`__scope${scopeName}`]: { - ...scope, - [scopeName]: contexts, - }, - }), - [scope, contexts] - ); - }; - }; - createScope.scopeName = scopeName; - return [ - $dec3cc0142d4f286$export$fd42f52fd3ae1109, - $dec3cc0142d4f286$var$composeContextScopes( - createScope, - ...createContextScopeDeps - ), - ]; - } - /* ------------------------------------------------------------------------------------------------- - * composeContextScopes - * -----------------------------------------------------------------------------------------------*/ - function $dec3cc0142d4f286$var$composeContextScopes(...scopes) { - const baseScope = scopes[0]; - if (scopes.length === 1) return baseScope; - const createScope1 = () => { - const scopeHooks = scopes.map((createScope) => ({ - useScope: createScope(), - scopeName: createScope.scopeName, - })); - return function useComposedScopes(overrideScopes) { - const nextScopes1 = scopeHooks.reduce( - (nextScopes, { useScope: useScope, scopeName: scopeName }) => { - // We are calling a hook inside a callback which React warns against to avoid inconsistent - // renders, however, scoping doesn't have render side effects so we ignore the rule. - // eslint-disable-next-line react-hooks/rules-of-hooks - const scopeProps = useScope(overrideScopes); - const currentScope = scopeProps[`__scope${scopeName}`]; - return { - ...nextScopes, - ...currentScope, - }; - }, - {} - ); - return $4O1Ne$react.useMemo( - () => ({ - [`__scope${baseScope.scopeName}`]: nextScopes1, - }), - [nextScopes1] - ); - }; - }; - createScope1.scopeName = baseScope.scopeName; - return createScope1; - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-dialog/dist/index.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dialog/dist/index.js ***! - \******************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $aJCrN$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $aJCrN$react = __webpack_require__(/*! react */ "react"); - var $aJCrN$radixuiprimitive = __webpack_require__( - /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" - ); - var $aJCrN$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $aJCrN$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $aJCrN$radixuireactid = __webpack_require__( - /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" - ); - var $aJCrN$radixuireactusecontrollablestate = __webpack_require__( - /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" - ); - var $aJCrN$radixuireactdismissablelayer = __webpack_require__( - /*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js" - ); - var $aJCrN$radixuireactfocusscope = __webpack_require__( - /*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js" - ); - var $aJCrN$radixuireactportal = __webpack_require__( - /*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js" - ); - var $aJCrN$radixuireactpresence = __webpack_require__( - /*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js" - ); - var $aJCrN$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $aJCrN$radixuireactfocusguards = __webpack_require__( - /*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js" - ); - var $aJCrN$reactremovescroll = __webpack_require__( - /*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js" - ); - var $aJCrN$ariahidden = __webpack_require__( - /*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js" - ); - var $aJCrN$radixuireactslot = __webpack_require__( - /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createDialogScope", - () => $f4833395aa1bca1a$export$cc702773b8ea3e41 - ); - $parcel$export( - module.exports, - "Dialog", - () => $f4833395aa1bca1a$export$3ddf2d174ce01153 - ); - $parcel$export( - module.exports, - "DialogTrigger", - () => $f4833395aa1bca1a$export$2e1e1122cf0cba88 - ); - $parcel$export( - module.exports, - "DialogPortal", - () => $f4833395aa1bca1a$export$dad7c95542bacce0 - ); - $parcel$export( - module.exports, - "DialogOverlay", - () => $f4833395aa1bca1a$export$bd1d06c79be19e17 - ); - $parcel$export( - module.exports, - "DialogContent", - () => $f4833395aa1bca1a$export$b6d9565de1e068cf - ); - $parcel$export( - module.exports, - "DialogTitle", - () => $f4833395aa1bca1a$export$16f7638e4a34b909 - ); - $parcel$export( - module.exports, - "DialogDescription", - () => $f4833395aa1bca1a$export$94e94c2ec2c954d5 - ); - $parcel$export( - module.exports, - "DialogClose", - () => $f4833395aa1bca1a$export$fba2fb7cd781b7ac - ); - $parcel$export( - module.exports, - "Root", - () => $f4833395aa1bca1a$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Trigger", - () => $f4833395aa1bca1a$export$41fb9f06171c75f4 - ); - $parcel$export( - module.exports, - "Portal", - () => $f4833395aa1bca1a$export$602eac185826482c - ); - $parcel$export( - module.exports, - "Overlay", - () => $f4833395aa1bca1a$export$c6fdb837b070b4ff - ); - $parcel$export( - module.exports, - "Content", - () => $f4833395aa1bca1a$export$7c6e2c02157bb7d2 - ); - $parcel$export( - module.exports, - "Title", - () => $f4833395aa1bca1a$export$f99233281efd08a0 - ); - $parcel$export( - module.exports, - "Description", - () => $f4833395aa1bca1a$export$393edc798c47379d - ); - $parcel$export( - module.exports, - "Close", - () => $f4833395aa1bca1a$export$f39c2d165cd861fe - ); - $parcel$export( - module.exports, - "WarningProvider", - () => $f4833395aa1bca1a$export$69b62a49393917d6 - ); - - /* ------------------------------------------------------------------------------------------------- - * Dialog - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$DIALOG_NAME = "Dialog"; - const [ - $f4833395aa1bca1a$var$createDialogContext, - $f4833395aa1bca1a$export$cc702773b8ea3e41, - ] = $aJCrN$radixuireactcontext.createContextScope( - $f4833395aa1bca1a$var$DIALOG_NAME - ); - const [ - $f4833395aa1bca1a$var$DialogProvider, - $f4833395aa1bca1a$var$useDialogContext, - ] = $f4833395aa1bca1a$var$createDialogContext( - $f4833395aa1bca1a$var$DIALOG_NAME - ); - const $f4833395aa1bca1a$export$3ddf2d174ce01153 = (props) => { - const { - __scopeDialog: __scopeDialog, - children: children, - open: openProp, - defaultOpen: defaultOpen, - onOpenChange: onOpenChange, - modal = true, - } = props; - const triggerRef = $aJCrN$react.useRef(null); - const contentRef = $aJCrN$react.useRef(null); - const [open = false, setOpen] = - $aJCrN$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange, - }); - return /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$DialogProvider, - { - scope: __scopeDialog, - triggerRef: triggerRef, - contentRef: contentRef, - contentId: $aJCrN$radixuireactid.useId(), - titleId: $aJCrN$radixuireactid.useId(), - descriptionId: $aJCrN$radixuireactid.useId(), - open: open, - onOpenChange: setOpen, - onOpenToggle: $aJCrN$react.useCallback( - () => setOpen((prevOpen) => !prevOpen), - [setOpen] - ), - modal: modal, - }, - children - ); - }; - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$3ddf2d174ce01153, { - displayName: $f4833395aa1bca1a$var$DIALOG_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DialogTrigger - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$TRIGGER_NAME = "DialogTrigger"; - const $f4833395aa1bca1a$export$2e1e1122cf0cba88 = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const { __scopeDialog: __scopeDialog, ...triggerProps } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$TRIGGER_NAME, - __scopeDialog - ); - const composedTriggerRef = - $aJCrN$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - context.triggerRef - ); - return /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactprimitive.Primitive.button, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - { - type: "button", - "aria-haspopup": "dialog", - "aria-expanded": context.open, - "aria-controls": context.contentId, - "data-state": $f4833395aa1bca1a$var$getState(context.open), - }, - triggerProps, - { - ref: composedTriggerRef, - onClick: $aJCrN$radixuiprimitive.composeEventHandlers( - props.onClick, - context.onOpenToggle - ), - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$2e1e1122cf0cba88, { - displayName: $f4833395aa1bca1a$var$TRIGGER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DialogPortal - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$PORTAL_NAME = "DialogPortal"; - const [ - $f4833395aa1bca1a$var$PortalProvider, - $f4833395aa1bca1a$var$usePortalContext, - ] = $f4833395aa1bca1a$var$createDialogContext( - $f4833395aa1bca1a$var$PORTAL_NAME, - { - forceMount: undefined, - } - ); - const $f4833395aa1bca1a$export$dad7c95542bacce0 = (props) => { - const { - __scopeDialog: __scopeDialog, - forceMount: forceMount, - children: children, - container: container, - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$PORTAL_NAME, - __scopeDialog - ); - return /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$PortalProvider, - { - scope: __scopeDialog, - forceMount: forceMount, - }, - $aJCrN$react.Children.map(children, (child) => - /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactportal.Portal, - { - asChild: true, - container: container, - }, - child - ) - ) - ) - ); - }; - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$dad7c95542bacce0, { - displayName: $f4833395aa1bca1a$var$PORTAL_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DialogOverlay - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$OVERLAY_NAME = "DialogOverlay"; - const $f4833395aa1bca1a$export$bd1d06c79be19e17 = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const portalContext = $f4833395aa1bca1a$var$usePortalContext( - $f4833395aa1bca1a$var$OVERLAY_NAME, - props.__scopeDialog - ); - const { forceMount = portalContext.forceMount, ...overlayProps } = - props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$OVERLAY_NAME, - props.__scopeDialog - ); - return context.modal - ? /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$DialogOverlayImpl, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - {}, - overlayProps, - { - ref: forwardedRef, - } - ) - ) - ) - : null; - }); - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$bd1d06c79be19e17, { - displayName: $f4833395aa1bca1a$var$OVERLAY_NAME, - }); - const $f4833395aa1bca1a$var$DialogOverlayImpl = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const { __scopeDialog: __scopeDialog, ...overlayProps } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$OVERLAY_NAME, - __scopeDialog - ); - return ( - /*#__PURE__*/ // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll` - // ie. when `Overlay` and `Content` are siblings - $aJCrN$react.createElement( - $aJCrN$reactremovescroll.RemoveScroll, - { - as: $aJCrN$radixuireactslot.Slot, - allowPinchZoom: true, - shards: [context.contentRef], - }, - /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - { - "data-state": $f4833395aa1bca1a$var$getState( - context.open - ), - }, - overlayProps, - { - ref: forwardedRef, // We re-enable pointer-events prevented by `Dialog.Content` to allow scrolling the overlay. - style: { - pointerEvents: "auto", - ...overlayProps.style, - }, - } - ) - ) - ) - ); - }); - /* ------------------------------------------------------------------------------------------------- - * DialogContent - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$CONTENT_NAME = "DialogContent"; - const $f4833395aa1bca1a$export$b6d9565de1e068cf = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const portalContext = $f4833395aa1bca1a$var$usePortalContext( - $f4833395aa1bca1a$var$CONTENT_NAME, - props.__scopeDialog - ); - const { forceMount = portalContext.forceMount, ...contentProps } = - props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$CONTENT_NAME, - props.__scopeDialog - ); - return /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - context.modal - ? /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$DialogContentModal, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - {}, - contentProps, - { - ref: forwardedRef, - } - ) - ) - : /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$DialogContentNonModal, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - {}, - contentProps, - { - ref: forwardedRef, - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$b6d9565de1e068cf, { - displayName: $f4833395aa1bca1a$var$CONTENT_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$DialogContentModal = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$CONTENT_NAME, - props.__scopeDialog - ); - const contentRef = $aJCrN$react.useRef(null); - const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - context.contentRef, - contentRef - ); // aria-hide everything except the content (better supported equivalent to setting aria-modal) - $aJCrN$react.useEffect(() => { - const content = contentRef.current; - if (content) return $aJCrN$ariahidden.hideOthers(content); - }, []); - return /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$DialogContentImpl, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - {}, - props, - { - ref: composedRefs, // we make sure focus isn't trapped once `DialogContent` has been closed - trapFocus: context.open, - disableOutsidePointerEvents: true, - onCloseAutoFocus: - $aJCrN$radixuiprimitive.composeEventHandlers( - props.onCloseAutoFocus, - (event) => { - var _context$triggerRef$c; - event.preventDefault(); - (_context$triggerRef$c = context.triggerRef.current) === - null || - _context$triggerRef$c === void 0 || - _context$triggerRef$c.focus(); - } - ), - onPointerDownOutside: - $aJCrN$radixuiprimitive.composeEventHandlers( - props.onPointerDownOutside, - (event) => { - const originalEvent = event.detail.originalEvent; - const ctrlLeftClick = - originalEvent.button === 0 && - originalEvent.ctrlKey === true; - const isRightClick = - originalEvent.button === 2 || ctrlLeftClick; // If the event is a right-click, we shouldn't close because - // it is effectively as if we right-clicked the `Overlay`. - if (isRightClick) event.preventDefault(); - } - ), // When focus is trapped, a `focusout` event may still happen. - onFocusOutside: $aJCrN$radixuiprimitive.composeEventHandlers( - props.onFocusOutside, - (event) => event.preventDefault() - ), - } - ) - ); - }); - /* -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$DialogContentNonModal = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$CONTENT_NAME, - props.__scopeDialog - ); - const hasInteractedOutsideRef = $aJCrN$react.useRef(false); - const hasPointerDownOutsideRef = $aJCrN$react.useRef(false); - return /*#__PURE__*/ $aJCrN$react.createElement( - $f4833395aa1bca1a$var$DialogContentImpl, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - {}, - props, - { - ref: forwardedRef, - trapFocus: false, - disableOutsidePointerEvents: false, - onCloseAutoFocus: (event) => { - var _props$onCloseAutoFoc; - (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || - _props$onCloseAutoFoc === void 0 || - _props$onCloseAutoFoc.call(props, event); - if (!event.defaultPrevented) { - var _context$triggerRef$c2; - if (!hasInteractedOutsideRef.current) - (_context$triggerRef$c2 = - context.triggerRef.current) === null || - _context$triggerRef$c2 === void 0 || - _context$triggerRef$c2.focus(); // Always prevent auto focus because we either focus manually or want user agent focus - event.preventDefault(); - } - hasInteractedOutsideRef.current = false; - hasPointerDownOutsideRef.current = false; - }, - onInteractOutside: (event) => { - var _props$onInteractOuts, _context$triggerRef$c3; - (_props$onInteractOuts = props.onInteractOutside) === - null || - _props$onInteractOuts === void 0 || - _props$onInteractOuts.call(props, event); - if (!event.defaultPrevented) { - hasInteractedOutsideRef.current = true; - if (event.detail.originalEvent.type === "pointerdown") - hasPointerDownOutsideRef.current = true; - } // Prevent dismissing when clicking the trigger. - // As the trigger is already setup to close, without doing so would - // cause it to close and immediately open. - const target = event.target; - const targetIsTrigger = - (_context$triggerRef$c3 = context.triggerRef.current) === - null || _context$triggerRef$c3 === void 0 - ? void 0 - : _context$triggerRef$c3.contains(target); - if (targetIsTrigger) event.preventDefault(); // On Safari if the trigger is inside a container with tabIndex={0}, when clicked - // we will get the pointer down outside event on the trigger, but then a subsequent - // focus outside event on the container, we ignore any focus outside event when we've - // already had a pointer down outside event. - if ( - event.detail.originalEvent.type === "focusin" && - hasPointerDownOutsideRef.current - ) - event.preventDefault(); - }, - } - ) - ); - }); - /* -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$DialogContentImpl = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const { - __scopeDialog: __scopeDialog, - trapFocus: trapFocus, - onOpenAutoFocus: onOpenAutoFocus, - onCloseAutoFocus: onCloseAutoFocus, - ...contentProps - } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$CONTENT_NAME, - __scopeDialog - ); - const contentRef = $aJCrN$react.useRef(null); - const composedRefs = $aJCrN$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - contentRef - ); // Make sure the whole tree has focus guards as our `Dialog` will be - // the last element in the DOM (beacuse of the `Portal`) - $aJCrN$radixuireactfocusguards.useFocusGuards(); - return /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$react.Fragment, - null, - /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactfocusscope.FocusScope, - { - asChild: true, - loop: true, - trapped: trapFocus, - onMountAutoFocus: onOpenAutoFocus, - onUnmountAutoFocus: onCloseAutoFocus, - }, - /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactdismissablelayer.DismissableLayer, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - { - role: "dialog", - id: context.contentId, - "aria-describedby": context.descriptionId, - "aria-labelledby": context.titleId, - "data-state": $f4833395aa1bca1a$var$getState( - context.open - ), - }, - contentProps, - { - ref: composedRefs, - onDismiss: () => context.onOpenChange(false), - } - ) - ) - ), - false - ); - }); - /* ------------------------------------------------------------------------------------------------- - * DialogTitle - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$TITLE_NAME = "DialogTitle"; - const $f4833395aa1bca1a$export$16f7638e4a34b909 = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const { __scopeDialog: __scopeDialog, ...titleProps } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$TITLE_NAME, - __scopeDialog - ); - return /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactprimitive.Primitive.h2, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - { - id: context.titleId, - }, - titleProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$16f7638e4a34b909, { - displayName: $f4833395aa1bca1a$var$TITLE_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DialogDescription - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$DESCRIPTION_NAME = "DialogDescription"; - const $f4833395aa1bca1a$export$94e94c2ec2c954d5 = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const { __scopeDialog: __scopeDialog, ...descriptionProps } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$DESCRIPTION_NAME, - __scopeDialog - ); - return /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactprimitive.Primitive.p, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - { - id: context.descriptionId, - }, - descriptionProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$94e94c2ec2c954d5, { - displayName: $f4833395aa1bca1a$var$DESCRIPTION_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DialogClose - * -----------------------------------------------------------------------------------------------*/ - const $f4833395aa1bca1a$var$CLOSE_NAME = "DialogClose"; - const $f4833395aa1bca1a$export$fba2fb7cd781b7ac = - /*#__PURE__*/ $aJCrN$react.forwardRef((props, forwardedRef) => { - const { __scopeDialog: __scopeDialog, ...closeProps } = props; - const context = $f4833395aa1bca1a$var$useDialogContext( - $f4833395aa1bca1a$var$CLOSE_NAME, - __scopeDialog - ); - return /*#__PURE__*/ $aJCrN$react.createElement( - $aJCrN$radixuireactprimitive.Primitive.button, - $parcel$interopDefault($aJCrN$babelruntimehelpersextends)( - { - type: "button", - }, - closeProps, - { - ref: forwardedRef, - onClick: $aJCrN$radixuiprimitive.composeEventHandlers( - props.onClick, - () => context.onOpenChange(false) - ), - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($f4833395aa1bca1a$export$fba2fb7cd781b7ac, { - displayName: $f4833395aa1bca1a$var$CLOSE_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - function $f4833395aa1bca1a$var$getState(open) { - return open ? "open" : "closed"; - } - const $f4833395aa1bca1a$var$TITLE_WARNING_NAME = "DialogTitleWarning"; - const [ - $f4833395aa1bca1a$export$69b62a49393917d6, - $f4833395aa1bca1a$var$useWarningContext, - ] = $aJCrN$radixuireactcontext.createContext( - $f4833395aa1bca1a$var$TITLE_WARNING_NAME, - { - contentName: $f4833395aa1bca1a$var$CONTENT_NAME, - titleName: $f4833395aa1bca1a$var$TITLE_NAME, - docsSlug: "dialog", - } - ); - const $f4833395aa1bca1a$var$TitleWarning = ({ titleId: titleId }) => { - const titleWarningContext = $f4833395aa1bca1a$var$useWarningContext( - $f4833395aa1bca1a$var$TITLE_WARNING_NAME - ); - const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users. - -If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component. - -For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`; - $aJCrN$react.useEffect(() => { - if (titleId) { - const hasTitle = document.getElementById(titleId); - if (!hasTitle) throw new Error(MESSAGE); - } - }, [MESSAGE, titleId]); - return null; - }; - const $f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME = - "DialogDescriptionWarning"; - const $f4833395aa1bca1a$var$DescriptionWarning = ({ - contentRef: contentRef, - descriptionId: descriptionId, - }) => { - const descriptionWarningContext = - $f4833395aa1bca1a$var$useWarningContext( - $f4833395aa1bca1a$var$DESCRIPTION_WARNING_NAME - ); - const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`; - $aJCrN$react.useEffect(() => { - var _contentRef$current; - const describedById = - (_contentRef$current = contentRef.current) === null || - _contentRef$current === void 0 - ? void 0 - : _contentRef$current.getAttribute("aria-describedby"); // if we have an id and the user hasn't set aria-describedby={undefined} - if (descriptionId && describedById) { - const hasDescription = document.getElementById(descriptionId); - if (!hasDescription) console.warn(MESSAGE); - } - }, [MESSAGE, contentRef, descriptionId]); - return null; - }; - const $f4833395aa1bca1a$export$be92b6f5f03c0fe9 = - $f4833395aa1bca1a$export$3ddf2d174ce01153; - const $f4833395aa1bca1a$export$41fb9f06171c75f4 = - $f4833395aa1bca1a$export$2e1e1122cf0cba88; - const $f4833395aa1bca1a$export$602eac185826482c = - $f4833395aa1bca1a$export$dad7c95542bacce0; - const $f4833395aa1bca1a$export$c6fdb837b070b4ff = - $f4833395aa1bca1a$export$bd1d06c79be19e17; - const $f4833395aa1bca1a$export$7c6e2c02157bb7d2 = - $f4833395aa1bca1a$export$b6d9565de1e068cf; - const $f4833395aa1bca1a$export$f99233281efd08a0 = - $f4833395aa1bca1a$export$16f7638e4a34b909; - const $f4833395aa1bca1a$export$393edc798c47379d = - $f4833395aa1bca1a$export$94e94c2ec2c954d5; - const $f4833395aa1bca1a$export$f39c2d165cd861fe = - $f4833395aa1bca1a$export$fba2fb7cd781b7ac; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-direction/dist/index.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-direction/dist/index.js ***! - \*********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $9g4ps$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useDirection", - () => $cc45c1b701a63adc$export$b39126d51d94e6f3 - ); - $parcel$export( - module.exports, - "Provider", - () => $cc45c1b701a63adc$export$2881499e37b75b9a - ); - $parcel$export( - module.exports, - "DirectionProvider", - () => $cc45c1b701a63adc$export$c760c09fdd558351 - ); - const $cc45c1b701a63adc$var$DirectionContext = - /*#__PURE__*/ $9g4ps$react.createContext(undefined); - /* ------------------------------------------------------------------------------------------------- - * Direction - * -----------------------------------------------------------------------------------------------*/ - const $cc45c1b701a63adc$export$c760c09fdd558351 = (props) => { - const { dir: dir, children: children } = props; - return /*#__PURE__*/ $9g4ps$react.createElement( - $cc45c1b701a63adc$var$DirectionContext.Provider, - { - value: dir, - }, - children - ); - }; - /* -----------------------------------------------------------------------------------------------*/ - function $cc45c1b701a63adc$export$b39126d51d94e6f3(localDir) { - const globalDir = $9g4ps$react.useContext( - $cc45c1b701a63adc$var$DirectionContext - ); - return localDir || globalDir || "ltr"; - } - const $cc45c1b701a63adc$export$2881499e37b75b9a = - $cc45c1b701a63adc$export$c760c09fdd558351; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js ***! - \*****************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $g2vWm$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $g2vWm$react = __webpack_require__(/*! react */ "react"); - var $g2vWm$radixuiprimitive = __webpack_require__( - /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" - ); - var $g2vWm$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $g2vWm$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $g2vWm$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - var $g2vWm$radixuireactuseescapekeydown = __webpack_require__( - /*! @radix-ui/react-use-escape-keydown */ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "DismissableLayer", - () => $d715e0554b679f1f$export$177fb62ff3ec1f22 - ); - $parcel$export( - module.exports, - "DismissableLayerBranch", - () => $d715e0554b679f1f$export$4d5eb2109db14228 - ); - $parcel$export( - module.exports, - "Root", - () => $d715e0554b679f1f$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Branch", - () => $d715e0554b679f1f$export$aecb2ddcb55c95be - ); - - /* ------------------------------------------------------------------------------------------------- - * DismissableLayer - * -----------------------------------------------------------------------------------------------*/ - const $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME = "DismissableLayer"; - const $d715e0554b679f1f$var$CONTEXT_UPDATE = "dismissableLayer.update"; - const $d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE = - "dismissableLayer.pointerDownOutside"; - const $d715e0554b679f1f$var$FOCUS_OUTSIDE = - "dismissableLayer.focusOutside"; - let $d715e0554b679f1f$var$originalBodyPointerEvents; - const $d715e0554b679f1f$var$DismissableLayerContext = - /*#__PURE__*/ $g2vWm$react.createContext({ - layers: new Set(), - layersWithOutsidePointerEventsDisabled: new Set(), - branches: new Set(), - }); - const $d715e0554b679f1f$export$177fb62ff3ec1f22 = - /*#__PURE__*/ $g2vWm$react.forwardRef((props, forwardedRef) => { - var _node$ownerDocument; - const { - disableOutsidePointerEvents = false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - ...layerProps - } = props; - const context = $g2vWm$react.useContext( - $d715e0554b679f1f$var$DismissableLayerContext - ); - const [node1, setNode] = $g2vWm$react.useState(null); - const ownerDocument = - (_node$ownerDocument = - node1 === null || node1 === void 0 - ? void 0 - : node1.ownerDocument) !== null && - _node$ownerDocument !== void 0 - ? _node$ownerDocument - : globalThis === null || globalThis === void 0 - ? void 0 - : globalThis.document; - const [, force] = $g2vWm$react.useState({}); - const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - (node) => setNode(node) - ); - const layers = Array.from(context.layers); - const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore - const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore - const index = node1 ? layers.indexOf(node1) : -1; - const isBodyPointerEventsDisabled = - context.layersWithOutsidePointerEventsDisabled.size > 0; - const isPointerEventsEnabled = - index >= highestLayerWithOutsidePointerEventsDisabledIndex; - const pointerDownOutside = - $d715e0554b679f1f$var$usePointerDownOutside((event) => { - const target = event.target; - const isPointerDownOnBranch = [...context.branches].some( - (branch) => branch.contains(target) - ); - if (!isPointerEventsEnabled || isPointerDownOnBranch) return; - onPointerDownOutside === null || - onPointerDownOutside === void 0 || - onPointerDownOutside(event); - onInteractOutside === null || - onInteractOutside === void 0 || - onInteractOutside(event); - if (!event.defaultPrevented) - onDismiss === null || onDismiss === void 0 || onDismiss(); - }, ownerDocument); - const focusOutside = $d715e0554b679f1f$var$useFocusOutside( - (event) => { - const target = event.target; - const isFocusInBranch = [...context.branches].some((branch) => - branch.contains(target) - ); - if (isFocusInBranch) return; - onFocusOutside === null || - onFocusOutside === void 0 || - onFocusOutside(event); - onInteractOutside === null || - onInteractOutside === void 0 || - onInteractOutside(event); - if (!event.defaultPrevented) - onDismiss === null || onDismiss === void 0 || onDismiss(); - }, - ownerDocument - ); - $g2vWm$radixuireactuseescapekeydown.useEscapeKeydown((event) => { - const isHighestLayer = index === context.layers.size - 1; - if (!isHighestLayer) return; - onEscapeKeyDown === null || - onEscapeKeyDown === void 0 || - onEscapeKeyDown(event); - if (!event.defaultPrevented && onDismiss) { - event.preventDefault(); - onDismiss(); - } - }, ownerDocument); - $g2vWm$react.useEffect(() => { - if (!node1) return; - if (disableOutsidePointerEvents) { - if (context.layersWithOutsidePointerEventsDisabled.size === 0) { - $d715e0554b679f1f$var$originalBodyPointerEvents = - ownerDocument.body.style.pointerEvents; - ownerDocument.body.style.pointerEvents = "none"; - } - context.layersWithOutsidePointerEventsDisabled.add(node1); - } - context.layers.add(node1); - $d715e0554b679f1f$var$dispatchUpdate(); - return () => { - if ( - disableOutsidePointerEvents && - context.layersWithOutsidePointerEventsDisabled.size === 1 - ) - ownerDocument.body.style.pointerEvents = - $d715e0554b679f1f$var$originalBodyPointerEvents; - }; - }, [node1, ownerDocument, disableOutsidePointerEvents, context]); - /** - * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect - * because a change to `disableOutsidePointerEvents` would remove this layer from the stack - * and add it to the end again so the layering order wouldn't be _creation order_. - * We only want them to be removed from context stacks when unmounted. - */ - $g2vWm$react.useEffect(() => { - return () => { - if (!node1) return; - context.layers.delete(node1); - context.layersWithOutsidePointerEventsDisabled.delete(node1); - $d715e0554b679f1f$var$dispatchUpdate(); - }; - }, [node1, context]); - $g2vWm$react.useEffect(() => { - const handleUpdate = () => force({}); - document.addEventListener( - $d715e0554b679f1f$var$CONTEXT_UPDATE, - handleUpdate - ); - return () => - document.removeEventListener( - $d715e0554b679f1f$var$CONTEXT_UPDATE, - handleUpdate - ); - }, []); - return /*#__PURE__*/ $g2vWm$react.createElement( - $g2vWm$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($g2vWm$babelruntimehelpersextends)( - {}, - layerProps, - { - ref: composedRefs, - style: { - pointerEvents: isBodyPointerEventsDisabled - ? isPointerEventsEnabled - ? "auto" - : "none" - : undefined, - ...props.style, - }, - onFocusCapture: $g2vWm$radixuiprimitive.composeEventHandlers( - props.onFocusCapture, - focusOutside.onFocusCapture - ), - onBlurCapture: $g2vWm$radixuiprimitive.composeEventHandlers( - props.onBlurCapture, - focusOutside.onBlurCapture - ), - onPointerDownCapture: - $g2vWm$radixuiprimitive.composeEventHandlers( - props.onPointerDownCapture, - pointerDownOutside.onPointerDownCapture - ), - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d715e0554b679f1f$export$177fb62ff3ec1f22, { - displayName: $d715e0554b679f1f$var$DISMISSABLE_LAYER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DismissableLayerBranch - * -----------------------------------------------------------------------------------------------*/ - const $d715e0554b679f1f$var$BRANCH_NAME = "DismissableLayerBranch"; - const $d715e0554b679f1f$export$4d5eb2109db14228 = - /*#__PURE__*/ $g2vWm$react.forwardRef((props, forwardedRef) => { - const context = $g2vWm$react.useContext( - $d715e0554b679f1f$var$DismissableLayerContext - ); - const ref = $g2vWm$react.useRef(null); - const composedRefs = $g2vWm$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - $g2vWm$react.useEffect(() => { - const node = ref.current; - if (node) { - context.branches.add(node); - return () => { - context.branches.delete(node); - }; - } - }, [context.branches]); - return /*#__PURE__*/ $g2vWm$react.createElement( - $g2vWm$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($g2vWm$babelruntimehelpersextends)( - {}, - props, - { - ref: composedRefs, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d715e0554b679f1f$export$4d5eb2109db14228, { - displayName: $d715e0554b679f1f$var$BRANCH_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ /** - * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup` - * to mimic layer dismissing behaviour present in OS. - * Returns props to pass to the node we want to check for outside events. - */ - function $d715e0554b679f1f$var$usePointerDownOutside( - onPointerDownOutside, - ownerDocument = globalThis === null || globalThis === void 0 - ? void 0 - : globalThis.document - ) { - const handlePointerDownOutside = - $g2vWm$radixuireactusecallbackref.useCallbackRef( - onPointerDownOutside - ); - const isPointerInsideReactTreeRef = $g2vWm$react.useRef(false); - const handleClickRef = $g2vWm$react.useRef(() => {}); - $g2vWm$react.useEffect(() => { - const handlePointerDown = (event) => { - if (event.target && !isPointerInsideReactTreeRef.current) { - const eventDetail = { - originalEvent: event, - }; - function handleAndDispatchPointerDownOutsideEvent() { - $d715e0554b679f1f$var$handleAndDispatchCustomEvent( - $d715e0554b679f1f$var$POINTER_DOWN_OUTSIDE, - handlePointerDownOutside, - eventDetail, - { - discrete: true, - } - ); - } - /** - * On touch devices, we need to wait for a click event because browsers implement - * a ~350ms delay between the time the user stops touching the display and when the - * browser executres events. We need to ensure we don't reactivate pointer-events within - * this timeframe otherwise the browser may execute events that should have been prevented. - * - * Additionally, this also lets us deal automatically with cancellations when a click event - * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc. - * - * This is why we also continuously remove the previous listener, because we cannot be - * certain that it was raised, and therefore cleaned-up. - */ - if (event.pointerType === "touch") { - ownerDocument.removeEventListener( - "click", - handleClickRef.current - ); - handleClickRef.current = - handleAndDispatchPointerDownOutsideEvent; - ownerDocument.addEventListener( - "click", - handleClickRef.current, - { - once: true, - } - ); - } else handleAndDispatchPointerDownOutsideEvent(); - } - isPointerInsideReactTreeRef.current = false; - }; - /** - * if this hook executes in a component that mounts via a `pointerdown` event, the event - * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid - * this by delaying the event listener registration on the document. - * This is not React specific, but rather how the DOM works, ie: - * ``` - * button.addEventListener('pointerdown', () => { - * console.log('I will log'); - * document.addEventListener('pointerdown', () => { - * console.log('I will also log'); - * }) - * }); - */ - const timerId = window.setTimeout(() => { - ownerDocument.addEventListener("pointerdown", handlePointerDown); - }, 0); - return () => { - window.clearTimeout(timerId); - ownerDocument.removeEventListener( - "pointerdown", - handlePointerDown - ); - ownerDocument.removeEventListener( - "click", - handleClickRef.current - ); - }; - }, [ownerDocument, handlePointerDownOutside]); - return { - // ensures we check React component tree (not just DOM tree) - onPointerDownCapture: () => - (isPointerInsideReactTreeRef.current = true), - }; - } - /** - * Listens for when focus happens outside a react subtree. - * Returns props to pass to the root (node) of the subtree we want to check. - */ - function $d715e0554b679f1f$var$useFocusOutside( - onFocusOutside, - ownerDocument = globalThis === null || globalThis === void 0 - ? void 0 - : globalThis.document - ) { - const handleFocusOutside = - $g2vWm$radixuireactusecallbackref.useCallbackRef(onFocusOutside); - const isFocusInsideReactTreeRef = $g2vWm$react.useRef(false); - $g2vWm$react.useEffect(() => { - const handleFocus = (event) => { - if (event.target && !isFocusInsideReactTreeRef.current) { - const eventDetail = { - originalEvent: event, - }; - $d715e0554b679f1f$var$handleAndDispatchCustomEvent( - $d715e0554b679f1f$var$FOCUS_OUTSIDE, - handleFocusOutside, - eventDetail, - { - discrete: false, - } - ); - } - }; - ownerDocument.addEventListener("focusin", handleFocus); - return () => - ownerDocument.removeEventListener("focusin", handleFocus); - }, [ownerDocument, handleFocusOutside]); - return { - onFocusCapture: () => (isFocusInsideReactTreeRef.current = true), - onBlurCapture: () => (isFocusInsideReactTreeRef.current = false), - }; - } - function $d715e0554b679f1f$var$dispatchUpdate() { - const event = new CustomEvent($d715e0554b679f1f$var$CONTEXT_UPDATE); - document.dispatchEvent(event); - } - function $d715e0554b679f1f$var$handleAndDispatchCustomEvent( - name, - handler, - detail, - { discrete: discrete } - ) { - const target = detail.originalEvent.target; - const event = new CustomEvent(name, { - bubbles: false, - cancelable: true, - detail: detail, - }); - if (handler) - target.addEventListener(name, handler, { - once: true, - }); - if (discrete) - $g2vWm$radixuireactprimitive.dispatchDiscreteCustomEvent( - target, - event - ); - else target.dispatchEvent(event); - } - const $d715e0554b679f1f$export$be92b6f5f03c0fe9 = - $d715e0554b679f1f$export$177fb62ff3ec1f22; - const $d715e0554b679f1f$export$aecb2ddcb55c95be = - $d715e0554b679f1f$export$4d5eb2109db14228; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js": - /*!*************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js ***! - \*************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $7dQ7Q$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $7dQ7Q$react = __webpack_require__(/*! react */ "react"); - var $7dQ7Q$radixuiprimitive = __webpack_require__( - /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" - ); - var $7dQ7Q$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $7dQ7Q$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $7dQ7Q$radixuireactusecontrollablestate = __webpack_require__( - /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" - ); - var $7dQ7Q$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $7dQ7Q$radixuireactmenu = __webpack_require__( - /*! @radix-ui/react-menu */ "../../../node_modules/@radix-ui/react-menu/dist/index.js" - ); - var $7dQ7Q$radixuireactid = __webpack_require__( - /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createDropdownMenuScope", - () => $d1bf075a6b218014$export$c0623cd925aeb687 - ); - $parcel$export( - module.exports, - "DropdownMenu", - () => $d1bf075a6b218014$export$e44a253a59704894 - ); - $parcel$export( - module.exports, - "DropdownMenuTrigger", - () => $d1bf075a6b218014$export$d2469213b3befba9 - ); - $parcel$export( - module.exports, - "DropdownMenuPortal", - () => $d1bf075a6b218014$export$cd369b4d4d54efc9 - ); - $parcel$export( - module.exports, - "DropdownMenuContent", - () => $d1bf075a6b218014$export$6e76d93a37c01248 - ); - $parcel$export( - module.exports, - "DropdownMenuGroup", - () => $d1bf075a6b218014$export$246bebaba3a2f70e - ); - $parcel$export( - module.exports, - "DropdownMenuLabel", - () => $d1bf075a6b218014$export$76e48c5b57f24495 - ); - $parcel$export( - module.exports, - "DropdownMenuItem", - () => $d1bf075a6b218014$export$ed97964d1871885d - ); - $parcel$export( - module.exports, - "DropdownMenuCheckboxItem", - () => $d1bf075a6b218014$export$53a69729da201fa9 - ); - $parcel$export( - module.exports, - "DropdownMenuRadioGroup", - () => $d1bf075a6b218014$export$3323ad73d55f587e - ); - $parcel$export( - module.exports, - "DropdownMenuRadioItem", - () => $d1bf075a6b218014$export$e4f69b41b1637536 - ); - $parcel$export( - module.exports, - "DropdownMenuItemIndicator", - () => $d1bf075a6b218014$export$42355ae145153fb6 - ); - $parcel$export( - module.exports, - "DropdownMenuSeparator", - () => $d1bf075a6b218014$export$da160178fd3bc7e9 - ); - $parcel$export( - module.exports, - "DropdownMenuArrow", - () => $d1bf075a6b218014$export$34b8980744021ec5 - ); - $parcel$export( - module.exports, - "DropdownMenuSub", - () => $d1bf075a6b218014$export$2f307d81a64f5442 - ); - $parcel$export( - module.exports, - "DropdownMenuSubTrigger", - () => $d1bf075a6b218014$export$21dcb7ec56f874cf - ); - $parcel$export( - module.exports, - "DropdownMenuSubContent", - () => $d1bf075a6b218014$export$f34ec8bc2482cc5f - ); - $parcel$export( - module.exports, - "Root", - () => $d1bf075a6b218014$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Trigger", - () => $d1bf075a6b218014$export$41fb9f06171c75f4 - ); - $parcel$export( - module.exports, - "Portal", - () => $d1bf075a6b218014$export$602eac185826482c - ); - $parcel$export( - module.exports, - "Content", - () => $d1bf075a6b218014$export$7c6e2c02157bb7d2 - ); - $parcel$export( - module.exports, - "Group", - () => $d1bf075a6b218014$export$eb2fcfdbd7ba97d4 - ); - $parcel$export( - module.exports, - "Label", - () => $d1bf075a6b218014$export$b04be29aa201d4f5 - ); - $parcel$export( - module.exports, - "Item", - () => $d1bf075a6b218014$export$6d08773d2e66f8f2 - ); - $parcel$export( - module.exports, - "CheckboxItem", - () => $d1bf075a6b218014$export$16ce288f89fa631c - ); - $parcel$export( - module.exports, - "RadioGroup", - () => $d1bf075a6b218014$export$a98f0dcb43a68a25 - ); - $parcel$export( - module.exports, - "RadioItem", - () => $d1bf075a6b218014$export$371ab307eab489c0 - ); - $parcel$export( - module.exports, - "ItemIndicator", - () => $d1bf075a6b218014$export$c3468e2714d175fa - ); - $parcel$export( - module.exports, - "Separator", - () => $d1bf075a6b218014$export$1ff3c3f08ae963c0 - ); - $parcel$export( - module.exports, - "Arrow", - () => $d1bf075a6b218014$export$21b07c8f274aebd5 - ); - $parcel$export( - module.exports, - "Sub", - () => $d1bf075a6b218014$export$d7a01e11500dfb6f - ); - $parcel$export( - module.exports, - "SubTrigger", - () => $d1bf075a6b218014$export$2ea8a7a591ac5eac - ); - $parcel$export( - module.exports, - "SubContent", - () => $d1bf075a6b218014$export$6d4de93b380beddf - ); - - /* ------------------------------------------------------------------------------------------------- - * DropdownMenu - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$DROPDOWN_MENU_NAME = "DropdownMenu"; - const [ - $d1bf075a6b218014$var$createDropdownMenuContext, - $d1bf075a6b218014$export$c0623cd925aeb687, - ] = $7dQ7Q$radixuireactcontext.createContextScope( - $d1bf075a6b218014$var$DROPDOWN_MENU_NAME, - [$7dQ7Q$radixuireactmenu.createMenuScope] - ); - const $d1bf075a6b218014$var$useMenuScope = - $7dQ7Q$radixuireactmenu.createMenuScope(); - const [ - $d1bf075a6b218014$var$DropdownMenuProvider, - $d1bf075a6b218014$var$useDropdownMenuContext, - ] = $d1bf075a6b218014$var$createDropdownMenuContext( - $d1bf075a6b218014$var$DROPDOWN_MENU_NAME - ); - const $d1bf075a6b218014$export$e44a253a59704894 = (props) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - children: children, - dir: dir, - open: openProp, - defaultOpen: defaultOpen, - onOpenChange: onOpenChange, - modal = true, - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const triggerRef = $7dQ7Q$react.useRef(null); - const [open = false, setOpen] = - $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange, - }); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $d1bf075a6b218014$var$DropdownMenuProvider, - { - scope: __scopeDropdownMenu, - triggerId: $7dQ7Q$radixuireactid.useId(), - triggerRef: triggerRef, - contentId: $7dQ7Q$radixuireactid.useId(), - open: open, - onOpenChange: setOpen, - onOpenToggle: $7dQ7Q$react.useCallback( - () => setOpen((prevOpen) => !prevOpen), - [setOpen] - ), - modal: modal, - }, - /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Root, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - { - open: open, - onOpenChange: setOpen, - dir: dir, - modal: modal, - } - ), - children - ) - ); - }; - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$e44a253a59704894, { - displayName: $d1bf075a6b218014$var$DROPDOWN_MENU_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuTrigger - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$TRIGGER_NAME = "DropdownMenuTrigger"; - const $d1bf075a6b218014$export$d2469213b3befba9 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - disabled = false, - ...triggerProps - } = props; - const context = $d1bf075a6b218014$var$useDropdownMenuContext( - $d1bf075a6b218014$var$TRIGGER_NAME, - __scopeDropdownMenu - ); - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Anchor, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - { - asChild: true, - }, - menuScope - ), - /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactprimitive.Primitive.button, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - { - type: "button", - id: context.triggerId, - "aria-haspopup": "menu", - "aria-expanded": context.open, - "aria-controls": context.open - ? context.contentId - : undefined, - "data-state": context.open ? "open" : "closed", - "data-disabled": disabled ? "" : undefined, - disabled: disabled, - }, - triggerProps, - { - ref: $7dQ7Q$radixuireactcomposerefs.composeRefs( - forwardedRef, - context.triggerRef - ), - onPointerDown: $7dQ7Q$radixuiprimitive.composeEventHandlers( - props.onPointerDown, - (event) => { - // only call handler if it's the left button (mousedown gets triggered by all mouse buttons) - // but not when the control key is pressed (avoiding MacOS right click) - if ( - !disabled && - event.button === 0 && - event.ctrlKey === false - ) { - context.onOpenToggle(); // prevent trigger focusing when opening - // this allows the content to be given focus without competition - if (!context.open) event.preventDefault(); - } - } - ), - onKeyDown: $7dQ7Q$radixuiprimitive.composeEventHandlers( - props.onKeyDown, - (event) => { - if (disabled) return; - if (["Enter", " "].includes(event.key)) - context.onOpenToggle(); - if (event.key === "ArrowDown") - context.onOpenChange(true); // prevent keydown from scrolling window / first focused item to execute - // that keydown (inadvertently closing the menu) - if (["Enter", " ", "ArrowDown"].includes(event.key)) - event.preventDefault(); - } - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$d2469213b3befba9, { - displayName: $d1bf075a6b218014$var$TRIGGER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuPortal - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$PORTAL_NAME = "DropdownMenuPortal"; - const $d1bf075a6b218014$export$cd369b4d4d54efc9 = (props) => { - const { __scopeDropdownMenu: __scopeDropdownMenu, ...portalProps } = - props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Portal, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - portalProps - ) - ); - }; - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$cd369b4d4d54efc9, { - displayName: $d1bf075a6b218014$var$PORTAL_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuContent - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$CONTENT_NAME = "DropdownMenuContent"; - const $d1bf075a6b218014$export$6e76d93a37c01248 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...contentProps - } = props; - const context = $d1bf075a6b218014$var$useDropdownMenuContext( - $d1bf075a6b218014$var$CONTENT_NAME, - __scopeDropdownMenu - ); - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const hasInteractedOutsideRef = $7dQ7Q$react.useRef(false); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Content, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - { - id: context.contentId, - "aria-labelledby": context.triggerId, - }, - menuScope, - contentProps, - { - ref: forwardedRef, - onCloseAutoFocus: - $7dQ7Q$radixuiprimitive.composeEventHandlers( - props.onCloseAutoFocus, - (event) => { - var _context$triggerRef$c; - if (!hasInteractedOutsideRef.current) - (_context$triggerRef$c = - context.triggerRef.current) === null || - _context$triggerRef$c === void 0 || - _context$triggerRef$c.focus(); - hasInteractedOutsideRef.current = false; // Always prevent auto focus because we either focus manually or want user agent focus - event.preventDefault(); - } - ), - onInteractOutside: - $7dQ7Q$radixuiprimitive.composeEventHandlers( - props.onInteractOutside, - (event) => { - const originalEvent = event.detail.originalEvent; - const ctrlLeftClick = - originalEvent.button === 0 && - originalEvent.ctrlKey === true; - const isRightClick = - originalEvent.button === 2 || ctrlLeftClick; - if (!context.modal || isRightClick) - hasInteractedOutsideRef.current = true; - } - ), - style: { - ...props.style, - "--radix-dropdown-menu-content-transform-origin": - "var(--radix-popper-transform-origin)", - "--radix-dropdown-menu-content-available-width": - "var(--radix-popper-available-width)", - "--radix-dropdown-menu-content-available-height": - "var(--radix-popper-available-height)", - "--radix-dropdown-menu-trigger-width": - "var(--radix-popper-anchor-width)", - "--radix-dropdown-menu-trigger-height": - "var(--radix-popper-anchor-height)", - }, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$6e76d93a37c01248, { - displayName: $d1bf075a6b218014$var$CONTENT_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuGroup - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$GROUP_NAME = "DropdownMenuGroup"; - const $d1bf075a6b218014$export$246bebaba3a2f70e = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { __scopeDropdownMenu: __scopeDropdownMenu, ...groupProps } = - props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Group, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - groupProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$246bebaba3a2f70e, { - displayName: $d1bf075a6b218014$var$GROUP_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuLabel - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$LABEL_NAME = "DropdownMenuLabel"; - const $d1bf075a6b218014$export$76e48c5b57f24495 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { __scopeDropdownMenu: __scopeDropdownMenu, ...labelProps } = - props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Label, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - labelProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$76e48c5b57f24495, { - displayName: $d1bf075a6b218014$var$LABEL_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuItem - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$ITEM_NAME = "DropdownMenuItem"; - const $d1bf075a6b218014$export$ed97964d1871885d = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { __scopeDropdownMenu: __scopeDropdownMenu, ...itemProps } = - props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Item, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - itemProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$ed97964d1871885d, { - displayName: $d1bf075a6b218014$var$ITEM_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuCheckboxItem - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME = - "DropdownMenuCheckboxItem"; - const $d1bf075a6b218014$export$53a69729da201fa9 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...checkboxItemProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.CheckboxItem, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - checkboxItemProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$53a69729da201fa9, { - displayName: $d1bf075a6b218014$var$CHECKBOX_ITEM_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuRadioGroup - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$RADIO_GROUP_NAME = "DropdownMenuRadioGroup"; - const $d1bf075a6b218014$export$3323ad73d55f587e = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...radioGroupProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.RadioGroup, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - radioGroupProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$3323ad73d55f587e, { - displayName: $d1bf075a6b218014$var$RADIO_GROUP_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuRadioItem - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$RADIO_ITEM_NAME = "DropdownMenuRadioItem"; - const $d1bf075a6b218014$export$e4f69b41b1637536 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...radioItemProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.RadioItem, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - radioItemProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$e4f69b41b1637536, { - displayName: $d1bf075a6b218014$var$RADIO_ITEM_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuItemIndicator - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$INDICATOR_NAME = - "DropdownMenuItemIndicator"; - const $d1bf075a6b218014$export$42355ae145153fb6 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...itemIndicatorProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.ItemIndicator, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - itemIndicatorProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$42355ae145153fb6, { - displayName: $d1bf075a6b218014$var$INDICATOR_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuSeparator - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$SEPARATOR_NAME = "DropdownMenuSeparator"; - const $d1bf075a6b218014$export$da160178fd3bc7e9 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...separatorProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Separator, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - separatorProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$da160178fd3bc7e9, { - displayName: $d1bf075a6b218014$var$SEPARATOR_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuArrow - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$ARROW_NAME = "DropdownMenuArrow"; - const $d1bf075a6b218014$export$34b8980744021ec5 = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { __scopeDropdownMenu: __scopeDropdownMenu, ...arrowProps } = - props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Arrow, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - arrowProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$34b8980744021ec5, { - displayName: $d1bf075a6b218014$var$ARROW_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuSub - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$export$2f307d81a64f5442 = (props) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - children: children, - open: openProp, - onOpenChange: onOpenChange, - defaultOpen: defaultOpen, - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - const [open = false, setOpen] = - $7dQ7Q$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: onOpenChange, - }); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.Sub, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - { - open: open, - onOpenChange: setOpen, - } - ), - children - ); - }; - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuSubTrigger - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$SUB_TRIGGER_NAME = "DropdownMenuSubTrigger"; - const $d1bf075a6b218014$export$21dcb7ec56f874cf = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...subTriggerProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.SubTrigger, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - subTriggerProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$21dcb7ec56f874cf, { - displayName: $d1bf075a6b218014$var$SUB_TRIGGER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * DropdownMenuSubContent - * -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$var$SUB_CONTENT_NAME = "DropdownMenuSubContent"; - const $d1bf075a6b218014$export$f34ec8bc2482cc5f = - /*#__PURE__*/ $7dQ7Q$react.forwardRef((props, forwardedRef) => { - const { - __scopeDropdownMenu: __scopeDropdownMenu, - ...subContentProps - } = props; - const menuScope = - $d1bf075a6b218014$var$useMenuScope(__scopeDropdownMenu); - return /*#__PURE__*/ $7dQ7Q$react.createElement( - $7dQ7Q$radixuireactmenu.SubContent, - $parcel$interopDefault($7dQ7Q$babelruntimehelpersextends)( - {}, - menuScope, - subContentProps, - { - ref: forwardedRef, - style: { - ...props.style, - "--radix-dropdown-menu-content-transform-origin": - "var(--radix-popper-transform-origin)", - "--radix-dropdown-menu-content-available-width": - "var(--radix-popper-available-width)", - "--radix-dropdown-menu-content-available-height": - "var(--radix-popper-available-height)", - "--radix-dropdown-menu-trigger-width": - "var(--radix-popper-anchor-width)", - "--radix-dropdown-menu-trigger-height": - "var(--radix-popper-anchor-height)", - }, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($d1bf075a6b218014$export$f34ec8bc2482cc5f, { - displayName: $d1bf075a6b218014$var$SUB_CONTENT_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - const $d1bf075a6b218014$export$be92b6f5f03c0fe9 = - $d1bf075a6b218014$export$e44a253a59704894; - const $d1bf075a6b218014$export$41fb9f06171c75f4 = - $d1bf075a6b218014$export$d2469213b3befba9; - const $d1bf075a6b218014$export$602eac185826482c = - $d1bf075a6b218014$export$cd369b4d4d54efc9; - const $d1bf075a6b218014$export$7c6e2c02157bb7d2 = - $d1bf075a6b218014$export$6e76d93a37c01248; - const $d1bf075a6b218014$export$eb2fcfdbd7ba97d4 = - $d1bf075a6b218014$export$246bebaba3a2f70e; - const $d1bf075a6b218014$export$b04be29aa201d4f5 = - $d1bf075a6b218014$export$76e48c5b57f24495; - const $d1bf075a6b218014$export$6d08773d2e66f8f2 = - $d1bf075a6b218014$export$ed97964d1871885d; - const $d1bf075a6b218014$export$16ce288f89fa631c = - $d1bf075a6b218014$export$53a69729da201fa9; - const $d1bf075a6b218014$export$a98f0dcb43a68a25 = - $d1bf075a6b218014$export$3323ad73d55f587e; - const $d1bf075a6b218014$export$371ab307eab489c0 = - $d1bf075a6b218014$export$e4f69b41b1637536; - const $d1bf075a6b218014$export$c3468e2714d175fa = - $d1bf075a6b218014$export$42355ae145153fb6; - const $d1bf075a6b218014$export$1ff3c3f08ae963c0 = - $d1bf075a6b218014$export$da160178fd3bc7e9; - const $d1bf075a6b218014$export$21b07c8f274aebd5 = - $d1bf075a6b218014$export$34b8980744021ec5; - const $d1bf075a6b218014$export$d7a01e11500dfb6f = - $d1bf075a6b218014$export$2f307d81a64f5442; - const $d1bf075a6b218014$export$2ea8a7a591ac5eac = - $d1bf075a6b218014$export$21dcb7ec56f874cf; - const $d1bf075a6b218014$export$6d4de93b380beddf = - $d1bf075a6b218014$export$f34ec8bc2482cc5f; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-focus-guards/dist/index.js ***! - \************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $cnctE$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "FocusGuards", - () => $71476a6ed7dbbaf3$export$ac5b58043b79449b - ); - $parcel$export( - module.exports, - "Root", - () => $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "useFocusGuards", - () => $71476a6ed7dbbaf3$export$b7ece24a22aeda8c - ); - - /** Number of components which have requested interest to have focus guards */ - let $71476a6ed7dbbaf3$var$count = 0; - function $71476a6ed7dbbaf3$export$ac5b58043b79449b(props) { - $71476a6ed7dbbaf3$export$b7ece24a22aeda8c(); - return props.children; - } - /** - * Injects a pair of focus guards at the edges of the whole DOM tree - * to ensure `focusin` & `focusout` events can be caught consistently. - */ - function $71476a6ed7dbbaf3$export$b7ece24a22aeda8c() { - $cnctE$react.useEffect(() => { - var _edgeGuards$, _edgeGuards$2; - const edgeGuards = document.querySelectorAll( - "[data-radix-focus-guard]" - ); - document.body.insertAdjacentElement( - "afterbegin", - (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 - ? _edgeGuards$ - : $71476a6ed7dbbaf3$var$createFocusGuard() - ); - document.body.insertAdjacentElement( - "beforeend", - (_edgeGuards$2 = edgeGuards[1]) !== null && - _edgeGuards$2 !== void 0 - ? _edgeGuards$2 - : $71476a6ed7dbbaf3$var$createFocusGuard() - ); - $71476a6ed7dbbaf3$var$count++; - return () => { - if ($71476a6ed7dbbaf3$var$count === 1) - document - .querySelectorAll("[data-radix-focus-guard]") - .forEach((node) => node.remove()); - $71476a6ed7dbbaf3$var$count--; - }; - }, []); - } - function $71476a6ed7dbbaf3$var$createFocusGuard() { - const element = document.createElement("span"); - element.setAttribute("data-radix-focus-guard", ""); - element.tabIndex = 0; - element.style.cssText = - "outline: none; opacity: 0; position: fixed; pointer-events: none"; - return element; - } - const $71476a6ed7dbbaf3$export$be92b6f5f03c0fe9 = - $71476a6ed7dbbaf3$export$ac5b58043b79449b; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-focus-scope/dist/index.js ***! - \***********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $buum9$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $buum9$react = __webpack_require__(/*! react */ "react"); - var $buum9$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $buum9$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $buum9$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "FocusScope", - () => $2bc01e66e04aa9ed$export$20e40289641fbbb6 - ); - $parcel$export( - module.exports, - "Root", - () => $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9 - ); - const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT = - "focusScope.autoFocusOnMount"; - const $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT = - "focusScope.autoFocusOnUnmount"; - const $2bc01e66e04aa9ed$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true, - }; - /* ------------------------------------------------------------------------------------------------- - * FocusScope - * -----------------------------------------------------------------------------------------------*/ - const $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME = "FocusScope"; - const $2bc01e66e04aa9ed$export$20e40289641fbbb6 = - /*#__PURE__*/ $buum9$react.forwardRef((props, forwardedRef) => { - const { - loop = false, - trapped = false, - onMountAutoFocus: onMountAutoFocusProp, - onUnmountAutoFocus: onUnmountAutoFocusProp, - ...scopeProps - } = props; - const [container1, setContainer] = $buum9$react.useState(null); - const onMountAutoFocus = - $buum9$radixuireactusecallbackref.useCallbackRef( - onMountAutoFocusProp - ); - const onUnmountAutoFocus = - $buum9$radixuireactusecallbackref.useCallbackRef( - onUnmountAutoFocusProp - ); - const lastFocusedElementRef = $buum9$react.useRef(null); - const composedRefs = $buum9$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - (node) => setContainer(node) - ); - const focusScope = $buum9$react.useRef({ - paused: false, - pause() { - this.paused = true; - }, - resume() { - this.paused = false; - }, - }).current; // Takes care of trapping focus if focus is moved outside programmatically for example - $buum9$react.useEffect(() => { - if (trapped) { - function handleFocusIn(event) { - if (focusScope.paused || !container1) return; - const target = event.target; - if (container1.contains(target)) - lastFocusedElementRef.current = target; - else - $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { - select: true, - }); - } - function handleFocusOut(event) { - if (focusScope.paused || !container1) return; - const relatedTarget = event.relatedTarget; // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases: - // - // 1. When the user switches app/tabs/windows/the browser itself loses focus. - // 2. In Google Chrome, when the focused element is removed from the DOM. - // - // We let the browser do its thing here because: - // - // 1. The browser already keeps a memory of what's focused for when the page gets refocused. - // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it - // throws the CPU to 100%, so we avoid doing anything for this reason here too. - if (relatedTarget === null) return; // If the focus has moved to an actual legitimate element (`relatedTarget !== null`) - // that is outside the container, we move focus to the last valid focused element inside. - if (!container1.contains(relatedTarget)) - $2bc01e66e04aa9ed$var$focus(lastFocusedElementRef.current, { - select: true, - }); - } // When the focused element gets removed from the DOM, browsers move focus - // back to the document.body. In this case, we move focus to the container - // to keep focus trapped correctly. - function handleMutations(mutations) { - const focusedElement = document.activeElement; - for (const mutation of mutations) { - if (mutation.removedNodes.length > 0) { - if ( - !( - container1 !== null && - container1 !== void 0 && - container1.contains(focusedElement) - ) - ) - $2bc01e66e04aa9ed$var$focus(container1); - } - } - } - document.addEventListener("focusin", handleFocusIn); - document.addEventListener("focusout", handleFocusOut); - const mutationObserver = new MutationObserver(handleMutations); - if (container1) - mutationObserver.observe(container1, { - childList: true, - subtree: true, - }); - return () => { - document.removeEventListener("focusin", handleFocusIn); - document.removeEventListener("focusout", handleFocusOut); - mutationObserver.disconnect(); - }; - } - }, [trapped, container1, focusScope.paused]); - $buum9$react.useEffect(() => { - if (container1) { - $2bc01e66e04aa9ed$var$focusScopesStack.add(focusScope); - const previouslyFocusedElement = document.activeElement; - const hasFocusedCandidate = container1.contains( - previouslyFocusedElement - ); - if (!hasFocusedCandidate) { - const mountEvent = new CustomEvent( - $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, - $2bc01e66e04aa9ed$var$EVENT_OPTIONS - ); - container1.addEventListener( - $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, - onMountAutoFocus - ); - container1.dispatchEvent(mountEvent); - if (!mountEvent.defaultPrevented) { - $2bc01e66e04aa9ed$var$focusFirst( - $2bc01e66e04aa9ed$var$removeLinks( - $2bc01e66e04aa9ed$var$getTabbableCandidates(container1) - ), - { - select: true, - } - ); - if (document.activeElement === previouslyFocusedElement) - $2bc01e66e04aa9ed$var$focus(container1); - } - } - return () => { - container1.removeEventListener( - $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_MOUNT, - onMountAutoFocus - ); // We hit a react bug (fixed in v17) with focusing in unmount. - // We need to delay the focus a little to get around it for now. - // See: https://github.com/facebook/react/issues/17894 - setTimeout(() => { - const unmountEvent = new CustomEvent( - $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, - $2bc01e66e04aa9ed$var$EVENT_OPTIONS - ); - container1.addEventListener( - $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, - onUnmountAutoFocus - ); - container1.dispatchEvent(unmountEvent); - if (!unmountEvent.defaultPrevented) - $2bc01e66e04aa9ed$var$focus( - previouslyFocusedElement !== null && - previouslyFocusedElement !== void 0 - ? previouslyFocusedElement - : document.body, - { - select: true, - } - ); - // we need to remove the listener after we `dispatchEvent` - container1.removeEventListener( - $2bc01e66e04aa9ed$var$AUTOFOCUS_ON_UNMOUNT, - onUnmountAutoFocus - ); - $2bc01e66e04aa9ed$var$focusScopesStack.remove(focusScope); - }, 0); - }; - } - }, [container1, onMountAutoFocus, onUnmountAutoFocus, focusScope]); // Takes care of looping focus (when tabbing whilst at the edges) - const handleKeyDown = $buum9$react.useCallback( - (event) => { - if (!loop && !trapped) return; - if (focusScope.paused) return; - const isTabKey = - event.key === "Tab" && - !event.altKey && - !event.ctrlKey && - !event.metaKey; - const focusedElement = document.activeElement; - if (isTabKey && focusedElement) { - const container = event.currentTarget; - const [first, last] = - $2bc01e66e04aa9ed$var$getTabbableEdges(container); - const hasTabbableElementsInside = first && last; // we can only wrap focus if we have tabbable edges - if (!hasTabbableElementsInside) { - if (focusedElement === container) event.preventDefault(); - } else { - if (!event.shiftKey && focusedElement === last) { - event.preventDefault(); - if (loop) - $2bc01e66e04aa9ed$var$focus(first, { - select: true, - }); - } else if (event.shiftKey && focusedElement === first) { - event.preventDefault(); - if (loop) - $2bc01e66e04aa9ed$var$focus(last, { - select: true, - }); - } - } - } - }, - [loop, trapped, focusScope.paused] - ); - return /*#__PURE__*/ $buum9$react.createElement( - $buum9$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($buum9$babelruntimehelpersextends)( - { - tabIndex: -1, - }, - scopeProps, - { - ref: composedRefs, - onKeyDown: handleKeyDown, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($2bc01e66e04aa9ed$export$20e40289641fbbb6, { - displayName: $2bc01e66e04aa9ed$var$FOCUS_SCOPE_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Attempts focusing the first element in a list of candidates. - * Stops when focus has actually moved. - */ - function $2bc01e66e04aa9ed$var$focusFirst( - candidates, - { select = false } = {} - ) { - const previouslyFocusedElement = document.activeElement; - for (const candidate of candidates) { - $2bc01e66e04aa9ed$var$focus(candidate, { - select: select, - }); - if (document.activeElement !== previouslyFocusedElement) return; - } - } - /** - * Returns the first and last tabbable elements inside a container. - */ - function $2bc01e66e04aa9ed$var$getTabbableEdges(container) { - const candidates = - $2bc01e66e04aa9ed$var$getTabbableCandidates(container); - const first = $2bc01e66e04aa9ed$var$findVisible( - candidates, - container - ); - const last = $2bc01e66e04aa9ed$var$findVisible( - candidates.reverse(), - container - ); - return [first, last]; - } - /** - * Returns a list of potential tabbable candidates. - * - * NOTE: This is only a close approximation. For example it doesn't take into account cases like when - * elements are not visible. This cannot be worked out easily by just reading a property, but rather - * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately. - * - * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker - * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1 - */ - function $2bc01e66e04aa9ed$var$getTabbableCandidates(container) { - const nodes = []; - const walker = document.createTreeWalker( - container, - NodeFilter.SHOW_ELEMENT, - { - acceptNode: (node) => { - const isHiddenInput = - node.tagName === "INPUT" && node.type === "hidden"; - if (node.disabled || node.hidden || isHiddenInput) - return NodeFilter.FILTER_SKIP; // `.tabIndex` is not the same as the `tabindex` attribute. It works on the - // runtime's understanding of tabbability, so this automatically accounts - // for any kind of element that could be tabbed to. - return node.tabIndex >= 0 - ? NodeFilter.FILTER_ACCEPT - : NodeFilter.FILTER_SKIP; - }, - } - ); - while (walker.nextNode()) nodes.push(walker.currentNode); // we do not take into account the order of nodes with positive `tabIndex` as it - // hinders accessibility to have tab order different from visual order. - return nodes; - } - /** - * Returns the first visible element in a list. - * NOTE: Only checks visibility up to the `container`. - */ - function $2bc01e66e04aa9ed$var$findVisible(elements, container) { - for (const element of elements) { - // we stop checking if it's hidden at the `container` level (excluding) - if ( - !$2bc01e66e04aa9ed$var$isHidden(element, { - upTo: container, - }) - ) - return element; - } - } - function $2bc01e66e04aa9ed$var$isHidden(node, { upTo: upTo }) { - if (getComputedStyle(node).visibility === "hidden") return true; - while (node) { - // we stop at `upTo` (excluding it) - if (upTo !== undefined && node === upTo) return false; - if (getComputedStyle(node).display === "none") return true; - node = node.parentElement; - } - return false; - } - function $2bc01e66e04aa9ed$var$isSelectableInput(element) { - return element instanceof HTMLInputElement && "select" in element; - } - function $2bc01e66e04aa9ed$var$focus(element, { select = false } = {}) { - // only focus if that element is focusable - if (element && element.focus) { - const previouslyFocusedElement = document.activeElement; // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users - element.focus({ - preventScroll: true, - }); // only select if its not the same element, it supports selection and we need to select - if ( - element !== previouslyFocusedElement && - $2bc01e66e04aa9ed$var$isSelectableInput(element) && - select - ) - element.select(); - } - } - /* ------------------------------------------------------------------------------------------------- - * FocusScope stack - * -----------------------------------------------------------------------------------------------*/ - const $2bc01e66e04aa9ed$var$focusScopesStack = - $2bc01e66e04aa9ed$var$createFocusScopesStack(); - function $2bc01e66e04aa9ed$var$createFocusScopesStack() { - /** A stack of focus scopes, with the active one at the top */ let stack = - []; - return { - add(focusScope) { - // pause the currently active focus scope (at the top of the stack) - const activeFocusScope = stack[0]; - if (focusScope !== activeFocusScope) - activeFocusScope === null || - activeFocusScope === void 0 || - activeFocusScope.pause(); - // remove in case it already exists (because we'll re-add it at the top of the stack) - stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); - stack.unshift(focusScope); - }, - remove(focusScope) { - var _stack$; - stack = $2bc01e66e04aa9ed$var$arrayRemove(stack, focusScope); - (_stack$ = stack[0]) === null || - _stack$ === void 0 || - _stack$.resume(); - }, - }; - } - function $2bc01e66e04aa9ed$var$arrayRemove(array, item) { - const updatedArray = [...array]; - const index = updatedArray.indexOf(item); - if (index !== -1) updatedArray.splice(index, 1); - return updatedArray; - } - function $2bc01e66e04aa9ed$var$removeLinks(items) { - return items.filter((item) => item.tagName !== "A"); - } - const $2bc01e66e04aa9ed$export$be92b6f5f03c0fe9 = - $2bc01e66e04aa9ed$export$20e40289641fbbb6; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-id/dist/index.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-id/dist/index.js ***! - \**************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $47woD$react = __webpack_require__(/*! react */ "react"); - var $47woD$radixuireactuselayouteffect = __webpack_require__( - /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useId", - () => $dc478e4659f630c5$export$f680877a34711e37 - ); - const $dc478e4659f630c5$var$useReactId = - $47woD$react["useId".toString()] || (() => undefined); - let $dc478e4659f630c5$var$count = 0; - function $dc478e4659f630c5$export$f680877a34711e37(deterministicId) { - const [id, setId] = $47woD$react.useState( - $dc478e4659f630c5$var$useReactId() - ); // React versions older than 18 will have client-side ids only. - $47woD$radixuireactuselayouteffect.useLayoutEffect(() => { - if (!deterministicId) - setId((reactId) => - reactId !== null && reactId !== void 0 - ? reactId - : String($dc478e4659f630c5$var$count++) - ); - }, [deterministicId]); - return deterministicId || (id ? `radix-${id}` : ""); - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-menu/dist/index.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-menu/dist/index.js ***! - \****************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $cnSS2$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $cnSS2$react = __webpack_require__(/*! react */ "react"); - var $cnSS2$radixuiprimitive = __webpack_require__( - /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" - ); - var $cnSS2$radixuireactcollection = __webpack_require__( - /*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js" - ); - var $cnSS2$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $cnSS2$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $cnSS2$radixuireactdirection = __webpack_require__( - /*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js" - ); - var $cnSS2$radixuireactdismissablelayer = __webpack_require__( - /*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js" - ); - var $cnSS2$radixuireactfocusguards = __webpack_require__( - /*! @radix-ui/react-focus-guards */ "../../../node_modules/@radix-ui/react-focus-guards/dist/index.js" - ); - var $cnSS2$radixuireactfocusscope = __webpack_require__( - /*! @radix-ui/react-focus-scope */ "../../../node_modules/@radix-ui/react-focus-scope/dist/index.js" - ); - var $cnSS2$radixuireactid = __webpack_require__( - /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" - ); - var $cnSS2$radixuireactpopper = __webpack_require__( - /*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js" - ); - var $cnSS2$radixuireactportal = __webpack_require__( - /*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js" - ); - var $cnSS2$radixuireactpresence = __webpack_require__( - /*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js" - ); - var $cnSS2$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $cnSS2$radixuireactrovingfocus = __webpack_require__( - /*! @radix-ui/react-roving-focus */ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js" - ); - var $cnSS2$radixuireactslot = __webpack_require__( - /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" - ); - var $cnSS2$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - var $cnSS2$ariahidden = __webpack_require__( - /*! aria-hidden */ "../../../node_modules/aria-hidden/dist/es2015/index.js" - ); - var $cnSS2$reactremovescroll = __webpack_require__( - /*! react-remove-scroll */ "../../../node_modules/react-remove-scroll/dist/es2015/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createMenuScope", - () => $213e4d2df823067d$export$4027731b685e72eb - ); - $parcel$export( - module.exports, - "Menu", - () => $213e4d2df823067d$export$d9b273488cd8ce6f - ); - $parcel$export( - module.exports, - "MenuAnchor", - () => $213e4d2df823067d$export$9fa5ebd18bee4d43 - ); - $parcel$export( - module.exports, - "MenuPortal", - () => $213e4d2df823067d$export$793392f970497feb - ); - $parcel$export( - module.exports, - "MenuContent", - () => $213e4d2df823067d$export$479f0f2f71193efe - ); - $parcel$export( - module.exports, - "MenuGroup", - () => $213e4d2df823067d$export$22a631d1f72787bb - ); - $parcel$export( - module.exports, - "MenuLabel", - () => $213e4d2df823067d$export$dd37bec0e8a99143 - ); - $parcel$export( - module.exports, - "MenuItem", - () => $213e4d2df823067d$export$2ce376c2cc3355c8 - ); - $parcel$export( - module.exports, - "MenuCheckboxItem", - () => $213e4d2df823067d$export$f6f243521332502d - ); - $parcel$export( - module.exports, - "MenuRadioGroup", - () => $213e4d2df823067d$export$ea2200c9eee416b3 - ); - $parcel$export( - module.exports, - "MenuRadioItem", - () => $213e4d2df823067d$export$69bd225e9817f6d0 - ); - $parcel$export( - module.exports, - "MenuItemIndicator", - () => $213e4d2df823067d$export$a2593e23056970a3 - ); - $parcel$export( - module.exports, - "MenuSeparator", - () => $213e4d2df823067d$export$1cec7dcdd713e220 - ); - $parcel$export( - module.exports, - "MenuArrow", - () => $213e4d2df823067d$export$bcdda4773debf5fa - ); - $parcel$export( - module.exports, - "MenuSub", - () => $213e4d2df823067d$export$71bdb9d1e2909932 - ); - $parcel$export( - module.exports, - "MenuSubTrigger", - () => $213e4d2df823067d$export$5fbbb3ba7297405f - ); - $parcel$export( - module.exports, - "MenuSubContent", - () => $213e4d2df823067d$export$e7142ab31822bde6 - ); - $parcel$export( - module.exports, - "Root", - () => $213e4d2df823067d$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Anchor", - () => $213e4d2df823067d$export$b688253958b8dfe7 - ); - $parcel$export( - module.exports, - "Portal", - () => $213e4d2df823067d$export$602eac185826482c - ); - $parcel$export( - module.exports, - "Content", - () => $213e4d2df823067d$export$7c6e2c02157bb7d2 - ); - $parcel$export( - module.exports, - "Group", - () => $213e4d2df823067d$export$eb2fcfdbd7ba97d4 - ); - $parcel$export( - module.exports, - "Label", - () => $213e4d2df823067d$export$b04be29aa201d4f5 - ); - $parcel$export( - module.exports, - "Item", - () => $213e4d2df823067d$export$6d08773d2e66f8f2 - ); - $parcel$export( - module.exports, - "CheckboxItem", - () => $213e4d2df823067d$export$16ce288f89fa631c - ); - $parcel$export( - module.exports, - "RadioGroup", - () => $213e4d2df823067d$export$a98f0dcb43a68a25 - ); - $parcel$export( - module.exports, - "RadioItem", - () => $213e4d2df823067d$export$371ab307eab489c0 - ); - $parcel$export( - module.exports, - "ItemIndicator", - () => $213e4d2df823067d$export$c3468e2714d175fa - ); - $parcel$export( - module.exports, - "Separator", - () => $213e4d2df823067d$export$1ff3c3f08ae963c0 - ); - $parcel$export( - module.exports, - "Arrow", - () => $213e4d2df823067d$export$21b07c8f274aebd5 - ); - $parcel$export( - module.exports, - "Sub", - () => $213e4d2df823067d$export$d7a01e11500dfb6f - ); - $parcel$export( - module.exports, - "SubTrigger", - () => $213e4d2df823067d$export$2ea8a7a591ac5eac - ); - $parcel$export( - module.exports, - "SubContent", - () => $213e4d2df823067d$export$6d4de93b380beddf - ); - const $213e4d2df823067d$var$SELECTION_KEYS = ["Enter", " "]; - const $213e4d2df823067d$var$FIRST_KEYS = [ - "ArrowDown", - "PageUp", - "Home", - ]; - const $213e4d2df823067d$var$LAST_KEYS = ["ArrowUp", "PageDown", "End"]; - const $213e4d2df823067d$var$FIRST_LAST_KEYS = [ - ...$213e4d2df823067d$var$FIRST_KEYS, - ...$213e4d2df823067d$var$LAST_KEYS, - ]; - const $213e4d2df823067d$var$SUB_OPEN_KEYS = { - ltr: [...$213e4d2df823067d$var$SELECTION_KEYS, "ArrowRight"], - rtl: [...$213e4d2df823067d$var$SELECTION_KEYS, "ArrowLeft"], - }; - const $213e4d2df823067d$var$SUB_CLOSE_KEYS = { - ltr: ["ArrowLeft"], - rtl: ["ArrowRight"], - }; - /* ------------------------------------------------------------------------------------------------- - * Menu - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$MENU_NAME = "Menu"; - const [ - $213e4d2df823067d$var$Collection, - $213e4d2df823067d$var$useCollection, - $213e4d2df823067d$var$createCollectionScope, - ] = $cnSS2$radixuireactcollection.createCollection( - $213e4d2df823067d$var$MENU_NAME - ); - const [ - $213e4d2df823067d$var$createMenuContext, - $213e4d2df823067d$export$4027731b685e72eb, - ] = $cnSS2$radixuireactcontext.createContextScope( - $213e4d2df823067d$var$MENU_NAME, - [ - $213e4d2df823067d$var$createCollectionScope, - $cnSS2$radixuireactpopper.createPopperScope, - $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope, - ] - ); - const $213e4d2df823067d$var$usePopperScope = - $cnSS2$radixuireactpopper.createPopperScope(); - const $213e4d2df823067d$var$useRovingFocusGroupScope = - $cnSS2$radixuireactrovingfocus.createRovingFocusGroupScope(); - const [ - $213e4d2df823067d$var$MenuProvider, - $213e4d2df823067d$var$useMenuContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$MENU_NAME - ); - const [ - $213e4d2df823067d$var$MenuRootProvider, - $213e4d2df823067d$var$useMenuRootContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$MENU_NAME - ); - const $213e4d2df823067d$export$d9b273488cd8ce6f = (props) => { - const { - __scopeMenu: __scopeMenu, - open = false, - children: children, - dir: dir, - onOpenChange: onOpenChange, - modal = true, - } = props; - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const [content, setContent] = $cnSS2$react.useState(null); - const isUsingKeyboardRef = $cnSS2$react.useRef(false); - const handleOpenChange = - $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); - const direction = $cnSS2$radixuireactdirection.useDirection(dir); - $cnSS2$react.useEffect(() => { - // Capture phase ensures we set the boolean before any side effects execute - // in response to the key or pointer event as they might depend on this value. - const handleKeyDown = () => { - isUsingKeyboardRef.current = true; - document.addEventListener("pointerdown", handlePointer, { - capture: true, - once: true, - }); - document.addEventListener("pointermove", handlePointer, { - capture: true, - once: true, - }); - }; - const handlePointer = () => (isUsingKeyboardRef.current = false); - document.addEventListener("keydown", handleKeyDown, { - capture: true, - }); - return () => { - document.removeEventListener("keydown", handleKeyDown, { - capture: true, - }); - document.removeEventListener("pointerdown", handlePointer, { - capture: true, - }); - document.removeEventListener("pointermove", handlePointer, { - capture: true, - }); - }; - }, []); - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpopper.Root, - popperScope, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuProvider, - { - scope: __scopeMenu, - open: open, - onOpenChange: handleOpenChange, - content: content, - onContentChange: setContent, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuRootProvider, - { - scope: __scopeMenu, - onClose: $cnSS2$react.useCallback( - () => handleOpenChange(false), - [handleOpenChange] - ), - isUsingKeyboardRef: isUsingKeyboardRef, - dir: direction, - modal: modal, - }, - children - ) - ) - ); - }; - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$d9b273488cd8ce6f, { - displayName: $213e4d2df823067d$var$MENU_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuAnchor - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$ANCHOR_NAME = "MenuAnchor"; - const $213e4d2df823067d$export$9fa5ebd18bee4d43 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { __scopeMenu: __scopeMenu, ...anchorProps } = props; - const popperScope = - $213e4d2df823067d$var$usePopperScope(__scopeMenu); - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpopper.Anchor, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - popperScope, - anchorProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$9fa5ebd18bee4d43, { - displayName: $213e4d2df823067d$var$ANCHOR_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuPortal - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$PORTAL_NAME = "MenuPortal"; - const [ - $213e4d2df823067d$var$PortalProvider, - $213e4d2df823067d$var$usePortalContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$PORTAL_NAME, - { - forceMount: undefined, - } - ); - const $213e4d2df823067d$export$793392f970497feb = (props) => { - const { - __scopeMenu: __scopeMenu, - forceMount: forceMount, - children: children, - container: container, - } = props; - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$PORTAL_NAME, - __scopeMenu - ); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$PortalProvider, - { - scope: __scopeMenu, - forceMount: forceMount, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactportal.Portal, - { - asChild: true, - container: container, - }, - children - ) - ) - ); - }; - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$793392f970497feb, { - displayName: $213e4d2df823067d$var$PORTAL_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuContent - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$CONTENT_NAME = "MenuContent"; - const [ - $213e4d2df823067d$var$MenuContentProvider, - $213e4d2df823067d$var$useMenuContentContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$CONTENT_NAME - ); - const $213e4d2df823067d$export$479f0f2f71193efe = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const portalContext = $213e4d2df823067d$var$usePortalContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - const { forceMount = portalContext.forceMount, ...contentProps } = - props; - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - const rootContext = $213e4d2df823067d$var$useMenuRootContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$Collection.Provider, - { - scope: props.__scopeMenu, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$Collection.Slot, - { - scope: props.__scopeMenu, - }, - rootContext.modal - ? /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuRootContentModal, - $parcel$interopDefault( - $cnSS2$babelruntimehelpersextends - )({}, contentProps, { - ref: forwardedRef, - }) - ) - : /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuRootContentNonModal, - $parcel$interopDefault( - $cnSS2$babelruntimehelpersextends - )({}, contentProps, { - ref: forwardedRef, - }) - ) - ) - ) - ); - }); - /* ---------------------------------------------------------------------------------------------- */ - const $213e4d2df823067d$var$MenuRootContentModal = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); // Hide everything from ARIA except the `MenuContent` - $cnSS2$react.useEffect(() => { - const content = ref.current; - if (content) return $cnSS2$ariahidden.hideOthers(content); - }, []); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuContentImpl, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - props, - { - ref: composedRefs, // we make sure we're not trapping once it's been closed - trapFocus: context.open, // make sure to only disable pointer events when open - disableOutsidePointerEvents: context.open, - disableOutsideScroll: true, // When focus is trapped, a `focusout` event may still happen. - onFocusOutside: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onFocusOutside, - (event) => event.preventDefault(), - { - checkForDefaultPrevented: false, - } - ), - onDismiss: () => context.onOpenChange(false), - } - ) - ); - }); - const $213e4d2df823067d$var$MenuRootContentNonModal = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuContentImpl, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - props, - { - ref: forwardedRef, - trapFocus: false, - disableOutsidePointerEvents: false, - disableOutsideScroll: false, - onDismiss: () => context.onOpenChange(false), - } - ) - ); - }); - /* ---------------------------------------------------------------------------------------------- */ - const $213e4d2df823067d$var$MenuContentImpl = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - loop = false, - trapFocus: trapFocus, - onOpenAutoFocus: onOpenAutoFocus, - onCloseAutoFocus: onCloseAutoFocus, - disableOutsidePointerEvents: disableOutsidePointerEvents, - onEntryFocus: onEntryFocus, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - disableOutsideScroll: disableOutsideScroll, - ...contentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$CONTENT_NAME, - __scopeMenu - ); - const rootContext = $213e4d2df823067d$var$useMenuRootContext( - $213e4d2df823067d$var$CONTENT_NAME, - __scopeMenu - ); - const popperScope = - $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const rovingFocusGroupScope = - $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); - const getItems = $213e4d2df823067d$var$useCollection(__scopeMenu); - const [currentItemId, setCurrentItemId] = - $cnSS2$react.useState(null); - const contentRef = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - contentRef, - context.onContentChange - ); - const timerRef = $cnSS2$react.useRef(0); - const searchRef = $cnSS2$react.useRef(""); - const pointerGraceTimerRef = $cnSS2$react.useRef(0); - const pointerGraceIntentRef = $cnSS2$react.useRef(null); - const pointerDirRef = $cnSS2$react.useRef("right"); - const lastPointerXRef = $cnSS2$react.useRef(0); - const ScrollLockWrapper = disableOutsideScroll - ? $cnSS2$reactremovescroll.RemoveScroll - : $cnSS2$react.Fragment; - const scrollLockWrapperProps = disableOutsideScroll - ? { - as: $cnSS2$radixuireactslot.Slot, - allowPinchZoom: true, - } - : undefined; - const handleTypeaheadSearch = (key) => { - var _items$find, _items$find2; - const search = searchRef.current + key; - const items = getItems().filter((item) => !item.disabled); - const currentItem = document.activeElement; - const currentMatch = - (_items$find = items.find( - (item) => item.ref.current === currentItem - )) === null || _items$find === void 0 - ? void 0 - : _items$find.textValue; - const values = items.map((item) => item.textValue); - const nextMatch = $213e4d2df823067d$var$getNextMatch( - values, - search, - currentMatch - ); - const newItem = - (_items$find2 = items.find( - (item) => item.textValue === nextMatch - )) === null || _items$find2 === void 0 - ? void 0 - : _items$find2.ref.current; // Reset `searchRef` 1 second after it was last updated - (function updateSearch(value) { - searchRef.current = value; - window.clearTimeout(timerRef.current); - if (value !== "") - timerRef.current = window.setTimeout( - () => updateSearch(""), - 1000 - ); - })(search); - if (newItem) - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => newItem.focus()); - }; - $cnSS2$react.useEffect(() => { - return () => window.clearTimeout(timerRef.current); - }, []); // Make sure the whole tree has focus guards as our `MenuContent` may be - // the last element in the DOM (beacuse of the `Portal`) - $cnSS2$radixuireactfocusguards.useFocusGuards(); - const isPointerMovingToSubmenu = $cnSS2$react.useCallback( - (event) => { - var _pointerGraceIntentRe, _pointerGraceIntentRe2; - const isMovingTowards = - pointerDirRef.current === - ((_pointerGraceIntentRe = pointerGraceIntentRef.current) === - null || _pointerGraceIntentRe === void 0 - ? void 0 - : _pointerGraceIntentRe.side); - return ( - isMovingTowards && - $213e4d2df823067d$var$isPointerInGraceArea( - event, - (_pointerGraceIntentRe2 = pointerGraceIntentRef.current) === - null || _pointerGraceIntentRe2 === void 0 - ? void 0 - : _pointerGraceIntentRe2.area - ) - ); - }, - [] - ); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuContentProvider, - { - scope: __scopeMenu, - searchRef: searchRef, - onItemEnter: $cnSS2$react.useCallback( - (event) => { - if (isPointerMovingToSubmenu(event)) event.preventDefault(); - }, - [isPointerMovingToSubmenu] - ), - onItemLeave: $cnSS2$react.useCallback( - (event) => { - var _contentRef$current; - if (isPointerMovingToSubmenu(event)) return; - (_contentRef$current = contentRef.current) === null || - _contentRef$current === void 0 || - _contentRef$current.focus(); - setCurrentItemId(null); - }, - [isPointerMovingToSubmenu] - ), - onTriggerLeave: $cnSS2$react.useCallback( - (event) => { - if (isPointerMovingToSubmenu(event)) event.preventDefault(); - }, - [isPointerMovingToSubmenu] - ), - pointerGraceTimerRef: pointerGraceTimerRef, - onPointerGraceIntentChange: $cnSS2$react.useCallback( - (intent) => { - pointerGraceIntentRef.current = intent; - }, - [] - ), - }, - /*#__PURE__*/ $cnSS2$react.createElement( - ScrollLockWrapper, - scrollLockWrapperProps, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactfocusscope.FocusScope, - { - asChild: true, - trapped: trapFocus, - onMountAutoFocus: - $cnSS2$radixuiprimitive.composeEventHandlers( - onOpenAutoFocus, - (event) => { - var _contentRef$current2; - // when opening, explicitly focus the content area only and leave - // `onEntryFocus` in control of focusing first item - event.preventDefault(); - (_contentRef$current2 = contentRef.current) === - null || - _contentRef$current2 === void 0 || - _contentRef$current2.focus(); - } - ), - onUnmountAutoFocus: onCloseAutoFocus, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactdismissablelayer.DismissableLayer, - { - asChild: true, - disableOutsidePointerEvents: disableOutsidePointerEvents, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: onFocusOutside, - onInteractOutside: onInteractOutside, - onDismiss: onDismiss, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactrovingfocus.Root, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - asChild: true, - }, - rovingFocusGroupScope, - { - dir: rootContext.dir, - orientation: "vertical", - loop: loop, - currentTabStopId: currentItemId, - onCurrentTabStopIdChange: setCurrentItemId, - onEntryFocus: - $cnSS2$radixuiprimitive.composeEventHandlers( - onEntryFocus, - (event) => { - // only focus first item when using keyboard - if (!rootContext.isUsingKeyboardRef.current) - event.preventDefault(); - } - ), - } - ), - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpopper.Content, - $parcel$interopDefault( - $cnSS2$babelruntimehelpersextends - )( - { - role: "menu", - "aria-orientation": "vertical", - "data-state": $213e4d2df823067d$var$getOpenState( - context.open - ), - "data-radix-menu-content": "", - dir: rootContext.dir, - }, - popperScope, - contentProps, - { - ref: composedRefs, - style: { - outline: "none", - ...contentProps.style, - }, - onKeyDown: - $cnSS2$radixuiprimitive.composeEventHandlers( - contentProps.onKeyDown, - (event) => { - // submenu key events bubble through portals. We only care about keys in this menu. - const target = event.target; - const isKeyDownInside = - target.closest( - "[data-radix-menu-content]" - ) === event.currentTarget; - const isModifierKey = - event.ctrlKey || - event.altKey || - event.metaKey; - const isCharacterKey = event.key.length === 1; - if (isKeyDownInside) { - // menus should not be navigated using tab key so we prevent it - if (event.key === "Tab") - event.preventDefault(); - if (!isModifierKey && isCharacterKey) - handleTypeaheadSearch(event.key); - } // focus first/last item based on key pressed - const content = contentRef.current; - if (event.target !== content) return; - if ( - !$213e4d2df823067d$var$FIRST_LAST_KEYS.includes( - event.key - ) - ) - return; - event.preventDefault(); - const items = getItems().filter( - (item) => !item.disabled - ); - const candidateNodes = items.map( - (item) => item.ref.current - ); - if ( - $213e4d2df823067d$var$LAST_KEYS.includes( - event.key - ) - ) - candidateNodes.reverse(); - $213e4d2df823067d$var$focusFirst( - candidateNodes - ); - } - ), - onBlur: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onBlur, - (event) => { - // clear search buffer when leaving the menu - if ( - !event.currentTarget.contains(event.target) - ) { - window.clearTimeout(timerRef.current); - searchRef.current = ""; - } - } - ), - onPointerMove: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onPointerMove, - $213e4d2df823067d$var$whenMouse((event) => { - const target = event.target; - const pointerXHasChanged = - lastPointerXRef.current !== event.clientX; // We don't use `event.movementX` for this check because Safari will - // always return `0` on a pointer event. - if ( - event.currentTarget.contains(target) && - pointerXHasChanged - ) { - const newDir = - event.clientX > lastPointerXRef.current - ? "right" - : "left"; - pointerDirRef.current = newDir; - lastPointerXRef.current = event.clientX; - } - }) - ), - } - ) - ) - ) - ) - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$479f0f2f71193efe, { - displayName: $213e4d2df823067d$var$CONTENT_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuGroup - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$GROUP_NAME = "MenuGroup"; - const $213e4d2df823067d$export$22a631d1f72787bb = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { __scopeMenu: __scopeMenu, ...groupProps } = props; - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - role: "group", - }, - groupProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$22a631d1f72787bb, { - displayName: $213e4d2df823067d$var$GROUP_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuLabel - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$LABEL_NAME = "MenuLabel"; - const $213e4d2df823067d$export$dd37bec0e8a99143 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { __scopeMenu: __scopeMenu, ...labelProps } = props; - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - labelProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$dd37bec0e8a99143, { - displayName: $213e4d2df823067d$var$LABEL_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuItem - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$ITEM_NAME = "MenuItem"; - const $213e4d2df823067d$var$ITEM_SELECT = "menu.itemSelect"; - const $213e4d2df823067d$export$2ce376c2cc3355c8 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { - disabled = false, - onSelect: onSelect, - ...itemProps - } = props; - const ref = $cnSS2$react.useRef(null); - const rootContext = $213e4d2df823067d$var$useMenuRootContext( - $213e4d2df823067d$var$ITEM_NAME, - props.__scopeMenu - ); - const contentContext = $213e4d2df823067d$var$useMenuContentContext( - $213e4d2df823067d$var$ITEM_NAME, - props.__scopeMenu - ); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - const isPointerDownRef = $cnSS2$react.useRef(false); - const handleSelect = () => { - const menuItem = ref.current; - if (!disabled && menuItem) { - const itemSelectEvent = new CustomEvent( - $213e4d2df823067d$var$ITEM_SELECT, - { - bubbles: true, - cancelable: true, - } - ); - menuItem.addEventListener( - $213e4d2df823067d$var$ITEM_SELECT, - (event) => - onSelect === null || onSelect === void 0 - ? void 0 - : onSelect(event), - { - once: true, - } - ); - $cnSS2$radixuireactprimitive.dispatchDiscreteCustomEvent( - menuItem, - itemSelectEvent - ); - if (itemSelectEvent.defaultPrevented) - isPointerDownRef.current = false; - else rootContext.onClose(); - } - }; - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuItemImpl, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - itemProps, - { - ref: composedRefs, - disabled: disabled, - onClick: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onClick, - handleSelect - ), - onPointerDown: (event) => { - var _props$onPointerDown; - (_props$onPointerDown = props.onPointerDown) === null || - _props$onPointerDown === void 0 || - _props$onPointerDown.call(props, event); - isPointerDownRef.current = true; - }, - onPointerUp: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onPointerUp, - (event) => { - var _event$currentTarget; - // Pointer down can move to a different menu item which should activate it on pointer up. - // We dispatch a click for selection to allow composition with click based triggers and to - // prevent Firefox from getting stuck in text selection mode when the menu closes. - if (!isPointerDownRef.current) - (_event$currentTarget = event.currentTarget) === null || - _event$currentTarget === void 0 || - _event$currentTarget.click(); - } - ), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onKeyDown, - (event) => { - const isTypingAhead = - contentContext.searchRef.current !== ""; - if (disabled || (isTypingAhead && event.key === " ")) - return; - if ( - $213e4d2df823067d$var$SELECTION_KEYS.includes(event.key) - ) { - event.currentTarget.click(); - /** - * We prevent default browser behaviour for selection keys as they should trigger - * a selection only: - * - prevents space from scrolling the page. - * - if keydown causes focus to move, prevents keydown from firing on the new target. - */ - event.preventDefault(); - } - } - ), - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$2ce376c2cc3355c8, { - displayName: $213e4d2df823067d$var$ITEM_NAME, - }); - /* ---------------------------------------------------------------------------------------------- */ - const $213e4d2df823067d$var$MenuItemImpl = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - disabled = false, - textValue: textValue, - ...itemProps - } = props; - const contentContext = $213e4d2df823067d$var$useMenuContentContext( - $213e4d2df823067d$var$ITEM_NAME, - __scopeMenu - ); - const rovingFocusGroupScope = - $213e4d2df823067d$var$useRovingFocusGroupScope(__scopeMenu); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - const [isFocused, setIsFocused] = $cnSS2$react.useState(false); // get the item's `.textContent` as default strategy for typeahead `textValue` - const [textContent, setTextContent] = $cnSS2$react.useState(""); - $cnSS2$react.useEffect(() => { - const menuItem = ref.current; - if (menuItem) { - var _menuItem$textContent; - setTextContent( - ((_menuItem$textContent = menuItem.textContent) !== null && - _menuItem$textContent !== void 0 - ? _menuItem$textContent - : "" - ).trim() - ); - } - }, [itemProps.children]); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$Collection.ItemSlot, - { - scope: __scopeMenu, - disabled: disabled, - textValue: - textValue !== null && textValue !== void 0 - ? textValue - : textContent, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactrovingfocus.Item, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - asChild: true, - }, - rovingFocusGroupScope, - { - focusable: !disabled, - } - ), - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - role: "menuitem", - "data-highlighted": isFocused ? "" : undefined, - "aria-disabled": disabled || undefined, - "data-disabled": disabled ? "" : undefined, - }, - itemProps, - { - ref: composedRefs, - onPointerMove: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onPointerMove, - $213e4d2df823067d$var$whenMouse((event) => { - if (disabled) contentContext.onItemLeave(event); - else { - contentContext.onItemEnter(event); - if (!event.defaultPrevented) { - const item = event.currentTarget; - item.focus(); - } - } - }) - ), - onPointerLeave: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onPointerLeave, - $213e4d2df823067d$var$whenMouse((event) => - contentContext.onItemLeave(event) - ) - ), - onFocus: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onFocus, - () => setIsFocused(true) - ), - onBlur: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onBlur, - () => setIsFocused(false) - ), - } - ) - ) - ) - ); - }); - /* ------------------------------------------------------------------------------------------------- - * MenuCheckboxItem - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$CHECKBOX_ITEM_NAME = "MenuCheckboxItem"; - const $213e4d2df823067d$export$f6f243521332502d = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { - checked = false, - onCheckedChange: onCheckedChange, - ...checkboxItemProps - } = props; - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$ItemIndicatorProvider, - { - scope: props.__scopeMenu, - checked: checked, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$export$2ce376c2cc3355c8, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - role: "menuitemcheckbox", - "aria-checked": $213e4d2df823067d$var$isIndeterminate( - checked - ) - ? "mixed" - : checked, - }, - checkboxItemProps, - { - ref: forwardedRef, - "data-state": - $213e4d2df823067d$var$getCheckedState(checked), - onSelect: $cnSS2$radixuiprimitive.composeEventHandlers( - checkboxItemProps.onSelect, - () => - onCheckedChange === null || onCheckedChange === void 0 - ? void 0 - : onCheckedChange( - $213e4d2df823067d$var$isIndeterminate(checked) - ? true - : !checked - ), - { - checkForDefaultPrevented: false, - } - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$f6f243521332502d, { - displayName: $213e4d2df823067d$var$CHECKBOX_ITEM_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuRadioGroup - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$RADIO_GROUP_NAME = "MenuRadioGroup"; - const [ - $213e4d2df823067d$var$RadioGroupProvider, - $213e4d2df823067d$var$useRadioGroupContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$RADIO_GROUP_NAME, - { - value: undefined, - onValueChange: () => {}, - } - ); - const $213e4d2df823067d$export$ea2200c9eee416b3 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { - value: value, - onValueChange: onValueChange, - ...groupProps - } = props; - const handleValueChange = - $cnSS2$radixuireactusecallbackref.useCallbackRef(onValueChange); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$RadioGroupProvider, - { - scope: props.__scopeMenu, - value: value, - onValueChange: handleValueChange, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$export$22a631d1f72787bb, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - groupProps, - { - ref: forwardedRef, - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$ea2200c9eee416b3, { - displayName: $213e4d2df823067d$var$RADIO_GROUP_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuRadioItem - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$RADIO_ITEM_NAME = "MenuRadioItem"; - const $213e4d2df823067d$export$69bd225e9817f6d0 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { value: value, ...radioItemProps } = props; - const context = $213e4d2df823067d$var$useRadioGroupContext( - $213e4d2df823067d$var$RADIO_ITEM_NAME, - props.__scopeMenu - ); - const checked = value === context.value; - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$ItemIndicatorProvider, - { - scope: props.__scopeMenu, - checked: checked, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$export$2ce376c2cc3355c8, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - role: "menuitemradio", - "aria-checked": checked, - }, - radioItemProps, - { - ref: forwardedRef, - "data-state": - $213e4d2df823067d$var$getCheckedState(checked), - onSelect: $cnSS2$radixuiprimitive.composeEventHandlers( - radioItemProps.onSelect, - () => { - var _context$onValueChang; - return (_context$onValueChang = - context.onValueChange) === null || - _context$onValueChang === void 0 - ? void 0 - : _context$onValueChang.call(context, value); - }, - { - checkForDefaultPrevented: false, - } - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$69bd225e9817f6d0, { - displayName: $213e4d2df823067d$var$RADIO_ITEM_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuItemIndicator - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$ITEM_INDICATOR_NAME = "MenuItemIndicator"; - const [ - $213e4d2df823067d$var$ItemIndicatorProvider, - $213e4d2df823067d$var$useItemIndicatorContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$ITEM_INDICATOR_NAME, - { - checked: false, - } - ); - const $213e4d2df823067d$export$a2593e23056970a3 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { - __scopeMenu: __scopeMenu, - forceMount: forceMount, - ...itemIndicatorProps - } = props; - const indicatorContext = - $213e4d2df823067d$var$useItemIndicatorContext( - $213e4d2df823067d$var$ITEM_INDICATOR_NAME, - __scopeMenu - ); - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpresence.Presence, - { - present: - forceMount || - $213e4d2df823067d$var$isIndeterminate( - indicatorContext.checked - ) || - indicatorContext.checked === true, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactprimitive.Primitive.span, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - itemIndicatorProps, - { - ref: forwardedRef, - "data-state": $213e4d2df823067d$var$getCheckedState( - indicatorContext.checked - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$a2593e23056970a3, { - displayName: $213e4d2df823067d$var$ITEM_INDICATOR_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuSeparator - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$SEPARATOR_NAME = "MenuSeparator"; - const $213e4d2df823067d$export$1cec7dcdd713e220 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { __scopeMenu: __scopeMenu, ...separatorProps } = props; - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - role: "separator", - "aria-orientation": "horizontal", - }, - separatorProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$1cec7dcdd713e220, { - displayName: $213e4d2df823067d$var$SEPARATOR_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuArrow - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$ARROW_NAME = "MenuArrow"; - const $213e4d2df823067d$export$bcdda4773debf5fa = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const { __scopeMenu: __scopeMenu, ...arrowProps } = props; - const popperScope = - $213e4d2df823067d$var$usePopperScope(__scopeMenu); - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpopper.Arrow, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - {}, - popperScope, - arrowProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$bcdda4773debf5fa, { - displayName: $213e4d2df823067d$var$ARROW_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuSub - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$SUB_NAME = "MenuSub"; - const [ - $213e4d2df823067d$var$MenuSubProvider, - $213e4d2df823067d$var$useMenuSubContext, - ] = $213e4d2df823067d$var$createMenuContext( - $213e4d2df823067d$var$SUB_NAME - ); - const $213e4d2df823067d$export$71bdb9d1e2909932 = (props) => { - const { - __scopeMenu: __scopeMenu, - children: children, - open = false, - onOpenChange: onOpenChange, - } = props; - const parentMenuContext = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$SUB_NAME, - __scopeMenu - ); - const popperScope = $213e4d2df823067d$var$usePopperScope(__scopeMenu); - const [trigger, setTrigger] = $cnSS2$react.useState(null); - const [content, setContent] = $cnSS2$react.useState(null); - const handleOpenChange = - $cnSS2$radixuireactusecallbackref.useCallbackRef(onOpenChange); // Prevent the parent menu from reopening with open submenus. - $cnSS2$react.useEffect(() => { - if (parentMenuContext.open === false) handleOpenChange(false); - return () => handleOpenChange(false); - }, [parentMenuContext.open, handleOpenChange]); - return /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpopper.Root, - popperScope, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuProvider, - { - scope: __scopeMenu, - open: open, - onOpenChange: handleOpenChange, - content: content, - onContentChange: setContent, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuSubProvider, - { - scope: __scopeMenu, - contentId: $cnSS2$radixuireactid.useId(), - triggerId: $cnSS2$radixuireactid.useId(), - trigger: trigger, - onTriggerChange: setTrigger, - }, - children - ) - ) - ); - }; - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$71bdb9d1e2909932, { - displayName: $213e4d2df823067d$var$SUB_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuSubTrigger - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$SUB_TRIGGER_NAME = "MenuSubTrigger"; - const $213e4d2df823067d$export$5fbbb3ba7297405f = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$SUB_TRIGGER_NAME, - props.__scopeMenu - ); - const rootContext = $213e4d2df823067d$var$useMenuRootContext( - $213e4d2df823067d$var$SUB_TRIGGER_NAME, - props.__scopeMenu - ); - const subContext = $213e4d2df823067d$var$useMenuSubContext( - $213e4d2df823067d$var$SUB_TRIGGER_NAME, - props.__scopeMenu - ); - const contentContext = $213e4d2df823067d$var$useMenuContentContext( - $213e4d2df823067d$var$SUB_TRIGGER_NAME, - props.__scopeMenu - ); - const openTimerRef = $cnSS2$react.useRef(null); - const { - pointerGraceTimerRef: pointerGraceTimerRef, - onPointerGraceIntentChange: onPointerGraceIntentChange, - } = contentContext; - const scope = { - __scopeMenu: props.__scopeMenu, - }; - const clearOpenTimer = $cnSS2$react.useCallback(() => { - if (openTimerRef.current) - window.clearTimeout(openTimerRef.current); - openTimerRef.current = null; - }, []); - $cnSS2$react.useEffect(() => clearOpenTimer, [clearOpenTimer]); - $cnSS2$react.useEffect(() => { - const pointerGraceTimer = pointerGraceTimerRef.current; - return () => { - window.clearTimeout(pointerGraceTimer); - onPointerGraceIntentChange(null); - }; - }, [pointerGraceTimerRef, onPointerGraceIntentChange]); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$export$9fa5ebd18bee4d43, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - asChild: true, - }, - scope - ), - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuItemImpl, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - id: subContext.triggerId, - "aria-haspopup": "menu", - "aria-expanded": context.open, - "aria-controls": subContext.contentId, - "data-state": $213e4d2df823067d$var$getOpenState( - context.open - ), - }, - props, - { - ref: $cnSS2$radixuireactcomposerefs.composeRefs( - forwardedRef, - subContext.onTriggerChange - ), // This is redundant for mouse users but we cannot determine pointer type from - onClick: (event) => { - var _props$onClick; - (_props$onClick = props.onClick) === null || - _props$onClick === void 0 || - _props$onClick.call(props, event); - if (props.disabled || event.defaultPrevented) return; - /** - * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons) - * and we rely heavily on `onFocusOutside` for submenus to close when switching - * between separate submenus. - */ - event.currentTarget.focus(); - if (!context.open) context.onOpenChange(true); - }, - onPointerMove: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onPointerMove, - $213e4d2df823067d$var$whenMouse((event) => { - contentContext.onItemEnter(event); - if (event.defaultPrevented) return; - if ( - !props.disabled && - !context.open && - !openTimerRef.current - ) { - contentContext.onPointerGraceIntentChange(null); - openTimerRef.current = window.setTimeout(() => { - context.onOpenChange(true); - clearOpenTimer(); - }, 100); - } - }) - ), - onPointerLeave: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onPointerLeave, - $213e4d2df823067d$var$whenMouse((event) => { - var _context$content; - clearOpenTimer(); - const contentRect = - (_context$content = context.content) === null || - _context$content === void 0 - ? void 0 - : _context$content.getBoundingClientRect(); - if (contentRect) { - var _context$content2; - // TODO: make sure to update this when we change positioning logic - const side = - (_context$content2 = context.content) === null || - _context$content2 === void 0 - ? void 0 - : _context$content2.dataset.side; - const rightSide = side === "right"; - const bleed = rightSide ? -5 : 5; - const contentNearEdge = - contentRect[rightSide ? "left" : "right"]; - const contentFarEdge = - contentRect[rightSide ? "right" : "left"]; - contentContext.onPointerGraceIntentChange({ - area: [ - // consistently within polygon bounds - { - x: event.clientX + bleed, - y: event.clientY, - }, - { - x: contentNearEdge, - y: contentRect.top, - }, - { - x: contentFarEdge, - y: contentRect.top, - }, - { - x: contentFarEdge, - y: contentRect.bottom, - }, - { - x: contentNearEdge, - y: contentRect.bottom, - }, - ], - side: side, - }); - window.clearTimeout(pointerGraceTimerRef.current); - pointerGraceTimerRef.current = window.setTimeout( - () => - contentContext.onPointerGraceIntentChange(null), - 300 - ); - } else { - contentContext.onTriggerLeave(event); - if (event.defaultPrevented) return; // There's 100ms where the user may leave an item before the submenu was opened. - contentContext.onPointerGraceIntentChange(null); - } - }) - ), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onKeyDown, - (event) => { - const isTypingAhead = - contentContext.searchRef.current !== ""; - if ( - props.disabled || - (isTypingAhead && event.key === " ") - ) - return; - if ( - $213e4d2df823067d$var$SUB_OPEN_KEYS[ - rootContext.dir - ].includes(event.key) - ) { - var _context$content3; - context.onOpenChange(true); // The trigger may hold focus if opened via pointer interaction - // so we ensure content is given focus again when switching to keyboard. - (_context$content3 = context.content) === null || - _context$content3 === void 0 || - _context$content3.focus(); // prevent window from scrolling - event.preventDefault(); - } - } - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$5fbbb3ba7297405f, { - displayName: $213e4d2df823067d$var$SUB_TRIGGER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * MenuSubContent - * -----------------------------------------------------------------------------------------------*/ - const $213e4d2df823067d$var$SUB_CONTENT_NAME = "MenuSubContent"; - const $213e4d2df823067d$export$e7142ab31822bde6 = - /*#__PURE__*/ $cnSS2$react.forwardRef((props, forwardedRef) => { - const portalContext = $213e4d2df823067d$var$usePortalContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - const { - forceMount = portalContext.forceMount, - ...subContentProps - } = props; - const context = $213e4d2df823067d$var$useMenuContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - const rootContext = $213e4d2df823067d$var$useMenuRootContext( - $213e4d2df823067d$var$CONTENT_NAME, - props.__scopeMenu - ); - const subContext = $213e4d2df823067d$var$useMenuSubContext( - $213e4d2df823067d$var$SUB_CONTENT_NAME, - props.__scopeMenu - ); - const ref = $cnSS2$react.useRef(null); - const composedRefs = $cnSS2$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - return /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$Collection.Provider, - { - scope: props.__scopeMenu, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $cnSS2$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$Collection.Slot, - { - scope: props.__scopeMenu, - }, - /*#__PURE__*/ $cnSS2$react.createElement( - $213e4d2df823067d$var$MenuContentImpl, - $parcel$interopDefault($cnSS2$babelruntimehelpersextends)( - { - id: subContext.contentId, - "aria-labelledby": subContext.triggerId, - }, - subContentProps, - { - ref: composedRefs, - align: "start", - side: rootContext.dir === "rtl" ? "left" : "right", - disableOutsidePointerEvents: false, - disableOutsideScroll: false, - trapFocus: false, - onOpenAutoFocus: (event) => { - var _ref$current; - // when opening a submenu, focus content for keyboard users only - if (rootContext.isUsingKeyboardRef.current) - (_ref$current = ref.current) === null || - _ref$current === void 0 || - _ref$current.focus(); - event.preventDefault(); - }, // The menu might close because of focusing another menu item in the parent menu. We - onCloseAutoFocus: (event) => event.preventDefault(), - onFocusOutside: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onFocusOutside, - (event) => { - // We prevent closing when the trigger is focused to avoid triggering a re-open animation - // on pointer interaction. - if (event.target !== subContext.trigger) - context.onOpenChange(false); - } - ), - onEscapeKeyDown: - $cnSS2$radixuiprimitive.composeEventHandlers( - props.onEscapeKeyDown, - (event) => { - rootContext.onClose(); // ensure pressing escape in submenu doesn't escape full screen mode - event.preventDefault(); - } - ), - onKeyDown: $cnSS2$radixuiprimitive.composeEventHandlers( - props.onKeyDown, - (event) => { - // Submenu key events bubble through portals. We only care about keys in this menu. - const isKeyDownInside = - event.currentTarget.contains(event.target); - const isCloseKey = - $213e4d2df823067d$var$SUB_CLOSE_KEYS[ - rootContext.dir - ].includes(event.key); - if (isKeyDownInside && isCloseKey) { - var _subContext$trigger; - context.onOpenChange(false); // We focus manually because we prevented it in `onCloseAutoFocus` - (_subContext$trigger = subContext.trigger) === - null || - _subContext$trigger === void 0 || - _subContext$trigger.focus(); // prevent window from scrolling - event.preventDefault(); - } - } - ), - } - ) - ) - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($213e4d2df823067d$export$e7142ab31822bde6, { - displayName: $213e4d2df823067d$var$SUB_CONTENT_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - function $213e4d2df823067d$var$getOpenState(open) { - return open ? "open" : "closed"; - } - function $213e4d2df823067d$var$isIndeterminate(checked) { - return checked === "indeterminate"; - } - function $213e4d2df823067d$var$getCheckedState(checked) { - return $213e4d2df823067d$var$isIndeterminate(checked) - ? "indeterminate" - : checked - ? "checked" - : "unchecked"; - } - function $213e4d2df823067d$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } - } - /** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ - function $213e4d2df823067d$var$wrapArray(array, startIndex) { - return array.map( - (_, index) => array[(startIndex + index) % array.length] - ); - } - /** - * This is the "meat" of the typeahead matching logic. It takes in all the values, - * the search and the current match, and returns the next match (or `undefined`). - * - * We normalize the search because if a user has repeatedly pressed a character, - * we want the exact same behavior as if we only had that one character - * (ie. cycle through options starting with that character) - * - * We also reorder the values by wrapping the array around the current match. - * This is so we always look forward from the current match, and picking the first - * match will always be the correct one. - * - * Finally, if the normalized search is exactly one character, we exclude the - * current match from the values because otherwise it would be the first to match always - * and focus would never move. This is as opposed to the regular case, where we - * don't want focus to move if the current match still matches. - */ - function $213e4d2df823067d$var$getNextMatch( - values, - search, - currentMatch - ) { - const isRepeated = - search.length > 1 && - Array.from(search).every((char) => char === search[0]); - const normalizedSearch = isRepeated ? search[0] : search; - const currentMatchIndex = currentMatch - ? values.indexOf(currentMatch) - : -1; - let wrappedValues = $213e4d2df823067d$var$wrapArray( - values, - Math.max(currentMatchIndex, 0) - ); - const excludeCurrentMatch = normalizedSearch.length === 1; - if (excludeCurrentMatch) - wrappedValues = wrappedValues.filter((v) => v !== currentMatch); - const nextMatch = wrappedValues.find((value) => - value.toLowerCase().startsWith(normalizedSearch.toLowerCase()) - ); - return nextMatch !== currentMatch ? nextMatch : undefined; - } - // Determine if a point is inside of a polygon. - // Based on https://github.com/substack/point-in-polygon - function $213e4d2df823067d$var$isPointInPolygon(point, polygon) { - const { x: x, y: y } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = - yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; - } - function $213e4d2df823067d$var$isPointerInGraceArea(event, area) { - if (!area) return false; - const cursorPos = { - x: event.clientX, - y: event.clientY, - }; - return $213e4d2df823067d$var$isPointInPolygon(cursorPos, area); - } - function $213e4d2df823067d$var$whenMouse(handler) { - return (event) => - event.pointerType === "mouse" ? handler(event) : undefined; - } - const $213e4d2df823067d$export$be92b6f5f03c0fe9 = - $213e4d2df823067d$export$d9b273488cd8ce6f; - const $213e4d2df823067d$export$b688253958b8dfe7 = - $213e4d2df823067d$export$9fa5ebd18bee4d43; - const $213e4d2df823067d$export$602eac185826482c = - $213e4d2df823067d$export$793392f970497feb; - const $213e4d2df823067d$export$7c6e2c02157bb7d2 = - $213e4d2df823067d$export$479f0f2f71193efe; - const $213e4d2df823067d$export$eb2fcfdbd7ba97d4 = - $213e4d2df823067d$export$22a631d1f72787bb; - const $213e4d2df823067d$export$b04be29aa201d4f5 = - $213e4d2df823067d$export$dd37bec0e8a99143; - const $213e4d2df823067d$export$6d08773d2e66f8f2 = - $213e4d2df823067d$export$2ce376c2cc3355c8; - const $213e4d2df823067d$export$16ce288f89fa631c = - $213e4d2df823067d$export$f6f243521332502d; - const $213e4d2df823067d$export$a98f0dcb43a68a25 = - $213e4d2df823067d$export$ea2200c9eee416b3; - const $213e4d2df823067d$export$371ab307eab489c0 = - $213e4d2df823067d$export$69bd225e9817f6d0; - const $213e4d2df823067d$export$c3468e2714d175fa = - $213e4d2df823067d$export$a2593e23056970a3; - const $213e4d2df823067d$export$1ff3c3f08ae963c0 = - $213e4d2df823067d$export$1cec7dcdd713e220; - const $213e4d2df823067d$export$21b07c8f274aebd5 = - $213e4d2df823067d$export$bcdda4773debf5fa; - const $213e4d2df823067d$export$d7a01e11500dfb6f = - $213e4d2df823067d$export$71bdb9d1e2909932; - const $213e4d2df823067d$export$2ea8a7a591ac5eac = - $213e4d2df823067d$export$5fbbb3ba7297405f; - const $213e4d2df823067d$export$6d4de93b380beddf = - $213e4d2df823067d$export$e7142ab31822bde6; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-popper/dist/index.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-popper/dist/index.js ***! - \******************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $50Iv9$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $50Iv9$react = __webpack_require__(/*! react */ "react"); - var $50Iv9$floatinguireactdom = __webpack_require__( - /*! @floating-ui/react-dom */ "../../../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js" - ); - var $50Iv9$radixuireactarrow = __webpack_require__( - /*! @radix-ui/react-arrow */ "../../../node_modules/@radix-ui/react-arrow/dist/index.js" - ); - var $50Iv9$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $50Iv9$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $50Iv9$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $50Iv9$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - var $50Iv9$radixuireactuselayouteffect = __webpack_require__( - /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" - ); - var $50Iv9$radixuireactusesize = __webpack_require__( - /*! @radix-ui/react-use-size */ "../../../node_modules/@radix-ui/react-use-size/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createPopperScope", - () => $34310caa050a8d63$export$722aac194ae923 - ); - $parcel$export( - module.exports, - "Popper", - () => $34310caa050a8d63$export$badac9ada3a0bdf9 - ); - $parcel$export( - module.exports, - "PopperAnchor", - () => $34310caa050a8d63$export$ecd4e1ccab6ed6d - ); - $parcel$export( - module.exports, - "PopperContent", - () => $34310caa050a8d63$export$bc4ae5855d3c4fc - ); - $parcel$export( - module.exports, - "PopperArrow", - () => $34310caa050a8d63$export$79d62cd4e10a3fd0 - ); - $parcel$export( - module.exports, - "Root", - () => $34310caa050a8d63$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Anchor", - () => $34310caa050a8d63$export$b688253958b8dfe7 - ); - $parcel$export( - module.exports, - "Content", - () => $34310caa050a8d63$export$7c6e2c02157bb7d2 - ); - $parcel$export( - module.exports, - "Arrow", - () => $34310caa050a8d63$export$21b07c8f274aebd5 - ); - $parcel$export( - module.exports, - "SIDE_OPTIONS", - () => $34310caa050a8d63$export$36f0086da09c4b9f - ); - $parcel$export( - module.exports, - "ALIGN_OPTIONS", - () => $34310caa050a8d63$export$3671ffab7b302fc9 - ); - const $34310caa050a8d63$export$36f0086da09c4b9f = [ - "top", - "right", - "bottom", - "left", - ]; - const $34310caa050a8d63$export$3671ffab7b302fc9 = [ - "start", - "center", - "end", - ]; - /* ------------------------------------------------------------------------------------------------- - * Popper - * -----------------------------------------------------------------------------------------------*/ - const $34310caa050a8d63$var$POPPER_NAME = "Popper"; - const [ - $34310caa050a8d63$var$createPopperContext, - $34310caa050a8d63$export$722aac194ae923, - ] = $50Iv9$radixuireactcontext.createContextScope( - $34310caa050a8d63$var$POPPER_NAME - ); - const [ - $34310caa050a8d63$var$PopperProvider, - $34310caa050a8d63$var$usePopperContext, - ] = $34310caa050a8d63$var$createPopperContext( - $34310caa050a8d63$var$POPPER_NAME - ); - const $34310caa050a8d63$export$badac9ada3a0bdf9 = (props) => { - const { __scopePopper: __scopePopper, children: children } = props; - const [anchor, setAnchor] = $50Iv9$react.useState(null); - return /*#__PURE__*/ $50Iv9$react.createElement( - $34310caa050a8d63$var$PopperProvider, - { - scope: __scopePopper, - anchor: anchor, - onAnchorChange: setAnchor, - }, - children - ); - }; - /*#__PURE__*/ - Object.assign($34310caa050a8d63$export$badac9ada3a0bdf9, { - displayName: $34310caa050a8d63$var$POPPER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * PopperAnchor - * -----------------------------------------------------------------------------------------------*/ - const $34310caa050a8d63$var$ANCHOR_NAME = "PopperAnchor"; - const $34310caa050a8d63$export$ecd4e1ccab6ed6d = - /*#__PURE__*/ $50Iv9$react.forwardRef((props, forwardedRef) => { - const { - __scopePopper: __scopePopper, - virtualRef: virtualRef, - ...anchorProps - } = props; - const context = $34310caa050a8d63$var$usePopperContext( - $34310caa050a8d63$var$ANCHOR_NAME, - __scopePopper - ); - const ref = $50Iv9$react.useRef(null); - const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - $50Iv9$react.useEffect(() => { - // Consumer can anchor the popper to something that isn't - // a DOM node e.g. pointer position, so we override the - // `anchorRef` with their virtual ref in this case. - context.onAnchorChange( - (virtualRef === null || virtualRef === void 0 - ? void 0 - : virtualRef.current) || ref.current - ); - }); - return virtualRef - ? null - : /*#__PURE__*/ $50Iv9$react.createElement( - $50Iv9$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($50Iv9$babelruntimehelpersextends)( - {}, - anchorProps, - { - ref: composedRefs, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($34310caa050a8d63$export$ecd4e1ccab6ed6d, { - displayName: $34310caa050a8d63$var$ANCHOR_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * PopperContent - * -----------------------------------------------------------------------------------------------*/ - const $34310caa050a8d63$var$CONTENT_NAME = "PopperContent"; - const [ - $34310caa050a8d63$var$PopperContentProvider, - $34310caa050a8d63$var$useContentContext, - ] = $34310caa050a8d63$var$createPopperContext( - $34310caa050a8d63$var$CONTENT_NAME - ); - const $34310caa050a8d63$export$bc4ae5855d3c4fc = - /*#__PURE__*/ $50Iv9$react.forwardRef((props, forwardedRef) => { - var _arrowSize$width, - _arrowSize$height, - _middlewareData$arrow, - _middlewareData$arrow2, - _middlewareData$arrow3, - _middlewareData$trans, - _middlewareData$trans2, - _middlewareData$hide; - const { - __scopePopper: __scopePopper, - side = "bottom", - sideOffset = 0, - align = "center", - alignOffset = 0, - arrowPadding = 0, - collisionBoundary = [], - collisionPadding: collisionPaddingProp = 0, - sticky = "partial", - hideWhenDetached = false, - avoidCollisions = true, - onPlaced: onPlaced, - ...contentProps - } = props; - const context = $34310caa050a8d63$var$usePopperContext( - $34310caa050a8d63$var$CONTENT_NAME, - __scopePopper - ); - const [content, setContent] = $50Iv9$react.useState(null); - const composedRefs = $50Iv9$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - (node) => setContent(node) - ); - const [arrow, setArrow] = $50Iv9$react.useState(null); - const arrowSize = $50Iv9$radixuireactusesize.useSize(arrow); - const arrowWidth = - (_arrowSize$width = - arrowSize === null || arrowSize === void 0 - ? void 0 - : arrowSize.width) !== null && _arrowSize$width !== void 0 - ? _arrowSize$width - : 0; - const arrowHeight = - (_arrowSize$height = - arrowSize === null || arrowSize === void 0 - ? void 0 - : arrowSize.height) !== null && _arrowSize$height !== void 0 - ? _arrowSize$height - : 0; - const desiredPlacement = - side + (align !== "center" ? "-" + align : ""); - const collisionPadding = - typeof collisionPaddingProp === "number" - ? collisionPaddingProp - : { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...collisionPaddingProp, - }; - const boundary = Array.isArray(collisionBoundary) - ? collisionBoundary - : [collisionBoundary]; - const hasExplicitBoundaries = boundary.length > 0; - const detectOverflowOptions = { - padding: collisionPadding, - boundary: boundary.filter($34310caa050a8d63$var$isNotNull), - // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries - altBoundary: hasExplicitBoundaries, - }; - const { - refs: refs, - floatingStyles: floatingStyles, - placement: placement, - isPositioned: isPositioned, - middlewareData: middlewareData, - } = $50Iv9$floatinguireactdom.useFloating({ - // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues - strategy: "fixed", - placement: desiredPlacement, - whileElementsMounted: $50Iv9$floatinguireactdom.autoUpdate, - elements: { - reference: context.anchor, - }, - middleware: [ - $50Iv9$floatinguireactdom.offset({ - mainAxis: sideOffset + arrowHeight, - alignmentAxis: alignOffset, - }), - avoidCollisions && - $50Iv9$floatinguireactdom.shift({ - mainAxis: true, - crossAxis: false, - limiter: - sticky === "partial" - ? $50Iv9$floatinguireactdom.limitShift() - : undefined, - ...detectOverflowOptions, - }), - avoidCollisions && - $50Iv9$floatinguireactdom.flip({ - ...detectOverflowOptions, - }), - $50Iv9$floatinguireactdom.size({ - ...detectOverflowOptions, - apply: ({ - elements: elements, - rects: rects, - availableWidth: availableWidth, - availableHeight: availableHeight, - }) => { - const { width: anchorWidth, height: anchorHeight } = - rects.reference; - const contentStyle = elements.floating.style; - contentStyle.setProperty( - "--radix-popper-available-width", - `${availableWidth}px` - ); - contentStyle.setProperty( - "--radix-popper-available-height", - `${availableHeight}px` - ); - contentStyle.setProperty( - "--radix-popper-anchor-width", - `${anchorWidth}px` - ); - contentStyle.setProperty( - "--radix-popper-anchor-height", - `${anchorHeight}px` - ); - }, - }), - arrow && - $50Iv9$floatinguireactdom.arrow({ - element: arrow, - padding: arrowPadding, - }), - $34310caa050a8d63$var$transformOrigin({ - arrowWidth: arrowWidth, - arrowHeight: arrowHeight, - }), - hideWhenDetached && - $50Iv9$floatinguireactdom.hide({ - strategy: "referenceHidden", - }), - ], - }); - const [placedSide, placedAlign] = - $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); - const handlePlaced = - $50Iv9$radixuireactusecallbackref.useCallbackRef(onPlaced); - $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { - if (isPositioned) - handlePlaced === null || - handlePlaced === void 0 || - handlePlaced(); - }, [isPositioned, handlePlaced]); - const arrowX = - (_middlewareData$arrow = middlewareData.arrow) === null || - _middlewareData$arrow === void 0 - ? void 0 - : _middlewareData$arrow.x; - const arrowY = - (_middlewareData$arrow2 = middlewareData.arrow) === null || - _middlewareData$arrow2 === void 0 - ? void 0 - : _middlewareData$arrow2.y; - const cannotCenterArrow = - ((_middlewareData$arrow3 = middlewareData.arrow) === null || - _middlewareData$arrow3 === void 0 - ? void 0 - : _middlewareData$arrow3.centerOffset) !== 0; - const [contentZIndex, setContentZIndex] = $50Iv9$react.useState(); - $50Iv9$radixuireactuselayouteffect.useLayoutEffect(() => { - if (content) - setContentZIndex(window.getComputedStyle(content).zIndex); - }, [content]); - return /*#__PURE__*/ $50Iv9$react.createElement( - "div", - { - ref: refs.setFloating, - "data-radix-popper-content-wrapper": "", - style: { - ...floatingStyles, - transform: isPositioned - ? floatingStyles.transform - : "translate(0, -200%)", - // keep off the page when measuring - minWidth: "max-content", - zIndex: contentZIndex, - ["--radix-popper-transform-origin"]: [ - (_middlewareData$trans = middlewareData.transformOrigin) === - null || _middlewareData$trans === void 0 - ? void 0 - : _middlewareData$trans.x, - (_middlewareData$trans2 = - middlewareData.transformOrigin) === null || - _middlewareData$trans2 === void 0 - ? void 0 - : _middlewareData$trans2.y, - ].join(" "), - }, // Floating UI interally calculates logical alignment based the `dir` attribute on - dir: props.dir, - }, - /*#__PURE__*/ $50Iv9$react.createElement( - $34310caa050a8d63$var$PopperContentProvider, - { - scope: __scopePopper, - placedSide: placedSide, - onArrowChange: setArrow, - arrowX: arrowX, - arrowY: arrowY, - shouldHideArrow: cannotCenterArrow, - }, - /*#__PURE__*/ $50Iv9$react.createElement( - $50Iv9$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($50Iv9$babelruntimehelpersextends)( - { - "data-side": placedSide, - "data-align": placedAlign, - }, - contentProps, - { - ref: composedRefs, - style: { - ...contentProps.style, - // if the PopperContent hasn't been placed yet (not all measurements done) - // we prevent animations so that users's animation don't kick in too early referring wrong sides - animation: !isPositioned ? "none" : undefined, - // hide the content if using the hide middleware and should be hidden - opacity: - (_middlewareData$hide = middlewareData.hide) !== - null && - _middlewareData$hide !== void 0 && - _middlewareData$hide.referenceHidden - ? 0 - : undefined, - }, - } - ) - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($34310caa050a8d63$export$bc4ae5855d3c4fc, { - displayName: $34310caa050a8d63$var$CONTENT_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * PopperArrow - * -----------------------------------------------------------------------------------------------*/ - const $34310caa050a8d63$var$ARROW_NAME = "PopperArrow"; - const $34310caa050a8d63$var$OPPOSITE_SIDE = { - top: "bottom", - right: "left", - bottom: "top", - left: "right", - }; - const $34310caa050a8d63$export$79d62cd4e10a3fd0 = - /*#__PURE__*/ $50Iv9$react.forwardRef( - function $34310caa050a8d63$export$79d62cd4e10a3fd0( - props, - forwardedRef - ) { - const { __scopePopper: __scopePopper, ...arrowProps } = props; - const contentContext = $34310caa050a8d63$var$useContentContext( - $34310caa050a8d63$var$ARROW_NAME, - __scopePopper - ); - const baseSide = - $34310caa050a8d63$var$OPPOSITE_SIDE[contentContext.placedSide]; - return ( - /*#__PURE__*/ // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`) - // doesn't report size as we'd expect on SVG elements. - // it reports their bounding box which is effectively the largest path inside the SVG. - $50Iv9$react.createElement( - "span", - { - ref: contentContext.onArrowChange, - style: { - position: "absolute", - left: contentContext.arrowX, - top: contentContext.arrowY, - [baseSide]: 0, - transformOrigin: { - top: "", - right: "0 0", - bottom: "center 0", - left: "100% 0", - }[contentContext.placedSide], - transform: { - top: "translateY(100%)", - right: "translateY(50%) rotate(90deg) translateX(-50%)", - bottom: `rotate(180deg)`, - left: "translateY(50%) rotate(-90deg) translateX(50%)", - }[contentContext.placedSide], - visibility: contentContext.shouldHideArrow - ? "hidden" - : undefined, - }, - }, - /*#__PURE__*/ $50Iv9$react.createElement( - $50Iv9$radixuireactarrow.Root, - $parcel$interopDefault($50Iv9$babelruntimehelpersextends)( - {}, - arrowProps, - { - ref: forwardedRef, - style: { - ...arrowProps.style, - // ensures the element can be measured correctly (mostly for if SVG) - display: "block", - }, - } - ) - ) - ) - ); - } - ); - /*#__PURE__*/ - Object.assign($34310caa050a8d63$export$79d62cd4e10a3fd0, { - displayName: $34310caa050a8d63$var$ARROW_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - function $34310caa050a8d63$var$isNotNull(value) { - return value !== null; - } - const $34310caa050a8d63$var$transformOrigin = (options) => ({ - name: "transformOrigin", - options: options, - fn(data) { - var _middlewareData$arrow4, - _middlewareData$arrow5, - _middlewareData$arrow6, - _middlewareData$arrow7, - _middlewareData$arrow8; - const { - placement: placement, - rects: rects, - middlewareData: middlewareData, - } = data; - const cannotCenterArrow = - ((_middlewareData$arrow4 = middlewareData.arrow) === null || - _middlewareData$arrow4 === void 0 - ? void 0 - : _middlewareData$arrow4.centerOffset) !== 0; - const isArrowHidden = cannotCenterArrow; - const arrowWidth = isArrowHidden ? 0 : options.arrowWidth; - const arrowHeight = isArrowHidden ? 0 : options.arrowHeight; - const [placedSide, placedAlign] = - $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement); - const noArrowAlign = { - start: "0%", - center: "50%", - end: "100%", - }[placedAlign]; - const arrowXCenter = - ((_middlewareData$arrow5 = - (_middlewareData$arrow6 = middlewareData.arrow) === null || - _middlewareData$arrow6 === void 0 - ? void 0 - : _middlewareData$arrow6.x) !== null && - _middlewareData$arrow5 !== void 0 - ? _middlewareData$arrow5 - : 0) + - arrowWidth / 2; - const arrowYCenter = - ((_middlewareData$arrow7 = - (_middlewareData$arrow8 = middlewareData.arrow) === null || - _middlewareData$arrow8 === void 0 - ? void 0 - : _middlewareData$arrow8.y) !== null && - _middlewareData$arrow7 !== void 0 - ? _middlewareData$arrow7 - : 0) + - arrowHeight / 2; - let x = ""; - let y = ""; - if (placedSide === "bottom") { - x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; - y = `${-arrowHeight}px`; - } else if (placedSide === "top") { - x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`; - y = `${rects.floating.height + arrowHeight}px`; - } else if (placedSide === "right") { - x = `${-arrowHeight}px`; - y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; - } else if (placedSide === "left") { - x = `${rects.floating.width + arrowHeight}px`; - y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`; - } - return { - data: { - x: x, - y: y, - }, - }; - }, - }); - function $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement) { - const [side, align = "center"] = placement.split("-"); - return [side, align]; - } - const $34310caa050a8d63$export$be92b6f5f03c0fe9 = - $34310caa050a8d63$export$badac9ada3a0bdf9; - const $34310caa050a8d63$export$b688253958b8dfe7 = - $34310caa050a8d63$export$ecd4e1ccab6ed6d; - const $34310caa050a8d63$export$7c6e2c02157bb7d2 = - $34310caa050a8d63$export$bc4ae5855d3c4fc; - const $34310caa050a8d63$export$21b07c8f274aebd5 = - $34310caa050a8d63$export$79d62cd4e10a3fd0; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-portal/dist/index.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-portal/dist/index.js ***! - \******************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $amzHf$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $amzHf$react = __webpack_require__(/*! react */ "react"); - var $amzHf$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); - var $amzHf$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "Portal", - () => $913a70b877676c16$export$602eac185826482c - ); - $parcel$export( - module.exports, - "Root", - () => $913a70b877676c16$export$be92b6f5f03c0fe9 - ); - - /* ------------------------------------------------------------------------------------------------- - * Portal - * -----------------------------------------------------------------------------------------------*/ - const $913a70b877676c16$var$PORTAL_NAME = "Portal"; - const $913a70b877676c16$export$602eac185826482c = - /*#__PURE__*/ $amzHf$react.forwardRef((props, forwardedRef) => { - var _globalThis$document; - const { - container = globalThis === null || globalThis === void 0 - ? void 0 - : (_globalThis$document = globalThis.document) === null || - _globalThis$document === void 0 - ? void 0 - : _globalThis$document.body, - ...portalProps - } = props; - return container - ? /*#__PURE__*/ $parcel$interopDefault( - $amzHf$reactdom - ).createPortal( - /*#__PURE__*/ $amzHf$react.createElement( - $amzHf$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($amzHf$babelruntimehelpersextends)( - {}, - portalProps, - { - ref: forwardedRef, - } - ) - ), - container - ) - : null; - }); - /*#__PURE__*/ - Object.assign($913a70b877676c16$export$602eac185826482c, { - displayName: $913a70b877676c16$var$PORTAL_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - const $913a70b877676c16$export$be92b6f5f03c0fe9 = - $913a70b877676c16$export$602eac185826482c; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-presence/dist/index.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-presence/dist/index.js ***! - \********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $fnLeV$react = __webpack_require__(/*! react */ "react"); - var $fnLeV$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); - var $fnLeV$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $fnLeV$radixuireactuselayouteffect = __webpack_require__( - /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "Presence", - () => $a2fa0214bb2735a1$export$99c2b779aa4e8b8b - ); - function $8f63844556d0d3cd$export$3e6543de14f8614f( - initialState, - machine - ) { - return $fnLeV$react.useReducer((state, event) => { - const nextState = machine[state][event]; - return nextState !== null && nextState !== void 0 - ? nextState - : state; - }, initialState); - } - const $a2fa0214bb2735a1$export$99c2b779aa4e8b8b = (props) => { - const { present: present, children: children } = props; - const presence = $a2fa0214bb2735a1$var$usePresence(present); - const child = - typeof children === "function" - ? children({ - present: presence.isPresent, - }) - : $fnLeV$react.Children.only(children); - const ref = $fnLeV$radixuireactcomposerefs.useComposedRefs( - presence.ref, - child.ref - ); - const forceMount = typeof children === "function"; - return forceMount || presence.isPresent - ? /*#__PURE__*/ $fnLeV$react.cloneElement(child, { - ref: ref, - }) - : null; - }; - $a2fa0214bb2735a1$export$99c2b779aa4e8b8b.displayName = "Presence"; - /* ------------------------------------------------------------------------------------------------- - * usePresence - * -----------------------------------------------------------------------------------------------*/ - function $a2fa0214bb2735a1$var$usePresence(present) { - const [node1, setNode] = $fnLeV$react.useState(); - const stylesRef = $fnLeV$react.useRef({}); - const prevPresentRef = $fnLeV$react.useRef(present); - const prevAnimationNameRef = $fnLeV$react.useRef("none"); - const initialState = present ? "mounted" : "unmounted"; - const [state, send] = $8f63844556d0d3cd$export$3e6543de14f8614f( - initialState, - { - mounted: { - UNMOUNT: "unmounted", - ANIMATION_OUT: "unmountSuspended", - }, - unmountSuspended: { - MOUNT: "mounted", - ANIMATION_END: "unmounted", - }, - unmounted: { - MOUNT: "mounted", - }, - } - ); - $fnLeV$react.useEffect(() => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName( - stylesRef.current - ); - prevAnimationNameRef.current = - state === "mounted" ? currentAnimationName : "none"; - }, [state]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - const styles = stylesRef.current; - const wasPresent = prevPresentRef.current; - const hasPresentChanged = wasPresent !== present; - if (hasPresentChanged) { - const prevAnimationName = prevAnimationNameRef.current; - const currentAnimationName = - $a2fa0214bb2735a1$var$getAnimationName(styles); - if (present) send("MOUNT"); - else if ( - currentAnimationName === "none" || - (styles === null || styles === void 0 - ? void 0 - : styles.display) === "none" - ) - // If there is no exit animation or the element is hidden, animations won't run - // so we unmount instantly - send("UNMOUNT"); - else { - /** - * When `present` changes to `false`, we check changes to animation-name to - * determine whether an animation has started. We chose this approach (reading - * computed styles) because there is no `animationrun` event and `animationstart` - * fires after `animation-delay` has expired which would be too late. - */ - const isAnimating = prevAnimationName !== currentAnimationName; - if (wasPresent && isAnimating) send("ANIMATION_OUT"); - else send("UNMOUNT"); - } - prevPresentRef.current = present; - } - }, [present, send]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - if (node1) { - /** - * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel` - * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we - * make sure we only trigger ANIMATION_END for the currently active animation. - */ - const handleAnimationEnd = (event) => { - const currentAnimationName = - $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - const isCurrentAnimation = currentAnimationName.includes( - event.animationName - ); - if (event.target === node1 && isCurrentAnimation) - // With React 18 concurrency this update is applied - // a frame after the animation ends, creating a flash of visible content. - // By manually flushing we ensure they sync within a frame, removing the flash. - $fnLeV$reactdom.flushSync(() => send("ANIMATION_END")); - }; - const handleAnimationStart = (event) => { - if (event.target === node1) - // if animation occurred, store its name as the previous animation. - prevAnimationNameRef.current = - $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - }; - node1.addEventListener("animationstart", handleAnimationStart); - node1.addEventListener("animationcancel", handleAnimationEnd); - node1.addEventListener("animationend", handleAnimationEnd); - return () => { - node1.removeEventListener( - "animationstart", - handleAnimationStart - ); - node1.removeEventListener( - "animationcancel", - handleAnimationEnd - ); - node1.removeEventListener("animationend", handleAnimationEnd); - }; - } - // Transition to the unmounted state if the node is removed prematurely. - // We avoid doing so during cleanup as the node may change but still exist. - else send("ANIMATION_END"); - }, [node1, send]); - return { - isPresent: ["mounted", "unmountSuspended"].includes(state), - ref: $fnLeV$react.useCallback((node) => { - if (node) stylesRef.current = getComputedStyle(node); - setNode(node); - }, []), - }; - } - /* -----------------------------------------------------------------------------------------------*/ - function $a2fa0214bb2735a1$var$getAnimationName(styles) { - return ( - (styles === null || styles === void 0 - ? void 0 - : styles.animationName) || "none" - ); - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-primitive/dist/index.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-primitive/dist/index.js ***! - \*********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $iMixA$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $iMixA$react = __webpack_require__(/*! react */ "react"); - var $iMixA$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); - var $iMixA$radixuireactslot = __webpack_require__( - /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "Primitive", - () => $c3def6332c2749a6$export$250ffa63cdc0d034 - ); - $parcel$export( - module.exports, - "Root", - () => $c3def6332c2749a6$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "dispatchDiscreteCustomEvent", - () => $c3def6332c2749a6$export$6d1a0317bde7de7f - ); - const $c3def6332c2749a6$var$NODES = [ - "a", - "button", - "div", - "form", - "h2", - "h3", - "img", - "input", - "label", - "li", - "nav", - "ol", - "p", - "span", - "svg", - "ul", - ]; // Temporary while we await merge of this fix: - // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/55396 - // prettier-ignore - /* ------------------------------------------------------------------------------------------------- - * Primitive - * -----------------------------------------------------------------------------------------------*/ - const $c3def6332c2749a6$export$250ffa63cdc0d034 = $c3def6332c2749a6$var$NODES.reduce((primitive, node) => { - const Node = /*#__PURE__*/$iMixA$react.forwardRef((props, forwardedRef) => { - const { - asChild: asChild, - ...primitiveProps - } = props; - const Comp = asChild ? $iMixA$radixuireactslot.Slot : node; - $iMixA$react.useEffect(() => { - window[Symbol.for('radix-ui')] = true; - }, []); - return /*#__PURE__*/$iMixA$react.createElement(Comp, $parcel$interopDefault($iMixA$babelruntimehelpersextends)({}, primitiveProps, { - ref: forwardedRef - })); - }); - Node.displayName = `Primitive.${node}`; - return { - ...primitive, - [node]: Node - }; -}, {}); - /* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Flush custom event dispatch - * https://github.com/radix-ui/primitives/pull/1378 - * - * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types. - * - * Internally, React prioritises events in the following order: - * - discrete - * - continuous - * - default - * - * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350 - * - * `discrete` is an important distinction as updates within these events are applied immediately. - * React however, is not able to infer the priority of custom event types due to how they are detected internally. - * Because of this, it's possible for updates from custom events to be unexpectedly batched when - * dispatched by another `discrete` event. - * - * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch. - * This utility should be used when dispatching a custom event from within another `discrete` event, this utility - * is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event. - * For example: - * - * dispatching a known click 👎 - * target.dispatchEvent(new Event(‘click’)) - * - * dispatching a custom type within a non-discrete event 👎 - * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(‘customType’))} - * - * dispatching a custom type within a `discrete` event 👍 - * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(‘customType’))} - * - * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use - * this utility with them. This is because it's possible for those handlers to be called implicitly during render - * e.g. when focus is within a component as it is unmounted, or when managing focus on mount. - */ - function $c3def6332c2749a6$export$6d1a0317bde7de7f(target, event) { - if (target) - $iMixA$reactdom.flushSync(() => target.dispatchEvent(event)); - } - /* -----------------------------------------------------------------------------------------------*/ - const $c3def6332c2749a6$export$be92b6f5f03c0fe9 = - $c3def6332c2749a6$export$250ffa63cdc0d034; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-roving-focus/dist/index.js ***! - \************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $9QJ9Y$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $9QJ9Y$react = __webpack_require__(/*! react */ "react"); - var $9QJ9Y$radixuiprimitive = __webpack_require__( - /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" - ); - var $9QJ9Y$radixuireactcollection = __webpack_require__( - /*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js" - ); - var $9QJ9Y$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $9QJ9Y$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $9QJ9Y$radixuireactid = __webpack_require__( - /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" - ); - var $9QJ9Y$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $9QJ9Y$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - var $9QJ9Y$radixuireactusecontrollablestate = __webpack_require__( - /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" - ); - var $9QJ9Y$radixuireactdirection = __webpack_require__( - /*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createRovingFocusGroupScope", - () => $0063afae63b3fa70$export$c7109489551a4f4 - ); - $parcel$export( - module.exports, - "RovingFocusGroup", - () => $0063afae63b3fa70$export$8699f7c8af148338 - ); - $parcel$export( - module.exports, - "RovingFocusGroupItem", - () => $0063afae63b3fa70$export$ab9df7c53fe8454 - ); - $parcel$export( - module.exports, - "Root", - () => $0063afae63b3fa70$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Item", - () => $0063afae63b3fa70$export$6d08773d2e66f8f2 - ); - const $0063afae63b3fa70$var$ENTRY_FOCUS = - "rovingFocusGroup.onEntryFocus"; - const $0063afae63b3fa70$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true, - }; - /* ------------------------------------------------------------------------------------------------- - * RovingFocusGroup - * -----------------------------------------------------------------------------------------------*/ - const $0063afae63b3fa70$var$GROUP_NAME = "RovingFocusGroup"; - const [ - $0063afae63b3fa70$var$Collection, - $0063afae63b3fa70$var$useCollection, - $0063afae63b3fa70$var$createCollectionScope, - ] = $9QJ9Y$radixuireactcollection.createCollection( - $0063afae63b3fa70$var$GROUP_NAME - ); - const [ - $0063afae63b3fa70$var$createRovingFocusGroupContext, - $0063afae63b3fa70$export$c7109489551a4f4, - ] = $9QJ9Y$radixuireactcontext.createContextScope( - $0063afae63b3fa70$var$GROUP_NAME, - [$0063afae63b3fa70$var$createCollectionScope] - ); - const [ - $0063afae63b3fa70$var$RovingFocusProvider, - $0063afae63b3fa70$var$useRovingFocusContext, - ] = $0063afae63b3fa70$var$createRovingFocusGroupContext( - $0063afae63b3fa70$var$GROUP_NAME - ); - const $0063afae63b3fa70$export$8699f7c8af148338 = - /*#__PURE__*/ $9QJ9Y$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/ $9QJ9Y$react.createElement( - $0063afae63b3fa70$var$Collection.Provider, - { - scope: props.__scopeRovingFocusGroup, - }, - /*#__PURE__*/ $9QJ9Y$react.createElement( - $0063afae63b3fa70$var$Collection.Slot, - { - scope: props.__scopeRovingFocusGroup, - }, - /*#__PURE__*/ $9QJ9Y$react.createElement( - $0063afae63b3fa70$var$RovingFocusGroupImpl, - $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)( - {}, - props, - { - ref: forwardedRef, - } - ) - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($0063afae63b3fa70$export$8699f7c8af148338, { - displayName: $0063afae63b3fa70$var$GROUP_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - const $0063afae63b3fa70$var$RovingFocusGroupImpl = - /*#__PURE__*/ $9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - orientation: orientation, - loop = false, - dir: dir, - currentTabStopId: currentTabStopIdProp, - defaultCurrentTabStopId: defaultCurrentTabStopId, - onCurrentTabStopIdChange: onCurrentTabStopIdChange, - onEntryFocus: onEntryFocus, - ...groupProps - } = props; - const ref = $9QJ9Y$react.useRef(null); - const composedRefs = $9QJ9Y$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - const direction = $9QJ9Y$radixuireactdirection.useDirection(dir); - const [currentTabStopId = null, setCurrentTabStopId] = - $9QJ9Y$radixuireactusecontrollablestate.useControllableState({ - prop: currentTabStopIdProp, - defaultProp: defaultCurrentTabStopId, - onChange: onCurrentTabStopIdChange, - }); - const [isTabbingBackOut, setIsTabbingBackOut] = - $9QJ9Y$react.useState(false); - const handleEntryFocus = - $9QJ9Y$radixuireactusecallbackref.useCallbackRef(onEntryFocus); - const getItems = $0063afae63b3fa70$var$useCollection( - __scopeRovingFocusGroup - ); - const isClickFocusRef = $9QJ9Y$react.useRef(false); - const [focusableItemsCount, setFocusableItemsCount] = - $9QJ9Y$react.useState(0); - $9QJ9Y$react.useEffect(() => { - const node = ref.current; - if (node) { - node.addEventListener( - $0063afae63b3fa70$var$ENTRY_FOCUS, - handleEntryFocus - ); - return () => - node.removeEventListener( - $0063afae63b3fa70$var$ENTRY_FOCUS, - handleEntryFocus - ); - } - }, [handleEntryFocus]); - return /*#__PURE__*/ $9QJ9Y$react.createElement( - $0063afae63b3fa70$var$RovingFocusProvider, - { - scope: __scopeRovingFocusGroup, - orientation: orientation, - dir: direction, - loop: loop, - currentTabStopId: currentTabStopId, - onItemFocus: $9QJ9Y$react.useCallback( - (tabStopId) => setCurrentTabStopId(tabStopId), - [setCurrentTabStopId] - ), - onItemShiftTab: $9QJ9Y$react.useCallback( - () => setIsTabbingBackOut(true), - [] - ), - onFocusableItemAdd: $9QJ9Y$react.useCallback( - () => setFocusableItemsCount((prevCount) => prevCount + 1), - [] - ), - onFocusableItemRemove: $9QJ9Y$react.useCallback( - () => setFocusableItemsCount((prevCount) => prevCount - 1), - [] - ), - }, - /*#__PURE__*/ $9QJ9Y$react.createElement( - $9QJ9Y$radixuireactprimitive.Primitive.div, - $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)( - { - tabIndex: - isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0, - "data-orientation": orientation, - }, - groupProps, - { - ref: composedRefs, - style: { - outline: "none", - ...props.style, - }, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers( - props.onMouseDown, - () => { - isClickFocusRef.current = true; - } - ), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers( - props.onFocus, - (event) => { - // We normally wouldn't need this check, because we already check - // that the focus is on the current target and not bubbling to it. - // We do this because Safari doesn't focus buttons when clicked, and - // instead, the wrapper will get focused and not through a bubbling event. - const isKeyboardFocus = !isClickFocusRef.current; - if ( - event.target === event.currentTarget && - isKeyboardFocus && - !isTabbingBackOut - ) { - const entryFocusEvent = new CustomEvent( - $0063afae63b3fa70$var$ENTRY_FOCUS, - $0063afae63b3fa70$var$EVENT_OPTIONS - ); - event.currentTarget.dispatchEvent(entryFocusEvent); - if (!entryFocusEvent.defaultPrevented) { - const items = getItems().filter( - (item) => item.focusable - ); - const activeItem = items.find( - (item) => item.active - ); - const currentItem = items.find( - (item) => item.id === currentTabStopId - ); - const candidateItems = [ - activeItem, - currentItem, - ...items, - ].filter(Boolean); - const candidateNodes = candidateItems.map( - (item) => item.ref.current - ); - $0063afae63b3fa70$var$focusFirst(candidateNodes); - } - } - isClickFocusRef.current = false; - } - ), - onBlur: $9QJ9Y$radixuiprimitive.composeEventHandlers( - props.onBlur, - () => setIsTabbingBackOut(false) - ), - } - ) - ) - ); - }); - /* ------------------------------------------------------------------------------------------------- - * RovingFocusGroupItem - * -----------------------------------------------------------------------------------------------*/ - const $0063afae63b3fa70$var$ITEM_NAME = "RovingFocusGroupItem"; - const $0063afae63b3fa70$export$ab9df7c53fe8454 = - /*#__PURE__*/ $9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - focusable = true, - active = false, - tabStopId: tabStopId, - ...itemProps - } = props; - const autoId = $9QJ9Y$radixuireactid.useId(); - const id = tabStopId || autoId; - const context = $0063afae63b3fa70$var$useRovingFocusContext( - $0063afae63b3fa70$var$ITEM_NAME, - __scopeRovingFocusGroup - ); - const isCurrentTabStop = context.currentTabStopId === id; - const getItems = $0063afae63b3fa70$var$useCollection( - __scopeRovingFocusGroup - ); - const { - onFocusableItemAdd: onFocusableItemAdd, - onFocusableItemRemove: onFocusableItemRemove, - } = context; - $9QJ9Y$react.useEffect(() => { - if (focusable) { - onFocusableItemAdd(); - return () => onFocusableItemRemove(); - } - }, [focusable, onFocusableItemAdd, onFocusableItemRemove]); - return /*#__PURE__*/ $9QJ9Y$react.createElement( - $0063afae63b3fa70$var$Collection.ItemSlot, - { - scope: __scopeRovingFocusGroup, - id: id, - focusable: focusable, - active: active, - }, - /*#__PURE__*/ $9QJ9Y$react.createElement( - $9QJ9Y$radixuireactprimitive.Primitive.span, - $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)( - { - tabIndex: isCurrentTabStop ? 0 : -1, - "data-orientation": context.orientation, - }, - itemProps, - { - ref: forwardedRef, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers( - props.onMouseDown, - (event) => { - // We prevent focusing non-focusable items on `mousedown`. - // Even though the item has tabIndex={-1}, that only means take it out of the tab order. - if (!focusable) - event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also - else context.onItemFocus(id); - } - ), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers( - props.onFocus, - () => context.onItemFocus(id) - ), - onKeyDown: $9QJ9Y$radixuiprimitive.composeEventHandlers( - props.onKeyDown, - (event) => { - if (event.key === "Tab" && event.shiftKey) { - context.onItemShiftTab(); - return; - } - if (event.target !== event.currentTarget) return; - const focusIntent = - $0063afae63b3fa70$var$getFocusIntent( - event, - context.orientation, - context.dir - ); - if (focusIntent !== undefined) { - event.preventDefault(); - const items = getItems().filter( - (item) => item.focusable - ); - let candidateNodes = items.map( - (item) => item.ref.current - ); - if (focusIntent === "last") candidateNodes.reverse(); - else if ( - focusIntent === "prev" || - focusIntent === "next" - ) { - if (focusIntent === "prev") - candidateNodes.reverse(); - const currentIndex = candidateNodes.indexOf( - event.currentTarget - ); - candidateNodes = context.loop - ? $0063afae63b3fa70$var$wrapArray( - candidateNodes, - currentIndex + 1 - ) - : candidateNodes.slice(currentIndex + 1); - } - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => - $0063afae63b3fa70$var$focusFirst(candidateNodes) - ); - } - } - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($0063afae63b3fa70$export$ab9df7c53fe8454, { - displayName: $0063afae63b3fa70$var$ITEM_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ // prettier-ignore - const $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT = { - ArrowLeft: 'prev', - ArrowUp: 'prev', - ArrowRight: 'next', - ArrowDown: 'next', - PageUp: 'first', - Home: 'first', - PageDown: 'last', - End: 'last' -}; - function $0063afae63b3fa70$var$getDirectionAwareKey(key, dir) { - if (dir !== "rtl") return key; - return key === "ArrowLeft" - ? "ArrowRight" - : key === "ArrowRight" - ? "ArrowLeft" - : key; - } - function $0063afae63b3fa70$var$getFocusIntent(event, orientation, dir) { - const key = $0063afae63b3fa70$var$getDirectionAwareKey( - event.key, - dir - ); - if ( - orientation === "vertical" && - ["ArrowLeft", "ArrowRight"].includes(key) - ) - return undefined; - if ( - orientation === "horizontal" && - ["ArrowUp", "ArrowDown"].includes(key) - ) - return undefined; - return $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT[key]; - } - function $0063afae63b3fa70$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } - } - /** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ - function $0063afae63b3fa70$var$wrapArray(array, startIndex) { - return array.map( - (_, index) => array[(startIndex + index) % array.length] - ); - } - const $0063afae63b3fa70$export$be92b6f5f03c0fe9 = - $0063afae63b3fa70$export$8699f7c8af148338; - const $0063afae63b3fa70$export$6d08773d2e66f8f2 = - $0063afae63b3fa70$export$ab9df7c53fe8454; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-slot/dist/index.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-slot/dist/index.js ***! - \****************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $dAvBt$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $dAvBt$react = __webpack_require__(/*! react */ "react"); - var $dAvBt$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "Slot", - () => $82dc8d030dec7549$export$8c6ed5c666ac1360 - ); - $parcel$export( - module.exports, - "Slottable", - () => $82dc8d030dec7549$export$d9f1ccf0bdb05d45 - ); - $parcel$export( - module.exports, - "Root", - () => $82dc8d030dec7549$export$be92b6f5f03c0fe9 - ); - - /* ------------------------------------------------------------------------------------------------- - * Slot - * -----------------------------------------------------------------------------------------------*/ - const $82dc8d030dec7549$export$8c6ed5c666ac1360 = - /*#__PURE__*/ $dAvBt$react.forwardRef((props, forwardedRef) => { - const { children: children, ...slotProps } = props; - const childrenArray = $dAvBt$react.Children.toArray(children); - const slottable = childrenArray.find( - $82dc8d030dec7549$var$isSlottable - ); - if (slottable) { - // the new element to render is the one passed as a child of `Slottable` - const newElement = slottable.props.children; - const newChildren = childrenArray.map((child) => { - if (child === slottable) { - // because the new element will be the one rendered, we are only interested - // in grabbing its children (`newElement.props.children`) - if ($dAvBt$react.Children.count(newElement) > 1) - return $dAvBt$react.Children.only(null); - return /*#__PURE__*/ $dAvBt$react.isValidElement(newElement) - ? newElement.props.children - : null; - } else return child; - }); - return /*#__PURE__*/ $dAvBt$react.createElement( - $82dc8d030dec7549$var$SlotClone, - $parcel$interopDefault($dAvBt$babelruntimehelpersextends)( - {}, - slotProps, - { - ref: forwardedRef, - } - ), - /*#__PURE__*/ $dAvBt$react.isValidElement(newElement) - ? /*#__PURE__*/ $dAvBt$react.cloneElement( - newElement, - undefined, - newChildren - ) - : null - ); - } - return /*#__PURE__*/ $dAvBt$react.createElement( - $82dc8d030dec7549$var$SlotClone, - $parcel$interopDefault($dAvBt$babelruntimehelpersextends)( - {}, - slotProps, - { - ref: forwardedRef, - } - ), - children - ); - }); - $82dc8d030dec7549$export$8c6ed5c666ac1360.displayName = "Slot"; - /* ------------------------------------------------------------------------------------------------- - * SlotClone - * -----------------------------------------------------------------------------------------------*/ - const $82dc8d030dec7549$var$SlotClone = - /*#__PURE__*/ $dAvBt$react.forwardRef((props, forwardedRef) => { - const { children: children, ...slotProps } = props; - if (/*#__PURE__*/ $dAvBt$react.isValidElement(children)) - return /*#__PURE__*/ $dAvBt$react.cloneElement(children, { - ...$82dc8d030dec7549$var$mergeProps(slotProps, children.props), - ref: forwardedRef - ? $dAvBt$radixuireactcomposerefs.composeRefs( - forwardedRef, - children.ref - ) - : children.ref, - }); - return $dAvBt$react.Children.count(children) > 1 - ? $dAvBt$react.Children.only(null) - : null; - }); - $82dc8d030dec7549$var$SlotClone.displayName = "SlotClone"; - /* ------------------------------------------------------------------------------------------------- - * Slottable - * -----------------------------------------------------------------------------------------------*/ - const $82dc8d030dec7549$export$d9f1ccf0bdb05d45 = ({ - children: children, - }) => { - return /*#__PURE__*/ $dAvBt$react.createElement( - $dAvBt$react.Fragment, - null, - children - ); - }; - /* ---------------------------------------------------------------------------------------------- */ - function $82dc8d030dec7549$var$isSlottable(child) { - return ( - /*#__PURE__*/ $dAvBt$react.isValidElement(child) && - child.type === $82dc8d030dec7549$export$d9f1ccf0bdb05d45 - ); - } - function $82dc8d030dec7549$var$mergeProps(slotProps, childProps) { - // all child props should override - const overrideProps = { - ...childProps, - }; - for (const propName in childProps) { - const slotPropValue = slotProps[propName]; - const childPropValue = childProps[propName]; - const isHandler = /^on[A-Z]/.test(propName); - if (isHandler) { - // if the handler exists on both, we compose them - if (slotPropValue && childPropValue) - overrideProps[propName] = (...args) => { - childPropValue(...args); - slotPropValue(...args); - }; - else if (slotPropValue) overrideProps[propName] = slotPropValue; - } else if (propName === "style") - overrideProps[propName] = { - ...slotPropValue, - ...childPropValue, - }; - else if (propName === "className") - overrideProps[propName] = [slotPropValue, childPropValue] - .filter(Boolean) - .join(" "); - } - return { - ...slotProps, - ...overrideProps, - }; - } - const $82dc8d030dec7549$export$be92b6f5f03c0fe9 = - $82dc8d030dec7549$export$8c6ed5c666ac1360; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-tooltip/dist/index.js ***! - \*******************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $iVrL9$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $iVrL9$react = __webpack_require__(/*! react */ "react"); - var $iVrL9$radixuiprimitive = __webpack_require__( - /*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js" - ); - var $iVrL9$radixuireactcomposerefs = __webpack_require__( - /*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js" - ); - var $iVrL9$radixuireactcontext = __webpack_require__( - /*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js" - ); - var $iVrL9$radixuireactdismissablelayer = __webpack_require__( - /*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js" - ); - var $iVrL9$radixuireactid = __webpack_require__( - /*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js" - ); - var $iVrL9$radixuireactpopper = __webpack_require__( - /*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js" - ); - var $iVrL9$radixuireactportal = __webpack_require__( - /*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js" - ); - var $iVrL9$radixuireactpresence = __webpack_require__( - /*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js" - ); - var $iVrL9$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - var $iVrL9$radixuireactslot = __webpack_require__( - /*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js" - ); - var $iVrL9$radixuireactusecontrollablestate = __webpack_require__( - /*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js" - ); - var $iVrL9$radixuireactvisuallyhidden = __webpack_require__( - /*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "createTooltipScope", - () => $c34afbc43c90cc6f$export$1c540a2224f0d865 - ); - $parcel$export( - module.exports, - "TooltipProvider", - () => $c34afbc43c90cc6f$export$f78649fb9ca566b8 - ); - $parcel$export( - module.exports, - "Tooltip", - () => $c34afbc43c90cc6f$export$28c660c63b792dea - ); - $parcel$export( - module.exports, - "TooltipTrigger", - () => $c34afbc43c90cc6f$export$8c610744efcf8a1d - ); - $parcel$export( - module.exports, - "TooltipPortal", - () => $c34afbc43c90cc6f$export$7b36b8f925ab7497 - ); - $parcel$export( - module.exports, - "TooltipContent", - () => $c34afbc43c90cc6f$export$e9003e2be37ec060 - ); - $parcel$export( - module.exports, - "TooltipArrow", - () => $c34afbc43c90cc6f$export$c27ee0ad710f7559 - ); - $parcel$export( - module.exports, - "Provider", - () => $c34afbc43c90cc6f$export$2881499e37b75b9a - ); - $parcel$export( - module.exports, - "Root", - () => $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 - ); - $parcel$export( - module.exports, - "Trigger", - () => $c34afbc43c90cc6f$export$41fb9f06171c75f4 - ); - $parcel$export( - module.exports, - "Portal", - () => $c34afbc43c90cc6f$export$602eac185826482c - ); - $parcel$export( - module.exports, - "Content", - () => $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 - ); - $parcel$export( - module.exports, - "Arrow", - () => $c34afbc43c90cc6f$export$21b07c8f274aebd5 - ); - const [ - $c34afbc43c90cc6f$var$createTooltipContext, - $c34afbc43c90cc6f$export$1c540a2224f0d865, - ] = $iVrL9$radixuireactcontext.createContextScope("Tooltip", [ - $iVrL9$radixuireactpopper.createPopperScope, - ]); - const $c34afbc43c90cc6f$var$usePopperScope = - $iVrL9$radixuireactpopper.createPopperScope(); - /* ------------------------------------------------------------------------------------------------- - * TooltipProvider - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$PROVIDER_NAME = "TooltipProvider"; - const $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION = 700; - const $c34afbc43c90cc6f$var$TOOLTIP_OPEN = "tooltip.open"; - const [ - $c34afbc43c90cc6f$var$TooltipProviderContextProvider, - $c34afbc43c90cc6f$var$useTooltipProviderContext, - ] = $c34afbc43c90cc6f$var$createTooltipContext( - $c34afbc43c90cc6f$var$PROVIDER_NAME - ); - const $c34afbc43c90cc6f$export$f78649fb9ca566b8 = (props) => { - const { - __scopeTooltip: __scopeTooltip, - delayDuration = $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION, - skipDelayDuration = 300, - disableHoverableContent = false, - children: children, - } = props; - const [isOpenDelayed, setIsOpenDelayed] = $iVrL9$react.useState(true); - const isPointerInTransitRef = $iVrL9$react.useRef(false); - const skipDelayTimerRef = $iVrL9$react.useRef(0); - $iVrL9$react.useEffect(() => { - const skipDelayTimer = skipDelayTimerRef.current; - return () => window.clearTimeout(skipDelayTimer); - }, []); - return /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$TooltipProviderContextProvider, - { - scope: __scopeTooltip, - isOpenDelayed: isOpenDelayed, - delayDuration: delayDuration, - onOpen: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - setIsOpenDelayed(false); - }, []), - onClose: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - skipDelayTimerRef.current = window.setTimeout( - () => setIsOpenDelayed(true), - skipDelayDuration - ); - }, [skipDelayDuration]), - isPointerInTransitRef: isPointerInTransitRef, - onPointerInTransitChange: $iVrL9$react.useCallback( - (inTransit) => { - isPointerInTransitRef.current = inTransit; - }, - [] - ), - disableHoverableContent: disableHoverableContent, - }, - children - ); - }; - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$f78649fb9ca566b8, { - displayName: $c34afbc43c90cc6f$var$PROVIDER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * Tooltip - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$TOOLTIP_NAME = "Tooltip"; - const [ - $c34afbc43c90cc6f$var$TooltipContextProvider, - $c34afbc43c90cc6f$var$useTooltipContext, - ] = $c34afbc43c90cc6f$var$createTooltipContext( - $c34afbc43c90cc6f$var$TOOLTIP_NAME - ); - const $c34afbc43c90cc6f$export$28c660c63b792dea = (props) => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - open: openProp, - defaultOpen = false, - onOpenChange: onOpenChange, - disableHoverableContent: disableHoverableContentProp, - delayDuration: delayDurationProp, - } = props; - const providerContext = - $c34afbc43c90cc6f$var$useTooltipProviderContext( - $c34afbc43c90cc6f$var$TOOLTIP_NAME, - props.__scopeTooltip - ); - const popperScope = - $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const [trigger, setTrigger] = $iVrL9$react.useState(null); - const contentId = $iVrL9$radixuireactid.useId(); - const openTimerRef = $iVrL9$react.useRef(0); - const disableHoverableContent = - disableHoverableContentProp !== null && - disableHoverableContentProp !== void 0 - ? disableHoverableContentProp - : providerContext.disableHoverableContent; - const delayDuration = - delayDurationProp !== null && delayDurationProp !== void 0 - ? delayDurationProp - : providerContext.delayDuration; - const wasOpenDelayedRef = $iVrL9$react.useRef(false); - const [open1 = false, setOpen] = - $iVrL9$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: (open) => { - if (open) { - providerContext.onOpen(); // as `onChange` is called within a lifecycle method we - // avoid dispatching via `dispatchDiscreteCustomEvent`. - document.dispatchEvent( - new CustomEvent($c34afbc43c90cc6f$var$TOOLTIP_OPEN) - ); - } else providerContext.onClose(); - onOpenChange === null || - onOpenChange === void 0 || - onOpenChange(open); - }, - }); - const stateAttribute = $iVrL9$react.useMemo(() => { - return open1 - ? wasOpenDelayedRef.current - ? "delayed-open" - : "instant-open" - : "closed"; - }, [open1]); - const handleOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - wasOpenDelayedRef.current = false; - setOpen(true); - }, [setOpen]); - const handleClose = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - setOpen(false); - }, [setOpen]); - const handleDelayedOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - openTimerRef.current = window.setTimeout(() => { - wasOpenDelayedRef.current = true; - setOpen(true); - }, delayDuration); - }, [delayDuration, setOpen]); - $iVrL9$react.useEffect(() => { - return () => window.clearTimeout(openTimerRef.current); - }, []); - return /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactpopper.Root, - popperScope, - /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$TooltipContextProvider, - { - scope: __scopeTooltip, - contentId: contentId, - open: open1, - stateAttribute: stateAttribute, - trigger: trigger, - onTriggerChange: setTrigger, - onTriggerEnter: $iVrL9$react.useCallback(() => { - if (providerContext.isOpenDelayed) handleDelayedOpen(); - else handleOpen(); - }, [ - providerContext.isOpenDelayed, - handleDelayedOpen, - handleOpen, - ]), - onTriggerLeave: $iVrL9$react.useCallback(() => { - if (disableHoverableContent) handleClose(); - // Clear the timer in case the pointer leaves the trigger before the tooltip is opened. - else window.clearTimeout(openTimerRef.current); - }, [handleClose, disableHoverableContent]), - onOpen: handleOpen, - onClose: handleClose, - disableHoverableContent: disableHoverableContent, - }, - children - ) - ); - }; - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$28c660c63b792dea, { - displayName: $c34afbc43c90cc6f$var$TOOLTIP_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipTrigger - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$TRIGGER_NAME = "TooltipTrigger"; - const $c34afbc43c90cc6f$export$8c610744efcf8a1d = - /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { - const { __scopeTooltip: __scopeTooltip, ...triggerProps } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext( - $c34afbc43c90cc6f$var$TRIGGER_NAME, - __scopeTooltip - ); - const providerContext = - $c34afbc43c90cc6f$var$useTooltipProviderContext( - $c34afbc43c90cc6f$var$TRIGGER_NAME, - __scopeTooltip - ); - const popperScope = - $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref, - context.onTriggerChange - ); - const isPointerDownRef = $iVrL9$react.useRef(false); - const hasPointerMoveOpenedRef = $iVrL9$react.useRef(false); - const handlePointerUp = $iVrL9$react.useCallback( - () => (isPointerDownRef.current = false), - [] - ); - $iVrL9$react.useEffect(() => { - return () => - document.removeEventListener("pointerup", handlePointerUp); - }, [handlePointerUp]); - return /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactpopper.Anchor, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - { - asChild: true, - }, - popperScope - ), - /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactprimitive.Primitive.button, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - { - // We purposefully avoid adding `type=button` here because tooltip triggers are also - // commonly anchors and the anchor `type` attribute signifies MIME type. - "aria-describedby": context.open - ? context.contentId - : undefined, - "data-state": context.stateAttribute, - }, - triggerProps, - { - ref: composedRefs, - onPointerMove: $iVrL9$radixuiprimitive.composeEventHandlers( - props.onPointerMove, - (event) => { - if (event.pointerType === "touch") return; - if ( - !hasPointerMoveOpenedRef.current && - !providerContext.isPointerInTransitRef.current - ) { - context.onTriggerEnter(); - hasPointerMoveOpenedRef.current = true; - } - } - ), - onPointerLeave: - $iVrL9$radixuiprimitive.composeEventHandlers( - props.onPointerLeave, - () => { - context.onTriggerLeave(); - hasPointerMoveOpenedRef.current = false; - } - ), - onPointerDown: $iVrL9$radixuiprimitive.composeEventHandlers( - props.onPointerDown, - () => { - isPointerDownRef.current = true; - document.addEventListener( - "pointerup", - handlePointerUp, - { - once: true, - } - ); - } - ), - onFocus: $iVrL9$radixuiprimitive.composeEventHandlers( - props.onFocus, - () => { - if (!isPointerDownRef.current) context.onOpen(); - } - ), - onBlur: $iVrL9$radixuiprimitive.composeEventHandlers( - props.onBlur, - context.onClose - ), - onClick: $iVrL9$radixuiprimitive.composeEventHandlers( - props.onClick, - context.onClose - ), - } - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$8c610744efcf8a1d, { - displayName: $c34afbc43c90cc6f$var$TRIGGER_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipPortal - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$PORTAL_NAME = "TooltipPortal"; - const [ - $c34afbc43c90cc6f$var$PortalProvider, - $c34afbc43c90cc6f$var$usePortalContext, - ] = $c34afbc43c90cc6f$var$createTooltipContext( - $c34afbc43c90cc6f$var$PORTAL_NAME, - { - forceMount: undefined, - } - ); - const $c34afbc43c90cc6f$export$7b36b8f925ab7497 = (props) => { - const { - __scopeTooltip: __scopeTooltip, - forceMount: forceMount, - children: children, - container: container, - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext( - $c34afbc43c90cc6f$var$PORTAL_NAME, - __scopeTooltip - ); - return /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$PortalProvider, - { - scope: __scopeTooltip, - forceMount: forceMount, - }, - /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactportal.Portal, - { - asChild: true, - container: container, - }, - children - ) - ) - ); - }; - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$7b36b8f925ab7497, { - displayName: $c34afbc43c90cc6f$var$PORTAL_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipContent - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$CONTENT_NAME = "TooltipContent"; - const $c34afbc43c90cc6f$export$e9003e2be37ec060 = - /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { - const portalContext = $c34afbc43c90cc6f$var$usePortalContext( - $c34afbc43c90cc6f$var$CONTENT_NAME, - props.__scopeTooltip - ); - const { - forceMount = portalContext.forceMount, - side = "top", - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext( - $c34afbc43c90cc6f$var$CONTENT_NAME, - props.__scopeTooltip - ); - return /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactpresence.Presence, - { - present: forceMount || context.open, - }, - context.disableHoverableContent - ? /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$TooltipContentImpl, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - { - side: side, - }, - contentProps, - { - ref: forwardedRef, - } - ) - ) - : /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$TooltipContentHoverable, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - { - side: side, - }, - contentProps, - { - ref: forwardedRef, - } - ) - ) - ); - }); - const $c34afbc43c90cc6f$var$TooltipContentHoverable = - /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { - const context = $c34afbc43c90cc6f$var$useTooltipContext( - $c34afbc43c90cc6f$var$CONTENT_NAME, - props.__scopeTooltip - ); - const providerContext = - $c34afbc43c90cc6f$var$useTooltipProviderContext( - $c34afbc43c90cc6f$var$CONTENT_NAME, - props.__scopeTooltip - ); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs( - forwardedRef, - ref - ); - const [pointerGraceArea, setPointerGraceArea] = - $iVrL9$react.useState(null); - const { trigger: trigger, onClose: onClose } = context; - const content = ref.current; - const { onPointerInTransitChange: onPointerInTransitChange } = - providerContext; - const handleRemoveGraceArea = $iVrL9$react.useCallback(() => { - setPointerGraceArea(null); - onPointerInTransitChange(false); - }, [onPointerInTransitChange]); - const handleCreateGraceArea = $iVrL9$react.useCallback( - (event, hoverTarget) => { - const currentTarget = event.currentTarget; - const exitPoint = { - x: event.clientX, - y: event.clientY, - }; - const exitSide = $c34afbc43c90cc6f$var$getExitSideFromRect( - exitPoint, - currentTarget.getBoundingClientRect() - ); - const paddedExitPoints = - $c34afbc43c90cc6f$var$getPaddedExitPoints( - exitPoint, - exitSide - ); - const hoverTargetPoints = - $c34afbc43c90cc6f$var$getPointsFromRect( - hoverTarget.getBoundingClientRect() - ); - const graceArea = $c34afbc43c90cc6f$var$getHull([ - ...paddedExitPoints, - ...hoverTargetPoints, - ]); - setPointerGraceArea(graceArea); - onPointerInTransitChange(true); - }, - [onPointerInTransitChange] - ); - $iVrL9$react.useEffect(() => { - return () => handleRemoveGraceArea(); - }, [handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (trigger && content) { - const handleTriggerLeave = (event) => - handleCreateGraceArea(event, content); - const handleContentLeave = (event) => - handleCreateGraceArea(event, trigger); - trigger.addEventListener("pointerleave", handleTriggerLeave); - content.addEventListener("pointerleave", handleContentLeave); - return () => { - trigger.removeEventListener( - "pointerleave", - handleTriggerLeave - ); - content.removeEventListener( - "pointerleave", - handleContentLeave - ); - }; - } - }, [ - trigger, - content, - handleCreateGraceArea, - handleRemoveGraceArea, - ]); - $iVrL9$react.useEffect(() => { - if (pointerGraceArea) { - const handleTrackPointerGrace = (event) => { - const target = event.target; - const pointerPosition = { - x: event.clientX, - y: event.clientY, - }; - const hasEnteredTarget = - (trigger === null || trigger === void 0 - ? void 0 - : trigger.contains(target)) || - (content === null || content === void 0 - ? void 0 - : content.contains(target)); - const isPointerOutsideGraceArea = - !$c34afbc43c90cc6f$var$isPointInPolygon( - pointerPosition, - pointerGraceArea - ); - if (hasEnteredTarget) handleRemoveGraceArea(); - else if (isPointerOutsideGraceArea) { - handleRemoveGraceArea(); - onClose(); - } - }; - document.addEventListener( - "pointermove", - handleTrackPointerGrace - ); - return () => - document.removeEventListener( - "pointermove", - handleTrackPointerGrace - ); - } - }, [ - trigger, - content, - pointerGraceArea, - onClose, - handleRemoveGraceArea, - ]); - return /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$TooltipContentImpl, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - {}, - props, - { - ref: composedRefs, - } - ) - ); - }); - const [ - $c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, - $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext, - ] = $c34afbc43c90cc6f$var$createTooltipContext( - $c34afbc43c90cc6f$var$TOOLTIP_NAME, - { - isInside: false, - } - ); - const $c34afbc43c90cc6f$var$TooltipContentImpl = - /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - "aria-label": ariaLabel, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext( - $c34afbc43c90cc6f$var$CONTENT_NAME, - __scopeTooltip - ); - const popperScope = - $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const { onClose: onClose } = context; // Close this tooltip if another one opens - $iVrL9$react.useEffect(() => { - document.addEventListener( - $c34afbc43c90cc6f$var$TOOLTIP_OPEN, - onClose - ); - return () => - document.removeEventListener( - $c34afbc43c90cc6f$var$TOOLTIP_OPEN, - onClose - ); - }, [onClose]); // Close the tooltip if the trigger is scrolled - $iVrL9$react.useEffect(() => { - if (context.trigger) { - const handleScroll = (event) => { - const target = event.target; - if ( - target !== null && - target !== void 0 && - target.contains(context.trigger) - ) - onClose(); - }; - window.addEventListener("scroll", handleScroll, { - capture: true, - }); - return () => - window.removeEventListener("scroll", handleScroll, { - capture: true, - }); - } - }, [context.trigger, onClose]); - return /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactdismissablelayer.DismissableLayer, - { - asChild: true, - disableOutsidePointerEvents: false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: (event) => event.preventDefault(), - onDismiss: onClose, - }, - /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactpopper.Content, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - { - "data-state": context.stateAttribute, - }, - popperScope, - contentProps, - { - ref: forwardedRef, - style: { - ...contentProps.style, - "--radix-tooltip-content-transform-origin": - "var(--radix-popper-transform-origin)", - "--radix-tooltip-content-available-width": - "var(--radix-popper-available-width)", - "--radix-tooltip-content-available-height": - "var(--radix-popper-available-height)", - "--radix-tooltip-trigger-width": - "var(--radix-popper-anchor-width)", - "--radix-tooltip-trigger-height": - "var(--radix-popper-anchor-height)", - }, - } - ), - /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactslot.Slottable, - null, - children - ), - /*#__PURE__*/ $iVrL9$react.createElement( - $c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, - { - scope: __scopeTooltip, - isInside: true, - }, - /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactvisuallyhidden.Root, - { - id: context.contentId, - role: "tooltip", - }, - ariaLabel || children - ) - ) - ) - ); - }); - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$e9003e2be37ec060, { - displayName: $c34afbc43c90cc6f$var$CONTENT_NAME, - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipArrow - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$ARROW_NAME = "TooltipArrow"; - const $c34afbc43c90cc6f$export$c27ee0ad710f7559 = - /*#__PURE__*/ $iVrL9$react.forwardRef((props, forwardedRef) => { - const { __scopeTooltip: __scopeTooltip, ...arrowProps } = props; - const popperScope = - $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const visuallyHiddenContentContext = - $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext( - $c34afbc43c90cc6f$var$ARROW_NAME, - __scopeTooltip - ); // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to - // prevent issues in positioning the arrow due to the duplicate - return visuallyHiddenContentContext.isInside - ? null - : /*#__PURE__*/ $iVrL9$react.createElement( - $iVrL9$radixuireactpopper.Arrow, - $parcel$interopDefault($iVrL9$babelruntimehelpersextends)( - {}, - popperScope, - arrowProps, - { - ref: forwardedRef, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$c27ee0ad710f7559, { - displayName: $c34afbc43c90cc6f$var$ARROW_NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - function $c34afbc43c90cc6f$var$getExitSideFromRect(point, rect) { - const top = Math.abs(rect.top - point.y); - const bottom = Math.abs(rect.bottom - point.y); - const right = Math.abs(rect.right - point.x); - const left = Math.abs(rect.left - point.x); - switch (Math.min(top, bottom, right, left)) { - case left: - return "left"; - case right: - return "right"; - case top: - return "top"; - case bottom: - return "bottom"; - default: - throw new Error("unreachable"); - } - } - function $c34afbc43c90cc6f$var$getPaddedExitPoints( - exitPoint, - exitSide, - padding = 5 - ) { - const paddedExitPoints = []; - switch (exitSide) { - case "top": - paddedExitPoints.push( - { - x: exitPoint.x - padding, - y: exitPoint.y + padding, - }, - { - x: exitPoint.x + padding, - y: exitPoint.y + padding, - } - ); - break; - case "bottom": - paddedExitPoints.push( - { - x: exitPoint.x - padding, - y: exitPoint.y - padding, - }, - { - x: exitPoint.x + padding, - y: exitPoint.y - padding, - } - ); - break; - case "left": - paddedExitPoints.push( - { - x: exitPoint.x + padding, - y: exitPoint.y - padding, - }, - { - x: exitPoint.x + padding, - y: exitPoint.y + padding, - } - ); - break; - case "right": - paddedExitPoints.push( - { - x: exitPoint.x - padding, - y: exitPoint.y - padding, - }, - { - x: exitPoint.x - padding, - y: exitPoint.y + padding, - } - ); - break; - } - return paddedExitPoints; - } - function $c34afbc43c90cc6f$var$getPointsFromRect(rect) { - const { top: top, right: right, bottom: bottom, left: left } = rect; - return [ - { - x: left, - y: top, - }, - { - x: right, - y: top, - }, - { - x: right, - y: bottom, - }, - { - x: left, - y: bottom, - }, - ]; - } // Determine if a point is inside of a polygon. - // Based on https://github.com/substack/point-in-polygon - function $c34afbc43c90cc6f$var$isPointInPolygon(point, polygon) { - const { x: x, y: y } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = - yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; - } // Returns a new array of points representing the convex hull of the given set of points. - // https://www.nayuki.io/page/convex-hull-algorithm - function $c34afbc43c90cc6f$var$getHull(points) { - const newPoints = points.slice(); - newPoints.sort((a, b) => { - if (a.x < b.x) return -1; - else if (a.x > b.x) return 1; - else if (a.y < b.y) return -1; - else if (a.y > b.y) return 1; - else return 0; - }); - return $c34afbc43c90cc6f$var$getHullPresorted(newPoints); - } // Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time. - function $c34afbc43c90cc6f$var$getHullPresorted(points) { - if (points.length <= 1) return points.slice(); - const upperHull = []; - for (let i = 0; i < points.length; i++) { - const p = points[i]; - while (upperHull.length >= 2) { - const q = upperHull[upperHull.length - 1]; - const r = upperHull[upperHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) - upperHull.pop(); - else break; - } - upperHull.push(p); - } - upperHull.pop(); - const lowerHull = []; - for (let i1 = points.length - 1; i1 >= 0; i1--) { - const p = points[i1]; - while (lowerHull.length >= 2) { - const q = lowerHull[lowerHull.length - 1]; - const r = lowerHull[lowerHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) - lowerHull.pop(); - else break; - } - lowerHull.push(p); - } - lowerHull.pop(); - if ( - upperHull.length === 1 && - lowerHull.length === 1 && - upperHull[0].x === lowerHull[0].x && - upperHull[0].y === lowerHull[0].y - ) - return upperHull; - else return upperHull.concat(lowerHull); - } - const $c34afbc43c90cc6f$export$2881499e37b75b9a = - $c34afbc43c90cc6f$export$f78649fb9ca566b8; - const $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 = - $c34afbc43c90cc6f$export$28c660c63b792dea; - const $c34afbc43c90cc6f$export$41fb9f06171c75f4 = - $c34afbc43c90cc6f$export$8c610744efcf8a1d; - const $c34afbc43c90cc6f$export$602eac185826482c = - $c34afbc43c90cc6f$export$7b36b8f925ab7497; - const $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 = - $c34afbc43c90cc6f$export$e9003e2be37ec060; - const $c34afbc43c90cc6f$export$21b07c8f274aebd5 = - $c34afbc43c90cc6f$export$c27ee0ad710f7559; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js ***! - \****************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $92muK$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useCallbackRef", - () => $28e03942f763e819$export$25bec8c6f54ee79a - ); - - /** - * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a - * prop or avoid re-executing effects when passed as a dependency - */ - function $28e03942f763e819$export$25bec8c6f54ee79a(callback) { - const callbackRef = $92muK$react.useRef(callback); - $92muK$react.useEffect(() => { - callbackRef.current = callback; - }); // https://github.com/facebook/react/issues/19240 - return $92muK$react.useMemo( - () => - (...args) => { - var _callbackRef$current; - return (_callbackRef$current = callbackRef.current) === null || - _callbackRef$current === void 0 - ? void 0 - : _callbackRef$current.call(callbackRef, ...args); - }, - [] - ); - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js ***! - \**********************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $ijazI$react = __webpack_require__(/*! react */ "react"); - var $ijazI$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useControllableState", - () => $b84d42d44371bff7$export$6f32135080cb4c3 - ); - function $b84d42d44371bff7$export$6f32135080cb4c3({ - prop: prop, - defaultProp: defaultProp, - onChange = () => {}, - }) { - const [uncontrolledProp, setUncontrolledProp] = - $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange, - }); - const isControlled = prop !== undefined; - const value1 = isControlled ? prop : uncontrolledProp; - const handleChange = - $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - const setValue = $ijazI$react.useCallback( - (nextValue) => { - if (isControlled) { - const setter = nextValue; - const value = - typeof nextValue === "function" ? setter(prop) : nextValue; - if (value !== prop) handleChange(value); - } else setUncontrolledProp(nextValue); - }, - [isControlled, prop, setUncontrolledProp, handleChange] - ); - return [value1, setValue]; - } - function $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange, - }) { - const uncontrolledState = $ijazI$react.useState(defaultProp); - const [value] = uncontrolledState; - const prevValueRef = $ijazI$react.useRef(value); - const handleChange = - $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - $ijazI$react.useEffect(() => { - if (prevValueRef.current !== value) { - handleChange(value); - prevValueRef.current = value; - } - }, [value, prevValueRef, handleChange]); - return uncontrolledState; - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js ***! - \******************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $b0gz3$react = __webpack_require__(/*! react */ "react"); - var $b0gz3$radixuireactusecallbackref = __webpack_require__( - /*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useEscapeKeydown", - () => $24c84e9f83c4454f$export$3a72a57244d6e765 - ); - - /** - * Listens for when the escape key is down - */ - function $24c84e9f83c4454f$export$3a72a57244d6e765( - onEscapeKeyDownProp, - ownerDocument = globalThis === null || globalThis === void 0 - ? void 0 - : globalThis.document - ) { - const onEscapeKeyDown = - $b0gz3$radixuireactusecallbackref.useCallbackRef( - onEscapeKeyDownProp - ); - $b0gz3$react.useEffect(() => { - const handleKeyDown = (event) => { - if (event.key === "Escape") onEscapeKeyDown(event); - }; - ownerDocument.addEventListener("keydown", handleKeyDown); - return () => - ownerDocument.removeEventListener("keydown", handleKeyDown); - }, [onEscapeKeyDown, ownerDocument]); - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js ***! - \*****************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $caHyQ$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useLayoutEffect", - () => $ca21affb0542a8a4$export$e5c5a5f917a5871c - ); - - /** - * On the server, React emits a warning when calling `useLayoutEffect`. - * This is because neither `useLayoutEffect` nor `useEffect` run on the server. - * We use this safe version which suppresses the warning by replacing it with a noop on the server. - * - * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect - */ - const $ca21affb0542a8a4$export$e5c5a5f917a5871c = Boolean( - globalThis === null || globalThis === void 0 - ? void 0 - : globalThis.document - ) - ? $caHyQ$react.useLayoutEffect - : () => {}; - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-use-size/dist/index.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-size/dist/index.js ***! - \********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $ksDzM$react = __webpack_require__(/*! react */ "react"); - var $ksDzM$radixuireactuselayouteffect = __webpack_require__( - /*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - $parcel$export( - module.exports, - "useSize", - () => $d2c1d285af17635b$export$1ab7ae714698c4b8 - ); - function $d2c1d285af17635b$export$1ab7ae714698c4b8(element) { - const [size, setSize] = $ksDzM$react.useState(undefined); - $ksDzM$radixuireactuselayouteffect.useLayoutEffect(() => { - if (element) { - // provide size as early as possible - setSize({ - width: element.offsetWidth, - height: element.offsetHeight, - }); - const resizeObserver = new ResizeObserver((entries) => { - if (!Array.isArray(entries)) return; - // Since we only observe the one element, we don't need to loop over the - // array - if (!entries.length) return; - const entry = entries[0]; - let width; - let height; - if ("borderBoxSize" in entry) { - const borderSizeEntry = entry["borderBoxSize"]; // iron out differences between browsers - const borderSize = Array.isArray(borderSizeEntry) - ? borderSizeEntry[0] - : borderSizeEntry; - width = borderSize["inlineSize"]; - height = borderSize["blockSize"]; - } else { - // for browsers that don't support `borderBoxSize` - // we calculate it ourselves to get the correct border box. - width = element.offsetWidth; - height = element.offsetHeight; - } - setSize({ - width: width, - height: height, - }); - }); - resizeObserver.observe(element, { - box: "border-box", - }); - return () => resizeObserver.unobserve(element); - } - // We only want to reset to `undefined` when the element becomes `null`, - // not if it changes to another element. - else setSize(undefined); - }, [element]); - return size; - } - - /***/ - }, - - /***/ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js ***! - \***************************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var $awrN2$babelruntimehelpersextends = __webpack_require__( - /*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js" - ); - var $awrN2$react = __webpack_require__(/*! react */ "react"); - var $awrN2$radixuireactprimitive = __webpack_require__( - /*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js" - ); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true, - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export( - module.exports, - "VisuallyHidden", - () => $685371e9c20848e2$export$439d29a4e110a164 - ); - $parcel$export( - module.exports, - "Root", - () => $685371e9c20848e2$export$be92b6f5f03c0fe9 - ); - - /* ------------------------------------------------------------------------------------------------- - * VisuallyHidden - * -----------------------------------------------------------------------------------------------*/ - const $685371e9c20848e2$var$NAME = "VisuallyHidden"; - const $685371e9c20848e2$export$439d29a4e110a164 = - /*#__PURE__*/ $awrN2$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/ $awrN2$react.createElement( - $awrN2$radixuireactprimitive.Primitive.span, - $parcel$interopDefault($awrN2$babelruntimehelpersextends)( - {}, - props, - { - ref: forwardedRef, - style: { - // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss - position: "absolute", - border: 0, - width: 1, - height: 1, - padding: 0, - margin: -1, - overflow: "hidden", - clip: "rect(0, 0, 0, 0)", - whiteSpace: "nowrap", - wordWrap: "normal", - ...props.style, - }, - } - ) - ); - }); - /*#__PURE__*/ - Object.assign($685371e9c20848e2$export$439d29a4e110a164, { - displayName: $685371e9c20848e2$var$NAME, - }); - /* -----------------------------------------------------------------------------------------------*/ - const $685371e9c20848e2$export$be92b6f5f03c0fe9 = - $685371e9c20848e2$export$439d29a4e110a164; - - /***/ - }, - - /***/ "../../../node_modules/aria-hidden/dist/es2015/index.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/aria-hidden/dist/es2015/index.js ***! - \**************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.suppressOthers = - exports.supportsInert = - exports.inertOthers = - exports.hideOthers = - void 0; - var getDefaultParent = function (originalTarget) { - if (typeof document === "undefined") { - return null; - } - var sampleTarget = Array.isArray(originalTarget) - ? originalTarget[0] - : originalTarget; - return sampleTarget.ownerDocument.body; - }; - var counterMap = new WeakMap(); - var uncontrolledNodes = new WeakMap(); - var markerMap = {}; - var lockCount = 0; - var unwrapHost = function (node) { - return node && (node.host || unwrapHost(node.parentNode)); - }; - var correctTargets = function (parent, targets) { - return targets - .map(function (target) { - if (parent.contains(target)) { - return target; - } - var correctedTarget = unwrapHost(target); - if (correctedTarget && parent.contains(correctedTarget)) { - return correctedTarget; - } - console.error( - "aria-hidden", - target, - "in not contained inside", - parent, - ". Doing nothing" - ); - return null; - }) - .filter(function (x) { - return Boolean(x); - }); - }; - /** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @param {String} [controlAttribute] - html Attribute to control - * @return {Undo} undo command - */ - var applyAttributeToOthers = function ( - originalTarget, - parentNode, - markerName, - controlAttribute - ) { - var targets = correctTargets( - parentNode, - Array.isArray(originalTarget) ? originalTarget : [originalTarget] - ); - if (!markerMap[markerName]) { - markerMap[markerName] = new WeakMap(); - } - var markerCounter = markerMap[markerName]; - var hiddenNodes = []; - var elementsToKeep = new Set(); - var elementsToStop = new Set(targets); - var keep = function (el) { - if (!el || elementsToKeep.has(el)) { - return; - } - elementsToKeep.add(el); - keep(el.parentNode); - }; - targets.forEach(keep); - var deep = function (parent) { - if (!parent || elementsToStop.has(parent)) { - return; - } - Array.prototype.forEach.call(parent.children, function (node) { - if (elementsToKeep.has(node)) { - deep(node); - } else { - var attr = node.getAttribute(controlAttribute); - var alreadyHidden = attr !== null && attr !== "false"; - var counterValue = (counterMap.get(node) || 0) + 1; - var markerValue = (markerCounter.get(node) || 0) + 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - hiddenNodes.push(node); - if (counterValue === 1 && alreadyHidden) { - uncontrolledNodes.set(node, true); - } - if (markerValue === 1) { - node.setAttribute(markerName, "true"); - } - if (!alreadyHidden) { - node.setAttribute(controlAttribute, "true"); - } - } - }); - }; - deep(parentNode); - elementsToKeep.clear(); - lockCount++; - return function () { - hiddenNodes.forEach(function (node) { - var counterValue = counterMap.get(node) - 1; - var markerValue = markerCounter.get(node) - 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - if (!counterValue) { - if (!uncontrolledNodes.has(node)) { - node.removeAttribute(controlAttribute); - } - uncontrolledNodes.delete(node); - } - if (!markerValue) { - node.removeAttribute(markerName); - } - }); - lockCount--; - if (!lockCount) { - // clear - counterMap = new WeakMap(); - counterMap = new WeakMap(); - uncontrolledNodes = new WeakMap(); - markerMap = {}; - } - }; - }; - /** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ - var hideOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = "data-aria-hidden"; - } - var targets = Array.from( - Array.isArray(originalTarget) ? originalTarget : [originalTarget] - ); - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - // we should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10 - targets.push.apply( - targets, - Array.from(activeParentNode.querySelectorAll("[aria-live]")) - ); - return applyAttributeToOthers( - targets, - activeParentNode, - markerName, - "aria-hidden" - ); - }; - /** - * Marks everything except given node(or nodes) as inert - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ - exports.hideOthers = hideOthers; - var inertOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = "data-inert-ed"; - } - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - return applyAttributeToOthers( - originalTarget, - activeParentNode, - markerName, - "inert" - ); - }; - /** - * @returns if current browser supports inert - */ - exports.inertOthers = inertOthers; - var supportsInert = function () { - return ( - typeof HTMLElement !== "undefined" && - HTMLElement.prototype.hasOwnProperty("inert") - ); - }; - /** - * Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command - */ - exports.supportsInert = supportsInert; - var suppressOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = "data-suppressed"; - } - return (supportsInert() ? inertOthers : hideOthers)( - originalTarget, - parentNode, - markerName - ); - }; - exports.suppressOthers = suppressOthers; - - /***/ - }, - - /***/ "../../../node_modules/clsx/dist/clsx.m.js": - /*!*************************************************!*\ - !*** ../../../node_modules/clsx/dist/clsx.m.js ***! - \*************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.clsx = clsx; - exports["default"] = void 0; - function r(e) { - var t, - f, - n = ""; - if ("string" == typeof e || "number" == typeof e) n += e; - else if ("object" == typeof e) - if (Array.isArray(e)) - for (t = 0; t < e.length; t++) - e[t] && (f = r(e[t])) && (n && (n += " "), (n += f)); - else for (t in e) e[t] && (n && (n += " "), (n += t)); - return n; - } - function clsx() { - for (var e, t, f = 0, n = ""; f < arguments.length; ) - (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), (n += t)); - return n; - } - var _default = (exports["default"] = clsx); - - /***/ - }, - - /***/ "../../../node_modules/copy-to-clipboard/index.js": - /*!********************************************************!*\ - !*** ../../../node_modules/copy-to-clipboard/index.js ***! - \********************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var deselectCurrent = __webpack_require__( - /*! toggle-selection */ "../../../node_modules/toggle-selection/index.js" - ); - var clipboardToIE11Formatting = { - "text/plain": "Text", - "text/html": "Url", - default: "Text", - }; - var defaultMessage = "Copy to clipboard: #{key}, Enter"; - function format(message) { - var copyKey = - (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; - return message.replace(/#{\s*key\s*}/g, copyKey); - } - function copy(text, options) { - var debug, - message, - reselectPrevious, - range, - selection, - mark, - success = false; - if (!options) { - options = {}; - } - debug = options.debug || false; - try { - reselectPrevious = deselectCurrent(); - range = document.createRange(); - selection = document.getSelection(); - mark = document.createElement("span"); - mark.textContent = text; - // avoid screen readers from reading out loud the text - mark.ariaHidden = "true"; - // reset user styles for span element - mark.style.all = "unset"; - // prevents scrolling to the end of the page - mark.style.position = "fixed"; - mark.style.top = 0; - mark.style.clip = "rect(0, 0, 0, 0)"; - // used to preserve spaces and line breaks - mark.style.whiteSpace = "pre"; - // do not inherit user-select (it may be `none`) - mark.style.webkitUserSelect = "text"; - mark.style.MozUserSelect = "text"; - mark.style.msUserSelect = "text"; - mark.style.userSelect = "text"; - mark.addEventListener("copy", function (e) { - e.stopPropagation(); - if (options.format) { - e.preventDefault(); - if (typeof e.clipboardData === "undefined") { - // IE 11 - debug && console.warn("unable to use e.clipboardData"); - debug && console.warn("trying IE specific stuff"); - window.clipboardData.clearData(); - var format = - clipboardToIE11Formatting[options.format] || - clipboardToIE11Formatting["default"]; - window.clipboardData.setData(format, text); - } else { - // all other browsers - e.clipboardData.clearData(); - e.clipboardData.setData(options.format, text); - } - } - if (options.onCopy) { - e.preventDefault(); - options.onCopy(e.clipboardData); - } - }); - document.body.appendChild(mark); - range.selectNodeContents(mark); - selection.addRange(range); - var successful = document.execCommand("copy"); - if (!successful) { - throw new Error("copy command was unsuccessful"); - } - success = true; - } catch (err) { - debug && console.error("unable to copy using execCommand: ", err); - debug && console.warn("trying IE specific stuff"); - try { - window.clipboardData.setData(options.format || "text", text); - options.onCopy && options.onCopy(window.clipboardData); - success = true; - } catch (err) { - debug && - console.error("unable to copy using clipboardData: ", err); - debug && console.error("falling back to prompt"); - message = format( - "message" in options ? options.message : defaultMessage - ); - window.prompt(message, text); - } - } finally { - if (selection) { - if (typeof selection.removeRange == "function") { - selection.removeRange(range); - } else { - selection.removeAllRanges(); - } - } - if (mark) { - document.body.removeChild(mark); - } - reselectPrevious(); - } - return success; - } - module.exports = copy; - - /***/ - }, - - /***/ "../../../node_modules/detect-node-es/esm/browser.js": - /*!***********************************************************!*\ - !*** ../../../node_modules/detect-node-es/esm/browser.js ***! - \***********************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isNode = void 0; - const isNode = (exports.isNode = false); - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/decode.js": - /*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/decode.js ***! - \****************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - var __createBinding = - (void 0 && (void 0).__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if ( - !desc || - ("get" in desc - ? !m.__esModule - : desc.writable || desc.configurable) - ) { - desc = { - enumerable: true, - get: function () { - return m[k]; - }, - }; - } - Object.defineProperty(o, k2, desc); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - var __setModuleDefault = - (void 0 && (void 0).__setModuleDefault) || - (Object.create - ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v, - }); - } - : function (o, v) { - o["default"] = v; - }); - var __importStar = - (void 0 && (void 0).__importStar) || - function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) - for (var k in mod) - if ( - k !== "default" && - Object.prototype.hasOwnProperty.call(mod, k) - ) - __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - var __importDefault = - (void 0 && (void 0).__importDefault) || - function (mod) { - return mod && mod.__esModule - ? mod - : { - default: mod, - }; - }; - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.decodeXML = - exports.decodeHTMLStrict = - exports.decodeHTMLAttribute = - exports.decodeHTML = - exports.determineBranch = - exports.EntityDecoder = - exports.DecodingMode = - exports.BinTrieFlags = - exports.fromCodePoint = - exports.replaceCodePoint = - exports.decodeCodePoint = - exports.xmlDecodeTree = - exports.htmlDecodeTree = - void 0; - var decode_data_html_js_1 = __importDefault( - __webpack_require__( - /*! ./generated/decode-data-html.js */ "../../../node_modules/entities/lib/generated/decode-data-html.js" - ) - ); - exports.htmlDecodeTree = decode_data_html_js_1.default; - var decode_data_xml_js_1 = __importDefault( - __webpack_require__( - /*! ./generated/decode-data-xml.js */ "../../../node_modules/entities/lib/generated/decode-data-xml.js" - ) - ); - exports.xmlDecodeTree = decode_data_xml_js_1.default; - var decode_codepoint_js_1 = __importStar( - __webpack_require__( - /*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js" - ) - ); - exports.decodeCodePoint = decode_codepoint_js_1.default; - var decode_codepoint_js_2 = __webpack_require__( - /*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js" - ); - Object.defineProperty(exports, "replaceCodePoint", { - enumerable: true, - get: function () { - return decode_codepoint_js_2.replaceCodePoint; - }, - }); - Object.defineProperty(exports, "fromCodePoint", { - enumerable: true, - get: function () { - return decode_codepoint_js_2.fromCodePoint; - }, - }); - var CharCodes; - (function (CharCodes) { - CharCodes[(CharCodes["NUM"] = 35)] = "NUM"; - CharCodes[(CharCodes["SEMI"] = 59)] = "SEMI"; - CharCodes[(CharCodes["EQUALS"] = 61)] = "EQUALS"; - CharCodes[(CharCodes["ZERO"] = 48)] = "ZERO"; - CharCodes[(CharCodes["NINE"] = 57)] = "NINE"; - CharCodes[(CharCodes["LOWER_A"] = 97)] = "LOWER_A"; - CharCodes[(CharCodes["LOWER_F"] = 102)] = "LOWER_F"; - CharCodes[(CharCodes["LOWER_X"] = 120)] = "LOWER_X"; - CharCodes[(CharCodes["LOWER_Z"] = 122)] = "LOWER_Z"; - CharCodes[(CharCodes["UPPER_A"] = 65)] = "UPPER_A"; - CharCodes[(CharCodes["UPPER_F"] = 70)] = "UPPER_F"; - CharCodes[(CharCodes["UPPER_Z"] = 90)] = "UPPER_Z"; - })(CharCodes || (CharCodes = {})); - /** Bit that needs to be set to convert an upper case ASCII character to lower case */ - var TO_LOWER_BIT = 32; - var BinTrieFlags; - (function (BinTrieFlags) { - BinTrieFlags[(BinTrieFlags["VALUE_LENGTH"] = 49152)] = "VALUE_LENGTH"; - BinTrieFlags[(BinTrieFlags["BRANCH_LENGTH"] = 16256)] = - "BRANCH_LENGTH"; - BinTrieFlags[(BinTrieFlags["JUMP_TABLE"] = 127)] = "JUMP_TABLE"; - })( - (BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {})) - ); - function isNumber(code) { - return code >= CharCodes.ZERO && code <= CharCodes.NINE; - } - function isHexadecimalCharacter(code) { - return ( - (code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || - (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F) - ); - } - function isAsciiAlphaNumeric(code) { - return ( - (code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || - (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || - isNumber(code) - ); - } - /** - * Checks if the given character is a valid end character for an entity in an attribute. - * - * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. - * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state - */ - function isEntityInAttributeInvalidEnd(code) { - return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); - } - var EntityDecoderState; - (function (EntityDecoderState) { - EntityDecoderState[(EntityDecoderState["EntityStart"] = 0)] = - "EntityStart"; - EntityDecoderState[(EntityDecoderState["NumericStart"] = 1)] = - "NumericStart"; - EntityDecoderState[(EntityDecoderState["NumericDecimal"] = 2)] = - "NumericDecimal"; - EntityDecoderState[(EntityDecoderState["NumericHex"] = 3)] = - "NumericHex"; - EntityDecoderState[(EntityDecoderState["NamedEntity"] = 4)] = - "NamedEntity"; - })(EntityDecoderState || (EntityDecoderState = {})); - var DecodingMode; - (function (DecodingMode) { - /** Entities in text nodes that can end with any character. */ - DecodingMode[(DecodingMode["Legacy"] = 0)] = "Legacy"; - /** Only allow entities terminated with a semicolon. */ - DecodingMode[(DecodingMode["Strict"] = 1)] = "Strict"; - /** Entities in attributes have limitations on ending characters. */ - DecodingMode[(DecodingMode["Attribute"] = 2)] = "Attribute"; - })( - (DecodingMode = exports.DecodingMode || (exports.DecodingMode = {})) - ); - /** - * Token decoder with support of writing partial entities. - */ - var EntityDecoder = /** @class */ (function () { - function EntityDecoder /** The tree used to decode entities. */( - decodeTree, - /** - * The function that is called when a codepoint is decoded. - * - * For multi-byte named entities, this will be called multiple times, - * with the second codepoint, and the same `consumed` value. - * - * @param codepoint The decoded codepoint. - * @param consumed The number of bytes consumed by the decoder. - */ - emitCodePoint /** An object that is used to produce errors. */, - errors - ) { - this.decodeTree = decodeTree; - this.emitCodePoint = emitCodePoint; - this.errors = errors; - /** The current state of the decoder. */ - this.state = EntityDecoderState.EntityStart; - /** Characters that were consumed while parsing an entity. */ - this.consumed = 1; - /** - * The result of the entity. - * - * Either the result index of a numeric entity, or the codepoint of a - * numeric entity. - */ - this.result = 0; - /** The current index in the decode tree. */ - this.treeIndex = 0; - /** The number of characters that were consumed in excess. */ - this.excess = 1; - /** The mode in which the decoder is operating. */ - this.decodeMode = DecodingMode.Strict; - } - /** Resets the instance to make it reusable. */ - EntityDecoder.prototype.startEntity = function (decodeMode) { - this.decodeMode = decodeMode; - this.state = EntityDecoderState.EntityStart; - this.result = 0; - this.treeIndex = 0; - this.excess = 1; - this.consumed = 1; - }; - /** - * Write an entity to the decoder. This can be called multiple times with partial entities. - * If the entity is incomplete, the decoder will return -1. - * - * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the - * entity is incomplete, and resume when the next string is written. - * - * @param string The string containing the entity (or a continuation of the entity). - * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.write = function (str, offset) { - switch (this.state) { - case EntityDecoderState.EntityStart: { - if (str.charCodeAt(offset) === CharCodes.NUM) { - this.state = EntityDecoderState.NumericStart; - this.consumed += 1; - return this.stateNumericStart(str, offset + 1); - } - this.state = EntityDecoderState.NamedEntity; - return this.stateNamedEntity(str, offset); - } - case EntityDecoderState.NumericStart: { - return this.stateNumericStart(str, offset); - } - case EntityDecoderState.NumericDecimal: { - return this.stateNumericDecimal(str, offset); - } - case EntityDecoderState.NumericHex: { - return this.stateNumericHex(str, offset); - } - case EntityDecoderState.NamedEntity: { - return this.stateNamedEntity(str, offset); - } - } - }; - /** - * Switches between the numeric decimal and hexadecimal states. - * - * Equivalent to the `Numeric character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericStart = function (str, offset) { - if (offset >= str.length) { - return -1; - } - if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { - this.state = EntityDecoderState.NumericHex; - this.consumed += 1; - return this.stateNumericHex(str, offset + 1); - } - this.state = EntityDecoderState.NumericDecimal; - return this.stateNumericDecimal(str, offset); - }; - EntityDecoder.prototype.addToNumericResult = function ( - str, - start, - end, - base - ) { - if (start !== end) { - var digitCount = end - start; - this.result = - this.result * Math.pow(base, digitCount) + - parseInt(str.substr(start, digitCount), base); - this.consumed += digitCount; - } - }; - /** - * Parses a hexadecimal numeric entity. - * - * Equivalent to the `Hexademical character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericHex = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char) || isHexadecimalCharacter(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 16); - return this.emitNumericEntity(char, 3); - } - } - this.addToNumericResult(str, startIdx, offset, 16); - return -1; - }; - /** - * Parses a decimal numeric entity. - * - * Equivalent to the `Decimal character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericDecimal = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 10); - return this.emitNumericEntity(char, 2); - } - } - this.addToNumericResult(str, startIdx, offset, 10); - return -1; - }; - /** - * Validate and emit a numeric entity. - * - * Implements the logic from the `Hexademical character reference start - * state` and `Numeric character reference end state` in the HTML spec. - * - * @param lastCp The last code point of the entity. Used to see if the - * entity was terminated with a semicolon. - * @param expectedLength The minimum number of characters that should be - * consumed. Used to validate that at least one digit - * was consumed. - * @returns The number of characters that were consumed. - */ - EntityDecoder.prototype.emitNumericEntity = function ( - lastCp, - expectedLength - ) { - var _a; - // Ensure we consumed at least one digit. - if (this.consumed <= expectedLength) { - (_a = this.errors) === null || _a === void 0 - ? void 0 - : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - // Figure out if this is a legit end of the entity - if (lastCp === CharCodes.SEMI) { - this.consumed += 1; - } else if (this.decodeMode === DecodingMode.Strict) { - return 0; - } - this.emitCodePoint( - (0, decode_codepoint_js_1.replaceCodePoint)(this.result), - this.consumed - ); - if (this.errors) { - if (lastCp !== CharCodes.SEMI) { - this.errors.missingSemicolonAfterCharacterReference(); - } - this.errors.validateNumericCharacterReference(this.result); - } - return this.consumed; - }; - /** - * Parses a named entity. - * - * Equivalent to the `Named character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNamedEntity = function (str, offset) { - var decodeTree = this.decodeTree; - var current = decodeTree[this.treeIndex]; - // The mask is the number of bytes of the value, including the current byte. - var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - for (; offset < str.length; offset++, this.excess++) { - var char = str.charCodeAt(offset); - this.treeIndex = determineBranch( - decodeTree, - current, - this.treeIndex + Math.max(1, valueLength), - char - ); - if (this.treeIndex < 0) { - return this.result === 0 || - // If we are parsing an attribute - (this.decodeMode === DecodingMode.Attribute && - // We shouldn't have consumed any characters after the entity, - (valueLength === 0 || - // And there should be no invalid characters. - isEntityInAttributeInvalidEnd(char))) - ? 0 - : this.emitNotTerminatedNamedEntity(); - } - current = decodeTree[this.treeIndex]; - valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - // If the branch is a value, store it and continue - if (valueLength !== 0) { - // If the entity is terminated by a semicolon, we are done. - if (char === CharCodes.SEMI) { - return this.emitNamedEntityData( - this.treeIndex, - valueLength, - this.consumed + this.excess - ); - } - // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. - if (this.decodeMode !== DecodingMode.Strict) { - this.result = this.treeIndex; - this.consumed += this.excess; - this.excess = 0; - } - } - } - return -1; - }; - /** - * Emit a named entity that was not terminated with a semicolon. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.emitNotTerminatedNamedEntity = function () { - var _a; - var _b = this, - result = _b.result, - decodeTree = _b.decodeTree; - var valueLength = - (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; - this.emitNamedEntityData(result, valueLength, this.consumed); - (_a = this.errors) === null || _a === void 0 - ? void 0 - : _a.missingSemicolonAfterCharacterReference(); - return this.consumed; - }; - /** - * Emit a named entity. - * - * @param result The index of the entity in the decode tree. - * @param valueLength The number of bytes in the entity. - * @param consumed The number of characters consumed. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.emitNamedEntityData = function ( - result, - valueLength, - consumed - ) { - var decodeTree = this.decodeTree; - this.emitCodePoint( - valueLength === 1 - ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH - : decodeTree[result + 1], - consumed - ); - if (valueLength === 3) { - // For multi-byte values, we need to emit the second byte. - this.emitCodePoint(decodeTree[result + 2], consumed); - } - return consumed; - }; - /** - * Signal to the parser that the end of the input was reached. - * - * Remaining data will be emitted and relevant errors will be produced. - * - * @returns The number of characters consumed. - */ - EntityDecoder.prototype.end = function () { - var _a; - switch (this.state) { - case EntityDecoderState.NamedEntity: { - // Emit a named entity if we have one. - return this.result !== 0 && - (this.decodeMode !== DecodingMode.Attribute || - this.result === this.treeIndex) - ? this.emitNotTerminatedNamedEntity() - : 0; - } - // Otherwise, emit a numeric entity if we have one. - case EntityDecoderState.NumericDecimal: { - return this.emitNumericEntity(0, 2); - } - case EntityDecoderState.NumericHex: { - return this.emitNumericEntity(0, 3); - } - case EntityDecoderState.NumericStart: { - (_a = this.errors) === null || _a === void 0 - ? void 0 - : _a.absenceOfDigitsInNumericCharacterReference( - this.consumed - ); - return 0; - } - case EntityDecoderState.EntityStart: { - // Return 0 if we have no entity. - return 0; - } - } - }; - return EntityDecoder; - })(); - exports.EntityDecoder = EntityDecoder; - /** - * Creates a function that decodes entities in a string. - * - * @param decodeTree The decode tree. - * @returns A function that decodes entities in a string. - */ - function getDecoder(decodeTree) { - var ret = ""; - var decoder = new EntityDecoder(decodeTree, function (str) { - return (ret += (0, decode_codepoint_js_1.fromCodePoint)(str)); - }); - return function decodeWithTrie(str, decodeMode) { - var lastIndex = 0; - var offset = 0; - while ((offset = str.indexOf("&", offset)) >= 0) { - ret += str.slice(lastIndex, offset); - decoder.startEntity(decodeMode); - var len = decoder.write( - str, - // Skip the "&" - offset + 1 - ); - if (len < 0) { - lastIndex = offset + decoder.end(); - break; - } - lastIndex = offset + len; - // If `len` is 0, skip the current `&` and continue. - offset = len === 0 ? lastIndex + 1 : lastIndex; - } - var result = ret + str.slice(lastIndex); - // Make sure we don't keep a reference to the final string. - ret = ""; - return result; - }; - } - /** - * Determines the branch of the current node that is taken given the current - * character. This function is used to traverse the trie. - * - * @param decodeTree The trie. - * @param current The current node. - * @param nodeIdx The index right after the current node and its value. - * @param char The current character. - * @returns The index of the next node, or -1 if no branch is taken. - */ - function determineBranch(decodeTree, current, nodeIdx, char) { - var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; - var jumpOffset = current & BinTrieFlags.JUMP_TABLE; - // Case 1: Single branch encoded in jump offset - if (branchCount === 0) { - return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; - } - // Case 2: Multiple branches encoded in jump table - if (jumpOffset) { - var value = char - jumpOffset; - return value < 0 || value >= branchCount - ? -1 - : decodeTree[nodeIdx + value] - 1; - } - // Case 3: Multiple branches encoded in dictionary - // Binary search for the character. - var lo = nodeIdx; - var hi = lo + branchCount - 1; - while (lo <= hi) { - var mid = (lo + hi) >>> 1; - var midVal = decodeTree[mid]; - if (midVal < char) { - lo = mid + 1; - } else if (midVal > char) { - hi = mid - 1; - } else { - return decodeTree[mid + branchCount]; - } - } - return -1; - } - exports.determineBranch = determineBranch; - var htmlDecoder = getDecoder(decode_data_html_js_1.default); - var xmlDecoder = getDecoder(decode_data_xml_js_1.default); - /** - * Decodes an HTML string. - * - * @param str The string to decode. - * @param mode The decoding mode. - * @returns The decoded string. - */ - function decodeHTML(str, mode) { - if (mode === void 0) { - mode = DecodingMode.Legacy; - } - return htmlDecoder(str, mode); - } - exports.decodeHTML = decodeHTML; - /** - * Decodes an HTML string in an attribute. - * - * @param str The string to decode. - * @returns The decoded string. - */ - function decodeHTMLAttribute(str) { - return htmlDecoder(str, DecodingMode.Attribute); - } - exports.decodeHTMLAttribute = decodeHTMLAttribute; - /** - * Decodes an HTML string, requiring all entities to be terminated by a semicolon. - * - * @param str The string to decode. - * @returns The decoded string. - */ - function decodeHTMLStrict(str) { - return htmlDecoder(str, DecodingMode.Strict); - } - exports.decodeHTMLStrict = decodeHTMLStrict; - /** - * Decodes an XML string, requiring all entities to be terminated by a semicolon. - * - * @param str The string to decode. - * @returns The decoded string. - */ - function decodeXML(str) { - return xmlDecoder(str, DecodingMode.Strict); - } - exports.decodeXML = decodeXML; - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/decode_codepoint.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/entities/lib/decode_codepoint.js ***! - \**************************************************************/ - /***/ function (__unused_webpack_module, exports) { - // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 - var _a; - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.replaceCodePoint = exports.fromCodePoint = void 0; - var decodeMap = new Map([ - [0, 65533], - // C1 Unicode control character reference replacements - [128, 8364], - [130, 8218], - [131, 402], - [132, 8222], - [133, 8230], - [134, 8224], - [135, 8225], - [136, 710], - [137, 8240], - [138, 352], - [139, 8249], - [140, 338], - [142, 381], - [145, 8216], - [146, 8217], - [147, 8220], - [148, 8221], - [149, 8226], - [150, 8211], - [151, 8212], - [152, 732], - [153, 8482], - [154, 353], - [155, 8250], - [156, 339], - [158, 382], - [159, 376], - ]); - /** - * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. - */ - exports.fromCodePoint = - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins - (_a = String.fromCodePoint) !== null && _a !== void 0 - ? _a - : function (codePoint) { - var output = ""; - if (codePoint > 0xffff) { - codePoint -= 0x10000; - output += String.fromCharCode( - ((codePoint >>> 10) & 0x3ff) | 0xd800 - ); - codePoint = 0xdc00 | (codePoint & 0x3ff); - } - output += String.fromCharCode(codePoint); - return output; - }; - /** - * Replace the given code point with a replacement character if it is a - * surrogate or is outside the valid range. Otherwise return the code - * point unchanged. - */ - function replaceCodePoint(codePoint) { - var _a; - if ( - (codePoint >= 0xd800 && codePoint <= 0xdfff) || - codePoint > 0x10ffff - ) { - return 0xfffd; - } - return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 - ? _a - : codePoint; - } - exports.replaceCodePoint = replaceCodePoint; - /** - * Replace the code point if relevant, then convert it to a string. - * - * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. - * @param codePoint The code point to decode. - * @returns The decoded code point. - */ - function decodeCodePoint(codePoint) { - return (0, exports.fromCodePoint)(replaceCodePoint(codePoint)); - } - exports["default"] = decodeCodePoint; - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/encode.js": - /*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/encode.js ***! - \****************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - var __importDefault = - (void 0 && (void 0).__importDefault) || - function (mod) { - return mod && mod.__esModule - ? mod - : { - default: mod, - }; - }; - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.encodeNonAsciiHTML = exports.encodeHTML = void 0; - var encode_html_js_1 = __importDefault( - __webpack_require__( - /*! ./generated/encode-html.js */ "../../../node_modules/entities/lib/generated/encode-html.js" - ) - ); - var escape_js_1 = __webpack_require__( - /*! ./escape.js */ "../../../node_modules/entities/lib/escape.js" - ); - var htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g; - /** - * Encodes all characters in the input using HTML entities. This includes - * characters that are valid ASCII characters in HTML documents, such as `#`. - * - * To get a more compact output, consider using the `encodeNonAsciiHTML` - * function, which will only encode characters that are not valid in HTML - * documents, as well as non-ASCII characters. - * - * If a character has no equivalent entity, a numeric hexadecimal reference - * (eg. `ü`) will be used. - */ - function encodeHTML(data) { - return encodeHTMLTrieRe(htmlReplacer, data); - } - exports.encodeHTML = encodeHTML; - /** - * Encodes all non-ASCII characters, as well as characters not valid in HTML - * documents using HTML entities. This function will not encode characters that - * are valid in HTML documents, such as `#`. - * - * If a character has no equivalent entity, a numeric hexadecimal reference - * (eg. `ü`) will be used. - */ - function encodeNonAsciiHTML(data) { - return encodeHTMLTrieRe(escape_js_1.xmlReplacer, data); - } - exports.encodeNonAsciiHTML = encodeNonAsciiHTML; - function encodeHTMLTrieRe(regExp, str) { - var ret = ""; - var lastIdx = 0; - var match; - while ((match = regExp.exec(str)) !== null) { - var i = match.index; - ret += str.substring(lastIdx, i); - var char = str.charCodeAt(i); - var next = encode_html_js_1.default.get(char); - if (typeof next === "object") { - // We are in a branch. Try to match the next char. - if (i + 1 < str.length) { - var nextChar = str.charCodeAt(i + 1); - var value = - typeof next.n === "number" - ? next.n === nextChar - ? next.o - : undefined - : next.n.get(nextChar); - if (value !== undefined) { - ret += value; - lastIdx = regExp.lastIndex += 1; - continue; - } - } - next = next.v; - } - // We might have a tree node without a value; skip and use a numeric entity. - if (next !== undefined) { - ret += next; - lastIdx = i + 1; - } else { - var cp = (0, escape_js_1.getCodePoint)(str, i); - ret += "&#x".concat(cp.toString(16), ";"); - // Increase by 1 if we have a surrogate pair - lastIdx = regExp.lastIndex += Number(cp !== char); - } - } - return ret + str.substr(lastIdx); - } - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/escape.js": - /*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/escape.js ***! - \****************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.escapeText = - exports.escapeAttribute = - exports.escapeUTF8 = - exports.escape = - exports.encodeXML = - exports.getCodePoint = - exports.xmlReplacer = - void 0; - exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g; - var xmlCodeMap = new Map([ - [34, """], - [38, "&"], - [39, "'"], - [60, "<"], - [62, ">"], - ]); - // For compatibility with node < 4, we wrap `codePointAt` - exports.getCodePoint = - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - String.prototype.codePointAt != null - ? function (str, index) { - return str.codePointAt(index); - } - : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - function (c, index) { - return (c.charCodeAt(index) & 0xfc00) === 0xd800 - ? (c.charCodeAt(index) - 0xd800) * 0x400 + - c.charCodeAt(index + 1) - - 0xdc00 + - 0x10000 - : c.charCodeAt(index); - }; - /** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using XML entities. - * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. - */ - function encodeXML(str) { - var ret = ""; - var lastIdx = 0; - var match; - while ((match = exports.xmlReplacer.exec(str)) !== null) { - var i = match.index; - var char = str.charCodeAt(i); - var next = xmlCodeMap.get(char); - if (next !== undefined) { - ret += str.substring(lastIdx, i) + next; - lastIdx = i + 1; - } else { - ret += "" - .concat(str.substring(lastIdx, i), "&#x") - .concat((0, exports.getCodePoint)(str, i).toString(16), ";"); - // Increase by 1 if we have a surrogate pair - lastIdx = exports.xmlReplacer.lastIndex += Number( - (char & 0xfc00) === 0xd800 - ); - } - } - return ret + str.substr(lastIdx); - } - exports.encodeXML = encodeXML; - /** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using numeric hexadecimal reference (eg. `ü`). - * - * Have a look at `escapeUTF8` if you want a more concise output at the expense - * of reduced transportability. - * - * @param data String to escape. - */ - exports.escape = encodeXML; - /** - * Creates a function that escapes all characters matched by the given regular - * expression using the given map of characters to escape to their entities. - * - * @param regex Regular expression to match characters to escape. - * @param map Map of characters to escape to their entities. - * - * @returns Function that escapes all characters matched by the given regular - * expression using the given map of characters to escape to their entities. - */ - function getEscaper(regex, map) { - return function escape(data) { - var match; - var lastIdx = 0; - var result = ""; - while ((match = regex.exec(data))) { - if (lastIdx !== match.index) { - result += data.substring(lastIdx, match.index); - } - // We know that this character will be in the map. - result += map.get(match[0].charCodeAt(0)); - // Every match will be of length 1 - lastIdx = match.index + 1; - } - return result + data.substring(lastIdx); - }; - } - /** - * Encodes all characters not valid in XML documents using XML entities. - * - * Note that the output will be character-set dependent. - * - * @param data String to escape. - */ - exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap); - /** - * Encodes all characters that have to be escaped in HTML attributes, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - * - * @param data String to escape. - */ - exports.escapeAttribute = getEscaper( - /["&\u00A0]/g, - new Map([ - [34, """], - [38, "&"], - [160, " "], - ]) - ); - /** - * Encodes all characters that have to be escaped in HTML text, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - * - * @param data String to escape. - */ - exports.escapeText = getEscaper( - /[&<>\u00A0]/g, - new Map([ - [38, "&"], - [60, "<"], - [62, ">"], - [160, " "], - ]) - ); - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/generated/decode-data-html.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/decode-data-html.js ***! - \************************************************************************/ - /***/ function (__unused_webpack_module, exports) { - // Generated using scripts/write-decode-map.ts - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports["default"] = new Uint16Array( - // prettier-ignore - "\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c".split("").map(function (c) { - return c.charCodeAt(0); -}) - ); - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/generated/decode-data-xml.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/decode-data-xml.js ***! - \***********************************************************************/ - /***/ function (__unused_webpack_module, exports) { - // Generated using scripts/write-decode-map.ts - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports["default"] = new Uint16Array( - // prettier-ignore - "\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022".split("").map(function (c) { - return c.charCodeAt(0); -}) - ); - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/generated/encode-html.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/entities/lib/generated/encode-html.js ***! - \*******************************************************************/ - /***/ function (__unused_webpack_module, exports) { - // Generated using scripts/write-encode-map.ts - Object.defineProperty(exports, "__esModule", { - value: true, - }); - function restoreDiff(arr) { - for (var i = 1; i < arr.length; i++) { - arr[i][0] += arr[i - 1][0] + 1; - } - return arr; - } - // prettier-ignore - exports["default"] = new Map( /* #__PURE__ */restoreDiff([[9, " "], [0, " "], [22, "!"], [0, """], [0, "#"], [0, "$"], [0, "%"], [0, "&"], [0, "'"], [0, "("], [0, ")"], [0, "*"], [0, "+"], [0, ","], [1, "."], [0, "/"], [10, ":"], [0, ";"], [0, { - v: "<", - n: 8402, - o: "<⃒" -}], [0, { - v: "=", - n: 8421, - o: "=⃥" -}], [0, { - v: ">", - n: 8402, - o: ">⃒" -}], [0, "?"], [0, "@"], [26, "["], [0, "\"], [0, "]"], [0, "^"], [0, "_"], [0, "`"], [5, { - n: 106, - o: "fj" -}], [20, "{"], [0, "|"], [0, "}"], [34, " "], [0, "¡"], [0, "¢"], [0, "£"], [0, "¤"], [0, "¥"], [0, "¦"], [0, "§"], [0, "¨"], [0, "©"], [0, "ª"], [0, "«"], [0, "¬"], [0, "­"], [0, "®"], [0, "¯"], [0, "°"], [0, "±"], [0, "²"], [0, "³"], [0, "´"], [0, "µ"], [0, "¶"], [0, "·"], [0, "¸"], [0, "¹"], [0, "º"], [0, "»"], [0, "¼"], [0, "½"], [0, "¾"], [0, "¿"], [0, "À"], [0, "Á"], [0, "Â"], [0, "Ã"], [0, "Ä"], [0, "Å"], [0, "Æ"], [0, "Ç"], [0, "È"], [0, "É"], [0, "Ê"], [0, "Ë"], [0, "Ì"], [0, "Í"], [0, "Î"], [0, "Ï"], [0, "Ð"], [0, "Ñ"], [0, "Ò"], [0, "Ó"], [0, "Ô"], [0, "Õ"], [0, "Ö"], [0, "×"], [0, "Ø"], [0, "Ù"], [0, "Ú"], [0, "Û"], [0, "Ü"], [0, "Ý"], [0, "Þ"], [0, "ß"], [0, "à"], [0, "á"], [0, "â"], [0, "ã"], [0, "ä"], [0, "å"], [0, "æ"], [0, "ç"], [0, "è"], [0, "é"], [0, "ê"], [0, "ë"], [0, "ì"], [0, "í"], [0, "î"], [0, "ï"], [0, "ð"], [0, "ñ"], [0, "ò"], [0, "ó"], [0, "ô"], [0, "õ"], [0, "ö"], [0, "÷"], [0, "ø"], [0, "ù"], [0, "ú"], [0, "û"], [0, "ü"], [0, "ý"], [0, "þ"], [0, "ÿ"], [0, "Ā"], [0, "ā"], [0, "Ă"], [0, "ă"], [0, "Ą"], [0, "ą"], [0, "Ć"], [0, "ć"], [0, "Ĉ"], [0, "ĉ"], [0, "Ċ"], [0, "ċ"], [0, "Č"], [0, "č"], [0, "Ď"], [0, "ď"], [0, "Đ"], [0, "đ"], [0, "Ē"], [0, "ē"], [2, "Ė"], [0, "ė"], [0, "Ę"], [0, "ę"], [0, "Ě"], [0, "ě"], [0, "Ĝ"], [0, "ĝ"], [0, "Ğ"], [0, "ğ"], [0, "Ġ"], [0, "ġ"], [0, "Ģ"], [1, "Ĥ"], [0, "ĥ"], [0, "Ħ"], [0, "ħ"], [0, "Ĩ"], [0, "ĩ"], [0, "Ī"], [0, "ī"], [2, "Į"], [0, "į"], [0, "İ"], [0, "ı"], [0, "IJ"], [0, "ij"], [0, "Ĵ"], [0, "ĵ"], [0, "Ķ"], [0, "ķ"], [0, "ĸ"], [0, "Ĺ"], [0, "ĺ"], [0, "Ļ"], [0, "ļ"], [0, "Ľ"], [0, "ľ"], [0, "Ŀ"], [0, "ŀ"], [0, "Ł"], [0, "ł"], [0, "Ń"], [0, "ń"], [0, "Ņ"], [0, "ņ"], [0, "Ň"], [0, "ň"], [0, "ʼn"], [0, "Ŋ"], [0, "ŋ"], [0, "Ō"], [0, "ō"], [2, "Ő"], [0, "ő"], [0, "Œ"], [0, "œ"], [0, "Ŕ"], [0, "ŕ"], [0, "Ŗ"], [0, "ŗ"], [0, "Ř"], [0, "ř"], [0, "Ś"], [0, "ś"], [0, "Ŝ"], [0, "ŝ"], [0, "Ş"], [0, "ş"], [0, "Š"], [0, "š"], [0, "Ţ"], [0, "ţ"], [0, "Ť"], [0, "ť"], [0, "Ŧ"], [0, "ŧ"], [0, "Ũ"], [0, "ũ"], [0, "Ū"], [0, "ū"], [0, "Ŭ"], [0, "ŭ"], [0, "Ů"], [0, "ů"], [0, "Ű"], [0, "ű"], [0, "Ų"], [0, "ų"], [0, "Ŵ"], [0, "ŵ"], [0, "Ŷ"], [0, "ŷ"], [0, "Ÿ"], [0, "Ź"], [0, "ź"], [0, "Ż"], [0, "ż"], [0, "Ž"], [0, "ž"], [19, "ƒ"], [34, "Ƶ"], [63, "ǵ"], [65, "ȷ"], [142, "ˆ"], [0, "ˇ"], [16, "˘"], [0, "˙"], [0, "˚"], [0, "˛"], [0, "˜"], [0, "˝"], [51, "̑"], [127, "Α"], [0, "Β"], [0, "Γ"], [0, "Δ"], [0, "Ε"], [0, "Ζ"], [0, "Η"], [0, "Θ"], [0, "Ι"], [0, "Κ"], [0, "Λ"], [0, "Μ"], [0, "Ν"], [0, "Ξ"], [0, "Ο"], [0, "Π"], [0, "Ρ"], [1, "Σ"], [0, "Τ"], [0, "Υ"], [0, "Φ"], [0, "Χ"], [0, "Ψ"], [0, "Ω"], [7, "α"], [0, "β"], [0, "γ"], [0, "δ"], [0, "ε"], [0, "ζ"], [0, "η"], [0, "θ"], [0, "ι"], [0, "κ"], [0, "λ"], [0, "μ"], [0, "ν"], [0, "ξ"], [0, "ο"], [0, "π"], [0, "ρ"], [0, "ς"], [0, "σ"], [0, "τ"], [0, "υ"], [0, "φ"], [0, "χ"], [0, "ψ"], [0, "ω"], [7, "ϑ"], [0, "ϒ"], [2, "ϕ"], [0, "ϖ"], [5, "Ϝ"], [0, "ϝ"], [18, "ϰ"], [0, "ϱ"], [3, "ϵ"], [0, "϶"], [10, "Ё"], [0, "Ђ"], [0, "Ѓ"], [0, "Є"], [0, "Ѕ"], [0, "І"], [0, "Ї"], [0, "Ј"], [0, "Љ"], [0, "Њ"], [0, "Ћ"], [0, "Ќ"], [1, "Ў"], [0, "Џ"], [0, "А"], [0, "Б"], [0, "В"], [0, "Г"], [0, "Д"], [0, "Е"], [0, "Ж"], [0, "З"], [0, "И"], [0, "Й"], [0, "К"], [0, "Л"], [0, "М"], [0, "Н"], [0, "О"], [0, "П"], [0, "Р"], [0, "С"], [0, "Т"], [0, "У"], [0, "Ф"], [0, "Х"], [0, "Ц"], [0, "Ч"], [0, "Ш"], [0, "Щ"], [0, "Ъ"], [0, "Ы"], [0, "Ь"], [0, "Э"], [0, "Ю"], [0, "Я"], [0, "а"], [0, "б"], [0, "в"], [0, "г"], [0, "д"], [0, "е"], [0, "ж"], [0, "з"], [0, "и"], [0, "й"], [0, "к"], [0, "л"], [0, "м"], [0, "н"], [0, "о"], [0, "п"], [0, "р"], [0, "с"], [0, "т"], [0, "у"], [0, "ф"], [0, "х"], [0, "ц"], [0, "ч"], [0, "ш"], [0, "щ"], [0, "ъ"], [0, "ы"], [0, "ь"], [0, "э"], [0, "ю"], [0, "я"], [1, "ё"], [0, "ђ"], [0, "ѓ"], [0, "є"], [0, "ѕ"], [0, "і"], [0, "ї"], [0, "ј"], [0, "љ"], [0, "њ"], [0, "ћ"], [0, "ќ"], [1, "ў"], [0, "џ"], [7074, " "], [0, " "], [0, " "], [0, " "], [1, " "], [0, " "], [0, " "], [0, " "], [0, "​"], [0, "‌"], [0, "‍"], [0, "‎"], [0, "‏"], [0, "‐"], [2, "–"], [0, "—"], [0, "―"], [0, "‖"], [1, "‘"], [0, "’"], [0, "‚"], [1, "“"], [0, "”"], [0, "„"], [1, "†"], [0, "‡"], [0, "•"], [2, "‥"], [0, "…"], [9, "‰"], [0, "‱"], [0, "′"], [0, "″"], [0, "‴"], [0, "‵"], [3, "‹"], [0, "›"], [3, "‾"], [2, "⁁"], [1, "⁃"], [0, "⁄"], [10, "⁏"], [7, "⁗"], [7, { - v: " ", - n: 8202, - o: "  " -}], [0, "⁠"], [0, "⁡"], [0, "⁢"], [0, "⁣"], [72, "€"], [46, "⃛"], [0, "⃜"], [37, "ℂ"], [2, "℅"], [4, "ℊ"], [0, "ℋ"], [0, "ℌ"], [0, "ℍ"], [0, "ℎ"], [0, "ℏ"], [0, "ℐ"], [0, "ℑ"], [0, "ℒ"], [0, "ℓ"], [1, "ℕ"], [0, "№"], [0, "℗"], [0, "℘"], [0, "ℙ"], [0, "ℚ"], [0, "ℛ"], [0, "ℜ"], [0, "ℝ"], [0, "℞"], [3, "™"], [1, "ℤ"], [2, "℧"], [0, "ℨ"], [0, "℩"], [2, "ℬ"], [0, "ℭ"], [1, "ℯ"], [0, "ℰ"], [0, "ℱ"], [1, "ℳ"], [0, "ℴ"], [0, "ℵ"], [0, "ℶ"], [0, "ℷ"], [0, "ℸ"], [12, "ⅅ"], [0, "ⅆ"], [0, "ⅇ"], [0, "ⅈ"], [10, "⅓"], [0, "⅔"], [0, "⅕"], [0, "⅖"], [0, "⅗"], [0, "⅘"], [0, "⅙"], [0, "⅚"], [0, "⅛"], [0, "⅜"], [0, "⅝"], [0, "⅞"], [49, "←"], [0, "↑"], [0, "→"], [0, "↓"], [0, "↔"], [0, "↕"], [0, "↖"], [0, "↗"], [0, "↘"], [0, "↙"], [0, "↚"], [0, "↛"], [1, { - v: "↝", - n: 824, - o: "↝̸" -}], [0, "↞"], [0, "↟"], [0, "↠"], [0, "↡"], [0, "↢"], [0, "↣"], [0, "↤"], [0, "↥"], [0, "↦"], [0, "↧"], [1, "↩"], [0, "↪"], [0, "↫"], [0, "↬"], [0, "↭"], [0, "↮"], [1, "↰"], [0, "↱"], [0, "↲"], [0, "↳"], [1, "↵"], [0, "↶"], [0, "↷"], [2, "↺"], [0, "↻"], [0, "↼"], [0, "↽"], [0, "↾"], [0, "↿"], [0, "⇀"], [0, "⇁"], [0, "⇂"], [0, "⇃"], [0, "⇄"], [0, "⇅"], [0, "⇆"], [0, "⇇"], [0, "⇈"], [0, "⇉"], [0, "⇊"], [0, "⇋"], [0, "⇌"], [0, "⇍"], [0, "⇎"], [0, "⇏"], [0, "⇐"], [0, "⇑"], [0, "⇒"], [0, "⇓"], [0, "⇔"], [0, "⇕"], [0, "⇖"], [0, "⇗"], [0, "⇘"], [0, "⇙"], [0, "⇚"], [0, "⇛"], [1, "⇝"], [6, "⇤"], [0, "⇥"], [15, "⇵"], [7, "⇽"], [0, "⇾"], [0, "⇿"], [0, "∀"], [0, "∁"], [0, { - v: "∂", - n: 824, - o: "∂̸" -}], [0, "∃"], [0, "∄"], [0, "∅"], [1, "∇"], [0, "∈"], [0, "∉"], [1, "∋"], [0, "∌"], [2, "∏"], [0, "∐"], [0, "∑"], [0, "−"], [0, "∓"], [0, "∔"], [1, "∖"], [0, "∗"], [0, "∘"], [1, "√"], [2, "∝"], [0, "∞"], [0, "∟"], [0, { - v: "∠", - n: 8402, - o: "∠⃒" -}], [0, "∡"], [0, "∢"], [0, "∣"], [0, "∤"], [0, "∥"], [0, "∦"], [0, "∧"], [0, "∨"], [0, { - v: "∩", - n: 65024, - o: "∩︀" -}], [0, { - v: "∪", - n: 65024, - o: "∪︀" -}], [0, "∫"], [0, "∬"], [0, "∭"], [0, "∮"], [0, "∯"], [0, "∰"], [0, "∱"], [0, "∲"], [0, "∳"], [0, "∴"], [0, "∵"], [0, "∶"], [0, "∷"], [0, "∸"], [1, "∺"], [0, "∻"], [0, { - v: "∼", - n: 8402, - o: "∼⃒" -}], [0, { - v: "∽", - n: 817, - o: "∽̱" -}], [0, { - v: "∾", - n: 819, - o: "∾̳" -}], [0, "∿"], [0, "≀"], [0, "≁"], [0, { - v: "≂", - n: 824, - o: "≂̸" -}], [0, "≃"], [0, "≄"], [0, "≅"], [0, "≆"], [0, "≇"], [0, "≈"], [0, "≉"], [0, "≊"], [0, { - v: "≋", - n: 824, - o: "≋̸" -}], [0, "≌"], [0, { - v: "≍", - n: 8402, - o: "≍⃒" -}], [0, { - v: "≎", - n: 824, - o: "≎̸" -}], [0, { - v: "≏", - n: 824, - o: "≏̸" -}], [0, { - v: "≐", - n: 824, - o: "≐̸" -}], [0, "≑"], [0, "≒"], [0, "≓"], [0, "≔"], [0, "≕"], [0, "≖"], [0, "≗"], [1, "≙"], [0, "≚"], [1, "≜"], [2, "≟"], [0, "≠"], [0, { - v: "≡", - n: 8421, - o: "≡⃥" -}], [0, "≢"], [1, { - v: "≤", - n: 8402, - o: "≤⃒" -}], [0, { - v: "≥", - n: 8402, - o: "≥⃒" -}], [0, { - v: "≦", - n: 824, - o: "≦̸" -}], [0, { - v: "≧", - n: 824, - o: "≧̸" -}], [0, { - v: "≨", - n: 65024, - o: "≨︀" -}], [0, { - v: "≩", - n: 65024, - o: "≩︀" -}], [0, { - v: "≪", - n: new Map( /* #__PURE__ */restoreDiff([[824, "≪̸"], [7577, "≪⃒"]])) -}], [0, { - v: "≫", - n: new Map( /* #__PURE__ */restoreDiff([[824, "≫̸"], [7577, "≫⃒"]])) -}], [0, "≬"], [0, "≭"], [0, "≮"], [0, "≯"], [0, "≰"], [0, "≱"], [0, "≲"], [0, "≳"], [0, "≴"], [0, "≵"], [0, "≶"], [0, "≷"], [0, "≸"], [0, "≹"], [0, "≺"], [0, "≻"], [0, "≼"], [0, "≽"], [0, "≾"], [0, { - v: "≿", - n: 824, - o: "≿̸" -}], [0, "⊀"], [0, "⊁"], [0, { - v: "⊂", - n: 8402, - o: "⊂⃒" -}], [0, { - v: "⊃", - n: 8402, - o: "⊃⃒" -}], [0, "⊄"], [0, "⊅"], [0, "⊆"], [0, "⊇"], [0, "⊈"], [0, "⊉"], [0, { - v: "⊊", - n: 65024, - o: "⊊︀" -}], [0, { - v: "⊋", - n: 65024, - o: "⊋︀" -}], [1, "⊍"], [0, "⊎"], [0, { - v: "⊏", - n: 824, - o: "⊏̸" -}], [0, { - v: "⊐", - n: 824, - o: "⊐̸" -}], [0, "⊑"], [0, "⊒"], [0, { - v: "⊓", - n: 65024, - o: "⊓︀" -}], [0, { - v: "⊔", - n: 65024, - o: "⊔︀" -}], [0, "⊕"], [0, "⊖"], [0, "⊗"], [0, "⊘"], [0, "⊙"], [0, "⊚"], [0, "⊛"], [1, "⊝"], [0, "⊞"], [0, "⊟"], [0, "⊠"], [0, "⊡"], [0, "⊢"], [0, "⊣"], [0, "⊤"], [0, "⊥"], [1, "⊧"], [0, "⊨"], [0, "⊩"], [0, "⊪"], [0, "⊫"], [0, "⊬"], [0, "⊭"], [0, "⊮"], [0, "⊯"], [0, "⊰"], [1, "⊲"], [0, "⊳"], [0, { - v: "⊴", - n: 8402, - o: "⊴⃒" -}], [0, { - v: "⊵", - n: 8402, - o: "⊵⃒" -}], [0, "⊶"], [0, "⊷"], [0, "⊸"], [0, "⊹"], [0, "⊺"], [0, "⊻"], [1, "⊽"], [0, "⊾"], [0, "⊿"], [0, "⋀"], [0, "⋁"], [0, "⋂"], [0, "⋃"], [0, "⋄"], [0, "⋅"], [0, "⋆"], [0, "⋇"], [0, "⋈"], [0, "⋉"], [0, "⋊"], [0, "⋋"], [0, "⋌"], [0, "⋍"], [0, "⋎"], [0, "⋏"], [0, "⋐"], [0, "⋑"], [0, "⋒"], [0, "⋓"], [0, "⋔"], [0, "⋕"], [0, "⋖"], [0, "⋗"], [0, { - v: "⋘", - n: 824, - o: "⋘̸" -}], [0, { - v: "⋙", - n: 824, - o: "⋙̸" -}], [0, { - v: "⋚", - n: 65024, - o: "⋚︀" -}], [0, { - v: "⋛", - n: 65024, - o: "⋛︀" -}], [2, "⋞"], [0, "⋟"], [0, "⋠"], [0, "⋡"], [0, "⋢"], [0, "⋣"], [2, "⋦"], [0, "⋧"], [0, "⋨"], [0, "⋩"], [0, "⋪"], [0, "⋫"], [0, "⋬"], [0, "⋭"], [0, "⋮"], [0, "⋯"], [0, "⋰"], [0, "⋱"], [0, "⋲"], [0, "⋳"], [0, "⋴"], [0, { - v: "⋵", - n: 824, - o: "⋵̸" -}], [0, "⋶"], [0, "⋷"], [1, { - v: "⋹", - n: 824, - o: "⋹̸" -}], [0, "⋺"], [0, "⋻"], [0, "⋼"], [0, "⋽"], [0, "⋾"], [6, "⌅"], [0, "⌆"], [1, "⌈"], [0, "⌉"], [0, "⌊"], [0, "⌋"], [0, "⌌"], [0, "⌍"], [0, "⌎"], [0, "⌏"], [0, "⌐"], [1, "⌒"], [0, "⌓"], [1, "⌕"], [0, "⌖"], [5, "⌜"], [0, "⌝"], [0, "⌞"], [0, "⌟"], [2, "⌢"], [0, "⌣"], [9, "⌭"], [0, "⌮"], [7, "⌶"], [6, "⌽"], [1, "⌿"], [60, "⍼"], [51, "⎰"], [0, "⎱"], [2, "⎴"], [0, "⎵"], [0, "⎶"], [37, "⏜"], [0, "⏝"], [0, "⏞"], [0, "⏟"], [2, "⏢"], [4, "⏧"], [59, "␣"], [164, "Ⓢ"], [55, "─"], [1, "│"], [9, "┌"], [3, "┐"], [3, "└"], [3, "┘"], [3, "├"], [7, "┤"], [7, "┬"], [7, "┴"], [7, "┼"], [19, "═"], [0, "║"], [0, "╒"], [0, "╓"], [0, "╔"], [0, "╕"], [0, "╖"], [0, "╗"], [0, "╘"], [0, "╙"], [0, "╚"], [0, "╛"], [0, "╜"], [0, "╝"], [0, "╞"], [0, "╟"], [0, "╠"], [0, "╡"], [0, "╢"], [0, "╣"], [0, "╤"], [0, "╥"], [0, "╦"], [0, "╧"], [0, "╨"], [0, "╩"], [0, "╪"], [0, "╫"], [0, "╬"], [19, "▀"], [3, "▄"], [3, "█"], [8, "░"], [0, "▒"], [0, "▓"], [13, "□"], [8, "▪"], [0, "▫"], [1, "▭"], [0, "▮"], [2, "▱"], [1, "△"], [0, "▴"], [0, "▵"], [2, "▸"], [0, "▹"], [3, "▽"], [0, "▾"], [0, "▿"], [2, "◂"], [0, "◃"], [6, "◊"], [0, "○"], [32, "◬"], [2, "◯"], [8, "◸"], [0, "◹"], [0, "◺"], [0, "◻"], [0, "◼"], [8, "★"], [0, "☆"], [7, "☎"], [49, "♀"], [1, "♂"], [29, "♠"], [2, "♣"], [1, "♥"], [0, "♦"], [3, "♪"], [2, "♭"], [0, "♮"], [0, "♯"], [163, "✓"], [3, "✗"], [8, "✠"], [21, "✶"], [33, "❘"], [25, "❲"], [0, "❳"], [84, "⟈"], [0, "⟉"], [28, "⟦"], [0, "⟧"], [0, "⟨"], [0, "⟩"], [0, "⟪"], [0, "⟫"], [0, "⟬"], [0, "⟭"], [7, "⟵"], [0, "⟶"], [0, "⟷"], [0, "⟸"], [0, "⟹"], [0, "⟺"], [1, "⟼"], [2, "⟿"], [258, "⤂"], [0, "⤃"], [0, "⤄"], [0, "⤅"], [6, "⤌"], [0, "⤍"], [0, "⤎"], [0, "⤏"], [0, "⤐"], [0, "⤑"], [0, "⤒"], [0, "⤓"], [2, "⤖"], [2, "⤙"], [0, "⤚"], [0, "⤛"], [0, "⤜"], [0, "⤝"], [0, "⤞"], [0, "⤟"], [0, "⤠"], [2, "⤣"], [0, "⤤"], [0, "⤥"], [0, "⤦"], [0, "⤧"], [0, "⤨"], [0, "⤩"], [0, "⤪"], [8, { - v: "⤳", - n: 824, - o: "⤳̸" -}], [1, "⤵"], [0, "⤶"], [0, "⤷"], [0, "⤸"], [0, "⤹"], [2, "⤼"], [0, "⤽"], [7, "⥅"], [2, "⥈"], [0, "⥉"], [0, "⥊"], [0, "⥋"], [2, "⥎"], [0, "⥏"], [0, "⥐"], [0, "⥑"], [0, "⥒"], [0, "⥓"], [0, "⥔"], [0, "⥕"], [0, "⥖"], [0, "⥗"], [0, "⥘"], [0, "⥙"], [0, "⥚"], [0, "⥛"], [0, "⥜"], [0, "⥝"], [0, "⥞"], [0, "⥟"], [0, "⥠"], [0, "⥡"], [0, "⥢"], [0, "⥣"], [0, "⥤"], [0, "⥥"], [0, "⥦"], [0, "⥧"], [0, "⥨"], [0, "⥩"], [0, "⥪"], [0, "⥫"], [0, "⥬"], [0, "⥭"], [0, "⥮"], [0, "⥯"], [0, "⥰"], [0, "⥱"], [0, "⥲"], [0, "⥳"], [0, "⥴"], [0, "⥵"], [0, "⥶"], [1, "⥸"], [0, "⥹"], [1, "⥻"], [0, "⥼"], [0, "⥽"], [0, "⥾"], [0, "⥿"], [5, "⦅"], [0, "⦆"], [4, "⦋"], [0, "⦌"], [0, "⦍"], [0, "⦎"], [0, "⦏"], [0, "⦐"], [0, "⦑"], [0, "⦒"], [0, "⦓"], [0, "⦔"], [0, "⦕"], [0, "⦖"], [3, "⦚"], [1, "⦜"], [0, "⦝"], [6, "⦤"], [0, "⦥"], [0, "⦦"], [0, "⦧"], [0, "⦨"], [0, "⦩"], [0, "⦪"], [0, "⦫"], [0, "⦬"], [0, "⦭"], [0, "⦮"], [0, "⦯"], [0, "⦰"], [0, "⦱"], [0, "⦲"], [0, "⦳"], [0, "⦴"], [0, "⦵"], [0, "⦶"], [0, "⦷"], [1, "⦹"], [1, "⦻"], [0, "⦼"], [1, "⦾"], [0, "⦿"], [0, "⧀"], [0, "⧁"], [0, "⧂"], [0, "⧃"], [0, "⧄"], [0, "⧅"], [3, "⧉"], [3, "⧍"], [0, "⧎"], [0, { - v: "⧏", - n: 824, - o: "⧏̸" -}], [0, { - v: "⧐", - n: 824, - o: "⧐̸" -}], [11, "⧜"], [0, "⧝"], [0, "⧞"], [4, "⧣"], [0, "⧤"], [0, "⧥"], [5, "⧫"], [8, "⧴"], [1, "⧶"], [9, "⨀"], [0, "⨁"], [0, "⨂"], [1, "⨄"], [1, "⨆"], [5, "⨌"], [0, "⨍"], [2, "⨐"], [0, "⨑"], [0, "⨒"], [0, "⨓"], [0, "⨔"], [0, "⨕"], [0, "⨖"], [0, "⨗"], [10, "⨢"], [0, "⨣"], [0, "⨤"], [0, "⨥"], [0, "⨦"], [0, "⨧"], [1, "⨩"], [0, "⨪"], [2, "⨭"], [0, "⨮"], [0, "⨯"], [0, "⨰"], [0, "⨱"], [1, "⨳"], [0, "⨴"], [0, "⨵"], [0, "⨶"], [0, "⨷"], [0, "⨸"], [0, "⨹"], [0, "⨺"], [0, "⨻"], [0, "⨼"], [2, "⨿"], [0, "⩀"], [1, "⩂"], [0, "⩃"], [0, "⩄"], [0, "⩅"], [0, "⩆"], [0, "⩇"], [0, "⩈"], [0, "⩉"], [0, "⩊"], [0, "⩋"], [0, "⩌"], [0, "⩍"], [2, "⩐"], [2, "⩓"], [0, "⩔"], [0, "⩕"], [0, "⩖"], [0, "⩗"], [0, "⩘"], [1, "⩚"], [0, "⩛"], [0, "⩜"], [0, "⩝"], [1, "⩟"], [6, "⩦"], [3, "⩪"], [2, { - v: "⩭", - n: 824, - o: "⩭̸" -}], [0, "⩮"], [0, "⩯"], [0, { - v: "⩰", - n: 824, - o: "⩰̸" -}], [0, "⩱"], [0, "⩲"], [0, "⩳"], [0, "⩴"], [0, "⩵"], [1, "⩷"], [0, "⩸"], [0, "⩹"], [0, "⩺"], [0, "⩻"], [0, "⩼"], [0, { - v: "⩽", - n: 824, - o: "⩽̸" -}], [0, { - v: "⩾", - n: 824, - o: "⩾̸" -}], [0, "⩿"], [0, "⪀"], [0, "⪁"], [0, "⪂"], [0, "⪃"], [0, "⪄"], [0, "⪅"], [0, "⪆"], [0, "⪇"], [0, "⪈"], [0, "⪉"], [0, "⪊"], [0, "⪋"], [0, "⪌"], [0, "⪍"], [0, "⪎"], [0, "⪏"], [0, "⪐"], [0, "⪑"], [0, "⪒"], [0, "⪓"], [0, "⪔"], [0, "⪕"], [0, "⪖"], [0, "⪗"], [0, "⪘"], [0, "⪙"], [0, "⪚"], [2, "⪝"], [0, "⪞"], [0, "⪟"], [0, "⪠"], [0, { - v: "⪡", - n: 824, - o: "⪡̸" -}], [0, { - v: "⪢", - n: 824, - o: "⪢̸" -}], [1, "⪤"], [0, "⪥"], [0, "⪦"], [0, "⪧"], [0, "⪨"], [0, "⪩"], [0, "⪪"], [0, "⪫"], [0, { - v: "⪬", - n: 65024, - o: "⪬︀" -}], [0, { - v: "⪭", - n: 65024, - o: "⪭︀" -}], [0, "⪮"], [0, { - v: "⪯", - n: 824, - o: "⪯̸" -}], [0, { - v: "⪰", - n: 824, - o: "⪰̸" -}], [2, "⪳"], [0, "⪴"], [0, "⪵"], [0, "⪶"], [0, "⪷"], [0, "⪸"], [0, "⪹"], [0, "⪺"], [0, "⪻"], [0, "⪼"], [0, "⪽"], [0, "⪾"], [0, "⪿"], [0, "⫀"], [0, "⫁"], [0, "⫂"], [0, "⫃"], [0, "⫄"], [0, { - v: "⫅", - n: 824, - o: "⫅̸" -}], [0, { - v: "⫆", - n: 824, - o: "⫆̸" -}], [0, "⫇"], [0, "⫈"], [2, { - v: "⫋", - n: 65024, - o: "⫋︀" -}], [0, { - v: "⫌", - n: 65024, - o: "⫌︀" -}], [2, "⫏"], [0, "⫐"], [0, "⫑"], [0, "⫒"], [0, "⫓"], [0, "⫔"], [0, "⫕"], [0, "⫖"], [0, "⫗"], [0, "⫘"], [0, "⫙"], [0, "⫚"], [0, "⫛"], [8, "⫤"], [1, "⫦"], [0, "⫧"], [0, "⫨"], [0, "⫩"], [1, "⫫"], [0, "⫬"], [0, "⫭"], [0, "⫮"], [0, "⫯"], [0, "⫰"], [0, "⫱"], [0, "⫲"], [0, "⫳"], [9, { - v: "⫽", - n: 8421, - o: "⫽⃥" -}], [44343, { - n: new Map( /* #__PURE__ */restoreDiff([[56476, "𝒜"], [1, "𝒞"], [0, "𝒟"], [2, "𝒢"], [2, "𝒥"], [0, "𝒦"], [2, "𝒩"], [0, "𝒪"], [0, "𝒫"], [0, "𝒬"], [1, "𝒮"], [0, "𝒯"], [0, "𝒰"], [0, "𝒱"], [0, "𝒲"], [0, "𝒳"], [0, "𝒴"], [0, "𝒵"], [0, "𝒶"], [0, "𝒷"], [0, "𝒸"], [0, "𝒹"], [1, "𝒻"], [1, "𝒽"], [0, "𝒾"], [0, "𝒿"], [0, "𝓀"], [0, "𝓁"], [0, "𝓂"], [0, "𝓃"], [1, "𝓅"], [0, "𝓆"], [0, "𝓇"], [0, "𝓈"], [0, "𝓉"], [0, "𝓊"], [0, "𝓋"], [0, "𝓌"], [0, "𝓍"], [0, "𝓎"], [0, "𝓏"], [52, "𝔄"], [0, "𝔅"], [1, "𝔇"], [0, "𝔈"], [0, "𝔉"], [0, "𝔊"], [2, "𝔍"], [0, "𝔎"], [0, "𝔏"], [0, "𝔐"], [0, "𝔑"], [0, "𝔒"], [0, "𝔓"], [0, "𝔔"], [1, "𝔖"], [0, "𝔗"], [0, "𝔘"], [0, "𝔙"], [0, "𝔚"], [0, "𝔛"], [0, "𝔜"], [1, "𝔞"], [0, "𝔟"], [0, "𝔠"], [0, "𝔡"], [0, "𝔢"], [0, "𝔣"], [0, "𝔤"], [0, "𝔥"], [0, "𝔦"], [0, "𝔧"], [0, "𝔨"], [0, "𝔩"], [0, "𝔪"], [0, "𝔫"], [0, "𝔬"], [0, "𝔭"], [0, "𝔮"], [0, "𝔯"], [0, "𝔰"], [0, "𝔱"], [0, "𝔲"], [0, "𝔳"], [0, "𝔴"], [0, "𝔵"], [0, "𝔶"], [0, "𝔷"], [0, "𝔸"], [0, "𝔹"], [1, "𝔻"], [0, "𝔼"], [0, "𝔽"], [0, "𝔾"], [1, "𝕀"], [0, "𝕁"], [0, "𝕂"], [0, "𝕃"], [0, "𝕄"], [1, "𝕆"], [3, "𝕊"], [0, "𝕋"], [0, "𝕌"], [0, "𝕍"], [0, "𝕎"], [0, "𝕏"], [0, "𝕐"], [1, "𝕒"], [0, "𝕓"], [0, "𝕔"], [0, "𝕕"], [0, "𝕖"], [0, "𝕗"], [0, "𝕘"], [0, "𝕙"], [0, "𝕚"], [0, "𝕛"], [0, "𝕜"], [0, "𝕝"], [0, "𝕞"], [0, "𝕟"], [0, "𝕠"], [0, "𝕡"], [0, "𝕢"], [0, "𝕣"], [0, "𝕤"], [0, "𝕥"], [0, "𝕦"], [0, "𝕧"], [0, "𝕨"], [0, "𝕩"], [0, "𝕪"], [0, "𝕫"]])) -}], [8906, "ff"], [0, "fi"], [0, "fl"], [0, "ffi"], [0, "ffl"]])); - - /***/ - }, - - /***/ "../../../node_modules/entities/lib/index.js": - /*!***************************************************!*\ - !*** ../../../node_modules/entities/lib/index.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.decodeXMLStrict = - exports.decodeHTML5Strict = - exports.decodeHTML4Strict = - exports.decodeHTML5 = - exports.decodeHTML4 = - exports.decodeHTMLAttribute = - exports.decodeHTMLStrict = - exports.decodeHTML = - exports.decodeXML = - exports.DecodingMode = - exports.EntityDecoder = - exports.encodeHTML5 = - exports.encodeHTML4 = - exports.encodeNonAsciiHTML = - exports.encodeHTML = - exports.escapeText = - exports.escapeAttribute = - exports.escapeUTF8 = - exports.escape = - exports.encodeXML = - exports.encode = - exports.decodeStrict = - exports.decode = - exports.EncodingMode = - exports.EntityLevel = - void 0; - var decode_js_1 = __webpack_require__( - /*! ./decode.js */ "../../../node_modules/entities/lib/decode.js" - ); - var encode_js_1 = __webpack_require__( - /*! ./encode.js */ "../../../node_modules/entities/lib/encode.js" - ); - var escape_js_1 = __webpack_require__( - /*! ./escape.js */ "../../../node_modules/entities/lib/escape.js" - ); - /** The level of entities to support. */ - var EntityLevel; - (function (EntityLevel) { - /** Support only XML entities. */ - EntityLevel[(EntityLevel["XML"] = 0)] = "XML"; - /** Support HTML entities, which are a superset of XML entities. */ - EntityLevel[(EntityLevel["HTML"] = 1)] = "HTML"; - })((EntityLevel = exports.EntityLevel || (exports.EntityLevel = {}))); - var EncodingMode; - (function (EncodingMode) { - /** - * The output is UTF-8 encoded. Only characters that need escaping within - * XML will be escaped. - */ - EncodingMode[(EncodingMode["UTF8"] = 0)] = "UTF8"; - /** - * The output consists only of ASCII characters. Characters that need - * escaping within HTML, and characters that aren't ASCII characters will - * be escaped. - */ - EncodingMode[(EncodingMode["ASCII"] = 1)] = "ASCII"; - /** - * Encode all characters that have an equivalent entity, as well as all - * characters that are not ASCII characters. - */ - EncodingMode[(EncodingMode["Extensive"] = 2)] = "Extensive"; - /** - * Encode all characters that have to be escaped in HTML attributes, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - */ - EncodingMode[(EncodingMode["Attribute"] = 3)] = "Attribute"; - /** - * Encode all characters that have to be escaped in HTML text, - * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. - */ - EncodingMode[(EncodingMode["Text"] = 4)] = "Text"; - })( - (EncodingMode = exports.EncodingMode || (exports.EncodingMode = {})) - ); - /** - * Decodes a string with entities. - * - * @param data String to decode. - * @param options Decoding options. - */ - function decode(data, options) { - if (options === void 0) { - options = EntityLevel.XML; - } - var level = typeof options === "number" ? options : options.level; - if (level === EntityLevel.HTML) { - var mode = typeof options === "object" ? options.mode : undefined; - return (0, decode_js_1.decodeHTML)(data, mode); - } - return (0, decode_js_1.decodeXML)(data); - } - exports.decode = decode; - /** - * Decodes a string with entities. Does not allow missing trailing semicolons for entities. - * - * @param data String to decode. - * @param options Decoding options. - * @deprecated Use `decode` with the `mode` set to `Strict`. - */ - function decodeStrict(data, options) { - var _a; - if (options === void 0) { - options = EntityLevel.XML; - } - var opts = - typeof options === "number" - ? { - level: options, - } - : options; - (_a = opts.mode) !== null && _a !== void 0 - ? _a - : (opts.mode = decode_js_1.DecodingMode.Strict); - return decode(data, opts); - } - exports.decodeStrict = decodeStrict; - /** - * Encodes a string with entities. - * - * @param data String to encode. - * @param options Encoding options. - */ - function encode(data, options) { - if (options === void 0) { - options = EntityLevel.XML; - } - var opts = - typeof options === "number" - ? { - level: options, - } - : options; - // Mode `UTF8` just escapes XML entities - if (opts.mode === EncodingMode.UTF8) - return (0, escape_js_1.escapeUTF8)(data); - if (opts.mode === EncodingMode.Attribute) - return (0, escape_js_1.escapeAttribute)(data); - if (opts.mode === EncodingMode.Text) - return (0, escape_js_1.escapeText)(data); - if (opts.level === EntityLevel.HTML) { - if (opts.mode === EncodingMode.ASCII) { - return (0, encode_js_1.encodeNonAsciiHTML)(data); - } - return (0, encode_js_1.encodeHTML)(data); - } - // ASCII and Extensive are equivalent - return (0, escape_js_1.encodeXML)(data); - } - exports.encode = encode; - var escape_js_2 = __webpack_require__( - /*! ./escape.js */ "../../../node_modules/entities/lib/escape.js" - ); - Object.defineProperty(exports, "encodeXML", { - enumerable: true, - get: function () { - return escape_js_2.encodeXML; - }, - }); - Object.defineProperty(exports, "escape", { - enumerable: true, - get: function () { - return escape_js_2.escape; - }, - }); - Object.defineProperty(exports, "escapeUTF8", { - enumerable: true, - get: function () { - return escape_js_2.escapeUTF8; - }, - }); - Object.defineProperty(exports, "escapeAttribute", { - enumerable: true, - get: function () { - return escape_js_2.escapeAttribute; - }, - }); - Object.defineProperty(exports, "escapeText", { - enumerable: true, - get: function () { - return escape_js_2.escapeText; - }, - }); - var encode_js_2 = __webpack_require__( - /*! ./encode.js */ "../../../node_modules/entities/lib/encode.js" - ); - Object.defineProperty(exports, "encodeHTML", { - enumerable: true, - get: function () { - return encode_js_2.encodeHTML; - }, - }); - Object.defineProperty(exports, "encodeNonAsciiHTML", { - enumerable: true, - get: function () { - return encode_js_2.encodeNonAsciiHTML; - }, - }); - // Legacy aliases (deprecated) - Object.defineProperty(exports, "encodeHTML4", { - enumerable: true, - get: function () { - return encode_js_2.encodeHTML; - }, - }); - Object.defineProperty(exports, "encodeHTML5", { - enumerable: true, - get: function () { - return encode_js_2.encodeHTML; - }, - }); - var decode_js_2 = __webpack_require__( - /*! ./decode.js */ "../../../node_modules/entities/lib/decode.js" - ); - Object.defineProperty(exports, "EntityDecoder", { - enumerable: true, - get: function () { - return decode_js_2.EntityDecoder; - }, - }); - Object.defineProperty(exports, "DecodingMode", { - enumerable: true, - get: function () { - return decode_js_2.DecodingMode; - }, - }); - Object.defineProperty(exports, "decodeXML", { - enumerable: true, - get: function () { - return decode_js_2.decodeXML; - }, - }); - Object.defineProperty(exports, "decodeHTML", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTML; - }, - }); - Object.defineProperty(exports, "decodeHTMLStrict", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLStrict; - }, - }); - Object.defineProperty(exports, "decodeHTMLAttribute", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLAttribute; - }, - }); - // Legacy aliases (deprecated) - Object.defineProperty(exports, "decodeHTML4", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTML; - }, - }); - Object.defineProperty(exports, "decodeHTML5", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTML; - }, - }); - Object.defineProperty(exports, "decodeHTML4Strict", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLStrict; - }, - }); - Object.defineProperty(exports, "decodeHTML5Strict", { - enumerable: true, - get: function () { - return decode_js_2.decodeHTMLStrict; - }, - }); - Object.defineProperty(exports, "decodeXMLStrict", { - enumerable: true, - get: function () { - return decode_js_2.decodeXML; - }, - }); - - /***/ - }, - - /***/ "../../../node_modules/framer-motion/dist/cjs/index.js": - /*!*************************************************************!*\ - !*** ../../../node_modules/framer-motion/dist/cjs/index.js ***! - \*************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var tslib = __webpack_require__( - /*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs" - ); - var React = __webpack_require__(/*! react */ "react"); - var heyListen = __webpack_require__( - /*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js" - ); - var styleValueTypes = __webpack_require__( - /*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js" - ); - var popmotion = __webpack_require__( - /*! popmotion */ "../../../node_modules/popmotion/dist/popmotion.cjs.js" - ); - var sync = __webpack_require__( - /*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js" - ); - var dom = __webpack_require__( - /*! @motionone/dom */ "../../../node_modules/@motionone/dom/dist/index.es.js" - ); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e - ? e - : { - default: e, - }; - } - function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== "default") { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); - } - }); - } - n["default"] = e; - return Object.freeze(n); - } - var React__namespace = /*#__PURE__*/ _interopNamespace(React); - var React__default = /*#__PURE__*/ _interopDefaultLegacy(React); - var sync__default = /*#__PURE__*/ _interopDefaultLegacy(sync); - - /** - * Browser-safe usage of process - */ - var defaultEnvironment = "production"; - var env = - typeof process === "undefined" || process.env === undefined - ? defaultEnvironment - : "development" || 0; - var createDefinition = function (propNames) { - return { - isEnabled: function (props) { - return propNames.some(function (name) { - return !!props[name]; - }); - }, - }; - }; - var featureDefinitions = { - measureLayout: createDefinition(["layout", "layoutId", "drag"]), - animation: createDefinition([ - "animate", - "exit", - "variants", - "whileHover", - "whileTap", - "whileFocus", - "whileDrag", - "whileInView", - ]), - exit: createDefinition(["exit"]), - drag: createDefinition(["drag", "dragControls"]), - focus: createDefinition(["whileFocus"]), - hover: createDefinition(["whileHover", "onHoverStart", "onHoverEnd"]), - tap: createDefinition([ - "whileTap", - "onTap", - "onTapStart", - "onTapCancel", - ]), - pan: createDefinition([ - "onPan", - "onPanStart", - "onPanSessionStart", - "onPanEnd", - ]), - inView: createDefinition([ - "whileInView", - "onViewportEnter", - "onViewportLeave", - ]), - }; - function loadFeatures(features) { - for (var key in features) { - if (features[key] === null) continue; - if (key === "projectionNodeConstructor") { - featureDefinitions.projectionNodeConstructor = features[key]; - } else { - featureDefinitions[key].Component = features[key]; - } - } - } - var LazyContext = React.createContext({ - strict: false, - }); - var featureNames = Object.keys(featureDefinitions); - var numFeatures = featureNames.length; - /** - * Load features via renderless components based on the provided MotionProps. - */ - function useFeatures(props, visualElement, preloadedFeatures) { - var features = []; - var lazyContext = React.useContext(LazyContext); - if (!visualElement) return null; - /** - * If we're in development mode, check to make sure we're not rendering a motion component - * as a child of LazyMotion, as this will break the file-size benefits of using it. - */ - if (env !== "production" && preloadedFeatures && lazyContext.strict) { - heyListen.invariant( - false, - "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead." - ); - } - for (var i = 0; i < numFeatures; i++) { - var name_1 = featureNames[i]; - var _a = featureDefinitions[name_1], - isEnabled = _a.isEnabled, - Component = _a.Component; - /** - * It might be possible in the future to use this moment to - * dynamically request functionality. In initial tests this - * was producing a lot of duplication amongst bundles. - */ - if (isEnabled(props) && Component) { - features.push( - React__namespace.createElement( - Component, - tslib.__assign( - { - key: name_1, - }, - props, - { - visualElement: visualElement, - } - ) - ) - ); - } - } - return features; - } - - /** - * @public - */ - var MotionConfigContext = React.createContext({ - transformPagePoint: function (p) { - return p; - }, - isStatic: false, - reducedMotion: "never", - }); - var MotionContext = React.createContext({}); - function useVisualElementContext() { - return React.useContext(MotionContext).visualElement; - } - - /** - * @public - */ - var PresenceContext = React.createContext(null); - var isBrowser = typeof document !== "undefined"; - var useIsomorphicLayoutEffect = isBrowser - ? React.useLayoutEffect - : React.useEffect; - - // Does this device prefer reduced motion? Returns `null` server-side. - var prefersReducedMotion = { - current: null, - }; - var hasDetected = false; - function initPrefersReducedMotion() { - hasDetected = true; - if (!isBrowser) return; - if (window.matchMedia) { - var motionMediaQuery_1 = window.matchMedia( - "(prefers-reduced-motion)" - ); - var setReducedMotionPreferences = function () { - return (prefersReducedMotion.current = - motionMediaQuery_1.matches); - }; - motionMediaQuery_1.addListener(setReducedMotionPreferences); - setReducedMotionPreferences(); - } else { - prefersReducedMotion.current = false; - } - } - /** - * A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting. - * - * This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing - * `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion. - * - * It will actively respond to changes and re-render your components with the latest setting. - * - * ```jsx - * export function Sidebar({ isOpen }) { - * const shouldReduceMotion = useReducedMotion() - * const closedX = shouldReduceMotion ? 0 : "-100%" - * - * return ( - * - * ) - * } - * ``` - * - * @return boolean - * - * @public - */ - function useReducedMotion() { - /** - * Lazy initialisation of prefersReducedMotion - */ - !hasDetected && initPrefersReducedMotion(); - var _a = tslib.__read( - React.useState(prefersReducedMotion.current), - 1 - ), - shouldReduceMotion = _a[0]; - /** - * TODO See if people miss automatically updating shouldReduceMotion setting - */ - return shouldReduceMotion; - } - function useReducedMotionConfig() { - var reducedMotionPreference = useReducedMotion(); - var reducedMotion = - React.useContext(MotionConfigContext).reducedMotion; - if (reducedMotion === "never") { - return false; - } else if (reducedMotion === "always") { - return true; - } else { - return reducedMotionPreference; - } - } - function useVisualElement( - Component, - visualState, - props, - createVisualElement - ) { - var lazyContext = React.useContext(LazyContext); - var parent = useVisualElementContext(); - var presenceContext = React.useContext(PresenceContext); - var shouldReduceMotion = useReducedMotionConfig(); - var visualElementRef = React.useRef(undefined); - /** - * If we haven't preloaded a renderer, check to see if we have one lazy-loaded - */ - if (!createVisualElement) createVisualElement = lazyContext.renderer; - if (!visualElementRef.current && createVisualElement) { - visualElementRef.current = createVisualElement(Component, { - visualState: visualState, - parent: parent, - props: props, - presenceId: - presenceContext === null || presenceContext === void 0 - ? void 0 - : presenceContext.id, - blockInitialAnimation: - (presenceContext === null || presenceContext === void 0 - ? void 0 - : presenceContext.initial) === false, - shouldReduceMotion: shouldReduceMotion, - }); - } - var visualElement = visualElementRef.current; - useIsomorphicLayoutEffect(function () { - visualElement === null || visualElement === void 0 - ? void 0 - : visualElement.syncRender(); - }); - React.useEffect(function () { - var _a; - (_a = - visualElement === null || visualElement === void 0 - ? void 0 - : visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.animateChanges(); - }); - useIsomorphicLayoutEffect(function () { - return function () { - return visualElement === null || visualElement === void 0 - ? void 0 - : visualElement.notifyUnmount(); - }; - }, []); - return visualElement; - } - function isRefObject(ref) { - return ( - typeof ref === "object" && - Object.prototype.hasOwnProperty.call(ref, "current") - ); - } - - /** - * Creates a ref function that, when called, hydrates the provided - * external ref and VisualElement. - */ - function useMotionRef(visualState, visualElement, externalRef) { - return React.useCallback( - function (instance) { - var _a; - instance && - ((_a = visualState.mount) === null || _a === void 0 - ? void 0 - : _a.call(visualState, instance)); - if (visualElement) { - instance - ? visualElement.mount(instance) - : visualElement.unmount(); - } - if (externalRef) { - if (typeof externalRef === "function") { - externalRef(instance); - } else if (isRefObject(externalRef)) { - externalRef.current = instance; - } - } - }, - /** - * Only pass a new ref callback to React if we've received a visual element - * factory. Otherwise we'll be mounting/remounting every time externalRef - * or other dependencies change. - */ - [visualElement] - ); - } - - /** - * Decides if the supplied variable is an array of variant labels - */ - function isVariantLabels(v) { - return Array.isArray(v); - } - /** - * Decides if the supplied variable is variant label - */ - function isVariantLabel(v) { - return typeof v === "string" || isVariantLabels(v); - } - /** - * Creates an object containing the latest state of every MotionValue on a VisualElement - */ - function getCurrent(visualElement) { - var current = {}; - visualElement.forEachValue(function (value, key) { - return (current[key] = value.get()); - }); - return current; - } - /** - * Creates an object containing the latest velocity of every MotionValue on a VisualElement - */ - function getVelocity$1(visualElement) { - var velocity = {}; - visualElement.forEachValue(function (value, key) { - return (velocity[key] = value.getVelocity()); - }); - return velocity; - } - function resolveVariantFromProps( - props, - definition, - custom, - currentValues, - currentVelocity - ) { - var _a; - if (currentValues === void 0) { - currentValues = {}; - } - if (currentVelocity === void 0) { - currentVelocity = {}; - } - /** - * If the variant definition is a function, resolve. - */ - if (typeof definition === "function") { - definition = definition( - custom !== null && custom !== void 0 ? custom : props.custom, - currentValues, - currentVelocity - ); - } - /** - * If the variant definition is a variant label, or - * the function returned a variant label, resolve. - */ - if (typeof definition === "string") { - definition = - (_a = props.variants) === null || _a === void 0 - ? void 0 - : _a[definition]; - } - /** - * At this point we've resolved both functions and variant labels, - * but the resolved variant label might itself have been a function. - * If so, resolve. This can only have returned a valid target object. - */ - if (typeof definition === "function") { - definition = definition( - custom !== null && custom !== void 0 ? custom : props.custom, - currentValues, - currentVelocity - ); - } - return definition; - } - function resolveVariant(visualElement, definition, custom) { - var props = visualElement.getProps(); - return resolveVariantFromProps( - props, - definition, - custom !== null && custom !== void 0 ? custom : props.custom, - getCurrent(visualElement), - getVelocity$1(visualElement) - ); - } - function checkIfControllingVariants(props) { - var _a; - return ( - typeof ((_a = props.animate) === null || _a === void 0 - ? void 0 - : _a.start) === "function" || - isVariantLabel(props.initial) || - isVariantLabel(props.animate) || - isVariantLabel(props.whileHover) || - isVariantLabel(props.whileDrag) || - isVariantLabel(props.whileTap) || - isVariantLabel(props.whileFocus) || - isVariantLabel(props.exit) - ); - } - function checkIfVariantNode(props) { - return Boolean(checkIfControllingVariants(props) || props.variants); - } - function getCurrentTreeVariants(props, context) { - if (checkIfControllingVariants(props)) { - var initial = props.initial, - animate = props.animate; - return { - initial: - initial === false || isVariantLabel(initial) - ? initial - : undefined, - animate: isVariantLabel(animate) ? animate : undefined, - }; - } - return props.inherit !== false ? context : {}; - } - function useCreateMotionContext(props) { - var _a = getCurrentTreeVariants( - props, - React.useContext(MotionContext) - ), - initial = _a.initial, - animate = _a.animate; - return React.useMemo( - function () { - return { - initial: initial, - animate: animate, - }; - }, - [ - variantLabelsAsDependency(initial), - variantLabelsAsDependency(animate), - ] - ); - } - function variantLabelsAsDependency(prop) { - return Array.isArray(prop) ? prop.join(" ") : prop; - } - - /** - * Creates a constant value over the lifecycle of a component. - * - * Even if `useMemo` is provided an empty array as its final argument, it doesn't offer - * a guarantee that it won't re-run for performance reasons later on. By using `useConstant` - * you can ensure that initialisers don't execute twice or more. - */ - function useConstant(init) { - var ref = React.useRef(null); - if (ref.current === null) { - ref.current = init(); - } - return ref.current; - } - - /** - * This should only ever be modified on the client otherwise it'll - * persist through server requests. If we need instanced states we - * could lazy-init via root. - */ - var globalProjectionState = { - /** - * Global flag as to whether the tree has animated since the last time - * we resized the window - */ - hasAnimatedSinceResize: true, - /** - * We set this to true once, on the first update. Any nodes added to the tree beyond that - * update will be given a `data-projection-id` attribute. - */ - hasEverUpdated: false, - }; - var id$1 = 1; - function useProjectionId() { - return useConstant(function () { - if (globalProjectionState.hasEverUpdated) { - return id$1++; - } - }); - } - var LayoutGroupContext = React.createContext({}); - - /** - * Internal, exported only for usage in Framer - */ - var SwitchLayoutGroupContext = React.createContext({}); - function useProjection( - projectionId, - _a, - visualElement, - ProjectionNodeConstructor - ) { - var _b; - var layoutId = _a.layoutId, - layout = _a.layout, - drag = _a.drag, - dragConstraints = _a.dragConstraints, - layoutScroll = _a.layoutScroll; - var initialPromotionConfig = React.useContext( - SwitchLayoutGroupContext - ); - if ( - !ProjectionNodeConstructor || - !visualElement || - (visualElement === null || visualElement === void 0 - ? void 0 - : visualElement.projection) - ) { - return; - } - visualElement.projection = new ProjectionNodeConstructor( - projectionId, - visualElement.getLatestValues(), - (_b = visualElement.parent) === null || _b === void 0 - ? void 0 - : _b.projection - ); - visualElement.projection.setOptions({ - layoutId: layoutId, - layout: layout, - alwaysMeasureLayout: - Boolean(drag) || - (dragConstraints && isRefObject(dragConstraints)), - visualElement: visualElement, - scheduleRender: function () { - return visualElement.scheduleRender(); - }, - /** - * TODO: Update options in an effect. This could be tricky as it'll be too late - * to update by the time layout animations run. - * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, - * ensuring it gets called if there's no potential layout animations. - * - */ - animationType: typeof layout === "string" ? layout : "both", - initialPromotionConfig: initialPromotionConfig, - layoutScroll: layoutScroll, - }); - } - var VisualElementHandler = /** @class */ (function (_super) { - tslib.__extends(VisualElementHandler, _super); - function VisualElementHandler() { - return (_super !== null && _super.apply(this, arguments)) || this; - } - /** - * Update visual element props as soon as we know this update is going to be commited. - */ - VisualElementHandler.prototype.getSnapshotBeforeUpdate = function () { - this.updateProps(); - return null; - }; - VisualElementHandler.prototype.componentDidUpdate = function () {}; - VisualElementHandler.prototype.updateProps = function () { - var _a = this.props, - visualElement = _a.visualElement, - props = _a.props; - if (visualElement) visualElement.setProps(props); - }; - VisualElementHandler.prototype.render = function () { - return this.props.children; - }; - return VisualElementHandler; - })(React__default["default"].Component); - - /** - * Create a `motion` component. - * - * This function accepts a Component argument, which can be either a string (ie "div" - * for `motion.div`), or an actual React component. - * - * Alongside this is a config option which provides a way of rendering the provided - * component "offline", or outside the React render cycle. - */ - function createMotionComponent(_a) { - var preloadedFeatures = _a.preloadedFeatures, - createVisualElement = _a.createVisualElement, - projectionNodeConstructor = _a.projectionNodeConstructor, - useRender = _a.useRender, - useVisualState = _a.useVisualState, - Component = _a.Component; - preloadedFeatures && loadFeatures(preloadedFeatures); - function MotionComponent(props, externalRef) { - var layoutId = useLayoutId(props); - props = tslib.__assign(tslib.__assign({}, props), { - layoutId: layoutId, - }); - /** - * If we're rendering in a static environment, we only visually update the component - * as a result of a React-rerender rather than interactions or animations. This - * means we don't need to load additional memory structures like VisualElement, - * or any gesture/animation features. - */ - var config = React.useContext(MotionConfigContext); - var features = null; - var context = useCreateMotionContext(props); - /** - * Create a unique projection ID for this component. If a new component is added - * during a layout animation we'll use this to query the DOM and hydrate its ref early, allowing - * us to measure it as soon as any layout effect flushes pending layout animations. - * - * Performance note: It'd be better not to have to search the DOM for these elements. - * For newly-entering components it could be enough to only correct treeScale, in which - * case we could mount in a scale-correction mode. This wouldn't be enough for - * shared element transitions however. Perhaps for those we could revert to a root node - * that gets forceRendered and layout animations are triggered on its layout effect. - */ - var projectionId = config.isStatic ? undefined : useProjectionId(); - /** - * - */ - var visualState = useVisualState(props, config.isStatic); - if (!config.isStatic && isBrowser) { - /** - * Create a VisualElement for this component. A VisualElement provides a common - * interface to renderer-specific APIs (ie DOM/Three.js etc) as well as - * providing a way of rendering to these APIs outside of the React render loop - * for more performant animations and interactions - */ - context.visualElement = useVisualElement( - Component, - visualState, - tslib.__assign(tslib.__assign({}, config), props), - createVisualElement - ); - useProjection( - projectionId, - props, - context.visualElement, - projectionNodeConstructor || - featureDefinitions.projectionNodeConstructor - ); - /** - * Load Motion gesture and animation features. These are rendered as renderless - * components so each feature can optionally make use of React lifecycle methods. - */ - features = useFeatures( - props, - context.visualElement, - preloadedFeatures - ); - } - /** - * The mount order and hierarchy is specific to ensure our element ref - * is hydrated by the time features fire their effects. - */ - return React__namespace.createElement( - VisualElementHandler, - { - visualElement: context.visualElement, - props: tslib.__assign(tslib.__assign({}, config), props), - }, - features, - React__namespace.createElement( - MotionContext.Provider, - { - value: context, - }, - useRender( - Component, - props, - projectionId, - useMotionRef(visualState, context.visualElement, externalRef), - visualState, - config.isStatic, - context.visualElement - ) - ) - ); - } - return React.forwardRef(MotionComponent); - } - function useLayoutId(_a) { - var _b; - var layoutId = _a.layoutId; - var layoutGroupId = - (_b = React.useContext(LayoutGroupContext)) === null || - _b === void 0 - ? void 0 - : _b.id; - return layoutGroupId && layoutId !== undefined - ? layoutGroupId + "-" + layoutId - : layoutId; - } - - /** - * Convert any React component into a `motion` component. The provided component - * **must** use `React.forwardRef` to the underlying DOM component you want to animate. - * - * ```jsx - * const Component = React.forwardRef((props, ref) => { - * return
    - * }) - * - * const MotionComponent = motion(Component) - * ``` - * - * @public - */ - function createMotionProxy(createConfig) { - function custom(Component, customMotionComponentConfig) { - if (customMotionComponentConfig === void 0) { - customMotionComponentConfig = {}; - } - return createMotionComponent( - createConfig(Component, customMotionComponentConfig) - ); - } - if (typeof Proxy === "undefined") { - return custom; - } - /** - * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. - * Rather than generating them anew every render. - */ - var componentCache = new Map(); - return new Proxy(custom, { - /** - * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. - * The prop name is passed through as `key` and we can use that to generate a `motion` - * DOM component with that name. - */ - get: function (_target, key) { - /** - * If this element doesn't exist in the component cache, create it and cache. - */ - if (!componentCache.has(key)) { - componentCache.set(key, custom(key)); - } - return componentCache.get(key); - }, - }); - } - - /** - * We keep these listed seperately as we use the lowercase tag names as part - * of the runtime bundle to detect SVG components - */ - var lowercaseSVGElements = [ - "animate", - "circle", - "defs", - "desc", - "ellipse", - "g", - "image", - "line", - "filter", - "marker", - "mask", - "metadata", - "path", - "pattern", - "polygon", - "polyline", - "rect", - "stop", - "svg", - "switch", - "symbol", - "text", - "tspan", - "use", - "view", - ]; - function isSVGComponent(Component) { - if ( - /** - * If it's not a string, it's a custom React component. Currently we only support - * HTML custom React components. - */ - typeof Component !== "string" || - /** - * If it contains a dash, the element is a custom HTML webcomponent. - */ - Component.includes("-") - ) { - return false; - } else if ( - /** - * If it's in our list of lowercase SVG tags, it's an SVG component - */ - lowercaseSVGElements.indexOf(Component) > -1 || - /** - * If it contains a capital letter, it's an SVG component - */ - /[A-Z]/.test(Component) - ) { - return true; - } - return false; - } - var scaleCorrectors = {}; - function addScaleCorrector(correctors) { - Object.assign(scaleCorrectors, correctors); - } - - /** - * A list of all transformable axes. We'll use this list to generated a version - * of each axes for each transform. - */ - var transformAxes = ["", "X", "Y", "Z"]; - /** - * An ordered array of each transformable value. By default, transform values - * will be sorted to this order. - */ - var order = ["translate", "scale", "rotate", "skew"]; - /** - * Generate a list of every possible transform key. - */ - var transformProps = ["transformPerspective", "x", "y", "z"]; - order.forEach(function (operationKey) { - return transformAxes.forEach(function (axesKey) { - return transformProps.push(operationKey + axesKey); - }); - }); - /** - * A function to use with Array.sort to sort transform keys by their default order. - */ - function sortTransformProps(a, b) { - return transformProps.indexOf(a) - transformProps.indexOf(b); - } - /** - * A quick lookup for transform props. - */ - var transformPropSet = new Set(transformProps); - function isTransformProp(key) { - return transformPropSet.has(key); - } - /** - * A quick lookup for transform origin props - */ - var transformOriginProps = new Set(["originX", "originY", "originZ"]); - function isTransformOriginProp(key) { - return transformOriginProps.has(key); - } - function isForcedMotionValue(key, _a) { - var layout = _a.layout, - layoutId = _a.layoutId; - return ( - isTransformProp(key) || - isTransformOriginProp(key) || - ((layout || layoutId !== undefined) && - (!!scaleCorrectors[key] || key === "opacity")) - ); - } - var isMotionValue = function (value) { - return Boolean( - value !== null && typeof value === "object" && value.getVelocity - ); - }; - var translateAlias = { - x: "translateX", - y: "translateY", - z: "translateZ", - transformPerspective: "perspective", - }; - /** - * Build a CSS transform style from individual x/y/scale etc properties. - * - * This outputs with a default order of transforms/scales/rotations, this can be customised by - * providing a transformTemplate function. - */ - function buildTransform(_a, _b, transformIsDefault, transformTemplate) { - var transform = _a.transform, - transformKeys = _a.transformKeys; - var _c = _b.enableHardwareAcceleration, - enableHardwareAcceleration = _c === void 0 ? true : _c, - _d = _b.allowTransformNone, - allowTransformNone = _d === void 0 ? true : _d; - // The transform string we're going to build into. - var transformString = ""; - // Transform keys into their default order - this will determine the output order. - transformKeys.sort(sortTransformProps); - // Track whether the defined transform has a defined z so we don't add a - // second to enable hardware acceleration - var transformHasZ = false; - // Loop over each transform and build them into transformString - var numTransformKeys = transformKeys.length; - for (var i = 0; i < numTransformKeys; i++) { - var key = transformKeys[i]; - transformString += "" - .concat(translateAlias[key] || key, "(") - .concat(transform[key], ") "); - if (key === "z") transformHasZ = true; - } - if (!transformHasZ && enableHardwareAcceleration) { - transformString += "translateZ(0)"; - } else { - transformString = transformString.trim(); - } - // If we have a custom `transform` template, pass our transform values and - // generated transformString to that before returning - if (transformTemplate) { - transformString = transformTemplate( - transform, - transformIsDefault ? "" : transformString - ); - } else if (allowTransformNone && transformIsDefault) { - transformString = "none"; - } - return transformString; - } - /** - * Build a transformOrigin style. Uses the same defaults as the browser for - * undefined origins. - */ - function buildTransformOrigin(_a) { - var _b = _a.originX, - originX = _b === void 0 ? "50%" : _b, - _c = _a.originY, - originY = _c === void 0 ? "50%" : _c, - _d = _a.originZ, - originZ = _d === void 0 ? 0 : _d; - return "".concat(originX, " ").concat(originY, " ").concat(originZ); - } - - /** - * Returns true if the provided key is a CSS variable - */ - function isCSSVariable$1(key) { - return key.startsWith("--"); - } - - /** - * Provided a value and a ValueType, returns the value as that value type. - */ - var getValueAsType = function (value, type) { - return type && typeof value === "number" - ? type.transform(value) - : value; - }; - var int = tslib.__assign(tslib.__assign({}, styleValueTypes.number), { - transform: Math.round, - }); - var numberValueTypes = { - // Border props - borderWidth: styleValueTypes.px, - borderTopWidth: styleValueTypes.px, - borderRightWidth: styleValueTypes.px, - borderBottomWidth: styleValueTypes.px, - borderLeftWidth: styleValueTypes.px, - borderRadius: styleValueTypes.px, - radius: styleValueTypes.px, - borderTopLeftRadius: styleValueTypes.px, - borderTopRightRadius: styleValueTypes.px, - borderBottomRightRadius: styleValueTypes.px, - borderBottomLeftRadius: styleValueTypes.px, - // Positioning props - width: styleValueTypes.px, - maxWidth: styleValueTypes.px, - height: styleValueTypes.px, - maxHeight: styleValueTypes.px, - size: styleValueTypes.px, - top: styleValueTypes.px, - right: styleValueTypes.px, - bottom: styleValueTypes.px, - left: styleValueTypes.px, - // Spacing props - padding: styleValueTypes.px, - paddingTop: styleValueTypes.px, - paddingRight: styleValueTypes.px, - paddingBottom: styleValueTypes.px, - paddingLeft: styleValueTypes.px, - margin: styleValueTypes.px, - marginTop: styleValueTypes.px, - marginRight: styleValueTypes.px, - marginBottom: styleValueTypes.px, - marginLeft: styleValueTypes.px, - // Transform props - rotate: styleValueTypes.degrees, - rotateX: styleValueTypes.degrees, - rotateY: styleValueTypes.degrees, - rotateZ: styleValueTypes.degrees, - scale: styleValueTypes.scale, - scaleX: styleValueTypes.scale, - scaleY: styleValueTypes.scale, - scaleZ: styleValueTypes.scale, - skew: styleValueTypes.degrees, - skewX: styleValueTypes.degrees, - skewY: styleValueTypes.degrees, - distance: styleValueTypes.px, - translateX: styleValueTypes.px, - translateY: styleValueTypes.px, - translateZ: styleValueTypes.px, - x: styleValueTypes.px, - y: styleValueTypes.px, - z: styleValueTypes.px, - perspective: styleValueTypes.px, - transformPerspective: styleValueTypes.px, - opacity: styleValueTypes.alpha, - originX: styleValueTypes.progressPercentage, - originY: styleValueTypes.progressPercentage, - originZ: styleValueTypes.px, - // Misc - zIndex: int, - // SVG - fillOpacity: styleValueTypes.alpha, - strokeOpacity: styleValueTypes.alpha, - numOctaves: int, - }; - function buildHTMLStyles( - state, - latestValues, - options, - transformTemplate - ) { - var _a; - var style = state.style, - vars = state.vars, - transform = state.transform, - transformKeys = state.transformKeys, - transformOrigin = state.transformOrigin; - // Empty the transformKeys array. As we're throwing out refs to its items - // this might not be as cheap as suspected. Maybe using the array as a buffer - // with a manual incrementation would be better. - transformKeys.length = 0; - // Track whether we encounter any transform or transformOrigin values. - var hasTransform = false; - var hasTransformOrigin = false; - // Does the calculated transform essentially equal "none"? - var transformIsNone = true; - /** - * Loop over all our latest animated values and decide whether to handle them - * as a style or CSS variable. - * - * Transforms and transform origins are kept seperately for further processing. - */ - for (var key in latestValues) { - var value = latestValues[key]; - /** - * If this is a CSS variable we don't do any further processing. - */ - if (isCSSVariable$1(key)) { - vars[key] = value; - continue; - } - // Convert the value to its default value type, ie 0 -> "0px" - var valueType = numberValueTypes[key]; - var valueAsType = getValueAsType(value, valueType); - if (isTransformProp(key)) { - // If this is a transform, flag to enable further transform processing - hasTransform = true; - transform[key] = valueAsType; - transformKeys.push(key); - // If we already know we have a non-default transform, early return - if (!transformIsNone) continue; - // Otherwise check to see if this is a default transform - if ( - value !== - ((_a = valueType.default) !== null && _a !== void 0 ? _a : 0) - ) - transformIsNone = false; - } else if (isTransformOriginProp(key)) { - transformOrigin[key] = valueAsType; - // If this is a transform origin, flag and enable further transform-origin processing - hasTransformOrigin = true; - } else { - style[key] = valueAsType; - } - } - if (hasTransform) { - style.transform = buildTransform( - state, - options, - transformIsNone, - transformTemplate - ); - } else if (transformTemplate) { - style.transform = transformTemplate({}, ""); - } else if (!latestValues.transform && style.transform) { - style.transform = "none"; - } - if (hasTransformOrigin) { - style.transformOrigin = buildTransformOrigin(transformOrigin); - } - } - var createHtmlRenderState = function () { - return { - style: {}, - transform: {}, - transformKeys: [], - transformOrigin: {}, - vars: {}, - }; - }; - function copyRawValuesOnly(target, source, props) { - for (var key in source) { - if ( - !isMotionValue(source[key]) && - !isForcedMotionValue(key, props) - ) { - target[key] = source[key]; - } - } - } - function useInitialMotionValues(_a, visualState, isStatic) { - var transformTemplate = _a.transformTemplate; - return React.useMemo( - function () { - var state = createHtmlRenderState(); - buildHTMLStyles( - state, - visualState, - { - enableHardwareAcceleration: !isStatic, - }, - transformTemplate - ); - var vars = state.vars, - style = state.style; - return tslib.__assign(tslib.__assign({}, vars), style); - }, - [visualState] - ); - } - function useStyle(props, visualState, isStatic) { - var styleProp = props.style || {}; - var style = {}; - /** - * Copy non-Motion Values straight into style - */ - copyRawValuesOnly(style, styleProp, props); - Object.assign( - style, - useInitialMotionValues(props, visualState, isStatic) - ); - if (props.transformValues) { - style = props.transformValues(style); - } - return style; - } - function useHTMLProps(props, visualState, isStatic) { - // The `any` isn't ideal but it is the type of createElement props argument - var htmlProps = {}; - var style = useStyle(props, visualState, isStatic); - if (Boolean(props.drag) && props.dragListener !== false) { - // Disable the ghost element when a user drags - htmlProps.draggable = false; - // Disable text selection - style.userSelect = - style.WebkitUserSelect = - style.WebkitTouchCallout = - "none"; - // Disable scrolling on the draggable direction - style.touchAction = - props.drag === true - ? "none" - : "pan-".concat(props.drag === "x" ? "y" : "x"); - } - htmlProps.style = style; - return htmlProps; - } - - /** - * A list of all valid MotionProps. - * - * @privateRemarks - * This doesn't throw if a `MotionProp` name is missing - it should. - */ - var validMotionProps = new Set([ - "initial", - "animate", - "exit", - "style", - "variants", - "transition", - "transformTemplate", - "transformValues", - "custom", - "inherit", - "layout", - "layoutId", - "layoutDependency", - "onLayoutAnimationStart", - "onLayoutAnimationComplete", - "onLayoutMeasure", - "onBeforeLayoutMeasure", - "onAnimationStart", - "onAnimationComplete", - "onUpdate", - "onDragStart", - "onDrag", - "onDragEnd", - "onMeasureDragConstraints", - "onDirectionLock", - "onDragTransitionEnd", - "drag", - "dragControls", - "dragListener", - "dragConstraints", - "dragDirectionLock", - "dragSnapToOrigin", - "_dragX", - "_dragY", - "dragElastic", - "dragMomentum", - "dragPropagation", - "dragTransition", - "whileDrag", - "onPan", - "onPanStart", - "onPanEnd", - "onPanSessionStart", - "onTap", - "onTapStart", - "onTapCancel", - "onHoverStart", - "onHoverEnd", - "whileFocus", - "whileTap", - "whileHover", - "whileInView", - "onViewportEnter", - "onViewportLeave", - "viewport", - "layoutScroll", - ]); - /** - * Check whether a prop name is a valid `MotionProp` key. - * - * @param key - Name of the property to check - * @returns `true` is key is a valid `MotionProp`. - * - * @public - */ - function isValidMotionProp(key) { - return validMotionProps.has(key); - } - var shouldForward = function (key) { - return !isValidMotionProp(key); - }; - function loadExternalIsValidProp(isValidProp) { - if (!isValidProp) return; - // Explicitly filter our events - shouldForward = function (key) { - return key.startsWith("on") - ? !isValidMotionProp(key) - : isValidProp(key); - }; - } - /** - * Emotion and Styled Components both allow users to pass through arbitrary props to their components - * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which - * of these should be passed to the underlying DOM node. - * - * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props - * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props - * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of - * `@emotion/is-prop-valid`, however to fix this problem we need to use it. - * - * By making it an optionalDependency we can offer this functionality only in the situations where it's - * actually required. - */ - try { - /** - * We attempt to import this package but require won't be defined in esm environments, in that case - * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed - * in favour of explicit injection. - */ - loadExternalIsValidProp( - __webpack_require__( - /*! @emotion/is-prop-valid */ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js" - )["default"] - ); - } catch (_a) { - // We don't need to actually do anything here - the fallback is the existing `isPropValid`. - } - function filterProps(props, isDom, forwardMotionProps) { - var filteredProps = {}; - for (var key in props) { - if ( - shouldForward(key) || - (forwardMotionProps === true && isValidMotionProp(key)) || - (!isDom && !isValidMotionProp(key)) || - // If trying to use native HTML drag events, forward drag listeners - (props["draggable"] && key.startsWith("onDrag")) - ) { - filteredProps[key] = props[key]; - } - } - return filteredProps; - } - function calcOrigin$1(origin, offset, size) { - return typeof origin === "string" - ? origin - : styleValueTypes.px.transform(offset + size * origin); - } - /** - * The SVG transform origin defaults are different to CSS and is less intuitive, - * so we use the measured dimensions of the SVG to reconcile these. - */ - function calcSVGTransformOrigin(dimensions, originX, originY) { - var pxOriginX = calcOrigin$1(originX, dimensions.x, dimensions.width); - var pxOriginY = calcOrigin$1( - originY, - dimensions.y, - dimensions.height - ); - return "".concat(pxOriginX, " ").concat(pxOriginY); - } - var dashKeys = { - offset: "stroke-dashoffset", - array: "stroke-dasharray", - }; - var camelKeys = { - offset: "strokeDashoffset", - array: "strokeDasharray", - }; - /** - * Build SVG path properties. Uses the path's measured length to convert - * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset - * and stroke-dasharray attributes. - * - * This function is mutative to reduce per-frame GC. - */ - function buildSVGPath(attrs, length, spacing, offset, useDashCase) { - if (spacing === void 0) { - spacing = 1; - } - if (offset === void 0) { - offset = 0; - } - if (useDashCase === void 0) { - useDashCase = true; - } - // Normalise path length by setting SVG attribute pathLength to 1 - attrs.pathLength = 1; - // We use dash case when setting attributes directly to the DOM node and camel case - // when defining props on a React component. - var keys = useDashCase ? dashKeys : camelKeys; - // Build the dash offset - attrs[keys.offset] = styleValueTypes.px.transform(-offset); - // Build the dash array - var pathLength = styleValueTypes.px.transform(length); - var pathSpacing = styleValueTypes.px.transform(spacing); - attrs[keys.array] = "".concat(pathLength, " ").concat(pathSpacing); - } - - /** - * Build SVG visual attrbutes, like cx and style.transform - */ - function buildSVGAttrs(state, _a, options, transformTemplate) { - var attrX = _a.attrX, - attrY = _a.attrY, - originX = _a.originX, - originY = _a.originY, - pathLength = _a.pathLength, - _b = _a.pathSpacing, - pathSpacing = _b === void 0 ? 1 : _b, - _c = _a.pathOffset, - pathOffset = _c === void 0 ? 0 : _c, - // This is object creation, which we try to avoid per-frame. - latest = tslib.__rest(_a, [ - "attrX", - "attrY", - "originX", - "originY", - "pathLength", - "pathSpacing", - "pathOffset", - ]); - buildHTMLStyles(state, latest, options, transformTemplate); - state.attrs = state.style; - state.style = {}; - var attrs = state.attrs, - style = state.style, - dimensions = state.dimensions; - /** - * However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs - * and copy it into style. - */ - if (attrs.transform) { - if (dimensions) style.transform = attrs.transform; - delete attrs.transform; - } - // Parse transformOrigin - if ( - dimensions && - (originX !== undefined || originY !== undefined || style.transform) - ) { - style.transformOrigin = calcSVGTransformOrigin( - dimensions, - originX !== undefined ? originX : 0.5, - originY !== undefined ? originY : 0.5 - ); - } - // Treat x/y not as shortcuts but as actual attributes - if (attrX !== undefined) attrs.x = attrX; - if (attrY !== undefined) attrs.y = attrY; - // Build SVG path if one has been defined - if (pathLength !== undefined) { - buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); - } - } - var createSvgRenderState = function () { - return tslib.__assign(tslib.__assign({}, createHtmlRenderState()), { - attrs: {}, - }); - }; - function useSVGProps(props, visualState) { - var visualProps = React.useMemo( - function () { - var state = createSvgRenderState(); - buildSVGAttrs( - state, - visualState, - { - enableHardwareAcceleration: false, - }, - props.transformTemplate - ); - return tslib.__assign(tslib.__assign({}, state.attrs), { - style: tslib.__assign({}, state.style), - }); - }, - [visualState] - ); - if (props.style) { - var rawStyles = {}; - copyRawValuesOnly(rawStyles, props.style, props); - visualProps.style = tslib.__assign( - tslib.__assign({}, rawStyles), - visualProps.style - ); - } - return visualProps; - } - function createUseRender(forwardMotionProps) { - if (forwardMotionProps === void 0) { - forwardMotionProps = false; - } - var useRender = function ( - Component, - props, - projectionId, - ref, - _a, - isStatic - ) { - var latestValues = _a.latestValues; - var useVisualProps = isSVGComponent(Component) - ? useSVGProps - : useHTMLProps; - var visualProps = useVisualProps(props, latestValues, isStatic); - var filteredProps = filterProps( - props, - typeof Component === "string", - forwardMotionProps - ); - var elementProps = tslib.__assign( - tslib.__assign(tslib.__assign({}, filteredProps), visualProps), - { - ref: ref, - } - ); - if (projectionId) { - elementProps["data-projection-id"] = projectionId; - } - return React.createElement(Component, elementProps); - }; - return useRender; - } - var CAMEL_CASE_PATTERN = /([a-z])([A-Z])/g; - var REPLACE_TEMPLATE = "$1-$2"; - /** - * Convert camelCase to dash-case properties. - */ - var camelToDash = function (str) { - return str - .replace(CAMEL_CASE_PATTERN, REPLACE_TEMPLATE) - .toLowerCase(); - }; - function renderHTML(element, _a, styleProp, projection) { - var style = _a.style, - vars = _a.vars; - Object.assign( - element.style, - style, - projection && projection.getProjectionStyles(styleProp) - ); - // Loop over any CSS variables and assign those. - for (var key in vars) { - element.style.setProperty(key, vars[key]); - } - } - - /** - * A set of attribute names that are always read/written as camel case. - */ - var camelCaseAttributes = new Set([ - "baseFrequency", - "diffuseConstant", - "kernelMatrix", - "kernelUnitLength", - "keySplines", - "keyTimes", - "limitingConeAngle", - "markerHeight", - "markerWidth", - "numOctaves", - "targetX", - "targetY", - "surfaceScale", - "specularConstant", - "specularExponent", - "stdDeviation", - "tableValues", - "viewBox", - "gradientTransform", - "pathLength", - ]); - function renderSVG(element, renderState, _styleProp, projection) { - renderHTML(element, renderState, undefined, projection); - for (var key in renderState.attrs) { - element.setAttribute( - !camelCaseAttributes.has(key) ? camelToDash(key) : key, - renderState.attrs[key] - ); - } - } - function scrapeMotionValuesFromProps$1(props) { - var style = props.style; - var newValues = {}; - for (var key in style) { - if (isMotionValue(style[key]) || isForcedMotionValue(key, props)) { - newValues[key] = style[key]; - } - } - return newValues; - } - function scrapeMotionValuesFromProps(props) { - var newValues = scrapeMotionValuesFromProps$1(props); - for (var key in props) { - if (isMotionValue(props[key])) { - var targetKey = - key === "x" || key === "y" ? "attr" + key.toUpperCase() : key; - newValues[targetKey] = props[key]; - } - } - return newValues; - } - function isAnimationControls(v) { - return typeof v === "object" && typeof v.start === "function"; - } - var isKeyframesTarget = function (v) { - return Array.isArray(v); - }; - var isCustomValue = function (v) { - return Boolean(v && typeof v === "object" && v.mix && v.toValue); - }; - var resolveFinalValueInKeyframes = function (v) { - // TODO maybe throw if v.length - 1 is placeholder token? - return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; - }; - - /** - * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself - * - * TODO: Remove and move to library - */ - function resolveMotionValue(value) { - var unwrappedValue = isMotionValue(value) ? value.get() : value; - return isCustomValue(unwrappedValue) - ? unwrappedValue.toValue() - : unwrappedValue; - } - function makeState(_a, props, context, presenceContext) { - var scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps, - createRenderState = _a.createRenderState, - onMount = _a.onMount; - var state = { - latestValues: makeLatestValues( - props, - context, - presenceContext, - scrapeMotionValuesFromProps - ), - renderState: createRenderState(), - }; - if (onMount) { - state.mount = function (instance) { - return onMount(props, instance, state); - }; - } - return state; - } - var makeUseVisualState = function (config) { - return function (props, isStatic) { - var context = React.useContext(MotionContext); - var presenceContext = React.useContext(PresenceContext); - return isStatic - ? makeState(config, props, context, presenceContext) - : useConstant(function () { - return makeState(config, props, context, presenceContext); - }); - }; - }; - function makeLatestValues( - props, - context, - presenceContext, - scrapeMotionValues - ) { - var values = {}; - var blockInitialAnimation = - (presenceContext === null || presenceContext === void 0 - ? void 0 - : presenceContext.initial) === false; - var motionValues = scrapeMotionValues(props); - for (var key in motionValues) { - values[key] = resolveMotionValue(motionValues[key]); - } - var initial = props.initial, - animate = props.animate; - var isControllingVariants = checkIfControllingVariants(props); - var isVariantNode = checkIfVariantNode(props); - if ( - context && - isVariantNode && - !isControllingVariants && - props.inherit !== false - ) { - initial !== null && initial !== void 0 - ? initial - : (initial = context.initial); - animate !== null && animate !== void 0 - ? animate - : (animate = context.animate); - } - var initialAnimationIsBlocked = - blockInitialAnimation || initial === false; - var variantToSet = initialAnimationIsBlocked ? animate : initial; - if ( - variantToSet && - typeof variantToSet !== "boolean" && - !isAnimationControls(variantToSet) - ) { - var list = Array.isArray(variantToSet) - ? variantToSet - : [variantToSet]; - list.forEach(function (definition) { - var resolved = resolveVariantFromProps(props, definition); - if (!resolved) return; - var transitionEnd = resolved.transitionEnd; - resolved.transition; - var target = tslib.__rest(resolved, [ - "transitionEnd", - "transition", - ]); - for (var key in target) { - var valueTarget = target[key]; - if (Array.isArray(valueTarget)) { - /** - * Take final keyframe if the initial animation is blocked because - * we want to initialise at the end of that blocked animation. - */ - var index = initialAnimationIsBlocked - ? valueTarget.length - 1 - : 0; - valueTarget = valueTarget[index]; - } - if (valueTarget !== null) { - values[key] = valueTarget; - } - } - for (var key in transitionEnd) values[key] = transitionEnd[key]; - }); - } - return values; - } - var svgMotionConfig = { - useVisualState: makeUseVisualState({ - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, - createRenderState: createSvgRenderState, - onMount: function (props, instance, _a) { - var renderState = _a.renderState, - latestValues = _a.latestValues; - try { - renderState.dimensions = - typeof instance.getBBox === "function" - ? instance.getBBox() - : instance.getBoundingClientRect(); - } catch (e) { - // Most likely trying to measure an unrendered element under Firefox - renderState.dimensions = { - x: 0, - y: 0, - width: 0, - height: 0, - }; - } - buildSVGAttrs( - renderState, - latestValues, - { - enableHardwareAcceleration: false, - }, - props.transformTemplate - ); - renderSVG(instance, renderState); - }, - }), - }; - var htmlMotionConfig = { - useVisualState: makeUseVisualState({ - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, - createRenderState: createHtmlRenderState, - }), - }; - function createDomMotionConfig( - Component, - _a, - preloadedFeatures, - createVisualElement, - projectionNodeConstructor - ) { - var _b = _a.forwardMotionProps, - forwardMotionProps = _b === void 0 ? false : _b; - var baseConfig = isSVGComponent(Component) - ? svgMotionConfig - : htmlMotionConfig; - return tslib.__assign(tslib.__assign({}, baseConfig), { - preloadedFeatures: preloadedFeatures, - useRender: createUseRender(forwardMotionProps), - createVisualElement: createVisualElement, - projectionNodeConstructor: projectionNodeConstructor, - Component: Component, - }); - } - exports.AnimationType = void 0; - (function (AnimationType) { - AnimationType["Animate"] = "animate"; - AnimationType["Hover"] = "whileHover"; - AnimationType["Tap"] = "whileTap"; - AnimationType["Drag"] = "whileDrag"; - AnimationType["Focus"] = "whileFocus"; - AnimationType["InView"] = "whileInView"; - AnimationType["Exit"] = "exit"; - })(exports.AnimationType || (exports.AnimationType = {})); - function addDomEvent(target, eventName, handler, options) { - if (options === void 0) { - options = { - passive: true, - }; - } - target.addEventListener(eventName, handler, options); - return function () { - return target.removeEventListener(eventName, handler); - }; - } - /** - * Attaches an event listener directly to the provided DOM element. - * - * Bypassing React's event system can be desirable, for instance when attaching non-passive - * event handlers. - * - * ```jsx - * const ref = useRef(null) - * - * useDomEvent(ref, 'wheel', onWheel, { passive: false }) - * - * return
    - * ``` - * - * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. - * @param eventName - Name of the event you want listen for. - * @param handler - Function to fire when receiving the event. - * @param options - Options to pass to `Event.addEventListener`. - * - * @public - */ - function useDomEvent(ref, eventName, handler, options) { - React.useEffect( - function () { - var element = ref.current; - if (handler && element) { - return addDomEvent(element, eventName, handler, options); - } - }, - [ref, eventName, handler, options] - ); - } - - /** - * - * @param props - * @param ref - * @internal - */ - function useFocusGesture(_a) { - var whileFocus = _a.whileFocus, - visualElement = _a.visualElement; - var onFocus = function () { - var _a; - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.Focus, true); - }; - var onBlur = function () { - var _a; - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.Focus, false); - }; - useDomEvent(visualElement, "focus", whileFocus ? onFocus : undefined); - useDomEvent(visualElement, "blur", whileFocus ? onBlur : undefined); - } - function isMouseEvent(event) { - // PointerEvent inherits from MouseEvent so we can't use a straight instanceof check. - if ( - typeof PointerEvent !== "undefined" && - event instanceof PointerEvent - ) { - return !!(event.pointerType === "mouse"); - } - return event instanceof MouseEvent; - } - function isTouchEvent(event) { - var hasTouches = !!event.touches; - return hasTouches; - } - - /** - * Filters out events not attached to the primary pointer (currently left mouse button) - * @param eventHandler - */ - function filterPrimaryPointer(eventHandler) { - return function (event) { - var isMouseEvent = event instanceof MouseEvent; - var isPrimaryPointer = - !isMouseEvent || (isMouseEvent && event.button === 0); - if (isPrimaryPointer) { - eventHandler(event); - } - }; - } - var defaultPagePoint = { - pageX: 0, - pageY: 0, - }; - function pointFromTouch(e, pointType) { - if (pointType === void 0) { - pointType = "page"; - } - var primaryTouch = e.touches[0] || e.changedTouches[0]; - var point = primaryTouch || defaultPagePoint; - return { - x: point[pointType + "X"], - y: point[pointType + "Y"], - }; - } - function pointFromMouse(point, pointType) { - if (pointType === void 0) { - pointType = "page"; - } - return { - x: point[pointType + "X"], - y: point[pointType + "Y"], - }; - } - function extractEventInfo(event, pointType) { - if (pointType === void 0) { - pointType = "page"; - } - return { - point: isTouchEvent(event) - ? pointFromTouch(event, pointType) - : pointFromMouse(event, pointType), - }; - } - var wrapHandler = function (handler, shouldFilterPrimaryPointer) { - if (shouldFilterPrimaryPointer === void 0) { - shouldFilterPrimaryPointer = false; - } - var listener = function (event) { - return handler(event, extractEventInfo(event)); - }; - return shouldFilterPrimaryPointer - ? filterPrimaryPointer(listener) - : listener; - }; - - // We check for event support via functions in case they've been mocked by a testing suite. - var supportsPointerEvents = function () { - return isBrowser && window.onpointerdown === null; - }; - var supportsTouchEvents = function () { - return isBrowser && window.ontouchstart === null; - }; - var supportsMouseEvents = function () { - return isBrowser && window.onmousedown === null; - }; - var mouseEventNames = { - pointerdown: "mousedown", - pointermove: "mousemove", - pointerup: "mouseup", - pointercancel: "mousecancel", - pointerover: "mouseover", - pointerout: "mouseout", - pointerenter: "mouseenter", - pointerleave: "mouseleave", - }; - var touchEventNames = { - pointerdown: "touchstart", - pointermove: "touchmove", - pointerup: "touchend", - pointercancel: "touchcancel", - }; - function getPointerEventName(name) { - if (supportsPointerEvents()) { - return name; - } else if (supportsTouchEvents()) { - return touchEventNames[name]; - } else if (supportsMouseEvents()) { - return mouseEventNames[name]; - } - return name; - } - function addPointerEvent(target, eventName, handler, options) { - return addDomEvent( - target, - getPointerEventName(eventName), - wrapHandler(handler, eventName === "pointerdown"), - options - ); - } - function usePointerEvent(ref, eventName, handler, options) { - return useDomEvent( - ref, - getPointerEventName(eventName), - handler && wrapHandler(handler, eventName === "pointerdown"), - options - ); - } - function createLock(name) { - var lock = null; - return function () { - var openLock = function () { - lock = null; - }; - if (lock === null) { - lock = name; - return openLock; - } - return false; - }; - } - var globalHorizontalLock = createLock("dragHorizontal"); - var globalVerticalLock = createLock("dragVertical"); - function getGlobalLock(drag) { - var lock = false; - if (drag === "y") { - lock = globalVerticalLock(); - } else if (drag === "x") { - lock = globalHorizontalLock(); - } else { - var openHorizontal_1 = globalHorizontalLock(); - var openVertical_1 = globalVerticalLock(); - if (openHorizontal_1 && openVertical_1) { - lock = function () { - openHorizontal_1(); - openVertical_1(); - }; - } else { - // Release the locks because we don't use them - if (openHorizontal_1) openHorizontal_1(); - if (openVertical_1) openVertical_1(); - } - } - return lock; - } - function isDragActive() { - // Check the gesture lock - if we get it, it means no drag gesture is active - // and we can safely fire the tap gesture. - var openGestureLock = getGlobalLock(true); - if (!openGestureLock) return true; - openGestureLock(); - return false; - } - function createHoverEvent(visualElement, isActive, callback) { - return function (event, info) { - var _a; - if (!isMouseEvent(event) || isDragActive()) return; - /** - * Ensure we trigger animations before firing event callback - */ - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.Hover, isActive); - callback === null || callback === void 0 - ? void 0 - : callback(event, info); - }; - } - function useHoverGesture(_a) { - var onHoverStart = _a.onHoverStart, - onHoverEnd = _a.onHoverEnd, - whileHover = _a.whileHover, - visualElement = _a.visualElement; - usePointerEvent( - visualElement, - "pointerenter", - onHoverStart || whileHover - ? createHoverEvent(visualElement, true, onHoverStart) - : undefined, - { - passive: !onHoverStart, - } - ); - usePointerEvent( - visualElement, - "pointerleave", - onHoverEnd || whileHover - ? createHoverEvent(visualElement, false, onHoverEnd) - : undefined, - { - passive: !onHoverEnd, - } - ); - } - - /** - * Recursively traverse up the tree to check whether the provided child node - * is the parent or a descendant of it. - * - * @param parent - Element to find - * @param child - Element to test against parent - */ - var isNodeOrChild = function (parent, child) { - if (!child) { - return false; - } else if (parent === child) { - return true; - } else { - return isNodeOrChild(parent, child.parentElement); - } - }; - function useUnmountEffect(callback) { - return React.useEffect(function () { - return function () { - return callback(); - }; - }, []); - } - - /** - * @param handlers - - * @internal - */ - function useTapGesture(_a) { - var onTap = _a.onTap, - onTapStart = _a.onTapStart, - onTapCancel = _a.onTapCancel, - whileTap = _a.whileTap, - visualElement = _a.visualElement; - var hasPressListeners = - onTap || onTapStart || onTapCancel || whileTap; - var isPressing = React.useRef(false); - var cancelPointerEndListeners = React.useRef(null); - /** - * Only set listener to passive if there are no external listeners. - */ - var eventOptions = { - passive: !(onTapStart || onTap || onTapCancel || onPointerDown), - }; - function removePointerEndListener() { - var _a; - (_a = cancelPointerEndListeners.current) === null || _a === void 0 - ? void 0 - : _a.call(cancelPointerEndListeners); - cancelPointerEndListeners.current = null; - } - function checkPointerEnd() { - var _a; - removePointerEndListener(); - isPressing.current = false; - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.Tap, false); - return !isDragActive(); - } - function onPointerUp(event, info) { - if (!checkPointerEnd()) return; - /** - * We only count this as a tap gesture if the event.target is the same - * as, or a child of, this component's element - */ - !isNodeOrChild(visualElement.getInstance(), event.target) - ? onTapCancel === null || onTapCancel === void 0 - ? void 0 - : onTapCancel(event, info) - : onTap === null || onTap === void 0 - ? void 0 - : onTap(event, info); - } - function onPointerCancel(event, info) { - if (!checkPointerEnd()) return; - onTapCancel === null || onTapCancel === void 0 - ? void 0 - : onTapCancel(event, info); - } - function onPointerDown(event, info) { - var _a; - removePointerEndListener(); - if (isPressing.current) return; - isPressing.current = true; - cancelPointerEndListeners.current = popmotion.pipe( - addPointerEvent(window, "pointerup", onPointerUp, eventOptions), - addPointerEvent( - window, - "pointercancel", - onPointerCancel, - eventOptions - ) - ); - /** - * Ensure we trigger animations before firing event callback - */ - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.Tap, true); - onTapStart === null || onTapStart === void 0 - ? void 0 - : onTapStart(event, info); - } - usePointerEvent( - visualElement, - "pointerdown", - hasPressListeners ? onPointerDown : undefined, - eventOptions - ); - useUnmountEffect(removePointerEndListener); - } - var warned = new Set(); - function warnOnce(condition, message, element) { - if (condition || warned.has(message)) return; - console.warn(message); - if (element) console.warn(element); - warned.add(message); - } - - /** - * Map an IntersectionHandler callback to an element. We only ever make one handler for one - * element, so even though these handlers might all be triggered by different - * observers, we can keep them in the same map. - */ - var observerCallbacks = new WeakMap(); - /** - * Multiple observers can be created for multiple element/document roots. Each with - * different settings. So here we store dictionaries of observers to each root, - * using serialised settings (threshold/margin) as lookup keys. - */ - var observers = new WeakMap(); - var fireObserverCallback = function (entry) { - var _a; - (_a = observerCallbacks.get(entry.target)) === null || _a === void 0 - ? void 0 - : _a(entry); - }; - var fireAllObserverCallbacks = function (entries) { - entries.forEach(fireObserverCallback); - }; - function initIntersectionObserver(_a) { - var root = _a.root, - options = tslib.__rest(_a, ["root"]); - var lookupRoot = root || document; - /** - * If we don't have an observer lookup map for this root, create one. - */ - if (!observers.has(lookupRoot)) { - observers.set(lookupRoot, {}); - } - var rootObservers = observers.get(lookupRoot); - var key = JSON.stringify(options); - /** - * If we don't have an observer for this combination of root and settings, - * create one. - */ - if (!rootObservers[key]) { - rootObservers[key] = new IntersectionObserver( - fireAllObserverCallbacks, - tslib.__assign( - { - root: root, - }, - options - ) - ); - } - return rootObservers[key]; - } - function observeIntersection(element, options, callback) { - var rootInteresectionObserver = initIntersectionObserver(options); - observerCallbacks.set(element, callback); - rootInteresectionObserver.observe(element); - return function () { - observerCallbacks.delete(element); - rootInteresectionObserver.unobserve(element); - }; - } - function useViewport(_a) { - var visualElement = _a.visualElement, - whileInView = _a.whileInView, - onViewportEnter = _a.onViewportEnter, - onViewportLeave = _a.onViewportLeave, - _b = _a.viewport, - viewport = _b === void 0 ? {} : _b; - var state = React.useRef({ - hasEnteredView: false, - isInView: false, - }); - var shouldObserve = Boolean( - whileInView || onViewportEnter || onViewportLeave - ); - if (viewport.once && state.current.hasEnteredView) - shouldObserve = false; - var useObserver = - typeof IntersectionObserver === "undefined" - ? useMissingIntersectionObserver - : useIntersectionObserver; - useObserver(shouldObserve, state.current, visualElement, viewport); - } - var thresholdNames = { - some: 0, - all: 1, - }; - function useIntersectionObserver( - shouldObserve, - state, - visualElement, - _a - ) { - var root = _a.root, - rootMargin = _a.margin, - _b = _a.amount, - amount = _b === void 0 ? "some" : _b, - once = _a.once; - React.useEffect( - function () { - if (!shouldObserve) return; - var options = { - root: root === null || root === void 0 ? void 0 : root.current, - rootMargin: rootMargin, - threshold: - typeof amount === "number" ? amount : thresholdNames[amount], - }; - var intersectionCallback = function (entry) { - var _a; - var isIntersecting = entry.isIntersecting; - /** - * If there's been no change in the viewport state, early return. - */ - if (state.isInView === isIntersecting) return; - state.isInView = isIntersecting; - /** - * Handle hasEnteredView. If this is only meant to run once, and - * element isn't visible, early return. Otherwise set hasEnteredView to true. - */ - if (once && !isIntersecting && state.hasEnteredView) { - return; - } else if (isIntersecting) { - state.hasEnteredView = true; - } - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.InView, isIntersecting); - /** - * Use the latest committed props rather than the ones in scope - * when this observer is created - */ - var props = visualElement.getProps(); - var callback = isIntersecting - ? props.onViewportEnter - : props.onViewportLeave; - callback === null || callback === void 0 - ? void 0 - : callback(entry); - }; - return observeIntersection( - visualElement.getInstance(), - options, - intersectionCallback - ); - }, - [shouldObserve, root, rootMargin, amount] - ); - } - /** - * If IntersectionObserver is missing, we activate inView and fire onViewportEnter - * on mount. This way, the page will be in the state the author expects users - * to see it in for everyone. - */ - function useMissingIntersectionObserver( - shouldObserve, - state, - visualElement, - _a - ) { - var _b = _a.fallback, - fallback = _b === void 0 ? true : _b; - React.useEffect( - function () { - if (!shouldObserve || !fallback) return; - if (env !== "production") { - warnOnce( - false, - "IntersectionObserver not available on this device. whileInView animations will trigger on mount." - ); - } - /** - * Fire this in an rAF because, at this point, the animation state - * won't have flushed for the first time and there's certain logic in - * there that behaves differently on the initial animation. - * - * This hook should be quite rarely called so setting this in an rAF - * is preferred to changing the behaviour of the animation state. - */ - requestAnimationFrame(function () { - var _a; - state.hasEnteredView = true; - var onViewportEnter = visualElement.getProps().onViewportEnter; - onViewportEnter === null || onViewportEnter === void 0 - ? void 0 - : onViewportEnter(null); - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.InView, true); - }); - }, - [shouldObserve] - ); - } - var makeRenderlessComponent = function (hook) { - return function (props) { - hook(props); - return null; - }; - }; - var gestureAnimations = { - inView: makeRenderlessComponent(useViewport), - tap: makeRenderlessComponent(useTapGesture), - focus: makeRenderlessComponent(useFocusGesture), - hover: makeRenderlessComponent(useHoverGesture), - }; - var counter = 0; - var incrementId = function () { - return counter++; - }; - var useId = function () { - return useConstant(incrementId); - }; - /** - * Ideally we'd use the following code to support React 18 optionally. - * But this fairly fails in Webpack (otherwise treeshaking wouldn't work at all). - * Need to come up with a different way of figuring this out. - */ - // export const useId = (React as any).useId - // ? (React as any).useId - // : () => useConstant(incrementId) - - /** - * When a component is the child of `AnimatePresence`, it can use `usePresence` - * to access information about whether it's still present in the React tree. - * - * ```jsx - * import { usePresence } from "framer-motion" - * - * export const Component = () => { - * const [isPresent, safeToRemove] = usePresence() - * - * useEffect(() => { - * !isPresent && setTimeout(safeToRemove, 1000) - * }, [isPresent]) - * - * return
    - * } - * ``` - * - * If `isPresent` is `false`, it means that a component has been removed the tree, but - * `AnimatePresence` won't really remove it until `safeToRemove` has been called. - * - * @public - */ - function usePresence() { - var context = React.useContext(PresenceContext); - if (context === null) return [true, null]; - var isPresent = context.isPresent, - onExitComplete = context.onExitComplete, - register = context.register; - // It's safe to call the following hooks conditionally (after an early return) because the context will always - // either be null or non-null for the lifespan of the component. - // Replace with useId when released in React - var id = useId(); - React.useEffect(function () { - return register(id); - }, []); - var safeToRemove = function () { - return onExitComplete === null || onExitComplete === void 0 - ? void 0 - : onExitComplete(id); - }; - return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; - } - /** - * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. - * There is no `safeToRemove` function. - * - * ```jsx - * import { useIsPresent } from "framer-motion" - * - * export const Component = () => { - * const isPresent = useIsPresent() - * - * useEffect(() => { - * !isPresent && console.log("I've been removed!") - * }, [isPresent]) - * - * return
    - * } - * ``` - * - * @public - */ - function useIsPresent() { - return isPresent(React.useContext(PresenceContext)); - } - function isPresent(context) { - return context === null ? true : context.isPresent; - } - function shallowCompare(next, prev) { - if (!Array.isArray(prev)) return false; - var prevLength = prev.length; - if (prevLength !== next.length) return false; - for (var i = 0; i < prevLength; i++) { - if (prev[i] !== next[i]) return false; - } - return true; - } - - /** - * Converts seconds to milliseconds - * - * @param seconds - Time in seconds. - * @return milliseconds - Converted time in milliseconds. - */ - var secondsToMilliseconds = function (seconds) { - return seconds * 1000; - }; - var easingLookup = { - linear: popmotion.linear, - easeIn: popmotion.easeIn, - easeInOut: popmotion.easeInOut, - easeOut: popmotion.easeOut, - circIn: popmotion.circIn, - circInOut: popmotion.circInOut, - circOut: popmotion.circOut, - backIn: popmotion.backIn, - backInOut: popmotion.backInOut, - backOut: popmotion.backOut, - anticipate: popmotion.anticipate, - bounceIn: popmotion.bounceIn, - bounceInOut: popmotion.bounceInOut, - bounceOut: popmotion.bounceOut, - }; - var easingDefinitionToFunction = function (definition) { - if (Array.isArray(definition)) { - // If cubic bezier definition, create bezier curve - heyListen.invariant( - definition.length === 4, - "Cubic bezier arrays must contain four numerical values." - ); - var _a = tslib.__read(definition, 4), - x1 = _a[0], - y1 = _a[1], - x2 = _a[2], - y2 = _a[3]; - return popmotion.cubicBezier(x1, y1, x2, y2); - } else if (typeof definition === "string") { - // Else lookup from table - heyListen.invariant( - easingLookup[definition] !== undefined, - "Invalid easing type '".concat(definition, "'") - ); - return easingLookup[definition]; - } - return definition; - }; - var isEasingArray = function (ease) { - return Array.isArray(ease) && typeof ease[0] !== "number"; - }; - - /** - * Check if a value is animatable. Examples: - * - * ✅: 100, "100px", "#fff" - * ❌: "block", "url(2.jpg)" - * @param value - * - * @internal - */ - var isAnimatable = function (key, value) { - // If the list of keys tat might be non-animatable grows, replace with Set - if (key === "zIndex") return false; - // If it's a number or a keyframes array, we can animate it. We might at some point - // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this, - // but for now lets leave it like this for performance reasons - if (typeof value === "number" || Array.isArray(value)) return true; - if ( - typeof value === "string" && - // It's animatable if we have a string - styleValueTypes.complex.test(value) && - // And it contains numbers and/or colors - !value.startsWith("url(") // Unless it starts with "url(" - ) { - return true; - } - return false; - }; - var underDampedSpring = function () { - return { - type: "spring", - stiffness: 500, - damping: 25, - restSpeed: 10, - }; - }; - var criticallyDampedSpring = function (to) { - return { - type: "spring", - stiffness: 550, - damping: to === 0 ? 2 * Math.sqrt(550) : 30, - restSpeed: 10, - }; - }; - var linearTween = function () { - return { - type: "keyframes", - ease: "linear", - duration: 0.3, - }; - }; - var keyframes = function (values) { - return { - type: "keyframes", - duration: 0.8, - values: values, - }; - }; - var defaultTransitions = { - x: underDampedSpring, - y: underDampedSpring, - z: underDampedSpring, - rotate: underDampedSpring, - rotateX: underDampedSpring, - rotateY: underDampedSpring, - rotateZ: underDampedSpring, - scaleX: criticallyDampedSpring, - scaleY: criticallyDampedSpring, - scale: criticallyDampedSpring, - opacity: linearTween, - backgroundColor: linearTween, - color: linearTween, - default: criticallyDampedSpring, - }; - var getDefaultTransition = function (valueKey, to) { - var transitionFactory; - if (isKeyframesTarget(to)) { - transitionFactory = keyframes; - } else { - transitionFactory = - defaultTransitions[valueKey] || defaultTransitions.default; - } - return tslib.__assign( - { - to: to, - }, - transitionFactory(to) - ); - }; - - /** - * A map of default value types for common values - */ - var defaultValueTypes = tslib.__assign( - tslib.__assign({}, numberValueTypes), - { - // Color props - color: styleValueTypes.color, - backgroundColor: styleValueTypes.color, - outlineColor: styleValueTypes.color, - fill: styleValueTypes.color, - stroke: styleValueTypes.color, - // Border props - borderColor: styleValueTypes.color, - borderTopColor: styleValueTypes.color, - borderRightColor: styleValueTypes.color, - borderBottomColor: styleValueTypes.color, - borderLeftColor: styleValueTypes.color, - filter: styleValueTypes.filter, - WebkitFilter: styleValueTypes.filter, - } - ); - /** - * Gets the default ValueType for the provided value key - */ - var getDefaultValueType = function (key) { - return defaultValueTypes[key]; - }; - function getAnimatableNone(key, value) { - var _a; - var defaultValueType = getDefaultValueType(key); - if (defaultValueType !== styleValueTypes.filter) - defaultValueType = styleValueTypes.complex; - // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target - return (_a = defaultValueType.getAnimatableNone) === null || - _a === void 0 - ? void 0 - : _a.call(defaultValueType, value); - } - var instantAnimationState = { - current: false, - }; - - /** - * Decide whether a transition is defined on a given Transition. - * This filters out orchestration options and returns true - * if any options are left. - */ - function isTransitionDefined(_a) { - _a.when; - _a.delay; - _a.delayChildren; - _a.staggerChildren; - _a.staggerDirection; - _a.repeat; - _a.repeatType; - _a.repeatDelay; - _a.from; - var transition = tslib.__rest(_a, [ - "when", - "delay", - "delayChildren", - "staggerChildren", - "staggerDirection", - "repeat", - "repeatType", - "repeatDelay", - "from", - ]); - return !!Object.keys(transition).length; - } - var legacyRepeatWarning = false; - /** - * Convert Framer Motion's Transition type into Popmotion-compatible options. - */ - function convertTransitionToAnimationOptions(_a) { - var ease = _a.ease, - times = _a.times, - yoyo = _a.yoyo, - flip = _a.flip, - loop = _a.loop, - transition = tslib.__rest(_a, [ - "ease", - "times", - "yoyo", - "flip", - "loop", - ]); - var options = tslib.__assign({}, transition); - if (times) options["offset"] = times; - /** - * Convert any existing durations from seconds to milliseconds - */ - if (transition.duration) - options["duration"] = secondsToMilliseconds(transition.duration); - if (transition.repeatDelay) - options.repeatDelay = secondsToMilliseconds(transition.repeatDelay); - /** - * Map easing names to Popmotion's easing functions - */ - if (ease) { - options["ease"] = isEasingArray(ease) - ? ease.map(easingDefinitionToFunction) - : easingDefinitionToFunction(ease); - } - /** - * Support legacy transition API - */ - if (transition.type === "tween") options.type = "keyframes"; - /** - * TODO: These options are officially removed from the API. - */ - if (yoyo || loop || flip) { - heyListen.warning( - !legacyRepeatWarning, - "yoyo, loop and flip have been removed from the API. Replace with repeat and repeatType options." - ); - legacyRepeatWarning = true; - if (yoyo) { - options.repeatType = "reverse"; - } else if (loop) { - options.repeatType = "loop"; - } else if (flip) { - options.repeatType = "mirror"; - } - options.repeat = loop || yoyo || flip || transition.repeat; - } - /** - * TODO: Popmotion 9 has the ability to automatically detect whether to use - * a keyframes or spring animation, but does so by detecting velocity and other spring options. - * It'd be good to introduce a similar thing here. - */ - if (transition.type !== "spring") options.type = "keyframes"; - return options; - } - /** - * Get the delay for a value by checking Transition with decreasing specificity. - */ - function getDelayFromTransition(transition, key) { - var _a, _b; - var valueTransition = getValueTransition(transition, key) || {}; - return (_b = - (_a = valueTransition.delay) !== null && _a !== void 0 - ? _a - : transition.delay) !== null && _b !== void 0 - ? _b - : 0; - } - function hydrateKeyframes(options) { - if (Array.isArray(options.to) && options.to[0] === null) { - options.to = tslib.__spreadArray( - [], - tslib.__read(options.to), - false - ); - options.to[0] = options.from; - } - return options; - } - function getPopmotionAnimationOptions(transition, options, key) { - var _a; - if (Array.isArray(options.to)) { - (_a = transition.duration) !== null && _a !== void 0 - ? _a - : (transition.duration = 0.8); - } - hydrateKeyframes(options); - /** - * Get a default transition if none is determined to be defined. - */ - if (!isTransitionDefined(transition)) { - transition = tslib.__assign( - tslib.__assign({}, transition), - getDefaultTransition(key, options.to) - ); - } - return tslib.__assign( - tslib.__assign({}, options), - convertTransitionToAnimationOptions(transition) - ); - } - /** - * - */ - function getAnimation(key, value, target, transition, onComplete) { - var _a; - var valueTransition = getValueTransition(transition, key); - var origin = - (_a = valueTransition.from) !== null && _a !== void 0 - ? _a - : value.get(); - var isTargetAnimatable = isAnimatable(key, target); - if ( - origin === "none" && - isTargetAnimatable && - typeof target === "string" - ) { - /** - * If we're trying to animate from "none", try and get an animatable version - * of the target. This could be improved to work both ways. - */ - origin = getAnimatableNone(key, target); - } else if (isZero(origin) && typeof target === "string") { - origin = getZeroUnit(target); - } else if ( - !Array.isArray(target) && - isZero(target) && - typeof origin === "string" - ) { - target = getZeroUnit(origin); - } - var isOriginAnimatable = isAnimatable(key, origin); - heyListen.warning( - isOriginAnimatable === isTargetAnimatable, - "You are trying to animate " - .concat(key, ' from "') - .concat(origin, '" to "') - .concat(target, '". ') - .concat( - origin, - " is not an animatable value - to enable this animation set " - ) - .concat(origin, " to a value animatable to ") - .concat(target, " via the `style` property.") - ); - function start() { - var options = { - from: origin, - to: target, - velocity: value.getVelocity(), - onComplete: onComplete, - onUpdate: function (v) { - return value.set(v); - }, - }; - return valueTransition.type === "inertia" || - valueTransition.type === "decay" - ? popmotion.inertia( - tslib.__assign(tslib.__assign({}, options), valueTransition) - ) - : popmotion.animate( - tslib.__assign( - tslib.__assign( - {}, - getPopmotionAnimationOptions( - valueTransition, - options, - key - ) - ), - { - onUpdate: function (v) { - var _a; - options.onUpdate(v); - (_a = valueTransition.onUpdate) === null || - _a === void 0 - ? void 0 - : _a.call(valueTransition, v); - }, - onComplete: function () { - var _a; - options.onComplete(); - (_a = valueTransition.onComplete) === null || - _a === void 0 - ? void 0 - : _a.call(valueTransition); - }, - } - ) - ); - } - function set() { - var _a, _b; - var finalTarget = resolveFinalValueInKeyframes(target); - value.set(finalTarget); - onComplete(); - (_a = - valueTransition === null || valueTransition === void 0 - ? void 0 - : valueTransition.onUpdate) === null || _a === void 0 - ? void 0 - : _a.call(valueTransition, finalTarget); - (_b = - valueTransition === null || valueTransition === void 0 - ? void 0 - : valueTransition.onComplete) === null || _b === void 0 - ? void 0 - : _b.call(valueTransition); - return { - stop: function () {}, - }; - } - return !isOriginAnimatable || - !isTargetAnimatable || - valueTransition.type === false - ? set - : start; - } - function isZero(value) { - return ( - value === 0 || - (typeof value === "string" && - parseFloat(value) === 0 && - value.indexOf(" ") === -1) - ); - } - function getZeroUnit(potentialUnitType) { - return typeof potentialUnitType === "number" - ? 0 - : getAnimatableNone("", potentialUnitType); - } - function getValueTransition(transition, key) { - return transition[key] || transition["default"] || transition; - } - /** - * Start animation on a MotionValue. This function is an interface between - * Framer Motion and Popmotion - */ - function startAnimation(key, value, target, transition) { - if (transition === void 0) { - transition = {}; - } - if (instantAnimationState.current) { - transition = { - type: false, - }; - } - return value.start(function (onComplete) { - var delayTimer; - var controls; - var animation = getAnimation( - key, - value, - target, - transition, - onComplete - ); - var delay = getDelayFromTransition(transition, key); - var start = function () { - return (controls = animation()); - }; - if (delay) { - delayTimer = window.setTimeout( - start, - secondsToMilliseconds(delay) - ); - } else { - start(); - } - return function () { - clearTimeout(delayTimer); - controls === null || controls === void 0 - ? void 0 - : controls.stop(); - }; - }); - } - - /** - * Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1" - */ - var isNumericalString = function (v) { - return /^\-?\d*\.?\d+$/.test(v); - }; - - /** - * Check if the value is a zero value string like "0px" or "0%" - */ - var isZeroValueString = function (v) { - return /^0[^.\s]+$/.test(v); - }; - function addUniqueItem(arr, item) { - arr.indexOf(item) === -1 && arr.push(item); - } - function removeItem(arr, item) { - var index = arr.indexOf(item); - index > -1 && arr.splice(index, 1); - } - // Adapted from array-move - function moveItem(_a, fromIndex, toIndex) { - var _b = tslib.__read(_a), - arr = _b.slice(0); - var startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex; - if (startIndex >= 0 && startIndex < arr.length) { - var endIndex = toIndex < 0 ? arr.length + toIndex : toIndex; - var _c = tslib.__read(arr.splice(fromIndex, 1), 1), - item = _c[0]; - arr.splice(endIndex, 0, item); - } - return arr; - } - var SubscriptionManager = /** @class */ (function () { - function SubscriptionManager() { - this.subscriptions = []; - } - SubscriptionManager.prototype.add = function (handler) { - var _this = this; - addUniqueItem(this.subscriptions, handler); - return function () { - return removeItem(_this.subscriptions, handler); - }; - }; - SubscriptionManager.prototype.notify = function (a, b, c) { - var numSubscriptions = this.subscriptions.length; - if (!numSubscriptions) return; - if (numSubscriptions === 1) { - /** - * If there's only a single handler we can just call it without invoking a loop. - */ - this.subscriptions[0](a, b, c); - } else { - for (var i = 0; i < numSubscriptions; i++) { - /** - * Check whether the handler exists before firing as it's possible - * the subscriptions were modified during this loop running. - */ - var handler = this.subscriptions[i]; - handler && handler(a, b, c); - } - } - }; - SubscriptionManager.prototype.getSize = function () { - return this.subscriptions.length; - }; - SubscriptionManager.prototype.clear = function () { - this.subscriptions.length = 0; - }; - return SubscriptionManager; - })(); - var isFloat = function (value) { - return !isNaN(parseFloat(value)); - }; - /** - * `MotionValue` is used to track the state and velocity of motion values. - * - * @public - */ - var MotionValue = /** @class */ (function () { - /** - * @param init - The initiating value - * @param config - Optional configuration options - * - * - `transformer`: A function to transform incoming values with. - * - * @internal - */ - function MotionValue(init) { - var _this = this; - /** - * This will be replaced by the build step with the latest version number. - * When MotionValues are provided to motion components, warn if versions are mixed. - */ - this.version = "6.5.1"; - /** - * Duration, in milliseconds, since last updating frame. - * - * @internal - */ - this.timeDelta = 0; - /** - * Timestamp of the last time this `MotionValue` was updated. - * - * @internal - */ - this.lastUpdated = 0; - /** - * Functions to notify when the `MotionValue` updates. - * - * @internal - */ - this.updateSubscribers = new SubscriptionManager(); - /** - * Functions to notify when the velocity updates. - * - * @internal - */ - this.velocityUpdateSubscribers = new SubscriptionManager(); - /** - * Functions to notify when the `MotionValue` updates and `render` is set to `true`. - * - * @internal - */ - this.renderSubscribers = new SubscriptionManager(); - /** - * Tracks whether this value can output a velocity. Currently this is only true - * if the value is numerical, but we might be able to widen the scope here and support - * other value types. - * - * @internal - */ - this.canTrackVelocity = false; - this.updateAndNotify = function (v, render) { - if (render === void 0) { - render = true; - } - _this.prev = _this.current; - _this.current = v; - // Update timestamp - var _a = sync.getFrameData(), - delta = _a.delta, - timestamp = _a.timestamp; - if (_this.lastUpdated !== timestamp) { - _this.timeDelta = delta; - _this.lastUpdated = timestamp; - sync__default["default"].postRender( - _this.scheduleVelocityCheck - ); - } - // Update update subscribers - if (_this.prev !== _this.current) { - _this.updateSubscribers.notify(_this.current); - } - // Update velocity subscribers - if (_this.velocityUpdateSubscribers.getSize()) { - _this.velocityUpdateSubscribers.notify(_this.getVelocity()); - } - // Update render subscribers - if (render) { - _this.renderSubscribers.notify(_this.current); - } - }; - /** - * Schedule a velocity check for the next frame. - * - * This is an instanced and bound function to prevent generating a new - * function once per frame. - * - * @internal - */ - this.scheduleVelocityCheck = function () { - return sync__default["default"].postRender(_this.velocityCheck); - }; - /** - * Updates `prev` with `current` if the value hasn't been updated this frame. - * This ensures velocity calculations return `0`. - * - * This is an instanced and bound function to prevent generating a new - * function once per frame. - * - * @internal - */ - this.velocityCheck = function (_a) { - var timestamp = _a.timestamp; - if (timestamp !== _this.lastUpdated) { - _this.prev = _this.current; - _this.velocityUpdateSubscribers.notify(_this.getVelocity()); - } - }; - this.hasAnimated = false; - this.prev = this.current = init; - this.canTrackVelocity = isFloat(this.current); - } - /** - * Adds a function that will be notified when the `MotionValue` is updated. - * - * It returns a function that, when called, will cancel the subscription. - * - * When calling `onChange` inside a React component, it should be wrapped with the - * `useEffect` hook. As it returns an unsubscribe function, this should be returned - * from the `useEffect` function to ensure you don't add duplicate subscribers.. - * - * ```jsx - * export const MyComponent = () => { - * const x = useMotionValue(0) - * const y = useMotionValue(0) - * const opacity = useMotionValue(1) - * - * useEffect(() => { - * function updateOpacity() { - * const maxXY = Math.max(x.get(), y.get()) - * const newOpacity = transform(maxXY, [0, 100], [1, 0]) - * opacity.set(newOpacity) - * } - * - * const unsubscribeX = x.onChange(updateOpacity) - * const unsubscribeY = y.onChange(updateOpacity) - * - * return () => { - * unsubscribeX() - * unsubscribeY() - * } - * }, []) - * - * return - * } - * ``` - * - * @privateRemarks - * - * We could look into a `useOnChange` hook if the above lifecycle management proves confusing. - * - * ```jsx - * useOnChange(x, () => {}) - * ``` - * - * @param subscriber - A function that receives the latest value. - * @returns A function that, when called, will cancel this subscription. - * - * @public - */ - MotionValue.prototype.onChange = function (subscription) { - return this.updateSubscribers.add(subscription); - }; - MotionValue.prototype.clearListeners = function () { - this.updateSubscribers.clear(); - }; - /** - * Adds a function that will be notified when the `MotionValue` requests a render. - * - * @param subscriber - A function that's provided the latest value. - * @returns A function that, when called, will cancel this subscription. - * - * @internal - */ - MotionValue.prototype.onRenderRequest = function (subscription) { - // Render immediately - subscription(this.get()); - return this.renderSubscribers.add(subscription); - }; - /** - * Attaches a passive effect to the `MotionValue`. - * - * @internal - */ - MotionValue.prototype.attach = function (passiveEffect) { - this.passiveEffect = passiveEffect; - }; - /** - * Sets the state of the `MotionValue`. - * - * @remarks - * - * ```jsx - * const x = useMotionValue(0) - * x.set(10) - * ``` - * - * @param latest - Latest value to set. - * @param render - Whether to notify render subscribers. Defaults to `true` - * - * @public - */ - MotionValue.prototype.set = function (v, render) { - if (render === void 0) { - render = true; - } - if (!render || !this.passiveEffect) { - this.updateAndNotify(v, render); - } else { - this.passiveEffect(v, this.updateAndNotify); - } - }; - /** - * Returns the latest state of `MotionValue` - * - * @returns - The latest state of `MotionValue` - * - * @public - */ - MotionValue.prototype.get = function () { - return this.current; - }; - /** - * @public - */ - MotionValue.prototype.getPrevious = function () { - return this.prev; - }; - /** - * Returns the latest velocity of `MotionValue` - * - * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. - * - * @public - */ - MotionValue.prototype.getVelocity = function () { - // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful - return this.canTrackVelocity - ? // These casts could be avoided if parseFloat would be typed better - popmotion.velocityPerSecond( - parseFloat(this.current) - parseFloat(this.prev), - this.timeDelta - ) - : 0; - }; - /** - * Registers a new animation to control this `MotionValue`. Only one - * animation can drive a `MotionValue` at one time. - * - * ```jsx - * value.start() - * ``` - * - * @param animation - A function that starts the provided animation - * - * @internal - */ - MotionValue.prototype.start = function (animation) { - var _this = this; - this.stop(); - return new Promise(function (resolve) { - _this.hasAnimated = true; - _this.stopAnimation = animation(resolve); - }).then(function () { - return _this.clearAnimation(); - }); - }; - /** - * Stop the currently active animation. - * - * @public - */ - MotionValue.prototype.stop = function () { - if (this.stopAnimation) this.stopAnimation(); - this.clearAnimation(); - }; - /** - * Returns `true` if this value is currently animating. - * - * @public - */ - MotionValue.prototype.isAnimating = function () { - return !!this.stopAnimation; - }; - MotionValue.prototype.clearAnimation = function () { - this.stopAnimation = null; - }; - /** - * Destroy and clean up subscribers to this `MotionValue`. - * - * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically - * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually - * created a `MotionValue` via the `motionValue` function. - * - * @public - */ - MotionValue.prototype.destroy = function () { - this.updateSubscribers.clear(); - this.renderSubscribers.clear(); - this.stop(); - }; - return MotionValue; - })(); - function motionValue(init) { - return new MotionValue(init); - } - - /** - * Tests a provided value against a ValueType - */ - var testValueType = function (v) { - return function (type) { - return type.test(v); - }; - }; - - /** - * ValueType for "auto" - */ - var auto = { - test: function (v) { - return v === "auto"; - }, - parse: function (v) { - return v; - }, - }; - - /** - * A list of value types commonly used for dimensions - */ - var dimensionValueTypes = [ - styleValueTypes.number, - styleValueTypes.px, - styleValueTypes.percent, - styleValueTypes.degrees, - styleValueTypes.vw, - styleValueTypes.vh, - auto, - ]; - /** - * Tests a dimensional value against the list of dimension ValueTypes - */ - var findDimensionValueType = function (v) { - return dimensionValueTypes.find(testValueType(v)); - }; - - /** - * A list of all ValueTypes - */ - var valueTypes = tslib.__spreadArray( - tslib.__spreadArray([], tslib.__read(dimensionValueTypes), false), - [styleValueTypes.color, styleValueTypes.complex], - false - ); - /** - * Tests a value against the list of ValueTypes - */ - var findValueType = function (v) { - return valueTypes.find(testValueType(v)); - }; - - /** - * Set VisualElement's MotionValue, creating a new MotionValue for it if - * it doesn't exist. - */ - function setMotionValue(visualElement, key, value) { - if (visualElement.hasValue(key)) { - visualElement.getValue(key).set(value); - } else { - visualElement.addValue(key, motionValue(value)); - } - } - function setTarget(visualElement, definition) { - var resolved = resolveVariant(visualElement, definition); - var _a = resolved - ? visualElement.makeTargetAnimatable(resolved, false) - : {}, - _b = _a.transitionEnd, - transitionEnd = _b === void 0 ? {} : _b; - _a.transition; - var target = tslib.__rest(_a, ["transitionEnd", "transition"]); - target = tslib.__assign(tslib.__assign({}, target), transitionEnd); - for (var key in target) { - var value = resolveFinalValueInKeyframes(target[key]); - setMotionValue(visualElement, key, value); - } - } - function setVariants(visualElement, variantLabels) { - var reversedLabels = tslib - .__spreadArray([], tslib.__read(variantLabels), false) - .reverse(); - reversedLabels.forEach(function (key) { - var _a; - var variant = visualElement.getVariant(key); - variant && setTarget(visualElement, variant); - (_a = visualElement.variantChildren) === null || _a === void 0 - ? void 0 - : _a.forEach(function (child) { - setVariants(child, variantLabels); - }); - }); - } - function setValues(visualElement, definition) { - if (Array.isArray(definition)) { - return setVariants(visualElement, definition); - } else if (typeof definition === "string") { - return setVariants(visualElement, [definition]); - } else { - setTarget(visualElement, definition); - } - } - function checkTargetForNewValues(visualElement, target, origin) { - var _a, _b, _c; - var _d; - var newValueKeys = Object.keys(target).filter(function (key) { - return !visualElement.hasValue(key); - }); - var numNewValues = newValueKeys.length; - if (!numNewValues) return; - for (var i = 0; i < numNewValues; i++) { - var key = newValueKeys[i]; - var targetValue = target[key]; - var value = null; - /** - * If the target is a series of keyframes, we can use the first value - * in the array. If this first value is null, we'll still need to read from the DOM. - */ - if (Array.isArray(targetValue)) { - value = targetValue[0]; - } - /** - * If the target isn't keyframes, or the first keyframe was null, we need to - * first check if an origin value was explicitly defined in the transition as "from", - * if not read the value from the DOM. As an absolute fallback, take the defined target value. - */ - if (value === null) { - value = - (_b = - (_a = origin[key]) !== null && _a !== void 0 - ? _a - : visualElement.readValue(key)) !== null && _b !== void 0 - ? _b - : target[key]; - } - /** - * If value is still undefined or null, ignore it. Preferably this would throw, - * but this was causing issues in Framer. - */ - if (value === undefined || value === null) continue; - if ( - typeof value === "string" && - (isNumericalString(value) || isZeroValueString(value)) - ) { - // If this is a number read as a string, ie "0" or "200", convert it to a number - value = parseFloat(value); - } else if ( - !findValueType(value) && - styleValueTypes.complex.test(targetValue) - ) { - value = getAnimatableNone(key, targetValue); - } - visualElement.addValue(key, motionValue(value)); - (_c = (_d = origin)[key]) !== null && _c !== void 0 - ? _c - : (_d[key] = value); - visualElement.setBaseTarget(key, value); - } - } - function getOriginFromTransition(key, transition) { - if (!transition) return; - var valueTransition = - transition[key] || transition["default"] || transition; - return valueTransition.from; - } - function getOrigin(target, transition, visualElement) { - var _a, _b; - var origin = {}; - for (var key in target) { - origin[key] = - (_a = getOriginFromTransition(key, transition)) !== null && - _a !== void 0 - ? _a - : (_b = visualElement.getValue(key)) === null || _b === void 0 - ? void 0 - : _b.get(); - } - return origin; - } - function animateVisualElement(visualElement, definition, options) { - if (options === void 0) { - options = {}; - } - visualElement.notifyAnimationStart(definition); - var animation; - if (Array.isArray(definition)) { - var animations = definition.map(function (variant) { - return animateVariant(visualElement, variant, options); - }); - animation = Promise.all(animations); - } else if (typeof definition === "string") { - animation = animateVariant(visualElement, definition, options); - } else { - var resolvedDefinition = - typeof definition === "function" - ? resolveVariant(visualElement, definition, options.custom) - : definition; - animation = animateTarget( - visualElement, - resolvedDefinition, - options - ); - } - return animation.then(function () { - return visualElement.notifyAnimationComplete(definition); - }); - } - function animateVariant(visualElement, variant, options) { - var _a; - if (options === void 0) { - options = {}; - } - var resolved = resolveVariant(visualElement, variant, options.custom); - var _b = (resolved || {}).transition, - transition = - _b === void 0 ? visualElement.getDefaultTransition() || {} : _b; - if (options.transitionOverride) { - transition = options.transitionOverride; - } - /** - * If we have a variant, create a callback that runs it as an animation. - * Otherwise, we resolve a Promise immediately for a composable no-op. - */ - var getAnimation = resolved - ? function () { - return animateTarget(visualElement, resolved, options); - } - : function () { - return Promise.resolve(); - }; - /** - * If we have children, create a callback that runs all their animations. - * Otherwise, we resolve a Promise immediately for a composable no-op. - */ - var getChildAnimations = ( - (_a = visualElement.variantChildren) === null || _a === void 0 - ? void 0 - : _a.size - ) - ? function (forwardDelay) { - if (forwardDelay === void 0) { - forwardDelay = 0; - } - var _a = transition.delayChildren, - delayChildren = _a === void 0 ? 0 : _a, - staggerChildren = transition.staggerChildren, - staggerDirection = transition.staggerDirection; - return animateChildren( - visualElement, - variant, - delayChildren + forwardDelay, - staggerChildren, - staggerDirection, - options - ); - } - : function () { - return Promise.resolve(); - }; - /** - * If the transition explicitly defines a "when" option, we need to resolve either - * this animation or all children animations before playing the other. - */ - var when = transition.when; - if (when) { - var _c = tslib.__read( - when === "beforeChildren" - ? [getAnimation, getChildAnimations] - : [getChildAnimations, getAnimation], - 2 - ), - first = _c[0], - last = _c[1]; - return first().then(last); - } else { - return Promise.all([ - getAnimation(), - getChildAnimations(options.delay), - ]); - } - } - /** - * @internal - */ - function animateTarget(visualElement, definition, _a) { - var _b; - var _c = _a === void 0 ? {} : _a, - _d = _c.delay, - delay = _d === void 0 ? 0 : _d, - transitionOverride = _c.transitionOverride, - type = _c.type; - var _e = visualElement.makeTargetAnimatable(definition), - _f = _e.transition, - transition = - _f === void 0 ? visualElement.getDefaultTransition() : _f, - transitionEnd = _e.transitionEnd, - target = tslib.__rest(_e, ["transition", "transitionEnd"]); - if (transitionOverride) transition = transitionOverride; - var animations = []; - var animationTypeState = - type && - ((_b = visualElement.animationState) === null || _b === void 0 - ? void 0 - : _b.getState()[type]); - for (var key in target) { - var value = visualElement.getValue(key); - var valueTarget = target[key]; - if ( - !value || - valueTarget === undefined || - (animationTypeState && - shouldBlockAnimation(animationTypeState, key)) - ) { - continue; - } - var valueTransition = tslib.__assign( - { - delay: delay, - }, - transition - ); - /** - * Make animation instant if this is a transform prop and we should reduce motion. - */ - if (visualElement.shouldReduceMotion && isTransformProp(key)) { - valueTransition = tslib.__assign( - tslib.__assign({}, valueTransition), - { - type: false, - delay: 0, - } - ); - } - var animation = startAnimation( - key, - value, - valueTarget, - valueTransition - ); - animations.push(animation); - } - return Promise.all(animations).then(function () { - transitionEnd && setTarget(visualElement, transitionEnd); - }); - } - function animateChildren( - visualElement, - variant, - delayChildren, - staggerChildren, - staggerDirection, - options - ) { - if (delayChildren === void 0) { - delayChildren = 0; - } - if (staggerChildren === void 0) { - staggerChildren = 0; - } - if (staggerDirection === void 0) { - staggerDirection = 1; - } - var animations = []; - var maxStaggerDuration = - (visualElement.variantChildren.size - 1) * staggerChildren; - var generateStaggerDuration = - staggerDirection === 1 - ? function (i) { - if (i === void 0) { - i = 0; - } - return i * staggerChildren; - } - : function (i) { - if (i === void 0) { - i = 0; - } - return maxStaggerDuration - i * staggerChildren; - }; - Array.from(visualElement.variantChildren) - .sort(sortByTreeOrder) - .forEach(function (child, i) { - animations.push( - animateVariant( - child, - variant, - tslib.__assign(tslib.__assign({}, options), { - delay: delayChildren + generateStaggerDuration(i), - }) - ).then(function () { - return child.notifyAnimationComplete(variant); - }) - ); - }); - return Promise.all(animations); - } - function stopAnimation(visualElement) { - visualElement.forEachValue(function (value) { - return value.stop(); - }); - } - function sortByTreeOrder(a, b) { - return a.sortNodePosition(b); - } - /** - * Decide whether we should block this animation. Previously, we achieved this - * just by checking whether the key was listed in protectedKeys, but this - * posed problems if an animation was triggered by afterChildren and protectedKeys - * had been set to true in the meantime. - */ - function shouldBlockAnimation(_a, key) { - var protectedKeys = _a.protectedKeys, - needsAnimating = _a.needsAnimating; - var shouldBlock = - protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; - needsAnimating[key] = false; - return shouldBlock; - } - var variantPriorityOrder = [ - exports.AnimationType.Animate, - exports.AnimationType.InView, - exports.AnimationType.Focus, - exports.AnimationType.Hover, - exports.AnimationType.Tap, - exports.AnimationType.Drag, - exports.AnimationType.Exit, - ]; - var reversePriorityOrder = tslib - .__spreadArray([], tslib.__read(variantPriorityOrder), false) - .reverse(); - var numAnimationTypes = variantPriorityOrder.length; - function animateList(visualElement) { - return function (animations) { - return Promise.all( - animations.map(function (_a) { - var animation = _a.animation, - options = _a.options; - return animateVisualElement(visualElement, animation, options); - }) - ); - }; - } - function createAnimationState(visualElement) { - var animate = animateList(visualElement); - var state = createState(); - var allAnimatedKeys = {}; - var isInitialRender = true; - /** - * This function will be used to reduce the animation definitions for - * each active animation type into an object of resolved values for it. - */ - var buildResolvedTypeValues = function (acc, definition) { - var resolved = resolveVariant(visualElement, definition); - if (resolved) { - resolved.transition; - var transitionEnd = resolved.transitionEnd, - target = tslib.__rest(resolved, [ - "transition", - "transitionEnd", - ]); - acc = tslib.__assign( - tslib.__assign(tslib.__assign({}, acc), target), - transitionEnd - ); - } - return acc; - }; - function isAnimated(key) { - return allAnimatedKeys[key] !== undefined; - } - /** - * This just allows us to inject mocked animation functions - * @internal - */ - function setAnimateFunction(makeAnimator) { - animate = makeAnimator(visualElement); - } - /** - * When we receive new props, we need to: - * 1. Create a list of protected keys for each type. This is a directory of - * value keys that are currently being "handled" by types of a higher priority - * so that whenever an animation is played of a given type, these values are - * protected from being animated. - * 2. Determine if an animation type needs animating. - * 3. Determine if any values have been removed from a type and figure out - * what to animate those to. - */ - function animateChanges(options, changedActiveType) { - var _a; - var props = visualElement.getProps(); - var context = visualElement.getVariantContext(true) || {}; - /** - * A list of animations that we'll build into as we iterate through the animation - * types. This will get executed at the end of the function. - */ - var animations = []; - /** - * Keep track of which values have been removed. Then, as we hit lower priority - * animation types, we can check if they contain removed values and animate to that. - */ - var removedKeys = new Set(); - /** - * A dictionary of all encountered keys. This is an object to let us build into and - * copy it without iteration. Each time we hit an animation type we set its protected - * keys - the keys its not allowed to animate - to the latest version of this object. - */ - var encounteredKeys = {}; - /** - * If a variant has been removed at a given index, and this component is controlling - * variant animations, we want to ensure lower-priority variants are forced to animate. - */ - var removedVariantIndex = Infinity; - var _loop_1 = function (i) { - var type = reversePriorityOrder[i]; - var typeState = state[type]; - var prop = - (_a = props[type]) !== null && _a !== void 0 - ? _a - : context[type]; - var propIsVariant = isVariantLabel(prop); - /** - * If this type has *just* changed isActive status, set activeDelta - * to that status. Otherwise set to null. - */ - var activeDelta = - type === changedActiveType ? typeState.isActive : null; - if (activeDelta === false) removedVariantIndex = i; - /** - * If this prop is an inherited variant, rather than been set directly on the - * component itself, we want to make sure we allow the parent to trigger animations. - * - * TODO: Can probably change this to a !isControllingVariants check - */ - var isInherited = - prop === context[type] && prop !== props[type] && propIsVariant; - /** - * - */ - if ( - isInherited && - isInitialRender && - visualElement.manuallyAnimateOnMount - ) { - isInherited = false; - } - /** - * Set all encountered keys so far as the protected keys for this type. This will - * be any key that has been animated or otherwise handled by active, higher-priortiy types. - */ - typeState.protectedKeys = tslib.__assign({}, encounteredKeys); - // Check if we can skip analysing this prop early - if ( - // If it isn't active and hasn't *just* been set as inactive - (!typeState.isActive && activeDelta === null) || - // If we didn't and don't have any defined prop for this animation type - (!prop && !typeState.prevProp) || - // Or if the prop doesn't define an animation - isAnimationControls(prop) || - typeof prop === "boolean" - ) { - return "continue"; - } - /** - * As we go look through the values defined on this type, if we detect - * a changed value or a value that was removed in a higher priority, we set - * this to true and add this prop to the animation list. - */ - var variantDidChange = checkVariantsDidChange( - typeState.prevProp, - prop - ); - var shouldAnimateType = - variantDidChange || - // If we're making this variant active, we want to always make it active - (type === changedActiveType && - typeState.isActive && - !isInherited && - propIsVariant) || - // If we removed a higher-priority variant (i is in reverse order) - (i > removedVariantIndex && propIsVariant); - /** - * As animations can be set as variant lists, variants or target objects, we - * coerce everything to an array if it isn't one already - */ - var definitionList = Array.isArray(prop) ? prop : [prop]; - /** - * Build an object of all the resolved values. We'll use this in the subsequent - * animateChanges calls to determine whether a value has changed. - */ - var resolvedValues = definitionList.reduce( - buildResolvedTypeValues, - {} - ); - if (activeDelta === false) resolvedValues = {}; - /** - * Now we need to loop through all the keys in the prev prop and this prop, - * and decide: - * 1. If the value has changed, and needs animating - * 2. If it has been removed, and needs adding to the removedKeys set - * 3. If it has been removed in a higher priority type and needs animating - * 4. If it hasn't been removed in a higher priority but hasn't changed, and - * needs adding to the type's protectedKeys list. - */ - var _b = typeState.prevResolvedValues, - prevResolvedValues = _b === void 0 ? {} : _b; - var allKeys = tslib.__assign( - tslib.__assign({}, prevResolvedValues), - resolvedValues - ); - var markToAnimate = function (key) { - shouldAnimateType = true; - removedKeys.delete(key); - typeState.needsAnimating[key] = true; - }; - for (var key in allKeys) { - var next = resolvedValues[key]; - var prev = prevResolvedValues[key]; - // If we've already handled this we can just skip ahead - if (encounteredKeys.hasOwnProperty(key)) continue; - /** - * If the value has changed, we probably want to animate it. - */ - if (next !== prev) { - /** - * If both values are keyframes, we need to shallow compare them to - * detect whether any value has changed. If it has, we animate it. - */ - if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { - if (!shallowCompare(next, prev) || variantDidChange) { - markToAnimate(key); - } else { - /** - * If it hasn't changed, we want to ensure it doesn't animate by - * adding it to the list of protected keys. - */ - typeState.protectedKeys[key] = true; - } - } else if (next !== undefined) { - // If next is defined and doesn't equal prev, it needs animating - markToAnimate(key); - } else { - // If it's undefined, it's been removed. - removedKeys.add(key); - } - } else if (next !== undefined && removedKeys.has(key)) { - /** - * If next hasn't changed and it isn't undefined, we want to check if it's - * been removed by a higher priority - */ - markToAnimate(key); - } else { - /** - * If it hasn't changed, we add it to the list of protected values - * to ensure it doesn't get animated. - */ - typeState.protectedKeys[key] = true; - } - } - /** - * Update the typeState so next time animateChanges is called we can compare the - * latest prop and resolvedValues to these. - */ - typeState.prevProp = prop; - typeState.prevResolvedValues = resolvedValues; - /** - * - */ - if (typeState.isActive) { - encounteredKeys = tslib.__assign( - tslib.__assign({}, encounteredKeys), - resolvedValues - ); - } - if (isInitialRender && visualElement.blockInitialAnimation) { - shouldAnimateType = false; - } - /** - * If this is an inherited prop we want to hard-block animations - * TODO: Test as this should probably still handle animations triggered - * by removed values? - */ - if (shouldAnimateType && !isInherited) { - animations.push.apply( - animations, - tslib.__spreadArray( - [], - tslib.__read( - definitionList.map(function (animation) { - return { - animation: animation, - options: tslib.__assign( - { - type: type, - }, - options - ), - }; - }) - ), - false - ) - ); - } - }; - /** - * Iterate through all animation types in reverse priority order. For each, we want to - * detect which values it's handling and whether or not they've changed (and therefore - * need to be animated). If any values have been removed, we want to detect those in - * lower priority props and flag for animation. - */ - for (var i = 0; i < numAnimationTypes; i++) { - _loop_1(i); - } - allAnimatedKeys = tslib.__assign({}, encounteredKeys); - /** - * If there are some removed value that haven't been dealt with, - * we need to create a new animation that falls back either to the value - * defined in the style prop, or the last read value. - */ - if (removedKeys.size) { - var fallbackAnimation_1 = {}; - removedKeys.forEach(function (key) { - var fallbackTarget = visualElement.getBaseTarget(key); - if (fallbackTarget !== undefined) { - fallbackAnimation_1[key] = fallbackTarget; - } - }); - animations.push({ - animation: fallbackAnimation_1, - }); - } - var shouldAnimate = Boolean(animations.length); - if ( - isInitialRender && - props.initial === false && - !visualElement.manuallyAnimateOnMount - ) { - shouldAnimate = false; - } - isInitialRender = false; - return shouldAnimate ? animate(animations) : Promise.resolve(); - } - /** - * Change whether a certain animation type is active. - */ - function setActive(type, isActive, options) { - var _a; - // If the active state hasn't changed, we can safely do nothing here - if (state[type].isActive === isActive) return Promise.resolve(); - // Propagate active change to children - (_a = visualElement.variantChildren) === null || _a === void 0 - ? void 0 - : _a.forEach(function (child) { - var _a; - return (_a = child.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(type, isActive); - }); - state[type].isActive = isActive; - var animations = animateChanges(options, type); - for (var key in state) { - state[key].protectedKeys = {}; - } - return animations; - } - return { - isAnimated: isAnimated, - animateChanges: animateChanges, - setActive: setActive, - setAnimateFunction: setAnimateFunction, - getState: function () { - return state; - }, - }; - } - function checkVariantsDidChange(prev, next) { - if (typeof next === "string") { - return next !== prev; - } else if (isVariantLabels(next)) { - return !shallowCompare(next, prev); - } - return false; - } - function createTypeState(isActive) { - if (isActive === void 0) { - isActive = false; - } - return { - isActive: isActive, - protectedKeys: {}, - needsAnimating: {}, - prevResolvedValues: {}, - }; - } - function createState() { - var _a; - return ( - (_a = {}), - (_a[exports.AnimationType.Animate] = createTypeState(true)), - (_a[exports.AnimationType.InView] = createTypeState()), - (_a[exports.AnimationType.Hover] = createTypeState()), - (_a[exports.AnimationType.Tap] = createTypeState()), - (_a[exports.AnimationType.Drag] = createTypeState()), - (_a[exports.AnimationType.Focus] = createTypeState()), - (_a[exports.AnimationType.Exit] = createTypeState()), - _a - ); - } - var animations = { - animation: makeRenderlessComponent(function (_a) { - var visualElement = _a.visualElement, - animate = _a.animate; - /** - * We dynamically generate the AnimationState manager as it contains a reference - * to the underlying animation library. We only want to load that if we load this, - * so people can optionally code split it out using the `m` component. - */ - visualElement.animationState || - (visualElement.animationState = - createAnimationState(visualElement)); - /** - * Subscribe any provided AnimationControls to the component's VisualElement - */ - if (isAnimationControls(animate)) { - React.useEffect( - function () { - return animate.subscribe(visualElement); - }, - [animate] - ); - } - }), - exit: makeRenderlessComponent(function (props) { - var custom = props.custom, - visualElement = props.visualElement; - var _a = tslib.__read(usePresence(), 2), - isPresent = _a[0], - safeToRemove = _a[1]; - var presenceContext = React.useContext(PresenceContext); - React.useEffect( - function () { - var _a, _b; - visualElement.isPresent = isPresent; - var animation = - (_a = visualElement.animationState) === null || _a === void 0 - ? void 0 - : _a.setActive(exports.AnimationType.Exit, !isPresent, { - custom: - (_b = - presenceContext === null || - presenceContext === void 0 - ? void 0 - : presenceContext.custom) !== null && - _b !== void 0 - ? _b - : custom, - }); - !isPresent && - (animation === null || animation === void 0 - ? void 0 - : animation.then(safeToRemove)); - }, - [isPresent] - ); - }), - }; - - /** - * @internal - */ - var PanSession = /** @class */ (function () { - function PanSession(event, handlers, _a) { - var _this = this; - var _b = _a === void 0 ? {} : _a, - transformPagePoint = _b.transformPagePoint; - /** - * @internal - */ - this.startEvent = null; - /** - * @internal - */ - this.lastMoveEvent = null; - /** - * @internal - */ - this.lastMoveEventInfo = null; - /** - * @internal - */ - this.handlers = {}; - this.updatePoint = function () { - if (!(_this.lastMoveEvent && _this.lastMoveEventInfo)) return; - var info = getPanInfo(_this.lastMoveEventInfo, _this.history); - var isPanStarted = _this.startEvent !== null; - // Only start panning if the offset is larger than 3 pixels. If we make it - // any larger than this we'll want to reset the pointer history - // on the first update to avoid visual snapping to the cursoe. - var isDistancePastThreshold = - popmotion.distance(info.offset, { - x: 0, - y: 0, - }) >= 3; - if (!isPanStarted && !isDistancePastThreshold) return; - var point = info.point; - var timestamp = sync.getFrameData().timestamp; - _this.history.push( - tslib.__assign(tslib.__assign({}, point), { - timestamp: timestamp, - }) - ); - var _a = _this.handlers, - onStart = _a.onStart, - onMove = _a.onMove; - if (!isPanStarted) { - onStart && onStart(_this.lastMoveEvent, info); - _this.startEvent = _this.lastMoveEvent; - } - onMove && onMove(_this.lastMoveEvent, info); - }; - this.handlePointerMove = function (event, info) { - _this.lastMoveEvent = event; - _this.lastMoveEventInfo = transformPoint( - info, - _this.transformPagePoint - ); - // Because Safari doesn't trigger mouseup events when it's above a `` + if (isMouseEvent(event) && event.buttons === 0) { + _this.handlePointerUp(event, info); + return; + } + // Throttle mouse move event to once per frame + sync__default["default"].update(_this.updatePoint, true); + }; + this.handlePointerUp = function (event, info) { + _this.end(); + var _a = _this.handlers, + onEnd = _a.onEnd, + onSessionEnd = _a.onSessionEnd; + var panInfo = getPanInfo(transformPoint(info, _this.transformPagePoint), _this.history); + if (_this.startEvent && onEnd) { + onEnd(event, panInfo); + } + onSessionEnd && onSessionEnd(event, panInfo); + }; + // If we have more than one touch, don't start detecting this gesture + if (isTouchEvent(event) && event.touches.length > 1) return; + this.handlers = handlers; + this.transformPagePoint = transformPagePoint; + var info = extractEventInfo(event); + var initialInfo = transformPoint(info, this.transformPagePoint); + var point = initialInfo.point; + var timestamp = sync.getFrameData().timestamp; + this.history = [tslib.__assign(tslib.__assign({}, point), { + timestamp: timestamp + })]; + var onSessionStart = handlers.onSessionStart; + onSessionStart && onSessionStart(event, getPanInfo(initialInfo, this.history)); + this.removeListeners = popmotion.pipe(addPointerEvent(window, "pointermove", this.handlePointerMove), addPointerEvent(window, "pointerup", this.handlePointerUp), addPointerEvent(window, "pointercancel", this.handlePointerUp)); + } + PanSession.prototype.updateHandlers = function (handlers) { + this.handlers = handlers; + }; + PanSession.prototype.end = function () { + this.removeListeners && this.removeListeners(); + sync.cancelSync.update(this.updatePoint); + }; + return PanSession; + }(); + function transformPoint(info, transformPagePoint) { + return transformPagePoint ? { + point: transformPagePoint(info.point) + } : info; + } + function subtractPoint(a, b) { + return { + x: a.x - b.x, + y: a.y - b.y + }; + } + function getPanInfo(_a, history) { + var point = _a.point; + return { + point: point, + delta: subtractPoint(point, lastDevicePoint(history)), + offset: subtractPoint(point, startDevicePoint(history)), + velocity: getVelocity(history, 0.1) + }; + } + function startDevicePoint(history) { + return history[0]; + } + function lastDevicePoint(history) { + return history[history.length - 1]; + } + function getVelocity(history, timeDelta) { + if (history.length < 2) { + return { + x: 0, + y: 0 + }; + } + var i = history.length - 1; + var timestampedPoint = null; + var lastPoint = lastDevicePoint(history); + while (i >= 0) { + timestampedPoint = history[i]; + if (lastPoint.timestamp - timestampedPoint.timestamp > secondsToMilliseconds(timeDelta)) { + break; + } + i--; + } + if (!timestampedPoint) { + return { + x: 0, + y: 0 + }; + } + var time = (lastPoint.timestamp - timestampedPoint.timestamp) / 1000; + if (time === 0) { + return { + x: 0, + y: 0 + }; + } + var currentVelocity = { + x: (lastPoint.x - timestampedPoint.x) / time, + y: (lastPoint.y - timestampedPoint.y) / time + }; + if (currentVelocity.x === Infinity) { + currentVelocity.x = 0; + } + if (currentVelocity.y === Infinity) { + currentVelocity.y = 0; + } + return currentVelocity; + } + function calcLength(axis) { + return axis.max - axis.min; + } + function isNear(value, target, maxDistance) { + if (target === void 0) { + target = 0; + } + if (maxDistance === void 0) { + maxDistance = 0.01; + } + return popmotion.distance(value, target) < maxDistance; + } + function calcAxisDelta(delta, source, target, origin) { + if (origin === void 0) { + origin = 0.5; + } + delta.origin = origin; + delta.originPoint = popmotion.mix(source.min, source.max, delta.origin); + delta.scale = calcLength(target) / calcLength(source); + if (isNear(delta.scale, 1, 0.0001) || isNaN(delta.scale)) delta.scale = 1; + delta.translate = popmotion.mix(target.min, target.max, delta.origin) - delta.originPoint; + if (isNear(delta.translate) || isNaN(delta.translate)) delta.translate = 0; + } + function calcBoxDelta(delta, source, target, origin) { + calcAxisDelta(delta.x, source.x, target.x, origin === null || origin === void 0 ? void 0 : origin.originX); + calcAxisDelta(delta.y, source.y, target.y, origin === null || origin === void 0 ? void 0 : origin.originY); + } + function calcRelativeAxis(target, relative, parent) { + target.min = parent.min + relative.min; + target.max = target.min + calcLength(relative); + } + function calcRelativeBox(target, relative, parent) { + calcRelativeAxis(target.x, relative.x, parent.x); + calcRelativeAxis(target.y, relative.y, parent.y); + } + function calcRelativeAxisPosition(target, layout, parent) { + target.min = layout.min - parent.min; + target.max = target.min + calcLength(layout); + } + function calcRelativePosition(target, layout, parent) { + calcRelativeAxisPosition(target.x, layout.x, parent.x); + calcRelativeAxisPosition(target.y, layout.y, parent.y); + } + + /** + * Apply constraints to a point. These constraints are both physical along an + * axis, and an elastic factor that determines how much to constrain the point + * by if it does lie outside the defined parameters. + */ + function applyConstraints(point, _a, elastic) { + var min = _a.min, + max = _a.max; + if (min !== undefined && point < min) { + // If we have a min point defined, and this is outside of that, constrain + point = elastic ? popmotion.mix(min, point, elastic.min) : Math.max(point, min); + } else if (max !== undefined && point > max) { + // If we have a max point defined, and this is outside of that, constrain + point = elastic ? popmotion.mix(max, point, elastic.max) : Math.min(point, max); + } + return point; + } + /** + * Calculate constraints in terms of the viewport when defined relatively to the + * measured axis. This is measured from the nearest edge, so a max constraint of 200 + * on an axis with a max value of 300 would return a constraint of 500 - axis length + */ + function calcRelativeAxisConstraints(axis, min, max) { + return { + min: min !== undefined ? axis.min + min : undefined, + max: max !== undefined ? axis.max + max - (axis.max - axis.min) : undefined + }; + } + /** + * Calculate constraints in terms of the viewport when + * defined relatively to the measured bounding box. + */ + function calcRelativeConstraints(layoutBox, _a) { + var top = _a.top, + left = _a.left, + bottom = _a.bottom, + right = _a.right; + return { + x: calcRelativeAxisConstraints(layoutBox.x, left, right), + y: calcRelativeAxisConstraints(layoutBox.y, top, bottom) + }; + } + /** + * Calculate viewport constraints when defined as another viewport-relative axis + */ + function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { + var _a; + var min = constraintsAxis.min - layoutAxis.min; + var max = constraintsAxis.max - layoutAxis.max; + // If the constraints axis is actually smaller than the layout axis then we can + // flip the constraints + if (constraintsAxis.max - constraintsAxis.min < layoutAxis.max - layoutAxis.min) { + _a = tslib.__read([max, min], 2), min = _a[0], max = _a[1]; + } + return { + min: min, + max: max + }; + } + /** + * Calculate viewport constraints when defined as another viewport-relative box + */ + function calcViewportConstraints(layoutBox, constraintsBox) { + return { + x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), + y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y) + }; + } + /** + * Calculate a transform origin relative to the source axis, between 0-1, that results + * in an asthetically pleasing scale/transform needed to project from source to target. + */ + function calcOrigin(source, target) { + var origin = 0.5; + var sourceLength = calcLength(source); + var targetLength = calcLength(target); + if (targetLength > sourceLength) { + origin = popmotion.progress(target.min, target.max - sourceLength, source.min); + } else if (sourceLength > targetLength) { + origin = popmotion.progress(source.min, source.max - targetLength, target.min); + } + return popmotion.clamp(0, 1, origin); + } + /** + * Rebase the calculated viewport constraints relative to the layout.min point. + */ + function rebaseAxisConstraints(layout, constraints) { + var relativeConstraints = {}; + if (constraints.min !== undefined) { + relativeConstraints.min = constraints.min - layout.min; + } + if (constraints.max !== undefined) { + relativeConstraints.max = constraints.max - layout.min; + } + return relativeConstraints; + } + var defaultElastic = 0.35; + /** + * Accepts a dragElastic prop and returns resolved elastic values for each axis. + */ + function resolveDragElastic(dragElastic) { + if (dragElastic === void 0) { + dragElastic = defaultElastic; + } + if (dragElastic === false) { + dragElastic = 0; + } else if (dragElastic === true) { + dragElastic = defaultElastic; + } + return { + x: resolveAxisElastic(dragElastic, "left", "right"), + y: resolveAxisElastic(dragElastic, "top", "bottom") + }; + } + function resolveAxisElastic(dragElastic, minLabel, maxLabel) { + return { + min: resolvePointElastic(dragElastic, minLabel), + max: resolvePointElastic(dragElastic, maxLabel) + }; + } + function resolvePointElastic(dragElastic, label) { + var _a; + return typeof dragElastic === "number" ? dragElastic : (_a = dragElastic[label]) !== null && _a !== void 0 ? _a : 0; + } + var createAxisDelta = function () { + return { + translate: 0, + scale: 1, + origin: 0, + originPoint: 0 + }; + }; + var createDelta = function () { + return { + x: createAxisDelta(), + y: createAxisDelta() + }; + }; + var createAxis = function () { + return { + min: 0, + max: 0 + }; + }; + var createBox = function () { + return { + x: createAxis(), + y: createAxis() + }; + }; + function eachAxis(callback) { + return [callback("x"), callback("y")]; + } + + /** + * Bounding boxes tend to be defined as top, left, right, bottom. For various operations + * it's easier to consider each axis individually. This function returns a bounding box + * as a map of single-axis min/max values. + */ + function convertBoundingBoxToBox(_a) { + var top = _a.top, + left = _a.left, + right = _a.right, + bottom = _a.bottom; + return { + x: { + min: left, + max: right + }, + y: { + min: top, + max: bottom + } + }; + } + function convertBoxToBoundingBox(_a) { + var x = _a.x, + y = _a.y; + return { + top: y.min, + right: x.max, + bottom: y.max, + left: x.min + }; + } + /** + * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function + * provided by Framer to allow measured points to be corrected for device scaling. This is used + * when measuring DOM elements and DOM event points. + */ + function transformBoxPoints(point, transformPoint) { + if (!transformPoint) return point; + var topLeft = transformPoint({ + x: point.left, + y: point.top + }); + var bottomRight = transformPoint({ + x: point.right, + y: point.bottom + }); + return { + top: topLeft.y, + left: topLeft.x, + bottom: bottomRight.y, + right: bottomRight.x + }; + } + function isIdentityScale(scale) { + return scale === undefined || scale === 1; + } + function hasScale(_a) { + var scale = _a.scale, + scaleX = _a.scaleX, + scaleY = _a.scaleY; + return !isIdentityScale(scale) || !isIdentityScale(scaleX) || !isIdentityScale(scaleY); + } + function hasTransform(values) { + return hasScale(values) || hasTranslate(values.x) || hasTranslate(values.y) || values.z || values.rotate || values.rotateX || values.rotateY; + } + function hasTranslate(value) { + return value && value !== "0%"; + } + + /** + * Scales a point based on a factor and an originPoint + */ + function scalePoint(point, scale, originPoint) { + var distanceFromOrigin = point - originPoint; + var scaled = scale * distanceFromOrigin; + return originPoint + scaled; + } + /** + * Applies a translate/scale delta to a point + */ + function applyPointDelta(point, translate, scale, originPoint, boxScale) { + if (boxScale !== undefined) { + point = scalePoint(point, boxScale, originPoint); + } + return scalePoint(point, scale, originPoint) + translate; + } + /** + * Applies a translate/scale delta to an axis + */ + function applyAxisDelta(axis, translate, scale, originPoint, boxScale) { + if (translate === void 0) { + translate = 0; + } + if (scale === void 0) { + scale = 1; + } + axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale); + } + /** + * Applies a translate/scale delta to a box + */ + function applyBoxDelta(box, _a) { + var x = _a.x, + y = _a.y; + applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); + applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); + } + /** + * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms + * in a tree upon our box before then calculating how to project it into our desired viewport-relative box + * + * This is the final nested loop within updateLayoutDelta for future refactoring + */ + function applyTreeDeltas(box, treeScale, treePath, isSharedTransition) { + var _a, _b; + if (isSharedTransition === void 0) { + isSharedTransition = false; + } + var treeLength = treePath.length; + if (!treeLength) return; + // Reset the treeScale + treeScale.x = treeScale.y = 1; + var node; + var delta; + for (var i = 0; i < treeLength; i++) { + node = treePath[i]; + delta = node.projectionDelta; + if (((_b = (_a = node.instance) === null || _a === void 0 ? void 0 : _a.style) === null || _b === void 0 ? void 0 : _b.display) === "contents") continue; + if (isSharedTransition && node.options.layoutScroll && node.scroll && node !== node.root) { + transformBox(box, { + x: -node.scroll.x, + y: -node.scroll.y + }); + } + if (delta) { + // Incoporate each ancestor's scale into a culmulative treeScale for this component + treeScale.x *= delta.x.scale; + treeScale.y *= delta.y.scale; + // Apply each ancestor's calculated delta into this component's recorded layout box + applyBoxDelta(box, delta); + } + if (isSharedTransition && hasTransform(node.latestValues)) { + transformBox(box, node.latestValues); + } + } + } + function translateAxis(axis, distance) { + axis.min = axis.min + distance; + axis.max = axis.max + distance; + } + /** + * Apply a transform to an axis from the latest resolved motion values. + * This function basically acts as a bridge between a flat motion value map + * and applyAxisDelta + */ + function transformAxis(axis, transforms, _a) { + var _b = tslib.__read(_a, 3), + key = _b[0], + scaleKey = _b[1], + originKey = _b[2]; + var axisOrigin = transforms[originKey] !== undefined ? transforms[originKey] : 0.5; + var originPoint = popmotion.mix(axis.min, axis.max, axisOrigin); + // Apply the axis delta to the final axis + applyAxisDelta(axis, transforms[key], transforms[scaleKey], originPoint, transforms.scale); + } + /** + * The names of the motion values we want to apply as translation, scale and origin. + */ + var xKeys$1 = ["x", "scaleX", "originX"]; + var yKeys$1 = ["y", "scaleY", "originY"]; + /** + * Apply a transform to a box from the latest resolved motion values. + */ + function transformBox(box, transform) { + transformAxis(box.x, transform, xKeys$1); + transformAxis(box.y, transform, yKeys$1); + } + function measureViewportBox(instance, transformPoint) { + return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); + } + function measurePageBox(element, rootProjectionNode, transformPagePoint) { + var viewportBox = measureViewportBox(element, transformPagePoint); + var scroll = rootProjectionNode.scroll; + if (scroll) { + translateAxis(viewportBox.x, scroll.x); + translateAxis(viewportBox.y, scroll.y); + } + return viewportBox; + } + var elementDragControls = new WeakMap(); + /** + * + */ + // let latestPointerEvent: AnyPointerEvent + var VisualElementDragControls = /** @class */function () { + function VisualElementDragControls(visualElement) { + // This is a reference to the global drag gesture lock, ensuring only one component + // can "capture" the drag of one or both axes. + // TODO: Look into moving this into pansession? + this.openGlobalLock = null; + this.isDragging = false; + this.currentDirection = null; + this.originPoint = { + x: 0, + y: 0 + }; + /** + * The permitted boundaries of travel, in pixels. + */ + this.constraints = false; + this.hasMutatedConstraints = false; + /** + * The per-axis resolved elastic values. + */ + this.elastic = createBox(); + this.visualElement = visualElement; + } + VisualElementDragControls.prototype.start = function (originEvent, _a) { + var _this = this; + var _b = _a === void 0 ? {} : _a, + _c = _b.snapToCursor, + snapToCursor = _c === void 0 ? false : _c; + /** + * Don't start dragging if this component is exiting + */ + if (this.visualElement.isPresent === false) return; + var onSessionStart = function (event) { + // Stop any animations on both axis values immediately. This allows the user to throw and catch + // the component. + _this.stopAnimation(); + if (snapToCursor) { + _this.snapToCursor(extractEventInfo(event, "page").point); + } + }; + var onStart = function (event, info) { + var _a; + // Attempt to grab the global drag gesture lock - maybe make this part of PanSession + var _b = _this.getProps(), + drag = _b.drag, + dragPropagation = _b.dragPropagation, + onDragStart = _b.onDragStart; + if (drag && !dragPropagation) { + if (_this.openGlobalLock) _this.openGlobalLock(); + _this.openGlobalLock = getGlobalLock(drag); + // If we don 't have the lock, don't start dragging + if (!_this.openGlobalLock) return; + } + _this.isDragging = true; + _this.currentDirection = null; + _this.resolveConstraints(); + if (_this.visualElement.projection) { + _this.visualElement.projection.isAnimationBlocked = true; + _this.visualElement.projection.target = undefined; + } + /** + * Record gesture origin + */ + eachAxis(function (axis) { + var _a, _b; + var current = _this.getAxisMotionValue(axis).get() || 0; + /** + * If the MotionValue is a percentage value convert to px + */ + if (styleValueTypes.percent.test(current)) { + var measuredAxis = (_b = (_a = _this.visualElement.projection) === null || _a === void 0 ? void 0 : _a.layout) === null || _b === void 0 ? void 0 : _b.actual[axis]; + if (measuredAxis) { + var length_1 = calcLength(measuredAxis); + current = length_1 * (parseFloat(current) / 100); + } + } + _this.originPoint[axis] = current; + }); + // Fire onDragStart event + onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(event, info); + (_a = _this.visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Drag, true); + }; + var onMove = function (event, info) { + // latestPointerEvent = event + var _a = _this.getProps(), + dragPropagation = _a.dragPropagation, + dragDirectionLock = _a.dragDirectionLock, + onDirectionLock = _a.onDirectionLock, + onDrag = _a.onDrag; + // If we didn't successfully receive the gesture lock, early return. + if (!dragPropagation && !_this.openGlobalLock) return; + var offset = info.offset; + // Attempt to detect drag direction if directionLock is true + if (dragDirectionLock && _this.currentDirection === null) { + _this.currentDirection = getCurrentDirection(offset); + // If we've successfully set a direction, notify listener + if (_this.currentDirection !== null) { + onDirectionLock === null || onDirectionLock === void 0 ? void 0 : onDirectionLock(_this.currentDirection); + } + return; + } + // Update each point with the latest position + _this.updateAxis("x", info.point, offset); + _this.updateAxis("y", info.point, offset); + /** + * Ideally we would leave the renderer to fire naturally at the end of + * this frame but if the element is about to change layout as the result + * of a re-render we want to ensure the browser can read the latest + * bounding box to ensure the pointer and element don't fall out of sync. + */ + _this.visualElement.syncRender(); + /** + * This must fire after the syncRender call as it might trigger a state + * change which itself might trigger a layout update. + */ + onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, info); + }; + var onSessionEnd = function (event, info) { + return _this.stop(event, info); + }; + this.panSession = new PanSession(originEvent, { + onSessionStart: onSessionStart, + onStart: onStart, + onMove: onMove, + onSessionEnd: onSessionEnd + }, { + transformPagePoint: this.visualElement.getTransformPagePoint() + }); + }; + VisualElementDragControls.prototype.stop = function (event, info) { + var isDragging = this.isDragging; + this.cancel(); + if (!isDragging) return; + var velocity = info.velocity; + this.startAnimation(velocity); + var onDragEnd = this.getProps().onDragEnd; + onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd(event, info); + }; + VisualElementDragControls.prototype.cancel = function () { + var _a, _b; + this.isDragging = false; + if (this.visualElement.projection) { + this.visualElement.projection.isAnimationBlocked = false; + } + (_a = this.panSession) === null || _a === void 0 ? void 0 : _a.end(); + this.panSession = undefined; + var dragPropagation = this.getProps().dragPropagation; + if (!dragPropagation && this.openGlobalLock) { + this.openGlobalLock(); + this.openGlobalLock = null; + } + (_b = this.visualElement.animationState) === null || _b === void 0 ? void 0 : _b.setActive(exports.AnimationType.Drag, false); + }; + VisualElementDragControls.prototype.updateAxis = function (axis, _point, offset) { + var drag = this.getProps().drag; + // If we're not dragging this axis, do an early return. + if (!offset || !shouldDrag(axis, drag, this.currentDirection)) return; + var axisValue = this.getAxisMotionValue(axis); + var next = this.originPoint[axis] + offset[axis]; + // Apply constraints + if (this.constraints && this.constraints[axis]) { + next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); + } + axisValue.set(next); + }; + VisualElementDragControls.prototype.resolveConstraints = function () { + var _this = this; + var _a = this.getProps(), + dragConstraints = _a.dragConstraints, + dragElastic = _a.dragElastic; + var layout = (this.visualElement.projection || {}).layout; + var prevConstraints = this.constraints; + if (dragConstraints && isRefObject(dragConstraints)) { + if (!this.constraints) { + this.constraints = this.resolveRefConstraints(); + } + } else { + if (dragConstraints && layout) { + this.constraints = calcRelativeConstraints(layout.actual, dragConstraints); + } else { + this.constraints = false; + } + } + this.elastic = resolveDragElastic(dragElastic); + /** + * If we're outputting to external MotionValues, we want to rebase the measured constraints + * from viewport-relative to component-relative. + */ + if (prevConstraints !== this.constraints && layout && this.constraints && !this.hasMutatedConstraints) { + eachAxis(function (axis) { + if (_this.getAxisMotionValue(axis)) { + _this.constraints[axis] = rebaseAxisConstraints(layout.actual[axis], _this.constraints[axis]); + } + }); + } + }; + VisualElementDragControls.prototype.resolveRefConstraints = function () { + var _a = this.getProps(), + constraints = _a.dragConstraints, + onMeasureDragConstraints = _a.onMeasureDragConstraints; + if (!constraints || !isRefObject(constraints)) return false; + var constraintsElement = constraints.current; + heyListen.invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop."); + var projection = this.visualElement.projection; + // TODO + if (!projection || !projection.layout) return false; + var constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); + var measuredConstraints = calcViewportConstraints(projection.layout.actual, constraintsBox); + /** + * If there's an onMeasureDragConstraints listener we call it and + * if different constraints are returned, set constraints to that + */ + if (onMeasureDragConstraints) { + var userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); + this.hasMutatedConstraints = !!userConstraints; + if (userConstraints) { + measuredConstraints = convertBoundingBoxToBox(userConstraints); + } + } + return measuredConstraints; + }; + VisualElementDragControls.prototype.startAnimation = function (velocity) { + var _this = this; + var _a = this.getProps(), + drag = _a.drag, + dragMomentum = _a.dragMomentum, + dragElastic = _a.dragElastic, + dragTransition = _a.dragTransition, + dragSnapToOrigin = _a.dragSnapToOrigin, + onDragTransitionEnd = _a.onDragTransitionEnd; + var constraints = this.constraints || {}; + var momentumAnimations = eachAxis(function (axis) { + var _a; + if (!shouldDrag(axis, drag, _this.currentDirection)) { + return; + } + var transition = (_a = constraints === null || constraints === void 0 ? void 0 : constraints[axis]) !== null && _a !== void 0 ? _a : {}; + if (dragSnapToOrigin) transition = { + min: 0, + max: 0 + }; + /** + * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame + * of spring animations so we should look into adding a disable spring option to `inertia`. + * We could do something here where we affect the `bounceStiffness` and `bounceDamping` + * using the value of `dragElastic`. + */ + var bounceStiffness = dragElastic ? 200 : 1000000; + var bounceDamping = dragElastic ? 40 : 10000000; + var inertia = tslib.__assign(tslib.__assign({ + type: "inertia", + velocity: dragMomentum ? velocity[axis] : 0, + bounceStiffness: bounceStiffness, + bounceDamping: bounceDamping, + timeConstant: 750, + restDelta: 1, + restSpeed: 10 + }, dragTransition), transition); + // If we're not animating on an externally-provided `MotionValue` we can use the + // component's animation controls which will handle interactions with whileHover (etc), + // otherwise we just have to animate the `MotionValue` itself. + return _this.startAxisValueAnimation(axis, inertia); + }); + // Run all animations and then resolve the new drag constraints. + return Promise.all(momentumAnimations).then(onDragTransitionEnd); + }; + VisualElementDragControls.prototype.startAxisValueAnimation = function (axis, transition) { + var axisValue = this.getAxisMotionValue(axis); + return startAnimation(axis, axisValue, 0, transition); + }; + VisualElementDragControls.prototype.stopAnimation = function () { + var _this = this; + eachAxis(function (axis) { + return _this.getAxisMotionValue(axis).stop(); + }); + }; + /** + * Drag works differently depending on which props are provided. + * + * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. + * - Otherwise, we apply the delta to the x/y motion values. + */ + VisualElementDragControls.prototype.getAxisMotionValue = function (axis) { + var _a, _b; + var dragKey = "_drag" + axis.toUpperCase(); + var externalMotionValue = this.visualElement.getProps()[dragKey]; + return externalMotionValue ? externalMotionValue : this.visualElement.getValue(axis, (_b = (_a = this.visualElement.getProps().initial) === null || _a === void 0 ? void 0 : _a[axis]) !== null && _b !== void 0 ? _b : 0); + }; + VisualElementDragControls.prototype.snapToCursor = function (point) { + var _this = this; + eachAxis(function (axis) { + var drag = _this.getProps().drag; + // If we're not dragging this axis, do an early return. + if (!shouldDrag(axis, drag, _this.currentDirection)) return; + var projection = _this.visualElement.projection; + var axisValue = _this.getAxisMotionValue(axis); + if (projection && projection.layout) { + var _a = projection.layout.actual[axis], + min = _a.min, + max = _a.max; + axisValue.set(point[axis] - popmotion.mix(min, max, 0.5)); + } + }); + }; + /** + * When the viewport resizes we want to check if the measured constraints + * have changed and, if so, reposition the element within those new constraints + * relative to where it was before the resize. + */ + VisualElementDragControls.prototype.scalePositionWithinConstraints = function () { + var _this = this; + var _a; + var _b = this.getProps(), + drag = _b.drag, + dragConstraints = _b.dragConstraints; + var projection = this.visualElement.projection; + if (!isRefObject(dragConstraints) || !projection || !this.constraints) return; + /** + * Stop current animations as there can be visual glitching if we try to do + * this mid-animation + */ + this.stopAnimation(); + /** + * Record the relative position of the dragged element relative to the + * constraints box and save as a progress value. + */ + var boxProgress = { + x: 0, + y: 0 + }; + eachAxis(function (axis) { + var axisValue = _this.getAxisMotionValue(axis); + if (axisValue) { + var latest = axisValue.get(); + boxProgress[axis] = calcOrigin({ + min: latest, + max: latest + }, _this.constraints[axis]); + } + }); + /** + * Update the layout of this element and resolve the latest drag constraints + */ + var transformTemplate = this.visualElement.getProps().transformTemplate; + this.visualElement.getInstance().style.transform = transformTemplate ? transformTemplate({}, "") : "none"; + (_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll(); + projection.updateLayout(); + this.resolveConstraints(); + /** + * For each axis, calculate the current progress of the layout axis + * within the new constraints. + */ + eachAxis(function (axis) { + if (!shouldDrag(axis, drag, null)) return; + /** + * Calculate a new transform based on the previous box progress + */ + var axisValue = _this.getAxisMotionValue(axis); + var _a = _this.constraints[axis], + min = _a.min, + max = _a.max; + axisValue.set(popmotion.mix(min, max, boxProgress[axis])); + }); + }; + VisualElementDragControls.prototype.addListeners = function () { + var _this = this; + var _a; + elementDragControls.set(this.visualElement, this); + var element = this.visualElement.getInstance(); + /** + * Attach a pointerdown event listener on this DOM element to initiate drag tracking. + */ + var stopPointerListener = addPointerEvent(element, "pointerdown", function (event) { + var _a = _this.getProps(), + drag = _a.drag, + _b = _a.dragListener, + dragListener = _b === void 0 ? true : _b; + drag && dragListener && _this.start(event); + }); + var measureDragConstraints = function () { + var dragConstraints = _this.getProps().dragConstraints; + if (isRefObject(dragConstraints)) { + _this.constraints = _this.resolveRefConstraints(); + } + }; + var projection = this.visualElement.projection; + var stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); + if (projection && !projection.layout) { + (_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll(); + projection.updateLayout(); + } + measureDragConstraints(); + /** + * Attach a window resize listener to scale the draggable target within its defined + * constraints as the window resizes. + */ + var stopResizeListener = addDomEvent(window, "resize", function () { + return _this.scalePositionWithinConstraints(); + }); + /** + * If the element's layout changes, calculate the delta and apply that to + * the drag gesture's origin point. + */ + projection.addEventListener("didUpdate", function (_a) { + var delta = _a.delta, + hasLayoutChanged = _a.hasLayoutChanged; + if (_this.isDragging && hasLayoutChanged) { + eachAxis(function (axis) { + var motionValue = _this.getAxisMotionValue(axis); + if (!motionValue) return; + _this.originPoint[axis] += delta[axis].translate; + motionValue.set(motionValue.get() + delta[axis].translate); + }); + _this.visualElement.syncRender(); + } + }); + return function () { + stopResizeListener(); + stopPointerListener(); + stopMeasureLayoutListener(); + }; + }; + VisualElementDragControls.prototype.getProps = function () { + var props = this.visualElement.getProps(); + var _a = props.drag, + drag = _a === void 0 ? false : _a, + _b = props.dragDirectionLock, + dragDirectionLock = _b === void 0 ? false : _b, + _c = props.dragPropagation, + dragPropagation = _c === void 0 ? false : _c, + _d = props.dragConstraints, + dragConstraints = _d === void 0 ? false : _d, + _e = props.dragElastic, + dragElastic = _e === void 0 ? defaultElastic : _e, + _f = props.dragMomentum, + dragMomentum = _f === void 0 ? true : _f; + return tslib.__assign(tslib.__assign({}, props), { + drag: drag, + dragDirectionLock: dragDirectionLock, + dragPropagation: dragPropagation, + dragConstraints: dragConstraints, + dragElastic: dragElastic, + dragMomentum: dragMomentum + }); + }; + return VisualElementDragControls; + }(); + function shouldDrag(direction, drag, currentDirection) { + return (drag === true || drag === direction) && (currentDirection === null || currentDirection === direction); + } + /** + * Based on a x/y offset determine the current drag direction. If both axis' offsets are lower + * than the provided threshold, return `null`. + * + * @param offset - The x/y offset from origin. + * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction. + */ + function getCurrentDirection(offset, lockThreshold) { + if (lockThreshold === void 0) { + lockThreshold = 10; + } + var direction = null; + if (Math.abs(offset.y) > lockThreshold) { + direction = "y"; + } else if (Math.abs(offset.x) > lockThreshold) { + direction = "x"; + } + return direction; + } + + /** + * A hook that allows an element to be dragged. + * + * @internal + */ + function useDrag(props) { + var groupDragControls = props.dragControls, + visualElement = props.visualElement; + var dragControls = useConstant(function () { + return new VisualElementDragControls(visualElement); + }); + // If we've been provided a DragControls for manual control over the drag gesture, + // subscribe this component to it on mount. + React.useEffect(function () { + return groupDragControls && groupDragControls.subscribe(dragControls); + }, [dragControls, groupDragControls]); + // Apply the event listeners to the element + React.useEffect(function () { + return dragControls.addListeners(); + }, [dragControls]); + } + + /** + * + * @param handlers - + * @param ref - + * + * @privateRemarks + * Currently this sets new pan gesture functions every render. The memo route has been explored + * in the past but ultimately we're still creating new functions every render. An optimisation + * to explore is creating the pan gestures and loading them into a `ref`. + * + * @internal + */ + function usePanGesture(_a) { + var onPan = _a.onPan, + onPanStart = _a.onPanStart, + onPanEnd = _a.onPanEnd, + onPanSessionStart = _a.onPanSessionStart, + visualElement = _a.visualElement; + var hasPanEvents = onPan || onPanStart || onPanEnd || onPanSessionStart; + var panSession = React.useRef(null); + var transformPagePoint = React.useContext(MotionConfigContext).transformPagePoint; + var handlers = { + onSessionStart: onPanSessionStart, + onStart: onPanStart, + onMove: onPan, + onEnd: function (event, info) { + panSession.current = null; + onPanEnd && onPanEnd(event, info); + } + }; + React.useEffect(function () { + if (panSession.current !== null) { + panSession.current.updateHandlers(handlers); + } + }); + function onPointerDown(event) { + panSession.current = new PanSession(event, handlers, { + transformPagePoint: transformPagePoint + }); + } + usePointerEvent(visualElement, "pointerdown", hasPanEvents && onPointerDown); + useUnmountEffect(function () { + return panSession.current && panSession.current.end(); + }); + } + var drag = { + pan: makeRenderlessComponent(usePanGesture), + drag: makeRenderlessComponent(useDrag) + }; + var names = ["LayoutMeasure", "BeforeLayoutMeasure", "LayoutUpdate", "ViewportBoxUpdate", "Update", "Render", "AnimationComplete", "LayoutAnimationComplete", "AnimationStart", "LayoutAnimationStart", "SetAxisTarget", "Unmount"]; + function createLifecycles() { + var managers = names.map(function () { + return new SubscriptionManager(); + }); + var propSubscriptions = {}; + var lifecycles = { + clearAllListeners: function () { + return managers.forEach(function (manager) { + return manager.clear(); + }); + }, + updatePropListeners: function (props) { + names.forEach(function (name) { + var _a; + var on = "on" + name; + var propListener = props[on]; + // Unsubscribe existing subscription + (_a = propSubscriptions[name]) === null || _a === void 0 ? void 0 : _a.call(propSubscriptions); + // Add new subscription + if (propListener) { + propSubscriptions[name] = lifecycles[on](propListener); + } + }); + } + }; + managers.forEach(function (manager, i) { + lifecycles["on" + names[i]] = function (handler) { + return manager.add(handler); + }; + lifecycles["notify" + names[i]] = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return manager.notify.apply(manager, tslib.__spreadArray([], tslib.__read(args), false)); + }; + }); + return lifecycles; + } + function updateMotionValuesFromProps(element, next, prev) { + var _a; + for (var key in next) { + var nextValue = next[key]; + var prevValue = prev[key]; + if (isMotionValue(nextValue)) { + /** + * If this is a motion value found in props or style, we want to add it + * to our visual element's motion value map. + */ + element.addValue(key, nextValue); + /** + * Check the version of the incoming motion value with this version + * and warn against mismatches. + */ + if (true) { + warnOnce(nextValue.version === "6.5.1", "Attempting to mix Framer Motion versions ".concat(nextValue.version, " with 6.5.1 may not work as expected.")); + } + } else if (isMotionValue(prevValue)) { + /** + * If we're swapping to a new motion value, create a new motion value + * from that + */ + element.addValue(key, motionValue(nextValue)); + } else if (prevValue !== nextValue) { + /** + * If this is a flat value that has changed, update the motion value + * or create one if it doesn't exist. We only want to do this if we're + * not handling the value with our animation state. + */ + if (element.hasValue(key)) { + var existingValue = element.getValue(key); + // TODO: Only update values that aren't being animated or even looked at + !existingValue.hasAnimated && existingValue.set(nextValue); + } else { + element.addValue(key, motionValue((_a = element.getStaticValue(key)) !== null && _a !== void 0 ? _a : nextValue)); + } + } + } + // Handle removed values + for (var key in prev) { + if (next[key] === undefined) element.removeValue(key); + } + return next; + } + var visualElement = function (_a) { + var _b = _a.treeType, + treeType = _b === void 0 ? "" : _b, + build = _a.build, + getBaseTarget = _a.getBaseTarget, + makeTargetAnimatable = _a.makeTargetAnimatable, + measureViewportBox = _a.measureViewportBox, + renderInstance = _a.render, + readValueFromInstance = _a.readValueFromInstance, + removeValueFromRenderState = _a.removeValueFromRenderState, + sortNodePosition = _a.sortNodePosition, + scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps; + return function (_a, options) { + var parent = _a.parent, + props = _a.props, + presenceId = _a.presenceId, + blockInitialAnimation = _a.blockInitialAnimation, + visualState = _a.visualState, + shouldReduceMotion = _a.shouldReduceMotion; + if (options === void 0) { + options = {}; + } + var isMounted = false; + var latestValues = visualState.latestValues, + renderState = visualState.renderState; + /** + * The instance of the render-specific node that will be hydrated by the + * exposed React ref. So for example, this visual element can host a + * HTMLElement, plain object, or Three.js object. The functions provided + * in VisualElementConfig allow us to interface with this instance. + */ + var instance; + /** + * Manages the subscriptions for a visual element's lifecycle, for instance + * onRender + */ + var lifecycles = createLifecycles(); + /** + * A map of all motion values attached to this visual element. Motion + * values are source of truth for any given animated value. A motion + * value might be provided externally by the component via props. + */ + var values = new Map(); + /** + * A map of every subscription that binds the provided or generated + * motion values onChange listeners to this visual element. + */ + var valueSubscriptions = new Map(); + /** + * A reference to the previously-provided motion values as returned + * from scrapeMotionValuesFromProps. We use the keys in here to determine + * if any motion values need to be removed after props are updated. + */ + var prevMotionValues = {}; + /** + * When values are removed from all animation props we need to search + * for a fallback value to animate to. These values are tracked in baseTarget. + */ + var baseTarget = tslib.__assign({}, latestValues); + // Internal methods ======================== + /** + * On mount, this will be hydrated with a callback to disconnect + * this visual element from its parent on unmount. + */ + var removeFromVariantTree; + /** + * Render the element with the latest styles outside of the React + * render lifecycle + */ + function render() { + if (!instance || !isMounted) return; + triggerBuild(); + renderInstance(instance, renderState, props.style, element.projection); + } + function triggerBuild() { + build(element, renderState, latestValues, options, props); + } + function update() { + lifecycles.notifyUpdate(latestValues); + } + /** + * + */ + function bindToMotionValue(key, value) { + var removeOnChange = value.onChange(function (latestValue) { + latestValues[key] = latestValue; + props.onUpdate && sync__default["default"].update(update, false, true); + }); + var removeOnRenderRequest = value.onRenderRequest(element.scheduleRender); + valueSubscriptions.set(key, function () { + removeOnChange(); + removeOnRenderRequest(); + }); + } + /** + * Any motion values that are provided to the element when created + * aren't yet bound to the element, as this would technically be impure. + * However, we iterate through the motion values and set them to the + * initial values for this component. + * + * TODO: This is impure and we should look at changing this to run on mount. + * Doing so will break some tests but this isn't neccessarily a breaking change, + * more a reflection of the test. + */ + var initialMotionValues = scrapeMotionValuesFromProps(props); + for (var key in initialMotionValues) { + var value = initialMotionValues[key]; + if (latestValues[key] !== undefined && isMotionValue(value)) { + value.set(latestValues[key], false); + } + } + /** + * Determine what role this visual element should take in the variant tree. + */ + var isControllingVariants = checkIfControllingVariants(props); + var isVariantNode = checkIfVariantNode(props); + var element = tslib.__assign(tslib.__assign({ + treeType: treeType, + /** + * This is a mirror of the internal instance prop, which keeps + * VisualElement type-compatible with React's RefObject. + */ + current: null, + /** + * The depth of this visual element within the visual element tree. + */ + depth: parent ? parent.depth + 1 : 0, + parent: parent, + children: new Set(), + /** + * + */ + presenceId: presenceId, + shouldReduceMotion: shouldReduceMotion, + /** + * If this component is part of the variant tree, it should track + * any children that are also part of the tree. This is essentially + * a shadow tree to simplify logic around how to stagger over children. + */ + variantChildren: isVariantNode ? new Set() : undefined, + /** + * Whether this instance is visible. This can be changed imperatively + * by the projection tree, is analogous to CSS's visibility in that + * hidden elements should take up layout, and needs enacting by the configured + * render function. + */ + isVisible: undefined, + /** + * Normally, if a component is controlled by a parent's variants, it can + * rely on that ancestor to trigger animations further down the tree. + * However, if a component is created after its parent is mounted, the parent + * won't trigger that mount animation so the child needs to. + * + * TODO: This might be better replaced with a method isParentMounted + */ + manuallyAnimateOnMount: Boolean(parent === null || parent === void 0 ? void 0 : parent.isMounted()), + /** + * This can be set by AnimatePresence to force components that mount + * at the same time as it to mount as if they have initial={false} set. + */ + blockInitialAnimation: blockInitialAnimation, + /** + * Determine whether this component has mounted yet. This is mostly used + * by variant children to determine whether they need to trigger their + * own animations on mount. + */ + isMounted: function () { + return Boolean(instance); + }, + mount: function (newInstance) { + isMounted = true; + instance = element.current = newInstance; + if (element.projection) { + element.projection.mount(newInstance); + } + if (isVariantNode && parent && !isControllingVariants) { + removeFromVariantTree = parent === null || parent === void 0 ? void 0 : parent.addVariantChild(element); + } + values.forEach(function (value, key) { + return bindToMotionValue(key, value); + }); + parent === null || parent === void 0 ? void 0 : parent.children.add(element); + element.setProps(props); + }, + /** + * + */ + unmount: function () { + var _a; + (_a = element.projection) === null || _a === void 0 ? void 0 : _a.unmount(); + sync.cancelSync.update(update); + sync.cancelSync.render(render); + valueSubscriptions.forEach(function (remove) { + return remove(); + }); + removeFromVariantTree === null || removeFromVariantTree === void 0 ? void 0 : removeFromVariantTree(); + parent === null || parent === void 0 ? void 0 : parent.children.delete(element); + lifecycles.clearAllListeners(); + instance = undefined; + isMounted = false; + }, + /** + * Add a child visual element to our set of children. + */ + addVariantChild: function (child) { + var _a; + var closestVariantNode = element.getClosestVariantNode(); + if (closestVariantNode) { + (_a = closestVariantNode.variantChildren) === null || _a === void 0 ? void 0 : _a.add(child); + return function () { + return closestVariantNode.variantChildren.delete(child); + }; + } + }, + sortNodePosition: function (other) { + /** + * If these nodes aren't even of the same type we can't compare their depth. + */ + if (!sortNodePosition || treeType !== other.treeType) return 0; + return sortNodePosition(element.getInstance(), other.getInstance()); + }, + /** + * Returns the closest variant node in the tree starting from + * this visual element. + */ + getClosestVariantNode: function () { + return isVariantNode ? element : parent === null || parent === void 0 ? void 0 : parent.getClosestVariantNode(); + }, + /** + * Expose the latest layoutId prop. + */ + getLayoutId: function () { + return props.layoutId; + }, + /** + * Returns the current instance. + */ + getInstance: function () { + return instance; + }, + /** + * Get/set the latest static values. + */ + getStaticValue: function (key) { + return latestValues[key]; + }, + setStaticValue: function (key, value) { + return latestValues[key] = value; + }, + /** + * Returns the latest motion value state. Currently only used to take + * a snapshot of the visual element - perhaps this can return the whole + * visual state + */ + getLatestValues: function () { + return latestValues; + }, + /** + * Set the visiblity of the visual element. If it's changed, schedule + * a render to reflect these changes. + */ + setVisibility: function (visibility) { + if (element.isVisible === visibility) return; + element.isVisible = visibility; + element.scheduleRender(); + }, + /** + * Make a target animatable by Popmotion. For instance, if we're + * trying to animate width from 100px to 100vw we need to measure 100vw + * in pixels to determine what we really need to animate to. This is also + * pluggable to support Framer's custom value types like Color, + * and CSS variables. + */ + makeTargetAnimatable: function (target, canMutate) { + if (canMutate === void 0) { + canMutate = true; + } + return makeTargetAnimatable(element, target, props, canMutate); + }, + /** + * Measure the current viewport box with or without transforms. + * Only measures axis-aligned boxes, rotate and skew must be manually + * removed with a re-render to work. + */ + measureViewportBox: function () { + return measureViewportBox(instance, props); + }, + // Motion values ======================== + /** + * Add a motion value and bind it to this visual element. + */ + addValue: function (key, value) { + // Remove existing value if it exists + if (element.hasValue(key)) element.removeValue(key); + values.set(key, value); + latestValues[key] = value.get(); + bindToMotionValue(key, value); + }, + /** + * Remove a motion value and unbind any active subscriptions. + */ + removeValue: function (key) { + var _a; + values.delete(key); + (_a = valueSubscriptions.get(key)) === null || _a === void 0 ? void 0 : _a(); + valueSubscriptions.delete(key); + delete latestValues[key]; + removeValueFromRenderState(key, renderState); + }, + /** + * Check whether we have a motion value for this key + */ + hasValue: function (key) { + return values.has(key); + }, + /** + * Get a motion value for this key. If called with a default + * value, we'll create one if none exists. + */ + getValue: function (key, defaultValue) { + var value = values.get(key); + if (value === undefined && defaultValue !== undefined) { + value = motionValue(defaultValue); + element.addValue(key, value); + } + return value; + }, + /** + * Iterate over our motion values. + */ + forEachValue: function (callback) { + return values.forEach(callback); + }, + /** + * If we're trying to animate to a previously unencountered value, + * we need to check for it in our state and as a last resort read it + * directly from the instance (which might have performance implications). + */ + readValue: function (key) { + var _a; + return (_a = latestValues[key]) !== null && _a !== void 0 ? _a : readValueFromInstance(instance, key, options); + }, + /** + * Set the base target to later animate back to. This is currently + * only hydrated on creation and when we first read a value. + */ + setBaseTarget: function (key, value) { + baseTarget[key] = value; + }, + /** + * Find the base target for a value thats been removed from all animation + * props. + */ + getBaseTarget: function (key) { + if (getBaseTarget) { + var target = getBaseTarget(props, key); + if (target !== undefined && !isMotionValue(target)) return target; + } + return baseTarget[key]; + } + }, lifecycles), { + /** + * Build the renderer state based on the latest visual state. + */ + build: function () { + triggerBuild(); + return renderState; + }, + /** + * Schedule a render on the next animation frame. + */ + scheduleRender: function () { + sync__default["default"].render(render, false, true); + }, + /** + * Synchronously fire render. It's prefered that we batch renders but + * in many circumstances, like layout measurement, we need to run this + * synchronously. However in those instances other measures should be taken + * to batch reads/writes. + */ + syncRender: render, + /** + * Update the provided props. Ensure any newly-added motion values are + * added to our map, old ones removed, and listeners updated. + */ + setProps: function (newProps) { + if (newProps.transformTemplate || props.transformTemplate) { + element.scheduleRender(); + } + props = newProps; + lifecycles.updatePropListeners(newProps); + prevMotionValues = updateMotionValuesFromProps(element, scrapeMotionValuesFromProps(props), prevMotionValues); + }, + getProps: function () { + return props; + }, + // Variants ============================== + /** + * Returns the variant definition with a given name. + */ + getVariant: function (name) { + var _a; + return (_a = props.variants) === null || _a === void 0 ? void 0 : _a[name]; + }, + /** + * Returns the defined default transition on this component. + */ + getDefaultTransition: function () { + return props.transition; + }, + getTransformPagePoint: function () { + return props.transformPagePoint; + }, + /** + * Used by child variant nodes to get the closest ancestor variant props. + */ + getVariantContext: function (startAtParent) { + if (startAtParent === void 0) { + startAtParent = false; + } + if (startAtParent) return parent === null || parent === void 0 ? void 0 : parent.getVariantContext(); + if (!isControllingVariants) { + var context_1 = (parent === null || parent === void 0 ? void 0 : parent.getVariantContext()) || {}; + if (props.initial !== undefined) { + context_1.initial = props.initial; + } + return context_1; + } + var context = {}; + for (var i = 0; i < numVariantProps; i++) { + var name_1 = variantProps[i]; + var prop = props[name_1]; + if (isVariantLabel(prop) || prop === false) { + context[name_1] = prop; + } + } + return context; + } + }); + return element; + }; + }; + var variantProps = tslib.__spreadArray(["initial"], tslib.__read(variantPriorityOrder), false); + var numVariantProps = variantProps.length; + function isCSSVariable(value) { + return typeof value === "string" && value.startsWith("var(--"); + } + /** + * Parse Framer's special CSS variable format into a CSS token and a fallback. + * + * ``` + * `var(--foo, #fff)` => [`--foo`, '#fff'] + * ``` + * + * @param current + */ + var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; + function parseCSSVariable(current) { + var match = cssVariableRegex.exec(current); + if (!match) return [,]; + var _a = tslib.__read(match, 3), + token = _a[1], + fallback = _a[2]; + return [token, fallback]; + } + var maxDepth = 4; + function getVariableValue(current, element, depth) { + if (depth === void 0) { + depth = 1; + } + heyListen.invariant(depth <= maxDepth, "Max CSS variable fallback depth detected in property \"".concat(current, "\". This may indicate a circular fallback dependency.")); + var _a = tslib.__read(parseCSSVariable(current), 2), + token = _a[0], + fallback = _a[1]; + // No CSS variable detected + if (!token) return; + // Attempt to read this CSS variable off the element + var resolved = window.getComputedStyle(element).getPropertyValue(token); + if (resolved) { + return resolved.trim(); + } else if (isCSSVariable(fallback)) { + // The fallback might itself be a CSS variable, in which case we attempt to resolve it too. + return getVariableValue(fallback, element, depth + 1); + } else { + return fallback; + } + } + /** + * Resolve CSS variables from + * + * @internal + */ + function resolveCSSVariables(visualElement, _a, transitionEnd) { + var _b; + var target = tslib.__rest(_a, []); + var element = visualElement.getInstance(); + if (!(element instanceof Element)) return { + target: target, + transitionEnd: transitionEnd + }; + // If `transitionEnd` isn't `undefined`, clone it. We could clone `target` and `transitionEnd` + // only if they change but I think this reads clearer and this isn't a performance-critical path. + if (transitionEnd) { + transitionEnd = tslib.__assign({}, transitionEnd); + } + // Go through existing `MotionValue`s and ensure any existing CSS variables are resolved + visualElement.forEachValue(function (value) { + var current = value.get(); + if (!isCSSVariable(current)) return; + var resolved = getVariableValue(current, element); + if (resolved) value.set(resolved); + }); + // Cycle through every target property and resolve CSS variables. Currently + // we only read single-var properties like `var(--foo)`, not `calc(var(--foo) + 20px)` + for (var key in target) { + var current = target[key]; + if (!isCSSVariable(current)) continue; + var resolved = getVariableValue(current, element); + if (!resolved) continue; + // Clone target if it hasn't already been + target[key] = resolved; + // If the user hasn't already set this key on `transitionEnd`, set it to the unresolved + // CSS variable. This will ensure that after the animation the component will reflect + // changes in the value of the CSS variable. + if (transitionEnd) (_b = transitionEnd[key]) !== null && _b !== void 0 ? _b : transitionEnd[key] = current; + } + return { + target: target, + transitionEnd: transitionEnd + }; + } + var positionalKeys = new Set(["width", "height", "top", "left", "right", "bottom", "x", "y"]); + var isPositionalKey = function (key) { + return positionalKeys.has(key); + }; + var hasPositionalKey = function (target) { + return Object.keys(target).some(isPositionalKey); + }; + var setAndResetVelocity = function (value, to) { + // Looks odd but setting it twice doesn't render, it'll just + // set both prev and current to the latest value + value.set(to, false); + value.set(to); + }; + var isNumOrPxType = function (v) { + return v === styleValueTypes.number || v === styleValueTypes.px; + }; + var BoundingBoxDimension; + (function (BoundingBoxDimension) { + BoundingBoxDimension["width"] = "width"; + BoundingBoxDimension["height"] = "height"; + BoundingBoxDimension["left"] = "left"; + BoundingBoxDimension["right"] = "right"; + BoundingBoxDimension["top"] = "top"; + BoundingBoxDimension["bottom"] = "bottom"; + })(BoundingBoxDimension || (BoundingBoxDimension = {})); + var getPosFromMatrix = function (matrix, pos) { + return parseFloat(matrix.split(", ")[pos]); + }; + var getTranslateFromMatrix = function (pos2, pos3) { + return function (_bbox, _a) { + var transform = _a.transform; + if (transform === "none" || !transform) return 0; + var matrix3d = transform.match(/^matrix3d\((.+)\)$/); + if (matrix3d) { + return getPosFromMatrix(matrix3d[1], pos3); + } else { + var matrix = transform.match(/^matrix\((.+)\)$/); + if (matrix) { + return getPosFromMatrix(matrix[1], pos2); + } else { + return 0; + } + } + }; + }; + var transformKeys = new Set(["x", "y", "z"]); + var nonTranslationalTransformKeys = transformProps.filter(function (key) { + return !transformKeys.has(key); + }); + function removeNonTranslationalTransform(visualElement) { + var removedTransforms = []; + nonTranslationalTransformKeys.forEach(function (key) { + var value = visualElement.getValue(key); + if (value !== undefined) { + removedTransforms.push([key, value.get()]); + value.set(key.startsWith("scale") ? 1 : 0); + } + }); + // Apply changes to element before measurement + if (removedTransforms.length) visualElement.syncRender(); + return removedTransforms; + } + var positionalValues = { + // Dimensions + width: function (_a, _b) { + var x = _a.x; + var _c = _b.paddingLeft, + paddingLeft = _c === void 0 ? "0" : _c, + _d = _b.paddingRight, + paddingRight = _d === void 0 ? "0" : _d; + return x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight); + }, + height: function (_a, _b) { + var y = _a.y; + var _c = _b.paddingTop, + paddingTop = _c === void 0 ? "0" : _c, + _d = _b.paddingBottom, + paddingBottom = _d === void 0 ? "0" : _d; + return y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom); + }, + top: function (_bbox, _a) { + var top = _a.top; + return parseFloat(top); + }, + left: function (_bbox, _a) { + var left = _a.left; + return parseFloat(left); + }, + bottom: function (_a, _b) { + var y = _a.y; + var top = _b.top; + return parseFloat(top) + (y.max - y.min); + }, + right: function (_a, _b) { + var x = _a.x; + var left = _b.left; + return parseFloat(left) + (x.max - x.min); + }, + // Transform + x: getTranslateFromMatrix(4, 13), + y: getTranslateFromMatrix(5, 14) + }; + var convertChangedValueTypes = function (target, visualElement, changedKeys) { + var originBbox = visualElement.measureViewportBox(); + var element = visualElement.getInstance(); + var elementComputedStyle = getComputedStyle(element); + var display = elementComputedStyle.display; + var origin = {}; + // If the element is currently set to display: "none", make it visible before + // measuring the target bounding box + if (display === "none") { + visualElement.setStaticValue("display", target.display || "block"); + } + /** + * Record origins before we render and update styles + */ + changedKeys.forEach(function (key) { + origin[key] = positionalValues[key](originBbox, elementComputedStyle); + }); + // Apply the latest values (as set in checkAndConvertChangedValueTypes) + visualElement.syncRender(); + var targetBbox = visualElement.measureViewportBox(); + changedKeys.forEach(function (key) { + // Restore styles to their **calculated computed style**, not their actual + // originally set style. This allows us to animate between equivalent pixel units. + var value = visualElement.getValue(key); + setAndResetVelocity(value, origin[key]); + target[key] = positionalValues[key](targetBbox, elementComputedStyle); + }); + return target; + }; + var checkAndConvertChangedValueTypes = function (visualElement, target, origin, transitionEnd) { + if (origin === void 0) { + origin = {}; + } + if (transitionEnd === void 0) { + transitionEnd = {}; + } + target = tslib.__assign({}, target); + transitionEnd = tslib.__assign({}, transitionEnd); + var targetPositionalKeys = Object.keys(target).filter(isPositionalKey); + // We want to remove any transform values that could affect the element's bounding box before + // it's measured. We'll reapply these later. + var removedTransformValues = []; + var hasAttemptedToRemoveTransformValues = false; + var changedValueTypeKeys = []; + targetPositionalKeys.forEach(function (key) { + var value = visualElement.getValue(key); + if (!visualElement.hasValue(key)) return; + var from = origin[key]; + var fromType = findDimensionValueType(from); + var to = target[key]; + var toType; + // TODO: The current implementation of this basically throws an error + // if you try and do value conversion via keyframes. There's probably + // a way of doing this but the performance implications would need greater scrutiny, + // as it'd be doing multiple resize-remeasure operations. + if (isKeyframesTarget(to)) { + var numKeyframes = to.length; + var fromIndex = to[0] === null ? 1 : 0; + from = to[fromIndex]; + fromType = findDimensionValueType(from); + for (var i = fromIndex; i < numKeyframes; i++) { + if (!toType) { + toType = findDimensionValueType(to[i]); + heyListen.invariant(toType === fromType || isNumOrPxType(fromType) && isNumOrPxType(toType), "Keyframes must be of the same dimension as the current value"); + } else { + heyListen.invariant(findDimensionValueType(to[i]) === toType, "All keyframes must be of the same type"); + } + } + } else { + toType = findDimensionValueType(to); + } + if (fromType !== toType) { + // If they're both just number or px, convert them both to numbers rather than + // relying on resize/remeasure to convert (which is wasteful in this situation) + if (isNumOrPxType(fromType) && isNumOrPxType(toType)) { + var current = value.get(); + if (typeof current === "string") { + value.set(parseFloat(current)); + } + if (typeof to === "string") { + target[key] = parseFloat(to); + } else if (Array.isArray(to) && toType === styleValueTypes.px) { + target[key] = to.map(parseFloat); + } + } else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) && (toType === null || toType === void 0 ? void 0 : toType.transform) && (from === 0 || to === 0)) { + // If one or the other value is 0, it's safe to coerce it to the + // type of the other without measurement + if (from === 0) { + value.set(toType.transform(from)); + } else { + target[key] = fromType.transform(to); + } + } else { + // If we're going to do value conversion via DOM measurements, we first + // need to remove non-positional transform values that could affect the bbox measurements. + if (!hasAttemptedToRemoveTransformValues) { + removedTransformValues = removeNonTranslationalTransform(visualElement); + hasAttemptedToRemoveTransformValues = true; + } + changedValueTypeKeys.push(key); + transitionEnd[key] = transitionEnd[key] !== undefined ? transitionEnd[key] : target[key]; + setAndResetVelocity(value, to); + } + } + }); + if (changedValueTypeKeys.length) { + var scrollY_1 = changedValueTypeKeys.indexOf("height") >= 0 ? window.pageYOffset : null; + var convertedTarget = convertChangedValueTypes(target, visualElement, changedValueTypeKeys); + // If we removed transform values, reapply them before the next render + if (removedTransformValues.length) { + removedTransformValues.forEach(function (_a) { + var _b = tslib.__read(_a, 2), + key = _b[0], + value = _b[1]; + visualElement.getValue(key).set(value); + }); + } + // Reapply original values + visualElement.syncRender(); + // Restore scroll position + if (scrollY_1 !== null) window.scrollTo({ + top: scrollY_1 + }); + return { + target: convertedTarget, + transitionEnd: transitionEnd + }; + } else { + return { + target: target, + transitionEnd: transitionEnd + }; + } + }; + /** + * Convert value types for x/y/width/height/top/left/bottom/right + * + * Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'` + * + * @internal + */ + function unitConversion(visualElement, target, origin, transitionEnd) { + return hasPositionalKey(target) ? checkAndConvertChangedValueTypes(visualElement, target, origin, transitionEnd) : { + target: target, + transitionEnd: transitionEnd + }; + } + + /** + * Parse a DOM variant to make it animatable. This involves resolving CSS variables + * and ensuring animations like "20%" => "calc(50vw)" are performed in pixels. + */ + var parseDomVariant = function (visualElement, target, origin, transitionEnd) { + var resolved = resolveCSSVariables(visualElement, target, transitionEnd); + target = resolved.target; + transitionEnd = resolved.transitionEnd; + return unitConversion(visualElement, target, origin, transitionEnd); + }; + function getComputedStyle$1(element) { + return window.getComputedStyle(element); + } + var htmlConfig = { + treeType: "dom", + readValueFromInstance: function (domElement, key) { + if (isTransformProp(key)) { + var defaultType = getDefaultValueType(key); + return defaultType ? defaultType.default || 0 : 0; + } else { + var computedStyle = getComputedStyle$1(domElement); + return (isCSSVariable$1(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0; + } + }, + sortNodePosition: function (a, b) { + /** + * compareDocumentPosition returns a bitmask, by using the bitwise & + * we're returning true if 2 in that bitmask is set to true. 2 is set + * to true if b preceeds a. + */ + return a.compareDocumentPosition(b) & 2 ? 1 : -1; + }, + getBaseTarget: function (props, key) { + var _a; + return (_a = props.style) === null || _a === void 0 ? void 0 : _a[key]; + }, + measureViewportBox: function (element, _a) { + var transformPagePoint = _a.transformPagePoint; + return measureViewportBox(element, transformPagePoint); + }, + /** + * Reset the transform on the current Element. This is called as part + * of a batched process across the entire layout tree. To remove this write + * cycle it'd be interesting to see if it's possible to "undo" all the current + * layout transforms up the tree in the same way this.getBoundingBoxWithoutTransforms + * works + */ + resetTransform: function (element, domElement, props) { + var transformTemplate = props.transformTemplate; + domElement.style.transform = transformTemplate ? transformTemplate({}, "") : "none"; + // Ensure that whatever happens next, we restore our transform on the next frame + element.scheduleRender(); + }, + restoreTransform: function (instance, mutableState) { + instance.style.transform = mutableState.style.transform; + }, + removeValueFromRenderState: function (key, _a) { + var vars = _a.vars, + style = _a.style; + delete vars[key]; + delete style[key]; + }, + /** + * Ensure that HTML and Framer-specific value types like `px`->`%` and `Color` + * can be animated by Motion. + */ + makeTargetAnimatable: function (element, _a, _b, isMounted) { + var transformValues = _b.transformValues; + if (isMounted === void 0) { + isMounted = true; + } + var transition = _a.transition, + transitionEnd = _a.transitionEnd, + target = tslib.__rest(_a, ["transition", "transitionEnd"]); + var origin = getOrigin(target, transition || {}, element); + /** + * If Framer has provided a function to convert `Color` etc value types, convert them + */ + if (transformValues) { + if (transitionEnd) transitionEnd = transformValues(transitionEnd); + if (target) target = transformValues(target); + if (origin) origin = transformValues(origin); + } + if (isMounted) { + checkTargetForNewValues(element, target, origin); + var parsed = parseDomVariant(element, target, origin, transitionEnd); + transitionEnd = parsed.transitionEnd; + target = parsed.target; + } + return tslib.__assign({ + transition: transition, + transitionEnd: transitionEnd + }, target); + }, + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + build: function (element, renderState, latestValues, options, props) { + if (element.isVisible !== undefined) { + renderState.style.visibility = element.isVisible ? "visible" : "hidden"; + } + buildHTMLStyles(renderState, latestValues, options, props.transformTemplate); + }, + render: renderHTML + }; + var htmlVisualElement = visualElement(htmlConfig); + var svgVisualElement = visualElement(tslib.__assign(tslib.__assign({}, htmlConfig), { + getBaseTarget: function (props, key) { + return props[key]; + }, + readValueFromInstance: function (domElement, key) { + var _a; + if (isTransformProp(key)) { + return ((_a = getDefaultValueType(key)) === null || _a === void 0 ? void 0 : _a.default) || 0; + } + key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; + return domElement.getAttribute(key); + }, + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + build: function (_element, renderState, latestValues, options, props) { + buildSVGAttrs(renderState, latestValues, options, props.transformTemplate); + }, + render: renderSVG + })); + var createDomVisualElement = function (Component, options) { + return isSVGComponent(Component) ? svgVisualElement(options, { + enableHardwareAcceleration: false + }) : htmlVisualElement(options, { + enableHardwareAcceleration: true + }); + }; + function pixelsToPercent(pixels, axis) { + if (axis.max === axis.min) return 0; + return pixels / (axis.max - axis.min) * 100; + } + /** + * We always correct borderRadius as a percentage rather than pixels to reduce paints. + * For example, if you are projecting a box that is 100px wide with a 10px borderRadius + * into a box that is 200px wide with a 20px borderRadius, that is actually a 10% + * borderRadius in both states. If we animate between the two in pixels that will trigger + * a paint each time. If we animate between the two in percentage we'll avoid a paint. + */ + var correctBorderRadius = { + correct: function (latest, node) { + if (!node.target) return latest; + /** + * If latest is a string, if it's a percentage we can return immediately as it's + * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number. + */ + if (typeof latest === "string") { + if (styleValueTypes.px.test(latest)) { + latest = parseFloat(latest); + } else { + return latest; + } + } + /** + * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that + * pixel value as a percentage of each axis + */ + var x = pixelsToPercent(latest, node.target.x); + var y = pixelsToPercent(latest, node.target.y); + return "".concat(x, "% ").concat(y, "%"); + } + }; + var varToken = "_$css"; + var correctBoxShadow = { + correct: function (latest, _a) { + var treeScale = _a.treeScale, + projectionDelta = _a.projectionDelta; + var original = latest; + /** + * We need to first strip and store CSS variables from the string. + */ + var containsCSSVariables = latest.includes("var("); + var cssVariables = []; + if (containsCSSVariables) { + latest = latest.replace(cssVariableRegex, function (match) { + cssVariables.push(match); + return varToken; + }); + } + var shadow = styleValueTypes.complex.parse(latest); + // TODO: Doesn't support multiple shadows + if (shadow.length > 5) return original; + var template = styleValueTypes.complex.createTransformer(latest); + var offset = typeof shadow[0] !== "number" ? 1 : 0; + // Calculate the overall context scale + var xScale = projectionDelta.x.scale * treeScale.x; + var yScale = projectionDelta.y.scale * treeScale.y; + shadow[0 + offset] /= xScale; + shadow[1 + offset] /= yScale; + /** + * Ideally we'd correct x and y scales individually, but because blur and + * spread apply to both we have to take a scale average and apply that instead. + * We could potentially improve the outcome of this by incorporating the ratio between + * the two scales. + */ + var averageScale = popmotion.mix(xScale, yScale, 0.5); + // Blur + if (typeof shadow[2 + offset] === "number") shadow[2 + offset] /= averageScale; + // Spread + if (typeof shadow[3 + offset] === "number") shadow[3 + offset] /= averageScale; + var output = template(shadow); + if (containsCSSVariables) { + var i_1 = 0; + output = output.replace(varToken, function () { + var cssVariable = cssVariables[i_1]; + i_1++; + return cssVariable; + }); + } + return output; + } + }; + var MeasureLayoutWithContext = /** @class */function (_super) { + tslib.__extends(MeasureLayoutWithContext, _super); + function MeasureLayoutWithContext() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * This only mounts projection nodes for components that + * need measuring, we might want to do it for all components + * in order to incorporate transforms + */ + MeasureLayoutWithContext.prototype.componentDidMount = function () { + var _this = this; + var _a = this.props, + visualElement = _a.visualElement, + layoutGroup = _a.layoutGroup, + switchLayoutGroup = _a.switchLayoutGroup, + layoutId = _a.layoutId; + var projection = visualElement.projection; + addScaleCorrector(defaultScaleCorrectors); + if (projection) { + if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group) layoutGroup.group.add(projection); + if ((switchLayoutGroup === null || switchLayoutGroup === void 0 ? void 0 : switchLayoutGroup.register) && layoutId) { + switchLayoutGroup.register(projection); + } + projection.root.didUpdate(); + projection.addEventListener("animationComplete", function () { + _this.safeToRemove(); + }); + projection.setOptions(tslib.__assign(tslib.__assign({}, projection.options), { + onExitComplete: function () { + return _this.safeToRemove(); + } + })); + } + globalProjectionState.hasEverUpdated = true; + }; + MeasureLayoutWithContext.prototype.getSnapshotBeforeUpdate = function (prevProps) { + var _this = this; + var _a = this.props, + layoutDependency = _a.layoutDependency, + visualElement = _a.visualElement, + drag = _a.drag, + isPresent = _a.isPresent; + var projection = visualElement.projection; + if (!projection) return null; + /** + * TODO: We use this data in relegate to determine whether to + * promote a previous element. There's no guarantee its presence data + * will have updated by this point - if a bug like this arises it will + * have to be that we markForRelegation and then find a new lead some other way, + * perhaps in didUpdate + */ + projection.isPresent = isPresent; + if (drag || prevProps.layoutDependency !== layoutDependency || layoutDependency === undefined) { + projection.willUpdate(); + } else { + this.safeToRemove(); + } + if (prevProps.isPresent !== isPresent) { + if (isPresent) { + projection.promote(); + } else if (!projection.relegate()) { + /** + * If there's another stack member taking over from this one, + * it's in charge of the exit animation and therefore should + * be in charge of the safe to remove. Otherwise we call it here. + */ + sync__default["default"].postRender(function () { + var _a; + if (!((_a = projection.getStack()) === null || _a === void 0 ? void 0 : _a.members.length)) { + _this.safeToRemove(); + } + }); + } + } + return null; + }; + MeasureLayoutWithContext.prototype.componentDidUpdate = function () { + var projection = this.props.visualElement.projection; + if (projection) { + projection.root.didUpdate(); + if (!projection.currentAnimation && projection.isLead()) { + this.safeToRemove(); + } + } + }; + MeasureLayoutWithContext.prototype.componentWillUnmount = function () { + var _a = this.props, + visualElement = _a.visualElement, + layoutGroup = _a.layoutGroup, + promoteContext = _a.switchLayoutGroup; + var projection = visualElement.projection; + if (projection) { + projection.scheduleCheckAfterUnmount(); + if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group) layoutGroup.group.remove(projection); + if (promoteContext === null || promoteContext === void 0 ? void 0 : promoteContext.deregister) promoteContext.deregister(projection); + } + }; + MeasureLayoutWithContext.prototype.safeToRemove = function () { + var safeToRemove = this.props.safeToRemove; + safeToRemove === null || safeToRemove === void 0 ? void 0 : safeToRemove(); + }; + MeasureLayoutWithContext.prototype.render = function () { + return null; + }; + return MeasureLayoutWithContext; + }(React__default["default"].Component); + function MeasureLayout(props) { + var _a = tslib.__read(usePresence(), 2), + isPresent = _a[0], + safeToRemove = _a[1]; + var layoutGroup = React.useContext(LayoutGroupContext); + return React__default["default"].createElement(MeasureLayoutWithContext, tslib.__assign({}, props, { + layoutGroup: layoutGroup, + switchLayoutGroup: React.useContext(SwitchLayoutGroupContext), + isPresent: isPresent, + safeToRemove: safeToRemove + })); + } + var defaultScaleCorrectors = { + borderRadius: tslib.__assign(tslib.__assign({}, correctBorderRadius), { + applyTo: ["borderTopLeftRadius", "borderTopRightRadius", "borderBottomLeftRadius", "borderBottomRightRadius"] + }), + borderTopLeftRadius: correctBorderRadius, + borderTopRightRadius: correctBorderRadius, + borderBottomLeftRadius: correctBorderRadius, + borderBottomRightRadius: correctBorderRadius, + boxShadow: correctBoxShadow + }; + var layoutFeatures = { + measureLayout: MeasureLayout + }; + + /** + * Animate a single value or a `MotionValue`. + * + * The first argument is either a `MotionValue` to animate, or an initial animation value. + * + * The second is either a value to animate to, or an array of keyframes to animate through. + * + * The third argument can be either tween or spring options, and optional lifecycle methods: `onUpdate`, `onPlay`, `onComplete`, `onRepeat` and `onStop`. + * + * Returns `AnimationPlaybackControls`, currently just a `stop` method. + * + * ```javascript + * const x = useMotionValue(0) + * + * useEffect(() => { + * const controls = animate(x, 100, { + * type: "spring", + * stiffness: 2000, + * onComplete: v => {} + * }) + * + * return controls.stop + * }) + * ``` + * + * @public + */ + function animate(from, to, transition) { + if (transition === void 0) { + transition = {}; + } + var value = isMotionValue(from) ? from : motionValue(from); + startAnimation("", value, to, transition); + return { + stop: function () { + return value.stop(); + }, + isAnimating: function () { + return value.isAnimating(); + } + }; + } + var borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"]; + var numBorders = borders.length; + var asNumber = function (value) { + return typeof value === "string" ? parseFloat(value) : value; + }; + var isPx = function (value) { + return typeof value === "number" || styleValueTypes.px.test(value); + }; + function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) { + var _a, _b, _c, _d; + if (shouldCrossfadeOpacity) { + target.opacity = popmotion.mix(0, + // (follow?.opacity as number) ?? 0, + // TODO Reinstate this if only child + (_a = lead.opacity) !== null && _a !== void 0 ? _a : 1, easeCrossfadeIn(progress)); + target.opacityExit = popmotion.mix((_b = follow.opacity) !== null && _b !== void 0 ? _b : 1, 0, easeCrossfadeOut(progress)); + } else if (isOnlyMember) { + target.opacity = popmotion.mix((_c = follow.opacity) !== null && _c !== void 0 ? _c : 1, (_d = lead.opacity) !== null && _d !== void 0 ? _d : 1, progress); + } + /** + * Mix border radius + */ + for (var i = 0; i < numBorders; i++) { + var borderLabel = "border".concat(borders[i], "Radius"); + var followRadius = getRadius(follow, borderLabel); + var leadRadius = getRadius(lead, borderLabel); + if (followRadius === undefined && leadRadius === undefined) continue; + followRadius || (followRadius = 0); + leadRadius || (leadRadius = 0); + var canMix = followRadius === 0 || leadRadius === 0 || isPx(followRadius) === isPx(leadRadius); + if (canMix) { + target[borderLabel] = Math.max(popmotion.mix(asNumber(followRadius), asNumber(leadRadius), progress), 0); + if (styleValueTypes.percent.test(leadRadius) || styleValueTypes.percent.test(followRadius)) { + target[borderLabel] += "%"; + } + } else { + target[borderLabel] = leadRadius; + } + } + /** + * Mix rotation + */ + if (follow.rotate || lead.rotate) { + target.rotate = popmotion.mix(follow.rotate || 0, lead.rotate || 0, progress); + } + } + function getRadius(values, radiusName) { + var _a; + return (_a = values[radiusName]) !== null && _a !== void 0 ? _a : values.borderRadius; + } + // /** + // * We only want to mix the background color if there's a follow element + // * that we're not crossfading opacity between. For instance with switch + // * AnimateSharedLayout animations, this helps the illusion of a continuous + // * element being animated but also cuts down on the number of paints triggered + // * for elements where opacity is doing that work for us. + // */ + // if ( + // !hasFollowElement && + // latestLeadValues.backgroundColor && + // latestFollowValues.backgroundColor + // ) { + // /** + // * This isn't ideal performance-wise as mixColor is creating a new function every frame. + // * We could probably create a mixer that runs at the start of the animation but + // * the idea behind the crossfader is that it runs dynamically between two potentially + // * changing targets (ie opacity or borderRadius may be animating independently via variants) + // */ + // leadState.backgroundColor = followState.backgroundColor = mixColor( + // latestFollowValues.backgroundColor as string, + // latestLeadValues.backgroundColor as string + // )(p) + // } + var easeCrossfadeIn = compress(0, 0.5, popmotion.circOut); + var easeCrossfadeOut = compress(0.5, 0.95, popmotion.linear); + function compress(min, max, easing) { + return function (p) { + // Could replace ifs with clamp + if (p < min) return 0; + if (p > max) return 1; + return easing(popmotion.progress(min, max, p)); + }; + } + + /** + * Reset an axis to the provided origin box. + * + * This is a mutative operation. + */ + function copyAxisInto(axis, originAxis) { + axis.min = originAxis.min; + axis.max = originAxis.max; + } + /** + * Reset a box to the provided origin box. + * + * This is a mutative operation. + */ + function copyBoxInto(box, originBox) { + copyAxisInto(box.x, originBox.x); + copyAxisInto(box.y, originBox.y); + } + + /** + * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse + */ + function removePointDelta(point, translate, scale, originPoint, boxScale) { + point -= translate; + point = scalePoint(point, 1 / scale, originPoint); + if (boxScale !== undefined) { + point = scalePoint(point, 1 / boxScale, originPoint); + } + return point; + } + /** + * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse + */ + function removeAxisDelta(axis, translate, scale, origin, boxScale, originAxis, sourceAxis) { + if (translate === void 0) { + translate = 0; + } + if (scale === void 0) { + scale = 1; + } + if (origin === void 0) { + origin = 0.5; + } + if (originAxis === void 0) { + originAxis = axis; + } + if (sourceAxis === void 0) { + sourceAxis = axis; + } + if (styleValueTypes.percent.test(translate)) { + translate = parseFloat(translate); + var relativeProgress = popmotion.mix(sourceAxis.min, sourceAxis.max, translate / 100); + translate = relativeProgress - sourceAxis.min; + } + if (typeof translate !== "number") return; + var originPoint = popmotion.mix(originAxis.min, originAxis.max, origin); + if (axis === originAxis) originPoint -= translate; + axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale); + axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale); + } + /** + * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ + function removeAxisTransforms(axis, transforms, _a, origin, sourceAxis) { + var _b = tslib.__read(_a, 3), + key = _b[0], + scaleKey = _b[1], + originKey = _b[2]; + removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); + } + /** + * The names of the motion values we want to apply as translation, scale and origin. + */ + var xKeys = ["x", "scaleX", "originX"]; + var yKeys = ["y", "scaleY", "originY"]; + /** + * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse + * and acts as a bridge between motion values and removeAxisDelta + */ + function removeBoxTransforms(box, transforms, originBox, sourceBox) { + removeAxisTransforms(box.x, transforms, xKeys, originBox === null || originBox === void 0 ? void 0 : originBox.x, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.x); + removeAxisTransforms(box.y, transforms, yKeys, originBox === null || originBox === void 0 ? void 0 : originBox.y, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.y); + } + function isAxisDeltaZero(delta) { + return delta.translate === 0 && delta.scale === 1; + } + function isDeltaZero(delta) { + return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); + } + function boxEquals(a, b) { + return a.x.min === b.x.min && a.x.max === b.x.max && a.y.min === b.y.min && a.y.max === b.y.max; + } + var NodeStack = /** @class */function () { + function NodeStack() { + this.members = []; + } + NodeStack.prototype.add = function (node) { + addUniqueItem(this.members, node); + node.scheduleRender(); + }; + NodeStack.prototype.remove = function (node) { + removeItem(this.members, node); + if (node === this.prevLead) { + this.prevLead = undefined; + } + if (node === this.lead) { + var prevLead = this.members[this.members.length - 1]; + if (prevLead) { + this.promote(prevLead); + } + } + }; + NodeStack.prototype.relegate = function (node) { + var indexOfNode = this.members.findIndex(function (member) { + return node === member; + }); + if (indexOfNode === 0) return false; + /** + * Find the next projection node that is present + */ + var prevLead; + for (var i = indexOfNode; i >= 0; i--) { + var member = this.members[i]; + if (member.isPresent !== false) { + prevLead = member; + break; + } + } + if (prevLead) { + this.promote(prevLead); + return true; + } else { + return false; + } + }; + NodeStack.prototype.promote = function (node, preserveFollowOpacity) { + var _a; + var prevLead = this.lead; + if (node === prevLead) return; + this.prevLead = prevLead; + this.lead = node; + node.show(); + if (prevLead) { + prevLead.instance && prevLead.scheduleRender(); + node.scheduleRender(); + node.resumeFrom = prevLead; + if (preserveFollowOpacity) { + node.resumeFrom.preserveOpacity = true; + } + if (prevLead.snapshot) { + node.snapshot = prevLead.snapshot; + node.snapshot.latestValues = prevLead.animationValues || prevLead.latestValues; + node.snapshot.isShared = true; + } + if ((_a = node.root) === null || _a === void 0 ? void 0 : _a.isUpdating) { + node.isLayoutDirty = true; + } + var crossfade = node.options.crossfade; + if (crossfade === false) { + prevLead.hide(); + } + /** + * TODO: + * - Test border radius when previous node was deleted + * - boxShadow mixing + * - Shared between element A in scrolled container and element B (scroll stays the same or changes) + * - Shared between element A in transformed container and element B (transform stays the same or changes) + * - Shared between element A in scrolled page and element B (scroll stays the same or changes) + * --- + * - Crossfade opacity of root nodes + * - layoutId changes after animation + * - layoutId changes mid animation + */ + } + }; + NodeStack.prototype.exitAnimationComplete = function () { + this.members.forEach(function (node) { + var _a, _b, _c, _d, _e; + (_b = (_a = node.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a); + (_e = (_c = node.resumingFrom) === null || _c === void 0 ? void 0 : (_d = _c.options).onExitComplete) === null || _e === void 0 ? void 0 : _e.call(_d); + }); + }; + NodeStack.prototype.scheduleRender = function () { + this.members.forEach(function (node) { + node.instance && node.scheduleRender(false); + }); + }; + /** + * Clear any leads that have been removed this render to prevent them from being + * used in future animations and to prevent memory leaks + */ + NodeStack.prototype.removeLeadSnapshot = function () { + if (this.lead && this.lead.snapshot) { + this.lead.snapshot = undefined; + } + }; + return NodeStack; + }(); + var identityProjection = "translate3d(0px, 0px, 0) scale(1, 1) scale(1, 1)"; + function buildProjectionTransform(delta, treeScale, latestTransform) { + /** + * The translations we use to calculate are always relative to the viewport coordinate space. + * But when we apply scales, we also scale the coordinate space of an element and its children. + * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need + * to move an element 100 pixels, we actually need to move it 200 in within that scaled space. + */ + var xTranslate = delta.x.translate / treeScale.x; + var yTranslate = delta.y.translate / treeScale.y; + var transform = "translate3d(".concat(xTranslate, "px, ").concat(yTranslate, "px, 0) "); + /** + * Apply scale correction for the tree transform. + * This will apply scale to the screen-orientated axes. + */ + transform += "scale(".concat(1 / treeScale.x, ", ").concat(1 / treeScale.y, ") "); + if (latestTransform) { + var rotate = latestTransform.rotate, + rotateX = latestTransform.rotateX, + rotateY = latestTransform.rotateY; + if (rotate) transform += "rotate(".concat(rotate, "deg) "); + if (rotateX) transform += "rotateX(".concat(rotateX, "deg) "); + if (rotateY) transform += "rotateY(".concat(rotateY, "deg) "); + } + /** + * Apply scale to match the size of the element to the size we want it. + * This will apply scale to the element-orientated axes. + */ + var elementScaleX = delta.x.scale * treeScale.x; + var elementScaleY = delta.y.scale * treeScale.y; + transform += "scale(".concat(elementScaleX, ", ").concat(elementScaleY, ")"); + return transform === identityProjection ? "none" : transform; + } + var compareByDepth = function (a, b) { + return a.depth - b.depth; + }; + var FlatTree = /** @class */function () { + function FlatTree() { + this.children = []; + this.isDirty = false; + } + FlatTree.prototype.add = function (child) { + addUniqueItem(this.children, child); + this.isDirty = true; + }; + FlatTree.prototype.remove = function (child) { + removeItem(this.children, child); + this.isDirty = true; + }; + FlatTree.prototype.forEach = function (callback) { + this.isDirty && this.children.sort(compareByDepth); + this.isDirty = false; + this.children.forEach(callback); + }; + return FlatTree; + }(); + + /** + * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1 + * which has a noticeable difference in spring animations + */ + var animationTarget = 1000; + function createProjectionNode(_a) { + var attachResizeListener = _a.attachResizeListener, + defaultParent = _a.defaultParent, + measureScroll = _a.measureScroll, + checkIsScrollRoot = _a.checkIsScrollRoot, + resetTransform = _a.resetTransform; + return /** @class */function () { + function ProjectionNode(id, latestValues, parent) { + var _this = this; + if (latestValues === void 0) { + latestValues = {}; + } + if (parent === void 0) { + parent = defaultParent === null || defaultParent === void 0 ? void 0 : defaultParent(); + } + /** + * A Set containing all this component's children. This is used to iterate + * through the children. + * + * TODO: This could be faster to iterate as a flat array stored on the root node. + */ + this.children = new Set(); + /** + * Options for the node. We use this to configure what kind of layout animations + * we should perform (if any). + */ + this.options = {}; + /** + * We use this to detect when its safe to shut down part of a projection tree. + * We have to keep projecting children for scale correction and relative projection + * until all their parents stop performing layout animations. + */ + this.isTreeAnimating = false; + this.isAnimationBlocked = false; + /** + * Flag to true if we think this layout has been changed. We can't always know this, + * currently we set it to true every time a component renders, or if it has a layoutDependency + * if that has changed between renders. Additionally, components can be grouped by LayoutGroup + * and if one node is dirtied, they all are. + */ + this.isLayoutDirty = false; + /** + * Block layout updates for instant layout transitions throughout the tree. + */ + this.updateManuallyBlocked = false; + this.updateBlockedByResize = false; + /** + * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate` + * call. + */ + this.isUpdating = false; + /** + * If this is an SVG element we currently disable projection transforms + */ + this.isSVG = false; + /** + * Flag to true (during promotion) if a node doing an instant layout transition needs to reset + * its projection styles. + */ + this.needsReset = false; + /** + * Flags whether this node should have its transform reset prior to measuring. + */ + this.shouldResetTransform = false; + /** + * An object representing the calculated contextual/accumulated/tree scale. + * This will be used to scale calculcated projection transforms, as these are + * calculated in screen-space but need to be scaled for elements to actually + * make it to their calculated destinations. + * + * TODO: Lazy-init + */ + this.treeScale = { + x: 1, + y: 1 + }; + /** + * + */ + this.eventHandlers = new Map(); + // Note: Currently only running on root node + this.potentialNodes = new Map(); + this.checkUpdateFailed = function () { + if (_this.isUpdating) { + _this.isUpdating = false; + _this.clearAllSnapshots(); + } + }; + this.updateProjection = function () { + _this.nodes.forEach(resolveTargetDelta); + _this.nodes.forEach(calcProjection); + }; + this.hasProjected = false; + this.isVisible = true; + this.animationProgress = 0; + /** + * Shared layout + */ + // TODO Only running on root node + this.sharedNodes = new Map(); + this.id = id; + this.latestValues = latestValues; + this.root = parent ? parent.root || parent : this; + this.path = parent ? tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(parent.path), false), [parent], false) : []; + this.parent = parent; + this.depth = parent ? parent.depth + 1 : 0; + id && this.root.registerPotentialNode(id, this); + for (var i = 0; i < this.path.length; i++) { + this.path[i].shouldResetTransform = true; + } + if (this.root === this) this.nodes = new FlatTree(); + } + ProjectionNode.prototype.addEventListener = function (name, handler) { + if (!this.eventHandlers.has(name)) { + this.eventHandlers.set(name, new SubscriptionManager()); + } + return this.eventHandlers.get(name).add(handler); + }; + ProjectionNode.prototype.notifyListeners = function (name) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var subscriptionManager = this.eventHandlers.get(name); + subscriptionManager === null || subscriptionManager === void 0 ? void 0 : subscriptionManager.notify.apply(subscriptionManager, tslib.__spreadArray([], tslib.__read(args), false)); + }; + ProjectionNode.prototype.hasListeners = function (name) { + return this.eventHandlers.has(name); + }; + ProjectionNode.prototype.registerPotentialNode = function (id, node) { + this.potentialNodes.set(id, node); + }; + /** + * Lifecycles + */ + ProjectionNode.prototype.mount = function (instance, isLayoutDirty) { + var _this = this; + var _a; + if (isLayoutDirty === void 0) { + isLayoutDirty = false; + } + if (this.instance) return; + this.isSVG = instance instanceof SVGElement && instance.tagName !== "svg"; + this.instance = instance; + var _b = this.options, + layoutId = _b.layoutId, + layout = _b.layout, + visualElement = _b.visualElement; + if (visualElement && !visualElement.getInstance()) { + visualElement.mount(instance); + } + this.root.nodes.add(this); + (_a = this.parent) === null || _a === void 0 ? void 0 : _a.children.add(this); + this.id && this.root.potentialNodes.delete(this.id); + if (isLayoutDirty && (layout || layoutId)) { + this.isLayoutDirty = true; + } + if (attachResizeListener) { + var unblockTimeout_1; + var resizeUnblockUpdate_1 = function () { + return _this.root.updateBlockedByResize = false; + }; + attachResizeListener(instance, function () { + _this.root.updateBlockedByResize = true; + clearTimeout(unblockTimeout_1); + unblockTimeout_1 = window.setTimeout(resizeUnblockUpdate_1, 250); + if (globalProjectionState.hasAnimatedSinceResize) { + globalProjectionState.hasAnimatedSinceResize = false; + _this.nodes.forEach(finishAnimation); + } + }); + } + if (layoutId) { + this.root.registerSharedNode(layoutId, this); + } + // Only register the handler if it requires layout animation + if (this.options.animate !== false && visualElement && (layoutId || layout)) { + this.addEventListener("didUpdate", function (_a) { + var _b, _c, _d, _e, _f; + var delta = _a.delta, + hasLayoutChanged = _a.hasLayoutChanged, + hasRelativeTargetChanged = _a.hasRelativeTargetChanged, + newLayout = _a.layout; + if (_this.isTreeAnimationBlocked()) { + _this.target = undefined; + _this.relativeTarget = undefined; + return; + } + // TODO: Check here if an animation exists + var layoutTransition = (_c = (_b = _this.options.transition) !== null && _b !== void 0 ? _b : visualElement.getDefaultTransition()) !== null && _c !== void 0 ? _c : defaultLayoutTransition; + var _g = visualElement.getProps(), + onLayoutAnimationStart = _g.onLayoutAnimationStart, + onLayoutAnimationComplete = _g.onLayoutAnimationComplete; + /** + * The target layout of the element might stay the same, + * but its position relative to its parent has changed. + */ + var targetChanged = !_this.targetLayout || !boxEquals(_this.targetLayout, newLayout) || hasRelativeTargetChanged; + /** + * If the layout hasn't seemed to have changed, it might be that the + * element is visually in the same place in the document but its position + * relative to its parent has indeed changed. So here we check for that. + */ + var hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeTargetChanged; + if (((_d = _this.resumeFrom) === null || _d === void 0 ? void 0 : _d.instance) || hasOnlyRelativeTargetChanged || hasLayoutChanged && (targetChanged || !_this.currentAnimation)) { + if (_this.resumeFrom) { + _this.resumingFrom = _this.resumeFrom; + _this.resumingFrom.resumingFrom = undefined; + } + _this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); + var animationOptions = tslib.__assign(tslib.__assign({}, getValueTransition(layoutTransition, "layout")), { + onPlay: onLayoutAnimationStart, + onComplete: onLayoutAnimationComplete + }); + if (visualElement.shouldReduceMotion) { + animationOptions.delay = 0; + animationOptions.type = false; } - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) { - runInOp(cm, function () { - return applyTextInput(cm, pasted, 0, null, "paste"); - }); - } - return true; - } + _this.startAnimation(animationOptions); + } else { + /** + * If the layout hasn't changed and we have an animation that hasn't started yet, + * finish it immediately. Otherwise it will be animating from a location + * that was probably never commited to screen and look like a jumpy box. + */ + if (!hasLayoutChanged && _this.animationProgress === 0) { + _this.finishAnimation(); + } + _this.isLead() && ((_f = (_e = _this.options).onExitComplete) === null || _f === void 0 ? void 0 : _f.call(_e)); + } + _this.targetLayout = newLayout; + }); + } + }; + ProjectionNode.prototype.unmount = function () { + var _a, _b; + this.options.layoutId && this.willUpdate(); + this.root.nodes.remove(this); + (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.remove(this); + (_b = this.parent) === null || _b === void 0 ? void 0 : _b.children.delete(this); + this.instance = undefined; + sync.cancelSync.preRender(this.updateProjection); + }; + // only on the root + ProjectionNode.prototype.blockUpdate = function () { + this.updateManuallyBlocked = true; + }; + ProjectionNode.prototype.unblockUpdate = function () { + this.updateManuallyBlocked = false; + }; + ProjectionNode.prototype.isUpdateBlocked = function () { + return this.updateManuallyBlocked || this.updateBlockedByResize; + }; + ProjectionNode.prototype.isTreeAnimationBlocked = function () { + var _a; + return this.isAnimationBlocked || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimationBlocked()) || false; + }; + // Note: currently only running on root node + ProjectionNode.prototype.startUpdate = function () { + var _a; + if (this.isUpdateBlocked()) return; + this.isUpdating = true; + (_a = this.nodes) === null || _a === void 0 ? void 0 : _a.forEach(resetRotation); + }; + ProjectionNode.prototype.willUpdate = function (shouldNotifyListeners) { + var _a, _b, _c; + if (shouldNotifyListeners === void 0) { + shouldNotifyListeners = true; + } + if (this.root.isUpdateBlocked()) { + (_b = (_a = this.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a); + return; + } + !this.root.isUpdating && this.root.startUpdate(); + if (this.isLayoutDirty) return; + this.isLayoutDirty = true; + for (var i = 0; i < this.path.length; i++) { + var node = this.path[i]; + node.shouldResetTransform = true; + /** + * TODO: Check we haven't updated the scroll + * since the last didUpdate + */ + node.updateScroll(); + } + var _d = this.options, + layoutId = _d.layoutId, + layout = _d.layout; + if (layoutId === undefined && !layout) return; + var transformTemplate = (_c = this.options.visualElement) === null || _c === void 0 ? void 0 : _c.getProps().transformTemplate; + this.prevTransformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, ""); + this.updateSnapshot(); + shouldNotifyListeners && this.notifyListeners("willUpdate"); + }; + // Note: Currently only running on root node + ProjectionNode.prototype.didUpdate = function () { + var updateWasBlocked = this.isUpdateBlocked(); + // When doing an instant transition, we skip the layout update, + // but should still clean up the measurements so that the next + // snapshot could be taken correctly. + if (updateWasBlocked) { + this.unblockUpdate(); + this.clearAllSnapshots(); + this.nodes.forEach(clearMeasurements); + return; + } + if (!this.isUpdating) return; + this.isUpdating = false; + /** + * Search for and mount newly-added projection elements. + * + * TODO: Every time a new component is rendered we could search up the tree for + * the closest mounted node and query from there rather than document. + */ + if (this.potentialNodes.size) { + this.potentialNodes.forEach(mountNodeEarly); + this.potentialNodes.clear(); + } + /** + * Write + */ + this.nodes.forEach(resetTransformStyle); + /** + * Read ================== + */ + // Update layout measurements of updated children + this.nodes.forEach(updateLayout); + /** + * Write + */ + // Notify listeners that the layout is updated + this.nodes.forEach(notifyLayoutUpdate); + this.clearAllSnapshots(); + // Flush any scheduled updates + sync.flushSync.update(); + sync.flushSync.preRender(); + sync.flushSync.render(); + }; + ProjectionNode.prototype.clearAllSnapshots = function () { + this.nodes.forEach(clearSnapshot); + this.sharedNodes.forEach(removeLeadSnapshots); + }; + ProjectionNode.prototype.scheduleUpdateProjection = function () { + sync__default["default"].preRender(this.updateProjection, false, true); + }; + ProjectionNode.prototype.scheduleCheckAfterUnmount = function () { + var _this = this; + /** + * If the unmounting node is in a layoutGroup and did trigger a willUpdate, + * we manually call didUpdate to give a chance to the siblings to animate. + * Otherwise, cleanup all snapshots to prevents future nodes from reusing them. + */ + sync__default["default"].postRender(function () { + if (_this.isLayoutDirty) { + _this.root.didUpdate(); + } else { + _this.root.checkUpdateFailed(); + } + }); + }; + /** + * Update measurements + */ + ProjectionNode.prototype.updateSnapshot = function () { + if (this.snapshot || !this.instance) return; + var measured = this.measure(); + var layout = this.removeTransform(this.removeElementScroll(measured)); + roundBox(layout); + this.snapshot = { + measured: measured, + layout: layout, + latestValues: {} + }; + }; + ProjectionNode.prototype.updateLayout = function () { + var _a; + if (!this.instance) return; + // TODO: Incorporate into a forwarded scroll offset + this.updateScroll(); + if (!(this.options.alwaysMeasureLayout && this.isLead()) && !this.isLayoutDirty) { + return; + } + /** + * When a node is mounted, it simply resumes from the prevLead's + * snapshot instead of taking a new one, but the ancestors scroll + * might have updated while the prevLead is unmounted. We need to + * update the scroll again to make sure the layout we measure is + * up to date. + */ + if (this.resumeFrom && !this.resumeFrom.instance) { + for (var i = 0; i < this.path.length; i++) { + var node = this.path[i]; + node.updateScroll(); + } + } + var measured = this.measure(); + roundBox(measured); + var prevLayout = this.layout; + this.layout = { + measured: measured, + actual: this.removeElementScroll(measured) + }; + this.layoutCorrected = createBox(); + this.isLayoutDirty = false; + this.projectionDelta = undefined; + this.notifyListeners("measure", this.layout.actual); + (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.notifyLayoutMeasure(this.layout.actual, prevLayout === null || prevLayout === void 0 ? void 0 : prevLayout.actual); + }; + ProjectionNode.prototype.updateScroll = function () { + if (this.options.layoutScroll && this.instance) { + this.isScrollRoot = checkIsScrollRoot(this.instance); + this.scroll = measureScroll(this.instance); + } + }; + ProjectionNode.prototype.resetTransform = function () { + var _a; + if (!resetTransform) return; + var isResetRequested = this.isLayoutDirty || this.shouldResetTransform; + var hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); + var transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate; + var transformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, ""); + var transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; + if (isResetRequested && (hasProjection || hasTransform(this.latestValues) || transformTemplateHasChanged)) { + resetTransform(this.instance, transformTemplateValue); + this.shouldResetTransform = false; + this.scheduleRender(); + } + }; + ProjectionNode.prototype.measure = function () { + var visualElement = this.options.visualElement; + if (!visualElement) return createBox(); + var box = visualElement.measureViewportBox(); + // Remove viewport scroll to give page-relative coordinates + var scroll = this.root.scroll; + if (scroll) { + translateAxis(box.x, scroll.x); + translateAxis(box.y, scroll.y); + } + return box; + }; + ProjectionNode.prototype.removeElementScroll = function (box) { + var boxWithoutScroll = createBox(); + copyBoxInto(boxWithoutScroll, box); + /** + * Performance TODO: Keep a cumulative scroll offset down the tree + * rather than loop back up the path. + */ + for (var i = 0; i < this.path.length; i++) { + var node = this.path[i]; + var scroll_1 = node.scroll, + options = node.options, + isScrollRoot = node.isScrollRoot; + if (node !== this.root && scroll_1 && options.layoutScroll) { + /** + * If this is a new scroll root, we want to remove all previous scrolls + * from the viewport box. + */ + if (isScrollRoot) { + copyBoxInto(boxWithoutScroll, box); + var rootScroll = this.root.scroll; + /** + * Undo the application of page scroll that was originally added + * to the measured bounding box. + */ + if (rootScroll) { + translateAxis(boxWithoutScroll.x, -rootScroll.x); + translateAxis(boxWithoutScroll.y, -rootScroll.y); } - function triggerElectric(cm, inserted) { - if (!cm.options.electricChars || !cm.options.smartIndent) { - return; - } - var sel = cm.doc.sel; - for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { - var range2 = sel.ranges[i2]; - if ( - range2.head.ch > 100 || - (i2 && sel.ranges[i2 - 1].head.line == range2.head.line) - ) { - continue; - } - var mode = cm.getModeAt(range2.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) { - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range2.head.line, "smart"); - break; - } + } + translateAxis(boxWithoutScroll.x, scroll_1.x); + translateAxis(boxWithoutScroll.y, scroll_1.y); + } + } + return boxWithoutScroll; + }; + ProjectionNode.prototype.applyTransform = function (box, transformOnly) { + if (transformOnly === void 0) { + transformOnly = false; + } + var withTransforms = createBox(); + copyBoxInto(withTransforms, box); + for (var i = 0; i < this.path.length; i++) { + var node = this.path[i]; + if (!transformOnly && node.options.layoutScroll && node.scroll && node !== node.root) { + transformBox(withTransforms, { + x: -node.scroll.x, + y: -node.scroll.y + }); + } + if (!hasTransform(node.latestValues)) continue; + transformBox(withTransforms, node.latestValues); + } + if (hasTransform(this.latestValues)) { + transformBox(withTransforms, this.latestValues); + } + return withTransforms; + }; + ProjectionNode.prototype.removeTransform = function (box) { + var _a; + var boxWithoutTransform = createBox(); + copyBoxInto(boxWithoutTransform, box); + for (var i = 0; i < this.path.length; i++) { + var node = this.path[i]; + if (!node.instance) continue; + if (!hasTransform(node.latestValues)) continue; + hasScale(node.latestValues) && node.updateSnapshot(); + var sourceBox = createBox(); + var nodeBox = node.measure(); + copyBoxInto(sourceBox, nodeBox); + removeBoxTransforms(boxWithoutTransform, node.latestValues, (_a = node.snapshot) === null || _a === void 0 ? void 0 : _a.layout, sourceBox); + } + if (hasTransform(this.latestValues)) { + removeBoxTransforms(boxWithoutTransform, this.latestValues); + } + return boxWithoutTransform; + }; + /** + * + */ + ProjectionNode.prototype.setTargetDelta = function (delta) { + this.targetDelta = delta; + this.root.scheduleUpdateProjection(); + }; + ProjectionNode.prototype.setOptions = function (options) { + var _a; + this.options = tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), options), { + crossfade: (_a = options.crossfade) !== null && _a !== void 0 ? _a : true + }); + }; + ProjectionNode.prototype.clearMeasurements = function () { + this.scroll = undefined; + this.layout = undefined; + this.snapshot = undefined; + this.prevTransformTemplateValue = undefined; + this.targetDelta = undefined; + this.target = undefined; + this.isLayoutDirty = false; + }; + /** + * Frame calculations + */ + ProjectionNode.prototype.resolveTargetDelta = function () { + var _a; + var _b = this.options, + layout = _b.layout, + layoutId = _b.layoutId; + /** + * If we have no layout, we can't perform projection, so early return + */ + if (!this.layout || !(layout || layoutId)) return; + /** + * If we don't have a targetDelta but do have a layout, we can attempt to resolve + * a relativeParent. This will allow a component to perform scale correction + * even if no animation has started. + */ + // TODO If this is unsuccessful this currently happens every frame + if (!this.targetDelta && !this.relativeTarget) { + // TODO: This is a semi-repetition of further down this function, make DRY + this.relativeParent = this.getClosestProjectingParent(); + if (this.relativeParent && this.relativeParent.layout) { + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.layout.actual, this.relativeParent.layout.actual); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + } + /** + * If we have no relative target or no target delta our target isn't valid + * for this frame. + */ + if (!this.relativeTarget && !this.targetDelta) return; + /** + * Lazy-init target data structure + */ + if (!this.target) { + this.target = createBox(); + this.targetWithTransforms = createBox(); + } + /** + * If we've got a relative box for this component, resolve it into a target relative to the parent. + */ + if (this.relativeTarget && this.relativeTargetOrigin && ((_a = this.relativeParent) === null || _a === void 0 ? void 0 : _a.target)) { + calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target); + /** + * If we've only got a targetDelta, resolve it into a target + */ + } else if (this.targetDelta) { + if (Boolean(this.resumingFrom)) { + // TODO: This is creating a new object every frame + this.target = this.applyTransform(this.layout.actual); + } else { + copyBoxInto(this.target, this.layout.actual); + } + applyBoxDelta(this.target, this.targetDelta); + } else { + /** + * If no target, use own layout as target + */ + copyBoxInto(this.target, this.layout.actual); + } + /** + * If we've been told to attempt to resolve a relative target, do so. + */ + if (this.attemptToResolveRelativeTarget) { + this.attemptToResolveRelativeTarget = false; + this.relativeParent = this.getClosestProjectingParent(); + if (this.relativeParent && Boolean(this.relativeParent.resumingFrom) === Boolean(this.resumingFrom) && !this.relativeParent.options.layoutScroll && this.relativeParent.target) { + this.relativeTarget = createBox(); + this.relativeTargetOrigin = createBox(); + calcRelativePosition(this.relativeTargetOrigin, this.target, this.relativeParent.target); + copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); + } + } + }; + ProjectionNode.prototype.getClosestProjectingParent = function () { + if (!this.parent || hasTransform(this.parent.latestValues)) return undefined; + if ((this.parent.relativeTarget || this.parent.targetDelta) && this.parent.layout) { + return this.parent; + } else { + return this.parent.getClosestProjectingParent(); + } + }; + ProjectionNode.prototype.calcProjection = function () { + var _a; + var _b = this.options, + layout = _b.layout, + layoutId = _b.layoutId; + /** + * If this section of the tree isn't animating we can + * delete our target sources for the following frame. + */ + this.isTreeAnimating = Boolean(((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimating) || this.currentAnimation || this.pendingAnimation); + if (!this.isTreeAnimating) { + this.targetDelta = this.relativeTarget = undefined; + } + if (!this.layout || !(layout || layoutId)) return; + var lead = this.getLead(); + /** + * Reset the corrected box with the latest values from box, as we're then going + * to perform mutative operations on it. + */ + copyBoxInto(this.layoutCorrected, this.layout.actual); + /** + * Apply all the parent deltas to this box to produce the corrected box. This + * is the layout box, as it will appear on screen as a result of the transforms of its parents. + */ + applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, Boolean(this.resumingFrom) || this !== lead); + var target = lead.target; + if (!target) return; + if (!this.projectionDelta) { + this.projectionDelta = createDelta(); + this.projectionDeltaWithTransform = createDelta(); + } + var prevTreeScaleX = this.treeScale.x; + var prevTreeScaleY = this.treeScale.y; + var prevProjectionTransform = this.projectionTransform; + /** + * Update the delta between the corrected box and the target box before user-set transforms were applied. + * This will allow us to calculate the corrected borderRadius and boxShadow to compensate + * for our layout reprojection, but still allow them to be scaled correctly by the user. + * It might be that to simplify this we may want to accept that user-set scale is also corrected + * and we wouldn't have to keep and calc both deltas, OR we could support a user setting + * to allow people to choose whether these styles are corrected based on just the + * layout reprojection or the final bounding box. + */ + calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); + this.projectionTransform = buildProjectionTransform(this.projectionDelta, this.treeScale); + if (this.projectionTransform !== prevProjectionTransform || this.treeScale.x !== prevTreeScaleX || this.treeScale.y !== prevTreeScaleY) { + this.hasProjected = true; + this.scheduleRender(); + this.notifyListeners("projectionUpdate", target); + } + }; + ProjectionNode.prototype.hide = function () { + this.isVisible = false; + // TODO: Schedule render + }; + ProjectionNode.prototype.show = function () { + this.isVisible = true; + // TODO: Schedule render + }; + ProjectionNode.prototype.scheduleRender = function (notifyAll) { + var _a, _b, _c; + if (notifyAll === void 0) { + notifyAll = true; + } + (_b = (_a = this.options).scheduleRender) === null || _b === void 0 ? void 0 : _b.call(_a); + notifyAll && ((_c = this.getStack()) === null || _c === void 0 ? void 0 : _c.scheduleRender()); + if (this.resumingFrom && !this.resumingFrom.instance) { + this.resumingFrom = undefined; + } + }; + ProjectionNode.prototype.setAnimationOrigin = function (delta, hasOnlyRelativeTargetChanged) { + var _this = this; + var _a; + if (hasOnlyRelativeTargetChanged === void 0) { + hasOnlyRelativeTargetChanged = false; + } + var snapshot = this.snapshot; + var snapshotLatestValues = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.latestValues) || {}; + var mixedValues = tslib.__assign({}, this.latestValues); + var targetDelta = createDelta(); + this.relativeTarget = this.relativeTargetOrigin = undefined; + this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; + var relativeLayout = createBox(); + var isSharedLayoutAnimation = snapshot === null || snapshot === void 0 ? void 0 : snapshot.isShared; + var isOnlyMember = (((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.members.length) || 0) <= 1; + var shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && !isOnlyMember && this.options.crossfade === true && !this.path.some(hasOpacityCrossfade)); + this.animationProgress = 0; + this.mixTargetDelta = function (latest) { + var _a; + var progress = latest / 1000; + mixAxisDelta(targetDelta.x, delta.x, progress); + mixAxisDelta(targetDelta.y, delta.y, progress); + _this.setTargetDelta(targetDelta); + if (_this.relativeTarget && _this.relativeTargetOrigin && _this.layout && ((_a = _this.relativeParent) === null || _a === void 0 ? void 0 : _a.layout)) { + calcRelativePosition(relativeLayout, _this.layout.actual, _this.relativeParent.layout.actual); + mixBox(_this.relativeTarget, _this.relativeTargetOrigin, relativeLayout, progress); + } + if (isSharedLayoutAnimation) { + _this.animationValues = mixedValues; + mixValues(mixedValues, snapshotLatestValues, _this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember); + } + _this.root.scheduleUpdateProjection(); + _this.scheduleRender(); + _this.animationProgress = progress; + }; + this.mixTargetDelta(0); + }; + ProjectionNode.prototype.startAnimation = function (options) { + var _this = this; + var _a, _b; + this.notifyListeners("animationStart"); + (_a = this.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); + if (this.resumingFrom) { + (_b = this.resumingFrom.currentAnimation) === null || _b === void 0 ? void 0 : _b.stop(); + } + if (this.pendingAnimation) { + sync.cancelSync.update(this.pendingAnimation); + this.pendingAnimation = undefined; + } + /** + * Start the animation in the next frame to have a frame with progress 0, + * where the target is the same as when the animation started, so we can + * calculate the relative positions correctly for instant transitions. + */ + this.pendingAnimation = sync__default["default"].update(function () { + globalProjectionState.hasAnimatedSinceResize = true; + _this.currentAnimation = animate(0, animationTarget, tslib.__assign(tslib.__assign({}, options), { + onUpdate: function (latest) { + var _a; + _this.mixTargetDelta(latest); + (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, latest); + }, + onComplete: function () { + var _a; + (_a = options.onComplete) === null || _a === void 0 ? void 0 : _a.call(options); + _this.completeAnimation(); + } + })); + if (_this.resumingFrom) { + _this.resumingFrom.currentAnimation = _this.currentAnimation; + } + _this.pendingAnimation = undefined; + }); + }; + ProjectionNode.prototype.completeAnimation = function () { + var _a; + if (this.resumingFrom) { + this.resumingFrom.currentAnimation = undefined; + this.resumingFrom.preserveOpacity = undefined; + } + (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.exitAnimationComplete(); + this.resumingFrom = this.currentAnimation = this.animationValues = undefined; + this.notifyListeners("animationComplete"); + }; + ProjectionNode.prototype.finishAnimation = function () { + var _a; + if (this.currentAnimation) { + (_a = this.mixTargetDelta) === null || _a === void 0 ? void 0 : _a.call(this, animationTarget); + this.currentAnimation.stop(); + } + this.completeAnimation(); + }; + ProjectionNode.prototype.applyTransformsToTarget = function () { + var _a = this.getLead(), + targetWithTransforms = _a.targetWithTransforms, + target = _a.target, + layout = _a.layout, + latestValues = _a.latestValues; + if (!targetWithTransforms || !target || !layout) return; + copyBoxInto(targetWithTransforms, target); + /** + * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal. + * This is the final box that we will then project into by calculating a transform delta and + * applying it to the corrected box. + */ + transformBox(targetWithTransforms, latestValues); + /** + * Update the delta between the corrected box and the final target box, after + * user-set transforms are applied to it. This will be used by the renderer to + * create a transform style that will reproject the element from its actual layout + * into the desired bounding box. + */ + calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); + }; + ProjectionNode.prototype.registerSharedNode = function (layoutId, node) { + var _a, _b, _c; + if (!this.sharedNodes.has(layoutId)) { + this.sharedNodes.set(layoutId, new NodeStack()); + } + var stack = this.sharedNodes.get(layoutId); + stack.add(node); + node.promote({ + transition: (_a = node.options.initialPromotionConfig) === null || _a === void 0 ? void 0 : _a.transition, + preserveFollowOpacity: (_c = (_b = node.options.initialPromotionConfig) === null || _b === void 0 ? void 0 : _b.shouldPreserveFollowOpacity) === null || _c === void 0 ? void 0 : _c.call(_b, node) + }); + }; + ProjectionNode.prototype.isLead = function () { + var stack = this.getStack(); + return stack ? stack.lead === this : true; + }; + ProjectionNode.prototype.getLead = function () { + var _a; + var layoutId = this.options.layoutId; + return layoutId ? ((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.lead) || this : this; + }; + ProjectionNode.prototype.getPrevLead = function () { + var _a; + var layoutId = this.options.layoutId; + return layoutId ? (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.prevLead : undefined; + }; + ProjectionNode.prototype.getStack = function () { + var layoutId = this.options.layoutId; + if (layoutId) return this.root.sharedNodes.get(layoutId); + }; + ProjectionNode.prototype.promote = function (_a) { + var _b = _a === void 0 ? {} : _a, + needsReset = _b.needsReset, + transition = _b.transition, + preserveFollowOpacity = _b.preserveFollowOpacity; + var stack = this.getStack(); + if (stack) stack.promote(this, preserveFollowOpacity); + if (needsReset) { + this.projectionDelta = undefined; + this.needsReset = true; + } + if (transition) this.setOptions({ + transition: transition + }); + }; + ProjectionNode.prototype.relegate = function () { + var stack = this.getStack(); + if (stack) { + return stack.relegate(this); + } else { + return false; + } + }; + ProjectionNode.prototype.resetRotation = function () { + var visualElement = this.options.visualElement; + if (!visualElement) return; + // If there's no detected rotation values, we can early return without a forced render. + var hasRotate = false; + // Keep a record of all the values we've reset + var resetValues = {}; + // Check the rotate value of all axes and reset to 0 + for (var i = 0; i < transformAxes.length; i++) { + var axis = transformAxes[i]; + var key = "rotate" + axis; + // If this rotation doesn't exist as a motion value, then we don't + // need to reset it + if (!visualElement.getStaticValue(key)) { + continue; + } + hasRotate = true; + // Record the rotation and then temporarily set it to 0 + resetValues[key] = visualElement.getStaticValue(key); + visualElement.setStaticValue(key, 0); + } + // If there's no rotation values, we don't need to do any more. + if (!hasRotate) return; + // Force a render of this element to apply the transform with all rotations + // set to 0. + visualElement === null || visualElement === void 0 ? void 0 : visualElement.syncRender(); + // Put back all the values we reset + for (var key in resetValues) { + visualElement.setStaticValue(key, resetValues[key]); + } + // Schedule a render for the next frame. This ensures we won't visually + // see the element with the reset rotate value applied. + visualElement.scheduleRender(); + }; + ProjectionNode.prototype.getProjectionStyles = function (styleProp) { + var _a, _b, _c, _d, _e, _f; + if (styleProp === void 0) { + styleProp = {}; + } + // TODO: Return lifecycle-persistent object + var styles = {}; + if (!this.instance || this.isSVG) return styles; + if (!this.isVisible) { + return { + visibility: "hidden" + }; + } else { + styles.visibility = ""; + } + var transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate; + if (this.needsReset) { + this.needsReset = false; + styles.opacity = ""; + styles.pointerEvents = resolveMotionValue(styleProp.pointerEvents) || ""; + styles.transform = transformTemplate ? transformTemplate(this.latestValues, "") : "none"; + return styles; + } + var lead = this.getLead(); + if (!this.projectionDelta || !this.layout || !lead.target) { + var emptyStyles = {}; + if (this.options.layoutId) { + emptyStyles.opacity = (_b = this.latestValues.opacity) !== null && _b !== void 0 ? _b : 1; + emptyStyles.pointerEvents = resolveMotionValue(styleProp.pointerEvents) || ""; + } + if (this.hasProjected && !hasTransform(this.latestValues)) { + emptyStyles.transform = transformTemplate ? transformTemplate({}, "") : "none"; + this.hasProjected = false; + } + return emptyStyles; + } + var valuesToRender = lead.animationValues || lead.latestValues; + this.applyTransformsToTarget(); + styles.transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); + if (transformTemplate) { + styles.transform = transformTemplate(valuesToRender, styles.transform); + } + var _g = this.projectionDelta, + x = _g.x, + y = _g.y; + styles.transformOrigin = "".concat(x.origin * 100, "% ").concat(y.origin * 100, "% 0"); + if (lead.animationValues) { + /** + * If the lead component is animating, assign this either the entering/leaving + * opacity + */ + styles.opacity = lead === this ? (_d = (_c = valuesToRender.opacity) !== null && _c !== void 0 ? _c : this.latestValues.opacity) !== null && _d !== void 0 ? _d : 1 : this.preserveOpacity ? this.latestValues.opacity : valuesToRender.opacityExit; + } else { + /** + * Or we're not animating at all, set the lead component to its actual + * opacity and other components to hidden. + */ + styles.opacity = lead === this ? (_e = valuesToRender.opacity) !== null && _e !== void 0 ? _e : "" : (_f = valuesToRender.opacityExit) !== null && _f !== void 0 ? _f : 0; + } + /** + * Apply scale correction + */ + for (var key in scaleCorrectors) { + if (valuesToRender[key] === undefined) continue; + var _h = scaleCorrectors[key], + correct = _h.correct, + applyTo = _h.applyTo; + var corrected = correct(valuesToRender[key], lead); + if (applyTo) { + var num = applyTo.length; + for (var i = 0; i < num; i++) { + styles[applyTo[i]] = corrected; + } + } else { + styles[key] = corrected; + } + } + /** + * Disable pointer events on follow components. This is to ensure + * that if a follow component covers a lead component it doesn't block + * pointer events on the lead. + */ + if (this.options.layoutId) { + styles.pointerEvents = lead === this ? resolveMotionValue(styleProp.pointerEvents) || "" : "none"; + } + return styles; + }; + ProjectionNode.prototype.clearSnapshot = function () { + this.resumeFrom = this.snapshot = undefined; + }; + // Only run on root + ProjectionNode.prototype.resetTree = function () { + this.root.nodes.forEach(function (node) { + var _a; + return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); + }); + this.root.nodes.forEach(clearMeasurements); + this.root.sharedNodes.clear(); + }; + return ProjectionNode; + }(); + } + function updateLayout(node) { + node.updateLayout(); + } + function notifyLayoutUpdate(node) { + var _a, _b, _c, _d; + var snapshot = (_b = (_a = node.resumeFrom) === null || _a === void 0 ? void 0 : _a.snapshot) !== null && _b !== void 0 ? _b : node.snapshot; + if (node.isLead() && node.layout && snapshot && node.hasListeners("didUpdate")) { + var _e = node.layout, + layout_1 = _e.actual, + measuredLayout = _e.measured; + // TODO Maybe we want to also resize the layout snapshot so we don't trigger + // animations for instance if layout="size" and an element has only changed position + if (node.options.animationType === "size") { + eachAxis(function (axis) { + var axisSnapshot = snapshot.isShared ? snapshot.measured[axis] : snapshot.layout[axis]; + var length = calcLength(axisSnapshot); + axisSnapshot.min = layout_1[axis].min; + axisSnapshot.max = axisSnapshot.min + length; + }); + } else if (node.options.animationType === "position") { + eachAxis(function (axis) { + var axisSnapshot = snapshot.isShared ? snapshot.measured[axis] : snapshot.layout[axis]; + var length = calcLength(layout_1[axis]); + axisSnapshot.max = axisSnapshot.min + length; + }); + } + var layoutDelta = createDelta(); + calcBoxDelta(layoutDelta, layout_1, snapshot.layout); + var visualDelta = createDelta(); + if (snapshot.isShared) { + calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measured); + } else { + calcBoxDelta(visualDelta, layout_1, snapshot.layout); + } + var hasLayoutChanged = !isDeltaZero(layoutDelta); + var hasRelativeTargetChanged = false; + if (!node.resumeFrom) { + node.relativeParent = node.getClosestProjectingParent(); + /** + * If the relativeParent is itself resuming from a different element then + * the relative snapshot is not relavent + */ + if (node.relativeParent && !node.relativeParent.resumeFrom) { + var _f = node.relativeParent, + parentSnapshot = _f.snapshot, + parentLayout = _f.layout; + if (parentSnapshot && parentLayout) { + var relativeSnapshot = createBox(); + calcRelativePosition(relativeSnapshot, snapshot.layout, parentSnapshot.layout); + var relativeLayout = createBox(); + calcRelativePosition(relativeLayout, layout_1, parentLayout.actual); + if (!boxEquals(relativeSnapshot, relativeLayout)) { + hasRelativeTargetChanged = true; + } + } + } + } + node.notifyListeners("didUpdate", { + layout: layout_1, + snapshot: snapshot, + delta: visualDelta, + layoutDelta: layoutDelta, + hasLayoutChanged: hasLayoutChanged, + hasRelativeTargetChanged: hasRelativeTargetChanged + }); + } else if (node.isLead()) { + (_d = (_c = node.options).onExitComplete) === null || _d === void 0 ? void 0 : _d.call(_c); + } + /** + * Clearing transition + * TODO: Investigate why this transition is being passed in as {type: false } from Framer + * and why we need it at all + */ + node.options.transition = undefined; + } + function clearSnapshot(node) { + node.clearSnapshot(); + } + function clearMeasurements(node) { + node.clearMeasurements(); + } + function resetTransformStyle(node) { + var visualElement = node.options.visualElement; + if (visualElement === null || visualElement === void 0 ? void 0 : visualElement.getProps().onBeforeLayoutMeasure) { + visualElement.notifyBeforeLayoutMeasure(); + } + node.resetTransform(); + } + function finishAnimation(node) { + node.finishAnimation(); + node.targetDelta = node.relativeTarget = node.target = undefined; + } + function resolveTargetDelta(node) { + node.resolveTargetDelta(); + } + function calcProjection(node) { + node.calcProjection(); + } + function resetRotation(node) { + node.resetRotation(); + } + function removeLeadSnapshots(stack) { + stack.removeLeadSnapshot(); + } + function mixAxisDelta(output, delta, p) { + output.translate = popmotion.mix(delta.translate, 0, p); + output.scale = popmotion.mix(delta.scale, 1, p); + output.origin = delta.origin; + output.originPoint = delta.originPoint; + } + function mixAxis(output, from, to, p) { + output.min = popmotion.mix(from.min, to.min, p); + output.max = popmotion.mix(from.max, to.max, p); + } + function mixBox(output, from, to, p) { + mixAxis(output.x, from.x, to.x, p); + mixAxis(output.y, from.y, to.y, p); + } + function hasOpacityCrossfade(node) { + return node.animationValues && node.animationValues.opacityExit !== undefined; + } + var defaultLayoutTransition = { + duration: 0.45, + ease: [0.4, 0, 0.1, 1] + }; + function mountNodeEarly(node, id) { + /** + * Rather than searching the DOM from document we can search the + * path for the deepest mounted ancestor and search from there + */ + var searchNode = node.root; + for (var i = node.path.length - 1; i >= 0; i--) { + if (Boolean(node.path[i].instance)) { + searchNode = node.path[i]; + break; + } + } + var searchElement = searchNode && searchNode !== node.root ? searchNode.instance : document; + var element = searchElement.querySelector("[data-projection-id=\"".concat(id, "\"]")); + if (element) node.mount(element, true); + } + function roundAxis(axis) { + axis.min = Math.round(axis.min); + axis.max = Math.round(axis.max); + } + function roundBox(box) { + roundAxis(box.x); + roundAxis(box.y); + } + var DocumentProjectionNode = createProjectionNode({ + attachResizeListener: function (ref, notify) { + return addDomEvent(ref, "resize", notify); + }, + measureScroll: function () { + return { + x: document.documentElement.scrollLeft || document.body.scrollLeft, + y: document.documentElement.scrollTop || document.body.scrollTop + }; + }, + checkIsScrollRoot: function () { + return true; + } + }); + var rootProjectionNode = { + current: undefined + }; + var HTMLProjectionNode = createProjectionNode({ + measureScroll: function (instance) { + return { + x: instance.scrollLeft, + y: instance.scrollTop + }; + }, + defaultParent: function () { + if (!rootProjectionNode.current) { + var documentNode = new DocumentProjectionNode(0, {}); + documentNode.mount(window); + documentNode.setOptions({ + layoutScroll: true + }); + rootProjectionNode.current = documentNode; + } + return rootProjectionNode.current; + }, + resetTransform: function (instance, value) { + instance.style.transform = value !== null && value !== void 0 ? value : "none"; + }, + checkIsScrollRoot: function (instance) { + return Boolean(window.getComputedStyle(instance).position === "fixed"); + } + }); + var featureBundle = tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, animations), gestureAnimations), drag), layoutFeatures); + /** + * HTML & SVG components, optimised for use with gestures and animation. These can be used as + * drop-in replacements for any HTML & SVG component, all CSS & SVG properties are supported. + * + * @public + */ + var motion = /*@__PURE__*/createMotionProxy(function (Component, config) { + return createDomMotionConfig(Component, config, featureBundle, createDomVisualElement, HTMLProjectionNode); + }); + /** + * Create a DOM `motion` component with the provided string. This is primarily intended + * as a full alternative to `motion` for consumers who have to support environments that don't + * support `Proxy`. + * + * ```javascript + * import { createDomMotionComponent } from "framer-motion" + * + * const motion = { + * div: createDomMotionComponent('div') + * } + * ``` + * + * @public + */ + function createDomMotionComponent(key) { + return createMotionComponent(createDomMotionConfig(key, { + forwardMotionProps: false + }, featureBundle, createDomVisualElement, HTMLProjectionNode)); + } + + /** + * @public + */ + var m = createMotionProxy(createDomMotionConfig); + function useIsMounted() { + var isMounted = React.useRef(false); + useIsomorphicLayoutEffect(function () { + isMounted.current = true; + return function () { + isMounted.current = false; + }; + }, []); + return isMounted; + } + function useForceUpdate() { + var isMounted = useIsMounted(); + var _a = tslib.__read(React.useState(0), 2), + forcedRenderCount = _a[0], + setForcedRenderCount = _a[1]; + var forceRender = React.useCallback(function () { + isMounted.current && setForcedRenderCount(forcedRenderCount + 1); + }, [forcedRenderCount]); + /** + * Defer this to the end of the next animation frame in case there are multiple + * synchronous calls. + */ + var deferredForceRender = React.useCallback(function () { + return sync__default["default"].postRender(forceRender); + }, [forceRender]); + return [deferredForceRender, forcedRenderCount]; + } + var PresenceChild = function (_a) { + var children = _a.children, + initial = _a.initial, + isPresent = _a.isPresent, + onExitComplete = _a.onExitComplete, + custom = _a.custom, + presenceAffectsLayout = _a.presenceAffectsLayout; + var presenceChildren = useConstant(newChildrenMap); + var id = useId(); + var context = React.useMemo(function () { + return { + id: id, + initial: initial, + isPresent: isPresent, + custom: custom, + onExitComplete: function (childId) { + var e_1, _a; + presenceChildren.set(childId, true); + try { + for (var _b = tslib.__values(presenceChildren.values()), _c = _b.next(); !_c.done; _c = _b.next()) { + var isComplete = _c.value; + if (!isComplete) return; // can stop searching when any is incomplete + } + } catch (e_1_1) { + e_1 = { + error: e_1_1 + }; + } finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } finally { + if (e_1) throw e_1.error; + } + } + onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete(); + }, + register: function (childId) { + presenceChildren.set(childId, false); + return function () { + return presenceChildren.delete(childId); + }; + } + }; + }, + /** + * If the presence of a child affects the layout of the components around it, + * we want to make a new context value to ensure they get re-rendered + * so they can detect that layout change. + */ + presenceAffectsLayout ? undefined : [isPresent]); + React.useMemo(function () { + presenceChildren.forEach(function (_, key) { + return presenceChildren.set(key, false); + }); + }, [isPresent]); + /** + * If there's no `motion` components to fire exit animations, we want to remove this + * component immediately. + */ + React__namespace.useEffect(function () { + !isPresent && !presenceChildren.size && (onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete()); + }, [isPresent]); + return React__namespace.createElement(PresenceContext.Provider, { + value: context + }, children); + }; + function newChildrenMap() { + return new Map(); + } + var getChildKey = function (child) { + return child.key || ""; + }; + function updateChildLookup(children, allChildren) { + children.forEach(function (child) { + var key = getChildKey(child); + allChildren.set(key, child); + }); + } + function onlyElements(children) { + var filtered = []; + // We use forEach here instead of map as map mutates the component key by preprending `.$` + React.Children.forEach(children, function (child) { + if (React.isValidElement(child)) filtered.push(child); + }); + return filtered; + } + /** + * `AnimatePresence` enables the animation of components that have been removed from the tree. + * + * When adding/removing more than a single child, every child **must** be given a unique `key` prop. + * + * Any `motion` components that have an `exit` property defined will animate out when removed from + * the tree. + * + * ```jsx + * import { motion, AnimatePresence } from 'framer-motion' + * + * export const Items = ({ items }) => ( + * + * {items.map(item => ( + * + * ))} + * + * ) + * ``` + * + * You can sequence exit animations throughout a tree using variants. + * + * If a child contains multiple `motion` components with `exit` props, it will only unmount the child + * once all `motion` components have finished animating out. Likewise, any components using + * `usePresence` all need to call `safeToRemove`. + * + * @public + */ + var AnimatePresence = function (_a) { + var children = _a.children, + custom = _a.custom, + _b = _a.initial, + initial = _b === void 0 ? true : _b, + onExitComplete = _a.onExitComplete, + exitBeforeEnter = _a.exitBeforeEnter, + _c = _a.presenceAffectsLayout, + presenceAffectsLayout = _c === void 0 ? true : _c; + // We want to force a re-render once all exiting animations have finished. We + // either use a local forceRender function, or one from a parent context if it exists. + var _d = tslib.__read(useForceUpdate(), 1), + forceRender = _d[0]; + var forceRenderLayoutGroup = React.useContext(LayoutGroupContext).forceRender; + if (forceRenderLayoutGroup) forceRender = forceRenderLayoutGroup; + var isMounted = useIsMounted(); + // Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key + var filteredChildren = onlyElements(children); + var childrenToRender = filteredChildren; + var exiting = new Set(); + // Keep a living record of the children we're actually rendering so we + // can diff to figure out which are entering and exiting + var presentChildren = React.useRef(childrenToRender); + // A lookup table to quickly reference components by key + var allChildren = React.useRef(new Map()).current; + // If this is the initial component render, just deal with logic surrounding whether + // we play onMount animations or not. + var isInitialRender = React.useRef(true); + useIsomorphicLayoutEffect(function () { + isInitialRender.current = false; + updateChildLookup(filteredChildren, allChildren); + presentChildren.current = childrenToRender; + }); + useUnmountEffect(function () { + isInitialRender.current = true; + allChildren.clear(); + exiting.clear(); + }); + if (isInitialRender.current) { + return React__namespace.createElement(React__namespace.Fragment, null, childrenToRender.map(function (child) { + return React__namespace.createElement(PresenceChild, { + key: getChildKey(child), + isPresent: true, + initial: initial ? undefined : false, + presenceAffectsLayout: presenceAffectsLayout + }, child); + })); + } + // If this is a subsequent render, deal with entering and exiting children + childrenToRender = tslib.__spreadArray([], tslib.__read(childrenToRender), false); + // Diff the keys of the currently-present and target children to update our + // exiting list. + var presentKeys = presentChildren.current.map(getChildKey); + var targetKeys = filteredChildren.map(getChildKey); + // Diff the present children with our target children and mark those that are exiting + var numPresent = presentKeys.length; + for (var i = 0; i < numPresent; i++) { + var key = presentKeys[i]; + if (targetKeys.indexOf(key) === -1) { + exiting.add(key); + } + } + // If we currently have exiting children, and we're deferring rendering incoming children + // until after all current children have exiting, empty the childrenToRender array + if (exitBeforeEnter && exiting.size) { + childrenToRender = []; + } + // Loop through all currently exiting components and clone them to overwrite `animate` + // with any `exit` prop they might have defined. + exiting.forEach(function (key) { + // If this component is actually entering again, early return + if (targetKeys.indexOf(key) !== -1) return; + var child = allChildren.get(key); + if (!child) return; + var insertionIndex = presentKeys.indexOf(key); + var onExit = function () { + allChildren.delete(key); + exiting.delete(key); + // Remove this child from the present children + var removeIndex = presentChildren.current.findIndex(function (presentChild) { + return presentChild.key === key; + }); + presentChildren.current.splice(removeIndex, 1); + // Defer re-rendering until all exiting children have indeed left + if (!exiting.size) { + presentChildren.current = filteredChildren; + if (isMounted.current === false) return; + forceRender(); + onExitComplete && onExitComplete(); + } + }; + childrenToRender.splice(insertionIndex, 0, React__namespace.createElement(PresenceChild, { + key: getChildKey(child), + isPresent: false, + onExitComplete: onExit, + custom: custom, + presenceAffectsLayout: presenceAffectsLayout + }, child)); + }); + // Add `MotionContext` even to children that don't need it to ensure we're rendering + // the same tree between renders + childrenToRender = childrenToRender.map(function (child) { + var key = child.key; + return exiting.has(key) ? child : React__namespace.createElement(PresenceChild, { + key: getChildKey(child), + isPresent: true, + presenceAffectsLayout: presenceAffectsLayout + }, child); + }); + if (env !== "production" && exitBeforeEnter && childrenToRender.length > 1) { + console.warn("You're attempting to animate multiple children within AnimatePresence, but its exitBeforeEnter prop is set to true. This will lead to odd visual behaviour."); + } + return React__namespace.createElement(React__namespace.Fragment, null, exiting.size ? childrenToRender : childrenToRender.map(function (child) { + return React.cloneElement(child); + })); + }; + + /** + * @deprecated + */ + var DeprecatedLayoutGroupContext = React.createContext(null); + var notify = function (node) { + return !node.isLayoutDirty && node.willUpdate(false); + }; + function nodeGroup() { + var nodes = new Set(); + var subscriptions = new WeakMap(); + var dirtyAll = function () { + return nodes.forEach(notify); + }; + return { + add: function (node) { + nodes.add(node); + subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll)); + }, + remove: function (node) { + var _a; + nodes.delete(node); + (_a = subscriptions.get(node)) === null || _a === void 0 ? void 0 : _a(); + subscriptions.delete(node); + dirtyAll(); + }, + dirty: dirtyAll + }; + } + var shouldInheritGroup = function (inherit) { + return inherit === true; + }; + var shouldInheritId = function (inherit) { + return shouldInheritGroup(inherit === true) || inherit === "id"; + }; + var LayoutGroup = function (_a) { + var _b, _c; + var children = _a.children, + id = _a.id, + inheritId = _a.inheritId, + _d = _a.inherit, + inherit = _d === void 0 ? true : _d; + // Maintain backwards-compatibility with inheritId until 7.0 + if (inheritId !== undefined) inherit = inheritId; + var layoutGroupContext = React.useContext(LayoutGroupContext); + var deprecatedLayoutGroupContext = React.useContext(DeprecatedLayoutGroupContext); + var _e = tslib.__read(useForceUpdate(), 2), + forceRender = _e[0], + key = _e[1]; + var context = React.useRef(null); + var upstreamId = (_b = layoutGroupContext.id) !== null && _b !== void 0 ? _b : deprecatedLayoutGroupContext; + if (context.current === null) { + if (shouldInheritId(inherit) && upstreamId) { + id = id ? upstreamId + "-" + id : upstreamId; + } + context.current = { + id: id, + group: shouldInheritGroup(inherit) ? (_c = layoutGroupContext === null || layoutGroupContext === void 0 ? void 0 : layoutGroupContext.group) !== null && _c !== void 0 ? _c : nodeGroup() : nodeGroup() + }; + } + var memoizedContext = React.useMemo(function () { + return tslib.__assign(tslib.__assign({}, context.current), { + forceRender: forceRender + }); + }, [key]); + return React__namespace.createElement(LayoutGroupContext.Provider, { + value: memoizedContext + }, children); + }; + var id = 0; + var AnimateSharedLayout = function (_a) { + var children = _a.children; + React__namespace.useEffect(function () { + heyListen.warning(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations"); + }, []); + return React__namespace.createElement(LayoutGroup, { + id: useConstant(function () { + return "asl-".concat(id++); + }) + }, children); + }; + + /** + * `MotionConfig` is used to set configuration options for all children `motion` components. + * + * ```jsx + * import { motion, MotionConfig } from "framer-motion" + * + * export function App() { + * return ( + * + * + * + * ) + * } + * ``` + * + * @public + */ + function MotionConfig(_a) { + var children = _a.children, + isValidProp = _a.isValidProp, + config = tslib.__rest(_a, ["children", "isValidProp"]); + isValidProp && loadExternalIsValidProp(isValidProp); + /** + * Inherit props from any parent MotionConfig components + */ + config = tslib.__assign(tslib.__assign({}, React.useContext(MotionConfigContext)), config); + /** + * Don't allow isStatic to change between renders as it affects how many hooks + * motion components fire. + */ + config.isStatic = useConstant(function () { + return config.isStatic; + }); + /** + * Creating a new config context object will re-render every `motion` component + * every time it renders. So we only want to create a new one sparingly. + */ + var context = React.useMemo(function () { + return config; + }, [JSON.stringify(config.transition), config.transformPagePoint, config.reducedMotion]); + return React__namespace.createElement(MotionConfigContext.Provider, { + value: context + }, children); + } + + /** + * Used in conjunction with the `m` component to reduce bundle size. + * + * `m` is a version of the `motion` component that only loads functionality + * critical for the initial render. + * + * `LazyMotion` can then be used to either synchronously or asynchronously + * load animation and gesture support. + * + * ```jsx + * // Synchronous loading + * import { LazyMotion, m, domAnimations } from "framer-motion" + * + * function App() { + * return ( + * + * + * + * ) + * } + * + * // Asynchronous loading + * import { LazyMotion, m } from "framer-motion" + * + * function App() { + * return ( + * import('./path/to/domAnimations')}> + * + * + * ) + * } + * ``` + * + * @public + */ + function LazyMotion(_a) { + var children = _a.children, + features = _a.features, + _b = _a.strict, + strict = _b === void 0 ? false : _b; + var _c = tslib.__read(React.useState(!isLazyBundle(features)), 2), + setIsLoaded = _c[1]; + var loadedRenderer = React.useRef(undefined); + /** + * If this is a synchronous load, load features immediately + */ + if (!isLazyBundle(features)) { + var renderer = features.renderer, + loadedFeatures = tslib.__rest(features, ["renderer"]); + loadedRenderer.current = renderer; + loadFeatures(loadedFeatures); + } + React.useEffect(function () { + if (isLazyBundle(features)) { + features().then(function (_a) { + var renderer = _a.renderer, + loadedFeatures = tslib.__rest(_a, ["renderer"]); + loadFeatures(loadedFeatures); + loadedRenderer.current = renderer; + setIsLoaded(true); + }); + } + }, []); + return React__namespace.createElement(LazyContext.Provider, { + value: { + renderer: loadedRenderer.current, + strict: strict + } + }, children); + } + function isLazyBundle(features) { + return typeof features === "function"; + } + var ReorderContext = React.createContext(null); + function checkReorder(order, value, offset, velocity) { + if (!velocity) return order; + var index = order.findIndex(function (item) { + return item.value === value; + }); + if (index === -1) return order; + var nextOffset = velocity > 0 ? 1 : -1; + var nextItem = order[index + nextOffset]; + if (!nextItem) return order; + var item = order[index]; + var nextLayout = nextItem.layout; + var nextItemCenter = popmotion.mix(nextLayout.min, nextLayout.max, 0.5); + if (nextOffset === 1 && item.layout.max + offset > nextItemCenter || nextOffset === -1 && item.layout.min + offset < nextItemCenter) { + return moveItem(order, index, index + nextOffset); + } + return order; + } + function ReorderGroup(_a, externalRef) { + var children = _a.children, + _b = _a.as, + as = _b === void 0 ? "ul" : _b, + _c = _a.axis, + axis = _c === void 0 ? "y" : _c, + onReorder = _a.onReorder, + values = _a.values, + props = tslib.__rest(_a, ["children", "as", "axis", "onReorder", "values"]); + var Component = useConstant(function () { + return motion(as); + }); + var order = []; + var isReordering = React.useRef(false); + heyListen.invariant(Boolean(values), "Reorder.Group must be provided a values prop"); + var context = { + axis: axis, + registerItem: function (value, layout) { + /** + * Ensure entries can't add themselves more than once + */ + if (layout && order.findIndex(function (entry) { + return value === entry.value; + }) === -1) { + order.push({ + value: value, + layout: layout[axis] + }); + order.sort(compareMin); + } + }, + updateOrder: function (id, offset, velocity) { + if (isReordering.current) return; + var newOrder = checkReorder(order, id, offset, velocity); + if (order !== newOrder) { + isReordering.current = true; + onReorder(newOrder.map(getValue).filter(function (value) { + return values.indexOf(value) !== -1; + })); + } + } + }; + React.useEffect(function () { + isReordering.current = false; + }); + return React__namespace.createElement(Component, tslib.__assign({}, props, { + ref: externalRef + }), React__namespace.createElement(ReorderContext.Provider, { + value: context + }, children)); + } + var Group = React.forwardRef(ReorderGroup); + function getValue(item) { + return item.value; + } + function compareMin(a, b) { + return a.layout.min - b.layout.min; + } + + /** + * Creates a `MotionValue` to track the state and velocity of a value. + * + * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. + * + * ```jsx + * export const MyComponent = () => { + * const scale = useMotionValue(1) + * + * return + * } + * ``` + * + * @param initial - The initial state. + * + * @public + */ + function useMotionValue(initial) { + var value = useConstant(function () { + return motionValue(initial); + }); + /** + * If this motion value is being used in static mode, like on + * the Framer canvas, force components to rerender when the motion + * value is updated. + */ + var isStatic = React.useContext(MotionConfigContext).isStatic; + if (isStatic) { + var _a = tslib.__read(React.useState(initial), 2), + setLatest_1 = _a[1]; + React.useEffect(function () { + return value.onChange(setLatest_1); + }, []); + } + return value; + } + var isCustomValueType = function (v) { + return typeof v === "object" && v.mix; + }; + var getMixer = function (v) { + return isCustomValueType(v) ? v.mix : undefined; + }; + function transform() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var useImmediate = !Array.isArray(args[0]); + var argOffset = useImmediate ? 0 : -1; + var inputValue = args[0 + argOffset]; + var inputRange = args[1 + argOffset]; + var outputRange = args[2 + argOffset]; + var options = args[3 + argOffset]; + var interpolator = popmotion.interpolate(inputRange, outputRange, tslib.__assign({ + mixer: getMixer(outputRange[0]) + }, options)); + return useImmediate ? interpolator(inputValue) : interpolator; + } + function useOnChange(value, callback) { + useIsomorphicLayoutEffect(function () { + if (isMotionValue(value)) return value.onChange(callback); + }, [callback]); + } + function useMultiOnChange(values, handler) { + useIsomorphicLayoutEffect(function () { + var subscriptions = values.map(function (value) { + return value.onChange(handler); + }); + return function () { + return subscriptions.forEach(function (unsubscribe) { + return unsubscribe(); + }); + }; + }); + } + function useCombineMotionValues(values, combineValues) { + /** + * Initialise the returned motion value. This remains the same between renders. + */ + var value = useMotionValue(combineValues()); + /** + * Create a function that will update the template motion value with the latest values. + * This is pre-bound so whenever a motion value updates it can schedule its + * execution in Framesync. If it's already been scheduled it won't be fired twice + * in a single frame. + */ + var updateValue = function () { + return value.set(combineValues()); + }; + /** + * Synchronously update the motion value with the latest values during the render. + * This ensures that within a React render, the styles applied to the DOM are up-to-date. + */ + updateValue(); + /** + * Subscribe to all motion values found within the template. Whenever any of them change, + * schedule an update. + */ + useMultiOnChange(values, function () { + return sync__default["default"].update(updateValue, false, true); + }); + return value; + } + function useTransform(input, inputRangeOrTransformer, outputRange, options) { + var transformer = typeof inputRangeOrTransformer === "function" ? inputRangeOrTransformer : transform(inputRangeOrTransformer, outputRange, options); + return Array.isArray(input) ? useListTransform(input, transformer) : useListTransform([input], function (_a) { + var _b = tslib.__read(_a, 1), + latest = _b[0]; + return transformer(latest); + }); + } + function useListTransform(values, transformer) { + var latest = useConstant(function () { + return []; + }); + return useCombineMotionValues(values, function () { + latest.length = 0; + var numValues = values.length; + for (var i = 0; i < numValues; i++) { + latest[i] = values[i].get(); + } + return transformer(latest); + }); + } + function useDefaultMotionValue(value, defaultValue) { + if (defaultValue === void 0) { + defaultValue = 0; + } + return isMotionValue(value) ? value : useMotionValue(defaultValue); + } + function ReorderItem(_a, externalRef) { + var children = _a.children, + style = _a.style, + value = _a.value, + _b = _a.as, + as = _b === void 0 ? "li" : _b, + onDrag = _a.onDrag, + _c = _a.layout, + layout = _c === void 0 ? true : _c, + props = tslib.__rest(_a, ["children", "style", "value", "as", "onDrag", "layout"]); + var Component = useConstant(function () { + return motion(as); + }); + var context = React.useContext(ReorderContext); + var point = { + x: useDefaultMotionValue(style === null || style === void 0 ? void 0 : style.x), + y: useDefaultMotionValue(style === null || style === void 0 ? void 0 : style.y) + }; + var zIndex = useTransform([point.x, point.y], function (_a) { + var _b = tslib.__read(_a, 2), + latestX = _b[0], + latestY = _b[1]; + return latestX || latestY ? 1 : "unset"; + }); + var measuredLayout = React.useRef(null); + heyListen.invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group"); + var _d = context, + axis = _d.axis, + registerItem = _d.registerItem, + updateOrder = _d.updateOrder; + React.useEffect(function () { + registerItem(value, measuredLayout.current); + }, [context]); + return React__namespace.createElement(Component, tslib.__assign({ + drag: axis + }, props, { + dragSnapToOrigin: true, + style: tslib.__assign(tslib.__assign({}, style), { + x: point.x, + y: point.y, + zIndex: zIndex + }), + layout: layout, + onDrag: function (event, gesturePoint) { + var velocity = gesturePoint.velocity; + velocity[axis] && updateOrder(value, point[axis].get(), velocity[axis]); + onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, gesturePoint); + }, + onLayoutMeasure: function (measured) { + measuredLayout.current = measured; + }, + ref: externalRef + }), children); + } + var Item = React.forwardRef(ReorderItem); + var Reorder = { + Group: Group, + Item: Item + }; + + /** + * @public + */ + var domAnimation = tslib.__assign(tslib.__assign({ + renderer: createDomVisualElement + }, animations), gestureAnimations); + + /** + * @public + */ + var domMax = tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, domAnimation), drag), layoutFeatures), { + projectionNodeConstructor: HTMLProjectionNode + }); + + /** + * Combine multiple motion values into a new one using a string template literal. + * + * ```jsx + * import { + * motion, + * useSpring, + * useMotionValue, + * useMotionTemplate + * } from "framer-motion" + * + * function Component() { + * const shadowX = useSpring(0) + * const shadowY = useMotionValue(0) + * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` + * + * return + * } + * ``` + * + * @public + */ + function useMotionTemplate(fragments) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + /** + * Create a function that will build a string from the latest motion values. + */ + var numFragments = fragments.length; + function buildValue() { + var output = ""; + for (var i = 0; i < numFragments; i++) { + output += fragments[i]; + var value = values[i]; + if (value) output += values[i].get(); + } + return output; + } + return useCombineMotionValues(values, buildValue); + } + + /** + * Creates a `MotionValue` that, when `set`, will use a spring animation to animate to its new state. + * + * It can either work as a stand-alone `MotionValue` by initialising it with a value, or as a subscriber + * to another `MotionValue`. + * + * @remarks + * + * ```jsx + * const x = useSpring(0, { stiffness: 300 }) + * const y = useSpring(x, { damping: 10 }) + * ``` + * + * @param inputValue - `MotionValue` or number. If provided a `MotionValue`, when the input `MotionValue` changes, the created `MotionValue` will spring towards that value. + * @param springConfig - Configuration options for the spring. + * @returns `MotionValue` + * + * @public + */ + function useSpring(source, config) { + if (config === void 0) { + config = {}; + } + var isStatic = React.useContext(MotionConfigContext).isStatic; + var activeSpringAnimation = React.useRef(null); + var value = useMotionValue(isMotionValue(source) ? source.get() : source); + React.useMemo(function () { + return value.attach(function (v, set) { + /** + * A more hollistic approach to this might be to use isStatic to fix VisualElement animations + * at that level, but this will work for now + */ + if (isStatic) return set(v); + if (activeSpringAnimation.current) { + activeSpringAnimation.current.stop(); + } + activeSpringAnimation.current = popmotion.animate(tslib.__assign(tslib.__assign({ + from: value.get(), + to: v, + velocity: value.getVelocity() + }, config), { + onUpdate: set + })); + return value.get(); + }); + }, [JSON.stringify(config)]); + useOnChange(source, function (v) { + return value.set(parseFloat(v)); + }); + return value; + } + + /** + * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. + * + * ```javascript + * const x = useMotionValue(0) + * const xVelocity = useVelocity(x) + * const xAcceleration = useVelocity(xVelocity) + * ``` + * + * @public + */ + function useVelocity(value) { + var velocity = useMotionValue(value.getVelocity()); + React.useEffect(function () { + return value.velocityUpdateSubscribers.add(function (newVelocity) { + velocity.set(newVelocity); + }); + }, [value]); + return velocity; + } + var createScrollMotionValues = function () { + return { + scrollX: motionValue(0), + scrollY: motionValue(0), + scrollXProgress: motionValue(0), + scrollYProgress: motionValue(0) + }; + }; + function useScroll(_a) { + if (_a === void 0) { + _a = {}; + } + var container = _a.container, + target = _a.target, + options = tslib.__rest(_a, ["container", "target"]); + var values = useConstant(createScrollMotionValues); + useIsomorphicLayoutEffect(function () { + return dom.scroll(function (_a) { + var x = _a.x, + y = _a.y; + values.scrollX.set(x.current); + values.scrollXProgress.set(x.progress); + values.scrollY.set(y.current); + values.scrollYProgress.set(y.progress); + }, tslib.__assign(tslib.__assign({}, options), { + container: (container === null || container === void 0 ? void 0 : container.current) || undefined, + target: (target === null || target === void 0 ? void 0 : target.current) || undefined + })); + }, []); + return values; + } + function useElementScroll(ref) { + warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref })."); + return useScroll({ + container: ref + }); + } + function useViewportScroll() { + warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll()."); + return useScroll(); + } + var getCurrentTime = typeof performance !== "undefined" ? function () { + return performance.now(); + } : function () { + return Date.now(); + }; + function useAnimationFrame(callback) { + var initialTimestamp = useConstant(getCurrentTime); + var isStatic = React.useContext(MotionConfigContext).isStatic; + React.useEffect(function () { + if (isStatic) return; + var provideTimeSinceStart = function (_a) { + var timestamp = _a.timestamp; + callback(timestamp - initialTimestamp); + }; + sync__default["default"].update(provideTimeSinceStart, true); + return function () { + return sync.cancelSync.update(provideTimeSinceStart); + }; + }, [callback]); + } + function useTime() { + var time = useMotionValue(0); + useAnimationFrame(function (t) { + return time.set(t); + }); + return time; + } + + /** + * @public + */ + function animationControls() { + /** + * Track whether the host component has mounted. + */ + var hasMounted = false; + /** + * Pending animations that are started before a component is mounted. + * TODO: Remove this as animations should only run in effects + */ + var pendingAnimations = []; + /** + * A collection of linked component animation controls. + */ + var subscribers = new Set(); + var controls = { + subscribe: function (visualElement) { + subscribers.add(visualElement); + return function () { + return void subscribers.delete(visualElement); + }; + }, + start: function (definition, transitionOverride) { + /** + * TODO: We only perform this hasMounted check because in Framer we used to + * encourage the ability to start an animation within the render phase. This + * isn't behaviour concurrent-safe so when we make Framer concurrent-safe + * we can ditch this. + */ + if (hasMounted) { + var animations_1 = []; + subscribers.forEach(function (visualElement) { + animations_1.push(animateVisualElement(visualElement, definition, { + transitionOverride: transitionOverride + })); + }); + return Promise.all(animations_1); + } else { + return new Promise(function (resolve) { + pendingAnimations.push({ + animation: [definition, transitionOverride], + resolve: resolve + }); + }); + } + }, + set: function (definition) { + heyListen.invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook."); + return subscribers.forEach(function (visualElement) { + setValues(visualElement, definition); + }); + }, + stop: function () { + subscribers.forEach(function (visualElement) { + stopAnimation(visualElement); + }); + }, + mount: function () { + hasMounted = true; + pendingAnimations.forEach(function (_a) { + var animation = _a.animation, + resolve = _a.resolve; + controls.start.apply(controls, tslib.__spreadArray([], tslib.__read(animation), false)).then(resolve); + }); + return function () { + hasMounted = false; + controls.stop(); + }; + } + }; + return controls; + } + + /** + * Creates `AnimationControls`, which can be used to manually start, stop + * and sequence animations on one or more components. + * + * The returned `AnimationControls` should be passed to the `animate` property + * of the components you want to animate. + * + * These components can then be animated with the `start` method. + * + * ```jsx + * import * as React from 'react' + * import { motion, useAnimation } from 'framer-motion' + * + * export function MyComponent(props) { + * const controls = useAnimation() + * + * controls.start({ + * x: 100, + * transition: { duration: 0.5 }, + * }) + * + * return + * } + * ``` + * + * @returns Animation controller with `start` and `stop` methods + * + * @public + */ + function useAnimationControls() { + var controls = useConstant(animationControls); + React.useEffect(controls.mount, []); + return controls; + } + var useAnimation = useAnimationControls; + + /** + * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. + * + * An index value can be passed to the returned `cycle` function to cycle to a specific index. + * + * ```jsx + * import * as React from "react" + * import { motion, useCycle } from "framer-motion" + * + * export const MyComponent = () => { + * const [x, cycleX] = useCycle(0, 50, 100) + * + * return ( + * cycleX()} + * /> + * ) + * } + * ``` + * + * @param items - items to cycle through + * @returns [currentState, cycleState] + * + * @public + */ + function useCycle() { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + var index = React.useRef(0); + var _a = tslib.__read(React.useState(items[index.current]), 2), + item = _a[0], + setItem = _a[1]; + var runCycle = React.useCallback(function (next) { + index.current = typeof next !== "number" ? popmotion.wrap(0, items.length, index.current + 1) : next; + setItem(items[index.current]); + }, tslib.__spreadArray([items.length], tslib.__read(items), false)); + return [item, runCycle]; + } + function useInView(ref, _a) { + var _b = _a === void 0 ? {} : _a, + root = _b.root, + margin = _b.margin, + amount = _b.amount, + _c = _b.once, + once = _c === void 0 ? false : _c; + var _d = tslib.__read(React.useState(false), 2), + isInView = _d[0], + setInView = _d[1]; + React.useEffect(function () { + var _a; + if (!ref.current || once && isInView) return; + var onEnter = function () { + setInView(true); + return once ? undefined : function () { + return setInView(false); + }; + }; + var options = { + root: (_a = root === null || root === void 0 ? void 0 : root.current) !== null && _a !== void 0 ? _a : undefined, + margin: margin, + amount: amount === "some" ? "any" : amount + }; + return dom.inView(ref.current, onEnter, options); + }, [root, ref, margin, once]); + return isInView; + } + + /** + * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
    + * + * + * ) + * ``` + * + * @public + */ + var DragControls = /** @class */function () { + function DragControls() { + this.componentControls = new Set(); + } + /** + * Subscribe a component's internal `VisualElementDragControls` to the user-facing API. + * + * @internal + */ + DragControls.prototype.subscribe = function (controls) { + var _this = this; + this.componentControls.add(controls); + return function () { + return _this.componentControls.delete(controls); + }; + }; + /** + * Start a drag gesture on every `motion` component that has this set of drag controls + * passed into it via the `dragControls` prop. + * + * ```jsx + * dragControls.start(e, { + * snapToCursor: true + * }) + * ``` + * + * @param event - PointerEvent + * @param options - Options + * + * @public + */ + DragControls.prototype.start = function (event, options) { + this.componentControls.forEach(function (controls) { + controls.start(event.nativeEvent || event, options); + }); + }; + return DragControls; + }(); + var createDragControls = function () { + return new DragControls(); + }; + /** + * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop + * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we + * might want to initiate that dragging from a different component than the draggable one. + * + * By creating a `dragControls` using the `useDragControls` hook, we can pass this into + * the draggable component's `dragControls` prop. It exposes a `start` method + * that can start dragging from pointer events on other components. + * + * ```jsx + * const dragControls = useDragControls() + * + * function startDrag(event) { + * dragControls.start(event, { snapToCursor: true }) + * } + * + * return ( + * <> + *
    + * + * + * ) + * ``` + * + * @public + */ + function useDragControls() { + return useConstant(createDragControls); + } + function useInstantLayoutTransition() { + return startTransition; + } + function startTransition(cb) { + if (!rootProjectionNode.current) return; + rootProjectionNode.current.isUpdating = false; + rootProjectionNode.current.blockUpdate(); + cb === null || cb === void 0 ? void 0 : cb(); + } + function useInstantTransition() { + var _a = tslib.__read(useForceUpdate(), 2), + forceUpdate = _a[0], + forcedRenderCount = _a[1]; + var startInstantLayoutTransition = useInstantLayoutTransition(); + React.useEffect(function () { + /** + * Unblock after two animation frames, otherwise this will unblock too soon. + */ + sync__default["default"].postRender(function () { + return sync__default["default"].postRender(function () { + return instantAnimationState.current = false; + }); + }); + }, [forcedRenderCount]); + return function (callback) { + startInstantLayoutTransition(function () { + instantAnimationState.current = true; + forceUpdate(); + callback(); + }); + }; + } + function useResetProjection() { + var reset = React__namespace.useCallback(function () { + var root = rootProjectionNode.current; + if (!root) return; + root.resetTree(); + }, []); + return reset; + } + var createObject = function () { + return {}; + }; + var stateVisualElement = visualElement({ + build: function () {}, + measureViewportBox: createBox, + resetTransform: function () {}, + restoreTransform: function () {}, + removeValueFromRenderState: function () {}, + render: function () {}, + scrapeMotionValuesFromProps: createObject, + readValueFromInstance: function (_state, key, options) { + return options.initialState[key] || 0; + }, + makeTargetAnimatable: function (element, _a) { + var transition = _a.transition, + transitionEnd = _a.transitionEnd, + target = tslib.__rest(_a, ["transition", "transitionEnd"]); + var origin = getOrigin(target, transition || {}, element); + checkTargetForNewValues(element, target, origin); + return tslib.__assign({ + transition: transition, + transitionEnd: transitionEnd + }, target); + } + }); + var useVisualState = makeUseVisualState({ + scrapeMotionValuesFromProps: createObject, + createRenderState: createObject + }); + /** + * This is not an officially supported API and may be removed + * on any version. + */ + function useAnimatedState(initialState) { + var _a = tslib.__read(React.useState(initialState), 2), + animationState = _a[0], + setAnimationState = _a[1]; + var visualState = useVisualState({}, false); + var element = useConstant(function () { + return stateVisualElement({ + props: {}, + visualState: visualState + }, { + initialState: initialState + }); + }); + React.useEffect(function () { + element.mount({}); + return element.unmount; + }, [element]); + React.useEffect(function () { + element.setProps({ + onUpdate: function (v) { + setAnimationState(tslib.__assign({}, v)); + } + }); + }, [setAnimationState, element]); + var startAnimation = useConstant(function () { + return function (animationDefinition) { + return animateVisualElement(element, animationDefinition); + }; + }); + return [animationState, startAnimation]; + } + + // Keep things reasonable and avoid scale: Infinity. In practise we might need + // to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1] + // to simply hide content at unreasonable scales. + var maxScale = 100000; + var invertScale = function (scale) { + return scale > 0.001 ? 1 / scale : maxScale; + }; + var hasWarned = false; + /** + * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse + * of their respective parent scales. + * + * This is useful for undoing the distortion of content when scaling a parent component. + * + * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. + * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output + * of those instead. + * + * ```jsx + * const MyComponent = () => { + * const { scaleX, scaleY } = useInvertedScale() + * return + * } + * ``` + * + * @deprecated + */ + function useInvertedScale(scale) { + var parentScaleX = useMotionValue(1); + var parentScaleY = useMotionValue(1); + var visualElement = useVisualElementContext(); + heyListen.invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component."); + heyListen.warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead."); + hasWarned = true; + if (scale) { + parentScaleX = scale.scaleX || parentScaleX; + parentScaleY = scale.scaleY || parentScaleY; + } else if (visualElement) { + parentScaleX = visualElement.getValue("scaleX", 1); + parentScaleY = visualElement.getValue("scaleY", 1); + } + var scaleX = useTransform(parentScaleX, invertScale); + var scaleY = useTransform(parentScaleY, invertScale); + return { + scaleX: scaleX, + scaleY: scaleY + }; + } + exports.AnimatePresence = AnimatePresence; + exports.AnimateSharedLayout = AnimateSharedLayout; + exports.DeprecatedLayoutGroupContext = DeprecatedLayoutGroupContext; + exports.DragControls = DragControls; + exports.FlatTree = FlatTree; + exports.LayoutGroup = LayoutGroup; + exports.LayoutGroupContext = LayoutGroupContext; + exports.LazyMotion = LazyMotion; + exports.MotionConfig = MotionConfig; + exports.MotionConfigContext = MotionConfigContext; + exports.MotionContext = MotionContext; + exports.MotionValue = MotionValue; + exports.PresenceContext = PresenceContext; + exports.Reorder = Reorder; + exports.SwitchLayoutGroupContext = SwitchLayoutGroupContext; + exports.addPointerEvent = addPointerEvent; + exports.addScaleCorrector = addScaleCorrector; + exports.animate = animate; + exports.animateVisualElement = animateVisualElement; + exports.animationControls = animationControls; + exports.animations = animations; + exports.calcLength = calcLength; + exports.checkTargetForNewValues = checkTargetForNewValues; + exports.createBox = createBox; + exports.createDomMotionComponent = createDomMotionComponent; + exports.createMotionComponent = createMotionComponent; + exports.domAnimation = domAnimation; + exports.domMax = domMax; + exports.filterProps = filterProps; + exports.isBrowser = isBrowser; + exports.isDragActive = isDragActive; + exports.isMotionValue = isMotionValue; + exports.isValidMotionProp = isValidMotionProp; + exports.m = m; + exports.makeUseVisualState = makeUseVisualState; + exports.motion = motion; + exports.motionValue = motionValue; + exports.resolveMotionValue = resolveMotionValue; + exports.transform = transform; + exports.useAnimation = useAnimation; + exports.useAnimationControls = useAnimationControls; + exports.useAnimationFrame = useAnimationFrame; + exports.useCycle = useCycle; + exports.useDeprecatedAnimatedState = useAnimatedState; + exports.useDeprecatedInvertedScale = useInvertedScale; + exports.useDomEvent = useDomEvent; + exports.useDragControls = useDragControls; + exports.useElementScroll = useElementScroll; + exports.useForceUpdate = useForceUpdate; + exports.useInView = useInView; + exports.useInstantLayoutTransition = useInstantLayoutTransition; + exports.useInstantTransition = useInstantTransition; + exports.useIsPresent = useIsPresent; + exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect; + exports.useMotionTemplate = useMotionTemplate; + exports.useMotionValue = useMotionValue; + exports.usePresence = usePresence; + exports.useReducedMotion = useReducedMotion; + exports.useReducedMotionConfig = useReducedMotionConfig; + exports.useResetProjection = useResetProjection; + exports.useScroll = useScroll; + exports.useSpring = useSpring; + exports.useTime = useTime; + exports.useTransform = useTransform; + exports.useUnmountEffect = useUnmountEffect; + exports.useVelocity = useVelocity; + exports.useViewportScroll = useViewportScroll; + exports.useVisualElementContext = useVisualElementContext; + exports.visualElement = visualElement; + exports.wrapHandler = wrapHandler; + + /***/ }), + + /***/ "../../../node_modules/framesync/dist/framesync.cjs.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/framesync/dist/framesync.cjs.js ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + const defaultTimestep = 1 / 60 * 1000; + const getCurrentTime = typeof performance !== "undefined" ? () => performance.now() : () => Date.now(); + const onNextFrame = typeof window !== "undefined" ? callback => window.requestAnimationFrame(callback) : callback => setTimeout(() => callback(getCurrentTime()), defaultTimestep); + function createRenderStep(runNextFrame) { + let toRun = []; + let toRunNextFrame = []; + let numToRun = 0; + let isProcessing = false; + let flushNextFrame = false; + const toKeepAlive = new WeakSet(); + const step = { + schedule: (callback, keepAlive = false, immediate = false) => { + const addToCurrentFrame = immediate && isProcessing; + const buffer = addToCurrentFrame ? toRun : toRunNextFrame; + if (keepAlive) toKeepAlive.add(callback); + if (buffer.indexOf(callback) === -1) { + buffer.push(callback); + if (addToCurrentFrame && isProcessing) numToRun = toRun.length; + } + return callback; + }, + cancel: callback => { + const index = toRunNextFrame.indexOf(callback); + if (index !== -1) toRunNextFrame.splice(index, 1); + toKeepAlive.delete(callback); + }, + process: frameData => { + if (isProcessing) { + flushNextFrame = true; + return; + } + isProcessing = true; + [toRun, toRunNextFrame] = [toRunNextFrame, toRun]; + toRunNextFrame.length = 0; + numToRun = toRun.length; + if (numToRun) { + for (let i = 0; i < numToRun; i++) { + const callback = toRun[i]; + callback(frameData); + if (toKeepAlive.has(callback)) { + step.schedule(callback); + runNextFrame(); + } + } + } + isProcessing = false; + if (flushNextFrame) { + flushNextFrame = false; + step.process(frameData); + } + } + }; + return step; + } + const maxElapsed = 40; + let useDefaultElapsed = true; + let runNextFrame = false; + let isProcessing = false; + const frame = { + delta: 0, + timestamp: 0 + }; + const stepsOrder = ["read", "update", "preRender", "render", "postRender"]; + const steps = stepsOrder.reduce((acc, key) => { + acc[key] = createRenderStep(() => runNextFrame = true); + return acc; + }, {}); + const sync = stepsOrder.reduce((acc, key) => { + const step = steps[key]; + acc[key] = (process, keepAlive = false, immediate = false) => { + if (!runNextFrame) startLoop(); + return step.schedule(process, keepAlive, immediate); + }; + return acc; + }, {}); + const cancelSync = stepsOrder.reduce((acc, key) => { + acc[key] = steps[key].cancel; + return acc; + }, {}); + const flushSync = stepsOrder.reduce((acc, key) => { + acc[key] = () => steps[key].process(frame); + return acc; + }, {}); + const processStep = stepId => steps[stepId].process(frame); + const processFrame = timestamp => { + runNextFrame = false; + frame.delta = useDefaultElapsed ? defaultTimestep : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1); + frame.timestamp = timestamp; + isProcessing = true; + stepsOrder.forEach(processStep); + isProcessing = false; + if (runNextFrame) { + useDefaultElapsed = false; + onNextFrame(processFrame); + } + }; + const startLoop = () => { + runNextFrame = true; + useDefaultElapsed = true; + if (!isProcessing) onNextFrame(processFrame); + }; + const getFrameData = () => frame; + exports.cancelSync = cancelSync; + exports["default"] = sync; + exports.flushSync = flushSync; + exports.getFrameData = getFrameData; + + /***/ }), + + /***/ "../../../node_modules/get-nonce/dist/es2015/index.js": + /*!************************************************************!*\ + !*** ../../../node_modules/get-nonce/dist/es2015/index.js ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.setNonce = exports.getNonce = void 0; + var currentNonce; + var setNonce = function (nonce) { + currentNonce = nonce; + }; + exports.setNonce = setNonce; + var getNonce = function () { + if (currentNonce) { + return currentNonce; + } + if (true) { + return __webpack_require__.nc; + } + return undefined; + }; + exports.getNonce = getNonce; + + /***/ }), + + /***/ "../../../node_modules/graphql-ws/lib/client.mjs": + /*!*******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/client.mjs ***! + \*******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _exportNames = { + createClient: true + }; + exports.createClient = createClient; + var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); + Object.keys(_common).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _common[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _common[key]; + } + }); + }); + var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); + /** + * + * client + * + */ + var __await = void 0 && (void 0).__await || function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } + }; + + /** This file is the entry point for browsers, re-export common elements. */ + + /** + * Creates a disposable GraphQL over WebSocket client. + * + * @category Client + */ + function createClient(options) { + const { + url, + connectionParams, + lazy = true, + onNonLazyError = console.error, + lazyCloseTimeout: lazyCloseTimeoutMs = 0, + keepAlive = 0, + disablePong, + connectionAckWaitTimeout = 0, + retryAttempts = 5, + retryWait = async function randomisedExponentialBackoff(retries) { + let retryDelay = 1000; // start with 1s delay + for (let i = 0; i < retries; i++) { + retryDelay *= 2; + } + await new Promise(resolve => setTimeout(resolve, retryDelay + + // add random timeout from 300ms to 3s + Math.floor(Math.random() * (3000 - 300) + 300))); + }, + shouldRetry = isLikeCloseEvent, + isFatalConnectionProblem, + on, + webSocketImpl, + /** + * Generates a v4 UUID to be used as the ID using `Math` + * as the random number generator. Supply your own generator + * in case you need more uniqueness. + * + * Reference: https://gist.github.com/jed/982883 + */ + generateID = function generateUUID() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { + const r = Math.random() * 16 | 0, + v = c == 'x' ? r : r & 0x3 | 0x8; + return v.toString(16); + }); + }, + jsonMessageReplacer: replacer, + jsonMessageReviver: reviver + } = options; + let ws; + if (webSocketImpl) { + if (!isWebSocket(webSocketImpl)) { + throw new Error('Invalid WebSocket implementation provided'); + } + ws = webSocketImpl; + } else if (typeof WebSocket !== 'undefined') { + ws = WebSocket; + } else if (typeof __webpack_require__.g !== 'undefined') { + ws = __webpack_require__.g.WebSocket || + // @ts-expect-error: Support more browsers + __webpack_require__.g.MozWebSocket; + } else if (typeof window !== 'undefined') { + ws = window.WebSocket || + // @ts-expect-error: Support more browsers + window.MozWebSocket; + } + if (!ws) throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`"); + const WebSocketImpl = ws; + // websocket status emitter, subscriptions are handled differently + const emitter = (() => { + const message = (() => { + const listeners = {}; + return { + on(id, listener) { + listeners[id] = listener; + return () => { + delete listeners[id]; + }; + }, + emit(message) { + var _a; + if ('id' in message) (_a = listeners[message.id]) === null || _a === void 0 ? void 0 : _a.call(listeners, message); + } + }; + })(); + const listeners = { + connecting: (on === null || on === void 0 ? void 0 : on.connecting) ? [on.connecting] : [], + opened: (on === null || on === void 0 ? void 0 : on.opened) ? [on.opened] : [], + connected: (on === null || on === void 0 ? void 0 : on.connected) ? [on.connected] : [], + ping: (on === null || on === void 0 ? void 0 : on.ping) ? [on.ping] : [], + pong: (on === null || on === void 0 ? void 0 : on.pong) ? [on.pong] : [], + message: (on === null || on === void 0 ? void 0 : on.message) ? [message.emit, on.message] : [message.emit], + closed: (on === null || on === void 0 ? void 0 : on.closed) ? [on.closed] : [], + error: (on === null || on === void 0 ? void 0 : on.error) ? [on.error] : [] + }; + return { + onMessage: message.on, + on(event, listener) { + const l = listeners[event]; + l.push(listener); + return () => { + l.splice(l.indexOf(listener), 1); + }; + }, + emit(event, ...args) { + // we copy the listeners so that unlistens dont "pull the rug under our feet" + for (const listener of [...listeners[event]]) { + // @ts-expect-error: The args should fit + listener(...args); + } + } + }; + })(); + // invokes the callback either when an error or closed event is emitted, + // first one that gets called prevails, other emissions are ignored + function errorOrClosed(cb) { + const listening = [ + // errors are fatal and more critical than close events, throw them first + emitter.on('error', err => { + listening.forEach(unlisten => unlisten()); + cb(err); + }), + // closes can be graceful and not fatal, throw them second (if error didnt throw) + emitter.on('closed', event => { + listening.forEach(unlisten => unlisten()); + cb(event); + })]; + } + let connecting, + locks = 0, + lazyCloseTimeout, + retrying = false, + retries = 0, + disposed = false; + async function connect() { + // clear the lazy close timeout immediatelly so that close gets debounced + // see: https://github.com/enisdenjo/graphql-ws/issues/388 + clearTimeout(lazyCloseTimeout); + const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : connecting = new Promise((connected, denied) => (async () => { + if (retrying) { + await retryWait(retries); + // subscriptions might complete while waiting for retry + if (!locks) { + connecting = undefined; + return denied({ + code: 1000, + reason: 'All Subscriptions Gone' + }); + } + retries++; + } + emitter.emit('connecting'); + const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, _common.GRAPHQL_TRANSPORT_WS_PROTOCOL); + let connectionAckTimeout, queuedPing; + function enqueuePing() { + if (isFinite(keepAlive) && keepAlive > 0) { + clearTimeout(queuedPing); // in case where a pong was received before a ping (this is valid behaviour) + queuedPing = setTimeout(() => { + if (socket.readyState === WebSocketImpl.OPEN) { + socket.send((0, _common.stringifyMessage)({ + type: _common.MessageType.Ping + })); + emitter.emit('ping', false, undefined); + } + }, keepAlive); + } + } + errorOrClosed(errOrEvent => { + connecting = undefined; + clearTimeout(connectionAckTimeout); + clearTimeout(queuedPing); + denied(errOrEvent); + if (isLikeCloseEvent(errOrEvent) && errOrEvent.code === 4499) { + socket.close(4499, 'Terminated'); // close event is artificial and emitted manually, see `Client.terminate()` below + socket.onerror = null; + socket.onclose = null; + } + }); + socket.onerror = err => emitter.emit('error', err); + socket.onclose = event => emitter.emit('closed', event); + socket.onopen = async () => { + try { + emitter.emit('opened', socket); + const payload = typeof connectionParams === 'function' ? await connectionParams() : connectionParams; + // connectionParams might take too long causing the server to kick off the client + // the necessary error/close event is already reported - simply stop execution + if (socket.readyState !== WebSocketImpl.OPEN) return; + socket.send((0, _common.stringifyMessage)(payload ? { + type: _common.MessageType.ConnectionInit, + payload + } : { + type: _common.MessageType.ConnectionInit + // payload is completely absent if not provided + }, replacer)); + if (isFinite(connectionAckWaitTimeout) && connectionAckWaitTimeout > 0) { + connectionAckTimeout = setTimeout(() => { + socket.close(_common.CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout'); + }, connectionAckWaitTimeout); + } + enqueuePing(); // enqueue ping (noop if disabled) + } catch (err) { + emitter.emit('error', err); + socket.close(_common.CloseCode.InternalClientError, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Internal client error')); + } + }; + let acknowledged = false; + socket.onmessage = ({ + data + }) => { + try { + const message = (0, _common.parseMessage)(data, reviver); + emitter.emit('message', message); + if (message.type === 'ping' || message.type === 'pong') { + emitter.emit(message.type, true, message.payload); // received + if (message.type === 'pong') { + enqueuePing(); // enqueue next ping (noop if disabled) + } else if (!disablePong) { + // respond with pong on ping + socket.send((0, _common.stringifyMessage)(message.payload ? { + type: _common.MessageType.Pong, + payload: message.payload + } : { + type: _common.MessageType.Pong + // payload is completely absent if not provided + })); + emitter.emit('pong', false, message.payload); + } + return; // ping and pongs can be received whenever + } + if (acknowledged) return; // already connected and acknowledged + if (message.type !== _common.MessageType.ConnectionAck) throw new Error(`First message cannot be of type ${message.type}`); + clearTimeout(connectionAckTimeout); + acknowledged = true; + emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged + retrying = false; // future lazy connects are not retries + retries = 0; // reset the retries on connect + connected([socket, new Promise((_, reject) => errorOrClosed(reject))]); + } catch (err) { + socket.onmessage = null; // stop reading messages as soon as reading breaks once + emitter.emit('error', err); + socket.close(_common.CloseCode.BadResponse, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Bad response')); + } + }; + })())); + // if the provided socket is in a closing state, wait for the throw on close + if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose; + let release = () => { + // releases this connection + }; + const released = new Promise(resolve => release = resolve); + return [socket, release, Promise.race([ + // wait for + released.then(() => { + if (!locks) { + // and if no more locks are present, complete the connection + const complete = () => socket.close(1000, 'Normal Closure'); + if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) { + // if the keepalive is set, allow for the specified calmdown time and + // then complete if the socket is still open. + lazyCloseTimeout = setTimeout(() => { + if (socket.readyState === WebSocketImpl.OPEN) complete(); + }, lazyCloseTimeoutMs); + } else { + // otherwise complete immediately + complete(); + } + } + }), + // or + throwOnClose])]; + } + /** + * Checks the `connect` problem and evaluates if the client should retry. + */ + function shouldRetryConnectOrThrow(errOrCloseEvent) { + // some close codes are worth reporting immediately + if (isLikeCloseEvent(errOrCloseEvent) && (isFatalInternalCloseCode(errOrCloseEvent.code) || [_common.CloseCode.InternalServerError, _common.CloseCode.InternalClientError, _common.CloseCode.BadRequest, _common.CloseCode.BadResponse, _common.CloseCode.Unauthorized, + // CloseCode.Forbidden, might grant access out after retry + _common.CloseCode.SubprotocolNotAcceptable, + // CloseCode.ConnectionInitialisationTimeout, might not time out after retry + // CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry + _common.CloseCode.SubscriberAlreadyExists, _common.CloseCode.TooManyInitialisationRequests + // 4499, // Terminated, probably because the socket froze, we want to retry + ].includes(errOrCloseEvent.code))) throw errOrCloseEvent; + // client was disposed, no retries should proceed regardless + if (disposed) return false; + // normal closure (possibly all subscriptions have completed) + // if no locks were acquired in the meantime, shouldnt try again + if (isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1000) return locks > 0; + // retries are not allowed or we tried to many times, report error + if (!retryAttempts || retries >= retryAttempts) throw errOrCloseEvent; + // throw non-retryable connection problems + if (!shouldRetry(errOrCloseEvent)) throw errOrCloseEvent; + // @deprecated throw fatal connection problems immediately + if (isFatalConnectionProblem === null || isFatalConnectionProblem === void 0 ? void 0 : isFatalConnectionProblem(errOrCloseEvent)) throw errOrCloseEvent; + // looks good, start retrying + return retrying = true; + } + // in non-lazy (hot?) mode always hold one connection lock to persist the socket + if (!lazy) { + (async () => { + locks++; + for (;;) { + try { + const [,, throwOnClose] = await connect(); + await throwOnClose; // will always throw because releaser is not used + } catch (errOrCloseEvent) { + try { + if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; + } catch (errOrCloseEvent) { + // report thrown error, no further retries + return onNonLazyError === null || onNonLazyError === void 0 ? void 0 : onNonLazyError(errOrCloseEvent); + } + } + } + })(); + } + return { + on: emitter.on, + subscribe(payload, sink) { + const id = generateID(payload); + let done = false, + errored = false, + releaser = () => { + // for handling completions before connect + locks--; + done = true; + }; + (async () => { + locks++; + for (;;) { + try { + const [socket, release, waitForReleaseOrThrowOnClose] = await connect(); + // if done while waiting for connect, release the connection lock right away + if (done) return release(); + const unlisten = emitter.onMessage(id, message => { + switch (message.type) { + case _common.MessageType.Next: + { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- payload will fit type + sink.next(message.payload); + return; } - } else if (mode.electricInput) { - if ( - mode.electricInput.test( - getLine(cm.doc, range2.head.line).text.slice( - 0, - range2.head.ch - ) - ) - ) { - indented = indentLine(cm, range2.head.line, "smart"); + case _common.MessageType.Error: + { + errored = true, done = true; + sink.error(message.payload); + releaser(); + return; + } + case _common.MessageType.Complete: + { + done = true; + releaser(); // release completes the sink + return; } - } - if (indented) { - signalLater(cm, "electricInput", cm, range2.head.line); - } - } - } - function copyableRanges(cm) { - var text = [], - ranges = []; - for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { - var line = cm.doc.sel.ranges[i2].head.line; - var lineRange = { - anchor: Pos(line, 0), - head: Pos(line + 1, 0), - }; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); } - return { - text, - ranges, - }; + }); + socket.send((0, _common.stringifyMessage)({ + id, + type: _common.MessageType.Subscribe, + payload + }, replacer)); + releaser = () => { + if (!done && socket.readyState === WebSocketImpl.OPEN) + // if not completed already and socket is open, send complete message to server on release + socket.send((0, _common.stringifyMessage)({ + id, + type: _common.MessageType.Complete + }, replacer)); + locks--; + done = true; + release(); + }; + // either the releaser will be called, connection completed and + // the promise resolved or the socket closed and the promise rejected. + // whatever happens though, we want to stop listening for messages + await waitForReleaseOrThrowOnClose.finally(unlisten); + return; // completed, shouldnt try again + } catch (errOrCloseEvent) { + if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; + } + } + })().then(() => { + // delivering either an error or a complete terminates the sequence + if (!errored) sink.complete(); + }) // resolves on release or normal closure + .catch(err => { + sink.error(err); + }); // rejects on close events and errors + return () => { + // dispose only of active subscriptions + if (!done) releaser(); + }; + }, + iterate(request) { + const pending = []; + const deferred = { + done: false, + error: null, + resolve: () => { + // noop + } + }; + const dispose = this.subscribe(request, { + next(val) { + pending.push(val); + deferred.resolve(); + }, + error(err) { + deferred.done = true; + deferred.error = err; + deferred.resolve(); + }, + complete() { + deferred.done = true; + deferred.resolve(); + } + }); + const iterator = function iterator() { + return __asyncGenerator(this, arguments, function* iterator_1() { + for (;;) { + if (!pending.length) { + // only wait if there are no pending messages available + yield __await(new Promise(resolve => deferred.resolve = resolve)); } - function disableBrowserMagic( - field, - spellcheck, - autocorrect, - autocapitalize - ) { - field.setAttribute("autocorrect", autocorrect ? "" : "off"); - field.setAttribute( - "autocapitalize", - autocapitalize ? "" : "off" - ); - field.setAttribute("spellcheck", !!spellcheck); + // first flush + while (pending.length) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + yield yield __await(pending.shift()); } - function hiddenTextarea() { - var te = elt( - "textarea", - null, - null, - "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none" - ); - var div = elt( - "div", - [te], - null, - "overflow: hidden; position: relative; width: 3px; height: 0px;" - ); - if (webkit) { - te.style.width = "1000px"; - } else { - te.setAttribute("wrap", "off"); - } - if (ios) { - te.style.border = "1px solid black"; - } - disableBrowserMagic(te); - return div; + // then error + if (deferred.error) { + throw deferred.error; } - function addEditorMethods(CodeMirror2) { - var optionHandlers2 = CodeMirror2.optionHandlers; - var helpers = (CodeMirror2.helpers = {}); - CodeMirror2.prototype = { - constructor: CodeMirror2, - focus: function () { - window.focus(); - this.display.input.focus(); - }, - setOption: function (option, value) { - var options = this.options, - old = options[option]; - if (options[option] == value && option != "mode") { - return; - } - options[option] = value; - if (optionHandlers2.hasOwnProperty(option)) { - operation(this, optionHandlers2[option])( - this, - value, - old - ); - } - signal(this, "optionChange", this, option); - }, - getOption: function (option) { - return this.options[option]; - }, - getDoc: function () { - return this.doc; - }, - addKeyMap: function (map2, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"]( - getKeyMap(map2) - ); - }, - removeKeyMap: function (map2) { - var maps = this.state.keyMaps; - for (var i2 = 0; i2 < maps.length; ++i2) { - if (maps[i2] == map2 || maps[i2].name == map2) { - maps.splice(i2, 1); - return true; - } - } - }, - addOverlay: methodOp(function (spec, options) { - var mode = spec.token - ? spec - : CodeMirror2.getMode(this.options, spec); - if (mode.startState) { - throw new Error("Overlays may not be stateful."); - } - insertSorted( - this.state.overlays, - { - mode, - modeSpec: spec, - opaque: options && options.opaque, - priority: (options && options.priority) || 0, - }, - function (overlay) { - return overlay.priority; - } - ); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function (spec) { - var overlays = this.state.overlays; - for (var i2 = 0; i2 < overlays.length; ++i2) { - var cur = overlays[i2].modeSpec; - if ( - cur == spec || - (typeof spec == "string" && cur.name == spec) - ) { - overlays.splice(i2, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - indentLine: methodOp(function (n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) { - dir = this.options.smartIndent ? "smart" : "prev"; - } else { - dir = dir ? "add" : "subtract"; - } - } - if (isLine(this.doc, n)) { - indentLine(this, n, dir, aggressive); - } - }), - indentSelection: methodOp(function (how) { - var ranges = this.doc.sel.ranges, - end = -1; - for (var i2 = 0; i2 < ranges.length; i2++) { - var range2 = ranges[i2]; - if (!range2.empty()) { - var from = range2.from(), - to = range2.to(); - var start = Math.max(end, from.line); - end = - Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + - 1; - for (var j = start; j < end; ++j) { - indentLine(this, j, how); - } - var newRanges = this.doc.sel.ranges; - if ( - from.ch == 0 && - ranges.length == newRanges.length && - newRanges[i2].from().ch > 0 - ) { - replaceOneSelection( - this.doc, - i2, - new Range(from, newRanges[i2].to()), - sel_dontScroll - ); - } - } else if (range2.head.line > end) { - indentLine(this, range2.head.line, how, true); - end = range2.head.line; - if (i2 == this.doc.sel.primIndex) { - ensureCursorVisible(this); - } - } - } - }), - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function (pos, precise) { - return takeToken(this, pos, precise); - }, - getLineTokens: function (line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - getTokenTypeAt: function (pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles( - this, - getLine(this.doc, pos.line) - ); - var before = 0, - after = (styles.length - 1) / 2, - ch = pos.ch; - var type; - if (ch == 0) { - type = styles[2]; - } else { - for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { - after = mid; - } else if (styles[mid * 2 + 1] < ch) { - before = mid + 1; - } else { - type = styles[mid * 2 + 2]; - break; - } - } - } - var cut = type ? type.indexOf("overlay ") : -1; - return cut < 0 - ? type - : cut == 0 - ? null - : type.slice(0, cut - 1); - }, - getModeAt: function (pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { - return mode; - } - return CodeMirror2.innerMode( - mode, - this.getTokenAt(pos).state - ).mode; - }, - getHelper: function (pos, type) { - return this.getHelpers(pos, type)[0]; - }, - getHelpers: function (pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) { - return found; - } - var help = helpers[type], - mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) { - found.push(help[mode[type]]); - } - } else if (mode[type]) { - for (var i2 = 0; i2 < mode[type].length; i2++) { - var val = help[mode[type][i2]]; - if (val) { - found.push(val); - } - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i$12 = 0; i$12 < help._global.length; i$12++) { - var cur = help._global[i$12]; - if ( - cur.pred(mode, this) && - indexOf(found, cur.val) == -1 - ) { - found.push(cur.val); - } - } - return found; - }, - getStateAfter: function (line, precise) { - var doc = this.doc; - line = clipLine( - doc, - line == null ? doc.first + doc.size - 1 : line - ); - return getContextBefore(this, line + 1, precise).state; - }, - cursorCoords: function (start, mode) { - var pos, - range2 = this.doc.sel.primary(); - if (start == null) { - pos = range2.head; - } else if (typeof start == "object") { - pos = clipPos(this.doc, start); - } else { - pos = start ? range2.from() : range2.to(); - } - return cursorCoords(this, pos, mode || "page"); - }, - charCoords: function (pos, mode) { - return charCoords( - this, - clipPos(this.doc, pos), - mode || "page" - ); - }, - coordsChar: function (coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - lineAtHeight: function (height, mode) { - height = fromCoordSystem( - this, - { - top: height, - left: 0, - }, - mode || "page" - ).top; - return lineAtHeight( - this.doc, - height + this.display.viewOffset - ); - }, - heightAtLine: function (line, mode, includeWidgets) { - var end = false, - lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) { - line = this.doc.first; - } else if (line > last) { - line = last; - end = true; - } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return ( - intoCoordSystem( - this, - lineObj, - { - top: 0, - left: 0, - }, - mode || "page", - includeWidgets || end - ).top + - (end ? this.doc.height - heightAtLine(lineObj) : 0) - ); - }, - defaultTextHeight: function () { - return textHeight(this.display); - }, - defaultCharWidth: function () { - return charWidth(this.display); - }, - getViewport: function () { - return { - from: this.display.viewFrom, - to: this.display.viewTo, - }; - }, - addWidget: function (pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, - left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max( - display.wrapper.clientHeight, - this.doc.height - ), - hspace = Math.max( - display.sizer.clientWidth, - display.lineSpace.clientWidth - ); - if ( - (vert == "above" || - pos.bottom + node.offsetHeight > vspace) && - pos.top > node.offsetHeight - ) { - top = pos.top - node.offsetHeight; - } else if (pos.bottom + node.offsetHeight <= vspace) { - top = pos.bottom; - } - if (left + node.offsetWidth > hspace) { - left = hspace - node.offsetWidth; - } - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") { - left = 0; - } else if (horiz == "middle") { - left = - (display.sizer.clientWidth - node.offsetWidth) / 2; - } - node.style.left = left + "px"; - } - if (scroll) { - scrollIntoView(this, { - left, - top, - right: left + node.offsetWidth, - bottom: top + node.offsetHeight, - }); - } - }, - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - execCommand: function (cmd) { - if (commands.hasOwnProperty(cmd)) { - return commands[cmd].call(null, this); - } - }, - triggerElectric: methodOp(function (text) { - triggerElectric(this, text); - }), - findPosH: function (from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i2 = 0; i2 < amount; ++i2) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) { - break; - } - } - return cur; - }, - moveH: methodOp(function (dir, unit) { - var this$1$1 = this; - this.extendSelectionsBy(function (range2) { - if ( - this$1$1.display.shift || - this$1$1.doc.extend || - range2.empty() - ) { - return findPosH( - this$1$1.doc, - range2.head, - dir, - unit, - this$1$1.options.rtlMoveVisually - ); - } else { - return dir < 0 ? range2.from() : range2.to(); - } - }, sel_move); - }), - deleteH: methodOp(function (dir, unit) { - var sel = this.doc.sel, - doc = this.doc; - if (sel.somethingSelected()) { - doc.replaceSelection("", null, "+delete"); - } else { - deleteNearSelection(this, function (range2) { - var other = findPosH( - doc, - range2.head, - dir, - unit, - false - ); - return dir < 0 - ? { - from: other, - to: range2.head, - } - : { - from: range2.head, - to: other, - }; - }); - } - }), - findPosV: function (from, amount, unit, goalColumn) { - var dir = 1, - x = goalColumn; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i2 = 0; i2 < amount; ++i2) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) { - x = coords.left; - } else { - coords.left = x; - } - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) { - break; - } - } - return cur; - }, - moveV: methodOp(function (dir, unit) { - var this$1$1 = this; - var doc = this.doc, - goals = []; - var collapse = - !this.display.shift && - !doc.extend && - doc.sel.somethingSelected(); - doc.extendSelectionsBy(function (range2) { - if (collapse) { - return dir < 0 ? range2.from() : range2.to(); - } - var headPos = cursorCoords(this$1$1, range2.head, "div"); - if (range2.goalColumn != null) { - headPos.left = range2.goalColumn; - } - goals.push(headPos.left); - var pos = findPosV(this$1$1, headPos, dir, unit); - if (unit == "page" && range2 == doc.sel.primary()) { - addToScrollTop( - this$1$1, - charCoords(this$1$1, pos, "div").top - headPos.top - ); - } - return pos; - }, sel_move); - if (goals.length) { - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - doc.sel.ranges[i2].goalColumn = goals[i2]; - } - } - }), - // Find the word at the given position (as returned by coordsChar). - findWordAt: function (pos) { - var doc = this.doc, - line = getLine(doc, pos.line).text; - var start = pos.ch, - end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ( - (pos.sticky == "before" || end == line.length) && - start - ) { - --start; - } else { - ++end; - } - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) - ? function (ch) { - return isWordChar(ch, helper); - } - : /\s/.test(startChar) - ? function (ch) { - return /\s/.test(ch); - } - : function (ch) { - return !/\s/.test(ch) && !isWordChar(ch); - }; - while (start > 0 && check(line.charAt(start - 1))) { - --start; - } - while (end < line.length && check(line.charAt(end))) { - ++end; - } - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - toggleOverwrite: function (value) { - if (value != null && value == this.state.overwrite) { - return; - } - if ((this.state.overwrite = !this.state.overwrite)) { - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } else { - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function () { - return this.display.input.getField() == activeElt(); - }, - isReadOnly: function () { - return !!(this.options.readOnly || this.doc.cantEdit); - }, - scrollTo: methodOp(function (x, y) { - scrollToCoords(this, x, y); - }), - getScrollInfo: function () { - var scroller = this.display.scroller; - return { - left: scroller.scrollLeft, - top: scroller.scrollTop, - height: - scroller.scrollHeight - - scrollGap(this) - - this.display.barHeight, - width: - scroller.scrollWidth - - scrollGap(this) - - this.display.barWidth, - clientHeight: displayHeight(this), - clientWidth: displayWidth(this), - }; - }, - scrollIntoView: methodOp(function (range2, margin) { - if (range2 == null) { - range2 = { - from: this.doc.sel.primary().head, - to: null, - }; - if (margin == null) { - margin = this.options.cursorScrollMargin; - } - } else if (typeof range2 == "number") { - range2 = { - from: Pos(range2, 0), - to: null, - }; - } else if (range2.from == null) { - range2 = { - from: range2, - to: null, - }; - } - if (!range2.to) { - range2.to = range2.from; - } - range2.margin = margin || 0; - if (range2.from.line != null) { - scrollToRange(this, range2); - } else { - scrollToCoordsRange( - this, - range2.from, - range2.to, - range2.margin - ); - } - }), - setSize: methodOp(function (width, height) { - var this$1$1 = this; - var interpret = function (val) { - return typeof val == "number" || /^\d+$/.test(String(val)) - ? val + "px" - : val; - }; - if (width != null) { - this.display.wrapper.style.width = interpret(width); - } - if (height != null) { - this.display.wrapper.style.height = interpret(height); - } - if (this.options.lineWrapping) { - clearLineMeasurementCache(this); - } - var lineNo2 = this.display.viewFrom; - this.doc.iter( - lineNo2, - this.display.viewTo, - function (line) { - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; i2++) { - if (line.widgets[i2].noHScroll) { - regLineChange(this$1$1, lineNo2, "widget"); - break; - } - } - } - ++lineNo2; - } - ); - this.curOp.forceUpdate = true; - signal(this, "refresh", this); - }), - operation: function (f) { - return runInOp(this, f); - }, - startOperation: function () { - return startOperation(this); - }, - endOperation: function () { - return endOperation(this); - }, - refresh: methodOp(function () { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - scrollToCoords( - this, - this.doc.scrollLeft, - this.doc.scrollTop - ); - updateGutterSpace(this.display); - if ( - oldHeight == null || - Math.abs(oldHeight - textHeight(this.display)) > 0.5 || - this.options.lineWrapping - ) { - estimateLineHeights(this); - } - signal(this, "refresh", this); - }), - swapDoc: methodOp(function (doc) { - var old = this.doc; - old.cm = null; - if (this.state.selectingText) { - this.state.selectingText(); - } - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - scrollToCoords(this, doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - phrase: function (phraseText) { - var phrases = this.options.phrases; - return phrases && - Object.prototype.hasOwnProperty.call(phrases, phraseText) - ? phrases[phraseText] - : phraseText; - }, - getInputField: function () { - return this.display.input.getField(); - }, - getWrapperElement: function () { - return this.display.wrapper; - }, - getScrollerElement: function () { - return this.display.scroller; - }, - getGutterElement: function () { - return this.display.gutters; - }, - }; - eventMixin(CodeMirror2); - CodeMirror2.registerHelper = function (type, name, value) { - if (!helpers.hasOwnProperty(type)) { - helpers[type] = CodeMirror2[type] = { - _global: [], - }; - } - helpers[type][name] = value; - }; - CodeMirror2.registerGlobalHelper = function ( - type, - name, - predicate, - value - ) { - CodeMirror2.registerHelper(type, name, value); - helpers[type]._global.push({ - pred: predicate, - val: value, - }); - }; + // or complete + if (deferred.done) { + return yield __await(void 0); } - function findPosH(doc, pos, dir, unit, visually) { - var oldPos = pos; - var origDir = dir; - var lineObj = getLine(doc, pos.line); - var lineDir = visually && doc.direction == "rtl" ? -dir : dir; - function findNextLine() { - var l = pos.line + lineDir; - if (l < doc.first || l >= doc.first + doc.size) { - return false; - } - pos = new Pos(l, pos.ch, pos.sticky); - return (lineObj = getLine(doc, l)); - } - function moveOnce(boundToLine) { - var next; - if (unit == "codepoint") { - var ch = lineObj.text.charCodeAt( - pos.ch + (dir > 0 ? 0 : -1) - ); - if (isNaN(ch)) { - next = null; - } else { - var astral = - dir > 0 - ? ch >= 55296 && ch < 56320 - : ch >= 56320 && ch < 57343; - next = new Pos( - pos.line, - Math.max( - 0, - Math.min( - lineObj.text.length, - pos.ch + dir * (astral ? 2 : 1) - ) - ), - -dir - ); - } - } else if (visually) { - next = moveVisually(doc.cm, lineObj, pos, dir); - } else { - next = moveLogically(lineObj, pos, dir); - } - if (next == null) { - if (!boundToLine && findNextLine()) { - pos = endOfLine( - visually, - doc.cm, - lineObj, - pos.line, - lineDir - ); - } else { - return false; - } - } else { - pos = next; - } - return true; - } - if (unit == "char" || unit == "codepoint") { - moveOnce(); - } else if (unit == "column") { - moveOnce(true); - } else if (unit == "word" || unit == "group") { - var sawType = null, - group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true; ; first = false) { - if (dir < 0 && !moveOnce(!first)) { - break; - } - var cur = lineObj.text.charAt(pos.ch) || "\n"; - var type = isWordChar(cur, helper) - ? "w" - : group && cur == "\n" - ? "n" - : !group || /\s/.test(cur) - ? null - : "p"; - if (group && !first && !type) { - type = "s"; - } - if (sawType && sawType != type) { - if (dir < 0) { - dir = 1; - moveOnce(); - pos.sticky = "after"; - } - break; - } - if (type) { - sawType = type; - } - if (dir > 0 && !moveOnce(!first)) { - break; - } - } - } - var result = skipAtomic(doc, pos, oldPos, origDir, true); - if (equalCursorPos(oldPos, result)) { - result.hitSide = true; - } - return result; + } + }); + }(); + iterator.throw = async err => { + if (!deferred.done) { + deferred.done = true; + deferred.error = err; + deferred.resolve(); + } + return { + done: true, + value: undefined + }; + }; + iterator.return = async () => { + dispose(); + return { + done: true, + value: undefined + }; + }; + return iterator; + }, + async dispose() { + disposed = true; + if (connecting) { + // if there is a connection, close it + const [socket] = await connecting; + socket.close(1000, 'Normal Closure'); + } + }, + terminate() { + if (connecting) { + // only if there is a connection + emitter.emit('closed', { + code: 4499, + reason: 'Terminated', + wasClean: false + }); + } + } + }; + } + function isLikeCloseEvent(val) { + return (0, _utils.isObject)(val) && 'code' in val && 'reason' in val; + } + function isFatalInternalCloseCode(code) { + if ([1000, 1001, 1006, 1005, 1012, 1013, 1013 // Bad Gateway + ].includes(code)) return false; + // all other internal errors are fatal + return code >= 1000 && code <= 1999; + } + function isWebSocket(val) { + return typeof val === 'function' && 'constructor' in val && 'CLOSED' in val && 'CLOSING' in val && 'CONNECTING' in val && 'OPEN' in val; + } + + /***/ }), + + /***/ "../../../node_modules/graphql-ws/lib/common.mjs": + /*!*******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/common.mjs ***! + \*******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.MessageType = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.CloseCode = void 0; + exports.isMessage = isMessage; + exports.parseMessage = parseMessage; + exports.stringifyMessage = stringifyMessage; + exports.validateMessage = validateMessage; + var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); + /** + * + * common + * + */ + + /** + * The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). + * + * @category Common + */ + const GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws'; + /** + * The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws). + * + * @private + */ + const DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws'; + /** + * `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). + * + * @category Common + */ + var CloseCode; + (function (CloseCode) { + CloseCode[CloseCode["InternalServerError"] = 4500] = "InternalServerError"; + CloseCode[CloseCode["InternalClientError"] = 4005] = "InternalClientError"; + CloseCode[CloseCode["BadRequest"] = 4400] = "BadRequest"; + CloseCode[CloseCode["BadResponse"] = 4004] = "BadResponse"; + /** Tried subscribing before connect ack */ + CloseCode[CloseCode["Unauthorized"] = 4401] = "Unauthorized"; + CloseCode[CloseCode["Forbidden"] = 4403] = "Forbidden"; + CloseCode[CloseCode["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable"; + CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout"; + CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout"; + /** Subscriber distinction is very important */ + CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists"; + CloseCode[CloseCode["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests"; + })(CloseCode || (exports.CloseCode = CloseCode = {})); + /** + * Types of messages allowed to be sent by the client/server over the WS protocol. + * + * @category Common + */ + var MessageType; + (function (MessageType) { + MessageType["ConnectionInit"] = "connection_init"; + MessageType["ConnectionAck"] = "connection_ack"; + MessageType["Ping"] = "ping"; + MessageType["Pong"] = "pong"; + MessageType["Subscribe"] = "subscribe"; + MessageType["Next"] = "next"; + MessageType["Error"] = "error"; + MessageType["Complete"] = "complete"; + })(MessageType || (exports.MessageType = MessageType = {})); + /** + * Validates the message against the GraphQL over WebSocket Protocol. + * + * Invalid messages will throw descriptive errors. + * + * @category Common + */ + function validateMessage(val) { + if (!(0, _utils.isObject)(val)) { + throw new Error(`Message is expected to be an object, but got ${(0, _utils.extendedTypeof)(val)}`); + } + if (!val.type) { + throw new Error(`Message is missing the 'type' property`); + } + if (typeof val.type !== 'string') { + throw new Error(`Message is expects the 'type' property to be a string, but got ${(0, _utils.extendedTypeof)(val.type)}`); + } + switch (val.type) { + case MessageType.ConnectionInit: + case MessageType.ConnectionAck: + case MessageType.Ping: + case MessageType.Pong: + { + if (val.payload != null && !(0, _utils.isObject)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${val.payload}"`); + } + break; + } + case MessageType.Subscribe: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + if (!(0, _utils.isObject)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); + } + if (typeof val.payload.query !== 'string') { + throw new Error(`"${val.type}" message payload expects the 'query' property to be a string, but got ${(0, _utils.extendedTypeof)(val.payload.query)}`); + } + if (val.payload.variables != null && !(0, _utils.isObject)(val.payload.variables)) { + throw new Error(`"${val.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.variables)}`); + } + if (val.payload.operationName != null && (0, _utils.extendedTypeof)(val.payload.operationName) !== 'string') { + throw new Error(`"${val.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.operationName)}`); + } + if (val.payload.extensions != null && !(0, _utils.isObject)(val.payload.extensions)) { + throw new Error(`"${val.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.extensions)}`); + } + break; + } + case MessageType.Next: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + if (!(0, _utils.isObject)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); + } + break; + } + case MessageType.Error: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + if (!(0, _utils.areGraphQLErrors)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(val.payload)}`); + } + break; + } + case MessageType.Complete: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + break; + } + default: + throw new Error(`Invalid message 'type' property "${val.type}"`); + } + return val; + } + /** + * Checks if the provided value is a valid GraphQL over WebSocket message. + * + * @deprecated Use `validateMessage` instead. + * + * @category Common + */ + function isMessage(val) { + try { + validateMessage(val); + return true; + } catch (_a) { + return false; + } + } + /** + * Parses the raw websocket message data to a valid message. + * + * @category Common + */ + function parseMessage(data, reviver) { + return validateMessage(typeof data === 'string' ? JSON.parse(data, reviver) : data); + } + /** + * Stringifies a valid message ready to be sent through the socket. + * + * @category Common + */ + function stringifyMessage(msg, replacer) { + validateMessage(msg); + return JSON.stringify(msg, replacer); + } + + /***/ }), + + /***/ "../../../node_modules/graphql-ws/lib/index.js": + /*!*****************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/index.js ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; + } + Object.defineProperty(o, k2, desc); + } : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + var __exportStar = void 0 && (void 0).__exportStar || function (m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); + }; + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + __exportStar(__webpack_require__(/*! ./client */ "../../../node_modules/graphql-ws/lib/client.mjs"), exports); + __exportStar(__webpack_require__(/*! ./server */ "../../../node_modules/graphql-ws/lib/server.mjs"), exports); + __exportStar(__webpack_require__(/*! ./common */ "../../../node_modules/graphql-ws/lib/common.mjs"), exports); + + /***/ }), + + /***/ "../../../node_modules/graphql-ws/lib/server.mjs": + /*!*******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/server.mjs ***! + \*******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.handleProtocols = handleProtocols; + exports.makeServer = makeServer; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); + var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); + /** + * + * server + * + */ + var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + }; + /** + * Makes a Protocol complient WebSocket GraphQL server. The server + * is actually an API which is to be used with your favourite WebSocket + * server library! + * + * Read more about the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). + * + * @category Server + */ + function makeServer(options) { + const { + schema, + context, + roots, + validate, + execute, + subscribe, + connectionInitWaitTimeout = 3000, + // 3 seconds + onConnect, + onDisconnect, + onClose, + onSubscribe, + onOperation, + onNext, + onError, + onComplete, + jsonMessageReviver: reviver, + jsonMessageReplacer: replacer + } = options; + return { + opened(socket, extra) { + const ctx = { + connectionInitReceived: false, + acknowledged: false, + subscriptions: {}, + extra + }; + if (socket.protocol !== _common.GRAPHQL_TRANSPORT_WS_PROTOCOL) { + socket.close(_common.CloseCode.SubprotocolNotAcceptable, 'Subprotocol not acceptable'); + return async (code, reason) => { + /* nothing was set up, just notify the closure */ + await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); + }; + } + // kick the client off (close socket) if the connection has + // not been initialised after the specified wait timeout + const connectionInitWait = connectionInitWaitTimeout > 0 && isFinite(connectionInitWaitTimeout) ? setTimeout(() => { + if (!ctx.connectionInitReceived) socket.close(_common.CloseCode.ConnectionInitialisationTimeout, 'Connection initialisation timeout'); + }, connectionInitWaitTimeout) : null; + socket.onMessage(async function onMessage(data) { + var _a, e_1, _b, _c; + var _d; + let message; + try { + message = (0, _common.parseMessage)(data, reviver); + } catch (err) { + return socket.close(_common.CloseCode.BadRequest, 'Invalid message received'); + } + switch (message.type) { + case _common.MessageType.ConnectionInit: + { + if (ctx.connectionInitReceived) return socket.close(_common.CloseCode.TooManyInitialisationRequests, 'Too many initialisation requests'); + // @ts-expect-error: I can write + ctx.connectionInitReceived = true; + if ((0, _utils.isObject)(message.payload)) + // @ts-expect-error: I can write + ctx.connectionParams = message.payload; + const permittedOrPayload = await (onConnect === null || onConnect === void 0 ? void 0 : onConnect(ctx)); + if (permittedOrPayload === false) return socket.close(_common.CloseCode.Forbidden, 'Forbidden'); + await socket.send((0, _common.stringifyMessage)((0, _utils.isObject)(permittedOrPayload) ? { + type: _common.MessageType.ConnectionAck, + payload: permittedOrPayload + } : { + type: _common.MessageType.ConnectionAck + // payload is completely absent if not provided + }, replacer)); + // @ts-expect-error: I can write + ctx.acknowledged = true; + return; } - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, - x = pos.left, - y; - if (unit == "page") { - var pageSize = Math.min( - cm.display.wrapper.clientHeight, - window.innerHeight || document.documentElement.clientHeight - ); - var moveAmount = Math.max( - pageSize - 0.5 * textHeight(cm.display), - 3 - ); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - var target; - for (;;) { - target = coordsChar(cm, x, y); - if (!target.outside) { - break; - } - if (dir < 0 ? y <= 0 : y >= doc.height) { - target.hitSide = true; - break; - } - y += dir * 5; - } - return target; + case _common.MessageType.Ping: + { + if (socket.onPing) + // if the onPing listener is registered, automatic pong is disabled + return await socket.onPing(message.payload); + await socket.send((0, _common.stringifyMessage)(message.payload ? { + type: _common.MessageType.Pong, + payload: message.payload + } : { + type: _common.MessageType.Pong + // payload is completely absent if not provided + })); + return; } - var ContentEditableInput = function (cm) { - this.cm = cm; - this.lastAnchorNode = - this.lastAnchorOffset = - this.lastFocusNode = - this.lastFocusOffset = - null; - this.polling = new Delayed(); - this.composing = null; - this.gracePeriod = false; - this.readDOMTimeout = null; - }; - ContentEditableInput.prototype.init = function (display) { - var this$1$1 = this; - var input = this, - cm = input.cm; - var div = (input.div = display.lineDiv); - div.contentEditable = true; - disableBrowserMagic( - div, - cm.options.spellcheck, - cm.options.autocorrect, - cm.options.autocapitalize - ); - function belongsToInput(e) { - for (var t = e.target; t; t = t.parentNode) { - if (t == div) { - return true; - } - if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { - break; - } - } - return false; - } - on(div, "paste", function (e) { - if ( - !belongsToInput(e) || - signalDOMEvent(cm, e) || - handlePaste(e, cm) - ) { - return; - } - if (ie_version <= 11) { - setTimeout( - operation(cm, function () { - return this$1$1.updateFromDOM(); - }), - 20 - ); - } - }); - on(div, "compositionstart", function (e) { - this$1$1.composing = { - data: e.data, - done: false, - }; - }); - on(div, "compositionupdate", function (e) { - if (!this$1$1.composing) { - this$1$1.composing = { - data: e.data, - done: false, + case _common.MessageType.Pong: + return await ((_d = socket.onPong) === null || _d === void 0 ? void 0 : _d.call(socket, message.payload)); + case _common.MessageType.Subscribe: + { + if (!ctx.acknowledged) return socket.close(_common.CloseCode.Unauthorized, 'Unauthorized'); + const { + id, + payload + } = message; + if (id in ctx.subscriptions) return socket.close(_common.CloseCode.SubscriberAlreadyExists, `Subscriber for ${id} already exists`); + // if this turns out to be a streaming operation, the subscription value + // will change to an `AsyncIterable`, otherwise it will stay as is + ctx.subscriptions[id] = null; + const emit = { + next: async (result, args) => { + let nextMessage = { + id, + type: _common.MessageType.Next, + payload: result }; - } - }); - on(div, "compositionend", function (e) { - if (this$1$1.composing) { - if (e.data != this$1$1.composing.data) { - this$1$1.readFromDOMSoon(); - } - this$1$1.composing.done = true; - } - }); - on(div, "touchstart", function () { - return input.forceCompositionEnd(); - }); - on(div, "input", function () { - if (!this$1$1.composing) { - this$1$1.readFromDOMSoon(); - } - }); - function onCopyCut(e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e)) { - return; - } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections(), + const maybeResult = await (onNext === null || onNext === void 0 ? void 0 : onNext(ctx, nextMessage, args, result)); + if (maybeResult) nextMessage = Object.assign(Object.assign({}, nextMessage), { + payload: maybeResult }); - if (e.type == "cut") { - cm.replaceSelection("", null, "cut"); - } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text, + await socket.send((0, _common.stringifyMessage)(nextMessage, replacer)); + }, + error: async errors => { + let errorMessage = { + id, + type: _common.MessageType.Error, + payload: errors + }; + const maybeErrors = await (onError === null || onError === void 0 ? void 0 : onError(ctx, errorMessage, errors)); + if (maybeErrors) errorMessage = Object.assign(Object.assign({}, errorMessage), { + payload: maybeErrors }); - if (e.type == "cut") { - cm.operation(function () { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); - } - } - if (e.clipboardData) { - e.clipboardData.clearData(); - var content = lastCopied.text.join("\n"); - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return; - } - } - var kludge = hiddenTextarea(), - te = kludge.firstChild; - cm.display.lineSpace.insertBefore( - kludge, - cm.display.lineSpace.firstChild - ); - te.value = lastCopied.text.join("\n"); - var hadFocus = activeElt(); - selectInput(te); - setTimeout(function () { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) { - input.showPrimarySelection(); - } - }, 50); - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }; - ContentEditableInput.prototype.screenReaderLabelChanged = - function (label) { - if (label) { - this.div.setAttribute("aria-label", label); - } else { - this.div.removeAttribute("aria-label"); - } - }; - ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = activeElt() == this.div; - return result; - }; - ContentEditableInput.prototype.showSelection = function ( - info, - takeFocus - ) { - if (!info || !this.cm.display.view.length) { - return; - } - if (info.focus || takeFocus) { - this.showPrimarySelection(); - } - this.showMultipleSelections(info); - }; - ContentEditableInput.prototype.getSelection = function () { - return this.cm.display.wrapper.ownerDocument.getSelection(); - }; - ContentEditableInput.prototype.showPrimarySelection = - function () { - var sel = this.getSelection(), - cm = this.cm, - prim = cm.doc.sel.primary(); - var from = prim.from(), - to = prim.to(); - if ( - cm.display.viewTo == cm.display.viewFrom || - from.line >= cm.display.viewTo || - to.line < cm.display.viewFrom - ) { - sel.removeAllRanges(); - return; - } - var curAnchor = domToPos( - cm, - sel.anchorNode, - sel.anchorOffset - ); - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); - if ( - curAnchor && - !curAnchor.bad && - curFocus && - !curFocus.bad && - cmp(minPos(curAnchor, curFocus), from) == 0 && - cmp(maxPos(curAnchor, curFocus), to) == 0 - ) { - return; - } - var view = cm.display.view; - var start = (from.line >= cm.display.viewFrom && - posToDOM(cm, from)) || { - node: view[0].measure.map[2], - offset: 0, - }; - var end = to.line < cm.display.viewTo && posToDOM(cm, to); - if (!end) { - var measure = view[view.length - 1].measure; - var map2 = measure.maps - ? measure.maps[measure.maps.length - 1] - : measure.map; - end = { - node: map2[map2.length - 1], - offset: map2[map2.length - 2] - map2[map2.length - 3], + await socket.send((0, _common.stringifyMessage)(errorMessage, replacer)); + }, + complete: async notifyClient => { + const completeMessage = { + id, + type: _common.MessageType.Complete }; + await (onComplete === null || onComplete === void 0 ? void 0 : onComplete(ctx, completeMessage)); + if (notifyClient) await socket.send((0, _common.stringifyMessage)(completeMessage, replacer)); } - if (!start || !end) { - sel.removeAllRanges(); - return; - } - var old = sel.rangeCount && sel.getRangeAt(0), - rng; - try { - rng = range(start.node, start.offset, end.offset, end.node); - } catch (e) {} - if (rng) { - if (!gecko && cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) { - sel.removeAllRanges(); - sel.addRange(rng); - } - } else { - sel.removeAllRanges(); - sel.addRange(rng); - } - if (old && sel.anchorNode == null) { - sel.addRange(old); - } else if (gecko) { - this.startGracePeriod(); - } - } - this.rememberSelection(); }; - ContentEditableInput.prototype.startGracePeriod = function () { - var this$1$1 = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function () { - this$1$1.gracePeriod = false; - if (this$1$1.selectionChanged()) { - this$1$1.cm.operation(function () { - return (this$1$1.cm.curOp.selectionChanged = true); - }); - } - }, 20); - }; - ContentEditableInput.prototype.showMultipleSelections = function ( - info - ) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd( - this.cm.display.selectionDiv, - info.selection - ); - }; - ContentEditableInput.prototype.rememberSelection = function () { - var sel = this.getSelection(); - this.lastAnchorNode = sel.anchorNode; - this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; - this.lastFocusOffset = sel.focusOffset; - }; - ContentEditableInput.prototype.selectionInEditor = function () { - var sel = this.getSelection(); - if (!sel.rangeCount) { - return false; - } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }; - ContentEditableInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor") { - if (!this.selectionInEditor() || activeElt() != this.div) { - this.showSelection(this.prepareSelection(), true); - } - this.div.focus(); - } - }; - ContentEditableInput.prototype.blur = function () { - this.div.blur(); - }; - ContentEditableInput.prototype.getField = function () { - return this.div; - }; - ContentEditableInput.prototype.supportsTouch = function () { - return true; - }; - ContentEditableInput.prototype.receivedFocus = function () { - var this$1$1 = this; - var input = this; - if (this.selectionInEditor()) { - setTimeout(function () { - return this$1$1.pollSelection(); - }, 20); - } else { - runInOp(this.cm, function () { - return (input.cm.curOp.selectionChanged = true); - }); - } - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }; - ContentEditableInput.prototype.selectionChanged = function () { - var sel = this.getSelection(); - return ( - sel.anchorNode != this.lastAnchorNode || - sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || - sel.focusOffset != this.lastFocusOffset - ); - }; - ContentEditableInput.prototype.pollSelection = function () { - if ( - this.readDOMTimeout != null || - this.gracePeriod || - !this.selectionChanged() - ) { - return; - } - var sel = this.getSelection(), - cm = this.cm; - if ( - android && - chrome && - this.cm.display.gutterSpecs.length && - isInGutter(sel.anchorNode) - ) { - this.cm.triggerOnKeyDown({ - type: "keydown", - keyCode: 8, - preventDefault: Math.abs, - }); - this.blur(); - this.focus(); - return; - } - if (this.composing) { - return; - } - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) { - runInOp(cm, function () { - setSelection( - cm.doc, - simpleSelection(anchor, head), - sel_dontScroll - ); - if (anchor.bad || head.bad) { - cm.curOp.selectionChanged = true; - } - }); - } - }; - ContentEditableInput.prototype.pollContent = function () { - if (this.readDOMTimeout != null) { - clearTimeout(this.readDOMTimeout); - this.readDOMTimeout = null; - } - var cm = this.cm, - display = cm.display, - sel = cm.doc.sel.primary(); - var from = sel.from(), - to = sel.to(); - if (from.ch == 0 && from.line > cm.firstLine()) { - from = Pos( - from.line - 1, - getLine(cm.doc, from.line - 1).length - ); - } - if ( - to.ch == getLine(cm.doc, to.line).text.length && - to.line < cm.lastLine() - ) { - to = Pos(to.line + 1, 0); - } - if ( - from.line < display.viewFrom || - to.line > display.viewTo - 1 - ) { - return false; - } - var fromIndex, fromLine, fromNode; - if ( - from.line == display.viewFrom || - (fromIndex = findViewIndex(cm, from.line)) == 0 - ) { - fromLine = lineNo(display.view[0].line); - fromNode = display.view[0].node; - } else { - fromLine = lineNo(display.view[fromIndex].line); - fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - var toLine, toNode; - if (toIndex == display.view.length - 1) { - toLine = display.viewTo - 1; - toNode = display.lineDiv.lastChild; - } else { - toLine = lineNo(display.view[toIndex + 1].line) - 1; - toNode = display.view[toIndex + 1].node.previousSibling; - } - if (!fromNode) { - return false; - } - var newText = cm.doc.splitLines( - domTextBetween(cm, fromNode, toNode, fromLine, toLine) - ); - var oldText = getBetween( - cm.doc, - Pos(fromLine, 0), - Pos(toLine, getLine(cm.doc, toLine).text.length) - ); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { - newText.pop(); - oldText.pop(); - toLine--; - } else if (newText[0] == oldText[0]) { - newText.shift(); - oldText.shift(); - fromLine++; + try { + let execArgs; + const maybeExecArgsOrErrors = await (onSubscribe === null || onSubscribe === void 0 ? void 0 : onSubscribe(ctx, message)); + if (maybeExecArgsOrErrors) { + if ((0, _utils.areGraphQLErrors)(maybeExecArgsOrErrors)) return await emit.error(maybeExecArgsOrErrors);else if (Array.isArray(maybeExecArgsOrErrors)) throw new Error('Invalid return value from onSubscribe hook, expected an array of GraphQLError objects'); + // not errors, is exec args + execArgs = maybeExecArgsOrErrors; } else { - break; - } - } - var cutFront = 0, - cutEnd = 0; - var newTop = newText[0], - oldTop = oldText[0], - maxCutFront = Math.min(newTop.length, oldTop.length); - while ( - cutFront < maxCutFront && - newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront) - ) { - ++cutFront; - } - var newBot = lst(newText), - oldBot = lst(oldText); - var maxCutEnd = Math.min( - newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0) - ); - while ( - cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == - oldBot.charCodeAt(oldBot.length - cutEnd - 1) - ) { - ++cutEnd; - } - if ( - newText.length == 1 && - oldText.length == 1 && - fromLine == from.line - ) { - while ( - cutFront && - cutFront > from.ch && - newBot.charCodeAt(newBot.length - cutEnd - 1) == - oldBot.charCodeAt(oldBot.length - cutEnd - 1) - ) { - cutFront--; - cutEnd++; - } - } - newText[newText.length - 1] = newBot - .slice(0, newBot.length - cutEnd) - .replace(/^\u200b+/, ""); - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos( - toLine, - oldText.length ? lst(oldText).length - cutEnd : 0 - ); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; - } - }; - ContentEditableInput.prototype.ensurePolled = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.reset = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.forceCompositionEnd = function () { - if (!this.composing) { - return; - } - clearTimeout(this.readDOMTimeout); - this.composing = null; - this.updateFromDOM(); - this.div.blur(); - this.div.focus(); - }; - ContentEditableInput.prototype.readFromDOMSoon = function () { - var this$1$1 = this; - if (this.readDOMTimeout != null) { - return; - } - this.readDOMTimeout = setTimeout(function () { - this$1$1.readDOMTimeout = null; - if (this$1$1.composing) { - if (this$1$1.composing.done) { - this$1$1.composing = null; + // you either provide a schema dynamically through + // `onSubscribe` or you set one up during the server setup + if (!schema) throw new Error('The GraphQL schema is not provided'); + const args = { + operationName: payload.operationName, + document: (0, _graphql.parse)(payload.query), + variableValues: payload.variables + }; + execArgs = Object.assign(Object.assign({}, args), { + schema: typeof schema === 'function' ? await schema(ctx, message, args) : schema + }); + const validationErrors = (validate !== null && validate !== void 0 ? validate : _graphql.validate)(execArgs.schema, execArgs.document); + if (validationErrors.length > 0) return await emit.error(validationErrors); + } + const operationAST = (0, _graphql.getOperationAST)(execArgs.document, execArgs.operationName); + if (!operationAST) return await emit.error([new _graphql.GraphQLError('Unable to identify operation')]); + // if `onSubscribe` didnt specify a rootValue, inject one + if (!('rootValue' in execArgs)) execArgs.rootValue = roots === null || roots === void 0 ? void 0 : roots[operationAST.operation]; + // if `onSubscribe` didn't specify a context, inject one + if (!('contextValue' in execArgs)) execArgs.contextValue = typeof context === 'function' ? await context(ctx, message, execArgs) : context; + // the execution arguments have been prepared + // perform the operation and act accordingly + let operationResult; + if (operationAST.operation === 'subscription') operationResult = await (subscribe !== null && subscribe !== void 0 ? subscribe : _graphql.subscribe)(execArgs); + // operation === 'query' || 'mutation' + else operationResult = await (execute !== null && execute !== void 0 ? execute : _graphql.execute)(execArgs); + const maybeResult = await (onOperation === null || onOperation === void 0 ? void 0 : onOperation(ctx, message, execArgs, operationResult)); + if (maybeResult) operationResult = maybeResult; + if ((0, _utils.isAsyncIterable)(operationResult)) { + /** multiple emitted results */ + if (!(id in ctx.subscriptions)) { + // subscription was completed/canceled before the operation settled + if ((0, _utils.isAsyncGenerator)(operationResult)) operationResult.return(undefined); } else { - return; + ctx.subscriptions[id] = operationResult; + try { + for (var _e = true, operationResult_1 = __asyncValues(operationResult), operationResult_1_1; operationResult_1_1 = await operationResult_1.next(), _a = operationResult_1_1.done, !_a; _e = true) { + _c = operationResult_1_1.value; + _e = false; + const result = _c; + await emit.next(result, execArgs); + } + } catch (e_1_1) { + e_1 = { + error: e_1_1 + }; + } finally { + try { + if (!_e && !_a && (_b = operationResult_1.return)) await _b.call(operationResult_1); + } finally { + if (e_1) throw e_1.error; + } + } } - } - this$1$1.updateFromDOM(); - }, 80); - }; - ContentEditableInput.prototype.updateFromDOM = function () { - var this$1$1 = this; - if (this.cm.isReadOnly() || !this.pollContent()) { - runInOp(this.cm, function () { - return regChange(this$1$1.cm); - }); - } - }; - ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; - }; - ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { - return; - } - e.preventDefault(); - if (!this.cm.isReadOnly()) { - operation(this.cm, applyTextInput)( - this.cm, - String.fromCharCode( - e.charCode == null ? e.keyCode : e.charCode - ), - 0 - ); - } - }; - ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); - }; - ContentEditableInput.prototype.onContextMenu = function () {}; - ContentEditableInput.prototype.resetPosition = function () {}; - ContentEditableInput.prototype.needsContentAttribute = true; - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) { - return null; - } - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - var order = getOrder(line, cm.doc.direction), - side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = - result.collapse == "right" ? result.end : result.start; - return result; - } - function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) { - if (/CodeMirror-gutter-wrapper/.test(scan.className)) { - return true; - } + } else { + /** single emitted result */ + // if the client completed the subscription before the single result + // became available, he effectively canceled it and no data should be sent + if (id in ctx.subscriptions) await emit.next(operationResult, execArgs); + } + // lack of subscription at this point indicates that the client + // completed the subscription, he doesnt need to be reminded + await emit.complete(id in ctx.subscriptions); + } finally { + // whatever happens to the subscription, we finally want to get rid of the reservation + delete ctx.subscriptions[id]; } - return false; + return; } - function badPos(pos, bad) { - if (bad) { - pos.bad = true; - } - return pos; + case _common.MessageType.Complete: + { + const subscription = ctx.subscriptions[message.id]; + delete ctx.subscriptions[message.id]; // deleting the subscription means no further activity should take place + if ((0, _utils.isAsyncGenerator)(subscription)) await subscription.return(undefined); + return; } - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", - closing = false, - lineSep = cm.doc.lineSeparator(), - extraLinebreak = false; - function recognizeMarker(id) { - return function (marker) { - return marker.id == id; - }; - } - function close() { - if (closing) { - text += lineSep; - if (extraLinebreak) { - text += lineSep; - } - closing = extraLinebreak = false; - } - } - function addText(str) { - if (str) { - close(); - text += str; - } - } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText) { - addText(cmText); - return; - } - var markerID = node.getAttribute("cm-marker"), - range2; - if (markerID) { - var found = cm.findMarks( - Pos(fromLine, 0), - Pos(toLine + 1, 0), - recognizeMarker(+markerID) - ); - if (found.length && (range2 = found[0].find(0))) { - addText( - getBetween(cm.doc, range2.from, range2.to).join( - lineSep - ) - ); - } - return; - } - if (node.getAttribute("contenteditable") == "false") { - return; - } - var isBlock = /^(pre|div|p|li|table|br)$/i.test( - node.nodeName - ); - if ( - !/^br$/i.test(node.nodeName) && - node.textContent.length == 0 - ) { - return; - } - if (isBlock) { - close(); - } - for (var i2 = 0; i2 < node.childNodes.length; i2++) { - walk(node.childNodes[i2]); - } - if (/^(pre|p)$/i.test(node.nodeName)) { - extraLinebreak = true; - } - if (isBlock) { - closing = true; - } - } else if (node.nodeType == 3) { - addText( - node.nodeValue - .replace(/\u200b/g, "") - .replace(/\u00a0/g, " ") - ); - } - } - for (;;) { - walk(from); - if (from == to) { - break; - } - from = from.nextSibling; - extraLinebreak = false; - } - return text; + default: + throw new Error(`Unexpected message of type ${message.type} received`); + } + }); + // wait for close, cleanup and the disconnect callback + return async (code, reason) => { + if (connectionInitWait) clearTimeout(connectionInitWait); + for (const sub of Object.values(ctx.subscriptions)) { + if ((0, _utils.isAsyncGenerator)(sub)) await sub.return(undefined); + } + if (ctx.acknowledged) await (onDisconnect === null || onDisconnect === void 0 ? void 0 : onDisconnect(ctx, code, reason)); + await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); + }; + } + }; + } + /** + * Helper utility for choosing the "graphql-transport-ws" subprotocol from + * a set of WebSocket subprotocols. + * + * Accepts a set of already extracted WebSocket subprotocols or the raw + * Sec-WebSocket-Protocol header value. In either case, if the right + * protocol appears, it will be returned. + * + * By specification, the server should not provide a value with Sec-WebSocket-Protocol + * if it does not agree with client's subprotocols. The client has a responsibility + * to handle the connection afterwards. + * + * @category Server + */ + function handleProtocols(protocols) { + switch (true) { + case protocols instanceof Set && protocols.has(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): + case Array.isArray(protocols) && protocols.includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): + case typeof protocols === 'string' && protocols.split(',').map(p => p.trim()).includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): + return _common.GRAPHQL_TRANSPORT_WS_PROTOCOL; + default: + return false; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql-ws/lib/utils.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/utils.mjs ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.areGraphQLErrors = areGraphQLErrors; + exports.extendedTypeof = extendedTypeof; + exports.isAsyncGenerator = isAsyncGenerator; + exports.isAsyncIterable = isAsyncIterable; + exports.isObject = isObject; + exports.limitCloseReason = limitCloseReason; + /** @private */ + function extendedTypeof(val) { + if (val === null) { + return 'null'; + } + if (Array.isArray(val)) { + return 'array'; + } + return typeof val; + } + /** @private */ + function isObject(val) { + return extendedTypeof(val) === 'object'; + } + /** @private */ + function isAsyncIterable(val) { + return typeof Object(val)[Symbol.asyncIterator] === 'function'; + } + /** @private */ + function isAsyncGenerator(val) { + return isObject(val) && typeof Object(val)[Symbol.asyncIterator] === 'function' && typeof val.return === 'function' + // for lazy ones, we only need the return anyway + // typeof val.throw === 'function' && + // typeof val.next === 'function' + ; + } + /** @private */ + function areGraphQLErrors(obj) { + return Array.isArray(obj) && + // must be at least one error + obj.length > 0 && + // error has at least a message + obj.every(ob => 'message' in ob); + } + /** + * Limits the WebSocket close event reason to not exceed a length of one frame. + * Reference: https://datatracker.ietf.org/doc/html/rfc6455#section-5.2. + * + * @private + */ + function limitCloseReason(reason, whenTooLong) { + return reason.length < 124 ? reason : whenTooLong; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/error/GraphQLError.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/error/GraphQLError.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.GraphQLError = void 0; + exports.formatError = formatError; + exports.printError = printError; + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _location = __webpack_require__(/*! ../language/location.mjs */ "../../../node_modules/graphql/language/location.mjs"); + var _printLocation = __webpack_require__(/*! ../language/printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); + function toNormalizedOptions(args) { + const firstArg = args[0]; + if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { + return { + nodes: firstArg, + source: args[1], + positions: args[2], + path: args[3], + originalError: args[4], + extensions: args[5] + }; + } + return firstArg; + } + /** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ + + class GraphQLError extends Error { + /** + * An array of `{ line, column }` locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + + /** + * The original error thrown from a field resolver during execution. + */ + + /** + * Extension fields to add to the formatted error. + */ + + /** + * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + */ + constructor(message, ...rawArgs) { + var _this$nodes, _nodeLocations$, _ref; + const { + nodes, + source, + positions, + path, + originalError, + extensions + } = toNormalizedOptions(rawArgs); + super(message); + this.name = 'GraphQLError'; + this.path = path !== null && path !== void 0 ? path : undefined; + this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. + + this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); + const nodeLocations = undefinedIfEmpty((_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map(node => node.loc).filter(loc => loc != null)); // Compute locations in the source for the given nodes/positions. + + this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source; + this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => loc.start); + this.locations = positions && source ? positions.map(pos => (0, _location.getLocation)(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => (0, _location.getLocation)(loc.source, loc.start)); + const originalExtensions = (0, _isObjectLike.isObjectLike)(originalError === null || originalError === void 0 ? void 0 : originalError.extensions) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : undefined; + this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : Object.create(null); // Only properties prescribed by the spec should be enumerable. + // Keep the rest as non-enumerable. + + Object.defineProperties(this, { + message: { + writable: true, + enumerable: true + }, + name: { + enumerable: false + }, + nodes: { + enumerable: false + }, + source: { + enumerable: false + }, + positions: { + enumerable: false + }, + originalError: { + enumerable: false + } + }); // Include (non-enumerable) stack trace. + + /* c8 ignore start */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + + if (originalError !== null && originalError !== void 0 && originalError.stack) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true + }); + } + /* c8 ignore stop */ + } + get [Symbol.toStringTag]() { + return 'GraphQLError'; + } + toString() { + let output = this.message; + if (this.nodes) { + for (const node of this.nodes) { + if (node.loc) { + output += '\n\n' + (0, _printLocation.printLocation)(node.loc); + } + } + } else if (this.source && this.locations) { + for (const location of this.locations) { + output += '\n\n' + (0, _printLocation.printSourceLocation)(this.source, location); + } + } + return output; + } + toJSON() { + const formattedError = { + message: this.message + }; + if (this.locations != null) { + formattedError.locations = this.locations; + } + if (this.path != null) { + formattedError.path = this.path; + } + if (this.extensions != null && Object.keys(this.extensions).length > 0) { + formattedError.extensions = this.extensions; + } + return formattedError; + } + } + exports.GraphQLError = GraphQLError; + function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; + } + /** + * See: https://spec.graphql.org/draft/#sec-Errors + */ + + /** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + * + * @deprecated Please use `error.toString` instead. Will be removed in v17 + */ + function printError(error) { + return error.toString(); + } + /** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + * + * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + */ + + function formatError(error) { + return error.toJSON(); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/error/index.mjs": + /*!*****************************************************!*\ + !*** ../../../node_modules/graphql/error/index.mjs ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "GraphQLError", ({ + enumerable: true, + get: function () { + return _GraphQLError.GraphQLError; + } + })); + Object.defineProperty(exports, "formatError", ({ + enumerable: true, + get: function () { + return _GraphQLError.formatError; + } + })); + Object.defineProperty(exports, "locatedError", ({ + enumerable: true, + get: function () { + return _locatedError.locatedError; + } + })); + Object.defineProperty(exports, "printError", ({ + enumerable: true, + get: function () { + return _GraphQLError.printError; + } + })); + Object.defineProperty(exports, "syntaxError", ({ + enumerable: true, + get: function () { + return _syntaxError.syntaxError; + } + })); + var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _syntaxError = __webpack_require__(/*! ./syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); + var _locatedError = __webpack_require__(/*! ./locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/error/locatedError.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/error/locatedError.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.locatedError = locatedError; + var _toError = __webpack_require__(/*! ../jsutils/toError.mjs */ "../../../node_modules/graphql/jsutils/toError.mjs"); + var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ + + function locatedError(rawOriginalError, nodes, path) { + var _nodes; + const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + + if (isLocatedGraphQLError(originalError)) { + return originalError; + } + return new _GraphQLError.GraphQLError(originalError.message, { + nodes: (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, + source: originalError.source, + positions: originalError.positions, + path, + originalError + }); + } + function isLocatedGraphQLError(error) { + return Array.isArray(error.path); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/error/syntaxError.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/error/syntaxError.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.syntaxError = syntaxError; + var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ + + function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { + source, + positions: [position] + }); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/execution/collectFields.mjs": + /*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/execution/collectFields.mjs ***! + \*****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.collectFields = collectFields; + exports.collectSubfields = collectSubfields; + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + /** + * Given a selectionSet, collects all of the fields and returns them. + * + * CollectFields requires the "runtime type" of an object. For a field that + * returns an Interface or Union type, the "runtime type" will be the actual + * object type returned by that field. + * + * @internal + */ + + function collectFields(schema, fragments, variableValues, runtimeType, selectionSet) { + const fields = new Map(); + collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, new Set()); + return fields; + } + /** + * Given an array of field nodes, collects all of the subfields of the passed + * in fields, and returns them at the end. + * + * CollectSubFields requires the "return type" of an object. For a field that + * returns an Interface or Union type, the "return type" will be the actual + * object type returned by that field. + * + * @internal + */ + + function collectSubfields(schema, fragments, variableValues, returnType, fieldNodes) { + const subFieldNodes = new Map(); + const visitedFragmentNames = new Set(); + for (const node of fieldNodes) { + if (node.selectionSet) { + collectFieldsImpl(schema, fragments, variableValues, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); + } + } + return subFieldNodes; + } + function collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: + { + if (!shouldIncludeNode(variableValues, selection)) { + continue; + } + const name = getFieldEntryKey(selection); + const fieldList = fields.get(name); + if (fieldList !== undefined) { + fieldList.push(selection); + } else { + fields.set(name, [selection]); + } + break; + } + case _kinds.Kind.INLINE_FRAGMENT: + { + if (!shouldIncludeNode(variableValues, selection) || !doesFragmentConditionMatch(schema, selection, runtimeType)) { + continue; + } + collectFieldsImpl(schema, fragments, variableValues, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + } + case _kinds.Kind.FRAGMENT_SPREAD: + { + const fragName = selection.name.value; + if (visitedFragmentNames.has(fragName) || !shouldIncludeNode(variableValues, selection)) { + continue; + } + visitedFragmentNames.add(fragName); + const fragment = fragments[fragName]; + if (!fragment || !doesFragmentConditionMatch(schema, fragment, runtimeType)) { + continue; + } + collectFieldsImpl(schema, fragments, variableValues, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + } + } + /** + * Determines if a field should be included based on the `@include` and `@skip` + * directives, where `@skip` has higher precedence than `@include`. + */ + + function shouldIncludeNode(variableValues, node) { + const skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, variableValues); + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; + } + const include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, variableValues); + if ((include === null || include === void 0 ? void 0 : include.if) === false) { + return false; + } + return true; + } + /** + * Determines if a fragment is applicable to the given type. + */ + + function doesFragmentConditionMatch(schema, fragment, type) { + const typeConditionNode = fragment.typeCondition; + if (!typeConditionNode) { + return true; + } + const conditionalType = (0, _typeFromAST.typeFromAST)(schema, typeConditionNode); + if (conditionalType === type) { + return true; + } + if ((0, _definition.isAbstractType)(conditionalType)) { + return schema.isSubType(conditionalType, type); + } + return false; + } + /** + * Implements the logic to compute the key of a given field's entry + */ + + function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/execution/execute.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/execution/execute.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.assertValidExecutionArguments = assertValidExecutionArguments; + exports.buildExecutionContext = buildExecutionContext; + exports.buildResolveInfo = buildResolveInfo; + exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; + exports.execute = execute; + exports.executeSync = executeSync; + exports.getFieldDef = getFieldDef; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _isPromise = __webpack_require__(/*! ../jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); + var _memoize = __webpack_require__(/*! ../jsutils/memoize3.mjs */ "../../../node_modules/graphql/jsutils/memoize3.mjs"); + var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); + var _promiseForObject = __webpack_require__(/*! ../jsutils/promiseForObject.mjs */ "../../../node_modules/graphql/jsutils/promiseForObject.mjs"); + var _promiseReduce = __webpack_require__(/*! ../jsutils/promiseReduce.mjs */ "../../../node_modules/graphql/jsutils/promiseReduce.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); + var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); + var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); + var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + /** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + const collectSubfields = (0, _memoize.memoize3)((exeContext, returnType, fieldNodes) => (0, _collectFields.collectSubfields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, returnType, fieldNodes)); + /** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g `a` + * 2) fragment "spreads" e.g. `...c` + * 3) inline fragment "spreads" e.g. `...on Type { a }` + */ + + /** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ + + /** + * Implements the "Executing requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + */ + function execute(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); + const { + schema, + document, + variableValues, + rootValue + } = args; // If arguments are missing or incorrect, throw an error. + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + // + // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + + try { + const { + operation + } = exeContext; + const result = executeOperation(exeContext, operation, rootValue); + if ((0, _isPromise.isPromise)(result)) { + return result.then(data => buildResponse(data, exeContext.errors), error => { + exeContext.errors.push(error); + return buildResponse(null, exeContext.errors); + }); + } + return buildResponse(result, exeContext.errors); + } catch (error) { + exeContext.errors.push(error); + return buildResponse(null, exeContext.errors); + } + } + /** + * Also implements the "Executing requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + function executeSync(args) { + const result = execute(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + return result; + } + /** + * Given a completed execution context and data, build the `{ errors, data }` + * response defined by the "Response" section of the GraphQL specification. + */ + + function buildResponse(data, errors) { + return errors.length === 0 ? { + data + } : { + errors, + data + }; + } + /** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + * + * @internal + */ + + function assertValidExecutionArguments(schema, document, rawVariableValues) { + document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + + rawVariableValues == null || (0, _isObjectLike.isObjectLike)(rawVariableValues) || (0, _devAssert.devAssert)(false, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); + } + /** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ + + function buildExecutionContext(args) { + var _definition$name, _operation$variableDe; + const { + schema, + document, + rootValue, + contextValue, + variableValues: rawVariableValues, + operationName, + fieldResolver, + typeResolver, + subscribeFieldResolver + } = args; + let operation; + const fragments = Object.create(null); + for (const definition of document.definitions) { + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')]; + } + operation = definition; + } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { + operation = definition; + } + break; + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + default: // ignore non-executable definitions + } + } + if (!operation) { + if (operationName != null) { + return [new _GraphQLError.GraphQLError(`Unknown operation named "${operationName}".`)]; + } + return [new _GraphQLError.GraphQLError('Must provide an operation.')]; + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : []; + const coercedVariableValues = (0, _values.getVariableValues)(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, { + maxErrors: 50 + }); + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver, + typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver, + subscribeFieldResolver: subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 ? subscribeFieldResolver : defaultFieldResolver, + errors: [] + }; + } + /** + * Implements the "Executing operations" section of the spec. + */ + + function executeOperation(exeContext, operation, rootValue) { + const rootType = exeContext.schema.getRootType(operation.operation); + if (rootType == null) { + throw new _GraphQLError.GraphQLError(`Schema is not configured to execute ${operation.operation} operation.`, { + nodes: operation + }); + } + const rootFields = (0, _collectFields.collectFields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, rootType, operation.selectionSet); + const path = undefined; + switch (operation.operation) { + case _ast.OperationTypeNode.QUERY: + return executeFields(exeContext, rootType, rootValue, path, rootFields); + case _ast.OperationTypeNode.MUTATION: + return executeFieldsSerially(exeContext, rootType, rootValue, path, rootFields); + case _ast.OperationTypeNode.SUBSCRIPTION: + // TODO: deprecate `subscribe` and move all logic here + // Temporary solution until we finish merging execute and subscribe together + return executeFields(exeContext, rootType, rootValue, path, rootFields); + } + } + /** + * Implements the "Executing selection sets" section of the spec + * for fields that must be executed serially. + */ + + function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return (0, _promiseReduce.promiseReduce)(fields.entries(), (results, [responseName, fieldNodes]) => { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + if (result === undefined) { + return results; + } + if ((0, _isPromise.isPromise)(result)) { + return result.then(resolvedResult => { + results[responseName] = resolvedResult; + return results; + }); + } + results[responseName] = result; + return results; + }, Object.create(null)); + } + /** + * Implements the "Executing selection sets" section of the spec + * for fields that may be executed in parallel. + */ + + function executeFields(exeContext, parentType, sourceValue, path, fields) { + const results = Object.create(null); + let containsPromise = false; + try { + for (const [responseName, fieldNodes] of fields.entries()) { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + if (result !== undefined) { + results[responseName] = result; + if ((0, _isPromise.isPromise)(result)) { + containsPromise = true; + } + } + } + } catch (error) { + if (containsPromise) { + // Ensure that any promises returned by other fields are handled, as they may also reject. + return (0, _promiseForObject.promiseForObject)(results).finally(() => { + throw error; + }); + } + throw error; + } // If there are no promises, we can just return the object + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + return (0, _promiseForObject.promiseForObject)(results); + } + /** + * Implements the "Executing fields" section of the spec + * In particular, this function figures out the value that the field returns by + * calling its resolve function, then calls completeValue to complete promises, + * serialize scalars, or execute the sub-selection-set for objects. + */ + + function executeField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); + if (!fieldDef) { + return; + } + const returnType = fieldDef.type; + const resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver; + const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error). + + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; + const result = resolveFn(source, args, contextValue, info); + let completed; + if ((0, _isPromise.isPromise)(result)) { + completed = result.then(resolved => completeValue(exeContext, returnType, fieldNodes, info, path, resolved)); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + if ((0, _isPromise.isPromise)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, rawError => { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); + return handleFieldError(error, returnType, exeContext); + }); + } + return completed; + } catch (rawError) { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); + return handleFieldError(error, returnType, exeContext); + } + } + /** + * @internal + */ + + function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; + } + function handleFieldError(error, returnType, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + exeContext.errors.push(error); + return null; + } + /** + * Implements the instructions for completeValue as defined in the + * "Value Completion" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by executing all sub-selections. + */ + + function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + if ((0, _definition.isNonNullType)(returnType)) { + const completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + if (completed === null) { + throw new Error(`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`); + } + return completed; + } // If result value is null or undefined then return null. + + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type + + if ((0, _definition.isListType)(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } + /* c8 ignore next 6 */ + // Not reachable, all possible output types have been considered. + + false || (0, _invariant.invariant)(false, 'Cannot complete value of unexpected output type: ' + (0, _inspect.inspect)(returnType)); + } + /** + * Complete a list value by completing each item in the list with the + * inner type + */ + + function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + if (!(0, _isIterableObject.isIterableObject)(result)) { + throw new _GraphQLError.GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`); + } // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = Array.from(result, (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const itemPath = (0, _Path.addPath)(path, index, undefined); + try { + let completedItem; + if ((0, _isPromise.isPromise)(item)) { + completedItem = item.then(resolved => completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved)); + } else { + completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item); + } + if ((0, _isPromise.isPromise)(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + + return completedItem.then(undefined, rawError => { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); + return handleFieldError(error, itemType, exeContext); + }); + } + return completedItem; + } catch (rawError) { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); + return handleFieldError(error, itemType, exeContext); + } + }); + return containsPromise ? Promise.all(completedResults) : completedResults; + } + /** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + function completeLeafValue(returnType, result) { + const serializedResult = returnType.serialize(result); + if (serializedResult == null) { + throw new Error(`Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, _inspect.inspect)(result)})\` to ` + `return non-nullable value, returned: ${(0, _inspect.inspect)(serializedResult)}`); + } + return serializedResult; + } + /** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var _returnType$resolveTy; + const resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver; + const contextValue = exeContext.contextValue; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); + if ((0, _isPromise.isPromise)(runtimeType)) { + return runtimeType.then(resolvedRuntimeType => completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result)); + } + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + } + function ensureValidRuntimeType(runtimeTypeName, exeContext, returnType, fieldNodes, info, result) { + if (runtimeTypeName == null) { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, fieldNodes); + } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` + // TODO: remove in 17.0.0 release + + if ((0, _definition.isObjectType)(runtimeTypeName)) { + throw new _GraphQLError.GraphQLError('Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.'); + } + if (typeof runtimeTypeName !== 'string') { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + `value ${(0, _inspect.inspect)(result)}, received "${(0, _inspect.inspect)(runtimeTypeName)}".`); + } + const runtimeType = exeContext.schema.getType(runtimeTypeName); + if (runtimeType == null) { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, { + nodes: fieldNodes + }); + } + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, { + nodes: fieldNodes + }); + } + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError(`Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, { + nodes: fieldNodes + }); + } + return runtimeType; + } + /** + * Complete an Object value by executing all sub-selections. + */ + + function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + if ((0, _isPromise.isPromise)(isTypeOf)) { + return isTypeOf.then(resolvedIsTypeOf => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + return executeFields(exeContext, returnType, result, path, subFieldNodes); + }); + } + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + return executeFields(exeContext, returnType, result, path, subFieldNodes); + } + function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError(`Expected value of type "${returnType.name}" but got: ${(0, _inspect.inspect)(result)}.`, { + nodes: fieldNodes + }); + } + /** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + const defaultTypeResolver = function (value, contextValue, info, abstractType) { + // First, look for `__typename`. + if ((0, _isObjectLike.isObjectLike)(value) && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + if ((0, _isPromise.isPromise)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type.name; + } + } + } + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; + } + } + }); + } + }; + /** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + exports.defaultTypeResolver = defaultTypeResolver; + const defaultFieldResolver = function (source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { + const property = source[info.fieldName]; + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + return property; + } + }; + /** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ + exports.defaultFieldResolver = defaultFieldResolver; + function getFieldDef(schema, parentType, fieldNode) { + const fieldName = fieldNode.name.value; + if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; + } + return parentType.getFields()[fieldName]; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/execution/index.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/execution/index.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "createSourceEventStream", ({ + enumerable: true, + get: function () { + return _subscribe.createSourceEventStream; + } + })); + Object.defineProperty(exports, "defaultFieldResolver", ({ + enumerable: true, + get: function () { + return _execute.defaultFieldResolver; + } + })); + Object.defineProperty(exports, "defaultTypeResolver", ({ + enumerable: true, + get: function () { + return _execute.defaultTypeResolver; + } + })); + Object.defineProperty(exports, "execute", ({ + enumerable: true, + get: function () { + return _execute.execute; + } + })); + Object.defineProperty(exports, "executeSync", ({ + enumerable: true, + get: function () { + return _execute.executeSync; + } + })); + Object.defineProperty(exports, "getArgumentValues", ({ + enumerable: true, + get: function () { + return _values.getArgumentValues; + } + })); + Object.defineProperty(exports, "getDirectiveValues", ({ + enumerable: true, + get: function () { + return _values.getDirectiveValues; + } + })); + Object.defineProperty(exports, "getVariableValues", ({ + enumerable: true, + get: function () { + return _values.getVariableValues; + } + })); + Object.defineProperty(exports, "responsePathAsArray", ({ + enumerable: true, + get: function () { + return _Path.pathToArray; + } + })); + Object.defineProperty(exports, "subscribe", ({ + enumerable: true, + get: function () { + return _subscribe.subscribe; + } + })); + var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); + var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); + var _subscribe = __webpack_require__(/*! ./subscribe.mjs */ "../../../node_modules/graphql/execution/subscribe.mjs"); + var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs": + /*!********************************************************************!*\ + !*** ../../../node_modules/graphql/execution/mapAsyncIterator.mjs ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.mapAsyncIterator = mapAsyncIterator; + /** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ + function mapAsyncIterator(iterable, callback) { + const iterator = iterable[Symbol.asyncIterator](); + async function mapResult(result) { + if (result.done) { + return result; + } + try { + return { + value: await callback(result.value), + done: false + }; + } catch (error) { + /* c8 ignore start */ + // FIXME: add test case + if (typeof iterator.return === 'function') { + try { + await iterator.return(); + } catch (_e) { + /* ignore error */ + } + } + throw error; + /* c8 ignore stop */ + } + } + return { + async next() { + return mapResult(await iterator.next()); + }, + async return() { + // If iterator.return() does not exist, then type R must be undefined. + return typeof iterator.return === 'function' ? mapResult(await iterator.return()) : { + value: undefined, + done: true + }; + }, + async throw(error) { + if (typeof iterator.throw === 'function') { + return mapResult(await iterator.throw(error)); + } + throw error; + }, + [Symbol.asyncIterator]() { + return this; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/execution/subscribe.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/execution/subscribe.mjs ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createSourceEventStream = createSourceEventStream; + exports.subscribe = subscribe; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _isAsyncIterable = __webpack_require__(/*! ../jsutils/isAsyncIterable.mjs */ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs"); + var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); + var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); + var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); + var _mapAsyncIterator = __webpack_require__(/*! ./mapAsyncIterator.mjs */ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs"); + var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + /** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ + + async function subscribe(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); + const resultOrStream = await createSourceEventStream(args); + if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { + return resultOrStream; + } // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + const mapSourceToResponse = payload => (0, _execute.execute)({ + ...args, + rootValue: payload + }); // Map every source value to a ExecutionResult value as described above. + + return (0, _mapAsyncIterator.mapAsyncIterator)(resultOrStream, mapSourceToResponse); + } + function toNormalizedArgs(args) { + const firstArg = args[0]; + if (firstArg && 'document' in firstArg) { + return firstArg; + } + return { + schema: firstArg, + // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 + document: args[1], + rootValue: args[2], + contextValue: args[3], + variableValues: args[4], + operationName: args[5], + subscribeFieldResolver: args[6] + }; + } + /** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise which resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + async function createSourceEventStream(...rawArgs) { + const args = toNormalizedArgs(rawArgs); + const { + schema, + document, + variableValues + } = args; // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { + return { + errors: exeContext + }; + } + try { + const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. + + if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { + throw new Error('Subscription field must return Async Iterable. ' + `Received: ${(0, _inspect.inspect)(eventStream)}.`); + } + return eventStream; + } catch (error) { + // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. + // Otherwise treat the error as a system-class error and re-throw it. + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error] + }; + } + throw error; + } + } + async function executeSubscription(exeContext) { + const { + schema, + fragments, + operation, + variableValues, + rootValue + } = exeContext; + const rootType = schema.getSubscriptionType(); + if (rootType == null) { + throw new _GraphQLError.GraphQLError('Schema is not configured to execute subscription operation.', { + nodes: operation + }); + } + const rootFields = (0, _collectFields.collectFields)(schema, fragments, variableValues, rootType, operation.selectionSet); + const [responseName, fieldNodes] = [...rootFields.entries()][0]; + const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); + if (!fieldDef) { + const fieldName = fieldNodes[0].name.value; + throw new _GraphQLError.GraphQLError(`The subscription field "${fieldName}" is not defined.`, { + nodes: fieldNodes + }); + } + const path = (0, _Path.addPath)(undefined, responseName, rootType.name); + const info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, rootType, path); + try { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + const resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.subscribeFieldResolver; + const eventStream = await resolveFn(rootValue, args, contextValue, info); + if (eventStream instanceof Error) { + throw eventStream; + } + return eventStream; + } catch (error) { + throw (0, _locatedError.locatedError)(error, fieldNodes, (0, _Path.pathToArray)(path)); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/execution/values.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/execution/values.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getArgumentValues = getArgumentValues; + exports.getDirectiveValues = getDirectiveValues; + exports.getVariableValues = getVariableValues; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _coerceInputValue = __webpack_require__(/*! ../utilities/coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); + var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + var _valueFromAST = __webpack_require__(/*! ../utilities/valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); + /** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors; + try { + const coerced = coerceVariableValues(schema, varDefNodes, inputs, error => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new _GraphQLError.GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.'); + } + errors.push(error); + }); + if (errors.length === 0) { + return { + coerced + }; + } + } catch (error) { + errors.push(error); + } + return { + errors + }; + } + function coerceVariableValues(schema, varDefNodes, inputs, onError) { + const coercedValues = {}; + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = (0, _printer.print)(varDefNode.type); + onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, { + nodes: varDefNode.type + })); + continue; + } + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); + } else if ((0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, { + nodes: varDefNode + })); + } + continue; + } + const value = inputs[varName]; + if (value === null && (0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, { + nodes: varDefNode + })); + continue; + } + coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)(value, varType, (path, invalidValue, error) => { + let prefix = `Variable "$${varName}" got invalid value ` + (0, _inspect.inspect)(invalidValue); + if (path.length > 0) { + prefix += ` at "${varName}${(0, _printPathArray.printPathArray)(path)}"`; + } + onError(new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { + nodes: varDefNode, + originalError: error + })); + }); + } + return coercedValues; + } + /** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + function getArgumentValues(def, node, variableValues) { + var _node$arguments; + const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : []; + const argNodeMap = (0, _keyMap.keyMap)(argumentNodes, arg => arg.name.value); + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + 'was not provided.', { + nodes: node + }); + } + continue; + } + const valueNode = argumentNode.value; + let isNull = valueNode.kind === _kinds.Kind.NULL; + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (variableValues == null || !hasOwnProperty(variableValues, variableName)) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + `was provided the variable "$${variableName}" which was not provided a runtime value.`, { + nodes: valueNode + }); + } + continue; + } + isNull = variableValues[variableName] == null; + } + if (isNull && (0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError(`Argument "${name}" of non-null type "${(0, _inspect.inspect)(argType)}" ` + 'must not be null.', { + nodes: valueNode + }); + } + const coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError(`Argument "${name}" has invalid value ${(0, _printer.print)(valueNode)}.`, { + nodes: valueNode + }); + } + coercedValues[name] = coercedValue; + } + return coercedValues; + } + /** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + function getDirectiveValues(directiveDef, node, variableValues) { + var _node$directives; + const directiveNode = (_node$directives = node.directives) === null || _node$directives === void 0 ? void 0 : _node$directives.find(directive => directive.name.value === directiveDef.name); + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/graphql.mjs": + /*!*************************************************!*\ + !*** ../../../node_modules/graphql/graphql.mjs ***! + \*************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.graphql = graphql; + exports.graphqlSync = graphqlSync; + var _devAssert = __webpack_require__(/*! ./jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _isPromise = __webpack_require__(/*! ./jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); + var _parser = __webpack_require__(/*! ./language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); + var _validate = __webpack_require__(/*! ./type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); + var _validate2 = __webpack_require__(/*! ./validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); + var _execute = __webpack_require__(/*! ./execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); + /** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + * typeResolver: + * A type resolver function to use when none is provided by the schema. + * If not provided, the default type resolver is used (which looks for a + * `__typename` field or alternatively calls the `isTypeOf` method). + */ + + function graphql(args) { + // Always return a Promise for a consistent API. + return new Promise(resolve => resolve(graphqlImpl(args))); + } + /** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + function graphqlSync(args) { + const result = graphqlImpl(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + return result; + } + function graphqlImpl(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver + } = args; // Validate Schema + + const schemaValidationErrors = (0, _validate.validateSchema)(schema); + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + let document; + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + const validationErrors = (0, _validate2.validate)(schema, document); + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + return (0, _execute.execute)({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver + }); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/index.mjs": + /*!***********************************************!*\ + !*** ../../../node_modules/graphql/index.mjs ***! + \***********************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "BREAK", ({ + enumerable: true, + get: function () { + return _index2.BREAK; + } + })); + Object.defineProperty(exports, "BreakingChangeType", ({ + enumerable: true, + get: function () { + return _index6.BreakingChangeType; + } + })); + Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ + enumerable: true, + get: function () { + return _index.DEFAULT_DEPRECATION_REASON; + } + })); + Object.defineProperty(exports, "DangerousChangeType", ({ + enumerable: true, + get: function () { + return _index6.DangerousChangeType; + } + })); + Object.defineProperty(exports, "DirectiveLocation", ({ + enumerable: true, + get: function () { + return _index2.DirectiveLocation; + } + })); + Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ + enumerable: true, + get: function () { + return _index4.ExecutableDefinitionsRule; + } + })); + Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _index4.FieldsOnCorrectTypeRule; + } + })); + Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ + enumerable: true, + get: function () { + return _index4.FragmentsOnCompositeTypesRule; + } + })); + Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ + enumerable: true, + get: function () { + return _index.GRAPHQL_MAX_INT; + } + })); + Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ + enumerable: true, + get: function () { + return _index.GRAPHQL_MIN_INT; + } + })); + Object.defineProperty(exports, "GraphQLBoolean", ({ + enumerable: true, + get: function () { + return _index.GraphQLBoolean; + } + })); + Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLDeprecatedDirective; + } + })); + Object.defineProperty(exports, "GraphQLDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLDirective; + } + })); + Object.defineProperty(exports, "GraphQLEnumType", ({ + enumerable: true, + get: function () { + return _index.GraphQLEnumType; + } + })); + Object.defineProperty(exports, "GraphQLError", ({ + enumerable: true, + get: function () { + return _index5.GraphQLError; + } + })); + Object.defineProperty(exports, "GraphQLFloat", ({ + enumerable: true, + get: function () { + return _index.GraphQLFloat; + } + })); + Object.defineProperty(exports, "GraphQLID", ({ + enumerable: true, + get: function () { + return _index.GraphQLID; + } + })); + Object.defineProperty(exports, "GraphQLIncludeDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLIncludeDirective; + } + })); + Object.defineProperty(exports, "GraphQLInputObjectType", ({ + enumerable: true, + get: function () { + return _index.GraphQLInputObjectType; + } + })); + Object.defineProperty(exports, "GraphQLInt", ({ + enumerable: true, + get: function () { + return _index.GraphQLInt; + } + })); + Object.defineProperty(exports, "GraphQLInterfaceType", ({ + enumerable: true, + get: function () { + return _index.GraphQLInterfaceType; + } + })); + Object.defineProperty(exports, "GraphQLList", ({ + enumerable: true, + get: function () { + return _index.GraphQLList; + } + })); + Object.defineProperty(exports, "GraphQLNonNull", ({ + enumerable: true, + get: function () { + return _index.GraphQLNonNull; + } + })); + Object.defineProperty(exports, "GraphQLObjectType", ({ + enumerable: true, + get: function () { + return _index.GraphQLObjectType; + } + })); + Object.defineProperty(exports, "GraphQLScalarType", ({ + enumerable: true, + get: function () { + return _index.GraphQLScalarType; + } + })); + Object.defineProperty(exports, "GraphQLSchema", ({ + enumerable: true, + get: function () { + return _index.GraphQLSchema; + } + })); + Object.defineProperty(exports, "GraphQLSkipDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLSkipDirective; + } + })); + Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLSpecifiedByDirective; + } + })); + Object.defineProperty(exports, "GraphQLString", ({ + enumerable: true, + get: function () { + return _index.GraphQLString; + } + })); + Object.defineProperty(exports, "GraphQLUnionType", ({ + enumerable: true, + get: function () { + return _index.GraphQLUnionType; + } + })); + Object.defineProperty(exports, "Kind", ({ + enumerable: true, + get: function () { + return _index2.Kind; + } + })); + Object.defineProperty(exports, "KnownArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownArgumentNamesRule; + } + })); + Object.defineProperty(exports, "KnownDirectivesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownDirectivesRule; + } + })); + Object.defineProperty(exports, "KnownFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownFragmentNamesRule; + } + })); + Object.defineProperty(exports, "KnownTypeNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownTypeNamesRule; + } + })); + Object.defineProperty(exports, "Lexer", ({ + enumerable: true, + get: function () { + return _index2.Lexer; + } + })); + Object.defineProperty(exports, "Location", ({ + enumerable: true, + get: function () { + return _index2.Location; + } + })); + Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ + enumerable: true, + get: function () { + return _index4.LoneAnonymousOperationRule; + } + })); + Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ + enumerable: true, + get: function () { + return _index4.LoneSchemaDefinitionRule; + } + })); + Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ + enumerable: true, + get: function () { + return _index4.NoDeprecatedCustomRule; + } + })); + Object.defineProperty(exports, "NoFragmentCyclesRule", ({ + enumerable: true, + get: function () { + return _index4.NoFragmentCyclesRule; + } + })); + Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ + enumerable: true, + get: function () { + return _index4.NoSchemaIntrospectionCustomRule; + } + })); + Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ + enumerable: true, + get: function () { + return _index4.NoUndefinedVariablesRule; + } + })); + Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ + enumerable: true, + get: function () { + return _index4.NoUnusedFragmentsRule; + } + })); + Object.defineProperty(exports, "NoUnusedVariablesRule", ({ + enumerable: true, + get: function () { + return _index4.NoUnusedVariablesRule; + } + })); + Object.defineProperty(exports, "OperationTypeNode", ({ + enumerable: true, + get: function () { + return _index2.OperationTypeNode; + } + })); + Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ + enumerable: true, + get: function () { + return _index4.OverlappingFieldsCanBeMergedRule; + } + })); + Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ + enumerable: true, + get: function () { + return _index4.PossibleFragmentSpreadsRule; + } + })); + Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ + enumerable: true, + get: function () { + return _index4.PossibleTypeExtensionsRule; + } + })); + Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ + enumerable: true, + get: function () { + return _index4.ProvidedRequiredArgumentsRule; + } + })); + Object.defineProperty(exports, "ScalarLeafsRule", ({ + enumerable: true, + get: function () { + return _index4.ScalarLeafsRule; + } + })); + Object.defineProperty(exports, "SchemaMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.SchemaMetaFieldDef; + } + })); + Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ + enumerable: true, + get: function () { + return _index4.SingleFieldSubscriptionsRule; + } + })); + Object.defineProperty(exports, "Source", ({ + enumerable: true, + get: function () { + return _index2.Source; + } + })); + Object.defineProperty(exports, "Token", ({ + enumerable: true, + get: function () { + return _index2.Token; + } + })); + Object.defineProperty(exports, "TokenKind", ({ + enumerable: true, + get: function () { + return _index2.TokenKind; + } + })); + Object.defineProperty(exports, "TypeInfo", ({ + enumerable: true, + get: function () { + return _index6.TypeInfo; + } + })); + Object.defineProperty(exports, "TypeKind", ({ + enumerable: true, + get: function () { + return _index.TypeKind; + } + })); + Object.defineProperty(exports, "TypeMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.TypeMetaFieldDef; + } + })); + Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.TypeNameMetaFieldDef; + } + })); + Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueArgumentDefinitionNamesRule; + } + })); + Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueArgumentNamesRule; + } + })); + Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueDirectiveNamesRule; + } + })); + Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueDirectivesPerLocationRule; + } + })); + Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueEnumValueNamesRule; + } + })); + Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueFieldDefinitionNamesRule; + } + })); + Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueFragmentNamesRule; + } + })); + Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueInputFieldNamesRule; + } + })); + Object.defineProperty(exports, "UniqueOperationNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueOperationNamesRule; + } + })); + Object.defineProperty(exports, "UniqueOperationTypesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueOperationTypesRule; + } + })); + Object.defineProperty(exports, "UniqueTypeNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueTypeNamesRule; + } + })); + Object.defineProperty(exports, "UniqueVariableNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueVariableNamesRule; + } + })); + Object.defineProperty(exports, "ValidationContext", ({ + enumerable: true, + get: function () { + return _index4.ValidationContext; + } + })); + Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _index4.ValuesOfCorrectTypeRule; + } + })); + Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ + enumerable: true, + get: function () { + return _index4.VariablesAreInputTypesRule; + } + })); + Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ + enumerable: true, + get: function () { + return _index4.VariablesInAllowedPositionRule; + } + })); + Object.defineProperty(exports, "__Directive", ({ + enumerable: true, + get: function () { + return _index.__Directive; + } + })); + Object.defineProperty(exports, "__DirectiveLocation", ({ + enumerable: true, + get: function () { + return _index.__DirectiveLocation; + } + })); + Object.defineProperty(exports, "__EnumValue", ({ + enumerable: true, + get: function () { + return _index.__EnumValue; + } + })); + Object.defineProperty(exports, "__Field", ({ + enumerable: true, + get: function () { + return _index.__Field; + } + })); + Object.defineProperty(exports, "__InputValue", ({ + enumerable: true, + get: function () { + return _index.__InputValue; + } + })); + Object.defineProperty(exports, "__Schema", ({ + enumerable: true, + get: function () { + return _index.__Schema; + } + })); + Object.defineProperty(exports, "__Type", ({ + enumerable: true, + get: function () { + return _index.__Type; + } + })); + Object.defineProperty(exports, "__TypeKind", ({ + enumerable: true, + get: function () { + return _index.__TypeKind; + } + })); + Object.defineProperty(exports, "assertAbstractType", ({ + enumerable: true, + get: function () { + return _index.assertAbstractType; + } + })); + Object.defineProperty(exports, "assertCompositeType", ({ + enumerable: true, + get: function () { + return _index.assertCompositeType; + } + })); + Object.defineProperty(exports, "assertDirective", ({ + enumerable: true, + get: function () { + return _index.assertDirective; + } + })); + Object.defineProperty(exports, "assertEnumType", ({ + enumerable: true, + get: function () { + return _index.assertEnumType; + } + })); + Object.defineProperty(exports, "assertEnumValueName", ({ + enumerable: true, + get: function () { + return _index.assertEnumValueName; + } + })); + Object.defineProperty(exports, "assertInputObjectType", ({ + enumerable: true, + get: function () { + return _index.assertInputObjectType; + } + })); + Object.defineProperty(exports, "assertInputType", ({ + enumerable: true, + get: function () { + return _index.assertInputType; + } + })); + Object.defineProperty(exports, "assertInterfaceType", ({ + enumerable: true, + get: function () { + return _index.assertInterfaceType; + } + })); + Object.defineProperty(exports, "assertLeafType", ({ + enumerable: true, + get: function () { + return _index.assertLeafType; + } + })); + Object.defineProperty(exports, "assertListType", ({ + enumerable: true, + get: function () { + return _index.assertListType; + } + })); + Object.defineProperty(exports, "assertName", ({ + enumerable: true, + get: function () { + return _index.assertName; + } + })); + Object.defineProperty(exports, "assertNamedType", ({ + enumerable: true, + get: function () { + return _index.assertNamedType; + } + })); + Object.defineProperty(exports, "assertNonNullType", ({ + enumerable: true, + get: function () { + return _index.assertNonNullType; + } + })); + Object.defineProperty(exports, "assertNullableType", ({ + enumerable: true, + get: function () { + return _index.assertNullableType; + } + })); + Object.defineProperty(exports, "assertObjectType", ({ + enumerable: true, + get: function () { + return _index.assertObjectType; + } + })); + Object.defineProperty(exports, "assertOutputType", ({ + enumerable: true, + get: function () { + return _index.assertOutputType; + } + })); + Object.defineProperty(exports, "assertScalarType", ({ + enumerable: true, + get: function () { + return _index.assertScalarType; + } + })); + Object.defineProperty(exports, "assertSchema", ({ + enumerable: true, + get: function () { + return _index.assertSchema; + } + })); + Object.defineProperty(exports, "assertType", ({ + enumerable: true, + get: function () { + return _index.assertType; + } + })); + Object.defineProperty(exports, "assertUnionType", ({ + enumerable: true, + get: function () { + return _index.assertUnionType; + } + })); + Object.defineProperty(exports, "assertValidName", ({ + enumerable: true, + get: function () { + return _index6.assertValidName; + } + })); + Object.defineProperty(exports, "assertValidSchema", ({ + enumerable: true, + get: function () { + return _index.assertValidSchema; + } + })); + Object.defineProperty(exports, "assertWrappingType", ({ + enumerable: true, + get: function () { + return _index.assertWrappingType; + } + })); + Object.defineProperty(exports, "astFromValue", ({ + enumerable: true, + get: function () { + return _index6.astFromValue; + } + })); + Object.defineProperty(exports, "buildASTSchema", ({ + enumerable: true, + get: function () { + return _index6.buildASTSchema; + } + })); + Object.defineProperty(exports, "buildClientSchema", ({ + enumerable: true, + get: function () { + return _index6.buildClientSchema; + } + })); + Object.defineProperty(exports, "buildSchema", ({ + enumerable: true, + get: function () { + return _index6.buildSchema; + } + })); + Object.defineProperty(exports, "coerceInputValue", ({ + enumerable: true, + get: function () { + return _index6.coerceInputValue; + } + })); + Object.defineProperty(exports, "concatAST", ({ + enumerable: true, + get: function () { + return _index6.concatAST; + } + })); + Object.defineProperty(exports, "createSourceEventStream", ({ + enumerable: true, + get: function () { + return _index3.createSourceEventStream; + } + })); + Object.defineProperty(exports, "defaultFieldResolver", ({ + enumerable: true, + get: function () { + return _index3.defaultFieldResolver; + } + })); + Object.defineProperty(exports, "defaultTypeResolver", ({ + enumerable: true, + get: function () { + return _index3.defaultTypeResolver; + } + })); + Object.defineProperty(exports, "doTypesOverlap", ({ + enumerable: true, + get: function () { + return _index6.doTypesOverlap; + } + })); + Object.defineProperty(exports, "execute", ({ + enumerable: true, + get: function () { + return _index3.execute; + } + })); + Object.defineProperty(exports, "executeSync", ({ + enumerable: true, + get: function () { + return _index3.executeSync; + } + })); + Object.defineProperty(exports, "extendSchema", ({ + enumerable: true, + get: function () { + return _index6.extendSchema; + } + })); + Object.defineProperty(exports, "findBreakingChanges", ({ + enumerable: true, + get: function () { + return _index6.findBreakingChanges; + } + })); + Object.defineProperty(exports, "findDangerousChanges", ({ + enumerable: true, + get: function () { + return _index6.findDangerousChanges; + } + })); + Object.defineProperty(exports, "formatError", ({ + enumerable: true, + get: function () { + return _index5.formatError; + } + })); + Object.defineProperty(exports, "getArgumentValues", ({ + enumerable: true, + get: function () { + return _index3.getArgumentValues; + } + })); + Object.defineProperty(exports, "getDirectiveValues", ({ + enumerable: true, + get: function () { + return _index3.getDirectiveValues; + } + })); + Object.defineProperty(exports, "getEnterLeaveForKind", ({ + enumerable: true, + get: function () { + return _index2.getEnterLeaveForKind; + } + })); + Object.defineProperty(exports, "getIntrospectionQuery", ({ + enumerable: true, + get: function () { + return _index6.getIntrospectionQuery; + } + })); + Object.defineProperty(exports, "getLocation", ({ + enumerable: true, + get: function () { + return _index2.getLocation; + } + })); + Object.defineProperty(exports, "getNamedType", ({ + enumerable: true, + get: function () { + return _index.getNamedType; + } + })); + Object.defineProperty(exports, "getNullableType", ({ + enumerable: true, + get: function () { + return _index.getNullableType; + } + })); + Object.defineProperty(exports, "getOperationAST", ({ + enumerable: true, + get: function () { + return _index6.getOperationAST; + } + })); + Object.defineProperty(exports, "getOperationRootType", ({ + enumerable: true, + get: function () { + return _index6.getOperationRootType; + } + })); + Object.defineProperty(exports, "getVariableValues", ({ + enumerable: true, + get: function () { + return _index3.getVariableValues; + } + })); + Object.defineProperty(exports, "getVisitFn", ({ + enumerable: true, + get: function () { + return _index2.getVisitFn; + } + })); + Object.defineProperty(exports, "graphql", ({ + enumerable: true, + get: function () { + return _graphql.graphql; + } + })); + Object.defineProperty(exports, "graphqlSync", ({ + enumerable: true, + get: function () { + return _graphql.graphqlSync; + } + })); + Object.defineProperty(exports, "introspectionFromSchema", ({ + enumerable: true, + get: function () { + return _index6.introspectionFromSchema; + } + })); + Object.defineProperty(exports, "introspectionTypes", ({ + enumerable: true, + get: function () { + return _index.introspectionTypes; + } + })); + Object.defineProperty(exports, "isAbstractType", ({ + enumerable: true, + get: function () { + return _index.isAbstractType; + } + })); + Object.defineProperty(exports, "isCompositeType", ({ + enumerable: true, + get: function () { + return _index.isCompositeType; + } + })); + Object.defineProperty(exports, "isConstValueNode", ({ + enumerable: true, + get: function () { + return _index2.isConstValueNode; + } + })); + Object.defineProperty(exports, "isDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isDefinitionNode; + } + })); + Object.defineProperty(exports, "isDirective", ({ + enumerable: true, + get: function () { + return _index.isDirective; + } + })); + Object.defineProperty(exports, "isEnumType", ({ + enumerable: true, + get: function () { + return _index.isEnumType; + } + })); + Object.defineProperty(exports, "isEqualType", ({ + enumerable: true, + get: function () { + return _index6.isEqualType; + } + })); + Object.defineProperty(exports, "isExecutableDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isExecutableDefinitionNode; + } + })); + Object.defineProperty(exports, "isInputObjectType", ({ + enumerable: true, + get: function () { + return _index.isInputObjectType; + } + })); + Object.defineProperty(exports, "isInputType", ({ + enumerable: true, + get: function () { + return _index.isInputType; + } + })); + Object.defineProperty(exports, "isInterfaceType", ({ + enumerable: true, + get: function () { + return _index.isInterfaceType; + } + })); + Object.defineProperty(exports, "isIntrospectionType", ({ + enumerable: true, + get: function () { + return _index.isIntrospectionType; + } + })); + Object.defineProperty(exports, "isLeafType", ({ + enumerable: true, + get: function () { + return _index.isLeafType; + } + })); + Object.defineProperty(exports, "isListType", ({ + enumerable: true, + get: function () { + return _index.isListType; + } + })); + Object.defineProperty(exports, "isNamedType", ({ + enumerable: true, + get: function () { + return _index.isNamedType; + } + })); + Object.defineProperty(exports, "isNonNullType", ({ + enumerable: true, + get: function () { + return _index.isNonNullType; + } + })); + Object.defineProperty(exports, "isNullableType", ({ + enumerable: true, + get: function () { + return _index.isNullableType; + } + })); + Object.defineProperty(exports, "isObjectType", ({ + enumerable: true, + get: function () { + return _index.isObjectType; + } + })); + Object.defineProperty(exports, "isOutputType", ({ + enumerable: true, + get: function () { + return _index.isOutputType; + } + })); + Object.defineProperty(exports, "isRequiredArgument", ({ + enumerable: true, + get: function () { + return _index.isRequiredArgument; + } + })); + Object.defineProperty(exports, "isRequiredInputField", ({ + enumerable: true, + get: function () { + return _index.isRequiredInputField; + } + })); + Object.defineProperty(exports, "isScalarType", ({ + enumerable: true, + get: function () { + return _index.isScalarType; + } + })); + Object.defineProperty(exports, "isSchema", ({ + enumerable: true, + get: function () { + return _index.isSchema; + } + })); + Object.defineProperty(exports, "isSelectionNode", ({ + enumerable: true, + get: function () { + return _index2.isSelectionNode; + } + })); + Object.defineProperty(exports, "isSpecifiedDirective", ({ + enumerable: true, + get: function () { + return _index.isSpecifiedDirective; + } + })); + Object.defineProperty(exports, "isSpecifiedScalarType", ({ + enumerable: true, + get: function () { + return _index.isSpecifiedScalarType; + } + })); + Object.defineProperty(exports, "isType", ({ + enumerable: true, + get: function () { + return _index.isType; + } + })); + Object.defineProperty(exports, "isTypeDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeDefinitionNode; + } + })); + Object.defineProperty(exports, "isTypeExtensionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeExtensionNode; + } + })); + Object.defineProperty(exports, "isTypeNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeNode; + } + })); + Object.defineProperty(exports, "isTypeSubTypeOf", ({ + enumerable: true, + get: function () { + return _index6.isTypeSubTypeOf; + } + })); + Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeSystemDefinitionNode; + } + })); + Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeSystemExtensionNode; + } + })); + Object.defineProperty(exports, "isUnionType", ({ + enumerable: true, + get: function () { + return _index.isUnionType; + } + })); + Object.defineProperty(exports, "isValidNameError", ({ + enumerable: true, + get: function () { + return _index6.isValidNameError; + } + })); + Object.defineProperty(exports, "isValueNode", ({ + enumerable: true, + get: function () { + return _index2.isValueNode; + } + })); + Object.defineProperty(exports, "isWrappingType", ({ + enumerable: true, + get: function () { + return _index.isWrappingType; + } + })); + Object.defineProperty(exports, "lexicographicSortSchema", ({ + enumerable: true, + get: function () { + return _index6.lexicographicSortSchema; + } + })); + Object.defineProperty(exports, "locatedError", ({ + enumerable: true, + get: function () { + return _index5.locatedError; + } + })); + Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _index2.parse; + } + })); + Object.defineProperty(exports, "parseConstValue", ({ + enumerable: true, + get: function () { + return _index2.parseConstValue; + } + })); + Object.defineProperty(exports, "parseType", ({ + enumerable: true, + get: function () { + return _index2.parseType; + } + })); + Object.defineProperty(exports, "parseValue", ({ + enumerable: true, + get: function () { + return _index2.parseValue; + } + })); + Object.defineProperty(exports, "print", ({ + enumerable: true, + get: function () { + return _index2.print; + } + })); + Object.defineProperty(exports, "printError", ({ + enumerable: true, + get: function () { + return _index5.printError; + } + })); + Object.defineProperty(exports, "printIntrospectionSchema", ({ + enumerable: true, + get: function () { + return _index6.printIntrospectionSchema; + } + })); + Object.defineProperty(exports, "printLocation", ({ + enumerable: true, + get: function () { + return _index2.printLocation; + } + })); + Object.defineProperty(exports, "printSchema", ({ + enumerable: true, + get: function () { + return _index6.printSchema; + } + })); + Object.defineProperty(exports, "printSourceLocation", ({ + enumerable: true, + get: function () { + return _index2.printSourceLocation; + } + })); + Object.defineProperty(exports, "printType", ({ + enumerable: true, + get: function () { + return _index6.printType; + } + })); + Object.defineProperty(exports, "resolveObjMapThunk", ({ + enumerable: true, + get: function () { + return _index.resolveObjMapThunk; + } + })); + Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ + enumerable: true, + get: function () { + return _index.resolveReadonlyArrayThunk; + } + })); + Object.defineProperty(exports, "responsePathAsArray", ({ + enumerable: true, + get: function () { + return _index3.responsePathAsArray; + } + })); + Object.defineProperty(exports, "separateOperations", ({ + enumerable: true, + get: function () { + return _index6.separateOperations; + } + })); + Object.defineProperty(exports, "specifiedDirectives", ({ + enumerable: true, + get: function () { + return _index.specifiedDirectives; + } + })); + Object.defineProperty(exports, "specifiedRules", ({ + enumerable: true, + get: function () { + return _index4.specifiedRules; + } + })); + Object.defineProperty(exports, "specifiedScalarTypes", ({ + enumerable: true, + get: function () { + return _index.specifiedScalarTypes; + } + })); + Object.defineProperty(exports, "stripIgnoredCharacters", ({ + enumerable: true, + get: function () { + return _index6.stripIgnoredCharacters; + } + })); + Object.defineProperty(exports, "subscribe", ({ + enumerable: true, + get: function () { + return _index3.subscribe; + } + })); + Object.defineProperty(exports, "syntaxError", ({ + enumerable: true, + get: function () { + return _index5.syntaxError; + } + })); + Object.defineProperty(exports, "typeFromAST", ({ + enumerable: true, + get: function () { + return _index6.typeFromAST; + } + })); + Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _index4.validate; + } + })); + Object.defineProperty(exports, "validateSchema", ({ + enumerable: true, + get: function () { + return _index.validateSchema; + } + })); + Object.defineProperty(exports, "valueFromAST", ({ + enumerable: true, + get: function () { + return _index6.valueFromAST; + } + })); + Object.defineProperty(exports, "valueFromASTUntyped", ({ + enumerable: true, + get: function () { + return _index6.valueFromASTUntyped; + } + })); + Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.version; + } + })); + Object.defineProperty(exports, "versionInfo", ({ + enumerable: true, + get: function () { + return _version.versionInfo; + } + })); + Object.defineProperty(exports, "visit", ({ + enumerable: true, + get: function () { + return _index2.visit; + } + })); + Object.defineProperty(exports, "visitInParallel", ({ + enumerable: true, + get: function () { + return _index2.visitInParallel; + } + })); + Object.defineProperty(exports, "visitWithTypeInfo", ({ + enumerable: true, + get: function () { + return _index6.visitWithTypeInfo; + } + })); + var _version = __webpack_require__(/*! ./version.mjs */ "../../../node_modules/graphql/version.mjs"); + var _graphql = __webpack_require__(/*! ./graphql.mjs */ "../../../node_modules/graphql/graphql.mjs"); + var _index = __webpack_require__(/*! ./type/index.mjs */ "../../../node_modules/graphql/type/index.mjs"); + var _index2 = __webpack_require__(/*! ./language/index.mjs */ "../../../node_modules/graphql/language/index.mjs"); + var _index3 = __webpack_require__(/*! ./execution/index.mjs */ "../../../node_modules/graphql/execution/index.mjs"); + var _index4 = __webpack_require__(/*! ./validation/index.mjs */ "../../../node_modules/graphql/validation/index.mjs"); + var _index5 = __webpack_require__(/*! ./error/index.mjs */ "../../../node_modules/graphql/error/index.mjs"); + var _index6 = __webpack_require__(/*! ./utilities/index.mjs */ "../../../node_modules/graphql/utilities/index.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/Path.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/Path.mjs ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.addPath = addPath; + exports.pathToArray = pathToArray; + /** + * Given a Path and a key, return a new Path containing the new key. + */ + function addPath(prev, key, typename) { + return { + prev, + key, + typename + }; + } + /** + * Given a Path, return an Array of the path keys. + */ + + function pathToArray(path) { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + return flattened.reverse(); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/devAssert.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/devAssert.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.devAssert = devAssert; + function devAssert(condition, message) { + const booleanCondition = Boolean(condition); + if (!booleanCondition) { + throw new Error(message); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/didYouMean.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/didYouMean.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.didYouMean = didYouMean; + const MAX_SUGGESTIONS = 5; + /** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ + + function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = secondArg ? [firstArg, secondArg] : [undefined, firstArg]; + let message = ' Did you mean '; + if (subMessage) { + message += subMessage + ' '; + } + const suggestions = suggestionsArg.map(x => `"${x}"`); + switch (suggestions.length) { + case 0: + return ''; + case 1: + return message + suggestions[0] + '?'; + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/groupBy.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/groupBy.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.groupBy = groupBy; + /** + * Groups array items into a Map, given a function to produce grouping key. + */ + function groupBy(list, keyFn) { + const result = new Map(); + for (const item of list) { + const key = keyFn(item); + const group = result.get(key); + if (group === undefined) { + result.set(key, [item]); + } else { + group.push(item); + } + } + return result; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/identityFunc.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/identityFunc.mjs ***! + \**************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.identityFunc = identityFunc; + /** + * Returns the first argument it receives. + */ + function identityFunc(x) { + return x; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/inspect.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/inspect.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.inspect = inspect; + const MAX_ARRAY_LENGTH = 10; + const MAX_RECURSIVE_DEPTH = 2; + /** + * Used to print values in error messages. + */ + + function inspect(value) { + return formatValue(value, []); + } + function formatValue(value, seenValues) { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + case 'object': + return formatObjectValue(value, seenValues); + default: + return String(value); + } + } + function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return 'null'; + } + if (previouslySeenValues.includes(value)) { + return '[Circular]'; + } + const seenValues = [...previouslySeenValues, value]; + if (isJSONable(value)) { + const jsonValue = value.toJSON(); // check for infinite recursion + + if (jsonValue !== value) { + return typeof jsonValue === 'string' ? jsonValue : formatValue(jsonValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + return formatObject(value, seenValues); + } + function isJSONable(value) { + return typeof value.toJSON === 'function'; + } + function formatObject(object, seenValues) { + const entries = Object.entries(object); + if (entries.length === 0) { + return '{}'; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + const properties = entries.map(([key, value]) => key + ': ' + formatValue(value, seenValues)); + return '{ ' + properties.join(', ') + ' }'; + } + function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + return '[' + items.join(', ') + ']'; + } + function getObjectTag(object) { + const tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, ''); + if (tag === 'Object' && typeof object.constructor === 'function') { + const name = object.constructor.name; + if (typeof name === 'string' && name !== '') { + return name; + } + } + return tag; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/instanceOf.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/instanceOf.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.instanceOf = void 0; + var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + /** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + */ + + const instanceOf = exports.instanceOf = /* c8 ignore next 6 */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + globalThis.process && globalThis.process.env.NODE_ENV === 'production' ? function instanceOf(value, constructor) { + return value instanceof constructor; + } : function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + if (typeof value === 'object' && value !== null) { + var _value$constructor; + + // Prefer Symbol.toStringTag since it is immune to minification. + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = + // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 + ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name; + if (className === valueClassName) { + const stringifiedValue = (0, _inspect.inspect)(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + + Ensure that there is only one instance of "graphql" in the node_modules + directory. If different versions of "graphql" are the dependencies of other + relied on modules, use "resolutions" to ensure only one version is installed. + + https://yarnpkg.com/en/docs/selective-version-resolutions + + Duplicate "graphql" modules cannot be used at the same time since different + versions may have different capabilities and behavior. The data from one + version used in the function from another could produce confusing and + spurious results.`); + } + } + return false; + }; + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/invariant.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/invariant.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.invariant = invariant; + function invariant(condition, message) { + const booleanCondition = Boolean(condition); + if (!booleanCondition) { + throw new Error(message != null ? message : 'Unexpected invariant triggered.'); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs": + /*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isAsyncIterable.mjs ***! + \*****************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isAsyncIterable = isAsyncIterable; + /** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + */ + function isAsyncIterable(maybeAsyncIterable) { + return typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 ? void 0 : maybeAsyncIterable[Symbol.asyncIterator]) === 'function'; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/isIterableObject.mjs": + /*!******************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isIterableObject.mjs ***! + \******************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isIterableObject = isIterableObject; + /** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @example + * ```ts + * isIterableObject([ 1, 2, 3 ]) // true + * isIterableObject(new Map()) // true + * isIterableObject('ABC') // false + * isIterableObject({ key: 'value' }) // false + * isIterableObject({ length: 1, 0: 'Alpha' }) // false + * ``` + */ + function isIterableObject(maybeIterable) { + return typeof maybeIterable === 'object' && typeof (maybeIterable === null || maybeIterable === void 0 ? void 0 : maybeIterable[Symbol.iterator]) === 'function'; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/isObjectLike.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isObjectLike.mjs ***! + \**************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isObjectLike = isObjectLike; + /** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ + function isObjectLike(value) { + return typeof value == 'object' && value !== null; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/isPromise.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isPromise.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isPromise = isPromise; + /** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ + function isPromise(value) { + return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function'; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/keyMap.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/keyMap.mjs ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.keyMap = keyMap; + /** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { + * // Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } + * // } + * + * const jennyEntry = entriesByName['Jenny'] + * + * // { name: 'Jenny', num: '857-6309' } + * ``` + */ + function keyMap(list, keyFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = item; + } + return result; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/keyValMap.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/keyValMap.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.keyValMap = keyValMap; + /** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * ``` + */ + function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + return result; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/mapValue.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/mapValue.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.mapValue = mapValue; + /** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ + function mapValue(map, fn) { + const result = Object.create(null); + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); + } + return result; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/memoize3.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/memoize3.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.memoize3 = memoize3; + /** + * Memoizes the provided three-argument function. + */ + function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + if (cache0 === undefined) { + cache0 = new WeakMap(); + } + let cache1 = cache0.get(a1); + if (cache1 === undefined) { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + let cache2 = cache1.get(a2); + if (cache2 === undefined) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + let fnResult = cache2.get(a3); + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); + } + return fnResult; + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/naturalCompare.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/naturalCompare.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.naturalCompare = naturalCompare; + /** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ + function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + let bNum = 0; + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + if (aNum < bNum) { + return -1; + } + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + if (aChar > bChar) { + return 1; + } + ++aIndex; + ++bIndex; + } + } + return aStr.length - bStr.length; + } + const DIGIT_0 = 48; + const DIGIT_9 = 57; + function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/printPathArray.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/printPathArray.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.printPathArray = printPathArray; + /** + * Build a string describing the path. + */ + function printPathArray(path) { + return path.map(key => typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key).join(''); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/promiseForObject.mjs": + /*!******************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/promiseForObject.mjs ***! + \******************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.promiseForObject = promiseForObject; + /** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ + function promiseForObject(object) { + return Promise.all(Object.values(object)).then(resolvedValues => { + const resolvedObject = Object.create(null); + for (const [i, key] of Object.keys(object).entries()) { + resolvedObject[key] = resolvedValues[i]; + } + return resolvedObject; + }); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/promiseReduce.mjs": + /*!***************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/promiseReduce.mjs ***! + \***************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.promiseReduce = promiseReduce; + var _isPromise = __webpack_require__(/*! ./isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); + /** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ + function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + for (const value of values) { + accumulator = (0, _isPromise.isPromise)(accumulator) ? accumulator.then(resolved => callbackFn(resolved, value)) : callbackFn(accumulator, value); + } + return accumulator; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/suggestionList.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/suggestionList.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.suggestionList = suggestionList; + var _naturalCompare = __webpack_require__(/*! ./naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); + /** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ + + function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : (0, _naturalCompare.naturalCompare)(a, b); + }); + } + /** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ + + class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)]; + } + measure(option, threshold) { + if (this._input === option) { + return 0; + } + const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + const aLength = a.length; + const bLength = b.length; + if (aLength - bLength > threshold) { + return undefined; + } + const rows = this._rows; + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = currentRow[0] = i; + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min(upRow[j] + 1, + // delete + currentRow[j - 1] + 1, + // insert + upRow[j - 1] + cost // substitute + ); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + currentRow[j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + if (smallestCell > threshold) { + return undefined; + } + } + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } + } + function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + return array; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/toError.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/toError.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.toError = toError; + var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + /** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + */ + + function toError(thrownValue) { + return thrownValue instanceof Error ? thrownValue : new NonErrorThrown(thrownValue); + } + class NonErrorThrown extends Error { + constructor(thrownValue) { + super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); + this.name = 'NonErrorThrown'; + this.thrownValue = thrownValue; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/jsutils/toObjMap.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/toObjMap.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.toObjMap = toObjMap; + function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + const map = Object.create(null); + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + return map; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/ast.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql/language/ast.mjs ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Token = exports.QueryDocumentKeys = exports.OperationTypeNode = exports.Location = void 0; + exports.isNode = isNode; + /** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ + class Location { + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The Token at which this Node begins. + */ + + /** + * The Token at which this Node ends. + */ + + /** + * The Source document the AST represents. + */ + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + get [Symbol.toStringTag]() { + return 'Location'; + } + toJSON() { + return { + start: this.start, + end: this.end + }; + } + } + /** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + exports.Location = Location; + class Token { + /** + * The kind of Token. + */ + + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The 1-indexed line number on which this Token appears. + */ + + /** + * The 1-indexed column number at which this Token begins. + */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + * + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + constructor(kind, start, end, line, column, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + + this.value = value; + this.prev = null; + this.next = null; + } + get [Symbol.toStringTag]() { + return 'Token'; + } + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; + } + } + /** + * The list of all possible AST node types. + */ + + /** + * @internal + */ + exports.Token = Token; + const QueryDocumentKeys = exports.QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', + // Note: fragment variable definitions are deprecated and will removed in v17.0.0 + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] + }; + const kindValues = new Set(Object.keys(QueryDocumentKeys)); + /** + * @internal + */ + + function isNode(maybeNode) { + const maybeKind = maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; + return typeof maybeKind === 'string' && kindValues.has(maybeKind); + } + /** Name */ + + var OperationTypeNode; + (function (OperationTypeNode) { + OperationTypeNode['QUERY'] = 'query'; + OperationTypeNode['MUTATION'] = 'mutation'; + OperationTypeNode['SUBSCRIPTION'] = 'subscription'; + })(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); + + /***/ }), + + /***/ "../../../node_modules/graphql/language/blockString.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/language/blockString.mjs ***! + \**************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.dedentBlockStringLines = dedentBlockStringLines; + exports.isPrintableAsBlockString = isPrintableAsBlockString; + exports.printBlockString = printBlockString; + var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); + /** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ + + function dedentBlockStringLines(lines) { + var _firstNonEmptyLine2; + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + for (let i = 0; i < lines.length; ++i) { + var _firstNonEmptyLine; + const line = lines[i]; + const indent = leadingWhitespace(line); + if (indent === line.length) { + continue; // skip empty lines + } + firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i; + lastNonEmptyLine = i; + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; + } + } + return lines // Remove common indentation from all lines but first. + .map((line, i) => i === 0 ? line : line.slice(commonIndent)) // Remove leading and trailing blank lines. + .slice((_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0, lastNonEmptyLine + 1); + } + function leadingWhitespace(str) { + let i = 0; + while (i < str.length && (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i))) { + ++i; + } + return i; + } + /** + * @internal + */ + + function isPrintableAsBlockString(value) { + if (value === '') { + return true; // empty string is printable + } + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + for (let i = 0; i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0x0000: + case 0x0001: + case 0x0002: + case 0x0003: + case 0x0004: + case 0x0005: + case 0x0006: + case 0x0007: + case 0x0008: + case 0x000b: + case 0x000c: + case 0x000e: + case 0x000f: + return false; + // Has non-printable characters + + case 0x000d: + // \r + return false; + // Has \r or \r\n which will be replaced as \n + + case 10: + // \n + if (isEmptyLine && !seenNonEmptyLine) { + return false; // Has leading new line + } + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + case 9: // \t + + case 32: + // + hasIndent || (hasIndent = isEmptyLine); + break; + default: + hasCommonIndent && (hasCommonIndent = hasIndent); + isEmptyLine = false; + } + } + if (isEmptyLine) { + return false; // Has trailing empty lines + } + if (hasCommonIndent && seenNonEmptyLine) { + return false; // Has internal indent + } + return true; + } + /** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + + function printBlockString(value, options) { + const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + + const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every(line => line.length === 0 || (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line + + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line + + const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith('\\'); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && ( + // add leading and trailing new lines only if it improves readability + !isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes); + let result = ''; // Format a multi-line block quote to account for leading space. + + const skipLeadingNewLine = isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); + if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) { + result += '\n'; + } + result += escapedValue; + if (printAsMultipleLines || forceTrailingNewline) { + result += '\n'; + } + return '"""' + result + '"""'; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/characterClasses.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/language/characterClasses.mjs ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isDigit = isDigit; + exports.isLetter = isLetter; + exports.isNameContinue = isNameContinue; + exports.isNameStart = isNameStart; + exports.isWhiteSpace = isWhiteSpace; + /** + * ``` + * WhiteSpace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ + function isWhiteSpace(code) { + return code === 0x0009 || code === 0x0020; + } + /** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ + + function isDigit(code) { + return code >= 0x0030 && code <= 0x0039; + } + /** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ + + function isLetter(code) { + return code >= 0x0061 && code <= 0x007a || + // A-Z + code >= 0x0041 && code <= 0x005a // a-z + ; + } + /** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ + + function isNameStart(code) { + return isLetter(code) || code === 0x005f; + } + /** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ + + function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 0x005f; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/directiveLocation.mjs": + /*!********************************************************************!*\ + !*** ../../../node_modules/graphql/language/directiveLocation.mjs ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.DirectiveLocation = void 0; + /** + * The set of allowed directive location values. + */ + var DirectiveLocation; + (function (DirectiveLocation) { + DirectiveLocation['QUERY'] = 'QUERY'; + DirectiveLocation['MUTATION'] = 'MUTATION'; + DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; + DirectiveLocation['FIELD'] = 'FIELD'; + DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; + DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; + DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; + DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; + DirectiveLocation['SCHEMA'] = 'SCHEMA'; + DirectiveLocation['SCALAR'] = 'SCALAR'; + DirectiveLocation['OBJECT'] = 'OBJECT'; + DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; + DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; + DirectiveLocation['INTERFACE'] = 'INTERFACE'; + DirectiveLocation['UNION'] = 'UNION'; + DirectiveLocation['ENUM'] = 'ENUM'; + DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; + DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; + DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; + })(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); + + /** + * The enum type representing the directive location values. + * + * @deprecated Please use `DirectiveLocation`. Will be remove in v17. + */ + + /***/ }), + + /***/ "../../../node_modules/graphql/language/index.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/index.mjs ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "BREAK", ({ + enumerable: true, + get: function () { + return _visitor.BREAK; + } + })); + Object.defineProperty(exports, "DirectiveLocation", ({ + enumerable: true, + get: function () { + return _directiveLocation.DirectiveLocation; + } + })); + Object.defineProperty(exports, "Kind", ({ + enumerable: true, + get: function () { + return _kinds.Kind; + } + })); + Object.defineProperty(exports, "Lexer", ({ + enumerable: true, + get: function () { + return _lexer.Lexer; + } + })); + Object.defineProperty(exports, "Location", ({ + enumerable: true, + get: function () { + return _ast.Location; + } + })); + Object.defineProperty(exports, "OperationTypeNode", ({ + enumerable: true, + get: function () { + return _ast.OperationTypeNode; + } + })); + Object.defineProperty(exports, "Source", ({ + enumerable: true, + get: function () { + return _source.Source; + } + })); + Object.defineProperty(exports, "Token", ({ + enumerable: true, + get: function () { + return _ast.Token; + } + })); + Object.defineProperty(exports, "TokenKind", ({ + enumerable: true, + get: function () { + return _tokenKind.TokenKind; + } + })); + Object.defineProperty(exports, "getEnterLeaveForKind", ({ + enumerable: true, + get: function () { + return _visitor.getEnterLeaveForKind; + } + })); + Object.defineProperty(exports, "getLocation", ({ + enumerable: true, + get: function () { + return _location.getLocation; + } + })); + Object.defineProperty(exports, "getVisitFn", ({ + enumerable: true, + get: function () { + return _visitor.getVisitFn; + } + })); + Object.defineProperty(exports, "isConstValueNode", ({ + enumerable: true, + get: function () { + return _predicates.isConstValueNode; + } + })); + Object.defineProperty(exports, "isDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isDefinitionNode; + } + })); + Object.defineProperty(exports, "isExecutableDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isExecutableDefinitionNode; + } + })); + Object.defineProperty(exports, "isSelectionNode", ({ + enumerable: true, + get: function () { + return _predicates.isSelectionNode; + } + })); + Object.defineProperty(exports, "isTypeDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeDefinitionNode; + } + })); + Object.defineProperty(exports, "isTypeExtensionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeExtensionNode; + } + })); + Object.defineProperty(exports, "isTypeNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeNode; + } + })); + Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeSystemDefinitionNode; + } + })); + Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeSystemExtensionNode; + } + })); + Object.defineProperty(exports, "isValueNode", ({ + enumerable: true, + get: function () { + return _predicates.isValueNode; + } + })); + Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parser.parse; + } + })); + Object.defineProperty(exports, "parseConstValue", ({ + enumerable: true, + get: function () { + return _parser.parseConstValue; + } + })); + Object.defineProperty(exports, "parseType", ({ + enumerable: true, + get: function () { + return _parser.parseType; + } + })); + Object.defineProperty(exports, "parseValue", ({ + enumerable: true, + get: function () { + return _parser.parseValue; + } + })); + Object.defineProperty(exports, "print", ({ + enumerable: true, + get: function () { + return _printer.print; + } + })); + Object.defineProperty(exports, "printLocation", ({ + enumerable: true, + get: function () { + return _printLocation.printLocation; + } + })); + Object.defineProperty(exports, "printSourceLocation", ({ + enumerable: true, + get: function () { + return _printLocation.printSourceLocation; + } + })); + Object.defineProperty(exports, "visit", ({ + enumerable: true, + get: function () { + return _visitor.visit; + } + })); + Object.defineProperty(exports, "visitInParallel", ({ + enumerable: true, + get: function () { + return _visitor.visitInParallel; + } + })); + var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); + var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); + var _printLocation = __webpack_require__(/*! ./printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); + var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); + var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); + var _parser = __webpack_require__(/*! ./parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); + var _printer = __webpack_require__(/*! ./printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); + var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _predicates = __webpack_require__(/*! ./predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); + var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/language/kinds.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/kinds.mjs ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Kind = void 0; + /** + * The set of allowed kind values for AST nodes. + */ + var Kind; + (function (Kind) { + Kind['NAME'] = 'Name'; + Kind['DOCUMENT'] = 'Document'; + Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; + Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; + Kind['SELECTION_SET'] = 'SelectionSet'; + Kind['FIELD'] = 'Field'; + Kind['ARGUMENT'] = 'Argument'; + Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; + Kind['INLINE_FRAGMENT'] = 'InlineFragment'; + Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; + Kind['VARIABLE'] = 'Variable'; + Kind['INT'] = 'IntValue'; + Kind['FLOAT'] = 'FloatValue'; + Kind['STRING'] = 'StringValue'; + Kind['BOOLEAN'] = 'BooleanValue'; + Kind['NULL'] = 'NullValue'; + Kind['ENUM'] = 'EnumValue'; + Kind['LIST'] = 'ListValue'; + Kind['OBJECT'] = 'ObjectValue'; + Kind['OBJECT_FIELD'] = 'ObjectField'; + Kind['DIRECTIVE'] = 'Directive'; + Kind['NAMED_TYPE'] = 'NamedType'; + Kind['LIST_TYPE'] = 'ListType'; + Kind['NON_NULL_TYPE'] = 'NonNullType'; + Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; + Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; + Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; + Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; + Kind['FIELD_DEFINITION'] = 'FieldDefinition'; + Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; + Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; + Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; + Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; + Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; + Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; + Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; + Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; + Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; + Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; + Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; + Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; + Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; + Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; + })(Kind || (exports.Kind = Kind = {})); + + /** + * The enum type representing the possible kind values of AST nodes. + * + * @deprecated Please use `Kind`. Will be remove in v17. + */ + + /***/ }), + + /***/ "../../../node_modules/graphql/language/lexer.mjs": + /*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/lexer.mjs ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Lexer = void 0; + exports.isPunctuatorTokenKind = isPunctuatorTokenKind; + var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); + var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); + var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); + var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); + /** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ + + class Lexer { + /** + * The previously focused non-ignored token. + */ + + /** + * The currently focused non-ignored token. + */ + + /** + * The (1-indexed) line containing the current token. + */ + + /** + * The character offset at which the current line begins. + */ + constructor(source) { + const startOfFileToken = new _ast.Token(_tokenKind.TokenKind.SOF, 0, 0, 0, 0); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + get [Symbol.toStringTag]() { + return 'Lexer'; + } + /** + * Advances the token stream to the next non-ignored token. + */ + + advance() { + this.lastToken = this.token; + const token = this.token = this.lookahead(); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ + + lookahead() { + let token = this.token; + if (token.kind !== _tokenKind.TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === _tokenKind.TokenKind.COMMENT); + } + return token; + } + } + /** + * @internal + */ + exports.Lexer = Lexer; + function isPunctuatorTokenKind(kind) { + return kind === _tokenKind.TokenKind.BANG || kind === _tokenKind.TokenKind.DOLLAR || kind === _tokenKind.TokenKind.AMP || kind === _tokenKind.TokenKind.PAREN_L || kind === _tokenKind.TokenKind.PAREN_R || kind === _tokenKind.TokenKind.SPREAD || kind === _tokenKind.TokenKind.COLON || kind === _tokenKind.TokenKind.EQUALS || kind === _tokenKind.TokenKind.AT || kind === _tokenKind.TokenKind.BRACKET_L || kind === _tokenKind.TokenKind.BRACKET_R || kind === _tokenKind.TokenKind.BRACE_L || kind === _tokenKind.TokenKind.PIPE || kind === _tokenKind.TokenKind.BRACE_R; + } + /** + * A Unicode scalar value is any Unicode code point except surrogate code + * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and + * 0xE000 to 0x10FFFF. + * + * SourceCharacter :: + * - "Any Unicode scalar value" + */ + + function isUnicodeScalarValue(code) { + return code >= 0x0000 && code <= 0xd7ff || code >= 0xe000 && code <= 0x10ffff; + } + /** + * The GraphQL specification defines source text as a sequence of unicode scalar + * values (which Unicode defines to exclude surrogate code points). However + * JavaScript defines strings as a sequence of UTF-16 code units which may + * include surrogates. A surrogate pair is a valid source character as it + * encodes a supplementary code point (above U+FFFF), but unpaired surrogate + * code points are not valid source characters. + */ + + function isSupplementaryCodePoint(body, location) { + return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1)); + } + function isLeadingSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; + } + function isTrailingSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; + } + /** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + */ + + function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); + if (code === undefined) { + return _tokenKind.TokenKind.EOF; + } else if (code >= 0x0020 && code <= 0x007e) { + // Printable ASCII + const char = String.fromCodePoint(code); + return char === '"' ? "'\"'" : `"${char}"`; + } // Unicode code point + + return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); + } + /** + * Create a token with line and column location information. + */ + + function createToken(lexer, kind, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new _ast.Token(kind, start, end, line, col, value); + } + /** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ + + function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + while (position < bodyLength) { + const code = body.charCodeAt(position); // SourceCharacter + + switch (code) { + // Ignored :: + // - UnicodeBOM + // - WhiteSpace + // - LineTerminator + // - Comment + // - Comma + // + // UnicodeBOM :: "Byte Order Mark (U+FEFF)" + // + // WhiteSpace :: + // - "Horizontal Tab (U+0009)" + // - "Space (U+0020)" + // + // Comma :: , + case 0xfeff: // + + case 0x0009: // \t + + case 0x0020: // + + case 0x002c: + // , + ++position; + continue; + // LineTerminator :: + // - "New Line (U+000A)" + // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] + // - "Carriage Return (U+000D)" "New Line (U+000A)" + + case 0x000a: + // \n + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; + case 0x000d: + // \r + if (body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + continue; + // Comment + + case 0x0023: + // # + return readComment(lexer, position); + // Token :: + // - Punctuator + // - Name + // - IntValue + // - FloatValue + // - StringValue + // + // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } + + case 0x0021: + // ! + return createToken(lexer, _tokenKind.TokenKind.BANG, position, position + 1); + case 0x0024: + // $ + return createToken(lexer, _tokenKind.TokenKind.DOLLAR, position, position + 1); + case 0x0026: + // & + return createToken(lexer, _tokenKind.TokenKind.AMP, position, position + 1); + case 0x0028: + // ( + return createToken(lexer, _tokenKind.TokenKind.PAREN_L, position, position + 1); + case 0x0029: + // ) + return createToken(lexer, _tokenKind.TokenKind.PAREN_R, position, position + 1); + case 0x002e: + // . + if (body.charCodeAt(position + 1) === 0x002e && body.charCodeAt(position + 2) === 0x002e) { + return createToken(lexer, _tokenKind.TokenKind.SPREAD, position, position + 3); + } + break; + case 0x003a: + // : + return createToken(lexer, _tokenKind.TokenKind.COLON, position, position + 1); + case 0x003d: + // = + return createToken(lexer, _tokenKind.TokenKind.EQUALS, position, position + 1); + case 0x0040: + // @ + return createToken(lexer, _tokenKind.TokenKind.AT, position, position + 1); + case 0x005b: + // [ + return createToken(lexer, _tokenKind.TokenKind.BRACKET_L, position, position + 1); + case 0x005d: + // ] + return createToken(lexer, _tokenKind.TokenKind.BRACKET_R, position, position + 1); + case 0x007b: + // { + return createToken(lexer, _tokenKind.TokenKind.BRACE_L, position, position + 1); + case 0x007c: + // | + return createToken(lexer, _tokenKind.TokenKind.PIPE, position, position + 1); + case 0x007d: + // } + return createToken(lexer, _tokenKind.TokenKind.BRACE_R, position, position + 1); + // StringValue + + case 0x0022: + // " + if (body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { + return readBlockString(lexer, position); + } + return readString(lexer, position); + } // IntValue | FloatValue (Digit | -) + + if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { + return readNumber(lexer, position, code); + } // Name + + if ((0, _characterClasses.isNameStart)(code)) { + return readName(lexer, position); + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, code === 0x0027 ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`); + } + return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); + } + /** + * Reads a comment token from the source file. + * + * ``` + * Comment :: # CommentChar* [lookahead != CommentChar] + * + * CommentChar :: SourceCharacter but not LineTerminator + * ``` + */ + + function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; + } + } + return createToken(lexer, _tokenKind.TokenKind.COMMENT, start, position, body.slice(start + 1, position)); + } + /** + * Reads a number token from the source file, either a FloatValue or an IntValue + * depending on whether a FractionalPart or ExponentPart is encountered. + * + * ``` + * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] + * + * IntegerPart :: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit Digit* + * + * NegativeSign :: - + * + * NonZeroDigit :: Digit but not `0` + * + * FloatValue :: + * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * + * FractionalPart :: . Digit+ + * + * ExponentPart :: ExponentIndicator Sign? Digit+ + * + * ExponentIndicator :: one of `e` `E` + * + * Sign :: one of + - + * ``` + */ + + function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; // NegativeSign (-) + + if (code === 0x002d) { + code = body.charCodeAt(++position); + } // Zero (0) + + if (code === 0x0030) { + code = body.charCodeAt(++position); + if ((0, _characterClasses.isDigit)(code)) { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, unexpected digit after 0: ${printCodePointAt(lexer, position)}.`); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Full stop (.) + + if (code === 0x002e) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // E e + + if (code === 0x0045 || code === 0x0065) { + isFloat = true; + code = body.charCodeAt(++position); // + - + + if (code === 0x002b || code === 0x002d) { + code = body.charCodeAt(++position); + } + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, expected digit but got: ${printCodePointAt(lexer, position)}.`); + } + return createToken(lexer, isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, start, position, body.slice(start, position)); + } + /** + * Returns the new position in the source after reading one or more digits. + */ + + function readDigits(lexer, start, firstCode) { + if (!(0, _characterClasses.isDigit)(firstCode)) { + throw (0, _syntaxError.syntaxError)(lexer.source, start, `Invalid number, expected digit but got: ${printCodePointAt(lexer, start)}.`); + } + const body = lexer.source.body; + let position = start + 1; // +1 to skip first firstCode + + while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { + ++position; + } + return position; + } + /** + * Reads a single-quote string token from the source file. + * + * ``` + * StringValue :: + * - `""` [lookahead != `"`] + * - `"` StringCharacter+ `"` + * + * StringCharacter :: + * - SourceCharacter but not `"` or `\` or LineTerminator + * - `\u` EscapedUnicode + * - `\` EscapedCharacter + * + * EscapedUnicode :: + * - `{` HexDigit+ `}` + * - HexDigit HexDigit HexDigit HexDigit + * + * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` + * ``` + */ + + function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ''; + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Quote (") + + if (code === 0x0022) { + value += body.slice(chunkStart, position); + return createToken(lexer, _tokenKind.TokenKind.STRING, start, position + 1, value); + } // Escape Sequence (\) + + if (code === 0x005c) { + value += body.slice(chunkStart, position); + const escape = body.charCodeAt(position + 1) === 0x0075 // u + ? body.charCodeAt(position + 2) === 0x007b // { + ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + } + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); + } // The string value and lexed size of an escape sequence. + + function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; // Cannot be larger than 12 chars (\u{00000000}). + + while (size < 12) { + const code = body.charCodeAt(position + size++); // Closing Brace (}) + + if (code === 0x007d) { + // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } + return { + value: String.fromCodePoint(point), + size + }; + } // Append this hex digit to the code point. + + point = point << 4 | readHexDigit(code); + if (point < 0) { + break; + } + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + size)}".`); + } + function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); + if (isUnicodeScalarValue(code)) { + return { + value: String.fromCodePoint(code), + size: 6 + }; + } // GraphQL allows JSON-style surrogate pair escape sequences, but only when + // a valid pair is formed. + + if (isLeadingSurrogate(code)) { + // \u + if (body.charCodeAt(position + 6) === 0x005c && body.charCodeAt(position + 7) === 0x0075) { + const trailingCode = read16BitHexCode(body, position + 8); + if (isTrailingSurrogate(trailingCode)) { + // JavaScript defines strings as a sequence of UTF-16 code units and + // encodes Unicode code points above U+FFFF using a surrogate pair of + // code units. Since this is a surrogate pair escape sequence, just + // include both codes into the JavaScript string value. Had JavaScript + // not been internally based on UTF-16, then this surrogate pair would + // be decoded to retrieve the supplementary code point. + return { + value: String.fromCodePoint(code, trailingCode), + size: 12 + }; + } + } + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`); + } + /** + * Reads four hexadecimal characters and returns the positive integer that 16bit + * hexadecimal string represents. For example, "000f" will return 15, and "dead" + * will return 57005. + * + * Returns a negative number if any char was not a valid hexadecimal digit. + */ + + function read16BitHexCode(body, position) { + // readHexDigit() returns -1 on error. ORing a negative value with any other + // value always produces a negative value. + return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3)); + } + /** + * Reads a hexadecimal character and returns its positive integer value (0-15). + * + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 if the provided character code was not a valid hexadecimal digit. + * + * HexDigit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * - `A` `B` `C` `D` `E` `F` + * - `a` `b` `c` `d` `e` `f` + */ + + function readHexDigit(code) { + return code >= 0x0030 && code <= 0x0039 // 0-9 + ? code - 0x0030 : code >= 0x0041 && code <= 0x0046 // A-F + ? code - 0x0037 : code >= 0x0061 && code <= 0x0066 // a-f + ? code - 0x0057 : -1; + } + /** + * | Escaped Character | Code Point | Character Name | + * | ----------------- | ---------- | ---------------------------- | + * | `"` | U+0022 | double quote | + * | `\` | U+005C | reverse solidus (back slash) | + * | `/` | U+002F | solidus (forward slash) | + * | `b` | U+0008 | backspace | + * | `f` | U+000C | form feed | + * | `n` | U+000A | line feed (new line) | + * | `r` | U+000D | carriage return | + * | `t` | U+0009 | horizontal tab | + */ + + function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); + switch (code) { + case 0x0022: + // " + return { + value: '\u0022', + size: 2 + }; + case 0x005c: + // \ + return { + value: '\u005c', + size: 2 + }; + case 0x002f: + // / + return { + value: '\u002f', + size: 2 + }; + case 0x0062: + // b + return { + value: '\u0008', + size: 2 + }; + case 0x0066: + // f + return { + value: '\u000c', + size: 2 + }; + case 0x006e: + // n + return { + value: '\u000a', + size: 2 + }; + case 0x0072: + // r + return { + value: '\u000d', + size: 2 + }; + case 0x0074: + // t + return { + value: '\u0009', + size: 2 + }; + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character escape sequence: "${body.slice(position, position + 2)}".`); + } + /** + * Reads a block string token from the source file. + * + * ``` + * StringValue :: + * - `"""` BlockStringCharacter* `"""` + * + * BlockStringCharacter :: + * - SourceCharacter but not `"""` or `\"""` + * - `\"""` + * ``` + */ + + function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ''; + const blockLines = []; + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Triple-Quote (""") + + if (code === 0x0022 && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken(lexer, _tokenKind.TokenKind.BLOCK_STRING, start, position + 3, + // Return a string of the lines joined with U+000A. + (0, _blockString.dedentBlockStringLines)(blockLines).join('\n')); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } // Escaped Triple-Quote (\""") + + if (code === 0x005c && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022 && body.charCodeAt(position + 3) === 0x0022) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; // skip only slash + + position += 4; + continue; + } // LineTerminator + + if (code === 0x000a || code === 0x000d) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + currentLine = ''; + chunkStart = position; + lineStart = position; + continue; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + } + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); + } + /** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + */ + + function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if ((0, _characterClasses.isNameContinue)(code)) { + ++position; + } else { + break; + } + } + return createToken(lexer, _tokenKind.TokenKind.NAME, start, position, body.slice(start, position)); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/location.mjs": + /*!***********************************************************!*\ + !*** ../../../node_modules/graphql/language/location.mjs ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getLocation = getLocation; + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + const LineRegExp = /\r\n|[\n\r]/g; + /** + * Represents a location in a Source. + */ + + /** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ + function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; + for (const match of source.body.matchAll(LineRegExp)) { + typeof match.index === 'number' || (0, _invariant.invariant)(false); + if (match.index >= position) { + break; + } + lastLineStart = match.index + match[0].length; + line += 1; + } + return { + line, + column: position + 1 - lastLineStart + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/parser.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/language/parser.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Parser = void 0; + exports.parse = parse; + exports.parseConstValue = parseConstValue; + exports.parseType = parseType; + exports.parseValue = parseValue; + var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); + var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); + var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); + var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); + var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); + /** + * Configuration options to control parser behavior + */ + + /** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ + function parse(source, options) { + const parser = new Parser(source, options); + return parser.parseDocument(); + } + /** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + + function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; + } + /** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + */ + + function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; + } + /** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + + function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return type; + } + /** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + + class Parser { + constructor(source, options = {}) { + const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); + this._lexer = new _lexer.Lexer(sourceObj); + this._options = options; + this._tokenCounter = 0; + } + /** + * Converts a name lex token into a name parse node. + */ + + parseName() { + const token = this.expectToken(_tokenKind.TokenKind.NAME); + return this.node(token, { + kind: _kinds.Kind.NAME, + value: token.value + }); + } // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + */ + + parseDocument() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.DOCUMENT, + definitions: this.many(_tokenKind.TokenKind.SOF, this.parseDefinition, _tokenKind.TokenKind.EOF) + }); + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + + parseDefinition() { + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } // Many definitions begin with a description and require a lookahead. + + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token; + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + case 'scalar': + return this.parseScalarTypeDefinition(); + case 'type': + return this.parseObjectTypeDefinition(); + case 'interface': + return this.parseInterfaceTypeDefinition(); + case 'union': + return this.parseUnionTypeDefinition(); + case 'enum': + return this.parseEnumTypeDefinition(); + case 'input': + return this.parseInputObjectTypeDefinition(); + case 'directive': + return this.parseDirectiveDefinition(); + } + if (hasDescription) { + throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, 'Unexpected description, descriptions are supported only on type definitions.'); + } + switch (keywordToken.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + case 'fragment': + return this.parseFragmentDefinition(); + case 'extend': + return this.parseTypeSystemExtension(); + } + } + throw this.unexpected(keywordToken); + } // Implements the parsing rules in the Operations section. + + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + + parseOperationDefinition() { + const start = this._lexer.token; + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: _ast.OperationTypeNode.QUERY, + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet() + }); + } + const operation = this.parseOperationType(); + let name; + if (this.peek(_tokenKind.TokenKind.NAME)) { + name = this.parseName(); + } + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + /** + * OperationType : one of query mutation subscription + */ + + parseOperationType() { + const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); + switch (operationToken.value) { + case 'query': + return _ast.OperationTypeNode.QUERY; + case 'mutation': + return _ast.OperationTypeNode.MUTATION; + case 'subscription': + return _ast.OperationTypeNode.SUBSCRIPTION; + } + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ + + parseVariableDefinitions() { + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseVariableDefinition, _tokenKind.TokenKind.PAREN_R); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: (this.expectToken(_tokenKind.TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.parseConstValueLiteral() : undefined, + directives: this.parseConstDirectives() + }); + } + /** + * Variable : $ Name + */ + + parseVariable() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.DOLLAR); + return this.node(start, { + kind: _kinds.Kind.VARIABLE, + name: this.parseName() + }); + } + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + */ + + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.SELECTION_SET, + selections: this.many(_tokenKind.TokenKind.BRACE_L, this.parseSelection, _tokenKind.TokenKind.BRACE_R) + }); + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + parseSelection() { + return this.peek(_tokenKind.TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; + if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + return this.node(start, { + kind: _kinds.Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined + }); + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, item, _tokenKind.TokenKind.PAREN_R); + } + /** + * Argument[Const] : Name : Value[?Const] + */ + + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst) + }); + } + parseConstArgument() { + return this.parseArgument(true); + } // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + + parseFragment() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword('on'); + if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false) + }); + } + return this.node(start, { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + parseFragmentDefinition() { + const start = this._lexer.token; + this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (this._options.allowLegacyFragmentVariables === true) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + /** + * FragmentName : Name but not `on` + */ + + parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } + return this.parseName(); + } // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + + parseValueLiteral(isConst) { + const token = this._lexer.token; + switch (token.kind) { + case _tokenKind.TokenKind.BRACKET_L: + return this.parseList(isConst); + case _tokenKind.TokenKind.BRACE_L: + return this.parseObject(isConst); + case _tokenKind.TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.INT, + value: token.value + }); + case _tokenKind.TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.FLOAT, + value: token.value + }); + case _tokenKind.TokenKind.STRING: + case _tokenKind.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + case _tokenKind.TokenKind.NAME: + this.advanceLexer(); + switch (token.value) { + case 'true': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: true + }); + case 'false': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: false + }); + case 'null': + return this.node(token, { + kind: _kinds.Kind.NULL + }); + default: + return this.node(token, { + kind: _kinds.Kind.ENUM, + value: token.value + }); + } + case _tokenKind.TokenKind.DOLLAR: + if (isConst) { + this.expectToken(_tokenKind.TokenKind.DOLLAR); + if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { + const varName = this._lexer.token.value; + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected variable "$${varName}" in constant value.`); + } else { + throw this.unexpected(token); + } + } + return this.parseVariable(); + default: + throw this.unexpected(); + } + } + parseConstValueLiteral() { + return this.parseValueLiteral(true); + } + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _tokenKind.TokenKind.BLOCK_STRING + }); + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.LIST, + values: this.any(_tokenKind.TokenKind.BRACKET_L, item, _tokenKind.TokenKind.BRACKET_R) + }); + } + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + */ + + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.OBJECT, + fields: this.any(_tokenKind.TokenKind.BRACE_L, item, _tokenKind.TokenKind.BRACE_R) + }); + } + /** + * ObjectField[Const] : Name : Value[?Const] + */ + + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst) + }); + } // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + */ + + parseDirectives(isConst) { + const directives = []; + while (this.peek(_tokenKind.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + return directives; + } + parseConstDirectives() { + return this.parseDirectives(true); + } + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + */ + + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.AT); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst) + }); + } // Implements the parsing rules in the Types section. + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + + parseTypeReference() { + const start = this._lexer.token; + let type; + if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(_tokenKind.TokenKind.BRACKET_R); + type = this.node(start, { + kind: _kinds.Kind.LIST_TYPE, + type: innerType + }); + } else { + type = this.parseNamedType(); + } + if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { + return this.node(start, { + kind: _kinds.Kind.NON_NULL_TYPE, + type + }); + } + return type; + } + /** + * NamedType : Name + */ + + parseNamedType() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.NAMED_TYPE, + name: this.parseName() + }); + } // Implements the parsing rules in the Type Definition section. + + peekDescription() { + return this.peek(_tokenKind.TokenKind.STRING) || this.peek(_tokenKind.TokenKind.BLOCK_STRING); + } + /** + * Description : StringValue + */ + + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + */ + + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.many(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); + return this.node(start, { + kind: _kinds.Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes + }); + } + /** + * OperationTypeDefinition : OperationType : NamedType + */ + + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation, + type + }); + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives + }); + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields + }); + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + + parseImplementsInterfaces() { + return this.expectOptionalKeyword('implements') ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) : []; + } + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + */ + + parseFieldsDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseFieldDefinition, _tokenKind.TokenKind.BRACE_R); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives + }); + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + + parseArgumentDefs() { + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseInputValueDef, _tokenKind.TokenKind.PAREN_R); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives + }); + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields + }); + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types + }); + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + + parseUnionMemberTypes() { + return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values + }); + } + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + */ + + parseEnumValuesDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseEnumValueDefinition, _tokenKind.TokenKind.BRACE_R); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + */ + + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives + }); + } + /** + * EnumValue : Name but not `true`, `false` or `null` + */ + + parseEnumValueName() { + if (this._lexer.token.value === 'true' || this._lexer.token.value === 'false' || this._lexer.token.value === 'null') { + throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, `${getTokenDesc(this._lexer.token)} is reserved and cannot be used for an enum value.`); + } + return this.parseName(); + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields + }); + } + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + */ + + parseInputFieldsDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseInputValueDef, _tokenKind.TokenKind.BRACE_R); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + case 'scalar': + return this.parseScalarTypeExtension(); + case 'type': + return this.parseObjectTypeExtension(); + case 'interface': + return this.parseInterfaceTypeExtension(); + case 'union': + return this.parseUnionTypeExtension(); + case 'enum': + return this.parseEnumTypeExtension(); + case 'input': + return this.parseInputObjectTypeExtension(); + } + } + throw this.unexpected(keywordToken); + } + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + */ + + parseSchemaExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives, + operationTypes + }); + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + if (directives.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name, + directives + }); + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields + }); + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ + + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields + }); + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name, + directives, + types + }); + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values + }); + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields + }); + } + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + */ + + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + repeatable, + locations + }); + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + + parseDirectiveLocations() { + return this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseDirectiveLocation); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); + if (Object.prototype.hasOwnProperty.call(_directiveLocation.DirectiveLocation, name.value)) { + return name; + } + throw this.unexpected(start); + } // Core parsing utility functions + + /** + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. + */ + + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new _ast.Location(startToken, this._lexer.lastToken, this._lexer.source); + } + return node; + } + /** + * Determines if the next token is of a given kind + */ + + peek(kind) { + return this._lexer.token.kind === kind; + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + + expectToken(kind) { + const token = this._lexer.token; + if (token.kind === kind) { + this.advanceLexer(); + return token; + } + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`); + } + /** + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + + expectOptionalToken(kind) { + const token = this._lexer.token; + if (token.kind === kind) { + this.advanceLexer(); + return true; + } + return false; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + + expectKeyword(value) { + const token = this._lexer.token; + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + } else { + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.`); + } + } + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + */ + + expectOptionalKeyword(value) { + const token = this._lexer.token; + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + return true; + } + return false; + } + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + */ + + unexpected(atToken) { + const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.`); + } + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + return []; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ + + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ + + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + return nodes; + } + advanceLexer() { + const { + maxTokens + } = this._options; + const token = this._lexer.advance(); + if (maxTokens !== undefined && token.kind !== _tokenKind.TokenKind.EOF) { + ++this._tokenCounter; + if (this._tokenCounter > maxTokens) { + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Document contains more that ${maxTokens} tokens. Parsing aborted.`); + } + } + } + } + /** + * A helper function to describe a token as a string for debugging. + */ + exports.Parser = Parser; + function getTokenDesc(token) { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); + } + /** + * A helper function to describe a token kind as a string for debugging. + */ + + function getTokenKindDesc(kind) { + return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/predicates.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/language/predicates.mjs ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isConstValueNode = isConstValueNode; + exports.isDefinitionNode = isDefinitionNode; + exports.isExecutableDefinitionNode = isExecutableDefinitionNode; + exports.isSelectionNode = isSelectionNode; + exports.isTypeDefinitionNode = isTypeDefinitionNode; + exports.isTypeExtensionNode = isTypeExtensionNode; + exports.isTypeNode = isTypeNode; + exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; + exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; + exports.isValueNode = isValueNode; + var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); + } + function isExecutableDefinitionNode(node) { + return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; + } + function isSelectionNode(node) { + return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; + } + function isValueNode(node) { + return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; + } + function isConstValueNode(node) { + return isValueNode(node) && (node.kind === _kinds.Kind.LIST ? node.values.some(isConstValueNode) : node.kind === _kinds.Kind.OBJECT ? node.fields.some(field => isConstValueNode(field.value)) : node.kind !== _kinds.Kind.VARIABLE); + } + function isTypeNode(node) { + return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; + } + function isTypeSystemDefinitionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; + } + function isTypeDefinitionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; + } + function isTypeSystemExtensionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); + } + function isTypeExtensionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/printLocation.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/language/printLocation.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.printLocation = printLocation; + exports.printSourceLocation = printSourceLocation; + var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); + /** + * Render a helpful description of the location in the GraphQL Source document. + */ + function printLocation(location) { + return printSourceLocation(location.source, (0, _location.getLocation)(location.source, location.start)); + } + /** + * Render a helpful description of the location in the GraphQL Source document. + */ + + function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = ''.padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + return locationStr + printPrefixedLines([[`${lineNum} |`, subLines[0]], ...subLines.slice(1, subLineIndex + 1).map(subLine => ['|', subLine]), ['|', '^'.padStart(subLineColumnNum)], ['|', subLines[subLineIndex + 1]]]); + } + return locationStr + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1} |`, lines[lineIndex - 1]], [`${lineNum} |`, locationLine], ['|', '^'.padStart(columnNum)], [`${lineNum + 1} |`, lines[lineIndex + 1]]]); + } + function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')).join('\n'); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/printString.mjs": + /*!**************************************************************!*\ + !*** ../../../node_modules/graphql/language/printString.mjs ***! + \**************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.printString = printString; + /** + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + */ + function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; + } // eslint-disable-next-line no-control-regex + + const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; + } // prettier-ignore + + const escapeSequences = ['\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007', '\\b', '\\t', '\\n', '\\u000B', '\\f', '\\r', '\\u000E', '\\u000F', '\\u0010', '\\u0011', '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019', '\\u001A', '\\u001B', '\\u001C', '\\u001D', '\\u001E', '\\u001F', '', '', '\\"', '', '', '', '', '', '', '', '', '', '', '', '', '', + // 2F + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + // 3F + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + // 4F + '', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', + // 5F + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + // 6F + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\u007F', '\\u0080', '\\u0081', '\\u0082', '\\u0083', '\\u0084', '\\u0085', '\\u0086', '\\u0087', '\\u0088', '\\u0089', '\\u008A', '\\u008B', '\\u008C', '\\u008D', '\\u008E', '\\u008F', '\\u0090', '\\u0091', '\\u0092', '\\u0093', '\\u0094', '\\u0095', '\\u0096', '\\u0097', '\\u0098', '\\u0099', '\\u009A', '\\u009B', '\\u009C', '\\u009D', '\\u009E', '\\u009F']; + + /***/ }), + + /***/ "../../../node_modules/graphql/language/printer.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/language/printer.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.print = print; + var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); + var _printString = __webpack_require__(/*! ./printString.mjs */ "../../../node_modules/graphql/language/printString.mjs"); + var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); + /** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ + + function print(ast) { + return (0, _visitor.visit)(ast, printDocASTReducer); + } + const MAX_LINE_LENGTH = 80; + const printDocASTReducer = { + Name: { + leave: node => node.value + }, + Variable: { + leave: node => '$' + node.name + }, + // Document + Document: { + leave: node => join(node.definitions, '\n\n') + }, + OperationDefinition: { + leave(node) { + const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + const prefix = join([node.operation, join([node.name, varDefs]), join(node.directives, ' ')], ' '); // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; + } + }, + VariableDefinition: { + leave: ({ + variable, + type, + defaultValue, + directives + }) => variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')) + }, + SelectionSet: { + leave: ({ + selections + }) => block(selections) + }, + Field: { + leave({ + alias, + name, + arguments: args, + directives, + selectionSet + }) { + const prefix = wrap('', alias, ': ') + name; + let argsLine = prefix + wrap('(', join(args, ', '), ')'); + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + return join([argsLine, join(directives, ' '), selectionSet], ' '); + } + }, + Argument: { + leave: ({ + name, + value + }) => name + ': ' + value + }, + // Fragments + FragmentSpread: { + leave: ({ + name, + directives + }) => '...' + name + wrap(' ', join(directives, ' ')) + }, + InlineFragment: { + leave: ({ + typeCondition, + directives, + selectionSet + }) => join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ') + }, + FragmentDefinition: { + leave: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet + } // Note: fragment variable definitions are experimental and may be changed + ) => + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + selectionSet + }, + // Value + IntValue: { + leave: ({ + value + }) => value + }, + FloatValue: { + leave: ({ + value + }) => value + }, + StringValue: { + leave: ({ + value, + block: isBlockString + }) => isBlockString ? (0, _blockString.printBlockString)(value) : (0, _printString.printString)(value) + }, + BooleanValue: { + leave: ({ + value + }) => value ? 'true' : 'false' + }, + NullValue: { + leave: () => 'null' + }, + EnumValue: { + leave: ({ + value + }) => value + }, + ListValue: { + leave: ({ + values + }) => '[' + join(values, ', ') + ']' + }, + ObjectValue: { + leave: ({ + fields + }) => '{' + join(fields, ', ') + '}' + }, + ObjectField: { + leave: ({ + name, + value + }) => name + ': ' + value + }, + // Directive + Directive: { + leave: ({ + name, + arguments: args + }) => '@' + name + wrap('(', join(args, ', '), ')') + }, + // Type + NamedType: { + leave: ({ + name + }) => name + }, + ListType: { + leave: ({ + type + }) => '[' + type + ']' + }, + NonNullType: { + leave: ({ + type + }) => type + '!' + }, + // Type System Definitions + SchemaDefinition: { + leave: ({ + description, + directives, + operationTypes + }) => wrap('', description, '\n') + join(['schema', join(directives, ' '), block(operationTypes)], ' ') + }, + OperationTypeDefinition: { + leave: ({ + operation, + type + }) => operation + ': ' + type + }, + ScalarTypeDefinition: { + leave: ({ + description, + name, + directives + }) => wrap('', description, '\n') + join(['scalar', name, join(directives, ' ')], ' ') + }, + ObjectTypeDefinition: { + leave: ({ + description, + name, + interfaces, + directives, + fields + }) => wrap('', description, '\n') + join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + FieldDefinition: { + leave: ({ + description, + name, + arguments: args, + type, + directives + }) => wrap('', description, '\n') + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' ')) + }, + InputValueDefinition: { + leave: ({ + description, + name, + type, + defaultValue, + directives + }) => wrap('', description, '\n') + join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ') + }, + InterfaceTypeDefinition: { + leave: ({ + description, + name, + interfaces, + directives, + fields + }) => wrap('', description, '\n') + join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + UnionTypeDefinition: { + leave: ({ + description, + name, + directives, + types + }) => wrap('', description, '\n') + join(['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') + }, + EnumTypeDefinition: { + leave: ({ + description, + name, + directives, + values + }) => wrap('', description, '\n') + join(['enum', name, join(directives, ' '), block(values)], ' ') + }, + EnumValueDefinition: { + leave: ({ + description, + name, + directives + }) => wrap('', description, '\n') + join([name, join(directives, ' ')], ' ') + }, + InputObjectTypeDefinition: { + leave: ({ + description, + name, + directives, + fields + }) => wrap('', description, '\n') + join(['input', name, join(directives, ' '), block(fields)], ' ') + }, + DirectiveDefinition: { + leave: ({ + description, + name, + arguments: args, + repeatable, + locations + }) => wrap('', description, '\n') + 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ') + }, + SchemaExtension: { + leave: ({ + directives, + operationTypes + }) => join(['extend schema', join(directives, ' '), block(operationTypes)], ' ') + }, + ScalarTypeExtension: { + leave: ({ + name, + directives + }) => join(['extend scalar', name, join(directives, ' ')], ' ') + }, + ObjectTypeExtension: { + leave: ({ + name, + interfaces, + directives, + fields + }) => join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + InterfaceTypeExtension: { + leave: ({ + name, + interfaces, + directives, + fields + }) => join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + UnionTypeExtension: { + leave: ({ + name, + directives, + types + }) => join(['extend union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') + }, + EnumTypeExtension: { + leave: ({ + name, + directives, + values + }) => join(['extend enum', name, join(directives, ' '), block(values)], ' ') + }, + InputObjectTypeExtension: { + leave: ({ + name, + directives, + fields + }) => join(['extend input', name, join(directives, ' '), block(fields)], ' ') + } + }; + /** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + function join(maybeArray, separator = '') { + var _maybeArray$filter$jo; + return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(x => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : ''; + } + /** + * Given array, print each item on its own line, wrapped in an indented `{ }` block. + */ + + function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); + } + /** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ + + function wrap(start, maybeString, end = '') { + return maybeString != null && maybeString !== '' ? start + maybeString + end : ''; + } + function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); + } + function hasMultilineItems(maybeArray) { + var _maybeArray$some; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + return (_maybeArray$some = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some(str => str.includes('\n'))) !== null && _maybeArray$some !== void 0 ? _maybeArray$some : false; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/source.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/language/source.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Source = void 0; + exports.isSource = isSource; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); + /** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ + class Source { + constructor(body, name = 'GraphQL request', locationOffset = { + line: 1, + column: 1 + }) { + typeof body === 'string' || (0, _devAssert.devAssert)(false, `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || (0, _devAssert.devAssert)(false, 'line in locationOffset is 1-indexed and must be positive.'); + this.locationOffset.column > 0 || (0, _devAssert.devAssert)(false, 'column in locationOffset is 1-indexed and must be positive.'); + } + get [Symbol.toStringTag]() { + return 'Source'; + } + } + /** + * Test if the given value is a Source object. + * + * @internal + */ + exports.Source = Source; + function isSource(source) { + return (0, _instanceOf.instanceOf)(source, Source); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/language/tokenKind.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/language/tokenKind.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.TokenKind = void 0; + /** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ + var TokenKind; + (function (TokenKind) { + TokenKind['SOF'] = ''; + TokenKind['EOF'] = ''; + TokenKind['BANG'] = '!'; + TokenKind['DOLLAR'] = '$'; + TokenKind['AMP'] = '&'; + TokenKind['PAREN_L'] = '('; + TokenKind['PAREN_R'] = ')'; + TokenKind['SPREAD'] = '...'; + TokenKind['COLON'] = ':'; + TokenKind['EQUALS'] = '='; + TokenKind['AT'] = '@'; + TokenKind['BRACKET_L'] = '['; + TokenKind['BRACKET_R'] = ']'; + TokenKind['BRACE_L'] = '{'; + TokenKind['PIPE'] = '|'; + TokenKind['BRACE_R'] = '}'; + TokenKind['NAME'] = 'Name'; + TokenKind['INT'] = 'Int'; + TokenKind['FLOAT'] = 'Float'; + TokenKind['STRING'] = 'String'; + TokenKind['BLOCK_STRING'] = 'BlockString'; + TokenKind['COMMENT'] = 'Comment'; + })(TokenKind || (exports.TokenKind = TokenKind = {})); + + /** + * The enum type representing the token kinds values. + * + * @deprecated Please use `TokenKind`. Will be remove in v17. + */ + + /***/ }), + + /***/ "../../../node_modules/graphql/language/visitor.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/language/visitor.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.BREAK = void 0; + exports.getEnterLeaveForKind = getEnterLeaveForKind; + exports.getVisitFn = getVisitFn; + exports.visit = visit; + exports.visitInParallel = visitInParallel; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + /** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ + + const BREAK = exports.BREAK = Object.freeze({}); + /** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * ```ts + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * ``` + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to three permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * ``` + * + * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * ``` + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * ```ts + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * ``` + */ + + function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { + const enterLeaveMap = new Map(); + for (const kind of Object.values(_kinds.Kind)) { + enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); + } + /* eslint-disable no-undef-init */ + + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; } - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) { - return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - } - node = null; - offset = 0; - } else { - for (lineNode = node; ; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) { - return null; - } - if ( - lineNode.parentNode && - lineNode.parentNode == cm.display.lineDiv - ) { - break; - } - } - } - for (var i2 = 0; i2 < cm.display.view.length; i2++) { - var lineView = cm.display.view[i2]; - if (lineView.node == lineNode) { - return locateNodeInLineView(lineView, node, offset); - } - } + } + } else { + node = Object.defineProperties({}, Object.getOwnPropertyDescriptors(node)); + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } + } + } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent) { + key = inArray ? index : keys[index]; + node = parent[key]; + if (node === null || node === undefined) { + continue; + } + path.push(key); + } + let result; + if (!Array.isArray(node)) { + var _enterLeaveMap$get, _enterLeaveMap$get2; + (0, _ast.isNode)(node) || (0, _devAssert.devAssert)(false, `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`); + const visitFn = isLeaving ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get === void 0 ? void 0 : _enterLeaveMap$get.leave : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get2 === void 0 ? void 0 : _enterLeaveMap$get2.enter; + result = visitFn === null || visitFn === void 0 ? void 0 : visitFn.call(visitor, node, key, parent, path, ancestors); + if (result === BREAK) { + break; + } + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if ((0, _ast.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + if (result === undefined && isEdited) { + edits.push([key, node]); + } + if (isLeaving) { + path.pop(); + } else { + var _node$kind; + stack = { + inArray, + index, + keys, + edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : (_node$kind = visitorKeys[node.kind]) !== null && _node$kind !== void 0 ? _node$kind : []; + index = -1; + edits = []; + if (parent) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + if (edits.length !== 0) { + // New root + return edits[edits.length - 1][1]; + } + return root; + } + /** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + + function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); + for (const kind of Object.values(_kinds.Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + for (let i = 0; i < visitors.length; ++i) { + const { + enter, + leave + } = getEnterLeaveForKind(visitors[i], kind); + hasVisitor || (hasVisitor = enter != null || leave != null); + enterList[i] = enter; + leaveList[i] = leave; + } + if (!hasVisitor) { + continue; + } + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _enterList$i; + const result = (_enterList$i = enterList[i]) === null || _enterList$i === void 0 ? void 0 : _enterList$i.apply(visitors[i], args); + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; } - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, - bad = false; - if (!node || !contains(wrapper, node)) { - return badPos(Pos(lineNo(lineView.line), 0), true); - } - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest - ? lst(lineView.rest) - : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); - } - } - var textNode = node.nodeType == 3 ? node : null, - topNode = node; - if ( - !textNode && - node.childNodes.length == 1 && - node.firstChild.nodeType == 3 - ) { - textNode = node.firstChild; - if (offset) { - offset = textNode.nodeValue.length; - } - } - while (topNode.parentNode != wrapper) { - topNode = topNode.parentNode; - } - var measure = lineView.measure, - maps = measure.maps; - function find(textNode2, topNode2, offset2) { - for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { - var map2 = i2 < 0 ? measure.map : maps[i2]; - for (var j = 0; j < map2.length; j += 3) { - var curNode = map2[j + 2]; - if (curNode == textNode2 || curNode == topNode2) { - var line2 = lineNo( - i2 < 0 ? lineView.line : lineView.rest[i2] - ); - var ch = map2[j] + offset2; - if (offset2 < 0 || curNode != textNode2) { - ch = map2[j + (offset2 ? 1 : 0)]; - } - return Pos(line2, ch); - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) { - return badPos(found, bad); - } - for ( - var after = topNode.nextSibling, - dist = textNode ? textNode.nodeValue.length - offset : 0; - after; - after = after.nextSibling - ) { - found = find(after, after.firstChild, 0); - if (found) { - return badPos(Pos(found.line, found.ch - dist), bad); - } else { - dist += after.textContent.length; - } - } - for ( - var before = topNode.previousSibling, dist$1 = offset; - before; - before = before.previousSibling - ) { - found = find(before, before.firstChild, -1); - if (found) { - return badPos(Pos(found.line, found.ch + dist$1), bad); - } else { - dist$1 += before.textContent.length; - } - } + } + } + }, + leave(...args) { + const node = args[0]; + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _leaveList$i; + const result = (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 ? void 0 : _leaveList$i.apply(visitors[i], args); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; + mergedVisitor[kind] = mergedEnterLeave; + } + return mergedVisitor; + } + /** + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + */ + + function getEnterLeaveForKind(visitor, kind) { + const kindVisitor = visitor[kind]; + if (typeof kindVisitor === 'object') { + // { Kind: { enter() {}, leave() {} } } + return kindVisitor; + } else if (typeof kindVisitor === 'function') { + // { Kind() {} } + return { + enter: kindVisitor, + leave: undefined + }; + } // { enter() {}, leave() {} } + + return { + enter: visitor.enter, + leave: visitor.leave + }; + } + /** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + * + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + */ + + /* c8 ignore next 8 */ + + function getVisitFn(visitor, kind, isLeaving) { + const { + enter, + leave + } = getEnterLeaveForKind(visitor, kind); + return isLeaving ? leave : enter; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/assertName.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/assertName.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.assertEnumValueName = assertEnumValueName; + exports.assertName = assertName; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _characterClasses = __webpack_require__(/*! ../language/characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); + /** + * Upholds the spec rules about naming. + */ + + function assertName(name) { + name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); + typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + if (name.length === 0) { + throw new _GraphQLError.GraphQLError('Expected name to be a non-empty string.'); + } + for (let i = 1; i < name.length; ++i) { + if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { + throw new _GraphQLError.GraphQLError(`Names must only contain [_a-zA-Z0-9] but "${name}" does not.`); + } + } + if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { + throw new _GraphQLError.GraphQLError(`Names must start with [_a-zA-Z] but "${name}" does not.`); + } + return name; + } + /** + * Upholds the spec rules about naming enum values. + * + * @internal + */ + + function assertEnumValueName(name) { + if (name === 'true' || name === 'false' || name === 'null') { + throw new _GraphQLError.GraphQLError(`Enum values cannot be named: ${name}`); + } + return assertName(name); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/definition.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/definition.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.GraphQLUnionType = exports.GraphQLScalarType = exports.GraphQLObjectType = exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInterfaceType = exports.GraphQLInputObjectType = exports.GraphQLEnumType = void 0; + exports.argsToArgsConfig = argsToArgsConfig; + exports.assertAbstractType = assertAbstractType; + exports.assertCompositeType = assertCompositeType; + exports.assertEnumType = assertEnumType; + exports.assertInputObjectType = assertInputObjectType; + exports.assertInputType = assertInputType; + exports.assertInterfaceType = assertInterfaceType; + exports.assertLeafType = assertLeafType; + exports.assertListType = assertListType; + exports.assertNamedType = assertNamedType; + exports.assertNonNullType = assertNonNullType; + exports.assertNullableType = assertNullableType; + exports.assertObjectType = assertObjectType; + exports.assertOutputType = assertOutputType; + exports.assertScalarType = assertScalarType; + exports.assertType = assertType; + exports.assertUnionType = assertUnionType; + exports.assertWrappingType = assertWrappingType; + exports.defineArguments = defineArguments; + exports.getNamedType = getNamedType; + exports.getNullableType = getNullableType; + exports.isAbstractType = isAbstractType; + exports.isCompositeType = isCompositeType; + exports.isEnumType = isEnumType; + exports.isInputObjectType = isInputObjectType; + exports.isInputType = isInputType; + exports.isInterfaceType = isInterfaceType; + exports.isLeafType = isLeafType; + exports.isListType = isListType; + exports.isNamedType = isNamedType; + exports.isNonNullType = isNonNullType; + exports.isNullableType = isNullableType; + exports.isObjectType = isObjectType; + exports.isOutputType = isOutputType; + exports.isRequiredArgument = isRequiredArgument; + exports.isRequiredInputField = isRequiredInputField; + exports.isScalarType = isScalarType; + exports.isType = isType; + exports.isUnionType = isUnionType; + exports.isWrappingType = isWrappingType; + exports.resolveObjMapThunk = resolveObjMapThunk; + exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _identityFunc = __webpack_require__(/*! ../jsutils/identityFunc.mjs */ "../../../node_modules/graphql/jsutils/identityFunc.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); + var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); + var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _valueFromASTUntyped = __webpack_require__(/*! ../utilities/valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); + var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); + function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); + } + function assertType(type) { + if (!isType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`); + } + return type; + } + /** + * There are predicates for each kind of GraphQL type. + */ + + function isScalarType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); + } + function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`); + } + return type; + } + function isObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); + } + function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`); + } + return type; + } + function isInterfaceType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); + } + function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`); + } + return type; + } + function isUnionType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); + } + function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`); + } + return type; + } + function isEnumType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); + } + function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`); + } + return type; + } + function isInputObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); + } + function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Input Object type.`); + } + return type; + } + function isListType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLList); + } + function assertListType(type) { + if (!isListType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`); + } + return type; + } + function isNonNullType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); + } + function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`); + } + return type; + } + /** + * These types may be used as input types for arguments and directives. + */ + + function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); + } + function assertInputType(type) { + if (!isInputType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`); + } + return type; + } + /** + * These types may be used as output types as the result of fields. + */ + + function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); + } + function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`); + } + return type; + } + /** + * These types may describe types which may be leaf values. + */ + + function isLeafType(type) { + return isScalarType(type) || isEnumType(type); + } + function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`); + } + return type; + } + /** + * These types may describe the parent context of a selection set. + */ + + function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); + } + function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`); + } + return type; + } + /** + * These types may describe the parent context of a selection set. + */ + + function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); + } + function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`); + } + return type; + } + /** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ + + class GraphQLList { + constructor(ofType) { + isType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return 'GraphQLList'; + } + toString() { + return '[' + String(this.ofType) + ']'; + } + toJSON() { + return this.toString(); + } + } + /** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * Note: the enforcement of non-nullability occurs within the executor. + */ + exports.GraphQLList = GraphQLList; + class GraphQLNonNull { + constructor(ofType) { + isNullableType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL nullable type.`); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return 'GraphQLNonNull'; + } + toString() { + return String(this.ofType) + '!'; + } + toJSON() { + return this.toString(); + } + } + /** + * These types wrap and modify other types + */ + exports.GraphQLNonNull = GraphQLNonNull; + function isWrappingType(type) { + return isListType(type) || isNonNullType(type); + } + function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`); + } + return type; + } + /** + * These types can all accept null as a value. + */ + + function isNullableType(type) { + return isType(type) && !isNonNullType(type); + } + function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`); + } + return type; + } + function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } + } + /** + * These named types do not include modifiers like List or NonNull. + */ + + function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); + } + function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`); + } + return type; + } + function getNamedType(type) { + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } + } + /** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + + function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; + } + function resolveObjMapThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; + } + /** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + + /** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. It is always better to validate + * + * Example: + * + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } + * + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` + */ + class GraphQLScalarType { + constructor(config) { + var _config$parseValue, _config$serialize, _config$parseLiteral, _config$extensionASTN; + const parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : _identityFunc.identityFunc; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : _identityFunc.identityFunc; + this.parseValue = parseValue; + this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : (node, variables) => parseValue((0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables)); + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; + config.specifiedByURL == null || typeof config.specifiedByURL === 'string' || (0, _devAssert.devAssert)(false, `${this.name} must provide "specifiedByURL" as a string, ` + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`); + config.serialize == null || typeof config.serialize === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`); + if (config.parseLiteral) { + typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide both "parseValue" and "parseLiteral" functions.`); + } + } + get [Symbol.toStringTag]() { + return 'GraphQLScalarType'; + } + toConfig() { + return { + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + + /** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` + */ + exports.GraphQLScalarType = GraphQLScalarType; + class GraphQLObjectType { + constructor(config) { + var _config$extensionASTN2; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN2 = config.extensionASTNodes) !== null && _config$extensionASTN2 !== void 0 ? _config$extensionASTN2 : []; + this._fields = () => defineFieldMap(config); + this._interfaces = () => defineInterfaces(config); + config.isTypeOf == null || typeof config.isTypeOf === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "isTypeOf" as a function, ` + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`); + } + get [Symbol.toStringTag]() { + return 'GraphQLObjectType'; + } + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLObjectType = GraphQLObjectType; + function defineInterfaces(config) { + var _config$interfaces; + const interfaces = resolveReadonlyArrayThunk((_config$interfaces = config.interfaces) !== null && _config$interfaces !== void 0 ? _config$interfaces : []); + Array.isArray(interfaces) || (0, _devAssert.devAssert)(false, `${config.name} interfaces must be an Array or a function which returns an Array.`); + return interfaces; + } + function defineFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + var _fieldConfig$args; + isPlainObj(fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field config must be an object.`); + fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`); + const argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {}; + isPlainObj(argsConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} args must be an object with argument names as keys.`); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + args: defineArguments(argsConfig), + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); + } + function defineArguments(config) { + return Object.entries(config).map(([argName, argConfig]) => ({ + name: (0, _assertName.assertName)(argName), + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), + astNode: argConfig.astNode + })); + } + function isPlainObj(obj) { + return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); + } + function fieldsToFieldsConfig(fields) { + return (0, _mapValue.mapValue)(fields, field => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + })); + } + /** + * @internal + */ + + function argsToArgsConfig(args) { + return (0, _keyValMap.keyValMap)(args, arg => arg.name, arg => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode + })); + } + function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; + } + + /** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ + class GraphQLInterfaceType { + constructor(config) { + var _config$extensionASTN3; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN3 = config.extensionASTNodes) !== null && _config$extensionASTN3 !== void 0 ? _config$extensionASTN3 : []; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); + } + get [Symbol.toStringTag]() { + return 'GraphQLInterfaceType'; + } + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + + /** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ + exports.GraphQLInterfaceType = GraphQLInterfaceType; + class GraphQLUnionType { + constructor(config) { + var _config$extensionASTN4; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN4 = config.extensionASTNodes) !== null && _config$extensionASTN4 !== void 0 ? _config$extensionASTN4 : []; + this._types = defineTypes.bind(undefined, config); + config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); + } + get [Symbol.toStringTag]() { + return 'GraphQLUnionType'; + } + getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + return this._types; + } + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLUnionType = GraphQLUnionType; + function defineTypes(config) { + const types = resolveReadonlyArrayThunk(config.types); + Array.isArray(types) || (0, _devAssert.devAssert)(false, `Must provide Array of types or a function which returns such an array for Union ${config.name}.`); + return types; + } + + /** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * ```ts + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ + class GraphQLEnumType { + /* */ + constructor(config) { + var _config$extensionASTN5; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN5 = config.extensionASTNodes) !== null && _config$extensionASTN5 !== void 0 ? _config$extensionASTN5 : []; + this._values = defineEnumValues(this.name, config.values); + this._valueLookup = new Map(this._values.map(enumValue => [enumValue.value, enumValue])); + this._nameLookup = (0, _keyMap.keyMap)(this._values, value => value.name); + } + get [Symbol.toStringTag]() { + return 'GraphQLEnumType'; + } + getValues() { + return this._values; + } + getValue(name) { + return this._nameLookup[name]; + } + serialize(outputValue) { + const enumValue = this._valueLookup.get(outputValue); + if (enumValue === undefined) { + throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); + } + return enumValue.name; + } + parseValue(inputValue) /* T */ + { + if (typeof inputValue !== 'string') { + const valueStr = (0, _inspect.inspect)(inputValue); + throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr)); + } + const enumValue = this.getValue(inputValue); + if (enumValue == null) { + throw new _GraphQLError.GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue)); + } + return enumValue.value; + } + parseLiteral(valueNode, _variables) /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== _kinds.Kind.ENUM) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr), { + nodes: valueNode + }); + } + const enumValue = this.getValue(valueNode.value); + if (enumValue == null) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr), { + nodes: valueNode + }); + } + return enumValue.value; + } + toConfig() { + const values = (0, _keyValMap.keyValMap)(this.getValues(), value => value.name, value => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode + })); + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLEnumType = GraphQLEnumType; + function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map(value => value.name); + const suggestedValues = (0, _suggestionList.suggestionList)(unknownValueStr, allNames); + return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); + } + function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || (0, _devAssert.devAssert)(false, `${typeName} values must be an object with value names as keys.`); + return Object.entries(valueMap).map(([valueName, valueConfig]) => { + isPlainObj(valueConfig) || (0, _devAssert.devAssert)(false, `${typeName}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${(0, _inspect.inspect)(valueConfig)}.`); + return { + name: (0, _assertName.assertEnumValueName)(valueName), + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + deprecationReason: valueConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), + astNode: valueConfig.astNode + }; + }); + } + + /** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` + */ + class GraphQLInputObjectType { + constructor(config) { + var _config$extensionASTN6; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN6 = config.extensionASTNodes) !== null && _config$extensionASTN6 !== void 0 ? _config$extensionASTN6 : []; + this._fields = defineInputFieldMap.bind(undefined, config); + } + get [Symbol.toStringTag]() { + return 'GraphQLInputObjectType'; + } + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + toConfig() { + const fields = (0, _mapValue.mapValue)(this.getFields(), field => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + })); + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLInputObjectType = GraphQLInputObjectType; + function defineInputFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + !('resolve' in fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); + } + function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/directives.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/directives.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.GraphQLSpecifiedByDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = void 0; + exports.assertDirective = assertDirective; + exports.isDirective = isDirective; + exports.isSpecifiedDirective = isSpecifiedDirective; + exports.specifiedDirectives = void 0; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); + var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); + var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); + var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + /** + * Test if the given value is a GraphQL directive. + */ + + function isDirective(directive) { + return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); + } + function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error(`Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`); + } + return directive; + } + /** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + + /** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + class GraphQLDirective { + constructor(config) { + var _config$isRepeatable, _config$args; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + Array.isArray(config.locations) || (0, _devAssert.devAssert)(false, `@${config.name} locations must be an Array.`); + const args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {}; + (0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args) || (0, _devAssert.devAssert)(false, `@${config.name} args must be an object with argument names as keys.`); + this.args = (0, _definition.defineArguments)(args); + } + get [Symbol.toStringTag]() { + return 'GraphQLDirective'; + } + toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: (0, _definition.argsToArgsConfig)(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode + }; + } + toString() { + return '@' + this.name; + } + toJSON() { + return this.toString(); + } + } + + /** + * Used to conditionally include fields or fragments. + */ + exports.GraphQLDirective = GraphQLDirective; + const GraphQLIncludeDirective = exports.GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Included when true.' + } + } + }); + /** + * Used to conditionally skip (exclude) fields or fragments. + */ + + const GraphQLSkipDirective = exports.GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Skipped when true.' + } + } + }); + /** + * Constant string used for default reason for a deprecation. + */ + + const DEFAULT_DEPRECATION_REASON = exports.DEFAULT_DEPRECATION_REASON = 'No longer supported'; + /** + * Used to declare element of a GraphQL schema as deprecated. + */ + + const GraphQLDeprecatedDirective = exports.GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: _scalars.GraphQLString, + description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } + }); + /** + * Used to provide a URL for specifying the behavior of custom scalar definitions. + */ + + const GraphQLSpecifiedByDirective = exports.GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behavior of this scalar.', + locations: [_directiveLocation.DirectiveLocation.SCALAR], + args: { + url: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The URL that specifies the behavior of this scalar.' + } + } + }); + /** + * The full list of specified directives. + */ + + const specifiedDirectives = exports.specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]); + function isSpecifiedDirective(directive) { + return specifiedDirectives.some(({ + name + }) => name === directive.name); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/index.mjs": + /*!****************************************************!*\ + !*** ../../../node_modules/graphql/type/index.mjs ***! + \****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ + enumerable: true, + get: function () { + return _directives.DEFAULT_DEPRECATION_REASON; + } + })); + Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MAX_INT; + } + })); + Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MIN_INT; + } + })); + Object.defineProperty(exports, "GraphQLBoolean", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLBoolean; + } + })); + Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLDeprecatedDirective; + } + })); + Object.defineProperty(exports, "GraphQLDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLDirective; + } + })); + Object.defineProperty(exports, "GraphQLEnumType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLEnumType; + } + })); + Object.defineProperty(exports, "GraphQLFloat", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLFloat; + } + })); + Object.defineProperty(exports, "GraphQLID", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLID; + } + })); + Object.defineProperty(exports, "GraphQLIncludeDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLIncludeDirective; + } + })); + Object.defineProperty(exports, "GraphQLInputObjectType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLInputObjectType; + } + })); + Object.defineProperty(exports, "GraphQLInt", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLInt; + } + })); + Object.defineProperty(exports, "GraphQLInterfaceType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLInterfaceType; + } + })); + Object.defineProperty(exports, "GraphQLList", ({ + enumerable: true, + get: function () { + return _definition.GraphQLList; + } + })); + Object.defineProperty(exports, "GraphQLNonNull", ({ + enumerable: true, + get: function () { + return _definition.GraphQLNonNull; + } + })); + Object.defineProperty(exports, "GraphQLObjectType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLObjectType; + } + })); + Object.defineProperty(exports, "GraphQLScalarType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLScalarType; + } + })); + Object.defineProperty(exports, "GraphQLSchema", ({ + enumerable: true, + get: function () { + return _schema.GraphQLSchema; + } + })); + Object.defineProperty(exports, "GraphQLSkipDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLSkipDirective; + } + })); + Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLSpecifiedByDirective; + } + })); + Object.defineProperty(exports, "GraphQLString", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLString; + } + })); + Object.defineProperty(exports, "GraphQLUnionType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLUnionType; + } + })); + Object.defineProperty(exports, "SchemaMetaFieldDef", ({ + enumerable: true, + get: function () { + return _introspection.SchemaMetaFieldDef; + } + })); + Object.defineProperty(exports, "TypeKind", ({ + enumerable: true, + get: function () { + return _introspection.TypeKind; + } + })); + Object.defineProperty(exports, "TypeMetaFieldDef", ({ + enumerable: true, + get: function () { + return _introspection.TypeMetaFieldDef; + } + })); + Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ + enumerable: true, + get: function () { + return _introspection.TypeNameMetaFieldDef; + } + })); + Object.defineProperty(exports, "__Directive", ({ + enumerable: true, + get: function () { + return _introspection.__Directive; + } + })); + Object.defineProperty(exports, "__DirectiveLocation", ({ + enumerable: true, + get: function () { + return _introspection.__DirectiveLocation; + } + })); + Object.defineProperty(exports, "__EnumValue", ({ + enumerable: true, + get: function () { + return _introspection.__EnumValue; + } + })); + Object.defineProperty(exports, "__Field", ({ + enumerable: true, + get: function () { + return _introspection.__Field; + } + })); + Object.defineProperty(exports, "__InputValue", ({ + enumerable: true, + get: function () { + return _introspection.__InputValue; + } + })); + Object.defineProperty(exports, "__Schema", ({ + enumerable: true, + get: function () { + return _introspection.__Schema; + } + })); + Object.defineProperty(exports, "__Type", ({ + enumerable: true, + get: function () { + return _introspection.__Type; + } + })); + Object.defineProperty(exports, "__TypeKind", ({ + enumerable: true, + get: function () { + return _introspection.__TypeKind; + } + })); + Object.defineProperty(exports, "assertAbstractType", ({ + enumerable: true, + get: function () { + return _definition.assertAbstractType; + } + })); + Object.defineProperty(exports, "assertCompositeType", ({ + enumerable: true, + get: function () { + return _definition.assertCompositeType; + } + })); + Object.defineProperty(exports, "assertDirective", ({ + enumerable: true, + get: function () { + return _directives.assertDirective; + } + })); + Object.defineProperty(exports, "assertEnumType", ({ + enumerable: true, + get: function () { + return _definition.assertEnumType; + } + })); + Object.defineProperty(exports, "assertEnumValueName", ({ + enumerable: true, + get: function () { + return _assertName.assertEnumValueName; + } + })); + Object.defineProperty(exports, "assertInputObjectType", ({ + enumerable: true, + get: function () { + return _definition.assertInputObjectType; + } + })); + Object.defineProperty(exports, "assertInputType", ({ + enumerable: true, + get: function () { + return _definition.assertInputType; + } + })); + Object.defineProperty(exports, "assertInterfaceType", ({ + enumerable: true, + get: function () { + return _definition.assertInterfaceType; + } + })); + Object.defineProperty(exports, "assertLeafType", ({ + enumerable: true, + get: function () { + return _definition.assertLeafType; + } + })); + Object.defineProperty(exports, "assertListType", ({ + enumerable: true, + get: function () { + return _definition.assertListType; + } + })); + Object.defineProperty(exports, "assertName", ({ + enumerable: true, + get: function () { + return _assertName.assertName; + } + })); + Object.defineProperty(exports, "assertNamedType", ({ + enumerable: true, + get: function () { + return _definition.assertNamedType; + } + })); + Object.defineProperty(exports, "assertNonNullType", ({ + enumerable: true, + get: function () { + return _definition.assertNonNullType; + } + })); + Object.defineProperty(exports, "assertNullableType", ({ + enumerable: true, + get: function () { + return _definition.assertNullableType; + } + })); + Object.defineProperty(exports, "assertObjectType", ({ + enumerable: true, + get: function () { + return _definition.assertObjectType; + } + })); + Object.defineProperty(exports, "assertOutputType", ({ + enumerable: true, + get: function () { + return _definition.assertOutputType; + } + })); + Object.defineProperty(exports, "assertScalarType", ({ + enumerable: true, + get: function () { + return _definition.assertScalarType; + } + })); + Object.defineProperty(exports, "assertSchema", ({ + enumerable: true, + get: function () { + return _schema.assertSchema; + } + })); + Object.defineProperty(exports, "assertType", ({ + enumerable: true, + get: function () { + return _definition.assertType; + } + })); + Object.defineProperty(exports, "assertUnionType", ({ + enumerable: true, + get: function () { + return _definition.assertUnionType; + } + })); + Object.defineProperty(exports, "assertValidSchema", ({ + enumerable: true, + get: function () { + return _validate.assertValidSchema; + } + })); + Object.defineProperty(exports, "assertWrappingType", ({ + enumerable: true, + get: function () { + return _definition.assertWrappingType; + } + })); + Object.defineProperty(exports, "getNamedType", ({ + enumerable: true, + get: function () { + return _definition.getNamedType; + } + })); + Object.defineProperty(exports, "getNullableType", ({ + enumerable: true, + get: function () { + return _definition.getNullableType; + } + })); + Object.defineProperty(exports, "introspectionTypes", ({ + enumerable: true, + get: function () { + return _introspection.introspectionTypes; + } + })); + Object.defineProperty(exports, "isAbstractType", ({ + enumerable: true, + get: function () { + return _definition.isAbstractType; + } + })); + Object.defineProperty(exports, "isCompositeType", ({ + enumerable: true, + get: function () { + return _definition.isCompositeType; + } + })); + Object.defineProperty(exports, "isDirective", ({ + enumerable: true, + get: function () { + return _directives.isDirective; + } + })); + Object.defineProperty(exports, "isEnumType", ({ + enumerable: true, + get: function () { + return _definition.isEnumType; + } + })); + Object.defineProperty(exports, "isInputObjectType", ({ + enumerable: true, + get: function () { + return _definition.isInputObjectType; + } + })); + Object.defineProperty(exports, "isInputType", ({ + enumerable: true, + get: function () { + return _definition.isInputType; + } + })); + Object.defineProperty(exports, "isInterfaceType", ({ + enumerable: true, + get: function () { + return _definition.isInterfaceType; + } + })); + Object.defineProperty(exports, "isIntrospectionType", ({ + enumerable: true, + get: function () { + return _introspection.isIntrospectionType; + } + })); + Object.defineProperty(exports, "isLeafType", ({ + enumerable: true, + get: function () { + return _definition.isLeafType; + } + })); + Object.defineProperty(exports, "isListType", ({ + enumerable: true, + get: function () { + return _definition.isListType; + } + })); + Object.defineProperty(exports, "isNamedType", ({ + enumerable: true, + get: function () { + return _definition.isNamedType; + } + })); + Object.defineProperty(exports, "isNonNullType", ({ + enumerable: true, + get: function () { + return _definition.isNonNullType; + } + })); + Object.defineProperty(exports, "isNullableType", ({ + enumerable: true, + get: function () { + return _definition.isNullableType; + } + })); + Object.defineProperty(exports, "isObjectType", ({ + enumerable: true, + get: function () { + return _definition.isObjectType; + } + })); + Object.defineProperty(exports, "isOutputType", ({ + enumerable: true, + get: function () { + return _definition.isOutputType; + } + })); + Object.defineProperty(exports, "isRequiredArgument", ({ + enumerable: true, + get: function () { + return _definition.isRequiredArgument; + } + })); + Object.defineProperty(exports, "isRequiredInputField", ({ + enumerable: true, + get: function () { + return _definition.isRequiredInputField; + } + })); + Object.defineProperty(exports, "isScalarType", ({ + enumerable: true, + get: function () { + return _definition.isScalarType; + } + })); + Object.defineProperty(exports, "isSchema", ({ + enumerable: true, + get: function () { + return _schema.isSchema; + } + })); + Object.defineProperty(exports, "isSpecifiedDirective", ({ + enumerable: true, + get: function () { + return _directives.isSpecifiedDirective; + } + })); + Object.defineProperty(exports, "isSpecifiedScalarType", ({ + enumerable: true, + get: function () { + return _scalars.isSpecifiedScalarType; + } + })); + Object.defineProperty(exports, "isType", ({ + enumerable: true, + get: function () { + return _definition.isType; + } + })); + Object.defineProperty(exports, "isUnionType", ({ + enumerable: true, + get: function () { + return _definition.isUnionType; + } + })); + Object.defineProperty(exports, "isWrappingType", ({ + enumerable: true, + get: function () { + return _definition.isWrappingType; + } + })); + Object.defineProperty(exports, "resolveObjMapThunk", ({ + enumerable: true, + get: function () { + return _definition.resolveObjMapThunk; + } + })); + Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ + enumerable: true, + get: function () { + return _definition.resolveReadonlyArrayThunk; + } + })); + Object.defineProperty(exports, "specifiedDirectives", ({ + enumerable: true, + get: function () { + return _directives.specifiedDirectives; + } + })); + Object.defineProperty(exports, "specifiedScalarTypes", ({ + enumerable: true, + get: function () { + return _scalars.specifiedScalarTypes; + } + })); + Object.defineProperty(exports, "validateSchema", ({ + enumerable: true, + get: function () { + return _validate.validateSchema; + } + })); + var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); + var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); + var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/type/introspection.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/type/introspection.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.introspectionTypes = exports.__TypeKind = exports.__Type = exports.__Schema = exports.__InputValue = exports.__Field = exports.__EnumValue = exports.__DirectiveLocation = exports.__Directive = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.TypeKind = exports.SchemaMetaFieldDef = void 0; + exports.isIntrospectionType = isIntrospectionType; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); + var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _astFromValue = __webpack_require__(/*! ../utilities/astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); + var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + const __Schema = exports.__Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', + fields: () => ({ + description: { + type: _scalars.GraphQLString, + resolve: schema => schema.description + }, + types: { + description: 'A list of all types supported by this server.', + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))), + resolve(schema) { + return Object.values(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new _definition.GraphQLNonNull(__Type), + resolve: schema => schema.getQueryType() + }, + mutationType: { + description: 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: schema => schema.getMutationType() + }, + subscriptionType: { + description: 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: schema => schema.getSubscriptionType() + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))), + resolve: schema => schema.getDirectives() + } + }) + }); + const __Directive = exports.__Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: directive => directive.name + }, + description: { + type: _scalars.GraphQLString, + resolve: directive => directive.description + }, + isRepeatable: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: directive => directive.isRepeatable + }, + locations: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation))), + resolve: directive => directive.locations + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(field, { + includeDeprecated + }) { + return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); + } + } + }) + }); + const __DirectiveLocation = exports.__DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } + }); + const __Type = exports.__Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', + fields: () => ({ + kind: { + type: new _definition.GraphQLNonNull(__TypeKind), + resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } + if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } + if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } + if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } + if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } + if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } + if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } + if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered) + + false || (0, _invariant.invariant)(false, `Unexpected type: "${(0, _inspect.inspect)(type)}".`); + } + }, + name: { + type: _scalars.GraphQLString, + resolve: type => 'name' in type ? type.name : undefined + }, + description: { + type: _scalars.GraphQLString, + resolve: (type // FIXME: add test case + ) => /* c8 ignore next */ + 'description' in type ? type.description : undefined + }, + specifiedByURL: { + type: _scalars.GraphQLString, + resolve: obj => 'specifiedByURL' in obj ? obj.specifiedByURL : undefined + }, + fields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(type, { + includeDeprecated + }) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + const fields = Object.values(type.getFields()); + return includeDeprecated ? fields : fields.filter(field => field.deprecationReason == null); + } + } + }, + interfaces: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve(type) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve(type, _args, _context, { + schema + }) { + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(type, { + includeDeprecated + }) { + if ((0, _definition.isEnumType)(type)) { + const values = type.getValues(); + return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); + } + } + }, + inputFields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(type, { + includeDeprecated + }) { + if ((0, _definition.isInputObjectType)(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); + } + } + }, + ofType: { + type: __Type, + resolve: type => 'ofType' in type ? type.ofType : undefined + } + }) + }); + const __Field = exports.__Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: field => field.name + }, + description: { + type: _scalars.GraphQLString, + resolve: field => field.description + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(field, { + includeDeprecated + }) { + return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); + } + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: field => field.type + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: field => field.deprecationReason != null + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: field => field.deprecationReason + } + }) + }); + const __InputValue = exports.__InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: inputValue => inputValue.name + }, + description: { + type: _scalars.GraphQLString, + resolve: inputValue => inputValue.description + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: inputValue => inputValue.type + }, + defaultValue: { + type: _scalars.GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this input value.', + resolve(inputValue) { + const { + type, + defaultValue + } = inputValue; + const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); + return valueAST ? (0, _printer.print)(valueAST) : null; + } + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: field => field.deprecationReason != null + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: obj => obj.deprecationReason + } + }) + }); + const __EnumValue = exports.__EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: enumValue => enumValue.name + }, + description: { + type: _scalars.GraphQLString, + resolve: enumValue => enumValue.description + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: enumValue => enumValue.deprecationReason != null + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: enumValue => enumValue.deprecationReason + } + }) + }); + var TypeKind; + (function (TypeKind) { + TypeKind['SCALAR'] = 'SCALAR'; + TypeKind['OBJECT'] = 'OBJECT'; + TypeKind['INTERFACE'] = 'INTERFACE'; + TypeKind['UNION'] = 'UNION'; + TypeKind['ENUM'] = 'ENUM'; + TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; + TypeKind['LIST'] = 'LIST'; + TypeKind['NON_NULL'] = 'NON_NULL'; + })(TypeKind || (exports.TypeKind = TypeKind = {})); + const __TypeKind = exports.__TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. `inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } + }); + /** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + + const SchemaMetaFieldDef = exports.SchemaMetaFieldDef = { + name: '__schema', + type: new _definition.GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (_source, _args, _context, { + schema + }) => schema, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined + }; + const TypeMetaFieldDef = exports.TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + description: undefined, + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined + }], + resolve: (_source, { + name + }, _context, { + schema + }) => schema.getType(name), + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined + }; + const TypeNameMetaFieldDef = exports.TypeNameMetaFieldDef = { + name: '__typename', + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (_source, _args, _context, { + parentType + }) => parentType.name, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined + }; + const introspectionTypes = exports.introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]); + function isIntrospectionType(type) { + return introspectionTypes.some(({ + name + }) => type.name === name); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/scalars.mjs": + /*!******************************************************!*\ + !*** ../../../node_modules/graphql/type/scalars.mjs ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.GraphQLString = exports.GraphQLInt = exports.GraphQLID = exports.GraphQLFloat = exports.GraphQLBoolean = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = void 0; + exports.isSpecifiedScalarType = isSpecifiedScalarType; + exports.specifiedScalarTypes = void 0; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + * */ + + const GRAPHQL_MAX_INT = exports.GRAPHQL_MAX_INT = 2147483647; + /** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + * */ + + const GRAPHQL_MIN_INT = exports.GRAPHQL_MIN_INT = -2147483648; + const GraphQLInt = exports.GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + let num = coercedValue; + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + if (typeof num !== 'number' || !Number.isInteger(num)) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(coercedValue)}`); + } + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError('Int cannot represent non 32-bit signed integer value: ' + (0, _inspect.inspect)(coercedValue)); + } + return num; + }, + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(inputValue)}`); + } + if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${inputValue}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _printer.print)(valueNode)}`, { + nodes: valueNode + }); + } + const num = parseInt(valueNode.value, 10); + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, { + nodes: valueNode + }); + } + return num; + } + }); + const GraphQLFloat = exports.GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + let num = coercedValue; + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + if (typeof num !== 'number' || !Number.isFinite(num)) { + throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(coercedValue)}`); + } + return num; + }, + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { + throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(inputValue)}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.FLOAT && valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _printer.print)(valueNode)}`, valueNode); + } + return parseFloat(valueNode.value); + } + }); + const GraphQLString = exports.GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; + } + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { + return coercedValue.toString(); + } + throw new _GraphQLError.GraphQLError(`String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); + }, + parseValue(inputValue) { + if (typeof inputValue !== 'string') { + throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _inspect.inspect)(inputValue)}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING) { + throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _printer.print)(valueNode)}`, { + nodes: valueNode + }); + } + return valueNode.value; + } + }); + const GraphQLBoolean = exports.GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + if (Number.isFinite(coercedValue)) { + return coercedValue !== 0; + } + throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(coercedValue)}`); + }, + parseValue(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(inputValue)}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.BOOLEAN) { + throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _printer.print)(valueNode)}`, { + nodes: valueNode + }); + } + return valueNode.value; + } + }); + const GraphQLID = exports.GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'string') { + return coercedValue; + } + if (Number.isInteger(coercedValue)) { + return String(coercedValue); + } + throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); + }, + parseValue(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; + } + if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { + return inputValue.toString(); + } + throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`); + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING && valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError('ID cannot represent a non-string and non-integer value: ' + (0, _printer.print)(valueNode), { + nodes: valueNode + }); + } + return valueNode.value; + } + }); + const specifiedScalarTypes = exports.specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]); + function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(({ + name + }) => type.name === name); + } // Support serializing objects with custom valueOf() or toJSON() functions - + // a common way to represent a complex value which can be represented as + // a string (ex: MongoDB id objects). + + function serializeObject(outputValue) { + if ((0, _isObjectLike.isObjectLike)(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + const valueOfResult = outputValue.valueOf(); + if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { + return valueOfResult; + } + } + if (typeof outputValue.toJSON === 'function') { + return outputValue.toJSON(); + } + } + return outputValue; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/schema.mjs": + /*!*****************************************************!*\ + !*** ../../../node_modules/graphql/type/schema.mjs ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.GraphQLSchema = void 0; + exports.assertSchema = assertSchema; + exports.isSchema = isSchema; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); + var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + /** + * Test if the given value is a GraphQL schema. + */ + + function isSchema(schema) { + return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); + } + function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error(`Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`); + } + return schema; + } + /** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + + /** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * ``` + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * ``` + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * ``` + */ + class GraphQLSchema { + // Used as a cache for validateSchema(). + constructor(config) { + var _config$extensionASTN, _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + (0, _isObjectLike.isObjectLike)(config) || (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); + !config.types || Array.isArray(config.types) || (0, _devAssert.devAssert)(false, `"types" must be Array if provided but got: ${(0, _inspect.inspect)(config.types)}.`); + !config.directives || Array.isArray(config.directives) || (0, _devAssert.devAssert)(false, '"directives" must be Array if provided but got: ' + `${(0, _inspect.inspect)(config.directives)}.`); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + const allReferencedTypes = new Set(config.types); + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if ((0, _directives.isDirective)(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + const typeName = namedType.name; + typeName || (0, _devAssert.devAssert)(false, 'One of the provided types for building the Schema is missing a name.'); + if (this._typeMap[typeName] !== undefined) { + throw new Error(`Schema must contain uniquely named types but contains multiple types named "${typeName}".`); + } + this._typeMap[typeName] = namedType; + if ((0, _definition.isInterfaceType)(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; } - var TextareaInput = function (cm) { - this.cm = cm; - this.prevInput = ""; - this.pollingFast = false; - this.polling = new Delayed(); - this.hasSelection = false; - this.composing = null; - }; - TextareaInput.prototype.init = function (display) { - var this$1$1 = this; - var input = this, - cm = this.cm; - this.createField(display); - var te = this.textarea; - display.wrapper.insertBefore( - this.wrapper, - display.wrapper.firstChild - ); - if (ios) { - te.style.width = "0px"; - } - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1$1.hasSelection) { - this$1$1.hasSelection = null; - } - input.poll(); - }); - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; - } - cm.state.pasteIncoming = +(/* @__PURE__ */ new Date()); - input.fastPoll(); - }); - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) { - return; - } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections(), - }); - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text, - }); - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") { - cm.state.cutIncoming = +(/* @__PURE__ */ new Date()); - } - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - on(display.scroller, "paste", function (e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { - return; - } - if (!te.dispatchEvent) { - cm.state.pasteIncoming = +(/* @__PURE__ */ new Date()); - input.focus(); - return; - } - var event = new Event("paste"); - event.clipboardData = e.clipboardData; - te.dispatchEvent(event); - }); - on(display.lineSpace, "selectstart", function (e) { - if (!eventInWidget(display, e)) { - e_preventDefault(e); - } - }); - on(te, "compositionstart", function () { - var start = cm.getCursor("from"); - if (input.composing) { - input.composing.range.clear(); - } - input.composing = { - start, - range: cm.markText(start, cm.getCursor("to"), { - className: "CodeMirror-composing", - }), - }; - }); - on(te, "compositionend", function () { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }; - TextareaInput.prototype.createField = function (_display) { - this.wrapper = hiddenTextarea(); - this.textarea = this.wrapper.firstChild; - }; - TextareaInput.prototype.screenReaderLabelChanged = function ( - label - ) { - if (label) { - this.textarea.setAttribute("aria-label", label); - } else { - this.textarea.removeAttribute("aria-label"); - } - }; - TextareaInput.prototype.prepareSelection = function () { - var cm = this.cm, - display = cm.display, - doc = cm.doc; - var result = prepareSelection(cm); - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), - lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max( - 0, - Math.min( - display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top - ) - ); - result.teLeft = Math.max( - 0, - Math.min( - display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left - ) - ); - } - return result; - }; - TextareaInput.prototype.showSelection = function (drawn) { - var cm = this.cm, - display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }; - TextareaInput.prototype.reset = function (typing) { - if (this.contextMenuPending || this.composing) { - return; - } - var cm = this.cm; - if (cm.somethingSelected()) { - this.prevInput = ""; - var content = cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) { - selectInput(this.textarea); - } - if (ie && ie_version >= 9) { - this.hasSelection = content; - } - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) { - this.hasSelection = null; - } - } - }; - TextareaInput.prototype.getField = function () { - return this.textarea; - }; - TextareaInput.prototype.supportsTouch = function () { - return false; - }; - TextareaInput.prototype.focus = function () { - if ( - this.cm.options.readOnly != "nocursor" && - (!mobile || activeElt() != this.textarea) - ) { - try { - this.textarea.focus(); - } catch (e) {} - } - }; - TextareaInput.prototype.blur = function () { - this.textarea.blur(); - }; - TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; - }; - TextareaInput.prototype.receivedFocus = function () { - this.slowPoll(); - }; - TextareaInput.prototype.slowPoll = function () { - var this$1$1 = this; - if (this.pollingFast) { - return; - } - this.polling.set(this.cm.options.pollInterval, function () { - this$1$1.poll(); - if (this$1$1.cm.state.focused) { - this$1$1.slowPoll(); - } - }); - }; - TextareaInput.prototype.fastPoll = function () { - var missed = false, - input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) { - missed = true; - input.polling.set(60, p); - } else { - input.pollingFast = false; - input.slowPoll(); - } - } - input.polling.set(20, p); - }; - TextareaInput.prototype.poll = function () { - var this$1$1 = this; - var cm = this.cm, - input = this.textarea, - prevInput = this.prevInput; - if ( - this.contextMenuPending || - !cm.state.focused || - (hasSelection(input) && !prevInput && !this.composing) || - cm.isReadOnly() || - cm.options.disableInput || - cm.state.keySeq - ) { - return false; - } - var text = input.value; - if (text == prevInput && !cm.somethingSelected()) { - return false; - } - if ( - (ie && ie_version >= 9 && this.hasSelection === text) || - (mac && /[\uf700-\uf7ff]/.test(text)) - ) { - cm.display.input.reset(); - return false; - } - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 8203 && !prevInput) { - prevInput = "​"; - } - if (first == 8666) { - this.reset(); - return this.cm.execCommand("undo"); - } - } - var same = 0, - l = Math.min(prevInput.length, text.length); - while ( - same < l && - prevInput.charCodeAt(same) == text.charCodeAt(same) - ) { - ++same; - } - runInOp(cm, function () { - applyTextInput( - cm, - text.slice(same), - prevInput.length - same, - null, - this$1$1.composing ? "*compose" : null - ); - if (text.length > 1e3 || text.indexOf("\n") > -1) { - input.value = this$1$1.prevInput = ""; - } else { - this$1$1.prevInput = text; - } - if (this$1$1.composing) { - this$1$1.composing.range.clear(); - this$1$1.composing.range = cm.markText( - this$1$1.composing.start, - cm.getCursor("to"), - { - className: "CodeMirror-composing", - } - ); - } - }); - return true; - }; - TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { - this.pollingFast = false; - } - }; - TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { - this.hasSelection = null; - } - this.fastPoll(); - }; - TextareaInput.prototype.onContextMenu = function (e) { - var input = this, - cm = input.cm, - display = cm.display, - te = input.textarea; - if (input.contextMenuPending) { - input.contextMenuPending(); - } - var pos = posFromMouse(cm, e), - scrollPos = display.scroller.scrollTop; - if (!pos || presto) { - return; - } - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) { - operation(cm, setSelection)( - cm.doc, - simpleSelection(pos), - sel_dontScroll - ); - } - var oldCSS = te.style.cssText, - oldWrapperCSS = input.wrapper.style.cssText; - var wrapperBox = - input.wrapper.offsetParent.getBoundingClientRect(); - input.wrapper.style.cssText = "position: static"; - te.style.cssText = - "position: absolute; width: 30px; height: 30px;\n top: " + - (e.clientY - wrapperBox.top - 5) + - "px; left: " + - (e.clientX - wrapperBox.left - 5) + - "px;\n z-index: 1000; background: " + - (ie ? "rgba(255, 255, 255, .05)" : "transparent") + - ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - var oldScrollY; - if (webkit) { - oldScrollY = window.scrollY; - } - display.input.focus(); - if (webkit) { - window.scrollTo(null, oldScrollY); - } - display.input.reset(); - if (!cm.somethingSelected()) { - te.value = input.prevInput = " "; - } - input.contextMenuPending = rehide; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "​" + (selected ? te.value : ""); - te.value = "⇚"; - te.value = extval; - input.prevInput = selected ? "" : "​"; - te.selectionStart = 1; - te.selectionEnd = extval.length; - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - if (input.contextMenuPending != rehide) { - return; - } - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) { - display.scrollbars.setScrollTop( - (display.scroller.scrollTop = scrollPos) - ); - } - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) { - prepareSelectAllHack(); - } - var i2 = 0, - poll = function () { - if ( - display.selForContextMenu == cm.doc.sel && - te.selectionStart == 0 && - te.selectionEnd > 0 && - input.prevInput == "​" - ) { - operation(cm, selectAll)(cm); - } else if (i2++ < 10) { - display.detectingSelectAll = setTimeout(poll, 500); - } else { - display.selForContextMenu = null; - display.input.reset(); - } - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - if (ie && ie_version >= 9) { - prepareSelectAllHack(); - } - if (captureRightClick) { - e_stop(e); - var mouseup = function () { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }; - TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { - this.reset(); - } - this.textarea.disabled = val == "nocursor"; - this.textarea.readOnly = !!val; - }; - TextareaInput.prototype.setUneditable = function () {}; - TextareaInput.prototype.needsContentAttribute = false; - function fromTextArea(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) { - options.tabindex = textarea.tabIndex; - } - if (!options.placeholder && textarea.placeholder) { - options.placeholder = textarea.placeholder; - } - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = - hasFocus == textarea || - (textarea.getAttribute("autofocus") != null && - hasFocus == document.body); - } - function save() { - textarea.value = cm.getValue(); - } - var realSubmit; - if (textarea.form) { - on(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form; - realSubmit = form.submit; - try { - var wrappedSubmit = (form.submit = function () { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }); - } catch (e) {} - } - } - options.finishInit = function (cm2) { - cm2.save = save; - cm2.getTextArea = function () { - return textarea; - }; - cm2.toTextArea = function () { - cm2.toTextArea = isNaN; - save(); - textarea.parentNode.removeChild(cm2.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if ( - !options.leaveSubmitMethodAlone && - typeof textarea.form.submit == "function" - ) { - textarea.form.submit = realSubmit; - } - } - }; + implementations.interfaces.push(namedType); + } + } + } else if ((0, _definition.isObjectType)(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] }; - textarea.style.display = "none"; - var cm = CodeMirror(function (node) { - return textarea.parentNode.insertBefore( - node, - textarea.nextSibling - ); - }, options); - return cm; } - function addLegacyProps(CodeMirror2) { - CodeMirror2.off = off; - CodeMirror2.on = on; - CodeMirror2.wheelEventPixels = wheelEventPixels; - CodeMirror2.Doc = Doc; - CodeMirror2.splitLines = splitLinesAuto; - CodeMirror2.countColumn = countColumn; - CodeMirror2.findColumn = findColumn; - CodeMirror2.isWordChar = isWordCharBasic; - CodeMirror2.Pass = Pass; - CodeMirror2.signal = signal; - CodeMirror2.Line = Line; - CodeMirror2.changeEnd = changeEnd; - CodeMirror2.scrollbarModel = scrollbarModel; - CodeMirror2.Pos = Pos; - CodeMirror2.cmpPos = cmp; - CodeMirror2.modes = modes; - CodeMirror2.mimeModes = mimeModes; - CodeMirror2.resolveMode = resolveMode; - CodeMirror2.getMode = getMode; - CodeMirror2.modeExtensions = modeExtensions; - CodeMirror2.extendMode = extendMode; - CodeMirror2.copyState = copyState; - CodeMirror2.startState = startState; - CodeMirror2.innerMode = innerMode; - CodeMirror2.commands = commands; - CodeMirror2.keyMap = keyMap; - CodeMirror2.keyName = keyName; - CodeMirror2.isModifierKey = isModifierKey; - CodeMirror2.lookupKey = lookupKey; - CodeMirror2.normalizeKeyMap = normalizeKeyMap; - CodeMirror2.StringStream = StringStream; - CodeMirror2.SharedTextMarker = SharedTextMarker; - CodeMirror2.TextMarker = TextMarker; - CodeMirror2.LineWidget = LineWidget; - CodeMirror2.e_preventDefault = e_preventDefault; - CodeMirror2.e_stopPropagation = e_stopPropagation; - CodeMirror2.e_stop = e_stop; - CodeMirror2.addClass = addClass; - CodeMirror2.contains = contains; - CodeMirror2.rmClass = rmClass; - CodeMirror2.keyNames = keyNames; + implementations.objects.push(namedType); + } + } + } + } + } + get [Symbol.toStringTag]() { + return 'GraphQLSchema'; + } + getQueryType() { + return this._queryType; + } + getMutationType() { + return this._mutationType; + } + getSubscriptionType() { + return this._subscriptionType; + } + getRootType(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return this.getQueryType(); + case _ast.OperationTypeNode.MUTATION: + return this.getMutationType(); + case _ast.OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); + } + } + getTypeMap() { + return this._typeMap; + } + getType(name) { + return this.getTypeMap()[name]; + } + getPossibleTypes(abstractType) { + return (0, _definition.isUnionType)(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; + } + getImplementations(interfaceType) { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 ? implementations : { + objects: [], + interfaces: [] + }; + } + isSubType(abstractType, maybeSubType) { + let map = this._subTypeMap[abstractType.name]; + if (map === undefined) { + map = Object.create(null); + if ((0, _definition.isUnionType)(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + for (const type of implementations.objects) { + map[type.name] = true; + } + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + this._subTypeMap[abstractType.name] = map; + } + return map[maybeSubType.name] !== undefined; + } + getDirectives() { + return this._directives; + } + getDirective(name) { + return this.getDirectives().find(directive => directive.name === name); + } + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.__validationErrors !== undefined + }; + } + } + exports.GraphQLSchema = GraphQLSchema; + function collectReferencedTypes(type, typeSet) { + const namedType = (0, _definition.getNamedType)(type); + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + if ((0, _definition.isUnionType)(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if ((0, _definition.isObjectType)(namedType) || (0, _definition.isInterfaceType)(namedType)) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, _definition.isInputObjectType)(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + return typeSet; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/type/validate.mjs": + /*!*******************************************************!*\ + !*** ../../../node_modules/graphql/type/validate.mjs ***! + \*******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.assertValidSchema = assertValidSchema; + exports.validateSchema = validateSchema; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _typeComparators = __webpack_require__(/*! ../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); + var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); + /** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ + + function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; + } + /** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + + function assertValidSchema(schema) { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } + } + class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + this._errors.push(new _GraphQLError.GraphQLError(message, { + nodes: _nodes + })); + } + getErrors() { + return this._errors; + } + } + function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + var _getOperationTypeNode; + context.reportError(`Query root type must be Object type, it cannot be ${(0, _inspect.inspect)(queryType)}.`, (_getOperationTypeNode = getOperationTypeNode(schema, _ast.OperationTypeNode.QUERY)) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode); + } + const mutationType = schema.getMutationType(); + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + var _getOperationTypeNode2; + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(mutationType)}.`, (_getOperationTypeNode2 = getOperationTypeNode(schema, _ast.OperationTypeNode.MUTATION)) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode); + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + var _getOperationTypeNode3; + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(subscriptionType)}.`, (_getOperationTypeNode3 = getOperationTypeNode(schema, _ast.OperationTypeNode.SUBSCRIPTION)) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode); + } + } + function getOperationTypeNode(schema, operation) { + var _flatMap$find; + return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes].flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + schemaNode => { + var _schemaNode$operation; + return /* c8 ignore next */( + (_schemaNode$operation = schemaNode === null || schemaNode === void 0 ? void 0 : schemaNode.operationTypes) !== null && _schemaNode$operation !== void 0 ? _schemaNode$operation : [] + ); + }).find(operationNode => operationNode.operation === operation)) === null || _flatMap$find === void 0 ? void 0 : _flatMap$find.type; + } + function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError(`Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, directive === null || directive === void 0 ? void 0 : directive.astNode); + continue; + } // Ensure they are named correctly. + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError(`The type of @${directive.name}(${arg.name}:) must be Input Type ` + `but got: ${(0, _inspect.inspect)(arg.type)}.`, arg.astNode); + } + if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { + var _arg$astNode; + context.reportError(`Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type]); + } + } + } + } + function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + if (node.name.startsWith('__')) { + context.reportError(`Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, node.astNode); + } + } + function validateTypes(context) { + const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + for (const type of Object.values(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError(`Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } + } + function validateFields(context, type) { + const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError(`Type ${type.name} must define one or more fields.`, [type.astNode, ...type.extensionASTNodes]); + } + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!(0, _definition.isOutputType)(field.type)) { + var _field$astNode; + context.reportError(`The type of ${type.name}.${field.name} must be Output Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type); + } // Ensure the arguments are valid + + for (const arg of field.args) { + const argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + var _arg$astNode2; + context.reportError(`The type of ${type.name}.${field.name}(${argName}:) must be Input ` + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type); + } + if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { + var _arg$astNode3; + context.reportError(`Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type]); + } + } + } + } + function validateInterfaces(context, type) { + const ifaceTypeNames = Object.create(null); + for (const iface of type.getInterfaces()) { + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError(`Type ${(0, _inspect.inspect)(type)} must only implement Interface types, ` + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, getAllImplementsInterfaceNodes(type, iface)); + continue; + } + if (type === iface) { + context.reportError(`Type ${type.name} cannot implement itself because it would create a circular reference.`, getAllImplementsInterfaceNodes(type, iface)); + continue; + } + if (ifaceTypeNames[iface.name]) { + context.reportError(`Type ${type.name} can only implement ${iface.name} once.`, getAllImplementsInterfaceNodes(type, iface)); + continue; + } + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } + } + function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (const ifaceField of Object.values(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError(`Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, [ifaceField.astNode, type.astNode, ...type.extensionASTNodes]); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, typeField.type, ifaceField.type)) { + var _ifaceField$astNode, _typeField$astNode; + context.reportError(`Interface field ${iface.name}.${fieldName} expects type ` + `${(0, _inspect.inspect)(ifaceField.type)} but ${type.name}.${fieldName} ` + `is type ${(0, _inspect.inspect)(typeField.type)}.`, [(_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]); + } // Assert each interface field arg is implemented. + + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = typeField.args.find(arg => arg.name === argName); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, [ifaceArg.astNode, typeField.astNode]); + continue; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + `${type.name}.${fieldName}(${argName}:) is type ` + `${(0, _inspect.inspect)(typeArg.type)}.`, [(_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]); + } // TODO: validate default values? + } // Assert additional arguments must not be required. + + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = ifaceField.args.find(arg => arg.name === argName); + if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { + context.reportError(`Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, [typeArg.astNode, ifaceField.astNode]); + } + } + } + } + function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError(transitive === type ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, [...getAllImplementsInterfaceNodes(iface, transitive), ...getAllImplementsInterfaceNodes(type, iface)]); + } + } + } + function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + if (memberTypes.length === 0) { + context.reportError(`Union type ${union.name} must define one or more member types.`, [union.astNode, ...union.extensionASTNodes]); + } + const includedTypeNames = Object.create(null); + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError(`Union type ${union.name} can only include type ${memberType.name} once.`, getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + includedTypeNames[memberType.name] = true; + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError(`Union type ${union.name} can only include Object types, ` + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, getUnionMemberTypeNodes(union, String(memberType))); + } + } + } + function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + if (enumValues.length === 0) { + context.reportError(`Enum type ${enumType.name} must define one or more values.`, [enumType.astNode, ...enumType.extensionASTNodes]); + } + for (const enumValue of enumValues) { + // Ensure valid name. + validateName(context, enumValue); + } + } + function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + if (fields.length === 0) { + context.reportError(`Input Object type ${inputObj.name} must define one or more fields.`, [inputObj.astNode, ...inputObj.extensionASTNodes]); + } // Ensure the arguments are valid + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + var _field$astNode2; + context.reportError(`The type of ${inputObj.name}.${field.name} must be Input Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type); + } + if ((0, _definition.isRequiredInputField)(field) && field.deprecationReason != null) { + var _field$astNode3; + context.reportError(`Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, [getDeprecatedDirectiveNode(field.astNode), (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type]); + } + } + } + function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + const fieldPath = []; // Position in the type path + + const fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + const fields = Object.values(inputObj.getFields()); + for (const field of fields) { + if ((0, _definition.isNonNullType)(field.type) && (0, _definition.isInputObjectType)(field.type.ofType)) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map(fieldObj => fieldObj.name).join('.'); + context.reportError(`Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, cyclePath.map(fieldObj => fieldObj.astNode)); + } + fieldPath.pop(); + } + } + fieldPathIndexByTypeName[inputObj.name] = undefined; + } + } + function getAllImplementsInterfaceNodes(type, iface) { + const { + astNode, + extensionASTNodes + } = type; + const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes.flatMap(typeNode => { + var _typeNode$interfaces; + return /* c8 ignore next */( + (_typeNode$interfaces = typeNode.interfaces) !== null && _typeNode$interfaces !== void 0 ? _typeNode$interfaces : [] + ); + }).filter(ifaceNode => ifaceNode.name.value === iface.name); + } + function getUnionMemberTypeNodes(union, typeName) { + const { + astNode, + extensionASTNodes + } = union; + const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes.flatMap(unionNode => { + var _unionNode$types; + return /* c8 ignore next */( + (_unionNode$types = unionNode.types) !== null && _unionNode$types !== void 0 ? _unionNode$types : [] + ); + }).filter(typeNode => typeNode.name.value === typeName); + } + function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(node => node.name.value === _directives.GraphQLDeprecatedDirective.name); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/TypeInfo.mjs": + /*!************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/TypeInfo.mjs ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.TypeInfo = void 0; + exports.visitWithTypeInfo = visitWithTypeInfo; + var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + /** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + + class TypeInfo { + constructor(schema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType, /** @deprecated will be removed in 17.0.0 */ + getFieldDefFn) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef; + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + get [Symbol.toStringTag]() { + return 'TypeInfo'; + } + getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + getDirective() { + return this._directive; + } + getArgument() { + return this._argument; + } + getEnumValue() { + return this._enumValue; + } + enter(node) { + const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + { + const namedType = (0, _definition.getNamedType)(this.getType()); + this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); + break; + } + case _kinds.Kind.FIELD: + { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + if (fieldDef) { + fieldType = fieldDef.type; } - defineOptions(CodeMirror); - addEditorMethods(CodeMirror); - var dontDelegate = - "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) { - if ( - Doc.prototype.hasOwnProperty(prop) && - indexOf(dontDelegate, prop) < 0 - ) { - CodeMirror.prototype[prop] = /* @__PURE__ */ (function ( - method - ) { - return function () { - return method.apply(this.doc, arguments); - }; - })(Doc.prototype[prop]); - } + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined); + break; + } + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case _kinds.Kind.OPERATION_DEFINITION: + { + const rootType = schema.getRootType(node.operation); + this._typeStack.push((0, _definition.isObjectType)(rootType) ? rootType : undefined); + break; + } + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType()); + this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); + break; + } + case _kinds.Kind.VARIABLE_DEFINITION: + { + const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); + break; + } + case _kinds.Kind.ARGUMENT: + { + var _this$getDirective; + let argDef; + let argType; + const fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef(); + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find(arg => arg.name === node.name.value); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined); + break; + } + case _kinds.Kind.LIST: + { + const listType = (0, _definition.getNullableType)(this.getInputType()); + const itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined); + break; + } + case _kinds.Kind.OBJECT_FIELD: + { + const objectType = (0, _definition.getNamedType)(this.getInputType()); + let inputFieldType; + let inputField; + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + if (inputField) { + inputFieldType = inputField.type; } - eventMixin(Doc); - CodeMirror.inputStyles = { - textarea: TextareaInput, - contenteditable: ContentEditableInput, - }; - CodeMirror.defineMode = function (name) { - if (!CodeMirror.defaults.mode && name != "null") { - CodeMirror.defaults.mode = name; - } - defineMode.apply(this, arguments); - }; - CodeMirror.defineMIME = defineMIME; - CodeMirror.defineMode("null", function () { - return { - token: function (stream) { - return stream.skipToEnd(); - }, - }; - }); - CodeMirror.defineMIME("text/plain", "null"); - CodeMirror.defineExtension = function (name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.fromTextArea = fromTextArea; - addLegacyProps(CodeMirror); - CodeMirror.version = "5.65.3"; - return CodeMirror; + } + this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); + this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined); + break; + } + case _kinds.Kind.ENUM: + { + const enumType = (0, _definition.getNamedType)(this.getInputType()); + let enumValue; + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + default: // Ignore other nodes + } + } + leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case _kinds.Kind.ARGUMENT: + this._argument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + default: // Ignore other nodes + } + } + } + + /** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ + exports.TypeInfo = TypeInfo; + function getFieldDef(schema, parentType, fieldNode) { + const name = fieldNode.name.value; + if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } + if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } + if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) { + return _introspection.TypeNameMetaFieldDef; + } + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + return parentType.getFields()[name]; + } + } + /** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + + function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; + if (fn) { + const result = fn.apply(visitor, args); + if (result !== undefined) { + typeInfo.leave(node); + if ((0, _ast.isNode)(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(...args) { + const node = args[0]; + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; + let result; + if (fn) { + result = fn.apply(visitor, args); + } + typeInfo.leave(node); + return result; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/assertValidName.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/assertValidName.mjs ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.assertValidName = assertValidName; + exports.isValidNameError = isValidNameError; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _assertName = __webpack_require__(/*! ../type/assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); + /* c8 ignore start */ + + /** + * Upholds the spec rules about naming. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + + function assertValidName(name) { + const error = isValidNameError(name); + if (error) { + throw error; + } + return name; + } + /** + * Returns an Error if a name is invalid. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + + function isValidNameError(name) { + typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + if (name.startsWith('__')) { + return new _GraphQLError.GraphQLError(`Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`); + } + try { + (0, _assertName.assertName)(name); + } catch (error) { + return error; + } + } + /* c8 ignore stop */ + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/astFromValue.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/astFromValue.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.astFromValue = astFromValue; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + /** + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. For example: + * + * astFromValue("value", GraphQLString) + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * + */ + + function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + const astValue = astFromValue(value, type.ofType); + if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === _kinds.Kind.NULL) { + return null; + } + return astValue; + } // only explicit null, not undefined, NaN + + if (value === null) { + return { + kind: _kinds.Kind.NULL + }; + } // undefined + + if (value === undefined) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if ((0, _isIterableObject.isIterableObject)(value)) { + const valuesNodes = []; + for (const item of value) { + const itemNode = astFromValue(item, itemType); + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + return { + kind: _kinds.Kind.LIST, + values: valuesNodes + }; + } + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(value)) { + return null; + } + const fieldNodes = []; + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name + }, + value: fieldValue + }); + } + } + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes + }; + } + if ((0, _definition.isLeafType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + if (serialized == null) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + if (typeof serialized === 'boolean') { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized + }; + } // JavaScript numbers can be Int or Float values. + + if (typeof serialized === 'number' && Number.isFinite(serialized)) { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) ? { + kind: _kinds.Kind.INT, + value: stringNum + } : { + kind: _kinds.Kind.FLOAT, + value: stringNum + }; + } + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized + }; + } // ID types can use Int literals. + + if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: _kinds.Kind.INT, + value: serialized + }; + } + return { + kind: _kinds.Kind.STRING, + value: serialized + }; + } + throw new TypeError(`Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); + } + /** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + + const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/buildASTSchema.mjs": + /*!******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/buildASTSchema.mjs ***! + \******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.buildASTSchema = buildASTSchema; + exports.buildSchema = buildSchema; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); + var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); + var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); + var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); + /** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + */ + function buildASTSchema(documentAST, options) { + documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { + (0, _validate.assertValidSDL)(documentAST); + } + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false + }; + const config = (0, _extendSchema.extendSchemaImpl)(emptySchemaConfig, documentAST, options); + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + case 'Query': + // @ts-expect-error validated in `validateSchema` + config.query = type; + break; + case 'Mutation': + // @ts-expect-error validated in `validateSchema` + config.mutation = type; + break; + case 'Subscription': + // @ts-expect-error validated in `validateSchema` + config.subscription = type; + break; + } + } + } + const directives = [...config.directives, + // If specified directives were not explicitly declared, add them. + ..._directives.specifiedDirectives.filter(stdDirective => config.directives.every(directive => directive.name !== stdDirective.name))]; + return new _schema.GraphQLSchema({ + ...config, + directives + }); + } + /** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + + function buildSchema(source, options) { + const document = (0, _parser.parse)(source, { + noLocation: options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacyFragmentVariables: options === null || options === void 0 ? void 0 : options.allowLegacyFragmentVariables + }); + return buildASTSchema(document, { + assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid + }); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/buildClientSchema.mjs": + /*!*********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/buildClientSchema.mjs ***! + \*********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.buildClientSchema = buildClientSchema; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); + var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); + var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); + /** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ + + function buildClientSchema(introspection, options) { + (0, _isObjectLike.isObjectLike)(introspection) && (0, _isObjectLike.isObjectLike)(introspection.__schema) || (0, _devAssert.devAssert)(false, `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, _inspect.inspect)(introspection)}.`); // Get the schema from the introspection result. + + const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + const typeMap = (0, _keyValMap.keyValMap)(schemaIntrospection.types, typeIntrospection => typeIntrospection.name, typeIntrospection => buildType(typeIntrospection)); // Include standard types only if they are used. + + for (const stdType of [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes]) { + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + const queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + const mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + const subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + const directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: Object.values(typeMap), + directives, + assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + const itemRef = typeRef.ofType; + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + return new _definition.GraphQLList(getType(itemRef)); + } + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + const nullableType = getType(nullableRef); + return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType)); + } + return getNamedType(typeRef); + } + function getNamedType(typeRef) { + const typeName = typeRef.name; + if (!typeName) { + throw new Error(`Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`); + } + const type = typeMap[typeName]; + if (!type) { + throw new Error(`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`); + } + return type; + } + function getObjectType(typeRef) { + return (0, _definition.assertObjectType)(getNamedType(typeRef)); + } + function getInterfaceType(typeRef) { + return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + function buildType(type) { + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (type != null && type.name != null && type.kind != null) { + // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + const typeStr = (0, _inspect.inspect)(type); + throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`); + } + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL + }); + } + function buildImplementationsList(implementingIntrospection) { + // TODO: Temporary workaround until GraphQL ecosystem will fully support + // 'interfaces' on interface types. + if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === _introspection.TypeKind.INTERFACE) { + return []; + } + if (!implementingIntrospection.interfaces) { + const implementingIntrospectionStr = (0, _inspect.inspect)(implementingIntrospection); + throw new Error(`Introspection result missing interfaces: ${implementingIntrospectionStr}.`); + } + return implementingIntrospection.interfaces.map(getInterfaceType); + } + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection) + }); + } + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection) + }); + } + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); + throw new Error(`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`); + } + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType) + }); + } + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); + throw new Error(`Introspection result missing enumValues: ${enumIntrospectionStr}.`); + } + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.keyValMap)(enumIntrospection.enumValues, valueIntrospection => valueIntrospection.name, valueIntrospection => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + })) + }); + } + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + const inputObjectIntrospectionStr = (0, _inspect.inspect)(inputObjectIntrospection); + throw new Error(`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`); + } + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields) + }); + } + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error(`Introspection result missing fields: ${(0, _inspect.inspect)(typeIntrospection)}.`); + } + return (0, _keyValMap.keyValMap)(typeIntrospection.fields, fieldIntrospection => fieldIntrospection.name, buildField); + } + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); + if (!(0, _definition.isOutputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error(`Introspection must provide output type for fields, but received: ${typeStr}.`); + } + if (!fieldIntrospection.args) { + const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); + throw new Error(`Introspection result missing field args: ${fieldIntrospectionStr}.`); + } + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args) + }; + } + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.keyValMap)(inputValueIntrospections, inputValue => inputValue.name, buildInputValue); + } + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); + if (!(0, _definition.isInputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error(`Introspection must provide input type for arguments, but received: ${typeStr}.`); + } + const defaultValue = inputValueIntrospection.defaultValue != null ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason + }; + } + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); + throw new Error(`Introspection result missing directive args: ${directiveIntrospectionStr}.`); + } + if (!directiveIntrospection.locations) { + const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); + throw new Error(`Introspection result missing directive locations: ${directiveIntrospectionStr}.`); + } + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/coerceInputValue.mjs": + /*!********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/coerceInputValue.mjs ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.coerceInputValue = coerceInputValue; + var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); + var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); + var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); + var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); + var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Coerces a JavaScript value given a GraphQL Input Type. + */ + function coerceInputValue(inputValue, type, onError = defaultOnError) { + return coerceInputValueImpl(inputValue, type, onError, undefined); + } + function defaultOnError(path, invalidValue, error) { + let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); + if (path.length > 0) { + errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; + } + error.message = errorPrefix + ': ' + error.message; + throw error; + } + function coerceInputValueImpl(inputValue, type, onError, path) { + if ((0, _definition.isNonNullType)(type)) { + if (inputValue != null) { + return coerceInputValueImpl(inputValue, type.ofType, onError, path); + } + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected non-nullable type "${(0, _inspect.inspect)(type)}" not to be null.`)); + return; + } + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if ((0, _isIterableObject.isIterableObject)(inputValue)) { + return Array.from(inputValue, (itemValue, index) => { + const itemPath = (0, _Path.addPath)(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + } // Lists accept a non-list value as a list of one. + + return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(inputValue)) { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}" to be an object.`)); + return; + } + const coercedValue = {}; + const fieldDefs = type.getFields(); + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + const typeStr = (0, _inspect.inspect)(field.type); + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${field.name}" of required type "${typeStr}" was not provided.`)); + } + continue; + } + coercedValue[field.name] = coerceInputValueImpl(fieldValue, field.type, onError, (0, _Path.addPath)(path, field.name, type.name)); + } // Ensure every provided field is defined. + + for (const fieldName of Object.keys(inputValue)) { + if (!fieldDefs[fieldName]) { + const suggestions = (0, _suggestionList.suggestionList)(fieldName, Object.keys(type.getFields())); + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${fieldName}" is not defined by type "${type.name}".` + (0, _didYouMean.didYouMean)(suggestions))); + } + } + return coercedValue; + } + if ((0, _definition.isLeafType)(type)) { + let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), + // which can throw to indicate failure. If it throws, maintain a reference + // to the original error. + + try { + parseResult = type.parseValue(inputValue); + } catch (error) { + if (error instanceof _GraphQLError.GraphQLError) { + onError((0, _Path.pathToArray)(path), inputValue, error); + } else { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}". ` + error.message, { + originalError: error + })); + } + return; + } + if (parseResult === undefined) { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}".`)); + } + return parseResult; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/concatAST.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/concatAST.mjs ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.concatAST = concatAST; + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + /** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ + + function concatAST(documents) { + const definitions = []; + for (const doc of documents) { + definitions.push(...doc.definitions); + } + return { + kind: _kinds.Kind.DOCUMENT, + definitions + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/extendSchema.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/extendSchema.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.extendSchema = extendSchema; + exports.extendSchemaImpl = extendSchemaImpl; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _predicates = __webpack_require__(/*! ../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); + var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); + var _values = __webpack_require__(/*! ../execution/values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); + /** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + */ + function extendSchema(schema, documentAST, options) { + (0, _schema.assertSchema)(schema); + documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); + } + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); + return schemaConfig === extendedConfig ? schema : new _schema.GraphQLSchema(extendedConfig); + } + /** + * @internal + */ + + function extendSchemaImpl(schemaConfig, documentAST, options) { + var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; + + // Collect the type definitions and extensions found in the document. + const typeDefs = []; + const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + const directiveDefs = []; + let schemaDef; // Schema extensions are collected which may add additional operation types. + + const schemaExtensions = []; + for (const def of documentAST.definitions) { + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + typeDefs.push(def); + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + const extendedTypeName = def.name.value; + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) { + return schemaConfig; + } + const typeMap = Object.create(null); + for (const existingType of schemaConfig.types) { + typeMap[existingType.name] = extendNamedType(existingType); + } + for (const typeNode of typeDefs) { + var _stdTypeMap$name; + const name = typeNode.name.value; + typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode); + } + const operationTypes = { + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), + // Then, incorporate schema definition and all schema extensions. + ...(schemaDef && getOperationTypes([schemaDef])), + ...getOperationTypes(schemaExtensions) + }; // Then produce and return a Schema config with these types. + + return { + description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value, + ...operationTypes, + types: Object.values(typeMap), + directives: [...schemaConfig.directives.map(replaceDirective), ...directiveDefs.map(buildDirective)], + extensions: Object.create(null), + astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode, + extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: (_options$assumeValid = options === null || options === void 0 ? void 0 : options.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false + }; // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } + if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME + + return replaceNamedType(type); + } + function replaceNamedType(type) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return typeMap[type.name]; + } + function replaceDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + args: (0, _mapValue.mapValue)(config.args, extendArg) + }); + } + function extendNamedType(type) { + if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) { + // Builtin types are not extended. + return type; + } + if ((0, _definition.isScalarType)(type)) { + return extendScalarType(type); + } + if ((0, _definition.isObjectType)(type)) { + return extendObjectType(type); + } + if ((0, _definition.isInterfaceType)(type)) { + return extendInterfaceType(type); + } + if ((0, _definition.isUnionType)(type)) { + return extendUnionType(type); + } + if ((0, _definition.isEnumType)(type)) { + return extendEnumType(type); + } + if ((0, _definition.isInputObjectType)(type)) { + return extendInputObjectType(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible type definition nodes have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : []; + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, field => ({ + ...field, + type: replaceType(field.type) + })), + ...buildInputFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendEnumType(type) { + var _typeExtensionsMap$ty; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : []; + return new _definition.GraphQLEnumType({ + ...config, + values: { + ...config.values, + ...buildEnumValueMap(extensions) + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendScalarType(type) { + var _typeExtensionsMap$co2; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : []; + let specifiedByURL = config.specifiedByURL; + for (const extensionNode of extensions) { + var _getSpecifiedByURL; + specifiedByURL = (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && _getSpecifiedByURL !== void 0 ? _getSpecifiedByURL : specifiedByURL; + } + return new _definition.GraphQLScalarType({ + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendObjectType(type) { + var _typeExtensionsMap$co3; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : []; + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : []; + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendUnionType(type) { + var _typeExtensionsMap$co5; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : []; + return new _definition.GraphQLUnionType({ + ...config, + types: () => [...type.getTypes().map(replaceNamedType), ...buildUnionTypes(extensions)], + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendField(field) { + return { + ...field, + type: replaceType(field.type), + args: field.args && (0, _mapValue.mapValue)(field.args, extendArg) + }; + } + function extendArg(arg) { + return { + ...arg, + type: replaceType(arg.type) + }; + } + function getOperationTypes(nodes) { + const opTypes = {}; + for (const node of nodes) { + var _node$operationTypes; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const operationTypesNodes = /* c8 ignore next */ + (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + for (const operationType of operationTypesNodes) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } + return opTypes; + } + function getNamedType(node) { + var _stdTypeMap$name2; + const name = node.name.value; + const type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name]; + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); + } + return type; + } + function getWrappedType(node) { + if (node.kind === _kinds.Kind.LIST_TYPE) { + return new _definition.GraphQLList(getWrappedType(node.type)); + } + if (node.kind === _kinds.Kind.NON_NULL_TYPE) { + return new _definition.GraphQLNonNull(getWrappedType(node.type)); + } + return getNamedType(node); + } + function buildDirective(node) { + var _node$description; + return new _directives.GraphQLDirective({ + name: node.name.value, + description: (_node$description = node.description) === null || _node$description === void 0 ? void 0 : _node$description.value, + // @ts-expect-error + locations: node.locations.map(({ + value + }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node + }); + } + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + for (const node of nodes) { + var _node$fields; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const nodeFields = /* c8 ignore next */ + (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + for (const field of nodeFields) { + var _field$description; + fieldConfigMap[field.name.value] = { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: getWrappedType(field.type), + description: (_field$description = field.description) === null || _field$description === void 0 ? void 0 : _field$description.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + return fieldConfigMap; + } + function buildArgumentMap(args) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const argsNodes = /* c8 ignore next */ + args !== null && args !== void 0 ? args : []; + const argConfigMap = Object.create(null); + for (const arg of argsNodes) { + var _arg$description; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type, + description: (_arg$description = arg.description) === null || _arg$description === void 0 ? void 0 : _arg$description.value, + defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg + }; + } + return argConfigMap; + } + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + for (const node of nodes) { + var _node$fields2; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fieldsNodes = /* c8 ignore next */ + (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []; + for (const field of fieldsNodes) { + var _field$description2; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type, + description: (_field$description2 = field.description) === null || _field$description2 === void 0 ? void 0 : _field$description2.value, + defaultValue: (0, _valueFromAST.valueFromAST)(field.defaultValue, type), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + return inputFieldMap; + } + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); + for (const node of nodes) { + var _node$values; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const valuesNodes = /* c8 ignore next */ + (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + for (const value of valuesNodes) { + var _value$description; + enumValueMap[value.name.value] = { + description: (_value$description = value.description) === null || _value$description === void 0 ? void 0 : _value$description.value, + deprecationReason: getDeprecationReason(value), + astNode: value + }; + } + } + return enumValueMap; + } + function buildInterfaces(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + node => { + var _node$interfaces$map, _node$interfaces; + return /* c8 ignore next */( + (_node$interfaces$map = (_node$interfaces = node.interfaces) === null || _node$interfaces === void 0 ? void 0 : _node$interfaces.map(getNamedType)) !== null && _node$interfaces$map !== void 0 ? _node$interfaces$map : [] + ); + }); + } + function buildUnionTypes(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + node => { + var _node$types$map, _node$types; + return /* c8 ignore next */( + (_node$types$map = (_node$types = node.types) === null || _node$types === void 0 ? void 0 : _node$types.map(getNamedType)) !== null && _node$types$map !== void 0 ? _node$types$map : [] + ); + }); + } + function buildType(astNode) { + var _typeExtensionsMap$na; + const name = astNode.name.value; + const extensionASTNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : []; + switch (astNode.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + { + var _astNode$description; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLObjectType({ + name, + description: (_astNode$description = astNode.description) === null || _astNode$description === void 0 ? void 0 : _astNode$description.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes }); - })(codemirror); - return codemirror.exports; + } + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + { + var _astNode$description2; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInterfaceType({ + name, + description: (_astNode$description2 = astNode.description) === null || _astNode$description2 === void 0 ? void 0 : _astNode$description2.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.ENUM_TYPE_DEFINITION: + { + var _astNode$description3; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLEnumType({ + name, + description: (_astNode$description3 = astNode.description) === null || _astNode$description3 === void 0 ? void 0 : _astNode$description3.value, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.UNION_TYPE_DEFINITION: + { + var _astNode$description4; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLUnionType({ + name, + description: (_astNode$description4 = astNode.description) === null || _astNode$description4 === void 0 ? void 0 : _astNode$description4.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + { + var _astNode$description5; + return new _definition.GraphQLScalarType({ + name, + description: (_astNode$description5 = astNode.description) === null || _astNode$description5 === void 0 ? void 0 : _astNode$description5.value, + specifiedByURL: getSpecifiedByURL(astNode), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + { + var _astNode$description6; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInputObjectType({ + name, + description: (_astNode$description6 = astNode.description) === null || _astNode$description6 === void 0 ? void 0 : _astNode$description6.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } + } + } + } + const stdTypeMap = (0, _keyMap.keyMap)([..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], type => type.name); + /** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + + function getDeprecationReason(node) { + const deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues` + + return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason; + } + /** + * Given a scalar node, returns the string value for the specifiedByURL. + */ + + function getSpecifiedByURL(node) { + const specifiedBy = (0, _values.getDirectiveValues)(_directives.GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues` + + return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs": + /*!***********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/findBreakingChanges.mjs ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.DangerousChangeType = exports.BreakingChangeType = void 0; + exports.findBreakingChanges = findBreakingChanges; + exports.findDangerousChanges = findDangerousChanges; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); + var _sortValueNode = __webpack_require__(/*! ./sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); + var BreakingChangeType; + (function (BreakingChangeType) { + BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; + BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; + BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; + BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; + BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = 'REQUIRED_INPUT_FIELD_ADDED'; + BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = 'IMPLEMENTED_INTERFACE_REMOVED'; + BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; + BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; + BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; + BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; + BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; + BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; + BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; + BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = 'REQUIRED_DIRECTIVE_ARG_ADDED'; + BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = 'DIRECTIVE_REPEATABLE_REMOVED'; + BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = 'DIRECTIVE_LOCATION_REMOVED'; + })(BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {})); + var DangerousChangeType; + (function (DangerousChangeType) { + DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; + DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; + DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = 'OPTIONAL_INPUT_FIELD_ADDED'; + DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; + DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = 'IMPLEMENTED_INTERFACE_ADDED'; + DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; + })(DangerousChangeType || (exports.DangerousChangeType = DangerousChangeType = {})); + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ + function findBreakingChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in BreakingChangeType); + } + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ + + function findDangerousChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in DangerousChangeType); + } + function findSchemaChanges(oldSchema, newSchema) { + return [...findTypeChanges(oldSchema, newSchema), ...findDirectiveChanges(oldSchema, newSchema)]; + } + function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${oldDirective.name} was removed.` + }); + } + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.` + }); } - exports.getDefaultExportFromCjs = getDefaultExportFromCjs; - exports.requireCodemirror = requireCodemirror; - - /***/ - }, - - /***/ "../../graphiql-react/dist/comment.cjs.js": - /*!************************************************!*\ - !*** ../../graphiql-react/dist/comment.cjs.js ***! - \************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } - } - } + } + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${oldArg.name} was removed from ${oldDirective.name}.` + }); + } + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective.name}.` + }); + } + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.` + }); + } + } + } + return schemaChanges; + } + function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff(Object.values(oldSchema.getTypeMap()), Object.values(newSchema.getTypeMap())); + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: (0, _scalars.isSpecifiedScalarType)(oldType) ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` : `${oldType.name} was removed.` + }); + } + for (const [oldType, newType] of typesDiff.persisted) { + if ((0, _definition.isEnumType)(oldType) && (0, _definition.isEnumType)(newType)) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if ((0, _definition.isUnionType)(oldType) && (0, _definition.isUnionType)(newType)) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if ((0, _definition.isInputObjectType)(oldType) && (0, _definition.isInputObjectType)(newType)) { + schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); + } else if ((0, _definition.isObjectType)(oldType) && (0, _definition.isObjectType)(newType)) { + schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); + } else if ((0, _definition.isInterfaceType)(oldType) && (0, _definition.isInterfaceType)(newType)) { + schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: `${oldType.name} changed from ` + `${typeKindName(oldType)} to ${typeKindName(newType)}.` + }); + } + } + return schemaChanges; + } + function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); + for (const newField of fieldsDiff.added) { + if ((0, _definition.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField.name} on input type ${oldType.name} was added.` + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField.name} on input type ${oldType.name} was added.` + }); + } + } + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.` + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldField.type, newField.type); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` + }); + } + } + return schemaChanges; + } + function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType.name} was added to union type ${oldType.name}.` + }); + } + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType.name} was removed from union type ${oldType.name}.` + }); + } + return schemaChanges; + } + function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${newValue.name} was added to enum type ${oldType.name}.` + }); + } + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${oldValue.name} was removed from enum type ${oldType.name}.` + }); + } + return schemaChanges; + } + function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.` + }); + } + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType.name} no longer implements interface ${oldInterface.name}.` + }); + } + return schemaChanges; + } + function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.` + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldType, oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField(oldField.type, newField.type); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` + }); + } + } + return schemaChanges; + } + function findArgChanges(oldType, oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.` + }); + } + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArg.type, newArg.type); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` + }); + } else if (oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.` + }); + } else { + // Since we looking only for client's observable changes we should + // compare default values in the same representation as they are + // represented inside introspection. + const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); + const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.` + }); } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); } - var comment$2 = { - exports: {}, - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var noOptions = {}; - var nonWS = /[^\s\u00a0]/; - var Pos = CodeMirror.Pos, - cmp = CodeMirror.cmpPos; - function firstNonWS(str) { - var found = str.search(nonWS); - return found == -1 ? 0 : found; - } - CodeMirror.commands.toggleComment = function (cm) { - cm.toggleComment(); - }; - CodeMirror.defineExtension("toggleComment", function (options) { - if (!options) options = noOptions; - var cm = this; - var minLine = Infinity, - ranges = this.listSelections(), - mode = null; - for (var i = ranges.length - 1; i >= 0; i--) { - var from = ranges[i].from(), - to = ranges[i].to(); - if (from.line >= minLine) continue; - if (to.line >= minLine) to = Pos(minLine, 0); - minLine = from.line; - if (mode == null) { - if (cm.uncomment(from, to, options)) mode = "un"; - else { - cm.lineComment(from, to, options); - mode = "line"; - } - } else if (mode == "un") { - cm.uncomment(from, to, options); - } else { - cm.lineComment(from, to, options); - } - } - }); - function probablyInsideString(cm, pos, line) { - return ( - /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && - !/^[\'\"\`]/.test(line) - ); - } - function getMode(cm, pos) { - var mode = cm.getMode(); - return mode.useInnerComments === false || !mode.innerMode - ? mode - : cm.getModeAt(pos); - } - CodeMirror.defineExtension( - "lineComment", - function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var firstLine = self.getLine(from.line); - if ( - firstLine == null || - probablyInsideString(self, from, firstLine) - ) - return; - var commentString = options.lineComment || mode.lineComment; - if (!commentString) { - if (options.blockCommentStart || mode.blockCommentStart) { - options.fullLines = true; - self.blockComment(from, to, options); - } - return; - } - var end = Math.min( - to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, - self.lastLine() + 1 - ); - var pad = options.padding == null ? " " : options.padding; - var blankLines = - options.commentBlankLines || from.line == to.line; - self.operation(function () { - if (options.indent) { - var baseString = null; - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i); - var whitespace = line.slice(0, firstNonWS(line)); - if ( - baseString == null || - baseString.length > whitespace.length - ) { - baseString = whitespace; - } - } - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i), - cut = baseString.length; - if (!blankLines && !nonWS.test(line)) continue; - if (line.slice(0, cut) != baseString) - cut = firstNonWS(line); - self.replaceRange( - baseString + commentString + pad, - Pos(i, 0), - Pos(i, cut) - ); - } - } else { - for (var i = from.line; i < end; ++i) { - if (blankLines || nonWS.test(self.getLine(i))) - self.replaceRange(commentString + pad, Pos(i, 0)); - } - } - }); - } - ); - CodeMirror.defineExtension( - "blockComment", - function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var startString = - options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) { - if ( - (options.lineComment || mode.lineComment) && - options.fullLines != false - ) - self.lineComment(from, to, options); - return; - } - if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) - return; - var end = Math.min(to.line, self.lastLine()); - if ( - end != from.line && - to.ch == 0 && - nonWS.test(self.getLine(end)) - ) - --end; - var pad = options.padding == null ? " " : options.padding; - if (from.line > end) return; - self.operation(function () { - if (options.fullLines != false) { - var lastLineHasText = nonWS.test(self.getLine(end)); - self.replaceRange(pad + endString, Pos(end)); - self.replaceRange(startString + pad, Pos(from.line, 0)); - var lead = - options.blockCommentLead || mode.blockCommentLead; - if (lead != null) { - for (var i = from.line + 1; i <= end; ++i) - if (i != end || lastLineHasText) - self.replaceRange(lead + pad, Pos(i, 0)); - } - } else { - var atCursor = cmp(self.getCursor("to"), to) == 0, - empty = !self.somethingSelected(); - self.replaceRange(endString, to); - if (atCursor) - self.setSelection( - empty ? to : self.getCursor("from"), - to - ); - self.replaceRange(startString, from); - } - }); - } - ); - CodeMirror.defineExtension( - "uncomment", - function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var end = Math.min( - to.ch != 0 || to.line == from.line ? to.line : to.line - 1, - self.lastLine() - ), - start = Math.min(from.line, end); - var lineString = options.lineComment || mode.lineComment, - lines = []; - var pad = options.padding == null ? " " : options.padding, - didSomething; - lineComment: { - if (!lineString) break lineComment; - for (var i = start; i <= end; ++i) { - var line = self.getLine(i); - var found = line.indexOf(lineString); - if ( - found > -1 && - !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1))) - ) - found = -1; - if (found == -1 && nonWS.test(line)) break lineComment; - if (found > -1 && nonWS.test(line.slice(0, found))) - break lineComment; - lines.push(line); - } - self.operation(function () { - for (var i2 = start; i2 <= end; ++i2) { - var line2 = lines[i2 - start]; - var pos = line2.indexOf(lineString), - endPos = pos + lineString.length; - if (pos < 0) continue; - if (line2.slice(endPos, endPos + pad.length) == pad) - endPos += pad.length; - didSomething = true; - self.replaceRange("", Pos(i2, pos), Pos(i2, endPos)); - } - }); - if (didSomething) return true; - } - var startString = - options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) return false; - var lead = options.blockCommentLead || mode.blockCommentLead; - var startLine = self.getLine(start), - open = startLine.indexOf(startString); - if (open == -1) return false; - var endLine = end == start ? startLine : self.getLine(end); - var close = endLine.indexOf( - endString, - end == start ? open + startString.length : 0 - ); - var insideStart = Pos(start, open + 1), - insideEnd = Pos(end, close + 1); - if ( - close == -1 || - !/comment/.test(self.getTokenTypeAt(insideStart)) || - !/comment/.test(self.getTokenTypeAt(insideEnd)) || - self - .getRange(insideStart, insideEnd, "\n") - .indexOf(endString) > -1 - ) - return false; - var lastStart = startLine.lastIndexOf(startString, from.ch); - var firstEnd = - lastStart == -1 - ? -1 - : startLine - .slice(0, from.ch) - .indexOf(endString, lastStart + startString.length); - if ( - lastStart != -1 && - firstEnd != -1 && - firstEnd + endString.length != from.ch - ) - return false; - firstEnd = endLine.indexOf(endString, to.ch); - var almostLastStart = endLine - .slice(to.ch) - .lastIndexOf(startString, firstEnd - to.ch); - lastStart = - firstEnd == -1 || almostLastStart == -1 - ? -1 - : to.ch + almostLastStart; - if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) - return false; - self.operation(function () { - self.replaceRange( - "", - Pos( - end, - close - - (pad && endLine.slice(close - pad.length, close) == pad - ? pad.length - : 0) - ), - Pos(end, close + endString.length) - ); - var openEnd = open + startString.length; - if ( - pad && - startLine.slice(openEnd, openEnd + pad.length) == pad - ) - openEnd += pad.length; - self.replaceRange("", Pos(start, open), Pos(start, openEnd)); - if (lead) - for (var i2 = start + 1; i2 <= end; ++i2) { - var line2 = self.getLine(i2), - found2 = line2.indexOf(lead); - if (found2 == -1 || nonWS.test(line2.slice(0, found2))) - continue; - var foundEnd = found2 + lead.length; - if ( - pad && - line2.slice(foundEnd, foundEnd + pad.length) == pad - ) - foundEnd += pad.length; - self.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd)); - } - }); - return true; - } - ); - }); - })(); - var commentExports = comment$2.exports; - const comment = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(commentExports); - const comment$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: comment, - }, - [commentExports] - ); - exports.comment = comment$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/dialog.cjs.js": - /*!***********************************************!*\ - !*** ../../graphiql-react/dist/dialog.cjs.js ***! - \***********************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } - } + } + } + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` + }); + } + } + return schemaChanges; + } + function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || + // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } + if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + return ( + // if they're both named types, see if their names are equivalent + (0, _definition.isNamedType)(newType) && oldType.name === newType.name || + // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } + function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } + if ((0, _definition.isNonNullType)(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || + // moving from non-null to nullable of the same underlying type is safe + !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) + ); + } // if they're both named types, see if their names are equivalent + + return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; + } + function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return 'a Scalar type'; + } + if ((0, _definition.isObjectType)(type)) { + return 'an Object type'; + } + if ((0, _definition.isInterfaceType)(type)) { + return 'an Interface type'; + } + if ((0, _definition.isUnionType)(type)) { + return 'a Union type'; + } + if ((0, _definition.isEnumType)(type)) { + return 'an Enum type'; + } + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } + function stringifyValue(value, type) { + const ast = (0, _astFromValue.astFromValue)(value, type); + ast != null || (0, _invariant.invariant)(false); + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); + } + function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = (0, _keyMap.keyMap)(oldArray, ({ + name + }) => name); + const newMap = (0, _keyMap.keyMap)(newArray, ({ + name + }) => name); + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); + } + } + return { + added, + persisted, + removed + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs": + /*!*************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs ***! + \*************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getIntrospectionQuery = getIntrospectionQuery; + /** + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. + */ + function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + ...options + }; + const descriptions = optionsWithDefault.descriptions ? 'description' : ''; + const specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByURL' : ''; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : ''; + const schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ''; + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + ${descriptions} + ${directiveIsRepeatable} + locations + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue } } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); } - var dialog$2 = { - exports: {}, - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function dialogDiv(cm, template, bottom) { - var wrap = cm.getWrapperElement(); - var dialog2; - dialog2 = wrap.appendChild(document.createElement("div")); - if (bottom) - dialog2.className = - "CodeMirror-dialog CodeMirror-dialog-bottom"; - else - dialog2.className = "CodeMirror-dialog CodeMirror-dialog-top"; - if (typeof template == "string") { - dialog2.innerHTML = template; - } else { - dialog2.appendChild(template); - } - CodeMirror.addClass(wrap, "dialog-opened"); - return dialog2; - } - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) - cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - CodeMirror.defineExtension( - "openDialog", - function (template, callback, options) { - if (!options) options = {}; - closeNotification(this, null); - var dialog2 = dialogDiv(this, template, options.bottom); - var closed = false, - me = this; - function close(newVal) { - if (typeof newVal == "string") { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - me.focus(); - if (options.onClose) options.onClose(dialog2); - } - } - var inp = dialog2.getElementsByTagName("input")[0], - button; - if (inp) { - inp.focus(); - if (options.value) { - inp.value = options.value; - if (options.selectValueOnOpen !== false) { - inp.select(); - } - } - if (options.onInput) - CodeMirror.on(inp, "input", function (e) { - options.onInput(e, inp.value, close); - }); - if (options.onKeyUp) - CodeMirror.on(inp, "keyup", function (e) { - options.onKeyUp(e, inp.value, close); - }); - CodeMirror.on(inp, "keydown", function (e) { - if ( - options && - options.onKeyDown && - options.onKeyDown(e, inp.value, close) - ) { - return; - } - if ( - e.keyCode == 27 || - (options.closeOnEnter !== false && e.keyCode == 13) - ) { - inp.blur(); - CodeMirror.e_stop(e); - close(); - } - if (e.keyCode == 13) callback(inp.value, e); - }); - if (options.closeOnBlur !== false) - CodeMirror.on(dialog2, "focusout", function (evt) { - if (evt.relatedTarget !== null) close(); - }); - } else if ( - (button = dialog2.getElementsByTagName("button")[0]) - ) { - CodeMirror.on(button, "click", function () { - close(); - me.focus(); - }); - if (options.closeOnBlur !== false) - CodeMirror.on(button, "blur", close); - button.focus(); - } - return close; - } - ); - CodeMirror.defineExtension( - "openConfirm", - function (template, callbacks, options) { - closeNotification(this, null); - var dialog2 = dialogDiv( - this, - template, - options && options.bottom - ); - var buttons = dialog2.getElementsByTagName("button"); - var closed = false, - me = this, - blurring = 1; - function close() { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - me.focus(); - } - buttons[0].focus(); - for (var i = 0; i < buttons.length; ++i) { - var b = buttons[i]; - (function (callback) { - CodeMirror.on(b, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - if (callback) callback(me); - }); - })(callbacks[i]); - CodeMirror.on(b, "blur", function () { - --blurring; - setTimeout(function () { - if (blurring <= 0) close(); - }, 200); - }); - CodeMirror.on(b, "focus", function () { - ++blurring; - }); - } - } - ); - CodeMirror.defineExtension( - "openNotification", - function (template, options) { - closeNotification(this, close); - var dialog2 = dialogDiv( - this, - template, - options && options.bottom - ); - var closed = false, - doneTimer; - var duration = - options && typeof options.duration !== "undefined" - ? options.duration - : 5e3; - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - } - CodeMirror.on(dialog2, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - }); - if (duration) doneTimer = setTimeout(close, duration); - return close; - } - ); - }); - })(); - var dialogExports = dialog$2.exports; - const dialog = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(dialogExports); - const dialog$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: dialog, - }, - [dialogExports] - ); - exports.dialog = dialog$1; - exports.dialogExports = dialogExports; - - /***/ - }, - - /***/ "../../graphiql-react/dist/foldgutter.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/foldgutter.cjs.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } - } - } + } + + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); + type { + ...TypeRef + } + isDeprecated + deprecationReason } - var foldgutter$2 = { - exports: {}, - }; - var foldcode = { - exports: {}, - }; - var hasRequiredFoldcode; - function requireFoldcode() { - if (hasRequiredFoldcode) return foldcode.exports; - hasRequiredFoldcode = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function doFold(cm, pos, options, force) { - if (options && options.call) { - var finder = options; - options = null; - } else { - var finder = getOption(cm, options, "rangeFinder"); - } - if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); - var minSize = getOption(cm, options, "minFoldSize"); - function getRange(allowFolded) { - var range2 = finder(cm, pos); - if (!range2 || range2.to.line - range2.from.line < minSize) - return null; - if (force === "fold") return range2; - var marks = cm.findMarksAt(range2.from); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - if (!allowFolded) return null; - range2.cleared = true; - marks[i].clear(); - } - } - return range2; - } - var range = getRange(true); - if (getOption(cm, options, "scanUp")) - while (!range && pos.line > cm.firstLine()) { - pos = CodeMirror.Pos(pos.line - 1, 0); - range = getRange(false); - } - if (!range || range.cleared || force === "unfold") return; - var myWidget = makeWidget(cm, options, range); - CodeMirror.on(myWidget, "mousedown", function (e) { - myRange.clear(); - CodeMirror.e_preventDefault(e); - }); - var myRange = cm.markText(range.from, range.to, { - replacedWith: myWidget, - clearOnEnter: getOption(cm, options, "clearOnEnter"), - __isFold: true, - }); - myRange.on("clear", function (from, to) { - CodeMirror.signal(cm, "unfold", cm, from, to); - }); - CodeMirror.signal(cm, "fold", cm, range.from, range.to); - } - function makeWidget(cm, options, range) { - var widget = getOption(cm, options, "widget"); - if (typeof widget == "function") { - widget = widget(range.from, range.to); - } - if (typeof widget == "string") { - var text = document.createTextNode(widget); - widget = document.createElement("span"); - widget.appendChild(text); - widget.className = "CodeMirror-foldmarker"; - } else if (widget) { - widget = widget.cloneNode(true); - } - return widget; - } - CodeMirror.newFoldFunction = function (rangeFinder, widget) { - return function (cm, pos) { - doFold(cm, pos, { - rangeFinder, - widget, - }); - }; - }; - CodeMirror.defineExtension( - "foldCode", - function (pos, options, force) { - doFold(this, pos, options, force); - } - ); - CodeMirror.defineExtension("isFolded", function (pos) { - var marks = this.findMarksAt(pos); - for (var i = 0; i < marks.length; ++i) - if (marks[i].__isFold) return true; - }); - CodeMirror.commands.toggleFold = function (cm) { - cm.foldCode(cm.getCursor()); - }; - CodeMirror.commands.fold = function (cm) { - cm.foldCode(cm.getCursor(), null, "fold"); - }; - CodeMirror.commands.unfold = function (cm) { - cm.foldCode( - cm.getCursor(), - { - scanUp: false, - }, - "unfold" - ); - }; - CodeMirror.commands.foldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) - cm.foldCode( - CodeMirror.Pos(i, 0), - { - scanUp: false, - }, - "fold" - ); - }); - }; - CodeMirror.commands.unfoldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) - cm.foldCode( - CodeMirror.Pos(i, 0), - { - scanUp: false, - }, - "unfold" - ); - }); - }; - CodeMirror.registerHelper("fold", "combine", function () { - var funcs = Array.prototype.slice.call(arguments, 0); - return function (cm, start) { - for (var i = 0; i < funcs.length; ++i) { - var found = funcs[i](cm, start); - if (found) return found; - } - }; - }); - CodeMirror.registerHelper("fold", "auto", function (cm, start) { - var helpers = cm.getHelpers(start, "fold"); - for (var i = 0; i < helpers.length; i++) { - var cur = helpers[i](cm, start); - if (cur) return cur; - } - }); - var defaultOptions = { - rangeFinder: CodeMirror.fold.auto, - widget: "↔", - minFoldSize: 0, - scanUp: false, - clearOnEnter: true, - }; - CodeMirror.defineOption("foldOptions", null); - function getOption(cm, options, name) { - if (options && options[name] !== void 0) return options[name]; - var editorOptions = cm.options.foldOptions; - if (editorOptions && editorOptions[name] !== void 0) - return editorOptions[name]; - return defaultOptions[name]; - } - CodeMirror.defineExtension( - "foldOption", - function (options, name) { - return getOption(this, options, name); - } - ); - }); - })(); - return foldcode.exports; - } - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), requireFoldcode()); - })(function (CodeMirror) { - CodeMirror.defineOption( - "foldGutter", - false, - function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.clearGutter(cm.state.foldGutter.options.gutter); - cm.state.foldGutter = null; - cm.off("gutterClick", onGutterClick); - cm.off("changes", onChange); - cm.off("viewportChange", onViewportChange); - cm.off("fold", onFold); - cm.off("unfold", onFold); - cm.off("swapDoc", onChange); - } - if (val) { - cm.state.foldGutter = new State(parseOptions(val)); - updateInViewport(cm); - cm.on("gutterClick", onGutterClick); - cm.on("changes", onChange); - cm.on("viewportChange", onViewportChange); - cm.on("fold", onFold); - cm.on("unfold", onFold); - cm.on("swapDoc", onChange); - } - } - ); - var Pos = CodeMirror.Pos; - function State(options) { - this.options = options; - this.from = this.to = 0; - } - function parseOptions(opts) { - if (opts === true) opts = {}; - if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; - if (opts.indicatorOpen == null) - opts.indicatorOpen = "CodeMirror-foldgutter-open"; - if (opts.indicatorFolded == null) - opts.indicatorFolded = "CodeMirror-foldgutter-folded"; - return opts; - } - function isFolded(cm, line) { - var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - var fromPos = marks[i].find(-1); - if (fromPos && fromPos.line === line) return marks[i]; - } - } - } - function marker(spec) { - if (typeof spec == "string") { - var elt = document.createElement("div"); - elt.className = spec + " CodeMirror-guttermarker-subtle"; - return elt; - } else { - return spec.cloneNode(true); - } - } - function updateFoldInfo(cm, from, to) { - var opts = cm.state.foldGutter.options, - cur = from - 1; - var minSize = cm.foldOption(opts, "minFoldSize"); - var func = cm.foldOption(opts, "rangeFinder"); - var clsFolded = - typeof opts.indicatorFolded == "string" && - classTest(opts.indicatorFolded); - var clsOpen = - typeof opts.indicatorOpen == "string" && - classTest(opts.indicatorOpen); - cm.eachLine(from, to, function (line) { - ++cur; - var mark = null; - var old = line.gutterMarkers; - if (old) old = old[opts.gutter]; - if (isFolded(cm, cur)) { - if (clsFolded && old && clsFolded.test(old.className)) return; - mark = marker(opts.indicatorFolded); - } else { - var pos = Pos(cur, 0); - var range = func && func(cm, pos); - if (range && range.to.line - range.from.line >= minSize) { - if (clsOpen && old && clsOpen.test(old.className)) return; - mark = marker(opts.indicatorOpen); - } - } - if (!mark && !old) return; - cm.setGutterMarker(line, opts.gutter, mark); - }); - } - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - function updateInViewport(cm) { - var vp = cm.getViewport(), - state = cm.state.foldGutter; - if (!state) return; - cm.operation(function () { - updateFoldInfo(cm, vp.from, vp.to); - }); - state.from = vp.from; - state.to = vp.to; - } - function onGutterClick(cm, line, gutter) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - if (gutter != opts.gutter) return; - var folded = isFolded(cm, line); - if (folded) folded.clear(); - else cm.foldCode(Pos(line, 0), opts); - } - function onChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - state.from = state.to = 0; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - updateInViewport(cm); - }, opts.foldOnChangeTimeSpan || 600); - } - function onViewportChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - var vp = cm.getViewport(); - if ( - state.from == state.to || - vp.from - state.to > 20 || - state.from - vp.to > 20 - ) { - updateInViewport(cm); - } else { - cm.operation(function () { - if (vp.from < state.from) { - updateFoldInfo(cm, vp.from, state.from); - state.from = vp.from; - } - if (vp.to > state.to) { - updateFoldInfo(cm, state.to, vp.to); - state.to = vp.to; + inputFields${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation('isDeprecated')} + ${inputDeprecation('deprecationReason')} + } + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } } - }); + } } - }, opts.updateViewportTimeSpan || 400); - } - function onFold(cm, from) { - var state = cm.state.foldGutter; - if (!state) return; - var line = from.line; - if (line >= state.from && line < state.to) - updateFoldInfo(cm, line, line + 1); - } - }); - })(); - var foldgutterExports = foldgutter$2.exports; - const foldgutter = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(foldgutterExports); - const foldgutter$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: foldgutter, - }, - [foldgutterExports] - ); - exports.foldgutter = foldgutter$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/forEachState.cjs.js": - /*!*****************************************************!*\ - !*** ../../graphiql-react/dist/forEachState.cjs.js ***! - \*****************************************************/ - /***/ function (__unused_webpack_module, exports) { - function forEachState(stack, fn) { - const reverseStateStack = []; - let state = stack; - while (state === null || state === void 0 ? void 0 : state.kind) { - reverseStateStack.push(state); - state = state.prevState; - } - for (let i = reverseStateStack.length - 1; i >= 0; i--) { - fn(reverseStateStack[i]); - } - } - exports.forEachState = forEachState; - - /***/ - }, - - /***/ "../../graphiql-react/dist/hint.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/hint.cjs.js ***! - \*********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - __webpack_require__( - /*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js" - ); - const graphqlLanguageService = __webpack_require__( - /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" - ); - codemirror.CodeMirror.registerHelper( - "hint", - "graphql", - (editor, options) => { - const { schema, externalFragments, autocompleteOptions } = options; - if (!schema) { - return; - } - const cur = editor.getCursor(); - const token = editor.getTokenAt(cur); - const tokenStart = - token.type !== null && /"|\w/.test(token.string[0]) - ? token.start - : token.end; - const position = new graphqlLanguageService.Position( - cur.line, - tokenStart - ); - const rawResults = - graphqlLanguageService.getAutocompleteSuggestions( - schema, - editor.getValue(), - position, - token, - externalFragments, - autocompleteOptions - ); - const results = { - list: rawResults.map((item) => { - var _a; - return { - text: - (_a = - item === null || item === void 0 - ? void 0 - : item.rawInsert) !== null && _a !== void 0 - ? _a - : item.label, - type: item.type, - description: item.documentation, - isDeprecated: item.isDeprecated, - deprecationReason: item.deprecationReason, - }; - }), - from: { - line: cur.line, - ch: tokenStart, - }, - to: { - line: cur.line, - ch: token.end, - }, - }; - if ( - (results === null || results === void 0 - ? void 0 - : results.list) && - results.list.length > 0 - ) { - results.from = codemirror.CodeMirror.Pos( - results.from.line, - results.from.ch - ); - results.to = codemirror.CodeMirror.Pos( - results.to.line, - results.to.ch - ); - codemirror.CodeMirror.signal( - editor, - "hasCompletion", - editor, - results, - token - ); + } } - return results; } - ); - - /***/ - }, - - /***/ "../../graphiql-react/dist/hint.cjs2.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/hint.cjs2.js ***! - \**********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const forEachState = __webpack_require__( - /*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js" - ); - function hintList(cursor, token, list) { - const hints = filterAndSortList(list, normalizeText(token.string)); - if (!hints) { - return; + } + } + `; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/getOperationAST.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getOperationAST.mjs ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getOperationAST = getOperationAST; + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + /** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ + + function getOperationAST(documentAST, operationName) { + let operation = null; + for (const definition of documentAST.definitions) { + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + var _definition$name; + if (operationName == null) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; } - const tokenStart = - token.type !== null && /"|\w/.test(token.string[0]) - ? token.start - : token.end; - return { - list: hints, - from: { - line: cursor.line, - ch: tokenStart, - }, - to: { - line: cursor.line, - ch: token.end, - }, - }; + operation = definition; + } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { + return definition; + } + } + } + return operation; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/getOperationRootType.mjs": + /*!************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getOperationRootType.mjs ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getOperationRootType = getOperationRootType; + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Extracts the root type of the operation from the schema. + * + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 + */ + function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + const queryType = schema.getQueryType(); + if (!queryType) { + throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', { + nodes: operation + }); + } + return queryType; + } + if (operation.operation === 'mutation') { + const mutationType = schema.getMutationType(); + if (!mutationType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', { + nodes: operation + }); + } + return mutationType; + } + if (operation.operation === 'subscription') { + const subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', { + nodes: operation + }); + } + return subscriptionType; + } + throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', { + nodes: operation + }); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/index.mjs": + /*!*********************************************************!*\ + !*** ../../../node_modules/graphql/utilities/index.mjs ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "BreakingChangeType", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.BreakingChangeType; + } + })); + Object.defineProperty(exports, "DangerousChangeType", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.DangerousChangeType; + } + })); + Object.defineProperty(exports, "TypeInfo", ({ + enumerable: true, + get: function () { + return _TypeInfo.TypeInfo; + } + })); + Object.defineProperty(exports, "assertValidName", ({ + enumerable: true, + get: function () { + return _assertValidName.assertValidName; + } + })); + Object.defineProperty(exports, "astFromValue", ({ + enumerable: true, + get: function () { + return _astFromValue.astFromValue; + } + })); + Object.defineProperty(exports, "buildASTSchema", ({ + enumerable: true, + get: function () { + return _buildASTSchema.buildASTSchema; + } + })); + Object.defineProperty(exports, "buildClientSchema", ({ + enumerable: true, + get: function () { + return _buildClientSchema.buildClientSchema; + } + })); + Object.defineProperty(exports, "buildSchema", ({ + enumerable: true, + get: function () { + return _buildASTSchema.buildSchema; + } + })); + Object.defineProperty(exports, "coerceInputValue", ({ + enumerable: true, + get: function () { + return _coerceInputValue.coerceInputValue; + } + })); + Object.defineProperty(exports, "concatAST", ({ + enumerable: true, + get: function () { + return _concatAST.concatAST; + } + })); + Object.defineProperty(exports, "doTypesOverlap", ({ + enumerable: true, + get: function () { + return _typeComparators.doTypesOverlap; + } + })); + Object.defineProperty(exports, "extendSchema", ({ + enumerable: true, + get: function () { + return _extendSchema.extendSchema; + } + })); + Object.defineProperty(exports, "findBreakingChanges", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.findBreakingChanges; + } + })); + Object.defineProperty(exports, "findDangerousChanges", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.findDangerousChanges; + } + })); + Object.defineProperty(exports, "getIntrospectionQuery", ({ + enumerable: true, + get: function () { + return _getIntrospectionQuery.getIntrospectionQuery; + } + })); + Object.defineProperty(exports, "getOperationAST", ({ + enumerable: true, + get: function () { + return _getOperationAST.getOperationAST; + } + })); + Object.defineProperty(exports, "getOperationRootType", ({ + enumerable: true, + get: function () { + return _getOperationRootType.getOperationRootType; + } + })); + Object.defineProperty(exports, "introspectionFromSchema", ({ + enumerable: true, + get: function () { + return _introspectionFromSchema.introspectionFromSchema; + } + })); + Object.defineProperty(exports, "isEqualType", ({ + enumerable: true, + get: function () { + return _typeComparators.isEqualType; + } + })); + Object.defineProperty(exports, "isTypeSubTypeOf", ({ + enumerable: true, + get: function () { + return _typeComparators.isTypeSubTypeOf; + } + })); + Object.defineProperty(exports, "isValidNameError", ({ + enumerable: true, + get: function () { + return _assertValidName.isValidNameError; + } + })); + Object.defineProperty(exports, "lexicographicSortSchema", ({ + enumerable: true, + get: function () { + return _lexicographicSortSchema.lexicographicSortSchema; + } + })); + Object.defineProperty(exports, "printIntrospectionSchema", ({ + enumerable: true, + get: function () { + return _printSchema.printIntrospectionSchema; + } + })); + Object.defineProperty(exports, "printSchema", ({ + enumerable: true, + get: function () { + return _printSchema.printSchema; + } + })); + Object.defineProperty(exports, "printType", ({ + enumerable: true, + get: function () { + return _printSchema.printType; + } + })); + Object.defineProperty(exports, "separateOperations", ({ + enumerable: true, + get: function () { + return _separateOperations.separateOperations; + } + })); + Object.defineProperty(exports, "stripIgnoredCharacters", ({ + enumerable: true, + get: function () { + return _stripIgnoredCharacters.stripIgnoredCharacters; + } + })); + Object.defineProperty(exports, "typeFromAST", ({ + enumerable: true, + get: function () { + return _typeFromAST.typeFromAST; + } + })); + Object.defineProperty(exports, "valueFromAST", ({ + enumerable: true, + get: function () { + return _valueFromAST.valueFromAST; + } + })); + Object.defineProperty(exports, "valueFromASTUntyped", ({ + enumerable: true, + get: function () { + return _valueFromASTUntyped.valueFromASTUntyped; + } + })); + Object.defineProperty(exports, "visitWithTypeInfo", ({ + enumerable: true, + get: function () { + return _TypeInfo.visitWithTypeInfo; + } + })); + var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); + var _getOperationAST = __webpack_require__(/*! ./getOperationAST.mjs */ "../../../node_modules/graphql/utilities/getOperationAST.mjs"); + var _getOperationRootType = __webpack_require__(/*! ./getOperationRootType.mjs */ "../../../node_modules/graphql/utilities/getOperationRootType.mjs"); + var _introspectionFromSchema = __webpack_require__(/*! ./introspectionFromSchema.mjs */ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs"); + var _buildClientSchema = __webpack_require__(/*! ./buildClientSchema.mjs */ "../../../node_modules/graphql/utilities/buildClientSchema.mjs"); + var _buildASTSchema = __webpack_require__(/*! ./buildASTSchema.mjs */ "../../../node_modules/graphql/utilities/buildASTSchema.mjs"); + var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); + var _lexicographicSortSchema = __webpack_require__(/*! ./lexicographicSortSchema.mjs */ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs"); + var _printSchema = __webpack_require__(/*! ./printSchema.mjs */ "../../../node_modules/graphql/utilities/printSchema.mjs"); + var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); + var _valueFromASTUntyped = __webpack_require__(/*! ./valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); + var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); + var _TypeInfo = __webpack_require__(/*! ./TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); + var _coerceInputValue = __webpack_require__(/*! ./coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); + var _concatAST = __webpack_require__(/*! ./concatAST.mjs */ "../../../node_modules/graphql/utilities/concatAST.mjs"); + var _separateOperations = __webpack_require__(/*! ./separateOperations.mjs */ "../../../node_modules/graphql/utilities/separateOperations.mjs"); + var _stripIgnoredCharacters = __webpack_require__(/*! ./stripIgnoredCharacters.mjs */ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs"); + var _typeComparators = __webpack_require__(/*! ./typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); + var _assertValidName = __webpack_require__(/*! ./assertValidName.mjs */ "../../../node_modules/graphql/utilities/assertValidName.mjs"); + var _findBreakingChanges = __webpack_require__(/*! ./findBreakingChanges.mjs */ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs": + /*!***************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/introspectionFromSchema.mjs ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.introspectionFromSchema = introspectionFromSchema; + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); + var _execute = __webpack_require__(/*! ../execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); + var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); + /** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ + + function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + ...options + }; + const document = (0, _parser.parse)((0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults)); + const result = (0, _execute.executeSync)({ + schema, + document + }); + !result.errors && result.data || (0, _invariant.invariant)(false); + return result.data; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs": + /*!***************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.lexicographicSortSchema = lexicographicSortSchema; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); + var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); + /** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ + + function lexicographicSortSchema(schema) { + const schemaConfig = schema.toConfig(); + const typeMap = (0, _keyValMap.keyValMap)(sortByName(schemaConfig.types), type => type.name, sortNamedType); + return new _schema.GraphQLSchema({ + ...schemaConfig, + types: Object.values(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription) + }); + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME: TS Conversion + + return replaceNamedType(type); + } + function replaceNamedType(type) { + return typeMap[type.name]; + } + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + function sortDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + locations: sortBy(config.locations, x => x), + args: sortArgs(config.args) + }); + } + function sortArgs(args) { + return sortObjMap(args, arg => ({ + ...arg, + type: replaceType(arg.type) + })); + } + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + ...field, + type: replaceType(field.type), + args: field.args && sortArgs(field.args) + })); + } + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + ...field, + type: replaceType(field.type) + })); + } + function sortTypes(array) { + return sortByName(array).map(replaceNamedType); + } + function sortNamedType(type) { + if ((0, _definition.isScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { + return type; + } + if ((0, _definition.isObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields) + }); + } + if ((0, _definition.isInterfaceType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields) + }); + } + if ((0, _definition.isUnionType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLUnionType({ + ...config, + types: () => sortTypes(config.types) + }); + } + if ((0, _definition.isEnumType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLEnumType({ + ...config, + values: sortObjMap(config.values, value => value) + }); + } + if ((0, _definition.isInputObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields) + }); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } + } + function sortObjMap(map, sortValueFn) { + const sortedMap = Object.create(null); + for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { + sortedMap[key] = sortValueFn(map[key]); + } + return sortedMap; + } + function sortByName(array) { + return sortBy(array, obj => obj.name); + } + function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return (0, _naturalCompare.naturalCompare)(key1, key2); + }); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/printSchema.mjs": + /*!***************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/printSchema.mjs ***! + \***************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.printIntrospectionSchema = printIntrospectionSchema; + exports.printSchema = printSchema; + exports.printType = printType; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); + function printSchema(schema) { + return printFilteredSchema(schema, n => !(0, _directives.isSpecifiedDirective)(n), isDefinedType); + } + function printIntrospectionSchema(schema) { + return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType); + } + function isDefinedType(type) { + return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); + } + function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [printSchemaDefinition(schema), ...directives.map(directive => printDirective(directive)), ...types.map(type => printType(type))].filter(Boolean).join('\n\n'); + } + function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + const operationTypes = []; + const queryType = schema.getQueryType(); + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + const mutationType = schema.getMutationType(); + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; + } + /** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * ```graphql + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * ``` + * + * When using this naming convention, the schema description can be omitted. + */ + + function isSchemaOfCommonNames(schema) { + const queryType = schema.getQueryType(); + if (queryType && queryType.name !== 'Query') { + return false; + } + const mutationType = schema.getMutationType(); + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + return true; + } + function printType(type) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type); + } + if ((0, _definition.isObjectType)(type)) { + return printObject(type); + } + if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type); + } + if ((0, _definition.isUnionType)(type)) { + return printUnion(type); + } + if ((0, _definition.isEnumType)(type)) { + return printEnum(type); + } + if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } + function printScalar(type) { + return printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type); + } + function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length ? ' implements ' + interfaces.map(i => i.name).join(' & ') : ''; + } + function printObject(type) { + return printDescription(type) + `type ${type.name}` + printImplementedInterfaces(type) + printFields(type); + } + function printInterface(type) { + return printDescription(type) + `interface ${type.name}` + printImplementedInterfaces(type) + printFields(type); + } + function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(type) + 'union ' + type.name + possibleTypes; + } + function printEnum(type) { + const values = type.getValues().map((value, i) => printDescription(value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason)); + return printDescription(type) + `enum ${type.name}` + printBlock(values); + } + function printInputObject(type) { + const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f)); + return printDescription(type) + `input ${type.name}` + printBlock(fields); + } + function printFields(type) { + const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + f.name + printArgs(f.args, ' ') + ': ' + String(f.type) + printDeprecated(f.deprecationReason)); + return printBlock(fields); + } + function printBlock(items) { + return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; + } + function printArgs(args, indentation = '') { + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + if (args.every(arg => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + return '(\n' + args.map((arg, i) => printDescription(arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg)).join('\n') + '\n' + indentation + ')'; + } + function printInputValue(arg) { + const defaultAST = (0, _astFromValue.astFromValue)(arg.defaultValue, arg.type); + let argDecl = arg.name + ': ' + String(arg.type); + if (defaultAST) { + argDecl += ` = ${(0, _printer.print)(defaultAST)}`; + } + return argDecl + printDeprecated(arg.deprecationReason); + } + function printDirective(directive) { + return printDescription(directive) + 'directive @' + directive.name + printArgs(directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | '); + } + function printDeprecated(reason) { + if (reason == null) { + return ''; + } + if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: reason + }); + return ` @deprecated(reason: ${astValue})`; + } + return ' @deprecated'; + } + function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ''; + } + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: scalar.specifiedByURL + }); + return ` @specifiedBy(url: ${astValue})`; + } + function printDescription(def, indentation = '', firstInBlock = true) { + const { + description + } = def; + if (description == null) { + return ''; + } + const blockString = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: description, + block: (0, _blockString.isPrintableAsBlockString)(description) + }); + const prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/separateOperations.mjs": + /*!**********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/separateOperations.mjs ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.separateOperations = separateOperations; + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); + /** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ + + function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + case _kinds.Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies(definitionNode.selectionSet); + break; + default: // ignore non-executable definitions + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + const separatedDocumentASTs = Object.create(null); + for (const operation of operations) { + const dependencies = new Set(); + for (const fragmentName of collectDependencies(operation.selectionSet)) { + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + separatedDocumentASTs[operationName] = { + kind: _kinds.Kind.DOCUMENT, + definitions: documentAST.definitions.filter(node => node === operation || node.kind === _kinds.Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value)) + }; + } + return separatedDocumentASTs; + } + + // From a dependency graph, collects a list of transitive dependencies by + // recursing through a dependency graph. + function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } + } + function collectDependencies(selectionSet) { + const dependencies = []; + (0, _visitor.visit)(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + } + }); + return dependencies; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/sortValueNode.mjs": + /*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/sortValueNode.mjs ***! + \*****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.sortValueNode = sortValueNode; + var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + /** + * Sort ValueNode. + * + * This function returns a sorted copy of the given ValueNode. + * + * @internal + */ + + function sortValueNode(valueNode) { + switch (valueNode.kind) { + case _kinds.Kind.OBJECT: + return { + ...valueNode, + fields: sortFields(valueNode.fields) + }; + case _kinds.Kind.LIST: + return { + ...valueNode, + values: valueNode.values.map(sortValueNode) + }; + case _kinds.Kind.INT: + case _kinds.Kind.FLOAT: + case _kinds.Kind.STRING: + case _kinds.Kind.BOOLEAN: + case _kinds.Kind.NULL: + case _kinds.Kind.ENUM: + case _kinds.Kind.VARIABLE: + return valueNode; + } + } + function sortFields(fields) { + return fields.map(fieldNode => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value) + })).sort((fieldA, fieldB) => (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value)); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs": + /*!**************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.stripIgnoredCharacters = stripIgnoredCharacters; + var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); + var _lexer = __webpack_require__(/*! ../language/lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); + var _source = __webpack_require__(/*! ../language/source.mjs */ "../../../node_modules/graphql/language/source.mjs"); + var _tokenKind = __webpack_require__(/*! ../language/tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); + /** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - WhiteSpace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * + * Query example: + * + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * + * SDL example: + * + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + */ + + function stripIgnoredCharacters(source) { + const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); + const body = sourceObj.body; + const lexer = new _lexer.Lexer(sourceObj); + let strippedBody = ''; + let wasLastAddedTokenNonPunctuator = false; + while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + /** + * Every two non-punctuator tokens should have space between them. + * Also prevent case of non-punctuator token following by spread resulting + * in invalid token (e.g. `1...` is invalid Float token). + */ + + const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)(currentToken.kind); + if (wasLastAddedTokenNonPunctuator) { + if (isNonPunctuator || currentToken.kind === _tokenKind.TokenKind.SPREAD) { + strippedBody += ' '; } - function filterAndSortList(list, text) { - if (!text) { - return filterNonEmpty(list, (entry) => !entry.isDeprecated); - } - const byProximity = list.map((entry) => ({ - proximity: getProximity(normalizeText(entry.text), text), - entry, - })); - const conciseMatches = filterNonEmpty( - filterNonEmpty(byProximity, (pair) => pair.proximity <= 2), - (pair) => !pair.entry.isDeprecated - ); - const sortedMatches = conciseMatches.sort( - (a, b) => - (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || - a.proximity - b.proximity || - a.entry.text.length - b.entry.text.length - ); - return sortedMatches.map((pair) => pair.entry); - } - function filterNonEmpty(array, predicate) { - const filtered = array.filter(predicate); - return filtered.length === 0 ? array : filtered; - } - function normalizeText(text) { - return text.toLowerCase().replaceAll(/\W/g, ""); - } - function getProximity(suggestion, text) { - let proximity = lexicalDistance(text, suggestion); - if (suggestion.length > text.length) { - proximity -= suggestion.length - text.length - 1; - proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; - } - return proximity; - } - function lexicalDistance(a, b) { - let i; - let j; - const d = []; - const aLength = a.length; - const bLength = b.length; - for (i = 0; i <= aLength; i++) { - d[i] = [i]; - } - for (j = 1; j <= bLength; j++) { - d[0][j] = j; - } - for (i = 1; i <= aLength; i++) { - for (j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - d[i][j] = Math.min( - d[i - 1][j] + 1, - d[i][j - 1] + 1, - d[i - 1][j - 1] + cost - ); - if ( - i > 1 && - j > 1 && - a[i - 1] === b[j - 2] && - a[i - 2] === b[j - 1] - ) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); - } + } + const tokenBody = body.slice(currentToken.start, currentToken.end); + if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { + strippedBody += (0, _blockString.printBlockString)(currentToken.value, { + minimize: true + }); + } else { + strippedBody += tokenBody; + } + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + return strippedBody; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/typeComparators.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/typeComparators.mjs ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.doTypesOverlap = doTypesOverlap; + exports.isEqualType = isEqualType; + exports.isTypeSubTypeOf = isTypeSubTypeOf; + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Provided two types, return true if the types are equal (invariant). + */ + function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + return false; + } + /** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + + function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, check if it is super type of maybeSubType. + // Otherwise, the child type is not a valid subtype of the parent type. + + return (0, _definition.isAbstractType)(superType) && ((0, _definition.isInterfaceType)(maybeSubType) || (0, _definition.isObjectType)(maybeSubType)) && schema.isSubType(superType, maybeSubType); + } + /** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + + function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema.getPossibleTypes(typeA).some(type => schema.isSubType(typeB, type)); + } // Determine if the latter type is a possible concrete type of the former. + + return schema.isSubType(typeA, typeB); + } + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isSubType(typeB, typeA); + } // Otherwise the types do not overlap. + + return false; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/typeFromAST.mjs": + /*!***************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/typeFromAST.mjs ***! + \***************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.typeFromAST = typeFromAST; + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case _kinds.Kind.LIST_TYPE: + { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); + } + case _kinds.Kind.NON_NULL_TYPE: + { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } + case _kinds.Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/valueFromAST.mjs": + /*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/valueFromAST.mjs ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.valueFromAST = valueFromAST; + var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | + * + */ + + function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (variables == null || variables[variableName] === undefined) { + // No valid return value. + return; + } + const variableValue = variables[variableName]; + if (variableValue === null && (0, _definition.isNonNullType)(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + return variableValue; + } + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. + } + return valueFromAST(valueNode, type.ofType, variables); + } + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if (valueNode.kind === _kinds.Kind.LIST) { + const coercedValues = []; + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. } - } - return d[aLength][bLength]; - } - codemirror.CodeMirror.registerHelper( - "hint", - "graphql-variables", - (editor, options) => { - const cur = editor.getCursor(); - const token = editor.getTokenAt(cur); - const results = getVariablesHint(cur, token, options); - if ( - (results === null || results === void 0 - ? void 0 - : results.list) && - results.list.length > 0 - ) { - results.from = codemirror.CodeMirror.Pos( - results.from.line, - results.from.ch - ); - results.to = codemirror.CodeMirror.Pos( - results.to.line, - results.to.ch - ); - codemirror.CodeMirror.signal( - editor, - "hasCompletion", - editor, - results, - token - ); + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. } - return results; - } - ); - function getVariablesHint(cur, token, options) { - const state = - token.state.kind === "Invalid" - ? token.state.prevState - : token.state; - const { kind, step } = state; - if (kind === "Document" && step === 0) { - return hintList(cur, token, [ - { - text: "{", - }, - ]); - } - const { variableToType } = options; - if (!variableToType) { - return; - } - const typeInfo = getTypeInfo(variableToType, token.state); - if (kind === "Document" || (kind === "Variable" && step === 0)) { - const variableNames = Object.keys(variableToType); - return hintList( - cur, - token, - variableNames.map((name) => ({ - text: `"${name}": `, - type: variableToType[name], - })) - ); + coercedValues.push(itemValue); } - if ( - (kind === "ObjectValue" || - (kind === "ObjectField" && step === 0)) && - typeInfo.fields - ) { - const inputFields = Object.keys(typeInfo.fields).map( - (fieldName) => typeInfo.fields[fieldName] - ); - return hintList( - cur, - token, - inputFields.map((field) => ({ - text: `"${field.name}": `, - type: field.type, - description: field.description, - })) - ); + } + return coercedValues; + } + const coercedValue = valueFromAST(valueNode, itemType, variables); + if (coercedValue === undefined) { + return; // Invalid: intentionally return no value. + } + return [coercedValue]; + } + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + const coercedObj = Object.create(null); + const fieldNodes = (0, _keyMap.keyMap)(valueNode.fields, field => field.name.value); + for (const field of Object.values(type.getFields())) { + const fieldNode = fieldNodes[field.name]; + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } + continue; + } + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + coercedObj[field.name] = fieldValue; + } + return coercedObj; + } + if ((0, _definition.isLeafType)(type)) { + // Scalars and Enums fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + if (result === undefined) { + return; // Invalid: intentionally return no value. + } + return result; + } + /* c8 ignore next 3 */ + // Not reachable, all possible input types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); + } // Returns true if the provided valueNode is a variable which is not defined + // in the set of variables. + + function isMissingVariable(valueNode, variables) { + return valueNode.kind === _kinds.Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs": + /*!***********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.valueFromASTUntyped = valueFromASTUntyped; + var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + /** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ + + function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; + case _kinds.Kind.LIST: + return valueNode.values.map(node => valueFromASTUntyped(node, variables)); + case _kinds.Kind.OBJECT: + return (0, _keyValMap.keyValMap)(valueNode.fields, field => field.name.value, field => valueFromASTUntyped(field.value, variables)); + case _kinds.Kind.VARIABLE: + return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value]; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/ValidationContext.mjs": + /*!**********************************************************************!*\ + !*** ../../../node_modules/graphql/validation/ValidationContext.mjs ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; + var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); + var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); + /** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ + class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + get [Symbol.toStringTag]() { + return 'ASTValidationContext'; + } + reportError(error) { + this._onError(error); + } + getDocument() { + return this._ast; + } + getFragment(name) { + let fragments; + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + this._fragments = fragments; + } + return fragments[name]; + } + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + while (set = setsToVisit.pop()) { + for (const selection of set.selections) { + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + } + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit = [operation.selectionSet]; + let node; + while (node = nodesToVisit.pop()) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } + } + exports.ASTValidationContext = ASTValidationContext; + class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } + get [Symbol.toStringTag]() { + return 'SDLValidationContext'; + } + getSchema() { + return this._schema; + } + } + exports.SDLValidationContext = SDLValidationContext; + class ValidationContext extends ASTValidationContext { + constructor(schema, ast, typeInfo, onError) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + get [Symbol.toStringTag]() { + return 'ValidationContext'; + } + getSchema() { + return this._schema; + } + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)(node, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); } - if ( - kind === "StringValue" || - kind === "NumberValue" || - kind === "BooleanValue" || - kind === "NullValue" || - (kind === "ListValue" && step === 1) || - (kind === "ObjectField" && step === 2) || - (kind === "Variable" && step === 2) - ) { - const namedInputType = typeInfo.type - ? graphql.getNamedType(typeInfo.type) - : void 0; - if (namedInputType instanceof graphql.GraphQLInputObjectType) { - return hintList(cur, token, [ - { - text: "{", - }, - ]); - } - if (namedInputType instanceof graphql.GraphQLEnumType) { - const values = namedInputType.getValues(); - return hintList( - cur, - token, - values.map((value) => ({ - text: `"${value.name}"`, - type: namedInputType, - description: value.description, - })) - ); - } - if (namedInputType === graphql.GraphQLBoolean) { - return hintList(cur, token, [ - { - text: "true", - type: graphql.GraphQLBoolean, - description: "Not false.", - }, - { - text: "false", - type: graphql.GraphQLBoolean, - description: "Not true.", - }, - ]); - } + })); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + } + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } + this._recursiveVariableUsages.set(operation, usages); + } + return usages; + } + getType() { + return this._typeInfo.getType(); + } + getParentType() { + return this._typeInfo.getParentType(); + } + getInputType() { + return this._typeInfo.getInputType(); + } + getParentInputType() { + return this._typeInfo.getParentInputType(); + } + getFieldDef() { + return this._typeInfo.getFieldDef(); + } + getDirective() { + return this._typeInfo.getDirective(); + } + getArgument() { + return this._typeInfo.getArgument(); + } + getEnumValue() { + return this._typeInfo.getEnumValue(); + } + } + exports.ValidationContext = ValidationContext; + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/index.mjs": + /*!**********************************************************!*\ + !*** ../../../node_modules/graphql/validation/index.mjs ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ + enumerable: true, + get: function () { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + } + })); + Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; + } + })); + Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ + enumerable: true, + get: function () { + return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; + } + })); + Object.defineProperty(exports, "KnownArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _KnownArgumentNamesRule.KnownArgumentNamesRule; + } + })); + Object.defineProperty(exports, "KnownDirectivesRule", ({ + enumerable: true, + get: function () { + return _KnownDirectivesRule.KnownDirectivesRule; + } + })); + Object.defineProperty(exports, "KnownFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _KnownFragmentNamesRule.KnownFragmentNamesRule; + } + })); + Object.defineProperty(exports, "KnownTypeNamesRule", ({ + enumerable: true, + get: function () { + return _KnownTypeNamesRule.KnownTypeNamesRule; + } + })); + Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ + enumerable: true, + get: function () { + return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; + } + })); + Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ + enumerable: true, + get: function () { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + } + })); + Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ + enumerable: true, + get: function () { + return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; + } + })); + Object.defineProperty(exports, "NoFragmentCyclesRule", ({ + enumerable: true, + get: function () { + return _NoFragmentCyclesRule.NoFragmentCyclesRule; + } + })); + Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ + enumerable: true, + get: function () { + return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; + } + })); + Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ + enumerable: true, + get: function () { + return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; + } + })); + Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ + enumerable: true, + get: function () { + return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; + } + })); + Object.defineProperty(exports, "NoUnusedVariablesRule", ({ + enumerable: true, + get: function () { + return _NoUnusedVariablesRule.NoUnusedVariablesRule; + } + })); + Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ + enumerable: true, + get: function () { + return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; + } + })); + Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ + enumerable: true, + get: function () { + return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; + } + })); + Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ + enumerable: true, + get: function () { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + } + })); + Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ + enumerable: true, + get: function () { + return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; + } + })); + Object.defineProperty(exports, "ScalarLeafsRule", ({ + enumerable: true, + get: function () { + return _ScalarLeafsRule.ScalarLeafsRule; + } + })); + Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ + enumerable: true, + get: function () { + return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; + } + })); + Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; + } + })); + Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; + } + })); + Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + } + })); + Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ + enumerable: true, + get: function () { + return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; + } + })); + Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + } + })); + Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + } + })); + Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; + } + })); + Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; + } + })); + Object.defineProperty(exports, "UniqueOperationNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueOperationNamesRule.UniqueOperationNamesRule; + } + })); + Object.defineProperty(exports, "UniqueOperationTypesRule", ({ + enumerable: true, + get: function () { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + } + })); + Object.defineProperty(exports, "UniqueTypeNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + } + })); + Object.defineProperty(exports, "UniqueVariableNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueVariableNamesRule.UniqueVariableNamesRule; + } + })); + Object.defineProperty(exports, "ValidationContext", ({ + enumerable: true, + get: function () { + return _ValidationContext.ValidationContext; + } + })); + Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; + } + })); + Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ + enumerable: true, + get: function () { + return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; + } + })); + Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ + enumerable: true, + get: function () { + return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; + } + })); + Object.defineProperty(exports, "specifiedRules", ({ + enumerable: true, + get: function () { + return _specifiedRules.specifiedRules; + } + })); + Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.validate; + } + })); + var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); + var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); + var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); + var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); + var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); + var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); + var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); + var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); + var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); + var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); + var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); + var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); + var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); + var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); + var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); + var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); + var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); + var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); + var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); + var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); + var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); + var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); + var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); + var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); + var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); + var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); + var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); + var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); + var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); + var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); + var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); + var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); + var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); + var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); + var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); + var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); + var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); + var _NoDeprecatedCustomRule = __webpack_require__(/*! ./rules/custom/NoDeprecatedCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs"); + var _NoSchemaIntrospectionCustomRule = __webpack_require__(/*! ./rules/custom/NoSchemaIntrospectionCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs"); + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs": + /*!************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs ***! + \************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); + /** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + */ + function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + const defName = definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"'; + context.reportError(new _GraphQLError.GraphQLError(`The ${defName} definition is not executable.`, { + nodes: definition + })); } } - function getTypeInfo(variableToType, tokenState) { - const info = { - type: null, - fields: null, - }; - forEachState.forEachState(tokenState, (state) => { - switch (state.kind) { - case "Variable": { - info.type = variableToType[state.name]; - break; - } - case "ListValue": { - const nullableType = info.type - ? graphql.getNullableType(info.type) - : void 0; - info.type = - nullableType instanceof graphql.GraphQLList - ? nullableType.ofType - : null; - break; - } - case "ObjectValue": { - const objectType = info.type - ? graphql.getNamedType(info.type) - : void 0; - info.fields = - objectType instanceof graphql.GraphQLInputObjectType - ? objectType.getFields() - : null; - break; - } - case "ObjectField": { - const objectField = - state.name && info.fields ? info.fields[state.name] : null; - info.type = - objectField === null || objectField === void 0 - ? void 0 - : objectField.type; - break; - } - } - }); - return info; + return false; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; + var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _naturalCompare = __webpack_require__(/*! ../../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); + var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + */ + function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + let suggestion = (0, _didYouMean.didYouMean)('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === '') { + suggestion = (0, _didYouMean.didYouMean)(getSuggestedFieldNames(type, fieldName)); + } // Report an error, including helpful suggestions. + + context.reportError(new _GraphQLError.GraphQLError(`Cannot query field "${fieldName}" on type "${type.name}".` + suggestion, { + nodes: node + })); + } } - - /***/ - }, - - /***/ "../../graphiql-react/dist/index.js": - /*!******************************************!*\ - !*** ../../graphiql-react/dist/index.js ***! - \******************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, Symbol.toStringTag, { - value: "Module", - }); - const jsxRuntime = __webpack_require__( - /*! react/jsx-runtime */ "../../../node_modules/react/jsx-runtime.js" - ); - const React = __webpack_require__(/*! react */ "react"); - const clsx = __webpack_require__( - /*! clsx */ "../../../node_modules/clsx/dist/clsx.m.js" - ); - const graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const toolkit = __webpack_require__( - /*! @graphiql/toolkit */ "../../graphiql-toolkit/esm/index.js" - ); - const graphqlLanguageService = __webpack_require__( - /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" - ); - const setValue = __webpack_require__( - /*! set-value */ "../../../node_modules/set-value/index.js" - ); - const copyToClipboard = __webpack_require__( - /*! copy-to-clipboard */ "../../../node_modules/copy-to-clipboard/index.js" - ); - const D = __webpack_require__( - /*! @radix-ui/react-dialog */ "../../../node_modules/@radix-ui/react-dialog/dist/index.js" - ); - const reactVisuallyHidden = __webpack_require__( - /*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js" - ); - const reactDropdownMenu = __webpack_require__( - /*! @radix-ui/react-dropdown-menu */ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js" - ); - const MarkdownIt = __webpack_require__( - /*! markdown-it */ "../node_modules/markdown-it/dist/index.cjs.js" - ); - const framerMotion = __webpack_require__( - /*! framer-motion */ "../../../node_modules/framer-motion/dist/cjs/index.js" - ); - const T = __webpack_require__( - /*! @radix-ui/react-tooltip */ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js" - ); - const react = __webpack_require__( - /*! @headlessui/react */ "../../../node_modules/@headlessui/react/dist/index.cjs" - ); - const ReactDOM = __webpack_require__(/*! react-dom */ "react-dom"); - function _interopNamespaceDefault(e) { - const n = Object.create(null, { - [Symbol.toStringTag]: { - value: "Module", - }, - }); - if (e) { - for (const k in e) { - if (k !== "default") { - const d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } + } + }; + } + /** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ + + function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, _definition.isAbstractType)(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + const suggestedTypes = new Set(); + const usageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + for (const possibleInterface of possibleType.getInterfaces()) { + var _usageCount$possibleI; + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1; + } + } + return [...suggestedTypes].sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + if ((0, _definition.isInterfaceType)(typeA) && schema.isSubType(typeA, typeB)) { + return -1; + } + if ((0, _definition.isInterfaceType)(typeB) && schema.isSubType(typeB, typeA)) { + return 1; + } + return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); + }).map(x => x.name); + } + /** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + function getSuggestedFieldNames(type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + return []; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs": + /*!****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs ***! + \****************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + /** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + */ + function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(typeCondition); + context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot condition on non composite type "${typeStr}".`, { + nodes: typeCondition + })); } - n.default = e; - return Object.freeze(n); - } - const React__namespace = - /* @__PURE__ */ _interopNamespaceDefault(React); - const D__namespace = /* @__PURE__ */ _interopNamespaceDefault(D); - const T__namespace = /* @__PURE__ */ _interopNamespaceDefault(T); - function createNullableContext(name) { - const context = React.createContext(null); - context.displayName = name; - return context; } - function createContextHook(context) { - function useGivenContext(options) { - var _a; - const value = React.useContext(context); - if ( - value === null && - (options == null ? void 0 : options.nonNull) - ) { - throw new Error( - `Tried to use \`${ - ((_a = options.caller) == null ? void 0 : _a.name) || - useGivenContext.caller.name - }\` without the necessary context. Make sure to render the \`${ - context.displayName - }Provider\` component higher up the tree.` - ); - } - return value; - } - Object.defineProperty(useGivenContext, "name", { - value: `use${context.displayName}`, - }); - return useGivenContext; + }, + FragmentDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(node.typeCondition); + context.reportError(new _GraphQLError.GraphQLError(`Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, { + nodes: node.typeCondition + })); } - const StorageContext = createNullableContext("StorageContext"); - function StorageContextProvider(props) { - const isInitialRender = React.useRef(true); - const [storage, setStorage] = React.useState( - new toolkit.StorageAPI(props.storage) - ); - React.useEffect(() => { - if (isInitialRender.current) { - isInitialRender.current = false; - } else { - setStorage(new toolkit.StorageAPI(props.storage)); - } - }, [props.storage]); - return /* @__PURE__ */ jsxRuntime.jsx(StorageContext.Provider, { - value: storage, - children: props.children, - }); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs": + /*!*********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs ***! + \*********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; + exports.KnownArgumentNamesRule = KnownArgumentNamesRule; + var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + /** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + */ + function KnownArgumentNamesRule(context) { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map(arg => arg.name); + const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgsNames); + context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + (0, _didYouMean.didYouMean)(suggestions), { + nodes: argNode + })); } - const useStorageContext = createContextHook(StorageContext); - const SvgArgument = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 6, - y: 6, - width: 2, - height: 2, - rx: 1, - fill: "currentColor", - }) - ); - const SvgChevronDown = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 9", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M1 1L7 7L13 1", - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgChevronLeft = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 7 10", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M6 1.04819L2 5.04819L6 9.04819", - stroke: "currentColor", - strokeWidth: 1.75, - }) - ); - const SvgChevronUp = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 9", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M13 8L7 2L1 8", - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgClose = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 14", - stroke: "currentColor", - strokeWidth: 3, - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M1 1L12.9998 12.9997", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M13 1L1.00079 13.0003", - }) - ); - const SvgCopy = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "-2 -2 22 22", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M11.25 14.2105V15.235C11.25 16.3479 10.3479 17.25 9.23501 17.25H2.76499C1.65214 17.25 0.75 16.3479 0.75 15.235L0.75 8.76499C0.75 7.65214 1.65214 6.75 2.76499 6.75L3.78947 6.75", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 6.75, - y: 0.75, - width: 10.5, - height: 10.5, - rx: 2.2069, - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgDeprecatedArgument = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M5 9L9 5", - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M5 5L9 9", - stroke: "currentColor", - strokeWidth: 1.2, - }) - ); - const SvgDeprecatedEnumValue = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4 8L8 4", - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4 4L8 8", - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", - fill: "currentColor", - }) - ); - const SvgDeprecatedField = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 10.8, - height: 10.8, - rx: 3.4, - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4 8L8 4", - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4 4L8 8", - stroke: "currentColor", - strokeWidth: 1.2, - }) - ); - const SvgDirective = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0.5 12 12", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 7, - y: 5.5, - width: 2, - height: 2, - rx: 1, - transform: "rotate(90 7 5.5)", - fill: "currentColor", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M10.8 9L10.8 9.5C10.8 10.4941 9.99411 11.3 9 11.3L3 11.3C2.00589 11.3 1.2 10.4941 1.2 9.5L1.2 9L-3.71547e-07 9L-3.93402e-07 9.5C-4.65826e-07 11.1569 1.34314 12.5 3 12.5L9 12.5C10.6569 12.5 12 11.1569 12 9.5L12 9L10.8 9ZM10.8 4L12 4L12 3.5C12 1.84315 10.6569 0.5 9 0.5L3 0.5C1.34315 0.5 -5.87117e-08 1.84315 -1.31135e-07 3.5L-1.5299e-07 4L1.2 4L1.2 3.5C1.2 2.50589 2.00589 1.7 3 1.7L9 1.7C9.99411 1.7 10.8 2.50589 10.8 3.5L10.8 4Z", - fill: "currentColor", - }) - ); - const SvgDocsFilled = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 20 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H17.25C17.8023 0.75 18.25 1.19772 18.25 1.75V5.25", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H18.25C18.8023 5.25 19.25 5.69771 19.25 6.25V22.25C19.25 22.8023 18.8023 23.25 18.25 23.25H3C1.75736 23.25 0.75 22.2426 0.75 21V3Z", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M3 5.25C1.75736 5.25 0.75 4.24264 0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H3ZM13 11L6 11V12.5L13 12.5V11Z", - fill: "currentColor", - }) - ); - const SvgDocs = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 20 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H17.25M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H16.25C16.8023 0.75 17.25 1.19772 17.25 1.75V5.25M0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H17.25", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("line", { - x1: 13, - y1: 11.75, - x2: 6, - y2: 11.75, - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgEnumValue = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 5, - y: 5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", - fill: "currentColor", - }) - ); - const SvgField = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 12 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 0.6, - y: 1.1, - width: 10.8, - height: 10.8, - rx: 2.4, - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 5, - y: 5.5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor", - }) - ); - const SvgHistory = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 24 20", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M1.59375 9.52344L4.87259 12.9944L8.07872 9.41249", - stroke: "currentColor", - strokeWidth: 1.5, - strokeLinecap: "square", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M13.75 5.25V10.75H18.75", - stroke: "currentColor", - strokeWidth: 1.5, - strokeLinecap: "square", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4.95427 11.9332C4.55457 10.0629 4.74441 8.11477 5.49765 6.35686C6.25089 4.59894 7.5305 3.11772 9.16034 2.11709C10.7902 1.11647 12.6901 0.645626 14.5986 0.769388C16.5071 0.893151 18.3303 1.60543 19.8172 2.80818C21.3042 4.01093 22.3818 5.64501 22.9017 7.48548C23.4216 9.32595 23.3582 11.2823 22.7203 13.0853C22.0824 14.8883 20.9013 16.4492 19.3396 17.5532C17.778 18.6572 15.9125 19.25 14 19.25", - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgImplements = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("circle", { - cx: 6, - cy: 6, - r: 5.4, - stroke: "currentColor", - strokeWidth: 1.2, - strokeDasharray: "4.241025 4.241025", - transform: "rotate(22.5)", - "transform-origin": "center", - }), - /* @__PURE__ */ React__namespace.createElement("circle", { - cx: 6, - cy: 6, - r: 1, - fill: "currentColor", - }) - ); - const SvgKeyboardShortcut = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 19 18", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M1.5 14.5653C1.5 15.211 1.75652 15.8303 2.21314 16.2869C2.66975 16.7435 3.28905 17 3.9348 17C4.58054 17 5.19984 16.7435 5.65646 16.2869C6.11307 15.8303 6.36959 15.211 6.36959 14.5653V12.1305H3.9348C3.28905 12.1305 2.66975 12.387 2.21314 12.8437C1.75652 13.3003 1.5 13.9195 1.5 14.5653Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M3.9348 1.00063C3.28905 1.00063 2.66975 1.25715 2.21314 1.71375C1.75652 2.17035 1.5 2.78964 1.5 3.43537C1.5 4.0811 1.75652 4.70038 2.21314 5.15698C2.66975 5.61358 3.28905 5.8701 3.9348 5.8701H6.36959V3.43537C6.36959 2.78964 6.11307 2.17035 5.65646 1.71375C5.19984 1.25715 4.58054 1.00063 3.9348 1.00063Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M15.0652 12.1305H12.6304V14.5653C12.6304 15.0468 12.7732 15.5175 13.0407 15.9179C13.3083 16.3183 13.6885 16.6304 14.1334 16.8147C14.5783 16.9989 15.0679 17.0472 15.5402 16.9532C16.0125 16.8593 16.4464 16.6274 16.7869 16.2869C17.1274 15.9464 17.3593 15.5126 17.4532 15.0403C17.5472 14.568 17.4989 14.0784 17.3147 13.6335C17.1304 13.1886 16.8183 12.8084 16.4179 12.5409C16.0175 12.2733 15.5468 12.1305 15.0652 12.1305Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M12.6318 5.86775H6.36955V12.1285H12.6318V5.86775Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M17.5 3.43473C17.5 2.789 17.2435 2.16972 16.7869 1.71312C16.3303 1.25652 15.711 1 15.0652 1C14.4195 1 13.8002 1.25652 13.3435 1.71312C12.8869 2.16972 12.6304 2.789 12.6304 3.43473V5.86946H15.0652C15.711 5.86946 16.3303 5.61295 16.7869 5.15635C17.2435 4.69975 17.5 4.08046 17.5 3.43473Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round", - }) - ); - const SvgMagnifyingGlass = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("circle", { - cx: 5, - cy: 5, - r: 4.35, - stroke: "currentColor", - strokeWidth: 1.3, - }), - /* @__PURE__ */ React__namespace.createElement("line", { - x1: 8.45962, - y1: 8.54038, - x2: 11.7525, - y2: 11.8333, - stroke: "currentColor", - strokeWidth: 1.3, - }) - ); - const SvgMerge = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "-2 -2 22 22", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M17.2492 6V2.9569C17.2492 1.73806 16.2611 0.75 15.0423 0.75L2.9569 0.75C1.73806 0.75 0.75 1.73806 0.75 2.9569L0.75 6", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M0.749873 12V15.0431C0.749873 16.2619 1.73794 17.25 2.95677 17.25H15.0421C16.261 17.25 17.249 16.2619 17.249 15.0431V12", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M6 4.5L9 7.5L12 4.5", - stroke: "currentColor", - strokeWidth: 1.5, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M12 13.5L9 10.5L6 13.5", - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgPen = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M0.75 13.25L0.0554307 12.967C-0.0593528 13.2488 0.00743073 13.5719 0.224488 13.7851C0.441545 13.9983 0.765869 14.0592 1.04549 13.9393L0.75 13.25ZM12.8214 1.83253L12.2911 2.36286L12.2911 2.36286L12.8214 1.83253ZM12.8214 3.90194L13.3517 4.43227L12.8214 3.90194ZM10.0981 1.17859L9.56773 0.648259L10.0981 1.17859ZM12.1675 1.17859L12.6978 0.648258L12.6978 0.648257L12.1675 1.17859ZM2.58049 8.75697L3.27506 9.03994L2.58049 8.75697ZM2.70066 8.57599L3.23099 9.10632L2.70066 8.57599ZM5.2479 11.4195L4.95355 10.7297L5.2479 11.4195ZM5.42036 11.303L4.89003 10.7727L5.42036 11.303ZM4.95355 10.7297C4.08882 11.0987 3.41842 11.362 2.73535 11.6308C2.05146 11.9 1.35588 12.1743 0.454511 12.5607L1.04549 13.9393C1.92476 13.5624 2.60256 13.2951 3.28469 13.0266C3.96762 12.7578 4.65585 12.4876 5.54225 12.1093L4.95355 10.7297ZM1.44457 13.533L3.27506 9.03994L1.88592 8.474L0.0554307 12.967L1.44457 13.533ZM3.23099 9.10632L10.6284 1.70892L9.56773 0.648259L2.17033 8.04566L3.23099 9.10632ZM11.6371 1.70892L12.2911 2.36286L13.3517 1.3022L12.6978 0.648258L11.6371 1.70892ZM12.2911 3.37161L4.89003 10.7727L5.95069 11.8333L13.3517 4.43227L12.2911 3.37161ZM12.2911 2.36286C12.5696 2.64142 12.5696 3.09305 12.2911 3.37161L13.3517 4.43227C14.2161 3.56792 14.2161 2.16654 13.3517 1.3022L12.2911 2.36286ZM10.6284 1.70892C10.9069 1.43036 11.3586 1.43036 11.6371 1.70892L12.6978 0.648257C11.8335 -0.216088 10.4321 -0.216084 9.56773 0.648259L10.6284 1.70892ZM3.27506 9.03994C3.26494 9.06479 3.24996 9.08735 3.23099 9.10632L2.17033 8.04566C2.04793 8.16806 1.95123 8.31369 1.88592 8.474L3.27506 9.03994ZM5.54225 12.1093C5.69431 12.0444 5.83339 11.9506 5.95069 11.8333L4.89003 10.7727C4.90863 10.7541 4.92988 10.7398 4.95355 10.7297L5.54225 12.1093Z", - fill: "currentColor", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M11.5 4.5L9.5 2.5", - stroke: "currentColor", - strokeWidth: 1.4026, - strokeLinecap: "round", - strokeLinejoin: "round", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M5.5 10.5L3.5 8.5", - stroke: "currentColor", - strokeWidth: 1.4026, - strokeLinecap: "round", - strokeLinejoin: "round", - }) - ); - const SvgPlay = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 16 18", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M1.32226e-07 1.6609C7.22332e-08 0.907329 0.801887 0.424528 1.46789 0.777117L15.3306 8.11621C16.0401 8.49182 16.0401 9.50818 15.3306 9.88379L1.46789 17.2229C0.801886 17.5755 1.36076e-06 17.0927 1.30077e-06 16.3391L1.32226e-07 1.6609Z", - fill: "currentColor", - }) - ); - const SvgPlus = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 10 16", - fill: "currentColor", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M4.25 9.25V13.5H5.75V9.25L10 9.25V7.75L5.75 7.75V3.5H4.25V7.75L0 7.75V9.25L4.25 9.25Z", - }) - ); - const SvgPrettify = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - width: 25, - height: 25, - viewBox: "0 0 25 25", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M10.2852 24.0745L13.7139 18.0742", - stroke: "currentColor", - strokeWidth: 1.5625, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M14.5742 24.0749L17.1457 19.7891", - stroke: "currentColor", - strokeWidth: 1.5625, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M19.4868 24.0735L20.7229 21.7523C21.3259 20.6143 21.5457 19.3122 21.3496 18.0394C21.1535 16.7666 20.5519 15.591 19.6342 14.6874L23.7984 6.87853C24.0123 6.47728 24.0581 6.00748 23.9256 5.57249C23.7932 5.1375 23.4933 4.77294 23.0921 4.55901C22.6908 4.34509 22.221 4.29932 21.7861 4.43178C21.3511 4.56424 20.9865 4.86408 20.7726 5.26533L16.6084 13.0742C15.3474 12.8142 14.0362 12.9683 12.8699 13.5135C11.7035 14.0586 10.7443 14.9658 10.135 16.1L6 24.0735", - stroke: "currentColor", - strokeWidth: 1.5625, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4 15L5 13L7 12L5 11L4 9L3 11L1 12L3 13L4 15Z", - stroke: "currentColor", - strokeWidth: 1.5625, - strokeLinejoin: "round", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M11.5 8L12.6662 5.6662L15 4.5L12.6662 3.3338L11.5 1L10.3338 3.3338L8 4.5L10.3338 5.6662L11.5 8Z", - stroke: "currentColor", - strokeWidth: 1.5625, - strokeLinejoin: "round", - }) - ); - const SvgReload = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 16 16", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4.75 9.25H1.25V12.75", - stroke: "currentColor", - strokeWidth: 1, - strokeLinecap: "square", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M11.25 6.75H14.75V3.25", - stroke: "currentColor", - strokeWidth: 1, - strokeLinecap: "square", - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M14.1036 6.65539C13.8 5.27698 13.0387 4.04193 11.9437 3.15131C10.8487 2.26069 9.48447 1.76694 8.0731 1.75043C6.66173 1.73392 5.28633 2.19563 4.17079 3.0604C3.05526 3.92516 2.26529 5.14206 1.92947 6.513", - stroke: "currentColor", - strokeWidth: 1, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M1.89635 9.34461C2.20001 10.723 2.96131 11.9581 4.05631 12.8487C5.15131 13.7393 6.51553 14.2331 7.9269 14.2496C9.33827 14.2661 10.7137 13.8044 11.8292 12.9396C12.9447 12.0748 13.7347 10.8579 14.0705 9.487", - stroke: "currentColor", - strokeWidth: 1, - }) - ); - const SvgRootType = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 11.8, - height: 11.8, - rx: 5.9, - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M4.25 7.5C4.25 6 5.75 5 6.5 6.5C7.25 8 8.75 7 8.75 5.5", - stroke: "currentColor", - strokeWidth: 1.2, - }) - ); - const SvgSettings = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 21 20", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M9.29186 1.92702C9.06924 1.82745 8.87014 1.68202 8.70757 1.50024L7.86631 0.574931C7.62496 0.309957 7.30773 0.12592 6.95791 0.0479385C6.60809 -0.0300431 6.24274 0.00182978 5.91171 0.139208C5.58068 0.276585 5.3001 0.512774 5.10828 0.815537C4.91645 1.1183 4.82272 1.47288 4.83989 1.83089L4.90388 3.08019C4.91612 3.32348 4.87721 3.56662 4.78968 3.79394C4.70215 4.02126 4.56794 4.2277 4.39571 4.39994C4.22347 4.57219 4.01704 4.7064 3.78974 4.79394C3.56243 4.88147 3.3193 4.92038 3.07603 4.90814L1.8308 4.84414C1.47162 4.82563 1.11553 4.91881 0.811445 5.11086C0.507359 5.30292 0.270203 5.58443 0.132561 5.91671C-0.00508149 6.249 -0.0364554 6.61576 0.0427496 6.9666C0.121955 7.31744 0.307852 7.63514 0.5749 7.87606L1.50016 8.71204C1.68193 8.87461 1.82735 9.07373 1.92692 9.29636C2.02648 9.51898 2.07794 9.76012 2.07794 10.004C2.07794 10.2479 2.02648 10.489 1.92692 10.7116C1.82735 10.9343 1.68193 11.1334 1.50016 11.296L0.5749 12.1319C0.309856 12.3729 0.125575 12.6898 0.0471809 13.0393C-0.0312128 13.3888 9.64098e-05 13.754 0.13684 14.0851C0.273583 14.4162 0.509106 14.6971 0.811296 14.8894C1.11349 15.0817 1.46764 15.1762 1.82546 15.1599L3.0707 15.0959C3.31397 15.0836 3.5571 15.1225 3.7844 15.2101C4.01171 15.2976 4.21814 15.4318 4.39037 15.6041C4.56261 15.7763 4.69682 15.9827 4.78435 16.2101C4.87188 16.4374 4.91078 16.6805 4.89855 16.9238L4.83455 18.1691C4.81605 18.5283 4.90921 18.8844 5.10126 19.1885C5.2933 19.4926 5.5748 19.7298 5.90707 19.8674C6.23934 20.0051 6.60608 20.0365 6.9569 19.9572C7.30772 19.878 7.6254 19.6921 7.86631 19.4251L8.7129 18.4998C8.87547 18.318 9.07458 18.1725 9.29719 18.073C9.51981 17.9734 9.76093 17.9219 10.0048 17.9219C10.2487 17.9219 10.4898 17.9734 10.7124 18.073C10.935 18.1725 11.1341 18.318 11.2967 18.4998L12.1326 19.4251C12.3735 19.6921 12.6912 19.878 13.042 19.9572C13.3929 20.0365 13.7596 20.0051 14.0919 19.8674C14.4241 19.7298 14.7056 19.4926 14.8977 19.1885C15.0897 18.8844 15.1829 18.5283 15.1644 18.1691L15.1004 16.9238C15.0882 16.6805 15.1271 16.4374 15.2146 16.2101C15.3021 15.9827 15.4363 15.7763 15.6086 15.6041C15.7808 15.4318 15.9872 15.2976 16.2145 15.2101C16.4418 15.1225 16.685 15.0836 16.9282 15.0959L18.1735 15.1599C18.5326 15.1784 18.8887 15.0852 19.1928 14.8931C19.4969 14.7011 19.7341 14.4196 19.8717 14.0873C20.0093 13.755 20.0407 13.3882 19.9615 13.0374C19.8823 12.6866 19.6964 12.3689 19.4294 12.1279L18.5041 11.292C18.3223 11.1294 18.1769 10.9303 18.0774 10.7076C17.9778 10.485 17.9263 10.2439 17.9263 10C17.9263 9.75612 17.9778 9.51499 18.0774 9.29236C18.1769 9.06973 18.3223 8.87062 18.5041 8.70804L19.4294 7.87206C19.6964 7.63114 19.8823 7.31344 19.9615 6.9626C20.0407 6.61176 20.0093 6.245 19.8717 5.91271C19.7341 5.58043 19.4969 5.29892 19.1928 5.10686C18.8887 4.91481 18.5326 4.82163 18.1735 4.84014L16.9282 4.90414C16.685 4.91638 16.4418 4.87747 16.2145 4.78994C15.9872 4.7024 15.7808 4.56818 15.6086 4.39594C15.4363 4.2237 15.3021 4.01726 15.2146 3.78994C15.1271 3.56262 15.0882 3.31948 15.1004 3.07619L15.1644 1.83089C15.1829 1.4717 15.0897 1.11559 14.8977 0.811487C14.7056 0.507385 14.4241 0.270217 14.0919 0.132568C13.7596 -0.00508182 13.3929 -0.0364573 13.042 0.0427519C12.6912 0.121961 12.3735 0.307869 12.1326 0.574931L11.2914 1.50024C11.1288 1.68202 10.9297 1.82745 10.7071 1.92702C10.4845 2.02659 10.2433 2.07805 9.99947 2.07805C9.7556 2.07805 9.51448 2.02659 9.29186 1.92702ZM14.3745 10C14.3745 12.4162 12.4159 14.375 9.99977 14.375C7.58365 14.375 5.625 12.4162 5.625 10C5.625 7.58375 7.58365 5.625 9.99977 5.625C12.4159 5.625 14.3745 7.58375 14.3745 10Z", - fill: "currentColor", - }) - ); - const SvgStarFilled = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", - fill: "currentColor", - stroke: "currentColor", - }) - ); - const SvgStar = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", - stroke: "currentColor", - strokeWidth: 1.5, - }) - ); - const SvgStop = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 16 16", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - width: 16, - height: 16, - rx: 2, - fill: "currentColor", - }) - ); - const SvgTrash = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - width: "1em", - height: "5em", - xmlns: "http://www.w3.org/2000/svg", - fillRule: "evenodd", - "aria-hidden": "true", - viewBox: "0 0 23 23", - style: { - height: "1.5em", - }, - clipRule: "evenodd", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("path", { - d: "M19 24h-14c-1.104 0-2-.896-2-2v-17h-1v-2h6v-1.5c0-.827.673-1.5 1.5-1.5h5c.825 0 1.5.671 1.5 1.5v1.5h6v2h-1v17c0 1.104-.896 2-2 2zm0-19h-14v16.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-16.5zm-7 7.586l3.293-3.293 1.414 1.414-3.293 3.293 3.293 3.293-1.414 1.414-3.293-3.293-3.293 3.293-1.414-1.414 3.293-3.293-3.293-3.293 1.414-1.414 3.293 3.293zm2-10.586h-4v1h4v-1z", - fill: "currentColor", - strokeWidth: 0.25, - stroke: "currentColor", - }) - ); - const SvgType = ({ title, titleId, ...props }) => - /* @__PURE__ */ React__namespace.createElement( - "svg", - { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props, - }, - title - ? /* @__PURE__ */ React__namespace.createElement( - "title", - { - id: titleId, - }, - title - ) - : null, - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 11.8, - height: 11.8, - rx: 5.9, - stroke: "currentColor", - strokeWidth: 1.2, - }), - /* @__PURE__ */ React__namespace.createElement("rect", { - x: 5.5, - y: 5.5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor", - }) - ); - const ArgumentIcon = generateIcon(SvgArgument); - const ChevronDownIcon = generateIcon(SvgChevronDown); - const ChevronLeftIcon = generateIcon(SvgChevronLeft); - const ChevronUpIcon = generateIcon(SvgChevronUp); - const CloseIcon = generateIcon(SvgClose); - const CopyIcon = generateIcon(SvgCopy); - const DeprecatedArgumentIcon = generateIcon(SvgDeprecatedArgument); - const DeprecatedEnumValueIcon = generateIcon(SvgDeprecatedEnumValue); - const DeprecatedFieldIcon = generateIcon(SvgDeprecatedField); - const DirectiveIcon = generateIcon(SvgDirective); - const DocsFilledIcon = generateIcon(SvgDocsFilled); - const DocsIcon = generateIcon(SvgDocs); - const EnumValueIcon = generateIcon(SvgEnumValue); - const FieldIcon = generateIcon(SvgField); - const HistoryIcon = generateIcon(SvgHistory); - const ImplementsIcon = generateIcon(SvgImplements); - const KeyboardShortcutIcon = generateIcon(SvgKeyboardShortcut); - const MagnifyingGlassIcon = generateIcon(SvgMagnifyingGlass); - const MergeIcon = generateIcon(SvgMerge); - const PenIcon = generateIcon(SvgPen); - const PlayIcon = generateIcon(SvgPlay); - const PlusIcon = generateIcon(SvgPlus); - const PrettifyIcon = generateIcon(SvgPrettify); - const ReloadIcon = generateIcon(SvgReload); - const RootTypeIcon = generateIcon(SvgRootType); - const SettingsIcon = generateIcon(SvgSettings); - const StarFilledIcon = generateIcon(SvgStarFilled); - const StarIcon = generateIcon(SvgStar); - const StopIcon = generateIcon(SvgStop); - const TrashIcon = generateIcon(SvgTrash); - const TypeIcon = generateIcon(SvgType); - function generateIcon(RawComponent) { - const title = - RawComponent.name - .replace("Svg", "") - .replaceAll(/([A-Z])/g, " $1") - .trimStart() - .toLowerCase() + " icon"; - function IconComponent(props) { - return /* @__PURE__ */ jsxRuntime.jsx(RawComponent, { - title, - ...props, - }); + } + }; + } + /** + * @internal + */ + + function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map(arg => arg.name); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + directiveArgs[def.name.value] = argsNodes.map(arg => arg.name.value); + } + } + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (!knownArgs.includes(argName)) { + const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgs); + context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on directive "@${directiveName}".` + (0, _didYouMean.didYouMean)(suggestions), { + nodes: argNode + })); + } } - IconComponent.displayName = RawComponent.name; - return IconComponent; } - const UnStyledButton = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-un-styled", props.className), - }) - ); - UnStyledButton.displayName = "UnStyledButton"; - const Button$1 = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx( - "graphiql-button", - { - success: "graphiql-button-success", - error: "graphiql-button-error", - }[props.state], - props.className - ), - }) - ); - Button$1.displayName = "Button"; - const ButtonGroup = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx("graphiql-button-group", props.className), - }) - ); - ButtonGroup.displayName = "ButtonGroup"; - const createComponentGroup = (root, children) => - Object.entries(children).reduce((r, [key, value]) => { - r[key] = value; - return r; - }, root); - const DialogClose = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Close, { - asChild: true, - children: /* @__PURE__ */ jsxRuntime.jsxs(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-dialog-close", props.className), - children: [ - /* @__PURE__ */ jsxRuntime.jsx(reactVisuallyHidden.Root, { - children: "Close dialog", - }), - /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}), - ], - }), - }) - ); - DialogClose.displayName = "Dialog.Close"; - function DialogRoot({ children, ...props }) { - return /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Root, { - ...props, - children: /* @__PURE__ */ jsxRuntime.jsxs(D__namespace.Portal, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Overlay, { - className: "graphiql-dialog-overlay", - }), - /* @__PURE__ */ jsxRuntime.jsx(D__namespace.Content, { - className: "graphiql-dialog", - children, - }), - ], - }), - }); + return false; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs": + /*!******************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.KnownDirectivesRule = KnownDirectivesRule; + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _ast = __webpack_require__(/*! ../../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); + var _directiveLocation = __webpack_require__(/*! ../../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + /** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + */ + function KnownDirectivesRule(context) { + const locationsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(name => name.value); + } + } + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + if (!locations) { + context.reportError(new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { + nodes: node + })); + return; + } + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (candidateLocation && !locations.includes(candidateLocation)) { + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${name}" may not be used on ${candidateLocation}.`, { + nodes: node + })); + } + } + }; + } + function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + 'kind' in appliedTo || (0, _invariant.invariant)(false); + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + case _kinds.Kind.INPUT_VALUE_DEFINITION: + { + const parentNode = ancestors[ancestors.length - 3]; + 'kind' in parentNode || (0, _invariant.invariant)(false); + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + // Not reachable, all possible types have been considered. + + /* c8 ignore next */ + + default: + false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind)); + } + } + function getDirectiveLocationForOperation(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return _directiveLocation.DirectiveLocation.QUERY; + case _ast.OperationTypeNode.MUTATION: + return _directiveLocation.DirectiveLocation.MUTATION; + case _ast.OperationTypeNode.SUBSCRIPTION: + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs": + /*!*********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs ***! + \*********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.KnownFragmentNamesRule = KnownFragmentNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined + */ + function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError(new _GraphQLError.GraphQLError(`Unknown fragment "${fragmentName}".`, { + nodes: node.name + })); + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.KnownTypeNamesRule = KnownTypeNamesRule; + var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); + var _introspection = __webpack_require__(/*! ../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + var _scalars = __webpack_require__(/*! ../../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + /** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + */ + function KnownTypeNamesRule(context) { + const schema = context.getSchema(); + const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = true; + } + } + const typeNames = [...Object.keys(existingTypesMap), ...Object.keys(definedTypes)]; + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + const definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + if (isSDL && standardTypeNames.includes(typeName)) { + return; + } + const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames); + context.reportError(new _GraphQLError.GraphQLError(`Unknown type "${typeName}".` + (0, _didYouMean.didYouMean)(suggestedTypes), { + nodes: node + })); + } + } + }; + } + const standardTypeNames = [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes].map(type => type.name); + function isSDLNode(value) { + return 'kind' in value && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs ***! + \*************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + /** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation + */ + function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter(definition => definition.kind === _kinds.Kind.OPERATION_DEFINITION).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new _GraphQLError.GraphQLError('This anonymous operation must be the only defined operation.', { + nodes: node + })); + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ + function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + const oldSchema = context.getSchema(); + const alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new _GraphQLError.GraphQLError('Cannot define a new schema within a schema extension.', { + nodes: node + })); + return; + } + if (schemaDefinitionsCount > 0) { + context.reportError(new _GraphQLError.GraphQLError('Must provide only one schema definition.', { + nodes: node + })); + } + ++schemaDefinitionsCount; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs": + /*!*******************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs ***! + \*******************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.NoFragmentCyclesRule = NoFragmentCyclesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles + */ + function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + const spreadPath = []; // Position in the spread path + + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + if (spreadNodes.length === 0) { + return; + } + spreadPathIndexByName[fragmentName] = spreadPath.length; + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath.slice(0, -1).map(s => '"' + s.name.value + '"').join(', '); + context.reportError(new _GraphQLError.GraphQLError(`Cannot spread fragment "${spreadName}" within itself` + (viaPath !== '' ? ` via ${viaPath}.` : '.'), { + nodes: cyclePath + })); + } + spreadPath.pop(); + } + spreadPathIndexByName[fragmentName] = undefined; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined + */ + function NoUndefinedVariablesRule(context) { + let variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { + node + } of usages) { + const varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` : `Variable "$${varName}" is not defined.`, { + nodes: [node, operation] + })); + } + } + } + }, + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs": + /*!********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs ***! + \********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used + */ + function NoUnusedFragmentsRule(context) { + const operationDefs = []; + const fragmentDefs = []; + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments(operation)) { + fragmentNameUsed[fragment.name.value] = true; + } + } + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" is never used.`, { + nodes: fragmentDef + })); + } + } + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs": + /*!********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs ***! + \********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.NoUnusedVariablesRule = NoUnusedVariablesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + * + * See https://spec.graphql.org/draft/#sec-All-Variables-Used + */ + function NoUnusedVariablesRule(context) { + let variableDefs = []; + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + for (const { + node + } of usages) { + variableNameUsed[node.name.value] = true; + } + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` : `Variable "$${variableName}" is never used.`, { + nodes: variableDef + })); + } + } + } + }, + VariableDefinition(def) { + variableDefs.push(def); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs": + /*!*******************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs ***! + \*******************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _sortValueNode = __webpack_require__(/*! ../../utilities/sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); + var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(([responseName, subReason]) => `subfields "${responseName}" conflict because ` + reasonMessage(subReason)).join(' and '); + } + return reason; + } + /** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + */ + + function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + const cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError(new _GraphQLError.GraphQLError(`Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, { + nodes: fields1.concat(fields2) + })); + } + } + }; + } + + /** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ + // Find all conflicts found "within" a selection set, including those found + // via spreading in fragments. Called when visiting each SelectionSet in the + // GraphQL Document. + function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + const conflicts = []; + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet); // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + return conflicts; + } // Collect all conflicts found between a set of fields and a fragment reference + // including via spreading in any nested fragments. + + function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + const [fieldMap2, referencedFragmentNames] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment); // Do not compare a fragment's fieldMap to itself. + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (const referencedFragmentName of referencedFragmentNames) { + // Memoize so two fragments are not compared for conflicts more than once. + if (comparedFragmentPairs.has(referencedFragmentName, fragmentName, areMutuallyExclusive)) { + continue; + } + comparedFragmentPairs.add(referencedFragmentName, fragmentName, areMutuallyExclusive); + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, referencedFragmentName); + } + } // Collect all conflicts found between two fragments, including via spreading in + // any nested fragments. + + function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; + } + const [fieldMap1, referencedFragmentNames1] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1); + const [fieldMap2, referencedFragmentNames2] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2); // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, referencedFragmentName2); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, referencedFragmentName1, fragmentName2); + } + } // Find all conflicts found between two selection sets, including those found + // via spreading in fragments. Called when determining if conflicts exist + // between the sub-fields of two overlapping fields. + + function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + const conflicts = []; + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2); // (H) First, collect all conflicts between these two collections of field. + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentName2); + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentName1); + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + for (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2); + } + } + return conflicts; + } // Collect all Conflicts "within" one collection of fields. + + function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of Object.entries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, + // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } + } // Collect all Conflicts between two collections of fields. This is similar to, + // but different from the `collectConflictsWithin` function above. This check + // assumes that `collectConflictsWithin` has already been called on each + // provided collection of fields. This is true because this validator traverses + // each individual selection set. + + function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const [responseName, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } + } // Determines if there is a conflict between two particular fields, including + // comparing their sub-fields. + + function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + const areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [[responseName, `"${name1}" and "${name2}" are different fields`], [node1], [node2]]; + } // Two field calls must have the same arguments. + + if (!sameArguments(node1, node2)) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } // The return type for each field. + + const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, `they return conflicting types "${(0, _inspect.inspect)(type1)}" and "${(0, _inspect.inspect)(type2)}"`], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } + } + function sameArguments(node1, node2) { + const args1 = node1.arguments; + const args2 = node2.arguments; + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; + } + if (args2 === undefined || args2.length === 0) { + return false; + } + /* c8 ignore next */ + + if (args1.length !== args2.length) { + /* c8 ignore next */ + return false; + /* c8 ignore next */ + } + const values2 = new Map(args2.map(({ + name, + value + }) => [name.value, value])); + return args1.every(arg1 => { + const value1 = arg1.value; + const value2 = values2.get(arg1.name.value); + if (value2 === undefined) { + return false; + } + return stringifyValue(value1) === stringifyValue(value2); + }); + } + function stringifyValue(value) { + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); + } // Two types conflict if both types could not apply to a value simultaneously. + // Composite types are ignored as their individual field types will be compared + // later recursively. However List and Non-Null types must match. + + function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if ((0, _definition.isListType)(type2)) { + return true; + } + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { + return type1 !== type2; + } + return false; + } // Given a selection set, return the collection of fields (a mapping of response + // name to field nodes and definitions) as well as a list of fragment names + // referenced via fragment spreads. + + function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + const cached = cachedFieldsAndFragmentNames.get(selectionSet); + if (cached) { + return cached; + } + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + const result = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, result); + return result; + } // Given a reference to a fragment, return the represented collection of fields + // as well as a list of nested fragment names referenced via fragment spreads. + + function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + if (cached) { + return cached; + } + const fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); + } + function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: + { + const fieldName = selection.name.value; + let fieldDef; + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias ? selection.alias.value : fieldName; + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case _kinds.Kind.INLINE_FRAGMENT: + { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + break; + } + } + } + } // Given a series of Conflicts which occurred between two sub-fields, generate + // a single Conflict. + + function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(([reason]) => reason)], [node1, ...conflicts.map(([, fields1]) => fields1).flat()], [node2, ...conflicts.map(([,, fields2]) => fields2).flat()]]; + } + } + /** + * A way to keep track of pairs of things when the ordering of the pair does not matter. + */ + + class PairSet { + constructor() { + this._data = new Map(); + } + has(a, b, areMutuallyExclusive) { + var _this$_data$get; + const [key1, key2] = a < b ? [a, b] : [b, a]; + const result = (_this$_data$get = this._data.get(key1)) === null || _this$_data$get === void 0 ? void 0 : _this$_data$get.get(key2); + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, hence if + // we want to know if this PairSet "has" these two with no exclusivity, + // we have to ensure it was added as such. + + return areMutuallyExclusive ? true : areMutuallyExclusive === result; + } + add(a, b, areMutuallyExclusive) { + const [key1, key2] = a < b ? [a, b] : [b, a]; + const map = this._data.get(key1); + if (map === undefined) { + this._data.set(key1, new Map([[key2, areMutuallyExclusive]])); + } else { + map.set(key2, areMutuallyExclusive); + } + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs": + /*!**************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs ***! + \**************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); + var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + /** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ + function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { + nodes: node + })); } - const Dialog = createComponentGroup(DialogRoot, { - Close: DialogClose, - Title: D__namespace.Title, - Trigger: D__namespace.Trigger, - Description: D__namespace.Description, - }); - const Button = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx(reactDropdownMenu.Trigger, { - asChild: true, - children: /* @__PURE__ */ jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-un-styled", props.className), - }), - }) - ); - Button.displayName = "DropdownMenuButton"; - function Content({ - children, - align = "start", - sideOffset = 5, - className, - ...props - }) { - return /* @__PURE__ */ jsxRuntime.jsx(reactDropdownMenu.Portal, { - children: /* @__PURE__ */ jsxRuntime.jsx( - reactDropdownMenu.Content, - { - align, - sideOffset, - className: clsx.clsx("graphiql-dropdown-content", className), - ...props, - children, - } - ), - }); + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { + nodes: node + })); } - const Item = ({ className, children, ...props }) => - /* @__PURE__ */ jsxRuntime.jsx(reactDropdownMenu.Item, { - className: clsx.clsx("graphiql-dropdown-item", className), - ...props, - children, - }); - const DropdownMenu = createComponentGroup(reactDropdownMenu.Root, { - Button, - Item, - Content, - }); - const markdown = new MarkdownIt({ - breaks: true, - linkify: true, - }); - const MarkdownContent = React.forwardRef( - ({ children, onlyShowFirstChild, type, ...props }, ref) => - /* @__PURE__ */ jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx( - `graphiql-markdown-${type}`, - onlyShowFirstChild && "graphiql-markdown-preview", - props.className - ), - dangerouslySetInnerHTML: { - __html: markdown.render(children), - }, - }) - ); - MarkdownContent.displayName = "MarkdownContent"; - const Spinner = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx("graphiql-spinner", props.className), - }) - ); - Spinner.displayName = "Spinner"; - function TooltipRoot({ - children, - align = "start", - side = "bottom", - sideOffset = 5, - label, - }) { - return /* @__PURE__ */ jsxRuntime.jsxs(T__namespace.Root, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx(T__namespace.Trigger, { - asChild: true, - children, - }), - /* @__PURE__ */ jsxRuntime.jsx(T__namespace.Portal, { - children: /* @__PURE__ */ jsxRuntime.jsx(T__namespace.Content, { - className: "graphiql-tooltip", - align, - side, - sideOffset, - children: label, - }), - }), - ], - }); + } + }; + } + function getFragmentType(context, name) { + const frag = context.getFragment(name); + if (frag) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); + if ((0, _definition.isCompositeType)(type)) { + return type; + } + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs ***! + \*************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; + var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ + function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = def; + } + } + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension + }; + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + let expectedKind; + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError(new _GraphQLError.GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, { + nodes: defNode ? [defNode, node] : node + })); } - const Tooltip = createComponentGroup(TooltipRoot, { - Provider: T__namespace.Provider, - }); - const TabRoot = React.forwardRef( - ({ isActive, value, children, className, ...props }, ref) => - /* @__PURE__ */ jsxRuntime.jsx(framerMotion.Reorder.Item, { - ...props, - ref, - value, - "aria-selected": isActive ? "true" : void 0, - role: "tab", - className: clsx.clsx( - "graphiql-tab", - isActive && "graphiql-tab-active", - className - ), - children, - }) - ); - TabRoot.displayName = "Tab"; - const TabButton = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-tab-button", props.className), - children: props.children, - }) - ); - TabButton.displayName = "Tab.Button"; - const TabClose = React.forwardRef((props, ref) => - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label: "Close Tab", - children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - "aria-label": "Close Tab", - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-tab-close", props.className), - children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}), - }), - }) - ); - TabClose.displayName = "Tab.Close"; - const Tab = createComponentGroup(TabRoot, { - Button: TabButton, - Close: TabClose, + } else { + const allTypeNames = Object.keys({ + ...definedTypes, + ...(schema === null || schema === void 0 ? void 0 : schema.getTypeMap()) }); - const Tabs = React.forwardRef( - ({ values, onReorder, children, className, ...props }, ref) => - /* @__PURE__ */ jsxRuntime.jsx(framerMotion.Reorder.Group, { - ...props, - ref, - values, - onReorder, - axis: "x", - role: "tablist", - className: clsx.clsx("graphiql-tabs", className), - children, - }) - ); - Tabs.displayName = "Tabs"; - const HistoryContext = createNullableContext("HistoryContext"); - function HistoryContextProvider(props) { - var _a; - const storage = useStorageContext(); - const historyStore = React.useRef( - new toolkit.HistoryStore( - // Fall back to a noop storage when the StorageContext is empty - storage || new toolkit.StorageAPI(null), - props.maxHistoryLength || DEFAULT_HISTORY_LENGTH - ) - ); - const [items, setItems] = React.useState( - ((_a = historyStore.current) == null ? void 0 : _a.queries) || [] - ); - const addToHistory = React.useCallback((operation) => { - var _a2; - (_a2 = historyStore.current) == null - ? void 0 - : _a2.updateHistory(operation); - setItems(historyStore.current.queries); - }, []); - const editLabel = React.useCallback((operation, index) => { - historyStore.current.editLabel(operation, index); - setItems(historyStore.current.queries); - }, []); - const toggleFavorite = React.useCallback((operation) => { - historyStore.current.toggleFavorite(operation); - setItems(historyStore.current.queries); - }, []); - const setActive = React.useCallback((item) => { - return item; - }, []); - const deleteFromHistory = React.useCallback( - (item, clearFavorites = false) => { - historyStore.current.deleteHistory(item, clearFavorites); - setItems(historyStore.current.queries); - }, - [] - ); - const value = React.useMemo( - () => ({ - addToHistory, - editLabel, - items, - toggleFavorite, - setActive, - deleteFromHistory, - }), - [ - addToHistory, - editLabel, - items, - toggleFavorite, - setActive, - deleteFromHistory, - ] - ); - return /* @__PURE__ */ jsxRuntime.jsx(HistoryContext.Provider, { - value, - children: props.children, - }); - } - const useHistoryContext = createContextHook(HistoryContext); - const DEFAULT_HISTORY_LENGTH = 20; - function History() { - const { items: all, deleteFromHistory } = useHistoryContext({ - nonNull: true, - }); - let items = all - .slice() - .map((item, i) => ({ - ...item, - index: i, - })) - .reverse(); - const favorites = items.filter((item) => item.favorite); - if (favorites.length) { - items = items.filter((item) => !item.favorite); - } - const [clearStatus, setClearStatus] = React.useState(null); - React.useEffect(() => { - if (clearStatus) { - setTimeout(() => { - setClearStatus(null); - }, 2e3); - } - }, [clearStatus]); - const handleClearStatus = React.useCallback(() => { - try { - for (const item of items) { - deleteFromHistory(item, true); - } - setClearStatus("success"); - } catch { - setClearStatus("error"); - } - }, [deleteFromHistory, items]); - return /* @__PURE__ */ jsxRuntime.jsxs("section", { - "aria-label": "History", - className: "graphiql-history", - children: [ - /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-history-header", - children: [ - "History", - (clearStatus || items.length > 0) && - /* @__PURE__ */ jsxRuntime.jsx(Button$1, { - type: "button", - state: clearStatus || void 0, - disabled: !items.length, - onClick: handleClearStatus, - children: - { - success: "Cleared", - error: "Failed to Clear", - }[clearStatus] || "Clear", - }), - ], - }), - Boolean(favorites.length) && - /* @__PURE__ */ jsxRuntime.jsx("ul", { - className: "graphiql-history-items", - children: favorites.map((item) => - /* @__PURE__ */ jsxRuntime.jsx( - HistoryItem, - { - item, - }, - item.index - ) - ), - }), - Boolean(favorites.length) && - Boolean(items.length) && - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-history-item-spacer", - }), - Boolean(items.length) && - /* @__PURE__ */ jsxRuntime.jsx("ul", { - className: "graphiql-history-items", - children: items.map((item) => - /* @__PURE__ */ jsxRuntime.jsx( - HistoryItem, - { - item, - }, - item.index - ) - ), - }), - ], - }); - } - function HistoryItem(props) { - const { editLabel, toggleFavorite, deleteFromHistory, setActive } = - useHistoryContext({ - nonNull: true, - caller: HistoryItem, - }); - const { headerEditor, queryEditor, variableEditor } = - useEditorContext({ - nonNull: true, - caller: HistoryItem, - }); - const inputRef = React.useRef(null); - const buttonRef = React.useRef(null); - const [isEditable, setIsEditable] = React.useState(false); - React.useEffect(() => { - var _a; - if (isEditable) { - (_a = inputRef.current) == null ? void 0 : _a.focus(); - } - }, [isEditable]); - const displayName = - props.item.label || - props.item.operationName || - formatQuery(props.item.query); - const handleSave = React.useCallback(() => { - var _a; - setIsEditable(false); - const { index, ...item } = props.item; - editLabel( - { - ...item, - label: (_a = inputRef.current) == null ? void 0 : _a.value, - }, - index - ); - }, [editLabel, props.item]); - const handleClose = React.useCallback(() => { - setIsEditable(false); - }, []); - const handleEditLabel = React.useCallback((e) => { - e.stopPropagation(); - setIsEditable(true); - }, []); - const handleHistoryItemClick = React.useCallback(() => { - const { query, variables, headers } = props.item; - queryEditor == null - ? void 0 - : queryEditor.setValue( - query !== null && query !== void 0 ? query : "" - ); - variableEditor == null - ? void 0 - : variableEditor.setValue( - variables !== null && variables !== void 0 ? variables : "" - ); - headerEditor == null - ? void 0 - : headerEditor.setValue( - headers !== null && headers !== void 0 ? headers : "" - ); - setActive(props.item); - }, [ - headerEditor, - props.item, - queryEditor, - setActive, - variableEditor, - ]); - const handleDeleteItemFromHistory = React.useCallback( - (e) => { - e.stopPropagation(); - deleteFromHistory(props.item); - }, - [props.item, deleteFromHistory] - ); - const handleToggleFavorite = React.useCallback( - (e) => { - e.stopPropagation(); - toggleFavorite(props.item); - }, - [props.item, toggleFavorite] - ); - return /* @__PURE__ */ jsxRuntime.jsx("li", { - className: clsx.clsx( - "graphiql-history-item", - isEditable && "editable" - ), - children: isEditable - ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("input", { - type: "text", - defaultValue: props.item.label, - ref: inputRef, - onKeyDown: (e) => { - if (e.key === "Esc") { - setIsEditable(false); - } else if (e.key === "Enter") { - setIsEditable(false); - editLabel({ - ...props.item, - label: e.currentTarget.value, - }); - } - }, - placeholder: "Type a label", - }), - /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - type: "button", - ref: buttonRef, - onClick: handleSave, - children: "Save", - }), - /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - type: "button", - ref: buttonRef, - onClick: handleClose, - children: /* @__PURE__ */ jsxRuntime.jsx(CloseIcon, {}), - }), - ], - }) - : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label: "Set active", - children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-label", - onClick: handleHistoryItemClick, - "aria-label": "Set active", - children: displayName, - }), - }), - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label: "Edit label", - children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleEditLabel, - "aria-label": "Edit label", - children: /* @__PURE__ */ jsxRuntime.jsx(PenIcon, { - "aria-hidden": "true", - }), - }), - }), - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label: props.item.favorite - ? "Remove favorite" - : "Add favorite", - children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleToggleFavorite, - "aria-label": props.item.favorite - ? "Remove favorite" - : "Add favorite", - children: props.item.favorite - ? /* @__PURE__ */ jsxRuntime.jsx(StarFilledIcon, { - "aria-hidden": "true", - }) - : /* @__PURE__ */ jsxRuntime.jsx(StarIcon, { - "aria-hidden": "true", - }), - }), - }), - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label: "Delete from history", - children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleDeleteItemFromHistory, - "aria-label": "Delete from history", - children: /* @__PURE__ */ jsxRuntime.jsx(TrashIcon, { - "aria-hidden": "true", - }), - }), - }), - ], - }), - }); - } - function formatQuery(query) { - return query == null - ? void 0 - : query - .split("\n") - .map((line) => line.replace(/#(.*)/, "")) - .join(" ") - .replaceAll("{", " { ") - .replaceAll("}", " } ") - .replaceAll(/[\s]{2,}/g, " "); - } - const ExecutionContext = createNullableContext("ExecutionContext"); - function ExecutionContextProvider({ - fetcher, - getDefaultFieldNames, - children, - operationName, - }) { - if (!fetcher) { - throw new TypeError( - "The `ExecutionContextProvider` component requires a `fetcher` function to be passed as prop." - ); + const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, allTypeNames); + context.reportError(new _GraphQLError.GraphQLError(`Cannot extend type "${typeName}" because it is not defined.` + (0, _didYouMean.didYouMean)(suggestedTypes), { + nodes: node.name + })); + } + } + } + const defKindToExtKind = { + [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, + [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, + [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, + [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, + [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION + }; + function typeToExtKind(type) { + if ((0, _definition.isScalarType)(type)) { + return _kinds.Kind.SCALAR_TYPE_EXTENSION; + } + if ((0, _definition.isObjectType)(type)) { + return _kinds.Kind.OBJECT_TYPE_EXTENSION; + } + if ((0, _definition.isInterfaceType)(type)) { + return _kinds.Kind.INTERFACE_TYPE_EXTENSION; + } + if ((0, _definition.isUnionType)(type)) { + return _kinds.Kind.UNION_TYPE_EXTENSION; + } + if ((0, _definition.isEnumType)(type)) { + return _kinds.Kind.ENUM_TYPE_EXTENSION; + } + if ((0, _definition.isInputObjectType)(type)) { + return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + /* c8 ignore next 3 */ + // Not reachable. All possible types have been considered + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } + function extensionKindToTypeName(kind) { + switch (kind) { + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + case _kinds.Kind.UNION_TYPE_EXTENSION: + return 'union'; + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + // Not reachable. All possible types have been considered + + /* c8 ignore next */ + + default: + false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(kind)); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs": + /*!****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs ***! + \****************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.ProvidedRequiredArgumentsOnDirectivesRule = ProvidedRequiredArgumentsOnDirectivesRule; + exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + /** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ + function ProvidedRequiredArgumentsRule(context) { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + var _fieldNode$arguments; + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; } - const { - externalFragments, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - updateActiveTabValues, - } = useEditorContext({ - nonNull: true, - caller: ExecutionContextProvider, - }); - const history = useHistoryContext(); - const autoCompleteLeafs = useAutoCompleteLeafs({ - getDefaultFieldNames, - caller: ExecutionContextProvider, - }); - const [isFetching, setIsFetching] = React.useState(false); - const [subscription, setSubscription] = React.useState(null); - const queryIdRef = React.useRef(0); - const stop = React.useCallback(() => { - subscription == null ? void 0 : subscription.unsubscribe(); - setIsFetching(false); - setSubscription(null); - }, [subscription]); - const run = React.useCallback(async () => { - var _ref; - if (!queryEditor || !responseEditor) { - return; - } - if (subscription) { - stop(); - return; + const providedArgs = new Set( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + (_fieldNode$arguments = fieldNode.arguments) === null || _fieldNode$arguments === void 0 ? void 0 : _fieldNode$arguments.map(arg => arg.name.value)); + for (const argDef of fieldDef.args) { + if (!providedArgs.has(argDef.name) && (0, _definition.isRequiredArgument)(argDef)) { + const argTypeStr = (0, _inspect.inspect)(argDef.type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, { + nodes: fieldNode + })); } - const setResponse = (value2) => { - responseEditor.setValue(value2); - updateActiveTabValues({ - response: value2, - }); - }; - queryIdRef.current += 1; - const queryId = queryIdRef.current; - let query = autoCompleteLeafs() || queryEditor.getValue(); - const variablesString = - variableEditor == null ? void 0 : variableEditor.getValue(); - let variables; - try { - variables = tryParseJsonObject({ - json: variablesString, - errorMessageParse: "Variables are invalid JSON", - errorMessageType: "Variables are not a JSON object.", - }); - } catch (error) { - setResponse(error instanceof Error ? error.message : `${error}`); - return; + } + } + } + }; + } + /** + * @internal + */ + + function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var _schema$getDirectives; + const requiredArgsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = (_schema$getDirectives = schema === null || schema === void 0 ? void 0 : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 ? _schema$getDirectives : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = (0, _keyMap.keyMap)(directive.args.filter(_definition.isRequiredArgument), arg => arg.name); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)(argNodes.filter(isRequiredArgumentNode), arg => arg.name.value); + } + } + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + if (requiredArgs) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; + const argNodeMap = new Set(argNodes.map(arg => arg.name.value)); + for (const [argName, argDef] of Object.entries(requiredArgs)) { + if (!argNodeMap.has(argName)) { + const argType = (0, _definition.isType)(argDef.type) ? (0, _inspect.inspect)(argDef.type) : (0, _printer.print)(argDef.type); + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, { + nodes: directiveNode + })); + } } - const headersString = - headerEditor == null ? void 0 : headerEditor.getValue(); - let headers; - try { - headers = tryParseJsonObject({ - json: headersString, - errorMessageParse: "Headers are invalid JSON", - errorMessageType: "Headers are not a JSON object.", - }); - } catch (error) { - setResponse(error instanceof Error ? error.message : `${error}`); - return; + } + } + } + }; + } + function isRequiredArgumentNode(arg) { + return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs": + /*!**************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.ScalarLeafsRule = ScalarLeafsRule; + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ + function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, { + nodes: selectionSet + })); } - if (externalFragments) { - const fragmentDependencies = queryEditor.documentAST - ? graphqlLanguageService.getFragmentDependenciesForAST( - queryEditor.documentAST, - externalFragments - ) - : []; - if (fragmentDependencies.length > 0) { - query += - "\n" + - fragmentDependencies - .map((node) => graphql.print(node)) - .join("\n"); + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, { + nodes: node + })); + } + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs": + /*!***************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs ***! + \***************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _collectFields = __webpack_require__(/*! ../../execution/collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); + /** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + */ + function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === 'subscription') { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document = context.getDocument(); + const fragments = Object.create(null); + for (const definition of document.definitions) { + if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = definition; } } - setResponse(""); - setIsFetching(true); - const opName = - (_ref = - operationName !== null && operationName !== void 0 - ? operationName - : queryEditor.operationName) !== null && _ref !== void 0 - ? _ref - : void 0; - history == null - ? void 0 - : history.addToHistory({ - query, - variables: variablesString, - headers: headersString, - operationName: opName, - }); - try { - var _headers, _queryEditor$document; - const fullResponse = {}; - const handleResponse = (result) => { - if (queryId !== queryIdRef.current) { - return; - } - let maybeMultipart = Array.isArray(result) ? result : false; - if ( - !maybeMultipart && - typeof result === "object" && - result !== null && - "hasNext" in result - ) { - maybeMultipart = [result]; - } - if (maybeMultipart) { - for (const part of maybeMultipart) { - mergeIncrementalResult(fullResponse, part); - } - setIsFetching(false); - setResponse(toolkit.formatResult(fullResponse)); - } else { - const response = toolkit.formatResult(result); - setIsFetching(false); - setResponse(response); - } - }; - const fetch2 = fetcher( - { - query, - variables, - operationName: opName, - }, - { - headers: - (_headers = headers) !== null && _headers !== void 0 - ? _headers - : void 0, - documentAST: - (_queryEditor$document = queryEditor.documentAST) !== - null && _queryEditor$document !== void 0 - ? _queryEditor$document - : void 0, - } - ); - const value2 = await Promise.resolve(fetch2); - if (toolkit.isObservable(value2)) { - setSubscription( - value2.subscribe({ - next(result) { - handleResponse(result); - }, - error(error) { - setIsFetching(false); - if (error) { - setResponse(toolkit.formatError(error)); - } - setSubscription(null); - }, - complete() { - setIsFetching(false); - setSubscription(null); - }, - }) - ); - } else if (toolkit.isAsyncIterable(value2)) { - setSubscription({ - unsubscribe: () => { - var _a, _b; - return (_b = (_a = value2[Symbol.asyncIterator]()) - .return) == null - ? void 0 - : _b.call(_a); - }, - }); - for await (const result of value2) { - handleResponse(result); - } - setIsFetching(false); - setSubscription(null); - } else { - handleResponse(value2); + const fields = (0, _collectFields.collectFields)(schema, fragments, variableValues, subscriptionType, node.selectionSet); + if (fields.size > 1) { + const fieldSelectionLists = [...fields.values()]; + const extraFieldSelectionLists = fieldSelectionLists.slice(1); + const extraFieldSelections = extraFieldSelectionLists.flat(); + context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must select only one top level field.` : 'Anonymous Subscription must select only one top level field.', { + nodes: extraFieldSelections + })); + } + for (const fieldNodes of fields.values()) { + const field = fieldNodes[0]; + const fieldName = field.name.value; + if (fieldName.startsWith('__')) { + context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must not select an introspection top level field.` : 'Anonymous Subscription must not select an introspection top level field.', { + nodes: fieldNodes + })); } - } catch (error) { - setIsFetching(false); - setResponse(toolkit.formatError(error)); - setSubscription(null); } - }, [ - autoCompleteLeafs, - externalFragments, - fetcher, - headerEditor, - history, - operationName, - queryEditor, - responseEditor, - stop, - subscription, - updateActiveTabValues, - variableEditor, - ]); - const isSubscribed = Boolean(subscription); - const value = React.useMemo( - () => ({ - isFetching, - isSubscribed, - operationName: - operationName !== null && operationName !== void 0 - ? operationName - : null, - run, - stop, - }), - [isFetching, isSubscribed, operationName, run, stop] - ); - return /* @__PURE__ */ jsxRuntime.jsx(ExecutionContext.Provider, { - value, - children, - }); + } + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs": + /*!********************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs ***! + \********************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; + var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique argument definition names + * + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. + */ + function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; + return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); + }, + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField + }; + function checkArgUniquenessPerField(typeNode) { + var _typeNode$fields; + const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = (_typeNode$fields = typeNode.fields) !== null && _typeNode$fields !== void 0 ? _typeNode$fields : []; + for (const fieldDef of fieldNodes) { + var _fieldDef$arguments; + const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = (_fieldDef$arguments = fieldDef.arguments) !== null && _fieldDef$arguments !== void 0 ? _fieldDef$arguments : []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + } + return false; + } + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError(new _GraphQLError.GraphQLError(`Argument "${parentName}(${argName}:)" can only be defined once.`, { + nodes: argNodes.map(node => node.name) + })); + } + } + return false; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; + var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + */ + function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness + }; + function checkArgUniqueness(parentNode) { + var _parentNode$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = (_parentNode$arguments = parentNode.arguments) !== null && _parentNode$arguments !== void 0 ? _parentNode$arguments : []; + const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one argument named "${argName}".`, { + nodes: argNodes.map(node => node.name) + })); + } + } + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ + function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) { + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, { + nodes: node.name + })); + return; + } + if (knownDirectiveNames[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one directive named "@${directiveName}".`, { + nodes: [knownDirectiveNames[directiveName], node.name] + })); + } else { + knownDirectiveNames[directiveName] = node.name; + } + return false; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs": + /*!******************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs ***! + \******************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); + var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); + /** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location + */ + function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (!('directives' in node) || !node.directives) { + return; } - const useExecutionContext = createContextHook(ExecutionContext); - function tryParseJsonObject({ - json, - errorMessageParse, - errorMessageType, - }) { - let parsed; - try { - parsed = json && json.trim() !== "" ? JSON.parse(json) : void 0; - } catch (error) { - throw new Error( - `${errorMessageParse}: ${ - error instanceof Error ? error.message : error - }.` - ); - } - const isObject = - typeof parsed === "object" && - parsed !== null && - !Array.isArray(parsed); - if (parsed !== void 0 && !isObject) { - throw new Error(errorMessageType); - } - return parsed; - } - function mergeIncrementalResult(executionResult, incrementalResult) { - var _incrementalResult$pa; - const path = [ - "data", - ...((_incrementalResult$pa = incrementalResult.path) !== null && - _incrementalResult$pa !== void 0 - ? _incrementalResult$pa - : []), - ]; - if (incrementalResult.items) { - for (const item of incrementalResult.items) { - setValue(executionResult, path.join("."), item); - path[path.length - 1]++; - } - } - if (incrementalResult.data) { - setValue(executionResult, path.join("."), incrementalResult.data, { - merge: true, - }); - } - if (incrementalResult.errors) { - executionResult.errors || (executionResult.errors = []); - executionResult.errors.push(...incrementalResult.errors); - } - if (incrementalResult.extensions) { - setValue( - executionResult, - "extensions", - incrementalResult.extensions, - { - merge: true, - } - ); + let seenDirectives; + if (node.kind === _kinds.Kind.SCHEMA_DEFINITION || node.kind === _kinds.Kind.SCHEMA_EXTENSION) { + seenDirectives = schemaDirectives; + } else if ((0, _predicates.isTypeDefinitionNode)(node) || (0, _predicates.isTypeExtensionNode)(node)) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); } - if (incrementalResult.incremental) { - for (const incrementalSubResult of incrementalResult.incremental) { - mergeIncrementalResult(executionResult, incrementalSubResult); + } else { + seenDirectives = Object.create(null); + } + for (const directive of node.directives) { + const directiveName = directive.name.value; + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError(`The directive "@${directiveName}" can only be used once at this location.`, { + nodes: [seenDirectives[directiveName], directive] + })); + } else { + seenDirectives[directiveName] = directive; } } } - const DEFAULT_EDITOR_THEME = "graphiql"; - const DEFAULT_KEY_MAP = "sublime"; - let isMacOs = false; - if (typeof window === "object") { - isMacOs = - window.navigator.platform.toLowerCase().indexOf("mac") === 0; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ + function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness + }; + function checkValueUniqueness(node) { + var _node$values; + const typeName = node.name.value; + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + const valueNames = knownValueNames[typeName]; + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) { + context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, { + nodes: valueDef.name + })); + } else if (valueNames[valueName]) { + context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" can only be defined once.`, { + nodes: [valueNames[valueName], valueDef.name] + })); + } else { + valueNames[valueName] = valueDef.name; } - const commonKeys = { - // Persistent search box in Query Editor - [isMacOs ? "Cmd-F" : "Ctrl-F"]: "findPersistent", - "Cmd-G": "findPersistent", - "Ctrl-G": "findPersistent", - // Editor improvements - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", - }; - async function importCodeMirror(addons, options) { - const CodeMirror = await Promise.resolve() - .then(() => - __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ) - ) - .then((n) => n.codemirror) - .then((c) => - // Depending on bundler and settings the dynamic import either returns a - // function (e.g. parcel) or an object containing a `default` property - typeof c === "function" ? c : c.default - ); - await Promise.all( - (options == null ? void 0 : options.useCommonAddons) === false - ? addons - : [ - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js" - ) - ) - .then((n) => n.showHint), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./matchbrackets.cjs.js */ "../../graphiql-react/dist/matchbrackets.cjs.js" - ) - ) - .then((n) => n.matchbrackets), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./closebrackets.cjs.js */ "../../graphiql-react/dist/closebrackets.cjs.js" - ) - ) - .then((n) => n.closebrackets), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js" - ) - ) - .then((n) => n.braceFold), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js" - ) - ) - .then((n) => n.foldgutter), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./lint.cjs.js */ "../../graphiql-react/dist/lint.cjs.js" - ) - ) - .then((n) => n.lint), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js" - ) - ) - .then((n) => n.searchcursor), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js" - ) - ) - .then((n) => n.jumpToLine), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" - ) - ) - .then((n) => n.dialog), - // @ts-expect-error - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js" - ) - ) - .then((n) => n.sublime), - ...addons, - ] - ); - return CodeMirror; + } + return false; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs": + /*!*****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs ***! + \*****************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ + function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness + }; + function checkFieldUniqueness(node) { + var _node$fields; + const typeName = node.name.value; + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + const fieldNames = knownFieldNames[typeName]; + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, { + nodes: fieldDef.name + })); + } else if (fieldNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" can only be defined once.`, { + nodes: [fieldNames[fieldName], fieldDef.name] + })); + } else { + fieldNames[fieldName] = fieldDef.name; } - const printDefault = (ast) => { - if (!ast) { - return ""; - } - return graphql.print(ast); - }; - function DefaultValue({ field }) { - if (!("defaultValue" in field) || field.defaultValue === void 0) { - return null; - } - const ast = graphql.astFromValue(field.defaultValue, field.type); - if (!ast) { - return null; + } + return false; + } + } + function hasField(type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) { + return type.getFields()[fieldName] != null; + } + return false; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + */ + function UniqueFragmentNamesRule(context) { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + if (knownFragmentNames[fragmentName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one fragment named "${fragmentName}".`, { + nodes: [knownFragmentNames[fragmentName], node.name] + })); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs": + /*!************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs ***! + \************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; + var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + */ + function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = Object.create(null); + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave() { + const prevKnownNames = knownNameStack.pop(); + prevKnownNames || (0, _invariant.invariant)(false); + knownNames = prevKnownNames; + } + }, + ObjectField(node) { + const fieldName = node.name.value; + if (knownNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one input field named "${fieldName}".`, { + nodes: [knownNames[fieldName], node.name] + })); + } else { + knownNames[fieldName] = node.name; + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueOperationNamesRule = UniqueOperationNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + */ + function UniqueOperationNamesRule(context) { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one operation named "${operationName.value}".`, { + nodes: [knownOperationNames[operationName.value], operationName] + })); + } else { + knownOperationNames[operationName.value] = operationName; } - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - " = ", - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-default-value", - children: printDefault(ast), - }), - ], - }); } - const SchemaContext = createNullableContext("SchemaContext"); - function SchemaContextProvider(props) { - if (!props.fetcher) { - throw new TypeError( - "The `SchemaContextProvider` component requires a `fetcher` function to be passed as prop." - ); + return false; + }, + FragmentDefinition: () => false + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs": + /*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs ***! + \***********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueOperationTypesRule = UniqueOperationTypesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ + function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType() + } : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes + }; + function checkOperationTypes(node) { + var _node$operationTypes; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes[operation]; + if (existingOperationTypes[operation]) { + context.reportError(new _GraphQLError.GraphQLError(`Type for ${operation} already defined in the schema. It cannot be redefined.`, { + nodes: operationType + })); + } else if (alreadyDefinedOperationType) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one ${operation} type in schema.`, { + nodes: [alreadyDefinedOperationType, operationType] + })); + } else { + definedOperationTypes[operation] = operationType; + } + } + return false; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs": + /*!******************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ + function UniqueTypeNamesRule(context) { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName + }; + function checkTypeName(node) { + const typeName = node.name.value; + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError(new _GraphQLError.GraphQLError(`Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, { + nodes: node.name + })); + return; + } + if (knownTypeNames[typeName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one type named "${typeName}".`, { + nodes: [knownTypeNames[typeName], node.name] + })); + } else { + knownTypeNames[typeName] = node.name; + } + return false; + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.UniqueVariableNamesRule = UniqueVariableNamesRule; + var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + /** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + var _operationNode$variab; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const variableDefinitions = (_operationNode$variab = operationNode.variableDefinitions) !== null && _operationNode$variab !== void 0 ? _operationNode$variab : []; + const seenVariableDefinitions = (0, _groupBy.groupBy)(variableDefinitions, node => node.variable.name.value); + for (const [variableName, variableNodes] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one variable named "$${variableName}".`, { + nodes: variableNodes.map(node => node.variable.name) + })); } - const { initialHeaders, headerEditor } = useEditorContext({ - nonNull: true, - caller: SchemaContextProvider, - }); - const [schema, setSchema] = React.useState(); - const [isFetching, setIsFetching] = React.useState(false); - const [fetchError, setFetchError] = React.useState(null); - const counterRef = React.useRef(0); - React.useEffect(() => { - setSchema( - graphql.isSchema(props.schema) || - props.schema === null || - props.schema === void 0 - ? props.schema - : void 0 - ); - counterRef.current++; - }, [props.schema]); - const headersRef = React.useRef(initialHeaders); - React.useEffect(() => { - if (headerEditor) { - headersRef.current = headerEditor.getValue(); - } - }); - const { - introspectionQuery, - introspectionQueryName, - introspectionQuerySansSubscriptions, - } = useIntrospectionQuery({ - inputValueDeprecation: props.inputValueDeprecation, - introspectionQueryName: props.introspectionQueryName, - schemaDescription: props.schemaDescription, - }); - const { - fetcher, - onSchemaChange, - dangerouslyAssumeSchemaIsValid, - children, - } = props; - const introspect = React.useCallback(() => { - if (graphql.isSchema(props.schema) || props.schema === null) { - return; - } - const counter = ++counterRef.current; - const maybeIntrospectionData = props.schema; - async function fetchIntrospectionData() { - if (maybeIntrospectionData) { - return maybeIntrospectionData; - } - const parsedHeaders = parseHeaderString(headersRef.current); - if (!parsedHeaders.isValidJSON) { - setFetchError("Introspection failed as headers are invalid."); - return; - } - const fetcherOpts = parsedHeaders.headers - ? { - headers: parsedHeaders.headers, - } - : {}; - const fetch2 = toolkit.fetcherReturnToPromise( - fetcher( - { - query: introspectionQuery, - operationName: introspectionQueryName, - }, - fetcherOpts - ) - ); - if (!toolkit.isPromise(fetch2)) { - setFetchError( - "Fetcher did not return a Promise for introspection." - ); - return; - } - setIsFetching(true); - setFetchError(null); - let result = await fetch2; - if ( - typeof result !== "object" || - result === null || - !("data" in result) - ) { - const fetch22 = toolkit.fetcherReturnToPromise( - fetcher( - { - query: introspectionQuerySansSubscriptions, - operationName: introspectionQueryName, - }, - fetcherOpts - ) - ); - if (!toolkit.isPromise(fetch22)) { - throw new Error( - "Fetcher did not return a Promise for introspection." - ); - } - result = await fetch22; - } - setIsFetching(false); - if ( - (result == null ? void 0 : result.data) && - "__schema" in result.data - ) { - return result.data; - } - const responseString = - typeof result === "string" - ? result - : toolkit.formatResult(result); - setFetchError(responseString); - } - fetchIntrospectionData() - .then((introspectionData) => { - if (counter !== counterRef.current || !introspectionData) { - return; - } - try { - const newSchema = - graphql.buildClientSchema(introspectionData); - setSchema(newSchema); - onSchemaChange == null ? void 0 : onSchemaChange(newSchema); - } catch (error) { - setFetchError(toolkit.formatError(error)); - } - }) - .catch((error) => { - if (counter !== counterRef.current) { - return; - } - setFetchError(toolkit.formatError(error)); - setIsFetching(false); - }); - }, [ - fetcher, - introspectionQueryName, - introspectionQuery, - introspectionQuerySansSubscriptions, - onSchemaChange, - props.schema, - ]); - React.useEffect(() => { - introspect(); - }, [introspect]); - React.useEffect(() => { - function triggerIntrospection(event) { - if (event.ctrlKey && event.key === "R") { - introspect(); - } - } - window.addEventListener("keydown", triggerIntrospection); - return () => - window.removeEventListener("keydown", triggerIntrospection); - }); - const validationErrors = React.useMemo(() => { - if (!schema || dangerouslyAssumeSchemaIsValid) { - return []; - } - return graphql.validateSchema(schema); - }, [schema, dangerouslyAssumeSchemaIsValid]); - const value = React.useMemo( - () => ({ - fetchError, - introspect, - isFetching, - schema, - validationErrors, - }), - [fetchError, introspect, isFetching, schema, validationErrors] - ); - return /* @__PURE__ */ jsxRuntime.jsx(SchemaContext.Provider, { - value, - children, - }); } - const useSchemaContext = createContextHook(SchemaContext); - function useIntrospectionQuery({ - inputValueDeprecation, - introspectionQueryName, - schemaDescription, - }) { - return React.useMemo(() => { - const queryName = introspectionQueryName || "IntrospectionQuery"; - let query = graphql.getIntrospectionQuery({ - inputValueDeprecation, - schemaDescription, - }); - if (introspectionQueryName) { - query = query.replace( - "query IntrospectionQuery", - `query ${queryName}` - ); - } - const querySansSubscriptions = query.replace( - "subscriptionType { name }", - "" - ); - return { - introspectionQueryName: queryName, - introspectionQuery: query, - introspectionQuerySansSubscriptions: querySansSubscriptions, - }; - }, [ - inputValueDeprecation, - introspectionQueryName, - schemaDescription, - ]); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs": + /*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; + var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); + var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + */ + function ValuesOfCorrectTypeRule(context) { + return { + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = (0, _definition.getNullableType)(context.getParentInputType()); + if (!(0, _definition.isListType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. } - function parseHeaderString(headersString) { - let headers = null; - let isValidJSON = true; - try { - if (headersString) { - headers = JSON.parse(headersString); - } - } catch { - isValidJSON = false; + }, + ObjectValue(node) { + const type = (0, _definition.getNamedType)(context.getInputType()); + if (!(0, _definition.isInputObjectType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + const fieldNodeMap = (0, _keyMap.keyMap)(node.fields, field => field.name.value); + for (const fieldDef of Object.values(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + const typeStr = (0, _inspect.inspect)(fieldDef.type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, { + nodes: node + })); } - return { - headers, - isValidJSON, - }; } - const initialNavStackItem = { - name: "Docs", - }; - const ExplorerContext = createNullableContext("ExplorerContext"); - function ExplorerContextProvider(props) { - const { schema, validationErrors } = useSchemaContext({ - nonNull: true, - caller: ExplorerContextProvider, - }); - const [navStack, setNavStack] = React.useState([initialNavStackItem]); - const push = React.useCallback((item) => { - setNavStack((currentState) => { - const lastItem = currentState.at(-1); - return lastItem.def === item.def - ? // Avoid pushing duplicate items - currentState - : [...currentState, item]; - }); - }, []); - const pop = React.useCallback(() => { - setNavStack((currentState) => - currentState.length > 1 ? currentState.slice(0, -1) : currentState - ); - }, []); - const reset = React.useCallback(() => { - setNavStack((currentState) => - currentState.length === 1 ? currentState : [initialNavStackItem] - ); - }, []); - React.useEffect(() => { - if (schema == null || validationErrors.length > 0) { - reset(); - } else { - setNavStack((oldNavStack) => { - if (oldNavStack.length === 1) { - return oldNavStack; - } - const newNavStack = [initialNavStackItem]; - let lastEntity = null; - for (const item of oldNavStack) { - if (item === initialNavStackItem) { - continue; - } - if (item.def) { - if (graphql.isNamedType(item.def)) { - const newType = schema.getType(item.def.name); - if (newType) { - newNavStack.push({ - name: item.name, - def: newType, - }); - lastEntity = newType; - } else { - break; - } - } else if (lastEntity === null) { - break; - } else if ( - graphql.isObjectType(lastEntity) || - graphql.isInputObjectType(lastEntity) - ) { - const field = lastEntity.getFields()[item.name]; - if (field) { - newNavStack.push({ - name: item.name, - def: field, - }); - } else { - break; - } - } else if ( - graphql.isScalarType(lastEntity) || - graphql.isEnumType(lastEntity) || - graphql.isInterfaceType(lastEntity) || - graphql.isUnionType(lastEntity) - ) { - break; - } else { - const field = lastEntity; - const arg = field.args.find((a) => a.name === item.name); - if (arg) { - newNavStack.push({ - name: item.name, - def: field, - }); - } else { - break; - } - } - } else { - lastEntity = null; - newNavStack.push(item); - } - } - return newNavStack; - }); - } - }, [reset, schema, validationErrors]); - const value = React.useMemo( - () => ({ - explorerNavStack: navStack, - push, - pop, - reset, - }), - [navStack, push, pop, reset] - ); - return /* @__PURE__ */ jsxRuntime.jsx(ExplorerContext.Provider, { - value, - children: props.children, - }); + }, + ObjectField(node) { + const parentType = (0, _definition.getNamedType)(context.getParentInputType()); + const fieldType = context.getInputType(); + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + const suggestions = (0, _suggestionList.suggestionList)(node.name.value, Object.keys(parentType.getFields())); + context.reportError(new _GraphQLError.GraphQLError(`Field "${node.name.value}" is not defined by type "${parentType.name}".` + (0, _didYouMean.didYouMean)(suggestions), { + nodes: node + })); + } + }, + NullValue(node) { + const type = context.getInputType(); + if ((0, _definition.isNonNullType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${(0, _inspect.inspect)(type)}", found ${(0, _printer.print)(node)}.`, { + nodes: node + })); + } + }, + EnumValue: node => isValidValueNode(context, node), + IntValue: node => isValidValueNode(context, node), + FloatValue: node => isValidValueNode(context, node), + StringValue: node => isValidValueNode(context, node), + BooleanValue: node => isValidValueNode(context, node) + }; + } + /** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + + function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + if (!locationType) { + return; + } + const type = (0, _definition.getNamedType)(locationType); + if (!(0, _definition.isLeafType)(type)) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { + nodes: node + })); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + try { + const parseResult = type.parseLiteral(node, undefined + /* variables */); + if (parseResult === undefined) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { + nodes: node + })); + } + } catch (error) { + const typeStr = (0, _inspect.inspect)(locationType); + if (error instanceof _GraphQLError.GraphQLError) { + context.reportError(error); + } else { + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}; ` + error.message, { + nodes: node, + originalError: error + })); + } + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs": + /*!*************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs ***! + \*************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + /** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + * + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types + */ + function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); + if (type !== undefined && !(0, _definition.isInputType)(type)) { + const variableName = node.variable.name.value; + const typeName = (0, _printer.print)(node.type); + context.reportError(new _GraphQLError.GraphQLError(`Variable "$${variableName}" cannot be non-input type "${typeName}".`, { + nodes: node.type + })); } - const useExplorerContext = createContextHook(ExplorerContext); - function renderType(type, renderNamedType) { - if (graphql.isNonNullType(type)) { - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [renderType(type.ofType, renderNamedType), "!"], - }); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs": + /*!*****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs ***! + \*****************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; + var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); + var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); + var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); + /** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + */ + function VariablesInAllowedPositionRule(context) { + let varDefMap = Object.create(null); + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { + node, + type, + defaultValue + } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + const varTypeStr = (0, _inspect.inspect)(varType); + const typeStr = (0, _inspect.inspect)(type); + context.reportError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, { + nodes: [varDef, node] + })); + } + } } - if (graphql.isListType(type)) { - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["[", renderType(type.ofType, renderNamedType), "]"], - }); + } + }, + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; + } + /** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + + function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { + const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + const nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); + } + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs": + /*!****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs ***! + \****************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; + var _invariant = __webpack_require__(/*! ../../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); + var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + /** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ + function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason; + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + parentType != null || (0, _invariant.invariant)(false); + context.reportError(new _GraphQLError.GraphQLError(`The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, { + nodes: node + })); + } + }, + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = argDef === null || argDef === void 0 ? void 0 : argDef.deprecationReason; + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); + if (directiveDef != null) { + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { + nodes: node + })); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + parentType != null && fieldDef != null || (0, _invariant.invariant)(false); + context.reportError(new _GraphQLError.GraphQLError(`Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { + nodes: node + })); } - return renderNamedType(type); } - function TypeLink(props) { - const { push } = useExplorerContext({ - nonNull: true, - caller: TypeLink, - }); - if (!props.type) { - return null; + }, + ObjectField(node) { + const inputObjectDef = (0, _definition.getNamedType)(context.getParentInputType()); + if ((0, _definition.isInputObjectType)(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + const deprecationReason = inputFieldDef === null || inputFieldDef === void 0 ? void 0 : inputFieldDef.deprecationReason; + if (deprecationReason != null) { + context.reportError(new _GraphQLError.GraphQLError(`The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, { + nodes: node + })); } - return renderType(props.type, (namedType) => - /* @__PURE__ */ jsxRuntime.jsx("a", { - className: "graphiql-doc-explorer-type-name", - onClick: (event) => { - event.preventDefault(); - push({ - name: namedType.name, - def: namedType, - }); - }, - href: "#", - children: namedType.name, - }) - ); } - function Argument({ arg, showDefaultValue, inline }) { - const definition = /* @__PURE__ */ jsxRuntime.jsxs("span", { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-argument-name", - children: arg.name, - }), - ": ", - /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: arg.type, - }), - showDefaultValue !== false && - /* @__PURE__ */ jsxRuntime.jsx(DefaultValue, { - field: arg, - }), - ], - }); - if (inline) { - return definition; - } - return /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-argument", - children: [ - definition, - arg.description - ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: arg.description, - }) - : null, - arg.deprecationReason - ? /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-argument-deprecation", - children: [ - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: - "graphiql-doc-explorer-argument-deprecation-label", - children: "Deprecated", - }), - /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - children: arg.deprecationReason, - }), - ], - }) - : null, - ], - }); + }, + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason; + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = (0, _definition.getNamedType)(context.getInputType()); + enumTypeDef != null || (0, _invariant.invariant)(false); + context.reportError(new _GraphQLError.GraphQLError(`The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, { + nodes: node + })); } - function DeprecationReason(props) { - var _props$preview; - return props.children - ? /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-deprecation", - children: [ - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-deprecation-label", - children: "Deprecated", - }), - /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - onlyShowFirstChild: - (_props$preview = props.preview) !== null && - _props$preview !== void 0 - ? _props$preview - : true, - children: props.children, - }), - ], - }) - : null; + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs": + /*!*************************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs ***! + \*************************************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; + var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); + var _introspection = __webpack_require__(/*! ../../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); + /** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ + function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = (0, _definition.getNamedType)(context.getType()); + if (type && (0, _introspection.isIntrospectionType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(`GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, { + nodes: node + })); } - function Directive({ directive }) { - return /* @__PURE__ */ jsxRuntime.jsxs("span", { - className: "graphiql-doc-explorer-directive", - children: ["@", directive.name.value], - }); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/specifiedRules.mjs": + /*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/validation/specifiedRules.mjs ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.specifiedSDLRules = exports.specifiedRules = void 0; + var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); + var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); + var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); + var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); + var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); + var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); + var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); + var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); + var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); + var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); + var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); + var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); + var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); + var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); + var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); + var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); + var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); + var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); + var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); + var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); + var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); + var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); + var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); + var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); + var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); + var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); + var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); + var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); + var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); + var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); + var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); + var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); + var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); + var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); + // Spec Section: "Executable Definitions" + // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + + // Spec Section: "Fragments on Composite Types" + + // Spec Section: "Argument Names" + + // Spec Section: "Directives Are Defined" + + // Spec Section: "Fragment spread target defined" + + // Spec Section: "Fragment Spread Type Existence" + + // Spec Section: "Lone Anonymous Operation" + + // SDL-specific validation rules + + // Spec Section: "Fragments must not form cycles" + + // Spec Section: "All Variable Used Defined" + + // Spec Section: "Fragments must be used" + + // Spec Section: "All Variables Used" + + // Spec Section: "Field Selection Merging" + + // Spec Section: "Fragment spread is possible" + + // Spec Section: "Argument Optionality" + + // Spec Section: "Leaf Field Selections" + + // Spec Section: "Subscriptions with Single Root Field" + + // Spec Section: "Argument Uniqueness" + + // Spec Section: "Directives Are Unique Per Location" + + // Spec Section: "Fragment Name Uniqueness" + + // Spec Section: "Input Object Field Uniqueness" + + // Spec Section: "Operation Name Uniqueness" + + // Spec Section: "Variable Uniqueness" + + // Spec Section: "Value Type Correctness" + + // Spec Section: "Variables are Input Types" + + // Spec Section: "All Variable Usages Are Allowed" + + /** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + const specifiedRules = exports.specifiedRules = Object.freeze([_ExecutableDefinitionsRule.ExecutableDefinitionsRule, _UniqueOperationNamesRule.UniqueOperationNamesRule, _LoneAnonymousOperationRule.LoneAnonymousOperationRule, _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, _KnownTypeNamesRule.KnownTypeNamesRule, _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, _VariablesAreInputTypesRule.VariablesAreInputTypesRule, _ScalarLeafsRule.ScalarLeafsRule, _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, _UniqueFragmentNamesRule.UniqueFragmentNamesRule, _KnownFragmentNamesRule.KnownFragmentNamesRule, _NoUnusedFragmentsRule.NoUnusedFragmentsRule, _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, _NoFragmentCyclesRule.NoFragmentCyclesRule, _UniqueVariableNamesRule.UniqueVariableNamesRule, _NoUndefinedVariablesRule.NoUndefinedVariablesRule, _NoUnusedVariablesRule.NoUnusedVariablesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _KnownArgumentNamesRule.KnownArgumentNamesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule]); + /** + * @internal + */ + + const specifiedSDLRules = exports.specifiedSDLRules = Object.freeze([_LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, _UniqueOperationTypesRule.UniqueOperationTypesRule, _UniqueTypeNamesRule.UniqueTypeNamesRule, _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, _KnownTypeNamesRule.KnownTypeNamesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule]); + + /***/ }), + + /***/ "../../../node_modules/graphql/validation/validate.mjs": + /*!*************************************************************!*\ + !*** ../../../node_modules/graphql/validation/validate.mjs ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.assertValidSDL = assertValidSDL; + exports.assertValidSDLExtension = assertValidSDLExtension; + exports.validate = validate; + exports.validateSDL = validateSDL; + var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); + var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); + var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); + var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); + var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); + var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); + var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); + /** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so by default `maxErrors` set to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ + + function validate(schema, documentAST, rules = _specifiedRules.specifiedRules, options, /** @deprecated will be removed in 17.0.0 */ + typeInfo = new _TypeInfo.TypeInfo(schema)) { + var _options$maxErrors; + const maxErrors = (_options$maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors) !== null && _options$maxErrors !== void 0 ? _options$maxErrors : 100; + documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + const abortObj = Object.freeze({}); + const errors = []; + const context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo, error => { + if (errors.length >= maxErrors) { + errors.push(new _GraphQLError.GraphQLError('Too many validation errors, error limit reached. Validation aborted.')); // eslint-disable-next-line @typescript-eslint/no-throw-literal + + throw abortObj; + } + errors.push(error); + }); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + const visitor = (0, _visitor.visitInParallel)(rules.map(rule => rule(context))); // Visit the whole document with each instance of all provided rules. + + try { + (0, _visitor.visit)(documentAST, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor)); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + return errors; + } + /** + * @internal + */ + + function validateSDL(documentAST, schemaToExtend, rules = _specifiedRules.specifiedSDLRules) { + const errors = []; + const context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend, error => { + errors.push(error); + }); + const visitors = rules.map(rule => rule(context)); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return errors; + } + /** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } + } + /** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } + } + + /***/ }), + + /***/ "../../../node_modules/graphql/version.mjs": + /*!*************************************************!*\ + !*** ../../../node_modules/graphql/version.mjs ***! + \*************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.versionInfo = exports.version = void 0; + // Note: This file is autogenerated using "resources/gen-version.js" script and + // automatically updated by "npm version" command. + + /** + * A string containing the version of the GraphQL.js library + */ + const version = exports.version = '16.8.1'; + /** + * An object containing the components of the GraphQL.js version string + */ + + const versionInfo = exports.versionInfo = Object.freeze({ + major: 16, + minor: 8, + patch: 1, + preReleaseTag: null + }); + + /***/ }), + + /***/ "../../../node_modules/hey-listen/dist/hey-listen.es.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/hey-listen/dist/hey-listen.es.js ***! + \**************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.warning = exports.invariant = void 0; + var warning = function () {}; + exports.warning = warning; + var invariant = function () {}; + exports.invariant = invariant; + if (true) { + exports.warning = warning = function (check, message) { + if (!check && typeof console !== 'undefined') { + console.warn(message); + } + }; + exports.invariant = invariant = function (check, message) { + if (!check) { + throw new Error(message); + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/is-plain-object/index.js": + /*!******************************************************!*\ + !*** ../../../node_modules/is-plain-object/index.js ***! + \******************************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + /*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + + var isObject = __webpack_require__(/*! isobject */ "../../../node_modules/isobject/index.js"); + function isObjectObject(o) { + return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; + } + module.exports = function isPlainObject(o) { + var ctor, prot; + if (isObjectObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (typeof ctor !== 'function') return false; + + // If has modified prototype + prot = ctor.prototype; + if (isObjectObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; + }; + + /***/ }), + + /***/ "../../../node_modules/is-primitive/index.js": + /*!***************************************************!*\ + !*** ../../../node_modules/is-primitive/index.js ***! + \***************************************************/ + /***/ (function(module) { + + /*! + * is-primitive + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + + + + module.exports = function isPrimitive(val) { + if (typeof val === 'object') { + return val === null; + } + return typeof val !== 'function'; + }; + + /***/ }), + + /***/ "../../../node_modules/isarray/index.js": + /*!**********************************************!*\ + !*** ../../../node_modules/isarray/index.js ***! + \**********************************************/ + /***/ (function(module) { + + + + var toString = {}.toString; + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + /***/ }), + + /***/ "../../../node_modules/isobject/index.js": + /*!***********************************************!*\ + !*** ../../../node_modules/isobject/index.js ***! + \***********************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + /*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + + var isArray = __webpack_require__(/*! isarray */ "../../../node_modules/isarray/index.js"); + module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; + }; + + /***/ }), + + /***/ "../../../node_modules/meros/browser/index.js": + /*!****************************************************!*\ + !*** ../../../node_modules/meros/browser/index.js ***! + \****************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + var e = new TextDecoder(); + async function t(t, n) { + if (!t.ok || !t.body || t.bodyUsed) return t; + let i = t.headers.get("content-type"); + if (!i || !~i.indexOf("multipart/")) return t; + let l = i.indexOf("boundary="), + r = "-"; + if (~l) { + let e = l + 9, + t = i.indexOf(";", e); + r = i.slice(e, t > -1 ? t : void 0).trim().replace(/"/g, ""); + } + return async function* (t, n, i) { + let l, + r, + d, + o = t.getReader(), + a = !i || !i.multiple, + f = n.length, + s = "", + c = []; + try { + let t; + e: for (; !(t = await o.read()).done;) { + let i = e.decode(t.value); + l = s.length, s += i; + let o = i.indexOf(n); + for (~o ? l += o : l = s.indexOf(n), c = []; ~l;) { + let e = s.slice(0, l), + t = s.slice(l + f); + if (r) { + let n = e.indexOf("\r\n\r\n") + 4, + i = e.lastIndexOf("\r\n", n), + l = !1, + r = e.slice(n, i > -1 ? void 0 : i), + o = String(e.slice(0, n)).trim().split("\r\n"), + f = {}, + s = o.length; + for (; d = o[--s]; d = d.split(": "), f[d.shift().toLowerCase()] = d.join(": ")); + if (d = f["content-type"], d && ~d.indexOf("application/json")) try { + r = JSON.parse(r), l = !0; + } catch (e) {} + if (d = { + headers: f, + body: r, + json: l + }, a ? yield d : c.push(d), "--" === t.slice(0, 2)) break e; + } else n = "\r\n" + n, r = f += 2; + s = t, l = s.indexOf(n); + } + c.length && (yield c); + } + } finally { + c.length && (yield c), await o.cancel(); + } + }(t.body, `--${r}`, n); + } + exports.meros = t; + + /***/ }), + + /***/ "../../../node_modules/nullthrows/nullthrows.js": + /*!******************************************************!*\ + !*** ../../../node_modules/nullthrows/nullthrows.js ***! + \******************************************************/ + /***/ (function(module) { + + + + function nullthrows(x, message) { + if (x != null) { + return x; + } + var error = new Error(message !== undefined ? message : 'Got unexpected ' + x); + error.framesToPop = 1; // Skip nullthrows's own stack frame. + throw error; + } + module.exports = nullthrows; + module.exports["default"] = nullthrows; + Object.defineProperty(module.exports, "__esModule", ({ + value: true + })); + + /***/ }), + + /***/ "../../../node_modules/popmotion/dist/popmotion.cjs.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/popmotion/dist/popmotion.cjs.js ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); + var styleValueTypes = __webpack_require__(/*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js"); + var sync = __webpack_require__(/*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js"); + function _interopDefaultLegacy(e) { + return e && typeof e === 'object' && 'default' in e ? e : { + 'default': e + }; + } + var sync__default = /*#__PURE__*/_interopDefaultLegacy(sync); + const clamp = (min, max, v) => Math.min(Math.max(v, min), max); + const safeMin = 0.001; + const minDuration = 0.01; + const maxDuration = 10.0; + const minDamping = 0.05; + const maxDamping = 1; + function findSpring({ + duration = 800, + bounce = 0.25, + velocity = 0, + mass = 1 + }) { + let envelope; + let derivative; + heyListen.warning(duration <= maxDuration * 1000, "Spring duration must be 10 seconds or less"); + let dampingRatio = 1 - bounce; + dampingRatio = clamp(minDamping, maxDamping, dampingRatio); + duration = clamp(minDuration, maxDuration, duration / 1000); + if (dampingRatio < 1) { + envelope = undampedFreq => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const a = exponentialDecay - velocity; + const b = calcAngularFreq(undampedFreq, dampingRatio); + const c = Math.exp(-delta); + return safeMin - a / b * c; + }; + derivative = undampedFreq => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const d = delta * velocity + velocity; + const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration; + const f = Math.exp(-delta); + const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio); + const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1; + return factor * ((d - e) * f) / g; + }; + } else { + envelope = undampedFreq => { + const a = Math.exp(-undampedFreq * duration); + const b = (undampedFreq - velocity) * duration + 1; + return -safeMin + a * b; + }; + derivative = undampedFreq => { + const a = Math.exp(-undampedFreq * duration); + const b = (velocity - undampedFreq) * (duration * duration); + return a * b; + }; + } + const initialGuess = 5 / duration; + const undampedFreq = approximateRoot(envelope, derivative, initialGuess); + duration = duration * 1000; + if (isNaN(undampedFreq)) { + return { + stiffness: 100, + damping: 10, + duration + }; + } else { + const stiffness = Math.pow(undampedFreq, 2) * mass; + return { + stiffness, + damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), + duration + }; + } + } + const rootIterations = 12; + function approximateRoot(envelope, derivative, initialGuess) { + let result = initialGuess; + for (let i = 1; i < rootIterations; i++) { + result = result - envelope(result) / derivative(result); + } + return result; + } + function calcAngularFreq(undampedFreq, dampingRatio) { + return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); + } + const durationKeys = ["duration", "bounce"]; + const physicsKeys = ["stiffness", "damping", "mass"]; + function isSpringType(options, keys) { + return keys.some(key => options[key] !== undefined); + } + function getSpringOptions(options) { + let springOptions = Object.assign({ + velocity: 0.0, + stiffness: 100, + damping: 10, + mass: 1.0, + isResolvedFromDuration: false + }, options); + if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) { + const derived = findSpring(options); + springOptions = Object.assign(Object.assign(Object.assign({}, springOptions), derived), { + velocity: 0.0, + mass: 1.0 + }); + springOptions.isResolvedFromDuration = true; + } + return springOptions; + } + function spring(_a) { + var { + from = 0.0, + to = 1.0, + restSpeed = 2, + restDelta + } = _a, + options = tslib.__rest(_a, ["from", "to", "restSpeed", "restDelta"]); + const state = { + done: false, + value: from + }; + let { + stiffness, + damping, + mass, + velocity, + duration, + isResolvedFromDuration + } = getSpringOptions(options); + let resolveSpring = zero; + let resolveVelocity = zero; + function createSpring() { + const initialVelocity = velocity ? -(velocity / 1000) : 0.0; + const initialDelta = to - from; + const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); + const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; + if (restDelta === undefined) { + restDelta = Math.min(Math.abs(to - from) / 100, 0.4); + } + if (dampingRatio < 1) { + const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); + resolveSpring = t => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); + }; + resolveVelocity = t => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return dampingRatio * undampedAngularFreq * envelope * (Math.sin(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq + initialDelta * Math.cos(angularFreq * t)) - envelope * (Math.cos(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) - angularFreq * initialDelta * Math.sin(angularFreq * t)); + }; + } else if (dampingRatio === 1) { + resolveSpring = t => to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t); + } else { + const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); + resolveSpring = t => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + const freqForT = Math.min(dampedAngularFreq * t, 300); + return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq; + }; + } + } + createSpring(); + return { + next: t => { + const current = resolveSpring(t); + if (!isResolvedFromDuration) { + const currentVelocity = resolveVelocity(t) * 1000; + const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; + const isBelowDisplacementThreshold = Math.abs(to - current) <= restDelta; + state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold; + } else { + state.done = t >= duration; } - function ExplorerSection(props) { - const Icon2 = TYPE_TO_ICON[props.title]; - return /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-section-title", - children: [ - /* @__PURE__ */ jsxRuntime.jsx(Icon2, {}), - props.title, - ], - }), - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-section-content", - children: props.children, - }), - ], - }); + state.value = state.done ? to : current; + return state; + }, + flipTarget: () => { + velocity = -velocity; + [from, to] = [to, from]; + createSpring(); + } + }; + } + spring.needsInterpolation = (a, b) => typeof a === "string" || typeof b === "string"; + const zero = _t => 0; + const progress = (from, to, value) => { + const toFromDifference = to - from; + return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; + }; + const mix = (from, to, progress) => -progress * from + progress * to + from; + function hueToRgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + function hslaToRgba({ + hue, + saturation, + lightness, + alpha + }) { + hue /= 360; + saturation /= 100; + lightness /= 100; + let red = 0; + let green = 0; + let blue = 0; + if (!saturation) { + red = green = blue = lightness; + } else { + const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; + const p = 2 * lightness - q; + red = hueToRgb(p, q, hue + 1 / 3); + green = hueToRgb(p, q, hue); + blue = hueToRgb(p, q, hue - 1 / 3); + } + return { + red: Math.round(red * 255), + green: Math.round(green * 255), + blue: Math.round(blue * 255), + alpha + }; + } + const mixLinearColor = (from, to, v) => { + const fromExpo = from * from; + const toExpo = to * to; + return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo)); + }; + const colorTypes = [styleValueTypes.hex, styleValueTypes.rgba, styleValueTypes.hsla]; + const getColorType = v => colorTypes.find(type => type.test(v)); + const notAnimatable = color => `'${color}' is not an animatable color. Use the equivalent color code instead.`; + const mixColor = (from, to) => { + let fromColorType = getColorType(from); + let toColorType = getColorType(to); + heyListen.invariant(!!fromColorType, notAnimatable(from)); + heyListen.invariant(!!toColorType, notAnimatable(to)); + let fromColor = fromColorType.parse(from); + let toColor = toColorType.parse(to); + if (fromColorType === styleValueTypes.hsla) { + fromColor = hslaToRgba(fromColor); + fromColorType = styleValueTypes.rgba; + } + if (toColorType === styleValueTypes.hsla) { + toColor = hslaToRgba(toColor); + toColorType = styleValueTypes.rgba; + } + const blended = Object.assign({}, fromColor); + return v => { + for (const key in blended) { + if (key !== "alpha") { + blended[key] = mixLinearColor(fromColor[key], toColor[key], v); } - const TYPE_TO_ICON = { - Arguments: ArgumentIcon, - "Deprecated Arguments": DeprecatedArgumentIcon, - "Deprecated Enum Values": DeprecatedEnumValueIcon, - "Deprecated Fields": DeprecatedFieldIcon, - Directives: DirectiveIcon, - "Enum Values": EnumValueIcon, - Fields: FieldIcon, - Implements: ImplementsIcon, - Implementations: TypeIcon, - "Possible Types": TypeIcon, - "Root Types": RootTypeIcon, - Type: TypeIcon, - "All Schema Types": TypeIcon, - }; - function FieldDocumentation(props) { - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - props.field.description - ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.field.description, - }) - : null, - /* @__PURE__ */ jsxRuntime.jsx(DeprecationReason, { - preview: false, - children: props.field.deprecationReason, - }), - /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Type", - children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: props.field.type, - }), - }), - /* @__PURE__ */ jsxRuntime.jsx(Arguments, { - field: props.field, - }), - /* @__PURE__ */ jsxRuntime.jsx(Directives, { - field: props.field, - }), - ], - }); + } + blended.alpha = mix(fromColor.alpha, toColor.alpha, v); + return fromColorType.transform(blended); + }; + }; + const zeroPoint = { + x: 0, + y: 0, + z: 0 + }; + const isNum = v => typeof v === 'number'; + const combineFunctions = (a, b) => v => b(a(v)); + const pipe = (...transformers) => transformers.reduce(combineFunctions); + function getMixer(origin, target) { + if (isNum(origin)) { + return v => mix(origin, target, v); + } else if (styleValueTypes.color.test(origin)) { + return mixColor(origin, target); + } else { + return mixComplex(origin, target); + } + } + const mixArray = (from, to) => { + const output = [...from]; + const numValues = output.length; + const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i])); + return v => { + for (let i = 0; i < numValues; i++) { + output[i] = blendValue[i](v); + } + return output; + }; + }; + const mixObject = (origin, target) => { + const output = Object.assign(Object.assign({}, origin), target); + const blendValue = {}; + for (const key in output) { + if (origin[key] !== undefined && target[key] !== undefined) { + blendValue[key] = getMixer(origin[key], target[key]); + } + } + return v => { + for (const key in blendValue) { + output[key] = blendValue[key](v); + } + return output; + }; + }; + function analyse(value) { + const parsed = styleValueTypes.complex.parse(value); + const numValues = parsed.length; + let numNumbers = 0; + let numRGB = 0; + let numHSL = 0; + for (let i = 0; i < numValues; i++) { + if (numNumbers || typeof parsed[i] === "number") { + numNumbers++; + } else { + if (parsed[i].hue !== undefined) { + numHSL++; + } else { + numRGB++; } - function Arguments({ field }) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!("args" in field)) { - return null; + } + } + return { + parsed, + numNumbers, + numRGB, + numHSL + }; + } + const mixComplex = (origin, target) => { + const template = styleValueTypes.complex.createTransformer(target); + const originStats = analyse(origin); + const targetStats = analyse(target); + const canInterpolate = originStats.numHSL === targetStats.numHSL && originStats.numRGB === targetStats.numRGB && originStats.numNumbers >= targetStats.numNumbers; + if (canInterpolate) { + return pipe(mixArray(originStats.parsed, targetStats.parsed), template); + } else { + heyListen.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`); + return p => `${p > 0 ? target : origin}`; + } + }; + const mixNumber = (from, to) => p => mix(from, to, p); + function detectMixerFactory(v) { + if (typeof v === 'number') { + return mixNumber; + } else if (typeof v === 'string') { + if (styleValueTypes.color.test(v)) { + return mixColor; + } else { + return mixComplex; + } + } else if (Array.isArray(v)) { + return mixArray; + } else if (typeof v === 'object') { + return mixObject; + } + } + function createMixers(output, ease, customMixer) { + const mixers = []; + const mixerFactory = customMixer || detectMixerFactory(output[0]); + const numMixers = output.length - 1; + for (let i = 0; i < numMixers; i++) { + let mixer = mixerFactory(output[i], output[i + 1]); + if (ease) { + const easingFunction = Array.isArray(ease) ? ease[i] : ease; + mixer = pipe(easingFunction, mixer); + } + mixers.push(mixer); + } + return mixers; + } + function fastInterpolate([from, to], [mixer]) { + return v => mixer(progress(from, to, v)); + } + function slowInterpolate(input, mixers) { + const inputLength = input.length; + const lastInputIndex = inputLength - 1; + return v => { + let mixerIndex = 0; + let foundMixerIndex = false; + if (v <= input[0]) { + foundMixerIndex = true; + } else if (v >= input[lastInputIndex]) { + mixerIndex = lastInputIndex - 1; + foundMixerIndex = true; + } + if (!foundMixerIndex) { + let i = 1; + for (; i < inputLength; i++) { + if (input[i] > v || i === lastInputIndex) { + break; } - const args = []; - const deprecatedArgs = []; - for (const argument of field.args) { - if (argument.deprecationReason) { - deprecatedArgs.push(argument); - } else { - args.push(argument); - } - } - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - args.length > 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Arguments", - children: args.map((arg) => - /* @__PURE__ */ jsxRuntime.jsx( - Argument, - { - arg, - }, - arg.name - ) - ), - }) - : null, - deprecatedArgs.length > 0 - ? showDeprecated || args.length === 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Arguments", - children: deprecatedArgs.map((arg) => - /* @__PURE__ */ jsxRuntime.jsx( - Argument, - { - arg, - }, - arg.name - ) - ), - }) - : /* @__PURE__ */ jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Arguments", - }) - : null, - ], - }); } - function Directives({ field }) { + mixerIndex = i - 1; + } + const progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v); + return mixers[mixerIndex](progressInRange); + }; + } + function interpolate(input, output, { + clamp: isClamp = true, + ease, + mixer + } = {}) { + const inputLength = input.length; + heyListen.invariant(inputLength === output.length, 'Both input and output ranges must be the same length'); + heyListen.invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1, 'Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values.'); + if (input[0] > input[inputLength - 1]) { + input = [].concat(input); + output = [].concat(output); + input.reverse(); + output.reverse(); + } + const mixers = createMixers(output, ease, mixer); + const interpolator = inputLength === 2 ? fastInterpolate(input, mixers) : slowInterpolate(input, mixers); + return isClamp ? v => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator; + } + const reverseEasing = easing => p => 1 - easing(1 - p); + const mirrorEasing = easing => p => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; + const createExpoIn = power => p => Math.pow(p, power); + const createBackIn = power => p => p * p * ((power + 1) * p - power); + const createAnticipate = power => { + const backEasing = createBackIn(power); + return p => (p *= 2) < 1 ? 0.5 * backEasing(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); + }; + const DEFAULT_OVERSHOOT_STRENGTH = 1.525; + const BOUNCE_FIRST_THRESHOLD = 4.0 / 11.0; + const BOUNCE_SECOND_THRESHOLD = 8.0 / 11.0; + const BOUNCE_THIRD_THRESHOLD = 9.0 / 10.0; + const linear = p => p; + const easeIn = createExpoIn(2); + const easeOut = reverseEasing(easeIn); + const easeInOut = mirrorEasing(easeIn); + const circIn = p => 1 - Math.sin(Math.acos(p)); + const circOut = reverseEasing(circIn); + const circInOut = mirrorEasing(circOut); + const backIn = createBackIn(DEFAULT_OVERSHOOT_STRENGTH); + const backOut = reverseEasing(backIn); + const backInOut = mirrorEasing(backIn); + const anticipate = createAnticipate(DEFAULT_OVERSHOOT_STRENGTH); + const ca = 4356.0 / 361.0; + const cb = 35442.0 / 1805.0; + const cc = 16061.0 / 1805.0; + const bounceOut = p => { + if (p === 1 || p === 0) return p; + const p2 = p * p; + return p < BOUNCE_FIRST_THRESHOLD ? 7.5625 * p2 : p < BOUNCE_SECOND_THRESHOLD ? 9.075 * p2 - 9.9 * p + 3.4 : p < BOUNCE_THIRD_THRESHOLD ? ca * p2 - cb * p + cc : 10.8 * p * p - 20.52 * p + 10.72; + }; + const bounceIn = reverseEasing(bounceOut); + const bounceInOut = p => p < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - p * 2.0)) : 0.5 * bounceOut(p * 2.0 - 1.0) + 0.5; + function defaultEasing(values, easing) { + return values.map(() => easing || easeInOut).splice(0, values.length - 1); + } + function defaultOffset(values) { + const numValues = values.length; + return values.map((_value, i) => i !== 0 ? i / (numValues - 1) : 0); + } + function convertOffsetToTimes(offset, duration) { + return offset.map(o => o * duration); + } + function keyframes({ + from = 0, + to = 1, + ease, + offset, + duration = 300 + }) { + const state = { + done: false, + value: from + }; + const values = Array.isArray(to) ? to : [from, to]; + const times = convertOffsetToTimes(offset && offset.length === values.length ? offset : defaultOffset(values), duration); + function createInterpolator() { + return interpolate(times, values, { + ease: Array.isArray(ease) ? ease : defaultEasing(values, ease) + }); + } + let interpolator = createInterpolator(); + return { + next: t => { + state.value = interpolator(t); + state.done = t >= duration; + return state; + }, + flipTarget: () => { + values.reverse(); + interpolator = createInterpolator(); + } + }; + } + function decay({ + velocity = 0, + from = 0, + power = 0.8, + timeConstant = 350, + restDelta = 0.5, + modifyTarget + }) { + const state = { + done: false, + value: from + }; + let amplitude = power * velocity; + const ideal = from + amplitude; + const target = modifyTarget === undefined ? ideal : modifyTarget(ideal); + if (target !== ideal) amplitude = target - from; + return { + next: t => { + const delta = -amplitude * Math.exp(-t / timeConstant); + state.done = !(delta > restDelta || delta < -restDelta); + state.value = state.done ? target : target + delta; + return state; + }, + flipTarget: () => {} + }; + } + const types = { + keyframes, + spring, + decay + }; + function detectAnimationFromOptions(config) { + if (Array.isArray(config.to)) { + return keyframes; + } else if (types[config.type]) { + return types[config.type]; + } + const keys = new Set(Object.keys(config)); + if (keys.has("ease") || keys.has("duration") && !keys.has("dampingRatio")) { + return keyframes; + } else if (keys.has("dampingRatio") || keys.has("stiffness") || keys.has("mass") || keys.has("damping") || keys.has("restSpeed") || keys.has("restDelta")) { + return spring; + } + return keyframes; + } + function loopElapsed(elapsed, duration, delay = 0) { + return elapsed - duration - delay; + } + function reverseElapsed(elapsed, duration, delay = 0, isForwardPlayback = true) { + return isForwardPlayback ? loopElapsed(duration + -elapsed, duration, delay) : duration - (elapsed - duration) + delay; + } + function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) { + return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay; + } + const framesync = update => { + const passTimestamp = ({ + delta + }) => update(delta); + return { + start: () => sync__default["default"].update(passTimestamp, true), + stop: () => sync.cancelSync.update(passTimestamp) + }; + }; + function animate(_a) { + var _b, _c; + var { + from, + autoplay = true, + driver = framesync, + elapsed = 0, + repeat: repeatMax = 0, + repeatType = "loop", + repeatDelay = 0, + onPlay, + onStop, + onComplete, + onRepeat, + onUpdate + } = _a, + options = tslib.__rest(_a, ["from", "autoplay", "driver", "elapsed", "repeat", "repeatType", "repeatDelay", "onPlay", "onStop", "onComplete", "onRepeat", "onUpdate"]); + let { + to + } = options; + let driverControls; + let repeatCount = 0; + let computedDuration = options.duration; + let latest; + let isComplete = false; + let isForwardPlayback = true; + let interpolateFromNumber; + const animator = detectAnimationFromOptions(options); + if ((_c = (_b = animator).needsInterpolation) === null || _c === void 0 ? void 0 : _c.call(_b, from, to)) { + interpolateFromNumber = interpolate([0, 100], [from, to], { + clamp: false + }); + from = 0; + to = 100; + } + const animation = animator(Object.assign(Object.assign({}, options), { + from, + to + })); + function repeat() { + repeatCount++; + if (repeatType === "reverse") { + isForwardPlayback = repeatCount % 2 === 0; + elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback); + } else { + elapsed = loopElapsed(elapsed, computedDuration, repeatDelay); + if (repeatType === "mirror") animation.flipTarget(); + } + isComplete = false; + onRepeat && onRepeat(); + } + function complete() { + driverControls.stop(); + onComplete && onComplete(); + } + function update(delta) { + if (!isForwardPlayback) delta = -delta; + elapsed += delta; + if (!isComplete) { + const state = animation.next(Math.max(0, elapsed)); + latest = state.value; + if (interpolateFromNumber) latest = interpolateFromNumber(latest); + isComplete = isForwardPlayback ? state.done : elapsed <= 0; + } + onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(latest); + if (isComplete) { + if (repeatCount === 0) computedDuration !== null && computedDuration !== void 0 ? computedDuration : computedDuration = elapsed; + if (repeatCount < repeatMax) { + hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat(); + } else { + complete(); + } + } + } + function play() { + onPlay === null || onPlay === void 0 ? void 0 : onPlay(); + driverControls = driver(update); + driverControls.start(); + } + autoplay && play(); + return { + stop: () => { + onStop === null || onStop === void 0 ? void 0 : onStop(); + driverControls.stop(); + } + }; + } + function velocityPerSecond(velocity, frameDuration) { + return frameDuration ? velocity * (1000 / frameDuration) : 0; + } + function inertia({ + from = 0, + velocity = 0, + min, + max, + power = 0.8, + timeConstant = 750, + bounceStiffness = 500, + bounceDamping = 10, + restDelta = 1, + modifyTarget, + driver, + onUpdate, + onComplete, + onStop + }) { + let currentAnimation; + function isOutOfBounds(v) { + return min !== undefined && v < min || max !== undefined && v > max; + } + function boundaryNearest(v) { + if (min === undefined) return max; + if (max === undefined) return min; + return Math.abs(min - v) < Math.abs(max - v) ? min : max; + } + function startAnimation(options) { + currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop(); + currentAnimation = animate(Object.assign(Object.assign({}, options), { + driver, + onUpdate: v => { var _a; - const directives = - ((_a = field.astNode) == null ? void 0 : _a.directives) || []; - if (!directives || directives.length === 0) { - return null; - } - return /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Directives", - children: directives.map((directive) => - /* @__PURE__ */ jsxRuntime.jsx( - "div", - { - children: /* @__PURE__ */ jsxRuntime.jsx(Directive, { - directive, - }), - }, - directive.name.value - ) - ), + onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(v); + (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, v); + }, + onComplete, + onStop + })); + } + function startSpring(options) { + startAnimation(Object.assign({ + type: "spring", + stiffness: bounceStiffness, + damping: bounceDamping, + restDelta + }, options)); + } + if (isOutOfBounds(from)) { + startSpring({ + from, + velocity, + to: boundaryNearest(from) + }); + } else { + let target = power * velocity + from; + if (typeof modifyTarget !== "undefined") target = modifyTarget(target); + const boundary = boundaryNearest(target); + const heading = boundary === min ? -1 : 1; + let prev; + let current; + const checkBoundary = v => { + prev = current; + current = v; + velocity = velocityPerSecond(v - prev, sync.getFrameData().delta); + if (heading === 1 && v > boundary || heading === -1 && v < boundary) { + startSpring({ + from: v, + to: boundary, + velocity }); } - function SchemaDocumentation(props) { - var _a, _b, _c, _d; - const queryType = props.schema.getQueryType(); - const mutationType = - (_b = (_a = props.schema).getMutationType) == null - ? void 0 - : _b.call(_a); - const subscriptionType = - (_d = (_c = props.schema).getSubscriptionType) == null - ? void 0 - : _d.call(_c); - const typeMap = props.schema.getTypeMap(); - const ignoreTypesInAllSchema = [ - queryType == null ? void 0 : queryType.name, - mutationType == null ? void 0 : mutationType.name, - subscriptionType == null ? void 0 : subscriptionType.name, - ]; - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: - props.schema.description || - "A GraphQL schema provides a root type for each kind of operation.", - }), - /* @__PURE__ */ jsxRuntime.jsxs(ExplorerSection, { - title: "Root Types", - children: [ - queryType - ? /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "query", - }), - ": ", - /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: queryType, - }), - ], - }) - : null, - mutationType && - /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "mutation", - }), - ": ", - /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: mutationType, - }), - ], - }), - subscriptionType && - /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "subscription", - }), - ": ", - /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: subscriptionType, - }), - ], - }), - ], - }), - /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "All Schema Types", - children: - typeMap && - /* @__PURE__ */ jsxRuntime.jsx("div", { - children: Object.values(typeMap).map((type) => { - if ( - ignoreTypesInAllSchema.includes(type.name) || - type.name.startsWith("__") - ) { - return null; - } - return /* @__PURE__ */ jsxRuntime.jsx( - "div", - { - children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type, - }), - }, - type.name - ); - }), - }), - }), - ], - }); + }; + startAnimation({ + type: "decay", + from, + velocity, + timeConstant, + power, + restDelta, + modifyTarget, + onUpdate: isOutOfBounds(target) ? checkBoundary : undefined + }); + } + return { + stop: () => currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop() + }; + } + const radiansToDegrees = radians => radians * 180 / Math.PI; + const angle = (a, b = zeroPoint) => radiansToDegrees(Math.atan2(b.y - a.y, b.x - a.x)); + const applyOffset = (from, to) => { + let hasReceivedFrom = true; + if (to === undefined) { + to = from; + hasReceivedFrom = false; + } + return v => { + if (hasReceivedFrom) { + return v - from + to; + } else { + from = v; + hasReceivedFrom = true; + return to; + } + }; + }; + const identity = v => v; + const createAttractor = (alterDisplacement = identity) => (constant, origin, v) => { + const displacement = origin - v; + const springModifiedDisplacement = -(0 - constant + 1) * (0 - alterDisplacement(Math.abs(displacement))); + return displacement <= 0 ? origin + springModifiedDisplacement : origin - springModifiedDisplacement; + }; + const attract = createAttractor(); + const attractExpo = createAttractor(Math.sqrt); + const degreesToRadians = degrees => degrees * Math.PI / 180; + const isPoint = point => point.hasOwnProperty('x') && point.hasOwnProperty('y'); + const isPoint3D = point => isPoint(point) && point.hasOwnProperty('z'); + const distance1D = (a, b) => Math.abs(a - b); + function distance(a, b) { + if (isNum(a) && isNum(b)) { + return distance1D(a, b); + } else if (isPoint(a) && isPoint(b)) { + const xDelta = distance1D(a.x, b.x); + const yDelta = distance1D(a.y, b.y); + const zDelta = isPoint3D(a) && isPoint3D(b) ? distance1D(a.z, b.z) : 0; + return Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2)); + } + } + const pointFromVector = (origin, angle, distance) => { + angle = degreesToRadians(angle); + return { + x: distance * Math.cos(angle) + origin.x, + y: distance * Math.sin(angle) + origin.y + }; + }; + const toDecimal = (num, precision = 2) => { + precision = Math.pow(10, precision); + return Math.round(num * precision) / precision; + }; + const smoothFrame = (prevValue, nextValue, duration, smoothing = 0) => toDecimal(prevValue + duration * (nextValue - prevValue) / Math.max(smoothing, duration)); + const smooth = (strength = 50) => { + let previousValue = 0; + let lastUpdated = 0; + return v => { + const currentFramestamp = sync.getFrameData().timestamp; + const timeDelta = currentFramestamp !== lastUpdated ? currentFramestamp - lastUpdated : 0; + const newValue = timeDelta ? smoothFrame(previousValue, v, timeDelta, strength) : previousValue; + lastUpdated = currentFramestamp; + previousValue = newValue; + return newValue; + }; + }; + const snap = points => { + if (typeof points === 'number') { + return v => Math.round(v / points) * points; + } else { + let i = 0; + const numPoints = points.length; + return v => { + let lastDistance = Math.abs(points[0] - v); + for (i = 1; i < numPoints; i++) { + const point = points[i]; + const distance = Math.abs(point - v); + if (distance === 0) return point; + if (distance > lastDistance) return points[i - 1]; + if (i === numPoints - 1) return point; + lastDistance = distance; + } + }; + } + }; + function velocityPerFrame(xps, frameDuration) { + return xps / (1000 / frameDuration); + } + const wrap = (min, max, v) => { + const rangeSize = max - min; + return ((v - min) % rangeSize + rangeSize) % rangeSize + min; + }; + const a = (a1, a2) => 1.0 - 3.0 * a2 + 3.0 * a1; + const b = (a1, a2) => 3.0 * a2 - 6.0 * a1; + const c = a1 => 3.0 * a1; + const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; + const getSlope = (t, a1, a2) => 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1); + const subdivisionPrecision = 0.0000001; + const subdivisionMaxIterations = 10; + function binarySubdivide(aX, aA, aB, mX1, mX2) { + let currentX; + let currentT; + let i = 0; + do { + currentT = aA + (aB - aA) / 2.0; + currentX = calcBezier(currentT, mX1, mX2) - aX; + if (currentX > 0.0) { + aB = currentT; + } else { + aA = currentT; + } + } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); + return currentT; + } + const newtonIterations = 8; + const newtonMinSlope = 0.001; + function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { + for (let i = 0; i < newtonIterations; ++i) { + const currentSlope = getSlope(aGuessT, mX1, mX2); + if (currentSlope === 0.0) { + return aGuessT; + } + const currentX = calcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; + } + return aGuessT; + } + const kSplineTableSize = 11; + const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); + function cubicBezier(mX1, mY1, mX2, mY2) { + if (mX1 === mY1 && mX2 === mY2) return linear; + const sampleValues = new Float32Array(kSplineTableSize); + for (let i = 0; i < kSplineTableSize; ++i) { + sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); + } + function getTForX(aX) { + let intervalStart = 0.0; + let currentSample = 1; + const lastSample = kSplineTableSize - 1; + for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) { + intervalStart += kSampleStepSize; + } + --currentSample; + const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); + const guessForT = intervalStart + dist * kSampleStepSize; + const initialSlope = getSlope(guessForT, mX1, mX2); + if (initialSlope >= newtonMinSlope) { + return newtonRaphsonIterate(aX, guessForT, mX1, mX2); + } else if (initialSlope === 0.0) { + return guessForT; + } else { + return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); + } + } + return t => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); + } + const steps = (steps, direction = 'end') => progress => { + progress = direction === 'end' ? Math.min(progress, 0.999) : Math.max(progress, 0.001); + const expanded = progress * steps; + const rounded = direction === 'end' ? Math.floor(expanded) : Math.ceil(expanded); + return clamp(0, 1, rounded / steps); + }; + exports.angle = angle; + exports.animate = animate; + exports.anticipate = anticipate; + exports.applyOffset = applyOffset; + exports.attract = attract; + exports.attractExpo = attractExpo; + exports.backIn = backIn; + exports.backInOut = backInOut; + exports.backOut = backOut; + exports.bounceIn = bounceIn; + exports.bounceInOut = bounceInOut; + exports.bounceOut = bounceOut; + exports.circIn = circIn; + exports.circInOut = circInOut; + exports.circOut = circOut; + exports.clamp = clamp; + exports.createAnticipate = createAnticipate; + exports.createAttractor = createAttractor; + exports.createBackIn = createBackIn; + exports.createExpoIn = createExpoIn; + exports.cubicBezier = cubicBezier; + exports.decay = decay; + exports.degreesToRadians = degreesToRadians; + exports.distance = distance; + exports.easeIn = easeIn; + exports.easeInOut = easeInOut; + exports.easeOut = easeOut; + exports.inertia = inertia; + exports.interpolate = interpolate; + exports.isPoint = isPoint; + exports.isPoint3D = isPoint3D; + exports.keyframes = keyframes; + exports.linear = linear; + exports.mirrorEasing = mirrorEasing; + exports.mix = mix; + exports.mixColor = mixColor; + exports.mixComplex = mixComplex; + exports.pipe = pipe; + exports.pointFromVector = pointFromVector; + exports.progress = progress; + exports.radiansToDegrees = radiansToDegrees; + exports.reverseEasing = reverseEasing; + exports.smooth = smooth; + exports.smoothFrame = smoothFrame; + exports.snap = snap; + exports.spring = spring; + exports.steps = steps; + exports.toDecimal = toDecimal; + exports.velocityPerFrame = velocityPerFrame; + exports.velocityPerSecond = velocityPerSecond; + exports.wrap = wrap; + + /***/ }), + + /***/ "../../../node_modules/punycode.js/punycode.es6.js": + /*!*********************************************************!*\ + !*** ../../../node_modules/punycode.js/punycode.es6.js ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + /** Highest positive signed 32-bit float value */ + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.toUnicode = exports.toASCII = exports.encode = exports["default"] = exports.decode = void 0; + exports.ucs2decode = ucs2decode; + exports.ucs2encode = void 0; + const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + const base = 36; + const tMin = 1; + const tMax = 26; + const skew = 38; + const damp = 700; + const initialBias = 72; + const initialN = 128; // 0x80 + const delimiter = '-'; // '\x2D' + + /** Regular expressions */ + const regexPunycode = /^xn--/; + const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. + const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }; + + /** Convenience shortcuts */ + const baseMinusTMin = base - tMin; + const floor = Math.floor; + const stringFromCharCode = String.fromCharCode; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ + function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + exports.ucs2encode = ucs2encode; + const basicToDigit = function (codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; + }; + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + const digitToBasic = function (digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + }; + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + const adapt = function (delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for /* no initialization */ + (; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + }; + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + const decode = function (input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for /* no final expression */ + (let index = basic > 0 ? basic + 1 : 0; index < inputLength;) { + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for /* no condition */ + (let w = 1, k = base;; k += base) { + if (index >= inputLength) { + error('invalid-input'); + } + const digit = basicToDigit(input.charCodeAt(index++)); + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); + } + i += digit * w; + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (digit < t) { + break; + } + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + w *= baseMinusT; + } + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + return String.fromCodePoint(...output); + }; + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + exports.decode = decode; + const encode = function (input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; } - function debounce(duration, fn) { - let timeout; - return function (...args) { - if (timeout) { - window.clearTimeout(timeout); + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for /* no condition */ + (let k = base;; k += base) { + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; } - timeout = window.setTimeout(() => { - timeout = null; - fn(...args); - }, duration); - }; + const qMinusT = q - t; + const baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; } - function Search() { - const { explorerNavStack, push } = useExplorerContext({ - nonNull: true, - caller: Search, + } + ++delta; + ++n; + } + return output.join(''); + }; + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + exports.encode = encode; + const toUnicode = function (input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); + }; + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + exports.toUnicode = toUnicode; + const toASCII = function (input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); + }; + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + exports.toASCII = toASCII; + const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.3.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + var _default = exports["default"] = punycode; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.RemoveScrollBar = void 0; + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); + var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); + var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + var Style = (0, _reactStyleSingleton.styleSingleton)(); + // important tip - once we measure scrollBar width and remove them + // we could not repeat this operation + // thus we are using style-singleton - only the first "yet correct" style will be applied. + var getStyles = function (_a, allowRelative, gapMode, important) { + var left = _a.left, + top = _a.top, + right = _a.right, + gap = _a.gap; + if (gapMode === void 0) { + gapMode = 'margin'; + } + return "\n .".concat(_constants.noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([allowRelative && "position: relative ".concat(important, ";"), gapMode === 'margin' && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), gapMode === 'padding' && "padding-right: ".concat(gap, "px ").concat(important, ";")].filter(Boolean).join(''), "\n }\n \n .").concat(_constants.zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.zeroRightClassName, " .").concat(_constants.zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " .").concat(_constants.fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body {\n ").concat(_constants.removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); + }; + /** + * Removes page scrollbar and blocks page scroll when mounted + */ + var RemoveScrollBar = function (props) { + var noRelative = props.noRelative, + noImportant = props.noImportant, + _a = props.gapMode, + gapMode = _a === void 0 ? 'margin' : _a; + var gap = React.useMemo(function () { + return (0, _utils.getGapWidth)(gapMode); + }, [gapMode]); + return /*#__PURE__*/React.createElement(Style, { + styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') + }); + }; + exports.RemoveScrollBar = RemoveScrollBar; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js": + /*!******************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js ***! + \******************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.zeroRightClassName = exports.removedBarSizeVariable = exports.noScrollbarsClassName = exports.fullWidthClassName = void 0; + var zeroRightClassName = exports.zeroRightClassName = 'right-scroll-bar-position'; + var fullWidthClassName = exports.fullWidthClassName = 'width-before-scroll-bar'; + var noScrollbarsClassName = exports.noScrollbarsClassName = 'with-scroll-bars-hidden'; + /** + * Name of a CSS variable containing the amount of "hidden" scrollbar + * ! might be undefined ! use will fallback! + */ + var removedBarSizeVariable = exports.removedBarSizeVariable = '--removed-body-scroll-bar-size'; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "RemoveScrollBar", ({ + enumerable: true, + get: function () { + return _component.RemoveScrollBar; + } + })); + Object.defineProperty(exports, "fullWidthClassName", ({ + enumerable: true, + get: function () { + return _constants.fullWidthClassName; + } + })); + Object.defineProperty(exports, "getGapWidth", ({ + enumerable: true, + get: function () { + return _utils.getGapWidth; + } + })); + Object.defineProperty(exports, "noScrollbarsClassName", ({ + enumerable: true, + get: function () { + return _constants.noScrollbarsClassName; + } + })); + Object.defineProperty(exports, "removedBarSizeVariable", ({ + enumerable: true, + get: function () { + return _constants.removedBarSizeVariable; + } + })); + Object.defineProperty(exports, "zeroRightClassName", ({ + enumerable: true, + get: function () { + return _constants.zeroRightClassName; + } + })); + var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js"); + var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); + var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.zeroGap = exports.getGapWidth = void 0; + var zeroGap = exports.zeroGap = { + left: 0, + top: 0, + right: 0, + gap: 0 + }; + var parse = function (x) { + return parseInt(x || '', 10) || 0; + }; + var getOffset = function (gapMode) { + var cs = window.getComputedStyle(document.body); + if (true) { + if (cs.overflowY === 'hidden') { + console.error('react-remove-scroll-bar: cannot calculate scrollbar size because it is removed (overflow:hidden on body'); + } + } + var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft']; + var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop']; + var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight']; + return [parse(left), parse(top), parse(right)]; + }; + var getGapWidth = function (gapMode) { + if (gapMode === void 0) { + gapMode = 'margin'; + } + if (typeof window === 'undefined') { + return zeroGap; + } + var offsets = getOffset(gapMode); + var documentWidth = document.documentElement.clientWidth; + var windowWidth = window.innerWidth; + return { + left: offsets[0], + top: offsets[1], + right: offsets[2], + gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) + }; + }; + exports.getGapWidth = getGapWidth; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/Combination.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = void 0; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _UI = __webpack_require__(/*! ./UI */ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js"); + var _sidecar = _interopRequireDefault(__webpack_require__(/*! ./sidecar */ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js")); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + var ReactRemoveScroll = /*#__PURE__*/React.forwardRef(function (props, ref) { + return /*#__PURE__*/React.createElement(_UI.RemoveScroll, (0, _tslib.__assign)({}, props, { + ref: ref, + sideCar: _sidecar.default + })); + }); + ReactRemoveScroll.classNames = _UI.RemoveScroll.classNames; + var _default = exports["default"] = ReactRemoveScroll; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.RemoveScrollSideCar = RemoveScrollSideCar; + exports.getTouchXY = exports.getDeltaXY = void 0; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _reactRemoveScrollBar = __webpack_require__(/*! react-remove-scroll-bar */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js"); + var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); + var _aggresiveCapture = __webpack_require__(/*! ./aggresiveCapture */ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js"); + var _handleScroll = __webpack_require__(/*! ./handleScroll */ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js"); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + var getTouchXY = function (event) { + return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; + }; + exports.getTouchXY = getTouchXY; + var getDeltaXY = function (event) { + return [event.deltaX, event.deltaY]; + }; + exports.getDeltaXY = getDeltaXY; + var extractRef = function (ref) { + return ref && 'current' in ref ? ref.current : ref; + }; + var deltaCompare = function (x, y) { + return x[0] === y[0] && x[1] === y[1]; + }; + var generateStyle = function (id) { + return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); + }; + var idCounter = 0; + var lockStack = []; + function RemoveScrollSideCar(props) { + var shouldPreventQueue = React.useRef([]); + var touchStartRef = React.useRef([0, 0]); + var activeAxis = React.useRef(); + var id = React.useState(idCounter++)[0]; + var Style = React.useState(function () { + return (0, _reactStyleSingleton.styleSingleton)(); + })[0]; + var lastProps = React.useRef(props); + React.useEffect(function () { + lastProps.current = props; + }, [props]); + React.useEffect(function () { + if (props.inert) { + document.body.classList.add("block-interactivity-".concat(id)); + var allow_1 = (0, _tslib.__spreadArray)([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); + allow_1.forEach(function (el) { + return el.classList.add("allow-interactivity-".concat(id)); + }); + return function () { + document.body.classList.remove("block-interactivity-".concat(id)); + allow_1.forEach(function (el) { + return el.classList.remove("allow-interactivity-".concat(id)); }); - const inputRef = React.useRef(null); - const getSearchResults = useSearchResults(); - const [searchValue, setSearchValue] = React.useState(""); - const [results, setResults] = React.useState( - getSearchResults(searchValue) - ); - const debouncedGetSearchResults = React.useMemo( - () => - debounce(200, (search) => { - setResults(getSearchResults(search)); - }), - [getSearchResults] - ); - React.useEffect(() => { - debouncedGetSearchResults(searchValue); - }, [debouncedGetSearchResults, searchValue]); - React.useEffect(() => { - function handleKeyDown(event) { - var _a; - if (event.metaKey && event.key === "k") { - (_a = inputRef.current) == null ? void 0 : _a.focus(); - } - } - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, []); - const navItem = explorerNavStack.at(-1); - const onSelect = React.useCallback( - (def) => { - push( - "field" in def - ? { - name: def.field.name, - def: def.field, - } - : { - name: def.type.name, - def: def.type, - } - ); - }, - [push] - ); - const isFocused = React.useRef(false); - const handleFocus = React.useCallback((e) => { - isFocused.current = e.type === "focus"; - }, []); - const shouldSearchBoxAppear = - explorerNavStack.length === 1 || - graphql.isObjectType(navItem.def) || - graphql.isInterfaceType(navItem.def) || - graphql.isInputObjectType(navItem.def); - if (!shouldSearchBoxAppear) { - return null; + }; + } + return; + }, [props.inert, props.lockRef.current, props.shards]); + var shouldCancelEvent = React.useCallback(function (event, parent) { + if ('touches' in event && event.touches.length === 2) { + return !lastProps.current.allowPinchZoom; + } + var touch = getTouchXY(event); + var touchStart = touchStartRef.current; + var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0]; + var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1]; + var currentAxis; + var target = event.target; + var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v'; + // allow horizontal touch move on Range inputs. They will not cause any scroll + if ('touches' in event && moveDirection === 'h' && target.type === 'range') { + return false; + } + var canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); + if (!canBeScrolledInMainDirection) { + return true; + } + if (canBeScrolledInMainDirection) { + currentAxis = moveDirection; + } else { + currentAxis = moveDirection === 'v' ? 'h' : 'v'; + canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); + // other axis might be not scrollable + } + if (!canBeScrolledInMainDirection) { + return false; + } + if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) { + activeAxis.current = currentAxis; + } + if (!currentAxis) { + return true; + } + var cancelingAxis = activeAxis.current || currentAxis; + return (0, _handleScroll.handleScroll)(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true); + }, []); + var shouldPrevent = React.useCallback(function (_event) { + var event = _event; + if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) { + // not the last active + return; + } + var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event); + var sourceEvent = shouldPreventQueue.current.filter(function (e) { + return e.name === event.type && e.target === event.target && deltaCompare(e.delta, delta); + })[0]; + // self event, and should be canceled + if (sourceEvent && sourceEvent.should) { + if (event.cancelable) { + event.preventDefault(); + } + return; + } + // outside or shard event + if (!sourceEvent) { + var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function (node) { + return node.contains(event.target); + }); + var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; + if (shouldStop) { + if (event.cancelable) { + event.preventDefault(); } - return /* @__PURE__ */ jsxRuntime.jsxs(react.Combobox, { - as: "div", - className: "graphiql-doc-explorer-search", - onChange: onSelect, - "data-state": isFocused ? void 0 : "idle", - "aria-label": `Search ${navItem.name}...`, - children: [ - /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-search-input", - onClick: () => { - var _a; - (_a = inputRef.current) == null ? void 0 : _a.focus(); - }, - children: [ - /* @__PURE__ */ jsxRuntime.jsx(MagnifyingGlassIcon, {}), - /* @__PURE__ */ jsxRuntime.jsx(react.Combobox.Input, { - autoComplete: "off", - onFocus: handleFocus, - onBlur: handleFocus, - onChange: (event) => setSearchValue(event.target.value), - placeholder: "⌘ K", - ref: inputRef, - value: searchValue, - "data-cy": "doc-explorer-input", - }), - ], - }), - isFocused.current && - /* @__PURE__ */ jsxRuntime.jsxs(react.Combobox.Options, { - "data-cy": "doc-explorer-list", - children: [ - results.within.length + - results.types.length + - results.fields.length === - 0 - ? /* @__PURE__ */ jsxRuntime.jsx("li", { - className: "graphiql-doc-explorer-search-empty", - children: "No results found", - }) - : results.within.map((result, i) => - /* @__PURE__ */ jsxRuntime.jsx( - react.Combobox.Option, - { - value: result, - "data-cy": "doc-explorer-option", - children: /* @__PURE__ */ jsxRuntime.jsx( - Field$1, - { - field: result.field, - argument: result.argument, - } - ), - }, - `within-${i}` - ) - ), - results.within.length > 0 && - results.types.length + results.fields.length > 0 - ? /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-search-divider", - children: "Other results", - }) - : null, - results.types.map((result, i) => - /* @__PURE__ */ jsxRuntime.jsx( - react.Combobox.Option, - { - value: result, - "data-cy": "doc-explorer-option", - children: /* @__PURE__ */ jsxRuntime.jsx(Type, { - type: result.type, - }), - }, - `type-${i}` - ) - ), - results.fields.map((result, i) => - /* @__PURE__ */ jsxRuntime.jsxs( - react.Combobox.Option, - { - value: result, - "data-cy": "doc-explorer-option", - children: [ - /* @__PURE__ */ jsxRuntime.jsx(Type, { - type: result.type, - }), - ".", - /* @__PURE__ */ jsxRuntime.jsx(Field$1, { - field: result.field, - argument: result.argument, - }), - ], - }, - `field-${i}` - ) - ), - ], - }), - ], - }); } - function useSearchResults(caller) { - const { explorerNavStack } = useExplorerContext({ - nonNull: true, - caller: caller || useSearchResults, - }); - const { schema } = useSchemaContext({ - nonNull: true, - caller: caller || useSearchResults, - }); - const navItem = explorerNavStack.at(-1); - return React.useCallback( - (searchValue) => { - const matches = { - within: [], - types: [], - fields: [], - }; - if (!schema) { - return matches; - } - const withinType = navItem.def; - const typeMap = schema.getTypeMap(); - let typeNames = Object.keys(typeMap); - if (withinType) { - typeNames = typeNames.filter((n) => n !== withinType.name); - typeNames.unshift(withinType.name); - } - for (const typeName of typeNames) { - if ( - matches.within.length + - matches.types.length + - matches.fields.length >= - 100 - ) { - break; - } - const type = typeMap[typeName]; - if (withinType !== type && isMatch(typeName, searchValue)) { - matches.types.push({ - type, - }); - } - if ( - !graphql.isObjectType(type) && - !graphql.isInterfaceType(type) && - !graphql.isInputObjectType(type) - ) { - continue; - } - const fields = type.getFields(); - for (const fieldName in fields) { - const field = fields[fieldName]; - let matchingArgs; - if (!isMatch(fieldName, searchValue)) { - if ("args" in field) { - matchingArgs = field.args.filter((arg) => - isMatch(arg.name, searchValue) - ); - if (matchingArgs.length === 0) { - continue; - } - } else { - continue; - } - } - matches[withinType === type ? "within" : "fields"].push( - ...(matchingArgs - ? matchingArgs.map((argument) => ({ - type, - field, - argument, - })) - : [ - { - type, - field, - }, - ]) - ); - } - } - return matches; - }, - [navItem.def, schema] - ); + } + }, []); + var shouldCancel = React.useCallback(function (name, delta, target, should) { + var event = { + name: name, + delta: delta, + target: target, + should: should + }; + shouldPreventQueue.current.push(event); + setTimeout(function () { + shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { + return e !== event; + }); + }, 1); + }, []); + var scrollTouchStart = React.useCallback(function (event) { + touchStartRef.current = getTouchXY(event); + activeAxis.current = undefined; + }, []); + var scrollWheel = React.useCallback(function (event) { + shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); + }, []); + var scrollTouchMove = React.useCallback(function (event) { + shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); + }, []); + React.useEffect(function () { + lockStack.push(Style); + props.setCallbacks({ + onScrollCapture: scrollWheel, + onWheelCapture: scrollWheel, + onTouchMoveCapture: scrollTouchMove + }); + document.addEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); + document.addEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); + document.addEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); + return function () { + lockStack = lockStack.filter(function (inst) { + return inst !== Style; + }); + document.removeEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); + document.removeEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); + document.removeEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); + }; + }, []); + var removeScrollBar = props.removeScrollBar, + inert = props.inert; + return /*#__PURE__*/React.createElement(React.Fragment, null, inert ? /*#__PURE__*/React.createElement(Style, { + styles: generateStyle(id) + }) : null, removeScrollBar ? /*#__PURE__*/React.createElement(_reactRemoveScrollBar.RemoveScrollBar, { + gapMode: "margin" + }) : null); + } + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/UI.js ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.RemoveScroll = void 0; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _constants = __webpack_require__(/*! react-remove-scroll-bar/constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); + var _useCallbackRef = __webpack_require__(/*! use-callback-ref */ "../../../node_modules/use-callback-ref/dist/es2015/index.js"); + var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + var nothing = function () { + return; + }; + /** + * Removes scrollbar from the page and contain the scroll within the Lock + */ + var RemoveScroll = exports.RemoveScroll = /*#__PURE__*/React.forwardRef(function (props, parentRef) { + var ref = React.useRef(null); + var _a = React.useState({ + onScrollCapture: nothing, + onWheelCapture: nothing, + onTouchMoveCapture: nothing + }), + callbacks = _a[0], + setCallbacks = _a[1]; + var forwardProps = props.forwardProps, + children = props.children, + className = props.className, + removeScrollBar = props.removeScrollBar, + enabled = props.enabled, + shards = props.shards, + sideCar = props.sideCar, + noIsolation = props.noIsolation, + inert = props.inert, + allowPinchZoom = props.allowPinchZoom, + _b = props.as, + Container = _b === void 0 ? 'div' : _b, + rest = (0, _tslib.__rest)(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]); + var SideCar = sideCar; + var containerRef = (0, _useCallbackRef.useMergeRefs)([ref, parentRef]); + var containerProps = (0, _tslib.__assign)((0, _tslib.__assign)({}, rest), callbacks); + return /*#__PURE__*/React.createElement(React.Fragment, null, enabled && ( /*#__PURE__*/React.createElement(SideCar, { + sideCar: _medium.effectCar, + removeScrollBar: removeScrollBar, + shards: shards, + noIsolation: noIsolation, + inert: inert, + setCallbacks: setCallbacks, + allowPinchZoom: !!allowPinchZoom, + lockRef: ref + })), forwardProps ? ( /*#__PURE__*/React.cloneElement(React.Children.only(children), (0, _tslib.__assign)((0, _tslib.__assign)({}, containerProps), { + ref: containerRef + }))) : ( /*#__PURE__*/React.createElement(Container, (0, _tslib.__assign)({}, containerProps, { + className: className, + ref: containerRef + }), children))); + }); + RemoveScroll.defaultProps = { + enabled: true, + removeScrollBar: true, + inert: false + }; + RemoveScroll.classNames = { + fullWidth: _constants.fullWidthClassName, + zeroRight: _constants.zeroRightClassName + }; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js": + /*!*********************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js ***! + \*********************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.nonPassive = void 0; + var passiveSupported = false; + if (typeof window !== 'undefined') { + try { + var options = Object.defineProperty({}, 'passive', { + get: function () { + passiveSupported = true; + return true; } - function isMatch(sourceText, searchValue) { - try { - const escaped = searchValue.replaceAll( - /[^_0-9A-Za-z]/g, - (ch) => "\\" + ch - ); - return sourceText.search(new RegExp(escaped, "i")) !== -1; - } catch { - return sourceText.toLowerCase().includes(searchValue.toLowerCase()); - } + }); + // @ts-ignore + window.addEventListener('test', options, options); + // @ts-ignore + window.removeEventListener('test', options, options); + } catch (err) { + passiveSupported = false; + } + } + var nonPassive = exports.nonPassive = passiveSupported ? { + passive: false + } : false; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.locationCouldBeScrolled = exports.handleScroll = void 0; + var alwaysContainsScroll = function (node) { + // textarea will always _contain_ scroll inside self. It only can be hidden + return node.tagName === 'TEXTAREA'; + }; + var elementCanBeScrolled = function (node, overflow) { + var styles = window.getComputedStyle(node); + return ( + // not-not-scrollable + styles[overflow] !== 'hidden' && + // contains scroll inside self + !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible') + ); + }; + var elementCouldBeVScrolled = function (node) { + return elementCanBeScrolled(node, 'overflowY'); + }; + var elementCouldBeHScrolled = function (node) { + return elementCanBeScrolled(node, 'overflowX'); + }; + var locationCouldBeScrolled = function (axis, node) { + var current = node; + do { + // Skip over shadow root + if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) { + current = current.host; + } + var isScrollable = elementCouldBeScrolled(axis, current); + if (isScrollable) { + var _a = getScrollVariables(axis, current), + s = _a[1], + d = _a[2]; + if (s > d) { + return true; } - function Type(props) { - return /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-type", - children: props.type.name, - }); + } + current = current.parentNode; + } while (current && current !== document.body); + return false; + }; + exports.locationCouldBeScrolled = locationCouldBeScrolled; + var getVScrollVariables = function (_a) { + var scrollTop = _a.scrollTop, + scrollHeight = _a.scrollHeight, + clientHeight = _a.clientHeight; + return [scrollTop, scrollHeight, clientHeight]; + }; + var getHScrollVariables = function (_a) { + var scrollLeft = _a.scrollLeft, + scrollWidth = _a.scrollWidth, + clientWidth = _a.clientWidth; + return [scrollLeft, scrollWidth, clientWidth]; + }; + var elementCouldBeScrolled = function (axis, node) { + return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); + }; + var getScrollVariables = function (axis, node) { + return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node); + }; + var getDirectionFactor = function (axis, direction) { + /** + * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position, + * and then increasingly negative as you scroll towards the end of the content. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft + */ + return axis === 'h' && direction === 'rtl' ? -1 : 1; + }; + var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) { + var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); + var delta = directionFactor * sourceDelta; + // find scrollable target + var target = event.target; + var targetInLock = endTarget.contains(target); + var shouldCancelScroll = false; + var isDeltaPositive = delta > 0; + var availableScroll = 0; + var availableScrollTop = 0; + do { + var _a = getScrollVariables(axis, target), + position = _a[0], + scroll_1 = _a[1], + capacity = _a[2]; + var elementScroll = scroll_1 - capacity - directionFactor * position; + if (position || elementScroll) { + if (elementCouldBeScrolled(axis, target)) { + availableScroll += elementScroll; + availableScrollTop += position; } - function Field$1({ field, argument }) { - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-field", - children: field.name, - }), - argument - ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - "(", - /* @__PURE__ */ jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-argument", - children: argument.name, - }), - ":", - " ", - renderType(argument.type, (namedType) => - /* @__PURE__ */ jsxRuntime.jsx(Type, { - type: namedType, - }) - ), - ")", - ], - }) - : null, - ], - }); + } + target = target.parentNode; + } while ( + // portaled content + !targetInLock && target !== document.body || + // self content + targetInLock && (endTarget.contains(target) || endTarget === target)); + if (isDeltaPositive && (noOverscroll && availableScroll === 0 || !noOverscroll && delta > availableScroll)) { + shouldCancelScroll = true; + } else if (!isDeltaPositive && (noOverscroll && availableScrollTop === 0 || !noOverscroll && -delta > availableScrollTop)) { + shouldCancelScroll = true; + } + return shouldCancelScroll; + }; + exports.handleScroll = handleScroll; + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/index.js": + /*!**********************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/index.js ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "RemoveScroll", ({ + enumerable: true, + get: function () { + return _Combination.default; + } + })); + var _Combination = _interopRequireDefault(__webpack_require__(/*! ./Combination */ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js")); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/medium.js ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.effectCar = void 0; + var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); + var effectCar = exports.effectCar = (0, _useSidecar.createSidecarMedium)(); + + /***/ }), + + /***/ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = void 0; + var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); + var _SideEffect = __webpack_require__(/*! ./SideEffect */ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js"); + var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); + var _default = exports["default"] = (0, _useSidecar.exportSidecar)(_medium.effectCar, _SideEffect.RemoveScrollSideCar); + + /***/ }), + + /***/ "../../../node_modules/react-style-singleton/dist/es2015/component.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/component.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.styleSingleton = void 0; + var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); + /** + * create a Component to add styles on demand + * - styles are added when first instance is mounted + * - styles are removed when the last instance is unmounted + * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior + */ + var styleSingleton = function () { + var useStyle = (0, _hook.styleHookSingleton)(); + var Sheet = function (_a) { + var styles = _a.styles, + dynamic = _a.dynamic; + useStyle(styles, dynamic); + return null; + }; + return Sheet; + }; + exports.styleSingleton = styleSingleton; + + /***/ }), + + /***/ "../../../node_modules/react-style-singleton/dist/es2015/hook.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/hook.js ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.styleHookSingleton = void 0; + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + /** + * creates a hook to control style singleton + * @see {@link styleSingleton} for a safer component version + * @example + * ```tsx + * const useStyle = styleHookSingleton(); + * /// + * useStyle('body { overflow: hidden}'); + */ + var styleHookSingleton = function () { + var sheet = (0, _singleton.stylesheetSingleton)(); + return function (styles, isDynamic) { + React.useEffect(function () { + sheet.add(styles); + return function () { + sheet.remove(); + }; + }, [styles && isDynamic]); + }; + }; + exports.styleHookSingleton = styleHookSingleton; + + /***/ }), + + /***/ "../../../node_modules/react-style-singleton/dist/es2015/index.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/index.js ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "styleHookSingleton", ({ + enumerable: true, + get: function () { + return _hook.styleHookSingleton; + } + })); + Object.defineProperty(exports, "styleSingleton", ({ + enumerable: true, + get: function () { + return _component.styleSingleton; + } + })); + Object.defineProperty(exports, "stylesheetSingleton", ({ + enumerable: true, + get: function () { + return _singleton.stylesheetSingleton; + } + })); + var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-style-singleton/dist/es2015/component.js"); + var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); + var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); + + /***/ }), + + /***/ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js": + /*!****************************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/singleton.js ***! + \****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.stylesheetSingleton = void 0; + var _getNonce = __webpack_require__(/*! get-nonce */ "../../../node_modules/get-nonce/dist/es2015/index.js"); + function makeStyleTag() { + if (!document) return null; + var tag = document.createElement('style'); + tag.type = 'text/css'; + var nonce = (0, _getNonce.getNonce)(); + if (nonce) { + tag.setAttribute('nonce', nonce); + } + return tag; + } + function injectStyles(tag, css) { + // @ts-ignore + if (tag.styleSheet) { + // @ts-ignore + tag.styleSheet.cssText = css; + } else { + tag.appendChild(document.createTextNode(css)); + } + } + function insertStyleTag(tag) { + var head = document.head || document.getElementsByTagName('head')[0]; + head.appendChild(tag); + } + var stylesheetSingleton = function () { + var counter = 0; + var stylesheet = null; + return { + add: function (style) { + if (counter == 0) { + if (stylesheet = makeStyleTag()) { + injectStyles(stylesheet, style); + insertStyleTag(stylesheet); + } + } + counter++; + }, + remove: function () { + counter--; + if (!counter && stylesheet) { + stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); + stylesheet = null; } - function FieldLink(props) { - const { push } = useExplorerContext({ - nonNull: true, - }); - return /* @__PURE__ */ jsxRuntime.jsx("a", { - className: "graphiql-doc-explorer-field-name", - onClick: (event) => { - event.preventDefault(); - push({ - name: props.field.name, - def: props.field, - }); - }, - href: "#", - children: props.field.name, - }); + } + }; + }; + exports.stylesheetSingleton = stylesheetSingleton; + + /***/ }), + + /***/ "../../../node_modules/react/cjs/react-jsx-runtime.development.js": + /*!************************************************************************!*\ + !*** ../../../node_modules/react/cjs/react-jsx-runtime.development.js ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + /** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + + if (true) { + (function () { + 'use strict'; + + var React = __webpack_require__(/*! react */ "react"); + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; } - function TypeDocumentation(props) { - return graphql.isNamedType(props.type) - ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - props.type.description - ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.type.description, - }) - : null, - /* @__PURE__ */ jsxRuntime.jsx(ImplementsInterfaces, { - type: props.type, - }), - /* @__PURE__ */ jsxRuntime.jsx(Fields, { - type: props.type, - }), - /* @__PURE__ */ jsxRuntime.jsx(EnumValues, { - type: props.type, - }), - /* @__PURE__ */ jsxRuntime.jsx(PossibleTypes, { - type: props.type, - }), - ], - }) - : null; + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === 'function') { + return maybeIterator; } - function ImplementsInterfaces({ type }) { - if (!graphql.isObjectType(type)) { - return null; - } - const interfaces = type.getInterfaces(); - return interfaces.length > 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Implements", - children: type.getInterfaces().map((implementedInterface) => - /* @__PURE__ */ jsxRuntime.jsx( - "div", - { - children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: implementedInterface, - }), - }, - implementedInterface.name - ) - ), - }) - : null; - } - function Fields({ type }) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if ( - !graphql.isObjectType(type) && - !graphql.isInterfaceType(type) && - !graphql.isInputObjectType(type) - ) { - return null; + return null; + } + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning('error', format, args); } - const fieldMap = type.getFields(); - const fields = []; - const deprecatedFields = []; - for (const field of Object.keys(fieldMap).map( - (name) => fieldMap[name] - )) { - if (field.deprecationReason) { - deprecatedFields.push(field); - } else { - fields.push(field); - } - } - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - fields.length > 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Fields", - children: fields.map((field) => - /* @__PURE__ */ jsxRuntime.jsx( - Field, - { - field, - }, - field.name - ) - ), - }) - : null, - deprecatedFields.length > 0 - ? showDeprecated || fields.length === 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Fields", - children: deprecatedFields.map((field) => - /* @__PURE__ */ jsxRuntime.jsx( - Field, - { - field, - }, - field.name - ) - ), - }) - : /* @__PURE__ */ jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Fields", - }) - : null, - ], - }); } - function Field({ field }) { - const args = - "args" in field - ? field.args.filter((arg) => !arg.deprecationReason) - : []; - return /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-item", - children: [ - /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - /* @__PURE__ */ jsxRuntime.jsx(FieldLink, { - field, - }), - args.length > 0 - ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - "(", - /* @__PURE__ */ jsxRuntime.jsx("span", { - children: args.map((arg) => - args.length === 1 - ? /* @__PURE__ */ jsxRuntime.jsx( - Argument, - { - arg, - inline: true, - }, - arg.name - ) - : /* @__PURE__ */ jsxRuntime.jsx( - "div", - { - className: - "graphiql-doc-explorer-argument-multiple", - children: /* @__PURE__ */ jsxRuntime.jsx( - Argument, - { - arg, - inline: true, - } - ), - }, - arg.name - ) - ), - }), - ")", - ], - }) - : null, - ": ", - /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: field.type, - }), - /* @__PURE__ */ jsxRuntime.jsx(DefaultValue, { - field, - }), - ], - }), - field.description - ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "description", - onlyShowFirstChild: true, - children: field.description, - }) - : null, - /* @__PURE__ */ jsxRuntime.jsx(DeprecationReason, { - children: field.deprecationReason, - }), - ], - }); - } - function EnumValues({ type }) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!graphql.isEnumType(type)) { - return null; - } - const values = []; - const deprecatedValues = []; - for (const value of type.getValues()) { - if (value.deprecationReason) { - deprecatedValues.push(value); - } else { - values.push(value); - } - } - return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - values.length > 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Enum Values", - children: values.map((value) => - /* @__PURE__ */ jsxRuntime.jsx( - EnumValue, - { - value, - }, - value.name - ) - ), - }) - : null, - deprecatedValues.length > 0 - ? showDeprecated || values.length === 0 - ? /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Enum Values", - children: deprecatedValues.map((value) => - /* @__PURE__ */ jsxRuntime.jsx( - EnumValue, - { - value, - }, - value.name - ) - ), - }) - : /* @__PURE__ */ jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Values", - }) - : null, - ], - }); + } + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); } - function EnumValue({ value }) { - return /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-item", - children: [ - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-enum-value", - children: value.name, - }), - value.description - ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: value.description, - }) - : null, - value.deprecationReason - ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - children: value.deprecationReason, - }) - : null, - ], - }); + } + + // ----------------------------------------------------------------------------- + + var enableScopeAPI = false; // Experimental Create Event Handle API. + var enableCacheElement = false; + var enableTransitionTracing = false; // No known bugs, but needs performance testing + + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + // stuff. Intended to enable React core members to more easily debug scheduling + // issues in DEV builds. + + var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); + } + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; } - function PossibleTypes({ type }) { - const { schema } = useSchemaContext({ - nonNull: true, - }); - if (!schema || !graphql.isAbstractType(type)) { - return null; + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || + // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; } - return /* @__PURE__ */ jsxRuntime.jsx(ExplorerSection, { - title: graphql.isInterfaceType(type) - ? "Implementations" - : "Possible Types", - children: schema.getPossibleTypes(type).map((possibleType) => - /* @__PURE__ */ jsxRuntime.jsx( - "div", - { - children: /* @__PURE__ */ jsxRuntime.jsx(TypeLink, { - type: possibleType, - }), - }, - possibleType.name - ) - ), - }); } - function DocExplorer() { - const { fetchError, isFetching, schema, validationErrors } = - useSchemaContext({ - nonNull: true, - caller: DocExplorer, - }); - const { explorerNavStack, pop } = useExplorerContext({ - nonNull: true, - caller: DocExplorer, - }); - const navItem = explorerNavStack.at(-1); - let content = null; - if (fetchError) { - content = /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-error", - children: "Error fetching schema", - }); - } else if (validationErrors.length > 0) { - content = /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-error", - children: ["Schema is invalid: ", validationErrors[0].message], - }); - } else if (isFetching) { - content = /* @__PURE__ */ jsxRuntime.jsx(Spinner, {}); - } else if (!schema) { - content = /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-error", - children: "No GraphQL schema available", - }); - } else if (explorerNavStack.length === 1) { - content = /* @__PURE__ */ jsxRuntime.jsx(SchemaDocumentation, { - schema, - }); - } else if (graphql.isType(navItem.def)) { - content = /* @__PURE__ */ jsxRuntime.jsx(TypeDocumentation, { - type: navItem.def, - }); - } else if (navItem.def) { - content = /* @__PURE__ */ jsxRuntime.jsx(FieldDocumentation, { - field: navItem.def, - }); + return false; + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber + + function getContextName(type) { + return type.displayName || 'Context'; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } - let prevName; - if (explorerNavStack.length > 1) { - prevName = explorerNavStack.at(-2).name; - } - return /* @__PURE__ */ jsxRuntime.jsxs("section", { - className: "graphiql-doc-explorer", - "aria-label": "Documentation Explorer", - children: [ - /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-header", - children: [ - /* @__PURE__ */ jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-header-content", - children: [ - prevName && - /* @__PURE__ */ jsxRuntime.jsxs("a", { - href: "#", - className: "graphiql-doc-explorer-back", - onClick: (event) => { - event.preventDefault(); - pop(); - }, - "aria-label": `Go back to ${prevName}`, - children: [ - /* @__PURE__ */ jsxRuntime.jsx(ChevronLeftIcon, {}), - prevName, - ], - }), - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-title", - children: navItem.name, - }), - ], - }), - /* @__PURE__ */ jsxRuntime.jsx(Search, {}, navItem.name), - ], - }), - /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-content", - children: content, - }), - ], - }); } - const DOC_EXPLORER_PLUGIN = { - title: "Documentation Explorer", - icon: function Icon() { - const pluginContext = usePluginContext(); - return (pluginContext == null - ? void 0 - : pluginContext.visiblePlugin) === DOC_EXPLORER_PLUGIN - ? /* @__PURE__ */ jsxRuntime.jsx(DocsFilledIcon, {}) - : /* @__PURE__ */ jsxRuntime.jsx(DocsIcon, {}); - }, - content: DocExplorer, - }; - const HISTORY_PLUGIN = { - title: "History", - icon: HistoryIcon, - content: History, - }; - const PluginContext = createNullableContext("PluginContext"); - function PluginContextProvider(props) { - const storage = useStorageContext(); - const explorerContext = useExplorerContext(); - const historyContext = useHistoryContext(); - const hasExplorerContext = Boolean(explorerContext); - const hasHistoryContext = Boolean(historyContext); - const plugins = React.useMemo(() => { - const pluginList = []; - const pluginTitles = {}; - if (hasExplorerContext) { - pluginList.push(DOC_EXPLORER_PLUGIN); - pluginTitles[DOC_EXPLORER_PLUGIN.title] = true; - } - if (hasHistoryContext) { - pluginList.push(HISTORY_PLUGIN); - pluginTitles[HISTORY_PLUGIN.title] = true; - } - for (const plugin of props.plugins || []) { - if (typeof plugin.title !== "string" || !plugin.title) { - throw new Error( - "All GraphiQL plugins must have a unique title" - ); - } - if (pluginTitles[plugin.title]) { - throw new Error( - `All GraphiQL plugins must have a unique title, found two plugins with the title '${plugin.title}'` - ); - } else { - pluginList.push(plugin); - pluginTitles[plugin.title] = true; - } - } - return pluginList; - }, [hasExplorerContext, hasHistoryContext, props.plugins]); - const [visiblePlugin, internalSetVisiblePlugin] = React.useState( - () => { - const storedValue = - storage == null ? void 0 : storage.get(STORAGE_KEY$4); - const pluginForStoredValue = plugins.find( - (plugin) => plugin.title === storedValue - ); - if (pluginForStoredValue) { - return pluginForStoredValue; - } - if (storedValue) { - storage == null ? void 0 : storage.set(STORAGE_KEY$4, ""); - } - if (!props.visiblePlugin) { - return null; - } - return ( - plugins.find( - (plugin) => - (typeof props.visiblePlugin === "string" - ? plugin.title - : plugin) === props.visiblePlugin - ) || null - ); - } - ); - const { onTogglePluginVisibility, children } = props; - const setVisiblePlugin = React.useCallback( - (plugin) => { - const newVisiblePlugin = plugin - ? plugins.find( - (p) => (typeof plugin === "string" ? p.title : p) === plugin - ) || null - : null; - internalSetVisiblePlugin((current) => { - if (newVisiblePlugin === current) { - return current; - } - onTogglePluginVisibility == null - ? void 0 - : onTogglePluginVisibility(newVisiblePlugin); - return newVisiblePlugin; - }); - }, - [onTogglePluginVisibility, plugins] - ); - React.useEffect(() => { - if (props.visiblePlugin) { - setVisiblePlugin(props.visiblePlugin); - } - }, [plugins, props.visiblePlugin, setVisiblePlugin]); - const value = React.useMemo( - () => ({ - plugins, - setVisiblePlugin, - visiblePlugin, - }), - [plugins, setVisiblePlugin, visiblePlugin] - ); - return /* @__PURE__ */ jsxRuntime.jsx(PluginContext.Provider, { - value, - children, - }); + if (typeof type === 'function') { + return type.displayName || type.name || null; } - const usePluginContext = createContextHook(PluginContext); - const STORAGE_KEY$4 = "visiblePlugin"; - function onHasCompletion( - _cm, - data, - schema, - explorer, - plugin, - callback - ) { - void importCodeMirror([], { - useCommonAddons: false, - }).then((CodeMirror) => { - let information; - let fieldName; - let typeNamePill; - let typeNamePrefix; - let typeName; - let typeNameSuffix; - let description; - let deprecation; - let deprecationReason; - CodeMirror.on( - data, - "select", - // @ts-expect-error - (ctx, el) => { - if (!information) { - const hintsUl = el.parentNode; - information = document.createElement("div"); - information.className = "CodeMirror-hint-information"; - hintsUl.append(information); - const header = document.createElement("header"); - header.className = "CodeMirror-hint-information-header"; - information.append(header); - fieldName = document.createElement("span"); - fieldName.className = - "CodeMirror-hint-information-field-name"; - header.append(fieldName); - typeNamePill = document.createElement("span"); - typeNamePill.className = - "CodeMirror-hint-information-type-name-pill"; - header.append(typeNamePill); - typeNamePrefix = document.createElement("span"); - typeNamePill.append(typeNamePrefix); - typeName = document.createElement("a"); - typeName.className = "CodeMirror-hint-information-type-name"; - typeName.href = "javascript:void 0"; - typeName.addEventListener("click", onClickHintInformation); - typeNamePill.append(typeName); - typeNameSuffix = document.createElement("span"); - typeNamePill.append(typeNameSuffix); - description = document.createElement("div"); - description.className = - "CodeMirror-hint-information-description"; - information.append(description); - deprecation = document.createElement("div"); - deprecation.className = - "CodeMirror-hint-information-deprecation"; - information.append(deprecation); - const deprecationLabel = document.createElement("span"); - deprecationLabel.className = - "CodeMirror-hint-information-deprecation-label"; - deprecationLabel.textContent = "Deprecated"; - deprecation.append(deprecationLabel); - deprecationReason = document.createElement("div"); - deprecationReason.className = - "CodeMirror-hint-information-deprecation-reason"; - deprecation.append(deprecationReason); - const defaultInformationPadding = - parseInt( - window - .getComputedStyle(information) - .paddingBottom.replace(/px$/, ""), - 10 - ) || 0; - const defaultInformationMaxHeight = - parseInt( - window - .getComputedStyle(information) - .maxHeight.replace(/px$/, ""), - 10 - ) || 0; - const handleScroll = () => { - if (information) { - information.style.paddingTop = - hintsUl.scrollTop + defaultInformationPadding + "px"; - information.style.maxHeight = - hintsUl.scrollTop + defaultInformationMaxHeight + "px"; - } - }; - hintsUl.addEventListener("scroll", handleScroll); - let onRemoveFn; - hintsUl.addEventListener( - "DOMNodeRemoved", - (onRemoveFn = (event) => { - if (event.target !== hintsUl) { - return; - } - hintsUl.removeEventListener("scroll", handleScroll); - hintsUl.removeEventListener("DOMNodeRemoved", onRemoveFn); - if (information) { - information.removeEventListener( - "click", - onClickHintInformation - ); - } - information = null; - fieldName = null; - typeNamePill = null; - typeNamePrefix = null; - typeName = null; - typeNameSuffix = null; - description = null; - deprecation = null; - deprecationReason = null; - onRemoveFn = null; - }) - ); - } - if (fieldName) { - fieldName.textContent = ctx.text; - } - if ( - typeNamePill && - typeNamePrefix && - typeName && - typeNameSuffix - ) { - if (ctx.type) { - typeNamePill.style.display = "inline"; - const renderType2 = (type) => { - if (graphql.isNonNullType(type)) { - typeNameSuffix.textContent = - "!" + typeNameSuffix.textContent; - renderType2(type.ofType); - } else if (graphql.isListType(type)) { - typeNamePrefix.textContent += "["; - typeNameSuffix.textContent = - "]" + typeNameSuffix.textContent; - renderType2(type.ofType); - } else { - typeName.textContent = type.name; - } - }; - typeNamePrefix.textContent = ""; - typeNameSuffix.textContent = ""; - renderType2(ctx.type); - } else { - typeNamePrefix.textContent = ""; - typeName.textContent = ""; - typeNameSuffix.textContent = ""; - typeNamePill.style.display = "none"; - } - } - if (description) { - if (ctx.description) { - description.style.display = "block"; - description.innerHTML = markdown.render(ctx.description); - } else { - description.style.display = "none"; - description.innerHTML = ""; - } - } - if (deprecation && deprecationReason) { - if (ctx.deprecationReason) { - deprecation.style.display = "block"; - deprecationReason.innerHTML = markdown.render( - ctx.deprecationReason - ); - } else { - deprecation.style.display = "none"; - deprecationReason.innerHTML = ""; - } - } - } - ); - }); - function onClickHintInformation(event) { - if ( - !schema || - !explorer || - !plugin || - !(event.currentTarget instanceof HTMLElement) - ) { - return; - } - const typeName = event.currentTarget.textContent || ""; - const type = schema.getType(typeName); - if (type) { - plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); - explorer.push({ - name: type.name, - def: type, - }); - callback == null ? void 0 : callback(type); - } - } - } - function useSynchronizeValue(editor, value) { - React.useEffect(() => { - if ( - editor && - typeof value === "string" && - value !== editor.getValue() - ) { - editor.setValue(value); - } - }, [editor, value]); - } - function useSynchronizeOption(editor, option, value) { - React.useEffect(() => { - if (editor) { - editor.setOption(option, value); - } - }, [editor, option, value]); - } - function useChangeHandler( - editor, - callback, - storageKey, - tabProperty, - caller - ) { - const { updateActiveTabValues } = useEditorContext({ - nonNull: true, - caller, - }); - const storage = useStorageContext(); - React.useEffect(() => { - if (!editor) { - return; - } - const store = debounce(500, (value) => { - if (!storage || storageKey === null) { - return; + if (typeof type === 'string') { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + case REACT_PORTAL_TYPE: + return 'Portal'; + case REACT_PROFILER_TYPE: + return 'Profiler'; + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || 'Memo'; + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } } - storage.set(storageKey, value); + + // eslint-disable-next-line no-fallthrough + } + } + return null; + } + var assign = Object.assign; + + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() {} + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props }); - const updateTab = debounce(100, (value) => { - updateActiveTabValues({ - [tabProperty]: value, - }); + /* eslint-enable react-internal/no-production-logging */ + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) }); - const handleChange = (editorInstance, changeObj) => { - if (!changeObj) { - return; - } - const newValue = editorInstance.getValue(); - store(newValue); - updateTab(newValue); - callback == null ? void 0 : callback(newValue); - }; - editor.on("change", handleChange); - return () => editor.off("change", handleChange); - }, [ - callback, - editor, - storage, - storageKey, - tabProperty, - updateActiveTabValues, - ]); - } - function useCompletion(editor, callback, caller) { - const { schema } = useSchemaContext({ - nonNull: true, - caller, - }); - const explorer = useExplorerContext(); - const plugin = usePluginContext(); - React.useEffect(() => { - if (!editor) { - return; - } - const handleCompletion = (instance, changeObj) => { - onHasCompletion( - instance, - changeObj, - schema, - explorer, - plugin, - (type) => { - callback == null - ? void 0 - : callback({ - kind: "Type", - type, - schema: schema || void 0, - }); - } - ); - }; - editor.on( - // @ts-expect-error @TODO additional args for hasCompletion event - "hasCompletion", - handleCompletion - ); - return () => - editor.off( - // @ts-expect-error @TODO additional args for hasCompletion event - "hasCompletion", - handleCompletion - ); - }, [callback, editor, explorer, plugin, schema]); + /* eslint-enable react-internal/no-production-logging */ + } + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } } - function useKeyMap(editor, keys, callback) { - React.useEffect(() => { - if (!editor) { - return; - } - for (const key of keys) { - editor.removeKeyMap(key); - } - if (callback) { - const keyMap = {}; - for (const key of keys) { - keyMap[key] = () => callback(); - } - editor.addKeyMap(keyMap); + } + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; } - }, [editor, keys, callback]); + } // We use the prefix to ensure our stacks line up with native stack frames. + + return '\n' + prefix + name; } - function useCopyQuery({ caller, onCopyQuery } = {}) { - const { queryEditor } = useEditorContext({ - nonNull: true, - caller: caller || useCopyQuery, - }); - return React.useCallback(() => { - if (!queryEditor) { - return; - } - const query = queryEditor.getValue(); - copyToClipboard(query); - onCopyQuery == null ? void 0 : onCopyQuery(query); - }, [queryEditor, onCopyQuery]); + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ''; } - function useMergeQuery({ caller } = {}) { - const { queryEditor } = useEditorContext({ - nonNull: true, - caller: caller || useMergeQuery, - }); - const { schema } = useSchemaContext({ - nonNull: true, - caller: useMergeQuery, - }); - return React.useCallback(() => { - const documentAST = - queryEditor == null ? void 0 : queryEditor.documentAST; - const query = queryEditor == null ? void 0 : queryEditor.getValue(); - if (!documentAST || !query) { - return; - } - queryEditor.setValue( - graphql.print(toolkit.mergeAst(documentAST, schema)) - ); - }, [queryEditor, schema]); + { + var frame = componentFrameCache.get(fn); + if (frame !== undefined) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); } - function usePrettifyEditors({ caller } = {}) { - const { queryEditor, headerEditor, variableEditor } = - useEditorContext({ - nonNull: true, - caller: caller || usePrettifyEditors, + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } }); - return React.useCallback(() => { - if (variableEditor) { - const variableEditorContent = variableEditor.getValue(); + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. try { - const prettifiedVariableEditorContent = JSON.stringify( - JSON.parse(variableEditorContent), - null, - 2 - ); - if (prettifiedVariableEditorContent !== variableEditorContent) { - variableEditor.setValue(prettifiedVariableEditorContent); - } - } catch {} - } - if (headerEditor) { - const headerEditorContent = headerEditor.getValue(); + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { try { - const prettifiedHeaderEditorContent = JSON.stringify( - JSON.parse(headerEditorContent), - null, - 2 - ); - if (prettifiedHeaderEditorContent !== headerEditorContent) { - headerEditor.setValue(prettifiedHeaderEditorContent); - } - } catch {} - } - if (queryEditor) { - const editorContent = queryEditor.getValue(); - const prettifiedEditorContent = graphql.print( - graphql.parse(editorContent) - ); - if (prettifiedEditorContent !== editorContent) { - queryEditor.setValue(prettifiedEditorContent); + Fake.call(); + } catch (x) { + control = x; } + fn.call(Fake.prototype); } - }, [queryEditor, variableEditor, headerEditor]); - } - function useAutoCompleteLeafs({ getDefaultFieldNames, caller } = {}) { - const { schema } = useSchemaContext({ - nonNull: true, - caller: caller || useAutoCompleteLeafs, - }); - const { queryEditor } = useEditorContext({ - nonNull: true, - caller: caller || useAutoCompleteLeafs, - }); - return React.useCallback(() => { - if (!queryEditor) { - return; - } - const query = queryEditor.getValue(); - const { insertions, result } = toolkit.fillLeafs( - schema, - query, - getDefaultFieldNames - ); - if (insertions && insertions.length > 0) { - queryEditor.operation(() => { - const cursor = queryEditor.getCursor(); - const cursorIndex = queryEditor.indexFromPos(cursor); - queryEditor.setValue(result || ""); - let added = 0; - const markers = insertions.map(({ index, string }) => - queryEditor.markText( - queryEditor.posFromIndex(index + added), - queryEditor.posFromIndex(index + (added += string.length)), - { - className: "auto-inserted-leaf", - clearOnEnter: true, - title: "Automatically added leaf fields", + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + return _frame; } - ) - ); - setTimeout(() => { - for (const marker of markers) { - marker.clear(); - } - }, 7e3); - let newCursorIndex = cursorIndex; - for (const { index, string } of insertions) { - if (index < cursorIndex) { - newCursorIndex += string.length; - } - } - queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex)); - }); - } - return result; - }, [getDefaultFieldNames, queryEditor, schema]); - } - const useEditorState = (editor) => { - var _ref2; - const context = useEditorContext({ - nonNull: true, - }); - const editorInstance = context[`${editor}Editor`]; - let valueString = ""; - const editorValue = - (_ref2 = - editorInstance == null ? void 0 : editorInstance.getValue()) !== - null && _ref2 !== void 0 - ? _ref2 - : false; - if (editorValue && editorValue.length > 0) { - valueString = editorValue; - } - const handleEditorValue = React.useCallback( - (value) => - editorInstance == null ? void 0 : editorInstance.setValue(value), - [editorInstance] - ); - return React.useMemo( - () => [valueString, handleEditorValue], - [valueString, handleEditorValue] - ); - }; - const useOperationsEditorState = () => { - return useEditorState("query"); - }; - const useVariablesEditorState = () => { - return useEditorState("variable"); - }; - const useHeadersEditorState = () => { - return useEditorState("header"); - }; - function useOptimisticState([upstreamState, upstreamSetState]) { - const lastStateRef = React.useRef({ - /** The last thing that we sent upstream; we're expecting this back */ - pending: null, - /** The last thing we received from upstream */ - last: upstreamState, - }); - const [state, setOperationsText] = React.useState(upstreamState); - React.useEffect(() => { - if (lastStateRef.current.last === upstreamState); - else { - lastStateRef.current.last = upstreamState; - if (lastStateRef.current.pending === null) { - setOperationsText(upstreamState); - } else if (lastStateRef.current.pending === upstreamState) { - lastStateRef.current.pending = null; - if (upstreamState !== state) { - lastStateRef.current.pending = state; - upstreamSetState(state); + } while (s >= 1 && c >= 0); } - } else { - lastStateRef.current.pending = null; - setOperationsText(upstreamState); + break; } } - }, [upstreamState, state, upstreamSetState]); - const setState = React.useCallback( - (newState) => { - setOperationsText(newState); - if ( - lastStateRef.current.pending === null && - lastStateRef.current.last !== newState - ) { - lastStateRef.current.pending = newState; - upstreamSetState(newState); - } - }, - [upstreamSetState] - ); - return React.useMemo(() => [state, setState], [state, setState]); + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } } - function useHeaderEditor( + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ''; + } + if (typeof type === 'function') { { - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onEdit, - readOnly = false, - } = {}, - caller - ) { - const { - initialHeaders, - headerEditor, - setHeaderEditor, - shouldPersistHeaders, - } = useEditorContext({ - nonNull: true, - caller: caller || useHeaderEditor, - }); - const executionContext = useExecutionContext(); - const merge = useMergeQuery({ - caller: caller || useHeaderEditor, - }); - const prettify = usePrettifyEditors({ - caller: caller || useHeaderEditor, - }); - const ref = React.useRef(null); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([ - // @ts-expect-error - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./javascript.cjs.js */ "../../graphiql-react/dist/javascript.cjs.js" - ) - ) - .then((n) => n.javascript), - ]).then((CodeMirror) => { - if (!isActive) { - return; - } - const container = ref.current; - if (!container) { - return; + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} } - const newEditor = CodeMirror(container, { - value: initialHeaders, - lineNumbers: true, - tabSize: 2, - mode: { - name: "javascript", - json: true, - }, - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - foldGutter: true, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: commonKeys, - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - }); - newEditor.on("keyup", (editorInstance, event) => { - const { code, key, shiftKey } = event; - const isLetter = code.startsWith("Key"); - const isNumber = !shiftKey && code.startsWith("Digit"); - if (isLetter || isNumber || key === "_" || key === '"') { - editorInstance.execCommand("autocomplete"); - } - }); - setHeaderEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialHeaders, readOnly, setHeaderEditor]); - useSynchronizeOption(headerEditor, "keyMap", keyMap); - useChangeHandler( - headerEditor, - onEdit, - shouldPersistHeaders ? STORAGE_KEY$3 : null, - "headers", - useHeaderEditor - ); - useKeyMap( - headerEditor, - ["Cmd-Enter", "Ctrl-Enter"], - executionContext == null ? void 0 : executionContext.run - ); - useKeyMap(headerEditor, ["Shift-Ctrl-P"], prettify); - useKeyMap(headerEditor, ["Shift-Ctrl-M"], merge); - return ref; + } } - const STORAGE_KEY$3 = "headers"; - const invalidCharacters = Array.from( - { - length: 11, - }, - (_, i) => { - return String.fromCharCode(8192 + i); + return ''; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); } - ).concat(["\u2028", "\u2029", " ", " "]); - const sanitizeRegex = new RegExp( - "[" + invalidCharacters.join("") + "]", - "g" - ); - function normalizeWhitespace(line) { - return line.replace(sanitizeRegex, " "); } - function useQueryEditor( - { - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onClickReference, - onCopyQuery, - onEdit, - readOnly = false, - } = {}, - caller - ) { - const { schema } = useSchemaContext({ - nonNull: true, - caller: caller || useQueryEditor, - }); - const { - externalFragments, - initialQuery, - queryEditor, - setOperationName, - setQueryEditor, - validationRules, - variableEditor, - updateActiveTabValues, - } = useEditorContext({ - nonNull: true, - caller: caller || useQueryEditor, - }); - const executionContext = useExecutionContext(); - const storage = useStorageContext(); - const explorer = useExplorerContext(); - const plugin = usePluginContext(); - const copy = useCopyQuery({ - caller: caller || useQueryEditor, - onCopyQuery, - }); - const merge = useMergeQuery({ - caller: caller || useQueryEditor, - }); - const prettify = usePrettifyEditors({ - caller: caller || useQueryEditor, - }); - const ref = React.useRef(null); - const codeMirrorRef = React.useRef(); - const onClickReferenceRef = React.useRef(() => {}); - React.useEffect(() => { - onClickReferenceRef.current = (reference) => { - if (!explorer || !plugin) { - return; - } - plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); - switch (reference.kind) { - case "Type": { - explorer.push({ - name: reference.type.name, - def: reference.type, - }); - break; - } - case "Field": { - explorer.push({ - name: reference.field.name, - def: reference.field, - }); - break; - } - case "Argument": { - if (reference.field) { - explorer.push({ - name: reference.field.name, - def: reference.field, - }); - } - break; - } - case "EnumValue": { - if (reference.type) { - explorer.push({ - name: reference.type.name, - def: reference.type, - }); - } - break; + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; } - onClickReference == null ? void 0 : onClickReference(reference); - }; - }, [explorer, onClickReference, plugin]); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([ - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./comment.cjs.js */ "../../graphiql-react/dist/comment.cjs.js" - ) - ) - .then((n) => n.comment), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js" - ) - ) - .then((n) => n.search), - Promise.resolve().then(() => - __webpack_require__( - /*! ./hint.cjs.js */ "../../graphiql-react/dist/hint.cjs.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./lint.cjs2.js */ "../../graphiql-react/dist/lint.cjs2.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./info.cjs.js */ "../../graphiql-react/dist/info.cjs.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./jump.cjs.js */ "../../graphiql-react/dist/jump.cjs.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./mode.cjs.js */ "../../graphiql-react/dist/mode.cjs.js" - ) - ), - ]).then((CodeMirror) => { - if (!isActive) { - return; + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); } - codeMirrorRef.current = CodeMirror; - const container = ref.current; - if (!container) { - return; + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error('Failed %s type: %s', location, error$1.message); + setCurrentlyValidatingElement(null); } - const newEditor = CodeMirror(container, { - value: initialQuery, - lineNumbers: true, - tabSize: 2, - foldGutter: true, - mode: "graphql", - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - lint: { - // @ts-expect-error - schema: void 0, - validationRules: null, - // linting accepts string or FragmentDefinitionNode[] - externalFragments: void 0, - }, - hintOptions: { - // @ts-expect-error - schema: void 0, - closeOnUnfocus: false, - completeSingle: false, - container, - externalFragments: void 0, - autocompleteOptions: { - // for the query editor, restrict to executable type definitions - mode: graphqlLanguageService.GraphQLDocumentMode.EXECUTABLE, - }, - }, - info: { - schema: void 0, - renderDescription: (text) => markdown.render(text), - onClick(reference) { - onClickReferenceRef.current(reference); - }, - }, - jump: { - schema: void 0, - onClick(reference) { - onClickReferenceRef.current(reference); - }, - }, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: { - ...commonKeys, - "Cmd-S"() {}, - "Ctrl-S"() {}, - }, - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: true, - container, - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: true, - container, - }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: true, - container, - }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: true, - container, - }); - }, - "Shift-Alt-Space"() { - newEditor.showHint({ - completeSingle: true, - container, - }); - }, - }); - newEditor.on("keyup", (editorInstance, event) => { - if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { - editorInstance.execCommand("autocomplete"); - } - }); - let showingHints = false; - newEditor.on("startCompletion", () => { - showingHints = true; - }); - newEditor.on("endCompletion", () => { - showingHints = false; - }); - newEditor.on("keydown", (editorInstance, event) => { - if (event.key === "Escape" && showingHints) { - event.stopPropagation(); - } - }); - newEditor.on("beforeChange", (editorInstance, change) => { - var _a; - if (change.origin === "paste") { - const text = change.text.map(normalizeWhitespace); - (_a = change.update) == null - ? void 0 - : _a.call(change, change.from, change.to, text); - } - }); - newEditor.documentAST = null; - newEditor.operationName = null; - newEditor.operations = null; - newEditor.variableToType = null; - setQueryEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialQuery, readOnly, setQueryEditor]); - useSynchronizeOption(queryEditor, "keyMap", keyMap); - React.useEffect(() => { - if (!queryEditor) { - return; } - function getAndUpdateOperationFacts(editorInstance) { - var _editorInstance$opera, _editorInstance$opera2, _ref3, _ref4; - var _a; - const operationFacts = graphqlLanguageService.getOperationFacts( - schema, - editorInstance.getValue() - ); - const operationName = toolkit.getSelectedOperationName( - (_editorInstance$opera = editorInstance.operations) !== null && - _editorInstance$opera !== void 0 - ? _editorInstance$opera - : void 0, - (_editorInstance$opera2 = editorInstance.operationName) !== - null && _editorInstance$opera2 !== void 0 - ? _editorInstance$opera2 - : void 0, - operationFacts == null ? void 0 : operationFacts.operations - ); - editorInstance.documentAST = - (_ref3 = - operationFacts == null - ? void 0 - : operationFacts.documentAST) !== null && _ref3 !== void 0 - ? _ref3 - : null; - editorInstance.operationName = - operationName !== null && operationName !== void 0 - ? operationName - : null; - editorInstance.operations = - (_ref4 = - operationFacts == null - ? void 0 - : operationFacts.operations) !== null && _ref4 !== void 0 - ? _ref4 - : null; - if (variableEditor) { - variableEditor.state.lint.linterOptions.variableToType = - operationFacts == null - ? void 0 - : operationFacts.variableToType; - variableEditor.options.lint.variableToType = - operationFacts == null - ? void 0 - : operationFacts.variableToType; - variableEditor.options.hintOptions.variableToType = - operationFacts == null - ? void 0 - : operationFacts.variableToType; - (_a = codeMirrorRef.current) == null - ? void 0 - : _a.signal(variableEditor, "change", variableEditor); - } - return operationFacts - ? { - ...operationFacts, - operationName, - } - : null; - } - const handleChange = debounce(100, (editorInstance) => { - var _ref5; - const query = editorInstance.getValue(); - storage == null ? void 0 : storage.set(STORAGE_KEY_QUERY, query); - const currentOperationName = editorInstance.operationName; - const operationFacts = getAndUpdateOperationFacts(editorInstance); - if ( - (operationFacts == null - ? void 0 - : operationFacts.operationName) !== void 0 - ) { - storage == null - ? void 0 - : storage.set( - STORAGE_KEY_OPERATION_NAME, - operationFacts.operationName - ); - } - onEdit == null - ? void 0 - : onEdit( - query, - operationFacts == null ? void 0 : operationFacts.documentAST - ); - if ( - (operationFacts == null - ? void 0 - : operationFacts.operationName) && - currentOperationName !== operationFacts.operationName - ) { - setOperationName(operationFacts.operationName); - } - updateActiveTabValues({ - query, - operationName: - (_ref5 = - operationFacts == null - ? void 0 - : operationFacts.operationName) !== null && - _ref5 !== void 0 - ? _ref5 - : null, - }); - }); - getAndUpdateOperationFacts(queryEditor); - queryEditor.on("change", handleChange); - return () => queryEditor.off("change", handleChange); - }, [ - onEdit, - queryEditor, - schema, - setOperationName, - storage, - variableEditor, - updateActiveTabValues, - ]); - useSynchronizeSchema( - queryEditor, - schema !== null && schema !== void 0 ? schema : null, - codeMirrorRef - ); - useSynchronizeValidationRules( - queryEditor, - validationRules !== null && validationRules !== void 0 - ? validationRules - : null, - codeMirrorRef - ); - useSynchronizeExternalFragments( - queryEditor, - externalFragments, - codeMirrorRef - ); - useCompletion(queryEditor, onClickReference || null, useQueryEditor); - const run = executionContext == null ? void 0 : executionContext.run; - const runAtCursor = React.useCallback(() => { - var _a; - if ( - !run || - !queryEditor || - !queryEditor.operations || - !queryEditor.hasFocus() - ) { - run == null ? void 0 : run(); - return; + } + } + } + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + + function isArray(a) { + return isArrayImpl(a); + } + + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. + + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } + } + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown; + var specialPropRefWarningShown; + var didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== undefined; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== undefined; + } + function warnIfStringRefCannotBeAutoConverted(config, self) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function () { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); + } + } + function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function () { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); + } + } + /** + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal + */ + + var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + /** + * https://github.com/reactjs/rfcs/pull/107 + * @param {*} type + * @param {object} props + * @param {string} key + */ + + function jsxDEV(type, config, maybeKey, source, self) { + { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; // Currently, key can be spread in as a prop. This causes a potential + // issue if key is also explicitly declared (ie.
    + // or
    ). We want to deprecate key spread, + // but as an intermediary step, we will use jsxDEV for everything except + //
    , because we aren't currently able to tell if + // key is explicitly declared to be undefined or not. + + if (maybeKey !== undefined) { + { + checkKeyStringCoercion(maybeKey); + } + key = '' + maybeKey; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); } - const cursorIndex = queryEditor.indexFromPos( - queryEditor.getCursor() - ); - let operationName; - for (const operation of queryEditor.operations) { - if ( - operation.loc && - operation.loc.start <= cursorIndex && - operation.loc.end >= cursorIndex - ) { - operationName = - (_a = operation.name) == null ? void 0 : _a.value; - } + key = '' + config.key; + } + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self); + } // Remaining properties are added to a new props object + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; } - if (operationName && operationName !== queryEditor.operationName) { - setOperationName(operationName); + } // Resolve default props + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } } - run(); - }, [queryEditor, run, setOperationName]); - useKeyMap(queryEditor, ["Cmd-Enter", "Ctrl-Enter"], runAtCursor); - useKeyMap(queryEditor, ["Shift-Ctrl-C"], copy); - useKeyMap( - queryEditor, - [ - "Shift-Ctrl-P", - // Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to prettify - "Shift-Ctrl-F", - ], - prettify - ); - useKeyMap(queryEditor, ["Shift-Ctrl-M"], merge); - return ref; - } - function useSynchronizeSchema(editor, schema, codeMirrorRef) { - React.useEffect(() => { - if (!editor) { - return; + } + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); } - const didChange = editor.options.lint.schema !== schema; - editor.state.lint.linterOptions.schema = schema; - editor.options.lint.schema = schema; - editor.options.hintOptions.schema = schema; - editor.options.info.schema = schema; - editor.options.jump.schema = schema; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); + if (ref) { + defineRefPropWarningGetter(props, displayName); } - }, [editor, schema, codeMirrorRef]); + } + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } - function useSynchronizeValidationRules( - editor, - validationRules, - codeMirrorRef - ) { - React.useEffect(() => { - if (!editor) { - return; + } + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + /** + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final + */ + + function isValidElement(object) { + { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + } + function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; } - const didChange = - editor.options.lint.validationRules !== validationRules; - editor.state.lint.linterOptions.validationRules = validationRules; - editor.options.lint.validationRules = validationRules; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); + } + return ''; + } + } + function getSourceInfoErrorAddendum(source) { + { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + return ''; + } + } + /** + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. + */ + + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; } - }, [editor, validationRules, codeMirrorRef]); + } + return info; } - function useSynchronizeExternalFragments( - editor, - externalFragments, - codeMirrorRef - ) { - const externalFragmentList = React.useMemo( - () => [...externalFragments.values()], - [externalFragments] - ); - React.useEffect(() => { - if (!editor) { - return; + } + /** + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. + */ + + function validateExplicitKey(element, parentType) { + { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + /** + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. + */ + + function validateChildKeys(node, parentType) { + { + if (typeof node !== 'object') { + return; + } + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } } - const didChange = - editor.options.lint.externalFragments !== externalFragmentList; - editor.state.lint.linterOptions.externalFragments = - externalFragmentList; - editor.options.lint.externalFragments = externalFragmentList; - editor.options.hintOptions.externalFragments = externalFragmentList; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, externalFragmentList, codeMirrorRef]); - } - const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/; - const STORAGE_KEY_QUERY = "query"; - const STORAGE_KEY_OPERATION_NAME = "operationName"; - function getDefaultTabState({ - defaultQuery, - defaultHeaders, - headers, - defaultTabs, - query, - variables, - storage, - shouldPersistHeaders, - }) { - const storedState = - storage == null ? void 0 : storage.get(STORAGE_KEY$2); - try { - if (!storedState) { - throw new Error("Storage for tabs is empty"); - } - const parsed = JSON.parse(storedState); - const headersForHash = shouldPersistHeaders ? headers : void 0; - if (isTabsState(parsed)) { - const expectedHash = hashFromTabContents({ - query, - variables, - headers: headersForHash, - }); - let matchingTabIndex = -1; - for (let index = 0; index < parsed.tabs.length; index++) { - const tab = parsed.tabs[index]; - tab.hash = hashFromTabContents({ - query: tab.query, - variables: tab.variables, - headers: tab.headers, - }); - if (tab.hash === expectedHash) { - matchingTabIndex = index; + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } } } - if (matchingTabIndex >= 0) { - parsed.activeTabIndex = matchingTabIndex; - } else { - const operationName = query - ? fuzzyExtractOperationName(query) - : null; - parsed.tabs.push({ - id: guid(), - hash: expectedHash, - title: operationName || DEFAULT_TITLE, - query, - variables, - headers, - operationName, - response: null, - }); - parsed.activeTabIndex = parsed.tabs.length - 1; - } - return parsed; } - throw new Error("Storage for tabs is invalid"); - } catch { - return { - activeTabIndex: 0, - tabs: ( - defaultTabs || [ - { - query: - query !== null && query !== void 0 ? query : defaultQuery, - variables, - headers: - headers !== null && headers !== void 0 - ? headers - : defaultHeaders, - }, - ] - ).map(createTab), - }; } } - function isTabsState(obj) { - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - hasNumberKey(obj, "activeTabIndex") && - "tabs" in obj && - Array.isArray(obj.tabs) && - obj.tabs.every(isTabState) - ); - } - function isTabState(obj) { - return ( - obj && - typeof obj === "object" && - !Array.isArray(obj) && - hasStringKey(obj, "id") && - hasStringKey(obj, "title") && - hasStringOrNullKey(obj, "query") && - hasStringOrNullKey(obj, "variables") && - hasStringOrNullKey(obj, "headers") && - hasStringOrNullKey(obj, "operationName") && - hasStringOrNullKey(obj, "response") - ); - } - function hasNumberKey(obj, key) { - return key in obj && typeof obj[key] === "number"; - } - function hasStringKey(obj, key) { - return key in obj && typeof obj[key] === "string"; - } - function hasStringOrNullKey(obj, key) { - return ( - key in obj && (typeof obj[key] === "string" || obj[key] === null) - ); + } + /** + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element + */ + + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === undefined || typeof type === 'string') { + return; + } + var propTypes; + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || + // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } } - function useSynchronizeActiveTabValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor, - }) { - return React.useCallback( - (state) => { - var _ref6, _ref7, _ref8, _ref9, _ref10; - const query = - (_ref6 = - queryEditor == null ? void 0 : queryEditor.getValue()) !== - null && _ref6 !== void 0 - ? _ref6 - : null; - const variables = - (_ref7 = - variableEditor == null - ? void 0 - : variableEditor.getValue()) !== null && _ref7 !== void 0 - ? _ref7 - : null; - const headers = - (_ref8 = - headerEditor == null ? void 0 : headerEditor.getValue()) !== - null && _ref8 !== void 0 - ? _ref8 - : null; - const operationName = - (_ref9 = - queryEditor == null ? void 0 : queryEditor.operationName) !== - null && _ref9 !== void 0 - ? _ref9 - : null; - const response = - (_ref10 = - responseEditor == null - ? void 0 - : responseEditor.getValue()) !== null && _ref10 !== void 0 - ? _ref10 - : null; - return setPropertiesInActiveTab(state, { - query, - variables, - headers, - response, - operationName, - }); - }, - [queryEditor, variableEditor, headerEditor, responseEditor] - ); + } + /** + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment + */ + + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + setCurrentlyValidatingElement$1(null); + } } - function serializeTabState(tabState, shouldPersistHeaders = false) { - return JSON.stringify(tabState, (key, value) => - key === "hash" || - key === "response" || - (!shouldPersistHeaders && key === "headers") - ? null - : value - ); + } + function jsxWithValidation(type, props, key, isStaticChildren, source, self) { + { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendum(source); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + if (validType) { + var children = props.children; + if (children !== undefined) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + validateChildKeys(children[i], type); + } + if (Object.freeze) { + Object.freeze(children); + } + } else { + error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); + } + } else { + validateChildKeys(children, type); + } + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; } - function useStoreTabs({ storage, shouldPersistHeaders }) { - const store = React.useMemo( - () => - debounce(500, (value) => { - storage == null ? void 0 : storage.set(STORAGE_KEY$2, value); - }), - [storage] - ); - return React.useCallback( - (currentState) => { - store(serializeTabState(currentState, shouldPersistHeaders)); - }, - [shouldPersistHeaders, store] - ); + } // These two functions exist to still get child warnings in dev + // even with the prod transform. This means that jsxDEV is purely + // opt-in behavior for better messages but that we won't stop + // giving you warnings if you use production apis. + + function jsxWithValidationStatic(type, props, key) { + { + return jsxWithValidation(type, props, key, true); } - function useSetEditorValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor, - }) { - return React.useCallback( - ({ query, variables, headers, response }) => { - queryEditor == null - ? void 0 - : queryEditor.setValue( - query !== null && query !== void 0 ? query : "" - ); - variableEditor == null - ? void 0 - : variableEditor.setValue( - variables !== null && variables !== void 0 ? variables : "" - ); - headerEditor == null - ? void 0 - : headerEditor.setValue( - headers !== null && headers !== void 0 ? headers : "" - ); - responseEditor == null - ? void 0 - : responseEditor.setValue( - response !== null && response !== void 0 ? response : "" - ); - }, - [headerEditor, queryEditor, responseEditor, variableEditor] - ); + } + function jsxWithValidationDynamic(type, props, key) { + { + return jsxWithValidation(type, props, key, false); } - function createTab({ - query = null, - variables = null, - headers = null, - } = {}) { - return { - id: guid(), - hash: hashFromTabContents({ - query, - variables, - headers, - }), - title: (query && fuzzyExtractOperationName(query)) || DEFAULT_TITLE, - query, - variables, - headers, - operationName: null, - response: null, - }; + } + var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children. + // for now we can ship identical prod functions + + var jsxs = jsxWithValidationStatic; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.jsx = jsx; + exports.jsxs = jsxs; + })(); + } + + /***/ }), + + /***/ "../../../node_modules/react/jsx-runtime.js": + /*!**************************************************!*\ + !*** ../../../node_modules/react/jsx-runtime.js ***! + \**************************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + + if (false) {} else { + module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ "../../../node_modules/react/cjs/react-jsx-runtime.development.js"); + } + + /***/ }), + + /***/ "../../../node_modules/set-value/index.js": + /*!************************************************!*\ + !*** ../../../node_modules/set-value/index.js ***! + \************************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + /*! + * set-value + * + * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert). + * Released under the MIT License. + */ + + + + const { + deleteProperty + } = Reflect; + const isPrimitive = __webpack_require__(/*! is-primitive */ "../../../node_modules/is-primitive/index.js"); + const isPlainObject = __webpack_require__(/*! is-plain-object */ "../../../node_modules/is-plain-object/index.js"); + const isObject = value => { + return typeof value === 'object' && value !== null || typeof value === 'function'; + }; + const isUnsafeKey = key => { + return key === '__proto__' || key === 'constructor' || key === 'prototype'; + }; + const validateKey = key => { + if (!isPrimitive(key)) { + throw new TypeError('Object keys must be strings or symbols'); + } + if (isUnsafeKey(key)) { + throw new Error(`Cannot set unsafe key: "${key}"`); + } + }; + const toStringKey = input => { + return Array.isArray(input) ? input.flat().map(String).join(',') : input; + }; + const createMemoKey = (input, options) => { + if (typeof input !== 'string' || !options) return input; + let key = input + ';'; + if (options.arrays !== undefined) key += `arrays=${options.arrays};`; + if (options.separator !== undefined) key += `separator=${options.separator};`; + if (options.split !== undefined) key += `split=${options.split};`; + if (options.merge !== undefined) key += `merge=${options.merge};`; + if (options.preservePaths !== undefined) key += `preservePaths=${options.preservePaths};`; + return key; + }; + const memoize = (input, options, fn) => { + const key = toStringKey(options ? createMemoKey(input, options) : input); + validateKey(key); + const value = setValue.cache.get(key) || fn(); + setValue.cache.set(key, value); + return value; + }; + const splitString = (input, options = {}) => { + const sep = options.separator || '.'; + const preserve = sep === '/' ? false : options.preservePaths; + if (typeof input === 'string' && preserve !== false && /\//.test(input)) { + return [input]; + } + const parts = []; + let part = ''; + const push = part => { + let number; + if (part.trim() !== '' && Number.isInteger(number = Number(part))) { + parts.push(number); + } else { + parts.push(part); + } + }; + for (let i = 0; i < input.length; i++) { + const value = input[i]; + if (value === '\\') { + part += input[++i]; + continue; + } + if (value === sep) { + push(part); + part = ''; + continue; + } + part += value; + } + if (part) { + push(part); + } + return parts; + }; + const split = (input, options) => { + if (options && typeof options.split === 'function') return options.split(input); + if (typeof input === 'symbol') return [input]; + if (Array.isArray(input)) return input; + return memoize(input, options, () => splitString(input, options)); + }; + const assignProp = (obj, prop, value, options) => { + validateKey(prop); + + // Delete property when "value" is undefined + if (value === undefined) { + deleteProperty(obj, prop); + } else if (options && options.merge) { + const merge = options.merge === 'function' ? options.merge : Object.assign; + + // Only merge plain objects + if (merge && isPlainObject(obj[prop]) && isPlainObject(value)) { + obj[prop] = merge(obj[prop], value); + } else { + obj[prop] = value; + } + } else { + obj[prop] = value; + } + return obj; + }; + const setValue = (target, path, value, options) => { + if (!path || !isObject(target)) return target; + const keys = split(path, options); + let obj = target; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const next = keys[i + 1]; + validateKey(key); + if (next === undefined) { + assignProp(obj, key, value, options); + break; + } + if (typeof next === 'number' && !Array.isArray(obj[key])) { + obj = obj[key] = []; + continue; + } + if (!isObject(obj[key])) { + obj[key] = {}; + } + obj = obj[key]; + } + return target; + }; + setValue.split = split; + setValue.cache = new Map(); + setValue.clear = () => { + setValue.cache = new Map(); + }; + module.exports = setValue; + + /***/ }), + + /***/ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js": + /*!**********************************************************************!*\ + !*** ../../../node_modules/style-value-types/dist/valueTypes.cjs.js ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + const clamp = (min, max) => v => Math.max(Math.min(v, max), min); + const sanitize = v => v % 1 ? Number(v.toFixed(5)) : v; + const floatRegex = /(-)?([\d]*\.?[\d])+/g; + const colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi; + const singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i; + function isString(v) { + return typeof v === 'string'; + } + const number = { + test: v => typeof v === 'number', + parse: parseFloat, + transform: v => v + }; + const alpha = Object.assign(Object.assign({}, number), { + transform: clamp(0, 1) + }); + const scale = Object.assign(Object.assign({}, number), { + default: 1 + }); + const createUnitType = unit => ({ + test: v => isString(v) && v.endsWith(unit) && v.split(' ').length === 1, + parse: parseFloat, + transform: v => `${v}${unit}` + }); + const degrees = createUnitType('deg'); + const percent = createUnitType('%'); + const px = createUnitType('px'); + const vh = createUnitType('vh'); + const vw = createUnitType('vw'); + const progressPercentage = Object.assign(Object.assign({}, percent), { + parse: v => percent.parse(v) / 100, + transform: v => percent.transform(v * 100) + }); + const isColorString = (type, testProp) => v => { + return Boolean(isString(v) && singleColorRegex.test(v) && v.startsWith(type) || testProp && Object.prototype.hasOwnProperty.call(v, testProp)); + }; + const splitColor = (aName, bName, cName) => v => { + if (!isString(v)) return v; + const [a, b, c, alpha] = v.match(floatRegex); + return { + [aName]: parseFloat(a), + [bName]: parseFloat(b), + [cName]: parseFloat(c), + alpha: alpha !== undefined ? parseFloat(alpha) : 1 + }; + }; + const hsla = { + test: isColorString('hsl', 'hue'), + parse: splitColor('hue', 'saturation', 'lightness'), + transform: ({ + hue, + saturation, + lightness, + alpha: alpha$1 = 1 + }) => { + return 'hsla(' + Math.round(hue) + ', ' + percent.transform(sanitize(saturation)) + ', ' + percent.transform(sanitize(lightness)) + ', ' + sanitize(alpha.transform(alpha$1)) + ')'; + } + }; + const clampRgbUnit = clamp(0, 255); + const rgbUnit = Object.assign(Object.assign({}, number), { + transform: v => Math.round(clampRgbUnit(v)) + }); + const rgba = { + test: isColorString('rgb', 'red'), + parse: splitColor('red', 'green', 'blue'), + transform: ({ + red, + green, + blue, + alpha: alpha$1 = 1 + }) => 'rgba(' + rgbUnit.transform(red) + ', ' + rgbUnit.transform(green) + ', ' + rgbUnit.transform(blue) + ', ' + sanitize(alpha.transform(alpha$1)) + ')' + }; + function parseHex(v) { + let r = ''; + let g = ''; + let b = ''; + let a = ''; + if (v.length > 5) { + r = v.substr(1, 2); + g = v.substr(3, 2); + b = v.substr(5, 2); + a = v.substr(7, 2); + } else { + r = v.substr(1, 1); + g = v.substr(2, 1); + b = v.substr(3, 1); + a = v.substr(4, 1); + r += r; + g += g; + b += b; + a += a; + } + return { + red: parseInt(r, 16), + green: parseInt(g, 16), + blue: parseInt(b, 16), + alpha: a ? parseInt(a, 16) / 255 : 1 + }; + } + const hex = { + test: isColorString('#'), + parse: parseHex, + transform: rgba.transform + }; + const color = { + test: v => rgba.test(v) || hex.test(v) || hsla.test(v), + parse: v => { + if (rgba.test(v)) { + return rgba.parse(v); + } else if (hsla.test(v)) { + return hsla.parse(v); + } else { + return hex.parse(v); + } + }, + transform: v => { + return isString(v) ? v : v.hasOwnProperty('red') ? rgba.transform(v) : hsla.transform(v); + } + }; + const colorToken = '${c}'; + const numberToken = '${n}'; + function test(v) { + var _a, _b, _c, _d; + return isNaN(v) && isString(v) && ((_b = (_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0; + } + function analyse(v) { + if (typeof v === 'number') v = `${v}`; + const values = []; + let numColors = 0; + const colors = v.match(colorRegex); + if (colors) { + numColors = colors.length; + v = v.replace(colorRegex, colorToken); + values.push(...colors.map(color.parse)); + } + const numbers = v.match(floatRegex); + if (numbers) { + v = v.replace(floatRegex, numberToken); + values.push(...numbers.map(number.parse)); + } + return { + values, + numColors, + tokenised: v + }; + } + function parse(v) { + return analyse(v).values; + } + function createTransformer(v) { + const { + values, + numColors, + tokenised + } = analyse(v); + const numValues = values.length; + return v => { + let output = tokenised; + for (let i = 0; i < numValues; i++) { + output = output.replace(i < numColors ? colorToken : numberToken, i < numColors ? color.transform(v[i]) : sanitize(v[i])); + } + return output; + }; + } + const convertNumbersToZero = v => typeof v === 'number' ? 0 : v; + function getAnimatableNone(v) { + const parsed = parse(v); + const transformer = createTransformer(v); + return transformer(parsed.map(convertNumbersToZero)); + } + const complex = { + test, + parse, + createTransformer, + getAnimatableNone + }; + const maxDefaults = new Set(['brightness', 'contrast', 'saturate', 'opacity']); + function applyDefaultFilter(v) { + let [name, value] = v.slice(0, -1).split('('); + if (name === 'drop-shadow') return v; + const [number] = value.match(floatRegex) || []; + if (!number) return v; + const unit = value.replace(number, ''); + let defaultValue = maxDefaults.has(name) ? 1 : 0; + if (number !== value) defaultValue *= 100; + return name + '(' + defaultValue + unit + ')'; + } + const functionRegex = /([a-z-]*)\(.*?\)/g; + const filter = Object.assign(Object.assign({}, complex), { + getAnimatableNone: v => { + const functions = v.match(functionRegex); + return functions ? functions.map(applyDefaultFilter).join(' ') : v; + } + }); + exports.alpha = alpha; + exports.color = color; + exports.complex = complex; + exports.degrees = degrees; + exports.filter = filter; + exports.hex = hex; + exports.hsla = hsla; + exports.number = number; + exports.percent = percent; + exports.progressPercentage = progressPercentage; + exports.px = px; + exports.rgbUnit = rgbUnit; + exports.rgba = rgba; + exports.scale = scale; + exports.vh = vh; + exports.vw = vw; + + /***/ }), + + /***/ "../../../node_modules/toggle-selection/index.js": + /*!*******************************************************!*\ + !*** ../../../node_modules/toggle-selection/index.js ***! + \*******************************************************/ + /***/ (function(module) { + + + + module.exports = function () { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function () {}; + } + var active = document.activeElement; + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + switch (active.tagName.toUpperCase()) { + // .toUpperCase handles XHTML + case 'INPUT': + case 'TEXTAREA': + active.blur(); + break; + default: + active = null; + break; + } + selection.removeAllRanges(); + return function () { + selection.type === 'Caret' && selection.removeAllRanges(); + if (!selection.rangeCount) { + ranges.forEach(function (range) { + selection.addRange(range); + }); + } + active && active.focus(); + }; + }; + + /***/ }), + + /***/ "../../../node_modules/tslib/tslib.es6.mjs": + /*!*************************************************!*\ + !*** ../../../node_modules/tslib/tslib.es6.mjs ***! + \*************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.__addDisposableResource = __addDisposableResource; + exports.__assign = void 0; + exports.__asyncDelegator = __asyncDelegator; + exports.__asyncGenerator = __asyncGenerator; + exports.__asyncValues = __asyncValues; + exports.__await = __await; + exports.__awaiter = __awaiter; + exports.__classPrivateFieldGet = __classPrivateFieldGet; + exports.__classPrivateFieldIn = __classPrivateFieldIn; + exports.__classPrivateFieldSet = __classPrivateFieldSet; + exports.__createBinding = void 0; + exports.__decorate = __decorate; + exports.__disposeResources = __disposeResources; + exports.__esDecorate = __esDecorate; + exports.__exportStar = __exportStar; + exports.__extends = __extends; + exports.__generator = __generator; + exports.__importDefault = __importDefault; + exports.__importStar = __importStar; + exports.__makeTemplateObject = __makeTemplateObject; + exports.__metadata = __metadata; + exports.__param = __param; + exports.__propKey = __propKey; + exports.__read = __read; + exports.__rest = __rest; + exports.__runInitializers = __runInitializers; + exports.__setFunctionName = __setFunctionName; + exports.__spread = __spread; + exports.__spreadArray = __spreadArray; + exports.__spreadArrays = __spreadArrays; + exports.__values = __values; + exports["default"] = void 0; + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + function __extends(d, b) { + if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + var __assign = function () { + exports.__assign = __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + exports.__assign = __assign; + function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + } + function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + } + function __param(paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; + } + function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, + key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, + done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { + get: descriptor.get, + set: descriptor.set + } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_);else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + } + ; + function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + } + ; + function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); + } + ; + function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { + configurable: true, + value: prefix ? "".concat(prefix, " ", name) : name + }); + } + ; + function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + } + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - function setPropertiesInActiveTab(state, partialTab) { - return { - ...state, - tabs: state.tabs.map((tab, index) => { - if (index !== state.activeTabIndex) { - return tab; - } - const newTab = { - ...tab, - ...partialTab, - }; - return { - ...newTab, - hash: hashFromTabContents(newTab), - title: - newTab.operationName || - (newTab.query - ? fuzzyExtractOperationName(newTab.query) - : void 0) || - DEFAULT_TITLE, - }; - }), - }; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - function guid() { - const s4 = () => { - return Math.floor((1 + Math.random()) * 65536) - .toString(16) - .slice(1); - }; - return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; - } - function hashFromTabContents(args) { - var _args$query, _args$variables, _args$headers; - return [ - (_args$query = args.query) !== null && _args$query !== void 0 - ? _args$query - : "", - (_args$variables = args.variables) !== null && - _args$variables !== void 0 - ? _args$variables - : "", - (_args$headers = args.headers) !== null && _args$headers !== void 0 - ? _args$headers - : "", - ].join("|"); - } - function fuzzyExtractOperationName(str) { - var _ref11; - const regex = - /^(?!#).*(query|subscription|mutation)\s+([a-zA-Z0-9_]+)/m; - const match = regex.exec(str); - return (_ref11 = match == null ? void 0 : match[2]) !== null && - _ref11 !== void 0 - ? _ref11 - : null; - } - function clearHeadersFromTabs(storage) { - const persistedTabs = - storage == null ? void 0 : storage.get(STORAGE_KEY$2); - if (persistedTabs) { - const parsedTabs = JSON.parse(persistedTabs); - storage == null - ? void 0 - : storage.set( - STORAGE_KEY$2, - JSON.stringify(parsedTabs, (key, value) => - key === "headers" ? null : value - ) - ); - } - } - const DEFAULT_TITLE = ""; - const STORAGE_KEY$2 = "tabState"; - function useVariableEditor( - { - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onClickReference, - onEdit, - readOnly = false, - } = {}, - caller - ) { - const { initialVariables, variableEditor, setVariableEditor } = - useEditorContext({ - nonNull: true, - caller: caller || useVariableEditor, - }); - const executionContext = useExecutionContext(); - const merge = useMergeQuery({ - caller: caller || useVariableEditor, - }); - const prettify = usePrettifyEditors({ - caller: caller || useVariableEditor, - }); - const ref = React.useRef(null); - const codeMirrorRef = React.useRef(); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([ - Promise.resolve().then(() => - __webpack_require__( - /*! ./hint.cjs2.js */ "../../graphiql-react/dist/hint.cjs2.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./lint.cjs3.js */ "../../graphiql-react/dist/lint.cjs3.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./mode.cjs2.js */ "../../graphiql-react/dist/mode.cjs2.js" - ) - ), - ]).then((CodeMirror) => { - if (!isActive) { - return; - } - codeMirrorRef.current = CodeMirror; - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialVariables, - lineNumbers: true, - tabSize: 2, - mode: "graphql-variables", - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - foldGutter: true, - lint: { - // @ts-expect-error - variableToType: void 0, - }, - hintOptions: { - closeOnUnfocus: false, - completeSingle: false, - container, - // @ts-expect-error - variableToType: void 0, - }, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: commonKeys, - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: false, - container, - }); - }, - }); - newEditor.on("keyup", (editorInstance, event) => { - const { code, key, shiftKey } = event; - const isLetter = code.startsWith("Key"); - const isNumber = !shiftKey && code.startsWith("Digit"); - if (isLetter || isNumber || key === "_" || key === '"') { - editorInstance.execCommand("autocomplete"); - } - }); - setVariableEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialVariables, readOnly, setVariableEditor]); - useSynchronizeOption(variableEditor, "keyMap", keyMap); - useChangeHandler( - variableEditor, - onEdit, - STORAGE_KEY$1, - "variables", - useVariableEditor - ); - useCompletion( - variableEditor, - onClickReference || null, - useVariableEditor - ); - useKeyMap( - variableEditor, - ["Cmd-Enter", "Ctrl-Enter"], - executionContext == null ? void 0 : executionContext.run - ); - useKeyMap(variableEditor, ["Shift-Ctrl-P"], prettify); - useKeyMap(variableEditor, ["Shift-Ctrl-M"], merge); - return ref; - } - const STORAGE_KEY$1 = "variables"; - const EditorContext = createNullableContext("EditorContext"); - function EditorContextProvider(props) { - const storage = useStorageContext(); - const [headerEditor, setHeaderEditor] = React.useState(null); - const [queryEditor, setQueryEditor] = React.useState(null); - const [responseEditor, setResponseEditor] = React.useState(null); - const [variableEditor, setVariableEditor] = React.useState(null); - const [shouldPersistHeaders, setShouldPersistHeadersInternal] = - React.useState(() => { - const isStored = - (storage == null - ? void 0 - : storage.get(PERSIST_HEADERS_STORAGE_KEY)) !== null; - return props.shouldPersistHeaders !== false && isStored - ? (storage == null - ? void 0 - : storage.get(PERSIST_HEADERS_STORAGE_KEY)) === "true" - : Boolean(props.shouldPersistHeaders); - }); - useSynchronizeValue(headerEditor, props.headers); - useSynchronizeValue(queryEditor, props.query); - useSynchronizeValue(responseEditor, props.response); - useSynchronizeValue(variableEditor, props.variables); - const storeTabs = useStoreTabs({ - storage, - shouldPersistHeaders, - }); - const [initialState] = React.useState(() => { - var _ref12, - _props$query, - _ref13, - _props$variables, - _ref14, - _props$headers, - _props$response, - _ref15, - _ref16; - const query = - (_ref12 = - (_props$query = props.query) !== null && _props$query !== void 0 - ? _props$query - : storage == null - ? void 0 - : storage.get(STORAGE_KEY_QUERY)) !== null && - _ref12 !== void 0 - ? _ref12 - : null; - const variables = - (_ref13 = - (_props$variables = props.variables) !== null && - _props$variables !== void 0 - ? _props$variables - : storage == null - ? void 0 - : storage.get(STORAGE_KEY$1)) !== null && _ref13 !== void 0 - ? _ref13 - : null; - const headers = - (_ref14 = - (_props$headers = props.headers) !== null && - _props$headers !== void 0 - ? _props$headers - : storage == null - ? void 0 - : storage.get(STORAGE_KEY$3)) !== null && _ref14 !== void 0 - ? _ref14 - : null; - const response = - (_props$response = props.response) !== null && - _props$response !== void 0 - ? _props$response - : ""; - const tabState2 = getDefaultTabState({ - query, - variables, - headers, - defaultTabs: props.defaultTabs, - defaultQuery: props.defaultQuery || DEFAULT_QUERY, - defaultHeaders: props.defaultHeaders, - storage, - shouldPersistHeaders, - }); - storeTabs(tabState2); + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; return { - query: - (_ref15 = - query !== null && query !== void 0 - ? query - : tabState2.activeTabIndex === 0 - ? tabState2.tabs[0].query - : null) !== null && _ref15 !== void 0 - ? _ref15 - : "", - variables: - variables !== null && variables !== void 0 ? variables : "", - headers: - (_ref16 = - headers !== null && headers !== void 0 - ? headers - : props.defaultHeaders) !== null && _ref16 !== void 0 - ? _ref16 - : "", - response, - tabState: tabState2, + value: op[1], + done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + } + var __createBinding = exports.__createBinding = Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; + } + Object.defineProperty(o, k2, desc); + } : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + } + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o + }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), + r, + ar = [], + e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + } + + /** @deprecated */ + function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; + } + + /** @deprecated */ + function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; + return r; + } + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } + } + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: false + } : f ? f(v) : v; + } : f; + } + } + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + } + function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + return cooked; + } + ; + var __setModuleDefault = Object.create ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v + }); + } : function (o, v) { + o["default"] = v; + }; + function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + } + function __importDefault(mod) { + return mod && mod.__esModule ? mod : { + default: mod + }; + } + function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + } + function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; + } + function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + } + function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ + value: value, + dispose: dispose, + async: async + }); + } else if (async) { + env.stack.push({ + async: true + }); + } + return value; + } + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function (e) { + fail(e); + return next(); }); - const [tabState, setTabState] = React.useState(initialState.tabState); - const setShouldPersistHeaders = React.useCallback( - (persist) => { - if (persist) { - var _ref17; - storage == null - ? void 0 - : storage.set( - STORAGE_KEY$3, - (_ref17 = - headerEditor == null - ? void 0 - : headerEditor.getValue()) !== null && - _ref17 !== void 0 - ? _ref17 - : "" - ); - const serializedTabs = serializeTabState(tabState, true); - storage == null - ? void 0 - : storage.set(STORAGE_KEY$2, serializedTabs); - } else { - storage == null ? void 0 : storage.set(STORAGE_KEY$3, ""); - clearHeadersFromTabs(storage); - } - setShouldPersistHeadersInternal(persist); - storage == null - ? void 0 - : storage.set(PERSIST_HEADERS_STORAGE_KEY, persist.toString()); - }, - [storage, tabState, headerEditor] - ); - const lastShouldPersistHeadersProp = React.useRef(); - React.useEffect(() => { - const propValue = Boolean(props.shouldPersistHeaders); - if ( - (lastShouldPersistHeadersProp == null - ? void 0 - : lastShouldPersistHeadersProp.current) !== propValue - ) { - setShouldPersistHeaders(propValue); - lastShouldPersistHeadersProp.current = propValue; - } - }, [props.shouldPersistHeaders, setShouldPersistHeaders]); - const synchronizeActiveTabValues = useSynchronizeActiveTabValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor, - }); - const setEditorValues = useSetEditorValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor, - }); - const { onTabChange, defaultHeaders, children } = props; - const addTab = React.useCallback(() => { - setTabState((current) => { - const updatedValues = synchronizeActiveTabValues(current); - const updated = { - tabs: [ - ...updatedValues.tabs, - createTab({ - headers: defaultHeaders, - }), - ], - activeTabIndex: updatedValues.tabs.length, - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [ - defaultHeaders, - onTabChange, - setEditorValues, - storeTabs, - synchronizeActiveTabValues, - ]); - const changeTab = React.useCallback( - (index) => { - setTabState((current) => { - const updated = { - ...current, - activeTabIndex: index, - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, - [onTabChange, setEditorValues, storeTabs] - ); - const moveTab = React.useCallback( - (newOrder) => { - setTabState((current) => { - const activeTab = current.tabs[current.activeTabIndex]; - const updated = { - tabs: newOrder, - activeTabIndex: newOrder.indexOf(activeTab), - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, - [onTabChange, setEditorValues, storeTabs] - ); - const closeTab = React.useCallback( - (index) => { - setTabState((current) => { - const updated = { - tabs: current.tabs.filter((_tab, i) => index !== i), - activeTabIndex: Math.max(current.activeTabIndex - 1, 0), - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, - [onTabChange, setEditorValues, storeTabs] - ); - const updateActiveTabValues = React.useCallback( - (partialTab) => { - setTabState((current) => { - const updated = setPropertiesInActiveTab(current, partialTab); - storeTabs(updated); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, - [onTabChange, storeTabs] - ); - const { onEditOperationName } = props; - const setOperationName = React.useCallback( - (operationName) => { - if (!queryEditor) { - return; - } - queryEditor.operationName = operationName; - updateActiveTabValues({ - operationName, - }); - onEditOperationName == null - ? void 0 - : onEditOperationName(operationName); - }, - [onEditOperationName, queryEditor, updateActiveTabValues] - ); - const externalFragments = React.useMemo(() => { - const map = /* @__PURE__ */ new Map(); - if (Array.isArray(props.externalFragments)) { - for (const fragment of props.externalFragments) { - map.set(fragment.name.value, fragment); - } - } else if (typeof props.externalFragments === "string") { - graphql.visit(graphql.parse(props.externalFragments, {}), { - FragmentDefinition(fragment) { - map.set(fragment.name.value, fragment); - }, - }); - } else if (props.externalFragments) { - throw new Error( - "The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects." - ); + } catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); + } + var _default = exports["default"] = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources + }; + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/assignRef.js ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.assignRef = assignRef; + /** + * Assigns a value for a given ref, no matter of the ref format + * @param {RefObject} ref - a callback function or ref object + * @param value - a new value + * + * @see https://github.com/theKashey/use-callback-ref#assignref + * @example + * const refObject = useRef(); + * const refFn = (ref) => {....} + * + * assignRef(refObject, "refValue"); + * assignRef(refFn, "refValue"); + */ + function assignRef(ref, value) { + if (typeof ref === 'function') { + ref(value); + } else if (ref) { + ref.current = value; + } + return ref; + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js": + /*!***********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/createRef.js ***! + \***********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createCallbackRef = createCallbackRef; + /** + * creates a Ref object with on change callback + * @param callback + * @returns {RefObject} + * + * @see {@link useCallbackRef} + * @see https://reactjs.org/docs/refs-and-the-dom.html#creating-refs + */ + function createCallbackRef(callback) { + var current = null; + return { + get current() { + return current; + }, + set current(value) { + var last = current; + if (last !== value) { + current = value; + callback(value, last); + } + } + }; + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/index.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/index.js ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "assignRef", ({ + enumerable: true, + get: function () { + return _assignRef.assignRef; + } + })); + Object.defineProperty(exports, "createCallbackRef", ({ + enumerable: true, + get: function () { + return _createRef.createCallbackRef; + } + })); + Object.defineProperty(exports, "mergeRefs", ({ + enumerable: true, + get: function () { + return _mergeRef.mergeRefs; + } + })); + Object.defineProperty(exports, "refToCallback", ({ + enumerable: true, + get: function () { + return _refToCallback.refToCallback; + } + })); + Object.defineProperty(exports, "transformRef", ({ + enumerable: true, + get: function () { + return _transformRef.transformRef; + } + })); + Object.defineProperty(exports, "useCallbackRef", ({ + enumerable: true, + get: function () { + return _useRef.useCallbackRef; + } + })); + Object.defineProperty(exports, "useMergeRefs", ({ + enumerable: true, + get: function () { + return _useMergeRef.useMergeRefs; + } + })); + Object.defineProperty(exports, "useRefToCallback", ({ + enumerable: true, + get: function () { + return _refToCallback.useRefToCallback; + } + })); + Object.defineProperty(exports, "useTransformRef", ({ + enumerable: true, + get: function () { + return _useTransformRef.useTransformRef; + } + })); + var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); + var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); + var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); + var _mergeRef = __webpack_require__(/*! ./mergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js"); + var _useMergeRef = __webpack_require__(/*! ./useMergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js"); + var _useTransformRef = __webpack_require__(/*! ./useTransformRef */ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js"); + var _transformRef = __webpack_require__(/*! ./transformRef */ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js"); + var _refToCallback = __webpack_require__(/*! ./refToCallback */ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js"); + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js": + /*!**********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.mergeRefs = mergeRefs; + var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); + var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); + /** + * Merges two or more refs together providing a single interface to set their value + * @param {RefObject|Ref} refs + * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} + * + * @see {@link useMergeRefs} to be used in ReactComponents + * @example + * const Component = React.forwardRef((props, ref) => { + * const ownRef = useRef(); + * const domRef = mergeRefs([ref, ownRef]); // 👈 merge together + * return
    ...
    + * } + */ + function mergeRefs(refs) { + return (0, _createRef.createCallbackRef)(function (newValue) { + return refs.forEach(function (ref) { + return (0, _assignRef.assignRef)(ref, newValue); + }); + }); + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js": + /*!***************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.refToCallback = refToCallback; + exports.useRefToCallback = useRefToCallback; + /** + * Unmemoized version of {@link useRefToCallback} + * @see {@link useRefToCallback} + * @param ref + */ + function refToCallback(ref) { + return function (newValue) { + if (typeof ref === 'function') { + ref(newValue); + } else if (ref) { + ref.current = newValue; + } + }; + } + var nullCallback = function () { + return null; + }; + // lets maintain a weak ref to, well, ref :) + // not using `kashe` to keep this package small + var weakMem = new WeakMap(); + var weakMemoize = function (ref) { + var usedRef = ref || nullCallback; + var storedRef = weakMem.get(usedRef); + if (storedRef) { + return storedRef; + } + var cb = refToCallback(usedRef); + weakMem.set(usedRef, cb); + return cb; + }; + /** + * Transforms a given `ref` into `callback`. + * + * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)} + * + * @param {ReactRef} ref + * @returns {Function} + * + * @see https://github.com/theKashey/use-callback-ref#reftocallback + * + * @example + * const ref = useRef(0); + * const setRef = useRefToCallback(ref); + * 👉 setRef(10); + * ✅ ref.current === 10 + */ + function useRefToCallback(ref) { + return weakMemoize(ref); + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js": + /*!**************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/transformRef.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.transformRef = transformRef; + var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); + var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); + /** + * Transforms one ref to another + * @example + * ```tsx + * const ResizableWithRef = forwardRef((props, ref) => + * i ? i.resizable : null)}/> + * ); + * ``` + */ + function transformRef(ref, transformer) { + return (0, _createRef.createCallbackRef)(function (value) { + return (0, _assignRef.assignRef)(ref, transformer(value)); + }); + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js": + /*!*************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js ***! + \*************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.useMergeRefs = useMergeRefs; + var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); + var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); + /** + * Merges two or more refs together providing a single interface to set their value + * @param {RefObject|Ref} refs + * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} + * + * @see {@link mergeRefs} a version without buit-in memoization + * @see https://github.com/theKashey/use-callback-ref#usemergerefs + * @example + * const Component = React.forwardRef((props, ref) => { + * const ownRef = useRef(); + * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together + * return
    ...
    + * } + */ + function useMergeRefs(refs, defaultValue) { + return (0, _useRef.useCallbackRef)(defaultValue || null, function (newValue) { + return refs.forEach(function (ref) { + return (0, _assignRef.assignRef)(ref, newValue); + }); + }); + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js": + /*!********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/useRef.js ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.useCallbackRef = useCallbackRef; + var _react = __webpack_require__(/*! react */ "react"); + /** + * creates a MutableRef with ref change callback + * @param initialValue - initial ref value + * @param {Function} callback - a callback to run when value changes + * + * @example + * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue); + * ref.current = 1; + * // prints 0 -> 1 + * + * @see https://reactjs.org/docs/hooks-reference.html#useref + * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref + * @returns {MutableRefObject} + */ + function useCallbackRef(initialValue, callback) { + var ref = (0, _react.useState)(function () { + return { + // value + value: initialValue, + // last callback + callback: callback, + // "memoized" public interface + facade: { + get current() { + return ref.value; + }, + set current(value) { + var last = ref.value; + if (last !== value) { + ref.value = value; + ref.callback(value, last); + } + } + } + }; + })[0]; + // update callback + ref.callback = callback; + return ref.facade; + } + + /***/ }), + + /***/ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js": + /*!*****************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js ***! + \*****************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.useTransformRef = useTransformRef; + var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); + var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); + /** + * Create a _lense_ on Ref, making it possible to transform ref value + * @param {ReactRef} ref + * @param {Function} transformer. 👉 Ref would be __NOT updated__ on `transformer` update. + * @returns {RefObject} + * + * @see https://github.com/theKashey/use-callback-ref#usetransformref-to-replace-reactuseimperativehandle + * @example + * + * const ResizableWithRef = forwardRef((props, ref) => + * i ? i.resizable : null)}/> + * ); + */ + function useTransformRef(ref, transformer) { + return (0, _useRef.useCallbackRef)(null, function (value) { + return (0, _assignRef.assignRef)(ref, transformer(value)); + }); + } + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/config.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/config.js ***! + \***************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.setConfig = exports.config = void 0; + var config = exports.config = { + onError: function (e) { + return console.error(e); + } + }; + var setConfig = function (conf) { + Object.assign(config, conf); + }; + exports.setConfig = setConfig; + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/env.js": + /*!************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/env.js ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.env = void 0; + var _detectNodeEs = __webpack_require__(/*! detect-node-es */ "../../../node_modules/detect-node-es/esm/browser.js"); + var env = exports.env = { + isNode: _detectNodeEs.isNode, + forceCache: false + }; + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/exports.js": + /*!****************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/exports.js ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.exportSidecar = exportSidecar; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + var SideCar = function (_a) { + var sideCar = _a.sideCar, + rest = (0, _tslib.__rest)(_a, ["sideCar"]); + if (!sideCar) { + throw new Error('Sidecar: please provide `sideCar` property to import the right car'); + } + var Target = sideCar.read(); + if (!Target) { + throw new Error('Sidecar medium not found'); + } + return /*#__PURE__*/React.createElement(Target, (0, _tslib.__assign)({}, rest)); + }; + SideCar.isSideCarExport = true; + function exportSidecar(medium, exported) { + medium.useMedium(exported); + return SideCar; + } + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/hoc.js": + /*!************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/hoc.js ***! + \************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.sidecar = sidecar; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + // eslint-disable-next-line @typescript-eslint/ban-types + function sidecar(importer, errorComponent) { + var ErrorCase = function () { + return errorComponent; + }; + return function Sidecar(props) { + var _a = (0, _hook.useSidecar)(importer, props.sideCar), + Car = _a[0], + error = _a[1]; + if (error && errorComponent) { + return ErrorCase; + } + // @ts-expect-error type shenanigans + return Car ? /*#__PURE__*/React.createElement(Car, (0, _tslib.__assign)({}, props)) : null; + }; + } + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/hook.js": + /*!*************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/hook.js ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.useSidecar = useSidecar; + var _react = __webpack_require__(/*! react */ "react"); + var _env = __webpack_require__(/*! ./env */ "../../../node_modules/use-sidecar/dist/es2015/env.js"); + var cache = new WeakMap(); + var NO_OPTIONS = {}; + function useSidecar(importer, effect) { + var options = effect && effect.options || NO_OPTIONS; + if (_env.env.isNode && !options.ssr) { + return [null, null]; + } + // eslint-disable-next-line react-hooks/rules-of-hooks + return useRealSidecar(importer, effect); + } + function useRealSidecar(importer, effect) { + var options = effect && effect.options || NO_OPTIONS; + var couldUseCache = _env.env.forceCache || _env.env.isNode && !!options.ssr || !options.async; + var _a = (0, _react.useState)(couldUseCache ? function () { + return cache.get(importer); + } : undefined), + Car = _a[0], + setCar = _a[1]; + var _b = (0, _react.useState)(null), + error = _b[0], + setError = _b[1]; + (0, _react.useEffect)(function () { + if (!Car) { + importer().then(function (car) { + var resolved = effect ? effect.read() : car.default || car; + if (!resolved) { + console.error('Sidecar error: with importer', importer); + var error_1; + if (effect) { + console.error('Sidecar error: with medium', effect); + error_1 = new Error('Sidecar medium was not found'); + } else { + error_1 = new Error('Sidecar was not found in exports'); } - return map; - }, [props.externalFragments]); - const validationRules = React.useMemo( - () => props.validationRules || [], - [props.validationRules] - ); - const value = React.useMemo( - () => ({ - ...tabState, - addTab, - changeTab, - moveTab, - closeTab, - updateActiveTabValues, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - setHeaderEditor, - setQueryEditor, - setResponseEditor, - setVariableEditor, - setOperationName, - initialQuery: initialState.query, - initialVariables: initialState.variables, - initialHeaders: initialState.headers, - initialResponse: initialState.response, - externalFragments, - validationRules, - shouldPersistHeaders, - setShouldPersistHeaders, - }), - [ - tabState, - addTab, - changeTab, - moveTab, - closeTab, - updateActiveTabValues, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - setOperationName, - initialState, - externalFragments, - validationRules, - shouldPersistHeaders, - setShouldPersistHeaders, - ] - ); - return /* @__PURE__ */ jsxRuntime.jsx(EditorContext.Provider, { - value, - children, - }); - } - const useEditorContext = createContextHook(EditorContext); - const PERSIST_HEADERS_STORAGE_KEY = "shouldPersistHeaders"; - const DEFAULT_QUERY = `# Welcome to GraphiQL -# -# GraphiQL is an in-browser tool for writing, validating, and -# testing GraphQL queries. -# -# Type queries into this side of the screen, and you will see intelligent -# typeaheads aware of the current GraphQL type schema and live syntax and -# validation errors highlighted within the text. -# -# GraphQL queries typically start with a "{" character. Lines that start -# with a # are ignored. -# -# An example GraphQL query might look like: -# -# { -# field(arg: "value") { -# subField -# } -# } -# -# Keyboard shortcuts: -# -# Prettify query: Shift-Ctrl-P (or press the prettify button) -# -# Merge fragments: Shift-Ctrl-M (or press the merge button) -# -# Run Query: Ctrl-Enter (or press the play button) -# -# Auto Complete: Ctrl-Space (or just start typing) -# - -`; - function HeaderEditor({ isHidden, ...hookArgs }) { - const { headerEditor } = useEditorContext({ - nonNull: true, - caller: HeaderEditor, + setError(function () { + return error_1; + }); + throw error_1; + } + cache.set(importer, resolved); + setCar(function () { + return resolved; }); - const ref = useHeaderEditor(hookArgs, HeaderEditor); - React.useEffect(() => { - if (!isHidden) { - headerEditor == null ? void 0 : headerEditor.refresh(); - } - }, [headerEditor, isHidden]); - return /* @__PURE__ */ jsxRuntime.jsx("div", { - className: clsx.clsx("graphiql-editor", isHidden && "hidden"), - ref, + }, function (e) { + return setError(function () { + return e; }); + }); + } + }, []); + return [Car, error]; + } + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/index.js": + /*!**************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/index.js ***! + \**************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "createMedium", ({ + enumerable: true, + get: function () { + return _medium.createMedium; + } + })); + Object.defineProperty(exports, "createSidecarMedium", ({ + enumerable: true, + get: function () { + return _medium.createSidecarMedium; + } + })); + Object.defineProperty(exports, "exportSidecar", ({ + enumerable: true, + get: function () { + return _exports.exportSidecar; + } + })); + Object.defineProperty(exports, "renderCar", ({ + enumerable: true, + get: function () { + return _renderProp.renderCar; + } + })); + Object.defineProperty(exports, "setConfig", ({ + enumerable: true, + get: function () { + return _config.setConfig; + } + })); + Object.defineProperty(exports, "sidecar", ({ + enumerable: true, + get: function () { + return _hoc.sidecar; + } + })); + Object.defineProperty(exports, "useSidecar", ({ + enumerable: true, + get: function () { + return _hook.useSidecar; + } + })); + var _hoc = __webpack_require__(/*! ./hoc */ "../../../node_modules/use-sidecar/dist/es2015/hoc.js"); + var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); + var _config = __webpack_require__(/*! ./config */ "../../../node_modules/use-sidecar/dist/es2015/config.js"); + var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/use-sidecar/dist/es2015/medium.js"); + var _renderProp = __webpack_require__(/*! ./renderProp */ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js"); + var _exports = __webpack_require__(/*! ./exports */ "../../../node_modules/use-sidecar/dist/es2015/exports.js"); + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/medium.js": + /*!***************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/medium.js ***! + \***************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createMedium = createMedium; + exports.createSidecarMedium = createSidecarMedium; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + function ItoI(a) { + return a; + } + function innerCreateMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + var buffer = []; + var assigned = false; + var medium = { + read: function () { + if (assigned) { + throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.'); } - function ImagePreview(props) { - var _a; - const [dimensions, setDimensions] = React.useState({ - width: null, - height: null, - }); - const [mime, setMime] = React.useState(null); - const ref = React.useRef(null); - const src = (_a = tokenToURL(props.token)) == null ? void 0 : _a.href; - React.useEffect(() => { - if (!ref.current) { - return; - } - if (!src) { - setDimensions({ - width: null, - height: null, - }); - setMime(null); - return; - } - fetch(src, { - method: "HEAD", - }) - .then((response) => { - setMime(response.headers.get("Content-Type")); - }) - .catch(() => { - setMime(null); - }); - }, [src]); - const dims = - dimensions.width !== null && dimensions.height !== null - ? /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - dimensions.width, - "x", - dimensions.height, - mime === null ? null : " " + mime, - ], - }) - : null; - return /* @__PURE__ */ jsxRuntime.jsxs("div", { - children: [ - /* @__PURE__ */ jsxRuntime.jsx("img", { - onLoad: () => { - var _ref18, _ref19; - var _a2, _b; - setDimensions({ - width: - (_ref18 = - (_a2 = ref.current) == null - ? void 0 - : _a2.naturalWidth) !== null && _ref18 !== void 0 - ? _ref18 - : null, - height: - (_ref19 = - (_b = ref.current) == null - ? void 0 - : _b.naturalHeight) !== null && _ref19 !== void 0 - ? _ref19 - : null, - }); - }, - ref, - src, - }), - dims, - ], - }); + if (buffer.length) { + return buffer[buffer.length - 1]; } - ImagePreview.shouldRender = function shouldRender(token) { - const url = tokenToURL(token); - return url ? isImageURL(url) : false; + return defaults; + }, + useMedium: function (data) { + var item = middleware(data, assigned); + buffer.push(item); + return function () { + buffer = buffer.filter(function (x) { + return x !== item; + }); }; - function tokenToURL(token) { - if (token.type !== "string") { - return; + }, + assignSyncMedium: function (cb) { + assigned = true; + while (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + } + buffer = { + push: function (x) { + return cb(x); + }, + filter: function () { + return buffer; } - const value = token.string.slice(1).slice(0, -1).trim(); - try { - const { location } = window; - return new URL(value, location.protocol + "//" + location.host); - } catch { - return; + }; + }, + assignMedium: function (cb) { + assigned = true; + var pendingQueue = []; + if (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + pendingQueue = buffer; + } + var executeQueue = function () { + var cbs = pendingQueue; + pendingQueue = []; + cbs.forEach(cb); + }; + var cycle = function () { + return Promise.resolve().then(executeQueue); + }; + cycle(); + buffer = { + push: function (x) { + pendingQueue.push(x); + cycle(); + }, + filter: function (filter) { + pendingQueue = pendingQueue.filter(filter); + return buffer; } + }; + } + }; + return medium; + } + function createMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + return innerCreateMedium(defaults, middleware); + } + // eslint-disable-next-line @typescript-eslint/ban-types + function createSidecarMedium(options) { + if (options === void 0) { + options = {}; + } + var medium = innerCreateMedium(null); + medium.options = (0, _tslib.__assign)({ + async: true, + ssr: false + }, options); + return medium; + } + + /***/ }), + + /***/ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js": + /*!*******************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/renderProp.js ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.renderCar = renderCar; + var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); + var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var React = _react; + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + function renderCar(WrappedComponent, defaults) { + function State(_a) { + var stateRef = _a.stateRef, + props = _a.props; + var renderTarget = (0, _react.useCallback)(function SideTarget() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + (0, _react.useLayoutEffect)(function () { + stateRef.current(args); + }); + return null; + }, []); + // @ts-ignore + return /*#__PURE__*/React.createElement(WrappedComponent, (0, _tslib.__assign)({}, props, { + children: renderTarget + })); + } + var Children = /*#__PURE__*/React.memo(function (_a) { + var stateRef = _a.stateRef, + defaultState = _a.defaultState, + children = _a.children; + var _b = (0, _react.useState)(defaultState.current), + state = _b[0], + setState = _b[1]; + (0, _react.useEffect)(function () { + stateRef.current = setState; + }, []); + return children.apply(void 0, state); + }, function () { + return true; + }); + return function Combiner(props) { + var defaultState = React.useRef(defaults(props)); + var ref = React.useRef(function (state) { + return defaultState.current = state; + }); + return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(State, { + stateRef: ref, + props: props + }), /*#__PURE__*/React.createElement(Children, { + stateRef: ref, + defaultState: defaultState, + children: props.children + })); + }; + } + + /***/ }), + + /***/ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js": + /*!*************************************************************************!*\ + !*** ../../../node_modules/vscode-languageserver-types/lib/esm/main.js ***! + \*************************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + /* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.uinteger = exports.integer = exports.WorkspaceSymbol = exports.WorkspaceFolder = exports.WorkspaceEdit = exports.WorkspaceChange = exports.VersionedTextDocumentIdentifier = exports.URI = exports.TextEdit = exports.TextDocumentItem = exports.TextDocumentIdentifier = exports.TextDocumentEdit = exports.TextDocument = exports.SymbolTag = exports.SymbolKind = exports.SymbolInformation = exports.SignatureInformation = exports.SemanticTokens = exports.SemanticTokenTypes = exports.SemanticTokenModifiers = exports.SelectionRange = exports.RenameFile = exports.Range = exports.Position = exports.ParameterInformation = exports.OptionalVersionedTextDocumentIdentifier = exports.MarkupKind = exports.MarkupContent = exports.MarkedString = exports.LocationLink = exports.Location = exports.InsertTextMode = exports.InsertTextFormat = exports.InsertReplaceEdit = exports.InlineValueVariableLookup = exports.InlineValueText = exports.InlineValueEvaluatableExpression = exports.InlineValueContext = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlayHint = exports.Hover = exports.FormattingOptions = exports.FoldingRangeKind = exports.FoldingRange = exports.EOL = exports.DocumentUri = exports.DocumentSymbol = exports.DocumentLink = exports.DocumentHighlightKind = exports.DocumentHighlight = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.Diagnostic = exports.DeleteFile = exports.CreateFile = exports.CompletionList = exports.CompletionItemTag = exports.CompletionItemLabelDetails = exports.CompletionItemKind = exports.CompletionItem = exports.Command = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.CodeLens = exports.CodeDescription = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.CodeActionContext = exports.CodeAction = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.AnnotatedTextEdit = void 0; + var DocumentUri; + (function (DocumentUri) { + function is(value) { + return typeof value === 'string'; + } + DocumentUri.is = is; + })(DocumentUri || (exports.DocumentUri = DocumentUri = {})); + var URI; + (function (URI) { + function is(value) { + return typeof value === 'string'; + } + URI.is = is; + })(URI || (exports.URI = URI = {})); + var integer; + (function (integer) { + integer.MIN_VALUE = -2147483648; + integer.MAX_VALUE = 2147483647; + function is(value) { + return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE; + } + integer.is = is; + })(integer || (exports.integer = integer = {})); + var uinteger; + (function (uinteger) { + uinteger.MIN_VALUE = 0; + uinteger.MAX_VALUE = 2147483647; + function is(value) { + return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE; + } + uinteger.is = is; + })(uinteger || (exports.uinteger = uinteger = {})); + /** + * The Position namespace provides helper functions to work with + * {@link Position} literals. + */ + var Position; + (function (Position) { + /** + * Creates a new Position literal from the given line and character. + * @param line The position's line. + * @param character The position's character. + */ + function create(line, character) { + if (line === Number.MAX_VALUE) { + line = uinteger.MAX_VALUE; + } + if (character === Number.MAX_VALUE) { + character = uinteger.MAX_VALUE; + } + return { + line: line, + character: character + }; + } + Position.create = create; + /** + * Checks whether the given literal conforms to the {@link Position} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); + } + Position.is = is; + })(Position || (exports.Position = Position = {})); + /** + * The Range namespace provides helper functions to work with + * {@link Range} literals. + */ + var Range; + (function (Range) { + function create(one, two, three, four) { + if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { + return { + start: Position.create(one, two), + end: Position.create(three, four) + }; + } else if (Position.is(one) && Position.is(two)) { + return { + start: one, + end: two + }; + } else { + throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]")); + } + } + Range.create = create; + /** + * Checks whether the given literal conforms to the {@link Range} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); + } + Range.is = is; + })(Range || (exports.Range = Range = {})); + /** + * The Location namespace provides helper functions to work with + * {@link Location} literals. + */ + var Location; + (function (Location) { + /** + * Creates a Location literal. + * @param uri The location's uri. + * @param range The location's range. + */ + function create(uri, range) { + return { + uri: uri, + range: range + }; + } + Location.create = create; + /** + * Checks whether the given literal conforms to the {@link Location} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); + } + Location.is = is; + })(Location || (exports.Location = Location = {})); + /** + * The LocationLink namespace provides helper functions to work with + * {@link LocationLink} literals. + */ + var LocationLink; + (function (LocationLink) { + /** + * Creates a LocationLink literal. + * @param targetUri The definition's uri. + * @param targetRange The full range of the definition. + * @param targetSelectionRange The span of the symbol definition at the target. + * @param originSelectionRange The span of the symbol being defined in the originating source file. + */ + function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { + return { + targetUri: targetUri, + targetRange: targetRange, + targetSelectionRange: targetSelectionRange, + originSelectionRange: originSelectionRange + }; + } + LocationLink.create = create; + /** + * Checks whether the given literal conforms to the {@link LocationLink} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); + } + LocationLink.is = is; + })(LocationLink || (exports.LocationLink = LocationLink = {})); + /** + * The Color namespace provides helper functions to work with + * {@link Color} literals. + */ + var Color; + (function (Color) { + /** + * Creates a new Color literal. + */ + function create(red, green, blue, alpha) { + return { + red: red, + green: green, + blue: blue, + alpha: alpha + }; + } + Color.create = create; + /** + * Checks whether the given literal conforms to the {@link Color} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); + } + Color.is = is; + })(Color || (exports.Color = Color = {})); + /** + * The ColorInformation namespace provides helper functions to work with + * {@link ColorInformation} literals. + */ + var ColorInformation; + (function (ColorInformation) { + /** + * Creates a new ColorInformation literal. + */ + function create(range, color) { + return { + range: range, + color: color + }; + } + ColorInformation.create = create; + /** + * Checks whether the given literal conforms to the {@link ColorInformation} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color); + } + ColorInformation.is = is; + })(ColorInformation || (exports.ColorInformation = ColorInformation = {})); + /** + * The Color namespace provides helper functions to work with + * {@link ColorPresentation} literals. + */ + var ColorPresentation; + (function (ColorPresentation) { + /** + * Creates a new ColorInformation literal. + */ + function create(label, textEdit, additionalTextEdits) { + return { + label: label, + textEdit: textEdit, + additionalTextEdits: additionalTextEdits + }; + } + ColorPresentation.create = create; + /** + * Checks whether the given literal conforms to the {@link ColorInformation} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); + } + ColorPresentation.is = is; + })(ColorPresentation || (exports.ColorPresentation = ColorPresentation = {})); + /** + * A set of predefined range kinds. + */ + var FoldingRangeKind; + (function (FoldingRangeKind) { + /** + * Folding range for a comment + */ + FoldingRangeKind.Comment = 'comment'; + /** + * Folding range for an import or include + */ + FoldingRangeKind.Imports = 'imports'; + /** + * Folding range for a region (e.g. `#region`) + */ + FoldingRangeKind.Region = 'region'; + })(FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {})); + /** + * The folding range namespace provides helper functions to work with + * {@link FoldingRange} literals. + */ + var FoldingRange; + (function (FoldingRange) { + /** + * Creates a new FoldingRange literal. + */ + function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) { + var result = { + startLine: startLine, + endLine: endLine + }; + if (Is.defined(startCharacter)) { + result.startCharacter = startCharacter; + } + if (Is.defined(endCharacter)) { + result.endCharacter = endCharacter; + } + if (Is.defined(kind)) { + result.kind = kind; + } + if (Is.defined(collapsedText)) { + result.collapsedText = collapsedText; + } + return result; + } + FoldingRange.create = create; + /** + * Checks whether the given literal conforms to the {@link FoldingRange} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); + } + FoldingRange.is = is; + })(FoldingRange || (exports.FoldingRange = FoldingRange = {})); + /** + * The DiagnosticRelatedInformation namespace provides helper functions to work with + * {@link DiagnosticRelatedInformation} literals. + */ + var DiagnosticRelatedInformation; + (function (DiagnosticRelatedInformation) { + /** + * Creates a new DiagnosticRelatedInformation literal. + */ + function create(location, message) { + return { + location: location, + message: message + }; + } + DiagnosticRelatedInformation.create = create; + /** + * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); + } + DiagnosticRelatedInformation.is = is; + })(DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {})); + /** + * The diagnostic's severity. + */ + var DiagnosticSeverity; + (function (DiagnosticSeverity) { + /** + * Reports an error. + */ + DiagnosticSeverity.Error = 1; + /** + * Reports a warning. + */ + DiagnosticSeverity.Warning = 2; + /** + * Reports an information. + */ + DiagnosticSeverity.Information = 3; + /** + * Reports a hint. + */ + DiagnosticSeverity.Hint = 4; + })(DiagnosticSeverity || (exports.DiagnosticSeverity = DiagnosticSeverity = {})); + /** + * The diagnostic tags. + * + * @since 3.15.0 + */ + var DiagnosticTag; + (function (DiagnosticTag) { + /** + * Unused or unnecessary code. + * + * Clients are allowed to render diagnostics with this tag faded out instead of having + * an error squiggle. + */ + DiagnosticTag.Unnecessary = 1; + /** + * Deprecated or obsolete code. + * + * Clients are allowed to rendered diagnostics with this tag strike through. + */ + DiagnosticTag.Deprecated = 2; + })(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {})); + /** + * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. + * + * @since 3.16.0 + */ + var CodeDescription; + (function (CodeDescription) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.href); + } + CodeDescription.is = is; + })(CodeDescription || (exports.CodeDescription = CodeDescription = {})); + /** + * The Diagnostic namespace provides helper functions to work with + * {@link Diagnostic} literals. + */ + var Diagnostic; + (function (Diagnostic) { + /** + * Creates a new Diagnostic literal. + */ + function create(range, message, severity, code, source, relatedInformation) { + var result = { + range: range, + message: message + }; + if (Is.defined(severity)) { + result.severity = severity; + } + if (Is.defined(code)) { + result.code = code; + } + if (Is.defined(source)) { + result.source = source; + } + if (Is.defined(relatedInformation)) { + result.relatedInformation = relatedInformation; + } + return result; + } + Diagnostic.create = create; + /** + * Checks whether the given literal conforms to the {@link Diagnostic} interface. + */ + function is(value) { + var _a; + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); + } + Diagnostic.is = is; + })(Diagnostic || (exports.Diagnostic = Diagnostic = {})); + /** + * The Command namespace provides helper functions to work with + * {@link Command} literals. + */ + var Command; + (function (Command) { + /** + * Creates a new Command literal. + */ + function create(title, command) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var result = { + title: title, + command: command + }; + if (Is.defined(args) && args.length > 0) { + result.arguments = args; + } + return result; + } + Command.create = create; + /** + * Checks whether the given literal conforms to the {@link Command} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); + } + Command.is = is; + })(Command || (exports.Command = Command = {})); + /** + * The TextEdit namespace provides helper function to create replace, + * insert and delete edits more easily. + */ + var TextEdit; + (function (TextEdit) { + /** + * Creates a replace text edit. + * @param range The range of text to be replaced. + * @param newText The new text. + */ + function replace(range, newText) { + return { + range: range, + newText: newText + }; + } + TextEdit.replace = replace; + /** + * Creates an insert text edit. + * @param position The position to insert the text at. + * @param newText The text to be inserted. + */ + function insert(position, newText) { + return { + range: { + start: position, + end: position + }, + newText: newText + }; + } + TextEdit.insert = insert; + /** + * Creates a delete text edit. + * @param range The range of text to be deleted. + */ + function del(range) { + return { + range: range, + newText: '' + }; + } + TextEdit.del = del; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); + } + TextEdit.is = is; + })(TextEdit || (exports.TextEdit = TextEdit = {})); + var ChangeAnnotation; + (function (ChangeAnnotation) { + function create(label, needsConfirmation, description) { + var result = { + label: label + }; + if (needsConfirmation !== undefined) { + result.needsConfirmation = needsConfirmation; + } + if (description !== undefined) { + result.description = description; + } + return result; + } + ChangeAnnotation.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined); + } + ChangeAnnotation.is = is; + })(ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {})); + var ChangeAnnotationIdentifier; + (function (ChangeAnnotationIdentifier) { + function is(value) { + var candidate = value; + return Is.string(candidate); + } + ChangeAnnotationIdentifier.is = is; + })(ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {})); + var AnnotatedTextEdit; + (function (AnnotatedTextEdit) { + /** + * Creates an annotated replace text edit. + * + * @param range The range of text to be replaced. + * @param newText The new text. + * @param annotation The annotation. + */ + function replace(range, newText, annotation) { + return { + range: range, + newText: newText, + annotationId: annotation + }; + } + AnnotatedTextEdit.replace = replace; + /** + * Creates an annotated insert text edit. + * + * @param position The position to insert the text at. + * @param newText The text to be inserted. + * @param annotation The annotation. + */ + function insert(position, newText, annotation) { + return { + range: { + start: position, + end: position + }, + newText: newText, + annotationId: annotation + }; + } + AnnotatedTextEdit.insert = insert; + /** + * Creates an annotated delete text edit. + * + * @param range The range of text to be deleted. + * @param annotation The annotation. + */ + function del(range, annotation) { + return { + range: range, + newText: '', + annotationId: annotation + }; + } + AnnotatedTextEdit.del = del; + function is(value) { + var candidate = value; + return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + AnnotatedTextEdit.is = is; + })(AnnotatedTextEdit || (exports.AnnotatedTextEdit = AnnotatedTextEdit = {})); + /** + * The TextDocumentEdit namespace provides helper function to create + * an edit that manipulates a text document. + */ + var TextDocumentEdit; + (function (TextDocumentEdit) { + /** + * Creates a new `TextDocumentEdit` + */ + function create(textDocument, edits) { + return { + textDocument: textDocument, + edits: edits + }; + } + TextDocumentEdit.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); + } + TextDocumentEdit.is = is; + })(TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {})); + var CreateFile; + (function (CreateFile) { + function create(uri, options, annotation) { + var result = { + kind: 'create', + uri: uri + }; + if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { + result.options = options; + } + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + CreateFile.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + CreateFile.is = is; + })(CreateFile || (exports.CreateFile = CreateFile = {})); + var RenameFile; + (function (RenameFile) { + function create(oldUri, newUri, options, annotation) { + var result = { + kind: 'rename', + oldUri: oldUri, + newUri: newUri + }; + if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { + result.options = options; + } + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + RenameFile.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + RenameFile.is = is; + })(RenameFile || (exports.RenameFile = RenameFile = {})); + var DeleteFile; + (function (DeleteFile) { + function create(uri, options, annotation) { + var result = { + kind: 'delete', + uri: uri + }; + if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) { + result.options = options; + } + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + DeleteFile.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + DeleteFile.is = is; + })(DeleteFile || (exports.DeleteFile = DeleteFile = {})); + var WorkspaceEdit; + (function (WorkspaceEdit) { + function is(value) { + var candidate = value; + return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) { + if (Is.string(change.kind)) { + return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); + } else { + return TextDocumentEdit.is(change); } - function isImageURL(url) { - return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname); - } - function QueryEditor(props) { - const ref = useQueryEditor(props, QueryEditor); - return /* @__PURE__ */ jsxRuntime.jsx("div", { - className: "graphiql-editor", - ref, - }); - } - function useResponseEditor( - { - responseTooltip, - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - } = {}, - caller - ) { - const { fetchError, validationErrors } = useSchemaContext({ - nonNull: true, - caller: caller || useResponseEditor, - }); - const { initialResponse, responseEditor, setResponseEditor } = - useEditorContext({ - nonNull: true, - caller: caller || useResponseEditor, - }); - const ref = React.useRef(null); - const responseTooltipRef = React.useRef(responseTooltip); - React.useEffect(() => { - responseTooltipRef.current = responseTooltip; - }, [responseTooltip]); - React.useEffect(() => { - let isActive = true; - void importCodeMirror( - [ - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js" - ) - ) - .then((n) => n.foldgutter), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js" - ) - ) - .then((n) => n.braceFold), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" - ) - ) - .then((n) => n.dialog), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js" - ) - ) - .then((n) => n.search), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js" - ) - ) - .then((n) => n.searchcursor), - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js" - ) - ) - .then((n) => n.jumpToLine), - // @ts-expect-error - Promise.resolve() - .then(() => - __webpack_require__( - /*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js" - ) - ) - .then((n) => n.sublime), - Promise.resolve().then(() => - __webpack_require__( - /*! ./mode.cjs3.js */ "../../graphiql-react/dist/mode.cjs3.js" - ) - ), - Promise.resolve().then(() => - __webpack_require__( - /*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js" - ) - ), - ], - { - useCommonAddons: false, - } - ).then((CodeMirror) => { - if (!isActive) { - return; - } - const tooltipDiv = document.createElement("div"); - CodeMirror.registerHelper( - "info", - "graphql-results", - (token, _options, _cm, pos) => { - const infoElements = []; - const ResponseTooltipComponent = responseTooltipRef.current; - if (ResponseTooltipComponent) { - infoElements.push( - /* @__PURE__ */ jsxRuntime.jsx(ResponseTooltipComponent, { - pos, - token, - }) - ); - } - if (ImagePreview.shouldRender(token)) { - infoElements.push( - /* @__PURE__ */ jsxRuntime.jsx( - ImagePreview, - { - token, - }, - "image-preview" - ) - ); - } - if (!infoElements.length) { - ReactDOM.unmountComponentAtNode(tooltipDiv); - return null; - } - ReactDOM.render(infoElements, tooltipDiv); - return tooltipDiv; - } - ); - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialResponse, - lineWrapping: true, - readOnly: true, - theme: editorTheme, - mode: "graphql-results", - foldGutter: true, - gutters: ["CodeMirror-foldgutter"], - // @ts-expect-error - info: true, - extraKeys: commonKeys, - }); - setResponseEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialResponse, setResponseEditor]); - useSynchronizeOption(responseEditor, "keyMap", keyMap); - React.useEffect(() => { - if (fetchError) { - responseEditor == null - ? void 0 - : responseEditor.setValue(fetchError); - } - if (validationErrors.length > 0) { - responseEditor == null - ? void 0 - : responseEditor.setValue( - toolkit.formatError(validationErrors) - ); - } - }, [responseEditor, fetchError, validationErrors]); - return ref; - } - function ResponseEditor(props) { - const ref = useResponseEditor(props, ResponseEditor); - return /* @__PURE__ */ jsxRuntime.jsx("section", { - className: "result-window", - "aria-label": "Result Window", - "aria-live": "polite", - "aria-atomic": "true", - ref, - }); - } - function VariableEditor({ isHidden, ...hookArgs }) { - const { variableEditor } = useEditorContext({ - nonNull: true, - caller: VariableEditor, - }); - const ref = useVariableEditor(hookArgs, VariableEditor); - React.useEffect(() => { - if (variableEditor && !isHidden) { - variableEditor.refresh(); - } - }, [variableEditor, isHidden]); - return /* @__PURE__ */ jsxRuntime.jsx("div", { - className: clsx.clsx("graphiql-editor", isHidden && "hidden"), - ref, - }); - } - function GraphiQLProvider({ - children, - dangerouslyAssumeSchemaIsValid, - defaultQuery, - defaultHeaders, - defaultTabs, - externalFragments, - fetcher, - getDefaultFieldNames, - headers, - inputValueDeprecation, - introspectionQueryName, - maxHistoryLength, - onEditOperationName, - onSchemaChange, - onTabChange, - onTogglePluginVisibility, - operationName, - plugins, - query, - response, - schema, - schemaDescription, - shouldPersistHeaders, - storage, - validationRules, - variables, - visiblePlugin, - }) { - return /* @__PURE__ */ jsxRuntime.jsx(StorageContextProvider, { - storage, - children: /* @__PURE__ */ jsxRuntime.jsx(HistoryContextProvider, { - maxHistoryLength, - children: /* @__PURE__ */ jsxRuntime.jsx(EditorContextProvider, { - defaultQuery, - defaultHeaders, - defaultTabs, - externalFragments, - headers, - onEditOperationName, - onTabChange, - query, - response, - shouldPersistHeaders, - validationRules, - variables, - children: /* @__PURE__ */ jsxRuntime.jsx( - SchemaContextProvider, - { - dangerouslyAssumeSchemaIsValid, - fetcher, - inputValueDeprecation, - introspectionQueryName, - onSchemaChange, - schema, - schemaDescription, - children: /* @__PURE__ */ jsxRuntime.jsx( - ExecutionContextProvider, - { - getDefaultFieldNames, - fetcher, - operationName, - children: /* @__PURE__ */ jsxRuntime.jsx( - ExplorerContextProvider, - { - children: /* @__PURE__ */ jsxRuntime.jsx( - PluginContextProvider, - { - onTogglePluginVisibility, - plugins, - visiblePlugin, - children, - } - ), - } - ), - } - ), - } - ), - }), - }), - }); - } - function useTheme() { - const storageContext = useStorageContext(); - const [theme, setThemeInternal] = React.useState(() => { - if (!storageContext) { - return null; - } - const stored = storageContext.get(STORAGE_KEY); - switch (stored) { - case "light": - return "light"; - case "dark": - return "dark"; - default: - if (typeof stored === "string") { - storageContext.set(STORAGE_KEY, ""); - } - return null; - } - }); - React.useLayoutEffect(() => { - if (typeof window === "undefined") { - return; - } - document.body.classList.remove("graphiql-light", "graphiql-dark"); - if (theme) { - document.body.classList.add(`graphiql-${theme}`); - } - }, [theme]); - const setTheme = React.useCallback( - (newTheme) => { - storageContext == null - ? void 0 - : storageContext.set(STORAGE_KEY, newTheme || ""); - setThemeInternal(newTheme); - }, - [storageContext] - ); - return React.useMemo( - () => ({ - theme, - setTheme, - }), - [theme, setTheme] - ); + })); + } + WorkspaceEdit.is = is; + })(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {})); + var TextEditChangeImpl = /** @class */function () { + function TextEditChangeImpl(edits, changeAnnotations) { + this.edits = edits; + this.changeAnnotations = changeAnnotations; + } + TextEditChangeImpl.prototype.insert = function (position, newText, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.insert(position, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.insert(position, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.insert(position, newText, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.replace = function (range, newText, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.replace(range, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.replace(range, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.replace(range, newText, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.delete = function (range, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.del(range); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.del(range, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.del(range, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.add = function (edit) { + this.edits.push(edit); + }; + TextEditChangeImpl.prototype.all = function () { + return this.edits; + }; + TextEditChangeImpl.prototype.clear = function () { + this.edits.splice(0, this.edits.length); + }; + TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) { + if (value === undefined) { + throw new Error("Text edit change is not configured to manage change annotations."); + } + }; + return TextEditChangeImpl; + }(); + /** + * A helper class + */ + var ChangeAnnotations = /** @class */function () { + function ChangeAnnotations(annotations) { + this._annotations = annotations === undefined ? Object.create(null) : annotations; + this._counter = 0; + this._size = 0; + } + ChangeAnnotations.prototype.all = function () { + return this._annotations; + }; + Object.defineProperty(ChangeAnnotations.prototype, "size", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) { + var id; + if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { + id = idOrAnnotation; + } else { + id = this.nextId(); + annotation = idOrAnnotation; + } + if (this._annotations[id] !== undefined) { + throw new Error("Id ".concat(id, " is already in use.")); + } + if (annotation === undefined) { + throw new Error("No annotation provided for id ".concat(id)); + } + this._annotations[id] = annotation; + this._size++; + return id; + }; + ChangeAnnotations.prototype.nextId = function () { + this._counter++; + return this._counter.toString(); + }; + return ChangeAnnotations; + }(); + /** + * A workspace change helps constructing changes to a workspace. + */ + var WorkspaceChange = exports.WorkspaceChange = /** @class */function () { + function WorkspaceChange(workspaceEdit) { + var _this = this; + this._textEditChanges = Object.create(null); + if (workspaceEdit !== undefined) { + this._workspaceEdit = workspaceEdit; + if (workspaceEdit.documentChanges) { + this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); + workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + workspaceEdit.documentChanges.forEach(function (change) { + if (TextDocumentEdit.is(change)) { + var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); + _this._textEditChanges[change.textDocument.uri] = textEditChange; + } + }); + } else if (workspaceEdit.changes) { + Object.keys(workspaceEdit.changes).forEach(function (key) { + var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); + _this._textEditChanges[key] = textEditChange; + }); + } + } else { + this._workspaceEdit = {}; + } + } + Object.defineProperty(WorkspaceChange.prototype, "edit", { + /** + * Returns the underlying {@link WorkspaceEdit} literal + * use to be returned from a workspace edit operation like rename. + */ + get: function () { + this.initDocumentChanges(); + if (this._changeAnnotations !== undefined) { + if (this._changeAnnotations.size === 0) { + this._workspaceEdit.changeAnnotations = undefined; + } else { + this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + } } - const STORAGE_KEY = "theme"; - function useDragResize({ - defaultSizeRelation = DEFAULT_FLEX, - direction, - initiallyHidden, - onHiddenElementChange, - sizeThresholdFirst = 100, - sizeThresholdSecond = 100, - storageKey, - }) { - const storage = useStorageContext(); - const store = React.useMemo( - () => - debounce(500, (value) => { - if (storageKey) { - storage == null ? void 0 : storage.set(storageKey, value); - } - }), - [storage, storageKey] - ); - const [hiddenElement, setHiddenElement] = React.useState(() => { - const storedValue = - storageKey && - (storage == null ? void 0 : storage.get(storageKey)); - if (storedValue === HIDE_FIRST || initiallyHidden === "first") { - return "first"; - } - if (storedValue === HIDE_SECOND || initiallyHidden === "second") { - return "second"; - } - return null; - }); - const setHiddenElementWithCallback = React.useCallback( - (element) => { - if (element !== hiddenElement) { - setHiddenElement(element); - onHiddenElementChange == null - ? void 0 - : onHiddenElementChange(element); - } - }, - [hiddenElement, onHiddenElementChange] - ); - const firstRef = React.useRef(null); - const dragBarRef = React.useRef(null); - const secondRef = React.useRef(null); - const defaultFlexRef = React.useRef(`${defaultSizeRelation}`); - React.useLayoutEffect(() => { - const storedValue = - (storageKey && - (storage == null ? void 0 : storage.get(storageKey))) || - defaultFlexRef.current; - if (firstRef.current) { - firstRef.current.style.display = "flex"; - firstRef.current.style.flex = - storedValue === HIDE_FIRST || storedValue === HIDE_SECOND - ? defaultFlexRef.current - : storedValue; - } - if (secondRef.current) { - secondRef.current.style.display = "flex"; - secondRef.current.style.flex = "1"; - } - if (dragBarRef.current) { - dragBarRef.current.style.display = "flex"; - } - }, [direction, storage, storageKey]); - const hide = React.useCallback((resizableElement) => { - const element = - resizableElement === "first" - ? firstRef.current - : secondRef.current; - if (!element) { - return; - } - element.style.left = "-1000px"; - element.style.position = "absolute"; - element.style.opacity = "0"; - element.style.height = "500px"; - element.style.width = "500px"; - if (firstRef.current) { - const flex = parseFloat(firstRef.current.style.flex); - if (!Number.isFinite(flex) || flex < 1) { - firstRef.current.style.flex = "1"; - } - } - }, []); - const show = React.useCallback( - (resizableElement) => { - const element = - resizableElement === "first" - ? firstRef.current - : secondRef.current; - if (!element) { - return; - } - element.style.width = ""; - element.style.height = ""; - element.style.opacity = ""; - element.style.position = ""; - element.style.left = ""; - if (storage && storageKey) { - const storedValue = storage.get(storageKey); - if ( - firstRef.current && - storedValue !== HIDE_FIRST && - storedValue !== HIDE_SECOND - ) { - firstRef.current.style.flex = - storedValue || defaultFlexRef.current; - } - } - }, - [storage, storageKey] - ); - React.useLayoutEffect(() => { - if (hiddenElement === "first") { - hide("first"); - } else { - show("first"); - } - if (hiddenElement === "second") { - hide("second"); - } else { - show("second"); - } - }, [hiddenElement, hide, show]); - React.useEffect(() => { - if ( - !dragBarRef.current || - !firstRef.current || - !secondRef.current - ) { - return; - } - const dragBarContainer = dragBarRef.current; - const firstContainer = firstRef.current; - const wrapper = firstContainer.parentElement; - const eventProperty = - direction === "horizontal" ? "clientX" : "clientY"; - const rectProperty = direction === "horizontal" ? "left" : "top"; - const adjacentRectProperty = - direction === "horizontal" ? "right" : "bottom"; - const sizeProperty = - direction === "horizontal" ? "clientWidth" : "clientHeight"; - function handleMouseDown(downEvent) { - downEvent.preventDefault(); - const offset = - downEvent[eventProperty] - - dragBarContainer.getBoundingClientRect()[rectProperty]; - function handleMouseMove(moveEvent) { - if (moveEvent.buttons === 0) { - return handleMouseUp(); - } - const firstSize = - moveEvent[eventProperty] - - wrapper.getBoundingClientRect()[rectProperty] - - offset; - const secondSize = - wrapper.getBoundingClientRect()[adjacentRectProperty] - - moveEvent[eventProperty] + - offset - - dragBarContainer[sizeProperty]; - if (firstSize < sizeThresholdFirst) { - setHiddenElementWithCallback("first"); - store(HIDE_FIRST); - } else if (secondSize < sizeThresholdSecond) { - setHiddenElementWithCallback("second"); - store(HIDE_SECOND); - } else { - setHiddenElementWithCallback(null); - const newFlex = `${firstSize / secondSize}`; - firstContainer.style.flex = newFlex; - store(newFlex); - } - } - function handleMouseUp() { - document.removeEventListener("mousemove", handleMouseMove); - document.removeEventListener("mouseup", handleMouseUp); - } - document.addEventListener("mousemove", handleMouseMove); - document.addEventListener("mouseup", handleMouseUp); - } - dragBarContainer.addEventListener("mousedown", handleMouseDown); - function reset() { - if (firstRef.current) { - firstRef.current.style.flex = defaultFlexRef.current; - } - store(defaultFlexRef.current); - setHiddenElementWithCallback(null); - } - dragBarContainer.addEventListener("dblclick", reset); - return () => { - dragBarContainer.removeEventListener( - "mousedown", - handleMouseDown - ); - dragBarContainer.removeEventListener("dblclick", reset); - }; - }, [ - direction, - setHiddenElementWithCallback, - sizeThresholdFirst, - sizeThresholdSecond, - store, - ]); - return React.useMemo( - () => ({ - dragBarRef, - hiddenElement, - firstRef, - setHiddenElement, - secondRef, - }), - [hiddenElement, setHiddenElement] - ); + return this._workspaceEdit; + }, + enumerable: false, + configurable: true + }); + WorkspaceChange.prototype.getTextEditChange = function (key) { + if (OptionalVersionedTextDocumentIdentifier.is(key)) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var textDocument = { + uri: key.uri, + version: key.version + }; + var result = this._textEditChanges[textDocument.uri]; + if (!result) { + var edits = []; + var textDocumentEdit = { + textDocument: textDocument, + edits: edits + }; + this._workspaceEdit.documentChanges.push(textDocumentEdit); + result = new TextEditChangeImpl(edits, this._changeAnnotations); + this._textEditChanges[textDocument.uri] = result; + } + return result; + } else { + this.initChanges(); + if (this._workspaceEdit.changes === undefined) { + throw new Error('Workspace edit is not configured for normal text edit changes.'); + } + var result = this._textEditChanges[key]; + if (!result) { + var edits = []; + this._workspaceEdit.changes[key] = edits; + result = new TextEditChangeImpl(edits); + this._textEditChanges[key] = result; + } + return result; + } + }; + WorkspaceChange.prototype.initDocumentChanges = function () { + if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { + this._changeAnnotations = new ChangeAnnotations(); + this._workspaceEdit.documentChanges = []; + this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + } + }; + WorkspaceChange.prototype.initChanges = function () { + if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { + this._workspaceEdit.changes = Object.create(null); + } + }; + WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = CreateFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = CreateFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = RenameFile.create(oldUri, newUri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = RenameFile.create(oldUri, newUri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = DeleteFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = DeleteFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + return WorkspaceChange; + }(); + /** + * The TextDocumentIdentifier namespace provides helper functions to work with + * {@link TextDocumentIdentifier} literals. + */ + var TextDocumentIdentifier; + (function (TextDocumentIdentifier) { + /** + * Creates a new TextDocumentIdentifier literal. + * @param uri The document's uri. + */ + function create(uri) { + return { + uri: uri + }; + } + TextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri); + } + TextDocumentIdentifier.is = is; + })(TextDocumentIdentifier || (exports.TextDocumentIdentifier = TextDocumentIdentifier = {})); + /** + * The VersionedTextDocumentIdentifier namespace provides helper functions to work with + * {@link VersionedTextDocumentIdentifier} literals. + */ + var VersionedTextDocumentIdentifier; + (function (VersionedTextDocumentIdentifier) { + /** + * Creates a new VersionedTextDocumentIdentifier literal. + * @param uri The document's uri. + * @param version The document's version. + */ + function create(uri, version) { + return { + uri: uri, + version: version + }; + } + VersionedTextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); + } + VersionedTextDocumentIdentifier.is = is; + })(VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {})); + /** + * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with + * {@link OptionalVersionedTextDocumentIdentifier} literals. + */ + var OptionalVersionedTextDocumentIdentifier; + (function (OptionalVersionedTextDocumentIdentifier) { + /** + * Creates a new OptionalVersionedTextDocumentIdentifier literal. + * @param uri The document's uri. + * @param version The document's version. + */ + function create(uri, version) { + return { + uri: uri, + version: version + }; + } + OptionalVersionedTextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); + } + OptionalVersionedTextDocumentIdentifier.is = is; + })(OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); + /** + * The TextDocumentItem namespace provides helper functions to work with + * {@link TextDocumentItem} literals. + */ + var TextDocumentItem; + (function (TextDocumentItem) { + /** + * Creates a new TextDocumentItem literal. + * @param uri The document's uri. + * @param languageId The document's language identifier. + * @param version The document's version number. + * @param text The document's text. + */ + function create(uri, languageId, version, text) { + return { + uri: uri, + languageId: languageId, + version: version, + text: text + }; + } + TextDocumentItem.create = create; + /** + * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); + } + TextDocumentItem.is = is; + })(TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {})); + /** + * Describes the content type that a client supports in various + * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. + * + * Please note that `MarkupKinds` must not start with a `$`. This kinds + * are reserved for internal usage. + */ + var MarkupKind; + (function (MarkupKind) { + /** + * Plain text is supported as a content format + */ + MarkupKind.PlainText = 'plaintext'; + /** + * Markdown is supported as a content format + */ + MarkupKind.Markdown = 'markdown'; + /** + * Checks whether the given value is a value of the {@link MarkupKind} type. + */ + function is(value) { + var candidate = value; + return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; + } + MarkupKind.is = is; + })(MarkupKind || (exports.MarkupKind = MarkupKind = {})); + var MarkupContent; + (function (MarkupContent) { + /** + * Checks whether the given value conforms to the {@link MarkupContent} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); + } + MarkupContent.is = is; + })(MarkupContent || (exports.MarkupContent = MarkupContent = {})); + /** + * The kind of a completion entry. + */ + var CompletionItemKind; + (function (CompletionItemKind) { + CompletionItemKind.Text = 1; + CompletionItemKind.Method = 2; + CompletionItemKind.Function = 3; + CompletionItemKind.Constructor = 4; + CompletionItemKind.Field = 5; + CompletionItemKind.Variable = 6; + CompletionItemKind.Class = 7; + CompletionItemKind.Interface = 8; + CompletionItemKind.Module = 9; + CompletionItemKind.Property = 10; + CompletionItemKind.Unit = 11; + CompletionItemKind.Value = 12; + CompletionItemKind.Enum = 13; + CompletionItemKind.Keyword = 14; + CompletionItemKind.Snippet = 15; + CompletionItemKind.Color = 16; + CompletionItemKind.File = 17; + CompletionItemKind.Reference = 18; + CompletionItemKind.Folder = 19; + CompletionItemKind.EnumMember = 20; + CompletionItemKind.Constant = 21; + CompletionItemKind.Struct = 22; + CompletionItemKind.Event = 23; + CompletionItemKind.Operator = 24; + CompletionItemKind.TypeParameter = 25; + })(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); + /** + * Defines whether the insert text in a completion item should be interpreted as + * plain text or a snippet. + */ + var InsertTextFormat; + (function (InsertTextFormat) { + /** + * The primary text to be inserted is treated as a plain string. + */ + InsertTextFormat.PlainText = 1; + /** + * The primary text to be inserted is treated as a snippet. + * + * A snippet can define tab stops and placeholders with `$1`, `$2` + * and `${3:foo}`. `$0` defines the final tab stop, it defaults to + * the end of the snippet. Placeholders with equal identifiers are linked, + * that is typing in one will update others too. + * + * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax + */ + InsertTextFormat.Snippet = 2; + })(InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {})); + /** + * Completion item tags are extra annotations that tweak the rendering of a completion + * item. + * + * @since 3.15.0 + */ + var CompletionItemTag; + (function (CompletionItemTag) { + /** + * Render a completion as obsolete, usually using a strike-out. + */ + CompletionItemTag.Deprecated = 1; + })(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {})); + /** + * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. + * + * @since 3.16.0 + */ + var InsertReplaceEdit; + (function (InsertReplaceEdit) { + /** + * Creates a new insert / replace edit + */ + function create(newText, insert, replace) { + return { + newText: newText, + insert: insert, + replace: replace + }; + } + InsertReplaceEdit.create = create; + /** + * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. + */ + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); + } + InsertReplaceEdit.is = is; + })(InsertReplaceEdit || (exports.InsertReplaceEdit = InsertReplaceEdit = {})); + /** + * How whitespace and indentation is handled during completion + * item insertion. + * + * @since 3.16.0 + */ + var InsertTextMode; + (function (InsertTextMode) { + /** + * The insertion or replace strings is taken as it is. If the + * value is multi line the lines below the cursor will be + * inserted using the indentation defined in the string value. + * The client will not apply any kind of adjustments to the + * string. + */ + InsertTextMode.asIs = 1; + /** + * The editor adjusts leading whitespace of new lines so that + * they match the indentation up to the cursor of the line for + * which the item is accepted. + * + * Consider a line like this: <2tabs><3tabs>foo. Accepting a + * multi line completion item is indented using 2 tabs and all + * following lines inserted will be indented using 2 tabs as well. + */ + InsertTextMode.adjustIndentation = 2; + })(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {})); + var CompletionItemLabelDetails; + (function (CompletionItemLabelDetails) { + function is(value) { + var candidate = value; + return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) && (Is.string(candidate.description) || candidate.description === undefined); + } + CompletionItemLabelDetails.is = is; + })(CompletionItemLabelDetails || (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = {})); + /** + * The CompletionItem namespace provides functions to deal with + * completion items. + */ + var CompletionItem; + (function (CompletionItem) { + /** + * Create a completion item and seed it with a label. + * @param label The completion item's label + */ + function create(label) { + return { + label: label + }; + } + CompletionItem.create = create; + })(CompletionItem || (exports.CompletionItem = CompletionItem = {})); + /** + * The CompletionList namespace provides functions to deal with + * completion lists. + */ + var CompletionList; + (function (CompletionList) { + /** + * Creates a new completion list. + * + * @param items The completion items. + * @param isIncomplete The list is not complete. + */ + function create(items, isIncomplete) { + return { + items: items ? items : [], + isIncomplete: !!isIncomplete + }; + } + CompletionList.create = create; + })(CompletionList || (exports.CompletionList = CompletionList = {})); + var MarkedString; + (function (MarkedString) { + /** + * Creates a marked string from plain text. + * + * @param plainText The plain text. + */ + function fromPlainText(plainText) { + return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash + } + MarkedString.fromPlainText = fromPlainText; + /** + * Checks whether the given value conforms to the {@link MarkedString} type. + */ + function is(value) { + var candidate = value; + return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value); + } + MarkedString.is = is; + })(MarkedString || (exports.MarkedString = MarkedString = {})); + var Hover; + (function (Hover) { + /** + * Checks whether the given value conforms to the {@link Hover} interface. + */ + function is(value) { + var candidate = value; + return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range)); + } + Hover.is = is; + })(Hover || (exports.Hover = Hover = {})); + /** + * The ParameterInformation namespace provides helper functions to work with + * {@link ParameterInformation} literals. + */ + var ParameterInformation; + (function (ParameterInformation) { + /** + * Creates a new parameter information literal. + * + * @param label A label string. + * @param documentation A doc string. + */ + function create(label, documentation) { + return documentation ? { + label: label, + documentation: documentation + } : { + label: label + }; + } + ParameterInformation.create = create; + })(ParameterInformation || (exports.ParameterInformation = ParameterInformation = {})); + /** + * The SignatureInformation namespace provides helper functions to work with + * {@link SignatureInformation} literals. + */ + var SignatureInformation; + (function (SignatureInformation) { + function create(label, documentation) { + var parameters = []; + for (var _i = 2; _i < arguments.length; _i++) { + parameters[_i - 2] = arguments[_i]; + } + var result = { + label: label + }; + if (Is.defined(documentation)) { + result.documentation = documentation; + } + if (Is.defined(parameters)) { + result.parameters = parameters; + } else { + result.parameters = []; + } + return result; + } + SignatureInformation.create = create; + })(SignatureInformation || (exports.SignatureInformation = SignatureInformation = {})); + /** + * A document highlight kind. + */ + var DocumentHighlightKind; + (function (DocumentHighlightKind) { + /** + * A textual occurrence. + */ + DocumentHighlightKind.Text = 1; + /** + * Read-access of a symbol, like reading a variable. + */ + DocumentHighlightKind.Read = 2; + /** + * Write-access of a symbol, like writing to a variable. + */ + DocumentHighlightKind.Write = 3; + })(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {})); + /** + * DocumentHighlight namespace to provide helper functions to work with + * {@link DocumentHighlight} literals. + */ + var DocumentHighlight; + (function (DocumentHighlight) { + /** + * Create a DocumentHighlight object. + * @param range The range the highlight applies to. + * @param kind The highlight kind + */ + function create(range, kind) { + var result = { + range: range + }; + if (Is.number(kind)) { + result.kind = kind; + } + return result; + } + DocumentHighlight.create = create; + })(DocumentHighlight || (exports.DocumentHighlight = DocumentHighlight = {})); + /** + * A symbol kind. + */ + var SymbolKind; + (function (SymbolKind) { + SymbolKind.File = 1; + SymbolKind.Module = 2; + SymbolKind.Namespace = 3; + SymbolKind.Package = 4; + SymbolKind.Class = 5; + SymbolKind.Method = 6; + SymbolKind.Property = 7; + SymbolKind.Field = 8; + SymbolKind.Constructor = 9; + SymbolKind.Enum = 10; + SymbolKind.Interface = 11; + SymbolKind.Function = 12; + SymbolKind.Variable = 13; + SymbolKind.Constant = 14; + SymbolKind.String = 15; + SymbolKind.Number = 16; + SymbolKind.Boolean = 17; + SymbolKind.Array = 18; + SymbolKind.Object = 19; + SymbolKind.Key = 20; + SymbolKind.Null = 21; + SymbolKind.EnumMember = 22; + SymbolKind.Struct = 23; + SymbolKind.Event = 24; + SymbolKind.Operator = 25; + SymbolKind.TypeParameter = 26; + })(SymbolKind || (exports.SymbolKind = SymbolKind = {})); + /** + * Symbol tags are extra annotations that tweak the rendering of a symbol. + * + * @since 3.16 + */ + var SymbolTag; + (function (SymbolTag) { + /** + * Render a symbol as obsolete, usually using a strike-out. + */ + SymbolTag.Deprecated = 1; + })(SymbolTag || (exports.SymbolTag = SymbolTag = {})); + var SymbolInformation; + (function (SymbolInformation) { + /** + * Creates a new symbol information literal. + * + * @param name The name of the symbol. + * @param kind The kind of the symbol. + * @param range The range of the location of the symbol. + * @param uri The resource of the location of symbol. + * @param containerName The name of the symbol containing the symbol. + */ + function create(name, kind, range, uri, containerName) { + var result = { + name: name, + kind: kind, + location: { + uri: uri, + range: range + } + }; + if (containerName) { + result.containerName = containerName; + } + return result; + } + SymbolInformation.create = create; + })(SymbolInformation || (exports.SymbolInformation = SymbolInformation = {})); + var WorkspaceSymbol; + (function (WorkspaceSymbol) { + /** + * Create a new workspace symbol. + * + * @param name The name of the symbol. + * @param kind The kind of the symbol. + * @param uri The resource of the location of the symbol. + * @param range An options range of the location. + * @returns A WorkspaceSymbol. + */ + function create(name, kind, uri, range) { + return range !== undefined ? { + name: name, + kind: kind, + location: { + uri: uri, + range: range + } + } : { + name: name, + kind: kind, + location: { + uri: uri + } + }; + } + WorkspaceSymbol.create = create; + })(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {})); + var DocumentSymbol; + (function (DocumentSymbol) { + /** + * Creates a new symbol information literal. + * + * @param name The name of the symbol. + * @param detail The detail of the symbol. + * @param kind The kind of the symbol. + * @param range The range of the symbol. + * @param selectionRange The selectionRange of the symbol. + * @param children Children of the symbol. + */ + function create(name, detail, kind, range, selectionRange, children) { + var result = { + name: name, + detail: detail, + kind: kind, + range: range, + selectionRange: selectionRange + }; + if (children !== undefined) { + result.children = children; + } + return result; + } + DocumentSymbol.create = create; + /** + * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. + */ + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags)); + } + DocumentSymbol.is = is; + })(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {})); + /** + * A set of predefined code action kinds + */ + var CodeActionKind; + (function (CodeActionKind) { + /** + * Empty kind. + */ + CodeActionKind.Empty = ''; + /** + * Base kind for quickfix actions: 'quickfix' + */ + CodeActionKind.QuickFix = 'quickfix'; + /** + * Base kind for refactoring actions: 'refactor' + */ + CodeActionKind.Refactor = 'refactor'; + /** + * Base kind for refactoring extraction actions: 'refactor.extract' + * + * Example extract actions: + * + * - Extract method + * - Extract function + * - Extract variable + * - Extract interface from class + * - ... + */ + CodeActionKind.RefactorExtract = 'refactor.extract'; + /** + * Base kind for refactoring inline actions: 'refactor.inline' + * + * Example inline actions: + * + * - Inline function + * - Inline variable + * - Inline constant + * - ... + */ + CodeActionKind.RefactorInline = 'refactor.inline'; + /** + * Base kind for refactoring rewrite actions: 'refactor.rewrite' + * + * Example rewrite actions: + * + * - Convert JavaScript function to class + * - Add or remove parameter + * - Encapsulate field + * - Make method static + * - Move method to base class + * - ... + */ + CodeActionKind.RefactorRewrite = 'refactor.rewrite'; + /** + * Base kind for source actions: `source` + * + * Source code actions apply to the entire file. + */ + CodeActionKind.Source = 'source'; + /** + * Base kind for an organize imports source action: `source.organizeImports` + */ + CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; + /** + * Base kind for auto-fix source actions: `source.fixAll`. + * + * Fix all actions automatically fix errors that have a clear fix that do not require user input. + * They should not suppress errors or perform unsafe fixes such as generating new types or classes. + * + * @since 3.15.0 + */ + CodeActionKind.SourceFixAll = 'source.fixAll'; + })(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {})); + /** + * The reason why code actions were requested. + * + * @since 3.17.0 + */ + var CodeActionTriggerKind; + (function (CodeActionTriggerKind) { + /** + * Code actions were explicitly requested by the user or by an extension. + */ + CodeActionTriggerKind.Invoked = 1; + /** + * Code actions were requested automatically. + * + * This typically happens when current selection in a file changes, but can + * also be triggered when file content changes. + */ + CodeActionTriggerKind.Automatic = 2; + })(CodeActionTriggerKind || (exports.CodeActionTriggerKind = CodeActionTriggerKind = {})); + /** + * The CodeActionContext namespace provides helper functions to work with + * {@link CodeActionContext} literals. + */ + var CodeActionContext; + (function (CodeActionContext) { + /** + * Creates a new CodeActionContext literal. + */ + function create(diagnostics, only, triggerKind) { + var result = { + diagnostics: diagnostics + }; + if (only !== undefined && only !== null) { + result.only = only; + } + if (triggerKind !== undefined && triggerKind !== null) { + result.triggerKind = triggerKind; + } + return result; + } + CodeActionContext.create = create; + /** + * Checks whether the given literal conforms to the {@link CodeActionContext} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); + } + CodeActionContext.is = is; + })(CodeActionContext || (exports.CodeActionContext = CodeActionContext = {})); + var CodeAction; + (function (CodeAction) { + function create(title, kindOrCommandOrEdit, kind) { + var result = { + title: title + }; + var checkKind = true; + if (typeof kindOrCommandOrEdit === 'string') { + checkKind = false; + result.kind = kindOrCommandOrEdit; + } else if (Command.is(kindOrCommandOrEdit)) { + result.command = kindOrCommandOrEdit; + } else { + result.edit = kindOrCommandOrEdit; + } + if (checkKind && kind !== undefined) { + result.kind = kind; + } + return result; + } + CodeAction.create = create; + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)); + } + CodeAction.is = is; + })(CodeAction || (exports.CodeAction = CodeAction = {})); + /** + * The CodeLens namespace provides helper functions to work with + * {@link CodeLens} literals. + */ + var CodeLens; + (function (CodeLens) { + /** + * Creates a new CodeLens literal. + */ + function create(range, data) { + var result = { + range: range + }; + if (Is.defined(data)) { + result.data = data; + } + return result; + } + CodeLens.create = create; + /** + * Checks whether the given literal conforms to the {@link CodeLens} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); + } + CodeLens.is = is; + })(CodeLens || (exports.CodeLens = CodeLens = {})); + /** + * The FormattingOptions namespace provides helper functions to work with + * {@link FormattingOptions} literals. + */ + var FormattingOptions; + (function (FormattingOptions) { + /** + * Creates a new FormattingOptions literal. + */ + function create(tabSize, insertSpaces) { + return { + tabSize: tabSize, + insertSpaces: insertSpaces + }; + } + FormattingOptions.create = create; + /** + * Checks whether the given literal conforms to the {@link FormattingOptions} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); + } + FormattingOptions.is = is; + })(FormattingOptions || (exports.FormattingOptions = FormattingOptions = {})); + /** + * The DocumentLink namespace provides helper functions to work with + * {@link DocumentLink} literals. + */ + var DocumentLink; + (function (DocumentLink) { + /** + * Creates a new DocumentLink literal. + */ + function create(range, target, data) { + return { + range: range, + target: target, + data: data + }; + } + DocumentLink.create = create; + /** + * Checks whether the given literal conforms to the {@link DocumentLink} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); + } + DocumentLink.is = is; + })(DocumentLink || (exports.DocumentLink = DocumentLink = {})); + /** + * The SelectionRange namespace provides helper function to work with + * SelectionRange literals. + */ + var SelectionRange; + (function (SelectionRange) { + /** + * Creates a new SelectionRange + * @param range the range. + * @param parent an optional parent. + */ + function create(range, parent) { + return { + range: range, + parent: parent + }; + } + SelectionRange.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); + } + SelectionRange.is = is; + })(SelectionRange || (exports.SelectionRange = SelectionRange = {})); + /** + * A set of predefined token types. This set is not fixed + * an clients can specify additional token types via the + * corresponding client capabilities. + * + * @since 3.16.0 + */ + var SemanticTokenTypes; + (function (SemanticTokenTypes) { + SemanticTokenTypes["namespace"] = "namespace"; + /** + * Represents a generic type. Acts as a fallback for types which can't be mapped to + * a specific type like class or enum. + */ + SemanticTokenTypes["type"] = "type"; + SemanticTokenTypes["class"] = "class"; + SemanticTokenTypes["enum"] = "enum"; + SemanticTokenTypes["interface"] = "interface"; + SemanticTokenTypes["struct"] = "struct"; + SemanticTokenTypes["typeParameter"] = "typeParameter"; + SemanticTokenTypes["parameter"] = "parameter"; + SemanticTokenTypes["variable"] = "variable"; + SemanticTokenTypes["property"] = "property"; + SemanticTokenTypes["enumMember"] = "enumMember"; + SemanticTokenTypes["event"] = "event"; + SemanticTokenTypes["function"] = "function"; + SemanticTokenTypes["method"] = "method"; + SemanticTokenTypes["macro"] = "macro"; + SemanticTokenTypes["keyword"] = "keyword"; + SemanticTokenTypes["modifier"] = "modifier"; + SemanticTokenTypes["comment"] = "comment"; + SemanticTokenTypes["string"] = "string"; + SemanticTokenTypes["number"] = "number"; + SemanticTokenTypes["regexp"] = "regexp"; + SemanticTokenTypes["operator"] = "operator"; + /** + * @since 3.17.0 + */ + SemanticTokenTypes["decorator"] = "decorator"; + })(SemanticTokenTypes || (exports.SemanticTokenTypes = SemanticTokenTypes = {})); + /** + * A set of predefined token modifiers. This set is not fixed + * an clients can specify additional token types via the + * corresponding client capabilities. + * + * @since 3.16.0 + */ + var SemanticTokenModifiers; + (function (SemanticTokenModifiers) { + SemanticTokenModifiers["declaration"] = "declaration"; + SemanticTokenModifiers["definition"] = "definition"; + SemanticTokenModifiers["readonly"] = "readonly"; + SemanticTokenModifiers["static"] = "static"; + SemanticTokenModifiers["deprecated"] = "deprecated"; + SemanticTokenModifiers["abstract"] = "abstract"; + SemanticTokenModifiers["async"] = "async"; + SemanticTokenModifiers["modification"] = "modification"; + SemanticTokenModifiers["documentation"] = "documentation"; + SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; + })(SemanticTokenModifiers || (exports.SemanticTokenModifiers = SemanticTokenModifiers = {})); + /** + * @since 3.16.0 + */ + var SemanticTokens; + (function (SemanticTokens) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); + } + SemanticTokens.is = is; + })(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {})); + /** + * The InlineValueText namespace provides functions to deal with InlineValueTexts. + * + * @since 3.17.0 + */ + var InlineValueText; + (function (InlineValueText) { + /** + * Creates a new InlineValueText literal. + */ + function create(range, text) { + return { + range: range, + text: text + }; + } + InlineValueText.create = create; + function is(value) { + var candidate = value; + return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text); + } + InlineValueText.is = is; + })(InlineValueText || (exports.InlineValueText = InlineValueText = {})); + /** + * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups. + * + * @since 3.17.0 + */ + var InlineValueVariableLookup; + (function (InlineValueVariableLookup) { + /** + * Creates a new InlineValueText literal. + */ + function create(range, variableName, caseSensitiveLookup) { + return { + range: range, + variableName: variableName, + caseSensitiveLookup: caseSensitiveLookup + }; + } + InlineValueVariableLookup.create = create; + function is(value) { + var candidate = value; + return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === undefined); + } + InlineValueVariableLookup.is = is; + })(InlineValueVariableLookup || (exports.InlineValueVariableLookup = InlineValueVariableLookup = {})); + /** + * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression. + * + * @since 3.17.0 + */ + var InlineValueEvaluatableExpression; + (function (InlineValueEvaluatableExpression) { + /** + * Creates a new InlineValueEvaluatableExpression literal. + */ + function create(range, expression) { + return { + range: range, + expression: expression + }; + } + InlineValueEvaluatableExpression.create = create; + function is(value) { + var candidate = value; + return candidate !== undefined && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === undefined); + } + InlineValueEvaluatableExpression.is = is; + })(InlineValueEvaluatableExpression || (exports.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {})); + /** + * The InlineValueContext namespace provides helper functions to work with + * {@link InlineValueContext} literals. + * + * @since 3.17.0 + */ + var InlineValueContext; + (function (InlineValueContext) { + /** + * Creates a new InlineValueContext literal. + */ + function create(frameId, stoppedLocation) { + return { + frameId: frameId, + stoppedLocation: stoppedLocation + }; + } + InlineValueContext.create = create; + /** + * Checks whether the given literal conforms to the {@link InlineValueContext} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(value.stoppedLocation); + } + InlineValueContext.is = is; + })(InlineValueContext || (exports.InlineValueContext = InlineValueContext = {})); + /** + * Inlay hint kinds. + * + * @since 3.17.0 + */ + var InlayHintKind; + (function (InlayHintKind) { + /** + * An inlay hint that for a type annotation. + */ + InlayHintKind.Type = 1; + /** + * An inlay hint that is for a parameter. + */ + InlayHintKind.Parameter = 2; + function is(value) { + return value === 1 || value === 2; + } + InlayHintKind.is = is; + })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {})); + var InlayHintLabelPart; + (function (InlayHintLabelPart) { + function create(value) { + return { + value: value + }; + } + InlayHintLabelPart.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === undefined || Location.is(candidate.location)) && (candidate.command === undefined || Command.is(candidate.command)); + } + InlayHintLabelPart.is = is; + })(InlayHintLabelPart || (exports.InlayHintLabelPart = InlayHintLabelPart = {})); + var InlayHint; + (function (InlayHint) { + function create(position, label, kind) { + var result = { + position: position, + label: label + }; + if (kind !== undefined) { + result.kind = kind; + } + return result; + } + InlayHint.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === undefined || InlayHintKind.is(candidate.kind)) && candidate.textEdits === undefined || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight)); + } + InlayHint.is = is; + })(InlayHint || (exports.InlayHint = InlayHint = {})); + var WorkspaceFolder; + (function (WorkspaceFolder) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); + } + WorkspaceFolder.is = is; + })(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {})); + var EOL = exports.EOL = ['\n', '\r\n', '\r']; + /** + * @deprecated Use the text document from the new vscode-languageserver-textdocument package. + */ + var TextDocument; + (function (TextDocument) { + /** + * Creates a new ITextDocument literal from the given uri and content. + * @param uri The document's uri. + * @param languageId The document's language Id. + * @param version The document's version. + * @param content The document's content. + */ + function create(uri, languageId, version, content) { + return new FullTextDocument(uri, languageId, version, content); + } + TextDocument.create = create; + /** + * Checks whether the given literal conforms to the {@link ITextDocument} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; + } + TextDocument.is = is; + function applyEdits(document, edits) { + var text = document.getText(); + var sortedEdits = mergeSort(edits, function (a, b) { + var diff = a.range.start.line - b.range.start.line; + if (diff === 0) { + return a.range.start.character - b.range.start.character; + } + return diff; + }); + var lastModifiedOffset = text.length; + for (var i = sortedEdits.length - 1; i >= 0; i--) { + var e = sortedEdits[i]; + var startOffset = document.offsetAt(e.range.start); + var endOffset = document.offsetAt(e.range.end); + if (endOffset <= lastModifiedOffset) { + text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); + } else { + throw new Error('Overlapping edit'); } - const DEFAULT_FLEX = 1; - const HIDE_FIRST = "hide-first"; - const HIDE_SECOND = "hide-second"; - const ToolbarButton = React.forwardRef( - ({ label, onClick, ...props }, ref) => { - const [error, setError] = React.useState(null); - const handleClick = React.useCallback( - (event) => { - try { - onClick == null ? void 0 : onClick(event); - setError(null); - } catch (err) { - setError( - err instanceof Error - ? err - : new Error(`Toolbar button click failed: ${err}`) - ); - } - }, - [onClick] - ); - return /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */ jsxRuntime.jsx(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx( - "graphiql-toolbar-button", - error && "error", - props.className - ), - onClick: handleClick, - "aria-label": error ? error.message : label, - "aria-invalid": error ? "true" : props["aria-invalid"], - }), - }); - } - ); - ToolbarButton.displayName = "ToolbarButton"; - function ExecuteButton() { - const { queryEditor, setOperationName } = useEditorContext({ - nonNull: true, - caller: ExecuteButton, - }); - const { isFetching, isSubscribed, operationName, run, stop } = - useExecutionContext({ - nonNull: true, - caller: ExecuteButton, - }); - const operations = - (queryEditor == null ? void 0 : queryEditor.operations) || []; - const hasOptions = - operations.length > 1 && typeof operationName !== "string"; - const isRunning = isFetching || isSubscribed; - const label = `${isRunning ? "Stop" : "Execute"} query (Ctrl-Enter)`; - const buttonProps = { - type: "button", - className: "graphiql-execute-button", - children: isRunning - ? /* @__PURE__ */ jsxRuntime.jsx(StopIcon, {}) - : /* @__PURE__ */ jsxRuntime.jsx(PlayIcon, {}), - "aria-label": label, - }; - return hasOptions && !isRunning - ? /* @__PURE__ */ jsxRuntime.jsxs(DropdownMenu, { - children: [ - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */ jsxRuntime.jsx( - DropdownMenu.Button, - { - ...buttonProps, - } - ), - }), - /* @__PURE__ */ jsxRuntime.jsx(DropdownMenu.Content, { - children: operations.map((operation, i) => { - const opName = operation.name - ? operation.name.value - : ``; - return /* @__PURE__ */ jsxRuntime.jsx( - DropdownMenu.Item, - { - onSelect: () => { - var _a; - const selectedOperationName = - (_a = operation.name) == null ? void 0 : _a.value; - if ( - queryEditor && - selectedOperationName && - selectedOperationName !== - queryEditor.operationName - ) { - setOperationName(selectedOperationName); - } - run(); - }, - children: opName, - }, - `${opName}-${i}` - ); - }), - }), - ], - }) - : /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */ jsxRuntime.jsx("button", { - ...buttonProps, - onClick: () => { - if (isRunning) { - stop(); - } else { - run(); - } - }, - }), - }); + lastModifiedOffset = startOffset; + } + return text; + } + TextDocument.applyEdits = applyEdits; + function mergeSort(data, compare) { + if (data.length <= 1) { + // sorted + return data; + } + var p = data.length / 2 | 0; + var left = data.slice(0, p); + var right = data.slice(p); + mergeSort(left, compare); + mergeSort(right, compare); + var leftIdx = 0; + var rightIdx = 0; + var i = 0; + while (leftIdx < left.length && rightIdx < right.length) { + var ret = compare(left[leftIdx], right[rightIdx]); + if (ret <= 0) { + // smaller_equal -> take left to preserve order + data[i++] = left[leftIdx++]; + } else { + // greater -> take right + data[i++] = right[rightIdx++]; } - const ToolbarMenuRoot = ({ button, children, label, ...props }) => - /* @__PURE__ */ jsxRuntime.jsxs(DropdownMenu, { - ...props, - children: [ - /* @__PURE__ */ jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */ jsxRuntime.jsx(DropdownMenu.Button, { - className: clsx.clsx( - "graphiql-un-styled graphiql-toolbar-menu", - props.className - ), - "aria-label": label, - children: button, - }), - }), - /* @__PURE__ */ jsxRuntime.jsx(DropdownMenu.Content, { - children, - }), - ], - }); - const ToolbarMenu = createComponentGroup(ToolbarMenuRoot, { - Item: DropdownMenu.Item, - }); - exports.Argument = Argument; - exports.ArgumentIcon = ArgumentIcon; - exports.Button = Button$1; - exports.ButtonGroup = ButtonGroup; - exports.ChevronDownIcon = ChevronDownIcon; - exports.ChevronLeftIcon = ChevronLeftIcon; - exports.ChevronUpIcon = ChevronUpIcon; - exports.CloseIcon = CloseIcon; - exports.CopyIcon = CopyIcon; - exports.DOC_EXPLORER_PLUGIN = DOC_EXPLORER_PLUGIN; - exports.DefaultValue = DefaultValue; - exports.DeprecatedArgumentIcon = DeprecatedArgumentIcon; - exports.DeprecatedEnumValueIcon = DeprecatedEnumValueIcon; - exports.DeprecatedFieldIcon = DeprecatedFieldIcon; - exports.DeprecationReason = DeprecationReason; - exports.Dialog = Dialog; - exports.DialogRoot = DialogRoot; - exports.Directive = Directive; - exports.DirectiveIcon = DirectiveIcon; - exports.DocExplorer = DocExplorer; - exports.DocsFilledIcon = DocsFilledIcon; - exports.DocsIcon = DocsIcon; - exports.DropdownMenu = DropdownMenu; - exports.EditorContext = EditorContext; - exports.EditorContextProvider = EditorContextProvider; - exports.EnumValueIcon = EnumValueIcon; - exports.ExecuteButton = ExecuteButton; - exports.ExecutionContext = ExecutionContext; - exports.ExecutionContextProvider = ExecutionContextProvider; - exports.ExplorerContext = ExplorerContext; - exports.ExplorerContextProvider = ExplorerContextProvider; - exports.ExplorerSection = ExplorerSection; - exports.FieldDocumentation = FieldDocumentation; - exports.FieldIcon = FieldIcon; - exports.FieldLink = FieldLink; - exports.GraphiQLProvider = GraphiQLProvider; - exports.HISTORY_PLUGIN = HISTORY_PLUGIN; - exports.HeaderEditor = HeaderEditor; - exports.History = History; - exports.HistoryContext = HistoryContext; - exports.HistoryContextProvider = HistoryContextProvider; - exports.HistoryIcon = HistoryIcon; - exports.ImagePreview = ImagePreview; - exports.ImplementsIcon = ImplementsIcon; - exports.KeyboardShortcutIcon = KeyboardShortcutIcon; - exports.MagnifyingGlassIcon = MagnifyingGlassIcon; - exports.MarkdownContent = MarkdownContent; - exports.MergeIcon = MergeIcon; - exports.PenIcon = PenIcon; - exports.PlayIcon = PlayIcon; - exports.PluginContext = PluginContext; - exports.PluginContextProvider = PluginContextProvider; - exports.PlusIcon = PlusIcon; - exports.PrettifyIcon = PrettifyIcon; - exports.QueryEditor = QueryEditor; - exports.ReloadIcon = ReloadIcon; - exports.ResponseEditor = ResponseEditor; - exports.RootTypeIcon = RootTypeIcon; - exports.SchemaContext = SchemaContext; - exports.SchemaContextProvider = SchemaContextProvider; - exports.SchemaDocumentation = SchemaDocumentation; - exports.Search = Search; - exports.SettingsIcon = SettingsIcon; - exports.Spinner = Spinner; - exports.StarFilledIcon = StarFilledIcon; - exports.StarIcon = StarIcon; - exports.StopIcon = StopIcon; - exports.StorageContext = StorageContext; - exports.StorageContextProvider = StorageContextProvider; - exports.Tab = Tab; - exports.Tabs = Tabs; - exports.ToolbarButton = ToolbarButton; - exports.ToolbarMenu = ToolbarMenu; - exports.Tooltip = Tooltip; - exports.TooltipRoot = TooltipRoot; - exports.TrashIcon = TrashIcon; - exports.TypeDocumentation = TypeDocumentation; - exports.TypeIcon = TypeIcon; - exports.TypeLink = TypeLink; - exports.UnStyledButton = UnStyledButton; - exports.VariableEditor = VariableEditor; - exports.useAutoCompleteLeafs = useAutoCompleteLeafs; - exports.useCopyQuery = useCopyQuery; - exports.useDragResize = useDragResize; - exports.useEditorContext = useEditorContext; - exports.useEditorState = useEditorState; - exports.useExecutionContext = useExecutionContext; - exports.useExplorerContext = useExplorerContext; - exports.useHeaderEditor = useHeaderEditor; - exports.useHeadersEditorState = useHeadersEditorState; - exports.useHistoryContext = useHistoryContext; - exports.useMergeQuery = useMergeQuery; - exports.useOperationsEditorState = useOperationsEditorState; - exports.useOptimisticState = useOptimisticState; - exports.usePluginContext = usePluginContext; - exports.usePrettifyEditors = usePrettifyEditors; - exports.useQueryEditor = useQueryEditor; - exports.useResponseEditor = useResponseEditor; - exports.useSchemaContext = useSchemaContext; - exports.useStorageContext = useStorageContext; - exports.useTheme = useTheme; - exports.useVariableEditor = useVariableEditor; - exports.useVariablesEditorState = useVariablesEditorState; - - /***/ + } + while (leftIdx < left.length) { + data[i++] = left[leftIdx++]; + } + while (rightIdx < right.length) { + data[i++] = right[rightIdx++]; + } + return data; + } + })(TextDocument || (exports.TextDocument = TextDocument = {})); + /** + * @deprecated Use the text document from the new vscode-languageserver-textdocument package. + */ + var FullTextDocument = /** @class */function () { + function FullTextDocument(uri, languageId, version, content) { + this._uri = uri; + this._languageId = languageId; + this._version = version; + this._content = content; + this._lineOffsets = undefined; + } + Object.defineProperty(FullTextDocument.prototype, "uri", { + get: function () { + return this._uri; }, - - /***/ "../../graphiql-react/dist/info-addon.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/info-addon.cjs.js ***! - \***************************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - codemirror.CodeMirror.defineOption( - "info", - false, - (cm, options, old) => { - if (old && old !== codemirror.CodeMirror.Init) { - const oldOnMouseOver = cm.state.info.onMouseOver; - codemirror.CodeMirror.off( - cm.getWrapperElement(), - "mouseover", - oldOnMouseOver - ); - clearTimeout(cm.state.info.hoverTimeout); - delete cm.state.info; - } - if (options) { - const state = (cm.state.info = createState(options)); - state.onMouseOver = onMouseOver.bind(null, cm); - codemirror.CodeMirror.on( - cm.getWrapperElement(), - "mouseover", - state.onMouseOver - ); - } - } - ); - function createState(options) { - return { - options: - options instanceof Function - ? { - render: options, - } - : options === true - ? {} - : options, - }; - } - function getHoverTime(cm) { - const { options } = cm.state.info; - return ( - (options === null || options === void 0 - ? void 0 - : options.hoverTime) || 500 - ); - } - function onMouseOver(cm, e) { - const state = cm.state.info; - const target = e.target || e.srcElement; - if (!(target instanceof HTMLElement)) { - return; - } - if (target.nodeName !== "SPAN" || state.hoverTimeout !== void 0) { - return; - } - const box = target.getBoundingClientRect(); - const onMouseMove = function () { - clearTimeout(state.hoverTimeout); - state.hoverTimeout = setTimeout(onHover, hoverTime); - }; - const onMouseOut = function () { - codemirror.CodeMirror.off(document, "mousemove", onMouseMove); - codemirror.CodeMirror.off( - cm.getWrapperElement(), - "mouseout", - onMouseOut - ); - clearTimeout(state.hoverTimeout); - state.hoverTimeout = void 0; - }; - const onHover = function () { - codemirror.CodeMirror.off(document, "mousemove", onMouseMove); - codemirror.CodeMirror.off( - cm.getWrapperElement(), - "mouseout", - onMouseOut - ); - state.hoverTimeout = void 0; - onMouseHover(cm, box); - }; - const hoverTime = getHoverTime(cm); - state.hoverTimeout = setTimeout(onHover, hoverTime); - codemirror.CodeMirror.on(document, "mousemove", onMouseMove); - codemirror.CodeMirror.on( - cm.getWrapperElement(), - "mouseout", - onMouseOut - ); - } - function onMouseHover(cm, box) { - const pos = cm.coordsChar( - { - left: (box.left + box.right) / 2, - top: (box.top + box.bottom) / 2, - }, - "window" - ); - const state = cm.state.info; - const { options } = state; - const render = options.render || cm.getHelper(pos, "info"); - if (render) { - const token = cm.getTokenAt(pos, true); - if (token) { - const info = render(token, options, cm, pos); - if (info) { - showPopup(cm, box, info); - } - } - } - } - function showPopup(cm, box, info) { - const popup = document.createElement("div"); - popup.className = "CodeMirror-info"; - popup.append(info); - document.body.append(popup); - const popupBox = popup.getBoundingClientRect(); - const popupStyle = window.getComputedStyle(popup); - const popupWidth = - popupBox.right - - popupBox.left + - parseFloat(popupStyle.marginLeft) + - parseFloat(popupStyle.marginRight); - const popupHeight = - popupBox.bottom - - popupBox.top + - parseFloat(popupStyle.marginTop) + - parseFloat(popupStyle.marginBottom); - let topPos = box.bottom; - if ( - popupHeight > window.innerHeight - box.bottom - 15 && - box.top > window.innerHeight - box.bottom - ) { - topPos = box.top - popupHeight; - } - if (topPos < 0) { - topPos = box.bottom; - } - let leftPos = Math.max(0, window.innerWidth - popupWidth - 15); - if (leftPos > box.left) { - leftPos = box.left; - } - popup.style.opacity = "1"; - popup.style.top = topPos + "px"; - popup.style.left = leftPos + "px"; - let popupTimeout; - const onMouseOverPopup = function () { - clearTimeout(popupTimeout); - }; - const onMouseOut = function () { - clearTimeout(popupTimeout); - popupTimeout = setTimeout(hidePopup, 200); - }; - const hidePopup = function () { - codemirror.CodeMirror.off(popup, "mouseover", onMouseOverPopup); - codemirror.CodeMirror.off(popup, "mouseout", onMouseOut); - codemirror.CodeMirror.off( - cm.getWrapperElement(), - "mouseout", - onMouseOut - ); - if (popup.style.opacity) { - popup.style.opacity = "0"; - setTimeout(() => { - if (popup.parentNode) { - popup.remove(); - } - }, 600); - } else if (popup.parentNode) { - popup.remove(); - } - }; - codemirror.CodeMirror.on(popup, "mouseover", onMouseOverPopup); - codemirror.CodeMirror.on(popup, "mouseout", onMouseOut); - codemirror.CodeMirror.on( - cm.getWrapperElement(), - "mouseout", - onMouseOut - ); - } - - /***/ + enumerable: false, + configurable: true + }); + Object.defineProperty(FullTextDocument.prototype, "languageId", { + get: function () { + return this._languageId; }, - - /***/ "../../graphiql-react/dist/info.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/info.cjs.js ***! - \*********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const SchemaReference = __webpack_require__( - /*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js" - ); - __webpack_require__( - /*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js" - ); - codemirror.CodeMirror.registerHelper( - "info", - "graphql", - (token, options) => { - var _a; - if (!options.schema || !token.state) { - return; - } - const { kind, step } = token.state; - const typeInfo = SchemaReference.getTypeInfo( - options.schema, - token.state - ); - if ( - (kind === "Field" && step === 0 && typeInfo.fieldDef) || - (kind === "AliasedField" && step === 2 && typeInfo.fieldDef) || - (kind === "ObjectField" && step === 0 && typeInfo.fieldDef) - ) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderField(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.fieldDef); - return into; - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderDirective(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.directiveDef); - return into; - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderArg(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.argDef); - return into; - } - if ( - kind === "EnumValue" && - ((_a = typeInfo.enumValue) === null || _a === void 0 - ? void 0 - : _a.description) - ) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderEnumValue(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.enumValue); - return into; - } - if ( - kind === "NamedType" && - typeInfo.type && - typeInfo.type.description - ) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderType(header, typeInfo, options, typeInfo.type); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.type); - return into; - } - } - ); - function renderField(into, typeInfo, options) { - renderQualifiedField(into, typeInfo, options); - renderTypeAnnotation(into, typeInfo, options, typeInfo.type); - } - function renderQualifiedField(into, typeInfo, options) { - var _a; - const fieldName = - ((_a = typeInfo.fieldDef) === null || _a === void 0 - ? void 0 - : _a.name) || ""; - text( - into, - fieldName, - "field-name", - options, - SchemaReference.getFieldReference(typeInfo) - ); - } - function renderDirective(into, typeInfo, options) { - var _a; - const name = - "@" + - (((_a = typeInfo.directiveDef) === null || _a === void 0 - ? void 0 - : _a.name) || ""); - text( - into, - name, - "directive-name", - options, - SchemaReference.getDirectiveReference(typeInfo) - ); - } - function renderArg(into, typeInfo, options) { - var _a; - const name = - ((_a = typeInfo.argDef) === null || _a === void 0 - ? void 0 - : _a.name) || ""; - text( - into, - name, - "arg-name", - options, - SchemaReference.getArgumentReference(typeInfo) - ); - renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); - } - function renderEnumValue(into, typeInfo, options) { - var _a; - const name = - ((_a = typeInfo.enumValue) === null || _a === void 0 - ? void 0 - : _a.name) || ""; - renderType(into, typeInfo, options, typeInfo.inputType); - text(into, "."); - text( - into, - name, - "enum-value", - options, - SchemaReference.getEnumValueReference(typeInfo) - ); - } - function renderTypeAnnotation(into, typeInfo, options, t) { - const typeSpan = document.createElement("span"); - typeSpan.className = "type-name-pill"; - if (t instanceof graphql.GraphQLNonNull) { - renderType(typeSpan, typeInfo, options, t.ofType); - text(typeSpan, "!"); - } else if (t instanceof graphql.GraphQLList) { - text(typeSpan, "["); - renderType(typeSpan, typeInfo, options, t.ofType); - text(typeSpan, "]"); - } else { - text( - typeSpan, - (t === null || t === void 0 ? void 0 : t.name) || "", - "type-name", - options, - SchemaReference.getTypeReference(typeInfo, t) - ); - } - into.append(typeSpan); - } - function renderType(into, typeInfo, options, t) { - if (t instanceof graphql.GraphQLNonNull) { - renderType(into, typeInfo, options, t.ofType); - text(into, "!"); - } else if (t instanceof graphql.GraphQLList) { - text(into, "["); - renderType(into, typeInfo, options, t.ofType); - text(into, "]"); - } else { - text( - into, - (t === null || t === void 0 ? void 0 : t.name) || "", - "type-name", - options, - SchemaReference.getTypeReference(typeInfo, t) - ); - } - } - function renderDescription(into, options, def) { - const { description } = def; - if (description) { - const descriptionDiv = document.createElement("div"); - descriptionDiv.className = "info-description"; - if (options.renderDescription) { - descriptionDiv.innerHTML = options.renderDescription(description); - } else { - descriptionDiv.append(document.createTextNode(description)); - } - into.append(descriptionDiv); - } - renderDeprecation(into, options, def); - } - function renderDeprecation(into, options, def) { - const reason = def.deprecationReason; - if (reason) { - const deprecationDiv = document.createElement("div"); - deprecationDiv.className = "info-deprecation"; - into.append(deprecationDiv); - const label = document.createElement("span"); - label.className = "info-deprecation-label"; - label.append(document.createTextNode("Deprecated")); - deprecationDiv.append(label); - const reasonDiv = document.createElement("div"); - reasonDiv.className = "info-deprecation-reason"; - if (options.renderDescription) { - reasonDiv.innerHTML = options.renderDescription(reason); - } else { - reasonDiv.append(document.createTextNode(reason)); - } - deprecationDiv.append(reasonDiv); - } - } - function text( - into, - content, - className = "", - options = { - onClick: null, - }, - ref = null - ) { - if (className) { - const { onClick } = options; - let node; - if (onClick) { - node = document.createElement("a"); - node.href = "javascript:void 0"; - node.addEventListener("click", (e) => { - e.preventDefault(); - onClick(ref, e); - }); - } else { - node = document.createElement("span"); - } - node.className = className; - node.append(document.createTextNode(content)); - into.append(node); - } else { - into.append(document.createTextNode(content)); - } - } - - /***/ + enumerable: false, + configurable: true + }); + Object.defineProperty(FullTextDocument.prototype, "version", { + get: function () { + return this._version; }, - - /***/ "../../graphiql-react/dist/javascript.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/javascript.cjs.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } + enumerable: false, + configurable: true + }); + FullTextDocument.prototype.getText = function (range) { + if (range) { + var start = this.offsetAt(range.start); + var end = this.offsetAt(range.end); + return this._content.substring(start, end); + } + return this._content; + }; + FullTextDocument.prototype.update = function (event, version) { + this._content = event.text; + this._version = version; + this._lineOffsets = undefined; + }; + FullTextDocument.prototype.getLineOffsets = function () { + if (this._lineOffsets === undefined) { + var lineOffsets = []; + var text = this._content; + var isLineStart = true; + for (var i = 0; i < text.length; i++) { + if (isLineStart) { + lineOffsets.push(i); + isLineStart = false; + } + var ch = text.charAt(i); + isLineStart = ch === '\r' || ch === '\n'; + if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { + i++; + } + } + if (isLineStart && text.length > 0) { + lineOffsets.push(text.length); + } + this._lineOffsets = lineOffsets; + } + return this._lineOffsets; + }; + FullTextDocument.prototype.positionAt = function (offset) { + offset = Math.max(Math.min(offset, this._content.length), 0); + var lineOffsets = this.getLineOffsets(); + var low = 0, + high = lineOffsets.length; + if (high === 0) { + return Position.create(0, offset); + } + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (lineOffsets[mid] > offset) { + high = mid; + } else { + low = mid + 1; + } + } + // low is the least x for which the line offset is larger than the current offset + // or array.length if no line offset is larger than the current offset + var line = low - 1; + return Position.create(line, offset - lineOffsets[line]); + }; + FullTextDocument.prototype.offsetAt = function (position) { + var lineOffsets = this.getLineOffsets(); + if (position.line >= lineOffsets.length) { + return this._content.length; + } else if (position.line < 0) { + return 0; + } + var lineOffset = lineOffsets[position.line]; + var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; + return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); + }; + Object.defineProperty(FullTextDocument.prototype, "lineCount", { + get: function () { + return this.getLineOffsets().length; + }, + enumerable: false, + configurable: true + }); + return FullTextDocument; + }(); + var Is; + (function (Is) { + var toString = Object.prototype.toString; + function defined(value) { + return typeof value !== 'undefined'; + } + Is.defined = defined; + function undefined(value) { + return typeof value === 'undefined'; + } + Is.undefined = undefined; + function boolean(value) { + return value === true || value === false; + } + Is.boolean = boolean; + function string(value) { + return toString.call(value) === '[object String]'; + } + Is.string = string; + function number(value) { + return toString.call(value) === '[object Number]'; + } + Is.number = number; + function numberRange(value, min, max) { + return toString.call(value) === '[object Number]' && min <= value && value <= max; + } + Is.numberRange = numberRange; + function integer(value) { + return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647; + } + Is.integer = integer; + function uinteger(value) { + return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647; + } + Is.uinteger = uinteger; + function func(value) { + return toString.call(value) === '[object Function]'; + } + Is.func = func; + function objectLiteral(value) { + // Strictly speaking class instances pass this check as well. Since the LSP + // doesn't use classes we ignore this for now. If we do we need to add something + // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` + return value !== null && typeof value === 'object'; + } + Is.objectLiteral = objectLiteral; + function typedArray(value, check) { + return Array.isArray(value) && value.every(check); + } + Is.typedArray = typedArray; + })(Is || (Is = {})); + + /***/ }), + + /***/ "../../graphiql-react/dist/SchemaReference.cjs.js": + /*!********************************************************!*\ + !*** ../../graphiql-react/dist/SchemaReference.cjs.js ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); + function getTypeInfo(schema, tokenState) { + const info = { + schema, + type: null, + parentType: null, + inputType: null, + directiveDef: null, + fieldDef: null, + argDef: null, + argDefs: null, + objectFieldDefs: null + }; + forEachState.forEachState(tokenState, state => { + var _a, _b; + switch (state.kind) { + case "Query": + case "ShortQuery": + info.type = schema.getQueryType(); + break; + case "Mutation": + info.type = schema.getMutationType(); + break; + case "Subscription": + info.type = schema.getSubscriptionType(); + break; + case "InlineFragment": + case "FragmentDefinition": + if (state.type) { + info.type = schema.getType(state.type); + } + break; + case "Field": + case "AliasedField": + info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null; + info.type = (_a = info.fieldDef) === null || _a === void 0 ? void 0 : _a.type; + break; + case "SelectionSet": + info.parentType = info.type ? graphql.getNamedType(info.type) : null; + break; + case "Directive": + info.directiveDef = state.name ? schema.getDirective(state.name) : null; + break; + case "Arguments": + const parentDef = state.prevState ? state.prevState.kind === "Field" ? info.fieldDef : state.prevState.kind === "Directive" ? info.directiveDef : state.prevState.kind === "AliasedField" ? state.prevState.name && getFieldDef(schema, info.parentType, state.prevState.name) : null : null; + info.argDefs = parentDef ? parentDef.args : null; + break; + case "Argument": + info.argDef = null; + if (info.argDefs) { + for (let i = 0; i < info.argDefs.length; i++) { + if (info.argDefs[i].name === state.name) { + info.argDef = info.argDefs[i]; + break; } } } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); - } - var javascript$2 = { - exports: {}, - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - CodeMirror.defineMode( - "javascript", - function (config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var trackScope = parserConfig.trackScope !== false; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - var keywords = (function () { - function kw(type2) { - return { - type: type2, - style: "keyword", - }; - } - var A = kw("keyword a"), - B = kw("keyword b"), - C = kw("keyword c"), - D = kw("keyword d"); - var operator = kw("operator"), - atom = { - type: "atom", - style: "atom", - }; - return { - if: kw("if"), - while: A, - with: A, - else: B, - do: B, - try: B, - finally: B, - return: D, - break: D, - continue: D, - new: kw("new"), - delete: C, - void: C, - throw: C, - debugger: kw("debugger"), - var: kw("var"), - const: kw("var"), - let: kw("var"), - function: kw("function"), - catch: kw("catch"), - for: kw("for"), - switch: kw("switch"), - case: kw("case"), - default: kw("default"), - in: operator, - typeof: operator, - instanceof: operator, - true: atom, - false: atom, - null: atom, - undefined: atom, - NaN: atom, - Infinity: atom, - this: kw("this"), - class: kw("class"), - super: kw("atom"), - yield: C, - export: kw("export"), - import: kw("import"), - extends: C, - await: C, - }; - })(); - var isOperatorChar = /[+\-*&%=<>!?|~^@]/; - var isJsonldKeyword = - /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - function readRegexp(stream) { - var escaped = false, - next, - inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true; - else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; - } - } - var type, content; - function ret(tp, style, cont2) { - type = tp; - content = cont2; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if ( - ch == "." && - stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/) - ) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if ( - ch == "0" && - stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/) - ) { - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match( - /^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/ - ); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (expressionAllowed(stream, state, 1)) { - readRegexp(stream); - stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); - return ret("regexp", "string-2"); - } else { - stream.eat("="); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#" && stream.peek() == "!") { - stream.skipToEnd(); - return ret("meta", "meta"); - } else if (ch == "#" && stream.eatWhile(wordRE)) { - return ret("variable", "property"); - } else if ( - (ch == "<" && stream.match("!--")) || - (ch == "-" && - stream.match("->") && - !/\S/.test(stream.string.slice(0, stream.start))) - ) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (isOperatorChar.test(ch)) { - if ( - ch != ">" || - !state.lexical || - state.lexical.type != ">" - ) { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("="); - } else if (/[<>*+\-|&?]/.test(ch)) { - stream.eat(ch); - if (ch == ">") stream.eat(ch); - } - } - if (ch == "?" && stream.eat(".")) return ret("."); - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current(); - if (state.lastType != ".") { - if (keywords.propertyIsEnumerable(word)) { - var kw = keywords[word]; - return ret(kw.type, kw.style, word); - } - if ( - word == "async" && - stream.match( - /^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, - false - ) - ) - return ret("async", "keyword", word); - } - return ret("variable", "variable", word); - } - } - function tokenString(quote) { - return function (stream, state) { - var escaped = false, - next; - if ( - jsonldMode && - stream.peek() == "@" && - stream.match(isJsonldKeyword) - ) { - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; - } - function tokenComment(stream, state) { - var maybeEnd = false, - ch; - while ((ch = stream.next())) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = ch == "*"; - } - return ret("comment", "comment"); - } - function tokenQuasi(stream, state) { - var escaped = false, - next; - while ((next = stream.next()) != null) { - if ( - !escaped && - (next == "`" || (next == "$" && stream.eat("{"))) - ) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - var brackets = "([{}])"; - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - if (isTS) { - var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec( - stream.string.slice(stream.start, arrow) - ); - if (m) arrow = m.index; - } - var depth = 0, - sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { - ++pos; - break; - } - if (--depth == 0) { - if (ch == "(") sawSomething = true; - break; - } - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/`]/.test(ch)) { - for (; ; --pos) { - if (pos == 0) return; - var next = stream.string.charAt(pos - 1); - if ( - next == ch && - stream.string.charAt(pos - 2) != "\\" - ) { - pos--; - break; - } - } - } else if (sawSomething && !depth) { - ++pos; - break; - } - } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - var atomicTypes = { - atom: true, - number: true, - variable: true, - string: true, - regexp: true, - this: true, - import: true, - "jsonld-keyword": true, - }; - function JSLexical(indented, column, type2, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type2; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - function inScope(state, varname) { - if (!trackScope) return false; - for (var v = state.localVars; v; v = v.next) - if (v.name == varname) return true; - for (var cx2 = state.context; cx2; cx2 = cx2.prev) { - for (var v = cx2.vars; v; v = v.next) - if (v.name == varname) return true; - } - } - function parseJS(state, style, type2, content2, stream) { - var cc = state.cc; - cx.state = state; - cx.stream = stream; - (cx.marked = null), (cx.cc = cc); - cx.style = style; - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = true; - while (true) { - var combinator = cc.length - ? cc.pop() - : jsonMode - ? expression - : statement; - if (combinator(type2, content2)) { - while (cc.length && cc[cc.length - 1].lex) cc.pop()(); - if (cx.marked) return cx.marked; - if (type2 == "variable" && inScope(state, content2)) - return "variable-2"; - return style; - } - } - } - var cx = { - state: null, - column: null, - marked: null, - cc: null, - }; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) - cx.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - function inList(name, list) { - for (var v = list; v; v = v.next) - if (v.name == name) return true; - return false; - } - function register(varname) { - var state = cx.state; - cx.marked = "def"; - if (!trackScope) return; - if (state.context) { - if ( - state.lexical.info == "var" && - state.context && - state.context.block - ) { - var newContext = registerVarScoped( - varname, - state.context - ); - if (newContext != null) { - state.context = newContext; - return; - } - } else if (!inList(varname, state.localVars)) { - state.localVars = new Var(varname, state.localVars); - return; - } - } - if ( - parserConfig.globalVars && - !inList(varname, state.globalVars) - ) - state.globalVars = new Var(varname, state.globalVars); - } - function registerVarScoped(varname, context) { - if (!context) { - return null; - } else if (context.block) { - var inner = registerVarScoped(varname, context.prev); - if (!inner) return null; - if (inner == context.prev) return context; - return new Context(inner, context.vars, true); - } else if (inList(varname, context.vars)) { - return context; - } else { - return new Context( - context.prev, - new Var(varname, context.vars), - false - ); - } - } - function isModifier(name) { - return ( - name == "public" || - name == "private" || - name == "protected" || - name == "abstract" || - name == "readonly" - ); - } - function Context(prev, vars, block2) { - this.prev = prev; - this.vars = vars; - this.block = block2; - } - function Var(name, next) { - this.name = name; - this.next = next; - } - var defaultVars = new Var("this", new Var("arguments", null)); - function pushcontext() { - cx.state.context = new Context( - cx.state.context, - cx.state.localVars, - false - ); - cx.state.localVars = defaultVars; - } - function pushblockcontext() { - cx.state.context = new Context( - cx.state.context, - cx.state.localVars, - true - ); - cx.state.localVars = null; - } - pushcontext.lex = pushblockcontext.lex = true; - function popcontext() { - cx.state.localVars = cx.state.context.vars; - cx.state.context = cx.state.context.prev; - } - popcontext.lex = true; - function pushlex(type2, info) { - var result = function () { - var state = cx.state, - indent = state.indented; - if (state.lexical.type == "stat") - indent = state.lexical.indented; - else - for ( - var outer = state.lexical; - outer && outer.type == ")" && outer.align; - outer = outer.prev - ) - indent = outer.indented; - state.lexical = new JSLexical( - indent, - cx.stream.column(), - type2, - null, - state.lexical, - info - ); - }; - result.lex = true; - return result; - } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") - state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - function expect(wanted) { - function exp(type2) { - if (type2 == wanted) return cont(); - else if ( - wanted == ";" || - type2 == "}" || - type2 == ")" || - type2 == "]" - ) - return pass(); - else return cont(exp); - } - return exp; - } - function statement(type2, value) { - if (type2 == "var") - return cont( - pushlex("vardef", value), - vardef, - expect(";"), - poplex - ); - if (type2 == "keyword a") - return cont(pushlex("form"), parenExpr, statement, poplex); - if (type2 == "keyword b") - return cont(pushlex("form"), statement, poplex); - if (type2 == "keyword d") - return cx.stream.match(/^\s*$/, false) - ? cont() - : cont( - pushlex("stat"), - maybeexpression, - expect(";"), - poplex - ); - if (type2 == "debugger") return cont(expect(";")); - if (type2 == "{") - return cont( - pushlex("}"), - pushblockcontext, - block, - poplex, - popcontext - ); - if (type2 == ";") return cont(); - if (type2 == "if") { - if ( - cx.state.lexical.info == "else" && - cx.state.cc[cx.state.cc.length - 1] == poplex - ) - cx.state.cc.pop()(); - return cont( - pushlex("form"), - parenExpr, - statement, - poplex, - maybeelse - ); - } - if (type2 == "function") return cont(functiondef); - if (type2 == "for") - return cont( - pushlex("form"), - pushblockcontext, - forspec, - statement, - popcontext, - poplex - ); - if (type2 == "class" || (isTS && value == "interface")) { - cx.marked = "keyword"; - return cont( - pushlex("form", type2 == "class" ? type2 : value), - className, - poplex - ); - } - if (type2 == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword"; - return cont(statement); - } else if ( - isTS && - (value == "module" || - value == "enum" || - value == "type") && - cx.stream.match(/^\s*\w/, false) - ) { - cx.marked = "keyword"; - if (value == "enum") return cont(enumdef); - else if (value == "type") - return cont( - typename, - expect("operator"), - typeexpr, - expect(";") - ); - else - return cont( - pushlex("form"), - pattern, - expect("{"), - pushlex("}"), - block, - poplex, - poplex - ); - } else if (isTS && value == "namespace") { - cx.marked = "keyword"; - return cont( - pushlex("form"), - expression, - statement, - poplex - ); - } else if (isTS && value == "abstract") { - cx.marked = "keyword"; - return cont(statement); - } else { - return cont(pushlex("stat"), maybelabel); - } - } - if (type2 == "switch") - return cont( - pushlex("form"), - parenExpr, - expect("{"), - pushlex("}", "switch"), - pushblockcontext, - block, - poplex, - poplex, - popcontext - ); - if (type2 == "case") return cont(expression, expect(":")); - if (type2 == "default") return cont(expect(":")); - if (type2 == "catch") - return cont( - pushlex("form"), - pushcontext, - maybeCatchBinding, - statement, - poplex, - popcontext - ); - if (type2 == "export") - return cont(pushlex("stat"), afterExport, poplex); - if (type2 == "import") - return cont(pushlex("stat"), afterImport, poplex); - if (type2 == "async") return cont(statement); - if (value == "@") return cont(expression, statement); - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function maybeCatchBinding(type2) { - if (type2 == "(") return cont(funarg, expect(")")); - } - function expression(type2, value) { - return expressionInner(type2, value, false); - } - function expressionNoComma(type2, value) { - return expressionInner(type2, value, true); - } - function parenExpr(type2) { - if (type2 != "(") return pass(); - return cont( - pushlex(")"), - maybeexpression, - expect(")"), - poplex - ); - } - function expressionInner(type2, value, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type2 == "(") - return cont( - pushcontext, - pushlex(")"), - commasep(funarg, ")"), - poplex, - expect("=>"), - body, - popcontext - ); - else if (type2 == "variable") - return pass( - pushcontext, - pattern, - expect("=>"), - body, - popcontext - ); - } - var maybeop = noComma - ? maybeoperatorNoComma - : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); - if (type2 == "function") return cont(functiondef, maybeop); - if (type2 == "class" || (isTS && value == "interface")) { - cx.marked = "keyword"; - return cont(pushlex("form"), classExpression, poplex); - } - if (type2 == "keyword c" || type2 == "async") - return cont(noComma ? expressionNoComma : expression); - if (type2 == "(") - return cont( - pushlex(")"), - maybeexpression, - expect(")"), - poplex, - maybeop - ); - if (type2 == "operator" || type2 == "spread") - return cont(noComma ? expressionNoComma : expression); - if (type2 == "[") - return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type2 == "{") - return contCommasep(objprop, "}", null, maybeop); - if (type2 == "quasi") return pass(quasi, maybeop); - if (type2 == "new") return cont(maybeTarget(noComma)); - return cont(); - } - function maybeexpression(type2) { - if (type2.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - function maybeoperatorComma(type2, value) { - if (type2 == ",") return cont(maybeexpression); - return maybeoperatorNoComma(type2, value, false); - } - function maybeoperatorNoComma(type2, value, noComma) { - var me = - noComma == false - ? maybeoperatorComma - : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type2 == "=>") - return cont( - pushcontext, - noComma ? arrowBodyNoComma : arrowBody, - popcontext - ); - if (type2 == "operator") { - if (/\+\+|--/.test(value) || (isTS && value == "!")) - return cont(me); - if ( - isTS && - value == "<" && - cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false) - ) - return cont( - pushlex(">"), - commasep(typeexpr, ">"), - poplex, - me - ); - if (value == "?") - return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type2 == "quasi") { - return pass(quasi, me); - } - if (type2 == ";") return; - if (type2 == "(") - return contCommasep(expressionNoComma, ")", "call", me); - if (type2 == ".") return cont(property, me); - if (type2 == "[") - return cont( - pushlex("]"), - maybeexpression, - expect("]"), - poplex, - me - ); - if (isTS && value == "as") { - cx.marked = "keyword"; - return cont(typeexpr, me); - } - if (type2 == "regexp") { - cx.state.lastType = cx.marked = "operator"; - cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); - return cont(expr); - } - } - function quasi(type2, value) { - if (type2 != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(maybeexpression, continueQuasi); - } - function continueQuasi(type2) { - if (type2 == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); - } - } - function arrowBody(type2) { - findFatArrow(cx.stream, cx.state); - return pass(type2 == "{" ? statement : expression); - } - function arrowBodyNoComma(type2) { - findFatArrow(cx.stream, cx.state); - return pass(type2 == "{" ? statement : expressionNoComma); - } - function maybeTarget(noComma) { - return function (type2) { - if (type2 == ".") - return cont(noComma ? targetNoComma : target); - else if (type2 == "variable" && isTS) - return cont( - maybeTypeArgs, - noComma ? maybeoperatorNoComma : maybeoperatorComma - ); - else return pass(noComma ? expressionNoComma : expression); - }; - } - function target(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorComma); - } - } - function targetNoComma(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorNoComma); - } - } - function maybelabel(type2) { - if (type2 == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type2) { - if (type2 == "variable") { - cx.marked = "property"; - return cont(); - } - } - function objprop(type2, value) { - if (type2 == "async") { - cx.marked = "property"; - return cont(objprop); - } else if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") - return cont(getterSetter); - var m; - if ( - isTS && - cx.state.fatArrowAt == cx.stream.start && - (m = cx.stream.match(/^\s*:\s*/, false)) - ) - cx.state.fatArrowAt = cx.stream.pos + m[0].length; - return cont(afterprop); - } else if (type2 == "number" || type2 == "string") { - cx.marked = jsonldMode - ? "property" - : cx.style + " property"; - return cont(afterprop); - } else if (type2 == "jsonld-keyword") { - return cont(afterprop); - } else if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(objprop); - } else if (type2 == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type2 == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } else if (type2 == ":") { - return pass(afterprop); - } - } - function getterSetter(type2) { - if (type2 != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type2) { - if (type2 == ":") return cont(expressionNoComma); - if (type2 == "(") return pass(functiondef); - } - function commasep(what, end, sep) { - function proceed(type2, value) { - if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(function (type3, value2) { - if (type3 == end || value2 == end) return pass(); - return pass(what); - }, proceed); - } - if (type2 == end || value == end) return cont(); - if (sep && sep.indexOf(";") > -1) return pass(what); - return cont(expect(end)); - } - return function (type2, value) { - if (type2 == end || value == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) - cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type2) { - if (type2 == "}") return cont(); - return pass(statement, block); - } - function maybetype(type2, value) { - if (isTS) { - if (type2 == ":") return cont(typeexpr); - if (value == "?") return cont(maybetype); - } - } - function maybetypeOrIn(type2, value) { - if (isTS && (type2 == ":" || value == "in")) - return cont(typeexpr); - } - function mayberettype(type2) { - if (isTS && type2 == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) - return cont(expression, isKW, typeexpr); - else return cont(typeexpr); - } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword"; - return cont(); - } - } - function typeexpr(type2, value) { - if ( - value == "keyof" || - value == "typeof" || - value == "infer" || - value == "readonly" - ) { - cx.marked = "keyword"; - return cont( - value == "typeof" ? expressionNoComma : typeexpr - ); - } - if (type2 == "variable" || value == "void") { - cx.marked = "type"; - return cont(afterType); - } - if (value == "|" || value == "&") return cont(typeexpr); - if (type2 == "string" || type2 == "number" || type2 == "atom") - return cont(afterType); - if (type2 == "[") - return cont( - pushlex("]"), - commasep(typeexpr, "]", ","), - poplex, - afterType - ); - if (type2 == "{") - return cont(pushlex("}"), typeprops, poplex, afterType); - if (type2 == "(") - return cont( - commasep(typearg, ")"), - maybeReturnType, - afterType - ); - if (type2 == "<") - return cont(commasep(typeexpr, ">"), typeexpr); - if (type2 == "quasi") { - return pass(quasiType, afterType); - } - } - function maybeReturnType(type2) { - if (type2 == "=>") return cont(typeexpr); - } - function typeprops(type2) { - if (type2.match(/[\}\)\]]/)) return cont(); - if (type2 == "," || type2 == ";") return cont(typeprops); - return pass(typeprop, typeprops); - } - function typeprop(type2, value) { - if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(typeprop); - } else if ( - value == "?" || - type2 == "number" || - type2 == "string" - ) { - return cont(typeprop); - } else if (type2 == ":") { - return cont(typeexpr); - } else if (type2 == "[") { - return cont( - expect("variable"), - maybetypeOrIn, - expect("]"), - typeprop - ); - } else if (type2 == "(") { - return pass(functiondecl, typeprop); - } else if (!type2.match(/[;\}\)\],]/)) { - return cont(); - } - } - function quasiType(type2, value) { - if (type2 != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") - return cont(quasiType); - return cont(typeexpr, continueQuasiType); - } - function continueQuasiType(type2) { - if (type2 == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasiType); - } - } - function typearg(type2, value) { - if ( - (type2 == "variable" && - cx.stream.match(/^\s*[?:]/, false)) || - value == "?" - ) - return cont(typearg); - if (type2 == ":") return cont(typeexpr); - if (type2 == "spread") return cont(typearg); - return pass(typeexpr); - } - function afterType(type2, value) { - if (value == "<") - return cont( - pushlex(">"), - commasep(typeexpr, ">"), - poplex, - afterType - ); - if (value == "|" || type2 == "." || value == "&") - return cont(typeexpr); - if (type2 == "[") - return cont(typeexpr, expect("]"), afterType); - if (value == "extends" || value == "implements") { - cx.marked = "keyword"; - return cont(typeexpr); - } - if (value == "?") - return cont(typeexpr, expect(":"), typeexpr); - } - function maybeTypeArgs(_, value) { - if (value == "<") - return cont( - pushlex(">"), - commasep(typeexpr, ">"), - poplex, - afterType - ); - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault); - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr); - } - function vardef(_, value) { - if (value == "enum") { - cx.marked = "keyword"; - return cont(enumdef); - } - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type2, value) { - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(pattern); - } - if (type2 == "variable") { - register(value); - return cont(); - } - if (type2 == "spread") return cont(pattern); - if (type2 == "[") return contCommasep(eltpattern, "]"); - if (type2 == "{") return contCommasep(proppattern, "}"); - } - function proppattern(type2, value) { - if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type2 == "variable") cx.marked = "property"; - if (type2 == "spread") return cont(pattern); - if (type2 == "}") return pass(); - if (type2 == "[") - return cont( - expression, - expect("]"), - expect(":"), - proppattern - ); - return cont(expect(":"), pattern, maybeAssign); - } - function eltpattern() { - return pass(pattern, maybeAssign); - } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); - } - function vardefCont(type2) { - if (type2 == ",") return cont(vardef); - } - function maybeelse(type2, value) { - if (type2 == "keyword b" && value == "else") - return cont(pushlex("form", "else"), statement, poplex); - } - function forspec(type2, value) { - if (value == "await") return cont(forspec); - if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); - } - function forspec1(type2) { - if (type2 == "var") return cont(vardef, forspec2); - if (type2 == "variable") return cont(forspec2); - return pass(forspec2); - } - function forspec2(type2, value) { - if (type2 == ")") return cont(); - if (type2 == ";") return cont(forspec2); - if (value == "in" || value == "of") { - cx.marked = "keyword"; - return cont(expression, forspec2); - } - return pass(expression, forspec2); - } - function functiondef(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondef); - } - if (type2 == "variable") { - register(value); - return cont(functiondef); - } - if (type2 == "(") - return cont( - pushcontext, - pushlex(")"), - commasep(funarg, ")"), - poplex, - mayberettype, - statement, - popcontext - ); - if (isTS && value == "<") - return cont( - pushlex(">"), - commasep(typeparam, ">"), - poplex, - functiondef - ); - } - function functiondecl(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondecl); - } - if (type2 == "variable") { - register(value); - return cont(functiondecl); - } - if (type2 == "(") - return cont( - pushcontext, - pushlex(")"), - commasep(funarg, ")"), - poplex, - mayberettype, - popcontext - ); - if (isTS && value == "<") - return cont( - pushlex(">"), - commasep(typeparam, ">"), - poplex, - functiondecl - ); - } - function typename(type2, value) { - if (type2 == "keyword" || type2 == "variable") { - cx.marked = "type"; - return cont(typename); - } else if (value == "<") { - return cont(pushlex(">"), commasep(typeparam, ">"), poplex); - } - } - function funarg(type2, value) { - if (value == "@") cont(expression, funarg); - if (type2 == "spread") return cont(funarg); - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(funarg); - } - if (isTS && type2 == "this") - return cont(maybetype, maybeAssign); - return pass(pattern, maybetype, maybeAssign); - } - function classExpression(type2, value) { - if (type2 == "variable") return className(type2, value); - return classNameAfter(type2, value); - } - function className(type2, value) { - if (type2 == "variable") { - register(value); - return cont(classNameAfter); - } - } - function classNameAfter(type2, value) { - if (value == "<") - return cont( - pushlex(">"), - commasep(typeparam, ">"), - poplex, - classNameAfter - ); - if ( - value == "extends" || - value == "implements" || - (isTS && type2 == ",") - ) { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); - } - if (type2 == "{") - return cont(pushlex("}"), classBody, poplex); - } - function classBody(type2, value) { - if ( - type2 == "async" || - (type2 == "variable" && - (value == "static" || - value == "get" || - value == "set" || - (isTS && isModifier(value))) && - cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) - ) { - cx.marked = "keyword"; - return cont(classBody); - } - if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(classfield, classBody); - } - if (type2 == "number" || type2 == "string") - return cont(classfield, classBody); - if (type2 == "[") - return cont( - expression, - maybetype, - expect("]"), - classfield, - classBody - ); - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (isTS && type2 == "(") - return pass(functiondecl, classBody); - if (type2 == ";" || type2 == ",") return cont(classBody); - if (type2 == "}") return cont(); - if (value == "@") return cont(expression, classBody); - } - function classfield(type2, value) { - if (value == "!") return cont(classfield); - if (value == "?") return cont(classfield); - if (type2 == ":") return cont(typeexpr, maybeAssign); - if (value == "=") return cont(expressionNoComma); - var context = cx.state.lexical.prev, - isInterface = context && context.info == "interface"; - return pass(isInterface ? functiondecl : functiondef); - } - function afterExport(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(maybeFrom, expect(";")); - } - if (value == "default") { - cx.marked = "keyword"; - return cont(expression, expect(";")); - } - if (type2 == "{") - return cont( - commasep(exportField, "}"), - maybeFrom, - expect(";") - ); - return pass(statement); - } - function exportField(type2, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(expect("variable")); - } - if (type2 == "variable") - return pass(expressionNoComma, exportField); - } - function afterImport(type2) { - if (type2 == "string") return cont(); - if (type2 == "(") return pass(expression); - if (type2 == ".") return pass(maybeoperatorComma); - return pass(importSpec, maybeMoreImports, maybeFrom); - } - function importSpec(type2, value) { - if (type2 == "{") return contCommasep(importSpec, "}"); - if (type2 == "variable") register(value); - if (value == "*") cx.marked = "keyword"; - return cont(maybeAs); - } - function maybeMoreImports(type2) { - if (type2 == ",") return cont(importSpec, maybeMoreImports); - } - function maybeAs(_type, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(importSpec); - } - } - function maybeFrom(_type, value) { - if (value == "from") { - cx.marked = "keyword"; - return cont(expression); - } - } - function arrayLiteral(type2) { - if (type2 == "]") return cont(); - return pass(commasep(expressionNoComma, "]")); - } - function enumdef() { - return pass( - pushlex("form"), - pattern, - expect("{"), - pushlex("}"), - commasep(enummember, "}"), - poplex, - poplex - ); - } - function enummember() { - return pass(pattern, maybeAssign); - } - function isContinuedStatement(state, textAfter) { - return ( - state.lastType == "operator" || - state.lastType == "," || - isOperatorChar.test(textAfter.charAt(0)) || - /[,.]/.test(textAfter.charAt(0)) - ); - } - function expressionAllowed(stream, state, backUp) { - return ( - (state.tokenize == tokenBase && - /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test( - state.lastType - )) || - (state.lastType == "quasi" && - /\{\s*$/.test( - stream.string.slice(0, stream.pos - (backUp || 0)) - )) - ); - } - return { - startState: function (basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical( - (basecolumn || 0) - indentUnit, - 0, - "block", - false - ), - localVars: parserConfig.localVars, - context: - parserConfig.localVars && - new Context(null, null, false), - indented: basecolumn || 0, - }; - if ( - parserConfig.globalVars && - typeof parserConfig.globalVars == "object" - ) - state.globalVars = parserConfig.globalVars; - return state; - }, - token: function (stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) - return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = - type == "operator" && (content == "++" || content == "--") - ? "incdec" - : type; - return parseJS(state, style, type, content, stream); - }, - indent: function (state, textAfter) { - if ( - state.tokenize == tokenComment || - state.tokenize == tokenQuasi - ) - return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), - lexical = state.lexical, - top; - if (!/^\s*else\b/.test(textAfter)) - for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev; - else if (c != maybeelse && c != popcontext) break; - } - while ( - (lexical.type == "stat" || lexical.type == "form") && - (firstChar == "}" || - ((top = state.cc[state.cc.length - 1]) && - (top == maybeoperatorComma || - top == maybeoperatorNoComma) && - !/^[,\.=+\-*:?[\(]/.test(textAfter))) - ) - lexical = lexical.prev; - if ( - statementIndent && - lexical.type == ")" && - lexical.prev.type == "stat" - ) - lexical = lexical.prev; - var type2 = lexical.type, - closing = firstChar == type2; - if (type2 == "vardef") - return ( - lexical.indented + - (state.lastType == "operator" || state.lastType == "," - ? lexical.info.length + 1 - : 0) - ); - else if (type2 == "form" && firstChar == "{") - return lexical.indented; - else if (type2 == "form") - return lexical.indented + indentUnit; - else if (type2 == "stat") - return ( - lexical.indented + - (isContinuedStatement(state, textAfter) - ? statementIndent || indentUnit - : 0) - ); - else if ( - lexical.info == "switch" && - !closing && - parserConfig.doubleIndentSwitch != false - ) - return ( - lexical.indented + - (/^(?:case|default)\b/.test(textAfter) - ? indentUnit - : 2 * indentUnit) - ); - else if (lexical.align) - return lexical.column + (closing ? 0 : 1); - else return lexical.indented + (closing ? 0 : indentUnit); - }, - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - blockCommentContinue: jsonMode ? null : " * ", - lineComment: jsonMode ? null : "//", - fold: "brace", - closeBrackets: "()[]{}''\"\"``", - helperType: jsonMode ? "json" : "javascript", - jsonldMode, - jsonMode, - expressionAllowed, - skipExpression: function (state) { - parseJS( - state, - "atom", - "atom", - "true", - new CodeMirror.StringStream("", 2, null) - ); - }, - }; + info.inputType = (_b = info.argDef) === null || _b === void 0 ? void 0 : _b.type; + break; + case "EnumValue": + const enumType = info.inputType ? graphql.getNamedType(info.inputType) : null; + info.enumValue = enumType instanceof graphql.GraphQLEnumType ? find(enumType.getValues(), val => val.value === state.name) : null; + break; + case "ListValue": + const nullableType = info.inputType ? graphql.getNullableType(info.inputType) : null; + info.inputType = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; + break; + case "ObjectValue": + const objectType = info.inputType ? graphql.getNamedType(info.inputType) : null; + info.objectFieldDefs = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; + break; + case "ObjectField": + const objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null; + info.inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; + info.fieldDef = objectField; + break; + case "NamedType": + info.type = state.name ? schema.getType(state.name) : null; + break; + } + }); + return info; + } + function getFieldDef(schema, type, fieldName) { + if (fieldName === graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { + return graphql.SchemaMetaFieldDef; + } + if (fieldName === graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { + return graphql.TypeMetaFieldDef; + } + if (fieldName === graphql.TypeNameMetaFieldDef.name && graphql.isCompositeType(type)) { + return graphql.TypeNameMetaFieldDef; + } + if (type && type.getFields) { + return type.getFields()[fieldName]; + } + } + function find(array, predicate) { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { + return array[i]; + } + } + } + function getFieldReference(typeInfo) { + return { + kind: "Field", + schema: typeInfo.schema, + field: typeInfo.fieldDef, + type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType + }; + } + function getDirectiveReference(typeInfo) { + return { + kind: "Directive", + schema: typeInfo.schema, + directive: typeInfo.directiveDef + }; + } + function getArgumentReference(typeInfo) { + return typeInfo.directiveDef ? { + kind: "Argument", + schema: typeInfo.schema, + argument: typeInfo.argDef, + directive: typeInfo.directiveDef + } : { + kind: "Argument", + schema: typeInfo.schema, + argument: typeInfo.argDef, + field: typeInfo.fieldDef, + type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType + }; + } + function getEnumValueReference(typeInfo) { + return { + kind: "EnumValue", + value: typeInfo.enumValue || void 0, + type: typeInfo.inputType ? graphql.getNamedType(typeInfo.inputType) : void 0 + }; + } + function getTypeReference(typeInfo, type) { + return { + kind: "Type", + schema: typeInfo.schema, + type: type || typeInfo.type + }; + } + function isMetaField(fieldDef) { + return fieldDef.name.slice(0, 2) === "__"; + } + exports.getArgumentReference = getArgumentReference; + exports.getDirectiveReference = getDirectiveReference; + exports.getEnumValueReference = getEnumValueReference; + exports.getFieldReference = getFieldReference; + exports.getTypeInfo = getTypeInfo; + exports.getTypeReference = getTypeReference; + + /***/ }), + + /***/ "../../graphiql-react/dist/brace-fold.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/brace-fold.cjs.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var braceFold$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function bracketFolding(pairs) { + return function (cm, start) { + var line = start.line, + lineText = cm.getLine(line); + function findOpening(pair) { + var tokenType; + for (var at = start.ch, pass = 0;;) { + var found2 = at <= 0 ? -1 : lineText.lastIndexOf(pair[0], at - 1); + if (found2 == -1) { + if (pass == 1) break; + pass = 1; + at = lineText.length; + continue; } - ); - CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - CodeMirror.defineMIME("text/javascript", "javascript"); - CodeMirror.defineMIME("text/ecmascript", "javascript"); - CodeMirror.defineMIME("application/javascript", "javascript"); - CodeMirror.defineMIME("application/x-javascript", "javascript"); - CodeMirror.defineMIME("application/ecmascript", "javascript"); - CodeMirror.defineMIME("application/json", { - name: "javascript", - json: true, - }); - CodeMirror.defineMIME("application/x-json", { - name: "javascript", - json: true, - }); - CodeMirror.defineMIME("application/manifest+json", { - name: "javascript", - json: true, - }); - CodeMirror.defineMIME("application/ld+json", { - name: "javascript", - jsonld: true, - }); - CodeMirror.defineMIME("text/typescript", { - name: "javascript", - typescript: true, - }); - CodeMirror.defineMIME("application/typescript", { - name: "javascript", - typescript: true, - }); - }); - })(); - var javascriptExports = javascript$2.exports; - const javascript = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(javascriptExports); - const javascript$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: javascript, - }, - [javascriptExports] - ); - exports.javascript = javascript$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/jump-to-line.cjs.js": - /*!*****************************************************!*\ - !*** ../../graphiql-react/dist/jump-to-line.cjs.js ***! - \*****************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - const dialog = __webpack_require__( - /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); + if (pass == 1 && found2 < start.ch) break; + tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found2 + 1)); + if (!/^(comment|string)/.test(tokenType)) return { + ch: found2 + 1, + tokenType, + pair + }; + at = found2 - 1; + } + } + function findRange(found2) { + var count = 1, + lastLine = cm.lastLine(), + end, + startCh = found2.ch, + endCh; + outer: for (var i2 = line; i2 <= lastLine; ++i2) { + var text = cm.getLine(i2), + pos = i2 == line ? startCh : 0; + for (;;) { + var nextOpen = text.indexOf(found2.pair[0], pos), + nextClose = text.indexOf(found2.pair[1], pos); + if (nextOpen < 0) nextOpen = text.length; + if (nextClose < 0) nextClose = text.length; + pos = Math.min(nextOpen, nextClose); + if (pos == text.length) break; + if (cm.getTokenTypeAt(CodeMirror.Pos(i2, pos + 1)) == found2.tokenType) { + if (pos == nextOpen) ++count;else if (! --count) { + end = i2; + endCh = pos; + break outer; } } + ++pos; } } + if (end == null || line == end) return null; + return { + from: CodeMirror.Pos(line, startCh), + to: CodeMirror.Pos(end, endCh) + }; } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); - } - var jumpToLine$2 = { - exports: {}, + var found = []; + for (var i = 0; i < pairs.length; i++) { + var open = findOpening(pairs[i]); + if (open) found.push(open); + } + found.sort(function (a, b) { + return a.ch - b.ch; + }); + for (var i = 0; i < found.length; i++) { + var range = findRange(found[i]); + if (range) return range; + } + return null; }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), dialog.dialogExports); - })(function (CodeMirror) { - CodeMirror.defineOption("search", { - bottom: false, - }); - function dialog2(cm, text, shortText, deflt, f) { - if (cm.openDialog) - cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom, - }); - else f(prompt(shortText, deflt)); - } - function getJumpDialog(cm) { - return ( - cm.phrase("Jump to line:") + - ' ' + - cm.phrase("(Use line:column or scroll% syntax)") + - "" - ); - } - function interpretLine(cm, string) { - var num = Number(string); - if (/^[-+]/.test(string)) return cm.getCursor().line + num; - else return num - 1; - } - CodeMirror.commands.jumpToLine = function (cm) { - var cur = cm.getCursor(); - dialog2( - cm, - getJumpDialog(cm), - cm.phrase("Jump to line:"), - cur.line + 1 + ":" + cur.ch, - function (posStr) { - if (!posStr) return; - var match; - if ( - (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) - ) { - cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); - } else if ( - (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) - ) { - var line = Math.round( - (cm.lineCount() * Number(match[1])) / 100 - ); - if (/^[-+]/.test(match[1])) line = cur.line + line + 1; - cm.setCursor(line - 1, cur.ch); - } else if ( - (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) - ) { - cm.setCursor(interpretLine(cm, match[1]), cur.ch); - } - } - ); + } + CodeMirror.registerHelper("fold", "brace", bracketFolding([["{", "}"], ["[", "]"]])); + CodeMirror.registerHelper("fold", "brace-paren", bracketFolding([["{", "}"], ["[", "]"], ["(", ")"]])); + CodeMirror.registerHelper("fold", "import", function (cm, start) { + function hasImport(line) { + if (line < cm.firstLine() || line > cm.lastLine()) return null; + var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); + if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); + if (start2.type != "keyword" || start2.string != "import") return null; + for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) { + var text = cm.getLine(i), + semi = text.indexOf(";"); + if (semi != -1) return { + startCh: start2.end, + end: CodeMirror.Pos(i, semi) }; - CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; - }); - })(); - var jumpToLineExports = jumpToLine$2.exports; - const jumpToLine = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(jumpToLineExports); - const jumpToLine$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: jumpToLine, - }, - [jumpToLineExports] - ); - exports.jumpToLine = jumpToLine$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/jump.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/jump.cjs.js ***! - \*********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const SchemaReference = __webpack_require__( - /*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js" - ); - codemirror.CodeMirror.defineOption( - "jump", - false, - (cm, options, old) => { - if (old && old !== codemirror.CodeMirror.Init) { - const oldOnMouseOver = cm.state.jump.onMouseOver; - codemirror.CodeMirror.off( - cm.getWrapperElement(), - "mouseover", - oldOnMouseOver - ); - const oldOnMouseOut = cm.state.jump.onMouseOut; - codemirror.CodeMirror.off( - cm.getWrapperElement(), - "mouseout", - oldOnMouseOut - ); - codemirror.CodeMirror.off( - document, - "keydown", - cm.state.jump.onKeyDown - ); - delete cm.state.jump; - } - if (options) { - const state = (cm.state.jump = { - options, - onMouseOver: onMouseOver.bind(null, cm), - onMouseOut: onMouseOut.bind(null, cm), - onKeyDown: onKeyDown.bind(null, cm), + } + } + var startLine = start.line, + has = hasImport(startLine), + prev; + if (!has || hasImport(startLine - 1) || (prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1) return null; + for (var end = has.end;;) { + var next = hasImport(end.line + 1); + if (next == null) break; + end = next.end; + } + return { + from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), + to: end + }; + }); + CodeMirror.registerHelper("fold", "include", function (cm, start) { + function hasInclude(line) { + if (line < cm.firstLine() || line > cm.lastLine()) return null; + var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); + if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); + if (start2.type == "meta" && start2.string.slice(0, 8) == "#include") return start2.start + 8; + } + var startLine = start.line, + has = hasInclude(startLine); + if (has == null || hasInclude(startLine - 1) != null) return null; + for (var end = startLine;;) { + var next = hasInclude(end + 1); + if (next == null) break; + ++end; + } + return { + from: CodeMirror.Pos(startLine, has + 1), + to: cm.clipPos(CodeMirror.Pos(end)) + }; + }); + }); + })(); + var braceFoldExports = braceFold$2.exports; + const braceFold = /* @__PURE__ */codemirror.getDefaultExportFromCjs(braceFoldExports); + const braceFold$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: braceFold + }, [braceFoldExports]); + exports.braceFold = braceFold$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/closebrackets.cjs.js": + /*!******************************************************!*\ + !*** ../../graphiql-react/dist/closebrackets.cjs.js ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] }); - codemirror.CodeMirror.on( - cm.getWrapperElement(), - "mouseover", - state.onMouseOver - ); - codemirror.CodeMirror.on( - cm.getWrapperElement(), - "mouseout", - state.onMouseOut - ); - codemirror.CodeMirror.on(document, "keydown", state.onKeyDown); } } - ); - function onMouseOver(cm, event) { - const target = event.target || event.srcElement; - if (!(target instanceof HTMLElement)) { - return; - } - if ( - (target === null || target === void 0 - ? void 0 - : target.nodeName) !== "SPAN" - ) { - return; + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var closebrackets$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var defaults = { + pairs: `()[]{}''""`, + closeBefore: `)]}'":;>`, + triples: "", + explode: "[]{}" + }; + var Pos = CodeMirror.Pos; + CodeMirror.defineOption("autoCloseBrackets", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.removeKeyMap(keyMap); + cm.state.closeBrackets = null; + } + if (val) { + ensureBound(getOption(val, "pairs")); + cm.state.closeBrackets = val; + cm.addKeyMap(keyMap); + } + }); + function getOption(conf, name) { + if (name == "pairs" && typeof conf == "string") return conf; + if (typeof conf == "object" && conf[name] != null) return conf[name]; + return defaults[name]; + } + var keyMap = { + Backspace: handleBackspace, + Enter: handleEnter + }; + function ensureBound(chars) { + for (var i = 0; i < chars.length; i++) { + var ch = chars.charAt(i), + key = "'" + ch + "'"; + if (!keyMap[key]) keyMap[key] = handler(ch); + } + } + ensureBound(defaults.pairs + "`"); + function handler(ch) { + return function (cm) { + return handleChar(cm, ch); + }; + } + function getConfig(cm) { + var deflt = cm.state.closeBrackets; + if (!deflt || deflt.override) return deflt; + var mode = cm.getModeAt(cm.getCursor()); + return mode.closeBrackets || deflt; + } + function handleBackspace(cm) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + var pairs = getOption(conf, "pairs"); + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; + } + for (var i = ranges.length - 1; i >= 0; i--) { + var cur = ranges[i].head; + cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); + } + } + function handleEnter(cm) { + var conf = getConfig(cm); + var explode = conf && getOption(conf, "explode"); + if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; + } + cm.operation(function () { + var linesep = cm.lineSeparator() || "\n"; + cm.replaceSelection(linesep + linesep, null); + moveSel(cm, -1); + ranges = cm.listSelections(); + for (var i2 = 0; i2 < ranges.length; i2++) { + var line = ranges[i2].head.line; + cm.indentLine(line, null, true); + cm.indentLine(line + 1, null, true); } - const box = target.getBoundingClientRect(); - const cursor = { - left: (box.left + box.right) / 2, - top: (box.top + box.bottom) / 2, + }); + } + function moveSel(cm, dir) { + var newRanges = [], + ranges = cm.listSelections(), + primary = 0; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head == cm.getCursor()) primary = i; + var pos = range.head.ch || dir > 0 ? { + line: range.head.line, + ch: range.head.ch + dir + } : { + line: range.head.line - 1 }; - cm.state.jump.cursor = cursor; - if (cm.state.jump.isHoldingModifier) { - enableJumpMode(cm); + newRanges.push({ + anchor: pos, + head: pos + }); + } + cm.setSelections(newRanges, primary); + } + function contractSelection(sel) { + var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; + return { + anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), + head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1)) + }; + } + function handleChar(cm, ch) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + var pairs = getOption(conf, "pairs"); + var pos = pairs.indexOf(ch); + if (pos == -1) return CodeMirror.Pass; + var closeBefore = getOption(conf, "closeBefore"); + var triples = getOption(conf, "triples"); + var identical = pairs.charAt(pos + 1) == ch; + var ranges = cm.listSelections(); + var opening = pos % 2 == 0; + var type; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + cur = range.head, + curType; + var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); + if (opening && !range.empty()) { + curType = "surround"; + } else if ((identical || !opening) && next == ch) { + if (identical && stringStartsAfter(cm, cur)) curType = "both";else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree";else curType = "skip"; + } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { + if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; + curType = "addFour"; + } else if (identical) { + var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur); + if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";else return CodeMirror.Pass; + } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { + curType = "both"; + } else { + return CodeMirror.Pass; + } + if (!type) type = curType;else if (type != curType) return CodeMirror.Pass; + } + var left = pos % 2 ? pairs.charAt(pos - 1) : ch; + var right = pos % 2 ? ch : pairs.charAt(pos + 1); + cm.operation(function () { + if (type == "skip") { + moveSel(cm, 1); + } else if (type == "skipThree") { + moveSel(cm, 3); + } else if (type == "surround") { + var sels = cm.getSelections(); + for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = left + sels[i2] + right; + cm.replaceSelections(sels, "around"); + sels = cm.listSelections().slice(); + for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = contractSelection(sels[i2]); + cm.setSelections(sels); + } else if (type == "both") { + cm.replaceSelection(left + right, null); + cm.triggerElectric(left + right); + moveSel(cm, -1); + } else if (type == "addFour") { + cm.replaceSelection(left + left + left + left, "before"); + moveSel(cm, 1); + } + }); + } + function charsAround(cm, pos) { + var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); + return str.length == 2 ? str : null; + } + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)); + return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))); + } + }); + })(); + var closebracketsExports = closebrackets$2.exports; + const closebrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(closebracketsExports); + const closebrackets$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: closebrackets + }, [closebracketsExports]); + exports.closebrackets = closebrackets$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/codemirror.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/codemirror.cjs.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror$1 = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } } - function onMouseOut(cm) { - if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) { - cm.state.jump.cursor = null; - return; + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var codemirrorExports = codemirror$1.requireCodemirror(); + const CodeMirror = /* @__PURE__ */codemirror$1.getDefaultExportFromCjs(codemirrorExports); + const codemirror = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: CodeMirror + }, [codemirrorExports]); + exports.CodeMirror = CodeMirror; + exports.codemirror = codemirror; + + /***/ }), + + /***/ "../../graphiql-react/dist/codemirror.cjs2.js": + /*!****************************************************!*\ + !*** ../../graphiql-react/dist/codemirror.cjs2.js ***! + \****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : {}; + function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; + } + var codemirror = { + exports: {} + }; + var hasRequiredCodemirror; + function requireCodemirror() { + if (hasRequiredCodemirror) return codemirror.exports; + hasRequiredCodemirror = 1; + (function (module2, exports2) { + (function (global2, factory) { + module2.exports = factory(); + })(commonjsGlobal, function () { + var userAgent = navigator.userAgent; + var platform = navigator.platform; + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var edge = /Edge\/(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up || edge; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); + var webkit = !edge && /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = !edge && /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); + var android = /Android/.test(userAgent); + var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) { + presto_version = Number(presto_version[1]); + } + if (presto_version && presto_version >= 15) { + presto = false; + webkit = true; + } + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || ie && ie_version >= 9; + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); + } + var rmClass = function (node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); } - if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) { - disableJumpMode(cm); + }; + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) { + e.removeChild(e.firstChild); } + return e; } - function onKeyDown(cm, event) { - if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) { - return; + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) { + e.className = className; } - cm.state.jump.isHoldingModifier = true; - if (cm.state.jump.cursor) { - enableJumpMode(cm); + if (style) { + e.style.cssText = style; } - const onKeyUp = (upEvent) => { - if (upEvent.code !== event.code) { - return; - } - cm.state.jump.isHoldingModifier = false; - if (cm.state.jump.marker) { - disableJumpMode(cm); - } - codemirror.CodeMirror.off(document, "keyup", onKeyUp); - codemirror.CodeMirror.off(document, "click", onClick); - cm.off("mousedown", onMouseDown); - }; - const onClick = (clickEvent) => { - const { destination, options } = cm.state.jump; - if (destination) { - options.onClick(destination, clickEvent); + if (typeof content == "string") { + e.appendChild(document.createTextNode(content)); + } else if (content) { + for (var i2 = 0; i2 < content.length; ++i2) { + e.appendChild(content[i2]); } + } + return e; + } + function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style); + e.setAttribute("role", "presentation"); + return e; + } + var range; + if (document.createRange) { + range = function (node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; }; - const onMouseDown = (_, downEvent) => { - if (cm.state.jump.destination) { - downEvent.codemirrorIgnore = true; + } else { + range = function (node, start, end) { + var r = document.body.createTextRange(); + try { + r.moveToElementText(node.parentNode); + } catch (e) { + return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; }; - codemirror.CodeMirror.on(document, "keyup", onKeyUp); - codemirror.CodeMirror.on(document, "click", onClick); - cm.on("mousedown", onMouseDown); - } - const isMac = - typeof navigator !== "undefined" && - (navigator === null || navigator === void 0 - ? void 0 - : navigator.appVersion.includes("Mac")); - function isJumpModifier(key) { - return key === (isMac ? "Meta" : "Control"); - } - function enableJumpMode(cm) { - if (cm.state.jump.marker) { - return; + } + function contains(parent, child) { + if (child.nodeType == 3) { + child = child.parentNode; } - const { cursor, options } = cm.state.jump; - const pos = cm.coordsChar(cursor); - const token = cm.getTokenAt(pos, true); - const getDestination = - options.getDestination || cm.getHelper(pos, "jump"); - if (getDestination) { - const destination = getDestination(token, options, cm); - if (destination) { - const marker = cm.markText( - { - line: pos.line, - ch: token.start, - }, - { - line: pos.line, - ch: token.end, - }, - { - className: "CodeMirror-jump-token", - } - ); - cm.state.jump.marker = marker; - cm.state.jump.destination = destination; - } + if (parent.contains) { + return parent.contains(child); } - } - function disableJumpMode(cm) { - const { marker } = cm.state.jump; - cm.state.jump.marker = null; - cm.state.jump.destination = null; - marker.clear(); - } - codemirror.CodeMirror.registerHelper( - "jump", - "graphql", - (token, options) => { - if (!options.schema || !options.onClick || !token.state) { - return; - } - const { state } = token; - const { kind, step } = state; - const typeInfo = SchemaReference.getTypeInfo(options.schema, state); - if ( - (kind === "Field" && step === 0 && typeInfo.fieldDef) || - (kind === "AliasedField" && step === 2 && typeInfo.fieldDef) - ) { - return SchemaReference.getFieldReference(typeInfo); - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - return SchemaReference.getDirectiveReference(typeInfo); - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - return SchemaReference.getArgumentReference(typeInfo); - } - if (kind === "EnumValue" && typeInfo.enumValue) { - return SchemaReference.getEnumValueReference(typeInfo); + do { + if (child.nodeType == 11) { + child = child.host; } - if (kind === "NamedType" && typeInfo.type) { - return SchemaReference.getTypeReference(typeInfo); + if (child == parent) { + return true; } + } while (child = child.parentNode); + } + function activeElt() { + var activeElement; + try { + activeElement = document.activeElement; + } catch (e) { + activeElement = document.body || null; } - ); - - /***/ - }, - - /***/ "../../graphiql-react/dist/lint.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs.js ***! - \*********************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } - } - } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { + activeElement = activeElement.shadowRoot.activeElement; } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); + return activeElement; } - var lint$2 = { - exports: {}, - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var GUTTER_ID = "CodeMirror-lint-markers"; - var LINT_LINE_ID = "CodeMirror-lint-line-"; - function showTooltip(cm, e, content) { - var tt = document.createElement("div"); - tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; - tt.appendChild(content.cloneNode(true)); - if (cm.state.lint.options.selfContain) - cm.getWrapperElement().appendChild(tt); - else document.body.appendChild(tt); - function position(e2) { - if (!tt.parentNode) - return CodeMirror.off(document, "mousemove", position); - tt.style.top = - Math.max(0, e2.clientY - tt.offsetHeight - 5) + "px"; - tt.style.left = e2.clientX + 5 + "px"; - } - CodeMirror.on(document, "mousemove", position); - position(e); - if (tt.style.opacity != null) tt.style.opacity = 1; - return tt; - } - function rm(elt) { - if (elt.parentNode) elt.parentNode.removeChild(elt); - } - function hideTooltip(tt) { - if (!tt.parentNode) return; - if (tt.style.opacity == null) rm(tt); - tt.style.opacity = 0; - setTimeout(function () { - rm(tt); - }, 600); - } - function showTooltipFor(cm, e, content, node) { - var tooltip = showTooltip(cm, e, content); - function hide() { - CodeMirror.off(node, "mouseout", hide); - if (tooltip) { - hideTooltip(tooltip); - tooltip = null; - } - } - var poll = setInterval(function () { - if (tooltip) - for (var n = node; ; n = n.parentNode) { - if (n && n.nodeType == 11) n = n.host; - if (n == document.body) return; - if (!n) { - hide(); - break; - } - } - if (!tooltip) return clearInterval(poll); - }, 400); - CodeMirror.on(node, "mouseout", hide); - } - function LintState(cm, conf, hasGutter) { - this.marked = []; - if (conf instanceof Function) - conf = { - getAnnotations: conf, - }; - if (!conf || conf === true) conf = {}; - this.options = {}; - this.linterOptions = conf.options || {}; - for (var prop in defaults) this.options[prop] = defaults[prop]; - for (var prop in conf) { - if (defaults.hasOwnProperty(prop)) { - if (conf[prop] != null) this.options[prop] = conf[prop]; - } else if (!conf.options) { - this.linterOptions[prop] = conf[prop]; - } - } - this.timeout = null; - this.hasGutter = hasGutter; - this.onMouseOver = function (e) { - onMouseOver(cm, e); - }; - this.waitingFor = 0; - } - var defaults = { - highlightLines: false, - tooltips: true, - delay: 500, - lintOnChange: true, - getAnnotations: null, - async: false, - selfContain: null, - formatAnnotation: null, - onUpdateLinting: null, - }; - function clearMarks(cm) { - var state = cm.state.lint; - if (state.hasGutter) cm.clearGutter(GUTTER_ID); - if (state.options.highlightLines) clearErrorLines(cm); - for (var i = 0; i < state.marked.length; ++i) - state.marked[i].clear(); - state.marked.length = 0; - } - function clearErrorLines(cm) { - cm.eachLine(function (line) { - var has = - line.wrapClass && - /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); - if (has) cm.removeLineClass(line, "wrap", has[0]); - }); - } - function makeMarker(cm, labels, severity, multiple, tooltips) { - var marker = document.createElement("div"), - inner = marker; - marker.className = - "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; - if (multiple) { - inner = marker.appendChild(document.createElement("div")); - inner.className = - "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; - } - if (tooltips != false) - CodeMirror.on(inner, "mouseover", function (e) { - showTooltipFor(cm, e, labels, inner); - }); - return marker; - } - function getMaxSeverity(a, b) { - if (a == "error") return a; - else return b; - } - function groupByLine(annotations) { - var lines = []; - for (var i = 0; i < annotations.length; ++i) { - var ann = annotations[i], - line = ann.from.line; - (lines[line] || (lines[line] = [])).push(ann); - } - return lines; - } - function annotationTooltip(ann) { - var severity = ann.severity; - if (!severity) severity = "error"; - var tip = document.createElement("div"); - tip.className = - "CodeMirror-lint-message CodeMirror-lint-message-" + severity; - if (typeof ann.messageHTML != "undefined") { - tip.innerHTML = ann.messageHTML; - } else { - tip.appendChild(document.createTextNode(ann.message)); - } - return tip; - } - function lintAsync(cm, getAnnotations) { - var state = cm.state.lint; - var id = ++state.waitingFor; - function abort() { - id = -1; - cm.off("change", abort); - } - cm.on("change", abort); - getAnnotations( - cm.getValue(), - function (annotations, arg2) { - cm.off("change", abort); - if (state.waitingFor != id) return; - if (arg2 && annotations instanceof CodeMirror) - annotations = arg2; - cm.operation(function () { - updateLinting(cm, annotations); - }); - }, - state.linterOptions, - cm - ); - } - function startLinting(cm) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - var getAnnotations = - options.getAnnotations || - cm.getHelper(CodeMirror.Pos(0, 0), "lint"); - if (!getAnnotations) return; - if (options.async || getAnnotations.async) { - lintAsync(cm, getAnnotations); - } else { - var annotations = getAnnotations( - cm.getValue(), - state.linterOptions, - cm - ); - if (!annotations) return; - if (annotations.then) - annotations.then(function (issues) { - cm.operation(function () { - updateLinting(cm, issues); - }); - }); - else - cm.operation(function () { - updateLinting(cm, annotations); - }); - } - } - function updateLinting(cm, annotationsNotSorted) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - clearMarks(cm); - var annotations = groupByLine(annotationsNotSorted); - for (var line = 0; line < annotations.length; ++line) { - var anns = annotations[line]; - if (!anns) continue; - var message = []; - anns = anns.filter(function (item) { - return message.indexOf(item.message) > -1 - ? false - : message.push(item.message); - }); - var maxSeverity = null; - var tipLabel = - state.hasGutter && document.createDocumentFragment(); - for (var i = 0; i < anns.length; ++i) { - var ann = anns[i]; - var severity = ann.severity; - if (!severity) severity = "error"; - maxSeverity = getMaxSeverity(maxSeverity, severity); - if (options.formatAnnotation) - ann = options.formatAnnotation(ann); - if (state.hasGutter) - tipLabel.appendChild(annotationTooltip(ann)); - if (ann.to) - state.marked.push( - cm.markText(ann.from, ann.to, { - className: - "CodeMirror-lint-mark CodeMirror-lint-mark-" + - severity, - __annotation: ann, - }) - ); - } - if (state.hasGutter) - cm.setGutterMarker( - line, - GUTTER_ID, - makeMarker( - cm, - tipLabel, - maxSeverity, - annotations[line].length > 1, - options.tooltips - ) - ); - if (options.highlightLines) - cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); - } - if (options.onUpdateLinting) - options.onUpdateLinting(annotationsNotSorted, annotations, cm); - } - function onChange(cm) { - var state = cm.state.lint; - if (!state) return; - clearTimeout(state.timeout); - state.timeout = setTimeout(function () { - startLinting(cm); - }, state.options.delay); - } - function popupTooltips(cm, annotations, e) { - var target = e.target || e.srcElement; - var tooltip = document.createDocumentFragment(); - for (var i = 0; i < annotations.length; i++) { - var ann = annotations[i]; - tooltip.appendChild(annotationTooltip(ann)); - } - showTooltipFor(cm, e, tooltip, target); - } - function onMouseOver(cm, e) { - var target = e.target || e.srcElement; - if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; - var box = target.getBoundingClientRect(), - x = (box.left + box.right) / 2, - y = (box.top + box.bottom) / 2; - var spans = cm.findMarksAt( - cm.coordsChar( - { - left: x, - top: y, - }, - "client" - ) - ); - var annotations = []; - for (var i = 0; i < spans.length; ++i) { - var ann = spans[i].__annotation; - if (ann) annotations.push(ann); - } - if (annotations.length) popupTooltips(cm, annotations, e); - } - CodeMirror.defineOption("lint", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - clearMarks(cm); - if (cm.state.lint.options.lintOnChange !== false) - cm.off("change", onChange); - CodeMirror.off( - cm.getWrapperElement(), - "mouseover", - cm.state.lint.onMouseOver - ); - clearTimeout(cm.state.lint.timeout); - delete cm.state.lint; - } - if (val) { - var gutters = cm.getOption("gutters"), - hasLintGutter = false; - for (var i = 0; i < gutters.length; ++i) - if (gutters[i] == GUTTER_ID) hasLintGutter = true; - var state = (cm.state.lint = new LintState( - cm, - val, - hasLintGutter - )); - if (state.options.lintOnChange) cm.on("change", onChange); - if ( - state.options.tooltips != false && - state.options.tooltips != "gutter" - ) - CodeMirror.on( - cm.getWrapperElement(), - "mouseover", - state.onMouseOver - ); - startLinting(cm); - } - }); - CodeMirror.defineExtension("performLint", function () { - startLinting(this); - }); - }); - })(); - var lintExports = lint$2.exports; - const lint = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(lintExports); - const lint$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: lint, - }, - [lintExports] - ); - exports.lint = lint$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/lint.cjs2.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs2.js ***! - \**********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const graphqlLanguageService = __webpack_require__( - /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" - ); - const SEVERITY = ["error", "warning", "information", "hint"]; - const TYPE = { - "GraphQL: Validation": "validation", - "GraphQL: Deprecation": "deprecation", - "GraphQL: Syntax": "syntax", - }; - codemirror.CodeMirror.registerHelper( - "lint", - "graphql", - (text, options) => { - const { schema, validationRules, externalFragments } = options; - const rawResults = graphqlLanguageService.getDiagnostics( - text, - schema, - validationRules, - void 0, - externalFragments - ); - const results = rawResults.map((error) => ({ - message: error.message, - severity: error.severity - ? SEVERITY[error.severity - 1] - : SEVERITY[0], - type: error.source ? TYPE[error.source] : void 0, - from: codemirror.CodeMirror.Pos( - error.range.start.line, - error.range.start.character - ), - to: codemirror.CodeMirror.Pos( - error.range.end.line, - error.range.end.character - ), - })); - return results; + function addClass(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) { + node.className += (current ? " " : "") + cls; } - ); - - /***/ - }, - - /***/ "../../graphiql-react/dist/lint.cjs3.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs3.js ***! - \**********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function jsonParse(str) { - string = str; - strLen = str.length; - start = end = lastEnd = -1; - ch(); - lex(); - const ast = parseObj(); - expect("EOF"); - return ast; - } - let string; - let strLen; - let start; - let end; - let lastEnd; - let code; - let kind; - function parseObj() { - const nodeStart = start; - const members = []; - expect("{"); - if (!skip("}")) { - do { - members.push(parseMember()); - } while (skip(",")); - expect("}"); + } + function joinClasses(a, b) { + var as = a.split(" "); + for (var i2 = 0; i2 < as.length; i2++) { + if (as[i2] && !classTest(as[i2]).test(b)) { + b += " " + as[i2]; + } } - return { - kind: "Object", - start: nodeStart, - end: lastEnd, - members, - }; + return b; } - function parseMember() { - const nodeStart = start; - const key = kind === "String" ? curToken() : null; - expect("String"); - expect(":"); - const value = parseVal(); - return { - kind: "Member", - start: nodeStart, - end: lastEnd, - key, - value, + var selectInput = function (node) { + node.select(); + }; + if (ios) { + selectInput = function (node) { + node.selectionStart = 0; + node.selectionEnd = node.value.length; }; - } - function parseArr() { - const nodeStart = start; - const values = []; - expect("["); - if (!skip("]")) { - do { - values.push(parseVal()); - } while (skip(",")); - expect("]"); - } - return { - kind: "Array", - start: nodeStart, - end: lastEnd, - values, + } else if (ie) { + selectInput = function (node) { + try { + node.select(); + } catch (_e) {} }; } - function parseVal() { - switch (kind) { - case "[": - return parseArr(); - case "{": - return parseObj(); - case "String": - case "Number": - case "Boolean": - case "Null": - const token = curToken(); - lex(); - return token; - } - expect("Value"); - } - function curToken() { - return { - kind, - start, - end, - value: JSON.parse(string.slice(start, end)), + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return f.apply(null, args); }; } - function expect(str) { - if (kind === str) { - lex(); - return; + function copyObj(obj, target, overwrite) { + if (!target) { + target = {}; } - let found; - if (kind === "EOF") { - found = "[end of file]"; - } else if (end - start > 1) { - found = "`" + string.slice(start, end) + "`"; - } else { - const match = string.slice(start).match(/^.+?\b/); - found = "`" + (match ? match[0] : string[start]) + "`"; + for (var prop2 in obj) { + if (obj.hasOwnProperty(prop2) && (overwrite !== false || !target.hasOwnProperty(prop2))) { + target[prop2] = obj[prop2]; + } } - throw syntaxError(`Expected ${str} but found ${found}.`); + return target; } - class JSONSyntaxError extends Error { - constructor(message, position) { - super(message); - this.position = position; + function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) { + end = string.length; + } } - } - function syntaxError(message) { - return new JSONSyntaxError(message, { - start, - end, - }); - } - function skip(k) { - if (kind === k) { - lex(); - return true; + for (var i2 = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf(" ", i2); + if (nextTab < 0 || nextTab >= end) { + return n + (end - i2); + } + n += nextTab - i2; + n += tabSize - n % tabSize; + i2 = nextTab + 1; } } - function ch() { - if (end < strLen) { - end++; - code = end === strLen ? 0 : string.charCodeAt(end); + var Delayed = function () { + this.id = null; + this.f = null; + this.time = 0; + this.handler = bind(this.onTimeout, this); + }; + Delayed.prototype.onTimeout = function (self2) { + self2.id = 0; + if (self2.time <= + /* @__PURE__ */new Date()) { + self2.f(); + } else { + setTimeout(self2.handler, self2.time - + /* @__PURE__ */new Date()); } - return code; - } - function lex() { - lastEnd = end; - while (code === 9 || code === 10 || code === 13 || code === 32) { - ch(); + }; + Delayed.prototype.set = function (ms, f) { + this.f = f; + var time = + /* @__PURE__ */new Date() + ms; + if (!this.id || time < this.time) { + clearTimeout(this.id); + this.id = setTimeout(this.handler, ms); + this.time = time; } - if (code === 0) { - kind = "EOF"; - return; + }; + function indexOf(array, elt2) { + for (var i2 = 0; i2 < array.length; ++i2) { + if (array[i2] == elt2) { + return i2; + } } - start = end; - switch (code) { - case 34: - kind = "String"; - return readString(); - case 45: - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - kind = "Number"; - return readNumber(); - case 102: - if (string.slice(start, start + 5) !== "false") { - break; - } - end += 4; - ch(); - kind = "Boolean"; - return; - case 110: - if (string.slice(start, start + 4) !== "null") { - break; - } - end += 3; - ch(); - kind = "Null"; - return; - case 116: - if (string.slice(start, start + 4) !== "true") { - break; - } - end += 3; - ch(); - kind = "Boolean"; - return; + return -1; + } + var scrollerGap = 50; + var Pass = { + toString: function () { + return "CodeMirror.Pass"; } - kind = string[start]; - ch(); - } - function readString() { - ch(); - while (code !== 34 && code > 31) { - if (code === 92) { - code = ch(); - switch (code) { - case 34: - case 47: - case 92: - case 98: - case 102: - case 110: - case 114: - case 116: - ch(); - break; - case 117: - ch(); - readHex(); - readHex(); - readHex(); - readHex(); - break; - default: - throw syntaxError("Bad character escape sequence."); - } - } else if (end === strLen) { - throw syntaxError("Unterminated string."); - } else { - ch(); + }; + var sel_dontScroll = { + scroll: false + }, + sel_mouse = { + origin: "*mouse" + }, + sel_move = { + origin: "+move" + }; + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf(" ", pos); + if (nextTab == -1) { + nextTab = string.length; + } + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) { + return pos + Math.min(skipped, goal - col); + } + col += nextTab - pos; + col += tabSize - col % tabSize; + pos = nextTab + 1; + if (col >= goal) { + return pos; } } - if (code === 34) { - ch(); - return; + } + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) { + spaceStrs.push(lst(spaceStrs) + " "); } - throw syntaxError("Unterminated string."); + return spaceStrs[n]; } - function readHex() { - if ( - (code >= 48 && code <= 57) || - (code >= 65 && code <= 70) || - (code >= 97 && code <= 102) - ) { - return ch(); + function lst(arr) { + return arr[arr.length - 1]; + } + function map(array, f) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = f(array[i2], i2); } - throw syntaxError("Expected hexadecimal digit."); + return out; } - function readNumber() { - if (code === 45) { - ch(); + function insertSorted(array, value, score) { + var pos = 0, + priority = score(value); + while (pos < array.length && score(array[pos]) <= priority) { + pos++; } - if (code === 48) { - ch(); + array.splice(pos, 0, value); + } + function nothing() {} + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); } else { - readDigits(); + nothing.prototype = base; + inst = new nothing(); } - if (code === 46) { - ch(); - readDigits(); + if (props) { + copyObj(props, inst); + } + return inst; + } + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "€" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + function isWordChar(ch, helper) { + if (!helper) { + return isWordCharBasic(ch); + } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { + return true; } - if (code === 69 || code === 101) { - code = ch(); - if (code === 43 || code === 45) { - ch(); + return helper.test(ch); + } + function isEmpty(obj) { + for (var n in obj) { + if (obj.hasOwnProperty(n) && obj[n]) { + return false; } - readDigits(); } + return true; } - function readDigits() { - if (code < 48 || code > 57) { - throw syntaxError("Expected decimal digit."); + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { + return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); + } + function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { + pos += dir; } - do { - ch(); - } while (code >= 48 && code <= 57); + return pos; } - codemirror.CodeMirror.registerHelper( - "lint", - "graphql-variables", - (text, options, editor) => { - if (!text) { - return []; - } - let ast; - try { - ast = jsonParse(text); - } catch (error) { - if (error instanceof JSONSyntaxError) { - return [lintError(editor, error.position, error.message)]; - } - throw error; + function findFirst(pred, from, to) { + var dir = from > to ? -1 : 1; + for (;;) { + if (from == to) { + return from; } - const { variableToType } = options; - if (!variableToType) { - return []; + var midF = (from + to) / 2, + mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); + if (mid == from) { + return pred(mid) ? from : to; } - return validateVariables(editor, variableToType, ast); - } - ); - function validateVariables(editor, variableToType, variablesAST) { - var _a; - const errors = []; - for (const member of variablesAST.members) { - if (member) { - const variableName = - (_a = member.key) === null || _a === void 0 ? void 0 : _a.value; - const type = variableToType[variableName]; - if (type) { - for (const [node, message] of validateValue( - type, - member.value - )) { - errors.push(lintError(editor, node, message)); - } - } else { - errors.push( - lintError( - editor, - member.key, - `Variable "$${variableName}" does not appear in any GraphQL query.` - ) - ); - } + if (pred(mid)) { + to = mid; + } else { + from = mid + dir; } } - return errors; } - function validateValue(type, valueAST) { - if (!type || !valueAST) { - return []; + function iterateBidiSections(order, from, to, f) { + if (!order) { + return f(from, to, "ltr", 0); } - if (type instanceof graphql.GraphQLNonNull) { - if (valueAST.kind === "Null") { - return [ - [ - valueAST, - `Type "${type}" is non-nullable and cannot be null.`, - ], - ]; + var found = false; + for (var i2 = 0; i2 < order.length; ++i2) { + var part = order[i2]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2); + found = true; } - return validateValue(type.ofType, valueAST); } - if (valueAST.kind === "Null") { - return []; - } - if (type instanceof graphql.GraphQLList) { - const itemType = type.ofType; - if (valueAST.kind === "Array") { - const values = valueAST.values || []; - return mapCat(values, (item) => validateValue(itemType, item)); - } - return validateValue(itemType, valueAST); + if (!found) { + f(from, to, "ltr"); } - if (type instanceof graphql.GraphQLInputObjectType) { - if (valueAST.kind !== "Object") { - return [[valueAST, `Type "${type}" must be an Object.`]]; + } + var bidiOther = null; + function getBidiPartAt(order, ch, sticky) { + var found; + bidiOther = null; + for (var i2 = 0; i2 < order.length; ++i2) { + var cur = order[i2]; + if (cur.from < ch && cur.to > ch) { + return i2; } - const providedFields = /* @__PURE__ */ Object.create(null); - const fieldErrors = mapCat(valueAST.members, (member) => { - var _a; - const fieldName = - (_a = - member === null || member === void 0 - ? void 0 - : member.key) === null || _a === void 0 - ? void 0 - : _a.value; - providedFields[fieldName] = true; - const inputField = type.getFields()[fieldName]; - if (!inputField) { - return [ - [ - member.key, - `Type "${type}" does not have a field "${fieldName}".`, - ], - ]; - } - const fieldType = inputField ? inputField.type : void 0; - return validateValue(fieldType, member.value); - }); - for (const fieldName of Object.keys(type.getFields())) { - const field = type.getFields()[fieldName]; - if ( - !providedFields[fieldName] && - field.type instanceof graphql.GraphQLNonNull && - !field.defaultValue - ) { - fieldErrors.push([ - valueAST, - `Object of type "${type}" is missing required field "${fieldName}".`, - ]); + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { + found = i2; + } else { + bidiOther = i2; } } - return fieldErrors; - } - if ( - (type.name === "Boolean" && valueAST.kind !== "Boolean") || - (type.name === "String" && valueAST.kind !== "String") || - (type.name === "ID" && - valueAST.kind !== "Number" && - valueAST.kind !== "String") || - (type.name === "Float" && valueAST.kind !== "Number") || - (type.name === "Int" && - (valueAST.kind !== "Number" || - (valueAST.value | 0) !== valueAST.value)) - ) { - return [[valueAST, `Expected value of type "${type}".`]]; - } - if ( - (type instanceof graphql.GraphQLEnumType || - type instanceof graphql.GraphQLScalarType) && - ((valueAST.kind !== "String" && - valueAST.kind !== "Number" && - valueAST.kind !== "Boolean" && - valueAST.kind !== "Null") || - isNullish(type.parseValue(valueAST.value))) - ) { - return [[valueAST, `Expected value of type "${type}".`]]; - } - return []; - } - function lintError(editor, node, message) { - return { - message, - severity: "error", - type: "validation", - from: editor.posFromIndex(node.start), - to: editor.posFromIndex(node.end), - }; - } - function isNullish(value) { - return value === null || value === void 0 || value !== value; - } - function mapCat(array, mapper) { - return Array.prototype.concat.apply([], array.map(mapper)); - } - - /***/ - }, - - /***/ "../../graphiql-react/dist/matchbrackets.cjs.js": - /*!******************************************************!*\ - !*** ../../graphiql-react/dist/matchbrackets.cjs.js ***! - \******************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - const matchbrackets$2 = __webpack_require__( - /*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } - } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { + found = i2; + } else { + bidiOther = i2; + } + } + } + return found != null ? found : bidiOther; + } + var bidiOrdering = /* @__PURE__ */function () { + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; + function charType(code) { + if (code <= 247) { + return lowTypes.charAt(code); + } else if (1424 <= code && code <= 1524) { + return "R"; + } else if (1536 <= code && code <= 1785) { + return arabicTypes.charAt(code - 1536); + } else if (1774 <= code && code <= 2220) { + return "r"; + } else if (8192 <= code && code <= 8203) { + return "w"; + } else if (code == 8204) { + return "b"; + } else { + return "L"; + } + } + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, + isStrong = /[LRr]/, + countsAsLeft = /[Lb1n]/, + countsAsNum = /[1n]/; + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; + this.to = to; + } + return function (str, direction) { + var outerType = direction == "ltr" ? "L" : "R"; + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { + return false; } - } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); - } - var matchbracketsExports = matchbrackets$2.requireMatchbrackets(); - const matchbrackets = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs( - matchbracketsExports - ); - const matchbrackets$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: matchbrackets, - }, - [matchbracketsExports] - ); - exports.matchbrackets = matchbrackets$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/matchbrackets.cjs2.js": - /*!*******************************************************!*\ - !*** ../../graphiql-react/dist/matchbrackets.cjs2.js ***! - \*******************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - var matchbrackets = { - exports: {}, - }; - var hasRequiredMatchbrackets; - function requireMatchbrackets() { - if (hasRequiredMatchbrackets) return matchbrackets.exports; - hasRequiredMatchbrackets = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var ie_lt8 = - /MSIE \d/.test(navigator.userAgent) && - (document.documentMode == null || document.documentMode < 8); - var Pos = CodeMirror.Pos; - var matching = { - "(": ")>", - ")": "(<", - "[": "]>", - "]": "[<", - "{": "}>", - "}": "{<", - "<": ">>", - ">": "<<", - }; - function bracketRegex(config) { - return (config && config.bracketRegex) || /[(){}[\]]/; - } - function findMatchingBracket(cm, where, config) { - var line = cm.getLineHandle(where.line), - pos = where.ch - 1; - var afterCursor = config && config.afterCursor; - if (afterCursor == null) - afterCursor = /(^| )cm-fat-cursor($| )/.test( - cm.getWrapperElement().className - ); - var re = bracketRegex(config); - var match = - (!afterCursor && - pos >= 0 && - re.test(line.text.charAt(pos)) && - matching[line.text.charAt(pos)]) || - (re.test(line.text.charAt(pos + 1)) && - matching[line.text.charAt(++pos)]); - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (config && config.strict && dir > 0 != (pos == where.ch)) - return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - var found = scanForBracket( - cm, - Pos(where.line, pos + (dir > 0 ? 1 : 0)), - dir, - style, - config - ); - if (found == null) return null; - return { - from: Pos(where.line, pos), - to: found && found.pos, - match: found && found.ch == match.charAt(0), - forward: dir > 0, - }; - } - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = (config && config.maxScanLineLength) || 1e4; - var maxScanLines = (config && config.maxScanLines) || 1e3; - var stack = []; - var re = bracketRegex(config); - var lineEnd = - dir > 0 - ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) - : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for ( - var lineNo = where.line; - lineNo != lineEnd; - lineNo += dir - ) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, - end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if ( - re.test(ch) && - (style === void 0 || - (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == - (style || "")) - ) { - var match = matching[ch]; - if (match && (match.charAt(1) == ">") == dir > 0) - stack.push(ch); - else if (!stack.length) - return { - pos: Pos(lineNo, pos), - ch, - }; - else stack.pop(); + var len = str.length, + types = []; + for (var i2 = 0; i2 < len; ++i2) { + types.push(charType(str.charCodeAt(i2))); + } + for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) { + var type = types[i$12]; + if (type == "m") { + types[i$12] = prev; + } else { + prev = type; + } + } + for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) { + var type$1 = types[i$22]; + if (type$1 == "1" && cur == "r") { + types[i$22] = "n"; + } else if (isStrong.test(type$1)) { + cur = type$1; + if (type$1 == "r") { + types[i$22] = "R"; + } + } + } + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3]; + if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { + types[i$3] = "1"; + } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) { + types[i$3] = prev$1; + } + prev$1 = type$2; + } + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4]; + if (type$3 == ",") { + types[i$4] = "N"; + } else if (type$3 == "%") { + var end = void 0; + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N"; + for (var j = i$4; j < end; ++j) { + types[j] = replace; + } + i$4 = end - 1; + } + } + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5]; + if (cur$1 == "L" && type$4 == "1") { + types[i$5] = "L"; + } else if (isStrong.test(type$4)) { + cur$1 = type$4; + } + } + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = void 0; + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; + var after = (end$1 < len ? types[end$1] : outerType) == "L"; + var replace$1 = before == after ? before ? "L" : "R" : outerType; + for (var j$1 = i$6; j$1 < end$1; ++j$1) { + types[j$1] = replace$1; + } + i$6 = end$1 - 1; + } + } + var order = [], + m; + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7; + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)); + } else { + var pos = i$7, + at = order.length, + isRTL = direction == "rtl" ? 1 : 0; + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { + order.splice(at, 0, new BidiSpan(1, pos, j$2)); + at += isRTL; } + var nstart = j$2; + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)); + at += isRTL; + pos = j$2; + } else { + ++j$2; } } - return lineNo - dir == - (dir > 0 ? cm.lastLine() : cm.firstLine()) - ? false - : null; - } - function matchBrackets(cm, autoclear, config) { - var maxHighlightLen = - cm.state.matchBrackets.maxHighlightLineLength || 1e3, - highlightNonMatching = config && config.highlightNonMatching; - var marks = [], - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = - ranges[i].empty() && - findMatchingBracket(cm, ranges[i].head, config); - if ( - match && - (match.match || highlightNonMatching !== false) && - cm.getLine(match.from.line).length <= maxHighlightLen - ) { - var style = match.match - ? "CodeMirror-matchingbracket" - : "CodeMirror-nonmatchingbracket"; - marks.push( - cm.markText( - match.from, - Pos(match.from.line, match.from.ch + 1), - { - className: style, - } - ) - ); - if ( - match.to && - cm.getLine(match.to.line).length <= maxHighlightLen - ) - marks.push( - cm.markText( - match.to, - Pos(match.to.line, match.to.ch + 1), - { - className: style, - } - ) - ); - } - } - if (marks.length) { - if (ie_lt8 && cm.state.focused) cm.focus(); - var clear = function () { - cm.operation(function () { - for (var i2 = 0; i2 < marks.length; i2++) - marks[i2].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800); - else return clear; + if (pos < i$7) { + order.splice(at, 0, new BidiSpan(1, pos, i$7)); } } - function doMatchBrackets(cm) { - cm.operation(function () { - if (cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - cm.state.matchBrackets.currentlyHighlighted = matchBrackets( - cm, - false, - cm.state.matchBrackets - ); - }); + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); } - function clearHighlighted(cm) { - if ( - cm.state.matchBrackets && - cm.state.matchBrackets.currentlyHighlighted - ) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); } - CodeMirror.defineOption( - "matchBrackets", - false, - function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.off("cursorActivity", doMatchBrackets); - cm.off("focus", doMatchBrackets); - cm.off("blur", clearHighlighted); - clearHighlighted(cm); - } - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - cm.on("focus", doMatchBrackets); - cm.on("blur", clearHighlighted); - } - } - ); - CodeMirror.defineExtension("matchBrackets", function () { - matchBrackets(this, true); - }); - CodeMirror.defineExtension( - "findMatchingBracket", - function (pos, config, oldConfig) { - if (oldConfig || typeof config == "boolean") { - if (!oldConfig) { - config = config - ? { - strict: true, - } - : null; - } else { - oldConfig.strict = config; - config = oldConfig; - } - } - return findMatchingBracket(this, pos, config); - } - ); - CodeMirror.defineExtension( - "scanForBracket", - function (pos, dir, style, config) { - return scanForBracket(this, pos, dir, style, config); - } - ); - }); - })(); - return matchbrackets.exports; - } - exports.requireMatchbrackets = requireMatchbrackets; - - /***/ - }, - - /***/ "../../graphiql-react/dist/mode-indent.cjs.js": - /*!****************************************************!*\ - !*** ../../graphiql-react/dist/mode-indent.cjs.js ***! - \****************************************************/ - /***/ function (__unused_webpack_module, exports) { - function indent(state, textAfter) { - var _a, _b; - const { levels, indentLevel } = state; - const level = - !levels || levels.length === 0 - ? indentLevel - : levels.at(-1) - - (( - (_a = this.electricInput) === null || _a === void 0 - ? void 0 - : _a.test(textAfter) - ) - ? 1 - : 0); - return ( - (level || 0) * - (((_b = this.config) === null || _b === void 0 - ? void 0 - : _b.indentUnit) || 0) - ); - } - exports.indent = indent; - - /***/ - }, - - /***/ "../../graphiql-react/dist/mode.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs.js ***! - \*********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const graphqlLanguageService = __webpack_require__( - /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" - ); - const modeIndent = __webpack_require__( - /*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js" - ); - const graphqlModeFactory = (config) => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: (stream) => - stream.eatWhile(graphqlLanguageService.isIgnored), - lexRules: graphqlLanguageService.LexRules, - parseRules: graphqlLanguageService.ParseRules, - editorConfig: { - tabSize: config.tabSize, - }, - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[})\]]/, - fold: "brace", - lineComment: "#", - closeBrackets: { - pairs: '()[]{}""', - explode: "()[]{}", - }, - }; - }; - codemirror.CodeMirror.defineMode("graphql", graphqlModeFactory); - - /***/ - }, - - /***/ "../../graphiql-react/dist/mode.cjs2.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs2.js ***! - \**********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const graphqlLanguageService = __webpack_require__( - /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" - ); - const modeIndent = __webpack_require__( - /*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js" - ); - codemirror.CodeMirror.defineMode("graphql-variables", (config) => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: (stream) => stream.eatSpace(), - lexRules: LexRules, - parseRules: ParseRules, - editorConfig: { - tabSize: config.tabSize, - }, - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[}\]]/, - fold: "brace", - closeBrackets: { - pairs: '[]{}""', - explode: "[]{}", - }, - }; - }); - const LexRules = { - Punctuation: /^\[|]|\{|\}|:|,/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, - Keyword: /^true|false|null/, - }; - const ParseRules = { - Document: [ - graphqlLanguageService.p("{"), - graphqlLanguageService.list( - "Variable", - graphqlLanguageService.opt(graphqlLanguageService.p(",")) - ), - graphqlLanguageService.p("}"), - ], - Variable: [ - namedKey("variable"), - graphqlLanguageService.p(":"), - "Value", - ], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; - } - return null; - case "Keyword": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - case "null": - return "NullValue"; - } - return null; } - }, - NumberValue: [graphqlLanguageService.t("Number", "number")], - StringValue: [graphqlLanguageService.t("String", "string")], - BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], - NullValue: [graphqlLanguageService.t("Keyword", "keyword")], - ListValue: [ - graphqlLanguageService.p("["), - graphqlLanguageService.list( - "Value", - graphqlLanguageService.opt(graphqlLanguageService.p(",")) - ), - graphqlLanguageService.p("]"), - ], - ObjectValue: [ - graphqlLanguageService.p("{"), - graphqlLanguageService.list( - "ObjectField", - graphqlLanguageService.opt(graphqlLanguageService.p(",")) - ), - graphqlLanguageService.p("}"), - ], - ObjectField: [ - namedKey("attribute"), - graphqlLanguageService.p(":"), - "Value", - ], - }; - function namedKey(style) { - return { - style, - match: (token) => token.kind === "String", - update(state, token) { - state.name = token.value.slice(1, -1); - }, + return direction == "rtl" ? order.reverse() : order; }; + }(); + function getOrder(line, direction) { + var order = line.order; + if (order == null) { + order = line.order = bidiOrdering(line.text, direction); + } + return order; } - - /***/ - }, - - /***/ "../../graphiql-react/dist/mode.cjs3.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs3.js ***! - \**********************************************/ - /***/ function ( - __unused_webpack_module, - __unused_webpack_exports, - __webpack_require__ - ) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js" - ); - const graphqlLanguageService = __webpack_require__( - /*! graphql-language-service */ "../../graphql-language-service/esm/index.js" - ); - const modeIndent = __webpack_require__( - /*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js" - ); - codemirror.CodeMirror.defineMode("graphql-results", (config) => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: (stream) => stream.eatSpace(), - lexRules: LexRules, - parseRules: ParseRules, - editorConfig: { - tabSize: config.tabSize, - }, - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[}\]]/, - fold: "brace", - closeBrackets: { - pairs: '[]{}""', - explode: "[]{}", - }, - }; - }); - const LexRules = { - Punctuation: /^\[|]|\{|\}|:|,/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, - Keyword: /^true|false|null/, + var noHandlers = []; + var on = function (emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false); + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f); + } else { + var map2 = emitter._handlers || (emitter._handlers = {}); + map2[type] = (map2[type] || noHandlers).concat(f); + } }; - const ParseRules = { - Document: [ - graphqlLanguageService.p("{"), - graphqlLanguageService.list("Entry", graphqlLanguageService.p(",")), - graphqlLanguageService.p("}"), - ], - Entry: [ - graphqlLanguageService.t("String", "def"), - graphqlLanguageService.p(":"), - "Value", - ], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; - } - return null; - case "Keyword": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - case "null": - return "NullValue"; - } - return null; + function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers; + } + function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false); + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f); + } else { + var map2 = emitter._handlers, + arr = map2 && map2[type]; + if (arr) { + var index = indexOf(arr, f); + if (index > -1) { + map2[type] = arr.slice(0, index).concat(arr.slice(index + 1)); + } } - }, - NumberValue: [graphqlLanguageService.t("Number", "number")], - StringValue: [graphqlLanguageService.t("String", "string")], - BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], - NullValue: [graphqlLanguageService.t("Keyword", "keyword")], - ListValue: [ - graphqlLanguageService.p("["), - graphqlLanguageService.list("Value", graphqlLanguageService.p(",")), - graphqlLanguageService.p("]"), - ], - ObjectValue: [ - graphqlLanguageService.p("{"), - graphqlLanguageService.list( - "ObjectField", - graphqlLanguageService.p(",") - ), - graphqlLanguageService.p("}"), - ], - ObjectField: [ - graphqlLanguageService.t("String", "property"), - graphqlLanguageService.p(":"), - "Value", - ], - }; - - /***/ - }, - - /***/ "../../graphiql-react/dist/search.cjs.js": - /*!***********************************************!*\ - !*** ../../graphiql-react/dist/search.cjs.js ***! - \***********************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - const searchcursor = __webpack_require__( - /*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js" - ); - const dialog = __webpack_require__( - /*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } + } + } + function signal(emitter, type) { + var handlers = getHandlers(emitter, type); + if (!handlers.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2); + for (var i2 = 0; i2 < handlers.length; ++i2) { + handlers[i2].apply(null, args); + } + } + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") { + e = { + type: e, + preventDefault: function () { + this.defaultPrevented = true; } + }; + } + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) { + return; + } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i2 = 0; i2 < arr.length; ++i2) { + if (indexOf(set, arr[i2]) == -1) { + set.push(arr[i2]); + } + } + } + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0; + } + function eventMixin(ctor) { + ctor.prototype.on = function (type, f) { + on(this, type, f); + }; + ctor.prototype.off = function (type, f) { + off(this, type, f); + }; + } + function e_preventDefault(e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + } + function e_stopPropagation(e) { + if (e.stopPropagation) { + e.stopPropagation(); + } else { + e.cancelBubble = true; + } + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + function e_stop(e) { + e_preventDefault(e); + e_stopPropagation(e); + } + function e_target(e) { + return e.target || e.srcElement; + } + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) { + b = 1; + } else if (e.button & 2) { + b = 3; + } else if (e.button & 4) { + b = 2; } } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); + if (mac && e.ctrlKey && b == 1) { + b = 3; + } + return b; } - var search$2 = { - exports: {}, + var dragAndDrop = function () { + if (ie && ie_version < 9) { + return false; + } + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + }(); + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "​"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) { + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); + } + } + var node = zwspSupported ? elt("span", "​") : elt("span", " ", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) { + return badBidiRects; + } + var txt = removeChildrenAndAdd(measure, document.createTextNode("AخA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + var r1 = range(txt, 1, 2).getBoundingClientRect(); + removeChildren(measure); + if (!r0 || r0.left == r0.right) { + return false; + } + return badBidiRects = r1.right - r0.right < 3; + } + var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, + result = [], + l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) { + nl = string.length; + } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function (string) { + return string.split(/\r\n?|\n/); }; - (function (module2, exports2) { - (function (mod) { - mod( - codemirror.requireCodemirror(), - searchcursor.requireSearchcursor(), - dialog.dialogExports - ); - })(function (CodeMirror) { - CodeMirror.defineOption("search", { - bottom: false, - }); - function searchOverlay(query, caseInsensitive) { - if (typeof query == "string") - query = new RegExp( - query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), - caseInsensitive ? "gi" : "g" - ); - else if (!query.global) - query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); - return { - token: function (stream) { - query.lastIndex = stream.pos; - var match = query.exec(stream.string); - if (match && match.index == stream.pos) { - stream.pos += match[0].length || 1; - return "searching"; - } else if (match) { - stream.pos = match.index; - } else { - stream.skipToEnd(); - } - }, + var hasSelection = window.getSelection ? function (te) { + try { + return te.selectionStart != te.selectionEnd; + } catch (e) { + return false; + } + } : function (te) { + var range2; + try { + range2 = te.ownerDocument.selection.createRange(); + } catch (e) {} + if (!range2 || range2.parentElement() != te) { + return false; + } + return range2.compareEndPoints("StartToEnd", range2) != 0; + }; + var hasCopyEvent = function () { + var e = elt("div"); + if ("oncopy" in e) { + return true; + } + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + }(); + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { + return badZoomedRects; + } + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + var modes = {}, + mimeModes = {}; + function defineMode(name, mode) { + if (arguments.length > 2) { + mode.dependencies = Array.prototype.slice.call(arguments, 2); + } + modes[name] = mode; + } + function defineMIME(mime, spec) { + mimeModes[mime] = spec; + } + function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") { + found = { + name: found }; } - function SearchState() { - this.posFrom = this.posTo = this.lastQuery = this.query = null; - this.overlay = null; - } - function getSearchState(cm) { - return cm.state.search || (cm.state.search = new SearchState()); - } - function queryCaseInsensitive(query) { - return typeof query == "string" && query == query.toLowerCase(); - } - function getSearchCursor(cm, query, pos) { - return cm.getSearchCursor(query, pos, { - caseFold: queryCaseInsensitive(query), - multiline: true, - }); + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml"); + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json"); + } + if (typeof spec == "string") { + return { + name: spec + }; + } else { + return spec || { + name: "null" + }; + } + } + function getMode(options, spec) { + spec = resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) { + return getMode(options, "text/plain"); + } + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop2 in exts) { + if (!exts.hasOwnProperty(prop2)) { + continue; + } + if (modeObj.hasOwnProperty(prop2)) { + modeObj["_" + prop2] = modeObj[prop2]; + } + modeObj[prop2] = exts[prop2]; } - function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { - cm.openDialog(text, onEnter, { - value: deflt, - selectValueOnOpen: true, - closeOnEnter: false, - onClose: function () { - clearSearch(cm); - }, - onKeyDown, - bottom: cm.options.search.bottom, - }); + } + modeObj.name = spec.name; + if (spec.helperType) { + modeObj.helperType = spec.helperType; + } + if (spec.modeProps) { + for (var prop$1 in spec.modeProps) { + modeObj[prop$1] = spec.modeProps[prop$1]; } - function dialog2(cm, text, shortText, deflt, f) { - if (cm.openDialog) - cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom, - }); - else f(prompt(shortText, deflt)); - } - function confirmDialog(cm, text, shortText, fs) { - if (cm.openConfirm) cm.openConfirm(text, fs); - else if (confirm(shortText)) fs[0](); - } - function parseString(string) { - return string.replace(/\\([nrt\\])/g, function (match, ch) { - if (ch == "n") return "\n"; - if (ch == "r") return "\r"; - if (ch == "t") return " "; - if (ch == "\\") return "\\"; - return match; - }); + } + return modeObj; + } + var modeExtensions = {}; + function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {}; + copyObj(properties, exts); + } + function copyState(mode, state) { + if (state === true) { + return state; + } + if (mode.copyState) { + return mode.copyState(state); + } + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) { + val = val.concat([]); } - function parseQuery(query) { - var isRE = query.match(/^\/(.*)\/([a-z]*)$/); - if (isRE) { - try { - query = new RegExp( - isRE[1], - isRE[2].indexOf("i") == -1 ? "" : "i" - ); - } catch (e) {} - } else { - query = parseString(query); - } - if (typeof query == "string" ? query == "" : query.test("")) - query = /x^/; - return query; - } - function startSearch(cm, state, query) { - state.queryText = query; - state.query = parseQuery(query); - cm.removeOverlay( - state.overlay, - queryCaseInsensitive(state.query) - ); - state.overlay = searchOverlay( - state.query, - queryCaseInsensitive(state.query) - ); - cm.addOverlay(state.overlay); - if (cm.showMatchesOnScrollbar) { - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; - } - state.annotate = cm.showMatchesOnScrollbar( - state.query, - queryCaseInsensitive(state.query) - ); - } + nstate[n] = val; + } + return nstate; + } + function innerMode(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) { + break; } - function doSearch(cm, rev, persistent, immediate) { - var state = getSearchState(cm); - if (state.query) return findNext(cm, rev); - var q = cm.getSelection() || state.lastQuery; - if (q instanceof RegExp && q.source == "x^") q = null; - if (persistent && cm.openDialog) { - var hiding = null; - var searchNext = function (query, event) { - CodeMirror.e_stop(event); - if (!query) return; - if (query != state.queryText) { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - } - if (hiding) hiding.style.opacity = 1; - findNext(cm, event.shiftKey, function (_, to) { - var dialog3; - if ( - to.line < 3 && - document.querySelector && - (dialog3 = - cm.display.wrapper.querySelector( - ".CodeMirror-dialog" - )) && - dialog3.getBoundingClientRect().bottom - 4 > - cm.cursorCoords(to, "window").top - ) - (hiding = dialog3).style.opacity = 0.4; - }); - }; - persistentDialog( - cm, - getQueryDialog(cm), - q, - searchNext, - function (event, query) { - var keyName = CodeMirror.keyName(event); - var extra = cm.getOption("extraKeys"), - cmd = - (extra && extra[keyName]) || - CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; - if ( - cmd == "findNext" || - cmd == "findPrev" || - cmd == "findPersistentNext" || - cmd == "findPersistentPrev" - ) { - CodeMirror.e_stop(event); - startSearch(cm, getSearchState(cm), query); - cm.execCommand(cmd); - } else if (cmd == "find" || cmd == "findPersistent") { - CodeMirror.e_stop(event); - searchNext(query, event); - } - } - ); - if (immediate && q) { - startSearch(cm, state, q); - findNext(cm, rev); - } - } else { - dialog2( - cm, - getQueryDialog(cm), - "Search for:", - q, - function (query) { - if (query && !state.query) - cm.operation(function () { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - findNext(cm, rev); - }); - } - ); + state = info.state; + mode = info.mode; + } + return info || { + mode, + state + }; + } + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + var StringStream = function (string, tabSize, lineOracle) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.lineOracle = lineOracle; + }; + StringStream.prototype.eol = function () { + return this.pos >= this.string.length; + }; + StringStream.prototype.sol = function () { + return this.pos == this.lineStart; + }; + StringStream.prototype.peek = function () { + return this.string.charAt(this.pos) || void 0; + }; + StringStream.prototype.next = function () { + if (this.pos < this.string.length) { + return this.string.charAt(this.pos++); + } + }; + StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos); + var ok; + if (typeof match == "string") { + ok = ch == match; + } else { + ok = ch && (match.test ? match.test(ch) : match(ch)); + } + if (ok) { + ++this.pos; + return ch; + } + }; + StringStream.prototype.eatWhile = function (match) { + var start = this.pos; + while (this.eat(match)) {} + return this.pos > start; + }; + StringStream.prototype.eatSpace = function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { + ++this.pos; + } + return this.pos > start; + }; + StringStream.prototype.skipToEnd = function () { + this.pos = this.string.length; + }; + StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) { + this.pos = found; + return true; + } + }; + StringStream.prototype.backUp = function (n) { + this.pos -= n; + }; + StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }; + StringStream.prototype.indentation = function () { + return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }; + StringStream.prototype.match = function (pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { + return caseInsensitive ? str.toLowerCase() : str; + }; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) { + this.pos += pattern.length; } + return true; } - function findNext(cm, rev, callback) { - cm.operation(function () { - var state = getSearchState(cm); - var cursor = getSearchCursor( - cm, - state.query, - rev ? state.posFrom : state.posTo - ); - if (!cursor.find(rev)) { - cursor = getSearchCursor( - cm, - state.query, - rev - ? CodeMirror.Pos(cm.lastLine()) - : CodeMirror.Pos(cm.firstLine(), 0) - ); - if (!cursor.find(rev)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView( - { - from: cursor.from(), - to: cursor.to(), - }, - 20 - ); - state.posFrom = cursor.from(); - state.posTo = cursor.to(); - if (callback) callback(cursor.from(), cursor.to()); - }); + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) { + return null; } - function clearSearch(cm) { - cm.operation(function () { - var state = getSearchState(cm); - state.lastQuery = state.query; - if (!state.query) return; - state.query = state.queryText = null; - cm.removeOverlay(state.overlay); - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; - } - }); + if (match && consume !== false) { + this.pos += match[0].length; } - function el(tag, attrs) { - var element = tag - ? document.createElement(tag) - : document.createDocumentFragment(); - for (var key in attrs) { - element[key] = attrs[key]; - } - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - element.appendChild( - typeof child == "string" - ? document.createTextNode(child) - : child - ); + return match; + } + }; + StringStream.prototype.current = function () { + return this.string.slice(this.start, this.pos); + }; + StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n; + try { + return inner(); + } finally { + this.lineStart -= n; + } + }; + StringStream.prototype.lookAhead = function (n) { + var oracle = this.lineOracle; + return oracle && oracle.lookAhead(n); + }; + StringStream.prototype.baseToken = function () { + var oracle = this.lineOracle; + return oracle && oracle.baseToken(this.pos); + }; + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) { + throw new Error("There is no line " + (n + doc.first) + " in the document."); + } + var chunk = doc; + while (!chunk.lines) { + for (var i2 = 0;; ++i2) { + var child = chunk.children[i2], + sz = child.chunkSize(); + if (n < sz) { + chunk = child; + break; } - return element; - } - function getQueryDialog(cm) { - return el( - "", - null, - el( - "span", - { - className: "CodeMirror-search-label", - }, - cm.phrase("Search:") - ), - " ", - el("input", { - type: "text", - style: "width: 10em", - className: "CodeMirror-search-field", - }), - " ", - el( - "span", - { - style: "color: #888", - className: "CodeMirror-search-hint", - }, - cm.phrase("(Use /re/ syntax for regexp search)") - ) - ); + n -= sz; } - function getReplaceQueryDialog(cm) { - return el( - "", - null, - " ", - el("input", { - type: "text", - style: "width: 10em", - className: "CodeMirror-search-field", - }), - " ", - el( - "span", - { - style: "color: #888", - className: "CodeMirror-search-hint", - }, - cm.phrase("(Use /re/ syntax for regexp search)") - ) - ); + } + return chunk.lines[n]; + } + function getBetween(doc, start, end) { + var out = [], + n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) { + text = text.slice(0, end.ch); } - function getReplacementQueryDialog(cm) { - return el( - "", - null, - el( - "span", - { - className: "CodeMirror-search-label", - }, - cm.phrase("With:") - ), - " ", - el("input", { - type: "text", - style: "width: 10em", - className: "CodeMirror-search-field", - }) - ); + if (n == start.line) { + text = text.slice(start.ch); } - function getDoReplaceConfirm(cm) { - return el( - "", - null, - el( - "span", - { - className: "CodeMirror-search-label", - }, - cm.phrase("Replace?") - ), - " ", - el("button", {}, cm.phrase("Yes")), - " ", - el("button", {}, cm.phrase("No")), - " ", - el("button", {}, cm.phrase("All")), - " ", - el("button", {}, cm.phrase("Stop")) - ); + out.push(text); + ++n; + }); + return out; + } + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function (line) { + out.push(line.text); + }); + return out; + } + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) { + for (var n = line; n; n = n.parent) { + n.height += diff; } - function replaceAll(cm, query, text) { - cm.operation(function () { - for ( - var cursor = getSearchCursor(cm, query); - cursor.findNext(); - - ) { - if (typeof query != "string") { - var match = cm - .getRange(cursor.from(), cursor.to()) - .match(query); - cursor.replace( - text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - }) - ); - } else cursor.replace(text); - } - }); + } + } + function lineNo(line) { + if (line.parent == null) { + return null; + } + var cur = line.parent, + no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i2 = 0;; ++i2) { + if (chunk.children[i2] == cur) { + break; + } + no += chunk.children[i2].chunkSize(); } - function replace(cm, all) { - if (cm.getOption("readOnly")) return; - var query = cm.getSelection() || getSearchState(cm).lastQuery; - var dialogText = all - ? cm.phrase("Replace all:") - : cm.phrase("Replace:"); - var fragment = el( - "", - null, - el( - "span", - { - className: "CodeMirror-search-label", - }, - dialogText - ), - getReplaceQueryDialog(cm) - ); - dialog2(cm, fragment, dialogText, query, function (query2) { - if (!query2) return; - query2 = parseQuery(query2); - dialog2( - cm, - getReplacementQueryDialog(cm), - cm.phrase("Replace with:"), - "", - function (text) { - text = parseString(text); - if (all) { - replaceAll(cm, query2, text); - } else { - clearSearch(cm); - var cursor = getSearchCursor( - cm, - query2, - cm.getCursor("from") - ); - var advance = function () { - var start = cursor.from(), - match; - if (!(match = cursor.findNext())) { - cursor = getSearchCursor(cm, query2); - if ( - !(match = cursor.findNext()) || - (start && - cursor.from().line == start.line && - cursor.from().ch == start.ch) - ) - return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to(), - }); - confirmDialog( - cm, - getDoReplaceConfirm(cm), - cm.phrase("Replace?"), - [ - function () { - doReplace(match); - }, - advance, - function () { - replaceAll(cm, query2, text); - }, - ] - ); - }; - var doReplace = function (match) { - cursor.replace( - typeof query2 == "string" - ? text - : text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - }) - ); - advance(); - }; - advance(); - } - } - ); - }); + } + return no + cur.first; + } + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) { + var child = chunk.children[i$12], + ch = child.height; + if (h < ch) { + chunk = child; + continue outer; + } + h -= ch; + n += child.chunkSize(); } - CodeMirror.commands.find = function (cm) { - clearSearch(cm); - doSearch(cm); - }; - CodeMirror.commands.findPersistent = function (cm) { - clearSearch(cm); - doSearch(cm, false, true); - }; - CodeMirror.commands.findPersistentNext = function (cm) { - doSearch(cm, false, true, true); - }; - CodeMirror.commands.findPersistentPrev = function (cm) { - doSearch(cm, true, true, true); - }; - CodeMirror.commands.findNext = doSearch; - CodeMirror.commands.findPrev = function (cm) { - doSearch(cm, true); - }; - CodeMirror.commands.clearSearch = clearSearch; - CodeMirror.commands.replace = replace; - CodeMirror.commands.replaceAll = function (cm) { - replace(cm, true); - }; - }); - })(); - var searchExports = search$2.exports; - const search = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(searchExports); - const search$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: search, - }, - [searchExports] - ); - exports.search = search$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/searchcursor.cjs.js": - /*!*****************************************************!*\ - !*** ../../graphiql-react/dist/searchcursor.cjs.js ***! - \*****************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - const searchcursor$2 = __webpack_require__( - /*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } + return n; + } while (!chunk.lines); + var i2 = 0; + for (; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2], + lh = line.height; + if (h < lh) { + break; + } + h -= lh; + } + return n + i2; + } + function isLine(doc, l) { + return l >= doc.first && l < doc.first + doc.size; + } + function lineNumberFor(options, i2) { + return String(options.lineNumberFormatter(i2 + options.firstLineNumber)); + } + function Pos(line, ch, sticky) { + if (sticky === void 0) sticky = null; + if (!(this instanceof Pos)) { + return new Pos(line, ch, sticky); + } + this.line = line; + this.ch = ch; + this.sticky = sticky; + } + function cmp(a, b) { + return a.line - b.line || a.ch - b.ch; + } + function equalCursorPos(a, b) { + return a.sticky == b.sticky && cmp(a, b) == 0; + } + function copyPos(x) { + return Pos(x.line, x.ch); + } + function maxPos(a, b) { + return cmp(a, b) < 0 ? b : a; + } + function minPos(a, b) { + return cmp(a, b) < 0 ? a : b; + } + function clipLine(doc, n) { + return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)); + } + function clipPos(doc, pos) { + if (pos.line < doc.first) { + return Pos(doc.first, 0); + } + var last = doc.first + doc.size - 1; + if (pos.line > last) { + return Pos(last, getLine(doc, last).text.length); + } + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) { + return Pos(pos.line, linelen); + } else if (ch < 0) { + return Pos(pos.line, 0); + } else { + return pos; + } + } + function clipPosArray(doc, array) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = clipPos(doc, array[i2]); + } + return out; + } + var SavedContext = function (state, lookAhead) { + this.state = state; + this.lookAhead = lookAhead; + }; + var Context = function (doc, state, line, lookAhead) { + this.state = state; + this.doc = doc; + this.line = line; + this.maxLookAhead = lookAhead || 0; + this.baseTokens = null; + this.baseTokenPos = 1; + }; + Context.prototype.lookAhead = function (n) { + var line = this.doc.getLine(this.line + n); + if (line != null && n > this.maxLookAhead) { + this.maxLookAhead = n; + } + return line; + }; + Context.prototype.baseToken = function (n) { + if (!this.baseTokens) { + return null; + } + while (this.baseTokens[this.baseTokenPos] <= n) { + this.baseTokenPos += 2; + } + var type = this.baseTokens[this.baseTokenPos + 1]; + return { + type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n + }; + }; + Context.prototype.nextLine = function () { + this.line++; + if (this.maxLookAhead > 0) { + this.maxLookAhead--; + } + }; + Context.fromSaved = function (doc, saved, line) { + if (saved instanceof SavedContext) { + return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead); + } else { + return new Context(doc, copyState(doc.mode, saved), line); + } + }; + Context.prototype.save = function (copy) { + var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state; + }; + function highlightLine(cm, line, context, forceToEnd) { + var st = [cm.state.modeGen], + lineClasses = {}; + runMode(cm, line.text, cm.doc.mode, context, function (end, style) { + return st.push(end, style); + }, lineClasses, forceToEnd); + var state = context.state; + var loop = function (o2) { + context.baseTokens = st; + var overlay = cm.state.overlays[o2], + i2 = 1, + at = 0; + context.state = true; + runMode(cm, line.text, overlay.mode, context, function (end, style) { + var start = i2; + while (at < end) { + var i_end = st[i2]; + if (i_end > end) { + st.splice(i2, 1, end, st[i2 + 1], i_end); + } + i2 += 2; + at = Math.min(end, i_end); + } + if (!style) { + return; + } + if (overlay.opaque) { + st.splice(start, i2 - start, end, "overlay " + style); + i2 = start + 2; + } else { + for (; start < i2; start += 2) { + var cur = st[start + 1]; + st[start + 1] = (cur ? cur + " " : "") + "overlay " + style; } } + }, lineClasses); + context.state = state; + context.baseTokens = null; + context.baseTokenPos = 1; + }; + for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); + return { + styles: st, + classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null + }; + } + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)); + var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); + var result = highlightLine(cm, line, context); + if (resetState) { + context.state = resetState; + } + line.stateAfter = context.save(!resetState); + line.styles = result.styles; + if (result.classes) { + line.styleClasses = result.classes; + } else if (line.styleClasses) { + line.styleClasses = null; + } + if (updateFrontier === cm.doc.highlightFrontier) { + cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); + } + } + return line.styles; + } + function getContextBefore(cm, n, precise) { + var doc = cm.doc, + display = cm.display; + if (!doc.mode.startState) { + return new Context(doc, true, n); + } + var start = findStartLine(cm, n, precise); + var saved = start > doc.first && getLine(doc, start - 1).stateAfter; + var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); + doc.iter(start, n, function (line) { + processLine(cm, line.text, context); + var pos = context.line; + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; + context.nextLine(); + }); + if (precise) { + doc.modeFrontier = context.line; + } + return context; + } + function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize, context); + stream.start = stream.pos = startAt || 0; + if (text == "") { + callBlankLine(mode, context.state); + } + while (!stream.eol()) { + readToken(mode, stream, context.state); + stream.start = stream.pos; + } + } + function callBlankLine(mode, state) { + if (mode.blankLine) { + return mode.blankLine(state); + } + if (!mode.innerMode) { + return; + } + var inner = innerMode(mode, state); + if (inner.mode.blankLine) { + return inner.mode.blankLine(inner.state); + } + } + function readToken(mode, stream, state, inner) { + for (var i2 = 0; i2 < 10; i2++) { + if (inner) { + inner[0] = innerMode(mode, state).mode; + } + var style = mode.token(stream, state); + if (stream.pos > stream.start) { + return style; } } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); + throw new Error("Mode " + mode.name + " failed to advance stream."); } - var searchcursorExports = searchcursor$2.requireSearchcursor(); - const searchcursor = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs( - searchcursorExports - ); - const searchcursor$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: searchcursor, - }, - [searchcursorExports] - ); - exports.searchcursor = searchcursor$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/searchcursor.cjs2.js": - /*!******************************************************!*\ - !*** ../../graphiql-react/dist/searchcursor.cjs2.js ***! - \******************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - var searchcursor = { - exports: {}, + var Token = function (stream, type, state) { + this.start = stream.start; + this.end = stream.pos; + this.string = stream.current(); + this.type = type || null; + this.state = state; }; - var hasRequiredSearchcursor; - function requireSearchcursor() { - if (hasRequiredSearchcursor) return searchcursor.exports; - hasRequiredSearchcursor = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var Pos = CodeMirror.Pos; - function regexpFlags(regexp) { - var flags = regexp.flags; - return flags != null - ? flags - : (regexp.ignoreCase ? "i" : "") + - (regexp.global ? "g" : "") + - (regexp.multiline ? "m" : ""); + function takeToken(cm, pos, precise, asArray) { + var doc = cm.doc, + mode = doc.mode, + style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), + context = getContextBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize, context), + tokens; + if (asArray) { + tokens = []; + } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, context.state); + if (asArray) { + tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); + } + } + return asArray ? tokens : new Token(stream, style, context.state); + } + function extractLineClasses(type, output) { + if (type) { + for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) { + break; } - function ensureFlags(regexp, flags) { - var current = regexpFlags(regexp), - target = current; - for (var i = 0; i < flags.length; i++) - if (target.indexOf(flags.charAt(i)) == -1) - target += flags.charAt(i); - return current == target - ? regexp - : new RegExp(regexp.source, target); + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop2 = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop2] == null) { + output[prop2] = lineClass[2]; + } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop2])) { + output[prop2] += " " + lineClass[2]; } - function maybeMultiline(regexp) { - return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); + } + } + return type; + } + function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) { + flattenSpans = cm.options.flattenSpans; + } + var curStart = 0, + curStyle = null; + var stream = new StringStream(text, cm.options.tabSize, context), + style; + var inner = cm.options.addModeClass && [null]; + if (text == "") { + extractLineClasses(callBlankLine(mode, context.state), lineClasses); + } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) { + processLine(cm, text, context, stream.pos); + } + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) { + style = "m-" + (style ? mName + " " + style : mName); } - function searchRegexpForward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for ( - var line = start.line, ch = start.ch, last = doc.lastLine(); - line <= last; - line++, ch = 0 - ) { - regexp.lastIndex = ch; - var string = doc.getLine(line), - match = regexp.exec(string); - if (match) - return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match, - }; - } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5e3); + f(curStart, curStyle); } - function searchRegexpForwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) - return searchRegexpForward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunk = 1; - for ( - var line = start.line, last = doc.lastLine(); - line <= last; - - ) { - for (var i = 0; i < chunk; i++) { - if (line > last) break; - var curLine = doc.getLine(line++); - string = string == null ? curLine : string + "\n" + curLine; - } - chunk = chunk * 2; - regexp.lastIndex = start.ch; - var match = regexp.exec(string); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = start.line + before.length - 1, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos( - startLine + inside.length - 1, - inside.length == 1 - ? startCh + inside[0].length - : inside[inside.length - 1].length - ), - match, - }; - } - } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + var pos = Math.min(stream.pos, curStart + 5e3); + f(pos, curStyle); + curStart = pos; + } + } + function findStartLine(cm, n, precise) { + var minindent, + minline, + doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) { + return doc.first; + } + var line = getLine(doc, search - 1), + after = line.stateAfter; + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { + return search; + } + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n); + if (doc.highlightFrontier < n - 10) { + return; + } + var start = doc.first; + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc, line).stateAfter; + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1; + break; + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start); + } + var sawReadOnlySpans = false, + sawCollapsedSpans = false; + function seeReadOnlySpans() { + sawReadOnlySpans = true; + } + function seeCollapsedSpans() { + sawCollapsedSpans = true; + } + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; + this.to = to; + } + function getMarkedSpanFor(spans, marker) { + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.marker == marker) { + return span; } - function lastMatchIn(string, regexp, endMargin) { - var match, - from = 0; - while (from <= string.length) { - regexp.lastIndex = from; - var newMatch = regexp.exec(string); - if (!newMatch) break; - var end = newMatch.index + newMatch[0].length; - if (end > string.length - endMargin) break; - if (!match || end > match.index + match[0].length) - match = newMatch; - from = newMatch.index + 1; - } - return match; + } + } + } + function removeMarkedSpan(spans, span) { + var r; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2] != span) { + (r || (r = [])).push(spans[i2]); + } + } + return r; + } + function addMarkedSpan(line, span, op) { + var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = /* @__PURE__ */new WeakSet())); + if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { + line.markedSpans.push(span); + } else { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + if (inThisOp) { + inThisOp.add(line.markedSpans); + } + } + span.marker.attachLine(line); + } + function markedSpansBefore(old, startCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], + marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); } - function searchRegexpBackward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for ( - var line = start.line, ch = start.ch, first = doc.firstLine(); - line >= first; - line--, ch = -1 - ) { - var string = doc.getLine(line); - var match = lastMatchIn( - string, - regexp, - ch < 0 ? 0 : string.length - ch - ); - if (match) - return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match, - }; - } + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], + marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); } - function searchRegexpBackwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) - return searchRegexpBackward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunkSize = 1, - endMargin = doc.getLine(start.line).length - start.ch; - for ( - var line = start.line, first = doc.firstLine(); - line >= first; - - ) { - for (var i = 0; i < chunkSize && line >= first; i++) { - var curLine = doc.getLine(line--); - string = string == null ? curLine : curLine + "\n" + string; - } - chunkSize *= 2; - var match = lastMatchIn(string, regexp, endMargin); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = line + before.length, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos( - startLine + inside.length - 1, - inside.length == 1 - ? startCh + inside[0].length - : inside[inside.length - 1].length - ), - match, - }; - } + } + } + return nw; + } + function stretchSpansOverChange(doc, change) { + if (change.full) { + return null; + } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) { + return null; + } + var startCh = change.from.ch, + endCh = change.to.ch, + isInsert = cmp(change.from, change.to) == 0; + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + var sameLine = change.text.length == 1, + offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + for (var i2 = 0; i2 < first.length; ++i2) { + var span = first[i2]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) { + span.to = startCh; + } else if (sameLine) { + span.to = found.to == null ? null : found.to + offset; } } - var doFold, noFold; - if (String.prototype.normalize) { - doFold = function (str) { - return str.normalize("NFD").toLowerCase(); - }; - noFold = function (str) { - return str.normalize("NFD"); - }; - } else { - doFold = function (str) { - return str.toLowerCase(); - }; - noFold = function (str) { - return str; - }; - } - function adjustPos(orig, folded, pos, foldFunc) { - if (orig.length == folded.length) return pos; - for ( - var min = 0, - max = pos + Math.max(0, orig.length - folded.length); - ; - - ) { - if (min == max) return min; - var mid = (min + max) >> 1; - var len = foldFunc(orig.slice(0, mid)).length; - if (len == pos) return mid; - else if (len > pos) max = mid; - else min = mid + 1; - } + } + } + if (last) { + for (var i$12 = 0; i$12 < last.length; ++i$12) { + var span$1 = last[i$12]; + if (span$1.to != null) { + span$1.to += offset; } - function searchStringForward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for ( - var line = start.line, - ch = start.ch, - last = doc.lastLine() + 1 - lines.length; - line <= last; - line++, ch = 0 - ) { - var orig = doc.getLine(line).slice(ch), - string = fold(orig); - if (lines.length == 1) { - var found = string.indexOf(lines[0]); - if (found == -1) continue search; - var start = adjustPos(orig, string, found, fold) + ch; - return { - from: Pos( - line, - adjustPos(orig, string, found, fold) + ch - ), - to: Pos( - line, - adjustPos(orig, string, found + lines[0].length, fold) + - ch - ), - }; - } else { - var cutFrom = string.length - lines[0].length; - if (string.slice(cutFrom) != lines[0]) continue search; - for (var i = 1; i < lines.length - 1; i++) - if (fold(doc.getLine(line + i)) != lines[i]) - continue search; - var end = doc.getLine(line + lines.length - 1), - endString = fold(end), - lastLine = lines[lines.length - 1]; - if (endString.slice(0, lastLine.length) != lastLine) - continue search; - return { - from: Pos( - line, - adjustPos(orig, string, cutFrom, fold) + ch - ), - to: Pos( - line + lines.length - 1, - adjustPos(end, endString, lastLine.length, fold) - ), - }; + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker); + if (!found$1) { + span$1.from = offset; + if (sameLine) { + (first || (first = [])).push(span$1); } } - } - function searchStringBackward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for ( - var line = start.line, - ch = start.ch, - first = doc.firstLine() - 1 + lines.length; - line >= first; - line--, ch = -1 - ) { - var orig = doc.getLine(line); - if (ch > -1) orig = orig.slice(0, ch); - var string = fold(orig); - if (lines.length == 1) { - var found = string.lastIndexOf(lines[0]); - if (found == -1) continue search; - return { - from: Pos(line, adjustPos(orig, string, found, fold)), - to: Pos( - line, - adjustPos(orig, string, found + lines[0].length, fold) - ), - }; - } else { - var lastLine = lines[lines.length - 1]; - if (string.slice(0, lastLine.length) != lastLine) - continue search; - for ( - var i = 1, start = line - lines.length + 1; - i < lines.length - 1; - i++ - ) - if (fold(doc.getLine(start + i)) != lines[i]) - continue search; - var top = doc.getLine(line + 1 - lines.length), - topString = fold(top); - if ( - topString.slice(topString.length - lines[0].length) != - lines[0] - ) - continue search; - return { - from: Pos( - line + 1 - lines.length, - adjustPos( - top, - topString, - top.length - lines[0].length, - fold - ) - ), - to: Pos( - line, - adjustPos(orig, string, lastLine.length, fold) - ), - }; - } + } else { + span$1.from += offset; + if (sameLine) { + (first || (first = [])).push(span$1); } } - function SearchCursor(doc, query, pos, options) { - this.atOccurrence = false; - this.afterEmptyMatch = false; - this.doc = doc; - pos = pos ? doc.clipPos(pos) : Pos(0, 0); - this.pos = { - from: pos, - to: pos, - }; - var caseFold; - if (typeof options == "object") { - caseFold = options.caseFold; - } else { - caseFold = options; - options = null; - } - if (typeof query == "string") { - if (caseFold == null) caseFold = false; - this.matches = function (reverse, pos2) { - return ( - reverse ? searchStringBackward : searchStringForward - )(doc, query, pos2, caseFold); - }; - } else { - query = ensureFlags(query, "gm"); - if (!options || options.multiline !== false) - this.matches = function (reverse, pos2) { - return ( - reverse - ? searchRegexpBackwardMultiline - : searchRegexpForwardMultiline - )(doc, query, pos2); - }; - else - this.matches = function (reverse, pos2) { - return ( - reverse ? searchRegexpBackward : searchRegexpForward - )(doc, query, pos2); - }; + } + } + if (first) { + first = clearEmptySpans(first); + } + if (last && last != first) { + last = clearEmptySpans(last); + } + var newMarkers = [first]; + if (!sameLine) { + var gap = change.text.length - 2, + gapMarkers; + if (gap > 0 && first) { + for (var i$22 = 0; i$22 < first.length; ++i$22) { + if (first[i$22].to == null) { + (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null)); } } - SearchCursor.prototype = { - findNext: function () { - return this.find(false); - }, - findPrevious: function () { - return this.find(true); - }, - find: function (reverse) { - var head = this.doc.clipPos( - reverse ? this.pos.from : this.pos.to - ); - if (this.afterEmptyMatch && this.atOccurrence) { - head = Pos(head.line, head.ch); - if (reverse) { - head.ch--; - if (head.ch < 0) { - head.line--; - head.ch = (this.doc.getLine(head.line) || "").length; - } - } else { - head.ch++; - if ( - head.ch > (this.doc.getLine(head.line) || "").length - ) { - head.ch = 0; - head.line++; - } - } - if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { - return (this.atOccurrence = false); - } - } - var result = this.matches(reverse, head); - this.afterEmptyMatch = - result && CodeMirror.cmpPos(result.from, result.to) == 0; - if (result) { - this.pos = result; - this.atOccurrence = true; - return this.pos.match || true; - } else { - var end = Pos( - reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, - 0 - ); - this.pos = { - from: end, - to: end, - }; - return (this.atOccurrence = false); - } - }, - from: function () { - if (this.atOccurrence) return this.pos.from; - }, - to: function () { - if (this.atOccurrence) return this.pos.to; - }, - replace: function (newText, origin) { - if (!this.atOccurrence) return; - var lines = CodeMirror.splitLines(newText); - this.doc.replaceRange( - lines, - this.pos.from, - this.pos.to, - origin - ); - this.pos.to = Pos( - this.pos.from.line + lines.length - 1, - lines[lines.length - 1].length + - (lines.length == 1 ? this.pos.from.ch : 0) - ); - }, - }; - CodeMirror.defineExtension( - "getSearchCursor", - function (query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold); - } - ); - CodeMirror.defineDocExtension( - "getSearchCursor", - function (query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold); - } - ); - CodeMirror.defineExtension( - "selectMatches", - function (query, caseFold) { - var ranges = []; - var cur = this.getSearchCursor( - query, - this.getCursor("from"), - caseFold - ); - while (cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) - break; - ranges.push({ - anchor: cur.from(), - head: cur.to(), - }); - } - if (ranges.length) this.setSelections(ranges, 0); - } - ); - }); - })(); - return searchcursor.exports; + } + for (var i$3 = 0; i$3 < gap; ++i$3) { + newMarkers.push(gapMarkers); + } + newMarkers.push(last); + } + return newMarkers; } - exports.requireSearchcursor = requireSearchcursor; - - /***/ - }, - - /***/ "../../graphiql-react/dist/show-hint.cjs.js": - /*!**************************************************!*\ - !*** ../../graphiql-react/dist/show-hint.cjs.js ***! - \**************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } - } - } + function clearEmptySpans(spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { + spans.splice(i2--, 1); } } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); + if (!spans.length) { + return null; + } + return spans; } - var showHint$2 = { - exports: {}, - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var HINT_ELEMENT_CLASS = "CodeMirror-hint"; - var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; - CodeMirror.showHint = function (cm, getHints, options) { - if (!getHints) return cm.showHint(options); - if (options && options.async) getHints.async = true; - var newOpts = { - hint: getHints, - }; - if (options) - for (var prop in options) newOpts[prop] = options[prop]; - return cm.showHint(newOpts); - }; - CodeMirror.defineExtension("showHint", function (options) { - options = parseOptions(this, this.getCursor("start"), options); - var selections = this.listSelections(); - if (selections.length > 1) return; - if (this.somethingSelected()) { - if (!options.hint.supportsSelection) return; - for (var i = 0; i < selections.length; i++) - if (selections[i].head.line != selections[i].anchor.line) - return; - } - if (this.state.completionActive) - this.state.completionActive.close(); - var completion = (this.state.completionActive = new Completion( - this, - options - )); - if (!completion.options.hint) return; - CodeMirror.signal(this, "startCompletion", this); - completion.update(true); - }); - CodeMirror.defineExtension("closeHint", function () { - if (this.state.completionActive) - this.state.completionActive.close(); - }); - function Completion(cm, options) { - this.cm = cm; - this.options = options; - this.widget = null; - this.debounce = 0; - this.tick = 0; - this.startPos = this.cm.getCursor("start"); - this.startLen = - this.cm.getLine(this.startPos.line).length - - this.cm.getSelection().length; - if (this.options.updateOnCursorActivity) { - var self = this; - cm.on( - "cursorActivity", - (this.activityFunc = function () { - self.cursorActivity(); - }) - ); + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { + for (var i3 = 0; i3 < line.markedSpans.length; ++i3) { + var mark = line.markedSpans[i3].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { + (markers || (markers = [])).push(mark); + } } } - var requestAnimationFrame = - window.requestAnimationFrame || - function (fn) { - return setTimeout(fn, 1e3 / 60); - }; - var cancelAnimationFrame = - window.cancelAnimationFrame || clearTimeout; - Completion.prototype = { - close: function () { - if (!this.active()) return; - this.cm.state.completionActive = null; - this.tick = null; - if (this.options.updateOnCursorActivity) { - this.cm.off("cursorActivity", this.activityFunc); - } - if (this.widget && this.data) - CodeMirror.signal(this.data, "close"); - if (this.widget) this.widget.close(); - CodeMirror.signal(this.cm, "endCompletion", this.cm); - }, - active: function () { - return this.cm.state.completionActive == this; - }, - pick: function (data, i) { - var completion = data.list[i], - self = this; - this.cm.operation(function () { - if (completion.hint) - completion.hint(self.cm, data, completion); - else - self.cm.replaceRange( - getText(completion), - completion.from || data.from, - completion.to || data.to, - "complete" - ); - CodeMirror.signal(data, "pick", completion); - self.cm.scrollIntoView(); + }); + if (!markers) { + return null; + } + var parts = [{ + from, + to + }]; + for (var i2 = 0; i2 < markers.length; ++i2) { + var mk = markers[i2], + m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { + continue; + } + var newParts = [j, 1], + dfrom = cmp(p.from, m.from), + dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { + newParts.push({ + from: p.from, + to: m.from }); - if (this.options.closeOnPick) { - this.close(); - } - }, - cursorActivity: function () { - if (this.debounce) { - cancelAnimationFrame(this.debounce); - this.debounce = 0; - } - var identStart = this.startPos; - if (this.data) { - identStart = this.data.from; - } - var pos = this.cm.getCursor(), - line = this.cm.getLine(pos.line); - if ( - pos.line != this.startPos.line || - line.length - pos.ch != this.startLen - this.startPos.ch || - pos.ch < identStart.ch || - this.cm.somethingSelected() || - !pos.ch || - this.options.closeCharacters.test(line.charAt(pos.ch - 1)) - ) { - this.close(); - } else { - var self = this; - this.debounce = requestAnimationFrame(function () { - self.update(); - }); - if (this.widget) this.widget.disable(); - } - }, - update: function (first) { - if (this.tick == null) return; - var self = this, - myTick = ++this.tick; - fetchHints( - this.options.hint, - this.cm, - this.options, - function (data) { - if (self.tick == myTick) self.finishUpdate(data, first); - } - ); - }, - finishUpdate: function (data, first) { - if (this.data) CodeMirror.signal(this.data, "update"); - var picked = - (this.widget && this.widget.picked) || - (first && this.options.completeSingle); - if (this.widget) this.widget.close(); - this.data = data; - if (data && data.list.length) { - if (picked && data.list.length == 1) { - this.pick(data, 0); - } else { - this.widget = new Widget(this, data); - CodeMirror.signal(data, "shown"); - } - } - }, - }; - function parseOptions(cm, pos, options) { - var editor = cm.options.hintOptions; - var out = {}; - for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) { - for (var prop in editor) - if (editor[prop] !== void 0) out[prop] = editor[prop]; } - if (options) { - for (var prop in options) - if (options[prop] !== void 0) out[prop] = options[prop]; + if (dto > 0 || !mk.inclusiveRight && !dto) { + newParts.push({ + from: m.to, + to: p.to + }); } - if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); - return out; - } - function getText(completion) { - if (typeof completion == "string") return completion; - else return completion.text; - } - function buildKeyMap(completion, handle) { - var baseMap = { - Up: function () { - handle.moveFocus(-1); - }, - Down: function () { - handle.moveFocus(1); - }, - PageUp: function () { - handle.moveFocus(-handle.menuSize() + 1, true); - }, - PageDown: function () { - handle.moveFocus(handle.menuSize() - 1, true); - }, - Home: function () { - handle.setFocus(0); - }, - End: function () { - handle.setFocus(handle.length - 1); - }, - Enter: handle.pick, - Tab: handle.pick, - Esc: handle.close, - }; - var mac = /Mac/.test(navigator.platform); - if (mac) { - baseMap["Ctrl-P"] = function () { - handle.moveFocus(-1); - }; - baseMap["Ctrl-N"] = function () { - handle.moveFocus(1); - }; + parts.splice.apply(parts, newParts); + j += newParts.length - 3; + } + } + return parts; + } + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.detachLine(line); + } + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.attachLine(line); + } + line.markedSpans = spans; + } + function extraLeft(marker) { + return marker.inclusiveLeft ? -1 : 0; + } + function extraRight(marker) { + return marker.inclusiveRight ? 1 : 0; + } + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) { + return lenDiff; + } + var aPos = a.find(), + bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) { + return -fromCmp; + } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) { + return toCmp; + } + return b.id - a.id; + } + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, + found; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { + found = sp.marker; } - var custom = completion.options.customKeys; - var ourMap = custom ? {} : baseMap; - function addBinding(key2, val) { - var bound; - if (typeof val != "string") - bound = function (cm) { - return val(cm, handle); - }; - else if (baseMap.hasOwnProperty(val)) bound = baseMap[val]; - else bound = val; - ourMap[key2] = bound; + } + } + return found; + } + function collapsedSpanAtStart(line) { + return collapsedSpanAtSide(line, true); + } + function collapsedSpanAtEnd(line) { + return collapsedSpanAtSide(line, false); + } + function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, + found; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { + found = sp.marker; } - if (custom) { - for (var key in custom) - if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); + } + } + return found; + } + function conflictingCollapsedRange(doc, lineNo2, from, to, marker) { + var line = getLine(doc, lineNo2); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; } - var extra = completion.options.extraKeys; - if (extra) { - for (var key in extra) - if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { + continue; } - return ourMap; - } - function getHintElement(hintsElement, el) { - while (el && el != hintsElement) { - if ( - el.nodeName.toUpperCase() === "LI" && - el.parentNode == hintsElement - ) - return el; - el = el.parentNode; + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { + return true; } } - function Widget(completion, data) { - this.id = "cm-complete-" + Math.floor(Math.random(1e6)); - this.completion = completion; - this.data = data; - this.picked = false; - var widget = this, - cm = completion.cm; - var ownerDocument = cm.getInputField().ownerDocument; - var parentWindow = - ownerDocument.defaultView || ownerDocument.parentWindow; - var hints = (this.hints = ownerDocument.createElement("ul")); - hints.setAttribute("role", "listbox"); - hints.setAttribute("aria-expanded", "true"); - hints.id = this.id; - var theme = completion.cm.options.theme; - hints.className = "CodeMirror-hints " + theme; - this.selectedHint = data.selectedHint || 0; - var completions = data.list; - for (var i = 0; i < completions.length; ++i) { - var elt = hints.appendChild(ownerDocument.createElement("li")), - cur = completions[i]; - var className = - HINT_ELEMENT_CLASS + - (i != this.selectedHint - ? "" - : " " + ACTIVE_HINT_ELEMENT_CLASS); - if (cur.className != null) - className = cur.className + " " + className; - elt.className = className; - if (i == this.selectedHint) - elt.setAttribute("aria-selected", "true"); - elt.id = this.id + "-" + i; - elt.setAttribute("role", "option"); - if (cur.render) cur.render(elt, data, cur); - else - elt.appendChild( - ownerDocument.createTextNode( - cur.displayText || getText(cur) - ) - ); - elt.hintId = i; - } - var container = - completion.options.container || ownerDocument.body; - var pos = cm.cursorCoords( - completion.options.alignWithWord ? data.from : null - ); - var left = pos.left, - top = pos.bottom, - below = true; - var offsetLeft = 0, - offsetTop = 0; - if (container !== ownerDocument.body) { - var isContainerPositioned = - ["absolute", "relative", "fixed"].indexOf( - parentWindow.getComputedStyle(container).position - ) !== -1; - var offsetParent = isContainerPositioned - ? container - : container.offsetParent; - var offsetParentPosition = offsetParent.getBoundingClientRect(); - var bodyPosition = ownerDocument.body.getBoundingClientRect(); - offsetLeft = - offsetParentPosition.left - - bodyPosition.left - - offsetParent.scrollLeft; - offsetTop = - offsetParentPosition.top - - bodyPosition.top - - offsetParent.scrollTop; - } - hints.style.left = left - offsetLeft + "px"; - hints.style.top = top - offsetTop + "px"; - var winW = - parentWindow.innerWidth || - Math.max( - ownerDocument.body.offsetWidth, - ownerDocument.documentElement.offsetWidth - ); - var winH = - parentWindow.innerHeight || - Math.max( - ownerDocument.body.offsetHeight, - ownerDocument.documentElement.offsetHeight - ); - container.appendChild(hints); - cm.getInputField().setAttribute("aria-autocomplete", "list"); - cm.getInputField().setAttribute("aria-owns", this.id); - cm.getInputField().setAttribute( - "aria-activedescendant", - this.id + "-" + this.selectedHint - ); - var box = completion.options.moveOnOverlap - ? hints.getBoundingClientRect() - : new DOMRect(); - var scrolls = completion.options.paddingForScrollbar - ? hints.scrollHeight > hints.clientHeight + 1 - : false; - var startScroll; - setTimeout(function () { - startScroll = cm.getScrollInfo(); - }); - var overlapY = box.bottom - winH; - if (overlapY > 0) { - var height = box.bottom - box.top, - curTop = pos.top - (pos.bottom - box.top); - if (curTop - height > 0) { - hints.style.top = (top = pos.top - height - offsetTop) + "px"; - below = false; - } else if (height > winH) { - hints.style.height = winH - 5 + "px"; - hints.style.top = - (top = pos.bottom - box.top - offsetTop) + "px"; - var cursor = cm.getCursor(); - if (data.from.ch != cursor.ch) { - pos = cm.cursorCoords(cursor); - hints.style.left = (left = pos.left - offsetLeft) + "px"; - box = hints.getBoundingClientRect(); - } - } + } + } + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) { + line = merged.find(-1, true).line; + } + return line; + } + function visualLineEnd(line) { + var merged; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + } + return line; + } + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), + vis = visualLine(line); + if (line == vis) { + return lineN; + } + return lineNo(vis); + } + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { + return lineN; + } + var line = getLine(doc, lineN), + merged; + if (!lineIsHidden(doc, line)) { + return lineN; + } + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + } + return lineNo(line) + 1; + } + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; } - var overlapX = box.right - winW; - if (scrolls) overlapX += cm.display.nativeBarWidth; - if (overlapX > 0) { - if (box.right - box.left > winW) { - hints.style.width = winW - 5 + "px"; - overlapX -= box.right - box.left - winW; - } - hints.style.left = - (left = pos.left - overlapX - offsetLeft) + "px"; + if (sp.from == null) { + return true; } - if (scrolls) - for (var node = hints.firstChild; node; node = node.nextSibling) - node.style.paddingRight = cm.display.nativeBarWidth + "px"; - cm.addKeyMap( - (this.keyMap = buildKeyMap(completion, { - moveFocus: function (n, avoidWrap) { - widget.changeActive(widget.selectedHint + n, avoidWrap); - }, - setFocus: function (n) { - widget.changeActive(n); - }, - menuSize: function () { - return widget.screenAmount(); - }, - length: completions.length, - close: function () { - completion.close(); - }, - pick: function () { - widget.pick(); - }, - data, - })) - ); - if (completion.options.closeOnUnfocus) { - var closingOnBlur; - cm.on( - "blur", - (this.onBlur = function () { - closingOnBlur = setTimeout(function () { - completion.close(); - }, 100); - }) - ); - cm.on( - "focus", - (this.onFocus = function () { - clearTimeout(closingOnBlur); - }) - ); + if (sp.marker.widgetNode) { + continue; } - cm.on( - "scroll", - (this.onScroll = function () { - var curScroll = cm.getScrollInfo(), - editor = cm.getWrapperElement().getBoundingClientRect(); - if (!startScroll) startScroll = cm.getScrollInfo(); - var newTop = top + startScroll.top - curScroll.top; - var point = - newTop - - (parentWindow.pageYOffset || - (ownerDocument.documentElement || ownerDocument.body) - .scrollTop); - if (!below) point += hints.offsetHeight; - if (point <= editor.top || point >= editor.bottom) - return completion.close(); - hints.style.top = newTop + "px"; - hints.style.left = - left + startScroll.left - curScroll.left + "px"; - }) - ); - CodeMirror.on(hints, "dblclick", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - widget.pick(); - } - }); - CodeMirror.on(hints, "click", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - if (completion.options.completeOnSingleClick) widget.pick(); - } - }); - CodeMirror.on(hints, "mousedown", function () { - setTimeout(function () { - cm.focus(); - }, 20); - }); - var selectedHintRange = this.getSelectedHintRange(); - if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { - this.scrollToActive(); + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { + return true; } - CodeMirror.signal( - data, - "select", - completions[this.selectedHint], - hints.childNodes[this.selectedHint] - ); + } + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) { + return true; + } + for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) { + sp = line.markedSpans[i2]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { return true; } - Widget.prototype = { - close: function () { - if (this.completion.widget != this) return; - this.completion.widget = null; - if (this.hints.parentNode) - this.hints.parentNode.removeChild(this.hints); - this.completion.cm.removeKeyMap(this.keyMap); - var input = this.completion.cm.getInputField(); - input.removeAttribute("aria-activedescendant"); - input.removeAttribute("aria-owns"); - var cm = this.completion.cm; - if (this.completion.options.closeOnUnfocus) { - cm.off("blur", this.onBlur); - cm.off("focus", this.onFocus); - } - cm.off("scroll", this.onScroll); - }, - disable: function () { - this.completion.cm.removeKeyMap(this.keyMap); - var widget = this; - this.keyMap = { - Enter: function () { - widget.picked = true; - }, - }; - this.completion.cm.addKeyMap(this.keyMap); - }, - pick: function () { - this.completion.pick(this.data, this.selectedHint); - }, - changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) - i = avoidWrap ? this.data.list.length - 1 : 0; - else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; - if (this.selectedHint == i) return; - var node = this.hints.childNodes[this.selectedHint]; - if (node) { - node.className = node.className.replace( - " " + ACTIVE_HINT_ELEMENT_CLASS, - "" - ); - node.removeAttribute("aria-selected"); - } - node = this.hints.childNodes[(this.selectedHint = i)]; - node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - node.setAttribute("aria-selected", "true"); - this.completion.cm - .getInputField() - .setAttribute("aria-activedescendant", node.id); - this.scrollToActive(); - CodeMirror.signal( - this.data, - "select", - this.data.list[this.selectedHint], - node - ); - }, - scrollToActive: function () { - var selectedHintRange = this.getSelectedHintRange(); - var node1 = this.hints.childNodes[selectedHintRange.from]; - var node2 = this.hints.childNodes[selectedHintRange.to]; - var firstNode = this.hints.firstChild; - if (node1.offsetTop < this.hints.scrollTop) - this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop; - else if ( - node2.offsetTop + node2.offsetHeight > - this.hints.scrollTop + this.hints.clientHeight - ) - this.hints.scrollTop = - node2.offsetTop + - node2.offsetHeight - - this.hints.clientHeight + - firstNode.offsetTop; - }, - screenAmount: function () { - return ( - Math.floor( - this.hints.clientHeight / this.hints.firstChild.offsetHeight - ) || 1 - ); - }, - getSelectedHintRange: function () { - var margin = this.completion.options.scrollMargin || 0; - return { - from: Math.max(0, this.selectedHint - margin), - to: Math.min( - this.data.list.length - 1, - this.selectedHint + margin - ), - }; - }, - }; - function applicableHelpers(cm, helpers) { - if (!cm.somethingSelected()) return helpers; - var result = []; - for (var i = 0; i < helpers.length; i++) - if (helpers[i].supportsSelection) result.push(helpers[i]); - return result; + } + } + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + var h = 0, + chunk = lineObj.parent; + for (var i2 = 0; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2]; + if (line == lineObj) { + break; + } else { + h += line.height; } - function fetchHints(hint, cm, options, callback) { - if (hint.async) { - hint(cm, callback, options); + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$12 = 0; i$12 < p.children.length; ++i$12) { + var cur = p.children[i$12]; + if (cur == chunk) { + break; } else { - var result = hint(cm, options); - if (result && result.then) result.then(callback); - else callback(result); + h += cur.height; } } - function resolveAutoHints(cm, pos) { - var helpers = cm.getHelpers(pos, "hint"), - words; - if (helpers.length) { - var resolved = function (cm2, callback, options) { - var app = applicableHelpers(cm2, helpers); - function run(i) { - if (i == app.length) return callback(null); - fetchHints(app[i], cm2, options, function (result) { - if (result && result.list.length > 0) callback(result); - else run(i + 1); - }); - } - run(0); - }; - resolved.async = true; - resolved.supportsSelection = true; - return resolved; - } else if ((words = cm.getHelper(cm.getCursor(), "hintWords"))) { - return function (cm2) { - return CodeMirror.hint.fromList(cm2, { - words, - }); - }; - } else if (CodeMirror.hint.anyword) { - return function (cm2, options) { - return CodeMirror.hint.anyword(cm2, options); - }; - } else { - return function () {}; - } + } + return h; + } + function lineLength(line) { + if (line.height == 0) { + return 0; + } + var len = line.text.length, + merged, + cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true); + len -= cur.text.length - found$1.from.ch; + cur = found$1.to.line; + len += cur.text.length - found$1.to.ch; + } + return len; + } + function findMaxLine(cm) { + var d = cm.display, + doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + var Line = function (text, markedSpans, estimateHeight2) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight2 ? estimateHeight2(this) : 1; + }; + Line.prototype.lineNo = function () { + return lineNo(this); + }; + eventMixin(Line); + function updateLine(line, text, markedSpans, estimateHeight2) { + line.text = text; + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + if (line.order != null) { + line.order = null; + } + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight2 ? estimateHeight2(line) : 1; + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + } + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + var styleToClassCache = {}, + styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { + return null; + } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + function buildLineContent(cm, lineView) { + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = { + pre: eltP("pre", [content], "CodeMirror-line"), + content, + col: 0, + pos: 0, + cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping") + }; + lineView.measure = {}; + for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) { + var line = i2 ? lineView.rest[i2 - 1] : lineView.line, + order = void 0; + builder.pos = 0; + builder.addToken = buildToken; + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { + builder.addToken = buildTokenBadBidi(builder.addToken, order); + } + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) { + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); + } + if (line.styleClasses.textClass) { + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); + } + } + if (builder.map.length == 0) { + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); + } + if (i2 == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); } - CodeMirror.registerHelper("hint", "auto", { - resolve: resolveAutoHints, - }); - CodeMirror.registerHelper( - "hint", - "fromList", - function (cm, options) { - var cur = cm.getCursor(), - token = cm.getTokenAt(cur); - var term, - from = CodeMirror.Pos(cur.line, token.start), - to = cur; - if ( - token.start < cur.ch && - /\w/.test(token.string.charAt(cur.ch - token.start - 1)) - ) { - term = token.string.substr(0, cur.ch - token.start); + } + if (webkit) { + var last = builder.content.lastChild; + if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) { + builder.content.className = "cm-tab-wrap-hack"; + } + } + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) { + builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); + } + return builder; + } + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "•", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { + if (!text) { + return; + } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; + var special = builder.cm.state.specialChars, + mustWrap = false; + var content; + if (!special.test(text)) { + builder.col += text.length; + content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) { + mustWrap = true; + } + builder.pos += text.length; + } else { + content = document.createDocumentFragment(); + var pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt])); } else { - term = ""; - from = cur; + content.appendChild(txt); } - var found = []; - for (var i = 0; i < options.words.length; i++) { - var word = options.words[i]; - if (word.slice(0, term.length) == term) found.push(word); - } - if (found.length) - return { - list: found, - from, - to, - }; + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; } - ); - CodeMirror.commands.autocomplete = CodeMirror.showHint; - var defaultOptions = { - hint: CodeMirror.hint.auto, - completeSingle: true, - alignWithWord: true, - closeCharacters: /[\s()\[\]{};:>,]/, - closeOnPick: true, - closeOnUnfocus: true, - updateOnCursorActivity: true, - completeOnSingleClick: true, - container: null, - customKeys: null, - extraKeys: null, - paddingForScrollbar: true, - moveOnOverlap: true, - }; - CodeMirror.defineOption("hintOptions", null); - }); - })(); - var showHintExports = showHint$2.exports; - const showHint = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(showHintExports); - const showHint$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: showHint, - }, - [showHintExports] - ); - exports.showHint = showHint$1; - - /***/ - }, - - /***/ "../../graphiql-react/dist/sublime.cjs.js": - /*!************************************************!*\ - !*** ../../graphiql-react/dist/sublime.cjs.js ***! - \************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - const codemirror = __webpack_require__( - /*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js" - ); - const searchcursor = __webpack_require__( - /*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js" - ); - const matchbrackets = __webpack_require__( - /*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js" - ); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: () => e[k], - } - ); - } + if (!m) { + break; + } + pos += skipped + 1; + var txt$1 = void 0; + if (m[0] == " ") { + var tabSize = builder.cm.options.tabSize, + tabWidth = tabSize - builder.col % tabSize; + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt$1.setAttribute("role", "presentation"); + txt$1.setAttribute("cm-text", " "); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar")); + txt$1.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); + txt$1.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt$1])); + } else { + content.appendChild(txt$1); } + builder.col += 1; } + builder.map.push(builder.pos, builder.pos + 1, txt$1); + builder.pos++; } } - return Object.freeze( - Object.defineProperty(n, Symbol.toStringTag, { - value: "Module", - }) - ); - } - var sublime$2 = { - exports: {}, - }; - (function (module2, exports2) { - (function (mod) { - mod( - codemirror.requireCodemirror(), - searchcursor.requireSearchcursor(), - matchbrackets.requireMatchbrackets() - ); - })(function (CodeMirror) { - var cmds = CodeMirror.commands; - var Pos = CodeMirror.Pos; - function findPosSubword(doc, start, dir) { - if (dir < 0 && start.ch == 0) - return doc.clipPos(Pos(start.line - 1)); - var line = doc.getLine(start.line); - if (dir > 0 && start.ch >= line.length) - return doc.clipPos(Pos(start.line + 1, 0)); - var state = "start", - type, - startPos = start.ch; - for ( - var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; - pos != e; - pos += dir, i++ - ) { - var next = line.charAt(dir < 0 ? pos - 1 : pos); - var cat = - next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; - if (cat == "w" && next.toUpperCase() == next) cat = "W"; - if (state == "start") { - if (cat != "o") { - state = "in"; - type = cat; - } else startPos = pos + dir; - } else if (state == "in") { - if (type != cat) { - if (type == "w" && cat == "W" && dir < 0) pos--; - if (type == "W" && cat == "w" && dir > 0) { - if (pos == startPos + 1) { - type = "w"; - continue; - } else pos--; - } - break; - } - } - } - return Pos(start.line, pos); + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; + if (style || startStyle || endStyle || mustWrap || css || attributes) { + var fullStyle = style || ""; + if (startStyle) { + fullStyle += startStyle; } - function moveSubword(cm, dir) { - cm.extendSelectionsBy(function (range) { - if (cm.display.shift || cm.doc.extend || range.empty()) - return findPosSubword(cm.doc, range.head, dir); - else return dir < 0 ? range.from() : range.to(); - }); + if (endStyle) { + fullStyle += endStyle; } - cmds.goSubwordLeft = function (cm) { - moveSubword(cm, -1); - }; - cmds.goSubwordRight = function (cm) { - moveSubword(cm, 1); - }; - cmds.scrollLineUp = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleBottomLine = cm.lineAtHeight( - info.top + info.clientHeight, - "local" - ); - if (cm.getCursor().line >= visibleBottomLine) - cm.execCommand("goLineUp"); - } - cm.scrollTo(null, info.top - cm.defaultTextHeight()); - }; - cmds.scrollLineDown = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; - if (cm.getCursor().line <= visibleTopLine) - cm.execCommand("goLineDown"); - } - cm.scrollTo(null, info.top + cm.defaultTextHeight()); - }; - cmds.splitSelectionByLine = function (cm) { - var ranges = cm.listSelections(), - lineRanges = []; - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - for (var line = from.line; line <= to.line; ++line) - if (!(to.line > from.line && line == to.line && to.ch == 0)) - lineRanges.push({ - anchor: line == from.line ? from : Pos(line, 0), - head: line == to.line ? to : Pos(line), - }); - } - cm.setSelections(lineRanges, 0); - }; - cmds.singleSelectionTop = function (cm) { - var range = cm.listSelections()[0]; - cm.setSelection(range.anchor, range.head, { - scroll: false, - }); - }; - cmds.selectLine = function (cm) { - var ranges = cm.listSelections(), - extended = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - extended.push({ - anchor: Pos(range.from().line, 0), - head: Pos(range.to().line + 1, 0), - }); - } - cm.setSelections(extended); - }; - function insertLine(cm, above) { - if (cm.isReadOnly()) return CodeMirror.Pass; - cm.operation(function () { - var len = cm.listSelections().length, - newSelection = [], - last = -1; - for (var i = 0; i < len; i++) { - var head = cm.listSelections()[i].head; - if (head.line <= last) continue; - var at = Pos(head.line + (above ? 0 : 1), 0); - cm.replaceRange("\n", at, null, "+insertLine"); - cm.indentLine(at.line, null, true); - newSelection.push({ - head: at, - anchor: at, - }); - last = head.line + 1; + var token = elt("span", [content], fullStyle, css); + if (attributes) { + for (var attr in attributes) { + if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { + token.setAttribute(attr, attributes[attr]); } - cm.setSelections(newSelection); - }); - cm.execCommand("indentAuto"); + } } - cmds.insertLineAfter = function (cm) { - return insertLine(cm, false); - }; - cmds.insertLineBefore = function (cm) { - return insertLine(cm, true); - }; - function wordAt(cm, pos) { - var start = pos.ch, - end = start, - line = cm.getLine(pos.line); - while (start && CodeMirror.isWordChar(line.charAt(start - 1))) - --start; - while ( - end < line.length && - CodeMirror.isWordChar(line.charAt(end)) - ) - ++end; - return { - from: Pos(pos.line, start), - to: Pos(pos.line, end), - word: line.slice(start, end), - }; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { + return text; + } + var spaceBefore = trailingBefore, + result = ""; + for (var i2 = 0; i2 < text.length; i2++) { + var ch = text.charAt(i2); + if (ch == " " && spaceBefore && (i2 == text.length - 1 || text.charCodeAt(i2 + 1) == 32)) { + ch = " "; } - cmds.selectNextOccurrence = function (cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - cm.setSelection(word.from, word.to); - fullWord = true; - } else { - var text = cm.getRange(from, to); - var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; - var cur = cm.getSearchCursor(query, to); - var found = cur.findNext(); - if (!found) { - cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); - found = cur.findNext(); + result += ch; + spaceBefore = ch == " "; + } + return result; + } + function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, css, attributes) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, + end = start + text.length; + for (;;) { + var part = void 0; + for (var i2 = 0; i2 < order.length; i2++) { + part = order[i2]; + if (part.to > start && part.from <= start) { + break; } - if ( - !found || - isSelectedRange(cm.listSelections(), cur.from(), cur.to()) - ) - return; - cm.addSelection(cur.from(), cur.to()); - } - if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; - }; - cmds.skipAndSelectNextOccurrence = function (cm) { - var prevAnchor = cm.getCursor("anchor"), - prevHead = cm.getCursor("head"); - cmds.selectNextOccurrence(cm); - if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { - cm.doc.setSelections( - cm.doc.listSelections().filter(function (sel) { - return sel.anchor != prevAnchor || sel.head != prevHead; - }) - ); } - }; - function addCursorToSelection(cm, dir) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var newAnchor = cm.findPosV( - range.anchor, - dir, - "line", - range.anchor.goalColumn - ); - var newHead = cm.findPosV( - range.head, - dir, - "line", - range.head.goalColumn - ); - newAnchor.goalColumn = - range.anchor.goalColumn != null - ? range.anchor.goalColumn - : cm.cursorCoords(range.anchor, "div").left; - newHead.goalColumn = - range.head.goalColumn != null - ? range.head.goalColumn - : cm.cursorCoords(range.head, "div").left; - var newRange = { - anchor: newAnchor, - head: newHead, - }; - newRanges.push(range); - newRanges.push(newRange); + if (part.to >= end) { + return inner(builder, text, style, startStyle, endStyle, css, attributes); } - cm.setSelections(newRanges); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; } - cmds.addCursorToPrevLine = function (cm) { - addCursorToSelection(cm, -1); - }; - cmds.addCursorToNextLine = function (cm) { - addCursorToSelection(cm, 1); - }; - function isSelectedRange(ranges, from, to) { - for (var i = 0; i < ranges.length; i++) - if ( - CodeMirror.cmpPos(ranges[i].from(), from) == 0 && - CodeMirror.cmpPos(ranges[i].to(), to) == 0 - ) - return true; - return false; + }; + } + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) { + builder.map.push(builder.pos, builder.pos + size, widget); + } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) { + widget = builder.content.appendChild(document.createElement("span")); } - var mirror = "(){}[]"; - function selectBetweenBrackets(cm) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - pos = range.head, - opening = cm.scanForBracket(pos, -1); - if (!opening) return false; - for (;;) { - var closing = cm.scanForBracket(pos, 1); - if (!closing) return false; - if ( - closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1) - ) { - var startPos = Pos(opening.pos.line, opening.pos.ch + 1); - if ( - CodeMirror.cmpPos(startPos, range.from()) == 0 && - CodeMirror.cmpPos(closing.pos, range.to()) == 0 - ) { - opening = cm.scanForBracket(opening.pos, -1); - if (!opening) return false; - } else { - newRanges.push({ - anchor: startPos, - head: closing.pos, - }); - break; + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + builder.trailingSpace = false; + } + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, + allText = line.text, + at = 0; + if (!spans) { + for (var i$12 = 1; i$12 < styles.length; i$12 += 2) { + builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options)); + } + return; + } + var len = allText.length, + pos = 0, + i2 = 1, + text = "", + style, + css; + var nextChange = 0, + spanStyle, + spanEndStyle, + spanStartStyle, + collapsed, + attributes; + for (;;) { + if (nextChange == pos) { + spanStyle = spanEndStyle = spanStartStyle = css = ""; + attributes = null; + collapsed = null; + nextChange = Infinity; + var foundBookmarks = [], + endStyles = void 0; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], + m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) { + spanStyle += " " + m.className; + } + if (m.css) { + css = (css ? css + ";" : "") + m.css; + } + if (m.startStyle && sp.from == pos) { + spanStartStyle += " " + m.startStyle; + } + if (m.endStyle && sp.to == nextChange) { + (endStyles || (endStyles = [])).push(m.endStyle, sp.to); + } + if (m.title) { + (attributes || (attributes = {})).title = m.title; + } + if (m.attributes) { + for (var attr in m.attributes) { + (attributes || (attributes = {}))[attr] = m.attributes[attr]; } } - pos = Pos(closing.pos.line, closing.pos.ch + 1); + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { + collapsed = sp; + } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; } } - cm.setSelections(newRanges); - return true; - } - cmds.selectScope = function (cm) { - selectBetweenBrackets(cm) || cm.execCommand("selectAll"); - }; - cmds.selectBetweenBrackets = function (cm) { - if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; - }; - function puncType(type) { - return !type - ? null - : /\bpunctuation\b/.test(type) - ? type - : void 0; - } - cmds.goToBracket = function (cm) { - cm.extendSelectionsBy(function (range) { - var next = cm.scanForBracket( - range.head, - 1, - puncType(cm.getTokenTypeAt(range.head)) - ); - if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) - return next.pos; - var prev = cm.scanForBracket( - range.head, - -1, - puncType( - cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)) - ) - ); - return ( - (prev && Pos(prev.pos.line, prev.pos.ch + 1)) || range.head - ); - }); - }; - cmds.swapLineUp = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.firstLine() - 1, - newSels = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from().line - 1, - to = range.to().line; - newSels.push({ - anchor: Pos(range.anchor.line - 1, range.anchor.ch), - head: Pos(range.head.line - 1, range.head.ch), - }); - if (range.to().ch == 0 && !range.empty()) --to; - if (from > at) linesToMove.push(from, to); - else if (linesToMove.length) - linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i2 = 0; i2 < linesToMove.length; i2 += 2) { - var from2 = linesToMove[i2], - to2 = linesToMove[i2 + 1]; - var line = cm.getLine(from2); - cm.replaceRange( - "", - Pos(from2, 0), - Pos(from2 + 1, 0), - "+swapLine" - ); - if (to2 > cm.lastLine()) - cm.replaceRange( - "\n" + line, - Pos(cm.lastLine()), - null, - "+swapLine" - ); - else - cm.replaceRange( - line + "\n", - Pos(to2, 0), - null, - "+swapLine" - ); + if (endStyles) { + for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { + if (endStyles[j$1 + 1] == nextChange) { + spanEndStyle += " " + endStyles[j$1]; + } } - cm.setSelections(newSels); - cm.scrollIntoView(); - }); - }; - cmds.swapLineDown = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.lastLine() + 1; - for (var i = ranges.length - 1; i >= 0; i--) { - var range = ranges[i], - from = range.to().line + 1, - to = range.from().line; - if (range.to().ch == 0 && !range.empty()) from--; - if (from < at) linesToMove.push(from, to); - else if (linesToMove.length) - linesToMove[linesToMove.length - 1] = to; - at = to; } - cm.operation(function () { - for (var i2 = linesToMove.length - 2; i2 >= 0; i2 -= 2) { - var from2 = linesToMove[i2], - to2 = linesToMove[i2 + 1]; - var line = cm.getLine(from2); - if (from2 == cm.lastLine()) - cm.replaceRange( - "", - Pos(from2 - 1), - Pos(from2), - "+swapLine" - ); - else - cm.replaceRange( - "", - Pos(from2, 0), - Pos(from2 + 1, 0), - "+swapLine" - ); - cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); + if (!collapsed || collapsed.from == pos) { + for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { + buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } - cm.scrollIntoView(); - }); - }; - cmds.toggleCommentIndented = function (cm) { - cm.toggleComment({ - indent: true, - }); - }; - cmds.joinLines = function (cm) { - var ranges = cm.listSelections(), - joined = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from(); - var start = from.line, - end = range.to().line; - while ( - i < ranges.length - 1 && - ranges[i + 1].from().line == end - ) - end = ranges[++i].to().line; - joined.push({ - start, - end, - anchor: !range.empty() && from, - }); } - cm.operation(function () { - var offset = 0, - ranges2 = []; - for (var i2 = 0; i2 < joined.length; i2++) { - var obj = joined[i2]; - var anchor = - obj.anchor && - Pos(obj.anchor.line - offset, obj.anchor.ch), - head; - for (var line = obj.start; line <= obj.end; line++) { - var actual = line - offset; - if (line == obj.end) - head = Pos(actual, cm.getLine(actual).length + 1); - if (actual < cm.lastLine()) { - cm.replaceRange( - " ", - Pos(actual), - Pos( - actual + 1, - /^\s*/.exec(cm.getLine(actual + 1))[0].length - ) - ); - ++offset; - } - } - ranges2.push({ - anchor: anchor || head, - head, - }); + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); + if (collapsed.to == null) { + return; } - cm.setSelections(ranges2, 0); - }); - }; - cmds.duplicateLine = function (cm) { - cm.operation(function () { - var rangeCount = cm.listSelections().length; - for (var i = 0; i < rangeCount; i++) { - var range = cm.listSelections()[i]; - if (range.empty()) - cm.replaceRange( - cm.getLine(range.head.line) + "\n", - Pos(range.head.line, 0) - ); - else - cm.replaceRange( - cm.getRange(range.from(), range.to()), - range.from() - ); + if (collapsed.to == pos) { + collapsed = false; } - cm.scrollIntoView(); - }); - }; - function sortLines(cm, caseSensitive, direction) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - toSort = [], - selected; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) continue; - var from = range.from().line, - to = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == to) - to = ranges[++i].to().line; - if (!ranges[i].to().ch) to--; - toSort.push(from, to); } - if (toSort.length) selected = true; - else toSort.push(cm.firstLine(), cm.lastLine()); - cm.operation(function () { - var ranges2 = []; - for (var i2 = 0; i2 < toSort.length; i2 += 2) { - var from2 = toSort[i2], - to2 = toSort[i2 + 1]; - var start = Pos(from2, 0), - end = Pos(to2); - var lines = cm.getRange(start, end, false); - if (caseSensitive) - lines.sort(function (a, b) { - return a < b ? -direction : a == b ? 0 : direction; - }); - else - lines.sort(function (a, b) { - var au = a.toUpperCase(), - bu = b.toUpperCase(); - if (au != bu) { - a = au; - b = bu; - } - return a < b ? -direction : a == b ? 0 : direction; - }); - cm.replaceRange(lines, start, end); - if (selected) - ranges2.push({ - anchor: start, - head: Pos(to2 + 1, 0), - }); - } - if (selected) cm.setSelections(ranges2, 0); - }); } - cmds.sortLines = function (cm) { - sortLines(cm, true, 1); - }; - cmds.reverseSortLines = function (cm) { - sortLines(cm, true, -1); - }; - cmds.sortLinesInsensitive = function (cm) { - sortLines(cm, false, 1); - }; - cmds.reverseSortLinesInsensitive = function (cm) { - sortLines(cm, false, -1); - }; - cmds.nextBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) - while (marks.length) { - var current = marks.shift(); - var found = current.find(); - if (found) { - marks.push(current); - return cm.setSelection(found.from, found.to); - } - } - }; - cmds.prevBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) - while (marks.length) { - marks.unshift(marks.pop()); - var found = marks[marks.length - 1].find(); - if (!found) marks.pop(); - else return cm.setSelection(found.from, found.to); - } - }; - cmds.toggleBookmark = function (cm) { - var ranges = cm.listSelections(); - var marks = - cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - var found = ranges[i].empty() - ? cm.findMarksAt(from) - : cm.findMarks(from, to); - for (var j = 0; j < found.length; j++) { - if (found[j].sublimeBookmark) { - found[j].clear(); - for (var k = 0; k < marks.length; k++) - if (marks[k] == found[j]) marks.splice(k--, 1); - break; - } - } - if (j == found.length) - marks.push( - cm.markText(from, to, { - sublimeBookmark: true, - clearWhenEmpty: false, - }) - ); - } - }; - cmds.clearBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) - for (var i = 0; i < marks.length; i++) marks[i].clear(); - marks.length = 0; - }; - cmds.selectBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks, - ranges = []; - if (marks) - for (var i = 0; i < marks.length; i++) { - var found = marks[i].find(); - if (!found) marks.splice(i--, 0); - else - ranges.push({ - anchor: found.from, - head: found.to, - }); - } - if (ranges.length) cm.setSelections(ranges, 0); - }; - function modifyWordOrSelection(cm, mod) { - cm.operation(function () { - var ranges = cm.listSelections(), - indices = [], - replacements = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) { - indices.push(i); - replacements.push(""); - } else - replacements.push( - mod(cm.getRange(range.from(), range.to())) - ); - } - cm.replaceSelections(replacements, "around", "case"); - for (var i = indices.length - 1, at; i >= 0; i--) { - var range = ranges[indices[i]]; - if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; - var word = wordAt(cm, range.head); - at = word.from; - cm.replaceRange(mod(word.word), word.from, word.to); - } - }); + if (pos >= len) { + break; } - cmds.smartBackspace = function (cm) { - if (cm.somethingSelected()) return CodeMirror.Pass; - cm.operation(function () { - var cursors = cm.listSelections(); - var indentUnit = cm.getOption("indentUnit"); - for (var i = cursors.length - 1; i >= 0; i--) { - var cursor = cursors[i].head; - var toStartOfLine = cm.getRange( - { - line: cursor.line, - ch: 0, - }, - cursor - ); - var column = CodeMirror.countColumn( - toStartOfLine, - null, - cm.getOption("tabSize") - ); - var deletePos = cm.findPosH(cursor, -1, "char", false); - if ( - toStartOfLine && - !/\S/.test(toStartOfLine) && - column % indentUnit == 0 - ) { - var prevIndent = new Pos( - cursor.line, - CodeMirror.findColumn( - toStartOfLine, - column - indentUnit, - indentUnit - ) - ); - if (prevIndent.ch != cursor.ch) deletePos = prevIndent; - } - cm.replaceRange("", deletePos, cursor, "+delete"); - } - }); - }; - cmds.delLineRight = function (cm) { - cm.operation(function () { - var ranges = cm.listSelections(); - for (var i = ranges.length - 1; i >= 0; i--) - cm.replaceRange( - "", - ranges[i].anchor, - Pos(ranges[i].to().line), - "+delete" - ); - cm.scrollIntoView(); - }); - }; - cmds.upcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toUpperCase(); - }); - }; - cmds.downcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toLowerCase(); - }); - }; - cmds.setSublimeMark = function (cm) { - if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - }; - cmds.selectToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) cm.setSelection(cm.getCursor(), found); - }; - cmds.deleteToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - var from = cm.getCursor(), - to = found; - if (CodeMirror.cmpPos(from, to) > 0) { - var tmp = to; - to = from; - from = tmp; + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); + } + if (end >= upto) { + text = text.slice(upto - pos); + pos = upto; + break; } - cm.state.sublimeKilled = cm.getRange(from, to); - cm.replaceRange("", from, to); - } - }; - cmds.swapWithSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - cm.setCursor(found); - } - }; - cmds.sublimeYank = function (cm) { - if (cm.state.sublimeKilled != null) - cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); - }; - cmds.showInCenter = function (cm) { - var pos = cm.cursorCoords(null, "local"); - cm.scrollTo( - null, - (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2 - ); - }; - function getTarget(cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - from = word.from; - to = word.to; - } - return { - from, - to, - query: cm.getRange(from, to), - word, - }; - } - function findAndGoTo(cm, forward) { - var target = getTarget(cm); - if (!target) return; - var query = target.query; - var cur = cm.getSearchCursor( - query, - forward ? target.to : target.from - ); - if (forward ? cur.findNext() : cur.findPrevious()) { - cm.setSelection(cur.from(), cur.to()); - } else { - cur = cm.getSearchCursor( - query, - forward - ? Pos(cm.firstLine(), 0) - : cm.clipPos(Pos(cm.lastLine())) - ); - if (forward ? cur.findNext() : cur.findPrevious()) - cm.setSelection(cur.from(), cur.to()); - else if (target.word) cm.setSelection(target.from, target.to); + pos = end; + spanStartStyle = ""; } + text = allText.slice(at, at = styles[i2++]); + style = interpretTokenStyle(styles[i2++], builder.cm.options); } - cmds.findUnder = function (cm) { - findAndGoTo(cm, true); - }; - cmds.findUnderPrevious = function (cm) { - findAndGoTo(cm, false); - }; - cmds.findAllUnder = function (cm) { - var target = getTarget(cm); - if (!target) return; - var cur = cm.getSearchCursor(target.query); - var matches = []; - var primaryIndex = -1; - while (cur.findNext()) { - matches.push({ - anchor: cur.from(), - head: cur.to(), - }); - if ( - cur.from().line <= target.from.line && - cur.from().ch <= target.from.ch - ) - primaryIndex++; - } - cm.setSelections(matches, primaryIndex); - }; - var keyMap = CodeMirror.keyMap; - keyMap.macSublime = { - "Cmd-Left": "goLineStartSmart", - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Ctrl-Alt-Up": "scrollLineUp", - "Ctrl-Alt-Down": "scrollLineDown", - "Cmd-L": "selectLine", - "Shift-Cmd-L": "splitSelectionByLine", - Esc: "singleSelectionTop", - "Cmd-Enter": "insertLineAfter", - "Shift-Cmd-Enter": "insertLineBefore", - "Cmd-D": "selectNextOccurrence", - "Shift-Cmd-Space": "selectScope", - "Shift-Cmd-M": "selectBetweenBrackets", - "Cmd-M": "goToBracket", - "Cmd-Ctrl-Up": "swapLineUp", - "Cmd-Ctrl-Down": "swapLineDown", - "Cmd-/": "toggleCommentIndented", - "Cmd-J": "joinLines", - "Shift-Cmd-D": "duplicateLine", - F5: "sortLines", - "Shift-F5": "reverseSortLines", - "Cmd-F5": "sortLinesInsensitive", - "Shift-Cmd-F5": "reverseSortLinesInsensitive", - F2: "nextBookmark", - "Shift-F2": "prevBookmark", - "Cmd-F2": "toggleBookmark", - "Shift-Cmd-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - Backspace: "smartBackspace", - "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", - "Cmd-K Cmd-K": "delLineRight", - "Cmd-K Cmd-U": "upcaseAtCursor", - "Cmd-K Cmd-L": "downcaseAtCursor", - "Cmd-K Cmd-Space": "setSublimeMark", - "Cmd-K Cmd-A": "selectToSublimeMark", - "Cmd-K Cmd-W": "deleteToSublimeMark", - "Cmd-K Cmd-X": "swapWithSublimeMark", - "Cmd-K Cmd-Y": "sublimeYank", - "Cmd-K Cmd-C": "showInCenter", - "Cmd-K Cmd-G": "clearBookmarks", - "Cmd-K Cmd-Backspace": "delLineLeft", - "Cmd-K Cmd-1": "foldAll", - "Cmd-K Cmd-0": "unfoldAll", - "Cmd-K Cmd-J": "unfoldAll", - "Ctrl-Shift-Up": "addCursorToPrevLine", - "Ctrl-Shift-Down": "addCursorToNextLine", - "Cmd-F3": "findUnder", - "Shift-Cmd-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Cmd-[": "fold", - "Shift-Cmd-]": "unfold", - "Cmd-I": "findIncremental", - "Shift-Cmd-I": "findIncrementalReverse", - "Cmd-H": "replace", - F3: "findNext", - "Shift-F3": "findPrev", - fallthrough: "macDefault", - }; - CodeMirror.normalizeKeyMap(keyMap.macSublime); - keyMap.pcSublime = { - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-T": "transposeChars", - "Alt-Left": "goSubwordLeft", - "Alt-Right": "goSubwordRight", - "Ctrl-Up": "scrollLineUp", - "Ctrl-Down": "scrollLineDown", - "Ctrl-L": "selectLine", - "Shift-Ctrl-L": "splitSelectionByLine", - Esc: "singleSelectionTop", - "Ctrl-Enter": "insertLineAfter", - "Shift-Ctrl-Enter": "insertLineBefore", - "Ctrl-D": "selectNextOccurrence", - "Shift-Ctrl-Space": "selectScope", - "Shift-Ctrl-M": "selectBetweenBrackets", - "Ctrl-M": "goToBracket", - "Shift-Ctrl-Up": "swapLineUp", - "Shift-Ctrl-Down": "swapLineDown", - "Ctrl-/": "toggleCommentIndented", - "Ctrl-J": "joinLines", - "Shift-Ctrl-D": "duplicateLine", - F9: "sortLines", - "Shift-F9": "reverseSortLines", - "Ctrl-F9": "sortLinesInsensitive", - "Shift-Ctrl-F9": "reverseSortLinesInsensitive", - F2: "nextBookmark", - "Shift-F2": "prevBookmark", - "Ctrl-F2": "toggleBookmark", - "Shift-Ctrl-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - Backspace: "smartBackspace", - "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", - "Ctrl-K Ctrl-K": "delLineRight", - "Ctrl-K Ctrl-U": "upcaseAtCursor", - "Ctrl-K Ctrl-L": "downcaseAtCursor", - "Ctrl-K Ctrl-Space": "setSublimeMark", - "Ctrl-K Ctrl-A": "selectToSublimeMark", - "Ctrl-K Ctrl-W": "deleteToSublimeMark", - "Ctrl-K Ctrl-X": "swapWithSublimeMark", - "Ctrl-K Ctrl-Y": "sublimeYank", - "Ctrl-K Ctrl-C": "showInCenter", - "Ctrl-K Ctrl-G": "clearBookmarks", - "Ctrl-K Ctrl-Backspace": "delLineLeft", - "Ctrl-K Ctrl-1": "foldAll", - "Ctrl-K Ctrl-0": "unfoldAll", - "Ctrl-K Ctrl-J": "unfoldAll", - "Ctrl-Alt-Up": "addCursorToPrevLine", - "Ctrl-Alt-Down": "addCursorToNextLine", - "Ctrl-F3": "findUnder", - "Shift-Ctrl-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Ctrl-[": "fold", - "Shift-Ctrl-]": "unfold", - "Ctrl-I": "findIncremental", - "Shift-Ctrl-I": "findIncrementalReverse", - "Ctrl-H": "replace", - F3: "findNext", - "Shift-F3": "findPrev", - fallthrough: "pcDefault", - }; - CodeMirror.normalizeKeyMap(keyMap.pcSublime); - var mac = keyMap.default == keyMap.macDefault; - keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; - }); - })(); - var sublimeExports = sublime$2.exports; - const sublime = - /* @__PURE__ */ codemirror.getDefaultExportFromCjs(sublimeExports); - const sublime$1 = /* @__PURE__ */ _mergeNamespaces( - { - __proto__: null, - default: sublime, - }, - [sublimeExports] - ); - exports.sublime = sublime$1; - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/async-helpers/index.js": - /*!*********************************************************!*\ - !*** ../../graphiql-toolkit/esm/async-helpers/index.js ***! - \*********************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.fetcherReturnToPromise = fetcherReturnToPromise; - exports.isAsyncIterable = isAsyncIterable; - exports.isObservable = isObservable; - exports.isPromise = isPromise; - var __awaiter = - (void 0 && (void 0).__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); + } + } + function LineView(doc, line, lineN) { + this.line = line; + this.rest = visualLineContinued(line); + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + function buildViewArray(cm, from, to) { + var array = [], + nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + var operationGroup = null; + function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op); + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + }; + } + } + function fireCallbacksForOps(group) { + var callbacks = group.delayedCallbacks, + i2 = 0; + do { + for (; i2 < callbacks.length; i2++) { + callbacks[i2].call(null); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } - 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() - ); + } + } while (i2 < callbacks.length); + } + function finishOperation(op, endCb) { + var group = op.ownsGroup; + if (!group) { + return; + } + try { + fireCallbacksForOps(group); + } finally { + operationGroup = null; + endCb(group); + } + } + var orphanDelayedCallbacks = null; + function signalLater(emitter, type) { + var arr = getHandlers(emitter, type); + if (!arr.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2), + list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + var loop = function (i3) { + list.push(function () { + return arr[i3].apply(null, args); }); }; - function isPromise(value) { - return ( - typeof value === "object" && - value !== null && - typeof value.then === "function" - ); + for (var i2 = 0; i2 < arr.length; ++i2) loop(i2); } - function observableToPromise(observable) { - return new Promise((resolve, reject) => { - const subscription = observable.subscribe({ - next(v) { - resolve(v); - subscription.unsubscribe(); - }, - error: reject, - complete() { - reject(new Error("no value resolved")); - }, - }); - }); + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i2 = 0; i2 < delayed.length; ++i2) { + delayed[i2](); + } } - function isObservable(value) { - return ( - typeof value === "object" && - value !== null && - "subscribe" in value && - typeof value.subscribe === "function" - ); + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") { + updateLineText(cm, lineView); + } else if (type == "gutter") { + updateLineGutter(cm, lineView, lineN, dims); + } else if (type == "class") { + updateLineClasses(cm, lineView); + } else if (type == "widget") { + updateLineWidgets(cm, lineView, dims); + } + } + lineView.changes = null; } - function isAsyncIterable(input) { - return ( - typeof input === "object" && - input !== null && - (input[Symbol.toStringTag] === "AsyncGenerator" || - Symbol.asyncIterator in input) - ); + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) { + lineView.text.parentNode.replaceChild(lineView.node, lineView.text); + } + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) { + lineView.node.style.zIndex = 2; + } + } + return lineView.node; } - function asyncIterableToPromise(input) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const iteratorReturn = - (_a = ("return" in input ? input : input[Symbol.asyncIterator]()) - .return) === null || _a === void 0 - ? void 0 - : _a.bind(input); - const iteratorNext = ( - "next" in input ? input : input[Symbol.asyncIterator]() - ).next.bind(input); - const result = yield iteratorNext(); - void (iteratorReturn === null || iteratorReturn === void 0 - ? void 0 - : iteratorReturn()); - return result.value; - }); + function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) { + cls += " CodeMirror-linebackground"; + } + if (lineView.background) { + if (cls) { + lineView.background.className = cls; + } else { + lineView.background.parentNode.removeChild(lineView.background); + lineView.background = null; + } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + cm.display.input.setUneditable(lineView.background); + } + } + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) { + lineView.node = built.pre; + } + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(cm, lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView); + if (lineView.line.wrapClass) { + ensureLineWrapped(lineView).className = lineView.line.wrapClass; + } else if (lineView.node != lineView.text) { + lineView.node.className = ""; + } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px"); + cm.display.input.setUneditable(lineView.gutterBackground); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); + gutterWrap.setAttribute("aria-hidden", "true"); + cm.display.input.setUneditable(gutterWrap); + wrap$1.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) { + gutterWrap.className += " " + lineView.line.gutterClass; + } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { + lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px")); + } + if (markers) { + for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { + var id = cm.display.gutterSpecs[k].className, + found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + } } - function fetcherReturnToPromise(fetcherResult) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield fetcherResult; - if (isAsyncIterable(result)) { - return asyncIterableToPromise(result); + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { + lineView.alignable = null; + } + var isWidget = classTest("CodeMirror-linewidget"); + for (var node = lineView.node.firstChild, next = void 0; node; node = next) { + next = node.nextSibling; + if (isWidget.test(node.className)) { + lineView.node.removeChild(node); } - if (isObservable(result)) { - return observableToPromise(result); + } + insertLineWidgets(cm, lineView, dims); + } + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) { + lineView.bgClass = built.bgClass; + } + if (built.textClass) { + lineView.textClass = built.textClass; + } + updateLineClasses(cm, lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false); } - return result; - }); + } } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js": - /*!******************************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/createFetcher.js ***! - \******************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createGraphiQLFetcher = createGraphiQLFetcher; - var _lib = __webpack_require__( - /*! ./lib */ "../../graphiql-toolkit/esm/create-fetcher/lib.js" - ); - function createGraphiQLFetcher(options) { - let httpFetch; - if (typeof window !== "undefined" && window.fetch) { - httpFetch = window.fetch; - } - if ( - (options === null || options === void 0 - ? void 0 - : options.enableIncrementalDelivery) === null || - options.enableIncrementalDelivery !== false - ) { - options.enableIncrementalDelivery = true; - } - if (options.fetch) { - httpFetch = options.fetch; - } - if (!httpFetch) { - throw new Error("No valid fetcher implementation available"); - } - const simpleFetcher = (0, _lib.createSimpleFetcher)( - options, - httpFetch - ); - const httpFetcher = options.enableIncrementalDelivery - ? (0, _lib.createMultipartFetcher)(options, httpFetch) - : simpleFetcher; - return (graphQLParams, fetcherOpts) => { - if (graphQLParams.operationName === "IntrospectionQuery") { - return (options.schemaFetcher || simpleFetcher)( - graphQLParams, - fetcherOpts - ); + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { + return; + } + var wrap = ensureLineWrapped(lineView); + for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) { + var widget = ws[i2], + node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); + if (!widget.handleMouseEvents) { + node.setAttribute("cm-ignore-events", "true"); + } + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) { + wrap.insertBefore(node, lineView.gutter || lineView.text); + } else { + wrap.appendChild(node); } - const isSubscription = ( - fetcherOpts === null || fetcherOpts === void 0 - ? void 0 - : fetcherOpts.documentAST - ) - ? (0, _lib.isSubscriptionWithName)( - fetcherOpts.documentAST, - graphQLParams.operationName || undefined - ) - : false; - if (isSubscription) { - const wsFetcher = (0, _lib.getWsFetcher)(options, fetcherOpts); - if (!wsFetcher) { - throw new Error( - `Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${ - options.subscriptionUrl - ? `Provided URL ${options.subscriptionUrl} failed` - : "Please provide subscriptionUrl, wsClient or legacyClient option first." - }` - ); - } - return wsFetcher(graphQLParams); + signalLater(widget, "redraw"); + } + } + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; } - return httpFetcher(graphQLParams, fetcherOpts); - }; + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) { + node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/create-fetcher/index.js": - /*!**********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/index.js ***! - \**********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var _exportNames = { - createGraphiQLFetcher: true, - }; - Object.defineProperty(exports, "createGraphiQLFetcher", { - enumerable: true, - get: function () { - return _createFetcher.createGraphiQLFetcher; - }, - }); - var _types = __webpack_require__( - /*! ./types */ "../../graphiql-toolkit/esm/create-fetcher/types.js" - ); - Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _types[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _types[key]; - }, - }); - }); - var _createFetcher = __webpack_require__( - /*! ./createFetcher */ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js" - ); - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/create-fetcher/lib.js": - /*!********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/lib.js ***! - \********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isSubscriptionWithName = - exports.getWsFetcher = - exports.createWebsocketsFetcherFromUrl = - exports.createWebsocketsFetcherFromClient = - exports.createSimpleFetcher = - exports.createMultipartFetcher = - exports.createLegacyWebsocketsFetcher = - void 0; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _meros = __webpack_require__( - /*! meros */ "../../../node_modules/meros/browser/index.js" - ); - var _pushPullAsyncIterableIterator = __webpack_require__( - /*! @n1ru4l/push-pull-async-iterable-iterator */ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js" - ); - var __awaiter = - (void 0 && (void 0).__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); + function widgetHeight(widget) { + if (widget.height != null) { + return widget.height; + } + var cm = widget.doc.cm; + if (!cm) { + return 0; + } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) { + parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + if (widget.noHScroll) { + parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.parentNode.offsetHeight; + } + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) { + return true; + } + } + } + function paddingTop(display) { + return display.lineSpace.offsetTop; + } + function paddingVert(display) { + return display.mover.offsetHeight - display.lineSpace.offsetHeight; + } + function paddingH(display) { + if (display.cachedPaddingH) { + return display.cachedPaddingH; + } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = { + left: parseInt(style.paddingLeft), + right: parseInt(style.paddingRight) + }; + if (!isNaN(data.left) && !isNaN(data.right)) { + display.cachedPaddingH = data; + } + return data; + } + function scrollGap(cm) { + return scrollerGap - cm.display.nativeBarWidth; + } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i2 = 0; i2 < rects.length - 1; i2++) { + var cur = rects[i2], + next = rects[i2 + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) { + heights.push((cur.bottom + next.top) / 2 - rect.top); } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + } + heights.push(rect.bottom - rect.top); + } + } + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) { + return { + map: lineView.measure.map, + cache: lineView.measure.cache + }; + } + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + if (lineView.rest[i2] == line) { + return { + map: lineView.measure.maps[i2], + cache: lineView.measure.caches[i2] + }; } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); + } + for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) { + if (lineNo(lineView.rest[i$12]) > lineN) { + return { + map: lineView.measure.maps[i$12], + cache: lineView.measure.caches[i$12], + before: true + }; } - step( - (generator = generator.apply(thisArg, _arguments || [])).next() - ); - }); - }; - var __await = - (void 0 && (void 0).__await) || - function (v) { - return this instanceof __await - ? ((this.v = v), this) - : new __await(v); + } + } + } + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { + return cm.display.view[findViewIndex(cm, lineN)]; + } + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { + return ext; + } + } + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) { + view = updateExternalMeasurement(cm, line); + } + var info = mapFromLineView(view, line, lineN); + return { + line, + view, + rect: null, + map: info.map, + cache: info.cache, + before: info.before, + hasHeights: false }; - var __asyncValues = - (void 0 && (void 0).__asyncValues) || - function (o) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m - ? m.call(o) - : ((o = - typeof __values === "function" - ? __values(o) - : o[Symbol.iterator]()), - (i = {}), - verb("next"), - verb("throw"), - verb("return"), - (i[Symbol.asyncIterator] = function () { - return this; - }), - i); - function verb(n) { - i[n] = - o[n] && - function (v) { - return new Promise(function (resolve, reject) { - (v = o[n](v)), settle(resolve, reject, v.done, v.value); - }); - }; + } + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { + ch = -1; + } + var key = ch + (bias || ""), + found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) { + prepared.rect = prepared.view.text.getBoundingClientRect(); } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d, - }); - }, reject); + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) { + prepared.cache[key] = found; } + } + return { + left: found.left, + right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom }; - var __asyncGenerator = - (void 0 && (void 0).__asyncGenerator) || - function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return ( - (i = {}), - verb("next"), - verb("throw"), - verb("return"), - (i[Symbol.asyncIterator] = function () { - return this; - }), - i - ); - function verb(n) { - if (g[n]) - i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; + } + var nullRect = { + left: 0, + right: 0, + top: 0, + bottom: 0 + }; + function nodeAndOffsetInLineMap(map2, ch, bias) { + var node, start, end, collapse, mStart, mEnd; + for (var i2 = 0; i2 < map2.length; i2 += 3) { + mStart = map2[i2]; + mEnd = map2[i2 + 1]; + if (ch < mStart) { + start = 0; + end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i2 == map2.length - 3 || ch == mEnd && map2[i2 + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) { + collapse = "right"; + } + } + if (start != null) { + node = map2[i2 + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { + collapse = bias; + } + if (bias == "left" && start == 0) { + while (i2 && map2[i2 - 2] == map2[i2 - 3] && map2[i2 - 1].insertLeft) { + node = map2[(i2 -= 3) + 2]; + collapse = "left"; + } + } + if (bias == "right" && start == mEnd - mStart) { + while (i2 < map2.length - 3 && map2[i2 + 3] == map2[i2 + 4] && !map2[i2 + 5].insertLeft) { + node = map2[(i2 += 3) + 2]; + collapse = "right"; + } + } + break; } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); + } + return { + node, + start, + end, + collapse, + coverStart: mStart, + coverEnd: mEnd + }; + } + function getUsefulRect(rects, bias) { + var rect = nullRect; + if (bias == "left") { + for (var i2 = 0; i2 < rects.length; i2++) { + if ((rect = rects[i2]).left != rect.right) { + break; } } - function step(r) { - r.value instanceof __await - ? Promise.resolve(r.value.v).then(fulfill, reject) - : settle(q[0][2], r); + } else { + for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) { + if ((rect = rects[i$12]).left != rect.right) { + break; + } } - function fulfill(value) { - resume("next", value); + } + return rect; + } + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, + start = place.start, + end = place.end, + collapse = place.collapse; + var rect; + if (node.nodeType == 3) { + for (var i$12 = 0; i$12 < 4; i$12++) { + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { + --start; + } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { + ++end; + } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else { + rect = getUsefulRect(range(node, start, end).getClientRects(), bias); + } + if (rect.left || rect.right || start == 0) { + break; + } + end = start; + start = start - 1; + collapse = "right"; } - function reject(value) { - resume("throw", value); + if (ie && ie_version < 11) { + rect = maybeUpdateRectForZooming(cm.display.measure, rect); } - function settle(f, v) { - if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } else { + if (start > 0) { + collapse = bias = "right"; } - }; - const errorHasCode = (err) => { - return typeof err === "object" && err !== null && "code" in err; - }; - const isSubscriptionWithName = (document, name) => { - let isSubscription = false; - (0, _graphql.visit)(document, { - OperationDefinition(node) { - var _a; - if ( - name === - ((_a = node.name) === null || _a === void 0 - ? void 0 - : _a.value) && - node.operation === "subscription" - ) { - isSubscription = true; - } - }, - }); - return isSubscription; - }; - exports.isSubscriptionWithName = isSubscriptionWithName; - const createSimpleFetcher = - (options, httpFetch) => (graphQLParams, fetcherOpts) => - __awaiter(void 0, void 0, void 0, function* () { - const data = yield httpFetch(options.url, { - method: "POST", - body: JSON.stringify(graphQLParams), - headers: Object.assign( - Object.assign( - { - "content-type": "application/json", - }, - options.headers - ), - fetcherOpts === null || fetcherOpts === void 0 - ? void 0 - : fetcherOpts.headers - ), - }); - return data.json(); - }); - exports.createSimpleFetcher = createSimpleFetcher; - const createWebsocketsFetcherFromUrl = (url, connectionParams) => { - let wsClient; - try { - const { createClient } = __webpack_require__( - /*! graphql-ws */ "../../../node_modules/graphql-ws/lib/index.js" - ); - wsClient = createClient({ - url, - connectionParams, - }); - return createWebsocketsFetcherFromClient(wsClient); - } catch (err) { - if (errorHasCode(err) && err.code === "MODULE_NOT_FOUND") { - throw new Error( - "You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'" - ); + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { + rect = rects[bias == "right" ? rects.length - 1 : 0]; + } else { + rect = node.getBoundingClientRect(); } - console.error(`Error creating websocket client for ${url}`, err); } - }; - exports.createWebsocketsFetcherFromUrl = createWebsocketsFetcherFromUrl; - const createWebsocketsFetcherFromClient = - (wsClient) => (graphQLParams) => - (0, - _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)( - (sink) => - wsClient.subscribe( - graphQLParams, - Object.assign(Object.assign({}, sink), { - error(err) { - if (err instanceof CloseEvent) { - sink.error( - new Error( - `Socket closed with event ${err.code} ${ - err.reason || "" - }`.trim() - ) - ); - } else { - sink.error(err); - } - }, - }) - ) - ); - exports.createWebsocketsFetcherFromClient = - createWebsocketsFetcherFromClient; - const createLegacyWebsocketsFetcher = - (legacyWsClient) => (graphQLParams) => { - const observable = legacyWsClient.request(graphQLParams); - return (0, - _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)( - (sink) => observable.subscribe(sink).unsubscribe - ); + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) { + rect = { + left: rSpan.left, + right: rSpan.left + charWidth(cm.display), + top: rSpan.top, + bottom: rSpan.bottom + }; + } else { + rect = nullRect; + } + } + var rtop = rect.top - prepared.rect.top, + rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + var i2 = 0; + for (; i2 < heights.length - 1; i2++) { + if (mid < heights[i2]) { + break; + } + } + var top = i2 ? heights[i2 - 1] : 0, + bot = heights[i2]; + var result = { + left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top, + bottom: bot }; - exports.createLegacyWebsocketsFetcher = createLegacyWebsocketsFetcher; - const createMultipartFetcher = (options, httpFetch) => - function (graphQLParams, fetcherOpts) { - return __asyncGenerator(this, arguments, function* () { - var e_1, _a; - const response = yield __await( - httpFetch(options.url, { - method: "POST", - body: JSON.stringify(graphQLParams), - headers: Object.assign( - Object.assign( - { - "content-type": "application/json", - accept: "application/json, multipart/mixed", - }, - options.headers - ), - fetcherOpts === null || fetcherOpts === void 0 - ? void 0 - : fetcherOpts.headers - ), - }).then((r) => - (0, _meros.meros)(r, { - multiple: true, - }) - ) - ); - if ( - !(0, _pushPullAsyncIterableIterator.isAsyncIterable)(response) - ) { - return yield __await(yield yield __await(response.json())); + if (!rect.left && !rect.right) { + result.bogus = true; + } + if (!cm.options.singleCursorHeightPerLine) { + result.rtop = rtop; + result.rbottom = rbot; + } + return result; + } + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { + return rect; + } + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return { + left: rect.left * scaleX, + right: rect.right * scaleX, + top: rect.top * scaleY, + bottom: rect.bottom * scaleY + }; + } + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + lineView.measure.caches[i2] = {}; } - try { - for ( - var response_1 = __asyncValues(response), response_1_1; - (response_1_1 = yield __await(response_1.next())), - !response_1_1.done; - - ) { - const chunk = response_1_1.value; - if (chunk.some((part) => !part.json)) { - const message = chunk.map( - (part) => - `Headers::\n${part.headers}\n\nBody::\n${part.body}` - ); - throw new Error( - `Expected multipart chunks to be of json type. got:\n${message}` - ); - } - yield yield __await(chunk.map((part) => part.body)); - } - } catch (e_1_1) { - e_1 = { - error: e_1_1, - }; - } finally { - try { - if ( - response_1_1 && - !response_1_1.done && - (_a = response_1.return) - ) - yield __await(_a.call(response_1)); - } finally { - if (e_1) throw e_1.error; - } + } + } + } + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + clearLineMeasurementCacheFor(cm.display.view[i2]); + } + } + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) { + cm.display.maxLineChanged = true; + } + cm.display.lineNumChars = null; + } + function pageScrollX() { + if (chrome && android) { + return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)); + } + return window.pageXOffset || (document.documentElement || document.body).scrollLeft; + } + function pageScrollY() { + if (chrome && android) { + return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)); + } + return window.pageYOffset || (document.documentElement || document.body).scrollTop; + } + function widgetTopHeight(lineObj) { + var ref = visualLine(lineObj); + var widgets = ref.widgets; + var height = 0; + if (widgets) { + for (var i2 = 0; i2 < widgets.length; ++i2) { + if (widgets[i2].above) { + height += widgetHeight(widgets[i2]); } - }); + } + } + return height; + } + function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj); + rect.top += height; + rect.bottom += height; + } + if (context == "line") { + return rect; + } + if (!context) { + context = "local"; + } + var yOff = heightAtLine(lineObj); + if (context == "local") { + yOff += paddingTop(cm.display); + } else { + yOff -= cm.display.viewOffset; + } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; + rect.right += xOff; + } + rect.top += yOff; + rect.bottom += yOff; + return rect; + } + function fromCoordSystem(cm, coords, context) { + if (context == "div") { + return coords; + } + var left = coords.left, + top = coords.top; + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return { + left: left - lineSpaceBox.left, + top: top - lineSpaceBox.top }; - exports.createMultipartFetcher = createMultipartFetcher; - const getWsFetcher = (options, fetcherOpts) => { - if (options.wsClient) { - return createWebsocketsFetcherFromClient(options.wsClient); - } - if (options.subscriptionUrl) { - return createWebsocketsFetcherFromUrl( - options.subscriptionUrl, - Object.assign( - Object.assign({}, options.wsConnectionParams), - fetcherOpts === null || fetcherOpts === void 0 - ? void 0 - : fetcherOpts.headers - ) - ); + } + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { + lineObj = getLine(cm.doc, pos.line); } - const legacyWebsocketsClient = - options.legacyClient || options.legacyWsClient; - if (legacyWebsocketsClient) { - return createLegacyWebsocketsFetcher(legacyWebsocketsClient); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); } - }; - exports.getWsFetcher = getWsFetcher; - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/create-fetcher/types.js": - /*!**********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/types.js ***! - \**********************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/format/index.js": - /*!**************************************************!*\ - !*** ../../graphiql-toolkit/esm/format/index.js ***! - \**************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.formatError = formatError; - exports.formatResult = formatResult; - function stringify(obj) { - return JSON.stringify(obj, null, 2); - } - function formatSingleError(error) { - return Object.assign(Object.assign({}, error), { - message: error.message, - stack: error.stack, - }); + function get(ch2, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch2, right ? "right" : "left", varHeight); + if (right) { + m.left = m.right; + } else { + m.right = m.left; + } + return intoCoordSystem(cm, lineObj, m, context); + } + var order = getOrder(lineObj, cm.doc.direction), + ch = pos.ch, + sticky = pos.sticky; + if (ch >= lineObj.text.length) { + ch = lineObj.text.length; + sticky = "before"; + } else if (ch <= 0) { + ch = 0; + sticky = "after"; + } + if (!order) { + return get(sticky == "before" ? ch - 1 : ch, sticky == "before"); + } + function getBidi(ch2, partPos2, invert) { + var part = order[partPos2], + right = part.level == 1; + return get(invert ? ch2 - 1 : ch2, right != invert); + } + var partPos = getBidiPartAt(order, ch, sticky); + var other = bidiOther; + var val = getBidi(ch, partPos, sticky == "before"); + if (other != null) { + val.other = getBidi(ch, other, sticky != "before"); + } + return val; } - function handleSingleError(error) { - if (error instanceof Error) { - return formatSingleError(error); + function estimateCoords(cm, pos) { + var left = 0; + pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) { + left = charWidth(cm.display) * pos.ch; } - return error; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return { + left, + right: left, + top, + bottom: top + lineObj.height + }; } - function formatError(error) { - if (Array.isArray(error)) { - return stringify({ - errors: error.map((e) => handleSingleError(e)), - }); + function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky); + pos.xRel = xRel; + if (outside) { + pos.outside = outside; } - return stringify({ - errors: [handleSingleError(error)], - }); + return pos; } - function formatResult(result) { - return stringify(result); + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) { + return PosWithInfo(doc.first, 0, null, -1, -1); + } + var lineN = lineAtHeight(doc, y), + last = doc.first + doc.size - 1; + if (lineN > last) { + return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1); + } + if (x < 0) { + x = 0; + } + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); + if (!collapsed) { + return found; + } + var rangeEnd = collapsed.find(1); + if (rangeEnd.line == lineN) { + return rangeEnd; + } + lineObj = getLine(doc, lineN = rangeEnd.line); + } + } + function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj); + var end = lineObj.text.length; + var begin = findFirst(function (ch) { + return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; + }, end, 0); + end = findFirst(function (ch) { + return measureCharPrepared(cm, preparedMeasure, ch).top > y; + }, begin, end); + return { + begin, + end + }; } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js": - /*!*******************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js ***! - \*******************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.fillLeafs = fillLeafs; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function fillLeafs(schema, docString, getDefaultFieldNames) { - const insertions = []; - if (!schema || !docString) { - return { - insertions, - result: docString, + function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop); + } + function boxIsAfter(box, x, y, left) { + return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x; + } + function coordsCharInner(cm, lineObj, lineNo2, x, y) { + y -= heightAtLine(lineObj); + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + var widgetHeight2 = widgetTopHeight(lineObj); + var begin = 0, + end = lineObj.text.length, + ltr = true; + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x, y); + ltr = part.level != 1; + begin = ltr ? part.from : part.to - 1; + end = ltr ? part.to : part.from - 1; + } + var chAround = null, + boxAround = null; + var ch = findFirst(function (ch2) { + var box = measureCharPrepared(cm, preparedMeasure, ch2); + box.top += widgetHeight2; + box.bottom += widgetHeight2; + if (!boxIsAfter(box, x, y, false)) { + return false; + } + if (box.top <= y && box.left <= x) { + chAround = ch2; + boxAround = box; + } + return true; + }, begin, end); + var baseX, + sticky, + outside = false; + if (boxAround) { + var atLeft = x - boxAround.left < boxAround.right - x, + atStart = atLeft == ltr; + ch = chAround + (atStart ? 0 : 1); + sticky = atStart ? "after" : "before"; + baseX = atLeft ? boxAround.left : boxAround.right; + } else { + if (!ltr && (ch == end || ch == begin)) { + ch++; + } + sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y == ltr ? "after" : "before"; + var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure); + baseX = coords.left; + outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + } + ch = skipExtendingChars(lineObj.text, ch, 1); + return PosWithInfo(lineNo2, ch, sticky, outside, x - baseX); + } + function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x, y) { + var index = findFirst(function (i2) { + var part2 = order[i2], + ltr2 = part2.level != 1; + return boxIsAfter(cursorCoords(cm, Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true); + }, 0, order.length - 1); + var part = order[index]; + if (index > 0) { + var ltr = part.level != 1; + var start = cursorCoords(cm, Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); + if (boxIsAfter(start, x, y, true) && start.top > y) { + part = order[index - 1]; + } + } + return part; + } + function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { + end--; + } + var part = null, + closestDist = null; + for (var i2 = 0; i2 < order.length; i2++) { + var p = order[i2]; + if (p.from >= end || p.to <= begin) { + continue; + } + var ltr = p.level != 1; + var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; + var dist = endX < x ? x - endX + 1e9 : endX - x; + if (!part || closestDist > dist) { + part = p; + closestDist = dist; + } + } + if (!part) { + part = order[order.length - 1]; + } + if (part.from < begin) { + part = { + from: begin, + to: part.to, + level: part.level }; } - let ast; - try { - ast = (0, _graphql.parse)(docString); - } catch (_a) { - return { - insertions, - result: docString, + if (part.to > end) { + part = { + from: part.from, + to: end, + level: part.level }; } - const fieldNameFn = - getDefaultFieldNames || defaultGetDefaultFieldNames; - const typeInfo = new _graphql.TypeInfo(schema); - (0, _graphql.visit)(ast, { - leave(node) { - typeInfo.leave(node); - }, - enter(node) { - typeInfo.enter(node); - if (node.kind === "Field" && !node.selectionSet) { - const fieldType = typeInfo.getType(); - const selectionSet = buildSelectionSet( - isFieldType(fieldType), - fieldNameFn - ); - if (selectionSet && node.loc) { - const indent = getIndentation(docString, node.loc.start); - insertions.push({ - index: node.loc.end, - string: - " " + - (0, _graphql.print)(selectionSet).replaceAll( - "\n", - "\n" + indent - ), - }); + return part; + } + var measureText; + function textHeight(display) { + if (display.cachedTextHeight != null) { + return display.cachedTextHeight; + } + if (measureText == null) { + measureText = elt("pre", null, "CodeMirror-line-like"); + for (var i2 = 0; i2 < 49; ++i2) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) { + display.cachedTextHeight = height; + } + removeChildren(display.measure); + return height || 1; + } + function charWidth(display) { + if (display.cachedCharWidth != null) { + return display.cachedCharWidth; + } + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor], "CodeMirror-line-like"); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), + width = (rect.right - rect.left) / 10; + if (width > 2) { + display.cachedCharWidth = width; + } + return width || 10; + } + function getDimensions(cm) { + var d = cm.display, + left = {}, + width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) { + var id = cm.display.gutterSpecs[i2].className; + left[id] = n.offsetLeft + n.clientLeft + gutterLeft; + width[id] = n.clientWidth; + } + return { + fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth + }; + } + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + function estimateHeight(cm) { + var th = textHeight(cm.display), + wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) { + return 0; + } + var widgetsHeight = 0; + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].height) { + widgetsHeight += line.widgets[i2].height; } } - }, - }); - return { - insertions, - result: withInsertions(docString, insertions), + } + if (wrapping) { + return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + } else { + return widgetsHeight + th; + } }; } - function defaultGetDefaultFieldNames(type) { - if (!("getFields" in type)) { - return []; + function estimateLineHeights(cm) { + var doc = cm.doc, + est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + }); + } + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { + return null; + } + var x, + y, + space = display.lineSpace.getBoundingClientRect(); + try { + x = e.clientX - space.left; + y = e.clientY - space.top; + } catch (e$1) { + return null; } - const fields = type.getFields(); - if (fields.id) { - return ["id"]; + var coords = coordsChar(cm, x, y), + line; + if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); } - if (fields.edges) { - return ["edges"]; + return coords; + } + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { + return null; } - if (fields.node) { - return ["node"]; + n -= cm.display.viewFrom; + if (n < 0) { + return null; } - const leafFieldNames = []; - for (const fieldName of Object.keys(fields)) { - if ((0, _graphql.isLeafType)(fields[fieldName].type)) { - leafFieldNames.push(fieldName); + var view = cm.display.view; + for (var i2 = 0; i2 < view.length; i2++) { + n -= view[i2].size; + if (n < 0) { + return i2; } } - return leafFieldNames; } - function buildSelectionSet(type, getDefaultFieldNames) { - const namedType = (0, _graphql.getNamedType)(type); - if (!type || (0, _graphql.isLeafType)(type)) { - return; + function regChange(cm, from, to, lendiff) { + if (from == null) { + from = cm.doc.first; } - const fieldNames = getDefaultFieldNames(namedType); - if ( - !Array.isArray(fieldNames) || - fieldNames.length === 0 || - !("getFields" in namedType) - ) { - return; + if (to == null) { + to = cm.doc.first + cm.doc.size; } - return { - kind: _graphql.Kind.SELECTION_SET, - selections: fieldNames.map((fieldName) => { - const fieldDef = namedType.getFields()[fieldName]; - const fieldType = fieldDef ? fieldDef.type : null; - return { - kind: _graphql.Kind.FIELD, - name: { - kind: _graphql.Kind.NAME, - value: fieldName, - }, - selectionSet: buildSelectionSet( - fieldType, - getDefaultFieldNames - ), - }; - }), - }; - } - function withInsertions(initial, insertions) { - if (insertions.length === 0) { - return initial; - } - let edited = ""; - let prevIndex = 0; - for (const { index, string } of insertions) { - edited += initial.slice(prevIndex, index) + string; - prevIndex = index; - } - edited += initial.slice(prevIndex); - return edited; - } - function getIndentation(str, index) { - let indentStart = index; - let indentEnd = index; - while (indentStart) { - const c = str.charCodeAt(indentStart - 1); - if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { - break; + if (!lendiff) { + lendiff = 0; + } + var display = cm.display; + if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { + display.updateLineNumbers = from; + } + cm.curOp.viewChanged = true; + if (from >= display.viewTo) { + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { + resetView(cm); + } + } else if (to <= display.viewFrom) { + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { + resetView(cm); + } else if (from <= display.viewFrom) { + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { + var cut$1 = viewCuttingPoint(cm, from, from, -1); + if (cut$1) { + display.view = display.view.slice(0, cut$1.index); + display.viewTo = cut$1.lineN; + } else { + resetView(cm); + } + } else { + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); } - indentStart--; - if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { - indentEnd = indentStart; + } + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) { + ext.lineN += lendiff; + } else if (from < ext.lineN + ext.size) { + display.externalMeasured = null; } } - return str.slice(indentStart, indentEnd); } - function isFieldType(fieldType) { - if (fieldType) { - return fieldType; + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, + ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { + display.externalMeasured = null; + } + if (line < display.viewFrom || line >= display.viewTo) { + return; + } + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) { + return; + } + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) { + arr.push(type); } } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/index.js": - /*!***********************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/index.js ***! - \***********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var _autoComplete = __webpack_require__( - /*! ./auto-complete */ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js" - ); - Object.keys(_autoComplete).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _autoComplete[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _autoComplete[key]; - }, - }); - }); - var _mergeAst = __webpack_require__( - /*! ./merge-ast */ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js" - ); - Object.keys(_mergeAst).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _mergeAst[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _mergeAst[key]; - }, - }); - }); - var _operationName = __webpack_require__( - /*! ./operation-name */ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js" - ); - Object.keys(_operationName).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _operationName[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _operationName[key]; - }, - }); - }); - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js": - /*!***************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js ***! - \***************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.mergeAst = mergeAst; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function uniqueBy(array, iteratee) { - var _a; - const FilteredMap = new Map(); - const result = []; - for (const item of array) { - if (item.kind === "Field") { - const uniqueValue = iteratee(item); - const existing = FilteredMap.get(uniqueValue); - if ( - (_a = item.directives) === null || _a === void 0 - ? void 0 - : _a.length - ) { - const itemClone = Object.assign({}, item); - result.push(itemClone); - } else if ( - (existing === null || existing === void 0 - ? void 0 - : existing.selectionSet) && - item.selectionSet - ) { - existing.selectionSet.selections = [ - ...existing.selectionSet.selections, - ...item.selectionSet.selections, - ]; - } else if (!existing) { - const itemClone = Object.assign({}, item); - FilteredMap.set(uniqueValue, itemClone); - result.push(itemClone); + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), + diff, + view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { + return { + index, + lineN: newN + }; + } + var n = cm.display.viewFrom; + for (var i2 = 0; i2 < index; i2++) { + n += view[i2].size; + } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { + return null; } + diff = n + view[index].size - oldN; + index++; } else { - result.push(item); + diff = n - oldN; + } + oldN += diff; + newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { + return null; + } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return { + index, + lineN: newN + }; + } + function adjustView(cm, from, to) { + var display = cm.display, + view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) { + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); + } else if (display.viewFrom < from) { + display.view = display.view.slice(findViewIndex(cm, from)); + } + display.viewFrom = from; + if (display.viewTo < to) { + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); + } else if (display.viewTo > to) { + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + } + display.viewTo = to; + } + function countDirtyView(cm) { + var view = cm.display.view, + dirty = 0; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) { + ++dirty; + } + } + return dirty; + } + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + function prepareSelection(cm, primary) { + if (primary === void 0) primary = true; + var doc = cm.doc, + result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + var customCursor = cm.options.$customCursor; + if (customCursor) { + primary = true; + } + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + if (!primary && i2 == doc.sel.primIndex) { + continue; + } + var range2 = doc.sel.ranges[i2]; + if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) { + continue; + } + var collapsed = range2.empty(); + if (customCursor) { + var head = customCursor(cm, range2); + if (head) { + drawSelectionCursor(cm, head, curFragment); + } + } else if (collapsed || cm.options.showCursorWhenSelecting) { + drawSelectionCursor(cm, range2.head, curFragment); + } + if (!collapsed) { + drawSelectionRange(cm, range2, selFragment); } } return result; } - function inlineRelevantFragmentSpreads( - fragmentDefinitions, - selections, - selectionSetType - ) { - var _a; - const selectionSetTypeName = selectionSetType - ? (0, _graphql.getNamedType)(selectionSetType).name - : null; - const outputSelections = []; - const seenSpreads = []; - for (let selection of selections) { - if (selection.kind === "FragmentSpread") { - const fragmentName = selection.name.value; - if (!selection.directives || selection.directives.length === 0) { - if (seenSpreads.includes(fragmentName)) { - continue; + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + var cursor = output.appendChild(elt("div", " ", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { + var charPos = charCoords(cm, head, "div", null, null); + var width = charPos.right - charPos.left; + cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; + } + if (pos.other) { + var otherCursor = output.appendChild(elt("div", " ", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px"; + } + } + function cmpCoords(a, b) { + return a.top - b.top || a.left - b.left; + } + function drawSelectionRange(cm, range2, output) { + var display = cm.display, + doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), + leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + var docLTR = doc.direction == "ltr"; + function add(left, top, width, bottom) { + if (top < 0) { + top = 0; + } + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")); + } + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos); + var prop2 = dir == "ltr" == (side == "after") ? "left" : "right"; + var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); + return coords(ch, prop2)[prop2]; + } + var order = getOrder(lineObj, doc.direction); + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i2) { + var ltr = dir == "ltr"; + var fromPos = coords(from, ltr ? "left" : "right"); + var toPos = coords(to - 1, ltr ? "right" : "left"); + var openStart = fromArg == null && from == 0, + openEnd = toArg == null && to == lineLen; + var first = i2 == 0, + last = !order || i2 == order.length - 1; + if (toPos.top - fromPos.top <= 3) { + var openLeft = (docLTR ? openStart : openEnd) && first; + var openRight = (docLTR ? openEnd : openStart) && last; + var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; + var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; + add(left, fromPos.top, right - left, fromPos.bottom); + } else { + var topLeft, topRight, botLeft, botRight; + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left; + topRight = docLTR ? rightSide : wrapX(from, dir, "before"); + botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); + botRight = docLTR && openEnd && last ? rightSide : toPos.right; } else { - seenSpreads.push(fragmentName); + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); + topRight = !docLTR && openStart && first ? rightSide : fromPos.right; + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; + botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); + if (fromPos.bottom < toPos.top) { + add(leftSide, fromPos.bottom, null, toPos.top); + } + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); } - const fragmentDefinition = - fragmentDefinitions[selection.name.value]; - if (fragmentDefinition) { - const { typeCondition, directives, selectionSet } = - fragmentDefinition; - selection = { - kind: _graphql.Kind.INLINE_FRAGMENT, - typeCondition, - directives, - selectionSet, - }; + if (!start || cmpCoords(fromPos, start) < 0) { + start = fromPos; } - } - if ( - selection.kind === _graphql.Kind.INLINE_FRAGMENT && - (!selection.directives || - ((_a = selection.directives) === null || _a === void 0 - ? void 0 - : _a.length) === 0) - ) { - const fragmentTypeName = selection.typeCondition - ? selection.typeCondition.name.value - : null; - if ( - !fragmentTypeName || - fragmentTypeName === selectionSetTypeName - ) { - outputSelections.push( - ...inlineRelevantFragmentSpreads( - fragmentDefinitions, - selection.selectionSet.selections, - selectionSetType - ) - ); - continue; + if (cmpCoords(toPos, start) < 0) { + start = toPos; + } + if (!end || cmpCoords(fromPos, end) < 0) { + end = fromPos; + } + if (cmpCoords(toPos, end) < 0) { + end = toPos; + } + }); + return { + start, + end + }; + } + var sFrom = range2.from(), + sTo = range2.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), + toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } - outputSelections.push(selection); + if (leftEnd.bottom < rightStart.top) { + add(leftSide, leftEnd.bottom, null, rightStart.top); + } + } + output.appendChild(fragment); + } + function restartBlink(cm) { + if (!cm.state.focused) { + return; + } + var display = cm.display; + clearInterval(display.blinker); + var on2 = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function () { + if (!cm.hasFocus()) { + onBlur(cm); + } + display.cursorDiv.style.visibility = (on2 = !on2) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) { + display.cursorDiv.style.visibility = "hidden"; } - return outputSelections; } - function mergeAst(documentAST, schema) { - const typeInfo = schema ? new _graphql.TypeInfo(schema) : null; - const fragmentDefinitions = Object.create(null); - for (const definition of documentAST.definitions) { - if (definition.kind === _graphql.Kind.FRAGMENT_DEFINITION) { - fragmentDefinitions[definition.name.value] = definition; + function ensureFocus(cm) { + if (!cm.hasFocus()) { + cm.display.input.focus(); + if (!cm.state.focused) { + onFocus(cm); } } - const flattenVisitors = { - SelectionSet(node) { - const selectionSetType = typeInfo - ? typeInfo.getParentType() - : null; - let { selections } = node; - selections = inlineRelevantFragmentSpreads( - fragmentDefinitions, - selections, - selectionSetType - ); - return Object.assign(Object.assign({}, node), { - selections, - }); - }, - FragmentDefinition() { - return null; - }, - }; - const flattenedAST = (0, _graphql.visit)( - documentAST, - typeInfo - ? (0, _graphql.visitWithTypeInfo)(typeInfo, flattenVisitors) - : flattenVisitors - ); - const deduplicateVisitors = { - SelectionSet(node) { - let { selections } = node; - selections = uniqueBy(selections, (selection) => - selection.alias ? selection.alias.value : selection.name.value - ); - return Object.assign(Object.assign({}, node), { - selections, - }); - }, - FragmentDefinition() { - return null; - }, - }; - return (0, _graphql.visit)(flattenedAST, deduplicateVisitors); } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js": - /*!********************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/operation-name.js ***! - \********************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getSelectedOperationName = getSelectedOperationName; - function getSelectedOperationName( - prevOperations, - prevSelectedOperationName, - operations - ) { - if (!operations || operations.length < 1) { + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + if (cm.state.focused) { + onBlur(cm); + } + } + }, 100); + } + function onFocus(cm, e) { + if (cm.state.delayingBlurEvent && !cm.state.draggingText) { + cm.state.delayingBlurEvent = false; + } + if (cm.options.readOnly == "nocursor") { return; } - const names = operations.map((op) => { - var _a; - return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; - }); - if ( - prevSelectedOperationName && - names.includes(prevSelectedOperationName) - ) { - return prevSelectedOperationName; - } - if (prevSelectedOperationName && prevOperations) { - const prevNames = prevOperations.map((op) => { - var _a; - return (_a = op.name) === null || _a === void 0 - ? void 0 - : _a.value; - }); - const prevIndex = prevNames.indexOf(prevSelectedOperationName); - if (prevIndex !== -1 && prevIndex < names.length) { - return names[prevIndex]; + if (!cm.state.focused) { + signal(cm, "focus", cm, e); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) { + setTimeout(function () { + return cm.display.input.reset(true); + }, 20); + } } + cm.display.input.receivedFocus(); } - return names[0]; - } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/index.js": - /*!*******************************************!*\ - !*** ../../graphiql-toolkit/esm/index.js ***! - \*******************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var _asyncHelpers = __webpack_require__( - /*! ./async-helpers */ "../../graphiql-toolkit/esm/async-helpers/index.js" - ); - Object.keys(_asyncHelpers).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _asyncHelpers[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _asyncHelpers[key]; - }, - }); - }); - var _createFetcher = __webpack_require__( - /*! ./create-fetcher */ "../../graphiql-toolkit/esm/create-fetcher/index.js" - ); - Object.keys(_createFetcher).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _createFetcher[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _createFetcher[key]; - }, - }); - }); - var _format = __webpack_require__( - /*! ./format */ "../../graphiql-toolkit/esm/format/index.js" - ); - Object.keys(_format).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _format[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _format[key]; - }, - }); - }); - var _graphqlHelpers = __webpack_require__( - /*! ./graphql-helpers */ "../../graphiql-toolkit/esm/graphql-helpers/index.js" - ); - Object.keys(_graphqlHelpers).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _graphqlHelpers[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _graphqlHelpers[key]; - }, - }); - }); - var _storage = __webpack_require__( - /*! ./storage */ "../../graphiql-toolkit/esm/storage/index.js" - ); - Object.keys(_storage).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _storage[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _storage[key]; - }, - }); - }); - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/storage/base.js": - /*!**************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/base.js ***! - \**************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.StorageAPI = void 0; - function isQuotaError(storage, e) { - return ( - e instanceof DOMException && - (e.code === 22 || - e.code === 1014 || - e.name === "QuotaExceededError" || - e.name === "NS_ERROR_DOM_QUOTA_REACHED") && - storage.length !== 0 - ); + restartBlink(cm); } - class StorageAPI { - constructor(storage) { - if (storage) { - this.storage = storage; - } else if (storage === null) { - this.storage = null; - } else if (typeof window === "undefined") { - this.storage = null; + function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { + return; + } + if (cm.state.focused) { + signal(cm, "blur", cm, e); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () { + if (!cm.state.focused) { + cm.display.shift = false; + } + }, 150); + } + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); + var oldHeight = display.lineDiv.getBoundingClientRect().top; + var mustScroll = 0; + for (var i2 = 0; i2 < display.view.length; i2++) { + var cur = display.view[i2], + wrapping = cm.options.lineWrapping; + var height = void 0, + width = 0; + if (cur.hidden) { + continue; + } + oldHeight += cur.line.height; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; } else { - this.storage = { - getItem: localStorage.getItem.bind(localStorage), - setItem: localStorage.setItem.bind(localStorage), - removeItem: localStorage.removeItem.bind(localStorage), - get length() { - let keys = 0; - for (const key in localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - keys += 1; - } - } - return keys; - }, - clear() { - for (const key in localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - localStorage.removeItem(key); - } - } - }, - }; + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + if (!wrapping && cur.text.firstChild) { + width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; + } } - } - get(name) { - if (!this.storage) { - return null; + var diff = cur.line.height - height; + if (diff > 5e-3 || diff < -5e-3) { + if (oldHeight < viewTop) { + mustScroll -= diff; + } + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) { + updateWidgetHeight(cur.rest[j]); + } + } } - const key = `${STORAGE_NAMESPACE}:${name}`; - const value = this.storage.getItem(key); - if (value === "null" || value === "undefined") { - this.storage.removeItem(key); - return null; + if (width > cm.display.sizerWidth) { + var chWidth = Math.ceil(width / charWidth(cm.display)); + if (chWidth > cm.display.maxLineLength) { + cm.display.maxLineLength = chWidth; + cm.display.maxLine = cur.line; + cm.display.maxLineChanged = true; + } } - return value || null; } - set(name, value) { - let quotaError = false; - let error = null; - if (this.storage) { - const key = `${STORAGE_NAMESPACE}:${name}`; - if (value) { - try { - this.storage.setItem(key, value); - } catch (e) { - error = e instanceof Error ? e : new Error(`${e}`); - quotaError = isQuotaError(this.storage, e); - } - } else { - this.storage.removeItem(key); + if (Math.abs(mustScroll) > 2) { + display.scroller.scrollTop += mustScroll; + } + } + function updateWidgetHeight(line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; ++i2) { + var w = line.widgets[i2], + parent = w.node.parentNode; + if (parent) { + w.height = parent.offsetHeight; } } - return { - isQuotaError: quotaError, - error, - }; } - clear() { - if (this.storage) { - this.storage.clear(); + } + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + var from = lineAtHeight(doc, top), + to = lineAtHeight(doc, bottom); + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, + ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; } } - } - exports.StorageAPI = StorageAPI; - const STORAGE_NAMESPACE = "graphiql"; - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/storage/custom.js": - /*!****************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/custom.js ***! - \****************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.createLocalStorage = createLocalStorage; - function createLocalStorage({ namespace }) { - const storageKeyPrefix = `${namespace}:`; - const getStorageKey = (key) => `${storageKeyPrefix}${key}`; - const storage = { - setItem: (key, value) => - localStorage.setItem(getStorageKey(key), value), - getItem: (key) => localStorage.getItem(getStorageKey(key)), - removeItem: (key) => localStorage.removeItem(getStorageKey(key)), - get length() { - let keys = 0; - for (const key in localStorage) { - if (key.indexOf(storageKeyPrefix) === 0) { - keys += 1; - } - } - return keys; - }, - clear() { - for (const key in localStorage) { - if (key.indexOf(storageKeyPrefix) === 0) { - localStorage.removeItem(key); - } - } - }, + return { + from, + to: Math.max(to, from + 1) }; - return storage; } - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/storage/history.js": - /*!*****************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/history.js ***! - \*****************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.HistoryStore = void 0; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _query = __webpack_require__( - /*! ./query */ "../../graphiql-toolkit/esm/storage/query.js" - ); - const MAX_QUERY_SIZE = 100000; - class HistoryStore { - constructor(storage, maxHistoryLength) { - this.storage = storage; - this.maxHistoryLength = maxHistoryLength; - this.updateHistory = ({ - query, - variables, - headers, - operationName, - }) => { - if ( - !this.shouldSaveQuery( - query, - variables, - headers, - this.history.fetchRecent() - ) - ) { - return; - } - this.history.push({ - query, - variables, - headers, - operationName, - }); - const historyQueries = this.history.items; - const favoriteQueries = this.favorite.items; - this.queries = historyQueries.concat(favoriteQueries); + function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { + return; + } + var display = cm.display, + box = display.sizer.getBoundingClientRect(), + doScroll = null; + if (rect.top + box.top < 0) { + doScroll = true; + } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { + doScroll = false; + } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "​", null, "position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { + margin = 0; + } + var rect; + if (!cm.options.lineWrapping && pos == end) { + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; + } + for (var limit = 0; limit < 5; limit++) { + var changed = false; + var coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + rect = { + left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin }; - this.deleteHistory = ( - { query, variables, headers, operationName, favorite }, - clearFavorites = false - ) => { - function deleteFromStore(store) { - const found = store.items.find( - (x) => - x.query === query && - x.variables === variables && - x.headers === headers && - x.operationName === operationName - ); - if (found) { - store.delete(found); - } - } - if (favorite || clearFavorites) { - deleteFromStore(this.favorite); - } - if (!favorite || clearFavorites) { - deleteFromStore(this.history); + var scrollPos = calculateScrollPos(cm, rect); + var startTop = cm.doc.scrollTop, + startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { + changed = true; } - this.queries = [...this.history.items, ...this.favorite.items]; - }; - this.history = new _query.QueryStore( - "queries", - this.storage, - this.maxHistoryLength - ); - this.favorite = new _query.QueryStore( - "favorites", - this.storage, - null - ); - this.queries = [ - ...this.history.fetchAll(), - ...this.favorite.fetchAll(), - ]; - } - shouldSaveQuery(query, variables, headers, lastQuerySaved) { - if (!query) { - return false; - } - try { - (0, _graphql.parse)(query); - } catch (_a) { - return false; - } - if (query.length > MAX_QUERY_SIZE) { - return false; - } - if (!lastQuerySaved) { - return true; } - if ( - JSON.stringify(query) === JSON.stringify(lastQuerySaved.query) - ) { - if ( - JSON.stringify(variables) === - JSON.stringify(lastQuerySaved.variables) - ) { - if ( - JSON.stringify(headers) === - JSON.stringify(lastQuerySaved.headers) - ) { - return false; - } - if (headers && !lastQuerySaved.headers) { - return false; - } - } - if (variables && !lastQuerySaved.variables) { - return false; + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { + changed = true; } } - return true; + if (!changed) { + break; + } } - toggleFavorite({ - query, - variables, - headers, - operationName, - label, - favorite, - }) { - const item = { - query, - variables, - headers, - operationName, - label, - }; - if (favorite) { - item.favorite = false; - this.favorite.delete(item); - this.history.push(item); - } else { - item.favorite = true; - this.favorite.push(item); - this.history.delete(item); - } - this.queries = [...this.history.items, ...this.favorite.items]; - } - editLabel( - { query, variables, headers, operationName, label, favorite }, - index - ) { - const item = { - query, - variables, - headers, - operationName, - label, - }; - if (favorite) { - this.favorite.edit( - Object.assign(Object.assign({}, item), { - favorite, - }), - index - ); - } else { - this.history.edit(item, index); + return rect; + } + function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect); + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + } + } + function calculateScrollPos(cm, rect) { + var display = cm.display, + snapMargin = textHeight(cm.display); + if (rect.top < 0) { + rect.top = 0; + } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen2 = displayHeight(cm), + result = {}; + if (rect.bottom - rect.top > screen2) { + rect.bottom = rect.top + screen2; + } + var docBottom = cm.doc.height + paddingVert(display); + var atTop = rect.top < snapMargin, + atBottom = rect.bottom > docBottom - snapMargin; + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top; + } else if (rect.bottom > screentop + screen2) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2); + if (newTop != screentop) { + result.scrollTop = newTop; } - this.queries = [...this.history.items, ...this.favorite.items]; } + var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; + var screenw = displayWidth(cm) - display.gutters.offsetWidth; + var tooWide = rect.right - rect.left > screenw; + if (tooWide) { + rect.right = rect.left + screenw; + } + if (rect.left < 10) { + result.scrollLeft = 0; + } else if (rect.left < screenleft) { + result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); + } else if (rect.right > screenw + screenleft - 3) { + result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; + } + return result; } - exports.HistoryStore = HistoryStore; - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/storage/index.js": - /*!***************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/index.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var _base = __webpack_require__( - /*! ./base */ "../../graphiql-toolkit/esm/storage/base.js" - ); - Object.keys(_base).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _base[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _base[key]; - }, - }); - }); - var _history = __webpack_require__( - /*! ./history */ "../../graphiql-toolkit/esm/storage/history.js" - ); - Object.keys(_history).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _history[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _history[key]; - }, + function addToScrollTop(cm, top) { + if (top == null) { + return; + } + resolveScrollToPos(cm); + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(); + cm.curOp.scrollToPos = { + from: cur, + to: cur, + margin: cm.options.cursorScrollMargin + }; + } + function scrollToCoords(cm, x, y) { + if (x != null || y != null) { + resolveScrollToPos(cm); + } + if (x != null) { + cm.curOp.scrollLeft = x; + } + if (y != null) { + cm.curOp.scrollTop = y; + } + } + function scrollToRange(cm, range2) { + resolveScrollToPos(cm); + cm.curOp.scrollToPos = range2; + } + function resolveScrollToPos(cm) { + var range2 = cm.curOp.scrollToPos; + if (range2) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range2.from), + to = estimateCoords(cm, range2.to); + scrollToCoordsRange(cm, from, to, range2.margin); + } + } + function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin }); - }); - var _query = __webpack_require__( - /*! ./query */ "../../graphiql-toolkit/esm/storage/query.js" - ); - Object.keys(_query).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _query[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _query[key]; - }, + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); + } + function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { + return; + } + if (!gecko) { + updateDisplaySimple(cm, { + top: val + }); + } + setScrollTop(cm, val, true); + if (gecko) { + updateDisplaySimple(cm); + } + startWorker(cm, 100); + } + function setScrollTop(cm, val, forceScroll) { + val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); + if (cm.display.scroller.scrollTop == val && !forceScroll) { + return; + } + cm.doc.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (cm.display.scroller.scrollTop != val) { + cm.display.scroller.scrollTop = val; + } + } + function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { + return; + } + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) { + cm.display.scroller.scrollLeft = val; + } + cm.display.scrollbars.setScrollLeft(val); + } + function measureForScrollbars(cm) { + var d = cm.display, + gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, + clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + }; + } + var NativeScrollbars = function (place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + vert.tabIndex = horiz.tabIndex = -1; + place(vert); + place(horiz); + on(vert, "scroll", function () { + if (vert.clientHeight) { + scroll(vert.scrollTop, "vertical"); + } }); - }); - var _custom = __webpack_require__( - /*! ./custom */ "../../graphiql-toolkit/esm/storage/custom.js" - ); - Object.keys(_custom).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _custom[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _custom[key]; - }, + on(horiz, "scroll", function () { + if (horiz.clientWidth) { + scroll(horiz.scrollLeft, "horizontal"); + } }); - }); - - /***/ - }, - - /***/ "../../graphiql-toolkit/esm/storage/query.js": - /*!***************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/query.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.QueryStore = void 0; - class QueryStore { - constructor(key, storage, maxSize = null) { - this.key = key; - this.storage = storage; - this.maxSize = maxSize; - this.items = this.fetchAll(); + this.checkedZeroWidth = false; + if (ie && ie_version < 8) { + this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } - get length() { - return this.items.length; - } - contains(item) { - return this.items.some( - (x) => - x.query === item.query && - x.variables === item.variables && - x.headers === item.headers && - x.operationName === item.operationName - ); + }; + NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.scrollTop = 0; + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; } - edit(item, index) { - if (typeof index === "number" && this.items[index]) { - const found = this.items[index]; - if ( - found.query === item.query && - found.variables === item.variables && - found.headers === item.headers && - found.operationName === item.operationName - ) { - this.items.splice(index, 1, item); - this.save(); - return; - } + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { + this.zeroWidthHack(); } - const itemIndex = this.items.findIndex( - (x) => - x.query === item.query && - x.variables === item.variables && - x.headers === item.headers && - x.operationName === item.operationName - ); - if (itemIndex !== -1) { - this.items.splice(itemIndex, 1, item); - this.save(); - } - } - delete(item) { - const itemIndex = this.items.findIndex( - (x) => - x.query === item.query && - x.variables === item.variables && - x.headers === item.headers && - x.operationName === item.operationName - ); - if (itemIndex !== -1) { - this.items.splice(itemIndex, 1); - this.save(); + this.checkedZeroWidth = true; + } + return { + right: needsV ? sWidth : 0, + bottom: needsH ? sWidth : 0 + }; + }; + NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { + this.horiz.scrollLeft = pos; + } + if (this.disableHoriz) { + this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); + } + }; + NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { + this.vert.scrollTop = pos; + } + if (this.disableVert) { + this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); + } + }; + NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; + this.disableHoriz = new Delayed(); + this.disableVert = new Delayed(); + }; + NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { + bar.style.pointerEvents = "auto"; + function maybeDisable() { + var box = bar.getBoundingClientRect(); + var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); + if (elt2 != bar) { + bar.style.pointerEvents = "none"; + } else { + delay.set(1e3, maybeDisable); } } - fetchRecent() { - return this.items.at(-1); + delay.set(1e3, maybeDisable); + }; + NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + }; + var NullScrollbars = function () {}; + NullScrollbars.prototype.update = function () { + return { + bottom: 0, + right: 0 + }; + }; + NullScrollbars.prototype.setScrollLeft = function () {}; + NullScrollbars.prototype.setScrollTop = function () {}; + NullScrollbars.prototype.clear = function () {}; + function updateScrollbars(cm, measure) { + if (!measure) { + measure = measureForScrollbars(cm); + } + var startWidth = cm.display.barWidth, + startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { + updateHeightsInViewport(cm); + } + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; + startHeight = cm.display.barHeight; + } + } + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else { + d.scrollbarFiller.style.display = ""; + } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else { + d.gutterFiller.style.display = ""; + } + } + var scrollbarModel = { + "native": NativeScrollbars, + "null": NullScrollbars + }; + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) { + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + on(node, "mousedown", function () { + if (cm.state.focused) { + setTimeout(function () { + return cm.display.input.focus(); + }, 0); + } + }); + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") { + setScrollLeft(cm, pos); + } else { + updateScrollTop(cm, pos); + } + }, cm); + if (cm.display.scrollbars.addClass) { + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + var nextOpId = 0; + function startOperation(cm) { + cm.curOp = { + cm, + viewChanged: false, + // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, + // Used to detect need to update scrollbar + forceUpdate: false, + // Used to force a redraw + updateInput: 0, + // Whether to reset the input textarea + typing: false, + // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, + // Accumulated changes, for firing change events + cursorActivityHandlers: null, + // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, + // Tracks which cursorActivity handlers have been called already + selectionChanged: false, + // Whether the selection needs to be redrawn + updateMaxLine: false, + // Set when the widest line needs to be determined anew + scrollLeft: null, + scrollTop: null, + // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, + // Used to scroll to a specific position + focus: false, + id: ++nextOpId, + // Unique ID + markArrays: null + // Used by addMarkedSpan + }; + pushOperation(cm.curOp); + } + function endOperation(cm) { + var op = cm.curOp; + if (op) { + finishOperation(op, function (group) { + for (var i2 = 0; i2 < group.ops.length; i2++) { + group.ops[i2].cm.curOp = null; + } + endOperations(group); + }); + } + } + function endOperations(group) { + var ops = group.ops; + for (var i2 = 0; i2 < ops.length; i2++) { + endOperation_R1(ops[i2]); + } + for (var i$12 = 0; i$12 < ops.length; i$12++) { + endOperation_W1(ops[i$12]); + } + for (var i$22 = 0; i$22 < ops.length; i$22++) { + endOperation_R2(ops[i$22]); + } + for (var i$3 = 0; i$3 < ops.length; i$3++) { + endOperation_W2(ops[i$3]); + } + for (var i$4 = 0; i$4 < ops.length; i$4++) { + endOperation_finish(ops[i$4]); + } + } + function endOperation_R1(op) { + var cm = op.cm, + display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) { + findMaxLine(cm); + } + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { + top: op.scrollTop, + ensure: op.scrollToPos + }, op.forceUpdate); + } + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + function endOperation_R2(op) { + var cm = op.cm, + display = cm.display; + if (op.updatedDisplay) { + updateHeightsInViewport(cm); + } + op.barMeasure = measureForScrollbars(cm); + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + if (op.updatedDisplay || op.selectionChanged) { + op.preparedSelection = display.input.prepareSelection(); } - fetchAll() { - const raw = this.storage.get(this.key); - if (raw) { - return JSON.parse(raw)[this.key]; + } + function endOperation_W2(op) { + var cm = op.cm; + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) { + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } - return []; + cm.display.maxLineChanged = false; + } + var takeFocus = op.focus && op.focus == activeElt(); + if (op.preparedSelection) { + cm.display.input.showSelection(op.preparedSelection, takeFocus); + } + if (op.updatedDisplay || op.startHeight != cm.doc.height) { + updateScrollbars(cm, op.barMeasure); + } + if (op.updatedDisplay) { + setDocumentHeight(cm, op.barMeasure); + } + if (op.selectionChanged) { + restartBlink(cm); + } + if (cm.state.focused && op.updateInput) { + cm.display.input.reset(op.typing); + } + if (takeFocus) { + ensureFocus(op.cm); + } + } + function endOperation_finish(op) { + var cm = op.cm, + display = cm.display, + doc = cm.doc; + if (op.updatedDisplay) { + postUpdateDisplay(cm, op.update); + } + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { + display.wheelStartX = display.wheelStartY = null; + } + if (op.scrollTop != null) { + setScrollTop(cm, op.scrollTop, op.forceScroll); + } + if (op.scrollLeft != null) { + setScrollLeft(cm, op.scrollLeft, true, true); } - push(item) { - const items = [...this.items, item]; - if (this.maxSize && items.length > this.maxSize) { - items.shift(); + if (op.scrollToPos) { + var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + maybeScrollWindow(cm, rect); + } + var hidden = op.maybeHiddenMarkers, + unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i2 = 0; i2 < hidden.length; ++i2) { + if (!hidden[i2].lines.length) { + signal(hidden[i2], "hide"); + } } - for (let attempts = 0; attempts < 5; attempts++) { - const response = this.storage.set( - this.key, - JSON.stringify({ - [this.key]: items, - }) - ); - if ( - !(response === null || response === void 0 - ? void 0 - : response.error) - ) { - this.items = items; - } else if (response.isQuotaError && this.maxSize) { - items.shift(); - } else { - return; + } + if (unhidden) { + for (var i$12 = 0; i$12 < unhidden.length; ++i$12) { + if (unhidden[i$12].lines.length) { + signal(unhidden[i$12], "unhide"); } } } - save() { - this.storage.set( - this.key, - JSON.stringify({ - [this.key]: this.items, - }) - ); + if (display.wrapper.offsetHeight) { + doc.scrollTop = cm.display.scroller.scrollTop; + } + if (op.changeObjs) { + signal(cm, "changes", cm, op.changeObjs); + } + if (op.update) { + op.update.finish(); } } - exports.QueryStore = QueryStore; - - /***/ - }, - - /***/ "../node_modules/linkify-it/build/index.cjs.js": - /*!*****************************************************!*\ - !*** ../node_modules/linkify-it/build/index.cjs.js ***! - \*****************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var uc_micro = __webpack_require__( - /*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js" - ); - function reFactory(opts) { - const re = {}; - opts = opts || {}; - re.src_Any = uc_micro.Any.source; - re.src_Cc = uc_micro.Cc.source; - re.src_Z = uc_micro.Z.source; - re.src_P = uc_micro.P.source; - - // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) - re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join("|"); - - // \p{\Z\Cc} (white spaces + control) - re.src_ZCc = [re.src_Z, re.src_Cc].join("|"); - - // Experimental. List of chars, completely prohibited in links - // because can separate it from other part of text - const text_separators = "[><\uff5c]"; - - // All possible word characters (everything without punctuation, spaces & controls) - // Defined via punctuation & spaces to save space - // Should be something like \p{\L\N\S\M} (\w but without `_`) - re.src_pseudo_letter = - "(?:(?!" + - text_separators + - "|" + - re.src_ZPCc + - ")" + - re.src_Any + - ")"; - // The same as abothe but without [0-9] - // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; - - re.src_ip4 = - "(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; - - // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. - re.src_auth = "(?:(?:(?!" + re.src_ZCc + "|[@/\\[\\]()]).)+@)?"; - re.src_port = - "(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?"; - re.src_host_terminator = - "(?=$|" + - text_separators + - "|" + - re.src_ZPCc + - ")" + - "(?!" + - (opts["---"] ? "-(?!--)|" : "-|") + - "_|:\\d|\\.-|\\.(?!$|" + - re.src_ZPCc + - "))"; - re.src_path = - "(?:" + - "[/?#]" + - "(?:" + - "(?!" + - re.src_ZCc + - "|" + - text_separators + - "|[()[\\]{}.,\"'?!\\-;]).|" + - "\\[(?:(?!" + - re.src_ZCc + - "|\\]).)*\\]|" + - "\\((?:(?!" + - re.src_ZCc + - "|[)]).)*\\)|" + - "\\{(?:(?!" + - re.src_ZCc + - "|[}]).)*\\}|" + - '\\"(?:(?!' + - re.src_ZCc + - '|["]).)+\\"|' + - "\\'(?:(?!" + - re.src_ZCc + - "|[']).)+\\'|" + - // allow `I'm_king` if no pair found - "\\'(?=" + - re.src_pseudo_letter + - "|[-])|" + - // google has many dots in "google search" links (#66, #81). - // github has ... in commit range links, - // Restrict to - // - english - // - percent-encoded - // - parts of file path - // - params separator - // until more examples found. - "\\.{2,}[a-zA-Z0-9%/&]|" + - "\\.(?!" + - re.src_ZCc + - "|[.]|$)|" + - (opts["---"] - ? "\\-(?!--(?:[^-]|$))(?:-*)|" // `---` => long dash, terminate - : "\\-+|") + - // allow `,,,` in paths - ",(?!" + - re.src_ZCc + - "|$)|" + - // allow `;` if not followed by space-like char - ";(?!" + - re.src_ZCc + - "|$)|" + - // allow `!!!` in paths, but not at the end - "\\!+(?!" + - re.src_ZCc + - "|[!]|$)|" + - "\\?(?!" + - re.src_ZCc + - "|[?]|$)" + - ")+" + - "|\\/" + - ")?"; - - // Allow anything in markdown spec, forbid quote (") at the first position - // because emails enclosed in quotes are far more common - re.src_email_name = - '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; - re.src_xn = "xn--[a-z0-9\\-]{1,59}"; - - // More to read about domain names - // http://serverfault.com/questions/638260/ - - re.src_domain_root = - // Allow letters & digits (http://test1) - "(?:" + re.src_xn + "|" + re.src_pseudo_letter + "{1,63}" + ")"; - re.src_domain = - "(?:" + - re.src_xn + - "|" + - "(?:" + - re.src_pseudo_letter + - ")" + - "|" + - "(?:" + - re.src_pseudo_letter + - "(?:-|" + - re.src_pseudo_letter + - "){0,61}" + - re.src_pseudo_letter + - ")" + - ")"; - re.src_host = - "(?:" + - // Don't need IP check, because digits are already allowed in normal domain names - // src_ip4 + - // '|' + - "(?:(?:(?:" + - re.src_domain + - ")\\.)*" + - re.src_domain /* _root */ + - ")" + - ")"; - re.tpl_host_fuzzy = - "(?:" + - re.src_ip4 + - "|" + - "(?:(?:(?:" + - re.src_domain + - ")\\.)+(?:%TLDS%))" + - ")"; - re.tpl_host_no_ip_fuzzy = - "(?:(?:(?:" + re.src_domain + ")\\.)+(?:%TLDS%))"; - re.src_host_strict = re.src_host + re.src_host_terminator; - re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; - re.src_host_port_strict = - re.src_host + re.src_port + re.src_host_terminator; - re.tpl_host_port_fuzzy_strict = - re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; - re.tpl_host_port_no_ip_fuzzy_strict = - re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; - - // - // Main rules - // - - // Rude test fuzzy links by host, for quick deny - re.tpl_host_fuzzy_test = - "localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + - re.src_ZPCc + - "|>|$))"; - re.tpl_email_fuzzy = - "(^|" + - text_separators + - '|"|\\(|' + - re.src_ZCc + - ")" + - "(" + - re.src_email_name + - "@" + - re.tpl_host_fuzzy_strict + - ")"; - re.tpl_link_fuzzy = - // Fuzzy link can't be prepended with .:/\- and non punctuation. - // but can start with > (markdown blockquote) - "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|" + - re.src_ZPCc + - "))" + - "((?![$+<=>^`|\uff5c])" + - re.tpl_host_port_fuzzy_strict + - re.src_path + - ")"; - re.tpl_link_no_ip_fuzzy = - // Fuzzy link can't be prepended with .:/\- and non punctuation. - // but can start with > (markdown blockquote) - "(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|" + - re.src_ZPCc + - "))" + - "((?![$+<=>^`|\uff5c])" + - re.tpl_host_port_no_ip_fuzzy_strict + - re.src_path + - ")"; - return re; + function runInOp(cm, f) { + if (cm.curOp) { + return f(); + } + startOperation(cm); + try { + return f(); + } finally { + endOperation(cm); + } } - - // - // Helpers - // - - // Merge objects - // - function assign(obj /* from1, from2, from3, ... */) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; + function operation(cm, f) { + return function () { + if (cm.curOp) { + return f.apply(cm, arguments); + } + startOperation(cm); + try { + return f.apply(cm, arguments); + } finally { + endOperation(cm); + } + }; + } + function methodOp(f) { + return function () { + if (this.curOp) { + return f.apply(this, arguments); + } + startOperation(this); + try { + return f.apply(this, arguments); + } finally { + endOperation(this); } - Object.keys(source).forEach(function (key) { - obj[key] = source[key]; - }); - }); - return obj; - } - function _class(obj) { - return Object.prototype.toString.call(obj); + }; } - function isString(obj) { - return _class(obj) === "[object String]"; + function docMethodOp(f) { + return function () { + var cm = this.cm; + if (!cm || cm.curOp) { + return f.apply(this, arguments); + } + startOperation(cm); + try { + return f.apply(this, arguments); + } finally { + endOperation(cm); + } + }; } - function isObject(obj) { - return _class(obj) === "[object Object]"; + function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) { + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } } - function isRegExp(obj) { - return _class(obj) === "[object RegExp]"; + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.highlightFrontier >= cm.display.viewTo) { + return; + } + var end = + /* @__PURE__ */new Date() + cm.options.workTime; + var context = getContextBefore(cm, doc.highlightFrontier); + var changedLines = []; + doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (context.line >= cm.display.viewFrom) { + var oldStyles = line.styles; + var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; + var highlighted = highlightLine(cm, line, context, true); + if (resetState) { + context.state = resetState; + } + line.styles = highlighted.styles; + var oldCls = line.styleClasses, + newCls = highlighted.classes; + if (newCls) { + line.styleClasses = newCls; + } else if (oldCls) { + line.styleClasses = null; + } + var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) { + ischange = oldStyles[i2] != line.styles[i2]; + } + if (ischange) { + changedLines.push(context.line); + } + line.stateAfter = context.save(); + context.nextLine(); + } else { + if (line.text.length <= cm.options.maxHighlightLength) { + processLine(cm, line.text, context); + } + line.stateAfter = context.line % 5 == 0 ? context.save() : null; + context.nextLine(); + } + if (+ /* @__PURE__ */new Date() > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + doc.highlightFrontier = context.line; + doc.modeFrontier = Math.max(doc.modeFrontier, context.line); + if (changedLines.length) { + runInOp(cm, function () { + for (var i2 = 0; i2 < changedLines.length; i2++) { + regLineChange(cm, changedLines[i2], "text"); + } + }); + } } - function isFunction(obj) { - return _class(obj) === "[object Function]"; + var DisplayUpdate = function (cm, viewport, force) { + var display = cm.display; + this.viewport = viewport; + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + }; + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) { + this.events.push(arguments); + } + }; + DisplayUpdate.prototype.finish = function () { + for (var i2 = 0; i2 < this.events.length; i2++) { + signal.apply(null, this.events[i2]); + } + }; + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + function selectionSnapshot(cm) { + if (cm.hasFocus()) { + return null; + } + var active = activeElt(); + if (!active || !contains(cm.display.lineDiv, active)) { + return null; + } + var result = { + activeElt: active + }; + if (window.getSelection) { + var sel = window.getSelection(); + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode; + result.anchorOffset = sel.anchorOffset; + result.focusNode = sel.focusNode; + result.focusOffset = sel.focusOffset; + } + } + return result; } - function escapeRE(str) { - return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"); + function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { + return; + } + snapshot.activeElt.focus(); + if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + var sel = window.getSelection(), + range2 = document.createRange(); + range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset); + range2.collapse(false); + sel.removeAllRanges(); + sel.addRange(range2); + sel.extend(snapshot.focusNode, snapshot.focusOffset); + } + } + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, + doc = cm.doc; + if (update.editorIsHidden) { + resetView(cm); + return false; + } + if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { + return false; + } + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) { + from = Math.max(doc.first, display.viewFrom); + } + if (display.viewTo > to && display.viewTo - to < 20) { + to = Math.min(end, display.viewTo); + } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + cm.display.mover.style.top = display.viewOffset + "px"; + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { + return false; + } + var selSnapshot = selectionSnapshot(cm); + if (toUpdate > 4) { + display.lineDiv.style.display = "none"; + } + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) { + display.lineDiv.style.display = ""; + } + display.renderedView = display.view; + restoreSelection(selSnapshot); + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + display.updateLineNumbers = null; + return true; } - - // - - const defaultOptions = { - fuzzyLink: true, - fuzzyEmail: true, - fuzzyIP: false, - }; - function isOptionsObj(obj) { - return Object.keys(obj || {}).reduce(function (acc, k) { - /* eslint-disable-next-line no-prototype-builtins */ - return acc || defaultOptions.hasOwnProperty(k); - }, false); - } - const defaultSchemas = { - "http:": { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.http) { - // compile lazily, because "host"-containing variables can change on tlds update. - self.re.http = new RegExp( - "^\\/\\/" + - self.re.src_auth + - self.re.src_host_port_strict + - self.re.src_path, - "i" - ); + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + if (viewport && viewport.top != null) { + viewport = { + top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) + }; } - if (self.re.http.test(tail)) { - return tail.match(self.re.http)[0].length; + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { + break; } - return 0; - }, - }, - "https:": "http:", - "ftp:": "http:", - "//": { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.no_http) { - // compile lazily, because "host"-containing variables can change on tlds update. - self.re.no_http = new RegExp( - "^" + - self.re.src_auth + - // Don't allow single-level domains, because of false positives like '//test' - // with code comments - "(?:localhost|(?:(?:" + - self.re.src_domain + - ")\\.)+" + - self.re.src_domain_root + - ")" + - self.re.src_port + - self.re.src_host_terminator + - self.re.src_path, - "i" - ); + } else if (first) { + update.visible = visibleLines(cm.display, cm.doc, viewport); + } + if (!updateDisplayIfNeeded(cm, update)) { + break; + } + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.force = false; + } + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; + cm.display.reportedViewTo = cm.display.viewTo; + } + } + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, + lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, + cur = container.firstChild; + function rm(node2) { + var next = node2.nextSibling; + if (webkit && mac && cm.display.currentWheelTarget == node2) { + node2.style.display = "none"; + } else { + node2.parentNode.removeChild(node2); + } + return next; + } + var view = display.view, + lineN = display.viewFrom; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (lineView.hidden) ;else if (!lineView.node || lineView.node.parentNode != container) { + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { + while (cur != lineView.node) { + cur = rm(cur); } - if (self.re.no_http.test(tail)) { - // should not be `://` & `///`, that protects from errors in protocol name - if (pos >= 3 && text[pos - 3] === ":") { - return 0; + var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { + updateNumber = false; } - if (pos >= 3 && text[pos - 3] === "/") { - return 0; - } - return tail.match(self.re.no_http)[0].length; - } - return 0; - }, - }, - "mailto:": { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.mailto) { - self.re.mailto = new RegExp( - "^" + self.re.src_email_name + "@" + self.re.src_host_strict, - "i" - ); + updateLineForChanges(cm, lineView, lineN, dims); } - if (self.re.mailto.test(tail)) { - return tail.match(self.re.mailto)[0].length; + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); } - return 0; - }, - }, - }; - - // RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) - /* eslint-disable-next-line max-len */ - const tlds_2ch_src_re = - "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"; - - // DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead - const tlds_default = - "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split( - "|" - ); - function resetScanCache(self) { - self.__index__ = -1; - self.__text_cache__ = ""; - } - function createValidator(re) { - return function (text, pos) { - const tail = text.slice(pos); - if (re.test(tail)) { - return tail.match(re)[0].length; + cur = lineView.node.nextSibling; } - return 0; - }; + lineN += lineView.size; + } + while (cur) { + cur = rm(cur); + } } - function createNormalizer() { - return function (match, self) { - self.normalize(match); - }; + function updateGutterSpace(display) { + var width = display.gutters.offsetWidth; + display.sizer.style.marginLeft = width + "px"; + signalLater(display, "gutterChanged", display); } - - // Schemas compiler. Build regexps. - // - function compile(self) { - // Load & clone RE patterns. - const re = (self.re = reFactory(self.__opts__)); - - // Define dynamic patterns - const tlds = self.__tlds__.slice(); - self.onCompile(); - if (!self.__tlds_replaced__) { - tlds.push(tlds_2ch_src_re); - } - tlds.push(re.src_xn); - re.src_tlds = tlds.join("|"); - function untpl(tpl) { - return tpl.replace("%TLDS%", re.src_tlds); - } - re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), "i"); - re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), "i"); - re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), "i"); - re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), "i"); - - // - // Compile each schema - // - - const aliases = []; - self.__compiled__ = {}; // Reset compiled data - - function schemaError(name, val) { - throw new Error( - '(LinkifyIt) Invalid schema "' + name + '": ' + val - ); + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px"; + } + function alignHorizontally(cm) { + var display = cm.display, + view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { + return; } - Object.keys(self.__schemas__).forEach(function (name) { - const val = self.__schemas__[name]; - - // skip disabled methods - if (val === null) { - return; - } - const compiled = { - validate: null, - link: null, - }; - self.__compiled__[name] = compiled; - if (isObject(val)) { - if (isRegExp(val.validate)) { - compiled.validate = createValidator(val.validate); - } else if (isFunction(val.validate)) { - compiled.validate = val.validate; - } else { - schemaError(name, val); + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, + left = comp + "px"; + for (var i2 = 0; i2 < view.length; i2++) { + if (!view[i2].hidden) { + if (cm.options.fixedGutter) { + if (view[i2].gutter) { + view[i2].gutter.style.left = left; + } + if (view[i2].gutterBackground) { + view[i2].gutterBackground.style.left = left; + } } - if (isFunction(val.normalize)) { - compiled.normalize = val.normalize; - } else if (!val.normalize) { - compiled.normalize = createNormalizer(); - } else { - schemaError(name, val); + var align = view[i2].alignable; + if (align) { + for (var j = 0; j < align.length; j++) { + align[j].style.left = left; + } } - return; - } - if (isString(val)) { - aliases.push(name); - return; - } - schemaError(name, val); - }); - - // - // Compile postponed aliases - // - - aliases.forEach(function (alias) { - if (!self.__compiled__[self.__schemas__[alias]]) { - // Silently fail on missed schemas to avoid errons on disable. - // schemaError(alias, self.__schemas__[alias]); - return; } - self.__compiled__[alias].validate = - self.__compiled__[self.__schemas__[alias]].validate; - self.__compiled__[alias].normalize = - self.__compiled__[self.__schemas__[alias]].normalize; - }); - - // - // Fake record for guessed links - // - self.__compiled__[""] = { - validate: null, - normalize: createNormalizer(), - }; - - // - // Build schema condition - // - const slist = Object.keys(self.__compiled__) - .filter(function (name) { - // Filter disabled & fake schemas - return name.length > 0 && self.__compiled__[name]; - }) - .map(escapeRE) - .join("|"); - // (?!_) cause 1.5x slowdown - self.re.schema_test = RegExp( - "(^|(?!_)(?:[><\uff5c]|" + re.src_ZPCc + "))(" + slist + ")", - "i" - ); - self.re.schema_search = RegExp( - "(^|(?!_)(?:[><\uff5c]|" + re.src_ZPCc + "))(" + slist + ")", - "ig" - ); - self.re.schema_at_start = RegExp( - "^" + self.re.schema_search.source, - "i" - ); - self.re.pretest = RegExp( - "(" + - self.re.schema_test.source + - ")|(" + - self.re.host_fuzzy_test.source + - ")|@", - "i" - ); - - // - // Cleanup - // - - resetScanCache(self); - } - - /** - * class Match - * - * Match result. Single element of array, returned by [[LinkifyIt#match]] - **/ - function Match(self, shift) { - const start = self.__index__; - const end = self.__last_index__; - const text = self.__text_cache__.slice(start, end); - - /** - * Match#schema -> String - * - * Prefix (protocol) for matched string. - **/ - this.schema = self.__schema__.toLowerCase(); - /** - * Match#index -> Number - * - * First position of matched string. - **/ - this.index = start + shift; - /** - * Match#lastIndex -> Number - * - * Next position after matched string. - **/ - this.lastIndex = end + shift; - /** - * Match#raw -> String - * - * Matched string. - **/ - this.raw = text; - /** - * Match#text -> String - * - * Notmalized text of matched string. - **/ - this.text = text; - /** - * Match#url -> String - * - * Normalized url of matched string. - **/ - this.url = text; - } - function createMatch(self, shift) { - const match = new Match(self, shift); - self.__compiled__[match.schema].normalize(match, self); - return match; - } - - /** - * class LinkifyIt - **/ - - /** - * new LinkifyIt(schemas, options) - * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) - * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } - * - * Creates new linkifier instance with optional additional schemas. - * Can be called without `new` keyword for convenience. - * - * By default understands: - * - * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links - * - "fuzzy" links and emails (example.com, foo@bar.com). - * - * `schemas` is an object, where each key/value describes protocol/rule: - * - * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` - * for example). `linkify-it` makes shure that prefix is not preceeded with - * alphanumeric char and symbols. Only whitespaces and punctuation allowed. - * - __value__ - rule to check tail after link prefix - * - _String_ - just alias to existing rule - * - _Object_ - * - _validate_ - validator function (should return matched length on success), - * or `RegExp`. - * - _normalize_ - optional function to normalize text & url of matched result - * (for example, for @twitter mentions). - * - * `options`: - * - * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. - * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts - * like version numbers. Default `false`. - * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. - * - **/ - function LinkifyIt(schemas, options) { - if (!(this instanceof LinkifyIt)) { - return new LinkifyIt(schemas, options); } - if (!options) { - if (isOptionsObj(schemas)) { - options = schemas; - schemas = {}; - } + if (cm.options.fixedGutter) { + display.gutters.style.left = comp + gutterW + "px"; } - this.__opts__ = assign({}, defaultOptions, options); - - // Cache last tested result. Used to skip repeating steps on next `match` call. - this.__index__ = -1; - this.__last_index__ = -1; // Next scan position - this.__schema__ = ""; - this.__text_cache__ = ""; - this.__schemas__ = assign({}, defaultSchemas, schemas); - this.__compiled__ = {}; - this.__tlds__ = tlds_default; - this.__tlds_replaced__ = false; - this.re = {}; - compile(this); } - - /** chainable - * LinkifyIt#add(schema, definition) - * - schema (String): rule name (fixed pattern prefix) - * - definition (String|RegExp|Object): schema definition - * - * Add new rule definition. See constructor description for details. - **/ - LinkifyIt.prototype.add = function add(schema, definition) { - this.__schemas__[schema] = definition; - compile(this); - return this; - }; - - /** chainable - * LinkifyIt#set(options) - * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } - * - * Set recognition options for links without schema. - **/ - LinkifyIt.prototype.set = function set(options) { - this.__opts__ = assign(this.__opts__, options); - return this; - }; - - /** - * LinkifyIt#test(text) -> Boolean - * - * Searches linkifiable pattern and returns `true` on success or `false` on fail. - **/ - LinkifyIt.prototype.test = function test(text) { - // Reset scan cache - this.__text_cache__ = text; - this.__index__ = -1; - if (!text.length) { + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false; } - let m, ml, me, len, shift, next, re, tld_pos, at_pos; - - // try to scan for link with schema - that's the most simple rule - if (this.re.schema_test.test(text)) { - re = this.re.schema_search; - re.lastIndex = 0; - while ((m = re.exec(text)) !== null) { - len = this.testSchemaAt(text, m[2], re.lastIndex); - if (len) { - this.__schema__ = m[2]; - this.__index__ = m.index + m[1].length; - this.__last_index__ = m.index + m[0].length + len; - break; + var doc = cm.doc, + last = lineNumberFor(cm.options, doc.first + doc.size - 1), + display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, + padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm.display); + return true; + } + return false; + } + function getGutters(gutters, lineNumbers) { + var result = [], + sawLineNumbers = false; + for (var i2 = 0; i2 < gutters.length; i2++) { + var name = gutters[i2], + style = null; + if (typeof name != "string") { + style = name.style; + name = name.className; + } + if (name == "CodeMirror-linenumbers") { + if (!lineNumbers) { + continue; + } else { + sawLineNumbers = true; } } + result.push({ + className: name, + style + }); } - if (this.__opts__.fuzzyLink && this.__compiled__["http:"]) { - // guess schemaless links - tld_pos = text.search(this.re.host_fuzzy_test); - if (tld_pos >= 0) { - // if tld is located after found link - no need to check fuzzy pattern - if (this.__index__ < 0 || tld_pos < this.__index__) { - if ( - (ml = text.match( - this.__opts__.fuzzyIP - ? this.re.link_fuzzy - : this.re.link_no_ip_fuzzy - )) !== null - ) { - shift = ml.index + ml[1].length; - if (this.__index__ < 0 || shift < this.__index__) { - this.__schema__ = ""; - this.__index__ = shift; - this.__last_index__ = ml.index + ml[0].length; - } + if (lineNumbers && !sawLineNumbers) { + result.push({ + className: "CodeMirror-linenumbers", + style: null + }); + } + return result; + } + function renderGutters(display) { + var gutters = display.gutters, + specs = display.gutterSpecs; + removeChildren(gutters); + display.lineGutter = null; + for (var i2 = 0; i2 < specs.length; ++i2) { + var ref = specs[i2]; + var className = ref.className; + var style = ref.style; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); + if (style) { + gElt.style.cssText = style; + } + if (className == "CodeMirror-linenumbers") { + display.lineGutter = gElt; + gElt.style.width = (display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = specs.length ? "" : "none"; + updateGutterSpace(display); + } + function updateGutters(cm) { + renderGutters(cm.display); + regChange(cm); + alignHorizontally(cm); + } + function Display(place, doc, input, options) { + var d = this; + this.input = input; + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + d.lineDiv = eltP("div", null, "CodeMirror-code"); + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + d.measure = elt("div", null, "CodeMirror-measure"); + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); + d.mover = elt("div", [lines], null, "position: relative"); + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + d.wrapper.setAttribute("translate", "no"); + if (ie && ie_version < 8) { + d.gutters.style.zIndex = -1; + d.scroller.style.paddingRight = 0; + } + if (!webkit && !(gecko && mobile)) { + d.scroller.draggable = true; + } + if (place) { + if (place.appendChild) { + place.appendChild(d.wrapper); + } else { + place(d.wrapper); + } + } + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + d.view = []; + d.renderedView = null; + d.externalMeasured = null; + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + d.alignWidgets = false; + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + d.shift = false; + d.selForContextMenu = null; + d.activeTouch = null; + d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); + renderGutters(d); + input.init(d); + } + var wheelSamples = 0, + wheelPixelsPerUnit = null; + if (ie) { + wheelPixelsPerUnit = -0.53; + } else if (gecko) { + wheelPixelsPerUnit = 15; + } else if (chrome) { + wheelPixelsPerUnit = -0.7; + } else if (safari) { + wheelPixelsPerUnit = -1 / 3; + } + function wheelEventDelta(e) { + var dx = e.wheelDeltaX, + dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { + dx = e.detail; + } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { + dy = e.detail; + } else if (dy == null) { + dy = e.wheelDelta; + } + return { + x: dx, + y: dy + }; + } + function wheelEventPixels(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + } + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), + dx = delta.x, + dy = delta.y; + var pixelsPerUnit = wheelPixelsPerUnit; + if (e.deltaMode === 0) { + dx = e.deltaX; + dy = e.deltaY; + pixelsPerUnit = 1; + } + var display = cm.display, + scroll = display.scroller; + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) { + return; + } + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i2 = 0; i2 < view.length; i2++) { + if (view[i2].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; } } } } - if (this.__opts__.fuzzyEmail && this.__compiled__["mailto:"]) { - // guess schemaless emails - at_pos = text.indexOf("@"); - if (at_pos >= 0) { - // We can't skip this check, because this cases are possible: - // 192.168.1.1@gmail.com, my.in@example.com - if ((me = text.match(this.re.email_fuzzy)) !== null) { - shift = me.index + me[1].length; - next = me.index + me[0].length; - if ( - this.__index__ < 0 || - shift < this.__index__ || - (shift === this.__index__ && next > this.__last_index__) - ) { - this.__schema__ = "mailto:"; - this.__index__ = shift; - this.__last_index__ = next; + if (dx && !gecko && !presto && pixelsPerUnit != null) { + if (dy && canScrollY) { + updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); + } + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); + if (!dy || dy && canScrollY) { + e_preventDefault(e); + } + display.wheelStartX = null; + return; + } + if (dy && pixelsPerUnit != null) { + var pixels = dy * pixelsPerUnit; + var top = cm.doc.scrollTop, + bot = top + display.wrapper.clientHeight; + if (pixels < 0) { + top = Math.max(0, top + pixels - 50); + } else { + bot = Math.min(cm.doc.height, bot + pixels + 50); + } + updateDisplaySimple(cm, { + top, + bottom: bot + }); + } + if (wheelSamples < 20 && e.deltaMode !== 0) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; + display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; + display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) { + return; } - } + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX; + display.wheelStartX = display.wheelStartY = null; + if (!sample) { + return; + } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; + display.wheelDY += dy; } } - return this.__index__ >= 0; - }; - - /** - * LinkifyIt#pretest(text) -> Boolean - * - * Very quick check, that can give false positives. Returns true if link MAY BE - * can exists. Can be used for speed optimization, when you need to check that - * link NOT exists. - **/ - LinkifyIt.prototype.pretest = function pretest(text) { - return this.re.pretest.test(text); + } + var Selection = function (ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; }; - - /** - * LinkifyIt#testSchemaAt(text, name, position) -> Number - * - text (String): text to scan - * - name (String): rule (schema) name - * - position (Number): text offset to check from - * - * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly - * at given position. Returns length of found pattern (0 on fail). - **/ - LinkifyIt.prototype.testSchemaAt = function testSchemaAt( - text, - schema, - pos - ) { - // If not supported schema check requested - terminate - if (!this.__compiled__[schema.toLowerCase()]) { - return 0; - } - return this.__compiled__[schema.toLowerCase()].validate( - text, - pos, - this - ); + Selection.prototype.primary = function () { + return this.ranges[this.primIndex]; }; - - /** - * LinkifyIt#match(text) -> Array|null - * - * Returns array of found link descriptions or `null` on fail. We strongly - * recommend to use [[LinkifyIt#test]] first, for best speed. - * - * ##### Result match description - * - * - __schema__ - link schema, can be empty for fuzzy links, or `//` for - * protocol-neutral links. - * - __index__ - offset of matched text - * - __lastIndex__ - index of next char after mathch end - * - __raw__ - matched text - * - __text__ - normalized text - * - __url__ - link, generated from matched text - **/ - LinkifyIt.prototype.match = function match(text) { - const result = []; - let shift = 0; - - // Try to take previous element from cache, if .test() called before - if (this.__index__ >= 0 && this.__text_cache__ === text) { - result.push(createMatch(this, shift)); - shift = this.__last_index__; + Selection.prototype.equals = function (other) { + if (other == this) { + return true; } - - // Cut head if cache was used - let tail = shift ? text.slice(shift) : text; - - // Scan string until end reached - while (this.test(tail)) { - result.push(createMatch(this, shift)); - tail = tail.slice(this.__last_index__); - shift += this.__last_index__; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { + return false; } - if (result.length) { - return result; + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var here = this.ranges[i2], + there = other.ranges[i2]; + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { + return false; + } } - return null; + return true; }; - - /** - * LinkifyIt#matchAtStart(text) -> Match|null - * - * Returns fully-formed (not fuzzy) link if it starts at the beginning - * of the string, and null otherwise. - **/ - LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { - // Reset scan cache - this.__text_cache__ = text; - this.__index__ = -1; - if (!text.length) return null; - const m = this.re.schema_at_start.exec(text); - if (!m) return null; - const len = this.testSchemaAt(text, m[2], m[0].length); - if (!len) return null; - this.__schema__ = m[2]; - this.__index__ = m.index + m[1].length; - this.__last_index__ = m.index + m[0].length + len; - return createMatch(this, 0); + Selection.prototype.deepCopy = function () { + var out = []; + for (var i2 = 0; i2 < this.ranges.length; i2++) { + out[i2] = new Range(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head)); + } + return new Selection(out, this.primIndex); }; - - /** chainable - * LinkifyIt#tlds(list [, keepOld]) -> this - * - list (Array): list of tlds - * - keepOld (Boolean): merge with current list if `true` (`false` by default) - * - * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) - * to avoid false positives. By default this algorythm used: - * - * - hostname with any 2-letter root zones are ok. - * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф - * are ok. - * - encoded (`xn--...`) root zones are ok. - * - * If list is replaced, then exact match for 2-chars root zones will be checked. - **/ - LinkifyIt.prototype.tlds = function tlds(list, keepOld) { - list = Array.isArray(list) ? list : [list]; - if (!keepOld) { - this.__tlds__ = list.slice(); - this.__tlds_replaced__ = true; - compile(this); - return this; - } - this.__tlds__ = this.__tlds__ - .concat(list) - .sort() - .filter(function (el, idx, arr) { - return el !== arr[idx - 1]; - }) - .reverse(); - compile(this); - return this; + Selection.prototype.somethingSelected = function () { + for (var i2 = 0; i2 < this.ranges.length; i2++) { + if (!this.ranges[i2].empty()) { + return true; + } + } + return false; }; - - /** - * LinkifyIt#normalize(match) - * - * Default normalizer (if schema does not define it's own). - **/ - LinkifyIt.prototype.normalize = function normalize(match) { - // Do minimal possible changes by default. Need to collect feedback prior - // to move forward https://github.com/markdown-it/linkify-it/issues/1 - - if (!match.schema) { - match.url = "http://" + match.url; + Selection.prototype.contains = function (pos, end) { + if (!end) { + end = pos; } - if (match.schema === "mailto:" && !/^mailto:/i.test(match.url)) { - match.url = "mailto:" + match.url; + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var range2 = this.ranges[i2]; + if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) { + return i2; + } } + return -1; + }; + var Range = function (anchor, head) { + this.anchor = anchor; + this.head = head; }; - - /** - * LinkifyIt#onCompile() - * - * Override to modify basic RegExp-s. - **/ - LinkifyIt.prototype.onCompile = function onCompile() {}; - module.exports = LinkifyIt; - - /***/ - }, - - /***/ "../node_modules/markdown-it/dist/index.cjs.js": - /*!*****************************************************!*\ - !*** ../node_modules/markdown-it/dist/index.cjs.js ***! - \*****************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var mdurl = __webpack_require__( - /*! mdurl */ "../node_modules/mdurl/build/index.cjs.js" - ); - var ucmicro = __webpack_require__( - /*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js" - ); - var entities = __webpack_require__( - /*! entities */ "../../../node_modules/entities/lib/index.js" - ); - var LinkifyIt = __webpack_require__( - /*! linkify-it */ "../node_modules/linkify-it/build/index.cjs.js" - ); - var punycode = __webpack_require__( - /*! punycode.js */ "../../../node_modules/punycode.js/punycode.es6.js" - ); - function _interopNamespaceDefault(e) { - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== "default") { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); + Range.prototype.from = function () { + return minPos(this.anchor, this.head); + }; + Range.prototype.to = function () { + return maxPos(this.anchor, this.head); + }; + Range.prototype.empty = function () { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + }; + function normalizeSelection(cm, ranges, primIndex) { + var mayTouch = cm && cm.options.selectionsMayTouch; + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { + return cmp(a.from(), b.from()); + }); + primIndex = indexOf(ranges, prim); + for (var i2 = 1; i2 < ranges.length; i2++) { + var cur = ranges[i2], + prev = ranges[i2 - 1]; + var diff = cmp(prev.to(), cur.from()); + if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { + var from = minPos(prev.from(), cur.from()), + to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i2 <= primIndex) { + --primIndex; } - }); + ranges.splice(--i2, 2, new Range(inv ? to : from, inv ? from : to)); + } } - n.default = e; - return Object.freeze(n); + return new Selection(ranges, primIndex); } - var mdurl__namespace = /*#__PURE__*/ _interopNamespaceDefault(mdurl); - var ucmicro__namespace = - /*#__PURE__*/ _interopNamespaceDefault(ucmicro); - - // Utilities - // - - function _class(obj) { - return Object.prototype.toString.call(obj); + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + function changeEnd(change) { + if (!change.text) { + return change.to; + } + return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); } - function isString(obj) { - return _class(obj) === "[object String]"; + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { + return pos; + } + if (cmp(pos, change.to) <= 0) { + return changeEnd(change); + } + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, + ch = pos.ch; + if (pos.line == change.to.line) { + ch += changeEnd(change).ch - change.to.ch; + } + return Pos(line, ch); } - const _hasOwnProperty = Object.prototype.hasOwnProperty; - function has(object, key) { - return _hasOwnProperty.call(object, key); + function computeSelAfterChange(doc, change) { + var out = []; + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + var range2 = doc.sel.ranges[i2]; + out.push(new Range(adjustForChange(range2.anchor, change), adjustForChange(range2.head, change))); + } + return normalizeSelection(doc.cm, out, doc.sel.primIndex); } - - // Merge objects - // - function assign(obj /* from1, from2, from3, ... */) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; + function offsetPos(pos, old, nw) { + if (pos.line == old.line) { + return Pos(nw.line, pos.ch - old.ch + nw.ch); + } else { + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + } + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), + newPrev = oldPrev; + for (var i2 = 0; i2 < changes.length; i2++) { + var change = changes[i2]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range2 = doc.sel.ranges[i2], + inv = cmp(range2.head, range2.anchor) < 0; + out[i2] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i2] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { + line.stateAfter = null; } - if (typeof source !== "object") { - throw new TypeError(source + "must be object"); + if (line.styles) { + line.styles = null; } - Object.keys(source).forEach(function (key) { - obj[key] = source[key]; - }); }); - return obj; - } - - // Remove element from array and put another array at those position. - // Useful for some operations with tokens - function arrayReplaceAt(src, pos, newElements) { - return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); - } - function isValidEntityCode(c) { - /* eslint no-bitwise:0 */ - // broken sequence - if (c >= 0xd800 && c <= 0xdfff) { - return false; + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) { + regChange(cm); } - // never used - if (c >= 0xfdd0 && c <= 0xfdef) { - return false; + } + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + function updateDoc(doc, change, markedSpans, estimateHeight2) { + function spansFor(n) { + return markedSpans ? markedSpans[n] : null; } - if ((c & 0xffff) === 0xffff || (c & 0xffff) === 0xfffe) { - return false; + function update(line, text2, spans) { + updateLine(line, text2, spans, estimateHeight2); + signalLater(line, "change", line, change); } - // control codes - if (c >= 0x00 && c <= 0x08) { - return false; + function linesFor(start, end) { + var result = []; + for (var i2 = start; i2 < end; ++i2) { + result.push(new Line(text[i2], spansFor(i2), estimateHeight2)); + } + return result; } - if (c === 0x0b) { - return false; + var from = change.from, + to = change.to, + text = change.text; + var firstLine = getLine(doc, from.line), + lastLine = getLine(doc, to.line); + var lastText = lst(text), + lastSpans = spansFor(text.length - 1), + nlines = to.line - from.line; + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) { + doc.remove(from.line, nlines); + } + if (added.length) { + doc.insert(from.line, added); + } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added$1 = linesFor(1, text.length - 1); + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added$1); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added$2 = linesFor(1, text.length - 1); + if (nlines > 1) { + doc.remove(from.line + 1, nlines - 1); + } + doc.insert(from.line + 1, added$2); + } + signalLater(doc, "change", doc, change); + } + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc2, skip, sharedHist) { + if (doc2.linked) { + for (var i2 = 0; i2 < doc2.linked.length; ++i2) { + var rel = doc2.linked[i2]; + if (rel.doc == skip) { + continue; + } + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) { + continue; + } + f(rel.doc, shared); + propagate(rel.doc, doc2, shared); + } + } } - if (c >= 0x0e && c <= 0x1f) { - return false; + propagate(doc, null, true); + } + function attachDoc(cm, doc) { + if (doc.cm) { + throw new Error("This document is already in use."); } - if (c >= 0x7f && c <= 0x9f) { - return false; + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + setDirectionClass(cm); + cm.options.direction = doc.direction; + if (!cm.options.lineWrapping) { + findMaxLine(cm); } - // out of range - if (c > 0x10ffff) { - return false; + cm.options.mode = doc.modeOption; + regChange(cm); + } + function setDirectionClass(cm) { + (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); + } + function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm); + regChange(cm); + }); + } + function History(prev) { + this.done = []; + this.undone = []; + this.undoDepth = prev ? prev.undoDepth : Infinity; + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; + } + function historyChangeFromChange(doc, change) { + var histChange = { + from: copyPos(change.from), + to: changeEnd(change), + text: getBetween(doc, change.from, change.to) + }; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc2) { + return attachLocalSpans(doc2, histChange, change.from.line, change.to.line + 1); + }, true); + return histChange; + } + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) { + array.pop(); + } else { + break; + } } - return true; } - function fromCodePoint(c) { - /* eslint no-bitwise:0 */ - if (c > 0xffff) { - c -= 0x10000; - const surrogate1 = 0xd800 + (c >> 10); - const surrogate2 = 0xdc00 + (c & 0x3ff); - return String.fromCharCode(surrogate1, surrogate2); - } - return String.fromCharCode(c); - } - const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g; - const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; - const UNESCAPE_ALL_RE = new RegExp( - UNESCAPE_MD_RE.source + "|" + ENTITY_RE.source, - "gi" - ); - const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i; - function replaceEntityPattern(match, name) { - if ( - name.charCodeAt(0) === 0x23 /* # */ && - DIGITAL_ENTITY_TEST_RE.test(name) - ) { - const code = - name[1].toLowerCase() === "x" - ? parseInt(name.slice(2), 16) - : parseInt(name.slice(1), 10); - if (isValidEntityCode(code)) { - return fromCodePoint(code); + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = + /* @__PURE__ */new Date(), + cur; + var last; + if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + last.to = changeEnd(change); + } else { + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + var before = lst(hist.done); + if (!before || !before.ranges) { + pushSelectionToHistory(doc.sel, hist.done); + } + cur = { + changes: [historyChangeFromChange(doc, change)], + generation: hist.generation + }; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) { + hist.done.shift(); + } } - return match; } - const decoded = entities.decodeHTML(match); - if (decoded !== match) { - return decoded; + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + if (!last) { + signal(doc, "historyAdded"); } - return match; } - - /* function replaceEntities(str) { - if (str.indexOf('&') < 0) { return str; } - - return str.replace(ENTITY_RE, replaceEntityPattern); -} */ - - function unescapeMd(str) { - if (str.indexOf("\\") < 0) { - return str; + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && /* @__PURE__ */new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, + origin = options && options.origin; + if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) { + hist.done[hist.done.length - 1] = sel; + } else { + pushSelectionToHistory(sel, hist.done); + } + hist.lastSelTime = + /* @__PURE__ */new Date(); + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) { + clearSelectionEvents(hist.undone); } - return str.replace(UNESCAPE_MD_RE, "$1"); } - function unescapeAll(str) { - if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) { - return str; + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) { + dest.push(sel); } - return str.replace( - UNESCAPE_ALL_RE, - function (match, escaped, entity) { - if (escaped) { - return escaped; + } + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], + n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) { + (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + } + ++n; + }); + } + function removeClearedSpans(spans) { + if (!spans) { + return null; + } + var out; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2].marker.explicitlyCleared) { + if (!out) { + out = spans.slice(0, i2); } - return replaceEntityPattern(match, entity); + } else if (out) { + out.push(spans[i2]); } - ); + } + return !out ? spans : out.length ? out : null; } - const HTML_ESCAPE_TEST_RE = /[&<>"]/; - const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; - const HTML_REPLACEMENTS = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - }; - function replaceUnsafeChar(ch) { - return HTML_REPLACEMENTS[ch]; + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) { + return null; + } + var nw = []; + for (var i2 = 0; i2 < change.text.length; ++i2) { + nw.push(removeClearedSpans(found[i2])); + } + return nw; } - function escapeHtml(str) { - if (HTML_ESCAPE_TEST_RE.test(str)) { - return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) { + return stretched; + } + if (!stretched) { + return old; + } + for (var i2 = 0; i2 < old.length; ++i2) { + var oldCur = old[i2], + stretchCur = stretched[i2]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) { + if (oldCur[k].marker == span.marker) { + continue spans; + } + } + oldCur.push(span); + } + } else if (stretchCur) { + old[i2] = stretchCur; + } } - return str; + return old; } - const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; - function escapeRE(str) { - return str.replace(REGEXP_ESCAPE_RE, "\\$&"); + function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = []; + for (var i2 = 0; i2 < events.length; ++i2) { + var event = events[i2]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, + newChanges = []; + copy.push({ + changes: newChanges + }); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], + m = void 0; + newChanges.push({ + from: change.from, + to: change.to, + text: change.text + }); + if (newGroup) { + for (var prop2 in change) { + if (m = prop2.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop2] = change[prop2]; + delete change[prop2]; + } + } + } + } + } + } + return copy; } - function isSpace(code) { - switch (code) { - case 0x09: - case 0x20: - return true; + function extendRange(range2, head, other, extend) { + if (extend) { + var anchor = range2.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != cmp(other, anchor) < 0) { + anchor = head; + head = other; + } else if (posBefore != cmp(head, other) < 0) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); } - return false; } - - // Zs (unicode class) || [\t\f\v\r\n] - function isWhitespace(code) { - if (code >= 0x2000 && code <= 0x200a) { - return true; + function extendSelection(doc, head, other, options, extend) { + if (extend == null) { + extend = doc.cm && (doc.cm.display.shift || doc.extend); } - switch (code) { - case 0x09: // \t - case 0x0a: // \n - case 0x0b: // \v - case 0x0c: // \f - case 0x0d: // \r - case 0x20: - case 0xa0: - case 0x1680: - case 0x202f: - case 0x205f: - case 0x3000: - return true; + setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); + } + function extendSelections(doc, heads, options) { + var out = []; + var extend = doc.cm && (doc.cm.display.shift || doc.extend); + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + out[i2] = extendRange(doc.sel.ranges[i2], heads[i2], null, extend); } - return false; + var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); + setSelection(doc, newSel, options); } - - /* eslint-disable max-len */ - - // Currently without astral characters support. - function isPunctChar(ch) { - return ucmicro__namespace.P.test(ch) || ucmicro__namespace.S.test(ch); + function replaceOneSelection(doc, i2, range2, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i2] = range2; + setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); } - - // Markdown ASCII punctuation characters. - // - // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ - // http://spec.commonmark.org/0.15/#ascii-punctuation-character - // - // Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. - // - function isMdAsciiPunct(ch) { - switch (ch) { - case 0x21 /* ! */: - case 0x22 /* " */: - case 0x23 /* # */: - case 0x24 /* $ */: - case 0x25 /* % */: - case 0x26 /* & */: - case 0x27 /* ' */: - case 0x28 /* ( */: - case 0x29 /* ) */: - case 0x2a /* * */: - case 0x2b /* + */: - case 0x2c /* , */: - case 0x2d /* - */: - case 0x2e /* . */: - case 0x2f /* / */: - case 0x3a /* : */: - case 0x3b /* ; */: - case 0x3c /* < */: - case 0x3d /* = */: - case 0x3e /* > */: - case 0x3f /* ? */: - case 0x40 /* @ */: - case 0x5b /* [ */: - case 0x5c /* \ */: - case 0x5d /* ] */: - case 0x5e /* ^ */: - case 0x5f /* _ */: - case 0x60 /* ` */: - case 0x7b /* { */: - case 0x7c /* | */: - case 0x7d /* } */: - case 0x7e /* ~ */: - return true; - default: - return false; + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function (ranges) { + this.ranges = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + this.ranges[i2] = new Range(clipPos(doc, ranges[i2].anchor), clipPos(doc, ranges[i2].head)); + } + }, + origin: options && options.origin + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) { + signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + } + if (obj.ranges != sel.ranges) { + return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1); + } else { + return sel; } } - - // Hepler to unify [reference labels]. - // - function normalizeReference(str) { - // Trim and collapse whitespace - // - str = str.trim().replace(/\s+/g, " "); - - // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug - // fixed in v12 (couldn't find any details). - // - // So treat this one as a special case - // (remove this when node v10 is no longer supported). - // - if ("ẞ".toLowerCase() === "Ṿ") { - str = str.replace(/ẞ/g, "ß"); + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, + last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); } - - // .toLowerCase().toUpperCase() should get rid of all differences - // between letter variants. - // - // Simple .toLowerCase() doesn't normalize 125 code points correctly, - // and .toUpperCase doesn't normalize 6 of them (list of exceptions: - // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently - // uppercased versions). - // - // Here's an example showing how it happens. Lets take greek letter omega: - // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) - // - // Unicode entries: - // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; - // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 - // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 - // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; - // - // Case-insensitive comparison should treat all of them as equivalent. - // - // But .toLowerCase() doesn't change ϑ (it's already lowercase), - // and .toUpperCase() doesn't change ϴ (already uppercase). - // - // Applying first lower then upper case normalizes any character: - // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' - // - // Note: this is equivalent to unicode case folding; unicode normalization - // is a different step that is not required here. - // - // Final result should be uppercased, because it's later stored in an object - // (this avoid a conflict with Object.prototype members, - // most notably, `__proto__`) - // - return str.toLowerCase().toUpperCase(); } - - // Re-export libraries commonly used in both markdown-it and its plugins, - // so plugins won't have to depend on them explicitly, which reduces their - // bundled size (e.g. a browser build). - // - const lib = { - mdurl: mdurl__namespace, - ucmicro: ucmicro__namespace, - }; - var utils = /*#__PURE__*/ Object.freeze({ - __proto__: null, - arrayReplaceAt: arrayReplaceAt, - assign: assign, - escapeHtml: escapeHtml, - escapeRE: escapeRE, - fromCodePoint: fromCodePoint, - has: has, - isMdAsciiPunct: isMdAsciiPunct, - isPunctChar: isPunctChar, - isSpace: isSpace, - isString: isString, - isValidEntityCode: isValidEntityCode, - isWhitespace: isWhitespace, - lib: lib, - normalizeReference: normalizeReference, - unescapeAll: unescapeAll, - unescapeMd: unescapeMd, - }); - - // Parse link label - // - // this function assumes that first character ("[") already matches; - // returns the end of the label - // - - function parseLinkLabel(state, start, disableNested) { - let level, found, marker, prevPos; - const max = state.posMax; - const oldPos = state.pos; - state.pos = start + 1; - level = 1; - while (state.pos < max) { - marker = state.src.charCodeAt(state.pos); - if (marker === 0x5d /* ] */) { - level--; - if (level === 0) { - found = true; - break; - } - } - prevPos = state.pos; - state.md.inline.skipToken(state); - if (marker === 0x5b /* [ */) { - if (prevPos === state.pos - 1) { - // increase level if we find text `[`, which is not a part of any token - level++; - } else if (disableNested) { - state.pos = oldPos; - return -1; + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { + sel = filterSelectionChange(doc, sel, options); + } + var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") { + ensureCursorVisible(doc.cm); + } + } + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { + return; + } + doc.sel = sel; + if (doc.cm) { + doc.cm.curOp.updateInput = 1; + doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); + } + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i2]; + var newAnchor = skipAtomic(doc, range2.anchor, old && old.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range2.head, old && old.head, bias, mayClear); + if (out || newAnchor != range2.anchor || newHead != range2.head) { + if (!out) { + out = sel.ranges.slice(0, i2); + } + out[i2] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel; + } + function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line); + if (line.markedSpans) { + for (var i2 = 0; i2 < line.markedSpans.length; ++i2) { + var sp = line.markedSpans[i2], + m = sp.marker; + var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; + var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight; + if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) { + break; + } else { + --i2; + continue; + } + } + } + if (!m.atomic) { + continue; + } + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), + diff = void 0; + if (dir < 0 ? preventCursorRight : preventCursorLeft) { + near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); + } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { + return skipAtomicInner(doc, near, pos, dir, mayClear); + } + } + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? preventCursorLeft : preventCursorRight) { + far = movePos(doc, far, dir, far.line == pos.line ? line : null); + } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; } } } - let labelEnd = -1; - if (found) { - labelEnd = state.pos; + return pos; + } + function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true); + if (!found) { + doc.cantEdit = true; + return Pos(doc.first, 0); } - - // restore old state - state.pos = oldPos; - return labelEnd; + return found; } - - // Parse link destination - // - - function parseLinkDestination(str, start, max) { - let code; - let pos = start; - const result = { - ok: false, - pos: 0, - str: "", + function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { + return clipPos(doc, Pos(pos.line - 1)); + } else { + return null; + } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { + return Pos(pos.line + 1, 0); + } else { + return null; + } + } else { + return new Pos(pos.line, pos.ch + dir); + } + } + function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); + } + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { + return obj.canceled = true; + } }; - if (str.charCodeAt(pos) === 0x3c /* < */) { - pos++; - while (pos < max) { - code = str.charCodeAt(pos); - if (code === 0x0a /* \n */) { - return result; + if (update) { + obj.update = function (from, to, text, origin) { + if (from) { + obj.from = clipPos(doc, from); } - if (code === 0x3c /* < */) { - return result; + if (to) { + obj.to = clipPos(doc, to); } - if (code === 0x3e /* > */) { - result.pos = pos + 1; - result.str = unescapeAll(str.slice(start + 1, pos)); - result.ok = true; - return result; + if (text) { + obj.text = text; } - if (code === 0x5c /* \ */ && pos + 1 < max) { - pos += 2; - continue; + if (origin !== void 0) { + obj.origin = origin; } - pos++; + }; + } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) { + signal(doc.cm, "beforeChange", doc.cm, obj); + } + if (obj.canceled) { + if (doc.cm) { + doc.cm.curOp.updateInput = 2; } - - // no closing '>' - return result; + return null; } - - // this should be ... } else { ... branch - - let level = 0; - while (pos < max) { - code = str.charCodeAt(pos); - if (code === 0x20) { - break; + return { + from: obj.from, + to: obj.to, + text: obj.text, + origin: obj.origin + }; + } + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { + return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); } - - // ascii control characters - if (code < 0x20 || code === 0x7f) { + if (doc.cm.state.suppressEdits) { + return; + } + } + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) { + return; + } + } + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i2 = split.length - 1; i2 >= 0; --i2) { + makeChangeInner(doc, { + from: split[i2].from, + to: split[i2].to, + text: i2 ? [""] : change.text, + origin: change.origin + }); + } + } else { + makeChangeInner(doc, change); + } + } + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { + return; + } + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + linkedDocs(doc, function (doc2, sharedHist) { + if (!sharedHist && indexOf(rebased, doc2.history) == -1) { + rebaseHist(doc2.history, change); + rebased.push(doc2.history); + } + makeChangeSingleDoc(doc2, change, null, stretchSpansOverChange(doc2, change)); + }); + } + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + var suppress = doc.cm && doc.cm.state.suppressEdits; + if (suppress && !allowSelectionOnly) { + return; + } + var hist = doc.history, + event, + selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, + dest = type == "undo" ? hist.undone : hist.done; + var i2 = 0; + for (; i2 < source.length; i2++) { + event = source[i2]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { break; } - if (code === 0x5c /* \ */ && pos + 1 < max) { - if (str.charCodeAt(pos + 1) === 0x20) { - break; + } + if (i2 == source.length) { + return; + } + hist.lastOrigin = hist.lastSelOrigin = null; + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, { + clearRedo: false + }); + return; } - pos += 2; - continue; + selAfter = event; + } else if (suppress) { + source.push(event); + return; + } else { + break; + } + } + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({ + changes: antiChanges, + generation: hist.generation + }); + hist.generation = event.generation || ++hist.maxGeneration; + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + var loop = function (i3) { + var change = event.changes[i3]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return {}; } - if (code === 0x28 /* ( */) { - level++; - if (level > 32) { - return result; - } + antiChanges.push(historyChangeFromChange(doc, change)); + var after = i3 ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i3 && doc.cm) { + doc.cm.scrollIntoView({ + from: change.from, + to: changeEnd(change) + }); } - if (code === 0x29 /* ) */) { - if (level === 0) { - break; + var rebased = []; + linkedDocs(doc, function (doc2, sharedHist) { + if (!sharedHist && indexOf(rebased, doc2.history) == -1) { + rebaseHist(doc2.history, change); + rebased.push(doc2.history); } - level--; - } - pos++; + makeChangeSingleDoc(doc2, change, null, mergeOldSpans(doc2, change)); + }); + }; + for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) { + var returned = loop(i$12); + if (returned) return returned.v; } - if (start === pos) { - return result; + } + function shiftDoc(doc, distance) { + if (distance == 0) { + return; } - if (level !== 0) { - return result; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range2) { + return new Range(Pos(range2.anchor.line + distance, range2.anchor.ch), Pos(range2.head.line + distance, range2.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { + regLineChange(doc.cm, l, "gutter"); + } } - result.str = unescapeAll(str.slice(start, pos)); - result.pos = pos; - result.ok = true; - return result; } - - // Parse link title - // - - // Parse link title within `str` in [start, max] range, - // or continue previous parsing if `prev_state` is defined (equal to result of last execution). - // - function parseLinkTitle(str, start, max, prev_state) { - let code; - let pos = start; - const state = { - // if `true`, this is a valid link title - ok: false, - // if `true`, this link can be continued on the next line - can_continue: false, - // if `ok`, it's the position of the first character after the closing marker - pos: 0, - // if `ok`, it's the unescaped title - str: "", - // expected closing marker character code - marker: 0, - }; - if (prev_state) { - // this is a continuation of a previous parseLinkTitle call on the next line, - // used in reference links only - state.str = prev_state.str; - state.marker = prev_state.marker; + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) { + return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + } + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) { + return; + } + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = { + from: Pos(doc.first, 0), + to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], + origin: change.origin + }; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = { + from: change.from, + to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], + origin: change.origin + }; + } + change.removed = getBetween(doc, change.from, change.to); + if (!selAfter) { + selAfter = computeSelAfterChange(doc, change); + } + if (doc.cm) { + makeChangeSingleDocInEditor(doc.cm, change, spans); } else { - if (pos >= max) { - return state; + updateDoc(doc, change, spans); + } + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { + doc.cantEdit = false; + } + } + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, + display = cm.display, + from = change.from, + to = change.to; + var recomputeMaxLength = false, + checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + if (doc.sel.contains(change.from, change.to) > -1) { + signalCursorActivity(cm); + } + updateDoc(doc, change, spans, estimateHeight(cm)); + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) { + cm.curOp.updateMaxLine = true; } - let marker = str.charCodeAt(pos); - if ( - marker !== 0x22 /* " */ && - marker !== 0x27 /* ' */ && - marker !== 0x28 /* ( */ - ) { - return state; + } + retreatFrontier(doc, from.line); + startWorker(cm, 400); + var lendiff = change.text.length - (to.line - from.line) - 1; + if (change.full) { + regChange(cm); + } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { + regLineChange(cm, from.line, "text"); + } else { + regChange(cm, from.line, to.line + 1, lendiff); + } + var changesHandler = hasHandler(cm, "changes"), + changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from, + to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) { + signalLater(cm, "change", cm, obj); } - start++; - pos++; - - // if opening marker is "(", switch it to closing marker ")" - if (marker === 0x28) { - marker = 0x29; - } - state.marker = marker; - } - while (pos < max) { - code = str.charCodeAt(pos); - if (code === state.marker) { - state.pos = pos + 1; - state.str += unescapeAll(str.slice(start, pos)); - state.ok = true; - return state; - } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) { - return state; - } else if (code === 0x5c /* \ */ && pos + 1 < max) { - pos++; + if (changesHandler) { + (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } - pos++; } - - // no closing marker found, but this link title may continue on the next line (for references) - state.can_continue = true; - state.str += unescapeAll(str.slice(start, pos)); - return state; + cm.display.selForContextMenu = null; } - - // Just a shortcut for bulk export - - var helpers = /*#__PURE__*/ Object.freeze({ - __proto__: null, - parseLinkDestination: parseLinkDestination, - parseLinkLabel: parseLinkLabel, - parseLinkTitle: parseLinkTitle, - }); - - /** - * class Renderer - * - * Generates HTML from parsed token stream. Each instance has independent - * copy of rules. Those can be rewritten with ease. Also, you can add new - * rules if you create plugin and adds new token types. - **/ - - const default_rules = {}; - default_rules.code_inline = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - return ( - "" + - escapeHtml(token.content) + - "" - ); - }; - default_rules.code_block = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - return ( - "" + - escapeHtml(tokens[idx].content) + - "\n" - ); - }; - default_rules.fence = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - const info = token.info ? unescapeAll(token.info).trim() : ""; - let langName = ""; - let langAttrs = ""; - if (info) { - const arr = info.split(/(\s+)/g); - langName = arr[0]; - langAttrs = arr.slice(2).join(""); - } - let highlighted; - if (options.highlight) { - highlighted = - options.highlight(token.content, langName, langAttrs) || - escapeHtml(token.content); - } else { - highlighted = escapeHtml(token.content); + function replaceRange(doc, code, from, to, origin) { + var assign; + if (!to) { + to = from; } - if (highlighted.indexOf("${highlighted}
    \n`; } - return `
    ${highlighted}
    \n`; - }; - default_rules.image = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - - // "alt" attr MUST be set, even if empty. Because it's mandatory and - // should be placed on proper position for tests. - // - // Replace content with actual value - - token.attrs[token.attrIndex("alt")][1] = slf.renderInlineAsText( - token.children, - options, - env - ); - return slf.renderToken(tokens, idx, options); - }; - default_rules.hardbreak = function (tokens, idx, options /*, env */) { - return options.xhtmlOut ? "
    \n" : "
    \n"; - }; - default_rules.softbreak = function (tokens, idx, options /*, env */) { - return options.breaks - ? options.xhtmlOut - ? "
    \n" - : "
    \n" - : "\n"; - }; - default_rules.text = function (tokens, idx /*, options, env */) { - return escapeHtml(tokens[idx].content); - }; - default_rules.html_block = function (tokens, idx /*, options, env */) { - return tokens[idx].content; - }; - default_rules.html_inline = function (tokens, idx /*, options, env */) { - return tokens[idx].content; - }; - - /** - * new Renderer() - * - * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. - **/ - function Renderer() { - /** - * Renderer#rules -> Object - * - * Contains render rules for tokens. Can be updated and extended. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.renderer.rules.strong_open = function () { return ''; }; - * md.renderer.rules.strong_close = function () { return ''; }; - * - * var result = md.renderInline(...); - * ``` - * - * Each rule is called as independent static function with fixed signature: - * - * ```javascript - * function my_token_render(tokens, idx, options, env, renderer) { - * // ... - * return renderedHTML; - * } - * ``` - * - * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs) - * for more details and examples. - **/ - this.rules = assign({}, default_rules); } - - /** - * Renderer.renderAttrs(token) -> String - * - * Render token attributes to string. - **/ - Renderer.prototype.renderAttrs = function renderAttrs(token) { - let i, l, result; - if (!token.attrs) { - return ""; - } - result = ""; - for (i = 0, l = token.attrs.length; i < l; i++) { - result += - " " + - escapeHtml(token.attrs[i][0]) + - '="' + - escapeHtml(token.attrs[i][1]) + - '"'; + function rebaseHist(hist, change) { + var from = change.from.line, + to = change.to.line, + diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + function changeLine(doc, handle, changeType, op) { + var no = handle, + line = handle; + if (typeof handle == "number") { + line = getLine(doc, clipLine(doc, handle)); + } else { + no = lineNo(handle); } - return result; - }; - - /** - * Renderer.renderToken(tokens, idx, options) -> String - * - tokens (Array): list of tokens - * - idx (Numbed): token index to render - * - options (Object): params of parser instance - * - * Default token renderer. Can be overriden by custom function - * in [[Renderer#rules]]. - **/ - Renderer.prototype.renderToken = function renderToken( - tokens, - idx, - options - ) { - const token = tokens[idx]; - let result = ""; - - // Tight list paragraphs - if (token.hidden) { - return ""; + if (no == null) { + return null; } - - // Insert a newline between hidden paragraph and subsequent opening - // block-level tag. - // - // For example, here we should insert a newline before blockquote: - // - a - // > - // - if ( - token.block && - token.nesting !== -1 && - idx && - tokens[idx - 1].hidden - ) { - result += "\n"; + if (op(line, no) && doc.cm) { + regLineChange(doc.cm, no, changeType); } - - // Add token name, e.g. ``. - // - needLf = false; - } + this.height = height; + } + LeafChunk.prototype = { + chunkSize: function () { + return this.lines.length; + }, + // Remove the n lines at offset 'at'. + removeInner: function (at, n) { + for (var i2 = at, e = at + n; i2 < e; ++i2) { + var line = this.lines[i2]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function (lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function (at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; + } + }, + // Used to iterate over a part of the tree. + iterN: function (at, n, op) { + for (var e = at + n; at < e; ++at) { + if (op(this.lines[at])) { + return true; } } } - result += needLf ? ">\n" : ">"; - return result; }; - - /** - * Renderer.renderInline(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * The same as [[Renderer.render]], but for single token of `inline` type. - **/ - Renderer.prototype.renderInline = function (tokens, options, env) { - let result = ""; - const rules = this.rules; - for (let i = 0, len = tokens.length; i < len; i++) { - const type = tokens[i].type; - if (typeof rules[type] !== "undefined") { - result += rules[type](tokens, i, options, env, this); - } else { - result += this.renderToken(tokens, i, options); + function BranchChunk(children) { + this.children = children; + var size = 0, + height = 0; + for (var i2 = 0; i2 < children.length; ++i2) { + var ch = children[i2]; + size += ch.chunkSize(); + height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + BranchChunk.prototype = { + chunkSize: function () { + return this.size; + }, + removeInner: function (at, n) { + this.size -= n; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), + oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { + this.children.splice(i2--, 1); + child.parent = null; + } + if ((n -= rm) == 0) { + break; + } + at = 0; + } else { + at -= sz; + } } - } - return result; - }; - - /** internal - * Renderer.renderInlineAsText(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * Special kludge for image `alt` attributes to conform CommonMark spec. - * Don't try to use it! Spec requires to show `alt` content with stripped markup, - * instead of simple escaping. - **/ - Renderer.prototype.renderInlineAsText = function ( - tokens, - options, - env - ) { - let result = ""; - for (let i = 0, len = tokens.length; i < len; i++) { - switch (tokens[i].type) { - case "text": - result += tokens[i].content; - break; - case "image": - result += this.renderInlineAsText( - tokens[i].children, - options, - env - ); - break; - case "html_inline": - case "html_block": - result += tokens[i].content; - break; - case "softbreak": - case "hardbreak": - result += "\n"; + if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function (lines) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + this.children[i2].collapse(lines); + } + }, + insertInner: function (at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + var remaining = child.lines.length % 25 + 25; + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); + child.height -= leaf.height; + this.children.splice(++i2, 0, leaf); + leaf.parent = this; + } + child.lines = child.lines.slice(0, remaining); + this.maybeSpill(); + } break; - // all other tokens are skipped + } + at -= sz; } - } - return result; - }; - - /** - * Renderer.render(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * Takes token stream and generates HTML. Probably, you will never need to call - * this method directly. - **/ - Renderer.prototype.render = function (tokens, options, env) { - let result = ""; - const rules = this.rules; - for (let i = 0, len = tokens.length; i < len; i++) { - const type = tokens[i].type; - if (type === "inline") { - result += this.renderInline(tokens[i].children, options, env); - } else if (typeof rules[type] !== "undefined") { - result += rules[type](tokens, i, options, env, this); - } else { - result += this.renderToken(tokens, i, options, env); + }, + // When a node has grown, check whether it should be split. + maybeSpill: function () { + if (this.children.length <= 10) { + return; + } + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function (at, n, op) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) { + return true; + } + if ((n -= used) == 0) { + break; + } + at = 0; + } else { + at -= sz; + } } } - return result; }; - - /** - * class Ruler - * - * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and - * [[MarkdownIt#inline]] to manage sequences of functions (rules): - * - * - keep rules in defined order - * - assign the name to each rule - * - enable/disable rules - * - add/replace rules - * - allow assign rules to additional named chains (in the same) - * - cacheing lists of active rules - * - * You will not need use this class directly until write plugins. For simple - * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and - * [[MarkdownIt.use]]. - **/ - - /** - * new Ruler() - **/ - function Ruler() { - // List of added rules. Each element is: - // - // { - // name: XXX, - // enabled: Boolean, - // fn: Function(), - // alt: [ name2, name3 ] - // } - // - this.__rules__ = []; - - // Cached rule chains. - // - // First level - chain name, '' for default. - // Second level - diginal anchor for fast filtering by charcodes. - // - this.__cache__ = null; - } - - // Helper methods, should not be used directly - - // Find rule index by name - // - Ruler.prototype.__find__ = function (name) { - for (let i = 0; i < this.__rules__.length; i++) { - if (this.__rules__[i].name === name) { - return i; + var LineWidget = function (doc, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) { + this[opt] = options[opt]; + } } } - return -1; + this.doc = doc; + this.node = node; }; - - // Build rules lookup cache - // - Ruler.prototype.__compile__ = function () { - const self = this; - const chains = [""]; - - // collect unique names - self.__rules__.forEach(function (rule) { - if (!rule.enabled) { - return; + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, + ws = this.line.widgets, + line = this.line, + no = lineNo(line); + if (no == null || !ws) { + return; + } + for (var i2 = 0; i2 < ws.length; ++i2) { + if (ws[i2] == this) { + ws.splice(i2--, 1); } - rule.alt.forEach(function (altName) { - if (chains.indexOf(altName) < 0) { - chains.push(altName); - } - }); - }); - self.__cache__ = {}; - chains.forEach(function (chain) { - self.__cache__[chain] = []; - self.__rules__.forEach(function (rule) { - if (!rule.enabled) { - return; - } - if (chain && rule.alt.indexOf(chain) < 0) { - return; - } - self.__cache__[chain].push(rule.fn); + } + if (!ws.length) { + line.widgets = null; + } + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); }); - }); - }; - - /** - * Ruler.at(name, fn [, options]) - * - name (String): rule name to replace. - * - fn (Function): new rule function. - * - options (Object): new rule options (not mandatory). - * - * Replace rule by name with new function & options. Throws error if name not - * found. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * Replace existing typographer replacement rule with new one: - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.core.ruler.at('replacements', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.at = function (name, fn, options) { - const index = this.__find__(name); - const opt = options || {}; - if (index === -1) { - throw new Error("Parser rule not found: " + name); - } - this.__rules__[index].fn = fn; - this.__rules__[index].alt = opt.alt || []; - this.__cache__ = null; - }; - - /** - * Ruler.before(beforeName, ruleName, fn [, options]) - * - beforeName (String): new rule will be added before this one. - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Add new rule to chain before one with given name. See also - * [[Ruler.after]], [[Ruler.push]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.before = function (beforeName, ruleName, fn, options) { - const index = this.__find__(beforeName); - const opt = options || {}; - if (index === -1) { - throw new Error("Parser rule not found: " + beforeName); - } - this.__rules__.splice(index, 0, { - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [], - }); - this.__cache__ = null; - }; - - /** - * Ruler.after(afterName, ruleName, fn [, options]) - * - afterName (String): new rule will be added after this one. - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Add new rule to chain after one with given name. See also - * [[Ruler.before]], [[Ruler.push]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.inline.ruler.after('text', 'my_rule', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.after = function (afterName, ruleName, fn, options) { - const index = this.__find__(afterName); - const opt = options || {}; - if (index === -1) { - throw new Error("Parser rule not found: " + afterName); - } - this.__rules__.splice(index + 1, 0, { - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [], - }); - this.__cache__ = null; - }; - - /** - * Ruler.push(ruleName, fn [, options]) - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Push new rule to the end of chain. See also - * [[Ruler.before]], [[Ruler.after]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.core.ruler.push('my_rule', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.push = function (ruleName, fn, options) { - const opt = options || {}; - this.__rules__.push({ - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [], - }); - this.__cache__ = null; + signalLater(cm, "lineWidgetCleared", cm, this, no); + } }; - - /** - * Ruler.enable(list [, ignoreInvalid]) -> Array - * - list (String|Array): list of rule names to enable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable rules with given names. If any rule name not found - throw Error. - * Errors can be disabled by second param. - * - * Returns list of found rule names (if no exception happened). - * - * See also [[Ruler.disable]], [[Ruler.enableOnly]]. - **/ - Ruler.prototype.enable = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; + LineWidget.prototype.changed = function () { + var this$1$1 = this; + var oldH = this.height, + cm = this.doc.cm, + line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) { + return; } - const result = []; - - // Search by name and enable - list.forEach(function (name) { - const idx = this.__find__(name); - if (idx < 0) { - if (ignoreInvalid) { - return; + if (!lineIsHidden(this.doc, line)) { + updateLineHeight(line, line.height + diff); + } + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line)); + }); + } + }; + eventMixin(LineWidget); + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) { + addToScrollTop(cm, diff); + } + } + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) { + cm.display.alignWidgets = true; + } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) { + widgets.push(widget); + } else { + widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); + } + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) { + addToScrollTop(cm, widget.height); } - throw new Error("Rules manager: invalid rule name " + name); + cm.curOp.forceUpdate = true; } - this.__rules__[idx].enabled = true; - result.push(name); - }, this); - this.__cache__ = null; - return result; - }; - - /** - * Ruler.enableOnly(list [, ignoreInvalid]) - * - list (String|Array): list of rule names to enable (whitelist). - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable rules with given names, and disable everything else. If any rule name - * not found - throw Error. Errors can be disabled by second param. - * - * See also [[Ruler.disable]], [[Ruler.enable]]. - **/ - Ruler.prototype.enableOnly = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; - } - this.__rules__.forEach(function (rule) { - rule.enabled = false; + return true; }); - this.enable(list, ignoreInvalid); + if (cm) { + signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); + } + return widget; + } + var nextMarkerId = 0; + var TextMarker = function (doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; }; - - /** - * Ruler.disable(list [, ignoreInvalid]) -> Array - * - list (String|Array): list of rule names to disable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Disable rules with given names. If any rule name not found - throw Error. - * Errors can be disabled by second param. - * - * Returns list of found rule names (if no exception happened). - * - * See also [[Ruler.enable]], [[Ruler.enableOnly]]. - **/ - Ruler.prototype.disable = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { + return; } - const result = []; - - // Search by name and disable - list.forEach(function (name) { - const idx = this.__find__(name); - if (idx < 0) { - if (ignoreInvalid) { - return; + var cm = this.doc.cm, + withOp = cm && !cm.curOp; + if (withOp) { + startOperation(cm); + } + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) { + signalLater(this, "clear", found.from, found.to); + } + } + var min = null, + max = null; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) { + regLineChange(cm, lineNo(line), "text"); + } else if (cm) { + if (span.to != null) { + max = lineNo(line); + } + if (span.from != null) { + min = lineNo(line); } - throw new Error("Rules manager: invalid rule name " + name); } - this.__rules__[idx].enabled = false; - result.push(name); - }, this); - this.__cache__ = null; - return result; - }; - - /** - * Ruler.getRules(chainName) -> Array - * - * Return array of active functions (rules) for given chain name. It analyzes - * rules configuration, compiles caches if not exists and returns result. - * - * Default chain name is `''` (empty string). It can't be skipped. That's - * done intentionally, to keep signature monomorphic for high speed. - **/ - Ruler.prototype.getRules = function (chainName) { - if (this.__cache__ === null) { - this.__compile__(); + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { + updateLineHeight(line, textHeight(cm.display)); + } } - - // Chain can be empty, if rules disabled. But we still have to return Array. - return this.__cache__[chainName] || []; - }; - - // Token class - - /** - * class Token - **/ - - /** - * new Token(type, tag, nesting) - * - * Create new token and fill passed properties. - **/ - function Token(type, tag, nesting) { - /** - * Token#type -> String - * - * Type of the token (string, e.g. "paragraph_open") - **/ - this.type = type; - - /** - * Token#tag -> String - * - * html tag name, e.g. "p" - **/ - this.tag = tag; - - /** - * Token#attrs -> Array - * - * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` - **/ - this.attrs = null; - - /** - * Token#map -> Array - * - * Source map info. Format: `[ line_begin, line_end ]` - **/ - this.map = null; - - /** - * Token#nesting -> Number - * - * Level change (number in {-1, 0, 1} set), where: - * - * - `1` means the tag is opening - * - `0` means the tag is self-closing - * - `-1` means the tag is closing - **/ - this.nesting = nesting; - - /** - * Token#level -> Number - * - * nesting level, the same as `state.level` - **/ - this.level = 0; - - /** - * Token#children -> Array - * - * An array of child nodes (inline and img tokens) - **/ - this.children = null; - - /** - * Token#content -> String - * - * In a case of self-closing tag (code, html, fence, etc.), - * it has contents of this tag. - **/ - this.content = ""; - - /** - * Token#markup -> String - * - * '*' or '_' for emphasis, fence string for fence, etc. - **/ - this.markup = ""; - - /** - * Token#info -> String - * - * Additional information: - * - * - Info string for "fence" tokens - * - The value "auto" for autolink "link_open" and "link_close" tokens - * - The string value of the item marker for ordered-list "list_item_open" tokens - **/ - this.info = ""; - - /** - * Token#meta -> Object - * - * A place for plugins to store an arbitrary data - **/ - this.meta = null; - - /** - * Token#block -> Boolean - * - * True for block-level tokens, false for inline tokens. - * Used in renderer to calculate line breaks - **/ - this.block = false; - - /** - * Token#hidden -> Boolean - * - * If it's true, ignore this element when rendering. Used for tight lists - * to hide paragraphs. - **/ - this.hidden = false; - } - - /** - * Token.attrIndex(name) -> Number - * - * Search attribute index by name. - **/ - Token.prototype.attrIndex = function attrIndex(name) { - if (!this.attrs) { - return -1; + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i$12 = 0; i$12 < this.lines.length; ++i$12) { + var visual = visualLine(this.lines[i$12]), + len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + } + if (min != null && cm && this.collapsed) { + regChange(cm, min, max + 1); } - const attrs = this.attrs; - for (let i = 0, len = attrs.length; i < len; i++) { - if (attrs[i][0] === name) { - return i; + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) { + reCheckSelection(cm.doc); } } - return -1; + if (cm) { + signalLater(cm, "markerCleared", cm, this, min, max); + } + if (withOp) { + endOperation(cm); + } + if (this.parent) { + this.parent.clear(); + } }; - - /** - * Token.attrPush(attrData) - * - * Add `[ name, value ]` attribute to list. Init attrs if necessary - **/ - Token.prototype.attrPush = function attrPush(attrData) { - if (this.attrs) { - this.attrs.push(attrData); - } else { - this.attrs = [attrData]; + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") { + side = 1; + } + var from, to; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) { + return from; + } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) { + return to; + } + } } + return from && { + from, + to + }; }; - - /** - * Token.attrSet(name, value) - * - * Set `name` attribute to `value`. Override old value if exists. - **/ - Token.prototype.attrSet = function attrSet(name, value) { - const idx = this.attrIndex(name); - const attrData = [name, value]; - if (idx < 0) { - this.attrPush(attrData); - } else { - this.attrs[idx] = attrData; + TextMarker.prototype.changed = function () { + var this$1$1 = this; + var pos = this.find(-1, true), + widget = this, + cm = this.doc.cm; + if (!pos || !cm) { + return; } + runInOp(cm, function () { + var line = pos.line, + lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) { + updateLineHeight(line, line.height + dHeight); + } + } + signalLater(cm, "markerChanged", cm, this$1$1); + }); }; - - /** - * Token.attrGet(name) - * - * Get the value of attribute `name`, or null if it does not exist. - **/ - Token.prototype.attrGet = function attrGet(name) { - const idx = this.attrIndex(name); - let value = null; - if (idx >= 0) { - value = this.attrs[idx][1]; + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); + } } - return value; + this.lines.push(line); }; - - /** - * Token.attrJoin(name, value) - * - * Join value to existing attribute via space. Or create new attribute if not - * exists. Useful to operate with token classes. - **/ - Token.prototype.attrJoin = function attrJoin(name, value) { - const idx = this.attrIndex(name); - if (idx < 0) { - this.attrPush([name, value]); - } else { - this.attrs[idx][1] = this.attrs[idx][1] + " " + value; + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; - - // Core state object - // - - function StateCore(src, md, env) { - this.src = src; - this.env = env; - this.tokens = []; - this.inlineMode = false; - this.md = md; // link to parser instance - } - - // re-export Token class to use in core rules - StateCore.prototype.Token = Token; - - // Normalize input string - - // https://spec.commonmark.org/0.29/#line-ending - const NEWLINES_RE = /\r\n?|\n/g; - const NULL_RE = /\0/g; - function normalize(state) { - let str; - - // Normalize newlines - str = state.src.replace(NEWLINES_RE, "\n"); - - // Replace NULL characters - str = str.replace(NULL_RE, "\uFFFD"); - state.src = str; - } - function block(state) { - let token; - if (state.inlineMode) { - token = new state.Token("inline", "", 0); - token.content = state.src; - token.map = [0, 1]; - token.children = []; - state.tokens.push(token); - } else { - state.md.block.parse(state.src, state.md, state.env, state.tokens); + eventMixin(TextMarker); + function markText(doc, from, to, options, type) { + if (options && options.shared) { + return markTextShared(doc, from, to, options, type); } - } - function inline(state) { - const tokens = state.tokens; - - // Parse inlines - for (let i = 0, l = tokens.length; i < l; i++) { - const tok = tokens[i]; - if (tok.type === "inline") { - state.md.inline.parse( - tok.content, - state.md, - state.env, - tok.children - ); + if (doc.cm && !doc.cm.curOp) { + return operation(doc.cm, markText)(doc, from, to, options, type); + } + var marker = new TextMarker(doc, type), + diff = cmp(from, to); + if (options) { + copyObj(options, marker, false); + } + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { + return marker; + } + if (marker.replacedWith) { + marker.collapsed = true; + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) { + marker.widgetNode.setAttribute("cm-ignore-events", "true"); + } + if (options.insertLeft) { + marker.widgetNode.insertLeft = true; } } - } - - // Replace link-like texts with link nodes. - // - // Currently restricted by `md.validateLink()` to http/https/ftp - // - - function isLinkOpen$1(str) { - return /^\s]/i.test(str); - } - function isLinkClose$1(str) { - return /^<\/a\s*>/i.test(str); - } - function linkify$1(state) { - const blockTokens = state.tokens; - if (!state.md.options.linkify) { - return; + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { + throw new Error("Inserting collapsed marker partially overlapping an existing one"); + } + seeCollapsedSpans(); } - for (let j = 0, l = blockTokens.length; j < l; j++) { - if ( - blockTokens[j].type !== "inline" || - !state.md.linkify.pretest(blockTokens[j].content) - ) { - continue; + if (marker.addToHistory) { + addChangeToHistory(doc, { + from, + to, + origin: "markText" + }, doc.sel, NaN); + } + var curLine = from.line, + cm = doc.cm, + updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { + updateMaxLine = true; } - let tokens = blockTokens[j].children; - let htmlLinkLevel = 0; - - // We scan from the end, to keep position when new tags added. - // Use reversed logic in links start/end match - for (let i = tokens.length - 1; i >= 0; i--) { - const currentToken = tokens[i]; - - // Skip content of markdown links - if (currentToken.type === "link_close") { - i--; - while ( - tokens[i].level !== currentToken.level && - tokens[i].type !== "link_open" - ) { - i--; - } - continue; - } - - // Skip content of html tag links - if (currentToken.type === "html_inline") { - if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) { - htmlLinkLevel--; - } - if (isLinkClose$1(currentToken.content)) { - htmlLinkLevel++; - } - } - if (htmlLinkLevel > 0) { - continue; + if (marker.collapsed && curLine != from.line) { + updateLineHeight(line, 0); + } + addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); + ++curLine; + }); + if (marker.collapsed) { + doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { + updateLineHeight(line, 0); } - if ( - currentToken.type === "text" && - state.md.linkify.test(currentToken.content) - ) { - const text = currentToken.content; - let links = state.md.linkify.match(text); - - // Now split string to nodes - const nodes = []; - let level = currentToken.level; - let lastPos = 0; - - // forbid escape sequence at the start of the string, - // this avoids http\://example.com/ from being linkified as - // http://example.com/ - if ( - links.length > 0 && - links[0].index === 0 && - i > 0 && - tokens[i - 1].type === "text_special" - ) { - links = links.slice(1); - } - for (let ln = 0; ln < links.length; ln++) { - const url = links[ln].url; - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) { - continue; - } - let urlText = links[ln].text; - - // Linkifier might send raw hostnames like "example.com", where url - // starts with domain name. So we prepend http:// in those cases, - // and remove it afterwards. - // - if (!links[ln].schema) { - urlText = state.md - .normalizeLinkText("http://" + urlText) - .replace(/^http:\/\//, ""); - } else if ( - links[ln].schema === "mailto:" && - !/^mailto:/i.test(urlText) - ) { - urlText = state.md - .normalizeLinkText("mailto:" + urlText) - .replace(/^mailto:/, ""); - } else { - urlText = state.md.normalizeLinkText(urlText); - } - const pos = links[ln].index; - if (pos > lastPos) { - const token = new state.Token("text", "", 0); - token.content = text.slice(lastPos, pos); - token.level = level; - nodes.push(token); - } - const token_o = new state.Token("link_open", "a", 1); - token_o.attrs = [["href", fullUrl]]; - token_o.level = level++; - token_o.markup = "linkify"; - token_o.info = "auto"; - nodes.push(token_o); - const token_t = new state.Token("text", "", 0); - token_t.content = urlText; - token_t.level = level; - nodes.push(token_t); - const token_c = new state.Token("link_close", "a", -1); - token_c.level = --level; - token_c.markup = "linkify"; - token_c.info = "auto"; - nodes.push(token_c); - lastPos = links[ln].lastIndex; - } - if (lastPos < text.length) { - const token = new state.Token("text", "", 0); - token.content = text.slice(lastPos); - token.level = level; - nodes.push(token); - } - - // replace current node - blockTokens[j].children = tokens = arrayReplaceAt( - tokens, - i, - nodes - ); + }); + } + if (marker.clearOnEnter) { + on(marker, "beforeCursorEnter", function () { + return marker.clear(); + }); + } + if (marker.readOnly) { + seeReadOnlySpans(); + if (doc.history.done.length || doc.history.undone.length) { + doc.clearHistory(); + } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + if (updateMaxLine) { + cm.curOp.updateMaxLine = true; + } + if (marker.collapsed) { + regChange(cm, from.line, to.line + 1); + } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { + for (var i2 = from.line; i2 <= to.line; i2++) { + regLineChange(cm, i2, "text"); } } + if (marker.atomic) { + reCheckSelection(cm.doc); + } + signalLater(cm, "markerAdded", cm, marker); } + return marker; } - - // Simple typographic replacements - // - // (c) (C) → © - // (tm) (TM) → ™ - // (r) (R) → ® - // +- → ± - // ... → … (also ?.... → ?.., !.... → !..) - // ???????? → ???, !!!!! → !!!, `,,` → `,` - // -- → –, --- → — - // - - // TODO: - // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ - // - multiplications 2 x 4 -> 2 × 4 - - const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; - - // Workaround for phantomjs - need regex without /g flag, - // or root check will fail every second time - const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; - const SCOPED_ABBR_RE = /\((c|tm|r)\)/gi; - const SCOPED_ABBR = { - c: "©", - r: "®", - tm: "™", + var SharedTextMarker = function (markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i2 = 0; i2 < markers.length; ++i2) { + markers[i2].parent = this; + } + }; + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { + return; + } + this.explicitlyCleared = true; + for (var i2 = 0; i2 < this.markers.length; ++i2) { + this.markers[i2].clear(); + } + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj); }; - function replaceFn(match, name) { - return SCOPED_ABBR[name.toLowerCase()]; - } - function replace_scoped(inlineTokens) { - let inside_autolink = 0; - for (let i = inlineTokens.length - 1; i >= 0; i--) { - const token = inlineTokens[i]; - if (token.type === "text" && !inside_autolink) { - token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); - } - if (token.type === "link_open" && token.info === "auto") { - inside_autolink--; - } - if (token.type === "link_close" && token.info === "auto") { - inside_autolink++; - } - } - } - function replace_rare(inlineTokens) { - let inside_autolink = 0; - for (let i = inlineTokens.length - 1; i >= 0; i--) { - const token = inlineTokens[i]; - if (token.type === "text" && !inside_autolink) { - if (RARE_RE.test(token.content)) { - token.content = token.content - .replace(/\+-/g, "±") - // .., ..., ....... -> … - // but ?..... & !..... -> ?.. & !.. - .replace(/\.{2,}/g, "…") - .replace(/([?!])…/g, "$1..") - .replace(/([?!]){4,}/g, "$1$1$1") - .replace(/,{2,}/g, ",") - // em-dash - .replace(/(^|[^-])---(?=[^-]|$)/gm, "$1\u2014") - // en-dash - .replace(/(^|\s)--(?=\s|$)/gm, "$1\u2013") - .replace(/(^|[^-\s])--(?=[^-\s]|$)/gm, "$1\u2013"); + eventMixin(SharedTextMarker); + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], + primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc2) { + if (widget) { + options.widgetNode = widget.cloneNode(true); + } + markers.push(markText(doc2, clipPos(doc2, from), clipPos(doc2, to), options, type)); + for (var i2 = 0; i2 < doc2.linked.length; ++i2) { + if (doc2.linked[i2].isParent) { + return; + } + } + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { + return m.parent; + }); + } + function copySharedMarkers(doc, markers) { + for (var i2 = 0; i2 < markers.length; i2++) { + var marker = markers[i2], + pos = marker.find(); + var mFrom = doc.clipPos(pos.from), + mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + function detachSharedMarkers(markers) { + var loop = function (i3) { + var marker = markers[i3], + linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { + return linked.push(d); + }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); } } - if (token.type === "link_open" && token.info === "auto") { - inside_autolink--; + }; + for (var i2 = 0; i2 < markers.length; i2++) loop(i2); + } + var nextDocId = 0; + var Doc = function (text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { + return new Doc(text, mode, firstLine, lineSep, direction); + } + if (firstLine == null) { + firstLine = 0; + } + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.modeFrontier = this.highlightFrontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.direction = direction == "rtl" ? "rtl" : "ltr"; + this.extend = false; + if (typeof text == "string") { + text = this.splitLines(text); + } + updateDoc(this, { + from: start, + to: start, + text + }); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function (from, to, op) { + if (op) { + this.iterN(from - this.first, to - from, op); + } else { + this.iterN(this.first, this.first + this.size, from); + } + }, + // Non-public interface for adding and removing lines. + insert: function (at, lines) { + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + height += lines[i2].height; + } + this.insertInner(at - this.first, lines, height); + }, + remove: function (at, n) { + this.removeInner(at - this.first, n); + }, + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + getValue: function (lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) { + return lines; + } + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function (code) { + var top = Pos(this.first, 0), + last = this.first + this.size - 1; + makeChange(this, { + from: top, + to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), + origin: "setValue", + full: true + }, true); + if (this.cm) { + scrollToCoords(this.cm, 0, 0); + } + setSelection(this, simpleSelection(top), sel_dontScroll); + }), + replaceRange: function (code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function (from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) { + return lines; + } + if (lineSep === "") { + return lines.join(""); + } + return lines.join(lineSep || this.lineSeparator()); + }, + getLine: function (line) { + var l = this.getLineHandle(line); + return l && l.text; + }, + getLineHandle: function (line) { + if (isLine(this, line)) { + return getLine(this, line); + } + }, + getLineNumber: function (line) { + return lineNo(line); + }, + getLineHandleVisualStart: function (line) { + if (typeof line == "number") { + line = getLine(this, line); + } + return visualLine(line); + }, + lineCount: function () { + return this.size; + }, + firstLine: function () { + return this.first; + }, + lastLine: function () { + return this.first + this.size - 1; + }, + clipPos: function (pos) { + return clipPos(this, pos); + }, + getCursor: function (start) { + var range2 = this.sel.primary(), + pos; + if (start == null || start == "head") { + pos = range2.head; + } else if (start == "anchor") { + pos = range2.anchor; + } else if (start == "end" || start == "to" || start === false) { + pos = range2.to(); + } else { + pos = range2.from(); + } + return pos; + }, + listSelections: function () { + return this.sel.ranges; + }, + somethingSelected: function () { + return this.sel.somethingSelected(); + }, + setCursor: docMethodOp(function (line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function (anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function (head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function (heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function (f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function (ranges, primary, options) { + if (!ranges.length) { + return; + } + var out = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + out[i2] = new Range(clipPos(this, ranges[i2].anchor), clipPos(this, ranges[i2].head || ranges[i2].anchor)); + } + if (primary == null) { + primary = Math.min(ranges.length - 1, this.sel.primIndex); } - if (token.type === "link_close" && token.info === "auto") { - inside_autolink++; + setSelection(this, normalizeSelection(this.cm, out, primary), options); + }), + addSelection: docMethodOp(function (anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); + }), + getSelection: function (lineSep) { + var ranges = this.sel.ranges, + lines; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) { + return lines; + } else { + return lines.join(lineSep || this.lineSeparator()); + } + }, + getSelections: function (lineSep) { + var parts = [], + ranges = this.sel.ranges; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); + if (lineSep !== false) { + sel = sel.join(lineSep || this.lineSeparator()); + } + parts[i2] = sel; + } + return parts; + }, + replaceSelection: function (code, collapse, origin) { + var dup = []; + for (var i2 = 0; i2 < this.sel.ranges.length; i2++) { + dup[i2] = code; + } + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function (code, collapse, origin) { + var changes = [], + sel = this.sel; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + changes[i2] = { + from: range2.from(), + to: range2.to(), + text: this.splitLines(code[i2]), + origin + }; } - } - } - function replace(state) { - let blkIdx; - if (!state.md.options.typographer) { - return; - } - for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { - if (state.tokens[blkIdx].type !== "inline") { - continue; + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) { + makeChange(this, changes[i$12]); } - if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { - replace_scoped(state.tokens[blkIdx].children); + if (newSel) { + setSelectionReplaceHistory(this, newSel); + } else if (this.cm) { + ensureCursorVisible(this.cm); } - if (RARE_RE.test(state.tokens[blkIdx].content)) { - replace_rare(state.tokens[blkIdx].children); + }), + undo: docMethodOp(function () { + makeChangeFromHistory(this, "undo"); + }), + redo: docMethodOp(function () { + makeChangeFromHistory(this, "redo"); + }), + undoSelection: docMethodOp(function () { + makeChangeFromHistory(this, "undo", true); + }), + redoSelection: docMethodOp(function () { + makeChangeFromHistory(this, "redo", true); + }), + setExtending: function (val) { + this.extend = val; + }, + getExtending: function () { + return this.extend; + }, + historySize: function () { + var hist = this.history, + done = 0, + undone = 0; + for (var i2 = 0; i2 < hist.done.length; i2++) { + if (!hist.done[i2].ranges) { + ++done; + } } - } - } - - // Convert straight quotation marks to typographic ones - // - - const QUOTE_TEST_RE = /['"]/; - const QUOTE_RE = /['"]/g; - const APOSTROPHE = "\u2019"; /* ’ */ - - function replaceAt(str, index, ch) { - return str.slice(0, index) + ch + str.slice(index + 1); - } - function process_inlines(tokens, state) { - let j; - const stack = []; - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - const thisLevel = tokens[i].level; - for (j = stack.length - 1; j >= 0; j--) { - if (stack[j].level <= thisLevel) { - break; + for (var i$12 = 0; i$12 < hist.undone.length; i$12++) { + if (!hist.undone[i$12].ranges) { + ++undone; } } - stack.length = j + 1; - if (token.type !== "text") { - continue; + return { + undo: done, + redo: undone + }; + }, + clearHistory: function () { + var this$1$1 = this; + this.history = new History(this.history); + linkedDocs(this, function (doc) { + return doc.history = this$1$1.history; + }, true); + }, + markClean: function () { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function (forceSplit) { + if (forceSplit) { + this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } - let text = token.content; - let pos = 0; - let max = text.length; - - /* eslint no-labels:0,block-scoped-var:0 */ - OUTER: while (pos < max) { - QUOTE_RE.lastIndex = pos; - const t = QUOTE_RE.exec(text); - if (!t) { - break; - } - let canOpen = true; - let canClose = true; - pos = t.index + 1; - const isSingle = t[0] === "'"; - - // Find previous character, - // default to space if it's the beginning of the line - // - let lastChar = 0x20; - if (t.index - 1 >= 0) { - lastChar = text.charCodeAt(t.index - 1); - } else { - for (j = i - 1; j >= 0; j--) { - if ( - tokens[j].type === "softbreak" || - tokens[j].type === "hardbreak" - ) - break; // lastChar defaults to 0x20 - if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' - - lastChar = tokens[j].content.charCodeAt( - tokens[j].content.length - 1 - ); - break; - } + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + getHistory: function () { + return { + done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone) + }; + }, + setHistory: function (histData) { + var hist = this.history = new History(this.history); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + setGutterMarker: docMethodOp(function (line, gutterID, value) { + return changeLine(this, line, "gutter", function (line2) { + var markers = line2.gutterMarkers || (line2.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) { + line2.gutterMarkers = null; } - - // Find next character, - // default to space if it's the end of the line - // - let nextChar = 0x20; - if (pos < max) { - nextChar = text.charCodeAt(pos); - } else { - for (j = i + 1; j < tokens.length; j++) { - if ( - tokens[j].type === "softbreak" || - tokens[j].type === "hardbreak" - ) - break; // nextChar defaults to 0x20 - if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' - - nextChar = tokens[j].content.charCodeAt(0); - break; - } + return true; + }); + }), + clearGutter: docMethodOp(function (gutterID) { + var this$1$1 = this; + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null; + if (isEmpty(line.gutterMarkers)) { + line.gutterMarkers = null; + } + return true; + }); } - const isLastPunctChar = - isMdAsciiPunct(lastChar) || - isPunctChar(String.fromCharCode(lastChar)); - const isNextPunctChar = - isMdAsciiPunct(nextChar) || - isPunctChar(String.fromCharCode(nextChar)); - const isLastWhitespace = isWhitespace(lastChar); - const isNextWhitespace = isWhitespace(nextChar); - if (isNextWhitespace) { - canOpen = false; - } else if (isNextPunctChar) { - if (!(isLastWhitespace || isLastPunctChar)) { - canOpen = false; - } + }); + }), + lineInfo: function (line) { + var n; + if (typeof line == "number") { + if (!isLine(this, line)) { + return null; } - if (isLastWhitespace) { - canClose = false; - } else if (isLastPunctChar) { - if (!(isNextWhitespace || isNextPunctChar)) { - canClose = false; - } + n = line; + line = getLine(this, line); + if (!line) { + return null; } - if (nextChar === 0x22 /* " */ && t[0] === '"') { - if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { - // special case: 1"" - count first quote as an inch - canClose = canOpen = false; - } + } else { + n = lineNo(line); + if (n == null) { + return null; } - if (canOpen && canClose) { - // Replace quotes in the middle of punctuation sequence, but not - // in the middle of the words, i.e.: - // - // 1. foo " bar " baz - not replaced - // 2. foo-"-bar-"-baz - replaced - // 3. foo"bar"baz - not replaced - // - canOpen = isLastPunctChar; - canClose = isNextPunctChar; + } + return { + line: n, + handle: line, + text: line.text, + gutterMarkers: line.gutterMarkers, + textClass: line.textClass, + bgClass: line.bgClass, + wrapClass: line.wrapClass, + widgets: line.widgets + }; + }, + addLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop2]) { + line[prop2] = cls; + } else if (classTest(cls).test(line[prop2])) { + return false; + } else { + line[prop2] += " " + cls; } - if (!canOpen && !canClose) { - // middle of word - if (isSingle) { - token.content = replaceAt(token.content, t.index, APOSTROPHE); + return true; + }); + }), + removeLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop2]; + if (!cur) { + return false; + } else if (cls == null) { + line[prop2] = null; + } else { + var found = cur.match(classTest(cls)); + if (!found) { + return false; } - continue; + var end = found.index + found[0].length; + line[prop2] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } - if (canClose) { - // this could be a closing quote, rewind the stack to get a match - for (j = stack.length - 1; j >= 0; j--) { - let item = stack[j]; - if (stack[j].level < thisLevel) { - break; + return true; + }); + }), + addLineWidget: docMethodOp(function (handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function (widget) { + widget.clear(); + }, + markText: function (from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); + }, + setBookmark: function (pos, options) { + var realOpts = { + replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, + shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents + }; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function (pos) { + pos = clipPos(this, pos); + var markers = [], + spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { + markers.push(span.marker.parent || span.marker); + } + } + } + return markers; + }, + findMarks: function (from, to, filter) { + from = clipPos(this, from); + to = clipPos(this, to); + var found = [], + lineNo2 = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; i2++) { + var span = spans[i2]; + if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { + found.push(span.marker.parent || span.marker); } - if ( - item.single === isSingle && - stack[j].level === thisLevel - ) { - item = stack[j]; - let openQuote; - let closeQuote; - if (isSingle) { - openQuote = state.md.options.quotes[2]; - closeQuote = state.md.options.quotes[3]; - } else { - openQuote = state.md.options.quotes[0]; - closeQuote = state.md.options.quotes[1]; - } - - // replace token.content *before* tokens[item.token].content, - // because, if they are pointing at the same token, replaceAt - // could mess up indices when quote length != 1 - token.content = replaceAt( - token.content, - t.index, - closeQuote - ); - tokens[item.token].content = replaceAt( - tokens[item.token].content, - item.pos, - openQuote - ); - pos += closeQuote.length - 1; - if (item.token === i) { - pos += openQuote.length - 1; - } - text = token.content; - max = text.length; - stack.length = j; - continue OUTER; + } + } + ++lineNo2; + }); + return found; + }, + getAllMarks: function () { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + if (sps[i2].from != null) { + markers.push(sps[i2].marker); } } } - if (canOpen) { - stack.push({ - token: i, - pos: t.index, - single: isSingle, - level: thisLevel, - }); - } else if (canClose && isSingle) { - token.content = replaceAt(token.content, t.index, APOSTROPHE); + }); + return markers; + }, + posFromIndex: function (off2) { + var ch, + lineNo2 = this.first, + sepSize = this.lineSeparator().length; + this.iter(function (line) { + var sz = line.text.length + sepSize; + if (sz > off2) { + ch = off2; + return true; } + off2 -= sz; + ++lineNo2; + }); + return clipPos(this, Pos(lineNo2, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) { + return 0; } - } - } - function smartquotes(state) { - /* eslint max-depth:0 */ - if (!state.md.options.typographer) { - return; - } - for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { - if ( - state.tokens[blkIdx].type !== "inline" || - !QUOTE_TEST_RE.test(state.tokens[blkIdx].content) - ) { - continue; + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + sepSize; + }); + return index; + }, + copy: function (copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); + doc.scrollTop = this.scrollTop; + doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + linkedDoc: function (options) { + if (!options) { + options = {}; } - process_inlines(state.tokens[blkIdx].children, state); - } - } - - // Join raw text tokens with the rest of the text - // - // This is set as a separate rule to provide an opportunity for plugins - // to run text replacements after text join, but before escape join. - // - // For example, `\:)` shouldn't be replaced with an emoji. - // - - function text_join(state) { - let curr, last; - const blockTokens = state.tokens; - const l = blockTokens.length; - for (let j = 0; j < l; j++) { - if (blockTokens[j].type !== "inline") continue; - const tokens = blockTokens[j].children; - const max = tokens.length; - for (curr = 0; curr < max; curr++) { - if (tokens[curr].type === "text_special") { - tokens[curr].type = "text"; - } + var from = this.first, + to = this.first + this.size; + if (options.from != null && options.from > from) { + from = options.from; } - for (curr = last = 0; curr < max; curr++) { - if ( - tokens[curr].type === "text" && - curr + 1 < max && - tokens[curr + 1].type === "text" - ) { - // collapse two adjacent text nodes - tokens[curr + 1].content = - tokens[curr].content + tokens[curr + 1].content; - } else { - if (curr !== last) { - tokens[last] = tokens[curr]; - } - last++; - } + if (options.to != null && options.to < to) { + to = options.to; } - if (curr !== last) { - tokens.length = last; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); + if (options.sharedHist) { + copy.history = this.history; } - } - } - - /** internal - * class Core - * - * Top-level rules executor. Glues block/inline parsers and does intermediate - * transformations. - **/ - - const _rules$2 = [ - ["normalize", normalize], - ["block", block], - ["inline", inline], - ["linkify", linkify$1], - ["replacements", replace], - ["smartquotes", smartquotes], - // `text_join` finds `text_special` tokens (for escape sequences) - // and joins them with the rest of the text - ["text_join", text_join], - ]; - - /** - * new Core() - **/ - function Core() { - /** - * Core#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of core rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules$2.length; i++) { - this.ruler.push(_rules$2[i][0], _rules$2[i][1]); - } - } - - /** - * Core.process(state) - * - * Executes core chain rules. - **/ - Core.prototype.process = function (state) { - const rules = this.ruler.getRules(""); - for (let i = 0, l = rules.length; i < l; i++) { - rules[i](state); - } - }; - Core.prototype.State = StateCore; - - // Parser state class - - function StateBlock(src, md, env, tokens) { - this.src = src; - - // link to parser instance - this.md = md; - this.env = env; - - // - // Internal state vartiables - // - - this.tokens = tokens; - this.bMarks = []; // line begin offsets for fast jumps - this.eMarks = []; // line end offsets for fast jumps - this.tShift = []; // offsets of the first non-space characters (tabs not expanded) - this.sCount = []; // indents for each line (tabs expanded) - - // An amount of virtual spaces (tabs expanded) between beginning - // of each line (bMarks) and real beginning of that line. - // - // It exists only as a hack because blockquotes override bMarks - // losing information in the process. - // - // It's used only when expanding tabs, you can think about it as - // an initial tab length, e.g. bsCount=21 applied to string `\t123` - // means first tab should be expanded to 4-21%4 === 3 spaces. - // - this.bsCount = []; - - // block parser variables - - // required block content indent (for example, if we are - // inside a list, it would be positioned after list marker) - this.blkIndent = 0; - this.line = 0; // line index in src - this.lineMax = 0; // lines count - this.tight = false; // loose/tight mode for lists - this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) - this.listIndent = -1; // indent of the current list block (-1 if there isn't any) - - // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' - // used in lists to determine if they interrupt a paragraph - this.parentType = "root"; - this.level = 0; - - // Create caches - // Generate markers. - const s = this.src; - for ( - let start = 0, - pos = 0, - indent = 0, - offset = 0, - len = s.length, - indent_found = false; - pos < len; - pos++ - ) { - const ch = s.charCodeAt(pos); - if (!indent_found) { - if (isSpace(ch)) { - indent++; - if (ch === 0x09) { - offset += 4 - (offset % 4); - } else { - offset++; + (this.linked || (this.linked = [])).push({ + doc: copy, + sharedHist: options.sharedHist + }); + copy.linked = [{ + doc: this, + isParent: true, + sharedHist: options.sharedHist + }]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function (other) { + if (other instanceof CodeMirror) { + other = other.doc; + } + if (this.linked) { + for (var i2 = 0; i2 < this.linked.length; ++i2) { + var link = this.linked[i2]; + if (link.doc != other) { + continue; } - continue; - } else { - indent_found = true; + this.linked.splice(i2, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; } } - if (ch === 0x0a || pos === len - 1) { - if (ch !== 0x0a) { - pos++; - } - this.bMarks.push(start); - this.eMarks.push(pos); - this.tShift.push(indent); - this.sCount.push(offset); - this.bsCount.push(0); - indent_found = false; - indent = 0; - offset = 0; - start = pos + 1; + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) { + return splitIds.push(doc.id); + }, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); } - } - - // Push fake entry to simplify cache bounds checks - this.bMarks.push(s.length); - this.eMarks.push(s.length); - this.tShift.push(0); - this.sCount.push(0); - this.bsCount.push(0); - this.lineMax = this.bMarks.length - 1; // don't count last fake line - } - - // Push new token to "stream". - // - StateBlock.prototype.push = function (type, tag, nesting) { - const token = new Token(type, tag, nesting); - token.block = true; - if (nesting < 0) this.level--; // closing tag - token.level = this.level; - if (nesting > 0) this.level++; // opening tag - - this.tokens.push(token); - return token; - }; - StateBlock.prototype.isEmpty = function isEmpty(line) { - return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; - }; - StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { - for (let max = this.lineMax; from < max; from++) { - if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { - break; + }, + iterLinkedDocs: function (f) { + linkedDocs(this, f); + }, + getMode: function () { + return this.mode; + }, + getEditor: function () { + return this.cm; + }, + splitLines: function (str) { + if (this.lineSep) { + return str.split(this.lineSep); } - } - return from; - }; - - // Skip spaces from given position. - StateBlock.prototype.skipSpaces = function skipSpaces(pos) { - for (let max = this.src.length; pos < max; pos++) { - const ch = this.src.charCodeAt(pos); - if (!isSpace(ch)) { - break; + return splitLinesAuto(str); + }, + lineSeparator: function () { + return this.lineSep || "\n"; + }, + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { + dir = "ltr"; } - } - return pos; - }; - - // Skip spaces from given position in reverse. - StateBlock.prototype.skipSpacesBack = function skipSpacesBack( - pos, - min - ) { - if (pos <= min) { - return pos; - } - while (pos > min) { - if (!isSpace(this.src.charCodeAt(--pos))) { - return pos + 1; + if (dir == this.direction) { + return; } - } - return pos; - }; - - // Skip char codes from given position - StateBlock.prototype.skipChars = function skipChars(pos, code) { - for (let max = this.src.length; pos < max; pos++) { - if (this.src.charCodeAt(pos) !== code) { - break; + this.direction = dir; + this.iter(function (line) { + return line.order = null; + }); + if (this.cm) { + directionChanged(this.cm); } + }) + }); + Doc.prototype.eachLine = Doc.prototype.iter; + var lastDrop = 0; + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; } - return pos; - }; - - // Skip char codes reverse from given position - 1 - StateBlock.prototype.skipCharsBack = function skipCharsBack( - pos, - code, - min - ) { - if (pos <= min) { - return pos; + e_preventDefault(e); + if (ie) { + lastDrop = + /* @__PURE__ */new Date(); } - while (pos > min) { - if (code !== this.src.charCodeAt(--pos)) { - return pos + 1; - } + var pos = posFromMouse(cm, e, true), + files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) { + return; } - return pos; - }; - - // cut lines range from source. - StateBlock.prototype.getLines = function getLines( - begin, - end, - indent, - keepLastLF - ) { - if (begin >= end) { - return ""; - } - const queue = new Array(end - begin); - for (let i = 0, line = begin; line < end; line++, i++) { - let lineIndent = 0; - const lineStart = this.bMarks[line]; - let first = lineStart; - let last; - if (line + 1 < end || keepLastLF) { - // No need for bounds check because we have fake entry on tail. - last = this.eMarks[line] + 1; - } else { - last = this.eMarks[line]; - } - while (first < last && lineIndent < indent) { - const ch = this.src.charCodeAt(first); - if (isSpace(ch)) { - if (ch === 0x09) { - lineIndent += 4 - ((lineIndent + this.bsCount[line]) % 4); - } else { - lineIndent++; - } - } else if (first - lineStart < this.tShift[line]) { - // patched tShift masked characters to look like spaces (blockquotes, list markers) - lineIndent++; - } else { - break; + if (files && files.length && window.FileReader && window.File) { + var n = files.length, + text = Array(n), + read = 0; + var markAsReadAndPasteIfAllFilesAreRead = function () { + if (++read == n) { + operation(cm, function () { + pos = clipPos(cm.doc, pos); + var change = { + from: pos, + to: pos, + text: cm.doc.splitLines(text.filter(function (t) { + return t != null; + }).join(cm.doc.lineSeparator())), + origin: "paste" + }; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); + })(); } - first++; - } - if (lineIndent > indent) { - // partially expanding tabs in code blocks, e.g '\t\tfoobar' - // with indent=2 becomes ' \tfoobar' - queue[i] = - new Array(lineIndent - indent + 1).join(" ") + - this.src.slice(first, last); - } else { - queue[i] = this.src.slice(first, last); - } - } - return queue.join(""); - }; - - // re-export Token class to use in block rules - StateBlock.prototype.Token = Token; - - // GFM table, https://github.github.com/gfm/#tables-extension- - - // Limit the amount of empty autocompleted cells in a table, - // see https://github.com/markdown-it/markdown-it/issues/1000, - // - // Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. - // We set it to 65k, which can expand user input by a factor of x370 - // (256x256 square is 1.8kB expanded into 650kB). - const MAX_AUTOCOMPLETED_CELLS = 0x10000; - function getLine(state, line) { - const pos = state.bMarks[line] + state.tShift[line]; - const max = state.eMarks[line]; - return state.src.slice(pos, max); - } - function escapedSplit(str) { - const result = []; - const max = str.length; - let pos = 0; - let ch = str.charCodeAt(pos); - let isEscaped = false; - let lastPos = 0; - let current = ""; - while (pos < max) { - if (ch === 0x7c /* | */) { - if (!isEscaped) { - // pipe separating cells, '|' - result.push(current + str.substring(lastPos, pos)); - current = ""; - lastPos = pos + 1; - } else { - // escaped pipe, '\|' - current += str.substring(lastPos, pos - 1); - lastPos = pos; + }; + var readTextFromFile = function (file, i3) { + if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { + markAsReadAndPasteIfAllFilesAreRead(); + return; } + var reader = new FileReader(); + reader.onerror = function () { + return markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.onload = function () { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + text[i3] = content; + markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.readAsText(file); + }; + for (var i2 = 0; i2 < files.length; i2++) { + readTextFromFile(files[i2], i2); } - isEscaped = ch === 0x5c /* \ */; - pos++; - ch = str.charCodeAt(pos); + } else { + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + setTimeout(function () { + return cm.display.input.focus(); + }, 20); + return; + } + try { + var text$1 = e.dataTransfer.getData("Text"); + if (text$1) { + var selected; + if (cm.state.draggingText && !cm.state.draggingText.copy) { + selected = cm.listSelections(); + } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i$12 = 0; i$12 < selected.length; ++i$12) { + replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag"); + } + } + cm.replaceSelection(text$1, "around", "paste"); + cm.display.input.focus(); + } + } catch (e$1) {} } - result.push(current + str.substring(lastPos)); - return result; } - function table(state, startLine, endLine, silent) { - // should have at least two lines - if (startLine + 2 > endLine) { - return false; - } - let nextLine = startLine + 1; - if (state.sCount[nextLine] < state.blkIndent) { - return false; + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || + /* @__PURE__ */new Date() - lastDrop < 100)) { + e_stop(e); + return; } - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - return false; + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; } - - // first character of the second line should be '|', '-', ':', - // and no other characters are allowed but spaces; - // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp - - let pos = state.bMarks[nextLine] + state.tShift[nextLine]; - if (pos >= state.eMarks[nextLine]) { - return false; + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove"; + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) { + img.parentNode.removeChild(img); + } } - const firstCh = state.src.charCodeAt(pos++); - if ( - firstCh !== 0x7c /* | */ && - firstCh !== 0x2d /* - */ && - firstCh !== 0x3a /* : */ - ) { - return false; + } + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) { + return; } - if (pos >= state.eMarks[nextLine]) { - return false; + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); } - const secondCh = state.src.charCodeAt(pos++); - if ( - secondCh !== 0x7c /* | */ && - secondCh !== 0x2d /* - */ && - secondCh !== 0x3a /* : */ && - !isSpace(secondCh) - ) { - return false; + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; } - - // if first character is '-', then second character must not be a space - // (due to parsing ambiguity with list) - if (firstCh === 0x2d /* - */ && isSpace(secondCh)) { - return false; + } + function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { + return; } - while (pos < state.eMarks[nextLine]) { - const ch = state.src.charCodeAt(pos); - if ( - ch !== 0x7c /* | */ && - ch !== 0x2d /* - */ && - ch !== 0x3a /* : */ && - !isSpace(ch) - ) { - return false; + var byClass = document.getElementsByClassName("CodeMirror"), + editors = []; + for (var i2 = 0; i2 < byClass.length; i2++) { + var cm = byClass[i2].CodeMirror; + if (cm) { + editors.push(cm); } - pos++; } - let lineText = getLine(state, startLine + 1); - let columns = lineText.split("|"); - const aligns = []; - for (let i = 0; i < columns.length; i++) { - const t = columns[i].trim(); - if (!t) { - // allow empty columns before and after table, but not in between columns; - // e.g. allow ` |---| `, disallow ` ---||--- ` - if (i === 0 || i === columns.length - 1) { - continue; - } else { - return false; + if (editors.length) { + editors[0].operation(function () { + for (var i3 = 0; i3 < editors.length; i3++) { + f(editors[i3]); } - } - if (!/^:?-+:?$/.test(t)) { - return false; - } - if (t.charCodeAt(t.length - 1) === 0x3a /* : */) { - aligns.push( - t.charCodeAt(0) === 0x3a /* : */ ? "center" : "right" - ); - } else if (t.charCodeAt(0) === 0x3a /* : */) { - aligns.push("left"); + }); + } + } + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) { + return; + } + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { + resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + } + }); + on(window, "blur", function () { + return forEachCodeMirror(onBlur); + }); + } + function onResize(cm) { + var d = cm.display; + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + var keyNames = { + 3: "Pause", + 8: "Backspace", + 9: "Tab", + 13: "Enter", + 16: "Shift", + 17: "Ctrl", + 18: "Alt", + 19: "Pause", + 20: "CapsLock", + 27: "Esc", + 32: "Space", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "Left", + 38: "Up", + 39: "Right", + 40: "Down", + 44: "PrintScrn", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Mod", + 92: "Mod", + 93: "Mod", + 106: "*", + 107: "=", + 109: "-", + 110: ".", + 111: "/", + 145: "ScrollLock", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'", + 224: "Mod", + 63232: "Up", + 63233: "Down", + 63234: "Left", + 63235: "Right", + 63272: "Delete", + 63273: "Home", + 63275: "End", + 63276: "PageUp", + 63277: "PageDown", + 63302: "Insert" + }; + for (var i = 0; i < 10; i++) { + keyNames[i + 48] = keyNames[i + 96] = String(i); + } + for (var i$1 = 65; i$1 <= 90; i$1++) { + keyNames[i$1] = String.fromCharCode(i$1); + } + for (var i$2 = 1; i$2 <= 12; i$2++) { + keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; + } + var keyMap = {}; + keyMap.basic = { + "Left": "goCharLeft", + "Right": "goCharRight", + "Up": "goLineUp", + "Down": "goLineDown", + "End": "goLineEnd", + "Home": "goLineStartSmart", + "PageUp": "goPageUp", + "PageDown": "goPageDown", + "Delete": "delCharAfter", + "Backspace": "delCharBefore", + "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", + "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", + "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + keyMap.pcDefault = { + "Ctrl-A": "selectAll", + "Ctrl-D": "deleteLine", + "Ctrl-Z": "undo", + "Shift-Ctrl-Z": "redo", + "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", + "Ctrl-End": "goDocEnd", + "Ctrl-Up": "goLineUp", + "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", + "Ctrl-Right": "goGroupRight", + "Alt-Left": "goLineStart", + "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", + "Ctrl-Delete": "delGroupAfter", + "Ctrl-S": "save", + "Ctrl-F": "find", + "Ctrl-G": "findNext", + "Shift-Ctrl-G": "findPrev", + "Shift-Ctrl-F": "replace", + "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", + "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", + "Shift-Ctrl-U": "redoSelection", + "Alt-U": "redoSelection", + "fallthrough": "basic" + }; + keyMap.emacsy = { + "Ctrl-F": "goCharRight", + "Ctrl-B": "goCharLeft", + "Ctrl-P": "goLineUp", + "Ctrl-N": "goLineDown", + "Ctrl-A": "goLineStart", + "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", + "Shift-Ctrl-V": "goPageUp", + "Ctrl-D": "delCharAfter", + "Ctrl-H": "delCharBefore", + "Alt-Backspace": "delWordBefore", + "Ctrl-K": "killLine", + "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", + "Cmd-D": "deleteLine", + "Cmd-Z": "undo", + "Shift-Cmd-Z": "redo", + "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", + "Cmd-Up": "goDocStart", + "Cmd-End": "goDocEnd", + "Cmd-Down": "goDocEnd", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", + "Cmd-Left": "goLineLeft", + "Cmd-Right": "goLineRight", + "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", + "Alt-Delete": "delGroupAfter", + "Cmd-S": "save", + "Cmd-F": "find", + "Cmd-G": "findNext", + "Shift-Cmd-G": "findPrev", + "Cmd-Alt-F": "replace", + "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", + "Cmd-]": "indentMore", + "Cmd-Backspace": "delWrappedLineLeft", + "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", + "Shift-Cmd-U": "redoSelection", + "Ctrl-Up": "goDocStart", + "Ctrl-Down": "goDocEnd", + "fallthrough": ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/); + name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i2 = 0; i2 < parts.length - 1; i2++) { + var mod = parts[i2]; + if (/^(cmd|meta|m)$/i.test(mod)) { + cmd = true; + } else if (/^a(lt)?$/i.test(mod)) { + alt = true; + } else if (/^(c|ctrl|control)$/i.test(mod)) { + ctrl = true; + } else if (/^s(hift)?$/i.test(mod)) { + shift = true; } else { - aligns.push(""); + throw new Error("Unrecognized modifier name: " + mod); } } - lineText = getLine(state, startLine).trim(); - if (lineText.indexOf("|") === -1) { - return false; + if (alt) { + name = "Alt-" + name; } - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; + if (ctrl) { + name = "Ctrl-" + name; } - columns = escapedSplit(lineText); - if (columns.length && columns[0] === "") columns.shift(); - if (columns.length && columns[columns.length - 1] === "") - columns.pop(); - - // header row will define an amount of columns in the entire table, - // and align row should be exactly the same (the rest of the rows can differ) - const columnCount = columns.length; - if (columnCount === 0 || columnCount !== aligns.length) { - return false; + if (cmd) { + name = "Cmd-" + name; } - if (silent) { - return true; + if (shift) { + name = "Shift-" + name; } - const oldParentType = state.parentType; - state.parentType = "table"; - - // use 'blockquote' lists for termination because it's - // the most similar to tables - const terminatorRules = state.md.block.ruler.getRules("blockquote"); - const token_to = state.push("table_open", "table", 1); - const tableLines = [startLine, 0]; - token_to.map = tableLines; - const token_tho = state.push("thead_open", "thead", 1); - token_tho.map = [startLine, startLine + 1]; - const token_htro = state.push("tr_open", "tr", 1); - token_htro.map = [startLine, startLine + 1]; - for (let i = 0; i < columns.length; i++) { - const token_ho = state.push("th_open", "th", 1); - if (aligns[i]) { - token_ho.attrs = [["style", "text-align:" + aligns[i]]]; - } - const token_il = state.push("inline", "", 0); - token_il.content = columns[i].trim(); - token_il.children = []; - state.push("th_close", "th", -1); - } - state.push("tr_close", "tr", -1); - state.push("thead_close", "thead", -1); - let tbodyLines; - let autocompletedCells = 0; - for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { - if (state.sCount[nextLine] < state.blkIndent) { - break; - } - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; + return name; + } + function normalizeKeyMap(keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { + continue; } - } - if (terminate) { - break; - } - lineText = getLine(state, nextLine).trim(); - if (!lineText) { - break; - } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - break; - } - columns = escapedSplit(lineText); - if (columns.length && columns[0] === "") columns.shift(); - if (columns.length && columns[columns.length - 1] === "") - columns.pop(); - - // note: autocomplete count can be negative if user specifies more columns than header, - // but that does not affect intended use (which is limiting expansion) - autocompletedCells += columnCount - columns.length; - if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) { - break; - } - if (nextLine === startLine + 2) { - const token_tbo = state.push("tbody_open", "tbody", 1); - token_tbo.map = tbodyLines = [startLine + 2, 0]; - } - const token_tro = state.push("tr_open", "tr", 1); - token_tro.map = [nextLine, nextLine + 1]; - for (let i = 0; i < columnCount; i++) { - const token_tdo = state.push("td_open", "td", 1); - if (aligns[i]) { - token_tdo.attrs = [["style", "text-align:" + aligns[i]]]; + if (value == "...") { + delete keymap[keyname]; + continue; + } + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i2 = 0; i2 < keys.length; i2++) { + var val = void 0, + name = void 0; + if (i2 == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i2 + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) { + copy[name] = val; + } else if (prev != val) { + throw new Error("Inconsistent bindings for " + name); + } } - const token_il = state.push("inline", "", 0); - token_il.content = columns[i] ? columns[i].trim() : ""; - token_il.children = []; - state.push("td_close", "td", -1); + delete keymap[keyname]; } - state.push("tr_close", "tr", -1); } - if (tbodyLines) { - state.push("tbody_close", "tbody", -1); - tbodyLines[1] = nextLine; + for (var prop2 in copy) { + keymap[prop2] = copy[prop2]; } - state.push("table_close", "table", -1); - tableLines[1] = nextLine; - state.parentType = oldParentType; - state.line = nextLine; - return true; + return keymap; } - - // Code block (4 spaces padded) - - function code(state, startLine, endLine /*, silent */) { - if (state.sCount[startLine] - state.blkIndent < 4) { - return false; + function lookupKey(key, map2, handle, context) { + map2 = getKeyMap(map2); + var found = map2.call ? map2.call(key, context) : map2[key]; + if (found === false) { + return "nothing"; } - let nextLine = startLine + 1; - let last = nextLine; - while (nextLine < endLine) { - if (state.isEmpty(nextLine)) { - nextLine++; - continue; + if (found === "...") { + return "multi"; + } + if (found != null && handle(found)) { + return "handled"; + } + if (map2.fallthrough) { + if (Object.prototype.toString.call(map2.fallthrough) != "[object Array]") { + return lookupKey(key, map2.fallthrough, handle, context); } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - nextLine++; - last = nextLine; - continue; + for (var i2 = 0; i2 < map2.fallthrough.length; i2++) { + var result = lookupKey(key, map2.fallthrough[i2], handle, context); + if (result) { + return result; + } } - break; } - state.line = last; - const token = state.push("code_block", "code", 0); - token.content = - state.getLines(startLine, last, 4 + state.blkIndent, false) + "\n"; - token.map = [startLine, state.line]; - return true; } - - // fences (``` lang, ~~~ lang) - - function fence(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; + function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + function addModifierNames(name, event, noShift) { + var base = name; + if (event.altKey && base != "Alt") { + name = "Alt-" + name; } - if (pos + 3 > max) { - return false; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { + name = "Ctrl-" + name; } - const marker = state.src.charCodeAt(pos); - if (marker !== 0x7e /* ~ */ && marker !== 0x60 /* ` */) { - return false; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { + name = "Cmd-" + name; } - - // scan marker length - let mem = pos; - pos = state.skipChars(pos, marker); - let len = pos - mem; - if (len < 3) { + if (!noShift && event.shiftKey && base != "Shift") { + name = "Shift-" + name; + } + return name; + } + function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false; } - const markup = state.src.slice(mem, pos); - const params = state.src.slice(pos, max); - if (marker === 0x60 /* ` */) { - if (params.indexOf(String.fromCharCode(marker)) >= 0) { - return false; - } + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) { + return false; } - - // Since start is found, we can report success here in validation mode - if (silent) { - return true; + if (event.keyCode == 3 && event.code) { + name = event.code; } - - // search end of block - let nextLine = startLine; - let haveEndMarker = false; - for (;;) { - nextLine++; - if (nextLine >= endLine) { - // unclosed block should be autoclosed by end of document. - // also block seems to be autoclosed by end of parent - break; - } - pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - if (pos < max && state.sCount[nextLine] < state.blkIndent) { - // non-empty line with negative indent should stop the list: - // - ``` - // test - break; - } - if (state.src.charCodeAt(pos) !== marker) { - continue; + return addModifierNames(name, event, noShift); + } + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, + kill = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + var toKill = compute(ranges[i2]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - // closing fence should be indented less than 4 spaces - continue; + kill.push(toKill); + } + runInOp(cm, function () { + for (var i3 = kill.length - 1; i3 >= 0; i3--) { + replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete"); } - pos = state.skipChars(pos, marker); - - // closing code fence must be at least as long as the opening one - if (pos - mem < len) { - continue; + ensureCursorVisible(cm); + }); + } + function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir); + return target < 0 || target > line.text.length ? null : target; + } + function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir); + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before"); + } + function endOfLine(visually, cm, lineObj, lineNo2, dir) { + if (visually) { + if (cm.doc.direction == "rtl") { + dir = -dir; } - - // make sure tail has spaces only - pos = state.skipSpaces(pos); - if (pos < max) { - continue; + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = dir < 0 ? lst(order) : order[0]; + var moveInStorageOrder = dir < 0 == (part.level == 1); + var sticky = moveInStorageOrder ? "after" : "before"; + var ch; + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj); + ch = dir < 0 ? lineObj.text.length - 1 : 0; + var targetTop = measureCharPrepared(cm, prep, ch).top; + ch = findFirst(function (ch2) { + return measureCharPrepared(cm, prep, ch2).top == targetTop; + }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch); + if (sticky == "before") { + ch = moveCharLogically(lineObj, ch, 1); + } + } else { + ch = dir < 0 ? part.to : part.from; + } + return new Pos(lineNo2, ch, sticky); } - haveEndMarker = true; - // found! - break; } - - // If a fence has heading spaces, they should be removed from its inner block - len = state.sCount[startLine]; - state.line = nextLine + (haveEndMarker ? 1 : 0); - const token = state.push("fence", "code", 0); - token.info = params; - token.content = state.getLines(startLine + 1, nextLine, len, true); - token.markup = markup; - token.map = [startLine, state.line]; - return true; + return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after"); } - - // Block quotes - - function blockquote(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - const oldLineMax = state.lineMax; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; + function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction); + if (!bidi) { + return moveLogically(line, start, dir); } - - // check the block quote marker - if (state.src.charCodeAt(pos) !== 0x3e /* > */) { - return false; + if (start.ch >= line.text.length) { + start.ch = line.text.length; + start.sticky = "before"; + } else if (start.ch <= 0) { + start.ch = 0; + start.sticky = "after"; } - - // we know that it's going to be a valid blockquote, - // so no point trying to find the end of it in silent mode - if (silent) { - return true; + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), + part = bidi[partPos]; + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + return moveLogically(line, start, dir); } - const oldBMarks = []; - const oldBSCount = []; - const oldSCount = []; - const oldTShift = []; - const terminatorRules = state.md.block.ruler.getRules("blockquote"); - const oldParentType = state.parentType; - state.parentType = "blockquote"; - let lastLineEmpty = false; - let nextLine; - - // Search the end of the block - // - // Block ends with either: - // 1. an empty line outside: - // ``` - // > test - // - // ``` - // 2. an empty line inside: - // ``` - // > - // test - // ``` - // 3. another tag: - // ``` - // > test - // - - - - // ``` - for (nextLine = startLine; nextLine < endLine; nextLine++) { - // check if it's outdented, i.e. it's inside list item and indented - // less than said list item: - // - // ``` - // 1. anything - // > current blockquote - // 2. checking this line - // ``` - const isOutdented = state.sCount[nextLine] < state.blkIndent; - pos = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - if (pos >= max) { - // Case 1: line is not inside the blockquote, and this line is empty. - break; + var mv = function (pos, dir2) { + return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2); + }; + var prep; + var getWrappedLineExtent = function (ch2) { + if (!cm.options.lineWrapping) { + return { + begin: 0, + end: line.text.length + }; } - if (state.src.charCodeAt(pos++) === 0x3e /* > */ && !isOutdented) { - // This line is inside the blockquote. - - // set offset past spaces and ">" - let initial = state.sCount[nextLine] + 1; - let spaceAfterMarker; - let adjustTab; - - // skip one optional space after '>' - if (state.src.charCodeAt(pos) === 0x20 /* space */) { - // ' > test ' - // ^ -- position start of line here: - pos++; - initial++; - adjustTab = false; - spaceAfterMarker = true; - } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { - spaceAfterMarker = true; - if ((state.bsCount[nextLine] + initial) % 4 === 3) { - // ' >\t test ' - // ^ -- position start of line here (tab has width===1) - pos++; - initial++; - adjustTab = false; + prep = prep || prepareMeasureForLine(cm, line); + return wrappedLineExtentChar(cm, line, prep, ch2); + }; + var wrappedLineExtent2 = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = part.level == 1 == dir < 0; + var ch = mv(start, moveInStorageOrder ? 1 : -1); + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) { + var sticky = moveInStorageOrder ? "before" : "after"; + return new Pos(start.line, ch, sticky); + } + } + var searchInVisualLine = function (partPos2, dir2, wrappedLineExtent3) { + var getRes = function (ch3, moveInStorageOrder3) { + return moveInStorageOrder3 ? new Pos(start.line, mv(ch3, 1), "before") : new Pos(start.line, ch3, "after"); + }; + for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) { + var part2 = bidi[partPos2]; + var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1); + var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1); + if (part2.from <= ch2 && ch2 < part2.to) { + return getRes(ch2, moveInStorageOrder2); + } + ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1); + if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) { + return getRes(ch2, moveInStorageOrder2); + } + } + }; + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2); + if (res) { + return res; + } + var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1); + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); + if (res) { + return res; + } + } + return null; + } + var commands = { + selectAll, + singleSelection: function (cm) { + return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function (cm) { + return deleteNearSelection(cm, function (range2) { + if (range2.empty()) { + var len = getLine(cm.doc, range2.head.line).text.length; + if (range2.head.ch == len && range2.head.line < cm.lastLine()) { + return { + from: range2.head, + to: Pos(range2.head.line + 1, 0) + }; } else { - // ' >\t test ' - // ^ -- position start of line here + shift bsCount slightly - // to make extra space appear - adjustTab = true; + return { + from: range2.head, + to: Pos(range2.head.line, len) + }; } } else { - spaceAfterMarker = false; + return { + from: range2.from(), + to: range2.to() + }; } - let offset = initial; - oldBMarks.push(state.bMarks[nextLine]); - state.bMarks[nextLine] = pos; - while (pos < max) { - const ch = state.src.charCodeAt(pos); - if (isSpace(ch)) { - if (ch === 0x09) { - offset += - 4 - - ((offset + - state.bsCount[nextLine] + - (adjustTab ? 1 : 0)) % - 4); - } else { - offset++; + }); + }, + deleteLine: function (cm) { + return deleteNearSelection(cm, function (range2) { + return { + from: Pos(range2.from().line, 0), + to: clipPos(cm.doc, Pos(range2.to().line + 1, 0)) + }; + }); + }, + delLineLeft: function (cm) { + return deleteNearSelection(cm, function (range2) { + return { + from: Pos(range2.from().line, 0), + to: range2.from() + }; + }); + }, + delWrappedLineLeft: function (cm) { + return deleteNearSelection(cm, function (range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var leftPos = cm.coordsChar({ + left: 0, + top + }, "div"); + return { + from: leftPos, + to: range2.from() + }; + }); + }, + delWrappedLineRight: function (cm) { + return deleteNearSelection(cm, function (range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var rightPos = cm.coordsChar({ + left: cm.display.lineDiv.offsetWidth + 100, + top + }, "div"); + return { + from: range2.from(), + to: rightPos + }; + }); + }, + undo: function (cm) { + return cm.undo(); + }, + redo: function (cm) { + return cm.redo(); + }, + undoSelection: function (cm) { + return cm.undoSelection(); + }, + redoSelection: function (cm) { + return cm.redoSelection(); + }, + goDocStart: function (cm) { + return cm.extendSelection(Pos(cm.firstLine(), 0)); + }, + goDocEnd: function (cm) { + return cm.extendSelection(Pos(cm.lastLine())); + }, + goLineStart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + return lineStart(cm, range2.head.line); + }, { + origin: "+move", + bias: 1 + }); + }, + goLineStartSmart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + return lineStartSmart(cm, range2.head); + }, { + origin: "+move", + bias: 1 + }); + }, + goLineEnd: function (cm) { + return cm.extendSelectionsBy(function (range2) { + return lineEnd(cm, range2.head.line); + }, { + origin: "+move", + bias: -1 + }); + }, + goLineRight: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar({ + left: cm.display.lineDiv.offsetWidth + 100, + top + }, "div"); + }, sel_move); + }, + goLineLeft: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar({ + left: 0, + top + }, "div"); + }, sel_move); + }, + goLineLeftSmart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + var pos = cm.coordsChar({ + left: 0, + top + }, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { + return lineStartSmart(cm, range2.head); + } + return pos; + }, sel_move); + }, + goLineUp: function (cm) { + return cm.moveV(-1, "line"); + }, + goLineDown: function (cm) { + return cm.moveV(1, "line"); + }, + goPageUp: function (cm) { + return cm.moveV(-1, "page"); + }, + goPageDown: function (cm) { + return cm.moveV(1, "page"); + }, + goCharLeft: function (cm) { + return cm.moveH(-1, "char"); + }, + goCharRight: function (cm) { + return cm.moveH(1, "char"); + }, + goColumnLeft: function (cm) { + return cm.moveH(-1, "column"); + }, + goColumnRight: function (cm) { + return cm.moveH(1, "column"); + }, + goWordLeft: function (cm) { + return cm.moveH(-1, "word"); + }, + goGroupRight: function (cm) { + return cm.moveH(1, "group"); + }, + goGroupLeft: function (cm) { + return cm.moveH(-1, "group"); + }, + goWordRight: function (cm) { + return cm.moveH(1, "word"); + }, + delCharBefore: function (cm) { + return cm.deleteH(-1, "codepoint"); + }, + delCharAfter: function (cm) { + return cm.deleteH(1, "char"); + }, + delWordBefore: function (cm) { + return cm.deleteH(-1, "word"); + }, + delWordAfter: function (cm) { + return cm.deleteH(1, "word"); + }, + delGroupBefore: function (cm) { + return cm.deleteH(-1, "group"); + }, + delGroupAfter: function (cm) { + return cm.deleteH(1, "group"); + }, + indentAuto: function (cm) { + return cm.indentSelection("smart"); + }, + indentMore: function (cm) { + return cm.indentSelection("add"); + }, + indentLess: function (cm) { + return cm.indentSelection("subtract"); + }, + insertTab: function (cm) { + return cm.replaceSelection(" "); + }, + insertSoftTab: function (cm) { + var spaces = [], + ranges = cm.listSelections(), + tabSize = cm.options.tabSize; + for (var i2 = 0; i2 < ranges.length; i2++) { + var pos = ranges[i2].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(spaceStr(tabSize - col % tabSize)); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { + cm.indentSelection("add"); + } else { + cm.execCommand("insertTab"); + } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { + return runInOp(cm, function () { + var ranges = cm.listSelections(), + newSel = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + if (!ranges[i2].empty()) { + continue; + } + var cur = ranges[i2].head, + line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) { + cur = new Pos(cur.line, cur.ch - 1); + } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cur = new Pos(cur.line, 1); + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); + } } - } else { - break; } - pos++; + newSel.push(new Range(cur, cur)); } - lastLineEmpty = pos >= max; - oldBSCount.push(state.bsCount[nextLine]); - state.bsCount[nextLine] = - state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); - oldSCount.push(state.sCount[nextLine]); - state.sCount[nextLine] = offset - initial; - oldTShift.push(state.tShift[nextLine]); - state.tShift[nextLine] = pos - state.bMarks[nextLine]; - continue; + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function (cm) { + return runInOp(cm, function () { + var sels = cm.listSelections(); + for (var i2 = sels.length - 1; i2 >= 0; i2--) { + cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input"); + } + sels = cm.listSelections(); + for (var i$12 = 0; i$12 < sels.length; i$12++) { + cm.indentLine(sels[i$12].from().line, null, true); + } + ensureCursorVisible(cm); + }); + }, + openLine: function (cm) { + return cm.replaceSelection("\n", "start"); + }, + toggleOverwrite: function (cm) { + return cm.toggleOverwrite(); + } + }; + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, visual, lineN, 1); + } + function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLineEnd(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, line, lineN, -1); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line, cm.doc.direction); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); + } + return start; + } + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) { + return false; } - - // Case 2: line is not inside the blockquote, and the last line was empty. - if (lastLineEmpty) { - break; + } + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, + done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; } - - // Case 3: another tag found. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } + if (dropShift) { + cm.display.shift = false; } - if (terminate) { - // Quirk to enforce "hard termination mode" for paragraphs; - // normally if you call `tokenize(state, startLine, nextLine)`, - // paragraphs will look below nextLine for paragraph continuation, - // but if blockquote is terminated by another tag, they shouldn't - state.lineMax = nextLine; - if (state.blkIndent !== 0) { - // state.blkIndent was non-zero, we now set it to zero, - // so we need to re-calculate all offsets to appear as - // if indent wasn't changed - oldBMarks.push(state.bMarks[nextLine]); - oldBSCount.push(state.bsCount[nextLine]); - oldTShift.push(state.tShift[nextLine]); - oldSCount.push(state.sCount[nextLine]); - state.sCount[nextLine] -= state.blkIndent; - } - break; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + function lookupKeyForEditor(cm, name, handle) { + for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) { + var result = lookupKey(name, cm.state.keyMaps[i2], handle, cm); + if (result) { + return result; } - oldBMarks.push(state.bMarks[nextLine]); - oldBSCount.push(state.bsCount[nextLine]); - oldTShift.push(state.tShift[nextLine]); - oldSCount.push(state.sCount[nextLine]); - - // A negative indentation means that this is a paragraph continuation - // - state.sCount[nextLine] = -1; - } - const oldIndent = state.blkIndent; - state.blkIndent = 0; - const token_o = state.push("blockquote_open", "blockquote", 1); - token_o.markup = ">"; - const lines = [startLine, 0]; - token_o.map = lines; - state.md.block.tokenize(state, startLine, nextLine); - const token_c = state.push("blockquote_close", "blockquote", -1); - token_c.markup = ">"; - state.lineMax = oldLineMax; - state.parentType = oldParentType; - lines[1] = state.line; - - // Restore original tShift; this might not be necessary since the parser - // has already been here, but just to make sure we can do that. - for (let i = 0; i < oldTShift.length; i++) { - state.bMarks[i + startLine] = oldBMarks[i]; - state.tShift[i + startLine] = oldTShift[i]; - state.sCount[i + startLine] = oldSCount[i]; - state.bsCount[i + startLine] = oldBSCount[i]; - } - state.blkIndent = oldIndent; - return true; + } + return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm); + } + var stopSeq = new Delayed(); + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) { + return "handled"; + } + if (/\'$/.test(name)) { + cm.state.keySeq = null; + } else { + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + } + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { + return true; + } + } + return dispatchKeyInner(cm, name, e, handle); + } + function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle); + if (result == "multi") { + cm.state.keySeq = name; + } + if (result == "handled") { + signalLater(cm, "keyHandled", cm, name, e); + } + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + return !!result; } - - // Horizontal rule - - function hr(state, startLine, endLine, silent) { - const max = state.eMarks[startLine]; - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) { return false; } - let pos = state.bMarks[startLine] + state.tShift[startLine]; - const marker = state.src.charCodeAt(pos++); - - // Check hr marker - if ( - marker !== 0x2a /* * */ && - marker !== 0x2d /* - */ && - marker !== 0x5f /* _ */ - ) { - return false; + if (e.shiftKey && !cm.state.keySeq) { + return dispatchKey(cm, "Shift-" + name, e, function (b) { + return doHandleBinding(cm, b, true); + }) || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { + return doHandleBinding(cm, b); + } + }); + } else { + return dispatchKey(cm, name, e, function (b) { + return doHandleBinding(cm, b); + }); } - - // markers can be mixed with spaces, but there should be at least 3 of them - - let cnt = 1; - while (pos < max) { - const ch = state.src.charCodeAt(pos++); - if (ch !== marker && !isSpace(ch)) { - return false; - } - if (ch === marker) { - cnt++; + } + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { + return doHandleBinding(cm, b, true); + }); + } + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; + } + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) { + return; + } + if (ie && ie_version < 11 && e.keyCode == 27) { + e.returnValue = false; + } + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { + cm.replaceSelection("", null, "cut"); } } - if (cnt < 3) { - return false; + if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { + document.execCommand("cut"); } - if (silent) { - return true; + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { + showCrossHair(cm); } - state.line = startLine + 1; - const token = state.push("hr", "hr", 0); - token.map = [startLine, state.line]; - token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); - return true; } - - // Lists - - // Search `[-+*][\n ]`, returns next pos after marker on success - // or -1 on fail. - function skipBulletListMarker(state, startLine) { - const max = state.eMarks[startLine]; - let pos = state.bMarks[startLine] + state.tShift[startLine]; - const marker = state.src.charCodeAt(pos++); - // Check bullet - if ( - marker !== 0x2a /* * */ && - marker !== 0x2d /* - */ && - marker !== 0x2b /* + */ - ) { - return -1; - } - if (pos < max) { - const ch = state.src.charCodeAt(pos); - if (!isSpace(ch)) { - // " -test " - is not a list item - return -1; + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); } } - return pos; + on(document, "keyup", up); + on(document, "mouseover", up); } - - // Search `\d+[.)][\n ]`, returns next pos after marker on success - // or -1 on fail. - function skipOrderedListMarker(state, startLine) { - const start = state.bMarks[startLine] + state.tShift[startLine]; - const max = state.eMarks[startLine]; - let pos = start; - - // List marker should have at least 2 chars (digit + dot) - if (pos + 1 >= max) { - return -1; + function onKeyUp(e) { + if (e.keyCode == 16) { + this.doc.sel.shift = false; + } + signalDOMEvent(this, e); + } + function onKeyPress(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; } - let ch = state.src.charCodeAt(pos++); - if (ch < 0x30 /* 0 */ || ch > 0x39 /* 9 */) { - return -1; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { + return; } - for (;;) { - // EOL -> fail - if (pos >= max) { - return -1; - } - ch = state.src.charCodeAt(pos++); - if (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) { - // List marker should have no more than 9 digits - // (prevents integer overflow in browsers) - if (pos - start >= 10) { - return -1; - } - continue; - } - - // found valid marker - if (ch === 0x29 /* ) */ || ch === 0x2e /* . */) { - break; - } - return -1; + var keyCode = e.keyCode, + charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) { + lastStoppedKey = null; + e_preventDefault(e); + return; } - if (pos < max) { - ch = state.src.charCodeAt(pos); - if (!isSpace(ch)) { - // " 1.test " - is not a list item - return -1; - } + if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) { + return; } - return pos; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (ch == "\b") { + return; + } + if (handleCharBinding(cm, e, ch)) { + return; + } + cm.display.input.onKeyPress(e); } - function markTightParagraphs(state, idx) { - const level = state.level + 2; - for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) { - if ( - state.tokens[i].level === level && - state.tokens[i].type === "paragraph_open" - ) { - state.tokens[i + 2].hidden = true; - state.tokens[i].hidden = true; - i += 2; - } + var DOUBLECLICK_DELAY = 400; + var PastClick = function (time, pos, button) { + this.time = time; + this.pos = pos; + this.button = button; + }; + PastClick.prototype.compare = function (time, pos, button) { + return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button; + }; + var lastClick, lastDoubleClick; + function clickRepeat(pos, button) { + var now = + /* @__PURE__ */new Date(); + if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { + lastClick = lastDoubleClick = null; + return "triple"; + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button); + lastClick = null; + return "double"; + } else { + lastClick = new PastClick(now, pos, button); + lastDoubleClick = null; + return "single"; } } - function list(state, startLine, endLine, silent) { - let max, pos, start, token; - let nextLine = startLine; - let tight = true; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - return false; + function onMouseDown(e) { + var cm = this, + display = cm.display; + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { + return; } - - // Special case: - // - item 1 - // - item 2 - // - item 3 - // - item 4 - // - this one is a paragraph continuation - if ( - state.listIndent >= 0 && - state.sCount[nextLine] - state.listIndent >= 4 && - state.sCount[nextLine] < state.blkIndent - ) { - return false; + display.input.ensurePolled(); + display.shift = e.shiftKey; + if (eventInWidget(display, e)) { + if (!webkit) { + display.scroller.draggable = false; + setTimeout(function () { + return display.scroller.draggable = true; + }, 100); + } + return; } - let isTerminatingParagraph = false; - - // limit conditions when list can interrupt - // a paragraph (validation mode only) - if (silent && state.parentType === "paragraph") { - // Next list item should still terminate previous list item; - // - // This code can fail if plugins use blkIndent as well as lists, - // but I hope the spec gets fixed long before that happens. - // - if (state.sCount[nextLine] >= state.blkIndent) { - isTerminatingParagraph = true; + if (clickInGutter(cm, e)) { + return; + } + var pos = posFromMouse(cm, e), + button = e_button(e), + repeat = pos ? clickRepeat(pos, button) : "single"; + window.focus(); + if (button == 1 && cm.state.selectingText) { + cm.state.selectingText(e); + } + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { + return; + } + if (button == 1) { + if (pos) { + leftButtonDown(cm, pos, repeat, e); + } else if (e_target(e) == display.scroller) { + e_preventDefault(e); + } + } else if (button == 2) { + if (pos) { + extendSelection(cm.doc, pos); + } + setTimeout(function () { + return display.input.focus(); + }, 20); + } else if (button == 3) { + if (captureRightClick) { + cm.display.input.onContextMenu(e); + } else { + delayBlurEvent(cm); } } - - // Detect list type and position after marker - let isOrdered; - let markerValue; - let posAfterMarker; - if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) { - isOrdered = true; - start = state.bMarks[nextLine] + state.tShift[nextLine]; - markerValue = Number(state.src.slice(start, posAfterMarker - 1)); - - // If we're starting a new ordered list right after - // a paragraph, it should start with 1. - if (isTerminatingParagraph && markerValue !== 1) return false; - } else if ( - (posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0 - ) { - isOrdered = false; - } else { - return false; + } + function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click"; + if (repeat == "double") { + name = "Double" + name; + } else if (repeat == "triple") { + name = "Triple" + name; } - - // If we're starting a new unordered list right after - // a paragraph, first line should not be empty. - if (isTerminatingParagraph) { - if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) + name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; + return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { + if (typeof bound == "string") { + bound = commands[bound]; + } + if (!bound) { return false; + } + var done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; + } + done = bound(cm, pos) != Pass; + } finally { + cm.state.suppressEdits = false; + } + return done; + }); + } + function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse"); + var value = option ? option(cm, repeat, event) : {}; + if (value.unit == null) { + var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; + value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; } - - // For validation mode we can terminate immediately - if (silent) { - return true; + if (value.extend == null || cm.doc.extend) { + value.extend = cm.doc.extend || event.shiftKey; } - - // We should terminate list on style change. Remember first one to compare. - const markerCharCode = state.src.charCodeAt(posAfterMarker - 1); - - // Start list - const listTokIdx = state.tokens.length; - if (isOrdered) { - token = state.push("ordered_list_open", "ol", 1); - if (markerValue !== 1) { - token.attrs = [["start", markerValue]]; - } + if (value.addNew == null) { + value.addNew = mac ? event.metaKey : event.ctrlKey; + } + if (value.moveOnDrag == null) { + value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); + } + return value; + } + function leftButtonDown(cm, pos, repeat, event) { + if (ie) { + setTimeout(bind(ensureFocus, cm), 0); } else { - token = state.push("bullet_list_open", "ul", 1); + cm.curOp.focus = activeElt(); } - const listLines = [nextLine, 0]; - token.map = listLines; - token.markup = String.fromCharCode(markerCharCode); - - // - // Iterate list items - // - - let prevEmptyEnd = false; - const terminatorRules = state.md.block.ruler.getRules("list"); - const oldParentType = state.parentType; - state.parentType = "list"; - while (nextLine < endLine) { - pos = posAfterMarker; - max = state.eMarks[nextLine]; - const initial = - state.sCount[nextLine] + - posAfterMarker - - (state.bMarks[nextLine] + state.tShift[nextLine]); - let offset = initial; - while (pos < max) { - const ch = state.src.charCodeAt(pos); - if (ch === 0x09) { - offset += 4 - ((offset + state.bsCount[nextLine]) % 4); - } else if (ch === 0x20) { - offset++; + var behavior = configureMouse(cm, repeat, event); + var sel = cm.doc.sel, + contained; + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { + leftButtonStartDrag(cm, event, pos, behavior); + } else { + leftButtonSelect(cm, event, pos, behavior); + } + } + function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, + moved = false; + var dragEnd = operation(cm, function (e) { + if (webkit) { + display.scroller.draggable = false; + } + cm.state.draggingText = false; + if (cm.state.delayingBlurEvent) { + if (cm.hasFocus()) { + cm.state.delayingBlurEvent = false; } else { - break; + delayBlurEvent(cm); } - pos++; - } - const contentStart = pos; - let indentAfterMarker; - if (contentStart >= max) { - // trimming space in "- \n 3" case, indent is 1 here - indentAfterMarker = 1; - } else { - indentAfterMarker = offset - initial; - } - - // If we have more than 4 spaces, the indent is 1 - // (the rest is just indented code block) - if (indentAfterMarker > 4) { - indentAfterMarker = 1; } - - // " - test" - // ^^^^^ - calculating total length of this thing - const indent = initial + indentAfterMarker; - - // Run subparser & write tokens - token = state.push("list_item_open", "li", 1); - token.markup = String.fromCharCode(markerCharCode); - const itemLines = [nextLine, 0]; - token.map = itemLines; - if (isOrdered) { - token.info = state.src.slice(start, posAfterMarker - 1); + off(display.wrapper.ownerDocument, "mouseup", dragEnd); + off(display.wrapper.ownerDocument, "mousemove", mouseMove); + off(display.scroller, "dragstart", dragStart); + off(display.scroller, "drop", dragEnd); + if (!moved) { + e_preventDefault(e); + if (!behavior.addNew) { + extendSelection(cm.doc, pos, null, null, behavior.extend); + } + if (webkit && !safari || ie && ie_version == 9) { + setTimeout(function () { + display.wrapper.ownerDocument.body.focus({ + preventScroll: true + }); + display.input.focus(); + }, 20); + } else { + display.input.focus(); + } } - - // change current state, then restore it after parser subcall - const oldTight = state.tight; - const oldTShift = state.tShift[nextLine]; - const oldSCount = state.sCount[nextLine]; - - // - example list - // ^ listIndent position will be here - // ^ blkIndent position will be here - // - const oldListIndent = state.listIndent; - state.listIndent = state.blkIndent; - state.blkIndent = indent; - state.tight = true; - state.tShift[nextLine] = contentStart - state.bMarks[nextLine]; - state.sCount[nextLine] = offset; - if (contentStart >= max && state.isEmpty(nextLine + 1)) { - // workaround for this case - // (list item is empty, list terminates before "foo"): - // ~~~~~~~~ - // - - // - // foo - // ~~~~~~~~ - state.line = Math.min(state.line + 2, endLine); + }); + var mouseMove = function (e2) { + moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; + }; + var dragStart = function () { + return moved = true; + }; + if (webkit) { + display.scroller.draggable = true; + } + cm.state.draggingText = dragEnd; + dragEnd.copy = !behavior.moveOnDrag; + on(display.wrapper.ownerDocument, "mouseup", dragEnd); + on(display.wrapper.ownerDocument, "mousemove", mouseMove); + on(display.scroller, "dragstart", dragStart); + on(display.scroller, "drop", dragEnd); + cm.state.delayingBlurEvent = true; + setTimeout(function () { + return display.input.focus(); + }, 20); + if (display.scroller.dragDrop) { + display.scroller.dragDrop(); + } + } + function rangeForUnit(cm, pos, unit) { + if (unit == "char") { + return new Range(pos, pos); + } + if (unit == "word") { + return cm.findWordAt(pos); + } + if (unit == "line") { + return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + } + var result = unit(cm, pos); + return new Range(result.from, result.to); + } + function leftButtonSelect(cm, event, start, behavior) { + if (ie) { + delayBlurEvent(cm); + } + var display = cm.display, + doc = cm.doc; + e_preventDefault(event); + var ourRange, + ourIndex, + startSel = doc.sel, + ranges = startSel.ranges; + if (behavior.addNew && !behavior.extend) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) { + ourRange = ranges[ourIndex]; } else { - state.md.block.tokenize(state, nextLine, endLine, true); - } - - // If any of list item is tight, mark list as tight - if (!state.tight || prevEmptyEnd) { - tight = false; - } - // Item become loose if finish with empty line, - // but we should filter last element, because it means list finish - prevEmptyEnd = - state.line - nextLine > 1 && state.isEmpty(state.line - 1); - state.blkIndent = state.listIndent; - state.listIndent = oldListIndent; - state.tShift[nextLine] = oldTShift; - state.sCount[nextLine] = oldSCount; - state.tight = oldTight; - token = state.push("list_item_close", "li", -1); - token.markup = String.fromCharCode(markerCharCode); - nextLine = state.line; - itemLines[1] = nextLine; - if (nextLine >= endLine) { - break; + ourRange = new Range(start, start); } - - // - // Try to check if list is terminated or continued. - // - if (state.sCount[nextLine] < state.blkIndent) { - break; + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { + ourRange = new Range(start, start); } - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - break; + start = posFromMouse(cm, event, true, true); + ourIndex = -1; + } else { + var range2 = rangeForUnit(cm, start, behavior.unit); + if (behavior.extend) { + ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend); + } else { + ourRange = range2; + } + } + if (!behavior.addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), { + scroll: false, + origin: "*mouse" + }); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), { + scroll: false, + origin: "*mouse" + }); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { + return; } - - // fail if terminating block found - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; + lastPos = pos; + if (behavior.unit == "rectangle") { + var ranges2 = [], + tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), + right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { + var text = getLine(doc, line).text, + leftPos = findColumn(text, left, tabSize); + if (left == right) { + ranges2.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); + } else if (text.length > leftPos) { + ranges2.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); + } + } + if (!ranges2.length) { + ranges2.push(new Range(start, start)); + } + setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex), { + origin: "*mouse", + scroll: false + }); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var range3 = rangeForUnit(cm, pos, behavior.unit); + var anchor = oldRange.anchor, + head; + if (cmp(range3.anchor, anchor) > 0) { + head = range3.head; + anchor = minPos(oldRange.from(), range3.anchor); + } else { + head = range3.anchor; + anchor = maxPos(oldRange.to(), range3.head); } + var ranges$1 = startSel.ranges.slice(0); + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); + setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); } - if (terminate) { - break; + } + var editorSize = display.wrapper.getBoundingClientRect(); + var counter = 0; + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); + if (!cur) { + return; } - - // fail if list has another type - if (isOrdered) { - posAfterMarker = skipOrderedListMarker(state, nextLine); - if (posAfterMarker < 0) { - break; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) { + setTimeout(operation(cm, function () { + if (counter == curCount) { + extend(e); + } + }), 150); } - start = state.bMarks[nextLine] + state.tShift[nextLine]; } else { - posAfterMarker = skipBulletListMarker(state, nextLine); - if (posAfterMarker < 0) { - break; + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { + setTimeout(operation(cm, function () { + if (counter != curCount) { + return; + } + display.scroller.scrollTop += outside; + extend(e); + }), 50); } } - if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { - break; + } + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + if (e) { + e_preventDefault(e); + display.input.focus(); } + off(display.wrapper.ownerDocument, "mousemove", move); + off(display.wrapper.ownerDocument, "mouseup", up); + doc.history.lastSelOrigin = null; } - - // Finalize list - if (isOrdered) { - token = state.push("ordered_list_close", "ol", -1); - } else { - token = state.push("bullet_list_close", "ul", -1); + var move = operation(cm, function (e) { + if (e.buttons === 0 || !e_button(e)) { + done(e); + } else { + extend(e); + } + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(display.wrapper.ownerDocument, "mousemove", move); + on(display.wrapper.ownerDocument, "mouseup", up); + } + function bidiSimplify(cm, range2) { + var anchor = range2.anchor; + var head = range2.head; + var anchorLine = getLine(cm.doc, anchor.line); + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { + return range2; } - token.markup = String.fromCharCode(markerCharCode); - listLines[1] = nextLine; - state.line = nextLine; - state.parentType = oldParentType; - - // mark paragraphs tight if needed - if (tight) { - markTightParagraphs(state, listTokIdx); + var order = getOrder(anchorLine); + if (!order) { + return range2; } - return true; + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), + part = order[index]; + if (part.from != anchor.ch && part.to != anchor.ch) { + return range2; + } + var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1); + if (boundary == 0 || boundary == order.length) { + return range2; + } + var leftSide; + if (head.line != anchor.line) { + leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky); + var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); + if (headIndex == boundary - 1 || headIndex == boundary) { + leftSide = dir < 0; + } else { + leftSide = dir > 0; + } + } + var usePart = order[boundary + (leftSide ? -1 : 0)]; + var from = leftSide == (usePart.level == 1); + var ch = from ? usePart.from : usePart.to, + sticky = from ? "after" : "before"; + return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range(new Pos(anchor.line, ch, sticky), head); } - function reference(state, startLine, _endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - let nextLine = startLine + 1; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; + function gutterEvent(cm, e, type, prevent) { + var mX, mY; + if (e.touches) { + mX = e.touches[0].clientX; + mY = e.touches[0].clientY; + } else { + try { + mX = e.clientX; + mY = e.clientY; + } catch (e$1) { + return false; + } } - if (state.src.charCodeAt(pos) !== 0x5b /* [ */) { + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false; } - function getNextLine(nextLine) { - const endLine = state.lineMax; - if (nextLine >= endLine || state.isEmpty(nextLine)) { - // empty line or end of input - return null; + if (prevent) { + e_preventDefault(e); + } + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + if (mY > lineBox.bottom || !hasHandler(cm, type)) { + return e_defaultPrevented(e); + } + mY -= lineBox.top - display.viewOffset; + for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) { + var g = display.gutters.childNodes[i2]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.display.gutterSpecs[i2]; + signal(cm, type, cm, line, gutter.className, e); + return e_defaultPrevented(e); } - let isContinuation = false; - - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - isContinuation = true; + } + } + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true); + } + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { + return; + } + if (signalDOMEvent(cm, e, "contextmenu")) { + return; + } + if (!captureRightClick) { + cm.display.input.onContextMenu(e); + } + } + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { + return false; + } + return gutterEvent(cm, e, "gutterContextMenu", false); + } + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + var Init = { + toString: function () { + return "CodeMirror.Init"; + } + }; + var defaults = {}; + var optionHandlers = {}; + function defineOptions(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + function option(name, deflt, handle, notOnInit) { + CodeMirror2.defaults[name] = deflt; + if (handle) { + optionHandlers2[name] = notOnInit ? function (cm, val, old) { + if (old != Init) { + handle(cm, val, old); + } + } : handle; + } + } + CodeMirror2.defineOption = option; + CodeMirror2.Init = Init; + option("value", "", function (cm, val) { + return cm.setValue(val); + }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val; + if (!val) { + return; } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - isContinuation = true; - } - if (!isContinuation) { - const terminatorRules = - state.md.block.ruler.getRules("reference"); - const oldParentType = state.parentType; - state.parentType = "reference"; - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; + var newBreaks = [], + lineNo2 = cm.doc.first; + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) { break; } + pos = found + val.length; + newBreaks.push(Pos(lineNo2, found)); + } + lineNo2++; + }); + for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) { + replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length)); + } + }); + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test(" ") ? "" : "| "), "g"); + if (old != Init) { + cm.refresh(); + } + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { + return cm.refresh(); + }, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor"); + }, true); + option("spellcheck", false, function (cm, val) { + return cm.getInputField().spellcheck = val; + }, true); + option("autocorrect", false, function (cm, val) { + return cm.getInputField().autocorrect = val; + }, true); + option("autocapitalize", false, function (cm, val) { + return cm.getInputField().autocapitalize = val; + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + option("theme", "default", function (cm) { + themeChanged(cm); + updateGutters(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != Init && getKeyMap(old); + if (prev && prev.detach) { + prev.detach(cm, next); + } + if (next.attach) { + next.attach(cm, prev || null); + } + }); + option("extraKeys", null); + option("configureMouse", null); + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm, val) { + cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); + updateGutters(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) { + return updateScrollbars(cm); + }, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm, val) { + cm.display.gutterSpecs = getGutters(cm.options.gutters, val); + updateGutters(cm); + }, true); + option("firstLineNumber", 1, updateGutters, true); + option("lineNumberFormatter", function (integer) { + return integer; + }, updateGutters, true); + option("showCursorWhenSelecting", false, updateSelection, true); + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + option("selectionsMayTouch", false); + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + } + cm.display.input.readOnlyChanged(val); + }); + option("screenReaderLabel", null, function (cm, val) { + val = val === "" ? null : val; + cm.display.input.screenReaderLabelChanged(val); + }); + option("disableInput", false, function (cm, val) { + if (!val) { + cm.display.input.reset(); + } + }, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) { + return cm.doc.history.undoDepth = val; + }); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) { + return cm.refresh(); + }, true); + option("maxHighlightLength", 1e4, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { + cm.display.input.resetPosition(); + } + }); + option("tabindex", null, function (cm, val) { + return cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + option("direction", "ltr", function (cm, val) { + return cm.doc.setDirection(val); + }, true); + option("phrases", null); + } + function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () { + return updateScrollbars(cm); + }, 100); + } + function CodeMirror(place, options) { + var this$1$1 = this; + if (!(this instanceof CodeMirror)) { + return new CodeMirror(place, options); + } + this.options = options = options ? copyObj(options) : {}; + copyObj(defaults, options, false); + var doc = options.value; + if (typeof doc == "string") { + doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); + } else if (options.mode) { + doc.modeOption = options.mode; + } + this.doc = doc; + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input, options); + display.wrapper.CodeMirror = this; + themeChanged(this); + if (options.lineWrapping) { + this.display.wrapper.className += " CodeMirror-wrap"; + } + initScrollbars(this); + this.state = { + keyMaps: [], + // stores maps added by addKeyMap + overlays: [], + // highlighting overlays, as added by addOverlay + modeGen: 0, + // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, + // used to disable editing during key handlers when in readOnly mode + pasteIncoming: -1, + cutIncoming: -1, + // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), + // stores highlight worker timeout + keySeq: null, + // Unfinished key sequence + specialChars: null + }; + if (options.autofocus && !mobile) { + display.input.focus(); + } + if (ie && ie_version < 11) { + setTimeout(function () { + return this$1$1.display.input.reset(true); + }, 20); + } + registerEventHandlers(this); + ensureGlobalHandlers(); + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + if (options.autofocus && !mobile || this.hasFocus()) { + setTimeout(function () { + if (this$1$1.hasFocus() && !this$1$1.state.focused) { + onFocus(this$1$1); + } + }, 20); + } else { + onBlur(this); + } + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) { + optionHandlers[opt](this, options[opt], Init); + } + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) { + options.finishInit(this); + } + for (var i2 = 0; i2 < initHooks.length; ++i2) { + initHooks[i2](this); + } + endOperation(this); + if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { + display.lineDiv.style.textRendering = "auto"; + } + } + CodeMirror.defaults = defaults; + CodeMirror.optionHandlers = optionHandlers; + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + if (ie && ie_version < 11) { + on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { + return; + } + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + } else { + on(d.scroller, "dblclick", function (e) { + return signalDOMEvent(cm, e) || e_preventDefault(e); + }); + } + on(d.scroller, "contextmenu", function (e) { + return onContextMenu(cm, e); + }); + on(d.input.getField(), "contextmenu", function (e) { + if (!d.scroller.contains(e.target)) { + onContextMenu(cm, e); + } + }); + var touchFinished, + prevTouch = { + end: 0 + }; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { + return d.activeTouch = null; + }, 1e3); + prevTouch = d.activeTouch; + prevTouch.end = + /* @__PURE__ */new Date(); + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { + return false; + } + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway(touch, other) { + if (other.left == null) { + return true; + } + var dx = other.left - touch.left, + dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { + d.input.ensurePolled(); + clearTimeout(touchFinished); + var now = + /* @__PURE__ */new Date(); + d.activeTouch = { + start: now, + moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null + }; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { + d.activeTouch.moved = true; + } + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && /* @__PURE__ */new Date() - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), + range2; + if (!touch.prev || farAway(touch, touch.prev)) { + range2 = new Range(pos, pos); + } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) { + range2 = cm.findWordAt(pos); + } else { + range2 = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + } + cm.setSelection(range2.anchor, range2.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + on(d.scroller, "mousewheel", function (e) { + return onScrollWheel(cm, e); + }); + on(d.scroller, "DOMMouseScroll", function (e) { + return onScrollWheel(cm, e); + }); + on(d.wrapper, "scroll", function () { + return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; + }); + d.dragFunctions = { + enter: function (e) { + if (!signalDOMEvent(cm, e)) { + e_stop(e); + } + }, + over: function (e) { + if (!signalDOMEvent(cm, e)) { + onDragOver(cm, e); + e_stop(e); } - state.parentType = oldParentType; - if (terminate) { - // terminated by another block - return null; + }, + start: function (e) { + return onDragStart(cm, e); + }, + drop: operation(cm, onDrop), + leave: function (e) { + if (!signalDOMEvent(cm, e)) { + clearDragCursor(cm); } } - const pos = state.bMarks[nextLine] + state.tShift[nextLine]; - const max = state.eMarks[nextLine]; - - // max + 1 explicitly includes the newline - return state.src.slice(pos, max + 1); - } - let str = state.src.slice(pos, max + 1); - max = str.length; - let labelEnd = -1; - for (pos = 1; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x5b /* [ */) { - return false; - } else if (ch === 0x5d /* ] */) { - labelEnd = pos; - break; - } else if (ch === 0x0a /* \n */) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; - } - } else if (ch === 0x5c /* \ */) { - pos++; - if (pos < max && str.charCodeAt(pos) === 0x0a) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; - } + }; + var inp = d.input.getField(); + on(inp, "keyup", function (e) { + return onKeyUp.call(cm, e); + }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", function (e) { + return onFocus(cm, e); + }); + on(inp, "blur", function (e) { + return onBlur(cm, e); + }); + } + var initHooks = []; + CodeMirror.defineInitHook = function (f) { + return initHooks.push(f); + }; + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, + state; + if (how == null) { + how = "add"; + } + if (how == "smart") { + if (!doc.mode.indent) { + how = "prev"; + } else { + state = getContextBefore(cm, n).state; + } + } + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), + curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) { + line.stateAfter = null; + } + var curSpaceString = line.text.match(/^\s*/)[0], + indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) { + return; } + how = "prev"; } } - if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3a /* : */) { - return false; - } - - // [label]: destination 'title' - // ^^^ skip optional whitespace here - for (pos = labelEnd + 2; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x0a) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + if (how == "prev") { + if (n > doc.first) { + indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); + } else { + indentation = 0; + } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + var indentString = "", + pos = 0; + if (cm.options.indentWithTabs) { + for (var i2 = Math.floor(indentation / tabSize); i2; --i2) { + pos += tabSize; + indentString += " "; + } + } + if (pos < indentation) { + indentString += spaceStr(indentation - pos); + } + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } else { + for (var i$12 = 0; i$12 < doc.sel.ranges.length; i$12++) { + var range2 = doc.sel.ranges[i$12]; + if (range2.head.line == n && range2.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i$12, new Range(pos$1, pos$1)); + break; } - } else if (isSpace(ch)); - else { - break; } } - - // [label]: destination 'title' - // ^^^^^^^^^^^ parse this - const destRes = state.md.helpers.parseLinkDestination(str, pos, max); - if (!destRes.ok) { - return false; - } - const href = state.md.normalizeLink(destRes.str); - if (!state.md.validateLink(href)) { - return false; + } + var lastCopied = null; + function setLastCopied(newLastCopied) { + lastCopied = newLastCopied; + } + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) { + sel = doc.sel; } - pos = destRes.pos; - - // save cursor state, we could require to rollback later - const destEndPos = pos; - const destEndLineNo = nextLine; - - // [label]: destination 'title' - // ^^^ skipping those spaces - const start = pos; - for (; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x0a) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + var recent = + /* @__PURE__ */new Date() - 200; + var paste = origin == "paste" || cm.state.pasteIncoming > recent; + var textLines = splitLinesAuto(inserted), + multiPaste = null; + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i2 = 0; i2 < lastCopied.text.length; i2++) { + multiPaste.push(doc.splitLines(lastCopied.text[i2])); + } } - } else if (isSpace(ch)); - else { - break; + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, function (l) { + return [l]; + }); } } - - // [label]: destination 'title' - // ^^^^^^^ parse this - let titleRes = state.md.helpers.parseLinkTitle(str, pos, max); - while (titleRes.can_continue) { - const lineContent = getNextLine(nextLine); - if (lineContent === null) break; - str += lineContent; - pos = max; - max = str.length; - nextLine++; - titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes); + var updateInput = cm.curOp.updateInput; + for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) { + var range2 = sel.ranges[i$12]; + var from = range2.from(), + to = range2.to(); + if (range2.empty()) { + if (deleted && deleted > 0) { + from = Pos(from.line, from.ch - deleted); + } else if (cm.state.overwrite && !paste) { + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); + } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { + from = to = Pos(from.line, 0); + } + } + var changeEvent = { + from, + to, + text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input") + }; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) { + triggerElectric(cm, inserted); + } + ensureCursorVisible(cm); + if (cm.curOp.updateInput < 2) { + cm.curOp.updateInput = updateInput; + } + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = -1; + } + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput) { + runInOp(cm, function () { + return applyTextInput(cm, pasted, 0, null, "paste"); + }); + } + return true; } - let title; - if (pos < max && start !== pos && titleRes.ok) { - title = titleRes.str; - pos = titleRes.pos; - } else { - title = ""; - pos = destEndPos; - nextLine = destEndLineNo; + } + function triggerElectric(cm, inserted) { + if (!cm.options.electricChars || !cm.options.smartIndent) { + return; } - - // skip trailing spaces until the rest of the line - while (pos < max) { - const ch = str.charCodeAt(pos); - if (!isSpace(ch)) { - break; + var sel = cm.doc.sel; + for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { + var range2 = sel.ranges[i2]; + if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) { + continue; } - pos++; - } - if (pos < max && str.charCodeAt(pos) !== 0x0a) { - if (title) { - // garbage at the end of the line after title, - // but it could still be a valid reference if we roll back - title = ""; - pos = destEndPos; - nextLine = destEndLineNo; - while (pos < max) { - const ch = str.charCodeAt(pos); - if (!isSpace(ch)) { + var mode = cm.getModeAt(range2.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range2.head.line, "smart"); break; } - pos++; + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) { + indented = indentLine(cm, range2.head.line, "smart"); } } + if (indented) { + signalLater(cm, "electricInput", cm, range2.head.line); + } } - if (pos < max && str.charCodeAt(pos) !== 0x0a) { - // garbage at the end of the line - return false; - } - const label = normalizeReference(str.slice(1, labelEnd)); - if (!label) { - // CommonMark 0.20 disallows empty labels - return false; - } - - // Reference can not terminate anything. This check is for safety only. - /* istanbul ignore if */ - if (silent) { - return true; - } - if (typeof state.env.references === "undefined") { - state.env.references = {}; - } - if (typeof state.env.references[label] === "undefined") { - state.env.references[label] = { - title, - href, + } + function copyableRanges(cm) { + var text = [], + ranges = []; + for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { + var line = cm.doc.sel.ranges[i2].head.line; + var lineRange = { + anchor: Pos(line, 0), + head: Pos(line + 1, 0) }; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); } - state.line = nextLine; - return true; + return { + text, + ranges + }; } - - // List of valid html blocks names, according to commonmark spec - // https://spec.commonmark.org/0.30/#html-blocks - - var block_names = [ - "address", - "article", - "aside", - "base", - "basefont", - "blockquote", - "body", - "caption", - "center", - "col", - "colgroup", - "dd", - "details", - "dialog", - "dir", - "div", - "dl", - "dt", - "fieldset", - "figcaption", - "figure", - "footer", - "form", - "frame", - "frameset", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "head", - "header", - "hr", - "html", - "iframe", - "legend", - "li", - "link", - "main", - "menu", - "menuitem", - "nav", - "noframes", - "ol", - "optgroup", - "option", - "p", - "param", - "search", - "section", - "summary", - "table", - "tbody", - "td", - "tfoot", - "th", - "thead", - "title", - "tr", - "track", - "ul", - ]; - - // Regexps to match html elements - - const attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*"; - const unquoted = "[^\"'=<>`\\x00-\\x20]+"; - const single_quoted = "'[^']*'"; - const double_quoted = '"[^"]*"'; - const attr_value = - "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")"; - const attribute = - "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)"; - const open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>"; - const close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>"; - const comment = ""; - const processing = "<[?][\\s\\S]*?[?]>"; - const declaration = "]*>"; - const cdata = ""; - const HTML_TAG_RE = new RegExp( - "^(?:" + - open_tag + - "|" + - close_tag + - "|" + - comment + - "|" + - processing + - "|" + - declaration + - "|" + - cdata + - ")" - ); - const HTML_OPEN_CLOSE_TAG_RE = new RegExp( - "^(?:" + open_tag + "|" + close_tag + ")" - ); - - // HTML block - - // An array of opening and corresponding closing sequences for html tags, - // last argument defines whether it can terminate a paragraph or not - // - const HTML_SEQUENCES = [ - [ - /^<(script|pre|style|textarea)(?=(\s|>|$))/i, - /<\/(script|pre|style|textarea)>/i, - true, - ], - [/^/, true], - [/^<\?/, /\?>/, true], - [/^/, true], - [/^/, true], - [ - new RegExp( - "^|$))", - "i" - ), - /^$/, - true, - ], - [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + "\\s*$"), /^$/, false], - ]; - function html_block(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (!state.md.options.html) { - return false; - } - if (state.src.charCodeAt(pos) !== 0x3c /* < */) { - return false; - } - let lineText = state.src.slice(pos, max); - let i = 0; - for (; i < HTML_SEQUENCES.length; i++) { - if (HTML_SEQUENCES[i][0].test(lineText)) { - break; + function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { + field.setAttribute("autocorrect", autocorrect ? "" : "off"); + field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); + field.setAttribute("spellcheck", !!spellcheck); + } + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + if (webkit) { + te.style.width = "1000px"; + } else { + te.setAttribute("wrap", "off"); + } + if (ios) { + te.style.border = "1px solid black"; + } + disableBrowserMagic(te); + return div; + } + function addEditorMethods(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + var helpers = CodeMirror2.helpers = {}; + CodeMirror2.prototype = { + constructor: CodeMirror2, + focus: function () { + window.focus(); + this.display.input.focus(); + }, + setOption: function (option, value) { + var options = this.options, + old = options[option]; + if (options[option] == value && option != "mode") { + return; + } + options[option] = value; + if (optionHandlers2.hasOwnProperty(option)) { + operation(this, optionHandlers2[option])(this, value, old); + } + signal(this, "optionChange", this, option); + }, + getOption: function (option) { + return this.options[option]; + }, + getDoc: function () { + return this.doc; + }, + addKeyMap: function (map2, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map2)); + }, + removeKeyMap: function (map2) { + var maps = this.state.keyMaps; + for (var i2 = 0; i2 < maps.length; ++i2) { + if (maps[i2] == map2 || maps[i2].name == map2) { + maps.splice(i2, 1); + return true; + } + } + }, + addOverlay: methodOp(function (spec, options) { + var mode = spec.token ? spec : CodeMirror2.getMode(this.options, spec); + if (mode.startState) { + throw new Error("Overlays may not be stateful."); + } + insertSorted(this.state.overlays, { + mode, + modeSpec: spec, + opaque: options && options.opaque, + priority: options && options.priority || 0 + }, function (overlay) { + return overlay.priority; + }); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function (spec) { + var overlays = this.state.overlays; + for (var i2 = 0; i2 < overlays.length; ++i2) { + var cur = overlays[i2].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i2, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + indentLine: methodOp(function (n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { + dir = this.options.smartIndent ? "smart" : "prev"; + } else { + dir = dir ? "add" : "subtract"; + } + } + if (isLine(this.doc, n)) { + indentLine(this, n, dir, aggressive); + } + }), + indentSelection: methodOp(function (how) { + var ranges = this.doc.sel.ranges, + end = -1; + for (var i2 = 0; i2 < ranges.length; i2++) { + var range2 = ranges[i2]; + if (!range2.empty()) { + var from = range2.from(), + to = range2.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) { + indentLine(this, j, how); + } + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) { + replaceOneSelection(this.doc, i2, new Range(from, newRanges[i2].to()), sel_dontScroll); + } + } else if (range2.head.line > end) { + indentLine(this, range2.head.line, how, true); + end = range2.head.line; + if (i2 == this.doc.sel.primIndex) { + ensureCursorVisible(this); + } + } + } + }), + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function (pos, precise) { + return takeToken(this, pos, precise); + }, + getLineTokens: function (line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + getTokenTypeAt: function (pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, + after = (styles.length - 1) / 2, + ch = pos.ch; + var type; + if (ch == 0) { + type = styles[2]; + } else { + for (;;) { + var mid = before + after >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { + after = mid; + } else if (styles[mid * 2 + 1] < ch) { + before = mid + 1; + } else { + type = styles[mid * 2 + 2]; + break; + } + } + } + var cut = type ? type.indexOf("overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + getModeAt: function (pos) { + var mode = this.doc.mode; + if (!mode.innerMode) { + return mode; + } + return CodeMirror2.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + getHelper: function (pos, type) { + return this.getHelpers(pos, type)[0]; + }, + getHelpers: function (pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) { + return found; + } + var help = helpers[type], + mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) { + found.push(help[mode[type]]); + } + } else if (mode[type]) { + for (var i2 = 0; i2 < mode[type].length; i2++) { + var val = help[mode[type][i2]]; + if (val) { + found.push(val); + } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i$12 = 0; i$12 < help._global.length; i$12++) { + var cur = help._global[i$12]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { + found.push(cur.val); + } + } + return found; + }, + getStateAfter: function (line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); + return getContextBefore(this, line + 1, precise).state; + }, + cursorCoords: function (start, mode) { + var pos, + range2 = this.doc.sel.primary(); + if (start == null) { + pos = range2.head; + } else if (typeof start == "object") { + pos = clipPos(this.doc, start); + } else { + pos = start ? range2.from() : range2.to(); + } + return cursorCoords(this, pos, mode || "page"); + }, + charCoords: function (pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + coordsChar: function (coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + lineAtHeight: function (height, mode) { + height = fromCoordSystem(this, { + top: height, + left: 0 + }, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function (line, mode, includeWidgets) { + var end = false, + lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) { + line = this.doc.first; + } else if (line > last) { + line = last; + end = true; + } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, { + top: 0, + left: 0 + }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + defaultTextHeight: function () { + return textHeight(this.display); + }, + defaultCharWidth: function () { + return charWidth(this.display); + }, + getViewport: function () { + return { + from: this.display.viewFrom, + to: this.display.viewTo + }; + }, + addWidget: function (pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, + left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { + top = pos.top - node.offsetHeight; + } else if (pos.bottom + node.offsetHeight <= vspace) { + top = pos.bottom; + } + if (left + node.offsetWidth > hspace) { + left = hspace - node.offsetWidth; + } + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") { + left = 0; + } else if (horiz == "middle") { + left = (display.sizer.clientWidth - node.offsetWidth) / 2; + } + node.style.left = left + "px"; + } + if (scroll) { + scrollIntoView(this, { + left, + top, + right: left + node.offsetWidth, + bottom: top + node.offsetHeight + }); + } + }, + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + execCommand: function (cmd) { + if (commands.hasOwnProperty(cmd)) { + return commands[cmd].call(null, this); + } + }, + triggerElectric: methodOp(function (text) { + triggerElectric(this, text); + }), + findPosH: function (from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveH: methodOp(function (dir, unit) { + var this$1$1 = this; + this.extendSelectionsBy(function (range2) { + if (this$1$1.display.shift || this$1$1.doc.extend || range2.empty()) { + return findPosH(this$1$1.doc, range2.head, dir, unit, this$1$1.options.rtlMoveVisually); + } else { + return dir < 0 ? range2.from() : range2.to(); + } + }, sel_move); + }), + deleteH: methodOp(function (dir, unit) { + var sel = this.doc.sel, + doc = this.doc; + if (sel.somethingSelected()) { + doc.replaceSelection("", null, "+delete"); + } else { + deleteNearSelection(this, function (range2) { + var other = findPosH(doc, range2.head, dir, unit, false); + return dir < 0 ? { + from: other, + to: range2.head + } : { + from: range2.head, + to: other + }; + }); + } + }), + findPosV: function (from, amount, unit, goalColumn) { + var dir = 1, + x = goalColumn; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) { + x = coords.left; + } else { + coords.left = x; + } + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveV: methodOp(function (dir, unit) { + var this$1$1 = this; + var doc = this.doc, + goals = []; + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range2) { + if (collapse) { + return dir < 0 ? range2.from() : range2.to(); + } + var headPos = cursorCoords(this$1$1, range2.head, "div"); + if (range2.goalColumn != null) { + headPos.left = range2.goalColumn; + } + goals.push(headPos.left); + var pos = findPosV(this$1$1, headPos, dir, unit); + if (unit == "page" && range2 == doc.sel.primary()) { + addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top); + } + return pos; + }, sel_move); + if (goals.length) { + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + doc.sel.ranges[i2].goalColumn = goals[i2]; + } + } + }), + // Find the word at the given position (as returned by coordsChar). + findWordAt: function (pos) { + var doc = this.doc, + line = getLine(doc, pos.line).text; + var start = pos.ch, + end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.sticky == "before" || end == line.length) && start) { + --start; + } else { + ++end; + } + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) ? function (ch) { + return isWordChar(ch, helper); + } : /\s/.test(startChar) ? function (ch) { + return /\s/.test(ch); + } : function (ch) { + return !/\s/.test(ch) && !isWordChar(ch); + }; + while (start > 0 && check(line.charAt(start - 1))) { + --start; + } + while (end < line.length && check(line.charAt(end))) { + ++end; + } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + toggleOverwrite: function (value) { + if (value != null && value == this.state.overwrite) { + return; + } + if (this.state.overwrite = !this.state.overwrite) { + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); + } else { + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); + } + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function () { + return this.display.input.getField() == activeElt(); + }, + isReadOnly: function () { + return !!(this.options.readOnly || this.doc.cantEdit); + }, + scrollTo: methodOp(function (x, y) { + scrollToCoords(this, x, y); + }), + getScrollInfo: function () { + var scroller = this.display.scroller; + return { + left: scroller.scrollLeft, + top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), + clientWidth: displayWidth(this) + }; + }, + scrollIntoView: methodOp(function (range2, margin) { + if (range2 == null) { + range2 = { + from: this.doc.sel.primary().head, + to: null + }; + if (margin == null) { + margin = this.options.cursorScrollMargin; + } + } else if (typeof range2 == "number") { + range2 = { + from: Pos(range2, 0), + to: null + }; + } else if (range2.from == null) { + range2 = { + from: range2, + to: null + }; + } + if (!range2.to) { + range2.to = range2.from; + } + range2.margin = margin || 0; + if (range2.from.line != null) { + scrollToRange(this, range2); + } else { + scrollToCoordsRange(this, range2.from, range2.to, range2.margin); + } + }), + setSize: methodOp(function (width, height) { + var this$1$1 = this; + var interpret = function (val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + }; + if (width != null) { + this.display.wrapper.style.width = interpret(width); + } + if (height != null) { + this.display.wrapper.style.height = interpret(height); + } + if (this.options.lineWrapping) { + clearLineMeasurementCache(this); + } + var lineNo2 = this.display.viewFrom; + this.doc.iter(lineNo2, this.display.viewTo, function (line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].noHScroll) { + regLineChange(this$1$1, lineNo2, "widget"); + break; + } + } + } + ++lineNo2; + }); + this.curOp.forceUpdate = true; + signal(this, "refresh", this); + }), + operation: function (f) { + return runInOp(this, f); + }, + startOperation: function () { + return startOperation(this); + }, + endOperation: function () { + return endOperation(this); + }, + refresh: methodOp(function () { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this.display); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) { + estimateLineHeights(this); + } + signal(this, "refresh", this); + }), + swapDoc: methodOp(function (doc) { + var old = this.doc; + old.cm = null; + if (this.state.selectingText) { + this.state.selectingText(); + } + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + scrollToCoords(this, doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + phrase: function (phraseText) { + var phrases = this.options.phrases; + return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText; + }, + getInputField: function () { + return this.display.input.getField(); + }, + getWrapperElement: function () { + return this.display.wrapper; + }, + getScrollerElement: function () { + return this.display.scroller; + }, + getGutterElement: function () { + return this.display.gutters; + } + }; + eventMixin(CodeMirror2); + CodeMirror2.registerHelper = function (type, name, value) { + if (!helpers.hasOwnProperty(type)) { + helpers[type] = CodeMirror2[type] = { + _global: [] + }; + } + helpers[type][name] = value; + }; + CodeMirror2.registerGlobalHelper = function (type, name, predicate, value) { + CodeMirror2.registerHelper(type, name, value); + helpers[type]._global.push({ + pred: predicate, + val: value + }); + }; + } + function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos; + var origDir = dir; + var lineObj = getLine(doc, pos.line); + var lineDir = visually && doc.direction == "rtl" ? -dir : dir; + function findNextLine() { + var l = pos.line + lineDir; + if (l < doc.first || l >= doc.first + doc.size) { + return false; } + pos = new Pos(l, pos.ch, pos.sticky); + return lineObj = getLine(doc, l); } - if (i === HTML_SEQUENCES.length) { - return false; - } - if (silent) { - // true if this sequence can be a terminator, false otherwise - return HTML_SEQUENCES[i][2]; - } - let nextLine = startLine + 1; - - // If we are here - we detected HTML block. - // Let's roll down till block end. - if (!HTML_SEQUENCES[i][1].test(lineText)) { - for (; nextLine < endLine; nextLine++) { - if (state.sCount[nextLine] < state.blkIndent) { - break; + function moveOnce(boundToLine) { + var next; + if (unit == "codepoint") { + var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); + if (isNaN(ch)) { + next = null; + } else { + var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343; + next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); } - pos = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - lineText = state.src.slice(pos, max); - if (HTML_SEQUENCES[i][1].test(lineText)) { - if (lineText.length !== 0) { - nextLine++; - } - break; + } else if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir); + } else { + next = moveLogically(lineObj, pos, dir); + } + if (next == null) { + if (!boundToLine && findNextLine()) { + pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); + } else { + return false; } + } else { + pos = next; } - } - state.line = nextLine; - const token = state.push("html_block", "", 0); - token.map = [startLine, nextLine]; - token.content = state.getLines( - startLine, - nextLine, - state.blkIndent, - true - ); - return true; - } - - // heading (#, ##, ...) - - function heading(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - let ch = state.src.charCodeAt(pos); - if (ch !== 0x23 /* # */ || pos >= max) { - return false; - } - - // count heading level - let level = 1; - ch = state.src.charCodeAt(++pos); - while (ch === 0x23 /* # */ && pos < max && level <= 6) { - level++; - ch = state.src.charCodeAt(++pos); - } - if (level > 6 || (pos < max && !isSpace(ch))) { - return false; - } - if (silent) { return true; } - - // Let's cut tails like ' ### ' from the end of string - - max = state.skipSpacesBack(max, pos); - const tmp = state.skipCharsBack(max, 0x23, pos); // # - if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { - max = tmp; - } - state.line = startLine + 1; - const token_o = state.push("heading_open", "h" + String(level), 1); - token_o.markup = "########".slice(0, level); - token_o.map = [startLine, state.line]; - const token_i = state.push("inline", "", 0); - token_i.content = state.src.slice(pos, max).trim(); - token_i.map = [startLine, state.line]; - token_i.children = []; - const token_c = state.push("heading_close", "h" + String(level), -1); - token_c.markup = "########".slice(0, level); - return true; - } - - // lheading (---, ===) - - function lheading(state, startLine, endLine /*, silent */) { - const terminatorRules = state.md.block.ruler.getRules("paragraph"); - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - const oldParentType = state.parentType; - state.parentType = "paragraph"; // use paragraph to match terminatorRules - - // jump line-by-line until empty one or EOF - let level = 0; - let marker; - let nextLine = startLine + 1; - for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - continue; - } - - // - // Check for underline in setext header - // - if (state.sCount[nextLine] >= state.blkIndent) { - let pos = state.bMarks[nextLine] + state.tShift[nextLine]; - const max = state.eMarks[nextLine]; - if (pos < max) { - marker = state.src.charCodeAt(pos); - if (marker === 0x2d /* - */ || marker === 0x3d /* = */) { - pos = state.skipChars(pos, marker); - pos = state.skipSpaces(pos); - if (pos >= max) { - level = marker === 0x3d /* = */ ? 1 : 2; - break; - } + if (unit == "char" || unit == "codepoint") { + moveOnce(); + } else if (unit == "column") { + moveOnce(true); + } else if (unit == "word" || unit == "group") { + var sawType = null, + group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { + break; + } + var cur = lineObj.text.charAt(pos.ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; + if (group && !first && !type) { + type = "s"; + } + if (sawType && sawType != type) { + if (dir < 0) { + dir = 1; + moveOnce(); + pos.sticky = "after"; } + break; } - } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - continue; - } - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; + if (type) { + sawType = type; + } + if (dir > 0 && !moveOnce(!first)) { break; } } - if (terminate) { - break; - } } - if (!level) { - // Didn't find valid underline - return false; + var result = skipAtomic(doc, pos, oldPos, origDir, true); + if (equalCursorPos(oldPos, result)) { + result.hitSide = true; } - const content = state - .getLines(startLine, nextLine, state.blkIndent, false) - .trim(); - state.line = nextLine + 1; - const token_o = state.push("heading_open", "h" + String(level), 1); - token_o.markup = String.fromCharCode(marker); - token_o.map = [startLine, state.line]; - const token_i = state.push("inline", "", 0); - token_i.content = content; - token_i.map = [startLine, state.line - 1]; - token_i.children = []; - const token_c = state.push("heading_close", "h" + String(level), -1); - token_c.markup = String.fromCharCode(marker); - state.parentType = oldParentType; - return true; + return result; } - - // Paragraph - - function paragraph(state, startLine, endLine) { - const terminatorRules = state.md.block.ruler.getRules("paragraph"); - const oldParentType = state.parentType; - let nextLine = startLine + 1; - state.parentType = "paragraph"; - - // jump line-by-line until empty one or EOF - for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - continue; - } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - continue; - } - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, + x = pos.left, + y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3); + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + var target; + for (;;) { + target = coordsChar(cm, x, y); + if (!target.outside) { + break; } - if (terminate) { + if (dir < 0 ? y <= 0 : y >= doc.height) { + target.hitSide = true; break; } + y += dir * 5; } - const content = state - .getLines(startLine, nextLine, state.blkIndent, false) - .trim(); - state.line = nextLine; - const token_o = state.push("paragraph_open", "p", 1); - token_o.map = [startLine, state.line]; - const token_i = state.push("inline", "", 0); - token_i.content = content; - token_i.map = [startLine, state.line]; - token_i.children = []; - state.push("paragraph_close", "p", -1); - state.parentType = oldParentType; - return true; + return target; } - - /** internal - * class ParserBlock - * - * Block-level tokenizer. - **/ - - const _rules$1 = [ - // First 2 params - rule name & source. Secondary array - list of rules, - // which can be terminated by this one. - ["table", table, ["paragraph", "reference"]], - ["code", code], - ["fence", fence, ["paragraph", "reference", "blockquote", "list"]], - [ - "blockquote", - blockquote, - ["paragraph", "reference", "blockquote", "list"], - ], - ["hr", hr, ["paragraph", "reference", "blockquote", "list"]], - ["list", list, ["paragraph", "reference", "blockquote"]], - ["reference", reference], - ["html_block", html_block, ["paragraph", "reference", "blockquote"]], - ["heading", heading, ["paragraph", "reference", "blockquote"]], - ["lheading", lheading], - ["paragraph", paragraph], - ]; - - /** - * new ParserBlock() - **/ - function ParserBlock() { - /** - * ParserBlock#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of block rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules$1.length; i++) { - this.ruler.push(_rules$1[i][0], _rules$1[i][1], { - alt: (_rules$1[i][2] || []).slice(), - }); + var ContentEditableInput = function (cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.composing = null; + this.gracePeriod = false; + this.readDOMTimeout = null; + }; + ContentEditableInput.prototype.init = function (display) { + var this$1$1 = this; + var input = this, + cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = true; + disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); + function belongsToInput(e) { + for (var t = e.target; t; t = t.parentNode) { + if (t == div) { + return true; + } + if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { + break; + } + } + return false; } - } - - // Generate tokens for input range - // - ParserBlock.prototype.tokenize = function (state, startLine, endLine) { - const rules = this.ruler.getRules(""); - const len = rules.length; - const maxNesting = state.md.options.maxNesting; - let line = startLine; - let hasEmptyLines = false; - while (line < endLine) { - state.line = line = state.skipEmptyLines(line); - if (line >= endLine) { - break; + on(div, "paste", function (e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; } - - // Termination condition for nested calls. - // Nested calls currently used for blockquotes & lists - if (state.sCount[line] < state.blkIndent) { - break; + if (ie_version <= 11) { + setTimeout(operation(cm, function () { + return this$1$1.updateFromDOM(); + }), 20); } - - // If nesting level exceeded - skip tail to the end. That's not ordinary - // situation and we should not care about content. - if (state.level >= maxNesting) { - state.line = endLine; - break; + }); + on(div, "compositionstart", function (e) { + this$1$1.composing = { + data: e.data, + done: false + }; + }); + on(div, "compositionupdate", function (e) { + if (!this$1$1.composing) { + this$1$1.composing = { + data: e.data, + done: false + }; } - - // Try all possible rules. - // On success, rule should: - // - // - update `state.line` - // - update `state.tokens` - // - return true - const prevLine = state.line; - let ok = false; - for (let i = 0; i < len; i++) { - ok = rules[i](state, line, endLine, false); - if (ok) { - if (prevLine >= state.line) { - throw new Error("block rule didn't increment state.line"); - } - break; + }); + on(div, "compositionend", function (e) { + if (this$1$1.composing) { + if (e.data != this$1$1.composing.data) { + this$1$1.readFromDOMSoon(); } + this$1$1.composing.done = true; } - - // this can only happen if user disables paragraph rule - if (!ok) throw new Error("none of the block rules matched"); - - // set state.tight if we had an empty line before current tag - // i.e. latest empty line should not count - state.tight = !hasEmptyLines; - - // paragraph might "eat" one newline after it in nested lists - if (state.isEmpty(state.line - 1)) { - hasEmptyLines = true; + }); + on(div, "touchstart", function () { + return input.forceCompositionEnd(); + }); + on(div, "input", function () { + if (!this$1$1.composing) { + this$1$1.readFromDOMSoon(); + } + }); + function onCopyCut(e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ + lineWise: false, + text: cm.getSelections() + }); + if (e.type == "cut") { + cm.replaceSelection("", null, "cut"); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ + lineWise: true, + text: ranges.text + }); + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } } - line = state.line; - if (line < endLine && state.isEmpty(line)) { - hasEmptyLines = true; - line++; - state.line = line; + if (e.clipboardData) { + e.clipboardData.clearData(); + var content = lastCopied.text.join("\n"); + e.clipboardData.setData("Text", content); + if (e.clipboardData.getData("Text") == content) { + e.preventDefault(); + return; + } } + var kludge = hiddenTextarea(), + te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.text.join("\n"); + var hadFocus = activeElt(); + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + if (hadFocus == div) { + input.showPrimarySelection(); + } + }, 50); } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); }; - - /** - * ParserBlock.parse(str, md, env, outTokens) - * - * Process input string and push block tokens into `outTokens` - **/ - ParserBlock.prototype.parse = function (src, md, env, outTokens) { - if (!src) { - return; + ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { + if (label) { + this.div.setAttribute("aria-label", label); + } else { + this.div.removeAttribute("aria-label"); } - const state = new this.State(src, md, env, outTokens); - this.tokenize(state, state.line, state.lineMax); }; - ParserBlock.prototype.State = StateBlock; - - // Inline parser state - - function StateInline(src, md, env, outTokens) { - this.src = src; - this.env = env; - this.md = md; - this.tokens = outTokens; - this.tokens_meta = Array(outTokens.length); - this.pos = 0; - this.posMax = this.src.length; - this.level = 0; - this.pending = ""; - this.pendingLevel = 0; - - // Stores { start: end } pairs. Useful for backtrack - // optimization of pairs parse (emphasis, strikes). - this.cache = {}; - - // List of emphasis-like delimiters for current tag - this.delimiters = []; - - // Stack of delimiter lists for upper level tags - this._prev_delimiters = []; - - // backtick length => last seen position - this.backticks = {}; - this.backticksScanned = false; - - // Counter used to disable inline linkify-it execution - // inside and markdown links - this.linkLevel = 0; - } - - // Flush pending text - // - StateInline.prototype.pushPending = function () { - const token = new Token("text", "", 0); - token.content = this.pending; - token.level = this.pendingLevel; - this.tokens.push(token); - this.pending = ""; - return token; + ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false); + result.focus = activeElt() == this.div; + return result; }; - - // Push new token to "stream". - // If pending text exists - flush it as text token - // - StateInline.prototype.push = function (type, tag, nesting) { - if (this.pending) { - this.pushPending(); - } - const token = new Token(type, tag, nesting); - let token_meta = null; - if (nesting < 0) { - // closing tag - this.level--; - this.delimiters = this._prev_delimiters.pop(); - } - token.level = this.level; - if (nesting > 0) { - // opening tag - this.level++; - this._prev_delimiters.push(this.delimiters); - this.delimiters = []; - token_meta = { - delimiters: this.delimiters, - }; + ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { + return; } - this.pendingLevel = this.level; - this.tokens.push(token); - this.tokens_meta.push(token_meta); - return token; - }; - - // Scan a sequence of emphasis-like markers, and determine whether - // it can start an emphasis sequence or end an emphasis sequence. - // - // - start - position to scan from (it should point at a valid marker); - // - canSplitWord - determine if these markers can be found inside a word - // - StateInline.prototype.scanDelims = function (start, canSplitWord) { - const max = this.posMax; - const marker = this.src.charCodeAt(start); - - // treat beginning of the line as a whitespace - const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; - let pos = start; - while (pos < max && this.src.charCodeAt(pos) === marker) { - pos++; + if (info.focus || takeFocus) { + this.showPrimarySelection(); } - const count = pos - start; - - // treat end of the line as a whitespace - const nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; - const isLastPunctChar = - isMdAsciiPunct(lastChar) || - isPunctChar(String.fromCharCode(lastChar)); - const isNextPunctChar = - isMdAsciiPunct(nextChar) || - isPunctChar(String.fromCharCode(nextChar)); - const isLastWhitespace = isWhitespace(lastChar); - const isNextWhitespace = isWhitespace(nextChar); - const left_flanking = - !isNextWhitespace && - (!isNextPunctChar || isLastWhitespace || isLastPunctChar); - const right_flanking = - !isLastWhitespace && - (!isLastPunctChar || isNextWhitespace || isNextPunctChar); - const can_open = - left_flanking && - (canSplitWord || !right_flanking || isLastPunctChar); - const can_close = - right_flanking && - (canSplitWord || !left_flanking || isNextPunctChar); - return { - can_open, - can_close, - length: count, - }; + this.showMultipleSelections(info); }; - - // re-export Token class to use in block rules - StateInline.prototype.Token = Token; - - // Skip text characters for text token, place those to pending buffer - // and increment current pos - - // Rule to skip pure text - // '{}$%@~+=:' reserved for extentions - - // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ - - // !!!! Don't confuse with "Markdown ASCII Punctuation" chars - // http://spec.commonmark.org/0.15/#ascii-punctuation-character - function isTerminatorChar(ch) { - switch (ch) { - case 0x0a /* \n */: - case 0x21 /* ! */: - case 0x23 /* # */: - case 0x24 /* $ */: - case 0x25 /* % */: - case 0x26 /* & */: - case 0x2a /* * */: - case 0x2b /* + */: - case 0x2d /* - */: - case 0x3a /* : */: - case 0x3c /* < */: - case 0x3d /* = */: - case 0x3e /* > */: - case 0x40 /* @ */: - case 0x5b /* [ */: - case 0x5c /* \ */: - case 0x5d /* ] */: - case 0x5e /* ^ */: - case 0x5f /* _ */: - case 0x60 /* ` */: - case 0x7b /* { */: - case 0x7d /* } */: - case 0x7e /* ~ */: - return true; - default: - return false; - } - } - function text(state, silent) { - let pos = state.pos; - while ( - pos < state.posMax && - !isTerminatorChar(state.src.charCodeAt(pos)) - ) { - pos++; + ContentEditableInput.prototype.getSelection = function () { + return this.cm.display.wrapper.ownerDocument.getSelection(); + }; + ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = this.getSelection(), + cm = this.cm, + prim = cm.doc.sel.primary(); + var from = prim.from(), + to = prim.to(); + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges(); + return; } - if (pos === state.pos) { - return false; + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { + return; } - if (!silent) { - state.pending += state.src.slice(state.pos, pos); + var view = cm.display.view; + var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { + node: view[0].measure.map[2], + offset: 0 + }; + var end = to.line < cm.display.viewTo && posToDOM(cm, to); + if (!end) { + var measure = view[view.length - 1].measure; + var map2 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = { + node: map2[map2.length - 1], + offset: map2[map2.length - 2] - map2[map2.length - 3] + }; } - state.pos = pos; - return true; - } - - // Alternative implementation, for memory. - // - // It costs 10% of performance, but allows extend terminators list, if place it - // to `ParserInline` property. Probably, will switch to it sometime, such - // flexibility required. - - /* -var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; - -module.exports = function text(state, silent) { - var pos = state.pos, - idx = state.src.slice(pos).search(TERMINATOR_RE); - - // first char is terminator -> empty text - if (idx === 0) { return false; } - - // no terminator -> text till end of string - if (idx < 0) { - if (!silent) { state.pending += state.src.slice(pos); } - state.pos = state.src.length; - return true; - } - - if (!silent) { state.pending += state.src.slice(pos, pos + idx); } - - state.pos += idx; - - return true; -}; */ - - // Process links like https://example.org/ - - // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; - function linkify(state, silent) { - if (!state.md.options.linkify) return false; - if (state.linkLevel > 0) return false; - const pos = state.pos; - const max = state.posMax; - if (pos + 3 > max) return false; - if (state.src.charCodeAt(pos) !== 0x3a /* : */) return false; - if (state.src.charCodeAt(pos + 1) !== 0x2f /* / */) return false; - if (state.src.charCodeAt(pos + 2) !== 0x2f /* / */) return false; - const match = state.pending.match(SCHEME_RE); - if (!match) return false; - const proto = match[1]; - const link = state.md.linkify.matchAtStart( - state.src.slice(pos - proto.length) - ); - if (!link) return false; - let url = link.url; - - // invalid link, but still detected by linkify somehow; - // need to check to prevent infinite loop below - if (url.length <= proto.length) return false; - - // disallow '*' at the end of the link (conflicts with emphasis) - url = url.replace(/\*+$/, ""); - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) return false; - if (!silent) { - state.pending = state.pending.slice(0, -proto.length); - const token_o = state.push("link_open", "a", 1); - token_o.attrs = [["href", fullUrl]]; - token_o.markup = "linkify"; - token_o.info = "auto"; - const token_t = state.push("text", "", 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push("link_close", "a", -1); - token_c.markup = "linkify"; - token_c.info = "auto"; - } - state.pos += url.length - proto.length; - return true; - } - - // Proceess '\n' - - function newline(state, silent) { - let pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x0a /* \n */) { - return false; + if (!start || !end) { + sel.removeAllRanges(); + return; } - const pmax = state.pending.length - 1; - const max = state.posMax; - - // ' \n' -> hardbreak - // Lookup in pending chars is bad practice! Don't copy to other rules! - // Pending string is stored in concat mode, indexed lookups will cause - // convertion to flat mode. - if (!silent) { - if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { - if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { - // Find whitespaces tail of pending chars. - let ws = pmax - 1; - while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) - ws--; - state.pending = state.pending.slice(0, ws); - state.push("hardbreak", "br", 0); - } else { - state.pending = state.pending.slice(0, -1); - state.push("softbreak", "br", 0); + var old = sel.rangeCount && sel.getRangeAt(0), + rng; + try { + rng = range(start.node, start.offset, end.offset, end.node); + } catch (e) {} + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) { + sel.removeAllRanges(); + sel.addRange(rng); } } else { - state.push("softbreak", "br", 0); - } - } - pos++; - - // skip heading spaces for next line - while (pos < max && isSpace(state.src.charCodeAt(pos))) { - pos++; - } - state.pos = pos; - return true; - } - - // Process escaped chars and hardbreaks - - const ESCAPED = []; - for (let i = 0; i < 256; i++) { - ESCAPED.push(0); - } - "\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function (ch) { - ESCAPED[ch.charCodeAt(0)] = 1; - }); - function escape(state, silent) { - let pos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(pos) !== 0x5c /* \ */) return false; - pos++; - - // '\' at the end of the inline block - if (pos >= max) return false; - let ch1 = state.src.charCodeAt(pos); - if (ch1 === 0x0a) { - if (!silent) { - state.push("hardbreak", "br", 0); + sel.removeAllRanges(); + sel.addRange(rng); } - pos++; - // skip leading whitespaces from next line - while (pos < max) { - ch1 = state.src.charCodeAt(pos); - if (!isSpace(ch1)) break; - pos++; + if (old && sel.anchorNode == null) { + sel.addRange(old); + } else if (gecko) { + this.startGracePeriod(); } - state.pos = pos; - return true; } - let escapedStr = state.src[pos]; - if (ch1 >= 0xd800 && ch1 <= 0xdbff && pos + 1 < max) { - const ch2 = state.src.charCodeAt(pos + 1); - if (ch2 >= 0xdc00 && ch2 <= 0xdfff) { - escapedStr += state.src[pos + 1]; - pos++; + this.rememberSelection(); + }; + ContentEditableInput.prototype.startGracePeriod = function () { + var this$1$1 = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + this$1$1.gracePeriod = false; + if (this$1$1.selectionChanged()) { + this$1$1.cm.operation(function () { + return this$1$1.cm.curOp.selectionChanged = true; + }); } + }, 20); + }; + ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }; + ContentEditableInput.prototype.rememberSelection = function () { + var sel = this.getSelection(); + this.lastAnchorNode = sel.anchorNode; + this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; + this.lastFocusOffset = sel.focusOffset; + }; + ContentEditableInput.prototype.selectionInEditor = function () { + var sel = this.getSelection(); + if (!sel.rangeCount) { + return false; } - const origStr = "\\" + escapedStr; - if (!silent) { - const token = state.push("text_special", "", 0); - if (ch1 < 256 && ESCAPED[ch1] !== 0) { - token.content = escapedStr; - } else { - token.content = origStr; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }; + ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor() || activeElt() != this.div) { + this.showSelection(this.prepareSelection(), true); } - token.markup = origStr; - token.info = "escape"; + this.div.focus(); } - state.pos = pos + 1; + }; + ContentEditableInput.prototype.blur = function () { + this.div.blur(); + }; + ContentEditableInput.prototype.getField = function () { + return this.div; + }; + ContentEditableInput.prototype.supportsTouch = function () { return true; - } - - // Parse backticks - - function backtick(state, silent) { - let pos = state.pos; - const ch = state.src.charCodeAt(pos); - if (ch !== 0x60 /* ` */) { - return false; + }; + ContentEditableInput.prototype.receivedFocus = function () { + var this$1$1 = this; + var input = this; + if (this.selectionInEditor()) { + setTimeout(function () { + return this$1$1.pollSelection(); + }, 20); + } else { + runInOp(this.cm, function () { + return input.cm.curOp.selectionChanged = true; + }); + } + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }; + ContentEditableInput.prototype.selectionChanged = function () { + var sel = this.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }; + ContentEditableInput.prototype.pollSelection = function () { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { + return; } - const start = pos; - pos++; - const max = state.posMax; - - // scan marker length - while (pos < max && state.src.charCodeAt(pos) === 0x60 /* ` */) { - pos++; + var sel = this.getSelection(), + cm = this.cm; + if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({ + type: "keydown", + keyCode: 8, + preventDefault: Math.abs + }); + this.blur(); + this.focus(); + return; } - const marker = state.src.slice(start, pos); - const openerLength = marker.length; - if ( - state.backticksScanned && - (state.backticks[openerLength] || 0) <= start - ) { - if (!silent) state.pending += marker; - state.pos += openerLength; - return true; + if (this.composing) { + return; } - let matchEnd = pos; - let matchStart; - - // Nothing found in the cache, scan until the end of the line (or until marker is found) - while ((matchStart = state.src.indexOf("`", matchEnd)) !== -1) { - matchEnd = matchStart + 1; - - // scan marker length - while ( - matchEnd < max && - state.src.charCodeAt(matchEnd) === 0x60 /* ` */ - ) { - matchEnd++; - } - const closerLength = matchEnd - matchStart; - if (closerLength === openerLength) { - // Found matching closer length. - if (!silent) { - const token = state.push("code_inline", "code", 0); - token.markup = marker; - token.content = state.src - .slice(pos, matchStart) - .replace(/\n/g, " ") - .replace(/^ (.+) $/, "$1"); + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) { + cm.curOp.selectionChanged = true; } - state.pos = matchEnd; - return true; - } - - // Some different length found, put it in cache as upper limit of where closer can be found - state.backticks[closerLength] = matchStart; + }); } - - // Scanned through the end, didn't find anything - state.backticksScanned = true; - if (!silent) state.pending += marker; - state.pos += openerLength; - return true; - } - - // ~~strike through~~ - // - - // Insert each marker as a separate text token, and add it to delimiter list - // - function strikethrough_tokenize(state, silent) { - const start = state.pos; - const marker = state.src.charCodeAt(start); - if (silent) { + }; + ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout); + this.readDOMTimeout = null; + } + var cm = this.cm, + display = cm.display, + sel = cm.doc.sel.primary(); + var from = sel.from(), + to = sel.to(); + if (from.ch == 0 && from.line > cm.firstLine()) { + from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); + } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { + to = Pos(to.line + 1, 0); + } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false; } - if (marker !== 0x7e /* ~ */) { - return false; + var fromIndex, fromLine, fromNode; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line); + fromNode = display.view[0].node; + } else { + fromLine = lineNo(display.view[fromIndex].line); + fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + var toLine, toNode; + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1; + toNode = display.lineDiv.lastChild; + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1; + toNode = display.view[toIndex + 1].node.previousSibling; } - const scanned = state.scanDelims(state.pos, true); - let len = scanned.length; - const ch = String.fromCharCode(marker); - if (len < 2) { + if (!fromNode) { return false; } - let token; - if (len % 2) { - token = state.push("text", "", 0); - token.content = ch; - len--; - } - for (let i = 0; i < len; i += 2) { - token = state.push("text", "", 0); - token.content = ch + ch; - state.delimiters.push({ - marker, - length: 0, - // disable "rule of 3" length checks meant for emphasis - token: state.tokens.length - 1, - end: -1, - open: scanned.can_open, - close: scanned.can_close, - }); - } - state.pos += scanned.length; - return true; - } - function postProcess$1(state, delimiters) { - let token; - const loneMarkers = []; - const max = delimiters.length; - for (let i = 0; i < max; i++) { - const startDelim = delimiters[i]; - if (startDelim.marker !== 0x7e /* ~ */) { - continue; - } - if (startDelim.end === -1) { - continue; - } - const endDelim = delimiters[startDelim.end]; - token = state.tokens[startDelim.token]; - token.type = "s_open"; - token.tag = "s"; - token.nesting = 1; - token.markup = "~~"; - token.content = ""; - token = state.tokens[endDelim.token]; - token.type = "s_close"; - token.tag = "s"; - token.nesting = -1; - token.markup = "~~"; - token.content = ""; - if ( - state.tokens[endDelim.token - 1].type === "text" && - state.tokens[endDelim.token - 1].content === "~" - ) { - loneMarkers.push(endDelim.token - 1); + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { + newText.pop(); + oldText.pop(); + toLine--; + } else if (newText[0] == oldText[0]) { + newText.shift(); + oldText.shift(); + fromLine++; + } else { + break; } } - - // If a marker sequence has an odd number of characters, it's splitted - // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the - // start of the sequence. - // - // So, we have to move all those markers after subsequent s_close tags. - // - while (loneMarkers.length) { - const i = loneMarkers.pop(); - let j = i + 1; - while ( - j < state.tokens.length && - state.tokens[j].type === "s_close" - ) { - j++; - } - j--; - if (i !== j) { - token = state.tokens[j]; - state.tokens[j] = state.tokens[i]; - state.tokens[i] = token; - } + var cutFront = 0, + cutEnd = 0; + var newTop = newText[0], + oldTop = oldText[0], + maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { + ++cutFront; + } + var newBot = lst(newText), + oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + ++cutEnd; + } + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront--; + cutEnd++; + } + } + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; } - } - - // Walk through delimiter list and replace text tokens with tags - // - function strikethrough_postProcess(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - postProcess$1(state, state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - postProcess$1(state, tokens_meta[curr].delimiters); + }; + ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { + return; + } + clearTimeout(this.readDOMTimeout); + this.composing = null; + this.updateFromDOM(); + this.div.blur(); + this.div.focus(); + }; + ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1$1 = this; + if (this.readDOMTimeout != null) { + return; + } + this.readDOMTimeout = setTimeout(function () { + this$1$1.readDOMTimeout = null; + if (this$1$1.composing) { + if (this$1$1.composing.done) { + this$1$1.composing = null; + } else { + return; + } } + this$1$1.updateFromDOM(); + }, 80); + }; + ContentEditableInput.prototype.updateFromDOM = function () { + var this$1$1 = this; + if (this.cm.isReadOnly() || !this.pollContent()) { + runInOp(this.cm, function () { + return regChange(this$1$1.cm); + }); } - } - var r_strikethrough = { - tokenize: strikethrough_tokenize, - postProcess: strikethrough_postProcess, }; - - // Process *this* and _that_ - // - - // Insert each marker as a separate text token, and add it to delimiter list - // - function emphasis_tokenize(state, silent) { - const start = state.pos; - const marker = state.src.charCodeAt(start); - if (silent) { - return false; + ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false"; + }; + ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0 || this.composing) { + return; } - if (marker !== 0x5f /* _ */ && marker !== 0x2a /* * */) { - return false; + e.preventDefault(); + if (!this.cm.isReadOnly()) { + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } - const scanned = state.scanDelims(state.pos, marker === 0x2a); - for (let i = 0; i < scanned.length; i++) { - const token = state.push("text", "", 0); - token.content = String.fromCharCode(marker); - state.delimiters.push({ - // Char code of the starting marker (number). - // - marker, - // Total length of these series of delimiters. - // - length: scanned.length, - // A position of the token this delimiter corresponds to. - // - token: state.tokens.length - 1, - // If this delimiter is matched as a valid opener, `end` will be - // equal to its position, otherwise it's `-1`. - // - end: -1, - // Boolean flags that determine if this delimiter could open or close - // an emphasis. - // - open: scanned.can_open, - close: scanned.can_close, - }); + }; + ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor"); + }; + ContentEditableInput.prototype.onContextMenu = function () {}; + ContentEditableInput.prototype.resetPosition = function () {}; + ContentEditableInput.prototype.needsContentAttribute = true; + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) { + return null; } - state.pos += scanned.length; - return true; - } - function postProcess(state, delimiters) { - const max = delimiters.length; - for (let i = max - 1; i >= 0; i--) { - const startDelim = delimiters[i]; - if ( - startDelim.marker !== 0x5f /* _ */ && - startDelim.marker !== 0x2a /* * */ - ) { - continue; - } - - // Process only opening markers - if (startDelim.end === -1) { - continue; - } - const endDelim = delimiters[startDelim.end]; - - // If the previous delimiter has the same marker and is adjacent to this one, - // merge those into one strong delimiter. - // - // `whatever` -> `whatever` - // - const isStrong = - i > 0 && - delimiters[i - 1].end === startDelim.end + 1 && - // check that first two markers match and adjacent - delimiters[i - 1].marker === startDelim.marker && - delimiters[i - 1].token === startDelim.token - 1 && - // check that last two markers are adjacent (we can safely assume they match) - delimiters[startDelim.end + 1].token === endDelim.token + 1; - const ch = String.fromCharCode(startDelim.marker); - const token_o = state.tokens[startDelim.token]; - token_o.type = isStrong ? "strong_open" : "em_open"; - token_o.tag = isStrong ? "strong" : "em"; - token_o.nesting = 1; - token_o.markup = isStrong ? ch + ch : ch; - token_o.content = ""; - const token_c = state.tokens[endDelim.token]; - token_c.type = isStrong ? "strong_close" : "em_close"; - token_c.tag = isStrong ? "strong" : "em"; - token_c.nesting = -1; - token_c.markup = isStrong ? ch + ch : ch; - token_c.content = ""; - if (isStrong) { - state.tokens[delimiters[i - 1].token].content = ""; - state.tokens[delimiters[startDelim.end + 1].token].content = ""; - i--; - } + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + var order = getOrder(line, cm.doc.direction), + side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; } - - // Walk through delimiter list and replace text tokens with tags - // - function emphasis_post_process(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - postProcess(state, state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - postProcess(state, tokens_meta[curr].delimiters); + function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) { + if (/CodeMirror-gutter-wrapper/.test(scan.className)) { + return true; } } + return false; } - var r_emphasis = { - tokenize: emphasis_tokenize, - postProcess: emphasis_post_process, - }; - - // Process [link]( "stuff") - - function link(state, silent) { - let code, label, res, ref; - let href = ""; - let title = ""; - let start = state.pos; - let parseReference = true; - if (state.src.charCodeAt(state.pos) !== 0x5b /* [ */) { - return false; + function badPos(pos, bad) { + if (bad) { + pos.bad = true; } - const oldPos = state.pos; - const max = state.posMax; - const labelStart = state.pos + 1; - const labelEnd = state.md.helpers.parseLinkLabel( - state, - state.pos, - true - ); - - // parser failed to find ']', so it's not a valid link - if (labelEnd < 0) { - return false; + return pos; + } + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", + closing = false, + lineSep = cm.doc.lineSeparator(), + extraLinebreak = false; + function recognizeMarker(id) { + return function (marker) { + return marker.id == id; + }; } - let pos = labelEnd + 1; - if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { - // - // Inline link - // - - // might have found a valid shortcut link, disable reference parsing - parseReference = false; - - // [link]( "title" ) - // ^^ skipping these spaces - pos++; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0a) { - break; + function close() { + if (closing) { + text += lineSep; + if (extraLinebreak) { + text += lineSep; } + closing = extraLinebreak = false; } - if (pos >= max) { - return false; + } + function addText(str) { + if (str) { + close(); + text += str; } - - // [link]( "title" ) - // ^^^^^^ parsing link destination - start = pos; - res = state.md.helpers.parseLinkDestination( - state.src, - pos, - state.posMax - ); - if (res.ok) { - href = state.md.normalizeLink(res.str); - if (state.md.validateLink(href)) { - pos = res.pos; - } else { - href = ""; + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText) { + addText(cmText); + return; } - - // [link]( "title" ) - // ^^ skipping these spaces - start = pos; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0a) { - break; + var markerID = node.getAttribute("cm-marker"), + range2; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range2 = found[0].find(0))) { + addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep)); } + return; } - - // [link]( "title" ) - // ^^^^^^^ parsing link title - res = state.md.helpers.parseLinkTitle( - state.src, - pos, - state.posMax - ); - if (pos < max && start !== pos && res.ok) { - title = res.str; - pos = res.pos; - - // [link]( "title" ) - // ^^ skipping these spaces - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0a) { - break; - } - } + if (node.getAttribute("contenteditable") == "false") { + return; + } + var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); + if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { + return; + } + if (isBlock) { + close(); + } + for (var i2 = 0; i2 < node.childNodes.length; i2++) { + walk(node.childNodes[i2]); + } + if (/^(pre|p)$/i.test(node.nodeName)) { + extraLinebreak = true; + } + if (isBlock) { + closing = true; } + } else if (node.nodeType == 3) { + addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); } - if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { - // parsing a valid shortcut link failed, fallback to reference - parseReference = true; + } + for (;;) { + walk(from); + if (from == to) { + break; } - pos++; + from = from.nextSibling; + extraLinebreak = false; } - if (parseReference) { - // - // Link reference - // - if (typeof state.env.references === "undefined") { - return false; + return text; + } + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) { + return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); } - if (pos < max && state.src.charCodeAt(pos) === 0x5b /* [ */) { - start = pos + 1; - pos = state.md.helpers.parseLinkLabel(state, pos); - if (pos >= 0) { - label = state.src.slice(start, pos++); - } else { - pos = labelEnd + 1; + node = null; + offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { + return null; + } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { + break; } - } else { - pos = labelEnd + 1; } - - // covers label === '' and label === undefined - // (collapsed reference link and shortcut reference link respectively) - if (!label) { - label = state.src.slice(labelStart, labelEnd); - } - ref = state.env.references[normalizeReference(label)]; - if (!ref) { - state.pos = oldPos; - return false; + } + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + var lineView = cm.display.view[i2]; + if (lineView.node == lineNode) { + return locateNodeInLineView(lineView, node, offset); } - href = ref.href; - title = ref.title; } - - // - // We found the end of the link, and know for a fact it's a valid link; - // so all that's left to do is to call tokenizer. - // - if (!silent) { - state.pos = labelStart; - state.posMax = labelEnd; - const token_o = state.push("link_open", "a", 1); - const attrs = [["href", href]]; - token_o.attrs = attrs; - if (title) { - attrs.push(["title", title]); - } - state.linkLevel++; - state.md.inline.tokenize(state); - state.linkLevel--; - state.push("link_close", "a", -1); - } - state.pos = pos; - state.posMax = max; - return true; } - - // Process ![image]( "title") - - function image(state, silent) { - let code, content, label, pos, ref, res, title, start; - let href = ""; - const oldPos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(state.pos) !== 0x21 /* ! */) { - return false; + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, + bad = false; + if (!node || !contains(wrapper, node)) { + return badPos(Pos(lineNo(lineView.line), 0), true); } - if (state.src.charCodeAt(state.pos + 1) !== 0x5b /* [ */) { - return false; + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } } - const labelStart = state.pos + 2; - const labelEnd = state.md.helpers.parseLinkLabel( - state, - state.pos + 1, - false - ); - - // parser failed to find ']', so it's not a valid link - if (labelEnd < 0) { - return false; + var textNode = node.nodeType == 3 ? node : null, + topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) { + offset = textNode.nodeValue.length; + } } - pos = labelEnd + 1; - if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { - // - // Inline link - // - - // [link]( "title" ) - // ^^ skipping these spaces - pos++; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0a) { - break; + while (topNode.parentNode != wrapper) { + topNode = topNode.parentNode; + } + var measure = lineView.measure, + maps = measure.maps; + function find(textNode2, topNode2, offset2) { + for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { + var map2 = i2 < 0 ? measure.map : maps[i2]; + for (var j = 0; j < map2.length; j += 3) { + var curNode = map2[j + 2]; + if (curNode == textNode2 || curNode == topNode2) { + var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]); + var ch = map2[j] + offset2; + if (offset2 < 0 || curNode != textNode2) { + ch = map2[j + (offset2 ? 1 : 0)]; + } + return Pos(line2, ch); + } } } - if (pos >= max) { - return false; + } + var found = find(textNode, topNode, offset); + if (found) { + return badPos(found, bad); + } + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) { + return badPos(Pos(found.line, found.ch - dist), bad); + } else { + dist += after.textContent.length; } - - // [link]( "title" ) - // ^^^^^^ parsing link destination - start = pos; - res = state.md.helpers.parseLinkDestination( - state.src, - pos, - state.posMax - ); - if (res.ok) { - href = state.md.normalizeLink(res.str); - if (state.md.validateLink(href)) { - pos = res.pos; + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) { + return badPos(Pos(found.line, found.ch + dist$1), bad); + } else { + dist$1 += before.textContent.length; + } + } + } + var TextareaInput = function (cm) { + this.cm = cm; + this.prevInput = ""; + this.pollingFast = false; + this.polling = new Delayed(); + this.hasSelection = false; + this.composing = null; + }; + TextareaInput.prototype.init = function (display) { + var this$1$1 = this; + var input = this, + cm = this.cm; + this.createField(display); + var te = this.textarea; + display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); + if (ios) { + te.style.width = "0px"; + } + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1$1.hasSelection) { + this$1$1.hasSelection = null; + } + input.poll(); + }); + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; + } + cm.state.pasteIncoming = + /* @__PURE__ */new Date(); + input.fastPoll(); + }); + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ + lineWise: false, + text: cm.getSelections() + }); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ + lineWise: true, + text: ranges.text + }); + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); } else { - href = ""; + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); } } - - // [link]( "title" ) - // ^^ skipping these spaces - start = pos; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0a) { - break; - } + if (e.type == "cut") { + cm.state.cutIncoming = + /* @__PURE__ */new Date(); } - - // [link]( "title" ) - // ^^^^^^^ parsing link title - res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); - if (pos < max && start !== pos && res.ok) { - title = res.str; - pos = res.pos; - - // [link]( "title" ) - // ^^ skipping these spaces - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0a) { - break; - } - } - } else { - title = ""; + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { + return; } - if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { - state.pos = oldPos; - return false; + if (!te.dispatchEvent) { + cm.state.pasteIncoming = + /* @__PURE__ */new Date(); + input.focus(); + return; } - pos++; + var event = new Event("paste"); + event.clipboardData = e.clipboardData; + te.dispatchEvent(event); + }); + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { + e_preventDefault(e); + } + }); + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + if (input.composing) { + input.composing.range.clear(); + } + input.composing = { + start, + range: cm.markText(start, cm.getCursor("to"), { + className: "CodeMirror-composing" + }) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }; + TextareaInput.prototype.createField = function (_display) { + this.wrapper = hiddenTextarea(); + this.textarea = this.wrapper.firstChild; + }; + TextareaInput.prototype.screenReaderLabelChanged = function (label) { + if (label) { + this.textarea.setAttribute("aria-label", label); } else { - // - // Link reference - // - if (typeof state.env.references === "undefined") { - return false; + this.textarea.removeAttribute("aria-label"); + } + }; + TextareaInput.prototype.prepareSelection = function () { + var cm = this.cm, + display = cm.display, + doc = cm.doc; + var result = prepareSelection(cm); + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), + lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); + } + return result; + }; + TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, + display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }; + TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending || this.composing) { + return; + } + var cm = this.cm; + if (cm.somethingSelected()) { + this.prevInput = ""; + var content = cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) { + selectInput(this.textarea); } - if (pos < max && state.src.charCodeAt(pos) === 0x5b /* [ */) { - start = pos + 1; - pos = state.md.helpers.parseLinkLabel(state, pos); - if (pos >= 0) { - label = state.src.slice(start, pos++); - } else { - pos = labelEnd + 1; - } - } else { - pos = labelEnd + 1; + if (ie && ie_version >= 9) { + this.hasSelection = content; } - - // covers label === '' and label === undefined - // (collapsed reference link and shortcut reference link respectively) - if (!label) { - label = state.src.slice(labelStart, labelEnd); - } - ref = state.env.references[normalizeReference(label)]; - if (!ref) { - state.pos = oldPos; - return false; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) { + this.hasSelection = null; } - href = ref.href; - title = ref.title; } - - // - // We found the end of the link, and know for a fact it's a valid link; - // so all that's left to do is to call tokenizer. - // - if (!silent) { - content = state.src.slice(labelStart, labelEnd); - const tokens = []; - state.md.inline.parse(content, state.md, state.env, tokens); - const token = state.push("image", "img", 0); - const attrs = [ - ["src", href], - ["alt", ""], - ]; - token.attrs = attrs; - token.children = tokens; - token.content = content; - if (title) { - attrs.push(["title", title]); - } - } - state.pos = pos; - state.posMax = max; - return true; - } - - // Process autolinks '' - - /* eslint max-len:0 */ - const EMAIL_RE = - /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; - /* eslint-disable-next-line no-control-regex */ - const AUTOLINK_RE = - /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/; - function autolink(state, silent) { - let pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x3c /* < */) { - return false; + }; + TextareaInput.prototype.getField = function () { + return this.textarea; + }; + TextareaInput.prototype.supportsTouch = function () { + return false; + }; + TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { + this.textarea.focus(); + } catch (e) {} } - const start = state.pos; - const max = state.posMax; - for (;;) { - if (++pos >= max) return false; - const ch = state.src.charCodeAt(pos); - if (ch === 0x3c /* < */) return false; - if (ch === 0x3e /* > */) break; + }; + TextareaInput.prototype.blur = function () { + this.textarea.blur(); + }; + TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }; + TextareaInput.prototype.receivedFocus = function () { + this.slowPoll(); + }; + TextareaInput.prototype.slowPoll = function () { + var this$1$1 = this; + if (this.pollingFast) { + return; } - const url = state.src.slice(start + 1, pos); - if (AUTOLINK_RE.test(url)) { - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) { - return false; + this.polling.set(this.cm.options.pollInterval, function () { + this$1$1.poll(); + if (this$1$1.cm.state.focused) { + this$1$1.slowPoll(); } - if (!silent) { - const token_o = state.push("link_open", "a", 1); - token_o.attrs = [["href", fullUrl]]; - token_o.markup = "autolink"; - token_o.info = "auto"; - const token_t = state.push("text", "", 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push("link_close", "a", -1); - token_c.markup = "autolink"; - token_c.info = "auto"; - } - state.pos += url.length + 2; - return true; - } - if (EMAIL_RE.test(url)) { - const fullUrl = state.md.normalizeLink("mailto:" + url); - if (!state.md.validateLink(fullUrl)) { - return false; + }); + }; + TextareaInput.prototype.fastPoll = function () { + var missed = false, + input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) { + missed = true; + input.polling.set(60, p); + } else { + input.pollingFast = false; + input.slowPoll(); } - if (!silent) { - const token_o = state.push("link_open", "a", 1); - token_o.attrs = [["href", fullUrl]]; - token_o.markup = "autolink"; - token_o.info = "auto"; - const token_t = state.push("text", "", 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push("link_close", "a", -1); - token_c.markup = "autolink"; - token_c.info = "auto"; - } - state.pos += url.length + 2; - return true; } - return false; - } - - // Process html tags - - function isLinkOpen(str) { - return /^\s]/i.test(str); - } - function isLinkClose(str) { - return /^<\/a\s*>/i.test(str); - } - function isLetter(ch) { - /* eslint no-bitwise:0 */ - const lc = ch | 0x20; // to lower case - return lc >= 0x61 /* a */ && lc <= 0x7a /* z */; - } - function html_inline(state, silent) { - if (!state.md.options.html) { + input.polling.set(20, p); + }; + TextareaInput.prototype.poll = function () { + var this$1$1 = this; + var cm = this.cm, + input = this.textarea, + prevInput = this.prevInput; + if (this.contextMenuPending || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { return false; } - - // Check start - const max = state.posMax; - const pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x3c /* < */ || pos + 2 >= max) { + var text = input.value; + if (text == prevInput && !cm.somethingSelected()) { return false; } - - // Quick fail on second char - const ch = state.src.charCodeAt(pos + 1); - if ( - ch !== 0x21 /* ! */ && - ch !== 0x3f /* ? */ && - ch !== 0x2f /* / */ && - !isLetter(ch) - ) { + if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); return false; } - const match = state.src.slice(pos).match(HTML_TAG_RE); - if (!match) { - return false; + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 8203 && !prevInput) { + prevInput = "​"; + } + if (first == 8666) { + this.reset(); + return this.cm.execCommand("undo"); + } } - if (!silent) { - const token = state.push("html_inline", "", 0); - token.content = match[0]; - if (isLinkOpen(token.content)) state.linkLevel++; - if (isLinkClose(token.content)) state.linkLevel--; + var same = 0, + l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { + ++same; } - state.pos += match[0].length; - return true; - } - - // Process html entity - {, ¯, ", ... - - const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; - const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; - function entity(state, silent) { - const pos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(pos) !== 0x26 /* & */) return false; - if (pos + 1 >= max) return false; - const ch = state.src.charCodeAt(pos + 1); - if (ch === 0x23 /* # */) { - const match = state.src.slice(pos).match(DIGITAL_RE); - if (match) { - if (!silent) { - const code = - match[1][0].toLowerCase() === "x" - ? parseInt(match[1].slice(1), 16) - : parseInt(match[1], 10); - const token = state.push("text_special", "", 0); - token.content = isValidEntityCode(code) - ? fromCodePoint(code) - : fromCodePoint(0xfffd); - token.markup = match[0]; - token.info = "entity"; - } - state.pos += match[0].length; - return true; + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1$1.composing ? "*compose" : null); + if (text.length > 1e3 || text.indexOf("\n") > -1) { + input.value = this$1$1.prevInput = ""; + } else { + this$1$1.prevInput = text; } - } else { - const match = state.src.slice(pos).match(NAMED_RE); - if (match) { - const decoded = entities.decodeHTML(match[0]); - if (decoded !== match[0]) { - if (!silent) { - const token = state.push("text_special", "", 0); - token.content = decoded; - token.markup = match[0]; - token.info = "entity"; - } - state.pos += match[0].length; - return true; - } + if (this$1$1.composing) { + this$1$1.composing.range.clear(); + this$1$1.composing.range = cm.markText(this$1$1.composing.start, cm.getCursor("to"), { + className: "CodeMirror-composing" + }); } + }); + return true; + }; + TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { + this.pollingFast = false; } - return false; - } - - // For each opening emphasis-like marker find a matching closing one - // - - function processDelimiters(delimiters) { - const openersBottom = {}; - const max = delimiters.length; - if (!max) return; - - // headerIdx is the first delimiter of the current (where closer is) delimiter run - let headerIdx = 0; - let lastTokenIdx = -2; // needs any value lower than -1 - const jumps = []; - for (let closerIdx = 0; closerIdx < max; closerIdx++) { - const closer = delimiters[closerIdx]; - jumps.push(0); - - // markers belong to same delimiter run if: - // - they have adjacent tokens - // - AND markers are the same - // - if ( - delimiters[headerIdx].marker !== closer.marker || - lastTokenIdx !== closer.token - 1 - ) { - headerIdx = closerIdx; + }; + TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { + this.hasSelection = null; + } + this.fastPoll(); + }; + TextareaInput.prototype.onContextMenu = function (e) { + var input = this, + cm = input.cm, + display = cm.display, + te = input.textarea; + if (input.contextMenuPending) { + input.contextMenuPending(); + } + var pos = posFromMouse(cm, e), + scrollPos = display.scroller.scrollTop; + if (!pos || presto) { + return; + } + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) { + operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + } + var oldCSS = te.style.cssText, + oldWrapperCSS = input.wrapper.style.cssText; + var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); + input.wrapper.style.cssText = "position: static"; + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + var oldScrollY; + if (webkit) { + oldScrollY = window.scrollY; + } + display.input.focus(); + if (webkit) { + window.scrollTo(null, oldScrollY); + } + display.input.reset(); + if (!cm.somethingSelected()) { + te.value = input.prevInput = " "; + } + input.contextMenuPending = rehide; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "​" + (selected ? te.value : ""); + te.value = "⇚"; + te.value = extval; + input.prevInput = selected ? "" : "​"; + te.selectionStart = 1; + te.selectionEnd = extval.length; + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + if (input.contextMenuPending != rehide) { + return; } - lastTokenIdx = closer.token; - - // Length is only used for emphasis-specific "rule of 3", - // if it's not defined (in strikethrough or 3rd party plugins), - // we can default it to 0 to disable those checks. - // - closer.length = closer.length || 0; - if (!closer.close) continue; - - // Previously calculated lower bounds (previous fails) - // for each marker, each delimiter length modulo 3, - // and for whether this closer can be an opener; - // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 - /* eslint-disable-next-line no-prototype-builtins */ - if (!openersBottom.hasOwnProperty(closer.marker)) { - openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]; - } - const minOpenerIdx = - openersBottom[closer.marker][ - (closer.open ? 3 : 0) + (closer.length % 3) - ]; - let openerIdx = headerIdx - jumps[headerIdx] - 1; - let newMinOpenerIdx = openerIdx; - for ( - ; - openerIdx > minOpenerIdx; - openerIdx -= jumps[openerIdx] + 1 - ) { - const opener = delimiters[openerIdx]; - if (opener.marker !== closer.marker) continue; - if (opener.open && opener.end < 0) { - let isOddMatch = false; - - // from spec: - // - // If one of the delimiters can both open and close emphasis, then the - // sum of the lengths of the delimiter runs containing the opening and - // closing delimiters must not be a multiple of 3 unless both lengths - // are multiples of 3. - // - if (opener.close || closer.open) { - if ((opener.length + closer.length) % 3 === 0) { - if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { - isOddMatch = true; - } + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) { + display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + } + if (te.selectionStart != null) { + if (!ie || ie && ie_version < 9) { + prepareSelectAllHack(); + } + var i2 = 0, + poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "​") { + operation(cm, selectAll)(cm); + } else if (i2++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500); + } else { + display.selForContextMenu = null; + display.input.reset(); } - } - if (!isOddMatch) { - // If previous delimiter cannot be an opener, we can safely skip - // the entire sequence in future checks. This is required to make - // sure algorithm has linear complexity (see *_*_*_*_*_... case). - // - const lastJump = - openerIdx > 0 && !delimiters[openerIdx - 1].open - ? jumps[openerIdx - 1] + 1 - : 0; - jumps[closerIdx] = closerIdx - openerIdx + lastJump; - jumps[openerIdx] = lastJump; - closer.open = false; - opener.end = closerIdx; - opener.close = false; - newMinOpenerIdx = -1; - // treat next token as start of run, - // it optimizes skips in **<...>**a**<...>** pathological case - lastTokenIdx = -2; - break; - } - } - } - if (newMinOpenerIdx !== -1) { - // If match for this delimiter run failed, we want to set lower bound for - // future lookups. This is required to make sure algorithm has linear - // complexity. - // - // See details here: - // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 - // - openersBottom[closer.marker][ - (closer.open ? 3 : 0) + ((closer.length || 0) % 3) - ] = newMinOpenerIdx; + }; + display.detectingSelectAll = setTimeout(poll, 200); } } - } - function link_pairs(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - processDelimiters(state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - processDelimiters(tokens_meta[curr].delimiters); - } + if (ie && ie_version >= 9) { + prepareSelectAllHack(); } - } - - // Clean up tokens after emphasis and strikethrough postprocessing: - // merge adjacent text nodes into one and re-calculate all token levels - // - // This is necessary because initially emphasis delimiter markers (*, _, ~) - // are treated as their own separate text tokens. Then emphasis rule either - // leaves them as text (needed to merge with adjacent text) or turns them - // into opening/closing tags (which messes up levels inside). - // - - function fragments_join(state) { - let curr, last; - let level = 0; - const tokens = state.tokens; - const max = state.tokens.length; - for (curr = last = 0; curr < max; curr++) { - // re-calculate levels after emphasis/strikethrough turns some text nodes - // into opening/closing tags - if (tokens[curr].nesting < 0) level--; // closing tag - tokens[curr].level = level; - if (tokens[curr].nesting > 0) level++; // opening tag - - if ( - tokens[curr].type === "text" && - curr + 1 < max && - tokens[curr + 1].type === "text" - ) { - // collapse two adjacent text nodes - tokens[curr + 1].content = - tokens[curr].content + tokens[curr + 1].content; - } else { - if (curr !== last) { - tokens[last] = tokens[curr]; - } - last++; + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }; + TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { + this.reset(); + } + this.textarea.disabled = val == "nocursor"; + this.textarea.readOnly = !!val; + }; + TextareaInput.prototype.setUneditable = function () {}; + TextareaInput.prototype.needsContentAttribute = false; + function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) { + options.tabindex = textarea.tabIndex; + } + if (!options.placeholder && textarea.placeholder) { + options.placeholder = textarea.placeholder; + } + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + function save() { + textarea.value = cm.getValue(); + } + var realSubmit; + if (textarea.form) { + on(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form; + realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch (e) {} } } - if (curr !== last) { - tokens.length = last; + options.finishInit = function (cm2) { + cm2.save = save; + cm2.getTextArea = function () { + return textarea; + }; + cm2.toTextArea = function () { + cm2.toTextArea = isNaN; + save(); + textarea.parentNode.removeChild(cm2.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { + textarea.form.submit = realSubmit; + } + } + }; + }; + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { + return textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + } + function addLegacyProps(CodeMirror2) { + CodeMirror2.off = off; + CodeMirror2.on = on; + CodeMirror2.wheelEventPixels = wheelEventPixels; + CodeMirror2.Doc = Doc; + CodeMirror2.splitLines = splitLinesAuto; + CodeMirror2.countColumn = countColumn; + CodeMirror2.findColumn = findColumn; + CodeMirror2.isWordChar = isWordCharBasic; + CodeMirror2.Pass = Pass; + CodeMirror2.signal = signal; + CodeMirror2.Line = Line; + CodeMirror2.changeEnd = changeEnd; + CodeMirror2.scrollbarModel = scrollbarModel; + CodeMirror2.Pos = Pos; + CodeMirror2.cmpPos = cmp; + CodeMirror2.modes = modes; + CodeMirror2.mimeModes = mimeModes; + CodeMirror2.resolveMode = resolveMode; + CodeMirror2.getMode = getMode; + CodeMirror2.modeExtensions = modeExtensions; + CodeMirror2.extendMode = extendMode; + CodeMirror2.copyState = copyState; + CodeMirror2.startState = startState; + CodeMirror2.innerMode = innerMode; + CodeMirror2.commands = commands; + CodeMirror2.keyMap = keyMap; + CodeMirror2.keyName = keyName; + CodeMirror2.isModifierKey = isModifierKey; + CodeMirror2.lookupKey = lookupKey; + CodeMirror2.normalizeKeyMap = normalizeKeyMap; + CodeMirror2.StringStream = StringStream; + CodeMirror2.SharedTextMarker = SharedTextMarker; + CodeMirror2.TextMarker = TextMarker; + CodeMirror2.LineWidget = LineWidget; + CodeMirror2.e_preventDefault = e_preventDefault; + CodeMirror2.e_stopPropagation = e_stopPropagation; + CodeMirror2.e_stop = e_stop; + CodeMirror2.addClass = addClass; + CodeMirror2.contains = contains; + CodeMirror2.rmClass = rmClass; + CodeMirror2.keyNames = keyNames; + } + defineOptions(CodeMirror); + addEditorMethods(CodeMirror); + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { + CodeMirror.prototype[prop] = /* @__PURE__ */function (method) { + return function () { + return method.apply(this.doc, arguments); + }; + }(Doc.prototype[prop]); } } - - /** internal - * class ParserInline - * - * Tokenizes paragraph content. - **/ - - // Parser rules - - const _rules = [ - ["text", text], - ["linkify", linkify], - ["newline", newline], - ["escape", escape], - ["backticks", backtick], - ["strikethrough", r_strikethrough.tokenize], - ["emphasis", r_emphasis.tokenize], - ["link", link], - ["image", image], - ["autolink", autolink], - ["html_inline", html_inline], - ["entity", entity], - ]; - - // `rule2` ruleset was created specifically for emphasis/strikethrough - // post-processing and may be changed in the future. - // - // Don't use this for anything except pairs (plugins working with `balance_pairs`). - // - const _rules2 = [ - ["balance_pairs", link_pairs], - ["strikethrough", r_strikethrough.postProcess], - ["emphasis", r_emphasis.postProcess], - // rules for pairs separate '**' into its own text tokens, which may be left unused, - // rule below merges unused segments back with the rest of the text - ["fragments_join", fragments_join], - ]; - - /** - * new ParserInline() - **/ - function ParserInline() { - /** - * ParserInline#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of inline rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules.length; i++) { - this.ruler.push(_rules[i][0], _rules[i][1]); + eventMixin(Doc); + CodeMirror.inputStyles = { + "textarea": TextareaInput, + "contenteditable": ContentEditableInput + }; + CodeMirror.defineMode = function (name) { + if (!CodeMirror.defaults.mode && name != "null") { + CodeMirror.defaults.mode = name; } - - /** - * ParserInline#ruler2 -> Ruler - * - * [[Ruler]] instance. Second ruler used for post-processing - * (e.g. in emphasis-like rules). - **/ - this.ruler2 = new Ruler(); - for (let i = 0; i < _rules2.length; i++) { - this.ruler2.push(_rules2[i][0], _rules2[i][1]); + defineMode.apply(this, arguments); + }; + CodeMirror.defineMIME = defineMIME; + CodeMirror.defineMode("null", function () { + return { + token: function (stream) { + return stream.skipToEnd(); + } + }; + }); + CodeMirror.defineMIME("text/plain", "null"); + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.fromTextArea = fromTextArea; + addLegacyProps(CodeMirror); + CodeMirror.version = "5.65.3"; + return CodeMirror; + }); + })(codemirror); + return codemirror.exports; + } + exports.getDefaultExportFromCjs = getDefaultExportFromCjs; + exports.requireCodemirror = requireCodemirror; + + /***/ }), + + /***/ "../../graphiql-react/dist/comment.cjs.js": + /*!************************************************!*\ + !*** ../../graphiql-react/dist/comment.cjs.js ***! + \************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } } - - // Skip single token by running all rules in validation mode; - // returns `true` if any rule reported success - // - ParserInline.prototype.skipToken = function (state) { - const pos = state.pos; - const rules = this.ruler.getRules(""); - const len = rules.length; - const maxNesting = state.md.options.maxNesting; - const cache = state.cache; - if (typeof cache[pos] !== "undefined") { - state.pos = cache[pos]; - return; + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var comment$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var noOptions = {}; + var nonWS = /[^\s\u00a0]/; + var Pos = CodeMirror.Pos, + cmp = CodeMirror.cmpPos; + function firstNonWS(str) { + var found = str.search(nonWS); + return found == -1 ? 0 : found; + } + CodeMirror.commands.toggleComment = function (cm) { + cm.toggleComment(); + }; + CodeMirror.defineExtension("toggleComment", function (options) { + if (!options) options = noOptions; + var cm = this; + var minLine = Infinity, + ranges = this.listSelections(), + mode = null; + for (var i = ranges.length - 1; i >= 0; i--) { + var from = ranges[i].from(), + to = ranges[i].to(); + if (from.line >= minLine) continue; + if (to.line >= minLine) to = Pos(minLine, 0); + minLine = from.line; + if (mode == null) { + if (cm.uncomment(from, to, options)) mode = "un";else { + cm.lineComment(from, to, options); + mode = "line"; + } + } else if (mode == "un") { + cm.uncomment(from, to, options); + } else { + cm.lineComment(from, to, options); } - let ok = false; - if (state.level < maxNesting) { - for (let i = 0; i < len; i++) { - // Increment state.level and decrement it later to limit recursion. - // It's harmless to do here, because no tokens are created. But ideally, - // we'd need a separate private state variable for this purpose. - // - state.level++; - ok = rules[i](state, true); - state.level--; - if (ok) { - if (pos >= state.pos) { - throw new Error("inline rule didn't increment state.pos"); - } - break; - } + } + }); + function probablyInsideString(cm, pos, line) { + return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line); + } + function getMode(cm, pos) { + var mode = cm.getMode(); + return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos); + } + CodeMirror.defineExtension("lineComment", function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var firstLine = self.getLine(from.line); + if (firstLine == null || probablyInsideString(self, from, firstLine)) return; + var commentString = options.lineComment || mode.lineComment; + if (!commentString) { + if (options.blockCommentStart || mode.blockCommentStart) { + options.fullLines = true; + self.blockComment(from, to, options); + } + return; + } + var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); + var pad = options.padding == null ? " " : options.padding; + var blankLines = options.commentBlankLines || from.line == to.line; + self.operation(function () { + if (options.indent) { + var baseString = null; + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i); + var whitespace = line.slice(0, firstNonWS(line)); + if (baseString == null || baseString.length > whitespace.length) { + baseString = whitespace; + } + } + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i), + cut = baseString.length; + if (!blankLines && !nonWS.test(line)) continue; + if (line.slice(0, cut) != baseString) cut = firstNonWS(line); + self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); } } else { - // Too much nesting, just skip until the end of the paragraph. - // - // NOTE: this will cause links to behave incorrectly in the following case, - // when an amount of `[` is exactly equal to `maxNesting + 1`: - // - // [[[[[[[[[[[[[[[[[[[[[foo]() - // - // TODO: remove this workaround when CM standard will allow nested links - // (we can replace it by preventing links from being parsed in - // validation mode) - // - state.pos = state.posMax; - } - if (!ok) { - state.pos++; + for (var i = from.line; i < end; ++i) { + if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); + } } - cache[pos] = state.pos; - }; - - // Generate tokens for input range - // - ParserInline.prototype.tokenize = function (state) { - const rules = this.ruler.getRules(""); - const len = rules.length; - const end = state.posMax; - const maxNesting = state.md.options.maxNesting; - while (state.pos < end) { - // Try all possible rules. - // On success, rule should: - // - // - update `state.pos` - // - update `state.tokens` - // - return true - const prevPos = state.pos; - let ok = false; - if (state.level < maxNesting) { - for (let i = 0; i < len; i++) { - ok = rules[i](state, false); - if (ok) { - if (prevPos >= state.pos) { - throw new Error("inline rule didn't increment state.pos"); - } - break; - } - } + }); + }); + CodeMirror.defineExtension("blockComment", function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var startString = options.blockCommentStart || mode.blockCommentStart; + var endString = options.blockCommentEnd || mode.blockCommentEnd; + if (!startString || !endString) { + if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); + return; + } + if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return; + var end = Math.min(to.line, self.lastLine()); + if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; + var pad = options.padding == null ? " " : options.padding; + if (from.line > end) return; + self.operation(function () { + if (options.fullLines != false) { + var lastLineHasText = nonWS.test(self.getLine(end)); + self.replaceRange(pad + endString, Pos(end)); + self.replaceRange(startString + pad, Pos(from.line, 0)); + var lead = options.blockCommentLead || mode.blockCommentLead; + if (lead != null) { + for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); } - if (ok) { - if (state.pos >= end) { - break; - } - continue; + } else { + var atCursor = cmp(self.getCursor("to"), to) == 0, + empty = !self.somethingSelected(); + self.replaceRange(endString, to); + if (atCursor) self.setSelection(empty ? to : self.getCursor("from"), to); + self.replaceRange(startString, from); + } + }); + }); + CodeMirror.defineExtension("uncomment", function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), + start = Math.min(from.line, end); + var lineString = options.lineComment || mode.lineComment, + lines = []; + var pad = options.padding == null ? " " : options.padding, + didSomething; + lineComment: { + if (!lineString) break lineComment; + for (var i = start; i <= end; ++i) { + var line = self.getLine(i); + var found = line.indexOf(lineString); + if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; + if (found == -1 && nonWS.test(line)) break lineComment; + if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; + lines.push(line); + } + self.operation(function () { + for (var i2 = start; i2 <= end; ++i2) { + var line2 = lines[i2 - start]; + var pos = line2.indexOf(lineString), + endPos = pos + lineString.length; + if (pos < 0) continue; + if (line2.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; + didSomething = true; + self.replaceRange("", Pos(i2, pos), Pos(i2, endPos)); + } + }); + if (didSomething) return true; + } + var startString = options.blockCommentStart || mode.blockCommentStart; + var endString = options.blockCommentEnd || mode.blockCommentEnd; + if (!startString || !endString) return false; + var lead = options.blockCommentLead || mode.blockCommentLead; + var startLine = self.getLine(start), + open = startLine.indexOf(startString); + if (open == -1) return false; + var endLine = end == start ? startLine : self.getLine(end); + var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); + var insideStart = Pos(start, open + 1), + insideEnd = Pos(end, close + 1); + if (close == -1 || !/comment/.test(self.getTokenTypeAt(insideStart)) || !/comment/.test(self.getTokenTypeAt(insideEnd)) || self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1) return false; + var lastStart = startLine.lastIndexOf(startString, from.ch); + var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); + if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; + firstEnd = endLine.indexOf(endString, to.ch); + var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); + lastStart = firstEnd == -1 || almostLastStart == -1 ? -1 : to.ch + almostLastStart; + if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; + self.operation(function () { + self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); + var openEnd = open + startString.length; + if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; + self.replaceRange("", Pos(start, open), Pos(start, openEnd)); + if (lead) for (var i2 = start + 1; i2 <= end; ++i2) { + var line2 = self.getLine(i2), + found2 = line2.indexOf(lead); + if (found2 == -1 || nonWS.test(line2.slice(0, found2))) continue; + var foundEnd = found2 + lead.length; + if (pad && line2.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; + self.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd)); + } + }); + return true; + }); + }); + })(); + var commentExports = comment$2.exports; + const comment = /* @__PURE__ */codemirror.getDefaultExportFromCjs(commentExports); + const comment$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: comment + }, [commentExports]); + exports.comment = comment$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/dialog.cjs.js": + /*!***********************************************!*\ + !*** ../../graphiql-react/dist/dialog.cjs.js ***! + \***********************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - state.pending += state.src[state.pos++]; } - if (state.pending) { - state.pushPending(); + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var dialog$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function dialogDiv(cm, template, bottom) { + var wrap = cm.getWrapperElement(); + var dialog2; + dialog2 = wrap.appendChild(document.createElement("div")); + if (bottom) dialog2.className = "CodeMirror-dialog CodeMirror-dialog-bottom";else dialog2.className = "CodeMirror-dialog CodeMirror-dialog-top"; + if (typeof template == "string") { + dialog2.innerHTML = template; + } else { + dialog2.appendChild(template); + } + CodeMirror.addClass(wrap, "dialog-opened"); + return dialog2; + } + function closeNotification(cm, newVal) { + if (cm.state.currentNotificationClose) cm.state.currentNotificationClose(); + cm.state.currentNotificationClose = newVal; + } + CodeMirror.defineExtension("openDialog", function (template, callback, options) { + if (!options) options = {}; + closeNotification(this, null); + var dialog2 = dialogDiv(this, template, options.bottom); + var closed = false, + me = this; + function close(newVal) { + if (typeof newVal == "string") { + inp.value = newVal; + } else { + if (closed) return; + closed = true; + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + me.focus(); + if (options.onClose) options.onClose(dialog2); } - }; - - /** - * ParserInline.parse(str, md, env, outTokens) - * - * Process input string and push inline tokens into `outTokens` - **/ - ParserInline.prototype.parse = function (str, md, env, outTokens) { - const state = new this.State(str, md, env, outTokens); - this.tokenize(state); - const rules = this.ruler2.getRules(""); - const len = rules.length; - for (let i = 0; i < len; i++) { - rules[i](state); + } + var inp = dialog2.getElementsByTagName("input")[0], + button; + if (inp) { + inp.focus(); + if (options.value) { + inp.value = options.value; + if (options.selectValueOnOpen !== false) { + inp.select(); + } } + if (options.onInput) CodeMirror.on(inp, "input", function (e) { + options.onInput(e, inp.value, close); + }); + if (options.onKeyUp) CodeMirror.on(inp, "keyup", function (e) { + options.onKeyUp(e, inp.value, close); + }); + CodeMirror.on(inp, "keydown", function (e) { + if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { + return; + } + if (e.keyCode == 27 || options.closeOnEnter !== false && e.keyCode == 13) { + inp.blur(); + CodeMirror.e_stop(e); + close(); + } + if (e.keyCode == 13) callback(inp.value, e); + }); + if (options.closeOnBlur !== false) CodeMirror.on(dialog2, "focusout", function (evt) { + if (evt.relatedTarget !== null) close(); + }); + } else if (button = dialog2.getElementsByTagName("button")[0]) { + CodeMirror.on(button, "click", function () { + close(); + me.focus(); + }); + if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); + button.focus(); + } + return close; + }); + CodeMirror.defineExtension("openConfirm", function (template, callbacks, options) { + closeNotification(this, null); + var dialog2 = dialogDiv(this, template, options && options.bottom); + var buttons = dialog2.getElementsByTagName("button"); + var closed = false, + me = this, + blurring = 1; + function close() { + if (closed) return; + closed = true; + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + me.focus(); + } + buttons[0].focus(); + for (var i = 0; i < buttons.length; ++i) { + var b = buttons[i]; + (function (callback) { + CodeMirror.on(b, "click", function (e) { + CodeMirror.e_preventDefault(e); + close(); + if (callback) callback(me); + }); + })(callbacks[i]); + CodeMirror.on(b, "blur", function () { + --blurring; + setTimeout(function () { + if (blurring <= 0) close(); + }, 200); + }); + CodeMirror.on(b, "focus", function () { + ++blurring; + }); + } + }); + CodeMirror.defineExtension("openNotification", function (template, options) { + closeNotification(this, close); + var dialog2 = dialogDiv(this, template, options && options.bottom); + var closed = false, + doneTimer; + var duration = options && typeof options.duration !== "undefined" ? options.duration : 5e3; + function close() { + if (closed) return; + closed = true; + clearTimeout(doneTimer); + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + } + CodeMirror.on(dialog2, "click", function (e) { + CodeMirror.e_preventDefault(e); + close(); + }); + if (duration) doneTimer = setTimeout(close, duration); + return close; + }); + }); + })(); + var dialogExports = dialog$2.exports; + const dialog = /* @__PURE__ */codemirror.getDefaultExportFromCjs(dialogExports); + const dialog$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: dialog + }, [dialogExports]); + exports.dialog = dialog$1; + exports.dialogExports = dialogExports; + + /***/ }), + + /***/ "../../graphiql-react/dist/foldgutter.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/foldgutter.cjs.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var foldgutter$2 = { + exports: {} + }; + var foldcode = { + exports: {} + }; + var hasRequiredFoldcode; + function requireFoldcode() { + if (hasRequiredFoldcode) return foldcode.exports; + hasRequiredFoldcode = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function doFold(cm, pos, options, force) { + if (options && options.call) { + var finder = options; + options = null; + } else { + var finder = getOption(cm, options, "rangeFinder"); + } + if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); + var minSize = getOption(cm, options, "minFoldSize"); + function getRange(allowFolded) { + var range2 = finder(cm, pos); + if (!range2 || range2.to.line - range2.from.line < minSize) return null; + if (force === "fold") return range2; + var marks = cm.findMarksAt(range2.from); + for (var i = 0; i < marks.length; ++i) { + if (marks[i].__isFold) { + if (!allowFolded) return null; + range2.cleared = true; + marks[i].clear(); + } + } + return range2; + } + var range = getRange(true); + if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) { + pos = CodeMirror.Pos(pos.line - 1, 0); + range = getRange(false); + } + if (!range || range.cleared || force === "unfold") return; + var myWidget = makeWidget(cm, options, range); + CodeMirror.on(myWidget, "mousedown", function (e) { + myRange.clear(); + CodeMirror.e_preventDefault(e); + }); + var myRange = cm.markText(range.from, range.to, { + replacedWith: myWidget, + clearOnEnter: getOption(cm, options, "clearOnEnter"), + __isFold: true + }); + myRange.on("clear", function (from, to) { + CodeMirror.signal(cm, "unfold", cm, from, to); + }); + CodeMirror.signal(cm, "fold", cm, range.from, range.to); + } + function makeWidget(cm, options, range) { + var widget = getOption(cm, options, "widget"); + if (typeof widget == "function") { + widget = widget(range.from, range.to); + } + if (typeof widget == "string") { + var text = document.createTextNode(widget); + widget = document.createElement("span"); + widget.appendChild(text); + widget.className = "CodeMirror-foldmarker"; + } else if (widget) { + widget = widget.cloneNode(true); + } + return widget; + } + CodeMirror.newFoldFunction = function (rangeFinder, widget) { + return function (cm, pos) { + doFold(cm, pos, { + rangeFinder, + widget + }); + }; }; - ParserInline.prototype.State = StateInline; - - // markdown-it default options - - var cfg_default = { - options: { - // Enable HTML tags in source - html: false, - // Use '/' to close single tags (
    ) - xhtmlOut: false, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: "language-", - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: "\u201c\u201d\u2018\u2019", - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with ) - xhtmlOut: false, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: "language-", - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: "\u201c\u201d\u2018\u2019", - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with ) - xhtmlOut: true, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: "language-", - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: "\u201c\u201d\u2018\u2019", - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with = 0 - ) { - try { - parsed.hostname = punycode.toASCII(parsed.hostname); - } catch (er) { - /**/ - } + CodeMirror.commands.fold = function (cm) { + cm.foldCode(cm.getCursor(), null, "fold"); + }; + CodeMirror.commands.unfold = function (cm) { + cm.foldCode(cm.getCursor(), { + scanUp: false + }, "unfold"); + }; + CodeMirror.commands.foldAll = function (cm) { + cm.operation(function () { + for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { + scanUp: false + }, "fold"); + }); + }; + CodeMirror.commands.unfoldAll = function (cm) { + cm.operation(function () { + for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { + scanUp: false + }, "unfold"); + }); + }; + CodeMirror.registerHelper("fold", "combine", function () { + var funcs = Array.prototype.slice.call(arguments, 0); + return function (cm, start) { + for (var i = 0; i < funcs.length; ++i) { + var found = funcs[i](cm, start); + if (found) return found; } + }; + }); + CodeMirror.registerHelper("fold", "auto", function (cm, start) { + var helpers = cm.getHelpers(start, "fold"); + for (var i = 0; i < helpers.length; i++) { + var cur = helpers[i](cm, start); + if (cur) return cur; } - return mdurl__namespace.encode(mdurl__namespace.format(parsed)); + }); + var defaultOptions = { + rangeFinder: CodeMirror.fold.auto, + widget: "↔", + minFoldSize: 0, + scanUp: false, + clearOnEnter: true + }; + CodeMirror.defineOption("foldOptions", null); + function getOption(cm, options, name) { + if (options && options[name] !== void 0) return options[name]; + var editorOptions = cm.options.foldOptions; + if (editorOptions && editorOptions[name] !== void 0) return editorOptions[name]; + return defaultOptions[name]; } - function normalizeLinkText(url) { - const parsed = mdurl__namespace.parse(url, true); - if (parsed.hostname) { - // Encode hostnames in urls like: - // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` - // - // We don't encode unknown schemas, because it's likely that we encode - // something we shouldn't (e.g. `skype:name` treated as `skype:host`) - // - if ( - !parsed.protocol || - RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0 - ) { - try { - parsed.hostname = punycode.toUnicode(parsed.hostname); - } catch (er) { - /**/ - } + CodeMirror.defineExtension("foldOption", function (options, name) { + return getOption(this, options, name); + }); + }); + })(); + return foldcode.exports; + } + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), requireFoldcode()); + })(function (CodeMirror) { + CodeMirror.defineOption("foldGutter", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.clearGutter(cm.state.foldGutter.options.gutter); + cm.state.foldGutter = null; + cm.off("gutterClick", onGutterClick); + cm.off("changes", onChange); + cm.off("viewportChange", onViewportChange); + cm.off("fold", onFold); + cm.off("unfold", onFold); + cm.off("swapDoc", onChange); + } + if (val) { + cm.state.foldGutter = new State(parseOptions(val)); + updateInViewport(cm); + cm.on("gutterClick", onGutterClick); + cm.on("changes", onChange); + cm.on("viewportChange", onViewportChange); + cm.on("fold", onFold); + cm.on("unfold", onFold); + cm.on("swapDoc", onChange); + } + }); + var Pos = CodeMirror.Pos; + function State(options) { + this.options = options; + this.from = this.to = 0; + } + function parseOptions(opts) { + if (opts === true) opts = {}; + if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; + if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; + if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; + return opts; + } + function isFolded(cm, line) { + var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); + for (var i = 0; i < marks.length; ++i) { + if (marks[i].__isFold) { + var fromPos = marks[i].find(-1); + if (fromPos && fromPos.line === line) return marks[i]; + } + } + } + function marker(spec) { + if (typeof spec == "string") { + var elt = document.createElement("div"); + elt.className = spec + " CodeMirror-guttermarker-subtle"; + return elt; + } else { + return spec.cloneNode(true); + } + } + function updateFoldInfo(cm, from, to) { + var opts = cm.state.foldGutter.options, + cur = from - 1; + var minSize = cm.foldOption(opts, "minFoldSize"); + var func = cm.foldOption(opts, "rangeFinder"); + var clsFolded = typeof opts.indicatorFolded == "string" && classTest(opts.indicatorFolded); + var clsOpen = typeof opts.indicatorOpen == "string" && classTest(opts.indicatorOpen); + cm.eachLine(from, to, function (line) { + ++cur; + var mark = null; + var old = line.gutterMarkers; + if (old) old = old[opts.gutter]; + if (isFolded(cm, cur)) { + if (clsFolded && old && clsFolded.test(old.className)) return; + mark = marker(opts.indicatorFolded); + } else { + var pos = Pos(cur, 0); + var range = func && func(cm, pos); + if (range && range.to.line - range.from.line >= minSize) { + if (clsOpen && old && clsOpen.test(old.className)) return; + mark = marker(opts.indicatorOpen); } } - - // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 - return mdurl__namespace.decode( - mdurl__namespace.format(parsed), - mdurl__namespace.decode.defaultChars + "%" - ); + if (!mark && !old) return; + cm.setGutterMarker(line, opts.gutter, mark); + }); + } + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); + } + function updateInViewport(cm) { + var vp = cm.getViewport(), + state = cm.state.foldGutter; + if (!state) return; + cm.operation(function () { + updateFoldInfo(cm, vp.from, vp.to); + }); + state.from = vp.from; + state.to = vp.to; + } + function onGutterClick(cm, line, gutter) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + if (gutter != opts.gutter) return; + var folded = isFolded(cm, line); + if (folded) folded.clear();else cm.foldCode(Pos(line, 0), opts); + } + function onChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + state.from = state.to = 0; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function () { + updateInViewport(cm); + }, opts.foldOnChangeTimeSpan || 600); + } + function onViewportChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function () { + var vp = cm.getViewport(); + if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { + updateInViewport(cm); + } else { + cm.operation(function () { + if (vp.from < state.from) { + updateFoldInfo(cm, vp.from, state.from); + state.from = vp.from; + } + if (vp.to > state.to) { + updateFoldInfo(cm, state.to, vp.to); + state.to = vp.to; + } + }); + } + }, opts.updateViewportTimeSpan || 400); + } + function onFold(cm, from) { + var state = cm.state.foldGutter; + if (!state) return; + var line = from.line; + if (line >= state.from && line < state.to) updateFoldInfo(cm, line, line + 1); + } + }); + })(); + var foldgutterExports = foldgutter$2.exports; + const foldgutter = /* @__PURE__ */codemirror.getDefaultExportFromCjs(foldgutterExports); + const foldgutter$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: foldgutter + }, [foldgutterExports]); + exports.foldgutter = foldgutter$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/forEachState.cjs.js": + /*!*****************************************************!*\ + !*** ../../graphiql-react/dist/forEachState.cjs.js ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + function forEachState(stack, fn) { + const reverseStateStack = []; + let state = stack; + while (state === null || state === void 0 ? void 0 : state.kind) { + reverseStateStack.push(state); + state = state.prevState; + } + for (let i = reverseStateStack.length - 1; i >= 0; i--) { + fn(reverseStateStack[i]); + } + } + exports.forEachState = forEachState; + + /***/ }), + + /***/ "../../graphiql-react/dist/hint.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/hint.cjs.js ***! + \*********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + __webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js"); + const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); + codemirror.CodeMirror.registerHelper("hint", "graphql", (editor, options) => { + const { + schema, + externalFragments, + autocompleteOptions + } = options; + if (!schema) { + return; + } + const cur = editor.getCursor(); + const token = editor.getTokenAt(cur); + const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; + const position = new graphqlLanguageService.Position(cur.line, tokenStart); + const rawResults = graphqlLanguageService.getAutocompleteSuggestions(schema, editor.getValue(), position, token, externalFragments, autocompleteOptions); + const results = { + list: rawResults.map(item => { + var _a; + return { + text: (_a = item === null || item === void 0 ? void 0 : item.rawInsert) !== null && _a !== void 0 ? _a : item.label, + type: item.type, + description: item.documentation, + isDeprecated: item.isDeprecated, + deprecationReason: item.deprecationReason + }; + }), + from: { + line: cur.line, + ch: tokenStart + }, + to: { + line: cur.line, + ch: token.end + } + }; + if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { + results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); + results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); + codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); + } + return results; + }); + + /***/ }), + + /***/ "../../graphiql-react/dist/hint.cjs2.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/hint.cjs2.js ***! + \**********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); + function hintList(cursor, token, list) { + const hints = filterAndSortList(list, normalizeText(token.string)); + if (!hints) { + return; + } + const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; + return { + list: hints, + from: { + line: cursor.line, + ch: tokenStart + }, + to: { + line: cursor.line, + ch: token.end + } + }; + } + function filterAndSortList(list, text) { + if (!text) { + return filterNonEmpty(list, entry => !entry.isDeprecated); + } + const byProximity = list.map(entry => ({ + proximity: getProximity(normalizeText(entry.text), text), + entry + })); + const conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated); + const sortedMatches = conciseMatches.sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.text.length - b.entry.text.length); + return sortedMatches.map(pair => pair.entry); + } + function filterNonEmpty(array, predicate) { + const filtered = array.filter(predicate); + return filtered.length === 0 ? array : filtered; + } + function normalizeText(text) { + return text.toLowerCase().replaceAll(/\W/g, ""); + } + function getProximity(suggestion, text) { + let proximity = lexicalDistance(text, suggestion); + if (suggestion.length > text.length) { + proximity -= suggestion.length - text.length - 1; + proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + } + return proximity; + } + function lexicalDistance(a, b) { + let i; + let j; + const d = []; + const aLength = a.length; + const bLength = b.length; + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); } - - /** - * class MarkdownIt - * - * Main parser/renderer class. - * - * ##### Usage - * - * ```javascript - * // node.js, "classic" way: - * var MarkdownIt = require('markdown-it'), - * md = new MarkdownIt(); - * var result = md.render('# markdown-it rulezz!'); - * - * // node.js, the same, but with sugar: - * var md = require('markdown-it')(); - * var result = md.render('# markdown-it rulezz!'); - * - * // browser without AMD, added to "window" on script load - * // Note, there are no dash. - * var md = window.markdownit(); - * var result = md.render('# markdown-it rulezz!'); - * ``` - * - * Single line rendering, without paragraph wrap: - * - * ```javascript - * var md = require('markdown-it')(); - * var result = md.renderInline('__markdown-it__ rulezz!'); - * ``` - **/ - - /** - * new MarkdownIt([presetName, options]) - * - presetName (String): optional, `commonmark` / `zero` - * - options (Object) - * - * Creates parser instanse with given config. Can be called without `new`. - * - * ##### presetName - * - * MarkdownIt provides named presets as a convenience to quickly - * enable/disable active syntax rules and options for common use cases. - * - * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.mjs) - - * configures parser to strict [CommonMark](http://commonmark.org/) mode. - * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.mjs) - - * similar to GFM, used when no preset name given. Enables all available rules, - * but still without html, typographer & autolinker. - * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.mjs) - - * all rules disabled. Useful to quickly setup your config via `.enable()`. - * For example, when you need only `bold` and `italic` markup and nothing else. - * - * ##### options: - * - * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! - * That's not safe! You may need external sanitizer to protect output from XSS. - * It's better to extend features via plugins, instead of enabling HTML. - * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags - * (`
    `). This is needed only for full CommonMark compatibility. In real - * world you will need HTML output. - * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
    `. - * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. - * Can be useful for external highlighters. - * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. - * - __typographer__ - `false`. Set `true` to enable [some language-neutral - * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs) + - * quotes beautification (smartquotes). - * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement - * pairs, when typographer enabled and smartquotes on. For example, you can - * use `'«»„“'` for Russian, `'„“‚‘'` for German, and - * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). - * - __highlight__ - `null`. Highlighter function for fenced code blocks. - * Highlighter `function (str, lang)` should return escaped HTML. It can also - * return empty string if the source was not changed and should be escaped - * externaly. If result starts with ` or ``): - * - * ```javascript - * var hljs = require('highlight.js') // https://highlightjs.org/ - * - * // Actual default values - * var md = require('markdown-it')({ - * highlight: function (str, lang) { - * if (lang && hljs.getLanguage(lang)) { - * try { - * return '
    ' +
    -         *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
    -         *                '
    '; - * } catch (__) {} - * } - * - * return '
    ' + md.utils.escapeHtml(str) + '
    '; - * } - * }); - * ``` - * - **/ - function MarkdownIt(presetName, options) { - if (!(this instanceof MarkdownIt)) { - return new MarkdownIt(presetName, options); + } + } + return d[aLength][bLength]; + } + codemirror.CodeMirror.registerHelper("hint", "graphql-variables", (editor, options) => { + const cur = editor.getCursor(); + const token = editor.getTokenAt(cur); + const results = getVariablesHint(cur, token, options); + if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { + results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); + results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); + codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); + } + return results; + }); + function getVariablesHint(cur, token, options) { + const state = token.state.kind === "Invalid" ? token.state.prevState : token.state; + const { + kind, + step + } = state; + if (kind === "Document" && step === 0) { + return hintList(cur, token, [{ + text: "{" + }]); + } + const { + variableToType + } = options; + if (!variableToType) { + return; + } + const typeInfo = getTypeInfo(variableToType, token.state); + if (kind === "Document" || kind === "Variable" && step === 0) { + const variableNames = Object.keys(variableToType); + return hintList(cur, token, variableNames.map(name => ({ + text: `"${name}": `, + type: variableToType[name] + }))); + } + if ((kind === "ObjectValue" || kind === "ObjectField" && step === 0) && typeInfo.fields) { + const inputFields = Object.keys(typeInfo.fields).map(fieldName => typeInfo.fields[fieldName]); + return hintList(cur, token, inputFields.map(field => ({ + text: `"${field.name}": `, + type: field.type, + description: field.description + }))); + } + if (kind === "StringValue" || kind === "NumberValue" || kind === "BooleanValue" || kind === "NullValue" || kind === "ListValue" && step === 1 || kind === "ObjectField" && step === 2 || kind === "Variable" && step === 2) { + const namedInputType = typeInfo.type ? graphql.getNamedType(typeInfo.type) : void 0; + if (namedInputType instanceof graphql.GraphQLInputObjectType) { + return hintList(cur, token, [{ + text: "{" + }]); + } + if (namedInputType instanceof graphql.GraphQLEnumType) { + const values = namedInputType.getValues(); + return hintList(cur, token, values.map(value => ({ + text: `"${value.name}"`, + type: namedInputType, + description: value.description + }))); + } + if (namedInputType === graphql.GraphQLBoolean) { + return hintList(cur, token, [{ + text: "true", + type: graphql.GraphQLBoolean, + description: "Not false." + }, { + text: "false", + type: graphql.GraphQLBoolean, + description: "Not true." + }]); + } + } + } + function getTypeInfo(variableToType, tokenState) { + const info = { + type: null, + fields: null + }; + forEachState.forEachState(tokenState, state => { + switch (state.kind) { + case "Variable": + { + info.type = variableToType[state.name]; + break; } - if (!options) { - if (!isString(presetName)) { - options = presetName || {}; - presetName = "default"; - } + case "ListValue": + { + const nullableType = info.type ? graphql.getNullableType(info.type) : void 0; + info.type = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; + break; } - - /** - * MarkdownIt#inline -> ParserInline - * - * Instance of [[ParserInline]]. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.inline = new ParserInline(); - - /** - * MarkdownIt#block -> ParserBlock - * - * Instance of [[ParserBlock]]. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.block = new ParserBlock(); - - /** - * MarkdownIt#core -> Core - * - * Instance of [[Core]] chain executor. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.core = new Core(); - - /** - * MarkdownIt#renderer -> Renderer - * - * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering - * rules for new token types, generated by plugins. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * function myToken(tokens, idx, options, env, self) { - * //... - * return result; - * }; - * - * md.renderer.rules['my_token'] = myToken - * ``` - * - * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs). - **/ - this.renderer = new Renderer(); - - /** - * MarkdownIt#linkify -> LinkifyIt - * - * [linkify-it](https://github.com/markdown-it/linkify-it) instance. - * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs) - * rule. - **/ - this.linkify = new LinkifyIt(); - - /** - * MarkdownIt#validateLink(url) -> Boolean - * - * Link validation function. CommonMark allows too much in links. By default - * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas - * except some embedded image types. - * - * You can change this behaviour: - * - * ```javascript - * var md = require('markdown-it')(); - * // enable everything - * md.validateLink = function () { return true; } - * ``` - **/ - this.validateLink = validateLink; - - /** - * MarkdownIt#normalizeLink(url) -> String - * - * Function used to encode link url to a machine-readable format, - * which includes url-encoding, punycode, etc. - **/ - this.normalizeLink = normalizeLink; - - /** - * MarkdownIt#normalizeLinkText(url) -> String - * - * Function used to decode link url to a human-readable format` - **/ - this.normalizeLinkText = normalizeLinkText; - - // Expose utils & helpers for easy acces from plugins - - /** - * MarkdownIt#utils -> utils - * - * Assorted utility functions, useful to write plugins. See details - * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs). - **/ - this.utils = utils; - - /** - * MarkdownIt#helpers -> helpers - * - * Link components parser functions, useful to write plugins. See details - * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). - **/ - this.helpers = assign({}, helpers); - this.options = {}; - this.configure(presetName); - if (options) { - this.set(options); + case "ObjectValue": + { + const objectType = info.type ? graphql.getNamedType(info.type) : void 0; + info.fields = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; + break; + } + case "ObjectField": + { + const objectField = state.name && info.fields ? info.fields[state.name] : null; + info.type = objectField === null || objectField === void 0 ? void 0 : objectField.type; + break; } + } + }); + return info; + } + + /***/ }), + + /***/ "../../graphiql-react/dist/index.js": + /*!******************************************!*\ + !*** ../../graphiql-react/dist/index.js ***! + \******************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, Symbol.toStringTag, { + value: "Module" + }); + const jsxRuntime = __webpack_require__(/*! react/jsx-runtime */ "../../../node_modules/react/jsx-runtime.js"); + const React = __webpack_require__(/*! react */ "react"); + const clsx = __webpack_require__(/*! clsx */ "../../../node_modules/clsx/dist/clsx.m.js"); + const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const toolkit = __webpack_require__(/*! @graphiql/toolkit */ "../../graphiql-toolkit/esm/index.js"); + const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); + const setValue = __webpack_require__(/*! set-value */ "../../../node_modules/set-value/index.js"); + const copyToClipboard = __webpack_require__(/*! copy-to-clipboard */ "../../../node_modules/copy-to-clipboard/index.js"); + const D = __webpack_require__(/*! @radix-ui/react-dialog */ "../../../node_modules/@radix-ui/react-dialog/dist/index.js"); + const reactVisuallyHidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); + const reactDropdownMenu = __webpack_require__(/*! @radix-ui/react-dropdown-menu */ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js"); + const MarkdownIt = __webpack_require__(/*! markdown-it */ "../node_modules/markdown-it/dist/index.cjs.js"); + const framerMotion = __webpack_require__(/*! framer-motion */ "../../../node_modules/framer-motion/dist/cjs/index.js"); + const T = __webpack_require__(/*! @radix-ui/react-tooltip */ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js"); + const react = __webpack_require__(/*! @headlessui/react */ "../../../node_modules/@headlessui/react/dist/index.cjs"); + const ReactDOM = __webpack_require__(/*! react-dom */ "react-dom"); + function _interopNamespaceDefault(e) { + const n = Object.create(null, { + [Symbol.toStringTag]: { + value: "Module" + } + }); + if (e) { + for (const k in e) { + if (k !== "default") { + const d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - - /** chainable - * MarkdownIt.set(options) - * - * Set parser options (in the same format as in constructor). Probably, you - * will never need it, but you can change options after constructor call. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')() - * .set({ html: true, breaks: true }) - * .set({ typographer, true }); - * ``` - * - * __Note:__ To achieve the best possible performance, don't modify a - * `markdown-it` instance options on the fly. If you need multiple configurations - * it's best to create multiple instances and initialize each with separate - * config. - **/ - MarkdownIt.prototype.set = function (options) { - assign(this.options, options); - return this; - }; - - /** chainable, internal - * MarkdownIt.configure(presets) - * - * Batch load of all options and compenent settings. This is internal method, - * and you probably will not need it. But if you will - see available presets - * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) - * - * We strongly recommend to use presets instead of direct config loads. That - * will give better compatibility with next versions. - **/ - MarkdownIt.prototype.configure = function (presets) { - const self = this; - if (isString(presets)) { - const presetName = presets; - presets = config[presetName]; - if (!presets) { - throw new Error( - 'Wrong `markdown-it` preset "' + presetName + '", check name' - ); + } + } + n.default = e; + return Object.freeze(n); + } + const React__namespace = /* @__PURE__ */_interopNamespaceDefault(React); + const D__namespace = /* @__PURE__ */_interopNamespaceDefault(D); + const T__namespace = /* @__PURE__ */_interopNamespaceDefault(T); + function createNullableContext(name) { + const context = React.createContext(null); + context.displayName = name; + return context; + } + function createContextHook(context) { + function useGivenContext(options) { + var _a; + const value = React.useContext(context); + if (value === null && (options == null ? void 0 : options.nonNull)) { + throw new Error(`Tried to use \`${((_a = options.caller) == null ? void 0 : _a.name) || useGivenContext.caller.name}\` without the necessary context. Make sure to render the \`${context.displayName}Provider\` component higher up the tree.`); + } + return value; + } + Object.defineProperty(useGivenContext, "name", { + value: `use${context.displayName}` + }); + return useGivenContext; + } + const StorageContext = createNullableContext("StorageContext"); + function StorageContextProvider(props) { + const isInitialRender = React.useRef(true); + const [storage, setStorage] = React.useState(new toolkit.StorageAPI(props.storage)); + React.useEffect(() => { + if (isInitialRender.current) { + isInitialRender.current = false; + } else { + setStorage(new toolkit.StorageAPI(props.storage)); + } + }, [props.storage]); + return /* @__PURE__ */jsxRuntime.jsx(StorageContext.Provider, { + value: storage, + children: props.children + }); + } + const useStorageContext = createContextHook(StorageContext); + const SvgArgument = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("rect", { + x: 6, + y: 6, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" + })); + const SvgChevronDown = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 9", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1 1L7 7L13 1", + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgChevronLeft = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 7 10", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M6 1.04819L2 5.04819L6 9.04819", + stroke: "currentColor", + strokeWidth: 1.75 + })); + const SvgChevronUp = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 9", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M13 8L7 2L1 8", + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgClose = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + stroke: "currentColor", + strokeWidth: 3, + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1 1L12.9998 12.9997" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M13 1L1.00079 13.0003" + })); + const SvgCopy = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "-2 -2 22 22", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.25 14.2105V15.235C11.25 16.3479 10.3479 17.25 9.23501 17.25H2.76499C1.65214 17.25 0.75 16.3479 0.75 15.235L0.75 8.76499C0.75 7.65214 1.65214 6.75 2.76499 6.75L3.78947 6.75", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("rect", { + x: 6.75, + y: 0.75, + width: 10.5, + height: 10.5, + rx: 2.2069, + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgDeprecatedArgument = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M5 9L9 5", + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M5 5L9 9", + stroke: "currentColor", + strokeWidth: 1.2 + })); + const SvgDeprecatedEnumValue = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 8L8 4", + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 4L8 8", + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", + fill: "currentColor" + })); + const SvgDeprecatedField = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 10.8, + height: 10.8, + rx: 3.4, + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 8L8 4", + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 4L8 8", + stroke: "currentColor", + strokeWidth: 1.2 + })); + const SvgDirective = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0.5 12 12", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 7, + y: 5.5, + width: 2, + height: 2, + rx: 1, + transform: "rotate(90 7 5.5)", + fill: "currentColor" + }), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M10.8 9L10.8 9.5C10.8 10.4941 9.99411 11.3 9 11.3L3 11.3C2.00589 11.3 1.2 10.4941 1.2 9.5L1.2 9L-3.71547e-07 9L-3.93402e-07 9.5C-4.65826e-07 11.1569 1.34314 12.5 3 12.5L9 12.5C10.6569 12.5 12 11.1569 12 9.5L12 9L10.8 9ZM10.8 4L12 4L12 3.5C12 1.84315 10.6569 0.5 9 0.5L3 0.5C1.34315 0.5 -5.87117e-08 1.84315 -1.31135e-07 3.5L-1.5299e-07 4L1.2 4L1.2 3.5C1.2 2.50589 2.00589 1.7 3 1.7L9 1.7C9.99411 1.7 10.8 2.50589 10.8 3.5L10.8 4Z", + fill: "currentColor" + })); + const SvgDocsFilled = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 20 24", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H17.25C17.8023 0.75 18.25 1.19772 18.25 1.75V5.25", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H18.25C18.8023 5.25 19.25 5.69771 19.25 6.25V22.25C19.25 22.8023 18.8023 23.25 18.25 23.25H3C1.75736 23.25 0.75 22.2426 0.75 21V3Z", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M3 5.25C1.75736 5.25 0.75 4.24264 0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H3ZM13 11L6 11V12.5L13 12.5V11Z", + fill: "currentColor" + })); + const SvgDocs = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 20 24", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H17.25M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H16.25C16.8023 0.75 17.25 1.19772 17.25 1.75V5.25M0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H17.25", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("line", { + x1: 13, + y1: 11.75, + x2: 6, + y2: 11.75, + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgEnumValue = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 5, + y: 5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" + }), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", + fill: "currentColor" + })); + const SvgField = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 1.1, + width: 10.8, + height: 10.8, + rx: 2.4, + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("rect", { + x: 5, + y: 5.5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" + })); + const SvgHistory = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 24 20", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.59375 9.52344L4.87259 12.9944L8.07872 9.41249", + stroke: "currentColor", + strokeWidth: 1.5, + strokeLinecap: "square" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M13.75 5.25V10.75H18.75", + stroke: "currentColor", + strokeWidth: 1.5, + strokeLinecap: "square" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4.95427 11.9332C4.55457 10.0629 4.74441 8.11477 5.49765 6.35686C6.25089 4.59894 7.5305 3.11772 9.16034 2.11709C10.7902 1.11647 12.6901 0.645626 14.5986 0.769388C16.5071 0.893151 18.3303 1.60543 19.8172 2.80818C21.3042 4.01093 22.3818 5.64501 22.9017 7.48548C23.4216 9.32595 23.3582 11.2823 22.7203 13.0853C22.0824 14.8883 20.9013 16.4492 19.3396 17.5532C17.778 18.6572 15.9125 19.25 14 19.25", + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgImplements = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { + cx: 6, + cy: 6, + r: 5.4, + stroke: "currentColor", + strokeWidth: 1.2, + strokeDasharray: "4.241025 4.241025", + transform: "rotate(22.5)", + "transform-origin": "center" + }), /* @__PURE__ */React__namespace.createElement("circle", { + cx: 6, + cy: 6, + r: 1, + fill: "currentColor" + })); + const SvgKeyboardShortcut = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 19 18", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.5 14.5653C1.5 15.211 1.75652 15.8303 2.21314 16.2869C2.66975 16.7435 3.28905 17 3.9348 17C4.58054 17 5.19984 16.7435 5.65646 16.2869C6.11307 15.8303 6.36959 15.211 6.36959 14.5653V12.1305H3.9348C3.28905 12.1305 2.66975 12.387 2.21314 12.8437C1.75652 13.3003 1.5 13.9195 1.5 14.5653Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M3.9348 1.00063C3.28905 1.00063 2.66975 1.25715 2.21314 1.71375C1.75652 2.17035 1.5 2.78964 1.5 3.43537C1.5 4.0811 1.75652 4.70038 2.21314 5.15698C2.66975 5.61358 3.28905 5.8701 3.9348 5.8701H6.36959V3.43537C6.36959 2.78964 6.11307 2.17035 5.65646 1.71375C5.19984 1.25715 4.58054 1.00063 3.9348 1.00063Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M15.0652 12.1305H12.6304V14.5653C12.6304 15.0468 12.7732 15.5175 13.0407 15.9179C13.3083 16.3183 13.6885 16.6304 14.1334 16.8147C14.5783 16.9989 15.0679 17.0472 15.5402 16.9532C16.0125 16.8593 16.4464 16.6274 16.7869 16.2869C17.1274 15.9464 17.3593 15.5126 17.4532 15.0403C17.5472 14.568 17.4989 14.0784 17.3147 13.6335C17.1304 13.1886 16.8183 12.8084 16.4179 12.5409C16.0175 12.2733 15.5468 12.1305 15.0652 12.1305Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M12.6318 5.86775H6.36955V12.1285H12.6318V5.86775Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M17.5 3.43473C17.5 2.789 17.2435 2.16972 16.7869 1.71312C16.3303 1.25652 15.711 1 15.0652 1C14.4195 1 13.8002 1.25652 13.3435 1.71312C12.8869 2.16972 12.6304 2.789 12.6304 3.43473V5.86946H15.0652C15.711 5.86946 16.3303 5.61295 16.7869 5.15635C17.2435 4.69975 17.5 4.08046 17.5 3.43473Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" + })); + const SvgMagnifyingGlass = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { + cx: 5, + cy: 5, + r: 4.35, + stroke: "currentColor", + strokeWidth: 1.3 + }), /* @__PURE__ */React__namespace.createElement("line", { + x1: 8.45962, + y1: 8.54038, + x2: 11.7525, + y2: 11.8333, + stroke: "currentColor", + strokeWidth: 1.3 + })); + const SvgMerge = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "-2 -2 22 22", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M17.2492 6V2.9569C17.2492 1.73806 16.2611 0.75 15.0423 0.75L2.9569 0.75C1.73806 0.75 0.75 1.73806 0.75 2.9569L0.75 6", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.749873 12V15.0431C0.749873 16.2619 1.73794 17.25 2.95677 17.25H15.0421C16.261 17.25 17.249 16.2619 17.249 15.0431V12", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M6 4.5L9 7.5L12 4.5", + stroke: "currentColor", + strokeWidth: 1.5 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M12 13.5L9 10.5L6 13.5", + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgPen = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 13.25L0.0554307 12.967C-0.0593528 13.2488 0.00743073 13.5719 0.224488 13.7851C0.441545 13.9983 0.765869 14.0592 1.04549 13.9393L0.75 13.25ZM12.8214 1.83253L12.2911 2.36286L12.2911 2.36286L12.8214 1.83253ZM12.8214 3.90194L13.3517 4.43227L12.8214 3.90194ZM10.0981 1.17859L9.56773 0.648259L10.0981 1.17859ZM12.1675 1.17859L12.6978 0.648258L12.6978 0.648257L12.1675 1.17859ZM2.58049 8.75697L3.27506 9.03994L2.58049 8.75697ZM2.70066 8.57599L3.23099 9.10632L2.70066 8.57599ZM5.2479 11.4195L4.95355 10.7297L5.2479 11.4195ZM5.42036 11.303L4.89003 10.7727L5.42036 11.303ZM4.95355 10.7297C4.08882 11.0987 3.41842 11.362 2.73535 11.6308C2.05146 11.9 1.35588 12.1743 0.454511 12.5607L1.04549 13.9393C1.92476 13.5624 2.60256 13.2951 3.28469 13.0266C3.96762 12.7578 4.65585 12.4876 5.54225 12.1093L4.95355 10.7297ZM1.44457 13.533L3.27506 9.03994L1.88592 8.474L0.0554307 12.967L1.44457 13.533ZM3.23099 9.10632L10.6284 1.70892L9.56773 0.648259L2.17033 8.04566L3.23099 9.10632ZM11.6371 1.70892L12.2911 2.36286L13.3517 1.3022L12.6978 0.648258L11.6371 1.70892ZM12.2911 3.37161L4.89003 10.7727L5.95069 11.8333L13.3517 4.43227L12.2911 3.37161ZM12.2911 2.36286C12.5696 2.64142 12.5696 3.09305 12.2911 3.37161L13.3517 4.43227C14.2161 3.56792 14.2161 2.16654 13.3517 1.3022L12.2911 2.36286ZM10.6284 1.70892C10.9069 1.43036 11.3586 1.43036 11.6371 1.70892L12.6978 0.648257C11.8335 -0.216088 10.4321 -0.216084 9.56773 0.648259L10.6284 1.70892ZM3.27506 9.03994C3.26494 9.06479 3.24996 9.08735 3.23099 9.10632L2.17033 8.04566C2.04793 8.16806 1.95123 8.31369 1.88592 8.474L3.27506 9.03994ZM5.54225 12.1093C5.69431 12.0444 5.83339 11.9506 5.95069 11.8333L4.89003 10.7727C4.90863 10.7541 4.92988 10.7398 4.95355 10.7297L5.54225 12.1093Z", + fill: "currentColor" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.5 4.5L9.5 2.5", + stroke: "currentColor", + strokeWidth: 1.4026, + strokeLinecap: "round", + strokeLinejoin: "round" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M5.5 10.5L3.5 8.5", + stroke: "currentColor", + strokeWidth: 1.4026, + strokeLinecap: "round", + strokeLinejoin: "round" + })); + const SvgPlay = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 16 18", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.32226e-07 1.6609C7.22332e-08 0.907329 0.801887 0.424528 1.46789 0.777117L15.3306 8.11621C16.0401 8.49182 16.0401 9.50818 15.3306 9.88379L1.46789 17.2229C0.801886 17.5755 1.36076e-06 17.0927 1.30077e-06 16.3391L1.32226e-07 1.6609Z", + fill: "currentColor" + })); + const SvgPlus = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 10 16", + fill: "currentColor", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M4.25 9.25V13.5H5.75V9.25L10 9.25V7.75L5.75 7.75V3.5H4.25V7.75L0 7.75V9.25L4.25 9.25Z" + })); + const SvgPrettify = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + width: 25, + height: 25, + viewBox: "0 0 25 25", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M10.2852 24.0745L13.7139 18.0742", + stroke: "currentColor", + strokeWidth: 1.5625 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M14.5742 24.0749L17.1457 19.7891", + stroke: "currentColor", + strokeWidth: 1.5625 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M19.4868 24.0735L20.7229 21.7523C21.3259 20.6143 21.5457 19.3122 21.3496 18.0394C21.1535 16.7666 20.5519 15.591 19.6342 14.6874L23.7984 6.87853C24.0123 6.47728 24.0581 6.00748 23.9256 5.57249C23.7932 5.1375 23.4933 4.77294 23.0921 4.55901C22.6908 4.34509 22.221 4.29932 21.7861 4.43178C21.3511 4.56424 20.9865 4.86408 20.7726 5.26533L16.6084 13.0742C15.3474 12.8142 14.0362 12.9683 12.8699 13.5135C11.7035 14.0586 10.7443 14.9658 10.135 16.1L6 24.0735", + stroke: "currentColor", + strokeWidth: 1.5625 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 15L5 13L7 12L5 11L4 9L3 11L1 12L3 13L4 15Z", + stroke: "currentColor", + strokeWidth: 1.5625, + strokeLinejoin: "round" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.5 8L12.6662 5.6662L15 4.5L12.6662 3.3338L11.5 1L10.3338 3.3338L8 4.5L10.3338 5.6662L11.5 8Z", + stroke: "currentColor", + strokeWidth: 1.5625, + strokeLinejoin: "round" + })); + const SvgReload = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 16 16", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M4.75 9.25H1.25V12.75", + stroke: "currentColor", + strokeWidth: 1, + strokeLinecap: "square" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.25 6.75H14.75V3.25", + stroke: "currentColor", + strokeWidth: 1, + strokeLinecap: "square" + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M14.1036 6.65539C13.8 5.27698 13.0387 4.04193 11.9437 3.15131C10.8487 2.26069 9.48447 1.76694 8.0731 1.75043C6.66173 1.73392 5.28633 2.19563 4.17079 3.0604C3.05526 3.92516 2.26529 5.14206 1.92947 6.513", + stroke: "currentColor", + strokeWidth: 1 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.89635 9.34461C2.20001 10.723 2.96131 11.9581 4.05631 12.8487C5.15131 13.7393 6.51553 14.2331 7.9269 14.2496C9.33827 14.2661 10.7137 13.8044 11.8292 12.9396C12.9447 12.0748 13.7347 10.8579 14.0705 9.487", + stroke: "currentColor", + strokeWidth: 1 + })); + const SvgRootType = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 11.8, + height: 11.8, + rx: 5.9, + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4.25 7.5C4.25 6 5.75 5 6.5 6.5C7.25 8 8.75 7 8.75 5.5", + stroke: "currentColor", + strokeWidth: 1.2 + })); + const SvgSettings = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 21 20", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M9.29186 1.92702C9.06924 1.82745 8.87014 1.68202 8.70757 1.50024L7.86631 0.574931C7.62496 0.309957 7.30773 0.12592 6.95791 0.0479385C6.60809 -0.0300431 6.24274 0.00182978 5.91171 0.139208C5.58068 0.276585 5.3001 0.512774 5.10828 0.815537C4.91645 1.1183 4.82272 1.47288 4.83989 1.83089L4.90388 3.08019C4.91612 3.32348 4.87721 3.56662 4.78968 3.79394C4.70215 4.02126 4.56794 4.2277 4.39571 4.39994C4.22347 4.57219 4.01704 4.7064 3.78974 4.79394C3.56243 4.88147 3.3193 4.92038 3.07603 4.90814L1.8308 4.84414C1.47162 4.82563 1.11553 4.91881 0.811445 5.11086C0.507359 5.30292 0.270203 5.58443 0.132561 5.91671C-0.00508149 6.249 -0.0364554 6.61576 0.0427496 6.9666C0.121955 7.31744 0.307852 7.63514 0.5749 7.87606L1.50016 8.71204C1.68193 8.87461 1.82735 9.07373 1.92692 9.29636C2.02648 9.51898 2.07794 9.76012 2.07794 10.004C2.07794 10.2479 2.02648 10.489 1.92692 10.7116C1.82735 10.9343 1.68193 11.1334 1.50016 11.296L0.5749 12.1319C0.309856 12.3729 0.125575 12.6898 0.0471809 13.0393C-0.0312128 13.3888 9.64098e-05 13.754 0.13684 14.0851C0.273583 14.4162 0.509106 14.6971 0.811296 14.8894C1.11349 15.0817 1.46764 15.1762 1.82546 15.1599L3.0707 15.0959C3.31397 15.0836 3.5571 15.1225 3.7844 15.2101C4.01171 15.2976 4.21814 15.4318 4.39037 15.6041C4.56261 15.7763 4.69682 15.9827 4.78435 16.2101C4.87188 16.4374 4.91078 16.6805 4.89855 16.9238L4.83455 18.1691C4.81605 18.5283 4.90921 18.8844 5.10126 19.1885C5.2933 19.4926 5.5748 19.7298 5.90707 19.8674C6.23934 20.0051 6.60608 20.0365 6.9569 19.9572C7.30772 19.878 7.6254 19.6921 7.86631 19.4251L8.7129 18.4998C8.87547 18.318 9.07458 18.1725 9.29719 18.073C9.51981 17.9734 9.76093 17.9219 10.0048 17.9219C10.2487 17.9219 10.4898 17.9734 10.7124 18.073C10.935 18.1725 11.1341 18.318 11.2967 18.4998L12.1326 19.4251C12.3735 19.6921 12.6912 19.878 13.042 19.9572C13.3929 20.0365 13.7596 20.0051 14.0919 19.8674C14.4241 19.7298 14.7056 19.4926 14.8977 19.1885C15.0897 18.8844 15.1829 18.5283 15.1644 18.1691L15.1004 16.9238C15.0882 16.6805 15.1271 16.4374 15.2146 16.2101C15.3021 15.9827 15.4363 15.7763 15.6086 15.6041C15.7808 15.4318 15.9872 15.2976 16.2145 15.2101C16.4418 15.1225 16.685 15.0836 16.9282 15.0959L18.1735 15.1599C18.5326 15.1784 18.8887 15.0852 19.1928 14.8931C19.4969 14.7011 19.7341 14.4196 19.8717 14.0873C20.0093 13.755 20.0407 13.3882 19.9615 13.0374C19.8823 12.6866 19.6964 12.3689 19.4294 12.1279L18.5041 11.292C18.3223 11.1294 18.1769 10.9303 18.0774 10.7076C17.9778 10.485 17.9263 10.2439 17.9263 10C17.9263 9.75612 17.9778 9.51499 18.0774 9.29236C18.1769 9.06973 18.3223 8.87062 18.5041 8.70804L19.4294 7.87206C19.6964 7.63114 19.8823 7.31344 19.9615 6.9626C20.0407 6.61176 20.0093 6.245 19.8717 5.91271C19.7341 5.58043 19.4969 5.29892 19.1928 5.10686C18.8887 4.91481 18.5326 4.82163 18.1735 4.84014L16.9282 4.90414C16.685 4.91638 16.4418 4.87747 16.2145 4.78994C15.9872 4.7024 15.7808 4.56818 15.6086 4.39594C15.4363 4.2237 15.3021 4.01726 15.2146 3.78994C15.1271 3.56262 15.0882 3.31948 15.1004 3.07619L15.1644 1.83089C15.1829 1.4717 15.0897 1.11559 14.8977 0.811487C14.7056 0.507385 14.4241 0.270217 14.0919 0.132568C13.7596 -0.00508182 13.3929 -0.0364573 13.042 0.0427519C12.6912 0.121961 12.3735 0.307869 12.1326 0.574931L11.2914 1.50024C11.1288 1.68202 10.9297 1.82745 10.7071 1.92702C10.4845 2.02659 10.2433 2.07805 9.99947 2.07805C9.7556 2.07805 9.51448 2.02659 9.29186 1.92702ZM14.3745 10C14.3745 12.4162 12.4159 14.375 9.99977 14.375C7.58365 14.375 5.625 12.4162 5.625 10C5.625 7.58375 7.58365 5.625 9.99977 5.625C12.4159 5.625 14.3745 7.58375 14.3745 10Z", + fill: "currentColor" + })); + const SvgStarFilled = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", + fill: "currentColor", + stroke: "currentColor" + })); + const SvgStar = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", + stroke: "currentColor", + strokeWidth: 1.5 + })); + const SvgStop = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 16 16", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + width: 16, + height: 16, + rx: 2, + fill: "currentColor" + })); + const SvgTrash = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + width: "1em", + height: "5em", + xmlns: "http://www.w3.org/2000/svg", + fillRule: "evenodd", + "aria-hidden": "true", + viewBox: "0 0 23 23", + style: { + height: "1.5em" + }, + clipRule: "evenodd", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M19 24h-14c-1.104 0-2-.896-2-2v-17h-1v-2h6v-1.5c0-.827.673-1.5 1.5-1.5h5c.825 0 1.5.671 1.5 1.5v1.5h6v2h-1v17c0 1.104-.896 2-2 2zm0-19h-14v16.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-16.5zm-7 7.586l3.293-3.293 1.414 1.414-3.293 3.293 3.293 3.293-1.414 1.414-3.293-3.293-3.293 3.293-1.414-1.414 3.293-3.293-3.293-3.293 1.414-1.414 3.293 3.293zm2-10.586h-4v1h4v-1z", + fill: "currentColor", + strokeWidth: 0.25, + stroke: "currentColor" + })); + const SvgType = ({ + title, + titleId, + ...props + }) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props + }, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId + }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 11.8, + height: 11.8, + rx: 5.9, + stroke: "currentColor", + strokeWidth: 1.2 + }), /* @__PURE__ */React__namespace.createElement("rect", { + x: 5.5, + y: 5.5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" + })); + const ArgumentIcon = generateIcon(SvgArgument); + const ChevronDownIcon = generateIcon(SvgChevronDown); + const ChevronLeftIcon = generateIcon(SvgChevronLeft); + const ChevronUpIcon = generateIcon(SvgChevronUp); + const CloseIcon = generateIcon(SvgClose); + const CopyIcon = generateIcon(SvgCopy); + const DeprecatedArgumentIcon = generateIcon(SvgDeprecatedArgument); + const DeprecatedEnumValueIcon = generateIcon(SvgDeprecatedEnumValue); + const DeprecatedFieldIcon = generateIcon(SvgDeprecatedField); + const DirectiveIcon = generateIcon(SvgDirective); + const DocsFilledIcon = generateIcon(SvgDocsFilled); + const DocsIcon = generateIcon(SvgDocs); + const EnumValueIcon = generateIcon(SvgEnumValue); + const FieldIcon = generateIcon(SvgField); + const HistoryIcon = generateIcon(SvgHistory); + const ImplementsIcon = generateIcon(SvgImplements); + const KeyboardShortcutIcon = generateIcon(SvgKeyboardShortcut); + const MagnifyingGlassIcon = generateIcon(SvgMagnifyingGlass); + const MergeIcon = generateIcon(SvgMerge); + const PenIcon = generateIcon(SvgPen); + const PlayIcon = generateIcon(SvgPlay); + const PlusIcon = generateIcon(SvgPlus); + const PrettifyIcon = generateIcon(SvgPrettify); + const ReloadIcon = generateIcon(SvgReload); + const RootTypeIcon = generateIcon(SvgRootType); + const SettingsIcon = generateIcon(SvgSettings); + const StarFilledIcon = generateIcon(SvgStarFilled); + const StarIcon = generateIcon(SvgStar); + const StopIcon = generateIcon(SvgStop); + const TrashIcon = generateIcon(SvgTrash); + const TypeIcon = generateIcon(SvgType); + function generateIcon(RawComponent) { + const title = RawComponent.name.replace("Svg", "").replaceAll(/([A-Z])/g, " $1").trimStart().toLowerCase() + " icon"; + function IconComponent(props) { + return /* @__PURE__ */jsxRuntime.jsx(RawComponent, { + title, + ...props + }); + } + IconComponent.displayName = RawComponent.name; + return IconComponent; + } + const UnStyledButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-un-styled", props.className) + })); + UnStyledButton.displayName = "UnStyledButton"; + const Button$1 = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-button", { + success: "graphiql-button-success", + error: "graphiql-button-error" + }[props.state], props.className) + })); + Button$1.displayName = "Button"; + const ButtonGroup = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx("graphiql-button-group", props.className) + })); + ButtonGroup.displayName = "ButtonGroup"; + const createComponentGroup = (root, children) => Object.entries(children).reduce((r, [key, value]) => { + r[key] = value; + return r; + }, root); + const DialogClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(D__namespace.Close, { + asChild: true, + children: /* @__PURE__ */jsxRuntime.jsxs(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-dialog-close", props.className), + children: [/* @__PURE__ */jsxRuntime.jsx(reactVisuallyHidden.Root, { + children: "Close dialog" + }), /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {})] + }) + })); + DialogClose.displayName = "Dialog.Close"; + function DialogRoot({ + children, + ...props + }) { + return /* @__PURE__ */jsxRuntime.jsx(D__namespace.Root, { + ...props, + children: /* @__PURE__ */jsxRuntime.jsxs(D__namespace.Portal, { + children: [/* @__PURE__ */jsxRuntime.jsx(D__namespace.Overlay, { + className: "graphiql-dialog-overlay" + }), /* @__PURE__ */jsxRuntime.jsx(D__namespace.Content, { + className: "graphiql-dialog", + children + })] + }) + }); + } + const Dialog = createComponentGroup(DialogRoot, { + Close: DialogClose, + Title: D__namespace.Title, + Trigger: D__namespace.Trigger, + Description: D__namespace.Description + }); + const Button = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Trigger, { + asChild: true, + children: /* @__PURE__ */jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-un-styled", props.className) + }) + })); + Button.displayName = "DropdownMenuButton"; + function Content({ + children, + align = "start", + sideOffset = 5, + className, + ...props + }) { + return /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Portal, { + children: /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Content, { + align, + sideOffset, + className: clsx.clsx("graphiql-dropdown-content", className), + ...props, + children + }) + }); + } + const Item = ({ + className, + children, + ...props + }) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Item, { + className: clsx.clsx("graphiql-dropdown-item", className), + ...props, + children + }); + const DropdownMenu = createComponentGroup(reactDropdownMenu.Root, { + Button, + Item, + Content + }); + const markdown = new MarkdownIt({ + breaks: true, + linkify: true + }); + const MarkdownContent = React.forwardRef(({ + children, + onlyShowFirstChild, + type, + ...props + }, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx(`graphiql-markdown-${type}`, onlyShowFirstChild && "graphiql-markdown-preview", props.className), + dangerouslySetInnerHTML: { + __html: markdown.render(children) + } + })); + MarkdownContent.displayName = "MarkdownContent"; + const Spinner = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx("graphiql-spinner", props.className) + })); + Spinner.displayName = "Spinner"; + function TooltipRoot({ + children, + align = "start", + side = "bottom", + sideOffset = 5, + label + }) { + return /* @__PURE__ */jsxRuntime.jsxs(T__namespace.Root, { + children: [/* @__PURE__ */jsxRuntime.jsx(T__namespace.Trigger, { + asChild: true, + children + }), /* @__PURE__ */jsxRuntime.jsx(T__namespace.Portal, { + children: /* @__PURE__ */jsxRuntime.jsx(T__namespace.Content, { + className: "graphiql-tooltip", + align, + side, + sideOffset, + children: label + }) + })] + }); + } + const Tooltip = createComponentGroup(TooltipRoot, { + Provider: T__namespace.Provider + }); + const TabRoot = React.forwardRef(({ + isActive, + value, + children, + className, + ...props + }, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Item, { + ...props, + ref, + value, + "aria-selected": isActive ? "true" : void 0, + role: "tab", + className: clsx.clsx("graphiql-tab", isActive && "graphiql-tab-active", className), + children + })); + TabRoot.displayName = "Tab"; + const TabButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-tab-button", props.className), + children: props.children + })); + TabButton.displayName = "Tab.Button"; + const TabClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Close Tab", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + "aria-label": "Close Tab", + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-tab-close", props.className), + children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) + }) + })); + TabClose.displayName = "Tab.Close"; + const Tab = createComponentGroup(TabRoot, { + Button: TabButton, + Close: TabClose + }); + const Tabs = React.forwardRef(({ + values, + onReorder, + children, + className, + ...props + }, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Group, { + ...props, + ref, + values, + onReorder, + axis: "x", + role: "tablist", + className: clsx.clsx("graphiql-tabs", className), + children + })); + Tabs.displayName = "Tabs"; + const HistoryContext = createNullableContext("HistoryContext"); + function HistoryContextProvider(props) { + var _a; + const storage = useStorageContext(); + const historyStore = React.useRef(new toolkit.HistoryStore( + // Fall back to a noop storage when the StorageContext is empty + storage || new toolkit.StorageAPI(null), props.maxHistoryLength || DEFAULT_HISTORY_LENGTH)); + const [items, setItems] = React.useState(((_a = historyStore.current) == null ? void 0 : _a.queries) || []); + const addToHistory = React.useCallback(operation => { + var _a2; + (_a2 = historyStore.current) == null ? void 0 : _a2.updateHistory(operation); + setItems(historyStore.current.queries); + }, []); + const editLabel = React.useCallback((operation, index) => { + historyStore.current.editLabel(operation, index); + setItems(historyStore.current.queries); + }, []); + const toggleFavorite = React.useCallback(operation => { + historyStore.current.toggleFavorite(operation); + setItems(historyStore.current.queries); + }, []); + const setActive = React.useCallback(item => { + return item; + }, []); + const deleteFromHistory = React.useCallback((item, clearFavorites = false) => { + historyStore.current.deleteHistory(item, clearFavorites); + setItems(historyStore.current.queries); + }, []); + const value = React.useMemo(() => ({ + addToHistory, + editLabel, + items, + toggleFavorite, + setActive, + deleteFromHistory + }), [addToHistory, editLabel, items, toggleFavorite, setActive, deleteFromHistory]); + return /* @__PURE__ */jsxRuntime.jsx(HistoryContext.Provider, { + value, + children: props.children + }); + } + const useHistoryContext = createContextHook(HistoryContext); + const DEFAULT_HISTORY_LENGTH = 20; + function History() { + const { + items: all, + deleteFromHistory + } = useHistoryContext({ + nonNull: true + }); + let items = all.slice().map((item, i) => ({ + ...item, + index: i + })).reverse(); + const favorites = items.filter(item => item.favorite); + if (favorites.length) { + items = items.filter(item => !item.favorite); + } + const [clearStatus, setClearStatus] = React.useState(null); + React.useEffect(() => { + if (clearStatus) { + setTimeout(() => { + setClearStatus(null); + }, 2e3); + } + }, [clearStatus]); + const handleClearStatus = React.useCallback(() => { + try { + for (const item of items) { + deleteFromHistory(item, true); + } + setClearStatus("success"); + } catch { + setClearStatus("error"); + } + }, [deleteFromHistory, items]); + return /* @__PURE__ */jsxRuntime.jsxs("section", { + "aria-label": "History", + className: "graphiql-history", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-history-header", + children: ["History", (clearStatus || items.length > 0) && /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + state: clearStatus || void 0, + disabled: !items.length, + onClick: handleClearStatus, + children: { + success: "Cleared", + error: "Failed to Clear" + }[clearStatus] || "Clear" + })] + }), Boolean(favorites.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { + className: "graphiql-history-items", + children: favorites.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { + item + }, item.index)) + }), Boolean(favorites.length) && Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-history-item-spacer" + }), Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { + className: "graphiql-history-items", + children: items.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { + item + }, item.index)) + })] + }); + } + function HistoryItem(props) { + const { + editLabel, + toggleFavorite, + deleteFromHistory, + setActive + } = useHistoryContext({ + nonNull: true, + caller: HistoryItem + }); + const { + headerEditor, + queryEditor, + variableEditor + } = useEditorContext({ + nonNull: true, + caller: HistoryItem + }); + const inputRef = React.useRef(null); + const buttonRef = React.useRef(null); + const [isEditable, setIsEditable] = React.useState(false); + React.useEffect(() => { + var _a; + if (isEditable) { + (_a = inputRef.current) == null ? void 0 : _a.focus(); + } + }, [isEditable]); + const displayName = props.item.label || props.item.operationName || formatQuery(props.item.query); + const handleSave = React.useCallback(() => { + var _a; + setIsEditable(false); + const { + index, + ...item + } = props.item; + editLabel({ + ...item, + label: (_a = inputRef.current) == null ? void 0 : _a.value + }, index); + }, [editLabel, props.item]); + const handleClose = React.useCallback(() => { + setIsEditable(false); + }, []); + const handleEditLabel = React.useCallback(e => { + e.stopPropagation(); + setIsEditable(true); + }, []); + const handleHistoryItemClick = React.useCallback(() => { + const { + query, + variables, + headers + } = props.item; + queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); + variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); + headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); + setActive(props.item); + }, [headerEditor, props.item, queryEditor, setActive, variableEditor]); + const handleDeleteItemFromHistory = React.useCallback(e => { + e.stopPropagation(); + deleteFromHistory(props.item); + }, [props.item, deleteFromHistory]); + const handleToggleFavorite = React.useCallback(e => { + e.stopPropagation(); + toggleFavorite(props.item); + }, [props.item, toggleFavorite]); + return /* @__PURE__ */jsxRuntime.jsx("li", { + className: clsx.clsx("graphiql-history-item", isEditable && "editable"), + children: isEditable ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx("input", { + type: "text", + defaultValue: props.item.label, + ref: inputRef, + onKeyDown: e => { + if (e.key === "Esc") { + setIsEditable(false); + } else if (e.key === "Enter") { + setIsEditable(false); + editLabel({ + ...props.item, + label: e.currentTarget.value + }); } + }, + placeholder: "Type a label" + }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + ref: buttonRef, + onClick: handleSave, + children: "Save" + }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + ref: buttonRef, + onClick: handleClose, + children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) + })] + }) : /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Set active", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-label", + onClick: handleHistoryItemClick, + "aria-label": "Set active", + children: displayName + }) + }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Edit label", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleEditLabel, + "aria-label": "Edit label", + children: /* @__PURE__ */jsxRuntime.jsx(PenIcon, { + "aria-hidden": "true" + }) + }) + }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: props.item.favorite ? "Remove favorite" : "Add favorite", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleToggleFavorite, + "aria-label": props.item.favorite ? "Remove favorite" : "Add favorite", + children: props.item.favorite ? /* @__PURE__ */jsxRuntime.jsx(StarFilledIcon, { + "aria-hidden": "true" + }) : /* @__PURE__ */jsxRuntime.jsx(StarIcon, { + "aria-hidden": "true" + }) + }) + }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Delete from history", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleDeleteItemFromHistory, + "aria-label": "Delete from history", + children: /* @__PURE__ */jsxRuntime.jsx(TrashIcon, { + "aria-hidden": "true" + }) + }) + })] + }) + }); + } + function formatQuery(query) { + return query == null ? void 0 : query.split("\n").map(line => line.replace(/#(.*)/, "")).join(" ").replaceAll("{", " { ").replaceAll("}", " } ").replaceAll(/[\s]{2,}/g, " "); + } + const ExecutionContext = createNullableContext("ExecutionContext"); + function ExecutionContextProvider({ + fetcher, + getDefaultFieldNames, + children, + operationName + }) { + if (!fetcher) { + throw new TypeError("The `ExecutionContextProvider` component requires a `fetcher` function to be passed as prop."); + } + const { + externalFragments, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + updateActiveTabValues + } = useEditorContext({ + nonNull: true, + caller: ExecutionContextProvider + }); + const history = useHistoryContext(); + const autoCompleteLeafs = useAutoCompleteLeafs({ + getDefaultFieldNames, + caller: ExecutionContextProvider + }); + const [isFetching, setIsFetching] = React.useState(false); + const [subscription, setSubscription] = React.useState(null); + const queryIdRef = React.useRef(0); + const stop = React.useCallback(() => { + subscription == null ? void 0 : subscription.unsubscribe(); + setIsFetching(false); + setSubscription(null); + }, [subscription]); + const run = React.useCallback(async () => { + var _ref; + if (!queryEditor || !responseEditor) { + return; + } + if (subscription) { + stop(); + return; + } + const setResponse = value2 => { + responseEditor.setValue(value2); + updateActiveTabValues({ + response: value2 + }); + }; + queryIdRef.current += 1; + const queryId = queryIdRef.current; + let query = autoCompleteLeafs() || queryEditor.getValue(); + const variablesString = variableEditor == null ? void 0 : variableEditor.getValue(); + let variables; + try { + variables = tryParseJsonObject({ + json: variablesString, + errorMessageParse: "Variables are invalid JSON", + errorMessageType: "Variables are not a JSON object." + }); + } catch (error) { + setResponse(error instanceof Error ? error.message : `${error}`); + return; + } + const headersString = headerEditor == null ? void 0 : headerEditor.getValue(); + let headers; + try { + headers = tryParseJsonObject({ + json: headersString, + errorMessageParse: "Headers are invalid JSON", + errorMessageType: "Headers are not a JSON object." + }); + } catch (error) { + setResponse(error instanceof Error ? error.message : `${error}`); + return; + } + if (externalFragments) { + const fragmentDependencies = queryEditor.documentAST ? graphqlLanguageService.getFragmentDependenciesForAST(queryEditor.documentAST, externalFragments) : []; + if (fragmentDependencies.length > 0) { + query += "\n" + fragmentDependencies.map(node => graphql.print(node)).join("\n"); + } + } + setResponse(""); + setIsFetching(true); + const opName = (_ref = operationName !== null && operationName !== void 0 ? operationName : queryEditor.operationName) !== null && _ref !== void 0 ? _ref : void 0; + history == null ? void 0 : history.addToHistory({ + query, + variables: variablesString, + headers: headersString, + operationName: opName + }); + try { + var _headers, _queryEditor$document; + const fullResponse = {}; + const handleResponse = result => { + if (queryId !== queryIdRef.current) { + return; } - if (!presets) { - throw new Error("Wrong `markdown-it` preset, can't be empty"); - } - if (presets.options) { - self.set(presets.options); - } - if (presets.components) { - Object.keys(presets.components).forEach(function (name) { - if (presets.components[name].rules) { - self[name].ruler.enableOnly(presets.components[name].rules); - } - if (presets.components[name].rules2) { - self[name].ruler2.enableOnly(presets.components[name].rules2); - } - }); - } - return this; - }; - - /** chainable - * MarkdownIt.enable(list, ignoreInvalid) - * - list (String|Array): rule name or list of rule names to enable - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable list or rules. It will automatically find appropriate components, - * containing rules with given names. If rule not found, and `ignoreInvalid` - * not set - throws exception. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')() - * .enable(['sub', 'sup']) - * .disable('smartquotes'); - * ``` - **/ - MarkdownIt.prototype.enable = function (list, ignoreInvalid) { - let result = []; - if (!Array.isArray(list)) { - list = [list]; - } - ["core", "block", "inline"].forEach(function (chain) { - result = result.concat(this[chain].ruler.enable(list, true)); - }, this); - result = result.concat(this.inline.ruler2.enable(list, true)); - const missed = list.filter(function (name) { - return result.indexOf(name) < 0; - }); - if (missed.length && !ignoreInvalid) { - throw new Error( - "MarkdownIt. Failed to enable unknown rule(s): " + missed - ); + let maybeMultipart = Array.isArray(result) ? result : false; + if (!maybeMultipart && typeof result === "object" && result !== null && "hasNext" in result) { + maybeMultipart = [result]; } - return this; - }; - - /** chainable - * MarkdownIt.disable(list, ignoreInvalid) - * - list (String|Array): rule name or list of rule names to disable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * The same as [[MarkdownIt.enable]], but turn specified rules off. - **/ - MarkdownIt.prototype.disable = function (list, ignoreInvalid) { - let result = []; - if (!Array.isArray(list)) { - list = [list]; - } - ["core", "block", "inline"].forEach(function (chain) { - result = result.concat(this[chain].ruler.disable(list, true)); - }, this); - result = result.concat(this.inline.ruler2.disable(list, true)); - const missed = list.filter(function (name) { - return result.indexOf(name) < 0; - }); - if (missed.length && !ignoreInvalid) { - throw new Error( - "MarkdownIt. Failed to disable unknown rule(s): " + missed - ); + if (maybeMultipart) { + for (const part of maybeMultipart) { + mergeIncrementalResult(fullResponse, part); + } + setIsFetching(false); + setResponse(toolkit.formatResult(fullResponse)); + } else { + const response = toolkit.formatResult(result); + setIsFetching(false); + setResponse(response); } - return this; - }; - - /** chainable - * MarkdownIt.use(plugin, params) - * - * Load specified plugin with given params into current parser instance. - * It's just a sugar to call `plugin(md, params)` with curring. - * - * ##### Example - * - * ```javascript - * var iterator = require('markdown-it-for-inline'); - * var md = require('markdown-it')() - * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { - * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); - * }); - * ``` - **/ - MarkdownIt.prototype.use = function (plugin /*, params, ... */) { - const args = [this].concat(Array.prototype.slice.call(arguments, 1)); - plugin.apply(plugin, args); - return this; }; - - /** internal - * MarkdownIt.parse(src, env) -> Array - * - src (String): source string - * - env (Object): environment sandbox - * - * Parse input string and return list of block tokens (special token type - * "inline" will contain list of inline tokens). You should not call this - * method directly, until you write custom renderer (for example, to produce - * AST). - * - * `env` is used to pass data between "distributed" rules and return additional - * metadata like reference info, needed for the renderer. It also can be used to - * inject data in specific cases. Usually, you will be ok to pass `{}`, - * and then pass updated object to renderer. - **/ - MarkdownIt.prototype.parse = function (src, env) { - if (typeof src !== "string") { - throw new Error("Input data should be a String"); - } - const state = new this.core.State(src, this, env); - this.core.process(state); - return state.tokens; - }; - - /** - * MarkdownIt.render(src [, env]) -> String - * - src (String): source string - * - env (Object): environment sandbox - * - * Render markdown string into html. It does all magic for you :). - * - * `env` can be used to inject additional metadata (`{}` by default). - * But you will not need it with high probability. See also comment - * in [[MarkdownIt.parse]]. - **/ - MarkdownIt.prototype.render = function (src, env) { - env = env || {}; - return this.renderer.render(this.parse(src, env), this.options, env); - }; - - /** internal - * MarkdownIt.parseInline(src, env) -> Array - * - src (String): source string - * - env (Object): environment sandbox - * - * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the - * block tokens list with the single `inline` element, containing parsed inline - * tokens in `children` property. Also updates `env` object. - **/ - MarkdownIt.prototype.parseInline = function (src, env) { - const state = new this.core.State(src, this, env); - state.inlineMode = true; - this.core.process(state); - return state.tokens; - }; - - /** - * MarkdownIt.renderInline(src [, env]) -> String - * - src (String): source string - * - env (Object): environment sandbox - * - * Similar to [[MarkdownIt.render]] but for single paragraph content. Result - * will NOT be wrapped into `
    ${highlighted}
    \n`; + }; + default_rules.image = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + + // "alt" attr MUST be set, even if empty. Because it's mandatory and + // should be placed on proper position for tests. + // + // Replace content with actual value + + token.attrs[token.attrIndex('alt')][1] = slf.renderInlineAsText(token.children, options, env); + return slf.renderToken(tokens, idx, options); + }; + default_rules.hardbreak = function (tokens, idx, options /*, env */) { + return options.xhtmlOut ? '
    \n' : '
    \n'; + }; + default_rules.softbreak = function (tokens, idx, options /*, env */) { + return options.breaks ? options.xhtmlOut ? '
    \n' : '
    \n' : '\n'; + }; + default_rules.text = function (tokens, idx /*, options, env */) { + return escapeHtml(tokens[idx].content); + }; + default_rules.html_block = function (tokens, idx /*, options, env */) { + return tokens[idx].content; + }; + default_rules.html_inline = function (tokens, idx /*, options, env */) { + return tokens[idx].content; + }; + + /** + * new Renderer() + * + * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. + **/ + function Renderer() { + /** + * Renderer#rules -> Object + * + * Contains render rules for tokens. Can be updated and extended. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.renderer.rules.strong_open = function () { return ''; }; + * md.renderer.rules.strong_close = function () { return ''; }; + * + * var result = md.renderInline(...); + * ``` + * + * Each rule is called as independent static function with fixed signature: + * + * ```javascript + * function my_token_render(tokens, idx, options, env, renderer) { + * // ... + * return renderedHTML; + * } + * ``` + * + * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs) + * for more details and examples. + **/ + this.rules = assign({}, default_rules); + } + + /** + * Renderer.renderAttrs(token) -> String + * + * Render token attributes to string. + **/ + Renderer.prototype.renderAttrs = function renderAttrs(token) { + let i, l, result; + if (!token.attrs) { + return ''; + } + result = ''; + for (i = 0, l = token.attrs.length; i < l; i++) { + result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"'; + } + return result; + }; + + /** + * Renderer.renderToken(tokens, idx, options) -> String + * - tokens (Array): list of tokens + * - idx (Numbed): token index to render + * - options (Object): params of parser instance + * + * Default token renderer. Can be overriden by custom function + * in [[Renderer#rules]]. + **/ + Renderer.prototype.renderToken = function renderToken(tokens, idx, options) { + const token = tokens[idx]; + let result = ''; + + // Tight list paragraphs + if (token.hidden) { + return ''; + } + + // Insert a newline between hidden paragraph and subsequent opening + // block-level tag. + // + // For example, here we should insert a newline before blockquote: + // - a + // > + // + if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) { + result += '\n'; + } + + // Add token name, e.g. ``. + // + needLf = false; } } - function getJSONSchemaFromGraphQLType(fieldOrType, options) { - var _a, _b; - let definition = Object.create(null); - const definitions = Object.create(null); - const isField = "type" in fieldOrType; - const type = isField ? fieldOrType.type : fieldOrType; - const baseType = (0, _graphql.isNonNullType)(type) - ? type.ofType - : type; - const required = (0, _graphql.isNonNullType)(type); - if ((0, _graphql.isScalarType)(baseType)) { - if ( - (_a = - options === null || options === void 0 - ? void 0 - : options.scalarSchemas) === null || _a === void 0 - ? void 0 - : _a[baseType.name] - ) { - definition = JSON.parse( - JSON.stringify(options.scalarSchemas[baseType.name]) - ); - } else { - definition.type = ["string", "number", "boolean", "integer"]; - } - if (!required) { - if (Array.isArray(definition.type)) { - definition.type.push("null"); - } else if (definition.type) { - definition.type = [definition.type, "null"]; - } else if (definition.enum) { - definition.enum.push(null); - } else if (definition.oneOf) { - definition.oneOf.push({ - type: "null", - }); - } else { - definition = { - oneOf: [ - definition, - { - type: "null", - }, - ], - }; - } - } - } else if ((0, _graphql.isEnumType)(baseType)) { - definition.enum = baseType.getValues().map((val) => val.name); - if (!required) { - definition.enum.push(null); - } - } else if ((0, _graphql.isListType)(baseType)) { - if (required) { - definition.type = "array"; - } else { - definition.type = ["array", "null"]; - } - const { definition: def, definitions: defs } = - getJSONSchemaFromGraphQLType(baseType.ofType, options); - definition.items = def; - if (defs) { - for (const defName of Object.keys(defs)) { - definitions[defName] = defs[defName]; - } - } - } else if ((0, _graphql.isInputObjectType)(baseType)) { - if (required) { - definition.$ref = `#/definitions/${baseType.name}`; - } else { - definition.oneOf = [ - { - $ref: `#/definitions/${baseType.name}`, - }, - { - type: "null", - }, - ]; - } - if ( - (_b = - options === null || options === void 0 - ? void 0 - : options.definitionMarker) === null || _b === void 0 - ? void 0 - : _b.mark(baseType.name) - ) { - const fields = baseType.getFields(); - const fieldDef = { - type: "object", - properties: {}, - required: [], - }; - fieldDef.description = renderDefinitionDescription(baseType); - if ( - options === null || options === void 0 - ? void 0 - : options.useMarkdownDescription - ) { - fieldDef.markdownDescription = renderDefinitionDescription( - baseType, - true - ); - } - for (const fieldName of Object.keys(fields)) { - const field = fields[fieldName]; - const { - required: fieldRequired, - definition: fieldDefinition, - definitions: typeDefinitions, - } = getJSONSchemaFromGraphQLType(field, options); - fieldDef.properties[fieldName] = fieldDefinition; - if (fieldRequired) { - fieldDef.required.push(fieldName); - } - if (typeDefinitions) { - for (const [defName, value] of Object.entries( - typeDefinitions - )) { - definitions[defName] = value; - } - } - } - definitions[baseType.name] = fieldDef; - } - } - if ( - "defaultValue" in fieldOrType && - fieldOrType.defaultValue !== undefined - ) { - definition.default = fieldOrType.defaultValue; - } - const { description } = definition; - definition.description = renderDefinitionDescription( - fieldOrType, - false, - description - ); - if ( - options === null || options === void 0 - ? void 0 - : options.useMarkdownDescription - ) { - definition.markdownDescription = renderDefinitionDescription( - fieldOrType, - true, - description - ); - } - return { - required, - definition, - definitions, - }; + } + } + result += needLf ? '>\n' : '>'; + return result; + }; + + /** + * Renderer.renderInline(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * The same as [[Renderer.render]], but for single token of `inline` type. + **/ + Renderer.prototype.renderInline = function (tokens, options, env) { + let result = ''; + const rules = this.rules; + for (let i = 0, len = tokens.length; i < len; i++) { + const type = tokens[i].type; + if (typeof rules[type] !== 'undefined') { + result += rules[type](tokens, i, options, env, this); + } else { + result += this.renderToken(tokens, i, options); + } + } + return result; + }; + + /** internal + * Renderer.renderInlineAsText(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * Special kludge for image `alt` attributes to conform CommonMark spec. + * Don't try to use it! Spec requires to show `alt` content with stripped markup, + * instead of simple escaping. + **/ + Renderer.prototype.renderInlineAsText = function (tokens, options, env) { + let result = ''; + for (let i = 0, len = tokens.length; i < len; i++) { + switch (tokens[i].type) { + case 'text': + result += tokens[i].content; + break; + case 'image': + result += this.renderInlineAsText(tokens[i].children, options, env); + break; + case 'html_inline': + case 'html_block': + result += tokens[i].content; + break; + case 'softbreak': + case 'hardbreak': + result += '\n'; + break; + // all other tokens are skipped + } + } + return result; + }; + + /** + * Renderer.render(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * Takes token stream and generates HTML. Probably, you will never need to call + * this method directly. + **/ + Renderer.prototype.render = function (tokens, options, env) { + let result = ''; + const rules = this.rules; + for (let i = 0, len = tokens.length; i < len; i++) { + const type = tokens[i].type; + if (type === 'inline') { + result += this.renderInline(tokens[i].children, options, env); + } else if (typeof rules[type] !== 'undefined') { + result += rules[type](tokens, i, options, env, this); + } else { + result += this.renderToken(tokens, i, options, env); + } + } + return result; + }; + + /** + * class Ruler + * + * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and + * [[MarkdownIt#inline]] to manage sequences of functions (rules): + * + * - keep rules in defined order + * - assign the name to each rule + * - enable/disable rules + * - add/replace rules + * - allow assign rules to additional named chains (in the same) + * - cacheing lists of active rules + * + * You will not need use this class directly until write plugins. For simple + * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and + * [[MarkdownIt.use]]. + **/ + + /** + * new Ruler() + **/ + function Ruler() { + // List of added rules. Each element is: + // + // { + // name: XXX, + // enabled: Boolean, + // fn: Function(), + // alt: [ name2, name3 ] + // } + // + this.__rules__ = []; + + // Cached rule chains. + // + // First level - chain name, '' for default. + // Second level - diginal anchor for fast filtering by charcodes. + // + this.__cache__ = null; + } + + // Helper methods, should not be used directly + + // Find rule index by name + // + Ruler.prototype.__find__ = function (name) { + for (let i = 0; i < this.__rules__.length; i++) { + if (this.__rules__[i].name === name) { + return i; + } + } + return -1; + }; + + // Build rules lookup cache + // + Ruler.prototype.__compile__ = function () { + const self = this; + const chains = ['']; + + // collect unique names + self.__rules__.forEach(function (rule) { + if (!rule.enabled) { + return; + } + rule.alt.forEach(function (altName) { + if (chains.indexOf(altName) < 0) { + chains.push(altName); } - function getVariablesJSONSchema(variableToType, options) { - var _a; - const jsonSchema = { - $schema: "http://json-schema.org/draft-04/schema", - type: "object", - properties: {}, - required: [], - }; - const runtimeOptions = Object.assign(Object.assign({}, options), { - definitionMarker: new Marker(), - scalarSchemas: Object.assign( - Object.assign({}, defaultScalarTypesMap), - options === null || options === void 0 - ? void 0 - : options.scalarSchemas - ), - }); - if (variableToType) { - for (const [variableName, type] of Object.entries(variableToType)) { - const { definition, required, definitions } = - getJSONSchemaFromGraphQLType(type, runtimeOptions); - jsonSchema.properties[variableName] = definition; - if (required) { - (_a = jsonSchema.required) === null || _a === void 0 - ? void 0 - : _a.push(variableName); - } - if (definitions) { - jsonSchema.definitions = Object.assign( - Object.assign( - {}, - jsonSchema === null || jsonSchema === void 0 - ? void 0 - : jsonSchema.definitions - ), - definitions - ); - } - } - } - return jsonSchema; + }); + }); + self.__cache__ = {}; + chains.forEach(function (chain) { + self.__cache__[chain] = []; + self.__rules__.forEach(function (rule) { + if (!rule.enabled) { + return; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/index.js": - /*!*********************************************************!*\ - !*** ../../graphql-language-service/esm/utils/index.js ***! - \*********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "Position", { - enumerable: true, - get: function () { - return _Range.Position; - }, - }); - Object.defineProperty(exports, "Range", { - enumerable: true, - get: function () { - return _Range.Range; - }, - }); - Object.defineProperty(exports, "collectVariables", { - enumerable: true, - get: function () { - return _collectVariables.collectVariables; - }, - }); - Object.defineProperty(exports, "getASTNodeAtPosition", { - enumerable: true, - get: function () { - return _getASTNodeAtPosition.getASTNodeAtPosition; - }, - }); - Object.defineProperty(exports, "getFragmentDependencies", { - enumerable: true, - get: function () { - return _fragmentDependencies.getFragmentDependencies; - }, - }); - Object.defineProperty(exports, "getFragmentDependenciesForAST", { - enumerable: true, - get: function () { - return _fragmentDependencies.getFragmentDependenciesForAST; - }, - }); - Object.defineProperty(exports, "getOperationASTFacts", { - enumerable: true, - get: function () { - return _getOperationFacts.getOperationASTFacts; - }, - }); - Object.defineProperty(exports, "getOperationFacts", { - enumerable: true, - get: function () { - return _getOperationFacts.default; - }, - }); - Object.defineProperty(exports, "getQueryFacts", { - enumerable: true, - get: function () { - return _getOperationFacts.getQueryFacts; - }, - }); - Object.defineProperty(exports, "getVariablesJSONSchema", { - enumerable: true, - get: function () { - return _getVariablesJSONSchema.getVariablesJSONSchema; - }, - }); - Object.defineProperty(exports, "locToRange", { - enumerable: true, - get: function () { - return _Range.locToRange; - }, - }); - Object.defineProperty(exports, "offsetToPosition", { - enumerable: true, - get: function () { - return _Range.offsetToPosition; - }, - }); - Object.defineProperty(exports, "pointToOffset", { - enumerable: true, - get: function () { - return _getASTNodeAtPosition.pointToOffset; - }, - }); - Object.defineProperty(exports, "validateWithCustomRules", { - enumerable: true, - get: function () { - return _validateWithCustomRules.validateWithCustomRules; - }, - }); - var _fragmentDependencies = __webpack_require__( - /*! ./fragmentDependencies */ "../../graphql-language-service/esm/utils/fragmentDependencies.js" - ); - var _getVariablesJSONSchema = __webpack_require__( - /*! ./getVariablesJSONSchema */ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js" - ); - var _getASTNodeAtPosition = __webpack_require__( - /*! ./getASTNodeAtPosition */ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js" - ); - var _Range = __webpack_require__( - /*! ./Range */ "../../graphql-language-service/esm/utils/Range.js" - ); - var _validateWithCustomRules = __webpack_require__( - /*! ./validateWithCustomRules */ "../../graphql-language-service/esm/utils/validateWithCustomRules.js" - ); - var _collectVariables = __webpack_require__( - /*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js" - ); - var _getOperationFacts = _interopRequireWildcard( - __webpack_require__( - /*! ./getOperationFacts */ "../../graphql-language-service/esm/utils/getOperationFacts.js" - ) - ); - function _getRequireWildcardCache(e) { - if ("function" != typeof WeakMap) return null; - var r = new WeakMap(), - t = new WeakMap(); - return (_getRequireWildcardCache = function (e) { - return e ? t : r; - })(e); - } - function _interopRequireWildcard(e, r) { - if (!r && e && e.__esModule) return e; - if (null === e || ("object" != typeof e && "function" != typeof e)) - return { default: e }; - var t = _getRequireWildcardCache(r); - if (t && t.has(e)) return t.get(e); - var n = { __proto__: null }, - a = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var u in e) - if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { - var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; - i && (i.get || i.set) - ? Object.defineProperty(n, u, i) - : (n[u] = e[u]); - } - return (n.default = e), t && t.set(e, n), n; + if (chain && rule.alt.indexOf(chain) < 0) { + return; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/validateWithCustomRules.js": - /*!***************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/validateWithCustomRules.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.validateWithCustomRules = validateWithCustomRules; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const specifiedSDLRules = [ - _graphql.LoneSchemaDefinitionRule, - _graphql.UniqueOperationTypesRule, - _graphql.UniqueTypeNamesRule, - _graphql.UniqueEnumValueNamesRule, - _graphql.UniqueFieldDefinitionNamesRule, - _graphql.UniqueDirectiveNamesRule, - _graphql.KnownTypeNamesRule, - _graphql.KnownDirectivesRule, - _graphql.UniqueDirectivesPerLocationRule, - _graphql.PossibleTypeExtensionsRule, - _graphql.UniqueArgumentNamesRule, - _graphql.UniqueInputFieldNamesRule, - _graphql.UniqueVariableNamesRule, - _graphql.FragmentsOnCompositeTypesRule, - _graphql.ProvidedRequiredArgumentsRule, - ]; - function validateWithCustomRules( - schema, - ast, - customRules, - isRelayCompatMode, - isSchemaDocument - ) { - const rules = _graphql.specifiedRules.filter((rule) => { - if ( - rule === _graphql.NoUnusedFragmentsRule || - rule === _graphql.ExecutableDefinitionsRule - ) { - return false; - } - if (isRelayCompatMode && rule === _graphql.KnownFragmentNamesRule) { - return false; - } - return true; - }); - if (customRules) { - Array.prototype.push.apply(rules, customRules); - } - if (isSchemaDocument) { - Array.prototype.push.apply(rules, specifiedSDLRules); - } - const errors = (0, _graphql.validate)(schema, ast, rules); - return errors.filter((error) => { - if (error.message.includes("Unknown directive") && error.nodes) { - const node = error.nodes[0]; - if (node && node.kind === _graphql.Kind.DIRECTIVE) { - const name = node.name.value; - if (name === "arguments" || name === "argumentDefinitions") { - return false; - } - } - } - return true; - }); + self.__cache__[chain].push(rule.fn); + }); + }); + }; + + /** + * Ruler.at(name, fn [, options]) + * - name (String): rule name to replace. + * - fn (Function): new rule function. + * - options (Object): new rule options (not mandatory). + * + * Replace rule by name with new function & options. Throws error if name not + * found. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * Replace existing typographer replacement rule with new one: + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.core.ruler.at('replacements', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.at = function (name, fn, options) { + const index = this.__find__(name); + const opt = options || {}; + if (index === -1) { + throw new Error('Parser rule not found: ' + name); + } + this.__rules__[index].fn = fn; + this.__rules__[index].alt = opt.alt || []; + this.__cache__ = null; + }; + + /** + * Ruler.before(beforeName, ruleName, fn [, options]) + * - beforeName (String): new rule will be added before this one. + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Add new rule to chain before one with given name. See also + * [[Ruler.after]], [[Ruler.push]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.before = function (beforeName, ruleName, fn, options) { + const index = this.__find__(beforeName); + const opt = options || {}; + if (index === -1) { + throw new Error('Parser rule not found: ' + beforeName); + } + this.__rules__.splice(index, 0, { + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [] + }); + this.__cache__ = null; + }; + + /** + * Ruler.after(afterName, ruleName, fn [, options]) + * - afterName (String): new rule will be added after this one. + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Add new rule to chain after one with given name. See also + * [[Ruler.before]], [[Ruler.push]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.inline.ruler.after('text', 'my_rule', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.after = function (afterName, ruleName, fn, options) { + const index = this.__find__(afterName); + const opt = options || {}; + if (index === -1) { + throw new Error('Parser rule not found: ' + afterName); + } + this.__rules__.splice(index + 1, 0, { + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [] + }); + this.__cache__ = null; + }; + + /** + * Ruler.push(ruleName, fn [, options]) + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Push new rule to the end of chain. See also + * [[Ruler.before]], [[Ruler.after]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.core.ruler.push('my_rule', function replace(state) { + * //... + * }); + * ``` + **/ + Ruler.prototype.push = function (ruleName, fn, options) { + const opt = options || {}; + this.__rules__.push({ + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [] + }); + this.__cache__ = null; + }; + + /** + * Ruler.enable(list [, ignoreInvalid]) -> Array + * - list (String|Array): list of rule names to enable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable rules with given names. If any rule name not found - throw Error. + * Errors can be disabled by second param. + * + * Returns list of found rule names (if no exception happened). + * + * See also [[Ruler.disable]], [[Ruler.enableOnly]]. + **/ + Ruler.prototype.enable = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + const result = []; + + // Search by name and enable + list.forEach(function (name) { + const idx = this.__find__(name); + if (idx < 0) { + if (ignoreInvalid) { + return; } - - /***/ - }, - - /***/ "./style.css": - /*!*******************!*\ - !*** ./style.css ***! - \*******************/ - /***/ function ( - __unused_webpack_module, - __webpack_exports__, - __webpack_require__ - ) { - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - /***/ - }, - - /***/ "../../graphiql-react/dist/style.css": - /*!*******************************************!*\ - !*** ../../graphiql-react/dist/style.css ***! - \*******************************************/ - /***/ function ( - __unused_webpack_module, - __webpack_exports__, - __webpack_require__ - ) { - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - /***/ - }, - - /***/ "../../graphiql-react/font/fira-code.css": - /*!***********************************************!*\ - !*** ../../graphiql-react/font/fira-code.css ***! - \***********************************************/ - /***/ function ( - __unused_webpack_module, - __webpack_exports__, - __webpack_require__ - ) { - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - /***/ - }, - - /***/ "../../graphiql-react/font/roboto.css": - /*!********************************************!*\ - !*** ../../graphiql-react/font/roboto.css ***! - \********************************************/ - /***/ function ( - __unused_webpack_module, - __webpack_exports__, - __webpack_require__ - ) { - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - /***/ - }, - - /***/ react: - /*!************************!*\ - !*** external "React" ***! - \************************/ - /***/ function (module) { - module.exports = window["React"]; - - /***/ - }, - - /***/ "react-dom": - /*!***************************!*\ - !*** external "ReactDOM" ***! - \***************************/ - /***/ function (module) { - module.exports = window["ReactDOM"]; - - /***/ - }, - - /***/ "../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs": - /*!***********************************************************************!*\ - !*** ../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs ***! - \***********************************************************************/ - /***/ function (module, __unused_webpack_exports, __webpack_require__) { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __defNormalProp = (obj, key, value) => - key in obj - ? __defProp(obj, key, { - enumerable: true, - configurable: true, - writable: true, - value, - }) - : (obj[key] = value); - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except, desc) => { - if ( - (from && typeof from === "object") || - typeof from === "function" - ) { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { - get: () => from[key], - enumerable: - !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, - }); - } - return to; - }; - var __toESM = (mod, isNodeMode, target) => ( - (target = mod != null ? __create(__getProtoOf(mod)) : {}), - __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule - ? __defProp(target, "default", { value: mod, enumerable: true }) - : target, - mod - ) - ); - var __toCommonJS = (mod) => - __copyProps(__defProp({}, "__esModule", { value: true }), mod); - var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; - }; - - // src/index.ts - var src_exports = {}; - __export(src_exports, { - Combobox: () => Combobox, - Dialog: () => Dialog, - Disclosure: () => Disclosure, - FocusTrap: () => FocusTrap, - Listbox: () => Listbox, - Menu: () => Menu, - Popover: () => Popover, - Portal: () => Portal, - RadioGroup: () => RadioGroup, - Switch: () => Switch, - Tab: () => Tab, - Transition: () => Transition, - }); - module.exports = __toCommonJS(src_exports); - - // src/components/combobox/combobox.tsx - var import_react19 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/hooks/use-computed.ts - var import_react3 = __webpack_require__(/*! react */ "react"); - - // src/hooks/use-iso-morphic-effect.ts - var import_react = __webpack_require__(/*! react */ "react"); - - // src/utils/env.ts - var Env = class { - constructor() { - __publicField(this, "current", this.detect()); - __publicField(this, "handoffState", "pending"); - __publicField(this, "currentId", 0); - } - set(env2) { - if (this.current === env2) return; - this.handoffState = "pending"; - this.currentId = 0; - this.current = env2; - } - reset() { - this.set(this.detect()); - } - nextId() { - return ++this.currentId; + throw new Error('Rules manager: invalid rule name ' + name); + } + this.__rules__[idx].enabled = true; + result.push(name); + }, this); + this.__cache__ = null; + return result; + }; + + /** + * Ruler.enableOnly(list [, ignoreInvalid]) + * - list (String|Array): list of rule names to enable (whitelist). + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable rules with given names, and disable everything else. If any rule name + * not found - throw Error. Errors can be disabled by second param. + * + * See also [[Ruler.disable]], [[Ruler.enable]]. + **/ + Ruler.prototype.enableOnly = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + this.__rules__.forEach(function (rule) { + rule.enabled = false; + }); + this.enable(list, ignoreInvalid); + }; + + /** + * Ruler.disable(list [, ignoreInvalid]) -> Array + * - list (String|Array): list of rule names to disable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Disable rules with given names. If any rule name not found - throw Error. + * Errors can be disabled by second param. + * + * Returns list of found rule names (if no exception happened). + * + * See also [[Ruler.enable]], [[Ruler.enableOnly]]. + **/ + Ruler.prototype.disable = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + const result = []; + + // Search by name and disable + list.forEach(function (name) { + const idx = this.__find__(name); + if (idx < 0) { + if (ignoreInvalid) { + return; + } + throw new Error('Rules manager: invalid rule name ' + name); + } + this.__rules__[idx].enabled = false; + result.push(name); + }, this); + this.__cache__ = null; + return result; + }; + + /** + * Ruler.getRules(chainName) -> Array + * + * Return array of active functions (rules) for given chain name. It analyzes + * rules configuration, compiles caches if not exists and returns result. + * + * Default chain name is `''` (empty string). It can't be skipped. That's + * done intentionally, to keep signature monomorphic for high speed. + **/ + Ruler.prototype.getRules = function (chainName) { + if (this.__cache__ === null) { + this.__compile__(); + } + + // Chain can be empty, if rules disabled. But we still have to return Array. + return this.__cache__[chainName] || []; + }; + + // Token class + + /** + * class Token + **/ + + /** + * new Token(type, tag, nesting) + * + * Create new token and fill passed properties. + **/ + function Token(type, tag, nesting) { + /** + * Token#type -> String + * + * Type of the token (string, e.g. "paragraph_open") + **/ + this.type = type; + + /** + * Token#tag -> String + * + * html tag name, e.g. "p" + **/ + this.tag = tag; + + /** + * Token#attrs -> Array + * + * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` + **/ + this.attrs = null; + + /** + * Token#map -> Array + * + * Source map info. Format: `[ line_begin, line_end ]` + **/ + this.map = null; + + /** + * Token#nesting -> Number + * + * Level change (number in {-1, 0, 1} set), where: + * + * - `1` means the tag is opening + * - `0` means the tag is self-closing + * - `-1` means the tag is closing + **/ + this.nesting = nesting; + + /** + * Token#level -> Number + * + * nesting level, the same as `state.level` + **/ + this.level = 0; + + /** + * Token#children -> Array + * + * An array of child nodes (inline and img tokens) + **/ + this.children = null; + + /** + * Token#content -> String + * + * In a case of self-closing tag (code, html, fence, etc.), + * it has contents of this tag. + **/ + this.content = ''; + + /** + * Token#markup -> String + * + * '*' or '_' for emphasis, fence string for fence, etc. + **/ + this.markup = ''; + + /** + * Token#info -> String + * + * Additional information: + * + * - Info string for "fence" tokens + * - The value "auto" for autolink "link_open" and "link_close" tokens + * - The string value of the item marker for ordered-list "list_item_open" tokens + **/ + this.info = ''; + + /** + * Token#meta -> Object + * + * A place for plugins to store an arbitrary data + **/ + this.meta = null; + + /** + * Token#block -> Boolean + * + * True for block-level tokens, false for inline tokens. + * Used in renderer to calculate line breaks + **/ + this.block = false; + + /** + * Token#hidden -> Boolean + * + * If it's true, ignore this element when rendering. Used for tight lists + * to hide paragraphs. + **/ + this.hidden = false; + } + + /** + * Token.attrIndex(name) -> Number + * + * Search attribute index by name. + **/ + Token.prototype.attrIndex = function attrIndex(name) { + if (!this.attrs) { + return -1; + } + const attrs = this.attrs; + for (let i = 0, len = attrs.length; i < len; i++) { + if (attrs[i][0] === name) { + return i; + } + } + return -1; + }; + + /** + * Token.attrPush(attrData) + * + * Add `[ name, value ]` attribute to list. Init attrs if necessary + **/ + Token.prototype.attrPush = function attrPush(attrData) { + if (this.attrs) { + this.attrs.push(attrData); + } else { + this.attrs = [attrData]; + } + }; + + /** + * Token.attrSet(name, value) + * + * Set `name` attribute to `value`. Override old value if exists. + **/ + Token.prototype.attrSet = function attrSet(name, value) { + const idx = this.attrIndex(name); + const attrData = [name, value]; + if (idx < 0) { + this.attrPush(attrData); + } else { + this.attrs[idx] = attrData; + } + }; + + /** + * Token.attrGet(name) + * + * Get the value of attribute `name`, or null if it does not exist. + **/ + Token.prototype.attrGet = function attrGet(name) { + const idx = this.attrIndex(name); + let value = null; + if (idx >= 0) { + value = this.attrs[idx][1]; + } + return value; + }; + + /** + * Token.attrJoin(name, value) + * + * Join value to existing attribute via space. Or create new attribute if not + * exists. Useful to operate with token classes. + **/ + Token.prototype.attrJoin = function attrJoin(name, value) { + const idx = this.attrIndex(name); + if (idx < 0) { + this.attrPush([name, value]); + } else { + this.attrs[idx][1] = this.attrs[idx][1] + ' ' + value; + } + }; + + // Core state object + // + + function StateCore(src, md, env) { + this.src = src; + this.env = env; + this.tokens = []; + this.inlineMode = false; + this.md = md; // link to parser instance + } + + // re-export Token class to use in core rules + StateCore.prototype.Token = Token; + + // Normalize input string + + // https://spec.commonmark.org/0.29/#line-ending + const NEWLINES_RE = /\r\n?|\n/g; + const NULL_RE = /\0/g; + function normalize(state) { + let str; + + // Normalize newlines + str = state.src.replace(NEWLINES_RE, '\n'); + + // Replace NULL characters + str = str.replace(NULL_RE, '\uFFFD'); + state.src = str; + } + function block(state) { + let token; + if (state.inlineMode) { + token = new state.Token('inline', '', 0); + token.content = state.src; + token.map = [0, 1]; + token.children = []; + state.tokens.push(token); + } else { + state.md.block.parse(state.src, state.md, state.env, state.tokens); + } + } + function inline(state) { + const tokens = state.tokens; + + // Parse inlines + for (let i = 0, l = tokens.length; i < l; i++) { + const tok = tokens[i]; + if (tok.type === 'inline') { + state.md.inline.parse(tok.content, state.md, state.env, tok.children); + } + } + } + + // Replace link-like texts with link nodes. + // + // Currently restricted by `md.validateLink()` to http/https/ftp + // + + function isLinkOpen$1(str) { + return /^\s]/i.test(str); + } + function isLinkClose$1(str) { + return /^<\/a\s*>/i.test(str); + } + function linkify$1(state) { + const blockTokens = state.tokens; + if (!state.md.options.linkify) { + return; + } + for (let j = 0, l = blockTokens.length; j < l; j++) { + if (blockTokens[j].type !== 'inline' || !state.md.linkify.pretest(blockTokens[j].content)) { + continue; + } + let tokens = blockTokens[j].children; + let htmlLinkLevel = 0; + + // We scan from the end, to keep position when new tags added. + // Use reversed logic in links start/end match + for (let i = tokens.length - 1; i >= 0; i--) { + const currentToken = tokens[i]; + + // Skip content of markdown links + if (currentToken.type === 'link_close') { + i--; + while (tokens[i].level !== currentToken.level && tokens[i].type !== 'link_open') { + i--; } - get isServer() { - return this.current === "server"; + continue; + } + + // Skip content of html tag links + if (currentToken.type === 'html_inline') { + if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) { + htmlLinkLevel--; } - get isClient() { - return this.current === "client"; + if (isLinkClose$1(currentToken.content)) { + htmlLinkLevel++; } - detect() { - if ( - typeof window === "undefined" || - typeof document === "undefined" - ) { - return "server"; + } + if (htmlLinkLevel > 0) { + continue; + } + if (currentToken.type === 'text' && state.md.linkify.test(currentToken.content)) { + const text = currentToken.content; + let links = state.md.linkify.match(text); + + // Now split string to nodes + const nodes = []; + let level = currentToken.level; + let lastPos = 0; + + // forbid escape sequence at the start of the string, + // this avoids http\://example.com/ from being linkified as + // http://example.com/ + if (links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === 'text_special') { + links = links.slice(1); + } + for (let ln = 0; ln < links.length; ln++) { + const url = links[ln].url; + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) { + continue; } - return "client"; + let urlText = links[ln].text; + + // Linkifier might send raw hostnames like "example.com", where url + // starts with domain name. So we prepend http:// in those cases, + // and remove it afterwards. + // + if (!links[ln].schema) { + urlText = state.md.normalizeLinkText('http://' + urlText).replace(/^http:\/\//, ''); + } else if (links[ln].schema === 'mailto:' && !/^mailto:/i.test(urlText)) { + urlText = state.md.normalizeLinkText('mailto:' + urlText).replace(/^mailto:/, ''); + } else { + urlText = state.md.normalizeLinkText(urlText); + } + const pos = links[ln].index; + if (pos > lastPos) { + const token = new state.Token('text', '', 0); + token.content = text.slice(lastPos, pos); + token.level = level; + nodes.push(token); + } + const token_o = new state.Token('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.level = level++; + token_o.markup = 'linkify'; + token_o.info = 'auto'; + nodes.push(token_o); + const token_t = new state.Token('text', '', 0); + token_t.content = urlText; + token_t.level = level; + nodes.push(token_t); + const token_c = new state.Token('link_close', 'a', -1); + token_c.level = --level; + token_c.markup = 'linkify'; + token_c.info = 'auto'; + nodes.push(token_c); + lastPos = links[ln].lastIndex; + } + if (lastPos < text.length) { + const token = new state.Token('text', '', 0); + token.content = text.slice(lastPos); + token.level = level; + nodes.push(token); } - handoff() { - if (this.handoffState === "pending") { - this.handoffState = "complete"; - } + + // replace current node + blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes); + } + } + } + } + + // Simple typographic replacements + // + // (c) (C) → © + // (tm) (TM) → ™ + // (r) (R) → ® + // +- → ± + // ... → … (also ?.... → ?.., !.... → !..) + // ???????? → ???, !!!!! → !!!, `,,` → `,` + // -- → –, --- → — + // + + // TODO: + // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ + // - multiplications 2 x 4 -> 2 × 4 + + const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; + + // Workaround for phantomjs - need regex without /g flag, + // or root check will fail every second time + const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; + const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig; + const SCOPED_ABBR = { + c: '©', + r: '®', + tm: '™' + }; + function replaceFn(match, name) { + return SCOPED_ABBR[name.toLowerCase()]; + } + function replace_scoped(inlineTokens) { + let inside_autolink = 0; + for (let i = inlineTokens.length - 1; i >= 0; i--) { + const token = inlineTokens[i]; + if (token.type === 'text' && !inside_autolink) { + token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); + } + if (token.type === 'link_open' && token.info === 'auto') { + inside_autolink--; + } + if (token.type === 'link_close' && token.info === 'auto') { + inside_autolink++; + } + } + } + function replace_rare(inlineTokens) { + let inside_autolink = 0; + for (let i = inlineTokens.length - 1; i >= 0; i--) { + const token = inlineTokens[i]; + if (token.type === 'text' && !inside_autolink) { + if (RARE_RE.test(token.content)) { + token.content = token.content.replace(/\+-/g, '±') + // .., ..., ....... -> … + // but ?..... & !..... -> ?.. & !.. + .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..').replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',') + // em-dash + .replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014') + // en-dash + .replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013').replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013'); + } + } + if (token.type === 'link_open' && token.info === 'auto') { + inside_autolink--; + } + if (token.type === 'link_close' && token.info === 'auto') { + inside_autolink++; + } + } + } + function replace(state) { + let blkIdx; + if (!state.md.options.typographer) { + return; + } + for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { + if (state.tokens[blkIdx].type !== 'inline') { + continue; + } + if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { + replace_scoped(state.tokens[blkIdx].children); + } + if (RARE_RE.test(state.tokens[blkIdx].content)) { + replace_rare(state.tokens[blkIdx].children); + } + } + } + + // Convert straight quotation marks to typographic ones + // + + const QUOTE_TEST_RE = /['"]/; + const QUOTE_RE = /['"]/g; + const APOSTROPHE = '\u2019'; /* ’ */ + + function replaceAt(str, index, ch) { + return str.slice(0, index) + ch + str.slice(index + 1); + } + function process_inlines(tokens, state) { + let j; + const stack = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const thisLevel = tokens[i].level; + for (j = stack.length - 1; j >= 0; j--) { + if (stack[j].level <= thisLevel) { + break; + } + } + stack.length = j + 1; + if (token.type !== 'text') { + continue; + } + let text = token.content; + let pos = 0; + let max = text.length; + + /* eslint no-labels:0,block-scoped-var:0 */ + OUTER: while (pos < max) { + QUOTE_RE.lastIndex = pos; + const t = QUOTE_RE.exec(text); + if (!t) { + break; + } + let canOpen = true; + let canClose = true; + pos = t.index + 1; + const isSingle = t[0] === "'"; + + // Find previous character, + // default to space if it's the beginning of the line + // + let lastChar = 0x20; + if (t.index - 1 >= 0) { + lastChar = text.charCodeAt(t.index - 1); + } else { + for (j = i - 1; j >= 0; j--) { + if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // lastChar defaults to 0x20 + if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + + lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1); + break; } - get isHandoffComplete() { - return this.handoffState === "complete"; + } + + // Find next character, + // default to space if it's the end of the line + // + let nextChar = 0x20; + if (pos < max) { + nextChar = text.charCodeAt(pos); + } else { + for (j = i + 1; j < tokens.length; j++) { + if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // nextChar defaults to 0x20 + if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + + nextChar = tokens[j].content.charCodeAt(0); + break; } - }; - var env = new Env(); - - // src/hooks/use-iso-morphic-effect.ts - var useIsoMorphicEffect = (effect, deps) => { - if (env.isServer) { - (0, import_react.useEffect)(effect, deps); - } else { - (0, import_react.useLayoutEffect)(effect, deps); + } + const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); + const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); + const isLastWhiteSpace = isWhiteSpace(lastChar); + const isNextWhiteSpace = isWhiteSpace(nextChar); + if (isNextWhiteSpace) { + canOpen = false; + } else if (isNextPunctChar) { + if (!(isLastWhiteSpace || isLastPunctChar)) { + canOpen = false; } - }; - - // src/hooks/use-latest-value.ts - var import_react2 = __webpack_require__(/*! react */ "react"); - function useLatestValue(value) { - let cache = (0, import_react2.useRef)(value); - useIsoMorphicEffect(() => { - cache.current = value; - }, [value]); - return cache; } - - // src/hooks/use-computed.ts - function useComputed(cb, dependencies) { - let [value, setValue] = (0, import_react3.useState)(cb); - let cbRef = useLatestValue(cb); - useIsoMorphicEffect( - () => setValue(cbRef.current), - [cbRef, setValue, ...dependencies] - ); - return value; + if (isLastWhiteSpace) { + canClose = false; + } else if (isLastPunctChar) { + if (!(isNextWhiteSpace || isNextPunctChar)) { + canClose = false; + } } - - // src/hooks/use-disposables.ts - var import_react4 = __webpack_require__(/*! react */ "react"); - - // src/utils/micro-task.ts - function microTask(cb) { - if (typeof queueMicrotask === "function") { - queueMicrotask(cb); - } else { - Promise.resolve() - .then(cb) - .catch((e) => - setTimeout(() => { - throw e; - }) - ); + if (nextChar === 0x22 /* " */ && t[0] === '"') { + if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { + // special case: 1"" - count first quote as an inch + canClose = canOpen = false; } } - - // src/utils/disposables.ts - function disposables() { - let _disposables = []; - let api = { - addEventListener(element, name, listener, options) { - element.addEventListener(name, listener, options); - return api.add(() => - element.removeEventListener(name, listener, options) - ); - }, - requestAnimationFrame(...args) { - let raf = requestAnimationFrame(...args); - return api.add(() => cancelAnimationFrame(raf)); - }, - nextFrame(...args) { - return api.requestAnimationFrame(() => { - return api.requestAnimationFrame(...args); - }); - }, - setTimeout(...args) { - let timer = setTimeout(...args); - return api.add(() => clearTimeout(timer)); - }, - microTask(...args) { - let task = { current: true }; - microTask(() => { - if (task.current) { - args[0](); - } - }); - return api.add(() => { - task.current = false; - }); - }, - style(node, property, value) { - let previous = node.style.getPropertyValue(property); - Object.assign(node.style, { [property]: value }); - return this.add(() => { - Object.assign(node.style, { [property]: previous }); - }); - }, - group(cb) { - let d = disposables(); - cb(d); - return this.add(() => d.dispose()); - }, - add(cb) { - _disposables.push(cb); - return () => { - let idx = _disposables.indexOf(cb); - if (idx >= 0) { - for (let dispose of _disposables.splice(idx, 1)) { - dispose(); - } - } - }; - }, - dispose() { - for (let dispose of _disposables.splice(0)) { - dispose(); - } - }, - }; - return api; + if (canOpen && canClose) { + // Replace quotes in the middle of punctuation sequence, but not + // in the middle of the words, i.e.: + // + // 1. foo " bar " baz - not replaced + // 2. foo-"-bar-"-baz - replaced + // 3. foo"bar"baz - not replaced + // + canOpen = isLastPunctChar; + canClose = isNextPunctChar; } - - // src/hooks/use-disposables.ts - function useDisposables() { - let [d] = (0, import_react4.useState)(disposables); - (0, import_react4.useEffect)(() => () => d.dispose(), [d]); - return d; + if (!canOpen && !canClose) { + // middle of word + if (isSingle) { + token.content = replaceAt(token.content, t.index, APOSTROPHE); + } + continue; } - - // src/hooks/use-event.ts - var import_react5 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var useEvent = - // TODO: Add React.useEvent ?? once the useEvent hook is available - function useEvent2(cb) { - let cache = useLatestValue(cb); - return import_react5.default.useCallback( - (...args) => cache.current(...args), - [cache] - ); - }; - - // src/hooks/use-id.ts - var import_react7 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/hooks/use-server-handoff-complete.ts - var import_react6 = __webpack_require__(/*! react */ "react"); - function useServerHandoffComplete() { - let [complete, setComplete] = (0, import_react6.useState)( - env.isHandoffComplete - ); - if (complete && env.isHandoffComplete === false) { - setComplete(false); + if (canClose) { + // this could be a closing quote, rewind the stack to get a match + for (j = stack.length - 1; j >= 0; j--) { + let item = stack[j]; + if (stack[j].level < thisLevel) { + break; + } + if (item.single === isSingle && stack[j].level === thisLevel) { + item = stack[j]; + let openQuote; + let closeQuote; + if (isSingle) { + openQuote = state.md.options.quotes[2]; + closeQuote = state.md.options.quotes[3]; + } else { + openQuote = state.md.options.quotes[0]; + closeQuote = state.md.options.quotes[1]; + } + + // replace token.content *before* tokens[item.token].content, + // because, if they are pointing at the same token, replaceAt + // could mess up indices when quote length != 1 + token.content = replaceAt(token.content, t.index, closeQuote); + tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, openQuote); + pos += closeQuote.length - 1; + if (item.token === i) { + pos += openQuote.length - 1; + } + text = token.content; + max = text.length; + stack.length = j; + continue OUTER; + } } - (0, import_react6.useEffect)(() => { - if (complete === true) return; - setComplete(true); - }, [complete]); - (0, import_react6.useEffect)(() => env.handoff(), []); - return complete; } - - // src/hooks/use-id.ts - var _a; - var useId = - // Prefer React's `useId` if it's available. - // @ts-expect-error - `useId` doesn't exist in React < 18. - (_a = import_react7.default.useId) != null - ? _a - : function useId2() { - let ready = useServerHandoffComplete(); - let [id, setId] = import_react7.default.useState( - ready ? () => env.nextId() : null - ); - useIsoMorphicEffect(() => { - if (id === null) setId(env.nextId()); - }, [id]); - return id != null ? "" + id : void 0; - }; - - // src/hooks/use-outside-click.ts - var import_react10 = __webpack_require__(/*! react */ "react"); - - // src/utils/match.ts - function match(value, lookup, ...args) { - if (value in lookup) { - let returnValue = lookup[value]; - return typeof returnValue === "function" - ? returnValue(...args) - : returnValue; - } - let error = new Error( - `Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys( - lookup - ) - .map((key) => `"${key}"`) - .join(", ")}.` - ); - if (Error.captureStackTrace) Error.captureStackTrace(error, match); - throw error; + if (canOpen) { + stack.push({ + token: i, + pos: t.index, + single: isSingle, + level: thisLevel + }); + } else if (canClose && isSingle) { + token.content = replaceAt(token.content, t.index, APOSTROPHE); } - - // src/utils/owner.ts - function getOwnerDocument(element) { - if (env.isServer) return null; - if (element instanceof Node) return element.ownerDocument; - if (element == null ? void 0 : element.hasOwnProperty("current")) { - if (element.current instanceof Node) - return element.current.ownerDocument; + } + } + } + function smartquotes(state) { + /* eslint max-depth:0 */ + if (!state.md.options.typographer) { + return; + } + for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { + if (state.tokens[blkIdx].type !== 'inline' || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) { + continue; + } + process_inlines(state.tokens[blkIdx].children, state); + } + } + + // Join raw text tokens with the rest of the text + // + // This is set as a separate rule to provide an opportunity for plugins + // to run text replacements after text join, but before escape join. + // + // For example, `\:)` shouldn't be replaced with an emoji. + // + + function text_join(state) { + let curr, last; + const blockTokens = state.tokens; + const l = blockTokens.length; + for (let j = 0; j < l; j++) { + if (blockTokens[j].type !== 'inline') continue; + const tokens = blockTokens[j].children; + const max = tokens.length; + for (curr = 0; curr < max; curr++) { + if (tokens[curr].type === 'text_special') { + tokens[curr].type = 'text'; + } + } + for (curr = last = 0; curr < max; curr++) { + if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { + // collapse two adjacent text nodes + tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; + } else { + if (curr !== last) { + tokens[last] = tokens[curr]; } - return document; + last++; } - - // src/utils/focus-management.ts - var focusableSelector = [ - "[contentEditable=true]", - "[tabindex]", - "a[href]", - "area[href]", - "button:not([disabled])", - "iframe", - "input:not([disabled])", - "select:not([disabled])", - "textarea:not([disabled])", - ] - .map( - false - ? // TODO: Remove this once JSDOM fixes the issue where an element that is - // "hidden" can be the document.activeElement, because this is not possible - // in real browsers. - 0 - : (selector) => `${selector}:not([tabindex='-1'])` - ) - .join(","); - function getFocusableElements(container = document.body) { - if (container == null) return []; - return Array.from(container.querySelectorAll(focusableSelector)).sort( - // We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well. - (a, z) => - Math.sign( - (a.tabIndex || Number.MAX_SAFE_INTEGER) - - (z.tabIndex || Number.MAX_SAFE_INTEGER) - ) - ); + } + if (curr !== last) { + tokens.length = last; + } + } + } + + /** internal + * class Core + * + * Top-level rules executor. Glues block/inline parsers and does intermediate + * transformations. + **/ + + const _rules$2 = [['normalize', normalize], ['block', block], ['inline', inline], ['linkify', linkify$1], ['replacements', replace], ['smartquotes', smartquotes], + // `text_join` finds `text_special` tokens (for escape sequences) + // and joins them with the rest of the text + ['text_join', text_join]]; + + /** + * new Core() + **/ + function Core() { + /** + * Core#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of core rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules$2.length; i++) { + this.ruler.push(_rules$2[i][0], _rules$2[i][1]); + } + } + + /** + * Core.process(state) + * + * Executes core chain rules. + **/ + Core.prototype.process = function (state) { + const rules = this.ruler.getRules(''); + for (let i = 0, l = rules.length; i < l; i++) { + rules[i](state); + } + }; + Core.prototype.State = StateCore; + + // Parser state class + + function StateBlock(src, md, env, tokens) { + this.src = src; + + // link to parser instance + this.md = md; + this.env = env; + + // + // Internal state vartiables + // + + this.tokens = tokens; + this.bMarks = []; // line begin offsets for fast jumps + this.eMarks = []; // line end offsets for fast jumps + this.tShift = []; // offsets of the first non-space characters (tabs not expanded) + this.sCount = []; // indents for each line (tabs expanded) + + // An amount of virtual spaces (tabs expanded) between beginning + // of each line (bMarks) and real beginning of that line. + // + // It exists only as a hack because blockquotes override bMarks + // losing information in the process. + // + // It's used only when expanding tabs, you can think about it as + // an initial tab length, e.g. bsCount=21 applied to string `\t123` + // means first tab should be expanded to 4-21%4 === 3 spaces. + // + this.bsCount = []; + + // block parser variables + + // required block content indent (for example, if we are + // inside a list, it would be positioned after list marker) + this.blkIndent = 0; + this.line = 0; // line index in src + this.lineMax = 0; // lines count + this.tight = false; // loose/tight mode for lists + this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) + this.listIndent = -1; // indent of the current list block (-1 if there isn't any) + + // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' + // used in lists to determine if they interrupt a paragraph + this.parentType = 'root'; + this.level = 0; + + // Create caches + // Generate markers. + const s = this.src; + for (let start = 0, pos = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos < len; pos++) { + const ch = s.charCodeAt(pos); + if (!indent_found) { + if (isSpace(ch)) { + indent++; + if (ch === 0x09) { + offset += 4 - offset % 4; + } else { + offset++; + } + continue; + } else { + indent_found = true; } - function isFocusableElement(element, mode = 0 /* Strict */) { - var _a3; - if ( - element === - ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body) - ) - return false; - return match(mode, { - [0 /* Strict */]() { - return element.matches(focusableSelector); - }, - [1 /* Loose */]() { - let next = element; - while (next !== null) { - if (next.matches(focusableSelector)) return true; - next = next.parentElement; - } - return false; - }, - }); + } + if (ch === 0x0A || pos === len - 1) { + if (ch !== 0x0A) { + pos++; } - function restoreFocusIfNecessary(element) { - let ownerDocument = getOwnerDocument(element); - disposables().nextFrame(() => { - if ( - ownerDocument && - !isFocusableElement(ownerDocument.activeElement, 0 /* Strict */) - ) { - focusElement(element); - } - }); + this.bMarks.push(start); + this.eMarks.push(pos); + this.tShift.push(indent); + this.sCount.push(offset); + this.bsCount.push(0); + indent_found = false; + indent = 0; + offset = 0; + start = pos + 1; + } + } + + // Push fake entry to simplify cache bounds checks + this.bMarks.push(s.length); + this.eMarks.push(s.length); + this.tShift.push(0); + this.sCount.push(0); + this.bsCount.push(0); + this.lineMax = this.bMarks.length - 1; // don't count last fake line + } + + // Push new token to "stream". + // + StateBlock.prototype.push = function (type, tag, nesting) { + const token = new Token(type, tag, nesting); + token.block = true; + if (nesting < 0) this.level--; // closing tag + token.level = this.level; + if (nesting > 0) this.level++; // opening tag + + this.tokens.push(token); + return token; + }; + StateBlock.prototype.isEmpty = function isEmpty(line) { + return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; + }; + StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { + for (let max = this.lineMax; from < max; from++) { + if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { + break; + } + } + return from; + }; + + // Skip spaces from given position. + StateBlock.prototype.skipSpaces = function skipSpaces(pos) { + for (let max = this.src.length; pos < max; pos++) { + const ch = this.src.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } + } + return pos; + }; + + // Skip spaces from given position in reverse. + StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) { + if (pos <= min) { + return pos; + } + while (pos > min) { + if (!isSpace(this.src.charCodeAt(--pos))) { + return pos + 1; + } + } + return pos; + }; + + // Skip char codes from given position + StateBlock.prototype.skipChars = function skipChars(pos, code) { + for (let max = this.src.length; pos < max; pos++) { + if (this.src.charCodeAt(pos) !== code) { + break; + } + } + return pos; + }; + + // Skip char codes reverse from given position - 1 + StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) { + if (pos <= min) { + return pos; + } + while (pos > min) { + if (code !== this.src.charCodeAt(--pos)) { + return pos + 1; + } + } + return pos; + }; + + // cut lines range from source. + StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) { + if (begin >= end) { + return ''; + } + const queue = new Array(end - begin); + for (let i = 0, line = begin; line < end; line++, i++) { + let lineIndent = 0; + const lineStart = this.bMarks[line]; + let first = lineStart; + let last; + if (line + 1 < end || keepLastLF) { + // No need for bounds check because we have fake entry on tail. + last = this.eMarks[line] + 1; + } else { + last = this.eMarks[line]; + } + while (first < last && lineIndent < indent) { + const ch = this.src.charCodeAt(first); + if (isSpace(ch)) { + if (ch === 0x09) { + lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4; + } else { + lineIndent++; + } + } else if (first - lineStart < this.tShift[line]) { + // patched tShift masked characters to look like spaces (blockquotes, list markers) + lineIndent++; + } else { + break; } - if (typeof window !== "undefined" && typeof document !== "undefined") { - document.addEventListener( - "keydown", - (event) => { - if (event.metaKey || event.altKey || event.ctrlKey) { - return; - } - document.documentElement.dataset.headlessuiFocusVisible = ""; - }, - true - ); - document.addEventListener( - "click", - (event) => { - if (event.detail === 1 /* Mouse */) { - delete document.documentElement.dataset.headlessuiFocusVisible; - } else if (event.detail === 0 /* Keyboard */) { - document.documentElement.dataset.headlessuiFocusVisible = ""; - } - }, - true - ); + first++; + } + if (lineIndent > indent) { + // partially expanding tabs in code blocks, e.g '\t\tfoobar' + // with indent=2 becomes ' \tfoobar' + queue[i] = new Array(lineIndent - indent + 1).join(' ') + this.src.slice(first, last); + } else { + queue[i] = this.src.slice(first, last); + } + } + return queue.join(''); + }; + + // re-export Token class to use in block rules + StateBlock.prototype.Token = Token; + + // GFM table, https://github.github.com/gfm/#tables-extension- + + // Limit the amount of empty autocompleted cells in a table, + // see https://github.com/markdown-it/markdown-it/issues/1000, + // + // Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. + // We set it to 65k, which can expand user input by a factor of x370 + // (256x256 square is 1.8kB expanded into 650kB). + const MAX_AUTOCOMPLETED_CELLS = 0x10000; + function getLine(state, line) { + const pos = state.bMarks[line] + state.tShift[line]; + const max = state.eMarks[line]; + return state.src.slice(pos, max); + } + function escapedSplit(str) { + const result = []; + const max = str.length; + let pos = 0; + let ch = str.charCodeAt(pos); + let isEscaped = false; + let lastPos = 0; + let current = ''; + while (pos < max) { + if (ch === 0x7c /* | */) { + if (!isEscaped) { + // pipe separating cells, '|' + result.push(current + str.substring(lastPos, pos)); + current = ''; + lastPos = pos + 1; + } else { + // escaped pipe, '\|' + current += str.substring(lastPos, pos - 1); + lastPos = pos; } - function focusElement(element) { - element == null ? void 0 : element.focus({ preventScroll: true }); + } + isEscaped = ch === 0x5c /* \ */; + pos++; + ch = str.charCodeAt(pos); + } + result.push(current + str.substring(lastPos)); + return result; + } + function table(state, startLine, endLine, silent) { + // should have at least two lines + if (startLine + 2 > endLine) { + return false; + } + let nextLine = startLine + 1; + if (state.sCount[nextLine] < state.blkIndent) { + return false; + } + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + return false; + } + + // first character of the second line should be '|', '-', ':', + // and no other characters are allowed but spaces; + // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp + + let pos = state.bMarks[nextLine] + state.tShift[nextLine]; + if (pos >= state.eMarks[nextLine]) { + return false; + } + const firstCh = state.src.charCodeAt(pos++); + if (firstCh !== 0x7C /* | */ && firstCh !== 0x2D /* - */ && firstCh !== 0x3A /* : */) { + return false; + } + if (pos >= state.eMarks[nextLine]) { + return false; + } + const secondCh = state.src.charCodeAt(pos++); + if (secondCh !== 0x7C /* | */ && secondCh !== 0x2D /* - */ && secondCh !== 0x3A /* : */ && !isSpace(secondCh)) { + return false; + } + + // if first character is '-', then second character must not be a space + // (due to parsing ambiguity with list) + if (firstCh === 0x2D /* - */ && isSpace(secondCh)) { + return false; + } + while (pos < state.eMarks[nextLine]) { + const ch = state.src.charCodeAt(pos); + if (ch !== 0x7C /* | */ && ch !== 0x2D /* - */ && ch !== 0x3A /* : */ && !isSpace(ch)) { + return false; + } + pos++; + } + let lineText = getLine(state, startLine + 1); + let columns = lineText.split('|'); + const aligns = []; + for (let i = 0; i < columns.length; i++) { + const t = columns[i].trim(); + if (!t) { + // allow empty columns before and after table, but not in between columns; + // e.g. allow ` |---| `, disallow ` ---||--- ` + if (i === 0 || i === columns.length - 1) { + continue; + } else { + return false; } - var selectableSelector = ["textarea", "input"].join(","); - function isSelectableElement(element) { - var _a3, _b; - return (_b = - (_a3 = element == null ? void 0 : element.matches) == null - ? void 0 - : _a3.call(element, selectableSelector)) != null - ? _b - : false; - } - function sortByDomNode(nodes, resolveKey = (i) => i) { - return nodes.slice().sort((aItem, zItem) => { - let a = resolveKey(aItem); - let z = resolveKey(zItem); - if (a === null || z === null) return 0; - let position = a.compareDocumentPosition(z); - if (position & Node.DOCUMENT_POSITION_FOLLOWING) return -1; - if (position & Node.DOCUMENT_POSITION_PRECEDING) return 1; - return 0; - }); + } + if (!/^:?-+:?$/.test(t)) { + return false; + } + if (t.charCodeAt(t.length - 1) === 0x3A /* : */) { + aligns.push(t.charCodeAt(0) === 0x3A /* : */ ? 'center' : 'right'); + } else if (t.charCodeAt(0) === 0x3A /* : */) { + aligns.push('left'); + } else { + aligns.push(''); + } + } + lineText = getLine(state, startLine).trim(); + if (lineText.indexOf('|') === -1) { + return false; + } + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + columns = escapedSplit(lineText); + if (columns.length && columns[0] === '') columns.shift(); + if (columns.length && columns[columns.length - 1] === '') columns.pop(); + + // header row will define an amount of columns in the entire table, + // and align row should be exactly the same (the rest of the rows can differ) + const columnCount = columns.length; + if (columnCount === 0 || columnCount !== aligns.length) { + return false; + } + if (silent) { + return true; + } + const oldParentType = state.parentType; + state.parentType = 'table'; + + // use 'blockquote' lists for termination because it's + // the most similar to tables + const terminatorRules = state.md.block.ruler.getRules('blockquote'); + const token_to = state.push('table_open', 'table', 1); + const tableLines = [startLine, 0]; + token_to.map = tableLines; + const token_tho = state.push('thead_open', 'thead', 1); + token_tho.map = [startLine, startLine + 1]; + const token_htro = state.push('tr_open', 'tr', 1); + token_htro.map = [startLine, startLine + 1]; + for (let i = 0; i < columns.length; i++) { + const token_ho = state.push('th_open', 'th', 1); + if (aligns[i]) { + token_ho.attrs = [['style', 'text-align:' + aligns[i]]]; + } + const token_il = state.push('inline', '', 0); + token_il.content = columns[i].trim(); + token_il.children = []; + state.push('th_close', 'th', -1); + } + state.push('tr_close', 'tr', -1); + state.push('thead_close', 'thead', -1); + let tbodyLines; + let autocompletedCells = 0; + for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { + if (state.sCount[nextLine] < state.blkIndent) { + break; + } + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; } - function focusFrom(current, focus) { - return focusIn(getFocusableElements(), focus, { - relativeTo: current, - }); + } + if (terminate) { + break; + } + lineText = getLine(state, nextLine).trim(); + if (!lineText) { + break; + } + if (state.sCount[nextLine] - state.blkIndent >= 4) { + break; + } + columns = escapedSplit(lineText); + if (columns.length && columns[0] === '') columns.shift(); + if (columns.length && columns[columns.length - 1] === '') columns.pop(); + + // note: autocomplete count can be negative if user specifies more columns than header, + // but that does not affect intended use (which is limiting expansion) + autocompletedCells += columnCount - columns.length; + if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) { + break; + } + if (nextLine === startLine + 2) { + const token_tbo = state.push('tbody_open', 'tbody', 1); + token_tbo.map = tbodyLines = [startLine + 2, 0]; + } + const token_tro = state.push('tr_open', 'tr', 1); + token_tro.map = [nextLine, nextLine + 1]; + for (let i = 0; i < columnCount; i++) { + const token_tdo = state.push('td_open', 'td', 1); + if (aligns[i]) { + token_tdo.attrs = [['style', 'text-align:' + aligns[i]]]; + } + const token_il = state.push('inline', '', 0); + token_il.content = columns[i] ? columns[i].trim() : ''; + token_il.children = []; + state.push('td_close', 'td', -1); + } + state.push('tr_close', 'tr', -1); + } + if (tbodyLines) { + state.push('tbody_close', 'tbody', -1); + tbodyLines[1] = nextLine; + } + state.push('table_close', 'table', -1); + tableLines[1] = nextLine; + state.parentType = oldParentType; + state.line = nextLine; + return true; + } + + // Code block (4 spaces padded) + + function code(state, startLine, endLine /*, silent */) { + if (state.sCount[startLine] - state.blkIndent < 4) { + return false; + } + let nextLine = startLine + 1; + let last = nextLine; + while (nextLine < endLine) { + if (state.isEmpty(nextLine)) { + nextLine++; + continue; + } + if (state.sCount[nextLine] - state.blkIndent >= 4) { + nextLine++; + last = nextLine; + continue; + } + break; + } + state.line = last; + const token = state.push('code_block', 'code', 0); + token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + '\n'; + token.map = [startLine, state.line]; + return true; + } + + // fences (``` lang, ~~~ lang) + + function fence(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (pos + 3 > max) { + return false; + } + const marker = state.src.charCodeAt(pos); + if (marker !== 0x7E /* ~ */ && marker !== 0x60 /* ` */) { + return false; + } + + // scan marker length + let mem = pos; + pos = state.skipChars(pos, marker); + let len = pos - mem; + if (len < 3) { + return false; + } + const markup = state.src.slice(mem, pos); + const params = state.src.slice(pos, max); + if (marker === 0x60 /* ` */) { + if (params.indexOf(String.fromCharCode(marker)) >= 0) { + return false; + } + } + + // Since start is found, we can report success here in validation mode + if (silent) { + return true; + } + + // search end of block + let nextLine = startLine; + let haveEndMarker = false; + for (;;) { + nextLine++; + if (nextLine >= endLine) { + // unclosed block should be autoclosed by end of document. + // also block seems to be autoclosed by end of parent + break; + } + pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + if (pos < max && state.sCount[nextLine] < state.blkIndent) { + // non-empty line with negative indent should stop the list: + // - ``` + // test + break; + } + if (state.src.charCodeAt(pos) !== marker) { + continue; + } + if (state.sCount[nextLine] - state.blkIndent >= 4) { + // closing fence should be indented less than 4 spaces + continue; + } + pos = state.skipChars(pos, marker); + + // closing code fence must be at least as long as the opening one + if (pos - mem < len) { + continue; + } + + // make sure tail has spaces only + pos = state.skipSpaces(pos); + if (pos < max) { + continue; + } + haveEndMarker = true; + // found! + break; + } + + // If a fence has heading spaces, they should be removed from its inner block + len = state.sCount[startLine]; + state.line = nextLine + (haveEndMarker ? 1 : 0); + const token = state.push('fence', 'code', 0); + token.info = params; + token.content = state.getLines(startLine + 1, nextLine, len, true); + token.markup = markup; + token.map = [startLine, state.line]; + return true; + } + + // Block quotes + + function blockquote(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + const oldLineMax = state.lineMax; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + + // check the block quote marker + if (state.src.charCodeAt(pos) !== 0x3E /* > */) { + return false; + } + + // we know that it's going to be a valid blockquote, + // so no point trying to find the end of it in silent mode + if (silent) { + return true; + } + const oldBMarks = []; + const oldBSCount = []; + const oldSCount = []; + const oldTShift = []; + const terminatorRules = state.md.block.ruler.getRules('blockquote'); + const oldParentType = state.parentType; + state.parentType = 'blockquote'; + let lastLineEmpty = false; + let nextLine; + + // Search the end of the block + // + // Block ends with either: + // 1. an empty line outside: + // ``` + // > test + // + // ``` + // 2. an empty line inside: + // ``` + // > + // test + // ``` + // 3. another tag: + // ``` + // > test + // - - - + // ``` + for (nextLine = startLine; nextLine < endLine; nextLine++) { + // check if it's outdented, i.e. it's inside list item and indented + // less than said list item: + // + // ``` + // 1. anything + // > current blockquote + // 2. checking this line + // ``` + const isOutdented = state.sCount[nextLine] < state.blkIndent; + pos = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + if (pos >= max) { + // Case 1: line is not inside the blockquote, and this line is empty. + break; + } + if (state.src.charCodeAt(pos++) === 0x3E /* > */ && !isOutdented) { + // This line is inside the blockquote. + + // set offset past spaces and ">" + let initial = state.sCount[nextLine] + 1; + let spaceAfterMarker; + let adjustTab; + + // skip one optional space after '>' + if (state.src.charCodeAt(pos) === 0x20 /* space */) { + // ' > test ' + // ^ -- position start of line here: + pos++; + initial++; + adjustTab = false; + spaceAfterMarker = true; + } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { + spaceAfterMarker = true; + if ((state.bsCount[nextLine] + initial) % 4 === 3) { + // ' >\t test ' + // ^ -- position start of line here (tab has width===1) + pos++; + initial++; + adjustTab = false; + } else { + // ' >\t test ' + // ^ -- position start of line here + shift bsCount slightly + // to make extra space appear + adjustTab = true; + } + } else { + spaceAfterMarker = false; } - function focusIn( - container, - focus, - { sorted = true, relativeTo = null, skipElements = [] } = {} - ) { - let ownerDocument = Array.isArray(container) - ? container.length > 0 - ? container[0].ownerDocument - : document - : container.ownerDocument; - let elements = Array.isArray(container) - ? sorted - ? sortByDomNode(container) - : container - : getFocusableElements(container); - if (skipElements.length > 0 && elements.length > 1) { - elements = elements.filter((x) => !skipElements.includes(x)); - } - relativeTo = - relativeTo != null ? relativeTo : ownerDocument.activeElement; - let direction = (() => { - if (focus & (1 /* First */ | 4) /* Next */) return 1 /* Next */; - if (focus & (2 /* Previous */ | 8) /* Last */) - return -1 /* Previous */; - throw new Error( - "Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last" - ); - })(); - let startIndex = (() => { - if (focus & 1 /* First */) return 0; - if (focus & 2 /* Previous */) - return Math.max(0, elements.indexOf(relativeTo)) - 1; - if (focus & 4 /* Next */) - return Math.max(0, elements.indexOf(relativeTo)) + 1; - if (focus & 8 /* Last */) return elements.length - 1; - throw new Error( - "Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last" - ); - })(); - let focusOptions = - focus & 32 /* NoScroll */ ? { preventScroll: true } : {}; - let offset = 0; - let total = elements.length; - let next = void 0; - do { - if (offset >= total || offset + total <= 0) return 0 /* Error */; - let nextIdx = startIndex + offset; - if (focus & 16 /* WrapAround */) { - nextIdx = (nextIdx + total) % total; + let offset = initial; + oldBMarks.push(state.bMarks[nextLine]); + state.bMarks[nextLine] = pos; + while (pos < max) { + const ch = state.src.charCodeAt(pos); + if (isSpace(ch)) { + if (ch === 0x09) { + offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4; } else { - if (nextIdx < 0) return 3 /* Underflow */; - if (nextIdx >= total) return 1 /* Overflow */; + offset++; } - next = elements[nextIdx]; - next == null ? void 0 : next.focus(focusOptions); - offset += direction; - } while (next !== ownerDocument.activeElement); - if ( - focus & (4 /* Next */ | 2) /* Previous */ && - isSelectableElement(next) - ) { - next.select(); + } else { + break; } - return 2 /* Success */; + pos++; } - - // src/hooks/use-document-event.ts - var import_react8 = __webpack_require__(/*! react */ "react"); - function useDocumentEvent(type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react8.useEffect)(() => { - function handler(event) { - listenerRef.current(event); - } - document.addEventListener(type, handler, options); - return () => document.removeEventListener(type, handler, options); - }, [type, options]); + lastLineEmpty = pos >= max; + oldBSCount.push(state.bsCount[nextLine]); + state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); + oldSCount.push(state.sCount[nextLine]); + state.sCount[nextLine] = offset - initial; + oldTShift.push(state.tShift[nextLine]); + state.tShift[nextLine] = pos - state.bMarks[nextLine]; + continue; + } + + // Case 2: line is not inside the blockquote, and the last line was empty. + if (lastLineEmpty) { + break; + } + + // Case 3: another tag found. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; } - - // src/hooks/use-window-event.ts - var import_react9 = __webpack_require__(/*! react */ "react"); - function useWindowEvent(type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react9.useEffect)(() => { - function handler(event) { - listenerRef.current(event); - } - window.addEventListener(type, handler, options); - return () => window.removeEventListener(type, handler, options); - }, [type, options]); + } + if (terminate) { + // Quirk to enforce "hard termination mode" for paragraphs; + // normally if you call `tokenize(state, startLine, nextLine)`, + // paragraphs will look below nextLine for paragraph continuation, + // but if blockquote is terminated by another tag, they shouldn't + state.lineMax = nextLine; + if (state.blkIndent !== 0) { + // state.blkIndent was non-zero, we now set it to zero, + // so we need to re-calculate all offsets to appear as + // if indent wasn't changed + oldBMarks.push(state.bMarks[nextLine]); + oldBSCount.push(state.bsCount[nextLine]); + oldTShift.push(state.tShift[nextLine]); + oldSCount.push(state.sCount[nextLine]); + state.sCount[nextLine] -= state.blkIndent; + } + break; + } + oldBMarks.push(state.bMarks[nextLine]); + oldBSCount.push(state.bsCount[nextLine]); + oldTShift.push(state.tShift[nextLine]); + oldSCount.push(state.sCount[nextLine]); + + // A negative indentation means that this is a paragraph continuation + // + state.sCount[nextLine] = -1; + } + const oldIndent = state.blkIndent; + state.blkIndent = 0; + const token_o = state.push('blockquote_open', 'blockquote', 1); + token_o.markup = '>'; + const lines = [startLine, 0]; + token_o.map = lines; + state.md.block.tokenize(state, startLine, nextLine); + const token_c = state.push('blockquote_close', 'blockquote', -1); + token_c.markup = '>'; + state.lineMax = oldLineMax; + state.parentType = oldParentType; + lines[1] = state.line; + + // Restore original tShift; this might not be necessary since the parser + // has already been here, but just to make sure we can do that. + for (let i = 0; i < oldTShift.length; i++) { + state.bMarks[i + startLine] = oldBMarks[i]; + state.tShift[i + startLine] = oldTShift[i]; + state.sCount[i + startLine] = oldSCount[i]; + state.bsCount[i + startLine] = oldBSCount[i]; + } + state.blkIndent = oldIndent; + return true; + } + + // Horizontal rule + + function hr(state, startLine, endLine, silent) { + const max = state.eMarks[startLine]; + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + let pos = state.bMarks[startLine] + state.tShift[startLine]; + const marker = state.src.charCodeAt(pos++); + + // Check hr marker + if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x5F /* _ */) { + return false; + } + + // markers can be mixed with spaces, but there should be at least 3 of them + + let cnt = 1; + while (pos < max) { + const ch = state.src.charCodeAt(pos++); + if (ch !== marker && !isSpace(ch)) { + return false; + } + if (ch === marker) { + cnt++; + } + } + if (cnt < 3) { + return false; + } + if (silent) { + return true; + } + state.line = startLine + 1; + const token = state.push('hr', 'hr', 0); + token.map = [startLine, state.line]; + token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); + return true; + } + + // Lists + + // Search `[-+*][\n ]`, returns next pos after marker on success + // or -1 on fail. + function skipBulletListMarker(state, startLine) { + const max = state.eMarks[startLine]; + let pos = state.bMarks[startLine] + state.tShift[startLine]; + const marker = state.src.charCodeAt(pos++); + // Check bullet + if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x2B /* + */) { + return -1; + } + if (pos < max) { + const ch = state.src.charCodeAt(pos); + if (!isSpace(ch)) { + // " -test " - is not a list item + return -1; + } + } + return pos; + } + + // Search `\d+[.)][\n ]`, returns next pos after marker on success + // or -1 on fail. + function skipOrderedListMarker(state, startLine) { + const start = state.bMarks[startLine] + state.tShift[startLine]; + const max = state.eMarks[startLine]; + let pos = start; + + // List marker should have at least 2 chars (digit + dot) + if (pos + 1 >= max) { + return -1; + } + let ch = state.src.charCodeAt(pos++); + if (ch < 0x30 /* 0 */ || ch > 0x39 /* 9 */) { + return -1; + } + for (;;) { + // EOL -> fail + if (pos >= max) { + return -1; + } + ch = state.src.charCodeAt(pos++); + if (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) { + // List marker should have no more than 9 digits + // (prevents integer overflow in browsers) + if (pos - start >= 10) { + return -1; } - - // src/hooks/use-outside-click.ts - function useOutsideClick(containers, cb, enabled = true) { - let enabledRef = (0, import_react10.useRef)(false); - (0, import_react10.useEffect)( - false - ? 0 - : () => { - requestAnimationFrame(() => { - enabledRef.current = enabled; - }); - }, - [enabled] - ); - function handleOutsideClick(event, resolveTarget) { - if (!enabledRef.current) return; - if (event.defaultPrevented) return; - let target = resolveTarget(event); - if (target === null) { - return; - } - if (!target.getRootNode().contains(target)) return; - let _containers = (function resolve(containers2) { - if (typeof containers2 === "function") { - return resolve(containers2()); - } - if (Array.isArray(containers2)) { - return containers2; - } - if (containers2 instanceof Set) { - return containers2; - } - return [containers2]; - })(containers); - for (let container of _containers) { - if (container === null) continue; - let domNode = - container instanceof HTMLElement - ? container - : container.current; - if (domNode == null ? void 0 : domNode.contains(target)) { - return; - } - if (event.composed && event.composedPath().includes(domNode)) { - return; - } - } - if ( - // This check alllows us to know whether or not we clicked on a "focusable" element like a - // button or an input. This is a backwards compatibility check so that you can open a and click on another which should close Menu A and open Menu B. We might - // revisit that so that you will require 2 clicks instead. - !isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1} to make it - // unfocusable via the keyboard so that tabbing to the next item from the input doesn't - // first go to the button. - target.tabIndex !== -1 - ) { - event.preventDefault(); - } - return cb(event, target); - } - let initialClickTarget = (0, import_react10.useRef)(null); - useDocumentEvent( - "mousedown", - (event) => { - var _a3, _b; - if (enabledRef.current) { - initialClickTarget.current = - ((_b = - (_a3 = event.composedPath) == null - ? void 0 - : _a3.call(event)) == null - ? void 0 - : _b[0]) || event.target; - } - }, - true - ); - useDocumentEvent( - "click", - (event) => { - if (!initialClickTarget.current) { - return; - } - handleOutsideClick(event, () => { - return initialClickTarget.current; - }); - initialClickTarget.current = null; - }, - // We will use the `capture` phase so that layers in between with `event.stopPropagation()` - // don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu` - // is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However, - // the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this. - true - ); - useWindowEvent( - "blur", - (event) => - handleOutsideClick(event, () => - window.document.activeElement instanceof HTMLIFrameElement - ? window.document.activeElement - : null - ), - true - ); + continue; + } + + // found valid marker + if (ch === 0x29 /* ) */ || ch === 0x2e /* . */) { + break; + } + return -1; + } + if (pos < max) { + ch = state.src.charCodeAt(pos); + if (!isSpace(ch)) { + // " 1.test " - is not a list item + return -1; + } + } + return pos; + } + function markTightParagraphs(state, idx) { + const level = state.level + 2; + for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) { + if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') { + state.tokens[i + 2].hidden = true; + state.tokens[i].hidden = true; + i += 2; + } + } + } + function list(state, startLine, endLine, silent) { + let max, pos, start, token; + let nextLine = startLine; + let tight = true; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + return false; + } + + // Special case: + // - item 1 + // - item 2 + // - item 3 + // - item 4 + // - this one is a paragraph continuation + if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) { + return false; + } + let isTerminatingParagraph = false; + + // limit conditions when list can interrupt + // a paragraph (validation mode only) + if (silent && state.parentType === 'paragraph') { + // Next list item should still terminate previous list item; + // + // This code can fail if plugins use blkIndent as well as lists, + // but I hope the spec gets fixed long before that happens. + // + if (state.sCount[nextLine] >= state.blkIndent) { + isTerminatingParagraph = true; + } + } + + // Detect list type and position after marker + let isOrdered; + let markerValue; + let posAfterMarker; + if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) { + isOrdered = true; + start = state.bMarks[nextLine] + state.tShift[nextLine]; + markerValue = Number(state.src.slice(start, posAfterMarker - 1)); + + // If we're starting a new ordered list right after + // a paragraph, it should start with 1. + if (isTerminatingParagraph && markerValue !== 1) return false; + } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) { + isOrdered = false; + } else { + return false; + } + + // If we're starting a new unordered list right after + // a paragraph, first line should not be empty. + if (isTerminatingParagraph) { + if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false; + } + + // For validation mode we can terminate immediately + if (silent) { + return true; + } + + // We should terminate list on style change. Remember first one to compare. + const markerCharCode = state.src.charCodeAt(posAfterMarker - 1); + + // Start list + const listTokIdx = state.tokens.length; + if (isOrdered) { + token = state.push('ordered_list_open', 'ol', 1); + if (markerValue !== 1) { + token.attrs = [['start', markerValue]]; + } + } else { + token = state.push('bullet_list_open', 'ul', 1); + } + const listLines = [nextLine, 0]; + token.map = listLines; + token.markup = String.fromCharCode(markerCharCode); + + // + // Iterate list items + // + + let prevEmptyEnd = false; + const terminatorRules = state.md.block.ruler.getRules('list'); + const oldParentType = state.parentType; + state.parentType = 'list'; + while (nextLine < endLine) { + pos = posAfterMarker; + max = state.eMarks[nextLine]; + const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]); + let offset = initial; + while (pos < max) { + const ch = state.src.charCodeAt(pos); + if (ch === 0x09) { + offset += 4 - (offset + state.bsCount[nextLine]) % 4; + } else if (ch === 0x20) { + offset++; + } else { + break; + } + pos++; + } + const contentStart = pos; + let indentAfterMarker; + if (contentStart >= max) { + // trimming space in "- \n 3" case, indent is 1 here + indentAfterMarker = 1; + } else { + indentAfterMarker = offset - initial; + } + + // If we have more than 4 spaces, the indent is 1 + // (the rest is just indented code block) + if (indentAfterMarker > 4) { + indentAfterMarker = 1; + } + + // " - test" + // ^^^^^ - calculating total length of this thing + const indent = initial + indentAfterMarker; + + // Run subparser & write tokens + token = state.push('list_item_open', 'li', 1); + token.markup = String.fromCharCode(markerCharCode); + const itemLines = [nextLine, 0]; + token.map = itemLines; + if (isOrdered) { + token.info = state.src.slice(start, posAfterMarker - 1); + } + + // change current state, then restore it after parser subcall + const oldTight = state.tight; + const oldTShift = state.tShift[nextLine]; + const oldSCount = state.sCount[nextLine]; + + // - example list + // ^ listIndent position will be here + // ^ blkIndent position will be here + // + const oldListIndent = state.listIndent; + state.listIndent = state.blkIndent; + state.blkIndent = indent; + state.tight = true; + state.tShift[nextLine] = contentStart - state.bMarks[nextLine]; + state.sCount[nextLine] = offset; + if (contentStart >= max && state.isEmpty(nextLine + 1)) { + // workaround for this case + // (list item is empty, list terminates before "foo"): + // ~~~~~~~~ + // - + // + // foo + // ~~~~~~~~ + state.line = Math.min(state.line + 2, endLine); + } else { + state.md.block.tokenize(state, nextLine, endLine, true); + } + + // If any of list item is tight, mark list as tight + if (!state.tight || prevEmptyEnd) { + tight = false; + } + // Item become loose if finish with empty line, + // but we should filter last element, because it means list finish + prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1); + state.blkIndent = state.listIndent; + state.listIndent = oldListIndent; + state.tShift[nextLine] = oldTShift; + state.sCount[nextLine] = oldSCount; + state.tight = oldTight; + token = state.push('list_item_close', 'li', -1); + token.markup = String.fromCharCode(markerCharCode); + nextLine = state.line; + itemLines[1] = nextLine; + if (nextLine >= endLine) { + break; + } + + // + // Try to check if list is terminated or continued. + // + if (state.sCount[nextLine] < state.blkIndent) { + break; + } + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + break; + } + + // fail if terminating block found + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + break; + } + + // fail if list has another type + if (isOrdered) { + posAfterMarker = skipOrderedListMarker(state, nextLine); + if (posAfterMarker < 0) { + break; + } + start = state.bMarks[nextLine] + state.tShift[nextLine]; + } else { + posAfterMarker = skipBulletListMarker(state, nextLine); + if (posAfterMarker < 0) { + break; + } + } + if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { + break; + } + } + + // Finalize list + if (isOrdered) { + token = state.push('ordered_list_close', 'ol', -1); + } else { + token = state.push('bullet_list_close', 'ul', -1); + } + token.markup = String.fromCharCode(markerCharCode); + listLines[1] = nextLine; + state.line = nextLine; + state.parentType = oldParentType; + + // mark paragraphs tight if needed + if (tight) { + markTightParagraphs(state, listTokIdx); + } + return true; + } + function reference(state, startLine, _endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + let nextLine = startLine + 1; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (state.src.charCodeAt(pos) !== 0x5B /* [ */) { + return false; + } + function getNextLine(nextLine) { + const endLine = state.lineMax; + if (nextLine >= endLine || state.isEmpty(nextLine)) { + // empty line or end of input + return null; + } + let isContinuation = false; + + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + isContinuation = true; + } + + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + isContinuation = true; + } + if (!isContinuation) { + const terminatorRules = state.md.block.ruler.getRules('reference'); + const oldParentType = state.parentType; + state.parentType = 'reference'; + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } } - - // src/hooks/use-resolve-button-type.ts - var import_react11 = __webpack_require__(/*! react */ "react"); - function resolveType(props) { - var _a3; - if (props.type) return props.type; - let tag = (_a3 = props.as) != null ? _a3 : "button"; - if (typeof tag === "string" && tag.toLowerCase() === "button") - return "button"; - return void 0; - } - function useResolveButtonType(props, ref) { - let [type, setType] = (0, import_react11.useState)(() => - resolveType(props) - ); - useIsoMorphicEffect(() => { - setType(resolveType(props)); - }, [props.type, props.as]); - useIsoMorphicEffect(() => { - if (type) return; - if (!ref.current) return; - if ( - ref.current instanceof HTMLButtonElement && - !ref.current.hasAttribute("type") - ) { - setType("button"); - } - }, [type, ref]); - return type; + state.parentType = oldParentType; + if (terminate) { + // terminated by another block + return null; } - - // src/hooks/use-sync-refs.ts - var import_react12 = __webpack_require__(/*! react */ "react"); - var Optional = Symbol(); - function optionalRef(cb, isOptional = true) { - return Object.assign(cb, { [Optional]: isOptional }); - } - function useSyncRefs(...refs) { - let cache = (0, import_react12.useRef)(refs); - (0, import_react12.useEffect)(() => { - cache.current = refs; - }, [refs]); - let syncRefs = useEvent((value) => { - for (let ref of cache.current) { - if (ref == null) continue; - if (typeof ref === "function") ref(value); - else ref.current = value; - } - }); - return refs.every( - (ref) => - ref == null || // @ts-expect-error - (ref == null ? void 0 : ref[Optional]) - ) - ? void 0 - : syncRefs; + } + const pos = state.bMarks[nextLine] + state.tShift[nextLine]; + const max = state.eMarks[nextLine]; + + // max + 1 explicitly includes the newline + return state.src.slice(pos, max + 1); + } + let str = state.src.slice(pos, max + 1); + max = str.length; + let labelEnd = -1; + for (pos = 1; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x5B /* [ */) { + return false; + } else if (ch === 0x5D /* ] */) { + labelEnd = pos; + break; + } else if (ch === 0x0A /* \n */) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; } - - // src/hooks/use-tree-walker.ts - var import_react13 = __webpack_require__(/*! react */ "react"); - function useTreeWalker({ container, accept, walk, enabled = true }) { - let acceptRef = (0, import_react13.useRef)(accept); - let walkRef = (0, import_react13.useRef)(walk); - (0, import_react13.useEffect)(() => { - acceptRef.current = accept; - walkRef.current = walk; - }, [accept, walk]); - useIsoMorphicEffect(() => { - if (!container) return; - if (!enabled) return; - let ownerDocument = getOwnerDocument(container); - if (!ownerDocument) return; - let accept2 = acceptRef.current; - let walk2 = walkRef.current; - let acceptNode = Object.assign((node) => accept2(node), { - acceptNode: accept2, - }); - let walker = ownerDocument.createTreeWalker( - container, - NodeFilter.SHOW_ELEMENT, - acceptNode, - // @ts-expect-error This `false` is a simple small fix for older browsers - false - ); - while (walker.nextNode()) walk2(walker.currentNode); - }, [container, enabled, acceptRef, walkRef]); + } else if (ch === 0x5C /* \ */) { + pos++; + if (pos < max && str.charCodeAt(pos) === 0x0A) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } } - - // src/utils/calculate-active-index.ts - function assertNever(x) { - throw new Error("Unexpected object: " + x); - } - function calculateActiveIndex(action, resolvers) { - let items = resolvers.resolveItems(); - if (items.length <= 0) return null; - let currentActiveIndex = resolvers.resolveActiveIndex(); - let activeIndex = - currentActiveIndex != null ? currentActiveIndex : -1; - let nextActiveIndex = (() => { - switch (action.focus) { - case 0 /* First */: - return items.findIndex( - (item) => !resolvers.resolveDisabled(item) - ); - case 1 /* Previous */: { - let idx = items - .slice() - .reverse() - .findIndex((item, idx2, all) => { - if ( - activeIndex !== -1 && - all.length - idx2 - 1 >= activeIndex - ) - return false; - return !resolvers.resolveDisabled(item); - }); - if (idx === -1) return idx; - return items.length - 1 - idx; - } - case 2 /* Next */: - return items.findIndex((item, idx) => { - if (idx <= activeIndex) return false; - return !resolvers.resolveDisabled(item); - }); - case 3 /* Last */: { - let idx = items - .slice() - .reverse() - .findIndex((item) => !resolvers.resolveDisabled(item)); - if (idx === -1) return idx; - return items.length - 1 - idx; - } - case 4 /* Specific */: - return items.findIndex( - (item) => resolvers.resolveId(item) === action.id - ); - case 5 /* Nothing */: - return null; - default: - assertNever(action); - } - })(); - return nextActiveIndex === -1 ? currentActiveIndex : nextActiveIndex; + } + } + if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A /* : */) { + return false; + } + + // [label]: destination 'title' + // ^^^ skip optional whitespace here + for (pos = labelEnd + 2; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x0A) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; } - - // src/utils/render.ts - var import_react14 = __webpack_require__(/*! react */ "react"); - - // src/utils/class-names.ts - function classNames(...classes) { - return classes.filter(Boolean).join(" "); + } else if (isSpace(ch)) ;else { + break; + } + } + + // [label]: destination 'title' + // ^^^^^^^^^^^ parse this + const destRes = state.md.helpers.parseLinkDestination(str, pos, max); + if (!destRes.ok) { + return false; + } + const href = state.md.normalizeLink(destRes.str); + if (!state.md.validateLink(href)) { + return false; + } + pos = destRes.pos; + + // save cursor state, we could require to rollback later + const destEndPos = pos; + const destEndLineNo = nextLine; + + // [label]: destination 'title' + // ^^^ skipping those spaces + const start = pos; + for (; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x0A) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; } - - // src/utils/render.ts - function render({ - ourProps, - theirProps, - slot, - defaultTag, - features, - visible = true, - name, - }) { - let props = mergeProps(theirProps, ourProps); - if (visible) return _render(props, slot, defaultTag, name); - let featureFlags = features != null ? features : 0; /* None */ - if (featureFlags & 2 /* Static */) { - let { static: isStatic = false, ...rest } = props; - if (isStatic) return _render(rest, slot, defaultTag, name); - } - if (featureFlags & 1 /* RenderStrategy */) { - let { unmount = true, ...rest } = props; - let strategy = unmount ? 0 /* Unmount */ : 1; /* Hidden */ - return match(strategy, { - [0 /* Unmount */]() { - return null; - }, - [1 /* Hidden */]() { - return _render( - { ...rest, ...{ hidden: true, style: { display: "none" } } }, - slot, - defaultTag, - name - ); - }, - }); + } else if (isSpace(ch)) ;else { + break; + } + } + + // [label]: destination 'title' + // ^^^^^^^ parse this + let titleRes = state.md.helpers.parseLinkTitle(str, pos, max); + while (titleRes.can_continue) { + const lineContent = getNextLine(nextLine); + if (lineContent === null) break; + str += lineContent; + pos = max; + max = str.length; + nextLine++; + titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes); + } + let title; + if (pos < max && start !== pos && titleRes.ok) { + title = titleRes.str; + pos = titleRes.pos; + } else { + title = ''; + pos = destEndPos; + nextLine = destEndLineNo; + } + + // skip trailing spaces until the rest of the line + while (pos < max) { + const ch = str.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } + pos++; + } + if (pos < max && str.charCodeAt(pos) !== 0x0A) { + if (title) { + // garbage at the end of the line after title, + // but it could still be a valid reference if we roll back + title = ''; + pos = destEndPos; + nextLine = destEndLineNo; + while (pos < max) { + const ch = str.charCodeAt(pos); + if (!isSpace(ch)) { + break; } - return _render(props, slot, defaultTag, name); + pos++; } - function _render(props, slot = {}, tag, name) { - let { - as: Component = tag, - children, - refName = "ref", - ...rest - } = omit(props, ["unmount", "static"]); - let refRelatedProps = - props.ref !== void 0 ? { [refName]: props.ref } : {}; - let resolvedChildren = - typeof children === "function" ? children(slot) : children; - if ( - "className" in rest && - rest.className && - typeof rest.className === "function" - ) { - rest.className = rest.className(slot); - } - let dataAttributes = {}; - if (slot) { - let exposeState = false; - let states = []; - for (let [k, v] of Object.entries(slot)) { - if (typeof v === "boolean") { - exposeState = true; - } - if (v === true) { - states.push(k); - } - } - if (exposeState) - dataAttributes[`data-headlessui-state`] = states.join(" "); - } - if (Component === import_react14.Fragment) { - if (Object.keys(compact(rest)).length > 0) { - if ( - !(0, import_react14.isValidElement)(resolvedChildren) || - (Array.isArray(resolvedChildren) && resolvedChildren.length > 1) - ) { - throw new Error( - [ - 'Passing props on "Fragment"!', - "", - `The current component <${name} /> is rendering a "Fragment".`, - `However we need to passthrough the following props:`, - Object.keys(rest) - .map((line) => ` - ${line}`) - .join("\n"), - "", - "You can apply a few solutions:", - [ - 'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', - "Render a single element as the child so that we can forward the props onto that element.", - ] - .map((line) => ` - ${line}`) - .join("\n"), - ].join("\n") - ); - } - let childProps = resolvedChildren.props; - let newClassName = - typeof (childProps == null ? void 0 : childProps.className) === - "function" - ? (...args) => - classNames( - childProps == null - ? void 0 - : childProps.className(...args), - rest.className - ) - : classNames( - childProps == null ? void 0 : childProps.className, - rest.className - ); - let classNameProps = newClassName - ? { className: newClassName } - : {}; - return (0, import_react14.cloneElement)( - resolvedChildren, - Object.assign( - {}, - // Filter out undefined values so that they don't override the existing values - mergeProps( - resolvedChildren.props, - compact(omit(rest, ["ref"])) - ), - dataAttributes, - refRelatedProps, - mergeRefs(resolvedChildren.ref, refRelatedProps.ref), - classNameProps - ) - ); - } + } + } + if (pos < max && str.charCodeAt(pos) !== 0x0A) { + // garbage at the end of the line + return false; + } + const label = normalizeReference(str.slice(1, labelEnd)); + if (!label) { + // CommonMark 0.20 disallows empty labels + return false; + } + + // Reference can not terminate anything. This check is for safety only. + /* istanbul ignore if */ + if (silent) { + return true; + } + if (typeof state.env.references === 'undefined') { + state.env.references = {}; + } + if (typeof state.env.references[label] === 'undefined') { + state.env.references[label] = { + title, + href + }; + } + state.line = nextLine; + return true; + } + + // List of valid html blocks names, according to commonmark spec + // https://spec.commonmark.org/0.30/#html-blocks + + var block_names = ['address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu', 'menuitem', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'search', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul']; + + // Regexps to match html elements + + const attr_name = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; + const unquoted = '[^"\'=<>`\\x00-\\x20]+'; + const single_quoted = "'[^']*'"; + const double_quoted = '"[^"]*"'; + const attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')'; + const attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)'; + const open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; + const close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; + const comment = ''; + const processing = '<[?][\\s\\S]*?[?]>'; + const declaration = ']*>'; + const cdata = ''; + const HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment + '|' + processing + '|' + declaration + '|' + cdata + ')'); + const HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')'); + + // HTML block + + // An array of opening and corresponding closing sequences for html tags, + // last argument defines whether it can terminate a paragraph or not + // + const HTML_SEQUENCES = [[/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true], [/^/, true], [/^<\?/, /\?>/, true], [/^/, true], [/^/, true], [new RegExp('^|$))', 'i'), /^$/, true], [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false]]; + function html_block(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (!state.md.options.html) { + return false; + } + if (state.src.charCodeAt(pos) !== 0x3C /* < */) { + return false; + } + let lineText = state.src.slice(pos, max); + let i = 0; + for (; i < HTML_SEQUENCES.length; i++) { + if (HTML_SEQUENCES[i][0].test(lineText)) { + break; + } + } + if (i === HTML_SEQUENCES.length) { + return false; + } + if (silent) { + // true if this sequence can be a terminator, false otherwise + return HTML_SEQUENCES[i][2]; + } + let nextLine = startLine + 1; + + // If we are here - we detected HTML block. + // Let's roll down till block end. + if (!HTML_SEQUENCES[i][1].test(lineText)) { + for (; nextLine < endLine; nextLine++) { + if (state.sCount[nextLine] < state.blkIndent) { + break; + } + pos = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + lineText = state.src.slice(pos, max); + if (HTML_SEQUENCES[i][1].test(lineText)) { + if (lineText.length !== 0) { + nextLine++; } - return (0, import_react14.createElement)( - Component, - Object.assign( - {}, - omit(rest, ["ref"]), - Component !== import_react14.Fragment && refRelatedProps, - Component !== import_react14.Fragment && dataAttributes - ), - resolvedChildren - ); - } - function mergeRefs(...refs) { - return { - ref: refs.every((ref) => ref == null) - ? void 0 - : (value) => { - for (let ref of refs) { - if (ref == null) continue; - if (typeof ref === "function") ref(value); - else ref.current = value; - } - }, - }; + break; } - function mergeProps(...listOfProps) { - var _a3; - if (listOfProps.length === 0) return {}; - if (listOfProps.length === 1) return listOfProps[0]; - let target = {}; - let eventHandlers = {}; - for (let props of listOfProps) { - for (let prop in props) { - if (prop.startsWith("on") && typeof props[prop] === "function") { - (_a3 = eventHandlers[prop]) != null - ? _a3 - : (eventHandlers[prop] = []); - eventHandlers[prop].push(props[prop]); - } else { - target[prop] = props[prop]; - } + } + } + state.line = nextLine; + const token = state.push('html_block', '', 0); + token.map = [startLine, nextLine]; + token.content = state.getLines(startLine, nextLine, state.blkIndent, true); + return true; + } + + // heading (#, ##, ...) + + function heading(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + let ch = state.src.charCodeAt(pos); + if (ch !== 0x23 /* # */ || pos >= max) { + return false; + } + + // count heading level + let level = 1; + ch = state.src.charCodeAt(++pos); + while (ch === 0x23 /* # */ && pos < max && level <= 6) { + level++; + ch = state.src.charCodeAt(++pos); + } + if (level > 6 || pos < max && !isSpace(ch)) { + return false; + } + if (silent) { + return true; + } + + // Let's cut tails like ' ### ' from the end of string + + max = state.skipSpacesBack(max, pos); + const tmp = state.skipCharsBack(max, 0x23, pos); // # + if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { + max = tmp; + } + state.line = startLine + 1; + const token_o = state.push('heading_open', 'h' + String(level), 1); + token_o.markup = '########'.slice(0, level); + token_o.map = [startLine, state.line]; + const token_i = state.push('inline', '', 0); + token_i.content = state.src.slice(pos, max).trim(); + token_i.map = [startLine, state.line]; + token_i.children = []; + const token_c = state.push('heading_close', 'h' + String(level), -1); + token_c.markup = '########'.slice(0, level); + return true; + } + + // lheading (---, ===) + + function lheading(state, startLine, endLine /*, silent */) { + const terminatorRules = state.md.block.ruler.getRules('paragraph'); + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + const oldParentType = state.parentType; + state.parentType = 'paragraph'; // use paragraph to match terminatorRules + + // jump line-by-line until empty one or EOF + let level = 0; + let marker; + let nextLine = startLine + 1; + for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + continue; + } + + // + // Check for underline in setext header + // + if (state.sCount[nextLine] >= state.blkIndent) { + let pos = state.bMarks[nextLine] + state.tShift[nextLine]; + const max = state.eMarks[nextLine]; + if (pos < max) { + marker = state.src.charCodeAt(pos); + if (marker === 0x2D /* - */ || marker === 0x3D /* = */) { + pos = state.skipChars(pos, marker); + pos = state.skipSpaces(pos); + if (pos >= max) { + level = marker === 0x3D /* = */ ? 1 : 2; + break; } } - if (target.disabled || target["aria-disabled"]) { - return Object.assign( - target, - // Set all event listeners that we collected to `undefined`. This is - // important because of the `cloneElement` from above, which merges the - // existing and new props, they don't just override therefore we have to - // explicitly nullify them. - Object.fromEntries( - Object.keys(eventHandlers).map((eventName) => [ - eventName, - void 0, - ]) - ) - ); - } - for (let eventName in eventHandlers) { - Object.assign(target, { - [eventName](event, ...args) { - let handlers = eventHandlers[eventName]; - for (let handler of handlers) { - if ( - (event instanceof Event || - (event == null ? void 0 : event.nativeEvent) instanceof - Event) && - event.defaultPrevented - ) { - return; - } - handler(event, ...args); - } - }, - }); - } - return target; } - function forwardRefWithAs(component) { - var _a3; - return Object.assign((0, import_react14.forwardRef)(component), { - displayName: - (_a3 = component.displayName) != null ? _a3 : component.name, - }); + } + + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + continue; + } + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; } - function compact(object) { - let clone = Object.assign({}, object); - for (let key in clone) { - if (clone[key] === void 0) delete clone[key]; - } - return clone; + } + if (terminate) { + break; + } + } + if (!level) { + // Didn't find valid underline + return false; + } + const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); + state.line = nextLine + 1; + const token_o = state.push('heading_open', 'h' + String(level), 1); + token_o.markup = String.fromCharCode(marker); + token_o.map = [startLine, state.line]; + const token_i = state.push('inline', '', 0); + token_i.content = content; + token_i.map = [startLine, state.line - 1]; + token_i.children = []; + const token_c = state.push('heading_close', 'h' + String(level), -1); + token_c.markup = String.fromCharCode(marker); + state.parentType = oldParentType; + return true; + } + + // Paragraph + + function paragraph(state, startLine, endLine) { + const terminatorRules = state.md.block.ruler.getRules('paragraph'); + const oldParentType = state.parentType; + let nextLine = startLine + 1; + state.parentType = 'paragraph'; + + // jump line-by-line until empty one or EOF + for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + continue; + } + + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + continue; + } + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } + } + if (terminate) { + break; + } + } + const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); + state.line = nextLine; + const token_o = state.push('paragraph_open', 'p', 1); + token_o.map = [startLine, state.line]; + const token_i = state.push('inline', '', 0); + token_i.content = content; + token_i.map = [startLine, state.line]; + token_i.children = []; + state.push('paragraph_close', 'p', -1); + state.parentType = oldParentType; + return true; + } + + /** internal + * class ParserBlock + * + * Block-level tokenizer. + **/ + + const _rules$1 = [ + // First 2 params - rule name & source. Secondary array - list of rules, + // which can be terminated by this one. + ['table', table, ['paragraph', 'reference']], ['code', code], ['fence', fence, ['paragraph', 'reference', 'blockquote', 'list']], ['blockquote', blockquote, ['paragraph', 'reference', 'blockquote', 'list']], ['hr', hr, ['paragraph', 'reference', 'blockquote', 'list']], ['list', list, ['paragraph', 'reference', 'blockquote']], ['reference', reference], ['html_block', html_block, ['paragraph', 'reference', 'blockquote']], ['heading', heading, ['paragraph', 'reference', 'blockquote']], ['lheading', lheading], ['paragraph', paragraph]]; + + /** + * new ParserBlock() + **/ + function ParserBlock() { + /** + * ParserBlock#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of block rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules$1.length; i++) { + this.ruler.push(_rules$1[i][0], _rules$1[i][1], { + alt: (_rules$1[i][2] || []).slice() + }); + } + } + + // Generate tokens for input range + // + ParserBlock.prototype.tokenize = function (state, startLine, endLine) { + const rules = this.ruler.getRules(''); + const len = rules.length; + const maxNesting = state.md.options.maxNesting; + let line = startLine; + let hasEmptyLines = false; + while (line < endLine) { + state.line = line = state.skipEmptyLines(line); + if (line >= endLine) { + break; + } + + // Termination condition for nested calls. + // Nested calls currently used for blockquotes & lists + if (state.sCount[line] < state.blkIndent) { + break; + } + + // If nesting level exceeded - skip tail to the end. That's not ordinary + // situation and we should not care about content. + if (state.level >= maxNesting) { + state.line = endLine; + break; + } + + // Try all possible rules. + // On success, rule should: + // + // - update `state.line` + // - update `state.tokens` + // - return true + const prevLine = state.line; + let ok = false; + for (let i = 0; i < len; i++) { + ok = rules[i](state, line, endLine, false); + if (ok) { + if (prevLine >= state.line) { + throw new Error("block rule didn't increment state.line"); + } + break; + } + } + + // this can only happen if user disables paragraph rule + if (!ok) throw new Error('none of the block rules matched'); + + // set state.tight if we had an empty line before current tag + // i.e. latest empty line should not count + state.tight = !hasEmptyLines; + + // paragraph might "eat" one newline after it in nested lists + if (state.isEmpty(state.line - 1)) { + hasEmptyLines = true; + } + line = state.line; + if (line < endLine && state.isEmpty(line)) { + hasEmptyLines = true; + line++; + state.line = line; + } + } + }; + + /** + * ParserBlock.parse(str, md, env, outTokens) + * + * Process input string and push block tokens into `outTokens` + **/ + ParserBlock.prototype.parse = function (src, md, env, outTokens) { + if (!src) { + return; + } + const state = new this.State(src, md, env, outTokens); + this.tokenize(state, state.line, state.lineMax); + }; + ParserBlock.prototype.State = StateBlock; + + // Inline parser state + + function StateInline(src, md, env, outTokens) { + this.src = src; + this.env = env; + this.md = md; + this.tokens = outTokens; + this.tokens_meta = Array(outTokens.length); + this.pos = 0; + this.posMax = this.src.length; + this.level = 0; + this.pending = ''; + this.pendingLevel = 0; + + // Stores { start: end } pairs. Useful for backtrack + // optimization of pairs parse (emphasis, strikes). + this.cache = {}; + + // List of emphasis-like delimiters for current tag + this.delimiters = []; + + // Stack of delimiter lists for upper level tags + this._prev_delimiters = []; + + // backtick length => last seen position + this.backticks = {}; + this.backticksScanned = false; + + // Counter used to disable inline linkify-it execution + // inside and markdown links + this.linkLevel = 0; + } + + // Flush pending text + // + StateInline.prototype.pushPending = function () { + const token = new Token('text', '', 0); + token.content = this.pending; + token.level = this.pendingLevel; + this.tokens.push(token); + this.pending = ''; + return token; + }; + + // Push new token to "stream". + // If pending text exists - flush it as text token + // + StateInline.prototype.push = function (type, tag, nesting) { + if (this.pending) { + this.pushPending(); + } + const token = new Token(type, tag, nesting); + let token_meta = null; + if (nesting < 0) { + // closing tag + this.level--; + this.delimiters = this._prev_delimiters.pop(); + } + token.level = this.level; + if (nesting > 0) { + // opening tag + this.level++; + this._prev_delimiters.push(this.delimiters); + this.delimiters = []; + token_meta = { + delimiters: this.delimiters + }; + } + this.pendingLevel = this.level; + this.tokens.push(token); + this.tokens_meta.push(token_meta); + return token; + }; + + // Scan a sequence of emphasis-like markers, and determine whether + // it can start an emphasis sequence or end an emphasis sequence. + // + // - start - position to scan from (it should point at a valid marker); + // - canSplitWord - determine if these markers can be found inside a word + // + StateInline.prototype.scanDelims = function (start, canSplitWord) { + const max = this.posMax; + const marker = this.src.charCodeAt(start); + + // treat beginning of the line as a whitespace + const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; + let pos = start; + while (pos < max && this.src.charCodeAt(pos) === marker) { + pos++; + } + const count = pos - start; + + // treat end of the line as a whitespace + const nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; + const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); + const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); + const isLastWhiteSpace = isWhiteSpace(lastChar); + const isNextWhiteSpace = isWhiteSpace(nextChar); + const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar); + const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar); + const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar); + const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar); + return { + can_open, + can_close, + length: count + }; + }; + + // re-export Token class to use in block rules + StateInline.prototype.Token = Token; + + // Skip text characters for text token, place those to pending buffer + // and increment current pos + + // Rule to skip pure text + // '{}$%@~+=:' reserved for extentions + + // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ + + // !!!! Don't confuse with "Markdown ASCII Punctuation" chars + // http://spec.commonmark.org/0.15/#ascii-punctuation-character + function isTerminatorChar(ch) { + switch (ch) { + case 0x0A /* \n */: + case 0x21 /* ! */: + case 0x23 /* # */: + case 0x24 /* $ */: + case 0x25 /* % */: + case 0x26 /* & */: + case 0x2A /* * */: + case 0x2B /* + */: + case 0x2D /* - */: + case 0x3A /* : */: + case 0x3C /* < */: + case 0x3D /* = */: + case 0x3E /* > */: + case 0x40 /* @ */: + case 0x5B /* [ */: + case 0x5C /* \ */: + case 0x5D /* ] */: + case 0x5E /* ^ */: + case 0x5F /* _ */: + case 0x60 /* ` */: + case 0x7B /* { */: + case 0x7D /* } */: + case 0x7E /* ~ */: + return true; + default: + return false; + } + } + function text(state, silent) { + let pos = state.pos; + while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) { + pos++; + } + if (pos === state.pos) { + return false; + } + if (!silent) { + state.pending += state.src.slice(state.pos, pos); + } + state.pos = pos; + return true; + } + + // Alternative implementation, for memory. + // + // It costs 10% of performance, but allows extend terminators list, if place it + // to `ParserInline` property. Probably, will switch to it sometime, such + // flexibility required. + + /* + var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; + + module.exports = function text(state, silent) { + var pos = state.pos, + idx = state.src.slice(pos).search(TERMINATOR_RE); + + // first char is terminator -> empty text + if (idx === 0) { return false; } + + // no terminator -> text till end of string + if (idx < 0) { + if (!silent) { state.pending += state.src.slice(pos); } + state.pos = state.src.length; + return true; + } + + if (!silent) { state.pending += state.src.slice(pos, pos + idx); } + + state.pos += idx; + + return true; + }; */ + + // Process links like https://example.org/ + + // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; + function linkify(state, silent) { + if (!state.md.options.linkify) return false; + if (state.linkLevel > 0) return false; + const pos = state.pos; + const max = state.posMax; + if (pos + 3 > max) return false; + if (state.src.charCodeAt(pos) !== 0x3A /* : */) return false; + if (state.src.charCodeAt(pos + 1) !== 0x2F /* / */) return false; + if (state.src.charCodeAt(pos + 2) !== 0x2F /* / */) return false; + const match = state.pending.match(SCHEME_RE); + if (!match) return false; + const proto = match[1]; + const link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length)); + if (!link) return false; + let url = link.url; + + // invalid link, but still detected by linkify somehow; + // need to check to prevent infinite loop below + if (url.length <= proto.length) return false; + + // disallow '*' at the end of the link (conflicts with emphasis) + url = url.replace(/\*+$/, ''); + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) return false; + if (!silent) { + state.pending = state.pending.slice(0, -proto.length); + const token_o = state.push('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.markup = 'linkify'; + token_o.info = 'auto'; + const token_t = state.push('text', '', 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push('link_close', 'a', -1); + token_c.markup = 'linkify'; + token_c.info = 'auto'; + } + state.pos += url.length - proto.length; + return true; + } + + // Proceess '\n' + + function newline(state, silent) { + let pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x0A /* \n */) { + return false; + } + const pmax = state.pending.length - 1; + const max = state.posMax; + + // ' \n' -> hardbreak + // Lookup in pending chars is bad practice! Don't copy to other rules! + // Pending string is stored in concat mode, indexed lookups will cause + // convertion to flat mode. + if (!silent) { + if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { + if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { + // Find whitespaces tail of pending chars. + let ws = pmax - 1; + while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) ws--; + state.pending = state.pending.slice(0, ws); + state.push('hardbreak', 'br', 0); + } else { + state.pending = state.pending.slice(0, -1); + state.push('softbreak', 'br', 0); } - function omit(object, keysToOmit = []) { - let clone = Object.assign({}, object); - for (let key of keysToOmit) { - if (key in clone) delete clone[key]; - } - return clone; + } else { + state.push('softbreak', 'br', 0); + } + } + pos++; + + // skip heading spaces for next line + while (pos < max && isSpace(state.src.charCodeAt(pos))) { + pos++; + } + state.pos = pos; + return true; + } + + // Process escaped chars and hardbreaks + + const ESCAPED = []; + for (let i = 0; i < 256; i++) { + ESCAPED.push(0); + } + '\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'.split('').forEach(function (ch) { + ESCAPED[ch.charCodeAt(0)] = 1; + }); + function escape(state, silent) { + let pos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(pos) !== 0x5C /* \ */) return false; + pos++; + + // '\' at the end of the inline block + if (pos >= max) return false; + let ch1 = state.src.charCodeAt(pos); + if (ch1 === 0x0A) { + if (!silent) { + state.push('hardbreak', 'br', 0); + } + pos++; + // skip leading whitespaces from next line + while (pos < max) { + ch1 = state.src.charCodeAt(pos); + if (!isSpace(ch1)) break; + pos++; + } + state.pos = pos; + return true; + } + let escapedStr = state.src[pos]; + if (ch1 >= 0xD800 && ch1 <= 0xDBFF && pos + 1 < max) { + const ch2 = state.src.charCodeAt(pos + 1); + if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { + escapedStr += state.src[pos + 1]; + pos++; + } + } + const origStr = '\\' + escapedStr; + if (!silent) { + const token = state.push('text_special', '', 0); + if (ch1 < 256 && ESCAPED[ch1] !== 0) { + token.content = escapedStr; + } else { + token.content = origStr; + } + token.markup = origStr; + token.info = 'escape'; + } + state.pos = pos + 1; + return true; + } + + // Parse backticks + + function backtick(state, silent) { + let pos = state.pos; + const ch = state.src.charCodeAt(pos); + if (ch !== 0x60 /* ` */) { + return false; + } + const start = pos; + pos++; + const max = state.posMax; + + // scan marker length + while (pos < max && state.src.charCodeAt(pos) === 0x60 /* ` */) { + pos++; + } + const marker = state.src.slice(start, pos); + const openerLength = marker.length; + if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) { + if (!silent) state.pending += marker; + state.pos += openerLength; + return true; + } + let matchEnd = pos; + let matchStart; + + // Nothing found in the cache, scan until the end of the line (or until marker is found) + while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { + matchEnd = matchStart + 1; + + // scan marker length + while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60 /* ` */) { + matchEnd++; + } + const closerLength = matchEnd - matchStart; + if (closerLength === openerLength) { + // Found matching closer length. + if (!silent) { + const token = state.push('code_inline', 'code', 0); + token.markup = marker; + token.content = state.src.slice(pos, matchStart).replace(/\n/g, ' ').replace(/^ (.+) $/, '$1'); + } + state.pos = matchEnd; + return true; + } + + // Some different length found, put it in cache as upper limit of where closer can be found + state.backticks[closerLength] = matchStart; + } + + // Scanned through the end, didn't find anything + state.backticksScanned = true; + if (!silent) state.pending += marker; + state.pos += openerLength; + return true; + } + + // ~~strike through~~ + // + + // Insert each marker as a separate text token, and add it to delimiter list + // + function strikethrough_tokenize(state, silent) { + const start = state.pos; + const marker = state.src.charCodeAt(start); + if (silent) { + return false; + } + if (marker !== 0x7E /* ~ */) { + return false; + } + const scanned = state.scanDelims(state.pos, true); + let len = scanned.length; + const ch = String.fromCharCode(marker); + if (len < 2) { + return false; + } + let token; + if (len % 2) { + token = state.push('text', '', 0); + token.content = ch; + len--; + } + for (let i = 0; i < len; i += 2) { + token = state.push('text', '', 0); + token.content = ch + ch; + state.delimiters.push({ + marker, + length: 0, + // disable "rule of 3" length checks meant for emphasis + token: state.tokens.length - 1, + end: -1, + open: scanned.can_open, + close: scanned.can_close + }); + } + state.pos += scanned.length; + return true; + } + function postProcess$1(state, delimiters) { + let token; + const loneMarkers = []; + const max = delimiters.length; + for (let i = 0; i < max; i++) { + const startDelim = delimiters[i]; + if (startDelim.marker !== 0x7E /* ~ */) { + continue; + } + if (startDelim.end === -1) { + continue; + } + const endDelim = delimiters[startDelim.end]; + token = state.tokens[startDelim.token]; + token.type = 's_open'; + token.tag = 's'; + token.nesting = 1; + token.markup = '~~'; + token.content = ''; + token = state.tokens[endDelim.token]; + token.type = 's_close'; + token.tag = 's'; + token.nesting = -1; + token.markup = '~~'; + token.content = ''; + if (state.tokens[endDelim.token - 1].type === 'text' && state.tokens[endDelim.token - 1].content === '~') { + loneMarkers.push(endDelim.token - 1); + } + } + + // If a marker sequence has an odd number of characters, it's splitted + // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the + // start of the sequence. + // + // So, we have to move all those markers after subsequent s_close tags. + // + while (loneMarkers.length) { + const i = loneMarkers.pop(); + let j = i + 1; + while (j < state.tokens.length && state.tokens[j].type === 's_close') { + j++; + } + j--; + if (i !== j) { + token = state.tokens[j]; + state.tokens[j] = state.tokens[i]; + state.tokens[i] = token; + } + } + } + + // Walk through delimiter list and replace text tokens with tags + // + function strikethrough_postProcess(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + postProcess$1(state, state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + postProcess$1(state, tokens_meta[curr].delimiters); + } + } + } + var r_strikethrough = { + tokenize: strikethrough_tokenize, + postProcess: strikethrough_postProcess + }; + + // Process *this* and _that_ + // + + // Insert each marker as a separate text token, and add it to delimiter list + // + function emphasis_tokenize(state, silent) { + const start = state.pos; + const marker = state.src.charCodeAt(start); + if (silent) { + return false; + } + if (marker !== 0x5F /* _ */ && marker !== 0x2A /* * */) { + return false; + } + const scanned = state.scanDelims(state.pos, marker === 0x2A); + for (let i = 0; i < scanned.length; i++) { + const token = state.push('text', '', 0); + token.content = String.fromCharCode(marker); + state.delimiters.push({ + // Char code of the starting marker (number). + // + marker, + // Total length of these series of delimiters. + // + length: scanned.length, + // A position of the token this delimiter corresponds to. + // + token: state.tokens.length - 1, + // If this delimiter is matched as a valid opener, `end` will be + // equal to its position, otherwise it's `-1`. + // + end: -1, + // Boolean flags that determine if this delimiter could open or close + // an emphasis. + // + open: scanned.can_open, + close: scanned.can_close + }); + } + state.pos += scanned.length; + return true; + } + function postProcess(state, delimiters) { + const max = delimiters.length; + for (let i = max - 1; i >= 0; i--) { + const startDelim = delimiters[i]; + if (startDelim.marker !== 0x5F /* _ */ && startDelim.marker !== 0x2A /* * */) { + continue; + } + + // Process only opening markers + if (startDelim.end === -1) { + continue; + } + const endDelim = delimiters[startDelim.end]; + + // If the previous delimiter has the same marker and is adjacent to this one, + // merge those into one strong delimiter. + // + // `whatever` -> `whatever` + // + const isStrong = i > 0 && delimiters[i - 1].end === startDelim.end + 1 && + // check that first two markers match and adjacent + delimiters[i - 1].marker === startDelim.marker && delimiters[i - 1].token === startDelim.token - 1 && + // check that last two markers are adjacent (we can safely assume they match) + delimiters[startDelim.end + 1].token === endDelim.token + 1; + const ch = String.fromCharCode(startDelim.marker); + const token_o = state.tokens[startDelim.token]; + token_o.type = isStrong ? 'strong_open' : 'em_open'; + token_o.tag = isStrong ? 'strong' : 'em'; + token_o.nesting = 1; + token_o.markup = isStrong ? ch + ch : ch; + token_o.content = ''; + const token_c = state.tokens[endDelim.token]; + token_c.type = isStrong ? 'strong_close' : 'em_close'; + token_c.tag = isStrong ? 'strong' : 'em'; + token_c.nesting = -1; + token_c.markup = isStrong ? ch + ch : ch; + token_c.content = ''; + if (isStrong) { + state.tokens[delimiters[i - 1].token].content = ''; + state.tokens[delimiters[startDelim.end + 1].token].content = ''; + i--; + } + } + } + + // Walk through delimiter list and replace text tokens with tags + // + function emphasis_post_process(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + postProcess(state, state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + postProcess(state, tokens_meta[curr].delimiters); + } + } + } + var r_emphasis = { + tokenize: emphasis_tokenize, + postProcess: emphasis_post_process + }; + + // Process [link]( "stuff") + + function link(state, silent) { + let code, label, res, ref; + let href = ''; + let title = ''; + let start = state.pos; + let parseReference = true; + if (state.src.charCodeAt(state.pos) !== 0x5B /* [ */) { + return false; + } + const oldPos = state.pos; + const max = state.posMax; + const labelStart = state.pos + 1; + const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true); + + // parser failed to find ']', so it's not a valid link + if (labelEnd < 0) { + return false; + } + let pos = labelEnd + 1; + if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { + // + // Inline link + // + + // might have found a valid shortcut link, disable reference parsing + parseReference = false; + + // [link]( "title" ) + // ^^ skipping these spaces + pos++; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } - - // src/utils/bugs.ts - function isDisabledReactIssue7711(element) { - let parent = element.parentElement; - let legend = null; - while (parent && !(parent instanceof HTMLFieldSetElement)) { - if (parent instanceof HTMLLegendElement) legend = parent; - parent = parent.parentElement; - } - let isParentDisabled = - (parent == null ? void 0 : parent.getAttribute("disabled")) === ""; - if (isParentDisabled && isFirstLegend(legend)) return false; - return isParentDisabled; - } - function isFirstLegend(element) { - if (!element) return false; - let previous = element.previousElementSibling; - while (previous !== null) { - if (previous instanceof HTMLLegendElement) return false; - previous = previous.previousElementSibling; - } - return true; + } + if (pos >= max) { + return false; + } + + // [link]( "title" ) + // ^^^^^^ parsing link destination + start = pos; + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); + if (res.ok) { + href = state.md.normalizeLink(res.str); + if (state.md.validateLink(href)) { + pos = res.pos; + } else { + href = ''; } - - // src/utils/form.ts - function objectToFormEntries( - source = {}, - parentKey = null, - entries = [] - ) { - for (let [key, value] of Object.entries(source)) { - append(entries, composeKey(parentKey, key), value); - } - return entries; - } - function composeKey(parent, key) { - return parent ? parent + "[" + key + "]" : key; - } - function append(entries, key, value) { - if (Array.isArray(value)) { - for (let [subkey, subvalue] of value.entries()) { - append(entries, composeKey(key, subkey.toString()), subvalue); - } - } else if (value instanceof Date) { - entries.push([key, value.toISOString()]); - } else if (typeof value === "boolean") { - entries.push([key, value ? "1" : "0"]); - } else if (typeof value === "string") { - entries.push([key, value]); - } else if (typeof value === "number") { - entries.push([key, `${value}`]); - } else if (value === null || value === void 0) { - entries.push([key, ""]); - } else { - objectToFormEntries(value, key, entries); + + // [link]( "title" ) + // ^^ skipping these spaces + start = pos; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } } - function attemptSubmit(element) { - var _a3; - let form = - (_a3 = element == null ? void 0 : element.form) != null - ? _a3 - : element.closest("form"); - if (!form) return; - for (let element2 of form.elements) { - if ( - (element2.tagName === "INPUT" && element2.type === "submit") || - (element2.tagName === "BUTTON" && element2.type === "submit") || - (element2.nodeName === "INPUT" && element2.type === "image") - ) { - element2.click(); - return; + + // [link]( "title" ) + // ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); + if (pos < max && start !== pos && res.ok) { + title = res.str; + pos = res.pos; + + // [link]( "title" ) + // ^^ skipping these spaces + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } } } - - // src/internal/hidden.tsx - var DEFAULT_VISUALLY_HIDDEN_TAG = "div"; - function VisuallyHidden(props, ref) { - let { features = 1 /* None */, ...theirProps } = props; - let ourProps = { - ref, - "aria-hidden": - (features & 2) /* Focusable */ === 2 /* Focusable */ - ? true - : void 0, - style: { - position: "fixed", - top: 1, - left: 1, - width: 1, - height: 0, - padding: 0, - margin: -1, - overflow: "hidden", - clip: "rect(0, 0, 0, 0)", - whiteSpace: "nowrap", - borderWidth: "0", - ...((features & 4) /* Hidden */ === 4 /* Hidden */ && - !(((features & 2) /* Focusable */ === 2) /* Focusable */) && { - display: "none", - }), - }, - }; - return render({ - ourProps, - theirProps, - slot: {}, - defaultTag: DEFAULT_VISUALLY_HIDDEN_TAG, - name: "Hidden", - }); - } - var Hidden = forwardRefWithAs(VisuallyHidden); - - // src/internal/open-closed.tsx - var import_react15 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var Context = (0, import_react15.createContext)(null); - Context.displayName = "OpenClosedContext"; - function useOpenClosed() { - return (0, import_react15.useContext)(Context); - } - function OpenClosedProvider({ value, children }) { - return /* @__PURE__ */ import_react15.default.createElement( - Context.Provider, - { value }, - children - ); - } - - // src/hooks/use-controllable.ts - var import_react16 = __webpack_require__(/*! react */ "react"); - function useControllable(controlledValue, onChange, defaultValue) { - let [internalValue, setInternalValue] = (0, import_react16.useState)( - defaultValue - ); - let isControlled = controlledValue !== void 0; - let wasControlled = (0, import_react16.useRef)(isControlled); - let didWarnOnUncontrolledToControlled = (0, import_react16.useRef)( - false - ); - let didWarnOnControlledToUncontrolled = (0, import_react16.useRef)( - false - ); - if ( - isControlled && - !wasControlled.current && - !didWarnOnUncontrolledToControlled.current - ) { - didWarnOnUncontrolledToControlled.current = true; - wasControlled.current = isControlled; - console.error( - "A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen." - ); - } else if ( - !isControlled && - wasControlled.current && - !didWarnOnControlledToUncontrolled.current - ) { - didWarnOnControlledToUncontrolled.current = true; - wasControlled.current = isControlled; - console.error( - "A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen." - ); - } - return [ - isControlled ? controlledValue : internalValue, - useEvent((value) => { - if (isControlled) { - return onChange == null ? void 0 : onChange(value); - } else { - setInternalValue(value); - return onChange == null ? void 0 : onChange(value); - } - }), - ]; - } - - // src/hooks/use-watch.ts - var import_react17 = __webpack_require__(/*! react */ "react"); - function useWatch(cb, dependencies) { - let track = (0, import_react17.useRef)([]); - let action = useEvent(cb); - (0, import_react17.useEffect)(() => { - let oldValues = [...track.current]; - for (let [idx, value] of dependencies.entries()) { - if (track.current[idx] !== value) { - let returnValue = action(dependencies, oldValues); - track.current = dependencies; - return returnValue; - } - } - }, [action, ...dependencies]); + } + if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { + // parsing a valid shortcut link failed, fallback to reference + parseReference = true; + } + pos++; + } + if (parseReference) { + // + // Link reference + // + if (typeof state.env.references === 'undefined') { + return false; + } + if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { + start = pos + 1; + pos = state.md.helpers.parseLinkLabel(state, pos); + if (pos >= 0) { + label = state.src.slice(start, pos++); + } else { + pos = labelEnd + 1; } - - // src/hooks/use-tracked-pointer.ts - var import_react18 = __webpack_require__(/*! react */ "react"); - function eventToPosition(evt) { - return [evt.screenX, evt.screenY]; + } else { + pos = labelEnd + 1; + } + + // covers label === '' and label === undefined + // (collapsed reference link and shortcut reference link respectively) + if (!label) { + label = state.src.slice(labelStart, labelEnd); + } + ref = state.env.references[normalizeReference(label)]; + if (!ref) { + state.pos = oldPos; + return false; + } + href = ref.href; + title = ref.title; + } + + // + // We found the end of the link, and know for a fact it's a valid link; + // so all that's left to do is to call tokenizer. + // + if (!silent) { + state.pos = labelStart; + state.posMax = labelEnd; + const token_o = state.push('link_open', 'a', 1); + const attrs = [['href', href]]; + token_o.attrs = attrs; + if (title) { + attrs.push(['title', title]); + } + state.linkLevel++; + state.md.inline.tokenize(state); + state.linkLevel--; + state.push('link_close', 'a', -1); + } + state.pos = pos; + state.posMax = max; + return true; + } + + // Process ![image]( "title") + + function image(state, silent) { + let code, content, label, pos, ref, res, title, start; + let href = ''; + const oldPos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(state.pos) !== 0x21 /* ! */) { + return false; + } + if (state.src.charCodeAt(state.pos + 1) !== 0x5B /* [ */) { + return false; + } + const labelStart = state.pos + 2; + const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false); + + // parser failed to find ']', so it's not a valid link + if (labelEnd < 0) { + return false; + } + pos = labelEnd + 1; + if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { + // + // Inline link + // + + // [link]( "title" ) + // ^^ skipping these spaces + pos++; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } - function useTrackedPointer() { - let lastPos = (0, import_react18.useRef)([-1, -1]); - return { - wasMoved(evt) { - if (false) { - } - let newPos = eventToPosition(evt); - if ( - lastPos.current[0] === newPos[0] && - lastPos.current[1] === newPos[1] - ) { - return false; - } - lastPos.current = newPos; - return true; - }, - update(evt) { - lastPos.current = eventToPosition(evt); - }, - }; + } + if (pos >= max) { + return false; + } + + // [link]( "title" ) + // ^^^^^^ parsing link destination + start = pos; + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); + if (res.ok) { + href = state.md.normalizeLink(res.str); + if (state.md.validateLink(href)) { + pos = res.pos; + } else { + href = ''; } - - // src/utils/platform.ts - function isIOS() { - return ( - // Check if it is an iPhone - /iPhone/gi.test(window.navigator.platform) || // Check if it is an iPad. iPad reports itself as "MacIntel", but we can check if it is a touch - // screen. Let's hope that Apple doesn't release a touch screen Mac (or maybe this would then - // work as expected 🤔). - (/Mac/gi.test(window.navigator.platform) && - window.navigator.maxTouchPoints > 0) - ); + } + + // [link]( "title" ) + // ^^ skipping these spaces + start = pos; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } - function isAndroid() { - return /Android/gi.test(window.navigator.userAgent); + } + + // [link]( "title" ) + // ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); + if (pos < max && start !== pos && res.ok) { + title = res.str; + pos = res.pos; + + // [link]( "title" ) + // ^^ skipping these spaces + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; + } } - function isMobile() { - return isIOS() || isAndroid(); + } else { + title = ''; + } + if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { + state.pos = oldPos; + return false; + } + pos++; + } else { + // + // Link reference + // + if (typeof state.env.references === 'undefined') { + return false; + } + if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { + start = pos + 1; + pos = state.md.helpers.parseLinkLabel(state, pos); + if (pos >= 0) { + label = state.src.slice(start, pos++); + } else { + pos = labelEnd + 1; } - - // src/components/combobox/combobox.tsx - function adjustOrderedState(state, adjustment = (i) => i) { - let currentActiveOption = - state.activeOptionIndex !== null - ? state.options[state.activeOptionIndex] - : null; - let sortedOptions = sortByDomNode( - adjustment(state.options.slice()), - (option) => option.dataRef.current.domRef.current - ); - let adjustedActiveOptionIndex = currentActiveOption - ? sortedOptions.indexOf(currentActiveOption) - : null; - if (adjustedActiveOptionIndex === -1) { - adjustedActiveOptionIndex = null; + } else { + pos = labelEnd + 1; + } + + // covers label === '' and label === undefined + // (collapsed reference link and shortcut reference link respectively) + if (!label) { + label = state.src.slice(labelStart, labelEnd); + } + ref = state.env.references[normalizeReference(label)]; + if (!ref) { + state.pos = oldPos; + return false; + } + href = ref.href; + title = ref.title; + } + + // + // We found the end of the link, and know for a fact it's a valid link; + // so all that's left to do is to call tokenizer. + // + if (!silent) { + content = state.src.slice(labelStart, labelEnd); + const tokens = []; + state.md.inline.parse(content, state.md, state.env, tokens); + const token = state.push('image', 'img', 0); + const attrs = [['src', href], ['alt', '']]; + token.attrs = attrs; + token.children = tokens; + token.content = content; + if (title) { + attrs.push(['title', title]); + } + } + state.pos = pos; + state.posMax = max; + return true; + } + + // Process autolinks '' + + /* eslint max-len:0 */ + const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; + /* eslint-disable-next-line no-control-regex */ + const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/; + function autolink(state, silent) { + let pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x3C /* < */) { + return false; + } + const start = state.pos; + const max = state.posMax; + for (;;) { + if (++pos >= max) return false; + const ch = state.src.charCodeAt(pos); + if (ch === 0x3C /* < */) return false; + if (ch === 0x3E /* > */) break; + } + const url = state.src.slice(start + 1, pos); + if (AUTOLINK_RE.test(url)) { + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) { + return false; + } + if (!silent) { + const token_o = state.push('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.markup = 'autolink'; + token_o.info = 'auto'; + const token_t = state.push('text', '', 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push('link_close', 'a', -1); + token_c.markup = 'autolink'; + token_c.info = 'auto'; + } + state.pos += url.length + 2; + return true; + } + if (EMAIL_RE.test(url)) { + const fullUrl = state.md.normalizeLink('mailto:' + url); + if (!state.md.validateLink(fullUrl)) { + return false; + } + if (!silent) { + const token_o = state.push('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.markup = 'autolink'; + token_o.info = 'auto'; + const token_t = state.push('text', '', 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push('link_close', 'a', -1); + token_c.markup = 'autolink'; + token_c.info = 'auto'; + } + state.pos += url.length + 2; + return true; + } + return false; + } + + // Process html tags + + function isLinkOpen(str) { + return /^\s]/i.test(str); + } + function isLinkClose(str) { + return /^<\/a\s*>/i.test(str); + } + function isLetter(ch) { + /* eslint no-bitwise:0 */ + const lc = ch | 0x20; // to lower case + return lc >= 0x61 /* a */ && lc <= 0x7a /* z */; + } + function html_inline(state, silent) { + if (!state.md.options.html) { + return false; + } + + // Check start + const max = state.posMax; + const pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x3C /* < */ || pos + 2 >= max) { + return false; + } + + // Quick fail on second char + const ch = state.src.charCodeAt(pos + 1); + if (ch !== 0x21 /* ! */ && ch !== 0x3F /* ? */ && ch !== 0x2F /* / */ && !isLetter(ch)) { + return false; + } + const match = state.src.slice(pos).match(HTML_TAG_RE); + if (!match) { + return false; + } + if (!silent) { + const token = state.push('html_inline', '', 0); + token.content = match[0]; + if (isLinkOpen(token.content)) state.linkLevel++; + if (isLinkClose(token.content)) state.linkLevel--; + } + state.pos += match[0].length; + return true; + } + + // Process html entity - {, ¯, ", ... + + const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; + const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; + function entity(state, silent) { + const pos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(pos) !== 0x26 /* & */) return false; + if (pos + 1 >= max) return false; + const ch = state.src.charCodeAt(pos + 1); + if (ch === 0x23 /* # */) { + const match = state.src.slice(pos).match(DIGITAL_RE); + if (match) { + if (!silent) { + const code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10); + const token = state.push('text_special', '', 0); + token.content = isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD); + token.markup = match[0]; + token.info = 'entity'; + } + state.pos += match[0].length; + return true; + } + } else { + const match = state.src.slice(pos).match(NAMED_RE); + if (match) { + const decoded = entities.decodeHTML(match[0]); + if (decoded !== match[0]) { + if (!silent) { + const token = state.push('text_special', '', 0); + token.content = decoded; + token.markup = match[0]; + token.info = 'entity'; } - return { - options: sortedOptions, - activeOptionIndex: adjustedActiveOptionIndex, - }; + state.pos += match[0].length; + return true; } - var reducers = { - [1 /* CloseCombobox */](state) { - var _a3; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (state.comboboxState === 1 /* Closed */) return state; - return { - ...state, - activeOptionIndex: null, - comboboxState: 1 /* Closed */, - }; - }, - [0 /* OpenCombobox */](state) { - var _a3; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (state.comboboxState === 0 /* Open */) return state; - let activeOptionIndex = state.activeOptionIndex; - if (state.dataRef.current) { - let { isSelected } = state.dataRef.current; - let optionIdx = state.options.findIndex((option) => - isSelected(option.dataRef.current.value) - ); - if (optionIdx !== -1) { - activeOptionIndex = optionIdx; - } - } - return { ...state, comboboxState: 0 /* Open */, activeOptionIndex }; - }, - [2 /* GoToOption */](state, action) { - var _a3, _b, _c, _d; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if ( - ((_b = state.dataRef.current) == null - ? void 0 - : _b.optionsRef.current) && - !((_c = state.dataRef.current) == null - ? void 0 - : _c.optionsPropsRef.current.static) && - state.comboboxState === 1 /* Closed */ - ) { - return state; - } - let adjustedState = adjustOrderedState(state); - if (adjustedState.activeOptionIndex === null) { - let localActiveOptionIndex = adjustedState.options.findIndex( - (option) => !option.dataRef.current.disabled - ); - if (localActiveOptionIndex !== -1) { - adjustedState.activeOptionIndex = localActiveOptionIndex; - } - } - let activeOptionIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.options, - resolveActiveIndex: () => adjustedState.activeOptionIndex, - resolveId: (item) => item.id, - resolveDisabled: (item) => item.dataRef.current.disabled, - }); - return { - ...state, - ...adjustedState, - activeOptionIndex, - activationTrigger: - (_d = action.trigger) != null ? _d : 1 /* Other */, - }; - }, - [3 /* RegisterOption */]: (state, action) => { - var _a3, _b; - let option = { id: action.id, dataRef: action.dataRef }; - let adjustedState = adjustOrderedState(state, (options) => [ - ...options, - option, - ]); - if (state.activeOptionIndex === null) { - if ( - (_a3 = state.dataRef.current) == null - ? void 0 - : _a3.isSelected(action.dataRef.current.value) - ) { - adjustedState.activeOptionIndex = - adjustedState.options.indexOf(option); + } + } + return false; + } + + // For each opening emphasis-like marker find a matching closing one + // + + function processDelimiters(delimiters) { + const openersBottom = {}; + const max = delimiters.length; + if (!max) return; + + // headerIdx is the first delimiter of the current (where closer is) delimiter run + let headerIdx = 0; + let lastTokenIdx = -2; // needs any value lower than -1 + const jumps = []; + for (let closerIdx = 0; closerIdx < max; closerIdx++) { + const closer = delimiters[closerIdx]; + jumps.push(0); + + // markers belong to same delimiter run if: + // - they have adjacent tokens + // - AND markers are the same + // + if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) { + headerIdx = closerIdx; + } + lastTokenIdx = closer.token; + + // Length is only used for emphasis-specific "rule of 3", + // if it's not defined (in strikethrough or 3rd party plugins), + // we can default it to 0 to disable those checks. + // + closer.length = closer.length || 0; + if (!closer.close) continue; + + // Previously calculated lower bounds (previous fails) + // for each marker, each delimiter length modulo 3, + // and for whether this closer can be an opener; + // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 + /* eslint-disable-next-line no-prototype-builtins */ + if (!openersBottom.hasOwnProperty(closer.marker)) { + openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]; + } + const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3]; + let openerIdx = headerIdx - jumps[headerIdx] - 1; + let newMinOpenerIdx = openerIdx; + for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) { + const opener = delimiters[openerIdx]; + if (opener.marker !== closer.marker) continue; + if (opener.open && opener.end < 0) { + let isOddMatch = false; + + // from spec: + // + // If one of the delimiters can both open and close emphasis, then the + // sum of the lengths of the delimiter runs containing the opening and + // closing delimiters must not be a multiple of 3 unless both lengths + // are multiples of 3. + // + if (opener.close || closer.open) { + if ((opener.length + closer.length) % 3 === 0) { + if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { + isOddMatch = true; } } - let nextState = { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */, - }; - if ( - ((_b = state.dataRef.current) == null ? void 0 : _b.__demoMode) && - state.dataRef.current.value === void 0 - ) { - nextState.activeOptionIndex = 0; - } - return nextState; - }, - [4 /* UnregisterOption */]: (state, action) => { - let adjustedState = adjustOrderedState(state, (options) => { - let idx = options.findIndex((a) => a.id === action.id); - if (idx !== -1) options.splice(idx, 1); - return options; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */, - }; - }, - [5 /* RegisterLabel */]: (state, action) => { - return { - ...state, - labelId: action.id, - }; - }, - }; - var ComboboxActionsContext = (0, import_react19.createContext)(null); - ComboboxActionsContext.displayName = "ComboboxActionsContext"; - function useActions(component) { - let context = (0, import_react19.useContext)(ComboboxActionsContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useActions); - throw err; } - return context; - } - var ComboboxDataContext = (0, import_react19.createContext)(null); - ComboboxDataContext.displayName = "ComboboxDataContext"; - function useData(component) { - let context = (0, import_react19.useContext)(ComboboxDataContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) Error.captureStackTrace(err, useData); - throw err; + if (!isOddMatch) { + // If previous delimiter cannot be an opener, we can safely skip + // the entire sequence in future checks. This is required to make + // sure algorithm has linear complexity (see *_*_*_*_*_... case). + // + const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0; + jumps[closerIdx] = closerIdx - openerIdx + lastJump; + jumps[openerIdx] = lastJump; + closer.open = false; + opener.end = closerIdx; + opener.close = false; + newMinOpenerIdx = -1; + // treat next token as start of run, + // it optimizes skips in **<...>**a**<...>** pathological case + lastTokenIdx = -2; + break; } - return context; } - function stateReducer(state, action) { - return match(action.type, reducers, state, action); + } + if (newMinOpenerIdx !== -1) { + // If match for this delimiter run failed, we want to set lower bound for + // future lookups. This is required to make sure algorithm has linear + // complexity. + // + // See details here: + // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 + // + openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx; + } + } + } + function link_pairs(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + processDelimiters(state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + processDelimiters(tokens_meta[curr].delimiters); + } + } + } + + // Clean up tokens after emphasis and strikethrough postprocessing: + // merge adjacent text nodes into one and re-calculate all token levels + // + // This is necessary because initially emphasis delimiter markers (*, _, ~) + // are treated as their own separate text tokens. Then emphasis rule either + // leaves them as text (needed to merge with adjacent text) or turns them + // into opening/closing tags (which messes up levels inside). + // + + function fragments_join(state) { + let curr, last; + let level = 0; + const tokens = state.tokens; + const max = state.tokens.length; + for (curr = last = 0; curr < max; curr++) { + // re-calculate levels after emphasis/strikethrough turns some text nodes + // into opening/closing tags + if (tokens[curr].nesting < 0) level--; // closing tag + tokens[curr].level = level; + if (tokens[curr].nesting > 0) level++; // opening tag + + if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { + // collapse two adjacent text nodes + tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; + } else { + if (curr !== last) { + tokens[last] = tokens[curr]; + } + last++; + } + } + if (curr !== last) { + tokens.length = last; + } + } + + /** internal + * class ParserInline + * + * Tokenizes paragraph content. + **/ + + // Parser rules + + const _rules = [['text', text], ['linkify', linkify], ['newline', newline], ['escape', escape], ['backticks', backtick], ['strikethrough', r_strikethrough.tokenize], ['emphasis', r_emphasis.tokenize], ['link', link], ['image', image], ['autolink', autolink], ['html_inline', html_inline], ['entity', entity]]; + + // `rule2` ruleset was created specifically for emphasis/strikethrough + // post-processing and may be changed in the future. + // + // Don't use this for anything except pairs (plugins working with `balance_pairs`). + // + const _rules2 = [['balance_pairs', link_pairs], ['strikethrough', r_strikethrough.postProcess], ['emphasis', r_emphasis.postProcess], + // rules for pairs separate '**' into its own text tokens, which may be left unused, + // rule below merges unused segments back with the rest of the text + ['fragments_join', fragments_join]]; + + /** + * new ParserInline() + **/ + function ParserInline() { + /** + * ParserInline#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of inline rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules.length; i++) { + this.ruler.push(_rules[i][0], _rules[i][1]); + } + + /** + * ParserInline#ruler2 -> Ruler + * + * [[Ruler]] instance. Second ruler used for post-processing + * (e.g. in emphasis-like rules). + **/ + this.ruler2 = new Ruler(); + for (let i = 0; i < _rules2.length; i++) { + this.ruler2.push(_rules2[i][0], _rules2[i][1]); + } + } + + // Skip single token by running all rules in validation mode; + // returns `true` if any rule reported success + // + ParserInline.prototype.skipToken = function (state) { + const pos = state.pos; + const rules = this.ruler.getRules(''); + const len = rules.length; + const maxNesting = state.md.options.maxNesting; + const cache = state.cache; + if (typeof cache[pos] !== 'undefined') { + state.pos = cache[pos]; + return; + } + let ok = false; + if (state.level < maxNesting) { + for (let i = 0; i < len; i++) { + // Increment state.level and decrement it later to limit recursion. + // It's harmless to do here, because no tokens are created. But ideally, + // we'd need a separate private state variable for this purpose. + // + state.level++; + ok = rules[i](state, true); + state.level--; + if (ok) { + if (pos >= state.pos) { + throw new Error("inline rule didn't increment state.pos"); + } + break; } - var DEFAULT_COMBOBOX_TAG = import_react19.Fragment; - function ComboboxFn(props, ref) { - let { - value: controlledValue, - defaultValue, - onChange: controlledOnChange, - form: formName, - name, - by = (a, z) => a === z, - disabled = false, - __demoMode = false, - nullable = false, - multiple = false, - ...theirProps - } = props; - let [value = multiple ? [] : void 0, theirOnChange] = useControllable( - controlledValue, - controlledOnChange, - defaultValue - ); - let [state, dispatch] = (0, import_react19.useReducer)(stateReducer, { - dataRef: (0, import_react19.createRef)(), - comboboxState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - options: [], - activeOptionIndex: null, - activationTrigger: 1 /* Other */, - labelId: null, - }); - let defaultToFirstOption = (0, import_react19.useRef)(false); - let optionsPropsRef = (0, import_react19.useRef)({ - static: false, - hold: false, - }); - let labelRef = (0, import_react19.useRef)(null); - let inputRef = (0, import_react19.useRef)(null); - let buttonRef = (0, import_react19.useRef)(null); - let optionsRef = (0, import_react19.useRef)(null); - let compare = useEvent( - // @ts-expect-error Eventually we'll want to tackle this, but for now this will do. - typeof by === "string" - ? (a, z) => { - let property = by; - return ( - (a == null ? void 0 : a[property]) === - (z == null ? void 0 : z[property]) - ); - } - : by - ); - let isSelected = (0, import_react19.useCallback)( - (compareValue) => - match(data.mode, { - [1 /* Multi */]: () => - value.some((option) => compare(option, compareValue)), - [0 /* Single */]: () => compare(value, compareValue), - }), - [value] - ); - let data = (0, import_react19.useMemo)( - () => ({ - ...state, - optionsPropsRef, - labelRef, - inputRef, - buttonRef, - optionsRef, - value, - defaultValue, - disabled, - mode: multiple ? 1 /* Multi */ : 0 /* Single */, - get activeOptionIndex() { - if ( - defaultToFirstOption.current && - state.activeOptionIndex === null && - state.options.length > 0 - ) { - let localActiveOptionIndex = state.options.findIndex( - (option) => !option.dataRef.current.disabled - ); - if (localActiveOptionIndex !== -1) { - return localActiveOptionIndex; - } - } - return state.activeOptionIndex; - }, - compare, - isSelected, - nullable, - __demoMode, - }), - [ - value, - defaultValue, - disabled, - multiple, - nullable, - __demoMode, - state, - ] - ); - let lastActiveOption = (0, import_react19.useRef)( - data.activeOptionIndex !== null - ? data.options[data.activeOptionIndex] - : null - ); - (0, import_react19.useEffect)(() => { - let currentActiveOption = - data.activeOptionIndex !== null - ? data.options[data.activeOptionIndex] - : null; - if (lastActiveOption.current !== currentActiveOption) { - lastActiveOption.current = currentActiveOption; - } - }); - useIsoMorphicEffect(() => { - state.dataRef.current = data; - }, [data]); - useOutsideClick( - [data.buttonRef, data.inputRef, data.optionsRef], - () => actions.closeCombobox(), - data.comboboxState === 0 /* Open */ - ); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled, - activeIndex: data.activeOptionIndex, - activeOption: - data.activeOptionIndex === null - ? null - : data.options[data.activeOptionIndex].dataRef.current.value, - value, - }), - [data, disabled, value] - ); - let selectOption = useEvent((id) => { - let option = data.options.find((item) => item.id === id); - if (!option) return; - onChange(option.dataRef.current.value); - }); - let selectActiveOption = useEvent(() => { - if (data.activeOptionIndex !== null) { - let { dataRef, id } = data.options[data.activeOptionIndex]; - onChange(dataRef.current.value); - actions.goToOption(4 /* Specific */, id); - } - }); - let openCombobox = useEvent(() => { - dispatch({ type: 0 /* OpenCombobox */ }); - defaultToFirstOption.current = true; - }); - let closeCombobox = useEvent(() => { - dispatch({ type: 1 /* CloseCombobox */ }); - defaultToFirstOption.current = false; - }); - let goToOption = useEvent((focus, id, trigger) => { - defaultToFirstOption.current = false; - if (focus === 4 /* Specific */) { - return dispatch({ - type: 2 /* GoToOption */, - focus: 4 /* Specific */, - id, - trigger, - }); + } + } else { + // Too much nesting, just skip until the end of the paragraph. + // + // NOTE: this will cause links to behave incorrectly in the following case, + // when an amount of `[` is exactly equal to `maxNesting + 1`: + // + // [[[[[[[[[[[[[[[[[[[[[foo]() + // + // TODO: remove this workaround when CM standard will allow nested links + // (we can replace it by preventing links from being parsed in + // validation mode) + // + state.pos = state.posMax; + } + if (!ok) { + state.pos++; + } + cache[pos] = state.pos; + }; + + // Generate tokens for input range + // + ParserInline.prototype.tokenize = function (state) { + const rules = this.ruler.getRules(''); + const len = rules.length; + const end = state.posMax; + const maxNesting = state.md.options.maxNesting; + while (state.pos < end) { + // Try all possible rules. + // On success, rule should: + // + // - update `state.pos` + // - update `state.tokens` + // - return true + const prevPos = state.pos; + let ok = false; + if (state.level < maxNesting) { + for (let i = 0; i < len; i++) { + ok = rules[i](state, false); + if (ok) { + if (prevPos >= state.pos) { + throw new Error("inline rule didn't increment state.pos"); } - return dispatch({ type: 2 /* GoToOption */, focus, trigger }); - }); - let registerOption = useEvent((id, dataRef) => { - dispatch({ type: 3 /* RegisterOption */, id, dataRef }); - return () => { - var _a3; - if ( - ((_a3 = lastActiveOption.current) == null ? void 0 : _a3.id) === - id - ) { - defaultToFirstOption.current = true; - } - dispatch({ type: 4 /* UnregisterOption */, id }); - }; - }); - let registerLabel = useEvent((id) => { - dispatch({ type: 5 /* RegisterLabel */, id }); - return () => dispatch({ type: 5 /* RegisterLabel */, id: null }); - }); - let onChange = useEvent((value2) => { - return match(data.mode, { - [0 /* Single */]() { - return theirOnChange == null ? void 0 : theirOnChange(value2); - }, - [1 /* Multi */]() { - let copy = data.value.slice(); - let idx = copy.findIndex((item) => compare(item, value2)); - if (idx === -1) { - copy.push(value2); - } else { - copy.splice(idx, 1); - } - return theirOnChange == null ? void 0 : theirOnChange(copy); - }, - }); - }); - let actions = (0, import_react19.useMemo)( - () => ({ - onChange, - registerOption, - registerLabel, - goToOption, - closeCombobox, - openCombobox, - selectActiveOption, - selectOption, - }), - [] - ); - let ourProps = ref === null ? {} : { ref }; - let form = (0, import_react19.useRef)(null); - let d = useDisposables(); - (0, import_react19.useEffect)(() => { - if (!form.current) return; - if (defaultValue === void 0) return; - d.addEventListener(form.current, "reset", () => { - onChange(defaultValue); - }); - }, [ - form, - onChange, - /* Explicitly ignoring `defaultValue` */ - ]); - return /* @__PURE__ */ import_react19.default.createElement( - ComboboxActionsContext.Provider, - { value: actions }, - /* @__PURE__ */ import_react19.default.createElement( - ComboboxDataContext.Provider, - { value: data }, - /* @__PURE__ */ import_react19.default.createElement( - OpenClosedProvider, - { - value: match(data.comboboxState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */, - }), - }, - name != null && - value != null && - objectToFormEntries({ [name]: value }).map( - ([name2, value2], idx) => - /* @__PURE__ */ import_react19.default.createElement( - Hidden, - { - features: 4 /* Hidden */, - ref: - idx === 0 - ? (element) => { - var _a3; - form.current = - (_a3 = - element == null - ? void 0 - : element.closest("form")) != null - ? _a3 - : null; - } - : void 0, - ...compact({ - key: name2, - as: "input", - type: "hidden", - hidden: true, - readOnly: true, - form: formName, - name: name2, - value: value2, - }), - } - ) - ), - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_COMBOBOX_TAG, - name: "Combobox", - }) - ) - ) - ); + break; + } } - var DEFAULT_INPUT_TAG = "input"; - function InputFn(props, ref) { - var _a3, _b, _c, _d; - let internalId = useId(); - let { - id = `headlessui-combobox-input-${internalId}`, - onChange, - displayValue, - // @ts-ignore: We know this MAY NOT exist for a given tag but we only care when it _does_ exist. - type = "text", - ...theirProps - } = props; - let data = useData("Combobox.Input"); - let actions = useActions("Combobox.Input"); - let inputRef = useSyncRefs(data.inputRef, ref); - let isTyping = (0, import_react19.useRef)(false); - let d = useDisposables(); - let currentDisplayValue = (function () { - var _a4; - if (typeof displayValue === "function" && data.value !== void 0) { - return (_a4 = displayValue(data.value)) != null ? _a4 : ""; - } else if (typeof data.value === "string") { - return data.value; - } else { - return ""; - } - })(); - useWatch( - ( - [currentDisplayValue2, state], - [oldCurrentDisplayValue, oldState] - ) => { - if (isTyping.current) return; - if (!data.inputRef.current) return; - if (oldState === 0 /* Open */ && state === 1 /* Closed */) { - data.inputRef.current.value = currentDisplayValue2; - } else if (currentDisplayValue2 !== oldCurrentDisplayValue) { - data.inputRef.current.value = currentDisplayValue2; - } - }, - [currentDisplayValue, data.comboboxState] - ); - useWatch( - ([newState], [oldState]) => { - if (newState === 0 /* Open */ && oldState === 1 /* Closed */) { - let input = data.inputRef.current; - if (!input) return; - let currentValue = input.value; - let { selectionStart, selectionEnd, selectionDirection } = - input; - input.value = ""; - input.value = currentValue; - if (selectionDirection !== null) { - input.setSelectionRange( - selectionStart, - selectionEnd, - selectionDirection - ); - } else { - input.setSelectionRange(selectionStart, selectionEnd); - } - } - }, - [data.comboboxState] - ); - let isComposing = (0, import_react19.useRef)(false); - let composedChangeEvent = (0, import_react19.useRef)(null); - let handleCompositionStart = useEvent(() => { - isComposing.current = true; - }); - let handleCompositionEnd = useEvent(() => { - d.nextFrame(() => { - isComposing.current = false; - if (composedChangeEvent.current) { - actions.openCombobox(); - onChange == null - ? void 0 - : onChange(composedChangeEvent.current); - composedChangeEvent.current = null; - } - }); - }); - let handleKeyDown = useEvent((event) => { - isTyping.current = true; - switch (event.key) { - case "Backspace" /* Backspace */: - case "Delete" /* Delete */: - if (data.mode !== 0 /* Single */) return; - if (!data.nullable) return; - let input = event.currentTarget; - d.requestAnimationFrame(() => { - if (input.value === "") { - actions.onChange(null); - if (data.optionsRef.current) { - data.optionsRef.current.scrollTop = 0; - } - actions.goToOption(5 /* Nothing */); - } - }); - break; - case "Enter" /* Enter */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) return; - if (isComposing.current) return; - event.preventDefault(); - event.stopPropagation(); - if (data.activeOptionIndex === null) { - actions.closeCombobox(); - return; - } - actions.selectActiveOption(); - if (data.mode === 0 /* Single */) { - actions.closeCombobox(); - } - break; - case "ArrowDown" /* ArrowDown */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return match(data.comboboxState, { - [0 /* Open */]: () => { - actions.goToOption(2 /* Next */); - }, - [1 /* Closed */]: () => { - actions.openCombobox(); - }, - }); - case "ArrowUp" /* ArrowUp */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return match(data.comboboxState, { - [0 /* Open */]: () => { - actions.goToOption(1 /* Previous */); - }, - [1 /* Closed */]: () => { - actions.openCombobox(); - d.nextFrame(() => { - if (!data.value) { - actions.goToOption(3 /* Last */); - } - }); - }, - }); - case "Home" /* Home */: - if (event.shiftKey) { - break; - } - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "PageUp" /* PageUp */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "End" /* End */: - if (event.shiftKey) { - break; - } - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "PageDown" /* PageDown */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "Escape" /* Escape */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) return; - event.preventDefault(); - if ( - data.optionsRef.current && - !data.optionsPropsRef.current.static - ) { - event.stopPropagation(); - } - return actions.closeCombobox(); - case "Tab" /* Tab */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) return; - if (data.mode === 0 /* Single */) actions.selectActiveOption(); - actions.closeCombobox(); - break; - } - }); - let handleChange = useEvent((event) => { - if (isComposing.current) { - composedChangeEvent.current = event; - return; - } - actions.openCombobox(); - onChange == null ? void 0 : onChange(event); - }); - let handleBlur = useEvent(() => { - isTyping.current = false; - }); - let labelledby = useComputed(() => { - if (!data.labelId) return void 0; - return [data.labelId].join(" "); - }, [data.labelId]); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled: data.disabled, - }), - [data] - ); - let ourProps = { - ref: inputRef, - id, - role: "combobox", - type, - "aria-controls": - (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled - ? void 0 - : data.comboboxState === 0 /* Open */, - "aria-activedescendant": - data.activeOptionIndex === null - ? void 0 - : (_b = data.options[data.activeOptionIndex]) == null - ? void 0 - : _b.id, - "aria-labelledby": labelledby, - "aria-autocomplete": "list", - defaultValue: - (_d = - (_c = props.defaultValue) != null - ? _c - : data.defaultValue !== void 0 - ? displayValue == null - ? void 0 - : displayValue(data.defaultValue) - : null) != null - ? _d - : data.defaultValue, - disabled: data.disabled, - onCompositionStart: handleCompositionStart, - onCompositionEnd: handleCompositionEnd, - onKeyDown: handleKeyDown, - onChange: handleChange, - onBlur: handleBlur, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_INPUT_TAG, - name: "Combobox.Input", - }); + } + if (ok) { + if (state.pos >= end) { + break; + } + continue; + } + state.pending += state.src[state.pos++]; + } + if (state.pending) { + state.pushPending(); + } + }; + + /** + * ParserInline.parse(str, md, env, outTokens) + * + * Process input string and push inline tokens into `outTokens` + **/ + ParserInline.prototype.parse = function (str, md, env, outTokens) { + const state = new this.State(str, md, env, outTokens); + this.tokenize(state); + const rules = this.ruler2.getRules(''); + const len = rules.length; + for (let i = 0; i < len; i++) { + rules[i](state); + } + }; + ParserInline.prototype.State = StateInline; + + // markdown-it default options + + var cfg_default = { + options: { + // Enable HTML tags in source + html: false, + // Use '/' to close single tags (
    ) + xhtmlOut: false, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: 'language-', + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: '\u201c\u201d\u2018\u2019', + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with ) + xhtmlOut: false, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: 'language-', + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: '\u201c\u201d\u2018\u2019', + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with ) + xhtmlOut: true, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: 'language-', + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: '\u201c\u201d\u2018\u2019', + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with = 0) { + try { + parsed.hostname = punycode.toASCII(parsed.hostname); + } catch (er) {/**/} + } + } + return mdurl__namespace.encode(mdurl__namespace.format(parsed)); + } + function normalizeLinkText(url) { + const parsed = mdurl__namespace.parse(url, true); + if (parsed.hostname) { + // Encode hostnames in urls like: + // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + // + // We don't encode unknown schemas, because it's likely that we encode + // something we shouldn't (e.g. `skype:name` treated as `skype:host`) + // + if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { + try { + parsed.hostname = punycode.toUnicode(parsed.hostname); + } catch (er) {/**/} + } + } + + // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 + return mdurl__namespace.decode(mdurl__namespace.format(parsed), mdurl__namespace.decode.defaultChars + '%'); + } + + /** + * class MarkdownIt + * + * Main parser/renderer class. + * + * ##### Usage + * + * ```javascript + * // node.js, "classic" way: + * var MarkdownIt = require('markdown-it'), + * md = new MarkdownIt(); + * var result = md.render('# markdown-it rulezz!'); + * + * // node.js, the same, but with sugar: + * var md = require('markdown-it')(); + * var result = md.render('# markdown-it rulezz!'); + * + * // browser without AMD, added to "window" on script load + * // Note, there are no dash. + * var md = window.markdownit(); + * var result = md.render('# markdown-it rulezz!'); + * ``` + * + * Single line rendering, without paragraph wrap: + * + * ```javascript + * var md = require('markdown-it')(); + * var result = md.renderInline('__markdown-it__ rulezz!'); + * ``` + **/ + + /** + * new MarkdownIt([presetName, options]) + * - presetName (String): optional, `commonmark` / `zero` + * - options (Object) + * + * Creates parser instanse with given config. Can be called without `new`. + * + * ##### presetName + * + * MarkdownIt provides named presets as a convenience to quickly + * enable/disable active syntax rules and options for common use cases. + * + * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.mjs) - + * configures parser to strict [CommonMark](http://commonmark.org/) mode. + * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.mjs) - + * similar to GFM, used when no preset name given. Enables all available rules, + * but still without html, typographer & autolinker. + * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.mjs) - + * all rules disabled. Useful to quickly setup your config via `.enable()`. + * For example, when you need only `bold` and `italic` markup and nothing else. + * + * ##### options: + * + * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! + * That's not safe! You may need external sanitizer to protect output from XSS. + * It's better to extend features via plugins, instead of enabling HTML. + * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags + * (`
    `). This is needed only for full CommonMark compatibility. In real + * world you will need HTML output. + * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
    `. + * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. + * Can be useful for external highlighters. + * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. + * - __typographer__ - `false`. Set `true` to enable [some language-neutral + * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs) + + * quotes beautification (smartquotes). + * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement + * pairs, when typographer enabled and smartquotes on. For example, you can + * use `'«»„“'` for Russian, `'„“‚‘'` for German, and + * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). + * - __highlight__ - `null`. Highlighter function for fenced code blocks. + * Highlighter `function (str, lang)` should return escaped HTML. It can also + * return empty string if the source was not changed and should be escaped + * externaly. If result starts with ` or ``): + * + * ```javascript + * var hljs = require('highlight.js') // https://highlightjs.org/ + * + * // Actual default values + * var md = require('markdown-it')({ + * highlight: function (str, lang) { + * if (lang && hljs.getLanguage(lang)) { + * try { + * return '
    ' +
    +   *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
    +   *                '
    '; + * } catch (__) {} + * } + * + * return '
    ' + md.utils.escapeHtml(str) + '
    '; + * } + * }); + * ``` + * + **/ + function MarkdownIt(presetName, options) { + if (!(this instanceof MarkdownIt)) { + return new MarkdownIt(presetName, options); + } + if (!options) { + if (!isString(presetName)) { + options = presetName || {}; + presetName = 'default'; + } + } + + /** + * MarkdownIt#inline -> ParserInline + * + * Instance of [[ParserInline]]. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.inline = new ParserInline(); + + /** + * MarkdownIt#block -> ParserBlock + * + * Instance of [[ParserBlock]]. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.block = new ParserBlock(); + + /** + * MarkdownIt#core -> Core + * + * Instance of [[Core]] chain executor. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.core = new Core(); + + /** + * MarkdownIt#renderer -> Renderer + * + * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering + * rules for new token types, generated by plugins. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * function myToken(tokens, idx, options, env, self) { + * //... + * return result; + * }; + * + * md.renderer.rules['my_token'] = myToken + * ``` + * + * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs). + **/ + this.renderer = new Renderer(); + + /** + * MarkdownIt#linkify -> LinkifyIt + * + * [linkify-it](https://github.com/markdown-it/linkify-it) instance. + * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs) + * rule. + **/ + this.linkify = new LinkifyIt(); + + /** + * MarkdownIt#validateLink(url) -> Boolean + * + * Link validation function. CommonMark allows too much in links. By default + * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas + * except some embedded image types. + * + * You can change this behaviour: + * + * ```javascript + * var md = require('markdown-it')(); + * // enable everything + * md.validateLink = function () { return true; } + * ``` + **/ + this.validateLink = validateLink; + + /** + * MarkdownIt#normalizeLink(url) -> String + * + * Function used to encode link url to a machine-readable format, + * which includes url-encoding, punycode, etc. + **/ + this.normalizeLink = normalizeLink; + + /** + * MarkdownIt#normalizeLinkText(url) -> String + * + * Function used to decode link url to a human-readable format` + **/ + this.normalizeLinkText = normalizeLinkText; + + // Expose utils & helpers for easy acces from plugins + + /** + * MarkdownIt#utils -> utils + * + * Assorted utility functions, useful to write plugins. See details + * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs). + **/ + this.utils = utils; + + /** + * MarkdownIt#helpers -> helpers + * + * Link components parser functions, useful to write plugins. See details + * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). + **/ + this.helpers = assign({}, helpers); + this.options = {}; + this.configure(presetName); + if (options) { + this.set(options); + } + } + + /** chainable + * MarkdownIt.set(options) + * + * Set parser options (in the same format as in constructor). Probably, you + * will never need it, but you can change options after constructor call. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')() + * .set({ html: true, breaks: true }) + * .set({ typographer, true }); + * ``` + * + * __Note:__ To achieve the best possible performance, don't modify a + * `markdown-it` instance options on the fly. If you need multiple configurations + * it's best to create multiple instances and initialize each with separate + * config. + **/ + MarkdownIt.prototype.set = function (options) { + assign(this.options, options); + return this; + }; + + /** chainable, internal + * MarkdownIt.configure(presets) + * + * Batch load of all options and compenent settings. This is internal method, + * and you probably will not need it. But if you will - see available presets + * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) + * + * We strongly recommend to use presets instead of direct config loads. That + * will give better compatibility with next versions. + **/ + MarkdownIt.prototype.configure = function (presets) { + const self = this; + if (isString(presets)) { + const presetName = presets; + presets = config[presetName]; + if (!presets) { + throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name'); + } + } + if (!presets) { + throw new Error('Wrong `markdown-it` preset, can\'t be empty'); + } + if (presets.options) { + self.set(presets.options); + } + if (presets.components) { + Object.keys(presets.components).forEach(function (name) { + if (presets.components[name].rules) { + self[name].ruler.enableOnly(presets.components[name].rules); } - var DEFAULT_BUTTON_TAG = "button"; - function ButtonFn(props, ref) { - var _a3; - let data = useData("Combobox.Button"); - let actions = useActions("Combobox.Button"); - let buttonRef = useSyncRefs(data.buttonRef, ref); - let internalId = useId(); - let { - id = `headlessui-combobox-button-${internalId}`, - ...theirProps - } = props; - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - if (data.comboboxState === 1 /* Closed */) { - actions.openCombobox(); - } - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - if (data.comboboxState === 1 /* Closed */) { - actions.openCombobox(); - d.nextFrame(() => { - if (!data.value) { - actions.goToOption(3 /* Last */); - } - }); - } - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - case "Escape" /* Escape */: - if (data.comboboxState !== 0 /* Open */) return; - event.preventDefault(); - if ( - data.optionsRef.current && - !data.optionsPropsRef.current.static - ) { - event.stopPropagation(); - } - actions.closeCombobox(); - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - default: - return; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (data.comboboxState === 0 /* Open */) { - actions.closeCombobox(); + if (presets.components[name].rules2) { + self[name].ruler2.enableOnly(presets.components[name].rules2); + } + }); + } + return this; + }; + + /** chainable + * MarkdownIt.enable(list, ignoreInvalid) + * - list (String|Array): rule name or list of rule names to enable + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable list or rules. It will automatically find appropriate components, + * containing rules with given names. If rule not found, and `ignoreInvalid` + * not set - throws exception. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')() + * .enable(['sub', 'sup']) + * .disable('smartquotes'); + * ``` + **/ + MarkdownIt.prototype.enable = function (list, ignoreInvalid) { + let result = []; + if (!Array.isArray(list)) { + list = [list]; + } + ['core', 'block', 'inline'].forEach(function (chain) { + result = result.concat(this[chain].ruler.enable(list, true)); + }, this); + result = result.concat(this.inline.ruler2.enable(list, true)); + const missed = list.filter(function (name) { + return result.indexOf(name) < 0; + }); + if (missed.length && !ignoreInvalid) { + throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed); + } + return this; + }; + + /** chainable + * MarkdownIt.disable(list, ignoreInvalid) + * - list (String|Array): rule name or list of rule names to disable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * The same as [[MarkdownIt.enable]], but turn specified rules off. + **/ + MarkdownIt.prototype.disable = function (list, ignoreInvalid) { + let result = []; + if (!Array.isArray(list)) { + list = [list]; + } + ['core', 'block', 'inline'].forEach(function (chain) { + result = result.concat(this[chain].ruler.disable(list, true)); + }, this); + result = result.concat(this.inline.ruler2.disable(list, true)); + const missed = list.filter(function (name) { + return result.indexOf(name) < 0; + }); + if (missed.length && !ignoreInvalid) { + throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed); + } + return this; + }; + + /** chainable + * MarkdownIt.use(plugin, params) + * + * Load specified plugin with given params into current parser instance. + * It's just a sugar to call `plugin(md, params)` with curring. + * + * ##### Example + * + * ```javascript + * var iterator = require('markdown-it-for-inline'); + * var md = require('markdown-it')() + * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { + * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); + * }); + * ``` + **/ + MarkdownIt.prototype.use = function (plugin /*, params, ... */) { + const args = [this].concat(Array.prototype.slice.call(arguments, 1)); + plugin.apply(plugin, args); + return this; + }; + + /** internal + * MarkdownIt.parse(src, env) -> Array + * - src (String): source string + * - env (Object): environment sandbox + * + * Parse input string and return list of block tokens (special token type + * "inline" will contain list of inline tokens). You should not call this + * method directly, until you write custom renderer (for example, to produce + * AST). + * + * `env` is used to pass data between "distributed" rules and return additional + * metadata like reference info, needed for the renderer. It also can be used to + * inject data in specific cases. Usually, you will be ok to pass `{}`, + * and then pass updated object to renderer. + **/ + MarkdownIt.prototype.parse = function (src, env) { + if (typeof src !== 'string') { + throw new Error('Input data should be a String'); + } + const state = new this.core.State(src, this, env); + this.core.process(state); + return state.tokens; + }; + + /** + * MarkdownIt.render(src [, env]) -> String + * - src (String): source string + * - env (Object): environment sandbox + * + * Render markdown string into html. It does all magic for you :). + * + * `env` can be used to inject additional metadata (`{}` by default). + * But you will not need it with high probability. See also comment + * in [[MarkdownIt.parse]]. + **/ + MarkdownIt.prototype.render = function (src, env) { + env = env || {}; + return this.renderer.render(this.parse(src, env), this.options, env); + }; + + /** internal + * MarkdownIt.parseInline(src, env) -> Array + * - src (String): source string + * - env (Object): environment sandbox + * + * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the + * block tokens list with the single `inline` element, containing parsed inline + * tokens in `children` property. Also updates `env` object. + **/ + MarkdownIt.prototype.parseInline = function (src, env) { + const state = new this.core.State(src, this, env); + state.inlineMode = true; + this.core.process(state); + return state.tokens; + }; + + /** + * MarkdownIt.renderInline(src [, env]) -> String + * - src (String): source string + * - env (Object): environment sandbox + * + * Similar to [[MarkdownIt.render]] but for single paragraph content. Result + * will NOT be wrapped into `

    ` tags. + **/ + MarkdownIt.prototype.renderInline = function (src, env) { + env = env || {}; + return this.renderer.render(this.parseInline(src, env), this.options, env); + }; + module.exports = MarkdownIt; + + /***/ }), + + /***/ "../node_modules/mdurl/build/index.cjs.js": + /*!************************************************!*\ + !*** ../node_modules/mdurl/build/index.cjs.js ***! + \************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + /* eslint-disable no-bitwise */ + const decodeCache = {}; + function getDecodeCache(exclude) { + let cache = decodeCache[exclude]; + if (cache) { + return cache; + } + cache = decodeCache[exclude] = []; + for (let i = 0; i < 128; i++) { + const ch = String.fromCharCode(i); + cache.push(ch); + } + for (let i = 0; i < exclude.length; i++) { + const ch = exclude.charCodeAt(i); + cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2); + } + return cache; + } + + // Decode percent-encoded string. + // + function decode(string, exclude) { + if (typeof exclude !== 'string') { + exclude = decode.defaultChars; + } + const cache = getDecodeCache(exclude); + return string.replace(/(%[a-f0-9]{2})+/gi, function (seq) { + let result = ''; + for (let i = 0, l = seq.length; i < l; i += 3) { + const b1 = parseInt(seq.slice(i + 1, i + 3), 16); + if (b1 < 0x80) { + result += cache[b1]; + continue; + } + if ((b1 & 0xE0) === 0xC0 && i + 3 < l) { + // 110xxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + if ((b2 & 0xC0) === 0x80) { + const chr = b1 << 6 & 0x7C0 | b2 & 0x3F; + if (chr < 0x80) { + result += '\ufffd\ufffd'; } else { - event.preventDefault(); - actions.openCombobox(); + result += String.fromCharCode(chr); } - d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - }); - let labelledby = useComputed(() => { - if (!data.labelId) return void 0; - return [data.labelId, id].join(" "); - }, [data.labelId, id]); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled: data.disabled, - value: data.value, - }), - [data] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, data.buttonRef), - tabIndex: -1, - "aria-haspopup": "listbox", - "aria-controls": - (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled - ? void 0 - : data.comboboxState === 0 /* Open */, - "aria-labelledby": labelledby, - disabled: data.disabled, - onClick: handleClick, - onKeyDown: handleKeyDown, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG, - name: "Combobox.Button", - }); - } - var DEFAULT_LABEL_TAG = "label"; - function LabelFn(props, ref) { - let internalId = useId(); - let { - id = `headlessui-combobox-label-${internalId}`, - ...theirProps - } = props; - let data = useData("Combobox.Label"); - let actions = useActions("Combobox.Label"); - let labelRef = useSyncRefs(data.labelRef, ref); - useIsoMorphicEffect(() => actions.registerLabel(id), [id]); - let handleClick = useEvent(() => { - var _a3; - return (_a3 = data.inputRef.current) == null - ? void 0 - : _a3.focus({ preventScroll: true }); - }); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled: data.disabled, - }), - [data] - ); - let ourProps = { ref: labelRef, id, onClick: handleClick }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_LABEL_TAG, - name: "Combobox.Label", - }); - } - var DEFAULT_OPTIONS_TAG = "ul"; - var OptionsRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ - function OptionsFn(props, ref) { - let internalId = useId(); - let { - id = `headlessui-combobox-options-${internalId}`, - hold = false, - ...theirProps - } = props; - let data = useData("Combobox.Options"); - let optionsRef = useSyncRefs(data.optionsRef, ref); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - return data.comboboxState === 0 /* Open */; - })(); - useIsoMorphicEffect(() => { - var _a3; - data.optionsPropsRef.current.static = - (_a3 = props.static) != null ? _a3 : false; - }, [data.optionsPropsRef, props.static]); - useIsoMorphicEffect(() => { - data.optionsPropsRef.current.hold = hold; - }, [data.optionsPropsRef, hold]); - useTreeWalker({ - container: data.optionsRef.current, - enabled: data.comboboxState === 0 /* Open */, - accept(node) { - if (node.getAttribute("role") === "option") - return NodeFilter.FILTER_REJECT; - if (node.hasAttribute("role")) return NodeFilter.FILTER_SKIP; - return NodeFilter.FILTER_ACCEPT; - }, - walk(node) { - node.setAttribute("role", "none"); - }, - }); - let labelledby = useComputed(() => { - var _a3, _b; - return (_b = data.labelId) != null - ? _b - : (_a3 = data.buttonRef.current) == null - ? void 0 - : _a3.id; - }, [data.labelId, data.buttonRef.current]); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */ }), - [data] - ); - let ourProps = { - "aria-labelledby": labelledby, - role: "listbox", - "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, - id, - ref: optionsRef, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTIONS_TAG, - features: OptionsRenderFeatures, - visible, - name: "Combobox.Options", - }); + i += 3; + continue; + } } - var DEFAULT_OPTION_TAG = "li"; - function OptionFn(props, ref) { - var _a3, _b; - let internalId = useId(); - let { - id = `headlessui-combobox-option-${internalId}`, - disabled = false, - value, - ...theirProps - } = props; - let data = useData("Combobox.Option"); - let actions = useActions("Combobox.Option"); - let active = - data.activeOptionIndex !== null - ? data.options[data.activeOptionIndex].id === id - : false; - let selected = data.isSelected(value); - let internalOptionRef = (0, import_react19.useRef)(null); - let bag = useLatestValue({ - disabled, - value, - domRef: internalOptionRef, - textValue: - (_b = - (_a3 = internalOptionRef.current) == null - ? void 0 - : _a3.textContent) == null - ? void 0 - : _b.toLowerCase(), - }); - let optionRef = useSyncRefs(ref, internalOptionRef); - let select = useEvent(() => actions.selectOption(id)); - useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); - let enableScrollIntoView = (0, import_react19.useRef)( - data.__demoMode ? false : true - ); - useIsoMorphicEffect(() => { - if (!data.__demoMode) return; - let d = disposables(); - d.requestAnimationFrame(() => { - enableScrollIntoView.current = true; - }); - return d.dispose; - }, []); - useIsoMorphicEffect(() => { - if (data.comboboxState !== 0 /* Open */) return; - if (!active) return; - if (!enableScrollIntoView.current) return; - if (data.activationTrigger === 0 /* Pointer */) return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a4, _b2; - (_b2 = - (_a4 = internalOptionRef.current) == null - ? void 0 - : _a4.scrollIntoView) == null - ? void 0 - : _b2.call(_a4, { block: "nearest" }); - }); - return d.dispose; - }, [ - internalOptionRef, - active, - data.comboboxState, - data.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - data.activeOptionIndex, - ]); - let handleClick = useEvent((event) => { - if (disabled) return event.preventDefault(); - select(); - if (data.mode === 0 /* Single */) { - actions.closeCombobox(); - } - if (!isMobile()) { - requestAnimationFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null - ? void 0 - : _a4.focus(); - }); + if ((b1 & 0xF0) === 0xE0 && i + 6 < l) { + // 1110xxxx 10xxxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + const b3 = parseInt(seq.slice(i + 7, i + 9), 16); + if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + const chr = b1 << 12 & 0xF000 | b2 << 6 & 0xFC0 | b3 & 0x3F; + if (chr < 0x800 || chr >= 0xD800 && chr <= 0xDFFF) { + result += '\ufffd\ufffd\ufffd'; + } else { + result += String.fromCharCode(chr); } - }); - let handleFocus = useEvent(() => { - if (disabled) return actions.goToOption(5 /* Nothing */); - actions.goToOption(4 /* Specific */, id); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) return; - if (disabled) return; - if (active) return; - actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) return; - if (disabled) return; - if (!active) return; - if (data.optionsPropsRef.current.hold) return; - actions.goToOption(5 /* Nothing */); - }); - let slot = (0, import_react19.useMemo)( - () => ({ active, selected, disabled }), - [active, selected, disabled] - ); - let ourProps = { - id, - ref: optionRef, - role: "option", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - // According to the WAI-ARIA best practices, we should use aria-checked for - // multi-select,but Voice-Over disagrees. So we use aria-checked instead for - // both single and multi-select. - "aria-selected": selected, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTION_TAG, - name: "Combobox.Option", - }); - } - var ComboboxRoot = forwardRefWithAs(ComboboxFn); - var Button = forwardRefWithAs(ButtonFn); - var Input = forwardRefWithAs(InputFn); - var Label = forwardRefWithAs(LabelFn); - var Options = forwardRefWithAs(OptionsFn); - var Option = forwardRefWithAs(OptionFn); - var Combobox = Object.assign(ComboboxRoot, { - Input, - Button, - Label, - Options, - Option, - }); - - // src/components/dialog/dialog.tsx - var import_react31 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/components/focus-trap/focus-trap.tsx - var import_react25 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/hooks/use-tab-direction.ts - var import_react20 = __webpack_require__(/*! react */ "react"); - function useTabDirection() { - let direction = (0, import_react20.useRef)(0 /* Forwards */); - useWindowEvent( - "keydown", - (event) => { - if (event.key === "Tab") { - direction.current = event.shiftKey - ? 1 /* Backwards */ - : 0 /* Forwards */; - } - }, - true - ); - return direction; - } - - // src/hooks/use-is-mounted.ts - var import_react21 = __webpack_require__(/*! react */ "react"); - function useIsMounted() { - let mounted = (0, import_react21.useRef)(false); - useIsoMorphicEffect(() => { - mounted.current = true; - return () => { - mounted.current = false; - }; - }, []); - return mounted; - } - - // src/hooks/use-owner.ts - var import_react22 = __webpack_require__(/*! react */ "react"); - function useOwnerDocument(...args) { - return (0, import_react22.useMemo)( - () => getOwnerDocument(...args), - [...args] - ); - } - - // src/hooks/use-event-listener.ts - var import_react23 = __webpack_require__(/*! react */ "react"); - function useEventListener(element, type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react23.useEffect)(() => { - element = element != null ? element : window; - function handler(event) { - listenerRef.current(event); - } - element.addEventListener(type, handler, options); - return () => element.removeEventListener(type, handler, options); - }, [element, type, options]); - } - - // src/utils/document-ready.ts - function onDocumentReady(cb) { - function check() { - if (document.readyState === "loading") return; - cb(); - document.removeEventListener("DOMContentLoaded", check); + i += 6; + continue; } - if ( - typeof window !== "undefined" && - typeof document !== "undefined" - ) { - document.addEventListener("DOMContentLoaded", check); - check(); + } + if ((b1 & 0xF8) === 0xF0 && i + 9 < l) { + // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + const b3 = parseInt(seq.slice(i + 7, i + 9), 16); + const b4 = parseInt(seq.slice(i + 10, i + 12), 16); + if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) { + let chr = b1 << 18 & 0x1C0000 | b2 << 12 & 0x3F000 | b3 << 6 & 0xFC0 | b4 & 0x3F; + if (chr < 0x10000 || chr > 0x10FFFF) { + result += '\ufffd\ufffd\ufffd\ufffd'; + } else { + chr -= 0x10000; + result += String.fromCharCode(0xD800 + (chr >> 10), 0xDC00 + (chr & 0x3FF)); + } + i += 9; + continue; } } - - // src/hooks/use-on-unmount.ts - var import_react24 = __webpack_require__(/*! react */ "react"); - function useOnUnmount(cb) { - let stableCb = useEvent(cb); - let trulyUnmounted = (0, import_react24.useRef)(false); - (0, import_react24.useEffect)(() => { - trulyUnmounted.current = false; - return () => { - trulyUnmounted.current = true; - microTask(() => { - if (!trulyUnmounted.current) return; - stableCb(); - }); - }; - }, [stableCb]); + result += '\ufffd'; + } + return result; + }); + } + decode.defaultChars = ';/?:@&=+$,#'; + decode.componentChars = ''; + const encodeCache = {}; + + // Create a lookup array where anything but characters in `chars` string + // and alphanumeric chars is percent-encoded. + // + function getEncodeCache(exclude) { + let cache = encodeCache[exclude]; + if (cache) { + return cache; + } + cache = encodeCache[exclude] = []; + for (let i = 0; i < 128; i++) { + const ch = String.fromCharCode(i); + if (/^[0-9a-z]$/i.test(ch)) { + // always allow unencoded alphanumeric characters + cache.push(ch); + } else { + cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2)); + } + } + for (let i = 0; i < exclude.length; i++) { + cache[exclude.charCodeAt(i)] = exclude[i]; + } + return cache; + } + + // Encode unsafe characters with percent-encoding, skipping already + // encoded sequences. + // + // - string - string to encode + // - exclude - list of characters to ignore (in addition to a-zA-Z0-9) + // - keepEscaped - don't encode '%' in a correct escape sequence (default: true) + // + function encode(string, exclude, keepEscaped) { + if (typeof exclude !== 'string') { + // encode(string, keepEscaped) + keepEscaped = exclude; + exclude = encode.defaultChars; + } + if (typeof keepEscaped === 'undefined') { + keepEscaped = true; + } + const cache = getEncodeCache(exclude); + let result = ''; + for (let i = 0, l = string.length; i < l; i++) { + const code = string.charCodeAt(i); + if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { + if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { + result += string.slice(i, i + 3); + i += 2; + continue; } - - // src/components/focus-trap/focus-trap.tsx - function resolveContainers(containers) { - if (!containers) return /* @__PURE__ */ new Set(); - if (typeof containers === "function") return new Set(containers()); - let all = /* @__PURE__ */ new Set(); - for (let container of containers.current) { - if (container.current instanceof HTMLElement) { - all.add(container.current); - } - } - return all; - } - var DEFAULT_FOCUS_TRAP_TAG = "div"; - var Features3 = /* @__PURE__ */ ((Features4) => { - Features4[(Features4["None"] = 1)] = "None"; - Features4[(Features4["InitialFocus"] = 2)] = "InitialFocus"; - Features4[(Features4["TabLock"] = 4)] = "TabLock"; - Features4[(Features4["FocusLock"] = 8)] = "FocusLock"; - Features4[(Features4["RestoreFocus"] = 16)] = "RestoreFocus"; - Features4[(Features4["All"] = 30)] = "All"; - return Features4; - })(Features3 || {}); - function FocusTrapFn(props, ref) { - let container = (0, import_react25.useRef)(null); - let focusTrapRef = useSyncRefs(container, ref); - let { - initialFocus, - containers, - features = 30 /* All */, - ...theirProps - } = props; - if (!useServerHandoffComplete()) { - features = 1 /* None */; - } - let ownerDocument = useOwnerDocument(container); - useRestoreFocus( - { ownerDocument }, - Boolean(features & 16 /* RestoreFocus */) - ); - let previousActiveElement = useInitialFocus( - { ownerDocument, container, initialFocus }, - Boolean(features & 2 /* InitialFocus */) - ); - useFocusLock( - { ownerDocument, container, containers, previousActiveElement }, - Boolean(features & 8 /* FocusLock */) - ); - let direction = useTabDirection(); - let handleFocus = useEvent((e) => { - let el = container.current; - if (!el) return; - let wrapper = false ? 0 : (cb) => cb(); - wrapper(() => { - match(direction.current, { - [0 /* Forwards */]: () => { - focusIn(el, 1 /* First */, { - skipElements: [e.relatedTarget], - }); - }, - [1 /* Backwards */]: () => { - focusIn(el, 8 /* Last */, { - skipElements: [e.relatedTarget], - }); - }, - }); - }); - }); - let d = useDisposables(); - let recentlyUsedTabKey = (0, import_react25.useRef)(false); - let ourProps = { - ref: focusTrapRef, - onKeyDown(e) { - if (e.key == "Tab") { - recentlyUsedTabKey.current = true; - d.requestAnimationFrame(() => { - recentlyUsedTabKey.current = false; - }); - } - }, - onBlur(e) { - let allContainers = resolveContainers(containers); - if (container.current instanceof HTMLElement) - allContainers.add(container.current); - let relatedTarget = e.relatedTarget; - if (!(relatedTarget instanceof HTMLElement)) return; - if (relatedTarget.dataset.headlessuiFocusGuard === "true") { - return; - } - if (!contains(allContainers, relatedTarget)) { - if (recentlyUsedTabKey.current) { - focusIn( - container.current, - match(direction.current, { - [0 /* Forwards */]: () => 4 /* Next */, - [1 /* Backwards */]: () => 2 /* Previous */, - }) | 16 /* WrapAround */, - { relativeTo: e.target } - ); - } else if (e.target instanceof HTMLElement) { - focusElement(e.target); - } - } - }, - }; - return /* @__PURE__ */ import_react25.default.createElement( - import_react25.default.Fragment, - null, - Boolean(features & 4 /* TabLock */) && - /* @__PURE__ */ import_react25.default.createElement(Hidden, { - as: "button", - type: "button", - "data-headlessui-focus-guard": true, - onFocus: handleFocus, - features: 2 /* Focusable */, - }), - render({ - ourProps, - theirProps, - defaultTag: DEFAULT_FOCUS_TRAP_TAG, - name: "FocusTrap", - }), - Boolean(features & 4 /* TabLock */) && - /* @__PURE__ */ import_react25.default.createElement(Hidden, { - as: "button", - type: "button", - "data-headlessui-focus-guard": true, - onFocus: handleFocus, - features: 2 /* Focusable */, - }) - ); + } + if (code < 128) { + result += cache[code]; + continue; + } + if (code >= 0xD800 && code <= 0xDFFF) { + if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) { + const nextCode = string.charCodeAt(i + 1); + if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) { + result += encodeURIComponent(string[i] + string[i + 1]); + i++; + continue; + } } - var FocusTrapRoot = forwardRefWithAs(FocusTrapFn); - var FocusTrap = Object.assign(FocusTrapRoot, { - features: Features3, - }); - var history = []; - onDocumentReady(() => { - function handle(e) { - if (!(e.target instanceof HTMLElement)) return; - if (e.target === document.body) return; - if (history[0] === e.target) return; - history.unshift(e.target); - history = history.filter((x) => x != null && x.isConnected); - history.splice(10); - } - window.addEventListener("click", handle, { capture: true }); - window.addEventListener("mousedown", handle, { capture: true }); - window.addEventListener("focus", handle, { capture: true }); - document.body.addEventListener("click", handle, { capture: true }); - document.body.addEventListener("mousedown", handle, { - capture: true, - }); - document.body.addEventListener("focus", handle, { capture: true }); - }); - function useRestoreElement(enabled = true) { - let localHistory = (0, import_react25.useRef)(history.slice()); - useWatch( - ([newEnabled], [oldEnabled]) => { - if (oldEnabled === true && newEnabled === false) { - microTask(() => { - localHistory.current.splice(0); - }); - } - if (oldEnabled === false && newEnabled === true) { - localHistory.current = history.slice(); - } - }, - [enabled, history, localHistory] - ); - return useEvent(() => { - var _a3; - return (_a3 = localHistory.current.find( - (x) => x != null && x.isConnected - )) != null - ? _a3 - : null; - }); + result += '%EF%BF%BD'; + continue; + } + result += encodeURIComponent(string[i]); + } + return result; + } + encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; + encode.componentChars = "-_.!~*'()"; + function format(url) { + let result = ''; + result += url.protocol || ''; + result += url.slashes ? '//' : ''; + result += url.auth ? url.auth + '@' : ''; + if (url.hostname && url.hostname.indexOf(':') !== -1) { + // ipv6 address + result += '[' + url.hostname + ']'; + } else { + result += url.hostname || ''; + } + result += url.port ? ':' + url.port : ''; + result += url.pathname || ''; + result += url.search || ''; + result += url.hash || ''; + return result; + } + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // + // Changes from joyent/node: + // + // 1. No leading slash in paths, + // e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` + // + // 2. Backslashes are not replaced with slashes, + // so `http:\\example.org\` is treated like a relative path + // + // 3. Trailing colon is treated like a part of the path, + // i.e. in `http://example.org:foo` pathname is `:foo` + // + // 4. Nothing is URL-encoded in the resulting object, + // (in joyent/node some chars in auth and paths are encoded) + // + // 5. `url.parse()` does not have `parseQueryString` argument + // + // 6. Removed extraneous result properties: `host`, `path`, `query`, etc., + // which can be constructed using other parts of the url. + // + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + const protocolPattern = /^([a-z0-9.+-]+:)/i; + const portPattern = /:[0-9]*$/; + + // Special case for a simple path URL + /* eslint-disable-next-line no-useless-escape */ + const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + const delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t']; + + // RFC 2396: characters not allowed for various reasons. + const unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims); + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + const autoEscape = ['\''].concat(unwise); + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + const nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape); + const hostEndingChars = ['/', '?', '#']; + const hostnameMaxLen = 255; + const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; + const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; + // protocols that can allow "unsafe" and "unwise" chars. + // protocols that never have a hostname. + const hostlessProtocol = { + javascript: true, + 'javascript:': true + }; + // protocols that always contain a // bit. + const slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + function urlParse(url, slashesDenoteHost) { + if (url && url instanceof Url) return url; + const u = new Url(); + u.parse(url, slashesDenoteHost); + return u; + } + Url.prototype.parse = function (url, slashesDenoteHost) { + let lowerProto, hec, slashes; + let rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + const simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + } + return this; + } + } + let proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + lowerProto = proto.toLowerCase(); + this.protocol = proto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + /* eslint-disable-next-line no-useless-escape */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) { + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + let hostEnd = -1; + for (let i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; } - function useRestoreFocus({ ownerDocument }, enabled) { - let getRestoreElement = useRestoreElement(enabled); - useWatch(() => { - if (enabled) return; - if ( - (ownerDocument == null ? void 0 : ownerDocument.activeElement) === - (ownerDocument == null ? void 0 : ownerDocument.body) - ) { - focusElement(getRestoreElement()); - } - }, [enabled]); - useOnUnmount(() => { - if (!enabled) return; - focusElement(getRestoreElement()); - }); + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + let auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = auth; + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (let i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; } - function useInitialFocus( - { ownerDocument, container, initialFocus }, - enabled - ) { - let previousActiveElement = (0, import_react25.useRef)(null); - let mounted = useIsMounted(); - useWatch(() => { - if (!enabled) return; - let containerElement = container.current; - if (!containerElement) return; - microTask(() => { - if (!mounted.current) { - return; - } - let activeElement = - ownerDocument == null ? void 0 : ownerDocument.activeElement; - if (initialFocus == null ? void 0 : initialFocus.current) { - if ( - (initialFocus == null ? void 0 : initialFocus.current) === - activeElement - ) { - previousActiveElement.current = activeElement; - return; - } - } else if (containerElement.contains(activeElement)) { - previousActiveElement.current = activeElement; - return; - } - if (initialFocus == null ? void 0 : initialFocus.current) { - focusElement(initialFocus.current); - } else { - if ( - focusIn(containerElement, 1 /* First */) === 0 /* Error */ - ) { - console.warn( - "There are no focusable elements inside the " - ); - } - } - previousActiveElement.current = - ownerDocument == null ? void 0 : ownerDocument.activeElement; - }); - }, [enabled]); - return previousActiveElement; - } - function useFocusLock( - { ownerDocument, container, containers, previousActiveElement }, - enabled - ) { - let mounted = useIsMounted(); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "focus", - (event) => { - if (!enabled) return; - if (!mounted.current) return; - let allContainers = resolveContainers(containers); - if (container.current instanceof HTMLElement) - allContainers.add(container.current); - let previous = previousActiveElement.current; - if (!previous) return; - let toElement = event.target; - if (toElement && toElement instanceof HTMLElement) { - if (!contains(allContainers, toElement)) { - event.preventDefault(); - event.stopPropagation(); - focusElement(previous); - } else { - previousActiveElement.current = toElement; - focusElement(toElement); - } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { + hostEnd = rest.length; + } + if (rest[hostEnd - 1] === ':') { + hostEnd--; + } + const host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(host); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + const ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + const hostparts = this.hostname.split(/\./); + for (let i = 0, l = hostparts.length; i < l; i++) { + const part = hostparts[i]; + if (!part) { + continue; + } + if (!part.match(hostnamePartPattern)) { + let newpart = ''; + for (let j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; } else { - focusElement(previousActiveElement.current); + newpart += part[j]; } - }, - true - ); - } - function contains(containers, element) { - for (let container of containers) { - if (container.contains(element)) return true; - } - return false; - } - - // src/components/portal/portal.tsx - var import_react27 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var import_react_dom = __webpack_require__( - /*! react-dom */ "react-dom" - ); - - // src/internal/portal-force-root.tsx - var import_react26 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var ForcePortalRootContext = (0, import_react26.createContext)(false); - function usePortalRoot() { - return (0, import_react26.useContext)(ForcePortalRootContext); - } - function ForcePortalRoot(props) { - return /* @__PURE__ */ import_react26.default.createElement( - ForcePortalRootContext.Provider, - { value: props.force }, - props.children - ); - } - - // src/components/portal/portal.tsx - function usePortalTarget(ref) { - let forceInRoot = usePortalRoot(); - let groupTarget = (0, import_react27.useContext)(PortalGroupContext); - let ownerDocument = useOwnerDocument(ref); - let [target, setTarget] = (0, import_react27.useState)(() => { - if (!forceInRoot && groupTarget !== null) return null; - if (env.isServer) return null; - let existingRoot = - ownerDocument == null - ? void 0 - : ownerDocument.getElementById("headlessui-portal-root"); - if (existingRoot) return existingRoot; - if (ownerDocument === null) return null; - let root = ownerDocument.createElement("div"); - root.setAttribute("id", "headlessui-portal-root"); - return ownerDocument.body.appendChild(root); - }); - (0, import_react27.useEffect)(() => { - if (target === null) return; - if ( - !(ownerDocument == null - ? void 0 - : ownerDocument.body.contains(target)) - ) { - ownerDocument == null - ? void 0 - : ownerDocument.body.appendChild(target); - } - }, [target, ownerDocument]); - (0, import_react27.useEffect)(() => { - if (forceInRoot) return; - if (groupTarget === null) return; - setTarget(groupTarget.current); - }, [groupTarget, setTarget, forceInRoot]); - return target; - } - var DEFAULT_PORTAL_TAG = import_react27.Fragment; - function PortalFn(props, ref) { - let theirProps = props; - let internalPortalRootRef = (0, import_react27.useRef)(null); - let portalRef = useSyncRefs( - optionalRef((ref2) => { - internalPortalRootRef.current = ref2; - }), - ref - ); - let ownerDocument = useOwnerDocument(internalPortalRootRef); - let target = usePortalTarget(internalPortalRootRef); - let [element] = (0, import_react27.useState)(() => { - var _a3; - return env.isServer - ? null - : (_a3 = - ownerDocument == null - ? void 0 - : ownerDocument.createElement("div")) != null - ? _a3 - : null; - }); - let parent = (0, import_react27.useContext)(PortalParentContext); - let ready = useServerHandoffComplete(); - useIsoMorphicEffect(() => { - if (!target || !element) return; - if (!target.contains(element)) { - element.setAttribute("data-headlessui-portal", ""); - target.appendChild(element); - } - }, [target, element]); - useIsoMorphicEffect(() => { - if (!element) return; - if (!parent) return; - return parent.register(element); - }, [parent, element]); - useOnUnmount(() => { - var _a3; - if (!target || !element) return; - if (element instanceof Node && target.contains(element)) { - target.removeChild(element); } - if (target.childNodes.length <= 0) { - (_a3 = target.parentElement) == null - ? void 0 - : _a3.removeChild(target); + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + const validParts = hostparts.slice(0, i); + const notHost = hostparts.slice(i + 1); + const bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; } - }); - if (!ready) return null; - let ourProps = { ref: portalRef }; - return !target || !element - ? null - : (0, import_react_dom.createPortal)( - render({ - ourProps, - theirProps, - defaultTag: DEFAULT_PORTAL_TAG, - name: "Portal", - }), - element - ); + } } - var DEFAULT_GROUP_TAG = import_react27.Fragment; - var PortalGroupContext = (0, import_react27.createContext)(null); - function GroupFn(props, ref) { - let { target, ...theirProps } = props; - let groupRef = useSyncRefs(ref); - let ourProps = { ref: groupRef }; - return /* @__PURE__ */ import_react27.default.createElement( - PortalGroupContext.Provider, - { value: target }, - render({ - ourProps, - theirProps, - defaultTag: DEFAULT_GROUP_TAG, - name: "Popover.Group", - }) - ); + } + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + } + } + + // chop off from the tail first. + const hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + const qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + rest = rest.slice(0, qm); + } + if (rest) { + this.pathname = rest; + } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = ''; + } + return this; + }; + Url.prototype.parseHost = function (host) { + let port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { + this.hostname = host; + } + }; + exports.decode = decode; + exports.encode = encode; + exports.format = format; + exports.parse = urlParse; + + /***/ }), + + /***/ "../node_modules/uc.micro/build/index.cjs.js": + /*!***************************************************!*\ + !*** ../node_modules/uc.micro/build/index.cjs.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + var regex$5 = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var regex$4 = /[\0-\x1F\x7F-\x9F]/; + var regex$3 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/; + var regex$2 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/; + var regex$1 = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/; + var regex = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; + exports.Any = regex$5; + exports.Cc = regex$4; + exports.Cf = regex$3; + exports.P = regex$2; + exports.S = regex$1; + exports.Z = regex; + + /***/ }), + + /***/ "./components/GraphiQL.tsx": + /*!*********************************!*\ + !*** ./components/GraphiQL.tsx ***! + \*********************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.GraphiQL = GraphiQL; + exports.GraphiQLInterface = GraphiQLInterface; + var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); + var _react2 = __webpack_require__(/*! @graphiql/react */ "../../graphiql-react/dist/index.js"); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** + * Copyright (c) 2020 GraphQL Contributors. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + const majorVersion = parseInt(_react.default.version.slice(0, 2), 10); + if (majorVersion < 16) { + throw new Error(['GraphiQL 0.18.0 and after is not compatible with React 15 or below.', 'If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:', 'https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49'].join('\n')); + } + + /** + * API docs for this live here: + * + * https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops + */ + + /** + * The top-level React component for GraphiQL, intended to encompass the entire + * browser viewport. + * + * @see https://github.com/graphql/graphiql#usage + */ + + function GraphiQL({ + dangerouslyAssumeSchemaIsValid, + defaultQuery, + defaultTabs, + externalFragments, + fetcher, + getDefaultFieldNames, + headers, + inputValueDeprecation, + introspectionQueryName, + maxHistoryLength, + onEditOperationName, + onSchemaChange, + onTabChange, + onTogglePluginVisibility, + operationName, + plugins, + query, + response, + schema, + schemaDescription, + shouldPersistHeaders, + storage, + validationRules, + variables, + visiblePlugin, + defaultHeaders, + ...props + }) { + var _props$disableTabs; + // Ensure props are correct + if (typeof fetcher !== 'function') { + throw new TypeError('The `GraphiQL` component requires a `fetcher` function to be passed as prop.'); + } + return /*#__PURE__*/_react.default.createElement(_react2.GraphiQLProvider, { + getDefaultFieldNames: getDefaultFieldNames, + dangerouslyAssumeSchemaIsValid: dangerouslyAssumeSchemaIsValid, + defaultQuery: defaultQuery, + defaultHeaders: defaultHeaders, + defaultTabs: defaultTabs, + externalFragments: externalFragments, + fetcher: fetcher, + headers: headers, + inputValueDeprecation: inputValueDeprecation, + introspectionQueryName: introspectionQueryName, + maxHistoryLength: maxHistoryLength, + onEditOperationName: onEditOperationName, + onSchemaChange: onSchemaChange, + onTabChange: onTabChange, + onTogglePluginVisibility: onTogglePluginVisibility, + plugins: plugins, + visiblePlugin: visiblePlugin, + operationName: operationName, + query: query, + response: response, + schema: schema, + schemaDescription: schemaDescription, + shouldPersistHeaders: shouldPersistHeaders, + storage: storage, + validationRules: validationRules, + variables: variables + }, /*#__PURE__*/_react.default.createElement(GraphiQLInterface, _extends({ + showPersistHeadersSettings: shouldPersistHeaders !== false, + disableTabs: (_props$disableTabs = props.disableTabs) !== null && _props$disableTabs !== void 0 ? _props$disableTabs : false, + forcedTheme: props.forcedTheme + }, props))); + } + + // Export main windows/panes to be used separately if desired. + GraphiQL.Logo = GraphiQLLogo; + GraphiQL.Toolbar = GraphiQLToolbar; + GraphiQL.Footer = GraphiQLFooter; + const THEMES = ['light', 'dark', 'system']; + function GraphiQLInterface(props) { + var _props$isHeadersEdito, _pluginContext$visibl, _props$toolbar, _props$toolbar2; + const isHeadersEditorEnabled = (_props$isHeadersEdito = props.isHeadersEditorEnabled) !== null && _props$isHeadersEdito !== void 0 ? _props$isHeadersEdito : true; + const editorContext = (0, _react2.useEditorContext)({ + nonNull: true + }); + const executionContext = (0, _react2.useExecutionContext)({ + nonNull: true + }); + const schemaContext = (0, _react2.useSchemaContext)({ + nonNull: true + }); + const storageContext = (0, _react2.useStorageContext)(); + const pluginContext = (0, _react2.usePluginContext)(); + const forcedTheme = (0, _react.useMemo)(() => props.forcedTheme && THEMES.includes(props.forcedTheme) ? props.forcedTheme : undefined, [props.forcedTheme]); + const copy = (0, _react2.useCopyQuery)({ + onCopyQuery: props.onCopyQuery + }); + const merge = (0, _react2.useMergeQuery)(); + const prettify = (0, _react2.usePrettifyEditors)(); + const { + theme, + setTheme + } = (0, _react2.useTheme)(); + (0, _react.useEffect)(() => { + if (forcedTheme === 'system') { + setTheme(null); + } else if (forcedTheme === 'light' || forcedTheme === 'dark') { + setTheme(forcedTheme); + } + }, [forcedTheme, setTheme]); + const PluginContent = pluginContext === null || pluginContext === void 0 ? void 0 : (_pluginContext$visibl = pluginContext.visiblePlugin) === null || _pluginContext$visibl === void 0 ? void 0 : _pluginContext$visibl.content; + const pluginResize = (0, _react2.useDragResize)({ + defaultSizeRelation: 1 / 3, + direction: 'horizontal', + initiallyHidden: pluginContext !== null && pluginContext !== void 0 && pluginContext.visiblePlugin ? undefined : 'first', + onHiddenElementChange(resizableElement) { + if (resizableElement === 'first') { + pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.setVisiblePlugin(null); } - var PortalParentContext = (0, import_react27.createContext)(null); - function useNestedPortals() { - let parent = (0, import_react27.useContext)(PortalParentContext); - let portals = (0, import_react27.useRef)([]); - let register = useEvent((portal) => { - portals.current.push(portal); - if (parent) parent.register(portal); - return () => unregister(portal); - }); - let unregister = useEvent((portal) => { - let idx = portals.current.indexOf(portal); - if (idx !== -1) portals.current.splice(idx, 1); - if (parent) parent.unregister(portal); - }); - let api = (0, import_react27.useMemo)( - () => ({ register, unregister, portals }), - [register, unregister, portals] - ); - return [ - portals, - (0, import_react27.useMemo)(() => { - return function PortalWrapper({ children }) { - return /* @__PURE__ */ import_react27.default.createElement( - PortalParentContext.Provider, - { value: api }, - children - ); - }; - }, [api]), - ]; + }, + sizeThresholdSecond: 200, + storageKey: 'docExplorerFlex' + }); + const editorResize = (0, _react2.useDragResize)({ + direction: 'horizontal', + storageKey: 'editorFlex' + }); + const editorToolsResize = (0, _react2.useDragResize)({ + defaultSizeRelation: 3, + direction: 'vertical', + initiallyHidden: (() => { + if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { + return; } - var PortalRoot = forwardRefWithAs(PortalFn); - var Group = forwardRefWithAs(GroupFn); - var Portal = Object.assign(PortalRoot, { Group }); - - // src/components/description/description.tsx - var import_react28 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var DescriptionContext = (0, import_react28.createContext)(null); - function useDescriptionContext() { - let context = (0, import_react28.useContext)(DescriptionContext); - if (context === null) { - let err = new Error( - "You used a component, but it is not inside a relevant parent." - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDescriptionContext); - throw err; - } - return context; + if (typeof props.defaultEditorToolsVisibility === 'boolean') { + return props.defaultEditorToolsVisibility ? undefined : 'second'; } - function useDescriptions() { - let [descriptionIds, setDescriptionIds] = (0, - import_react28.useState)([]); - return [ - // The actual id's as string or undefined - descriptionIds.length > 0 ? descriptionIds.join(" ") : void 0, - // The provider component - (0, import_react28.useMemo)(() => { - return function DescriptionProvider(props) { - let register = useEvent((value) => { - setDescriptionIds((existing) => [...existing, value]); - return () => - setDescriptionIds((existing) => { - let clone = existing.slice(); - let idx = clone.indexOf(value); - if (idx !== -1) clone.splice(idx, 1); - return clone; - }); - }); - let contextBag = (0, import_react28.useMemo)( - () => ({ - register, - slot: props.slot, - name: props.name, - props: props.props, - }), - [register, props.slot, props.name, props.props] - ); - return /* @__PURE__ */ import_react28.default.createElement( - DescriptionContext.Provider, - { value: contextBag }, - props.children - ); - }; - }, [setDescriptionIds]), - ]; - } - var DEFAULT_DESCRIPTION_TAG = "p"; - function DescriptionFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-description-${internalId}`, ...theirProps } = - props; - let context = useDescriptionContext(); - let descriptionRef = useSyncRefs(ref); - useIsoMorphicEffect( - () => context.register(id), - [id, context.register] - ); - let ourProps = { ref: descriptionRef, ...context.props, id }; - return render({ - ourProps, - theirProps, - slot: context.slot || {}, - defaultTag: DEFAULT_DESCRIPTION_TAG, - name: context.name || "Description", - }); + return editorContext.initialVariables || editorContext.initialHeaders ? undefined : 'second'; + })(), + sizeThresholdSecond: 60, + storageKey: 'secondaryEditorFlex' + }); + const [activeSecondaryEditor, setActiveSecondaryEditor] = (0, _react.useState)(() => { + if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { + return props.defaultEditorToolsVisibility; + } + return !editorContext.initialVariables && editorContext.initialHeaders && isHeadersEditorEnabled ? 'headers' : 'variables'; + }); + const [showDialog, setShowDialog] = (0, _react.useState)(null); + const [clearStorageStatus, setClearStorageStatus] = (0, _react.useState)(null); + const children = _react.default.Children.toArray(props.children); + const logo = children.find(child => isChildComponentType(child, GraphiQL.Logo)) || /*#__PURE__*/_react.default.createElement(GraphiQL.Logo, null); + const toolbar = children.find(child => isChildComponentType(child, GraphiQL.Toolbar)) || /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { + onClick: prettify, + label: "Prettify query (Shift-Ctrl-P)" + }, /*#__PURE__*/_react.default.createElement(_react2.PrettifyIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true" + })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { + onClick: merge, + label: "Merge fragments into query (Shift-Ctrl-M)" + }, /*#__PURE__*/_react.default.createElement(_react2.MergeIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true" + })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { + onClick: copy, + label: "Copy query (Shift-Ctrl-C)" + }, /*#__PURE__*/_react.default.createElement(_react2.CopyIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true" + })), (_props$toolbar = props.toolbar) === null || _props$toolbar === void 0 ? void 0 : _props$toolbar.additionalContent, ((_props$toolbar2 = props.toolbar) === null || _props$toolbar2 === void 0 ? void 0 : _props$toolbar2.additionalComponent) && /*#__PURE__*/_react.default.createElement(props.toolbar.additionalComponent, null)); + const footer = children.find(child => isChildComponentType(child, GraphiQL.Footer)); + const onClickReference = (0, _react.useCallback)(() => { + if (pluginResize.hiddenElement === 'first') { + pluginResize.setHiddenElement(null); + } + }, [pluginResize]); + const handleClearData = (0, _react.useCallback)(() => { + try { + storageContext === null || storageContext === void 0 ? void 0 : storageContext.clear(); + setClearStorageStatus('success'); + } catch { + setClearStorageStatus('error'); + } + }, [storageContext]); + const handlePersistHeaders = (0, _react.useCallback)(event => { + editorContext.setShouldPersistHeaders(event.currentTarget.dataset.value === 'true'); + }, [editorContext]); + const handleChangeTheme = (0, _react.useCallback)(event => { + const selectedTheme = event.currentTarget.dataset.theme; + setTheme(selectedTheme || null); + }, [setTheme]); + const handleAddTab = editorContext.addTab; + const handleRefetchSchema = schemaContext.introspect; + const handleReorder = editorContext.moveTab; + const handleShowDialog = (0, _react.useCallback)(event => { + setShowDialog(event.currentTarget.dataset.value); + }, []); + const handlePluginClick = (0, _react.useCallback)(e => { + const context = pluginContext; + const pluginIndex = Number(e.currentTarget.dataset.index); + const plugin = context.plugins.find((_, index) => pluginIndex === index); + const isVisible = plugin === context.visiblePlugin; + if (isVisible) { + context.setVisiblePlugin(null); + pluginResize.setHiddenElement('first'); + } else { + context.setVisiblePlugin(plugin); + pluginResize.setHiddenElement(null); + } + }, [pluginContext, pluginResize]); + const handleToolsTabClick = (0, _react.useCallback)(event => { + if (editorToolsResize.hiddenElement === 'second') { + editorToolsResize.setHiddenElement(null); + } + setActiveSecondaryEditor(event.currentTarget.dataset.name); + }, [editorToolsResize]); + const toggleEditorTools = (0, _react.useCallback)(() => { + editorToolsResize.setHiddenElement(editorToolsResize.hiddenElement === 'second' ? null : 'second'); + }, [editorToolsResize]); + const handleOpenShortKeysDialog = (0, _react.useCallback)(isOpen => { + if (!isOpen) { + setShowDialog(null); + } + }, []); + const handleOpenSettingsDialog = (0, _react.useCallback)(isOpen => { + if (!isOpen) { + setShowDialog(null); + setClearStorageStatus(null); + } + }, []); + const addTab = /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Add tab" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: "graphiql-tab-add", + onClick: handleAddTab, + "aria-label": "Add tab" + }, /*#__PURE__*/_react.default.createElement(_react2.PlusIcon, { + "aria-hidden": "true" + }))); + const className = props.className ? ` ${props.className}` : ''; + return /*#__PURE__*/_react.default.createElement(_react2.Tooltip.Provider, null, /*#__PURE__*/_react.default.createElement("div", { + "data-testid": "graphiql-container", + className: `graphiql-container${className}` + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-sidebar" + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-sidebar-section" + }, pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.plugins.map((plugin, index) => { + const isVisible = plugin === pluginContext.visiblePlugin; + const label = `${isVisible ? 'Hide' : 'Show'} ${plugin.title}`; + const Icon = plugin.icon; + return /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + key: plugin.title, + label: label + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: isVisible ? 'active' : '', + onClick: handlePluginClick, + "data-index": index, + "aria-label": label + }, /*#__PURE__*/_react.default.createElement(Icon, { + "aria-hidden": "true" + }))); + })), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-sidebar-section" + }, /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Re-fetch GraphQL schema" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + disabled: schemaContext.isFetching, + onClick: handleRefetchSchema, + "aria-label": "Re-fetch GraphQL schema" + }, /*#__PURE__*/_react.default.createElement(_react2.ReloadIcon, { + className: schemaContext.isFetching ? 'graphiql-spin' : '', + "aria-hidden": "true" + }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Open short keys dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + "data-value": "short-keys", + onClick: handleShowDialog, + "aria-label": "Open short keys dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.KeyboardShortcutIcon, { + "aria-hidden": "true" + }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Open settings dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + "data-value": "settings", + onClick: handleShowDialog, + "aria-label": "Open settings dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.SettingsIcon, { + "aria-hidden": "true" + }))))), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-main" + }, /*#__PURE__*/_react.default.createElement("div", { + ref: pluginResize.firstRef, + style: { + // Make sure the container shrinks when containing long + // non-breaking texts + minWidth: '200px' + } + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-plugin" + }, PluginContent ? /*#__PURE__*/_react.default.createElement(PluginContent, null) : null)), (pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.visiblePlugin) && /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-horizontal-drag-bar", + ref: pluginResize.dragBarRef + }), /*#__PURE__*/_react.default.createElement("div", { + ref: pluginResize.secondRef, + className: "graphiql-sessions" + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-session-header" + }, !props.disableTabs && /*#__PURE__*/_react.default.createElement(_react2.Tabs, { + values: editorContext.tabs, + onReorder: handleReorder, + "aria-label": "Select active operation" + }, editorContext.tabs.length > 1 && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, editorContext.tabs.map((tab, index) => /*#__PURE__*/_react.default.createElement(_react2.Tab, { + key: tab.id, + value: tab, + isActive: index === editorContext.activeTabIndex + }, /*#__PURE__*/_react.default.createElement(_react2.Tab.Button, { + "aria-controls": "graphiql-session", + id: `graphiql-session-tab-${index}`, + onClick: () => { + executionContext.stop(); + editorContext.changeTab(index); + } + }, tab.title), /*#__PURE__*/_react.default.createElement(_react2.Tab.Close, { + onClick: () => { + if (editorContext.activeTabIndex === index) { + executionContext.stop(); } - var DescriptionRoot = forwardRefWithAs(DescriptionFn); - var Description = Object.assign(DescriptionRoot, { - // - }); - - // src/internal/stack-context.tsx - var import_react29 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var StackContext = (0, import_react29.createContext)(() => {}); - StackContext.displayName = "StackContext"; - function useStackContext() { - return (0, import_react29.useContext)(StackContext); - } - function StackProvider({ children, onUpdate, type, element, enabled }) { - let parentUpdate = useStackContext(); - let notify = useEvent((...args) => { - onUpdate == null ? void 0 : onUpdate(...args); - parentUpdate(...args); - }); - useIsoMorphicEffect(() => { - let shouldNotify = enabled === void 0 || enabled === true; - shouldNotify && notify(0 /* Add */, type, element); - return () => { - shouldNotify && notify(1 /* Remove */, type, element); - }; - }, [notify, type, element, enabled]); - return /* @__PURE__ */ import_react29.default.createElement( - StackContext.Provider, - { value: notify }, - children - ); + editorContext.closeTab(index); + } + }))), addTab)), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-session-header-right" + }, editorContext.tabs.length === 1 && addTab, logo)), /*#__PURE__*/_react.default.createElement("div", { + role: "tabpanel", + id: "graphiql-session", + className: "graphiql-session", + "aria-labelledby": `graphiql-session-tab-${editorContext.activeTabIndex}` + }, /*#__PURE__*/_react.default.createElement("div", { + ref: editorResize.firstRef + }, /*#__PURE__*/_react.default.createElement("div", { + className: `graphiql-editors${editorContext.tabs.length === 1 ? ' full-height' : ''}` + }, /*#__PURE__*/_react.default.createElement("div", { + ref: editorToolsResize.firstRef + }, /*#__PURE__*/_react.default.createElement("section", { + className: "graphiql-query-editor", + "aria-label": "Query Editor" + }, /*#__PURE__*/_react.default.createElement(_react2.QueryEditor, { + editorTheme: props.editorTheme, + keyMap: props.keyMap, + onClickReference: onClickReference, + onCopyQuery: props.onCopyQuery, + onEdit: props.onEditQuery, + readOnly: props.readOnly + }), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-toolbar", + role: "toolbar", + "aria-label": "Editor Commands" + }, /*#__PURE__*/_react.default.createElement(_react2.ExecuteButton, null), toolbar))), /*#__PURE__*/_react.default.createElement("div", { + ref: editorToolsResize.dragBarRef + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-editor-tools" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: activeSecondaryEditor === 'variables' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', + onClick: handleToolsTabClick, + "data-name": "variables" + }, "Variables"), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: activeSecondaryEditor === 'headers' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', + onClick: handleToolsTabClick, + "data-name": "headers" + }, "Headers"), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools' + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + onClick: toggleEditorTools, + "aria-label": editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools', + className: "graphiql-toggle-editor-tools" + }, editorToolsResize.hiddenElement === 'second' ? /*#__PURE__*/_react.default.createElement(_react2.ChevronUpIcon, { + className: "graphiql-chevron-icon", + "aria-hidden": "true" + }) : /*#__PURE__*/_react.default.createElement(_react2.ChevronDownIcon, { + className: "graphiql-chevron-icon", + "aria-hidden": "true" + }))))), /*#__PURE__*/_react.default.createElement("div", { + ref: editorToolsResize.secondRef + }, /*#__PURE__*/_react.default.createElement("section", { + className: "graphiql-editor-tool", + "aria-label": activeSecondaryEditor === 'variables' ? 'Variables' : 'Headers' + }, /*#__PURE__*/_react.default.createElement(_react2.VariableEditor, { + editorTheme: props.editorTheme, + isHidden: activeSecondaryEditor !== 'variables', + keyMap: props.keyMap, + onEdit: props.onEditVariables, + onClickReference: onClickReference, + readOnly: props.readOnly + }), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.HeaderEditor, { + editorTheme: props.editorTheme, + isHidden: activeSecondaryEditor !== 'headers', + keyMap: props.keyMap, + onEdit: props.onEditHeaders, + readOnly: props.readOnly + }))))), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-horizontal-drag-bar", + ref: editorResize.dragBarRef + }), /*#__PURE__*/_react.default.createElement("div", { + ref: editorResize.secondRef + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-response" + }, executionContext.isFetching ? /*#__PURE__*/_react.default.createElement(_react2.Spinner, null) : null, /*#__PURE__*/_react.default.createElement(_react2.ResponseEditor, { + editorTheme: props.editorTheme, + responseTooltip: props.responseTooltip, + keyMap: props.keyMap + }), footer))))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { + open: showDialog === 'short-keys', + onOpenChange: handleOpenShortKeysDialog + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-header" + }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { + className: "graphiql-dialog-title" + }, "Short Keys"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement(ShortKeys, { + keyMap: props.keyMap || 'sublime' + }))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { + open: showDialog === 'settings', + onOpenChange: handleOpenSettingsDialog + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-header" + }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { + className: "graphiql-dialog-title" + }, "Settings"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), props.showPersistHeadersSettings ? /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-title" + }, "Persist headers"), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-caption" + }, "Save headers upon reloading.", ' ', /*#__PURE__*/_react.default.createElement("span", { + className: "graphiql-warning-text" + }, "Only enable if you trust this device."))), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + id: "enable-persist-headers", + className: editorContext.shouldPersistHeaders ? 'active' : '', + "data-value": "true", + onClick: handlePersistHeaders + }, "On"), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + id: "disable-persist-headers", + className: editorContext.shouldPersistHeaders ? '' : 'active', + onClick: handlePersistHeaders + }, "Off"))) : null, !forcedTheme && /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-title" + }, "Theme"), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-caption" + }, "Adjust how the interface appears.")), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + className: theme === null ? 'active' : '', + onClick: handleChangeTheme + }, "System"), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + className: theme === 'light' ? 'active' : '', + "data-theme": "light", + onClick: handleChangeTheme + }, "Light"), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + className: theme === 'dark' ? 'active' : '', + "data-theme": "dark", + onClick: handleChangeTheme + }, "Dark"))), storageContext ? /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-title" + }, "Clear storage"), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-caption" + }, "Remove all locally stored data and start fresh.")), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + state: clearStorageStatus || undefined, + disabled: clearStorageStatus === 'success', + onClick: handleClearData + }, { + success: 'Cleared data', + error: 'Failed' + }[clearStorageStatus] || 'Clear data')) : null))); + } + const modifier = typeof window !== 'undefined' && window.navigator.platform.toLowerCase().indexOf('mac') === 0 ? 'Cmd' : 'Ctrl'; + const SHORT_KEYS = Object.entries({ + 'Search in editor': [modifier, 'F'], + 'Search in documentation': [modifier, 'K'], + 'Execute query': [modifier, 'Enter'], + 'Prettify editors': ['Ctrl', 'Shift', 'P'], + 'Merge fragments definitions into operation definition': ['Ctrl', 'Shift', 'M'], + 'Copy query': ['Ctrl', 'Shift', 'C'], + 'Re-fetch schema using introspection': ['Ctrl', 'Shift', 'R'] + }); + function ShortKeys({ + keyMap + }) { + return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("table", { + className: "graphiql-table" + }, /*#__PURE__*/_react.default.createElement("thead", null, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("th", null, "Short Key"), /*#__PURE__*/_react.default.createElement("th", null, "Function"))), /*#__PURE__*/_react.default.createElement("tbody", null, SHORT_KEYS.map(([title, keys]) => /*#__PURE__*/_react.default.createElement("tr", { + key: title + }, /*#__PURE__*/_react.default.createElement("td", null, keys.map((key, index, array) => /*#__PURE__*/_react.default.createElement(_react.Fragment, { + key: key + }, /*#__PURE__*/_react.default.createElement("code", { + className: "graphiql-key" + }, key), index !== array.length - 1 && ' + '))), /*#__PURE__*/_react.default.createElement("td", null, title))))), /*#__PURE__*/_react.default.createElement("p", null, "The editors use", ' ', /*#__PURE__*/_react.default.createElement("a", { + href: "https://codemirror.net/5/doc/manual.html#keymaps", + target: "_blank", + rel: "noopener noreferrer" + }, "CodeMirror Key Maps"), ' ', "that add more short keys. This instance of Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL uses", ' ', /*#__PURE__*/_react.default.createElement("code", null, keyMap), ".")); + } + + // Configure the UI by providing this Component as a child of GraphiQL. + function GraphiQLLogo(props) { + return /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-logo" + }, props.children || /*#__PURE__*/_react.default.createElement("a", { + className: "graphiql-logo-link", + href: "https://github.com/graphql/graphiql", + target: "_blank", + rel: "noreferrer" + }, "Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL")); + } + GraphiQLLogo.displayName = 'GraphiQLLogo'; + + // Configure the UI by providing this Component as a child of GraphiQL. + function GraphiQLToolbar(props) { + // eslint-disable-next-line react/jsx-no-useless-fragment + return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, props.children); + } + GraphiQLToolbar.displayName = 'GraphiQLToolbar'; + + // Configure the UI by providing this Component as a child of GraphiQL. + function GraphiQLFooter(props) { + return /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-footer" + }, props.children); + } + GraphiQLFooter.displayName = 'GraphiQLFooter'; + + // Determines if the React child is of the same type of the provided React component + function isChildComponentType(child, component) { + var _child$type; + if (child !== null && child !== void 0 && (_child$type = child.type) !== null && _child$type !== void 0 && _child$type.displayName && child.type.displayName === component.displayName) { + return true; + } + return child.type === component; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/index.js": + /*!***************************************************!*\ + !*** ../../graphql-language-service/esm/index.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "CharacterStream", ({ + enumerable: true, + get: function () { + return _parser.CharacterStream; + } + })); + Object.defineProperty(exports, "CompletionItemKind", ({ + enumerable: true, + get: function () { + return _types.CompletionItemKind; + } + })); + Object.defineProperty(exports, "DIAGNOSTIC_SEVERITY", ({ + enumerable: true, + get: function () { + return _interface.DIAGNOSTIC_SEVERITY; + } + })); + Object.defineProperty(exports, "FileChangeTypeKind", ({ + enumerable: true, + get: function () { + return _types.FileChangeTypeKind; + } + })); + Object.defineProperty(exports, "GraphQLDocumentMode", ({ + enumerable: true, + get: function () { + return _parser.GraphQLDocumentMode; + } + })); + Object.defineProperty(exports, "LexRules", ({ + enumerable: true, + get: function () { + return _parser.LexRules; + } + })); + Object.defineProperty(exports, "ParseRules", ({ + enumerable: true, + get: function () { + return _parser.ParseRules; + } + })); + Object.defineProperty(exports, "Position", ({ + enumerable: true, + get: function () { + return _utils.Position; + } + })); + Object.defineProperty(exports, "Range", ({ + enumerable: true, + get: function () { + return _utils.Range; + } + })); + Object.defineProperty(exports, "RuleKinds", ({ + enumerable: true, + get: function () { + return _parser.RuleKinds; + } + })); + Object.defineProperty(exports, "SEVERITY", ({ + enumerable: true, + get: function () { + return _interface.SEVERITY; + } + })); + Object.defineProperty(exports, "SuggestionCommand", ({ + enumerable: true, + get: function () { + return _interface.SuggestionCommand; + } + })); + Object.defineProperty(exports, "canUseDirective", ({ + enumerable: true, + get: function () { + return _interface.canUseDirective; + } + })); + Object.defineProperty(exports, "collectVariables", ({ + enumerable: true, + get: function () { + return _utils.collectVariables; + } + })); + Object.defineProperty(exports, "getASTNodeAtPosition", ({ + enumerable: true, + get: function () { + return _utils.getASTNodeAtPosition; + } + })); + Object.defineProperty(exports, "getAutocompleteSuggestions", ({ + enumerable: true, + get: function () { + return _interface.getAutocompleteSuggestions; + } + })); + Object.defineProperty(exports, "getDefinitionQueryResultForArgument", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForArgument; + } + })); + Object.defineProperty(exports, "getDefinitionQueryResultForDefinitionNode", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForDefinitionNode; + } + })); + Object.defineProperty(exports, "getDefinitionQueryResultForField", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForField; + } + })); + Object.defineProperty(exports, "getDefinitionQueryResultForFragmentSpread", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForFragmentSpread; + } + })); + Object.defineProperty(exports, "getDefinitionQueryResultForNamedType", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForNamedType; + } + })); + Object.defineProperty(exports, "getDefinitionState", ({ + enumerable: true, + get: function () { + return _parser.getDefinitionState; + } + })); + Object.defineProperty(exports, "getDiagnostics", ({ + enumerable: true, + get: function () { + return _interface.getDiagnostics; + } + })); + Object.defineProperty(exports, "getFieldDef", ({ + enumerable: true, + get: function () { + return _parser.getFieldDef; + } + })); + Object.defineProperty(exports, "getFragmentDefinitions", ({ + enumerable: true, + get: function () { + return _interface.getFragmentDefinitions; + } + })); + Object.defineProperty(exports, "getFragmentDependencies", ({ + enumerable: true, + get: function () { + return _utils.getFragmentDependencies; + } + })); + Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ + enumerable: true, + get: function () { + return _utils.getFragmentDependenciesForAST; + } + })); + Object.defineProperty(exports, "getHoverInformation", ({ + enumerable: true, + get: function () { + return _interface.getHoverInformation; + } + })); + Object.defineProperty(exports, "getOperationASTFacts", ({ + enumerable: true, + get: function () { + return _utils.getOperationASTFacts; + } + })); + Object.defineProperty(exports, "getOperationFacts", ({ + enumerable: true, + get: function () { + return _utils.getOperationFacts; + } + })); + Object.defineProperty(exports, "getOutline", ({ + enumerable: true, + get: function () { + return _interface.getOutline; + } + })); + Object.defineProperty(exports, "getQueryFacts", ({ + enumerable: true, + get: function () { + return _utils.getQueryFacts; + } + })); + Object.defineProperty(exports, "getRange", ({ + enumerable: true, + get: function () { + return _interface.getRange; + } + })); + Object.defineProperty(exports, "getTokenAtPosition", ({ + enumerable: true, + get: function () { + return _parser.getTokenAtPosition; + } + })); + Object.defineProperty(exports, "getTypeInfo", ({ + enumerable: true, + get: function () { + return _interface.getTypeInfo; + } + })); + Object.defineProperty(exports, "getVariableCompletions", ({ + enumerable: true, + get: function () { + return _interface.getVariableCompletions; + } + })); + Object.defineProperty(exports, "getVariablesJSONSchema", ({ + enumerable: true, + get: function () { + return _utils.getVariablesJSONSchema; + } + })); + Object.defineProperty(exports, "isIgnored", ({ + enumerable: true, + get: function () { + return _parser.isIgnored; + } + })); + Object.defineProperty(exports, "list", ({ + enumerable: true, + get: function () { + return _parser.list; + } + })); + Object.defineProperty(exports, "offsetToPosition", ({ + enumerable: true, + get: function () { + return _utils.offsetToPosition; + } + })); + Object.defineProperty(exports, "onlineParser", ({ + enumerable: true, + get: function () { + return _parser.onlineParser; + } + })); + Object.defineProperty(exports, "opt", ({ + enumerable: true, + get: function () { + return _parser.opt; + } + })); + Object.defineProperty(exports, "p", ({ + enumerable: true, + get: function () { + return _parser.p; + } + })); + Object.defineProperty(exports, "pointToOffset", ({ + enumerable: true, + get: function () { + return _utils.pointToOffset; + } + })); + Object.defineProperty(exports, "t", ({ + enumerable: true, + get: function () { + return _parser.t; + } + })); + Object.defineProperty(exports, "validateQuery", ({ + enumerable: true, + get: function () { + return _interface.validateQuery; + } + })); + Object.defineProperty(exports, "validateWithCustomRules", ({ + enumerable: true, + get: function () { + return _utils.validateWithCustomRules; + } + })); + var _interface = __webpack_require__(/*! ./interface */ "../../graphql-language-service/esm/interface/index.js"); + var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); + var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/types.js"); + var _utils = __webpack_require__(/*! ./utils */ "../../graphql-language-service/esm/utils/index.js"); + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/autocompleteUtils.js": + /*!*************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/autocompleteUtils.js ***! + \*************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getInsertText = exports.getInputInsertText = exports.getFieldInsertText = void 0; + exports.hintList = hintList; + exports.objectValues = objectValues; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function objectValues(object) { + const keys = Object.keys(object); + const len = keys.length; + const values = new Array(len); + for (let i = 0; i < len; ++i) { + values[i] = object[keys[i]]; + } + return values; + } + function hintList(token, list) { + return filterAndSortList(list, normalizeText(token.string)); + } + function filterAndSortList(list, text) { + if (!text || text.trim() === '' || text.trim() === ':' || text.trim() === '{') { + return filterNonEmpty(list, entry => !entry.isDeprecated); + } + const byProximity = list.map(entry => ({ + proximity: getProximity(normalizeText(entry.label), text), + entry + })); + return filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated).sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.label.length - b.entry.label.length).map(pair => pair.entry); + } + function filterNonEmpty(array, predicate) { + const filtered = array.filter(predicate); + return filtered.length === 0 ? array : filtered; + } + function normalizeText(text) { + return text.toLowerCase().replaceAll(/\W/g, ''); + } + function getProximity(suggestion, text) { + let proximity = lexicalDistance(text, suggestion); + if (suggestion.length > text.length) { + proximity -= suggestion.length - text.length - 1; + proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + } + return proximity; + } + function lexicalDistance(a, b) { + let i; + let j; + const d = []; + const aLength = a.length; + const bLength = b.length; + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); } - - // src/use-sync-external-store-shim/index.ts - var React11 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/use-sync-external-store-shim/useSyncExternalStoreShimClient.ts - var React10 = __toESM(__webpack_require__(/*! react */ "react"), 1); - function isPolyfill(x, y) { - return ( - (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) - ); + } + } + return d[aLength][bLength]; + } + const insertSuffix = n => ` {\n $${n !== null && n !== void 0 ? n : 1}\n}`; + const getInsertText = (prefix, type, fallback) => { + if (!type) { + return fallback !== null && fallback !== void 0 ? fallback : prefix; + } + const namedType = (0, _graphql.getNamedType)(type); + if ((0, _graphql.isObjectType)(namedType) || (0, _graphql.isInputObjectType)(namedType) || (0, _graphql.isListType)(namedType) || (0, _graphql.isAbstractType)(namedType)) { + return prefix + insertSuffix(); + } + return fallback !== null && fallback !== void 0 ? fallback : prefix; + }; + exports.getInsertText = getInsertText; + const getInputInsertText = (prefix, type, fallback) => { + if ((0, _graphql.isListType)(type)) { + const baseType = (0, _graphql.getNamedType)(type.ofType); + return prefix + `[${getInsertText('', baseType, '$1')}]`; + } + return getInsertText(prefix, type, fallback); + }; + exports.getInputInsertText = getInputInsertText; + const getFieldInsertText = field => { + const requiredArgs = field.args.filter(arg => arg.type.toString().endsWith('!')); + if (!requiredArgs.length) { + return; + } + return field.name + `(${requiredArgs.map((arg, i) => `${arg.name}: $${i + 1}`)}) ${getInsertText('', field.type, '\n')}`; + }; + exports.getFieldInsertText = getFieldInsertText; + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js": + /*!**********************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js ***! + \**********************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.SuggestionCommand = void 0; + exports.canUseDirective = canUseDirective; + exports.getAutocompleteSuggestions = getAutocompleteSuggestions; + exports.getFragmentDefinitions = getFragmentDefinitions; + Object.defineProperty(exports, "getTypeInfo", ({ + enumerable: true, + get: function () { + return _parser.getTypeInfo; + } + })); + exports.getVariableCompletions = getVariableCompletions; + Object.defineProperty(exports, "runOnlineParser", ({ + enumerable: true, + get: function () { + return _parser.runOnlineParser; + } + })); + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _types = __webpack_require__(/*! ../types */ "../../graphql-language-service/esm/types.js"); + var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); + var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); + var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); + const SuggestionCommand = exports.SuggestionCommand = { + command: 'editor.action.triggerSuggest', + title: 'Suggestions' + }; + const collectFragmentDefs = op => { + const externalFragments = []; + if (op) { + try { + (0, _graphql.visit)((0, _graphql.parse)(op), { + FragmentDefinition(def) { + externalFragments.push(def); + } + }); + } catch (_a) { + return []; + } + } + return externalFragments; + }; + function getAutocompleteSuggestions(schema, queryText, cursor, contextToken, fragmentDefs, options) { + var _a; + const opts = Object.assign(Object.assign({}, options), { + schema + }); + const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken, options); + if (!context) { + return []; + } + const { + state, + typeInfo, + mode, + token + } = context; + const { + kind, + step, + prevState + } = state; + if (kind === _parser.RuleKinds.DOCUMENT) { + if (mode === _parser.GraphQLDocumentMode.TYPE_SYSTEM) { + return getSuggestionsForTypeSystemDefinitions(token); + } + if (mode === _parser.GraphQLDocumentMode.EXECUTABLE) { + return getSuggestionsForExecutableDefinitions(token); + } + return getSuggestionsForUnknownDocumentMode(token); + } + if (kind === _parser.RuleKinds.EXTEND_DEF) { + return getSuggestionsForExtensionDefinitions(token); + } + if (((_a = prevState === null || prevState === void 0 ? void 0 : prevState.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.EXTENSION_DEFINITION && state.name) { + return (0, _autocompleteUtils.hintList)(token, []); + } + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.SCALAR_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isScalarType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); + } + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.OBJECT_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isObjectType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); + } + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INTERFACE_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInterfaceType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); + } + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.UNION_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isUnionType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); + } + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.ENUM_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isEnumType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); + } + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInputObjectType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); + } + if (kind === _parser.RuleKinds.IMPLEMENTS || kind === _parser.RuleKinds.NAMED_TYPE && (prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _parser.RuleKinds.IMPLEMENTS) { + return getSuggestionsForImplements(token, state, schema, queryText, typeInfo); + } + if (kind === _parser.RuleKinds.SELECTION_SET || kind === _parser.RuleKinds.FIELD || kind === _parser.RuleKinds.ALIASED_FIELD) { + return getSuggestionsForFieldNames(token, typeInfo, opts); + } + if (kind === _parser.RuleKinds.ARGUMENTS || kind === _parser.RuleKinds.ARGUMENT && step === 0) { + const { + argDefs + } = typeInfo; + if (argDefs) { + return (0, _autocompleteUtils.hintList)(token, argDefs.map(argDef => { + var _a; + return { + label: argDef.name, + insertText: (0, _autocompleteUtils.getInputInsertText)(argDef.name + ': ', argDef.type), + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + command: SuggestionCommand, + labelDetails: { + detail: ' ' + String(argDef.type) + }, + documentation: (_a = argDef.description) !== null && _a !== void 0 ? _a : undefined, + kind: _types.CompletionItemKind.Variable, + type: argDef.type + }; + })); + } + } + if ((kind === _parser.RuleKinds.OBJECT_VALUE || kind === _parser.RuleKinds.OBJECT_FIELD && step === 0) && typeInfo.objectFieldDefs) { + const objectFields = (0, _autocompleteUtils.objectValues)(typeInfo.objectFieldDefs); + const completionKind = kind === _parser.RuleKinds.OBJECT_VALUE ? _types.CompletionItemKind.Value : _types.CompletionItemKind.Field; + return (0, _autocompleteUtils.hintList)(token, objectFields.map(field => { + var _a; + return { + label: field.name, + detail: String(field.type), + documentation: (_a = field === null || field === void 0 ? void 0 : field.description) !== null && _a !== void 0 ? _a : undefined, + kind: completionKind, + type: field.type, + insertText: (0, _autocompleteUtils.getInputInsertText)(field.name + ': ', field.type), + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + command: SuggestionCommand + }; + })); + } + if (kind === _parser.RuleKinds.ENUM_VALUE || kind === _parser.RuleKinds.LIST_VALUE && step === 1 || kind === _parser.RuleKinds.OBJECT_FIELD && step === 2 || kind === _parser.RuleKinds.ARGUMENT && step === 2) { + return getSuggestionsForInputValues(token, typeInfo, queryText, schema); + } + if (kind === _parser.RuleKinds.VARIABLE && step === 1) { + const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); + const variableDefinitions = getVariableCompletions(queryText, schema, token); + return (0, _autocompleteUtils.hintList)(token, variableDefinitions.filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name))); + } + if (kind === _parser.RuleKinds.TYPE_CONDITION && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState != null && prevState.kind === _parser.RuleKinds.TYPE_CONDITION) { + return getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, kind); + } + if (kind === _parser.RuleKinds.FRAGMENT_SPREAD && step === 1) { + return getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, Array.isArray(fragmentDefs) ? fragmentDefs : collectFragmentDefs(fragmentDefs)); + } + const unwrappedState = unwrapType(state); + if (unwrappedState.kind === _parser.RuleKinds.FIELD_DEF) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isOutputType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n' : type.name, + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation + }))); + } + if (unwrappedState.kind === _parser.RuleKinds.INPUT_VALUE_DEF && step === 2) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isInputType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n$1' : type.name, + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet + }))); + } + if (kind === _parser.RuleKinds.VARIABLE_DEFINITION && step === 2 || kind === _parser.RuleKinds.LIST_TYPE && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState && (prevState.kind === _parser.RuleKinds.VARIABLE_DEFINITION || prevState.kind === _parser.RuleKinds.LIST_TYPE || prevState.kind === _parser.RuleKinds.NON_NULL_TYPE)) { + return getSuggestionsForVariableDefinition(token, schema, kind); + } + if (kind === _parser.RuleKinds.DIRECTIVE) { + return getSuggestionsForDirective(token, state, schema, kind); + } + if (kind === _parser.RuleKinds.DIRECTIVE_DEF) { + return getSuggestionsForDirectiveArguments(token, state, schema, kind); + } + return []; + } + const typeSystemCompletionItems = [{ + label: 'type', + kind: _types.CompletionItemKind.Function + }, { + label: 'interface', + kind: _types.CompletionItemKind.Function + }, { + label: 'union', + kind: _types.CompletionItemKind.Function + }, { + label: 'input', + kind: _types.CompletionItemKind.Function + }, { + label: 'scalar', + kind: _types.CompletionItemKind.Function + }, { + label: 'schema', + kind: _types.CompletionItemKind.Function + }]; + const executableCompletionItems = [{ + label: 'query', + kind: _types.CompletionItemKind.Function + }, { + label: 'mutation', + kind: _types.CompletionItemKind.Function + }, { + label: 'subscription', + kind: _types.CompletionItemKind.Function + }, { + label: 'fragment', + kind: _types.CompletionItemKind.Function + }, { + label: '{', + kind: _types.CompletionItemKind.Constructor + }]; + function getSuggestionsForTypeSystemDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, [{ + label: 'extend', + kind: _types.CompletionItemKind.Function + }, ...typeSystemCompletionItems]); + } + function getSuggestionsForExecutableDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, executableCompletionItems); + } + function getSuggestionsForUnknownDocumentMode(token) { + return (0, _autocompleteUtils.hintList)(token, [{ + label: 'extend', + kind: _types.CompletionItemKind.Function + }, ...executableCompletionItems, ...typeSystemCompletionItems]); + } + function getSuggestionsForExtensionDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, typeSystemCompletionItems); + } + function getSuggestionsForFieldNames(token, typeInfo, options) { + var _a; + if (typeInfo.parentType) { + const { + parentType + } = typeInfo; + let fields = []; + if ('getFields' in parentType) { + fields = (0, _autocompleteUtils.objectValues)(parentType.getFields()); + } + if ((0, _graphql.isCompositeType)(parentType)) { + fields.push(_graphql.TypeNameMetaFieldDef); + } + if (parentType === ((_a = options === null || options === void 0 ? void 0 : options.schema) === null || _a === void 0 ? void 0 : _a.getQueryType())) { + fields.push(_graphql.SchemaMetaFieldDef, _graphql.TypeMetaFieldDef); + } + return (0, _autocompleteUtils.hintList)(token, fields.map((field, index) => { + var _a; + const suggestion = { + sortText: String(index) + field.name, + label: field.name, + detail: String(field.type), + documentation: (_a = field.description) !== null && _a !== void 0 ? _a : undefined, + deprecated: Boolean(field.deprecationReason), + isDeprecated: Boolean(field.deprecationReason), + deprecationReason: field.deprecationReason, + kind: _types.CompletionItemKind.Field, + labelDetails: { + detail: ' ' + field.type.toString() + }, + type: field.type + }; + if (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) { + suggestion.insertText = (0, _autocompleteUtils.getFieldInsertText)(field); + if (!suggestion.insertText) { + suggestion.insertText = (0, _autocompleteUtils.getInsertText)(field.name, field.type, field.name + (token.state.needsAdvance ? '' : '\n')); + } + if (suggestion.insertText) { + suggestion.insertTextFormat = _types.InsertTextFormat.Snippet; + suggestion.insertTextMode = _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation; + suggestion.command = SuggestionCommand; + } } - var is = typeof Object.is === "function" ? Object.is : isPolyfill; - var { - useState: useState8, - useEffect: useEffect14, - useLayoutEffect: useLayoutEffect2, - useDebugValue, - } = React10; - var didWarnOld18Alpha = false; - var didWarnUncachedGetSnapshot = false; - function useSyncExternalStore( - subscribe, - getSnapshot, - getServerSnapshot - ) { - if (true) { - if (!didWarnOld18Alpha) { - if ("startTransition" in React10) { - didWarnOld18Alpha = true; - console.error( - "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." - ); - } + return suggestion; + })); + } + return []; + } + function getSuggestionsForInputValues(token, typeInfo, queryText, schema) { + const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); + const queryVariables = getVariableCompletions(queryText, schema, token).filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name)); + if (namedInputType instanceof _graphql.GraphQLEnumType) { + const values = namedInputType.getValues(); + return (0, _autocompleteUtils.hintList)(token, values.map(value => { + var _a; + return { + label: value.name, + detail: String(namedInputType), + documentation: (_a = value.description) !== null && _a !== void 0 ? _a : undefined, + deprecated: Boolean(value.deprecationReason), + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + kind: _types.CompletionItemKind.EnumMember, + type: namedInputType + }; + }).concat(queryVariables)); + } + if (namedInputType === _graphql.GraphQLBoolean) { + return (0, _autocompleteUtils.hintList)(token, queryVariables.concat([{ + label: 'true', + detail: String(_graphql.GraphQLBoolean), + documentation: 'Not false.', + kind: _types.CompletionItemKind.Variable, + type: _graphql.GraphQLBoolean + }, { + label: 'false', + detail: String(_graphql.GraphQLBoolean), + documentation: 'Not true.', + kind: _types.CompletionItemKind.Variable, + type: _graphql.GraphQLBoolean + }])); + } + return queryVariables; + } + function getSuggestionsForImplements(token, tokenState, schema, documentText, typeInfo) { + if (tokenState.needsSeparator) { + return []; + } + const typeMap = schema.getTypeMap(); + const schemaInterfaces = (0, _autocompleteUtils.objectValues)(typeMap).filter(_graphql.isInterfaceType); + const schemaInterfaceNames = schemaInterfaces.map(({ + name + }) => name); + const inlineInterfaces = new Set(); + (0, _parser.runOnlineParser)(documentText, (_, state) => { + var _a, _b, _c, _d, _e; + if (state.name) { + if (state.kind === _parser.RuleKinds.INTERFACE_DEF && !schemaInterfaceNames.includes(state.name)) { + inlineInterfaces.add(state.name); + } + if (state.kind === _parser.RuleKinds.NAMED_TYPE && ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.IMPLEMENTS) { + if (typeInfo.interfaceDef) { + const existingType = (_b = typeInfo.interfaceDef) === null || _b === void 0 ? void 0 : _b.getInterfaces().find(({ + name + }) => name === state.name); + if (existingType) { + return; } - } - const value = getSnapshot(); - if (true) { - if (!didWarnUncachedGetSnapshot) { - const cachedValue = getSnapshot(); - if (!is(value, cachedValue)) { - console.error( - "The result of getSnapshot should be cached to avoid an infinite loop" - ); - didWarnUncachedGetSnapshot = true; - } + const type = schema.getType(state.name); + const interfaceConfig = (_c = typeInfo.interfaceDef) === null || _c === void 0 ? void 0 : _c.toConfig(); + typeInfo.interfaceDef = new _graphql.GraphQLInterfaceType(Object.assign(Object.assign({}, interfaceConfig), { + interfaces: [...interfaceConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ + name: state.name, + fields: {} + })] + })); + } else if (typeInfo.objectTypeDef) { + const existingType = (_d = typeInfo.objectTypeDef) === null || _d === void 0 ? void 0 : _d.getInterfaces().find(({ + name + }) => name === state.name); + if (existingType) { + return; } + const type = schema.getType(state.name); + const objectTypeConfig = (_e = typeInfo.objectTypeDef) === null || _e === void 0 ? void 0 : _e.toConfig(); + typeInfo.objectTypeDef = new _graphql.GraphQLObjectType(Object.assign(Object.assign({}, objectTypeConfig), { + interfaces: [...objectTypeConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ + name: state.name, + fields: {} + })] + })); } - const [{ inst }, forceUpdate] = useState8({ - inst: { value, getSnapshot }, - }); - useLayoutEffect2(() => { - inst.value = value; - inst.getSnapshot = getSnapshot; - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - }, [subscribe, value, getSnapshot]); - useEffect14(() => { - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - const handleStoreChange = () => { - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - }; - return subscribe(handleStoreChange); - }, [subscribe]); - useDebugValue(value); - return value; } - function checkIfSnapshotChanged(inst) { - const latestGetSnapshot = inst.getSnapshot; - const prevValue = inst.value; - try { - const nextValue = latestGetSnapshot(); - return !is(prevValue, nextValue); - } catch (error) { - return true; + } + }); + const currentTypeToExtend = typeInfo.interfaceDef || typeInfo.objectTypeDef; + const siblingInterfaces = (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.getInterfaces()) || []; + const siblingInterfaceNames = siblingInterfaces.map(({ + name + }) => name); + const possibleInterfaces = schemaInterfaces.concat([...inlineInterfaces].map(name => ({ + name + }))).filter(({ + name + }) => name !== (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.name) && !siblingInterfaceNames.includes(name)); + return (0, _autocompleteUtils.hintList)(token, possibleInterfaces.map(type => { + const result = { + label: type.name, + kind: _types.CompletionItemKind.Interface, + type + }; + if (type === null || type === void 0 ? void 0 : type.description) { + result.documentation = type.description; + } + return result; + })); + } + function getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, _kind) { + let possibleTypes; + if (typeInfo.parentType) { + if ((0, _graphql.isAbstractType)(typeInfo.parentType)) { + const abstractType = (0, _graphql.assertAbstractType)(typeInfo.parentType); + const possibleObjTypes = schema.getPossibleTypes(abstractType); + const possibleIfaceMap = Object.create(null); + for (const type of possibleObjTypes) { + for (const iface of type.getInterfaces()) { + possibleIfaceMap[iface.name] = iface; } } - - // src/use-sync-external-store-shim/useSyncExternalStoreShimServer.ts - function useSyncExternalStore2( - subscribe, - getSnapshot, - getServerSnapshot - ) { - return getSnapshot(); - } - - // src/use-sync-external-store-shim/index.ts - var canUseDOM = !!( - typeof window !== "undefined" && - typeof window.document !== "undefined" && - typeof window.document.createElement !== "undefined" - ); - var isServerEnvironment = !canUseDOM; - var shim = isServerEnvironment - ? useSyncExternalStore2 - : useSyncExternalStore; - var useSyncExternalStore3 = - "useSyncExternalStore" in React11 - ? ((r) => r.useSyncExternalStore)(React11) - : shim; - - // src/hooks/use-store.ts - function useStore(store) { - return useSyncExternalStore3( - store.subscribe, - store.getSnapshot, - store.getSnapshot - ); - } - - // src/utils/store.ts - function createStore(initial, actions) { - let state = initial(); - let listeners = /* @__PURE__ */ new Set(); - return { - getSnapshot() { - return state; - }, - subscribe(onChange) { - listeners.add(onChange); - return () => listeners.delete(onChange); - }, - dispatch(key, ...args) { - let newState = actions[key].call(state, ...args); - if (newState) { - state = newState; - listeners.forEach((listener) => listener()); - } - }, - }; - } - - // src/hooks/document-overflow/adjust-scrollbar-padding.ts - function adjustScrollbarPadding() { - let scrollbarWidthBefore; - return { - before({ doc }) { - var _a3; - let documentElement = doc.documentElement; - let ownerWindow = (_a3 = doc.defaultView) != null ? _a3 : window; - scrollbarWidthBefore = - ownerWindow.innerWidth - documentElement.clientWidth; - }, - after({ doc, d }) { - let documentElement = doc.documentElement; - let scrollbarWidthAfter = - documentElement.clientWidth - documentElement.offsetWidth; - let scrollbarWidth = scrollbarWidthBefore - scrollbarWidthAfter; - d.style(documentElement, "paddingRight", `${scrollbarWidth}px`); - }, - }; + possibleTypes = possibleObjTypes.concat((0, _autocompleteUtils.objectValues)(possibleIfaceMap)); + } else { + possibleTypes = [typeInfo.parentType]; + } + } else { + const typeMap = schema.getTypeMap(); + possibleTypes = (0, _autocompleteUtils.objectValues)(typeMap).filter(type => (0, _graphql.isCompositeType)(type) && !type.name.startsWith('__')); + } + return (0, _autocompleteUtils.hintList)(token, possibleTypes.map(type => { + const namedType = (0, _graphql.getNamedType)(type); + return { + label: String(type), + documentation: (namedType === null || namedType === void 0 ? void 0 : namedType.description) || '', + kind: _types.CompletionItemKind.Field + }; + })); + } + function getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, fragmentDefs) { + if (!queryText) { + return []; + } + const typeMap = schema.getTypeMap(); + const defState = (0, _parser.getDefinitionState)(token.state); + const fragments = getFragmentDefinitions(queryText); + if (fragmentDefs && fragmentDefs.length > 0) { + fragments.push(...fragmentDefs); + } + const relevantFrags = fragments.filter(frag => typeMap[frag.typeCondition.name.value] && !(defState && defState.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && defState.name === frag.name.value) && (0, _graphql.isCompositeType)(typeInfo.parentType) && (0, _graphql.isCompositeType)(typeMap[frag.typeCondition.name.value]) && (0, _graphql.doTypesOverlap)(schema, typeInfo.parentType, typeMap[frag.typeCondition.name.value])); + return (0, _autocompleteUtils.hintList)(token, relevantFrags.map(frag => ({ + label: frag.name.value, + detail: String(typeMap[frag.typeCondition.name.value]), + documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, + labelDetails: { + detail: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}` + }, + kind: _types.CompletionItemKind.Field, + type: typeMap[frag.typeCondition.name.value] + }))); + } + const getParentDefinition = (state, kind) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + if (((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === kind) { + return state.prevState; + } + if (((_c = (_b = state.prevState) === null || _b === void 0 ? void 0 : _b.prevState) === null || _c === void 0 ? void 0 : _c.kind) === kind) { + return state.prevState.prevState; + } + if (((_f = (_e = (_d = state.prevState) === null || _d === void 0 ? void 0 : _d.prevState) === null || _e === void 0 ? void 0 : _e.prevState) === null || _f === void 0 ? void 0 : _f.kind) === kind) { + return state.prevState.prevState.prevState; + } + if (((_k = (_j = (_h = (_g = state.prevState) === null || _g === void 0 ? void 0 : _g.prevState) === null || _h === void 0 ? void 0 : _h.prevState) === null || _j === void 0 ? void 0 : _j.prevState) === null || _k === void 0 ? void 0 : _k.kind) === kind) { + return state.prevState.prevState.prevState.prevState; + } + }; + function getVariableCompletions(queryText, schema, token) { + let variableName = null; + let variableType; + const definitions = Object.create({}); + (0, _parser.runOnlineParser)(queryText, (_, state) => { + var _a; + if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.VARIABLE && state.name) { + variableName = state.name; + } + if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.NAMED_TYPE && variableName) { + const parentDefinition = getParentDefinition(state, _parser.RuleKinds.TYPE); + if (parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type) { + variableType = schema.getType(parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type); } - - // src/hooks/document-overflow/handle-ios-locking.ts - function handleIOSLocking() { - if (!isIOS()) { - return {}; + } + if (variableName && variableType && !definitions[variableName]) { + const replaceString = token.string === '$' || ((_a = token === null || token === void 0 ? void 0 : token.state) === null || _a === void 0 ? void 0 : _a.kind) === 'Variable' ? variableName : '$' + variableName; + definitions[variableName] = { + detail: variableType.toString(), + insertText: replaceString, + label: '$' + variableName, + rawInsert: replaceString, + type: variableType, + kind: _types.CompletionItemKind.Variable + }; + variableName = null; + variableType = null; + } + }); + return (0, _autocompleteUtils.objectValues)(definitions); + } + function getFragmentDefinitions(queryText) { + const fragmentDefs = []; + (0, _parser.runOnlineParser)(queryText, (_, state) => { + if (state.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && state.name && state.type) { + fragmentDefs.push({ + kind: _parser.RuleKinds.FRAGMENT_DEFINITION, + name: { + kind: _graphql.Kind.NAME, + value: state.name + }, + selectionSet: { + kind: _parser.RuleKinds.SELECTION_SET, + selections: [] + }, + typeCondition: { + kind: _parser.RuleKinds.NAMED_TYPE, + name: { + kind: _graphql.Kind.NAME, + value: state.type + } } - let scrollPosition; - return { - before() { - scrollPosition = window.pageYOffset; - }, - after({ doc, d, meta }) { - function inAllowedContainer(el) { - return meta.containers - .flatMap((resolve) => resolve()) - .some((container) => container.contains(el)); - } - d.style(doc.body, "marginTop", `-${scrollPosition}px`); - window.scrollTo(0, 0); - let scrollToElement = null; - d.addEventListener( - doc, - "click", - (e) => { - if (!(e.target instanceof HTMLElement)) { - return; - } - try { - let anchor = e.target.closest("a"); - if (!anchor) return; - let { hash } = new URL(anchor.href); - let el = doc.querySelector(hash); - if (el && !inAllowedContainer(el)) { - scrollToElement = el; - } - } catch (err) {} - }, - true - ); - d.addEventListener( - doc, - "touchmove", - (e) => { - if ( - e.target instanceof HTMLElement && - !inAllowedContainer(e.target) - ) { - e.preventDefault(); - } - }, - { passive: false } - ); - d.add(() => { - window.scrollTo(0, window.pageYOffset + scrollPosition); - if (scrollToElement && scrollToElement.isConnected) { - scrollToElement.scrollIntoView({ block: "nearest" }); - scrollToElement = null; - } - }); - }, - }; + }); + } + }); + return fragmentDefs; + } + function getSuggestionsForVariableDefinition(token, schema, _kind) { + const inputTypeMap = schema.getTypeMap(); + const inputTypes = (0, _autocompleteUtils.objectValues)(inputTypeMap).filter(_graphql.isInputType); + return (0, _autocompleteUtils.hintList)(token, inputTypes.map(type => ({ + label: type.name, + documentation: (type === null || type === void 0 ? void 0 : type.description) || '', + kind: _types.CompletionItemKind.Variable + }))); + } + function getSuggestionsForDirective(token, state, schema, _kind) { + var _a; + if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) { + const directives = schema.getDirectives().filter(directive => canUseDirective(state.prevState, directive)); + return (0, _autocompleteUtils.hintList)(token, directives.map(directive => ({ + label: directive.name, + documentation: (directive === null || directive === void 0 ? void 0 : directive.description) || '', + kind: _types.CompletionItemKind.Function + }))); + } + return []; + } + function getSuggestionsForDirectiveArguments(token, state, schema, _kind) { + const directive = schema.getDirectives().find(d => d.name === state.name); + return (0, _autocompleteUtils.hintList)(token, (directive === null || directive === void 0 ? void 0 : directive.args.map(arg => ({ + label: arg.name, + documentation: arg.description || '', + kind: _types.CompletionItemKind.Field + }))) || []); + } + function canUseDirective(state, directive) { + if (!(state === null || state === void 0 ? void 0 : state.kind)) { + return false; + } + const { + kind, + prevState + } = state; + const { + locations + } = directive; + switch (kind) { + case _parser.RuleKinds.QUERY: + return locations.includes(_graphql.DirectiveLocation.QUERY); + case _parser.RuleKinds.MUTATION: + return locations.includes(_graphql.DirectiveLocation.MUTATION); + case _parser.RuleKinds.SUBSCRIPTION: + return locations.includes(_graphql.DirectiveLocation.SUBSCRIPTION); + case _parser.RuleKinds.FIELD: + case _parser.RuleKinds.ALIASED_FIELD: + return locations.includes(_graphql.DirectiveLocation.FIELD); + case _parser.RuleKinds.FRAGMENT_DEFINITION: + return locations.includes(_graphql.DirectiveLocation.FRAGMENT_DEFINITION); + case _parser.RuleKinds.FRAGMENT_SPREAD: + return locations.includes(_graphql.DirectiveLocation.FRAGMENT_SPREAD); + case _parser.RuleKinds.INLINE_FRAGMENT: + return locations.includes(_graphql.DirectiveLocation.INLINE_FRAGMENT); + case _parser.RuleKinds.SCHEMA_DEF: + return locations.includes(_graphql.DirectiveLocation.SCHEMA); + case _parser.RuleKinds.SCALAR_DEF: + return locations.includes(_graphql.DirectiveLocation.SCALAR); + case _parser.RuleKinds.OBJECT_TYPE_DEF: + return locations.includes(_graphql.DirectiveLocation.OBJECT); + case _parser.RuleKinds.FIELD_DEF: + return locations.includes(_graphql.DirectiveLocation.FIELD_DEFINITION); + case _parser.RuleKinds.INTERFACE_DEF: + return locations.includes(_graphql.DirectiveLocation.INTERFACE); + case _parser.RuleKinds.UNION_DEF: + return locations.includes(_graphql.DirectiveLocation.UNION); + case _parser.RuleKinds.ENUM_DEF: + return locations.includes(_graphql.DirectiveLocation.ENUM); + case _parser.RuleKinds.ENUM_VALUE: + return locations.includes(_graphql.DirectiveLocation.ENUM_VALUE); + case _parser.RuleKinds.INPUT_DEF: + return locations.includes(_graphql.DirectiveLocation.INPUT_OBJECT); + case _parser.RuleKinds.INPUT_VALUE_DEF: + const prevStateKind = prevState === null || prevState === void 0 ? void 0 : prevState.kind; + switch (prevStateKind) { + case _parser.RuleKinds.ARGUMENTS_DEF: + return locations.includes(_graphql.DirectiveLocation.ARGUMENT_DEFINITION); + case _parser.RuleKinds.INPUT_DEF: + return locations.includes(_graphql.DirectiveLocation.INPUT_FIELD_DEFINITION); } - - // src/hooks/document-overflow/prevent-scroll.ts - function preventScroll() { - return { - before({ doc, d }) { - d.style(doc.documentElement, "overflow", "hidden"); - }, - }; + } + return false; + } + function unwrapType(state) { + if (state.prevState && state.kind && [_parser.RuleKinds.NAMED_TYPE, _parser.RuleKinds.LIST_TYPE, _parser.RuleKinds.TYPE, _parser.RuleKinds.NON_NULL_TYPE].includes(state.kind)) { + return unwrapType(state.prevState); + } + return state; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/getDefinition.js": + /*!*********************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getDefinition.js ***! + \*********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.LANGUAGE = void 0; + exports.getDefinitionQueryResultForArgument = getDefinitionQueryResultForArgument; + exports.getDefinitionQueryResultForDefinitionNode = getDefinitionQueryResultForDefinitionNode; + exports.getDefinitionQueryResultForField = getDefinitionQueryResultForField; + exports.getDefinitionQueryResultForFragmentSpread = getDefinitionQueryResultForFragmentSpread; + exports.getDefinitionQueryResultForNamedType = getDefinitionQueryResultForNamedType; + var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); + var __awaiter = void 0 && (void 0).__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); } - - // src/hooks/document-overflow/overflow-store.ts - function buildMeta(fns) { - let tmp = {}; - for (let fn of fns) { - Object.assign(tmp, fn(tmp)); - } - return tmp; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - var overflows = createStore(() => /* @__PURE__ */ new Map(), { - PUSH(doc, meta) { - var _a3; - let entry = - (_a3 = this.get(doc)) != null - ? _a3 - : { - doc, - count: 0, - d: disposables(), - meta: /* @__PURE__ */ new Set(), - }; - entry.count++; - entry.meta.add(meta); - this.set(doc, entry); - return this; - }, - POP(doc, meta) { - let entry = this.get(doc); - if (entry) { - entry.count--; - entry.meta.delete(meta); - } - return this; - }, - SCROLL_PREVENT({ doc, d, meta }) { - let ctx = { - doc, - d, - meta: buildMeta(meta), - }; - let steps = [ - handleIOSLocking(), - adjustScrollbarPadding(), - preventScroll(), - ]; - steps.forEach(({ before }) => - before == null ? void 0 : before(ctx) - ); - steps.forEach(({ after }) => (after == null ? void 0 : after(ctx))); - }, - SCROLL_ALLOW({ d }) { - d.dispose(); - }, - TEARDOWN({ doc }) { - this.delete(doc); - }, + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + const LANGUAGE = exports.LANGUAGE = 'GraphQL'; + function assert(value, message) { + if (!value) { + throw new Error(message); + } + } + function getRange(text, node) { + const location = node.loc; + assert(location, 'Expected ASTNode to have a location.'); + return (0, _utils.locToRange)(text, location); + } + function getPosition(text, node) { + const location = node.loc; + assert(location, 'Expected ASTNode to have a location.'); + return (0, _utils.offsetToPosition)(text, location.start); + } + function getDefinitionQueryResultForNamedType(text, node, dependencies) { + return __awaiter(this, void 0, void 0, function* () { + const name = node.name.value; + const defNodes = dependencies.filter(({ + definition + }) => definition.name && definition.name.value === name); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL type ${name}`); + } + const definitions = defNodes.map(({ + filePath, + content, + definition + }) => getDefinitionForNodeDefinition(filePath || '', content, definition)); + return { + definitions, + queryRange: definitions.map(_ => getRange(text, node)), + printedName: name + }; + }); + } + function getDefinitionQueryResultForField(fieldName, typeName, dependencies) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const defNodes = dependencies.filter(({ + definition + }) => definition.name && definition.name.value === typeName); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL type ${typeName}`); + } + const definitions = []; + for (const { + filePath, + content, + definition + } of defNodes) { + const fieldDefinition = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName); + if (fieldDefinition == null) { + continue; + } + definitions.push(getDefinitionForFieldDefinition(filePath || '', content, fieldDefinition)); + } + return { + definitions, + queryRange: [], + printedName: [typeName, fieldName].join('.') + }; + }); + } + function getDefinitionQueryResultForArgument(argumentName, fieldName, typeName, dependencies) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const definitions = []; + for (const { + filePath, + content, + definition + } of dependencies) { + const argDefinition = (_c = (_b = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName)) === null || _b === void 0 ? void 0 : _b.arguments) === null || _c === void 0 ? void 0 : _c.find(item => item.name.value === argumentName); + if (argDefinition == null) { + continue; + } + definitions.push(getDefinitionForArgumentDefinition(filePath || '', content, argDefinition)); + } + return { + definitions, + queryRange: [], + printedName: `${[typeName, fieldName].join('.')}(${argumentName})` + }; + }); + } + function getDefinitionQueryResultForFragmentSpread(text, fragment, dependencies) { + return __awaiter(this, void 0, void 0, function* () { + const name = fragment.name.value; + const defNodes = dependencies.filter(({ + definition + }) => definition.name.value === name); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL fragment ${name}`); + } + const definitions = defNodes.map(({ + filePath, + content, + definition + }) => getDefinitionForFragmentDefinition(filePath || '', content, definition)); + return { + definitions, + queryRange: definitions.map(_ => getRange(text, fragment)), + printedName: name + }; + }); + } + function getDefinitionQueryResultForDefinitionNode(path, text, definition) { + var _a; + return { + definitions: [getDefinitionForFragmentDefinition(path, text, definition)], + queryRange: definition.name ? [getRange(text, definition.name)] : [], + printedName: (_a = definition.name) === null || _a === void 0 ? void 0 : _a.value + }; + } + function getDefinitionForFragmentDefinition(path, text, definition) { + const { + name + } = definition; + if (!name) { + throw new Error('Expected ASTNode to have a Name.'); + } + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; + } + function getDefinitionForNodeDefinition(path, text, definition) { + const { + name + } = definition; + assert(name, 'Expected ASTNode to have a Name.'); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; + } + function getDefinitionForFieldDefinition(path, text, definition) { + const { + name + } = definition; + assert(name, 'Expected ASTNode to have a Name.'); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; + } + function getDefinitionForArgumentDefinition(path, text, definition) { + const { + name + } = definition; + assert(name, 'Expected ASTNode to have a Name.'); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/getDiagnostics.js": + /*!**********************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getDiagnostics.js ***! + \**********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.SEVERITY = exports.DIAGNOSTIC_SEVERITY = void 0; + exports.getDiagnostics = getDiagnostics; + exports.getRange = getRange; + exports.validateQuery = validateQuery; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); + var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); + const SEVERITY = exports.SEVERITY = { + Error: 'Error', + Warning: 'Warning', + Information: 'Information', + Hint: 'Hint' + }; + const DIAGNOSTIC_SEVERITY = exports.DIAGNOSTIC_SEVERITY = { + [SEVERITY.Error]: 1, + [SEVERITY.Warning]: 2, + [SEVERITY.Information]: 3, + [SEVERITY.Hint]: 4 + }; + const invariant = (condition, message) => { + if (!condition) { + throw new Error(message); + } + }; + function getDiagnostics(query, schema = null, customRules, isRelayCompatMode, externalFragments) { + var _a, _b; + let ast = null; + let fragments = ''; + if (externalFragments) { + fragments = typeof externalFragments === 'string' ? externalFragments : externalFragments.reduce((acc, node) => acc + (0, _graphql.print)(node) + '\n\n', ''); + } + const enhancedQuery = fragments ? `${query}\n\n${fragments}` : query; + try { + ast = (0, _graphql.parse)(enhancedQuery); + } catch (error) { + if (error instanceof _graphql.GraphQLError) { + const range = getRange((_b = (_a = error.locations) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : { + line: 0, + column: 0 + }, enhancedQuery); + return [{ + severity: DIAGNOSTIC_SEVERITY.Error, + message: error.message, + source: 'GraphQL: Syntax', + range + }]; + } + throw error; + } + return validateQuery(ast, schema, customRules, isRelayCompatMode); + } + function validateQuery(ast, schema = null, customRules, isRelayCompatMode) { + if (!schema) { + return []; + } + const validationErrorAnnotations = (0, _utils.validateWithCustomRules)(schema, ast, customRules, isRelayCompatMode).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Error, 'Validation')); + const deprecationWarningAnnotations = (0, _graphql.validate)(schema, ast, [_graphql.NoDeprecatedCustomRule]).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Warning, 'Deprecation')); + return validationErrorAnnotations.concat(deprecationWarningAnnotations); + } + function annotations(error, severity, type) { + if (!error.nodes) { + return []; + } + const highlightedNodes = []; + for (const [i, node] of error.nodes.entries()) { + const highlightNode = node.kind !== 'Variable' && 'name' in node && node.name !== undefined ? node.name : 'variable' in node && node.variable !== undefined ? node.variable : node; + if (highlightNode) { + invariant(error.locations, 'GraphQL validation error requires locations.'); + const loc = error.locations[i]; + const highlightLoc = getLocation(highlightNode); + const end = loc.column + (highlightLoc.end - highlightLoc.start); + highlightedNodes.push({ + source: `GraphQL: ${type}`, + message: error.message, + severity, + range: new _utils.Range(new _utils.Position(loc.line - 1, loc.column - 1), new _utils.Position(loc.line - 1, end)) }); - overflows.subscribe(() => { - let docs = overflows.getSnapshot(); - let styles = /* @__PURE__ */ new Map(); - for (let [doc] of docs) { - styles.set(doc, doc.documentElement.style.overflow); - } - for (let entry of docs.values()) { - let isHidden = styles.get(entry.doc) === "hidden"; - let isLocked = entry.count !== 0; - let willChange = (isLocked && !isHidden) || (!isLocked && isHidden); - if (willChange) { - overflows.dispatch( - entry.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", - entry - ); - } - if (entry.count === 0) { - overflows.dispatch("TEARDOWN", entry); + } + } + return highlightedNodes; + } + function getRange(location, queryText) { + const parser = (0, _parser.onlineParser)(); + const state = parser.startState(); + const lines = queryText.split('\n'); + invariant(lines.length >= location.line, 'Query text must have more lines than where the error happened'); + let stream = null; + for (let i = 0; i < location.line; i++) { + stream = new _parser.CharacterStream(lines[i]); + while (!stream.eol()) { + const style = parser.token(stream, state); + if (style === 'invalidchar') { + break; + } + } + } + invariant(stream, 'Expected Parser stream to be available.'); + const line = location.line - 1; + const start = stream.getStartOfToken(); + const end = stream.getCurrentPosition(); + return new _utils.Range(new _utils.Position(line, start), new _utils.Position(line, end)); + } + function getLocation(node) { + const typeCastedNode = node; + const location = typeCastedNode.loc; + invariant(location, 'Expected ASTNode to have a location.'); + return location; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/getHoverInformation.js": + /*!***************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getHoverInformation.js ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getHoverInformation = getHoverInformation; + exports.renderArg = renderArg; + exports.renderDirective = renderDirective; + exports.renderEnumValue = renderEnumValue; + exports.renderField = renderField; + exports.renderType = renderType; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); + function getHoverInformation(schema, queryText, cursor, contextToken, config) { + const options = Object.assign(Object.assign({}, config), { + schema + }); + const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken); + if (!context) { + return ''; + } + const { + typeInfo, + token + } = context; + const { + kind, + step + } = token.state; + if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef || kind === 'ObjectField' && step === 0 && typeInfo.fieldDef) { + const into = []; + renderMdCodeStart(into, options); + renderField(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.fieldDef); + return into.join('').trim(); + } + if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) { + const into = []; + renderMdCodeStart(into, options); + renderDirective(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.directiveDef); + return into.join('').trim(); + } + if (kind === 'Variable' && typeInfo.type) { + const into = []; + renderMdCodeStart(into, options); + renderType(into, typeInfo, options, typeInfo.type); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.type); + return into.join('').trim(); + } + if (kind === 'Argument' && step === 0 && typeInfo.argDef) { + const into = []; + renderMdCodeStart(into, options); + renderArg(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.argDef); + return into.join('').trim(); + } + if (kind === 'EnumValue' && typeInfo.enumValue && 'description' in typeInfo.enumValue) { + const into = []; + renderMdCodeStart(into, options); + renderEnumValue(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.enumValue); + return into.join('').trim(); + } + if (kind === 'NamedType' && typeInfo.type && 'description' in typeInfo.type) { + const into = []; + renderMdCodeStart(into, options); + renderType(into, typeInfo, options, typeInfo.type); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.type); + return into.join('').trim(); + } + return ''; + } + function renderMdCodeStart(into, options) { + if (options.useMarkdown) { + text(into, '```graphql\n'); + } + } + function renderMdCodeEnd(into, options) { + if (options.useMarkdown) { + text(into, '\n```'); + } + } + function renderField(into, typeInfo, options) { + renderQualifiedField(into, typeInfo, options); + renderTypeAnnotation(into, typeInfo, options, typeInfo.type); + } + function renderQualifiedField(into, typeInfo, options) { + if (!typeInfo.fieldDef) { + return; + } + const fieldName = typeInfo.fieldDef.name; + if (fieldName.slice(0, 2) !== '__') { + renderType(into, typeInfo, options, typeInfo.parentType); + text(into, '.'); + } + text(into, fieldName); + } + function renderDirective(into, typeInfo, _options) { + if (!typeInfo.directiveDef) { + return; + } + const name = '@' + typeInfo.directiveDef.name; + text(into, name); + } + function renderArg(into, typeInfo, options) { + if (typeInfo.directiveDef) { + renderDirective(into, typeInfo, options); + } else if (typeInfo.fieldDef) { + renderQualifiedField(into, typeInfo, options); + } + if (!typeInfo.argDef) { + return; + } + const { + name + } = typeInfo.argDef; + text(into, '('); + text(into, name); + renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); + text(into, ')'); + } + function renderTypeAnnotation(into, typeInfo, options, t) { + text(into, ': '); + renderType(into, typeInfo, options, t); + } + function renderEnumValue(into, typeInfo, options) { + if (!typeInfo.enumValue) { + return; + } + const { + name + } = typeInfo.enumValue; + renderType(into, typeInfo, options, typeInfo.inputType); + text(into, '.'); + text(into, name); + } + function renderType(into, typeInfo, options, t) { + if (!t) { + return; + } + if (t instanceof _graphql.GraphQLNonNull) { + renderType(into, typeInfo, options, t.ofType); + text(into, '!'); + } else if (t instanceof _graphql.GraphQLList) { + text(into, '['); + renderType(into, typeInfo, options, t.ofType); + text(into, ']'); + } else { + text(into, t.name); + } + } + function renderDescription(into, options, def) { + if (!def) { + return; + } + const description = typeof def.description === 'string' ? def.description : null; + if (description) { + text(into, '\n\n'); + text(into, description); + } + renderDeprecation(into, options, def); + } + function renderDeprecation(into, _options, def) { + if (!def) { + return; + } + const reason = def.deprecationReason || null; + if (!reason) { + return; + } + text(into, '\n\n'); + text(into, 'Deprecated: '); + text(into, reason); + } + function text(into, content) { + into.push(content); + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/getOutline.js": + /*!******************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getOutline.js ***! + \******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getOutline = getOutline; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); + const { + INLINE_FRAGMENT + } = _graphql.Kind; + const OUTLINEABLE_KINDS = { + Field: true, + OperationDefinition: true, + Document: true, + SelectionSet: true, + Name: true, + FragmentDefinition: true, + FragmentSpread: true, + InlineFragment: true, + ObjectTypeDefinition: true, + InputObjectTypeDefinition: true, + InterfaceTypeDefinition: true, + EnumTypeDefinition: true, + EnumValueDefinition: true, + InputValueDefinition: true, + FieldDefinition: true + }; + function getOutline(documentText) { + let ast; + try { + ast = (0, _graphql.parse)(documentText); + } catch (_a) { + return null; + } + const visitorFns = outlineTreeConverter(documentText); + const outlineTrees = (0, _graphql.visit)(ast, { + leave(node) { + if (visitorFns !== undefined && node.kind in visitorFns) { + return visitorFns[node.kind](node); + } + return null; + } + }); + return { + outlineTrees + }; + } + function outlineTreeConverter(docText) { + const meta = node => { + return { + representativeName: node.name, + startPosition: (0, _utils.offsetToPosition)(docText, node.loc.start), + endPosition: (0, _utils.offsetToPosition)(docText, node.loc.end), + kind: node.kind, + children: node.selectionSet || node.fields || node.values || node.arguments || [] + }; + }; + return { + Field(node) { + const tokenizedText = node.alias ? [buildToken('plain', node.alias), buildToken('plain', ': ')] : []; + tokenizedText.push(buildToken('plain', node.name)); + return Object.assign({ + tokenizedText + }, meta(node)); + }, + OperationDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', node.operation), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + Document: node => node.definitions, + SelectionSet: node => concatMap(node.selections, child => { + return child.kind === INLINE_FRAGMENT ? child.selectionSet : child; + }), + Name: node => node.value, + FragmentDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'fragment'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + InterfaceTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'interface'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + EnumTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'enum'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + EnumValueDefinition: node => Object.assign({ + tokenizedText: [buildToken('plain', node.name)] + }, meta(node)), + ObjectTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'type'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + InputObjectTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'input'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + FragmentSpread: node => Object.assign({ + tokenizedText: [buildToken('plain', '...'), buildToken('class-name', node.name)] + }, meta(node)), + InputValueDefinition(node) { + return Object.assign({ + tokenizedText: [buildToken('plain', node.name)] + }, meta(node)); + }, + FieldDefinition(node) { + return Object.assign({ + tokenizedText: [buildToken('plain', node.name)] + }, meta(node)); + }, + InlineFragment: node => node.selectionSet + }; + } + function buildToken(kind, value) { + return { + kind, + value + }; + } + function concatMap(arr, fn) { + const res = []; + for (let i = 0; i < arr.length; i++) { + const x = fn(arr[i], i); + if (Array.isArray(x)) { + res.push(...x); + } else { + res.push(x); + } + } + return res; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/interface/index.js": + /*!*************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/index.js ***! + \*************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _exportNames = { + getOutline: true, + getHoverInformation: true + }; + Object.defineProperty(exports, "getHoverInformation", ({ + enumerable: true, + get: function () { + return _getHoverInformation.getHoverInformation; + } + })); + Object.defineProperty(exports, "getOutline", ({ + enumerable: true, + get: function () { + return _getOutline.getOutline; + } + })); + var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); + Object.keys(_autocompleteUtils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _autocompleteUtils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _autocompleteUtils[key]; + } + }); + }); + var _getAutocompleteSuggestions = __webpack_require__(/*! ./getAutocompleteSuggestions */ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js"); + Object.keys(_getAutocompleteSuggestions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getAutocompleteSuggestions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getAutocompleteSuggestions[key]; + } + }); + }); + var _getDefinition = __webpack_require__(/*! ./getDefinition */ "../../graphql-language-service/esm/interface/getDefinition.js"); + Object.keys(_getDefinition).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getDefinition[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getDefinition[key]; + } + }); + }); + var _getDiagnostics = __webpack_require__(/*! ./getDiagnostics */ "../../graphql-language-service/esm/interface/getDiagnostics.js"); + Object.keys(_getDiagnostics).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getDiagnostics[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getDiagnostics[key]; + } + }); + }); + var _getOutline = __webpack_require__(/*! ./getOutline */ "../../graphql-language-service/esm/interface/getOutline.js"); + var _getHoverInformation = __webpack_require__(/*! ./getHoverInformation */ "../../graphql-language-service/esm/interface/getHoverInformation.js"); + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/CharacterStream.js": + /*!********************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/CharacterStream.js ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = void 0; + class CharacterStream { + constructor(sourceText) { + this._start = 0; + this._pos = 0; + this.getStartOfToken = () => this._start; + this.getCurrentPosition = () => this._pos; + this.eol = () => this._sourceText.length === this._pos; + this.sol = () => this._pos === 0; + this.peek = () => { + return this._sourceText.charAt(this._pos) || null; + }; + this.next = () => { + const char = this._sourceText.charAt(this._pos); + this._pos++; + return char; + }; + this.eat = pattern => { + const isMatched = this._testNextCharacter(pattern); + if (isMatched) { + this._start = this._pos; + this._pos++; + return this._sourceText.charAt(this._pos - 1); + } + return undefined; + }; + this.eatWhile = match => { + let isMatched = this._testNextCharacter(match); + let didEat = false; + if (isMatched) { + didEat = isMatched; + this._start = this._pos; + } + while (isMatched) { + this._pos++; + isMatched = this._testNextCharacter(match); + didEat = true; + } + return didEat; + }; + this.eatSpace = () => this.eatWhile(/[\s\u00a0]/); + this.skipToEnd = () => { + this._pos = this._sourceText.length; + }; + this.skipTo = position => { + this._pos = position; + }; + this.match = (pattern, consume = true, caseFold = false) => { + let token = null; + let match = null; + if (typeof pattern === 'string') { + const regex = new RegExp(pattern, caseFold ? 'i' : 'g'); + match = regex.test(this._sourceText.slice(this._pos, this._pos + pattern.length)); + token = pattern; + } else if (pattern instanceof RegExp) { + match = this._sourceText.slice(this._pos).match(pattern); + token = match === null || match === void 0 ? void 0 : match[0]; + } + if (match != null && (typeof pattern === 'string' || match instanceof Array && this._sourceText.startsWith(match[0], this._pos))) { + if (consume) { + this._start = this._pos; + if (token && token.length) { + this._pos += token.length; } } - }); - - // src/hooks/document-overflow/use-document-overflow.ts - function useDocumentOverflowLockedEffect(doc, shouldBeLocked, meta) { - let store = useStore(overflows); - let entry = doc ? store.get(doc) : void 0; - let locked = entry ? entry.count > 0 : false; - useIsoMorphicEffect(() => { - if (!doc || !shouldBeLocked) { - return; - } - overflows.dispatch("PUSH", doc, meta); - return () => overflows.dispatch("POP", doc, meta); - }, [shouldBeLocked, doc]); - return locked; - } - - // src/hooks/use-inert.tsx - var originals = /* @__PURE__ */ new Map(); - var counts = /* @__PURE__ */ new Map(); - function useInert(node, enabled = true) { - useIsoMorphicEffect(() => { - var _a3; - if (!enabled) return; - let element = typeof node === "function" ? node() : node.current; - if (!element) return; - function cleanup() { - var _a4; - if (!element) return; - let count2 = (_a4 = counts.get(element)) != null ? _a4 : 1; - if (count2 === 1) counts.delete(element); - else counts.set(element, count2 - 1); - if (count2 !== 1) return; - let original = originals.get(element); - if (!original) return; - if (original["aria-hidden"] === null) - element.removeAttribute("aria-hidden"); - else element.setAttribute("aria-hidden", original["aria-hidden"]); - element.inert = original.inert; - originals.delete(element); - } - let count = (_a3 = counts.get(element)) != null ? _a3 : 0; - counts.set(element, count + 1); - if (count !== 0) return cleanup; - originals.set(element, { - "aria-hidden": element.getAttribute("aria-hidden"), - inert: element.inert, - }); - element.setAttribute("aria-hidden", "true"); - element.inert = true; - return cleanup; - }, [node, enabled]); + return match; } - - // src/hooks/use-root-containers.tsx - var import_react30 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - function useRootContainers({ defaultContainers = [], portals } = {}) { - let mainTreeNodeRef = (0, import_react30.useRef)(null); - let ownerDocument = useOwnerDocument(mainTreeNodeRef); - let resolveContainers2 = useEvent(() => { - var _a3; - let containers = []; - for (let container of defaultContainers) { - if (container === null) continue; - if (container instanceof HTMLElement) { - containers.push(container); - } else if ( - "current" in container && - container.current instanceof HTMLElement - ) { - containers.push(container.current); - } - } - if (portals == null ? void 0 : portals.current) { - for (let portal of portals.current) { - containers.push(portal); - } - } - for (let container of (_a3 = - ownerDocument == null - ? void 0 - : ownerDocument.querySelectorAll("html > *, body > *")) != null - ? _a3 - : []) { - if (container === document.body) continue; - if (container === document.head) continue; - if (!(container instanceof HTMLElement)) continue; - if (container.id === "headlessui-portal-root") continue; - if (container.contains(mainTreeNodeRef.current)) continue; - if ( - containers.some((defaultContainer) => - container.contains(defaultContainer) - ) - ) - continue; - containers.push(container); + return false; + }; + this.backUp = num => { + this._pos -= num; + }; + this.column = () => this._pos; + this.indentation = () => { + const match = this._sourceText.match(/\s*/); + let indent = 0; + if (match && match.length !== 0) { + const whiteSpaces = match[0]; + let pos = 0; + while (whiteSpaces.length > pos) { + if (whiteSpaces.charCodeAt(pos) === 9) { + indent += 2; + } else { + indent++; } - return containers; - }); - return { - resolveContainers: resolveContainers2, - contains: useEvent((element) => - resolveContainers2().some((container) => - container.contains(element) - ) - ), - mainTreeNodeRef, - MainTreeNode: (0, import_react30.useMemo)(() => { - return function MainTreeNode() { - return /* @__PURE__ */ import_react30.default.createElement( - Hidden, - { features: 4 /* Hidden */, ref: mainTreeNodeRef } - ); - }; - }, [mainTreeNodeRef]), - }; - } - - // src/components/dialog/dialog.tsx - var reducers2 = { - [0 /* SetTitleId */](state, action) { - if (state.titleId === action.id) return state; - return { ...state, titleId: action.id }; - }, - }; - var DialogContext = (0, import_react31.createContext)(null); - DialogContext.displayName = "DialogContext"; - function useDialogContext(component) { - let context = (0, import_react31.useContext)(DialogContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent

    component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDialogContext); - throw err; + pos++; } - return context; } - function useScrollLock( - ownerDocument, - enabled, - resolveAllowedContainers = () => [document.body] - ) { - useDocumentOverflowLockedEffect(ownerDocument, enabled, (meta) => { - var _a3; - return { - containers: [ - ...((_a3 = meta.containers) != null ? _a3 : []), - resolveAllowedContainers, - ], - }; - }); - } - function stateReducer2(state, action) { - return match(action.type, reducers2, state, action); - } - var DEFAULT_DIALOG_TAG = "div"; - var DialogRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ - function DialogFn(props, ref) { - var _a3; - let internalId = useId(); - let { - id = `headlessui-dialog-${internalId}`, - open, - onClose, - initialFocus, - __demoMode = false, - ...theirProps - } = props; - let [nestedDialogCount, setNestedDialogCount] = (0, - import_react31.useState)(0); - let usesOpenClosedState = useOpenClosed(); - if (open === void 0 && usesOpenClosedState !== null) { - open = (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - let internalDialogRef = (0, import_react31.useRef)(null); - let dialogRef = useSyncRefs(internalDialogRef, ref); - let ownerDocument = useOwnerDocument(internalDialogRef); - let hasOpen = - props.hasOwnProperty("open") || usesOpenClosedState !== null; - let hasOnClose = props.hasOwnProperty("onClose"); - if (!hasOpen && !hasOnClose) { - throw new Error( - `You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.` - ); - } - if (!hasOpen) { - throw new Error( - `You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.` - ); - } - if (!hasOnClose) { - throw new Error( - `You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.` - ); + return indent; + }; + this.current = () => this._sourceText.slice(this._start, this._pos); + this._sourceText = sourceText; + } + _testNextCharacter(pattern) { + const character = this._sourceText.charAt(this._pos); + let isMatched = false; + if (typeof pattern === 'string') { + isMatched = character === pattern; + } else { + isMatched = pattern instanceof RegExp ? pattern.test(character) : pattern(character); + } + return isMatched; + } + } + exports["default"] = CharacterStream; + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/RuleHelpers.js": + /*!****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/RuleHelpers.js ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.butNot = butNot; + exports.list = list; + exports.opt = opt; + exports.p = p; + exports.t = t; + function opt(ofRule) { + return { + ofRule + }; + } + function list(ofRule, separator) { + return { + ofRule, + isList: true, + separator + }; + } + function butNot(rule, exclusions) { + const ruleMatch = rule.match; + rule.match = token => { + let check = false; + if (ruleMatch) { + check = ruleMatch(token); + } + return check && exclusions.every(exclusion => exclusion.match && !exclusion.match(token)); + }; + return rule; + } + function t(kind, style) { + return { + style, + match: token => token.kind === kind + }; + } + function p(value, style) { + return { + style: style || 'punctuation', + match: token => token.kind === 'Punctuation' && token.value === value + }; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/Rules.js": + /*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/Rules.js ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isIgnored = exports.ParseRules = exports.LexRules = void 0; + var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const isIgnored = ch => ch === ' ' || ch === '\t' || ch === ',' || ch === '\n' || ch === '\r' || ch === '\uFEFF' || ch === '\u00A0'; + exports.isIgnored = isIgnored; + const LexRules = exports.LexRules = { + Name: /^[_A-Za-z][_0-9A-Za-z]*/, + Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|&|@|\[|]|\{|\||\})/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/, + Comment: /^#.*/ + }; + const ParseRules = exports.ParseRules = { + Document: [(0, _RuleHelpers.list)('Definition')], + Definition(token) { + switch (token.value) { + case '{': + return 'ShortQuery'; + case 'query': + return 'Query'; + case 'mutation': + return 'Mutation'; + case 'subscription': + return 'Subscription'; + case 'fragment': + return _graphql.Kind.FRAGMENT_DEFINITION; + case 'schema': + return 'SchemaDef'; + case 'scalar': + return 'ScalarDef'; + case 'type': + return 'ObjectTypeDef'; + case 'interface': + return 'InterfaceDef'; + case 'union': + return 'UnionDef'; + case 'enum': + return 'EnumDef'; + case 'input': + return 'InputDef'; + case 'extend': + return 'ExtendDef'; + case 'directive': + return 'DirectiveDef'; + } + }, + ShortQuery: ['SelectionSet'], + Query: [word('query'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + Mutation: [word('mutation'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + Subscription: [word('subscription'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + VariableDefinitions: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('VariableDefinition'), (0, _RuleHelpers.p)(')')], + VariableDefinition: ['Variable', (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue')], + Variable: [(0, _RuleHelpers.p)('$', 'variable'), name('variable')], + DefaultValue: [(0, _RuleHelpers.p)('='), 'Value'], + SelectionSet: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Selection'), (0, _RuleHelpers.p)('}')], + Selection(token, stream) { + return token.value === '...' ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field'; + }, + AliasedField: [name('property'), (0, _RuleHelpers.p)(':'), name('qualifier'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], + Field: [name('property'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], + Arguments: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('Argument'), (0, _RuleHelpers.p)(')')], + Argument: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], + FragmentSpread: [(0, _RuleHelpers.p)('...'), name('def'), (0, _RuleHelpers.list)('Directive')], + InlineFragment: [(0, _RuleHelpers.p)('...'), (0, _RuleHelpers.opt)('TypeCondition'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + FragmentDefinition: [word('fragment'), (0, _RuleHelpers.opt)((0, _RuleHelpers.butNot)(name('def'), [word('on')])), 'TypeCondition', (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + TypeCondition: [word('on'), 'NamedType'], + Value(token) { + switch (token.kind) { + case 'Number': + return 'NumberValue'; + case 'String': + return 'StringValue'; + case 'Punctuation': + switch (token.value) { + case '[': + return 'ListValue'; + case '{': + return 'ObjectValue'; + case '$': + return 'Variable'; + case '&': + return 'NamedType'; } - if (typeof open !== "boolean") { - throw new Error( - `You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${open}` - ); + return null; + case 'Name': + switch (token.value) { + case 'true': + case 'false': + return 'BooleanValue'; } - if (typeof onClose !== "function") { - throw new Error( - `You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${onClose}` - ); + if (token.value === 'null') { + return 'NullValue'; } - let dialogState = open ? 0 /* Open */ : 1; /* Closed */ - let [state, dispatch] = (0, import_react31.useReducer)( - stateReducer2, - { - titleId: null, - descriptionId: null, - panelRef: (0, import_react31.createRef)(), - } - ); - let close = useEvent(() => onClose(false)); - let setTitleId = useEvent((id2) => - dispatch({ type: 0 /* SetTitleId */, id: id2 }) - ); - let ready = useServerHandoffComplete(); - let enabled = ready - ? __demoMode - ? false - : dialogState === 0 /* Open */ - : false; - let hasNestedDialogs = nestedDialogCount > 1; - let hasParentDialog = - (0, import_react31.useContext)(DialogContext) !== null; - let [portals, PortalWrapper] = useNestedPortals(); - let { - resolveContainers: resolveRootContainers, - mainTreeNodeRef, - MainTreeNode, - } = useRootContainers({ - portals, - defaultContainers: [ - (_a3 = state.panelRef.current) != null - ? _a3 - : internalDialogRef.current, - ], - }); - let position = !hasNestedDialogs ? "leaf" : "parent"; - let isClosing = - usesOpenClosedState !== null - ? (usesOpenClosedState & 4) /* Closing */ === 4 /* Closing */ - : false; - let inertOthersEnabled = (() => { - if (hasParentDialog) return false; - if (isClosing) return false; - return enabled; - })(); - let resolveRootOfMainTreeNode = (0, - import_react31.useCallback)(() => { - var _a4, _b; - return (_b = Array.from( - (_a4 = - ownerDocument == null - ? void 0 - : ownerDocument.querySelectorAll("body > *")) != null - ? _a4 - : [] - ).find((root) => { - if (root.id === "headlessui-portal-root") return false; - return ( - root.contains(mainTreeNodeRef.current) && - root instanceof HTMLElement - ); - })) != null - ? _b - : null; - }, [mainTreeNodeRef]); - useInert(resolveRootOfMainTreeNode, inertOthersEnabled); - let inertParentDialogs = (() => { - if (hasNestedDialogs) return true; - return enabled; - })(); - let resolveRootOfParentDialog = (0, - import_react31.useCallback)(() => { - var _a4, _b; - return (_b = Array.from( - (_a4 = - ownerDocument == null - ? void 0 - : ownerDocument.querySelectorAll( - "[data-headlessui-portal]" - )) != null - ? _a4 - : [] - ).find( - (root) => - root.contains(mainTreeNodeRef.current) && - root instanceof HTMLElement - )) != null - ? _b - : null; - }, [mainTreeNodeRef]); - useInert(resolveRootOfParentDialog, inertParentDialogs); - let outsideClickEnabled = (() => { - if (!enabled) return false; - if (hasNestedDialogs) return false; - return true; - })(); - useOutsideClick(resolveRootContainers, close, outsideClickEnabled); - let escapeToCloseEnabled = (() => { - if (hasNestedDialogs) return false; - if (dialogState !== 0 /* Open */) return false; - return true; - })(); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "keydown", - (event) => { - if (!escapeToCloseEnabled) return; - if (event.defaultPrevented) return; - if (event.key !== "Escape" /* Escape */) return; - event.preventDefault(); - event.stopPropagation(); - close(); - } - ); - let scrollLockEnabled = (() => { - if (isClosing) return false; - if (dialogState !== 0 /* Open */) return false; - if (hasParentDialog) return false; - return true; - })(); - useScrollLock( - ownerDocument, - scrollLockEnabled, - resolveRootContainers - ); - (0, import_react31.useEffect)(() => { - if (dialogState !== 0 /* Open */) return; - if (!internalDialogRef.current) return; - let observer = new ResizeObserver((entries) => { - for (let entry of entries) { - let rect = entry.target.getBoundingClientRect(); - if ( - rect.x === 0 && - rect.y === 0 && - rect.width === 0 && - rect.height === 0 - ) { - close(); - } - } - }); - observer.observe(internalDialogRef.current); - return () => observer.disconnect(); - }, [dialogState, internalDialogRef, close]); - let [describedby, DescriptionProvider] = useDescriptions(); - let contextBag = (0, import_react31.useMemo)( - () => [{ dialogState, close, setTitleId }, state], - [dialogState, state, close, setTitleId] - ); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: dialogRef, - id, - role: "dialog", - "aria-modal": dialogState === 0 /* Open */ ? true : void 0, - "aria-labelledby": state.titleId, - "aria-describedby": describedby, - }; - return /* @__PURE__ */ import_react31.default.createElement( - StackProvider, - { - type: "Dialog", - enabled: dialogState === 0 /* Open */, - element: internalDialogRef, - onUpdate: useEvent((message, type) => { - if (type !== "Dialog") return; - match(message, { - [0 /* Add */]: () => - setNestedDialogCount((count) => count + 1), - [1 /* Remove */]: () => - setNestedDialogCount((count) => count - 1), - }); - }), - }, - /* @__PURE__ */ import_react31.default.createElement( - ForcePortalRoot, - { force: true }, - /* @__PURE__ */ import_react31.default.createElement( - Portal, - null, - /* @__PURE__ */ import_react31.default.createElement( - DialogContext.Provider, - { value: contextBag }, - /* @__PURE__ */ import_react31.default.createElement( - Portal.Group, - { target: internalDialogRef }, - /* @__PURE__ */ import_react31.default.createElement( - ForcePortalRoot, - { force: false }, - /* @__PURE__ */ import_react31.default.createElement( - DescriptionProvider, - { slot, name: "Dialog.Description" }, - /* @__PURE__ */ import_react31.default.createElement( - FocusTrap, - { - initialFocus, - containers: resolveRootContainers, - features: enabled - ? match(position, { - parent: FocusTrap.features.RestoreFocus, - leaf: - FocusTrap.features.All & - ~FocusTrap.features.FocusLock, - }) - : FocusTrap.features.None, - }, - /* @__PURE__ */ import_react31.default.createElement( - PortalWrapper, - null, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_DIALOG_TAG, - features: DialogRenderFeatures, - visible: dialogState === 0 /* Open */, - name: "Dialog", - }) - ) - ) - ) - ) - ) - ) - ) - ), - /* @__PURE__ */ import_react31.default.createElement( - MainTreeNode, - null - ) - ); - } - var DEFAULT_OVERLAY_TAG = "div"; - function OverlayFn(props, ref) { - let internalId = useId(); - let { - id = `headlessui-dialog-overlay-${internalId}`, - ...theirProps - } = props; - let [{ dialogState, close }] = useDialogContext("Dialog.Overlay"); - let overlayRef = useSyncRefs(ref); - let handleClick = useEvent((event) => { - if (event.target !== event.currentTarget) return; - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - event.preventDefault(); - event.stopPropagation(); - close(); - }); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: overlayRef, - id, - "aria-hidden": true, - onClick: handleClick, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OVERLAY_TAG, - name: "Dialog.Overlay", - }); - } - var DEFAULT_BACKDROP_TAG = "div"; - function BackdropFn(props, ref) { - let internalId = useId(); - let { - id = `headlessui-dialog-backdrop-${internalId}`, - ...theirProps - } = props; - let [{ dialogState }, state] = useDialogContext("Dialog.Backdrop"); - let backdropRef = useSyncRefs(ref); - (0, import_react31.useEffect)(() => { - if (state.panelRef.current === null) { - throw new Error( - `A component is being used, but a component is missing.` - ); - } - }, [state.panelRef]); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: backdropRef, - id, - "aria-hidden": true, - }; - return /* @__PURE__ */ import_react31.default.createElement( - ForcePortalRoot, - { force: true }, - /* @__PURE__ */ import_react31.default.createElement( - Portal, - null, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BACKDROP_TAG, - name: "Dialog.Backdrop", - }) - ) - ); + return 'EnumValue'; + } + }, + NumberValue: [(0, _RuleHelpers.t)('Number', 'number')], + StringValue: [{ + style: 'string', + match: token => token.kind === 'String', + update(state, token) { + if (token.value.startsWith('"""')) { + state.inBlockstring = !token.value.slice(3).endsWith('"""'); } - var DEFAULT_PANEL_TAG = "div"; - function PanelFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-panel-${internalId}`, ...theirProps } = - props; - let [{ dialogState }, state] = useDialogContext("Dialog.Panel"); - let panelRef = useSyncRefs(ref, state.panelRef); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let handleClick = useEvent((event) => { - event.stopPropagation(); - }); - let ourProps = { - ref: panelRef, - id, - onClick: handleClick, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG, - name: "Dialog.Panel", - }); + } + }], + BooleanValue: [(0, _RuleHelpers.t)('Name', 'builtin')], + NullValue: [(0, _RuleHelpers.t)('Name', 'keyword')], + EnumValue: [name('string-2')], + ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value'), (0, _RuleHelpers.p)(']')], + ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField'), (0, _RuleHelpers.p)('}')], + ObjectField: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], + Type(token) { + return token.value === '[' ? 'ListType' : 'NonNullType'; + }, + ListType: [(0, _RuleHelpers.p)('['), 'Type', (0, _RuleHelpers.p)(']'), (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], + NonNullType: ['NamedType', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], + NamedType: [type('atom')], + Directive: [(0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('Arguments')], + DirectiveDef: [word('directive'), (0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('ArgumentsDef'), word('on'), (0, _RuleHelpers.list)('DirectiveLocation', (0, _RuleHelpers.p)('|'))], + InterfaceDef: [word('interface'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], + Implements: [word('implements'), (0, _RuleHelpers.list)('NamedType', (0, _RuleHelpers.p)('&'))], + DirectiveLocation: [name('string-2')], + SchemaDef: [word('schema'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('OperationTypeDef'), (0, _RuleHelpers.p)('}')], + OperationTypeDef: [name('keyword'), (0, _RuleHelpers.p)(':'), name('atom')], + ScalarDef: [word('scalar'), name('atom'), (0, _RuleHelpers.list)('Directive')], + ObjectTypeDef: [word('type'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], + FieldDef: [name('property'), (0, _RuleHelpers.opt)('ArgumentsDef'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.list)('Directive')], + ArgumentsDef: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)(')')], + InputValueDef: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue'), (0, _RuleHelpers.list)('Directive')], + UnionDef: [word('union'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('='), (0, _RuleHelpers.list)('UnionMember', (0, _RuleHelpers.p)('|'))], + UnionMember: ['NamedType'], + EnumDef: [word('enum'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('EnumValueDef'), (0, _RuleHelpers.p)('}')], + EnumValueDef: [name('string-2'), (0, _RuleHelpers.list)('Directive')], + InputDef: [word('input'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)('}')], + ExtendDef: [word('extend'), 'ExtensionDefinition'], + ExtensionDefinition(token) { + switch (token.value) { + case 'schema': + return _graphql.Kind.SCHEMA_EXTENSION; + case 'scalar': + return _graphql.Kind.SCALAR_TYPE_EXTENSION; + case 'type': + return _graphql.Kind.OBJECT_TYPE_EXTENSION; + case 'interface': + return _graphql.Kind.INTERFACE_TYPE_EXTENSION; + case 'union': + return _graphql.Kind.UNION_TYPE_EXTENSION; + case 'enum': + return _graphql.Kind.ENUM_TYPE_EXTENSION; + case 'input': + return _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + }, + [_graphql.Kind.SCHEMA_EXTENSION]: ['SchemaDef'], + [_graphql.Kind.SCALAR_TYPE_EXTENSION]: ['ScalarDef'], + [_graphql.Kind.OBJECT_TYPE_EXTENSION]: ['ObjectTypeDef'], + [_graphql.Kind.INTERFACE_TYPE_EXTENSION]: ['InterfaceDef'], + [_graphql.Kind.UNION_TYPE_EXTENSION]: ['UnionDef'], + [_graphql.Kind.ENUM_TYPE_EXTENSION]: ['EnumDef'], + [_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]: ['InputDef'] + }; + function word(value) { + return { + style: 'keyword', + match: token => token.kind === 'Name' && token.value === value + }; + } + function name(style) { + return { + style, + match: token => token.kind === 'Name', + update(state, token) { + state.name = token.value; + } + }; + } + function type(style) { + return { + style, + match: token => token.kind === 'Name', + update(state, token) { + var _a; + if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.prevState) { + state.name = token.value; + state.prevState.prevState.type = token.value; } - var DEFAULT_TITLE_TAG = "h2"; - function TitleFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-title-${internalId}`, ...theirProps } = - props; - let [{ dialogState, setTitleId }] = useDialogContext("Dialog.Title"); - let titleRef = useSyncRefs(ref); - (0, import_react31.useEffect)(() => { - setTitleId(id); - return () => setTitleId(null); - }, [id, setTitleId]); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { ref: titleRef, id }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_TITLE_TAG, - name: "Dialog.Title", - }); + } + }; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/api.js": + /*!********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/api.js ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.TYPE_SYSTEM_KINDS = exports.GraphQLDocumentMode = void 0; + exports.getContextAtPosition = getContextAtPosition; + exports.getDocumentMode = getDocumentMode; + exports.getTokenAtPosition = getTokenAtPosition; + exports.runOnlineParser = runOnlineParser; + var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function runOnlineParser(queryText, callback) { + const lines = queryText.split('\n'); + const parser = (0, _.onlineParser)(); + let state = parser.startState(); + let style = ''; + let stream = new _.CharacterStream(''); + for (let i = 0; i < lines.length; i++) { + stream = new _.CharacterStream(lines[i]); + while (!stream.eol()) { + style = parser.token(stream, state); + const code = callback(stream, state, style, i); + if (code === 'BREAK') { + break; } - var DialogRoot = forwardRefWithAs(DialogFn); - var Backdrop = forwardRefWithAs(BackdropFn); - var Panel = forwardRefWithAs(PanelFn); - var Overlay = forwardRefWithAs(OverlayFn); - var Title = forwardRefWithAs(TitleFn); - var Dialog = Object.assign(DialogRoot, { - Backdrop, - Panel, - Overlay, - Title, - Description, + } + callback(stream, state, style, i); + if (!state.kind) { + state = parser.startState(); + } + } + return { + start: stream.getStartOfToken(), + end: stream.getCurrentPosition(), + string: stream.current(), + state, + style + }; + } + var GraphQLDocumentMode; + (function (GraphQLDocumentMode) { + GraphQLDocumentMode["TYPE_SYSTEM"] = "TYPE_SYSTEM"; + GraphQLDocumentMode["EXECUTABLE"] = "EXECUTABLE"; + GraphQLDocumentMode["UNKNOWN"] = "UNKNOWN"; + })(GraphQLDocumentMode || (exports.GraphQLDocumentMode = GraphQLDocumentMode = {})); + const TYPE_SYSTEM_KINDS = exports.TYPE_SYSTEM_KINDS = [_graphql.Kind.SCHEMA_DEFINITION, _graphql.Kind.OPERATION_TYPE_DEFINITION, _graphql.Kind.SCALAR_TYPE_DEFINITION, _graphql.Kind.OBJECT_TYPE_DEFINITION, _graphql.Kind.INTERFACE_TYPE_DEFINITION, _graphql.Kind.UNION_TYPE_DEFINITION, _graphql.Kind.ENUM_TYPE_DEFINITION, _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION, _graphql.Kind.DIRECTIVE_DEFINITION, _graphql.Kind.SCHEMA_EXTENSION, _graphql.Kind.SCALAR_TYPE_EXTENSION, _graphql.Kind.OBJECT_TYPE_EXTENSION, _graphql.Kind.INTERFACE_TYPE_EXTENSION, _graphql.Kind.UNION_TYPE_EXTENSION, _graphql.Kind.ENUM_TYPE_EXTENSION, _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]; + const getParsedMode = sdl => { + let mode = GraphQLDocumentMode.UNKNOWN; + if (sdl) { + try { + (0, _graphql.visit)((0, _graphql.parse)(sdl), { + enter(node) { + if (node.kind === 'Document') { + mode = GraphQLDocumentMode.EXECUTABLE; + return; + } + if (TYPE_SYSTEM_KINDS.includes(node.kind)) { + mode = GraphQLDocumentMode.TYPE_SYSTEM; + return _graphql.BREAK; + } + return false; + } }); - - // src/components/disclosure/disclosure.tsx - var import_react33 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/utils/start-transition.ts - var import_react32 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var _a2; - var startTransition = - // Prefer React's `startTransition` if it's available. - // @ts-expect-error - `startTransition` doesn't exist in React < 18. - (_a2 = import_react32.default.startTransition) != null - ? _a2 - : function startTransition2(cb) { - cb(); - }; - - // src/components/disclosure/disclosure.tsx - var reducers3 = { - [0 /* ToggleDisclosure */]: (state) => ({ - ...state, - disclosureState: match(state.disclosureState, { - [0 /* Open */]: 1 /* Closed */, - [1 /* Closed */]: 0 /* Open */, - }), - }), - [1 /* CloseDisclosure */]: (state) => { - if (state.disclosureState === 1 /* Closed */) return state; - return { ...state, disclosureState: 1 /* Closed */ }; - }, - [4 /* LinkPanel */](state) { - if (state.linkedPanel === true) return state; - return { ...state, linkedPanel: true }; - }, - [5 /* UnlinkPanel */](state) { - if (state.linkedPanel === false) return state; - return { ...state, linkedPanel: false }; - }, - [2 /* SetButtonId */](state, action) { - if (state.buttonId === action.buttonId) return state; - return { ...state, buttonId: action.buttonId }; - }, - [3 /* SetPanelId */](state, action) { - if (state.panelId === action.panelId) return state; - return { ...state, panelId: action.panelId }; - }, - }; - var DisclosureContext = (0, import_react33.createContext)(null); - DisclosureContext.displayName = "DisclosureContext"; - function useDisclosureContext(component) { - let context = (0, import_react33.useContext)(DisclosureContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDisclosureContext); - throw err; + } catch (_a) { + return mode; + } + } + return mode; + }; + function getDocumentMode(documentText, uri) { + if (uri === null || uri === void 0 ? void 0 : uri.endsWith('.graphqls')) { + return GraphQLDocumentMode.TYPE_SYSTEM; + } + return getParsedMode(documentText); + } + function getTokenAtPosition(queryText, cursor, offset = 0) { + let styleAtCursor = null; + let stateAtCursor = null; + let stringAtCursor = null; + const token = runOnlineParser(queryText, (stream, state, style, index) => { + if (index !== cursor.line || stream.getCurrentPosition() + offset < cursor.character + 1) { + return; + } + styleAtCursor = style; + stateAtCursor = Object.assign({}, state); + stringAtCursor = stream.current(); + return 'BREAK'; + }); + return { + start: token.start, + end: token.end, + string: stringAtCursor || token.string, + state: stateAtCursor || token.state, + style: styleAtCursor || token.style + }; + } + function getContextAtPosition(queryText, cursor, schema, contextToken, options) { + const token = contextToken || getTokenAtPosition(queryText, cursor, 1); + if (!token) { + return null; + } + const state = token.state.kind === 'Invalid' ? token.state.prevState : token.state; + if (!state) { + return null; + } + const typeInfo = (0, _.getTypeInfo)(schema, token.state); + const mode = (options === null || options === void 0 ? void 0 : options.mode) || getDocumentMode(queryText, options === null || options === void 0 ? void 0 : options.uri); + return { + token, + state, + typeInfo, + mode + }; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/getTypeInfo.js": + /*!****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/getTypeInfo.js ***! + \****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.forEachState = forEachState; + exports.getDefinitionState = getDefinitionState; + exports.getFieldDef = getFieldDef; + exports.getTypeInfo = getTypeInfo; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); + function getFieldDef(schema, type, fieldName) { + if (fieldName === _graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { + return _graphql.SchemaMetaFieldDef; + } + if (fieldName === _graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { + return _graphql.TypeMetaFieldDef; + } + if (fieldName === _graphql.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) { + return _graphql.TypeNameMetaFieldDef; + } + if ('getFields' in type) { + return type.getFields()[fieldName]; + } + return null; + } + function forEachState(stack, fn) { + const reverseStateStack = []; + let state = stack; + while (state === null || state === void 0 ? void 0 : state.kind) { + reverseStateStack.push(state); + state = state.prevState; + } + for (let i = reverseStateStack.length - 1; i >= 0; i--) { + fn(reverseStateStack[i]); + } + } + function getDefinitionState(tokenState) { + let definitionState; + forEachState(tokenState, state => { + switch (state.kind) { + case 'Query': + case 'ShortQuery': + case 'Mutation': + case 'Subscription': + case 'FragmentDefinition': + definitionState = state; + break; + } + }); + return definitionState; + } + function getTypeInfo(schema, tokenState) { + let argDef; + let argDefs; + let directiveDef; + let enumValue; + let fieldDef; + let inputType; + let objectTypeDef; + let objectFieldDefs; + let parentType; + let type; + let interfaceDef; + forEachState(tokenState, state => { + var _a; + switch (state.kind) { + case _.RuleKinds.QUERY: + case 'ShortQuery': + type = schema.getQueryType(); + break; + case _.RuleKinds.MUTATION: + type = schema.getMutationType(); + break; + case _.RuleKinds.SUBSCRIPTION: + type = schema.getSubscriptionType(); + break; + case _.RuleKinds.INLINE_FRAGMENT: + case _.RuleKinds.FRAGMENT_DEFINITION: + if (state.type) { + type = schema.getType(state.type); + } + break; + case _.RuleKinds.FIELD: + case _.RuleKinds.ALIASED_FIELD: + { + if (!type || !state.name) { + fieldDef = null; + } else { + fieldDef = parentType ? getFieldDef(schema, parentType, state.name) : null; + type = fieldDef ? fieldDef.type : null; + } + break; } - return context; - } - var DisclosureAPIContext = (0, import_react33.createContext)(null); - DisclosureAPIContext.displayName = "DisclosureAPIContext"; - function useDisclosureAPIContext(component) { - let context = (0, import_react33.useContext)(DisclosureAPIContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDisclosureAPIContext); - throw err; + case _.RuleKinds.SELECTION_SET: + parentType = (0, _graphql.getNamedType)(type); + break; + case _.RuleKinds.DIRECTIVE: + directiveDef = state.name ? schema.getDirective(state.name) : null; + break; + case _.RuleKinds.INTERFACE_DEF: + if (state.name) { + objectTypeDef = null; + interfaceDef = new _graphql.GraphQLInterfaceType({ + name: state.name, + interfaces: [], + fields: {} + }); } - return context; - } - var DisclosurePanelContext = (0, import_react33.createContext)(null); - DisclosurePanelContext.displayName = "DisclosurePanelContext"; - function useDisclosurePanelContext() { - return (0, import_react33.useContext)(DisclosurePanelContext); - } - function stateReducer3(state, action) { - return match(action.type, reducers3, state, action); - } - var DEFAULT_DISCLOSURE_TAG = import_react33.Fragment; - function DisclosureFn(props, ref) { - let { defaultOpen = false, ...theirProps } = props; - let internalDisclosureRef = (0, import_react33.useRef)(null); - let disclosureRef = useSyncRefs( - ref, - optionalRef( - (ref2) => { - internalDisclosureRef.current = ref2; - }, - props.as === void 0 || // @ts-expect-error The `as` prop _can_ be a Fragment - props.as === import_react33.Fragment - ) - ); - let panelRef = (0, import_react33.useRef)(null); - let buttonRef = (0, import_react33.useRef)(null); - let reducerBag = (0, import_react33.useReducer)(stateReducer3, { - disclosureState: defaultOpen ? 0 /* Open */ : 1 /* Closed */, - linkedPanel: false, - buttonRef, - panelRef, - buttonId: null, - panelId: null, - }); - let [{ disclosureState, buttonId }, dispatch] = reducerBag; - let close = useEvent((focusableElement) => { - dispatch({ type: 1 /* CloseDisclosure */ }); - let ownerDocument = getOwnerDocument(internalDisclosureRef); - if (!ownerDocument) return; - if (!buttonId) return; - let restoreElement = (() => { - if (!focusableElement) - return ownerDocument.getElementById(buttonId); - if (focusableElement instanceof HTMLElement) - return focusableElement; - if (focusableElement.current instanceof HTMLElement) - return focusableElement.current; - return ownerDocument.getElementById(buttonId); - })(); - restoreElement == null ? void 0 : restoreElement.focus(); - }); - let api = (0, import_react33.useMemo)(() => ({ close }), [close]); - let slot = (0, import_react33.useMemo)( - () => ({ open: disclosureState === 0 /* Open */, close }), - [disclosureState, close] - ); - let ourProps = { - ref: disclosureRef, - }; - return /* @__PURE__ */ import_react33.default.createElement( - DisclosureContext.Provider, - { value: reducerBag }, - /* @__PURE__ */ import_react33.default.createElement( - DisclosureAPIContext.Provider, - { value: api }, - /* @__PURE__ */ import_react33.default.createElement( - OpenClosedProvider, - { - value: match(disclosureState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */, - }), - }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_DISCLOSURE_TAG, - name: "Disclosure", - }) - ) - ) - ); - } - var DEFAULT_BUTTON_TAG2 = "button"; - function ButtonFn2(props, ref) { - let internalId = useId(); - let { - id = `headlessui-disclosure-button-${internalId}`, - ...theirProps - } = props; - let [state, dispatch] = useDisclosureContext("Disclosure.Button"); - let panelContext = useDisclosurePanelContext(); - let isWithinPanel = - panelContext === null ? false : panelContext === state.panelId; - let internalButtonRef = (0, import_react33.useRef)(null); - let buttonRef = useSyncRefs( - internalButtonRef, - ref, - !isWithinPanel ? state.buttonRef : null - ); - (0, import_react33.useEffect)(() => { - if (isWithinPanel) return; - dispatch({ type: 2 /* SetButtonId */, buttonId: id }); - return () => { - dispatch({ type: 2 /* SetButtonId */, buttonId: null }); - }; - }, [id, dispatch, isWithinPanel]); - let handleKeyDown = useEvent((event) => { - var _a3; - if (isWithinPanel) { - if (state.disclosureState === 1 /* Closed */) return; - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* ToggleDisclosure */ }); - (_a3 = state.buttonRef.current) == null - ? void 0 - : _a3.focus(); + break; + case _.RuleKinds.OBJECT_TYPE_DEF: + if (state.name) { + interfaceDef = null; + objectTypeDef = new _graphql.GraphQLObjectType({ + name: state.name, + interfaces: [], + fields: {} + }); + } + break; + case _.RuleKinds.ARGUMENTS: + { + if (state.prevState) { + switch (state.prevState.kind) { + case _.RuleKinds.FIELD: + argDefs = fieldDef && fieldDef.args; + break; + case _.RuleKinds.DIRECTIVE: + argDefs = directiveDef && directiveDef.args; + break; + case _.RuleKinds.ALIASED_FIELD: + { + const name = (_a = state.prevState) === null || _a === void 0 ? void 0 : _a.name; + if (!name) { + argDefs = null; + break; + } + const field = parentType ? getFieldDef(schema, parentType, name) : null; + if (!field) { + argDefs = null; + break; + } + argDefs = field.args; + break; + } + default: + argDefs = null; break; } } else { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* ToggleDisclosure */ }); - break; - } + argDefs = null; } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); + break; + } + case _.RuleKinds.ARGUMENT: + if (argDefs) { + for (let i = 0; i < argDefs.length; i++) { + if (argDefs[i].name === state.name) { + argDef = argDefs[i]; break; - } - }); - let handleClick = useEvent((event) => { - var _a3; - if (isDisabledReactIssue7711(event.currentTarget)) return; - if (props.disabled) return; - if (isWithinPanel) { - dispatch({ type: 0 /* ToggleDisclosure */ }); - (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); - } else { - dispatch({ type: 0 /* ToggleDisclosure */ }); - } - }); - let slot = (0, import_react33.useMemo)( - () => ({ open: state.disclosureState === 0 /* Open */ }), - [state] - ); - let type = useResolveButtonType(props, internalButtonRef); - let ourProps = isWithinPanel - ? { - ref: buttonRef, - type, - onKeyDown: handleKeyDown, - onClick: handleClick, } - : { - ref: buttonRef, - id, - type, - "aria-expanded": props.disabled - ? void 0 - : state.disclosureState === 0 /* Open */, - "aria-controls": state.linkedPanel ? state.panelId : void 0, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG2, - name: "Disclosure.Button", - }); - } - var DEFAULT_PANEL_TAG2 = "div"; - var PanelRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ - function PanelFn2(props, ref) { - let internalId = useId(); - let { - id = `headlessui-disclosure-panel-${internalId}`, - ...theirProps - } = props; - let [state, dispatch] = useDisclosureContext("Disclosure.Panel"); - let { close } = useDisclosureAPIContext("Disclosure.Panel"); - let panelRef = useSyncRefs(ref, state.panelRef, (el) => { - startTransition(() => - dispatch({ type: el ? 4 /* LinkPanel */ : 5 /* UnlinkPanel */ }) - ); - }); - (0, import_react33.useEffect)(() => { - dispatch({ type: 3 /* SetPanelId */, panelId: id }); - return () => { - dispatch({ type: 3 /* SetPanelId */, panelId: null }); - }; - }, [id, dispatch]); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - return state.disclosureState === 0 /* Open */; - })(); - let slot = (0, import_react33.useMemo)( - () => ({ open: state.disclosureState === 0 /* Open */, close }), - [state, close] - ); - let ourProps = { - ref: panelRef, - id, - }; - return /* @__PURE__ */ import_react33.default.createElement( - DisclosurePanelContext.Provider, - { value: state.panelId }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG2, - features: PanelRenderFeatures, - visible, - name: "Disclosure.Panel", - }) - ); - } - var DisclosureRoot = forwardRefWithAs(DisclosureFn); - var Button2 = forwardRefWithAs(ButtonFn2); - var Panel2 = forwardRefWithAs(PanelFn2); - var Disclosure = Object.assign(DisclosureRoot, { - Button: Button2, - Panel: Panel2, - }); - - // src/components/listbox/listbox.tsx - var import_react35 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/hooks/use-text-value.ts - var import_react34 = __webpack_require__(/*! react */ "react"); - - // src/utils/get-text-value.ts - var emojiRegex = - /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; - function getTextContents(element) { - var _a3, _b; - let currentInnerText = (_a3 = element.innerText) != null ? _a3 : ""; - let copy = element.cloneNode(true); - if (!(copy instanceof HTMLElement)) { - return currentInnerText; - } - let dropped = false; - for (let child of copy.querySelectorAll( - '[hidden],[aria-hidden],[role="img"]' - )) { - child.remove(); - dropped = true; - } - let value = dropped - ? (_b = copy.innerText) != null - ? _b - : "" - : currentInnerText; - if (emojiRegex.test(value)) { - value = value.replace(emojiRegex, ""); + } } - return value; + inputType = argDef === null || argDef === void 0 ? void 0 : argDef.type; + break; + case _.RuleKinds.VARIABLE_DEFINITION: + case _.RuleKinds.VARIABLE: + type = inputType; + break; + case _.RuleKinds.ENUM_VALUE: + const enumType = (0, _graphql.getNamedType)(inputType); + enumValue = enumType instanceof _graphql.GraphQLEnumType ? enumType.getValues().find(val => val.value === state.name) : null; + break; + case _.RuleKinds.LIST_VALUE: + const nullableType = (0, _graphql.getNullableType)(inputType); + inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null; + break; + case _.RuleKinds.OBJECT_VALUE: + const objectType = (0, _graphql.getNamedType)(inputType); + objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null; + break; + case _.RuleKinds.OBJECT_FIELD: + const objectField = state.name && objectFieldDefs ? objectFieldDefs[state.name] : null; + inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; + fieldDef = objectField; + type = fieldDef ? fieldDef.type : null; + break; + case _.RuleKinds.NAMED_TYPE: + if (state.name) { + type = schema.getType(state.name); + } + break; + } + }); + return { + argDef, + argDefs, + directiveDef, + enumValue, + fieldDef, + inputType, + objectFieldDefs, + parentType, + type, + interfaceDef, + objectTypeDef + }; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/index.js": + /*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/index.js ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _exportNames = { + CharacterStream: true, + LexRules: true, + ParseRules: true, + isIgnored: true, + butNot: true, + list: true, + opt: true, + p: true, + t: true, + onlineParser: true, + runOnlineParser: true, + getTokenAtPosition: true, + getContextAtPosition: true, + GraphQLDocumentMode: true, + getDocumentMode: true, + getTypeInfo: true, + getDefinitionState: true, + getFieldDef: true + }; + Object.defineProperty(exports, "CharacterStream", ({ + enumerable: true, + get: function () { + return _CharacterStream.default; + } + })); + Object.defineProperty(exports, "GraphQLDocumentMode", ({ + enumerable: true, + get: function () { + return _api.GraphQLDocumentMode; + } + })); + Object.defineProperty(exports, "LexRules", ({ + enumerable: true, + get: function () { + return _Rules.LexRules; + } + })); + Object.defineProperty(exports, "ParseRules", ({ + enumerable: true, + get: function () { + return _Rules.ParseRules; + } + })); + Object.defineProperty(exports, "butNot", ({ + enumerable: true, + get: function () { + return _RuleHelpers.butNot; + } + })); + Object.defineProperty(exports, "getContextAtPosition", ({ + enumerable: true, + get: function () { + return _api.getContextAtPosition; + } + })); + Object.defineProperty(exports, "getDefinitionState", ({ + enumerable: true, + get: function () { + return _getTypeInfo.getDefinitionState; + } + })); + Object.defineProperty(exports, "getDocumentMode", ({ + enumerable: true, + get: function () { + return _api.getDocumentMode; + } + })); + Object.defineProperty(exports, "getFieldDef", ({ + enumerable: true, + get: function () { + return _getTypeInfo.getFieldDef; + } + })); + Object.defineProperty(exports, "getTokenAtPosition", ({ + enumerable: true, + get: function () { + return _api.getTokenAtPosition; + } + })); + Object.defineProperty(exports, "getTypeInfo", ({ + enumerable: true, + get: function () { + return _getTypeInfo.getTypeInfo; + } + })); + Object.defineProperty(exports, "isIgnored", ({ + enumerable: true, + get: function () { + return _Rules.isIgnored; + } + })); + Object.defineProperty(exports, "list", ({ + enumerable: true, + get: function () { + return _RuleHelpers.list; + } + })); + Object.defineProperty(exports, "onlineParser", ({ + enumerable: true, + get: function () { + return _onlineParser.default; + } + })); + Object.defineProperty(exports, "opt", ({ + enumerable: true, + get: function () { + return _RuleHelpers.opt; + } + })); + Object.defineProperty(exports, "p", ({ + enumerable: true, + get: function () { + return _RuleHelpers.p; + } + })); + Object.defineProperty(exports, "runOnlineParser", ({ + enumerable: true, + get: function () { + return _api.runOnlineParser; + } + })); + Object.defineProperty(exports, "t", ({ + enumerable: true, + get: function () { + return _RuleHelpers.t; + } + })); + var _CharacterStream = _interopRequireDefault(__webpack_require__(/*! ./CharacterStream */ "../../graphql-language-service/esm/parser/CharacterStream.js")); + var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); + var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); + var _onlineParser = _interopRequireDefault(__webpack_require__(/*! ./onlineParser */ "../../graphql-language-service/esm/parser/onlineParser.js")); + var _api = __webpack_require__(/*! ./api */ "../../graphql-language-service/esm/parser/api.js"); + var _getTypeInfo = __webpack_require__(/*! ./getTypeInfo */ "../../graphql-language-service/esm/parser/getTypeInfo.js"); + var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/parser/types.js"); + Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); + }); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/onlineParser.js": + /*!*****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/onlineParser.js ***! + \*****************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = onlineParser; + var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function onlineParser(options = { + eatWhitespace: stream => stream.eatWhile(_Rules.isIgnored), + lexRules: _Rules.LexRules, + parseRules: _Rules.ParseRules, + editorConfig: {} + }) { + return { + startState() { + const initialState = { + level: 0, + step: 0, + name: null, + kind: null, + type: null, + rule: null, + needsSeparator: false, + prevState: null + }; + pushRule(options.parseRules, initialState, _graphql.Kind.DOCUMENT); + return initialState; + }, + token(stream, state) { + return getToken(stream, state, options); + } + }; + } + function getToken(stream, state, options) { + var _a; + if (state.inBlockstring) { + if (stream.match(/.*"""/)) { + state.inBlockstring = false; + return 'string'; + } + stream.skipToEnd(); + return 'string'; + } + const { + lexRules, + parseRules, + eatWhitespace, + editorConfig + } = options; + if (state.rule && state.rule.length === 0) { + popRule(state); + } else if (state.needsAdvance) { + state.needsAdvance = false; + advanceRule(state, true); + } + if (stream.sol()) { + const tabSize = (editorConfig === null || editorConfig === void 0 ? void 0 : editorConfig.tabSize) || 2; + state.indentLevel = Math.floor(stream.indentation() / tabSize); + } + if (eatWhitespace(stream)) { + return 'ws'; + } + const token = lex(lexRules, stream); + if (!token) { + const matchedSomething = stream.match(/\S+/); + if (!matchedSomething) { + stream.match(/\s/); + } + pushRule(SpecialParseRules, state, 'Invalid'); + return 'invalidchar'; + } + if (token.kind === 'Comment') { + pushRule(SpecialParseRules, state, 'Comment'); + return 'comment'; + } + const backupState = assign({}, state); + if (token.kind === 'Punctuation') { + if (/^[{([]/.test(token.value)) { + if (state.indentLevel !== undefined) { + state.levels = (state.levels || []).concat(state.indentLevel + 1); } - function getTextValue(element) { - let label = element.getAttribute("aria-label"); - if (typeof label === "string") return label.trim(); - let labelledby = element.getAttribute("aria-labelledby"); - if (labelledby) { - let labels = labelledby - .split(" ") - .map((labelledby2) => { - let labelEl = document.getElementById(labelledby2); - if (labelEl) { - let label2 = labelEl.getAttribute("aria-label"); - if (typeof label2 === "string") return label2.trim(); - return getTextContents(labelEl).trim(); - } - return null; - }) - .filter(Boolean); - if (labels.length > 0) return labels.join(", "); - } - return getTextContents(element).trim(); + } else if (/^[})\]]/.test(token.value)) { + const levels = state.levels = (state.levels || []).slice(0, -1); + if (state.indentLevel && levels.length > 0 && levels.at(-1) < state.indentLevel) { + state.indentLevel = levels.at(-1); } - - // src/hooks/use-text-value.ts - function useTextValue(element) { - let cacheKey = (0, import_react34.useRef)(""); - let cacheValue = (0, import_react34.useRef)(""); - return useEvent(() => { - let el = element.current; - if (!el) return ""; - let currentKey = el.innerText; - if (cacheKey.current === currentKey) { - return cacheValue.current; - } - let value = getTextValue(el).trim().toLowerCase(); - cacheKey.current = currentKey; - cacheValue.current = value; - return value; - }); + } + } + while (state.rule) { + let expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step]; + if (state.needsSeparator) { + expected = expected === null || expected === void 0 ? void 0 : expected.separator; + } + if (expected) { + if (expected.ofRule) { + expected = expected.ofRule; } - - // src/components/listbox/listbox.tsx - function adjustOrderedState2(state, adjustment = (i) => i) { - let currentActiveOption = - state.activeOptionIndex !== null - ? state.options[state.activeOptionIndex] - : null; - let sortedOptions = sortByDomNode( - adjustment(state.options.slice()), - (option) => option.dataRef.current.domRef.current - ); - let adjustedActiveOptionIndex = currentActiveOption - ? sortedOptions.indexOf(currentActiveOption) - : null; - if (adjustedActiveOptionIndex === -1) { - adjustedActiveOptionIndex = null; - } - return { - options: sortedOptions, - activeOptionIndex: adjustedActiveOptionIndex, - }; + if (typeof expected === 'string') { + pushRule(parseRules, state, expected); + continue; } - var reducers4 = { - [1 /* CloseListbox */](state) { - if (state.dataRef.current.disabled) return state; - if (state.listboxState === 1 /* Closed */) return state; - return { - ...state, - activeOptionIndex: null, - listboxState: 1 /* Closed */, - }; - }, - [0 /* OpenListbox */](state) { - if (state.dataRef.current.disabled) return state; - if (state.listboxState === 0 /* Open */) return state; - let activeOptionIndex = state.activeOptionIndex; - let { isSelected } = state.dataRef.current; - let optionIdx = state.options.findIndex((option) => - isSelected(option.dataRef.current.value) - ); - if (optionIdx !== -1) { - activeOptionIndex = optionIdx; - } - return { ...state, listboxState: 0 /* Open */, activeOptionIndex }; - }, - [2 /* GoToOption */](state, action) { - var _a3; - if (state.dataRef.current.disabled) return state; - if (state.listboxState === 1 /* Closed */) return state; - let adjustedState = adjustOrderedState2(state); - let activeOptionIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.options, - resolveActiveIndex: () => adjustedState.activeOptionIndex, - resolveId: (option) => option.id, - resolveDisabled: (option) => option.dataRef.current.disabled, - }); - return { - ...state, - ...adjustedState, - searchQuery: "", - activeOptionIndex, - activationTrigger: - (_a3 = action.trigger) != null ? _a3 : 1 /* Other */, - }; - }, - [3 /* Search */]: (state, action) => { - if (state.dataRef.current.disabled) return state; - if (state.listboxState === 1 /* Closed */) return state; - let wasAlreadySearching = state.searchQuery !== ""; - let offset = wasAlreadySearching ? 0 : 1; - let searchQuery = state.searchQuery + action.value.toLowerCase(); - let reOrderedOptions = - state.activeOptionIndex !== null - ? state.options - .slice(state.activeOptionIndex + offset) - .concat( - state.options.slice(0, state.activeOptionIndex + offset) - ) - : state.options; - let matchingOption = reOrderedOptions.find((option) => { - var _a3; - return ( - !option.dataRef.current.disabled && - ((_a3 = option.dataRef.current.textValue) == null - ? void 0 - : _a3.startsWith(searchQuery)) - ); - }); - let matchIdx = matchingOption - ? state.options.indexOf(matchingOption) - : -1; - if (matchIdx === -1 || matchIdx === state.activeOptionIndex) - return { ...state, searchQuery }; - return { - ...state, - searchQuery, - activeOptionIndex: matchIdx, - activationTrigger: 1 /* Other */, - }; - }, - [4 /* ClearSearch */](state) { - if (state.dataRef.current.disabled) return state; - if (state.listboxState === 1 /* Closed */) return state; - if (state.searchQuery === "") return state; - return { ...state, searchQuery: "" }; - }, - [5 /* RegisterOption */]: (state, action) => { - let option = { id: action.id, dataRef: action.dataRef }; - let adjustedState = adjustOrderedState2(state, (options) => [ - ...options, - option, - ]); - if (state.activeOptionIndex === null) { - if ( - state.dataRef.current.isSelected(action.dataRef.current.value) - ) { - adjustedState.activeOptionIndex = - adjustedState.options.indexOf(option); - } - } - return { ...state, ...adjustedState }; - }, - [6 /* UnregisterOption */]: (state, action) => { - let adjustedState = adjustOrderedState2(state, (options) => { - let idx = options.findIndex((a) => a.id === action.id); - if (idx !== -1) options.splice(idx, 1); - return options; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */, - }; - }, - [7 /* RegisterLabel */]: (state, action) => { - return { - ...state, - labelId: action.id, - }; - }, - }; - var ListboxActionsContext = (0, import_react35.createContext)(null); - ListboxActionsContext.displayName = "ListboxActionsContext"; - function useActions2(component) { - let context = (0, import_react35.useContext)(ListboxActionsContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useActions2); - throw err; + if ((_a = expected.match) === null || _a === void 0 ? void 0 : _a.call(expected, token)) { + if (expected.update) { + expected.update(state, token); } - return context; - } - var ListboxDataContext = (0, import_react35.createContext)(null); - ListboxDataContext.displayName = "ListboxDataContext"; - function useData2(component) { - let context = (0, import_react35.useContext)(ListboxDataContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) Error.captureStackTrace(err, useData2); - throw err; + if (token.kind === 'Punctuation') { + advanceRule(state, true); + } else { + state.needsAdvance = true; } - return context; + return expected.style; } - function stateReducer4(state, action) { - return match(action.type, reducers4, state, action); + } + unsuccessful(state); + } + assign(state, backupState); + pushRule(SpecialParseRules, state, 'Invalid'); + return 'invalidchar'; + } + function assign(to, from) { + const keys = Object.keys(from); + for (let i = 0; i < keys.length; i++) { + to[keys[i]] = from[keys[i]]; + } + return to; + } + const SpecialParseRules = { + Invalid: [], + Comment: [] + }; + function pushRule(rules, state, ruleKind) { + if (!rules[ruleKind]) { + throw new TypeError('Unknown rule: ' + ruleKind); + } + state.prevState = Object.assign({}, state); + state.kind = ruleKind; + state.name = null; + state.type = null; + state.rule = rules[ruleKind]; + state.step = 0; + state.needsSeparator = false; + } + function popRule(state) { + if (!state.prevState) { + return; + } + state.kind = state.prevState.kind; + state.name = state.prevState.name; + state.type = state.prevState.type; + state.rule = state.prevState.rule; + state.step = state.prevState.step; + state.needsSeparator = state.prevState.needsSeparator; + state.prevState = state.prevState.prevState; + } + function advanceRule(state, successful) { + var _a; + if (isList(state) && state.rule) { + const step = state.rule[state.step]; + if (step.separator) { + const { + separator + } = step; + state.needsSeparator = !state.needsSeparator; + if (!state.needsSeparator && separator.ofRule) { + return; } - var DEFAULT_LISTBOX_TAG = import_react35.Fragment; - function ListboxFn(props, ref) { - let { - value: controlledValue, - defaultValue, - form: formName, - name, - onChange: controlledOnChange, - by = (a, z) => a === z, - disabled = false, - horizontal = false, - multiple = false, - ...theirProps - } = props; - const orientation = horizontal ? "horizontal" : "vertical"; - let listboxRef = useSyncRefs(ref); - let [value = multiple ? [] : void 0, theirOnChange] = useControllable( - controlledValue, - controlledOnChange, - defaultValue - ); - let [state, dispatch] = (0, import_react35.useReducer)( - stateReducer4, - { - dataRef: (0, import_react35.createRef)(), - listboxState: 1 /* Closed */, - options: [], - searchQuery: "", - labelId: null, - activeOptionIndex: null, - activationTrigger: 1 /* Other */, - } - ); - let optionsPropsRef = (0, import_react35.useRef)({ - static: false, - hold: false, - }); - let labelRef = (0, import_react35.useRef)(null); - let buttonRef = (0, import_react35.useRef)(null); - let optionsRef = (0, import_react35.useRef)(null); - let compare = useEvent( - typeof by === "string" - ? (a, z) => { - let property = by; - return ( - (a == null ? void 0 : a[property]) === - (z == null ? void 0 : z[property]) - ); - } - : by - ); - let isSelected = (0, import_react35.useCallback)( - (compareValue) => - match(data.mode, { - [1 /* Multi */]: () => - value.some((option) => compare(option, compareValue)), - [0 /* Single */]: () => compare(value, compareValue), - }), - [value] - ); - let data = (0, import_react35.useMemo)( - () => ({ - ...state, - value, - disabled, - mode: multiple ? 1 /* Multi */ : 0 /* Single */, - orientation, - compare, - isSelected, - optionsPropsRef, - labelRef, - buttonRef, - optionsRef, - }), - [value, disabled, multiple, state] - ); - useIsoMorphicEffect(() => { - state.dataRef.current = data; - }, [data]); - useOutsideClick( - [data.buttonRef, data.optionsRef], - (event, target) => { - var _a3; - dispatch({ type: 1 /* CloseListbox */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus(); - } - }, - data.listboxState === 0 /* Open */ - ); - let slot = (0, import_react35.useMemo)( - () => ({ - open: data.listboxState === 0 /* Open */, - disabled, - value, - }), - [data, disabled, value] - ); - let selectOption = useEvent((id) => { - let option = data.options.find((item) => item.id === id); - if (!option) return; - onChange(option.dataRef.current.value); - }); - let selectActiveOption = useEvent(() => { - if (data.activeOptionIndex !== null) { - let { dataRef, id } = data.options[data.activeOptionIndex]; - onChange(dataRef.current.value); - dispatch({ - type: 2 /* GoToOption */, - focus: 4 /* Specific */, - id, - }); - } - }); - let openListbox = useEvent(() => - dispatch({ type: 0 /* OpenListbox */ }) - ); - let closeListbox = useEvent(() => - dispatch({ type: 1 /* CloseListbox */ }) - ); - let goToOption = useEvent((focus, id, trigger) => { - if (focus === 4 /* Specific */) { - return dispatch({ - type: 2 /* GoToOption */, - focus: 4 /* Specific */, - id, - trigger, - }); - } - return dispatch({ type: 2 /* GoToOption */, focus, trigger }); - }); - let registerOption = useEvent((id, dataRef) => { - dispatch({ type: 5 /* RegisterOption */, id, dataRef }); - return () => dispatch({ type: 6 /* UnregisterOption */, id }); - }); - let registerLabel = useEvent((id) => { - dispatch({ type: 7 /* RegisterLabel */, id }); - return () => dispatch({ type: 7 /* RegisterLabel */, id: null }); - }); - let onChange = useEvent((value2) => { - return match(data.mode, { - [0 /* Single */]() { - return theirOnChange == null ? void 0 : theirOnChange(value2); - }, - [1 /* Multi */]() { - let copy = data.value.slice(); - let idx = copy.findIndex((item) => compare(item, value2)); - if (idx === -1) { - copy.push(value2); - } else { - copy.splice(idx, 1); - } - return theirOnChange == null ? void 0 : theirOnChange(copy); - }, - }); - }); - let search = useEvent((value2) => - dispatch({ type: 3 /* Search */, value: value2 }) - ); - let clearSearch = useEvent(() => - dispatch({ type: 4 /* ClearSearch */ }) - ); - let actions = (0, import_react35.useMemo)( - () => ({ - onChange, - registerOption, - registerLabel, - goToOption, - closeListbox, - openListbox, - selectActiveOption, - selectOption, - search, - clearSearch, - }), - [] - ); - let ourProps = { ref: listboxRef }; - let form = (0, import_react35.useRef)(null); - let d = useDisposables(); - (0, import_react35.useEffect)(() => { - if (!form.current) return; - if (defaultValue === void 0) return; - d.addEventListener(form.current, "reset", () => { - onChange(defaultValue); - }); - }, [ - form, - onChange, - /* Explicitly ignoring `defaultValue` */ - ]); - return /* @__PURE__ */ import_react35.default.createElement( - ListboxActionsContext.Provider, - { value: actions }, - /* @__PURE__ */ import_react35.default.createElement( - ListboxDataContext.Provider, - { value: data }, - /* @__PURE__ */ import_react35.default.createElement( - OpenClosedProvider, - { - value: match(data.listboxState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */, - }), - }, - name != null && - value != null && - objectToFormEntries({ [name]: value }).map( - ([name2, value2], idx) => - /* @__PURE__ */ import_react35.default.createElement( - Hidden, - { - features: 4 /* Hidden */, - ref: - idx === 0 - ? (element) => { - var _a3; - form.current = - (_a3 = - element == null - ? void 0 - : element.closest("form")) != null - ? _a3 - : null; - } - : void 0, - ...compact({ - key: name2, - as: "input", - type: "hidden", - hidden: true, - readOnly: true, - form: formName, - name: name2, - value: value2, - }), - } - ) - ), - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_LISTBOX_TAG, - name: "Listbox", - }) - ) - ) - ); + } + if (successful) { + return; + } + } + state.needsSeparator = false; + state.step++; + while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) { + popRule(state); + if (state.rule) { + if (isList(state)) { + if ((_a = state.rule) === null || _a === void 0 ? void 0 : _a[state.step].separator) { + state.needsSeparator = !state.needsSeparator; + } + } else { + state.needsSeparator = false; + state.step++; } - var DEFAULT_BUTTON_TAG3 = "button"; - function ButtonFn3(props, ref) { - var _a3; - let internalId = useId(); - let { - id = `headlessui-listbox-button-${internalId}`, - ...theirProps - } = props; - let data = useData2("Listbox.Button"); - let actions = useActions2("Listbox.Button"); - let buttonRef = useSyncRefs(data.buttonRef, ref); - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - actions.openListbox(); - d.nextFrame(() => { - if (!data.value) actions.goToOption(0 /* First */); - }); - break; - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - actions.openListbox(); - d.nextFrame(() => { - if (!data.value) actions.goToOption(3 /* Last */); - }); - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (data.listboxState === 0 /* Open */) { - actions.closeListbox(); - d.nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - } else { - event.preventDefault(); - actions.openListbox(); + } + } + } + function isList(state) { + const step = Array.isArray(state.rule) && typeof state.rule[state.step] !== 'string' && state.rule[state.step]; + return step && step.isList; + } + function unsuccessful(state) { + while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) { + popRule(state); + } + if (state.rule) { + advanceRule(state, false); + } + } + function lex(lexRules, stream) { + const kinds = Object.keys(lexRules); + for (let i = 0; i < kinds.length; i++) { + const match = stream.match(lexRules[kinds[i]]); + if (match && match instanceof Array) { + return { + kind: kinds[i], + value: match[0] + }; + } + } + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/parser/types.js": + /*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/types.js ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.RuleKinds = exports.AdditionalRuleKinds = void 0; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const AdditionalRuleKinds = exports.AdditionalRuleKinds = { + ALIASED_FIELD: 'AliasedField', + ARGUMENTS: 'Arguments', + SHORT_QUERY: 'ShortQuery', + QUERY: 'Query', + MUTATION: 'Mutation', + SUBSCRIPTION: 'Subscription', + TYPE_CONDITION: 'TypeCondition', + INVALID: 'Invalid', + COMMENT: 'Comment', + SCHEMA_DEF: 'SchemaDef', + SCALAR_DEF: 'ScalarDef', + OBJECT_TYPE_DEF: 'ObjectTypeDef', + OBJECT_VALUE: 'ObjectValue', + LIST_VALUE: 'ListValue', + INTERFACE_DEF: 'InterfaceDef', + UNION_DEF: 'UnionDef', + ENUM_DEF: 'EnumDef', + ENUM_VALUE: 'EnumValue', + FIELD_DEF: 'FieldDef', + INPUT_DEF: 'InputDef', + INPUT_VALUE_DEF: 'InputValueDef', + ARGUMENTS_DEF: 'ArgumentsDef', + EXTEND_DEF: 'ExtendDef', + EXTENSION_DEFINITION: 'ExtensionDefinition', + DIRECTIVE_DEF: 'DirectiveDef', + IMPLEMENTS: 'Implements', + VARIABLE_DEFINITIONS: 'VariableDefinitions', + TYPE: 'Type', + VARIABLE: 'Variable' + }; + const RuleKinds = exports.RuleKinds = Object.assign(Object.assign({}, _graphql.Kind), AdditionalRuleKinds); + + /***/ }), + + /***/ "../../graphql-language-service/esm/types.js": + /*!***************************************************!*\ + !*** ../../graphql-language-service/esm/types.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.FileChangeTypeKind = exports.CompletionItemKind = void 0; + Object.defineProperty(exports, "GraphQLDocumentMode", ({ + enumerable: true, + get: function () { + return _parser.GraphQLDocumentMode; + } + })); + Object.defineProperty(exports, "InsertTextFormat", ({ + enumerable: true, + get: function () { + return _vscodeLanguageserverTypes.InsertTextFormat; + } + })); + var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); + var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); + const FileChangeTypeKind = exports.FileChangeTypeKind = { + Created: 1, + Changed: 2, + Deleted: 3 + }; + var CompletionItemKind; + (function (CompletionItemKind) { + CompletionItemKind.Text = 1; + CompletionItemKind.Method = 2; + CompletionItemKind.Function = 3; + CompletionItemKind.Constructor = 4; + CompletionItemKind.Field = 5; + CompletionItemKind.Variable = 6; + CompletionItemKind.Class = 7; + CompletionItemKind.Interface = 8; + CompletionItemKind.Module = 9; + CompletionItemKind.Property = 10; + CompletionItemKind.Unit = 11; + CompletionItemKind.Value = 12; + CompletionItemKind.Enum = 13; + CompletionItemKind.Keyword = 14; + CompletionItemKind.Snippet = 15; + CompletionItemKind.Color = 16; + CompletionItemKind.File = 17; + CompletionItemKind.Reference = 18; + CompletionItemKind.Folder = 19; + CompletionItemKind.EnumMember = 20; + CompletionItemKind.Constant = 21; + CompletionItemKind.Struct = 22; + CompletionItemKind.Event = 23; + CompletionItemKind.Operator = 24; + CompletionItemKind.TypeParameter = 25; + })(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/Range.js": + /*!*********************************************************!*\ + !*** ../../graphql-language-service/esm/utils/Range.js ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.Range = exports.Position = void 0; + exports.locToRange = locToRange; + exports.offsetToPosition = offsetToPosition; + class Range { + constructor(start, end) { + this.containsPosition = position => { + if (this.start.line === position.line) { + return this.start.character <= position.character; + } + if (this.end.line === position.line) { + return this.end.character >= position.character; + } + return this.start.line <= position.line && this.end.line >= position.line; + }; + this.start = start; + this.end = end; + } + setStart(line, character) { + this.start = new Position(line, character); + } + setEnd(line, character) { + this.end = new Position(line, character); + } + } + exports.Range = Range; + class Position { + constructor(line, character) { + this.lessThanOrEqualTo = position => this.line < position.line || this.line === position.line && this.character <= position.character; + this.line = line; + this.character = character; + } + setLine(line) { + this.line = line; + } + setCharacter(character) { + this.character = character; + } + } + exports.Position = Position; + function offsetToPosition(text, loc) { + const EOL = '\n'; + const buf = text.slice(0, loc); + const lines = buf.split(EOL).length - 1; + const lastLineIndex = buf.lastIndexOf(EOL); + return new Position(lines, loc - lastLineIndex - 1); + } + function locToRange(text, loc) { + const start = offsetToPosition(text, loc.start); + const end = offsetToPosition(text, loc.end); + return new Range(start, end); + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/collectVariables.js": + /*!********************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/collectVariables.js ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.collectVariables = collectVariables; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function collectVariables(schema, documentAST) { + const variableToType = Object.create(null); + for (const definition of documentAST.definitions) { + if (definition.kind === 'OperationDefinition') { + const { + variableDefinitions + } = definition; + if (variableDefinitions) { + for (const { + variable, + type + } of variableDefinitions) { + const inputType = (0, _graphql.typeFromAST)(schema, type); + if (inputType) { + variableToType[variable.name.value] = inputType; + } else if (type.kind === _graphql.Kind.NAMED_TYPE && type.name.value === 'Float') { + variableToType[variable.name.value] = _graphql.GraphQLFloat; } - }); - let labelledby = useComputed(() => { - if (!data.labelId) return void 0; - return [data.labelId, id].join(" "); - }, [data.labelId, id]); - let slot = (0, import_react35.useMemo)( - () => ({ - open: data.listboxState === 0 /* Open */, - disabled: data.disabled, - value: data.value, - }), - [data] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, data.buttonRef), - "aria-haspopup": "listbox", - "aria-controls": - (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled - ? void 0 - : data.listboxState === 0 /* Open */, - "aria-labelledby": labelledby, - disabled: data.disabled, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG3, - name: "Listbox.Button", - }); + } } - var DEFAULT_LABEL_TAG2 = "label"; - function LabelFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-listbox-label-${internalId}`, ...theirProps } = - props; - let data = useData2("Listbox.Label"); - let actions = useActions2("Listbox.Label"); - let labelRef = useSyncRefs(data.labelRef, ref); - useIsoMorphicEffect(() => actions.registerLabel(id), [id]); - let handleClick = useEvent(() => { - var _a3; - return (_a3 = data.buttonRef.current) == null - ? void 0 - : _a3.focus({ preventScroll: true }); - }); - let slot = (0, import_react35.useMemo)( - () => ({ - open: data.listboxState === 0 /* Open */, - disabled: data.disabled, - }), - [data] - ); - let ourProps = { ref: labelRef, id, onClick: handleClick }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_LABEL_TAG2, - name: "Listbox.Label", - }); + } + } + return variableToType; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/fragmentDependencies.js": + /*!************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/fragmentDependencies.js ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getFragmentDependenciesForAST = exports.getFragmentDependencies = void 0; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _nullthrows = _interopRequireDefault(__webpack_require__(/*! nullthrows */ "../../../node_modules/nullthrows/nullthrows.js")); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + const getFragmentDependencies = (operationString, fragmentDefinitions) => { + if (!fragmentDefinitions) { + return []; + } + let parsedOperation; + try { + parsedOperation = (0, _graphql.parse)(operationString); + } catch (_a) { + return []; + } + return getFragmentDependenciesForAST(parsedOperation, fragmentDefinitions); + }; + exports.getFragmentDependencies = getFragmentDependencies; + const getFragmentDependenciesForAST = (parsedOperation, fragmentDefinitions) => { + if (!fragmentDefinitions) { + return []; + } + const existingFrags = new Map(); + const referencedFragNames = new Set(); + (0, _graphql.visit)(parsedOperation, { + FragmentDefinition(node) { + existingFrags.set(node.name.value, true); + }, + FragmentSpread(node) { + if (!referencedFragNames.has(node.name.value)) { + referencedFragNames.add(node.name.value); } - var DEFAULT_OPTIONS_TAG2 = "ul"; - var OptionsRenderFeatures2 = 1 /* RenderStrategy */ | 2; /* Static */ - function OptionsFn2(props, ref) { - var _a3; - let internalId = useId(); - let { - id = `headlessui-listbox-options-${internalId}`, - ...theirProps - } = props; - let data = useData2("Listbox.Options"); - let actions = useActions2("Listbox.Options"); - let optionsRef = useSyncRefs(data.optionsRef, ref); - let d = useDisposables(); - let searchDisposables = useDisposables(); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - return data.listboxState === 0 /* Open */; - })(); - (0, import_react35.useEffect)(() => { - var _a4; - let container = data.optionsRef.current; - if (!container) return; - if (data.listboxState !== 0 /* Open */) return; - if ( - container === - ((_a4 = getOwnerDocument(container)) == null - ? void 0 - : _a4.activeElement) - ) - return; - container.focus({ preventScroll: true }); - }, [data.listboxState, data.optionsRef]); - let handleKeyDown = useEvent((event) => { - searchDisposables.dispose(); - switch (event.key) { - case " " /* Space */: - if (data.searchQuery !== "") { - event.preventDefault(); - event.stopPropagation(); - return actions.search(event.key); - } - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - if (data.activeOptionIndex !== null) { - let { dataRef } = data.options[data.activeOptionIndex]; - actions.onChange(dataRef.current.value); - } - if (data.mode === 0 /* Single */) { - actions.closeListbox(); - disposables().nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - } - break; - case match(data.orientation, { - vertical: "ArrowDown" /* ArrowDown */, - horizontal: "ArrowRight" /* ArrowRight */, - }): - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(2 /* Next */); - case match(data.orientation, { - vertical: "ArrowUp" /* ArrowUp */, - horizontal: "ArrowLeft" /* ArrowLeft */, - }): - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(1 /* Previous */); - case "Home" /* Home */: - case "PageUp" /* PageUp */: - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "End" /* End */: - case "PageDown" /* PageDown */: - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "Escape" /* Escape */: - event.preventDefault(); - event.stopPropagation(); - actions.closeListbox(); - return d.nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - case "Tab" /* Tab */: - event.preventDefault(); - event.stopPropagation(); - break; - default: - if (event.key.length === 1) { - actions.search(event.key); - searchDisposables.setTimeout( - () => actions.clearSearch(), - 350 - ); - } - break; - } - }); - let labelledby = useComputed(() => { - var _a4, _b, _c; - return (_c = - (_a4 = data.labelRef.current) == null ? void 0 : _a4.id) != null - ? _c - : (_b = data.buttonRef.current) == null - ? void 0 - : _b.id; - }, [data.labelRef.current, data.buttonRef.current]); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */ }), - [data] - ); - let ourProps = { - "aria-activedescendant": - data.activeOptionIndex === null - ? void 0 - : (_a3 = data.options[data.activeOptionIndex]) == null - ? void 0 - : _a3.id, - "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, - "aria-labelledby": labelledby, - "aria-orientation": data.orientation, - id, - onKeyDown: handleKeyDown, - role: "listbox", - tabIndex: 0, - ref: optionsRef, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTIONS_TAG2, - features: OptionsRenderFeatures2, - visible, - name: "Listbox.Options", - }); + } + }); + const asts = new Set(); + for (const name of referencedFragNames) { + if (!existingFrags.has(name) && fragmentDefinitions.has(name)) { + asts.add((0, _nullthrows.default)(fragmentDefinitions.get(name))); + } + } + const referencedFragments = []; + for (const ast of asts) { + (0, _graphql.visit)(ast, { + FragmentSpread(node) { + if (!referencedFragNames.has(node.name.value) && fragmentDefinitions.get(node.name.value)) { + asts.add((0, _nullthrows.default)(fragmentDefinitions.get(node.name.value))); + referencedFragNames.add(node.name.value); + } + } + }); + if (!existingFrags.has(ast.name.value)) { + referencedFragments.push(ast); + } + } + return referencedFragments; + }; + exports.getFragmentDependenciesForAST = getFragmentDependenciesForAST; + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js": + /*!************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getASTNodeAtPosition.js ***! + \************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getASTNodeAtPosition = getASTNodeAtPosition; + exports.pointToOffset = pointToOffset; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function getASTNodeAtPosition(query, ast, point) { + const offset = pointToOffset(query, point); + let nodeContainingPosition; + (0, _graphql.visit)(ast, { + enter(node) { + if (node.kind !== 'Name' && node.loc && node.loc.start <= offset && offset <= node.loc.end) { + nodeContainingPosition = node; + } else { + return false; } - var DEFAULT_OPTION_TAG2 = "li"; - function OptionFn2(props, ref) { - let internalId = useId(); - let { - id = `headlessui-listbox-option-${internalId}`, - disabled = false, - value, - ...theirProps - } = props; - let data = useData2("Listbox.Option"); - let actions = useActions2("Listbox.Option"); - let active = - data.activeOptionIndex !== null - ? data.options[data.activeOptionIndex].id === id - : false; - let selected = data.isSelected(value); - let internalOptionRef = (0, import_react35.useRef)(null); - let getTextValue2 = useTextValue(internalOptionRef); - let bag = useLatestValue({ - disabled, - value, - domRef: internalOptionRef, - get textValue() { - return getTextValue2(); - }, - }); - let optionRef = useSyncRefs(ref, internalOptionRef); - useIsoMorphicEffect(() => { - if (data.listboxState !== 0 /* Open */) return; - if (!active) return; - if (data.activationTrigger === 0 /* Pointer */) return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a3, _b; - (_b = - (_a3 = internalOptionRef.current) == null - ? void 0 - : _a3.scrollIntoView) == null - ? void 0 - : _b.call(_a3, { block: "nearest" }); - }); - return d.dispose; - }, [ - internalOptionRef, - active, - data.listboxState, - data.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - data.activeOptionIndex, - ]); - useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); - let handleClick = useEvent((event) => { - if (disabled) return event.preventDefault(); - actions.onChange(value); - if (data.mode === 0 /* Single */) { - actions.closeListbox(); - disposables().nextFrame(() => { - var _a3; - return (_a3 = data.buttonRef.current) == null - ? void 0 - : _a3.focus({ preventScroll: true }); - }); - } - }); - let handleFocus = useEvent(() => { - if (disabled) return actions.goToOption(5 /* Nothing */); - actions.goToOption(4 /* Specific */, id); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) return; - if (disabled) return; - if (active) return; - actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) return; - if (disabled) return; - if (!active) return; - actions.goToOption(5 /* Nothing */); + }, + leave(node) { + if (node.loc && node.loc.start <= offset && offset <= node.loc.end) { + return false; + } + } + }); + return nodeContainingPosition; + } + function pointToOffset(text, point) { + const linesUntilPosition = text.split('\n').slice(0, point.line); + return point.character + linesUntilPosition.map(line => line.length + 1).reduce((a, b) => a + b, 0); + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/getOperationFacts.js": + /*!*********************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getOperationFacts.js ***! + \*********************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports["default"] = getOperationFacts; + exports.getOperationASTFacts = getOperationASTFacts; + exports.getQueryFacts = void 0; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); + function getOperationASTFacts(documentAST, schema) { + const variableToType = schema ? (0, _collectVariables.collectVariables)(schema, documentAST) : undefined; + const operations = []; + (0, _graphql.visit)(documentAST, { + OperationDefinition(node) { + operations.push(node); + } + }); + return { + variableToType, + operations + }; + } + function getOperationFacts(schema, documentString) { + if (!documentString) { + return; + } + try { + const documentAST = (0, _graphql.parse)(documentString); + return Object.assign(Object.assign({}, getOperationASTFacts(documentAST, schema)), { + documentAST + }); + } catch (_a) { + return; + } + } + const getQueryFacts = exports.getQueryFacts = getOperationFacts; + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js": + /*!**************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getVariablesJSONSchema.js ***! + \**************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.defaultJSONSchemaOptions = void 0; + exports.getVariablesJSONSchema = getVariablesJSONSchema; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const defaultJSONSchemaOptions = exports.defaultJSONSchemaOptions = { + useMarkdownDescription: false + }; + function text(into, newText) { + into.push(newText); + } + function renderType(into, t) { + if ((0, _graphql.isNonNullType)(t)) { + renderType(into, t.ofType); + text(into, '!'); + } else if ((0, _graphql.isListType)(t)) { + text(into, '['); + renderType(into, t.ofType); + text(into, ']'); + } else { + text(into, t.name); + } + } + function renderDefinitionDescription(t, useMarkdown, description) { + const into = []; + const type = 'type' in t ? t.type : t; + if ('type' in t && t.description) { + text(into, t.description); + text(into, '\n\n'); + } + text(into, renderTypeToString(type, useMarkdown)); + if (description) { + text(into, '\n'); + text(into, description); + } else if (!(0, _graphql.isScalarType)(type) && 'description' in type && type.description) { + text(into, '\n'); + text(into, type.description); + } else if ('ofType' in type && !(0, _graphql.isScalarType)(type.ofType) && 'description' in type.ofType && type.ofType.description) { + text(into, '\n'); + text(into, type.ofType.description); + } + return into.join(''); + } + function renderTypeToString(t, useMarkdown) { + const into = []; + if (useMarkdown) { + text(into, '```graphql\n'); + } + renderType(into, t); + if (useMarkdown) { + text(into, '\n```'); + } + return into.join(''); + } + const defaultScalarTypesMap = { + Int: { + type: 'integer' + }, + String: { + type: 'string' + }, + Float: { + type: 'number' + }, + ID: { + type: 'string' + }, + Boolean: { + type: 'boolean' + }, + DateTime: { + type: 'string' + } + }; + class Marker { + constructor() { + this.set = new Set(); + } + mark(name) { + if (this.set.has(name)) { + return false; + } + this.set.add(name); + return true; + } + } + function getJSONSchemaFromGraphQLType(fieldOrType, options) { + var _a, _b; + let definition = Object.create(null); + const definitions = Object.create(null); + const isField = ('type' in fieldOrType); + const type = isField ? fieldOrType.type : fieldOrType; + const baseType = (0, _graphql.isNonNullType)(type) ? type.ofType : type; + const required = (0, _graphql.isNonNullType)(type); + if ((0, _graphql.isScalarType)(baseType)) { + if ((_a = options === null || options === void 0 ? void 0 : options.scalarSchemas) === null || _a === void 0 ? void 0 : _a[baseType.name]) { + definition = JSON.parse(JSON.stringify(options.scalarSchemas[baseType.name])); + } else { + definition.type = ['string', 'number', 'boolean', 'integer']; + } + if (!required) { + if (Array.isArray(definition.type)) { + definition.type.push('null'); + } else if (definition.type) { + definition.type = [definition.type, 'null']; + } else if (definition.enum) { + definition.enum.push(null); + } else if (definition.oneOf) { + definition.oneOf.push({ + type: 'null' }); - let slot = (0, import_react35.useMemo)( - () => ({ active, selected, disabled }), - [active, selected, disabled] - ); - let ourProps = { - id, - ref: optionRef, - role: "option", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - // According to the WAI-ARIA best practices, we should use aria-checked for - // multi-select,but Voice-Over disagrees. So we use aria-checked instead for - // both single and multi-select. - "aria-selected": selected, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave, + } else { + definition = { + oneOf: [definition, { + type: 'null' + }] }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTION_TAG2, - name: "Listbox.Option", - }); } - var ListboxRoot = forwardRefWithAs(ListboxFn); - var Button3 = forwardRefWithAs(ButtonFn3); - var Label2 = forwardRefWithAs(LabelFn2); - var Options2 = forwardRefWithAs(OptionsFn2); - var Option2 = forwardRefWithAs(OptionFn2); - var Listbox = Object.assign(ListboxRoot, { - Button: Button3, - Label: Label2, - Options: Options2, - Option: Option2, - }); - - // src/components/menu/menu.tsx - var import_react36 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - function adjustOrderedState3(state, adjustment = (i) => i) { - let currentActiveItem = - state.activeItemIndex !== null - ? state.items[state.activeItemIndex] - : null; - let sortedItems = sortByDomNode( - adjustment(state.items.slice()), - (item) => item.dataRef.current.domRef.current - ); - let adjustedActiveItemIndex = currentActiveItem - ? sortedItems.indexOf(currentActiveItem) - : null; - if (adjustedActiveItemIndex === -1) { - adjustedActiveItemIndex = null; - } - return { - items: sortedItems, - activeItemIndex: adjustedActiveItemIndex, - }; + } + } else if ((0, _graphql.isEnumType)(baseType)) { + definition.enum = baseType.getValues().map(val => val.name); + if (!required) { + definition.enum.push(null); + } + } else if ((0, _graphql.isListType)(baseType)) { + if (required) { + definition.type = 'array'; + } else { + definition.type = ['array', 'null']; + } + const { + definition: def, + definitions: defs + } = getJSONSchemaFromGraphQLType(baseType.ofType, options); + definition.items = def; + if (defs) { + for (const defName of Object.keys(defs)) { + definitions[defName] = defs[defName]; } - var reducers5 = { - [1 /* CloseMenu */](state) { - if (state.menuState === 1 /* Closed */) return state; - return { - ...state, - activeItemIndex: null, - menuState: 1 /* Closed */, - }; - }, - [0 /* OpenMenu */](state) { - if (state.menuState === 0 /* Open */) return state; - return { - ...state, - /* We can turn off demo mode once we re-open the `Menu` */ - __demoMode: false, - menuState: 0 /* Open */, - }; - }, - [2 /* GoToItem */]: (state, action) => { - var _a3; - let adjustedState = adjustOrderedState3(state); - let activeItemIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.items, - resolveActiveIndex: () => adjustedState.activeItemIndex, - resolveId: (item) => item.id, - resolveDisabled: (item) => item.dataRef.current.disabled, - }); - return { - ...state, - ...adjustedState, - searchQuery: "", - activeItemIndex, - activationTrigger: - (_a3 = action.trigger) != null ? _a3 : 1 /* Other */, - }; - }, - [3 /* Search */]: (state, action) => { - let wasAlreadySearching = state.searchQuery !== ""; - let offset = wasAlreadySearching ? 0 : 1; - let searchQuery = state.searchQuery + action.value.toLowerCase(); - let reOrderedItems = - state.activeItemIndex !== null - ? state.items - .slice(state.activeItemIndex + offset) - .concat( - state.items.slice(0, state.activeItemIndex + offset) - ) - : state.items; - let matchingItem = reOrderedItems.find((item) => { - var _a3; - return ( - ((_a3 = item.dataRef.current.textValue) == null - ? void 0 - : _a3.startsWith(searchQuery)) && - !item.dataRef.current.disabled - ); - }); - let matchIdx = matchingItem - ? state.items.indexOf(matchingItem) - : -1; - if (matchIdx === -1 || matchIdx === state.activeItemIndex) - return { ...state, searchQuery }; - return { - ...state, - searchQuery, - activeItemIndex: matchIdx, - activationTrigger: 1 /* Other */, - }; - }, - [4 /* ClearSearch */](state) { - if (state.searchQuery === "") return state; - return { ...state, searchQuery: "", searchActiveItemIndex: null }; - }, - [5 /* RegisterItem */]: (state, action) => { - let adjustedState = adjustOrderedState3(state, (items) => [ - ...items, - { id: action.id, dataRef: action.dataRef }, - ]); - return { ...state, ...adjustedState }; - }, - [6 /* UnregisterItem */]: (state, action) => { - let adjustedState = adjustOrderedState3(state, (items) => { - let idx = items.findIndex((a) => a.id === action.id); - if (idx !== -1) items.splice(idx, 1); - return items; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */, - }; - }, + } + } else if ((0, _graphql.isInputObjectType)(baseType)) { + if (required) { + definition.$ref = `#/definitions/${baseType.name}`; + } else { + definition.oneOf = [{ + $ref: `#/definitions/${baseType.name}` + }, { + type: 'null' + }]; + } + if ((_b = options === null || options === void 0 ? void 0 : options.definitionMarker) === null || _b === void 0 ? void 0 : _b.mark(baseType.name)) { + const fields = baseType.getFields(); + const fieldDef = { + type: 'object', + properties: {}, + required: [] }; - var MenuContext = (0, import_react36.createContext)(null); - MenuContext.displayName = "MenuContext"; - function useMenuContext(component) { - let context = (0, import_react36.useContext)(MenuContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent
    component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useMenuContext); - throw err; - } - return context; - } - function stateReducer5(state, action) { - return match(action.type, reducers5, state, action); - } - var DEFAULT_MENU_TAG = import_react36.Fragment; - function MenuFn(props, ref) { - let { __demoMode = false, ...theirProps } = props; - let reducerBag = (0, import_react36.useReducer)(stateReducer5, { - __demoMode, - menuState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - buttonRef: (0, import_react36.createRef)(), - itemsRef: (0, import_react36.createRef)(), - items: [], - searchQuery: "", - activeItemIndex: null, - activationTrigger: 1 /* Other */, - }); - let [{ menuState, itemsRef, buttonRef }, dispatch] = reducerBag; - let menuRef = useSyncRefs(ref); - useOutsideClick( - [buttonRef, itemsRef], - (event, target) => { - var _a3; - dispatch({ type: 1 /* CloseMenu */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - (_a3 = buttonRef.current) == null ? void 0 : _a3.focus(); - } - }, - menuState === 0 /* Open */ - ); - let close = useEvent(() => { - dispatch({ type: 1 /* CloseMenu */ }); - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: menuState === 0 /* Open */, close }), - [menuState, close] - ); - let ourProps = { ref: menuRef }; - return /* @__PURE__ */ import_react36.default.createElement( - MenuContext.Provider, - { value: reducerBag }, - /* @__PURE__ */ import_react36.default.createElement( - OpenClosedProvider, - { - value: match(menuState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */, - }), - }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_MENU_TAG, - name: "Menu", - }) - ) - ); + fieldDef.description = renderDefinitionDescription(baseType); + if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { + fieldDef.markdownDescription = renderDefinitionDescription(baseType, true); } - var DEFAULT_BUTTON_TAG4 = "button"; - function ButtonFn4(props, ref) { - var _a3; - let internalId = useId(); - let { id = `headlessui-menu-button-${internalId}`, ...theirProps } = - props; - let [state, dispatch] = useMenuContext("Menu.Button"); - let buttonRef = useSyncRefs(state.buttonRef, ref); - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* OpenMenu */ }); - d.nextFrame(() => - dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ }) - ); - break; - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* OpenMenu */ }); - d.nextFrame(() => - dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ }) - ); - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (props.disabled) return; - if (state.menuState === 0 /* Open */) { - dispatch({ type: 1 /* CloseMenu */ }); - d.nextFrame(() => { - var _a4; - return (_a4 = state.buttonRef.current) == null - ? void 0 - : _a4.focus({ preventScroll: true }); - }); - } else { - event.preventDefault(); - dispatch({ type: 0 /* OpenMenu */ }); + for (const fieldName of Object.keys(fields)) { + const field = fields[fieldName]; + const { + required: fieldRequired, + definition: fieldDefinition, + definitions: typeDefinitions + } = getJSONSchemaFromGraphQLType(field, options); + fieldDef.properties[fieldName] = fieldDefinition; + if (fieldRequired) { + fieldDef.required.push(fieldName); + } + if (typeDefinitions) { + for (const [defName, value] of Object.entries(typeDefinitions)) { + definitions[defName] = value; } - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: state.menuState === 0 /* Open */ }), - [state] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, state.buttonRef), - "aria-haspopup": "menu", - "aria-controls": - (_a3 = state.itemsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": props.disabled - ? void 0 - : state.menuState === 0 /* Open */, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG4, - name: "Menu.Button", - }); + } } - var DEFAULT_ITEMS_TAG = "div"; - var ItemsRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ - function ItemsFn(props, ref) { - var _a3, _b; - let internalId = useId(); - let { id = `headlessui-menu-items-${internalId}`, ...theirProps } = - props; - let [state, dispatch] = useMenuContext("Menu.Items"); - let itemsRef = useSyncRefs(state.itemsRef, ref); - let ownerDocument = useOwnerDocument(state.itemsRef); - let searchDisposables = useDisposables(); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - return state.menuState === 0 /* Open */; - })(); - (0, import_react36.useEffect)(() => { - let container = state.itemsRef.current; - if (!container) return; - if (state.menuState !== 0 /* Open */) return; - if ( - container === - (ownerDocument == null ? void 0 : ownerDocument.activeElement) - ) - return; - container.focus({ preventScroll: true }); - }, [state.menuState, state.itemsRef, ownerDocument]); - useTreeWalker({ - container: state.itemsRef.current, - enabled: state.menuState === 0 /* Open */, - accept(node) { - if (node.getAttribute("role") === "menuitem") - return NodeFilter.FILTER_REJECT; - if (node.hasAttribute("role")) return NodeFilter.FILTER_SKIP; - return NodeFilter.FILTER_ACCEPT; - }, - walk(node) { - node.setAttribute("role", "none"); - }, - }); - let handleKeyDown = useEvent((event) => { - var _a4, _b2; - searchDisposables.dispose(); - switch (event.key) { - case " " /* Space */: - if (state.searchQuery !== "") { - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 3 /* Search */, value: event.key }); - } - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - if (state.activeItemIndex !== null) { - let { dataRef } = state.items[state.activeItemIndex]; - (_b2 = - (_a4 = dataRef.current) == null - ? void 0 - : _a4.domRef.current) == null - ? void 0 - : _b2.click(); - } - restoreFocusIfNecessary(state.buttonRef.current); - break; - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ - type: 2 /* GoToItem */, - focus: 2 /* Next */, - }); - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ - type: 2 /* GoToItem */, - focus: 1 /* Previous */, - }); - case "Home" /* Home */: - case "PageUp" /* PageUp */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ - type: 2 /* GoToItem */, - focus: 0 /* First */, - }); - case "End" /* End */: - case "PageDown" /* PageDown */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ - type: 2 /* GoToItem */, - focus: 3 /* Last */, - }); - case "Escape" /* Escape */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - disposables().nextFrame(() => { - var _a5; - return (_a5 = state.buttonRef.current) == null - ? void 0 - : _a5.focus({ preventScroll: true }); - }); - break; - case "Tab" /* Tab */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - disposables().nextFrame(() => { - focusFrom( - state.buttonRef.current, - event.shiftKey ? 2 /* Previous */ : 4 /* Next */ - ); - }); - break; - default: - if (event.key.length === 1) { - dispatch({ type: 3 /* Search */, value: event.key }); - searchDisposables.setTimeout( - () => dispatch({ type: 4 /* ClearSearch */ }), - 350 - ); - } - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: state.menuState === 0 /* Open */ }), - [state] - ); - let ourProps = { - "aria-activedescendant": - state.activeItemIndex === null - ? void 0 - : (_a3 = state.items[state.activeItemIndex]) == null - ? void 0 - : _a3.id, - "aria-labelledby": - (_b = state.buttonRef.current) == null ? void 0 : _b.id, - id, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - role: "menu", - tabIndex: 0, - ref: itemsRef, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_ITEMS_TAG, - features: ItemsRenderFeatures, - visible, - name: "Menu.Items", - }); + definitions[baseType.name] = fieldDef; + } + } + if ('defaultValue' in fieldOrType && fieldOrType.defaultValue !== undefined) { + definition.default = fieldOrType.defaultValue; + } + const { + description + } = definition; + definition.description = renderDefinitionDescription(fieldOrType, false, description); + if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { + definition.markdownDescription = renderDefinitionDescription(fieldOrType, true, description); + } + return { + required, + definition, + definitions + }; + } + function getVariablesJSONSchema(variableToType, options) { + var _a; + const jsonSchema = { + $schema: 'http://json-schema.org/draft-04/schema', + type: 'object', + properties: {}, + required: [] + }; + const runtimeOptions = Object.assign(Object.assign({}, options), { + definitionMarker: new Marker(), + scalarSchemas: Object.assign(Object.assign({}, defaultScalarTypesMap), options === null || options === void 0 ? void 0 : options.scalarSchemas) + }); + if (variableToType) { + for (const [variableName, type] of Object.entries(variableToType)) { + const { + definition, + required, + definitions + } = getJSONSchemaFromGraphQLType(type, runtimeOptions); + jsonSchema.properties[variableName] = definition; + if (required) { + (_a = jsonSchema.required) === null || _a === void 0 ? void 0 : _a.push(variableName); } - var DEFAULT_ITEM_TAG = import_react36.Fragment; - function ItemFn(props, ref) { - let internalId = useId(); - let { - id = `headlessui-menu-item-${internalId}`, - disabled = false, - ...theirProps - } = props; - let [state, dispatch] = useMenuContext("Menu.Item"); - let active = - state.activeItemIndex !== null - ? state.items[state.activeItemIndex].id === id - : false; - let internalItemRef = (0, import_react36.useRef)(null); - let itemRef = useSyncRefs(ref, internalItemRef); - useIsoMorphicEffect(() => { - if (state.__demoMode) return; - if (state.menuState !== 0 /* Open */) return; - if (!active) return; - if (state.activationTrigger === 0 /* Pointer */) return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a3, _b; - (_b = - (_a3 = internalItemRef.current) == null - ? void 0 - : _a3.scrollIntoView) == null - ? void 0 - : _b.call(_a3, { block: "nearest" }); - }); - return d.dispose; - }, [ - state.__demoMode, - internalItemRef, - active, - state.menuState, - state.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - state.activeItemIndex, - ]); - let getTextValue2 = useTextValue(internalItemRef); - let bag = (0, import_react36.useRef)({ - disabled, - domRef: internalItemRef, - get textValue() { - return getTextValue2(); - }, - }); - useIsoMorphicEffect(() => { - bag.current.disabled = disabled; - }, [bag, disabled]); - useIsoMorphicEffect(() => { - dispatch({ type: 5 /* RegisterItem */, id, dataRef: bag }); - return () => dispatch({ type: 6 /* UnregisterItem */, id }); - }, [bag, id]); - let close = useEvent(() => { - dispatch({ type: 1 /* CloseMenu */ }); - }); - let handleClick = useEvent((event) => { - if (disabled) return event.preventDefault(); - dispatch({ type: 1 /* CloseMenu */ }); - restoreFocusIfNecessary(state.buttonRef.current); - }); - let handleFocus = useEvent(() => { - if (disabled) - return dispatch({ - type: 2 /* GoToItem */, - focus: 5 /* Nothing */, - }); - dispatch({ type: 2 /* GoToItem */, focus: 4 /* Specific */, id }); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) return; - if (disabled) return; - if (active) return; - dispatch({ - type: 2 /* GoToItem */, - focus: 4 /* Specific */, - id, - trigger: 0 /* Pointer */, - }); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) return; - if (disabled) return; - if (!active) return; - dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); - }); - let slot = (0, import_react36.useMemo)( - () => ({ active, disabled, close }), - [active, disabled, close] - ); - let ourProps = { - id, - ref: itemRef, - role: "menuitem", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_ITEM_TAG, - name: "Menu.Item", - }); + if (definitions) { + jsonSchema.definitions = Object.assign(Object.assign({}, jsonSchema === null || jsonSchema === void 0 ? void 0 : jsonSchema.definitions), definitions); + } + } + } + return jsonSchema; + } + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/index.js": + /*!*********************************************************!*\ + !*** ../../graphql-language-service/esm/utils/index.js ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + Object.defineProperty(exports, "Position", ({ + enumerable: true, + get: function () { + return _Range.Position; + } + })); + Object.defineProperty(exports, "Range", ({ + enumerable: true, + get: function () { + return _Range.Range; + } + })); + Object.defineProperty(exports, "collectVariables", ({ + enumerable: true, + get: function () { + return _collectVariables.collectVariables; + } + })); + Object.defineProperty(exports, "getASTNodeAtPosition", ({ + enumerable: true, + get: function () { + return _getASTNodeAtPosition.getASTNodeAtPosition; + } + })); + Object.defineProperty(exports, "getFragmentDependencies", ({ + enumerable: true, + get: function () { + return _fragmentDependencies.getFragmentDependencies; + } + })); + Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ + enumerable: true, + get: function () { + return _fragmentDependencies.getFragmentDependenciesForAST; + } + })); + Object.defineProperty(exports, "getOperationASTFacts", ({ + enumerable: true, + get: function () { + return _getOperationFacts.getOperationASTFacts; + } + })); + Object.defineProperty(exports, "getOperationFacts", ({ + enumerable: true, + get: function () { + return _getOperationFacts.default; + } + })); + Object.defineProperty(exports, "getQueryFacts", ({ + enumerable: true, + get: function () { + return _getOperationFacts.getQueryFacts; + } + })); + Object.defineProperty(exports, "getVariablesJSONSchema", ({ + enumerable: true, + get: function () { + return _getVariablesJSONSchema.getVariablesJSONSchema; + } + })); + Object.defineProperty(exports, "locToRange", ({ + enumerable: true, + get: function () { + return _Range.locToRange; + } + })); + Object.defineProperty(exports, "offsetToPosition", ({ + enumerable: true, + get: function () { + return _Range.offsetToPosition; + } + })); + Object.defineProperty(exports, "pointToOffset", ({ + enumerable: true, + get: function () { + return _getASTNodeAtPosition.pointToOffset; + } + })); + Object.defineProperty(exports, "validateWithCustomRules", ({ + enumerable: true, + get: function () { + return _validateWithCustomRules.validateWithCustomRules; + } + })); + var _fragmentDependencies = __webpack_require__(/*! ./fragmentDependencies */ "../../graphql-language-service/esm/utils/fragmentDependencies.js"); + var _getVariablesJSONSchema = __webpack_require__(/*! ./getVariablesJSONSchema */ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js"); + var _getASTNodeAtPosition = __webpack_require__(/*! ./getASTNodeAtPosition */ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js"); + var _Range = __webpack_require__(/*! ./Range */ "../../graphql-language-service/esm/utils/Range.js"); + var _validateWithCustomRules = __webpack_require__(/*! ./validateWithCustomRules */ "../../graphql-language-service/esm/utils/validateWithCustomRules.js"); + var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); + var _getOperationFacts = _interopRequireWildcard(__webpack_require__(/*! ./getOperationFacts */ "../../graphql-language-service/esm/utils/getOperationFacts.js")); + function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } + function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + + /***/ }), + + /***/ "../../graphql-language-service/esm/utils/validateWithCustomRules.js": + /*!***************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/validateWithCustomRules.js ***! + \***************************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.validateWithCustomRules = validateWithCustomRules; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const specifiedSDLRules = [_graphql.LoneSchemaDefinitionRule, _graphql.UniqueOperationTypesRule, _graphql.UniqueTypeNamesRule, _graphql.UniqueEnumValueNamesRule, _graphql.UniqueFieldDefinitionNamesRule, _graphql.UniqueDirectiveNamesRule, _graphql.KnownTypeNamesRule, _graphql.KnownDirectivesRule, _graphql.UniqueDirectivesPerLocationRule, _graphql.PossibleTypeExtensionsRule, _graphql.UniqueArgumentNamesRule, _graphql.UniqueInputFieldNamesRule, _graphql.UniqueVariableNamesRule, _graphql.FragmentsOnCompositeTypesRule, _graphql.ProvidedRequiredArgumentsRule]; + function validateWithCustomRules(schema, ast, customRules, isRelayCompatMode, isSchemaDocument) { + const rules = _graphql.specifiedRules.filter(rule => { + if (rule === _graphql.NoUnusedFragmentsRule || rule === _graphql.ExecutableDefinitionsRule) { + return false; + } + if (isRelayCompatMode && rule === _graphql.KnownFragmentNamesRule) { + return false; + } + return true; + }); + if (customRules) { + Array.prototype.push.apply(rules, customRules); + } + if (isSchemaDocument) { + Array.prototype.push.apply(rules, specifiedSDLRules); + } + const errors = (0, _graphql.validate)(schema, ast, rules); + return errors.filter(error => { + if (error.message.includes('Unknown directive') && error.nodes) { + const node = error.nodes[0]; + if (node && node.kind === _graphql.Kind.DIRECTIVE) { + const name = node.name.value; + if (name === 'arguments' || name === 'argumentDefinitions') { + return false; + } } - var MenuRoot = forwardRefWithAs(MenuFn); - var Button4 = forwardRefWithAs(ButtonFn4); - var Items = forwardRefWithAs(ItemsFn); - var Item = forwardRefWithAs(ItemFn); - var Menu = Object.assign(MenuRoot, { Button: Button4, Items, Item }); - - // src/components/popover/popover.tsx - var import_react37 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var reducers6 = { - [0 /* TogglePopover */]: (state) => { - let nextState = { - ...state, - popoverState: match(state.popoverState, { - [0 /* Open */]: 1 /* Closed */, - [1 /* Closed */]: 0 /* Open */, - }), - }; - if (nextState.popoverState === 0 /* Open */) { - nextState.__demoMode = false; + } + return true; + }); + } + + /***/ }), + + /***/ "./style.css": + /*!*******************!*\ + !*** ./style.css ***! + \*******************/ + /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + + /***/ }), + + /***/ "../../graphiql-react/dist/style.css": + /*!*******************************************!*\ + !*** ../../graphiql-react/dist/style.css ***! + \*******************************************/ + /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + + /***/ }), + + /***/ "../../graphiql-react/font/fira-code.css": + /*!***********************************************!*\ + !*** ../../graphiql-react/font/fira-code.css ***! + \***********************************************/ + /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + + /***/ }), + + /***/ "../../graphiql-react/font/roboto.css": + /*!********************************************!*\ + !*** ../../graphiql-react/font/roboto.css ***! + \********************************************/ + /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + + __webpack_require__.r(__webpack_exports__); + // extracted by mini-css-extract-plugin + + + /***/ }), + + /***/ "react": + /*!************************!*\ + !*** external "React" ***! + \************************/ + /***/ (function(module) { + + module.exports = window["React"]; + + /***/ }), + + /***/ "react-dom": + /*!***************************!*\ + !*** external "ReactDOM" ***! + \***************************/ + /***/ (function(module) { + + module.exports = window["ReactDOM"]; + + /***/ }), + + /***/ "../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs": + /*!***********************************************************************!*\ + !*** ../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs ***! + \***********************************************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + + // src/index.ts + var src_exports = {}; + __export(src_exports, { + Combobox: () => Combobox, + Dialog: () => Dialog, + Disclosure: () => Disclosure, + FocusTrap: () => FocusTrap, + Listbox: () => Listbox, + Menu: () => Menu, + Popover: () => Popover, + Portal: () => Portal, + RadioGroup: () => RadioGroup, + Switch: () => Switch, + Tab: () => Tab, + Transition: () => Transition + }); + module.exports = __toCommonJS(src_exports); + + // src/components/combobox/combobox.tsx + var import_react19 = __toESM(__webpack_require__(/*! react */ "react"), 1); + + // src/hooks/use-computed.ts + var import_react3 = __webpack_require__(/*! react */ "react"); + + // src/hooks/use-iso-morphic-effect.ts + var import_react = __webpack_require__(/*! react */ "react"); + + // src/utils/env.ts + var Env = class { + constructor() { + __publicField(this, "current", this.detect()); + __publicField(this, "handoffState", "pending"); + __publicField(this, "currentId", 0); + } + set(env2) { + if (this.current === env2) + return; + this.handoffState = "pending"; + this.currentId = 0; + this.current = env2; + } + reset() { + this.set(this.detect()); + } + nextId() { + return ++this.currentId; + } + get isServer() { + return this.current === "server"; + } + get isClient() { + return this.current === "client"; + } + detect() { + if (typeof window === "undefined" || typeof document === "undefined") { + return "server"; + } + return "client"; + } + handoff() { + if (this.handoffState === "pending") { + this.handoffState = "complete"; + } + } + get isHandoffComplete() { + return this.handoffState === "complete"; + } + }; + var env = new Env(); + + // src/hooks/use-iso-morphic-effect.ts + var useIsoMorphicEffect = (effect, deps) => { + if (env.isServer) { + (0, import_react.useEffect)(effect, deps); + } else { + (0, import_react.useLayoutEffect)(effect, deps); + } + }; + + // src/hooks/use-latest-value.ts + var import_react2 = __webpack_require__(/*! react */ "react"); + function useLatestValue(value) { + let cache = (0, import_react2.useRef)(value); + useIsoMorphicEffect(() => { + cache.current = value; + }, [value]); + return cache; + } + + // src/hooks/use-computed.ts + function useComputed(cb, dependencies) { + let [value, setValue] = (0, import_react3.useState)(cb); + let cbRef = useLatestValue(cb); + useIsoMorphicEffect(() => setValue(cbRef.current), [cbRef, setValue, ...dependencies]); + return value; + } + + // src/hooks/use-disposables.ts + var import_react4 = __webpack_require__(/*! react */ "react"); + + // src/utils/micro-task.ts + function microTask(cb) { + if (typeof queueMicrotask === "function") { + queueMicrotask(cb); + } else { + Promise.resolve().then(cb).catch( + (e) => setTimeout(() => { + throw e; + }) + ); + } + } + + // src/utils/disposables.ts + function disposables() { + let _disposables = []; + let api = { + addEventListener(element, name, listener, options) { + element.addEventListener(name, listener, options); + return api.add(() => element.removeEventListener(name, listener, options)); + }, + requestAnimationFrame(...args) { + let raf = requestAnimationFrame(...args); + return api.add(() => cancelAnimationFrame(raf)); + }, + nextFrame(...args) { + return api.requestAnimationFrame(() => { + return api.requestAnimationFrame(...args); + }); + }, + setTimeout(...args) { + let timer = setTimeout(...args); + return api.add(() => clearTimeout(timer)); + }, + microTask(...args) { + let task = { current: true }; + microTask(() => { + if (task.current) { + args[0](); + } + }); + return api.add(() => { + task.current = false; + }); + }, + style(node, property, value) { + let previous = node.style.getPropertyValue(property); + Object.assign(node.style, { [property]: value }); + return this.add(() => { + Object.assign(node.style, { [property]: previous }); + }); + }, + group(cb) { + let d = disposables(); + cb(d); + return this.add(() => d.dispose()); + }, + add(cb) { + _disposables.push(cb); + return () => { + let idx = _disposables.indexOf(cb); + if (idx >= 0) { + for (let dispose of _disposables.splice(idx, 1)) { + dispose(); } - return nextState; - }, - [1 /* ClosePopover */](state) { - if (state.popoverState === 1 /* Closed */) return state; - return { ...state, popoverState: 1 /* Closed */ }; - }, - [2 /* SetButton */](state, action) { - if (state.button === action.button) return state; - return { ...state, button: action.button }; - }, - [3 /* SetButtonId */](state, action) { - if (state.buttonId === action.buttonId) return state; - return { ...state, buttonId: action.buttonId }; - }, - [4 /* SetPanel */](state, action) { - if (state.panel === action.panel) return state; - return { ...state, panel: action.panel }; - }, - [5 /* SetPanelId */](state, action) { - if (state.panelId === action.panelId) return state; - return { ...state, panelId: action.panelId }; - }, - }; - var PopoverContext = (0, import_react37.createContext)(null); - PopoverContext.displayName = "PopoverContext"; - function usePopoverContext(component) { - let context = (0, import_react37.useContext)(PopoverContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, usePopoverContext); - throw err; } - return context; + }; + }, + dispose() { + for (let dispose of _disposables.splice(0)) { + dispose(); } - var PopoverAPIContext = (0, import_react37.createContext)(null); - PopoverAPIContext.displayName = "PopoverAPIContext"; - function usePopoverAPIContext(component) { - let context = (0, import_react37.useContext)(PopoverAPIContext); - if (context === null) { - let err = new Error( - `<${component} /> is missing a parent component.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, usePopoverAPIContext); - throw err; - } - return context; + } + }; + return api; + } + + // src/hooks/use-disposables.ts + function useDisposables() { + let [d] = (0, import_react4.useState)(disposables); + (0, import_react4.useEffect)(() => () => d.dispose(), [d]); + return d; + } + + // src/hooks/use-event.ts + var import_react5 = __toESM(__webpack_require__(/*! react */ "react"), 1); + var useEvent = ( + // TODO: Add React.useEvent ?? once the useEvent hook is available + function useEvent2(cb) { + let cache = useLatestValue(cb); + return import_react5.default.useCallback((...args) => cache.current(...args), [cache]); + } + ); + + // src/hooks/use-id.ts + var import_react7 = __toESM(__webpack_require__(/*! react */ "react"), 1); + + // src/hooks/use-server-handoff-complete.ts + var import_react6 = __webpack_require__(/*! react */ "react"); + function useServerHandoffComplete() { + let [complete, setComplete] = (0, import_react6.useState)(env.isHandoffComplete); + if (complete && env.isHandoffComplete === false) { + setComplete(false); + } + (0, import_react6.useEffect)(() => { + if (complete === true) + return; + setComplete(true); + }, [complete]); + (0, import_react6.useEffect)(() => env.handoff(), []); + return complete; + } + + // src/hooks/use-id.ts + var _a; + var useId = ( + // Prefer React's `useId` if it's available. + // @ts-expect-error - `useId` doesn't exist in React < 18. + (_a = import_react7.default.useId) != null ? _a : function useId2() { + let ready = useServerHandoffComplete(); + let [id, setId] = import_react7.default.useState(ready ? () => env.nextId() : null); + useIsoMorphicEffect(() => { + if (id === null) + setId(env.nextId()); + }, [id]); + return id != null ? "" + id : void 0; + } + ); + + // src/hooks/use-outside-click.ts + var import_react10 = __webpack_require__(/*! react */ "react"); + + // src/utils/match.ts + function match(value, lookup, ...args) { + if (value in lookup) { + let returnValue = lookup[value]; + return typeof returnValue === "function" ? returnValue(...args) : returnValue; + } + let error = new Error( + `Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys( + lookup + ).map((key) => `"${key}"`).join(", ")}.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(error, match); + throw error; + } + + // src/utils/owner.ts + function getOwnerDocument(element) { + if (env.isServer) + return null; + if (element instanceof Node) + return element.ownerDocument; + if (element == null ? void 0 : element.hasOwnProperty("current")) { + if (element.current instanceof Node) + return element.current.ownerDocument; + } + return document; + } + + // src/utils/focus-management.ts + var focusableSelector = [ + "[contentEditable=true]", + "[tabindex]", + "a[href]", + "area[href]", + "button:not([disabled])", + "iframe", + "input:not([disabled])", + "select:not([disabled])", + "textarea:not([disabled])" + ].map( + false ? ( + // TODO: Remove this once JSDOM fixes the issue where an element that is + // "hidden" can be the document.activeElement, because this is not possible + // in real browsers. + 0 + ) : (selector) => `${selector}:not([tabindex='-1'])` + ).join(","); + function getFocusableElements(container = document.body) { + if (container == null) + return []; + return Array.from(container.querySelectorAll(focusableSelector)).sort( + // We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well. + (a, z) => Math.sign((a.tabIndex || Number.MAX_SAFE_INTEGER) - (z.tabIndex || Number.MAX_SAFE_INTEGER)) + ); + } + function isFocusableElement(element, mode = 0 /* Strict */) { + var _a3; + if (element === ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body)) + return false; + return match(mode, { + [0 /* Strict */]() { + return element.matches(focusableSelector); + }, + [1 /* Loose */]() { + let next = element; + while (next !== null) { + if (next.matches(focusableSelector)) + return true; + next = next.parentElement; } - var PopoverGroupContext = (0, import_react37.createContext)(null); - PopoverGroupContext.displayName = "PopoverGroupContext"; - function usePopoverGroupContext() { - return (0, import_react37.useContext)(PopoverGroupContext); + return false; + } + }); + } + function restoreFocusIfNecessary(element) { + let ownerDocument = getOwnerDocument(element); + disposables().nextFrame(() => { + if (ownerDocument && !isFocusableElement(ownerDocument.activeElement, 0 /* Strict */)) { + focusElement(element); + } + }); + } + if (typeof window !== "undefined" && typeof document !== "undefined") { + document.addEventListener( + "keydown", + (event) => { + if (event.metaKey || event.altKey || event.ctrlKey) { + return; } - var PopoverPanelContext = (0, import_react37.createContext)(null); - PopoverPanelContext.displayName = "PopoverPanelContext"; - function usePopoverPanelContext() { - return (0, import_react37.useContext)(PopoverPanelContext); + document.documentElement.dataset.headlessuiFocusVisible = ""; + }, + true + ); + document.addEventListener( + "click", + (event) => { + if (event.detail === 1 /* Mouse */) { + delete document.documentElement.dataset.headlessuiFocusVisible; + } else if (event.detail === 0 /* Keyboard */) { + document.documentElement.dataset.headlessuiFocusVisible = ""; } - function stateReducer6(state, action) { - return match(action.type, reducers6, state, action); + }, + true + ); + } + function focusElement(element) { + element == null ? void 0 : element.focus({ preventScroll: true }); + } + var selectableSelector = ["textarea", "input"].join(","); + function isSelectableElement(element) { + var _a3, _b; + return (_b = (_a3 = element == null ? void 0 : element.matches) == null ? void 0 : _a3.call(element, selectableSelector)) != null ? _b : false; + } + function sortByDomNode(nodes, resolveKey = (i) => i) { + return nodes.slice().sort((aItem, zItem) => { + let a = resolveKey(aItem); + let z = resolveKey(zItem); + if (a === null || z === null) + return 0; + let position = a.compareDocumentPosition(z); + if (position & Node.DOCUMENT_POSITION_FOLLOWING) + return -1; + if (position & Node.DOCUMENT_POSITION_PRECEDING) + return 1; + return 0; + }); + } + function focusFrom(current, focus) { + return focusIn(getFocusableElements(), focus, { relativeTo: current }); + } + function focusIn(container, focus, { + sorted = true, + relativeTo = null, + skipElements = [] + } = {}) { + let ownerDocument = Array.isArray(container) ? container.length > 0 ? container[0].ownerDocument : document : container.ownerDocument; + let elements = Array.isArray(container) ? sorted ? sortByDomNode(container) : container : getFocusableElements(container); + if (skipElements.length > 0 && elements.length > 1) { + elements = elements.filter((x) => !skipElements.includes(x)); + } + relativeTo = relativeTo != null ? relativeTo : ownerDocument.activeElement; + let direction = (() => { + if (focus & (1 /* First */ | 4 /* Next */)) + return 1 /* Next */; + if (focus & (2 /* Previous */ | 8 /* Last */)) + return -1 /* Previous */; + throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); + })(); + let startIndex = (() => { + if (focus & 1 /* First */) + return 0; + if (focus & 2 /* Previous */) + return Math.max(0, elements.indexOf(relativeTo)) - 1; + if (focus & 4 /* Next */) + return Math.max(0, elements.indexOf(relativeTo)) + 1; + if (focus & 8 /* Last */) + return elements.length - 1; + throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); + })(); + let focusOptions = focus & 32 /* NoScroll */ ? { preventScroll: true } : {}; + let offset = 0; + let total = elements.length; + let next = void 0; + do { + if (offset >= total || offset + total <= 0) + return 0 /* Error */; + let nextIdx = startIndex + offset; + if (focus & 16 /* WrapAround */) { + nextIdx = (nextIdx + total) % total; + } else { + if (nextIdx < 0) + return 3 /* Underflow */; + if (nextIdx >= total) + return 1 /* Overflow */; + } + next = elements[nextIdx]; + next == null ? void 0 : next.focus(focusOptions); + offset += direction; + } while (next !== ownerDocument.activeElement); + if (focus & (4 /* Next */ | 2 /* Previous */) && isSelectableElement(next)) { + next.select(); + } + return 2 /* Success */; + } + + // src/hooks/use-document-event.ts + var import_react8 = __webpack_require__(/*! react */ "react"); + function useDocumentEvent(type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react8.useEffect)(() => { + function handler(event) { + listenerRef.current(event); + } + document.addEventListener(type, handler, options); + return () => document.removeEventListener(type, handler, options); + }, [type, options]); + } + + // src/hooks/use-window-event.ts + var import_react9 = __webpack_require__(/*! react */ "react"); + function useWindowEvent(type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react9.useEffect)(() => { + function handler(event) { + listenerRef.current(event); + } + window.addEventListener(type, handler, options); + return () => window.removeEventListener(type, handler, options); + }, [type, options]); + } + + // src/hooks/use-outside-click.ts + function useOutsideClick(containers, cb, enabled = true) { + let enabledRef = (0, import_react10.useRef)(false); + (0, import_react10.useEffect)( + false ? 0 : () => { + requestAnimationFrame(() => { + enabledRef.current = enabled; + }); + }, + [enabled] + ); + function handleOutsideClick(event, resolveTarget) { + if (!enabledRef.current) + return; + if (event.defaultPrevented) + return; + let target = resolveTarget(event); + if (target === null) { + return; + } + if (!target.getRootNode().contains(target)) + return; + let _containers = function resolve(containers2) { + if (typeof containers2 === "function") { + return resolve(containers2()); + } + if (Array.isArray(containers2)) { + return containers2; + } + if (containers2 instanceof Set) { + return containers2; + } + return [containers2]; + }(containers); + for (let container of _containers) { + if (container === null) + continue; + let domNode = container instanceof HTMLElement ? container : container.current; + if (domNode == null ? void 0 : domNode.contains(target)) { + return; } - var DEFAULT_POPOVER_TAG = "div"; - function PopoverFn(props, ref) { - var _a3; - let { __demoMode = false, ...theirProps } = props; - let internalPopoverRef = (0, import_react37.useRef)(null); - let popoverRef = useSyncRefs( - ref, - optionalRef((ref2) => { - internalPopoverRef.current = ref2; - }) - ); - let buttons = (0, import_react37.useRef)([]); - let reducerBag = (0, import_react37.useReducer)(stateReducer6, { - __demoMode, - popoverState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - buttons, - button: null, - buttonId: null, - panel: null, - panelId: null, - beforePanelSentinel: (0, import_react37.createRef)(), - afterPanelSentinel: (0, import_react37.createRef)(), - }); - let [ - { - popoverState, - button, - buttonId, - panel, - panelId, - beforePanelSentinel, - afterPanelSentinel, - }, - dispatch, - ] = reducerBag; - let ownerDocument = useOwnerDocument( - (_a3 = internalPopoverRef.current) != null ? _a3 : button - ); - let isPortalled = (0, import_react37.useMemo)(() => { - if (!button) return false; - if (!panel) return false; - for (let root2 of document.querySelectorAll("body > *")) { - if ( - Number(root2 == null ? void 0 : root2.contains(button)) ^ - Number(root2 == null ? void 0 : root2.contains(panel)) - ) { - return true; - } - } - let elements = getFocusableElements(); - let buttonIdx = elements.indexOf(button); - let beforeIdx = (buttonIdx + elements.length - 1) % elements.length; - let afterIdx = (buttonIdx + 1) % elements.length; - let beforeElement = elements[beforeIdx]; - let afterElement = elements[afterIdx]; - if ( - !panel.contains(beforeElement) && - !panel.contains(afterElement) - ) { - return true; - } - return false; - }, [button, panel]); - let buttonIdRef = useLatestValue(buttonId); - let panelIdRef = useLatestValue(panelId); - let registerBag = (0, import_react37.useMemo)( - () => ({ - buttonId: buttonIdRef, - panelId: panelIdRef, - close: () => dispatch({ type: 1 /* ClosePopover */ }), - }), - [buttonIdRef, panelIdRef, dispatch] - ); - let groupContext = usePopoverGroupContext(); - let registerPopover = - groupContext == null ? void 0 : groupContext.registerPopover; - let isFocusWithinPopoverGroup = useEvent(() => { - var _a4; - return (_a4 = - groupContext == null - ? void 0 - : groupContext.isFocusWithinPopoverGroup()) != null - ? _a4 - : (ownerDocument == null - ? void 0 - : ownerDocument.activeElement) && - ((button == null - ? void 0 - : button.contains(ownerDocument.activeElement)) || - (panel == null - ? void 0 - : panel.contains(ownerDocument.activeElement))); - }); - (0, import_react37.useEffect)( - () => - registerPopover == null ? void 0 : registerPopover(registerBag), - [registerPopover, registerBag] - ); - let [portals, PortalWrapper] = useNestedPortals(); - let root = useRootContainers({ - portals, - defaultContainers: [button, panel], - }); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "focus", - (event) => { - var _a4, _b, _c, _d; - if (event.target === window) return; - if (!(event.target instanceof HTMLElement)) return; - if (popoverState !== 0 /* Open */) return; - if (isFocusWithinPopoverGroup()) return; - if (!button) return; - if (!panel) return; - if (root.contains(event.target)) return; - if ( - (_b = - (_a4 = beforePanelSentinel.current) == null - ? void 0 - : _a4.contains) == null - ? void 0 - : _b.call(_a4, event.target) - ) - return; - if ( - (_d = - (_c = afterPanelSentinel.current) == null - ? void 0 - : _c.contains) == null - ? void 0 - : _d.call(_c, event.target) - ) - return; - dispatch({ type: 1 /* ClosePopover */ }); - }, - true - ); - useOutsideClick( - root.resolveContainers, - (event, target) => { - dispatch({ type: 1 /* ClosePopover */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - button == null ? void 0 : button.focus(); - } - }, - popoverState === 0 /* Open */ - ); - let close = useEvent((focusableElement) => { - dispatch({ type: 1 /* ClosePopover */ }); - let restoreElement = (() => { - if (!focusableElement) return button; - if (focusableElement instanceof HTMLElement) - return focusableElement; - if ( - "current" in focusableElement && - focusableElement.current instanceof HTMLElement - ) - return focusableElement.current; - return button; - })(); - restoreElement == null ? void 0 : restoreElement.focus(); - }); - let api = (0, import_react37.useMemo)( - () => ({ close, isPortalled }), - [close, isPortalled] - ); - let slot = (0, import_react37.useMemo)( - () => ({ open: popoverState === 0 /* Open */, close }), - [popoverState, close] - ); - let ourProps = { ref: popoverRef }; - return /* @__PURE__ */ import_react37.default.createElement( - PopoverPanelContext.Provider, - { value: null }, - /* @__PURE__ */ import_react37.default.createElement( - PopoverContext.Provider, - { value: reducerBag }, - /* @__PURE__ */ import_react37.default.createElement( - PopoverAPIContext.Provider, - { value: api }, - /* @__PURE__ */ import_react37.default.createElement( - OpenClosedProvider, - { - value: match(popoverState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */, - }), - }, - /* @__PURE__ */ import_react37.default.createElement( - PortalWrapper, - null, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_POPOVER_TAG, - name: "Popover", - }), - /* @__PURE__ */ import_react37.default.createElement( - root.MainTreeNode, - null - ) - ) - ) - ) - ) - ); + if (event.composed && event.composedPath().includes(domNode)) { + return; } - var DEFAULT_BUTTON_TAG5 = "button"; - function ButtonFn5(props, ref) { - let internalId = useId(); - let { - id = `headlessui-popover-button-${internalId}`, - ...theirProps - } = props; - let [state, dispatch] = usePopoverContext("Popover.Button"); - let { isPortalled } = usePopoverAPIContext("Popover.Button"); - let internalButtonRef = (0, import_react37.useRef)(null); - let sentinelId = `headlessui-focus-sentinel-${useId()}`; - let groupContext = usePopoverGroupContext(); - let closeOthers = - groupContext == null ? void 0 : groupContext.closeOthers; - let panelContext = usePopoverPanelContext(); - let isWithinPanel = panelContext !== null; - (0, import_react37.useEffect)(() => { - if (isWithinPanel) return; - dispatch({ type: 3 /* SetButtonId */, buttonId: id }); - return () => { - dispatch({ type: 3 /* SetButtonId */, buttonId: null }); - }; - }, [isWithinPanel, id, dispatch]); - let [uniqueIdentifier] = (0, import_react37.useState)(() => Symbol()); - let buttonRef = useSyncRefs( - internalButtonRef, - ref, - isWithinPanel - ? null - : (button) => { - if (button) { - state.buttons.current.push(uniqueIdentifier); - } else { - let idx = state.buttons.current.indexOf(uniqueIdentifier); - if (idx !== -1) state.buttons.current.splice(idx, 1); - } - if (state.buttons.current.length > 1) { - console.warn( - "You are already using a but only 1 is supported." - ); - } - button && dispatch({ type: 2 /* SetButton */, button }); - } - ); - let withinPanelButtonRef = useSyncRefs(internalButtonRef, ref); - let ownerDocument = useOwnerDocument(internalButtonRef); - let handleKeyDown = useEvent((event) => { - var _a3, _b, _c; - if (isWithinPanel) { - if (state.popoverState === 1 /* Closed */) return; - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - (_b = (_a3 = event.target).click) == null - ? void 0 - : _b.call(_a3); - dispatch({ type: 1 /* ClosePopover */ }); - (_c = state.button) == null ? void 0 : _c.focus(); - break; - } - } else { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - if (state.popoverState === 1 /* Closed */) - closeOthers == null ? void 0 : closeOthers(state.buttonId); - dispatch({ type: 0 /* TogglePopover */ }); - break; - case "Escape" /* Escape */: - if (state.popoverState !== 0 /* Open */) - return closeOthers == null - ? void 0 - : closeOthers(state.buttonId); - if (!internalButtonRef.current) return; - if ( - (ownerDocument == null - ? void 0 - : ownerDocument.activeElement) && - !internalButtonRef.current.contains( - ownerDocument.activeElement - ) - ) { - return; - } - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* ClosePopover */ }); - break; - } - } - }); - let handleKeyUp = useEvent((event) => { - if (isWithinPanel) return; - if (event.key === " " /* Space */) { - event.preventDefault(); - } - }); - let handleClick = useEvent((event) => { - var _a3, _b; - if (isDisabledReactIssue7711(event.currentTarget)) return; - if (props.disabled) return; - if (isWithinPanel) { - dispatch({ type: 1 /* ClosePopover */ }); - (_a3 = state.button) == null ? void 0 : _a3.focus(); - } else { - event.preventDefault(); - event.stopPropagation(); - if (state.popoverState === 1 /* Closed */) - closeOthers == null ? void 0 : closeOthers(state.buttonId); - dispatch({ type: 0 /* TogglePopover */ }); - (_b = state.button) == null ? void 0 : _b.focus(); - } - }); - let handleMouseDown = useEvent((event) => { - event.preventDefault(); - event.stopPropagation(); - }); - let visible = state.popoverState === 0; /* Open */ - let slot = (0, import_react37.useMemo)( - () => ({ open: visible }), - [visible] - ); - let type = useResolveButtonType(props, internalButtonRef); - let ourProps = isWithinPanel - ? { - ref: withinPanelButtonRef, - type, - onKeyDown: handleKeyDown, - onClick: handleClick, - } - : { - ref: buttonRef, - id: state.buttonId, - type, - "aria-expanded": props.disabled - ? void 0 - : state.popoverState === 0 /* Open */, - "aria-controls": state.panel ? state.panelId : void 0, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick, - onMouseDown: handleMouseDown, - }; - let direction = useTabDirection(); - let handleFocus = useEvent(() => { - let el = state.panel; - if (!el) return; - function run() { - let result = match(direction.current, { - [0 /* Forwards */]: () => focusIn(el, 1 /* First */), - [1 /* Backwards */]: () => focusIn(el, 8 /* Last */), - }); - if (result === 0 /* Error */) { - focusIn( - getFocusableElements().filter( - (el2) => el2.dataset.headlessuiFocusGuard !== "true" - ), - match(direction.current, { - [0 /* Forwards */]: 4 /* Next */, - [1 /* Backwards */]: 2 /* Previous */, - }), - { relativeTo: state.button } - ); - } - } - if (false) { - } else { - run(); - } - }); - return /* @__PURE__ */ import_react37.default.createElement( - import_react37.default.Fragment, - null, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG5, - name: "Popover.Button", - }), - visible && - !isWithinPanel && - isPortalled && - /* @__PURE__ */ import_react37.default.createElement(Hidden, { - id: sentinelId, - features: 2 /* Focusable */, - "data-headlessui-focus-guard": true, - as: "button", - type: "button", - onFocus: handleFocus, - }) - ); + } + if ( + // This check alllows us to know whether or not we clicked on a "focusable" element like a + // button or an input. This is a backwards compatibility check so that you can open a and click on another which should close Menu A and open Menu B. We might + // revisit that so that you will require 2 clicks instead. + !isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1} to make it + // unfocusable via the keyboard so that tabbing to the next item from the input doesn't + // first go to the button. + target.tabIndex !== -1 + ) { + event.preventDefault(); + } + return cb(event, target); + } + let initialClickTarget = (0, import_react10.useRef)(null); + useDocumentEvent( + "mousedown", + (event) => { + var _a3, _b; + if (enabledRef.current) { + initialClickTarget.current = ((_b = (_a3 = event.composedPath) == null ? void 0 : _a3.call(event)) == null ? void 0 : _b[0]) || event.target; } - var DEFAULT_OVERLAY_TAG2 = "div"; - var OverlayRenderFeatures = 1 /* RenderStrategy */ | 2; /* Static */ - function OverlayFn2(props, ref) { - let internalId = useId(); - let { - id = `headlessui-popover-overlay-${internalId}`, - ...theirProps - } = props; - let [{ popoverState }, dispatch] = - usePopoverContext("Popover.Overlay"); - let overlayRef = useSyncRefs(ref); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - return popoverState === 0 /* Open */; - })(); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - dispatch({ type: 1 /* ClosePopover */ }); - }); - let slot = (0, import_react37.useMemo)( - () => ({ open: popoverState === 0 /* Open */ }), - [popoverState] - ); - let ourProps = { - ref: overlayRef, - id, - "aria-hidden": true, - onClick: handleClick, - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OVERLAY_TAG2, - features: OverlayRenderFeatures, - visible, - name: "Popover.Overlay", - }); + }, + true + ); + useDocumentEvent( + "click", + (event) => { + if (!initialClickTarget.current) { + return; } - var DEFAULT_PANEL_TAG3 = "div"; - var PanelRenderFeatures2 = 1 /* RenderStrategy */ | 2; /* Static */ - function PanelFn3(props, ref) { - let internalId = useId(); - let { - id = `headlessui-popover-panel-${internalId}`, - focus = false, - ...theirProps - } = props; - let [state, dispatch] = usePopoverContext("Popover.Panel"); - let { close, isPortalled } = usePopoverAPIContext("Popover.Panel"); - let beforePanelSentinelId = `headlessui-focus-sentinel-before-${useId()}`; - let afterPanelSentinelId = `headlessui-focus-sentinel-after-${useId()}`; - let internalPanelRef = (0, import_react37.useRef)(null); - let panelRef = useSyncRefs(internalPanelRef, ref, (panel) => { - dispatch({ type: 4 /* SetPanel */, panel }); - }); - let ownerDocument = useOwnerDocument(internalPanelRef); - useIsoMorphicEffect(() => { - dispatch({ type: 5 /* SetPanelId */, panelId: id }); - return () => { - dispatch({ type: 5 /* SetPanelId */, panelId: null }); - }; - }, [id, dispatch]); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1) /* Open */ === 1 /* Open */; - } - return state.popoverState === 0 /* Open */; - })(); - let handleKeyDown = useEvent((event) => { - var _a3; - switch (event.key) { - case "Escape" /* Escape */: - if (state.popoverState !== 0 /* Open */) return; - if (!internalPanelRef.current) return; - if ( - (ownerDocument == null - ? void 0 - : ownerDocument.activeElement) && - !internalPanelRef.current.contains( - ownerDocument.activeElement - ) - ) { - return; - } - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* ClosePopover */ }); - (_a3 = state.button) == null ? void 0 : _a3.focus(); - break; - } - }); - (0, import_react37.useEffect)(() => { - var _a3; - if (props.static) return; - if ( - state.popoverState === 1 /* Closed */ && - ((_a3 = props.unmount) != null ? _a3 : true) - ) { - dispatch({ type: 4 /* SetPanel */, panel: null }); - } - }, [state.popoverState, props.unmount, props.static, dispatch]); - (0, import_react37.useEffect)(() => { - if (state.__demoMode) return; - if (!focus) return; - if (state.popoverState !== 0 /* Open */) return; - if (!internalPanelRef.current) return; - let activeElement = - ownerDocument == null ? void 0 : ownerDocument.activeElement; - if (internalPanelRef.current.contains(activeElement)) return; - focusIn(internalPanelRef.current, 1 /* First */); - }, [state.__demoMode, focus, internalPanelRef, state.popoverState]); - let slot = (0, import_react37.useMemo)( - () => ({ open: state.popoverState === 0 /* Open */, close }), - [state, close] - ); - let ourProps = { - ref: panelRef, - id, - onKeyDown: handleKeyDown, - onBlur: - focus && state.popoverState === 0 /* Open */ - ? (event) => { - var _a3, _b, _c, _d, _e; - let el = event.relatedTarget; - if (!el) return; - if (!internalPanelRef.current) return; - if ( - (_a3 = internalPanelRef.current) == null - ? void 0 - : _a3.contains(el) - ) - return; - dispatch({ type: 1 /* ClosePopover */ }); - if ( - ((_c = - (_b = state.beforePanelSentinel.current) == null - ? void 0 - : _b.contains) == null - ? void 0 - : _c.call(_b, el)) || - ((_e = - (_d = state.afterPanelSentinel.current) == null - ? void 0 - : _d.contains) == null - ? void 0 - : _e.call(_d, el)) - ) { - el.focus({ preventScroll: true }); - } - } - : void 0, - tabIndex: -1, - }; - let direction = useTabDirection(); - let handleBeforeFocus = useEvent(() => { - let el = internalPanelRef.current; - if (!el) return; - function run() { - match(direction.current, { - [0 /* Forwards */]: () => { - var _a3; - let result = focusIn(el, 1 /* First */); - if (result === 0 /* Error */) { - (_a3 = state.afterPanelSentinel.current) == null - ? void 0 - : _a3.focus(); - } - }, - [1 /* Backwards */]: () => { - var _a3; - (_a3 = state.button) == null - ? void 0 - : _a3.focus({ preventScroll: true }); - }, - }); - } - if (false) { - } else { - run(); - } + handleOutsideClick(event, () => { + return initialClickTarget.current; + }); + initialClickTarget.current = null; + }, + // We will use the `capture` phase so that layers in between with `event.stopPropagation()` + // don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu` + // is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However, + // the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this. + true + ); + useWindowEvent( + "blur", + (event) => handleOutsideClick( + event, + () => window.document.activeElement instanceof HTMLIFrameElement ? window.document.activeElement : null + ), + true + ); + } + + // src/hooks/use-resolve-button-type.ts + var import_react11 = __webpack_require__(/*! react */ "react"); + function resolveType(props) { + var _a3; + if (props.type) + return props.type; + let tag = (_a3 = props.as) != null ? _a3 : "button"; + if (typeof tag === "string" && tag.toLowerCase() === "button") + return "button"; + return void 0; + } + function useResolveButtonType(props, ref) { + let [type, setType] = (0, import_react11.useState)(() => resolveType(props)); + useIsoMorphicEffect(() => { + setType(resolveType(props)); + }, [props.type, props.as]); + useIsoMorphicEffect(() => { + if (type) + return; + if (!ref.current) + return; + if (ref.current instanceof HTMLButtonElement && !ref.current.hasAttribute("type")) { + setType("button"); + } + }, [type, ref]); + return type; + } + + // src/hooks/use-sync-refs.ts + var import_react12 = __webpack_require__(/*! react */ "react"); + var Optional = Symbol(); + function optionalRef(cb, isOptional = true) { + return Object.assign(cb, { [Optional]: isOptional }); + } + function useSyncRefs(...refs) { + let cache = (0, import_react12.useRef)(refs); + (0, import_react12.useEffect)(() => { + cache.current = refs; + }, [refs]); + let syncRefs = useEvent((value) => { + for (let ref of cache.current) { + if (ref == null) + continue; + if (typeof ref === "function") + ref(value); + else + ref.current = value; + } + }); + return refs.every( + (ref) => ref == null || // @ts-expect-error + (ref == null ? void 0 : ref[Optional]) + ) ? void 0 : syncRefs; + } + + // src/hooks/use-tree-walker.ts + var import_react13 = __webpack_require__(/*! react */ "react"); + function useTreeWalker({ + container, + accept, + walk, + enabled = true + }) { + let acceptRef = (0, import_react13.useRef)(accept); + let walkRef = (0, import_react13.useRef)(walk); + (0, import_react13.useEffect)(() => { + acceptRef.current = accept; + walkRef.current = walk; + }, [accept, walk]); + useIsoMorphicEffect(() => { + if (!container) + return; + if (!enabled) + return; + let ownerDocument = getOwnerDocument(container); + if (!ownerDocument) + return; + let accept2 = acceptRef.current; + let walk2 = walkRef.current; + let acceptNode = Object.assign((node) => accept2(node), { acceptNode: accept2 }); + let walker = ownerDocument.createTreeWalker( + container, + NodeFilter.SHOW_ELEMENT, + acceptNode, + // @ts-expect-error This `false` is a simple small fix for older browsers + false + ); + while (walker.nextNode()) + walk2(walker.currentNode); + }, [container, enabled, acceptRef, walkRef]); + } + + // src/utils/calculate-active-index.ts + function assertNever(x) { + throw new Error("Unexpected object: " + x); + } + function calculateActiveIndex(action, resolvers) { + let items = resolvers.resolveItems(); + if (items.length <= 0) + return null; + let currentActiveIndex = resolvers.resolveActiveIndex(); + let activeIndex = currentActiveIndex != null ? currentActiveIndex : -1; + let nextActiveIndex = (() => { + switch (action.focus) { + case 0 /* First */: + return items.findIndex((item) => !resolvers.resolveDisabled(item)); + case 1 /* Previous */: { + let idx = items.slice().reverse().findIndex((item, idx2, all) => { + if (activeIndex !== -1 && all.length - idx2 - 1 >= activeIndex) + return false; + return !resolvers.resolveDisabled(item); }); - let handleAfterFocus = useEvent(() => { - let el = internalPanelRef.current; - if (!el) return; - function run() { - match(direction.current, { - [0 /* Forwards */]: () => { - var _a3; - if (!state.button) return; - let elements = getFocusableElements(); - let idx = elements.indexOf(state.button); - let before = elements.slice(0, idx + 1); - let after = elements.slice(idx + 1); - let combined = [...after, ...before]; - for (let element of combined.slice()) { - if ( - element.dataset.headlessuiFocusGuard === "true" || - ((_a3 = state.panel) == null - ? void 0 - : _a3.contains(element)) - ) { - let idx2 = combined.indexOf(element); - if (idx2 !== -1) combined.splice(idx2, 1); - } - } - focusIn(combined, 1 /* First */, { sorted: false }); - }, - [1 /* Backwards */]: () => { - var _a3; - let result = focusIn(el, 2 /* Previous */); - if (result === 0 /* Error */) { - (_a3 = state.button) == null ? void 0 : _a3.focus(); - } - }, - }); - } - if (false) { - } else { - run(); - } + if (idx === -1) + return idx; + return items.length - 1 - idx; + } + case 2 /* Next */: + return items.findIndex((item, idx) => { + if (idx <= activeIndex) + return false; + return !resolvers.resolveDisabled(item); }); - return /* @__PURE__ */ import_react37.default.createElement( - PopoverPanelContext.Provider, - { value: id }, - visible && - isPortalled && - /* @__PURE__ */ import_react37.default.createElement(Hidden, { - id: beforePanelSentinelId, - ref: state.beforePanelSentinel, - features: 2 /* Focusable */, - "data-headlessui-focus-guard": true, - as: "button", - type: "button", - onFocus: handleBeforeFocus, - }), - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG3, - features: PanelRenderFeatures2, - visible, - name: "Popover.Panel", - }), - visible && - isPortalled && - /* @__PURE__ */ import_react37.default.createElement(Hidden, { - id: afterPanelSentinelId, - ref: state.afterPanelSentinel, - features: 2 /* Focusable */, - "data-headlessui-focus-guard": true, - as: "button", - type: "button", - onFocus: handleAfterFocus, - }) + case 3 /* Last */: { + let idx = items.slice().reverse().findIndex((item) => !resolvers.resolveDisabled(item)); + if (idx === -1) + return idx; + return items.length - 1 - idx; + } + case 4 /* Specific */: + return items.findIndex((item) => resolvers.resolveId(item) === action.id); + case 5 /* Nothing */: + return null; + default: + assertNever(action); + } + })(); + return nextActiveIndex === -1 ? currentActiveIndex : nextActiveIndex; + } + + // src/utils/render.ts + var import_react14 = __webpack_require__(/*! react */ "react"); + + // src/utils/class-names.ts + function classNames(...classes) { + return classes.filter(Boolean).join(" "); + } + + // src/utils/render.ts + function render({ + ourProps, + theirProps, + slot, + defaultTag, + features, + visible = true, + name + }) { + let props = mergeProps(theirProps, ourProps); + if (visible) + return _render(props, slot, defaultTag, name); + let featureFlags = features != null ? features : 0 /* None */; + if (featureFlags & 2 /* Static */) { + let { static: isStatic = false, ...rest } = props; + if (isStatic) + return _render(rest, slot, defaultTag, name); + } + if (featureFlags & 1 /* RenderStrategy */) { + let { unmount = true, ...rest } = props; + let strategy = unmount ? 0 /* Unmount */ : 1 /* Hidden */; + return match(strategy, { + [0 /* Unmount */]() { + return null; + }, + [1 /* Hidden */]() { + return _render( + { ...rest, ...{ hidden: true, style: { display: "none" } } }, + slot, + defaultTag, + name ); } - var DEFAULT_GROUP_TAG2 = "div"; - function GroupFn2(props, ref) { - let internalGroupRef = (0, import_react37.useRef)(null); - let groupRef = useSyncRefs(internalGroupRef, ref); - let [popovers, setPopovers] = (0, import_react37.useState)([]); - let unregisterPopover = useEvent((registerbag) => { - setPopovers((existing) => { - let idx = existing.indexOf(registerbag); - if (idx !== -1) { - let clone = existing.slice(); - clone.splice(idx, 1); - return clone; - } - return existing; - }); - }); - let registerPopover = useEvent((registerbag) => { - setPopovers((existing) => [...existing, registerbag]); - return () => unregisterPopover(registerbag); - }); - let isFocusWithinPopoverGroup = useEvent(() => { - var _a3; - let ownerDocument = getOwnerDocument(internalGroupRef); - if (!ownerDocument) return false; - let element = ownerDocument.activeElement; - if ( - (_a3 = internalGroupRef.current) == null - ? void 0 - : _a3.contains(element) - ) - return true; - return popovers.some((bag) => { - var _a4, _b; - return ( - ((_a4 = ownerDocument.getElementById(bag.buttonId.current)) == - null - ? void 0 - : _a4.contains(element)) || - ((_b = ownerDocument.getElementById(bag.panelId.current)) == - null - ? void 0 - : _b.contains(element)) - ); - }); - }); - let closeOthers = useEvent((buttonId) => { - for (let popover of popovers) { - if (popover.buttonId.current !== buttonId) popover.close(); - } - }); - let contextBag = (0, import_react37.useMemo)( - () => ({ - registerPopover, - unregisterPopover, - isFocusWithinPopoverGroup, - closeOthers, - }), + }); + } + return _render(props, slot, defaultTag, name); + } + function _render(props, slot = {}, tag, name) { + let { + as: Component = tag, + children, + refName = "ref", + ...rest + } = omit(props, ["unmount", "static"]); + let refRelatedProps = props.ref !== void 0 ? { [refName]: props.ref } : {}; + let resolvedChildren = typeof children === "function" ? children(slot) : children; + if ("className" in rest && rest.className && typeof rest.className === "function") { + rest.className = rest.className(slot); + } + let dataAttributes = {}; + if (slot) { + let exposeState = false; + let states = []; + for (let [k, v] of Object.entries(slot)) { + if (typeof v === "boolean") { + exposeState = true; + } + if (v === true) { + states.push(k); + } + } + if (exposeState) + dataAttributes[`data-headlessui-state`] = states.join(" "); + } + if (Component === import_react14.Fragment) { + if (Object.keys(compact(rest)).length > 0) { + if (!(0, import_react14.isValidElement)(resolvedChildren) || Array.isArray(resolvedChildren) && resolvedChildren.length > 1) { + throw new Error( [ - registerPopover, - unregisterPopover, - isFocusWithinPopoverGroup, - closeOthers, - ] - ); - let slot = (0, import_react37.useMemo)(() => ({}), []); - let theirProps = props; - let ourProps = { ref: groupRef }; - return /* @__PURE__ */ import_react37.default.createElement( - PopoverGroupContext.Provider, - { value: contextBag }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_GROUP_TAG2, - name: "Popover.Group", - }) + 'Passing props on "Fragment"!', + "", + `The current component <${name} /> is rendering a "Fragment".`, + `However we need to passthrough the following props:`, + Object.keys(rest).map((line) => ` - ${line}`).join("\n"), + "", + "You can apply a few solutions:", + [ + 'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', + "Render a single element as the child so that we can forward the props onto that element." + ].map((line) => ` - ${line}`).join("\n") + ].join("\n") ); } - var PopoverRoot = forwardRefWithAs(PopoverFn); - var Button5 = forwardRefWithAs(ButtonFn5); - var Overlay2 = forwardRefWithAs(OverlayFn2); - var Panel3 = forwardRefWithAs(PanelFn3); - var Group2 = forwardRefWithAs(GroupFn2); - var Popover = Object.assign(PopoverRoot, { - Button: Button5, - Overlay: Overlay2, - Panel: Panel3, - Group: Group2, - }); - - // src/components/radio-group/radio-group.tsx - var import_react40 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 + let childProps = resolvedChildren.props; + let newClassName = typeof (childProps == null ? void 0 : childProps.className) === "function" ? (...args) => classNames(childProps == null ? void 0 : childProps.className(...args), rest.className) : classNames(childProps == null ? void 0 : childProps.className, rest.className); + let classNameProps = newClassName ? { className: newClassName } : {}; + return (0, import_react14.cloneElement)( + resolvedChildren, + Object.assign( + {}, + // Filter out undefined values so that they don't override the existing values + mergeProps(resolvedChildren.props, compact(omit(rest, ["ref"]))), + dataAttributes, + refRelatedProps, + mergeRefs(resolvedChildren.ref, refRelatedProps.ref), + classNameProps + ) ); - - // src/hooks/use-flags.ts - var import_react38 = __webpack_require__(/*! react */ "react"); - function useFlags(initialFlags = 0) { - let [flags, setFlags] = (0, import_react38.useState)(initialFlags); - let mounted = useIsMounted(); - let addFlag = (0, import_react38.useCallback)( - (flag) => { - if (!mounted.current) return; - setFlags((flags2) => flags2 | flag); - }, - [flags, mounted] - ); - let hasFlag = (0, import_react38.useCallback)( - (flag) => Boolean(flags & flag), - [flags] - ); - let removeFlag = (0, import_react38.useCallback)( - (flag) => { - if (!mounted.current) return; - setFlags((flags2) => flags2 & ~flag); - }, - [setFlags, mounted] - ); - let toggleFlag = (0, import_react38.useCallback)( - (flag) => { - if (!mounted.current) return; - setFlags((flags2) => flags2 ^ flag); - }, - [setFlags] - ); - return { flags, addFlag, hasFlag, removeFlag, toggleFlag }; + } + } + return (0, import_react14.createElement)( + Component, + Object.assign( + {}, + omit(rest, ["ref"]), + Component !== import_react14.Fragment && refRelatedProps, + Component !== import_react14.Fragment && dataAttributes + ), + resolvedChildren + ); + } + function mergeRefs(...refs) { + return { + ref: refs.every((ref) => ref == null) ? void 0 : (value) => { + for (let ref of refs) { + if (ref == null) + continue; + if (typeof ref === "function") + ref(value); + else + ref.current = value; } - - // src/components/label/label.tsx - var import_react39 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - var LabelContext = (0, import_react39.createContext)(null); - function useLabelContext() { - let context = (0, import_react39.useContext)(LabelContext); - if (context === null) { - let err = new Error( - "You used a component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useMenuContext); + throw err; + } + return context; + } + function stateReducer5(state, action) { + return match(action.type, reducers5, state, action); + } + var DEFAULT_MENU_TAG = import_react36.Fragment; + function MenuFn(props, ref) { + let { __demoMode = false, ...theirProps } = props; + let reducerBag = (0, import_react36.useReducer)(stateReducer5, { + __demoMode, + menuState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + buttonRef: (0, import_react36.createRef)(), + itemsRef: (0, import_react36.createRef)(), + items: [], + searchQuery: "", + activeItemIndex: null, + activationTrigger: 1 /* Other */ + }); + let [{ menuState, itemsRef, buttonRef }, dispatch] = reducerBag; + let menuRef = useSyncRefs(ref); + useOutsideClick( + [buttonRef, itemsRef], + (event, target) => { + var _a3; + dispatch({ type: 1 /* CloseMenu */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + (_a3 = buttonRef.current) == null ? void 0 : _a3.focus(); } - var DEFAULT_PANEL_TAG4 = "div"; - var PanelRenderFeatures3 = 1 /* RenderStrategy */ | 2; /* Static */ - function PanelFn4(props, ref) { - var _a3, _b, _c, _d; - let internalId = useId(); - let { - id = `headlessui-tabs-panel-${internalId}`, - tabIndex = 0, - ...theirProps - } = props; - let { selectedIndex, tabs, panels } = useData4("Tab.Panel"); - let actions = useActions4("Tab.Panel"); - let internalPanelRef = (0, import_react43.useRef)(null); - let panelRef = useSyncRefs(internalPanelRef, ref); - useIsoMorphicEffect( - () => actions.registerPanel(internalPanelRef), - [actions, internalPanelRef] - ); - let mySSRIndex = useStableCollectionIndex("panels"); - let myIndex = panels.indexOf(internalPanelRef); - if (myIndex === -1) myIndex = mySSRIndex; - let selected = myIndex === selectedIndex; - let slot = (0, import_react43.useMemo)( - () => ({ selected }), - [selected] - ); - let ourProps = { - ref: panelRef, - id, - role: "tabpanel", - "aria-labelledby": - (_b = (_a3 = tabs[myIndex]) == null ? void 0 : _a3.current) == - null - ? void 0 - : _b.id, - tabIndex: selected ? tabIndex : -1, - }; - if ( - !selected && - ((_c = theirProps.unmount) != null ? _c : true) && - !((_d = theirProps.static) != null ? _d : false) - ) { - return /* @__PURE__ */ import_react43.default.createElement( - Hidden, - { as: "span", ...ourProps } + }, + menuState === 0 /* Open */ + ); + let close = useEvent(() => { + dispatch({ type: 1 /* CloseMenu */ }); + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: menuState === 0 /* Open */, close }), + [menuState, close] + ); + let ourProps = { ref: menuRef }; + return /* @__PURE__ */ import_react36.default.createElement(MenuContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react36.default.createElement( + OpenClosedProvider, + { + value: match(menuState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) + }, + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_MENU_TAG, + name: "Menu" + }) + )); + } + var DEFAULT_BUTTON_TAG4 = "button"; + function ButtonFn4(props, ref) { + var _a3; + let internalId = useId(); + let { id = `headlessui-menu-button-${internalId}`, ...theirProps } = props; + let [state, dispatch] = useMenuContext("Menu.Button"); + let buttonRef = useSyncRefs(state.buttonRef, ref); + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* OpenMenu */ }); + d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ })); + break; + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* OpenMenu */ }); + d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ })); + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (props.disabled) + return; + if (state.menuState === 0 /* Open */) { + dispatch({ type: 1 /* CloseMenu */ }); + d.nextFrame(() => { + var _a4; + return (_a4 = state.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + }); + } else { + event.preventDefault(); + dispatch({ type: 0 /* OpenMenu */ }); + } + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: state.menuState === 0 /* Open */ }), + [state] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, state.buttonRef), + "aria-haspopup": "menu", + "aria-controls": (_a3 = state.itemsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": props.disabled ? void 0 : state.menuState === 0 /* Open */, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG4, + name: "Menu.Button" + }); + } + var DEFAULT_ITEMS_TAG = "div"; + var ItemsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; + function ItemsFn(props, ref) { + var _a3, _b; + let internalId = useId(); + let { id = `headlessui-menu-items-${internalId}`, ...theirProps } = props; + let [state, dispatch] = useMenuContext("Menu.Items"); + let itemsRef = useSyncRefs(state.itemsRef, ref); + let ownerDocument = useOwnerDocument(state.itemsRef); + let searchDisposables = useDisposables(); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return state.menuState === 0 /* Open */; + })(); + (0, import_react36.useEffect)(() => { + let container = state.itemsRef.current; + if (!container) + return; + if (state.menuState !== 0 /* Open */) + return; + if (container === (ownerDocument == null ? void 0 : ownerDocument.activeElement)) + return; + container.focus({ preventScroll: true }); + }, [state.menuState, state.itemsRef, ownerDocument]); + useTreeWalker({ + container: state.itemsRef.current, + enabled: state.menuState === 0 /* Open */, + accept(node) { + if (node.getAttribute("role") === "menuitem") + return NodeFilter.FILTER_REJECT; + if (node.hasAttribute("role")) + return NodeFilter.FILTER_SKIP; + return NodeFilter.FILTER_ACCEPT; + }, + walk(node) { + node.setAttribute("role", "none"); + } + }); + let handleKeyDown = useEvent((event) => { + var _a4, _b2; + searchDisposables.dispose(); + switch (event.key) { + case " " /* Space */: + if (state.searchQuery !== "") { + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 3 /* Search */, value: event.key }); + } + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + if (state.activeItemIndex !== null) { + let { dataRef } = state.items[state.activeItemIndex]; + (_b2 = (_a4 = dataRef.current) == null ? void 0 : _a4.domRef.current) == null ? void 0 : _b2.click(); + } + restoreFocusIfNecessary(state.buttonRef.current); + break; + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 2 /* Next */ }); + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 1 /* Previous */ }); + case "Home" /* Home */: + case "PageUp" /* PageUp */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ }); + case "End" /* End */: + case "PageDown" /* PageDown */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ }); + case "Escape" /* Escape */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + disposables().nextFrame(() => { + var _a5; + return (_a5 = state.buttonRef.current) == null ? void 0 : _a5.focus({ preventScroll: true }); + }); + break; + case "Tab" /* Tab */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + disposables().nextFrame(() => { + focusFrom( + state.buttonRef.current, + event.shiftKey ? 2 /* Previous */ : 4 /* Next */ ); - } - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG4, - features: PanelRenderFeatures3, - visible: selected, - name: "Tabs.Panel", }); + break; + default: + if (event.key.length === 1) { + dispatch({ type: 3 /* Search */, value: event.key }); + searchDisposables.setTimeout(() => dispatch({ type: 4 /* ClearSearch */ }), 350); + } + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: state.menuState === 0 /* Open */ }), + [state] + ); + let ourProps = { + "aria-activedescendant": state.activeItemIndex === null ? void 0 : (_a3 = state.items[state.activeItemIndex]) == null ? void 0 : _a3.id, + "aria-labelledby": (_b = state.buttonRef.current) == null ? void 0 : _b.id, + id, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + role: "menu", + tabIndex: 0, + ref: itemsRef + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_ITEMS_TAG, + features: ItemsRenderFeatures, + visible, + name: "Menu.Items" + }); + } + var DEFAULT_ITEM_TAG = import_react36.Fragment; + function ItemFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-menu-item-${internalId}`, disabled = false, ...theirProps } = props; + let [state, dispatch] = useMenuContext("Menu.Item"); + let active = state.activeItemIndex !== null ? state.items[state.activeItemIndex].id === id : false; + let internalItemRef = (0, import_react36.useRef)(null); + let itemRef = useSyncRefs(ref, internalItemRef); + useIsoMorphicEffect(() => { + if (state.__demoMode) + return; + if (state.menuState !== 0 /* Open */) + return; + if (!active) + return; + if (state.activationTrigger === 0 /* Pointer */) + return; + let d = disposables(); + d.requestAnimationFrame(() => { + var _a3, _b; + (_b = (_a3 = internalItemRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); + }); + return d.dispose; + }, [ + state.__demoMode, + internalItemRef, + active, + state.menuState, + state.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + state.activeItemIndex + ]); + let getTextValue2 = useTextValue(internalItemRef); + let bag = (0, import_react36.useRef)({ + disabled, + domRef: internalItemRef, + get textValue() { + return getTextValue2(); + } + }); + useIsoMorphicEffect(() => { + bag.current.disabled = disabled; + }, [bag, disabled]); + useIsoMorphicEffect(() => { + dispatch({ type: 5 /* RegisterItem */, id, dataRef: bag }); + return () => dispatch({ type: 6 /* UnregisterItem */, id }); + }, [bag, id]); + let close = useEvent(() => { + dispatch({ type: 1 /* CloseMenu */ }); + }); + let handleClick = useEvent((event) => { + if (disabled) + return event.preventDefault(); + dispatch({ type: 1 /* CloseMenu */ }); + restoreFocusIfNecessary(state.buttonRef.current); + }); + let handleFocus = useEvent(() => { + if (disabled) + return dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); + dispatch({ type: 2 /* GoToItem */, focus: 4 /* Specific */, id }); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (active) + return; + dispatch({ + type: 2 /* GoToItem */, + focus: 4 /* Specific */, + id, + trigger: 0 /* Pointer */ + }); + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (!active) + return; + dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); + }); + let slot = (0, import_react36.useMemo)( + () => ({ active, disabled, close }), + [active, disabled, close] + ); + let ourProps = { + id, + ref: itemRef, + role: "menuitem", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_ITEM_TAG, + name: "Menu.Item" + }); + } + var MenuRoot = forwardRefWithAs(MenuFn); + var Button4 = forwardRefWithAs(ButtonFn4); + var Items = forwardRefWithAs(ItemsFn); + var Item = forwardRefWithAs(ItemFn); + var Menu = Object.assign(MenuRoot, { Button: Button4, Items, Item }); + + // src/components/popover/popover.tsx + var import_react37 = __toESM(__webpack_require__(/*! react */ "react"), 1); + var reducers6 = { + [0 /* TogglePopover */]: (state) => { + let nextState = { + ...state, + popoverState: match(state.popoverState, { + [0 /* Open */]: 1 /* Closed */, + [1 /* Closed */]: 0 /* Open */ + }) + }; + if (nextState.popoverState === 0 /* Open */) { + nextState.__demoMode = false; + } + return nextState; + }, + [1 /* ClosePopover */](state) { + if (state.popoverState === 1 /* Closed */) + return state; + return { ...state, popoverState: 1 /* Closed */ }; + }, + [2 /* SetButton */](state, action) { + if (state.button === action.button) + return state; + return { ...state, button: action.button }; + }, + [3 /* SetButtonId */](state, action) { + if (state.buttonId === action.buttonId) + return state; + return { ...state, buttonId: action.buttonId }; + }, + [4 /* SetPanel */](state, action) { + if (state.panel === action.panel) + return state; + return { ...state, panel: action.panel }; + }, + [5 /* SetPanelId */](state, action) { + if (state.panelId === action.panelId) + return state; + return { ...state, panelId: action.panelId }; + } + }; + var PopoverContext = (0, import_react37.createContext)(null); + PopoverContext.displayName = "PopoverContext"; + function usePopoverContext(component) { + let context = (0, import_react37.useContext)(PopoverContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, usePopoverContext); + throw err; + } + return context; + } + var PopoverAPIContext = (0, import_react37.createContext)(null); + PopoverAPIContext.displayName = "PopoverAPIContext"; + function usePopoverAPIContext(component) { + let context = (0, import_react37.useContext)(PopoverAPIContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, usePopoverAPIContext); + throw err; + } + return context; + } + var PopoverGroupContext = (0, import_react37.createContext)(null); + PopoverGroupContext.displayName = "PopoverGroupContext"; + function usePopoverGroupContext() { + return (0, import_react37.useContext)(PopoverGroupContext); + } + var PopoverPanelContext = (0, import_react37.createContext)(null); + PopoverPanelContext.displayName = "PopoverPanelContext"; + function usePopoverPanelContext() { + return (0, import_react37.useContext)(PopoverPanelContext); + } + function stateReducer6(state, action) { + return match(action.type, reducers6, state, action); + } + var DEFAULT_POPOVER_TAG = "div"; + function PopoverFn(props, ref) { + var _a3; + let { __demoMode = false, ...theirProps } = props; + let internalPopoverRef = (0, import_react37.useRef)(null); + let popoverRef = useSyncRefs( + ref, + optionalRef((ref2) => { + internalPopoverRef.current = ref2; + }) + ); + let buttons = (0, import_react37.useRef)([]); + let reducerBag = (0, import_react37.useReducer)(stateReducer6, { + __demoMode, + popoverState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + buttons, + button: null, + buttonId: null, + panel: null, + panelId: null, + beforePanelSentinel: (0, import_react37.createRef)(), + afterPanelSentinel: (0, import_react37.createRef)() + }); + let [ + { popoverState, button, buttonId, panel, panelId, beforePanelSentinel, afterPanelSentinel }, + dispatch + ] = reducerBag; + let ownerDocument = useOwnerDocument((_a3 = internalPopoverRef.current) != null ? _a3 : button); + let isPortalled = (0, import_react37.useMemo)(() => { + if (!button) + return false; + if (!panel) + return false; + for (let root2 of document.querySelectorAll("body > *")) { + if (Number(root2 == null ? void 0 : root2.contains(button)) ^ Number(root2 == null ? void 0 : root2.contains(panel))) { + return true; } - var TabRoot = forwardRefWithAs(TabFn); - var Group4 = forwardRefWithAs(GroupFn4); - var List = forwardRefWithAs(ListFn); - var Panels = forwardRefWithAs(PanelsFn); - var Panel4 = forwardRefWithAs(PanelFn4); - var Tab = Object.assign(TabRoot, { - Group: Group4, - List, - Panels, - Panel: Panel4, - }); - - // src/components/transitions/transition.tsx - var import_react44 = __toESM( - __webpack_require__(/*! react */ "react"), - 1 - ); - - // src/utils/once.ts - function once(cb) { - let state = { called: false }; - return (...args) => { - if (state.called) return; - state.called = true; - return cb(...args); - }; + } + let elements = getFocusableElements(); + let buttonIdx = elements.indexOf(button); + let beforeIdx = (buttonIdx + elements.length - 1) % elements.length; + let afterIdx = (buttonIdx + 1) % elements.length; + let beforeElement = elements[beforeIdx]; + let afterElement = elements[afterIdx]; + if (!panel.contains(beforeElement) && !panel.contains(afterElement)) { + return true; + } + return false; + }, [button, panel]); + let buttonIdRef = useLatestValue(buttonId); + let panelIdRef = useLatestValue(panelId); + let registerBag = (0, import_react37.useMemo)( + () => ({ + buttonId: buttonIdRef, + panelId: panelIdRef, + close: () => dispatch({ type: 1 /* ClosePopover */ }) + }), + [buttonIdRef, panelIdRef, dispatch] + ); + let groupContext = usePopoverGroupContext(); + let registerPopover = groupContext == null ? void 0 : groupContext.registerPopover; + let isFocusWithinPopoverGroup = useEvent(() => { + var _a4; + return (_a4 = groupContext == null ? void 0 : groupContext.isFocusWithinPopoverGroup()) != null ? _a4 : (ownerDocument == null ? void 0 : ownerDocument.activeElement) && ((button == null ? void 0 : button.contains(ownerDocument.activeElement)) || (panel == null ? void 0 : panel.contains(ownerDocument.activeElement))); + }); + (0, import_react37.useEffect)(() => registerPopover == null ? void 0 : registerPopover(registerBag), [registerPopover, registerBag]); + let [portals, PortalWrapper] = useNestedPortals(); + let root = useRootContainers({ + portals, + defaultContainers: [button, panel] + }); + useEventListener( + ownerDocument == null ? void 0 : ownerDocument.defaultView, + "focus", + (event) => { + var _a4, _b, _c, _d; + if (event.target === window) + return; + if (!(event.target instanceof HTMLElement)) + return; + if (popoverState !== 0 /* Open */) + return; + if (isFocusWithinPopoverGroup()) + return; + if (!button) + return; + if (!panel) + return; + if (root.contains(event.target)) + return; + if ((_b = (_a4 = beforePanelSentinel.current) == null ? void 0 : _a4.contains) == null ? void 0 : _b.call(_a4, event.target)) + return; + if ((_d = (_c = afterPanelSentinel.current) == null ? void 0 : _c.contains) == null ? void 0 : _d.call(_c, event.target)) + return; + dispatch({ type: 1 /* ClosePopover */ }); + }, + true + ); + useOutsideClick( + root.resolveContainers, + (event, target) => { + dispatch({ type: 1 /* ClosePopover */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + button == null ? void 0 : button.focus(); + } + }, + popoverState === 0 /* Open */ + ); + let close = useEvent( + (focusableElement) => { + dispatch({ type: 1 /* ClosePopover */ }); + let restoreElement = (() => { + if (!focusableElement) + return button; + if (focusableElement instanceof HTMLElement) + return focusableElement; + if ("current" in focusableElement && focusableElement.current instanceof HTMLElement) + return focusableElement.current; + return button; + })(); + restoreElement == null ? void 0 : restoreElement.focus(); + } + ); + let api = (0, import_react37.useMemo)( + () => ({ close, isPortalled }), + [close, isPortalled] + ); + let slot = (0, import_react37.useMemo)( + () => ({ open: popoverState === 0 /* Open */, close }), + [popoverState, close] + ); + let ourProps = { ref: popoverRef }; + return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: null }, /* @__PURE__ */ import_react37.default.createElement(PopoverContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react37.default.createElement(PopoverAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react37.default.createElement( + OpenClosedProvider, + { + value: match(popoverState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) + }, + /* @__PURE__ */ import_react37.default.createElement(PortalWrapper, null, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_POPOVER_TAG, + name: "Popover" + }), /* @__PURE__ */ import_react37.default.createElement(root.MainTreeNode, null)) + )))); + } + var DEFAULT_BUTTON_TAG5 = "button"; + function ButtonFn5(props, ref) { + let internalId = useId(); + let { id = `headlessui-popover-button-${internalId}`, ...theirProps } = props; + let [state, dispatch] = usePopoverContext("Popover.Button"); + let { isPortalled } = usePopoverAPIContext("Popover.Button"); + let internalButtonRef = (0, import_react37.useRef)(null); + let sentinelId = `headlessui-focus-sentinel-${useId()}`; + let groupContext = usePopoverGroupContext(); + let closeOthers = groupContext == null ? void 0 : groupContext.closeOthers; + let panelContext = usePopoverPanelContext(); + let isWithinPanel = panelContext !== null; + (0, import_react37.useEffect)(() => { + if (isWithinPanel) + return; + dispatch({ type: 3 /* SetButtonId */, buttonId: id }); + return () => { + dispatch({ type: 3 /* SetButtonId */, buttonId: null }); + }; + }, [isWithinPanel, id, dispatch]); + let [uniqueIdentifier] = (0, import_react37.useState)(() => Symbol()); + let buttonRef = useSyncRefs( + internalButtonRef, + ref, + isWithinPanel ? null : (button) => { + if (button) { + state.buttons.current.push(uniqueIdentifier); + } else { + let idx = state.buttons.current.indexOf(uniqueIdentifier); + if (idx !== -1) + state.buttons.current.splice(idx, 1); } - - // src/components/transitions/utils/transition.ts - function addClasses(node, ...classes) { - node && classes.length > 0 && node.classList.add(...classes); - } - function removeClasses(node, ...classes) { - node && classes.length > 0 && node.classList.remove(...classes); - } - function waitForTransition(node, done) { - let d = disposables(); - if (!node) return d.dispose; - let { transitionDuration, transitionDelay } = getComputedStyle(node); - let [durationMs, delayMs] = [transitionDuration, transitionDelay].map( - (value) => { - let [resolvedValue = 0] = value - .split(",") - .filter(Boolean) - .map((v) => - v.includes("ms") ? parseFloat(v) : parseFloat(v) * 1e3 - ) - .sort((a, z) => z - a); - return resolvedValue; - } + if (state.buttons.current.length > 1) { + console.warn( + "You are already using a but only 1 is supported." ); - let totalDuration = durationMs + delayMs; - if (totalDuration !== 0) { - if (false) { - } else { - d.group((d2) => { - d2.setTimeout(() => { - done(); - d2.dispose(); - }, totalDuration); - d2.addEventListener(node, "transitionrun", (event) => { - if (event.target !== event.currentTarget) return; - d2.dispose(); - }); - }); - let dispose = d.addEventListener( - node, - "transitionend", - (event) => { - if (event.target !== event.currentTarget) return; - done(); - dispose(); - } - ); + } + button && dispatch({ type: 2 /* SetButton */, button }); + } + ); + let withinPanelButtonRef = useSyncRefs(internalButtonRef, ref); + let ownerDocument = useOwnerDocument(internalButtonRef); + let handleKeyDown = useEvent((event) => { + var _a3, _b, _c; + if (isWithinPanel) { + if (state.popoverState === 1 /* Closed */) + return; + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + (_b = (_a3 = event.target).click) == null ? void 0 : _b.call(_a3); + dispatch({ type: 1 /* ClosePopover */ }); + (_c = state.button) == null ? void 0 : _c.focus(); + break; + } + } else { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + if (state.popoverState === 1 /* Closed */) + closeOthers == null ? void 0 : closeOthers(state.buttonId); + dispatch({ type: 0 /* TogglePopover */ }); + break; + case "Escape" /* Escape */: + if (state.popoverState !== 0 /* Open */) + return closeOthers == null ? void 0 : closeOthers(state.buttonId); + if (!internalButtonRef.current) + return; + if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) && !internalButtonRef.current.contains(ownerDocument.activeElement)) { + return; } - } else { - done(); - } - d.add(() => done()); - return d.dispose; + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* ClosePopover */ }); + break; } - function transition(node, classes, show, done) { - let direction = show ? "enter" : "leave"; - let d = disposables(); - let _done = done !== void 0 ? once(done) : () => {}; - if (direction === "enter") { - node.removeAttribute("hidden"); - node.style.display = ""; - } - let base = match(direction, { - enter: () => classes.enter, - leave: () => classes.leave, - }); - let to = match(direction, { - enter: () => classes.enterTo, - leave: () => classes.leaveTo, - }); - let from = match(direction, { - enter: () => classes.enterFrom, - leave: () => classes.leaveFrom, - }); - removeClasses( - node, - ...classes.enter, - ...classes.enterTo, - ...classes.enterFrom, - ...classes.leave, - ...classes.leaveFrom, - ...classes.leaveTo, - ...classes.entered + } + }); + let handleKeyUp = useEvent((event) => { + if (isWithinPanel) + return; + if (event.key === " " /* Space */) { + event.preventDefault(); + } + }); + let handleClick = useEvent((event) => { + var _a3, _b; + if (isDisabledReactIssue7711(event.currentTarget)) + return; + if (props.disabled) + return; + if (isWithinPanel) { + dispatch({ type: 1 /* ClosePopover */ }); + (_a3 = state.button) == null ? void 0 : _a3.focus(); + } else { + event.preventDefault(); + event.stopPropagation(); + if (state.popoverState === 1 /* Closed */) + closeOthers == null ? void 0 : closeOthers(state.buttonId); + dispatch({ type: 0 /* TogglePopover */ }); + (_b = state.button) == null ? void 0 : _b.focus(); + } + }); + let handleMouseDown = useEvent((event) => { + event.preventDefault(); + event.stopPropagation(); + }); + let visible = state.popoverState === 0 /* Open */; + let slot = (0, import_react37.useMemo)(() => ({ open: visible }), [visible]); + let type = useResolveButtonType(props, internalButtonRef); + let ourProps = isWithinPanel ? { + ref: withinPanelButtonRef, + type, + onKeyDown: handleKeyDown, + onClick: handleClick + } : { + ref: buttonRef, + id: state.buttonId, + type, + "aria-expanded": props.disabled ? void 0 : state.popoverState === 0 /* Open */, + "aria-controls": state.panel ? state.panelId : void 0, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick, + onMouseDown: handleMouseDown + }; + let direction = useTabDirection(); + let handleFocus = useEvent(() => { + let el = state.panel; + if (!el) + return; + function run() { + let result = match(direction.current, { + [0 /* Forwards */]: () => focusIn(el, 1 /* First */), + [1 /* Backwards */]: () => focusIn(el, 8 /* Last */) + }); + if (result === 0 /* Error */) { + focusIn( + getFocusableElements().filter((el2) => el2.dataset.headlessuiFocusGuard !== "true"), + match(direction.current, { + [0 /* Forwards */]: 4 /* Next */, + [1 /* Backwards */]: 2 /* Previous */ + }), + { relativeTo: state.button } ); - addClasses(node, ...base, ...from); - d.nextFrame(() => { - removeClasses(node, ...from); - addClasses(node, ...to); - waitForTransition(node, () => { - removeClasses(node, ...base); - addClasses(node, ...classes.entered); - return _done(); - }); - }); - return d.dispose; - } - - // src/hooks/use-transition.ts - function useTransition({ - container, - direction, - classes, - onStart, - onStop, - }) { - let mounted = useIsMounted(); - let d = useDisposables(); - let latestDirection = useLatestValue(direction); - useIsoMorphicEffect(() => { - let dd = disposables(); - d.add(dd.dispose); - let node = container.current; - if (!node) return; - if (latestDirection.current === "idle") return; - if (!mounted.current) return; - dd.dispose(); - onStart.current(latestDirection.current); - dd.add( - transition( - node, - classes.current, - latestDirection.current === "enter", - () => { - dd.dispose(); - onStop.current(latestDirection.current); - } - ) - ); - return dd.dispose; - }, [direction]); } - - // src/components/transitions/transition.tsx - function splitClasses(classes = "") { - return classes - .split(" ") - .filter((className) => className.trim().length > 1); - } - var TransitionContext = (0, import_react44.createContext)(null); - TransitionContext.displayName = "TransitionContext"; - function useTransitionContext() { - let context = (0, import_react44.useContext)(TransitionContext); - if (context === null) { - throw new Error( - "A is used but it is missing a parent or ." - ); + } + if (false) {} else { + run(); + } + }); + return /* @__PURE__ */ import_react37.default.createElement(import_react37.default.Fragment, null, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG5, + name: "Popover.Button" + }), visible && !isWithinPanel && isPortalled && /* @__PURE__ */ import_react37.default.createElement( + Hidden, + { + id: sentinelId, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleFocus + } + )); + } + var DEFAULT_OVERLAY_TAG2 = "div"; + var OverlayRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; + function OverlayFn2(props, ref) { + let internalId = useId(); + let { id = `headlessui-popover-overlay-${internalId}`, ...theirProps } = props; + let [{ popoverState }, dispatch] = usePopoverContext("Popover.Overlay"); + let overlayRef = useSyncRefs(ref); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return popoverState === 0 /* Open */; + })(); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + dispatch({ type: 1 /* ClosePopover */ }); + }); + let slot = (0, import_react37.useMemo)( + () => ({ open: popoverState === 0 /* Open */ }), + [popoverState] + ); + let ourProps = { + ref: overlayRef, + id, + "aria-hidden": true, + onClick: handleClick + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OVERLAY_TAG2, + features: OverlayRenderFeatures, + visible, + name: "Popover.Overlay" + }); + } + var DEFAULT_PANEL_TAG3 = "div"; + var PanelRenderFeatures2 = 1 /* RenderStrategy */ | 2 /* Static */; + function PanelFn3(props, ref) { + let internalId = useId(); + let { id = `headlessui-popover-panel-${internalId}`, focus = false, ...theirProps } = props; + let [state, dispatch] = usePopoverContext("Popover.Panel"); + let { close, isPortalled } = usePopoverAPIContext("Popover.Panel"); + let beforePanelSentinelId = `headlessui-focus-sentinel-before-${useId()}`; + let afterPanelSentinelId = `headlessui-focus-sentinel-after-${useId()}`; + let internalPanelRef = (0, import_react37.useRef)(null); + let panelRef = useSyncRefs(internalPanelRef, ref, (panel) => { + dispatch({ type: 4 /* SetPanel */, panel }); + }); + let ownerDocument = useOwnerDocument(internalPanelRef); + useIsoMorphicEffect(() => { + dispatch({ type: 5 /* SetPanelId */, panelId: id }); + return () => { + dispatch({ type: 5 /* SetPanelId */, panelId: null }); + }; + }, [id, dispatch]); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return state.popoverState === 0 /* Open */; + })(); + let handleKeyDown = useEvent((event) => { + var _a3; + switch (event.key) { + case "Escape" /* Escape */: + if (state.popoverState !== 0 /* Open */) + return; + if (!internalPanelRef.current) + return; + if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) && !internalPanelRef.current.contains(ownerDocument.activeElement)) { + return; } - return context; + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* ClosePopover */ }); + (_a3 = state.button) == null ? void 0 : _a3.focus(); + break; + } + }); + (0, import_react37.useEffect)(() => { + var _a3; + if (props.static) + return; + if (state.popoverState === 1 /* Closed */ && ((_a3 = props.unmount) != null ? _a3 : true)) { + dispatch({ type: 4 /* SetPanel */, panel: null }); + } + }, [state.popoverState, props.unmount, props.static, dispatch]); + (0, import_react37.useEffect)(() => { + if (state.__demoMode) + return; + if (!focus) + return; + if (state.popoverState !== 0 /* Open */) + return; + if (!internalPanelRef.current) + return; + let activeElement = ownerDocument == null ? void 0 : ownerDocument.activeElement; + if (internalPanelRef.current.contains(activeElement)) + return; + focusIn(internalPanelRef.current, 1 /* First */); + }, [state.__demoMode, focus, internalPanelRef, state.popoverState]); + let slot = (0, import_react37.useMemo)( + () => ({ open: state.popoverState === 0 /* Open */, close }), + [state, close] + ); + let ourProps = { + ref: panelRef, + id, + onKeyDown: handleKeyDown, + onBlur: focus && state.popoverState === 0 /* Open */ ? (event) => { + var _a3, _b, _c, _d, _e; + let el = event.relatedTarget; + if (!el) + return; + if (!internalPanelRef.current) + return; + if ((_a3 = internalPanelRef.current) == null ? void 0 : _a3.contains(el)) + return; + dispatch({ type: 1 /* ClosePopover */ }); + if (((_c = (_b = state.beforePanelSentinel.current) == null ? void 0 : _b.contains) == null ? void 0 : _c.call(_b, el)) || ((_e = (_d = state.afterPanelSentinel.current) == null ? void 0 : _d.contains) == null ? void 0 : _e.call(_d, el))) { + el.focus({ preventScroll: true }); } - function useParentNesting() { - let context = (0, import_react44.useContext)(NestingContext); - if (context === null) { - throw new Error( - "A is used but it is missing a parent or ." - ); + } : void 0, + tabIndex: -1 + }; + let direction = useTabDirection(); + let handleBeforeFocus = useEvent(() => { + let el = internalPanelRef.current; + if (!el) + return; + function run() { + match(direction.current, { + [0 /* Forwards */]: () => { + var _a3; + let result = focusIn(el, 1 /* First */); + if (result === 0 /* Error */) { + (_a3 = state.afterPanelSentinel.current) == null ? void 0 : _a3.focus(); + } + }, + [1 /* Backwards */]: () => { + var _a3; + (_a3 = state.button) == null ? void 0 : _a3.focus({ preventScroll: true }); } - return context; - } - var NestingContext = (0, import_react44.createContext)(null); - NestingContext.displayName = "NestingContext"; - function hasChildren(bag) { - if ("children" in bag) return hasChildren(bag.children); - return ( - bag.current - .filter(({ el }) => el.current !== null) - .filter(({ state }) => state === "visible" /* Visible */).length > - 0 - ); - } - function useNesting(done, parent) { - let doneRef = useLatestValue(done); - let transitionableChildren = (0, import_react44.useRef)([]); - let mounted = useIsMounted(); - let d = useDisposables(); - let unregister = useEvent((container, strategy = 1 /* Hidden */) => { - let idx = transitionableChildren.current.findIndex( - ({ el }) => el === container - ); - if (idx === -1) return; - match(strategy, { - [0 /* Unmount */]() { - transitionableChildren.current.splice(idx, 1); - }, - [1 /* Hidden */]() { - transitionableChildren.current[idx].state = - "hidden" /* Hidden */; - }, - }); - d.microTask(() => { - var _a3; - if (!hasChildren(transitionableChildren) && mounted.current) { - (_a3 = doneRef.current) == null ? void 0 : _a3.call(doneRef); + }); + } + if (false) {} else { + run(); + } + }); + let handleAfterFocus = useEvent(() => { + let el = internalPanelRef.current; + if (!el) + return; + function run() { + match(direction.current, { + [0 /* Forwards */]: () => { + var _a3; + if (!state.button) + return; + let elements = getFocusableElements(); + let idx = elements.indexOf(state.button); + let before = elements.slice(0, idx + 1); + let after = elements.slice(idx + 1); + let combined = [...after, ...before]; + for (let element of combined.slice()) { + if (element.dataset.headlessuiFocusGuard === "true" || ((_a3 = state.panel) == null ? void 0 : _a3.contains(element))) { + let idx2 = combined.indexOf(element); + if (idx2 !== -1) + combined.splice(idx2, 1); } - }); - }); - let register = useEvent((container) => { - let child = transitionableChildren.current.find( - ({ el }) => el === container - ); - if (!child) { - transitionableChildren.current.push({ - el: container, - state: "visible" /* Visible */, - }); - } else if (child.state !== "visible" /* Visible */) { - child.state = "visible" /* Visible */; - } - return () => unregister(container, 0 /* Unmount */); - }); - let todos = (0, import_react44.useRef)([]); - let wait = (0, import_react44.useRef)(Promise.resolve()); - let chains = (0, import_react44.useRef)({ - enter: [], - leave: [], - idle: [], - }); - let onStart = useEvent((container, direction, cb) => { - todos.current.splice(0); - if (parent) { - parent.chains.current[direction] = parent.chains.current[ - direction - ].filter( - ([containerInParent]) => containerInParent !== container - ); } - parent == null - ? void 0 - : parent.chains.current[direction].push([ - container, - new Promise((resolve) => { - todos.current.push(resolve); - }), - ]); - parent == null - ? void 0 - : parent.chains.current[direction].push([ - container, - new Promise((resolve) => { - Promise.all( - chains.current[direction].map( - ([_container, promise]) => promise - ) - ).then(() => resolve()); - }), - ]); - if (direction === "enter") { - wait.current = wait.current - .then(() => (parent == null ? void 0 : parent.wait.current)) - .then(() => cb(direction)); - } else { - cb(direction); + focusIn(combined, 1 /* First */, { sorted: false }); + }, + [1 /* Backwards */]: () => { + var _a3; + let result = focusIn(el, 2 /* Previous */); + if (result === 0 /* Error */) { + (_a3 = state.button) == null ? void 0 : _a3.focus(); } - }); - let onStop = useEvent((_container, direction, cb) => { - Promise.all( - chains.current[direction] - .splice(0) - .map(([_container2, promise]) => promise) - ) - .then(() => { - var _a3; - (_a3 = todos.current.shift()) == null ? void 0 : _a3(); - }) - .then(() => cb(direction)); - }); - return (0, import_react44.useMemo)( - () => ({ - children: transitionableChildren, - register, - unregister, - onStart, - onStop, - wait, - chains, - }), - [ - register, - unregister, - transitionableChildren, - onStart, - onStop, - chains, - wait, - ] - ); - } - function noop() {} - var eventNames = [ - "beforeEnter", - "afterEnter", - "beforeLeave", - "afterLeave", - ]; - function ensureEventHooksExist(events) { - var _a3; - let result = {}; - for (let name of eventNames) { - result[name] = (_a3 = events[name]) != null ? _a3 : noop; } - return result; + }); + } + if (false) {} else { + run(); + } + }); + return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: id }, visible && isPortalled && /* @__PURE__ */ import_react37.default.createElement( + Hidden, + { + id: beforePanelSentinelId, + ref: state.beforePanelSentinel, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleBeforeFocus + } + ), render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG3, + features: PanelRenderFeatures2, + visible, + name: "Popover.Panel" + }), visible && isPortalled && /* @__PURE__ */ import_react37.default.createElement( + Hidden, + { + id: afterPanelSentinelId, + ref: state.afterPanelSentinel, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleAfterFocus + } + )); + } + var DEFAULT_GROUP_TAG2 = "div"; + function GroupFn2(props, ref) { + let internalGroupRef = (0, import_react37.useRef)(null); + let groupRef = useSyncRefs(internalGroupRef, ref); + let [popovers, setPopovers] = (0, import_react37.useState)([]); + let unregisterPopover = useEvent((registerbag) => { + setPopovers((existing) => { + let idx = existing.indexOf(registerbag); + if (idx !== -1) { + let clone = existing.slice(); + clone.splice(idx, 1); + return clone; } - function useEvents(events) { - let eventsRef = (0, import_react44.useRef)( - ensureEventHooksExist(events) - ); - (0, import_react44.useEffect)(() => { - eventsRef.current = ensureEventHooksExist(events); - }, [events]); - return eventsRef; - } - var DEFAULT_TRANSITION_CHILD_TAG = "div"; - var TransitionChildRenderFeatures = 1; /* RenderStrategy */ - function TransitionChildFn(props, ref) { - let { - // Event "handlers" - beforeEnter, - afterEnter, - beforeLeave, - afterLeave, - // Class names - enter, - enterFrom, - enterTo, - entered, - leave, - leaveFrom, - leaveTo, - // @ts-expect-error - ...rest - } = props; - let container = (0, import_react44.useRef)(null); - let transitionRef = useSyncRefs(container, ref); - let strategy = rest.unmount ? 0 /* Unmount */ : 1; /* Hidden */ - let { show, appear, initial } = useTransitionContext(); - let [state, setState] = (0, import_react44.useState)( - show ? "visible" /* Visible */ : "hidden" /* Hidden */ - ); - let parentNesting = useParentNesting(); - let { register, unregister } = parentNesting; - let prevShow = (0, import_react44.useRef)(null); - (0, import_react44.useEffect)( - () => register(container), - [register, container] - ); - (0, import_react44.useEffect)(() => { - if (strategy !== 1 /* Hidden */) return; - if (!container.current) return; - if (show && state !== "visible" /* Visible */) { - setState("visible" /* Visible */); - return; - } - return match(state, { - ["hidden" /* Hidden */]: () => unregister(container), - ["visible" /* Visible */]: () => register(container), + return existing; + }); + }); + let registerPopover = useEvent((registerbag) => { + setPopovers((existing) => [...existing, registerbag]); + return () => unregisterPopover(registerbag); + }); + let isFocusWithinPopoverGroup = useEvent(() => { + var _a3; + let ownerDocument = getOwnerDocument(internalGroupRef); + if (!ownerDocument) + return false; + let element = ownerDocument.activeElement; + if ((_a3 = internalGroupRef.current) == null ? void 0 : _a3.contains(element)) + return true; + return popovers.some((bag) => { + var _a4, _b; + return ((_a4 = ownerDocument.getElementById(bag.buttonId.current)) == null ? void 0 : _a4.contains(element)) || ((_b = ownerDocument.getElementById(bag.panelId.current)) == null ? void 0 : _b.contains(element)); + }); + }); + let closeOthers = useEvent((buttonId) => { + for (let popover of popovers) { + if (popover.buttonId.current !== buttonId) + popover.close(); + } + }); + let contextBag = (0, import_react37.useMemo)( + () => ({ + registerPopover, + unregisterPopover, + isFocusWithinPopoverGroup, + closeOthers + }), + [registerPopover, unregisterPopover, isFocusWithinPopoverGroup, closeOthers] + ); + let slot = (0, import_react37.useMemo)(() => ({}), []); + let theirProps = props; + let ourProps = { ref: groupRef }; + return /* @__PURE__ */ import_react37.default.createElement(PopoverGroupContext.Provider, { value: contextBag }, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_GROUP_TAG2, + name: "Popover.Group" + })); + } + var PopoverRoot = forwardRefWithAs(PopoverFn); + var Button5 = forwardRefWithAs(ButtonFn5); + var Overlay2 = forwardRefWithAs(OverlayFn2); + var Panel3 = forwardRefWithAs(PanelFn3); + var Group2 = forwardRefWithAs(GroupFn2); + var Popover = Object.assign(PopoverRoot, { Button: Button5, Overlay: Overlay2, Panel: Panel3, Group: Group2 }); + + // src/components/radio-group/radio-group.tsx + var import_react40 = __toESM(__webpack_require__(/*! react */ "react"), 1); + + // src/hooks/use-flags.ts + var import_react38 = __webpack_require__(/*! react */ "react"); + function useFlags(initialFlags = 0) { + let [flags, setFlags] = (0, import_react38.useState)(initialFlags); + let mounted = useIsMounted(); + let addFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) + return; + setFlags((flags2) => flags2 | flag); + }, + [flags, mounted] + ); + let hasFlag = (0, import_react38.useCallback)((flag) => Boolean(flags & flag), [flags]); + let removeFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) + return; + setFlags((flags2) => flags2 & ~flag); + }, + [setFlags, mounted] + ); + let toggleFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) + return; + setFlags((flags2) => flags2 ^ flag); + }, + [setFlags] + ); + return { flags, addFlag, hasFlag, removeFlag, toggleFlag }; + } + + // src/components/label/label.tsx + var import_react39 = __toESM(__webpack_require__(/*! react */ "react"), 1); + var LabelContext = (0, import_react39.createContext)( + null + ); + function useLabelContext() { + let context = (0, import_react39.useContext)(LabelContext); + if (context === null) { + let err = new Error("You used a
    + * }) + * + * const MotionComponent = motion(Component) + * ``` + * + * @public + */ +function createMotionProxy(createConfig) { + function custom(Component, customMotionComponentConfig) { + if (customMotionComponentConfig === void 0) { + customMotionComponentConfig = {}; + } + return createMotionComponent(createConfig(Component, customMotionComponentConfig)); + } + if (typeof Proxy === "undefined") { + return custom; + } + /** + * A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc. + * Rather than generating them anew every render. + */ + var componentCache = new Map(); + return new Proxy(custom, { + /** + * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. + * The prop name is passed through as `key` and we can use that to generate a `motion` + * DOM component with that name. + */ + get: function (_target, key) { + /** + * If this element doesn't exist in the component cache, create it and cache. + */ + if (!componentCache.has(key)) { + componentCache.set(key, custom(key)); } - return { - data: { - x: x, - y: y - } - }; + return componentCache.get(key); } }); - function $34310caa050a8d63$var$getSideAndAlignFromPlacement(placement) { - const [side, align = 'center'] = placement.split('-'); - return [side, align]; - } - const $34310caa050a8d63$export$be92b6f5f03c0fe9 = $34310caa050a8d63$export$badac9ada3a0bdf9; - const $34310caa050a8d63$export$b688253958b8dfe7 = $34310caa050a8d63$export$ecd4e1ccab6ed6d; - const $34310caa050a8d63$export$7c6e2c02157bb7d2 = $34310caa050a8d63$export$bc4ae5855d3c4fc; - const $34310caa050a8d63$export$21b07c8f274aebd5 = $34310caa050a8d63$export$79d62cd4e10a3fd0; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-portal/dist/index.js": - /*!******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-portal/dist/index.js ***! - \******************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $amzHf$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); - var $amzHf$react = __webpack_require__(/*! react */ "react"); - var $amzHf$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); - var $amzHf$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; +} + +/** + * We keep these listed seperately as we use the lowercase tag names as part + * of the runtime bundle to detect SVG components + */ +var lowercaseSVGElements = ["animate", "circle", "defs", "desc", "ellipse", "g", "image", "line", "filter", "marker", "mask", "metadata", "path", "pattern", "polygon", "polyline", "rect", "stop", "svg", "switch", "symbol", "text", "tspan", "use", "view"]; +function isSVGComponent(Component) { + if ( + /** + * If it's not a string, it's a custom React component. Currently we only support + * HTML custom React components. + */ + typeof Component !== "string" || + /** + * If it contains a dash, the element is a custom HTML webcomponent. + */ + Component.includes("-")) { + return false; + } else if ( + /** + * If it's in our list of lowercase SVG tags, it's an SVG component + */ + lowercaseSVGElements.indexOf(Component) > -1 || + /** + * If it contains a capital letter, it's an SVG component + */ + /[A-Z]/.test(Component)) { + return true; } - $parcel$export(module.exports, "Portal", () => $913a70b877676c16$export$602eac185826482c); - $parcel$export(module.exports, "Root", () => $913a70b877676c16$export$be92b6f5f03c0fe9); - - /* ------------------------------------------------------------------------------------------------- - * Portal - * -----------------------------------------------------------------------------------------------*/ - const $913a70b877676c16$var$PORTAL_NAME = 'Portal'; - const $913a70b877676c16$export$602eac185826482c = /*#__PURE__*/$amzHf$react.forwardRef((props, forwardedRef) => { - var _globalThis$document; - const { - container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body, - ...portalProps - } = props; - return container ? /*#__PURE__*/$parcel$interopDefault($amzHf$reactdom).createPortal( /*#__PURE__*/$amzHf$react.createElement($amzHf$radixuireactprimitive.Primitive.div, $parcel$interopDefault($amzHf$babelruntimehelpersextends)({}, portalProps, { - ref: forwardedRef - })), container) : null; + return false; +} +var scaleCorrectors = {}; +function addScaleCorrector(correctors) { + Object.assign(scaleCorrectors, correctors); +} + +/** + * A list of all transformable axes. We'll use this list to generated a version + * of each axes for each transform. + */ +var transformAxes = ["", "X", "Y", "Z"]; +/** + * An ordered array of each transformable value. By default, transform values + * will be sorted to this order. + */ +var order = ["translate", "scale", "rotate", "skew"]; +/** + * Generate a list of every possible transform key. + */ +var transformProps = ["transformPerspective", "x", "y", "z"]; +order.forEach(function (operationKey) { + return transformAxes.forEach(function (axesKey) { + return transformProps.push(operationKey + axesKey); }); - /*#__PURE__*/ - Object.assign($913a70b877676c16$export$602eac185826482c, { - displayName: $913a70b877676c16$var$PORTAL_NAME +}); +/** + * A function to use with Array.sort to sort transform keys by their default order. + */ +function sortTransformProps(a, b) { + return transformProps.indexOf(a) - transformProps.indexOf(b); +} +/** + * A quick lookup for transform props. + */ +var transformPropSet = new Set(transformProps); +function isTransformProp(key) { + return transformPropSet.has(key); +} +/** + * A quick lookup for transform origin props + */ +var transformOriginProps = new Set(["originX", "originY", "originZ"]); +function isTransformOriginProp(key) { + return transformOriginProps.has(key); +} +function isForcedMotionValue(key, _a) { + var layout = _a.layout, + layoutId = _a.layoutId; + return isTransformProp(key) || isTransformOriginProp(key) || (layout || layoutId !== undefined) && (!!scaleCorrectors[key] || key === "opacity"); +} +var isMotionValue = function (value) { + return Boolean(value !== null && typeof value === "object" && value.getVelocity); +}; +var translateAlias = { + x: "translateX", + y: "translateY", + z: "translateZ", + transformPerspective: "perspective" +}; +/** + * Build a CSS transform style from individual x/y/scale etc properties. + * + * This outputs with a default order of transforms/scales/rotations, this can be customised by + * providing a transformTemplate function. + */ +function buildTransform(_a, _b, transformIsDefault, transformTemplate) { + var transform = _a.transform, + transformKeys = _a.transformKeys; + var _c = _b.enableHardwareAcceleration, + enableHardwareAcceleration = _c === void 0 ? true : _c, + _d = _b.allowTransformNone, + allowTransformNone = _d === void 0 ? true : _d; + // The transform string we're going to build into. + var transformString = ""; + // Transform keys into their default order - this will determine the output order. + transformKeys.sort(sortTransformProps); + // Track whether the defined transform has a defined z so we don't add a + // second to enable hardware acceleration + var transformHasZ = false; + // Loop over each transform and build them into transformString + var numTransformKeys = transformKeys.length; + for (var i = 0; i < numTransformKeys; i++) { + var key = transformKeys[i]; + transformString += "".concat(translateAlias[key] || key, "(").concat(transform[key], ") "); + if (key === "z") transformHasZ = true; + } + if (!transformHasZ && enableHardwareAcceleration) { + transformString += "translateZ(0)"; + } else { + transformString = transformString.trim(); + } + // If we have a custom `transform` template, pass our transform values and + // generated transformString to that before returning + if (transformTemplate) { + transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); + } else if (allowTransformNone && transformIsDefault) { + transformString = "none"; + } + return transformString; +} +/** + * Build a transformOrigin style. Uses the same defaults as the browser for + * undefined origins. + */ +function buildTransformOrigin(_a) { + var _b = _a.originX, + originX = _b === void 0 ? "50%" : _b, + _c = _a.originY, + originY = _c === void 0 ? "50%" : _c, + _d = _a.originZ, + originZ = _d === void 0 ? 0 : _d; + return "".concat(originX, " ").concat(originY, " ").concat(originZ); +} + +/** + * Returns true if the provided key is a CSS variable + */ +function isCSSVariable$1(key) { + return key.startsWith("--"); +} + +/** + * Provided a value and a ValueType, returns the value as that value type. + */ +var getValueAsType = function (value, type) { + return type && typeof value === "number" ? type.transform(value) : value; +}; +var int = tslib.__assign(tslib.__assign({}, styleValueTypes.number), { + transform: Math.round +}); +var numberValueTypes = { + // Border props + borderWidth: styleValueTypes.px, + borderTopWidth: styleValueTypes.px, + borderRightWidth: styleValueTypes.px, + borderBottomWidth: styleValueTypes.px, + borderLeftWidth: styleValueTypes.px, + borderRadius: styleValueTypes.px, + radius: styleValueTypes.px, + borderTopLeftRadius: styleValueTypes.px, + borderTopRightRadius: styleValueTypes.px, + borderBottomRightRadius: styleValueTypes.px, + borderBottomLeftRadius: styleValueTypes.px, + // Positioning props + width: styleValueTypes.px, + maxWidth: styleValueTypes.px, + height: styleValueTypes.px, + maxHeight: styleValueTypes.px, + size: styleValueTypes.px, + top: styleValueTypes.px, + right: styleValueTypes.px, + bottom: styleValueTypes.px, + left: styleValueTypes.px, + // Spacing props + padding: styleValueTypes.px, + paddingTop: styleValueTypes.px, + paddingRight: styleValueTypes.px, + paddingBottom: styleValueTypes.px, + paddingLeft: styleValueTypes.px, + margin: styleValueTypes.px, + marginTop: styleValueTypes.px, + marginRight: styleValueTypes.px, + marginBottom: styleValueTypes.px, + marginLeft: styleValueTypes.px, + // Transform props + rotate: styleValueTypes.degrees, + rotateX: styleValueTypes.degrees, + rotateY: styleValueTypes.degrees, + rotateZ: styleValueTypes.degrees, + scale: styleValueTypes.scale, + scaleX: styleValueTypes.scale, + scaleY: styleValueTypes.scale, + scaleZ: styleValueTypes.scale, + skew: styleValueTypes.degrees, + skewX: styleValueTypes.degrees, + skewY: styleValueTypes.degrees, + distance: styleValueTypes.px, + translateX: styleValueTypes.px, + translateY: styleValueTypes.px, + translateZ: styleValueTypes.px, + x: styleValueTypes.px, + y: styleValueTypes.px, + z: styleValueTypes.px, + perspective: styleValueTypes.px, + transformPerspective: styleValueTypes.px, + opacity: styleValueTypes.alpha, + originX: styleValueTypes.progressPercentage, + originY: styleValueTypes.progressPercentage, + originZ: styleValueTypes.px, + // Misc + zIndex: int, + // SVG + fillOpacity: styleValueTypes.alpha, + strokeOpacity: styleValueTypes.alpha, + numOctaves: int +}; +function buildHTMLStyles(state, latestValues, options, transformTemplate) { + var _a; + var style = state.style, + vars = state.vars, + transform = state.transform, + transformKeys = state.transformKeys, + transformOrigin = state.transformOrigin; + // Empty the transformKeys array. As we're throwing out refs to its items + // this might not be as cheap as suspected. Maybe using the array as a buffer + // with a manual incrementation would be better. + transformKeys.length = 0; + // Track whether we encounter any transform or transformOrigin values. + var hasTransform = false; + var hasTransformOrigin = false; + // Does the calculated transform essentially equal "none"? + var transformIsNone = true; + /** + * Loop over all our latest animated values and decide whether to handle them + * as a style or CSS variable. + * + * Transforms and transform origins are kept seperately for further processing. + */ + for (var key in latestValues) { + var value = latestValues[key]; + /** + * If this is a CSS variable we don't do any further processing. + */ + if (isCSSVariable$1(key)) { + vars[key] = value; + continue; + } + // Convert the value to its default value type, ie 0 -> "0px" + var valueType = numberValueTypes[key]; + var valueAsType = getValueAsType(value, valueType); + if (isTransformProp(key)) { + // If this is a transform, flag to enable further transform processing + hasTransform = true; + transform[key] = valueAsType; + transformKeys.push(key); + // If we already know we have a non-default transform, early return + if (!transformIsNone) continue; + // Otherwise check to see if this is a default transform + if (value !== ((_a = valueType.default) !== null && _a !== void 0 ? _a : 0)) transformIsNone = false; + } else if (isTransformOriginProp(key)) { + transformOrigin[key] = valueAsType; + // If this is a transform origin, flag and enable further transform-origin processing + hasTransformOrigin = true; + } else { + style[key] = valueAsType; + } + } + if (hasTransform) { + style.transform = buildTransform(state, options, transformIsNone, transformTemplate); + } else if (transformTemplate) { + style.transform = transformTemplate({}, ""); + } else if (!latestValues.transform && style.transform) { + style.transform = "none"; + } + if (hasTransformOrigin) { + style.transformOrigin = buildTransformOrigin(transformOrigin); + } +} +var createHtmlRenderState = function () { + return { + style: {}, + transform: {}, + transformKeys: [], + transformOrigin: {}, + vars: {} + }; +}; +function copyRawValuesOnly(target, source, props) { + for (var key in source) { + if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { + target[key] = source[key]; + } + } +} +function useInitialMotionValues(_a, visualState, isStatic) { + var transformTemplate = _a.transformTemplate; + return React.useMemo(function () { + var state = createHtmlRenderState(); + buildHTMLStyles(state, visualState, { + enableHardwareAcceleration: !isStatic + }, transformTemplate); + var vars = state.vars, + style = state.style; + return tslib.__assign(tslib.__assign({}, vars), style); + }, [visualState]); +} +function useStyle(props, visualState, isStatic) { + var styleProp = props.style || {}; + var style = {}; + /** + * Copy non-Motion Values straight into style + */ + copyRawValuesOnly(style, styleProp, props); + Object.assign(style, useInitialMotionValues(props, visualState, isStatic)); + if (props.transformValues) { + style = props.transformValues(style); + } + return style; +} +function useHTMLProps(props, visualState, isStatic) { + // The `any` isn't ideal but it is the type of createElement props argument + var htmlProps = {}; + var style = useStyle(props, visualState, isStatic); + if (Boolean(props.drag) && props.dragListener !== false) { + // Disable the ghost element when a user drags + htmlProps.draggable = false; + // Disable text selection + style.userSelect = style.WebkitUserSelect = style.WebkitTouchCallout = "none"; + // Disable scrolling on the draggable direction + style.touchAction = props.drag === true ? "none" : "pan-".concat(props.drag === "x" ? "y" : "x"); + } + htmlProps.style = style; + return htmlProps; +} + +/** + * A list of all valid MotionProps. + * + * @privateRemarks + * This doesn't throw if a `MotionProp` name is missing - it should. + */ +var validMotionProps = new Set(["initial", "animate", "exit", "style", "variants", "transition", "transformTemplate", "transformValues", "custom", "inherit", "layout", "layoutId", "layoutDependency", "onLayoutAnimationStart", "onLayoutAnimationComplete", "onLayoutMeasure", "onBeforeLayoutMeasure", "onAnimationStart", "onAnimationComplete", "onUpdate", "onDragStart", "onDrag", "onDragEnd", "onMeasureDragConstraints", "onDirectionLock", "onDragTransitionEnd", "drag", "dragControls", "dragListener", "dragConstraints", "dragDirectionLock", "dragSnapToOrigin", "_dragX", "_dragY", "dragElastic", "dragMomentum", "dragPropagation", "dragTransition", "whileDrag", "onPan", "onPanStart", "onPanEnd", "onPanSessionStart", "onTap", "onTapStart", "onTapCancel", "onHoverStart", "onHoverEnd", "whileFocus", "whileTap", "whileHover", "whileInView", "onViewportEnter", "onViewportLeave", "viewport", "layoutScroll"]); +/** + * Check whether a prop name is a valid `MotionProp` key. + * + * @param key - Name of the property to check + * @returns `true` is key is a valid `MotionProp`. + * + * @public + */ +function isValidMotionProp(key) { + return validMotionProps.has(key); +} +var shouldForward = function (key) { + return !isValidMotionProp(key); +}; +function loadExternalIsValidProp(isValidProp) { + if (!isValidProp) return; + // Explicitly filter our events + shouldForward = function (key) { + return key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); + }; +} +/** + * Emotion and Styled Components both allow users to pass through arbitrary props to their components + * to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which + * of these should be passed to the underlying DOM node. + * + * However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props + * as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props + * passed through the `custom` prop so it doesn't *need* the payload or computational overhead of + * `@emotion/is-prop-valid`, however to fix this problem we need to use it. + * + * By making it an optionalDependency we can offer this functionality only in the situations where it's + * actually required. + */ +try { + /** + * We attempt to import this package but require won't be defined in esm environments, in that case + * isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed + * in favour of explicit injection. + */ + loadExternalIsValidProp((__webpack_require__(/*! @emotion/is-prop-valid */ "../../../node_modules/@emotion/is-prop-valid/dist/is-prop-valid.browser.esm.js")["default"])); +} catch (_a) { + // We don't need to actually do anything here - the fallback is the existing `isPropValid`. +} +function filterProps(props, isDom, forwardMotionProps) { + var filteredProps = {}; + for (var key in props) { + if (shouldForward(key) || forwardMotionProps === true && isValidMotionProp(key) || !isDom && !isValidMotionProp(key) || + // If trying to use native HTML drag events, forward drag listeners + props["draggable"] && key.startsWith("onDrag")) { + filteredProps[key] = props[key]; + } + } + return filteredProps; +} +function calcOrigin$1(origin, offset, size) { + return typeof origin === "string" ? origin : styleValueTypes.px.transform(offset + size * origin); +} +/** + * The SVG transform origin defaults are different to CSS and is less intuitive, + * so we use the measured dimensions of the SVG to reconcile these. + */ +function calcSVGTransformOrigin(dimensions, originX, originY) { + var pxOriginX = calcOrigin$1(originX, dimensions.x, dimensions.width); + var pxOriginY = calcOrigin$1(originY, dimensions.y, dimensions.height); + return "".concat(pxOriginX, " ").concat(pxOriginY); +} +var dashKeys = { + offset: "stroke-dashoffset", + array: "stroke-dasharray" +}; +var camelKeys = { + offset: "strokeDashoffset", + array: "strokeDasharray" +}; +/** + * Build SVG path properties. Uses the path's measured length to convert + * our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset + * and stroke-dasharray attributes. + * + * This function is mutative to reduce per-frame GC. + */ +function buildSVGPath(attrs, length, spacing, offset, useDashCase) { + if (spacing === void 0) { + spacing = 1; + } + if (offset === void 0) { + offset = 0; + } + if (useDashCase === void 0) { + useDashCase = true; + } + // Normalise path length by setting SVG attribute pathLength to 1 + attrs.pathLength = 1; + // We use dash case when setting attributes directly to the DOM node and camel case + // when defining props on a React component. + var keys = useDashCase ? dashKeys : camelKeys; + // Build the dash offset + attrs[keys.offset] = styleValueTypes.px.transform(-offset); + // Build the dash array + var pathLength = styleValueTypes.px.transform(length); + var pathSpacing = styleValueTypes.px.transform(spacing); + attrs[keys.array] = "".concat(pathLength, " ").concat(pathSpacing); +} + +/** + * Build SVG visual attrbutes, like cx and style.transform + */ +function buildSVGAttrs(state, _a, options, transformTemplate) { + var attrX = _a.attrX, + attrY = _a.attrY, + originX = _a.originX, + originY = _a.originY, + pathLength = _a.pathLength, + _b = _a.pathSpacing, + pathSpacing = _b === void 0 ? 1 : _b, + _c = _a.pathOffset, + pathOffset = _c === void 0 ? 0 : _c, + // This is object creation, which we try to avoid per-frame. + latest = tslib.__rest(_a, ["attrX", "attrY", "originX", "originY", "pathLength", "pathSpacing", "pathOffset"]); + buildHTMLStyles(state, latest, options, transformTemplate); + state.attrs = state.style; + state.style = {}; + var attrs = state.attrs, + style = state.style, + dimensions = state.dimensions; + /** + * However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs + * and copy it into style. + */ + if (attrs.transform) { + if (dimensions) style.transform = attrs.transform; + delete attrs.transform; + } + // Parse transformOrigin + if (dimensions && (originX !== undefined || originY !== undefined || style.transform)) { + style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== undefined ? originX : 0.5, originY !== undefined ? originY : 0.5); + } + // Treat x/y not as shortcuts but as actual attributes + if (attrX !== undefined) attrs.x = attrX; + if (attrY !== undefined) attrs.y = attrY; + // Build SVG path if one has been defined + if (pathLength !== undefined) { + buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); + } +} +var createSvgRenderState = function () { + return tslib.__assign(tslib.__assign({}, createHtmlRenderState()), { + attrs: {} }); - /* -----------------------------------------------------------------------------------------------*/ - const $913a70b877676c16$export$be92b6f5f03c0fe9 = $913a70b877676c16$export$602eac185826482c; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-presence/dist/index.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-presence/dist/index.js ***! - \********************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $fnLeV$react = __webpack_require__(/*! react */ "react"); - var $fnLeV$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); - var $fnLeV$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); - var $fnLeV$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true +}; +function useSVGProps(props, visualState) { + var visualProps = React.useMemo(function () { + var state = createSvgRenderState(); + buildSVGAttrs(state, visualState, { + enableHardwareAcceleration: false + }, props.transformTemplate); + return tslib.__assign(tslib.__assign({}, state.attrs), { + style: tslib.__assign({}, state.style) }); - } - $parcel$export(module.exports, "Presence", () => $a2fa0214bb2735a1$export$99c2b779aa4e8b8b); - function $8f63844556d0d3cd$export$3e6543de14f8614f(initialState, machine) { - return $fnLeV$react.useReducer((state, event) => { - const nextState = machine[state][event]; - return nextState !== null && nextState !== void 0 ? nextState : state; - }, initialState); - } - const $a2fa0214bb2735a1$export$99c2b779aa4e8b8b = props => { - const { - present: present, - children: children - } = props; - const presence = $a2fa0214bb2735a1$var$usePresence(present); - const child = typeof children === 'function' ? children({ - present: presence.isPresent - }) : $fnLeV$react.Children.only(children); - const ref = $fnLeV$radixuireactcomposerefs.useComposedRefs(presence.ref, child.ref); - const forceMount = typeof children === 'function'; - return forceMount || presence.isPresent ? /*#__PURE__*/$fnLeV$react.cloneElement(child, { + }, [visualState]); + if (props.style) { + var rawStyles = {}; + copyRawValuesOnly(rawStyles, props.style, props); + visualProps.style = tslib.__assign(tslib.__assign({}, rawStyles), visualProps.style); + } + return visualProps; +} +function createUseRender(forwardMotionProps) { + if (forwardMotionProps === void 0) { + forwardMotionProps = false; + } + var useRender = function (Component, props, projectionId, ref, _a, isStatic) { + var latestValues = _a.latestValues; + var useVisualProps = isSVGComponent(Component) ? useSVGProps : useHTMLProps; + var visualProps = useVisualProps(props, latestValues, isStatic); + var filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); + var elementProps = tslib.__assign(tslib.__assign(tslib.__assign({}, filteredProps), visualProps), { ref: ref - }) : null; + }); + if (projectionId) { + elementProps["data-projection-id"] = projectionId; + } + return React.createElement(Component, elementProps); }; - $a2fa0214bb2735a1$export$99c2b779aa4e8b8b.displayName = 'Presence'; - /* ------------------------------------------------------------------------------------------------- - * usePresence - * -----------------------------------------------------------------------------------------------*/ - function $a2fa0214bb2735a1$var$usePresence(present) { - const [node1, setNode] = $fnLeV$react.useState(); - const stylesRef = $fnLeV$react.useRef({}); - const prevPresentRef = $fnLeV$react.useRef(present); - const prevAnimationNameRef = $fnLeV$react.useRef('none'); - const initialState = present ? 'mounted' : 'unmounted'; - const [state, send] = $8f63844556d0d3cd$export$3e6543de14f8614f(initialState, { - mounted: { - UNMOUNT: 'unmounted', - ANIMATION_OUT: 'unmountSuspended' - }, - unmountSuspended: { - MOUNT: 'mounted', - ANIMATION_END: 'unmounted' - }, - unmounted: { - MOUNT: 'mounted' - } + return useRender; +} +var CAMEL_CASE_PATTERN = /([a-z])([A-Z])/g; +var REPLACE_TEMPLATE = "$1-$2"; +/** + * Convert camelCase to dash-case properties. + */ +var camelToDash = function (str) { + return str.replace(CAMEL_CASE_PATTERN, REPLACE_TEMPLATE).toLowerCase(); +}; +function renderHTML(element, _a, styleProp, projection) { + var style = _a.style, + vars = _a.vars; + Object.assign(element.style, style, projection && projection.getProjectionStyles(styleProp)); + // Loop over any CSS variables and assign those. + for (var key in vars) { + element.style.setProperty(key, vars[key]); + } +} + +/** + * A set of attribute names that are always read/written as camel case. + */ +var camelCaseAttributes = new Set(["baseFrequency", "diffuseConstant", "kernelMatrix", "kernelUnitLength", "keySplines", "keyTimes", "limitingConeAngle", "markerHeight", "markerWidth", "numOctaves", "targetX", "targetY", "surfaceScale", "specularConstant", "specularExponent", "stdDeviation", "tableValues", "viewBox", "gradientTransform", "pathLength"]); +function renderSVG(element, renderState, _styleProp, projection) { + renderHTML(element, renderState, undefined, projection); + for (var key in renderState.attrs) { + element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); + } +} +function scrapeMotionValuesFromProps$1(props) { + var style = props.style; + var newValues = {}; + for (var key in style) { + if (isMotionValue(style[key]) || isForcedMotionValue(key, props)) { + newValues[key] = style[key]; + } + } + return newValues; +} +function scrapeMotionValuesFromProps(props) { + var newValues = scrapeMotionValuesFromProps$1(props); + for (var key in props) { + if (isMotionValue(props[key])) { + var targetKey = key === "x" || key === "y" ? "attr" + key.toUpperCase() : key; + newValues[targetKey] = props[key]; + } + } + return newValues; +} +function isAnimationControls(v) { + return typeof v === "object" && typeof v.start === "function"; +} +var isKeyframesTarget = function (v) { + return Array.isArray(v); +}; +var isCustomValue = function (v) { + return Boolean(v && typeof v === "object" && v.mix && v.toValue); +}; +var resolveFinalValueInKeyframes = function (v) { + // TODO maybe throw if v.length - 1 is placeholder token? + return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; +}; + +/** + * If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself + * + * TODO: Remove and move to library + */ +function resolveMotionValue(value) { + var unwrappedValue = isMotionValue(value) ? value.get() : value; + return isCustomValue(unwrappedValue) ? unwrappedValue.toValue() : unwrappedValue; +} +function makeState(_a, props, context, presenceContext) { + var scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps, + createRenderState = _a.createRenderState, + onMount = _a.onMount; + var state = { + latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps), + renderState: createRenderState() + }; + if (onMount) { + state.mount = function (instance) { + return onMount(props, instance, state); + }; + } + return state; +} +var makeUseVisualState = function (config) { + return function (props, isStatic) { + var context = React.useContext(MotionContext); + var presenceContext = React.useContext(PresenceContext); + return isStatic ? makeState(config, props, context, presenceContext) : useConstant(function () { + return makeState(config, props, context, presenceContext); }); - $fnLeV$react.useEffect(() => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - prevAnimationNameRef.current = state === 'mounted' ? currentAnimationName : 'none'; - }, [state]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - const styles = stylesRef.current; - const wasPresent = prevPresentRef.current; - const hasPresentChanged = wasPresent !== present; - if (hasPresentChanged) { - const prevAnimationName = prevAnimationNameRef.current; - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(styles); - if (present) send('MOUNT');else if (currentAnimationName === 'none' || (styles === null || styles === void 0 ? void 0 : styles.display) === 'none') - // If there is no exit animation or the element is hidden, animations won't run - // so we unmount instantly - send('UNMOUNT');else { + }; +}; +function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { + var values = {}; + var blockInitialAnimation = (presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.initial) === false; + var motionValues = scrapeMotionValues(props); + for (var key in motionValues) { + values[key] = resolveMotionValue(motionValues[key]); + } + var initial = props.initial, + animate = props.animate; + var isControllingVariants = checkIfControllingVariants(props); + var isVariantNode = checkIfVariantNode(props); + if (context && isVariantNode && !isControllingVariants && props.inherit !== false) { + initial !== null && initial !== void 0 ? initial : initial = context.initial; + animate !== null && animate !== void 0 ? animate : animate = context.animate; + } + var initialAnimationIsBlocked = blockInitialAnimation || initial === false; + var variantToSet = initialAnimationIsBlocked ? animate : initial; + if (variantToSet && typeof variantToSet !== "boolean" && !isAnimationControls(variantToSet)) { + var list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; + list.forEach(function (definition) { + var resolved = resolveVariantFromProps(props, definition); + if (!resolved) return; + var transitionEnd = resolved.transitionEnd; + resolved.transition; + var target = tslib.__rest(resolved, ["transitionEnd", "transition"]); + for (var key in target) { + var valueTarget = target[key]; + if (Array.isArray(valueTarget)) { /** - * When `present` changes to `false`, we check changes to animation-name to - * determine whether an animation has started. We chose this approach (reading - * computed styles) because there is no `animationrun` event and `animationstart` - * fires after `animation-delay` has expired which would be too late. - */ - const isAnimating = prevAnimationName !== currentAnimationName; - if (wasPresent && isAnimating) send('ANIMATION_OUT');else send('UNMOUNT'); - } - prevPresentRef.current = present; - } - }, [present, send]); - $fnLeV$radixuireactuselayouteffect.useLayoutEffect(() => { - if (node1) { - /** - * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel` - * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we - * make sure we only trigger ANIMATION_END for the currently active animation. - */ - const handleAnimationEnd = event => { - const currentAnimationName = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - const isCurrentAnimation = currentAnimationName.includes(event.animationName); - if (event.target === node1 && isCurrentAnimation) - // With React 18 concurrency this update is applied - // a frame after the animation ends, creating a flash of visible content. - // By manually flushing we ensure they sync within a frame, removing the flash. - $fnLeV$reactdom.flushSync(() => send('ANIMATION_END')); - }; - const handleAnimationStart = event => { - if (event.target === node1) - // if animation occurred, store its name as the previous animation. - prevAnimationNameRef.current = $a2fa0214bb2735a1$var$getAnimationName(stylesRef.current); - }; - node1.addEventListener('animationstart', handleAnimationStart); - node1.addEventListener('animationcancel', handleAnimationEnd); - node1.addEventListener('animationend', handleAnimationEnd); - return () => { - node1.removeEventListener('animationstart', handleAnimationStart); - node1.removeEventListener('animationcancel', handleAnimationEnd); - node1.removeEventListener('animationend', handleAnimationEnd); + * Take final keyframe if the initial animation is blocked because + * we want to initialise at the end of that blocked animation. + */ + var index = initialAnimationIsBlocked ? valueTarget.length - 1 : 0; + valueTarget = valueTarget[index]; + } + if (valueTarget !== null) { + values[key] = valueTarget; + } + } + for (var key in transitionEnd) values[key] = transitionEnd[key]; + }); + } + return values; +} +var svgMotionConfig = { + useVisualState: makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, + createRenderState: createSvgRenderState, + onMount: function (props, instance, _a) { + var renderState = _a.renderState, + latestValues = _a.latestValues; + try { + renderState.dimensions = typeof instance.getBBox === "function" ? instance.getBBox() : instance.getBoundingClientRect(); + } catch (e) { + // Most likely trying to measure an unrendered element under Firefox + renderState.dimensions = { + x: 0, + y: 0, + width: 0, + height: 0 }; - } else - // Transition to the unmounted state if the node is removed prematurely. - // We avoid doing so during cleanup as the node may change but still exist. - send('ANIMATION_END'); - }, [node1, send]); - return { - isPresent: ['mounted', 'unmountSuspended'].includes(state), - ref: $fnLeV$react.useCallback(node => { - if (node) stylesRef.current = getComputedStyle(node); - setNode(node); - }, []) + } + buildSVGAttrs(renderState, latestValues, { + enableHardwareAcceleration: false + }, props.transformTemplate); + renderSVG(instance, renderState); + } + }) +}; +var htmlMotionConfig = { + useVisualState: makeUseVisualState({ + scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, + createRenderState: createHtmlRenderState + }) +}; +function createDomMotionConfig(Component, _a, preloadedFeatures, createVisualElement, projectionNodeConstructor) { + var _b = _a.forwardMotionProps, + forwardMotionProps = _b === void 0 ? false : _b; + var baseConfig = isSVGComponent(Component) ? svgMotionConfig : htmlMotionConfig; + return tslib.__assign(tslib.__assign({}, baseConfig), { + preloadedFeatures: preloadedFeatures, + useRender: createUseRender(forwardMotionProps), + createVisualElement: createVisualElement, + projectionNodeConstructor: projectionNodeConstructor, + Component: Component + }); +} +exports.AnimationType = void 0; +(function (AnimationType) { + AnimationType["Animate"] = "animate"; + AnimationType["Hover"] = "whileHover"; + AnimationType["Tap"] = "whileTap"; + AnimationType["Drag"] = "whileDrag"; + AnimationType["Focus"] = "whileFocus"; + AnimationType["InView"] = "whileInView"; + AnimationType["Exit"] = "exit"; +})(exports.AnimationType || (exports.AnimationType = {})); +function addDomEvent(target, eventName, handler, options) { + if (options === void 0) { + options = { + passive: true }; } - /* -----------------------------------------------------------------------------------------------*/ - function $a2fa0214bb2735a1$var$getAnimationName(styles) { - return (styles === null || styles === void 0 ? void 0 : styles.animationName) || 'none'; + target.addEventListener(eventName, handler, options); + return function () { + return target.removeEventListener(eventName, handler); + }; +} +/** + * Attaches an event listener directly to the provided DOM element. + * + * Bypassing React's event system can be desirable, for instance when attaching non-passive + * event handlers. + * + * ```jsx + * const ref = useRef(null) + * + * useDomEvent(ref, 'wheel', onWheel, { passive: false }) + * + * return
    + * ``` + * + * @param ref - React.RefObject that's been provided to the element you want to bind the listener to. + * @param eventName - Name of the event you want listen for. + * @param handler - Function to fire when receiving the event. + * @param options - Options to pass to `Event.addEventListener`. + * + * @public + */ +function useDomEvent(ref, eventName, handler, options) { + React.useEffect(function () { + var element = ref.current; + if (handler && element) { + return addDomEvent(element, eventName, handler, options); + } + }, [ref, eventName, handler, options]); +} + +/** + * + * @param props + * @param ref + * @internal + */ +function useFocusGesture(_a) { + var whileFocus = _a.whileFocus, + visualElement = _a.visualElement; + var onFocus = function () { + var _a; + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Focus, true); + }; + var onBlur = function () { + var _a; + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Focus, false); + }; + useDomEvent(visualElement, "focus", whileFocus ? onFocus : undefined); + useDomEvent(visualElement, "blur", whileFocus ? onBlur : undefined); +} +function isMouseEvent(event) { + // PointerEvent inherits from MouseEvent so we can't use a straight instanceof check. + if (typeof PointerEvent !== "undefined" && event instanceof PointerEvent) { + return !!(event.pointerType === "mouse"); + } + return event instanceof MouseEvent; +} +function isTouchEvent(event) { + var hasTouches = !!event.touches; + return hasTouches; +} + +/** + * Filters out events not attached to the primary pointer (currently left mouse button) + * @param eventHandler + */ +function filterPrimaryPointer(eventHandler) { + return function (event) { + var isMouseEvent = event instanceof MouseEvent; + var isPrimaryPointer = !isMouseEvent || isMouseEvent && event.button === 0; + if (isPrimaryPointer) { + eventHandler(event); + } + }; +} +var defaultPagePoint = { + pageX: 0, + pageY: 0 +}; +function pointFromTouch(e, pointType) { + if (pointType === void 0) { + pointType = "page"; + } + var primaryTouch = e.touches[0] || e.changedTouches[0]; + var point = primaryTouch || defaultPagePoint; + return { + x: point[pointType + "X"], + y: point[pointType + "Y"] + }; +} +function pointFromMouse(point, pointType) { + if (pointType === void 0) { + pointType = "page"; + } + return { + x: point[pointType + "X"], + y: point[pointType + "Y"] + }; +} +function extractEventInfo(event, pointType) { + if (pointType === void 0) { + pointType = "page"; } - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-primitive/dist/index.js": - /*!*********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-primitive/dist/index.js ***! - \*********************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $iMixA$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); - var $iMixA$react = __webpack_require__(/*! react */ "react"); - var $iMixA$reactdom = __webpack_require__(/*! react-dom */ "react-dom"); - var $iMixA$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); + return { + point: isTouchEvent(event) ? pointFromTouch(event, pointType) : pointFromMouse(event, pointType) + }; +} +var wrapHandler = function (handler, shouldFilterPrimaryPointer) { + if (shouldFilterPrimaryPointer === void 0) { + shouldFilterPrimaryPointer = false; } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export(module.exports, "Primitive", () => $c3def6332c2749a6$export$250ffa63cdc0d034); - $parcel$export(module.exports, "Root", () => $c3def6332c2749a6$export$be92b6f5f03c0fe9); - $parcel$export(module.exports, "dispatchDiscreteCustomEvent", () => $c3def6332c2749a6$export$6d1a0317bde7de7f); - const $c3def6332c2749a6$var$NODES = ['a', 'button', 'div', 'form', 'h2', 'h3', 'img', 'input', 'label', 'li', 'nav', 'ol', 'p', 'span', 'svg', 'ul']; // Temporary while we await merge of this fix: - // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/55396 - // prettier-ignore - /* ------------------------------------------------------------------------------------------------- - * Primitive - * -----------------------------------------------------------------------------------------------*/ - const $c3def6332c2749a6$export$250ffa63cdc0d034 = $c3def6332c2749a6$var$NODES.reduce((primitive, node) => { - const Node = /*#__PURE__*/$iMixA$react.forwardRef((props, forwardedRef) => { - const { - asChild: asChild, - ...primitiveProps - } = props; - const Comp = asChild ? $iMixA$radixuireactslot.Slot : node; - $iMixA$react.useEffect(() => { - window[Symbol.for('radix-ui')] = true; - }, []); - return /*#__PURE__*/$iMixA$react.createElement(Comp, $parcel$interopDefault($iMixA$babelruntimehelpersextends)({}, primitiveProps, { - ref: forwardedRef - })); - }); - Node.displayName = `Primitive.${node}`; - return { - ...primitive, - [node]: Node + var listener = function (event) { + return handler(event, extractEventInfo(event)); + }; + return shouldFilterPrimaryPointer ? filterPrimaryPointer(listener) : listener; +}; + +// We check for event support via functions in case they've been mocked by a testing suite. +var supportsPointerEvents = function () { + return isBrowser && window.onpointerdown === null; +}; +var supportsTouchEvents = function () { + return isBrowser && window.ontouchstart === null; +}; +var supportsMouseEvents = function () { + return isBrowser && window.onmousedown === null; +}; +var mouseEventNames = { + pointerdown: "mousedown", + pointermove: "mousemove", + pointerup: "mouseup", + pointercancel: "mousecancel", + pointerover: "mouseover", + pointerout: "mouseout", + pointerenter: "mouseenter", + pointerleave: "mouseleave" +}; +var touchEventNames = { + pointerdown: "touchstart", + pointermove: "touchmove", + pointerup: "touchend", + pointercancel: "touchcancel" +}; +function getPointerEventName(name) { + if (supportsPointerEvents()) { + return name; + } else if (supportsTouchEvents()) { + return touchEventNames[name]; + } else if (supportsMouseEvents()) { + return mouseEventNames[name]; + } + return name; +} +function addPointerEvent(target, eventName, handler, options) { + return addDomEvent(target, getPointerEventName(eventName), wrapHandler(handler, eventName === "pointerdown"), options); +} +function usePointerEvent(ref, eventName, handler, options) { + return useDomEvent(ref, getPointerEventName(eventName), handler && wrapHandler(handler, eventName === "pointerdown"), options); +} +function createLock(name) { + var lock = null; + return function () { + var openLock = function () { + lock = null; }; - }, {}); - /* ------------------------------------------------------------------------------------------------- - * Utils - * -----------------------------------------------------------------------------------------------*/ /** - * Flush custom event dispatch - * https://github.com/radix-ui/primitives/pull/1378 - * - * React batches *all* event handlers since version 18, this introduces certain considerations when using custom event types. - * - * Internally, React prioritises events in the following order: - * - discrete - * - continuous - * - default - * - * https://github.com/facebook/react/blob/a8a4742f1c54493df00da648a3f9d26e3db9c8b5/packages/react-dom/src/events/ReactDOMEventListener.js#L294-L350 - * - * `discrete` is an important distinction as updates within these events are applied immediately. - * React however, is not able to infer the priority of custom event types due to how they are detected internally. - * Because of this, it's possible for updates from custom events to be unexpectedly batched when - * dispatched by another `discrete` event. - * - * In order to ensure that updates from custom events are applied predictably, we need to manually flush the batch. - * This utility should be used when dispatching a custom event from within another `discrete` event, this utility - * is not nessesary when dispatching known event types, or if dispatching a custom type inside a non-discrete event. - * For example: - * - * dispatching a known click 👎 - * target.dispatchEvent(new Event(‘click’)) - * - * dispatching a custom type within a non-discrete event 👎 - * onScroll={(event) => event.target.dispatchEvent(new CustomEvent(‘customType’))} - * - * dispatching a custom type within a `discrete` event 👍 - * onPointerDown={(event) => dispatchDiscreteCustomEvent(event.target, new CustomEvent(‘customType’))} - * - * Note: though React classifies `focus`, `focusin` and `focusout` events as `discrete`, it's not recommended to use - * this utility with them. This is because it's possible for those handlers to be called implicitly during render - * e.g. when focus is within a component as it is unmounted, or when managing focus on mount. - */ - function $c3def6332c2749a6$export$6d1a0317bde7de7f(target, event) { - if (target) $iMixA$reactdom.flushSync(() => target.dispatchEvent(event)); - } - /* -----------------------------------------------------------------------------------------------*/ - const $c3def6332c2749a6$export$be92b6f5f03c0fe9 = $c3def6332c2749a6$export$250ffa63cdc0d034; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-roving-focus/dist/index.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-roving-focus/dist/index.js ***! - \************************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $9QJ9Y$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); - var $9QJ9Y$react = __webpack_require__(/*! react */ "react"); - var $9QJ9Y$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); - var $9QJ9Y$radixuireactcollection = __webpack_require__(/*! @radix-ui/react-collection */ "../../../node_modules/@radix-ui/react-collection/dist/index.js"); - var $9QJ9Y$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); - var $9QJ9Y$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); - var $9QJ9Y$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); - var $9QJ9Y$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); - var $9QJ9Y$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); - var $9QJ9Y$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); - var $9QJ9Y$radixuireactdirection = __webpack_require__(/*! @radix-ui/react-direction */ "../../../node_modules/@radix-ui/react-direction/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export(module.exports, "createRovingFocusGroupScope", () => $0063afae63b3fa70$export$c7109489551a4f4); - $parcel$export(module.exports, "RovingFocusGroup", () => $0063afae63b3fa70$export$8699f7c8af148338); - $parcel$export(module.exports, "RovingFocusGroupItem", () => $0063afae63b3fa70$export$ab9df7c53fe8454); - $parcel$export(module.exports, "Root", () => $0063afae63b3fa70$export$be92b6f5f03c0fe9); - $parcel$export(module.exports, "Item", () => $0063afae63b3fa70$export$6d08773d2e66f8f2); - const $0063afae63b3fa70$var$ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus'; - const $0063afae63b3fa70$var$EVENT_OPTIONS = { - bubbles: false, - cancelable: true + if (lock === null) { + lock = name; + return openLock; + } + return false; }; - /* ------------------------------------------------------------------------------------------------- - * RovingFocusGroup - * -----------------------------------------------------------------------------------------------*/ - const $0063afae63b3fa70$var$GROUP_NAME = 'RovingFocusGroup'; - const [$0063afae63b3fa70$var$Collection, $0063afae63b3fa70$var$useCollection, $0063afae63b3fa70$var$createCollectionScope] = $9QJ9Y$radixuireactcollection.createCollection($0063afae63b3fa70$var$GROUP_NAME); - const [$0063afae63b3fa70$var$createRovingFocusGroupContext, $0063afae63b3fa70$export$c7109489551a4f4] = $9QJ9Y$radixuireactcontext.createContextScope($0063afae63b3fa70$var$GROUP_NAME, [$0063afae63b3fa70$var$createCollectionScope]); - const [$0063afae63b3fa70$var$RovingFocusProvider, $0063afae63b3fa70$var$useRovingFocusContext] = $0063afae63b3fa70$var$createRovingFocusGroupContext($0063afae63b3fa70$var$GROUP_NAME); - const $0063afae63b3fa70$export$8699f7c8af148338 = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.Provider, { - scope: props.__scopeRovingFocusGroup - }, /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.Slot, { - scope: props.__scopeRovingFocusGroup - }, /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$RovingFocusGroupImpl, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({}, props, { - ref: forwardedRef - })))); - }); - /*#__PURE__*/ - Object.assign($0063afae63b3fa70$export$8699f7c8af148338, { - displayName: $0063afae63b3fa70$var$GROUP_NAME - }); - /* -----------------------------------------------------------------------------------------------*/ - const $0063afae63b3fa70$var$RovingFocusGroupImpl = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - orientation: orientation, - loop = false, - dir: dir, - currentTabStopId: currentTabStopIdProp, - defaultCurrentTabStopId: defaultCurrentTabStopId, - onCurrentTabStopIdChange: onCurrentTabStopIdChange, - onEntryFocus: onEntryFocus, - ...groupProps - } = props; - const ref = $9QJ9Y$react.useRef(null); - const composedRefs = $9QJ9Y$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const direction = $9QJ9Y$radixuireactdirection.useDirection(dir); - const [currentTabStopId = null, setCurrentTabStopId] = $9QJ9Y$radixuireactusecontrollablestate.useControllableState({ - prop: currentTabStopIdProp, - defaultProp: defaultCurrentTabStopId, - onChange: onCurrentTabStopIdChange - }); - const [isTabbingBackOut, setIsTabbingBackOut] = $9QJ9Y$react.useState(false); - const handleEntryFocus = $9QJ9Y$radixuireactusecallbackref.useCallbackRef(onEntryFocus); - const getItems = $0063afae63b3fa70$var$useCollection(__scopeRovingFocusGroup); - const isClickFocusRef = $9QJ9Y$react.useRef(false); - const [focusableItemsCount, setFocusableItemsCount] = $9QJ9Y$react.useState(0); - $9QJ9Y$react.useEffect(() => { - const node = ref.current; - if (node) { - node.addEventListener($0063afae63b3fa70$var$ENTRY_FOCUS, handleEntryFocus); - return () => node.removeEventListener($0063afae63b3fa70$var$ENTRY_FOCUS, handleEntryFocus); - } - }, [handleEntryFocus]); - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$RovingFocusProvider, { - scope: __scopeRovingFocusGroup, - orientation: orientation, - dir: direction, - loop: loop, - currentTabStopId: currentTabStopId, - onItemFocus: $9QJ9Y$react.useCallback(tabStopId => setCurrentTabStopId(tabStopId), [setCurrentTabStopId]), - onItemShiftTab: $9QJ9Y$react.useCallback(() => setIsTabbingBackOut(true), []), - onFocusableItemAdd: $9QJ9Y$react.useCallback(() => setFocusableItemsCount(prevCount => prevCount + 1), []), - onFocusableItemRemove: $9QJ9Y$react.useCallback(() => setFocusableItemsCount(prevCount => prevCount - 1), []) - }, /*#__PURE__*/$9QJ9Y$react.createElement($9QJ9Y$radixuireactprimitive.Primitive.div, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({ - tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0, - "data-orientation": orientation - }, groupProps, { - ref: composedRefs, - style: { - outline: 'none', - ...props.style - }, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onMouseDown, () => { - isClickFocusRef.current = true; - }), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onFocus, event => { - // We normally wouldn't need this check, because we already check - // that the focus is on the current target and not bubbling to it. - // We do this because Safari doesn't focus buttons when clicked, and - // instead, the wrapper will get focused and not through a bubbling event. - const isKeyboardFocus = !isClickFocusRef.current; - if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) { - const entryFocusEvent = new CustomEvent($0063afae63b3fa70$var$ENTRY_FOCUS, $0063afae63b3fa70$var$EVENT_OPTIONS); - event.currentTarget.dispatchEvent(entryFocusEvent); - if (!entryFocusEvent.defaultPrevented) { - const items = getItems().filter(item => item.focusable); - const activeItem = items.find(item => item.active); - const currentItem = items.find(item => item.id === currentTabStopId); - const candidateItems = [activeItem, currentItem, ...items].filter(Boolean); - const candidateNodes = candidateItems.map(item => item.ref.current); - $0063afae63b3fa70$var$focusFirst(candidateNodes); - } - } - isClickFocusRef.current = false; - }), - onBlur: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onBlur, () => setIsTabbingBackOut(false)) - }))); - }); - /* ------------------------------------------------------------------------------------------------- - * RovingFocusGroupItem - * -----------------------------------------------------------------------------------------------*/ - const $0063afae63b3fa70$var$ITEM_NAME = 'RovingFocusGroupItem'; - const $0063afae63b3fa70$export$ab9df7c53fe8454 = /*#__PURE__*/$9QJ9Y$react.forwardRef((props, forwardedRef) => { - const { - __scopeRovingFocusGroup: __scopeRovingFocusGroup, - focusable = true, - active = false, - tabStopId: tabStopId, - ...itemProps - } = props; - const autoId = $9QJ9Y$radixuireactid.useId(); - const id = tabStopId || autoId; - const context = $0063afae63b3fa70$var$useRovingFocusContext($0063afae63b3fa70$var$ITEM_NAME, __scopeRovingFocusGroup); - const isCurrentTabStop = context.currentTabStopId === id; - const getItems = $0063afae63b3fa70$var$useCollection(__scopeRovingFocusGroup); - const { - onFocusableItemAdd: onFocusableItemAdd, - onFocusableItemRemove: onFocusableItemRemove - } = context; - $9QJ9Y$react.useEffect(() => { - if (focusable) { - onFocusableItemAdd(); - return () => onFocusableItemRemove(); - } - }, [focusable, onFocusableItemAdd, onFocusableItemRemove]); - return /*#__PURE__*/$9QJ9Y$react.createElement($0063afae63b3fa70$var$Collection.ItemSlot, { - scope: __scopeRovingFocusGroup, - id: id, - focusable: focusable, - active: active - }, /*#__PURE__*/$9QJ9Y$react.createElement($9QJ9Y$radixuireactprimitive.Primitive.span, $parcel$interopDefault($9QJ9Y$babelruntimehelpersextends)({ - tabIndex: isCurrentTabStop ? 0 : -1, - "data-orientation": context.orientation - }, itemProps, { - ref: forwardedRef, - onMouseDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onMouseDown, event => { - // We prevent focusing non-focusable items on `mousedown`. - // Even though the item has tabIndex={-1}, that only means take it out of the tab order. - if (!focusable) event.preventDefault(); // Safari doesn't focus a button when clicked so we run our logic on mousedown also - else context.onItemFocus(id); - }), - onFocus: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onFocus, () => context.onItemFocus(id)), - onKeyDown: $9QJ9Y$radixuiprimitive.composeEventHandlers(props.onKeyDown, event => { - if (event.key === 'Tab' && event.shiftKey) { - context.onItemShiftTab(); - return; - } - if (event.target !== event.currentTarget) return; - const focusIntent = $0063afae63b3fa70$var$getFocusIntent(event, context.orientation, context.dir); - if (focusIntent !== undefined) { - event.preventDefault(); - const items = getItems().filter(item => item.focusable); - let candidateNodes = items.map(item => item.ref.current); - if (focusIntent === 'last') candidateNodes.reverse();else if (focusIntent === 'prev' || focusIntent === 'next') { - if (focusIntent === 'prev') candidateNodes.reverse(); - const currentIndex = candidateNodes.indexOf(event.currentTarget); - candidateNodes = context.loop ? $0063afae63b3fa70$var$wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1); - } - /** - * Imperative focus during keydown is risky so we prevent React's batching updates - * to avoid potential bugs. See: https://github.com/facebook/react/issues/20332 - */ - setTimeout(() => $0063afae63b3fa70$var$focusFirst(candidateNodes)); - } - }) - }))); +} +var globalHorizontalLock = createLock("dragHorizontal"); +var globalVerticalLock = createLock("dragVertical"); +function getGlobalLock(drag) { + var lock = false; + if (drag === "y") { + lock = globalVerticalLock(); + } else if (drag === "x") { + lock = globalHorizontalLock(); + } else { + var openHorizontal_1 = globalHorizontalLock(); + var openVertical_1 = globalVerticalLock(); + if (openHorizontal_1 && openVertical_1) { + lock = function () { + openHorizontal_1(); + openVertical_1(); + }; + } else { + // Release the locks because we don't use them + if (openHorizontal_1) openHorizontal_1(); + if (openVertical_1) openVertical_1(); + } + } + return lock; +} +function isDragActive() { + // Check the gesture lock - if we get it, it means no drag gesture is active + // and we can safely fire the tap gesture. + var openGestureLock = getGlobalLock(true); + if (!openGestureLock) return true; + openGestureLock(); + return false; +} +function createHoverEvent(visualElement, isActive, callback) { + return function (event, info) { + var _a; + if (!isMouseEvent(event) || isDragActive()) return; + /** + * Ensure we trigger animations before firing event callback + */ + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Hover, isActive); + callback === null || callback === void 0 ? void 0 : callback(event, info); + }; +} +function useHoverGesture(_a) { + var onHoverStart = _a.onHoverStart, + onHoverEnd = _a.onHoverEnd, + whileHover = _a.whileHover, + visualElement = _a.visualElement; + usePointerEvent(visualElement, "pointerenter", onHoverStart || whileHover ? createHoverEvent(visualElement, true, onHoverStart) : undefined, { + passive: !onHoverStart }); - /*#__PURE__*/ - Object.assign($0063afae63b3fa70$export$ab9df7c53fe8454, { - displayName: $0063afae63b3fa70$var$ITEM_NAME + usePointerEvent(visualElement, "pointerleave", onHoverEnd || whileHover ? createHoverEvent(visualElement, false, onHoverEnd) : undefined, { + passive: !onHoverEnd }); - /* -----------------------------------------------------------------------------------------------*/ // prettier-ignore - const $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT = { - ArrowLeft: 'prev', - ArrowUp: 'prev', - ArrowRight: 'next', - ArrowDown: 'next', - PageUp: 'first', - Home: 'first', - PageDown: 'last', - End: 'last' - }; - function $0063afae63b3fa70$var$getDirectionAwareKey(key, dir) { - if (dir !== 'rtl') return key; - return key === 'ArrowLeft' ? 'ArrowRight' : key === 'ArrowRight' ? 'ArrowLeft' : key; +} + +/** + * Recursively traverse up the tree to check whether the provided child node + * is the parent or a descendant of it. + * + * @param parent - Element to find + * @param child - Element to test against parent + */ +var isNodeOrChild = function (parent, child) { + if (!child) { + return false; + } else if (parent === child) { + return true; + } else { + return isNodeOrChild(parent, child.parentElement); } - function $0063afae63b3fa70$var$getFocusIntent(event, orientation, dir) { - const key = $0063afae63b3fa70$var$getDirectionAwareKey(event.key, dir); - if (orientation === 'vertical' && ['ArrowLeft', 'ArrowRight'].includes(key)) return undefined; - if (orientation === 'horizontal' && ['ArrowUp', 'ArrowDown'].includes(key)) return undefined; - return $0063afae63b3fa70$var$MAP_KEY_TO_FOCUS_INTENT[key]; +}; +function useUnmountEffect(callback) { + return React.useEffect(function () { + return function () { + return callback(); + }; + }, []); +} + +/** + * @param handlers - + * @internal + */ +function useTapGesture(_a) { + var onTap = _a.onTap, + onTapStart = _a.onTapStart, + onTapCancel = _a.onTapCancel, + whileTap = _a.whileTap, + visualElement = _a.visualElement; + var hasPressListeners = onTap || onTapStart || onTapCancel || whileTap; + var isPressing = React.useRef(false); + var cancelPointerEndListeners = React.useRef(null); + /** + * Only set listener to passive if there are no external listeners. + */ + var eventOptions = { + passive: !(onTapStart || onTap || onTapCancel || onPointerDown) + }; + function removePointerEndListener() { + var _a; + (_a = cancelPointerEndListeners.current) === null || _a === void 0 ? void 0 : _a.call(cancelPointerEndListeners); + cancelPointerEndListeners.current = null; } - function $0063afae63b3fa70$var$focusFirst(candidates) { - const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement; - for (const candidate of candidates) { - // if focus is already where we want to go, we don't want to keep going through the candidates - if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return; - candidate.focus(); - if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return; - } + function checkPointerEnd() { + var _a; + removePointerEndListener(); + isPressing.current = false; + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Tap, false); + return !isDragActive(); } - /** - * Wraps an array around itself at a given start index - * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']` - */ - function $0063afae63b3fa70$var$wrapArray(array, startIndex) { - return array.map((_, index) => array[(startIndex + index) % array.length]); + function onPointerUp(event, info) { + if (!checkPointerEnd()) return; + /** + * We only count this as a tap gesture if the event.target is the same + * as, or a child of, this component's element + */ + !isNodeOrChild(visualElement.getInstance(), event.target) ? onTapCancel === null || onTapCancel === void 0 ? void 0 : onTapCancel(event, info) : onTap === null || onTap === void 0 ? void 0 : onTap(event, info); } - const $0063afae63b3fa70$export$be92b6f5f03c0fe9 = $0063afae63b3fa70$export$8699f7c8af148338; - const $0063afae63b3fa70$export$6d08773d2e66f8f2 = $0063afae63b3fa70$export$ab9df7c53fe8454; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-slot/dist/index.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-slot/dist/index.js ***! - \****************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $dAvBt$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); - var $dAvBt$react = __webpack_require__(/*! react */ "react"); - var $dAvBt$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); + function onPointerCancel(event, info) { + if (!checkPointerEnd()) return; + onTapCancel === null || onTapCancel === void 0 ? void 0 : onTapCancel(event, info); } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; + function onPointerDown(event, info) { + var _a; + removePointerEndListener(); + if (isPressing.current) return; + isPressing.current = true; + cancelPointerEndListeners.current = popmotion.pipe(addPointerEvent(window, "pointerup", onPointerUp, eventOptions), addPointerEvent(window, "pointercancel", onPointerCancel, eventOptions)); + /** + * Ensure we trigger animations before firing event callback + */ + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Tap, true); + onTapStart === null || onTapStart === void 0 ? void 0 : onTapStart(event, info); + } + usePointerEvent(visualElement, "pointerdown", hasPressListeners ? onPointerDown : undefined, eventOptions); + useUnmountEffect(removePointerEndListener); +} +var warned = new Set(); +function warnOnce(condition, message, element) { + if (condition || warned.has(message)) return; + console.warn(message); + if (element) console.warn(element); + warned.add(message); +} + +/** + * Map an IntersectionHandler callback to an element. We only ever make one handler for one + * element, so even though these handlers might all be triggered by different + * observers, we can keep them in the same map. + */ +var observerCallbacks = new WeakMap(); +/** + * Multiple observers can be created for multiple element/document roots. Each with + * different settings. So here we store dictionaries of observers to each root, + * using serialised settings (threshold/margin) as lookup keys. + */ +var observers = new WeakMap(); +var fireObserverCallback = function (entry) { + var _a; + (_a = observerCallbacks.get(entry.target)) === null || _a === void 0 ? void 0 : _a(entry); +}; +var fireAllObserverCallbacks = function (entries) { + entries.forEach(fireObserverCallback); +}; +function initIntersectionObserver(_a) { + var root = _a.root, + options = tslib.__rest(_a, ["root"]); + var lookupRoot = root || document; + /** + * If we don't have an observer lookup map for this root, create one. + */ + if (!observers.has(lookupRoot)) { + observers.set(lookupRoot, {}); + } + var rootObservers = observers.get(lookupRoot); + var key = JSON.stringify(options); + /** + * If we don't have an observer for this combination of root and settings, + * create one. + */ + if (!rootObservers[key]) { + rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, tslib.__assign({ + root: root + }, options)); } - $parcel$export(module.exports, "Slot", () => $82dc8d030dec7549$export$8c6ed5c666ac1360); - $parcel$export(module.exports, "Slottable", () => $82dc8d030dec7549$export$d9f1ccf0bdb05d45); - $parcel$export(module.exports, "Root", () => $82dc8d030dec7549$export$be92b6f5f03c0fe9); - - /* ------------------------------------------------------------------------------------------------- - * Slot - * -----------------------------------------------------------------------------------------------*/ - const $82dc8d030dec7549$export$8c6ed5c666ac1360 = /*#__PURE__*/$dAvBt$react.forwardRef((props, forwardedRef) => { - const { - children: children, - ...slotProps - } = props; - const childrenArray = $dAvBt$react.Children.toArray(children); - const slottable = childrenArray.find($82dc8d030dec7549$var$isSlottable); - if (slottable) { - // the new element to render is the one passed as a child of `Slottable` - const newElement = slottable.props.children; - const newChildren = childrenArray.map(child => { - if (child === slottable) { - // because the new element will be the one rendered, we are only interested - // in grabbing its children (`newElement.props.children`) - if ($dAvBt$react.Children.count(newElement) > 1) return $dAvBt$react.Children.only(null); - return /*#__PURE__*/$dAvBt$react.isValidElement(newElement) ? newElement.props.children : null; - } else return child; - }); - return /*#__PURE__*/$dAvBt$react.createElement($82dc8d030dec7549$var$SlotClone, $parcel$interopDefault($dAvBt$babelruntimehelpersextends)({}, slotProps, { - ref: forwardedRef - }), /*#__PURE__*/$dAvBt$react.isValidElement(newElement) ? /*#__PURE__*/$dAvBt$react.cloneElement(newElement, undefined, newChildren) : null); - } - return /*#__PURE__*/$dAvBt$react.createElement($82dc8d030dec7549$var$SlotClone, $parcel$interopDefault($dAvBt$babelruntimehelpersextends)({}, slotProps, { - ref: forwardedRef - }), children); - }); - $82dc8d030dec7549$export$8c6ed5c666ac1360.displayName = 'Slot'; - /* ------------------------------------------------------------------------------------------------- - * SlotClone - * -----------------------------------------------------------------------------------------------*/ - const $82dc8d030dec7549$var$SlotClone = /*#__PURE__*/$dAvBt$react.forwardRef((props, forwardedRef) => { - const { - children: children, - ...slotProps - } = props; - if ( /*#__PURE__*/$dAvBt$react.isValidElement(children)) return /*#__PURE__*/$dAvBt$react.cloneElement(children, { - ...$82dc8d030dec7549$var$mergeProps(slotProps, children.props), - ref: forwardedRef ? $dAvBt$radixuireactcomposerefs.composeRefs(forwardedRef, children.ref) : children.ref - }); - return $dAvBt$react.Children.count(children) > 1 ? $dAvBt$react.Children.only(null) : null; - }); - $82dc8d030dec7549$var$SlotClone.displayName = 'SlotClone'; - /* ------------------------------------------------------------------------------------------------- - * Slottable - * -----------------------------------------------------------------------------------------------*/ - const $82dc8d030dec7549$export$d9f1ccf0bdb05d45 = ({ - children: children - }) => { - return /*#__PURE__*/$dAvBt$react.createElement($dAvBt$react.Fragment, null, children); + return rootObservers[key]; +} +function observeIntersection(element, options, callback) { + var rootInteresectionObserver = initIntersectionObserver(options); + observerCallbacks.set(element, callback); + rootInteresectionObserver.observe(element); + return function () { + observerCallbacks.delete(element); + rootInteresectionObserver.unobserve(element); }; - /* ---------------------------------------------------------------------------------------------- */ - function $82dc8d030dec7549$var$isSlottable(child) { - return /*#__PURE__*/$dAvBt$react.isValidElement(child) && child.type === $82dc8d030dec7549$export$d9f1ccf0bdb05d45; - } - function $82dc8d030dec7549$var$mergeProps(slotProps, childProps) { - // all child props should override - const overrideProps = { - ...childProps +} +function useViewport(_a) { + var visualElement = _a.visualElement, + whileInView = _a.whileInView, + onViewportEnter = _a.onViewportEnter, + onViewportLeave = _a.onViewportLeave, + _b = _a.viewport, + viewport = _b === void 0 ? {} : _b; + var state = React.useRef({ + hasEnteredView: false, + isInView: false + }); + var shouldObserve = Boolean(whileInView || onViewportEnter || onViewportLeave); + if (viewport.once && state.current.hasEnteredView) shouldObserve = false; + var useObserver = typeof IntersectionObserver === "undefined" ? useMissingIntersectionObserver : useIntersectionObserver; + useObserver(shouldObserve, state.current, visualElement, viewport); +} +var thresholdNames = { + some: 0, + all: 1 +}; +function useIntersectionObserver(shouldObserve, state, visualElement, _a) { + var root = _a.root, + rootMargin = _a.margin, + _b = _a.amount, + amount = _b === void 0 ? "some" : _b, + once = _a.once; + React.useEffect(function () { + if (!shouldObserve) return; + var options = { + root: root === null || root === void 0 ? void 0 : root.current, + rootMargin: rootMargin, + threshold: typeof amount === "number" ? amount : thresholdNames[amount] }; - for (const propName in childProps) { - const slotPropValue = slotProps[propName]; - const childPropValue = childProps[propName]; - const isHandler = /^on[A-Z]/.test(propName); - if (isHandler) { - // if the handler exists on both, we compose them - if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => { - childPropValue(...args); - slotPropValue(...args); - };else if (slotPropValue) overrideProps[propName] = slotPropValue; - } else if (propName === 'style') overrideProps[propName] = { - ...slotPropValue, - ...childPropValue - };else if (propName === 'className') overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(' '); - } - return { - ...slotProps, - ...overrideProps + var intersectionCallback = function (entry) { + var _a; + var isIntersecting = entry.isIntersecting; + /** + * If there's been no change in the viewport state, early return. + */ + if (state.isInView === isIntersecting) return; + state.isInView = isIntersecting; + /** + * Handle hasEnteredView. If this is only meant to run once, and + * element isn't visible, early return. Otherwise set hasEnteredView to true. + */ + if (once && !isIntersecting && state.hasEnteredView) { + return; + } else if (isIntersecting) { + state.hasEnteredView = true; + } + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.InView, isIntersecting); + /** + * Use the latest committed props rather than the ones in scope + * when this observer is created + */ + var props = visualElement.getProps(); + var callback = isIntersecting ? props.onViewportEnter : props.onViewportLeave; + callback === null || callback === void 0 ? void 0 : callback(entry); }; - } - const $82dc8d030dec7549$export$be92b6f5f03c0fe9 = $82dc8d030dec7549$export$8c6ed5c666ac1360; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-tooltip/dist/index.js ***! - \*******************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $iVrL9$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); - var $iVrL9$react = __webpack_require__(/*! react */ "react"); - var $iVrL9$radixuiprimitive = __webpack_require__(/*! @radix-ui/primitive */ "../../../node_modules/@radix-ui/primitive/dist/index.js"); - var $iVrL9$radixuireactcomposerefs = __webpack_require__(/*! @radix-ui/react-compose-refs */ "../../../node_modules/@radix-ui/react-compose-refs/dist/index.js"); - var $iVrL9$radixuireactcontext = __webpack_require__(/*! @radix-ui/react-context */ "../../../node_modules/@radix-ui/react-context/dist/index.js"); - var $iVrL9$radixuireactdismissablelayer = __webpack_require__(/*! @radix-ui/react-dismissable-layer */ "../../../node_modules/@radix-ui/react-dismissable-layer/dist/index.js"); - var $iVrL9$radixuireactid = __webpack_require__(/*! @radix-ui/react-id */ "../../../node_modules/@radix-ui/react-id/dist/index.js"); - var $iVrL9$radixuireactpopper = __webpack_require__(/*! @radix-ui/react-popper */ "../../../node_modules/@radix-ui/react-popper/dist/index.js"); - var $iVrL9$radixuireactportal = __webpack_require__(/*! @radix-ui/react-portal */ "../../../node_modules/@radix-ui/react-portal/dist/index.js"); - var $iVrL9$radixuireactpresence = __webpack_require__(/*! @radix-ui/react-presence */ "../../../node_modules/@radix-ui/react-presence/dist/index.js"); - var $iVrL9$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); - var $iVrL9$radixuireactslot = __webpack_require__(/*! @radix-ui/react-slot */ "../../../node_modules/@radix-ui/react-slot/dist/index.js"); - var $iVrL9$radixuireactusecontrollablestate = __webpack_require__(/*! @radix-ui/react-use-controllable-state */ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js"); - var $iVrL9$radixuireactvisuallyhidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true + return observeIntersection(visualElement.getInstance(), options, intersectionCallback); + }, [shouldObserve, root, rootMargin, amount]); +} +/** + * If IntersectionObserver is missing, we activate inView and fire onViewportEnter + * on mount. This way, the page will be in the state the author expects users + * to see it in for everyone. + */ +function useMissingIntersectionObserver(shouldObserve, state, visualElement, _a) { + var _b = _a.fallback, + fallback = _b === void 0 ? true : _b; + React.useEffect(function () { + if (!shouldObserve || !fallback) return; + if (env !== "production") { + warnOnce(false, "IntersectionObserver not available on this device. whileInView animations will trigger on mount."); + } + /** + * Fire this in an rAF because, at this point, the animation state + * won't have flushed for the first time and there's certain logic in + * there that behaves differently on the initial animation. + * + * This hook should be quite rarely called so setting this in an rAF + * is preferred to changing the behaviour of the animation state. + */ + requestAnimationFrame(function () { + var _a; + state.hasEnteredView = true; + var onViewportEnter = visualElement.getProps().onViewportEnter; + onViewportEnter === null || onViewportEnter === void 0 ? void 0 : onViewportEnter(null); + (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.InView, true); }); + }, [shouldObserve]); +} +var makeRenderlessComponent = function (hook) { + return function (props) { + hook(props); + return null; + }; +}; +var gestureAnimations = { + inView: makeRenderlessComponent(useViewport), + tap: makeRenderlessComponent(useTapGesture), + focus: makeRenderlessComponent(useFocusGesture), + hover: makeRenderlessComponent(useHoverGesture) +}; +var counter = 0; +var incrementId = function () { + return counter++; +}; +var useId = function () { + return useConstant(incrementId); +}; +/** + * Ideally we'd use the following code to support React 18 optionally. + * But this fairly fails in Webpack (otherwise treeshaking wouldn't work at all). + * Need to come up with a different way of figuring this out. + */ +// export const useId = (React as any).useId +// ? (React as any).useId +// : () => useConstant(incrementId) + +/** + * When a component is the child of `AnimatePresence`, it can use `usePresence` + * to access information about whether it's still present in the React tree. + * + * ```jsx + * import { usePresence } from "framer-motion" + * + * export const Component = () => { + * const [isPresent, safeToRemove] = usePresence() + * + * useEffect(() => { + * !isPresent && setTimeout(safeToRemove, 1000) + * }, [isPresent]) + * + * return
    + * } + * ``` + * + * If `isPresent` is `false`, it means that a component has been removed the tree, but + * `AnimatePresence` won't really remove it until `safeToRemove` has been called. + * + * @public + */ +function usePresence() { + var context = React.useContext(PresenceContext); + if (context === null) return [true, null]; + var isPresent = context.isPresent, + onExitComplete = context.onExitComplete, + register = context.register; + // It's safe to call the following hooks conditionally (after an early return) because the context will always + // either be null or non-null for the lifespan of the component. + // Replace with useId when released in React + var id = useId(); + React.useEffect(function () { + return register(id); + }, []); + var safeToRemove = function () { + return onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete(id); + }; + return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; +} +/** + * Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present. + * There is no `safeToRemove` function. + * + * ```jsx + * import { useIsPresent } from "framer-motion" + * + * export const Component = () => { + * const isPresent = useIsPresent() + * + * useEffect(() => { + * !isPresent && console.log("I've been removed!") + * }, [isPresent]) + * + * return
    + * } + * ``` + * + * @public + */ +function useIsPresent() { + return isPresent(React.useContext(PresenceContext)); +} +function isPresent(context) { + return context === null ? true : context.isPresent; +} +function shallowCompare(next, prev) { + if (!Array.isArray(prev)) return false; + var prevLength = prev.length; + if (prevLength !== next.length) return false; + for (var i = 0; i < prevLength; i++) { + if (prev[i] !== next[i]) return false; + } + return true; +} + +/** + * Converts seconds to milliseconds + * + * @param seconds - Time in seconds. + * @return milliseconds - Converted time in milliseconds. + */ +var secondsToMilliseconds = function (seconds) { + return seconds * 1000; +}; +var easingLookup = { + linear: popmotion.linear, + easeIn: popmotion.easeIn, + easeInOut: popmotion.easeInOut, + easeOut: popmotion.easeOut, + circIn: popmotion.circIn, + circInOut: popmotion.circInOut, + circOut: popmotion.circOut, + backIn: popmotion.backIn, + backInOut: popmotion.backInOut, + backOut: popmotion.backOut, + anticipate: popmotion.anticipate, + bounceIn: popmotion.bounceIn, + bounceInOut: popmotion.bounceInOut, + bounceOut: popmotion.bounceOut +}; +var easingDefinitionToFunction = function (definition) { + if (Array.isArray(definition)) { + // If cubic bezier definition, create bezier curve + heyListen.invariant(definition.length === 4, "Cubic bezier arrays must contain four numerical values."); + var _a = tslib.__read(definition, 4), + x1 = _a[0], + y1 = _a[1], + x2 = _a[2], + y2 = _a[3]; + return popmotion.cubicBezier(x1, y1, x2, y2); + } else if (typeof definition === "string") { + // Else lookup from table + heyListen.invariant(easingLookup[definition] !== undefined, "Invalid easing type '".concat(definition, "'")); + return easingLookup[definition]; + } + return definition; +}; +var isEasingArray = function (ease) { + return Array.isArray(ease) && typeof ease[0] !== "number"; +}; + +/** + * Check if a value is animatable. Examples: + * + * ✅: 100, "100px", "#fff" + * ❌: "block", "url(2.jpg)" + * @param value + * + * @internal + */ +var isAnimatable = function (key, value) { + // If the list of keys tat might be non-animatable grows, replace with Set + if (key === "zIndex") return false; + // If it's a number or a keyframes array, we can animate it. We might at some point + // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this, + // but for now lets leave it like this for performance reasons + if (typeof value === "number" || Array.isArray(value)) return true; + if (typeof value === "string" && + // It's animatable if we have a string + styleValueTypes.complex.test(value) && + // And it contains numbers and/or colors + !value.startsWith("url(") // Unless it starts with "url(" + ) { + return true; } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export(module.exports, "createTooltipScope", () => $c34afbc43c90cc6f$export$1c540a2224f0d865); - $parcel$export(module.exports, "TooltipProvider", () => $c34afbc43c90cc6f$export$f78649fb9ca566b8); - $parcel$export(module.exports, "Tooltip", () => $c34afbc43c90cc6f$export$28c660c63b792dea); - $parcel$export(module.exports, "TooltipTrigger", () => $c34afbc43c90cc6f$export$8c610744efcf8a1d); - $parcel$export(module.exports, "TooltipPortal", () => $c34afbc43c90cc6f$export$7b36b8f925ab7497); - $parcel$export(module.exports, "TooltipContent", () => $c34afbc43c90cc6f$export$e9003e2be37ec060); - $parcel$export(module.exports, "TooltipArrow", () => $c34afbc43c90cc6f$export$c27ee0ad710f7559); - $parcel$export(module.exports, "Provider", () => $c34afbc43c90cc6f$export$2881499e37b75b9a); - $parcel$export(module.exports, "Root", () => $c34afbc43c90cc6f$export$be92b6f5f03c0fe9); - $parcel$export(module.exports, "Trigger", () => $c34afbc43c90cc6f$export$41fb9f06171c75f4); - $parcel$export(module.exports, "Portal", () => $c34afbc43c90cc6f$export$602eac185826482c); - $parcel$export(module.exports, "Content", () => $c34afbc43c90cc6f$export$7c6e2c02157bb7d2); - $parcel$export(module.exports, "Arrow", () => $c34afbc43c90cc6f$export$21b07c8f274aebd5); - const [$c34afbc43c90cc6f$var$createTooltipContext, $c34afbc43c90cc6f$export$1c540a2224f0d865] = $iVrL9$radixuireactcontext.createContextScope('Tooltip', [$iVrL9$radixuireactpopper.createPopperScope]); - const $c34afbc43c90cc6f$var$usePopperScope = $iVrL9$radixuireactpopper.createPopperScope(); - /* ------------------------------------------------------------------------------------------------- - * TooltipProvider - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$PROVIDER_NAME = 'TooltipProvider'; - const $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION = 700; - const $c34afbc43c90cc6f$var$TOOLTIP_OPEN = 'tooltip.open'; - const [$c34afbc43c90cc6f$var$TooltipProviderContextProvider, $c34afbc43c90cc6f$var$useTooltipProviderContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$PROVIDER_NAME); - const $c34afbc43c90cc6f$export$f78649fb9ca566b8 = props => { - const { - __scopeTooltip: __scopeTooltip, - delayDuration = $c34afbc43c90cc6f$var$DEFAULT_DELAY_DURATION, - skipDelayDuration = 300, - disableHoverableContent = false, - children: children - } = props; - const [isOpenDelayed, setIsOpenDelayed] = $iVrL9$react.useState(true); - const isPointerInTransitRef = $iVrL9$react.useRef(false); - const skipDelayTimerRef = $iVrL9$react.useRef(0); - $iVrL9$react.useEffect(() => { - const skipDelayTimer = skipDelayTimerRef.current; - return () => window.clearTimeout(skipDelayTimer); - }, []); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipProviderContextProvider, { - scope: __scopeTooltip, - isOpenDelayed: isOpenDelayed, - delayDuration: delayDuration, - onOpen: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - setIsOpenDelayed(false); - }, []), - onClose: $iVrL9$react.useCallback(() => { - window.clearTimeout(skipDelayTimerRef.current); - skipDelayTimerRef.current = window.setTimeout(() => setIsOpenDelayed(true), skipDelayDuration); - }, [skipDelayDuration]), - isPointerInTransitRef: isPointerInTransitRef, - onPointerInTransitChange: $iVrL9$react.useCallback(inTransit => { - isPointerInTransitRef.current = inTransit; - }, []), - disableHoverableContent: disableHoverableContent - }, children); + return false; +}; +var underDampedSpring = function () { + return { + type: "spring", + stiffness: 500, + damping: 25, + restSpeed: 10 }; - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$f78649fb9ca566b8, { - displayName: $c34afbc43c90cc6f$var$PROVIDER_NAME - }); - /* ------------------------------------------------------------------------------------------------- - * Tooltip - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$TOOLTIP_NAME = 'Tooltip'; - const [$c34afbc43c90cc6f$var$TooltipContextProvider, $c34afbc43c90cc6f$var$useTooltipContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$TOOLTIP_NAME); - const $c34afbc43c90cc6f$export$28c660c63b792dea = props => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - open: openProp, - defaultOpen = false, - onOpenChange: onOpenChange, - disableHoverableContent: disableHoverableContentProp, - delayDuration: delayDurationProp - } = props; - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$TOOLTIP_NAME, props.__scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const [trigger, setTrigger] = $iVrL9$react.useState(null); - const contentId = $iVrL9$radixuireactid.useId(); - const openTimerRef = $iVrL9$react.useRef(0); - const disableHoverableContent = disableHoverableContentProp !== null && disableHoverableContentProp !== void 0 ? disableHoverableContentProp : providerContext.disableHoverableContent; - const delayDuration = delayDurationProp !== null && delayDurationProp !== void 0 ? delayDurationProp : providerContext.delayDuration; - const wasOpenDelayedRef = $iVrL9$react.useRef(false); - const [open1 = false, setOpen] = $iVrL9$radixuireactusecontrollablestate.useControllableState({ - prop: openProp, - defaultProp: defaultOpen, - onChange: open => { - if (open) { - providerContext.onOpen(); // as `onChange` is called within a lifecycle method we - // avoid dispatching via `dispatchDiscreteCustomEvent`. - document.dispatchEvent(new CustomEvent($c34afbc43c90cc6f$var$TOOLTIP_OPEN)); - } else providerContext.onClose(); - onOpenChange === null || onOpenChange === void 0 || onOpenChange(open); - } - }); - const stateAttribute = $iVrL9$react.useMemo(() => { - return open1 ? wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open' : 'closed'; - }, [open1]); - const handleOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - wasOpenDelayedRef.current = false; - setOpen(true); - }, [setOpen]); - const handleClose = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - setOpen(false); - }, [setOpen]); - const handleDelayedOpen = $iVrL9$react.useCallback(() => { - window.clearTimeout(openTimerRef.current); - openTimerRef.current = window.setTimeout(() => { - wasOpenDelayedRef.current = true; - setOpen(true); - }, delayDuration); - }, [delayDuration, setOpen]); - $iVrL9$react.useEffect(() => { - return () => window.clearTimeout(openTimerRef.current); - }, []); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Root, popperScope, /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContextProvider, { - scope: __scopeTooltip, - contentId: contentId, - open: open1, - stateAttribute: stateAttribute, - trigger: trigger, - onTriggerChange: setTrigger, - onTriggerEnter: $iVrL9$react.useCallback(() => { - if (providerContext.isOpenDelayed) handleDelayedOpen();else handleOpen(); - }, [providerContext.isOpenDelayed, handleDelayedOpen, handleOpen]), - onTriggerLeave: $iVrL9$react.useCallback(() => { - if (disableHoverableContent) handleClose();else - // Clear the timer in case the pointer leaves the trigger before the tooltip is opened. - window.clearTimeout(openTimerRef.current); - }, [handleClose, disableHoverableContent]), - onOpen: handleOpen, - onClose: handleClose, - disableHoverableContent: disableHoverableContent - }, children)); +}; +var criticallyDampedSpring = function (to) { + return { + type: "spring", + stiffness: 550, + damping: to === 0 ? 2 * Math.sqrt(550) : 30, + restSpeed: 10 }; - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$28c660c63b792dea, { - displayName: $c34afbc43c90cc6f$var$TOOLTIP_NAME - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipTrigger - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$TRIGGER_NAME = 'TooltipTrigger'; - const $c34afbc43c90cc6f$export$8c610744efcf8a1d = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - ...triggerProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$TRIGGER_NAME, __scopeTooltip); - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$TRIGGER_NAME, __scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref, context.onTriggerChange); - const isPointerDownRef = $iVrL9$react.useRef(false); - const hasPointerMoveOpenedRef = $iVrL9$react.useRef(false); - const handlePointerUp = $iVrL9$react.useCallback(() => isPointerDownRef.current = false, []); - $iVrL9$react.useEffect(() => { - return () => document.removeEventListener('pointerup', handlePointerUp); - }, [handlePointerUp]); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Anchor, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - asChild: true - }, popperScope), /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactprimitive.Primitive.button, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - // We purposefully avoid adding `type=button` here because tooltip triggers are also - // commonly anchors and the anchor `type` attribute signifies MIME type. - "aria-describedby": context.open ? context.contentId : undefined, - "data-state": context.stateAttribute - }, triggerProps, { - ref: composedRefs, - onPointerMove: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerMove, event => { - if (event.pointerType === 'touch') return; - if (!hasPointerMoveOpenedRef.current && !providerContext.isPointerInTransitRef.current) { - context.onTriggerEnter(); - hasPointerMoveOpenedRef.current = true; - } - }), - onPointerLeave: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerLeave, () => { - context.onTriggerLeave(); - hasPointerMoveOpenedRef.current = false; - }), - onPointerDown: $iVrL9$radixuiprimitive.composeEventHandlers(props.onPointerDown, () => { - isPointerDownRef.current = true; - document.addEventListener('pointerup', handlePointerUp, { - once: true - }); - }), - onFocus: $iVrL9$radixuiprimitive.composeEventHandlers(props.onFocus, () => { - if (!isPointerDownRef.current) context.onOpen(); - }), - onBlur: $iVrL9$radixuiprimitive.composeEventHandlers(props.onBlur, context.onClose), - onClick: $iVrL9$radixuiprimitive.composeEventHandlers(props.onClick, context.onClose) - }))); - }); - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$8c610744efcf8a1d, { - displayName: $c34afbc43c90cc6f$var$TRIGGER_NAME - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipPortal - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$PORTAL_NAME = 'TooltipPortal'; - const [$c34afbc43c90cc6f$var$PortalProvider, $c34afbc43c90cc6f$var$usePortalContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$PORTAL_NAME, { - forceMount: undefined - }); - const $c34afbc43c90cc6f$export$7b36b8f925ab7497 = props => { - const { - __scopeTooltip: __scopeTooltip, - forceMount: forceMount, - children: children, - container: container - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$PORTAL_NAME, __scopeTooltip); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$PortalProvider, { - scope: __scopeTooltip, - forceMount: forceMount - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpresence.Presence, { - present: forceMount || context.open - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactportal.Portal, { - asChild: true, - container: container - }, children))); +}; +var linearTween = function () { + return { + type: "keyframes", + ease: "linear", + duration: 0.3 }; - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$7b36b8f925ab7497, { - displayName: $c34afbc43c90cc6f$var$PORTAL_NAME - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipContent - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$CONTENT_NAME = 'TooltipContent'; - const $c34afbc43c90cc6f$export$e9003e2be37ec060 = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const portalContext = $c34afbc43c90cc6f$var$usePortalContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const { - forceMount = portalContext.forceMount, - side = 'top', - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpresence.Presence, { - present: forceMount || context.open - }, context.disableHoverableContent ? /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentImpl, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - side: side - }, contentProps, { - ref: forwardedRef - })) : /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentHoverable, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - side: side - }, contentProps, { - ref: forwardedRef - }))); - }); - const $c34afbc43c90cc6f$var$TooltipContentHoverable = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const providerContext = $c34afbc43c90cc6f$var$useTooltipProviderContext($c34afbc43c90cc6f$var$CONTENT_NAME, props.__scopeTooltip); - const ref = $iVrL9$react.useRef(null); - const composedRefs = $iVrL9$radixuireactcomposerefs.useComposedRefs(forwardedRef, ref); - const [pointerGraceArea, setPointerGraceArea] = $iVrL9$react.useState(null); - const { - trigger: trigger, - onClose: onClose - } = context; - const content = ref.current; - const { - onPointerInTransitChange: onPointerInTransitChange - } = providerContext; - const handleRemoveGraceArea = $iVrL9$react.useCallback(() => { - setPointerGraceArea(null); - onPointerInTransitChange(false); - }, [onPointerInTransitChange]); - const handleCreateGraceArea = $iVrL9$react.useCallback((event, hoverTarget) => { - const currentTarget = event.currentTarget; - const exitPoint = { - x: event.clientX, - y: event.clientY - }; - const exitSide = $c34afbc43c90cc6f$var$getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect()); - const paddedExitPoints = $c34afbc43c90cc6f$var$getPaddedExitPoints(exitPoint, exitSide); - const hoverTargetPoints = $c34afbc43c90cc6f$var$getPointsFromRect(hoverTarget.getBoundingClientRect()); - const graceArea = $c34afbc43c90cc6f$var$getHull([...paddedExitPoints, ...hoverTargetPoints]); - setPointerGraceArea(graceArea); - onPointerInTransitChange(true); - }, [onPointerInTransitChange]); - $iVrL9$react.useEffect(() => { - return () => handleRemoveGraceArea(); - }, [handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (trigger && content) { - const handleTriggerLeave = event => handleCreateGraceArea(event, content); - const handleContentLeave = event => handleCreateGraceArea(event, trigger); - trigger.addEventListener('pointerleave', handleTriggerLeave); - content.addEventListener('pointerleave', handleContentLeave); - return () => { - trigger.removeEventListener('pointerleave', handleTriggerLeave); - content.removeEventListener('pointerleave', handleContentLeave); - }; +}; +var keyframes = function (values) { + return { + type: "keyframes", + duration: 0.8, + values: values + }; +}; +var defaultTransitions = { + x: underDampedSpring, + y: underDampedSpring, + z: underDampedSpring, + rotate: underDampedSpring, + rotateX: underDampedSpring, + rotateY: underDampedSpring, + rotateZ: underDampedSpring, + scaleX: criticallyDampedSpring, + scaleY: criticallyDampedSpring, + scale: criticallyDampedSpring, + opacity: linearTween, + backgroundColor: linearTween, + color: linearTween, + default: criticallyDampedSpring +}; +var getDefaultTransition = function (valueKey, to) { + var transitionFactory; + if (isKeyframesTarget(to)) { + transitionFactory = keyframes; + } else { + transitionFactory = defaultTransitions[valueKey] || defaultTransitions.default; + } + return tslib.__assign({ + to: to + }, transitionFactory(to)); +}; + +/** + * A map of default value types for common values + */ +var defaultValueTypes = tslib.__assign(tslib.__assign({}, numberValueTypes), { + // Color props + color: styleValueTypes.color, + backgroundColor: styleValueTypes.color, + outlineColor: styleValueTypes.color, + fill: styleValueTypes.color, + stroke: styleValueTypes.color, + // Border props + borderColor: styleValueTypes.color, + borderTopColor: styleValueTypes.color, + borderRightColor: styleValueTypes.color, + borderBottomColor: styleValueTypes.color, + borderLeftColor: styleValueTypes.color, + filter: styleValueTypes.filter, + WebkitFilter: styleValueTypes.filter +}); +/** + * Gets the default ValueType for the provided value key + */ +var getDefaultValueType = function (key) { + return defaultValueTypes[key]; +}; +function getAnimatableNone(key, value) { + var _a; + var defaultValueType = getDefaultValueType(key); + if (defaultValueType !== styleValueTypes.filter) defaultValueType = styleValueTypes.complex; + // If value is not recognised as animatable, ie "none", create an animatable version origin based on the target + return (_a = defaultValueType.getAnimatableNone) === null || _a === void 0 ? void 0 : _a.call(defaultValueType, value); +} +var instantAnimationState = { + current: false +}; + +/** + * Decide whether a transition is defined on a given Transition. + * This filters out orchestration options and returns true + * if any options are left. + */ +function isTransitionDefined(_a) { + _a.when; + _a.delay; + _a.delayChildren; + _a.staggerChildren; + _a.staggerDirection; + _a.repeat; + _a.repeatType; + _a.repeatDelay; + _a.from; + var transition = tslib.__rest(_a, ["when", "delay", "delayChildren", "staggerChildren", "staggerDirection", "repeat", "repeatType", "repeatDelay", "from"]); + return !!Object.keys(transition).length; +} +var legacyRepeatWarning = false; +/** + * Convert Framer Motion's Transition type into Popmotion-compatible options. + */ +function convertTransitionToAnimationOptions(_a) { + var ease = _a.ease, + times = _a.times, + yoyo = _a.yoyo, + flip = _a.flip, + loop = _a.loop, + transition = tslib.__rest(_a, ["ease", "times", "yoyo", "flip", "loop"]); + var options = tslib.__assign({}, transition); + if (times) options["offset"] = times; + /** + * Convert any existing durations from seconds to milliseconds + */ + if (transition.duration) options["duration"] = secondsToMilliseconds(transition.duration); + if (transition.repeatDelay) options.repeatDelay = secondsToMilliseconds(transition.repeatDelay); + /** + * Map easing names to Popmotion's easing functions + */ + if (ease) { + options["ease"] = isEasingArray(ease) ? ease.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease); + } + /** + * Support legacy transition API + */ + if (transition.type === "tween") options.type = "keyframes"; + /** + * TODO: These options are officially removed from the API. + */ + if (yoyo || loop || flip) { + heyListen.warning(!legacyRepeatWarning, "yoyo, loop and flip have been removed from the API. Replace with repeat and repeatType options."); + legacyRepeatWarning = true; + if (yoyo) { + options.repeatType = "reverse"; + } else if (loop) { + options.repeatType = "loop"; + } else if (flip) { + options.repeatType = "mirror"; + } + options.repeat = loop || yoyo || flip || transition.repeat; + } + /** + * TODO: Popmotion 9 has the ability to automatically detect whether to use + * a keyframes or spring animation, but does so by detecting velocity and other spring options. + * It'd be good to introduce a similar thing here. + */ + if (transition.type !== "spring") options.type = "keyframes"; + return options; +} +/** + * Get the delay for a value by checking Transition with decreasing specificity. + */ +function getDelayFromTransition(transition, key) { + var _a, _b; + var valueTransition = getValueTransition(transition, key) || {}; + return (_b = (_a = valueTransition.delay) !== null && _a !== void 0 ? _a : transition.delay) !== null && _b !== void 0 ? _b : 0; +} +function hydrateKeyframes(options) { + if (Array.isArray(options.to) && options.to[0] === null) { + options.to = tslib.__spreadArray([], tslib.__read(options.to), false); + options.to[0] = options.from; + } + return options; +} +function getPopmotionAnimationOptions(transition, options, key) { + var _a; + if (Array.isArray(options.to)) { + (_a = transition.duration) !== null && _a !== void 0 ? _a : transition.duration = 0.8; + } + hydrateKeyframes(options); + /** + * Get a default transition if none is determined to be defined. + */ + if (!isTransitionDefined(transition)) { + transition = tslib.__assign(tslib.__assign({}, transition), getDefaultTransition(key, options.to)); + } + return tslib.__assign(tslib.__assign({}, options), convertTransitionToAnimationOptions(transition)); +} +/** + * + */ +function getAnimation(key, value, target, transition, onComplete) { + var _a; + var valueTransition = getValueTransition(transition, key); + var origin = (_a = valueTransition.from) !== null && _a !== void 0 ? _a : value.get(); + var isTargetAnimatable = isAnimatable(key, target); + if (origin === "none" && isTargetAnimatable && typeof target === "string") { + /** + * If we're trying to animate from "none", try and get an animatable version + * of the target. This could be improved to work both ways. + */ + origin = getAnimatableNone(key, target); + } else if (isZero(origin) && typeof target === "string") { + origin = getZeroUnit(target); + } else if (!Array.isArray(target) && isZero(target) && typeof origin === "string") { + target = getZeroUnit(origin); + } + var isOriginAnimatable = isAnimatable(key, origin); + heyListen.warning(isOriginAnimatable === isTargetAnimatable, "You are trying to animate ".concat(key, " from \"").concat(origin, "\" to \"").concat(target, "\". ").concat(origin, " is not an animatable value - to enable this animation set ").concat(origin, " to a value animatable to ").concat(target, " via the `style` property.")); + function start() { + var options = { + from: origin, + to: target, + velocity: value.getVelocity(), + onComplete: onComplete, + onUpdate: function (v) { + return value.set(v); } - }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]); - $iVrL9$react.useEffect(() => { - if (pointerGraceArea) { - const handleTrackPointerGrace = event => { - const target = event.target; - const pointerPosition = { - x: event.clientX, - y: event.clientY - }; - const hasEnteredTarget = (trigger === null || trigger === void 0 ? void 0 : trigger.contains(target)) || (content === null || content === void 0 ? void 0 : content.contains(target)); - const isPointerOutsideGraceArea = !$c34afbc43c90cc6f$var$isPointInPolygon(pointerPosition, pointerGraceArea); - if (hasEnteredTarget) handleRemoveGraceArea();else if (isPointerOutsideGraceArea) { - handleRemoveGraceArea(); - onClose(); - } - }; - document.addEventListener('pointermove', handleTrackPointerGrace); - return () => document.removeEventListener('pointermove', handleTrackPointerGrace); + }; + return valueTransition.type === "inertia" || valueTransition.type === "decay" ? popmotion.inertia(tslib.__assign(tslib.__assign({}, options), valueTransition)) : popmotion.animate(tslib.__assign(tslib.__assign({}, getPopmotionAnimationOptions(valueTransition, options, key)), { + onUpdate: function (v) { + var _a; + options.onUpdate(v); + (_a = valueTransition.onUpdate) === null || _a === void 0 ? void 0 : _a.call(valueTransition, v); + }, + onComplete: function () { + var _a; + options.onComplete(); + (_a = valueTransition.onComplete) === null || _a === void 0 ? void 0 : _a.call(valueTransition); } - }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]); - return /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$TooltipContentImpl, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({}, props, { - ref: composedRefs })); + } + function set() { + var _a, _b; + var finalTarget = resolveFinalValueInKeyframes(target); + value.set(finalTarget); + onComplete(); + (_a = valueTransition === null || valueTransition === void 0 ? void 0 : valueTransition.onUpdate) === null || _a === void 0 ? void 0 : _a.call(valueTransition, finalTarget); + (_b = valueTransition === null || valueTransition === void 0 ? void 0 : valueTransition.onComplete) === null || _b === void 0 ? void 0 : _b.call(valueTransition); + return { + stop: function () {} + }; + } + return !isOriginAnimatable || !isTargetAnimatable || valueTransition.type === false ? set : start; +} +function isZero(value) { + return value === 0 || typeof value === "string" && parseFloat(value) === 0 && value.indexOf(" ") === -1; +} +function getZeroUnit(potentialUnitType) { + return typeof potentialUnitType === "number" ? 0 : getAnimatableNone("", potentialUnitType); +} +function getValueTransition(transition, key) { + return transition[key] || transition["default"] || transition; +} +/** + * Start animation on a MotionValue. This function is an interface between + * Framer Motion and Popmotion + */ +function startAnimation(key, value, target, transition) { + if (transition === void 0) { + transition = {}; + } + if (instantAnimationState.current) { + transition = { + type: false + }; + } + return value.start(function (onComplete) { + var delayTimer; + var controls; + var animation = getAnimation(key, value, target, transition, onComplete); + var delay = getDelayFromTransition(transition, key); + var start = function () { + return controls = animation(); + }; + if (delay) { + delayTimer = window.setTimeout(start, secondsToMilliseconds(delay)); + } else { + start(); + } + return function () { + clearTimeout(delayTimer); + controls === null || controls === void 0 ? void 0 : controls.stop(); + }; }); - const [$c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext] = $c34afbc43c90cc6f$var$createTooltipContext($c34afbc43c90cc6f$var$TOOLTIP_NAME, { - isInside: false - }); - const $c34afbc43c90cc6f$var$TooltipContentImpl = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - children: children, - 'aria-label': ariaLabel, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - ...contentProps - } = props; - const context = $c34afbc43c90cc6f$var$useTooltipContext($c34afbc43c90cc6f$var$CONTENT_NAME, __scopeTooltip); - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const { - onClose: onClose - } = context; // Close this tooltip if another one opens - $iVrL9$react.useEffect(() => { - document.addEventListener($c34afbc43c90cc6f$var$TOOLTIP_OPEN, onClose); - return () => document.removeEventListener($c34afbc43c90cc6f$var$TOOLTIP_OPEN, onClose); - }, [onClose]); // Close the tooltip if the trigger is scrolled - $iVrL9$react.useEffect(() => { - if (context.trigger) { - const handleScroll = event => { - const target = event.target; - if (target !== null && target !== void 0 && target.contains(context.trigger)) onClose(); - }; - window.addEventListener('scroll', handleScroll, { - capture: true - }); - return () => window.removeEventListener('scroll', handleScroll, { - capture: true - }); - } - }, [context.trigger, onClose]); - return /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactdismissablelayer.DismissableLayer, { - asChild: true, - disableOutsidePointerEvents: false, - onEscapeKeyDown: onEscapeKeyDown, - onPointerDownOutside: onPointerDownOutside, - onFocusOutside: event => event.preventDefault(), - onDismiss: onClose - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Content, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({ - "data-state": context.stateAttribute - }, popperScope, contentProps, { - ref: forwardedRef, - style: { - ...contentProps.style, - '--radix-tooltip-content-transform-origin': 'var(--radix-popper-transform-origin)', - '--radix-tooltip-content-available-width': 'var(--radix-popper-available-width)', - '--radix-tooltip-content-available-height': 'var(--radix-popper-available-height)', - '--radix-tooltip-trigger-width': 'var(--radix-popper-anchor-width)', - '--radix-tooltip-trigger-height': 'var(--radix-popper-anchor-height)' - } - }), /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactslot.Slottable, null, children), /*#__PURE__*/$iVrL9$react.createElement($c34afbc43c90cc6f$var$VisuallyHiddenContentContextProvider, { - scope: __scopeTooltip, - isInside: true - }, /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactvisuallyhidden.Root, { - id: context.contentId, - role: "tooltip" - }, ariaLabel || children)))); - }); - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$e9003e2be37ec060, { - displayName: $c34afbc43c90cc6f$var$CONTENT_NAME - }); - /* ------------------------------------------------------------------------------------------------- - * TooltipArrow - * -----------------------------------------------------------------------------------------------*/ - const $c34afbc43c90cc6f$var$ARROW_NAME = 'TooltipArrow'; - const $c34afbc43c90cc6f$export$c27ee0ad710f7559 = /*#__PURE__*/$iVrL9$react.forwardRef((props, forwardedRef) => { - const { - __scopeTooltip: __scopeTooltip, - ...arrowProps - } = props; - const popperScope = $c34afbc43c90cc6f$var$usePopperScope(__scopeTooltip); - const visuallyHiddenContentContext = $c34afbc43c90cc6f$var$useVisuallyHiddenContentContext($c34afbc43c90cc6f$var$ARROW_NAME, __scopeTooltip); // if the arrow is inside the `VisuallyHidden`, we don't want to render it all to - // prevent issues in positioning the arrow due to the duplicate - return visuallyHiddenContentContext.isInside ? null : /*#__PURE__*/$iVrL9$react.createElement($iVrL9$radixuireactpopper.Arrow, $parcel$interopDefault($iVrL9$babelruntimehelpersextends)({}, popperScope, arrowProps, { - ref: forwardedRef - })); - }); - /*#__PURE__*/ - Object.assign($c34afbc43c90cc6f$export$c27ee0ad710f7559, { - displayName: $c34afbc43c90cc6f$var$ARROW_NAME - }); - /* -----------------------------------------------------------------------------------------------*/ - function $c34afbc43c90cc6f$var$getExitSideFromRect(point, rect) { - const top = Math.abs(rect.top - point.y); - const bottom = Math.abs(rect.bottom - point.y); - const right = Math.abs(rect.right - point.x); - const left = Math.abs(rect.left - point.x); - switch (Math.min(top, bottom, right, left)) { - case left: - return 'left'; - case right: - return 'right'; - case top: - return 'top'; - case bottom: - return 'bottom'; - default: - throw new Error('unreachable'); - } - } - function $c34afbc43c90cc6f$var$getPaddedExitPoints(exitPoint, exitSide, padding = 5) { - const paddedExitPoints = []; - switch (exitSide) { - case 'top': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y + padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y + padding - }); - break; - case 'bottom': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y - padding - }); - break; - case 'left': - paddedExitPoints.push({ - x: exitPoint.x + padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x + padding, - y: exitPoint.y + padding - }); - break; - case 'right': - paddedExitPoints.push({ - x: exitPoint.x - padding, - y: exitPoint.y - padding - }, { - x: exitPoint.x - padding, - y: exitPoint.y + padding - }); - break; - } - return paddedExitPoints; - } - function $c34afbc43c90cc6f$var$getPointsFromRect(rect) { - const { - top: top, - right: right, - bottom: bottom, - left: left - } = rect; - return [{ - x: left, - y: top - }, { - x: right, - y: top - }, { - x: right, - y: bottom - }, { - x: left, - y: bottom - }]; - } // Determine if a point is inside of a polygon. - // Based on https://github.com/substack/point-in-polygon - function $c34afbc43c90cc6f$var$isPointInPolygon(point, polygon) { - const { - x: x, - y: y - } = point; - let inside = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - const xi = polygon[i].x; - const yi = polygon[i].y; - const xj = polygon[j].x; - const yj = polygon[j].y; // prettier-ignore - const intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; - } // Returns a new array of points representing the convex hull of the given set of points. - // https://www.nayuki.io/page/convex-hull-algorithm - function $c34afbc43c90cc6f$var$getHull(points) { - const newPoints = points.slice(); - newPoints.sort((a, b) => { - if (a.x < b.x) return -1;else if (a.x > b.x) return 1;else if (a.y < b.y) return -1;else if (a.y > b.y) return 1;else return 0; - }); - return $c34afbc43c90cc6f$var$getHullPresorted(newPoints); - } // Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time. - function $c34afbc43c90cc6f$var$getHullPresorted(points) { - if (points.length <= 1) return points.slice(); - const upperHull = []; - for (let i = 0; i < points.length; i++) { - const p = points[i]; - while (upperHull.length >= 2) { - const q = upperHull[upperHull.length - 1]; - const r = upperHull[upperHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) upperHull.pop();else break; - } - upperHull.push(p); - } - upperHull.pop(); - const lowerHull = []; - for (let i1 = points.length - 1; i1 >= 0; i1--) { - const p = points[i1]; - while (lowerHull.length >= 2) { - const q = lowerHull[lowerHull.length - 1]; - const r = lowerHull[lowerHull.length - 2]; - if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x)) lowerHull.pop();else break; - } - lowerHull.push(p); - } - lowerHull.pop(); - if (upperHull.length === 1 && lowerHull.length === 1 && upperHull[0].x === lowerHull[0].x && upperHull[0].y === lowerHull[0].y) return upperHull;else return upperHull.concat(lowerHull); - } - const $c34afbc43c90cc6f$export$2881499e37b75b9a = $c34afbc43c90cc6f$export$f78649fb9ca566b8; - const $c34afbc43c90cc6f$export$be92b6f5f03c0fe9 = $c34afbc43c90cc6f$export$28c660c63b792dea; - const $c34afbc43c90cc6f$export$41fb9f06171c75f4 = $c34afbc43c90cc6f$export$8c610744efcf8a1d; - const $c34afbc43c90cc6f$export$602eac185826482c = $c34afbc43c90cc6f$export$7b36b8f925ab7497; - const $c34afbc43c90cc6f$export$7c6e2c02157bb7d2 = $c34afbc43c90cc6f$export$e9003e2be37ec060; - const $c34afbc43c90cc6f$export$21b07c8f274aebd5 = $c34afbc43c90cc6f$export$c27ee0ad710f7559; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js ***! - \****************************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $92muK$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - $parcel$export(module.exports, "useCallbackRef", () => $28e03942f763e819$export$25bec8c6f54ee79a); - - /** - * A custom hook that converts a callback to a ref to avoid triggering re-renders when passed as a - * prop or avoid re-executing effects when passed as a dependency - */ - function $28e03942f763e819$export$25bec8c6f54ee79a(callback) { - const callbackRef = $92muK$react.useRef(callback); - $92muK$react.useEffect(() => { - callbackRef.current = callback; - }); // https://github.com/facebook/react/issues/19240 - return $92muK$react.useMemo(() => (...args) => { - var _callbackRef$current; - return (_callbackRef$current = callbackRef.current) === null || _callbackRef$current === void 0 ? void 0 : _callbackRef$current.call(callbackRef, ...args); - }, []); - } - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-controllable-state/dist/index.js ***! - \**********************************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $ijazI$react = __webpack_require__(/*! react */ "react"); - var $ijazI$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - $parcel$export(module.exports, "useControllableState", () => $b84d42d44371bff7$export$6f32135080cb4c3); - function $b84d42d44371bff7$export$6f32135080cb4c3({ - prop: prop, - defaultProp: defaultProp, - onChange = () => {} - }) { - const [uncontrolledProp, setUncontrolledProp] = $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange - }); - const isControlled = prop !== undefined; - const value1 = isControlled ? prop : uncontrolledProp; - const handleChange = $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - const setValue = $ijazI$react.useCallback(nextValue => { - if (isControlled) { - const setter = nextValue; - const value = typeof nextValue === 'function' ? setter(prop) : nextValue; - if (value !== prop) handleChange(value); - } else setUncontrolledProp(nextValue); - }, [isControlled, prop, setUncontrolledProp, handleChange]); - return [value1, setValue]; - } - function $b84d42d44371bff7$var$useUncontrolledState({ - defaultProp: defaultProp, - onChange: onChange - }) { - const uncontrolledState = $ijazI$react.useState(defaultProp); - const [value] = uncontrolledState; - const prevValueRef = $ijazI$react.useRef(value); - const handleChange = $ijazI$radixuireactusecallbackref.useCallbackRef(onChange); - $ijazI$react.useEffect(() => { - if (prevValueRef.current !== value) { - handleChange(value); - prevValueRef.current = value; - } - }, [value, prevValueRef, handleChange]); - return uncontrolledState; - } - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-escape-keydown/dist/index.js ***! - \******************************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $b0gz3$react = __webpack_require__(/*! react */ "react"); - var $b0gz3$radixuireactusecallbackref = __webpack_require__(/*! @radix-ui/react-use-callback-ref */ "../../../node_modules/@radix-ui/react-use-callback-ref/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - $parcel$export(module.exports, "useEscapeKeydown", () => $24c84e9f83c4454f$export$3a72a57244d6e765); - - /** - * Listens for when the escape key is down - */ - function $24c84e9f83c4454f$export$3a72a57244d6e765(onEscapeKeyDownProp, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) { - const onEscapeKeyDown = $b0gz3$radixuireactusecallbackref.useCallbackRef(onEscapeKeyDownProp); - $b0gz3$react.useEffect(() => { - const handleKeyDown = event => { - if (event.key === 'Escape') onEscapeKeyDown(event); - }; - ownerDocument.addEventListener('keydown', handleKeyDown); - return () => ownerDocument.removeEventListener('keydown', handleKeyDown); - }, [onEscapeKeyDown, ownerDocument]); - } - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js ***! - \*****************************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $caHyQ$react = __webpack_require__(/*! react */ "react"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - $parcel$export(module.exports, "useLayoutEffect", () => $ca21affb0542a8a4$export$e5c5a5f917a5871c); - - /** - * On the server, React emits a warning when calling `useLayoutEffect`. - * This is because neither `useLayoutEffect` nor `useEffect` run on the server. - * We use this safe version which suppresses the warning by replacing it with a noop on the server. - * - * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect - */ - const $ca21affb0542a8a4$export$e5c5a5f917a5871c = Boolean(globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) ? $caHyQ$react.useLayoutEffect : () => {}; - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-use-size/dist/index.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-use-size/dist/index.js ***! - \********************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $ksDzM$react = __webpack_require__(/*! react */ "react"); - var $ksDzM$radixuireactuselayouteffect = __webpack_require__(/*! @radix-ui/react-use-layout-effect */ "../../../node_modules/@radix-ui/react-use-layout-effect/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - $parcel$export(module.exports, "useSize", () => $d2c1d285af17635b$export$1ab7ae714698c4b8); - function $d2c1d285af17635b$export$1ab7ae714698c4b8(element) { - const [size, setSize] = $ksDzM$react.useState(undefined); - $ksDzM$radixuireactuselayouteffect.useLayoutEffect(() => { - if (element) { - // provide size as early as possible - setSize({ - width: element.offsetWidth, - height: element.offsetHeight - }); - const resizeObserver = new ResizeObserver(entries => { - if (!Array.isArray(entries)) return; - // Since we only observe the one element, we don't need to loop over the - // array - if (!entries.length) return; - const entry = entries[0]; - let width; - let height; - if ('borderBoxSize' in entry) { - const borderSizeEntry = entry['borderBoxSize']; // iron out differences between browsers - const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry; - width = borderSize['inlineSize']; - height = borderSize['blockSize']; - } else { - // for browsers that don't support `borderBoxSize` - // we calculate it ourselves to get the correct border box. - width = element.offsetWidth; - height = element.offsetHeight; - } - setSize({ - width: width, - height: height - }); - }); - resizeObserver.observe(element, { - box: 'border-box' - }); - return () => resizeObserver.unobserve(element); - } else - // We only want to reset to `undefined` when the element becomes `null`, - // not if it changes to another element. - setSize(undefined); - }, [element]); - return size; - } - - /***/ }), - - /***/ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js ***! - \***************************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var $awrN2$babelruntimehelpersextends = __webpack_require__(/*! @babel/runtime/helpers/extends */ "../../../node_modules/@babel/runtime/helpers/extends.js"); - var $awrN2$react = __webpack_require__(/*! react */ "react"); - var $awrN2$radixuireactprimitive = __webpack_require__(/*! @radix-ui/react-primitive */ "../../../node_modules/@radix-ui/react-primitive/dist/index.js"); - function $parcel$export(e, n, v, s) { - Object.defineProperty(e, n, { - get: v, - set: s, - enumerable: true, - configurable: true - }); - } - function $parcel$interopDefault(a) { - return a && a.__esModule ? a.default : a; - } - $parcel$export(module.exports, "VisuallyHidden", () => $685371e9c20848e2$export$439d29a4e110a164); - $parcel$export(module.exports, "Root", () => $685371e9c20848e2$export$be92b6f5f03c0fe9); - - /* ------------------------------------------------------------------------------------------------- - * VisuallyHidden - * -----------------------------------------------------------------------------------------------*/ - const $685371e9c20848e2$var$NAME = 'VisuallyHidden'; - const $685371e9c20848e2$export$439d29a4e110a164 = /*#__PURE__*/$awrN2$react.forwardRef((props, forwardedRef) => { - return /*#__PURE__*/$awrN2$react.createElement($awrN2$radixuireactprimitive.Primitive.span, $parcel$interopDefault($awrN2$babelruntimehelpersextends)({}, props, { - ref: forwardedRef, - style: { - // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss - position: 'absolute', - border: 0, - width: 1, - height: 1, - padding: 0, - margin: -1, - overflow: 'hidden', - clip: 'rect(0, 0, 0, 0)', - whiteSpace: 'nowrap', - wordWrap: 'normal', - ...props.style +} + +/** + * Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1" + */ +var isNumericalString = function (v) { + return /^\-?\d*\.?\d+$/.test(v); +}; + +/** + * Check if the value is a zero value string like "0px" or "0%" + */ +var isZeroValueString = function (v) { + return /^0[^.\s]+$/.test(v); +}; +function addUniqueItem(arr, item) { + arr.indexOf(item) === -1 && arr.push(item); +} +function removeItem(arr, item) { + var index = arr.indexOf(item); + index > -1 && arr.splice(index, 1); +} +// Adapted from array-move +function moveItem(_a, fromIndex, toIndex) { + var _b = tslib.__read(_a), + arr = _b.slice(0); + var startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex; + if (startIndex >= 0 && startIndex < arr.length) { + var endIndex = toIndex < 0 ? arr.length + toIndex : toIndex; + var _c = tslib.__read(arr.splice(fromIndex, 1), 1), + item = _c[0]; + arr.splice(endIndex, 0, item); + } + return arr; +} +var SubscriptionManager = /** @class */function () { + function SubscriptionManager() { + this.subscriptions = []; + } + SubscriptionManager.prototype.add = function (handler) { + var _this = this; + addUniqueItem(this.subscriptions, handler); + return function () { + return removeItem(_this.subscriptions, handler); + }; + }; + SubscriptionManager.prototype.notify = function (a, b, c) { + var numSubscriptions = this.subscriptions.length; + if (!numSubscriptions) return; + if (numSubscriptions === 1) { + /** + * If there's only a single handler we can just call it without invoking a loop. + */ + this.subscriptions[0](a, b, c); + } else { + for (var i = 0; i < numSubscriptions; i++) { + /** + * Check whether the handler exists before firing as it's possible + * the subscriptions were modified during this loop running. + */ + var handler = this.subscriptions[i]; + handler && handler(a, b, c); } - })); - }); - /*#__PURE__*/ - Object.assign($685371e9c20848e2$export$439d29a4e110a164, { - displayName: $685371e9c20848e2$var$NAME - }); - /* -----------------------------------------------------------------------------------------------*/ - const $685371e9c20848e2$export$be92b6f5f03c0fe9 = $685371e9c20848e2$export$439d29a4e110a164; - - /***/ }), - - /***/ "../../../node_modules/aria-hidden/dist/es2015/index.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/aria-hidden/dist/es2015/index.js ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.suppressOthers = exports.supportsInert = exports.inertOthers = exports.hideOthers = void 0; - var getDefaultParent = function (originalTarget) { - if (typeof document === 'undefined') { - return null; } - var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget; - return sampleTarget.ownerDocument.body; }; - var counterMap = new WeakMap(); - var uncontrolledNodes = new WeakMap(); - var markerMap = {}; - var lockCount = 0; - var unwrapHost = function (node) { - return node && (node.host || unwrapHost(node.parentNode)); + SubscriptionManager.prototype.getSize = function () { + return this.subscriptions.length; }; - var correctTargets = function (parent, targets) { - return targets.map(function (target) { - if (parent.contains(target)) { - return target; - } - var correctedTarget = unwrapHost(target); - if (correctedTarget && parent.contains(correctedTarget)) { - return correctedTarget; - } - console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing'); - return null; - }).filter(function (x) { - return Boolean(x); - }); + SubscriptionManager.prototype.clear = function () { + this.subscriptions.length = 0; }; - /** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @param {String} [controlAttribute] - html Attribute to control - * @return {Undo} undo command + return SubscriptionManager; +}(); +var isFloat = function (value) { + return !isNaN(parseFloat(value)); +}; +/** + * `MotionValue` is used to track the state and velocity of motion values. + * + * @public + */ +var MotionValue = /** @class */function () { + /** + * @param init - The initiating value + * @param config - Optional configuration options + * + * - `transformer`: A function to transform incoming values with. + * + * @internal */ - var applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) { - var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]); - if (!markerMap[markerName]) { - markerMap[markerName] = new WeakMap(); - } - var markerCounter = markerMap[markerName]; - var hiddenNodes = []; - var elementsToKeep = new Set(); - var elementsToStop = new Set(targets); - var keep = function (el) { - if (!el || elementsToKeep.has(el)) { - return; + function MotionValue(init) { + var _this = this; + /** + * This will be replaced by the build step with the latest version number. + * When MotionValues are provided to motion components, warn if versions are mixed. + */ + this.version = "6.5.1"; + /** + * Duration, in milliseconds, since last updating frame. + * + * @internal + */ + this.timeDelta = 0; + /** + * Timestamp of the last time this `MotionValue` was updated. + * + * @internal + */ + this.lastUpdated = 0; + /** + * Functions to notify when the `MotionValue` updates. + * + * @internal + */ + this.updateSubscribers = new SubscriptionManager(); + /** + * Functions to notify when the velocity updates. + * + * @internal + */ + this.velocityUpdateSubscribers = new SubscriptionManager(); + /** + * Functions to notify when the `MotionValue` updates and `render` is set to `true`. + * + * @internal + */ + this.renderSubscribers = new SubscriptionManager(); + /** + * Tracks whether this value can output a velocity. Currently this is only true + * if the value is numerical, but we might be able to widen the scope here and support + * other value types. + * + * @internal + */ + this.canTrackVelocity = false; + this.updateAndNotify = function (v, render) { + if (render === void 0) { + render = true; } - elementsToKeep.add(el); - keep(el.parentNode); - }; - targets.forEach(keep); - var deep = function (parent) { - if (!parent || elementsToStop.has(parent)) { - return; + _this.prev = _this.current; + _this.current = v; + // Update timestamp + var _a = sync.getFrameData(), + delta = _a.delta, + timestamp = _a.timestamp; + if (_this.lastUpdated !== timestamp) { + _this.timeDelta = delta; + _this.lastUpdated = timestamp; + sync__default["default"].postRender(_this.scheduleVelocityCheck); + } + // Update update subscribers + if (_this.prev !== _this.current) { + _this.updateSubscribers.notify(_this.current); + } + // Update velocity subscribers + if (_this.velocityUpdateSubscribers.getSize()) { + _this.velocityUpdateSubscribers.notify(_this.getVelocity()); + } + // Update render subscribers + if (render) { + _this.renderSubscribers.notify(_this.current); } - Array.prototype.forEach.call(parent.children, function (node) { - if (elementsToKeep.has(node)) { - deep(node); - } else { - var attr = node.getAttribute(controlAttribute); - var alreadyHidden = attr !== null && attr !== 'false'; - var counterValue = (counterMap.get(node) || 0) + 1; - var markerValue = (markerCounter.get(node) || 0) + 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - hiddenNodes.push(node); - if (counterValue === 1 && alreadyHidden) { - uncontrolledNodes.set(node, true); - } - if (markerValue === 1) { - node.setAttribute(markerName, 'true'); - } - if (!alreadyHidden) { - node.setAttribute(controlAttribute, 'true'); - } - } - }); }; - deep(parentNode); - elementsToKeep.clear(); - lockCount++; - return function () { - hiddenNodes.forEach(function (node) { - var counterValue = counterMap.get(node) - 1; - var markerValue = markerCounter.get(node) - 1; - counterMap.set(node, counterValue); - markerCounter.set(node, markerValue); - if (!counterValue) { - if (!uncontrolledNodes.has(node)) { - node.removeAttribute(controlAttribute); - } - uncontrolledNodes.delete(node); - } - if (!markerValue) { - node.removeAttribute(markerName); - } - }); - lockCount--; - if (!lockCount) { - // clear - counterMap = new WeakMap(); - counterMap = new WeakMap(); - uncontrolledNodes = new WeakMap(); - markerMap = {}; + /** + * Schedule a velocity check for the next frame. + * + * This is an instanced and bound function to prevent generating a new + * function once per frame. + * + * @internal + */ + this.scheduleVelocityCheck = function () { + return sync__default["default"].postRender(_this.velocityCheck); + }; + /** + * Updates `prev` with `current` if the value hasn't been updated this frame. + * This ensures velocity calculations return `0`. + * + * This is an instanced and bound function to prevent generating a new + * function once per frame. + * + * @internal + */ + this.velocityCheck = function (_a) { + var timestamp = _a.timestamp; + if (timestamp !== _this.lastUpdated) { + _this.prev = _this.current; + _this.velocityUpdateSubscribers.notify(_this.getVelocity()); } }; - }; + this.hasAnimated = false; + this.prev = this.current = init; + this.canTrackVelocity = isFloat(this.current); + } /** - * Marks everything except given node(or nodes) as aria-hidden - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command + * Adds a function that will be notified when the `MotionValue` is updated. + * + * It returns a function that, when called, will cancel the subscription. + * + * When calling `onChange` inside a React component, it should be wrapped with the + * `useEffect` hook. As it returns an unsubscribe function, this should be returned + * from the `useEffect` function to ensure you don't add duplicate subscribers.. + * + * ```jsx + * export const MyComponent = () => { + * const x = useMotionValue(0) + * const y = useMotionValue(0) + * const opacity = useMotionValue(1) + * + * useEffect(() => { + * function updateOpacity() { + * const maxXY = Math.max(x.get(), y.get()) + * const newOpacity = transform(maxXY, [0, 100], [1, 0]) + * opacity.set(newOpacity) + * } + * + * const unsubscribeX = x.onChange(updateOpacity) + * const unsubscribeY = y.onChange(updateOpacity) + * + * return () => { + * unsubscribeX() + * unsubscribeY() + * } + * }, []) + * + * return + * } + * ``` + * + * @privateRemarks + * + * We could look into a `useOnChange` hook if the above lifecycle management proves confusing. + * + * ```jsx + * useOnChange(x, () => {}) + * ``` + * + * @param subscriber - A function that receives the latest value. + * @returns A function that, when called, will cancel this subscription. + * + * @public */ - var hideOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-aria-hidden'; - } - var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]); - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - // we should not hide ariaLive elements - https://github.com/theKashey/aria-hidden/issues/10 - targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live]'))); - return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden'); + MotionValue.prototype.onChange = function (subscription) { + return this.updateSubscribers.add(subscription); + }; + MotionValue.prototype.clearListeners = function () { + this.updateSubscribers.clear(); }; /** - * Marks everything except given node(or nodes) as inert - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command + * Adds a function that will be notified when the `MotionValue` requests a render. + * + * @param subscriber - A function that's provided the latest value. + * @returns A function that, when called, will cancel this subscription. + * + * @internal */ - exports.hideOthers = hideOthers; - var inertOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-inert-ed'; - } - var activeParentNode = parentNode || getDefaultParent(originalTarget); - if (!activeParentNode) { - return function () { - return null; - }; - } - return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert'); + MotionValue.prototype.onRenderRequest = function (subscription) { + // Render immediately + subscription(this.get()); + return this.renderSubscribers.add(subscription); }; /** - * @returns if current browser supports inert + * Attaches a passive effect to the `MotionValue`. + * + * @internal */ - exports.inertOthers = inertOthers; - var supportsInert = function () { - return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert'); + MotionValue.prototype.attach = function (passiveEffect) { + this.passiveEffect = passiveEffect; }; /** - * Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way - * @param {Element | Element[]} originalTarget - elements to keep on the page - * @param [parentNode] - top element, defaults to document.body - * @param {String} [markerName] - a special attribute to mark every node - * @return {Undo} undo command + * Sets the state of the `MotionValue`. + * + * @remarks + * + * ```jsx + * const x = useMotionValue(0) + * x.set(10) + * ``` + * + * @param latest - Latest value to set. + * @param render - Whether to notify render subscribers. Defaults to `true` + * + * @public */ - exports.supportsInert = supportsInert; - var suppressOthers = function (originalTarget, parentNode, markerName) { - if (markerName === void 0) { - markerName = 'data-suppressed'; + MotionValue.prototype.set = function (v, render) { + if (render === void 0) { + render = true; + } + if (!render || !this.passiveEffect) { + this.updateAndNotify(v, render); + } else { + this.passiveEffect(v, this.updateAndNotify); } - return (supportsInert() ? inertOthers : hideOthers)(originalTarget, parentNode, markerName); }; - exports.suppressOthers = suppressOthers; - - /***/ }), - - /***/ "../../../node_modules/clsx/dist/clsx.m.js": - /*!*************************************************!*\ - !*** ../../../node_modules/clsx/dist/clsx.m.js ***! - \*************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.clsx = clsx; - exports["default"] = void 0; - function r(e) { - var t, - f, - n = ""; - if ("string" == typeof e || "number" == typeof e) n += e;else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);else for (t in e) e[t] && (n && (n += " "), n += t); - return n; - } - function clsx() { - for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t); - return n; - } - var _default = exports["default"] = clsx; - - /***/ }), - - /***/ "../../../node_modules/copy-to-clipboard/index.js": - /*!********************************************************!*\ - !*** ../../../node_modules/copy-to-clipboard/index.js ***! - \********************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var deselectCurrent = __webpack_require__(/*! toggle-selection */ "../../../node_modules/toggle-selection/index.js"); - var clipboardToIE11Formatting = { - "text/plain": "Text", - "text/html": "Url", - "default": "Text" + /** + * Returns the latest state of `MotionValue` + * + * @returns - The latest state of `MotionValue` + * + * @public + */ + MotionValue.prototype.get = function () { + return this.current; }; - var defaultMessage = "Copy to clipboard: #{key}, Enter"; - function format(message) { - var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; - return message.replace(/#{\s*key\s*}/g, copyKey); - } - function copy(text, options) { - var debug, - message, - reselectPrevious, - range, - selection, - mark, - success = false; - if (!options) { - options = {}; + /** + * @public + */ + MotionValue.prototype.getPrevious = function () { + return this.prev; + }; + /** + * Returns the latest velocity of `MotionValue` + * + * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. + * + * @public + */ + MotionValue.prototype.getVelocity = function () { + // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful + return this.canTrackVelocity ? + // These casts could be avoided if parseFloat would be typed better + popmotion.velocityPerSecond(parseFloat(this.current) - parseFloat(this.prev), this.timeDelta) : 0; + }; + /** + * Registers a new animation to control this `MotionValue`. Only one + * animation can drive a `MotionValue` at one time. + * + * ```jsx + * value.start() + * ``` + * + * @param animation - A function that starts the provided animation + * + * @internal + */ + MotionValue.prototype.start = function (animation) { + var _this = this; + this.stop(); + return new Promise(function (resolve) { + _this.hasAnimated = true; + _this.stopAnimation = animation(resolve); + }).then(function () { + return _this.clearAnimation(); + }); + }; + /** + * Stop the currently active animation. + * + * @public + */ + MotionValue.prototype.stop = function () { + if (this.stopAnimation) this.stopAnimation(); + this.clearAnimation(); + }; + /** + * Returns `true` if this value is currently animating. + * + * @public + */ + MotionValue.prototype.isAnimating = function () { + return !!this.stopAnimation; + }; + MotionValue.prototype.clearAnimation = function () { + this.stopAnimation = null; + }; + /** + * Destroy and clean up subscribers to this `MotionValue`. + * + * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically + * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually + * created a `MotionValue` via the `motionValue` function. + * + * @public + */ + MotionValue.prototype.destroy = function () { + this.updateSubscribers.clear(); + this.renderSubscribers.clear(); + this.stop(); + }; + return MotionValue; +}(); +function motionValue(init) { + return new MotionValue(init); +} + +/** + * Tests a provided value against a ValueType + */ +var testValueType = function (v) { + return function (type) { + return type.test(v); + }; +}; + +/** + * ValueType for "auto" + */ +var auto = { + test: function (v) { + return v === "auto"; + }, + parse: function (v) { + return v; + } +}; + +/** + * A list of value types commonly used for dimensions + */ +var dimensionValueTypes = [styleValueTypes.number, styleValueTypes.px, styleValueTypes.percent, styleValueTypes.degrees, styleValueTypes.vw, styleValueTypes.vh, auto]; +/** + * Tests a dimensional value against the list of dimension ValueTypes + */ +var findDimensionValueType = function (v) { + return dimensionValueTypes.find(testValueType(v)); +}; + +/** + * A list of all ValueTypes + */ +var valueTypes = tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(dimensionValueTypes), false), [styleValueTypes.color, styleValueTypes.complex], false); +/** + * Tests a value against the list of ValueTypes + */ +var findValueType = function (v) { + return valueTypes.find(testValueType(v)); +}; + +/** + * Set VisualElement's MotionValue, creating a new MotionValue for it if + * it doesn't exist. + */ +function setMotionValue(visualElement, key, value) { + if (visualElement.hasValue(key)) { + visualElement.getValue(key).set(value); + } else { + visualElement.addValue(key, motionValue(value)); + } +} +function setTarget(visualElement, definition) { + var resolved = resolveVariant(visualElement, definition); + var _a = resolved ? visualElement.makeTargetAnimatable(resolved, false) : {}, + _b = _a.transitionEnd, + transitionEnd = _b === void 0 ? {} : _b; + _a.transition; + var target = tslib.__rest(_a, ["transitionEnd", "transition"]); + target = tslib.__assign(tslib.__assign({}, target), transitionEnd); + for (var key in target) { + var value = resolveFinalValueInKeyframes(target[key]); + setMotionValue(visualElement, key, value); + } +} +function setVariants(visualElement, variantLabels) { + var reversedLabels = tslib.__spreadArray([], tslib.__read(variantLabels), false).reverse(); + reversedLabels.forEach(function (key) { + var _a; + var variant = visualElement.getVariant(key); + variant && setTarget(visualElement, variant); + (_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach(function (child) { + setVariants(child, variantLabels); + }); + }); +} +function setValues(visualElement, definition) { + if (Array.isArray(definition)) { + return setVariants(visualElement, definition); + } else if (typeof definition === "string") { + return setVariants(visualElement, [definition]); + } else { + setTarget(visualElement, definition); + } +} +function checkTargetForNewValues(visualElement, target, origin) { + var _a, _b, _c; + var _d; + var newValueKeys = Object.keys(target).filter(function (key) { + return !visualElement.hasValue(key); + }); + var numNewValues = newValueKeys.length; + if (!numNewValues) return; + for (var i = 0; i < numNewValues; i++) { + var key = newValueKeys[i]; + var targetValue = target[key]; + var value = null; + /** + * If the target is a series of keyframes, we can use the first value + * in the array. If this first value is null, we'll still need to read from the DOM. + */ + if (Array.isArray(targetValue)) { + value = targetValue[0]; } - debug = options.debug || false; - try { - reselectPrevious = deselectCurrent(); - range = document.createRange(); - selection = document.getSelection(); - mark = document.createElement("span"); - mark.textContent = text; - // avoid screen readers from reading out loud the text - mark.ariaHidden = "true"; - // reset user styles for span element - mark.style.all = "unset"; - // prevents scrolling to the end of the page - mark.style.position = "fixed"; - mark.style.top = 0; - mark.style.clip = "rect(0, 0, 0, 0)"; - // used to preserve spaces and line breaks - mark.style.whiteSpace = "pre"; - // do not inherit user-select (it may be `none`) - mark.style.webkitUserSelect = "text"; - mark.style.MozUserSelect = "text"; - mark.style.msUserSelect = "text"; - mark.style.userSelect = "text"; - mark.addEventListener("copy", function (e) { - e.stopPropagation(); - if (options.format) { - e.preventDefault(); - if (typeof e.clipboardData === "undefined") { - // IE 11 - debug && console.warn("unable to use e.clipboardData"); - debug && console.warn("trying IE specific stuff"); - window.clipboardData.clearData(); - var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; - window.clipboardData.setData(format, text); - } else { - // all other browsers - e.clipboardData.clearData(); - e.clipboardData.setData(options.format, text); - } - } - if (options.onCopy) { - e.preventDefault(); - options.onCopy(e.clipboardData); - } + /** + * If the target isn't keyframes, or the first keyframe was null, we need to + * first check if an origin value was explicitly defined in the transition as "from", + * if not read the value from the DOM. As an absolute fallback, take the defined target value. + */ + if (value === null) { + value = (_b = (_a = origin[key]) !== null && _a !== void 0 ? _a : visualElement.readValue(key)) !== null && _b !== void 0 ? _b : target[key]; + } + /** + * If value is still undefined or null, ignore it. Preferably this would throw, + * but this was causing issues in Framer. + */ + if (value === undefined || value === null) continue; + if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) { + // If this is a number read as a string, ie "0" or "200", convert it to a number + value = parseFloat(value); + } else if (!findValueType(value) && styleValueTypes.complex.test(targetValue)) { + value = getAnimatableNone(key, targetValue); + } + visualElement.addValue(key, motionValue(value)); + (_c = (_d = origin)[key]) !== null && _c !== void 0 ? _c : _d[key] = value; + visualElement.setBaseTarget(key, value); + } +} +function getOriginFromTransition(key, transition) { + if (!transition) return; + var valueTransition = transition[key] || transition["default"] || transition; + return valueTransition.from; +} +function getOrigin(target, transition, visualElement) { + var _a, _b; + var origin = {}; + for (var key in target) { + origin[key] = (_a = getOriginFromTransition(key, transition)) !== null && _a !== void 0 ? _a : (_b = visualElement.getValue(key)) === null || _b === void 0 ? void 0 : _b.get(); + } + return origin; +} +function animateVisualElement(visualElement, definition, options) { + if (options === void 0) { + options = {}; + } + visualElement.notifyAnimationStart(definition); + var animation; + if (Array.isArray(definition)) { + var animations = definition.map(function (variant) { + return animateVariant(visualElement, variant, options); + }); + animation = Promise.all(animations); + } else if (typeof definition === "string") { + animation = animateVariant(visualElement, definition, options); + } else { + var resolvedDefinition = typeof definition === "function" ? resolveVariant(visualElement, definition, options.custom) : definition; + animation = animateTarget(visualElement, resolvedDefinition, options); + } + return animation.then(function () { + return visualElement.notifyAnimationComplete(definition); + }); +} +function animateVariant(visualElement, variant, options) { + var _a; + if (options === void 0) { + options = {}; + } + var resolved = resolveVariant(visualElement, variant, options.custom); + var _b = (resolved || {}).transition, + transition = _b === void 0 ? visualElement.getDefaultTransition() || {} : _b; + if (options.transitionOverride) { + transition = options.transitionOverride; + } + /** + * If we have a variant, create a callback that runs it as an animation. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + var getAnimation = resolved ? function () { + return animateTarget(visualElement, resolved, options); + } : function () { + return Promise.resolve(); + }; + /** + * If we have children, create a callback that runs all their animations. + * Otherwise, we resolve a Promise immediately for a composable no-op. + */ + var getChildAnimations = ((_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.size) ? function (forwardDelay) { + if (forwardDelay === void 0) { + forwardDelay = 0; + } + var _a = transition.delayChildren, + delayChildren = _a === void 0 ? 0 : _a, + staggerChildren = transition.staggerChildren, + staggerDirection = transition.staggerDirection; + return animateChildren(visualElement, variant, delayChildren + forwardDelay, staggerChildren, staggerDirection, options); + } : function () { + return Promise.resolve(); + }; + /** + * If the transition explicitly defines a "when" option, we need to resolve either + * this animation or all children animations before playing the other. + */ + var when = transition.when; + if (when) { + var _c = tslib.__read(when === "beforeChildren" ? [getAnimation, getChildAnimations] : [getChildAnimations, getAnimation], 2), + first = _c[0], + last = _c[1]; + return first().then(last); + } else { + return Promise.all([getAnimation(), getChildAnimations(options.delay)]); + } +} +/** + * @internal + */ +function animateTarget(visualElement, definition, _a) { + var _b; + var _c = _a === void 0 ? {} : _a, + _d = _c.delay, + delay = _d === void 0 ? 0 : _d, + transitionOverride = _c.transitionOverride, + type = _c.type; + var _e = visualElement.makeTargetAnimatable(definition), + _f = _e.transition, + transition = _f === void 0 ? visualElement.getDefaultTransition() : _f, + transitionEnd = _e.transitionEnd, + target = tslib.__rest(_e, ["transition", "transitionEnd"]); + if (transitionOverride) transition = transitionOverride; + var animations = []; + var animationTypeState = type && ((_b = visualElement.animationState) === null || _b === void 0 ? void 0 : _b.getState()[type]); + for (var key in target) { + var value = visualElement.getValue(key); + var valueTarget = target[key]; + if (!value || valueTarget === undefined || animationTypeState && shouldBlockAnimation(animationTypeState, key)) { + continue; + } + var valueTransition = tslib.__assign({ + delay: delay + }, transition); + /** + * Make animation instant if this is a transform prop and we should reduce motion. + */ + if (visualElement.shouldReduceMotion && isTransformProp(key)) { + valueTransition = tslib.__assign(tslib.__assign({}, valueTransition), { + type: false, + delay: 0 }); - document.body.appendChild(mark); - range.selectNodeContents(mark); - selection.addRange(range); - var successful = document.execCommand("copy"); - if (!successful) { - throw new Error("copy command was unsuccessful"); - } - success = true; - } catch (err) { - debug && console.error("unable to copy using execCommand: ", err); - debug && console.warn("trying IE specific stuff"); - try { - window.clipboardData.setData(options.format || "text", text); - options.onCopy && options.onCopy(window.clipboardData); - success = true; - } catch (err) { - debug && console.error("unable to copy using clipboardData: ", err); - debug && console.error("falling back to prompt"); - message = format("message" in options ? options.message : defaultMessage); - window.prompt(message, text); - } - } finally { - if (selection) { - if (typeof selection.removeRange == "function") { - selection.removeRange(range); - } else { - selection.removeAllRanges(); - } - } - if (mark) { - document.body.removeChild(mark); - } - reselectPrevious(); } - return success; + var animation = startAnimation(key, value, valueTarget, valueTransition); + animations.push(animation); } - module.exports = copy; - - /***/ }), - - /***/ "../../../node_modules/detect-node-es/esm/browser.js": - /*!***********************************************************!*\ - !*** ../../../node_modules/detect-node-es/esm/browser.js ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isNode = void 0; - const isNode = exports.isNode = false; - - /***/ }), - - /***/ "../../../node_modules/entities/lib/decode.js": - /*!****************************************************!*\ - !*** ../../../node_modules/entities/lib/decode.js ***! - \****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; + return Promise.all(animations).then(function () { + transitionEnd && setTarget(visualElement, transitionEnd); + }); +} +function animateChildren(visualElement, variant, delayChildren, staggerChildren, staggerDirection, options) { + if (delayChildren === void 0) { + delayChildren = 0; + } + if (staggerChildren === void 0) { + staggerChildren = 0; + } + if (staggerDirection === void 0) { + staggerDirection = 1; + } + var animations = []; + var maxStaggerDuration = (visualElement.variantChildren.size - 1) * staggerChildren; + var generateStaggerDuration = staggerDirection === 1 ? function (i) { + if (i === void 0) { + i = 0; + } + return i * staggerChildren; + } : function (i) { + if (i === void 0) { + i = 0; } - Object.defineProperty(o, k2, desc); - } : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; + return maxStaggerDuration - i * staggerChildren; + }; + Array.from(visualElement.variantChildren).sort(sortByTreeOrder).forEach(function (child, i) { + animations.push(animateVariant(child, variant, tslib.__assign(tslib.__assign({}, options), { + delay: delayChildren + generateStaggerDuration(i) + })).then(function () { + return child.notifyAnimationComplete(variant); + })); }); - var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); - } : function (o, v) { - o["default"] = v; + return Promise.all(animations); +} +function stopAnimation(visualElement) { + visualElement.forEachValue(function (value) { + return value.stop(); }); - var __importStar = void 0 && (void 0).__importStar || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - var __importDefault = void 0 && (void 0).__importDefault || function (mod) { - return mod && mod.__esModule ? mod : { - "default": mod - }; +} +function sortByTreeOrder(a, b) { + return a.sortNodePosition(b); +} +/** + * Decide whether we should block this animation. Previously, we achieved this + * just by checking whether the key was listed in protectedKeys, but this + * posed problems if an animation was triggered by afterChildren and protectedKeys + * had been set to true in the meantime. + */ +function shouldBlockAnimation(_a, key) { + var protectedKeys = _a.protectedKeys, + needsAnimating = _a.needsAnimating; + var shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; + needsAnimating[key] = false; + return shouldBlock; +} +var variantPriorityOrder = [exports.AnimationType.Animate, exports.AnimationType.InView, exports.AnimationType.Focus, exports.AnimationType.Hover, exports.AnimationType.Tap, exports.AnimationType.Drag, exports.AnimationType.Exit]; +var reversePriorityOrder = tslib.__spreadArray([], tslib.__read(variantPriorityOrder), false).reverse(); +var numAnimationTypes = variantPriorityOrder.length; +function animateList(visualElement) { + return function (animations) { + return Promise.all(animations.map(function (_a) { + var animation = _a.animation, + options = _a.options; + return animateVisualElement(visualElement, animation, options); + })); }; - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.decodeXML = exports.decodeHTMLStrict = exports.decodeHTMLAttribute = exports.decodeHTML = exports.determineBranch = exports.EntityDecoder = exports.DecodingMode = exports.BinTrieFlags = exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = void 0; - var decode_data_html_js_1 = __importDefault(__webpack_require__(/*! ./generated/decode-data-html.js */ "../../../node_modules/entities/lib/generated/decode-data-html.js")); - exports.htmlDecodeTree = decode_data_html_js_1.default; - var decode_data_xml_js_1 = __importDefault(__webpack_require__(/*! ./generated/decode-data-xml.js */ "../../../node_modules/entities/lib/generated/decode-data-xml.js")); - exports.xmlDecodeTree = decode_data_xml_js_1.default; - var decode_codepoint_js_1 = __importStar(__webpack_require__(/*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js")); - exports.decodeCodePoint = decode_codepoint_js_1.default; - var decode_codepoint_js_2 = __webpack_require__(/*! ./decode_codepoint.js */ "../../../node_modules/entities/lib/decode_codepoint.js"); - Object.defineProperty(exports, "replaceCodePoint", ({ - enumerable: true, - get: function () { - return decode_codepoint_js_2.replaceCodePoint; - } - })); - Object.defineProperty(exports, "fromCodePoint", ({ - enumerable: true, - get: function () { - return decode_codepoint_js_2.fromCodePoint; +} +function createAnimationState(visualElement) { + var animate = animateList(visualElement); + var state = createState(); + var allAnimatedKeys = {}; + var isInitialRender = true; + /** + * This function will be used to reduce the animation definitions for + * each active animation type into an object of resolved values for it. + */ + var buildResolvedTypeValues = function (acc, definition) { + var resolved = resolveVariant(visualElement, definition); + if (resolved) { + resolved.transition; + var transitionEnd = resolved.transitionEnd, + target = tslib.__rest(resolved, ["transition", "transitionEnd"]); + acc = tslib.__assign(tslib.__assign(tslib.__assign({}, acc), target), transitionEnd); } - })); - var CharCodes; - (function (CharCodes) { - CharCodes[CharCodes["NUM"] = 35] = "NUM"; - CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; - CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; - CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; - CharCodes[CharCodes["NINE"] = 57] = "NINE"; - CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; - CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; - CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; - CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; - CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; - CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; - CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; - })(CharCodes || (CharCodes = {})); - /** Bit that needs to be set to convert an upper case ASCII character to lower case */ - var TO_LOWER_BIT = 32; - var BinTrieFlags; - (function (BinTrieFlags) { - BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; - BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; - BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; - })(BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {})); - function isNumber(code) { - return code >= CharCodes.ZERO && code <= CharCodes.NINE; - } - function isHexadecimalCharacter(code) { - return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F; - } - function isAsciiAlphaNumeric(code) { - return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z || isNumber(code); + return acc; + }; + function isAnimated(key) { + return allAnimatedKeys[key] !== undefined; } /** - * Checks if the given character is a valid end character for an entity in an attribute. - * - * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. - * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state + * This just allows us to inject mocked animation functions + * @internal */ - function isEntityInAttributeInvalidEnd(code) { - return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); - } - var EntityDecoderState; - (function (EntityDecoderState) { - EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; - EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; - EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; - EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; - EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; - })(EntityDecoderState || (EntityDecoderState = {})); - var DecodingMode; - (function (DecodingMode) { - /** Entities in text nodes that can end with any character. */ - DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; - /** Only allow entities terminated with a semicolon. */ - DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; - /** Entities in attributes have limitations on ending characters. */ - DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; - })(DecodingMode = exports.DecodingMode || (exports.DecodingMode = {})); + function setAnimateFunction(makeAnimator) { + animate = makeAnimator(visualElement); + } /** - * Token decoder with support of writing partial entities. + * When we receive new props, we need to: + * 1. Create a list of protected keys for each type. This is a directory of + * value keys that are currently being "handled" by types of a higher priority + * so that whenever an animation is played of a given type, these values are + * protected from being animated. + * 2. Determine if an animation type needs animating. + * 3. Determine if any values have been removed from a type and figure out + * what to animate those to. */ - var EntityDecoder = /** @class */function () { - function EntityDecoder( /** The tree used to decode entities. */ - decodeTree, + function animateChanges(options, changedActiveType) { + var _a; + var props = visualElement.getProps(); + var context = visualElement.getVariantContext(true) || {}; /** - * The function that is called when a codepoint is decoded. - * - * For multi-byte named entities, this will be called multiple times, - * with the second codepoint, and the same `consumed` value. - * - * @param codepoint The decoded codepoint. - * @param consumed The number of bytes consumed by the decoder. + * A list of animations that we'll build into as we iterate through the animation + * types. This will get executed at the end of the function. */ - emitCodePoint, /** An object that is used to produce errors. */ - errors) { - this.decodeTree = decodeTree; - this.emitCodePoint = emitCodePoint; - this.errors = errors; - /** The current state of the decoder. */ - this.state = EntityDecoderState.EntityStart; - /** Characters that were consumed while parsing an entity. */ - this.consumed = 1; - /** - * The result of the entity. - * - * Either the result index of a numeric entity, or the codepoint of a - * numeric entity. - */ - this.result = 0; - /** The current index in the decode tree. */ - this.treeIndex = 0; - /** The number of characters that were consumed in excess. */ - this.excess = 1; - /** The mode in which the decoder is operating. */ - this.decodeMode = DecodingMode.Strict; - } - /** Resets the instance to make it reusable. */ - EntityDecoder.prototype.startEntity = function (decodeMode) { - this.decodeMode = decodeMode; - this.state = EntityDecoderState.EntityStart; - this.result = 0; - this.treeIndex = 0; - this.excess = 1; - this.consumed = 1; - }; + var animations = []; /** - * Write an entity to the decoder. This can be called multiple times with partial entities. - * If the entity is incomplete, the decoder will return -1. - * - * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the - * entity is incomplete, and resume when the next string is written. - * - * @param string The string containing the entity (or a continuation of the entity). - * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + * Keep track of which values have been removed. Then, as we hit lower priority + * animation types, we can check if they contain removed values and animate to that. */ - EntityDecoder.prototype.write = function (str, offset) { - switch (this.state) { - case EntityDecoderState.EntityStart: - { - if (str.charCodeAt(offset) === CharCodes.NUM) { - this.state = EntityDecoderState.NumericStart; - this.consumed += 1; - return this.stateNumericStart(str, offset + 1); - } - this.state = EntityDecoderState.NamedEntity; - return this.stateNamedEntity(str, offset); - } - case EntityDecoderState.NumericStart: - { - return this.stateNumericStart(str, offset); - } - case EntityDecoderState.NumericDecimal: - { - return this.stateNumericDecimal(str, offset); - } - case EntityDecoderState.NumericHex: - { - return this.stateNumericHex(str, offset); - } - case EntityDecoderState.NamedEntity: - { - return this.stateNamedEntity(str, offset); - } - } - }; + var removedKeys = new Set(); /** - * Switches between the numeric decimal and hexadecimal states. - * - * Equivalent to the `Numeric character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + * A dictionary of all encountered keys. This is an object to let us build into and + * copy it without iteration. Each time we hit an animation type we set its protected + * keys - the keys its not allowed to animate - to the latest version of this object. */ - EntityDecoder.prototype.stateNumericStart = function (str, offset) { - if (offset >= str.length) { - return -1; - } - if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { - this.state = EntityDecoderState.NumericHex; - this.consumed += 1; - return this.stateNumericHex(str, offset + 1); - } - this.state = EntityDecoderState.NumericDecimal; - return this.stateNumericDecimal(str, offset); - }; - EntityDecoder.prototype.addToNumericResult = function (str, start, end, base) { - if (start !== end) { - var digitCount = end - start; - this.result = this.result * Math.pow(base, digitCount) + parseInt(str.substr(start, digitCount), base); - this.consumed += digitCount; - } - }; + var encounteredKeys = {}; /** - * Parses a hexadecimal numeric entity. - * - * Equivalent to the `Hexademical character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + * If a variant has been removed at a given index, and this component is controlling + * variant animations, we want to ensure lower-priority variants are forced to animate. */ - EntityDecoder.prototype.stateNumericHex = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char) || isHexadecimalCharacter(char)) { - offset += 1; - } else { - this.addToNumericResult(str, startIdx, offset, 16); - return this.emitNumericEntity(char, 3); - } + var removedVariantIndex = Infinity; + var _loop_1 = function (i) { + var type = reversePriorityOrder[i]; + var typeState = state[type]; + var prop = (_a = props[type]) !== null && _a !== void 0 ? _a : context[type]; + var propIsVariant = isVariantLabel(prop); + /** + * If this type has *just* changed isActive status, set activeDelta + * to that status. Otherwise set to null. + */ + var activeDelta = type === changedActiveType ? typeState.isActive : null; + if (activeDelta === false) removedVariantIndex = i; + /** + * If this prop is an inherited variant, rather than been set directly on the + * component itself, we want to make sure we allow the parent to trigger animations. + * + * TODO: Can probably change this to a !isControllingVariants check + */ + var isInherited = prop === context[type] && prop !== props[type] && propIsVariant; + /** + * + */ + if (isInherited && isInitialRender && visualElement.manuallyAnimateOnMount) { + isInherited = false; } - this.addToNumericResult(str, startIdx, offset, 16); - return -1; - }; - /** - * Parses a decimal numeric entity. - * - * Equivalent to the `Decimal character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - EntityDecoder.prototype.stateNumericDecimal = function (str, offset) { - var startIdx = offset; - while (offset < str.length) { - var char = str.charCodeAt(offset); - if (isNumber(char)) { - offset += 1; + /** + * Set all encountered keys so far as the protected keys for this type. This will + * be any key that has been animated or otherwise handled by active, higher-priortiy types. + */ + typeState.protectedKeys = tslib.__assign({}, encounteredKeys); + // Check if we can skip analysing this prop early + if ( + // If it isn't active and hasn't *just* been set as inactive + !typeState.isActive && activeDelta === null || + // If we didn't and don't have any defined prop for this animation type + !prop && !typeState.prevProp || + // Or if the prop doesn't define an animation + isAnimationControls(prop) || typeof prop === "boolean") { + return "continue"; + } + /** + * As we go look through the values defined on this type, if we detect + * a changed value or a value that was removed in a higher priority, we set + * this to true and add this prop to the animation list. + */ + var variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); + var shouldAnimateType = variantDidChange || + // If we're making this variant active, we want to always make it active + type === changedActiveType && typeState.isActive && !isInherited && propIsVariant || + // If we removed a higher-priority variant (i is in reverse order) + i > removedVariantIndex && propIsVariant; + /** + * As animations can be set as variant lists, variants or target objects, we + * coerce everything to an array if it isn't one already + */ + var definitionList = Array.isArray(prop) ? prop : [prop]; + /** + * Build an object of all the resolved values. We'll use this in the subsequent + * animateChanges calls to determine whether a value has changed. + */ + var resolvedValues = definitionList.reduce(buildResolvedTypeValues, {}); + if (activeDelta === false) resolvedValues = {}; + /** + * Now we need to loop through all the keys in the prev prop and this prop, + * and decide: + * 1. If the value has changed, and needs animating + * 2. If it has been removed, and needs adding to the removedKeys set + * 3. If it has been removed in a higher priority type and needs animating + * 4. If it hasn't been removed in a higher priority but hasn't changed, and + * needs adding to the type's protectedKeys list. + */ + var _b = typeState.prevResolvedValues, + prevResolvedValues = _b === void 0 ? {} : _b; + var allKeys = tslib.__assign(tslib.__assign({}, prevResolvedValues), resolvedValues); + var markToAnimate = function (key) { + shouldAnimateType = true; + removedKeys.delete(key); + typeState.needsAnimating[key] = true; + }; + for (var key in allKeys) { + var next = resolvedValues[key]; + var prev = prevResolvedValues[key]; + // If we've already handled this we can just skip ahead + if (encounteredKeys.hasOwnProperty(key)) continue; + /** + * If the value has changed, we probably want to animate it. + */ + if (next !== prev) { + /** + * If both values are keyframes, we need to shallow compare them to + * detect whether any value has changed. If it has, we animate it. + */ + if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { + if (!shallowCompare(next, prev) || variantDidChange) { + markToAnimate(key); + } else { + /** + * If it hasn't changed, we want to ensure it doesn't animate by + * adding it to the list of protected keys. + */ + typeState.protectedKeys[key] = true; + } + } else if (next !== undefined) { + // If next is defined and doesn't equal prev, it needs animating + markToAnimate(key); + } else { + // If it's undefined, it's been removed. + removedKeys.add(key); + } + } else if (next !== undefined && removedKeys.has(key)) { + /** + * If next hasn't changed and it isn't undefined, we want to check if it's + * been removed by a higher priority + */ + markToAnimate(key); } else { - this.addToNumericResult(str, startIdx, offset, 10); - return this.emitNumericEntity(char, 2); + /** + * If it hasn't changed, we add it to the list of protected values + * to ensure it doesn't get animated. + */ + typeState.protectedKeys[key] = true; } } - this.addToNumericResult(str, startIdx, offset, 10); - return -1; - }; - /** - * Validate and emit a numeric entity. - * - * Implements the logic from the `Hexademical character reference start - * state` and `Numeric character reference end state` in the HTML spec. - * - * @param lastCp The last code point of the entity. Used to see if the - * entity was terminated with a semicolon. - * @param expectedLength The minimum number of characters that should be - * consumed. Used to validate that at least one digit - * was consumed. - * @returns The number of characters that were consumed. - */ - EntityDecoder.prototype.emitNumericEntity = function (lastCp, expectedLength) { - var _a; - // Ensure we consumed at least one digit. - if (this.consumed <= expectedLength) { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; + /** + * Update the typeState so next time animateChanges is called we can compare the + * latest prop and resolvedValues to these. + */ + typeState.prevProp = prop; + typeState.prevResolvedValues = resolvedValues; + /** + * + */ + if (typeState.isActive) { + encounteredKeys = tslib.__assign(tslib.__assign({}, encounteredKeys), resolvedValues); } - // Figure out if this is a legit end of the entity - if (lastCp === CharCodes.SEMI) { - this.consumed += 1; - } else if (this.decodeMode === DecodingMode.Strict) { - return 0; + if (isInitialRender && visualElement.blockInitialAnimation) { + shouldAnimateType = false; } - this.emitCodePoint((0, decode_codepoint_js_1.replaceCodePoint)(this.result), this.consumed); - if (this.errors) { - if (lastCp !== CharCodes.SEMI) { - this.errors.missingSemicolonAfterCharacterReference(); - } - this.errors.validateNumericCharacterReference(this.result); + /** + * If this is an inherited prop we want to hard-block animations + * TODO: Test as this should probably still handle animations triggered + * by removed values? + */ + if (shouldAnimateType && !isInherited) { + animations.push.apply(animations, tslib.__spreadArray([], tslib.__read(definitionList.map(function (animation) { + return { + animation: animation, + options: tslib.__assign({ + type: type + }, options) + }; + })), false)); } - return this.consumed; }; /** - * Parses a named entity. - * - * Equivalent to the `Named character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + * Iterate through all animation types in reverse priority order. For each, we want to + * detect which values it's handling and whether or not they've changed (and therefore + * need to be animated). If any values have been removed, we want to detect those in + * lower priority props and flag for animation. */ - EntityDecoder.prototype.stateNamedEntity = function (str, offset) { - var decodeTree = this.decodeTree; - var current = decodeTree[this.treeIndex]; - // The mask is the number of bytes of the value, including the current byte. - var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - for (; offset < str.length; offset++, this.excess++) { - var char = str.charCodeAt(offset); - this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); - if (this.treeIndex < 0) { - return this.result === 0 || - // If we are parsing an attribute - this.decodeMode === DecodingMode.Attribute && ( - // We shouldn't have consumed any characters after the entity, - valueLength === 0 || - // And there should be no invalid characters. - isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity(); - } - current = decodeTree[this.treeIndex]; - valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - // If the branch is a value, store it and continue - if (valueLength !== 0) { - // If the entity is terminated by a semicolon, we are done. - if (char === CharCodes.SEMI) { - return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); - } - // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. - if (this.decodeMode !== DecodingMode.Strict) { - this.result = this.treeIndex; - this.consumed += this.excess; - this.excess = 0; - } - } - } - return -1; - }; + for (var i = 0; i < numAnimationTypes; i++) { + _loop_1(i); + } + allAnimatedKeys = tslib.__assign({}, encounteredKeys); /** - * Emit a named entity that was not terminated with a semicolon. - * - * @returns The number of characters consumed. + * If there are some removed value that haven't been dealt with, + * we need to create a new animation that falls back either to the value + * defined in the style prop, or the last read value. */ - EntityDecoder.prototype.emitNotTerminatedNamedEntity = function () { + if (removedKeys.size) { + var fallbackAnimation_1 = {}; + removedKeys.forEach(function (key) { + var fallbackTarget = visualElement.getBaseTarget(key); + if (fallbackTarget !== undefined) { + fallbackAnimation_1[key] = fallbackTarget; + } + }); + animations.push({ + animation: fallbackAnimation_1 + }); + } + var shouldAnimate = Boolean(animations.length); + if (isInitialRender && props.initial === false && !visualElement.manuallyAnimateOnMount) { + shouldAnimate = false; + } + isInitialRender = false; + return shouldAnimate ? animate(animations) : Promise.resolve(); + } + /** + * Change whether a certain animation type is active. + */ + function setActive(type, isActive, options) { + var _a; + // If the active state hasn't changed, we can safely do nothing here + if (state[type].isActive === isActive) return Promise.resolve(); + // Propagate active change to children + (_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach(function (child) { var _a; - var _b = this, - result = _b.result, - decodeTree = _b.decodeTree; - var valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; - this.emitNamedEntityData(result, valueLength, this.consumed); - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); - return this.consumed; - }; + return (_a = child.animationState) === null || _a === void 0 ? void 0 : _a.setActive(type, isActive); + }); + state[type].isActive = isActive; + var animations = animateChanges(options, type); + for (var key in state) { + state[key].protectedKeys = {}; + } + return animations; + } + return { + isAnimated: isAnimated, + animateChanges: animateChanges, + setActive: setActive, + setAnimateFunction: setAnimateFunction, + getState: function () { + return state; + } + }; +} +function checkVariantsDidChange(prev, next) { + if (typeof next === "string") { + return next !== prev; + } else if (isVariantLabels(next)) { + return !shallowCompare(next, prev); + } + return false; +} +function createTypeState(isActive) { + if (isActive === void 0) { + isActive = false; + } + return { + isActive: isActive, + protectedKeys: {}, + needsAnimating: {}, + prevResolvedValues: {} + }; +} +function createState() { + var _a; + return _a = {}, _a[exports.AnimationType.Animate] = createTypeState(true), _a[exports.AnimationType.InView] = createTypeState(), _a[exports.AnimationType.Hover] = createTypeState(), _a[exports.AnimationType.Tap] = createTypeState(), _a[exports.AnimationType.Drag] = createTypeState(), _a[exports.AnimationType.Focus] = createTypeState(), _a[exports.AnimationType.Exit] = createTypeState(), _a; +} +var animations = { + animation: makeRenderlessComponent(function (_a) { + var visualElement = _a.visualElement, + animate = _a.animate; /** - * Emit a named entity. - * - * @param result The index of the entity in the decode tree. - * @param valueLength The number of bytes in the entity. - * @param consumed The number of characters consumed. - * - * @returns The number of characters consumed. + * We dynamically generate the AnimationState manager as it contains a reference + * to the underlying animation library. We only want to load that if we load this, + * so people can optionally code split it out using the `m` component. */ - EntityDecoder.prototype.emitNamedEntityData = function (result, valueLength, consumed) { - var decodeTree = this.decodeTree; - this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed); - if (valueLength === 3) { - // For multi-byte values, we need to emit the second byte. - this.emitCodePoint(decodeTree[result + 2], consumed); - } - return consumed; - }; + visualElement.animationState || (visualElement.animationState = createAnimationState(visualElement)); /** - * Signal to the parser that the end of the input was reached. - * - * Remaining data will be emitted and relevant errors will be produced. - * - * @returns The number of characters consumed. + * Subscribe any provided AnimationControls to the component's VisualElement */ - EntityDecoder.prototype.end = function () { - var _a; - switch (this.state) { - case EntityDecoderState.NamedEntity: - { - // Emit a named entity if we have one. - return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0; - } - // Otherwise, emit a numeric entity if we have one. - case EntityDecoderState.NumericDecimal: - { - return this.emitNumericEntity(0, 2); - } - case EntityDecoderState.NumericHex: - { - return this.emitNumericEntity(0, 3); - } - case EntityDecoderState.NumericStart: - { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - case EntityDecoderState.EntityStart: - { - // Return 0 if we have no entity. - return 0; - } - } + if (isAnimationControls(animate)) { + React.useEffect(function () { + return animate.subscribe(visualElement); + }, [animate]); + } + }), + exit: makeRenderlessComponent(function (props) { + var custom = props.custom, + visualElement = props.visualElement; + var _a = tslib.__read(usePresence(), 2), + isPresent = _a[0], + safeToRemove = _a[1]; + var presenceContext = React.useContext(PresenceContext); + React.useEffect(function () { + var _a, _b; + visualElement.isPresent = isPresent; + var animation = (_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Exit, !isPresent, { + custom: (_b = presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.custom) !== null && _b !== void 0 ? _b : custom + }); + !isPresent && (animation === null || animation === void 0 ? void 0 : animation.then(safeToRemove)); + }, [isPresent]); + }) +}; + +/** + * @internal + */ +var PanSession = /** @class */function () { + function PanSession(event, handlers, _a) { + var _this = this; + var _b = _a === void 0 ? {} : _a, + transformPagePoint = _b.transformPagePoint; + /** + * @internal + */ + this.startEvent = null; + /** + * @internal + */ + this.lastMoveEvent = null; + /** + * @internal + */ + this.lastMoveEventInfo = null; + /** + * @internal + */ + this.handlers = {}; + this.updatePoint = function () { + if (!(_this.lastMoveEvent && _this.lastMoveEventInfo)) return; + var info = getPanInfo(_this.lastMoveEventInfo, _this.history); + var isPanStarted = _this.startEvent !== null; + // Only start panning if the offset is larger than 3 pixels. If we make it + // any larger than this we'll want to reset the pointer history + // on the first update to avoid visual snapping to the cursoe. + var isDistancePastThreshold = popmotion.distance(info.offset, { + x: 0, + y: 0 + }) >= 3; + if (!isPanStarted && !isDistancePastThreshold) return; + var point = info.point; + var timestamp = sync.getFrameData().timestamp; + _this.history.push(tslib.__assign(tslib.__assign({}, point), { + timestamp: timestamp + })); + var _a = _this.handlers, + onStart = _a.onStart, + onMove = _a.onMove; + if (!isPanStarted) { + onStart && onStart(_this.lastMoveEvent, info); + _this.startEvent = _this.lastMoveEvent; + } + onMove && onMove(_this.lastMoveEvent, info); }; - return EntityDecoder; - }(); - exports.EntityDecoder = EntityDecoder; - /** - * Creates a function that decodes entities in a string. - * - * @param decodeTree The decode tree. - * @returns A function that decodes entities in a string. - */ - function getDecoder(decodeTree) { - var ret = ""; - var decoder = new EntityDecoder(decodeTree, function (str) { - return ret += (0, decode_codepoint_js_1.fromCodePoint)(str); - }); - return function decodeWithTrie(str, decodeMode) { - var lastIndex = 0; - var offset = 0; - while ((offset = str.indexOf("&", offset)) >= 0) { - ret += str.slice(lastIndex, offset); - decoder.startEntity(decodeMode); - var len = decoder.write(str, - // Skip the "&" - offset + 1); - if (len < 0) { - lastIndex = offset + decoder.end(); - break; - } - lastIndex = offset + len; - // If `len` is 0, skip the current `&` and continue. - offset = len === 0 ? lastIndex + 1 : lastIndex; + this.handlePointerMove = function (event, info) { + _this.lastMoveEvent = event; + _this.lastMoveEventInfo = transformPoint(info, _this.transformPagePoint); + // Because Safari doesn't trigger mouseup events when it's above a `` - if (isMouseEvent(event) && event.buttons === 0) { - _this.handlePointerUp(event, info); - return; - } - // Throttle mouse move event to once per frame - sync__default["default"].update(_this.updatePoint, true); - }; - this.handlePointerUp = function (event, info) { - _this.end(); - var _a = _this.handlers, - onEnd = _a.onEnd, - onSessionEnd = _a.onSessionEnd; - var panInfo = getPanInfo(transformPoint(info, _this.transformPagePoint), _this.history); - if (_this.startEvent && onEnd) { - onEnd(event, panInfo); - } - onSessionEnd && onSessionEnd(event, panInfo); - }; - // If we have more than one touch, don't start detecting this gesture - if (isTouchEvent(event) && event.touches.length > 1) return; - this.handlers = handlers; - this.transformPagePoint = transformPagePoint; - var info = extractEventInfo(event); - var initialInfo = transformPoint(info, this.transformPagePoint); - var point = initialInfo.point; - var timestamp = sync.getFrameData().timestamp; - this.history = [tslib.__assign(tslib.__assign({}, point), { - timestamp: timestamp - })]; - var onSessionStart = handlers.onSessionStart; - onSessionStart && onSessionStart(event, getPanInfo(initialInfo, this.history)); - this.removeListeners = popmotion.pipe(addPointerEvent(window, "pointermove", this.handlePointerMove), addPointerEvent(window, "pointerup", this.handlePointerUp), addPointerEvent(window, "pointercancel", this.handlePointerUp)); + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); } - PanSession.prototype.updateHandlers = function (handlers) { - this.handlers = handlers; - }; - PanSession.prototype.end = function () { - this.removeListeners && this.removeListeners(); - sync.cancelSync.update(this.updatePoint); - }; - return PanSession; - }(); - function transformPoint(info, transformPagePoint) { - return transformPagePoint ? { - point: transformPagePoint(info.point) - } : info; } - function subtractPoint(a, b) { - return { - x: a.x - b.x, - y: a.y - b.y - }; + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function getPanInfo(_a, history) { - var point = _a.point; - return { - point: point, - delta: subtractPoint(point, lastDevicePoint(history)), - offset: subtractPoint(point, startDevicePoint(history)), - velocity: getVelocity(history, 0.1) - }; + function fulfill(value) { + resume("next", value); } - function startDevicePoint(history) { - return history[0]; + function reject(value) { + resume("throw", value); } - function lastDevicePoint(history) { - return history[history.length - 1]; + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - function getVelocity(history, timeDelta) { - if (history.length < 2) { +}; + +/** This file is the entry point for browsers, re-export common elements. */ + +/** + * Creates a disposable GraphQL over WebSocket client. + * + * @category Client + */ +function createClient(options) { + const { + url, + connectionParams, + lazy = true, + onNonLazyError = console.error, + lazyCloseTimeout: lazyCloseTimeoutMs = 0, + keepAlive = 0, + disablePong, + connectionAckWaitTimeout = 0, + retryAttempts = 5, + retryWait = async function randomisedExponentialBackoff(retries) { + let retryDelay = 1000; // start with 1s delay + for (let i = 0; i < retries; i++) { + retryDelay *= 2; + } + await new Promise(resolve => setTimeout(resolve, retryDelay + + // add random timeout from 300ms to 3s + Math.floor(Math.random() * (3000 - 300) + 300))); + }, + shouldRetry = isLikeCloseEvent, + isFatalConnectionProblem, + on, + webSocketImpl, + /** + * Generates a v4 UUID to be used as the ID using `Math` + * as the random number generator. Supply your own generator + * in case you need more uniqueness. + * + * Reference: https://gist.github.com/jed/982883 + */ + generateID = function generateUUID() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { + const r = Math.random() * 16 | 0, + v = c == 'x' ? r : r & 0x3 | 0x8; + return v.toString(16); + }); + }, + jsonMessageReplacer: replacer, + jsonMessageReviver: reviver + } = options; + let ws; + if (webSocketImpl) { + if (!isWebSocket(webSocketImpl)) { + throw new Error('Invalid WebSocket implementation provided'); + } + ws = webSocketImpl; + } else if (typeof WebSocket !== 'undefined') { + ws = WebSocket; + } else if (typeof __webpack_require__.g !== 'undefined') { + ws = __webpack_require__.g.WebSocket || + // @ts-expect-error: Support more browsers + __webpack_require__.g.MozWebSocket; + } else if (typeof window !== 'undefined') { + ws = window.WebSocket || + // @ts-expect-error: Support more browsers + window.MozWebSocket; + } + if (!ws) throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`"); + const WebSocketImpl = ws; + // websocket status emitter, subscriptions are handled differently + const emitter = (() => { + const message = (() => { + const listeners = {}; return { - x: 0, - y: 0 + on(id, listener) { + listeners[id] = listener; + return () => { + delete listeners[id]; + }; + }, + emit(message) { + var _a; + if ('id' in message) (_a = listeners[message.id]) === null || _a === void 0 ? void 0 : _a.call(listeners, message); + } }; - } - var i = history.length - 1; - var timestampedPoint = null; - var lastPoint = lastDevicePoint(history); - while (i >= 0) { - timestampedPoint = history[i]; - if (lastPoint.timestamp - timestampedPoint.timestamp > secondsToMilliseconds(timeDelta)) { - break; - } - i--; - } - if (!timestampedPoint) { - return { - x: 0, - y: 0 - }; - } - var time = (lastPoint.timestamp - timestampedPoint.timestamp) / 1000; - if (time === 0) { - return { - x: 0, - y: 0 - }; - } - var currentVelocity = { - x: (lastPoint.x - timestampedPoint.x) / time, - y: (lastPoint.y - timestampedPoint.y) / time - }; - if (currentVelocity.x === Infinity) { - currentVelocity.x = 0; - } - if (currentVelocity.y === Infinity) { - currentVelocity.y = 0; - } - return currentVelocity; - } - function calcLength(axis) { - return axis.max - axis.min; - } - function isNear(value, target, maxDistance) { - if (target === void 0) { - target = 0; - } - if (maxDistance === void 0) { - maxDistance = 0.01; - } - return popmotion.distance(value, target) < maxDistance; - } - function calcAxisDelta(delta, source, target, origin) { - if (origin === void 0) { - origin = 0.5; - } - delta.origin = origin; - delta.originPoint = popmotion.mix(source.min, source.max, delta.origin); - delta.scale = calcLength(target) / calcLength(source); - if (isNear(delta.scale, 1, 0.0001) || isNaN(delta.scale)) delta.scale = 1; - delta.translate = popmotion.mix(target.min, target.max, delta.origin) - delta.originPoint; - if (isNear(delta.translate) || isNaN(delta.translate)) delta.translate = 0; - } - function calcBoxDelta(delta, source, target, origin) { - calcAxisDelta(delta.x, source.x, target.x, origin === null || origin === void 0 ? void 0 : origin.originX); - calcAxisDelta(delta.y, source.y, target.y, origin === null || origin === void 0 ? void 0 : origin.originY); - } - function calcRelativeAxis(target, relative, parent) { - target.min = parent.min + relative.min; - target.max = target.min + calcLength(relative); - } - function calcRelativeBox(target, relative, parent) { - calcRelativeAxis(target.x, relative.x, parent.x); - calcRelativeAxis(target.y, relative.y, parent.y); - } - function calcRelativeAxisPosition(target, layout, parent) { - target.min = layout.min - parent.min; - target.max = target.min + calcLength(layout); - } - function calcRelativePosition(target, layout, parent) { - calcRelativeAxisPosition(target.x, layout.x, parent.x); - calcRelativeAxisPosition(target.y, layout.y, parent.y); - } - - /** - * Apply constraints to a point. These constraints are both physical along an - * axis, and an elastic factor that determines how much to constrain the point - * by if it does lie outside the defined parameters. - */ - function applyConstraints(point, _a, elastic) { - var min = _a.min, - max = _a.max; - if (min !== undefined && point < min) { - // If we have a min point defined, and this is outside of that, constrain - point = elastic ? popmotion.mix(min, point, elastic.min) : Math.max(point, min); - } else if (max !== undefined && point > max) { - // If we have a max point defined, and this is outside of that, constrain - point = elastic ? popmotion.mix(max, point, elastic.max) : Math.min(point, max); - } - return point; - } - /** - * Calculate constraints in terms of the viewport when defined relatively to the - * measured axis. This is measured from the nearest edge, so a max constraint of 200 - * on an axis with a max value of 300 would return a constraint of 500 - axis length - */ - function calcRelativeAxisConstraints(axis, min, max) { - return { - min: min !== undefined ? axis.min + min : undefined, - max: max !== undefined ? axis.max + max - (axis.max - axis.min) : undefined - }; - } - /** - * Calculate constraints in terms of the viewport when - * defined relatively to the measured bounding box. - */ - function calcRelativeConstraints(layoutBox, _a) { - var top = _a.top, - left = _a.left, - bottom = _a.bottom, - right = _a.right; - return { - x: calcRelativeAxisConstraints(layoutBox.x, left, right), - y: calcRelativeAxisConstraints(layoutBox.y, top, bottom) - }; - } - /** - * Calculate viewport constraints when defined as another viewport-relative axis - */ - function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { - var _a; - var min = constraintsAxis.min - layoutAxis.min; - var max = constraintsAxis.max - layoutAxis.max; - // If the constraints axis is actually smaller than the layout axis then we can - // flip the constraints - if (constraintsAxis.max - constraintsAxis.min < layoutAxis.max - layoutAxis.min) { - _a = tslib.__read([max, min], 2), min = _a[0], max = _a[1]; - } - return { - min: min, - max: max - }; - } - /** - * Calculate viewport constraints when defined as another viewport-relative box - */ - function calcViewportConstraints(layoutBox, constraintsBox) { - return { - x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), - y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y) - }; - } - /** - * Calculate a transform origin relative to the source axis, between 0-1, that results - * in an asthetically pleasing scale/transform needed to project from source to target. - */ - function calcOrigin(source, target) { - var origin = 0.5; - var sourceLength = calcLength(source); - var targetLength = calcLength(target); - if (targetLength > sourceLength) { - origin = popmotion.progress(target.min, target.max - sourceLength, source.min); - } else if (sourceLength > targetLength) { - origin = popmotion.progress(source.min, source.max - targetLength, target.min); - } - return popmotion.clamp(0, 1, origin); - } - /** - * Rebase the calculated viewport constraints relative to the layout.min point. - */ - function rebaseAxisConstraints(layout, constraints) { - var relativeConstraints = {}; - if (constraints.min !== undefined) { - relativeConstraints.min = constraints.min - layout.min; - } - if (constraints.max !== undefined) { - relativeConstraints.max = constraints.max - layout.min; - } - return relativeConstraints; - } - var defaultElastic = 0.35; - /** - * Accepts a dragElastic prop and returns resolved elastic values for each axis. - */ - function resolveDragElastic(dragElastic) { - if (dragElastic === void 0) { - dragElastic = defaultElastic; - } - if (dragElastic === false) { - dragElastic = 0; - } else if (dragElastic === true) { - dragElastic = defaultElastic; - } - return { - x: resolveAxisElastic(dragElastic, "left", "right"), - y: resolveAxisElastic(dragElastic, "top", "bottom") - }; - } - function resolveAxisElastic(dragElastic, minLabel, maxLabel) { - return { - min: resolvePointElastic(dragElastic, minLabel), - max: resolvePointElastic(dragElastic, maxLabel) - }; - } - function resolvePointElastic(dragElastic, label) { - var _a; - return typeof dragElastic === "number" ? dragElastic : (_a = dragElastic[label]) !== null && _a !== void 0 ? _a : 0; - } - var createAxisDelta = function () { - return { - translate: 0, - scale: 1, - origin: 0, - originPoint: 0 - }; - }; - var createDelta = function () { - return { - x: createAxisDelta(), - y: createAxisDelta() - }; - }; - var createAxis = function () { - return { - min: 0, - max: 0 - }; - }; - var createBox = function () { - return { - x: createAxis(), - y: createAxis() + })(); + const listeners = { + connecting: (on === null || on === void 0 ? void 0 : on.connecting) ? [on.connecting] : [], + opened: (on === null || on === void 0 ? void 0 : on.opened) ? [on.opened] : [], + connected: (on === null || on === void 0 ? void 0 : on.connected) ? [on.connected] : [], + ping: (on === null || on === void 0 ? void 0 : on.ping) ? [on.ping] : [], + pong: (on === null || on === void 0 ? void 0 : on.pong) ? [on.pong] : [], + message: (on === null || on === void 0 ? void 0 : on.message) ? [message.emit, on.message] : [message.emit], + closed: (on === null || on === void 0 ? void 0 : on.closed) ? [on.closed] : [], + error: (on === null || on === void 0 ? void 0 : on.error) ? [on.error] : [] }; - }; - function eachAxis(callback) { - return [callback("x"), callback("y")]; - } - - /** - * Bounding boxes tend to be defined as top, left, right, bottom. For various operations - * it's easier to consider each axis individually. This function returns a bounding box - * as a map of single-axis min/max values. - */ - function convertBoundingBoxToBox(_a) { - var top = _a.top, - left = _a.left, - right = _a.right, - bottom = _a.bottom; return { - x: { - min: left, - max: right + onMessage: message.on, + on(event, listener) { + const l = listeners[event]; + l.push(listener); + return () => { + l.splice(l.indexOf(listener), 1); + }; }, - y: { - min: top, - max: bottom + emit(event, ...args) { + // we copy the listeners so that unlistens dont "pull the rug under our feet" + for (const listener of [...listeners[event]]) { + // @ts-expect-error: The args should fit + listener(...args); + } } }; - } - function convertBoxToBoundingBox(_a) { - var x = _a.x, - y = _a.y; - return { - top: y.min, - right: x.max, - bottom: y.max, - left: x.min - }; - } - /** - * Applies a TransformPoint function to a bounding box. TransformPoint is usually a function - * provided by Framer to allow measured points to be corrected for device scaling. This is used - * when measuring DOM elements and DOM event points. - */ - function transformBoxPoints(point, transformPoint) { - if (!transformPoint) return point; - var topLeft = transformPoint({ - x: point.left, - y: point.top - }); - var bottomRight = transformPoint({ - x: point.right, - y: point.bottom - }); - return { - top: topLeft.y, - left: topLeft.x, - bottom: bottomRight.y, - right: bottomRight.x - }; - } - function isIdentityScale(scale) { - return scale === undefined || scale === 1; - } - function hasScale(_a) { - var scale = _a.scale, - scaleX = _a.scaleX, - scaleY = _a.scaleY; - return !isIdentityScale(scale) || !isIdentityScale(scaleX) || !isIdentityScale(scaleY); - } - function hasTransform(values) { - return hasScale(values) || hasTranslate(values.x) || hasTranslate(values.y) || values.z || values.rotate || values.rotateX || values.rotateY; - } - function hasTranslate(value) { - return value && value !== "0%"; - } - - /** - * Scales a point based on a factor and an originPoint - */ - function scalePoint(point, scale, originPoint) { - var distanceFromOrigin = point - originPoint; - var scaled = scale * distanceFromOrigin; - return originPoint + scaled; - } - /** - * Applies a translate/scale delta to a point - */ - function applyPointDelta(point, translate, scale, originPoint, boxScale) { - if (boxScale !== undefined) { - point = scalePoint(point, boxScale, originPoint); - } - return scalePoint(point, scale, originPoint) + translate; - } - /** - * Applies a translate/scale delta to an axis - */ - function applyAxisDelta(axis, translate, scale, originPoint, boxScale) { - if (translate === void 0) { - translate = 0; - } - if (scale === void 0) { - scale = 1; - } - axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale); - axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale); - } - /** - * Applies a translate/scale delta to a box - */ - function applyBoxDelta(box, _a) { - var x = _a.x, - y = _a.y; - applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); - applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); - } - /** - * Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms - * in a tree upon our box before then calculating how to project it into our desired viewport-relative box - * - * This is the final nested loop within updateLayoutDelta for future refactoring - */ - function applyTreeDeltas(box, treeScale, treePath, isSharedTransition) { - var _a, _b; - if (isSharedTransition === void 0) { - isSharedTransition = false; - } - var treeLength = treePath.length; - if (!treeLength) return; - // Reset the treeScale - treeScale.x = treeScale.y = 1; - var node; - var delta; - for (var i = 0; i < treeLength; i++) { - node = treePath[i]; - delta = node.projectionDelta; - if (((_b = (_a = node.instance) === null || _a === void 0 ? void 0 : _a.style) === null || _b === void 0 ? void 0 : _b.display) === "contents") continue; - if (isSharedTransition && node.options.layoutScroll && node.scroll && node !== node.root) { - transformBox(box, { - x: -node.scroll.x, - y: -node.scroll.y - }); - } - if (delta) { - // Incoporate each ancestor's scale into a culmulative treeScale for this component - treeScale.x *= delta.x.scale; - treeScale.y *= delta.y.scale; - // Apply each ancestor's calculated delta into this component's recorded layout box - applyBoxDelta(box, delta); + })(); + // invokes the callback either when an error or closed event is emitted, + // first one that gets called prevails, other emissions are ignored + function errorOrClosed(cb) { + const listening = [ + // errors are fatal and more critical than close events, throw them first + emitter.on('error', err => { + listening.forEach(unlisten => unlisten()); + cb(err); + }), + // closes can be graceful and not fatal, throw them second (if error didnt throw) + emitter.on('closed', event => { + listening.forEach(unlisten => unlisten()); + cb(event); + })]; + } + let connecting, + locks = 0, + lazyCloseTimeout, + retrying = false, + retries = 0, + disposed = false; + async function connect() { + // clear the lazy close timeout immediatelly so that close gets debounced + // see: https://github.com/enisdenjo/graphql-ws/issues/388 + clearTimeout(lazyCloseTimeout); + const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : connecting = new Promise((connected, denied) => (async () => { + if (retrying) { + await retryWait(retries); + // subscriptions might complete while waiting for retry + if (!locks) { + connecting = undefined; + return denied({ + code: 1000, + reason: 'All Subscriptions Gone' + }); + } + retries++; } - if (isSharedTransition && hasTransform(node.latestValues)) { - transformBox(box, node.latestValues); + emitter.emit('connecting'); + const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, _common.GRAPHQL_TRANSPORT_WS_PROTOCOL); + let connectionAckTimeout, queuedPing; + function enqueuePing() { + if (isFinite(keepAlive) && keepAlive > 0) { + clearTimeout(queuedPing); // in case where a pong was received before a ping (this is valid behaviour) + queuedPing = setTimeout(() => { + if (socket.readyState === WebSocketImpl.OPEN) { + socket.send((0, _common.stringifyMessage)({ + type: _common.MessageType.Ping + })); + emitter.emit('ping', false, undefined); + } + }, keepAlive); + } } - } - } - function translateAxis(axis, distance) { - axis.min = axis.min + distance; - axis.max = axis.max + distance; - } - /** - * Apply a transform to an axis from the latest resolved motion values. - * This function basically acts as a bridge between a flat motion value map - * and applyAxisDelta - */ - function transformAxis(axis, transforms, _a) { - var _b = tslib.__read(_a, 3), - key = _b[0], - scaleKey = _b[1], - originKey = _b[2]; - var axisOrigin = transforms[originKey] !== undefined ? transforms[originKey] : 0.5; - var originPoint = popmotion.mix(axis.min, axis.max, axisOrigin); - // Apply the axis delta to the final axis - applyAxisDelta(axis, transforms[key], transforms[scaleKey], originPoint, transforms.scale); - } - /** - * The names of the motion values we want to apply as translation, scale and origin. - */ - var xKeys$1 = ["x", "scaleX", "originX"]; - var yKeys$1 = ["y", "scaleY", "originY"]; - /** - * Apply a transform to a box from the latest resolved motion values. - */ - function transformBox(box, transform) { - transformAxis(box.x, transform, xKeys$1); - transformAxis(box.y, transform, yKeys$1); - } - function measureViewportBox(instance, transformPoint) { - return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint)); - } - function measurePageBox(element, rootProjectionNode, transformPagePoint) { - var viewportBox = measureViewportBox(element, transformPagePoint); - var scroll = rootProjectionNode.scroll; - if (scroll) { - translateAxis(viewportBox.x, scroll.x); - translateAxis(viewportBox.y, scroll.y); - } - return viewportBox; - } - var elementDragControls = new WeakMap(); - /** - * - */ - // let latestPointerEvent: AnyPointerEvent - var VisualElementDragControls = /** @class */function () { - function VisualElementDragControls(visualElement) { - // This is a reference to the global drag gesture lock, ensuring only one component - // can "capture" the drag of one or both axes. - // TODO: Look into moving this into pansession? - this.openGlobalLock = null; - this.isDragging = false; - this.currentDirection = null; - this.originPoint = { - x: 0, - y: 0 - }; - /** - * The permitted boundaries of travel, in pixels. - */ - this.constraints = false; - this.hasMutatedConstraints = false; - /** - * The per-axis resolved elastic values. - */ - this.elastic = createBox(); - this.visualElement = visualElement; - } - VisualElementDragControls.prototype.start = function (originEvent, _a) { - var _this = this; - var _b = _a === void 0 ? {} : _a, - _c = _b.snapToCursor, - snapToCursor = _c === void 0 ? false : _c; - /** - * Don't start dragging if this component is exiting - */ - if (this.visualElement.isPresent === false) return; - var onSessionStart = function (event) { - // Stop any animations on both axis values immediately. This allows the user to throw and catch - // the component. - _this.stopAnimation(); - if (snapToCursor) { - _this.snapToCursor(extractEventInfo(event, "page").point); + errorOrClosed(errOrEvent => { + connecting = undefined; + clearTimeout(connectionAckTimeout); + clearTimeout(queuedPing); + denied(errOrEvent); + if (isLikeCloseEvent(errOrEvent) && errOrEvent.code === 4499) { + socket.close(4499, 'Terminated'); // close event is artificial and emitted manually, see `Client.terminate()` below + socket.onerror = null; + socket.onclose = null; } - }; - var onStart = function (event, info) { - var _a; - // Attempt to grab the global drag gesture lock - maybe make this part of PanSession - var _b = _this.getProps(), - drag = _b.drag, - dragPropagation = _b.dragPropagation, - onDragStart = _b.onDragStart; - if (drag && !dragPropagation) { - if (_this.openGlobalLock) _this.openGlobalLock(); - _this.openGlobalLock = getGlobalLock(drag); - // If we don 't have the lock, don't start dragging - if (!_this.openGlobalLock) return; - } - _this.isDragging = true; - _this.currentDirection = null; - _this.resolveConstraints(); - if (_this.visualElement.projection) { - _this.visualElement.projection.isAnimationBlocked = true; - _this.visualElement.projection.target = undefined; + }); + socket.onerror = err => emitter.emit('error', err); + socket.onclose = event => emitter.emit('closed', event); + socket.onopen = async () => { + try { + emitter.emit('opened', socket); + const payload = typeof connectionParams === 'function' ? await connectionParams() : connectionParams; + // connectionParams might take too long causing the server to kick off the client + // the necessary error/close event is already reported - simply stop execution + if (socket.readyState !== WebSocketImpl.OPEN) return; + socket.send((0, _common.stringifyMessage)(payload ? { + type: _common.MessageType.ConnectionInit, + payload + } : { + type: _common.MessageType.ConnectionInit + // payload is completely absent if not provided + }, replacer)); + if (isFinite(connectionAckWaitTimeout) && connectionAckWaitTimeout > 0) { + connectionAckTimeout = setTimeout(() => { + socket.close(_common.CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout'); + }, connectionAckWaitTimeout); + } + enqueuePing(); // enqueue ping (noop if disabled) + } catch (err) { + emitter.emit('error', err); + socket.close(_common.CloseCode.InternalClientError, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Internal client error')); } - /** - * Record gesture origin - */ - eachAxis(function (axis) { - var _a, _b; - var current = _this.getAxisMotionValue(axis).get() || 0; - /** - * If the MotionValue is a percentage value convert to px - */ - if (styleValueTypes.percent.test(current)) { - var measuredAxis = (_b = (_a = _this.visualElement.projection) === null || _a === void 0 ? void 0 : _a.layout) === null || _b === void 0 ? void 0 : _b.actual[axis]; - if (measuredAxis) { - var length_1 = calcLength(measuredAxis); - current = length_1 * (parseFloat(current) / 100); - } - } - _this.originPoint[axis] = current; - }); - // Fire onDragStart event - onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(event, info); - (_a = _this.visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(exports.AnimationType.Drag, true); }; - var onMove = function (event, info) { - // latestPointerEvent = event - var _a = _this.getProps(), - dragPropagation = _a.dragPropagation, - dragDirectionLock = _a.dragDirectionLock, - onDirectionLock = _a.onDirectionLock, - onDrag = _a.onDrag; - // If we didn't successfully receive the gesture lock, early return. - if (!dragPropagation && !_this.openGlobalLock) return; - var offset = info.offset; - // Attempt to detect drag direction if directionLock is true - if (dragDirectionLock && _this.currentDirection === null) { - _this.currentDirection = getCurrentDirection(offset); - // If we've successfully set a direction, notify listener - if (_this.currentDirection !== null) { - onDirectionLock === null || onDirectionLock === void 0 ? void 0 : onDirectionLock(_this.currentDirection); + let acknowledged = false; + socket.onmessage = ({ + data + }) => { + try { + const message = (0, _common.parseMessage)(data, reviver); + emitter.emit('message', message); + if (message.type === 'ping' || message.type === 'pong') { + emitter.emit(message.type, true, message.payload); // received + if (message.type === 'pong') { + enqueuePing(); // enqueue next ping (noop if disabled) + } else if (!disablePong) { + // respond with pong on ping + socket.send((0, _common.stringifyMessage)(message.payload ? { + type: _common.MessageType.Pong, + payload: message.payload + } : { + type: _common.MessageType.Pong + // payload is completely absent if not provided + })); + emitter.emit('pong', false, message.payload); + } + return; // ping and pongs can be received whenever } - return; + if (acknowledged) return; // already connected and acknowledged + if (message.type !== _common.MessageType.ConnectionAck) throw new Error(`First message cannot be of type ${message.type}`); + clearTimeout(connectionAckTimeout); + acknowledged = true; + emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged + retrying = false; // future lazy connects are not retries + retries = 0; // reset the retries on connect + connected([socket, new Promise((_, reject) => errorOrClosed(reject))]); + } catch (err) { + socket.onmessage = null; // stop reading messages as soon as reading breaks once + emitter.emit('error', err); + socket.close(_common.CloseCode.BadResponse, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Bad response')); } - // Update each point with the latest position - _this.updateAxis("x", info.point, offset); - _this.updateAxis("y", info.point, offset); - /** - * Ideally we would leave the renderer to fire naturally at the end of - * this frame but if the element is about to change layout as the result - * of a re-render we want to ensure the browser can read the latest - * bounding box to ensure the pointer and element don't fall out of sync. - */ - _this.visualElement.syncRender(); - /** - * This must fire after the syncRender call as it might trigger a state - * change which itself might trigger a layout update. - */ - onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, info); }; - var onSessionEnd = function (event, info) { - return _this.stop(event, info); - }; - this.panSession = new PanSession(originEvent, { - onSessionStart: onSessionStart, - onStart: onStart, - onMove: onMove, - onSessionEnd: onSessionEnd - }, { - transformPagePoint: this.visualElement.getTransformPagePoint() - }); - }; - VisualElementDragControls.prototype.stop = function (event, info) { - var isDragging = this.isDragging; - this.cancel(); - if (!isDragging) return; - var velocity = info.velocity; - this.startAnimation(velocity); - var onDragEnd = this.getProps().onDragEnd; - onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd(event, info); - }; - VisualElementDragControls.prototype.cancel = function () { - var _a, _b; - this.isDragging = false; - if (this.visualElement.projection) { - this.visualElement.projection.isAnimationBlocked = false; - } - (_a = this.panSession) === null || _a === void 0 ? void 0 : _a.end(); - this.panSession = undefined; - var dragPropagation = this.getProps().dragPropagation; - if (!dragPropagation && this.openGlobalLock) { - this.openGlobalLock(); - this.openGlobalLock = null; - } - (_b = this.visualElement.animationState) === null || _b === void 0 ? void 0 : _b.setActive(exports.AnimationType.Drag, false); + })())); + // if the provided socket is in a closing state, wait for the throw on close + if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose; + let release = () => { + // releases this connection }; - VisualElementDragControls.prototype.updateAxis = function (axis, _point, offset) { - var drag = this.getProps().drag; - // If we're not dragging this axis, do an early return. - if (!offset || !shouldDrag(axis, drag, this.currentDirection)) return; - var axisValue = this.getAxisMotionValue(axis); - var next = this.originPoint[axis] + offset[axis]; - // Apply constraints - if (this.constraints && this.constraints[axis]) { - next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); - } - axisValue.set(next); - }; - VisualElementDragControls.prototype.resolveConstraints = function () { - var _this = this; - var _a = this.getProps(), - dragConstraints = _a.dragConstraints, - dragElastic = _a.dragElastic; - var layout = (this.visualElement.projection || {}).layout; - var prevConstraints = this.constraints; - if (dragConstraints && isRefObject(dragConstraints)) { - if (!this.constraints) { - this.constraints = this.resolveRefConstraints(); - } - } else { - if (dragConstraints && layout) { - this.constraints = calcRelativeConstraints(layout.actual, dragConstraints); + const released = new Promise(resolve => release = resolve); + return [socket, release, Promise.race([ + // wait for + released.then(() => { + if (!locks) { + // and if no more locks are present, complete the connection + const complete = () => socket.close(1000, 'Normal Closure'); + if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) { + // if the keepalive is set, allow for the specified calmdown time and + // then complete if the socket is still open. + lazyCloseTimeout = setTimeout(() => { + if (socket.readyState === WebSocketImpl.OPEN) complete(); + }, lazyCloseTimeoutMs); } else { - this.constraints = false; + // otherwise complete immediately + complete(); } } - this.elastic = resolveDragElastic(dragElastic); - /** - * If we're outputting to external MotionValues, we want to rebase the measured constraints - * from viewport-relative to component-relative. - */ - if (prevConstraints !== this.constraints && layout && this.constraints && !this.hasMutatedConstraints) { - eachAxis(function (axis) { - if (_this.getAxisMotionValue(axis)) { - _this.constraints[axis] = rebaseAxisConstraints(layout.actual[axis], _this.constraints[axis]); + }), + // or + throwOnClose])]; + } + /** + * Checks the `connect` problem and evaluates if the client should retry. + */ + function shouldRetryConnectOrThrow(errOrCloseEvent) { + // some close codes are worth reporting immediately + if (isLikeCloseEvent(errOrCloseEvent) && (isFatalInternalCloseCode(errOrCloseEvent.code) || [_common.CloseCode.InternalServerError, _common.CloseCode.InternalClientError, _common.CloseCode.BadRequest, _common.CloseCode.BadResponse, _common.CloseCode.Unauthorized, + // CloseCode.Forbidden, might grant access out after retry + _common.CloseCode.SubprotocolNotAcceptable, + // CloseCode.ConnectionInitialisationTimeout, might not time out after retry + // CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry + _common.CloseCode.SubscriberAlreadyExists, _common.CloseCode.TooManyInitialisationRequests + // 4499, // Terminated, probably because the socket froze, we want to retry + ].includes(errOrCloseEvent.code))) throw errOrCloseEvent; + // client was disposed, no retries should proceed regardless + if (disposed) return false; + // normal closure (possibly all subscriptions have completed) + // if no locks were acquired in the meantime, shouldnt try again + if (isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1000) return locks > 0; + // retries are not allowed or we tried to many times, report error + if (!retryAttempts || retries >= retryAttempts) throw errOrCloseEvent; + // throw non-retryable connection problems + if (!shouldRetry(errOrCloseEvent)) throw errOrCloseEvent; + // @deprecated throw fatal connection problems immediately + if (isFatalConnectionProblem === null || isFatalConnectionProblem === void 0 ? void 0 : isFatalConnectionProblem(errOrCloseEvent)) throw errOrCloseEvent; + // looks good, start retrying + return retrying = true; + } + // in non-lazy (hot?) mode always hold one connection lock to persist the socket + if (!lazy) { + (async () => { + locks++; + for (;;) { + try { + const [,, throwOnClose] = await connect(); + await throwOnClose; // will always throw because releaser is not used + } catch (errOrCloseEvent) { + try { + if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; + } catch (errOrCloseEvent) { + // report thrown error, no further retries + return onNonLazyError === null || onNonLazyError === void 0 ? void 0 : onNonLazyError(errOrCloseEvent); } - }); - } - }; - VisualElementDragControls.prototype.resolveRefConstraints = function () { - var _a = this.getProps(), - constraints = _a.dragConstraints, - onMeasureDragConstraints = _a.onMeasureDragConstraints; - if (!constraints || !isRefObject(constraints)) return false; - var constraintsElement = constraints.current; - heyListen.invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop."); - var projection = this.visualElement.projection; - // TODO - if (!projection || !projection.layout) return false; - var constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); - var measuredConstraints = calcViewportConstraints(projection.layout.actual, constraintsBox); - /** - * If there's an onMeasureDragConstraints listener we call it and - * if different constraints are returned, set constraints to that - */ - if (onMeasureDragConstraints) { - var userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); - this.hasMutatedConstraints = !!userConstraints; - if (userConstraints) { - measuredConstraints = convertBoundingBoxToBox(userConstraints); } } - return measuredConstraints; - }; - VisualElementDragControls.prototype.startAnimation = function (velocity) { - var _this = this; - var _a = this.getProps(), - drag = _a.drag, - dragMomentum = _a.dragMomentum, - dragElastic = _a.dragElastic, - dragTransition = _a.dragTransition, - dragSnapToOrigin = _a.dragSnapToOrigin, - onDragTransitionEnd = _a.onDragTransitionEnd; - var constraints = this.constraints || {}; - var momentumAnimations = eachAxis(function (axis) { - var _a; - if (!shouldDrag(axis, drag, _this.currentDirection)) { - return; - } - var transition = (_a = constraints === null || constraints === void 0 ? void 0 : constraints[axis]) !== null && _a !== void 0 ? _a : {}; - if (dragSnapToOrigin) transition = { - min: 0, - max: 0 + })(); + } + return { + on: emitter.on, + subscribe(payload, sink) { + const id = generateID(payload); + let done = false, + errored = false, + releaser = () => { + // for handling completions before connect + locks--; + done = true; }; - /** - * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame - * of spring animations so we should look into adding a disable spring option to `inertia`. - * We could do something here where we affect the `bounceStiffness` and `bounceDamping` - * using the value of `dragElastic`. - */ - var bounceStiffness = dragElastic ? 200 : 1000000; - var bounceDamping = dragElastic ? 40 : 10000000; - var inertia = tslib.__assign(tslib.__assign({ - type: "inertia", - velocity: dragMomentum ? velocity[axis] : 0, - bounceStiffness: bounceStiffness, - bounceDamping: bounceDamping, - timeConstant: 750, - restDelta: 1, - restSpeed: 10 - }, dragTransition), transition); - // If we're not animating on an externally-provided `MotionValue` we can use the - // component's animation controls which will handle interactions with whileHover (etc), - // otherwise we just have to animate the `MotionValue` itself. - return _this.startAxisValueAnimation(axis, inertia); - }); - // Run all animations and then resolve the new drag constraints. - return Promise.all(momentumAnimations).then(onDragTransitionEnd); - }; - VisualElementDragControls.prototype.startAxisValueAnimation = function (axis, transition) { - var axisValue = this.getAxisMotionValue(axis); - return startAnimation(axis, axisValue, 0, transition); - }; - VisualElementDragControls.prototype.stopAnimation = function () { - var _this = this; - eachAxis(function (axis) { - return _this.getAxisMotionValue(axis).stop(); - }); - }; - /** - * Drag works differently depending on which props are provided. - * - * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. - * - Otherwise, we apply the delta to the x/y motion values. - */ - VisualElementDragControls.prototype.getAxisMotionValue = function (axis) { - var _a, _b; - var dragKey = "_drag" + axis.toUpperCase(); - var externalMotionValue = this.visualElement.getProps()[dragKey]; - return externalMotionValue ? externalMotionValue : this.visualElement.getValue(axis, (_b = (_a = this.visualElement.getProps().initial) === null || _a === void 0 ? void 0 : _a[axis]) !== null && _b !== void 0 ? _b : 0); - }; - VisualElementDragControls.prototype.snapToCursor = function (point) { - var _this = this; - eachAxis(function (axis) { - var drag = _this.getProps().drag; - // If we're not dragging this axis, do an early return. - if (!shouldDrag(axis, drag, _this.currentDirection)) return; - var projection = _this.visualElement.projection; - var axisValue = _this.getAxisMotionValue(axis); - if (projection && projection.layout) { - var _a = projection.layout.actual[axis], - min = _a.min, - max = _a.max; - axisValue.set(point[axis] - popmotion.mix(min, max, 0.5)); - } - }); - }; - /** - * When the viewport resizes we want to check if the measured constraints - * have changed and, if so, reposition the element within those new constraints - * relative to where it was before the resize. - */ - VisualElementDragControls.prototype.scalePositionWithinConstraints = function () { - var _this = this; - var _a; - var _b = this.getProps(), - drag = _b.drag, - dragConstraints = _b.dragConstraints; - var projection = this.visualElement.projection; - if (!isRefObject(dragConstraints) || !projection || !this.constraints) return; - /** - * Stop current animations as there can be visual glitching if we try to do - * this mid-animation - */ - this.stopAnimation(); - /** - * Record the relative position of the dragged element relative to the - * constraints box and save as a progress value. - */ - var boxProgress = { - x: 0, - y: 0 + (async () => { + locks++; + for (;;) { + try { + const [socket, release, waitForReleaseOrThrowOnClose] = await connect(); + // if done while waiting for connect, release the connection lock right away + if (done) return release(); + const unlisten = emitter.onMessage(id, message => { + switch (message.type) { + case _common.MessageType.Next: + { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- payload will fit type + sink.next(message.payload); + return; + } + case _common.MessageType.Error: + { + errored = true, done = true; + sink.error(message.payload); + releaser(); + return; + } + case _common.MessageType.Complete: + { + done = true; + releaser(); // release completes the sink + return; + } + } + }); + socket.send((0, _common.stringifyMessage)({ + id, + type: _common.MessageType.Subscribe, + payload + }, replacer)); + releaser = () => { + if (!done && socket.readyState === WebSocketImpl.OPEN) + // if not completed already and socket is open, send complete message to server on release + socket.send((0, _common.stringifyMessage)({ + id, + type: _common.MessageType.Complete + }, replacer)); + locks--; + done = true; + release(); + }; + // either the releaser will be called, connection completed and + // the promise resolved or the socket closed and the promise rejected. + // whatever happens though, we want to stop listening for messages + await waitForReleaseOrThrowOnClose.finally(unlisten); + return; // completed, shouldnt try again + } catch (errOrCloseEvent) { + if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; + } + } + })().then(() => { + // delivering either an error or a complete terminates the sequence + if (!errored) sink.complete(); + }) // resolves on release or normal closure + .catch(err => { + sink.error(err); + }); // rejects on close events and errors + return () => { + // dispose only of active subscriptions + if (!done) releaser(); }; - eachAxis(function (axis) { - var axisValue = _this.getAxisMotionValue(axis); - if (axisValue) { - var latest = axisValue.get(); - boxProgress[axis] = calcOrigin({ - min: latest, - max: latest - }, _this.constraints[axis]); + }, + iterate(request) { + const pending = []; + const deferred = { + done: false, + error: null, + resolve: () => { + // noop + } + }; + const dispose = this.subscribe(request, { + next(val) { + pending.push(val); + deferred.resolve(); + }, + error(err) { + deferred.done = true; + deferred.error = err; + deferred.resolve(); + }, + complete() { + deferred.done = true; + deferred.resolve(); } }); - /** - * Update the layout of this element and resolve the latest drag constraints - */ - var transformTemplate = this.visualElement.getProps().transformTemplate; - this.visualElement.getInstance().style.transform = transformTemplate ? transformTemplate({}, "") : "none"; - (_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll(); - projection.updateLayout(); - this.resolveConstraints(); - /** - * For each axis, calculate the current progress of the layout axis - * within the new constraints. - */ - eachAxis(function (axis) { - if (!shouldDrag(axis, drag, null)) return; - /** - * Calculate a new transform based on the previous box progress - */ - var axisValue = _this.getAxisMotionValue(axis); - var _a = _this.constraints[axis], - min = _a.min, - max = _a.max; - axisValue.set(popmotion.mix(min, max, boxProgress[axis])); + const iterator = function iterator() { + return __asyncGenerator(this, arguments, function* iterator_1() { + for (;;) { + if (!pending.length) { + // only wait if there are no pending messages available + yield __await(new Promise(resolve => deferred.resolve = resolve)); + } + // first flush + while (pending.length) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + yield yield __await(pending.shift()); + } + // then error + if (deferred.error) { + throw deferred.error; + } + // or complete + if (deferred.done) { + return yield __await(void 0); + } + } + }); + }(); + iterator.throw = async err => { + if (!deferred.done) { + deferred.done = true; + deferred.error = err; + deferred.resolve(); + } + return { + done: true, + value: undefined + }; + }; + iterator.return = async () => { + dispose(); + return { + done: true, + value: undefined + }; + }; + return iterator; + }, + async dispose() { + disposed = true; + if (connecting) { + // if there is a connection, close it + const [socket] = await connecting; + socket.close(1000, 'Normal Closure'); + } + }, + terminate() { + if (connecting) { + // only if there is a connection + emitter.emit('closed', { + code: 4499, + reason: 'Terminated', + wasClean: false + }); + } + } + }; +} +function isLikeCloseEvent(val) { + return (0, _utils.isObject)(val) && 'code' in val && 'reason' in val; +} +function isFatalInternalCloseCode(code) { + if ([1000, 1001, 1006, 1005, 1012, 1013, 1013 // Bad Gateway + ].includes(code)) return false; + // all other internal errors are fatal + return code >= 1000 && code <= 1999; +} +function isWebSocket(val) { + return typeof val === 'function' && 'constructor' in val && 'CLOSED' in val && 'CLOSING' in val && 'CONNECTING' in val && 'OPEN' in val; +} + +/***/ }), + +/***/ "../../../node_modules/graphql-ws/lib/common.mjs": +/*!*******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/common.mjs ***! + \*******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.MessageType = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.CloseCode = void 0; +exports.isMessage = isMessage; +exports.parseMessage = parseMessage; +exports.stringifyMessage = stringifyMessage; +exports.validateMessage = validateMessage; +var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); +/** + * + * common + * + */ + +/** + * The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). + * + * @category Common + */ +const GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws'; +/** + * The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws). + * + * @private + */ +const DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws'; +/** + * `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). + * + * @category Common + */ +var CloseCode; +(function (CloseCode) { + CloseCode[CloseCode["InternalServerError"] = 4500] = "InternalServerError"; + CloseCode[CloseCode["InternalClientError"] = 4005] = "InternalClientError"; + CloseCode[CloseCode["BadRequest"] = 4400] = "BadRequest"; + CloseCode[CloseCode["BadResponse"] = 4004] = "BadResponse"; + /** Tried subscribing before connect ack */ + CloseCode[CloseCode["Unauthorized"] = 4401] = "Unauthorized"; + CloseCode[CloseCode["Forbidden"] = 4403] = "Forbidden"; + CloseCode[CloseCode["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable"; + CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout"; + CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout"; + /** Subscriber distinction is very important */ + CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists"; + CloseCode[CloseCode["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests"; +})(CloseCode || (exports.CloseCode = CloseCode = {})); +/** + * Types of messages allowed to be sent by the client/server over the WS protocol. + * + * @category Common + */ +var MessageType; +(function (MessageType) { + MessageType["ConnectionInit"] = "connection_init"; + MessageType["ConnectionAck"] = "connection_ack"; + MessageType["Ping"] = "ping"; + MessageType["Pong"] = "pong"; + MessageType["Subscribe"] = "subscribe"; + MessageType["Next"] = "next"; + MessageType["Error"] = "error"; + MessageType["Complete"] = "complete"; +})(MessageType || (exports.MessageType = MessageType = {})); +/** + * Validates the message against the GraphQL over WebSocket Protocol. + * + * Invalid messages will throw descriptive errors. + * + * @category Common + */ +function validateMessage(val) { + if (!(0, _utils.isObject)(val)) { + throw new Error(`Message is expected to be an object, but got ${(0, _utils.extendedTypeof)(val)}`); + } + if (!val.type) { + throw new Error(`Message is missing the 'type' property`); + } + if (typeof val.type !== 'string') { + throw new Error(`Message is expects the 'type' property to be a string, but got ${(0, _utils.extendedTypeof)(val.type)}`); + } + switch (val.type) { + case MessageType.ConnectionInit: + case MessageType.ConnectionAck: + case MessageType.Ping: + case MessageType.Pong: + { + if (val.payload != null && !(0, _utils.isObject)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${val.payload}"`); + } + break; + } + case MessageType.Subscribe: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + if (!(0, _utils.isObject)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); + } + if (typeof val.payload.query !== 'string') { + throw new Error(`"${val.type}" message payload expects the 'query' property to be a string, but got ${(0, _utils.extendedTypeof)(val.payload.query)}`); + } + if (val.payload.variables != null && !(0, _utils.isObject)(val.payload.variables)) { + throw new Error(`"${val.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.variables)}`); + } + if (val.payload.operationName != null && (0, _utils.extendedTypeof)(val.payload.operationName) !== 'string') { + throw new Error(`"${val.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.operationName)}`); + } + if (val.payload.extensions != null && !(0, _utils.isObject)(val.payload.extensions)) { + throw new Error(`"${val.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.extensions)}`); + } + break; + } + case MessageType.Next: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + if (!(0, _utils.isObject)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); + } + break; + } + case MessageType.Error: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + if (!(0, _utils.areGraphQLErrors)(val.payload)) { + throw new Error(`"${val.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(val.payload)}`); + } + break; + } + case MessageType.Complete: + { + if (typeof val.id !== 'string') { + throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); + } + if (!val.id) { + throw new Error(`"${val.type}" message requires a non-empty 'id' property`); + } + break; + } + default: + throw new Error(`Invalid message 'type' property "${val.type}"`); + } + return val; +} +/** + * Checks if the provided value is a valid GraphQL over WebSocket message. + * + * @deprecated Use `validateMessage` instead. + * + * @category Common + */ +function isMessage(val) { + try { + validateMessage(val); + return true; + } catch (_a) { + return false; + } +} +/** + * Parses the raw websocket message data to a valid message. + * + * @category Common + */ +function parseMessage(data, reviver) { + return validateMessage(typeof data === 'string' ? JSON.parse(data, reviver) : data); +} +/** + * Stringifies a valid message ready to be sent through the socket. + * + * @category Common + */ +function stringifyMessage(msg, replacer) { + validateMessage(msg); + return JSON.stringify(msg, replacer); +} + +/***/ }), + +/***/ "../../../node_modules/graphql-ws/lib/index.js": +/*!*****************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/index.js ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; + } + Object.defineProperty(o, k2, desc); +} : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); +var __exportStar = void 0 && (void 0).__exportStar || function (m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +__exportStar(__webpack_require__(/*! ./client */ "../../../node_modules/graphql-ws/lib/client.mjs"), exports); +__exportStar(__webpack_require__(/*! ./server */ "../../../node_modules/graphql-ws/lib/server.mjs"), exports); +__exportStar(__webpack_require__(/*! ./common */ "../../../node_modules/graphql-ws/lib/common.mjs"), exports); + +/***/ }), + +/***/ "../../../node_modules/graphql-ws/lib/server.mjs": +/*!*******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/server.mjs ***! + \*******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.handleProtocols = handleProtocols; +exports.makeServer = makeServer; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); +var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); +/** + * + * server + * + */ +var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; - VisualElementDragControls.prototype.addListeners = function () { - var _this = this; - var _a; - elementDragControls.set(this.visualElement, this); - var element = this.visualElement.getInstance(); - /** - * Attach a pointerdown event listener on this DOM element to initiate drag tracking. - */ - var stopPointerListener = addPointerEvent(element, "pointerdown", function (event) { - var _a = _this.getProps(), - drag = _a.drag, - _b = _a.dragListener, - dragListener = _b === void 0 ? true : _b; - drag && dragListener && _this.start(event); + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d }); - var measureDragConstraints = function () { - var dragConstraints = _this.getProps().dragConstraints; - if (isRefObject(dragConstraints)) { - _this.constraints = _this.resolveRefConstraints(); - } + }, reject); + } +}; +/** + * Makes a Protocol complient WebSocket GraphQL server. The server + * is actually an API which is to be used with your favourite WebSocket + * server library! + * + * Read more about the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). + * + * @category Server + */ +function makeServer(options) { + const { + schema, + context, + roots, + validate, + execute, + subscribe, + connectionInitWaitTimeout = 3000, + // 3 seconds + onConnect, + onDisconnect, + onClose, + onSubscribe, + onOperation, + onNext, + onError, + onComplete, + jsonMessageReviver: reviver, + jsonMessageReplacer: replacer + } = options; + return { + opened(socket, extra) { + const ctx = { + connectionInitReceived: false, + acknowledged: false, + subscriptions: {}, + extra }; - var projection = this.visualElement.projection; - var stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); - if (projection && !projection.layout) { - (_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll(); - projection.updateLayout(); + if (socket.protocol !== _common.GRAPHQL_TRANSPORT_WS_PROTOCOL) { + socket.close(_common.CloseCode.SubprotocolNotAcceptable, 'Subprotocol not acceptable'); + return async (code, reason) => { + /* nothing was set up, just notify the closure */ + await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); + }; } - measureDragConstraints(); - /** - * Attach a window resize listener to scale the draggable target within its defined - * constraints as the window resizes. - */ - var stopResizeListener = addDomEvent(window, "resize", function () { - return _this.scalePositionWithinConstraints(); - }); - /** - * If the element's layout changes, calculate the delta and apply that to - * the drag gesture's origin point. - */ - projection.addEventListener("didUpdate", function (_a) { - var delta = _a.delta, - hasLayoutChanged = _a.hasLayoutChanged; - if (_this.isDragging && hasLayoutChanged) { - eachAxis(function (axis) { - var motionValue = _this.getAxisMotionValue(axis); - if (!motionValue) return; - _this.originPoint[axis] += delta[axis].translate; - motionValue.set(motionValue.get() + delta[axis].translate); - }); - _this.visualElement.syncRender(); + // kick the client off (close socket) if the connection has + // not been initialised after the specified wait timeout + const connectionInitWait = connectionInitWaitTimeout > 0 && isFinite(connectionInitWaitTimeout) ? setTimeout(() => { + if (!ctx.connectionInitReceived) socket.close(_common.CloseCode.ConnectionInitialisationTimeout, 'Connection initialisation timeout'); + }, connectionInitWaitTimeout) : null; + socket.onMessage(async function onMessage(data) { + var _a, e_1, _b, _c; + var _d; + let message; + try { + message = (0, _common.parseMessage)(data, reviver); + } catch (err) { + return socket.close(_common.CloseCode.BadRequest, 'Invalid message received'); + } + switch (message.type) { + case _common.MessageType.ConnectionInit: + { + if (ctx.connectionInitReceived) return socket.close(_common.CloseCode.TooManyInitialisationRequests, 'Too many initialisation requests'); + // @ts-expect-error: I can write + ctx.connectionInitReceived = true; + if ((0, _utils.isObject)(message.payload)) + // @ts-expect-error: I can write + ctx.connectionParams = message.payload; + const permittedOrPayload = await (onConnect === null || onConnect === void 0 ? void 0 : onConnect(ctx)); + if (permittedOrPayload === false) return socket.close(_common.CloseCode.Forbidden, 'Forbidden'); + await socket.send((0, _common.stringifyMessage)((0, _utils.isObject)(permittedOrPayload) ? { + type: _common.MessageType.ConnectionAck, + payload: permittedOrPayload + } : { + type: _common.MessageType.ConnectionAck + // payload is completely absent if not provided + }, replacer)); + // @ts-expect-error: I can write + ctx.acknowledged = true; + return; + } + case _common.MessageType.Ping: + { + if (socket.onPing) + // if the onPing listener is registered, automatic pong is disabled + return await socket.onPing(message.payload); + await socket.send((0, _common.stringifyMessage)(message.payload ? { + type: _common.MessageType.Pong, + payload: message.payload + } : { + type: _common.MessageType.Pong + // payload is completely absent if not provided + })); + return; + } + case _common.MessageType.Pong: + return await ((_d = socket.onPong) === null || _d === void 0 ? void 0 : _d.call(socket, message.payload)); + case _common.MessageType.Subscribe: + { + if (!ctx.acknowledged) return socket.close(_common.CloseCode.Unauthorized, 'Unauthorized'); + const { + id, + payload + } = message; + if (id in ctx.subscriptions) return socket.close(_common.CloseCode.SubscriberAlreadyExists, `Subscriber for ${id} already exists`); + // if this turns out to be a streaming operation, the subscription value + // will change to an `AsyncIterable`, otherwise it will stay as is + ctx.subscriptions[id] = null; + const emit = { + next: async (result, args) => { + let nextMessage = { + id, + type: _common.MessageType.Next, + payload: result + }; + const maybeResult = await (onNext === null || onNext === void 0 ? void 0 : onNext(ctx, nextMessage, args, result)); + if (maybeResult) nextMessage = Object.assign(Object.assign({}, nextMessage), { + payload: maybeResult + }); + await socket.send((0, _common.stringifyMessage)(nextMessage, replacer)); + }, + error: async errors => { + let errorMessage = { + id, + type: _common.MessageType.Error, + payload: errors + }; + const maybeErrors = await (onError === null || onError === void 0 ? void 0 : onError(ctx, errorMessage, errors)); + if (maybeErrors) errorMessage = Object.assign(Object.assign({}, errorMessage), { + payload: maybeErrors + }); + await socket.send((0, _common.stringifyMessage)(errorMessage, replacer)); + }, + complete: async notifyClient => { + const completeMessage = { + id, + type: _common.MessageType.Complete + }; + await (onComplete === null || onComplete === void 0 ? void 0 : onComplete(ctx, completeMessage)); + if (notifyClient) await socket.send((0, _common.stringifyMessage)(completeMessage, replacer)); + } + }; + try { + let execArgs; + const maybeExecArgsOrErrors = await (onSubscribe === null || onSubscribe === void 0 ? void 0 : onSubscribe(ctx, message)); + if (maybeExecArgsOrErrors) { + if ((0, _utils.areGraphQLErrors)(maybeExecArgsOrErrors)) return await emit.error(maybeExecArgsOrErrors);else if (Array.isArray(maybeExecArgsOrErrors)) throw new Error('Invalid return value from onSubscribe hook, expected an array of GraphQLError objects'); + // not errors, is exec args + execArgs = maybeExecArgsOrErrors; + } else { + // you either provide a schema dynamically through + // `onSubscribe` or you set one up during the server setup + if (!schema) throw new Error('The GraphQL schema is not provided'); + const args = { + operationName: payload.operationName, + document: (0, _graphql.parse)(payload.query), + variableValues: payload.variables + }; + execArgs = Object.assign(Object.assign({}, args), { + schema: typeof schema === 'function' ? await schema(ctx, message, args) : schema + }); + const validationErrors = (validate !== null && validate !== void 0 ? validate : _graphql.validate)(execArgs.schema, execArgs.document); + if (validationErrors.length > 0) return await emit.error(validationErrors); + } + const operationAST = (0, _graphql.getOperationAST)(execArgs.document, execArgs.operationName); + if (!operationAST) return await emit.error([new _graphql.GraphQLError('Unable to identify operation')]); + // if `onSubscribe` didnt specify a rootValue, inject one + if (!('rootValue' in execArgs)) execArgs.rootValue = roots === null || roots === void 0 ? void 0 : roots[operationAST.operation]; + // if `onSubscribe` didn't specify a context, inject one + if (!('contextValue' in execArgs)) execArgs.contextValue = typeof context === 'function' ? await context(ctx, message, execArgs) : context; + // the execution arguments have been prepared + // perform the operation and act accordingly + let operationResult; + if (operationAST.operation === 'subscription') operationResult = await (subscribe !== null && subscribe !== void 0 ? subscribe : _graphql.subscribe)(execArgs); + // operation === 'query' || 'mutation' + else operationResult = await (execute !== null && execute !== void 0 ? execute : _graphql.execute)(execArgs); + const maybeResult = await (onOperation === null || onOperation === void 0 ? void 0 : onOperation(ctx, message, execArgs, operationResult)); + if (maybeResult) operationResult = maybeResult; + if ((0, _utils.isAsyncIterable)(operationResult)) { + /** multiple emitted results */ + if (!(id in ctx.subscriptions)) { + // subscription was completed/canceled before the operation settled + if ((0, _utils.isAsyncGenerator)(operationResult)) operationResult.return(undefined); + } else { + ctx.subscriptions[id] = operationResult; + try { + for (var _e = true, operationResult_1 = __asyncValues(operationResult), operationResult_1_1; operationResult_1_1 = await operationResult_1.next(), _a = operationResult_1_1.done, !_a; _e = true) { + _c = operationResult_1_1.value; + _e = false; + const result = _c; + await emit.next(result, execArgs); + } + } catch (e_1_1) { + e_1 = { + error: e_1_1 + }; + } finally { + try { + if (!_e && !_a && (_b = operationResult_1.return)) await _b.call(operationResult_1); + } finally { + if (e_1) throw e_1.error; + } + } + } + } else { + /** single emitted result */ + // if the client completed the subscription before the single result + // became available, he effectively canceled it and no data should be sent + if (id in ctx.subscriptions) await emit.next(operationResult, execArgs); + } + // lack of subscription at this point indicates that the client + // completed the subscription, he doesnt need to be reminded + await emit.complete(id in ctx.subscriptions); + } finally { + // whatever happens to the subscription, we finally want to get rid of the reservation + delete ctx.subscriptions[id]; + } + return; + } + case _common.MessageType.Complete: + { + const subscription = ctx.subscriptions[message.id]; + delete ctx.subscriptions[message.id]; // deleting the subscription means no further activity should take place + if ((0, _utils.isAsyncGenerator)(subscription)) await subscription.return(undefined); + return; + } + default: + throw new Error(`Unexpected message of type ${message.type} received`); } }); - return function () { - stopResizeListener(); - stopPointerListener(); - stopMeasureLayoutListener(); + // wait for close, cleanup and the disconnect callback + return async (code, reason) => { + if (connectionInitWait) clearTimeout(connectionInitWait); + for (const sub of Object.values(ctx.subscriptions)) { + if ((0, _utils.isAsyncGenerator)(sub)) await sub.return(undefined); + } + if (ctx.acknowledged) await (onDisconnect === null || onDisconnect === void 0 ? void 0 : onDisconnect(ctx, code, reason)); + await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); }; + } + }; +} +/** + * Helper utility for choosing the "graphql-transport-ws" subprotocol from + * a set of WebSocket subprotocols. + * + * Accepts a set of already extracted WebSocket subprotocols or the raw + * Sec-WebSocket-Protocol header value. In either case, if the right + * protocol appears, it will be returned. + * + * By specification, the server should not provide a value with Sec-WebSocket-Protocol + * if it does not agree with client's subprotocols. The client has a responsibility + * to handle the connection afterwards. + * + * @category Server + */ +function handleProtocols(protocols) { + switch (true) { + case protocols instanceof Set && protocols.has(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): + case Array.isArray(protocols) && protocols.includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): + case typeof protocols === 'string' && protocols.split(',').map(p => p.trim()).includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): + return _common.GRAPHQL_TRANSPORT_WS_PROTOCOL; + default: + return false; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql-ws/lib/utils.mjs": +/*!******************************************************!*\ + !*** ../../../node_modules/graphql-ws/lib/utils.mjs ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.areGraphQLErrors = areGraphQLErrors; +exports.extendedTypeof = extendedTypeof; +exports.isAsyncGenerator = isAsyncGenerator; +exports.isAsyncIterable = isAsyncIterable; +exports.isObject = isObject; +exports.limitCloseReason = limitCloseReason; +/** @private */ +function extendedTypeof(val) { + if (val === null) { + return 'null'; + } + if (Array.isArray(val)) { + return 'array'; + } + return typeof val; +} +/** @private */ +function isObject(val) { + return extendedTypeof(val) === 'object'; +} +/** @private */ +function isAsyncIterable(val) { + return typeof Object(val)[Symbol.asyncIterator] === 'function'; +} +/** @private */ +function isAsyncGenerator(val) { + return isObject(val) && typeof Object(val)[Symbol.asyncIterator] === 'function' && typeof val.return === 'function' + // for lazy ones, we only need the return anyway + // typeof val.throw === 'function' && + // typeof val.next === 'function' + ; +} +/** @private */ +function areGraphQLErrors(obj) { + return Array.isArray(obj) && + // must be at least one error + obj.length > 0 && + // error has at least a message + obj.every(ob => 'message' in ob); +} +/** + * Limits the WebSocket close event reason to not exceed a length of one frame. + * Reference: https://datatracker.ietf.org/doc/html/rfc6455#section-5.2. + * + * @private + */ +function limitCloseReason(reason, whenTooLong) { + return reason.length < 124 ? reason : whenTooLong; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/error/GraphQLError.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/error/GraphQLError.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.GraphQLError = void 0; +exports.formatError = formatError; +exports.printError = printError; +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _location = __webpack_require__(/*! ../language/location.mjs */ "../../../node_modules/graphql/language/location.mjs"); +var _printLocation = __webpack_require__(/*! ../language/printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); +function toNormalizedOptions(args) { + const firstArg = args[0]; + if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { + return { + nodes: firstArg, + source: args[1], + positions: args[2], + path: args[3], + originalError: args[4], + extensions: args[5] }; - VisualElementDragControls.prototype.getProps = function () { - var props = this.visualElement.getProps(); - var _a = props.drag, - drag = _a === void 0 ? false : _a, - _b = props.dragDirectionLock, - dragDirectionLock = _b === void 0 ? false : _b, - _c = props.dragPropagation, - dragPropagation = _c === void 0 ? false : _c, - _d = props.dragConstraints, - dragConstraints = _d === void 0 ? false : _d, - _e = props.dragElastic, - dragElastic = _e === void 0 ? defaultElastic : _e, - _f = props.dragMomentum, - dragMomentum = _f === void 0 ? true : _f; - return tslib.__assign(tslib.__assign({}, props), { - drag: drag, - dragDirectionLock: dragDirectionLock, - dragPropagation: dragPropagation, - dragConstraints: dragConstraints, - dragElastic: dragElastic, - dragMomentum: dragMomentum - }); - }; - return VisualElementDragControls; - }(); - function shouldDrag(direction, drag, currentDirection) { - return (drag === true || drag === direction) && (currentDirection === null || currentDirection === direction); } + return firstArg; +} +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ + +class GraphQLError extends Error { /** - * Based on a x/y offset determine the current drag direction. If both axis' offsets are lower - * than the provided threshold, return `null`. + * An array of `{ line, column }` locations within the source GraphQL document + * which correspond to this error. * - * @param offset - The x/y offset from origin. - * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction. + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). */ - function getCurrentDirection(offset, lockThreshold) { - if (lockThreshold === void 0) { - lockThreshold = 10; - } - var direction = null; - if (Math.abs(offset.y) > lockThreshold) { - direction = "y"; - } else if (Math.abs(offset.x) > lockThreshold) { - direction = "x"; - } - return direction; - } - + /** - * A hook that allows an element to be dragged. + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. * - * @internal + * Enumerable, and appears in the result of JSON.stringify(). */ - function useDrag(props) { - var groupDragControls = props.dragControls, - visualElement = props.visualElement; - var dragControls = useConstant(function () { - return new VisualElementDragControls(visualElement); - }); - // If we've been provided a DragControls for manual control over the drag gesture, - // subscribe this component to it on mount. - React.useEffect(function () { - return groupDragControls && groupDragControls.subscribe(dragControls); - }, [dragControls, groupDragControls]); - // Apply the event listeners to the element - React.useEffect(function () { - return dragControls.addListeners(); - }, [dragControls]); - } - + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + + /** + * The source GraphQL document for the first location of this error. * - * @param handlers - - * @param ref - - * - * @privateRemarks - * Currently this sets new pan gesture functions every render. The memo route has been explored - * in the past but ultimately we're still creating new functions every render. An optimisation - * to explore is creating the pan gestures and loading them into a `ref`. - * - * @internal + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. */ - function usePanGesture(_a) { - var onPan = _a.onPan, - onPanStart = _a.onPanStart, - onPanEnd = _a.onPanEnd, - onPanSessionStart = _a.onPanSessionStart, - visualElement = _a.visualElement; - var hasPanEvents = onPan || onPanStart || onPanEnd || onPanSessionStart; - var panSession = React.useRef(null); - var transformPagePoint = React.useContext(MotionConfigContext).transformPagePoint; - var handlers = { - onSessionStart: onPanSessionStart, - onStart: onPanStart, - onMove: onPan, - onEnd: function (event, info) { - panSession.current = null; - onPanEnd && onPanEnd(event, info); - } - }; - React.useEffect(function () { - if (panSession.current !== null) { - panSession.current.updateHandlers(handlers); - } - }); - function onPointerDown(event) { - panSession.current = new PanSession(event, handlers, { - transformPagePoint: transformPagePoint - }); - } - usePointerEvent(visualElement, "pointerdown", hasPanEvents && onPointerDown); - useUnmountEffect(function () { - return panSession.current && panSession.current.end(); - }); - } - var drag = { - pan: makeRenderlessComponent(usePanGesture), - drag: makeRenderlessComponent(useDrag) - }; - var names = ["LayoutMeasure", "BeforeLayoutMeasure", "LayoutUpdate", "ViewportBoxUpdate", "Update", "Render", "AnimationComplete", "LayoutAnimationComplete", "AnimationStart", "LayoutAnimationStart", "SetAxisTarget", "Unmount"]; - function createLifecycles() { - var managers = names.map(function () { - return new SubscriptionManager(); - }); - var propSubscriptions = {}; - var lifecycles = { - clearAllListeners: function () { - return managers.forEach(function (manager) { - return manager.clear(); - }); - }, - updatePropListeners: function (props) { - names.forEach(function (name) { - var _a; - var on = "on" + name; - var propListener = props[on]; - // Unsubscribe existing subscription - (_a = propSubscriptions[name]) === null || _a === void 0 ? void 0 : _a.call(propSubscriptions); - // Add new subscription - if (propListener) { - propSubscriptions[name] = lifecycles[on](propListener); - } - }); - } - }; - managers.forEach(function (manager, i) { - lifecycles["on" + names[i]] = function (handler) { - return manager.add(handler); - }; - lifecycles["notify" + names[i]] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return manager.notify.apply(manager, tslib.__spreadArray([], tslib.__read(args), false)); - }; - }); - return lifecycles; + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + + /** + * The original error thrown from a field resolver during execution. + */ + + /** + * Extension fields to add to the formatted error. + */ + + /** + * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + */ + constructor(message, ...rawArgs) { + var _this$nodes, _nodeLocations$, _ref; + const { + nodes, + source, + positions, + path, + originalError, + extensions + } = toNormalizedOptions(rawArgs); + super(message); + this.name = 'GraphQLError'; + this.path = path !== null && path !== void 0 ? path : undefined; + this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. + + this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); + const nodeLocations = undefinedIfEmpty((_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map(node => node.loc).filter(loc => loc != null)); // Compute locations in the source for the given nodes/positions. + + this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source; + this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => loc.start); + this.locations = positions && source ? positions.map(pos => (0, _location.getLocation)(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => (0, _location.getLocation)(loc.source, loc.start)); + const originalExtensions = (0, _isObjectLike.isObjectLike)(originalError === null || originalError === void 0 ? void 0 : originalError.extensions) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : undefined; + this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : Object.create(null); // Only properties prescribed by the spec should be enumerable. + // Keep the rest as non-enumerable. + + Object.defineProperties(this, { + message: { + writable: true, + enumerable: true + }, + name: { + enumerable: false + }, + nodes: { + enumerable: false + }, + source: { + enumerable: false + }, + positions: { + enumerable: false + }, + originalError: { + enumerable: false + } + }); // Include (non-enumerable) stack trace. + + /* c8 ignore start */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + + if (originalError !== null && originalError !== void 0 && originalError.stack) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true + }); + } + /* c8 ignore stop */ } - function updateMotionValuesFromProps(element, next, prev) { - var _a; - for (var key in next) { - var nextValue = next[key]; - var prevValue = prev[key]; - if (isMotionValue(nextValue)) { - /** - * If this is a motion value found in props or style, we want to add it - * to our visual element's motion value map. - */ - element.addValue(key, nextValue); - /** - * Check the version of the incoming motion value with this version - * and warn against mismatches. - */ - if (true) { - warnOnce(nextValue.version === "6.5.1", "Attempting to mix Framer Motion versions ".concat(nextValue.version, " with 6.5.1 may not work as expected.")); - } - } else if (isMotionValue(prevValue)) { - /** - * If we're swapping to a new motion value, create a new motion value - * from that - */ - element.addValue(key, motionValue(nextValue)); - } else if (prevValue !== nextValue) { - /** - * If this is a flat value that has changed, update the motion value - * or create one if it doesn't exist. We only want to do this if we're - * not handling the value with our animation state. - */ - if (element.hasValue(key)) { - var existingValue = element.getValue(key); - // TODO: Only update values that aren't being animated or even looked at - !existingValue.hasAnimated && existingValue.set(nextValue); - } else { - element.addValue(key, motionValue((_a = element.getStaticValue(key)) !== null && _a !== void 0 ? _a : nextValue)); + get [Symbol.toStringTag]() { + return 'GraphQLError'; + } + toString() { + let output = this.message; + if (this.nodes) { + for (const node of this.nodes) { + if (node.loc) { + output += '\n\n' + (0, _printLocation.printLocation)(node.loc); } } + } else if (this.source && this.locations) { + for (const location of this.locations) { + output += '\n\n' + (0, _printLocation.printSourceLocation)(this.source, location); + } + } + return output; + } + toJSON() { + const formattedError = { + message: this.message + }; + if (this.locations != null) { + formattedError.locations = this.locations; } - // Handle removed values - for (var key in prev) { - if (next[key] === undefined) element.removeValue(key); + if (this.path != null) { + formattedError.path = this.path; } - return next; + if (this.extensions != null && Object.keys(this.extensions).length > 0) { + formattedError.extensions = this.extensions; + } + return formattedError; } - var visualElement = function (_a) { - var _b = _a.treeType, - treeType = _b === void 0 ? "" : _b, - build = _a.build, - getBaseTarget = _a.getBaseTarget, - makeTargetAnimatable = _a.makeTargetAnimatable, - measureViewportBox = _a.measureViewportBox, - renderInstance = _a.render, - readValueFromInstance = _a.readValueFromInstance, - removeValueFromRenderState = _a.removeValueFromRenderState, - sortNodePosition = _a.sortNodePosition, - scrapeMotionValuesFromProps = _a.scrapeMotionValuesFromProps; - return function (_a, options) { - var parent = _a.parent, - props = _a.props, - presenceId = _a.presenceId, - blockInitialAnimation = _a.blockInitialAnimation, - visualState = _a.visualState, - shouldReduceMotion = _a.shouldReduceMotion; - if (options === void 0) { - options = {}; - } - var isMounted = false; - var latestValues = visualState.latestValues, - renderState = visualState.renderState; - /** - * The instance of the render-specific node that will be hydrated by the - * exposed React ref. So for example, this visual element can host a - * HTMLElement, plain object, or Three.js object. The functions provided - * in VisualElementConfig allow us to interface with this instance. - */ - var instance; - /** - * Manages the subscriptions for a visual element's lifecycle, for instance - * onRender - */ - var lifecycles = createLifecycles(); - /** - * A map of all motion values attached to this visual element. Motion - * values are source of truth for any given animated value. A motion - * value might be provided externally by the component via props. - */ - var values = new Map(); - /** - * A map of every subscription that binds the provided or generated - * motion values onChange listeners to this visual element. - */ - var valueSubscriptions = new Map(); - /** - * A reference to the previously-provided motion values as returned - * from scrapeMotionValuesFromProps. We use the keys in here to determine - * if any motion values need to be removed after props are updated. - */ - var prevMotionValues = {}; - /** - * When values are removed from all animation props we need to search - * for a fallback value to animate to. These values are tracked in baseTarget. - */ - var baseTarget = tslib.__assign({}, latestValues); - // Internal methods ======================== - /** - * On mount, this will be hydrated with a callback to disconnect - * this visual element from its parent on unmount. - */ - var removeFromVariantTree; - /** - * Render the element with the latest styles outside of the React - * render lifecycle - */ - function render() { - if (!instance || !isMounted) return; - triggerBuild(); - renderInstance(instance, renderState, props.style, element.projection); - } - function triggerBuild() { - build(element, renderState, latestValues, options, props); - } - function update() { - lifecycles.notifyUpdate(latestValues); - } - /** - * - */ - function bindToMotionValue(key, value) { - var removeOnChange = value.onChange(function (latestValue) { - latestValues[key] = latestValue; - props.onUpdate && sync__default["default"].update(update, false, true); - }); - var removeOnRenderRequest = value.onRenderRequest(element.scheduleRender); - valueSubscriptions.set(key, function () { - removeOnChange(); - removeOnRenderRequest(); - }); - } - /** - * Any motion values that are provided to the element when created - * aren't yet bound to the element, as this would technically be impure. - * However, we iterate through the motion values and set them to the - * initial values for this component. - * - * TODO: This is impure and we should look at changing this to run on mount. - * Doing so will break some tests but this isn't neccessarily a breaking change, - * more a reflection of the test. - */ - var initialMotionValues = scrapeMotionValuesFromProps(props); - for (var key in initialMotionValues) { - var value = initialMotionValues[key]; - if (latestValues[key] !== undefined && isMotionValue(value)) { - value.set(latestValues[key], false); - } - } - /** - * Determine what role this visual element should take in the variant tree. - */ - var isControllingVariants = checkIfControllingVariants(props); - var isVariantNode = checkIfVariantNode(props); - var element = tslib.__assign(tslib.__assign({ - treeType: treeType, - /** - * This is a mirror of the internal instance prop, which keeps - * VisualElement type-compatible with React's RefObject. - */ - current: null, - /** - * The depth of this visual element within the visual element tree. - */ - depth: parent ? parent.depth + 1 : 0, - parent: parent, - children: new Set(), - /** - * - */ - presenceId: presenceId, - shouldReduceMotion: shouldReduceMotion, - /** - * If this component is part of the variant tree, it should track - * any children that are also part of the tree. This is essentially - * a shadow tree to simplify logic around how to stagger over children. - */ - variantChildren: isVariantNode ? new Set() : undefined, - /** - * Whether this instance is visible. This can be changed imperatively - * by the projection tree, is analogous to CSS's visibility in that - * hidden elements should take up layout, and needs enacting by the configured - * render function. - */ - isVisible: undefined, - /** - * Normally, if a component is controlled by a parent's variants, it can - * rely on that ancestor to trigger animations further down the tree. - * However, if a component is created after its parent is mounted, the parent - * won't trigger that mount animation so the child needs to. - * - * TODO: This might be better replaced with a method isParentMounted - */ - manuallyAnimateOnMount: Boolean(parent === null || parent === void 0 ? void 0 : parent.isMounted()), - /** - * This can be set by AnimatePresence to force components that mount - * at the same time as it to mount as if they have initial={false} set. - */ - blockInitialAnimation: blockInitialAnimation, - /** - * Determine whether this component has mounted yet. This is mostly used - * by variant children to determine whether they need to trigger their - * own animations on mount. - */ - isMounted: function () { - return Boolean(instance); - }, - mount: function (newInstance) { - isMounted = true; - instance = element.current = newInstance; - if (element.projection) { - element.projection.mount(newInstance); - } - if (isVariantNode && parent && !isControllingVariants) { - removeFromVariantTree = parent === null || parent === void 0 ? void 0 : parent.addVariantChild(element); - } - values.forEach(function (value, key) { - return bindToMotionValue(key, value); - }); - parent === null || parent === void 0 ? void 0 : parent.children.add(element); - element.setProps(props); - }, - /** - * - */ - unmount: function () { - var _a; - (_a = element.projection) === null || _a === void 0 ? void 0 : _a.unmount(); - sync.cancelSync.update(update); - sync.cancelSync.render(render); - valueSubscriptions.forEach(function (remove) { - return remove(); - }); - removeFromVariantTree === null || removeFromVariantTree === void 0 ? void 0 : removeFromVariantTree(); - parent === null || parent === void 0 ? void 0 : parent.children.delete(element); - lifecycles.clearAllListeners(); - instance = undefined; - isMounted = false; - }, - /** - * Add a child visual element to our set of children. - */ - addVariantChild: function (child) { - var _a; - var closestVariantNode = element.getClosestVariantNode(); - if (closestVariantNode) { - (_a = closestVariantNode.variantChildren) === null || _a === void 0 ? void 0 : _a.add(child); - return function () { - return closestVariantNode.variantChildren.delete(child); - }; - } - }, - sortNodePosition: function (other) { - /** - * If these nodes aren't even of the same type we can't compare their depth. - */ - if (!sortNodePosition || treeType !== other.treeType) return 0; - return sortNodePosition(element.getInstance(), other.getInstance()); - }, - /** - * Returns the closest variant node in the tree starting from - * this visual element. - */ - getClosestVariantNode: function () { - return isVariantNode ? element : parent === null || parent === void 0 ? void 0 : parent.getClosestVariantNode(); - }, - /** - * Expose the latest layoutId prop. - */ - getLayoutId: function () { - return props.layoutId; - }, - /** - * Returns the current instance. - */ - getInstance: function () { - return instance; - }, - /** - * Get/set the latest static values. - */ - getStaticValue: function (key) { - return latestValues[key]; - }, - setStaticValue: function (key, value) { - return latestValues[key] = value; - }, - /** - * Returns the latest motion value state. Currently only used to take - * a snapshot of the visual element - perhaps this can return the whole - * visual state - */ - getLatestValues: function () { - return latestValues; - }, - /** - * Set the visiblity of the visual element. If it's changed, schedule - * a render to reflect these changes. - */ - setVisibility: function (visibility) { - if (element.isVisible === visibility) return; - element.isVisible = visibility; - element.scheduleRender(); - }, - /** - * Make a target animatable by Popmotion. For instance, if we're - * trying to animate width from 100px to 100vw we need to measure 100vw - * in pixels to determine what we really need to animate to. This is also - * pluggable to support Framer's custom value types like Color, - * and CSS variables. - */ - makeTargetAnimatable: function (target, canMutate) { - if (canMutate === void 0) { - canMutate = true; +} +exports.GraphQLError = GraphQLError; +function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; +} +/** + * See: https://spec.graphql.org/draft/#sec-Errors + */ + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + * + * @deprecated Please use `error.toString` instead. Will be removed in v17 + */ +function printError(error) { + return error.toString(); +} +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + * + * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + */ + +function formatError(error) { + return error.toJSON(); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/error/index.mjs": +/*!*****************************************************!*\ + !*** ../../../node_modules/graphql/error/index.mjs ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "GraphQLError", ({ + enumerable: true, + get: function () { + return _GraphQLError.GraphQLError; + } +})); +Object.defineProperty(exports, "formatError", ({ + enumerable: true, + get: function () { + return _GraphQLError.formatError; + } +})); +Object.defineProperty(exports, "locatedError", ({ + enumerable: true, + get: function () { + return _locatedError.locatedError; + } +})); +Object.defineProperty(exports, "printError", ({ + enumerable: true, + get: function () { + return _GraphQLError.printError; + } +})); +Object.defineProperty(exports, "syntaxError", ({ + enumerable: true, + get: function () { + return _syntaxError.syntaxError; + } +})); +var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _syntaxError = __webpack_require__(/*! ./syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); +var _locatedError = __webpack_require__(/*! ./locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/error/locatedError.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/error/locatedError.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.locatedError = locatedError; +var _toError = __webpack_require__(/*! ../jsutils/toError.mjs */ "../../../node_modules/graphql/jsutils/toError.mjs"); +var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ + +function locatedError(rawOriginalError, nodes, path) { + var _nodes; + const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + + if (isLocatedGraphQLError(originalError)) { + return originalError; + } + return new _GraphQLError.GraphQLError(originalError.message, { + nodes: (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, + source: originalError.source, + positions: originalError.positions, + path, + originalError + }); +} +function isLocatedGraphQLError(error) { + return Array.isArray(error.path); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/error/syntaxError.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/error/syntaxError.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.syntaxError = syntaxError; +var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ + +function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { + source, + positions: [position] + }); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/execution/collectFields.mjs": +/*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/execution/collectFields.mjs ***! + \*****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.collectFields = collectFields; +exports.collectSubfields = collectSubfields; +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); +/** + * Given a selectionSet, collects all of the fields and returns them. + * + * CollectFields requires the "runtime type" of an object. For a field that + * returns an Interface or Union type, the "runtime type" will be the actual + * object type returned by that field. + * + * @internal + */ + +function collectFields(schema, fragments, variableValues, runtimeType, selectionSet) { + const fields = new Map(); + collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, new Set()); + return fields; +} +/** + * Given an array of field nodes, collects all of the subfields of the passed + * in fields, and returns them at the end. + * + * CollectSubFields requires the "return type" of an object. For a field that + * returns an Interface or Union type, the "return type" will be the actual + * object type returned by that field. + * + * @internal + */ + +function collectSubfields(schema, fragments, variableValues, returnType, fieldNodes) { + const subFieldNodes = new Map(); + const visitedFragmentNames = new Set(); + for (const node of fieldNodes) { + if (node.selectionSet) { + collectFieldsImpl(schema, fragments, variableValues, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); + } + } + return subFieldNodes; +} +function collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: + { + if (!shouldIncludeNode(variableValues, selection)) { + continue; } - return makeTargetAnimatable(element, target, props, canMutate); - }, - /** - * Measure the current viewport box with or without transforms. - * Only measures axis-aligned boxes, rotate and skew must be manually - * removed with a re-render to work. - */ - measureViewportBox: function () { - return measureViewportBox(instance, props); - }, - // Motion values ======================== - /** - * Add a motion value and bind it to this visual element. - */ - addValue: function (key, value) { - // Remove existing value if it exists - if (element.hasValue(key)) element.removeValue(key); - values.set(key, value); - latestValues[key] = value.get(); - bindToMotionValue(key, value); - }, - /** - * Remove a motion value and unbind any active subscriptions. - */ - removeValue: function (key) { - var _a; - values.delete(key); - (_a = valueSubscriptions.get(key)) === null || _a === void 0 ? void 0 : _a(); - valueSubscriptions.delete(key); - delete latestValues[key]; - removeValueFromRenderState(key, renderState); - }, - /** - * Check whether we have a motion value for this key - */ - hasValue: function (key) { - return values.has(key); - }, - /** - * Get a motion value for this key. If called with a default - * value, we'll create one if none exists. - */ - getValue: function (key, defaultValue) { - var value = values.get(key); - if (value === undefined && defaultValue !== undefined) { - value = motionValue(defaultValue); - element.addValue(key, value); + const name = getFieldEntryKey(selection); + const fieldList = fields.get(name); + if (fieldList !== undefined) { + fieldList.push(selection); + } else { + fields.set(name, [selection]); } - return value; - }, - /** - * Iterate over our motion values. - */ - forEachValue: function (callback) { - return values.forEach(callback); - }, - /** - * If we're trying to animate to a previously unencountered value, - * we need to check for it in our state and as a last resort read it - * directly from the instance (which might have performance implications). - */ - readValue: function (key) { - var _a; - return (_a = latestValues[key]) !== null && _a !== void 0 ? _a : readValueFromInstance(instance, key, options); - }, - /** - * Set the base target to later animate back to. This is currently - * only hydrated on creation and when we first read a value. - */ - setBaseTarget: function (key, value) { - baseTarget[key] = value; - }, - /** - * Find the base target for a value thats been removed from all animation - * props. - */ - getBaseTarget: function (key) { - if (getBaseTarget) { - var target = getBaseTarget(props, key); - if (target !== undefined && !isMotionValue(target)) return target; + break; + } + case _kinds.Kind.INLINE_FRAGMENT: + { + if (!shouldIncludeNode(variableValues, selection) || !doesFragmentConditionMatch(schema, selection, runtimeType)) { + continue; } - return baseTarget[key]; + collectFieldsImpl(schema, fragments, variableValues, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; } - }, lifecycles), { - /** - * Build the renderer state based on the latest visual state. - */ - build: function () { - triggerBuild(); - return renderState; - }, - /** - * Schedule a render on the next animation frame. - */ - scheduleRender: function () { - sync__default["default"].render(render, false, true); - }, - /** - * Synchronously fire render. It's prefered that we batch renders but - * in many circumstances, like layout measurement, we need to run this - * synchronously. However in those instances other measures should be taken - * to batch reads/writes. - */ - syncRender: render, - /** - * Update the provided props. Ensure any newly-added motion values are - * added to our map, old ones removed, and listeners updated. - */ - setProps: function (newProps) { - if (newProps.transformTemplate || props.transformTemplate) { - element.scheduleRender(); + case _kinds.Kind.FRAGMENT_SPREAD: + { + const fragName = selection.name.value; + if (visitedFragmentNames.has(fragName) || !shouldIncludeNode(variableValues, selection)) { + continue; } - props = newProps; - lifecycles.updatePropListeners(newProps); - prevMotionValues = updateMotionValuesFromProps(element, scrapeMotionValuesFromProps(props), prevMotionValues); - }, - getProps: function () { - return props; - }, - // Variants ============================== - /** - * Returns the variant definition with a given name. - */ - getVariant: function (name) { - var _a; - return (_a = props.variants) === null || _a === void 0 ? void 0 : _a[name]; - }, - /** - * Returns the defined default transition on this component. - */ - getDefaultTransition: function () { - return props.transition; - }, - getTransformPagePoint: function () { - return props.transformPagePoint; - }, - /** - * Used by child variant nodes to get the closest ancestor variant props. - */ - getVariantContext: function (startAtParent) { - if (startAtParent === void 0) { - startAtParent = false; - } - if (startAtParent) return parent === null || parent === void 0 ? void 0 : parent.getVariantContext(); - if (!isControllingVariants) { - var context_1 = (parent === null || parent === void 0 ? void 0 : parent.getVariantContext()) || {}; - if (props.initial !== undefined) { - context_1.initial = props.initial; - } - return context_1; - } - var context = {}; - for (var i = 0; i < numVariantProps; i++) { - var name_1 = variantProps[i]; - var prop = props[name_1]; - if (isVariantLabel(prop) || prop === false) { - context[name_1] = prop; - } + visitedFragmentNames.add(fragName); + const fragment = fragments[fragName]; + if (!fragment || !doesFragmentConditionMatch(schema, fragment, runtimeType)) { + continue; } - return context; + collectFieldsImpl(schema, fragments, variableValues, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; } - }); - return element; - }; - }; - var variantProps = tslib.__spreadArray(["initial"], tslib.__read(variantPriorityOrder), false); - var numVariantProps = variantProps.length; - function isCSSVariable(value) { - return typeof value === "string" && value.startsWith("var(--"); + } } - /** - * Parse Framer's special CSS variable format into a CSS token and a fallback. - * - * ``` - * `var(--foo, #fff)` => [`--foo`, '#fff'] - * ``` - * - * @param current - */ - var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/; - function parseCSSVariable(current) { - var match = cssVariableRegex.exec(current); - if (!match) return [,]; - var _a = tslib.__read(match, 3), - token = _a[1], - fallback = _a[2]; - return [token, fallback]; - } - var maxDepth = 4; - function getVariableValue(current, element, depth) { - if (depth === void 0) { - depth = 1; - } - heyListen.invariant(depth <= maxDepth, "Max CSS variable fallback depth detected in property \"".concat(current, "\". This may indicate a circular fallback dependency.")); - var _a = tslib.__read(parseCSSVariable(current), 2), - token = _a[0], - fallback = _a[1]; - // No CSS variable detected - if (!token) return; - // Attempt to read this CSS variable off the element - var resolved = window.getComputedStyle(element).getPropertyValue(token); - if (resolved) { - return resolved.trim(); - } else if (isCSSVariable(fallback)) { - // The fallback might itself be a CSS variable, in which case we attempt to resolve it too. - return getVariableValue(fallback, element, depth + 1); - } else { - return fallback; - } +} +/** + * Determines if a field should be included based on the `@include` and `@skip` + * directives, where `@skip` has higher precedence than `@include`. + */ + +function shouldIncludeNode(variableValues, node) { + const skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, variableValues); + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; } - /** - * Resolve CSS variables from - * - * @internal - */ - function resolveCSSVariables(visualElement, _a, transitionEnd) { - var _b; - var target = tslib.__rest(_a, []); - var element = visualElement.getInstance(); - if (!(element instanceof Element)) return { - target: target, - transitionEnd: transitionEnd - }; - // If `transitionEnd` isn't `undefined`, clone it. We could clone `target` and `transitionEnd` - // only if they change but I think this reads clearer and this isn't a performance-critical path. - if (transitionEnd) { - transitionEnd = tslib.__assign({}, transitionEnd); - } - // Go through existing `MotionValue`s and ensure any existing CSS variables are resolved - visualElement.forEachValue(function (value) { - var current = value.get(); - if (!isCSSVariable(current)) return; - var resolved = getVariableValue(current, element); - if (resolved) value.set(resolved); - }); - // Cycle through every target property and resolve CSS variables. Currently - // we only read single-var properties like `var(--foo)`, not `calc(var(--foo) + 20px)` - for (var key in target) { - var current = target[key]; - if (!isCSSVariable(current)) continue; - var resolved = getVariableValue(current, element); - if (!resolved) continue; - // Clone target if it hasn't already been - target[key] = resolved; - // If the user hasn't already set this key on `transitionEnd`, set it to the unresolved - // CSS variable. This will ensure that after the animation the component will reflect - // changes in the value of the CSS variable. - if (transitionEnd) (_b = transitionEnd[key]) !== null && _b !== void 0 ? _b : transitionEnd[key] = current; - } + const include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, variableValues); + if ((include === null || include === void 0 ? void 0 : include.if) === false) { + return false; + } + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + +function doesFragmentConditionMatch(schema, fragment, type) { + const typeConditionNode = fragment.typeCondition; + if (!typeConditionNode) { + return true; + } + const conditionalType = (0, _typeFromAST.typeFromAST)(schema, typeConditionNode); + if (conditionalType === type) { + return true; + } + if ((0, _definition.isAbstractType)(conditionalType)) { + return schema.isSubType(conditionalType, type); + } + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/execution/execute.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/execution/execute.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.buildResolveInfo = buildResolveInfo; +exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; +exports.execute = execute; +exports.executeSync = executeSync; +exports.getFieldDef = getFieldDef; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _isPromise = __webpack_require__(/*! ../jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); +var _memoize = __webpack_require__(/*! ../jsutils/memoize3.mjs */ "../../../node_modules/graphql/jsutils/memoize3.mjs"); +var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); +var _promiseForObject = __webpack_require__(/*! ../jsutils/promiseForObject.mjs */ "../../../node_modules/graphql/jsutils/promiseForObject.mjs"); +var _promiseReduce = __webpack_require__(/*! ../jsutils/promiseReduce.mjs */ "../../../node_modules/graphql/jsutils/promiseReduce.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); +var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); +var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); +var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + +const collectSubfields = (0, _memoize.memoize3)((exeContext, returnType, fieldNodes) => (0, _collectFields.collectSubfields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, returnType, fieldNodes)); +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g `a` + * 2) fragment "spreads" e.g. `...c` + * 3) inline fragment "spreads" e.g. `...on Type { a }` + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ + +/** + * Implements the "Executing requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + */ +function execute(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); + const { + schema, + document, + variableValues, + rootValue + } = args; // If arguments are missing or incorrect, throw an error. + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { return { - target: target, - transitionEnd: transitionEnd + errors: exeContext }; - } - var positionalKeys = new Set(["width", "height", "top", "left", "right", "bottom", "x", "y"]); - var isPositionalKey = function (key) { - return positionalKeys.has(key); - }; - var hasPositionalKey = function (target) { - return Object.keys(target).some(isPositionalKey); - }; - var setAndResetVelocity = function (value, to) { - // Looks odd but setting it twice doesn't render, it'll just - // set both prev and current to the latest value - value.set(to, false); - value.set(to); - }; - var isNumOrPxType = function (v) { - return v === styleValueTypes.number || v === styleValueTypes.px; - }; - var BoundingBoxDimension; - (function (BoundingBoxDimension) { - BoundingBoxDimension["width"] = "width"; - BoundingBoxDimension["height"] = "height"; - BoundingBoxDimension["left"] = "left"; - BoundingBoxDimension["right"] = "right"; - BoundingBoxDimension["top"] = "top"; - BoundingBoxDimension["bottom"] = "bottom"; - })(BoundingBoxDimension || (BoundingBoxDimension = {})); - var getPosFromMatrix = function (matrix, pos) { - return parseFloat(matrix.split(", ")[pos]); + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + // + // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + + try { + const { + operation + } = exeContext; + const result = executeOperation(exeContext, operation, rootValue); + if ((0, _isPromise.isPromise)(result)) { + return result.then(data => buildResponse(data, exeContext.errors), error => { + exeContext.errors.push(error); + return buildResponse(null, exeContext.errors); + }); + } + return buildResponse(result, exeContext.errors); + } catch (error) { + exeContext.errors.push(error); + return buildResponse(null, exeContext.errors); + } +} +/** + * Also implements the "Executing requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + +function executeSync(args) { + const result = execute(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + return result; +} +/** + * Given a completed execution context and data, build the `{ errors, data }` + * response defined by the "Response" section of the GraphQL specification. + */ + +function buildResponse(data, errors) { + return errors.length === 0 ? { + data + } : { + errors, + data }; - var getTranslateFromMatrix = function (pos2, pos3) { - return function (_bbox, _a) { - var transform = _a.transform; - if (transform === "none" || !transform) return 0; - var matrix3d = transform.match(/^matrix3d\((.+)\)$/); - if (matrix3d) { - return getPosFromMatrix(matrix3d[1], pos3); - } else { - var matrix = transform.match(/^matrix\((.+)\)$/); - if (matrix) { - return getPosFromMatrix(matrix[1], pos2); - } else { - return 0; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + * + * @internal + */ + +function assertValidExecutionArguments(schema, document, rawVariableValues) { + document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + + rawVariableValues == null || (0, _isObjectLike.isObjectLike)(rawVariableValues) || (0, _devAssert.devAssert)(false, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ + +function buildExecutionContext(args) { + var _definition$name, _operation$variableDe; + const { + schema, + document, + rootValue, + contextValue, + variableValues: rawVariableValues, + operationName, + fieldResolver, + typeResolver, + subscribeFieldResolver + } = args; + let operation; + const fragments = Object.create(null); + for (const definition of document.definitions) { + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')]; + } + operation = definition; + } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { + operation = definition; } - } - }; - }; - var transformKeys = new Set(["x", "y", "z"]); - var nonTranslationalTransformKeys = transformProps.filter(function (key) { - return !transformKeys.has(key); + break; + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + default: // ignore non-executable definitions + } + } + if (!operation) { + if (operationName != null) { + return [new _GraphQLError.GraphQLError(`Unknown operation named "${operationName}".`)]; + } + return [new _GraphQLError.GraphQLError('Must provide an operation.')]; + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : []; + const coercedVariableValues = (0, _values.getVariableValues)(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, { + maxErrors: 50 }); - function removeNonTranslationalTransform(visualElement) { - var removedTransforms = []; - nonTranslationalTransformKeys.forEach(function (key) { - var value = visualElement.getValue(key); - if (value !== undefined) { - removedTransforms.push([key, value.get()]); - value.set(key.startsWith("scale") ? 1 : 0); - } - }); - // Apply changes to element before measurement - if (removedTransforms.length) visualElement.syncRender(); - return removedTransforms; - } - var positionalValues = { - // Dimensions - width: function (_a, _b) { - var x = _a.x; - var _c = _b.paddingLeft, - paddingLeft = _c === void 0 ? "0" : _c, - _d = _b.paddingRight, - paddingRight = _d === void 0 ? "0" : _d; - return x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight); - }, - height: function (_a, _b) { - var y = _a.y; - var _c = _b.paddingTop, - paddingTop = _c === void 0 ? "0" : _c, - _d = _b.paddingBottom, - paddingBottom = _d === void 0 ? "0" : _d; - return y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom); - }, - top: function (_bbox, _a) { - var top = _a.top; - return parseFloat(top); - }, - left: function (_bbox, _a) { - var left = _a.left; - return parseFloat(left); - }, - bottom: function (_a, _b) { - var y = _a.y; - var top = _b.top; - return parseFloat(top) + (y.max - y.min); - }, - right: function (_a, _b) { - var x = _a.x; - var left = _b.left; - return parseFloat(left) + (x.max - x.min); - }, - // Transform - x: getTranslateFromMatrix(4, 13), - y: getTranslateFromMatrix(5, 14) + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver, + typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver, + subscribeFieldResolver: subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 ? subscribeFieldResolver : defaultFieldResolver, + errors: [] }; - var convertChangedValueTypes = function (target, visualElement, changedKeys) { - var originBbox = visualElement.measureViewportBox(); - var element = visualElement.getInstance(); - var elementComputedStyle = getComputedStyle(element); - var display = elementComputedStyle.display; - var origin = {}; - // If the element is currently set to display: "none", make it visible before - // measuring the target bounding box - if (display === "none") { - visualElement.setStaticValue("display", target.display || "block"); - } - /** - * Record origins before we render and update styles - */ - changedKeys.forEach(function (key) { - origin[key] = positionalValues[key](originBbox, elementComputedStyle); - }); - // Apply the latest values (as set in checkAndConvertChangedValueTypes) - visualElement.syncRender(); - var targetBbox = visualElement.measureViewportBox(); - changedKeys.forEach(function (key) { - // Restore styles to their **calculated computed style**, not their actual - // originally set style. This allows us to animate between equivalent pixel units. - var value = visualElement.getValue(key); - setAndResetVelocity(value, origin[key]); - target[key] = positionalValues[key](targetBbox, elementComputedStyle); +} +/** + * Implements the "Executing operations" section of the spec. + */ + +function executeOperation(exeContext, operation, rootValue) { + const rootType = exeContext.schema.getRootType(operation.operation); + if (rootType == null) { + throw new _GraphQLError.GraphQLError(`Schema is not configured to execute ${operation.operation} operation.`, { + nodes: operation }); - return target; - }; - var checkAndConvertChangedValueTypes = function (visualElement, target, origin, transitionEnd) { - if (origin === void 0) { - origin = {}; + } + const rootFields = (0, _collectFields.collectFields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, rootType, operation.selectionSet); + const path = undefined; + switch (operation.operation) { + case _ast.OperationTypeNode.QUERY: + return executeFields(exeContext, rootType, rootValue, path, rootFields); + case _ast.OperationTypeNode.MUTATION: + return executeFieldsSerially(exeContext, rootType, rootValue, path, rootFields); + case _ast.OperationTypeNode.SUBSCRIPTION: + // TODO: deprecate `subscribe` and move all logic here + // Temporary solution until we finish merging execute and subscribe together + return executeFields(exeContext, rootType, rootValue, path, rootFields); + } +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that must be executed serially. + */ + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return (0, _promiseReduce.promiseReduce)(fields.entries(), (results, [responseName, fieldNodes]) => { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + if (result === undefined) { + return results; } - if (transitionEnd === void 0) { - transitionEnd = {}; + if ((0, _isPromise.isPromise)(result)) { + return result.then(resolvedResult => { + results[responseName] = resolvedResult; + return results; + }); } - target = tslib.__assign({}, target); - transitionEnd = tslib.__assign({}, transitionEnd); - var targetPositionalKeys = Object.keys(target).filter(isPositionalKey); - // We want to remove any transform values that could affect the element's bounding box before - // it's measured. We'll reapply these later. - var removedTransformValues = []; - var hasAttemptedToRemoveTransformValues = false; - var changedValueTypeKeys = []; - targetPositionalKeys.forEach(function (key) { - var value = visualElement.getValue(key); - if (!visualElement.hasValue(key)) return; - var from = origin[key]; - var fromType = findDimensionValueType(from); - var to = target[key]; - var toType; - // TODO: The current implementation of this basically throws an error - // if you try and do value conversion via keyframes. There's probably - // a way of doing this but the performance implications would need greater scrutiny, - // as it'd be doing multiple resize-remeasure operations. - if (isKeyframesTarget(to)) { - var numKeyframes = to.length; - var fromIndex = to[0] === null ? 1 : 0; - from = to[fromIndex]; - fromType = findDimensionValueType(from); - for (var i = fromIndex; i < numKeyframes; i++) { - if (!toType) { - toType = findDimensionValueType(to[i]); - heyListen.invariant(toType === fromType || isNumOrPxType(fromType) && isNumOrPxType(toType), "Keyframes must be of the same dimension as the current value"); - } else { - heyListen.invariant(findDimensionValueType(to[i]) === toType, "All keyframes must be of the same type"); - } - } - } else { - toType = findDimensionValueType(to); - } - if (fromType !== toType) { - // If they're both just number or px, convert them both to numbers rather than - // relying on resize/remeasure to convert (which is wasteful in this situation) - if (isNumOrPxType(fromType) && isNumOrPxType(toType)) { - var current = value.get(); - if (typeof current === "string") { - value.set(parseFloat(current)); - } - if (typeof to === "string") { - target[key] = parseFloat(to); - } else if (Array.isArray(to) && toType === styleValueTypes.px) { - target[key] = to.map(parseFloat); - } - } else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) && (toType === null || toType === void 0 ? void 0 : toType.transform) && (from === 0 || to === 0)) { - // If one or the other value is 0, it's safe to coerce it to the - // type of the other without measurement - if (from === 0) { - value.set(toType.transform(from)); - } else { - target[key] = fromType.transform(to); - } - } else { - // If we're going to do value conversion via DOM measurements, we first - // need to remove non-positional transform values that could affect the bbox measurements. - if (!hasAttemptedToRemoveTransformValues) { - removedTransformValues = removeNonTranslationalTransform(visualElement); - hasAttemptedToRemoveTransformValues = true; - } - changedValueTypeKeys.push(key); - transitionEnd[key] = transitionEnd[key] !== undefined ? transitionEnd[key] : target[key]; - setAndResetVelocity(value, to); + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that may be executed in parallel. + */ + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + const results = Object.create(null); + let containsPromise = false; + try { + for (const [responseName, fieldNodes] of fields.entries()) { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + if (result !== undefined) { + results[responseName] = result; + if ((0, _isPromise.isPromise)(result)) { + containsPromise = true; } } - }); - if (changedValueTypeKeys.length) { - var scrollY_1 = changedValueTypeKeys.indexOf("height") >= 0 ? window.pageYOffset : null; - var convertedTarget = convertChangedValueTypes(target, visualElement, changedValueTypeKeys); - // If we removed transform values, reapply them before the next render - if (removedTransformValues.length) { - removedTransformValues.forEach(function (_a) { - var _b = tslib.__read(_a, 2), - key = _b[0], - value = _b[1]; - visualElement.getValue(key).set(value); - }); - } - // Reapply original values - visualElement.syncRender(); - // Restore scroll position - if (scrollY_1 !== null) window.scrollTo({ - top: scrollY_1 + } + } catch (error) { + if (containsPromise) { + // Ensure that any promises returned by other fields are handled, as they may also reject. + return (0, _promiseForObject.promiseForObject)(results).finally(() => { + throw error; }); - return { - target: convertedTarget, - transitionEnd: transitionEnd - }; + } + throw error; + } // If there are no promises, we can just return the object + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + return (0, _promiseForObject.promiseForObject)(results); +} +/** + * Implements the "Executing fields" section of the spec + * In particular, this function figures out the value that the field returns by + * calling its resolve function, then calls completeValue to complete promises, + * serialize scalars, or execute the sub-selection-set for objects. + */ + +function executeField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); + if (!fieldDef) { + return; + } + const returnType = fieldDef.type; + const resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver; + const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error). + + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; + const result = resolveFn(source, args, contextValue, info); + let completed; + if ((0, _isPromise.isPromise)(result)) { + completed = result.then(resolved => completeValue(exeContext, returnType, fieldNodes, info, path, resolved)); } else { - return { - target: target, - transitionEnd: transitionEnd - }; + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + if ((0, _isPromise.isPromise)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, rawError => { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); + return handleFieldError(error, returnType, exeContext); + }); } - }; - /** - * Convert value types for x/y/width/height/top/left/bottom/right - * - * Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'` - * - * @internal - */ - function unitConversion(visualElement, target, origin, transitionEnd) { - return hasPositionalKey(target) ? checkAndConvertChangedValueTypes(visualElement, target, origin, transitionEnd) : { - target: target, - transitionEnd: transitionEnd - }; + return completed; + } catch (rawError) { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); + return handleFieldError(error, returnType, exeContext); } - - /** - * Parse a DOM variant to make it animatable. This involves resolving CSS variables - * and ensuring animations like "20%" => "calc(50vw)" are performed in pixels. - */ - var parseDomVariant = function (visualElement, target, origin, transitionEnd) { - var resolved = resolveCSSVariables(visualElement, target, transitionEnd); - target = resolved.target; - transitionEnd = resolved.transitionEnd; - return unitConversion(visualElement, target, origin, transitionEnd); +} +/** + * @internal + */ + +function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues }; - function getComputedStyle$1(element) { - return window.getComputedStyle(element); - } - var htmlConfig = { - treeType: "dom", - readValueFromInstance: function (domElement, key) { - if (isTransformProp(key)) { - var defaultType = getDefaultValueType(key); - return defaultType ? defaultType.default || 0 : 0; +} +function handleFieldError(error, returnType, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Value Completion" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by executing all sub-selections. + */ + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + if ((0, _definition.isNonNullType)(returnType)) { + const completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + if (completed === null) { + throw new Error(`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`); + } + return completed; + } // If result value is null or undefined then return null. + + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type + + if ((0, _definition.isListType)(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } + /* c8 ignore next 6 */ + // Not reachable, all possible output types have been considered. + + false || (0, _invariant.invariant)(false, 'Cannot complete value of unexpected output type: ' + (0, _inspect.inspect)(returnType)); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + if (!(0, _isIterableObject.isIterableObject)(result)) { + throw new _GraphQLError.GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`); + } // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = Array.from(result, (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const itemPath = (0, _Path.addPath)(path, index, undefined); + try { + let completedItem; + if ((0, _isPromise.isPromise)(item)) { + completedItem = item.then(resolved => completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved)); } else { - var computedStyle = getComputedStyle$1(domElement); - return (isCSSVariable$1(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0; - } - }, - sortNodePosition: function (a, b) { - /** - * compareDocumentPosition returns a bitmask, by using the bitwise & - * we're returning true if 2 in that bitmask is set to true. 2 is set - * to true if b preceeds a. - */ - return a.compareDocumentPosition(b) & 2 ? 1 : -1; - }, - getBaseTarget: function (props, key) { - var _a; - return (_a = props.style) === null || _a === void 0 ? void 0 : _a[key]; - }, - measureViewportBox: function (element, _a) { - var transformPagePoint = _a.transformPagePoint; - return measureViewportBox(element, transformPagePoint); - }, - /** - * Reset the transform on the current Element. This is called as part - * of a batched process across the entire layout tree. To remove this write - * cycle it'd be interesting to see if it's possible to "undo" all the current - * layout transforms up the tree in the same way this.getBoundingBoxWithoutTransforms - * works - */ - resetTransform: function (element, domElement, props) { - var transformTemplate = props.transformTemplate; - domElement.style.transform = transformTemplate ? transformTemplate({}, "") : "none"; - // Ensure that whatever happens next, we restore our transform on the next frame - element.scheduleRender(); - }, - restoreTransform: function (instance, mutableState) { - instance.style.transform = mutableState.style.transform; - }, - removeValueFromRenderState: function (key, _a) { - var vars = _a.vars, - style = _a.style; - delete vars[key]; - delete style[key]; - }, - /** - * Ensure that HTML and Framer-specific value types like `px`->`%` and `Color` - * can be animated by Motion. - */ - makeTargetAnimatable: function (element, _a, _b, isMounted) { - var transformValues = _b.transformValues; - if (isMounted === void 0) { - isMounted = true; - } - var transition = _a.transition, - transitionEnd = _a.transitionEnd, - target = tslib.__rest(_a, ["transition", "transitionEnd"]); - var origin = getOrigin(target, transition || {}, element); - /** - * If Framer has provided a function to convert `Color` etc value types, convert them - */ - if (transformValues) { - if (transitionEnd) transitionEnd = transformValues(transitionEnd); - if (target) target = transformValues(target); - if (origin) origin = transformValues(origin); - } - if (isMounted) { - checkTargetForNewValues(element, target, origin); - var parsed = parseDomVariant(element, target, origin, transitionEnd); - transitionEnd = parsed.transitionEnd; - target = parsed.target; - } - return tslib.__assign({ - transition: transition, - transitionEnd: transitionEnd - }, target); - }, - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, - build: function (element, renderState, latestValues, options, props) { - if (element.isVisible !== undefined) { - renderState.style.visibility = element.isVisible ? "visible" : "hidden"; + completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item); } - buildHTMLStyles(renderState, latestValues, options, props.transformTemplate); - }, - render: renderHTML - }; - var htmlVisualElement = visualElement(htmlConfig); - var svgVisualElement = visualElement(tslib.__assign(tslib.__assign({}, htmlConfig), { - getBaseTarget: function (props, key) { - return props[key]; - }, - readValueFromInstance: function (domElement, key) { - var _a; - if (isTransformProp(key)) { - return ((_a = getDefaultValueType(key)) === null || _a === void 0 ? void 0 : _a.default) || 0; + if ((0, _isPromise.isPromise)(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + + return completedItem.then(undefined, rawError => { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); + return handleFieldError(error, itemType, exeContext); + }); } - key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; - return domElement.getAttribute(key); - }, - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps, - build: function (_element, renderState, latestValues, options, props) { - buildSVGAttrs(renderState, latestValues, options, props.transformTemplate); - }, - render: renderSVG - })); - var createDomVisualElement = function (Component, options) { - return isSVGComponent(Component) ? svgVisualElement(options, { - enableHardwareAcceleration: false - }) : htmlVisualElement(options, { - enableHardwareAcceleration: true + return completedItem; + } catch (rawError) { + const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); + return handleFieldError(error, itemType, exeContext); + } + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + +function completeLeafValue(returnType, result) { + const serializedResult = returnType.serialize(result); + if (serializedResult == null) { + throw new Error(`Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, _inspect.inspect)(result)})\` to ` + `return non-nullable value, returned: ${(0, _inspect.inspect)(serializedResult)}`); + } + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var _returnType$resolveTy; + const resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver; + const contextValue = exeContext.contextValue; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); + if ((0, _isPromise.isPromise)(runtimeType)) { + return runtimeType.then(resolvedRuntimeType => completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result)); + } + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} +function ensureValidRuntimeType(runtimeTypeName, exeContext, returnType, fieldNodes, info, result) { + if (runtimeTypeName == null) { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, fieldNodes); + } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` + // TODO: remove in 17.0.0 release + + if ((0, _definition.isObjectType)(runtimeTypeName)) { + throw new _GraphQLError.GraphQLError('Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.'); + } + if (typeof runtimeTypeName !== 'string') { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + `value ${(0, _inspect.inspect)(result)}, received "${(0, _inspect.inspect)(runtimeTypeName)}".`); + } + const runtimeType = exeContext.schema.getType(runtimeTypeName); + if (runtimeType == null) { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, { + nodes: fieldNodes }); - }; - function pixelsToPercent(pixels, axis) { - if (axis.max === axis.min) return 0; - return pixels / (axis.max - axis.min) * 100; } - /** - * We always correct borderRadius as a percentage rather than pixels to reduce paints. - * For example, if you are projecting a box that is 100px wide with a 10px borderRadius - * into a box that is 200px wide with a 20px borderRadius, that is actually a 10% - * borderRadius in both states. If we animate between the two in pixels that will trigger - * a paint each time. If we animate between the two in percentage we'll avoid a paint. - */ - var correctBorderRadius = { - correct: function (latest, node) { - if (!node.target) return latest; - /** - * If latest is a string, if it's a percentage we can return immediately as it's - * going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number. - */ - if (typeof latest === "string") { - if (styleValueTypes.px.test(latest)) { - latest = parseFloat(latest); - } else { - return latest; - } - } - /** - * If latest is a number, it's a pixel value. We use the current viewportBox to calculate that - * pixel value as a percentage of each axis - */ - var x = pixelsToPercent(latest, node.target.x); - var y = pixelsToPercent(latest, node.target.y); - return "".concat(x, "% ").concat(y, "%"); + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, { + nodes: fieldNodes + }); + } + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError(`Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, { + nodes: fieldNodes + }); + } + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + if ((0, _isPromise.isPromise)(isTypeOf)) { + return isTypeOf.then(resolvedIsTypeOf => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + return executeFields(exeContext, returnType, result, path, subFieldNodes); + }); } - }; - var varToken = "_$css"; - var correctBoxShadow = { - correct: function (latest, _a) { - var treeScale = _a.treeScale, - projectionDelta = _a.projectionDelta; - var original = latest; - /** - * We need to first strip and store CSS variables from the string. - */ - var containsCSSVariables = latest.includes("var("); - var cssVariables = []; - if (containsCSSVariables) { - latest = latest.replace(cssVariableRegex, function (match) { - cssVariables.push(match); - return varToken; - }); - } - var shadow = styleValueTypes.complex.parse(latest); - // TODO: Doesn't support multiple shadows - if (shadow.length > 5) return original; - var template = styleValueTypes.complex.createTransformer(latest); - var offset = typeof shadow[0] !== "number" ? 1 : 0; - // Calculate the overall context scale - var xScale = projectionDelta.x.scale * treeScale.x; - var yScale = projectionDelta.y.scale * treeScale.y; - shadow[0 + offset] /= xScale; - shadow[1 + offset] /= yScale; - /** - * Ideally we'd correct x and y scales individually, but because blur and - * spread apply to both we have to take a scale average and apply that instead. - * We could potentially improve the outcome of this by incorporating the ratio between - * the two scales. - */ - var averageScale = popmotion.mix(xScale, yScale, 0.5); - // Blur - if (typeof shadow[2 + offset] === "number") shadow[2 + offset] /= averageScale; - // Spread - if (typeof shadow[3 + offset] === "number") shadow[3 + offset] /= averageScale; - var output = template(shadow); - if (containsCSSVariables) { - var i_1 = 0; - output = output.replace(varToken, function () { - var cssVariable = cssVariables[i_1]; - i_1++; - return cssVariable; - }); - } - return output; + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); } - }; - var MeasureLayoutWithContext = /** @class */function (_super) { - tslib.__extends(MeasureLayoutWithContext, _super); - function MeasureLayoutWithContext() { - return _super !== null && _super.apply(this, arguments) || this; + } + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError(`Expected value of type "${returnType.name}" but got: ${(0, _inspect.inspect)(result)}.`, { + nodes: fieldNodes + }); +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + +const defaultTypeResolver = function (value, contextValue, info, abstractType) { + // First, look for `__typename`. + if ((0, _isObjectLike.isObjectLike)(value) && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + if ((0, _isPromise.isPromise)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type.name; + } } - /** - * This only mounts projection nodes for components that - * need measuring, we might want to do it for all components - * in order to incorporate transforms - */ - MeasureLayoutWithContext.prototype.componentDidMount = function () { - var _this = this; - var _a = this.props, - visualElement = _a.visualElement, - layoutGroup = _a.layoutGroup, - switchLayoutGroup = _a.switchLayoutGroup, - layoutId = _a.layoutId; - var projection = visualElement.projection; - addScaleCorrector(defaultScaleCorrectors); - if (projection) { - if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group) layoutGroup.group.add(projection); - if ((switchLayoutGroup === null || switchLayoutGroup === void 0 ? void 0 : switchLayoutGroup.register) && layoutId) { - switchLayoutGroup.register(projection); - } - projection.root.didUpdate(); - projection.addEventListener("animationComplete", function () { - _this.safeToRemove(); - }); - projection.setOptions(tslib.__assign(tslib.__assign({}, projection.options), { - onExitComplete: function () { - return _this.safeToRemove(); - } - })); - } - globalProjectionState.hasEverUpdated = true; - }; - MeasureLayoutWithContext.prototype.getSnapshotBeforeUpdate = function (prevProps) { - var _this = this; - var _a = this.props, - layoutDependency = _a.layoutDependency, - visualElement = _a.visualElement, - drag = _a.drag, - isPresent = _a.isPresent; - var projection = visualElement.projection; - if (!projection) return null; - /** - * TODO: We use this data in relegate to determine whether to - * promote a previous element. There's no guarantee its presence data - * will have updated by this point - if a bug like this arises it will - * have to be that we markForRelegation and then find a new lead some other way, - * perhaps in didUpdate - */ - projection.isPresent = isPresent; - if (drag || prevProps.layoutDependency !== layoutDependency || layoutDependency === undefined) { - projection.willUpdate(); - } else { - this.safeToRemove(); - } - if (prevProps.isPresent !== isPresent) { - if (isPresent) { - projection.promote(); - } else if (!projection.relegate()) { - /** - * If there's another stack member taking over from this one, - * it's in charge of the exit animation and therefore should - * be in charge of the safe to remove. Otherwise we call it here. - */ - sync__default["default"].postRender(function () { - var _a; - if (!((_a = projection.getStack()) === null || _a === void 0 ? void 0 : _a.members.length)) { - _this.safeToRemove(); - } - }); + } + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; } } - return null; - }; - MeasureLayoutWithContext.prototype.componentDidUpdate = function () { - var projection = this.props.visualElement.projection; - if (projection) { - projection.root.didUpdate(); - if (!projection.currentAnimation && projection.isLead()) { - this.safeToRemove(); + }); + } +}; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ +exports.defaultTypeResolver = defaultTypeResolver; +const defaultFieldResolver = function (source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { + const property = source[info.fieldName]; + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ +exports.defaultFieldResolver = defaultFieldResolver; +function getFieldDef(schema, parentType, fieldNode) { + const fieldName = fieldNode.name.value; + if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; + } + return parentType.getFields()[fieldName]; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/execution/index.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/execution/index.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "createSourceEventStream", ({ + enumerable: true, + get: function () { + return _subscribe.createSourceEventStream; + } +})); +Object.defineProperty(exports, "defaultFieldResolver", ({ + enumerable: true, + get: function () { + return _execute.defaultFieldResolver; + } +})); +Object.defineProperty(exports, "defaultTypeResolver", ({ + enumerable: true, + get: function () { + return _execute.defaultTypeResolver; + } +})); +Object.defineProperty(exports, "execute", ({ + enumerable: true, + get: function () { + return _execute.execute; + } +})); +Object.defineProperty(exports, "executeSync", ({ + enumerable: true, + get: function () { + return _execute.executeSync; + } +})); +Object.defineProperty(exports, "getArgumentValues", ({ + enumerable: true, + get: function () { + return _values.getArgumentValues; + } +})); +Object.defineProperty(exports, "getDirectiveValues", ({ + enumerable: true, + get: function () { + return _values.getDirectiveValues; + } +})); +Object.defineProperty(exports, "getVariableValues", ({ + enumerable: true, + get: function () { + return _values.getVariableValues; + } +})); +Object.defineProperty(exports, "responsePathAsArray", ({ + enumerable: true, + get: function () { + return _Path.pathToArray; + } +})); +Object.defineProperty(exports, "subscribe", ({ + enumerable: true, + get: function () { + return _subscribe.subscribe; + } +})); +var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); +var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); +var _subscribe = __webpack_require__(/*! ./subscribe.mjs */ "../../../node_modules/graphql/execution/subscribe.mjs"); +var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs": +/*!********************************************************************!*\ + !*** ../../../node_modules/graphql/execution/mapAsyncIterator.mjs ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.mapAsyncIterator = mapAsyncIterator; +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +function mapAsyncIterator(iterable, callback) { + const iterator = iterable[Symbol.asyncIterator](); + async function mapResult(result) { + if (result.done) { + return result; + } + try { + return { + value: await callback(result.value), + done: false + }; + } catch (error) { + /* c8 ignore start */ + // FIXME: add test case + if (typeof iterator.return === 'function') { + try { + await iterator.return(); + } catch (_e) { + /* ignore error */ } } - }; - MeasureLayoutWithContext.prototype.componentWillUnmount = function () { - var _a = this.props, - visualElement = _a.visualElement, - layoutGroup = _a.layoutGroup, - promoteContext = _a.switchLayoutGroup; - var projection = visualElement.projection; - if (projection) { - projection.scheduleCheckAfterUnmount(); - if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group) layoutGroup.group.remove(projection); - if (promoteContext === null || promoteContext === void 0 ? void 0 : promoteContext.deregister) promoteContext.deregister(projection); - } - }; - MeasureLayoutWithContext.prototype.safeToRemove = function () { - var safeToRemove = this.props.safeToRemove; - safeToRemove === null || safeToRemove === void 0 ? void 0 : safeToRemove(); - }; - MeasureLayoutWithContext.prototype.render = function () { - return null; - }; - return MeasureLayoutWithContext; - }(React__default["default"].Component); - function MeasureLayout(props) { - var _a = tslib.__read(usePresence(), 2), - isPresent = _a[0], - safeToRemove = _a[1]; - var layoutGroup = React.useContext(LayoutGroupContext); - return React__default["default"].createElement(MeasureLayoutWithContext, tslib.__assign({}, props, { - layoutGroup: layoutGroup, - switchLayoutGroup: React.useContext(SwitchLayoutGroupContext), - isPresent: isPresent, - safeToRemove: safeToRemove - })); + throw error; + /* c8 ignore stop */ + } } - var defaultScaleCorrectors = { - borderRadius: tslib.__assign(tslib.__assign({}, correctBorderRadius), { - applyTo: ["borderTopLeftRadius", "borderTopRightRadius", "borderBottomLeftRadius", "borderBottomRightRadius"] - }), - borderTopLeftRadius: correctBorderRadius, - borderTopRightRadius: correctBorderRadius, - borderBottomLeftRadius: correctBorderRadius, - borderBottomRightRadius: correctBorderRadius, - boxShadow: correctBoxShadow + return { + async next() { + return mapResult(await iterator.next()); + }, + async return() { + // If iterator.return() does not exist, then type R must be undefined. + return typeof iterator.return === 'function' ? mapResult(await iterator.return()) : { + value: undefined, + done: true + }; + }, + async throw(error) { + if (typeof iterator.throw === 'function') { + return mapResult(await iterator.throw(error)); + } + throw error; + }, + [Symbol.asyncIterator]() { + return this; + } }; - var layoutFeatures = { - measureLayout: MeasureLayout +} + +/***/ }), + +/***/ "../../../node_modules/graphql/execution/subscribe.mjs": +/*!*************************************************************!*\ + !*** ../../../node_modules/graphql/execution/subscribe.mjs ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createSourceEventStream = createSourceEventStream; +exports.subscribe = subscribe; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _isAsyncIterable = __webpack_require__(/*! ../jsutils/isAsyncIterable.mjs */ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs"); +var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); +var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); +var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); +var _mapAsyncIterator = __webpack_require__(/*! ./mapAsyncIterator.mjs */ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs"); +var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ + +async function subscribe(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); + const resultOrStream = await createSourceEventStream(args); + if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { + return resultOrStream; + } // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + const mapSourceToResponse = payload => (0, _execute.execute)({ + ...args, + rootValue: payload + }); // Map every source value to a ExecutionResult value as described above. + + return (0, _mapAsyncIterator.mapAsyncIterator)(resultOrStream, mapSourceToResponse); +} +function toNormalizedArgs(args) { + const firstArg = args[0]; + if (firstArg && 'document' in firstArg) { + return firstArg; + } + return { + schema: firstArg, + // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 + document: args[1], + rootValue: args[2], + contextValue: args[3], + variableValues: args[4], + operationName: args[5], + subscribeFieldResolver: args[6] }; - - /** - * Animate a single value or a `MotionValue`. - * - * The first argument is either a `MotionValue` to animate, or an initial animation value. - * - * The second is either a value to animate to, or an array of keyframes to animate through. - * - * The third argument can be either tween or spring options, and optional lifecycle methods: `onUpdate`, `onPlay`, `onComplete`, `onRepeat` and `onStop`. - * - * Returns `AnimationPlaybackControls`, currently just a `stop` method. - * - * ```javascript - * const x = useMotionValue(0) - * - * useEffect(() => { - * const controls = animate(x, 100, { - * type: "spring", - * stiffness: 2000, - * onComplete: v => {} - * }) - * - * return controls.stop - * }) - * ``` - * - * @public - */ - function animate(from, to, transition) { - if (transition === void 0) { - transition = {}; - } - var value = isMotionValue(from) ? from : motionValue(from); - startAnimation("", value, to, transition); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise which resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + +async function createSourceEventStream(...rawArgs) { + const args = toNormalizedArgs(rawArgs); + const { + schema, + document, + variableValues + } = args; // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { return { - stop: function () { - return value.stop(); - }, - isAnimating: function () { - return value.isAnimating(); - } + errors: exeContext }; } - var borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"]; - var numBorders = borders.length; - var asNumber = function (value) { - return typeof value === "string" ? parseFloat(value) : value; - }; - var isPx = function (value) { - return typeof value === "number" || styleValueTypes.px.test(value); - }; - function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) { - var _a, _b, _c, _d; - if (shouldCrossfadeOpacity) { - target.opacity = popmotion.mix(0, - // (follow?.opacity as number) ?? 0, - // TODO Reinstate this if only child - (_a = lead.opacity) !== null && _a !== void 0 ? _a : 1, easeCrossfadeIn(progress)); - target.opacityExit = popmotion.mix((_b = follow.opacity) !== null && _b !== void 0 ? _b : 1, 0, easeCrossfadeOut(progress)); - } else if (isOnlyMember) { - target.opacity = popmotion.mix((_c = follow.opacity) !== null && _c !== void 0 ? _c : 1, (_d = lead.opacity) !== null && _d !== void 0 ? _d : 1, progress); - } - /** - * Mix border radius - */ - for (var i = 0; i < numBorders; i++) { - var borderLabel = "border".concat(borders[i], "Radius"); - var followRadius = getRadius(follow, borderLabel); - var leadRadius = getRadius(lead, borderLabel); - if (followRadius === undefined && leadRadius === undefined) continue; - followRadius || (followRadius = 0); - leadRadius || (leadRadius = 0); - var canMix = followRadius === 0 || leadRadius === 0 || isPx(followRadius) === isPx(leadRadius); - if (canMix) { - target[borderLabel] = Math.max(popmotion.mix(asNumber(followRadius), asNumber(leadRadius), progress), 0); - if (styleValueTypes.percent.test(leadRadius) || styleValueTypes.percent.test(followRadius)) { - target[borderLabel] += "%"; - } - } else { - target[borderLabel] = leadRadius; - } - } - /** - * Mix rotation - */ - if (follow.rotate || lead.rotate) { - target.rotate = popmotion.mix(follow.rotate || 0, lead.rotate || 0, progress); + try { + const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. + + if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { + throw new Error('Subscription field must return Async Iterable. ' + `Received: ${(0, _inspect.inspect)(eventStream)}.`); + } + return eventStream; + } catch (error) { + // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. + // Otherwise treat the error as a system-class error and re-throw it. + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error] + }; } + throw error; } - function getRadius(values, radiusName) { - var _a; - return (_a = values[radiusName]) !== null && _a !== void 0 ? _a : values.borderRadius; - } - // /** - // * We only want to mix the background color if there's a follow element - // * that we're not crossfading opacity between. For instance with switch - // * AnimateSharedLayout animations, this helps the illusion of a continuous - // * element being animated but also cuts down on the number of paints triggered - // * for elements where opacity is doing that work for us. - // */ - // if ( - // !hasFollowElement && - // latestLeadValues.backgroundColor && - // latestFollowValues.backgroundColor - // ) { - // /** - // * This isn't ideal performance-wise as mixColor is creating a new function every frame. - // * We could probably create a mixer that runs at the start of the animation but - // * the idea behind the crossfader is that it runs dynamically between two potentially - // * changing targets (ie opacity or borderRadius may be animating independently via variants) - // */ - // leadState.backgroundColor = followState.backgroundColor = mixColor( - // latestFollowValues.backgroundColor as string, - // latestLeadValues.backgroundColor as string - // )(p) - // } - var easeCrossfadeIn = compress(0, 0.5, popmotion.circOut); - var easeCrossfadeOut = compress(0.5, 0.95, popmotion.linear); - function compress(min, max, easing) { - return function (p) { - // Could replace ifs with clamp - if (p < min) return 0; - if (p > max) return 1; - return easing(popmotion.progress(min, max, p)); - }; - } - - /** - * Reset an axis to the provided origin box. - * - * This is a mutative operation. - */ - function copyAxisInto(axis, originAxis) { - axis.min = originAxis.min; - axis.max = originAxis.max; +} +async function executeSubscription(exeContext) { + const { + schema, + fragments, + operation, + variableValues, + rootValue + } = exeContext; + const rootType = schema.getSubscriptionType(); + if (rootType == null) { + throw new _GraphQLError.GraphQLError('Schema is not configured to execute subscription operation.', { + nodes: operation + }); } - /** - * Reset a box to the provided origin box. - * - * This is a mutative operation. - */ - function copyBoxInto(box, originBox) { - copyAxisInto(box.x, originBox.x); - copyAxisInto(box.y, originBox.y); + const rootFields = (0, _collectFields.collectFields)(schema, fragments, variableValues, rootType, operation.selectionSet); + const [responseName, fieldNodes] = [...rootFields.entries()][0]; + const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); + if (!fieldDef) { + const fieldName = fieldNodes[0].name.value; + throw new _GraphQLError.GraphQLError(`The subscription field "${fieldName}" is not defined.`, { + nodes: fieldNodes + }); } - - /** - * Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse - */ - function removePointDelta(point, translate, scale, originPoint, boxScale) { - point -= translate; - point = scalePoint(point, 1 / scale, originPoint); - if (boxScale !== undefined) { - point = scalePoint(point, 1 / boxScale, originPoint); + const path = (0, _Path.addPath)(undefined, responseName, rootType.name); + const info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, rootType, path); + try { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + const resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.subscribeFieldResolver; + const eventStream = await resolveFn(rootValue, args, contextValue, info); + if (eventStream instanceof Error) { + throw eventStream; } - return point; + return eventStream; + } catch (error) { + throw (0, _locatedError.locatedError)(error, fieldNodes, (0, _Path.pathToArray)(path)); } - /** - * Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse - */ - function removeAxisDelta(axis, translate, scale, origin, boxScale, originAxis, sourceAxis) { - if (translate === void 0) { - translate = 0; - } - if (scale === void 0) { - scale = 1; - } - if (origin === void 0) { - origin = 0.5; - } - if (originAxis === void 0) { - originAxis = axis; - } - if (sourceAxis === void 0) { - sourceAxis = axis; - } - if (styleValueTypes.percent.test(translate)) { - translate = parseFloat(translate); - var relativeProgress = popmotion.mix(sourceAxis.min, sourceAxis.max, translate / 100); - translate = relativeProgress - sourceAxis.min; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/execution/values.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/execution/values.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; +exports.getVariableValues = getVariableValues; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _coerceInputValue = __webpack_require__(/*! ../utilities/coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); +var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +var _valueFromAST = __webpack_require__(/*! ../utilities/valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors; + try { + const coerced = coerceVariableValues(schema, varDefNodes, inputs, error => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new _GraphQLError.GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.'); + } + errors.push(error); + }); + if (errors.length === 0) { + return { + coerced + }; } - if (typeof translate !== "number") return; - var originPoint = popmotion.mix(originAxis.min, originAxis.max, origin); - if (axis === originAxis) originPoint -= translate; - axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale); - axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale); + } catch (error) { + errors.push(error); } - /** - * Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse - * and acts as a bridge between motion values and removeAxisDelta - */ - function removeAxisTransforms(axis, transforms, _a, origin, sourceAxis) { - var _b = tslib.__read(_a, 3), - key = _b[0], - scaleKey = _b[1], - originKey = _b[2]; - removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); - } - /** - * The names of the motion values we want to apply as translation, scale and origin. - */ - var xKeys = ["x", "scaleX", "originX"]; - var yKeys = ["y", "scaleY", "originY"]; - /** - * Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse - * and acts as a bridge between motion values and removeAxisDelta - */ - function removeBoxTransforms(box, transforms, originBox, sourceBox) { - removeAxisTransforms(box.x, transforms, xKeys, originBox === null || originBox === void 0 ? void 0 : originBox.x, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.x); - removeAxisTransforms(box.y, transforms, yKeys, originBox === null || originBox === void 0 ? void 0 : originBox.y, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.y); - } - function isAxisDeltaZero(delta) { - return delta.translate === 0 && delta.scale === 1; - } - function isDeltaZero(delta) { - return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); - } - function boxEquals(a, b) { - return a.x.min === b.x.min && a.x.max === b.x.max && a.y.min === b.y.min && a.y.max === b.y.max; - } - var NodeStack = /** @class */function () { - function NodeStack() { - this.members = []; + return { + errors + }; +} +function coerceVariableValues(schema, varDefNodes, inputs, onError) { + const coercedValues = {}; + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = (0, _printer.print)(varDefNode.type); + onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, { + nodes: varDefNode.type + })); + continue; } - NodeStack.prototype.add = function (node) { - addUniqueItem(this.members, node); - node.scheduleRender(); - }; - NodeStack.prototype.remove = function (node) { - removeItem(this.members, node); - if (node === this.prevLead) { - this.prevLead = undefined; - } - if (node === this.lead) { - var prevLead = this.members[this.members.length - 1]; - if (prevLead) { - this.promote(prevLead); - } + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); + } else if ((0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, { + nodes: varDefNode + })); } - }; - NodeStack.prototype.relegate = function (node) { - var indexOfNode = this.members.findIndex(function (member) { - return node === member; - }); - if (indexOfNode === 0) return false; - /** - * Find the next projection node that is present - */ - var prevLead; - for (var i = indexOfNode; i >= 0; i--) { - var member = this.members[i]; - if (member.isPresent !== false) { - prevLead = member; - break; - } + continue; + } + const value = inputs[varName]; + if (value === null && (0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, { + nodes: varDefNode + })); + continue; + } + coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)(value, varType, (path, invalidValue, error) => { + let prefix = `Variable "$${varName}" got invalid value ` + (0, _inspect.inspect)(invalidValue); + if (path.length > 0) { + prefix += ` at "${varName}${(0, _printPathArray.printPathArray)(path)}"`; } - if (prevLead) { - this.promote(prevLead); - return true; - } else { - return false; + onError(new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { + nodes: varDefNode, + originalError: error + })); + }); + } + return coercedValues; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + +function getArgumentValues(def, node, variableValues) { + var _node$arguments; + const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : []; + const argNodeMap = (0, _keyMap.keyMap)(argumentNodes, arg => arg.name.value); + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + 'was not provided.', { + nodes: node + }); } - }; - NodeStack.prototype.promote = function (node, preserveFollowOpacity) { - var _a; - var prevLead = this.lead; - if (node === prevLead) return; - this.prevLead = prevLead; - this.lead = node; - node.show(); - if (prevLead) { - prevLead.instance && prevLead.scheduleRender(); - node.scheduleRender(); - node.resumeFrom = prevLead; - if (preserveFollowOpacity) { - node.resumeFrom.preserveOpacity = true; - } - if (prevLead.snapshot) { - node.snapshot = prevLead.snapshot; - node.snapshot.latestValues = prevLead.animationValues || prevLead.latestValues; - node.snapshot.isShared = true; - } - if ((_a = node.root) === null || _a === void 0 ? void 0 : _a.isUpdating) { - node.isLayoutDirty = true; - } - var crossfade = node.options.crossfade; - if (crossfade === false) { - prevLead.hide(); + continue; + } + const valueNode = argumentNode.value; + let isNull = valueNode.kind === _kinds.Kind.NULL; + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (variableValues == null || !hasOwnProperty(variableValues, variableName)) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + `was provided the variable "$${variableName}" which was not provided a runtime value.`, { + nodes: valueNode + }); } - /** - * TODO: - * - Test border radius when previous node was deleted - * - boxShadow mixing - * - Shared between element A in scrolled container and element B (scroll stays the same or changes) - * - Shared between element A in transformed container and element B (transform stays the same or changes) - * - Shared between element A in scrolled page and element B (scroll stays the same or changes) - * --- - * - Crossfade opacity of root nodes - * - layoutId changes after animation - * - layoutId changes mid animation - */ + continue; } - }; - NodeStack.prototype.exitAnimationComplete = function () { - this.members.forEach(function (node) { - var _a, _b, _c, _d, _e; - (_b = (_a = node.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a); - (_e = (_c = node.resumingFrom) === null || _c === void 0 ? void 0 : (_d = _c.options).onExitComplete) === null || _e === void 0 ? void 0 : _e.call(_d); + isNull = variableValues[variableName] == null; + } + if (isNull && (0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError(`Argument "${name}" of non-null type "${(0, _inspect.inspect)(argType)}" ` + 'must not be null.', { + nodes: valueNode }); - }; - NodeStack.prototype.scheduleRender = function () { - this.members.forEach(function (node) { - node.instance && node.scheduleRender(false); + } + const coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError(`Argument "${name}" has invalid value ${(0, _printer.print)(valueNode)}.`, { + nodes: valueNode }); - }; - /** - * Clear any leads that have been removed this render to prevent them from being - * used in future animations and to prevent memory leaks - */ - NodeStack.prototype.removeLeadSnapshot = function () { - if (this.lead && this.lead.snapshot) { - this.lead.snapshot = undefined; - } - }; - return NodeStack; - }(); - var identityProjection = "translate3d(0px, 0px, 0) scale(1, 1) scale(1, 1)"; - function buildProjectionTransform(delta, treeScale, latestTransform) { - /** - * The translations we use to calculate are always relative to the viewport coordinate space. - * But when we apply scales, we also scale the coordinate space of an element and its children. - * For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need - * to move an element 100 pixels, we actually need to move it 200 in within that scaled space. - */ - var xTranslate = delta.x.translate / treeScale.x; - var yTranslate = delta.y.translate / treeScale.y; - var transform = "translate3d(".concat(xTranslate, "px, ").concat(yTranslate, "px, 0) "); - /** - * Apply scale correction for the tree transform. - * This will apply scale to the screen-orientated axes. - */ - transform += "scale(".concat(1 / treeScale.x, ", ").concat(1 / treeScale.y, ") "); - if (latestTransform) { - var rotate = latestTransform.rotate, - rotateX = latestTransform.rotateX, - rotateY = latestTransform.rotateY; - if (rotate) transform += "rotate(".concat(rotate, "deg) "); - if (rotateX) transform += "rotateX(".concat(rotateX, "deg) "); - if (rotateY) transform += "rotateY(".concat(rotateY, "deg) "); } - /** - * Apply scale to match the size of the element to the size we want it. - * This will apply scale to the element-orientated axes. - */ - var elementScaleX = delta.x.scale * treeScale.x; - var elementScaleY = delta.y.scale * treeScale.y; - transform += "scale(".concat(elementScaleX, ", ").concat(elementScaleY, ")"); - return transform === identityProjection ? "none" : transform; - } - var compareByDepth = function (a, b) { - return a.depth - b.depth; - }; - var FlatTree = /** @class */function () { - function FlatTree() { - this.children = []; - this.isDirty = false; - } - FlatTree.prototype.add = function (child) { - addUniqueItem(this.children, child); - this.isDirty = true; + coercedValues[name] = coercedValue; + } + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + +function getDirectiveValues(directiveDef, node, variableValues) { + var _node$directives; + const directiveNode = (_node$directives = node.directives) === null || _node$directives === void 0 ? void 0 : _node$directives.find(directive => directive.name.value === directiveDef.name); + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/graphql.mjs": +/*!*************************************************!*\ + !*** ../../../node_modules/graphql/graphql.mjs ***! + \*************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.graphql = graphql; +exports.graphqlSync = graphqlSync; +var _devAssert = __webpack_require__(/*! ./jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _isPromise = __webpack_require__(/*! ./jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); +var _parser = __webpack_require__(/*! ./language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); +var _validate = __webpack_require__(/*! ./type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); +var _validate2 = __webpack_require__(/*! ./validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); +var _execute = __webpack_require__(/*! ./execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + * typeResolver: + * A type resolver function to use when none is provided by the schema. + * If not provided, the default type resolver is used (which looks for a + * `__typename` field or alternatively calls the `isTypeOf` method). + */ + +function graphql(args) { + // Always return a Promise for a consistent API. + return new Promise(resolve => resolve(graphqlImpl(args))); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + +function graphqlSync(args) { + const result = graphqlImpl(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + return result; +} +function graphqlImpl(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver + } = args; // Validate Schema + + const schemaValidationErrors = (0, _validate.validateSchema)(schema); + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors }; - FlatTree.prototype.remove = function (child) { - removeItem(this.children, child); - this.isDirty = true; + } // Parse + + let document; + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError] }; - FlatTree.prototype.forEach = function (callback) { - this.isDirty && this.children.sort(compareByDepth); - this.isDirty = false; - this.children.forEach(callback); + } // Validate + + const validationErrors = (0, _validate2.validate)(schema, document); + if (validationErrors.length > 0) { + return { + errors: validationErrors }; - return FlatTree; - }(); - - /** - * We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1 - * which has a noticeable difference in spring animations - */ - var animationTarget = 1000; - function createProjectionNode(_a) { - var attachResizeListener = _a.attachResizeListener, - defaultParent = _a.defaultParent, - measureScroll = _a.measureScroll, - checkIsScrollRoot = _a.checkIsScrollRoot, - resetTransform = _a.resetTransform; - return /** @class */function () { - function ProjectionNode(id, latestValues, parent) { - var _this = this; - if (latestValues === void 0) { - latestValues = {}; - } - if (parent === void 0) { - parent = defaultParent === null || defaultParent === void 0 ? void 0 : defaultParent(); - } - /** - * A Set containing all this component's children. This is used to iterate - * through the children. - * - * TODO: This could be faster to iterate as a flat array stored on the root node. - */ - this.children = new Set(); - /** - * Options for the node. We use this to configure what kind of layout animations - * we should perform (if any). - */ - this.options = {}; - /** - * We use this to detect when its safe to shut down part of a projection tree. - * We have to keep projecting children for scale correction and relative projection - * until all their parents stop performing layout animations. - */ - this.isTreeAnimating = false; - this.isAnimationBlocked = false; - /** - * Flag to true if we think this layout has been changed. We can't always know this, - * currently we set it to true every time a component renders, or if it has a layoutDependency - * if that has changed between renders. Additionally, components can be grouped by LayoutGroup - * and if one node is dirtied, they all are. - */ - this.isLayoutDirty = false; - /** - * Block layout updates for instant layout transitions throughout the tree. - */ - this.updateManuallyBlocked = false; - this.updateBlockedByResize = false; - /** - * Set to true between the start of the first `willUpdate` call and the end of the `didUpdate` - * call. - */ - this.isUpdating = false; - /** - * If this is an SVG element we currently disable projection transforms - */ - this.isSVG = false; - /** - * Flag to true (during promotion) if a node doing an instant layout transition needs to reset - * its projection styles. - */ - this.needsReset = false; - /** - * Flags whether this node should have its transform reset prior to measuring. - */ - this.shouldResetTransform = false; - /** - * An object representing the calculated contextual/accumulated/tree scale. - * This will be used to scale calculcated projection transforms, as these are - * calculated in screen-space but need to be scaled for elements to actually - * make it to their calculated destinations. - * - * TODO: Lazy-init - */ - this.treeScale = { - x: 1, - y: 1 - }; - /** - * - */ - this.eventHandlers = new Map(); - // Note: Currently only running on root node - this.potentialNodes = new Map(); - this.checkUpdateFailed = function () { - if (_this.isUpdating) { - _this.isUpdating = false; - _this.clearAllSnapshots(); - } - }; - this.updateProjection = function () { - _this.nodes.forEach(resolveTargetDelta); - _this.nodes.forEach(calcProjection); - }; - this.hasProjected = false; - this.isVisible = true; - this.animationProgress = 0; - /** - * Shared layout - */ - // TODO Only running on root node - this.sharedNodes = new Map(); - this.id = id; - this.latestValues = latestValues; - this.root = parent ? parent.root || parent : this; - this.path = parent ? tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(parent.path), false), [parent], false) : []; - this.parent = parent; - this.depth = parent ? parent.depth + 1 : 0; - id && this.root.registerPotentialNode(id, this); - for (var i = 0; i < this.path.length; i++) { - this.path[i].shouldResetTransform = true; - } - if (this.root === this) this.nodes = new FlatTree(); + } // Execute + + return (0, _execute.execute)({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver + }); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/index.mjs": +/*!***********************************************!*\ + !*** ../../../node_modules/graphql/index.mjs ***! + \***********************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "BREAK", ({ + enumerable: true, + get: function () { + return _index2.BREAK; + } +})); +Object.defineProperty(exports, "BreakingChangeType", ({ + enumerable: true, + get: function () { + return _index6.BreakingChangeType; + } +})); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ + enumerable: true, + get: function () { + return _index.DEFAULT_DEPRECATION_REASON; + } +})); +Object.defineProperty(exports, "DangerousChangeType", ({ + enumerable: true, + get: function () { + return _index6.DangerousChangeType; + } +})); +Object.defineProperty(exports, "DirectiveLocation", ({ + enumerable: true, + get: function () { + return _index2.DirectiveLocation; + } +})); +Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ + enumerable: true, + get: function () { + return _index4.ExecutableDefinitionsRule; + } +})); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _index4.FieldsOnCorrectTypeRule; + } +})); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ + enumerable: true, + get: function () { + return _index4.FragmentsOnCompositeTypesRule; + } +})); +Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ + enumerable: true, + get: function () { + return _index.GRAPHQL_MAX_INT; + } +})); +Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ + enumerable: true, + get: function () { + return _index.GRAPHQL_MIN_INT; + } +})); +Object.defineProperty(exports, "GraphQLBoolean", ({ + enumerable: true, + get: function () { + return _index.GraphQLBoolean; + } +})); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLDeprecatedDirective; + } +})); +Object.defineProperty(exports, "GraphQLDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLDirective; + } +})); +Object.defineProperty(exports, "GraphQLEnumType", ({ + enumerable: true, + get: function () { + return _index.GraphQLEnumType; + } +})); +Object.defineProperty(exports, "GraphQLError", ({ + enumerable: true, + get: function () { + return _index5.GraphQLError; + } +})); +Object.defineProperty(exports, "GraphQLFloat", ({ + enumerable: true, + get: function () { + return _index.GraphQLFloat; + } +})); +Object.defineProperty(exports, "GraphQLID", ({ + enumerable: true, + get: function () { + return _index.GraphQLID; + } +})); +Object.defineProperty(exports, "GraphQLIncludeDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLIncludeDirective; + } +})); +Object.defineProperty(exports, "GraphQLInputObjectType", ({ + enumerable: true, + get: function () { + return _index.GraphQLInputObjectType; + } +})); +Object.defineProperty(exports, "GraphQLInt", ({ + enumerable: true, + get: function () { + return _index.GraphQLInt; + } +})); +Object.defineProperty(exports, "GraphQLInterfaceType", ({ + enumerable: true, + get: function () { + return _index.GraphQLInterfaceType; + } +})); +Object.defineProperty(exports, "GraphQLList", ({ + enumerable: true, + get: function () { + return _index.GraphQLList; + } +})); +Object.defineProperty(exports, "GraphQLNonNull", ({ + enumerable: true, + get: function () { + return _index.GraphQLNonNull; + } +})); +Object.defineProperty(exports, "GraphQLObjectType", ({ + enumerable: true, + get: function () { + return _index.GraphQLObjectType; + } +})); +Object.defineProperty(exports, "GraphQLScalarType", ({ + enumerable: true, + get: function () { + return _index.GraphQLScalarType; + } +})); +Object.defineProperty(exports, "GraphQLSchema", ({ + enumerable: true, + get: function () { + return _index.GraphQLSchema; + } +})); +Object.defineProperty(exports, "GraphQLSkipDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLSkipDirective; + } +})); +Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLSpecifiedByDirective; + } +})); +Object.defineProperty(exports, "GraphQLString", ({ + enumerable: true, + get: function () { + return _index.GraphQLString; + } +})); +Object.defineProperty(exports, "GraphQLUnionType", ({ + enumerable: true, + get: function () { + return _index.GraphQLUnionType; + } +})); +Object.defineProperty(exports, "Kind", ({ + enumerable: true, + get: function () { + return _index2.Kind; + } +})); +Object.defineProperty(exports, "KnownArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownArgumentNamesRule; + } +})); +Object.defineProperty(exports, "KnownDirectivesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownDirectivesRule; + } +})); +Object.defineProperty(exports, "KnownFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownFragmentNamesRule; + } +})); +Object.defineProperty(exports, "KnownTypeNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownTypeNamesRule; + } +})); +Object.defineProperty(exports, "Lexer", ({ + enumerable: true, + get: function () { + return _index2.Lexer; + } +})); +Object.defineProperty(exports, "Location", ({ + enumerable: true, + get: function () { + return _index2.Location; + } +})); +Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ + enumerable: true, + get: function () { + return _index4.LoneAnonymousOperationRule; + } +})); +Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ + enumerable: true, + get: function () { + return _index4.LoneSchemaDefinitionRule; + } +})); +Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ + enumerable: true, + get: function () { + return _index4.NoDeprecatedCustomRule; + } +})); +Object.defineProperty(exports, "NoFragmentCyclesRule", ({ + enumerable: true, + get: function () { + return _index4.NoFragmentCyclesRule; + } +})); +Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ + enumerable: true, + get: function () { + return _index4.NoSchemaIntrospectionCustomRule; + } +})); +Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ + enumerable: true, + get: function () { + return _index4.NoUndefinedVariablesRule; + } +})); +Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ + enumerable: true, + get: function () { + return _index4.NoUnusedFragmentsRule; + } +})); +Object.defineProperty(exports, "NoUnusedVariablesRule", ({ + enumerable: true, + get: function () { + return _index4.NoUnusedVariablesRule; + } +})); +Object.defineProperty(exports, "OperationTypeNode", ({ + enumerable: true, + get: function () { + return _index2.OperationTypeNode; + } +})); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ + enumerable: true, + get: function () { + return _index4.OverlappingFieldsCanBeMergedRule; + } +})); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ + enumerable: true, + get: function () { + return _index4.PossibleFragmentSpreadsRule; + } +})); +Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ + enumerable: true, + get: function () { + return _index4.PossibleTypeExtensionsRule; + } +})); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ + enumerable: true, + get: function () { + return _index4.ProvidedRequiredArgumentsRule; + } +})); +Object.defineProperty(exports, "ScalarLeafsRule", ({ + enumerable: true, + get: function () { + return _index4.ScalarLeafsRule; + } +})); +Object.defineProperty(exports, "SchemaMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.SchemaMetaFieldDef; + } +})); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ + enumerable: true, + get: function () { + return _index4.SingleFieldSubscriptionsRule; + } +})); +Object.defineProperty(exports, "Source", ({ + enumerable: true, + get: function () { + return _index2.Source; + } +})); +Object.defineProperty(exports, "Token", ({ + enumerable: true, + get: function () { + return _index2.Token; + } +})); +Object.defineProperty(exports, "TokenKind", ({ + enumerable: true, + get: function () { + return _index2.TokenKind; + } +})); +Object.defineProperty(exports, "TypeInfo", ({ + enumerable: true, + get: function () { + return _index6.TypeInfo; + } +})); +Object.defineProperty(exports, "TypeKind", ({ + enumerable: true, + get: function () { + return _index.TypeKind; + } +})); +Object.defineProperty(exports, "TypeMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.TypeMetaFieldDef; + } +})); +Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.TypeNameMetaFieldDef; + } +})); +Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueArgumentDefinitionNamesRule; + } +})); +Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueArgumentNamesRule; + } +})); +Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueDirectiveNamesRule; + } +})); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueDirectivesPerLocationRule; + } +})); +Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueEnumValueNamesRule; + } +})); +Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueFieldDefinitionNamesRule; + } +})); +Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueFragmentNamesRule; + } +})); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueInputFieldNamesRule; + } +})); +Object.defineProperty(exports, "UniqueOperationNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueOperationNamesRule; + } +})); +Object.defineProperty(exports, "UniqueOperationTypesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueOperationTypesRule; + } +})); +Object.defineProperty(exports, "UniqueTypeNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueTypeNamesRule; + } +})); +Object.defineProperty(exports, "UniqueVariableNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueVariableNamesRule; + } +})); +Object.defineProperty(exports, "ValidationContext", ({ + enumerable: true, + get: function () { + return _index4.ValidationContext; + } +})); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _index4.ValuesOfCorrectTypeRule; + } +})); +Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ + enumerable: true, + get: function () { + return _index4.VariablesAreInputTypesRule; + } +})); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ + enumerable: true, + get: function () { + return _index4.VariablesInAllowedPositionRule; + } +})); +Object.defineProperty(exports, "__Directive", ({ + enumerable: true, + get: function () { + return _index.__Directive; + } +})); +Object.defineProperty(exports, "__DirectiveLocation", ({ + enumerable: true, + get: function () { + return _index.__DirectiveLocation; + } +})); +Object.defineProperty(exports, "__EnumValue", ({ + enumerable: true, + get: function () { + return _index.__EnumValue; + } +})); +Object.defineProperty(exports, "__Field", ({ + enumerable: true, + get: function () { + return _index.__Field; + } +})); +Object.defineProperty(exports, "__InputValue", ({ + enumerable: true, + get: function () { + return _index.__InputValue; + } +})); +Object.defineProperty(exports, "__Schema", ({ + enumerable: true, + get: function () { + return _index.__Schema; + } +})); +Object.defineProperty(exports, "__Type", ({ + enumerable: true, + get: function () { + return _index.__Type; + } +})); +Object.defineProperty(exports, "__TypeKind", ({ + enumerable: true, + get: function () { + return _index.__TypeKind; + } +})); +Object.defineProperty(exports, "assertAbstractType", ({ + enumerable: true, + get: function () { + return _index.assertAbstractType; + } +})); +Object.defineProperty(exports, "assertCompositeType", ({ + enumerable: true, + get: function () { + return _index.assertCompositeType; + } +})); +Object.defineProperty(exports, "assertDirective", ({ + enumerable: true, + get: function () { + return _index.assertDirective; + } +})); +Object.defineProperty(exports, "assertEnumType", ({ + enumerable: true, + get: function () { + return _index.assertEnumType; + } +})); +Object.defineProperty(exports, "assertEnumValueName", ({ + enumerable: true, + get: function () { + return _index.assertEnumValueName; + } +})); +Object.defineProperty(exports, "assertInputObjectType", ({ + enumerable: true, + get: function () { + return _index.assertInputObjectType; + } +})); +Object.defineProperty(exports, "assertInputType", ({ + enumerable: true, + get: function () { + return _index.assertInputType; + } +})); +Object.defineProperty(exports, "assertInterfaceType", ({ + enumerable: true, + get: function () { + return _index.assertInterfaceType; + } +})); +Object.defineProperty(exports, "assertLeafType", ({ + enumerable: true, + get: function () { + return _index.assertLeafType; + } +})); +Object.defineProperty(exports, "assertListType", ({ + enumerable: true, + get: function () { + return _index.assertListType; + } +})); +Object.defineProperty(exports, "assertName", ({ + enumerable: true, + get: function () { + return _index.assertName; + } +})); +Object.defineProperty(exports, "assertNamedType", ({ + enumerable: true, + get: function () { + return _index.assertNamedType; + } +})); +Object.defineProperty(exports, "assertNonNullType", ({ + enumerable: true, + get: function () { + return _index.assertNonNullType; + } +})); +Object.defineProperty(exports, "assertNullableType", ({ + enumerable: true, + get: function () { + return _index.assertNullableType; + } +})); +Object.defineProperty(exports, "assertObjectType", ({ + enumerable: true, + get: function () { + return _index.assertObjectType; + } +})); +Object.defineProperty(exports, "assertOutputType", ({ + enumerable: true, + get: function () { + return _index.assertOutputType; + } +})); +Object.defineProperty(exports, "assertScalarType", ({ + enumerable: true, + get: function () { + return _index.assertScalarType; + } +})); +Object.defineProperty(exports, "assertSchema", ({ + enumerable: true, + get: function () { + return _index.assertSchema; + } +})); +Object.defineProperty(exports, "assertType", ({ + enumerable: true, + get: function () { + return _index.assertType; + } +})); +Object.defineProperty(exports, "assertUnionType", ({ + enumerable: true, + get: function () { + return _index.assertUnionType; + } +})); +Object.defineProperty(exports, "assertValidName", ({ + enumerable: true, + get: function () { + return _index6.assertValidName; + } +})); +Object.defineProperty(exports, "assertValidSchema", ({ + enumerable: true, + get: function () { + return _index.assertValidSchema; + } +})); +Object.defineProperty(exports, "assertWrappingType", ({ + enumerable: true, + get: function () { + return _index.assertWrappingType; + } +})); +Object.defineProperty(exports, "astFromValue", ({ + enumerable: true, + get: function () { + return _index6.astFromValue; + } +})); +Object.defineProperty(exports, "buildASTSchema", ({ + enumerable: true, + get: function () { + return _index6.buildASTSchema; + } +})); +Object.defineProperty(exports, "buildClientSchema", ({ + enumerable: true, + get: function () { + return _index6.buildClientSchema; + } +})); +Object.defineProperty(exports, "buildSchema", ({ + enumerable: true, + get: function () { + return _index6.buildSchema; + } +})); +Object.defineProperty(exports, "coerceInputValue", ({ + enumerable: true, + get: function () { + return _index6.coerceInputValue; + } +})); +Object.defineProperty(exports, "concatAST", ({ + enumerable: true, + get: function () { + return _index6.concatAST; + } +})); +Object.defineProperty(exports, "createSourceEventStream", ({ + enumerable: true, + get: function () { + return _index3.createSourceEventStream; + } +})); +Object.defineProperty(exports, "defaultFieldResolver", ({ + enumerable: true, + get: function () { + return _index3.defaultFieldResolver; + } +})); +Object.defineProperty(exports, "defaultTypeResolver", ({ + enumerable: true, + get: function () { + return _index3.defaultTypeResolver; + } +})); +Object.defineProperty(exports, "doTypesOverlap", ({ + enumerable: true, + get: function () { + return _index6.doTypesOverlap; + } +})); +Object.defineProperty(exports, "execute", ({ + enumerable: true, + get: function () { + return _index3.execute; + } +})); +Object.defineProperty(exports, "executeSync", ({ + enumerable: true, + get: function () { + return _index3.executeSync; + } +})); +Object.defineProperty(exports, "extendSchema", ({ + enumerable: true, + get: function () { + return _index6.extendSchema; + } +})); +Object.defineProperty(exports, "findBreakingChanges", ({ + enumerable: true, + get: function () { + return _index6.findBreakingChanges; + } +})); +Object.defineProperty(exports, "findDangerousChanges", ({ + enumerable: true, + get: function () { + return _index6.findDangerousChanges; + } +})); +Object.defineProperty(exports, "formatError", ({ + enumerable: true, + get: function () { + return _index5.formatError; + } +})); +Object.defineProperty(exports, "getArgumentValues", ({ + enumerable: true, + get: function () { + return _index3.getArgumentValues; + } +})); +Object.defineProperty(exports, "getDirectiveValues", ({ + enumerable: true, + get: function () { + return _index3.getDirectiveValues; + } +})); +Object.defineProperty(exports, "getEnterLeaveForKind", ({ + enumerable: true, + get: function () { + return _index2.getEnterLeaveForKind; + } +})); +Object.defineProperty(exports, "getIntrospectionQuery", ({ + enumerable: true, + get: function () { + return _index6.getIntrospectionQuery; + } +})); +Object.defineProperty(exports, "getLocation", ({ + enumerable: true, + get: function () { + return _index2.getLocation; + } +})); +Object.defineProperty(exports, "getNamedType", ({ + enumerable: true, + get: function () { + return _index.getNamedType; + } +})); +Object.defineProperty(exports, "getNullableType", ({ + enumerable: true, + get: function () { + return _index.getNullableType; + } +})); +Object.defineProperty(exports, "getOperationAST", ({ + enumerable: true, + get: function () { + return _index6.getOperationAST; + } +})); +Object.defineProperty(exports, "getOperationRootType", ({ + enumerable: true, + get: function () { + return _index6.getOperationRootType; + } +})); +Object.defineProperty(exports, "getVariableValues", ({ + enumerable: true, + get: function () { + return _index3.getVariableValues; + } +})); +Object.defineProperty(exports, "getVisitFn", ({ + enumerable: true, + get: function () { + return _index2.getVisitFn; + } +})); +Object.defineProperty(exports, "graphql", ({ + enumerable: true, + get: function () { + return _graphql.graphql; + } +})); +Object.defineProperty(exports, "graphqlSync", ({ + enumerable: true, + get: function () { + return _graphql.graphqlSync; + } +})); +Object.defineProperty(exports, "introspectionFromSchema", ({ + enumerable: true, + get: function () { + return _index6.introspectionFromSchema; + } +})); +Object.defineProperty(exports, "introspectionTypes", ({ + enumerable: true, + get: function () { + return _index.introspectionTypes; + } +})); +Object.defineProperty(exports, "isAbstractType", ({ + enumerable: true, + get: function () { + return _index.isAbstractType; + } +})); +Object.defineProperty(exports, "isCompositeType", ({ + enumerable: true, + get: function () { + return _index.isCompositeType; + } +})); +Object.defineProperty(exports, "isConstValueNode", ({ + enumerable: true, + get: function () { + return _index2.isConstValueNode; + } +})); +Object.defineProperty(exports, "isDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isDefinitionNode; + } +})); +Object.defineProperty(exports, "isDirective", ({ + enumerable: true, + get: function () { + return _index.isDirective; + } +})); +Object.defineProperty(exports, "isEnumType", ({ + enumerable: true, + get: function () { + return _index.isEnumType; + } +})); +Object.defineProperty(exports, "isEqualType", ({ + enumerable: true, + get: function () { + return _index6.isEqualType; + } +})); +Object.defineProperty(exports, "isExecutableDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isExecutableDefinitionNode; + } +})); +Object.defineProperty(exports, "isInputObjectType", ({ + enumerable: true, + get: function () { + return _index.isInputObjectType; + } +})); +Object.defineProperty(exports, "isInputType", ({ + enumerable: true, + get: function () { + return _index.isInputType; + } +})); +Object.defineProperty(exports, "isInterfaceType", ({ + enumerable: true, + get: function () { + return _index.isInterfaceType; + } +})); +Object.defineProperty(exports, "isIntrospectionType", ({ + enumerable: true, + get: function () { + return _index.isIntrospectionType; + } +})); +Object.defineProperty(exports, "isLeafType", ({ + enumerable: true, + get: function () { + return _index.isLeafType; + } +})); +Object.defineProperty(exports, "isListType", ({ + enumerable: true, + get: function () { + return _index.isListType; + } +})); +Object.defineProperty(exports, "isNamedType", ({ + enumerable: true, + get: function () { + return _index.isNamedType; + } +})); +Object.defineProperty(exports, "isNonNullType", ({ + enumerable: true, + get: function () { + return _index.isNonNullType; + } +})); +Object.defineProperty(exports, "isNullableType", ({ + enumerable: true, + get: function () { + return _index.isNullableType; + } +})); +Object.defineProperty(exports, "isObjectType", ({ + enumerable: true, + get: function () { + return _index.isObjectType; + } +})); +Object.defineProperty(exports, "isOutputType", ({ + enumerable: true, + get: function () { + return _index.isOutputType; + } +})); +Object.defineProperty(exports, "isRequiredArgument", ({ + enumerable: true, + get: function () { + return _index.isRequiredArgument; + } +})); +Object.defineProperty(exports, "isRequiredInputField", ({ + enumerable: true, + get: function () { + return _index.isRequiredInputField; + } +})); +Object.defineProperty(exports, "isScalarType", ({ + enumerable: true, + get: function () { + return _index.isScalarType; + } +})); +Object.defineProperty(exports, "isSchema", ({ + enumerable: true, + get: function () { + return _index.isSchema; + } +})); +Object.defineProperty(exports, "isSelectionNode", ({ + enumerable: true, + get: function () { + return _index2.isSelectionNode; + } +})); +Object.defineProperty(exports, "isSpecifiedDirective", ({ + enumerable: true, + get: function () { + return _index.isSpecifiedDirective; + } +})); +Object.defineProperty(exports, "isSpecifiedScalarType", ({ + enumerable: true, + get: function () { + return _index.isSpecifiedScalarType; + } +})); +Object.defineProperty(exports, "isType", ({ + enumerable: true, + get: function () { + return _index.isType; + } +})); +Object.defineProperty(exports, "isTypeDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeDefinitionNode; + } +})); +Object.defineProperty(exports, "isTypeExtensionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeExtensionNode; + } +})); +Object.defineProperty(exports, "isTypeNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeNode; + } +})); +Object.defineProperty(exports, "isTypeSubTypeOf", ({ + enumerable: true, + get: function () { + return _index6.isTypeSubTypeOf; + } +})); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeSystemDefinitionNode; + } +})); +Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeSystemExtensionNode; + } +})); +Object.defineProperty(exports, "isUnionType", ({ + enumerable: true, + get: function () { + return _index.isUnionType; + } +})); +Object.defineProperty(exports, "isValidNameError", ({ + enumerable: true, + get: function () { + return _index6.isValidNameError; + } +})); +Object.defineProperty(exports, "isValueNode", ({ + enumerable: true, + get: function () { + return _index2.isValueNode; + } +})); +Object.defineProperty(exports, "isWrappingType", ({ + enumerable: true, + get: function () { + return _index.isWrappingType; + } +})); +Object.defineProperty(exports, "lexicographicSortSchema", ({ + enumerable: true, + get: function () { + return _index6.lexicographicSortSchema; + } +})); +Object.defineProperty(exports, "locatedError", ({ + enumerable: true, + get: function () { + return _index5.locatedError; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _index2.parse; + } +})); +Object.defineProperty(exports, "parseConstValue", ({ + enumerable: true, + get: function () { + return _index2.parseConstValue; + } +})); +Object.defineProperty(exports, "parseType", ({ + enumerable: true, + get: function () { + return _index2.parseType; + } +})); +Object.defineProperty(exports, "parseValue", ({ + enumerable: true, + get: function () { + return _index2.parseValue; + } +})); +Object.defineProperty(exports, "print", ({ + enumerable: true, + get: function () { + return _index2.print; + } +})); +Object.defineProperty(exports, "printError", ({ + enumerable: true, + get: function () { + return _index5.printError; + } +})); +Object.defineProperty(exports, "printIntrospectionSchema", ({ + enumerable: true, + get: function () { + return _index6.printIntrospectionSchema; + } +})); +Object.defineProperty(exports, "printLocation", ({ + enumerable: true, + get: function () { + return _index2.printLocation; + } +})); +Object.defineProperty(exports, "printSchema", ({ + enumerable: true, + get: function () { + return _index6.printSchema; + } +})); +Object.defineProperty(exports, "printSourceLocation", ({ + enumerable: true, + get: function () { + return _index2.printSourceLocation; + } +})); +Object.defineProperty(exports, "printType", ({ + enumerable: true, + get: function () { + return _index6.printType; + } +})); +Object.defineProperty(exports, "resolveObjMapThunk", ({ + enumerable: true, + get: function () { + return _index.resolveObjMapThunk; + } +})); +Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ + enumerable: true, + get: function () { + return _index.resolveReadonlyArrayThunk; + } +})); +Object.defineProperty(exports, "responsePathAsArray", ({ + enumerable: true, + get: function () { + return _index3.responsePathAsArray; + } +})); +Object.defineProperty(exports, "separateOperations", ({ + enumerable: true, + get: function () { + return _index6.separateOperations; + } +})); +Object.defineProperty(exports, "specifiedDirectives", ({ + enumerable: true, + get: function () { + return _index.specifiedDirectives; + } +})); +Object.defineProperty(exports, "specifiedRules", ({ + enumerable: true, + get: function () { + return _index4.specifiedRules; + } +})); +Object.defineProperty(exports, "specifiedScalarTypes", ({ + enumerable: true, + get: function () { + return _index.specifiedScalarTypes; + } +})); +Object.defineProperty(exports, "stripIgnoredCharacters", ({ + enumerable: true, + get: function () { + return _index6.stripIgnoredCharacters; + } +})); +Object.defineProperty(exports, "subscribe", ({ + enumerable: true, + get: function () { + return _index3.subscribe; + } +})); +Object.defineProperty(exports, "syntaxError", ({ + enumerable: true, + get: function () { + return _index5.syntaxError; + } +})); +Object.defineProperty(exports, "typeFromAST", ({ + enumerable: true, + get: function () { + return _index6.typeFromAST; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _index4.validate; + } +})); +Object.defineProperty(exports, "validateSchema", ({ + enumerable: true, + get: function () { + return _index.validateSchema; + } +})); +Object.defineProperty(exports, "valueFromAST", ({ + enumerable: true, + get: function () { + return _index6.valueFromAST; + } +})); +Object.defineProperty(exports, "valueFromASTUntyped", ({ + enumerable: true, + get: function () { + return _index6.valueFromASTUntyped; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.version; + } +})); +Object.defineProperty(exports, "versionInfo", ({ + enumerable: true, + get: function () { + return _version.versionInfo; + } +})); +Object.defineProperty(exports, "visit", ({ + enumerable: true, + get: function () { + return _index2.visit; + } +})); +Object.defineProperty(exports, "visitInParallel", ({ + enumerable: true, + get: function () { + return _index2.visitInParallel; + } +})); +Object.defineProperty(exports, "visitWithTypeInfo", ({ + enumerable: true, + get: function () { + return _index6.visitWithTypeInfo; + } +})); +var _version = __webpack_require__(/*! ./version.mjs */ "../../../node_modules/graphql/version.mjs"); +var _graphql = __webpack_require__(/*! ./graphql.mjs */ "../../../node_modules/graphql/graphql.mjs"); +var _index = __webpack_require__(/*! ./type/index.mjs */ "../../../node_modules/graphql/type/index.mjs"); +var _index2 = __webpack_require__(/*! ./language/index.mjs */ "../../../node_modules/graphql/language/index.mjs"); +var _index3 = __webpack_require__(/*! ./execution/index.mjs */ "../../../node_modules/graphql/execution/index.mjs"); +var _index4 = __webpack_require__(/*! ./validation/index.mjs */ "../../../node_modules/graphql/validation/index.mjs"); +var _index5 = __webpack_require__(/*! ./error/index.mjs */ "../../../node_modules/graphql/error/index.mjs"); +var _index6 = __webpack_require__(/*! ./utilities/index.mjs */ "../../../node_modules/graphql/utilities/index.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/Path.mjs": +/*!******************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/Path.mjs ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.addPath = addPath; +exports.pathToArray = pathToArray; +/** + * Given a Path and a key, return a new Path containing the new key. + */ +function addPath(prev, key, typename) { + return { + prev, + key, + typename + }; +} +/** + * Given a Path, return an Array of the path keys. + */ + +function pathToArray(path) { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + return flattened.reverse(); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/devAssert.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/devAssert.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.devAssert = devAssert; +function devAssert(condition, message) { + const booleanCondition = Boolean(condition); + if (!booleanCondition) { + throw new Error(message); + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/didYouMean.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/didYouMean.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.didYouMean = didYouMean; +const MAX_SUGGESTIONS = 5; +/** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ + +function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = secondArg ? [firstArg, secondArg] : [undefined, firstArg]; + let message = ' Did you mean '; + if (subMessage) { + message += subMessage + ' '; + } + const suggestions = suggestionsArg.map(x => `"${x}"`); + switch (suggestions.length) { + case 0: + return ''; + case 1: + return message + suggestions[0] + '?'; + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/groupBy.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/groupBy.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.groupBy = groupBy; +/** + * Groups array items into a Map, given a function to produce grouping key. + */ +function groupBy(list, keyFn) { + const result = new Map(); + for (const item of list) { + const key = keyFn(item); + const group = result.get(key); + if (group === undefined) { + result.set(key, [item]); + } else { + group.push(item); + } + } + return result; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/identityFunc.mjs": +/*!**************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/identityFunc.mjs ***! + \**************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.identityFunc = identityFunc; +/** + * Returns the first argument it receives. + */ +function identityFunc(x) { + return x; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/inspect.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/inspect.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.inspect = inspect; +const MAX_ARRAY_LENGTH = 10; +const MAX_RECURSIVE_DEPTH = 2; +/** + * Used to print values in error messages. + */ + +function inspect(value) { + return formatValue(value, []); +} +function formatValue(value, seenValues) { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + case 'object': + return formatObjectValue(value, seenValues); + default: + return String(value); + } +} +function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return 'null'; + } + if (previouslySeenValues.includes(value)) { + return '[Circular]'; + } + const seenValues = [...previouslySeenValues, value]; + if (isJSONable(value)) { + const jsonValue = value.toJSON(); // check for infinite recursion + + if (jsonValue !== value) { + return typeof jsonValue === 'string' ? jsonValue : formatValue(jsonValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + return formatObject(value, seenValues); +} +function isJSONable(value) { + return typeof value.toJSON === 'function'; +} +function formatObject(object, seenValues) { + const entries = Object.entries(object); + if (entries.length === 0) { + return '{}'; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + const properties = entries.map(([key, value]) => key + ': ' + formatValue(value, seenValues)); + return '{ ' + properties.join(', ') + ' }'; +} +function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + return '[' + items.join(', ') + ']'; +} +function getObjectTag(object) { + const tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, ''); + if (tag === 'Object' && typeof object.constructor === 'function') { + const name = object.constructor.name; + if (typeof name === 'string' && name !== '') { + return name; + } + } + return tag; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/instanceOf.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/instanceOf.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.instanceOf = void 0; +var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + */ + +const instanceOf = exports.instanceOf = /* c8 ignore next 6 */ +// FIXME: https://github.com/graphql/graphql-js/issues/2317 +globalThis.process && globalThis.process.env.NODE_ENV === 'production' ? function instanceOf(value, constructor) { + return value instanceof constructor; +} : function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + if (typeof value === 'object' && value !== null) { + var _value$constructor; + + // Prefer Symbol.toStringTag since it is immune to minification. + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = + // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 + ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name; + if (className === valueClassName) { + const stringifiedValue = (0, _inspect.inspect)(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`); + } + } + return false; +}; + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/invariant.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/invariant.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.invariant = invariant; +function invariant(condition, message) { + const booleanCondition = Boolean(condition); + if (!booleanCondition) { + throw new Error(message != null ? message : 'Unexpected invariant triggered.'); + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs": +/*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isAsyncIterable.mjs ***! + \*****************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isAsyncIterable = isAsyncIterable; +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + */ +function isAsyncIterable(maybeAsyncIterable) { + return typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 ? void 0 : maybeAsyncIterable[Symbol.asyncIterator]) === 'function'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/isIterableObject.mjs": +/*!******************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isIterableObject.mjs ***! + \******************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isIterableObject = isIterableObject; +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @example + * ```ts + * isIterableObject([ 1, 2, 3 ]) // true + * isIterableObject(new Map()) // true + * isIterableObject('ABC') // false + * isIterableObject({ key: 'value' }) // false + * isIterableObject({ length: 1, 0: 'Alpha' }) // false + * ``` + */ +function isIterableObject(maybeIterable) { + return typeof maybeIterable === 'object' && typeof (maybeIterable === null || maybeIterable === void 0 ? void 0 : maybeIterable[Symbol.iterator]) === 'function'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/isObjectLike.mjs": +/*!**************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isObjectLike.mjs ***! + \**************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isObjectLike = isObjectLike; +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ +function isObjectLike(value) { + return typeof value == 'object' && value !== null; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/isPromise.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/isPromise.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isPromise = isPromise; +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +function isPromise(value) { + return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/keyMap.mjs": +/*!********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/keyMap.mjs ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.keyMap = keyMap; +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { + * // Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } + * // } + * + * const jennyEntry = entriesByName['Jenny'] + * + * // { name: 'Jenny', num: '857-6309' } + * ``` + */ +function keyMap(list, keyFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = item; + } + return result; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/keyValMap.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/keyValMap.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.keyValMap = keyValMap; +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * ``` + */ +function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + return result; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/mapValue.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/mapValue.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.mapValue = mapValue; +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ +function mapValue(map, fn) { + const result = Object.create(null); + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); + } + return result; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/memoize3.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/memoize3.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.memoize3 = memoize3; +/** + * Memoizes the provided three-argument function. + */ +function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + if (cache0 === undefined) { + cache0 = new WeakMap(); + } + let cache1 = cache0.get(a1); + if (cache1 === undefined) { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + let cache2 = cache1.get(a2); + if (cache2 === undefined) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + let fnResult = cache2.get(a3); + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); + } + return fnResult; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/naturalCompare.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/naturalCompare.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.naturalCompare = naturalCompare; +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ +function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + let bNum = 0; + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + if (aNum < bNum) { + return -1; } - ProjectionNode.prototype.addEventListener = function (name, handler) { - if (!this.eventHandlers.has(name)) { - this.eventHandlers.set(name, new SubscriptionManager()); - } - return this.eventHandlers.get(name).add(handler); - }; - ProjectionNode.prototype.notifyListeners = function (name) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var subscriptionManager = this.eventHandlers.get(name); - subscriptionManager === null || subscriptionManager === void 0 ? void 0 : subscriptionManager.notify.apply(subscriptionManager, tslib.__spreadArray([], tslib.__read(args), false)); - }; - ProjectionNode.prototype.hasListeners = function (name) { - return this.eventHandlers.has(name); - }; - ProjectionNode.prototype.registerPotentialNode = function (id, node) { - this.potentialNodes.set(id, node); - }; - /** - * Lifecycles - */ - ProjectionNode.prototype.mount = function (instance, isLayoutDirty) { - var _this = this; - var _a; - if (isLayoutDirty === void 0) { - isLayoutDirty = false; - } - if (this.instance) return; - this.isSVG = instance instanceof SVGElement && instance.tagName !== "svg"; - this.instance = instance; - var _b = this.options, - layoutId = _b.layoutId, - layout = _b.layout, - visualElement = _b.visualElement; - if (visualElement && !visualElement.getInstance()) { - visualElement.mount(instance); - } - this.root.nodes.add(this); - (_a = this.parent) === null || _a === void 0 ? void 0 : _a.children.add(this); - this.id && this.root.potentialNodes.delete(this.id); - if (isLayoutDirty && (layout || layoutId)) { - this.isLayoutDirty = true; - } - if (attachResizeListener) { - var unblockTimeout_1; - var resizeUnblockUpdate_1 = function () { - return _this.root.updateBlockedByResize = false; - }; - attachResizeListener(instance, function () { - _this.root.updateBlockedByResize = true; - clearTimeout(unblockTimeout_1); - unblockTimeout_1 = window.setTimeout(resizeUnblockUpdate_1, 250); - if (globalProjectionState.hasAnimatedSinceResize) { - globalProjectionState.hasAnimatedSinceResize = false; - _this.nodes.forEach(finishAnimation); - } - }); - } - if (layoutId) { - this.root.registerSharedNode(layoutId, this); - } - // Only register the handler if it requires layout animation - if (this.options.animate !== false && visualElement && (layoutId || layout)) { - this.addEventListener("didUpdate", function (_a) { - var _b, _c, _d, _e, _f; - var delta = _a.delta, - hasLayoutChanged = _a.hasLayoutChanged, - hasRelativeTargetChanged = _a.hasRelativeTargetChanged, - newLayout = _a.layout; - if (_this.isTreeAnimationBlocked()) { - _this.target = undefined; - _this.relativeTarget = undefined; - return; - } - // TODO: Check here if an animation exists - var layoutTransition = (_c = (_b = _this.options.transition) !== null && _b !== void 0 ? _b : visualElement.getDefaultTransition()) !== null && _c !== void 0 ? _c : defaultLayoutTransition; - var _g = visualElement.getProps(), - onLayoutAnimationStart = _g.onLayoutAnimationStart, - onLayoutAnimationComplete = _g.onLayoutAnimationComplete; - /** - * The target layout of the element might stay the same, - * but its position relative to its parent has changed. - */ - var targetChanged = !_this.targetLayout || !boxEquals(_this.targetLayout, newLayout) || hasRelativeTargetChanged; - /** - * If the layout hasn't seemed to have changed, it might be that the - * element is visually in the same place in the document but its position - * relative to its parent has indeed changed. So here we check for that. - */ - var hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeTargetChanged; - if (((_d = _this.resumeFrom) === null || _d === void 0 ? void 0 : _d.instance) || hasOnlyRelativeTargetChanged || hasLayoutChanged && (targetChanged || !_this.currentAnimation)) { - if (_this.resumeFrom) { - _this.resumingFrom = _this.resumeFrom; - _this.resumingFrom.resumingFrom = undefined; - } - _this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); - var animationOptions = tslib.__assign(tslib.__assign({}, getValueTransition(layoutTransition, "layout")), { - onPlay: onLayoutAnimationStart, - onComplete: onLayoutAnimationComplete - }); - if (visualElement.shouldReduceMotion) { - animationOptions.delay = 0; - animationOptions.type = false; - } - _this.startAnimation(animationOptions); - } else { - /** - * If the layout hasn't changed and we have an animation that hasn't started yet, - * finish it immediately. Otherwise it will be animating from a location - * that was probably never commited to screen and look like a jumpy box. - */ - if (!hasLayoutChanged && _this.animationProgress === 0) { - _this.finishAnimation(); - } - _this.isLead() && ((_f = (_e = _this.options).onExitComplete) === null || _f === void 0 ? void 0 : _f.call(_e)); - } - _this.targetLayout = newLayout; - }); - } - }; - ProjectionNode.prototype.unmount = function () { - var _a, _b; - this.options.layoutId && this.willUpdate(); - this.root.nodes.remove(this); - (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.remove(this); - (_b = this.parent) === null || _b === void 0 ? void 0 : _b.children.delete(this); - this.instance = undefined; - sync.cancelSync.preRender(this.updateProjection); - }; - // only on the root - ProjectionNode.prototype.blockUpdate = function () { - this.updateManuallyBlocked = true; - }; - ProjectionNode.prototype.unblockUpdate = function () { - this.updateManuallyBlocked = false; - }; - ProjectionNode.prototype.isUpdateBlocked = function () { - return this.updateManuallyBlocked || this.updateBlockedByResize; - }; - ProjectionNode.prototype.isTreeAnimationBlocked = function () { - var _a; - return this.isAnimationBlocked || ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimationBlocked()) || false; - }; - // Note: currently only running on root node - ProjectionNode.prototype.startUpdate = function () { - var _a; - if (this.isUpdateBlocked()) return; - this.isUpdating = true; - (_a = this.nodes) === null || _a === void 0 ? void 0 : _a.forEach(resetRotation); - }; - ProjectionNode.prototype.willUpdate = function (shouldNotifyListeners) { - var _a, _b, _c; - if (shouldNotifyListeners === void 0) { - shouldNotifyListeners = true; - } - if (this.root.isUpdateBlocked()) { - (_b = (_a = this.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a); - return; + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + if (aChar > bChar) { + return 1; + } + ++aIndex; + ++bIndex; + } + } + return aStr.length - bStr.length; +} +const DIGIT_0 = 48; +const DIGIT_9 = 57; +function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/printPathArray.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/printPathArray.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.printPathArray = printPathArray; +/** + * Build a string describing the path. + */ +function printPathArray(path) { + return path.map(key => typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key).join(''); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/promiseForObject.mjs": +/*!******************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/promiseForObject.mjs ***! + \******************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.promiseForObject = promiseForObject; +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +function promiseForObject(object) { + return Promise.all(Object.values(object)).then(resolvedValues => { + const resolvedObject = Object.create(null); + for (const [i, key] of Object.keys(object).entries()) { + resolvedObject[key] = resolvedValues[i]; + } + return resolvedObject; + }); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/promiseReduce.mjs": +/*!***************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/promiseReduce.mjs ***! + \***************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.promiseReduce = promiseReduce; +var _isPromise = __webpack_require__(/*! ./isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + for (const value of values) { + accumulator = (0, _isPromise.isPromise)(accumulator) ? accumulator.then(resolved => callbackFn(resolved, value)) : callbackFn(accumulator, value); + } + return accumulator; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/suggestionList.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/suggestionList.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.suggestionList = suggestionList; +var _naturalCompare = __webpack_require__(/*! ./naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ + +function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : (0, _naturalCompare.naturalCompare)(a, b); + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ + +class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)]; + } + measure(option, threshold) { + if (this._input === option) { + return 0; + } + const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + const aLength = a.length; + const bLength = b.length; + if (aLength - bLength > threshold) { + return undefined; + } + const rows = this._rows; + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = currentRow[0] = i; + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min(upRow[j] + 1, + // delete + currentRow[j - 1] + 1, + // insert + upRow[j - 1] + cost // substitute + ); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); } - !this.root.isUpdating && this.root.startUpdate(); - if (this.isLayoutDirty) return; - this.isLayoutDirty = true; - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - node.shouldResetTransform = true; - /** - * TODO: Check we haven't updated the scroll - * since the last didUpdate - */ - node.updateScroll(); - } - var _d = this.options, - layoutId = _d.layoutId, - layout = _d.layout; - if (layoutId === undefined && !layout) return; - var transformTemplate = (_c = this.options.visualElement) === null || _c === void 0 ? void 0 : _c.getProps().transformTemplate; - this.prevTransformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, ""); - this.updateSnapshot(); - shouldNotifyListeners && this.notifyListeners("willUpdate"); - }; - // Note: Currently only running on root node - ProjectionNode.prototype.didUpdate = function () { - var updateWasBlocked = this.isUpdateBlocked(); - // When doing an instant transition, we skip the layout update, - // but should still clean up the measurements so that the next - // snapshot could be taken correctly. - if (updateWasBlocked) { - this.unblockUpdate(); - this.clearAllSnapshots(); - this.nodes.forEach(clearMeasurements); - return; - } - if (!this.isUpdating) return; - this.isUpdating = false; - /** - * Search for and mount newly-added projection elements. - * - * TODO: Every time a new component is rendered we could search up the tree for - * the closest mounted node and query from there rather than document. - */ - if (this.potentialNodes.size) { - this.potentialNodes.forEach(mountNodeEarly); - this.potentialNodes.clear(); - } - /** - * Write - */ - this.nodes.forEach(resetTransformStyle); - /** - * Read ================== - */ - // Update layout measurements of updated children - this.nodes.forEach(updateLayout); - /** - * Write - */ - // Notify listeners that the layout is updated - this.nodes.forEach(notifyLayoutUpdate); - this.clearAllSnapshots(); - // Flush any scheduled updates - sync.flushSync.update(); - sync.flushSync.preRender(); - sync.flushSync.render(); - }; - ProjectionNode.prototype.clearAllSnapshots = function () { - this.nodes.forEach(clearSnapshot); - this.sharedNodes.forEach(removeLeadSnapshots); - }; - ProjectionNode.prototype.scheduleUpdateProjection = function () { - sync__default["default"].preRender(this.updateProjection, false, true); - }; - ProjectionNode.prototype.scheduleCheckAfterUnmount = function () { - var _this = this; - /** - * If the unmounting node is in a layoutGroup and did trigger a willUpdate, - * we manually call didUpdate to give a chance to the siblings to animate. - * Otherwise, cleanup all snapshots to prevents future nodes from reusing them. - */ - sync__default["default"].postRender(function () { - if (_this.isLayoutDirty) { - _this.root.didUpdate(); - } else { - _this.root.checkUpdateFailed(); - } - }); - }; - /** - * Update measurements - */ - ProjectionNode.prototype.updateSnapshot = function () { - if (this.snapshot || !this.instance) return; - var measured = this.measure(); - var layout = this.removeTransform(this.removeElementScroll(measured)); - roundBox(layout); - this.snapshot = { - measured: measured, - layout: layout, - latestValues: {} - }; - }; - ProjectionNode.prototype.updateLayout = function () { - var _a; - if (!this.instance) return; - // TODO: Incorporate into a forwarded scroll offset - this.updateScroll(); - if (!(this.options.alwaysMeasureLayout && this.isLead()) && !this.isLayoutDirty) { - return; - } - /** - * When a node is mounted, it simply resumes from the prevLead's - * snapshot instead of taking a new one, but the ancestors scroll - * might have updated while the prevLead is unmounted. We need to - * update the scroll again to make sure the layout we measure is - * up to date. - */ - if (this.resumeFrom && !this.resumeFrom.instance) { - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - node.updateScroll(); - } - } - var measured = this.measure(); - roundBox(measured); - var prevLayout = this.layout; - this.layout = { - measured: measured, - actual: this.removeElementScroll(measured) - }; - this.layoutCorrected = createBox(); - this.isLayoutDirty = false; - this.projectionDelta = undefined; - this.notifyListeners("measure", this.layout.actual); - (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.notifyLayoutMeasure(this.layout.actual, prevLayout === null || prevLayout === void 0 ? void 0 : prevLayout.actual); - }; - ProjectionNode.prototype.updateScroll = function () { - if (this.options.layoutScroll && this.instance) { - this.isScrollRoot = checkIsScrollRoot(this.instance); - this.scroll = measureScroll(this.instance); - } - }; - ProjectionNode.prototype.resetTransform = function () { - var _a; - if (!resetTransform) return; - var isResetRequested = this.isLayoutDirty || this.shouldResetTransform; - var hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); - var transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate; - var transformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, ""); - var transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; - if (isResetRequested && (hasProjection || hasTransform(this.latestValues) || transformTemplateHasChanged)) { - resetTransform(this.instance, transformTemplateValue); - this.shouldResetTransform = false; - this.scheduleRender(); - } - }; - ProjectionNode.prototype.measure = function () { - var visualElement = this.options.visualElement; - if (!visualElement) return createBox(); - var box = visualElement.measureViewportBox(); - // Remove viewport scroll to give page-relative coordinates - var scroll = this.root.scroll; - if (scroll) { - translateAxis(box.x, scroll.x); - translateAxis(box.y, scroll.y); - } - return box; - }; - ProjectionNode.prototype.removeElementScroll = function (box) { - var boxWithoutScroll = createBox(); - copyBoxInto(boxWithoutScroll, box); - /** - * Performance TODO: Keep a cumulative scroll offset down the tree - * rather than loop back up the path. - */ - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - var scroll_1 = node.scroll, - options = node.options, - isScrollRoot = node.isScrollRoot; - if (node !== this.root && scroll_1 && options.layoutScroll) { - /** - * If this is a new scroll root, we want to remove all previous scrolls - * from the viewport box. - */ - if (isScrollRoot) { - copyBoxInto(boxWithoutScroll, box); - var rootScroll = this.root.scroll; - /** - * Undo the application of page scroll that was originally added - * to the measured bounding box. - */ - if (rootScroll) { - translateAxis(boxWithoutScroll.x, -rootScroll.x); - translateAxis(boxWithoutScroll.y, -rootScroll.y); - } - } - translateAxis(boxWithoutScroll.x, scroll_1.x); - translateAxis(boxWithoutScroll.y, scroll_1.y); - } - } - return boxWithoutScroll; - }; - ProjectionNode.prototype.applyTransform = function (box, transformOnly) { - if (transformOnly === void 0) { - transformOnly = false; - } - var withTransforms = createBox(); - copyBoxInto(withTransforms, box); - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - if (!transformOnly && node.options.layoutScroll && node.scroll && node !== node.root) { - transformBox(withTransforms, { - x: -node.scroll.x, - y: -node.scroll.y - }); - } - if (!hasTransform(node.latestValues)) continue; - transformBox(withTransforms, node.latestValues); - } - if (hasTransform(this.latestValues)) { - transformBox(withTransforms, this.latestValues); - } - return withTransforms; - }; - ProjectionNode.prototype.removeTransform = function (box) { - var _a; - var boxWithoutTransform = createBox(); - copyBoxInto(boxWithoutTransform, box); - for (var i = 0; i < this.path.length; i++) { - var node = this.path[i]; - if (!node.instance) continue; - if (!hasTransform(node.latestValues)) continue; - hasScale(node.latestValues) && node.updateSnapshot(); - var sourceBox = createBox(); - var nodeBox = node.measure(); - copyBoxInto(sourceBox, nodeBox); - removeBoxTransforms(boxWithoutTransform, node.latestValues, (_a = node.snapshot) === null || _a === void 0 ? void 0 : _a.layout, sourceBox); - } - if (hasTransform(this.latestValues)) { - removeBoxTransforms(boxWithoutTransform, this.latestValues); - } - return boxWithoutTransform; - }; - /** - * - */ - ProjectionNode.prototype.setTargetDelta = function (delta) { - this.targetDelta = delta; - this.root.scheduleUpdateProjection(); - }; - ProjectionNode.prototype.setOptions = function (options) { - var _a; - this.options = tslib.__assign(tslib.__assign(tslib.__assign({}, this.options), options), { - crossfade: (_a = options.crossfade) !== null && _a !== void 0 ? _a : true - }); - }; - ProjectionNode.prototype.clearMeasurements = function () { - this.scroll = undefined; - this.layout = undefined; - this.snapshot = undefined; - this.prevTransformTemplateValue = undefined; - this.targetDelta = undefined; - this.target = undefined; - this.isLayoutDirty = false; - }; - /** - * Frame calculations - */ - ProjectionNode.prototype.resolveTargetDelta = function () { - var _a; - var _b = this.options, - layout = _b.layout, - layoutId = _b.layoutId; - /** - * If we have no layout, we can't perform projection, so early return - */ - if (!this.layout || !(layout || layoutId)) return; - /** - * If we don't have a targetDelta but do have a layout, we can attempt to resolve - * a relativeParent. This will allow a component to perform scale correction - * even if no animation has started. - */ - // TODO If this is unsuccessful this currently happens every frame - if (!this.targetDelta && !this.relativeTarget) { - // TODO: This is a semi-repetition of further down this function, make DRY - this.relativeParent = this.getClosestProjectingParent(); - if (this.relativeParent && this.relativeParent.layout) { - this.relativeTarget = createBox(); - this.relativeTargetOrigin = createBox(); - calcRelativePosition(this.relativeTargetOrigin, this.layout.actual, this.relativeParent.layout.actual); - copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); - } - } - /** - * If we have no relative target or no target delta our target isn't valid - * for this frame. - */ - if (!this.relativeTarget && !this.targetDelta) return; - /** - * Lazy-init target data structure - */ - if (!this.target) { - this.target = createBox(); - this.targetWithTransforms = createBox(); - } - /** - * If we've got a relative box for this component, resolve it into a target relative to the parent. - */ - if (this.relativeTarget && this.relativeTargetOrigin && ((_a = this.relativeParent) === null || _a === void 0 ? void 0 : _a.target)) { - calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target); - /** - * If we've only got a targetDelta, resolve it into a target - */ - } else if (this.targetDelta) { - if (Boolean(this.resumingFrom)) { - // TODO: This is creating a new object every frame - this.target = this.applyTransform(this.layout.actual); - } else { - copyBoxInto(this.target, this.layout.actual); - } - applyBoxDelta(this.target, this.targetDelta); - } else { - /** - * If no target, use own layout as target - */ - copyBoxInto(this.target, this.layout.actual); - } - /** - * If we've been told to attempt to resolve a relative target, do so. - */ - if (this.attemptToResolveRelativeTarget) { - this.attemptToResolveRelativeTarget = false; - this.relativeParent = this.getClosestProjectingParent(); - if (this.relativeParent && Boolean(this.relativeParent.resumingFrom) === Boolean(this.resumingFrom) && !this.relativeParent.options.layoutScroll && this.relativeParent.target) { - this.relativeTarget = createBox(); - this.relativeTargetOrigin = createBox(); - calcRelativePosition(this.relativeTargetOrigin, this.target, this.relativeParent.target); - copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); - } - } - }; - ProjectionNode.prototype.getClosestProjectingParent = function () { - if (!this.parent || hasTransform(this.parent.latestValues)) return undefined; - if ((this.parent.relativeTarget || this.parent.targetDelta) && this.parent.layout) { - return this.parent; - } else { - return this.parent.getClosestProjectingParent(); - } - }; - ProjectionNode.prototype.calcProjection = function () { - var _a; - var _b = this.options, - layout = _b.layout, - layoutId = _b.layoutId; - /** - * If this section of the tree isn't animating we can - * delete our target sources for the following frame. - */ - this.isTreeAnimating = Boolean(((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimating) || this.currentAnimation || this.pendingAnimation); - if (!this.isTreeAnimating) { - this.targetDelta = this.relativeTarget = undefined; - } - if (!this.layout || !(layout || layoutId)) return; - var lead = this.getLead(); - /** - * Reset the corrected box with the latest values from box, as we're then going - * to perform mutative operations on it. - */ - copyBoxInto(this.layoutCorrected, this.layout.actual); - /** - * Apply all the parent deltas to this box to produce the corrected box. This - * is the layout box, as it will appear on screen as a result of the transforms of its parents. - */ - applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, Boolean(this.resumingFrom) || this !== lead); - var target = lead.target; - if (!target) return; - if (!this.projectionDelta) { - this.projectionDelta = createDelta(); - this.projectionDeltaWithTransform = createDelta(); - } - var prevTreeScaleX = this.treeScale.x; - var prevTreeScaleY = this.treeScale.y; - var prevProjectionTransform = this.projectionTransform; - /** - * Update the delta between the corrected box and the target box before user-set transforms were applied. - * This will allow us to calculate the corrected borderRadius and boxShadow to compensate - * for our layout reprojection, but still allow them to be scaled correctly by the user. - * It might be that to simplify this we may want to accept that user-set scale is also corrected - * and we wouldn't have to keep and calc both deltas, OR we could support a user setting - * to allow people to choose whether these styles are corrected based on just the - * layout reprojection or the final bounding box. - */ - calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); - this.projectionTransform = buildProjectionTransform(this.projectionDelta, this.treeScale); - if (this.projectionTransform !== prevProjectionTransform || this.treeScale.x !== prevTreeScaleX || this.treeScale.y !== prevTreeScaleY) { - this.hasProjected = true; - this.scheduleRender(); - this.notifyListeners("projectionUpdate", target); - } - }; - ProjectionNode.prototype.hide = function () { - this.isVisible = false; - // TODO: Schedule render - }; - ProjectionNode.prototype.show = function () { - this.isVisible = true; - // TODO: Schedule render - }; - ProjectionNode.prototype.scheduleRender = function (notifyAll) { - var _a, _b, _c; - if (notifyAll === void 0) { - notifyAll = true; - } - (_b = (_a = this.options).scheduleRender) === null || _b === void 0 ? void 0 : _b.call(_a); - notifyAll && ((_c = this.getStack()) === null || _c === void 0 ? void 0 : _c.scheduleRender()); - if (this.resumingFrom && !this.resumingFrom.instance) { - this.resumingFrom = undefined; - } - }; - ProjectionNode.prototype.setAnimationOrigin = function (delta, hasOnlyRelativeTargetChanged) { - var _this = this; - var _a; - if (hasOnlyRelativeTargetChanged === void 0) { - hasOnlyRelativeTargetChanged = false; - } - var snapshot = this.snapshot; - var snapshotLatestValues = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.latestValues) || {}; - var mixedValues = tslib.__assign({}, this.latestValues); - var targetDelta = createDelta(); - this.relativeTarget = this.relativeTargetOrigin = undefined; - this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; - var relativeLayout = createBox(); - var isSharedLayoutAnimation = snapshot === null || snapshot === void 0 ? void 0 : snapshot.isShared; - var isOnlyMember = (((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.members.length) || 0) <= 1; - var shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && !isOnlyMember && this.options.crossfade === true && !this.path.some(hasOpacityCrossfade)); - this.animationProgress = 0; - this.mixTargetDelta = function (latest) { - var _a; - var progress = latest / 1000; - mixAxisDelta(targetDelta.x, delta.x, progress); - mixAxisDelta(targetDelta.y, delta.y, progress); - _this.setTargetDelta(targetDelta); - if (_this.relativeTarget && _this.relativeTargetOrigin && _this.layout && ((_a = _this.relativeParent) === null || _a === void 0 ? void 0 : _a.layout)) { - calcRelativePosition(relativeLayout, _this.layout.actual, _this.relativeParent.layout.actual); - mixBox(_this.relativeTarget, _this.relativeTargetOrigin, relativeLayout, progress); - } - if (isSharedLayoutAnimation) { - _this.animationValues = mixedValues; - mixValues(mixedValues, snapshotLatestValues, _this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember); - } - _this.root.scheduleUpdateProjection(); - _this.scheduleRender(); - _this.animationProgress = progress; - }; - this.mixTargetDelta(0); - }; - ProjectionNode.prototype.startAnimation = function (options) { - var _this = this; - var _a, _b; - this.notifyListeners("animationStart"); - (_a = this.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); - if (this.resumingFrom) { - (_b = this.resumingFrom.currentAnimation) === null || _b === void 0 ? void 0 : _b.stop(); - } - if (this.pendingAnimation) { - sync.cancelSync.update(this.pendingAnimation); - this.pendingAnimation = undefined; - } - /** - * Start the animation in the next frame to have a frame with progress 0, - * where the target is the same as when the animation started, so we can - * calculate the relative positions correctly for instant transitions. - */ - this.pendingAnimation = sync__default["default"].update(function () { - globalProjectionState.hasAnimatedSinceResize = true; - _this.currentAnimation = animate(0, animationTarget, tslib.__assign(tslib.__assign({}, options), { - onUpdate: function (latest) { - var _a; - _this.mixTargetDelta(latest); - (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, latest); - }, - onComplete: function () { - var _a; - (_a = options.onComplete) === null || _a === void 0 ? void 0 : _a.call(options); - _this.completeAnimation(); - } - })); - if (_this.resumingFrom) { - _this.resumingFrom.currentAnimation = _this.currentAnimation; - } - _this.pendingAnimation = undefined; - }); - }; - ProjectionNode.prototype.completeAnimation = function () { - var _a; - if (this.resumingFrom) { - this.resumingFrom.currentAnimation = undefined; - this.resumingFrom.preserveOpacity = undefined; - } - (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.exitAnimationComplete(); - this.resumingFrom = this.currentAnimation = this.animationValues = undefined; - this.notifyListeners("animationComplete"); - }; - ProjectionNode.prototype.finishAnimation = function () { - var _a; - if (this.currentAnimation) { - (_a = this.mixTargetDelta) === null || _a === void 0 ? void 0 : _a.call(this, animationTarget); - this.currentAnimation.stop(); - } - this.completeAnimation(); - }; - ProjectionNode.prototype.applyTransformsToTarget = function () { - var _a = this.getLead(), - targetWithTransforms = _a.targetWithTransforms, - target = _a.target, - layout = _a.layout, - latestValues = _a.latestValues; - if (!targetWithTransforms || !target || !layout) return; - copyBoxInto(targetWithTransforms, target); - /** - * Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal. - * This is the final box that we will then project into by calculating a transform delta and - * applying it to the corrected box. - */ - transformBox(targetWithTransforms, latestValues); - /** - * Update the delta between the corrected box and the final target box, after - * user-set transforms are applied to it. This will be used by the renderer to - * create a transform style that will reproject the element from its actual layout - * into the desired bounding box. - */ - calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); - }; - ProjectionNode.prototype.registerSharedNode = function (layoutId, node) { - var _a, _b, _c; - if (!this.sharedNodes.has(layoutId)) { - this.sharedNodes.set(layoutId, new NodeStack()); - } - var stack = this.sharedNodes.get(layoutId); - stack.add(node); - node.promote({ - transition: (_a = node.options.initialPromotionConfig) === null || _a === void 0 ? void 0 : _a.transition, - preserveFollowOpacity: (_c = (_b = node.options.initialPromotionConfig) === null || _b === void 0 ? void 0 : _b.shouldPreserveFollowOpacity) === null || _c === void 0 ? void 0 : _c.call(_b, node) - }); - }; - ProjectionNode.prototype.isLead = function () { - var stack = this.getStack(); - return stack ? stack.lead === this : true; - }; - ProjectionNode.prototype.getLead = function () { - var _a; - var layoutId = this.options.layoutId; - return layoutId ? ((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.lead) || this : this; - }; - ProjectionNode.prototype.getPrevLead = function () { - var _a; - var layoutId = this.options.layoutId; - return layoutId ? (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.prevLead : undefined; - }; - ProjectionNode.prototype.getStack = function () { - var layoutId = this.options.layoutId; - if (layoutId) return this.root.sharedNodes.get(layoutId); - }; - ProjectionNode.prototype.promote = function (_a) { - var _b = _a === void 0 ? {} : _a, - needsReset = _b.needsReset, - transition = _b.transition, - preserveFollowOpacity = _b.preserveFollowOpacity; - var stack = this.getStack(); - if (stack) stack.promote(this, preserveFollowOpacity); - if (needsReset) { - this.projectionDelta = undefined; - this.needsReset = true; - } - if (transition) this.setOptions({ - transition: transition - }); - }; - ProjectionNode.prototype.relegate = function () { - var stack = this.getStack(); - if (stack) { - return stack.relegate(this); - } else { - return false; - } - }; - ProjectionNode.prototype.resetRotation = function () { - var visualElement = this.options.visualElement; - if (!visualElement) return; - // If there's no detected rotation values, we can early return without a forced render. - var hasRotate = false; - // Keep a record of all the values we've reset - var resetValues = {}; - // Check the rotate value of all axes and reset to 0 - for (var i = 0; i < transformAxes.length; i++) { - var axis = transformAxes[i]; - var key = "rotate" + axis; - // If this rotation doesn't exist as a motion value, then we don't - // need to reset it - if (!visualElement.getStaticValue(key)) { - continue; - } - hasRotate = true; - // Record the rotation and then temporarily set it to 0 - resetValues[key] = visualElement.getStaticValue(key); - visualElement.setStaticValue(key, 0); - } - // If there's no rotation values, we don't need to do any more. - if (!hasRotate) return; - // Force a render of this element to apply the transform with all rotations - // set to 0. - visualElement === null || visualElement === void 0 ? void 0 : visualElement.syncRender(); - // Put back all the values we reset - for (var key in resetValues) { - visualElement.setStaticValue(key, resetValues[key]); - } - // Schedule a render for the next frame. This ensures we won't visually - // see the element with the reset rotate value applied. - visualElement.scheduleRender(); - }; - ProjectionNode.prototype.getProjectionStyles = function (styleProp) { - var _a, _b, _c, _d, _e, _f; - if (styleProp === void 0) { - styleProp = {}; - } - // TODO: Return lifecycle-persistent object - var styles = {}; - if (!this.instance || this.isSVG) return styles; - if (!this.isVisible) { - return { - visibility: "hidden" - }; - } else { - styles.visibility = ""; - } - var transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate; - if (this.needsReset) { - this.needsReset = false; - styles.opacity = ""; - styles.pointerEvents = resolveMotionValue(styleProp.pointerEvents) || ""; - styles.transform = transformTemplate ? transformTemplate(this.latestValues, "") : "none"; - return styles; - } - var lead = this.getLead(); - if (!this.projectionDelta || !this.layout || !lead.target) { - var emptyStyles = {}; - if (this.options.layoutId) { - emptyStyles.opacity = (_b = this.latestValues.opacity) !== null && _b !== void 0 ? _b : 1; - emptyStyles.pointerEvents = resolveMotionValue(styleProp.pointerEvents) || ""; - } - if (this.hasProjected && !hasTransform(this.latestValues)) { - emptyStyles.transform = transformTemplate ? transformTemplate({}, "") : "none"; - this.hasProjected = false; - } - return emptyStyles; - } - var valuesToRender = lead.animationValues || lead.latestValues; - this.applyTransformsToTarget(); - styles.transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); - if (transformTemplate) { - styles.transform = transformTemplate(valuesToRender, styles.transform); - } - var _g = this.projectionDelta, - x = _g.x, - y = _g.y; - styles.transformOrigin = "".concat(x.origin * 100, "% ").concat(y.origin * 100, "% 0"); - if (lead.animationValues) { - /** - * If the lead component is animating, assign this either the entering/leaving - * opacity - */ - styles.opacity = lead === this ? (_d = (_c = valuesToRender.opacity) !== null && _c !== void 0 ? _c : this.latestValues.opacity) !== null && _d !== void 0 ? _d : 1 : this.preserveOpacity ? this.latestValues.opacity : valuesToRender.opacityExit; - } else { - /** - * Or we're not animating at all, set the lead component to its actual - * opacity and other components to hidden. - */ - styles.opacity = lead === this ? (_e = valuesToRender.opacity) !== null && _e !== void 0 ? _e : "" : (_f = valuesToRender.opacityExit) !== null && _f !== void 0 ? _f : 0; - } - /** - * Apply scale correction - */ - for (var key in scaleCorrectors) { - if (valuesToRender[key] === undefined) continue; - var _h = scaleCorrectors[key], - correct = _h.correct, - applyTo = _h.applyTo; - var corrected = correct(valuesToRender[key], lead); - if (applyTo) { - var num = applyTo.length; - for (var i = 0; i < num; i++) { - styles[applyTo[i]] = corrected; - } - } else { - styles[key] = corrected; - } - } - /** - * Disable pointer events on follow components. This is to ensure - * that if a follow component covers a lead component it doesn't block - * pointer events on the lead. - */ - if (this.options.layoutId) { - styles.pointerEvents = lead === this ? resolveMotionValue(styleProp.pointerEvents) || "" : "none"; - } - return styles; - }; - ProjectionNode.prototype.clearSnapshot = function () { - this.resumeFrom = this.snapshot = undefined; - }; - // Only run on root - ProjectionNode.prototype.resetTree = function () { - this.root.nodes.forEach(function (node) { - var _a; - return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); - }); - this.root.nodes.forEach(clearMeasurements); - this.root.sharedNodes.clear(); - }; - return ProjectionNode; - }(); - } - function updateLayout(node) { - node.updateLayout(); - } - function notifyLayoutUpdate(node) { - var _a, _b, _c, _d; - var snapshot = (_b = (_a = node.resumeFrom) === null || _a === void 0 ? void 0 : _a.snapshot) !== null && _b !== void 0 ? _b : node.snapshot; - if (node.isLead() && node.layout && snapshot && node.hasListeners("didUpdate")) { - var _e = node.layout, - layout_1 = _e.actual, - measuredLayout = _e.measured; - // TODO Maybe we want to also resize the layout snapshot so we don't trigger - // animations for instance if layout="size" and an element has only changed position - if (node.options.animationType === "size") { - eachAxis(function (axis) { - var axisSnapshot = snapshot.isShared ? snapshot.measured[axis] : snapshot.layout[axis]; - var length = calcLength(axisSnapshot); - axisSnapshot.min = layout_1[axis].min; - axisSnapshot.max = axisSnapshot.min + length; - }); - } else if (node.options.animationType === "position") { - eachAxis(function (axis) { - var axisSnapshot = snapshot.isShared ? snapshot.measured[axis] : snapshot.layout[axis]; - var length = calcLength(layout_1[axis]); - axisSnapshot.max = axisSnapshot.min + length; - }); - } - var layoutDelta = createDelta(); - calcBoxDelta(layoutDelta, layout_1, snapshot.layout); - var visualDelta = createDelta(); - if (snapshot.isShared) { - calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measured); - } else { - calcBoxDelta(visualDelta, layout_1, snapshot.layout); - } - var hasLayoutChanged = !isDeltaZero(layoutDelta); - var hasRelativeTargetChanged = false; - if (!node.resumeFrom) { - node.relativeParent = node.getClosestProjectingParent(); - /** - * If the relativeParent is itself resuming from a different element then - * the relative snapshot is not relavent - */ - if (node.relativeParent && !node.relativeParent.resumeFrom) { - var _f = node.relativeParent, - parentSnapshot = _f.snapshot, - parentLayout = _f.layout; - if (parentSnapshot && parentLayout) { - var relativeSnapshot = createBox(); - calcRelativePosition(relativeSnapshot, snapshot.layout, parentSnapshot.layout); - var relativeLayout = createBox(); - calcRelativePosition(relativeLayout, layout_1, parentLayout.actual); - if (!boxEquals(relativeSnapshot, relativeLayout)) { - hasRelativeTargetChanged = true; - } - } + if (currentCell < smallestCell) { + smallestCell = currentCell; } + currentRow[j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + if (smallestCell > threshold) { + return undefined; } - node.notifyListeners("didUpdate", { - layout: layout_1, - snapshot: snapshot, - delta: visualDelta, - layoutDelta: layoutDelta, - hasLayoutChanged: hasLayoutChanged, - hasRelativeTargetChanged: hasRelativeTargetChanged - }); - } else if (node.isLead()) { - (_d = (_c = node.options).onExitComplete) === null || _d === void 0 ? void 0 : _d.call(_c); - } - /** - * Clearing transition - * TODO: Investigate why this transition is being passed in as {type: false } from Framer - * and why we need it at all - */ - node.options.transition = undefined; - } - function clearSnapshot(node) { - node.clearSnapshot(); - } - function clearMeasurements(node) { - node.clearMeasurements(); - } - function resetTransformStyle(node) { - var visualElement = node.options.visualElement; - if (visualElement === null || visualElement === void 0 ? void 0 : visualElement.getProps().onBeforeLayoutMeasure) { - visualElement.notifyBeforeLayoutMeasure(); } - node.resetTransform(); - } - function finishAnimation(node) { - node.finishAnimation(); - node.targetDelta = node.relativeTarget = node.target = undefined; + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; } - function resolveTargetDelta(node) { - node.resolveTargetDelta(); +} +function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); } - function calcProjection(node) { - node.calcProjection(); - } - function resetRotation(node) { - node.resetRotation(); - } - function removeLeadSnapshots(stack) { - stack.removeLeadSnapshot(); + return array; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/toError.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/toError.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.toError = toError; +var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +/** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + */ + +function toError(thrownValue) { + return thrownValue instanceof Error ? thrownValue : new NonErrorThrown(thrownValue); +} +class NonErrorThrown extends Error { + constructor(thrownValue) { + super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); + this.name = 'NonErrorThrown'; + this.thrownValue = thrownValue; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/jsutils/toObjMap.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/jsutils/toObjMap.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.toObjMap = toObjMap; +function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + if (Object.getPrototypeOf(obj) === null) { + return obj; } - function mixAxisDelta(output, delta, p) { - output.translate = popmotion.mix(delta.translate, 0, p); - output.scale = popmotion.mix(delta.scale, 1, p); - output.origin = delta.origin; - output.originPoint = delta.originPoint; + const map = Object.create(null); + for (const [key, value] of Object.entries(obj)) { + map[key] = value; } - function mixAxis(output, from, to, p) { - output.min = popmotion.mix(from.min, to.min, p); - output.max = popmotion.mix(from.max, to.max, p); + return map; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/ast.mjs": +/*!******************************************************!*\ + !*** ../../../node_modules/graphql/language/ast.mjs ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Token = exports.QueryDocumentKeys = exports.OperationTypeNode = exports.Location = void 0; +exports.isNode = isNode; +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +class Location { + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The Token at which this Node begins. + */ + + /** + * The Token at which this Node ends. + */ + + /** + * The Source document the AST represents. + */ + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; } - function mixBox(output, from, to, p) { - mixAxis(output.x, from.x, to.x, p); - mixAxis(output.y, from.y, to.y, p); + get [Symbol.toStringTag]() { + return 'Location'; } - function hasOpacityCrossfade(node) { - return node.animationValues && node.animationValues.opacityExit !== undefined; + toJSON() { + return { + start: this.start, + end: this.end + }; } - var defaultLayoutTransition = { - duration: 0.45, - ease: [0.4, 0, 0.1, 1] - }; - function mountNodeEarly(node, id) { - /** - * Rather than searching the DOM from document we can search the - * path for the deepest mounted ancestor and search from there - */ - var searchNode = node.root; - for (var i = node.path.length - 1; i >= 0; i--) { - if (Boolean(node.path[i].instance)) { - searchNode = node.path[i]; - break; - } - } - var searchElement = searchNode && searchNode !== node.root ? searchNode.instance : document; - var element = searchElement.querySelector("[data-projection-id=\"".concat(id, "\"]")); - if (element) node.mount(element, true); - } - function roundAxis(axis) { - axis.min = Math.round(axis.min); - axis.max = Math.round(axis.max); - } - function roundBox(box) { - roundAxis(box.x); - roundAxis(box.y); - } - var DocumentProjectionNode = createProjectionNode({ - attachResizeListener: function (ref, notify) { - return addDomEvent(ref, "resize", notify); - }, - measureScroll: function () { - return { - x: document.documentElement.scrollLeft || document.body.scrollLeft, - y: document.documentElement.scrollTop || document.body.scrollTop - }; - }, - checkIsScrollRoot: function () { - return true; - } - }); - var rootProjectionNode = { - current: undefined - }; - var HTMLProjectionNode = createProjectionNode({ - measureScroll: function (instance) { - return { - x: instance.scrollLeft, - y: instance.scrollTop - }; - }, - defaultParent: function () { - if (!rootProjectionNode.current) { - var documentNode = new DocumentProjectionNode(0, {}); - documentNode.mount(window); - documentNode.setOptions({ - layoutScroll: true - }); - rootProjectionNode.current = documentNode; - } - return rootProjectionNode.current; - }, - resetTransform: function (instance, value) { - instance.style.transform = value !== null && value !== void 0 ? value : "none"; - }, - checkIsScrollRoot: function (instance) { - return Boolean(window.getComputedStyle(instance).position === "fixed"); - } - }); - var featureBundle = tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, animations), gestureAnimations), drag), layoutFeatures); +} +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +exports.Location = Location; +class Token { /** - * HTML & SVG components, optimised for use with gestures and animation. These can be used as - * drop-in replacements for any HTML & SVG component, all CSS & SVG properties are supported. - * - * @public + * The kind of Token. */ - var motion = /*@__PURE__*/createMotionProxy(function (Component, config) { - return createDomMotionConfig(Component, config, featureBundle, createDomVisualElement, HTMLProjectionNode); - }); + /** - * Create a DOM `motion` component with the provided string. This is primarily intended - * as a full alternative to `motion` for consumers who have to support environments that don't - * support `Proxy`. - * - * ```javascript - * import { createDomMotionComponent } from "framer-motion" - * - * const motion = { - * div: createDomMotionComponent('div') - * } - * ``` - * - * @public + * The character offset at which this Node begins. */ - function createDomMotionComponent(key) { - return createMotionComponent(createDomMotionConfig(key, { - forwardMotionProps: false - }, featureBundle, createDomVisualElement, HTMLProjectionNode)); - } - + /** - * @public + * The character offset at which this Node ends. */ - var m = createMotionProxy(createDomMotionConfig); - function useIsMounted() { - var isMounted = React.useRef(false); - useIsomorphicLayoutEffect(function () { - isMounted.current = true; - return function () { - isMounted.current = false; - }; - }, []); - return isMounted; - } - function useForceUpdate() { - var isMounted = useIsMounted(); - var _a = tslib.__read(React.useState(0), 2), - forcedRenderCount = _a[0], - setForcedRenderCount = _a[1]; - var forceRender = React.useCallback(function () { - isMounted.current && setForcedRenderCount(forcedRenderCount + 1); - }, [forcedRenderCount]); - /** - * Defer this to the end of the next animation frame in case there are multiple - * synchronous calls. - */ - var deferredForceRender = React.useCallback(function () { - return sync__default["default"].postRender(forceRender); - }, [forceRender]); - return [deferredForceRender, forcedRenderCount]; - } - var PresenceChild = function (_a) { - var children = _a.children, - initial = _a.initial, - isPresent = _a.isPresent, - onExitComplete = _a.onExitComplete, - custom = _a.custom, - presenceAffectsLayout = _a.presenceAffectsLayout; - var presenceChildren = useConstant(newChildrenMap); - var id = useId(); - var context = React.useMemo(function () { - return { - id: id, - initial: initial, - isPresent: isPresent, - custom: custom, - onExitComplete: function (childId) { - var e_1, _a; - presenceChildren.set(childId, true); - try { - for (var _b = tslib.__values(presenceChildren.values()), _c = _b.next(); !_c.done; _c = _b.next()) { - var isComplete = _c.value; - if (!isComplete) return; // can stop searching when any is incomplete - } - } catch (e_1_1) { - e_1 = { - error: e_1_1 - }; - } finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } finally { - if (e_1) throw e_1.error; - } - } - onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete(); - }, - register: function (childId) { - presenceChildren.set(childId, false); - return function () { - return presenceChildren.delete(childId); - }; - } - }; - }, - /** - * If the presence of a child affects the layout of the components around it, - * we want to make a new context value to ensure they get re-rendered - * so they can detect that layout change. - */ - presenceAffectsLayout ? undefined : [isPresent]); - React.useMemo(function () { - presenceChildren.forEach(function (_, key) { - return presenceChildren.set(key, false); - }); - }, [isPresent]); - /** - * If there's no `motion` components to fire exit animations, we want to remove this - * component immediately. - */ - React__namespace.useEffect(function () { - !isPresent && !presenceChildren.size && (onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete()); - }, [isPresent]); - return React__namespace.createElement(PresenceContext.Provider, { - value: context - }, children); - }; - function newChildrenMap() { - return new Map(); - } - var getChildKey = function (child) { - return child.key || ""; - }; - function updateChildLookup(children, allChildren) { - children.forEach(function (child) { - var key = getChildKey(child); - allChildren.set(key, child); - }); - } - function onlyElements(children) { - var filtered = []; - // We use forEach here instead of map as map mutates the component key by preprending `.$` - React.Children.forEach(children, function (child) { - if (React.isValidElement(child)) filtered.push(child); - }); - return filtered; - } + /** - * `AnimatePresence` enables the animation of components that have been removed from the tree. - * - * When adding/removing more than a single child, every child **must** be given a unique `key` prop. - * - * Any `motion` components that have an `exit` property defined will animate out when removed from - * the tree. - * - * ```jsx - * import { motion, AnimatePresence } from 'framer-motion' - * - * export const Items = ({ items }) => ( - * - * {items.map(item => ( - * - * ))} - * - * ) - * ``` - * - * You can sequence exit animations throughout a tree using variants. - * - * If a child contains multiple `motion` components with `exit` props, it will only unmount the child - * once all `motion` components have finished animating out. Likewise, any components using - * `usePresence` all need to call `safeToRemove`. - * - * @public + * The 1-indexed line number on which this Token appears. */ - var AnimatePresence = function (_a) { - var children = _a.children, - custom = _a.custom, - _b = _a.initial, - initial = _b === void 0 ? true : _b, - onExitComplete = _a.onExitComplete, - exitBeforeEnter = _a.exitBeforeEnter, - _c = _a.presenceAffectsLayout, - presenceAffectsLayout = _c === void 0 ? true : _c; - // We want to force a re-render once all exiting animations have finished. We - // either use a local forceRender function, or one from a parent context if it exists. - var _d = tslib.__read(useForceUpdate(), 1), - forceRender = _d[0]; - var forceRenderLayoutGroup = React.useContext(LayoutGroupContext).forceRender; - if (forceRenderLayoutGroup) forceRender = forceRenderLayoutGroup; - var isMounted = useIsMounted(); - // Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key - var filteredChildren = onlyElements(children); - var childrenToRender = filteredChildren; - var exiting = new Set(); - // Keep a living record of the children we're actually rendering so we - // can diff to figure out which are entering and exiting - var presentChildren = React.useRef(childrenToRender); - // A lookup table to quickly reference components by key - var allChildren = React.useRef(new Map()).current; - // If this is the initial component render, just deal with logic surrounding whether - // we play onMount animations or not. - var isInitialRender = React.useRef(true); - useIsomorphicLayoutEffect(function () { - isInitialRender.current = false; - updateChildLookup(filteredChildren, allChildren); - presentChildren.current = childrenToRender; - }); - useUnmountEffect(function () { - isInitialRender.current = true; - allChildren.clear(); - exiting.clear(); - }); - if (isInitialRender.current) { - return React__namespace.createElement(React__namespace.Fragment, null, childrenToRender.map(function (child) { - return React__namespace.createElement(PresenceChild, { - key: getChildKey(child), - isPresent: true, - initial: initial ? undefined : false, - presenceAffectsLayout: presenceAffectsLayout - }, child); - })); - } - // If this is a subsequent render, deal with entering and exiting children - childrenToRender = tslib.__spreadArray([], tslib.__read(childrenToRender), false); - // Diff the keys of the currently-present and target children to update our - // exiting list. - var presentKeys = presentChildren.current.map(getChildKey); - var targetKeys = filteredChildren.map(getChildKey); - // Diff the present children with our target children and mark those that are exiting - var numPresent = presentKeys.length; - for (var i = 0; i < numPresent; i++) { - var key = presentKeys[i]; - if (targetKeys.indexOf(key) === -1) { - exiting.add(key); - } - } - // If we currently have exiting children, and we're deferring rendering incoming children - // until after all current children have exiting, empty the childrenToRender array - if (exitBeforeEnter && exiting.size) { - childrenToRender = []; - } - // Loop through all currently exiting components and clone them to overwrite `animate` - // with any `exit` prop they might have defined. - exiting.forEach(function (key) { - // If this component is actually entering again, early return - if (targetKeys.indexOf(key) !== -1) return; - var child = allChildren.get(key); - if (!child) return; - var insertionIndex = presentKeys.indexOf(key); - var onExit = function () { - allChildren.delete(key); - exiting.delete(key); - // Remove this child from the present children - var removeIndex = presentChildren.current.findIndex(function (presentChild) { - return presentChild.key === key; - }); - presentChildren.current.splice(removeIndex, 1); - // Defer re-rendering until all exiting children have indeed left - if (!exiting.size) { - presentChildren.current = filteredChildren; - if (isMounted.current === false) return; - forceRender(); - onExitComplete && onExitComplete(); - } - }; - childrenToRender.splice(insertionIndex, 0, React__namespace.createElement(PresenceChild, { - key: getChildKey(child), - isPresent: false, - onExitComplete: onExit, - custom: custom, - presenceAffectsLayout: presenceAffectsLayout - }, child)); - }); - // Add `MotionContext` even to children that don't need it to ensure we're rendering - // the same tree between renders - childrenToRender = childrenToRender.map(function (child) { - var key = child.key; - return exiting.has(key) ? child : React__namespace.createElement(PresenceChild, { - key: getChildKey(child), - isPresent: true, - presenceAffectsLayout: presenceAffectsLayout - }, child); - }); - if (env !== "production" && exitBeforeEnter && childrenToRender.length > 1) { - console.warn("You're attempting to animate multiple children within AnimatePresence, but its exitBeforeEnter prop is set to true. This will lead to odd visual behaviour."); - } - return React__namespace.createElement(React__namespace.Fragment, null, exiting.size ? childrenToRender : childrenToRender.map(function (child) { - return React.cloneElement(child); - })); - }; - + /** - * @deprecated + * The 1-indexed column number at which this Token begins. */ - var DeprecatedLayoutGroupContext = React.createContext(null); - var notify = function (node) { - return !node.isLayoutDirty && node.willUpdate(false); - }; - function nodeGroup() { - var nodes = new Set(); - var subscriptions = new WeakMap(); - var dirtyAll = function () { - return nodes.forEach(notify); - }; - return { - add: function (node) { - nodes.add(node); - subscriptions.set(node, node.addEventListener("willUpdate", dirtyAll)); - }, - remove: function (node) { - var _a; - nodes.delete(node); - (_a = subscriptions.get(node)) === null || _a === void 0 ? void 0 : _a(); - subscriptions.delete(node); - dirtyAll(); - }, - dirty: dirtyAll - }; - } - var shouldInheritGroup = function (inherit) { - return inherit === true; - }; - var shouldInheritId = function (inherit) { - return shouldInheritGroup(inherit === true) || inherit === "id"; - }; - var LayoutGroup = function (_a) { - var _b, _c; - var children = _a.children, - id = _a.id, - inheritId = _a.inheritId, - _d = _a.inherit, - inherit = _d === void 0 ? true : _d; - // Maintain backwards-compatibility with inheritId until 7.0 - if (inheritId !== undefined) inherit = inheritId; - var layoutGroupContext = React.useContext(LayoutGroupContext); - var deprecatedLayoutGroupContext = React.useContext(DeprecatedLayoutGroupContext); - var _e = tslib.__read(useForceUpdate(), 2), - forceRender = _e[0], - key = _e[1]; - var context = React.useRef(null); - var upstreamId = (_b = layoutGroupContext.id) !== null && _b !== void 0 ? _b : deprecatedLayoutGroupContext; - if (context.current === null) { - if (shouldInheritId(inherit) && upstreamId) { - id = id ? upstreamId + "-" + id : upstreamId; - } - context.current = { - id: id, - group: shouldInheritGroup(inherit) ? (_c = layoutGroupContext === null || layoutGroupContext === void 0 ? void 0 : layoutGroupContext.group) !== null && _c !== void 0 ? _c : nodeGroup() : nodeGroup() - }; - } - var memoizedContext = React.useMemo(function () { - return tslib.__assign(tslib.__assign({}, context.current), { - forceRender: forceRender - }); - }, [key]); - return React__namespace.createElement(LayoutGroupContext.Provider, { - value: memoizedContext - }, children); - }; - var id = 0; - var AnimateSharedLayout = function (_a) { - var children = _a.children; - React__namespace.useEffect(function () { - heyListen.warning(false, "AnimateSharedLayout is deprecated: https://www.framer.com/docs/guide-upgrade/##shared-layout-animations"); - }, []); - return React__namespace.createElement(LayoutGroup, { - id: useConstant(function () { - return "asl-".concat(id++); - }) - }, children); - }; - + /** - * `MotionConfig` is used to set configuration options for all children `motion` components. - * - * ```jsx - * import { motion, MotionConfig } from "framer-motion" - * - * export function App() { - * return ( - * - * - * - * ) - * } - * ``` + * For non-punctuation tokens, represents the interpreted value of the token. * - * @public + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. */ - function MotionConfig(_a) { - var children = _a.children, - isValidProp = _a.isValidProp, - config = tslib.__rest(_a, ["children", "isValidProp"]); - isValidProp && loadExternalIsValidProp(isValidProp); - /** - * Inherit props from any parent MotionConfig components - */ - config = tslib.__assign(tslib.__assign({}, React.useContext(MotionConfigContext)), config); - /** - * Don't allow isStatic to change between renders as it affects how many hooks - * motion components fire. - */ - config.isStatic = useConstant(function () { - return config.isStatic; - }); - /** - * Creating a new config context object will re-render every `motion` component - * every time it renders. So we only want to create a new one sparingly. - */ - var context = React.useMemo(function () { - return config; - }, [JSON.stringify(config.transition), config.transformPagePoint, config.reducedMotion]); - return React__namespace.createElement(MotionConfigContext.Provider, { - value: context - }, children); - } - + /** - * Used in conjunction with the `m` component to reduce bundle size. - * - * `m` is a version of the `motion` component that only loads functionality - * critical for the initial render. - * - * `LazyMotion` can then be used to either synchronously or asynchronously - * load animation and gesture support. - * - * ```jsx - * // Synchronous loading - * import { LazyMotion, m, domAnimations } from "framer-motion" - * - * function App() { - * return ( - * - * - * - * ) - * } - * - * // Asynchronous loading - * import { LazyMotion, m } from "framer-motion" - * - * function App() { - * return ( - * import('./path/to/domAnimations')}> - * - * - * ) - * } - * ``` - * - * @public + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. */ - function LazyMotion(_a) { - var children = _a.children, - features = _a.features, - _b = _a.strict, - strict = _b === void 0 ? false : _b; - var _c = tslib.__read(React.useState(!isLazyBundle(features)), 2), - setIsLoaded = _c[1]; - var loadedRenderer = React.useRef(undefined); - /** - * If this is a synchronous load, load features immediately - */ - if (!isLazyBundle(features)) { - var renderer = features.renderer, - loadedFeatures = tslib.__rest(features, ["renderer"]); - loadedRenderer.current = renderer; - loadFeatures(loadedFeatures); - } - React.useEffect(function () { - if (isLazyBundle(features)) { - features().then(function (_a) { - var renderer = _a.renderer, - loadedFeatures = tslib.__rest(_a, ["renderer"]); - loadFeatures(loadedFeatures); - loadedRenderer.current = renderer; - setIsLoaded(true); - }); - } - }, []); - return React__namespace.createElement(LazyContext.Provider, { - value: { - renderer: loadedRenderer.current, - strict: strict - } - }, children); + constructor(kind, start, end, line, column, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + + this.value = value; + this.prev = null; + this.next = null; } - function isLazyBundle(features) { - return typeof features === "function"; + get [Symbol.toStringTag]() { + return 'Token'; } - var ReorderContext = React.createContext(null); - function checkReorder(order, value, offset, velocity) { - if (!velocity) return order; - var index = order.findIndex(function (item) { - return item.value === value; - }); - if (index === -1) return order; - var nextOffset = velocity > 0 ? 1 : -1; - var nextItem = order[index + nextOffset]; - if (!nextItem) return order; - var item = order[index]; - var nextLayout = nextItem.layout; - var nextItemCenter = popmotion.mix(nextLayout.min, nextLayout.max, 0.5); - if (nextOffset === 1 && item.layout.max + offset > nextItemCenter || nextOffset === -1 && item.layout.min + offset < nextItemCenter) { - return moveItem(order, index, index + nextOffset); - } - return order; - } - function ReorderGroup(_a, externalRef) { - var children = _a.children, - _b = _a.as, - as = _b === void 0 ? "ul" : _b, - _c = _a.axis, - axis = _c === void 0 ? "y" : _c, - onReorder = _a.onReorder, - values = _a.values, - props = tslib.__rest(_a, ["children", "as", "axis", "onReorder", "values"]); - var Component = useConstant(function () { - return motion(as); - }); - var order = []; - var isReordering = React.useRef(false); - heyListen.invariant(Boolean(values), "Reorder.Group must be provided a values prop"); - var context = { - axis: axis, - registerItem: function (value, layout) { - /** - * Ensure entries can't add themselves more than once - */ - if (layout && order.findIndex(function (entry) { - return value === entry.value; - }) === -1) { - order.push({ - value: value, - layout: layout[axis] - }); - order.sort(compareMin); - } - }, - updateOrder: function (id, offset, velocity) { - if (isReordering.current) return; - var newOrder = checkReorder(order, id, offset, velocity); - if (order !== newOrder) { - isReordering.current = true; - onReorder(newOrder.map(getValue).filter(function (value) { - return values.indexOf(value) !== -1; - })); - } - } + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column }; - React.useEffect(function () { - isReordering.current = false; - }); - return React__namespace.createElement(Component, tslib.__assign({}, props, { - ref: externalRef - }), React__namespace.createElement(ReorderContext.Provider, { - value: context - }, children)); - } - var Group = React.forwardRef(ReorderGroup); - function getValue(item) { - return item.value; } - function compareMin(a, b) { - return a.layout.min - b.layout.min; - } - - /** - * Creates a `MotionValue` to track the state and velocity of a value. - * - * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop. - * - * ```jsx - * export const MyComponent = () => { - * const scale = useMotionValue(1) - * - * return - * } - * ``` - * - * @param initial - The initial state. - * - * @public - */ - function useMotionValue(initial) { - var value = useConstant(function () { - return motionValue(initial); - }); - /** - * If this motion value is being used in static mode, like on - * the Framer canvas, force components to rerender when the motion - * value is updated. - */ - var isStatic = React.useContext(MotionConfigContext).isStatic; - if (isStatic) { - var _a = tslib.__read(React.useState(initial), 2), - setLatest_1 = _a[1]; - React.useEffect(function () { - return value.onChange(setLatest_1); - }, []); +} +/** + * The list of all possible AST node types. + */ + +/** + * @internal + */ +exports.Token = Token; +const QueryDocumentKeys = exports.QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', + // Note: fragment variable definitions are deprecated and will removed in v17.0.0 + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +const kindValues = new Set(Object.keys(QueryDocumentKeys)); +/** + * @internal + */ + +function isNode(maybeNode) { + const maybeKind = maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; + return typeof maybeKind === 'string' && kindValues.has(maybeKind); +} +/** Name */ + +var OperationTypeNode; +(function (OperationTypeNode) { + OperationTypeNode['QUERY'] = 'query'; + OperationTypeNode['MUTATION'] = 'mutation'; + OperationTypeNode['SUBSCRIPTION'] = 'subscription'; +})(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); + +/***/ }), + +/***/ "../../../node_modules/graphql/language/blockString.mjs": +/*!**************************************************************!*\ + !*** ../../../node_modules/graphql/language/blockString.mjs ***! + \**************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.dedentBlockStringLines = dedentBlockStringLines; +exports.isPrintableAsBlockString = isPrintableAsBlockString; +exports.printBlockString = printBlockString; +var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ + +function dedentBlockStringLines(lines) { + var _firstNonEmptyLine2; + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + for (let i = 0; i < lines.length; ++i) { + var _firstNonEmptyLine; + const line = lines[i]; + const indent = leadingWhitespace(line); + if (indent === line.length) { + continue; // skip empty lines + } + firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i; + lastNonEmptyLine = i; + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; + } + } + return lines // Remove common indentation from all lines but first. + .map((line, i) => i === 0 ? line : line.slice(commonIndent)) // Remove leading and trailing blank lines. + .slice((_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0, lastNonEmptyLine + 1); +} +function leadingWhitespace(str) { + let i = 0; + while (i < str.length && (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i))) { + ++i; + } + return i; +} +/** + * @internal + */ + +function isPrintableAsBlockString(value) { + if (value === '') { + return true; // empty string is printable + } + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + for (let i = 0; i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0x0000: + case 0x0001: + case 0x0002: + case 0x0003: + case 0x0004: + case 0x0005: + case 0x0006: + case 0x0007: + case 0x0008: + case 0x000b: + case 0x000c: + case 0x000e: + case 0x000f: + return false; + // Has non-printable characters + + case 0x000d: + // \r + return false; + // Has \r or \r\n which will be replaced as \n + + case 10: + // \n + if (isEmptyLine && !seenNonEmptyLine) { + return false; // Has leading new line + } + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + case 9: // \t + + case 32: + // + hasIndent || (hasIndent = isEmptyLine); + break; + default: + hasCommonIndent && (hasCommonIndent = hasIndent); + isEmptyLine = false; } - return value; - } - var isCustomValueType = function (v) { - return typeof v === "object" && v.mix; - }; - var getMixer = function (v) { - return isCustomValueType(v) ? v.mix : undefined; - }; - function transform() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var useImmediate = !Array.isArray(args[0]); - var argOffset = useImmediate ? 0 : -1; - var inputValue = args[0 + argOffset]; - var inputRange = args[1 + argOffset]; - var outputRange = args[2 + argOffset]; - var options = args[3 + argOffset]; - var interpolator = popmotion.interpolate(inputRange, outputRange, tslib.__assign({ - mixer: getMixer(outputRange[0]) - }, options)); - return useImmediate ? interpolator(inputValue) : interpolator; - } - function useOnChange(value, callback) { - useIsomorphicLayoutEffect(function () { - if (isMotionValue(value)) return value.onChange(callback); - }, [callback]); } - function useMultiOnChange(values, handler) { - useIsomorphicLayoutEffect(function () { - var subscriptions = values.map(function (value) { - return value.onChange(handler); - }); - return function () { - return subscriptions.forEach(function (unsubscribe) { - return unsubscribe(); - }); - }; - }); + if (isEmptyLine) { + return false; // Has trailing empty lines } - function useCombineMotionValues(values, combineValues) { - /** - * Initialise the returned motion value. This remains the same between renders. - */ - var value = useMotionValue(combineValues()); - /** - * Create a function that will update the template motion value with the latest values. - * This is pre-bound so whenever a motion value updates it can schedule its - * execution in Framesync. If it's already been scheduled it won't be fired twice - * in a single frame. - */ - var updateValue = function () { - return value.set(combineValues()); - }; - /** - * Synchronously update the motion value with the latest values during the render. - * This ensures that within a React render, the styles applied to the DOM are up-to-date. - */ - updateValue(); - /** - * Subscribe to all motion values found within the template. Whenever any of them change, - * schedule an update. - */ - useMultiOnChange(values, function () { - return sync__default["default"].update(updateValue, false, true); - }); - return value; + if (hasCommonIndent && seenNonEmptyLine) { + return false; // Has internal indent } - function useTransform(input, inputRangeOrTransformer, outputRange, options) { - var transformer = typeof inputRangeOrTransformer === "function" ? inputRangeOrTransformer : transform(inputRangeOrTransformer, outputRange, options); - return Array.isArray(input) ? useListTransform(input, transformer) : useListTransform([input], function (_a) { - var _b = tslib.__read(_a, 1), - latest = _b[0]; - return transformer(latest); - }); + return true; +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + +function printBlockString(value, options) { + const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + + const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every(line => line.length === 0 || (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line + + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line + + const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith('\\'); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && ( + // add leading and trailing new lines only if it improves readability + !isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes); + let result = ''; // Format a multi-line block quote to account for leading space. + + const skipLeadingNewLine = isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); + if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) { + result += '\n'; } - function useListTransform(values, transformer) { - var latest = useConstant(function () { - return []; - }); - return useCombineMotionValues(values, function () { - latest.length = 0; - var numValues = values.length; - for (var i = 0; i < numValues; i++) { - latest[i] = values[i].get(); - } - return transformer(latest); - }); + result += escapedValue; + if (printAsMultipleLines || forceTrailingNewline) { + result += '\n'; } - function useDefaultMotionValue(value, defaultValue) { - if (defaultValue === void 0) { - defaultValue = 0; - } - return isMotionValue(value) ? value : useMotionValue(defaultValue); - } - function ReorderItem(_a, externalRef) { - var children = _a.children, - style = _a.style, - value = _a.value, - _b = _a.as, - as = _b === void 0 ? "li" : _b, - onDrag = _a.onDrag, - _c = _a.layout, - layout = _c === void 0 ? true : _c, - props = tslib.__rest(_a, ["children", "style", "value", "as", "onDrag", "layout"]); - var Component = useConstant(function () { - return motion(as); - }); - var context = React.useContext(ReorderContext); - var point = { - x: useDefaultMotionValue(style === null || style === void 0 ? void 0 : style.x), - y: useDefaultMotionValue(style === null || style === void 0 ? void 0 : style.y) - }; - var zIndex = useTransform([point.x, point.y], function (_a) { - var _b = tslib.__read(_a, 2), - latestX = _b[0], - latestY = _b[1]; - return latestX || latestY ? 1 : "unset"; - }); - var measuredLayout = React.useRef(null); - heyListen.invariant(Boolean(context), "Reorder.Item must be a child of Reorder.Group"); - var _d = context, - axis = _d.axis, - registerItem = _d.registerItem, - updateOrder = _d.updateOrder; - React.useEffect(function () { - registerItem(value, measuredLayout.current); - }, [context]); - return React__namespace.createElement(Component, tslib.__assign({ - drag: axis - }, props, { - dragSnapToOrigin: true, - style: tslib.__assign(tslib.__assign({}, style), { - x: point.x, - y: point.y, - zIndex: zIndex - }), - layout: layout, - onDrag: function (event, gesturePoint) { - var velocity = gesturePoint.velocity; - velocity[axis] && updateOrder(value, point[axis].get(), velocity[axis]); - onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, gesturePoint); - }, - onLayoutMeasure: function (measured) { - measuredLayout.current = measured; - }, - ref: externalRef - }), children); - } - var Item = React.forwardRef(ReorderItem); - var Reorder = { - Group: Group, - Item: Item - }; - + return '"""' + result + '"""'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/characterClasses.mjs": +/*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/language/characterClasses.mjs ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isDigit = isDigit; +exports.isLetter = isLetter; +exports.isNameContinue = isNameContinue; +exports.isNameStart = isNameStart; +exports.isWhiteSpace = isWhiteSpace; +/** + * ``` + * WhiteSpace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ +function isWhiteSpace(code) { + return code === 0x0009 || code === 0x0020; +} +/** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ + +function isDigit(code) { + return code >= 0x0030 && code <= 0x0039; +} +/** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ + +function isLetter(code) { + return code >= 0x0061 && code <= 0x007a || + // A-Z + code >= 0x0041 && code <= 0x005a // a-z + ; +} +/** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ + +function isNameStart(code) { + return isLetter(code) || code === 0x005f; +} +/** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ + +function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 0x005f; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/directiveLocation.mjs": +/*!********************************************************************!*\ + !*** ../../../node_modules/graphql/language/directiveLocation.mjs ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DirectiveLocation = void 0; +/** + * The set of allowed directive location values. + */ +var DirectiveLocation; +(function (DirectiveLocation) { + DirectiveLocation['QUERY'] = 'QUERY'; + DirectiveLocation['MUTATION'] = 'MUTATION'; + DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; + DirectiveLocation['FIELD'] = 'FIELD'; + DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; + DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; + DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; + DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; + DirectiveLocation['SCHEMA'] = 'SCHEMA'; + DirectiveLocation['SCALAR'] = 'SCALAR'; + DirectiveLocation['OBJECT'] = 'OBJECT'; + DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; + DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; + DirectiveLocation['INTERFACE'] = 'INTERFACE'; + DirectiveLocation['UNION'] = 'UNION'; + DirectiveLocation['ENUM'] = 'ENUM'; + DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; + DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; + DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; +})(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); + +/** + * The enum type representing the directive location values. + * + * @deprecated Please use `DirectiveLocation`. Will be remove in v17. + */ + +/***/ }), + +/***/ "../../../node_modules/graphql/language/index.mjs": +/*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/index.mjs ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "BREAK", ({ + enumerable: true, + get: function () { + return _visitor.BREAK; + } +})); +Object.defineProperty(exports, "DirectiveLocation", ({ + enumerable: true, + get: function () { + return _directiveLocation.DirectiveLocation; + } +})); +Object.defineProperty(exports, "Kind", ({ + enumerable: true, + get: function () { + return _kinds.Kind; + } +})); +Object.defineProperty(exports, "Lexer", ({ + enumerable: true, + get: function () { + return _lexer.Lexer; + } +})); +Object.defineProperty(exports, "Location", ({ + enumerable: true, + get: function () { + return _ast.Location; + } +})); +Object.defineProperty(exports, "OperationTypeNode", ({ + enumerable: true, + get: function () { + return _ast.OperationTypeNode; + } +})); +Object.defineProperty(exports, "Source", ({ + enumerable: true, + get: function () { + return _source.Source; + } +})); +Object.defineProperty(exports, "Token", ({ + enumerable: true, + get: function () { + return _ast.Token; + } +})); +Object.defineProperty(exports, "TokenKind", ({ + enumerable: true, + get: function () { + return _tokenKind.TokenKind; + } +})); +Object.defineProperty(exports, "getEnterLeaveForKind", ({ + enumerable: true, + get: function () { + return _visitor.getEnterLeaveForKind; + } +})); +Object.defineProperty(exports, "getLocation", ({ + enumerable: true, + get: function () { + return _location.getLocation; + } +})); +Object.defineProperty(exports, "getVisitFn", ({ + enumerable: true, + get: function () { + return _visitor.getVisitFn; + } +})); +Object.defineProperty(exports, "isConstValueNode", ({ + enumerable: true, + get: function () { + return _predicates.isConstValueNode; + } +})); +Object.defineProperty(exports, "isDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isDefinitionNode; + } +})); +Object.defineProperty(exports, "isExecutableDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isExecutableDefinitionNode; + } +})); +Object.defineProperty(exports, "isSelectionNode", ({ + enumerable: true, + get: function () { + return _predicates.isSelectionNode; + } +})); +Object.defineProperty(exports, "isTypeDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeDefinitionNode; + } +})); +Object.defineProperty(exports, "isTypeExtensionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeExtensionNode; + } +})); +Object.defineProperty(exports, "isTypeNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeNode; + } +})); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeSystemDefinitionNode; + } +})); +Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeSystemExtensionNode; + } +})); +Object.defineProperty(exports, "isValueNode", ({ + enumerable: true, + get: function () { + return _predicates.isValueNode; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parser.parse; + } +})); +Object.defineProperty(exports, "parseConstValue", ({ + enumerable: true, + get: function () { + return _parser.parseConstValue; + } +})); +Object.defineProperty(exports, "parseType", ({ + enumerable: true, + get: function () { + return _parser.parseType; + } +})); +Object.defineProperty(exports, "parseValue", ({ + enumerable: true, + get: function () { + return _parser.parseValue; + } +})); +Object.defineProperty(exports, "print", ({ + enumerable: true, + get: function () { + return _printer.print; + } +})); +Object.defineProperty(exports, "printLocation", ({ + enumerable: true, + get: function () { + return _printLocation.printLocation; + } +})); +Object.defineProperty(exports, "printSourceLocation", ({ + enumerable: true, + get: function () { + return _printLocation.printSourceLocation; + } +})); +Object.defineProperty(exports, "visit", ({ + enumerable: true, + get: function () { + return _visitor.visit; + } +})); +Object.defineProperty(exports, "visitInParallel", ({ + enumerable: true, + get: function () { + return _visitor.visitInParallel; + } +})); +var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); +var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); +var _printLocation = __webpack_require__(/*! ./printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); +var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); +var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); +var _parser = __webpack_require__(/*! ./parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); +var _printer = __webpack_require__(/*! ./printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); +var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _predicates = __webpack_require__(/*! ./predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); +var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/language/kinds.mjs": +/*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/kinds.mjs ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Kind = void 0; +/** + * The set of allowed kind values for AST nodes. + */ +var Kind; +(function (Kind) { + Kind['NAME'] = 'Name'; + Kind['DOCUMENT'] = 'Document'; + Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; + Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; + Kind['SELECTION_SET'] = 'SelectionSet'; + Kind['FIELD'] = 'Field'; + Kind['ARGUMENT'] = 'Argument'; + Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; + Kind['INLINE_FRAGMENT'] = 'InlineFragment'; + Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; + Kind['VARIABLE'] = 'Variable'; + Kind['INT'] = 'IntValue'; + Kind['FLOAT'] = 'FloatValue'; + Kind['STRING'] = 'StringValue'; + Kind['BOOLEAN'] = 'BooleanValue'; + Kind['NULL'] = 'NullValue'; + Kind['ENUM'] = 'EnumValue'; + Kind['LIST'] = 'ListValue'; + Kind['OBJECT'] = 'ObjectValue'; + Kind['OBJECT_FIELD'] = 'ObjectField'; + Kind['DIRECTIVE'] = 'Directive'; + Kind['NAMED_TYPE'] = 'NamedType'; + Kind['LIST_TYPE'] = 'ListType'; + Kind['NON_NULL_TYPE'] = 'NonNullType'; + Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; + Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; + Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; + Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; + Kind['FIELD_DEFINITION'] = 'FieldDefinition'; + Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; + Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; + Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; + Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; + Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; + Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; + Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; + Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; + Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; + Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; + Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; + Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; + Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; + Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; +})(Kind || (exports.Kind = Kind = {})); + +/** + * The enum type representing the possible kind values of AST nodes. + * + * @deprecated Please use `Kind`. Will be remove in v17. + */ + +/***/ }), + +/***/ "../../../node_modules/graphql/language/lexer.mjs": +/*!********************************************************!*\ + !*** ../../../node_modules/graphql/language/lexer.mjs ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Lexer = void 0; +exports.isPunctuatorTokenKind = isPunctuatorTokenKind; +var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); +var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); +var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); +var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ + +class Lexer { /** - * @public + * The previously focused non-ignored token. */ - var domAnimation = tslib.__assign(tslib.__assign({ - renderer: createDomVisualElement - }, animations), gestureAnimations); - + /** - * @public + * The currently focused non-ignored token. */ - var domMax = tslib.__assign(tslib.__assign(tslib.__assign(tslib.__assign({}, domAnimation), drag), layoutFeatures), { - projectionNodeConstructor: HTMLProjectionNode - }); - + /** - * Combine multiple motion values into a new one using a string template literal. - * - * ```jsx - * import { - * motion, - * useSpring, - * useMotionValue, - * useMotionTemplate - * } from "framer-motion" - * - * function Component() { - * const shadowX = useSpring(0) - * const shadowY = useMotionValue(0) - * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))` - * - * return - * } - * ``` - * - * @public + * The (1-indexed) line containing the current token. */ - function useMotionTemplate(fragments) { - var values = []; - for (var _i = 1; _i < arguments.length; _i++) { - values[_i - 1] = arguments[_i]; - } - /** - * Create a function that will build a string from the latest motion values. - */ - var numFragments = fragments.length; - function buildValue() { - var output = ""; - for (var i = 0; i < numFragments; i++) { - output += fragments[i]; - var value = values[i]; - if (value) output += values[i].get(); - } - return output; - } - return useCombineMotionValues(values, buildValue); + + /** + * The character offset at which the current line begins. + */ + constructor(source) { + const startOfFileToken = new _ast.Token(_tokenKind.TokenKind.SOF, 0, 0, 0, 0); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + get [Symbol.toStringTag]() { + return 'Lexer'; } - /** - * Creates a `MotionValue` that, when `set`, will use a spring animation to animate to its new state. - * - * It can either work as a stand-alone `MotionValue` by initialising it with a value, or as a subscriber - * to another `MotionValue`. - * - * @remarks - * - * ```jsx - * const x = useSpring(0, { stiffness: 300 }) - * const y = useSpring(x, { damping: 10 }) - * ``` - * - * @param inputValue - `MotionValue` or number. If provided a `MotionValue`, when the input `MotionValue` changes, the created `MotionValue` will spring towards that value. - * @param springConfig - Configuration options for the spring. - * @returns `MotionValue` - * - * @public + * Advances the token stream to the next non-ignored token. */ - function useSpring(source, config) { - if (config === void 0) { - config = {}; - } - var isStatic = React.useContext(MotionConfigContext).isStatic; - var activeSpringAnimation = React.useRef(null); - var value = useMotionValue(isMotionValue(source) ? source.get() : source); - React.useMemo(function () { - return value.attach(function (v, set) { - /** - * A more hollistic approach to this might be to use isStatic to fix VisualElement animations - * at that level, but this will work for now - */ - if (isStatic) return set(v); - if (activeSpringAnimation.current) { - activeSpringAnimation.current.stop(); - } - activeSpringAnimation.current = popmotion.animate(tslib.__assign(tslib.__assign({ - from: value.get(), - to: v, - velocity: value.getVelocity() - }, config), { - onUpdate: set - })); - return value.get(); - }); - }, [JSON.stringify(config)]); - useOnChange(source, function (v) { - return value.set(parseFloat(v)); - }); - return value; + + advance() { + this.lastToken = this.token; + const token = this.token = this.lookahead(); + return token; } - /** - * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes. - * - * ```javascript - * const x = useMotionValue(0) - * const xVelocity = useVelocity(x) - * const xAcceleration = useVelocity(xVelocity) - * ``` - * - * @public + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. */ - function useVelocity(value) { - var velocity = useMotionValue(value.getVelocity()); - React.useEffect(function () { - return value.velocityUpdateSubscribers.add(function (newVelocity) { - velocity.set(newVelocity); - }); - }, [value]); - return velocity; + + lookahead() { + let token = this.token; + if (token.kind !== _tokenKind.TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === _tokenKind.TokenKind.COMMENT); + } + return token; } - var createScrollMotionValues = function () { - return { - scrollX: motionValue(0), - scrollY: motionValue(0), - scrollXProgress: motionValue(0), - scrollYProgress: motionValue(0) - }; - }; - function useScroll(_a) { - if (_a === void 0) { - _a = {}; - } - var container = _a.container, - target = _a.target, - options = tslib.__rest(_a, ["container", "target"]); - var values = useConstant(createScrollMotionValues); - useIsomorphicLayoutEffect(function () { - return dom.scroll(function (_a) { - var x = _a.x, - y = _a.y; - values.scrollX.set(x.current); - values.scrollXProgress.set(x.progress); - values.scrollY.set(y.current); - values.scrollYProgress.set(y.progress); - }, tslib.__assign(tslib.__assign({}, options), { - container: (container === null || container === void 0 ? void 0 : container.current) || undefined, - target: (target === null || target === void 0 ? void 0 : target.current) || undefined - })); - }, []); - return values; +} +/** + * @internal + */ +exports.Lexer = Lexer; +function isPunctuatorTokenKind(kind) { + return kind === _tokenKind.TokenKind.BANG || kind === _tokenKind.TokenKind.DOLLAR || kind === _tokenKind.TokenKind.AMP || kind === _tokenKind.TokenKind.PAREN_L || kind === _tokenKind.TokenKind.PAREN_R || kind === _tokenKind.TokenKind.SPREAD || kind === _tokenKind.TokenKind.COLON || kind === _tokenKind.TokenKind.EQUALS || kind === _tokenKind.TokenKind.AT || kind === _tokenKind.TokenKind.BRACKET_L || kind === _tokenKind.TokenKind.BRACKET_R || kind === _tokenKind.TokenKind.BRACE_L || kind === _tokenKind.TokenKind.PIPE || kind === _tokenKind.TokenKind.BRACE_R; +} +/** + * A Unicode scalar value is any Unicode code point except surrogate code + * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and + * 0xE000 to 0x10FFFF. + * + * SourceCharacter :: + * - "Any Unicode scalar value" + */ + +function isUnicodeScalarValue(code) { + return code >= 0x0000 && code <= 0xd7ff || code >= 0xe000 && code <= 0x10ffff; +} +/** + * The GraphQL specification defines source text as a sequence of unicode scalar + * values (which Unicode defines to exclude surrogate code points). However + * JavaScript defines strings as a sequence of UTF-16 code units which may + * include surrogates. A surrogate pair is a valid source character as it + * encodes a supplementary code point (above U+FFFF), but unpaired surrogate + * code points are not valid source characters. + */ + +function isSupplementaryCodePoint(body, location) { + return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1)); +} +function isLeadingSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; +} +function isTrailingSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; +} +/** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + */ + +function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); + if (code === undefined) { + return _tokenKind.TokenKind.EOF; + } else if (code >= 0x0020 && code <= 0x007e) { + // Printable ASCII + const char = String.fromCodePoint(code); + return char === '"' ? "'\"'" : `"${char}"`; + } // Unicode code point + + return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); +} +/** + * Create a token with line and column location information. + */ + +function createToken(lexer, kind, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new _ast.Token(kind, start, end, line, col, value); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ + +function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + while (position < bodyLength) { + const code = body.charCodeAt(position); // SourceCharacter + + switch (code) { + // Ignored :: + // - UnicodeBOM + // - WhiteSpace + // - LineTerminator + // - Comment + // - Comma + // + // UnicodeBOM :: "Byte Order Mark (U+FEFF)" + // + // WhiteSpace :: + // - "Horizontal Tab (U+0009)" + // - "Space (U+0020)" + // + // Comma :: , + case 0xfeff: // + + case 0x0009: // \t + + case 0x0020: // + + case 0x002c: + // , + ++position; + continue; + // LineTerminator :: + // - "New Line (U+000A)" + // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] + // - "Carriage Return (U+000D)" "New Line (U+000A)" + + case 0x000a: + // \n + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; + case 0x000d: + // \r + if (body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + continue; + // Comment + + case 0x0023: + // # + return readComment(lexer, position); + // Token :: + // - Punctuator + // - Name + // - IntValue + // - FloatValue + // - StringValue + // + // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } + + case 0x0021: + // ! + return createToken(lexer, _tokenKind.TokenKind.BANG, position, position + 1); + case 0x0024: + // $ + return createToken(lexer, _tokenKind.TokenKind.DOLLAR, position, position + 1); + case 0x0026: + // & + return createToken(lexer, _tokenKind.TokenKind.AMP, position, position + 1); + case 0x0028: + // ( + return createToken(lexer, _tokenKind.TokenKind.PAREN_L, position, position + 1); + case 0x0029: + // ) + return createToken(lexer, _tokenKind.TokenKind.PAREN_R, position, position + 1); + case 0x002e: + // . + if (body.charCodeAt(position + 1) === 0x002e && body.charCodeAt(position + 2) === 0x002e) { + return createToken(lexer, _tokenKind.TokenKind.SPREAD, position, position + 3); + } + break; + case 0x003a: + // : + return createToken(lexer, _tokenKind.TokenKind.COLON, position, position + 1); + case 0x003d: + // = + return createToken(lexer, _tokenKind.TokenKind.EQUALS, position, position + 1); + case 0x0040: + // @ + return createToken(lexer, _tokenKind.TokenKind.AT, position, position + 1); + case 0x005b: + // [ + return createToken(lexer, _tokenKind.TokenKind.BRACKET_L, position, position + 1); + case 0x005d: + // ] + return createToken(lexer, _tokenKind.TokenKind.BRACKET_R, position, position + 1); + case 0x007b: + // { + return createToken(lexer, _tokenKind.TokenKind.BRACE_L, position, position + 1); + case 0x007c: + // | + return createToken(lexer, _tokenKind.TokenKind.PIPE, position, position + 1); + case 0x007d: + // } + return createToken(lexer, _tokenKind.TokenKind.BRACE_R, position, position + 1); + // StringValue + + case 0x0022: + // " + if (body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { + return readBlockString(lexer, position); + } + return readString(lexer, position); + } // IntValue | FloatValue (Digit | -) + + if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { + return readNumber(lexer, position, code); + } // Name + + if ((0, _characterClasses.isNameStart)(code)) { + return readName(lexer, position); + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, code === 0x0027 ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`); + } + return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); +} +/** + * Reads a comment token from the source file. + * + * ``` + * Comment :: # CommentChar* [lookahead != CommentChar] + * + * CommentChar :: SourceCharacter but not LineTerminator + * ``` + */ + +function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; + } } - function useElementScroll(ref) { - warnOnce(false, "useElementScroll is deprecated. Convert to useScroll({ container: ref })."); - return useScroll({ - container: ref - }); + return createToken(lexer, _tokenKind.TokenKind.COMMENT, start, position, body.slice(start + 1, position)); +} +/** + * Reads a number token from the source file, either a FloatValue or an IntValue + * depending on whether a FractionalPart or ExponentPart is encountered. + * + * ``` + * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] + * + * IntegerPart :: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit Digit* + * + * NegativeSign :: - + * + * NonZeroDigit :: Digit but not `0` + * + * FloatValue :: + * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * + * FractionalPart :: . Digit+ + * + * ExponentPart :: ExponentIndicator Sign? Digit+ + * + * ExponentIndicator :: one of `e` `E` + * + * Sign :: one of + - + * ``` + */ + +function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; // NegativeSign (-) + + if (code === 0x002d) { + code = body.charCodeAt(++position); + } // Zero (0) + + if (code === 0x0030) { + code = body.charCodeAt(++position); + if ((0, _characterClasses.isDigit)(code)) { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, unexpected digit after 0: ${printCodePointAt(lexer, position)}.`); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Full stop (.) + + if (code === 0x002e) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // E e + + if (code === 0x0045 || code === 0x0065) { + isFloat = true; + code = body.charCodeAt(++position); // + - + + if (code === 0x002b || code === 0x002d) { + code = body.charCodeAt(++position); + } + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, expected digit but got: ${printCodePointAt(lexer, position)}.`); + } + return createToken(lexer, isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, start, position, body.slice(start, position)); +} +/** + * Returns the new position in the source after reading one or more digits. + */ + +function readDigits(lexer, start, firstCode) { + if (!(0, _characterClasses.isDigit)(firstCode)) { + throw (0, _syntaxError.syntaxError)(lexer.source, start, `Invalid number, expected digit but got: ${printCodePointAt(lexer, start)}.`); } - function useViewportScroll() { - warnOnce(false, "useViewportScroll is deprecated. Convert to useScroll()."); - return useScroll(); + const body = lexer.source.body; + let position = start + 1; // +1 to skip first firstCode + + while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { + ++position; + } + return position; +} +/** + * Reads a single-quote string token from the source file. + * + * ``` + * StringValue :: + * - `""` [lookahead != `"`] + * - `"` StringCharacter+ `"` + * + * StringCharacter :: + * - SourceCharacter but not `"` or `\` or LineTerminator + * - `\u` EscapedUnicode + * - `\` EscapedCharacter + * + * EscapedUnicode :: + * - `{` HexDigit+ `}` + * - HexDigit HexDigit HexDigit HexDigit + * + * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` + * ``` + */ + +function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ''; + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Quote (") + + if (code === 0x0022) { + value += body.slice(chunkStart, position); + return createToken(lexer, _tokenKind.TokenKind.STRING, start, position + 1, value); + } // Escape Sequence (\) + + if (code === 0x005c) { + value += body.slice(chunkStart, position); + const escape = body.charCodeAt(position + 1) === 0x0075 // u + ? body.charCodeAt(position + 2) === 0x007b // { + ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + } } - var getCurrentTime = typeof performance !== "undefined" ? function () { - return performance.now(); - } : function () { - return Date.now(); - }; - function useAnimationFrame(callback) { - var initialTimestamp = useConstant(getCurrentTime); - var isStatic = React.useContext(MotionConfigContext).isStatic; - React.useEffect(function () { - if (isStatic) return; - var provideTimeSinceStart = function (_a) { - var timestamp = _a.timestamp; - callback(timestamp - initialTimestamp); - }; - sync__default["default"].update(provideTimeSinceStart, true); - return function () { - return sync.cancelSync.update(provideTimeSinceStart); + throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); +} // The string value and lexed size of an escape sequence. + +function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; // Cannot be larger than 12 chars (\u{00000000}). + + while (size < 12) { + const code = body.charCodeAt(position + size++); // Closing Brace (}) + + if (code === 0x007d) { + // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } + return { + value: String.fromCodePoint(point), + size }; - }, [callback]); - } - function useTime() { - var time = useMotionValue(0); - useAnimationFrame(function (t) { - return time.set(t); - }); - return time; + } // Append this hex digit to the code point. + + point = point << 4 | readHexDigit(code); + if (point < 0) { + break; + } } - - /** - * @public - */ - function animationControls() { - /** - * Track whether the host component has mounted. - */ - var hasMounted = false; - /** - * Pending animations that are started before a component is mounted. - * TODO: Remove this as animations should only run in effects - */ - var pendingAnimations = []; - /** - * A collection of linked component animation controls. - */ - var subscribers = new Set(); - var controls = { - subscribe: function (visualElement) { - subscribers.add(visualElement); - return function () { - return void subscribers.delete(visualElement); - }; - }, - start: function (definition, transitionOverride) { - /** - * TODO: We only perform this hasMounted check because in Framer we used to - * encourage the ability to start an animation within the render phase. This - * isn't behaviour concurrent-safe so when we make Framer concurrent-safe - * we can ditch this. - */ - if (hasMounted) { - var animations_1 = []; - subscribers.forEach(function (visualElement) { - animations_1.push(animateVisualElement(visualElement, definition, { - transitionOverride: transitionOverride - })); - }); - return Promise.all(animations_1); - } else { - return new Promise(function (resolve) { - pendingAnimations.push({ - animation: [definition, transitionOverride], - resolve: resolve - }); - }); - } - }, - set: function (definition) { - heyListen.invariant(hasMounted, "controls.set() should only be called after a component has mounted. Consider calling within a useEffect hook."); - return subscribers.forEach(function (visualElement) { - setValues(visualElement, definition); - }); - }, - stop: function () { - subscribers.forEach(function (visualElement) { - stopAnimation(visualElement); - }); - }, - mount: function () { - hasMounted = true; - pendingAnimations.forEach(function (_a) { - var animation = _a.animation, - resolve = _a.resolve; - controls.start.apply(controls, tslib.__spreadArray([], tslib.__read(animation), false)).then(resolve); - }); - return function () { - hasMounted = false; - controls.stop(); + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + size)}".`); +} +function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); + if (isUnicodeScalarValue(code)) { + return { + value: String.fromCodePoint(code), + size: 6 + }; + } // GraphQL allows JSON-style surrogate pair escape sequences, but only when + // a valid pair is formed. + + if (isLeadingSurrogate(code)) { + // \u + if (body.charCodeAt(position + 6) === 0x005c && body.charCodeAt(position + 7) === 0x0075) { + const trailingCode = read16BitHexCode(body, position + 8); + if (isTrailingSurrogate(trailingCode)) { + // JavaScript defines strings as a sequence of UTF-16 code units and + // encodes Unicode code points above U+FFFF using a surrogate pair of + // code units. Since this is a surrogate pair escape sequence, just + // include both codes into the JavaScript string value. Had JavaScript + // not been internally based on UTF-16, then this surrogate pair would + // be decoded to retrieve the supplementary code point. + return { + value: String.fromCodePoint(code, trailingCode), + size: 12 }; } - }; - return controls; + } } - - /** - * Creates `AnimationControls`, which can be used to manually start, stop - * and sequence animations on one or more components. - * - * The returned `AnimationControls` should be passed to the `animate` property - * of the components you want to animate. - * - * These components can then be animated with the `start` method. - * - * ```jsx - * import * as React from 'react' - * import { motion, useAnimation } from 'framer-motion' - * - * export function MyComponent(props) { - * const controls = useAnimation() - * - * controls.start({ - * x: 100, - * transition: { duration: 0.5 }, - * }) - * - * return - * } - * ``` - * - * @returns Animation controller with `start` and `stop` methods - * - * @public - */ - function useAnimationControls() { - var controls = useConstant(animationControls); - React.useEffect(controls.mount, []); - return controls; + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`); +} +/** + * Reads four hexadecimal characters and returns the positive integer that 16bit + * hexadecimal string represents. For example, "000f" will return 15, and "dead" + * will return 57005. + * + * Returns a negative number if any char was not a valid hexadecimal digit. + */ + +function read16BitHexCode(body, position) { + // readHexDigit() returns -1 on error. ORing a negative value with any other + // value always produces a negative value. + return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3)); +} +/** + * Reads a hexadecimal character and returns its positive integer value (0-15). + * + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 if the provided character code was not a valid hexadecimal digit. + * + * HexDigit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * - `A` `B` `C` `D` `E` `F` + * - `a` `b` `c` `d` `e` `f` + */ + +function readHexDigit(code) { + return code >= 0x0030 && code <= 0x0039 // 0-9 + ? code - 0x0030 : code >= 0x0041 && code <= 0x0046 // A-F + ? code - 0x0037 : code >= 0x0061 && code <= 0x0066 // a-f + ? code - 0x0057 : -1; +} +/** + * | Escaped Character | Code Point | Character Name | + * | ----------------- | ---------- | ---------------------------- | + * | `"` | U+0022 | double quote | + * | `\` | U+005C | reverse solidus (back slash) | + * | `/` | U+002F | solidus (forward slash) | + * | `b` | U+0008 | backspace | + * | `f` | U+000C | form feed | + * | `n` | U+000A | line feed (new line) | + * | `r` | U+000D | carriage return | + * | `t` | U+0009 | horizontal tab | + */ + +function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); + switch (code) { + case 0x0022: + // " + return { + value: '\u0022', + size: 2 + }; + case 0x005c: + // \ + return { + value: '\u005c', + size: 2 + }; + case 0x002f: + // / + return { + value: '\u002f', + size: 2 + }; + case 0x0062: + // b + return { + value: '\u0008', + size: 2 + }; + case 0x0066: + // f + return { + value: '\u000c', + size: 2 + }; + case 0x006e: + // n + return { + value: '\u000a', + size: 2 + }; + case 0x0072: + // r + return { + value: '\u000d', + size: 2 + }; + case 0x0074: + // t + return { + value: '\u0009', + size: 2 + }; + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character escape sequence: "${body.slice(position, position + 2)}".`); +} +/** + * Reads a block string token from the source file. + * + * ``` + * StringValue :: + * - `"""` BlockStringCharacter* `"""` + * + * BlockStringCharacter :: + * - SourceCharacter but not `"""` or `\"""` + * - `\"""` + * ``` + */ + +function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ''; + const blockLines = []; + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Triple-Quote (""") + + if (code === 0x0022 && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken(lexer, _tokenKind.TokenKind.BLOCK_STRING, start, position + 3, + // Return a string of the lines joined with U+000A. + (0, _blockString.dedentBlockStringLines)(blockLines).join('\n')); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } // Escaped Triple-Quote (\""") + + if (code === 0x005c && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022 && body.charCodeAt(position + 3) === 0x0022) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; // skip only slash + + position += 4; + continue; + } // LineTerminator + + if (code === 0x000a || code === 0x000d) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + currentLine = ''; + chunkStart = position; + lineStart = position; + continue; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + } + } + throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + */ + +function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if ((0, _characterClasses.isNameContinue)(code)) { + ++position; + } else { + break; + } + } + return createToken(lexer, _tokenKind.TokenKind.NAME, start, position, body.slice(start, position)); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/location.mjs": +/*!***********************************************************!*\ + !*** ../../../node_modules/graphql/language/location.mjs ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getLocation = getLocation; +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +const LineRegExp = /\r\n|[\n\r]/g; +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; + for (const match of source.body.matchAll(LineRegExp)) { + typeof match.index === 'number' || (0, _invariant.invariant)(false); + if (match.index >= position) { + break; + } + lastLineStart = match.index + match[0].length; + line += 1; + } + return { + line, + column: position + 1 - lastLineStart + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/parser.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/language/parser.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Parser = void 0; +exports.parse = parse; +exports.parseConstValue = parseConstValue; +exports.parseType = parseType; +exports.parseValue = parseValue; +var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); +var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); +var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); +var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); +var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); +/** + * Configuration options to control parser behavior + */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +function parse(source, options) { + const parser = new Parser(source, options); + return parser.parseDocument(); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + +function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + */ + +function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + +function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return type; +} +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + +class Parser { + constructor(source, options = {}) { + const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); + this._lexer = new _lexer.Lexer(sourceObj); + this._options = options; + this._tokenCounter = 0; } - var useAnimation = useAnimationControls; - /** - * Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to `useState` in React. It is provided an initial array of possible states, and returns an array of two arguments. - * - * An index value can be passed to the returned `cycle` function to cycle to a specific index. - * - * ```jsx - * import * as React from "react" - * import { motion, useCycle } from "framer-motion" - * - * export const MyComponent = () => { - * const [x, cycleX] = useCycle(0, 50, 100) - * - * return ( - * cycleX()} - * /> - * ) - * } - * ``` - * - * @param items - items to cycle through - * @returns [currentState, cycleState] - * - * @public + * Converts a name lex token into a name parse node. */ - function useCycle() { - var items = []; - for (var _i = 0; _i < arguments.length; _i++) { - items[_i] = arguments[_i]; - } - var index = React.useRef(0); - var _a = tslib.__read(React.useState(items[index.current]), 2), - item = _a[0], - setItem = _a[1]; - var runCycle = React.useCallback(function (next) { - index.current = typeof next !== "number" ? popmotion.wrap(0, items.length, index.current + 1) : next; - setItem(items[index.current]); - }, tslib.__spreadArray([items.length], tslib.__read(items), false)); - return [item, runCycle]; - } - function useInView(ref, _a) { - var _b = _a === void 0 ? {} : _a, - root = _b.root, - margin = _b.margin, - amount = _b.amount, - _c = _b.once, - once = _c === void 0 ? false : _c; - var _d = tslib.__read(React.useState(false), 2), - isInView = _d[0], - setInView = _d[1]; - React.useEffect(function () { - var _a; - if (!ref.current || once && isInView) return; - var onEnter = function () { - setInView(true); - return once ? undefined : function () { - return setInView(false); - }; - }; - var options = { - root: (_a = root === null || root === void 0 ? void 0 : root.current) !== null && _a !== void 0 ? _a : undefined, - margin: margin, - amount: amount === "some" ? "any" : amount - }; - return dom.inView(ref.current, onEnter, options); - }, [root, ref, margin, once]); - return isInView; + + parseName() { + const token = this.expectToken(_tokenKind.TokenKind.NAME); + return this.node(token, { + kind: _kinds.Kind.NAME, + value: token.value + }); + } // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + */ + + parseDocument() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.DOCUMENT, + definitions: this.many(_tokenKind.TokenKind.SOF, this.parseDefinition, _tokenKind.TokenKind.EOF) + }); } - /** - * Can manually trigger a drag gesture on one or more `drag`-enabled `motion` components. - * - * ```jsx - * const dragControls = useDragControls() + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension * - * function startDrag(event) { - * dragControls.start(event, { snapToCursor: true }) - * } + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition * - * return ( - * <> - *
    - * - * - * ) - * ``` + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition * - * @public + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition */ - var DragControls = /** @class */function () { - function DragControls() { - this.componentControls = new Set(); + + parseDefinition() { + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } // Many definitions begin with a description and require a lookahead. + + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token; + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + case 'scalar': + return this.parseScalarTypeDefinition(); + case 'type': + return this.parseObjectTypeDefinition(); + case 'interface': + return this.parseInterfaceTypeDefinition(); + case 'union': + return this.parseUnionTypeDefinition(); + case 'enum': + return this.parseEnumTypeDefinition(); + case 'input': + return this.parseInputObjectTypeDefinition(); + case 'directive': + return this.parseDirectiveDefinition(); + } + if (hasDescription) { + throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, 'Unexpected description, descriptions are supported only on type definitions.'); + } + switch (keywordToken.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + case 'fragment': + return this.parseFragmentDefinition(); + case 'extend': + return this.parseTypeSystemExtension(); + } } - /** - * Subscribe a component's internal `VisualElementDragControls` to the user-facing API. - * - * @internal - */ - DragControls.prototype.subscribe = function (controls) { - var _this = this; - this.componentControls.add(controls); - return function () { - return _this.componentControls.delete(controls); - }; - }; - /** - * Start a drag gesture on every `motion` component that has this set of drag controls - * passed into it via the `dragControls` prop. - * - * ```jsx - * dragControls.start(e, { - * snapToCursor: true - * }) - * ``` - * - * @param event - PointerEvent - * @param options - Options - * - * @public - */ - DragControls.prototype.start = function (event, options) { - this.componentControls.forEach(function (controls) { - controls.start(event.nativeEvent || event, options); - }); - }; - return DragControls; - }(); - var createDragControls = function () { - return new DragControls(); - }; + throw this.unexpected(keywordToken); + } // Implements the parsing rules in the Operations section. + /** - * Usually, dragging is initiated by pressing down on a `motion` component with a `drag` prop - * and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we - * might want to initiate that dragging from a different component than the draggable one. - * - * By creating a `dragControls` using the `useDragControls` hook, we can pass this into - * the draggable component's `dragControls` prop. It exposes a `start` method - * that can start dragging from pointer events on other components. - * - * ```jsx - * const dragControls = useDragControls() - * - * function startDrag(event) { - * dragControls.start(event, { snapToCursor: true }) - * } - * - * return ( - * <> - *
    - * - * - * ) - * ``` - * - * @public + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet */ - function useDragControls() { - return useConstant(createDragControls); - } - function useInstantLayoutTransition() { - return startTransition; - } - function startTransition(cb) { - if (!rootProjectionNode.current) return; - rootProjectionNode.current.isUpdating = false; - rootProjectionNode.current.blockUpdate(); - cb === null || cb === void 0 ? void 0 : cb(); - } - function useInstantTransition() { - var _a = tslib.__read(useForceUpdate(), 2), - forceUpdate = _a[0], - forcedRenderCount = _a[1]; - var startInstantLayoutTransition = useInstantLayoutTransition(); - React.useEffect(function () { - /** - * Unblock after two animation frames, otherwise this will unblock too soon. - */ - sync__default["default"].postRender(function () { - return sync__default["default"].postRender(function () { - return instantAnimationState.current = false; - }); - }); - }, [forcedRenderCount]); - return function (callback) { - startInstantLayoutTransition(function () { - instantAnimationState.current = true; - forceUpdate(); - callback(); + + parseOperationDefinition() { + const start = this._lexer.token; + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: _ast.OperationTypeNode.QUERY, + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet() }); - }; - } - function useResetProjection() { - var reset = React__namespace.useCallback(function () { - var root = rootProjectionNode.current; - if (!root) return; - root.resetTree(); - }, []); - return reset; + } + const operation = this.parseOperationType(); + let name; + if (this.peek(_tokenKind.TokenKind.NAME)) { + name = this.parseName(); + } + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); } - var createObject = function () { - return {}; - }; - var stateVisualElement = visualElement({ - build: function () {}, - measureViewportBox: createBox, - resetTransform: function () {}, - restoreTransform: function () {}, - removeValueFromRenderState: function () {}, - render: function () {}, - scrapeMotionValuesFromProps: createObject, - readValueFromInstance: function (_state, key, options) { - return options.initialState[key] || 0; - }, - makeTargetAnimatable: function (element, _a) { - var transition = _a.transition, - transitionEnd = _a.transitionEnd, - target = tslib.__rest(_a, ["transition", "transitionEnd"]); - var origin = getOrigin(target, transition || {}, element); - checkTargetForNewValues(element, target, origin); - return tslib.__assign({ - transition: transition, - transitionEnd: transitionEnd - }, target); + /** + * OperationType : one of query mutation subscription + */ + + parseOperationType() { + const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); + switch (operationToken.value) { + case 'query': + return _ast.OperationTypeNode.QUERY; + case 'mutation': + return _ast.OperationTypeNode.MUTATION; + case 'subscription': + return _ast.OperationTypeNode.SUBSCRIPTION; } - }); - var useVisualState = makeUseVisualState({ - scrapeMotionValuesFromProps: createObject, - createRenderState: createObject - }); + throw this.unexpected(operationToken); + } /** - * This is not an officially supported API and may be removed - * on any version. + * VariableDefinitions : ( VariableDefinition+ ) */ - function useAnimatedState(initialState) { - var _a = tslib.__read(React.useState(initialState), 2), - animationState = _a[0], - setAnimationState = _a[1]; - var visualState = useVisualState({}, false); - var element = useConstant(function () { - return stateVisualElement({ - props: {}, - visualState: visualState - }, { - initialState: initialState - }); + + parseVariableDefinitions() { + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseVariableDefinition, _tokenKind.TokenKind.PAREN_R); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: (this.expectToken(_tokenKind.TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.parseConstValueLiteral() : undefined, + directives: this.parseConstDirectives() }); - React.useEffect(function () { - element.mount({}); - return element.unmount; - }, [element]); - React.useEffect(function () { - element.setProps({ - onUpdate: function (v) { - setAnimationState(tslib.__assign({}, v)); - } - }); - }, [setAnimationState, element]); - var startAnimation = useConstant(function () { - return function (animationDefinition) { - return animateVisualElement(element, animationDefinition); - }; + } + /** + * Variable : $ Name + */ + + parseVariable() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.DOLLAR); + return this.node(start, { + kind: _kinds.Kind.VARIABLE, + name: this.parseName() }); - return [animationState, startAnimation]; } - - // Keep things reasonable and avoid scale: Infinity. In practise we might need - // to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1] - // to simply hide content at unreasonable scales. - var maxScale = 100000; - var invertScale = function (scale) { - return scale > 0.001 ? 1 / scale : maxScale; - }; - var hasWarned = false; /** - * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse - * of their respective parent scales. - * - * This is useful for undoing the distortion of content when scaling a parent component. - * - * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent. - * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output - * of those instead. - * - * ```jsx - * const MyComponent = () => { - * const { scaleX, scaleY } = useInvertedScale() - * return - * } * ``` - * - * @deprecated + * SelectionSet : { Selection+ } + * ``` */ - function useInvertedScale(scale) { - var parentScaleX = useMotionValue(1); - var parentScaleY = useMotionValue(1); - var visualElement = useVisualElementContext(); - heyListen.invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component."); - heyListen.warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead."); - hasWarned = true; - if (scale) { - parentScaleX = scale.scaleX || parentScaleX; - parentScaleY = scale.scaleY || parentScaleY; - } else if (visualElement) { - parentScaleX = visualElement.getValue("scaleX", 1); - parentScaleY = visualElement.getValue("scaleY", 1); - } - var scaleX = useTransform(parentScaleX, invertScale); - var scaleY = useTransform(parentScaleY, invertScale); - return { - scaleX: scaleX, - scaleY: scaleY - }; + + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.SELECTION_SET, + selections: this.many(_tokenKind.TokenKind.BRACE_L, this.parseSelection, _tokenKind.TokenKind.BRACE_R) + }); } - exports.AnimatePresence = AnimatePresence; - exports.AnimateSharedLayout = AnimateSharedLayout; - exports.DeprecatedLayoutGroupContext = DeprecatedLayoutGroupContext; - exports.DragControls = DragControls; - exports.FlatTree = FlatTree; - exports.LayoutGroup = LayoutGroup; - exports.LayoutGroupContext = LayoutGroupContext; - exports.LazyMotion = LazyMotion; - exports.MotionConfig = MotionConfig; - exports.MotionConfigContext = MotionConfigContext; - exports.MotionContext = MotionContext; - exports.MotionValue = MotionValue; - exports.PresenceContext = PresenceContext; - exports.Reorder = Reorder; - exports.SwitchLayoutGroupContext = SwitchLayoutGroupContext; - exports.addPointerEvent = addPointerEvent; - exports.addScaleCorrector = addScaleCorrector; - exports.animate = animate; - exports.animateVisualElement = animateVisualElement; - exports.animationControls = animationControls; - exports.animations = animations; - exports.calcLength = calcLength; - exports.checkTargetForNewValues = checkTargetForNewValues; - exports.createBox = createBox; - exports.createDomMotionComponent = createDomMotionComponent; - exports.createMotionComponent = createMotionComponent; - exports.domAnimation = domAnimation; - exports.domMax = domMax; - exports.filterProps = filterProps; - exports.isBrowser = isBrowser; - exports.isDragActive = isDragActive; - exports.isMotionValue = isMotionValue; - exports.isValidMotionProp = isValidMotionProp; - exports.m = m; - exports.makeUseVisualState = makeUseVisualState; - exports.motion = motion; - exports.motionValue = motionValue; - exports.resolveMotionValue = resolveMotionValue; - exports.transform = transform; - exports.useAnimation = useAnimation; - exports.useAnimationControls = useAnimationControls; - exports.useAnimationFrame = useAnimationFrame; - exports.useCycle = useCycle; - exports.useDeprecatedAnimatedState = useAnimatedState; - exports.useDeprecatedInvertedScale = useInvertedScale; - exports.useDomEvent = useDomEvent; - exports.useDragControls = useDragControls; - exports.useElementScroll = useElementScroll; - exports.useForceUpdate = useForceUpdate; - exports.useInView = useInView; - exports.useInstantLayoutTransition = useInstantLayoutTransition; - exports.useInstantTransition = useInstantTransition; - exports.useIsPresent = useIsPresent; - exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect; - exports.useMotionTemplate = useMotionTemplate; - exports.useMotionValue = useMotionValue; - exports.usePresence = usePresence; - exports.useReducedMotion = useReducedMotion; - exports.useReducedMotionConfig = useReducedMotionConfig; - exports.useResetProjection = useResetProjection; - exports.useScroll = useScroll; - exports.useSpring = useSpring; - exports.useTime = useTime; - exports.useTransform = useTransform; - exports.useUnmountEffect = useUnmountEffect; - exports.useVelocity = useVelocity; - exports.useViewportScroll = useViewportScroll; - exports.useVisualElementContext = useVisualElementContext; - exports.visualElement = visualElement; - exports.wrapHandler = wrapHandler; - - /***/ }), - - /***/ "../../../node_modules/framesync/dist/framesync.cjs.js": - /*!*************************************************************!*\ - !*** ../../../node_modules/framesync/dist/framesync.cjs.js ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - const defaultTimestep = 1 / 60 * 1000; - const getCurrentTime = typeof performance !== "undefined" ? () => performance.now() : () => Date.now(); - const onNextFrame = typeof window !== "undefined" ? callback => window.requestAnimationFrame(callback) : callback => setTimeout(() => callback(getCurrentTime()), defaultTimestep); - function createRenderStep(runNextFrame) { - let toRun = []; - let toRunNextFrame = []; - let numToRun = 0; - let isProcessing = false; - let flushNextFrame = false; - const toKeepAlive = new WeakSet(); - const step = { - schedule: (callback, keepAlive = false, immediate = false) => { - const addToCurrentFrame = immediate && isProcessing; - const buffer = addToCurrentFrame ? toRun : toRunNextFrame; - if (keepAlive) toKeepAlive.add(callback); - if (buffer.indexOf(callback) === -1) { - buffer.push(callback); - if (addToCurrentFrame && isProcessing) numToRun = toRun.length; - } - return callback; - }, - cancel: callback => { - const index = toRunNextFrame.indexOf(callback); - if (index !== -1) toRunNextFrame.splice(index, 1); - toKeepAlive.delete(callback); - }, - process: frameData => { - if (isProcessing) { - flushNextFrame = true; - return; - } - isProcessing = true; - [toRun, toRunNextFrame] = [toRunNextFrame, toRun]; - toRunNextFrame.length = 0; - numToRun = toRun.length; - if (numToRun) { - for (let i = 0; i < numToRun; i++) { - const callback = toRun[i]; - callback(frameData); - if (toKeepAlive.has(callback)) { - step.schedule(callback); - runNextFrame(); - } - } - } - isProcessing = false; - if (flushNextFrame) { - flushNextFrame = false; - step.process(frameData); - } - } - }; - return step; + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + parseSelection() { + return this.peek(_tokenKind.TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); } - const maxElapsed = 40; - let useDefaultElapsed = true; - let runNextFrame = false; - let isProcessing = false; - const frame = { - delta: 0, - timestamp: 0 - }; - const stepsOrder = ["read", "update", "preRender", "render", "postRender"]; - const steps = stepsOrder.reduce((acc, key) => { - acc[key] = createRenderStep(() => runNextFrame = true); - return acc; - }, {}); - const sync = stepsOrder.reduce((acc, key) => { - const step = steps[key]; - acc[key] = (process, keepAlive = false, immediate = false) => { - if (!runNextFrame) startLoop(); - return step.schedule(process, keepAlive, immediate); - }; - return acc; - }, {}); - const cancelSync = stepsOrder.reduce((acc, key) => { - acc[key] = steps[key].cancel; - return acc; - }, {}); - const flushSync = stepsOrder.reduce((acc, key) => { - acc[key] = () => steps[key].process(frame); - return acc; - }, {}); - const processStep = stepId => steps[stepId].process(frame); - const processFrame = timestamp => { - runNextFrame = false; - frame.delta = useDefaultElapsed ? defaultTimestep : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1); - frame.timestamp = timestamp; - isProcessing = true; - stepsOrder.forEach(processStep); - isProcessing = false; - if (runNextFrame) { - useDefaultElapsed = false; - onNextFrame(processFrame); - } - }; - const startLoop = () => { - runNextFrame = true; - useDefaultElapsed = true; - if (!isProcessing) onNextFrame(processFrame); - }; - const getFrameData = () => frame; - exports.cancelSync = cancelSync; - exports["default"] = sync; - exports.flushSync = flushSync; - exports.getFrameData = getFrameData; - - /***/ }), - - /***/ "../../../node_modules/get-nonce/dist/es2015/index.js": - /*!************************************************************!*\ - !*** ../../../node_modules/get-nonce/dist/es2015/index.js ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.setNonce = exports.getNonce = void 0; - var currentNonce; - var setNonce = function (nonce) { - currentNonce = nonce; - }; - exports.setNonce = setNonce; - var getNonce = function () { - if (currentNonce) { - return currentNonce; - } - if (true) { - return __webpack_require__.nc; + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; + if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; } - return undefined; - }; - exports.getNonce = getNonce; - - /***/ }), - - /***/ "../../../node_modules/graphql-ws/lib/client.mjs": - /*!*******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/client.mjs ***! - \*******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var _exportNames = { - createClient: true - }; - exports.createClient = createClient; - var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); - Object.keys(_common).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _common[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _common[key]; - } + return this.node(start, { + kind: _kinds.Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined }); - }); - var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, item, _tokenKind.TokenKind.PAREN_R); + } + /** + * Argument[Const] : Name : Value[?Const] + */ + + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst) + }); + } + parseConstArgument() { + return this.parseArgument(true); + } // Implements the parsing rules in the Fragments section. + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. * - * client + * FragmentSpread : ... FragmentName Directives? * + * InlineFragment : ... TypeCondition? Directives? SelectionSet */ - var __await = void 0 && (void 0).__await || function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } + + parseFragment() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword('on'); + if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false) + }); } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); + return this.node(start, { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + parseFragmentDefinition() { + const start = this._lexer.token; + this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (this._options.allowLegacyFragmentVariables === true) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + /** + * FragmentName : Name but not `on` + */ + + parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); } - }; - - /** This file is the entry point for browsers, re-export common elements. */ - + return this.parseName(); + } // Implements the parsing rules in the Values section. + /** - * Creates a disposable GraphQL over WebSocket client. + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` * - * @category Client + * EnumValue : Name but not `true`, `false` or `null` */ - function createClient(options) { - const { - url, - connectionParams, - lazy = true, - onNonLazyError = console.error, - lazyCloseTimeout: lazyCloseTimeoutMs = 0, - keepAlive = 0, - disablePong, - connectionAckWaitTimeout = 0, - retryAttempts = 5, - retryWait = async function randomisedExponentialBackoff(retries) { - let retryDelay = 1000; // start with 1s delay - for (let i = 0; i < retries; i++) { - retryDelay *= 2; - } - await new Promise(resolve => setTimeout(resolve, retryDelay + - // add random timeout from 300ms to 3s - Math.floor(Math.random() * (3000 - 300) + 300))); - }, - shouldRetry = isLikeCloseEvent, - isFatalConnectionProblem, - on, - webSocketImpl, - /** - * Generates a v4 UUID to be used as the ID using `Math` - * as the random number generator. Supply your own generator - * in case you need more uniqueness. - * - * Reference: https://gist.github.com/jed/982883 - */ - generateID = function generateUUID() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { - const r = Math.random() * 16 | 0, - v = c == 'x' ? r : r & 0x3 | 0x8; - return v.toString(16); + + parseValueLiteral(isConst) { + const token = this._lexer.token; + switch (token.kind) { + case _tokenKind.TokenKind.BRACKET_L: + return this.parseList(isConst); + case _tokenKind.TokenKind.BRACE_L: + return this.parseObject(isConst); + case _tokenKind.TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.INT, + value: token.value }); - }, - jsonMessageReplacer: replacer, - jsonMessageReviver: reviver - } = options; - let ws; - if (webSocketImpl) { - if (!isWebSocket(webSocketImpl)) { - throw new Error('Invalid WebSocket implementation provided'); - } - ws = webSocketImpl; - } else if (typeof WebSocket !== 'undefined') { - ws = WebSocket; - } else if (typeof __webpack_require__.g !== 'undefined') { - ws = __webpack_require__.g.WebSocket || - // @ts-expect-error: Support more browsers - __webpack_require__.g.MozWebSocket; - } else if (typeof window !== 'undefined') { - ws = window.WebSocket || - // @ts-expect-error: Support more browsers - window.MozWebSocket; - } - if (!ws) throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`"); - const WebSocketImpl = ws; - // websocket status emitter, subscriptions are handled differently - const emitter = (() => { - const message = (() => { - const listeners = {}; - return { - on(id, listener) { - listeners[id] = listener; - return () => { - delete listeners[id]; - }; - }, - emit(message) { - var _a; - if ('id' in message) (_a = listeners[message.id]) === null || _a === void 0 ? void 0 : _a.call(listeners, message); - } - }; - })(); - const listeners = { - connecting: (on === null || on === void 0 ? void 0 : on.connecting) ? [on.connecting] : [], - opened: (on === null || on === void 0 ? void 0 : on.opened) ? [on.opened] : [], - connected: (on === null || on === void 0 ? void 0 : on.connected) ? [on.connected] : [], - ping: (on === null || on === void 0 ? void 0 : on.ping) ? [on.ping] : [], - pong: (on === null || on === void 0 ? void 0 : on.pong) ? [on.pong] : [], - message: (on === null || on === void 0 ? void 0 : on.message) ? [message.emit, on.message] : [message.emit], - closed: (on === null || on === void 0 ? void 0 : on.closed) ? [on.closed] : [], - error: (on === null || on === void 0 ? void 0 : on.error) ? [on.error] : [] - }; - return { - onMessage: message.on, - on(event, listener) { - const l = listeners[event]; - l.push(listener); - return () => { - l.splice(l.indexOf(listener), 1); - }; - }, - emit(event, ...args) { - // we copy the listeners so that unlistens dont "pull the rug under our feet" - for (const listener of [...listeners[event]]) { - // @ts-expect-error: The args should fit - listener(...args); - } - } - }; - })(); - // invokes the callback either when an error or closed event is emitted, - // first one that gets called prevails, other emissions are ignored - function errorOrClosed(cb) { - const listening = [ - // errors are fatal and more critical than close events, throw them first - emitter.on('error', err => { - listening.forEach(unlisten => unlisten()); - cb(err); - }), - // closes can be graceful and not fatal, throw them second (if error didnt throw) - emitter.on('closed', event => { - listening.forEach(unlisten => unlisten()); - cb(event); - })]; - } - let connecting, - locks = 0, - lazyCloseTimeout, - retrying = false, - retries = 0, - disposed = false; - async function connect() { - // clear the lazy close timeout immediatelly so that close gets debounced - // see: https://github.com/enisdenjo/graphql-ws/issues/388 - clearTimeout(lazyCloseTimeout); - const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : connecting = new Promise((connected, denied) => (async () => { - if (retrying) { - await retryWait(retries); - // subscriptions might complete while waiting for retry - if (!locks) { - connecting = undefined; - return denied({ - code: 1000, - reason: 'All Subscriptions Gone' + case _tokenKind.TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.FLOAT, + value: token.value + }); + case _tokenKind.TokenKind.STRING: + case _tokenKind.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + case _tokenKind.TokenKind.NAME: + this.advanceLexer(); + switch (token.value) { + case 'true': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: true + }); + case 'false': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: false + }); + case 'null': + return this.node(token, { + kind: _kinds.Kind.NULL + }); + default: + return this.node(token, { + kind: _kinds.Kind.ENUM, + value: token.value }); - } - retries++; - } - emitter.emit('connecting'); - const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, _common.GRAPHQL_TRANSPORT_WS_PROTOCOL); - let connectionAckTimeout, queuedPing; - function enqueuePing() { - if (isFinite(keepAlive) && keepAlive > 0) { - clearTimeout(queuedPing); // in case where a pong was received before a ping (this is valid behaviour) - queuedPing = setTimeout(() => { - if (socket.readyState === WebSocketImpl.OPEN) { - socket.send((0, _common.stringifyMessage)({ - type: _common.MessageType.Ping - })); - emitter.emit('ping', false, undefined); - } - }, keepAlive); - } } - errorOrClosed(errOrEvent => { - connecting = undefined; - clearTimeout(connectionAckTimeout); - clearTimeout(queuedPing); - denied(errOrEvent); - if (isLikeCloseEvent(errOrEvent) && errOrEvent.code === 4499) { - socket.close(4499, 'Terminated'); // close event is artificial and emitted manually, see `Client.terminate()` below - socket.onerror = null; - socket.onclose = null; - } - }); - socket.onerror = err => emitter.emit('error', err); - socket.onclose = event => emitter.emit('closed', event); - socket.onopen = async () => { - try { - emitter.emit('opened', socket); - const payload = typeof connectionParams === 'function' ? await connectionParams() : connectionParams; - // connectionParams might take too long causing the server to kick off the client - // the necessary error/close event is already reported - simply stop execution - if (socket.readyState !== WebSocketImpl.OPEN) return; - socket.send((0, _common.stringifyMessage)(payload ? { - type: _common.MessageType.ConnectionInit, - payload - } : { - type: _common.MessageType.ConnectionInit - // payload is completely absent if not provided - }, replacer)); - if (isFinite(connectionAckWaitTimeout) && connectionAckWaitTimeout > 0) { - connectionAckTimeout = setTimeout(() => { - socket.close(_common.CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout'); - }, connectionAckWaitTimeout); - } - enqueuePing(); // enqueue ping (noop if disabled) - } catch (err) { - emitter.emit('error', err); - socket.close(_common.CloseCode.InternalClientError, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Internal client error')); - } - }; - let acknowledged = false; - socket.onmessage = ({ - data - }) => { - try { - const message = (0, _common.parseMessage)(data, reviver); - emitter.emit('message', message); - if (message.type === 'ping' || message.type === 'pong') { - emitter.emit(message.type, true, message.payload); // received - if (message.type === 'pong') { - enqueuePing(); // enqueue next ping (noop if disabled) - } else if (!disablePong) { - // respond with pong on ping - socket.send((0, _common.stringifyMessage)(message.payload ? { - type: _common.MessageType.Pong, - payload: message.payload - } : { - type: _common.MessageType.Pong - // payload is completely absent if not provided - })); - emitter.emit('pong', false, message.payload); - } - return; // ping and pongs can be received whenever - } - if (acknowledged) return; // already connected and acknowledged - if (message.type !== _common.MessageType.ConnectionAck) throw new Error(`First message cannot be of type ${message.type}`); - clearTimeout(connectionAckTimeout); - acknowledged = true; - emitter.emit('connected', socket, message.payload); // connected = socket opened + acknowledged - retrying = false; // future lazy connects are not retries - retries = 0; // reset the retries on connect - connected([socket, new Promise((_, reject) => errorOrClosed(reject))]); - } catch (err) { - socket.onmessage = null; // stop reading messages as soon as reading breaks once - emitter.emit('error', err); - socket.close(_common.CloseCode.BadResponse, (0, _utils.limitCloseReason)(err instanceof Error ? err.message : new Error(err).message, 'Bad response')); - } - }; - })())); - // if the provided socket is in a closing state, wait for the throw on close - if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose; - let release = () => { - // releases this connection - }; - const released = new Promise(resolve => release = resolve); - return [socket, release, Promise.race([ - // wait for - released.then(() => { - if (!locks) { - // and if no more locks are present, complete the connection - const complete = () => socket.close(1000, 'Normal Closure'); - if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) { - // if the keepalive is set, allow for the specified calmdown time and - // then complete if the socket is still open. - lazyCloseTimeout = setTimeout(() => { - if (socket.readyState === WebSocketImpl.OPEN) complete(); - }, lazyCloseTimeoutMs); + case _tokenKind.TokenKind.DOLLAR: + if (isConst) { + this.expectToken(_tokenKind.TokenKind.DOLLAR); + if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { + const varName = this._lexer.token.value; + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected variable "$${varName}" in constant value.`); } else { - // otherwise complete immediately - complete(); - } - } - }), - // or - throwOnClose])]; - } - /** - * Checks the `connect` problem and evaluates if the client should retry. - */ - function shouldRetryConnectOrThrow(errOrCloseEvent) { - // some close codes are worth reporting immediately - if (isLikeCloseEvent(errOrCloseEvent) && (isFatalInternalCloseCode(errOrCloseEvent.code) || [_common.CloseCode.InternalServerError, _common.CloseCode.InternalClientError, _common.CloseCode.BadRequest, _common.CloseCode.BadResponse, _common.CloseCode.Unauthorized, - // CloseCode.Forbidden, might grant access out after retry - _common.CloseCode.SubprotocolNotAcceptable, - // CloseCode.ConnectionInitialisationTimeout, might not time out after retry - // CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry - _common.CloseCode.SubscriberAlreadyExists, _common.CloseCode.TooManyInitialisationRequests - // 4499, // Terminated, probably because the socket froze, we want to retry - ].includes(errOrCloseEvent.code))) throw errOrCloseEvent; - // client was disposed, no retries should proceed regardless - if (disposed) return false; - // normal closure (possibly all subscriptions have completed) - // if no locks were acquired in the meantime, shouldnt try again - if (isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1000) return locks > 0; - // retries are not allowed or we tried to many times, report error - if (!retryAttempts || retries >= retryAttempts) throw errOrCloseEvent; - // throw non-retryable connection problems - if (!shouldRetry(errOrCloseEvent)) throw errOrCloseEvent; - // @deprecated throw fatal connection problems immediately - if (isFatalConnectionProblem === null || isFatalConnectionProblem === void 0 ? void 0 : isFatalConnectionProblem(errOrCloseEvent)) throw errOrCloseEvent; - // looks good, start retrying - return retrying = true; - } - // in non-lazy (hot?) mode always hold one connection lock to persist the socket - if (!lazy) { - (async () => { - locks++; - for (;;) { - try { - const [,, throwOnClose] = await connect(); - await throwOnClose; // will always throw because releaser is not used - } catch (errOrCloseEvent) { - try { - if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; - } catch (errOrCloseEvent) { - // report thrown error, no further retries - return onNonLazyError === null || onNonLazyError === void 0 ? void 0 : onNonLazyError(errOrCloseEvent); - } + throw this.unexpected(token); } } - })(); + return this.parseVariable(); + default: + throw this.unexpected(); } - return { - on: emitter.on, - subscribe(payload, sink) { - const id = generateID(payload); - let done = false, - errored = false, - releaser = () => { - // for handling completions before connect - locks--; - done = true; - }; - (async () => { - locks++; - for (;;) { - try { - const [socket, release, waitForReleaseOrThrowOnClose] = await connect(); - // if done while waiting for connect, release the connection lock right away - if (done) return release(); - const unlisten = emitter.onMessage(id, message => { - switch (message.type) { - case _common.MessageType.Next: - { - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- payload will fit type - sink.next(message.payload); - return; - } - case _common.MessageType.Error: - { - errored = true, done = true; - sink.error(message.payload); - releaser(); - return; - } - case _common.MessageType.Complete: - { - done = true; - releaser(); // release completes the sink - return; - } - } - }); - socket.send((0, _common.stringifyMessage)({ - id, - type: _common.MessageType.Subscribe, - payload - }, replacer)); - releaser = () => { - if (!done && socket.readyState === WebSocketImpl.OPEN) - // if not completed already and socket is open, send complete message to server on release - socket.send((0, _common.stringifyMessage)({ - id, - type: _common.MessageType.Complete - }, replacer)); - locks--; - done = true; - release(); - }; - // either the releaser will be called, connection completed and - // the promise resolved or the socket closed and the promise rejected. - // whatever happens though, we want to stop listening for messages - await waitForReleaseOrThrowOnClose.finally(unlisten); - return; // completed, shouldnt try again - } catch (errOrCloseEvent) { - if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return; - } - } - })().then(() => { - // delivering either an error or a complete terminates the sequence - if (!errored) sink.complete(); - }) // resolves on release or normal closure - .catch(err => { - sink.error(err); - }); // rejects on close events and errors - return () => { - // dispose only of active subscriptions - if (!done) releaser(); - }; - }, - iterate(request) { - const pending = []; - const deferred = { - done: false, - error: null, - resolve: () => { - // noop - } - }; - const dispose = this.subscribe(request, { - next(val) { - pending.push(val); - deferred.resolve(); - }, - error(err) { - deferred.done = true; - deferred.error = err; - deferred.resolve(); - }, - complete() { - deferred.done = true; - deferred.resolve(); - } - }); - const iterator = function iterator() { - return __asyncGenerator(this, arguments, function* iterator_1() { - for (;;) { - if (!pending.length) { - // only wait if there are no pending messages available - yield __await(new Promise(resolve => deferred.resolve = resolve)); - } - // first flush - while (pending.length) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield yield __await(pending.shift()); - } - // then error - if (deferred.error) { - throw deferred.error; - } - // or complete - if (deferred.done) { - return yield __await(void 0); - } - } - }); - }(); - iterator.throw = async err => { - if (!deferred.done) { - deferred.done = true; - deferred.error = err; - deferred.resolve(); - } - return { - done: true, - value: undefined - }; - }; - iterator.return = async () => { - dispose(); - return { - done: true, - value: undefined - }; - }; - return iterator; - }, - async dispose() { - disposed = true; - if (connecting) { - // if there is a connection, close it - const [socket] = await connecting; - socket.close(1000, 'Normal Closure'); - } - }, - terminate() { - if (connecting) { - // only if there is a connection - emitter.emit('closed', { - code: 4499, - reason: 'Terminated', - wasClean: false - }); - } - } - }; } - function isLikeCloseEvent(val) { - return (0, _utils.isObject)(val) && 'code' in val && 'reason' in val; + parseConstValueLiteral() { + return this.parseValueLiteral(true); } - function isFatalInternalCloseCode(code) { - if ([1000, 1001, 1006, 1005, 1012, 1013, 1013 // Bad Gateway - ].includes(code)) return false; - // all other internal errors are fatal - return code >= 1000 && code <= 1999; - } - function isWebSocket(val) { - return typeof val === 'function' && 'constructor' in val && 'CLOSED' in val && 'CLOSING' in val && 'CONNECTING' in val && 'OPEN' in val; + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _tokenKind.TokenKind.BLOCK_STRING + }); } - - /***/ }), - - /***/ "../../../node_modules/graphql-ws/lib/common.mjs": - /*!*******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/common.mjs ***! - \*******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.MessageType = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.CloseCode = void 0; - exports.isMessage = isMessage; - exports.parseMessage = parseMessage; - exports.stringifyMessage = stringifyMessage; - exports.validateMessage = validateMessage; - var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); /** - * - * common - * + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] */ - + + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.LIST, + values: this.any(_tokenKind.TokenKind.BRACKET_L, item, _tokenKind.TokenKind.BRACKET_R) + }); + } /** - * The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). - * - * @category Common + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` */ - const GRAPHQL_TRANSPORT_WS_PROTOCOL = exports.GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws'; + + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.OBJECT, + fields: this.any(_tokenKind.TokenKind.BRACE_L, item, _tokenKind.TokenKind.BRACE_R) + }); + } /** - * The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws). - * - * @private + * ObjectField[Const] : Name : Value[?Const] */ - const DEPRECATED_GRAPHQL_WS_PROTOCOL = exports.DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws'; + + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst) + }); + } // Implements the parsing rules in the Directives section. + /** - * `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). - * - * @category Common + * Directives[Const] : Directive[?Const]+ */ - var CloseCode; - (function (CloseCode) { - CloseCode[CloseCode["InternalServerError"] = 4500] = "InternalServerError"; - CloseCode[CloseCode["InternalClientError"] = 4005] = "InternalClientError"; - CloseCode[CloseCode["BadRequest"] = 4400] = "BadRequest"; - CloseCode[CloseCode["BadResponse"] = 4004] = "BadResponse"; - /** Tried subscribing before connect ack */ - CloseCode[CloseCode["Unauthorized"] = 4401] = "Unauthorized"; - CloseCode[CloseCode["Forbidden"] = 4403] = "Forbidden"; - CloseCode[CloseCode["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable"; - CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout"; - CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout"; - /** Subscriber distinction is very important */ - CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists"; - CloseCode[CloseCode["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests"; - })(CloseCode || (exports.CloseCode = CloseCode = {})); + + parseDirectives(isConst) { + const directives = []; + while (this.peek(_tokenKind.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + return directives; + } + parseConstDirectives() { + return this.parseDirectives(true); + } /** - * Types of messages allowed to be sent by the client/server over the WS protocol. - * - * @category Common + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` */ - var MessageType; - (function (MessageType) { - MessageType["ConnectionInit"] = "connection_init"; - MessageType["ConnectionAck"] = "connection_ack"; - MessageType["Ping"] = "ping"; - MessageType["Pong"] = "pong"; - MessageType["Subscribe"] = "subscribe"; - MessageType["Next"] = "next"; - MessageType["Error"] = "error"; - MessageType["Complete"] = "complete"; - })(MessageType || (exports.MessageType = MessageType = {})); + + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.AT); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst) + }); + } // Implements the parsing rules in the Types section. + /** - * Validates the message against the GraphQL over WebSocket Protocol. - * - * Invalid messages will throw descriptive errors. - * - * @category Common + * Type : + * - NamedType + * - ListType + * - NonNullType */ - function validateMessage(val) { - if (!(0, _utils.isObject)(val)) { - throw new Error(`Message is expected to be an object, but got ${(0, _utils.extendedTypeof)(val)}`); - } - if (!val.type) { - throw new Error(`Message is missing the 'type' property`); - } - if (typeof val.type !== 'string') { - throw new Error(`Message is expects the 'type' property to be a string, but got ${(0, _utils.extendedTypeof)(val.type)}`); + + parseTypeReference() { + const start = this._lexer.token; + let type; + if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(_tokenKind.TokenKind.BRACKET_R); + type = this.node(start, { + kind: _kinds.Kind.LIST_TYPE, + type: innerType + }); + } else { + type = this.parseNamedType(); } - switch (val.type) { - case MessageType.ConnectionInit: - case MessageType.ConnectionAck: - case MessageType.Ping: - case MessageType.Pong: - { - if (val.payload != null && !(0, _utils.isObject)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${val.payload}"`); - } - break; - } - case MessageType.Subscribe: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); - } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); - } - if (!(0, _utils.isObject)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); - } - if (typeof val.payload.query !== 'string') { - throw new Error(`"${val.type}" message payload expects the 'query' property to be a string, but got ${(0, _utils.extendedTypeof)(val.payload.query)}`); - } - if (val.payload.variables != null && !(0, _utils.isObject)(val.payload.variables)) { - throw new Error(`"${val.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.variables)}`); - } - if (val.payload.operationName != null && (0, _utils.extendedTypeof)(val.payload.operationName) !== 'string') { - throw new Error(`"${val.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.operationName)}`); - } - if (val.payload.extensions != null && !(0, _utils.isObject)(val.payload.extensions)) { - throw new Error(`"${val.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${(0, _utils.extendedTypeof)(val.payload.extensions)}`); - } - break; - } - case MessageType.Next: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); - } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); - } - if (!(0, _utils.isObject)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${(0, _utils.extendedTypeof)(val.payload)}`); - } - break; - } - case MessageType.Error: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); - } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); - } - if (!(0, _utils.areGraphQLErrors)(val.payload)) { - throw new Error(`"${val.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(val.payload)}`); - } - break; - } - case MessageType.Complete: - { - if (typeof val.id !== 'string') { - throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${(0, _utils.extendedTypeof)(val.id)}`); - } - if (!val.id) { - throw new Error(`"${val.type}" message requires a non-empty 'id' property`); - } - break; - } - default: - throw new Error(`Invalid message 'type' property "${val.type}"`); + if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { + return this.node(start, { + kind: _kinds.Kind.NON_NULL_TYPE, + type + }); } - return val; + return type; } /** - * Checks if the provided value is a valid GraphQL over WebSocket message. - * - * @deprecated Use `validateMessage` instead. - * - * @category Common + * NamedType : Name */ - function isMessage(val) { - try { - validateMessage(val); - return true; - } catch (_a) { - return false; - } + + parseNamedType() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.NAMED_TYPE, + name: this.parseName() + }); + } // Implements the parsing rules in the Type Definition section. + + peekDescription() { + return this.peek(_tokenKind.TokenKind.STRING) || this.peek(_tokenKind.TokenKind.BLOCK_STRING); } /** - * Parses the raw websocket message data to a valid message. - * - * @category Common + * Description : StringValue */ - function parseMessage(data, reviver) { - return validateMessage(typeof data === 'string' ? JSON.parse(data, reviver) : data); + + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } } /** - * Stringifies a valid message ready to be sent through the socket. - * - * @category Common + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` */ - function stringifyMessage(msg, replacer) { - validateMessage(msg); - return JSON.stringify(msg, replacer); - } - - /***/ }), - - /***/ "../../../node_modules/graphql-ws/lib/index.js": - /*!*****************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/index.js ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); - } : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - var __exportStar = void 0 && (void 0).__exportStar || function (m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); - }; - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - __exportStar(__webpack_require__(/*! ./client */ "../../../node_modules/graphql-ws/lib/client.mjs"), exports); - __exportStar(__webpack_require__(/*! ./server */ "../../../node_modules/graphql-ws/lib/server.mjs"), exports); - __exportStar(__webpack_require__(/*! ./common */ "../../../node_modules/graphql-ws/lib/common.mjs"), exports); - - /***/ }), - - /***/ "../../../node_modules/graphql-ws/lib/server.mjs": - /*!*******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/server.mjs ***! - \*******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.handleProtocols = handleProtocols; - exports.makeServer = makeServer; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _common = __webpack_require__(/*! ./common.mjs */ "../../../node_modules/graphql-ws/lib/common.mjs"); - var _utils = __webpack_require__(/*! ./utils.mjs */ "../../../node_modules/graphql-ws/lib/utils.mjs"); + + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.many(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); + return this.node(start, { + kind: _kinds.Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes + }); + } /** - * - * server - * + * OperationTypeDefinition : OperationType : NamedType */ - var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function (v) { - return new Promise(function (resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } - }; + + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation, + type + }); + } /** - * Makes a Protocol complient WebSocket GraphQL server. The server - * is actually an API which is to be used with your favourite WebSocket - * server library! - * - * Read more about the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md). - * - * @category Server + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? */ - function makeServer(options) { - const { - schema, - context, - roots, - validate, - execute, - subscribe, - connectionInitWaitTimeout = 3000, - // 3 seconds - onConnect, - onDisconnect, - onClose, - onSubscribe, - onOperation, - onNext, - onError, - onComplete, - jsonMessageReviver: reviver, - jsonMessageReplacer: replacer - } = options; - return { - opened(socket, extra) { - const ctx = { - connectionInitReceived: false, - acknowledged: false, - subscriptions: {}, - extra - }; - if (socket.protocol !== _common.GRAPHQL_TRANSPORT_WS_PROTOCOL) { - socket.close(_common.CloseCode.SubprotocolNotAcceptable, 'Subprotocol not acceptable'); - return async (code, reason) => { - /* nothing was set up, just notify the closure */ - await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); - }; - } - // kick the client off (close socket) if the connection has - // not been initialised after the specified wait timeout - const connectionInitWait = connectionInitWaitTimeout > 0 && isFinite(connectionInitWaitTimeout) ? setTimeout(() => { - if (!ctx.connectionInitReceived) socket.close(_common.CloseCode.ConnectionInitialisationTimeout, 'Connection initialisation timeout'); - }, connectionInitWaitTimeout) : null; - socket.onMessage(async function onMessage(data) { - var _a, e_1, _b, _c; - var _d; - let message; - try { - message = (0, _common.parseMessage)(data, reviver); - } catch (err) { - return socket.close(_common.CloseCode.BadRequest, 'Invalid message received'); - } - switch (message.type) { - case _common.MessageType.ConnectionInit: - { - if (ctx.connectionInitReceived) return socket.close(_common.CloseCode.TooManyInitialisationRequests, 'Too many initialisation requests'); - // @ts-expect-error: I can write - ctx.connectionInitReceived = true; - if ((0, _utils.isObject)(message.payload)) - // @ts-expect-error: I can write - ctx.connectionParams = message.payload; - const permittedOrPayload = await (onConnect === null || onConnect === void 0 ? void 0 : onConnect(ctx)); - if (permittedOrPayload === false) return socket.close(_common.CloseCode.Forbidden, 'Forbidden'); - await socket.send((0, _common.stringifyMessage)((0, _utils.isObject)(permittedOrPayload) ? { - type: _common.MessageType.ConnectionAck, - payload: permittedOrPayload - } : { - type: _common.MessageType.ConnectionAck - // payload is completely absent if not provided - }, replacer)); - // @ts-expect-error: I can write - ctx.acknowledged = true; - return; - } - case _common.MessageType.Ping: - { - if (socket.onPing) - // if the onPing listener is registered, automatic pong is disabled - return await socket.onPing(message.payload); - await socket.send((0, _common.stringifyMessage)(message.payload ? { - type: _common.MessageType.Pong, - payload: message.payload - } : { - type: _common.MessageType.Pong - // payload is completely absent if not provided - })); - return; - } - case _common.MessageType.Pong: - return await ((_d = socket.onPong) === null || _d === void 0 ? void 0 : _d.call(socket, message.payload)); - case _common.MessageType.Subscribe: - { - if (!ctx.acknowledged) return socket.close(_common.CloseCode.Unauthorized, 'Unauthorized'); - const { - id, - payload - } = message; - if (id in ctx.subscriptions) return socket.close(_common.CloseCode.SubscriberAlreadyExists, `Subscriber for ${id} already exists`); - // if this turns out to be a streaming operation, the subscription value - // will change to an `AsyncIterable`, otherwise it will stay as is - ctx.subscriptions[id] = null; - const emit = { - next: async (result, args) => { - let nextMessage = { - id, - type: _common.MessageType.Next, - payload: result - }; - const maybeResult = await (onNext === null || onNext === void 0 ? void 0 : onNext(ctx, nextMessage, args, result)); - if (maybeResult) nextMessage = Object.assign(Object.assign({}, nextMessage), { - payload: maybeResult - }); - await socket.send((0, _common.stringifyMessage)(nextMessage, replacer)); - }, - error: async errors => { - let errorMessage = { - id, - type: _common.MessageType.Error, - payload: errors - }; - const maybeErrors = await (onError === null || onError === void 0 ? void 0 : onError(ctx, errorMessage, errors)); - if (maybeErrors) errorMessage = Object.assign(Object.assign({}, errorMessage), { - payload: maybeErrors - }); - await socket.send((0, _common.stringifyMessage)(errorMessage, replacer)); - }, - complete: async notifyClient => { - const completeMessage = { - id, - type: _common.MessageType.Complete - }; - await (onComplete === null || onComplete === void 0 ? void 0 : onComplete(ctx, completeMessage)); - if (notifyClient) await socket.send((0, _common.stringifyMessage)(completeMessage, replacer)); - } - }; - try { - let execArgs; - const maybeExecArgsOrErrors = await (onSubscribe === null || onSubscribe === void 0 ? void 0 : onSubscribe(ctx, message)); - if (maybeExecArgsOrErrors) { - if ((0, _utils.areGraphQLErrors)(maybeExecArgsOrErrors)) return await emit.error(maybeExecArgsOrErrors);else if (Array.isArray(maybeExecArgsOrErrors)) throw new Error('Invalid return value from onSubscribe hook, expected an array of GraphQLError objects'); - // not errors, is exec args - execArgs = maybeExecArgsOrErrors; - } else { - // you either provide a schema dynamically through - // `onSubscribe` or you set one up during the server setup - if (!schema) throw new Error('The GraphQL schema is not provided'); - const args = { - operationName: payload.operationName, - document: (0, _graphql.parse)(payload.query), - variableValues: payload.variables - }; - execArgs = Object.assign(Object.assign({}, args), { - schema: typeof schema === 'function' ? await schema(ctx, message, args) : schema - }); - const validationErrors = (validate !== null && validate !== void 0 ? validate : _graphql.validate)(execArgs.schema, execArgs.document); - if (validationErrors.length > 0) return await emit.error(validationErrors); - } - const operationAST = (0, _graphql.getOperationAST)(execArgs.document, execArgs.operationName); - if (!operationAST) return await emit.error([new _graphql.GraphQLError('Unable to identify operation')]); - // if `onSubscribe` didnt specify a rootValue, inject one - if (!('rootValue' in execArgs)) execArgs.rootValue = roots === null || roots === void 0 ? void 0 : roots[operationAST.operation]; - // if `onSubscribe` didn't specify a context, inject one - if (!('contextValue' in execArgs)) execArgs.contextValue = typeof context === 'function' ? await context(ctx, message, execArgs) : context; - // the execution arguments have been prepared - // perform the operation and act accordingly - let operationResult; - if (operationAST.operation === 'subscription') operationResult = await (subscribe !== null && subscribe !== void 0 ? subscribe : _graphql.subscribe)(execArgs); - // operation === 'query' || 'mutation' - else operationResult = await (execute !== null && execute !== void 0 ? execute : _graphql.execute)(execArgs); - const maybeResult = await (onOperation === null || onOperation === void 0 ? void 0 : onOperation(ctx, message, execArgs, operationResult)); - if (maybeResult) operationResult = maybeResult; - if ((0, _utils.isAsyncIterable)(operationResult)) { - /** multiple emitted results */ - if (!(id in ctx.subscriptions)) { - // subscription was completed/canceled before the operation settled - if ((0, _utils.isAsyncGenerator)(operationResult)) operationResult.return(undefined); - } else { - ctx.subscriptions[id] = operationResult; - try { - for (var _e = true, operationResult_1 = __asyncValues(operationResult), operationResult_1_1; operationResult_1_1 = await operationResult_1.next(), _a = operationResult_1_1.done, !_a; _e = true) { - _c = operationResult_1_1.value; - _e = false; - const result = _c; - await emit.next(result, execArgs); - } - } catch (e_1_1) { - e_1 = { - error: e_1_1 - }; - } finally { - try { - if (!_e && !_a && (_b = operationResult_1.return)) await _b.call(operationResult_1); - } finally { - if (e_1) throw e_1.error; - } - } - } - } else { - /** single emitted result */ - // if the client completed the subscription before the single result - // became available, he effectively canceled it and no data should be sent - if (id in ctx.subscriptions) await emit.next(operationResult, execArgs); - } - // lack of subscription at this point indicates that the client - // completed the subscription, he doesnt need to be reminded - await emit.complete(id in ctx.subscriptions); - } finally { - // whatever happens to the subscription, we finally want to get rid of the reservation - delete ctx.subscriptions[id]; - } - return; - } - case _common.MessageType.Complete: - { - const subscription = ctx.subscriptions[message.id]; - delete ctx.subscriptions[message.id]; // deleting the subscription means no further activity should take place - if ((0, _utils.isAsyncGenerator)(subscription)) await subscription.return(undefined); - return; - } - default: - throw new Error(`Unexpected message of type ${message.type} received`); - } - }); - // wait for close, cleanup and the disconnect callback - return async (code, reason) => { - if (connectionInitWait) clearTimeout(connectionInitWait); - for (const sub of Object.values(ctx.subscriptions)) { - if ((0, _utils.isAsyncGenerator)(sub)) await sub.return(undefined); - } - if (ctx.acknowledged) await (onDisconnect === null || onDisconnect === void 0 ? void 0 : onDisconnect(ctx, code, reason)); - await (onClose === null || onClose === void 0 ? void 0 : onClose(ctx, code, reason)); - }; - } - }; + + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives + }); } /** - * Helper utility for choosing the "graphql-transport-ws" subprotocol from - * a set of WebSocket subprotocols. - * - * Accepts a set of already extracted WebSocket subprotocols or the raw - * Sec-WebSocket-Protocol header value. In either case, if the right - * protocol appears, it will be returned. - * - * By specification, the server should not provide a value with Sec-WebSocket-Protocol - * if it does not agree with client's subprotocols. The client has a responsibility - * to handle the connection afterwards. - * - * @category Server + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? */ - function handleProtocols(protocols) { - switch (true) { - case protocols instanceof Set && protocols.has(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): - case Array.isArray(protocols) && protocols.includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): - case typeof protocols === 'string' && protocols.split(',').map(p => p.trim()).includes(_common.GRAPHQL_TRANSPORT_WS_PROTOCOL): - return _common.GRAPHQL_TRANSPORT_WS_PROTOCOL; - default: - return false; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql-ws/lib/utils.mjs": - /*!******************************************************!*\ - !*** ../../../node_modules/graphql-ws/lib/utils.mjs ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.areGraphQLErrors = areGraphQLErrors; - exports.extendedTypeof = extendedTypeof; - exports.isAsyncGenerator = isAsyncGenerator; - exports.isAsyncIterable = isAsyncIterable; - exports.isObject = isObject; - exports.limitCloseReason = limitCloseReason; - /** @private */ - function extendedTypeof(val) { - if (val === null) { - return 'null'; - } - if (Array.isArray(val)) { - return 'array'; - } - return typeof val; + + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields + }); } - /** @private */ - function isObject(val) { - return extendedTypeof(val) === 'object'; + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + + parseImplementsInterfaces() { + return this.expectOptionalKeyword('implements') ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) : []; } - /** @private */ - function isAsyncIterable(val) { - return typeof Object(val)[Symbol.asyncIterator] === 'function'; + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + */ + + parseFieldsDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseFieldDefinition, _tokenKind.TokenKind.BRACE_R); } - /** @private */ - function isAsyncGenerator(val) { - return isObject(val) && typeof Object(val)[Symbol.asyncIterator] === 'function' && typeof val.return === 'function' - // for lazy ones, we only need the return anyway - // typeof val.throw === 'function' && - // typeof val.next === 'function' - ; + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives + }); } - /** @private */ - function areGraphQLErrors(obj) { - return Array.isArray(obj) && - // must be at least one error - obj.length > 0 && - // error has at least a message - obj.every(ob => 'message' in ob); + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + + parseArgumentDefs() { + return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseInputValueDef, _tokenKind.TokenKind.PAREN_R); } /** - * Limits the WebSocket close event reason to not exceed a length of one frame. - * Reference: https://datatracker.ietf.org/doc/html/rfc6455#section-5.2. - * - * @private + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? */ - function limitCloseReason(reason, whenTooLong) { - return reason.length < 124 ? reason : whenTooLong; + + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives + }); } - - /***/ }), - - /***/ "../../../node_modules/graphql/error/GraphQLError.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/error/GraphQLError.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.GraphQLError = void 0; - exports.formatError = formatError; - exports.printError = printError; - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _location = __webpack_require__(/*! ../language/location.mjs */ "../../../node_modules/graphql/language/location.mjs"); - var _printLocation = __webpack_require__(/*! ../language/printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); - function toNormalizedOptions(args) { - const firstArg = args[0]; - if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { - return { - nodes: firstArg, - source: args[1], - positions: args[2], - path: args[3], - originalError: args[4], - extensions: args[5] - }; - } - return firstArg; + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields + }); } /** - * A GraphQLError describes an Error found during the parse, validate, or - * execute phases of performing a GraphQL operation. In addition to a message - * and stack trace, it also includes information about the locations in a - * GraphQL document and/or execution result that correspond to the Error. + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? */ - - class GraphQLError extends Error { - /** - * An array of `{ line, column }` locations within the source GraphQL document - * which correspond to this error. - * - * Errors during validation often contain multiple locations, for example to - * point out two things with the same name. Errors during execution include a - * single location, the field which produced the error. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - - /** - * An array describing the JSON-path into the execution response which - * corresponds to this error. Only included for errors during execution. - * - * Enumerable, and appears in the result of JSON.stringify(). - */ - - /** - * An array of GraphQL AST Nodes corresponding to this error. - */ - - /** - * The source GraphQL document for the first location of this error. - * - * Note that if this Error represents more than one node, the source may not - * represent nodes after the first node. - */ - - /** - * An array of character offsets within the source GraphQL document - * which correspond to this error. - */ - - /** - * The original error thrown from a field resolver during execution. - */ - - /** - * Extension fields to add to the formatted error. - */ - - /** - * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. - */ - constructor(message, ...rawArgs) { - var _this$nodes, _nodeLocations$, _ref; - const { - nodes, - source, - positions, - path, - originalError, - extensions - } = toNormalizedOptions(rawArgs); - super(message); - this.name = 'GraphQLError'; - this.path = path !== null && path !== void 0 ? path : undefined; - this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes. - - this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); - const nodeLocations = undefinedIfEmpty((_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map(node => node.loc).filter(loc => loc != null)); // Compute locations in the source for the given nodes/positions. - - this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source; - this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => loc.start); - this.locations = positions && source ? positions.map(pos => (0, _location.getLocation)(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map(loc => (0, _location.getLocation)(loc.source, loc.start)); - const originalExtensions = (0, _isObjectLike.isObjectLike)(originalError === null || originalError === void 0 ? void 0 : originalError.extensions) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : undefined; - this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : Object.create(null); // Only properties prescribed by the spec should be enumerable. - // Keep the rest as non-enumerable. - - Object.defineProperties(this, { - message: { - writable: true, - enumerable: true - }, - name: { - enumerable: false - }, - nodes: { - enumerable: false - }, - source: { - enumerable: false - }, - positions: { - enumerable: false - }, - originalError: { - enumerable: false - } - }); // Include (non-enumerable) stack trace. - - /* c8 ignore start */ - // FIXME: https://github.com/graphql/graphql-js/issues/2317 - - if (originalError !== null && originalError !== void 0 && originalError.stack) { - Object.defineProperty(this, 'stack', { - value: originalError.stack, - writable: true, - configurable: true - }); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, GraphQLError); - } else { - Object.defineProperty(this, 'stack', { - value: Error().stack, - writable: true, - configurable: true - }); - } - /* c8 ignore stop */ - } - get [Symbol.toStringTag]() { - return 'GraphQLError'; - } - toString() { - let output = this.message; - if (this.nodes) { - for (const node of this.nodes) { - if (node.loc) { - output += '\n\n' + (0, _printLocation.printLocation)(node.loc); - } - } - } else if (this.source && this.locations) { - for (const location of this.locations) { - output += '\n\n' + (0, _printLocation.printSourceLocation)(this.source, location); - } - } - return output; - } - toJSON() { - const formattedError = { - message: this.message - }; - if (this.locations != null) { - formattedError.locations = this.locations; - } - if (this.path != null) { - formattedError.path = this.path; - } - if (this.extensions != null && Object.keys(this.extensions).length > 0) { - formattedError.extensions = this.extensions; - } - return formattedError; - } + + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types + }); } - exports.GraphQLError = GraphQLError; - function undefinedIfEmpty(array) { - return array === undefined || array.length === 0 ? undefined : array; + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + + parseUnionMemberTypes() { + return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) : []; } /** - * See: https://spec.graphql.org/draft/#sec-Errors + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? */ - + + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values + }); + } /** - * Prints a GraphQLError to a string, representing useful location information - * about the error's position in the source. - * - * @deprecated Please use `error.toString` instead. Will be removed in v17 + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` */ - function printError(error) { - return error.toString(); + + parseEnumValuesDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseEnumValueDefinition, _tokenKind.TokenKind.BRACE_R); } /** - * Given a GraphQLError, format it according to the rules described by the - * Response Format, Errors section of the GraphQL Specification. - * - * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + * EnumValueDefinition : Description? EnumValue Directives[Const]? */ - - function formatError(error) { - return error.toJSON(); + + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives + }); } - - /***/ }), - - /***/ "../../../node_modules/graphql/error/index.mjs": - /*!*****************************************************!*\ - !*** ../../../node_modules/graphql/error/index.mjs ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "GraphQLError", ({ - enumerable: true, - get: function () { - return _GraphQLError.GraphQLError; - } - })); - Object.defineProperty(exports, "formatError", ({ - enumerable: true, - get: function () { - return _GraphQLError.formatError; - } - })); - Object.defineProperty(exports, "locatedError", ({ - enumerable: true, - get: function () { - return _locatedError.locatedError; + /** + * EnumValue : Name but not `true`, `false` or `null` + */ + + parseEnumValueName() { + if (this._lexer.token.value === 'true' || this._lexer.token.value === 'false' || this._lexer.token.value === 'null') { + throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, `${getTokenDesc(this._lexer.token)} is reserved and cannot be used for an enum value.`); } - })); - Object.defineProperty(exports, "printError", ({ - enumerable: true, - get: function () { - return _GraphQLError.printError; - } - })); - Object.defineProperty(exports, "syntaxError", ({ - enumerable: true, - get: function () { - return _syntaxError.syntaxError; - } - })); - var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _syntaxError = __webpack_require__(/*! ./syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); - var _locatedError = __webpack_require__(/*! ./locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/error/locatedError.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/error/locatedError.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.locatedError = locatedError; - var _toError = __webpack_require__(/*! ../jsutils/toError.mjs */ "../../../node_modules/graphql/jsutils/toError.mjs"); - var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Given an arbitrary value, presumably thrown while attempting to execute a - * GraphQL operation, produce a new GraphQLError aware of the location in the - * document responsible for the original Error. - */ - - function locatedError(rawOriginalError, nodes, path) { - var _nodes; - const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. - - if (isLocatedGraphQLError(originalError)) { - return originalError; - } - return new _GraphQLError.GraphQLError(originalError.message, { - nodes: (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, - source: originalError.source, - positions: originalError.positions, - path, - originalError - }); - } - function isLocatedGraphQLError(error) { - return Array.isArray(error.path); + return this.parseName(); } - - /***/ }), - - /***/ "../../../node_modules/graphql/error/syntaxError.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/error/syntaxError.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.syntaxError = syntaxError; - var _GraphQLError = __webpack_require__(/*! ./GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); /** - * Produces a GraphQLError representing a syntax error, containing useful - * descriptive information about the syntax error's position in the source. + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? */ - - function syntaxError(source, position, description) { - return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { - source, - positions: [position] + + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields }); } - - /***/ }), - - /***/ "../../../node_modules/graphql/execution/collectFields.mjs": - /*!*****************************************************************!*\ - !*** ../../../node_modules/graphql/execution/collectFields.mjs ***! - \*****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.collectFields = collectFields; - exports.collectSubfields = collectSubfields; - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); /** - * Given a selectionSet, collects all of the fields and returns them. - * - * CollectFields requires the "runtime type" of an object. For a field that - * returns an Interface or Union type, the "runtime type" will be the actual - * object type returned by that field. - * - * @internal + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` */ - - function collectFields(schema, fragments, variableValues, runtimeType, selectionSet) { - const fields = new Map(); - collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, new Set()); - return fields; + + parseInputFieldsDefinition() { + return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseInputValueDef, _tokenKind.TokenKind.BRACE_R); } /** - * Given an array of field nodes, collects all of the subfields of the passed - * in fields, and returns them at the end. + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension * - * CollectSubFields requires the "return type" of an object. For a field that - * returns an Interface or Union type, the "return type" will be the actual - * object type returned by that field. - * - * @internal + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition */ - - function collectSubfields(schema, fragments, variableValues, returnType, fieldNodes) { - const subFieldNodes = new Map(); - const visitedFragmentNames = new Set(); - for (const node of fieldNodes) { - if (node.selectionSet) { - collectFieldsImpl(schema, fragments, variableValues, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); + + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + case 'scalar': + return this.parseScalarTypeExtension(); + case 'type': + return this.parseObjectTypeExtension(); + case 'interface': + return this.parseInterfaceTypeExtension(); + case 'union': + return this.parseUnionTypeExtension(); + case 'enum': + return this.parseEnumTypeExtension(); + case 'input': + return this.parseInputObjectTypeExtension(); } } - return subFieldNodes; + throw this.unexpected(keywordToken); } - function collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, visitedFragmentNames) { - for (const selection of selectionSet.selections) { - switch (selection.kind) { - case _kinds.Kind.FIELD: - { - if (!shouldIncludeNode(variableValues, selection)) { - continue; - } - const name = getFieldEntryKey(selection); - const fieldList = fields.get(name); - if (fieldList !== undefined) { - fieldList.push(selection); - } else { - fields.set(name, [selection]); - } - break; - } - case _kinds.Kind.INLINE_FRAGMENT: - { - if (!shouldIncludeNode(variableValues, selection) || !doesFragmentConditionMatch(schema, selection, runtimeType)) { - continue; - } - collectFieldsImpl(schema, fragments, variableValues, runtimeType, selection.selectionSet, fields, visitedFragmentNames); - break; - } - case _kinds.Kind.FRAGMENT_SPREAD: - { - const fragName = selection.name.value; - if (visitedFragmentNames.has(fragName) || !shouldIncludeNode(variableValues, selection)) { - continue; - } - visitedFragmentNames.add(fragName); - const fragment = fragments[fragName]; - if (!fragment || !doesFragmentConditionMatch(schema, fragment, runtimeType)) { - continue; - } - collectFieldsImpl(schema, fragments, variableValues, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); - break; - } - } - } + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + */ + + parseSchemaExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives, + operationTypes + }); } /** - * Determines if a field should be included based on the `@include` and `@skip` - * directives, where `@skip` has higher precedence than `@include`. + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] */ - - function shouldIncludeNode(variableValues, node) { - const skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, variableValues); - if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { - return false; - } - const include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, variableValues); - if ((include === null || include === void 0 ? void 0 : include.if) === false) { - return false; - } - return true; + + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + if (directives.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name, + directives + }); } /** - * Determines if a fragment is applicable to the given type. + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces */ - - function doesFragmentConditionMatch(schema, fragment, type) { - const typeConditionNode = fragment.typeCondition; - if (!typeConditionNode) { - return true; - } - const conditionalType = (0, _typeFromAST.typeFromAST)(schema, typeConditionNode); - if (conditionalType === type) { - return true; - } - if ((0, _definition.isAbstractType)(conditionalType)) { - return schema.isSubType(conditionalType, type); - } - return false; + + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields + }); } /** - * Implements the logic to compute the key of a given field's entry + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces */ - - function getFieldEntryKey(node) { - return node.alias ? node.alias.value : node.name.value; + + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields + }); } - - /***/ }), - - /***/ "../../../node_modules/graphql/execution/execute.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/execution/execute.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.assertValidExecutionArguments = assertValidExecutionArguments; - exports.buildExecutionContext = buildExecutionContext; - exports.buildResolveInfo = buildResolveInfo; - exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; - exports.execute = execute; - exports.executeSync = executeSync; - exports.getFieldDef = getFieldDef; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _isPromise = __webpack_require__(/*! ../jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); - var _memoize = __webpack_require__(/*! ../jsutils/memoize3.mjs */ "../../../node_modules/graphql/jsutils/memoize3.mjs"); - var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); - var _promiseForObject = __webpack_require__(/*! ../jsutils/promiseForObject.mjs */ "../../../node_modules/graphql/jsutils/promiseForObject.mjs"); - var _promiseReduce = __webpack_require__(/*! ../jsutils/promiseReduce.mjs */ "../../../node_modules/graphql/jsutils/promiseReduce.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); - var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); - var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); - var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); /** - * A memoized collection of relevant subfields with regard to the return - * type. Memoizing ensures the subfields are not repeatedly calculated, which - * saves overhead when resolving lists of values. + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] */ - - const collectSubfields = (0, _memoize.memoize3)((exeContext, returnType, fieldNodes) => (0, _collectFields.collectSubfields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, returnType, fieldNodes)); + + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name, + directives, + types + }); + } /** - * Terminology - * - * "Definitions" are the generic name for top-level statements in the document. - * Examples of this include: - * 1) Operations (such as a query) - * 2) Fragments - * - * "Operations" are a generic name for requests in the document. - * Examples of this include: - * 1) query, - * 2) mutation - * - * "Selections" are the definitions that can appear legally and at - * single level of the query. These include: - * 1) field references e.g `a` - * 2) fragment "spreads" e.g. `...c` - * 3) inline fragment "spreads" e.g. `...on Type { a }` + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] */ - + + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values + }); + } /** - * Data that must be available at all points during query execution. - * - * Namely, schema of the type system that is currently executing, - * and the fragments defined in the query document + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] */ - + + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields + }); + } /** - * Implements the "Executing requests" section of the GraphQL specification. - * - * Returns either a synchronous ExecutionResult (if all encountered resolvers - * are synchronous), or a Promise of an ExecutionResult that will eventually be - * resolved and never rejected. - * - * If the arguments to this function do not result in a legal execution context, - * a GraphQLError will be thrown immediately explaining the invalid input. + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` */ - function execute(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); - const { - schema, - document, - variableValues, - rootValue - } = args; // If arguments are missing or incorrect, throw an error. - - assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, - // a "Response" with only errors is returned. - - const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. - - if (!('schema' in exeContext)) { - return { - errors: exeContext - }; - } // Return a Promise that will eventually resolve to the data described by - // The "Response" section of the GraphQL specification. - // - // If errors are encountered while executing a GraphQL field, only that - // field and its descendants will be omitted, and sibling fields will still - // be executed. An execution which encounters errors will still result in a - // resolved Promise. - // - // Errors from sub-fields of a NonNull type may propagate to the top level, - // at which point we still log the error and null the parent field, which - // in this case is the entire response. - - try { - const { - operation - } = exeContext; - const result = executeOperation(exeContext, operation, rootValue); - if ((0, _isPromise.isPromise)(result)) { - return result.then(data => buildResponse(data, exeContext.errors), error => { - exeContext.errors.push(error); - return buildResponse(null, exeContext.errors); - }); - } - return buildResponse(result, exeContext.errors); - } catch (error) { - exeContext.errors.push(error); - return buildResponse(null, exeContext.errors); - } + + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + repeatable, + locations + }); } /** - * Also implements the "Executing requests" section of the GraphQL specification. - * However, it guarantees to complete synchronously (or throw an error) assuming - * that all field resolvers are also synchronous. + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation */ - - function executeSync(args) { - const result = execute(args); // Assert that the execution was synchronous. - - if ((0, _isPromise.isPromise)(result)) { - throw new Error('GraphQL execution failed to complete synchronously.'); - } - return result; + + parseDirectiveLocations() { + return this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseDirectiveLocation); } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); + if (Object.prototype.hasOwnProperty.call(_directiveLocation.DirectiveLocation, name.value)) { + return name; + } + throw this.unexpected(start); + } // Core parsing utility functions + /** - * Given a completed execution context and data, build the `{ errors, data }` - * response defined by the "Response" section of the GraphQL specification. + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. */ - - function buildResponse(data, errors) { - return errors.length === 0 ? { - data - } : { - errors, - data - }; + + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new _ast.Location(startToken, this._lexer.lastToken, this._lexer.source); + } + return node; } /** - * Essential assertions before executing to provide developer feedback for - * improper use of the GraphQL library. - * - * @internal + * Determines if the next token is of a given kind */ - - function assertValidExecutionArguments(schema, document, rawVariableValues) { - document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. - - (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. - - rawVariableValues == null || (0, _isObjectLike.isObjectLike)(rawVariableValues) || (0, _devAssert.devAssert)(false, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); + + peek(kind) { + return this._lexer.token.kind === kind; } /** - * Constructs a ExecutionContext object from the arguments passed to - * execute, which we will pass throughout the other execution methods. - * - * Throws a GraphQLError if a valid execution context cannot be created. - * - * @internal + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. */ - - function buildExecutionContext(args) { - var _definition$name, _operation$variableDe; - const { - schema, - document, - rootValue, - contextValue, - variableValues: rawVariableValues, - operationName, - fieldResolver, - typeResolver, - subscribeFieldResolver - } = args; - let operation; - const fragments = Object.create(null); - for (const definition of document.definitions) { - switch (definition.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - if (operationName == null) { - if (operation !== undefined) { - return [new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')]; - } - operation = definition; - } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { - operation = definition; - } - break; - case _kinds.Kind.FRAGMENT_DEFINITION: - fragments[definition.name.value] = definition; - break; - default: // ignore non-executable definitions - } - } - if (!operation) { - if (operationName != null) { - return [new _GraphQLError.GraphQLError(`Unknown operation named "${operationName}".`)]; - } - return [new _GraphQLError.GraphQLError('Must provide an operation.')]; - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : []; - const coercedVariableValues = (0, _values.getVariableValues)(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, { - maxErrors: 50 - }); - if (coercedVariableValues.errors) { - return coercedVariableValues.errors; + + expectToken(kind) { + const token = this._lexer.token; + if (token.kind === kind) { + this.advanceLexer(); + return token; } - return { - schema, - fragments, - rootValue, - contextValue, - operation, - variableValues: coercedVariableValues.coerced, - fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver, - typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver, - subscribeFieldResolver: subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 ? subscribeFieldResolver : defaultFieldResolver, - errors: [] - }; + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`); } /** - * Implements the "Executing operations" section of the spec. + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". */ - - function executeOperation(exeContext, operation, rootValue) { - const rootType = exeContext.schema.getRootType(operation.operation); - if (rootType == null) { - throw new _GraphQLError.GraphQLError(`Schema is not configured to execute ${operation.operation} operation.`, { - nodes: operation - }); + + expectOptionalToken(kind) { + const token = this._lexer.token; + if (token.kind === kind) { + this.advanceLexer(); + return true; } - const rootFields = (0, _collectFields.collectFields)(exeContext.schema, exeContext.fragments, exeContext.variableValues, rootType, operation.selectionSet); - const path = undefined; - switch (operation.operation) { - case _ast.OperationTypeNode.QUERY: - return executeFields(exeContext, rootType, rootValue, path, rootFields); - case _ast.OperationTypeNode.MUTATION: - return executeFieldsSerially(exeContext, rootType, rootValue, path, rootFields); - case _ast.OperationTypeNode.SUBSCRIPTION: - // TODO: deprecate `subscribe` and move all logic here - // Temporary solution until we finish merging execute and subscribe together - return executeFields(exeContext, rootType, rootValue, path, rootFields); + return false; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + */ + + expectKeyword(value) { + const token = this._lexer.token; + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + } else { + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.`); } } /** - * Implements the "Executing selection sets" section of the spec - * for fields that must be executed serially. + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". */ - - function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { - return (0, _promiseReduce.promiseReduce)(fields.entries(), (results, [responseName, fieldNodes]) => { - const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); - const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); - if (result === undefined) { - return results; - } - if ((0, _isPromise.isPromise)(result)) { - return result.then(resolvedResult => { - results[responseName] = resolvedResult; - return results; - }); - } - results[responseName] = result; - return results; - }, Object.create(null)); + + expectOptionalKeyword(value) { + const token = this._lexer.token; + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + return true; + } + return false; } /** - * Implements the "Executing selection sets" section of the spec - * for fields that may be executed in parallel. + * Helper function for creating an error when an unexpected lexed token is encountered. */ - - function executeFields(exeContext, parentType, sourceValue, path, fields) { - const results = Object.create(null); - let containsPromise = false; - try { - for (const [responseName, fieldNodes] of fields.entries()) { - const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); - const result = executeField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); - if (result !== undefined) { - results[responseName] = result; - if ((0, _isPromise.isPromise)(result)) { - containsPromise = true; - } - } - } - } catch (error) { - if (containsPromise) { - // Ensure that any promises returned by other fields are handled, as they may also reject. - return (0, _promiseForObject.promiseForObject)(results).finally(() => { - throw error; - }); - } - throw error; - } // If there are no promises, we can just return the object - - if (!containsPromise) { - return results; - } // Otherwise, results is a map from field name to the result of resolving that - // field, which is possibly a promise. Return a promise that will return this - // same map, but with any promises replaced with the values they resolved to. - - return (0, _promiseForObject.promiseForObject)(results); + + unexpected(atToken) { + const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.`); } /** - * Implements the "Executing fields" section of the spec - * In particular, this function figures out the value that the field returns by - * calling its resolve function, then calls completeValue to complete promises, - * serialize scalars, or execute the sub-selection-set for objects. + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. */ - - function executeField(exeContext, parentType, source, fieldNodes, path) { - var _fieldDef$resolve; - const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); - if (!fieldDef) { - return; - } - const returnType = fieldDef.type; - const resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver; - const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal or abrupt (error). - - try { - // Build a JS object of arguments from the field.arguments AST, using the - // variables scope to fulfill any variable references. - // TODO: find a way to memoize, in case this field is within a List type. - const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. - - const contextValue = exeContext.contextValue; - const result = resolveFn(source, args, contextValue, info); - let completed; - if ((0, _isPromise.isPromise)(result)) { - completed = result.then(resolved => completeValue(exeContext, returnType, fieldNodes, info, path, resolved)); - } else { - completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); - } - if ((0, _isPromise.isPromise)(completed)) { - // Note: we don't rely on a `catch` method, but we do expect "thenable" - // to take a second callback for the error case. - return completed.then(undefined, rawError => { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); - return handleFieldError(error, returnType, exeContext); - }); - } - return completed; - } catch (rawError) { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(path)); - return handleFieldError(error, returnType, exeContext); + + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); } + return nodes; } /** - * @internal - */ - - function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { - // The resolve function's optional fourth argument is a collection of - // information about the current execution state. - return { - fieldName: fieldDef.name, - fieldNodes, - returnType: fieldDef.type, - parentType, - path, - schema: exeContext.schema, - fragments: exeContext.fragments, - rootValue: exeContext.rootValue, - operation: exeContext.operation, - variableValues: exeContext.variableValues - }; - } - function handleFieldError(error, returnType, exeContext) { - // If the field type is non-nullable, then it is resolved without any - // protection from errors, however it still properly locates the error. - if ((0, _definition.isNonNullType)(returnType)) { - throw error; - } // Otherwise, error protection is applied, logging the error and resolving - // a null value for this field if one is encountered. - - exeContext.errors.push(error); - return null; - } - /** - * Implements the instructions for completeValue as defined in the - * "Value Completion" section of the spec. - * - * If the field type is Non-Null, then this recursively completes the value - * for the inner type. It throws a field error if that completion returns null, - * as per the "Nullability" section of the spec. - * - * If the field type is a List, then this recursively completes the value - * for the inner type on each item in the list. - * - * If the field type is a Scalar or Enum, ensures the completed value is a legal - * value of the type by calling the `serialize` method of GraphQL type - * definition. - * - * If the field is an abstract type, determine the runtime type of the value - * and then complete based on that type - * - * Otherwise, the field type expects a sub-selection set, and will complete the - * value by executing all sub-selections. + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. */ - - function completeValue(exeContext, returnType, fieldNodes, info, path, result) { - // If result is an Error, throw a located error. - if (result instanceof Error) { - throw result; - } // If field type is NonNull, complete for inner type, and throw field error - // if result is null. - - if ((0, _definition.isNonNullType)(returnType)) { - const completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); - if (completed === null) { - throw new Error(`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`); - } - return completed; - } // If result value is null or undefined then return null. - - if (result == null) { - return null; - } // If field type is List, complete each item in the list with the inner type - - if ((0, _definition.isListType)(returnType)) { - return completeListValue(exeContext, returnType, fieldNodes, info, path, result); - } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, - // returning null if serialization is not possible. - - if ((0, _definition.isLeafType)(returnType)) { - return completeLeafValue(returnType, result); - } // If field type is an abstract type, Interface or Union, determine the - // runtime Object type and complete for that type. - - if ((0, _definition.isAbstractType)(returnType)) { - return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); - } // If field type is Object, execute and complete all sub-selections. - - if ((0, _definition.isObjectType)(returnType)) { - return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; } - /* c8 ignore next 6 */ - // Not reachable, all possible output types have been considered. - - false || (0, _invariant.invariant)(false, 'Cannot complete value of unexpected output type: ' + (0, _inspect.inspect)(returnType)); - } - /** - * Complete a list value by completing each item in the list with the - * inner type - */ - - function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { - if (!(0, _isIterableObject.isIterableObject)(result)) { - throw new _GraphQLError.GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`); - } // This is specified as a simple map, however we're optimizing the path - // where the list contains no Promises by avoiding creating another Promise. - - const itemType = returnType.ofType; - let containsPromise = false; - const completedResults = Array.from(result, (item, index) => { - // No need to modify the info object containing the path, - // since from here on it is not ever accessed by resolver functions. - const itemPath = (0, _Path.addPath)(path, index, undefined); - try { - let completedItem; - if ((0, _isPromise.isPromise)(item)) { - completedItem = item.then(resolved => completeValue(exeContext, itemType, fieldNodes, info, itemPath, resolved)); - } else { - completedItem = completeValue(exeContext, itemType, fieldNodes, info, itemPath, item); - } - if ((0, _isPromise.isPromise)(completedItem)) { - containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" - // to take a second callback for the error case. - - return completedItem.then(undefined, rawError => { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); - return handleFieldError(error, itemType, exeContext); - }); - } - return completedItem; - } catch (rawError) { - const error = (0, _locatedError.locatedError)(rawError, fieldNodes, (0, _Path.pathToArray)(itemPath)); - return handleFieldError(error, itemType, exeContext); - } - }); - return containsPromise ? Promise.all(completedResults) : completedResults; + return []; } /** - * Complete a Scalar or Enum by serializing to a valid value, returning - * null if serialization is not possible. + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. */ - - function completeLeafValue(returnType, result) { - const serializedResult = returnType.serialize(result); - if (serializedResult == null) { - throw new Error(`Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, _inspect.inspect)(result)})\` to ` + `return non-nullable value, returned: ${(0, _inspect.inspect)(serializedResult)}`); - } - return serializedResult; + + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; } /** - * Complete a value of an abstract type by determining the runtime object type - * of that value, then complete the value for that type. + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. */ - - function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { - var _returnType$resolveTy; - const resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver; - const contextValue = exeContext.contextValue; - const runtimeType = resolveTypeFn(result, contextValue, info, returnType); - if ((0, _isPromise.isPromise)(runtimeType)) { - return runtimeType.then(resolvedRuntimeType => completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result)); - } - return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + return nodes; } - function ensureValidRuntimeType(runtimeTypeName, exeContext, returnType, fieldNodes, info, result) { - if (runtimeTypeName == null) { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, fieldNodes); - } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` - // TODO: remove in 17.0.0 release - - if ((0, _definition.isObjectType)(runtimeTypeName)) { - throw new _GraphQLError.GraphQLError('Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.'); - } - if (typeof runtimeTypeName !== 'string') { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + `value ${(0, _inspect.inspect)(result)}, received "${(0, _inspect.inspect)(runtimeTypeName)}".`); - } - const runtimeType = exeContext.schema.getType(runtimeTypeName); - if (runtimeType == null) { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, { - nodes: fieldNodes - }); - } - if (!(0, _definition.isObjectType)(runtimeType)) { - throw new _GraphQLError.GraphQLError(`Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, { - nodes: fieldNodes - }); - } - if (!exeContext.schema.isSubType(returnType, runtimeType)) { - throw new _GraphQLError.GraphQLError(`Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, { - nodes: fieldNodes - }); + advanceLexer() { + const { + maxTokens + } = this._options; + const token = this._lexer.advance(); + if (maxTokens !== undefined && token.kind !== _tokenKind.TokenKind.EOF) { + ++this._tokenCounter; + if (this._tokenCounter > maxTokens) { + throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Document contains more that ${maxTokens} tokens. Parsing aborted.`); + } + } + } +} +/** + * A helper function to describe a token as a string for debugging. + */ +exports.Parser = Parser; +function getTokenDesc(token) { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); +} +/** + * A helper function to describe a token kind as a string for debugging. + */ + +function getTokenKindDesc(kind) { + return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/predicates.mjs": +/*!*************************************************************!*\ + !*** ../../../node_modules/graphql/language/predicates.mjs ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isConstValueNode = isConstValueNode; +exports.isDefinitionNode = isDefinitionNode; +exports.isExecutableDefinitionNode = isExecutableDefinitionNode; +exports.isSelectionNode = isSelectionNode; +exports.isTypeDefinitionNode = isTypeDefinitionNode; +exports.isTypeExtensionNode = isTypeExtensionNode; +exports.isTypeNode = isTypeNode; +exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; +exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; +exports.isValueNode = isValueNode; +var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} +function isExecutableDefinitionNode(node) { + return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; +} +function isSelectionNode(node) { + return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; +} +function isValueNode(node) { + return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; +} +function isConstValueNode(node) { + return isValueNode(node) && (node.kind === _kinds.Kind.LIST ? node.values.some(isConstValueNode) : node.kind === _kinds.Kind.OBJECT ? node.fields.some(field => isConstValueNode(field.value)) : node.kind !== _kinds.Kind.VARIABLE); +} +function isTypeNode(node) { + return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; +} +function isTypeSystemDefinitionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; +} +function isTypeDefinitionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; +} +function isTypeSystemExtensionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} +function isTypeExtensionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/printLocation.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/language/printLocation.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.printLocation = printLocation; +exports.printSourceLocation = printSourceLocation; +var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); +/** + * Render a helpful description of the location in the GraphQL Source document. + */ +function printLocation(location) { + return printSourceLocation(location.source, (0, _location.getLocation)(location.source, location.start)); +} +/** + * Render a helpful description of the location in the GraphQL Source document. + */ + +function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = ''.padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + return locationStr + printPrefixedLines([[`${lineNum} |`, subLines[0]], ...subLines.slice(1, subLineIndex + 1).map(subLine => ['|', subLine]), ['|', '^'.padStart(subLineColumnNum)], ['|', subLines[subLineIndex + 1]]]); + } + return locationStr + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1} |`, lines[lineIndex - 1]], [`${lineNum} |`, locationLine], ['|', '^'.padStart(columnNum)], [`${lineNum + 1} |`, lines[lineIndex + 1]]]); +} +function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')).join('\n'); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/printString.mjs": +/*!**************************************************************!*\ + !*** ../../../node_modules/graphql/language/printString.mjs ***! + \**************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.printString = printString; +/** + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + */ +function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; +} // eslint-disable-next-line no-control-regex + +const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; +function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; +} // prettier-ignore + +const escapeSequences = ['\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007', '\\b', '\\t', '\\n', '\\u000B', '\\f', '\\r', '\\u000E', '\\u000F', '\\u0010', '\\u0011', '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019', '\\u001A', '\\u001B', '\\u001C', '\\u001D', '\\u001E', '\\u001F', '', '', '\\"', '', '', '', '', '', '', '', '', '', '', '', '', '', +// 2F +'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', +// 3F +'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', +// 4F +'', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', +// 5F +'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', +// 6F +'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\u007F', '\\u0080', '\\u0081', '\\u0082', '\\u0083', '\\u0084', '\\u0085', '\\u0086', '\\u0087', '\\u0088', '\\u0089', '\\u008A', '\\u008B', '\\u008C', '\\u008D', '\\u008E', '\\u008F', '\\u0090', '\\u0091', '\\u0092', '\\u0093', '\\u0094', '\\u0095', '\\u0096', '\\u0097', '\\u0098', '\\u0099', '\\u009A', '\\u009B', '\\u009C', '\\u009D', '\\u009E', '\\u009F']; + +/***/ }), + +/***/ "../../../node_modules/graphql/language/printer.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/language/printer.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.print = print; +var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); +var _printString = __webpack_require__(/*! ./printString.mjs */ "../../../node_modules/graphql/language/printString.mjs"); +var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ + +function print(ast) { + return (0, _visitor.visit)(ast, printDocASTReducer); +} +const MAX_LINE_LENGTH = 80; +const printDocASTReducer = { + Name: { + leave: node => node.value + }, + Variable: { + leave: node => '$' + node.name + }, + // Document + Document: { + leave: node => join(node.definitions, '\n\n') + }, + OperationDefinition: { + leave(node) { + const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + const prefix = join([node.operation, join([node.name, varDefs]), join(node.directives, ' ')], ' '); // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; } - return runtimeType; - } - /** - * Complete an Object value by executing all sub-selections. - */ - - function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { - // Collect sub-fields to execute to complete this value. - const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the - // current result. If isTypeOf returns false, then raise an error rather - // than continuing execution. - - if (returnType.isTypeOf) { - const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); - if ((0, _isPromise.isPromise)(isTypeOf)) { - return isTypeOf.then(resolvedIsTypeOf => { - if (!resolvedIsTypeOf) { - throw invalidReturnTypeError(returnType, result, fieldNodes); - } - return executeFields(exeContext, returnType, result, path, subFieldNodes); - }); - } - if (!isTypeOf) { - throw invalidReturnTypeError(returnType, result, fieldNodes); + }, + VariableDefinition: { + leave: ({ + variable, + type, + defaultValue, + directives + }) => variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')) + }, + SelectionSet: { + leave: ({ + selections + }) => block(selections) + }, + Field: { + leave({ + alias, + name, + arguments: args, + directives, + selectionSet + }) { + const prefix = wrap('', alias, ': ') + name; + let argsLine = prefix + wrap('(', join(args, ', '), ')'); + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); } + return join([argsLine, join(directives, ' '), selectionSet], ' '); } - return executeFields(exeContext, returnType, result, path, subFieldNodes); - } - function invalidReturnTypeError(returnType, result, fieldNodes) { - return new _GraphQLError.GraphQLError(`Expected value of type "${returnType.name}" but got: ${(0, _inspect.inspect)(result)}.`, { - nodes: fieldNodes - }); + }, + Argument: { + leave: ({ + name, + value + }) => name + ': ' + value + }, + // Fragments + FragmentSpread: { + leave: ({ + name, + directives + }) => '...' + name + wrap(' ', join(directives, ' ')) + }, + InlineFragment: { + leave: ({ + typeCondition, + directives, + selectionSet + }) => join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ') + }, + FragmentDefinition: { + leave: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet + } // Note: fragment variable definitions are experimental and may be changed + ) => + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + selectionSet + }, + // Value + IntValue: { + leave: ({ + value + }) => value + }, + FloatValue: { + leave: ({ + value + }) => value + }, + StringValue: { + leave: ({ + value, + block: isBlockString + }) => isBlockString ? (0, _blockString.printBlockString)(value) : (0, _printString.printString)(value) + }, + BooleanValue: { + leave: ({ + value + }) => value ? 'true' : 'false' + }, + NullValue: { + leave: () => 'null' + }, + EnumValue: { + leave: ({ + value + }) => value + }, + ListValue: { + leave: ({ + values + }) => '[' + join(values, ', ') + ']' + }, + ObjectValue: { + leave: ({ + fields + }) => '{' + join(fields, ', ') + '}' + }, + ObjectField: { + leave: ({ + name, + value + }) => name + ': ' + value + }, + // Directive + Directive: { + leave: ({ + name, + arguments: args + }) => '@' + name + wrap('(', join(args, ', '), ')') + }, + // Type + NamedType: { + leave: ({ + name + }) => name + }, + ListType: { + leave: ({ + type + }) => '[' + type + ']' + }, + NonNullType: { + leave: ({ + type + }) => type + '!' + }, + // Type System Definitions + SchemaDefinition: { + leave: ({ + description, + directives, + operationTypes + }) => wrap('', description, '\n') + join(['schema', join(directives, ' '), block(operationTypes)], ' ') + }, + OperationTypeDefinition: { + leave: ({ + operation, + type + }) => operation + ': ' + type + }, + ScalarTypeDefinition: { + leave: ({ + description, + name, + directives + }) => wrap('', description, '\n') + join(['scalar', name, join(directives, ' ')], ' ') + }, + ObjectTypeDefinition: { + leave: ({ + description, + name, + interfaces, + directives, + fields + }) => wrap('', description, '\n') + join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + FieldDefinition: { + leave: ({ + description, + name, + arguments: args, + type, + directives + }) => wrap('', description, '\n') + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' ')) + }, + InputValueDefinition: { + leave: ({ + description, + name, + type, + defaultValue, + directives + }) => wrap('', description, '\n') + join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ') + }, + InterfaceTypeDefinition: { + leave: ({ + description, + name, + interfaces, + directives, + fields + }) => wrap('', description, '\n') + join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + UnionTypeDefinition: { + leave: ({ + description, + name, + directives, + types + }) => wrap('', description, '\n') + join(['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') + }, + EnumTypeDefinition: { + leave: ({ + description, + name, + directives, + values + }) => wrap('', description, '\n') + join(['enum', name, join(directives, ' '), block(values)], ' ') + }, + EnumValueDefinition: { + leave: ({ + description, + name, + directives + }) => wrap('', description, '\n') + join([name, join(directives, ' ')], ' ') + }, + InputObjectTypeDefinition: { + leave: ({ + description, + name, + directives, + fields + }) => wrap('', description, '\n') + join(['input', name, join(directives, ' '), block(fields)], ' ') + }, + DirectiveDefinition: { + leave: ({ + description, + name, + arguments: args, + repeatable, + locations + }) => wrap('', description, '\n') + 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ') + }, + SchemaExtension: { + leave: ({ + directives, + operationTypes + }) => join(['extend schema', join(directives, ' '), block(operationTypes)], ' ') + }, + ScalarTypeExtension: { + leave: ({ + name, + directives + }) => join(['extend scalar', name, join(directives, ' ')], ' ') + }, + ObjectTypeExtension: { + leave: ({ + name, + interfaces, + directives, + fields + }) => join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + InterfaceTypeExtension: { + leave: ({ + name, + interfaces, + directives, + fields + }) => join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') + }, + UnionTypeExtension: { + leave: ({ + name, + directives, + types + }) => join(['extend union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') + }, + EnumTypeExtension: { + leave: ({ + name, + directives, + values + }) => join(['extend enum', name, join(directives, ' '), block(values)], ' ') + }, + InputObjectTypeExtension: { + leave: ({ + name, + directives, + fields + }) => join(['extend input', name, join(directives, ' '), block(fields)], ' ') + } +}; +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + +function join(maybeArray, separator = '') { + var _maybeArray$filter$jo; + return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(x => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : ''; +} +/** + * Given array, print each item on its own line, wrapped in an indented `{ }` block. + */ + +function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ + +function wrap(start, maybeString, end = '') { + return maybeString != null && maybeString !== '' ? start + maybeString + end : ''; +} +function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); +} +function hasMultilineItems(maybeArray) { + var _maybeArray$some; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + return (_maybeArray$some = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some(str => str.includes('\n'))) !== null && _maybeArray$some !== void 0 ? _maybeArray$some : false; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/source.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/language/source.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Source = void 0; +exports.isSource = isSource; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +class Source { + constructor(body, name = 'GraphQL request', locationOffset = { + line: 1, + column: 1 + }) { + typeof body === 'string' || (0, _devAssert.devAssert)(false, `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || (0, _devAssert.devAssert)(false, 'line in locationOffset is 1-indexed and must be positive.'); + this.locationOffset.column > 0 || (0, _devAssert.devAssert)(false, 'column in locationOffset is 1-indexed and must be positive.'); + } + get [Symbol.toStringTag]() { + return 'Source'; + } +} +/** + * Test if the given value is a Source object. + * + * @internal + */ +exports.Source = Source; +function isSource(source) { + return (0, _instanceOf.instanceOf)(source, Source); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/language/tokenKind.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/language/tokenKind.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TokenKind = void 0; +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind; +(function (TokenKind) { + TokenKind['SOF'] = ''; + TokenKind['EOF'] = ''; + TokenKind['BANG'] = '!'; + TokenKind['DOLLAR'] = '$'; + TokenKind['AMP'] = '&'; + TokenKind['PAREN_L'] = '('; + TokenKind['PAREN_R'] = ')'; + TokenKind['SPREAD'] = '...'; + TokenKind['COLON'] = ':'; + TokenKind['EQUALS'] = '='; + TokenKind['AT'] = '@'; + TokenKind['BRACKET_L'] = '['; + TokenKind['BRACKET_R'] = ']'; + TokenKind['BRACE_L'] = '{'; + TokenKind['PIPE'] = '|'; + TokenKind['BRACE_R'] = '}'; + TokenKind['NAME'] = 'Name'; + TokenKind['INT'] = 'Int'; + TokenKind['FLOAT'] = 'Float'; + TokenKind['STRING'] = 'String'; + TokenKind['BLOCK_STRING'] = 'BlockString'; + TokenKind['COMMENT'] = 'Comment'; +})(TokenKind || (exports.TokenKind = TokenKind = {})); + +/** + * The enum type representing the token kinds values. + * + * @deprecated Please use `TokenKind`. Will be remove in v17. + */ + +/***/ }), + +/***/ "../../../node_modules/graphql/language/visitor.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/language/visitor.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.BREAK = void 0; +exports.getEnterLeaveForKind = getEnterLeaveForKind; +exports.getVisitFn = getVisitFn; +exports.visit = visit; +exports.visitInParallel = visitInParallel; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +/** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ + +const BREAK = exports.BREAK = Object.freeze({}); +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * ```ts + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * ``` + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to three permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * ``` + * + * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * ``` + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * ```ts + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * ``` + */ + +function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { + const enterLeaveMap = new Map(); + for (const kind of Object.values(_kinds.Kind)) { + enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); } - /** - * If a resolveType function is not given, then a default resolve behavior is - * used which attempts two strategies: - * - * First, See if the provided value has a `__typename` field defined, if so, use - * that value as name of the resolved type. - * - * Otherwise, test each possible type for the abstract type by calling - * isTypeOf for the object being coerced, returning the first type that matches. - */ - - const defaultTypeResolver = function (value, contextValue, info, abstractType) { - // First, look for `__typename`. - if ((0, _isObjectLike.isObjectLike)(value) && typeof value.__typename === 'string') { - return value.__typename; - } // Otherwise, test each possible type. - - const possibleTypes = info.schema.getPossibleTypes(abstractType); - const promisedIsTypeOfResults = []; - for (let i = 0; i < possibleTypes.length; i++) { - const type = possibleTypes[i]; - if (type.isTypeOf) { - const isTypeOfResult = type.isTypeOf(value, contextValue, info); - if ((0, _isPromise.isPromise)(isTypeOfResult)) { - promisedIsTypeOfResults[i] = isTypeOfResult; - } else if (isTypeOfResult) { - return type.name; + /* eslint-disable no-undef-init */ + + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; + } + } + } else { + node = Object.defineProperties({}, Object.getOwnPropertyDescriptors(node)); + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } } } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent) { + key = inArray ? index : keys[index]; + node = parent[key]; + if (node === null || node === undefined) { + continue; + } + path.push(key); } - if (promisedIsTypeOfResults.length) { - return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { - for (let i = 0; i < isTypeOfResults.length; i++) { - if (isTypeOfResults[i]) { - return possibleTypes[i].name; + let result; + if (!Array.isArray(node)) { + var _enterLeaveMap$get, _enterLeaveMap$get2; + (0, _ast.isNode)(node) || (0, _devAssert.devAssert)(false, `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`); + const visitFn = isLeaving ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get === void 0 ? void 0 : _enterLeaveMap$get.leave : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get2 === void 0 ? void 0 : _enterLeaveMap$get2.enter; + result = visitFn === null || visitFn === void 0 ? void 0 : visitFn.call(visitor, node, key, parent, path, ancestors); + if (result === BREAK) { + break; + } + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if ((0, _ast.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; } } - }); - } - }; - /** - * If a resolve function is not given, then a default resolve behavior is used - * which takes the property of the source object of the same name as the field - * and returns it as the result, or if it's a function, returns the result - * of calling that function while passing along args and context value. - */ - exports.defaultTypeResolver = defaultTypeResolver; - const defaultFieldResolver = function (source, args, contextValue, info) { - // ensure source is a value for which property access is acceptable. - if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { - const property = source[info.fieldName]; - if (typeof property === 'function') { - return source[info.fieldName](args, contextValue, info); } - return property; } - }; - /** - * This method looks up the field on the given type definition. - * It has special casing for the three introspection fields, - * __schema, __type and __typename. __typename is special because - * it can always be queried as a field, even in situations where no - * other fields are allowed, like on a Union. __schema and __type - * could get automatically added to the query type, but that would - * require mutating type definitions, which would cause issues. - * - * @internal - */ - exports.defaultFieldResolver = defaultFieldResolver; - function getFieldDef(schema, parentType, fieldNode) { - const fieldName = fieldNode.name.value; - if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.SchemaMetaFieldDef; - } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.TypeMetaFieldDef; - } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { - return _introspection.TypeNameMetaFieldDef; - } - return parentType.getFields()[fieldName]; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/execution/index.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/execution/index.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "createSourceEventStream", ({ - enumerable: true, - get: function () { - return _subscribe.createSourceEventStream; + if (result === undefined && isEdited) { + edits.push([key, node]); } - })); - Object.defineProperty(exports, "defaultFieldResolver", ({ - enumerable: true, - get: function () { - return _execute.defaultFieldResolver; - } - })); - Object.defineProperty(exports, "defaultTypeResolver", ({ - enumerable: true, - get: function () { - return _execute.defaultTypeResolver; - } - })); - Object.defineProperty(exports, "execute", ({ - enumerable: true, - get: function () { - return _execute.execute; - } - })); - Object.defineProperty(exports, "executeSync", ({ - enumerable: true, - get: function () { - return _execute.executeSync; - } - })); - Object.defineProperty(exports, "getArgumentValues", ({ - enumerable: true, - get: function () { - return _values.getArgumentValues; - } - })); - Object.defineProperty(exports, "getDirectiveValues", ({ - enumerable: true, - get: function () { - return _values.getDirectiveValues; - } - })); - Object.defineProperty(exports, "getVariableValues", ({ - enumerable: true, - get: function () { - return _values.getVariableValues; - } - })); - Object.defineProperty(exports, "responsePathAsArray", ({ - enumerable: true, - get: function () { - return _Path.pathToArray; + if (isLeaving) { + path.pop(); + } else { + var _node$kind; + stack = { + inArray, + index, + keys, + edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : (_node$kind = visitorKeys[node.kind]) !== null && _node$kind !== void 0 ? _node$kind : []; + index = -1; + edits = []; + if (parent) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + if (edits.length !== 0) { + // New root + return edits[edits.length - 1][1]; + } + return root; +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + +function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); + for (const kind of Object.values(_kinds.Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + for (let i = 0; i < visitors.length; ++i) { + const { + enter, + leave + } = getEnterLeaveForKind(visitors[i], kind); + hasVisitor || (hasVisitor = enter != null || leave != null); + enterList[i] = enter; + leaveList[i] = leave; } - })); - Object.defineProperty(exports, "subscribe", ({ - enumerable: true, - get: function () { - return _subscribe.subscribe; + if (!hasVisitor) { + continue; } - })); - var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); - var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); - var _subscribe = __webpack_require__(/*! ./subscribe.mjs */ "../../../node_modules/graphql/execution/subscribe.mjs"); - var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs": - /*!********************************************************************!*\ - !*** ../../../node_modules/graphql/execution/mapAsyncIterator.mjs ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.mapAsyncIterator = mapAsyncIterator; - /** - * Given an AsyncIterable and a callback function, return an AsyncIterator - * which produces values mapped via calling the callback function. - */ - function mapAsyncIterator(iterable, callback) { - const iterator = iterable[Symbol.asyncIterator](); - async function mapResult(result) { - if (result.done) { - return result; - } - try { - return { - value: await callback(result.value), - done: false - }; - } catch (error) { - /* c8 ignore start */ - // FIXME: add test case - if (typeof iterator.return === 'function') { - try { - await iterator.return(); - } catch (_e) { - /* ignore error */ + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _enterList$i; + const result = (_enterList$i = enterList[i]) === null || _enterList$i === void 0 ? void 0 : _enterList$i.apply(visitors[i], args); + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } } } - throw error; - /* c8 ignore stop */ - } - } - return { - async next() { - return mapResult(await iterator.next()); }, - async return() { - // If iterator.return() does not exist, then type R must be undefined. - return typeof iterator.return === 'function' ? mapResult(await iterator.return()) : { - value: undefined, - done: true - }; - }, - async throw(error) { - if (typeof iterator.throw === 'function') { - return mapResult(await iterator.throw(error)); + leave(...args) { + const node = args[0]; + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _leaveList$i; + const result = (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 ? void 0 : _leaveList$i.apply(visitors[i], args); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } } - throw error; - }, - [Symbol.asyncIterator]() { - return this; } }; + mergedVisitor[kind] = mergedEnterLeave; } - - /***/ }), - - /***/ "../../../node_modules/graphql/execution/subscribe.mjs": - /*!*************************************************************!*\ - !*** ../../../node_modules/graphql/execution/subscribe.mjs ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.createSourceEventStream = createSourceEventStream; - exports.subscribe = subscribe; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _isAsyncIterable = __webpack_require__(/*! ../jsutils/isAsyncIterable.mjs */ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs"); - var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _locatedError = __webpack_require__(/*! ../error/locatedError.mjs */ "../../../node_modules/graphql/error/locatedError.mjs"); - var _collectFields = __webpack_require__(/*! ./collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); - var _execute = __webpack_require__(/*! ./execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); - var _mapAsyncIterator = __webpack_require__(/*! ./mapAsyncIterator.mjs */ "../../../node_modules/graphql/execution/mapAsyncIterator.mjs"); - var _values = __webpack_require__(/*! ./values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); - /** - * Implements the "Subscribe" algorithm described in the GraphQL specification. - * - * Returns a Promise which resolves to either an AsyncIterator (if successful) - * or an ExecutionResult (error). The promise will be rejected if the schema or - * other arguments to this function are invalid, or if the resolved event stream - * is not an async iterable. - * - * If the client-provided arguments to this function do not result in a - * compliant subscription, a GraphQL Response (ExecutionResult) with - * descriptive errors and no data will be returned. - * - * If the source stream could not be created due to faulty subscription - * resolver logic or underlying systems, the promise will resolve to a single - * ExecutionResult containing `errors` and no `data`. - * - * If the operation succeeded, the promise resolves to an AsyncIterator, which - * yields a stream of ExecutionResults representing the response stream. - * - * Accepts either an object with named arguments, or individual arguments. - */ - - async function subscribe(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); - const resultOrStream = await createSourceEventStream(args); - if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { - return resultOrStream; - } // For each payload yielded from a subscription, map it over the normal - // GraphQL `execute` function, with `payload` as the rootValue. - // This implements the "MapSourceToResponseEvent" algorithm described in - // the GraphQL specification. The `execute` function provides the - // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the - // "ExecuteQuery" algorithm, for which `execute` is also used. - - const mapSourceToResponse = payload => (0, _execute.execute)({ - ...args, - rootValue: payload - }); // Map every source value to a ExecutionResult value as described above. - - return (0, _mapAsyncIterator.mapAsyncIterator)(resultOrStream, mapSourceToResponse); + return mergedVisitor; +} +/** + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + */ + +function getEnterLeaveForKind(visitor, kind) { + const kindVisitor = visitor[kind]; + if (typeof kindVisitor === 'object') { + // { Kind: { enter() {}, leave() {} } } + return kindVisitor; + } else if (typeof kindVisitor === 'function') { + // { Kind() {} } + return { + enter: kindVisitor, + leave: undefined + }; + } // { enter() {}, leave() {} } + + return { + enter: visitor.enter, + leave: visitor.leave + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + * + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + */ + +/* c8 ignore next 8 */ + +function getVisitFn(visitor, kind, isLeaving) { + const { + enter, + leave + } = getEnterLeaveForKind(visitor, kind); + return isLeaving ? leave : enter; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/assertName.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/assertName.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.assertEnumValueName = assertEnumValueName; +exports.assertName = assertName; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _characterClasses = __webpack_require__(/*! ../language/characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); +/** + * Upholds the spec rules about naming. + */ + +function assertName(name) { + name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); + typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + if (name.length === 0) { + throw new _GraphQLError.GraphQLError('Expected name to be a non-empty string.'); + } + for (let i = 1; i < name.length; ++i) { + if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { + throw new _GraphQLError.GraphQLError(`Names must only contain [_a-zA-Z0-9] but "${name}" does not.`); + } + } + if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { + throw new _GraphQLError.GraphQLError(`Names must start with [_a-zA-Z] but "${name}" does not.`); + } + return name; +} +/** + * Upholds the spec rules about naming enum values. + * + * @internal + */ + +function assertEnumValueName(name) { + if (name === 'true' || name === 'false' || name === 'null') { + throw new _GraphQLError.GraphQLError(`Enum values cannot be named: ${name}`); } - function toNormalizedArgs(args) { - const firstArg = args[0]; - if (firstArg && 'document' in firstArg) { - return firstArg; - } + return assertName(name); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/definition.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/definition.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.GraphQLUnionType = exports.GraphQLScalarType = exports.GraphQLObjectType = exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInterfaceType = exports.GraphQLInputObjectType = exports.GraphQLEnumType = void 0; +exports.argsToArgsConfig = argsToArgsConfig; +exports.assertAbstractType = assertAbstractType; +exports.assertCompositeType = assertCompositeType; +exports.assertEnumType = assertEnumType; +exports.assertInputObjectType = assertInputObjectType; +exports.assertInputType = assertInputType; +exports.assertInterfaceType = assertInterfaceType; +exports.assertLeafType = assertLeafType; +exports.assertListType = assertListType; +exports.assertNamedType = assertNamedType; +exports.assertNonNullType = assertNonNullType; +exports.assertNullableType = assertNullableType; +exports.assertObjectType = assertObjectType; +exports.assertOutputType = assertOutputType; +exports.assertScalarType = assertScalarType; +exports.assertType = assertType; +exports.assertUnionType = assertUnionType; +exports.assertWrappingType = assertWrappingType; +exports.defineArguments = defineArguments; +exports.getNamedType = getNamedType; +exports.getNullableType = getNullableType; +exports.isAbstractType = isAbstractType; +exports.isCompositeType = isCompositeType; +exports.isEnumType = isEnumType; +exports.isInputObjectType = isInputObjectType; +exports.isInputType = isInputType; +exports.isInterfaceType = isInterfaceType; +exports.isLeafType = isLeafType; +exports.isListType = isListType; +exports.isNamedType = isNamedType; +exports.isNonNullType = isNonNullType; +exports.isNullableType = isNullableType; +exports.isObjectType = isObjectType; +exports.isOutputType = isOutputType; +exports.isRequiredArgument = isRequiredArgument; +exports.isRequiredInputField = isRequiredInputField; +exports.isScalarType = isScalarType; +exports.isType = isType; +exports.isUnionType = isUnionType; +exports.isWrappingType = isWrappingType; +exports.resolveObjMapThunk = resolveObjMapThunk; +exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _identityFunc = __webpack_require__(/*! ../jsutils/identityFunc.mjs */ "../../../node_modules/graphql/jsutils/identityFunc.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); +var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); +var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _valueFromASTUntyped = __webpack_require__(/*! ../utilities/valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); +var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); +function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} +function assertType(type) { + if (!isType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`); + } + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + +function isScalarType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); +} +function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`); + } + return type; +} +function isObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); +} +function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`); + } + return type; +} +function isInterfaceType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); +} +function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`); + } + return type; +} +function isUnionType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); +} +function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`); + } + return type; +} +function isEnumType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); +} +function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`); + } + return type; +} +function isInputObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); +} +function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Input Object type.`); + } + return type; +} +function isListType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLList); +} +function assertListType(type) { + if (!isListType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`); + } + return type; +} +function isNonNullType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); +} +function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`); + } + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + +function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} +function assertInputType(type) { + if (!isInputType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`); + } + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + +function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} +function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`); + } + return type; +} +/** + * These types may describe types which may be leaf values. + */ + +function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} +function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`); + } + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} +function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`); + } + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} +function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`); + } + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ + +class GraphQLList { + constructor(ofType) { + isType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return 'GraphQLList'; + } + toString() { + return '[' + String(this.ofType) + ']'; + } + toJSON() { + return this.toString(); + } +} +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * Note: the enforcement of non-nullability occurs within the executor. + */ +exports.GraphQLList = GraphQLList; +class GraphQLNonNull { + constructor(ofType) { + isNullableType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL nullable type.`); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return 'GraphQLNonNull'; + } + toString() { + return String(this.ofType) + '!'; + } + toJSON() { + return this.toString(); + } +} +/** + * These types wrap and modify other types + */ +exports.GraphQLNonNull = GraphQLNonNull; +function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} +function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`); + } + return type; +} +/** + * These types can all accept null as a value. + */ + +function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} +function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`); + } + return type; +} +function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + +function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} +function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`); + } + return type; +} +function getNamedType(type) { + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + +function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +function resolveObjMapThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. It is always better to validate + * + * Example: + * + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } + * + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` + */ +class GraphQLScalarType { + constructor(config) { + var _config$parseValue, _config$serialize, _config$parseLiteral, _config$extensionASTN; + const parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : _identityFunc.identityFunc; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : _identityFunc.identityFunc; + this.parseValue = parseValue; + this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : (node, variables) => parseValue((0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables)); + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; + config.specifiedByURL == null || typeof config.specifiedByURL === 'string' || (0, _devAssert.devAssert)(false, `${this.name} must provide "specifiedByURL" as a string, ` + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`); + config.serialize == null || typeof config.serialize === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`); + if (config.parseLiteral) { + typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide both "parseValue" and "parseLiteral" functions.`); + } + } + get [Symbol.toStringTag]() { + return 'GraphQLScalarType'; + } + toConfig() { return { - schema: firstArg, - // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 - document: args[1], - rootValue: args[2], - contextValue: args[3], - variableValues: args[4], - operationName: args[5], - subscribeFieldResolver: args[6] + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes }; } - /** - * Implements the "CreateSourceEventStream" algorithm described in the - * GraphQL specification, resolving the subscription source event stream. - * - * Returns a Promise which resolves to either an AsyncIterable (if successful) - * or an ExecutionResult (error). The promise will be rejected if the schema or - * other arguments to this function are invalid, or if the resolved event stream - * is not an async iterable. - * - * If the client-provided arguments to this function do not result in a - * compliant subscription, a GraphQL Response (ExecutionResult) with - * descriptive errors and no data will be returned. - * - * If the the source stream could not be created due to faulty subscription - * resolver logic or underlying systems, the promise will resolve to a single - * ExecutionResult containing `errors` and no `data`. - * - * If the operation succeeded, the promise resolves to the AsyncIterable for the - * event stream returned by the resolver. - * - * A Source Event Stream represents a sequence of events, each of which triggers - * a GraphQL execution for that event. - * - * This may be useful when hosting the stateful subscription service in a - * different process or machine than the stateless GraphQL execution engine, - * or otherwise separating these two steps. For more on this, see the - * "Supporting Subscriptions at Scale" information in the GraphQL specification. - */ - - async function createSourceEventStream(...rawArgs) { - const args = toNormalizedArgs(rawArgs); - const { - schema, - document, - variableValues - } = args; // If arguments are missing or incorrectly typed, this is an internal - // developer mistake which should throw an early error. - - (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, - // a "Response" with only errors is returned. - - const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. - - if (!('schema' in exeContext)) { - return { - errors: exeContext - }; - } - try { - const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. - - if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { - throw new Error('Subscription field must return Async Iterable. ' + `Received: ${(0, _inspect.inspect)(eventStream)}.`); - } - return eventStream; - } catch (error) { - // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. - // Otherwise treat the error as a system-class error and re-throw it. - if (error instanceof _GraphQLError.GraphQLError) { - return { - errors: [error] - }; - } - throw error; - } + toString() { + return this.name; } - async function executeSubscription(exeContext) { - const { - schema, - fragments, - operation, - variableValues, - rootValue - } = exeContext; - const rootType = schema.getSubscriptionType(); - if (rootType == null) { - throw new _GraphQLError.GraphQLError('Schema is not configured to execute subscription operation.', { - nodes: operation - }); - } - const rootFields = (0, _collectFields.collectFields)(schema, fragments, variableValues, rootType, operation.selectionSet); - const [responseName, fieldNodes] = [...rootFields.entries()][0]; - const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); - if (!fieldDef) { - const fieldName = fieldNodes[0].name.value; - throw new _GraphQLError.GraphQLError(`The subscription field "${fieldName}" is not defined.`, { - nodes: fieldNodes - }); - } - const path = (0, _Path.addPath)(undefined, responseName, rootType.name); - const info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, rootType, path); - try { - var _fieldDef$subscribe; - - // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. - // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. - // Build a JS object of arguments from the field.arguments AST, using the - // variables scope to fulfill any variable references. - const args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. - - const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an - // AsyncIterable yielding raw payloads. - - const resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.subscribeFieldResolver; - const eventStream = await resolveFn(rootValue, args, contextValue, info); - if (eventStream instanceof Error) { - throw eventStream; - } - return eventStream; - } catch (error) { - throw (0, _locatedError.locatedError)(error, fieldNodes, (0, _Path.pathToArray)(path)); - } + toJSON() { + return this.toString(); } - - /***/ }), - - /***/ "../../../node_modules/graphql/execution/values.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/execution/values.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getArgumentValues = getArgumentValues; - exports.getDirectiveValues = getDirectiveValues; - exports.getVariableValues = getVariableValues; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _coerceInputValue = __webpack_require__(/*! ../utilities/coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); - var _typeFromAST = __webpack_require__(/*! ../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - var _valueFromAST = __webpack_require__(/*! ../utilities/valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); - /** - * Prepares an object map of variableValues of the correct type based on the - * provided variable definitions and arbitrary input. If the input cannot be - * parsed to match the variable definitions, a GraphQLError will be thrown. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ - function getVariableValues(schema, varDefNodes, inputs, options) { - const errors = []; - const maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors; - try { - const coerced = coerceVariableValues(schema, varDefNodes, inputs, error => { - if (maxErrors != null && errors.length >= maxErrors) { - throw new _GraphQLError.GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.'); - } - errors.push(error); - }); - if (errors.length === 0) { - return { - coerced - }; - } - } catch (error) { - errors.push(error); - } +} + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` + */ +exports.GraphQLScalarType = GraphQLScalarType; +class GraphQLObjectType { + constructor(config) { + var _config$extensionASTN2; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN2 = config.extensionASTNodes) !== null && _config$extensionASTN2 !== void 0 ? _config$extensionASTN2 : []; + this._fields = () => defineFieldMap(config); + this._interfaces = () => defineInterfaces(config); + config.isTypeOf == null || typeof config.isTypeOf === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "isTypeOf" as a function, ` + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`); + } + get [Symbol.toStringTag]() { + return 'GraphQLObjectType'; + } + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { return { - errors + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes }; } - function coerceVariableValues(schema, varDefNodes, inputs, onError) { - const coercedValues = {}; - for (const varDefNode of varDefNodes) { - const varName = varDefNode.variable.name.value; - const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); - if (!(0, _definition.isInputType)(varType)) { - // Must use input types for variables. This should be caught during - // validation, however is checked again here for safety. - const varTypeStr = (0, _printer.print)(varDefNode.type); - onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, { - nodes: varDefNode.type - })); - continue; - } - if (!hasOwnProperty(inputs, varName)) { - if (varDefNode.defaultValue) { - coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); - } else if ((0, _definition.isNonNullType)(varType)) { - const varTypeStr = (0, _inspect.inspect)(varType); - onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, { - nodes: varDefNode - })); - } - continue; - } - const value = inputs[varName]; - if (value === null && (0, _definition.isNonNullType)(varType)) { - const varTypeStr = (0, _inspect.inspect)(varType); - onError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, { - nodes: varDefNode - })); - continue; - } - coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)(value, varType, (path, invalidValue, error) => { - let prefix = `Variable "$${varName}" got invalid value ` + (0, _inspect.inspect)(invalidValue); - if (path.length > 0) { - prefix += ` at "${varName}${(0, _printPathArray.printPathArray)(path)}"`; - } - onError(new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { - nodes: varDefNode, - originalError: error - })); - }); - } - return coercedValues; + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } +} +exports.GraphQLObjectType = GraphQLObjectType; +function defineInterfaces(config) { + var _config$interfaces; + const interfaces = resolveReadonlyArrayThunk((_config$interfaces = config.interfaces) !== null && _config$interfaces !== void 0 ? _config$interfaces : []); + Array.isArray(interfaces) || (0, _devAssert.devAssert)(false, `${config.name} interfaces must be an Array or a function which returns an Array.`); + return interfaces; +} +function defineFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + var _fieldConfig$args; + isPlainObj(fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field config must be an object.`); + fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`); + const argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {}; + isPlainObj(argsConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} args must be an object with argument names as keys.`); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + args: defineArguments(argsConfig), + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); +} +function defineArguments(config) { + return Object.entries(config).map(([argName, argConfig]) => ({ + name: (0, _assertName.assertName)(argName), + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), + astNode: argConfig.astNode + })); +} +function isPlainObj(obj) { + return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); +} +function fieldsToFieldsConfig(fields) { + return (0, _mapValue.mapValue)(fields, field => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + })); +} +/** + * @internal + */ + +function argsToArgsConfig(args) { + return (0, _keyValMap.keyValMap)(args, arg => arg.name, arg => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode + })); +} +function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ +class GraphQLInterfaceType { + constructor(config) { + var _config$extensionASTN3; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN3 = config.extensionASTNodes) !== null && _config$extensionASTN3 !== void 0 ? _config$extensionASTN3 : []; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); + } + get [Symbol.toStringTag]() { + return 'GraphQLInterfaceType'; + } + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; } - /** - * Prepares an object map of argument values given a list of argument - * definitions and list of argument AST nodes. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ - - function getArgumentValues(def, node, variableValues) { - var _node$arguments; - const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : []; - const argNodeMap = (0, _keyMap.keyMap)(argumentNodes, arg => arg.name.value); - for (const argDef of def.args) { - const name = argDef.name; - const argType = argDef.type; - const argumentNode = argNodeMap[name]; - if (!argumentNode) { - if (argDef.defaultValue !== undefined) { - coercedValues[name] = argDef.defaultValue; - } else if ((0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + 'was not provided.', { - nodes: node - }); - } - continue; - } - const valueNode = argumentNode.value; - let isNull = valueNode.kind === _kinds.Kind.NULL; - if (valueNode.kind === _kinds.Kind.VARIABLE) { - const variableName = valueNode.name.value; - if (variableValues == null || !hasOwnProperty(variableValues, variableName)) { - if (argDef.defaultValue !== undefined) { - coercedValues[name] = argDef.defaultValue; - } else if ((0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError(`Argument "${name}" of required type "${(0, _inspect.inspect)(argType)}" ` + `was provided the variable "$${variableName}" which was not provided a runtime value.`, { - nodes: valueNode - }); - } - continue; - } - isNull = variableValues[variableName] == null; - } - if (isNull && (0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError(`Argument "${name}" of non-null type "${(0, _inspect.inspect)(argType)}" ` + 'must not be null.', { - nodes: valueNode - }); - } - const coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); - if (coercedValue === undefined) { - // Note: ValuesOfCorrectTypeRule validation should catch this before - // execution. This is a runtime check to ensure execution does not - // continue with an invalid argument value. - throw new _GraphQLError.GraphQLError(`Argument "${name}" has invalid value ${(0, _printer.print)(valueNode)}.`, { - nodes: valueNode - }); - } - coercedValues[name] = coercedValue; - } - return coercedValues; + toString() { + return this.name; } - /** - * Prepares an object map of argument values given a directive definition - * and a AST node which may contain directives. Optionally also accepts a map - * of variable values. - * - * If the directive does not exist on the node, returns undefined. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ - - function getDirectiveValues(directiveDef, node, variableValues) { - var _node$directives; - const directiveNode = (_node$directives = node.directives) === null || _node$directives === void 0 ? void 0 : _node$directives.find(directive => directive.name.value === directiveDef.name); - if (directiveNode) { - return getArgumentValues(directiveDef, directiveNode, variableValues); - } + toJSON() { + return this.toString(); } - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); +} + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ +exports.GraphQLInterfaceType = GraphQLInterfaceType; +class GraphQLUnionType { + constructor(config) { + var _config$extensionASTN4; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN4 = config.extensionASTNodes) !== null && _config$extensionASTN4 !== void 0 ? _config$extensionASTN4 : []; + this._types = defineTypes.bind(undefined, config); + config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); + } + get [Symbol.toStringTag]() { + return 'GraphQLUnionType'; + } + getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + return this._types; + } + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; } - - /***/ }), - - /***/ "../../../node_modules/graphql/graphql.mjs": - /*!*************************************************!*\ - !*** ../../../node_modules/graphql/graphql.mjs ***! - \*************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.graphql = graphql; - exports.graphqlSync = graphqlSync; - var _devAssert = __webpack_require__(/*! ./jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _isPromise = __webpack_require__(/*! ./jsutils/isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); - var _parser = __webpack_require__(/*! ./language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); - var _validate = __webpack_require__(/*! ./type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); - var _validate2 = __webpack_require__(/*! ./validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); - var _execute = __webpack_require__(/*! ./execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); - /** - * This is the primary entry point function for fulfilling GraphQL operations - * by parsing, validating, and executing a GraphQL document along side a - * GraphQL schema. - * - * More sophisticated GraphQL servers, such as those which persist queries, - * may wish to separate the validation and execution phases to a static time - * tooling step, and a server runtime step. - * - * Accepts either an object with named arguments, or individual arguments: - * - * schema: - * The GraphQL type system to use when validating and executing a query. - * source: - * A GraphQL language formatted string representing the requested operation. - * rootValue: - * The value provided as the first argument to resolver functions on the top - * level type (e.g. the query object type). - * contextValue: - * The context value is provided as an argument to resolver functions after - * field arguments. It is used to pass shared information useful at any point - * during executing this query, for example the currently logged in user and - * connections to databases or other services. - * variableValues: - * A mapping of variable name to runtime value to use for all variables - * defined in the requestString. - * operationName: - * The name of the operation to use if requestString contains multiple - * possible operations. Can be omitted if requestString contains only - * one operation. - * fieldResolver: - * A resolver function to use when one is not provided by the schema. - * If not provided, the default field resolver is used (which looks for a - * value or method on the source value with the field's name). - * typeResolver: - * A type resolver function to use when none is provided by the schema. - * If not provided, the default type resolver is used (which looks for a - * `__typename` field or alternatively calls the `isTypeOf` method). - */ - - function graphql(args) { - // Always return a Promise for a consistent API. - return new Promise(resolve => resolve(graphqlImpl(args))); + toString() { + return this.name; } - /** - * The graphqlSync function also fulfills GraphQL operations by parsing, - * validating, and executing a GraphQL document along side a GraphQL schema. - * However, it guarantees to complete synchronously (or throw an error) assuming - * that all field resolvers are also synchronous. - */ - - function graphqlSync(args) { - const result = graphqlImpl(args); // Assert that the execution was synchronous. - - if ((0, _isPromise.isPromise)(result)) { - throw new Error('GraphQL execution failed to complete synchronously.'); - } - return result; + toJSON() { + return this.toString(); } - function graphqlImpl(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || (0, _devAssert.devAssert)(false, 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.'); - const { - schema, - source, - rootValue, - contextValue, - variableValues, - operationName, - fieldResolver, - typeResolver - } = args; // Validate Schema - - const schemaValidationErrors = (0, _validate.validateSchema)(schema); - if (schemaValidationErrors.length > 0) { - return { - errors: schemaValidationErrors - }; - } // Parse - - let document; - try { - document = (0, _parser.parse)(source); - } catch (syntaxError) { - return { - errors: [syntaxError] - }; - } // Validate - - const validationErrors = (0, _validate2.validate)(schema, document); - if (validationErrors.length > 0) { - return { - errors: validationErrors - }; - } // Execute - - return (0, _execute.execute)({ - schema, - document, - rootValue, - contextValue, - variableValues, - operationName, - fieldResolver, - typeResolver - }); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/index.mjs": - /*!***********************************************!*\ - !*** ../../../node_modules/graphql/index.mjs ***! - \***********************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "BREAK", ({ - enumerable: true, - get: function () { - return _index2.BREAK; +} +exports.GraphQLUnionType = GraphQLUnionType; +function defineTypes(config) { + const types = resolveReadonlyArrayThunk(config.types); + Array.isArray(types) || (0, _devAssert.devAssert)(false, `Must provide Array of types or a function which returns such an array for Union ${config.name}.`); + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * ```ts + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +class GraphQLEnumType { + /* */ + constructor(config) { + var _config$extensionASTN5; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN5 = config.extensionASTNodes) !== null && _config$extensionASTN5 !== void 0 ? _config$extensionASTN5 : []; + this._values = defineEnumValues(this.name, config.values); + this._valueLookup = new Map(this._values.map(enumValue => [enumValue.value, enumValue])); + this._nameLookup = (0, _keyMap.keyMap)(this._values, value => value.name); + } + get [Symbol.toStringTag]() { + return 'GraphQLEnumType'; + } + getValues() { + return this._values; + } + getValue(name) { + return this._nameLookup[name]; + } + serialize(outputValue) { + const enumValue = this._valueLookup.get(outputValue); + if (enumValue === undefined) { + throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); + } + return enumValue.name; + } + parseValue(inputValue) /* T */ + { + if (typeof inputValue !== 'string') { + const valueStr = (0, _inspect.inspect)(inputValue); + throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr)); + } + const enumValue = this.getValue(inputValue); + if (enumValue == null) { + throw new _GraphQLError.GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue)); + } + return enumValue.value; + } + parseLiteral(valueNode, _variables) /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== _kinds.Kind.ENUM) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr), { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "BreakingChangeType", ({ - enumerable: true, - get: function () { - return _index6.BreakingChangeType; + const enumValue = this.getValue(valueNode.value); + if (enumValue == null) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr), { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ - enumerable: true, - get: function () { - return _index.DEFAULT_DEPRECATION_REASON; + return enumValue.value; + } + toConfig() { + const values = (0, _keyValMap.keyValMap)(this.getValues(), value => value.name, value => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode + })); + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } +} +exports.GraphQLEnumType = GraphQLEnumType; +function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map(value => value.name); + const suggestedValues = (0, _suggestionList.suggestionList)(unknownValueStr, allNames); + return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); +} +function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || (0, _devAssert.devAssert)(false, `${typeName} values must be an object with value names as keys.`); + return Object.entries(valueMap).map(([valueName, valueConfig]) => { + isPlainObj(valueConfig) || (0, _devAssert.devAssert)(false, `${typeName}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${(0, _inspect.inspect)(valueConfig)}.`); + return { + name: (0, _assertName.assertEnumValueName)(valueName), + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + deprecationReason: valueConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), + astNode: valueConfig.astNode + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` + */ +class GraphQLInputObjectType { + constructor(config) { + var _config$extensionASTN6; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN6 = config.extensionASTNodes) !== null && _config$extensionASTN6 !== void 0 ? _config$extensionASTN6 : []; + this._fields = defineInputFieldMap.bind(undefined, config); + } + get [Symbol.toStringTag]() { + return 'GraphQLInputObjectType'; + } + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + toConfig() { + const fields = (0, _mapValue.mapValue)(this.getFields(), field => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode + })); + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } +} +exports.GraphQLInputObjectType = GraphQLInputObjectType; +function defineInputFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + !('resolve' in fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode + }; + }); +} +function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/directives.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/type/directives.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.GraphQLSpecifiedByDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = void 0; +exports.assertDirective = assertDirective; +exports.isDirective = isDirective; +exports.isSpecifiedDirective = isSpecifiedDirective; +exports.specifiedDirectives = void 0; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); +var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); +var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); +var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +/** + * Test if the given value is a GraphQL directive. + */ + +function isDirective(directive) { + return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); +} +function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error(`Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`); + } + return directive; +} +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +class GraphQLDirective { + constructor(config) { + var _config$isRepeatable, _config$args; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + Array.isArray(config.locations) || (0, _devAssert.devAssert)(false, `@${config.name} locations must be an Array.`); + const args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {}; + (0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args) || (0, _devAssert.devAssert)(false, `@${config.name} args must be an object with argument names as keys.`); + this.args = (0, _definition.defineArguments)(args); + } + get [Symbol.toStringTag]() { + return 'GraphQLDirective'; + } + toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: (0, _definition.argsToArgsConfig)(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode + }; + } + toString() { + return '@' + this.name; + } + toJSON() { + return this.toString(); + } +} + +/** + * Used to conditionally include fields or fragments. + */ +exports.GraphQLDirective = GraphQLDirective; +const GraphQLIncludeDirective = exports.GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +const GraphQLSkipDirective = exports.GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +const DEFAULT_DEPRECATION_REASON = exports.DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +const GraphQLDeprecatedDirective = exports.GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: _scalars.GraphQLString, + description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * Used to provide a URL for specifying the behavior of custom scalar definitions. + */ + +const GraphQLSpecifiedByDirective = exports.GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behavior of this scalar.', + locations: [_directiveLocation.DirectiveLocation.SCALAR], + args: { + url: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The URL that specifies the behavior of this scalar.' } - })); - Object.defineProperty(exports, "DangerousChangeType", ({ - enumerable: true, - get: function () { - return _index6.DangerousChangeType; + } +}); +/** + * The full list of specified directives. + */ + +const specifiedDirectives = exports.specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]); +function isSpecifiedDirective(directive) { + return specifiedDirectives.some(({ + name + }) => name === directive.name); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/index.mjs": +/*!****************************************************!*\ + !*** ../../../node_modules/graphql/type/index.mjs ***! + \****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ + enumerable: true, + get: function () { + return _directives.DEFAULT_DEPRECATION_REASON; + } +})); +Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MAX_INT; + } +})); +Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MIN_INT; + } +})); +Object.defineProperty(exports, "GraphQLBoolean", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLBoolean; + } +})); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLDeprecatedDirective; + } +})); +Object.defineProperty(exports, "GraphQLDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLDirective; + } +})); +Object.defineProperty(exports, "GraphQLEnumType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLEnumType; + } +})); +Object.defineProperty(exports, "GraphQLFloat", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLFloat; + } +})); +Object.defineProperty(exports, "GraphQLID", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLID; + } +})); +Object.defineProperty(exports, "GraphQLIncludeDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLIncludeDirective; + } +})); +Object.defineProperty(exports, "GraphQLInputObjectType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLInputObjectType; + } +})); +Object.defineProperty(exports, "GraphQLInt", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLInt; + } +})); +Object.defineProperty(exports, "GraphQLInterfaceType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLInterfaceType; + } +})); +Object.defineProperty(exports, "GraphQLList", ({ + enumerable: true, + get: function () { + return _definition.GraphQLList; + } +})); +Object.defineProperty(exports, "GraphQLNonNull", ({ + enumerable: true, + get: function () { + return _definition.GraphQLNonNull; + } +})); +Object.defineProperty(exports, "GraphQLObjectType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLObjectType; + } +})); +Object.defineProperty(exports, "GraphQLScalarType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLScalarType; + } +})); +Object.defineProperty(exports, "GraphQLSchema", ({ + enumerable: true, + get: function () { + return _schema.GraphQLSchema; + } +})); +Object.defineProperty(exports, "GraphQLSkipDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLSkipDirective; + } +})); +Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ + enumerable: true, + get: function () { + return _directives.GraphQLSpecifiedByDirective; + } +})); +Object.defineProperty(exports, "GraphQLString", ({ + enumerable: true, + get: function () { + return _scalars.GraphQLString; + } +})); +Object.defineProperty(exports, "GraphQLUnionType", ({ + enumerable: true, + get: function () { + return _definition.GraphQLUnionType; + } +})); +Object.defineProperty(exports, "SchemaMetaFieldDef", ({ + enumerable: true, + get: function () { + return _introspection.SchemaMetaFieldDef; + } +})); +Object.defineProperty(exports, "TypeKind", ({ + enumerable: true, + get: function () { + return _introspection.TypeKind; + } +})); +Object.defineProperty(exports, "TypeMetaFieldDef", ({ + enumerable: true, + get: function () { + return _introspection.TypeMetaFieldDef; + } +})); +Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ + enumerable: true, + get: function () { + return _introspection.TypeNameMetaFieldDef; + } +})); +Object.defineProperty(exports, "__Directive", ({ + enumerable: true, + get: function () { + return _introspection.__Directive; + } +})); +Object.defineProperty(exports, "__DirectiveLocation", ({ + enumerable: true, + get: function () { + return _introspection.__DirectiveLocation; + } +})); +Object.defineProperty(exports, "__EnumValue", ({ + enumerable: true, + get: function () { + return _introspection.__EnumValue; + } +})); +Object.defineProperty(exports, "__Field", ({ + enumerable: true, + get: function () { + return _introspection.__Field; + } +})); +Object.defineProperty(exports, "__InputValue", ({ + enumerable: true, + get: function () { + return _introspection.__InputValue; + } +})); +Object.defineProperty(exports, "__Schema", ({ + enumerable: true, + get: function () { + return _introspection.__Schema; + } +})); +Object.defineProperty(exports, "__Type", ({ + enumerable: true, + get: function () { + return _introspection.__Type; + } +})); +Object.defineProperty(exports, "__TypeKind", ({ + enumerable: true, + get: function () { + return _introspection.__TypeKind; + } +})); +Object.defineProperty(exports, "assertAbstractType", ({ + enumerable: true, + get: function () { + return _definition.assertAbstractType; + } +})); +Object.defineProperty(exports, "assertCompositeType", ({ + enumerable: true, + get: function () { + return _definition.assertCompositeType; + } +})); +Object.defineProperty(exports, "assertDirective", ({ + enumerable: true, + get: function () { + return _directives.assertDirective; + } +})); +Object.defineProperty(exports, "assertEnumType", ({ + enumerable: true, + get: function () { + return _definition.assertEnumType; + } +})); +Object.defineProperty(exports, "assertEnumValueName", ({ + enumerable: true, + get: function () { + return _assertName.assertEnumValueName; + } +})); +Object.defineProperty(exports, "assertInputObjectType", ({ + enumerable: true, + get: function () { + return _definition.assertInputObjectType; + } +})); +Object.defineProperty(exports, "assertInputType", ({ + enumerable: true, + get: function () { + return _definition.assertInputType; + } +})); +Object.defineProperty(exports, "assertInterfaceType", ({ + enumerable: true, + get: function () { + return _definition.assertInterfaceType; + } +})); +Object.defineProperty(exports, "assertLeafType", ({ + enumerable: true, + get: function () { + return _definition.assertLeafType; + } +})); +Object.defineProperty(exports, "assertListType", ({ + enumerable: true, + get: function () { + return _definition.assertListType; + } +})); +Object.defineProperty(exports, "assertName", ({ + enumerable: true, + get: function () { + return _assertName.assertName; + } +})); +Object.defineProperty(exports, "assertNamedType", ({ + enumerable: true, + get: function () { + return _definition.assertNamedType; + } +})); +Object.defineProperty(exports, "assertNonNullType", ({ + enumerable: true, + get: function () { + return _definition.assertNonNullType; + } +})); +Object.defineProperty(exports, "assertNullableType", ({ + enumerable: true, + get: function () { + return _definition.assertNullableType; + } +})); +Object.defineProperty(exports, "assertObjectType", ({ + enumerable: true, + get: function () { + return _definition.assertObjectType; + } +})); +Object.defineProperty(exports, "assertOutputType", ({ + enumerable: true, + get: function () { + return _definition.assertOutputType; + } +})); +Object.defineProperty(exports, "assertScalarType", ({ + enumerable: true, + get: function () { + return _definition.assertScalarType; + } +})); +Object.defineProperty(exports, "assertSchema", ({ + enumerable: true, + get: function () { + return _schema.assertSchema; + } +})); +Object.defineProperty(exports, "assertType", ({ + enumerable: true, + get: function () { + return _definition.assertType; + } +})); +Object.defineProperty(exports, "assertUnionType", ({ + enumerable: true, + get: function () { + return _definition.assertUnionType; + } +})); +Object.defineProperty(exports, "assertValidSchema", ({ + enumerable: true, + get: function () { + return _validate.assertValidSchema; + } +})); +Object.defineProperty(exports, "assertWrappingType", ({ + enumerable: true, + get: function () { + return _definition.assertWrappingType; + } +})); +Object.defineProperty(exports, "getNamedType", ({ + enumerable: true, + get: function () { + return _definition.getNamedType; + } +})); +Object.defineProperty(exports, "getNullableType", ({ + enumerable: true, + get: function () { + return _definition.getNullableType; + } +})); +Object.defineProperty(exports, "introspectionTypes", ({ + enumerable: true, + get: function () { + return _introspection.introspectionTypes; + } +})); +Object.defineProperty(exports, "isAbstractType", ({ + enumerable: true, + get: function () { + return _definition.isAbstractType; + } +})); +Object.defineProperty(exports, "isCompositeType", ({ + enumerable: true, + get: function () { + return _definition.isCompositeType; + } +})); +Object.defineProperty(exports, "isDirective", ({ + enumerable: true, + get: function () { + return _directives.isDirective; + } +})); +Object.defineProperty(exports, "isEnumType", ({ + enumerable: true, + get: function () { + return _definition.isEnumType; + } +})); +Object.defineProperty(exports, "isInputObjectType", ({ + enumerable: true, + get: function () { + return _definition.isInputObjectType; + } +})); +Object.defineProperty(exports, "isInputType", ({ + enumerable: true, + get: function () { + return _definition.isInputType; + } +})); +Object.defineProperty(exports, "isInterfaceType", ({ + enumerable: true, + get: function () { + return _definition.isInterfaceType; + } +})); +Object.defineProperty(exports, "isIntrospectionType", ({ + enumerable: true, + get: function () { + return _introspection.isIntrospectionType; + } +})); +Object.defineProperty(exports, "isLeafType", ({ + enumerable: true, + get: function () { + return _definition.isLeafType; + } +})); +Object.defineProperty(exports, "isListType", ({ + enumerable: true, + get: function () { + return _definition.isListType; + } +})); +Object.defineProperty(exports, "isNamedType", ({ + enumerable: true, + get: function () { + return _definition.isNamedType; + } +})); +Object.defineProperty(exports, "isNonNullType", ({ + enumerable: true, + get: function () { + return _definition.isNonNullType; + } +})); +Object.defineProperty(exports, "isNullableType", ({ + enumerable: true, + get: function () { + return _definition.isNullableType; + } +})); +Object.defineProperty(exports, "isObjectType", ({ + enumerable: true, + get: function () { + return _definition.isObjectType; + } +})); +Object.defineProperty(exports, "isOutputType", ({ + enumerable: true, + get: function () { + return _definition.isOutputType; + } +})); +Object.defineProperty(exports, "isRequiredArgument", ({ + enumerable: true, + get: function () { + return _definition.isRequiredArgument; + } +})); +Object.defineProperty(exports, "isRequiredInputField", ({ + enumerable: true, + get: function () { + return _definition.isRequiredInputField; + } +})); +Object.defineProperty(exports, "isScalarType", ({ + enumerable: true, + get: function () { + return _definition.isScalarType; + } +})); +Object.defineProperty(exports, "isSchema", ({ + enumerable: true, + get: function () { + return _schema.isSchema; + } +})); +Object.defineProperty(exports, "isSpecifiedDirective", ({ + enumerable: true, + get: function () { + return _directives.isSpecifiedDirective; + } +})); +Object.defineProperty(exports, "isSpecifiedScalarType", ({ + enumerable: true, + get: function () { + return _scalars.isSpecifiedScalarType; + } +})); +Object.defineProperty(exports, "isType", ({ + enumerable: true, + get: function () { + return _definition.isType; + } +})); +Object.defineProperty(exports, "isUnionType", ({ + enumerable: true, + get: function () { + return _definition.isUnionType; + } +})); +Object.defineProperty(exports, "isWrappingType", ({ + enumerable: true, + get: function () { + return _definition.isWrappingType; + } +})); +Object.defineProperty(exports, "resolveObjMapThunk", ({ + enumerable: true, + get: function () { + return _definition.resolveObjMapThunk; + } +})); +Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ + enumerable: true, + get: function () { + return _definition.resolveReadonlyArrayThunk; + } +})); +Object.defineProperty(exports, "specifiedDirectives", ({ + enumerable: true, + get: function () { + return _directives.specifiedDirectives; + } +})); +Object.defineProperty(exports, "specifiedScalarTypes", ({ + enumerable: true, + get: function () { + return _scalars.specifiedScalarTypes; + } +})); +Object.defineProperty(exports, "validateSchema", ({ + enumerable: true, + get: function () { + return _validate.validateSchema; + } +})); +var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); +var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); +var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/type/introspection.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/type/introspection.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.introspectionTypes = exports.__TypeKind = exports.__Type = exports.__Schema = exports.__InputValue = exports.__Field = exports.__EnumValue = exports.__DirectiveLocation = exports.__Directive = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.TypeKind = exports.SchemaMetaFieldDef = void 0; +exports.isIntrospectionType = isIntrospectionType; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); +var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _astFromValue = __webpack_require__(/*! ../utilities/astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); +var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +const __Schema = exports.__Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', + fields: () => ({ + description: { + type: _scalars.GraphQLString, + resolve: schema => schema.description + }, + types: { + description: 'A list of all types supported by this server.', + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))), + resolve(schema) { + return Object.values(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new _definition.GraphQLNonNull(__Type), + resolve: schema => schema.getQueryType() + }, + mutationType: { + description: 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: schema => schema.getMutationType() + }, + subscriptionType: { + description: 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: schema => schema.getSubscriptionType() + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))), + resolve: schema => schema.getDirectives() + } + }) +}); +const __Directive = exports.__Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: directive => directive.name + }, + description: { + type: _scalars.GraphQLString, + resolve: directive => directive.description + }, + isRepeatable: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: directive => directive.isRepeatable + }, + locations: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation))), + resolve: directive => directive.locations + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(field, { + includeDeprecated + }) { + return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); + } + } + }) +}); +const __DirectiveLocation = exports.__DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' } - })); - Object.defineProperty(exports, "DirectiveLocation", ({ - enumerable: true, - get: function () { - return _index2.DirectiveLocation; + } +}); +const __Type = exports.__Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', + fields: () => ({ + kind: { + type: new _definition.GraphQLNonNull(__TypeKind), + resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } + if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } + if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } + if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } + if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } + if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } + if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } + if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered) + + false || (0, _invariant.invariant)(false, `Unexpected type: "${(0, _inspect.inspect)(type)}".`); + } + }, + name: { + type: _scalars.GraphQLString, + resolve: type => 'name' in type ? type.name : undefined + }, + description: { + type: _scalars.GraphQLString, + resolve: (type // FIXME: add test case + ) => /* c8 ignore next */ + 'description' in type ? type.description : undefined + }, + specifiedByURL: { + type: _scalars.GraphQLString, + resolve: obj => 'specifiedByURL' in obj ? obj.specifiedByURL : undefined + }, + fields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(type, { + includeDeprecated + }) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + const fields = Object.values(type.getFields()); + return includeDeprecated ? fields : fields.filter(field => field.deprecationReason == null); + } + } + }, + interfaces: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve(type) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve(type, _args, _context, { + schema + }) { + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(type, { + includeDeprecated + }) { + if ((0, _definition.isEnumType)(type)) { + const values = type.getValues(); + return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); + } + } + }, + inputFields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(type, { + includeDeprecated + }) { + if ((0, _definition.isInputObjectType)(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); + } + } + }, + ofType: { + type: __Type, + resolve: type => 'ofType' in type ? type.ofType : undefined + } + }) +}); +const __Field = exports.__Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: field => field.name + }, + description: { + type: _scalars.GraphQLString, + resolve: field => field.description + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve(field, { + includeDeprecated + }) { + return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); + } + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: field => field.type + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: field => field.deprecationReason != null + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: field => field.deprecationReason + } + }) +}); +const __InputValue = exports.__InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: inputValue => inputValue.name + }, + description: { + type: _scalars.GraphQLString, + resolve: inputValue => inputValue.description + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: inputValue => inputValue.type + }, + defaultValue: { + type: _scalars.GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this input value.', + resolve(inputValue) { + const { + type, + defaultValue + } = inputValue; + const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); + return valueAST ? (0, _printer.print)(valueAST) : null; + } + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: field => field.deprecationReason != null + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: obj => obj.deprecationReason + } + }) +}); +const __EnumValue = exports.__EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: enumValue => enumValue.name + }, + description: { + type: _scalars.GraphQLString, + resolve: enumValue => enumValue.description + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: enumValue => enumValue.deprecationReason != null + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: enumValue => enumValue.deprecationReason + } + }) +}); +var TypeKind; +(function (TypeKind) { + TypeKind['SCALAR'] = 'SCALAR'; + TypeKind['OBJECT'] = 'OBJECT'; + TypeKind['INTERFACE'] = 'INTERFACE'; + TypeKind['UNION'] = 'UNION'; + TypeKind['ENUM'] = 'ENUM'; + TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; + TypeKind['LIST'] = 'LIST'; + TypeKind['NON_NULL'] = 'NON_NULL'; +})(TypeKind || (exports.TypeKind = TypeKind = {})); +const __TypeKind = exports.__TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. `inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' } - })); - Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ - enumerable: true, - get: function () { - return _index4.ExecutableDefinitionsRule; + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +const SchemaMetaFieldDef = exports.SchemaMetaFieldDef = { + name: '__schema', + type: new _definition.GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (_source, _args, _context, { + schema + }) => schema, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined +}; +const TypeMetaFieldDef = exports.TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + description: undefined, + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined + }], + resolve: (_source, { + name + }, _context, { + schema + }) => schema.getType(name), + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined +}; +const TypeNameMetaFieldDef = exports.TypeNameMetaFieldDef = { + name: '__typename', + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (_source, _args, _context, { + parentType + }) => parentType.name, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined +}; +const introspectionTypes = exports.introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]); +function isIntrospectionType(type) { + return introspectionTypes.some(({ + name + }) => type.name === name); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/scalars.mjs": +/*!******************************************************!*\ + !*** ../../../node_modules/graphql/type/scalars.mjs ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.GraphQLString = exports.GraphQLInt = exports.GraphQLID = exports.GraphQLFloat = exports.GraphQLBoolean = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = void 0; +exports.isSpecifiedScalarType = isSpecifiedScalarType; +exports.specifiedScalarTypes = void 0; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + * */ + +const GRAPHQL_MAX_INT = exports.GRAPHQL_MAX_INT = 2147483647; +/** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + * */ + +const GRAPHQL_MIN_INT = exports.GRAPHQL_MIN_INT = -2147483648; +const GraphQLInt = exports.GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + let num = coercedValue; + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + if (typeof num !== 'number' || !Number.isInteger(num)) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(coercedValue)}`); + } + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError('Int cannot represent non 32-bit signed integer value: ' + (0, _inspect.inspect)(coercedValue)); + } + return num; + }, + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(inputValue)}`); + } + if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${inputValue}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _printer.print)(valueNode)}`, { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _index4.FieldsOnCorrectTypeRule; + const num = parseInt(valueNode.value, 10); + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ - enumerable: true, - get: function () { - return _index4.FragmentsOnCompositeTypesRule; + return num; + } +}); +const GraphQLFloat = exports.GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + let num = coercedValue; + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + if (typeof num !== 'number' || !Number.isFinite(num)) { + throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(coercedValue)}`); + } + return num; + }, + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { + throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(inputValue)}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.FLOAT && valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _printer.print)(valueNode)}`, valueNode); + } + return parseFloat(valueNode.value); + } +}); +const GraphQLString = exports.GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; } - })); - Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ - enumerable: true, - get: function () { - return _index.GRAPHQL_MAX_INT; + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; } - })); - Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ - enumerable: true, - get: function () { - return _index.GRAPHQL_MIN_INT; + if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { + return coercedValue.toString(); } - })); - Object.defineProperty(exports, "GraphQLBoolean", ({ - enumerable: true, - get: function () { - return _index.GraphQLBoolean; + throw new _GraphQLError.GraphQLError(`String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); + }, + parseValue(inputValue) { + if (typeof inputValue !== 'string') { + throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _inspect.inspect)(inputValue)}`); } - })); - Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLDeprecatedDirective; + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING) { + throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _printer.print)(valueNode)}`, { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "GraphQLDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLDirective; + return valueNode.value; + } +}); +const GraphQLBoolean = exports.GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'boolean') { + return coercedValue; } - })); - Object.defineProperty(exports, "GraphQLEnumType", ({ - enumerable: true, - get: function () { - return _index.GraphQLEnumType; + if (Number.isFinite(coercedValue)) { + return coercedValue !== 0; + } + throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(coercedValue)}`); + }, + parseValue(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(inputValue)}`); + } + return inputValue; + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.BOOLEAN) { + throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _printer.print)(valueNode)}`, { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "GraphQLError", ({ - enumerable: true, - get: function () { - return _index5.GraphQLError; + return valueNode.value; + } +}); +const GraphQLID = exports.GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + if (typeof coercedValue === 'string') { + return coercedValue; } - })); - Object.defineProperty(exports, "GraphQLFloat", ({ - enumerable: true, - get: function () { - return _index.GraphQLFloat; + if (Number.isInteger(coercedValue)) { + return String(coercedValue); } - })); - Object.defineProperty(exports, "GraphQLID", ({ - enumerable: true, - get: function () { - return _index.GraphQLID; + throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); + }, + parseValue(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; } - })); - Object.defineProperty(exports, "GraphQLIncludeDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLIncludeDirective; + if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { + return inputValue.toString(); } - })); - Object.defineProperty(exports, "GraphQLInputObjectType", ({ - enumerable: true, - get: function () { - return _index.GraphQLInputObjectType; + throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`); + }, + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING && valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError('ID cannot represent a non-string and non-integer value: ' + (0, _printer.print)(valueNode), { + nodes: valueNode + }); } - })); - Object.defineProperty(exports, "GraphQLInt", ({ - enumerable: true, - get: function () { - return _index.GraphQLInt; + return valueNode.value; + } +}); +const specifiedScalarTypes = exports.specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]); +function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(({ + name + }) => type.name === name); +} // Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). + +function serializeObject(outputValue) { + if ((0, _isObjectLike.isObjectLike)(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + const valueOfResult = outputValue.valueOf(); + if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { + return valueOfResult; + } } - })); - Object.defineProperty(exports, "GraphQLInterfaceType", ({ - enumerable: true, - get: function () { - return _index.GraphQLInterfaceType; + if (typeof outputValue.toJSON === 'function') { + return outputValue.toJSON(); } - })); - Object.defineProperty(exports, "GraphQLList", ({ - enumerable: true, - get: function () { - return _index.GraphQLList; + } + return outputValue; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/schema.mjs": +/*!*****************************************************!*\ + !*** ../../../node_modules/graphql/type/schema.mjs ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.GraphQLSchema = void 0; +exports.assertSchema = assertSchema; +exports.isSchema = isSchema; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); +var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +/** + * Test if the given value is a GraphQL schema. + */ + +function isSchema(schema) { + return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); +} +function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error(`Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`); + } + return schema; +} +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * ``` + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * ``` + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * ``` + */ +class GraphQLSchema { + // Used as a cache for validateSchema(). + constructor(config) { + var _config$extensionASTN, _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + (0, _isObjectLike.isObjectLike)(config) || (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); + !config.types || Array.isArray(config.types) || (0, _devAssert.devAssert)(false, `"types" must be Array if provided but got: ${(0, _inspect.inspect)(config.types)}.`); + !config.directives || Array.isArray(config.directives) || (0, _devAssert.devAssert)(false, '"directives" must be Array if provided but got: ' + `${(0, _inspect.inspect)(config.directives)}.`); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + const allReferencedTypes = new Set(config.types); + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } } - })); - Object.defineProperty(exports, "GraphQLNonNull", ({ - enumerable: true, - get: function () { - return _index.GraphQLNonNull; + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); } - })); - Object.defineProperty(exports, "GraphQLObjectType", ({ - enumerable: true, - get: function () { - return _index.GraphQLObjectType; + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); } - })); - Object.defineProperty(exports, "GraphQLScalarType", ({ - enumerable: true, - get: function () { - return _index.GraphQLScalarType; + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); } - })); - Object.defineProperty(exports, "GraphQLSchema", ({ - enumerable: true, - get: function () { - return _index.GraphQLSchema; + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if ((0, _directives.isDirective)(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } } - })); - Object.defineProperty(exports, "GraphQLSkipDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLSkipDirective; + collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + const typeName = namedType.name; + typeName || (0, _devAssert.devAssert)(false, 'One of the provided types for building the Schema is missing a name.'); + if (this._typeMap[typeName] !== undefined) { + throw new Error(`Schema must contain uniquely named types but contains multiple types named "${typeName}".`); + } + this._typeMap[typeName] = namedType; + if ((0, _definition.isInterfaceType)(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; + } + implementations.interfaces.push(namedType); + } + } + } else if ((0, _definition.isObjectType)(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; + } + implementations.objects.push(namedType); + } + } + } } - })); - Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ - enumerable: true, - get: function () { - return _index.GraphQLSpecifiedByDirective; + } + get [Symbol.toStringTag]() { + return 'GraphQLSchema'; + } + getQueryType() { + return this._queryType; + } + getMutationType() { + return this._mutationType; + } + getSubscriptionType() { + return this._subscriptionType; + } + getRootType(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return this.getQueryType(); + case _ast.OperationTypeNode.MUTATION: + return this.getMutationType(); + case _ast.OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); } - })); - Object.defineProperty(exports, "GraphQLString", ({ - enumerable: true, - get: function () { - return _index.GraphQLString; + } + getTypeMap() { + return this._typeMap; + } + getType(name) { + return this.getTypeMap()[name]; + } + getPossibleTypes(abstractType) { + return (0, _definition.isUnionType)(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; + } + getImplementations(interfaceType) { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 ? implementations : { + objects: [], + interfaces: [] + }; + } + isSubType(abstractType, maybeSubType) { + let map = this._subTypeMap[abstractType.name]; + if (map === undefined) { + map = Object.create(null); + if ((0, _definition.isUnionType)(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + for (const type of implementations.objects) { + map[type.name] = true; + } + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + this._subTypeMap[abstractType.name] = map; } - })); - Object.defineProperty(exports, "GraphQLUnionType", ({ - enumerable: true, - get: function () { - return _index.GraphQLUnionType; + return map[maybeSubType.name] !== undefined; + } + getDirectives() { + return this._directives; + } + getDirective(name) { + return this.getDirectives().find(directive => directive.name === name); + } + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.__validationErrors !== undefined + }; + } +} +exports.GraphQLSchema = GraphQLSchema; +function collectReferencedTypes(type, typeSet) { + const namedType = (0, _definition.getNamedType)(type); + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + if ((0, _definition.isUnionType)(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if ((0, _definition.isObjectType)(namedType) || (0, _definition.isInterfaceType)(namedType)) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, _definition.isInputObjectType)(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } } - })); - Object.defineProperty(exports, "Kind", ({ - enumerable: true, - get: function () { - return _index2.Kind; + } + return typeSet; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/type/validate.mjs": +/*!*******************************************************!*\ + !*** ../../../node_modules/graphql/type/validate.mjs ***! + \*******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.assertValidSchema = assertValidSchema; +exports.validateSchema = validateSchema; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _typeComparators = __webpack_require__(/*! ../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); +var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ + +function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + +function assertValidSchema(schema) { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} +class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + this._errors.push(new _GraphQLError.GraphQLError(message, { + nodes: _nodes + })); + } + getErrors() { + return this._errors; + } +} +function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + var _getOperationTypeNode; + context.reportError(`Query root type must be Object type, it cannot be ${(0, _inspect.inspect)(queryType)}.`, (_getOperationTypeNode = getOperationTypeNode(schema, _ast.OperationTypeNode.QUERY)) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode); + } + const mutationType = schema.getMutationType(); + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + var _getOperationTypeNode2; + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(mutationType)}.`, (_getOperationTypeNode2 = getOperationTypeNode(schema, _ast.OperationTypeNode.MUTATION)) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode); + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + var _getOperationTypeNode3; + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(subscriptionType)}.`, (_getOperationTypeNode3 = getOperationTypeNode(schema, _ast.OperationTypeNode.SUBSCRIPTION)) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode); + } +} +function getOperationTypeNode(schema, operation) { + var _flatMap$find; + return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes].flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + schemaNode => { + var _schemaNode$operation; + return /* c8 ignore next */( + (_schemaNode$operation = schemaNode === null || schemaNode === void 0 ? void 0 : schemaNode.operationTypes) !== null && _schemaNode$operation !== void 0 ? _schemaNode$operation : [] + ); + }).find(operationNode => operationNode.operation === operation)) === null || _flatMap$find === void 0 ? void 0 : _flatMap$find.type; +} +function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError(`Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, directive === null || directive === void 0 ? void 0 : directive.astNode); + continue; + } // Ensure they are named correctly. + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError(`The type of @${directive.name}(${arg.name}:) must be Input Type ` + `but got: ${(0, _inspect.inspect)(arg.type)}.`, arg.astNode); + } + if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { + var _arg$astNode; + context.reportError(`Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type]); + } + } + } +} +function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + if (node.name.startsWith('__')) { + context.reportError(`Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, node.astNode); + } +} +function validateTypes(context) { + const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + for (const type of Object.values(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError(`Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); } - })); - Object.defineProperty(exports, "KnownArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownArgumentNamesRule; + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); } - })); - Object.defineProperty(exports, "KnownDirectivesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownDirectivesRule; + } +} +function validateFields(context, type) { + const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError(`Type ${type.name} must define one or more fields.`, [type.astNode, ...type.extensionASTNodes]); + } + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!(0, _definition.isOutputType)(field.type)) { + var _field$astNode; + context.reportError(`The type of ${type.name}.${field.name} must be Output Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type); + } // Ensure the arguments are valid + + for (const arg of field.args) { + const argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + var _arg$astNode2; + context.reportError(`The type of ${type.name}.${field.name}(${argName}:) must be Input ` + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type); + } + if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { + var _arg$astNode3; + context.reportError(`Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type]); + } } - })); - Object.defineProperty(exports, "KnownFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownFragmentNamesRule; + } +} +function validateInterfaces(context, type) { + const ifaceTypeNames = Object.create(null); + for (const iface of type.getInterfaces()) { + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError(`Type ${(0, _inspect.inspect)(type)} must only implement Interface types, ` + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, getAllImplementsInterfaceNodes(type, iface)); + continue; } - })); - Object.defineProperty(exports, "KnownTypeNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownTypeNamesRule; + if (type === iface) { + context.reportError(`Type ${type.name} cannot implement itself because it would create a circular reference.`, getAllImplementsInterfaceNodes(type, iface)); + continue; } - })); - Object.defineProperty(exports, "Lexer", ({ - enumerable: true, - get: function () { - return _index2.Lexer; + if (ifaceTypeNames[iface.name]) { + context.reportError(`Type ${type.name} can only implement ${iface.name} once.`, getAllImplementsInterfaceNodes(type, iface)); + continue; } - })); - Object.defineProperty(exports, "Location", ({ - enumerable: true, - get: function () { - return _index2.Location; + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} +function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (const ifaceField of Object.values(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError(`Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, [ifaceField.astNode, type.astNode, ...type.extensionASTNodes]); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, typeField.type, ifaceField.type)) { + var _ifaceField$astNode, _typeField$astNode; + context.reportError(`Interface field ${iface.name}.${fieldName} expects type ` + `${(0, _inspect.inspect)(ifaceField.type)} but ${type.name}.${fieldName} ` + `is type ${(0, _inspect.inspect)(typeField.type)}.`, [(_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]); + } // Assert each interface field arg is implemented. + + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = typeField.args.find(arg => arg.name === argName); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, [ifaceArg.astNode, typeField.astNode]); + continue; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + `${type.name}.${fieldName}(${argName}:) is type ` + `${(0, _inspect.inspect)(typeArg.type)}.`, [(_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]); + } // TODO: validate default values? + } // Assert additional arguments must not be required. + + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = ifaceField.args.find(arg => arg.name === argName); + if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { + context.reportError(`Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, [typeArg.astNode, ifaceField.astNode]); + } + } + } +} +function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError(transitive === type ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, [...getAllImplementsInterfaceNodes(iface, transitive), ...getAllImplementsInterfaceNodes(type, iface)]); + } + } +} +function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + if (memberTypes.length === 0) { + context.reportError(`Union type ${union.name} must define one or more member types.`, [union.astNode, ...union.extensionASTNodes]); + } + const includedTypeNames = Object.create(null); + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError(`Union type ${union.name} can only include type ${memberType.name} once.`, getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + includedTypeNames[memberType.name] = true; + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError(`Union type ${union.name} can only include Object types, ` + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, getUnionMemberTypeNodes(union, String(memberType))); + } + } +} +function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + if (enumValues.length === 0) { + context.reportError(`Enum type ${enumType.name} must define one or more values.`, [enumType.astNode, ...enumType.extensionASTNodes]); + } + for (const enumValue of enumValues) { + // Ensure valid name. + validateName(context, enumValue); + } +} +function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + if (fields.length === 0) { + context.reportError(`Input Object type ${inputObj.name} must define one or more fields.`, [inputObj.astNode, ...inputObj.extensionASTNodes]); + } // Ensure the arguments are valid + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + var _field$astNode2; + context.reportError(`The type of ${inputObj.name}.${field.name} must be Input Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type); } - })); - Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ - enumerable: true, - get: function () { - return _index4.LoneAnonymousOperationRule; + if ((0, _definition.isRequiredInputField)(field) && field.deprecationReason != null) { + var _field$astNode3; + context.reportError(`Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, [getDeprecatedDirectiveNode(field.astNode), (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type]); } - })); - Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ - enumerable: true, - get: function () { - return _index4.LoneSchemaDefinitionRule; + } +} +function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + const fieldPath = []; // Position in the type path + + const fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; } - })); - Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ - enumerable: true, - get: function () { - return _index4.NoDeprecatedCustomRule; + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + const fields = Object.values(inputObj.getFields()); + for (const field of fields) { + if ((0, _definition.isNonNullType)(field.type) && (0, _definition.isInputObjectType)(field.type.ofType)) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map(fieldObj => fieldObj.name).join('.'); + context.reportError(`Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, cyclePath.map(fieldObj => fieldObj.astNode)); + } + fieldPath.pop(); + } } - })); - Object.defineProperty(exports, "NoFragmentCyclesRule", ({ - enumerable: true, - get: function () { - return _index4.NoFragmentCyclesRule; + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} +function getAllImplementsInterfaceNodes(type, iface) { + const { + astNode, + extensionASTNodes + } = type; + const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes.flatMap(typeNode => { + var _typeNode$interfaces; + return /* c8 ignore next */( + (_typeNode$interfaces = typeNode.interfaces) !== null && _typeNode$interfaces !== void 0 ? _typeNode$interfaces : [] + ); + }).filter(ifaceNode => ifaceNode.name.value === iface.name); +} +function getUnionMemberTypeNodes(union, typeName) { + const { + astNode, + extensionASTNodes + } = union; + const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes.flatMap(unionNode => { + var _unionNode$types; + return /* c8 ignore next */( + (_unionNode$types = unionNode.types) !== null && _unionNode$types !== void 0 ? _unionNode$types : [] + ); + }).filter(typeNode => typeNode.name.value === typeName); +} +function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(node => node.name.value === _directives.GraphQLDeprecatedDirective.name); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/TypeInfo.mjs": +/*!************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/TypeInfo.mjs ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TypeInfo = void 0; +exports.visitWithTypeInfo = visitWithTypeInfo; +var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + +class TypeInfo { + constructor(schema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType, /** @deprecated will be removed in 17.0.0 */ + getFieldDefFn) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef; + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } } - })); - Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ - enumerable: true, - get: function () { - return _index4.NoSchemaIntrospectionCustomRule; + } + get [Symbol.toStringTag]() { + return 'TypeInfo'; + } + getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; } - })); - Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ - enumerable: true, - get: function () { - return _index4.NoUndefinedVariablesRule; + } + getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; } - })); - Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ - enumerable: true, - get: function () { - return _index4.NoUnusedFragmentsRule; + } + getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; } - })); - Object.defineProperty(exports, "NoUnusedVariablesRule", ({ - enumerable: true, - get: function () { - return _index4.NoUnusedVariablesRule; + } + getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; } - })); - Object.defineProperty(exports, "OperationTypeNode", ({ - enumerable: true, - get: function () { - return _index2.OperationTypeNode; + } + getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; } - })); - Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ - enumerable: true, - get: function () { - return _index4.OverlappingFieldsCanBeMergedRule; + } + getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; } - })); - Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ - enumerable: true, - get: function () { - return _index4.PossibleFragmentSpreadsRule; + } + getDirective() { + return this._directive; + } + getArgument() { + return this._argument; + } + getEnumValue() { + return this._enumValue; + } + enter(node) { + const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + { + const namedType = (0, _definition.getNamedType)(this.getType()); + this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); + break; + } + case _kinds.Kind.FIELD: + { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + if (fieldDef) { + fieldType = fieldDef.type; + } + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined); + break; + } + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case _kinds.Kind.OPERATION_DEFINITION: + { + const rootType = schema.getRootType(node.operation); + this._typeStack.push((0, _definition.isObjectType)(rootType) ? rootType : undefined); + break; + } + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType()); + this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); + break; + } + case _kinds.Kind.VARIABLE_DEFINITION: + { + const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); + break; + } + case _kinds.Kind.ARGUMENT: + { + var _this$getDirective; + let argDef; + let argType; + const fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef(); + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find(arg => arg.name === node.name.value); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined); + break; + } + case _kinds.Kind.LIST: + { + const listType = (0, _definition.getNullableType)(this.getInputType()); + const itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined); + break; + } + case _kinds.Kind.OBJECT_FIELD: + { + const objectType = (0, _definition.getNamedType)(this.getInputType()); + let inputFieldType; + let inputField; + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + if (inputField) { + inputFieldType = inputField.type; + } + } + this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); + this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined); + break; + } + case _kinds.Kind.ENUM: + { + const enumType = (0, _definition.getNamedType)(this.getInputType()); + let enumValue; + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + default: // Ignore other nodes } - })); - Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ - enumerable: true, - get: function () { - return _index4.PossibleTypeExtensionsRule; + } + leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case _kinds.Kind.ARGUMENT: + this._argument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + default: // Ignore other nodes } - })); - Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ - enumerable: true, - get: function () { - return _index4.ProvidedRequiredArgumentsRule; + } +} + +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ +exports.TypeInfo = TypeInfo; +function getFieldDef(schema, parentType, fieldNode) { + const name = fieldNode.name.value; + if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } + if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } + if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) { + return _introspection.TypeNameMetaFieldDef; + } + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + return parentType.getFields()[name]; + } +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + +function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; + if (fn) { + const result = fn.apply(visitor, args); + if (result !== undefined) { + typeInfo.leave(node); + if ((0, _ast.isNode)(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(...args) { + const node = args[0]; + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; + let result; + if (fn) { + result = fn.apply(visitor, args); + } + typeInfo.leave(node); + return result; } - })); - Object.defineProperty(exports, "ScalarLeafsRule", ({ - enumerable: true, - get: function () { - return _index4.ScalarLeafsRule; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/assertValidName.mjs": +/*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/assertValidName.mjs ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.assertValidName = assertValidName; +exports.isValidNameError = isValidNameError; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _assertName = __webpack_require__(/*! ../type/assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); +/* c8 ignore start */ + +/** + * Upholds the spec rules about naming. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + +function assertValidName(name) { + const error = isValidNameError(name); + if (error) { + throw error; + } + return name; +} +/** + * Returns an Error if a name is invalid. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + +function isValidNameError(name) { + typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + if (name.startsWith('__')) { + return new _GraphQLError.GraphQLError(`Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`); + } + try { + (0, _assertName.assertName)(name); + } catch (error) { + return error; + } +} +/* c8 ignore stop */ + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/astFromValue.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/astFromValue.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.astFromValue = astFromValue; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +/** + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. For example: + * + * astFromValue("value", GraphQLString) + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * + */ + +function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + const astValue = astFromValue(value, type.ofType); + if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === _kinds.Kind.NULL) { + return null; } - })); - Object.defineProperty(exports, "SchemaMetaFieldDef", ({ - enumerable: true, - get: function () { - return _index.SchemaMetaFieldDef; + return astValue; + } // only explicit null, not undefined, NaN + + if (value === null) { + return { + kind: _kinds.Kind.NULL + }; + } // undefined + + if (value === undefined) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if ((0, _isIterableObject.isIterableObject)(value)) { + const valuesNodes = []; + for (const item of value) { + const itemNode = astFromValue(item, itemType); + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + return { + kind: _kinds.Kind.LIST, + values: valuesNodes + }; } - })); - Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ - enumerable: true, - get: function () { - return _index4.SingleFieldSubscriptionsRule; + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(value)) { + return null; } - })); - Object.defineProperty(exports, "Source", ({ - enumerable: true, - get: function () { - return _index2.Source; + const fieldNodes = []; + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name + }, + value: fieldValue + }); + } } - })); - Object.defineProperty(exports, "Token", ({ - enumerable: true, - get: function () { - return _index2.Token; + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes + }; + } + if ((0, _definition.isLeafType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + if (serialized == null) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + if (typeof serialized === 'boolean') { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized + }; + } // JavaScript numbers can be Int or Float values. + + if (typeof serialized === 'number' && Number.isFinite(serialized)) { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) ? { + kind: _kinds.Kind.INT, + value: stringNum + } : { + kind: _kinds.Kind.FLOAT, + value: stringNum + }; } - })); - Object.defineProperty(exports, "TokenKind", ({ - enumerable: true, - get: function () { - return _index2.TokenKind; + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized + }; + } // ID types can use Int literals. + + if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: _kinds.Kind.INT, + value: serialized + }; + } + return { + kind: _kinds.Kind.STRING, + value: serialized + }; } - })); - Object.defineProperty(exports, "TypeInfo", ({ - enumerable: true, - get: function () { - return _index6.TypeInfo; + throw new TypeError(`Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + +const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/buildASTSchema.mjs": +/*!******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/buildASTSchema.mjs ***! + \******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.buildASTSchema = buildASTSchema; +exports.buildSchema = buildSchema; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); +var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); +var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); +var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + */ +function buildASTSchema(documentAST, options) { + documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { + (0, _validate.assertValidSDL)(documentAST); + } + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false + }; + const config = (0, _extendSchema.extendSchemaImpl)(emptySchemaConfig, documentAST, options); + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + case 'Query': + // @ts-expect-error validated in `validateSchema` + config.query = type; + break; + case 'Mutation': + // @ts-expect-error validated in `validateSchema` + config.mutation = type; + break; + case 'Subscription': + // @ts-expect-error validated in `validateSchema` + config.subscription = type; + break; + } } - })); - Object.defineProperty(exports, "TypeKind", ({ - enumerable: true, - get: function () { - return _index.TypeKind; + } + const directives = [...config.directives, + // If specified directives were not explicitly declared, add them. + ..._directives.specifiedDirectives.filter(stdDirective => config.directives.every(directive => directive.name !== stdDirective.name))]; + return new _schema.GraphQLSchema({ + ...config, + directives + }); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + +function buildSchema(source, options) { + const document = (0, _parser.parse)(source, { + noLocation: options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacyFragmentVariables: options === null || options === void 0 ? void 0 : options.allowLegacyFragmentVariables + }); + return buildASTSchema(document, { + assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid + }); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/buildClientSchema.mjs": +/*!*********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/buildClientSchema.mjs ***! + \*********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.buildClientSchema = buildClientSchema; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); +var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); +var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ + +function buildClientSchema(introspection, options) { + (0, _isObjectLike.isObjectLike)(introspection) && (0, _isObjectLike.isObjectLike)(introspection.__schema) || (0, _devAssert.devAssert)(false, `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, _inspect.inspect)(introspection)}.`); // Get the schema from the introspection result. + + const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + const typeMap = (0, _keyValMap.keyValMap)(schemaIntrospection.types, typeIntrospection => typeIntrospection.name, typeIntrospection => buildType(typeIntrospection)); // Include standard types only if they are used. + + for (const stdType of [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes]) { + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; } - })); - Object.defineProperty(exports, "TypeMetaFieldDef", ({ - enumerable: true, - get: function () { - return _index.TypeMetaFieldDef; + } // Get the root Query, Mutation, and Subscription types. + + const queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + const mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + const subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + const directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: Object.values(typeMap), + directives, + assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + const itemRef = typeRef.ofType; + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + return new _definition.GraphQLList(getType(itemRef)); } - })); - Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ - enumerable: true, - get: function () { - return _index.TypeNameMetaFieldDef; + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + const nullableType = getType(nullableRef); + return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType)); } - })); - Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueArgumentDefinitionNamesRule; + return getNamedType(typeRef); + } + function getNamedType(typeRef) { + const typeName = typeRef.name; + if (!typeName) { + throw new Error(`Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`); } - })); - Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueArgumentNamesRule; + const type = typeMap[typeName]; + if (!type) { + throw new Error(`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`); } - })); - Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueDirectiveNamesRule; + return type; + } + function getObjectType(typeRef) { + return (0, _definition.assertObjectType)(getNamedType(typeRef)); + } + function getInterfaceType(typeRef) { + return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + function buildType(type) { + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (type != null && type.name != null && type.kind != null) { + // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + const typeStr = (0, _inspect.inspect)(type); + throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`); + } + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL + }); + } + function buildImplementationsList(implementingIntrospection) { + // TODO: Temporary workaround until GraphQL ecosystem will fully support + // 'interfaces' on interface types. + if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === _introspection.TypeKind.INTERFACE) { + return []; } - })); - Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueDirectivesPerLocationRule; + if (!implementingIntrospection.interfaces) { + const implementingIntrospectionStr = (0, _inspect.inspect)(implementingIntrospection); + throw new Error(`Introspection result missing interfaces: ${implementingIntrospectionStr}.`); } - })); - Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueEnumValueNamesRule; + return implementingIntrospection.interfaces.map(getInterfaceType); + } + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection) + }); + } + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection) + }); + } + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); + throw new Error(`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`); } - })); - Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueFieldDefinitionNamesRule; + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType) + }); + } + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); + throw new Error(`Introspection result missing enumValues: ${enumIntrospectionStr}.`); + } + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.keyValMap)(enumIntrospection.enumValues, valueIntrospection => valueIntrospection.name, valueIntrospection => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + })) + }); + } + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + const inputObjectIntrospectionStr = (0, _inspect.inspect)(inputObjectIntrospection); + throw new Error(`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`); } - })); - Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueFragmentNamesRule; - } - })); - Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueInputFieldNamesRule; - } - })); - Object.defineProperty(exports, "UniqueOperationNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueOperationNamesRule; - } - })); - Object.defineProperty(exports, "UniqueOperationTypesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueOperationTypesRule; - } - })); - Object.defineProperty(exports, "UniqueTypeNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueTypeNamesRule; + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields) + }); + } + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error(`Introspection result missing fields: ${(0, _inspect.inspect)(typeIntrospection)}.`); } - })); - Object.defineProperty(exports, "UniqueVariableNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueVariableNamesRule; + return (0, _keyValMap.keyValMap)(typeIntrospection.fields, fieldIntrospection => fieldIntrospection.name, buildField); + } + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); + if (!(0, _definition.isOutputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error(`Introspection must provide output type for fields, but received: ${typeStr}.`); } - })); - Object.defineProperty(exports, "ValidationContext", ({ - enumerable: true, - get: function () { - return _index4.ValidationContext; + if (!fieldIntrospection.args) { + const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); + throw new Error(`Introspection result missing field args: ${fieldIntrospectionStr}.`); } - })); - Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _index4.ValuesOfCorrectTypeRule; + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args) + }; + } + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.keyValMap)(inputValueIntrospections, inputValue => inputValue.name, buildInputValue); + } + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); + if (!(0, _definition.isInputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error(`Introspection must provide input type for arguments, but received: ${typeStr}.`); } - })); - Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ - enumerable: true, - get: function () { - return _index4.VariablesAreInputTypesRule; + const defaultValue = inputValueIntrospection.defaultValue != null ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason + }; + } + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); + throw new Error(`Introspection result missing directive args: ${directiveIntrospectionStr}.`); + } + if (!directiveIntrospection.locations) { + const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); + throw new Error(`Introspection result missing directive locations: ${directiveIntrospectionStr}.`); + } + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/coerceInputValue.mjs": +/*!********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/coerceInputValue.mjs ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.coerceInputValue = coerceInputValue; +var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); +var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); +var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); +var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); +var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Coerces a JavaScript value given a GraphQL Input Type. + */ +function coerceInputValue(inputValue, type, onError = defaultOnError) { + return coerceInputValueImpl(inputValue, type, onError, undefined); +} +function defaultOnError(path, invalidValue, error) { + let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); + if (path.length > 0) { + errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; + } + error.message = errorPrefix + ': ' + error.message; + throw error; +} +function coerceInputValueImpl(inputValue, type, onError, path) { + if ((0, _definition.isNonNullType)(type)) { + if (inputValue != null) { + return coerceInputValueImpl(inputValue, type.ofType, onError, path); + } + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected non-nullable type "${(0, _inspect.inspect)(type)}" not to be null.`)); + return; + } + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if ((0, _isIterableObject.isIterableObject)(inputValue)) { + return Array.from(inputValue, (itemValue, index) => { + const itemPath = (0, _Path.addPath)(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + } // Lists accept a non-list value as a list of one. + + return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(inputValue)) { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}" to be an object.`)); + return; } - })); - Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ - enumerable: true, - get: function () { - return _index4.VariablesInAllowedPositionRule; + const coercedValue = {}; + const fieldDefs = type.getFields(); + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + const typeStr = (0, _inspect.inspect)(field.type); + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${field.name}" of required type "${typeStr}" was not provided.`)); + } + continue; + } + coercedValue[field.name] = coerceInputValueImpl(fieldValue, field.type, onError, (0, _Path.addPath)(path, field.name, type.name)); + } // Ensure every provided field is defined. + + for (const fieldName of Object.keys(inputValue)) { + if (!fieldDefs[fieldName]) { + const suggestions = (0, _suggestionList.suggestionList)(fieldName, Object.keys(type.getFields())); + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${fieldName}" is not defined by type "${type.name}".` + (0, _didYouMean.didYouMean)(suggestions))); + } } - })); - Object.defineProperty(exports, "__Directive", ({ - enumerable: true, - get: function () { - return _index.__Directive; + return coercedValue; + } + if ((0, _definition.isLeafType)(type)) { + let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), + // which can throw to indicate failure. If it throws, maintain a reference + // to the original error. + + try { + parseResult = type.parseValue(inputValue); + } catch (error) { + if (error instanceof _GraphQLError.GraphQLError) { + onError((0, _Path.pathToArray)(path), inputValue, error); + } else { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}". ` + error.message, { + originalError: error + })); + } + return; } - })); - Object.defineProperty(exports, "__DirectiveLocation", ({ - enumerable: true, - get: function () { - return _index.__DirectiveLocation; + if (parseResult === undefined) { + onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}".`)); } - })); - Object.defineProperty(exports, "__EnumValue", ({ - enumerable: true, - get: function () { - return _index.__EnumValue; + return parseResult; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/concatAST.mjs": +/*!*************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/concatAST.mjs ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.concatAST = concatAST; +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ + +function concatAST(documents) { + const definitions = []; + for (const doc of documents) { + definitions.push(...doc.definitions); + } + return { + kind: _kinds.Kind.DOCUMENT, + definitions + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/extendSchema.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/extendSchema.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extendSchema = extendSchema; +exports.extendSchemaImpl = extendSchemaImpl; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _predicates = __webpack_require__(/*! ../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); +var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); +var _values = __webpack_require__(/*! ../execution/values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); +var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + */ +function extendSchema(schema, documentAST, options) { + (0, _schema.assertSchema)(schema); + documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); + } + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); + return schemaConfig === extendedConfig ? schema : new _schema.GraphQLSchema(extendedConfig); +} +/** + * @internal + */ + +function extendSchemaImpl(schemaConfig, documentAST, options) { + var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; + + // Collect the type definitions and extensions found in the document. + const typeDefs = []; + const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + const directiveDefs = []; + let schemaDef; // Schema extensions are collected which may add additional operation types. + + const schemaExtensions = []; + for (const def of documentAST.definitions) { + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + typeDefs.push(def); + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + const extendedTypeName = def.name.value; + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) { + return schemaConfig; + } + const typeMap = Object.create(null); + for (const existingType of schemaConfig.types) { + typeMap[existingType.name] = extendNamedType(existingType); + } + for (const typeNode of typeDefs) { + var _stdTypeMap$name; + const name = typeNode.name.value; + typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode); + } + const operationTypes = { + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), + // Then, incorporate schema definition and all schema extensions. + ...(schemaDef && getOperationTypes([schemaDef])), + ...getOperationTypes(schemaExtensions) + }; // Then produce and return a Schema config with these types. + + return { + description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value, + ...operationTypes, + types: Object.values(typeMap), + directives: [...schemaConfig.directives.map(replaceDirective), ...directiveDefs.map(buildDirective)], + extensions: Object.create(null), + astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode, + extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: (_options$assumeValid = options === null || options === void 0 ? void 0 : options.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false + }; // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); } - })); - Object.defineProperty(exports, "__Field", ({ - enumerable: true, - get: function () { - return _index.__Field; + if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME + + return replaceNamedType(type); + } + function replaceNamedType(type) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return typeMap[type.name]; + } + function replaceDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + args: (0, _mapValue.mapValue)(config.args, extendArg) + }); + } + function extendNamedType(type) { + if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) { + // Builtin types are not extended. + return type; } - })); - Object.defineProperty(exports, "__InputValue", ({ - enumerable: true, - get: function () { - return _index.__InputValue; + if ((0, _definition.isScalarType)(type)) { + return extendScalarType(type); } - })); - Object.defineProperty(exports, "__Schema", ({ - enumerable: true, - get: function () { - return _index.__Schema; + if ((0, _definition.isObjectType)(type)) { + return extendObjectType(type); } - })); - Object.defineProperty(exports, "__Type", ({ - enumerable: true, - get: function () { - return _index.__Type; + if ((0, _definition.isInterfaceType)(type)) { + return extendInterfaceType(type); } - })); - Object.defineProperty(exports, "__TypeKind", ({ - enumerable: true, - get: function () { - return _index.__TypeKind; + if ((0, _definition.isUnionType)(type)) { + return extendUnionType(type); } - })); - Object.defineProperty(exports, "assertAbstractType", ({ - enumerable: true, - get: function () { - return _index.assertAbstractType; + if ((0, _definition.isEnumType)(type)) { + return extendEnumType(type); } - })); - Object.defineProperty(exports, "assertCompositeType", ({ - enumerable: true, - get: function () { - return _index.assertCompositeType; + if ((0, _definition.isInputObjectType)(type)) { + return extendInputObjectType(type); } - })); - Object.defineProperty(exports, "assertDirective", ({ - enumerable: true, - get: function () { - return _index.assertDirective; + /* c8 ignore next 3 */ + // Not reachable, all possible type definition nodes have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : []; + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, field => ({ + ...field, + type: replaceType(field.type) + })), + ...buildInputFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendEnumType(type) { + var _typeExtensionsMap$ty; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : []; + return new _definition.GraphQLEnumType({ + ...config, + values: { + ...config.values, + ...buildEnumValueMap(extensions) + }, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendScalarType(type) { + var _typeExtensionsMap$co2; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : []; + let specifiedByURL = config.specifiedByURL; + for (const extensionNode of extensions) { + var _getSpecifiedByURL; + specifiedByURL = (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && _getSpecifiedByURL !== void 0 ? _getSpecifiedByURL : specifiedByURL; } - })); - Object.defineProperty(exports, "assertEnumType", ({ - enumerable: true, - get: function () { - return _index.assertEnumType; + return new _definition.GraphQLScalarType({ + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendObjectType(type) { + var _typeExtensionsMap$co3; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : []; + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : []; + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendUnionType(type) { + var _typeExtensionsMap$co5; + const config = type.toConfig(); + const extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : []; + return new _definition.GraphQLUnionType({ + ...config, + types: () => [...type.getTypes().map(replaceNamedType), ...buildUnionTypes(extensions)], + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }); + } + function extendField(field) { + return { + ...field, + type: replaceType(field.type), + args: field.args && (0, _mapValue.mapValue)(field.args, extendArg) + }; + } + function extendArg(arg) { + return { + ...arg, + type: replaceType(arg.type) + }; + } + function getOperationTypes(nodes) { + const opTypes = {}; + for (const node of nodes) { + var _node$operationTypes; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const operationTypesNodes = /* c8 ignore next */ + (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + for (const operationType of operationTypesNodes) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + opTypes[operationType.operation] = getNamedType(operationType.type); + } } - })); - Object.defineProperty(exports, "assertEnumValueName", ({ - enumerable: true, - get: function () { - return _index.assertEnumValueName; + return opTypes; + } + function getNamedType(node) { + var _stdTypeMap$name2; + const name = node.name.value; + const type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name]; + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); } - })); - Object.defineProperty(exports, "assertInputObjectType", ({ - enumerable: true, - get: function () { - return _index.assertInputObjectType; + return type; + } + function getWrappedType(node) { + if (node.kind === _kinds.Kind.LIST_TYPE) { + return new _definition.GraphQLList(getWrappedType(node.type)); } - })); - Object.defineProperty(exports, "assertInputType", ({ - enumerable: true, - get: function () { - return _index.assertInputType; + if (node.kind === _kinds.Kind.NON_NULL_TYPE) { + return new _definition.GraphQLNonNull(getWrappedType(node.type)); } - })); - Object.defineProperty(exports, "assertInterfaceType", ({ - enumerable: true, - get: function () { - return _index.assertInterfaceType; + return getNamedType(node); + } + function buildDirective(node) { + var _node$description; + return new _directives.GraphQLDirective({ + name: node.name.value, + description: (_node$description = node.description) === null || _node$description === void 0 ? void 0 : _node$description.value, + // @ts-expect-error + locations: node.locations.map(({ + value + }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node + }); + } + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + for (const node of nodes) { + var _node$fields; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const nodeFields = /* c8 ignore next */ + (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + for (const field of nodeFields) { + var _field$description; + fieldConfigMap[field.name.value] = { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: getWrappedType(field.type), + description: (_field$description = field.description) === null || _field$description === void 0 ? void 0 : _field$description.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } } - })); - Object.defineProperty(exports, "assertLeafType", ({ - enumerable: true, - get: function () { - return _index.assertLeafType; + return fieldConfigMap; + } + function buildArgumentMap(args) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const argsNodes = /* c8 ignore next */ + args !== null && args !== void 0 ? args : []; + const argConfigMap = Object.create(null); + for (const arg of argsNodes) { + var _arg$description; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type, + description: (_arg$description = arg.description) === null || _arg$description === void 0 ? void 0 : _arg$description.value, + defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg + }; } - })); - Object.defineProperty(exports, "assertListType", ({ - enumerable: true, - get: function () { - return _index.assertListType; + return argConfigMap; + } + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + for (const node of nodes) { + var _node$fields2; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fieldsNodes = /* c8 ignore next */ + (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []; + for (const field of fieldsNodes) { + var _field$description2; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type, + description: (_field$description2 = field.description) === null || _field$description2 === void 0 ? void 0 : _field$description2.value, + defaultValue: (0, _valueFromAST.valueFromAST)(field.defaultValue, type), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } } - })); - Object.defineProperty(exports, "assertName", ({ - enumerable: true, - get: function () { - return _index.assertName; + return inputFieldMap; + } + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); + for (const node of nodes) { + var _node$values; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const valuesNodes = /* c8 ignore next */ + (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + for (const value of valuesNodes) { + var _value$description; + enumValueMap[value.name.value] = { + description: (_value$description = value.description) === null || _value$description === void 0 ? void 0 : _value$description.value, + deprecationReason: getDeprecationReason(value), + astNode: value + }; + } } - })); - Object.defineProperty(exports, "assertNamedType", ({ - enumerable: true, - get: function () { - return _index.assertNamedType; - } - })); - Object.defineProperty(exports, "assertNonNullType", ({ - enumerable: true, - get: function () { - return _index.assertNonNullType; - } - })); - Object.defineProperty(exports, "assertNullableType", ({ - enumerable: true, - get: function () { - return _index.assertNullableType; - } - })); - Object.defineProperty(exports, "assertObjectType", ({ - enumerable: true, - get: function () { - return _index.assertObjectType; - } - })); - Object.defineProperty(exports, "assertOutputType", ({ - enumerable: true, - get: function () { - return _index.assertOutputType; - } - })); - Object.defineProperty(exports, "assertScalarType", ({ - enumerable: true, - get: function () { - return _index.assertScalarType; - } - })); - Object.defineProperty(exports, "assertSchema", ({ - enumerable: true, - get: function () { - return _index.assertSchema; - } - })); - Object.defineProperty(exports, "assertType", ({ - enumerable: true, - get: function () { - return _index.assertType; - } - })); - Object.defineProperty(exports, "assertUnionType", ({ - enumerable: true, - get: function () { - return _index.assertUnionType; - } - })); - Object.defineProperty(exports, "assertValidName", ({ - enumerable: true, - get: function () { - return _index6.assertValidName; + return enumValueMap; + } + function buildInterfaces(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + node => { + var _node$interfaces$map, _node$interfaces; + return /* c8 ignore next */( + (_node$interfaces$map = (_node$interfaces = node.interfaces) === null || _node$interfaces === void 0 ? void 0 : _node$interfaces.map(getNamedType)) !== null && _node$interfaces$map !== void 0 ? _node$interfaces$map : [] + ); + }); + } + function buildUnionTypes(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + node => { + var _node$types$map, _node$types; + return /* c8 ignore next */( + (_node$types$map = (_node$types = node.types) === null || _node$types === void 0 ? void 0 : _node$types.map(getNamedType)) !== null && _node$types$map !== void 0 ? _node$types$map : [] + ); + }); + } + function buildType(astNode) { + var _typeExtensionsMap$na; + const name = astNode.name.value; + const extensionASTNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : []; + switch (astNode.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + { + var _astNode$description; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLObjectType({ + name, + description: (_astNode$description = astNode.description) === null || _astNode$description === void 0 ? void 0 : _astNode$description.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + { + var _astNode$description2; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInterfaceType({ + name, + description: (_astNode$description2 = astNode.description) === null || _astNode$description2 === void 0 ? void 0 : _astNode$description2.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.ENUM_TYPE_DEFINITION: + { + var _astNode$description3; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLEnumType({ + name, + description: (_astNode$description3 = astNode.description) === null || _astNode$description3 === void 0 ? void 0 : _astNode$description3.value, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.UNION_TYPE_DEFINITION: + { + var _astNode$description4; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLUnionType({ + name, + description: (_astNode$description4 = astNode.description) === null || _astNode$description4 === void 0 ? void 0 : _astNode$description4.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + { + var _astNode$description5; + return new _definition.GraphQLScalarType({ + name, + description: (_astNode$description5 = astNode.description) === null || _astNode$description5 === void 0 ? void 0 : _astNode$description5.value, + specifiedByURL: getSpecifiedByURL(astNode), + astNode, + extensionASTNodes + }); + } + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + { + var _astNode$description6; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInputObjectType({ + name, + description: (_astNode$description6 = astNode.description) === null || _astNode$description6 === void 0 ? void 0 : _astNode$description6.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } } - })); - Object.defineProperty(exports, "assertValidSchema", ({ - enumerable: true, - get: function () { - return _index.assertValidSchema; + } +} +const stdTypeMap = (0, _keyMap.keyMap)([..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], type => type.name); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + +function getDeprecationReason(node) { + const deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues` + + return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason; +} +/** + * Given a scalar node, returns the string value for the specifiedByURL. + */ + +function getSpecifiedByURL(node) { + const specifiedBy = (0, _values.getDirectiveValues)(_directives.GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues` + + return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs": +/*!***********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/findBreakingChanges.mjs ***! + \***********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DangerousChangeType = exports.BreakingChangeType = void 0; +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); +var _sortValueNode = __webpack_require__(/*! ./sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); +var BreakingChangeType; +(function (BreakingChangeType) { + BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; + BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; + BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; + BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; + BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = 'REQUIRED_INPUT_FIELD_ADDED'; + BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = 'IMPLEMENTED_INTERFACE_REMOVED'; + BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; + BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; + BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; + BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; + BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; + BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; + BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; + BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = 'REQUIRED_DIRECTIVE_ARG_ADDED'; + BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = 'DIRECTIVE_REPEATABLE_REMOVED'; + BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = 'DIRECTIVE_LOCATION_REMOVED'; +})(BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {})); +var DangerousChangeType; +(function (DangerousChangeType) { + DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; + DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; + DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = 'OPTIONAL_INPUT_FIELD_ADDED'; + DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; + DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = 'IMPLEMENTED_INTERFACE_ADDED'; + DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; +})(DangerousChangeType || (exports.DangerousChangeType = DangerousChangeType = {})); +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +function findBreakingChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in BreakingChangeType); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ + +function findDangerousChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in DangerousChangeType); +} +function findSchemaChanges(oldSchema, newSchema) { + return [...findTypeChanges(oldSchema, newSchema), ...findDirectiveChanges(oldSchema, newSchema)]; +} +function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${oldDirective.name} was removed.` + }); + } + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.` + }); + } } - })); - Object.defineProperty(exports, "assertWrappingType", ({ - enumerable: true, - get: function () { - return _index.assertWrappingType; + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${oldArg.name} was removed from ${oldDirective.name}.` + }); } - })); - Object.defineProperty(exports, "astFromValue", ({ - enumerable: true, - get: function () { - return _index6.astFromValue; + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective.name}.` + }); } - })); - Object.defineProperty(exports, "buildASTSchema", ({ - enumerable: true, - get: function () { - return _index6.buildASTSchema; + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.` + }); + } } - })); - Object.defineProperty(exports, "buildClientSchema", ({ - enumerable: true, - get: function () { - return _index6.buildClientSchema; + } + return schemaChanges; +} +function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff(Object.values(oldSchema.getTypeMap()), Object.values(newSchema.getTypeMap())); + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: (0, _scalars.isSpecifiedScalarType)(oldType) ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` : `${oldType.name} was removed.` + }); + } + for (const [oldType, newType] of typesDiff.persisted) { + if ((0, _definition.isEnumType)(oldType) && (0, _definition.isEnumType)(newType)) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if ((0, _definition.isUnionType)(oldType) && (0, _definition.isUnionType)(newType)) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if ((0, _definition.isInputObjectType)(oldType) && (0, _definition.isInputObjectType)(newType)) { + schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); + } else if ((0, _definition.isObjectType)(oldType) && (0, _definition.isObjectType)(newType)) { + schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); + } else if ((0, _definition.isInterfaceType)(oldType) && (0, _definition.isInterfaceType)(newType)) { + schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: `${oldType.name} changed from ` + `${typeKindName(oldType)} to ${typeKindName(newType)}.` + }); } - })); - Object.defineProperty(exports, "buildSchema", ({ - enumerable: true, - get: function () { - return _index6.buildSchema; + } + return schemaChanges; +} +function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); + for (const newField of fieldsDiff.added) { + if ((0, _definition.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField.name} on input type ${oldType.name} was added.` + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField.name} on input type ${oldType.name} was added.` + }); } - })); - Object.defineProperty(exports, "coerceInputValue", ({ - enumerable: true, - get: function () { - return _index6.coerceInputValue; + } + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.` + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldField.type, newField.type); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` + }); } - })); - Object.defineProperty(exports, "concatAST", ({ - enumerable: true, - get: function () { - return _index6.concatAST; + } + return schemaChanges; +} +function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType.name} was added to union type ${oldType.name}.` + }); + } + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType.name} was removed from union type ${oldType.name}.` + }); + } + return schemaChanges; +} +function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${newValue.name} was added to enum type ${oldType.name}.` + }); + } + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${oldValue.name} was removed from enum type ${oldType.name}.` + }); + } + return schemaChanges; +} +function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.` + }); + } + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType.name} no longer implements interface ${oldInterface.name}.` + }); + } + return schemaChanges; +} +function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.` + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldType, oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField(oldField.type, newField.type); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` + }); } - })); - Object.defineProperty(exports, "createSourceEventStream", ({ - enumerable: true, - get: function () { - return _index3.createSourceEventStream; + } + return schemaChanges; +} +function findArgChanges(oldType, oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.` + }); + } + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArg.type, newArg.type); + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` + }); + } else if (oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.` + }); + } else { + // Since we looking only for client's observable changes we should + // compare default values in the same representation as they are + // represented inside introspection. + const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); + const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.` + }); + } + } } - })); - Object.defineProperty(exports, "defaultFieldResolver", ({ - enumerable: true, - get: function () { - return _index3.defaultFieldResolver; + } + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` + }); } - })); - Object.defineProperty(exports, "defaultTypeResolver", ({ - enumerable: true, - get: function () { - return _index3.defaultTypeResolver; + } + return schemaChanges; +} +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || + // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } + if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + return ( + // if they're both named types, see if their names are equivalent + (0, _definition.isNamedType)(newType) && oldType.name === newType.name || + // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); +} +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } + if ((0, _definition.isNonNullType)(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || + // moving from non-null to nullable of the same underlying type is safe + !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) + ); + } // if they're both named types, see if their names are equivalent + + return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; +} +function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return 'a Scalar type'; + } + if ((0, _definition.isObjectType)(type)) { + return 'an Object type'; + } + if ((0, _definition.isInterfaceType)(type)) { + return 'an Interface type'; + } + if ((0, _definition.isUnionType)(type)) { + return 'a Union type'; + } + if ((0, _definition.isEnumType)(type)) { + return 'an Enum type'; + } + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); +} +function stringifyValue(value, type) { + const ast = (0, _astFromValue.astFromValue)(value, type); + ast != null || (0, _invariant.invariant)(false); + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); +} +function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = (0, _keyMap.keyMap)(oldArray, ({ + name + }) => name); + const newMap = (0, _keyMap.keyMap)(newArray, ({ + name + }) => name); + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); } - })); - Object.defineProperty(exports, "doTypesOverlap", ({ - enumerable: true, - get: function () { - return _index6.doTypesOverlap; + } + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); } - })); - Object.defineProperty(exports, "execute", ({ - enumerable: true, - get: function () { - return _index3.execute; + } + return { + added, + persisted, + removed + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs": +/*!*************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs ***! + \*************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getIntrospectionQuery = getIntrospectionQuery; +/** + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. + */ +function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + ...options + }; + const descriptions = optionsWithDefault.descriptions ? 'description' : ''; + const specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByURL' : ''; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : ''; + const schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ''; + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + ${descriptions} + ${directiveIsRepeatable} + locations + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + } + } } - })); - Object.defineProperty(exports, "executeSync", ({ - enumerable: true, - get: function () { - return _index3.executeSync; + + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } } - })); - Object.defineProperty(exports, "extendSchema", ({ - enumerable: true, - get: function () { - return _index6.extendSchema; + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation('isDeprecated')} + ${inputDeprecation('deprecationReason')} } - })); - Object.defineProperty(exports, "findBreakingChanges", ({ - enumerable: true, - get: function () { - return _index6.findBreakingChanges; - } - })); - Object.defineProperty(exports, "findDangerousChanges", ({ - enumerable: true, - get: function () { - return _index6.findDangerousChanges; - } - })); - Object.defineProperty(exports, "formatError", ({ - enumerable: true, - get: function () { - return _index5.formatError; - } - })); - Object.defineProperty(exports, "getArgumentValues", ({ - enumerable: true, - get: function () { - return _index3.getArgumentValues; + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } + } } - })); - Object.defineProperty(exports, "getDirectiveValues", ({ - enumerable: true, - get: function () { - return _index3.getDirectiveValues; + `; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/getOperationAST.mjs": +/*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getOperationAST.mjs ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getOperationAST = getOperationAST; +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ + +function getOperationAST(documentAST, operationName) { + let operation = null; + for (const definition of documentAST.definitions) { + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + var _definition$name; + if (operationName == null) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + operation = definition; + } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { + return definition; + } } - })); - Object.defineProperty(exports, "getEnterLeaveForKind", ({ - enumerable: true, - get: function () { - return _index2.getEnterLeaveForKind; + } + return operation; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/getOperationRootType.mjs": +/*!************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/getOperationRootType.mjs ***! + \************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getOperationRootType = getOperationRootType; +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Extracts the root type of the operation from the schema. + * + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 + */ +function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + const queryType = schema.getQueryType(); + if (!queryType) { + throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', { + nodes: operation + }); } - })); - Object.defineProperty(exports, "getIntrospectionQuery", ({ - enumerable: true, - get: function () { - return _index6.getIntrospectionQuery; + return queryType; + } + if (operation.operation === 'mutation') { + const mutationType = schema.getMutationType(); + if (!mutationType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', { + nodes: operation + }); } - })); - Object.defineProperty(exports, "getLocation", ({ - enumerable: true, - get: function () { - return _index2.getLocation; + return mutationType; + } + if (operation.operation === 'subscription') { + const subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', { + nodes: operation + }); } - })); - Object.defineProperty(exports, "getNamedType", ({ - enumerable: true, - get: function () { - return _index.getNamedType; + return subscriptionType; + } + throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', { + nodes: operation + }); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/index.mjs": +/*!*********************************************************!*\ + !*** ../../../node_modules/graphql/utilities/index.mjs ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "BreakingChangeType", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.BreakingChangeType; + } +})); +Object.defineProperty(exports, "DangerousChangeType", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.DangerousChangeType; + } +})); +Object.defineProperty(exports, "TypeInfo", ({ + enumerable: true, + get: function () { + return _TypeInfo.TypeInfo; + } +})); +Object.defineProperty(exports, "assertValidName", ({ + enumerable: true, + get: function () { + return _assertValidName.assertValidName; + } +})); +Object.defineProperty(exports, "astFromValue", ({ + enumerable: true, + get: function () { + return _astFromValue.astFromValue; + } +})); +Object.defineProperty(exports, "buildASTSchema", ({ + enumerable: true, + get: function () { + return _buildASTSchema.buildASTSchema; + } +})); +Object.defineProperty(exports, "buildClientSchema", ({ + enumerable: true, + get: function () { + return _buildClientSchema.buildClientSchema; + } +})); +Object.defineProperty(exports, "buildSchema", ({ + enumerable: true, + get: function () { + return _buildASTSchema.buildSchema; + } +})); +Object.defineProperty(exports, "coerceInputValue", ({ + enumerable: true, + get: function () { + return _coerceInputValue.coerceInputValue; + } +})); +Object.defineProperty(exports, "concatAST", ({ + enumerable: true, + get: function () { + return _concatAST.concatAST; + } +})); +Object.defineProperty(exports, "doTypesOverlap", ({ + enumerable: true, + get: function () { + return _typeComparators.doTypesOverlap; + } +})); +Object.defineProperty(exports, "extendSchema", ({ + enumerable: true, + get: function () { + return _extendSchema.extendSchema; + } +})); +Object.defineProperty(exports, "findBreakingChanges", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.findBreakingChanges; + } +})); +Object.defineProperty(exports, "findDangerousChanges", ({ + enumerable: true, + get: function () { + return _findBreakingChanges.findDangerousChanges; + } +})); +Object.defineProperty(exports, "getIntrospectionQuery", ({ + enumerable: true, + get: function () { + return _getIntrospectionQuery.getIntrospectionQuery; + } +})); +Object.defineProperty(exports, "getOperationAST", ({ + enumerable: true, + get: function () { + return _getOperationAST.getOperationAST; + } +})); +Object.defineProperty(exports, "getOperationRootType", ({ + enumerable: true, + get: function () { + return _getOperationRootType.getOperationRootType; + } +})); +Object.defineProperty(exports, "introspectionFromSchema", ({ + enumerable: true, + get: function () { + return _introspectionFromSchema.introspectionFromSchema; + } +})); +Object.defineProperty(exports, "isEqualType", ({ + enumerable: true, + get: function () { + return _typeComparators.isEqualType; + } +})); +Object.defineProperty(exports, "isTypeSubTypeOf", ({ + enumerable: true, + get: function () { + return _typeComparators.isTypeSubTypeOf; + } +})); +Object.defineProperty(exports, "isValidNameError", ({ + enumerable: true, + get: function () { + return _assertValidName.isValidNameError; + } +})); +Object.defineProperty(exports, "lexicographicSortSchema", ({ + enumerable: true, + get: function () { + return _lexicographicSortSchema.lexicographicSortSchema; + } +})); +Object.defineProperty(exports, "printIntrospectionSchema", ({ + enumerable: true, + get: function () { + return _printSchema.printIntrospectionSchema; + } +})); +Object.defineProperty(exports, "printSchema", ({ + enumerable: true, + get: function () { + return _printSchema.printSchema; + } +})); +Object.defineProperty(exports, "printType", ({ + enumerable: true, + get: function () { + return _printSchema.printType; + } +})); +Object.defineProperty(exports, "separateOperations", ({ + enumerable: true, + get: function () { + return _separateOperations.separateOperations; + } +})); +Object.defineProperty(exports, "stripIgnoredCharacters", ({ + enumerable: true, + get: function () { + return _stripIgnoredCharacters.stripIgnoredCharacters; + } +})); +Object.defineProperty(exports, "typeFromAST", ({ + enumerable: true, + get: function () { + return _typeFromAST.typeFromAST; + } +})); +Object.defineProperty(exports, "valueFromAST", ({ + enumerable: true, + get: function () { + return _valueFromAST.valueFromAST; + } +})); +Object.defineProperty(exports, "valueFromASTUntyped", ({ + enumerable: true, + get: function () { + return _valueFromASTUntyped.valueFromASTUntyped; + } +})); +Object.defineProperty(exports, "visitWithTypeInfo", ({ + enumerable: true, + get: function () { + return _TypeInfo.visitWithTypeInfo; + } +})); +var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); +var _getOperationAST = __webpack_require__(/*! ./getOperationAST.mjs */ "../../../node_modules/graphql/utilities/getOperationAST.mjs"); +var _getOperationRootType = __webpack_require__(/*! ./getOperationRootType.mjs */ "../../../node_modules/graphql/utilities/getOperationRootType.mjs"); +var _introspectionFromSchema = __webpack_require__(/*! ./introspectionFromSchema.mjs */ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs"); +var _buildClientSchema = __webpack_require__(/*! ./buildClientSchema.mjs */ "../../../node_modules/graphql/utilities/buildClientSchema.mjs"); +var _buildASTSchema = __webpack_require__(/*! ./buildASTSchema.mjs */ "../../../node_modules/graphql/utilities/buildASTSchema.mjs"); +var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); +var _lexicographicSortSchema = __webpack_require__(/*! ./lexicographicSortSchema.mjs */ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs"); +var _printSchema = __webpack_require__(/*! ./printSchema.mjs */ "../../../node_modules/graphql/utilities/printSchema.mjs"); +var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); +var _valueFromASTUntyped = __webpack_require__(/*! ./valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); +var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); +var _TypeInfo = __webpack_require__(/*! ./TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); +var _coerceInputValue = __webpack_require__(/*! ./coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); +var _concatAST = __webpack_require__(/*! ./concatAST.mjs */ "../../../node_modules/graphql/utilities/concatAST.mjs"); +var _separateOperations = __webpack_require__(/*! ./separateOperations.mjs */ "../../../node_modules/graphql/utilities/separateOperations.mjs"); +var _stripIgnoredCharacters = __webpack_require__(/*! ./stripIgnoredCharacters.mjs */ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs"); +var _typeComparators = __webpack_require__(/*! ./typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); +var _assertValidName = __webpack_require__(/*! ./assertValidName.mjs */ "../../../node_modules/graphql/utilities/assertValidName.mjs"); +var _findBreakingChanges = __webpack_require__(/*! ./findBreakingChanges.mjs */ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs": +/*!***************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/introspectionFromSchema.mjs ***! + \***************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.introspectionFromSchema = introspectionFromSchema; +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); +var _execute = __webpack_require__(/*! ../execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); +var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ + +function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + ...options + }; + const document = (0, _parser.parse)((0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults)); + const result = (0, _execute.executeSync)({ + schema, + document + }); + !result.errors && result.data || (0, _invariant.invariant)(false); + return result.data; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs": +/*!***************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs ***! + \***************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.lexicographicSortSchema = lexicographicSortSchema; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); +var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ + +function lexicographicSortSchema(schema) { + const schemaConfig = schema.toConfig(); + const typeMap = (0, _keyValMap.keyValMap)(sortByName(schemaConfig.types), type => type.name, sortNamedType); + return new _schema.GraphQLSchema({ + ...schemaConfig, + types: Object.values(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription) + }); + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME: TS Conversion + + return replaceNamedType(type); + } + function replaceNamedType(type) { + return typeMap[type.name]; + } + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + function sortDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + locations: sortBy(config.locations, x => x), + args: sortArgs(config.args) + }); + } + function sortArgs(args) { + return sortObjMap(args, arg => ({ + ...arg, + type: replaceType(arg.type) + })); + } + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + ...field, + type: replaceType(field.type), + args: field.args && sortArgs(field.args) + })); + } + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + ...field, + type: replaceType(field.type) + })); + } + function sortTypes(array) { + return sortByName(array).map(replaceNamedType); + } + function sortNamedType(type) { + if ((0, _definition.isScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { + return type; } - })); - Object.defineProperty(exports, "getNullableType", ({ - enumerable: true, - get: function () { - return _index.getNullableType; + if ((0, _definition.isObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields) + }); } - })); - Object.defineProperty(exports, "getOperationAST", ({ - enumerable: true, - get: function () { - return _index6.getOperationAST; + if ((0, _definition.isInterfaceType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields) + }); } - })); - Object.defineProperty(exports, "getOperationRootType", ({ - enumerable: true, - get: function () { - return _index6.getOperationRootType; + if ((0, _definition.isUnionType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLUnionType({ + ...config, + types: () => sortTypes(config.types) + }); } - })); - Object.defineProperty(exports, "getVariableValues", ({ - enumerable: true, - get: function () { - return _index3.getVariableValues; + if ((0, _definition.isEnumType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLEnumType({ + ...config, + values: sortObjMap(config.values, value => value) + }); } - })); - Object.defineProperty(exports, "getVisitFn", ({ - enumerable: true, - get: function () { - return _index2.getVisitFn; + if ((0, _definition.isInputObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields) + }); } - })); - Object.defineProperty(exports, "graphql", ({ - enumerable: true, - get: function () { - return _graphql.graphql; + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); + } +} +function sortObjMap(map, sortValueFn) { + const sortedMap = Object.create(null); + for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { + sortedMap[key] = sortValueFn(map[key]); + } + return sortedMap; +} +function sortByName(array) { + return sortBy(array, obj => obj.name); +} +function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return (0, _naturalCompare.naturalCompare)(key1, key2); + }); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/printSchema.mjs": +/*!***************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/printSchema.mjs ***! + \***************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printSchema = printSchema; +exports.printType = printType; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); +function printSchema(schema) { + return printFilteredSchema(schema, n => !(0, _directives.isSpecifiedDirective)(n), isDefinedType); +} +function printIntrospectionSchema(schema) { + return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType); +} +function isDefinedType(type) { + return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); +} +function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [printSchemaDefinition(schema), ...directives.map(directive => printDirective(directive)), ...types.map(type => printType(type))].filter(Boolean).join('\n\n'); +} +function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + const operationTypes = []; + const queryType = schema.getQueryType(); + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + const mutationType = schema.getMutationType(); + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * ```graphql + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * ``` + * + * When using this naming convention, the schema description can be omitted. + */ + +function isSchemaOfCommonNames(schema) { + const queryType = schema.getQueryType(); + if (queryType && queryType.name !== 'Query') { + return false; + } + const mutationType = schema.getMutationType(); + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + return true; +} +function printType(type) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type); + } + if ((0, _definition.isObjectType)(type)) { + return printObject(type); + } + if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type); + } + if ((0, _definition.isUnionType)(type)) { + return printUnion(type); + } + if ((0, _definition.isEnumType)(type)) { + return printEnum(type); + } + if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); +} +function printScalar(type) { + return printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type); +} +function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length ? ' implements ' + interfaces.map(i => i.name).join(' & ') : ''; +} +function printObject(type) { + return printDescription(type) + `type ${type.name}` + printImplementedInterfaces(type) + printFields(type); +} +function printInterface(type) { + return printDescription(type) + `interface ${type.name}` + printImplementedInterfaces(type) + printFields(type); +} +function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(type) + 'union ' + type.name + possibleTypes; +} +function printEnum(type) { + const values = type.getValues().map((value, i) => printDescription(value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason)); + return printDescription(type) + `enum ${type.name}` + printBlock(values); +} +function printInputObject(type) { + const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f)); + return printDescription(type) + `input ${type.name}` + printBlock(fields); +} +function printFields(type) { + const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + f.name + printArgs(f.args, ' ') + ': ' + String(f.type) + printDeprecated(f.deprecationReason)); + return printBlock(fields); +} +function printBlock(items) { + return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; +} +function printArgs(args, indentation = '') { + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + if (args.every(arg => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + return '(\n' + args.map((arg, i) => printDescription(arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg)).join('\n') + '\n' + indentation + ')'; +} +function printInputValue(arg) { + const defaultAST = (0, _astFromValue.astFromValue)(arg.defaultValue, arg.type); + let argDecl = arg.name + ': ' + String(arg.type); + if (defaultAST) { + argDecl += ` = ${(0, _printer.print)(defaultAST)}`; + } + return argDecl + printDeprecated(arg.deprecationReason); +} +function printDirective(directive) { + return printDescription(directive) + 'directive @' + directive.name + printArgs(directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | '); +} +function printDeprecated(reason) { + if (reason == null) { + return ''; + } + if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: reason + }); + return ` @deprecated(reason: ${astValue})`; + } + return ' @deprecated'; +} +function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ''; + } + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: scalar.specifiedByURL + }); + return ` @specifiedBy(url: ${astValue})`; +} +function printDescription(def, indentation = '', firstInBlock = true) { + const { + description + } = def; + if (description == null) { + return ''; + } + const blockString = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: description, + block: (0, _blockString.isPrintableAsBlockString)(description) + }); + const prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/separateOperations.mjs": +/*!**********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/separateOperations.mjs ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.separateOperations = separateOperations; +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ + +function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + case _kinds.Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies(definitionNode.selectionSet); + break; + default: // ignore non-executable definitions } - })); - Object.defineProperty(exports, "graphqlSync", ({ - enumerable: true, - get: function () { - return _graphql.graphqlSync; + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + const separatedDocumentASTs = Object.create(null); + for (const operation of operations) { + const dependencies = new Set(); + for (const fragmentName of collectDependencies(operation.selectionSet)) { + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + separatedDocumentASTs[operationName] = { + kind: _kinds.Kind.DOCUMENT, + definitions: documentAST.definitions.filter(node => node === operation || node.kind === _kinds.Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value)) + }; + } + return separatedDocumentASTs; +} + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); + } } - })); - Object.defineProperty(exports, "introspectionFromSchema", ({ - enumerable: true, - get: function () { - return _index6.introspectionFromSchema; + } +} +function collectDependencies(selectionSet) { + const dependencies = []; + (0, _visitor.visit)(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); } - })); - Object.defineProperty(exports, "introspectionTypes", ({ - enumerable: true, - get: function () { - return _index.introspectionTypes; - } - })); - Object.defineProperty(exports, "isAbstractType", ({ - enumerable: true, - get: function () { - return _index.isAbstractType; - } - })); - Object.defineProperty(exports, "isCompositeType", ({ - enumerable: true, - get: function () { - return _index.isCompositeType; + }); + return dependencies; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/sortValueNode.mjs": +/*!*****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/sortValueNode.mjs ***! + \*****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.sortValueNode = sortValueNode; +var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +/** + * Sort ValueNode. + * + * This function returns a sorted copy of the given ValueNode. + * + * @internal + */ + +function sortValueNode(valueNode) { + switch (valueNode.kind) { + case _kinds.Kind.OBJECT: + return { + ...valueNode, + fields: sortFields(valueNode.fields) + }; + case _kinds.Kind.LIST: + return { + ...valueNode, + values: valueNode.values.map(sortValueNode) + }; + case _kinds.Kind.INT: + case _kinds.Kind.FLOAT: + case _kinds.Kind.STRING: + case _kinds.Kind.BOOLEAN: + case _kinds.Kind.NULL: + case _kinds.Kind.ENUM: + case _kinds.Kind.VARIABLE: + return valueNode; + } +} +function sortFields(fields) { + return fields.map(fieldNode => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value) + })).sort((fieldA, fieldB) => (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value)); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs": +/*!**************************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs ***! + \**************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.stripIgnoredCharacters = stripIgnoredCharacters; +var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); +var _lexer = __webpack_require__(/*! ../language/lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); +var _source = __webpack_require__(/*! ../language/source.mjs */ "../../../node_modules/graphql/language/source.mjs"); +var _tokenKind = __webpack_require__(/*! ../language/tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); +/** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - WhiteSpace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * + * Query example: + * + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * + * SDL example: + * + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + */ + +function stripIgnoredCharacters(source) { + const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); + const body = sourceObj.body; + const lexer = new _lexer.Lexer(sourceObj); + let strippedBody = ''; + let wasLastAddedTokenNonPunctuator = false; + while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + /** + * Every two non-punctuator tokens should have space between them. + * Also prevent case of non-punctuator token following by spread resulting + * in invalid token (e.g. `1...` is invalid Float token). + */ + + const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)(currentToken.kind); + if (wasLastAddedTokenNonPunctuator) { + if (isNonPunctuator || currentToken.kind === _tokenKind.TokenKind.SPREAD) { + strippedBody += ' '; + } } - })); - Object.defineProperty(exports, "isConstValueNode", ({ - enumerable: true, - get: function () { - return _index2.isConstValueNode; + const tokenBody = body.slice(currentToken.start, currentToken.end); + if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { + strippedBody += (0, _blockString.printBlockString)(currentToken.value, { + minimize: true + }); + } else { + strippedBody += tokenBody; } - })); - Object.defineProperty(exports, "isDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isDefinitionNode; + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + return strippedBody; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/typeComparators.mjs": +/*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/typeComparators.mjs ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.doTypesOverlap = doTypesOverlap; +exports.isEqualType = isEqualType; +exports.isTypeSubTypeOf = isTypeSubTypeOf; +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Provided two types, return true if the types are equal (invariant). + */ +function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + +function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); } - })); - Object.defineProperty(exports, "isDirective", ({ - enumerable: true, - get: function () { - return _index.isDirective; + return false; + } + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); } - })); - Object.defineProperty(exports, "isEnumType", ({ - enumerable: true, - get: function () { - return _index.isEnumType; + return false; + } + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, check if it is super type of maybeSubType. + // Otherwise, the child type is not a valid subtype of the parent type. + + return (0, _definition.isAbstractType)(superType) && ((0, _definition.isInterfaceType)(maybeSubType) || (0, _definition.isObjectType)(maybeSubType)) && schema.isSubType(superType, maybeSubType); +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + +function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema.getPossibleTypes(typeA).some(type => schema.isSubType(typeB, type)); + } // Determine if the latter type is a possible concrete type of the former. + + return schema.isSubType(typeA, typeB); + } + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isSubType(typeB, typeA); + } // Otherwise the types do not overlap. + + return false; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/typeFromAST.mjs": +/*!***************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/typeFromAST.mjs ***! + \***************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.typeFromAST = typeFromAST; +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case _kinds.Kind.LIST_TYPE: + { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); + } + case _kinds.Kind.NON_NULL_TYPE: + { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } + case _kinds.Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/valueFromAST.mjs": +/*!****************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/valueFromAST.mjs ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.valueFromAST = valueFromAST; +var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | + * + */ + +function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (variables == null || variables[variableName] === undefined) { + // No valid return value. + return; } - })); - Object.defineProperty(exports, "isEqualType", ({ - enumerable: true, - get: function () { - return _index6.isEqualType; + const variableValue = variables[variableName]; + if (variableValue === null && (0, _definition.isNonNullType)(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + return variableValue; + } + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. } - })); - Object.defineProperty(exports, "isExecutableDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isExecutableDefinitionNode; + return valueFromAST(valueNode, type.ofType, variables); + } + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + if (valueNode.kind === _kinds.Kind.LIST) { + const coercedValues = []; + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(itemValue); + } + } + return coercedValues; } - })); - Object.defineProperty(exports, "isInputObjectType", ({ - enumerable: true, - get: function () { - return _index.isInputObjectType; + const coercedValue = valueFromAST(valueNode, itemType, variables); + if (coercedValue === undefined) { + return; // Invalid: intentionally return no value. } - })); - Object.defineProperty(exports, "isInputType", ({ - enumerable: true, - get: function () { - return _index.isInputType; + return [coercedValue]; + } + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. } - })); - Object.defineProperty(exports, "isInterfaceType", ({ - enumerable: true, - get: function () { - return _index.isInterfaceType; + const coercedObj = Object.create(null); + const fieldNodes = (0, _keyMap.keyMap)(valueNode.fields, field => field.name.value); + for (const field of Object.values(type.getFields())) { + const fieldNode = fieldNodes[field.name]; + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } + continue; + } + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + coercedObj[field.name] = fieldValue; } - })); - Object.defineProperty(exports, "isIntrospectionType", ({ - enumerable: true, - get: function () { - return _index.isIntrospectionType; + return coercedObj; + } + if ((0, _definition.isLeafType)(type)) { + // Scalars and Enums fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. } - })); - Object.defineProperty(exports, "isLeafType", ({ - enumerable: true, - get: function () { - return _index.isLeafType; + if (result === undefined) { + return; // Invalid: intentionally return no value. } - })); - Object.defineProperty(exports, "isListType", ({ - enumerable: true, - get: function () { - return _index.isListType; + return result; + } + /* c8 ignore next 3 */ + // Not reachable, all possible input types have been considered. + + false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + +function isMissingVariable(valueNode, variables) { + return valueNode.kind === _kinds.Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs": +/*!***********************************************************************!*\ + !*** ../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs ***! + \***********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.valueFromASTUntyped = valueFromASTUntyped; +var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ + +function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; + case _kinds.Kind.LIST: + return valueNode.values.map(node => valueFromASTUntyped(node, variables)); + case _kinds.Kind.OBJECT: + return (0, _keyValMap.keyValMap)(valueNode.fields, field => field.name.value, field => valueFromASTUntyped(field.value, variables)); + case _kinds.Kind.VARIABLE: + return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value]; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/ValidationContext.mjs": +/*!**********************************************************************!*\ + !*** ../../../node_modules/graphql/validation/ValidationContext.mjs ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; +var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); +var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + get [Symbol.toStringTag]() { + return 'ASTValidationContext'; + } + reportError(error) { + this._onError(error); + } + getDocument() { + return this._ast; + } + getFragment(name) { + let fragments; + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + this._fragments = fragments; } - })); - Object.defineProperty(exports, "isNamedType", ({ - enumerable: true, - get: function () { - return _index.isNamedType; + return fragments[name]; + } + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + while (set = setsToVisit.pop()) { + for (const selection of set.selections) { + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); } - })); - Object.defineProperty(exports, "isNonNullType", ({ - enumerable: true, - get: function () { - return _index.isNonNullType; + return spreads; + } + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit = [operation.selectionSet]; + let node; + while (node = nodesToVisit.pop()) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } +} +exports.ASTValidationContext = ASTValidationContext; +class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } + get [Symbol.toStringTag]() { + return 'SDLValidationContext'; + } + getSchema() { + return this._schema; + } +} +exports.SDLValidationContext = SDLValidationContext; +class ValidationContext extends ASTValidationContext { + constructor(schema, ast, typeInfo, onError) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + get [Symbol.toStringTag]() { + return 'ValidationContext'; + } + getSchema() { + return this._schema; + } + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)(node, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + this._variableUsages.set(node, usages); } - })); - Object.defineProperty(exports, "isNullableType", ({ - enumerable: true, - get: function () { - return _index.isNullableType; + return usages; + } + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } + this._recursiveVariableUsages.set(operation, usages); } - })); - Object.defineProperty(exports, "isObjectType", ({ - enumerable: true, - get: function () { - return _index.isObjectType; + return usages; + } + getType() { + return this._typeInfo.getType(); + } + getParentType() { + return this._typeInfo.getParentType(); + } + getInputType() { + return this._typeInfo.getInputType(); + } + getParentInputType() { + return this._typeInfo.getParentInputType(); + } + getFieldDef() { + return this._typeInfo.getFieldDef(); + } + getDirective() { + return this._typeInfo.getDirective(); + } + getArgument() { + return this._typeInfo.getArgument(); + } + getEnumValue() { + return this._typeInfo.getEnumValue(); + } +} +exports.ValidationContext = ValidationContext; + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/index.mjs": +/*!**********************************************************!*\ + !*** ../../../node_modules/graphql/validation/index.mjs ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ + enumerable: true, + get: function () { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + } +})); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; + } +})); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ + enumerable: true, + get: function () { + return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; + } +})); +Object.defineProperty(exports, "KnownArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _KnownArgumentNamesRule.KnownArgumentNamesRule; + } +})); +Object.defineProperty(exports, "KnownDirectivesRule", ({ + enumerable: true, + get: function () { + return _KnownDirectivesRule.KnownDirectivesRule; + } +})); +Object.defineProperty(exports, "KnownFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _KnownFragmentNamesRule.KnownFragmentNamesRule; + } +})); +Object.defineProperty(exports, "KnownTypeNamesRule", ({ + enumerable: true, + get: function () { + return _KnownTypeNamesRule.KnownTypeNamesRule; + } +})); +Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ + enumerable: true, + get: function () { + return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; + } +})); +Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ + enumerable: true, + get: function () { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + } +})); +Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ + enumerable: true, + get: function () { + return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; + } +})); +Object.defineProperty(exports, "NoFragmentCyclesRule", ({ + enumerable: true, + get: function () { + return _NoFragmentCyclesRule.NoFragmentCyclesRule; + } +})); +Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ + enumerable: true, + get: function () { + return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; + } +})); +Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ + enumerable: true, + get: function () { + return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; + } +})); +Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ + enumerable: true, + get: function () { + return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; + } +})); +Object.defineProperty(exports, "NoUnusedVariablesRule", ({ + enumerable: true, + get: function () { + return _NoUnusedVariablesRule.NoUnusedVariablesRule; + } +})); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ + enumerable: true, + get: function () { + return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; + } +})); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ + enumerable: true, + get: function () { + return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; + } +})); +Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ + enumerable: true, + get: function () { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + } +})); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ + enumerable: true, + get: function () { + return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; + } +})); +Object.defineProperty(exports, "ScalarLeafsRule", ({ + enumerable: true, + get: function () { + return _ScalarLeafsRule.ScalarLeafsRule; + } +})); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ + enumerable: true, + get: function () { + return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; + } +})); +Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; + } +})); +Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; + } +})); +Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + } +})); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ + enumerable: true, + get: function () { + return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; + } +})); +Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + } +})); +Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + } +})); +Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; + } +})); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; + } +})); +Object.defineProperty(exports, "UniqueOperationNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueOperationNamesRule.UniqueOperationNamesRule; + } +})); +Object.defineProperty(exports, "UniqueOperationTypesRule", ({ + enumerable: true, + get: function () { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + } +})); +Object.defineProperty(exports, "UniqueTypeNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + } +})); +Object.defineProperty(exports, "UniqueVariableNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueVariableNamesRule.UniqueVariableNamesRule; + } +})); +Object.defineProperty(exports, "ValidationContext", ({ + enumerable: true, + get: function () { + return _ValidationContext.ValidationContext; + } +})); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; + } +})); +Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ + enumerable: true, + get: function () { + return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; + } +})); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ + enumerable: true, + get: function () { + return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; + } +})); +Object.defineProperty(exports, "specifiedRules", ({ + enumerable: true, + get: function () { + return _specifiedRules.specifiedRules; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.validate; + } +})); +var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); +var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); +var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); +var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); +var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); +var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); +var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); +var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); +var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); +var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); +var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); +var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); +var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); +var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); +var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); +var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); +var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); +var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); +var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); +var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); +var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); +var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); +var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); +var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); +var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); +var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); +var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); +var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); +var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); +var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); +var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); +var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); +var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); +var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); +var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); +var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); +var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); +var _NoDeprecatedCustomRule = __webpack_require__(/*! ./rules/custom/NoDeprecatedCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs"); +var _NoSchemaIntrospectionCustomRule = __webpack_require__(/*! ./rules/custom/NoSchemaIntrospectionCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs"); + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs": +/*!************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs ***! + \************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + */ +function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + const defName = definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"'; + context.reportError(new _GraphQLError.GraphQLError(`The ${defName} definition is not executable.`, { + nodes: definition + })); + } + } + return false; } - })); - Object.defineProperty(exports, "isOutputType", ({ - enumerable: true, - get: function () { - return _index.isOutputType; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs": +/*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs ***! + \**********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; +var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _naturalCompare = __webpack_require__(/*! ../../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); +var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + */ +function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + let suggestion = (0, _didYouMean.didYouMean)('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === '') { + suggestion = (0, _didYouMean.didYouMean)(getSuggestedFieldNames(type, fieldName)); + } // Report an error, including helpful suggestions. + + context.reportError(new _GraphQLError.GraphQLError(`Cannot query field "${fieldName}" on type "${type.name}".` + suggestion, { + nodes: node + })); + } + } } - })); - Object.defineProperty(exports, "isRequiredArgument", ({ - enumerable: true, - get: function () { - return _index.isRequiredArgument; + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ + +function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, _definition.isAbstractType)(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + const suggestedTypes = new Set(); + const usageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + for (const possibleInterface of possibleType.getInterfaces()) { + var _usageCount$possibleI; + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1; } - })); - Object.defineProperty(exports, "isRequiredInputField", ({ - enumerable: true, - get: function () { - return _index.isRequiredInputField; + } + return [...suggestedTypes].sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + if ((0, _definition.isInterfaceType)(typeA) && schema.isSubType(typeA, typeB)) { + return -1; } - })); - Object.defineProperty(exports, "isScalarType", ({ - enumerable: true, - get: function () { - return _index.isScalarType; + if ((0, _definition.isInterfaceType)(typeB) && schema.isSubType(typeB, typeA)) { + return 1; } - })); - Object.defineProperty(exports, "isSchema", ({ - enumerable: true, - get: function () { - return _index.isSchema; - } - })); - Object.defineProperty(exports, "isSelectionNode", ({ - enumerable: true, - get: function () { - return _index2.isSelectionNode; - } - })); - Object.defineProperty(exports, "isSpecifiedDirective", ({ - enumerable: true, - get: function () { - return _index.isSpecifiedDirective; + return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); + }).map(x => x.name); +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + +function getSuggestedFieldNames(type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + return []; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs": +/*!****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs ***! + \****************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + */ +function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(typeCondition); + context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot condition on non composite type "${typeStr}".`, { + nodes: typeCondition + })); + } + } + }, + FragmentDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(node.typeCondition); + context.reportError(new _GraphQLError.GraphQLError(`Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, { + nodes: node.typeCondition + })); + } } - })); - Object.defineProperty(exports, "isSpecifiedScalarType", ({ - enumerable: true, - get: function () { - return _index.isSpecifiedScalarType; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs": +/*!*********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs ***! + \*********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; +exports.KnownArgumentNamesRule = KnownArgumentNamesRule; +var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + */ +function KnownArgumentNamesRule(context) { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map(arg => arg.name); + const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgsNames); + context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + (0, _didYouMean.didYouMean)(suggestions), { + nodes: argNode + })); + } } - })); - Object.defineProperty(exports, "isType", ({ - enumerable: true, - get: function () { - return _index.isType; + }; +} +/** + * @internal + */ + +function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map(arg => arg.name); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + directiveArgs[def.name.value] = argsNodes.map(arg => arg.name.value); } - })); - Object.defineProperty(exports, "isTypeDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeDefinitionNode; + } + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (!knownArgs.includes(argName)) { + const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgs); + context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on directive "@${directiveName}".` + (0, _didYouMean.didYouMean)(suggestions), { + nodes: argNode + })); + } + } + } + return false; } - })); - Object.defineProperty(exports, "isTypeExtensionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeExtensionNode; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs": +/*!******************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs ***! + \******************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.KnownDirectivesRule = KnownDirectivesRule; +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _ast = __webpack_require__(/*! ../../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); +var _directiveLocation = __webpack_require__(/*! ../../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + */ +function KnownDirectivesRule(context) { + const locationsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(name => name.value); + } + } + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + if (!locations) { + context.reportError(new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { + nodes: node + })); + return; + } + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (candidateLocation && !locations.includes(candidateLocation)) { + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${name}" may not be used on ${candidateLocation}.`, { + nodes: node + })); + } } - })); - Object.defineProperty(exports, "isTypeNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeNode; + }; +} +function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + 'kind' in appliedTo || (0, _invariant.invariant)(false); + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + case _kinds.Kind.INPUT_VALUE_DEFINITION: + { + const parentNode = ancestors[ancestors.length - 3]; + 'kind' in parentNode || (0, _invariant.invariant)(false); + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + // Not reachable, all possible types have been considered. + + /* c8 ignore next */ + + default: + false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind)); + } +} +function getDirectiveLocationForOperation(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return _directiveLocation.DirectiveLocation.QUERY; + case _ast.OperationTypeNode.MUTATION: + return _directiveLocation.DirectiveLocation.MUTATION; + case _ast.OperationTypeNode.SUBSCRIPTION: + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs": +/*!*********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs ***! + \*********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.KnownFragmentNamesRule = KnownFragmentNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined + */ +function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError(new _GraphQLError.GraphQLError(`Unknown fragment "${fragmentName}".`, { + nodes: node.name + })); + } } - })); - Object.defineProperty(exports, "isTypeSubTypeOf", ({ - enumerable: true, - get: function () { - return _index6.isTypeSubTypeOf; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs": +/*!*****************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs ***! + \*****************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.KnownTypeNamesRule = KnownTypeNamesRule; +var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); +var _introspection = __webpack_require__(/*! ../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +var _scalars = __webpack_require__(/*! ../../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + */ +function KnownTypeNamesRule(context) { + const schema = context.getSchema(); + const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = true; + } + } + const typeNames = [...Object.keys(existingTypesMap), ...Object.keys(definedTypes)]; + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + const definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + if (isSDL && standardTypeNames.includes(typeName)) { + return; + } + const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames); + context.reportError(new _GraphQLError.GraphQLError(`Unknown type "${typeName}".` + (0, _didYouMean.didYouMean)(suggestedTypes), { + nodes: node + })); + } } - })); - Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeSystemDefinitionNode; + }; +} +const standardTypeNames = [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes].map(type => type.name); +function isSDLNode(value) { + return 'kind' in value && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs": +/*!*************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs ***! + \*************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation + */ +function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter(definition => definition.kind === _kinds.Kind.OPERATION_DEFINITION).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new _GraphQLError.GraphQLError('This anonymous operation must be the only defined operation.', { + nodes: node + })); + } } - })); - Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeSystemExtensionNode; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs": +/*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs ***! + \***********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + const oldSchema = context.getSchema(); + const alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new _GraphQLError.GraphQLError('Cannot define a new schema within a schema extension.', { + nodes: node + })); + return; + } + if (schemaDefinitionsCount > 0) { + context.reportError(new _GraphQLError.GraphQLError('Must provide only one schema definition.', { + nodes: node + })); + } + ++schemaDefinitionsCount; } - })); - Object.defineProperty(exports, "isUnionType", ({ - enumerable: true, - get: function () { - return _index.isUnionType; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs": +/*!*******************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs ***! + \*******************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NoFragmentCyclesRule = NoFragmentCyclesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles + */ +function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + const spreadPath = []; // Position in the spread path + + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; } - })); - Object.defineProperty(exports, "isValidNameError", ({ - enumerable: true, - get: function () { - return _index6.isValidNameError; + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; } - })); - Object.defineProperty(exports, "isValueNode", ({ - enumerable: true, - get: function () { - return _index2.isValueNode; + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + if (spreadNodes.length === 0) { + return; } - })); - Object.defineProperty(exports, "isWrappingType", ({ - enumerable: true, - get: function () { - return _index.isWrappingType; + spreadPathIndexByName[fragmentName] = spreadPath.length; + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath.slice(0, -1).map(s => '"' + s.name.value + '"').join(', '); + context.reportError(new _GraphQLError.GraphQLError(`Cannot spread fragment "${spreadName}" within itself` + (viaPath !== '' ? ` via ${viaPath}.` : '.'), { + nodes: cyclePath + })); + } + spreadPath.pop(); } - })); - Object.defineProperty(exports, "lexicographicSortSchema", ({ - enumerable: true, - get: function () { - return _index6.lexicographicSortSchema; + spreadPathIndexByName[fragmentName] = undefined; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs": +/*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs ***! + \***********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined + */ +function NoUndefinedVariablesRule(context) { + let variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { + node + } of usages) { + const varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` : `Variable "$${varName}" is not defined.`, { + nodes: [node, operation] + })); + } + } + } + }, + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; } - })); - Object.defineProperty(exports, "locatedError", ({ - enumerable: true, - get: function () { - return _index5.locatedError; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs": +/*!********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs ***! + \********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used + */ +function NoUnusedFragmentsRule(context) { + const operationDefs = []; + const fragmentDefs = []; + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments(operation)) { + fragmentNameUsed[fragment.name.value] = true; + } + } + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" is never used.`, { + nodes: fragmentDef + })); + } + } + } } - })); - Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _index2.parse; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs": +/*!********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs ***! + \********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NoUnusedVariablesRule = NoUnusedVariablesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + * + * See https://spec.graphql.org/draft/#sec-All-Variables-Used + */ +function NoUnusedVariablesRule(context) { + let variableDefs = []; + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + for (const { + node + } of usages) { + variableNameUsed[node.name.value] = true; + } + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` : `Variable "$${variableName}" is never used.`, { + nodes: variableDef + })); + } + } + } + }, + VariableDefinition(def) { + variableDefs.push(def); } - })); - Object.defineProperty(exports, "parseConstValue", ({ - enumerable: true, - get: function () { - return _index2.parseConstValue; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs": +/*!*******************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs ***! + \*******************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _sortValueNode = __webpack_require__(/*! ../../utilities/sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); +var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(([responseName, subReason]) => `subfields "${responseName}" conflict because ` + reasonMessage(subReason)).join(' and '); + } + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + */ + +function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + const cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError(new _GraphQLError.GraphQLError(`Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, { + nodes: fields1.concat(fields2) + })); + } } - })); - Object.defineProperty(exports, "parseType", ({ - enumerable: true, - get: function () { - return _index2.parseType; + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + const conflicts = []; + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet); // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } } - })); - Object.defineProperty(exports, "parseValue", ({ - enumerable: true, - get: function () { - return _index2.parseValue; + } + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + const [fieldMap2, referencedFragmentNames] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment); // Do not compare a fragment's fieldMap to itself. + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (const referencedFragmentName of referencedFragmentNames) { + // Memoize so two fragments are not compared for conflicts more than once. + if (comparedFragmentPairs.has(referencedFragmentName, fragmentName, areMutuallyExclusive)) { + continue; } - })); - Object.defineProperty(exports, "print", ({ - enumerable: true, - get: function () { - return _index2.print; - } - })); - Object.defineProperty(exports, "printError", ({ - enumerable: true, - get: function () { - return _index5.printError; - } - })); - Object.defineProperty(exports, "printIntrospectionSchema", ({ - enumerable: true, - get: function () { - return _index6.printIntrospectionSchema; - } - })); - Object.defineProperty(exports, "printLocation", ({ - enumerable: true, - get: function () { - return _index2.printLocation; - } - })); - Object.defineProperty(exports, "printSchema", ({ - enumerable: true, - get: function () { - return _index6.printSchema; - } - })); - Object.defineProperty(exports, "printSourceLocation", ({ - enumerable: true, - get: function () { - return _index2.printSourceLocation; - } - })); - Object.defineProperty(exports, "printType", ({ - enumerable: true, - get: function () { - return _index6.printType; - } - })); - Object.defineProperty(exports, "resolveObjMapThunk", ({ - enumerable: true, - get: function () { - return _index.resolveObjMapThunk; - } - })); - Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ - enumerable: true, - get: function () { - return _index.resolveReadonlyArrayThunk; - } - })); - Object.defineProperty(exports, "responsePathAsArray", ({ - enumerable: true, - get: function () { - return _index3.responsePathAsArray; - } - })); - Object.defineProperty(exports, "separateOperations", ({ - enumerable: true, - get: function () { - return _index6.separateOperations; - } - })); - Object.defineProperty(exports, "specifiedDirectives", ({ - enumerable: true, - get: function () { - return _index.specifiedDirectives; - } - })); - Object.defineProperty(exports, "specifiedRules", ({ - enumerable: true, - get: function () { - return _index4.specifiedRules; - } - })); - Object.defineProperty(exports, "specifiedScalarTypes", ({ - enumerable: true, - get: function () { - return _index.specifiedScalarTypes; - } - })); - Object.defineProperty(exports, "stripIgnoredCharacters", ({ - enumerable: true, - get: function () { - return _index6.stripIgnoredCharacters; - } - })); - Object.defineProperty(exports, "subscribe", ({ - enumerable: true, - get: function () { - return _index3.subscribe; - } - })); - Object.defineProperty(exports, "syntaxError", ({ - enumerable: true, - get: function () { - return _index5.syntaxError; - } - })); - Object.defineProperty(exports, "typeFromAST", ({ - enumerable: true, - get: function () { - return _index6.typeFromAST; - } - })); - Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _index4.validate; - } - })); - Object.defineProperty(exports, "validateSchema", ({ - enumerable: true, - get: function () { - return _index.validateSchema; - } - })); - Object.defineProperty(exports, "valueFromAST", ({ - enumerable: true, - get: function () { - return _index6.valueFromAST; - } - })); - Object.defineProperty(exports, "valueFromASTUntyped", ({ - enumerable: true, - get: function () { - return _index6.valueFromASTUntyped; - } - })); - Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.version; - } - })); - Object.defineProperty(exports, "versionInfo", ({ - enumerable: true, - get: function () { - return _version.versionInfo; - } - })); - Object.defineProperty(exports, "visit", ({ - enumerable: true, - get: function () { - return _index2.visit; - } - })); - Object.defineProperty(exports, "visitInParallel", ({ - enumerable: true, - get: function () { - return _index2.visitInParallel; - } - })); - Object.defineProperty(exports, "visitWithTypeInfo", ({ - enumerable: true, - get: function () { - return _index6.visitWithTypeInfo; - } - })); - var _version = __webpack_require__(/*! ./version.mjs */ "../../../node_modules/graphql/version.mjs"); - var _graphql = __webpack_require__(/*! ./graphql.mjs */ "../../../node_modules/graphql/graphql.mjs"); - var _index = __webpack_require__(/*! ./type/index.mjs */ "../../../node_modules/graphql/type/index.mjs"); - var _index2 = __webpack_require__(/*! ./language/index.mjs */ "../../../node_modules/graphql/language/index.mjs"); - var _index3 = __webpack_require__(/*! ./execution/index.mjs */ "../../../node_modules/graphql/execution/index.mjs"); - var _index4 = __webpack_require__(/*! ./validation/index.mjs */ "../../../node_modules/graphql/validation/index.mjs"); - var _index5 = __webpack_require__(/*! ./error/index.mjs */ "../../../node_modules/graphql/error/index.mjs"); - var _index6 = __webpack_require__(/*! ./utilities/index.mjs */ "../../../node_modules/graphql/utilities/index.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/Path.mjs": - /*!******************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/Path.mjs ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.addPath = addPath; - exports.pathToArray = pathToArray; - /** - * Given a Path and a key, return a new Path containing the new key. - */ - function addPath(prev, key, typename) { - return { - prev, - key, - typename - }; + comparedFragmentPairs.add(referencedFragmentName, fragmentName, areMutuallyExclusive); + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, referencedFragmentName); } - /** - * Given a Path, return an Array of the path keys. - */ - - function pathToArray(path) { - const flattened = []; - let curr = path; - while (curr) { - flattened.push(curr.key); - curr = curr.prev; - } - return flattened.reverse(); +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/devAssert.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/devAssert.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.devAssert = devAssert; - function devAssert(condition, message) { - const booleanCondition = Boolean(condition); - if (!booleanCondition) { - throw new Error(message); - } + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/didYouMean.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/didYouMean.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.didYouMean = didYouMean; - const MAX_SUGGESTIONS = 5; - /** - * Given [ A, B, C ] return ' Did you mean A, B, or C?'. - */ - - function didYouMean(firstArg, secondArg) { - const [subMessage, suggestionsArg] = secondArg ? [firstArg, secondArg] : [undefined, firstArg]; - let message = ' Did you mean '; - if (subMessage) { - message += subMessage + ' '; - } - const suggestions = suggestionsArg.map(x => `"${x}"`); - switch (suggestions.length) { - case 0: - return ''; - case 1: - return message + suggestions[0] + '?'; - case 2: - return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + const [fieldMap1, referencedFragmentNames1] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1); + const [fieldMap2, referencedFragmentNames2] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2); // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, referencedFragmentName2); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, referencedFragmentName1, fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + const conflicts = []; + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2); // (H) First, collect all conflicts between these two collections of field. + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentName2); + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentName1); + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + for (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2); } - const selected = suggestions.slice(0, MAX_SUGGESTIONS); - const lastItem = selected.pop(); - return message + selected.join(', ') + ', or ' + lastItem + '?'; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/groupBy.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/groupBy.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.groupBy = groupBy; - /** - * Groups array items into a Map, given a function to produce grouping key. - */ - function groupBy(list, keyFn) { - const result = new Map(); - for (const item of list) { - const key = keyFn(item); - const group = result.get(key); - if (group === undefined) { - result.set(key, [item]); - } else { - group.push(item); + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of Object.entries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, + // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const [responseName, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2); + if (conflict) { + conflicts.push(conflict); + } + } } } - return result; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/identityFunc.mjs": - /*!**************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/identityFunc.mjs ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.identityFunc = identityFunc; - /** - * Returns the first argument it receives. - */ - function identityFunc(x) { - return x; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/inspect.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/inspect.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.inspect = inspect; - const MAX_ARRAY_LENGTH = 10; - const MAX_RECURSIVE_DEPTH = 2; - /** - * Used to print values in error messages. - */ - - function inspect(value) { - return formatValue(value, []); - } - function formatValue(value, seenValues) { - switch (typeof value) { - case 'string': - return JSON.stringify(value); - case 'function': - return value.name ? `[function ${value.name}]` : '[function]'; - case 'object': - return formatObjectValue(value, seenValues); - default: - return String(value); +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + const areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [[responseName, `"${name1}" and "${name2}" are different fields`], [node1], [node2]]; + } // Two field calls must have the same arguments. + + if (!sameArguments(node1, node2)) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; } + } // The return type for each field. + + const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, `they return conflicting types "${(0, _inspect.inspect)(type1)}" and "${(0, _inspect.inspect)(type2)}"`], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} +function sameArguments(node1, node2) { + const args1 = node1.arguments; + const args2 = node2.arguments; + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; + } + if (args2 === undefined || args2.length === 0) { + return false; } - function formatObjectValue(value, previouslySeenValues) { - if (value === null) { - return 'null'; - } - if (previouslySeenValues.includes(value)) { - return '[Circular]'; - } - const seenValues = [...previouslySeenValues, value]; - if (isJSONable(value)) { - const jsonValue = value.toJSON(); // check for infinite recursion - - if (jsonValue !== value) { - return typeof jsonValue === 'string' ? jsonValue : formatValue(jsonValue, seenValues); - } - } else if (Array.isArray(value)) { - return formatArray(value, seenValues); + /* c8 ignore next */ + + if (args1.length !== args2.length) { + /* c8 ignore next */ + return false; + /* c8 ignore next */ + } + const values2 = new Map(args2.map(({ + name, + value + }) => [name.value, value])); + return args1.every(arg1 => { + const value1 = arg1.value; + const value2 = values2.get(arg1.name.value); + if (value2 === undefined) { + return false; } - return formatObject(value, seenValues); + return stringifyValue(value1) === stringifyValue(value2); + }); +} +function stringifyValue(value) { + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + +function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; } - function isJSONable(value) { - return typeof value.toJSON === 'function'; + if ((0, _definition.isListType)(type2)) { + return true; } - function formatObject(object, seenValues) { - const entries = Object.entries(object); - if (entries.length === 0) { - return '{}'; - } - if (seenValues.length > MAX_RECURSIVE_DEPTH) { - return '[' + getObjectTag(object) + ']'; - } - const properties = entries.map(([key, value]) => key + ': ' + formatValue(value, seenValues)); - return '{ ' + properties.join(', ') + ' }'; + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; } - function formatArray(array, seenValues) { - if (array.length === 0) { - return '[]'; - } - if (seenValues.length > MAX_RECURSIVE_DEPTH) { - return '[Array]'; - } - const len = Math.min(MAX_ARRAY_LENGTH, array.length); - const remaining = array.length - len; - const items = []; - for (let i = 0; i < len; ++i) { - items.push(formatValue(array[i], seenValues)); + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { + return type1 !== type2; + } + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + const cached = cachedFieldsAndFragmentNames.get(selectionSet); + if (cached) { + return cached; + } + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + const result = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, result); + return result; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + if (cached) { + return cached; + } + const fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: + { + const fieldName = selection.name.value; + let fieldDef; + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias ? selection.alias.value : fieldName; + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case _kinds.Kind.INLINE_FRAGMENT: + { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + break; + } } - if (remaining === 1) { - items.push('... 1 more item'); - } else if (remaining > 1) { - items.push(`... ${remaining} more items`); + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(([reason]) => reason)], [node1, ...conflicts.map(([, fields1]) => fields1).flat()], [node2, ...conflicts.map(([,, fields2]) => fields2).flat()]]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does not matter. + */ + +class PairSet { + constructor() { + this._data = new Map(); + } + has(a, b, areMutuallyExclusive) { + var _this$_data$get; + const [key1, key2] = a < b ? [a, b] : [b, a]; + const result = (_this$_data$get = this._data.get(key1)) === null || _this$_data$get === void 0 ? void 0 : _this$_data$get.get(key2); + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, hence if + // we want to know if this PairSet "has" these two with no exclusivity, + // we have to ensure it was added as such. + + return areMutuallyExclusive ? true : areMutuallyExclusive === result; + } + add(a, b, areMutuallyExclusive) { + const [key1, key2] = a < b ? [a, b] : [b, a]; + const map = this._data.get(key1); + if (map === undefined) { + this._data.set(key1, new Map([[key2, areMutuallyExclusive]])); + } else { + map.set(key2, areMutuallyExclusive); } - return '[' + items.join(', ') + ']'; } - function getObjectTag(object) { - const tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, ''); - if (tag === 'Object' && typeof object.constructor === 'function') { - const name = object.constructor.name; - if (typeof name === 'string' && name !== '') { - return name; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs": +/*!**************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs ***! + \**************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); +var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { + nodes: node + })); + } + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { + nodes: node + })); } } - return tag; + }; +} +function getFragmentType(context, name) { + const frag = context.getFragment(name); + if (frag) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); + if ((0, _definition.isCompositeType)(type)) { + return type; + } } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/instanceOf.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/instanceOf.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.instanceOf = void 0; - var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - /** - * A replacement for instanceof which includes an error warning when multi-realm - * constructors are detected. - * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production - * See: https://webpack.js.org/guides/production/ - */ - - const instanceOf = exports.instanceOf = /* c8 ignore next 6 */ - // FIXME: https://github.com/graphql/graphql-js/issues/2317 - globalThis.process && globalThis.process.env.NODE_ENV === 'production' ? function instanceOf(value, constructor) { - return value instanceof constructor; - } : function instanceOf(value, constructor) { - if (value instanceof constructor) { - return true; - } - if (typeof value === 'object' && value !== null) { - var _value$constructor; - - // Prefer Symbol.toStringTag since it is immune to minification. - const className = constructor.prototype[Symbol.toStringTag]; - const valueClassName = - // We still need to support constructor's name to detect conflicts with older versions of this library. - Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 - ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name; - if (className === valueClassName) { - const stringifiedValue = (0, _inspect.inspect)(value); - throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. - - Ensure that there is only one instance of "graphql" in the node_modules - directory. If different versions of "graphql" are the dependencies of other - relied on modules, use "resolutions" to ensure only one version is installed. - - https://yarnpkg.com/en/docs/selective-version-resolutions - - Duplicate "graphql" modules cannot be used at the same time since different - versions may have different capabilities and behavior. The data from one - version used in the function from another could produce confusing and - spurious results.`); - } - } - return false; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs": +/*!*************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs ***! + \*************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; +var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ +function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = def; + } + } + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension }; - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/invariant.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/invariant.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.invariant = invariant; - function invariant(condition, message) { - const booleanCondition = Boolean(condition); - if (!booleanCondition) { - throw new Error(message != null ? message : 'Unexpected invariant triggered.'); + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + let expectedKind; + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError(new _GraphQLError.GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, { + nodes: defNode ? [defNode, node] : node + })); + } + } else { + const allTypeNames = Object.keys({ + ...definedTypes, + ...(schema === null || schema === void 0 ? void 0 : schema.getTypeMap()) + }); + const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, allTypeNames); + context.reportError(new _GraphQLError.GraphQLError(`Cannot extend type "${typeName}" because it is not defined.` + (0, _didYouMean.didYouMean)(suggestedTypes), { + nodes: node.name + })); } } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/isAsyncIterable.mjs": - /*!*****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isAsyncIterable.mjs ***! - \*****************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isAsyncIterable = isAsyncIterable; - /** - * Returns true if the provided object implements the AsyncIterator protocol via - * implementing a `Symbol.asyncIterator` method. - */ - function isAsyncIterable(maybeAsyncIterable) { - return typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 ? void 0 : maybeAsyncIterable[Symbol.asyncIterator]) === 'function'; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/isIterableObject.mjs": - /*!******************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isIterableObject.mjs ***! - \******************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isIterableObject = isIterableObject; - /** - * Returns true if the provided object is an Object (i.e. not a string literal) - * and implements the Iterator protocol. - * - * This may be used in place of [Array.isArray()][isArray] to determine if - * an object should be iterated-over e.g. Array, Map, Set, Int8Array, - * TypedArray, etc. but excludes string literals. - * - * @example - * ```ts - * isIterableObject([ 1, 2, 3 ]) // true - * isIterableObject(new Map()) // true - * isIterableObject('ABC') // false - * isIterableObject({ key: 'value' }) // false - * isIterableObject({ length: 1, 0: 'Alpha' }) // false - * ``` - */ - function isIterableObject(maybeIterable) { - return typeof maybeIterable === 'object' && typeof (maybeIterable === null || maybeIterable === void 0 ? void 0 : maybeIterable[Symbol.iterator]) === 'function'; +} +const defKindToExtKind = { + [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, + [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, + [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, + [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, + [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION +}; +function typeToExtKind(type) { + if ((0, _definition.isScalarType)(type)) { + return _kinds.Kind.SCALAR_TYPE_EXTENSION; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/isObjectLike.mjs": - /*!**************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isObjectLike.mjs ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isObjectLike = isObjectLike; - /** - * Return true if `value` is object-like. A value is object-like if it's not - * `null` and has a `typeof` result of "object". - */ - function isObjectLike(value) { - return typeof value == 'object' && value !== null; + if ((0, _definition.isObjectType)(type)) { + return _kinds.Kind.OBJECT_TYPE_EXTENSION; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/isPromise.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/isPromise.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isPromise = isPromise; - /** - * Returns true if the value acts like a Promise, i.e. has a "then" function, - * otherwise returns false. - */ - function isPromise(value) { - return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function'; + if ((0, _definition.isInterfaceType)(type)) { + return _kinds.Kind.INTERFACE_TYPE_EXTENSION; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/keyMap.mjs": - /*!********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/keyMap.mjs ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.keyMap = keyMap; - /** - * Creates a keyed JS object from an array, given a function to produce the keys - * for each value in the array. - * - * This provides a convenient lookup for the array items if the key function - * produces unique results. - * ```ts - * const phoneBook = [ - * { name: 'Jon', num: '555-1234' }, - * { name: 'Jenny', num: '867-5309' } - * ] - * - * const entriesByName = keyMap( - * phoneBook, - * entry => entry.name - * ) - * - * // { - * // Jon: { name: 'Jon', num: '555-1234' }, - * // Jenny: { name: 'Jenny', num: '867-5309' } - * // } - * - * const jennyEntry = entriesByName['Jenny'] - * - * // { name: 'Jenny', num: '857-6309' } - * ``` - */ - function keyMap(list, keyFn) { - const result = Object.create(null); - for (const item of list) { - result[keyFn(item)] = item; - } - return result; + if ((0, _definition.isUnionType)(type)) { + return _kinds.Kind.UNION_TYPE_EXTENSION; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/keyValMap.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/keyValMap.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.keyValMap = keyValMap; - /** - * Creates a keyed JS object from an array, given a function to produce the keys - * and a function to produce the values from each item in the array. - * ```ts - * const phoneBook = [ - * { name: 'Jon', num: '555-1234' }, - * { name: 'Jenny', num: '867-5309' } - * ] - * - * // { Jon: '555-1234', Jenny: '867-5309' } - * const phonesByName = keyValMap( - * phoneBook, - * entry => entry.name, - * entry => entry.num - * ) - * ``` - */ - function keyValMap(list, keyFn, valFn) { - const result = Object.create(null); - for (const item of list) { - result[keyFn(item)] = valFn(item); - } - return result; + if ((0, _definition.isEnumType)(type)) { + return _kinds.Kind.ENUM_TYPE_EXTENSION; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/mapValue.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/mapValue.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.mapValue = mapValue; - /** - * Creates an object map with the same keys as `map` and values generated by - * running each value of `map` thru `fn`. - */ - function mapValue(map, fn) { - const result = Object.create(null); - for (const key of Object.keys(map)) { - result[key] = fn(map[key], key); - } - return result; + if ((0, _definition.isInputObjectType)(type)) { + return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/memoize3.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/memoize3.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.memoize3 = memoize3; - /** - * Memoizes the provided three-argument function. - */ - function memoize3(fn) { - let cache0; - return function memoized(a1, a2, a3) { - if (cache0 === undefined) { - cache0 = new WeakMap(); - } - let cache1 = cache0.get(a1); - if (cache1 === undefined) { - cache1 = new WeakMap(); - cache0.set(a1, cache1); - } - let cache2 = cache1.get(a2); - if (cache2 === undefined) { - cache2 = new WeakMap(); - cache1.set(a2, cache2); - } - let fnResult = cache2.get(a3); - if (fnResult === undefined) { - fnResult = fn(a1, a2, a3); - cache2.set(a3, fnResult); - } - return fnResult; - }; + /* c8 ignore next 3 */ + // Not reachable. All possible types have been considered + + false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); +} +function extensionKindToTypeName(kind) { + switch (kind) { + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + case _kinds.Kind.UNION_TYPE_EXTENSION: + return 'union'; + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + // Not reachable. All possible types have been considered + + /* c8 ignore next */ + + default: + false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(kind)); } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/naturalCompare.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/naturalCompare.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.naturalCompare = naturalCompare; - /** - * Returns a number indicating whether a reference string comes before, or after, - * or is the same as the given string in natural sort order. - * - * See: https://en.wikipedia.org/wiki/Natural_sort_order - * - */ - function naturalCompare(aStr, bStr) { - let aIndex = 0; - let bIndex = 0; - while (aIndex < aStr.length && bIndex < bStr.length) { - let aChar = aStr.charCodeAt(aIndex); - let bChar = bStr.charCodeAt(bIndex); - if (isDigit(aChar) && isDigit(bChar)) { - let aNum = 0; - do { - ++aIndex; - aNum = aNum * 10 + aChar - DIGIT_0; - aChar = aStr.charCodeAt(aIndex); - } while (isDigit(aChar) && aNum > 0); - let bNum = 0; - do { - ++bIndex; - bNum = bNum * 10 + bChar - DIGIT_0; - bChar = bStr.charCodeAt(bIndex); - } while (isDigit(bChar) && bNum > 0); - if (aNum < bNum) { - return -1; - } - if (aNum > bNum) { - return 1; - } - } else { - if (aChar < bChar) { - return -1; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs": +/*!****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs ***! + \****************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ProvidedRequiredArgumentsOnDirectivesRule = ProvidedRequiredArgumentsOnDirectivesRule; +exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +function ProvidedRequiredArgumentsRule(context) { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + var _fieldNode$arguments; + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; } - if (aChar > bChar) { - return 1; + const providedArgs = new Set( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + (_fieldNode$arguments = fieldNode.arguments) === null || _fieldNode$arguments === void 0 ? void 0 : _fieldNode$arguments.map(arg => arg.name.value)); + for (const argDef of fieldDef.args) { + if (!providedArgs.has(argDef.name) && (0, _definition.isRequiredArgument)(argDef)) { + const argTypeStr = (0, _inspect.inspect)(argDef.type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, { + nodes: fieldNode + })); + } } - ++aIndex; - ++bIndex; } } - return aStr.length - bStr.length; - } - const DIGIT_0 = 48; - const DIGIT_9 = 57; - function isDigit(code) { - return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/printPathArray.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/printPathArray.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.printPathArray = printPathArray; - /** - * Build a string describing the path. - */ - function printPathArray(path) { - return path.map(key => typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key).join(''); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/promiseForObject.mjs": - /*!******************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/promiseForObject.mjs ***! - \******************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.promiseForObject = promiseForObject; - /** - * This function transforms a JS object `ObjMap>` into - * a `Promise>` - * - * This is akin to bluebird's `Promise.props`, but implemented only using - * `Promise.all` so it will work with any implementation of ES6 promises. - */ - function promiseForObject(object) { - return Promise.all(Object.values(object)).then(resolvedValues => { - const resolvedObject = Object.create(null); - for (const [i, key] of Object.keys(object).entries()) { - resolvedObject[key] = resolvedValues[i]; - } - return resolvedObject; - }); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/promiseReduce.mjs": - /*!***************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/promiseReduce.mjs ***! - \***************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.promiseReduce = promiseReduce; - var _isPromise = __webpack_require__(/*! ./isPromise.mjs */ "../../../node_modules/graphql/jsutils/isPromise.mjs"); - /** - * Similar to Array.prototype.reduce(), however the reducing callback may return - * a Promise, in which case reduction will continue after each promise resolves. - * - * If the callback does not return a Promise, then this function will also not - * return a Promise. - */ - function promiseReduce(values, callbackFn, initialValue) { - let accumulator = initialValue; - for (const value of values) { - accumulator = (0, _isPromise.isPromise)(accumulator) ? accumulator.then(resolved => callbackFn(resolved, value)) : callbackFn(accumulator, value); + }; +} +/** + * @internal + */ + +function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var _schema$getDirectives; + const requiredArgsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = (_schema$getDirectives = schema === null || schema === void 0 ? void 0 : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 ? _schema$getDirectives : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = (0, _keyMap.keyMap)(directive.args.filter(_definition.isRequiredArgument), arg => arg.name); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; + requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)(argNodes.filter(isRequiredArgumentNode), arg => arg.name.value); } - return accumulator; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/suggestionList.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/suggestionList.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.suggestionList = suggestionList; - var _naturalCompare = __webpack_require__(/*! ./naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); - /** - * Given an invalid input string and a list of valid options, returns a filtered - * list of valid options sorted based on their similarity with the input. - */ - - function suggestionList(input, options) { - const optionsByDistance = Object.create(null); - const lexicalDistance = new LexicalDistance(input); - const threshold = Math.floor(input.length * 0.4) + 1; - for (const option of options) { - const distance = lexicalDistance.measure(option, threshold); - if (distance !== undefined) { - optionsByDistance[option] = distance; - } - } - return Object.keys(optionsByDistance).sort((a, b) => { - const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; - return distanceDiff !== 0 ? distanceDiff : (0, _naturalCompare.naturalCompare)(a, b); - }); } - /** - * Computes the lexical distance between strings A and B. - * - * The "distance" between two strings is given by counting the minimum number - * of edits needed to transform string A into string B. An edit can be an - * insertion, deletion, or substitution of a single character, or a swap of two - * adjacent characters. - * - * Includes a custom alteration from Damerau-Levenshtein to treat case changes - * as a single edit which helps identify mis-cased values with an edit distance - * of 1. - * - * This distance can be useful for detecting typos in input or sorting - */ - - class LexicalDistance { - constructor(input) { - this._input = input; - this._inputLowerCase = input.toLowerCase(); - this._inputArray = stringToArray(this._inputLowerCase); - this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)]; - } - measure(option, threshold) { - if (this._input === option) { - return 0; - } - const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit - - if (this._inputLowerCase === optionLowerCase) { - return 1; - } - let a = stringToArray(optionLowerCase); - let b = this._inputArray; - if (a.length < b.length) { - const tmp = a; - a = b; - b = tmp; + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + if (requiredArgs) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; + const argNodeMap = new Set(argNodes.map(arg => arg.name.value)); + for (const [argName, argDef] of Object.entries(requiredArgs)) { + if (!argNodeMap.has(argName)) { + const argType = (0, _definition.isType)(argDef.type) ? (0, _inspect.inspect)(argDef.type) : (0, _printer.print)(argDef.type); + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, { + nodes: directiveNode + })); + } + } + } } - const aLength = a.length; - const bLength = b.length; - if (aLength - bLength > threshold) { - return undefined; + } + }; +} +function isRequiredArgumentNode(arg) { + return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs": +/*!**************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs ***! + \**************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ScalarLeafsRule = ScalarLeafsRule; +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, { + nodes: selectionSet + })); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, { + nodes: node + })); + } } - const rows = this._rows; - for (let j = 0; j <= bLength; j++) { - rows[0][j] = j; - } - for (let i = 1; i <= aLength; i++) { - const upRow = rows[(i - 1) % 3]; - const currentRow = rows[i % 3]; - let smallestCell = currentRow[0] = i; - for (let j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - let currentCell = Math.min(upRow[j] + 1, - // delete - currentRow[j - 1] + 1, - // insert - upRow[j - 1] + cost // substitute - ); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - // transposition - const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; - currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs": +/*!***************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs ***! + \***************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _collectFields = __webpack_require__(/*! ../../execution/collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); +/** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + */ +function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === 'subscription') { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document = context.getDocument(); + const fragments = Object.create(null); + for (const definition of document.definitions) { + if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = definition; + } + } + const fields = (0, _collectFields.collectFields)(schema, fragments, variableValues, subscriptionType, node.selectionSet); + if (fields.size > 1) { + const fieldSelectionLists = [...fields.values()]; + const extraFieldSelectionLists = fieldSelectionLists.slice(1); + const extraFieldSelections = extraFieldSelectionLists.flat(); + context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must select only one top level field.` : 'Anonymous Subscription must select only one top level field.', { + nodes: extraFieldSelections + })); } - if (currentCell < smallestCell) { - smallestCell = currentCell; + for (const fieldNodes of fields.values()) { + const field = fieldNodes[0]; + const fieldName = field.name.value; + if (fieldName.startsWith('__')) { + context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must not select an introspection top level field.` : 'Anonymous Subscription must not select an introspection top level field.', { + nodes: fieldNodes + })); + } } - currentRow[j] = currentCell; - } // Early exit, since distance can't go smaller than smallest element of the previous row. - - if (smallestCell > threshold) { - return undefined; } } - const distance = rows[aLength % 3][bLength]; - return distance <= threshold ? distance : undefined; } - } - function stringToArray(str) { - const strLength = str.length; - const array = new Array(strLength); - for (let i = 0; i < strLength; ++i) { - array[i] = str.charCodeAt(i); - } - return array; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/toError.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/toError.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.toError = toError; - var _inspect = __webpack_require__(/*! ./inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - /** - * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. - */ - - function toError(thrownValue) { - return thrownValue instanceof Error ? thrownValue : new NonErrorThrown(thrownValue); - } - class NonErrorThrown extends Error { - constructor(thrownValue) { - super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); - this.name = 'NonErrorThrown'; - this.thrownValue = thrownValue; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs": +/*!********************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs ***! + \********************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; +var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique argument definition names + * + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. + */ +function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; + return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); + }, + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField + }; + function checkArgUniquenessPerField(typeNode) { + var _typeNode$fields; + const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = (_typeNode$fields = typeNode.fields) !== null && _typeNode$fields !== void 0 ? _typeNode$fields : []; + for (const fieldDef of fieldNodes) { + var _fieldDef$arguments; + const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = (_fieldDef$arguments = fieldDef.arguments) !== null && _fieldDef$arguments !== void 0 ? _fieldDef$arguments : []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); } + return false; } - - /***/ }), - - /***/ "../../../node_modules/graphql/jsutils/toObjMap.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/jsutils/toObjMap.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.toObjMap = toObjMap; - function toObjMap(obj) { - if (obj == null) { - return Object.create(null); - } - if (Object.getPrototypeOf(obj) === null) { - return obj; - } - const map = Object.create(null); - for (const [key, value] of Object.entries(obj)) { - map[key] = value; + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError(new _GraphQLError.GraphQLError(`Argument "${parentName}(${argName}:)" can only be defined once.`, { + nodes: argNodes.map(node => node.name) + })); + } } - return map; + return false; } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/ast.mjs": - /*!******************************************************!*\ - !*** ../../../node_modules/graphql/language/ast.mjs ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.Token = exports.QueryDocumentKeys = exports.OperationTypeNode = exports.Location = void 0; - exports.isNode = isNode; - /** - * Contains a range of UTF-8 character offsets and token references that - * identify the region of the source from which the AST derived. - */ - class Location { - /** - * The character offset at which this Node begins. - */ - - /** - * The character offset at which this Node ends. - */ - - /** - * The Token at which this Node begins. - */ - - /** - * The Token at which this Node ends. - */ - - /** - * The Source document the AST represents. - */ - constructor(startToken, endToken, source) { - this.start = startToken.start; - this.end = endToken.end; - this.startToken = startToken; - this.endToken = endToken; - this.source = source; - } - get [Symbol.toStringTag]() { - return 'Location'; - } - toJSON() { - return { - start: this.start, - end: this.end - }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs": +/*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs ***! + \**********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; +var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + */ +function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness + }; + function checkArgUniqueness(parentNode) { + var _parentNode$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = (_parentNode$arguments = parentNode.arguments) !== null && _parentNode$arguments !== void 0 ? _parentNode$arguments : []; + const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one argument named "${argName}".`, { + nodes: argNodes.map(node => node.name) + })); + } } } - /** - * Represents a range of characters represented by a lexical token - * within a Source. - */ - exports.Location = Location; - class Token { - /** - * The kind of Token. - */ - - /** - * The character offset at which this Node begins. - */ - - /** - * The character offset at which this Node ends. - */ - - /** - * The 1-indexed line number on which this Token appears. - */ - - /** - * The 1-indexed column number at which this Token begins. - */ - - /** - * For non-punctuation tokens, represents the interpreted value of the token. - * - * Note: is undefined for punctuation tokens, but typed as string for - * convenience in the parser. - */ - - /** - * Tokens exist as nodes in a double-linked-list amongst all tokens - * including ignored tokens. is always the first node and - * the last. - */ - constructor(kind, start, end, line, column, value) { - this.kind = kind; - this.start = start; - this.end = end; - this.line = line; - this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - - this.value = value; - this.prev = null; - this.next = null; - } - get [Symbol.toStringTag]() { - return 'Token'; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs": +/*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs ***! + \***********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + */ +function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) { + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, { + nodes: node.name + })); + return; + } + if (knownDirectiveNames[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one directive named "@${directiveName}".`, { + nodes: [knownDirectiveNames[directiveName], node.name] + })); + } else { + knownDirectiveNames[directiveName] = node.name; + } + return false; } - toJSON() { - return { - kind: this.kind, - value: this.value, - line: this.line, - column: this.column - }; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs": +/*!******************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs ***! + \******************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); +var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location + */ +function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (!('directives' in node) || !node.directives) { + return; + } + let seenDirectives; + if (node.kind === _kinds.Kind.SCHEMA_DEFINITION || node.kind === _kinds.Kind.SCHEMA_EXTENSION) { + seenDirectives = schemaDirectives; + } else if ((0, _predicates.isTypeDefinitionNode)(node) || (0, _predicates.isTypeExtensionNode)(node)) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + for (const directive of node.directives) { + const directiveName = directive.name.value; + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError(`The directive "@${directiveName}" can only be used once at this location.`, { + nodes: [seenDirectives[directiveName], directive] + })); + } else { + seenDirectives[directiveName] = directive; + } + } + } } - } - /** - * The list of all possible AST node types. - */ - - /** - * @internal - */ - exports.Token = Token; - const QueryDocumentKeys = exports.QueryDocumentKeys = { - Name: [], - Document: ['definitions'], - OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], - VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], - Variable: ['name'], - SelectionSet: ['selections'], - Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], - Argument: ['name', 'value'], - FragmentSpread: ['name', 'directives'], - InlineFragment: ['typeCondition', 'directives', 'selectionSet'], - FragmentDefinition: ['name', - // Note: fragment variable definitions are deprecated and will removed in v17.0.0 - 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], - IntValue: [], - FloatValue: [], - StringValue: [], - BooleanValue: [], - NullValue: [], - EnumValue: [], - ListValue: ['values'], - ObjectValue: ['fields'], - ObjectField: ['name', 'value'], - Directive: ['name', 'arguments'], - NamedType: ['name'], - ListType: ['type'], - NonNullType: ['type'], - SchemaDefinition: ['description', 'directives', 'operationTypes'], - OperationTypeDefinition: ['type'], - ScalarTypeDefinition: ['description', 'name', 'directives'], - ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], - FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], - InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], - InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], - UnionTypeDefinition: ['description', 'name', 'directives', 'types'], - EnumTypeDefinition: ['description', 'name', 'directives', 'values'], - EnumValueDefinition: ['description', 'name', 'directives'], - InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], - DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], - SchemaExtension: ['directives', 'operationTypes'], - ScalarTypeExtension: ['name', 'directives'], - ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], - InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], - UnionTypeExtension: ['name', 'directives', 'types'], - EnumTypeExtension: ['name', 'directives', 'values'], - InputObjectTypeExtension: ['name', 'directives', 'fields'] }; - const kindValues = new Set(Object.keys(QueryDocumentKeys)); - /** - * @internal - */ - - function isNode(maybeNode) { - const maybeKind = maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; - return typeof maybeKind === 'string' && kindValues.has(maybeKind); - } - /** Name */ - - var OperationTypeNode; - (function (OperationTypeNode) { - OperationTypeNode['QUERY'] = 'query'; - OperationTypeNode['MUTATION'] = 'mutation'; - OperationTypeNode['SUBSCRIPTION'] = 'subscription'; - })(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); - - /***/ }), - - /***/ "../../../node_modules/graphql/language/blockString.mjs": - /*!**************************************************************!*\ - !*** ../../../node_modules/graphql/language/blockString.mjs ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.dedentBlockStringLines = dedentBlockStringLines; - exports.isPrintableAsBlockString = isPrintableAsBlockString; - exports.printBlockString = printBlockString; - var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); - /** - * Produces the value of a block string from its parsed raw value, similar to - * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. - * - * This implements the GraphQL spec's BlockStringValue() static algorithm. - * - * @internal - */ - - function dedentBlockStringLines(lines) { - var _firstNonEmptyLine2; - let commonIndent = Number.MAX_SAFE_INTEGER; - let firstNonEmptyLine = null; - let lastNonEmptyLine = -1; - for (let i = 0; i < lines.length; ++i) { - var _firstNonEmptyLine; - const line = lines[i]; - const indent = leadingWhitespace(line); - if (indent === line.length) { - continue; // skip empty lines - } - firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i; - lastNonEmptyLine = i; - if (i !== 0 && indent < commonIndent) { - commonIndent = indent; - } - } - return lines // Remove common indentation from all lines but first. - .map((line, i) => i === 0 ? line : line.slice(commonIndent)) // Remove leading and trailing blank lines. - .slice((_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0, lastNonEmptyLine + 1); - } - function leadingWhitespace(str) { - let i = 0; - while (i < str.length && (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i))) { - ++i; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs": +/*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs ***! + \***********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ +function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness + }; + function checkValueUniqueness(node) { + var _node$values; + const typeName = node.name.value; + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; + const valueNames = knownValueNames[typeName]; + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) { + context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, { + nodes: valueDef.name + })); + } else if (valueNames[valueName]) { + context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" can only be defined once.`, { + nodes: [valueNames[valueName], valueDef.name] + })); + } else { + valueNames[valueName] = valueDef.name; + } } - return i; + return false; } - /** - * @internal - */ - - function isPrintableAsBlockString(value) { - if (value === '') { - return true; // empty string is printable - } - let isEmptyLine = true; - let hasIndent = false; - let hasCommonIndent = true; - let seenNonEmptyLine = false; - for (let i = 0; i < value.length; ++i) { - switch (value.codePointAt(i)) { - case 0x0000: - case 0x0001: - case 0x0002: - case 0x0003: - case 0x0004: - case 0x0005: - case 0x0006: - case 0x0007: - case 0x0008: - case 0x000b: - case 0x000c: - case 0x000e: - case 0x000f: - return false; - // Has non-printable characters - - case 0x000d: - // \r - return false; - // Has \r or \r\n which will be replaced as \n - - case 10: - // \n - if (isEmptyLine && !seenNonEmptyLine) { - return false; // Has leading new line - } - seenNonEmptyLine = true; - isEmptyLine = true; - hasIndent = false; - break; - case 9: // \t - - case 32: - // - hasIndent || (hasIndent = isEmptyLine); - break; - default: - hasCommonIndent && (hasCommonIndent = hasIndent); - isEmptyLine = false; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs": +/*!*****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs ***! + \*****************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ +function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness + }; + function checkFieldUniqueness(node) { + var _node$fields; + const typeName = node.name.value; + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; + const fieldNames = knownFieldNames[typeName]; + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, { + nodes: fieldDef.name + })); + } else if (fieldNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" can only be defined once.`, { + nodes: [fieldNames[fieldName], fieldDef.name] + })); + } else { + fieldNames[fieldName] = fieldDef.name; } } - if (isEmptyLine) { - return false; // Has trailing empty lines - } - if (hasCommonIndent && seenNonEmptyLine) { - return false; // Has internal indent - } - return true; + return false; } - /** - * Print a block string in the indented block form by adding a leading and - * trailing blank line. However, if a block string starts with whitespace and is - * a single-line, adding a leading blank line would strip that whitespace. - * - * @internal - */ - - function printBlockString(value, options) { - const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. - - const lines = escapedValue.split(/\r\n|[\n\r]/g); - const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line - - const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every(line => line.length === 0 || (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line - - const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line - - const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; - const hasTrailingSlash = value.endsWith('\\'); - const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; - const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && ( - // add leading and trailing new lines only if it improves readability - !isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes); - let result = ''; // Format a multi-line block quote to account for leading space. - - const skipLeadingNewLine = isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); - if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) { - result += '\n'; +} +function hasField(type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) { + return type.getFields()[fieldName] != null; + } + return false; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs": +/*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs ***! + \**********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + */ +function UniqueFragmentNamesRule(context) { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + if (knownFragmentNames[fragmentName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one fragment named "${fragmentName}".`, { + nodes: [knownFragmentNames[fragmentName], node.name] + })); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; } - result += escapedValue; - if (printAsMultipleLines || forceTrailingNewline) { - result += '\n'; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs": +/*!************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs ***! + \************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; +var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + */ +function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = Object.create(null); + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave() { + const prevKnownNames = knownNameStack.pop(); + prevKnownNames || (0, _invariant.invariant)(false); + knownNames = prevKnownNames; + } + }, + ObjectField(node) { + const fieldName = node.name.value; + if (knownNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one input field named "${fieldName}".`, { + nodes: [knownNames[fieldName], node.name] + })); + } else { + knownNames[fieldName] = node.name; + } } - return '"""' + result + '"""'; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/characterClasses.mjs": - /*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/language/characterClasses.mjs ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isDigit = isDigit; - exports.isLetter = isLetter; - exports.isNameContinue = isNameContinue; - exports.isNameStart = isNameStart; - exports.isWhiteSpace = isWhiteSpace; - /** - * ``` - * WhiteSpace :: - * - "Horizontal Tab (U+0009)" - * - "Space (U+0020)" - * ``` - * @internal - */ - function isWhiteSpace(code) { - return code === 0x0009 || code === 0x0020; - } - /** - * ``` - * Digit :: one of - * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` - * ``` - * @internal - */ - - function isDigit(code) { - return code >= 0x0030 && code <= 0x0039; - } - /** - * ``` - * Letter :: one of - * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` - * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` - * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` - * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` - * ``` - * @internal - */ - - function isLetter(code) { - return code >= 0x0061 && code <= 0x007a || - // A-Z - code >= 0x0041 && code <= 0x005a // a-z - ; - } - /** - * ``` - * NameStart :: - * - Letter - * - `_` - * ``` - * @internal - */ - - function isNameStart(code) { - return isLetter(code) || code === 0x005f; - } - /** - * ``` - * NameContinue :: - * - Letter - * - Digit - * - `_` - * ``` - * @internal - */ - - function isNameContinue(code) { - return isLetter(code) || isDigit(code) || code === 0x005f; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/directiveLocation.mjs": - /*!********************************************************************!*\ - !*** ../../../node_modules/graphql/language/directiveLocation.mjs ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.DirectiveLocation = void 0; - /** - * The set of allowed directive location values. - */ - var DirectiveLocation; - (function (DirectiveLocation) { - DirectiveLocation['QUERY'] = 'QUERY'; - DirectiveLocation['MUTATION'] = 'MUTATION'; - DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; - DirectiveLocation['FIELD'] = 'FIELD'; - DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; - DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; - DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; - DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; - DirectiveLocation['SCHEMA'] = 'SCHEMA'; - DirectiveLocation['SCALAR'] = 'SCALAR'; - DirectiveLocation['OBJECT'] = 'OBJECT'; - DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; - DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; - DirectiveLocation['INTERFACE'] = 'INTERFACE'; - DirectiveLocation['UNION'] = 'UNION'; - DirectiveLocation['ENUM'] = 'ENUM'; - DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; - DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; - DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; - })(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); - - /** - * The enum type representing the directive location values. - * - * @deprecated Please use `DirectiveLocation`. Will be remove in v17. - */ - - /***/ }), - - /***/ "../../../node_modules/graphql/language/index.mjs": - /*!********************************************************!*\ - !*** ../../../node_modules/graphql/language/index.mjs ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "BREAK", ({ - enumerable: true, - get: function () { - return _visitor.BREAK; - } - })); - Object.defineProperty(exports, "DirectiveLocation", ({ - enumerable: true, - get: function () { - return _directiveLocation.DirectiveLocation; - } - })); - Object.defineProperty(exports, "Kind", ({ - enumerable: true, - get: function () { - return _kinds.Kind; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs": +/*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs ***! + \***********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueOperationNamesRule = UniqueOperationNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + */ +function UniqueOperationNamesRule(context) { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one operation named "${operationName.value}".`, { + nodes: [knownOperationNames[operationName.value], operationName] + })); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + return false; + }, + FragmentDefinition: () => false + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs": +/*!***********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs ***! + \***********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueOperationTypesRule = UniqueOperationTypesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ +function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType() + } : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes + }; + function checkOperationTypes(node) { + var _node$operationTypes; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes[operation]; + if (existingOperationTypes[operation]) { + context.reportError(new _GraphQLError.GraphQLError(`Type for ${operation} already defined in the schema. It cannot be redefined.`, { + nodes: operationType + })); + } else if (alreadyDefinedOperationType) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one ${operation} type in schema.`, { + nodes: [alreadyDefinedOperationType, operationType] + })); + } else { + definedOperationTypes[operation] = operationType; + } } - })); - Object.defineProperty(exports, "Lexer", ({ - enumerable: true, - get: function () { - return _lexer.Lexer; + return false; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs": +/*!******************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs ***! + \******************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueTypeNamesRule = UniqueTypeNamesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + */ +function UniqueTypeNamesRule(context) { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName + }; + function checkTypeName(node) { + const typeName = node.name.value; + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError(new _GraphQLError.GraphQLError(`Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, { + nodes: node.name + })); + return; } - })); - Object.defineProperty(exports, "Location", ({ - enumerable: true, - get: function () { - return _ast.Location; + if (knownTypeNames[typeName]) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one type named "${typeName}".`, { + nodes: [knownTypeNames[typeName], node.name] + })); + } else { + knownTypeNames[typeName] = node.name; } - })); - Object.defineProperty(exports, "OperationTypeNode", ({ - enumerable: true, - get: function () { - return _ast.OperationTypeNode; + return false; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs": +/*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs ***! + \**********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UniqueVariableNamesRule = UniqueVariableNamesRule; +var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + var _operationNode$variab; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const variableDefinitions = (_operationNode$variab = operationNode.variableDefinitions) !== null && _operationNode$variab !== void 0 ? _operationNode$variab : []; + const seenVariableDefinitions = (0, _groupBy.groupBy)(variableDefinitions, node => node.variable.name.value); + for (const [variableName, variableNodes] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError(new _GraphQLError.GraphQLError(`There can be only one variable named "$${variableName}".`, { + nodes: variableNodes.map(node => node.variable.name) + })); + } + } } - })); - Object.defineProperty(exports, "Source", ({ - enumerable: true, - get: function () { - return _source.Source; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs": +/*!**********************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs ***! + \**********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; +var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); +var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + */ +function ValuesOfCorrectTypeRule(context) { + return { + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = (0, _definition.getNullableType)(context.getParentInputType()); + if (!(0, _definition.isListType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue(node) { + const type = (0, _definition.getNamedType)(context.getInputType()); + if (!(0, _definition.isInputObjectType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + const fieldNodeMap = (0, _keyMap.keyMap)(node.fields, field => field.name.value); + for (const fieldDef of Object.values(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + const typeStr = (0, _inspect.inspect)(fieldDef.type); + context.reportError(new _GraphQLError.GraphQLError(`Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, { + nodes: node + })); + } + } + }, + ObjectField(node) { + const parentType = (0, _definition.getNamedType)(context.getParentInputType()); + const fieldType = context.getInputType(); + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + const suggestions = (0, _suggestionList.suggestionList)(node.name.value, Object.keys(parentType.getFields())); + context.reportError(new _GraphQLError.GraphQLError(`Field "${node.name.value}" is not defined by type "${parentType.name}".` + (0, _didYouMean.didYouMean)(suggestions), { + nodes: node + })); + } + }, + NullValue(node) { + const type = context.getInputType(); + if ((0, _definition.isNonNullType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${(0, _inspect.inspect)(type)}", found ${(0, _printer.print)(node)}.`, { + nodes: node + })); + } + }, + EnumValue: node => isValidValueNode(context, node), + IntValue: node => isValidValueNode(context, node), + FloatValue: node => isValidValueNode(context, node), + StringValue: node => isValidValueNode(context, node), + BooleanValue: node => isValidValueNode(context, node) + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + +function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + if (!locationType) { + return; + } + const type = (0, _definition.getNamedType)(locationType); + if (!(0, _definition.isLeafType)(type)) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { + nodes: node + })); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + try { + const parseResult = type.parseLiteral(node, undefined + /* variables */); + if (parseResult === undefined) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { + nodes: node + })); } - })); - Object.defineProperty(exports, "Token", ({ - enumerable: true, - get: function () { - return _ast.Token; + } catch (error) { + const typeStr = (0, _inspect.inspect)(locationType); + if (error instanceof _GraphQLError.GraphQLError) { + context.reportError(error); + } else { + context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}; ` + error.message, { + nodes: node, + originalError: error + })); } - })); - Object.defineProperty(exports, "TokenKind", ({ - enumerable: true, - get: function () { - return _tokenKind.TokenKind; + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs": +/*!*************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs ***! + \*************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + * + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types + */ +function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); + if (type !== undefined && !(0, _definition.isInputType)(type)) { + const variableName = node.variable.name.value; + const typeName = (0, _printer.print)(node.type); + context.reportError(new _GraphQLError.GraphQLError(`Variable "$${variableName}" cannot be non-input type "${typeName}".`, { + nodes: node.type + })); + } } - })); - Object.defineProperty(exports, "getEnterLeaveForKind", ({ - enumerable: true, - get: function () { - return _visitor.getEnterLeaveForKind; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs": +/*!*****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs ***! + \*****************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; +var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); +var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); +var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); +/** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + */ +function VariablesInAllowedPositionRule(context) { + let varDefMap = Object.create(null); + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { + node, + type, + defaultValue + } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + const varTypeStr = (0, _inspect.inspect)(varType); + const typeStr = (0, _inspect.inspect)(type); + context.reportError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, { + nodes: [varDef, node] + })); + } + } + } + } + }, + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; } - })); - Object.defineProperty(exports, "getLocation", ({ - enumerable: true, - get: function () { - return _location.getLocation; + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { + const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; } - })); - Object.defineProperty(exports, "getVisitFn", ({ - enumerable: true, - get: function () { - return _visitor.getVisitFn; + const nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); + } + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs": +/*!****************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs ***! + \****************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; +var _invariant = __webpack_require__(/*! ../../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); +var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ +function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason; + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + parentType != null || (0, _invariant.invariant)(false); + context.reportError(new _GraphQLError.GraphQLError(`The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, { + nodes: node + })); + } + }, + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = argDef === null || argDef === void 0 ? void 0 : argDef.deprecationReason; + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); + if (directiveDef != null) { + context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { + nodes: node + })); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + parentType != null && fieldDef != null || (0, _invariant.invariant)(false); + context.reportError(new _GraphQLError.GraphQLError(`Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { + nodes: node + })); + } + } + }, + ObjectField(node) { + const inputObjectDef = (0, _definition.getNamedType)(context.getParentInputType()); + if ((0, _definition.isInputObjectType)(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + const deprecationReason = inputFieldDef === null || inputFieldDef === void 0 ? void 0 : inputFieldDef.deprecationReason; + if (deprecationReason != null) { + context.reportError(new _GraphQLError.GraphQLError(`The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, { + nodes: node + })); + } + } + }, + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason; + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = (0, _definition.getNamedType)(context.getInputType()); + enumTypeDef != null || (0, _invariant.invariant)(false); + context.reportError(new _GraphQLError.GraphQLError(`The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, { + nodes: node + })); + } } - })); - Object.defineProperty(exports, "isConstValueNode", ({ - enumerable: true, - get: function () { - return _predicates.isConstValueNode; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs": +/*!*************************************************************************************************!*\ + !*** ../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs ***! + \*************************************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; +var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); +var _introspection = __webpack_require__(/*! ../../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + */ +function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = (0, _definition.getNamedType)(context.getType()); + if (type && (0, _introspection.isIntrospectionType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(`GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, { + nodes: node + })); + } } - })); - Object.defineProperty(exports, "isDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isDefinitionNode; - } - })); - Object.defineProperty(exports, "isExecutableDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isExecutableDefinitionNode; - } - })); - Object.defineProperty(exports, "isSelectionNode", ({ - enumerable: true, - get: function () { - return _predicates.isSelectionNode; + }; +} + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/specifiedRules.mjs": +/*!*******************************************************************!*\ + !*** ../../../node_modules/graphql/validation/specifiedRules.mjs ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.specifiedSDLRules = exports.specifiedRules = void 0; +var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); +var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); +var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); +var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); +var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); +var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); +var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); +var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); +var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); +var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); +var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); +var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); +var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); +var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); +var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); +var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); +var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); +var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); +var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); +var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); +var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); +var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); +var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); +var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); +var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); +var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); +var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); +var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); +var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); +var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); +var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); +var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); +var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); +var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); +// Spec Section: "Executable Definitions" +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +// Spec Section: "Fragments on Composite Types" + +// Spec Section: "Argument Names" + +// Spec Section: "Directives Are Defined" + +// Spec Section: "Fragment spread target defined" + +// Spec Section: "Fragment Spread Type Existence" + +// Spec Section: "Lone Anonymous Operation" + +// SDL-specific validation rules + +// Spec Section: "Fragments must not form cycles" + +// Spec Section: "All Variable Used Defined" + +// Spec Section: "Fragments must be used" + +// Spec Section: "All Variables Used" + +// Spec Section: "Field Selection Merging" + +// Spec Section: "Fragment spread is possible" + +// Spec Section: "Argument Optionality" + +// Spec Section: "Leaf Field Selections" + +// Spec Section: "Subscriptions with Single Root Field" + +// Spec Section: "Argument Uniqueness" + +// Spec Section: "Directives Are Unique Per Location" + +// Spec Section: "Fragment Name Uniqueness" + +// Spec Section: "Input Object Field Uniqueness" + +// Spec Section: "Operation Name Uniqueness" + +// Spec Section: "Variable Uniqueness" + +// Spec Section: "Value Type Correctness" + +// Spec Section: "Variables are Input Types" + +// Spec Section: "All Variable Usages Are Allowed" + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +const specifiedRules = exports.specifiedRules = Object.freeze([_ExecutableDefinitionsRule.ExecutableDefinitionsRule, _UniqueOperationNamesRule.UniqueOperationNamesRule, _LoneAnonymousOperationRule.LoneAnonymousOperationRule, _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, _KnownTypeNamesRule.KnownTypeNamesRule, _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, _VariablesAreInputTypesRule.VariablesAreInputTypesRule, _ScalarLeafsRule.ScalarLeafsRule, _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, _UniqueFragmentNamesRule.UniqueFragmentNamesRule, _KnownFragmentNamesRule.KnownFragmentNamesRule, _NoUnusedFragmentsRule.NoUnusedFragmentsRule, _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, _NoFragmentCyclesRule.NoFragmentCyclesRule, _UniqueVariableNamesRule.UniqueVariableNamesRule, _NoUndefinedVariablesRule.NoUndefinedVariablesRule, _NoUnusedVariablesRule.NoUnusedVariablesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _KnownArgumentNamesRule.KnownArgumentNamesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule]); +/** + * @internal + */ + +const specifiedSDLRules = exports.specifiedSDLRules = Object.freeze([_LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, _UniqueOperationTypesRule.UniqueOperationTypesRule, _UniqueTypeNamesRule.UniqueTypeNamesRule, _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, _KnownTypeNamesRule.KnownTypeNamesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule]); + +/***/ }), + +/***/ "../../../node_modules/graphql/validation/validate.mjs": +/*!*************************************************************!*\ + !*** ../../../node_modules/graphql/validation/validate.mjs ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.assertValidSDL = assertValidSDL; +exports.assertValidSDLExtension = assertValidSDLExtension; +exports.validate = validate; +exports.validateSDL = validateSDL; +var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); +var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); +var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); +var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); +var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); +var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); +var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so by default `maxErrors` set to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ + +function validate(schema, documentAST, rules = _specifiedRules.specifiedRules, options, /** @deprecated will be removed in 17.0.0 */ +typeInfo = new _TypeInfo.TypeInfo(schema)) { + var _options$maxErrors; + const maxErrors = (_options$maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors) !== null && _options$maxErrors !== void 0 ? _options$maxErrors : 100; + documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + const abortObj = Object.freeze({}); + const errors = []; + const context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo, error => { + if (errors.length >= maxErrors) { + errors.push(new _GraphQLError.GraphQLError('Too many validation errors, error limit reached. Validation aborted.')); // eslint-disable-next-line @typescript-eslint/no-throw-literal + + throw abortObj; } - })); - Object.defineProperty(exports, "isTypeDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeDefinitionNode; + errors.push(error); + }); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + const visitor = (0, _visitor.visitInParallel)(rules.map(rule => rule(context))); // Visit the whole document with each instance of all provided rules. + + try { + (0, _visitor.visit)(documentAST, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor)); + } catch (e) { + if (e !== abortObj) { + throw e; } - })); - Object.defineProperty(exports, "isTypeExtensionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeExtensionNode; + } + return errors; +} +/** + * @internal + */ + +function validateSDL(documentAST, schemaToExtend, rules = _specifiedRules.specifiedSDLRules) { + const errors = []; + const context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend, error => { + errors.push(error); + }); + const visitors = rules.map(rule => rule(context)); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return errors; +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} + +/***/ }), + +/***/ "../../../node_modules/graphql/version.mjs": +/*!*************************************************!*\ + !*** ../../../node_modules/graphql/version.mjs ***! + \*************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.versionInfo = exports.version = void 0; +// Note: This file is autogenerated using "resources/gen-version.js" script and +// automatically updated by "npm version" command. + +/** + * A string containing the version of the GraphQL.js library + */ +const version = exports.version = '16.8.1'; +/** + * An object containing the components of the GraphQL.js version string + */ + +const versionInfo = exports.versionInfo = Object.freeze({ + major: 16, + minor: 8, + patch: 1, + preReleaseTag: null +}); + +/***/ }), + +/***/ "../../../node_modules/hey-listen/dist/hey-listen.es.js": +/*!**************************************************************!*\ + !*** ../../../node_modules/hey-listen/dist/hey-listen.es.js ***! + \**************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.warning = exports.invariant = void 0; +var warning = function () {}; +exports.warning = warning; +var invariant = function () {}; +exports.invariant = invariant; +if (true) { + exports.warning = warning = function (check, message) { + if (!check && typeof console !== 'undefined') { + console.warn(message); } - })); - Object.defineProperty(exports, "isTypeNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeNode; + }; + exports.invariant = invariant = function (check, message) { + if (!check) { + throw new Error(message); } - })); - Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeSystemDefinitionNode; + }; +} + +/***/ }), + +/***/ "../../../node_modules/is-plain-object/index.js": +/*!******************************************************!*\ + !*** ../../../node_modules/is-plain-object/index.js ***! + \******************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isObject = __webpack_require__(/*! isobject */ "../../../node_modules/isobject/index.js"); +function isObjectObject(o) { + return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; +} +module.exports = function isPlainObject(o) { + var ctor, prot; + if (isObjectObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (typeof ctor !== 'function') return false; + + // If has modified prototype + prot = ctor.prototype; + if (isObjectObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +}; + +/***/ }), + +/***/ "../../../node_modules/is-primitive/index.js": +/*!***************************************************!*\ + !*** ../../../node_modules/is-primitive/index.js ***! + \***************************************************/ +/***/ (function(module) { + +/*! + * is-primitive + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function isPrimitive(val) { + if (typeof val === 'object') { + return val === null; + } + return typeof val !== 'function'; +}; + +/***/ }), + +/***/ "../../../node_modules/isarray/index.js": +/*!**********************************************!*\ + !*** ../../../node_modules/isarray/index.js ***! + \**********************************************/ +/***/ (function(module) { + + + +var toString = {}.toString; +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +/***/ }), + +/***/ "../../../node_modules/isobject/index.js": +/*!***********************************************!*\ + !*** ../../../node_modules/isobject/index.js ***! + \***********************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isArray = __webpack_require__(/*! isarray */ "../../../node_modules/isarray/index.js"); +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; +}; + +/***/ }), + +/***/ "../../../node_modules/meros/browser/index.js": +/*!****************************************************!*\ + !*** ../../../node_modules/meros/browser/index.js ***! + \****************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +var e = new TextDecoder(); +async function t(t, n) { + if (!t.ok || !t.body || t.bodyUsed) return t; + let i = t.headers.get("content-type"); + if (!i || !~i.indexOf("multipart/")) return t; + let l = i.indexOf("boundary="), + r = "-"; + if (~l) { + let e = l + 9, + t = i.indexOf(";", e); + r = i.slice(e, t > -1 ? t : void 0).trim().replace(/"/g, ""); + } + return async function* (t, n, i) { + let l, + r, + d, + o = t.getReader(), + a = !i || !i.multiple, + f = n.length, + s = "", + c = []; + try { + let t; + e: for (; !(t = await o.read()).done;) { + let i = e.decode(t.value); + l = s.length, s += i; + let o = i.indexOf(n); + for (~o ? l += o : l = s.indexOf(n), c = []; ~l;) { + let e = s.slice(0, l), + t = s.slice(l + f); + if (r) { + let n = e.indexOf("\r\n\r\n") + 4, + i = e.lastIndexOf("\r\n", n), + l = !1, + r = e.slice(n, i > -1 ? void 0 : i), + o = String(e.slice(0, n)).trim().split("\r\n"), + f = {}, + s = o.length; + for (; d = o[--s]; d = d.split(": "), f[d.shift().toLowerCase()] = d.join(": ")); + if (d = f["content-type"], d && ~d.indexOf("application/json")) try { + r = JSON.parse(r), l = !0; + } catch (e) {} + if (d = { + headers: f, + body: r, + json: l + }, a ? yield d : c.push(d), "--" === t.slice(0, 2)) break e; + } else n = "\r\n" + n, r = f += 2; + s = t, l = s.indexOf(n); + } + c.length && (yield c); + } + } finally { + c.length && (yield c), await o.cancel(); } - })); - Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ - enumerable: true, - get: function () { - return _predicates.isTypeSystemExtensionNode; + }(t.body, `--${r}`, n); +} +exports.meros = t; + +/***/ }), + +/***/ "../../../node_modules/nullthrows/nullthrows.js": +/*!******************************************************!*\ + !*** ../../../node_modules/nullthrows/nullthrows.js ***! + \******************************************************/ +/***/ (function(module) { + + + +function nullthrows(x, message) { + if (x != null) { + return x; + } + var error = new Error(message !== undefined ? message : 'Got unexpected ' + x); + error.framesToPop = 1; // Skip nullthrows's own stack frame. + throw error; +} +module.exports = nullthrows; +module.exports["default"] = nullthrows; +Object.defineProperty(module.exports, "__esModule", ({ + value: true +})); + +/***/ }), + +/***/ "../../../node_modules/popmotion/dist/popmotion.cjs.js": +/*!*************************************************************!*\ + !*** ../../../node_modules/popmotion/dist/popmotion.cjs.js ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); +var styleValueTypes = __webpack_require__(/*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js"); +var sync = __webpack_require__(/*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js"); +function _interopDefaultLegacy(e) { + return e && typeof e === 'object' && 'default' in e ? e : { + 'default': e + }; +} +var sync__default = /*#__PURE__*/_interopDefaultLegacy(sync); +const clamp = (min, max, v) => Math.min(Math.max(v, min), max); +const safeMin = 0.001; +const minDuration = 0.01; +const maxDuration = 10.0; +const minDamping = 0.05; +const maxDamping = 1; +function findSpring({ + duration = 800, + bounce = 0.25, + velocity = 0, + mass = 1 +}) { + let envelope; + let derivative; + heyListen.warning(duration <= maxDuration * 1000, "Spring duration must be 10 seconds or less"); + let dampingRatio = 1 - bounce; + dampingRatio = clamp(minDamping, maxDamping, dampingRatio); + duration = clamp(minDuration, maxDuration, duration / 1000); + if (dampingRatio < 1) { + envelope = undampedFreq => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const a = exponentialDecay - velocity; + const b = calcAngularFreq(undampedFreq, dampingRatio); + const c = Math.exp(-delta); + return safeMin - a / b * c; + }; + derivative = undampedFreq => { + const exponentialDecay = undampedFreq * dampingRatio; + const delta = exponentialDecay * duration; + const d = delta * velocity + velocity; + const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration; + const f = Math.exp(-delta); + const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio); + const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1; + return factor * ((d - e) * f) / g; + }; + } else { + envelope = undampedFreq => { + const a = Math.exp(-undampedFreq * duration); + const b = (undampedFreq - velocity) * duration + 1; + return -safeMin + a * b; + }; + derivative = undampedFreq => { + const a = Math.exp(-undampedFreq * duration); + const b = (velocity - undampedFreq) * (duration * duration); + return a * b; + }; + } + const initialGuess = 5 / duration; + const undampedFreq = approximateRoot(envelope, derivative, initialGuess); + duration = duration * 1000; + if (isNaN(undampedFreq)) { + return { + stiffness: 100, + damping: 10, + duration + }; + } else { + const stiffness = Math.pow(undampedFreq, 2) * mass; + return { + stiffness, + damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), + duration + }; + } +} +const rootIterations = 12; +function approximateRoot(envelope, derivative, initialGuess) { + let result = initialGuess; + for (let i = 1; i < rootIterations; i++) { + result = result - envelope(result) / derivative(result); + } + return result; +} +function calcAngularFreq(undampedFreq, dampingRatio) { + return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); +} +const durationKeys = ["duration", "bounce"]; +const physicsKeys = ["stiffness", "damping", "mass"]; +function isSpringType(options, keys) { + return keys.some(key => options[key] !== undefined); +} +function getSpringOptions(options) { + let springOptions = Object.assign({ + velocity: 0.0, + stiffness: 100, + damping: 10, + mass: 1.0, + isResolvedFromDuration: false + }, options); + if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) { + const derived = findSpring(options); + springOptions = Object.assign(Object.assign(Object.assign({}, springOptions), derived), { + velocity: 0.0, + mass: 1.0 + }); + springOptions.isResolvedFromDuration = true; + } + return springOptions; +} +function spring(_a) { + var { + from = 0.0, + to = 1.0, + restSpeed = 2, + restDelta + } = _a, + options = tslib.__rest(_a, ["from", "to", "restSpeed", "restDelta"]); + const state = { + done: false, + value: from + }; + let { + stiffness, + damping, + mass, + velocity, + duration, + isResolvedFromDuration + } = getSpringOptions(options); + let resolveSpring = zero; + let resolveVelocity = zero; + function createSpring() { + const initialVelocity = velocity ? -(velocity / 1000) : 0.0; + const initialDelta = to - from; + const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); + const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; + if (restDelta === undefined) { + restDelta = Math.min(Math.abs(to - from) / 100, 0.4); } - })); - Object.defineProperty(exports, "isValueNode", ({ - enumerable: true, - get: function () { - return _predicates.isValueNode; + if (dampingRatio < 1) { + const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); + resolveSpring = t => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); + }; + resolveVelocity = t => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + return dampingRatio * undampedAngularFreq * envelope * (Math.sin(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq + initialDelta * Math.cos(angularFreq * t)) - envelope * (Math.cos(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) - angularFreq * initialDelta * Math.sin(angularFreq * t)); + }; + } else if (dampingRatio === 1) { + resolveSpring = t => to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t); + } else { + const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); + resolveSpring = t => { + const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); + const freqForT = Math.min(dampedAngularFreq * t, 300); + return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq; + }; } - })); - Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parser.parse; + } + createSpring(); + return { + next: t => { + const current = resolveSpring(t); + if (!isResolvedFromDuration) { + const currentVelocity = resolveVelocity(t) * 1000; + const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; + const isBelowDisplacementThreshold = Math.abs(to - current) <= restDelta; + state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold; + } else { + state.done = t >= duration; + } + state.value = state.done ? to : current; + return state; + }, + flipTarget: () => { + velocity = -velocity; + [from, to] = [to, from]; + createSpring(); } - })); - Object.defineProperty(exports, "parseConstValue", ({ - enumerable: true, - get: function () { - return _parser.parseConstValue; + }; +} +spring.needsInterpolation = (a, b) => typeof a === "string" || typeof b === "string"; +const zero = _t => 0; +const progress = (from, to, value) => { + const toFromDifference = to - from; + return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; +}; +const mix = (from, to, progress) => -progress * from + progress * to + from; +function hueToRgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; +} +function hslaToRgba({ + hue, + saturation, + lightness, + alpha +}) { + hue /= 360; + saturation /= 100; + lightness /= 100; + let red = 0; + let green = 0; + let blue = 0; + if (!saturation) { + red = green = blue = lightness; + } else { + const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; + const p = 2 * lightness - q; + red = hueToRgb(p, q, hue + 1 / 3); + green = hueToRgb(p, q, hue); + blue = hueToRgb(p, q, hue - 1 / 3); + } + return { + red: Math.round(red * 255), + green: Math.round(green * 255), + blue: Math.round(blue * 255), + alpha + }; +} +const mixLinearColor = (from, to, v) => { + const fromExpo = from * from; + const toExpo = to * to; + return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo)); +}; +const colorTypes = [styleValueTypes.hex, styleValueTypes.rgba, styleValueTypes.hsla]; +const getColorType = v => colorTypes.find(type => type.test(v)); +const notAnimatable = color => `'${color}' is not an animatable color. Use the equivalent color code instead.`; +const mixColor = (from, to) => { + let fromColorType = getColorType(from); + let toColorType = getColorType(to); + heyListen.invariant(!!fromColorType, notAnimatable(from)); + heyListen.invariant(!!toColorType, notAnimatable(to)); + let fromColor = fromColorType.parse(from); + let toColor = toColorType.parse(to); + if (fromColorType === styleValueTypes.hsla) { + fromColor = hslaToRgba(fromColor); + fromColorType = styleValueTypes.rgba; + } + if (toColorType === styleValueTypes.hsla) { + toColor = hslaToRgba(toColor); + toColorType = styleValueTypes.rgba; + } + const blended = Object.assign({}, fromColor); + return v => { + for (const key in blended) { + if (key !== "alpha") { + blended[key] = mixLinearColor(fromColor[key], toColor[key], v); + } + } + blended.alpha = mix(fromColor.alpha, toColor.alpha, v); + return fromColorType.transform(blended); + }; +}; +const zeroPoint = { + x: 0, + y: 0, + z: 0 +}; +const isNum = v => typeof v === 'number'; +const combineFunctions = (a, b) => v => b(a(v)); +const pipe = (...transformers) => transformers.reduce(combineFunctions); +function getMixer(origin, target) { + if (isNum(origin)) { + return v => mix(origin, target, v); + } else if (styleValueTypes.color.test(origin)) { + return mixColor(origin, target); + } else { + return mixComplex(origin, target); + } +} +const mixArray = (from, to) => { + const output = [...from]; + const numValues = output.length; + const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i])); + return v => { + for (let i = 0; i < numValues; i++) { + output[i] = blendValue[i](v); } - })); - Object.defineProperty(exports, "parseType", ({ - enumerable: true, - get: function () { - return _parser.parseType; + return output; + }; +}; +const mixObject = (origin, target) => { + const output = Object.assign(Object.assign({}, origin), target); + const blendValue = {}; + for (const key in output) { + if (origin[key] !== undefined && target[key] !== undefined) { + blendValue[key] = getMixer(origin[key], target[key]); } - })); - Object.defineProperty(exports, "parseValue", ({ - enumerable: true, - get: function () { - return _parser.parseValue; + } + return v => { + for (const key in blendValue) { + output[key] = blendValue[key](v); } - })); - Object.defineProperty(exports, "print", ({ - enumerable: true, - get: function () { - return _printer.print; + return output; + }; +}; +function analyse(value) { + const parsed = styleValueTypes.complex.parse(value); + const numValues = parsed.length; + let numNumbers = 0; + let numRGB = 0; + let numHSL = 0; + for (let i = 0; i < numValues; i++) { + if (numNumbers || typeof parsed[i] === "number") { + numNumbers++; + } else { + if (parsed[i].hue !== undefined) { + numHSL++; + } else { + numRGB++; + } } - })); - Object.defineProperty(exports, "printLocation", ({ - enumerable: true, - get: function () { - return _printLocation.printLocation; + } + return { + parsed, + numNumbers, + numRGB, + numHSL + }; +} +const mixComplex = (origin, target) => { + const template = styleValueTypes.complex.createTransformer(target); + const originStats = analyse(origin); + const targetStats = analyse(target); + const canInterpolate = originStats.numHSL === targetStats.numHSL && originStats.numRGB === targetStats.numRGB && originStats.numNumbers >= targetStats.numNumbers; + if (canInterpolate) { + return pipe(mixArray(originStats.parsed, targetStats.parsed), template); + } else { + heyListen.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`); + return p => `${p > 0 ? target : origin}`; + } +}; +const mixNumber = (from, to) => p => mix(from, to, p); +function detectMixerFactory(v) { + if (typeof v === 'number') { + return mixNumber; + } else if (typeof v === 'string') { + if (styleValueTypes.color.test(v)) { + return mixColor; + } else { + return mixComplex; + } + } else if (Array.isArray(v)) { + return mixArray; + } else if (typeof v === 'object') { + return mixObject; + } +} +function createMixers(output, ease, customMixer) { + const mixers = []; + const mixerFactory = customMixer || detectMixerFactory(output[0]); + const numMixers = output.length - 1; + for (let i = 0; i < numMixers; i++) { + let mixer = mixerFactory(output[i], output[i + 1]); + if (ease) { + const easingFunction = Array.isArray(ease) ? ease[i] : ease; + mixer = pipe(easingFunction, mixer); + } + mixers.push(mixer); + } + return mixers; +} +function fastInterpolate([from, to], [mixer]) { + return v => mixer(progress(from, to, v)); +} +function slowInterpolate(input, mixers) { + const inputLength = input.length; + const lastInputIndex = inputLength - 1; + return v => { + let mixerIndex = 0; + let foundMixerIndex = false; + if (v <= input[0]) { + foundMixerIndex = true; + } else if (v >= input[lastInputIndex]) { + mixerIndex = lastInputIndex - 1; + foundMixerIndex = true; + } + if (!foundMixerIndex) { + let i = 1; + for (; i < inputLength; i++) { + if (input[i] > v || i === lastInputIndex) { + break; + } + } + mixerIndex = i - 1; } - })); - Object.defineProperty(exports, "printSourceLocation", ({ - enumerable: true, - get: function () { - return _printLocation.printSourceLocation; + const progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v); + return mixers[mixerIndex](progressInRange); + }; +} +function interpolate(input, output, { + clamp: isClamp = true, + ease, + mixer +} = {}) { + const inputLength = input.length; + heyListen.invariant(inputLength === output.length, 'Both input and output ranges must be the same length'); + heyListen.invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1, 'Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values.'); + if (input[0] > input[inputLength - 1]) { + input = [].concat(input); + output = [].concat(output); + input.reverse(); + output.reverse(); + } + const mixers = createMixers(output, ease, mixer); + const interpolator = inputLength === 2 ? fastInterpolate(input, mixers) : slowInterpolate(input, mixers); + return isClamp ? v => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator; +} +const reverseEasing = easing => p => 1 - easing(1 - p); +const mirrorEasing = easing => p => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; +const createExpoIn = power => p => Math.pow(p, power); +const createBackIn = power => p => p * p * ((power + 1) * p - power); +const createAnticipate = power => { + const backEasing = createBackIn(power); + return p => (p *= 2) < 1 ? 0.5 * backEasing(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); +}; +const DEFAULT_OVERSHOOT_STRENGTH = 1.525; +const BOUNCE_FIRST_THRESHOLD = 4.0 / 11.0; +const BOUNCE_SECOND_THRESHOLD = 8.0 / 11.0; +const BOUNCE_THIRD_THRESHOLD = 9.0 / 10.0; +const linear = p => p; +const easeIn = createExpoIn(2); +const easeOut = reverseEasing(easeIn); +const easeInOut = mirrorEasing(easeIn); +const circIn = p => 1 - Math.sin(Math.acos(p)); +const circOut = reverseEasing(circIn); +const circInOut = mirrorEasing(circOut); +const backIn = createBackIn(DEFAULT_OVERSHOOT_STRENGTH); +const backOut = reverseEasing(backIn); +const backInOut = mirrorEasing(backIn); +const anticipate = createAnticipate(DEFAULT_OVERSHOOT_STRENGTH); +const ca = 4356.0 / 361.0; +const cb = 35442.0 / 1805.0; +const cc = 16061.0 / 1805.0; +const bounceOut = p => { + if (p === 1 || p === 0) return p; + const p2 = p * p; + return p < BOUNCE_FIRST_THRESHOLD ? 7.5625 * p2 : p < BOUNCE_SECOND_THRESHOLD ? 9.075 * p2 - 9.9 * p + 3.4 : p < BOUNCE_THIRD_THRESHOLD ? ca * p2 - cb * p + cc : 10.8 * p * p - 20.52 * p + 10.72; +}; +const bounceIn = reverseEasing(bounceOut); +const bounceInOut = p => p < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - p * 2.0)) : 0.5 * bounceOut(p * 2.0 - 1.0) + 0.5; +function defaultEasing(values, easing) { + return values.map(() => easing || easeInOut).splice(0, values.length - 1); +} +function defaultOffset(values) { + const numValues = values.length; + return values.map((_value, i) => i !== 0 ? i / (numValues - 1) : 0); +} +function convertOffsetToTimes(offset, duration) { + return offset.map(o => o * duration); +} +function keyframes({ + from = 0, + to = 1, + ease, + offset, + duration = 300 +}) { + const state = { + done: false, + value: from + }; + const values = Array.isArray(to) ? to : [from, to]; + const times = convertOffsetToTimes(offset && offset.length === values.length ? offset : defaultOffset(values), duration); + function createInterpolator() { + return interpolate(times, values, { + ease: Array.isArray(ease) ? ease : defaultEasing(values, ease) + }); + } + let interpolator = createInterpolator(); + return { + next: t => { + state.value = interpolator(t); + state.done = t >= duration; + return state; + }, + flipTarget: () => { + values.reverse(); + interpolator = createInterpolator(); } - })); - Object.defineProperty(exports, "visit", ({ - enumerable: true, - get: function () { - return _visitor.visit; + }; +} +function decay({ + velocity = 0, + from = 0, + power = 0.8, + timeConstant = 350, + restDelta = 0.5, + modifyTarget +}) { + const state = { + done: false, + value: from + }; + let amplitude = power * velocity; + const ideal = from + amplitude; + const target = modifyTarget === undefined ? ideal : modifyTarget(ideal); + if (target !== ideal) amplitude = target - from; + return { + next: t => { + const delta = -amplitude * Math.exp(-t / timeConstant); + state.done = !(delta > restDelta || delta < -restDelta); + state.value = state.done ? target : target + delta; + return state; + }, + flipTarget: () => {} + }; +} +const types = { + keyframes, + spring, + decay +}; +function detectAnimationFromOptions(config) { + if (Array.isArray(config.to)) { + return keyframes; + } else if (types[config.type]) { + return types[config.type]; + } + const keys = new Set(Object.keys(config)); + if (keys.has("ease") || keys.has("duration") && !keys.has("dampingRatio")) { + return keyframes; + } else if (keys.has("dampingRatio") || keys.has("stiffness") || keys.has("mass") || keys.has("damping") || keys.has("restSpeed") || keys.has("restDelta")) { + return spring; + } + return keyframes; +} +function loopElapsed(elapsed, duration, delay = 0) { + return elapsed - duration - delay; +} +function reverseElapsed(elapsed, duration, delay = 0, isForwardPlayback = true) { + return isForwardPlayback ? loopElapsed(duration + -elapsed, duration, delay) : duration - (elapsed - duration) + delay; +} +function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) { + return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay; +} +const framesync = update => { + const passTimestamp = ({ + delta + }) => update(delta); + return { + start: () => sync__default["default"].update(passTimestamp, true), + stop: () => sync.cancelSync.update(passTimestamp) + }; +}; +function animate(_a) { + var _b, _c; + var { + from, + autoplay = true, + driver = framesync, + elapsed = 0, + repeat: repeatMax = 0, + repeatType = "loop", + repeatDelay = 0, + onPlay, + onStop, + onComplete, + onRepeat, + onUpdate + } = _a, + options = tslib.__rest(_a, ["from", "autoplay", "driver", "elapsed", "repeat", "repeatType", "repeatDelay", "onPlay", "onStop", "onComplete", "onRepeat", "onUpdate"]); + let { + to + } = options; + let driverControls; + let repeatCount = 0; + let computedDuration = options.duration; + let latest; + let isComplete = false; + let isForwardPlayback = true; + let interpolateFromNumber; + const animator = detectAnimationFromOptions(options); + if ((_c = (_b = animator).needsInterpolation) === null || _c === void 0 ? void 0 : _c.call(_b, from, to)) { + interpolateFromNumber = interpolate([0, 100], [from, to], { + clamp: false + }); + from = 0; + to = 100; + } + const animation = animator(Object.assign(Object.assign({}, options), { + from, + to + })); + function repeat() { + repeatCount++; + if (repeatType === "reverse") { + isForwardPlayback = repeatCount % 2 === 0; + elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback); + } else { + elapsed = loopElapsed(elapsed, computedDuration, repeatDelay); + if (repeatType === "mirror") animation.flipTarget(); + } + isComplete = false; + onRepeat && onRepeat(); + } + function complete() { + driverControls.stop(); + onComplete && onComplete(); + } + function update(delta) { + if (!isForwardPlayback) delta = -delta; + elapsed += delta; + if (!isComplete) { + const state = animation.next(Math.max(0, elapsed)); + latest = state.value; + if (interpolateFromNumber) latest = interpolateFromNumber(latest); + isComplete = isForwardPlayback ? state.done : elapsed <= 0; + } + onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(latest); + if (isComplete) { + if (repeatCount === 0) computedDuration !== null && computedDuration !== void 0 ? computedDuration : computedDuration = elapsed; + if (repeatCount < repeatMax) { + hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat(); + } else { + complete(); + } } - })); - Object.defineProperty(exports, "visitInParallel", ({ - enumerable: true, - get: function () { - return _visitor.visitInParallel; + } + function play() { + onPlay === null || onPlay === void 0 ? void 0 : onPlay(); + driverControls = driver(update); + driverControls.start(); + } + autoplay && play(); + return { + stop: () => { + onStop === null || onStop === void 0 ? void 0 : onStop(); + driverControls.stop(); } - })); - var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); - var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); - var _printLocation = __webpack_require__(/*! ./printLocation.mjs */ "../../../node_modules/graphql/language/printLocation.mjs"); - var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); - var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); - var _parser = __webpack_require__(/*! ./parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); - var _printer = __webpack_require__(/*! ./printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); - var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _predicates = __webpack_require__(/*! ./predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); - var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/language/kinds.mjs": - /*!********************************************************!*\ - !*** ../../../node_modules/graphql/language/kinds.mjs ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.Kind = void 0; - /** - * The set of allowed kind values for AST nodes. - */ - var Kind; - (function (Kind) { - Kind['NAME'] = 'Name'; - Kind['DOCUMENT'] = 'Document'; - Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; - Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; - Kind['SELECTION_SET'] = 'SelectionSet'; - Kind['FIELD'] = 'Field'; - Kind['ARGUMENT'] = 'Argument'; - Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; - Kind['INLINE_FRAGMENT'] = 'InlineFragment'; - Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; - Kind['VARIABLE'] = 'Variable'; - Kind['INT'] = 'IntValue'; - Kind['FLOAT'] = 'FloatValue'; - Kind['STRING'] = 'StringValue'; - Kind['BOOLEAN'] = 'BooleanValue'; - Kind['NULL'] = 'NullValue'; - Kind['ENUM'] = 'EnumValue'; - Kind['LIST'] = 'ListValue'; - Kind['OBJECT'] = 'ObjectValue'; - Kind['OBJECT_FIELD'] = 'ObjectField'; - Kind['DIRECTIVE'] = 'Directive'; - Kind['NAMED_TYPE'] = 'NamedType'; - Kind['LIST_TYPE'] = 'ListType'; - Kind['NON_NULL_TYPE'] = 'NonNullType'; - Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; - Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; - Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; - Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; - Kind['FIELD_DEFINITION'] = 'FieldDefinition'; - Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; - Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; - Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; - Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; - Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; - Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; - Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; - Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; - Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; - Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; - Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; - Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; - Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; - Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; - })(Kind || (exports.Kind = Kind = {})); - - /** - * The enum type representing the possible kind values of AST nodes. - * - * @deprecated Please use `Kind`. Will be remove in v17. - */ - - /***/ }), - - /***/ "../../../node_modules/graphql/language/lexer.mjs": - /*!********************************************************!*\ - !*** ../../../node_modules/graphql/language/lexer.mjs ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.Lexer = void 0; - exports.isPunctuatorTokenKind = isPunctuatorTokenKind; - var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); - var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); - var _characterClasses = __webpack_require__(/*! ./characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); - var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); - /** - * Given a Source object, creates a Lexer for that source. - * A Lexer is a stateful stream generator in that every time - * it is advanced, it returns the next token in the Source. Assuming the - * source lexes, the final Token emitted by the lexer will be of kind - * EOF, after which the lexer will repeatedly return the same EOF token - * whenever called. - */ - - class Lexer { - /** - * The previously focused non-ignored token. - */ - - /** - * The currently focused non-ignored token. - */ - - /** - * The (1-indexed) line containing the current token. - */ - - /** - * The character offset at which the current line begins. - */ - constructor(source) { - const startOfFileToken = new _ast.Token(_tokenKind.TokenKind.SOF, 0, 0, 0, 0); - this.source = source; - this.lastToken = startOfFileToken; - this.token = startOfFileToken; - this.line = 1; - this.lineStart = 0; - } - get [Symbol.toStringTag]() { - return 'Lexer'; - } - /** - * Advances the token stream to the next non-ignored token. - */ - - advance() { - this.lastToken = this.token; - const token = this.token = this.lookahead(); - return token; - } - /** - * Looks ahead and returns the next non-ignored token, but does not change - * the state of Lexer. - */ - - lookahead() { - let token = this.token; - if (token.kind !== _tokenKind.TokenKind.EOF) { - do { - if (token.next) { - token = token.next; - } else { - // Read the next token and form a link in the token linked-list. - const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. - - token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. - - nextToken.prev = token; - token = nextToken; - } - } while (token.kind === _tokenKind.TokenKind.COMMENT); - } - return token; - } - } - /** - * @internal - */ - exports.Lexer = Lexer; - function isPunctuatorTokenKind(kind) { - return kind === _tokenKind.TokenKind.BANG || kind === _tokenKind.TokenKind.DOLLAR || kind === _tokenKind.TokenKind.AMP || kind === _tokenKind.TokenKind.PAREN_L || kind === _tokenKind.TokenKind.PAREN_R || kind === _tokenKind.TokenKind.SPREAD || kind === _tokenKind.TokenKind.COLON || kind === _tokenKind.TokenKind.EQUALS || kind === _tokenKind.TokenKind.AT || kind === _tokenKind.TokenKind.BRACKET_L || kind === _tokenKind.TokenKind.BRACKET_R || kind === _tokenKind.TokenKind.BRACE_L || kind === _tokenKind.TokenKind.PIPE || kind === _tokenKind.TokenKind.BRACE_R; - } - /** - * A Unicode scalar value is any Unicode code point except surrogate code - * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and - * 0xE000 to 0x10FFFF. - * - * SourceCharacter :: - * - "Any Unicode scalar value" - */ - - function isUnicodeScalarValue(code) { - return code >= 0x0000 && code <= 0xd7ff || code >= 0xe000 && code <= 0x10ffff; - } - /** - * The GraphQL specification defines source text as a sequence of unicode scalar - * values (which Unicode defines to exclude surrogate code points). However - * JavaScript defines strings as a sequence of UTF-16 code units which may - * include surrogates. A surrogate pair is a valid source character as it - * encodes a supplementary code point (above U+FFFF), but unpaired surrogate - * code points are not valid source characters. - */ - - function isSupplementaryCodePoint(body, location) { - return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1)); - } - function isLeadingSurrogate(code) { - return code >= 0xd800 && code <= 0xdbff; - } - function isTrailingSurrogate(code) { - return code >= 0xdc00 && code <= 0xdfff; - } - /** - * Prints the code point (or end of file reference) at a given location in a - * source for use in error messages. - * - * Printable ASCII is printed quoted, while other points are printed in Unicode - * code point form (ie. U+1234). - */ - - function printCodePointAt(lexer, location) { - const code = lexer.source.body.codePointAt(location); - if (code === undefined) { - return _tokenKind.TokenKind.EOF; - } else if (code >= 0x0020 && code <= 0x007e) { - // Printable ASCII - const char = String.fromCodePoint(code); - return char === '"' ? "'\"'" : `"${char}"`; - } // Unicode code point - - return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); + }; +} +function velocityPerSecond(velocity, frameDuration) { + return frameDuration ? velocity * (1000 / frameDuration) : 0; +} +function inertia({ + from = 0, + velocity = 0, + min, + max, + power = 0.8, + timeConstant = 750, + bounceStiffness = 500, + bounceDamping = 10, + restDelta = 1, + modifyTarget, + driver, + onUpdate, + onComplete, + onStop +}) { + let currentAnimation; + function isOutOfBounds(v) { + return min !== undefined && v < min || max !== undefined && v > max; + } + function boundaryNearest(v) { + if (min === undefined) return max; + if (max === undefined) return min; + return Math.abs(min - v) < Math.abs(max - v) ? min : max; + } + function startAnimation(options) { + currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop(); + currentAnimation = animate(Object.assign(Object.assign({}, options), { + driver, + onUpdate: v => { + var _a; + onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(v); + (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, v); + }, + onComplete, + onStop + })); } - /** - * Create a token with line and column location information. - */ - - function createToken(lexer, kind, start, end, value) { - const line = lexer.line; - const col = 1 + start - lexer.lineStart; - return new _ast.Token(kind, start, end, line, col, value); + function startSpring(options) { + startAnimation(Object.assign({ + type: "spring", + stiffness: bounceStiffness, + damping: bounceDamping, + restDelta + }, options)); } - /** - * Gets the next token from the source starting at the given position. - * - * This skips over whitespace until it finds the next lexable token, then lexes - * punctuators immediately or calls the appropriate helper function for more - * complicated tokens. - */ - - function readNextToken(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start; - while (position < bodyLength) { - const code = body.charCodeAt(position); // SourceCharacter - - switch (code) { - // Ignored :: - // - UnicodeBOM - // - WhiteSpace - // - LineTerminator - // - Comment - // - Comma - // - // UnicodeBOM :: "Byte Order Mark (U+FEFF)" - // - // WhiteSpace :: - // - "Horizontal Tab (U+0009)" - // - "Space (U+0020)" - // - // Comma :: , - case 0xfeff: // - - case 0x0009: // \t - - case 0x0020: // - - case 0x002c: - // , - ++position; - continue; - // LineTerminator :: - // - "New Line (U+000A)" - // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] - // - "Carriage Return (U+000D)" "New Line (U+000A)" - - case 0x000a: - // \n - ++position; - ++lexer.line; - lexer.lineStart = position; - continue; - case 0x000d: - // \r - if (body.charCodeAt(position + 1) === 0x000a) { - position += 2; - } else { - ++position; - } - ++lexer.line; - lexer.lineStart = position; - continue; - // Comment - - case 0x0023: - // # - return readComment(lexer, position); - // Token :: - // - Punctuator - // - Name - // - IntValue - // - FloatValue - // - StringValue - // - // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } - - case 0x0021: - // ! - return createToken(lexer, _tokenKind.TokenKind.BANG, position, position + 1); - case 0x0024: - // $ - return createToken(lexer, _tokenKind.TokenKind.DOLLAR, position, position + 1); - case 0x0026: - // & - return createToken(lexer, _tokenKind.TokenKind.AMP, position, position + 1); - case 0x0028: - // ( - return createToken(lexer, _tokenKind.TokenKind.PAREN_L, position, position + 1); - case 0x0029: - // ) - return createToken(lexer, _tokenKind.TokenKind.PAREN_R, position, position + 1); - case 0x002e: - // . - if (body.charCodeAt(position + 1) === 0x002e && body.charCodeAt(position + 2) === 0x002e) { - return createToken(lexer, _tokenKind.TokenKind.SPREAD, position, position + 3); - } - break; - case 0x003a: - // : - return createToken(lexer, _tokenKind.TokenKind.COLON, position, position + 1); - case 0x003d: - // = - return createToken(lexer, _tokenKind.TokenKind.EQUALS, position, position + 1); - case 0x0040: - // @ - return createToken(lexer, _tokenKind.TokenKind.AT, position, position + 1); - case 0x005b: - // [ - return createToken(lexer, _tokenKind.TokenKind.BRACKET_L, position, position + 1); - case 0x005d: - // ] - return createToken(lexer, _tokenKind.TokenKind.BRACKET_R, position, position + 1); - case 0x007b: - // { - return createToken(lexer, _tokenKind.TokenKind.BRACE_L, position, position + 1); - case 0x007c: - // | - return createToken(lexer, _tokenKind.TokenKind.PIPE, position, position + 1); - case 0x007d: - // } - return createToken(lexer, _tokenKind.TokenKind.BRACE_R, position, position + 1); - // StringValue - - case 0x0022: - // " - if (body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { - return readBlockString(lexer, position); - } - return readString(lexer, position); - } // IntValue | FloatValue (Digit | -) - - if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { - return readNumber(lexer, position, code); - } // Name - - if ((0, _characterClasses.isNameStart)(code)) { - return readName(lexer, position); + if (isOutOfBounds(from)) { + startSpring({ + from, + velocity, + to: boundaryNearest(from) + }); + } else { + let target = power * velocity + from; + if (typeof modifyTarget !== "undefined") target = modifyTarget(target); + const boundary = boundaryNearest(target); + const heading = boundary === min ? -1 : 1; + let prev; + let current; + const checkBoundary = v => { + prev = current; + current = v; + velocity = velocityPerSecond(v - prev, sync.getFrameData().delta); + if (heading === 1 && v > boundary || heading === -1 && v < boundary) { + startSpring({ + from: v, + to: boundary, + velocity + }); } - throw (0, _syntaxError.syntaxError)(lexer.source, position, code === 0x0027 ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`); + }; + startAnimation({ + type: "decay", + from, + velocity, + timeConstant, + power, + restDelta, + modifyTarget, + onUpdate: isOutOfBounds(target) ? checkBoundary : undefined + }); + } + return { + stop: () => currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop() + }; +} +const radiansToDegrees = radians => radians * 180 / Math.PI; +const angle = (a, b = zeroPoint) => radiansToDegrees(Math.atan2(b.y - a.y, b.x - a.x)); +const applyOffset = (from, to) => { + let hasReceivedFrom = true; + if (to === undefined) { + to = from; + hasReceivedFrom = false; + } + return v => { + if (hasReceivedFrom) { + return v - from + to; + } else { + from = v; + hasReceivedFrom = true; + return to; } - return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); + }; +}; +const identity = v => v; +const createAttractor = (alterDisplacement = identity) => (constant, origin, v) => { + const displacement = origin - v; + const springModifiedDisplacement = -(0 - constant + 1) * (0 - alterDisplacement(Math.abs(displacement))); + return displacement <= 0 ? origin + springModifiedDisplacement : origin - springModifiedDisplacement; +}; +const attract = createAttractor(); +const attractExpo = createAttractor(Math.sqrt); +const degreesToRadians = degrees => degrees * Math.PI / 180; +const isPoint = point => point.hasOwnProperty('x') && point.hasOwnProperty('y'); +const isPoint3D = point => isPoint(point) && point.hasOwnProperty('z'); +const distance1D = (a, b) => Math.abs(a - b); +function distance(a, b) { + if (isNum(a) && isNum(b)) { + return distance1D(a, b); + } else if (isPoint(a) && isPoint(b)) { + const xDelta = distance1D(a.x, b.x); + const yDelta = distance1D(a.y, b.y); + const zDelta = isPoint3D(a) && isPoint3D(b) ? distance1D(a.z, b.z) : 0; + return Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2)); + } +} +const pointFromVector = (origin, angle, distance) => { + angle = degreesToRadians(angle); + return { + x: distance * Math.cos(angle) + origin.x, + y: distance * Math.sin(angle) + origin.y + }; +}; +const toDecimal = (num, precision = 2) => { + precision = Math.pow(10, precision); + return Math.round(num * precision) / precision; +}; +const smoothFrame = (prevValue, nextValue, duration, smoothing = 0) => toDecimal(prevValue + duration * (nextValue - prevValue) / Math.max(smoothing, duration)); +const smooth = (strength = 50) => { + let previousValue = 0; + let lastUpdated = 0; + return v => { + const currentFramestamp = sync.getFrameData().timestamp; + const timeDelta = currentFramestamp !== lastUpdated ? currentFramestamp - lastUpdated : 0; + const newValue = timeDelta ? smoothFrame(previousValue, v, timeDelta, strength) : previousValue; + lastUpdated = currentFramestamp; + previousValue = newValue; + return newValue; + }; +}; +const snap = points => { + if (typeof points === 'number') { + return v => Math.round(v / points) * points; + } else { + let i = 0; + const numPoints = points.length; + return v => { + let lastDistance = Math.abs(points[0] - v); + for (i = 1; i < numPoints; i++) { + const point = points[i]; + const distance = Math.abs(point - v); + if (distance === 0) return point; + if (distance > lastDistance) return points[i - 1]; + if (i === numPoints - 1) return point; + lastDistance = distance; + } + }; } - /** - * Reads a comment token from the source file. - * - * ``` - * Comment :: # CommentChar* [lookahead != CommentChar] - * - * CommentChar :: SourceCharacter but not LineTerminator - * ``` - */ - - function readComment(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - while (position < bodyLength) { - const code = body.charCodeAt(position); // LineTerminator (\n | \r) - - if (code === 0x000a || code === 0x000d) { - break; - } // SourceCharacter - - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; +}; +function velocityPerFrame(xps, frameDuration) { + return xps / (1000 / frameDuration); +} +const wrap = (min, max, v) => { + const rangeSize = max - min; + return ((v - min) % rangeSize + rangeSize) % rangeSize + min; +}; +const a = (a1, a2) => 1.0 - 3.0 * a2 + 3.0 * a1; +const b = (a1, a2) => 3.0 * a2 - 6.0 * a1; +const c = a1 => 3.0 * a1; +const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; +const getSlope = (t, a1, a2) => 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1); +const subdivisionPrecision = 0.0000001; +const subdivisionMaxIterations = 10; +function binarySubdivide(aX, aA, aB, mX1, mX2) { + let currentX; + let currentT; + let i = 0; + do { + currentT = aA + (aB - aA) / 2.0; + currentX = calcBezier(currentT, mX1, mX2) - aX; + if (currentX > 0.0) { + aB = currentT; + } else { + aA = currentT; + } + } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); + return currentT; +} +const newtonIterations = 8; +const newtonMinSlope = 0.001; +function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { + for (let i = 0; i < newtonIterations; ++i) { + const currentSlope = getSlope(aGuessT, mX1, mX2); + if (currentSlope === 0.0) { + return aGuessT; + } + const currentX = calcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; + } + return aGuessT; +} +const kSplineTableSize = 11; +const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); +function cubicBezier(mX1, mY1, mX2, mY2) { + if (mX1 === mY1 && mX2 === mY2) return linear; + const sampleValues = new Float32Array(kSplineTableSize); + for (let i = 0; i < kSplineTableSize; ++i) { + sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); + } + function getTForX(aX) { + let intervalStart = 0.0; + let currentSample = 1; + const lastSample = kSplineTableSize - 1; + for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) { + intervalStart += kSampleStepSize; + } + --currentSample; + const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); + const guessForT = intervalStart + dist * kSampleStepSize; + const initialSlope = getSlope(guessForT, mX1, mX2); + if (initialSlope >= newtonMinSlope) { + return newtonRaphsonIterate(aX, guessForT, mX1, mX2); + } else if (initialSlope === 0.0) { + return guessForT; + } else { + return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); + } + } + return t => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); +} +const steps = (steps, direction = 'end') => progress => { + progress = direction === 'end' ? Math.min(progress, 0.999) : Math.max(progress, 0.001); + const expanded = progress * steps; + const rounded = direction === 'end' ? Math.floor(expanded) : Math.ceil(expanded); + return clamp(0, 1, rounded / steps); +}; +exports.angle = angle; +exports.animate = animate; +exports.anticipate = anticipate; +exports.applyOffset = applyOffset; +exports.attract = attract; +exports.attractExpo = attractExpo; +exports.backIn = backIn; +exports.backInOut = backInOut; +exports.backOut = backOut; +exports.bounceIn = bounceIn; +exports.bounceInOut = bounceInOut; +exports.bounceOut = bounceOut; +exports.circIn = circIn; +exports.circInOut = circInOut; +exports.circOut = circOut; +exports.clamp = clamp; +exports.createAnticipate = createAnticipate; +exports.createAttractor = createAttractor; +exports.createBackIn = createBackIn; +exports.createExpoIn = createExpoIn; +exports.cubicBezier = cubicBezier; +exports.decay = decay; +exports.degreesToRadians = degreesToRadians; +exports.distance = distance; +exports.easeIn = easeIn; +exports.easeInOut = easeInOut; +exports.easeOut = easeOut; +exports.inertia = inertia; +exports.interpolate = interpolate; +exports.isPoint = isPoint; +exports.isPoint3D = isPoint3D; +exports.keyframes = keyframes; +exports.linear = linear; +exports.mirrorEasing = mirrorEasing; +exports.mix = mix; +exports.mixColor = mixColor; +exports.mixComplex = mixComplex; +exports.pipe = pipe; +exports.pointFromVector = pointFromVector; +exports.progress = progress; +exports.radiansToDegrees = radiansToDegrees; +exports.reverseEasing = reverseEasing; +exports.smooth = smooth; +exports.smoothFrame = smoothFrame; +exports.snap = snap; +exports.spring = spring; +exports.steps = steps; +exports.toDecimal = toDecimal; +exports.velocityPerFrame = velocityPerFrame; +exports.velocityPerSecond = velocityPerSecond; +exports.wrap = wrap; + +/***/ }), + +/***/ "../../../node_modules/punycode.js/punycode.es6.js": +/*!*********************************************************!*\ + !*** ../../../node_modules/punycode.js/punycode.es6.js ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +/** Highest positive signed 32-bit float value */ +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.toUnicode = exports.toASCII = exports.encode = exports["default"] = exports.decode = void 0; +exports.ucs2decode = ucs2decode; +exports.ucs2encode = void 0; +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { - break; + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; } + } else { + output.push(value); } - return createToken(lexer, _tokenKind.TokenKind.COMMENT, start, position, body.slice(start + 1, position)); } - /** - * Reads a number token from the source file, either a FloatValue or an IntValue - * depending on whether a FractionalPart or ExponentPart is encountered. - * - * ``` - * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] - * - * IntegerPart :: - * - NegativeSign? 0 - * - NegativeSign? NonZeroDigit Digit* - * - * NegativeSign :: - - * - * NonZeroDigit :: Digit but not `0` - * - * FloatValue :: - * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] - * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] - * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] - * - * FractionalPart :: . Digit+ - * - * ExponentPart :: ExponentIndicator Sign? Digit+ - * - * ExponentIndicator :: one of `e` `E` - * - * Sign :: one of + - - * ``` - */ - - function readNumber(lexer, start, firstCode) { - const body = lexer.source.body; - let position = start; - let code = firstCode; - let isFloat = false; // NegativeSign (-) - - if (code === 0x002d) { - code = body.charCodeAt(++position); - } // Zero (0) - - if (code === 0x0030) { - code = body.charCodeAt(++position); - if ((0, _characterClasses.isDigit)(code)) { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, unexpected digit after 0: ${printCodePointAt(lexer, position)}.`); + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +exports.ucs2encode = ucs2encode; +const basicToDigit = function (codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function (digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function (delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for /* no initialization */ + (; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function (input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for /* no final expression */ + (let index = basic > 0 ? basic + 1 : 0; index < inputLength;) { + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for /* no condition */ + (let w = 1, k = base;; k += base) { + if (index >= inputLength) { + error('invalid-input'); + } + const digit = basicToDigit(input.charCodeAt(index++)); + if (digit >= base) { + error('invalid-input'); + } + if (digit > floor((maxInt - i) / w)) { + error('overflow'); } - } else { - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // Full stop (.) - - if (code === 0x002e) { - isFloat = true; - code = body.charCodeAt(++position); - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // E e - - if (code === 0x0045 || code === 0x0065) { - isFloat = true; - code = body.charCodeAt(++position); // + - - - if (code === 0x002b || code === 0x002d) { - code = body.charCodeAt(++position); + i += digit * w; + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (digit < t) { + break; } - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // Numbers cannot be followed by . or NameStart - - if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid number, expected digit but got: ${printCodePointAt(lexer, position)}.`); + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + w *= baseMinusT; } - return createToken(lexer, isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, start, position, body.slice(start, position)); - } - /** - * Returns the new position in the source after reading one or more digits. - */ - - function readDigits(lexer, start, firstCode) { - if (!(0, _characterClasses.isDigit)(firstCode)) { - throw (0, _syntaxError.syntaxError)(lexer.source, start, `Invalid number, expected digit but got: ${printCodePointAt(lexer, start)}.`); + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); } - const body = lexer.source.body; - let position = start + 1; // +1 to skip first firstCode - - while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { - ++position; + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +exports.decode = decode; +const encode = function (input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); } - return position; } - /** - * Reads a single-quote string token from the source file. - * - * ``` - * StringValue :: - * - `""` [lookahead != `"`] - * - `"` StringCharacter+ `"` - * - * StringCharacter :: - * - SourceCharacter but not `"` or `\` or LineTerminator - * - `\u` EscapedUnicode - * - `\` EscapedCharacter - * - * EscapedUnicode :: - * - `{` HexDigit+ `}` - * - HexDigit HexDigit HexDigit HexDigit - * - * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` - * ``` - */ - - function readString(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - let chunkStart = position; - let value = ''; - while (position < bodyLength) { - const code = body.charCodeAt(position); // Closing Quote (") - - if (code === 0x0022) { - value += body.slice(chunkStart, position); - return createToken(lexer, _tokenKind.TokenKind.STRING, start, position + 1, value); - } // Escape Sequence (\) - - if (code === 0x005c) { - value += body.slice(chunkStart, position); - const escape = body.charCodeAt(position + 1) === 0x0075 // u - ? body.charCodeAt(position + 2) === 0x007b // { - ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position); - value += escape.value; - position += escape.size; - chunkStart = position; - continue; - } // LineTerminator (\n | \r) - - if (code === 0x000a || code === 0x000d) { - break; - } // SourceCharacter - - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; } } - throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); - } // The string value and lexed size of an escape sequence. - - function readEscapedUnicodeVariableWidth(lexer, position) { - const body = lexer.source.body; - let point = 0; - let size = 3; // Cannot be larger than 12 chars (\u{00000000}). - - while (size < 12) { - const code = body.charCodeAt(position + size++); // Closing Brace (}) - - if (code === 0x007d) { - // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. - if (size < 5 || !isUnicodeScalarValue(point)) { - break; - } - return { - value: String.fromCodePoint(point), - size - }; - } // Append this hex digit to the code point. - - point = point << 4 | readHexDigit(code); - if (point < 0) { - break; + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); } - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + size)}".`); - } - function readEscapedUnicodeFixedWidth(lexer, position) { - const body = lexer.source.body; - const code = read16BitHexCode(body, position + 2); - if (isUnicodeScalarValue(code)) { - return { - value: String.fromCodePoint(code), - size: 6 - }; - } // GraphQL allows JSON-style surrogate pair escape sequences, but only when - // a valid pair is formed. - - if (isLeadingSurrogate(code)) { - // \u - if (body.charCodeAt(position + 6) === 0x005c && body.charCodeAt(position + 7) === 0x0075) { - const trailingCode = read16BitHexCode(body, position + 8); - if (isTrailingSurrogate(trailingCode)) { - // JavaScript defines strings as a sequence of UTF-16 code units and - // encodes Unicode code points above U+FFFF using a surrogate pair of - // code units. Since this is a surrogate pair escape sequence, just - // include both codes into the JavaScript string value. Had JavaScript - // not been internally based on UTF-16, then this surrogate pair would - // be decoded to retrieve the supplementary code point. - return { - value: String.fromCodePoint(code, trailingCode), - size: 12 - }; + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for /* no condition */ + (let k = base;; k += base) { + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); } + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; } } - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`); - } - /** - * Reads four hexadecimal characters and returns the positive integer that 16bit - * hexadecimal string represents. For example, "000f" will return 15, and "dead" - * will return 57005. - * - * Returns a negative number if any char was not a valid hexadecimal digit. - */ - - function read16BitHexCode(body, position) { - // readHexDigit() returns -1 on error. ORing a negative value with any other - // value always produces a negative value. - return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3)); - } - /** - * Reads a hexadecimal character and returns its positive integer value (0-15). - * - * '0' becomes 0, '9' becomes 9 - * 'A' becomes 10, 'F' becomes 15 - * 'a' becomes 10, 'f' becomes 15 - * - * Returns -1 if the provided character code was not a valid hexadecimal digit. - * - * HexDigit :: one of - * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` - * - `A` `B` `C` `D` `E` `F` - * - `a` `b` `c` `d` `e` `f` - */ - - function readHexDigit(code) { - return code >= 0x0030 && code <= 0x0039 // 0-9 - ? code - 0x0030 : code >= 0x0041 && code <= 0x0046 // A-F - ? code - 0x0037 : code >= 0x0061 && code <= 0x0066 // a-f - ? code - 0x0057 : -1; + ++delta; + ++n; } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +exports.encode = encode; +const toUnicode = function (input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +exports.toUnicode = toUnicode; +const toASCII = function (input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +exports.toASCII = toASCII; +const punycode = { /** - * | Escaped Character | Code Point | Character Name | - * | ----------------- | ---------- | ---------------------------- | - * | `"` | U+0022 | double quote | - * | `\` | U+005C | reverse solidus (back slash) | - * | `/` | U+002F | solidus (forward slash) | - * | `b` | U+0008 | backspace | - * | `f` | U+000C | form feed | - * | `n` | U+000A | line feed (new line) | - * | `r` | U+000D | carriage return | - * | `t` | U+0009 | horizontal tab | + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String */ - - function readEscapedCharacter(lexer, position) { - const body = lexer.source.body; - const code = body.charCodeAt(position + 1); - switch (code) { - case 0x0022: - // " - return { - value: '\u0022', - size: 2 - }; - case 0x005c: - // \ - return { - value: '\u005c', - size: 2 - }; - case 0x002f: - // / - return { - value: '\u002f', - size: 2 - }; - case 0x0062: - // b - return { - value: '\u0008', - size: 2 - }; - case 0x0066: - // f - return { - value: '\u000c', - size: 2 - }; - case 0x006e: - // n - return { - value: '\u000a', - size: 2 - }; - case 0x0072: - // r - return { - value: '\u000d', - size: 2 - }; - case 0x0074: - // t - return { - value: '\u0009', - size: 2 - }; - } - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character escape sequence: "${body.slice(position, position + 2)}".`); - } + 'version': '2.3.1', /** - * Reads a block string token from the source file. - * - * ``` - * StringValue :: - * - `"""` BlockStringCharacter* `"""` - * - * BlockStringCharacter :: - * - SourceCharacter but not `"""` or `\"""` - * - `\"""` - * ``` - */ - - function readBlockString(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let lineStart = lexer.lineStart; - let position = start + 3; - let chunkStart = position; - let currentLine = ''; - const blockLines = []; - while (position < bodyLength) { - const code = body.charCodeAt(position); // Closing Triple-Quote (""") - - if (code === 0x0022 && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022) { - currentLine += body.slice(chunkStart, position); - blockLines.push(currentLine); - const token = createToken(lexer, _tokenKind.TokenKind.BLOCK_STRING, start, position + 3, - // Return a string of the lines joined with U+000A. - (0, _blockString.dedentBlockStringLines)(blockLines).join('\n')); - lexer.line += blockLines.length - 1; - lexer.lineStart = lineStart; - return token; - } // Escaped Triple-Quote (\""") - - if (code === 0x005c && body.charCodeAt(position + 1) === 0x0022 && body.charCodeAt(position + 2) === 0x0022 && body.charCodeAt(position + 3) === 0x0022) { - currentLine += body.slice(chunkStart, position); - chunkStart = position + 1; // skip only slash - - position += 4; - continue; - } // LineTerminator - - if (code === 0x000a || code === 0x000d) { - currentLine += body.slice(chunkStart, position); - blockLines.push(currentLine); - if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { - position += 2; - } else { - ++position; - } - currentLine = ''; - chunkStart = position; - lineStart = position; - continue; - } // SourceCharacter - - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - throw (0, _syntaxError.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); - } + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; +var _default = exports["default"] = punycode; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js": +/*!******************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js ***! + \******************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.RemoveScrollBar = void 0; +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); +var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); +var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var Style = (0, _reactStyleSingleton.styleSingleton)(); +// important tip - once we measure scrollBar width and remove them +// we could not repeat this operation +// thus we are using style-singleton - only the first "yet correct" style will be applied. +var getStyles = function (_a, allowRelative, gapMode, important) { + var left = _a.left, + top = _a.top, + right = _a.right, + gap = _a.gap; + if (gapMode === void 0) { + gapMode = 'margin'; + } + return "\n .".concat(_constants.noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([allowRelative && "position: relative ".concat(important, ";"), gapMode === 'margin' && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), gapMode === 'padding' && "padding-right: ".concat(gap, "px ").concat(important, ";")].filter(Boolean).join(''), "\n }\n \n .").concat(_constants.zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.zeroRightClassName, " .").concat(_constants.zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " .").concat(_constants.fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body {\n ").concat(_constants.removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); +}; +/** + * Removes page scrollbar and blocks page scroll when mounted + */ +var RemoveScrollBar = function (props) { + var noRelative = props.noRelative, + noImportant = props.noImportant, + _a = props.gapMode, + gapMode = _a === void 0 ? 'margin' : _a; + var gap = React.useMemo(function () { + return (0, _utils.getGapWidth)(gapMode); + }, [gapMode]); + return /*#__PURE__*/React.createElement(Style, { + styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') + }); +}; +exports.RemoveScrollBar = RemoveScrollBar; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js": +/*!******************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js ***! + \******************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.zeroRightClassName = exports.removedBarSizeVariable = exports.noScrollbarsClassName = exports.fullWidthClassName = void 0; +var zeroRightClassName = exports.zeroRightClassName = 'right-scroll-bar-position'; +var fullWidthClassName = exports.fullWidthClassName = 'width-before-scroll-bar'; +var noScrollbarsClassName = exports.noScrollbarsClassName = 'with-scroll-bars-hidden'; +/** + * Name of a CSS variable containing the amount of "hidden" scrollbar + * ! might be undefined ! use will fallback! + */ +var removedBarSizeVariable = exports.removedBarSizeVariable = '--removed-body-scroll-bar-size'; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js": +/*!**************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js ***! + \**************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "RemoveScrollBar", ({ + enumerable: true, + get: function () { + return _component.RemoveScrollBar; + } +})); +Object.defineProperty(exports, "fullWidthClassName", ({ + enumerable: true, + get: function () { + return _constants.fullWidthClassName; + } +})); +Object.defineProperty(exports, "getGapWidth", ({ + enumerable: true, + get: function () { + return _utils.getGapWidth; + } +})); +Object.defineProperty(exports, "noScrollbarsClassName", ({ + enumerable: true, + get: function () { + return _constants.noScrollbarsClassName; + } +})); +Object.defineProperty(exports, "removedBarSizeVariable", ({ + enumerable: true, + get: function () { + return _constants.removedBarSizeVariable; + } +})); +Object.defineProperty(exports, "zeroRightClassName", ({ + enumerable: true, + get: function () { + return _constants.zeroRightClassName; + } +})); +var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js"); +var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); +var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js": +/*!**************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js ***! + \**************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.zeroGap = exports.getGapWidth = void 0; +var zeroGap = exports.zeroGap = { + left: 0, + top: 0, + right: 0, + gap: 0 +}; +var parse = function (x) { + return parseInt(x || '', 10) || 0; +}; +var getOffset = function (gapMode) { + var cs = window.getComputedStyle(document.body); + if (true) { + if (cs.overflowY === 'hidden') { + console.error('react-remove-scroll-bar: cannot calculate scrollbar size because it is removed (overflow:hidden on body'); + } + } + var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft']; + var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop']; + var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight']; + return [parse(left), parse(top), parse(right)]; +}; +var getGapWidth = function (gapMode) { + if (gapMode === void 0) { + gapMode = 'margin'; + } + if (typeof window === 'undefined') { + return zeroGap; + } + var offsets = getOffset(gapMode); + var documentWidth = document.documentElement.clientWidth; + var windowWidth = window.innerWidth; + return { + left: offsets[0], + top: offsets[1], + right: offsets[2], + gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) + }; +}; +exports.getGapWidth = getGapWidth; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js": +/*!****************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/Combination.js ***! + \****************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _UI = __webpack_require__(/*! ./UI */ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js"); +var _sidecar = _interopRequireDefault(__webpack_require__(/*! ./sidecar */ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var ReactRemoveScroll = /*#__PURE__*/React.forwardRef(function (props, ref) { + return /*#__PURE__*/React.createElement(_UI.RemoveScroll, (0, _tslib.__assign)({}, props, { + ref: ref, + sideCar: _sidecar.default + })); +}); +ReactRemoveScroll.classNames = _UI.RemoveScroll.classNames; +var _default = exports["default"] = ReactRemoveScroll; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js": +/*!***************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js ***! + \***************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.RemoveScrollSideCar = RemoveScrollSideCar; +exports.getTouchXY = exports.getDeltaXY = void 0; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _reactRemoveScrollBar = __webpack_require__(/*! react-remove-scroll-bar */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js"); +var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); +var _aggresiveCapture = __webpack_require__(/*! ./aggresiveCapture */ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js"); +var _handleScroll = __webpack_require__(/*! ./handleScroll */ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var getTouchXY = function (event) { + return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; +}; +exports.getTouchXY = getTouchXY; +var getDeltaXY = function (event) { + return [event.deltaX, event.deltaY]; +}; +exports.getDeltaXY = getDeltaXY; +var extractRef = function (ref) { + return ref && 'current' in ref ? ref.current : ref; +}; +var deltaCompare = function (x, y) { + return x[0] === y[0] && x[1] === y[1]; +}; +var generateStyle = function (id) { + return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); +}; +var idCounter = 0; +var lockStack = []; +function RemoveScrollSideCar(props) { + var shouldPreventQueue = React.useRef([]); + var touchStartRef = React.useRef([0, 0]); + var activeAxis = React.useRef(); + var id = React.useState(idCounter++)[0]; + var Style = React.useState(function () { + return (0, _reactStyleSingleton.styleSingleton)(); + })[0]; + var lastProps = React.useRef(props); + React.useEffect(function () { + lastProps.current = props; + }, [props]); + React.useEffect(function () { + if (props.inert) { + document.body.classList.add("block-interactivity-".concat(id)); + var allow_1 = (0, _tslib.__spreadArray)([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); + allow_1.forEach(function (el) { + return el.classList.add("allow-interactivity-".concat(id)); + }); + return function () { + document.body.classList.remove("block-interactivity-".concat(id)); + allow_1.forEach(function (el) { + return el.classList.remove("allow-interactivity-".concat(id)); + }); + }; } - throw (0, _syntaxError.syntaxError)(lexer.source, position, 'Unterminated string.'); - } - /** - * Reads an alphanumeric + underscore name from the source. - * - * ``` - * Name :: - * - NameStart NameContinue* [lookahead != NameContinue] - * ``` - */ - - function readName(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - while (position < bodyLength) { - const code = body.charCodeAt(position); - if ((0, _characterClasses.isNameContinue)(code)) { - ++position; - } else { - break; - } + return; + }, [props.inert, props.lockRef.current, props.shards]); + var shouldCancelEvent = React.useCallback(function (event, parent) { + if ('touches' in event && event.touches.length === 2) { + return !lastProps.current.allowPinchZoom; + } + var touch = getTouchXY(event); + var touchStart = touchStartRef.current; + var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0]; + var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1]; + var currentAxis; + var target = event.target; + var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v'; + // allow horizontal touch move on Range inputs. They will not cause any scroll + if ('touches' in event && moveDirection === 'h' && target.type === 'range') { + return false; } - return createToken(lexer, _tokenKind.TokenKind.NAME, start, position, body.slice(start, position)); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/location.mjs": - /*!***********************************************************!*\ - !*** ../../../node_modules/graphql/language/location.mjs ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getLocation = getLocation; - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - const LineRegExp = /\r\n|[\n\r]/g; - /** - * Represents a location in a Source. - */ - - /** - * Takes a Source and a UTF-8 character offset, and returns the corresponding - * line and column as a SourceLocation. - */ - function getLocation(source, position) { - let lastLineStart = 0; - let line = 1; - for (const match of source.body.matchAll(LineRegExp)) { - typeof match.index === 'number' || (0, _invariant.invariant)(false); - if (match.index >= position) { - break; - } - lastLineStart = match.index + match[0].length; - line += 1; + var canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); + if (!canBeScrolledInMainDirection) { + return true; } - return { - line, - column: position + 1 - lastLineStart - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/parser.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/language/parser.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.Parser = void 0; - exports.parse = parse; - exports.parseConstValue = parseConstValue; - exports.parseType = parseType; - exports.parseValue = parseValue; - var _syntaxError = __webpack_require__(/*! ../error/syntaxError.mjs */ "../../../node_modules/graphql/error/syntaxError.mjs"); - var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _directiveLocation = __webpack_require__(/*! ./directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); - var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _lexer = __webpack_require__(/*! ./lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); - var _source = __webpack_require__(/*! ./source.mjs */ "../../../node_modules/graphql/language/source.mjs"); - var _tokenKind = __webpack_require__(/*! ./tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); - /** - * Configuration options to control parser behavior - */ - - /** - * Given a GraphQL source, parses it into a Document. - * Throws GraphQLError if a syntax error is encountered. - */ - function parse(source, options) { - const parser = new Parser(source, options); - return parser.parseDocument(); - } - /** - * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for - * that value. - * Throws GraphQLError if a syntax error is encountered. - * - * This is useful within tools that operate upon GraphQL Values directly and - * in isolation of complete GraphQL documents. - * - * Consider providing the results to the utility function: valueFromAST(). - */ - - function parseValue(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const value = parser.parseValueLiteral(false); - parser.expectToken(_tokenKind.TokenKind.EOF); - return value; - } - /** - * Similar to parseValue(), but raises a parse error if it encounters a - * variable. The return type will be a constant value. - */ - - function parseConstValue(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const value = parser.parseConstValueLiteral(); - parser.expectToken(_tokenKind.TokenKind.EOF); - return value; - } - /** - * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for - * that type. - * Throws GraphQLError if a syntax error is encountered. - * - * This is useful within tools that operate upon GraphQL Types directly and - * in isolation of complete GraphQL documents. - * - * Consider providing the results to the utility function: typeFromAST(). - */ - - function parseType(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const type = parser.parseTypeReference(); - parser.expectToken(_tokenKind.TokenKind.EOF); - return type; - } - /** - * This class is exported only to assist people in implementing their own parsers - * without duplicating too much code and should be used only as last resort for cases - * such as experimental syntax or if certain features could not be contributed upstream. - * - * It is still part of the internal API and is versioned, so any changes to it are never - * considered breaking changes. If you still need to support multiple versions of the - * library, please use the `versionInfo` variable for version detection. - * - * @internal - */ - - class Parser { - constructor(source, options = {}) { - const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); - this._lexer = new _lexer.Lexer(sourceObj); - this._options = options; - this._tokenCounter = 0; + if (canBeScrolledInMainDirection) { + currentAxis = moveDirection; + } else { + currentAxis = moveDirection === 'v' ? 'h' : 'v'; + canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); + // other axis might be not scrollable } - /** - * Converts a name lex token into a name parse node. - */ - - parseName() { - const token = this.expectToken(_tokenKind.TokenKind.NAME); - return this.node(token, { - kind: _kinds.Kind.NAME, - value: token.value - }); - } // Implements the parsing rules in the Document section. - - /** - * Document : Definition+ - */ - - parseDocument() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.DOCUMENT, - definitions: this.many(_tokenKind.TokenKind.SOF, this.parseDefinition, _tokenKind.TokenKind.EOF) - }); + if (!canBeScrolledInMainDirection) { + return false; } - /** - * Definition : - * - ExecutableDefinition - * - TypeSystemDefinition - * - TypeSystemExtension - * - * ExecutableDefinition : - * - OperationDefinition - * - FragmentDefinition - * - * TypeSystemDefinition : - * - SchemaDefinition - * - TypeDefinition - * - DirectiveDefinition - * - * TypeDefinition : - * - ScalarTypeDefinition - * - ObjectTypeDefinition - * - InterfaceTypeDefinition - * - UnionTypeDefinition - * - EnumTypeDefinition - * - InputObjectTypeDefinition - */ - - parseDefinition() { - if (this.peek(_tokenKind.TokenKind.BRACE_L)) { - return this.parseOperationDefinition(); - } // Many definitions begin with a description and require a lookahead. - - const hasDescription = this.peekDescription(); - const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token; - if (keywordToken.kind === _tokenKind.TokenKind.NAME) { - switch (keywordToken.value) { - case 'schema': - return this.parseSchemaDefinition(); - case 'scalar': - return this.parseScalarTypeDefinition(); - case 'type': - return this.parseObjectTypeDefinition(); - case 'interface': - return this.parseInterfaceTypeDefinition(); - case 'union': - return this.parseUnionTypeDefinition(); - case 'enum': - return this.parseEnumTypeDefinition(); - case 'input': - return this.parseInputObjectTypeDefinition(); - case 'directive': - return this.parseDirectiveDefinition(); - } - if (hasDescription) { - throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, 'Unexpected description, descriptions are supported only on type definitions.'); - } - switch (keywordToken.value) { - case 'query': - case 'mutation': - case 'subscription': - return this.parseOperationDefinition(); - case 'fragment': - return this.parseFragmentDefinition(); - case 'extend': - return this.parseTypeSystemExtension(); - } - } - throw this.unexpected(keywordToken); - } // Implements the parsing rules in the Operations section. - - /** - * OperationDefinition : - * - SelectionSet - * - OperationType Name? VariableDefinitions? Directives? SelectionSet - */ - - parseOperationDefinition() { - const start = this._lexer.token; - if (this.peek(_tokenKind.TokenKind.BRACE_L)) { - return this.node(start, { - kind: _kinds.Kind.OPERATION_DEFINITION, - operation: _ast.OperationTypeNode.QUERY, - name: undefined, - variableDefinitions: [], - directives: [], - selectionSet: this.parseSelectionSet() - }); - } - const operation = this.parseOperationType(); - let name; - if (this.peek(_tokenKind.TokenKind.NAME)) { - name = this.parseName(); - } - return this.node(start, { - kind: _kinds.Kind.OPERATION_DEFINITION, - operation, - name, - variableDefinitions: this.parseVariableDefinitions(), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); + if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) { + activeAxis.current = currentAxis; } - /** - * OperationType : one of query mutation subscription - */ - - parseOperationType() { - const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); - switch (operationToken.value) { - case 'query': - return _ast.OperationTypeNode.QUERY; - case 'mutation': - return _ast.OperationTypeNode.MUTATION; - case 'subscription': - return _ast.OperationTypeNode.SUBSCRIPTION; - } - throw this.unexpected(operationToken); + if (!currentAxis) { + return true; } - /** - * VariableDefinitions : ( VariableDefinition+ ) - */ - - parseVariableDefinitions() { - return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseVariableDefinition, _tokenKind.TokenKind.PAREN_R); + var cancelingAxis = activeAxis.current || currentAxis; + return (0, _handleScroll.handleScroll)(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true); + }, []); + var shouldPrevent = React.useCallback(function (_event) { + var event = _event; + if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) { + // not the last active + return; } - /** - * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? - */ - - parseVariableDefinition() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.VARIABLE_DEFINITION, - variable: this.parseVariable(), - type: (this.expectToken(_tokenKind.TokenKind.COLON), this.parseTypeReference()), - defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.parseConstValueLiteral() : undefined, - directives: this.parseConstDirectives() - }); + var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event); + var sourceEvent = shouldPreventQueue.current.filter(function (e) { + return e.name === event.type && e.target === event.target && deltaCompare(e.delta, delta); + })[0]; + // self event, and should be canceled + if (sourceEvent && sourceEvent.should) { + if (event.cancelable) { + event.preventDefault(); + } + return; } - /** - * Variable : $ Name - */ - - parseVariable() { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.DOLLAR); - return this.node(start, { - kind: _kinds.Kind.VARIABLE, - name: this.parseName() + // outside or shard event + if (!sourceEvent) { + var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function (node) { + return node.contains(event.target); }); + var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; + if (shouldStop) { + if (event.cancelable) { + event.preventDefault(); + } + } } - /** - * ``` - * SelectionSet : { Selection+ } - * ``` - */ - - parseSelectionSet() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.SELECTION_SET, - selections: this.many(_tokenKind.TokenKind.BRACE_L, this.parseSelection, _tokenKind.TokenKind.BRACE_R) + }, []); + var shouldCancel = React.useCallback(function (name, delta, target, should) { + var event = { + name: name, + delta: delta, + target: target, + should: should + }; + shouldPreventQueue.current.push(event); + setTimeout(function () { + shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { + return e !== event; }); - } - /** - * Selection : - * - Field - * - FragmentSpread - * - InlineFragment - */ - - parseSelection() { - return this.peek(_tokenKind.TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); - } - /** - * Field : Alias? Name Arguments? Directives? SelectionSet? - * - * Alias : Name : - */ - - parseField() { - const start = this._lexer.token; - const nameOrAlias = this.parseName(); - let alias; - let name; - if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { - alias = nameOrAlias; - name = this.parseName(); - } else { - name = nameOrAlias; - } - return this.node(start, { - kind: _kinds.Kind.FIELD, - alias, - name, - arguments: this.parseArguments(false), - directives: this.parseDirectives(false), - selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined + }, 1); + }, []); + var scrollTouchStart = React.useCallback(function (event) { + touchStartRef.current = getTouchXY(event); + activeAxis.current = undefined; + }, []); + var scrollWheel = React.useCallback(function (event) { + shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); + }, []); + var scrollTouchMove = React.useCallback(function (event) { + shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); + }, []); + React.useEffect(function () { + lockStack.push(Style); + props.setCallbacks({ + onScrollCapture: scrollWheel, + onWheelCapture: scrollWheel, + onTouchMoveCapture: scrollTouchMove + }); + document.addEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); + document.addEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); + document.addEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); + return function () { + lockStack = lockStack.filter(function (inst) { + return inst !== Style; }); - } - /** - * Arguments[Const] : ( Argument[?Const]+ ) - */ - - parseArguments(isConst) { - const item = isConst ? this.parseConstArgument : this.parseArgument; - return this.optionalMany(_tokenKind.TokenKind.PAREN_L, item, _tokenKind.TokenKind.PAREN_R); - } - /** - * Argument[Const] : Name : Value[?Const] - */ - - parseArgument(isConst = false) { - const start = this._lexer.token; - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - return this.node(start, { - kind: _kinds.Kind.ARGUMENT, - name, - value: this.parseValueLiteral(isConst) - }); - } - parseConstArgument() { - return this.parseArgument(true); - } // Implements the parsing rules in the Fragments section. - - /** - * Corresponds to both FragmentSpread and InlineFragment in the spec. - * - * FragmentSpread : ... FragmentName Directives? - * - * InlineFragment : ... TypeCondition? Directives? SelectionSet - */ - - parseFragment() { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.SPREAD); - const hasTypeCondition = this.expectOptionalKeyword('on'); - if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_SPREAD, - name: this.parseFragmentName(), - directives: this.parseDirectives(false) - }); + document.removeEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); + document.removeEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); + document.removeEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); + }; + }, []); + var removeScrollBar = props.removeScrollBar, + inert = props.inert; + return /*#__PURE__*/React.createElement(React.Fragment, null, inert ? /*#__PURE__*/React.createElement(Style, { + styles: generateStyle(id) + }) : null, removeScrollBar ? /*#__PURE__*/React.createElement(_reactRemoveScrollBar.RemoveScrollBar, { + gapMode: "margin" + }) : null); +} + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js": +/*!*******************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/UI.js ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.RemoveScroll = void 0; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _constants = __webpack_require__(/*! react-remove-scroll-bar/constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); +var _useCallbackRef = __webpack_require__(/*! use-callback-ref */ "../../../node_modules/use-callback-ref/dist/es2015/index.js"); +var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var nothing = function () { + return; +}; +/** + * Removes scrollbar from the page and contain the scroll within the Lock + */ +var RemoveScroll = exports.RemoveScroll = /*#__PURE__*/React.forwardRef(function (props, parentRef) { + var ref = React.useRef(null); + var _a = React.useState({ + onScrollCapture: nothing, + onWheelCapture: nothing, + onTouchMoveCapture: nothing + }), + callbacks = _a[0], + setCallbacks = _a[1]; + var forwardProps = props.forwardProps, + children = props.children, + className = props.className, + removeScrollBar = props.removeScrollBar, + enabled = props.enabled, + shards = props.shards, + sideCar = props.sideCar, + noIsolation = props.noIsolation, + inert = props.inert, + allowPinchZoom = props.allowPinchZoom, + _b = props.as, + Container = _b === void 0 ? 'div' : _b, + rest = (0, _tslib.__rest)(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]); + var SideCar = sideCar; + var containerRef = (0, _useCallbackRef.useMergeRefs)([ref, parentRef]); + var containerProps = (0, _tslib.__assign)((0, _tslib.__assign)({}, rest), callbacks); + return /*#__PURE__*/React.createElement(React.Fragment, null, enabled && ( /*#__PURE__*/React.createElement(SideCar, { + sideCar: _medium.effectCar, + removeScrollBar: removeScrollBar, + shards: shards, + noIsolation: noIsolation, + inert: inert, + setCallbacks: setCallbacks, + allowPinchZoom: !!allowPinchZoom, + lockRef: ref + })), forwardProps ? ( /*#__PURE__*/React.cloneElement(React.Children.only(children), (0, _tslib.__assign)((0, _tslib.__assign)({}, containerProps), { + ref: containerRef + }))) : ( /*#__PURE__*/React.createElement(Container, (0, _tslib.__assign)({}, containerProps, { + className: className, + ref: containerRef + }), children))); +}); +RemoveScroll.defaultProps = { + enabled: true, + removeScrollBar: true, + inert: false +}; +RemoveScroll.classNames = { + fullWidth: _constants.fullWidthClassName, + zeroRight: _constants.zeroRightClassName +}; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js": +/*!*********************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js ***! + \*********************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.nonPassive = void 0; +var passiveSupported = false; +if (typeof window !== 'undefined') { + try { + var options = Object.defineProperty({}, 'passive', { + get: function () { + passiveSupported = true; + return true; } - return this.node(start, { - kind: _kinds.Kind.INLINE_FRAGMENT, - typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); - } - /** - * FragmentDefinition : - * - fragment FragmentName on TypeCondition Directives? SelectionSet - * - * TypeCondition : NamedType - */ - - parseFragmentDefinition() { - const start = this._lexer.token; - this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes - // the grammar of FragmentDefinition: - // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet - - if (this._options.allowLegacyFragmentVariables === true) { - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_DEFINITION, - name: this.parseFragmentName(), - variableDefinitions: this.parseVariableDefinitions(), - typeCondition: (this.expectKeyword('on'), this.parseNamedType()), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); + }); + // @ts-ignore + window.addEventListener('test', options, options); + // @ts-ignore + window.removeEventListener('test', options, options); + } catch (err) { + passiveSupported = false; + } +} +var nonPassive = exports.nonPassive = passiveSupported ? { + passive: false +} : false; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js": +/*!*****************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js ***! + \*****************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.locationCouldBeScrolled = exports.handleScroll = void 0; +var alwaysContainsScroll = function (node) { + // textarea will always _contain_ scroll inside self. It only can be hidden + return node.tagName === 'TEXTAREA'; +}; +var elementCanBeScrolled = function (node, overflow) { + var styles = window.getComputedStyle(node); + return ( + // not-not-scrollable + styles[overflow] !== 'hidden' && + // contains scroll inside self + !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible') + ); +}; +var elementCouldBeVScrolled = function (node) { + return elementCanBeScrolled(node, 'overflowY'); +}; +var elementCouldBeHScrolled = function (node) { + return elementCanBeScrolled(node, 'overflowX'); +}; +var locationCouldBeScrolled = function (axis, node) { + var current = node; + do { + // Skip over shadow root + if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) { + current = current.host; + } + var isScrollable = elementCouldBeScrolled(axis, current); + if (isScrollable) { + var _a = getScrollVariables(axis, current), + s = _a[1], + d = _a[2]; + if (s > d) { + return true; } - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_DEFINITION, - name: this.parseFragmentName(), - typeCondition: (this.expectKeyword('on'), this.parseNamedType()), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet() - }); } - /** - * FragmentName : Name but not `on` - */ - - parseFragmentName() { - if (this._lexer.token.value === 'on') { - throw this.unexpected(); + current = current.parentNode; + } while (current && current !== document.body); + return false; +}; +exports.locationCouldBeScrolled = locationCouldBeScrolled; +var getVScrollVariables = function (_a) { + var scrollTop = _a.scrollTop, + scrollHeight = _a.scrollHeight, + clientHeight = _a.clientHeight; + return [scrollTop, scrollHeight, clientHeight]; +}; +var getHScrollVariables = function (_a) { + var scrollLeft = _a.scrollLeft, + scrollWidth = _a.scrollWidth, + clientWidth = _a.clientWidth; + return [scrollLeft, scrollWidth, clientWidth]; +}; +var elementCouldBeScrolled = function (axis, node) { + return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); +}; +var getScrollVariables = function (axis, node) { + return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node); +}; +var getDirectionFactor = function (axis, direction) { + /** + * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position, + * and then increasingly negative as you scroll towards the end of the content. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft + */ + return axis === 'h' && direction === 'rtl' ? -1 : 1; +}; +var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) { + var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); + var delta = directionFactor * sourceDelta; + // find scrollable target + var target = event.target; + var targetInLock = endTarget.contains(target); + var shouldCancelScroll = false; + var isDeltaPositive = delta > 0; + var availableScroll = 0; + var availableScrollTop = 0; + do { + var _a = getScrollVariables(axis, target), + position = _a[0], + scroll_1 = _a[1], + capacity = _a[2]; + var elementScroll = scroll_1 - capacity - directionFactor * position; + if (position || elementScroll) { + if (elementCouldBeScrolled(axis, target)) { + availableScroll += elementScroll; + availableScrollTop += position; + } + } + target = target.parentNode; + } while ( + // portaled content + !targetInLock && target !== document.body || + // self content + targetInLock && (endTarget.contains(target) || endTarget === target)); + if (isDeltaPositive && (noOverscroll && availableScroll === 0 || !noOverscroll && delta > availableScroll)) { + shouldCancelScroll = true; + } else if (!isDeltaPositive && (noOverscroll && availableScrollTop === 0 || !noOverscroll && -delta > availableScrollTop)) { + shouldCancelScroll = true; + } + return shouldCancelScroll; +}; +exports.handleScroll = handleScroll; + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/index.js": +/*!**********************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/index.js ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "RemoveScroll", ({ + enumerable: true, + get: function () { + return _Combination.default; + } +})); +var _Combination = _interopRequireDefault(__webpack_require__(/*! ./Combination */ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js": +/*!***********************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/medium.js ***! + \***********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.effectCar = void 0; +var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); +var effectCar = exports.effectCar = (0, _useSidecar.createSidecarMedium)(); + +/***/ }), + +/***/ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js": +/*!************************************************************************!*\ + !*** ../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js ***! + \************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); +var _SideEffect = __webpack_require__(/*! ./SideEffect */ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js"); +var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); +var _default = exports["default"] = (0, _useSidecar.exportSidecar)(_medium.effectCar, _SideEffect.RemoveScrollSideCar); + +/***/ }), + +/***/ "../../../node_modules/react-style-singleton/dist/es2015/component.js": +/*!****************************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/component.js ***! + \****************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.styleSingleton = void 0; +var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); +/** + * create a Component to add styles on demand + * - styles are added when first instance is mounted + * - styles are removed when the last instance is unmounted + * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior + */ +var styleSingleton = function () { + var useStyle = (0, _hook.styleHookSingleton)(); + var Sheet = function (_a) { + var styles = _a.styles, + dynamic = _a.dynamic; + useStyle(styles, dynamic); + return null; + }; + return Sheet; +}; +exports.styleSingleton = styleSingleton; + +/***/ }), + +/***/ "../../../node_modules/react-style-singleton/dist/es2015/hook.js": +/*!***********************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/hook.js ***! + \***********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.styleHookSingleton = void 0; +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +/** + * creates a hook to control style singleton + * @see {@link styleSingleton} for a safer component version + * @example + * ```tsx + * const useStyle = styleHookSingleton(); + * /// + * useStyle('body { overflow: hidden}'); + */ +var styleHookSingleton = function () { + var sheet = (0, _singleton.stylesheetSingleton)(); + return function (styles, isDynamic) { + React.useEffect(function () { + sheet.add(styles); + return function () { + sheet.remove(); + }; + }, [styles && isDynamic]); + }; +}; +exports.styleHookSingleton = styleHookSingleton; + +/***/ }), + +/***/ "../../../node_modules/react-style-singleton/dist/es2015/index.js": +/*!************************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/index.js ***! + \************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "styleHookSingleton", ({ + enumerable: true, + get: function () { + return _hook.styleHookSingleton; + } +})); +Object.defineProperty(exports, "styleSingleton", ({ + enumerable: true, + get: function () { + return _component.styleSingleton; + } +})); +Object.defineProperty(exports, "stylesheetSingleton", ({ + enumerable: true, + get: function () { + return _singleton.stylesheetSingleton; + } +})); +var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-style-singleton/dist/es2015/component.js"); +var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); +var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); + +/***/ }), + +/***/ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js": +/*!****************************************************************************!*\ + !*** ../../../node_modules/react-style-singleton/dist/es2015/singleton.js ***! + \****************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.stylesheetSingleton = void 0; +var _getNonce = __webpack_require__(/*! get-nonce */ "../../../node_modules/get-nonce/dist/es2015/index.js"); +function makeStyleTag() { + if (!document) return null; + var tag = document.createElement('style'); + tag.type = 'text/css'; + var nonce = (0, _getNonce.getNonce)(); + if (nonce) { + tag.setAttribute('nonce', nonce); + } + return tag; +} +function injectStyles(tag, css) { + // @ts-ignore + if (tag.styleSheet) { + // @ts-ignore + tag.styleSheet.cssText = css; + } else { + tag.appendChild(document.createTextNode(css)); + } +} +function insertStyleTag(tag) { + var head = document.head || document.getElementsByTagName('head')[0]; + head.appendChild(tag); +} +var stylesheetSingleton = function () { + var counter = 0; + var stylesheet = null; + return { + add: function (style) { + if (counter == 0) { + if (stylesheet = makeStyleTag()) { + injectStyles(stylesheet, style); + insertStyleTag(stylesheet); + } } - return this.parseName(); - } // Implements the parsing rules in the Values section. - - /** - * Value[Const] : - * - [~Const] Variable - * - IntValue - * - FloatValue - * - StringValue - * - BooleanValue - * - NullValue - * - EnumValue - * - ListValue[?Const] - * - ObjectValue[?Const] - * - * BooleanValue : one of `true` `false` - * - * NullValue : `null` - * - * EnumValue : Name but not `true`, `false` or `null` - */ - - parseValueLiteral(isConst) { - const token = this._lexer.token; - switch (token.kind) { - case _tokenKind.TokenKind.BRACKET_L: - return this.parseList(isConst); - case _tokenKind.TokenKind.BRACE_L: - return this.parseObject(isConst); - case _tokenKind.TokenKind.INT: - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.INT, - value: token.value - }); - case _tokenKind.TokenKind.FLOAT: - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.FLOAT, - value: token.value - }); - case _tokenKind.TokenKind.STRING: - case _tokenKind.TokenKind.BLOCK_STRING: - return this.parseStringLiteral(); - case _tokenKind.TokenKind.NAME: - this.advanceLexer(); - switch (token.value) { - case 'true': - return this.node(token, { - kind: _kinds.Kind.BOOLEAN, - value: true - }); - case 'false': - return this.node(token, { - kind: _kinds.Kind.BOOLEAN, - value: false - }); - case 'null': - return this.node(token, { - kind: _kinds.Kind.NULL - }); - default: - return this.node(token, { - kind: _kinds.Kind.ENUM, - value: token.value - }); - } - case _tokenKind.TokenKind.DOLLAR: - if (isConst) { - this.expectToken(_tokenKind.TokenKind.DOLLAR); - if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { - const varName = this._lexer.token.value; - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected variable "$${varName}" in constant value.`); - } else { - throw this.unexpected(token); - } - } - return this.parseVariable(); - default: - throw this.unexpected(); + counter++; + }, + remove: function () { + counter--; + if (!counter && stylesheet) { + stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); + stylesheet = null; } } - parseConstValueLiteral() { - return this.parseValueLiteral(true); - } - parseStringLiteral() { - const token = this._lexer.token; - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.STRING, - value: token.value, - block: token.kind === _tokenKind.TokenKind.BLOCK_STRING - }); - } - /** - * ListValue[Const] : - * - [ ] - * - [ Value[?Const]+ ] - */ - - parseList(isConst) { - const item = () => this.parseValueLiteral(isConst); - return this.node(this._lexer.token, { - kind: _kinds.Kind.LIST, - values: this.any(_tokenKind.TokenKind.BRACKET_L, item, _tokenKind.TokenKind.BRACKET_R) - }); + }; +}; +exports.stylesheetSingleton = stylesheetSingleton; + +/***/ }), + +/***/ "../../../node_modules/react/cjs/react-jsx-runtime.development.js": +/*!************************************************************************!*\ + !*** ../../../node_modules/react/cjs/react-jsx-runtime.development.js ***! + \************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +if (true) { + (function () { + 'use strict'; + + var React = __webpack_require__(/*! react */ "react"); + + // ATTENTION + // When adding new symbols to this file, + // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' + // The Symbol used to tag the ReactElement-like types. + var REACT_ELEMENT_TYPE = Symbol.for('react.element'); + var REACT_PORTAL_TYPE = Symbol.for('react.portal'); + var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); + var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); + var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); + var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); + var REACT_CONTEXT_TYPE = Symbol.for('react.context'); + var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); + var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); + var REACT_MEMO_TYPE = Symbol.for('react.memo'); + var REACT_LAZY_TYPE = Symbol.for('react.lazy'); + var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + return null; } - /** - * ``` - * ObjectValue[Const] : - * - { } - * - { ObjectField[?Const]+ } - * ``` - */ - - parseObject(isConst) { - const item = () => this.parseObjectField(isConst); - return this.node(this._lexer.token, { - kind: _kinds.Kind.OBJECT, - fields: this.any(_tokenKind.TokenKind.BRACE_L, item, _tokenKind.TokenKind.BRACE_R) - }); + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning('error', format, args); + } + } } - /** - * ObjectField[Const] : Name : Value[?Const] - */ - - parseObjectField(isConst) { - const start = this._lexer.token; - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - return this.node(start, { - kind: _kinds.Kind.OBJECT_FIELD, - name, - value: this.parseValueLiteral(isConst) - }); - } // Implements the parsing rules in the Directives section. - - /** - * Directives[Const] : Directive[?Const]+ - */ - - parseDirectives(isConst) { - const directives = []; - while (this.peek(_tokenKind.TokenKind.AT)) { - directives.push(this.parseDirective(isConst)); + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); } - return directives; } - parseConstDirectives() { - return this.parseDirectives(true); + + // ----------------------------------------------------------------------------- + + var enableScopeAPI = false; // Experimental Create Event Handle API. + var enableCacheElement = false; + var enableTransitionTracing = false; // No known bugs, but needs performance testing + + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + // stuff. Intended to enable React core members to more easily debug scheduling + // issues in DEV builds. + + var enableDebugTracing = false; // Track which Fiber(s) schedule render work. + + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } - /** - * ``` - * Directive[Const] : @ Name Arguments[?Const]? - * ``` - */ - - parseDirective(isConst) { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.AT); - return this.node(start, { - kind: _kinds.Kind.DIRECTIVE, - name: this.parseName(), - arguments: this.parseArguments(isConst) - }); - } // Implements the parsing rules in the Types section. - - /** - * Type : - * - NamedType - * - ListType - * - NonNullType - */ - - parseTypeReference() { - const start = this._lexer.token; - let type; - if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { - const innerType = this.parseTypeReference(); - this.expectToken(_tokenKind.TokenKind.BRACKET_R); - type = this.node(start, { - kind: _kinds.Kind.LIST_TYPE, - type: innerType - }); - } else { - type = this.parseNamedType(); + function isValidElementType(type) { + if (typeof type === 'string' || typeof type === 'function') { + return true; + } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). + + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; } - if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { - return this.node(start, { - kind: _kinds.Kind.NON_NULL_TYPE, - type - }); + if (typeof type === 'object' && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || + // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } } - return type; - } - /** - * NamedType : Name - */ - - parseNamedType() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.NAMED_TYPE, - name: this.parseName() - }); - } // Implements the parsing rules in the Type Definition section. - - peekDescription() { - return this.peek(_tokenKind.TokenKind.STRING) || this.peek(_tokenKind.TokenKind.BLOCK_STRING); + return false; } - /** - * Description : StringValue - */ - - parseDescription() { - if (this.peekDescription()) { - return this.parseStringLiteral(); + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; + } // Keep in sync with react-reconciler/getComponentNameFromFiber + + function getContextName(type) { + return type.displayName || 'Context'; + } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; } + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + if (typeof type === 'string') { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + case REACT_PORTAL_TYPE: + return 'Portal'; + case REACT_PROFILER_TYPE: + return 'Profiler'; + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || 'Memo'; + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + return null; } - /** - * ``` - * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } - * ``` - */ - - parseSchemaDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('schema'); - const directives = this.parseConstDirectives(); - const operationTypes = this.many(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); - return this.node(start, { - kind: _kinds.Kind.SCHEMA_DEFINITION, - description, - directives, - operationTypes - }); + var assign = Object.assign; + + // Helpers to patch console.logs to avoid logging during side-effect free + // replaying on render function. This currently only patches the object + // lazily which won't cover if the log function was extracted eagerly. + // We could also eagerly patch the method. + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() {} + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + disabledDepth++; + } } - /** - * OperationTypeDefinition : OperationType : NamedType - */ - - parseOperationTypeDefinition() { - const start = this._lexer.token; - const operation = this.parseOperationType(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseNamedType(); - return this.node(start, { - kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, - operation, - type - }); + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } } - /** - * ScalarTypeDefinition : Description? scalar Name Directives[Const]? - */ - - parseScalarTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('scalar'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, - description, - name, - directives - }); + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + return '\n' + prefix + name; + } } - /** - * ObjectTypeDefinition : - * Description? - * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? - */ - - parseObjectTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('type'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, - description, - name, - interfaces, - directives, - fields - }); + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); } - /** - * ImplementsInterfaces : - * - implements `&`? NamedType - * - ImplementsInterfaces & NamedType - */ - - parseImplementsInterfaces() { - return this.expectOptionalKeyword('implements') ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) : []; + function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if (!fn || reentry) { + return ''; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== undefined) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; } - /** - * ``` - * FieldsDefinition : { FieldDefinition+ } - * ``` - */ - - parseFieldsDefinition() { - return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseFieldDefinition, _tokenKind.TokenKind.BRACE_R); + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } } - /** - * FieldDefinition : - * - Description? Name ArgumentsDefinition? : Type Directives[Const]? - */ - - parseFieldDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseName(); - const args = this.parseArgumentDefs(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseTypeReference(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.FIELD_DEFINITION, - description, - name, - arguments: args, - type, - directives - }); + function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); } - /** - * ArgumentsDefinition : ( InputValueDefinition+ ) - */ - - parseArgumentDefs() { - return this.optionalMany(_tokenKind.TokenKind.PAREN_L, this.parseInputValueDef, _tokenKind.TokenKind.PAREN_R); + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ''; + } + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + return ''; } - /** - * InputValueDefinition : - * - Description? Name : Type DefaultValue? Directives[Const]? - */ - - parseInputValueDef() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseTypeReference(); - let defaultValue; - if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { - defaultValue = this.parseConstValueLiteral(); - } - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.INPUT_VALUE_DEFINITION, - description, - name, - type, - defaultValue, - directives - }); + var hasOwnProperty = Object.prototype.hasOwnProperty; + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } } - /** - * InterfaceTypeDefinition : - * - Description? interface Name Directives[Const]? FieldsDefinition? - */ - - parseInterfaceTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('interface'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, - description, - name, - interfaces, - directives, - fields - }); + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error('Failed %s type: %s', location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } } - /** - * UnionTypeDefinition : - * - Description? union Name Directives[Const]? UnionMemberTypes? - */ - - parseUnionTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('union'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const types = this.parseUnionMemberTypes(); - return this.node(start, { - kind: _kinds.Kind.UNION_TYPE_DEFINITION, - description, - name, - directives, - types - }); + var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + + function isArray(a) { + return isArrayImpl(a); } - /** - * UnionMemberTypes : - * - = `|`? NamedType - * - UnionMemberTypes | NamedType + + /* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). */ - - parseUnionMemberTypes() { - return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) : []; + // $FlowFixMe only called in DEV, so void return is not possible. + function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } + } // $FlowFixMe only called in DEV, so void return is not possible. + + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } } - /** - * EnumTypeDefinition : - * - Description? enum Name Directives[Const]? EnumValuesDefinition? - */ - - parseEnumTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('enum'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const values = this.parseEnumValuesDefinition(); - return this.node(start, { - kind: _kinds.Kind.ENUM_TYPE_DEFINITION, - description, - name, - directives, - values - }); + function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; } - /** - * ``` - * EnumValuesDefinition : { EnumValueDefinition+ } - * ``` - */ - - parseEnumValuesDefinition() { - return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseEnumValueDefinition, _tokenKind.TokenKind.BRACE_R); + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } } - /** - * EnumValueDefinition : Description? EnumValue Directives[Const]? - */ - - parseEnumValueDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseEnumValueName(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.ENUM_VALUE_DEFINITION, - description, - name, - directives - }); + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown; + var specialPropRefWarningShown; + var didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; } - /** - * EnumValue : Name but not `true`, `false` or `null` - */ - - parseEnumValueName() { - if (this._lexer.token.value === 'true' || this._lexer.token.value === 'false' || this._lexer.token.value === 'null') { - throw (0, _syntaxError.syntaxError)(this._lexer.source, this._lexer.token.start, `${getTokenDesc(this._lexer.token)} is reserved and cannot be used for an enum value.`); + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, 'ref')) { + var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; + if (getter && getter.isReactWarning) { + return false; + } + } } - return this.parseName(); - } - /** - * InputObjectTypeDefinition : - * - Description? input Name Directives[Const]? InputFieldsDefinition? - */ - - parseInputObjectTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('input'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const fields = this.parseInputFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, - description, - name, - directives, - fields - }); + return config.ref !== undefined; } - /** - * ``` - * InputFieldsDefinition : { InputValueDefinition+ } - * ``` - */ - - parseInputFieldsDefinition() { - return this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseInputValueDef, _tokenKind.TokenKind.BRACE_R); + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, 'key')) { + var getter = Object.getOwnPropertyDescriptor(config, 'key').get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== undefined; } - /** - * TypeSystemExtension : - * - SchemaExtension - * - TypeExtension - * - * TypeExtension : - * - ScalarTypeExtension - * - ObjectTypeExtension - * - InterfaceTypeExtension - * - UnionTypeExtension - * - EnumTypeExtension - * - InputObjectTypeDefinition - */ - - parseTypeSystemExtension() { - const keywordToken = this._lexer.lookahead(); - if (keywordToken.kind === _tokenKind.TokenKind.NAME) { - switch (keywordToken.value) { - case 'schema': - return this.parseSchemaExtension(); - case 'scalar': - return this.parseScalarTypeExtension(); - case 'type': - return this.parseObjectTypeExtension(); - case 'interface': - return this.parseInterfaceTypeExtension(); - case 'union': - return this.parseUnionTypeExtension(); - case 'enum': - return this.parseEnumTypeExtension(); - case 'input': - return this.parseInputObjectTypeExtension(); - } - } - throw this.unexpected(keywordToken); + function warnIfStringRefCannotBeAutoConverted(config, self) { + { + if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } } - /** - * ``` - * SchemaExtension : - * - extend schema Directives[Const]? { OperationTypeDefinition+ } - * - extend schema Directives[Const] - * ``` - */ - - parseSchemaExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('schema'); - const directives = this.parseConstDirectives(); - const operationTypes = this.optionalMany(_tokenKind.TokenKind.BRACE_L, this.parseOperationTypeDefinition, _tokenKind.TokenKind.BRACE_R); - if (directives.length === 0 && operationTypes.length === 0) { - throw this.unexpected(); + function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function () { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, 'key', { + get: warnAboutAccessingKey, + configurable: true + }); } - return this.node(start, { - kind: _kinds.Kind.SCHEMA_EXTENSION, - directives, - operationTypes - }); } - /** - * ScalarTypeExtension : - * - extend scalar Name Directives[Const] - */ - - parseScalarTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('scalar'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - if (directives.length === 0) { - throw this.unexpected(); + function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function () { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, 'ref', { + get: warnAboutAccessingRef, + configurable: true + }); } - return this.node(start, { - kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, - name, - directives - }); } /** - * ObjectTypeExtension : - * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition - * - extend type Name ImplementsInterfaces? Directives[Const] - * - extend type Name ImplementsInterfaces + * Factory method to create a new React element. This no longer adheres to + * the class pattern, so do not use new to call it. Also, instanceof check + * will not work. Instead test $$typeof field against Symbol.for('react.element') to check + * if something is a React Element. + * + * @param {*} type + * @param {*} props + * @param {*} key + * @param {string|object} ref + * @param {*} owner + * @param {*} self A *temporary* helper to detect places where `this` is + * different from the `owner` when React.createElement is called, so that we + * can warn. We want to get rid of owner and replace string `ref`s with arrow + * functions, and as long as `this` and owner are the same, there will be no + * change in behavior. + * @param {*} source An annotation object (added by a transpiler or otherwise) + * indicating filename, line number, and/or other information. + * @internal */ - - parseObjectTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('type'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { - throw this.unexpected(); + + var ReactElement = function (type, key, ref, self, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: ref, + props: props, + // Record the component responsible for creating this element. + _owner: owner + }; + { + // The validation flag is currently mutative. We put it on + // an external backing store so that we can freeze the whole object. + // This can be replaced with a WeakMap once they are implemented in + // commonly used development environments. + element._store = {}; // To make comparing ReactElements easier for testing purposes, we make + // the validation flag non-enumerable (where possible, which should + // include every environment we run tests in), so the test framework + // ignores it. + + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: false + }); // self and source are DEV only properties. + + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: self + }); // Two elements created in two different places should be considered + // equal for testing purposes and therefore we hide it from enumeration. + + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } } - return this.node(start, { - kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, - name, - interfaces, - directives, - fields - }); - } + return element; + }; /** - * InterfaceTypeExtension : - * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition - * - extend interface Name ImplementsInterfaces? Directives[Const] - * - extend interface Name ImplementsInterfaces + * https://github.com/reactjs/rfcs/pull/107 + * @param {*} type + * @param {object} props + * @param {string} key */ - - parseInterfaceTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('interface'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { - throw this.unexpected(); + + function jsxDEV(type, config, maybeKey, source, self) { + { + var propName; // Reserved names are extracted + + var props = {}; + var key = null; + var ref = null; // Currently, key can be spread in as a prop. This causes a potential + // issue if key is also explicitly declared (ie.
    + // or
    ). We want to deprecate key spread, + // but as an intermediary step, we will use jsxDEV for everything except + //
    , because we aren't currently able to tell if + // key is explicitly declared to be undefined or not. + + if (maybeKey !== undefined) { + { + checkKeyStringCoercion(maybeKey); + } + key = '' + maybeKey; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = '' + config.key; + } + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self); + } // Remaining properties are added to a new props object + + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } // Resolve default props + + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + if (key || ref) { + var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } - return this.node(start, { - kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, - name, - interfaces, - directives, - fields - }); } - /** - * UnionTypeExtension : - * - extend union Name Directives[Const]? UnionMemberTypes - * - extend union Name Directives[Const] - */ - - parseUnionTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('union'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const types = this.parseUnionMemberTypes(); - if (directives.length === 0 && types.length === 0) { - throw this.unexpected(); + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } } - return this.node(start, { - kind: _kinds.Kind.UNION_TYPE_EXTENSION, - name, - directives, - types - }); + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; } /** - * EnumTypeExtension : - * - extend enum Name Directives[Const]? EnumValuesDefinition - * - extend enum Name Directives[Const] + * Verifies the object is a ReactElement. + * See https://reactjs.org/docs/react-api.html#isvalidelement + * @param {?object} object + * @return {boolean} True if `object` is a ReactElement. + * @final */ - - parseEnumTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('enum'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const values = this.parseEnumValuesDefinition(); - if (directives.length === 0 && values.length === 0) { - throw this.unexpected(); + + function isValidElement(object) { + { + return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } - return this.node(start, { - kind: _kinds.Kind.ENUM_TYPE_EXTENSION, - name, - directives, - values - }); } - /** - * InputObjectTypeExtension : - * - extend input Name Directives[Const]? InputFieldsDefinition - * - extend input Name Directives[Const] - */ - - parseInputObjectTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('input'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const fields = this.parseInputFieldsDefinition(); - if (directives.length === 0 && fields.length === 0) { - throw this.unexpected(); + function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); + if (name) { + return '\n\nCheck the render method of `' + name + '`.'; + } + } + return ''; } - return this.node(start, { - kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, - name, - directives, - fields - }); } - /** - * ``` - * DirectiveDefinition : - * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations - * ``` - */ - - parseDirectiveDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('directive'); - this.expectToken(_tokenKind.TokenKind.AT); - const name = this.parseName(); - const args = this.parseArgumentDefs(); - const repeatable = this.expectOptionalKeyword('repeatable'); - this.expectKeyword('on'); - const locations = this.parseDirectiveLocations(); - return this.node(start, { - kind: _kinds.Kind.DIRECTIVE_DEFINITION, - description, - name, - arguments: args, - repeatable, - locations - }); + function getSourceInfoErrorAddendum(source) { + { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ''); + var lineNumber = source.lineNumber; + return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; + } + return ''; + } } /** - * DirectiveLocations : - * - `|`? DirectiveLocation - * - DirectiveLocations | DirectiveLocation - */ - - parseDirectiveLocations() { - return this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseDirectiveLocation); - } - /* - * DirectiveLocation : - * - ExecutableDirectiveLocation - * - TypeSystemDirectiveLocation - * - * ExecutableDirectiveLocation : one of - * `QUERY` - * `MUTATION` - * `SUBSCRIPTION` - * `FIELD` - * `FRAGMENT_DEFINITION` - * `FRAGMENT_SPREAD` - * `INLINE_FRAGMENT` - * - * TypeSystemDirectiveLocation : one of - * `SCHEMA` - * `SCALAR` - * `OBJECT` - * `FIELD_DEFINITION` - * `ARGUMENT_DEFINITION` - * `INTERFACE` - * `UNION` - * `ENUM` - * `ENUM_VALUE` - * `INPUT_OBJECT` - * `INPUT_FIELD_DEFINITION` + * Warn if there's no key explicitly set on dynamic arrays of children or + * object keys are not valid. This allows us to keep track of children between + * updates. */ - - parseDirectiveLocation() { - const start = this._lexer.token; - const name = this.parseName(); - if (Object.prototype.hasOwnProperty.call(_directiveLocation.DirectiveLocation, name.value)) { - return name; + + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; } - throw this.unexpected(start); - } // Core parsing utility functions - + } /** - * Returns a node that, if configured to do so, sets a "loc" field as a - * location object, used to identify the place in the source that created a - * given parsed object. + * Warn if the element doesn't have an explicit key assigned to it. + * This element is in an array. The array could grow and shrink or be + * reordered. All children that haven't already been validated are required to + * have a "key" property assigned to it. Error statuses are cached so a warning + * will only be shown once. + * + * @internal + * @param {ReactElement} element Element that requires a key. + * @param {*} parentType element's parent's type. */ - - node(startToken, node) { - if (this._options.noLocation !== true) { - node.loc = new _ast.Location(startToken, this._lexer.lastToken, this._lexer.source); + + function validateExplicitKey(element, parentType) { + { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a + // property, it may be the creator of the child that's responsible for + // assigning it a key. + + var childOwner = ''; + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { + // Give the component that originally created this child. + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); } - return node; } /** - * Determines if the next token is of a given kind + * Ensure that every element either is passed in a static location, in an + * array with an explicit keys property defined, or in an object literal + * with valid key property. + * + * @internal + * @param {ReactNode} node Statically passed child of any type. + * @param {*} parentType node's parent's type. */ - - peek(kind) { - return this._lexer.token.kind === kind; + + function validateChildKeys(node, parentType) { + { + if (typeof node !== 'object') { + return; + } + if (isArray(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + // This element was passed in a valid location. + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === 'function') { + // Entry iterators used to provide implicit keys, + // but now we print a separate warning for them later. + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } } /** - * If the next token is of the given kind, return that token after advancing the lexer. - * Otherwise, do not change the parser state and throw an error. + * Given an element, validate that its props follow the propTypes definition, + * provided by the type. + * + * @param {ReactElement} element */ - - expectToken(kind) { - const token = this._lexer.token; - if (token.kind === kind) { - this.advanceLexer(); - return token; + + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === undefined || typeof type === 'string') { + return; + } + var propTypes; + if (typeof type === 'function') { + propTypes = type.propTypes; + } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || + // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + // Intentionally inside to avoid triggering lazy initializers: + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, 'prop', name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: + + var _name = getComponentNameFromType(type); + error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); + } + if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { + error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); + } } - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`); } /** - * If the next token is of the given kind, return "true" after advancing the lexer. - * Otherwise, do not change the parser state and return "false". + * Given a fragment, validate that it can only be provided with fragment props + * @param {ReactElement} fragment */ - - expectOptionalToken(kind) { - const token = this._lexer.token; - if (token.kind === kind) { - this.advanceLexer(); - return true; + + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key !== 'children' && key !== 'key') { + setCurrentlyValidatingElement$1(fragment); + error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error('Invalid attribute `ref` supplied to `React.Fragment`.'); + setCurrentlyValidatingElement$1(null); + } } - return false; } - /** - * If the next token is a given keyword, advance the lexer. - * Otherwise, do not change the parser state and throw an error. - */ - - expectKeyword(value) { - const token = this._lexer.token; - if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { - this.advanceLexer(); - } else { - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.`); + function jsxWithValidation(type, props, key, isStaticChildren, source, self) { + { + var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to + // succeed and there will likely be errors in render. + + if (!validType) { + var info = ''; + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendum(source); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = 'null'; + } else if (isArray(type)) { + typeString = 'array'; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; + info = ' Did you accidentally export a JSX literal instead of a component?'; + } else { + typeString = typeof type; + } + error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); + } + var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. + // TODO: Drop this when these are no longer allowed as the type argument. + + if (element == null) { + return element; + } // Skip key warning if the type isn't valid since our key validation logic + // doesn't expect a non-string/function type and can throw confusing errors. + // We don't want exception behavior to differ between dev and prod. + // (Rendering will throw with a helpful message and as soon as the type is + // fixed, the key warnings will appear.) + + if (validType) { + var children = props.children; + if (children !== undefined) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i = 0; i < children.length; i++) { + validateChildKeys(children[i], type); + } + if (Object.freeze) { + Object.freeze(children); + } + } else { + error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); + } + } else { + validateChildKeys(children, type); + } + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + } // These two functions exist to still get child warnings in dev + // even with the prod transform. This means that jsxDEV is purely + // opt-in behavior for better messages but that we won't stop + // giving you warnings if you use production apis. + + function jsxWithValidationStatic(type, props, key) { + { + return jsxWithValidation(type, props, key, true); } } - /** - * If the next token is a given keyword, return "true" after advancing the lexer. - * Otherwise, do not change the parser state and return "false". - */ - - expectOptionalKeyword(value) { - const token = this._lexer.token; - if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { - this.advanceLexer(); - return true; + function jsxWithValidationDynamic(type, props, key) { + { + return jsxWithValidation(type, props, key, false); } - return false; } - /** - * Helper function for creating an error when an unexpected lexed token is encountered. - */ - - unexpected(atToken) { - const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; - return (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.`); + var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children. + // for now we can ship identical prod functions + + var jsxs = jsxWithValidationStatic; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.jsx = jsx; + exports.jsxs = jsxs; + })(); +} + +/***/ }), + +/***/ "../../../node_modules/react/jsx-runtime.js": +/*!**************************************************!*\ + !*** ../../../node_modules/react/jsx-runtime.js ***! + \**************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + +if (false) {} else { + module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ "../../../node_modules/react/cjs/react-jsx-runtime.development.js"); +} + +/***/ }), + +/***/ "../../../node_modules/set-value/index.js": +/*!************************************************!*\ + !*** ../../../node_modules/set-value/index.js ***! + \************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/*! + * set-value + * + * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert). + * Released under the MIT License. + */ + + + +const { + deleteProperty +} = Reflect; +const isPrimitive = __webpack_require__(/*! is-primitive */ "../../../node_modules/is-primitive/index.js"); +const isPlainObject = __webpack_require__(/*! is-plain-object */ "../../../node_modules/is-plain-object/index.js"); +const isObject = value => { + return typeof value === 'object' && value !== null || typeof value === 'function'; +}; +const isUnsafeKey = key => { + return key === '__proto__' || key === 'constructor' || key === 'prototype'; +}; +const validateKey = key => { + if (!isPrimitive(key)) { + throw new TypeError('Object keys must be strings or symbols'); + } + if (isUnsafeKey(key)) { + throw new Error(`Cannot set unsafe key: "${key}"`); + } +}; +const toStringKey = input => { + return Array.isArray(input) ? input.flat().map(String).join(',') : input; +}; +const createMemoKey = (input, options) => { + if (typeof input !== 'string' || !options) return input; + let key = input + ';'; + if (options.arrays !== undefined) key += `arrays=${options.arrays};`; + if (options.separator !== undefined) key += `separator=${options.separator};`; + if (options.split !== undefined) key += `split=${options.split};`; + if (options.merge !== undefined) key += `merge=${options.merge};`; + if (options.preservePaths !== undefined) key += `preservePaths=${options.preservePaths};`; + return key; +}; +const memoize = (input, options, fn) => { + const key = toStringKey(options ? createMemoKey(input, options) : input); + validateKey(key); + const value = setValue.cache.get(key) || fn(); + setValue.cache.set(key, value); + return value; +}; +const splitString = (input, options = {}) => { + const sep = options.separator || '.'; + const preserve = sep === '/' ? false : options.preservePaths; + if (typeof input === 'string' && preserve !== false && /\//.test(input)) { + return [input]; + } + const parts = []; + let part = ''; + const push = part => { + let number; + if (part.trim() !== '' && Number.isInteger(number = Number(part))) { + parts.push(number); + } else { + parts.push(part); } - /** - * Returns a possibly empty list of parse nodes, determined by the parseFn. - * This list begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ - - any(openKind, parseFn, closeKind) { - this.expectToken(openKind); - const nodes = []; - while (!this.expectOptionalToken(closeKind)) { - nodes.push(parseFn.call(this)); - } - return nodes; + }; + for (let i = 0; i < input.length; i++) { + const value = input[i]; + if (value === '\\') { + part += input[++i]; + continue; } - /** - * Returns a list of parse nodes, determined by the parseFn. - * It can be empty only if open token is missing otherwise it will always return non-empty list - * that begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ - - optionalMany(openKind, parseFn, closeKind) { - if (this.expectOptionalToken(openKind)) { - const nodes = []; - do { - nodes.push(parseFn.call(this)); - } while (!this.expectOptionalToken(closeKind)); - return nodes; - } - return []; + if (value === sep) { + push(part); + part = ''; + continue; + } + part += value; + } + if (part) { + push(part); + } + return parts; +}; +const split = (input, options) => { + if (options && typeof options.split === 'function') return options.split(input); + if (typeof input === 'symbol') return [input]; + if (Array.isArray(input)) return input; + return memoize(input, options, () => splitString(input, options)); +}; +const assignProp = (obj, prop, value, options) => { + validateKey(prop); + + // Delete property when "value" is undefined + if (value === undefined) { + deleteProperty(obj, prop); + } else if (options && options.merge) { + const merge = options.merge === 'function' ? options.merge : Object.assign; + + // Only merge plain objects + if (merge && isPlainObject(obj[prop]) && isPlainObject(value)) { + obj[prop] = merge(obj[prop], value); + } else { + obj[prop] = value; } - /** - * Returns a non-empty list of parse nodes, determined by the parseFn. - * This list begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ - - many(openKind, parseFn, closeKind) { - this.expectToken(openKind); - const nodes = []; - do { - nodes.push(parseFn.call(this)); - } while (!this.expectOptionalToken(closeKind)); - return nodes; + } else { + obj[prop] = value; + } + return obj; +}; +const setValue = (target, path, value, options) => { + if (!path || !isObject(target)) return target; + const keys = split(path, options); + let obj = target; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const next = keys[i + 1]; + validateKey(key); + if (next === undefined) { + assignProp(obj, key, value, options); + break; } - /** - * Returns a non-empty list of parse nodes, determined by the parseFn. - * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. - * Advances the parser to the next lex token after last item in the list. - */ - - delimitedMany(delimiterKind, parseFn) { - this.expectOptionalToken(delimiterKind); - const nodes = []; - do { - nodes.push(parseFn.call(this)); - } while (this.expectOptionalToken(delimiterKind)); - return nodes; + if (typeof next === 'number' && !Array.isArray(obj[key])) { + obj = obj[key] = []; + continue; } - advanceLexer() { - const { - maxTokens - } = this._options; - const token = this._lexer.advance(); - if (maxTokens !== undefined && token.kind !== _tokenKind.TokenKind.EOF) { - ++this._tokenCounter; - if (this._tokenCounter > maxTokens) { - throw (0, _syntaxError.syntaxError)(this._lexer.source, token.start, `Document contains more that ${maxTokens} tokens. Parsing aborted.`); - } - } + if (!isObject(obj[key])) { + obj[key] = {}; } + obj = obj[key]; } - /** - * A helper function to describe a token as a string for debugging. - */ - exports.Parser = Parser; - function getTokenDesc(token) { - const value = token.value; - return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); - } - /** - * A helper function to describe a token kind as a string for debugging. - */ - - function getTokenKindDesc(kind) { - return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; + return target; +}; +setValue.split = split; +setValue.cache = new Map(); +setValue.clear = () => { + setValue.cache = new Map(); +}; +module.exports = setValue; + +/***/ }), + +/***/ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js": +/*!**********************************************************************!*\ + !*** ../../../node_modules/style-value-types/dist/valueTypes.cjs.js ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +const clamp = (min, max) => v => Math.max(Math.min(v, max), min); +const sanitize = v => v % 1 ? Number(v.toFixed(5)) : v; +const floatRegex = /(-)?([\d]*\.?[\d])+/g; +const colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi; +const singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i; +function isString(v) { + return typeof v === 'string'; +} +const number = { + test: v => typeof v === 'number', + parse: parseFloat, + transform: v => v +}; +const alpha = Object.assign(Object.assign({}, number), { + transform: clamp(0, 1) +}); +const scale = Object.assign(Object.assign({}, number), { + default: 1 +}); +const createUnitType = unit => ({ + test: v => isString(v) && v.endsWith(unit) && v.split(' ').length === 1, + parse: parseFloat, + transform: v => `${v}${unit}` +}); +const degrees = createUnitType('deg'); +const percent = createUnitType('%'); +const px = createUnitType('px'); +const vh = createUnitType('vh'); +const vw = createUnitType('vw'); +const progressPercentage = Object.assign(Object.assign({}, percent), { + parse: v => percent.parse(v) / 100, + transform: v => percent.transform(v * 100) +}); +const isColorString = (type, testProp) => v => { + return Boolean(isString(v) && singleColorRegex.test(v) && v.startsWith(type) || testProp && Object.prototype.hasOwnProperty.call(v, testProp)); +}; +const splitColor = (aName, bName, cName) => v => { + if (!isString(v)) return v; + const [a, b, c, alpha] = v.match(floatRegex); + return { + [aName]: parseFloat(a), + [bName]: parseFloat(b), + [cName]: parseFloat(c), + alpha: alpha !== undefined ? parseFloat(alpha) : 1 + }; +}; +const hsla = { + test: isColorString('hsl', 'hue'), + parse: splitColor('hue', 'saturation', 'lightness'), + transform: ({ + hue, + saturation, + lightness, + alpha: alpha$1 = 1 + }) => { + return 'hsla(' + Math.round(hue) + ', ' + percent.transform(sanitize(saturation)) + ', ' + percent.transform(sanitize(lightness)) + ', ' + sanitize(alpha.transform(alpha$1)) + ')'; + } +}; +const clampRgbUnit = clamp(0, 255); +const rgbUnit = Object.assign(Object.assign({}, number), { + transform: v => Math.round(clampRgbUnit(v)) +}); +const rgba = { + test: isColorString('rgb', 'red'), + parse: splitColor('red', 'green', 'blue'), + transform: ({ + red, + green, + blue, + alpha: alpha$1 = 1 + }) => 'rgba(' + rgbUnit.transform(red) + ', ' + rgbUnit.transform(green) + ', ' + rgbUnit.transform(blue) + ', ' + sanitize(alpha.transform(alpha$1)) + ')' +}; +function parseHex(v) { + let r = ''; + let g = ''; + let b = ''; + let a = ''; + if (v.length > 5) { + r = v.substr(1, 2); + g = v.substr(3, 2); + b = v.substr(5, 2); + a = v.substr(7, 2); + } else { + r = v.substr(1, 1); + g = v.substr(2, 1); + b = v.substr(3, 1); + a = v.substr(4, 1); + r += r; + g += g; + b += b; + a += a; + } + return { + red: parseInt(r, 16), + green: parseInt(g, 16), + blue: parseInt(b, 16), + alpha: a ? parseInt(a, 16) / 255 : 1 + }; +} +const hex = { + test: isColorString('#'), + parse: parseHex, + transform: rgba.transform +}; +const color = { + test: v => rgba.test(v) || hex.test(v) || hsla.test(v), + parse: v => { + if (rgba.test(v)) { + return rgba.parse(v); + } else if (hsla.test(v)) { + return hsla.parse(v); + } else { + return hex.parse(v); + } + }, + transform: v => { + return isString(v) ? v : v.hasOwnProperty('red') ? rgba.transform(v) : hsla.transform(v); + } +}; +const colorToken = '${c}'; +const numberToken = '${n}'; +function test(v) { + var _a, _b, _c, _d; + return isNaN(v) && isString(v) && ((_b = (_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0; +} +function analyse(v) { + if (typeof v === 'number') v = `${v}`; + const values = []; + let numColors = 0; + const colors = v.match(colorRegex); + if (colors) { + numColors = colors.length; + v = v.replace(colorRegex, colorToken); + values.push(...colors.map(color.parse)); + } + const numbers = v.match(floatRegex); + if (numbers) { + v = v.replace(floatRegex, numberToken); + values.push(...numbers.map(number.parse)); + } + return { + values, + numColors, + tokenised: v + }; +} +function parse(v) { + return analyse(v).values; +} +function createTransformer(v) { + const { + values, + numColors, + tokenised + } = analyse(v); + const numValues = values.length; + return v => { + let output = tokenised; + for (let i = 0; i < numValues; i++) { + output = output.replace(i < numColors ? colorToken : numberToken, i < numColors ? color.transform(v[i]) : sanitize(v[i])); + } + return output; + }; +} +const convertNumbersToZero = v => typeof v === 'number' ? 0 : v; +function getAnimatableNone(v) { + const parsed = parse(v); + const transformer = createTransformer(v); + return transformer(parsed.map(convertNumbersToZero)); +} +const complex = { + test, + parse, + createTransformer, + getAnimatableNone +}; +const maxDefaults = new Set(['brightness', 'contrast', 'saturate', 'opacity']); +function applyDefaultFilter(v) { + let [name, value] = v.slice(0, -1).split('('); + if (name === 'drop-shadow') return v; + const [number] = value.match(floatRegex) || []; + if (!number) return v; + const unit = value.replace(number, ''); + let defaultValue = maxDefaults.has(name) ? 1 : 0; + if (number !== value) defaultValue *= 100; + return name + '(' + defaultValue + unit + ')'; +} +const functionRegex = /([a-z-]*)\(.*?\)/g; +const filter = Object.assign(Object.assign({}, complex), { + getAnimatableNone: v => { + const functions = v.match(functionRegex); + return functions ? functions.map(applyDefaultFilter).join(' ') : v; + } +}); +exports.alpha = alpha; +exports.color = color; +exports.complex = complex; +exports.degrees = degrees; +exports.filter = filter; +exports.hex = hex; +exports.hsla = hsla; +exports.number = number; +exports.percent = percent; +exports.progressPercentage = progressPercentage; +exports.px = px; +exports.rgbUnit = rgbUnit; +exports.rgba = rgba; +exports.scale = scale; +exports.vh = vh; +exports.vw = vw; + +/***/ }), + +/***/ "../../../node_modules/toggle-selection/index.js": +/*!*******************************************************!*\ + !*** ../../../node_modules/toggle-selection/index.js ***! + \*******************************************************/ +/***/ (function(module) { + + + +module.exports = function () { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function () {}; + } + var active = document.activeElement; + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + switch (active.tagName.toUpperCase()) { + // .toUpperCase handles XHTML + case 'INPUT': + case 'TEXTAREA': + active.blur(); + break; + default: + active = null; + break; } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/predicates.mjs": - /*!*************************************************************!*\ - !*** ../../../node_modules/graphql/language/predicates.mjs ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isConstValueNode = isConstValueNode; - exports.isDefinitionNode = isDefinitionNode; - exports.isExecutableDefinitionNode = isExecutableDefinitionNode; - exports.isSelectionNode = isSelectionNode; - exports.isTypeDefinitionNode = isTypeDefinitionNode; - exports.isTypeExtensionNode = isTypeExtensionNode; - exports.isTypeNode = isTypeNode; - exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; - exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; - exports.isValueNode = isValueNode; - var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - function isDefinitionNode(node) { - return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); + selection.removeAllRanges(); + return function () { + selection.type === 'Caret' && selection.removeAllRanges(); + if (!selection.rangeCount) { + ranges.forEach(function (range) { + selection.addRange(range); + }); + } + active && active.focus(); + }; +}; + +/***/ }), + +/***/ "../../../node_modules/tslib/tslib.es6.mjs": +/*!*************************************************!*\ + !*** ../../../node_modules/tslib/tslib.es6.mjs ***! + \*************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.__addDisposableResource = __addDisposableResource; +exports.__assign = void 0; +exports.__asyncDelegator = __asyncDelegator; +exports.__asyncGenerator = __asyncGenerator; +exports.__asyncValues = __asyncValues; +exports.__await = __await; +exports.__awaiter = __awaiter; +exports.__classPrivateFieldGet = __classPrivateFieldGet; +exports.__classPrivateFieldIn = __classPrivateFieldIn; +exports.__classPrivateFieldSet = __classPrivateFieldSet; +exports.__createBinding = void 0; +exports.__decorate = __decorate; +exports.__disposeResources = __disposeResources; +exports.__esDecorate = __esDecorate; +exports.__exportStar = __exportStar; +exports.__extends = __extends; +exports.__generator = __generator; +exports.__importDefault = __importDefault; +exports.__importStar = __importStar; +exports.__makeTemplateObject = __makeTemplateObject; +exports.__metadata = __metadata; +exports.__param = __param; +exports.__propKey = __propKey; +exports.__read = __read; +exports.__rest = __rest; +exports.__runInitializers = __runInitializers; +exports.__setFunctionName = __setFunctionName; +exports.__spread = __spread; +exports.__spreadArray = __spreadArray; +exports.__spreadArrays = __spreadArrays; +exports.__values = __values; +exports["default"] = void 0; +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + +var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; + }; + return extendStatics(d, b); +}; +function __extends(d, b) { + if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +var __assign = function () { + exports.__assign = __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +exports.__assign = __assign; +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, + key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, + done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { + get: descriptor.get, + set: descriptor.set + } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_);else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +; +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +; +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +; +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { + configurable: true, + value: prefix ? "".concat(prefix, " ", name) : name + }); +} +; +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); } - function isExecutableDefinitionNode(node) { - return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; } - function isSelectionNode(node) { - return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { + value: op[1], + done: false + }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; } - function isValueNode(node) { - return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; +} +var __createBinding = exports.__createBinding = Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; } - function isConstValueNode(node) { - return isValueNode(node) && (node.kind === _kinds.Kind.LIST ? node.values.some(isConstValueNode) : node.kind === _kinds.Kind.OBJECT ? node.fields.some(field => isConstValueNode(field.value)) : node.kind !== _kinds.Kind.VARIABLE); + Object.defineProperty(o, k2, desc); +} : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}; +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o + }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), + r, + ar = [], + e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } } - function isTypeNode(node) { - return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; + return ar; +} + +/** @deprecated */ +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; } - function isTypeSystemDefinitionNode(node) { - return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } } - function isTypeDefinitionNode(node) { - return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function isTypeSystemExtensionNode(node) { - return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); + function fulfill(value) { + resume("next", value); } - function isTypeExtensionNode(node) { - return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + function reject(value) { + resume("throw", value); } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/printLocation.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/language/printLocation.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.printLocation = printLocation; - exports.printSourceLocation = printSourceLocation; - var _location = __webpack_require__(/*! ./location.mjs */ "../../../node_modules/graphql/language/location.mjs"); - /** - * Render a helpful description of the location in the GraphQL Source document. - */ - function printLocation(location) { - return printSourceLocation(location.source, (0, _location.getLocation)(location.source, location.start)); + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - /** - * Render a helpful description of the location in the GraphQL Source document. - */ - - function printSourceLocation(source, sourceLocation) { - const firstLineColumnOffset = source.locationOffset.column - 1; - const body = ''.padStart(firstLineColumnOffset) + source.body; - const lineIndex = sourceLocation.line - 1; - const lineOffset = source.locationOffset.line - 1; - const lineNum = sourceLocation.line + lineOffset; - const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; - const columnNum = sourceLocation.column + columnOffset; - const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; - const lines = body.split(/\r\n|[\n\r]/g); - const locationLine = lines[lineIndex]; // Special case for minified documents - - if (locationLine.length > 120) { - const subLineIndex = Math.floor(columnNum / 80); - const subLineColumnNum = columnNum % 80; - const subLines = []; - for (let i = 0; i < locationLine.length; i += 80) { - subLines.push(locationLine.slice(i, i + 80)); - } - return locationStr + printPrefixedLines([[`${lineNum} |`, subLines[0]], ...subLines.slice(1, subLineIndex + 1).map(subLine => ['|', subLine]), ['|', '^'.padStart(subLineColumnNum)], ['|', subLines[subLineIndex + 1]]]); - } - return locationStr + printPrefixedLines([ - // Lines specified like this: ["prefix", "string"], - [`${lineNum - 1} |`, lines[lineIndex - 1]], [`${lineNum} |`, locationLine], ['|', '^'.padStart(columnNum)], [`${lineNum + 1} |`, lines[lineIndex + 1]]]); +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: false + } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; } - function printPrefixedLines(lines) { - const existingLines = lines.filter(([_, line]) => line !== undefined); - const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); - return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')).join('\n'); + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/printString.mjs": - /*!**************************************************************!*\ - !*** ../../../node_modules/graphql/language/printString.mjs ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.printString = printString; - /** - * Prints a string as a GraphQL StringValue literal. Replaces control characters - * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. - */ - function printString(str) { - return `"${str.replace(escapedRegExp, escapedReplacer)}"`; - } // eslint-disable-next-line no-control-regex - - const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; - function escapedReplacer(str) { - return escapeSequences[str.charCodeAt(0)]; - } // prettier-ignore - - const escapeSequences = ['\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007', '\\b', '\\t', '\\n', '\\u000B', '\\f', '\\r', '\\u000E', '\\u000F', '\\u0010', '\\u0011', '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019', '\\u001A', '\\u001B', '\\u001C', '\\u001D', '\\u001E', '\\u001F', '', '', '\\"', '', '', '', '', '', '', '', '', '', '', '', '', '', - // 2F - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - // 3F - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - // 4F - '', '', '', '', '', '', '', '', '', '', '', '', '\\\\', '', '', '', - // 5F - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', - // 6F - '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '\\u007F', '\\u0080', '\\u0081', '\\u0082', '\\u0083', '\\u0084', '\\u0085', '\\u0086', '\\u0087', '\\u0088', '\\u0089', '\\u008A', '\\u008B', '\\u008C', '\\u008D', '\\u008E', '\\u008F', '\\u0090', '\\u0091', '\\u0092', '\\u0093', '\\u0094', '\\u0095', '\\u0096', '\\u0097', '\\u0098', '\\u0099', '\\u009A', '\\u009B', '\\u009C', '\\u009D', '\\u009E', '\\u009F']; - - /***/ }), - - /***/ "../../../node_modules/graphql/language/printer.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/language/printer.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.print = print; - var _blockString = __webpack_require__(/*! ./blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); - var _printString = __webpack_require__(/*! ./printString.mjs */ "../../../node_modules/graphql/language/printString.mjs"); - var _visitor = __webpack_require__(/*! ./visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); - /** - * Converts an AST into a string, using one set of reasonable - * formatting rules. - */ - - function print(ast) { - return (0, _visitor.visit)(ast, printDocASTReducer); +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; } - const MAX_LINE_LENGTH = 80; - const printDocASTReducer = { - Name: { - leave: node => node.value - }, - Variable: { - leave: node => '$' + node.name - }, - // Document - Document: { - leave: node => join(node.definitions, '\n\n') - }, - OperationDefinition: { - leave(node) { - const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); - const prefix = join([node.operation, join([node.name, varDefs]), join(node.directives, ' ')], ' '); // Anonymous queries with no directives or variable definitions can use - // the query short form. - - return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; - } - }, - VariableDefinition: { - leave: ({ - variable, - type, - defaultValue, - directives - }) => variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')) - }, - SelectionSet: { - leave: ({ - selections - }) => block(selections) + return cooked; +} +; +var __setModuleDefault = Object.create ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v + }); +} : function (o, v) { + o["default"] = v; +}; +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { + default: mod + }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ + value: value, + dispose: dispose, + async: async + }); + } else if (async) { + env.stack.push({ + async: true + }); + } + return value; +} +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function (e) { + fail(e); + return next(); + }); + } catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); +} +var _default = exports["default"] = { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources +}; + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js": +/*!***********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/assignRef.js ***! + \***********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.assignRef = assignRef; +/** + * Assigns a value for a given ref, no matter of the ref format + * @param {RefObject} ref - a callback function or ref object + * @param value - a new value + * + * @see https://github.com/theKashey/use-callback-ref#assignref + * @example + * const refObject = useRef(); + * const refFn = (ref) => {....} + * + * assignRef(refObject, "refValue"); + * assignRef(refFn, "refValue"); + */ +function assignRef(ref, value) { + if (typeof ref === 'function') { + ref(value); + } else if (ref) { + ref.current = value; + } + return ref; +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js": +/*!***********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/createRef.js ***! + \***********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createCallbackRef = createCallbackRef; +/** + * creates a Ref object with on change callback + * @param callback + * @returns {RefObject} + * + * @see {@link useCallbackRef} + * @see https://reactjs.org/docs/refs-and-the-dom.html#creating-refs + */ +function createCallbackRef(callback) { + var current = null; + return { + get current() { + return current; }, - Field: { - leave({ - alias, - name, - arguments: args, - directives, - selectionSet - }) { - const prefix = wrap('', alias, ': ') + name; - let argsLine = prefix + wrap('(', join(args, ', '), ')'); - if (argsLine.length > MAX_LINE_LENGTH) { - argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); - } - return join([argsLine, join(directives, ' '), selectionSet], ' '); + set current(value) { + var last = current; + if (last !== value) { + current = value; + callback(value, last); } - }, - Argument: { - leave: ({ - name, - value - }) => name + ': ' + value - }, - // Fragments - FragmentSpread: { - leave: ({ - name, - directives - }) => '...' + name + wrap(' ', join(directives, ' ')) - }, - InlineFragment: { - leave: ({ - typeCondition, - directives, - selectionSet - }) => join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ') - }, - FragmentDefinition: { - leave: ({ - name, - typeCondition, - variableDefinitions, - directives, - selectionSet - } // Note: fragment variable definitions are experimental and may be changed - ) => - // or removed in the future. - `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + selectionSet - }, - // Value - IntValue: { - leave: ({ - value - }) => value - }, - FloatValue: { - leave: ({ - value - }) => value - }, - StringValue: { - leave: ({ - value, - block: isBlockString - }) => isBlockString ? (0, _blockString.printBlockString)(value) : (0, _printString.printString)(value) - }, - BooleanValue: { - leave: ({ - value - }) => value ? 'true' : 'false' - }, - NullValue: { - leave: () => 'null' - }, - EnumValue: { - leave: ({ - value - }) => value - }, - ListValue: { - leave: ({ - values - }) => '[' + join(values, ', ') + ']' - }, - ObjectValue: { - leave: ({ - fields - }) => '{' + join(fields, ', ') + '}' - }, - ObjectField: { - leave: ({ - name, - value - }) => name + ': ' + value - }, - // Directive - Directive: { - leave: ({ - name, - arguments: args - }) => '@' + name + wrap('(', join(args, ', '), ')') - }, - // Type - NamedType: { - leave: ({ - name - }) => name - }, - ListType: { - leave: ({ - type - }) => '[' + type + ']' - }, - NonNullType: { - leave: ({ - type - }) => type + '!' - }, - // Type System Definitions - SchemaDefinition: { - leave: ({ - description, - directives, - operationTypes - }) => wrap('', description, '\n') + join(['schema', join(directives, ' '), block(operationTypes)], ' ') - }, - OperationTypeDefinition: { - leave: ({ - operation, - type - }) => operation + ': ' + type - }, - ScalarTypeDefinition: { - leave: ({ - description, - name, - directives - }) => wrap('', description, '\n') + join(['scalar', name, join(directives, ' ')], ' ') - }, - ObjectTypeDefinition: { - leave: ({ - description, - name, - interfaces, - directives, - fields - }) => wrap('', description, '\n') + join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - FieldDefinition: { - leave: ({ - description, - name, - arguments: args, - type, - directives - }) => wrap('', description, '\n') + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' ')) - }, - InputValueDefinition: { - leave: ({ - description, - name, - type, - defaultValue, - directives - }) => wrap('', description, '\n') + join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ') - }, - InterfaceTypeDefinition: { - leave: ({ - description, - name, - interfaces, - directives, - fields - }) => wrap('', description, '\n') + join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - UnionTypeDefinition: { - leave: ({ - description, - name, - directives, - types - }) => wrap('', description, '\n') + join(['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') - }, - EnumTypeDefinition: { - leave: ({ - description, - name, - directives, - values - }) => wrap('', description, '\n') + join(['enum', name, join(directives, ' '), block(values)], ' ') - }, - EnumValueDefinition: { - leave: ({ - description, - name, - directives - }) => wrap('', description, '\n') + join([name, join(directives, ' ')], ' ') - }, - InputObjectTypeDefinition: { - leave: ({ - description, - name, - directives, - fields - }) => wrap('', description, '\n') + join(['input', name, join(directives, ' '), block(fields)], ' ') - }, - DirectiveDefinition: { - leave: ({ - description, - name, - arguments: args, - repeatable, - locations - }) => wrap('', description, '\n') + 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ') - }, - SchemaExtension: { - leave: ({ - directives, - operationTypes - }) => join(['extend schema', join(directives, ' '), block(operationTypes)], ' ') - }, - ScalarTypeExtension: { - leave: ({ - name, - directives - }) => join(['extend scalar', name, join(directives, ' ')], ' ') - }, - ObjectTypeExtension: { - leave: ({ - name, - interfaces, - directives, - fields - }) => join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - InterfaceTypeExtension: { - leave: ({ - name, - interfaces, - directives, - fields - }) => join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ') - }, - UnionTypeExtension: { - leave: ({ - name, - directives, - types - }) => join(['extend union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], ' ') - }, - EnumTypeExtension: { - leave: ({ - name, - directives, - values - }) => join(['extend enum', name, join(directives, ' '), block(values)], ' ') - }, - InputObjectTypeExtension: { - leave: ({ - name, - directives, - fields - }) => join(['extend input', name, join(directives, ' '), block(fields)], ' ') } }; - /** - * Given maybeArray, print an empty string if it is null or empty, otherwise - * print all items together separated by separator if provided - */ - - function join(maybeArray, separator = '') { - var _maybeArray$filter$jo; - return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(x => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : ''; - } - /** - * Given array, print each item on its own line, wrapped in an indented `{ }` block. - */ - - function block(array) { - return wrap('{\n', indent(join(array, '\n')), '\n}'); - } - /** - * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. - */ - - function wrap(start, maybeString, end = '') { - return maybeString != null && maybeString !== '' ? start + maybeString + end : ''; - } - function indent(str) { - return wrap(' ', str.replace(/\n/g, '\n ')); - } - function hasMultilineItems(maybeArray) { - var _maybeArray$some; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - return (_maybeArray$some = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some(str => str.includes('\n'))) !== null && _maybeArray$some !== void 0 ? _maybeArray$some : false; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/source.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/language/source.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.Source = void 0; - exports.isSource = isSource; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); - /** - * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are - * optional, but they are useful for clients who store GraphQL documents in source files. - * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might - * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. - * The `line` and `column` properties in `locationOffset` are 1-indexed. - */ - class Source { - constructor(body, name = 'GraphQL request', locationOffset = { - line: 1, - column: 1 - }) { - typeof body === 'string' || (0, _devAssert.devAssert)(false, `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`); - this.body = body; - this.name = name; - this.locationOffset = locationOffset; - this.locationOffset.line > 0 || (0, _devAssert.devAssert)(false, 'line in locationOffset is 1-indexed and must be positive.'); - this.locationOffset.column > 0 || (0, _devAssert.devAssert)(false, 'column in locationOffset is 1-indexed and must be positive.'); - } - get [Symbol.toStringTag]() { - return 'Source'; - } - } - /** - * Test if the given value is a Source object. - * - * @internal - */ - exports.Source = Source; - function isSource(source) { - return (0, _instanceOf.instanceOf)(source, Source); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/language/tokenKind.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/language/tokenKind.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.TokenKind = void 0; - /** - * An exported enum describing the different kinds of tokens that the - * lexer emits. - */ - var TokenKind; - (function (TokenKind) { - TokenKind['SOF'] = ''; - TokenKind['EOF'] = ''; - TokenKind['BANG'] = '!'; - TokenKind['DOLLAR'] = '$'; - TokenKind['AMP'] = '&'; - TokenKind['PAREN_L'] = '('; - TokenKind['PAREN_R'] = ')'; - TokenKind['SPREAD'] = '...'; - TokenKind['COLON'] = ':'; - TokenKind['EQUALS'] = '='; - TokenKind['AT'] = '@'; - TokenKind['BRACKET_L'] = '['; - TokenKind['BRACKET_R'] = ']'; - TokenKind['BRACE_L'] = '{'; - TokenKind['PIPE'] = '|'; - TokenKind['BRACE_R'] = '}'; - TokenKind['NAME'] = 'Name'; - TokenKind['INT'] = 'Int'; - TokenKind['FLOAT'] = 'Float'; - TokenKind['STRING'] = 'String'; - TokenKind['BLOCK_STRING'] = 'BlockString'; - TokenKind['COMMENT'] = 'Comment'; - })(TokenKind || (exports.TokenKind = TokenKind = {})); - - /** - * The enum type representing the token kinds values. - * - * @deprecated Please use `TokenKind`. Will be remove in v17. - */ - - /***/ }), - - /***/ "../../../node_modules/graphql/language/visitor.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/language/visitor.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.BREAK = void 0; - exports.getEnterLeaveForKind = getEnterLeaveForKind; - exports.getVisitFn = getVisitFn; - exports.visit = visit; - exports.visitInParallel = visitInParallel; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _ast = __webpack_require__(/*! ./ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _kinds = __webpack_require__(/*! ./kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - /** - * A visitor is provided to visit, it contains the collection of - * relevant functions to be called during the visitor's traversal. - */ - - const BREAK = exports.BREAK = Object.freeze({}); - /** - * visit() will walk through an AST using a depth-first traversal, calling - * the visitor's enter function at each node in the traversal, and calling the - * leave function after visiting that node and all of its child nodes. - * - * By returning different values from the enter and leave functions, the - * behavior of the visitor can be altered, including skipping over a sub-tree of - * the AST (by returning false), editing the AST by returning a value or null - * to remove the value, or to stop the whole traversal by returning BREAK. - * - * When using visit() to edit an AST, the original AST will not be modified, and - * a new version of the AST with the changes applied will be returned from the - * visit function. - * - * ```ts - * const editedAST = visit(ast, { - * enter(node, key, parent, path, ancestors) { - * // @return - * // undefined: no action - * // false: skip visiting this node - * // visitor.BREAK: stop visiting altogether - * // null: delete this node - * // any value: replace this node with the returned value - * }, - * leave(node, key, parent, path, ancestors) { - * // @return - * // undefined: no action - * // false: no action - * // visitor.BREAK: stop visiting altogether - * // null: delete this node - * // any value: replace this node with the returned value - * } - * }); - * ``` - * - * Alternatively to providing enter() and leave() functions, a visitor can - * instead provide functions named the same as the kinds of AST nodes, or - * enter/leave visitors at a named key, leading to three permutations of the - * visitor API: - * - * 1) Named visitors triggered when entering a node of a specific kind. - * - * ```ts - * visit(ast, { - * Kind(node) { - * // enter the "Kind" node - * } - * }) - * ``` - * - * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. - * - * ```ts - * visit(ast, { - * Kind: { - * enter(node) { - * // enter the "Kind" node - * } - * leave(node) { - * // leave the "Kind" node - * } - * } - * }) - * ``` - * - * 3) Generic visitors that trigger upon entering and leaving any node. - * - * ```ts - * visit(ast, { - * enter(node) { - * // enter any node - * }, - * leave(node) { - * // leave any node - * } - * }) - * ``` - */ - - function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { - const enterLeaveMap = new Map(); - for (const kind of Object.values(_kinds.Kind)) { - enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/index.js": +/*!*******************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/index.js ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "assignRef", ({ + enumerable: true, + get: function () { + return _assignRef.assignRef; + } +})); +Object.defineProperty(exports, "createCallbackRef", ({ + enumerable: true, + get: function () { + return _createRef.createCallbackRef; + } +})); +Object.defineProperty(exports, "mergeRefs", ({ + enumerable: true, + get: function () { + return _mergeRef.mergeRefs; + } +})); +Object.defineProperty(exports, "refToCallback", ({ + enumerable: true, + get: function () { + return _refToCallback.refToCallback; + } +})); +Object.defineProperty(exports, "transformRef", ({ + enumerable: true, + get: function () { + return _transformRef.transformRef; + } +})); +Object.defineProperty(exports, "useCallbackRef", ({ + enumerable: true, + get: function () { + return _useRef.useCallbackRef; + } +})); +Object.defineProperty(exports, "useMergeRefs", ({ + enumerable: true, + get: function () { + return _useMergeRef.useMergeRefs; + } +})); +Object.defineProperty(exports, "useRefToCallback", ({ + enumerable: true, + get: function () { + return _refToCallback.useRefToCallback; + } +})); +Object.defineProperty(exports, "useTransformRef", ({ + enumerable: true, + get: function () { + return _useTransformRef.useTransformRef; + } +})); +var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); +var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); +var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); +var _mergeRef = __webpack_require__(/*! ./mergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js"); +var _useMergeRef = __webpack_require__(/*! ./useMergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js"); +var _useTransformRef = __webpack_require__(/*! ./useTransformRef */ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js"); +var _transformRef = __webpack_require__(/*! ./transformRef */ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js"); +var _refToCallback = __webpack_require__(/*! ./refToCallback */ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js"); + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js": +/*!**********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.mergeRefs = mergeRefs; +var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); +var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); +/** + * Merges two or more refs together providing a single interface to set their value + * @param {RefObject|Ref} refs + * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} + * + * @see {@link useMergeRefs} to be used in ReactComponents + * @example + * const Component = React.forwardRef((props, ref) => { + * const ownRef = useRef(); + * const domRef = mergeRefs([ref, ownRef]); // 👈 merge together + * return
    ...
    + * } + */ +function mergeRefs(refs) { + return (0, _createRef.createCallbackRef)(function (newValue) { + return refs.forEach(function (ref) { + return (0, _assignRef.assignRef)(ref, newValue); + }); + }); +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js": +/*!***************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js ***! + \***************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.refToCallback = refToCallback; +exports.useRefToCallback = useRefToCallback; +/** + * Unmemoized version of {@link useRefToCallback} + * @see {@link useRefToCallback} + * @param ref + */ +function refToCallback(ref) { + return function (newValue) { + if (typeof ref === 'function') { + ref(newValue); + } else if (ref) { + ref.current = newValue; } - /* eslint-disable no-undef-init */ - - let stack = undefined; - let inArray = Array.isArray(root); - let keys = [root]; - let index = -1; - let edits = []; - let node = root; - let key = undefined; - let parent = undefined; - const path = []; - const ancestors = []; - /* eslint-enable no-undef-init */ - - do { - index++; - const isLeaving = index === keys.length; - const isEdited = isLeaving && edits.length !== 0; - if (isLeaving) { - key = ancestors.length === 0 ? undefined : path[path.length - 1]; - node = parent; - parent = ancestors.pop(); - if (isEdited) { - if (inArray) { - node = node.slice(); - let editOffset = 0; - for (const [editKey, editValue] of edits) { - const arrayKey = editKey - editOffset; - if (editValue === null) { - node.splice(arrayKey, 1); - editOffset++; - } else { - node[arrayKey] = editValue; - } - } - } else { - node = Object.defineProperties({}, Object.getOwnPropertyDescriptors(node)); - for (const [editKey, editValue] of edits) { - node[editKey] = editValue; - } + }; +} +var nullCallback = function () { + return null; +}; +// lets maintain a weak ref to, well, ref :) +// not using `kashe` to keep this package small +var weakMem = new WeakMap(); +var weakMemoize = function (ref) { + var usedRef = ref || nullCallback; + var storedRef = weakMem.get(usedRef); + if (storedRef) { + return storedRef; + } + var cb = refToCallback(usedRef); + weakMem.set(usedRef, cb); + return cb; +}; +/** + * Transforms a given `ref` into `callback`. + * + * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)} + * + * @param {ReactRef} ref + * @returns {Function} + * + * @see https://github.com/theKashey/use-callback-ref#reftocallback + * + * @example + * const ref = useRef(0); + * const setRef = useRefToCallback(ref); + * 👉 setRef(10); + * ✅ ref.current === 10 + */ +function useRefToCallback(ref) { + return weakMemoize(ref); +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js": +/*!**************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/transformRef.js ***! + \**************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.transformRef = transformRef; +var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); +var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); +/** + * Transforms one ref to another + * @example + * ```tsx + * const ResizableWithRef = forwardRef((props, ref) => + * i ? i.resizable : null)}/> + * ); + * ``` + */ +function transformRef(ref, transformer) { + return (0, _createRef.createCallbackRef)(function (value) { + return (0, _assignRef.assignRef)(ref, transformer(value)); + }); +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js": +/*!*************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js ***! + \*************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.useMergeRefs = useMergeRefs; +var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); +var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); +/** + * Merges two or more refs together providing a single interface to set their value + * @param {RefObject|Ref} refs + * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} + * + * @see {@link mergeRefs} a version without buit-in memoization + * @see https://github.com/theKashey/use-callback-ref#usemergerefs + * @example + * const Component = React.forwardRef((props, ref) => { + * const ownRef = useRef(); + * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together + * return
    ...
    + * } + */ +function useMergeRefs(refs, defaultValue) { + return (0, _useRef.useCallbackRef)(defaultValue || null, function (newValue) { + return refs.forEach(function (ref) { + return (0, _assignRef.assignRef)(ref, newValue); + }); + }); +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js": +/*!********************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/useRef.js ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.useCallbackRef = useCallbackRef; +var _react = __webpack_require__(/*! react */ "react"); +/** + * creates a MutableRef with ref change callback + * @param initialValue - initial ref value + * @param {Function} callback - a callback to run when value changes + * + * @example + * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue); + * ref.current = 1; + * // prints 0 -> 1 + * + * @see https://reactjs.org/docs/hooks-reference.html#useref + * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref + * @returns {MutableRefObject} + */ +function useCallbackRef(initialValue, callback) { + var ref = (0, _react.useState)(function () { + return { + // value + value: initialValue, + // last callback + callback: callback, + // "memoized" public interface + facade: { + get current() { + return ref.value; + }, + set current(value) { + var last = ref.value; + if (last !== value) { + ref.value = value; + ref.callback(value, last); } } - index = stack.index; - keys = stack.keys; - edits = stack.edits; - inArray = stack.inArray; - stack = stack.prev; - } else if (parent) { - key = inArray ? index : keys[index]; - node = parent[key]; - if (node === null || node === undefined) { - continue; - } - path.push(key); } - let result; - if (!Array.isArray(node)) { - var _enterLeaveMap$get, _enterLeaveMap$get2; - (0, _ast.isNode)(node) || (0, _devAssert.devAssert)(false, `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`); - const visitFn = isLeaving ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get === void 0 ? void 0 : _enterLeaveMap$get.leave : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get2 === void 0 ? void 0 : _enterLeaveMap$get2.enter; - result = visitFn === null || visitFn === void 0 ? void 0 : visitFn.call(visitor, node, key, parent, path, ancestors); - if (result === BREAK) { - break; - } - if (result === false) { - if (!isLeaving) { - path.pop(); - continue; - } - } else if (result !== undefined) { - edits.push([key, result]); - if (!isLeaving) { - if ((0, _ast.isNode)(result)) { - node = result; - } else { - path.pop(); - continue; - } + }; + })[0]; + // update callback + ref.callback = callback; + return ref.facade; +} + +/***/ }), + +/***/ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js": +/*!*****************************************************************************!*\ + !*** ../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js ***! + \*****************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.useTransformRef = useTransformRef; +var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); +var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); +/** + * Create a _lense_ on Ref, making it possible to transform ref value + * @param {ReactRef} ref + * @param {Function} transformer. 👉 Ref would be __NOT updated__ on `transformer` update. + * @returns {RefObject} + * + * @see https://github.com/theKashey/use-callback-ref#usetransformref-to-replace-reactuseimperativehandle + * @example + * + * const ResizableWithRef = forwardRef((props, ref) => + * i ? i.resizable : null)}/> + * ); + */ +function useTransformRef(ref, transformer) { + return (0, _useRef.useCallbackRef)(null, function (value) { + return (0, _assignRef.assignRef)(ref, transformer(value)); + }); +} + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/config.js": +/*!***************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/config.js ***! + \***************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.setConfig = exports.config = void 0; +var config = exports.config = { + onError: function (e) { + return console.error(e); + } +}; +var setConfig = function (conf) { + Object.assign(config, conf); +}; +exports.setConfig = setConfig; + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/env.js": +/*!************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/env.js ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.env = void 0; +var _detectNodeEs = __webpack_require__(/*! detect-node-es */ "../../../node_modules/detect-node-es/esm/browser.js"); +var env = exports.env = { + isNode: _detectNodeEs.isNode, + forceCache: false +}; + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/exports.js": +/*!****************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/exports.js ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.exportSidecar = exportSidecar; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +var SideCar = function (_a) { + var sideCar = _a.sideCar, + rest = (0, _tslib.__rest)(_a, ["sideCar"]); + if (!sideCar) { + throw new Error('Sidecar: please provide `sideCar` property to import the right car'); + } + var Target = sideCar.read(); + if (!Target) { + throw new Error('Sidecar medium not found'); + } + return /*#__PURE__*/React.createElement(Target, (0, _tslib.__assign)({}, rest)); +}; +SideCar.isSideCarExport = true; +function exportSidecar(medium, exported) { + medium.useMedium(exported); + return SideCar; +} + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/hoc.js": +/*!************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/hoc.js ***! + \************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.sidecar = sidecar; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +// eslint-disable-next-line @typescript-eslint/ban-types +function sidecar(importer, errorComponent) { + var ErrorCase = function () { + return errorComponent; + }; + return function Sidecar(props) { + var _a = (0, _hook.useSidecar)(importer, props.sideCar), + Car = _a[0], + error = _a[1]; + if (error && errorComponent) { + return ErrorCase; + } + // @ts-expect-error type shenanigans + return Car ? /*#__PURE__*/React.createElement(Car, (0, _tslib.__assign)({}, props)) : null; + }; +} + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/hook.js": +/*!*************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/hook.js ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.useSidecar = useSidecar; +var _react = __webpack_require__(/*! react */ "react"); +var _env = __webpack_require__(/*! ./env */ "../../../node_modules/use-sidecar/dist/es2015/env.js"); +var cache = new WeakMap(); +var NO_OPTIONS = {}; +function useSidecar(importer, effect) { + var options = effect && effect.options || NO_OPTIONS; + if (_env.env.isNode && !options.ssr) { + return [null, null]; + } + // eslint-disable-next-line react-hooks/rules-of-hooks + return useRealSidecar(importer, effect); +} +function useRealSidecar(importer, effect) { + var options = effect && effect.options || NO_OPTIONS; + var couldUseCache = _env.env.forceCache || _env.env.isNode && !!options.ssr || !options.async; + var _a = (0, _react.useState)(couldUseCache ? function () { + return cache.get(importer); + } : undefined), + Car = _a[0], + setCar = _a[1]; + var _b = (0, _react.useState)(null), + error = _b[0], + setError = _b[1]; + (0, _react.useEffect)(function () { + if (!Car) { + importer().then(function (car) { + var resolved = effect ? effect.read() : car.default || car; + if (!resolved) { + console.error('Sidecar error: with importer', importer); + var error_1; + if (effect) { + console.error('Sidecar error: with medium', effect); + error_1 = new Error('Sidecar medium was not found'); + } else { + error_1 = new Error('Sidecar was not found in exports'); } + setError(function () { + return error_1; + }); + throw error_1; } - } - if (result === undefined && isEdited) { - edits.push([key, node]); - } - if (isLeaving) { - path.pop(); - } else { - var _node$kind; - stack = { - inArray, - index, - keys, - edits, - prev: stack - }; - inArray = Array.isArray(node); - keys = inArray ? node : (_node$kind = visitorKeys[node.kind]) !== null && _node$kind !== void 0 ? _node$kind : []; - index = -1; - edits = []; - if (parent) { - ancestors.push(parent); + cache.set(importer, resolved); + setCar(function () { + return resolved; + }); + }, function (e) { + return setError(function () { + return e; + }); + }); + } + }, []); + return [Car, error]; +} + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/index.js": +/*!**************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/index.js ***! + \**************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "createMedium", ({ + enumerable: true, + get: function () { + return _medium.createMedium; + } +})); +Object.defineProperty(exports, "createSidecarMedium", ({ + enumerable: true, + get: function () { + return _medium.createSidecarMedium; + } +})); +Object.defineProperty(exports, "exportSidecar", ({ + enumerable: true, + get: function () { + return _exports.exportSidecar; + } +})); +Object.defineProperty(exports, "renderCar", ({ + enumerable: true, + get: function () { + return _renderProp.renderCar; + } +})); +Object.defineProperty(exports, "setConfig", ({ + enumerable: true, + get: function () { + return _config.setConfig; + } +})); +Object.defineProperty(exports, "sidecar", ({ + enumerable: true, + get: function () { + return _hoc.sidecar; + } +})); +Object.defineProperty(exports, "useSidecar", ({ + enumerable: true, + get: function () { + return _hook.useSidecar; + } +})); +var _hoc = __webpack_require__(/*! ./hoc */ "../../../node_modules/use-sidecar/dist/es2015/hoc.js"); +var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); +var _config = __webpack_require__(/*! ./config */ "../../../node_modules/use-sidecar/dist/es2015/config.js"); +var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/use-sidecar/dist/es2015/medium.js"); +var _renderProp = __webpack_require__(/*! ./renderProp */ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js"); +var _exports = __webpack_require__(/*! ./exports */ "../../../node_modules/use-sidecar/dist/es2015/exports.js"); + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/medium.js": +/*!***************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/medium.js ***! + \***************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createMedium = createMedium; +exports.createSidecarMedium = createSidecarMedium; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +function ItoI(a) { + return a; +} +function innerCreateMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + var buffer = []; + var assigned = false; + var medium = { + read: function () { + if (assigned) { + throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.'); + } + if (buffer.length) { + return buffer[buffer.length - 1]; + } + return defaults; + }, + useMedium: function (data) { + var item = middleware(data, assigned); + buffer.push(item); + return function () { + buffer = buffer.filter(function (x) { + return x !== item; + }); + }; + }, + assignSyncMedium: function (cb) { + assigned = true; + while (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + } + buffer = { + push: function (x) { + return cb(x); + }, + filter: function () { + return buffer; + } + }; + }, + assignMedium: function (cb) { + assigned = true; + var pendingQueue = []; + if (buffer.length) { + var cbs = buffer; + buffer = []; + cbs.forEach(cb); + pendingQueue = buffer; + } + var executeQueue = function () { + var cbs = pendingQueue; + pendingQueue = []; + cbs.forEach(cb); + }; + var cycle = function () { + return Promise.resolve().then(executeQueue); + }; + cycle(); + buffer = { + push: function (x) { + pendingQueue.push(x); + cycle(); + }, + filter: function (filter) { + pendingQueue = pendingQueue.filter(filter); + return buffer; } - parent = node; + }; + } + }; + return medium; +} +function createMedium(defaults, middleware) { + if (middleware === void 0) { + middleware = ItoI; + } + return innerCreateMedium(defaults, middleware); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function createSidecarMedium(options) { + if (options === void 0) { + options = {}; + } + var medium = innerCreateMedium(null); + medium.options = (0, _tslib.__assign)({ + async: true, + ssr: false + }, options); + return medium; +} + +/***/ }), + +/***/ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js": +/*!*******************************************************************!*\ + !*** ../../../node_modules/use-sidecar/dist/es2015/renderProp.js ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.renderCar = renderCar; +var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); +var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var React = _react; +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function renderCar(WrappedComponent, defaults) { + function State(_a) { + var stateRef = _a.stateRef, + props = _a.props; + var renderTarget = (0, _react.useCallback)(function SideTarget() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - } while (stack !== undefined); - if (edits.length !== 0) { - // New root - return edits[edits.length - 1][1]; + (0, _react.useLayoutEffect)(function () { + stateRef.current(args); + }); + return null; + }, []); + // @ts-ignore + return /*#__PURE__*/React.createElement(WrappedComponent, (0, _tslib.__assign)({}, props, { + children: renderTarget + })); + } + var Children = /*#__PURE__*/React.memo(function (_a) { + var stateRef = _a.stateRef, + defaultState = _a.defaultState, + children = _a.children; + var _b = (0, _react.useState)(defaultState.current), + state = _b[0], + setState = _b[1]; + (0, _react.useEffect)(function () { + stateRef.current = setState; + }, []); + return children.apply(void 0, state); + }, function () { + return true; + }); + return function Combiner(props) { + var defaultState = React.useRef(defaults(props)); + var ref = React.useRef(function (state) { + return defaultState.current = state; + }); + return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(State, { + stateRef: ref, + props: props + }), /*#__PURE__*/React.createElement(Children, { + stateRef: ref, + defaultState: defaultState, + children: props.children + })); + }; +} + +/***/ }), + +/***/ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js": +/*!*************************************************************************!*\ + !*** ../../../node_modules/vscode-languageserver-types/lib/esm/main.js ***! + \*************************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.uinteger = exports.integer = exports.WorkspaceSymbol = exports.WorkspaceFolder = exports.WorkspaceEdit = exports.WorkspaceChange = exports.VersionedTextDocumentIdentifier = exports.URI = exports.TextEdit = exports.TextDocumentItem = exports.TextDocumentIdentifier = exports.TextDocumentEdit = exports.TextDocument = exports.SymbolTag = exports.SymbolKind = exports.SymbolInformation = exports.SignatureInformation = exports.SemanticTokens = exports.SemanticTokenTypes = exports.SemanticTokenModifiers = exports.SelectionRange = exports.RenameFile = exports.Range = exports.Position = exports.ParameterInformation = exports.OptionalVersionedTextDocumentIdentifier = exports.MarkupKind = exports.MarkupContent = exports.MarkedString = exports.LocationLink = exports.Location = exports.InsertTextMode = exports.InsertTextFormat = exports.InsertReplaceEdit = exports.InlineValueVariableLookup = exports.InlineValueText = exports.InlineValueEvaluatableExpression = exports.InlineValueContext = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlayHint = exports.Hover = exports.FormattingOptions = exports.FoldingRangeKind = exports.FoldingRange = exports.EOL = exports.DocumentUri = exports.DocumentSymbol = exports.DocumentLink = exports.DocumentHighlightKind = exports.DocumentHighlight = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.Diagnostic = exports.DeleteFile = exports.CreateFile = exports.CompletionList = exports.CompletionItemTag = exports.CompletionItemLabelDetails = exports.CompletionItemKind = exports.CompletionItem = exports.Command = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.CodeLens = exports.CodeDescription = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.CodeActionContext = exports.CodeAction = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.AnnotatedTextEdit = void 0; +var DocumentUri; +(function (DocumentUri) { + function is(value) { + return typeof value === 'string'; + } + DocumentUri.is = is; +})(DocumentUri || (exports.DocumentUri = DocumentUri = {})); +var URI; +(function (URI) { + function is(value) { + return typeof value === 'string'; + } + URI.is = is; +})(URI || (exports.URI = URI = {})); +var integer; +(function (integer) { + integer.MIN_VALUE = -2147483648; + integer.MAX_VALUE = 2147483647; + function is(value) { + return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE; + } + integer.is = is; +})(integer || (exports.integer = integer = {})); +var uinteger; +(function (uinteger) { + uinteger.MIN_VALUE = 0; + uinteger.MAX_VALUE = 2147483647; + function is(value) { + return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE; + } + uinteger.is = is; +})(uinteger || (exports.uinteger = uinteger = {})); +/** + * The Position namespace provides helper functions to work with + * {@link Position} literals. + */ +var Position; +(function (Position) { + /** + * Creates a new Position literal from the given line and character. + * @param line The position's line. + * @param character The position's character. + */ + function create(line, character) { + if (line === Number.MAX_VALUE) { + line = uinteger.MAX_VALUE; + } + if (character === Number.MAX_VALUE) { + character = uinteger.MAX_VALUE; } - return root; + return { + line: line, + character: character + }; } + Position.create = create; /** - * Creates a new visitor instance which delegates to many visitors to run in - * parallel. Each visitor will be visited for each node before moving on. - * - * If a prior visitor edits a node, no following visitors will see that node. + * Checks whether the given literal conforms to the {@link Position} interface. */ - - function visitInParallel(visitors) { - const skipping = new Array(visitors.length).fill(null); - const mergedVisitor = Object.create(null); - for (const kind of Object.values(_kinds.Kind)) { - let hasVisitor = false; - const enterList = new Array(visitors.length).fill(undefined); - const leaveList = new Array(visitors.length).fill(undefined); - for (let i = 0; i < visitors.length; ++i) { - const { - enter, - leave - } = getEnterLeaveForKind(visitors[i], kind); - hasVisitor || (hasVisitor = enter != null || leave != null); - enterList[i] = enter; - leaveList[i] = leave; - } - if (!hasVisitor) { - continue; - } - const mergedEnterLeave = { - enter(...args) { - const node = args[0]; - for (let i = 0; i < visitors.length; i++) { - if (skipping[i] === null) { - var _enterList$i; - const result = (_enterList$i = enterList[i]) === null || _enterList$i === void 0 ? void 0 : _enterList$i.apply(visitors[i], args); - if (result === false) { - skipping[i] = node; - } else if (result === BREAK) { - skipping[i] = BREAK; - } else if (result !== undefined) { - return result; - } - } - } - }, - leave(...args) { - const node = args[0]; - for (let i = 0; i < visitors.length; i++) { - if (skipping[i] === null) { - var _leaveList$i; - const result = (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 ? void 0 : _leaveList$i.apply(visitors[i], args); - if (result === BREAK) { - skipping[i] = BREAK; - } else if (result !== undefined && result !== false) { - return result; - } - } else if (skipping[i] === node) { - skipping[i] = null; - } - } - } + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); + } + Position.is = is; +})(Position || (exports.Position = Position = {})); +/** + * The Range namespace provides helper functions to work with + * {@link Range} literals. + */ +var Range; +(function (Range) { + function create(one, two, three, four) { + if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { + return { + start: Position.create(one, two), + end: Position.create(three, four) + }; + } else if (Position.is(one) && Position.is(two)) { + return { + start: one, + end: two }; - mergedVisitor[kind] = mergedEnterLeave; + } else { + throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]")); } - return mergedVisitor; } + Range.create = create; /** - * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + * Checks whether the given literal conforms to the {@link Range} interface. */ - - function getEnterLeaveForKind(visitor, kind) { - const kindVisitor = visitor[kind]; - if (typeof kindVisitor === 'object') { - // { Kind: { enter() {}, leave() {} } } - return kindVisitor; - } else if (typeof kindVisitor === 'function') { - // { Kind() {} } - return { - enter: kindVisitor, - leave: undefined - }; - } // { enter() {}, leave() {} } - + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); + } + Range.is = is; +})(Range || (exports.Range = Range = {})); +/** + * The Location namespace provides helper functions to work with + * {@link Location} literals. + */ +var Location; +(function (Location) { + /** + * Creates a Location literal. + * @param uri The location's uri. + * @param range The location's range. + */ + function create(uri, range) { return { - enter: visitor.enter, - leave: visitor.leave + uri: uri, + range: range }; } + Location.create = create; /** - * Given a visitor instance, if it is leaving or not, and a node kind, return - * the function the visitor runtime should call. - * - * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + * Checks whether the given literal conforms to the {@link Location} interface. */ - - /* c8 ignore next 8 */ - - function getVisitFn(visitor, kind, isLeaving) { - const { - enter, - leave - } = getEnterLeaveForKind(visitor, kind); - return isLeaving ? leave : enter; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/assertName.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/type/assertName.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.assertEnumValueName = assertEnumValueName; - exports.assertName = assertName; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _characterClasses = __webpack_require__(/*! ../language/characterClasses.mjs */ "../../../node_modules/graphql/language/characterClasses.mjs"); + Location.is = is; +})(Location || (exports.Location = Location = {})); +/** + * The LocationLink namespace provides helper functions to work with + * {@link LocationLink} literals. + */ +var LocationLink; +(function (LocationLink) { /** - * Upholds the spec rules about naming. + * Creates a LocationLink literal. + * @param targetUri The definition's uri. + * @param targetRange The full range of the definition. + * @param targetSelectionRange The span of the symbol definition at the target. + * @param originSelectionRange The span of the symbol being defined in the originating source file. */ - - function assertName(name) { - name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); - typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); - if (name.length === 0) { - throw new _GraphQLError.GraphQLError('Expected name to be a non-empty string.'); - } - for (let i = 1; i < name.length; ++i) { - if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { - throw new _GraphQLError.GraphQLError(`Names must only contain [_a-zA-Z0-9] but "${name}" does not.`); - } - } - if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { - throw new _GraphQLError.GraphQLError(`Names must start with [_a-zA-Z] but "${name}" does not.`); - } - return name; + function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { + return { + targetUri: targetUri, + targetRange: targetRange, + targetSelectionRange: targetSelectionRange, + originSelectionRange: originSelectionRange + }; } + LocationLink.create = create; /** - * Upholds the spec rules about naming enum values. - * - * @internal + * Checks whether the given literal conforms to the {@link LocationLink} interface. */ - - function assertEnumValueName(name) { - if (name === 'true' || name === 'false' || name === 'null') { - throw new _GraphQLError.GraphQLError(`Enum values cannot be named: ${name}`); - } - return assertName(name); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/definition.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/type/definition.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.GraphQLUnionType = exports.GraphQLScalarType = exports.GraphQLObjectType = exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInterfaceType = exports.GraphQLInputObjectType = exports.GraphQLEnumType = void 0; - exports.argsToArgsConfig = argsToArgsConfig; - exports.assertAbstractType = assertAbstractType; - exports.assertCompositeType = assertCompositeType; - exports.assertEnumType = assertEnumType; - exports.assertInputObjectType = assertInputObjectType; - exports.assertInputType = assertInputType; - exports.assertInterfaceType = assertInterfaceType; - exports.assertLeafType = assertLeafType; - exports.assertListType = assertListType; - exports.assertNamedType = assertNamedType; - exports.assertNonNullType = assertNonNullType; - exports.assertNullableType = assertNullableType; - exports.assertObjectType = assertObjectType; - exports.assertOutputType = assertOutputType; - exports.assertScalarType = assertScalarType; - exports.assertType = assertType; - exports.assertUnionType = assertUnionType; - exports.assertWrappingType = assertWrappingType; - exports.defineArguments = defineArguments; - exports.getNamedType = getNamedType; - exports.getNullableType = getNullableType; - exports.isAbstractType = isAbstractType; - exports.isCompositeType = isCompositeType; - exports.isEnumType = isEnumType; - exports.isInputObjectType = isInputObjectType; - exports.isInputType = isInputType; - exports.isInterfaceType = isInterfaceType; - exports.isLeafType = isLeafType; - exports.isListType = isListType; - exports.isNamedType = isNamedType; - exports.isNonNullType = isNonNullType; - exports.isNullableType = isNullableType; - exports.isObjectType = isObjectType; - exports.isOutputType = isOutputType; - exports.isRequiredArgument = isRequiredArgument; - exports.isRequiredInputField = isRequiredInputField; - exports.isScalarType = isScalarType; - exports.isType = isType; - exports.isUnionType = isUnionType; - exports.isWrappingType = isWrappingType; - exports.resolveObjMapThunk = resolveObjMapThunk; - exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _identityFunc = __webpack_require__(/*! ../jsutils/identityFunc.mjs */ "../../../node_modules/graphql/jsutils/identityFunc.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); - var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); - var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _valueFromASTUntyped = __webpack_require__(/*! ../utilities/valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); - var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); - function isType(type) { - return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); - } - function assertType(type) { - if (!isType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`); - } - return type; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); } + LocationLink.is = is; +})(LocationLink || (exports.LocationLink = LocationLink = {})); +/** + * The Color namespace provides helper functions to work with + * {@link Color} literals. + */ +var Color; +(function (Color) { /** - * There are predicates for each kind of GraphQL type. + * Creates a new Color literal. */ - - function isScalarType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); - } - function assertScalarType(type) { - if (!isScalarType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`); - } - return type; - } - function isObjectType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); - } - function assertObjectType(type) { - if (!isObjectType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`); - } - return type; + function create(red, green, blue, alpha) { + return { + red: red, + green: green, + blue: blue, + alpha: alpha + }; } - function isInterfaceType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); + Color.create = create; + /** + * Checks whether the given literal conforms to the {@link Color} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); } - function assertInterfaceType(type) { - if (!isInterfaceType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`); - } - return type; + Color.is = is; +})(Color || (exports.Color = Color = {})); +/** + * The ColorInformation namespace provides helper functions to work with + * {@link ColorInformation} literals. + */ +var ColorInformation; +(function (ColorInformation) { + /** + * Creates a new ColorInformation literal. + */ + function create(range, color) { + return { + range: range, + color: color + }; } - function isUnionType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); + ColorInformation.create = create; + /** + * Checks whether the given literal conforms to the {@link ColorInformation} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color); } - function assertUnionType(type) { - if (!isUnionType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`); - } - return type; + ColorInformation.is = is; +})(ColorInformation || (exports.ColorInformation = ColorInformation = {})); +/** + * The Color namespace provides helper functions to work with + * {@link ColorPresentation} literals. + */ +var ColorPresentation; +(function (ColorPresentation) { + /** + * Creates a new ColorInformation literal. + */ + function create(label, textEdit, additionalTextEdits) { + return { + label: label, + textEdit: textEdit, + additionalTextEdits: additionalTextEdits + }; } - function isEnumType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); + ColorPresentation.create = create; + /** + * Checks whether the given literal conforms to the {@link ColorInformation} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); } - function assertEnumType(type) { - if (!isEnumType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`); + ColorPresentation.is = is; +})(ColorPresentation || (exports.ColorPresentation = ColorPresentation = {})); +/** + * A set of predefined range kinds. + */ +var FoldingRangeKind; +(function (FoldingRangeKind) { + /** + * Folding range for a comment + */ + FoldingRangeKind.Comment = 'comment'; + /** + * Folding range for an import or include + */ + FoldingRangeKind.Imports = 'imports'; + /** + * Folding range for a region (e.g. `#region`) + */ + FoldingRangeKind.Region = 'region'; +})(FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {})); +/** + * The folding range namespace provides helper functions to work with + * {@link FoldingRange} literals. + */ +var FoldingRange; +(function (FoldingRange) { + /** + * Creates a new FoldingRange literal. + */ + function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) { + var result = { + startLine: startLine, + endLine: endLine + }; + if (Is.defined(startCharacter)) { + result.startCharacter = startCharacter; } - return type; - } - function isInputObjectType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); - } - function assertInputObjectType(type) { - if (!isInputObjectType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Input Object type.`); + if (Is.defined(endCharacter)) { + result.endCharacter = endCharacter; } - return type; - } - function isListType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLList); - } - function assertListType(type) { - if (!isListType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`); + if (Is.defined(kind)) { + result.kind = kind; } - return type; - } - function isNonNullType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); - } - function assertNonNullType(type) { - if (!isNonNullType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`); + if (Is.defined(collapsedText)) { + result.collapsedText = collapsedText; } - return type; + return result; } + FoldingRange.create = create; /** - * These types may be used as input types for arguments and directives. + * Checks whether the given literal conforms to the {@link FoldingRange} interface. */ - - function isInputType(type) { - return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); - } - function assertInputType(type) { - if (!isInputType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`); - } - return type; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); } + FoldingRange.is = is; +})(FoldingRange || (exports.FoldingRange = FoldingRange = {})); +/** + * The DiagnosticRelatedInformation namespace provides helper functions to work with + * {@link DiagnosticRelatedInformation} literals. + */ +var DiagnosticRelatedInformation; +(function (DiagnosticRelatedInformation) { /** - * These types may be used as output types as the result of fields. + * Creates a new DiagnosticRelatedInformation literal. */ - - function isOutputType(type) { - return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); - } - function assertOutputType(type) { - if (!isOutputType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`); - } - return type; + function create(location, message) { + return { + location: location, + message: message + }; } + DiagnosticRelatedInformation.create = create; /** - * These types may describe types which may be leaf values. + * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. */ - - function isLeafType(type) { - return isScalarType(type) || isEnumType(type); - } - function assertLeafType(type) { - if (!isLeafType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`); - } - return type; + function is(value) { + var candidate = value; + return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); } + DiagnosticRelatedInformation.is = is; +})(DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {})); +/** + * The diagnostic's severity. + */ +var DiagnosticSeverity; +(function (DiagnosticSeverity) { /** - * These types may describe the parent context of a selection set. + * Reports an error. */ - - function isCompositeType(type) { - return isObjectType(type) || isInterfaceType(type) || isUnionType(type); - } - function assertCompositeType(type) { - if (!isCompositeType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`); - } - return type; - } + DiagnosticSeverity.Error = 1; /** - * These types may describe the parent context of a selection set. + * Reports a warning. */ - - function isAbstractType(type) { - return isInterfaceType(type) || isUnionType(type); - } - function assertAbstractType(type) { - if (!isAbstractType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`); - } - return type; - } + DiagnosticSeverity.Warning = 2; /** - * List Type Wrapper - * - * A list is a wrapping type which points to another type. - * Lists are often created within the context of defining the fields of - * an object type. + * Reports an information. + */ + DiagnosticSeverity.Information = 3; + /** + * Reports a hint. + */ + DiagnosticSeverity.Hint = 4; +})(DiagnosticSeverity || (exports.DiagnosticSeverity = DiagnosticSeverity = {})); +/** + * The diagnostic tags. + * + * @since 3.15.0 + */ +var DiagnosticTag; +(function (DiagnosticTag) { + /** + * Unused or unnecessary code. * - * Example: + * Clients are allowed to render diagnostics with this tag faded out instead of having + * an error squiggle. + */ + DiagnosticTag.Unnecessary = 1; + /** + * Deprecated or obsolete code. * - * ```ts - * const PersonType = new GraphQLObjectType({ - * name: 'Person', - * fields: () => ({ - * parents: { type: new GraphQLList(PersonType) }, - * children: { type: new GraphQLList(PersonType) }, - * }) - * }) - * ``` + * Clients are allowed to rendered diagnostics with this tag strike through. */ - - class GraphQLList { - constructor(ofType) { - isType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`); - this.ofType = ofType; - } - get [Symbol.toStringTag]() { - return 'GraphQLList'; - } - toString() { - return '[' + String(this.ofType) + ']'; - } - toJSON() { - return this.toString(); - } + DiagnosticTag.Deprecated = 2; +})(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {})); +/** + * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. + * + * @since 3.16.0 + */ +var CodeDescription; +(function (CodeDescription) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.href); } + CodeDescription.is = is; +})(CodeDescription || (exports.CodeDescription = CodeDescription = {})); +/** + * The Diagnostic namespace provides helper functions to work with + * {@link Diagnostic} literals. + */ +var Diagnostic; +(function (Diagnostic) { /** - * Non-Null Type Wrapper - * - * A non-null is a wrapping type which points to another type. - * Non-null types enforce that their values are never null and can ensure - * an error is raised if this ever occurs during a request. It is useful for - * fields which you can make a strong guarantee on non-nullability, for example - * usually the id field of a database row will never be null. - * - * Example: - * - * ```ts - * const RowType = new GraphQLObjectType({ - * name: 'Row', - * fields: () => ({ - * id: { type: new GraphQLNonNull(GraphQLString) }, - * }) - * }) - * ``` - * Note: the enforcement of non-nullability occurs within the executor. + * Creates a new Diagnostic literal. */ - exports.GraphQLList = GraphQLList; - class GraphQLNonNull { - constructor(ofType) { - isNullableType(ofType) || (0, _devAssert.devAssert)(false, `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL nullable type.`); - this.ofType = ofType; + function create(range, message, severity, code, source, relatedInformation) { + var result = { + range: range, + message: message + }; + if (Is.defined(severity)) { + result.severity = severity; } - get [Symbol.toStringTag]() { - return 'GraphQLNonNull'; + if (Is.defined(code)) { + result.code = code; } - toString() { - return String(this.ofType) + '!'; + if (Is.defined(source)) { + result.source = source; } - toJSON() { - return this.toString(); + if (Is.defined(relatedInformation)) { + result.relatedInformation = relatedInformation; } + return result; } + Diagnostic.create = create; /** - * These types wrap and modify other types + * Checks whether the given literal conforms to the {@link Diagnostic} interface. */ - exports.GraphQLNonNull = GraphQLNonNull; - function isWrappingType(type) { - return isListType(type) || isNonNullType(type); - } - function assertWrappingType(type) { - if (!isWrappingType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`); - } - return type; + function is(value) { + var _a; + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); } + Diagnostic.is = is; +})(Diagnostic || (exports.Diagnostic = Diagnostic = {})); +/** + * The Command namespace provides helper functions to work with + * {@link Command} literals. + */ +var Command; +(function (Command) { /** - * These types can all accept null as a value. + * Creates a new Command literal. */ - - function isNullableType(type) { - return isType(type) && !isNonNullType(type); - } - function assertNullableType(type) { - if (!isNullableType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`); + function create(title, command) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; } - return type; - } - function getNullableType(type) { - if (type) { - return isNonNullType(type) ? type.ofType : type; + var result = { + title: title, + command: command + }; + if (Is.defined(args) && args.length > 0) { + result.arguments = args; } + return result; } + Command.create = create; /** - * These named types do not include modifiers like List or NonNull. + * Checks whether the given literal conforms to the {@link Command} interface. */ - - function isNamedType(type) { - return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); - } - function assertNamedType(type) { - if (!isNamedType(type)) { - throw new Error(`Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`); - } - return type; - } - function getNamedType(type) { - if (type) { - let unwrappedType = type; - while (isWrappingType(unwrappedType)) { - unwrappedType = unwrappedType.ofType; - } - return unwrappedType; - } + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); } + Command.is = is; +})(Command || (exports.Command = Command = {})); +/** + * The TextEdit namespace provides helper function to create replace, + * insert and delete edits more easily. + */ +var TextEdit; +(function (TextEdit) { /** - * Used while defining GraphQL types to allow for circular references in - * otherwise immutable type definitions. + * Creates a replace text edit. + * @param range The range of text to be replaced. + * @param newText The new text. */ - - function resolveReadonlyArrayThunk(thunk) { - return typeof thunk === 'function' ? thunk() : thunk; - } - function resolveObjMapThunk(thunk) { - return typeof thunk === 'function' ? thunk() : thunk; + function replace(range, newText) { + return { + range: range, + newText: newText + }; } + TextEdit.replace = replace; /** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ - - /** - * Scalar Type Definition - * - * The leaf values of any request and input values to arguments are - * Scalars (or Enums) and are defined with a name and a series of functions - * used to parse input from ast or variables and to ensure validity. - * - * If a type's serialize function returns `null` or does not return a value - * (i.e. it returns `undefined`) then an error will be raised and a `null` - * value will be returned in the response. It is always better to validate - * - * Example: - * - * ```ts - * const OddType = new GraphQLScalarType({ - * name: 'Odd', - * serialize(value) { - * if (!Number.isFinite(value)) { - * throw new Error( - * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, - * ); - * } - * - * if (value % 2 === 0) { - * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); - * } - * return value; - * } - * }); - * ``` + * Creates an insert text edit. + * @param position The position to insert the text at. + * @param newText The text to be inserted. */ - class GraphQLScalarType { - constructor(config) { - var _config$parseValue, _config$serialize, _config$parseLiteral, _config$extensionASTN; - const parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : _identityFunc.identityFunc; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.specifiedByURL = config.specifiedByURL; - this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : _identityFunc.identityFunc; - this.parseValue = parseValue; - this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : (node, variables) => parseValue((0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables)); - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; - config.specifiedByURL == null || typeof config.specifiedByURL === 'string' || (0, _devAssert.devAssert)(false, `${this.name} must provide "specifiedByURL" as a string, ` + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`); - config.serialize == null || typeof config.serialize === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`); - if (config.parseLiteral) { - typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide both "parseValue" and "parseLiteral" functions.`); - } - } - get [Symbol.toStringTag]() { - return 'GraphQLScalarType'; - } - toConfig() { - return { - name: this.name, - description: this.description, - specifiedByURL: this.specifiedByURL, - serialize: this.serialize, - parseValue: this.parseValue, - parseLiteral: this.parseLiteral, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } + function insert(position, newText) { + return { + range: { + start: position, + end: position + }, + newText: newText + }; } - + TextEdit.insert = insert; /** - * Object Type Definition - * - * Almost all of the GraphQL types you define will be object types. Object types - * have a name, but most importantly describe their fields. - * - * Example: - * - * ```ts - * const AddressType = new GraphQLObjectType({ - * name: 'Address', - * fields: { - * street: { type: GraphQLString }, - * number: { type: GraphQLInt }, - * formatted: { - * type: GraphQLString, - * resolve(obj) { - * return obj.number + ' ' + obj.street - * } - * } - * } - * }); - * ``` - * - * When two types need to refer to each other, or a type needs to refer to - * itself in a field, you can use a function expression (aka a closure or a - * thunk) to supply the fields lazily. - * - * Example: - * - * ```ts - * const PersonType = new GraphQLObjectType({ - * name: 'Person', - * fields: () => ({ - * name: { type: GraphQLString }, - * bestFriend: { type: PersonType }, - * }) - * }); - * ``` + * Creates a delete text edit. + * @param range The range of text to be deleted. */ - exports.GraphQLScalarType = GraphQLScalarType; - class GraphQLObjectType { - constructor(config) { - var _config$extensionASTN2; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.isTypeOf = config.isTypeOf; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN2 = config.extensionASTNodes) !== null && _config$extensionASTN2 !== void 0 ? _config$extensionASTN2 : []; - this._fields = () => defineFieldMap(config); - this._interfaces = () => defineInterfaces(config); - config.isTypeOf == null || typeof config.isTypeOf === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "isTypeOf" as a function, ` + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`); - } - get [Symbol.toStringTag]() { - return 'GraphQLObjectType'; - } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } - return this._fields; - } - getInterfaces() { - if (typeof this._interfaces === 'function') { - this._interfaces = this._interfaces(); - } - return this._interfaces; - } - toConfig() { - return { - name: this.name, - description: this.description, - interfaces: this.getInterfaces(), - fields: fieldsToFieldsConfig(this.getFields()), - isTypeOf: this.isTypeOf, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } - } - exports.GraphQLObjectType = GraphQLObjectType; - function defineInterfaces(config) { - var _config$interfaces; - const interfaces = resolveReadonlyArrayThunk((_config$interfaces = config.interfaces) !== null && _config$interfaces !== void 0 ? _config$interfaces : []); - Array.isArray(interfaces) || (0, _devAssert.devAssert)(false, `${config.name} interfaces must be an Array or a function which returns an Array.`); - return interfaces; - } - function defineFieldMap(config) { - const fieldMap = resolveObjMapThunk(config.fields); - isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); - return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { - var _fieldConfig$args; - isPlainObj(fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field config must be an object.`); - fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function' || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`); - const argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {}; - isPlainObj(argsConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} args must be an object with argument names as keys.`); - return { - name: (0, _assertName.assertName)(fieldName), - description: fieldConfig.description, - type: fieldConfig.type, - args: defineArguments(argsConfig), - resolve: fieldConfig.resolve, - subscribe: fieldConfig.subscribe, - deprecationReason: fieldConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), - astNode: fieldConfig.astNode - }; - }); + function del(range) { + return { + range: range, + newText: '' + }; } - function defineArguments(config) { - return Object.entries(config).map(([argName, argConfig]) => ({ - name: (0, _assertName.assertName)(argName), - description: argConfig.description, - type: argConfig.type, - defaultValue: argConfig.defaultValue, - deprecationReason: argConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), - astNode: argConfig.astNode - })); + TextEdit.del = del; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); + } + TextEdit.is = is; +})(TextEdit || (exports.TextEdit = TextEdit = {})); +var ChangeAnnotation; +(function (ChangeAnnotation) { + function create(label, needsConfirmation, description) { + var result = { + label: label + }; + if (needsConfirmation !== undefined) { + result.needsConfirmation = needsConfirmation; + } + if (description !== undefined) { + result.description = description; + } + return result; } - function isPlainObj(obj) { - return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); + ChangeAnnotation.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined); } - function fieldsToFieldsConfig(fields) { - return (0, _mapValue.mapValue)(fields, field => ({ - description: field.description, - type: field.type, - args: argsToArgsConfig(field.args), - resolve: field.resolve, - subscribe: field.subscribe, - deprecationReason: field.deprecationReason, - extensions: field.extensions, - astNode: field.astNode - })); + ChangeAnnotation.is = is; +})(ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {})); +var ChangeAnnotationIdentifier; +(function (ChangeAnnotationIdentifier) { + function is(value) { + var candidate = value; + return Is.string(candidate); } + ChangeAnnotationIdentifier.is = is; +})(ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {})); +var AnnotatedTextEdit; +(function (AnnotatedTextEdit) { /** - * @internal + * Creates an annotated replace text edit. + * + * @param range The range of text to be replaced. + * @param newText The new text. + * @param annotation The annotation. */ - - function argsToArgsConfig(args) { - return (0, _keyValMap.keyValMap)(args, arg => arg.name, arg => ({ - description: arg.description, - type: arg.type, - defaultValue: arg.defaultValue, - deprecationReason: arg.deprecationReason, - extensions: arg.extensions, - astNode: arg.astNode - })); - } - function isRequiredArgument(arg) { - return isNonNullType(arg.type) && arg.defaultValue === undefined; + function replace(range, newText, annotation) { + return { + range: range, + newText: newText, + annotationId: annotation + }; } - + AnnotatedTextEdit.replace = replace; /** - * Interface Type Definition - * - * When a field can return one of a heterogeneous set of types, a Interface type - * is used to describe what types are possible, what fields are in common across - * all types, as well as a function to determine which type is actually used - * when the field is resolved. + * Creates an annotated insert text edit. * - * Example: - * - * ```ts - * const EntityType = new GraphQLInterfaceType({ - * name: 'Entity', - * fields: { - * name: { type: GraphQLString } - * } - * }); - * ``` + * @param position The position to insert the text at. + * @param newText The text to be inserted. + * @param annotation The annotation. */ - class GraphQLInterfaceType { - constructor(config) { - var _config$extensionASTN3; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.resolveType = config.resolveType; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN3 = config.extensionASTNodes) !== null && _config$extensionASTN3 !== void 0 ? _config$extensionASTN3 : []; - this._fields = defineFieldMap.bind(undefined, config); - this._interfaces = defineInterfaces.bind(undefined, config); - config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); - } - get [Symbol.toStringTag]() { - return 'GraphQLInterfaceType'; - } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } - return this._fields; - } - getInterfaces() { - if (typeof this._interfaces === 'function') { - this._interfaces = this._interfaces(); - } - return this._interfaces; - } - toConfig() { - return { - name: this.name, - description: this.description, - interfaces: this.getInterfaces(), - fields: fieldsToFieldsConfig(this.getFields()), - resolveType: this.resolveType, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } + function insert(position, newText, annotation) { + return { + range: { + start: position, + end: position + }, + newText: newText, + annotationId: annotation + }; } - + AnnotatedTextEdit.insert = insert; /** - * Union Type Definition - * - * When a field can return one of a heterogeneous set of types, a Union type - * is used to describe what types are possible as well as providing a function - * to determine which type is actually used when the field is resolved. + * Creates an annotated delete text edit. * - * Example: - * - * ```ts - * const PetType = new GraphQLUnionType({ - * name: 'Pet', - * types: [ DogType, CatType ], - * resolveType(value) { - * if (value instanceof Dog) { - * return DogType; - * } - * if (value instanceof Cat) { - * return CatType; - * } - * } - * }); - * ``` + * @param range The range of text to be deleted. + * @param annotation The annotation. */ - exports.GraphQLInterfaceType = GraphQLInterfaceType; - class GraphQLUnionType { - constructor(config) { - var _config$extensionASTN4; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.resolveType = config.resolveType; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN4 = config.extensionASTNodes) !== null && _config$extensionASTN4 !== void 0 ? _config$extensionASTN4 : []; - this._types = defineTypes.bind(undefined, config); - config.resolveType == null || typeof config.resolveType === 'function' || (0, _devAssert.devAssert)(false, `${this.name} must provide "resolveType" as a function, ` + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`); - } - get [Symbol.toStringTag]() { - return 'GraphQLUnionType'; - } - getTypes() { - if (typeof this._types === 'function') { - this._types = this._types(); - } - return this._types; - } - toConfig() { - return { - name: this.name, - description: this.description, - types: this.getTypes(), - resolveType: this.resolveType, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; - } - toString() { - return this.name; - } - toJSON() { - return this.toString(); - } + function del(range, annotation) { + return { + range: range, + newText: '', + annotationId: annotation + }; } - exports.GraphQLUnionType = GraphQLUnionType; - function defineTypes(config) { - const types = resolveReadonlyArrayThunk(config.types); - Array.isArray(types) || (0, _devAssert.devAssert)(false, `Must provide Array of types or a function which returns such an array for Union ${config.name}.`); - return types; + AnnotatedTextEdit.del = del; + function is(value) { + var candidate = value; + return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); } - + AnnotatedTextEdit.is = is; +})(AnnotatedTextEdit || (exports.AnnotatedTextEdit = AnnotatedTextEdit = {})); +/** + * The TextDocumentEdit namespace provides helper function to create + * an edit that manipulates a text document. + */ +var TextDocumentEdit; +(function (TextDocumentEdit) { /** - * Enum Type Definition - * - * Some leaf values of requests and input values are Enums. GraphQL serializes - * Enum values as strings, however internally Enums can be represented by any - * kind of type, often integers. - * - * Example: - * - * ```ts - * const RGBType = new GraphQLEnumType({ - * name: 'RGB', - * values: { - * RED: { value: 0 }, - * GREEN: { value: 1 }, - * BLUE: { value: 2 } - * } - * }); - * ``` - * - * Note: If a value is not provided in a definition, the name of the enum value - * will be used as its internal value. + * Creates a new `TextDocumentEdit` */ - class GraphQLEnumType { - /* */ - constructor(config) { - var _config$extensionASTN5; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN5 = config.extensionASTNodes) !== null && _config$extensionASTN5 !== void 0 ? _config$extensionASTN5 : []; - this._values = defineEnumValues(this.name, config.values); - this._valueLookup = new Map(this._values.map(enumValue => [enumValue.value, enumValue])); - this._nameLookup = (0, _keyMap.keyMap)(this._values, value => value.name); - } - get [Symbol.toStringTag]() { - return 'GraphQLEnumType'; - } - getValues() { - return this._values; - } - getValue(name) { - return this._nameLookup[name]; - } - serialize(outputValue) { - const enumValue = this._valueLookup.get(outputValue); - if (enumValue === undefined) { - throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); - } - return enumValue.name; - } - parseValue(inputValue) /* T */ - { - if (typeof inputValue !== 'string') { - const valueStr = (0, _inspect.inspect)(inputValue); - throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr)); - } - const enumValue = this.getValue(inputValue); - if (enumValue == null) { - throw new _GraphQLError.GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue)); - } - return enumValue.value; + function create(textDocument, edits) { + return { + textDocument: textDocument, + edits: edits + }; + } + TextDocumentEdit.create = create; + function is(value) { + var candidate = value; + return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); + } + TextDocumentEdit.is = is; +})(TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {})); +var CreateFile; +(function (CreateFile) { + function create(uri, options, annotation) { + var result = { + kind: 'create', + uri: uri + }; + if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { + result.options = options; } - parseLiteral(valueNode, _variables) /* T */ - { - // Note: variables will be resolved to a value before calling this function. - if (valueNode.kind !== _kinds.Kind.ENUM) { - const valueStr = (0, _printer.print)(valueNode); - throw new _GraphQLError.GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr), { - nodes: valueNode - }); - } - const enumValue = this.getValue(valueNode.value); - if (enumValue == null) { - const valueStr = (0, _printer.print)(valueNode); - throw new _GraphQLError.GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr), { - nodes: valueNode - }); - } - return enumValue.value; + if (annotation !== undefined) { + result.annotationId = annotation; } - toConfig() { - const values = (0, _keyValMap.keyValMap)(this.getValues(), value => value.name, value => ({ - description: value.description, - value: value.value, - deprecationReason: value.deprecationReason, - extensions: value.extensions, - astNode: value.astNode - })); - return { - name: this.name, - description: this.description, - values, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes - }; + return result; + } + CreateFile.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + CreateFile.is = is; +})(CreateFile || (exports.CreateFile = CreateFile = {})); +var RenameFile; +(function (RenameFile) { + function create(oldUri, newUri, options, annotation) { + var result = { + kind: 'rename', + oldUri: oldUri, + newUri: newUri + }; + if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { + result.options = options; } - toString() { - return this.name; + if (annotation !== undefined) { + result.annotationId = annotation; + } + return result; + } + RenameFile.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + RenameFile.is = is; +})(RenameFile || (exports.RenameFile = RenameFile = {})); +var DeleteFile; +(function (DeleteFile) { + function create(uri, options, annotation) { + var result = { + kind: 'delete', + uri: uri + }; + if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) { + result.options = options; } - toJSON() { - return this.toString(); + if (annotation !== undefined) { + result.annotationId = annotation; } + return result; } - exports.GraphQLEnumType = GraphQLEnumType; - function didYouMeanEnumValue(enumType, unknownValueStr) { - const allNames = enumType.getValues().map(value => value.name); - const suggestedValues = (0, _suggestionList.suggestionList)(unknownValueStr, allNames); - return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); + DeleteFile.create = create; + function is(value) { + var candidate = value; + return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); + } + DeleteFile.is = is; +})(DeleteFile || (exports.DeleteFile = DeleteFile = {})); +var WorkspaceEdit; +(function (WorkspaceEdit) { + function is(value) { + var candidate = value; + return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) { + if (Is.string(change.kind)) { + return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); + } else { + return TextDocumentEdit.is(change); + } + })); } - function defineEnumValues(typeName, valueMap) { - isPlainObj(valueMap) || (0, _devAssert.devAssert)(false, `${typeName} values must be an object with value names as keys.`); - return Object.entries(valueMap).map(([valueName, valueConfig]) => { - isPlainObj(valueConfig) || (0, _devAssert.devAssert)(false, `${typeName}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${(0, _inspect.inspect)(valueConfig)}.`); - return { - name: (0, _assertName.assertEnumValueName)(valueName), - description: valueConfig.description, - value: valueConfig.value !== undefined ? valueConfig.value : valueName, - deprecationReason: valueConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), - astNode: valueConfig.astNode - }; - }); + WorkspaceEdit.is = is; +})(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {})); +var TextEditChangeImpl = /** @class */function () { + function TextEditChangeImpl(edits, changeAnnotations) { + this.edits = edits; + this.changeAnnotations = changeAnnotations; + } + TextEditChangeImpl.prototype.insert = function (position, newText, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.insert(position, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.insert(position, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.insert(position, newText, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.replace = function (range, newText, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.replace(range, newText); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.replace(range, newText, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.replace(range, newText, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.delete = function (range, annotation) { + var edit; + var id; + if (annotation === undefined) { + edit = TextEdit.del(range); + } else if (ChangeAnnotationIdentifier.is(annotation)) { + id = annotation; + edit = AnnotatedTextEdit.del(range, annotation); + } else { + this.assertChangeAnnotations(this.changeAnnotations); + id = this.changeAnnotations.manage(annotation); + edit = AnnotatedTextEdit.del(range, id); + } + this.edits.push(edit); + if (id !== undefined) { + return id; + } + }; + TextEditChangeImpl.prototype.add = function (edit) { + this.edits.push(edit); + }; + TextEditChangeImpl.prototype.all = function () { + return this.edits; + }; + TextEditChangeImpl.prototype.clear = function () { + this.edits.splice(0, this.edits.length); + }; + TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) { + if (value === undefined) { + throw new Error("Text edit change is not configured to manage change annotations."); + } + }; + return TextEditChangeImpl; +}(); +/** + * A helper class + */ +var ChangeAnnotations = /** @class */function () { + function ChangeAnnotations(annotations) { + this._annotations = annotations === undefined ? Object.create(null) : annotations; + this._counter = 0; + this._size = 0; + } + ChangeAnnotations.prototype.all = function () { + return this._annotations; + }; + Object.defineProperty(ChangeAnnotations.prototype, "size", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) { + var id; + if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { + id = idOrAnnotation; + } else { + id = this.nextId(); + annotation = idOrAnnotation; + } + if (this._annotations[id] !== undefined) { + throw new Error("Id ".concat(id, " is already in use.")); + } + if (annotation === undefined) { + throw new Error("No annotation provided for id ".concat(id)); + } + this._annotations[id] = annotation; + this._size++; + return id; + }; + ChangeAnnotations.prototype.nextId = function () { + this._counter++; + return this._counter.toString(); + }; + return ChangeAnnotations; +}(); +/** + * A workspace change helps constructing changes to a workspace. + */ +var WorkspaceChange = exports.WorkspaceChange = /** @class */function () { + function WorkspaceChange(workspaceEdit) { + var _this = this; + this._textEditChanges = Object.create(null); + if (workspaceEdit !== undefined) { + this._workspaceEdit = workspaceEdit; + if (workspaceEdit.documentChanges) { + this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); + workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + workspaceEdit.documentChanges.forEach(function (change) { + if (TextDocumentEdit.is(change)) { + var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); + _this._textEditChanges[change.textDocument.uri] = textEditChange; + } + }); + } else if (workspaceEdit.changes) { + Object.keys(workspaceEdit.changes).forEach(function (key) { + var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); + _this._textEditChanges[key] = textEditChange; + }); + } + } else { + this._workspaceEdit = {}; + } } - - /** - * Input Object Type Definition - * - * An input object defines a structured collection of fields which may be - * supplied to a field argument. - * - * Using `NonNull` will ensure that a value must be provided by the query - * - * Example: - * - * ```ts - * const GeoPoint = new GraphQLInputObjectType({ - * name: 'GeoPoint', - * fields: { - * lat: { type: new GraphQLNonNull(GraphQLFloat) }, - * lon: { type: new GraphQLNonNull(GraphQLFloat) }, - * alt: { type: GraphQLFloat, defaultValue: 0 }, - * } - * }); - * ``` - */ - class GraphQLInputObjectType { - constructor(config) { - var _config$extensionASTN6; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN6 = config.extensionASTNodes) !== null && _config$extensionASTN6 !== void 0 ? _config$extensionASTN6 : []; - this._fields = defineInputFieldMap.bind(undefined, config); - } - get [Symbol.toStringTag]() { - return 'GraphQLInputObjectType'; - } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } - return this._fields; - } - toConfig() { - const fields = (0, _mapValue.mapValue)(this.getFields(), field => ({ - description: field.description, - type: field.type, - defaultValue: field.defaultValue, - deprecationReason: field.deprecationReason, - extensions: field.extensions, - astNode: field.astNode - })); - return { - name: this.name, - description: this.description, - fields, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes + Object.defineProperty(WorkspaceChange.prototype, "edit", { + /** + * Returns the underlying {@link WorkspaceEdit} literal + * use to be returned from a workspace edit operation like rename. + */ + get: function () { + this.initDocumentChanges(); + if (this._changeAnnotations !== undefined) { + if (this._changeAnnotations.size === 0) { + this._workspaceEdit.changeAnnotations = undefined; + } else { + this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + } + } + return this._workspaceEdit; + }, + enumerable: false, + configurable: true + }); + WorkspaceChange.prototype.getTextEditChange = function (key) { + if (OptionalVersionedTextDocumentIdentifier.is(key)) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var textDocument = { + uri: key.uri, + version: key.version }; + var result = this._textEditChanges[textDocument.uri]; + if (!result) { + var edits = []; + var textDocumentEdit = { + textDocument: textDocument, + edits: edits + }; + this._workspaceEdit.documentChanges.push(textDocumentEdit); + result = new TextEditChangeImpl(edits, this._changeAnnotations); + this._textEditChanges[textDocument.uri] = result; + } + return result; + } else { + this.initChanges(); + if (this._workspaceEdit.changes === undefined) { + throw new Error('Workspace edit is not configured for normal text edit changes.'); + } + var result = this._textEditChanges[key]; + if (!result) { + var edits = []; + this._workspaceEdit.changes[key] = edits; + result = new TextEditChangeImpl(edits); + this._textEditChanges[key] = result; + } + return result; + } + }; + WorkspaceChange.prototype.initDocumentChanges = function () { + if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { + this._changeAnnotations = new ChangeAnnotations(); + this._workspaceEdit.documentChanges = []; + this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); + } + }; + WorkspaceChange.prototype.initChanges = function () { + if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { + this._workspaceEdit.changes = Object.create(null); + } + }; + WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = CreateFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = CreateFile.create(uri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; + } + }; + WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = RenameFile.create(oldUri, newUri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = RenameFile.create(oldUri, newUri, options, id); + } + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; } - toString() { - return this.name; + }; + WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) { + this.initDocumentChanges(); + if (this._workspaceEdit.documentChanges === undefined) { + throw new Error('Workspace edit is not configured for document changes.'); + } + var annotation; + if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { + annotation = optionsOrAnnotation; + } else { + options = optionsOrAnnotation; + } + var operation; + var id; + if (annotation === undefined) { + operation = DeleteFile.create(uri, options); + } else { + id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); + operation = DeleteFile.create(uri, options, id); } - toJSON() { - return this.toString(); + this._workspaceEdit.documentChanges.push(operation); + if (id !== undefined) { + return id; } + }; + return WorkspaceChange; +}(); +/** + * The TextDocumentIdentifier namespace provides helper functions to work with + * {@link TextDocumentIdentifier} literals. + */ +var TextDocumentIdentifier; +(function (TextDocumentIdentifier) { + /** + * Creates a new TextDocumentIdentifier literal. + * @param uri The document's uri. + */ + function create(uri) { + return { + uri: uri + }; } - exports.GraphQLInputObjectType = GraphQLInputObjectType; - function defineInputFieldMap(config) { - const fieldMap = resolveObjMapThunk(config.fields); - isPlainObj(fieldMap) || (0, _devAssert.devAssert)(false, `${config.name} fields must be an object with field names as keys or a function which returns such an object.`); - return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { - !('resolve' in fieldConfig) || (0, _devAssert.devAssert)(false, `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`); - return { - name: (0, _assertName.assertName)(fieldName), - description: fieldConfig.description, - type: fieldConfig.type, - defaultValue: fieldConfig.defaultValue, - deprecationReason: fieldConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), - astNode: fieldConfig.astNode - }; - }); + TextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri); } - function isRequiredInputField(field) { - return isNonNullType(field.type) && field.defaultValue === undefined; + TextDocumentIdentifier.is = is; +})(TextDocumentIdentifier || (exports.TextDocumentIdentifier = TextDocumentIdentifier = {})); +/** + * The VersionedTextDocumentIdentifier namespace provides helper functions to work with + * {@link VersionedTextDocumentIdentifier} literals. + */ +var VersionedTextDocumentIdentifier; +(function (VersionedTextDocumentIdentifier) { + /** + * Creates a new VersionedTextDocumentIdentifier literal. + * @param uri The document's uri. + * @param version The document's version. + */ + function create(uri, version) { + return { + uri: uri, + version: version + }; } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/directives.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/type/directives.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.GraphQLSpecifiedByDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = void 0; - exports.assertDirective = assertDirective; - exports.isDirective = isDirective; - exports.isSpecifiedDirective = isSpecifiedDirective; - exports.specifiedDirectives = void 0; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); - var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); - var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); - var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); + VersionedTextDocumentIdentifier.create = create; /** - * Test if the given value is a GraphQL directive. + * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. */ - - function isDirective(directive) { - return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); } - function assertDirective(directive) { - if (!isDirective(directive)) { - throw new Error(`Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`); - } - return directive; + VersionedTextDocumentIdentifier.is = is; +})(VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {})); +/** + * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with + * {@link OptionalVersionedTextDocumentIdentifier} literals. + */ +var OptionalVersionedTextDocumentIdentifier; +(function (OptionalVersionedTextDocumentIdentifier) { + /** + * Creates a new OptionalVersionedTextDocumentIdentifier literal. + * @param uri The document's uri. + * @param version The document's version. + */ + function create(uri, version) { + return { + uri: uri, + version: version + }; + } + OptionalVersionedTextDocumentIdentifier.create = create; + /** + * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); + } + OptionalVersionedTextDocumentIdentifier.is = is; +})(OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); +/** + * The TextDocumentItem namespace provides helper functions to work with + * {@link TextDocumentItem} literals. + */ +var TextDocumentItem; +(function (TextDocumentItem) { + /** + * Creates a new TextDocumentItem literal. + * @param uri The document's uri. + * @param languageId The document's language identifier. + * @param version The document's version number. + * @param text The document's text. + */ + function create(uri, languageId, version, text) { + return { + uri: uri, + languageId: languageId, + version: version, + text: text + }; + } + TextDocumentItem.create = create; + /** + * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); + } + TextDocumentItem.is = is; +})(TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {})); +/** + * Describes the content type that a client supports in various + * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. + * + * Please note that `MarkupKinds` must not start with a `$`. This kinds + * are reserved for internal usage. + */ +var MarkupKind; +(function (MarkupKind) { + /** + * Plain text is supported as a content format + */ + MarkupKind.PlainText = 'plaintext'; + /** + * Markdown is supported as a content format + */ + MarkupKind.Markdown = 'markdown'; + /** + * Checks whether the given value is a value of the {@link MarkupKind} type. + */ + function is(value) { + var candidate = value; + return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; + } + MarkupKind.is = is; +})(MarkupKind || (exports.MarkupKind = MarkupKind = {})); +var MarkupContent; +(function (MarkupContent) { + /** + * Checks whether the given value conforms to the {@link MarkupContent} interface. + */ + function is(value) { + var candidate = value; + return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); + } + MarkupContent.is = is; +})(MarkupContent || (exports.MarkupContent = MarkupContent = {})); +/** + * The kind of a completion entry. + */ +var CompletionItemKind; +(function (CompletionItemKind) { + CompletionItemKind.Text = 1; + CompletionItemKind.Method = 2; + CompletionItemKind.Function = 3; + CompletionItemKind.Constructor = 4; + CompletionItemKind.Field = 5; + CompletionItemKind.Variable = 6; + CompletionItemKind.Class = 7; + CompletionItemKind.Interface = 8; + CompletionItemKind.Module = 9; + CompletionItemKind.Property = 10; + CompletionItemKind.Unit = 11; + CompletionItemKind.Value = 12; + CompletionItemKind.Enum = 13; + CompletionItemKind.Keyword = 14; + CompletionItemKind.Snippet = 15; + CompletionItemKind.Color = 16; + CompletionItemKind.File = 17; + CompletionItemKind.Reference = 18; + CompletionItemKind.Folder = 19; + CompletionItemKind.EnumMember = 20; + CompletionItemKind.Constant = 21; + CompletionItemKind.Struct = 22; + CompletionItemKind.Event = 23; + CompletionItemKind.Operator = 24; + CompletionItemKind.TypeParameter = 25; +})(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); +/** + * Defines whether the insert text in a completion item should be interpreted as + * plain text or a snippet. + */ +var InsertTextFormat; +(function (InsertTextFormat) { + /** + * The primary text to be inserted is treated as a plain string. + */ + InsertTextFormat.PlainText = 1; + /** + * The primary text to be inserted is treated as a snippet. + * + * A snippet can define tab stops and placeholders with `$1`, `$2` + * and `${3:foo}`. `$0` defines the final tab stop, it defaults to + * the end of the snippet. Placeholders with equal identifiers are linked, + * that is typing in one will update others too. + * + * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax + */ + InsertTextFormat.Snippet = 2; +})(InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {})); +/** + * Completion item tags are extra annotations that tweak the rendering of a completion + * item. + * + * @since 3.15.0 + */ +var CompletionItemTag; +(function (CompletionItemTag) { + /** + * Render a completion as obsolete, usually using a strike-out. + */ + CompletionItemTag.Deprecated = 1; +})(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {})); +/** + * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. + * + * @since 3.16.0 + */ +var InsertReplaceEdit; +(function (InsertReplaceEdit) { + /** + * Creates a new insert / replace edit + */ + function create(newText, insert, replace) { + return { + newText: newText, + insert: insert, + replace: replace + }; } + InsertReplaceEdit.create = create; + /** + * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. + */ + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); + } + InsertReplaceEdit.is = is; +})(InsertReplaceEdit || (exports.InsertReplaceEdit = InsertReplaceEdit = {})); +/** + * How whitespace and indentation is handled during completion + * item insertion. + * + * @since 3.16.0 + */ +var InsertTextMode; +(function (InsertTextMode) { + /** + * The insertion or replace strings is taken as it is. If the + * value is multi line the lines below the cursor will be + * inserted using the indentation defined in the string value. + * The client will not apply any kind of adjustments to the + * string. + */ + InsertTextMode.asIs = 1; + /** + * The editor adjusts leading whitespace of new lines so that + * they match the indentation up to the cursor of the line for + * which the item is accepted. + * + * Consider a line like this: <2tabs><3tabs>foo. Accepting a + * multi line completion item is indented using 2 tabs and all + * following lines inserted will be indented using 2 tabs as well. + */ + InsertTextMode.adjustIndentation = 2; +})(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {})); +var CompletionItemLabelDetails; +(function (CompletionItemLabelDetails) { + function is(value) { + var candidate = value; + return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) && (Is.string(candidate.description) || candidate.description === undefined); + } + CompletionItemLabelDetails.is = is; +})(CompletionItemLabelDetails || (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = {})); +/** + * The CompletionItem namespace provides functions to deal with + * completion items. + */ +var CompletionItem; +(function (CompletionItem) { + /** + * Create a completion item and seed it with a label. + * @param label The completion item's label + */ + function create(label) { + return { + label: label + }; + } + CompletionItem.create = create; +})(CompletionItem || (exports.CompletionItem = CompletionItem = {})); +/** + * The CompletionList namespace provides functions to deal with + * completion lists. + */ +var CompletionList; +(function (CompletionList) { /** - * Custom extensions + * Creates a new completion list. * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. + * @param items The completion items. + * @param isIncomplete The list is not complete. */ - + function create(items, isIncomplete) { + return { + items: items ? items : [], + isIncomplete: !!isIncomplete + }; + } + CompletionList.create = create; +})(CompletionList || (exports.CompletionList = CompletionList = {})); +var MarkedString; +(function (MarkedString) { /** - * Directives are used by the GraphQL runtime as a way of modifying execution - * behavior. Type system creators will usually not create these directly. + * Creates a marked string from plain text. + * + * @param plainText The plain text. */ - class GraphQLDirective { - constructor(config) { - var _config$isRepeatable, _config$args; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.locations = config.locations; - this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - Array.isArray(config.locations) || (0, _devAssert.devAssert)(false, `@${config.name} locations must be an Array.`); - const args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {}; - (0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args) || (0, _devAssert.devAssert)(false, `@${config.name} args must be an object with argument names as keys.`); - this.args = (0, _definition.defineArguments)(args); - } - get [Symbol.toStringTag]() { - return 'GraphQLDirective'; - } - toConfig() { - return { - name: this.name, - description: this.description, - locations: this.locations, - args: (0, _definition.argsToArgsConfig)(this.args), - isRepeatable: this.isRepeatable, - extensions: this.extensions, - astNode: this.astNode - }; - } - toString() { - return '@' + this.name; + function fromPlainText(plainText) { + return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash + } + MarkedString.fromPlainText = fromPlainText; + /** + * Checks whether the given value conforms to the {@link MarkedString} type. + */ + function is(value) { + var candidate = value; + return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value); + } + MarkedString.is = is; +})(MarkedString || (exports.MarkedString = MarkedString = {})); +var Hover; +(function (Hover) { + /** + * Checks whether the given value conforms to the {@link Hover} interface. + */ + function is(value) { + var candidate = value; + return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range)); + } + Hover.is = is; +})(Hover || (exports.Hover = Hover = {})); +/** + * The ParameterInformation namespace provides helper functions to work with + * {@link ParameterInformation} literals. + */ +var ParameterInformation; +(function (ParameterInformation) { + /** + * Creates a new parameter information literal. + * + * @param label A label string. + * @param documentation A doc string. + */ + function create(label, documentation) { + return documentation ? { + label: label, + documentation: documentation + } : { + label: label + }; + } + ParameterInformation.create = create; +})(ParameterInformation || (exports.ParameterInformation = ParameterInformation = {})); +/** + * The SignatureInformation namespace provides helper functions to work with + * {@link SignatureInformation} literals. + */ +var SignatureInformation; +(function (SignatureInformation) { + function create(label, documentation) { + var parameters = []; + for (var _i = 2; _i < arguments.length; _i++) { + parameters[_i - 2] = arguments[_i]; + } + var result = { + label: label + }; + if (Is.defined(documentation)) { + result.documentation = documentation; } - toJSON() { - return this.toString(); + if (Is.defined(parameters)) { + result.parameters = parameters; + } else { + result.parameters = []; } + return result; } - + SignatureInformation.create = create; +})(SignatureInformation || (exports.SignatureInformation = SignatureInformation = {})); +/** + * A document highlight kind. + */ +var DocumentHighlightKind; +(function (DocumentHighlightKind) { /** - * Used to conditionally include fields or fragments. + * A textual occurrence. */ - exports.GraphQLDirective = GraphQLDirective; - const GraphQLIncludeDirective = exports.GraphQLIncludeDirective = new GraphQLDirective({ - name: 'include', - description: 'Directs the executor to include this field or fragment only when the `if` argument is true.', - locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], - args: { - if: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - description: 'Included when true.' - } - } - }); + DocumentHighlightKind.Text = 1; /** - * Used to conditionally skip (exclude) fields or fragments. + * Read-access of a symbol, like reading a variable. */ - - const GraphQLSkipDirective = exports.GraphQLSkipDirective = new GraphQLDirective({ - name: 'skip', - description: 'Directs the executor to skip this field or fragment when the `if` argument is true.', - locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], - args: { - if: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - description: 'Skipped when true.' - } - } - }); + DocumentHighlightKind.Read = 2; /** - * Constant string used for default reason for a deprecation. + * Write-access of a symbol, like writing to a variable. */ - - const DEFAULT_DEPRECATION_REASON = exports.DEFAULT_DEPRECATION_REASON = 'No longer supported'; + DocumentHighlightKind.Write = 3; +})(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {})); +/** + * DocumentHighlight namespace to provide helper functions to work with + * {@link DocumentHighlight} literals. + */ +var DocumentHighlight; +(function (DocumentHighlight) { /** - * Used to declare element of a GraphQL schema as deprecated. + * Create a DocumentHighlight object. + * @param range The range the highlight applies to. + * @param kind The highlight kind */ - - const GraphQLDeprecatedDirective = exports.GraphQLDeprecatedDirective = new GraphQLDirective({ - name: 'deprecated', - description: 'Marks an element of a GraphQL schema as no longer supported.', - locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], - args: { - reason: { - type: _scalars.GraphQLString, - description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', - defaultValue: DEFAULT_DEPRECATION_REASON + function create(range, kind) { + var result = { + range: range + }; + if (Is.number(kind)) { + result.kind = kind; + } + return result; + } + DocumentHighlight.create = create; +})(DocumentHighlight || (exports.DocumentHighlight = DocumentHighlight = {})); +/** + * A symbol kind. + */ +var SymbolKind; +(function (SymbolKind) { + SymbolKind.File = 1; + SymbolKind.Module = 2; + SymbolKind.Namespace = 3; + SymbolKind.Package = 4; + SymbolKind.Class = 5; + SymbolKind.Method = 6; + SymbolKind.Property = 7; + SymbolKind.Field = 8; + SymbolKind.Constructor = 9; + SymbolKind.Enum = 10; + SymbolKind.Interface = 11; + SymbolKind.Function = 12; + SymbolKind.Variable = 13; + SymbolKind.Constant = 14; + SymbolKind.String = 15; + SymbolKind.Number = 16; + SymbolKind.Boolean = 17; + SymbolKind.Array = 18; + SymbolKind.Object = 19; + SymbolKind.Key = 20; + SymbolKind.Null = 21; + SymbolKind.EnumMember = 22; + SymbolKind.Struct = 23; + SymbolKind.Event = 24; + SymbolKind.Operator = 25; + SymbolKind.TypeParameter = 26; +})(SymbolKind || (exports.SymbolKind = SymbolKind = {})); +/** + * Symbol tags are extra annotations that tweak the rendering of a symbol. + * + * @since 3.16 + */ +var SymbolTag; +(function (SymbolTag) { + /** + * Render a symbol as obsolete, usually using a strike-out. + */ + SymbolTag.Deprecated = 1; +})(SymbolTag || (exports.SymbolTag = SymbolTag = {})); +var SymbolInformation; +(function (SymbolInformation) { + /** + * Creates a new symbol information literal. + * + * @param name The name of the symbol. + * @param kind The kind of the symbol. + * @param range The range of the location of the symbol. + * @param uri The resource of the location of symbol. + * @param containerName The name of the symbol containing the symbol. + */ + function create(name, kind, range, uri, containerName) { + var result = { + name: name, + kind: kind, + location: { + uri: uri, + range: range } + }; + if (containerName) { + result.containerName = containerName; } - }); + return result; + } + SymbolInformation.create = create; +})(SymbolInformation || (exports.SymbolInformation = SymbolInformation = {})); +var WorkspaceSymbol; +(function (WorkspaceSymbol) { /** - * Used to provide a URL for specifying the behavior of custom scalar definitions. + * Create a new workspace symbol. + * + * @param name The name of the symbol. + * @param kind The kind of the symbol. + * @param uri The resource of the location of the symbol. + * @param range An options range of the location. + * @returns A WorkspaceSymbol. */ - - const GraphQLSpecifiedByDirective = exports.GraphQLSpecifiedByDirective = new GraphQLDirective({ - name: 'specifiedBy', - description: 'Exposes a URL that specifies the behavior of this scalar.', - locations: [_directiveLocation.DirectiveLocation.SCALAR], - args: { - url: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - description: 'The URL that specifies the behavior of this scalar.' + function create(name, kind, uri, range) { + return range !== undefined ? { + name: name, + kind: kind, + location: { + uri: uri, + range: range + } + } : { + name: name, + kind: kind, + location: { + uri: uri } + }; + } + WorkspaceSymbol.create = create; +})(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {})); +var DocumentSymbol; +(function (DocumentSymbol) { + /** + * Creates a new symbol information literal. + * + * @param name The name of the symbol. + * @param detail The detail of the symbol. + * @param kind The kind of the symbol. + * @param range The range of the symbol. + * @param selectionRange The selectionRange of the symbol. + * @param children Children of the symbol. + */ + function create(name, detail, kind, range, selectionRange, children) { + var result = { + name: name, + detail: detail, + kind: kind, + range: range, + selectionRange: selectionRange + }; + if (children !== undefined) { + result.children = children; } - }); + return result; + } + DocumentSymbol.create = create; /** - * The full list of specified directives. + * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. */ - - const specifiedDirectives = exports.specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]); - function isSpecifiedDirective(directive) { - return specifiedDirectives.some(({ - name - }) => name === directive.name); + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags)); } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/index.mjs": - /*!****************************************************!*\ - !*** ../../../node_modules/graphql/type/index.mjs ***! - \****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ - enumerable: true, - get: function () { - return _directives.DEFAULT_DEPRECATION_REASON; + DocumentSymbol.is = is; +})(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {})); +/** + * A set of predefined code action kinds + */ +var CodeActionKind; +(function (CodeActionKind) { + /** + * Empty kind. + */ + CodeActionKind.Empty = ''; + /** + * Base kind for quickfix actions: 'quickfix' + */ + CodeActionKind.QuickFix = 'quickfix'; + /** + * Base kind for refactoring actions: 'refactor' + */ + CodeActionKind.Refactor = 'refactor'; + /** + * Base kind for refactoring extraction actions: 'refactor.extract' + * + * Example extract actions: + * + * - Extract method + * - Extract function + * - Extract variable + * - Extract interface from class + * - ... + */ + CodeActionKind.RefactorExtract = 'refactor.extract'; + /** + * Base kind for refactoring inline actions: 'refactor.inline' + * + * Example inline actions: + * + * - Inline function + * - Inline variable + * - Inline constant + * - ... + */ + CodeActionKind.RefactorInline = 'refactor.inline'; + /** + * Base kind for refactoring rewrite actions: 'refactor.rewrite' + * + * Example rewrite actions: + * + * - Convert JavaScript function to class + * - Add or remove parameter + * - Encapsulate field + * - Make method static + * - Move method to base class + * - ... + */ + CodeActionKind.RefactorRewrite = 'refactor.rewrite'; + /** + * Base kind for source actions: `source` + * + * Source code actions apply to the entire file. + */ + CodeActionKind.Source = 'source'; + /** + * Base kind for an organize imports source action: `source.organizeImports` + */ + CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; + /** + * Base kind for auto-fix source actions: `source.fixAll`. + * + * Fix all actions automatically fix errors that have a clear fix that do not require user input. + * They should not suppress errors or perform unsafe fixes such as generating new types or classes. + * + * @since 3.15.0 + */ + CodeActionKind.SourceFixAll = 'source.fixAll'; +})(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {})); +/** + * The reason why code actions were requested. + * + * @since 3.17.0 + */ +var CodeActionTriggerKind; +(function (CodeActionTriggerKind) { + /** + * Code actions were explicitly requested by the user or by an extension. + */ + CodeActionTriggerKind.Invoked = 1; + /** + * Code actions were requested automatically. + * + * This typically happens when current selection in a file changes, but can + * also be triggered when file content changes. + */ + CodeActionTriggerKind.Automatic = 2; +})(CodeActionTriggerKind || (exports.CodeActionTriggerKind = CodeActionTriggerKind = {})); +/** + * The CodeActionContext namespace provides helper functions to work with + * {@link CodeActionContext} literals. + */ +var CodeActionContext; +(function (CodeActionContext) { + /** + * Creates a new CodeActionContext literal. + */ + function create(diagnostics, only, triggerKind) { + var result = { + diagnostics: diagnostics + }; + if (only !== undefined && only !== null) { + result.only = only; } - })); - Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ - enumerable: true, - get: function () { - return _scalars.GRAPHQL_MAX_INT; + if (triggerKind !== undefined && triggerKind !== null) { + result.triggerKind = triggerKind; } - })); - Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ - enumerable: true, - get: function () { - return _scalars.GRAPHQL_MIN_INT; + return result; + } + CodeActionContext.create = create; + /** + * Checks whether the given literal conforms to the {@link CodeActionContext} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); + } + CodeActionContext.is = is; +})(CodeActionContext || (exports.CodeActionContext = CodeActionContext = {})); +var CodeAction; +(function (CodeAction) { + function create(title, kindOrCommandOrEdit, kind) { + var result = { + title: title + }; + var checkKind = true; + if (typeof kindOrCommandOrEdit === 'string') { + checkKind = false; + result.kind = kindOrCommandOrEdit; + } else if (Command.is(kindOrCommandOrEdit)) { + result.command = kindOrCommandOrEdit; + } else { + result.edit = kindOrCommandOrEdit; } - })); - Object.defineProperty(exports, "GraphQLBoolean", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLBoolean; - } - })); - Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLDeprecatedDirective; - } - })); - Object.defineProperty(exports, "GraphQLDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLDirective; - } - })); - Object.defineProperty(exports, "GraphQLEnumType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLEnumType; - } - })); - Object.defineProperty(exports, "GraphQLFloat", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLFloat; - } - })); - Object.defineProperty(exports, "GraphQLID", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLID; - } - })); - Object.defineProperty(exports, "GraphQLIncludeDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLIncludeDirective; - } - })); - Object.defineProperty(exports, "GraphQLInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLInputObjectType; - } - })); - Object.defineProperty(exports, "GraphQLInt", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLInt; - } - })); - Object.defineProperty(exports, "GraphQLInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLInterfaceType; - } - })); - Object.defineProperty(exports, "GraphQLList", ({ - enumerable: true, - get: function () { - return _definition.GraphQLList; - } - })); - Object.defineProperty(exports, "GraphQLNonNull", ({ - enumerable: true, - get: function () { - return _definition.GraphQLNonNull; - } - })); - Object.defineProperty(exports, "GraphQLObjectType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLObjectType; - } - })); - Object.defineProperty(exports, "GraphQLScalarType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLScalarType; - } - })); - Object.defineProperty(exports, "GraphQLSchema", ({ - enumerable: true, - get: function () { - return _schema.GraphQLSchema; - } - })); - Object.defineProperty(exports, "GraphQLSkipDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLSkipDirective; - } - })); - Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLSpecifiedByDirective; - } - })); - Object.defineProperty(exports, "GraphQLString", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLString; - } - })); - Object.defineProperty(exports, "GraphQLUnionType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLUnionType; - } - })); - Object.defineProperty(exports, "SchemaMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.SchemaMetaFieldDef; - } - })); - Object.defineProperty(exports, "TypeKind", ({ - enumerable: true, - get: function () { - return _introspection.TypeKind; - } - })); - Object.defineProperty(exports, "TypeMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.TypeMetaFieldDef; - } - })); - Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.TypeNameMetaFieldDef; - } - })); - Object.defineProperty(exports, "__Directive", ({ - enumerable: true, - get: function () { - return _introspection.__Directive; - } - })); - Object.defineProperty(exports, "__DirectiveLocation", ({ - enumerable: true, - get: function () { - return _introspection.__DirectiveLocation; - } - })); - Object.defineProperty(exports, "__EnumValue", ({ - enumerable: true, - get: function () { - return _introspection.__EnumValue; - } - })); - Object.defineProperty(exports, "__Field", ({ - enumerable: true, - get: function () { - return _introspection.__Field; - } - })); - Object.defineProperty(exports, "__InputValue", ({ - enumerable: true, - get: function () { - return _introspection.__InputValue; - } - })); - Object.defineProperty(exports, "__Schema", ({ - enumerable: true, - get: function () { - return _introspection.__Schema; - } - })); - Object.defineProperty(exports, "__Type", ({ - enumerable: true, - get: function () { - return _introspection.__Type; - } - })); - Object.defineProperty(exports, "__TypeKind", ({ - enumerable: true, - get: function () { - return _introspection.__TypeKind; + if (checkKind && kind !== undefined) { + result.kind = kind; } - })); - Object.defineProperty(exports, "assertAbstractType", ({ - enumerable: true, - get: function () { - return _definition.assertAbstractType; + return result; + } + CodeAction.create = create; + function is(value) { + var candidate = value; + return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)); + } + CodeAction.is = is; +})(CodeAction || (exports.CodeAction = CodeAction = {})); +/** + * The CodeLens namespace provides helper functions to work with + * {@link CodeLens} literals. + */ +var CodeLens; +(function (CodeLens) { + /** + * Creates a new CodeLens literal. + */ + function create(range, data) { + var result = { + range: range + }; + if (Is.defined(data)) { + result.data = data; } - })); - Object.defineProperty(exports, "assertCompositeType", ({ - enumerable: true, - get: function () { - return _definition.assertCompositeType; + return result; + } + CodeLens.create = create; + /** + * Checks whether the given literal conforms to the {@link CodeLens} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); + } + CodeLens.is = is; +})(CodeLens || (exports.CodeLens = CodeLens = {})); +/** + * The FormattingOptions namespace provides helper functions to work with + * {@link FormattingOptions} literals. + */ +var FormattingOptions; +(function (FormattingOptions) { + /** + * Creates a new FormattingOptions literal. + */ + function create(tabSize, insertSpaces) { + return { + tabSize: tabSize, + insertSpaces: insertSpaces + }; + } + FormattingOptions.create = create; + /** + * Checks whether the given literal conforms to the {@link FormattingOptions} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); + } + FormattingOptions.is = is; +})(FormattingOptions || (exports.FormattingOptions = FormattingOptions = {})); +/** + * The DocumentLink namespace provides helper functions to work with + * {@link DocumentLink} literals. + */ +var DocumentLink; +(function (DocumentLink) { + /** + * Creates a new DocumentLink literal. + */ + function create(range, target, data) { + return { + range: range, + target: target, + data: data + }; + } + DocumentLink.create = create; + /** + * Checks whether the given literal conforms to the {@link DocumentLink} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); + } + DocumentLink.is = is; +})(DocumentLink || (exports.DocumentLink = DocumentLink = {})); +/** + * The SelectionRange namespace provides helper function to work with + * SelectionRange literals. + */ +var SelectionRange; +(function (SelectionRange) { + /** + * Creates a new SelectionRange + * @param range the range. + * @param parent an optional parent. + */ + function create(range, parent) { + return { + range: range, + parent: parent + }; + } + SelectionRange.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); + } + SelectionRange.is = is; +})(SelectionRange || (exports.SelectionRange = SelectionRange = {})); +/** + * A set of predefined token types. This set is not fixed + * an clients can specify additional token types via the + * corresponding client capabilities. + * + * @since 3.16.0 + */ +var SemanticTokenTypes; +(function (SemanticTokenTypes) { + SemanticTokenTypes["namespace"] = "namespace"; + /** + * Represents a generic type. Acts as a fallback for types which can't be mapped to + * a specific type like class or enum. + */ + SemanticTokenTypes["type"] = "type"; + SemanticTokenTypes["class"] = "class"; + SemanticTokenTypes["enum"] = "enum"; + SemanticTokenTypes["interface"] = "interface"; + SemanticTokenTypes["struct"] = "struct"; + SemanticTokenTypes["typeParameter"] = "typeParameter"; + SemanticTokenTypes["parameter"] = "parameter"; + SemanticTokenTypes["variable"] = "variable"; + SemanticTokenTypes["property"] = "property"; + SemanticTokenTypes["enumMember"] = "enumMember"; + SemanticTokenTypes["event"] = "event"; + SemanticTokenTypes["function"] = "function"; + SemanticTokenTypes["method"] = "method"; + SemanticTokenTypes["macro"] = "macro"; + SemanticTokenTypes["keyword"] = "keyword"; + SemanticTokenTypes["modifier"] = "modifier"; + SemanticTokenTypes["comment"] = "comment"; + SemanticTokenTypes["string"] = "string"; + SemanticTokenTypes["number"] = "number"; + SemanticTokenTypes["regexp"] = "regexp"; + SemanticTokenTypes["operator"] = "operator"; + /** + * @since 3.17.0 + */ + SemanticTokenTypes["decorator"] = "decorator"; +})(SemanticTokenTypes || (exports.SemanticTokenTypes = SemanticTokenTypes = {})); +/** + * A set of predefined token modifiers. This set is not fixed + * an clients can specify additional token types via the + * corresponding client capabilities. + * + * @since 3.16.0 + */ +var SemanticTokenModifiers; +(function (SemanticTokenModifiers) { + SemanticTokenModifiers["declaration"] = "declaration"; + SemanticTokenModifiers["definition"] = "definition"; + SemanticTokenModifiers["readonly"] = "readonly"; + SemanticTokenModifiers["static"] = "static"; + SemanticTokenModifiers["deprecated"] = "deprecated"; + SemanticTokenModifiers["abstract"] = "abstract"; + SemanticTokenModifiers["async"] = "async"; + SemanticTokenModifiers["modification"] = "modification"; + SemanticTokenModifiers["documentation"] = "documentation"; + SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; +})(SemanticTokenModifiers || (exports.SemanticTokenModifiers = SemanticTokenModifiers = {})); +/** + * @since 3.16.0 + */ +var SemanticTokens; +(function (SemanticTokens) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); + } + SemanticTokens.is = is; +})(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {})); +/** + * The InlineValueText namespace provides functions to deal with InlineValueTexts. + * + * @since 3.17.0 + */ +var InlineValueText; +(function (InlineValueText) { + /** + * Creates a new InlineValueText literal. + */ + function create(range, text) { + return { + range: range, + text: text + }; + } + InlineValueText.create = create; + function is(value) { + var candidate = value; + return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text); + } + InlineValueText.is = is; +})(InlineValueText || (exports.InlineValueText = InlineValueText = {})); +/** + * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups. + * + * @since 3.17.0 + */ +var InlineValueVariableLookup; +(function (InlineValueVariableLookup) { + /** + * Creates a new InlineValueText literal. + */ + function create(range, variableName, caseSensitiveLookup) { + return { + range: range, + variableName: variableName, + caseSensitiveLookup: caseSensitiveLookup + }; + } + InlineValueVariableLookup.create = create; + function is(value) { + var candidate = value; + return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === undefined); + } + InlineValueVariableLookup.is = is; +})(InlineValueVariableLookup || (exports.InlineValueVariableLookup = InlineValueVariableLookup = {})); +/** + * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression. + * + * @since 3.17.0 + */ +var InlineValueEvaluatableExpression; +(function (InlineValueEvaluatableExpression) { + /** + * Creates a new InlineValueEvaluatableExpression literal. + */ + function create(range, expression) { + return { + range: range, + expression: expression + }; + } + InlineValueEvaluatableExpression.create = create; + function is(value) { + var candidate = value; + return candidate !== undefined && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === undefined); + } + InlineValueEvaluatableExpression.is = is; +})(InlineValueEvaluatableExpression || (exports.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {})); +/** + * The InlineValueContext namespace provides helper functions to work with + * {@link InlineValueContext} literals. + * + * @since 3.17.0 + */ +var InlineValueContext; +(function (InlineValueContext) { + /** + * Creates a new InlineValueContext literal. + */ + function create(frameId, stoppedLocation) { + return { + frameId: frameId, + stoppedLocation: stoppedLocation + }; + } + InlineValueContext.create = create; + /** + * Checks whether the given literal conforms to the {@link InlineValueContext} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Range.is(value.stoppedLocation); + } + InlineValueContext.is = is; +})(InlineValueContext || (exports.InlineValueContext = InlineValueContext = {})); +/** + * Inlay hint kinds. + * + * @since 3.17.0 + */ +var InlayHintKind; +(function (InlayHintKind) { + /** + * An inlay hint that for a type annotation. + */ + InlayHintKind.Type = 1; + /** + * An inlay hint that is for a parameter. + */ + InlayHintKind.Parameter = 2; + function is(value) { + return value === 1 || value === 2; + } + InlayHintKind.is = is; +})(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {})); +var InlayHintLabelPart; +(function (InlayHintLabelPart) { + function create(value) { + return { + value: value + }; + } + InlayHintLabelPart.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === undefined || Location.is(candidate.location)) && (candidate.command === undefined || Command.is(candidate.command)); + } + InlayHintLabelPart.is = is; +})(InlayHintLabelPart || (exports.InlayHintLabelPart = InlayHintLabelPart = {})); +var InlayHint; +(function (InlayHint) { + function create(position, label, kind) { + var result = { + position: position, + label: label + }; + if (kind !== undefined) { + result.kind = kind; } - })); - Object.defineProperty(exports, "assertDirective", ({ - enumerable: true, - get: function () { - return _directives.assertDirective; + return result; + } + InlayHint.create = create; + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === undefined || InlayHintKind.is(candidate.kind)) && candidate.textEdits === undefined || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight)); + } + InlayHint.is = is; +})(InlayHint || (exports.InlayHint = InlayHint = {})); +var WorkspaceFolder; +(function (WorkspaceFolder) { + function is(value) { + var candidate = value; + return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); + } + WorkspaceFolder.is = is; +})(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {})); +var EOL = exports.EOL = ['\n', '\r\n', '\r']; +/** + * @deprecated Use the text document from the new vscode-languageserver-textdocument package. + */ +var TextDocument; +(function (TextDocument) { + /** + * Creates a new ITextDocument literal from the given uri and content. + * @param uri The document's uri. + * @param languageId The document's language Id. + * @param version The document's version. + * @param content The document's content. + */ + function create(uri, languageId, version, content) { + return new FullTextDocument(uri, languageId, version, content); + } + TextDocument.create = create; + /** + * Checks whether the given literal conforms to the {@link ITextDocument} interface. + */ + function is(value) { + var candidate = value; + return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; + } + TextDocument.is = is; + function applyEdits(document, edits) { + var text = document.getText(); + var sortedEdits = mergeSort(edits, function (a, b) { + var diff = a.range.start.line - b.range.start.line; + if (diff === 0) { + return a.range.start.character - b.range.start.character; + } + return diff; + }); + var lastModifiedOffset = text.length; + for (var i = sortedEdits.length - 1; i >= 0; i--) { + var e = sortedEdits[i]; + var startOffset = document.offsetAt(e.range.start); + var endOffset = document.offsetAt(e.range.end); + if (endOffset <= lastModifiedOffset) { + text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); + } else { + throw new Error('Overlapping edit'); + } + lastModifiedOffset = startOffset; } - })); - Object.defineProperty(exports, "assertEnumType", ({ - enumerable: true, - get: function () { - return _definition.assertEnumType; + return text; + } + TextDocument.applyEdits = applyEdits; + function mergeSort(data, compare) { + if (data.length <= 1) { + // sorted + return data; } - })); - Object.defineProperty(exports, "assertEnumValueName", ({ - enumerable: true, - get: function () { - return _assertName.assertEnumValueName; + var p = data.length / 2 | 0; + var left = data.slice(0, p); + var right = data.slice(p); + mergeSort(left, compare); + mergeSort(right, compare); + var leftIdx = 0; + var rightIdx = 0; + var i = 0; + while (leftIdx < left.length && rightIdx < right.length) { + var ret = compare(left[leftIdx], right[rightIdx]); + if (ret <= 0) { + // smaller_equal -> take left to preserve order + data[i++] = left[leftIdx++]; + } else { + // greater -> take right + data[i++] = right[rightIdx++]; + } } - })); - Object.defineProperty(exports, "assertInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.assertInputObjectType; + while (leftIdx < left.length) { + data[i++] = left[leftIdx++]; } - })); - Object.defineProperty(exports, "assertInputType", ({ - enumerable: true, - get: function () { - return _definition.assertInputType; + while (rightIdx < right.length) { + data[i++] = right[rightIdx++]; } - })); - Object.defineProperty(exports, "assertInterfaceType", ({ - enumerable: true, + return data; + } +})(TextDocument || (exports.TextDocument = TextDocument = {})); +/** + * @deprecated Use the text document from the new vscode-languageserver-textdocument package. + */ +var FullTextDocument = /** @class */function () { + function FullTextDocument(uri, languageId, version, content) { + this._uri = uri; + this._languageId = languageId; + this._version = version; + this._content = content; + this._lineOffsets = undefined; + } + Object.defineProperty(FullTextDocument.prototype, "uri", { get: function () { - return _definition.assertInterfaceType; - } - })); - Object.defineProperty(exports, "assertLeafType", ({ - enumerable: true, + return this._uri; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FullTextDocument.prototype, "languageId", { get: function () { - return _definition.assertLeafType; - } - })); - Object.defineProperty(exports, "assertListType", ({ - enumerable: true, + return this._languageId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(FullTextDocument.prototype, "version", { get: function () { - return _definition.assertListType; + return this._version; + }, + enumerable: false, + configurable: true + }); + FullTextDocument.prototype.getText = function (range) { + if (range) { + var start = this.offsetAt(range.start); + var end = this.offsetAt(range.end); + return this._content.substring(start, end); } - })); - Object.defineProperty(exports, "assertName", ({ - enumerable: true, - get: function () { - return _assertName.assertName; + return this._content; + }; + FullTextDocument.prototype.update = function (event, version) { + this._content = event.text; + this._version = version; + this._lineOffsets = undefined; + }; + FullTextDocument.prototype.getLineOffsets = function () { + if (this._lineOffsets === undefined) { + var lineOffsets = []; + var text = this._content; + var isLineStart = true; + for (var i = 0; i < text.length; i++) { + if (isLineStart) { + lineOffsets.push(i); + isLineStart = false; + } + var ch = text.charAt(i); + isLineStart = ch === '\r' || ch === '\n'; + if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { + i++; + } + } + if (isLineStart && text.length > 0) { + lineOffsets.push(text.length); + } + this._lineOffsets = lineOffsets; } - })); - Object.defineProperty(exports, "assertNamedType", ({ - enumerable: true, - get: function () { - return _definition.assertNamedType; + return this._lineOffsets; + }; + FullTextDocument.prototype.positionAt = function (offset) { + offset = Math.max(Math.min(offset, this._content.length), 0); + var lineOffsets = this.getLineOffsets(); + var low = 0, + high = lineOffsets.length; + if (high === 0) { + return Position.create(0, offset); + } + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (lineOffsets[mid] > offset) { + high = mid; + } else { + low = mid + 1; + } } - })); - Object.defineProperty(exports, "assertNonNullType", ({ - enumerable: true, - get: function () { - return _definition.assertNonNullType; + // low is the least x for which the line offset is larger than the current offset + // or array.length if no line offset is larger than the current offset + var line = low - 1; + return Position.create(line, offset - lineOffsets[line]); + }; + FullTextDocument.prototype.offsetAt = function (position) { + var lineOffsets = this.getLineOffsets(); + if (position.line >= lineOffsets.length) { + return this._content.length; + } else if (position.line < 0) { + return 0; } - })); - Object.defineProperty(exports, "assertNullableType", ({ - enumerable: true, + var lineOffset = lineOffsets[position.line]; + var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; + return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); + }; + Object.defineProperty(FullTextDocument.prototype, "lineCount", { get: function () { - return _definition.assertNullableType; - } - })); - Object.defineProperty(exports, "assertObjectType", ({ - enumerable: true, - get: function () { - return _definition.assertObjectType; - } - })); - Object.defineProperty(exports, "assertOutputType", ({ - enumerable: true, - get: function () { - return _definition.assertOutputType; - } - })); - Object.defineProperty(exports, "assertScalarType", ({ - enumerable: true, - get: function () { - return _definition.assertScalarType; - } - })); - Object.defineProperty(exports, "assertSchema", ({ - enumerable: true, - get: function () { - return _schema.assertSchema; - } - })); - Object.defineProperty(exports, "assertType", ({ - enumerable: true, - get: function () { - return _definition.assertType; - } - })); - Object.defineProperty(exports, "assertUnionType", ({ - enumerable: true, - get: function () { - return _definition.assertUnionType; - } - })); - Object.defineProperty(exports, "assertValidSchema", ({ - enumerable: true, - get: function () { - return _validate.assertValidSchema; - } - })); - Object.defineProperty(exports, "assertWrappingType", ({ - enumerable: true, - get: function () { - return _definition.assertWrappingType; - } - })); - Object.defineProperty(exports, "getNamedType", ({ - enumerable: true, - get: function () { - return _definition.getNamedType; - } - })); - Object.defineProperty(exports, "getNullableType", ({ - enumerable: true, - get: function () { - return _definition.getNullableType; - } - })); - Object.defineProperty(exports, "introspectionTypes", ({ - enumerable: true, - get: function () { - return _introspection.introspectionTypes; - } - })); - Object.defineProperty(exports, "isAbstractType", ({ - enumerable: true, - get: function () { - return _definition.isAbstractType; - } - })); - Object.defineProperty(exports, "isCompositeType", ({ - enumerable: true, - get: function () { - return _definition.isCompositeType; - } - })); - Object.defineProperty(exports, "isDirective", ({ - enumerable: true, - get: function () { - return _directives.isDirective; - } - })); - Object.defineProperty(exports, "isEnumType", ({ - enumerable: true, - get: function () { - return _definition.isEnumType; - } - })); - Object.defineProperty(exports, "isInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.isInputObjectType; - } - })); - Object.defineProperty(exports, "isInputType", ({ - enumerable: true, - get: function () { - return _definition.isInputType; - } - })); - Object.defineProperty(exports, "isInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.isInterfaceType; - } - })); - Object.defineProperty(exports, "isIntrospectionType", ({ - enumerable: true, - get: function () { - return _introspection.isIntrospectionType; - } - })); - Object.defineProperty(exports, "isLeafType", ({ - enumerable: true, - get: function () { - return _definition.isLeafType; - } - })); - Object.defineProperty(exports, "isListType", ({ - enumerable: true, - get: function () { - return _definition.isListType; - } - })); - Object.defineProperty(exports, "isNamedType", ({ - enumerable: true, - get: function () { - return _definition.isNamedType; - } - })); - Object.defineProperty(exports, "isNonNullType", ({ - enumerable: true, - get: function () { - return _definition.isNonNullType; - } - })); - Object.defineProperty(exports, "isNullableType", ({ - enumerable: true, - get: function () { - return _definition.isNullableType; - } - })); - Object.defineProperty(exports, "isObjectType", ({ - enumerable: true, - get: function () { - return _definition.isObjectType; - } - })); - Object.defineProperty(exports, "isOutputType", ({ - enumerable: true, - get: function () { - return _definition.isOutputType; - } - })); - Object.defineProperty(exports, "isRequiredArgument", ({ - enumerable: true, - get: function () { - return _definition.isRequiredArgument; - } - })); - Object.defineProperty(exports, "isRequiredInputField", ({ - enumerable: true, - get: function () { - return _definition.isRequiredInputField; - } - })); - Object.defineProperty(exports, "isScalarType", ({ - enumerable: true, - get: function () { - return _definition.isScalarType; - } - })); - Object.defineProperty(exports, "isSchema", ({ - enumerable: true, - get: function () { - return _schema.isSchema; - } - })); - Object.defineProperty(exports, "isSpecifiedDirective", ({ - enumerable: true, - get: function () { - return _directives.isSpecifiedDirective; - } - })); - Object.defineProperty(exports, "isSpecifiedScalarType", ({ - enumerable: true, - get: function () { - return _scalars.isSpecifiedScalarType; - } - })); - Object.defineProperty(exports, "isType", ({ - enumerable: true, - get: function () { - return _definition.isType; - } - })); - Object.defineProperty(exports, "isUnionType", ({ - enumerable: true, - get: function () { - return _definition.isUnionType; - } - })); - Object.defineProperty(exports, "isWrappingType", ({ - enumerable: true, - get: function () { - return _definition.isWrappingType; - } - })); - Object.defineProperty(exports, "resolveObjMapThunk", ({ - enumerable: true, - get: function () { - return _definition.resolveObjMapThunk; - } - })); - Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ - enumerable: true, - get: function () { - return _definition.resolveReadonlyArrayThunk; - } - })); - Object.defineProperty(exports, "specifiedDirectives", ({ - enumerable: true, - get: function () { - return _directives.specifiedDirectives; - } - })); - Object.defineProperty(exports, "specifiedScalarTypes", ({ - enumerable: true, - get: function () { - return _scalars.specifiedScalarTypes; - } - })); - Object.defineProperty(exports, "validateSchema", ({ - enumerable: true, - get: function () { - return _validate.validateSchema; - } - })); - var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); - var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); - var _assertName = __webpack_require__(/*! ./assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/type/introspection.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/type/introspection.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.introspectionTypes = exports.__TypeKind = exports.__Type = exports.__Schema = exports.__InputValue = exports.__Field = exports.__EnumValue = exports.__DirectiveLocation = exports.__Directive = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.TypeKind = exports.SchemaMetaFieldDef = void 0; - exports.isIntrospectionType = isIntrospectionType; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _directiveLocation = __webpack_require__(/*! ../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); - var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _astFromValue = __webpack_require__(/*! ../utilities/astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); - var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _scalars = __webpack_require__(/*! ./scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - const __Schema = exports.__Schema = new _definition.GraphQLObjectType({ - name: '__Schema', - description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', - fields: () => ({ - description: { - type: _scalars.GraphQLString, - resolve: schema => schema.description - }, - types: { - description: 'A list of all types supported by this server.', - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))), - resolve(schema) { - return Object.values(schema.getTypeMap()); - } - }, - queryType: { - description: 'The type that query operations will be rooted at.', - type: new _definition.GraphQLNonNull(__Type), - resolve: schema => schema.getQueryType() - }, - mutationType: { - description: 'If this server supports mutation, the type that mutation operations will be rooted at.', - type: __Type, - resolve: schema => schema.getMutationType() - }, - subscriptionType: { - description: 'If this server support subscription, the type that subscription operations will be rooted at.', - type: __Type, - resolve: schema => schema.getSubscriptionType() - }, - directives: { - description: 'A list of all directives supported by this server.', - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))), - resolve: schema => schema.getDirectives() - } - }) - }); - const __Directive = exports.__Directive = new _definition.GraphQLObjectType({ - name: '__Directive', - description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: directive => directive.name - }, - description: { - type: _scalars.GraphQLString, - resolve: directive => directive.description - }, - isRepeatable: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: directive => directive.isRepeatable - }, - locations: { - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation))), - resolve: directive => directive.locations - }, - args: { - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false - } - }, - resolve(field, { - includeDeprecated - }) { - return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); - } - } - }) - }); - const __DirectiveLocation = exports.__DirectiveLocation = new _definition.GraphQLEnumType({ - name: '__DirectiveLocation', - description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', - values: { - QUERY: { - value: _directiveLocation.DirectiveLocation.QUERY, - description: 'Location adjacent to a query operation.' - }, - MUTATION: { - value: _directiveLocation.DirectiveLocation.MUTATION, - description: 'Location adjacent to a mutation operation.' - }, - SUBSCRIPTION: { - value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, - description: 'Location adjacent to a subscription operation.' - }, - FIELD: { - value: _directiveLocation.DirectiveLocation.FIELD, - description: 'Location adjacent to a field.' - }, - FRAGMENT_DEFINITION: { - value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, - description: 'Location adjacent to a fragment definition.' - }, - FRAGMENT_SPREAD: { - value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, - description: 'Location adjacent to a fragment spread.' - }, - INLINE_FRAGMENT: { - value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, - description: 'Location adjacent to an inline fragment.' - }, - VARIABLE_DEFINITION: { - value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, - description: 'Location adjacent to a variable definition.' - }, - SCHEMA: { - value: _directiveLocation.DirectiveLocation.SCHEMA, - description: 'Location adjacent to a schema definition.' - }, - SCALAR: { - value: _directiveLocation.DirectiveLocation.SCALAR, - description: 'Location adjacent to a scalar definition.' - }, - OBJECT: { - value: _directiveLocation.DirectiveLocation.OBJECT, - description: 'Location adjacent to an object type definition.' - }, - FIELD_DEFINITION: { - value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, - description: 'Location adjacent to a field definition.' - }, - ARGUMENT_DEFINITION: { - value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, - description: 'Location adjacent to an argument definition.' - }, - INTERFACE: { - value: _directiveLocation.DirectiveLocation.INTERFACE, - description: 'Location adjacent to an interface definition.' - }, - UNION: { - value: _directiveLocation.DirectiveLocation.UNION, - description: 'Location adjacent to a union definition.' - }, - ENUM: { - value: _directiveLocation.DirectiveLocation.ENUM, - description: 'Location adjacent to an enum definition.' - }, - ENUM_VALUE: { - value: _directiveLocation.DirectiveLocation.ENUM_VALUE, - description: 'Location adjacent to an enum value definition.' - }, - INPUT_OBJECT: { - value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, - description: 'Location adjacent to an input object type definition.' - }, - INPUT_FIELD_DEFINITION: { - value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, - description: 'Location adjacent to an input object field definition.' - } - } - }); - const __Type = exports.__Type = new _definition.GraphQLObjectType({ - name: '__Type', - description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', - fields: () => ({ - kind: { - type: new _definition.GraphQLNonNull(__TypeKind), - resolve(type) { - if ((0, _definition.isScalarType)(type)) { - return TypeKind.SCALAR; - } - if ((0, _definition.isObjectType)(type)) { - return TypeKind.OBJECT; - } - if ((0, _definition.isInterfaceType)(type)) { - return TypeKind.INTERFACE; - } - if ((0, _definition.isUnionType)(type)) { - return TypeKind.UNION; - } - if ((0, _definition.isEnumType)(type)) { - return TypeKind.ENUM; - } - if ((0, _definition.isInputObjectType)(type)) { - return TypeKind.INPUT_OBJECT; - } - if ((0, _definition.isListType)(type)) { - return TypeKind.LIST; - } - if ((0, _definition.isNonNullType)(type)) { - return TypeKind.NON_NULL; - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered) - - false || (0, _invariant.invariant)(false, `Unexpected type: "${(0, _inspect.inspect)(type)}".`); - } - }, - name: { - type: _scalars.GraphQLString, - resolve: type => 'name' in type ? type.name : undefined - }, - description: { - type: _scalars.GraphQLString, - resolve: (type // FIXME: add test case - ) => /* c8 ignore next */ - 'description' in type ? type.description : undefined - }, - specifiedByURL: { - type: _scalars.GraphQLString, - resolve: obj => 'specifiedByURL' in obj ? obj.specifiedByURL : undefined - }, - fields: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false - } - }, - resolve(type, { - includeDeprecated - }) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { - const fields = Object.values(type.getFields()); - return includeDeprecated ? fields : fields.filter(field => field.deprecationReason == null); - } - } - }, - interfaces: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), - resolve(type) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { - return type.getInterfaces(); - } - } - }, - possibleTypes: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), - resolve(type, _args, _context, { - schema - }) { - if ((0, _definition.isAbstractType)(type)) { - return schema.getPossibleTypes(type); - } - } - }, - enumValues: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false - } - }, - resolve(type, { - includeDeprecated - }) { - if ((0, _definition.isEnumType)(type)) { - const values = type.getValues(); - return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); - } - } - }, - inputFields: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false - } - }, - resolve(type, { - includeDeprecated - }) { - if ((0, _definition.isInputObjectType)(type)) { - const values = Object.values(type.getFields()); - return includeDeprecated ? values : values.filter(field => field.deprecationReason == null); - } - } - }, - ofType: { - type: __Type, - resolve: type => 'ofType' in type ? type.ofType : undefined - } - }) + return this.getLineOffsets().length; + }, + enumerable: false, + configurable: true }); - const __Field = exports.__Field = new _definition.GraphQLObjectType({ - name: '__Field', - description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: field => field.name - }, - description: { - type: _scalars.GraphQLString, - resolve: field => field.description - }, - args: { - type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false - } - }, - resolve(field, { - includeDeprecated - }) { - return includeDeprecated ? field.args : field.args.filter(arg => arg.deprecationReason == null); - } - }, - type: { - type: new _definition.GraphQLNonNull(__Type), - resolve: field => field.type - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: field => field.deprecationReason != null - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: field => field.deprecationReason - } - }) - }); - const __InputValue = exports.__InputValue = new _definition.GraphQLObjectType({ - name: '__InputValue', - description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: inputValue => inputValue.name - }, - description: { - type: _scalars.GraphQLString, - resolve: inputValue => inputValue.description - }, - type: { - type: new _definition.GraphQLNonNull(__Type), - resolve: inputValue => inputValue.type - }, - defaultValue: { - type: _scalars.GraphQLString, - description: 'A GraphQL-formatted string representing the default value for this input value.', - resolve(inputValue) { - const { - type, - defaultValue - } = inputValue; - const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); - return valueAST ? (0, _printer.print)(valueAST) : null; - } - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: field => field.deprecationReason != null - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: obj => obj.deprecationReason - } - }) - }); - const __EnumValue = exports.__EnumValue = new _definition.GraphQLObjectType({ - name: '__EnumValue', - description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: enumValue => enumValue.name - }, - description: { - type: _scalars.GraphQLString, - resolve: enumValue => enumValue.description - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: enumValue => enumValue.deprecationReason != null - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: enumValue => enumValue.deprecationReason - } - }) - }); - var TypeKind; - (function (TypeKind) { - TypeKind['SCALAR'] = 'SCALAR'; - TypeKind['OBJECT'] = 'OBJECT'; - TypeKind['INTERFACE'] = 'INTERFACE'; - TypeKind['UNION'] = 'UNION'; - TypeKind['ENUM'] = 'ENUM'; - TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; - TypeKind['LIST'] = 'LIST'; - TypeKind['NON_NULL'] = 'NON_NULL'; - })(TypeKind || (exports.TypeKind = TypeKind = {})); - const __TypeKind = exports.__TypeKind = new _definition.GraphQLEnumType({ - name: '__TypeKind', - description: 'An enum describing what kind of type a given `__Type` is.', - values: { - SCALAR: { - value: TypeKind.SCALAR, - description: 'Indicates this type is a scalar.' - }, - OBJECT: { - value: TypeKind.OBJECT, - description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.' - }, - INTERFACE: { - value: TypeKind.INTERFACE, - description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.' - }, - UNION: { - value: TypeKind.UNION, - description: 'Indicates this type is a union. `possibleTypes` is a valid field.' - }, - ENUM: { - value: TypeKind.ENUM, - description: 'Indicates this type is an enum. `enumValues` is a valid field.' - }, - INPUT_OBJECT: { - value: TypeKind.INPUT_OBJECT, - description: 'Indicates this type is an input object. `inputFields` is a valid field.' - }, - LIST: { - value: TypeKind.LIST, - description: 'Indicates this type is a list. `ofType` is a valid field.' - }, - NON_NULL: { - value: TypeKind.NON_NULL, - description: 'Indicates this type is a non-null. `ofType` is a valid field.' - } - } - }); - /** - * Note that these are GraphQLField and not GraphQLFieldConfig, - * so the format for args is different. - */ - - const SchemaMetaFieldDef = exports.SchemaMetaFieldDef = { - name: '__schema', - type: new _definition.GraphQLNonNull(__Schema), - description: 'Access the current type schema of this server.', - args: [], - resolve: (_source, _args, _context, { - schema - }) => schema, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined - }; - const TypeMetaFieldDef = exports.TypeMetaFieldDef = { - name: '__type', - type: __Type, - description: 'Request the type information of a single type.', - args: [{ - name: 'name', - description: undefined, - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - defaultValue: undefined, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined - }], - resolve: (_source, { - name - }, _context, { - schema - }) => schema.getType(name), - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined - }; - const TypeNameMetaFieldDef = exports.TypeNameMetaFieldDef = { - name: '__typename', - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - description: 'The name of the current Object type at runtime.', - args: [], - resolve: (_source, _args, _context, { - parentType - }) => parentType.name, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined - }; - const introspectionTypes = exports.introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]); - function isIntrospectionType(type) { - return introspectionTypes.some(({ - name - }) => type.name === name); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/scalars.mjs": - /*!******************************************************!*\ - !*** ../../../node_modules/graphql/type/scalars.mjs ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.GraphQLString = exports.GraphQLInt = exports.GraphQLID = exports.GraphQLFloat = exports.GraphQLBoolean = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = void 0; - exports.isSpecifiedScalarType = isSpecifiedScalarType; - exports.specifiedScalarTypes = void 0; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). - * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 - * */ - - const GRAPHQL_MAX_INT = exports.GRAPHQL_MAX_INT = 2147483647; - /** - * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). - * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) - * */ - - const GRAPHQL_MIN_INT = exports.GRAPHQL_MIN_INT = -2147483648; - const GraphQLInt = exports.GraphQLInt = new _definition.GraphQLScalarType({ - name: 'Int', - description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue ? 1 : 0; - } - let num = coercedValue; - if (typeof coercedValue === 'string' && coercedValue !== '') { - num = Number(coercedValue); - } - if (typeof num !== 'number' || !Number.isInteger(num)) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(coercedValue)}`); - } - if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError('Int cannot represent non 32-bit signed integer value: ' + (0, _inspect.inspect)(coercedValue)); - } - return num; - }, - parseValue(inputValue) { - if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _inspect.inspect)(inputValue)}`); - } - if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${inputValue}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non-integer value: ${(0, _printer.print)(valueNode)}`, { - nodes: valueNode - }); - } - const num = parseInt(valueNode.value, 10); - if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, { - nodes: valueNode - }); - } - return num; - } - }); - const GraphQLFloat = exports.GraphQLFloat = new _definition.GraphQLScalarType({ - name: 'Float', - description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue ? 1 : 0; - } - let num = coercedValue; - if (typeof coercedValue === 'string' && coercedValue !== '') { - num = Number(coercedValue); - } - if (typeof num !== 'number' || !Number.isFinite(num)) { - throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(coercedValue)}`); - } - return num; - }, - parseValue(inputValue) { - if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { - throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _inspect.inspect)(inputValue)}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.FLOAT && valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError(`Float cannot represent non numeric value: ${(0, _printer.print)(valueNode)}`, valueNode); - } - return parseFloat(valueNode.value); - } - }); - const GraphQLString = exports.GraphQLString = new _definition.GraphQLScalarType({ - name: 'String', - description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not - // attempt to coerce object, function, symbol, or other types as strings. - - if (typeof coercedValue === 'string') { - return coercedValue; - } - if (typeof coercedValue === 'boolean') { - return coercedValue ? 'true' : 'false'; - } - if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { - return coercedValue.toString(); - } - throw new _GraphQLError.GraphQLError(`String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); - }, - parseValue(inputValue) { - if (typeof inputValue !== 'string') { - throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _inspect.inspect)(inputValue)}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.STRING) { - throw new _GraphQLError.GraphQLError(`String cannot represent a non string value: ${(0, _printer.print)(valueNode)}`, { - nodes: valueNode - }); - } - return valueNode.value; - } - }); - const GraphQLBoolean = exports.GraphQLBoolean = new _definition.GraphQLScalarType({ - name: 'Boolean', - description: 'The `Boolean` scalar type represents `true` or `false`.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue; - } - if (Number.isFinite(coercedValue)) { - return coercedValue !== 0; - } - throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(coercedValue)}`); - }, - parseValue(inputValue) { - if (typeof inputValue !== 'boolean') { - throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)(inputValue)}`); - } - return inputValue; - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.BOOLEAN) { - throw new _GraphQLError.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, _printer.print)(valueNode)}`, { - nodes: valueNode - }); - } - return valueNode.value; - } - }); - const GraphQLID = exports.GraphQLID = new _definition.GraphQLScalarType({ - name: 'ID', - description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'string') { - return coercedValue; - } - if (Number.isInteger(coercedValue)) { - return String(coercedValue); - } - throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`); - }, - parseValue(inputValue) { - if (typeof inputValue === 'string') { - return inputValue; - } - if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { - return inputValue.toString(); - } - throw new _GraphQLError.GraphQLError(`ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`); - }, - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.STRING && valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError('ID cannot represent a non-string and non-integer value: ' + (0, _printer.print)(valueNode), { - nodes: valueNode - }); - } - return valueNode.value; - } - }); - const specifiedScalarTypes = exports.specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]); - function isSpecifiedScalarType(type) { - return specifiedScalarTypes.some(({ - name - }) => type.name === name); - } // Support serializing objects with custom valueOf() or toJSON() functions - - // a common way to represent a complex value which can be represented as - // a string (ex: MongoDB id objects). - - function serializeObject(outputValue) { - if ((0, _isObjectLike.isObjectLike)(outputValue)) { - if (typeof outputValue.valueOf === 'function') { - const valueOfResult = outputValue.valueOf(); - if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { - return valueOfResult; - } - } - if (typeof outputValue.toJSON === 'function') { - return outputValue.toJSON(); - } - } - return outputValue; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/schema.mjs": - /*!*****************************************************!*\ - !*** ../../../node_modules/graphql/type/schema.mjs ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.GraphQLSchema = void 0; - exports.assertSchema = assertSchema; - exports.isSchema = isSchema; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _instanceOf = __webpack_require__(/*! ../jsutils/instanceOf.mjs */ "../../../node_modules/graphql/jsutils/instanceOf.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _toObjMap = __webpack_require__(/*! ../jsutils/toObjMap.mjs */ "../../../node_modules/graphql/jsutils/toObjMap.mjs"); - var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - /** - * Test if the given value is a GraphQL schema. - */ - - function isSchema(schema) { - return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); - } - function assertSchema(schema) { - if (!isSchema(schema)) { - throw new Error(`Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`); - } - return schema; - } - /** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ - - /** - * Schema Definition - * - * A Schema is created by supplying the root types of each type of operation, - * query and mutation (optional). A schema definition is then supplied to the - * validator and executor. - * - * Example: - * - * ```ts - * const MyAppSchema = new GraphQLSchema({ - * query: MyAppQueryRootType, - * mutation: MyAppMutationRootType, - * }) - * ``` - * - * Note: When the schema is constructed, by default only the types that are - * reachable by traversing the root types are included, other types must be - * explicitly referenced. - * - * Example: - * - * ```ts - * const characterInterface = new GraphQLInterfaceType({ - * name: 'Character', - * ... - * }); - * - * const humanType = new GraphQLObjectType({ - * name: 'Human', - * interfaces: [characterInterface], - * ... - * }); - * - * const droidType = new GraphQLObjectType({ - * name: 'Droid', - * interfaces: [characterInterface], - * ... - * }); - * - * const schema = new GraphQLSchema({ - * query: new GraphQLObjectType({ - * name: 'Query', - * fields: { - * hero: { type: characterInterface, ... }, - * } - * }), - * ... - * // Since this schema references only the `Character` interface it's - * // necessary to explicitly list the types that implement it if - * // you want them to be included in the final schema. - * types: [humanType, droidType], - * }) - * ``` - * - * Note: If an array of `directives` are provided to GraphQLSchema, that will be - * the exact list of directives represented and allowed. If `directives` is not - * provided then a default set of the specified directives (e.g. `@include` and - * `@skip`) will be used. If you wish to provide *additional* directives to these - * specified directives, you must explicitly declare them. Example: - * - * ```ts - * const MyAppSchema = new GraphQLSchema({ - * ... - * directives: specifiedDirectives.concat([ myCustomDirective ]), - * }) - * ``` - */ - class GraphQLSchema { - // Used as a cache for validateSchema(). - constructor(config) { - var _config$extensionASTN, _config$directives; - - // If this schema was built from a source known to be valid, then it may be - // marked with assumeValid to avoid an additional type system validation. - this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. - - (0, _isObjectLike.isObjectLike)(config) || (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); - !config.types || Array.isArray(config.types) || (0, _devAssert.devAssert)(false, `"types" must be Array if provided but got: ${(0, _inspect.inspect)(config.types)}.`); - !config.directives || Array.isArray(config.directives) || (0, _devAssert.devAssert)(false, '"directives" must be Array if provided but got: ' + `${(0, _inspect.inspect)(config.directives)}.`); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : []; - this._queryType = config.query; - this._mutationType = config.mutation; - this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. - - this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to - // the set of "collected" types, so `collectReferencedTypes` ignore them. - - const allReferencedTypes = new Set(config.types); - if (config.types != null) { - for (const type of config.types) { - // When we ready to process this type, we remove it from "collected" types - // and then add it together with all dependent types in the correct position. - allReferencedTypes.delete(type); - collectReferencedTypes(type, allReferencedTypes); - } - } - if (this._queryType != null) { - collectReferencedTypes(this._queryType, allReferencedTypes); - } - if (this._mutationType != null) { - collectReferencedTypes(this._mutationType, allReferencedTypes); - } - if (this._subscriptionType != null) { - collectReferencedTypes(this._subscriptionType, allReferencedTypes); - } - for (const directive of this._directives) { - // Directives are not validated until validateSchema() is called. - if ((0, _directives.isDirective)(directive)) { - for (const arg of directive.args) { - collectReferencedTypes(arg.type, allReferencedTypes); - } - } - } - collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. - - this._typeMap = Object.create(null); - this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. - - this._implementationsMap = Object.create(null); - for (const namedType of allReferencedTypes) { - if (namedType == null) { - continue; - } - const typeName = namedType.name; - typeName || (0, _devAssert.devAssert)(false, 'One of the provided types for building the Schema is missing a name.'); - if (this._typeMap[typeName] !== undefined) { - throw new Error(`Schema must contain uniquely named types but contains multiple types named "${typeName}".`); - } - this._typeMap[typeName] = namedType; - if ((0, _definition.isInterfaceType)(namedType)) { - // Store implementations by interface. - for (const iface of namedType.getInterfaces()) { - if ((0, _definition.isInterfaceType)(iface)) { - let implementations = this._implementationsMap[iface.name]; - if (implementations === undefined) { - implementations = this._implementationsMap[iface.name] = { - objects: [], - interfaces: [] - }; - } - implementations.interfaces.push(namedType); - } - } - } else if ((0, _definition.isObjectType)(namedType)) { - // Store implementations by objects. - for (const iface of namedType.getInterfaces()) { - if ((0, _definition.isInterfaceType)(iface)) { - let implementations = this._implementationsMap[iface.name]; - if (implementations === undefined) { - implementations = this._implementationsMap[iface.name] = { - objects: [], - interfaces: [] - }; - } - implementations.objects.push(namedType); - } - } - } - } - } - get [Symbol.toStringTag]() { - return 'GraphQLSchema'; - } - getQueryType() { - return this._queryType; - } - getMutationType() { - return this._mutationType; - } - getSubscriptionType() { - return this._subscriptionType; - } - getRootType(operation) { - switch (operation) { - case _ast.OperationTypeNode.QUERY: - return this.getQueryType(); - case _ast.OperationTypeNode.MUTATION: - return this.getMutationType(); - case _ast.OperationTypeNode.SUBSCRIPTION: - return this.getSubscriptionType(); - } - } - getTypeMap() { - return this._typeMap; - } - getType(name) { - return this.getTypeMap()[name]; - } - getPossibleTypes(abstractType) { - return (0, _definition.isUnionType)(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; - } - getImplementations(interfaceType) { - const implementations = this._implementationsMap[interfaceType.name]; - return implementations !== null && implementations !== void 0 ? implementations : { - objects: [], - interfaces: [] - }; - } - isSubType(abstractType, maybeSubType) { - let map = this._subTypeMap[abstractType.name]; - if (map === undefined) { - map = Object.create(null); - if ((0, _definition.isUnionType)(abstractType)) { - for (const type of abstractType.getTypes()) { - map[type.name] = true; - } - } else { - const implementations = this.getImplementations(abstractType); - for (const type of implementations.objects) { - map[type.name] = true; - } - for (const type of implementations.interfaces) { - map[type.name] = true; - } - } - this._subTypeMap[abstractType.name] = map; - } - return map[maybeSubType.name] !== undefined; - } - getDirectives() { - return this._directives; - } - getDirective(name) { - return this.getDirectives().find(directive => directive.name === name); - } - toConfig() { - return { - description: this.description, - query: this.getQueryType(), - mutation: this.getMutationType(), - subscription: this.getSubscriptionType(), - types: Object.values(this.getTypeMap()), - directives: this.getDirectives(), - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - assumeValid: this.__validationErrors !== undefined - }; - } - } - exports.GraphQLSchema = GraphQLSchema; - function collectReferencedTypes(type, typeSet) { - const namedType = (0, _definition.getNamedType)(type); - if (!typeSet.has(namedType)) { - typeSet.add(namedType); - if ((0, _definition.isUnionType)(namedType)) { - for (const memberType of namedType.getTypes()) { - collectReferencedTypes(memberType, typeSet); - } - } else if ((0, _definition.isObjectType)(namedType) || (0, _definition.isInterfaceType)(namedType)) { - for (const interfaceType of namedType.getInterfaces()) { - collectReferencedTypes(interfaceType, typeSet); - } - for (const field of Object.values(namedType.getFields())) { - collectReferencedTypes(field.type, typeSet); - for (const arg of field.args) { - collectReferencedTypes(arg.type, typeSet); - } - } - } else if ((0, _definition.isInputObjectType)(namedType)) { - for (const field of Object.values(namedType.getFields())) { - collectReferencedTypes(field.type, typeSet); - } - } - } - return typeSet; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/type/validate.mjs": - /*!*******************************************************!*\ - !*** ../../../node_modules/graphql/type/validate.mjs ***! - \*******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.assertValidSchema = assertValidSchema; - exports.validateSchema = validateSchema; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _typeComparators = __webpack_require__(/*! ../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); - var _definition = __webpack_require__(/*! ./definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ./directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _introspection = __webpack_require__(/*! ./introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _schema = __webpack_require__(/*! ./schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); - /** - * Implements the "Type Validation" sub-sections of the specification's - * "Type System" section. - * - * Validation runs synchronously, returning an array of encountered errors, or - * an empty array if no errors were encountered and the Schema is valid. - */ - - function validateSchema(schema) { - // First check to ensure the provided value is in fact a GraphQLSchema. - (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. - - if (schema.__validationErrors) { - return schema.__validationErrors; - } // Validate the schema, producing a list of errors. - - const context = new SchemaValidationContext(schema); - validateRootTypes(context); - validateDirectives(context); - validateTypes(context); // Persist the results of validation before returning to ensure validation - // does not run multiple times for this schema. - - const errors = context.getErrors(); - schema.__validationErrors = errors; - return errors; - } - /** - * Utility function which asserts a schema is valid by throwing an error if - * it is invalid. - */ - - function assertValidSchema(schema) { - const errors = validateSchema(schema); - if (errors.length !== 0) { - throw new Error(errors.map(error => error.message).join('\n\n')); - } - } - class SchemaValidationContext { - constructor(schema) { - this._errors = []; - this.schema = schema; - } - reportError(message, nodes) { - const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; - this._errors.push(new _GraphQLError.GraphQLError(message, { - nodes: _nodes - })); - } - getErrors() { - return this._errors; - } - } - function validateRootTypes(context) { - const schema = context.schema; - const queryType = schema.getQueryType(); - if (!queryType) { - context.reportError('Query root type must be provided.', schema.astNode); - } else if (!(0, _definition.isObjectType)(queryType)) { - var _getOperationTypeNode; - context.reportError(`Query root type must be Object type, it cannot be ${(0, _inspect.inspect)(queryType)}.`, (_getOperationTypeNode = getOperationTypeNode(schema, _ast.OperationTypeNode.QUERY)) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode); - } - const mutationType = schema.getMutationType(); - if (mutationType && !(0, _definition.isObjectType)(mutationType)) { - var _getOperationTypeNode2; - context.reportError('Mutation root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(mutationType)}.`, (_getOperationTypeNode2 = getOperationTypeNode(schema, _ast.OperationTypeNode.MUTATION)) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode); - } - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { - var _getOperationTypeNode3; - context.reportError('Subscription root type must be Object type if provided, it cannot be ' + `${(0, _inspect.inspect)(subscriptionType)}.`, (_getOperationTypeNode3 = getOperationTypeNode(schema, _ast.OperationTypeNode.SUBSCRIPTION)) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode); - } - } - function getOperationTypeNode(schema, operation) { - var _flatMap$find; - return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes].flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - schemaNode => { - var _schemaNode$operation; - return /* c8 ignore next */( - (_schemaNode$operation = schemaNode === null || schemaNode === void 0 ? void 0 : schemaNode.operationTypes) !== null && _schemaNode$operation !== void 0 ? _schemaNode$operation : [] - ); - }).find(operationNode => operationNode.operation === operation)) === null || _flatMap$find === void 0 ? void 0 : _flatMap$find.type; - } - function validateDirectives(context) { - for (const directive of context.schema.getDirectives()) { - // Ensure all directives are in fact GraphQL directives. - if (!(0, _directives.isDirective)(directive)) { - context.reportError(`Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, directive === null || directive === void 0 ? void 0 : directive.astNode); - continue; - } // Ensure they are named correctly. - - validateName(context, directive); // TODO: Ensure proper locations. - // Ensure the arguments are valid. - - for (const arg of directive.args) { - // Ensure they are named correctly. - validateName(context, arg); // Ensure the type is an input type. - - if (!(0, _definition.isInputType)(arg.type)) { - context.reportError(`The type of @${directive.name}(${arg.name}:) must be Input Type ` + `but got: ${(0, _inspect.inspect)(arg.type)}.`, arg.astNode); - } - if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { - var _arg$astNode; - context.reportError(`Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type]); - } - } - } - } - function validateName(context, node) { - // Ensure names are valid, however introspection types opt out. - if (node.name.startsWith('__')) { - context.reportError(`Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, node.astNode); - } - } - function validateTypes(context) { - const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context); - const typeMap = context.schema.getTypeMap(); - for (const type of Object.values(typeMap)) { - // Ensure all provided types are in fact GraphQL type. - if (!(0, _definition.isNamedType)(type)) { - context.reportError(`Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, type.astNode); - continue; - } // Ensure it is named correctly (excluding introspection types). - - if (!(0, _introspection.isIntrospectionType)(type)) { - validateName(context, type); - } - if ((0, _definition.isObjectType)(type)) { - // Ensure fields are valid - validateFields(context, type); // Ensure objects implement the interfaces they claim to. - - validateInterfaces(context, type); - } else if ((0, _definition.isInterfaceType)(type)) { - // Ensure fields are valid. - validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. - - validateInterfaces(context, type); - } else if ((0, _definition.isUnionType)(type)) { - // Ensure Unions include valid member types. - validateUnionMembers(context, type); - } else if ((0, _definition.isEnumType)(type)) { - // Ensure Enums have valid values. - validateEnumValues(context, type); - } else if ((0, _definition.isInputObjectType)(type)) { - // Ensure Input Object fields are valid. - validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references - - validateInputObjectCircularRefs(type); - } - } - } - function validateFields(context, type) { - const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. - - if (fields.length === 0) { - context.reportError(`Type ${type.name} must define one or more fields.`, [type.astNode, ...type.extensionASTNodes]); - } - for (const field of fields) { - // Ensure they are named correctly. - validateName(context, field); // Ensure the type is an output type - - if (!(0, _definition.isOutputType)(field.type)) { - var _field$astNode; - context.reportError(`The type of ${type.name}.${field.name} must be Output Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type); - } // Ensure the arguments are valid - - for (const arg of field.args) { - const argName = arg.name; // Ensure they are named correctly. - - validateName(context, arg); // Ensure the type is an input type - - if (!(0, _definition.isInputType)(arg.type)) { - var _arg$astNode2; - context.reportError(`The type of ${type.name}.${field.name}(${argName}:) must be Input ` + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type); - } - if ((0, _definition.isRequiredArgument)(arg) && arg.deprecationReason != null) { - var _arg$astNode3; - context.reportError(`Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, [getDeprecatedDirectiveNode(arg.astNode), (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type]); - } - } - } - } - function validateInterfaces(context, type) { - const ifaceTypeNames = Object.create(null); - for (const iface of type.getInterfaces()) { - if (!(0, _definition.isInterfaceType)(iface)) { - context.reportError(`Type ${(0, _inspect.inspect)(type)} must only implement Interface types, ` + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, getAllImplementsInterfaceNodes(type, iface)); - continue; - } - if (type === iface) { - context.reportError(`Type ${type.name} cannot implement itself because it would create a circular reference.`, getAllImplementsInterfaceNodes(type, iface)); - continue; - } - if (ifaceTypeNames[iface.name]) { - context.reportError(`Type ${type.name} can only implement ${iface.name} once.`, getAllImplementsInterfaceNodes(type, iface)); - continue; - } - ifaceTypeNames[iface.name] = true; - validateTypeImplementsAncestors(context, type, iface); - validateTypeImplementsInterface(context, type, iface); - } - } - function validateTypeImplementsInterface(context, type, iface) { - const typeFieldMap = type.getFields(); // Assert each interface field is implemented. - - for (const ifaceField of Object.values(iface.getFields())) { - const fieldName = ifaceField.name; - const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. - - if (!typeField) { - context.reportError(`Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, [ifaceField.astNode, type.astNode, ...type.extensionASTNodes]); - continue; - } // Assert interface field type is satisfied by type field type, by being - // a valid subtype. (covariant) - - if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, typeField.type, ifaceField.type)) { - var _ifaceField$astNode, _typeField$astNode; - context.reportError(`Interface field ${iface.name}.${fieldName} expects type ` + `${(0, _inspect.inspect)(ifaceField.type)} but ${type.name}.${fieldName} ` + `is type ${(0, _inspect.inspect)(typeField.type)}.`, [(_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]); - } // Assert each interface field arg is implemented. - - for (const ifaceArg of ifaceField.args) { - const argName = ifaceArg.name; - const typeArg = typeField.args.find(arg => arg.name === argName); // Assert interface field arg exists on object field. - - if (!typeArg) { - context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, [ifaceArg.astNode, typeField.astNode]); - continue; - } // Assert interface field arg type matches object field arg type. - // (invariant) - // TODO: change to contravariant? - - if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { - var _ifaceArg$astNode, _typeArg$astNode; - context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + `${type.name}.${fieldName}(${argName}:) is type ` + `${(0, _inspect.inspect)(typeArg.type)}.`, [(_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]); - } // TODO: validate default values? - } // Assert additional arguments must not be required. - - for (const typeArg of typeField.args) { - const argName = typeArg.name; - const ifaceArg = ifaceField.args.find(arg => arg.name === argName); - if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { - context.reportError(`Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, [typeArg.astNode, ifaceField.astNode]); - } - } - } - } - function validateTypeImplementsAncestors(context, type, iface) { - const ifaceInterfaces = type.getInterfaces(); - for (const transitive of iface.getInterfaces()) { - if (!ifaceInterfaces.includes(transitive)) { - context.reportError(transitive === type ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, [...getAllImplementsInterfaceNodes(iface, transitive), ...getAllImplementsInterfaceNodes(type, iface)]); - } - } - } - function validateUnionMembers(context, union) { - const memberTypes = union.getTypes(); - if (memberTypes.length === 0) { - context.reportError(`Union type ${union.name} must define one or more member types.`, [union.astNode, ...union.extensionASTNodes]); - } - const includedTypeNames = Object.create(null); - for (const memberType of memberTypes) { - if (includedTypeNames[memberType.name]) { - context.reportError(`Union type ${union.name} can only include type ${memberType.name} once.`, getUnionMemberTypeNodes(union, memberType.name)); - continue; - } - includedTypeNames[memberType.name] = true; - if (!(0, _definition.isObjectType)(memberType)) { - context.reportError(`Union type ${union.name} can only include Object types, ` + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, getUnionMemberTypeNodes(union, String(memberType))); - } - } - } - function validateEnumValues(context, enumType) { - const enumValues = enumType.getValues(); - if (enumValues.length === 0) { - context.reportError(`Enum type ${enumType.name} must define one or more values.`, [enumType.astNode, ...enumType.extensionASTNodes]); - } - for (const enumValue of enumValues) { - // Ensure valid name. - validateName(context, enumValue); - } - } - function validateInputFields(context, inputObj) { - const fields = Object.values(inputObj.getFields()); - if (fields.length === 0) { - context.reportError(`Input Object type ${inputObj.name} must define one or more fields.`, [inputObj.astNode, ...inputObj.extensionASTNodes]); - } // Ensure the arguments are valid - - for (const field of fields) { - // Ensure they are named correctly. - validateName(context, field); // Ensure the type is an input type - - if (!(0, _definition.isInputType)(field.type)) { - var _field$astNode2; - context.reportError(`The type of ${inputObj.name}.${field.name} must be Input Type ` + `but got: ${(0, _inspect.inspect)(field.type)}.`, (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type); - } - if ((0, _definition.isRequiredInputField)(field) && field.deprecationReason != null) { - var _field$astNode3; - context.reportError(`Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, [getDeprecatedDirectiveNode(field.astNode), (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type]); - } - } - } - function createInputObjectCircularRefsValidator(context) { - // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. - // Tracks already visited types to maintain O(N) and to ensure that cycles - // are not redundantly reported. - const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors - - const fieldPath = []; // Position in the type path - - const fieldPathIndexByTypeName = Object.create(null); - return detectCycleRecursive; // This does a straight-forward DFS to find cycles. - // It does not terminate when a cycle was found but continues to explore - // the graph to find all possible cycles. - - function detectCycleRecursive(inputObj) { - if (visitedTypes[inputObj.name]) { - return; - } - visitedTypes[inputObj.name] = true; - fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; - const fields = Object.values(inputObj.getFields()); - for (const field of fields) { - if ((0, _definition.isNonNullType)(field.type) && (0, _definition.isInputObjectType)(field.type.ofType)) { - const fieldType = field.type.ofType; - const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; - fieldPath.push(field); - if (cycleIndex === undefined) { - detectCycleRecursive(fieldType); - } else { - const cyclePath = fieldPath.slice(cycleIndex); - const pathStr = cyclePath.map(fieldObj => fieldObj.name).join('.'); - context.reportError(`Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, cyclePath.map(fieldObj => fieldObj.astNode)); - } - fieldPath.pop(); - } - } - fieldPathIndexByTypeName[inputObj.name] = undefined; - } - } - function getAllImplementsInterfaceNodes(type, iface) { - const { - astNode, - extensionASTNodes - } = type; - const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - return nodes.flatMap(typeNode => { - var _typeNode$interfaces; - return /* c8 ignore next */( - (_typeNode$interfaces = typeNode.interfaces) !== null && _typeNode$interfaces !== void 0 ? _typeNode$interfaces : [] - ); - }).filter(ifaceNode => ifaceNode.name.value === iface.name); - } - function getUnionMemberTypeNodes(union, typeName) { - const { - astNode, - extensionASTNodes - } = union; - const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - return nodes.flatMap(unionNode => { - var _unionNode$types; - return /* c8 ignore next */( - (_unionNode$types = unionNode.types) !== null && _unionNode$types !== void 0 ? _unionNode$types : [] - ); - }).filter(typeNode => typeNode.name.value === typeName); - } - function getDeprecatedDirectiveNode(definitionNode) { - var _definitionNode$direc; - return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(node => node.name.value === _directives.GraphQLDeprecatedDirective.name); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/TypeInfo.mjs": - /*!************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/TypeInfo.mjs ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.TypeInfo = void 0; - exports.visitWithTypeInfo = visitWithTypeInfo; - var _ast = __webpack_require__(/*! ../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - /** - * TypeInfo is a utility class which, given a GraphQL schema, can keep track - * of the current field and type definitions at any point in a GraphQL document - * AST during a recursive descent by calling `enter(node)` and `leave(node)`. - */ - - class TypeInfo { - constructor(schema, - /** - * Initial type may be provided in rare cases to facilitate traversals - * beginning somewhere other than documents. - */ - initialType, /** @deprecated will be removed in 17.0.0 */ - getFieldDefFn) { - this._schema = schema; - this._typeStack = []; - this._parentTypeStack = []; - this._inputTypeStack = []; - this._fieldDefStack = []; - this._defaultValueStack = []; - this._directive = null; - this._argument = null; - this._enumValue = null; - this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef; - if (initialType) { - if ((0, _definition.isInputType)(initialType)) { - this._inputTypeStack.push(initialType); - } - if ((0, _definition.isCompositeType)(initialType)) { - this._parentTypeStack.push(initialType); - } - if ((0, _definition.isOutputType)(initialType)) { - this._typeStack.push(initialType); - } - } - } - get [Symbol.toStringTag]() { - return 'TypeInfo'; - } - getType() { - if (this._typeStack.length > 0) { - return this._typeStack[this._typeStack.length - 1]; - } - } - getParentType() { - if (this._parentTypeStack.length > 0) { - return this._parentTypeStack[this._parentTypeStack.length - 1]; - } - } - getInputType() { - if (this._inputTypeStack.length > 0) { - return this._inputTypeStack[this._inputTypeStack.length - 1]; - } - } - getParentInputType() { - if (this._inputTypeStack.length > 1) { - return this._inputTypeStack[this._inputTypeStack.length - 2]; - } - } - getFieldDef() { - if (this._fieldDefStack.length > 0) { - return this._fieldDefStack[this._fieldDefStack.length - 1]; - } - } - getDefaultValue() { - if (this._defaultValueStack.length > 0) { - return this._defaultValueStack[this._defaultValueStack.length - 1]; - } - } - getDirective() { - return this._directive; - } - getArgument() { - return this._argument; - } - getEnumValue() { - return this._enumValue; - } - enter(node) { - const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop - // any assumptions of a valid schema to ensure runtime types are properly - // checked before continuing since TypeInfo is used as part of validation - // which occurs before guarantees of schema and document validity. - - switch (node.kind) { - case _kinds.Kind.SELECTION_SET: - { - const namedType = (0, _definition.getNamedType)(this.getType()); - this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); - break; - } - case _kinds.Kind.FIELD: - { - const parentType = this.getParentType(); - let fieldDef; - let fieldType; - if (parentType) { - fieldDef = this._getFieldDef(schema, parentType, node); - if (fieldDef) { - fieldType = fieldDef.type; - } - } - this._fieldDefStack.push(fieldDef); - this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined); - break; - } - case _kinds.Kind.DIRECTIVE: - this._directive = schema.getDirective(node.name.value); - break; - case _kinds.Kind.OPERATION_DEFINITION: - { - const rootType = schema.getRootType(node.operation); - this._typeStack.push((0, _definition.isObjectType)(rootType) ? rootType : undefined); - break; - } - case _kinds.Kind.INLINE_FRAGMENT: - case _kinds.Kind.FRAGMENT_DEFINITION: - { - const typeConditionAST = node.typeCondition; - const outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType()); - this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); - break; - } - case _kinds.Kind.VARIABLE_DEFINITION: - { - const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); - this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); - break; - } - case _kinds.Kind.ARGUMENT: - { - var _this$getDirective; - let argDef; - let argType; - const fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef(); - if (fieldOrDirective) { - argDef = fieldOrDirective.args.find(arg => arg.name === node.name.value); - if (argDef) { - argType = argDef.type; - } - } - this._argument = argDef; - this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); - this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined); - break; - } - case _kinds.Kind.LIST: - { - const listType = (0, _definition.getNullableType)(this.getInputType()); - const itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value. - - this._defaultValueStack.push(undefined); - this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined); - break; - } - case _kinds.Kind.OBJECT_FIELD: - { - const objectType = (0, _definition.getNamedType)(this.getInputType()); - let inputFieldType; - let inputField; - if ((0, _definition.isInputObjectType)(objectType)) { - inputField = objectType.getFields()[node.name.value]; - if (inputField) { - inputFieldType = inputField.type; - } - } - this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); - this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined); - break; - } - case _kinds.Kind.ENUM: - { - const enumType = (0, _definition.getNamedType)(this.getInputType()); - let enumValue; - if ((0, _definition.isEnumType)(enumType)) { - enumValue = enumType.getValue(node.value); - } - this._enumValue = enumValue; - break; - } - default: // Ignore other nodes - } - } - leave(node) { - switch (node.kind) { - case _kinds.Kind.SELECTION_SET: - this._parentTypeStack.pop(); - break; - case _kinds.Kind.FIELD: - this._fieldDefStack.pop(); - this._typeStack.pop(); - break; - case _kinds.Kind.DIRECTIVE: - this._directive = null; - break; - case _kinds.Kind.OPERATION_DEFINITION: - case _kinds.Kind.INLINE_FRAGMENT: - case _kinds.Kind.FRAGMENT_DEFINITION: - this._typeStack.pop(); - break; - case _kinds.Kind.VARIABLE_DEFINITION: - this._inputTypeStack.pop(); - break; - case _kinds.Kind.ARGUMENT: - this._argument = null; - this._defaultValueStack.pop(); - this._inputTypeStack.pop(); - break; - case _kinds.Kind.LIST: - case _kinds.Kind.OBJECT_FIELD: - this._defaultValueStack.pop(); - this._inputTypeStack.pop(); - break; - case _kinds.Kind.ENUM: - this._enumValue = null; - break; - default: // Ignore other nodes - } - } - } - - /** - * Not exactly the same as the executor's definition of getFieldDef, in this - * statically evaluated environment we do not always have an Object type, - * and need to handle Interface and Union types. - */ - exports.TypeInfo = TypeInfo; - function getFieldDef(schema, parentType, fieldNode) { - const name = fieldNode.name.value; - if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.SchemaMetaFieldDef; - } - if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { - return _introspection.TypeMetaFieldDef; - } - if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) { - return _introspection.TypeNameMetaFieldDef; - } - if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { - return parentType.getFields()[name]; - } - } - /** - * Creates a new visitor instance which maintains a provided TypeInfo instance - * along with visiting visitor. - */ - - function visitWithTypeInfo(typeInfo, visitor) { - return { - enter(...args) { - const node = args[0]; - typeInfo.enter(node); - const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; - if (fn) { - const result = fn.apply(visitor, args); - if (result !== undefined) { - typeInfo.leave(node); - if ((0, _ast.isNode)(result)) { - typeInfo.enter(result); - } - } - return result; - } - }, - leave(...args) { - const node = args[0]; - const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; - let result; - if (fn) { - result = fn.apply(visitor, args); - } - typeInfo.leave(node); - return result; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/assertValidName.mjs": - /*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/assertValidName.mjs ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.assertValidName = assertValidName; - exports.isValidNameError = isValidNameError; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _assertName = __webpack_require__(/*! ../type/assertName.mjs */ "../../../node_modules/graphql/type/assertName.mjs"); - /* c8 ignore start */ - - /** - * Upholds the spec rules about naming. - * @deprecated Please use `assertName` instead. Will be removed in v17 - */ - - function assertValidName(name) { - const error = isValidNameError(name); - if (error) { - throw error; - } - return name; - } - /** - * Returns an Error if a name is invalid. - * @deprecated Please use `assertName` instead. Will be removed in v17 - */ - - function isValidNameError(name) { - typeof name === 'string' || (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); - if (name.startsWith('__')) { - return new _GraphQLError.GraphQLError(`Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`); - } - try { - (0, _assertName.assertName)(name); - } catch (error) { - return error; - } - } - /* c8 ignore stop */ - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/astFromValue.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/astFromValue.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.astFromValue = astFromValue; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - /** - * Produces a GraphQL Value AST given a JavaScript object. - * Function will match JavaScript/JSON values to GraphQL AST schema format - * by using suggested GraphQLInputType. For example: - * - * astFromValue("value", GraphQLString) - * - * A GraphQL type must be provided, which will be used to interpret different - * JavaScript values. - * - * | JSON Value | GraphQL Value | - * | ------------- | -------------------- | - * | Object | Input Object | - * | Array | List | - * | Boolean | Boolean | - * | String | String / Enum Value | - * | Number | Int / Float | - * | Unknown | Enum Value | - * | null | NullValue | - * - */ - - function astFromValue(value, type) { - if ((0, _definition.isNonNullType)(type)) { - const astValue = astFromValue(value, type.ofType); - if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === _kinds.Kind.NULL) { - return null; - } - return astValue; - } // only explicit null, not undefined, NaN - - if (value === null) { - return { - kind: _kinds.Kind.NULL - }; - } // undefined - - if (value === undefined) { - return null; - } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but - // the value is not an array, convert the value using the list's item type. - - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; - if ((0, _isIterableObject.isIterableObject)(value)) { - const valuesNodes = []; - for (const item of value) { - const itemNode = astFromValue(item, itemType); - if (itemNode != null) { - valuesNodes.push(itemNode); - } - } - return { - kind: _kinds.Kind.LIST, - values: valuesNodes - }; - } - return astFromValue(value, itemType); - } // Populate the fields of the input object by creating ASTs from each value - // in the JavaScript object according to the fields in the input type. - - if ((0, _definition.isInputObjectType)(type)) { - if (!(0, _isObjectLike.isObjectLike)(value)) { - return null; - } - const fieldNodes = []; - for (const field of Object.values(type.getFields())) { - const fieldValue = astFromValue(value[field.name], field.type); - if (fieldValue) { - fieldNodes.push({ - kind: _kinds.Kind.OBJECT_FIELD, - name: { - kind: _kinds.Kind.NAME, - value: field.name - }, - value: fieldValue - }); - } - } - return { - kind: _kinds.Kind.OBJECT, - fields: fieldNodes - }; - } - if ((0, _definition.isLeafType)(type)) { - // Since value is an internally represented value, it must be serialized - // to an externally represented value before converting into an AST. - const serialized = type.serialize(value); - if (serialized == null) { - return null; - } // Others serialize based on their corresponding JavaScript scalar types. - - if (typeof serialized === 'boolean') { - return { - kind: _kinds.Kind.BOOLEAN, - value: serialized - }; - } // JavaScript numbers can be Int or Float values. - - if (typeof serialized === 'number' && Number.isFinite(serialized)) { - const stringNum = String(serialized); - return integerStringRegExp.test(stringNum) ? { - kind: _kinds.Kind.INT, - value: stringNum - } : { - kind: _kinds.Kind.FLOAT, - value: stringNum - }; - } - if (typeof serialized === 'string') { - // Enum types use Enum literals. - if ((0, _definition.isEnumType)(type)) { - return { - kind: _kinds.Kind.ENUM, - value: serialized - }; - } // ID types can use Int literals. - - if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { - return { - kind: _kinds.Kind.INT, - value: serialized - }; - } - return { - kind: _kinds.Kind.STRING, - value: serialized - }; - } - throw new TypeError(`Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); - } - /** - * IntValue: - * - NegativeSign? 0 - * - NegativeSign? NonZeroDigit ( Digit+ )? - */ - - const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/buildASTSchema.mjs": - /*!******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/buildASTSchema.mjs ***! - \******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.buildASTSchema = buildASTSchema; - exports.buildSchema = buildSchema; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); - var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); - var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); - var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); - /** - * This takes the ast of a schema document produced by the parse function in - * src/language/parser.js. - * - * If no schema definition is provided, then it will look for types named Query, - * Mutation and Subscription. - * - * Given that AST it constructs a GraphQLSchema. The resulting schema - * has no resolve methods, so execution will use default resolvers. - */ - function buildASTSchema(documentAST, options) { - documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); - if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { - (0, _validate.assertValidSDL)(documentAST); - } - const emptySchemaConfig = { - description: undefined, - types: [], - directives: [], - extensions: Object.create(null), - extensionASTNodes: [], - assumeValid: false - }; - const config = (0, _extendSchema.extendSchemaImpl)(emptySchemaConfig, documentAST, options); - if (config.astNode == null) { - for (const type of config.types) { - switch (type.name) { - // Note: While this could make early assertions to get the correctly - // typed values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - case 'Query': - // @ts-expect-error validated in `validateSchema` - config.query = type; - break; - case 'Mutation': - // @ts-expect-error validated in `validateSchema` - config.mutation = type; - break; - case 'Subscription': - // @ts-expect-error validated in `validateSchema` - config.subscription = type; - break; - } - } - } - const directives = [...config.directives, - // If specified directives were not explicitly declared, add them. - ..._directives.specifiedDirectives.filter(stdDirective => config.directives.every(directive => directive.name !== stdDirective.name))]; - return new _schema.GraphQLSchema({ - ...config, - directives - }); - } - /** - * A helper function to build a GraphQLSchema directly from a source - * document. - */ - - function buildSchema(source, options) { - const document = (0, _parser.parse)(source, { - noLocation: options === null || options === void 0 ? void 0 : options.noLocation, - allowLegacyFragmentVariables: options === null || options === void 0 ? void 0 : options.allowLegacyFragmentVariables - }); - return buildASTSchema(document, { - assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL, - assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid - }); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/buildClientSchema.mjs": - /*!*********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/buildClientSchema.mjs ***! - \*********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.buildClientSchema = buildClientSchema; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); - var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); - var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); - /** - * Build a GraphQLSchema for use by client tools. - * - * Given the result of a client running the introspection query, creates and - * returns a GraphQLSchema instance which can be then used with all graphql-js - * tools, but cannot be used to execute a query, as introspection does not - * represent the "resolver", "parse" or "serialize" functions or any other - * server-internal mechanisms. - * - * This function expects a complete introspection result. Don't forget to check - * the "errors" field of a server response before calling this function. - */ - - function buildClientSchema(introspection, options) { - (0, _isObjectLike.isObjectLike)(introspection) && (0, _isObjectLike.isObjectLike)(introspection.__schema) || (0, _devAssert.devAssert)(false, `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, _inspect.inspect)(introspection)}.`); // Get the schema from the introspection result. - - const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. - - const typeMap = (0, _keyValMap.keyValMap)(schemaIntrospection.types, typeIntrospection => typeIntrospection.name, typeIntrospection => buildType(typeIntrospection)); // Include standard types only if they are used. - - for (const stdType of [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes]) { - if (typeMap[stdType.name]) { - typeMap[stdType.name] = stdType; - } - } // Get the root Query, Mutation, and Subscription types. - - const queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; - const mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; - const subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if - // directives were not queried for. - - const directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. - - return new _schema.GraphQLSchema({ - description: schemaIntrospection.description, - query: queryType, - mutation: mutationType, - subscription: subscriptionType, - types: Object.values(typeMap), - directives, - assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid - }); // Given a type reference in introspection, return the GraphQLType instance. - // preferring cached instances before building new instances. - - function getType(typeRef) { - if (typeRef.kind === _introspection.TypeKind.LIST) { - const itemRef = typeRef.ofType; - if (!itemRef) { - throw new Error('Decorated type deeper than introspection query.'); - } - return new _definition.GraphQLList(getType(itemRef)); - } - if (typeRef.kind === _introspection.TypeKind.NON_NULL) { - const nullableRef = typeRef.ofType; - if (!nullableRef) { - throw new Error('Decorated type deeper than introspection query.'); - } - const nullableType = getType(nullableRef); - return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType)); - } - return getNamedType(typeRef); - } - function getNamedType(typeRef) { - const typeName = typeRef.name; - if (!typeName) { - throw new Error(`Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`); - } - const type = typeMap[typeName]; - if (!type) { - throw new Error(`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`); - } - return type; - } - function getObjectType(typeRef) { - return (0, _definition.assertObjectType)(getNamedType(typeRef)); - } - function getInterfaceType(typeRef) { - return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); - } // Given a type's introspection result, construct the correct - // GraphQLType instance. - - function buildType(type) { - // eslint-disable-next-line @typescript-eslint/prefer-optional-chain - if (type != null && type.name != null && type.kind != null) { - // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 - // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check - switch (type.kind) { - case _introspection.TypeKind.SCALAR: - return buildScalarDef(type); - case _introspection.TypeKind.OBJECT: - return buildObjectDef(type); - case _introspection.TypeKind.INTERFACE: - return buildInterfaceDef(type); - case _introspection.TypeKind.UNION: - return buildUnionDef(type); - case _introspection.TypeKind.ENUM: - return buildEnumDef(type); - case _introspection.TypeKind.INPUT_OBJECT: - return buildInputObjectDef(type); - } - } - const typeStr = (0, _inspect.inspect)(type); - throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`); - } - function buildScalarDef(scalarIntrospection) { - return new _definition.GraphQLScalarType({ - name: scalarIntrospection.name, - description: scalarIntrospection.description, - specifiedByURL: scalarIntrospection.specifiedByURL - }); - } - function buildImplementationsList(implementingIntrospection) { - // TODO: Temporary workaround until GraphQL ecosystem will fully support - // 'interfaces' on interface types. - if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === _introspection.TypeKind.INTERFACE) { - return []; - } - if (!implementingIntrospection.interfaces) { - const implementingIntrospectionStr = (0, _inspect.inspect)(implementingIntrospection); - throw new Error(`Introspection result missing interfaces: ${implementingIntrospectionStr}.`); - } - return implementingIntrospection.interfaces.map(getInterfaceType); - } - function buildObjectDef(objectIntrospection) { - return new _definition.GraphQLObjectType({ - name: objectIntrospection.name, - description: objectIntrospection.description, - interfaces: () => buildImplementationsList(objectIntrospection), - fields: () => buildFieldDefMap(objectIntrospection) - }); - } - function buildInterfaceDef(interfaceIntrospection) { - return new _definition.GraphQLInterfaceType({ - name: interfaceIntrospection.name, - description: interfaceIntrospection.description, - interfaces: () => buildImplementationsList(interfaceIntrospection), - fields: () => buildFieldDefMap(interfaceIntrospection) - }); - } - function buildUnionDef(unionIntrospection) { - if (!unionIntrospection.possibleTypes) { - const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); - throw new Error(`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`); - } - return new _definition.GraphQLUnionType({ - name: unionIntrospection.name, - description: unionIntrospection.description, - types: () => unionIntrospection.possibleTypes.map(getObjectType) - }); - } - function buildEnumDef(enumIntrospection) { - if (!enumIntrospection.enumValues) { - const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); - throw new Error(`Introspection result missing enumValues: ${enumIntrospectionStr}.`); - } - return new _definition.GraphQLEnumType({ - name: enumIntrospection.name, - description: enumIntrospection.description, - values: (0, _keyValMap.keyValMap)(enumIntrospection.enumValues, valueIntrospection => valueIntrospection.name, valueIntrospection => ({ - description: valueIntrospection.description, - deprecationReason: valueIntrospection.deprecationReason - })) - }); - } - function buildInputObjectDef(inputObjectIntrospection) { - if (!inputObjectIntrospection.inputFields) { - const inputObjectIntrospectionStr = (0, _inspect.inspect)(inputObjectIntrospection); - throw new Error(`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`); - } - return new _definition.GraphQLInputObjectType({ - name: inputObjectIntrospection.name, - description: inputObjectIntrospection.description, - fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields) - }); - } - function buildFieldDefMap(typeIntrospection) { - if (!typeIntrospection.fields) { - throw new Error(`Introspection result missing fields: ${(0, _inspect.inspect)(typeIntrospection)}.`); - } - return (0, _keyValMap.keyValMap)(typeIntrospection.fields, fieldIntrospection => fieldIntrospection.name, buildField); - } - function buildField(fieldIntrospection) { - const type = getType(fieldIntrospection.type); - if (!(0, _definition.isOutputType)(type)) { - const typeStr = (0, _inspect.inspect)(type); - throw new Error(`Introspection must provide output type for fields, but received: ${typeStr}.`); - } - if (!fieldIntrospection.args) { - const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); - throw new Error(`Introspection result missing field args: ${fieldIntrospectionStr}.`); - } - return { - description: fieldIntrospection.description, - deprecationReason: fieldIntrospection.deprecationReason, - type, - args: buildInputValueDefMap(fieldIntrospection.args) - }; - } - function buildInputValueDefMap(inputValueIntrospections) { - return (0, _keyValMap.keyValMap)(inputValueIntrospections, inputValue => inputValue.name, buildInputValue); - } - function buildInputValue(inputValueIntrospection) { - const type = getType(inputValueIntrospection.type); - if (!(0, _definition.isInputType)(type)) { - const typeStr = (0, _inspect.inspect)(type); - throw new Error(`Introspection must provide input type for arguments, but received: ${typeStr}.`); - } - const defaultValue = inputValueIntrospection.defaultValue != null ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; - return { - description: inputValueIntrospection.description, - type, - defaultValue, - deprecationReason: inputValueIntrospection.deprecationReason - }; - } - function buildDirective(directiveIntrospection) { - if (!directiveIntrospection.args) { - const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); - throw new Error(`Introspection result missing directive args: ${directiveIntrospectionStr}.`); - } - if (!directiveIntrospection.locations) { - const directiveIntrospectionStr = (0, _inspect.inspect)(directiveIntrospection); - throw new Error(`Introspection result missing directive locations: ${directiveIntrospectionStr}.`); - } - return new _directives.GraphQLDirective({ - name: directiveIntrospection.name, - description: directiveIntrospection.description, - isRepeatable: directiveIntrospection.isRepeatable, - locations: directiveIntrospection.locations.slice(), - args: buildInputValueDefMap(directiveIntrospection.args) - }); - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/coerceInputValue.mjs": - /*!********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/coerceInputValue.mjs ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.coerceInputValue = coerceInputValue; - var _didYouMean = __webpack_require__(/*! ../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _isIterableObject = __webpack_require__(/*! ../jsutils/isIterableObject.mjs */ "../../../node_modules/graphql/jsutils/isIterableObject.mjs"); - var _isObjectLike = __webpack_require__(/*! ../jsutils/isObjectLike.mjs */ "../../../node_modules/graphql/jsutils/isObjectLike.mjs"); - var _Path = __webpack_require__(/*! ../jsutils/Path.mjs */ "../../../node_modules/graphql/jsutils/Path.mjs"); - var _printPathArray = __webpack_require__(/*! ../jsutils/printPathArray.mjs */ "../../../node_modules/graphql/jsutils/printPathArray.mjs"); - var _suggestionList = __webpack_require__(/*! ../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Coerces a JavaScript value given a GraphQL Input Type. - */ - function coerceInputValue(inputValue, type, onError = defaultOnError) { - return coerceInputValueImpl(inputValue, type, onError, undefined); - } - function defaultOnError(path, invalidValue, error) { - let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); - if (path.length > 0) { - errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; - } - error.message = errorPrefix + ': ' + error.message; - throw error; - } - function coerceInputValueImpl(inputValue, type, onError, path) { - if ((0, _definition.isNonNullType)(type)) { - if (inputValue != null) { - return coerceInputValueImpl(inputValue, type.ofType, onError, path); - } - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected non-nullable type "${(0, _inspect.inspect)(type)}" not to be null.`)); - return; - } - if (inputValue == null) { - // Explicitly return the value null. - return null; - } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; - if ((0, _isIterableObject.isIterableObject)(inputValue)) { - return Array.from(inputValue, (itemValue, index) => { - const itemPath = (0, _Path.addPath)(path, index, undefined); - return coerceInputValueImpl(itemValue, itemType, onError, itemPath); - }); - } // Lists accept a non-list value as a list of one. - - return [coerceInputValueImpl(inputValue, itemType, onError, path)]; - } - if ((0, _definition.isInputObjectType)(type)) { - if (!(0, _isObjectLike.isObjectLike)(inputValue)) { - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}" to be an object.`)); - return; - } - const coercedValue = {}; - const fieldDefs = type.getFields(); - for (const field of Object.values(fieldDefs)) { - const fieldValue = inputValue[field.name]; - if (fieldValue === undefined) { - if (field.defaultValue !== undefined) { - coercedValue[field.name] = field.defaultValue; - } else if ((0, _definition.isNonNullType)(field.type)) { - const typeStr = (0, _inspect.inspect)(field.type); - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${field.name}" of required type "${typeStr}" was not provided.`)); - } - continue; - } - coercedValue[field.name] = coerceInputValueImpl(fieldValue, field.type, onError, (0, _Path.addPath)(path, field.name, type.name)); - } // Ensure every provided field is defined. - - for (const fieldName of Object.keys(inputValue)) { - if (!fieldDefs[fieldName]) { - const suggestions = (0, _suggestionList.suggestionList)(fieldName, Object.keys(type.getFields())); - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Field "${fieldName}" is not defined by type "${type.name}".` + (0, _didYouMean.didYouMean)(suggestions))); - } - } - return coercedValue; - } - if ((0, _definition.isLeafType)(type)) { - let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), - // which can throw to indicate failure. If it throws, maintain a reference - // to the original error. - - try { - parseResult = type.parseValue(inputValue); - } catch (error) { - if (error instanceof _GraphQLError.GraphQLError) { - onError((0, _Path.pathToArray)(path), inputValue, error); - } else { - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}". ` + error.message, { - originalError: error - })); - } - return; - } - if (parseResult === undefined) { - onError((0, _Path.pathToArray)(path), inputValue, new _GraphQLError.GraphQLError(`Expected type "${type.name}".`)); - } - return parseResult; - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/concatAST.mjs": - /*!*************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/concatAST.mjs ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.concatAST = concatAST; - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - /** - * Provided a collection of ASTs, presumably each from different files, - * concatenate the ASTs together into batched AST, useful for validating many - * GraphQL source files which together represent one conceptual application. - */ - - function concatAST(documents) { - const definitions = []; - for (const doc of documents) { - definitions.push(...doc.definitions); - } - return { - kind: _kinds.Kind.DOCUMENT, - definitions - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/extendSchema.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/extendSchema.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.extendSchema = extendSchema; - exports.extendSchemaImpl = extendSchemaImpl; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _mapValue = __webpack_require__(/*! ../jsutils/mapValue.mjs */ "../../../node_modules/graphql/jsutils/mapValue.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _predicates = __webpack_require__(/*! ../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); - var _validate = __webpack_require__(/*! ../validation/validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); - var _values = __webpack_require__(/*! ../execution/values.mjs */ "../../../node_modules/graphql/execution/values.mjs"); - var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); - /** - * Produces a new schema given an existing schema and a document which may - * contain GraphQL type extensions and definitions. The original schema will - * remain unaltered. - * - * Because a schema represents a graph of references, a schema cannot be - * extended without effectively making an entire copy. We do not know until it's - * too late if subgraphs remain unchanged. - * - * This algorithm copies the provided schema, applying extensions while - * producing the copy. The original schema remains unaltered. - */ - function extendSchema(schema, documentAST, options) { - (0, _schema.assertSchema)(schema); - documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT || (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); - if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) { - (0, _validate.assertValidSDLExtension)(documentAST, schema); - } - const schemaConfig = schema.toConfig(); - const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); - return schemaConfig === extendedConfig ? schema : new _schema.GraphQLSchema(extendedConfig); - } - /** - * @internal - */ - - function extendSchemaImpl(schemaConfig, documentAST, options) { - var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; - - // Collect the type definitions and extensions found in the document. - const typeDefs = []; - const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can - // have the same name. For example, a type named "skip". - - const directiveDefs = []; - let schemaDef; // Schema extensions are collected which may add additional operation types. - - const schemaExtensions = []; - for (const def of documentAST.definitions) { - if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { - schemaDef = def; - } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { - schemaExtensions.push(def); - } else if ((0, _predicates.isTypeDefinitionNode)(def)) { - typeDefs.push(def); - } else if ((0, _predicates.isTypeExtensionNode)(def)) { - const extendedTypeName = def.name.value; - const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; - typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; - } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - directiveDefs.push(def); - } - } // If this document contains no new types, extensions, or directives then - // return the same unmodified GraphQLSchema instance. - - if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) { - return schemaConfig; - } - const typeMap = Object.create(null); - for (const existingType of schemaConfig.types) { - typeMap[existingType.name] = extendNamedType(existingType); - } - for (const typeNode of typeDefs) { - var _stdTypeMap$name; - const name = typeNode.name.value; - typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode); - } - const operationTypes = { - // Get the extended root operation types. - query: schemaConfig.query && replaceNamedType(schemaConfig.query), - mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), - subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), - // Then, incorporate schema definition and all schema extensions. - ...(schemaDef && getOperationTypes([schemaDef])), - ...getOperationTypes(schemaExtensions) - }; // Then produce and return a Schema config with these types. - - return { - description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value, - ...operationTypes, - types: Object.values(typeMap), - directives: [...schemaConfig.directives.map(replaceDirective), ...directiveDefs.map(buildDirective)], - extensions: Object.create(null), - astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode, - extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), - assumeValid: (_options$assumeValid = options === null || options === void 0 ? void 0 : options.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false - }; // Below are functions used for producing this schema that have closed over - // this scope and have access to the schema, cache, and newly defined types. - - function replaceType(type) { - if ((0, _definition.isListType)(type)) { - // @ts-expect-error - return new _definition.GraphQLList(replaceType(type.ofType)); - } - if ((0, _definition.isNonNullType)(type)) { - // @ts-expect-error - return new _definition.GraphQLNonNull(replaceType(type.ofType)); - } // @ts-expect-error FIXME - - return replaceNamedType(type); - } - function replaceNamedType(type) { - // Note: While this could make early assertions to get the correctly - // typed values, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - return typeMap[type.name]; - } - function replaceDirective(directive) { - const config = directive.toConfig(); - return new _directives.GraphQLDirective({ - ...config, - args: (0, _mapValue.mapValue)(config.args, extendArg) - }); - } - function extendNamedType(type) { - if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) { - // Builtin types are not extended. - return type; - } - if ((0, _definition.isScalarType)(type)) { - return extendScalarType(type); - } - if ((0, _definition.isObjectType)(type)) { - return extendObjectType(type); - } - if ((0, _definition.isInterfaceType)(type)) { - return extendInterfaceType(type); - } - if ((0, _definition.isUnionType)(type)) { - return extendUnionType(type); - } - if ((0, _definition.isEnumType)(type)) { - return extendEnumType(type); - } - if ((0, _definition.isInputObjectType)(type)) { - return extendInputObjectType(type); - } - /* c8 ignore next 3 */ - // Not reachable, all possible type definition nodes have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } - function extendInputObjectType(type) { - var _typeExtensionsMap$co; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : []; - return new _definition.GraphQLInputObjectType({ - ...config, - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, field => ({ - ...field, - type: replaceType(field.type) - })), - ...buildInputFieldMap(extensions) - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendEnumType(type) { - var _typeExtensionsMap$ty; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : []; - return new _definition.GraphQLEnumType({ - ...config, - values: { - ...config.values, - ...buildEnumValueMap(extensions) - }, - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendScalarType(type) { - var _typeExtensionsMap$co2; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : []; - let specifiedByURL = config.specifiedByURL; - for (const extensionNode of extensions) { - var _getSpecifiedByURL; - specifiedByURL = (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && _getSpecifiedByURL !== void 0 ? _getSpecifiedByURL : specifiedByURL; - } - return new _definition.GraphQLScalarType({ - ...config, - specifiedByURL, - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendObjectType(type) { - var _typeExtensionsMap$co3; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : []; - return new _definition.GraphQLObjectType({ - ...config, - interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, extendField), - ...buildFieldMap(extensions) - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendInterfaceType(type) { - var _typeExtensionsMap$co4; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : []; - return new _definition.GraphQLInterfaceType({ - ...config, - interfaces: () => [...type.getInterfaces().map(replaceNamedType), ...buildInterfaces(extensions)], - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, extendField), - ...buildFieldMap(extensions) - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendUnionType(type) { - var _typeExtensionsMap$co5; - const config = type.toConfig(); - const extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : []; - return new _definition.GraphQLUnionType({ - ...config, - types: () => [...type.getTypes().map(replaceNamedType), ...buildUnionTypes(extensions)], - extensionASTNodes: config.extensionASTNodes.concat(extensions) - }); - } - function extendField(field) { - return { - ...field, - type: replaceType(field.type), - args: field.args && (0, _mapValue.mapValue)(field.args, extendArg) - }; - } - function extendArg(arg) { - return { - ...arg, - type: replaceType(arg.type) - }; - } - function getOperationTypes(nodes) { - const opTypes = {}; - for (const node of nodes) { - var _node$operationTypes; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const operationTypesNodes = /* c8 ignore next */ - (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; - for (const operationType of operationTypesNodes) { - // Note: While this could make early assertions to get the correctly - // typed values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - opTypes[operationType.operation] = getNamedType(operationType.type); - } - } - return opTypes; - } - function getNamedType(node) { - var _stdTypeMap$name2; - const name = node.name.value; - const type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name]; - if (type === undefined) { - throw new Error(`Unknown type: "${name}".`); - } - return type; - } - function getWrappedType(node) { - if (node.kind === _kinds.Kind.LIST_TYPE) { - return new _definition.GraphQLList(getWrappedType(node.type)); - } - if (node.kind === _kinds.Kind.NON_NULL_TYPE) { - return new _definition.GraphQLNonNull(getWrappedType(node.type)); - } - return getNamedType(node); - } - function buildDirective(node) { - var _node$description; - return new _directives.GraphQLDirective({ - name: node.name.value, - description: (_node$description = node.description) === null || _node$description === void 0 ? void 0 : _node$description.value, - // @ts-expect-error - locations: node.locations.map(({ - value - }) => value), - isRepeatable: node.repeatable, - args: buildArgumentMap(node.arguments), - astNode: node - }); - } - function buildFieldMap(nodes) { - const fieldConfigMap = Object.create(null); - for (const node of nodes) { - var _node$fields; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const nodeFields = /* c8 ignore next */ - (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; - for (const field of nodeFields) { - var _field$description; - fieldConfigMap[field.name.value] = { - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - type: getWrappedType(field.type), - description: (_field$description = field.description) === null || _field$description === void 0 ? void 0 : _field$description.value, - args: buildArgumentMap(field.arguments), - deprecationReason: getDeprecationReason(field), - astNode: field - }; - } - } - return fieldConfigMap; - } - function buildArgumentMap(args) { - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const argsNodes = /* c8 ignore next */ - args !== null && args !== void 0 ? args : []; - const argConfigMap = Object.create(null); - for (const arg of argsNodes) { - var _arg$description; - - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - const type = getWrappedType(arg.type); - argConfigMap[arg.name.value] = { - type, - description: (_arg$description = arg.description) === null || _arg$description === void 0 ? void 0 : _arg$description.value, - defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), - deprecationReason: getDeprecationReason(arg), - astNode: arg - }; - } - return argConfigMap; - } - function buildInputFieldMap(nodes) { - const inputFieldMap = Object.create(null); - for (const node of nodes) { - var _node$fields2; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const fieldsNodes = /* c8 ignore next */ - (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []; - for (const field of fieldsNodes) { - var _field$description2; - - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - const type = getWrappedType(field.type); - inputFieldMap[field.name.value] = { - type, - description: (_field$description2 = field.description) === null || _field$description2 === void 0 ? void 0 : _field$description2.value, - defaultValue: (0, _valueFromAST.valueFromAST)(field.defaultValue, type), - deprecationReason: getDeprecationReason(field), - astNode: field - }; - } - } - return inputFieldMap; - } - function buildEnumValueMap(nodes) { - const enumValueMap = Object.create(null); - for (const node of nodes) { - var _node$values; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const valuesNodes = /* c8 ignore next */ - (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; - for (const value of valuesNodes) { - var _value$description; - enumValueMap[value.name.value] = { - description: (_value$description = value.description) === null || _value$description === void 0 ? void 0 : _value$description.value, - deprecationReason: getDeprecationReason(value), - astNode: value - }; - } - } - return enumValueMap; - } - function buildInterfaces(nodes) { - // Note: While this could make assertions to get the correctly typed - // values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - return nodes.flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - node => { - var _node$interfaces$map, _node$interfaces; - return /* c8 ignore next */( - (_node$interfaces$map = (_node$interfaces = node.interfaces) === null || _node$interfaces === void 0 ? void 0 : _node$interfaces.map(getNamedType)) !== null && _node$interfaces$map !== void 0 ? _node$interfaces$map : [] - ); - }); - } - function buildUnionTypes(nodes) { - // Note: While this could make assertions to get the correctly typed - // values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - return nodes.flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - node => { - var _node$types$map, _node$types; - return /* c8 ignore next */( - (_node$types$map = (_node$types = node.types) === null || _node$types === void 0 ? void 0 : _node$types.map(getNamedType)) !== null && _node$types$map !== void 0 ? _node$types$map : [] - ); - }); - } - function buildType(astNode) { - var _typeExtensionsMap$na; - const name = astNode.name.value; - const extensionASTNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : []; - switch (astNode.kind) { - case _kinds.Kind.OBJECT_TYPE_DEFINITION: - { - var _astNode$description; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLObjectType({ - name, - description: (_astNode$description = astNode.description) === null || _astNode$description === void 0 ? void 0 : _astNode$description.value, - interfaces: () => buildInterfaces(allNodes), - fields: () => buildFieldMap(allNodes), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.INTERFACE_TYPE_DEFINITION: - { - var _astNode$description2; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLInterfaceType({ - name, - description: (_astNode$description2 = astNode.description) === null || _astNode$description2 === void 0 ? void 0 : _astNode$description2.value, - interfaces: () => buildInterfaces(allNodes), - fields: () => buildFieldMap(allNodes), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.ENUM_TYPE_DEFINITION: - { - var _astNode$description3; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLEnumType({ - name, - description: (_astNode$description3 = astNode.description) === null || _astNode$description3 === void 0 ? void 0 : _astNode$description3.value, - values: buildEnumValueMap(allNodes), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.UNION_TYPE_DEFINITION: - { - var _astNode$description4; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLUnionType({ - name, - description: (_astNode$description4 = astNode.description) === null || _astNode$description4 === void 0 ? void 0 : _astNode$description4.value, - types: () => buildUnionTypes(allNodes), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.SCALAR_TYPE_DEFINITION: - { - var _astNode$description5; - return new _definition.GraphQLScalarType({ - name, - description: (_astNode$description5 = astNode.description) === null || _astNode$description5 === void 0 ? void 0 : _astNode$description5.value, - specifiedByURL: getSpecifiedByURL(astNode), - astNode, - extensionASTNodes - }); - } - case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: - { - var _astNode$description6; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLInputObjectType({ - name, - description: (_astNode$description6 = astNode.description) === null || _astNode$description6 === void 0 ? void 0 : _astNode$description6.value, - fields: () => buildInputFieldMap(allNodes), - astNode, - extensionASTNodes - }); - } - } - } - } - const stdTypeMap = (0, _keyMap.keyMap)([..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], type => type.name); - /** - * Given a field or enum value node, returns the string value for the - * deprecation reason. - */ - - function getDeprecationReason(node) { - const deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues` - - return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason; - } - /** - * Given a scalar node, returns the string value for the specifiedByURL. - */ - - function getSpecifiedByURL(node) { - const specifiedBy = (0, _values.getDirectiveValues)(_directives.GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues` - - return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs": - /*!***********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/findBreakingChanges.mjs ***! - \***********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.DangerousChangeType = exports.BreakingChangeType = void 0; - exports.findBreakingChanges = findBreakingChanges; - exports.findDangerousChanges = findDangerousChanges; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); - var _sortValueNode = __webpack_require__(/*! ./sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); - var BreakingChangeType; - (function (BreakingChangeType) { - BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; - BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; - BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; - BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; - BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = 'REQUIRED_INPUT_FIELD_ADDED'; - BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = 'IMPLEMENTED_INTERFACE_REMOVED'; - BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; - BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; - BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; - BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; - BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; - BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; - BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; - BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = 'REQUIRED_DIRECTIVE_ARG_ADDED'; - BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = 'DIRECTIVE_REPEATABLE_REMOVED'; - BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = 'DIRECTIVE_LOCATION_REMOVED'; - })(BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {})); - var DangerousChangeType; - (function (DangerousChangeType) { - DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; - DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; - DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = 'OPTIONAL_INPUT_FIELD_ADDED'; - DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; - DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = 'IMPLEMENTED_INTERFACE_ADDED'; - DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; - })(DangerousChangeType || (exports.DangerousChangeType = DangerousChangeType = {})); - /** - * Given two schemas, returns an Array containing descriptions of all the types - * of breaking changes covered by the other functions down below. - */ - function findBreakingChanges(oldSchema, newSchema) { - // @ts-expect-error - return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in BreakingChangeType); - } - /** - * Given two schemas, returns an Array containing descriptions of all the types - * of potentially dangerous changes covered by the other functions down below. - */ - - function findDangerousChanges(oldSchema, newSchema) { - // @ts-expect-error - return findSchemaChanges(oldSchema, newSchema).filter(change => change.type in DangerousChangeType); - } - function findSchemaChanges(oldSchema, newSchema) { - return [...findTypeChanges(oldSchema, newSchema), ...findDirectiveChanges(oldSchema, newSchema)]; - } - function findDirectiveChanges(oldSchema, newSchema) { - const schemaChanges = []; - const directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); - for (const oldDirective of directivesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_REMOVED, - description: `${oldDirective.name} was removed.` - }); - } - for (const [oldDirective, newDirective] of directivesDiff.persisted) { - const argsDiff = diff(oldDirective.args, newDirective.args); - for (const newArg of argsDiff.added) { - if ((0, _definition.isRequiredArgument)(newArg)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, - description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.` - }); - } - } - for (const oldArg of argsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, - description: `${oldArg.name} was removed from ${oldDirective.name}.` - }); - } - if (oldDirective.isRepeatable && !newDirective.isRepeatable) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, - description: `Repeatable flag was removed from ${oldDirective.name}.` - }); - } - for (const location of oldDirective.locations) { - if (!newDirective.locations.includes(location)) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, - description: `${location} was removed from ${oldDirective.name}.` - }); - } - } - } - return schemaChanges; - } - function findTypeChanges(oldSchema, newSchema) { - const schemaChanges = []; - const typesDiff = diff(Object.values(oldSchema.getTypeMap()), Object.values(newSchema.getTypeMap())); - for (const oldType of typesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_REMOVED, - description: (0, _scalars.isSpecifiedScalarType)(oldType) ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` : `${oldType.name} was removed.` - }); - } - for (const [oldType, newType] of typesDiff.persisted) { - if ((0, _definition.isEnumType)(oldType) && (0, _definition.isEnumType)(newType)) { - schemaChanges.push(...findEnumTypeChanges(oldType, newType)); - } else if ((0, _definition.isUnionType)(oldType) && (0, _definition.isUnionType)(newType)) { - schemaChanges.push(...findUnionTypeChanges(oldType, newType)); - } else if ((0, _definition.isInputObjectType)(oldType) && (0, _definition.isInputObjectType)(newType)) { - schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); - } else if ((0, _definition.isObjectType)(oldType) && (0, _definition.isObjectType)(newType)) { - schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); - } else if ((0, _definition.isInterfaceType)(oldType) && (0, _definition.isInterfaceType)(newType)) { - schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); - } else if (oldType.constructor !== newType.constructor) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_CHANGED_KIND, - description: `${oldType.name} changed from ` + `${typeKindName(oldType)} to ${typeKindName(newType)}.` - }); - } - } - return schemaChanges; - } - function findInputObjectTypeChanges(oldType, newType) { - const schemaChanges = []; - const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); - for (const newField of fieldsDiff.added) { - if ((0, _definition.isRequiredInputField)(newField)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, - description: `A required field ${newField.name} on input type ${oldType.name} was added.` - }); - } else { - schemaChanges.push({ - type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, - description: `An optional field ${newField.name} on input type ${oldType.name} was added.` - }); - } - } - for (const oldField of fieldsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_REMOVED, - description: `${oldType.name}.${oldField.name} was removed.` - }); - } - for (const [oldField, newField] of fieldsDiff.persisted) { - const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldField.type, newField.type); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_CHANGED_KIND, - description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` - }); - } - } - return schemaChanges; - } - function findUnionTypeChanges(oldType, newType) { - const schemaChanges = []; - const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); - for (const newPossibleType of possibleTypesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.TYPE_ADDED_TO_UNION, - description: `${newPossibleType.name} was added to union type ${oldType.name}.` - }); - } - for (const oldPossibleType of possibleTypesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, - description: `${oldPossibleType.name} was removed from union type ${oldType.name}.` - }); - } - return schemaChanges; - } - function findEnumTypeChanges(oldType, newType) { - const schemaChanges = []; - const valuesDiff = diff(oldType.getValues(), newType.getValues()); - for (const newValue of valuesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.VALUE_ADDED_TO_ENUM, - description: `${newValue.name} was added to enum type ${oldType.name}.` - }); - } - for (const oldValue of valuesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, - description: `${oldValue.name} was removed from enum type ${oldType.name}.` - }); - } - return schemaChanges; - } - function findImplementedInterfacesChanges(oldType, newType) { - const schemaChanges = []; - const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); - for (const newInterface of interfacesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, - description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.` - }); - } - for (const oldInterface of interfacesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, - description: `${oldType.name} no longer implements interface ${oldInterface.name}.` - }); - } - return schemaChanges; - } - function findFieldChanges(oldType, newType) { - const schemaChanges = []; - const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); - for (const oldField of fieldsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_REMOVED, - description: `${oldType.name}.${oldField.name} was removed.` - }); - } - for (const [oldField, newField] of fieldsDiff.persisted) { - schemaChanges.push(...findArgChanges(oldType, oldField, newField)); - const isSafe = isChangeSafeForObjectOrInterfaceField(oldField.type, newField.type); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_CHANGED_KIND, - description: `${oldType.name}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` - }); - } - } - return schemaChanges; - } - function findArgChanges(oldType, oldField, newField) { - const schemaChanges = []; - const argsDiff = diff(oldField.args, newField.args); - for (const oldArg of argsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.ARG_REMOVED, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.` - }); - } - for (const [oldArg, newArg] of argsDiff.persisted) { - const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArg.type, newArg.type); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.ARG_CHANGED_KIND, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` - }); - } else if (oldArg.defaultValue !== undefined) { - if (newArg.defaultValue === undefined) { - schemaChanges.push({ - type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.` - }); - } else { - // Since we looking only for client's observable changes we should - // compare default values in the same representation as they are - // represented inside introspection. - const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); - const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); - if (oldValueStr !== newValueStr) { - schemaChanges.push({ - type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.` - }); - } - } - } - } - for (const newArg of argsDiff.added) { - if ((0, _definition.isRequiredArgument)(newArg)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_ARG_ADDED, - description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` - }); - } else { - schemaChanges.push({ - type: DangerousChangeType.OPTIONAL_ARG_ADDED, - description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.` - }); - } - } - return schemaChanges; - } - function isChangeSafeForObjectOrInterfaceField(oldType, newType) { - if ((0, _definition.isListType)(oldType)) { - return ( - // if they're both lists, make sure the underlying types are compatible - (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || - // moving from nullable to non-null of the same underlying type is safe - (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) - ); - } - if ((0, _definition.isNonNullType)(oldType)) { - // if they're both non-null, make sure the underlying types are compatible - return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); - } - return ( - // if they're both named types, see if their names are equivalent - (0, _definition.isNamedType)(newType) && oldType.name === newType.name || - // moving from nullable to non-null of the same underlying type is safe - (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) - ); - } - function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { - if ((0, _definition.isListType)(oldType)) { - // if they're both lists, make sure the underlying types are compatible - return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); - } - if ((0, _definition.isNonNullType)(oldType)) { - return ( - // if they're both non-null, make sure the underlying types are - // compatible - (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || - // moving from non-null to nullable of the same underlying type is safe - !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) - ); - } // if they're both named types, see if their names are equivalent - - return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; - } - function typeKindName(type) { - if ((0, _definition.isScalarType)(type)) { - return 'a Scalar type'; - } - if ((0, _definition.isObjectType)(type)) { - return 'an Object type'; - } - if ((0, _definition.isInterfaceType)(type)) { - return 'an Interface type'; - } - if ((0, _definition.isUnionType)(type)) { - return 'a Union type'; - } - if ((0, _definition.isEnumType)(type)) { - return 'an Enum type'; - } - if ((0, _definition.isInputObjectType)(type)) { - return 'an Input type'; - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } - function stringifyValue(value, type) { - const ast = (0, _astFromValue.astFromValue)(value, type); - ast != null || (0, _invariant.invariant)(false); - return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); - } - function diff(oldArray, newArray) { - const added = []; - const removed = []; - const persisted = []; - const oldMap = (0, _keyMap.keyMap)(oldArray, ({ - name - }) => name); - const newMap = (0, _keyMap.keyMap)(newArray, ({ - name - }) => name); - for (const oldItem of oldArray) { - const newItem = newMap[oldItem.name]; - if (newItem === undefined) { - removed.push(oldItem); - } else { - persisted.push([oldItem, newItem]); - } - } - for (const newItem of newArray) { - if (oldMap[newItem.name] === undefined) { - added.push(newItem); - } - } - return { - added, - persisted, - removed - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs": - /*!*************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs ***! - \*************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getIntrospectionQuery = getIntrospectionQuery; - /** - * Produce the GraphQL query recommended for a full schema introspection. - * Accepts optional IntrospectionOptions. - */ - function getIntrospectionQuery(options) { - const optionsWithDefault = { - descriptions: true, - specifiedByUrl: false, - directiveIsRepeatable: false, - schemaDescription: false, - inputValueDeprecation: false, - ...options - }; - const descriptions = optionsWithDefault.descriptions ? 'description' : ''; - const specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByURL' : ''; - const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : ''; - const schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ''; - function inputDeprecation(str) { - return optionsWithDefault.inputValueDeprecation ? str : ''; - } - return ` - query IntrospectionQuery { - __schema { - ${schemaDescription} - queryType { name } - mutationType { name } - subscriptionType { name } - types { - ...FullType - } - directives { - name - ${descriptions} - ${directiveIsRepeatable} - locations - args${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - } - } - } - - fragment FullType on __Type { - kind - name - ${descriptions} - ${specifiedByUrl} - fields(includeDeprecated: true) { - name - ${descriptions} - args${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - type { - ...TypeRef - } - isDeprecated - deprecationReason - } - inputFields${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - interfaces { - ...TypeRef - } - enumValues(includeDeprecated: true) { - name - ${descriptions} - isDeprecated - deprecationReason - } - possibleTypes { - ...TypeRef - } - } - - fragment InputValue on __InputValue { - name - ${descriptions} - type { ...TypeRef } - defaultValue - ${inputDeprecation('isDeprecated')} - ${inputDeprecation('deprecationReason')} - } - - fragment TypeRef on __Type { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - } - } - } - } - } - } - } - } - } - } - `; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/getOperationAST.mjs": - /*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/getOperationAST.mjs ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getOperationAST = getOperationAST; - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - /** - * Returns an operation AST given a document AST and optionally an operation - * name. If a name is not provided, an operation is only returned if only one is - * provided in the document. - */ - - function getOperationAST(documentAST, operationName) { - let operation = null; - for (const definition of documentAST.definitions) { - if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { - var _definition$name; - if (operationName == null) { - // If no operation name was provided, only return an Operation if there - // is one defined in the document. Upon encountering the second, return - // null. - if (operation) { - return null; - } - operation = definition; - } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) { - return definition; - } - } - } - return operation; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/getOperationRootType.mjs": - /*!************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/getOperationRootType.mjs ***! - \************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getOperationRootType = getOperationRootType; - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Extracts the root type of the operation from the schema. - * - * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 - */ - function getOperationRootType(schema, operation) { - if (operation.operation === 'query') { - const queryType = schema.getQueryType(); - if (!queryType) { - throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', { - nodes: operation - }); - } - return queryType; - } - if (operation.operation === 'mutation') { - const mutationType = schema.getMutationType(); - if (!mutationType) { - throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', { - nodes: operation - }); - } - return mutationType; - } - if (operation.operation === 'subscription') { - const subscriptionType = schema.getSubscriptionType(); - if (!subscriptionType) { - throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', { - nodes: operation - }); - } - return subscriptionType; - } - throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', { - nodes: operation - }); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/index.mjs": - /*!*********************************************************!*\ - !*** ../../../node_modules/graphql/utilities/index.mjs ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "BreakingChangeType", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.BreakingChangeType; - } - })); - Object.defineProperty(exports, "DangerousChangeType", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.DangerousChangeType; - } - })); - Object.defineProperty(exports, "TypeInfo", ({ - enumerable: true, - get: function () { - return _TypeInfo.TypeInfo; - } - })); - Object.defineProperty(exports, "assertValidName", ({ - enumerable: true, - get: function () { - return _assertValidName.assertValidName; - } - })); - Object.defineProperty(exports, "astFromValue", ({ - enumerable: true, - get: function () { - return _astFromValue.astFromValue; - } - })); - Object.defineProperty(exports, "buildASTSchema", ({ - enumerable: true, - get: function () { - return _buildASTSchema.buildASTSchema; - } - })); - Object.defineProperty(exports, "buildClientSchema", ({ - enumerable: true, - get: function () { - return _buildClientSchema.buildClientSchema; - } - })); - Object.defineProperty(exports, "buildSchema", ({ - enumerable: true, - get: function () { - return _buildASTSchema.buildSchema; - } - })); - Object.defineProperty(exports, "coerceInputValue", ({ - enumerable: true, - get: function () { - return _coerceInputValue.coerceInputValue; - } - })); - Object.defineProperty(exports, "concatAST", ({ - enumerable: true, - get: function () { - return _concatAST.concatAST; - } - })); - Object.defineProperty(exports, "doTypesOverlap", ({ - enumerable: true, - get: function () { - return _typeComparators.doTypesOverlap; - } - })); - Object.defineProperty(exports, "extendSchema", ({ - enumerable: true, - get: function () { - return _extendSchema.extendSchema; - } - })); - Object.defineProperty(exports, "findBreakingChanges", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.findBreakingChanges; - } - })); - Object.defineProperty(exports, "findDangerousChanges", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.findDangerousChanges; - } - })); - Object.defineProperty(exports, "getIntrospectionQuery", ({ - enumerable: true, - get: function () { - return _getIntrospectionQuery.getIntrospectionQuery; - } - })); - Object.defineProperty(exports, "getOperationAST", ({ - enumerable: true, - get: function () { - return _getOperationAST.getOperationAST; - } - })); - Object.defineProperty(exports, "getOperationRootType", ({ - enumerable: true, - get: function () { - return _getOperationRootType.getOperationRootType; - } - })); - Object.defineProperty(exports, "introspectionFromSchema", ({ - enumerable: true, - get: function () { - return _introspectionFromSchema.introspectionFromSchema; - } - })); - Object.defineProperty(exports, "isEqualType", ({ - enumerable: true, - get: function () { - return _typeComparators.isEqualType; - } - })); - Object.defineProperty(exports, "isTypeSubTypeOf", ({ - enumerable: true, - get: function () { - return _typeComparators.isTypeSubTypeOf; - } - })); - Object.defineProperty(exports, "isValidNameError", ({ - enumerable: true, - get: function () { - return _assertValidName.isValidNameError; - } - })); - Object.defineProperty(exports, "lexicographicSortSchema", ({ - enumerable: true, - get: function () { - return _lexicographicSortSchema.lexicographicSortSchema; - } - })); - Object.defineProperty(exports, "printIntrospectionSchema", ({ - enumerable: true, - get: function () { - return _printSchema.printIntrospectionSchema; - } - })); - Object.defineProperty(exports, "printSchema", ({ - enumerable: true, - get: function () { - return _printSchema.printSchema; - } - })); - Object.defineProperty(exports, "printType", ({ - enumerable: true, - get: function () { - return _printSchema.printType; - } - })); - Object.defineProperty(exports, "separateOperations", ({ - enumerable: true, - get: function () { - return _separateOperations.separateOperations; - } - })); - Object.defineProperty(exports, "stripIgnoredCharacters", ({ - enumerable: true, - get: function () { - return _stripIgnoredCharacters.stripIgnoredCharacters; - } - })); - Object.defineProperty(exports, "typeFromAST", ({ - enumerable: true, - get: function () { - return _typeFromAST.typeFromAST; - } - })); - Object.defineProperty(exports, "valueFromAST", ({ - enumerable: true, - get: function () { - return _valueFromAST.valueFromAST; - } - })); - Object.defineProperty(exports, "valueFromASTUntyped", ({ - enumerable: true, - get: function () { - return _valueFromASTUntyped.valueFromASTUntyped; - } - })); - Object.defineProperty(exports, "visitWithTypeInfo", ({ - enumerable: true, - get: function () { - return _TypeInfo.visitWithTypeInfo; - } - })); - var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); - var _getOperationAST = __webpack_require__(/*! ./getOperationAST.mjs */ "../../../node_modules/graphql/utilities/getOperationAST.mjs"); - var _getOperationRootType = __webpack_require__(/*! ./getOperationRootType.mjs */ "../../../node_modules/graphql/utilities/getOperationRootType.mjs"); - var _introspectionFromSchema = __webpack_require__(/*! ./introspectionFromSchema.mjs */ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs"); - var _buildClientSchema = __webpack_require__(/*! ./buildClientSchema.mjs */ "../../../node_modules/graphql/utilities/buildClientSchema.mjs"); - var _buildASTSchema = __webpack_require__(/*! ./buildASTSchema.mjs */ "../../../node_modules/graphql/utilities/buildASTSchema.mjs"); - var _extendSchema = __webpack_require__(/*! ./extendSchema.mjs */ "../../../node_modules/graphql/utilities/extendSchema.mjs"); - var _lexicographicSortSchema = __webpack_require__(/*! ./lexicographicSortSchema.mjs */ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs"); - var _printSchema = __webpack_require__(/*! ./printSchema.mjs */ "../../../node_modules/graphql/utilities/printSchema.mjs"); - var _typeFromAST = __webpack_require__(/*! ./typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - var _valueFromAST = __webpack_require__(/*! ./valueFromAST.mjs */ "../../../node_modules/graphql/utilities/valueFromAST.mjs"); - var _valueFromASTUntyped = __webpack_require__(/*! ./valueFromASTUntyped.mjs */ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs"); - var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); - var _TypeInfo = __webpack_require__(/*! ./TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); - var _coerceInputValue = __webpack_require__(/*! ./coerceInputValue.mjs */ "../../../node_modules/graphql/utilities/coerceInputValue.mjs"); - var _concatAST = __webpack_require__(/*! ./concatAST.mjs */ "../../../node_modules/graphql/utilities/concatAST.mjs"); - var _separateOperations = __webpack_require__(/*! ./separateOperations.mjs */ "../../../node_modules/graphql/utilities/separateOperations.mjs"); - var _stripIgnoredCharacters = __webpack_require__(/*! ./stripIgnoredCharacters.mjs */ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs"); - var _typeComparators = __webpack_require__(/*! ./typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); - var _assertValidName = __webpack_require__(/*! ./assertValidName.mjs */ "../../../node_modules/graphql/utilities/assertValidName.mjs"); - var _findBreakingChanges = __webpack_require__(/*! ./findBreakingChanges.mjs */ "../../../node_modules/graphql/utilities/findBreakingChanges.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/introspectionFromSchema.mjs": - /*!***************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/introspectionFromSchema.mjs ***! - \***************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.introspectionFromSchema = introspectionFromSchema; - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _parser = __webpack_require__(/*! ../language/parser.mjs */ "../../../node_modules/graphql/language/parser.mjs"); - var _execute = __webpack_require__(/*! ../execution/execute.mjs */ "../../../node_modules/graphql/execution/execute.mjs"); - var _getIntrospectionQuery = __webpack_require__(/*! ./getIntrospectionQuery.mjs */ "../../../node_modules/graphql/utilities/getIntrospectionQuery.mjs"); - /** - * Build an IntrospectionQuery from a GraphQLSchema - * - * IntrospectionQuery is useful for utilities that care about type and field - * relationships, but do not need to traverse through those relationships. - * - * This is the inverse of buildClientSchema. The primary use case is outside - * of the server context, for instance when doing schema comparisons. - */ - - function introspectionFromSchema(schema, options) { - const optionsWithDefaults = { - specifiedByUrl: true, - directiveIsRepeatable: true, - schemaDescription: true, - inputValueDeprecation: true, - ...options - }; - const document = (0, _parser.parse)((0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults)); - const result = (0, _execute.executeSync)({ - schema, - document - }); - !result.errors && result.data || (0, _invariant.invariant)(false); - return result.data; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs": - /*!***************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/lexicographicSortSchema.mjs ***! - \***************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.lexicographicSortSchema = lexicographicSortSchema; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); - var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _schema = __webpack_require__(/*! ../type/schema.mjs */ "../../../node_modules/graphql/type/schema.mjs"); - /** - * Sort GraphQLSchema. - * - * This function returns a sorted copy of the given GraphQLSchema. - */ - - function lexicographicSortSchema(schema) { - const schemaConfig = schema.toConfig(); - const typeMap = (0, _keyValMap.keyValMap)(sortByName(schemaConfig.types), type => type.name, sortNamedType); - return new _schema.GraphQLSchema({ - ...schemaConfig, - types: Object.values(typeMap), - directives: sortByName(schemaConfig.directives).map(sortDirective), - query: replaceMaybeType(schemaConfig.query), - mutation: replaceMaybeType(schemaConfig.mutation), - subscription: replaceMaybeType(schemaConfig.subscription) - }); - function replaceType(type) { - if ((0, _definition.isListType)(type)) { - // @ts-expect-error - return new _definition.GraphQLList(replaceType(type.ofType)); - } else if ((0, _definition.isNonNullType)(type)) { - // @ts-expect-error - return new _definition.GraphQLNonNull(replaceType(type.ofType)); - } // @ts-expect-error FIXME: TS Conversion - - return replaceNamedType(type); - } - function replaceNamedType(type) { - return typeMap[type.name]; - } - function replaceMaybeType(maybeType) { - return maybeType && replaceNamedType(maybeType); - } - function sortDirective(directive) { - const config = directive.toConfig(); - return new _directives.GraphQLDirective({ - ...config, - locations: sortBy(config.locations, x => x), - args: sortArgs(config.args) - }); - } - function sortArgs(args) { - return sortObjMap(args, arg => ({ - ...arg, - type: replaceType(arg.type) - })); - } - function sortFields(fieldsMap) { - return sortObjMap(fieldsMap, field => ({ - ...field, - type: replaceType(field.type), - args: field.args && sortArgs(field.args) - })); - } - function sortInputFields(fieldsMap) { - return sortObjMap(fieldsMap, field => ({ - ...field, - type: replaceType(field.type) - })); - } - function sortTypes(array) { - return sortByName(array).map(replaceNamedType); - } - function sortNamedType(type) { - if ((0, _definition.isScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { - return type; - } - if ((0, _definition.isObjectType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLObjectType({ - ...config, - interfaces: () => sortTypes(config.interfaces), - fields: () => sortFields(config.fields) - }); - } - if ((0, _definition.isInterfaceType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLInterfaceType({ - ...config, - interfaces: () => sortTypes(config.interfaces), - fields: () => sortFields(config.fields) - }); - } - if ((0, _definition.isUnionType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLUnionType({ - ...config, - types: () => sortTypes(config.types) - }); - } - if ((0, _definition.isEnumType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLEnumType({ - ...config, - values: sortObjMap(config.values, value => value) - }); - } - if ((0, _definition.isInputObjectType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLInputObjectType({ - ...config, - fields: () => sortInputFields(config.fields) - }); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } - } - function sortObjMap(map, sortValueFn) { - const sortedMap = Object.create(null); - for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { - sortedMap[key] = sortValueFn(map[key]); - } - return sortedMap; - } - function sortByName(array) { - return sortBy(array, obj => obj.name); - } - function sortBy(array, mapToKey) { - return array.slice().sort((obj1, obj2) => { - const key1 = mapToKey(obj1); - const key2 = mapToKey(obj2); - return (0, _naturalCompare.naturalCompare)(key1, key2); - }); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/printSchema.mjs": - /*!***************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/printSchema.mjs ***! - \***************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.printIntrospectionSchema = printIntrospectionSchema; - exports.printSchema = printSchema; - exports.printType = printType; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _printer = __webpack_require__(/*! ../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - var _introspection = __webpack_require__(/*! ../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _scalars = __webpack_require__(/*! ../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - var _astFromValue = __webpack_require__(/*! ./astFromValue.mjs */ "../../../node_modules/graphql/utilities/astFromValue.mjs"); - function printSchema(schema) { - return printFilteredSchema(schema, n => !(0, _directives.isSpecifiedDirective)(n), isDefinedType); - } - function printIntrospectionSchema(schema) { - return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType); - } - function isDefinedType(type) { - return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); - } - function printFilteredSchema(schema, directiveFilter, typeFilter) { - const directives = schema.getDirectives().filter(directiveFilter); - const types = Object.values(schema.getTypeMap()).filter(typeFilter); - return [printSchemaDefinition(schema), ...directives.map(directive => printDirective(directive)), ...types.map(type => printType(type))].filter(Boolean).join('\n\n'); - } - function printSchemaDefinition(schema) { - if (schema.description == null && isSchemaOfCommonNames(schema)) { - return; - } - const operationTypes = []; - const queryType = schema.getQueryType(); - if (queryType) { - operationTypes.push(` query: ${queryType.name}`); - } - const mutationType = schema.getMutationType(); - if (mutationType) { - operationTypes.push(` mutation: ${mutationType.name}`); - } - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType) { - operationTypes.push(` subscription: ${subscriptionType.name}`); - } - return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; - } - /** - * GraphQL schema define root types for each type of operation. These types are - * the same as any other type and can be named in any manner, however there is - * a common naming convention: - * - * ```graphql - * schema { - * query: Query - * mutation: Mutation - * subscription: Subscription - * } - * ``` - * - * When using this naming convention, the schema description can be omitted. - */ - - function isSchemaOfCommonNames(schema) { - const queryType = schema.getQueryType(); - if (queryType && queryType.name !== 'Query') { - return false; - } - const mutationType = schema.getMutationType(); - if (mutationType && mutationType.name !== 'Mutation') { - return false; - } - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType && subscriptionType.name !== 'Subscription') { - return false; - } - return true; - } - function printType(type) { - if ((0, _definition.isScalarType)(type)) { - return printScalar(type); - } - if ((0, _definition.isObjectType)(type)) { - return printObject(type); - } - if ((0, _definition.isInterfaceType)(type)) { - return printInterface(type); - } - if ((0, _definition.isUnionType)(type)) { - return printUnion(type); - } - if ((0, _definition.isEnumType)(type)) { - return printEnum(type); - } - if ((0, _definition.isInputObjectType)(type)) { - return printInputObject(type); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } - function printScalar(type) { - return printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type); - } - function printImplementedInterfaces(type) { - const interfaces = type.getInterfaces(); - return interfaces.length ? ' implements ' + interfaces.map(i => i.name).join(' & ') : ''; - } - function printObject(type) { - return printDescription(type) + `type ${type.name}` + printImplementedInterfaces(type) + printFields(type); - } - function printInterface(type) { - return printDescription(type) + `interface ${type.name}` + printImplementedInterfaces(type) + printFields(type); - } - function printUnion(type) { - const types = type.getTypes(); - const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; - return printDescription(type) + 'union ' + type.name + possibleTypes; - } - function printEnum(type) { - const values = type.getValues().map((value, i) => printDescription(value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason)); - return printDescription(type) + `enum ${type.name}` + printBlock(values); - } - function printInputObject(type) { - const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f)); - return printDescription(type) + `input ${type.name}` + printBlock(fields); - } - function printFields(type) { - const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, ' ', !i) + ' ' + f.name + printArgs(f.args, ' ') + ': ' + String(f.type) + printDeprecated(f.deprecationReason)); - return printBlock(fields); - } - function printBlock(items) { - return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; - } - function printArgs(args, indentation = '') { - if (args.length === 0) { - return ''; - } // If every arg does not have a description, print them on one line. - - if (args.every(arg => !arg.description)) { - return '(' + args.map(printInputValue).join(', ') + ')'; - } - return '(\n' + args.map((arg, i) => printDescription(arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg)).join('\n') + '\n' + indentation + ')'; - } - function printInputValue(arg) { - const defaultAST = (0, _astFromValue.astFromValue)(arg.defaultValue, arg.type); - let argDecl = arg.name + ': ' + String(arg.type); - if (defaultAST) { - argDecl += ` = ${(0, _printer.print)(defaultAST)}`; - } - return argDecl + printDeprecated(arg.deprecationReason); - } - function printDirective(directive) { - return printDescription(directive) + 'directive @' + directive.name + printArgs(directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | '); - } - function printDeprecated(reason) { - if (reason == null) { - return ''; - } - if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { - const astValue = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: reason - }); - return ` @deprecated(reason: ${astValue})`; - } - return ' @deprecated'; - } - function printSpecifiedByURL(scalar) { - if (scalar.specifiedByURL == null) { - return ''; - } - const astValue = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: scalar.specifiedByURL - }); - return ` @specifiedBy(url: ${astValue})`; - } - function printDescription(def, indentation = '', firstInBlock = true) { - const { - description - } = def; - if (description == null) { - return ''; - } - const blockString = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: description, - block: (0, _blockString.isPrintableAsBlockString)(description) - }); - const prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; - return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/separateOperations.mjs": - /*!**********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/separateOperations.mjs ***! - \**********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.separateOperations = separateOperations; - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); - /** - * separateOperations accepts a single AST document which may contain many - * operations and fragments and returns a collection of AST documents each of - * which contains a single operation as well the fragment definitions it - * refers to. - */ - - function separateOperations(documentAST) { - const operations = []; - const depGraph = Object.create(null); // Populate metadata and build a dependency graph. - - for (const definitionNode of documentAST.definitions) { - switch (definitionNode.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - operations.push(definitionNode); - break; - case _kinds.Kind.FRAGMENT_DEFINITION: - depGraph[definitionNode.name.value] = collectDependencies(definitionNode.selectionSet); - break; - default: // ignore non-executable definitions - } - } // For each operation, produce a new synthesized AST which includes only what - // is necessary for completing that operation. - - const separatedDocumentASTs = Object.create(null); - for (const operation of operations) { - const dependencies = new Set(); - for (const fragmentName of collectDependencies(operation.selectionSet)) { - collectTransitiveDependencies(dependencies, depGraph, fragmentName); - } // Provides the empty string for anonymous operations. - - const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted - // to retain the same order as the original document. - - separatedDocumentASTs[operationName] = { - kind: _kinds.Kind.DOCUMENT, - definitions: documentAST.definitions.filter(node => node === operation || node.kind === _kinds.Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value)) - }; - } - return separatedDocumentASTs; - } - - // From a dependency graph, collects a list of transitive dependencies by - // recursing through a dependency graph. - function collectTransitiveDependencies(collected, depGraph, fromName) { - if (!collected.has(fromName)) { - collected.add(fromName); - const immediateDeps = depGraph[fromName]; - if (immediateDeps !== undefined) { - for (const toName of immediateDeps) { - collectTransitiveDependencies(collected, depGraph, toName); - } - } - } - } - function collectDependencies(selectionSet) { - const dependencies = []; - (0, _visitor.visit)(selectionSet, { - FragmentSpread(node) { - dependencies.push(node.name.value); - } - }); - return dependencies; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/sortValueNode.mjs": - /*!*****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/sortValueNode.mjs ***! - \*****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.sortValueNode = sortValueNode; - var _naturalCompare = __webpack_require__(/*! ../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - /** - * Sort ValueNode. - * - * This function returns a sorted copy of the given ValueNode. - * - * @internal - */ - - function sortValueNode(valueNode) { - switch (valueNode.kind) { - case _kinds.Kind.OBJECT: - return { - ...valueNode, - fields: sortFields(valueNode.fields) - }; - case _kinds.Kind.LIST: - return { - ...valueNode, - values: valueNode.values.map(sortValueNode) - }; - case _kinds.Kind.INT: - case _kinds.Kind.FLOAT: - case _kinds.Kind.STRING: - case _kinds.Kind.BOOLEAN: - case _kinds.Kind.NULL: - case _kinds.Kind.ENUM: - case _kinds.Kind.VARIABLE: - return valueNode; - } - } - function sortFields(fields) { - return fields.map(fieldNode => ({ - ...fieldNode, - value: sortValueNode(fieldNode.value) - })).sort((fieldA, fieldB) => (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value)); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs": - /*!**************************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/stripIgnoredCharacters.mjs ***! - \**************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.stripIgnoredCharacters = stripIgnoredCharacters; - var _blockString = __webpack_require__(/*! ../language/blockString.mjs */ "../../../node_modules/graphql/language/blockString.mjs"); - var _lexer = __webpack_require__(/*! ../language/lexer.mjs */ "../../../node_modules/graphql/language/lexer.mjs"); - var _source = __webpack_require__(/*! ../language/source.mjs */ "../../../node_modules/graphql/language/source.mjs"); - var _tokenKind = __webpack_require__(/*! ../language/tokenKind.mjs */ "../../../node_modules/graphql/language/tokenKind.mjs"); - /** - * Strips characters that are not significant to the validity or execution - * of a GraphQL document: - * - UnicodeBOM - * - WhiteSpace - * - LineTerminator - * - Comment - * - Comma - * - BlockString indentation - * - * Note: It is required to have a delimiter character between neighboring - * non-punctuator tokens and this function always uses single space as delimiter. - * - * It is guaranteed that both input and output documents if parsed would result - * in the exact same AST except for nodes location. - * - * Warning: It is guaranteed that this function will always produce stable results. - * However, it's not guaranteed that it will stay the same between different - * releases due to bugfixes or changes in the GraphQL specification. - * - * Query example: - * - * ```graphql - * query SomeQuery($foo: String!, $bar: String) { - * someField(foo: $foo, bar: $bar) { - * a - * b { - * c - * d - * } - * } - * } - * ``` - * - * Becomes: - * - * ```graphql - * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} - * ``` - * - * SDL example: - * - * ```graphql - * """ - * Type description - * """ - * type Foo { - * """ - * Field description - * """ - * bar: String - * } - * ``` - * - * Becomes: - * - * ```graphql - * """Type description""" type Foo{"""Field description""" bar:String} - * ``` - */ - - function stripIgnoredCharacters(source) { - const sourceObj = (0, _source.isSource)(source) ? source : new _source.Source(source); - const body = sourceObj.body; - const lexer = new _lexer.Lexer(sourceObj); - let strippedBody = ''; - let wasLastAddedTokenNonPunctuator = false; - while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { - const currentToken = lexer.token; - const tokenKind = currentToken.kind; - /** - * Every two non-punctuator tokens should have space between them. - * Also prevent case of non-punctuator token following by spread resulting - * in invalid token (e.g. `1...` is invalid Float token). - */ - - const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)(currentToken.kind); - if (wasLastAddedTokenNonPunctuator) { - if (isNonPunctuator || currentToken.kind === _tokenKind.TokenKind.SPREAD) { - strippedBody += ' '; - } - } - const tokenBody = body.slice(currentToken.start, currentToken.end); - if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { - strippedBody += (0, _blockString.printBlockString)(currentToken.value, { - minimize: true - }); - } else { - strippedBody += tokenBody; - } - wasLastAddedTokenNonPunctuator = isNonPunctuator; - } - return strippedBody; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/typeComparators.mjs": - /*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/typeComparators.mjs ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.doTypesOverlap = doTypesOverlap; - exports.isEqualType = isEqualType; - exports.isTypeSubTypeOf = isTypeSubTypeOf; - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Provided two types, return true if the types are equal (invariant). - */ - function isEqualType(typeA, typeB) { - // Equivalent types are equal. - if (typeA === typeB) { - return true; - } // If either type is non-null, the other must also be non-null. - - if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) { - return isEqualType(typeA.ofType, typeB.ofType); - } // If either type is a list, the other must also be a list. - - if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) { - return isEqualType(typeA.ofType, typeB.ofType); - } // Otherwise the types are not equal. - - return false; - } - /** - * Provided a type and a super type, return true if the first type is either - * equal or a subset of the second super type (covariant). - */ - - function isTypeSubTypeOf(schema, maybeSubType, superType) { - // Equivalent type is a valid subtype - if (maybeSubType === superType) { - return true; - } // If superType is non-null, maybeSubType must also be non-null. - - if ((0, _definition.isNonNullType)(superType)) { - if ((0, _definition.isNonNullType)(maybeSubType)) { - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); - } - return false; - } - if ((0, _definition.isNonNullType)(maybeSubType)) { - // If superType is nullable, maybeSubType may be non-null or nullable. - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); - } // If superType type is a list, maybeSubType type must also be a list. - - if ((0, _definition.isListType)(superType)) { - if ((0, _definition.isListType)(maybeSubType)) { - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); - } - return false; - } - if ((0, _definition.isListType)(maybeSubType)) { - // If superType is not a list, maybeSubType must also be not a list. - return false; - } // If superType type is an abstract type, check if it is super type of maybeSubType. - // Otherwise, the child type is not a valid subtype of the parent type. - - return (0, _definition.isAbstractType)(superType) && ((0, _definition.isInterfaceType)(maybeSubType) || (0, _definition.isObjectType)(maybeSubType)) && schema.isSubType(superType, maybeSubType); - } - /** - * Provided two composite types, determine if they "overlap". Two composite - * types overlap when the Sets of possible concrete types for each intersect. - * - * This is often used to determine if a fragment of a given type could possibly - * be visited in a context of another type. - * - * This function is commutative. - */ - - function doTypesOverlap(schema, typeA, typeB) { - // Equivalent types overlap - if (typeA === typeB) { - return true; - } - if ((0, _definition.isAbstractType)(typeA)) { - if ((0, _definition.isAbstractType)(typeB)) { - // If both types are abstract, then determine if there is any intersection - // between possible concrete types of each. - return schema.getPossibleTypes(typeA).some(type => schema.isSubType(typeB, type)); - } // Determine if the latter type is a possible concrete type of the former. - - return schema.isSubType(typeA, typeB); - } - if ((0, _definition.isAbstractType)(typeB)) { - // Determine if the former type is a possible concrete type of the latter. - return schema.isSubType(typeB, typeA); - } // Otherwise the types do not overlap. - - return false; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/typeFromAST.mjs": - /*!***************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/typeFromAST.mjs ***! - \***************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.typeFromAST = typeFromAST; - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - function typeFromAST(schema, typeNode) { - switch (typeNode.kind) { - case _kinds.Kind.LIST_TYPE: - { - const innerType = typeFromAST(schema, typeNode.type); - return innerType && new _definition.GraphQLList(innerType); - } - case _kinds.Kind.NON_NULL_TYPE: - { - const innerType = typeFromAST(schema, typeNode.type); - return innerType && new _definition.GraphQLNonNull(innerType); - } - case _kinds.Kind.NAMED_TYPE: - return schema.getType(typeNode.name.value); - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/valueFromAST.mjs": - /*!****************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/valueFromAST.mjs ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.valueFromAST = valueFromAST; - var _inspect = __webpack_require__(/*! ../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _keyMap = __webpack_require__(/*! ../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _definition = __webpack_require__(/*! ../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Produces a JavaScript value given a GraphQL Value AST. - * - * A GraphQL type must be provided, which will be used to interpret different - * GraphQL Value literals. - * - * Returns `undefined` when the value could not be validly coerced according to - * the provided type. - * - * | GraphQL Value | JSON Value | - * | -------------------- | ------------- | - * | Input Object | Object | - * | List | Array | - * | Boolean | Boolean | - * | String | String | - * | Int / Float | Number | - * | Enum Value | Unknown | - * | NullValue | null | - * - */ - - function valueFromAST(valueNode, type, variables) { - if (!valueNode) { - // When there is no node, then there is also no value. - // Importantly, this is different from returning the value null. - return; - } - if (valueNode.kind === _kinds.Kind.VARIABLE) { - const variableName = valueNode.name.value; - if (variables == null || variables[variableName] === undefined) { - // No valid return value. - return; - } - const variableValue = variables[variableName]; - if (variableValue === null && (0, _definition.isNonNullType)(type)) { - return; // Invalid: intentionally return no value. - } // Note: This does no further checking that this variable is correct. - // This assumes that this query has been validated and the variable - // usage here is of the correct type. - - return variableValue; - } - if ((0, _definition.isNonNullType)(type)) { - if (valueNode.kind === _kinds.Kind.NULL) { - return; // Invalid: intentionally return no value. - } - return valueFromAST(valueNode, type.ofType, variables); - } - if (valueNode.kind === _kinds.Kind.NULL) { - // This is explicitly returning the value null. - return null; - } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; - if (valueNode.kind === _kinds.Kind.LIST) { - const coercedValues = []; - for (const itemNode of valueNode.values) { - if (isMissingVariable(itemNode, variables)) { - // If an array contains a missing variable, it is either coerced to - // null or if the item type is non-null, it considered invalid. - if ((0, _definition.isNonNullType)(itemType)) { - return; // Invalid: intentionally return no value. - } - coercedValues.push(null); - } else { - const itemValue = valueFromAST(itemNode, itemType, variables); - if (itemValue === undefined) { - return; // Invalid: intentionally return no value. - } - coercedValues.push(itemValue); - } - } - return coercedValues; - } - const coercedValue = valueFromAST(valueNode, itemType, variables); - if (coercedValue === undefined) { - return; // Invalid: intentionally return no value. - } - return [coercedValue]; - } - if ((0, _definition.isInputObjectType)(type)) { - if (valueNode.kind !== _kinds.Kind.OBJECT) { - return; // Invalid: intentionally return no value. - } - const coercedObj = Object.create(null); - const fieldNodes = (0, _keyMap.keyMap)(valueNode.fields, field => field.name.value); - for (const field of Object.values(type.getFields())) { - const fieldNode = fieldNodes[field.name]; - if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { - if (field.defaultValue !== undefined) { - coercedObj[field.name] = field.defaultValue; - } else if ((0, _definition.isNonNullType)(field.type)) { - return; // Invalid: intentionally return no value. - } - continue; - } - const fieldValue = valueFromAST(fieldNode.value, field.type, variables); - if (fieldValue === undefined) { - return; // Invalid: intentionally return no value. - } - coercedObj[field.name] = fieldValue; - } - return coercedObj; - } - if ((0, _definition.isLeafType)(type)) { - // Scalars and Enums fulfill parsing a literal value via parseLiteral(). - // Invalid values represent a failure to parse correctly, in which case - // no value is returned. - let result; - try { - result = type.parseLiteral(valueNode, variables); - } catch (_error) { - return; // Invalid: intentionally return no value. - } - if (result === undefined) { - return; // Invalid: intentionally return no value. - } - return result; - } - /* c8 ignore next 3 */ - // Not reachable, all possible input types have been considered. - - false || (0, _invariant.invariant)(false, 'Unexpected input type: ' + (0, _inspect.inspect)(type)); - } // Returns true if the provided valueNode is a variable which is not defined - // in the set of variables. - - function isMissingVariable(valueNode, variables) { - return valueNode.kind === _kinds.Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs": - /*!***********************************************************************!*\ - !*** ../../../node_modules/graphql/utilities/valueFromASTUntyped.mjs ***! - \***********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.valueFromASTUntyped = valueFromASTUntyped; - var _keyValMap = __webpack_require__(/*! ../jsutils/keyValMap.mjs */ "../../../node_modules/graphql/jsutils/keyValMap.mjs"); - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - /** - * Produces a JavaScript value given a GraphQL Value AST. - * - * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value - * will reflect the provided GraphQL value AST. - * - * | GraphQL Value | JavaScript Value | - * | -------------------- | ---------------- | - * | Input Object | Object | - * | List | Array | - * | Boolean | Boolean | - * | String / Enum | String | - * | Int / Float | Number | - * | Null | null | - * - */ - - function valueFromASTUntyped(valueNode, variables) { - switch (valueNode.kind) { - case _kinds.Kind.NULL: - return null; - case _kinds.Kind.INT: - return parseInt(valueNode.value, 10); - case _kinds.Kind.FLOAT: - return parseFloat(valueNode.value); - case _kinds.Kind.STRING: - case _kinds.Kind.ENUM: - case _kinds.Kind.BOOLEAN: - return valueNode.value; - case _kinds.Kind.LIST: - return valueNode.values.map(node => valueFromASTUntyped(node, variables)); - case _kinds.Kind.OBJECT: - return (0, _keyValMap.keyValMap)(valueNode.fields, field => field.name.value, field => valueFromASTUntyped(field.value, variables)); - case _kinds.Kind.VARIABLE: - return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value]; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/ValidationContext.mjs": - /*!**********************************************************************!*\ - !*** ../../../node_modules/graphql/validation/ValidationContext.mjs ***! - \**********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; - var _kinds = __webpack_require__(/*! ../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); - var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); - /** - * An instance of this class is passed as the "this" context to all validators, - * allowing access to commonly useful contextual information from within a - * validation rule. - */ - class ASTValidationContext { - constructor(ast, onError) { - this._ast = ast; - this._fragments = undefined; - this._fragmentSpreads = new Map(); - this._recursivelyReferencedFragments = new Map(); - this._onError = onError; - } - get [Symbol.toStringTag]() { - return 'ASTValidationContext'; - } - reportError(error) { - this._onError(error); - } - getDocument() { - return this._ast; - } - getFragment(name) { - let fragments; - if (this._fragments) { - fragments = this._fragments; - } else { - fragments = Object.create(null); - for (const defNode of this.getDocument().definitions) { - if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { - fragments[defNode.name.value] = defNode; - } - } - this._fragments = fragments; - } - return fragments[name]; - } - getFragmentSpreads(node) { - let spreads = this._fragmentSpreads.get(node); - if (!spreads) { - spreads = []; - const setsToVisit = [node]; - let set; - while (set = setsToVisit.pop()) { - for (const selection of set.selections) { - if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { - spreads.push(selection); - } else if (selection.selectionSet) { - setsToVisit.push(selection.selectionSet); - } - } - } - this._fragmentSpreads.set(node, spreads); - } - return spreads; - } - getRecursivelyReferencedFragments(operation) { - let fragments = this._recursivelyReferencedFragments.get(operation); - if (!fragments) { - fragments = []; - const collectedNames = Object.create(null); - const nodesToVisit = [operation.selectionSet]; - let node; - while (node = nodesToVisit.pop()) { - for (const spread of this.getFragmentSpreads(node)) { - const fragName = spread.name.value; - if (collectedNames[fragName] !== true) { - collectedNames[fragName] = true; - const fragment = this.getFragment(fragName); - if (fragment) { - fragments.push(fragment); - nodesToVisit.push(fragment.selectionSet); - } - } - } - } - this._recursivelyReferencedFragments.set(operation, fragments); - } - return fragments; - } - } - exports.ASTValidationContext = ASTValidationContext; - class SDLValidationContext extends ASTValidationContext { - constructor(ast, schema, onError) { - super(ast, onError); - this._schema = schema; - } - get [Symbol.toStringTag]() { - return 'SDLValidationContext'; - } - getSchema() { - return this._schema; - } - } - exports.SDLValidationContext = SDLValidationContext; - class ValidationContext extends ASTValidationContext { - constructor(schema, ast, typeInfo, onError) { - super(ast, onError); - this._schema = schema; - this._typeInfo = typeInfo; - this._variableUsages = new Map(); - this._recursiveVariableUsages = new Map(); - } - get [Symbol.toStringTag]() { - return 'ValidationContext'; - } - getSchema() { - return this._schema; - } - getVariableUsages(node) { - let usages = this._variableUsages.get(node); - if (!usages) { - const newUsages = []; - const typeInfo = new _TypeInfo.TypeInfo(this._schema); - (0, _visitor.visit)(node, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { - VariableDefinition: () => false, - Variable(variable) { - newUsages.push({ - node: variable, - type: typeInfo.getInputType(), - defaultValue: typeInfo.getDefaultValue() - }); - } - })); - usages = newUsages; - this._variableUsages.set(node, usages); - } - return usages; - } - getRecursiveVariableUsages(operation) { - let usages = this._recursiveVariableUsages.get(operation); - if (!usages) { - usages = this.getVariableUsages(operation); - for (const frag of this.getRecursivelyReferencedFragments(operation)) { - usages = usages.concat(this.getVariableUsages(frag)); - } - this._recursiveVariableUsages.set(operation, usages); - } - return usages; - } - getType() { - return this._typeInfo.getType(); - } - getParentType() { - return this._typeInfo.getParentType(); - } - getInputType() { - return this._typeInfo.getInputType(); - } - getParentInputType() { - return this._typeInfo.getParentInputType(); - } - getFieldDef() { - return this._typeInfo.getFieldDef(); - } - getDirective() { - return this._typeInfo.getDirective(); - } - getArgument() { - return this._typeInfo.getArgument(); - } - getEnumValue() { - return this._typeInfo.getEnumValue(); - } - } - exports.ValidationContext = ValidationContext; - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/index.mjs": - /*!**********************************************************!*\ - !*** ../../../node_modules/graphql/validation/index.mjs ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ - enumerable: true, - get: function () { - return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; - } - })); - Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; - } - })); - Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ - enumerable: true, - get: function () { - return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; - } - })); - Object.defineProperty(exports, "KnownArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _KnownArgumentNamesRule.KnownArgumentNamesRule; - } - })); - Object.defineProperty(exports, "KnownDirectivesRule", ({ - enumerable: true, - get: function () { - return _KnownDirectivesRule.KnownDirectivesRule; - } - })); - Object.defineProperty(exports, "KnownFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _KnownFragmentNamesRule.KnownFragmentNamesRule; - } - })); - Object.defineProperty(exports, "KnownTypeNamesRule", ({ - enumerable: true, - get: function () { - return _KnownTypeNamesRule.KnownTypeNamesRule; - } - })); - Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ - enumerable: true, - get: function () { - return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; - } - })); - Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ - enumerable: true, - get: function () { - return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; - } - })); - Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ - enumerable: true, - get: function () { - return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; - } - })); - Object.defineProperty(exports, "NoFragmentCyclesRule", ({ - enumerable: true, - get: function () { - return _NoFragmentCyclesRule.NoFragmentCyclesRule; - } - })); - Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ - enumerable: true, - get: function () { - return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; - } - })); - Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ - enumerable: true, - get: function () { - return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; - } - })); - Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ - enumerable: true, - get: function () { - return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; - } - })); - Object.defineProperty(exports, "NoUnusedVariablesRule", ({ - enumerable: true, - get: function () { - return _NoUnusedVariablesRule.NoUnusedVariablesRule; - } - })); - Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ - enumerable: true, - get: function () { - return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; - } - })); - Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ - enumerable: true, - get: function () { - return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; - } - })); - Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ - enumerable: true, - get: function () { - return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; - } - })); - Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ - enumerable: true, - get: function () { - return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; - } - })); - Object.defineProperty(exports, "ScalarLeafsRule", ({ - enumerable: true, - get: function () { - return _ScalarLeafsRule.ScalarLeafsRule; - } - })); - Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ - enumerable: true, - get: function () { - return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; - } - })); - Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; - } - })); - Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; - } - })); - Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; - } - })); - Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ - enumerable: true, - get: function () { - return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; - } - })); - Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; - } - })); - Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; - } - })); - Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; - } - })); - Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; - } - })); - Object.defineProperty(exports, "UniqueOperationNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueOperationNamesRule.UniqueOperationNamesRule; - } - })); - Object.defineProperty(exports, "UniqueOperationTypesRule", ({ - enumerable: true, - get: function () { - return _UniqueOperationTypesRule.UniqueOperationTypesRule; - } - })); - Object.defineProperty(exports, "UniqueTypeNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueTypeNamesRule.UniqueTypeNamesRule; - } - })); - Object.defineProperty(exports, "UniqueVariableNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueVariableNamesRule.UniqueVariableNamesRule; - } - })); - Object.defineProperty(exports, "ValidationContext", ({ - enumerable: true, - get: function () { - return _ValidationContext.ValidationContext; - } - })); - Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; - } - })); - Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ - enumerable: true, - get: function () { - return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; - } - })); - Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ - enumerable: true, - get: function () { - return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; - } - })); - Object.defineProperty(exports, "specifiedRules", ({ - enumerable: true, - get: function () { - return _specifiedRules.specifiedRules; - } - })); - Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.validate; - } - })); - var _validate = __webpack_require__(/*! ./validate.mjs */ "../../../node_modules/graphql/validation/validate.mjs"); - var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); - var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); - var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); - var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); - var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); - var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); - var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); - var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); - var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); - var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); - var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); - var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); - var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); - var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); - var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); - var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); - var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); - var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); - var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); - var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); - var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); - var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); - var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); - var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); - var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); - var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); - var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); - var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); - var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); - var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); - var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); - var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); - var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); - var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); - var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); - var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); - var _NoDeprecatedCustomRule = __webpack_require__(/*! ./rules/custom/NoDeprecatedCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs"); - var _NoSchemaIntrospectionCustomRule = __webpack_require__(/*! ./rules/custom/NoSchemaIntrospectionCustomRule.mjs */ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs"); - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs": - /*!************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs ***! - \************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); - /** - * Executable definitions - * - * A GraphQL document is only valid for execution if all definitions are either - * operation or fragment definitions. - * - * See https://spec.graphql.org/draft/#sec-Executable-Definitions - */ - function ExecutableDefinitionsRule(context) { - return { - Document(node) { - for (const definition of node.definitions) { - if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { - const defName = definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"'; - context.reportError(new _GraphQLError.GraphQLError(`The ${defName} definition is not executable.`, { - nodes: definition - })); - } - } - return false; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs ***! - \**********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; - var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _naturalCompare = __webpack_require__(/*! ../../jsutils/naturalCompare.mjs */ "../../../node_modules/graphql/jsutils/naturalCompare.mjs"); - var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Fields on correct type - * - * A GraphQL document is only valid if all fields selected are defined by the - * parent type, or are an allowed meta field such as __typename. - * - * See https://spec.graphql.org/draft/#sec-Field-Selections - */ - function FieldsOnCorrectTypeRule(context) { - return { - Field(node) { - const type = context.getParentType(); - if (type) { - const fieldDef = context.getFieldDef(); - if (!fieldDef) { - // This field doesn't exist, lets look for suggestions. - const schema = context.getSchema(); - const fieldName = node.name.value; // First determine if there are any suggested types to condition on. - - let suggestion = (0, _didYouMean.didYouMean)('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo? - - if (suggestion === '') { - suggestion = (0, _didYouMean.didYouMean)(getSuggestedFieldNames(type, fieldName)); - } // Report an error, including helpful suggestions. - - context.reportError(new _GraphQLError.GraphQLError(`Cannot query field "${fieldName}" on type "${type.name}".` + suggestion, { - nodes: node - })); - } - } - } - }; - } - /** - * Go through all of the implementations of type, as well as the interfaces that - * they implement. If any of those types include the provided field, suggest them, - * sorted by how often the type is referenced. - */ - - function getSuggestedTypeNames(schema, type, fieldName) { - if (!(0, _definition.isAbstractType)(type)) { - // Must be an Object type, which does not have possible fields. - return []; - } - const suggestedTypes = new Set(); - const usageCount = Object.create(null); - for (const possibleType of schema.getPossibleTypes(type)) { - if (!possibleType.getFields()[fieldName]) { - continue; - } // This object type defines this field. - - suggestedTypes.add(possibleType); - usageCount[possibleType.name] = 1; - for (const possibleInterface of possibleType.getInterfaces()) { - var _usageCount$possibleI; - if (!possibleInterface.getFields()[fieldName]) { - continue; - } // This interface type defines this field. - - suggestedTypes.add(possibleInterface); - usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1; - } - } - return [...suggestedTypes].sort((typeA, typeB) => { - // Suggest both interface and object types based on how common they are. - const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; - if (usageCountDiff !== 0) { - return usageCountDiff; - } // Suggest super types first followed by subtypes - - if ((0, _definition.isInterfaceType)(typeA) && schema.isSubType(typeA, typeB)) { - return -1; - } - if ((0, _definition.isInterfaceType)(typeB) && schema.isSubType(typeB, typeA)) { - return 1; - } - return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); - }).map(x => x.name); - } - /** - * For the field name provided, determine if there are any similar field names - * that may be the result of a typo. - */ - - function getSuggestedFieldNames(type, fieldName) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { - const possibleFieldNames = Object.keys(type.getFields()); - return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); - } // Otherwise, must be a Union type, which does not define fields. - - return []; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs": - /*!****************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs ***! - \****************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - /** - * Fragments on composite type - * - * Fragments use a type condition to determine if they apply, since fragments - * can only be spread into a composite type (object, interface, or union), the - * type condition must also be a composite type. - * - * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types - */ - function FragmentsOnCompositeTypesRule(context) { - return { - InlineFragment(node) { - const typeCondition = node.typeCondition; - if (typeCondition) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); - if (type && !(0, _definition.isCompositeType)(type)) { - const typeStr = (0, _printer.print)(typeCondition); - context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot condition on non composite type "${typeStr}".`, { - nodes: typeCondition - })); - } - } - }, - FragmentDefinition(node) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); - if (type && !(0, _definition.isCompositeType)(type)) { - const typeStr = (0, _printer.print)(node.typeCondition); - context.reportError(new _GraphQLError.GraphQLError(`Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, { - nodes: node.typeCondition - })); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs": - /*!*********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs ***! - \*********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; - exports.KnownArgumentNamesRule = KnownArgumentNamesRule; - var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - /** - * Known argument names - * - * A GraphQL field is only valid if all supplied arguments are defined by - * that field. - * - * See https://spec.graphql.org/draft/#sec-Argument-Names - * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations - */ - function KnownArgumentNamesRule(context) { - return { - // eslint-disable-next-line new-cap - ...KnownArgumentNamesOnDirectivesRule(context), - Argument(argNode) { - const argDef = context.getArgument(); - const fieldDef = context.getFieldDef(); - const parentType = context.getParentType(); - if (!argDef && fieldDef && parentType) { - const argName = argNode.name.value; - const knownArgsNames = fieldDef.args.map(arg => arg.name); - const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgsNames); - context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + (0, _didYouMean.didYouMean)(suggestions), { - nodes: argNode - })); - } - } - }; - } - /** - * @internal - */ - - function KnownArgumentNamesOnDirectivesRule(context) { - const directiveArgs = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - directiveArgs[directive.name] = directive.args.map(arg => arg.name); - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - var _def$arguments; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; - directiveArgs[def.name.value] = argsNodes.map(arg => arg.name.value); - } - } - return { - Directive(directiveNode) { - const directiveName = directiveNode.name.value; - const knownArgs = directiveArgs[directiveName]; - if (directiveNode.arguments && knownArgs) { - for (const argNode of directiveNode.arguments) { - const argName = argNode.name.value; - if (!knownArgs.includes(argName)) { - const suggestions = (0, _suggestionList.suggestionList)(argName, knownArgs); - context.reportError(new _GraphQLError.GraphQLError(`Unknown argument "${argName}" on directive "@${directiveName}".` + (0, _didYouMean.didYouMean)(suggestions), { - nodes: argNode - })); - } - } - } - return false; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs": - /*!******************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs ***! - \******************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.KnownDirectivesRule = KnownDirectivesRule; - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _ast = __webpack_require__(/*! ../../language/ast.mjs */ "../../../node_modules/graphql/language/ast.mjs"); - var _directiveLocation = __webpack_require__(/*! ../../language/directiveLocation.mjs */ "../../../node_modules/graphql/language/directiveLocation.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - /** - * Known directives - * - * A GraphQL document is only valid if all `@directives` are known by the - * schema and legally positioned. - * - * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined - */ - function KnownDirectivesRule(context) { - const locationsMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - locationsMap[directive.name] = directive.locations; - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - locationsMap[def.name.value] = def.locations.map(name => name.value); - } - } - return { - Directive(node, _key, _parent, _path, ancestors) { - const name = node.name.value; - const locations = locationsMap[name]; - if (!locations) { - context.reportError(new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { - nodes: node - })); - return; - } - const candidateLocation = getDirectiveLocationForASTPath(ancestors); - if (candidateLocation && !locations.includes(candidateLocation)) { - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${name}" may not be used on ${candidateLocation}.`, { - nodes: node - })); - } - } - }; - } - function getDirectiveLocationForASTPath(ancestors) { - const appliedTo = ancestors[ancestors.length - 1]; - 'kind' in appliedTo || (0, _invariant.invariant)(false); - switch (appliedTo.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - return getDirectiveLocationForOperation(appliedTo.operation); - case _kinds.Kind.FIELD: - return _directiveLocation.DirectiveLocation.FIELD; - case _kinds.Kind.FRAGMENT_SPREAD: - return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; - case _kinds.Kind.INLINE_FRAGMENT: - return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; - case _kinds.Kind.FRAGMENT_DEFINITION: - return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; - case _kinds.Kind.VARIABLE_DEFINITION: - return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; - case _kinds.Kind.SCHEMA_DEFINITION: - case _kinds.Kind.SCHEMA_EXTENSION: - return _directiveLocation.DirectiveLocation.SCHEMA; - case _kinds.Kind.SCALAR_TYPE_DEFINITION: - case _kinds.Kind.SCALAR_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.SCALAR; - case _kinds.Kind.OBJECT_TYPE_DEFINITION: - case _kinds.Kind.OBJECT_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.OBJECT; - case _kinds.Kind.FIELD_DEFINITION: - return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; - case _kinds.Kind.INTERFACE_TYPE_DEFINITION: - case _kinds.Kind.INTERFACE_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.INTERFACE; - case _kinds.Kind.UNION_TYPE_DEFINITION: - case _kinds.Kind.UNION_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.UNION; - case _kinds.Kind.ENUM_TYPE_DEFINITION: - case _kinds.Kind.ENUM_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.ENUM; - case _kinds.Kind.ENUM_VALUE_DEFINITION: - return _directiveLocation.DirectiveLocation.ENUM_VALUE; - case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: - case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.INPUT_OBJECT; - case _kinds.Kind.INPUT_VALUE_DEFINITION: - { - const parentNode = ancestors[ancestors.length - 3]; - 'kind' in parentNode || (0, _invariant.invariant)(false); - return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; - } - // Not reachable, all possible types have been considered. - - /* c8 ignore next */ - - default: - false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind)); - } - } - function getDirectiveLocationForOperation(operation) { - switch (operation) { - case _ast.OperationTypeNode.QUERY: - return _directiveLocation.DirectiveLocation.QUERY; - case _ast.OperationTypeNode.MUTATION: - return _directiveLocation.DirectiveLocation.MUTATION; - case _ast.OperationTypeNode.SUBSCRIPTION: - return _directiveLocation.DirectiveLocation.SUBSCRIPTION; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs": - /*!*********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs ***! - \*********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.KnownFragmentNamesRule = KnownFragmentNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Known fragment names - * - * A GraphQL document is only valid if all `...Fragment` fragment spreads refer - * to fragments defined in the same document. - * - * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined - */ - function KnownFragmentNamesRule(context) { - return { - FragmentSpread(node) { - const fragmentName = node.name.value; - const fragment = context.getFragment(fragmentName); - if (!fragment) { - context.reportError(new _GraphQLError.GraphQLError(`Unknown fragment "${fragmentName}".`, { - nodes: node.name - })); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs ***! - \*****************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.KnownTypeNamesRule = KnownTypeNamesRule; - var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); - var _introspection = __webpack_require__(/*! ../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - var _scalars = __webpack_require__(/*! ../../type/scalars.mjs */ "../../../node_modules/graphql/type/scalars.mjs"); - /** - * Known type names - * - * A GraphQL document is only valid if referenced types (specifically - * variable definitions and fragment conditions) are defined by the type schema. - * - * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence - */ - function KnownTypeNamesRule(context) { - const schema = context.getSchema(); - const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); - const definedTypes = Object.create(null); - for (const def of context.getDocument().definitions) { - if ((0, _predicates.isTypeDefinitionNode)(def)) { - definedTypes[def.name.value] = true; - } - } - const typeNames = [...Object.keys(existingTypesMap), ...Object.keys(definedTypes)]; - return { - NamedType(node, _1, parent, _2, ancestors) { - const typeName = node.name.value; - if (!existingTypesMap[typeName] && !definedTypes[typeName]) { - var _ancestors$; - const definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent; - const isSDL = definitionNode != null && isSDLNode(definitionNode); - if (isSDL && standardTypeNames.includes(typeName)) { - return; - } - const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames); - context.reportError(new _GraphQLError.GraphQLError(`Unknown type "${typeName}".` + (0, _didYouMean.didYouMean)(suggestedTypes), { - nodes: node - })); - } - } - }; - } - const standardTypeNames = [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes].map(type => type.name); - function isSDLNode(value) { - return 'kind' in value && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs": - /*!*************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs ***! - \*************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - /** - * Lone anonymous operation - * - * A GraphQL document is only valid if when it contains an anonymous operation - * (the query short-hand) that it contains only that one operation definition. - * - * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation - */ - function LoneAnonymousOperationRule(context) { - let operationCount = 0; - return { - Document(node) { - operationCount = node.definitions.filter(definition => definition.kind === _kinds.Kind.OPERATION_DEFINITION).length; - }, - OperationDefinition(node) { - if (!node.name && operationCount > 1) { - context.reportError(new _GraphQLError.GraphQLError('This anonymous operation must be the only defined operation.', { - nodes: node - })); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs ***! - \***********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Lone Schema definition - * - * A GraphQL document is only valid if it contains only one schema definition. - */ - function LoneSchemaDefinitionRule(context) { - var _ref, _ref2, _oldSchema$astNode; - const oldSchema = context.getSchema(); - const alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType(); - let schemaDefinitionsCount = 0; - return { - SchemaDefinition(node) { - if (alreadyDefined) { - context.reportError(new _GraphQLError.GraphQLError('Cannot define a new schema within a schema extension.', { - nodes: node - })); - return; - } - if (schemaDefinitionsCount > 0) { - context.reportError(new _GraphQLError.GraphQLError('Must provide only one schema definition.', { - nodes: node - })); - } - ++schemaDefinitionsCount; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs": - /*!*******************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs ***! - \*******************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.NoFragmentCyclesRule = NoFragmentCyclesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * No fragment cycles - * - * The graph of fragment spreads must not form any cycles including spreading itself. - * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. - * - * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles - */ - function NoFragmentCyclesRule(context) { - // Tracks already visited fragments to maintain O(N) and to ensure that cycles - // are not redundantly reported. - const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors - - const spreadPath = []; // Position in the spread path - - const spreadPathIndexByName = Object.create(null); - return { - OperationDefinition: () => false, - FragmentDefinition(node) { - detectCycleRecursive(node); - return false; - } - }; // This does a straight-forward DFS to find cycles. - // It does not terminate when a cycle was found but continues to explore - // the graph to find all possible cycles. - - function detectCycleRecursive(fragment) { - if (visitedFrags[fragment.name.value]) { - return; - } - const fragmentName = fragment.name.value; - visitedFrags[fragmentName] = true; - const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); - if (spreadNodes.length === 0) { - return; - } - spreadPathIndexByName[fragmentName] = spreadPath.length; - for (const spreadNode of spreadNodes) { - const spreadName = spreadNode.name.value; - const cycleIndex = spreadPathIndexByName[spreadName]; - spreadPath.push(spreadNode); - if (cycleIndex === undefined) { - const spreadFragment = context.getFragment(spreadName); - if (spreadFragment) { - detectCycleRecursive(spreadFragment); - } - } else { - const cyclePath = spreadPath.slice(cycleIndex); - const viaPath = cyclePath.slice(0, -1).map(s => '"' + s.name.value + '"').join(', '); - context.reportError(new _GraphQLError.GraphQLError(`Cannot spread fragment "${spreadName}" within itself` + (viaPath !== '' ? ` via ${viaPath}.` : '.'), { - nodes: cyclePath - })); - } - spreadPath.pop(); - } - spreadPathIndexByName[fragmentName] = undefined; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs ***! - \***********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * No undefined variables - * - * A GraphQL operation is only valid if all variables encountered, both directly - * and via fragment spreads, are defined by that operation. - * - * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined - */ - function NoUndefinedVariablesRule(context) { - let variableNameDefined = Object.create(null); - return { - OperationDefinition: { - enter() { - variableNameDefined = Object.create(null); - }, - leave(operation) { - const usages = context.getRecursiveVariableUsages(operation); - for (const { - node - } of usages) { - const varName = node.name.value; - if (variableNameDefined[varName] !== true) { - context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` : `Variable "$${varName}" is not defined.`, { - nodes: [node, operation] - })); - } - } - } - }, - VariableDefinition(node) { - variableNameDefined[node.variable.name.value] = true; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs": - /*!********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs ***! - \********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * No unused fragments - * - * A GraphQL document is only valid if all fragment definitions are spread - * within operations, or spread within other fragments spread within operations. - * - * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used - */ - function NoUnusedFragmentsRule(context) { - const operationDefs = []; - const fragmentDefs = []; - return { - OperationDefinition(node) { - operationDefs.push(node); - return false; - }, - FragmentDefinition(node) { - fragmentDefs.push(node); - return false; - }, - Document: { - leave() { - const fragmentNameUsed = Object.create(null); - for (const operation of operationDefs) { - for (const fragment of context.getRecursivelyReferencedFragments(operation)) { - fragmentNameUsed[fragment.name.value] = true; - } - } - for (const fragmentDef of fragmentDefs) { - const fragName = fragmentDef.name.value; - if (fragmentNameUsed[fragName] !== true) { - context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" is never used.`, { - nodes: fragmentDef - })); - } - } - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs": - /*!********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs ***! - \********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.NoUnusedVariablesRule = NoUnusedVariablesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * No unused variables - * - * A GraphQL operation is only valid if all variables defined by an operation - * are used, either directly or within a spread fragment. - * - * See https://spec.graphql.org/draft/#sec-All-Variables-Used - */ - function NoUnusedVariablesRule(context) { - let variableDefs = []; - return { - OperationDefinition: { - enter() { - variableDefs = []; - }, - leave(operation) { - const variableNameUsed = Object.create(null); - const usages = context.getRecursiveVariableUsages(operation); - for (const { - node - } of usages) { - variableNameUsed[node.name.value] = true; - } - for (const variableDef of variableDefs) { - const variableName = variableDef.variable.name.value; - if (variableNameUsed[variableName] !== true) { - context.reportError(new _GraphQLError.GraphQLError(operation.name ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` : `Variable "$${variableName}" is never used.`, { - nodes: variableDef - })); - } - } - } - }, - VariableDefinition(def) { - variableDefs.push(def); - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs": - /*!*******************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs ***! - \*******************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _sortValueNode = __webpack_require__(/*! ../../utilities/sortValueNode.mjs */ "../../../node_modules/graphql/utilities/sortValueNode.mjs"); - var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - function reasonMessage(reason) { - if (Array.isArray(reason)) { - return reason.map(([responseName, subReason]) => `subfields "${responseName}" conflict because ` + reasonMessage(subReason)).join(' and '); - } - return reason; - } - /** - * Overlapping fields can be merged - * - * A selection set is only valid if all fields (including spreading any - * fragments) either correspond to distinct response names or can be merged - * without ambiguity. - * - * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging - */ - - function OverlappingFieldsCanBeMergedRule(context) { - // A memoization for when two fragments are compared "between" each other for - // conflicts. Two fragments may be compared many times, so memoizing this can - // dramatically improve the performance of this validator. - const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given - // selection set. Selection sets may be asked for this information multiple - // times, so this improves the performance of this validator. - - const cachedFieldsAndFragmentNames = new Map(); - return { - SelectionSet(selectionSet) { - const conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); - for (const [[responseName, reason], fields1, fields2] of conflicts) { - const reasonMsg = reasonMessage(reason); - context.reportError(new _GraphQLError.GraphQLError(`Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, { - nodes: fields1.concat(fields2) - })); - } - } - }; - } - - /** - * Algorithm: - * - * Conflicts occur when two fields exist in a query which will produce the same - * response name, but represent differing values, thus creating a conflict. - * The algorithm below finds all conflicts via making a series of comparisons - * between fields. In order to compare as few fields as possible, this makes - * a series of comparisons "within" sets of fields and "between" sets of fields. - * - * Given any selection set, a collection produces both a set of fields by - * also including all inline fragments, as well as a list of fragments - * referenced by fragment spreads. - * - * A) Each selection set represented in the document first compares "within" its - * collected set of fields, finding any conflicts between every pair of - * overlapping fields. - * Note: This is the *only time* that a the fields "within" a set are compared - * to each other. After this only fields "between" sets are compared. - * - * B) Also, if any fragment is referenced in a selection set, then a - * comparison is made "between" the original set of fields and the - * referenced fragment. - * - * C) Also, if multiple fragments are referenced, then comparisons - * are made "between" each referenced fragment. - * - * D) When comparing "between" a set of fields and a referenced fragment, first - * a comparison is made between each field in the original set of fields and - * each field in the the referenced set of fields. - * - * E) Also, if any fragment is referenced in the referenced selection set, - * then a comparison is made "between" the original set of fields and the - * referenced fragment (recursively referring to step D). - * - * F) When comparing "between" two fragments, first a comparison is made between - * each field in the first referenced set of fields and each field in the the - * second referenced set of fields. - * - * G) Also, any fragments referenced by the first must be compared to the - * second, and any fragments referenced by the second must be compared to the - * first (recursively referring to step F). - * - * H) When comparing two fields, if both have selection sets, then a comparison - * is made "between" both selection sets, first comparing the set of fields in - * the first selection set with the set of fields in the second. - * - * I) Also, if any fragment is referenced in either selection set, then a - * comparison is made "between" the other set of fields and the - * referenced fragment. - * - * J) Also, if two fragments are referenced in both selection sets, then a - * comparison is made "between" the two fragments. - * - */ - // Find all conflicts found "within" a selection set, including those found - // via spreading in fragments. Called when visiting each SelectionSet in the - // GraphQL Document. - function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { - const conflicts = []; - const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet); // (A) Find find all conflicts "within" the fields of this selection set. - // Note: this is the *only place* `collectConflictsWithin` is called. - - collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); - if (fragmentNames.length !== 0) { - // (B) Then collect conflicts between these fields and those represented by - // each spread fragment name found. - for (let i = 0; i < fragmentNames.length; i++) { - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this - // selection set to collect conflicts between fragments spread together. - // This compares each item in the list of fragment names to every other - // item in that same list (except for itself). - - for (let j = i + 1; j < fragmentNames.length; j++) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); - } - } - } - return conflicts; - } // Collect all conflicts found between a set of fields and a fragment reference - // including via spreading in any nested fragments. - - function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { - const fragment = context.getFragment(fragmentName); - if (!fragment) { - return; - } - const [fieldMap2, referencedFragmentNames] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment); // Do not compare a fragment's fieldMap to itself. - - if (fieldMap === fieldMap2) { - return; - } // (D) First collect any conflicts between the provided collection of fields - // and the collection of fields represented by the given fragment. - - collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields - // and any fragment names found in the given fragment. - - for (const referencedFragmentName of referencedFragmentNames) { - // Memoize so two fragments are not compared for conflicts more than once. - if (comparedFragmentPairs.has(referencedFragmentName, fragmentName, areMutuallyExclusive)) { - continue; - } - comparedFragmentPairs.add(referencedFragmentName, fragmentName, areMutuallyExclusive); - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, referencedFragmentName); - } - } // Collect all conflicts found between two fragments, including via spreading in - // any nested fragments. - - function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { - // No need to compare a fragment to itself. - if (fragmentName1 === fragmentName2) { - return; - } // Memoize so two fragments are not compared for conflicts more than once. - - if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { - return; - } - comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); - const fragment1 = context.getFragment(fragmentName1); - const fragment2 = context.getFragment(fragmentName2); - if (!fragment1 || !fragment2) { - return; - } - const [fieldMap1, referencedFragmentNames1] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1); - const [fieldMap2, referencedFragmentNames2] = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2); // (F) First, collect all conflicts between these two collections of fields - // (not including any nested fragments). - - collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested - // fragments spread in the second fragment. - - for (const referencedFragmentName2 of referencedFragmentNames2) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, referencedFragmentName2); - } // (G) Then collect conflicts between the second fragment and any nested - // fragments spread in the first fragment. - - for (const referencedFragmentName1 of referencedFragmentNames1) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, referencedFragmentName1, fragmentName2); - } - } // Find all conflicts found between two selection sets, including those found - // via spreading in fragments. Called when determining if conflicts exist - // between the sub-fields of two overlapping fields. - - function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { - const conflicts = []; - const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1); - const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2); // (H) First, collect all conflicts between these two collections of field. - - collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and - // those referenced by each fragment name associated with the second. - - for (const fragmentName2 of fragmentNames2) { - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentName2); - } // (I) Then collect conflicts between the second collection of fields and - // those referenced by each fragment name associated with the first. - - for (const fragmentName1 of fragmentNames1) { - collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentName1); - } // (J) Also collect conflicts between any fragment names by the first and - // fragment names by the second. This compares each item in the first set of - // names to each item in the second set of names. - - for (const fragmentName1 of fragmentNames1) { - for (const fragmentName2 of fragmentNames2) { - collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2); - } - } - return conflicts; - } // Collect all Conflicts "within" one collection of fields. - - function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { - // A field map is a keyed collection, where each key represents a response - // name and the value at that key is a list of all fields which provide that - // response name. For every response name, if there are multiple fields, they - // must be compared to find a potential conflict. - for (const [responseName, fields] of Object.entries(fieldMap)) { - // This compares every field in the list to every other field in this list - // (except to itself). If the list only has one item, nothing needs to - // be compared. - if (fields.length > 1) { - for (let i = 0; i < fields.length; i++) { - for (let j = i + 1; j < fields.length; j++) { - const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, - // within one collection is never mutually exclusive - responseName, fields[i], fields[j]); - if (conflict) { - conflicts.push(conflict); - } - } - } - } - } - } // Collect all Conflicts between two collections of fields. This is similar to, - // but different from the `collectConflictsWithin` function above. This check - // assumes that `collectConflictsWithin` has already been called on each - // provided collection of fields. This is true because this validator traverses - // each individual selection set. - - function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { - // A field map is a keyed collection, where each key represents a response - // name and the value at that key is a list of all fields which provide that - // response name. For any response name which appears in both provided field - // maps, each field from the first field map must be compared to every field - // in the second field map to find potential conflicts. - for (const [responseName, fields1] of Object.entries(fieldMap1)) { - const fields2 = fieldMap2[responseName]; - if (fields2) { - for (const field1 of fields1) { - for (const field2 of fields2) { - const conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2); - if (conflict) { - conflicts.push(conflict); - } - } - } - } - } - } // Determines if there is a conflict between two particular fields, including - // comparing their sub-fields. - - function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { - const [parentType1, node1, def1] = field1; - const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same - // time, due to the parent types, then it is safe to permit them to diverge - // in aliased field or arguments used as they will not present any ambiguity - // by differing. - // It is known that two parent types could never overlap if they are - // different Object types. Interface or Union types might overlap - if not - // in the current state of the schema, then perhaps in some future version, - // thus may not safely diverge. - - const areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); - if (!areMutuallyExclusive) { - // Two aliases must refer to the same field. - const name1 = node1.name.value; - const name2 = node2.name.value; - if (name1 !== name2) { - return [[responseName, `"${name1}" and "${name2}" are different fields`], [node1], [node2]]; - } // Two field calls must have the same arguments. - - if (!sameArguments(node1, node2)) { - return [[responseName, 'they have differing arguments'], [node1], [node2]]; - } - } // The return type for each field. - - const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; - const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; - if (type1 && type2 && doTypesConflict(type1, type2)) { - return [[responseName, `they return conflicting types "${(0, _inspect.inspect)(type1)}" and "${(0, _inspect.inspect)(type2)}"`], [node1], [node2]]; - } // Collect and compare sub-fields. Use the same "visited fragment names" list - // for both collections so fields in a fragment reference are never - // compared to themselves. - - const selectionSet1 = node1.selectionSet; - const selectionSet2 = node2.selectionSet; - if (selectionSet1 && selectionSet2) { - const conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); - return subfieldConflicts(conflicts, responseName, node1, node2); - } - } - function sameArguments(node1, node2) { - const args1 = node1.arguments; - const args2 = node2.arguments; - if (args1 === undefined || args1.length === 0) { - return args2 === undefined || args2.length === 0; - } - if (args2 === undefined || args2.length === 0) { - return false; - } - /* c8 ignore next */ - - if (args1.length !== args2.length) { - /* c8 ignore next */ - return false; - /* c8 ignore next */ - } - const values2 = new Map(args2.map(({ - name, - value - }) => [name.value, value])); - return args1.every(arg1 => { - const value1 = arg1.value; - const value2 = values2.get(arg1.name.value); - if (value2 === undefined) { - return false; - } - return stringifyValue(value1) === stringifyValue(value2); - }); - } - function stringifyValue(value) { - return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); - } // Two types conflict if both types could not apply to a value simultaneously. - // Composite types are ignored as their individual field types will be compared - // later recursively. However List and Non-Null types must match. - - function doTypesConflict(type1, type2) { - if ((0, _definition.isListType)(type1)) { - return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; - } - if ((0, _definition.isListType)(type2)) { - return true; - } - if ((0, _definition.isNonNullType)(type1)) { - return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; - } - if ((0, _definition.isNonNullType)(type2)) { - return true; - } - if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { - return type1 !== type2; - } - return false; - } // Given a selection set, return the collection of fields (a mapping of response - // name to field nodes and definitions) as well as a list of fragment names - // referenced via fragment spreads. - - function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { - const cached = cachedFieldsAndFragmentNames.get(selectionSet); - if (cached) { - return cached; - } - const nodeAndDefs = Object.create(null); - const fragmentNames = Object.create(null); - _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); - const result = [nodeAndDefs, Object.keys(fragmentNames)]; - cachedFieldsAndFragmentNames.set(selectionSet, result); - return result; - } // Given a reference to a fragment, return the represented collection of fields - // as well as a list of nested fragment names referenced via fragment spreads. - - function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { - // Short-circuit building a type from the node if possible. - const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); - if (cached) { - return cached; - } - const fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); - return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); - } - function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { - for (const selection of selectionSet.selections) { - switch (selection.kind) { - case _kinds.Kind.FIELD: - { - const fieldName = selection.name.value; - let fieldDef; - if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { - fieldDef = parentType.getFields()[fieldName]; - } - const responseName = selection.alias ? selection.alias.value : fieldName; - if (!nodeAndDefs[responseName]) { - nodeAndDefs[responseName] = []; - } - nodeAndDefs[responseName].push([parentType, selection, fieldDef]); - break; - } - case _kinds.Kind.FRAGMENT_SPREAD: - fragmentNames[selection.name.value] = true; - break; - case _kinds.Kind.INLINE_FRAGMENT: - { - const typeCondition = selection.typeCondition; - const inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; - _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); - break; - } - } - } - } // Given a series of Conflicts which occurred between two sub-fields, generate - // a single Conflict. - - function subfieldConflicts(conflicts, responseName, node1, node2) { - if (conflicts.length > 0) { - return [[responseName, conflicts.map(([reason]) => reason)], [node1, ...conflicts.map(([, fields1]) => fields1).flat()], [node2, ...conflicts.map(([,, fields2]) => fields2).flat()]]; - } - } - /** - * A way to keep track of pairs of things when the ordering of the pair does not matter. - */ - - class PairSet { - constructor() { - this._data = new Map(); - } - has(a, b, areMutuallyExclusive) { - var _this$_data$get; - const [key1, key2] = a < b ? [a, b] : [b, a]; - const result = (_this$_data$get = this._data.get(key1)) === null || _this$_data$get === void 0 ? void 0 : _this$_data$get.get(key2); - if (result === undefined) { - return false; - } // areMutuallyExclusive being false is a superset of being true, hence if - // we want to know if this PairSet "has" these two with no exclusivity, - // we have to ensure it was added as such. - - return areMutuallyExclusive ? true : areMutuallyExclusive === result; - } - add(a, b, areMutuallyExclusive) { - const [key1, key2] = a < b ? [a, b] : [b, a]; - const map = this._data.get(key1); - if (map === undefined) { - this._data.set(key1, new Map([[key2, areMutuallyExclusive]])); - } else { - map.set(key2, areMutuallyExclusive); - } - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs": - /*!**************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs ***! - \**************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); - var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - /** - * Possible fragment spread - * - * A fragment spread is only valid if the type condition could ever possibly - * be true: if there is a non-empty intersection of the possible parent types, - * and possible types which pass the type condition. - */ - function PossibleFragmentSpreadsRule(context) { - return { - InlineFragment(node) { - const fragType = context.getType(); - const parentType = context.getParentType(); - if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { - const parentTypeStr = (0, _inspect.inspect)(parentType); - const fragTypeStr = (0, _inspect.inspect)(fragType); - context.reportError(new _GraphQLError.GraphQLError(`Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { - nodes: node - })); - } - }, - FragmentSpread(node) { - const fragName = node.name.value; - const fragType = getFragmentType(context, fragName); - const parentType = context.getParentType(); - if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { - const parentTypeStr = (0, _inspect.inspect)(parentType); - const fragTypeStr = (0, _inspect.inspect)(fragType); - context.reportError(new _GraphQLError.GraphQLError(`Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { - nodes: node - })); - } - } - }; - } - function getFragmentType(context, name) { - const frag = context.getFragment(name); - if (frag) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); - if ((0, _definition.isCompositeType)(type)) { - return type; - } - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs": - /*!*************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs ***! - \*************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; - var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Possible type extension - * - * A type extension is only valid if the type is defined and has the same kind. - */ - function PossibleTypeExtensionsRule(context) { - const schema = context.getSchema(); - const definedTypes = Object.create(null); - for (const def of context.getDocument().definitions) { - if ((0, _predicates.isTypeDefinitionNode)(def)) { - definedTypes[def.name.value] = def; - } - } - return { - ScalarTypeExtension: checkExtension, - ObjectTypeExtension: checkExtension, - InterfaceTypeExtension: checkExtension, - UnionTypeExtension: checkExtension, - EnumTypeExtension: checkExtension, - InputObjectTypeExtension: checkExtension - }; - function checkExtension(node) { - const typeName = node.name.value; - const defNode = definedTypes[typeName]; - const existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName); - let expectedKind; - if (defNode) { - expectedKind = defKindToExtKind[defNode.kind]; - } else if (existingType) { - expectedKind = typeToExtKind(existingType); - } - if (expectedKind) { - if (expectedKind !== node.kind) { - const kindStr = extensionKindToTypeName(node.kind); - context.reportError(new _GraphQLError.GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, { - nodes: defNode ? [defNode, node] : node - })); - } - } else { - const allTypeNames = Object.keys({ - ...definedTypes, - ...(schema === null || schema === void 0 ? void 0 : schema.getTypeMap()) - }); - const suggestedTypes = (0, _suggestionList.suggestionList)(typeName, allTypeNames); - context.reportError(new _GraphQLError.GraphQLError(`Cannot extend type "${typeName}" because it is not defined.` + (0, _didYouMean.didYouMean)(suggestedTypes), { - nodes: node.name - })); - } - } - } - const defKindToExtKind = { - [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, - [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, - [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, - [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, - [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, - [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION - }; - function typeToExtKind(type) { - if ((0, _definition.isScalarType)(type)) { - return _kinds.Kind.SCALAR_TYPE_EXTENSION; - } - if ((0, _definition.isObjectType)(type)) { - return _kinds.Kind.OBJECT_TYPE_EXTENSION; - } - if ((0, _definition.isInterfaceType)(type)) { - return _kinds.Kind.INTERFACE_TYPE_EXTENSION; - } - if ((0, _definition.isUnionType)(type)) { - return _kinds.Kind.UNION_TYPE_EXTENSION; - } - if ((0, _definition.isEnumType)(type)) { - return _kinds.Kind.ENUM_TYPE_EXTENSION; - } - if ((0, _definition.isInputObjectType)(type)) { - return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; - } - /* c8 ignore next 3 */ - // Not reachable. All possible types have been considered - - false || (0, _invariant.invariant)(false, 'Unexpected type: ' + (0, _inspect.inspect)(type)); - } - function extensionKindToTypeName(kind) { - switch (kind) { - case _kinds.Kind.SCALAR_TYPE_EXTENSION: - return 'scalar'; - case _kinds.Kind.OBJECT_TYPE_EXTENSION: - return 'object'; - case _kinds.Kind.INTERFACE_TYPE_EXTENSION: - return 'interface'; - case _kinds.Kind.UNION_TYPE_EXTENSION: - return 'union'; - case _kinds.Kind.ENUM_TYPE_EXTENSION: - return 'enum'; - case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: - return 'input object'; - // Not reachable. All possible types have been considered - - /* c8 ignore next */ - - default: - false || (0, _invariant.invariant)(false, 'Unexpected kind: ' + (0, _inspect.inspect)(kind)); - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs": - /*!****************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs ***! - \****************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.ProvidedRequiredArgumentsOnDirectivesRule = ProvidedRequiredArgumentsOnDirectivesRule; - exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - /** - * Provided required arguments - * - * A field or directive is only valid if all required (non-null without a - * default value) field arguments have been provided. - */ - function ProvidedRequiredArgumentsRule(context) { - return { - // eslint-disable-next-line new-cap - ...ProvidedRequiredArgumentsOnDirectivesRule(context), - Field: { - // Validate on leave to allow for deeper errors to appear first. - leave(fieldNode) { - var _fieldNode$arguments; - const fieldDef = context.getFieldDef(); - if (!fieldDef) { - return false; - } - const providedArgs = new Set( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - /* c8 ignore next */ - (_fieldNode$arguments = fieldNode.arguments) === null || _fieldNode$arguments === void 0 ? void 0 : _fieldNode$arguments.map(arg => arg.name.value)); - for (const argDef of fieldDef.args) { - if (!providedArgs.has(argDef.name) && (0, _definition.isRequiredArgument)(argDef)) { - const argTypeStr = (0, _inspect.inspect)(argDef.type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, { - nodes: fieldNode - })); - } - } - } - } - }; - } - /** - * @internal - */ - - function ProvidedRequiredArgumentsOnDirectivesRule(context) { - var _schema$getDirectives; - const requiredArgsMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = (_schema$getDirectives = schema === null || schema === void 0 ? void 0 : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 ? _schema$getDirectives : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - requiredArgsMap[directive.name] = (0, _keyMap.keyMap)(directive.args.filter(_definition.isRequiredArgument), arg => arg.name); - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - var _def$arguments; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : []; - requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)(argNodes.filter(isRequiredArgumentNode), arg => arg.name.value); - } - } - return { - Directive: { - // Validate on leave to allow for deeper errors to appear first. - leave(directiveNode) { - const directiveName = directiveNode.name.value; - const requiredArgs = requiredArgsMap[directiveName]; - if (requiredArgs) { - var _directiveNode$argume; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; - const argNodeMap = new Set(argNodes.map(arg => arg.name.value)); - for (const [argName, argDef] of Object.entries(requiredArgs)) { - if (!argNodeMap.has(argName)) { - const argType = (0, _definition.isType)(argDef.type) ? (0, _inspect.inspect)(argDef.type) : (0, _printer.print)(argDef.type); - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, { - nodes: directiveNode - })); - } - } - } - } - } - }; - } - function isRequiredArgumentNode(arg) { - return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs": - /*!**************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs ***! - \**************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.ScalarLeafsRule = ScalarLeafsRule; - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Scalar leafs - * - * A GraphQL document is valid only if all leaf fields (fields without - * sub selections) are of scalar or enum types. - */ - function ScalarLeafsRule(context) { - return { - Field(node) { - const type = context.getType(); - const selectionSet = node.selectionSet; - if (type) { - if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { - if (selectionSet) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, { - nodes: selectionSet - })); - } - } else if (!selectionSet) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, { - nodes: node - })); - } - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs": - /*!***************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs ***! - \***************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _collectFields = __webpack_require__(/*! ../../execution/collectFields.mjs */ "../../../node_modules/graphql/execution/collectFields.mjs"); - /** - * Subscriptions must only include a non-introspection field. - * - * A GraphQL subscription is valid only if it contains a single root field and - * that root field is not an introspection field. - * - * See https://spec.graphql.org/draft/#sec-Single-root-field - */ - function SingleFieldSubscriptionsRule(context) { - return { - OperationDefinition(node) { - if (node.operation === 'subscription') { - const schema = context.getSchema(); - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType) { - const operationName = node.name ? node.name.value : null; - const variableValues = Object.create(null); - const document = context.getDocument(); - const fragments = Object.create(null); - for (const definition of document.definitions) { - if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { - fragments[definition.name.value] = definition; - } - } - const fields = (0, _collectFields.collectFields)(schema, fragments, variableValues, subscriptionType, node.selectionSet); - if (fields.size > 1) { - const fieldSelectionLists = [...fields.values()]; - const extraFieldSelectionLists = fieldSelectionLists.slice(1); - const extraFieldSelections = extraFieldSelectionLists.flat(); - context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must select only one top level field.` : 'Anonymous Subscription must select only one top level field.', { - nodes: extraFieldSelections - })); - } - for (const fieldNodes of fields.values()) { - const field = fieldNodes[0]; - const fieldName = field.name.value; - if (fieldName.startsWith('__')) { - context.reportError(new _GraphQLError.GraphQLError(operationName != null ? `Subscription "${operationName}" must not select an introspection top level field.` : 'Anonymous Subscription must not select an introspection top level field.', { - nodes: fieldNodes - })); - } - } - } - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs": - /*!********************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs ***! - \********************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; - var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique argument definition names - * - * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. - * A GraphQL Directive is only valid if all its arguments are uniquely named. - */ - function UniqueArgumentDefinitionNamesRule(context) { - return { - DirectiveDefinition(directiveNode) { - var _directiveNode$argume; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argumentNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : []; - return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); - }, - InterfaceTypeDefinition: checkArgUniquenessPerField, - InterfaceTypeExtension: checkArgUniquenessPerField, - ObjectTypeDefinition: checkArgUniquenessPerField, - ObjectTypeExtension: checkArgUniquenessPerField - }; - function checkArgUniquenessPerField(typeNode) { - var _typeNode$fields; - const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const fieldNodes = (_typeNode$fields = typeNode.fields) !== null && _typeNode$fields !== void 0 ? _typeNode$fields : []; - for (const fieldDef of fieldNodes) { - var _fieldDef$arguments; - const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const argumentNodes = (_fieldDef$arguments = fieldDef.arguments) !== null && _fieldDef$arguments !== void 0 ? _fieldDef$arguments : []; - checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); - } - return false; - } - function checkArgUniqueness(parentName, argumentNodes) { - const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); - for (const [argName, argNodes] of seenArgs) { - if (argNodes.length > 1) { - context.reportError(new _GraphQLError.GraphQLError(`Argument "${parentName}(${argName}:)" can only be defined once.`, { - nodes: argNodes.map(node => node.name) - })); - } - } - return false; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs ***! - \**********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; - var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique argument names - * - * A GraphQL field or directive is only valid if all supplied arguments are - * uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Argument-Names - */ - function UniqueArgumentNamesRule(context) { - return { - Field: checkArgUniqueness, - Directive: checkArgUniqueness - }; - function checkArgUniqueness(parentNode) { - var _parentNode$arguments; - - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const argumentNodes = (_parentNode$arguments = parentNode.arguments) !== null && _parentNode$arguments !== void 0 ? _parentNode$arguments : []; - const seenArgs = (0, _groupBy.groupBy)(argumentNodes, arg => arg.name.value); - for (const [argName, argNodes] of seenArgs) { - if (argNodes.length > 1) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one argument named "${argName}".`, { - nodes: argNodes.map(node => node.name) - })); - } - } - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs ***! - \***********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique directive names - * - * A GraphQL document is only valid if all defined directives have unique names. - */ - function UniqueDirectiveNamesRule(context) { - const knownDirectiveNames = Object.create(null); - const schema = context.getSchema(); - return { - DirectiveDefinition(node) { - const directiveName = node.name.value; - if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) { - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, { - nodes: node.name - })); - return; - } - if (knownDirectiveNames[directiveName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one directive named "@${directiveName}".`, { - nodes: [knownDirectiveNames[directiveName], node.name] - })); - } else { - knownDirectiveNames[directiveName] = node.name; - } - return false; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs": - /*!******************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs ***! - \******************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _predicates = __webpack_require__(/*! ../../language/predicates.mjs */ "../../../node_modules/graphql/language/predicates.mjs"); - var _directives = __webpack_require__(/*! ../../type/directives.mjs */ "../../../node_modules/graphql/type/directives.mjs"); - /** - * Unique directive names per location - * - * A GraphQL document is only valid if all non-repeatable directives at - * a given location are uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location - */ - function UniqueDirectivesPerLocationRule(context) { - const uniqueDirectiveMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; - for (const directive of definedDirectives) { - uniqueDirectiveMap[directive.name] = !directive.isRepeatable; - } - const astDefinitions = context.getDocument().definitions; - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - uniqueDirectiveMap[def.name.value] = !def.repeatable; - } - } - const schemaDirectives = Object.create(null); - const typeDirectivesMap = Object.create(null); - return { - // Many different AST nodes may contain directives. Rather than listing - // them all, just listen for entering any node, and check to see if it - // defines any directives. - enter(node) { - if (!('directives' in node) || !node.directives) { - return; - } - let seenDirectives; - if (node.kind === _kinds.Kind.SCHEMA_DEFINITION || node.kind === _kinds.Kind.SCHEMA_EXTENSION) { - seenDirectives = schemaDirectives; - } else if ((0, _predicates.isTypeDefinitionNode)(node) || (0, _predicates.isTypeExtensionNode)(node)) { - const typeName = node.name.value; - seenDirectives = typeDirectivesMap[typeName]; - if (seenDirectives === undefined) { - typeDirectivesMap[typeName] = seenDirectives = Object.create(null); - } - } else { - seenDirectives = Object.create(null); - } - for (const directive of node.directives) { - const directiveName = directive.name.value; - if (uniqueDirectiveMap[directiveName]) { - if (seenDirectives[directiveName]) { - context.reportError(new _GraphQLError.GraphQLError(`The directive "@${directiveName}" can only be used once at this location.`, { - nodes: [seenDirectives[directiveName], directive] - })); - } else { - seenDirectives[directiveName] = directive; - } - } - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs ***! - \***********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Unique enum value names - * - * A GraphQL enum type is only valid if all its values are uniquely named. - */ - function UniqueEnumValueNamesRule(context) { - const schema = context.getSchema(); - const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); - const knownValueNames = Object.create(null); - return { - EnumTypeDefinition: checkValueUniqueness, - EnumTypeExtension: checkValueUniqueness - }; - function checkValueUniqueness(node) { - var _node$values; - const typeName = node.name.value; - if (!knownValueNames[typeName]) { - knownValueNames[typeName] = Object.create(null); - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []; - const valueNames = knownValueNames[typeName]; - for (const valueDef of valueNodes) { - const valueName = valueDef.name.value; - const existingType = existingTypeMap[typeName]; - if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) { - context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, { - nodes: valueDef.name - })); - } else if (valueNames[valueName]) { - context.reportError(new _GraphQLError.GraphQLError(`Enum value "${typeName}.${valueName}" can only be defined once.`, { - nodes: [valueNames[valueName], valueDef.name] - })); - } else { - valueNames[valueName] = valueDef.name; - } - } - return false; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs": - /*!*****************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs ***! - \*****************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Unique field definition names - * - * A GraphQL complex type is only valid if all its fields are uniquely named. - */ - function UniqueFieldDefinitionNamesRule(context) { - const schema = context.getSchema(); - const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); - const knownFieldNames = Object.create(null); - return { - InputObjectTypeDefinition: checkFieldUniqueness, - InputObjectTypeExtension: checkFieldUniqueness, - InterfaceTypeDefinition: checkFieldUniqueness, - InterfaceTypeExtension: checkFieldUniqueness, - ObjectTypeDefinition: checkFieldUniqueness, - ObjectTypeExtension: checkFieldUniqueness - }; - function checkFieldUniqueness(node) { - var _node$fields; - const typeName = node.name.value; - if (!knownFieldNames[typeName]) { - knownFieldNames[typeName] = Object.create(null); - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []; - const fieldNames = knownFieldNames[typeName]; - for (const fieldDef of fieldNodes) { - const fieldName = fieldDef.name.value; - if (hasField(existingTypeMap[typeName], fieldName)) { - context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, { - nodes: fieldDef.name - })); - } else if (fieldNames[fieldName]) { - context.reportError(new _GraphQLError.GraphQLError(`Field "${typeName}.${fieldName}" can only be defined once.`, { - nodes: [fieldNames[fieldName], fieldDef.name] - })); - } else { - fieldNames[fieldName] = fieldDef.name; - } - } - return false; - } - } - function hasField(type, fieldName) { - if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) { - return type.getFields()[fieldName] != null; - } - return false; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs ***! - \**********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique fragment names - * - * A GraphQL document is only valid if all defined fragments have unique names. - * - * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness - */ - function UniqueFragmentNamesRule(context) { - const knownFragmentNames = Object.create(null); - return { - OperationDefinition: () => false, - FragmentDefinition(node) { - const fragmentName = node.name.value; - if (knownFragmentNames[fragmentName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one fragment named "${fragmentName}".`, { - nodes: [knownFragmentNames[fragmentName], node.name] - })); - } else { - knownFragmentNames[fragmentName] = node.name; - } - return false; - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs": - /*!************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs ***! - \************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; - var _invariant = __webpack_require__(/*! ../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique input field names - * - * A GraphQL input object value is only valid if all supplied fields are - * uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness - */ - function UniqueInputFieldNamesRule(context) { - const knownNameStack = []; - let knownNames = Object.create(null); - return { - ObjectValue: { - enter() { - knownNameStack.push(knownNames); - knownNames = Object.create(null); - }, - leave() { - const prevKnownNames = knownNameStack.pop(); - prevKnownNames || (0, _invariant.invariant)(false); - knownNames = prevKnownNames; - } - }, - ObjectField(node) { - const fieldName = node.name.value; - if (knownNames[fieldName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one input field named "${fieldName}".`, { - nodes: [knownNames[fieldName], node.name] - })); - } else { - knownNames[fieldName] = node.name; - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs ***! - \***********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueOperationNamesRule = UniqueOperationNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique operation names - * - * A GraphQL document is only valid if all defined operations have unique names. - * - * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness - */ - function UniqueOperationNamesRule(context) { - const knownOperationNames = Object.create(null); - return { - OperationDefinition(node) { - const operationName = node.name; - if (operationName) { - if (knownOperationNames[operationName.value]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one operation named "${operationName.value}".`, { - nodes: [knownOperationNames[operationName.value], operationName] - })); - } else { - knownOperationNames[operationName.value] = operationName; - } - } - return false; - }, - FragmentDefinition: () => false - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs": - /*!***********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs ***! - \***********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueOperationTypesRule = UniqueOperationTypesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique operation types - * - * A GraphQL document is only valid if it has only one type per operation. - */ - function UniqueOperationTypesRule(context) { - const schema = context.getSchema(); - const definedOperationTypes = Object.create(null); - const existingOperationTypes = schema ? { - query: schema.getQueryType(), - mutation: schema.getMutationType(), - subscription: schema.getSubscriptionType() - } : {}; - return { - SchemaDefinition: checkOperationTypes, - SchemaExtension: checkOperationTypes - }; - function checkOperationTypes(node) { - var _node$operationTypes; - - // See: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []; - for (const operationType of operationTypesNodes) { - const operation = operationType.operation; - const alreadyDefinedOperationType = definedOperationTypes[operation]; - if (existingOperationTypes[operation]) { - context.reportError(new _GraphQLError.GraphQLError(`Type for ${operation} already defined in the schema. It cannot be redefined.`, { - nodes: operationType - })); - } else if (alreadyDefinedOperationType) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one ${operation} type in schema.`, { - nodes: [alreadyDefinedOperationType, operationType] - })); - } else { - definedOperationTypes[operation] = operationType; - } - } - return false; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs": - /*!******************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs ***! - \******************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueTypeNamesRule = UniqueTypeNamesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique type names - * - * A GraphQL document is only valid if all defined types have unique names. - */ - function UniqueTypeNamesRule(context) { - const knownTypeNames = Object.create(null); - const schema = context.getSchema(); - return { - ScalarTypeDefinition: checkTypeName, - ObjectTypeDefinition: checkTypeName, - InterfaceTypeDefinition: checkTypeName, - UnionTypeDefinition: checkTypeName, - EnumTypeDefinition: checkTypeName, - InputObjectTypeDefinition: checkTypeName - }; - function checkTypeName(node) { - const typeName = node.name.value; - if (schema !== null && schema !== void 0 && schema.getType(typeName)) { - context.reportError(new _GraphQLError.GraphQLError(`Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, { - nodes: node.name - })); - return; - } - if (knownTypeNames[typeName]) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one type named "${typeName}".`, { - nodes: [knownTypeNames[typeName], node.name] - })); - } else { - knownTypeNames[typeName] = node.name; - } - return false; - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs ***! - \**********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.UniqueVariableNamesRule = UniqueVariableNamesRule; - var _groupBy = __webpack_require__(/*! ../../jsutils/groupBy.mjs */ "../../../node_modules/graphql/jsutils/groupBy.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - /** - * Unique variable names - * - * A GraphQL operation is only valid if all its variables are uniquely named. - */ - function UniqueVariableNamesRule(context) { - return { - OperationDefinition(operationNode) { - var _operationNode$variab; - - // See: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - const variableDefinitions = (_operationNode$variab = operationNode.variableDefinitions) !== null && _operationNode$variab !== void 0 ? _operationNode$variab : []; - const seenVariableDefinitions = (0, _groupBy.groupBy)(variableDefinitions, node => node.variable.name.value); - for (const [variableName, variableNodes] of seenVariableDefinitions) { - if (variableNodes.length > 1) { - context.reportError(new _GraphQLError.GraphQLError(`There can be only one variable named "$${variableName}".`, { - nodes: variableNodes.map(node => node.variable.name) - })); - } - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs": - /*!**********************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs ***! - \**********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; - var _didYouMean = __webpack_require__(/*! ../../jsutils/didYouMean.mjs */ "../../../node_modules/graphql/jsutils/didYouMean.mjs"); - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _keyMap = __webpack_require__(/*! ../../jsutils/keyMap.mjs */ "../../../node_modules/graphql/jsutils/keyMap.mjs"); - var _suggestionList = __webpack_require__(/*! ../../jsutils/suggestionList.mjs */ "../../../node_modules/graphql/jsutils/suggestionList.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * Value literals of correct type - * - * A GraphQL document is only valid if all value literals are of the type - * expected at their position. - * - * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type - */ - function ValuesOfCorrectTypeRule(context) { - return { - ListValue(node) { - // Note: TypeInfo will traverse into a list's item type, so look to the - // parent input type to check if it is a list. - const type = (0, _definition.getNullableType)(context.getParentInputType()); - if (!(0, _definition.isListType)(type)) { - isValidValueNode(context, node); - return false; // Don't traverse further. - } - }, - ObjectValue(node) { - const type = (0, _definition.getNamedType)(context.getInputType()); - if (!(0, _definition.isInputObjectType)(type)) { - isValidValueNode(context, node); - return false; // Don't traverse further. - } // Ensure every required field exists. - - const fieldNodeMap = (0, _keyMap.keyMap)(node.fields, field => field.name.value); - for (const fieldDef of Object.values(type.getFields())) { - const fieldNode = fieldNodeMap[fieldDef.name]; - if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { - const typeStr = (0, _inspect.inspect)(fieldDef.type); - context.reportError(new _GraphQLError.GraphQLError(`Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, { - nodes: node - })); - } - } - }, - ObjectField(node) { - const parentType = (0, _definition.getNamedType)(context.getParentInputType()); - const fieldType = context.getInputType(); - if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { - const suggestions = (0, _suggestionList.suggestionList)(node.name.value, Object.keys(parentType.getFields())); - context.reportError(new _GraphQLError.GraphQLError(`Field "${node.name.value}" is not defined by type "${parentType.name}".` + (0, _didYouMean.didYouMean)(suggestions), { - nodes: node - })); - } - }, - NullValue(node) { - const type = context.getInputType(); - if ((0, _definition.isNonNullType)(type)) { - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${(0, _inspect.inspect)(type)}", found ${(0, _printer.print)(node)}.`, { - nodes: node - })); - } - }, - EnumValue: node => isValidValueNode(context, node), - IntValue: node => isValidValueNode(context, node), - FloatValue: node => isValidValueNode(context, node), - StringValue: node => isValidValueNode(context, node), - BooleanValue: node => isValidValueNode(context, node) - }; - } - /** - * Any value literal may be a valid representation of a Scalar, depending on - * that scalar type. - */ - - function isValidValueNode(context, node) { - // Report any error at the full type expected by the location. - const locationType = context.getInputType(); - if (!locationType) { - return; - } - const type = (0, _definition.getNamedType)(locationType); - if (!(0, _definition.isLeafType)(type)) { - const typeStr = (0, _inspect.inspect)(locationType); - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { - nodes: node - })); - return; - } // Scalars and Enums determine if a literal value is valid via parseLiteral(), - // which may throw or return an invalid value to indicate failure. - - try { - const parseResult = type.parseLiteral(node, undefined - /* variables */); - if (parseResult === undefined) { - const typeStr = (0, _inspect.inspect)(locationType); - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}.`, { - nodes: node - })); - } - } catch (error) { - const typeStr = (0, _inspect.inspect)(locationType); - if (error instanceof _GraphQLError.GraphQLError) { - context.reportError(error); - } else { - context.reportError(new _GraphQLError.GraphQLError(`Expected value of type "${typeStr}", found ${(0, _printer.print)(node)}; ` + error.message, { - nodes: node, - originalError: error - })); - } - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs": - /*!*************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs ***! - \*************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _printer = __webpack_require__(/*! ../../language/printer.mjs */ "../../../node_modules/graphql/language/printer.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - /** - * Variables are input types - * - * A GraphQL operation is only valid if all the variables it defines are of - * input types (scalar, enum, or input object). - * - * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types - */ - function VariablesAreInputTypesRule(context) { - return { - VariableDefinition(node) { - const type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); - if (type !== undefined && !(0, _definition.isInputType)(type)) { - const variableName = node.variable.name.value; - const typeName = (0, _printer.print)(node.type); - context.reportError(new _GraphQLError.GraphQLError(`Variable "$${variableName}" cannot be non-input type "${typeName}".`, { - nodes: node.type - })); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs": - /*!*****************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs ***! - \*****************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; - var _inspect = __webpack_require__(/*! ../../jsutils/inspect.mjs */ "../../../node_modules/graphql/jsutils/inspect.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _kinds = __webpack_require__(/*! ../../language/kinds.mjs */ "../../../node_modules/graphql/language/kinds.mjs"); - var _definition = __webpack_require__(/*! ../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _typeComparators = __webpack_require__(/*! ../../utilities/typeComparators.mjs */ "../../../node_modules/graphql/utilities/typeComparators.mjs"); - var _typeFromAST = __webpack_require__(/*! ../../utilities/typeFromAST.mjs */ "../../../node_modules/graphql/utilities/typeFromAST.mjs"); - /** - * Variables in allowed position - * - * Variable usages must be compatible with the arguments they are passed to. - * - * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed - */ - function VariablesInAllowedPositionRule(context) { - let varDefMap = Object.create(null); - return { - OperationDefinition: { - enter() { - varDefMap = Object.create(null); - }, - leave(operation) { - const usages = context.getRecursiveVariableUsages(operation); - for (const { - node, - type, - defaultValue - } of usages) { - const varName = node.name.value; - const varDef = varDefMap[varName]; - if (varDef && type) { - // A var type is allowed if it is the same or more strict (e.g. is - // a subtype of) than the expected type. It can be more strict if - // the variable type is non-null when the expected type is nullable. - // If both are list types, the variable item type can be more strict - // than the expected item type (contravariant). - const schema = context.getSchema(); - const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); - if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { - const varTypeStr = (0, _inspect.inspect)(varType); - const typeStr = (0, _inspect.inspect)(type); - context.reportError(new _GraphQLError.GraphQLError(`Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, { - nodes: [varDef, node] - })); - } - } - } - } - }, - VariableDefinition(node) { - varDefMap[node.variable.name.value] = node; - } - }; - } - /** - * Returns true if the variable is allowed in the location it was found, - * which includes considering if default values exist for either the variable - * or the location at which it is located. - */ - - function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { - if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { - const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; - const hasLocationDefaultValue = locationDefaultValue !== undefined; - if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { - return false; - } - const nullableLocationType = locationType.ofType; - return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); - } - return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs": - /*!****************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs ***! - \****************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; - var _invariant = __webpack_require__(/*! ../../../jsutils/invariant.mjs */ "../../../node_modules/graphql/jsutils/invariant.mjs"); - var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - /** - * No deprecated - * - * A GraphQL document is only valid if all selected fields and all used enum values have not been - * deprecated. - * - * Note: This rule is optional and is not part of the Validation section of the GraphQL - * Specification. The main purpose of this rule is detection of deprecated usages and not - * necessarily to forbid their use when querying a service. - */ - function NoDeprecatedCustomRule(context) { - return { - Field(node) { - const fieldDef = context.getFieldDef(); - const deprecationReason = fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason; - if (fieldDef && deprecationReason != null) { - const parentType = context.getParentType(); - parentType != null || (0, _invariant.invariant)(false); - context.reportError(new _GraphQLError.GraphQLError(`The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - }, - Argument(node) { - const argDef = context.getArgument(); - const deprecationReason = argDef === null || argDef === void 0 ? void 0 : argDef.deprecationReason; - if (argDef && deprecationReason != null) { - const directiveDef = context.getDirective(); - if (directiveDef != null) { - context.reportError(new _GraphQLError.GraphQLError(`Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { - nodes: node - })); - } else { - const parentType = context.getParentType(); - const fieldDef = context.getFieldDef(); - parentType != null && fieldDef != null || (0, _invariant.invariant)(false); - context.reportError(new _GraphQLError.GraphQLError(`Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - } - }, - ObjectField(node) { - const inputObjectDef = (0, _definition.getNamedType)(context.getParentInputType()); - if ((0, _definition.isInputObjectType)(inputObjectDef)) { - const inputFieldDef = inputObjectDef.getFields()[node.name.value]; - const deprecationReason = inputFieldDef === null || inputFieldDef === void 0 ? void 0 : inputFieldDef.deprecationReason; - if (deprecationReason != null) { - context.reportError(new _GraphQLError.GraphQLError(`The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - } - }, - EnumValue(node) { - const enumValueDef = context.getEnumValue(); - const deprecationReason = enumValueDef === null || enumValueDef === void 0 ? void 0 : enumValueDef.deprecationReason; - if (enumValueDef && deprecationReason != null) { - const enumTypeDef = (0, _definition.getNamedType)(context.getInputType()); - enumTypeDef != null || (0, _invariant.invariant)(false); - context.reportError(new _GraphQLError.GraphQLError(`The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, { - nodes: node - })); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs": - /*!*************************************************************************************************!*\ - !*** ../../../node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs ***! - \*************************************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; - var _GraphQLError = __webpack_require__(/*! ../../../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _definition = __webpack_require__(/*! ../../../type/definition.mjs */ "../../../node_modules/graphql/type/definition.mjs"); - var _introspection = __webpack_require__(/*! ../../../type/introspection.mjs */ "../../../node_modules/graphql/type/introspection.mjs"); - /** - * Prohibit introspection queries - * - * A GraphQL document is only valid if all fields selected are not fields that - * return an introspection type. - * - * Note: This rule is optional and is not part of the Validation section of the - * GraphQL Specification. This rule effectively disables introspection, which - * does not reflect best practices and should only be done if absolutely necessary. - */ - function NoSchemaIntrospectionCustomRule(context) { - return { - Field(node) { - const type = (0, _definition.getNamedType)(context.getType()); - if (type && (0, _introspection.isIntrospectionType)(type)) { - context.reportError(new _GraphQLError.GraphQLError(`GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, { - nodes: node - })); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/specifiedRules.mjs": - /*!*******************************************************************!*\ - !*** ../../../node_modules/graphql/validation/specifiedRules.mjs ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.specifiedSDLRules = exports.specifiedRules = void 0; - var _ExecutableDefinitionsRule = __webpack_require__(/*! ./rules/ExecutableDefinitionsRule.mjs */ "../../../node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs"); - var _FieldsOnCorrectTypeRule = __webpack_require__(/*! ./rules/FieldsOnCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs"); - var _FragmentsOnCompositeTypesRule = __webpack_require__(/*! ./rules/FragmentsOnCompositeTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs"); - var _KnownArgumentNamesRule = __webpack_require__(/*! ./rules/KnownArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs"); - var _KnownDirectivesRule = __webpack_require__(/*! ./rules/KnownDirectivesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownDirectivesRule.mjs"); - var _KnownFragmentNamesRule = __webpack_require__(/*! ./rules/KnownFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs"); - var _KnownTypeNamesRule = __webpack_require__(/*! ./rules/KnownTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs"); - var _LoneAnonymousOperationRule = __webpack_require__(/*! ./rules/LoneAnonymousOperationRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs"); - var _LoneSchemaDefinitionRule = __webpack_require__(/*! ./rules/LoneSchemaDefinitionRule.mjs */ "../../../node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs"); - var _NoFragmentCyclesRule = __webpack_require__(/*! ./rules/NoFragmentCyclesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs"); - var _NoUndefinedVariablesRule = __webpack_require__(/*! ./rules/NoUndefinedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs"); - var _NoUnusedFragmentsRule = __webpack_require__(/*! ./rules/NoUnusedFragmentsRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs"); - var _NoUnusedVariablesRule = __webpack_require__(/*! ./rules/NoUnusedVariablesRule.mjs */ "../../../node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs"); - var _OverlappingFieldsCanBeMergedRule = __webpack_require__(/*! ./rules/OverlappingFieldsCanBeMergedRule.mjs */ "../../../node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs"); - var _PossibleFragmentSpreadsRule = __webpack_require__(/*! ./rules/PossibleFragmentSpreadsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs"); - var _PossibleTypeExtensionsRule = __webpack_require__(/*! ./rules/PossibleTypeExtensionsRule.mjs */ "../../../node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs"); - var _ProvidedRequiredArgumentsRule = __webpack_require__(/*! ./rules/ProvidedRequiredArgumentsRule.mjs */ "../../../node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs"); - var _ScalarLeafsRule = __webpack_require__(/*! ./rules/ScalarLeafsRule.mjs */ "../../../node_modules/graphql/validation/rules/ScalarLeafsRule.mjs"); - var _SingleFieldSubscriptionsRule = __webpack_require__(/*! ./rules/SingleFieldSubscriptionsRule.mjs */ "../../../node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs"); - var _UniqueArgumentDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs"); - var _UniqueArgumentNamesRule = __webpack_require__(/*! ./rules/UniqueArgumentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs"); - var _UniqueDirectiveNamesRule = __webpack_require__(/*! ./rules/UniqueDirectiveNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs"); - var _UniqueDirectivesPerLocationRule = __webpack_require__(/*! ./rules/UniqueDirectivesPerLocationRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs"); - var _UniqueEnumValueNamesRule = __webpack_require__(/*! ./rules/UniqueEnumValueNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs"); - var _UniqueFieldDefinitionNamesRule = __webpack_require__(/*! ./rules/UniqueFieldDefinitionNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs"); - var _UniqueFragmentNamesRule = __webpack_require__(/*! ./rules/UniqueFragmentNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs"); - var _UniqueInputFieldNamesRule = __webpack_require__(/*! ./rules/UniqueInputFieldNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs"); - var _UniqueOperationNamesRule = __webpack_require__(/*! ./rules/UniqueOperationNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs"); - var _UniqueOperationTypesRule = __webpack_require__(/*! ./rules/UniqueOperationTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs"); - var _UniqueTypeNamesRule = __webpack_require__(/*! ./rules/UniqueTypeNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs"); - var _UniqueVariableNamesRule = __webpack_require__(/*! ./rules/UniqueVariableNamesRule.mjs */ "../../../node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs"); - var _ValuesOfCorrectTypeRule = __webpack_require__(/*! ./rules/ValuesOfCorrectTypeRule.mjs */ "../../../node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs"); - var _VariablesAreInputTypesRule = __webpack_require__(/*! ./rules/VariablesAreInputTypesRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs"); - var _VariablesInAllowedPositionRule = __webpack_require__(/*! ./rules/VariablesInAllowedPositionRule.mjs */ "../../../node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs"); - // Spec Section: "Executable Definitions" - // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" - - // Spec Section: "Fragments on Composite Types" - - // Spec Section: "Argument Names" - - // Spec Section: "Directives Are Defined" - - // Spec Section: "Fragment spread target defined" - - // Spec Section: "Fragment Spread Type Existence" - - // Spec Section: "Lone Anonymous Operation" - - // SDL-specific validation rules - - // Spec Section: "Fragments must not form cycles" - - // Spec Section: "All Variable Used Defined" - - // Spec Section: "Fragments must be used" - - // Spec Section: "All Variables Used" - - // Spec Section: "Field Selection Merging" - - // Spec Section: "Fragment spread is possible" - - // Spec Section: "Argument Optionality" - - // Spec Section: "Leaf Field Selections" - - // Spec Section: "Subscriptions with Single Root Field" - - // Spec Section: "Argument Uniqueness" - - // Spec Section: "Directives Are Unique Per Location" - - // Spec Section: "Fragment Name Uniqueness" - - // Spec Section: "Input Object Field Uniqueness" - - // Spec Section: "Operation Name Uniqueness" - - // Spec Section: "Variable Uniqueness" - - // Spec Section: "Value Type Correctness" - - // Spec Section: "Variables are Input Types" - - // Spec Section: "All Variable Usages Are Allowed" - - /** - * This set includes all validation rules defined by the GraphQL spec. - * - * The order of the rules in this list has been adjusted to lead to the - * most clear output when encountering multiple validation errors. - */ - const specifiedRules = exports.specifiedRules = Object.freeze([_ExecutableDefinitionsRule.ExecutableDefinitionsRule, _UniqueOperationNamesRule.UniqueOperationNamesRule, _LoneAnonymousOperationRule.LoneAnonymousOperationRule, _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, _KnownTypeNamesRule.KnownTypeNamesRule, _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, _VariablesAreInputTypesRule.VariablesAreInputTypesRule, _ScalarLeafsRule.ScalarLeafsRule, _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, _UniqueFragmentNamesRule.UniqueFragmentNamesRule, _KnownFragmentNamesRule.KnownFragmentNamesRule, _NoUnusedFragmentsRule.NoUnusedFragmentsRule, _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, _NoFragmentCyclesRule.NoFragmentCyclesRule, _UniqueVariableNamesRule.UniqueVariableNamesRule, _NoUndefinedVariablesRule.NoUndefinedVariablesRule, _NoUnusedVariablesRule.NoUnusedVariablesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _KnownArgumentNamesRule.KnownArgumentNamesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule]); - /** - * @internal - */ - - const specifiedSDLRules = exports.specifiedSDLRules = Object.freeze([_LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, _UniqueOperationTypesRule.UniqueOperationTypesRule, _UniqueTypeNamesRule.UniqueTypeNamesRule, _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, _KnownTypeNamesRule.KnownTypeNamesRule, _KnownDirectivesRule.KnownDirectivesRule, _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, _UniqueArgumentNamesRule.UniqueArgumentNamesRule, _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule]); - - /***/ }), - - /***/ "../../../node_modules/graphql/validation/validate.mjs": - /*!*************************************************************!*\ - !*** ../../../node_modules/graphql/validation/validate.mjs ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.assertValidSDL = assertValidSDL; - exports.assertValidSDLExtension = assertValidSDLExtension; - exports.validate = validate; - exports.validateSDL = validateSDL; - var _devAssert = __webpack_require__(/*! ../jsutils/devAssert.mjs */ "../../../node_modules/graphql/jsutils/devAssert.mjs"); - var _GraphQLError = __webpack_require__(/*! ../error/GraphQLError.mjs */ "../../../node_modules/graphql/error/GraphQLError.mjs"); - var _visitor = __webpack_require__(/*! ../language/visitor.mjs */ "../../../node_modules/graphql/language/visitor.mjs"); - var _validate = __webpack_require__(/*! ../type/validate.mjs */ "../../../node_modules/graphql/type/validate.mjs"); - var _TypeInfo = __webpack_require__(/*! ../utilities/TypeInfo.mjs */ "../../../node_modules/graphql/utilities/TypeInfo.mjs"); - var _specifiedRules = __webpack_require__(/*! ./specifiedRules.mjs */ "../../../node_modules/graphql/validation/specifiedRules.mjs"); - var _ValidationContext = __webpack_require__(/*! ./ValidationContext.mjs */ "../../../node_modules/graphql/validation/ValidationContext.mjs"); - /** - * Implements the "Validation" section of the spec. - * - * Validation runs synchronously, returning an array of encountered errors, or - * an empty array if no errors were encountered and the document is valid. - * - * A list of specific validation rules may be provided. If not provided, the - * default list of rules defined by the GraphQL specification will be used. - * - * Each validation rules is a function which returns a visitor - * (see the language/visitor API). Visitor methods are expected to return - * GraphQLErrors, or Arrays of GraphQLErrors when invalid. - * - * Validate will stop validation after a `maxErrors` limit has been reached. - * Attackers can send pathologically invalid queries to induce a DoS attack, - * so by default `maxErrors` set to 100 errors. - * - * Optionally a custom TypeInfo instance may be provided. If not provided, one - * will be created from the provided schema. - */ - - function validate(schema, documentAST, rules = _specifiedRules.specifiedRules, options, /** @deprecated will be removed in 17.0.0 */ - typeInfo = new _TypeInfo.TypeInfo(schema)) { - var _options$maxErrors; - const maxErrors = (_options$maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors) !== null && _options$maxErrors !== void 0 ? _options$maxErrors : 100; - documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. - - (0, _validate.assertValidSchema)(schema); - const abortObj = Object.freeze({}); - const errors = []; - const context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo, error => { - if (errors.length >= maxErrors) { - errors.push(new _GraphQLError.GraphQLError('Too many validation errors, error limit reached. Validation aborted.')); // eslint-disable-next-line @typescript-eslint/no-throw-literal - - throw abortObj; - } - errors.push(error); - }); // This uses a specialized visitor which runs multiple visitors in parallel, - // while maintaining the visitor skip and break API. - - const visitor = (0, _visitor.visitInParallel)(rules.map(rule => rule(context))); // Visit the whole document with each instance of all provided rules. - - try { - (0, _visitor.visit)(documentAST, (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor)); - } catch (e) { - if (e !== abortObj) { - throw e; - } - } - return errors; - } - /** - * @internal - */ - - function validateSDL(documentAST, schemaToExtend, rules = _specifiedRules.specifiedSDLRules) { - const errors = []; - const context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend, error => { - errors.push(error); - }); - const visitors = rules.map(rule => rule(context)); - (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); - return errors; - } - /** - * Utility function which asserts a SDL document is valid by throwing an error - * if it is invalid. - * - * @internal - */ - - function assertValidSDL(documentAST) { - const errors = validateSDL(documentAST); - if (errors.length !== 0) { - throw new Error(errors.map(error => error.message).join('\n\n')); - } - } - /** - * Utility function which asserts a SDL document is valid by throwing an error - * if it is invalid. - * - * @internal - */ - - function assertValidSDLExtension(documentAST, schema) { - const errors = validateSDL(documentAST, schema); - if (errors.length !== 0) { - throw new Error(errors.map(error => error.message).join('\n\n')); - } - } - - /***/ }), - - /***/ "../../../node_modules/graphql/version.mjs": - /*!*************************************************!*\ - !*** ../../../node_modules/graphql/version.mjs ***! - \*************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.versionInfo = exports.version = void 0; - // Note: This file is autogenerated using "resources/gen-version.js" script and - // automatically updated by "npm version" command. - - /** - * A string containing the version of the GraphQL.js library - */ - const version = exports.version = '16.8.1'; - /** - * An object containing the components of the GraphQL.js version string - */ - - const versionInfo = exports.versionInfo = Object.freeze({ - major: 16, - minor: 8, - patch: 1, - preReleaseTag: null - }); - - /***/ }), - - /***/ "../../../node_modules/hey-listen/dist/hey-listen.es.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/hey-listen/dist/hey-listen.es.js ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.warning = exports.invariant = void 0; - var warning = function () {}; - exports.warning = warning; - var invariant = function () {}; - exports.invariant = invariant; - if (true) { - exports.warning = warning = function (check, message) { - if (!check && typeof console !== 'undefined') { - console.warn(message); - } - }; - exports.invariant = invariant = function (check, message) { - if (!check) { - throw new Error(message); - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/is-plain-object/index.js": - /*!******************************************************!*\ - !*** ../../../node_modules/is-plain-object/index.js ***! - \******************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - /*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - - - - var isObject = __webpack_require__(/*! isobject */ "../../../node_modules/isobject/index.js"); - function isObjectObject(o) { - return isObject(o) === true && Object.prototype.toString.call(o) === '[object Object]'; - } - module.exports = function isPlainObject(o) { - var ctor, prot; - if (isObjectObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (typeof ctor !== 'function') return false; - - // If has modified prototype - prot = ctor.prototype; - if (isObjectObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; - }; - - /***/ }), - - /***/ "../../../node_modules/is-primitive/index.js": - /*!***************************************************!*\ - !*** ../../../node_modules/is-primitive/index.js ***! - \***************************************************/ - /***/ (function(module) { - - /*! - * is-primitive - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Released under the MIT License. - */ - - - - module.exports = function isPrimitive(val) { - if (typeof val === 'object') { - return val === null; - } - return typeof val !== 'function'; - }; - - /***/ }), - - /***/ "../../../node_modules/isarray/index.js": - /*!**********************************************!*\ - !*** ../../../node_modules/isarray/index.js ***! - \**********************************************/ - /***/ (function(module) { - - - - var toString = {}.toString; - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - /***/ }), - - /***/ "../../../node_modules/isobject/index.js": - /*!***********************************************!*\ - !*** ../../../node_modules/isobject/index.js ***! - \***********************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - /*! - * isobject - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - - var isArray = __webpack_require__(/*! isarray */ "../../../node_modules/isarray/index.js"); - module.exports = function isObject(val) { - return val != null && typeof val === 'object' && isArray(val) === false; - }; - - /***/ }), - - /***/ "../../../node_modules/meros/browser/index.js": - /*!****************************************************!*\ - !*** ../../../node_modules/meros/browser/index.js ***! - \****************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - var e = new TextDecoder(); - async function t(t, n) { - if (!t.ok || !t.body || t.bodyUsed) return t; - let i = t.headers.get("content-type"); - if (!i || !~i.indexOf("multipart/")) return t; - let l = i.indexOf("boundary="), - r = "-"; - if (~l) { - let e = l + 9, - t = i.indexOf(";", e); - r = i.slice(e, t > -1 ? t : void 0).trim().replace(/"/g, ""); - } - return async function* (t, n, i) { - let l, - r, - d, - o = t.getReader(), - a = !i || !i.multiple, - f = n.length, - s = "", - c = []; - try { - let t; - e: for (; !(t = await o.read()).done;) { - let i = e.decode(t.value); - l = s.length, s += i; - let o = i.indexOf(n); - for (~o ? l += o : l = s.indexOf(n), c = []; ~l;) { - let e = s.slice(0, l), - t = s.slice(l + f); - if (r) { - let n = e.indexOf("\r\n\r\n") + 4, - i = e.lastIndexOf("\r\n", n), - l = !1, - r = e.slice(n, i > -1 ? void 0 : i), - o = String(e.slice(0, n)).trim().split("\r\n"), - f = {}, - s = o.length; - for (; d = o[--s]; d = d.split(": "), f[d.shift().toLowerCase()] = d.join(": ")); - if (d = f["content-type"], d && ~d.indexOf("application/json")) try { - r = JSON.parse(r), l = !0; - } catch (e) {} - if (d = { - headers: f, - body: r, - json: l - }, a ? yield d : c.push(d), "--" === t.slice(0, 2)) break e; - } else n = "\r\n" + n, r = f += 2; - s = t, l = s.indexOf(n); - } - c.length && (yield c); - } - } finally { - c.length && (yield c), await o.cancel(); - } - }(t.body, `--${r}`, n); - } - exports.meros = t; - - /***/ }), - - /***/ "../../../node_modules/nullthrows/nullthrows.js": - /*!******************************************************!*\ - !*** ../../../node_modules/nullthrows/nullthrows.js ***! - \******************************************************/ - /***/ (function(module) { - - - - function nullthrows(x, message) { - if (x != null) { - return x; - } - var error = new Error(message !== undefined ? message : 'Got unexpected ' + x); - error.framesToPop = 1; // Skip nullthrows's own stack frame. - throw error; - } - module.exports = nullthrows; - module.exports["default"] = nullthrows; - Object.defineProperty(module.exports, "__esModule", ({ - value: true - })); - - /***/ }), - - /***/ "../../../node_modules/popmotion/dist/popmotion.cjs.js": - /*!*************************************************************!*\ - !*** ../../../node_modules/popmotion/dist/popmotion.cjs.js ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var heyListen = __webpack_require__(/*! hey-listen */ "../../../node_modules/hey-listen/dist/hey-listen.es.js"); - var styleValueTypes = __webpack_require__(/*! style-value-types */ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js"); - var sync = __webpack_require__(/*! framesync */ "../../../node_modules/framesync/dist/framesync.cjs.js"); - function _interopDefaultLegacy(e) { - return e && typeof e === 'object' && 'default' in e ? e : { - 'default': e - }; - } - var sync__default = /*#__PURE__*/_interopDefaultLegacy(sync); - const clamp = (min, max, v) => Math.min(Math.max(v, min), max); - const safeMin = 0.001; - const minDuration = 0.01; - const maxDuration = 10.0; - const minDamping = 0.05; - const maxDamping = 1; - function findSpring({ - duration = 800, - bounce = 0.25, - velocity = 0, - mass = 1 - }) { - let envelope; - let derivative; - heyListen.warning(duration <= maxDuration * 1000, "Spring duration must be 10 seconds or less"); - let dampingRatio = 1 - bounce; - dampingRatio = clamp(minDamping, maxDamping, dampingRatio); - duration = clamp(minDuration, maxDuration, duration / 1000); - if (dampingRatio < 1) { - envelope = undampedFreq => { - const exponentialDecay = undampedFreq * dampingRatio; - const delta = exponentialDecay * duration; - const a = exponentialDecay - velocity; - const b = calcAngularFreq(undampedFreq, dampingRatio); - const c = Math.exp(-delta); - return safeMin - a / b * c; - }; - derivative = undampedFreq => { - const exponentialDecay = undampedFreq * dampingRatio; - const delta = exponentialDecay * duration; - const d = delta * velocity + velocity; - const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration; - const f = Math.exp(-delta); - const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio); - const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1; - return factor * ((d - e) * f) / g; - }; - } else { - envelope = undampedFreq => { - const a = Math.exp(-undampedFreq * duration); - const b = (undampedFreq - velocity) * duration + 1; - return -safeMin + a * b; - }; - derivative = undampedFreq => { - const a = Math.exp(-undampedFreq * duration); - const b = (velocity - undampedFreq) * (duration * duration); - return a * b; - }; - } - const initialGuess = 5 / duration; - const undampedFreq = approximateRoot(envelope, derivative, initialGuess); - duration = duration * 1000; - if (isNaN(undampedFreq)) { - return { - stiffness: 100, - damping: 10, - duration - }; - } else { - const stiffness = Math.pow(undampedFreq, 2) * mass; - return { - stiffness, - damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), - duration - }; - } - } - const rootIterations = 12; - function approximateRoot(envelope, derivative, initialGuess) { - let result = initialGuess; - for (let i = 1; i < rootIterations; i++) { - result = result - envelope(result) / derivative(result); - } - return result; - } - function calcAngularFreq(undampedFreq, dampingRatio) { - return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); - } - const durationKeys = ["duration", "bounce"]; - const physicsKeys = ["stiffness", "damping", "mass"]; - function isSpringType(options, keys) { - return keys.some(key => options[key] !== undefined); - } - function getSpringOptions(options) { - let springOptions = Object.assign({ - velocity: 0.0, - stiffness: 100, - damping: 10, - mass: 1.0, - isResolvedFromDuration: false - }, options); - if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) { - const derived = findSpring(options); - springOptions = Object.assign(Object.assign(Object.assign({}, springOptions), derived), { - velocity: 0.0, - mass: 1.0 - }); - springOptions.isResolvedFromDuration = true; - } - return springOptions; - } - function spring(_a) { - var { - from = 0.0, - to = 1.0, - restSpeed = 2, - restDelta - } = _a, - options = tslib.__rest(_a, ["from", "to", "restSpeed", "restDelta"]); - const state = { - done: false, - value: from - }; - let { - stiffness, - damping, - mass, - velocity, - duration, - isResolvedFromDuration - } = getSpringOptions(options); - let resolveSpring = zero; - let resolveVelocity = zero; - function createSpring() { - const initialVelocity = velocity ? -(velocity / 1000) : 0.0; - const initialDelta = to - from; - const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); - const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000; - if (restDelta === undefined) { - restDelta = Math.min(Math.abs(to - from) / 100, 0.4); - } - if (dampingRatio < 1) { - const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); - resolveSpring = t => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); - }; - resolveVelocity = t => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - return dampingRatio * undampedAngularFreq * envelope * (Math.sin(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq + initialDelta * Math.cos(angularFreq * t)) - envelope * (Math.cos(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) - angularFreq * initialDelta * Math.sin(angularFreq * t)); - }; - } else if (dampingRatio === 1) { - resolveSpring = t => to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t); - } else { - const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); - resolveSpring = t => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - const freqForT = Math.min(dampedAngularFreq * t, 300); - return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq; - }; - } - } - createSpring(); - return { - next: t => { - const current = resolveSpring(t); - if (!isResolvedFromDuration) { - const currentVelocity = resolveVelocity(t) * 1000; - const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed; - const isBelowDisplacementThreshold = Math.abs(to - current) <= restDelta; - state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold; - } else { - state.done = t >= duration; - } - state.value = state.done ? to : current; - return state; - }, - flipTarget: () => { - velocity = -velocity; - [from, to] = [to, from]; - createSpring(); - } - }; - } - spring.needsInterpolation = (a, b) => typeof a === "string" || typeof b === "string"; - const zero = _t => 0; - const progress = (from, to, value) => { - const toFromDifference = to - from; - return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; - }; - const mix = (from, to, progress) => -progress * from + progress * to + from; - function hueToRgb(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1 / 6) return p + (q - p) * 6 * t; - if (t < 1 / 2) return q; - if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; - return p; - } - function hslaToRgba({ - hue, - saturation, - lightness, - alpha - }) { - hue /= 360; - saturation /= 100; - lightness /= 100; - let red = 0; - let green = 0; - let blue = 0; - if (!saturation) { - red = green = blue = lightness; - } else { - const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; - const p = 2 * lightness - q; - red = hueToRgb(p, q, hue + 1 / 3); - green = hueToRgb(p, q, hue); - blue = hueToRgb(p, q, hue - 1 / 3); - } - return { - red: Math.round(red * 255), - green: Math.round(green * 255), - blue: Math.round(blue * 255), - alpha - }; - } - const mixLinearColor = (from, to, v) => { - const fromExpo = from * from; - const toExpo = to * to; - return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo)); - }; - const colorTypes = [styleValueTypes.hex, styleValueTypes.rgba, styleValueTypes.hsla]; - const getColorType = v => colorTypes.find(type => type.test(v)); - const notAnimatable = color => `'${color}' is not an animatable color. Use the equivalent color code instead.`; - const mixColor = (from, to) => { - let fromColorType = getColorType(from); - let toColorType = getColorType(to); - heyListen.invariant(!!fromColorType, notAnimatable(from)); - heyListen.invariant(!!toColorType, notAnimatable(to)); - let fromColor = fromColorType.parse(from); - let toColor = toColorType.parse(to); - if (fromColorType === styleValueTypes.hsla) { - fromColor = hslaToRgba(fromColor); - fromColorType = styleValueTypes.rgba; - } - if (toColorType === styleValueTypes.hsla) { - toColor = hslaToRgba(toColor); - toColorType = styleValueTypes.rgba; - } - const blended = Object.assign({}, fromColor); - return v => { - for (const key in blended) { - if (key !== "alpha") { - blended[key] = mixLinearColor(fromColor[key], toColor[key], v); - } - } - blended.alpha = mix(fromColor.alpha, toColor.alpha, v); - return fromColorType.transform(blended); - }; - }; - const zeroPoint = { - x: 0, - y: 0, - z: 0 - }; - const isNum = v => typeof v === 'number'; - const combineFunctions = (a, b) => v => b(a(v)); - const pipe = (...transformers) => transformers.reduce(combineFunctions); - function getMixer(origin, target) { - if (isNum(origin)) { - return v => mix(origin, target, v); - } else if (styleValueTypes.color.test(origin)) { - return mixColor(origin, target); - } else { - return mixComplex(origin, target); - } - } - const mixArray = (from, to) => { - const output = [...from]; - const numValues = output.length; - const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i])); - return v => { - for (let i = 0; i < numValues; i++) { - output[i] = blendValue[i](v); - } - return output; - }; - }; - const mixObject = (origin, target) => { - const output = Object.assign(Object.assign({}, origin), target); - const blendValue = {}; - for (const key in output) { - if (origin[key] !== undefined && target[key] !== undefined) { - blendValue[key] = getMixer(origin[key], target[key]); - } - } - return v => { - for (const key in blendValue) { - output[key] = blendValue[key](v); - } - return output; - }; - }; - function analyse(value) { - const parsed = styleValueTypes.complex.parse(value); - const numValues = parsed.length; - let numNumbers = 0; - let numRGB = 0; - let numHSL = 0; - for (let i = 0; i < numValues; i++) { - if (numNumbers || typeof parsed[i] === "number") { - numNumbers++; - } else { - if (parsed[i].hue !== undefined) { - numHSL++; - } else { - numRGB++; - } - } - } - return { - parsed, - numNumbers, - numRGB, - numHSL - }; - } - const mixComplex = (origin, target) => { - const template = styleValueTypes.complex.createTransformer(target); - const originStats = analyse(origin); - const targetStats = analyse(target); - const canInterpolate = originStats.numHSL === targetStats.numHSL && originStats.numRGB === targetStats.numRGB && originStats.numNumbers >= targetStats.numNumbers; - if (canInterpolate) { - return pipe(mixArray(originStats.parsed, targetStats.parsed), template); - } else { - heyListen.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`); - return p => `${p > 0 ? target : origin}`; - } - }; - const mixNumber = (from, to) => p => mix(from, to, p); - function detectMixerFactory(v) { - if (typeof v === 'number') { - return mixNumber; - } else if (typeof v === 'string') { - if (styleValueTypes.color.test(v)) { - return mixColor; - } else { - return mixComplex; - } - } else if (Array.isArray(v)) { - return mixArray; - } else if (typeof v === 'object') { - return mixObject; - } - } - function createMixers(output, ease, customMixer) { - const mixers = []; - const mixerFactory = customMixer || detectMixerFactory(output[0]); - const numMixers = output.length - 1; - for (let i = 0; i < numMixers; i++) { - let mixer = mixerFactory(output[i], output[i + 1]); - if (ease) { - const easingFunction = Array.isArray(ease) ? ease[i] : ease; - mixer = pipe(easingFunction, mixer); - } - mixers.push(mixer); - } - return mixers; - } - function fastInterpolate([from, to], [mixer]) { - return v => mixer(progress(from, to, v)); - } - function slowInterpolate(input, mixers) { - const inputLength = input.length; - const lastInputIndex = inputLength - 1; - return v => { - let mixerIndex = 0; - let foundMixerIndex = false; - if (v <= input[0]) { - foundMixerIndex = true; - } else if (v >= input[lastInputIndex]) { - mixerIndex = lastInputIndex - 1; - foundMixerIndex = true; - } - if (!foundMixerIndex) { - let i = 1; - for (; i < inputLength; i++) { - if (input[i] > v || i === lastInputIndex) { - break; - } - } - mixerIndex = i - 1; - } - const progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v); - return mixers[mixerIndex](progressInRange); - }; - } - function interpolate(input, output, { - clamp: isClamp = true, - ease, - mixer - } = {}) { - const inputLength = input.length; - heyListen.invariant(inputLength === output.length, 'Both input and output ranges must be the same length'); - heyListen.invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1, 'Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values.'); - if (input[0] > input[inputLength - 1]) { - input = [].concat(input); - output = [].concat(output); - input.reverse(); - output.reverse(); - } - const mixers = createMixers(output, ease, mixer); - const interpolator = inputLength === 2 ? fastInterpolate(input, mixers) : slowInterpolate(input, mixers); - return isClamp ? v => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator; - } - const reverseEasing = easing => p => 1 - easing(1 - p); - const mirrorEasing = easing => p => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; - const createExpoIn = power => p => Math.pow(p, power); - const createBackIn = power => p => p * p * ((power + 1) * p - power); - const createAnticipate = power => { - const backEasing = createBackIn(power); - return p => (p *= 2) < 1 ? 0.5 * backEasing(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); - }; - const DEFAULT_OVERSHOOT_STRENGTH = 1.525; - const BOUNCE_FIRST_THRESHOLD = 4.0 / 11.0; - const BOUNCE_SECOND_THRESHOLD = 8.0 / 11.0; - const BOUNCE_THIRD_THRESHOLD = 9.0 / 10.0; - const linear = p => p; - const easeIn = createExpoIn(2); - const easeOut = reverseEasing(easeIn); - const easeInOut = mirrorEasing(easeIn); - const circIn = p => 1 - Math.sin(Math.acos(p)); - const circOut = reverseEasing(circIn); - const circInOut = mirrorEasing(circOut); - const backIn = createBackIn(DEFAULT_OVERSHOOT_STRENGTH); - const backOut = reverseEasing(backIn); - const backInOut = mirrorEasing(backIn); - const anticipate = createAnticipate(DEFAULT_OVERSHOOT_STRENGTH); - const ca = 4356.0 / 361.0; - const cb = 35442.0 / 1805.0; - const cc = 16061.0 / 1805.0; - const bounceOut = p => { - if (p === 1 || p === 0) return p; - const p2 = p * p; - return p < BOUNCE_FIRST_THRESHOLD ? 7.5625 * p2 : p < BOUNCE_SECOND_THRESHOLD ? 9.075 * p2 - 9.9 * p + 3.4 : p < BOUNCE_THIRD_THRESHOLD ? ca * p2 - cb * p + cc : 10.8 * p * p - 20.52 * p + 10.72; - }; - const bounceIn = reverseEasing(bounceOut); - const bounceInOut = p => p < 0.5 ? 0.5 * (1.0 - bounceOut(1.0 - p * 2.0)) : 0.5 * bounceOut(p * 2.0 - 1.0) + 0.5; - function defaultEasing(values, easing) { - return values.map(() => easing || easeInOut).splice(0, values.length - 1); - } - function defaultOffset(values) { - const numValues = values.length; - return values.map((_value, i) => i !== 0 ? i / (numValues - 1) : 0); - } - function convertOffsetToTimes(offset, duration) { - return offset.map(o => o * duration); - } - function keyframes({ - from = 0, - to = 1, - ease, - offset, - duration = 300 - }) { - const state = { - done: false, - value: from - }; - const values = Array.isArray(to) ? to : [from, to]; - const times = convertOffsetToTimes(offset && offset.length === values.length ? offset : defaultOffset(values), duration); - function createInterpolator() { - return interpolate(times, values, { - ease: Array.isArray(ease) ? ease : defaultEasing(values, ease) - }); - } - let interpolator = createInterpolator(); - return { - next: t => { - state.value = interpolator(t); - state.done = t >= duration; - return state; - }, - flipTarget: () => { - values.reverse(); - interpolator = createInterpolator(); - } - }; - } - function decay({ - velocity = 0, - from = 0, - power = 0.8, - timeConstant = 350, - restDelta = 0.5, - modifyTarget - }) { - const state = { - done: false, - value: from - }; - let amplitude = power * velocity; - const ideal = from + amplitude; - const target = modifyTarget === undefined ? ideal : modifyTarget(ideal); - if (target !== ideal) amplitude = target - from; - return { - next: t => { - const delta = -amplitude * Math.exp(-t / timeConstant); - state.done = !(delta > restDelta || delta < -restDelta); - state.value = state.done ? target : target + delta; - return state; - }, - flipTarget: () => {} - }; - } - const types = { - keyframes, - spring, - decay - }; - function detectAnimationFromOptions(config) { - if (Array.isArray(config.to)) { - return keyframes; - } else if (types[config.type]) { - return types[config.type]; - } - const keys = new Set(Object.keys(config)); - if (keys.has("ease") || keys.has("duration") && !keys.has("dampingRatio")) { - return keyframes; - } else if (keys.has("dampingRatio") || keys.has("stiffness") || keys.has("mass") || keys.has("damping") || keys.has("restSpeed") || keys.has("restDelta")) { - return spring; - } - return keyframes; - } - function loopElapsed(elapsed, duration, delay = 0) { - return elapsed - duration - delay; - } - function reverseElapsed(elapsed, duration, delay = 0, isForwardPlayback = true) { - return isForwardPlayback ? loopElapsed(duration + -elapsed, duration, delay) : duration - (elapsed - duration) + delay; - } - function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) { - return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay; - } - const framesync = update => { - const passTimestamp = ({ - delta - }) => update(delta); - return { - start: () => sync__default["default"].update(passTimestamp, true), - stop: () => sync.cancelSync.update(passTimestamp) - }; - }; - function animate(_a) { - var _b, _c; - var { - from, - autoplay = true, - driver = framesync, - elapsed = 0, - repeat: repeatMax = 0, - repeatType = "loop", - repeatDelay = 0, - onPlay, - onStop, - onComplete, - onRepeat, - onUpdate - } = _a, - options = tslib.__rest(_a, ["from", "autoplay", "driver", "elapsed", "repeat", "repeatType", "repeatDelay", "onPlay", "onStop", "onComplete", "onRepeat", "onUpdate"]); - let { - to - } = options; - let driverControls; - let repeatCount = 0; - let computedDuration = options.duration; - let latest; - let isComplete = false; - let isForwardPlayback = true; - let interpolateFromNumber; - const animator = detectAnimationFromOptions(options); - if ((_c = (_b = animator).needsInterpolation) === null || _c === void 0 ? void 0 : _c.call(_b, from, to)) { - interpolateFromNumber = interpolate([0, 100], [from, to], { - clamp: false - }); - from = 0; - to = 100; - } - const animation = animator(Object.assign(Object.assign({}, options), { - from, - to - })); - function repeat() { - repeatCount++; - if (repeatType === "reverse") { - isForwardPlayback = repeatCount % 2 === 0; - elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback); - } else { - elapsed = loopElapsed(elapsed, computedDuration, repeatDelay); - if (repeatType === "mirror") animation.flipTarget(); - } - isComplete = false; - onRepeat && onRepeat(); - } - function complete() { - driverControls.stop(); - onComplete && onComplete(); - } - function update(delta) { - if (!isForwardPlayback) delta = -delta; - elapsed += delta; - if (!isComplete) { - const state = animation.next(Math.max(0, elapsed)); - latest = state.value; - if (interpolateFromNumber) latest = interpolateFromNumber(latest); - isComplete = isForwardPlayback ? state.done : elapsed <= 0; - } - onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(latest); - if (isComplete) { - if (repeatCount === 0) computedDuration !== null && computedDuration !== void 0 ? computedDuration : computedDuration = elapsed; - if (repeatCount < repeatMax) { - hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat(); - } else { - complete(); - } - } - } - function play() { - onPlay === null || onPlay === void 0 ? void 0 : onPlay(); - driverControls = driver(update); - driverControls.start(); - } - autoplay && play(); - return { - stop: () => { - onStop === null || onStop === void 0 ? void 0 : onStop(); - driverControls.stop(); - } - }; - } - function velocityPerSecond(velocity, frameDuration) { - return frameDuration ? velocity * (1000 / frameDuration) : 0; - } - function inertia({ - from = 0, - velocity = 0, - min, - max, - power = 0.8, - timeConstant = 750, - bounceStiffness = 500, - bounceDamping = 10, - restDelta = 1, - modifyTarget, - driver, - onUpdate, - onComplete, - onStop - }) { - let currentAnimation; - function isOutOfBounds(v) { - return min !== undefined && v < min || max !== undefined && v > max; - } - function boundaryNearest(v) { - if (min === undefined) return max; - if (max === undefined) return min; - return Math.abs(min - v) < Math.abs(max - v) ? min : max; - } - function startAnimation(options) { - currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop(); - currentAnimation = animate(Object.assign(Object.assign({}, options), { - driver, - onUpdate: v => { - var _a; - onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(v); - (_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, v); - }, - onComplete, - onStop - })); - } - function startSpring(options) { - startAnimation(Object.assign({ - type: "spring", - stiffness: bounceStiffness, - damping: bounceDamping, - restDelta - }, options)); - } - if (isOutOfBounds(from)) { - startSpring({ - from, - velocity, - to: boundaryNearest(from) - }); - } else { - let target = power * velocity + from; - if (typeof modifyTarget !== "undefined") target = modifyTarget(target); - const boundary = boundaryNearest(target); - const heading = boundary === min ? -1 : 1; - let prev; - let current; - const checkBoundary = v => { - prev = current; - current = v; - velocity = velocityPerSecond(v - prev, sync.getFrameData().delta); - if (heading === 1 && v > boundary || heading === -1 && v < boundary) { - startSpring({ - from: v, - to: boundary, - velocity - }); - } - }; - startAnimation({ - type: "decay", - from, - velocity, - timeConstant, - power, - restDelta, - modifyTarget, - onUpdate: isOutOfBounds(target) ? checkBoundary : undefined - }); - } - return { - stop: () => currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop() - }; - } - const radiansToDegrees = radians => radians * 180 / Math.PI; - const angle = (a, b = zeroPoint) => radiansToDegrees(Math.atan2(b.y - a.y, b.x - a.x)); - const applyOffset = (from, to) => { - let hasReceivedFrom = true; - if (to === undefined) { - to = from; - hasReceivedFrom = false; - } - return v => { - if (hasReceivedFrom) { - return v - from + to; - } else { - from = v; - hasReceivedFrom = true; - return to; - } - }; - }; - const identity = v => v; - const createAttractor = (alterDisplacement = identity) => (constant, origin, v) => { - const displacement = origin - v; - const springModifiedDisplacement = -(0 - constant + 1) * (0 - alterDisplacement(Math.abs(displacement))); - return displacement <= 0 ? origin + springModifiedDisplacement : origin - springModifiedDisplacement; - }; - const attract = createAttractor(); - const attractExpo = createAttractor(Math.sqrt); - const degreesToRadians = degrees => degrees * Math.PI / 180; - const isPoint = point => point.hasOwnProperty('x') && point.hasOwnProperty('y'); - const isPoint3D = point => isPoint(point) && point.hasOwnProperty('z'); - const distance1D = (a, b) => Math.abs(a - b); - function distance(a, b) { - if (isNum(a) && isNum(b)) { - return distance1D(a, b); - } else if (isPoint(a) && isPoint(b)) { - const xDelta = distance1D(a.x, b.x); - const yDelta = distance1D(a.y, b.y); - const zDelta = isPoint3D(a) && isPoint3D(b) ? distance1D(a.z, b.z) : 0; - return Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2)); - } - } - const pointFromVector = (origin, angle, distance) => { - angle = degreesToRadians(angle); - return { - x: distance * Math.cos(angle) + origin.x, - y: distance * Math.sin(angle) + origin.y - }; - }; - const toDecimal = (num, precision = 2) => { - precision = Math.pow(10, precision); - return Math.round(num * precision) / precision; - }; - const smoothFrame = (prevValue, nextValue, duration, smoothing = 0) => toDecimal(prevValue + duration * (nextValue - prevValue) / Math.max(smoothing, duration)); - const smooth = (strength = 50) => { - let previousValue = 0; - let lastUpdated = 0; - return v => { - const currentFramestamp = sync.getFrameData().timestamp; - const timeDelta = currentFramestamp !== lastUpdated ? currentFramestamp - lastUpdated : 0; - const newValue = timeDelta ? smoothFrame(previousValue, v, timeDelta, strength) : previousValue; - lastUpdated = currentFramestamp; - previousValue = newValue; - return newValue; - }; - }; - const snap = points => { - if (typeof points === 'number') { - return v => Math.round(v / points) * points; - } else { - let i = 0; - const numPoints = points.length; - return v => { - let lastDistance = Math.abs(points[0] - v); - for (i = 1; i < numPoints; i++) { - const point = points[i]; - const distance = Math.abs(point - v); - if (distance === 0) return point; - if (distance > lastDistance) return points[i - 1]; - if (i === numPoints - 1) return point; - lastDistance = distance; - } - }; - } - }; - function velocityPerFrame(xps, frameDuration) { - return xps / (1000 / frameDuration); - } - const wrap = (min, max, v) => { - const rangeSize = max - min; - return ((v - min) % rangeSize + rangeSize) % rangeSize + min; - }; - const a = (a1, a2) => 1.0 - 3.0 * a2 + 3.0 * a1; - const b = (a1, a2) => 3.0 * a2 - 6.0 * a1; - const c = a1 => 3.0 * a1; - const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; - const getSlope = (t, a1, a2) => 3.0 * a(a1, a2) * t * t + 2.0 * b(a1, a2) * t + c(a1); - const subdivisionPrecision = 0.0000001; - const subdivisionMaxIterations = 10; - function binarySubdivide(aX, aA, aB, mX1, mX2) { - let currentX; - let currentT; - let i = 0; - do { - currentT = aA + (aB - aA) / 2.0; - currentX = calcBezier(currentT, mX1, mX2) - aX; - if (currentX > 0.0) { - aB = currentT; - } else { - aA = currentT; - } - } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); - return currentT; - } - const newtonIterations = 8; - const newtonMinSlope = 0.001; - function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { - for (let i = 0; i < newtonIterations; ++i) { - const currentSlope = getSlope(aGuessT, mX1, mX2); - if (currentSlope === 0.0) { - return aGuessT; - } - const currentX = calcBezier(aGuessT, mX1, mX2) - aX; - aGuessT -= currentX / currentSlope; - } - return aGuessT; - } - const kSplineTableSize = 11; - const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); - function cubicBezier(mX1, mY1, mX2, mY2) { - if (mX1 === mY1 && mX2 === mY2) return linear; - const sampleValues = new Float32Array(kSplineTableSize); - for (let i = 0; i < kSplineTableSize; ++i) { - sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); - } - function getTForX(aX) { - let intervalStart = 0.0; - let currentSample = 1; - const lastSample = kSplineTableSize - 1; - for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) { - intervalStart += kSampleStepSize; - } - --currentSample; - const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]); - const guessForT = intervalStart + dist * kSampleStepSize; - const initialSlope = getSlope(guessForT, mX1, mX2); - if (initialSlope >= newtonMinSlope) { - return newtonRaphsonIterate(aX, guessForT, mX1, mX2); - } else if (initialSlope === 0.0) { - return guessForT; - } else { - return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); - } - } - return t => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); - } - const steps = (steps, direction = 'end') => progress => { - progress = direction === 'end' ? Math.min(progress, 0.999) : Math.max(progress, 0.001); - const expanded = progress * steps; - const rounded = direction === 'end' ? Math.floor(expanded) : Math.ceil(expanded); - return clamp(0, 1, rounded / steps); - }; - exports.angle = angle; - exports.animate = animate; - exports.anticipate = anticipate; - exports.applyOffset = applyOffset; - exports.attract = attract; - exports.attractExpo = attractExpo; - exports.backIn = backIn; - exports.backInOut = backInOut; - exports.backOut = backOut; - exports.bounceIn = bounceIn; - exports.bounceInOut = bounceInOut; - exports.bounceOut = bounceOut; - exports.circIn = circIn; - exports.circInOut = circInOut; - exports.circOut = circOut; - exports.clamp = clamp; - exports.createAnticipate = createAnticipate; - exports.createAttractor = createAttractor; - exports.createBackIn = createBackIn; - exports.createExpoIn = createExpoIn; - exports.cubicBezier = cubicBezier; - exports.decay = decay; - exports.degreesToRadians = degreesToRadians; - exports.distance = distance; - exports.easeIn = easeIn; - exports.easeInOut = easeInOut; - exports.easeOut = easeOut; - exports.inertia = inertia; - exports.interpolate = interpolate; - exports.isPoint = isPoint; - exports.isPoint3D = isPoint3D; - exports.keyframes = keyframes; - exports.linear = linear; - exports.mirrorEasing = mirrorEasing; - exports.mix = mix; - exports.mixColor = mixColor; - exports.mixComplex = mixComplex; - exports.pipe = pipe; - exports.pointFromVector = pointFromVector; - exports.progress = progress; - exports.radiansToDegrees = radiansToDegrees; - exports.reverseEasing = reverseEasing; - exports.smooth = smooth; - exports.smoothFrame = smoothFrame; - exports.snap = snap; - exports.spring = spring; - exports.steps = steps; - exports.toDecimal = toDecimal; - exports.velocityPerFrame = velocityPerFrame; - exports.velocityPerSecond = velocityPerSecond; - exports.wrap = wrap; - - /***/ }), - - /***/ "../../../node_modules/punycode.js/punycode.es6.js": - /*!*********************************************************!*\ - !*** ../../../node_modules/punycode.js/punycode.es6.js ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - /** Highest positive signed 32-bit float value */ - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.toUnicode = exports.toASCII = exports.encode = exports["default"] = exports.decode = void 0; - exports.ucs2decode = ucs2decode; - exports.ucs2encode = void 0; - const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - const base = 36; - const tMin = 1; - const tMax = 26; - const skew = 38; - const damp = 700; - const initialBias = 72; - const initialN = 128; // 0x80 - const delimiter = '-'; // '\x2D' - - /** Regular expressions */ - const regexPunycode = /^xn--/; - const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. - const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - - /** Error messages */ - const errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }; - - /** Convenience shortcuts */ - const baseMinusTMin = base - tMin; - const floor = Math.floor; - const stringFromCharCode = String.fromCharCode; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, callback) { - const result = []; - let length = array.length; - while (length--) { - result[length] = callback(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {String} A new string of characters returned by the callback - * function. - */ - function mapDomain(domain, callback) { - const parts = domain.split('@'); - let result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - domain = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - domain = domain.replace(regexSeparators, '\x2E'); - const labels = domain.split('.'); - const encoded = map(labels, callback).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - const output = []; - let counter = 0; - const length = string.length; - while (counter < length) { - const value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // It's a high surrogate, and there is a next character. - const extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // Low surrogate. - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // It's an unmatched surrogate; only append this code unit, in case the - // next code unit is the high surrogate of a surrogate pair. - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - const ucs2encode = codePoints => String.fromCodePoint(...codePoints); - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - exports.ucs2encode = ucs2encode; - const basicToDigit = function (codePoint) { - if (codePoint >= 0x30 && codePoint < 0x3A) { - return 26 + (codePoint - 0x30); - } - if (codePoint >= 0x41 && codePoint < 0x5B) { - return codePoint - 0x41; - } - if (codePoint >= 0x61 && codePoint < 0x7B) { - return codePoint - 0x61; - } - return base; - }; - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - const digitToBasic = function (digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - }; - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - const adapt = function (delta, numPoints, firstTime) { - let k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for /* no initialization */ - (; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - }; - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - const decode = function (input) { - // Don't use UCS-2. - const output = []; - const inputLength = input.length; - let i = 0; - let n = initialN; - let bias = initialBias; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - let basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - for (let j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for /* no final expression */ - (let index = basic > 0 ? basic + 1 : 0; index < inputLength;) { - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - const oldi = i; - for /* no condition */ - (let w = 1, k = base;; k += base) { - if (index >= inputLength) { - error('invalid-input'); - } - const digit = basicToDigit(input.charCodeAt(index++)); - if (digit >= base) { - error('invalid-input'); - } - if (digit > floor((maxInt - i) / w)) { - error('overflow'); - } - i += digit * w; - const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (digit < t) { - break; - } - const baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - w *= baseMinusT; - } - const out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } - return String.fromCodePoint(...output); - }; - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - exports.decode = decode; - const encode = function (input) { - const output = []; - - // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); - - // Cache the length. - const inputLength = input.length; - - // Initialize the state. - let n = initialN; - let delta = 0; - let bias = initialBias; - - // Handle the basic code points. - for (const currentValue of input) { - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - const basicLength = output.length; - let handledCPCount = basicLength; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string with a delimiter unless it's empty. - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - // All non-basic code points < n have been handled already. Find the next - // larger one: - let m = maxInt; - for (const currentValue of input) { - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow. - const handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - delta += (m - n) * handledCPCountPlusOne; - n = m; - for (const currentValue of input) { - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - if (currentValue === n) { - // Represent delta as a generalized variable-length integer. - let q = delta; - for /* no condition */ - (let k = base;; k += base) { - const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; - } - const qMinusT = q - t; - const baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); - delta = 0; - ++handledCPCount; - } - } - ++delta; - ++n; - } - return output.join(''); - }; - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - exports.encode = encode; - const toUnicode = function (input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); - }; - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - exports.toUnicode = toUnicode; - const toASCII = function (input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); - }; - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - exports.toASCII = toASCII; - const punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '2.3.1', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - var _default = exports["default"] = punycode; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js ***! - \******************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.RemoveScrollBar = void 0; - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); - var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); - var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - var Style = (0, _reactStyleSingleton.styleSingleton)(); - // important tip - once we measure scrollBar width and remove them - // we could not repeat this operation - // thus we are using style-singleton - only the first "yet correct" style will be applied. - var getStyles = function (_a, allowRelative, gapMode, important) { - var left = _a.left, - top = _a.top, - right = _a.right, - gap = _a.gap; - if (gapMode === void 0) { - gapMode = 'margin'; - } - return "\n .".concat(_constants.noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([allowRelative && "position: relative ".concat(important, ";"), gapMode === 'margin' && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), gapMode === 'padding' && "padding-right: ".concat(gap, "px ").concat(important, ";")].filter(Boolean).join(''), "\n }\n \n .").concat(_constants.zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(_constants.zeroRightClassName, " .").concat(_constants.zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(_constants.fullWidthClassName, " .").concat(_constants.fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body {\n ").concat(_constants.removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); - }; - /** - * Removes page scrollbar and blocks page scroll when mounted - */ - var RemoveScrollBar = function (props) { - var noRelative = props.noRelative, - noImportant = props.noImportant, - _a = props.gapMode, - gapMode = _a === void 0 ? 'margin' : _a; - var gap = React.useMemo(function () { - return (0, _utils.getGapWidth)(gapMode); - }, [gapMode]); - return /*#__PURE__*/React.createElement(Style, { - styles: getStyles(gap, !noRelative, gapMode, !noImportant ? '!important' : '') - }); - }; - exports.RemoveScrollBar = RemoveScrollBar; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js": - /*!******************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js ***! - \******************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.zeroRightClassName = exports.removedBarSizeVariable = exports.noScrollbarsClassName = exports.fullWidthClassName = void 0; - var zeroRightClassName = exports.zeroRightClassName = 'right-scroll-bar-position'; - var fullWidthClassName = exports.fullWidthClassName = 'width-before-scroll-bar'; - var noScrollbarsClassName = exports.noScrollbarsClassName = 'with-scroll-bars-hidden'; - /** - * Name of a CSS variable containing the amount of "hidden" scrollbar - * ! might be undefined ! use will fallback! - */ - var removedBarSizeVariable = exports.removedBarSizeVariable = '--removed-body-scroll-bar-size'; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js ***! - \**************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "RemoveScrollBar", ({ - enumerable: true, - get: function () { - return _component.RemoveScrollBar; - } - })); - Object.defineProperty(exports, "fullWidthClassName", ({ - enumerable: true, - get: function () { - return _constants.fullWidthClassName; - } - })); - Object.defineProperty(exports, "getGapWidth", ({ - enumerable: true, - get: function () { - return _utils.getGapWidth; - } - })); - Object.defineProperty(exports, "noScrollbarsClassName", ({ - enumerable: true, - get: function () { - return _constants.noScrollbarsClassName; - } - })); - Object.defineProperty(exports, "removedBarSizeVariable", ({ - enumerable: true, - get: function () { - return _constants.removedBarSizeVariable; - } - })); - Object.defineProperty(exports, "zeroRightClassName", ({ - enumerable: true, - get: function () { - return _constants.zeroRightClassName; - } - })); - var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/component.js"); - var _constants = __webpack_require__(/*! ./constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); - var _utils = __webpack_require__(/*! ./utils */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js"); - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll-bar/dist/es2015/utils.js ***! - \**************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.zeroGap = exports.getGapWidth = void 0; - var zeroGap = exports.zeroGap = { - left: 0, - top: 0, - right: 0, - gap: 0 - }; - var parse = function (x) { - return parseInt(x || '', 10) || 0; - }; - var getOffset = function (gapMode) { - var cs = window.getComputedStyle(document.body); - if (true) { - if (cs.overflowY === 'hidden') { - console.error('react-remove-scroll-bar: cannot calculate scrollbar size because it is removed (overflow:hidden on body'); - } - } - var left = cs[gapMode === 'padding' ? 'paddingLeft' : 'marginLeft']; - var top = cs[gapMode === 'padding' ? 'paddingTop' : 'marginTop']; - var right = cs[gapMode === 'padding' ? 'paddingRight' : 'marginRight']; - return [parse(left), parse(top), parse(right)]; - }; - var getGapWidth = function (gapMode) { - if (gapMode === void 0) { - gapMode = 'margin'; - } - if (typeof window === 'undefined') { - return zeroGap; - } - var offsets = getOffset(gapMode); - var documentWidth = document.documentElement.clientWidth; - var windowWidth = window.innerWidth; - return { - left: offsets[0], - top: offsets[1], - right: offsets[2], - gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) - }; - }; - exports.getGapWidth = getGapWidth; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/Combination.js ***! - \****************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports["default"] = void 0; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _UI = __webpack_require__(/*! ./UI */ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js"); - var _sidecar = _interopRequireDefault(__webpack_require__(/*! ./sidecar */ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js")); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - var ReactRemoveScroll = /*#__PURE__*/React.forwardRef(function (props, ref) { - return /*#__PURE__*/React.createElement(_UI.RemoveScroll, (0, _tslib.__assign)({}, props, { - ref: ref, - sideCar: _sidecar.default - })); - }); - ReactRemoveScroll.classNames = _UI.RemoveScroll.classNames; - var _default = exports["default"] = ReactRemoveScroll; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js ***! - \***************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.RemoveScrollSideCar = RemoveScrollSideCar; - exports.getTouchXY = exports.getDeltaXY = void 0; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _reactRemoveScrollBar = __webpack_require__(/*! react-remove-scroll-bar */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/index.js"); - var _reactStyleSingleton = __webpack_require__(/*! react-style-singleton */ "../../../node_modules/react-style-singleton/dist/es2015/index.js"); - var _aggresiveCapture = __webpack_require__(/*! ./aggresiveCapture */ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js"); - var _handleScroll = __webpack_require__(/*! ./handleScroll */ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js"); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - var getTouchXY = function (event) { - return 'changedTouches' in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; - }; - exports.getTouchXY = getTouchXY; - var getDeltaXY = function (event) { - return [event.deltaX, event.deltaY]; - }; - exports.getDeltaXY = getDeltaXY; - var extractRef = function (ref) { - return ref && 'current' in ref ? ref.current : ref; - }; - var deltaCompare = function (x, y) { - return x[0] === y[0] && x[1] === y[1]; - }; - var generateStyle = function (id) { - return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); - }; - var idCounter = 0; - var lockStack = []; - function RemoveScrollSideCar(props) { - var shouldPreventQueue = React.useRef([]); - var touchStartRef = React.useRef([0, 0]); - var activeAxis = React.useRef(); - var id = React.useState(idCounter++)[0]; - var Style = React.useState(function () { - return (0, _reactStyleSingleton.styleSingleton)(); - })[0]; - var lastProps = React.useRef(props); - React.useEffect(function () { - lastProps.current = props; - }, [props]); - React.useEffect(function () { - if (props.inert) { - document.body.classList.add("block-interactivity-".concat(id)); - var allow_1 = (0, _tslib.__spreadArray)([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); - allow_1.forEach(function (el) { - return el.classList.add("allow-interactivity-".concat(id)); - }); - return function () { - document.body.classList.remove("block-interactivity-".concat(id)); - allow_1.forEach(function (el) { - return el.classList.remove("allow-interactivity-".concat(id)); - }); - }; - } - return; - }, [props.inert, props.lockRef.current, props.shards]); - var shouldCancelEvent = React.useCallback(function (event, parent) { - if ('touches' in event && event.touches.length === 2) { - return !lastProps.current.allowPinchZoom; - } - var touch = getTouchXY(event); - var touchStart = touchStartRef.current; - var deltaX = 'deltaX' in event ? event.deltaX : touchStart[0] - touch[0]; - var deltaY = 'deltaY' in event ? event.deltaY : touchStart[1] - touch[1]; - var currentAxis; - var target = event.target; - var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'h' : 'v'; - // allow horizontal touch move on Range inputs. They will not cause any scroll - if ('touches' in event && moveDirection === 'h' && target.type === 'range') { - return false; - } - var canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); - if (!canBeScrolledInMainDirection) { - return true; - } - if (canBeScrolledInMainDirection) { - currentAxis = moveDirection; - } else { - currentAxis = moveDirection === 'v' ? 'h' : 'v'; - canBeScrolledInMainDirection = (0, _handleScroll.locationCouldBeScrolled)(moveDirection, target); - // other axis might be not scrollable - } - if (!canBeScrolledInMainDirection) { - return false; - } - if (!activeAxis.current && 'changedTouches' in event && (deltaX || deltaY)) { - activeAxis.current = currentAxis; - } - if (!currentAxis) { - return true; - } - var cancelingAxis = activeAxis.current || currentAxis; - return (0, _handleScroll.handleScroll)(cancelingAxis, parent, event, cancelingAxis === 'h' ? deltaX : deltaY, true); - }, []); - var shouldPrevent = React.useCallback(function (_event) { - var event = _event; - if (!lockStack.length || lockStack[lockStack.length - 1] !== Style) { - // not the last active - return; - } - var delta = 'deltaY' in event ? getDeltaXY(event) : getTouchXY(event); - var sourceEvent = shouldPreventQueue.current.filter(function (e) { - return e.name === event.type && e.target === event.target && deltaCompare(e.delta, delta); - })[0]; - // self event, and should be canceled - if (sourceEvent && sourceEvent.should) { - if (event.cancelable) { - event.preventDefault(); - } - return; - } - // outside or shard event - if (!sourceEvent) { - var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function (node) { - return node.contains(event.target); - }); - var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; - if (shouldStop) { - if (event.cancelable) { - event.preventDefault(); - } - } - } - }, []); - var shouldCancel = React.useCallback(function (name, delta, target, should) { - var event = { - name: name, - delta: delta, - target: target, - should: should - }; - shouldPreventQueue.current.push(event); - setTimeout(function () { - shouldPreventQueue.current = shouldPreventQueue.current.filter(function (e) { - return e !== event; - }); - }, 1); - }, []); - var scrollTouchStart = React.useCallback(function (event) { - touchStartRef.current = getTouchXY(event); - activeAxis.current = undefined; - }, []); - var scrollWheel = React.useCallback(function (event) { - shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); - }, []); - var scrollTouchMove = React.useCallback(function (event) { - shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); - }, []); - React.useEffect(function () { - lockStack.push(Style); - props.setCallbacks({ - onScrollCapture: scrollWheel, - onWheelCapture: scrollWheel, - onTouchMoveCapture: scrollTouchMove - }); - document.addEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); - document.addEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); - document.addEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); - return function () { - lockStack = lockStack.filter(function (inst) { - return inst !== Style; - }); - document.removeEventListener('wheel', shouldPrevent, _aggresiveCapture.nonPassive); - document.removeEventListener('touchmove', shouldPrevent, _aggresiveCapture.nonPassive); - document.removeEventListener('touchstart', scrollTouchStart, _aggresiveCapture.nonPassive); - }; - }, []); - var removeScrollBar = props.removeScrollBar, - inert = props.inert; - return /*#__PURE__*/React.createElement(React.Fragment, null, inert ? /*#__PURE__*/React.createElement(Style, { - styles: generateStyle(id) - }) : null, removeScrollBar ? /*#__PURE__*/React.createElement(_reactRemoveScrollBar.RemoveScrollBar, { - gapMode: "margin" - }) : null); - } - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/UI.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/UI.js ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.RemoveScroll = void 0; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _constants = __webpack_require__(/*! react-remove-scroll-bar/constants */ "../../../node_modules/react-remove-scroll-bar/dist/es2015/constants.js"); - var _useCallbackRef = __webpack_require__(/*! use-callback-ref */ "../../../node_modules/use-callback-ref/dist/es2015/index.js"); - var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - var nothing = function () { - return; - }; - /** - * Removes scrollbar from the page and contain the scroll within the Lock - */ - var RemoveScroll = exports.RemoveScroll = /*#__PURE__*/React.forwardRef(function (props, parentRef) { - var ref = React.useRef(null); - var _a = React.useState({ - onScrollCapture: nothing, - onWheelCapture: nothing, - onTouchMoveCapture: nothing - }), - callbacks = _a[0], - setCallbacks = _a[1]; - var forwardProps = props.forwardProps, - children = props.children, - className = props.className, - removeScrollBar = props.removeScrollBar, - enabled = props.enabled, - shards = props.shards, - sideCar = props.sideCar, - noIsolation = props.noIsolation, - inert = props.inert, - allowPinchZoom = props.allowPinchZoom, - _b = props.as, - Container = _b === void 0 ? 'div' : _b, - rest = (0, _tslib.__rest)(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]); - var SideCar = sideCar; - var containerRef = (0, _useCallbackRef.useMergeRefs)([ref, parentRef]); - var containerProps = (0, _tslib.__assign)((0, _tslib.__assign)({}, rest), callbacks); - return /*#__PURE__*/React.createElement(React.Fragment, null, enabled && ( /*#__PURE__*/React.createElement(SideCar, { - sideCar: _medium.effectCar, - removeScrollBar: removeScrollBar, - shards: shards, - noIsolation: noIsolation, - inert: inert, - setCallbacks: setCallbacks, - allowPinchZoom: !!allowPinchZoom, - lockRef: ref - })), forwardProps ? ( /*#__PURE__*/React.cloneElement(React.Children.only(children), (0, _tslib.__assign)((0, _tslib.__assign)({}, containerProps), { - ref: containerRef - }))) : ( /*#__PURE__*/React.createElement(Container, (0, _tslib.__assign)({}, containerProps, { - className: className, - ref: containerRef - }), children))); - }); - RemoveScroll.defaultProps = { - enabled: true, - removeScrollBar: true, - inert: false - }; - RemoveScroll.classNames = { - fullWidth: _constants.fullWidthClassName, - zeroRight: _constants.zeroRightClassName - }; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js": - /*!*********************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js ***! - \*********************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.nonPassive = void 0; - var passiveSupported = false; - if (typeof window !== 'undefined') { - try { - var options = Object.defineProperty({}, 'passive', { - get: function () { - passiveSupported = true; - return true; - } - }); - // @ts-ignore - window.addEventListener('test', options, options); - // @ts-ignore - window.removeEventListener('test', options, options); - } catch (err) { - passiveSupported = false; - } - } - var nonPassive = exports.nonPassive = passiveSupported ? { - passive: false - } : false; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/handleScroll.js ***! - \*****************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.locationCouldBeScrolled = exports.handleScroll = void 0; - var alwaysContainsScroll = function (node) { - // textarea will always _contain_ scroll inside self. It only can be hidden - return node.tagName === 'TEXTAREA'; - }; - var elementCanBeScrolled = function (node, overflow) { - var styles = window.getComputedStyle(node); - return ( - // not-not-scrollable - styles[overflow] !== 'hidden' && - // contains scroll inside self - !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === 'visible') - ); - }; - var elementCouldBeVScrolled = function (node) { - return elementCanBeScrolled(node, 'overflowY'); - }; - var elementCouldBeHScrolled = function (node) { - return elementCanBeScrolled(node, 'overflowX'); - }; - var locationCouldBeScrolled = function (axis, node) { - var current = node; - do { - // Skip over shadow root - if (typeof ShadowRoot !== 'undefined' && current instanceof ShadowRoot) { - current = current.host; - } - var isScrollable = elementCouldBeScrolled(axis, current); - if (isScrollable) { - var _a = getScrollVariables(axis, current), - s = _a[1], - d = _a[2]; - if (s > d) { - return true; - } - } - current = current.parentNode; - } while (current && current !== document.body); - return false; - }; - exports.locationCouldBeScrolled = locationCouldBeScrolled; - var getVScrollVariables = function (_a) { - var scrollTop = _a.scrollTop, - scrollHeight = _a.scrollHeight, - clientHeight = _a.clientHeight; - return [scrollTop, scrollHeight, clientHeight]; - }; - var getHScrollVariables = function (_a) { - var scrollLeft = _a.scrollLeft, - scrollWidth = _a.scrollWidth, - clientWidth = _a.clientWidth; - return [scrollLeft, scrollWidth, clientWidth]; - }; - var elementCouldBeScrolled = function (axis, node) { - return axis === 'v' ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); - }; - var getScrollVariables = function (axis, node) { - return axis === 'v' ? getVScrollVariables(node) : getHScrollVariables(node); - }; - var getDirectionFactor = function (axis, direction) { - /** - * If the element's direction is rtl (right-to-left), then scrollLeft is 0 when the scrollbar is at its rightmost position, - * and then increasingly negative as you scroll towards the end of the content. - * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft - */ - return axis === 'h' && direction === 'rtl' ? -1 : 1; - }; - var handleScroll = function (axis, endTarget, event, sourceDelta, noOverscroll) { - var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); - var delta = directionFactor * sourceDelta; - // find scrollable target - var target = event.target; - var targetInLock = endTarget.contains(target); - var shouldCancelScroll = false; - var isDeltaPositive = delta > 0; - var availableScroll = 0; - var availableScrollTop = 0; - do { - var _a = getScrollVariables(axis, target), - position = _a[0], - scroll_1 = _a[1], - capacity = _a[2]; - var elementScroll = scroll_1 - capacity - directionFactor * position; - if (position || elementScroll) { - if (elementCouldBeScrolled(axis, target)) { - availableScroll += elementScroll; - availableScrollTop += position; - } - } - target = target.parentNode; - } while ( - // portaled content - !targetInLock && target !== document.body || - // self content - targetInLock && (endTarget.contains(target) || endTarget === target)); - if (isDeltaPositive && (noOverscroll && availableScroll === 0 || !noOverscroll && delta > availableScroll)) { - shouldCancelScroll = true; - } else if (!isDeltaPositive && (noOverscroll && availableScrollTop === 0 || !noOverscroll && -delta > availableScrollTop)) { - shouldCancelScroll = true; - } - return shouldCancelScroll; - }; - exports.handleScroll = handleScroll; - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/index.js": - /*!**********************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/index.js ***! - \**********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "RemoveScroll", ({ - enumerable: true, - get: function () { - return _Combination.default; - } - })); - var _Combination = _interopRequireDefault(__webpack_require__(/*! ./Combination */ "../../../node_modules/react-remove-scroll/dist/es2015/Combination.js")); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/medium.js ***! - \***********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.effectCar = void 0; - var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); - var effectCar = exports.effectCar = (0, _useSidecar.createSidecarMedium)(); - - /***/ }), - - /***/ "../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/react-remove-scroll/dist/es2015/sidecar.js ***! - \************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports["default"] = void 0; - var _useSidecar = __webpack_require__(/*! use-sidecar */ "../../../node_modules/use-sidecar/dist/es2015/index.js"); - var _SideEffect = __webpack_require__(/*! ./SideEffect */ "../../../node_modules/react-remove-scroll/dist/es2015/SideEffect.js"); - var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/react-remove-scroll/dist/es2015/medium.js"); - var _default = exports["default"] = (0, _useSidecar.exportSidecar)(_medium.effectCar, _SideEffect.RemoveScrollSideCar); - - /***/ }), - - /***/ "../../../node_modules/react-style-singleton/dist/es2015/component.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/react-style-singleton/dist/es2015/component.js ***! - \****************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.styleSingleton = void 0; - var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); - /** - * create a Component to add styles on demand - * - styles are added when first instance is mounted - * - styles are removed when the last instance is unmounted - * - changing styles in runtime does nothing unless dynamic is set. But with multiple components that can lead to the undefined behavior - */ - var styleSingleton = function () { - var useStyle = (0, _hook.styleHookSingleton)(); - var Sheet = function (_a) { - var styles = _a.styles, - dynamic = _a.dynamic; - useStyle(styles, dynamic); - return null; - }; - return Sheet; - }; - exports.styleSingleton = styleSingleton; - - /***/ }), - - /***/ "../../../node_modules/react-style-singleton/dist/es2015/hook.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/react-style-singleton/dist/es2015/hook.js ***! - \***********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.styleHookSingleton = void 0; - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - /** - * creates a hook to control style singleton - * @see {@link styleSingleton} for a safer component version - * @example - * ```tsx - * const useStyle = styleHookSingleton(); - * /// - * useStyle('body { overflow: hidden}'); - */ - var styleHookSingleton = function () { - var sheet = (0, _singleton.stylesheetSingleton)(); - return function (styles, isDynamic) { - React.useEffect(function () { - sheet.add(styles); - return function () { - sheet.remove(); - }; - }, [styles && isDynamic]); - }; - }; - exports.styleHookSingleton = styleHookSingleton; - - /***/ }), - - /***/ "../../../node_modules/react-style-singleton/dist/es2015/index.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/react-style-singleton/dist/es2015/index.js ***! - \************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "styleHookSingleton", ({ - enumerable: true, - get: function () { - return _hook.styleHookSingleton; - } - })); - Object.defineProperty(exports, "styleSingleton", ({ - enumerable: true, - get: function () { - return _component.styleSingleton; - } - })); - Object.defineProperty(exports, "stylesheetSingleton", ({ - enumerable: true, - get: function () { - return _singleton.stylesheetSingleton; - } - })); - var _component = __webpack_require__(/*! ./component */ "../../../node_modules/react-style-singleton/dist/es2015/component.js"); - var _singleton = __webpack_require__(/*! ./singleton */ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js"); - var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/react-style-singleton/dist/es2015/hook.js"); - - /***/ }), - - /***/ "../../../node_modules/react-style-singleton/dist/es2015/singleton.js": - /*!****************************************************************************!*\ - !*** ../../../node_modules/react-style-singleton/dist/es2015/singleton.js ***! - \****************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.stylesheetSingleton = void 0; - var _getNonce = __webpack_require__(/*! get-nonce */ "../../../node_modules/get-nonce/dist/es2015/index.js"); - function makeStyleTag() { - if (!document) return null; - var tag = document.createElement('style'); - tag.type = 'text/css'; - var nonce = (0, _getNonce.getNonce)(); - if (nonce) { - tag.setAttribute('nonce', nonce); - } - return tag; - } - function injectStyles(tag, css) { - // @ts-ignore - if (tag.styleSheet) { - // @ts-ignore - tag.styleSheet.cssText = css; - } else { - tag.appendChild(document.createTextNode(css)); - } - } - function insertStyleTag(tag) { - var head = document.head || document.getElementsByTagName('head')[0]; - head.appendChild(tag); - } - var stylesheetSingleton = function () { - var counter = 0; - var stylesheet = null; - return { - add: function (style) { - if (counter == 0) { - if (stylesheet = makeStyleTag()) { - injectStyles(stylesheet, style); - insertStyleTag(stylesheet); - } - } - counter++; - }, - remove: function () { - counter--; - if (!counter && stylesheet) { - stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); - stylesheet = null; - } - } - }; - }; - exports.stylesheetSingleton = stylesheetSingleton; - - /***/ }), - - /***/ "../../../node_modules/react/cjs/react-jsx-runtime.development.js": - /*!************************************************************************!*\ - !*** ../../../node_modules/react/cjs/react-jsx-runtime.development.js ***! - \************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - /** - * @license React - * react-jsx-runtime.development.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - - - - if (true) { - (function () { - 'use strict'; - - var React = __webpack_require__(/*! react */ "react"); - - // ATTENTION - // When adding new symbols to this file, - // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' - // The Symbol used to tag the ReactElement-like types. - var REACT_ELEMENT_TYPE = Symbol.for('react.element'); - var REACT_PORTAL_TYPE = Symbol.for('react.portal'); - var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); - var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); - var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); - var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); - var REACT_CONTEXT_TYPE = Symbol.for('react.context'); - var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); - var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); - var REACT_MEMO_TYPE = Symbol.for('react.memo'); - var REACT_LAZY_TYPE = Symbol.for('react.lazy'); - var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = '@@iterator'; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - return null; - } - var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - function error(format) { - { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning('error', format, args); - } - } - } - function printWarning(level, format, args) { - // When changing this logic, you might want to also - // update consoleWithStackDev.www.js as well. - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - if (stack !== '') { - format += '%s'; - args = args.concat([stack]); - } // eslint-disable-next-line react-internal/safe-string-coercion - - var argsWithFormat = args.map(function (item) { - return String(item); - }); // Careful: RN currently depends on this prefix - - argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - // eslint-disable-next-line react-internal/no-production-logging - - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - - // ----------------------------------------------------------------------------- - - var enableScopeAPI = false; // Experimental Create Event Handle API. - var enableCacheElement = false; - var enableTransitionTracing = false; // No known bugs, but needs performance testing - - var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber - // stuff. Intended to enable React core members to more easily debug scheduling - // issues in DEV builds. - - var enableDebugTracing = false; // Track which Fiber(s) schedule render work. - - var REACT_MODULE_REFERENCE; - { - REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); - } - function isValidElementType(type) { - if (typeof type === 'string' || typeof type === 'function') { - return true; - } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). - - if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { - return true; - } - if (typeof type === 'object' && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || - // This needs to include all possible module reference object - // types supported by any Flight configuration anywhere since - // we don't know which Flight build this will end up being used - // with. - type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { - return true; - } - } - return false; - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ''; - return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; - } // Keep in sync with react-reconciler/getComponentNameFromFiber - - function getContextName(type) { - return type.displayName || 'Context'; - } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. - - function getComponentNameFromType(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null; - } - { - if (typeof type.tag === 'number') { - error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); - } - } - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - if (typeof type === 'string') { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment'; - case REACT_PORTAL_TYPE: - return 'Portal'; - case REACT_PROFILER_TYPE: - return 'Profiler'; - case REACT_STRICT_MODE_TYPE: - return 'StrictMode'; - case REACT_SUSPENSE_TYPE: - return 'Suspense'; - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList'; - } - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + '.Consumer'; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + '.Provider'; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef'); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || 'Memo'; - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - - // eslint-disable-next-line no-fallthrough - } - } - return null; - } - var assign = Object.assign; - - // Helpers to patch console.logs to avoid logging during side-effect free - // replaying on render function. This currently only patches the object - // lazily which won't cover if the log function was extracted eagerly. - // We could also eagerly patch the method. - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() {} - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 - - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - /* eslint-enable react-internal/no-production-logging */ - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - /* eslint-disable react-internal/no-production-logging */ - var props = { - configurable: true, - enumerable: true, - writable: true - }; // $FlowFixMe Flow thinks console is immutable. - - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - /* eslint-enable react-internal/no-production-logging */ - } - if (disabledDepth < 0) { - error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - // Extract the VM specific prefix used by each line. - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ''; - } - } // We use the prefix to ensure our stacks line up with native stack frames. - - return '\n' + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - // If something asked for a stack inside a fake render, it should get ignored. - if (!fn || reentry) { - return ''; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== undefined) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. - - Error.prepareStackTrace = undefined; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function - // for warnings. - - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - // This should throw. - if (construct) { - // Something should be setting the props in the constructor. - var Fake = function () { - throw Error(); - }; // $FlowFixMe - - Object.defineProperty(Fake.prototype, 'props', { - set: function () { - // We use a throwing setter instead of frozen or non-writable props - // because that won't throw in a non-strict mode function. - throw Error(); - } - }); - if (typeof Reflect === 'object' && Reflect.construct) { - // We construct a different control for this case to include any extra - // frames added by the construct call. - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - // This is inlined manually because closure doesn't do it for us. - if (sample && control && typeof sample.stack === 'string') { - // This extracts the first frame from the sample that isn't also in the control. - // Skipping one frame that we assume is the frame that calls the two. - var sampleLines = sample.stack.split('\n'); - var controlLines = control.stack.split('\n'); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - // We expect at least one stack frame to be shared. - // Typically this will be the root most one. However, stack frames may be - // cut off due to maximum stack limits. In this case, one maybe cut off - // earlier than the other. We assume that the sample is longer or the same - // and there for cut off earlier. So we should find the root most frame in - // the sample somewhere in the control. - c--; - } - for (; s >= 1 && c >= 0; s--, c--) { - // Next we find the first one that isn't the same which should be the - // frame that called our sample function and the control. - if (sampleLines[s] !== controlLines[c]) { - // In V8, the first line is describing the message but other VMs don't. - // If we're about to return the first line, and the control is also on the same - // line, that's a pretty good indicator that our sample threw at same line as - // the control. I.e. before we entered the sample frame. So we ignore this result. - // This can happen if you passed a class to function component, or non-function. - if (s !== 1 || c !== 1) { - do { - s--; - c--; // We may still have similar intermediate frames from the construct call. - // The next one that isn't the same should be our match though. - - if (c < 0 || sampleLines[s] !== controlLines[c]) { - // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. - var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. - - if (fn.displayName && _frame.includes('')) { - _frame = _frame.replace('', fn.displayName); - } - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, _frame); - } - } // Return the line we found. - - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } // Fallback to just using the name if we couldn't make it throw. - - var name = fn ? fn.displayName || fn.name : ''; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; - { - if (typeof fn === 'function') { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ''; - } - if (typeof type === 'function') { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === 'string') { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame('Suspense'); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame('SuspenseList'); - } - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - // Memo may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - // Lazy may contain any component type so we recursively resolve it. - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} - } - } - } - return ''; - } - var hasOwnProperty = Object.prototype.hasOwnProperty; - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - // $FlowFixMe This is okay but Flow doesn't know it. - var has = Function.call.bind(hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to - // fail the render phase where it didn't fail before. So we log it. - // After these have been cleaned up, we'll let them throw. - - try { - // This is intentionally an invariant that gets caught. It's the same - // behavior as without this statement except with a better message. - if (typeof typeSpecs[typeSpecName] !== 'function') { - // eslint-disable-next-line react-internal/prod-error-codes - var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); - err.name = 'Invariant Violation'; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - // Only monitor this failure once because there tends to be a lot of the - // same error. - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error('Failed %s type: %s', location, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare - - function isArray(a) { - return isArrayImpl(a); - } - - /* - * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol - * and Temporal.* types. See https://github.com/facebook/react/pull/22064. - * - * The functions in this module will throw an easier-to-understand, - * easier-to-debug exception with a clear errors message message explaining the - * problem. (Instead of a confusing exception thrown inside the implementation - * of the `value` object). - */ - // $FlowFixMe only called in DEV, so void return is not possible. - function typeName(value) { - { - // toStringTag is needed for namespaced types like Temporal.Instant - var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; - return type; - } - } // $FlowFixMe only called in DEV, so void return is not possible. - - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - function testStringCoercion(value) { - // If you ended up here by following an exception call stack, here's what's - // happened: you supplied an object or symbol value to React (as a prop, key, - // DOM attribute, CSS property, string ref, etc.) and when React tried to - // coerce it to a string using `'' + value`, an exception was thrown. - // - // The most common types that will cause this exception are `Symbol` instances - // and Temporal objects like `Temporal.Instant`. But any object that has a - // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this - // exception. (Library authors do this to prevent users from using built-in - // numeric operators like `+` or comparison operators like `>=` because custom - // methods are needed to perform accurate arithmetic or comparison.) - // - // To fix the problem, coerce this object or symbol value to a string before - // passing it to React. The most reliable way is usually `String(value)`. - // - // To find which value is throwing, check the browser or debugger console. - // Before this exception was thrown, there should be `console.error` output - // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the - // problem and how that type was used: key, atrribute, input value prop, etc. - // In most cases, this console output also shows the component and its - // ancestor components where the exception happened. - // - // eslint-disable-next-line react-internal/safe-string-coercion - return '' + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); - return testStringCoercion(value); // throw (to help callers find troubleshooting comments) - } - } - } - var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown; - var specialPropRefWarningShown; - var didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config) { - { - if (hasOwnProperty.call(config, 'ref')) { - var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.ref !== undefined; - } - function hasValidKey(config) { - { - if (hasOwnProperty.call(config, 'key')) { - var getter = Object.getOwnPropertyDescriptor(config, 'key').get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.key !== undefined; - } - function warnIfStringRefCannotBeAutoConverted(config, self) { - { - if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { - var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - function defineKeyPropWarningGetter(props, displayName) { - { - var warnAboutAccessingKey = function () { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, 'key', { - get: warnAboutAccessingKey, - configurable: true - }); - } - } - function defineRefPropWarningGetter(props, displayName) { - { - var warnAboutAccessingRef = function () { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, 'ref', { - get: warnAboutAccessingRef, - configurable: true - }); - } - } - /** - * Factory method to create a new React element. This no longer adheres to - * the class pattern, so do not use new to call it. Also, instanceof check - * will not work. Instead test $$typeof field against Symbol.for('react.element') to check - * if something is a React Element. - * - * @param {*} type - * @param {*} props - * @param {*} key - * @param {string|object} ref - * @param {*} owner - * @param {*} self A *temporary* helper to detect places where `this` is - * different from the `owner` when React.createElement is called, so that we - * can warn. We want to get rid of owner and replace string `ref`s with arrow - * functions, and as long as `this` and owner are the same, there will be no - * change in behavior. - * @param {*} source An annotation object (added by a transpiler or otherwise) - * indicating filename, line number, and/or other information. - * @internal - */ - - var ReactElement = function (type, key, ref, self, source, owner, props) { - var element = { - // This tag allows us to uniquely identify this as a React Element - $$typeof: REACT_ELEMENT_TYPE, - // Built-in properties that belong on the element - type: type, - key: key, - ref: ref, - props: props, - // Record the component responsible for creating this element. - _owner: owner - }; - { - // The validation flag is currently mutative. We put it on - // an external backing store so that we can freeze the whole object. - // This can be replaced with a WeakMap once they are implemented in - // commonly used development environments. - element._store = {}; // To make comparing ReactElements easier for testing purposes, we make - // the validation flag non-enumerable (where possible, which should - // include every environment we run tests in), so the test framework - // ignores it. - - Object.defineProperty(element._store, 'validated', { - configurable: false, - enumerable: false, - writable: true, - value: false - }); // self and source are DEV only properties. - - Object.defineProperty(element, '_self', { - configurable: false, - enumerable: false, - writable: false, - value: self - }); // Two elements created in two different places should be considered - // equal for testing purposes and therefore we hide it from enumeration. - - Object.defineProperty(element, '_source', { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - /** - * https://github.com/reactjs/rfcs/pull/107 - * @param {*} type - * @param {object} props - * @param {string} key - */ - - function jsxDEV(type, config, maybeKey, source, self) { - { - var propName; // Reserved names are extracted - - var props = {}; - var key = null; - var ref = null; // Currently, key can be spread in as a prop. This causes a potential - // issue if key is also explicitly declared (ie.
    - // or
    ). We want to deprecate key spread, - // but as an intermediary step, we will use jsxDEV for everything except - //
    , because we aren't currently able to tell if - // key is explicitly declared to be undefined or not. - - if (maybeKey !== undefined) { - { - checkKeyStringCoercion(maybeKey); - } - key = '' + maybeKey; - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = '' + config.key; - } - if (hasValidRef(config)) { - ref = config.ref; - warnIfStringRefCannotBeAutoConverted(config, self); - } // Remaining properties are added to a new props object - - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config[propName]; - } - } // Resolve default props - - if (type && type.defaultProps) { - var defaultProps = type.defaultProps; - for (propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - } - if (key || ref) { - var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); - } - } - var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - /** - * Verifies the object is a ReactElement. - * See https://reactjs.org/docs/react-api.html#isvalidelement - * @param {?object} object - * @return {boolean} True if `object` is a ReactElement. - * @final - */ - - function isValidElement(object) { - { - return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - } - function getDeclarationErrorAddendum() { - { - if (ReactCurrentOwner$1.current) { - var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); - if (name) { - return '\n\nCheck the render method of `' + name + '`.'; - } - } - return ''; - } - } - function getSourceInfoErrorAddendum(source) { - { - if (source !== undefined) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ''); - var lineNumber = source.lineNumber; - return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; - } - return ''; - } - } - /** - * Warn if there's no key explicitly set on dynamic arrays of children or - * object keys are not valid. This allows us to keep track of children between - * updates. - */ - - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } - } - return info; - } - } - /** - * Warn if the element doesn't have an explicit key assigned to it. - * This element is in an array. The array could grow and shrink or be - * reordered. All children that haven't already been validated are required to - * have a "key" property assigned to it. Error statuses are cached so a warning - * will only be shown once. - * - * @internal - * @param {ReactElement} element Element that requires a key. - * @param {*} parentType element's parent's type. - */ - - function validateExplicitKey(element, parentType) { - { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a - // property, it may be the creator of the child that's responsible for - // assigning it a key. - - var childOwner = ''; - if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { - // Give the component that originally created this child. - childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; - } - setCurrentlyValidatingElement$1(element); - error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - /** - * Ensure that every element either is passed in a static location, in an - * array with an explicit keys property defined, or in an object literal - * with valid key property. - * - * @internal - * @param {ReactNode} node Statically passed child of any type. - * @param {*} parentType node's parent's type. - */ - - function validateChildKeys(node, parentType) { - { - if (typeof node !== 'object') { - return; - } - if (isArray(node)) { - for (var i = 0; i < node.length; i++) { - var child = node[i]; - if (isValidElement(child)) { - validateExplicitKey(child, parentType); - } - } - } else if (isValidElement(node)) { - // This element was passed in a valid location. - if (node._store) { - node._store.validated = true; - } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === 'function') { - // Entry iterators used to provide implicit keys, - // but now we print a separate warning for them later. - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType); - } - } - } - } - } - } - } - /** - * Given an element, validate that its props follow the propTypes definition, - * provided by the type. - * - * @param {ReactElement} element - */ - - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === undefined || typeof type === 'string') { - return; - } - var propTypes; - if (typeof type === 'function') { - propTypes = type.propTypes; - } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || - // Note: Memo only checks outer props here. - // Inner props are checked in the reconciler. - type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - // Intentionally inside to avoid triggering lazy initializers: - var name = getComponentNameFromType(type); - checkPropTypes(propTypes, element.props, 'prop', name, element); - } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: - - var _name = getComponentNameFromType(type); - error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); - } - if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { - error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); - } - } - } - /** - * Given a fragment, validate that it can only be provided with fragment props - * @param {ReactElement} fragment - */ - - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key !== 'children' && key !== 'key') { - setCurrentlyValidatingElement$1(fragment); - error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error('Invalid attribute `ref` supplied to `React.Fragment`.'); - setCurrentlyValidatingElement$1(null); - } - } - } - function jsxWithValidation(type, props, key, isStaticChildren, source, self) { - { - var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to - // succeed and there will likely be errors in render. - - if (!validType) { - var info = ''; - if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { - info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendum(source); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = 'null'; - } else if (isArray(type)) { - typeString = 'array'; - } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; - info = ' Did you accidentally export a JSX literal instead of a component?'; - } else { - typeString = typeof type; - } - error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); - } - var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. - // TODO: Drop this when these are no longer allowed as the type argument. - - if (element == null) { - return element; - } // Skip key warning if the type isn't valid since our key validation logic - // doesn't expect a non-string/function type and can throw confusing errors. - // We don't want exception behavior to differ between dev and prod. - // (Rendering will throw with a helpful message and as soon as the type is - // fixed, the key warnings will appear.) - - if (validType) { - var children = props.children; - if (children !== undefined) { - if (isStaticChildren) { - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - validateChildKeys(children[i], type); - } - if (Object.freeze) { - Object.freeze(children); - } - } else { - error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); - } - } else { - validateChildKeys(children, type); - } - } - } - if (type === REACT_FRAGMENT_TYPE) { - validateFragmentProps(element); - } else { - validatePropTypes(element); - } - return element; - } - } // These two functions exist to still get child warnings in dev - // even with the prod transform. This means that jsxDEV is purely - // opt-in behavior for better messages but that we won't stop - // giving you warnings if you use production apis. - - function jsxWithValidationStatic(type, props, key) { - { - return jsxWithValidation(type, props, key, true); - } - } - function jsxWithValidationDynamic(type, props, key) { - { - return jsxWithValidation(type, props, key, false); - } - } - var jsx = jsxWithValidationDynamic; // we may want to special case jsxs internally to take advantage of static children. - // for now we can ship identical prod functions - - var jsxs = jsxWithValidationStatic; - exports.Fragment = REACT_FRAGMENT_TYPE; - exports.jsx = jsx; - exports.jsxs = jsxs; - })(); - } - - /***/ }), - - /***/ "../../../node_modules/react/jsx-runtime.js": - /*!**************************************************!*\ - !*** ../../../node_modules/react/jsx-runtime.js ***! - \**************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - if (false) {} else { - module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ "../../../node_modules/react/cjs/react-jsx-runtime.development.js"); - } - - /***/ }), - - /***/ "../../../node_modules/set-value/index.js": - /*!************************************************!*\ - !*** ../../../node_modules/set-value/index.js ***! - \************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - /*! - * set-value - * - * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert). - * Released under the MIT License. - */ - - - - const { - deleteProperty - } = Reflect; - const isPrimitive = __webpack_require__(/*! is-primitive */ "../../../node_modules/is-primitive/index.js"); - const isPlainObject = __webpack_require__(/*! is-plain-object */ "../../../node_modules/is-plain-object/index.js"); - const isObject = value => { - return typeof value === 'object' && value !== null || typeof value === 'function'; - }; - const isUnsafeKey = key => { - return key === '__proto__' || key === 'constructor' || key === 'prototype'; - }; - const validateKey = key => { - if (!isPrimitive(key)) { - throw new TypeError('Object keys must be strings or symbols'); - } - if (isUnsafeKey(key)) { - throw new Error(`Cannot set unsafe key: "${key}"`); - } - }; - const toStringKey = input => { - return Array.isArray(input) ? input.flat().map(String).join(',') : input; - }; - const createMemoKey = (input, options) => { - if (typeof input !== 'string' || !options) return input; - let key = input + ';'; - if (options.arrays !== undefined) key += `arrays=${options.arrays};`; - if (options.separator !== undefined) key += `separator=${options.separator};`; - if (options.split !== undefined) key += `split=${options.split};`; - if (options.merge !== undefined) key += `merge=${options.merge};`; - if (options.preservePaths !== undefined) key += `preservePaths=${options.preservePaths};`; - return key; - }; - const memoize = (input, options, fn) => { - const key = toStringKey(options ? createMemoKey(input, options) : input); - validateKey(key); - const value = setValue.cache.get(key) || fn(); - setValue.cache.set(key, value); - return value; - }; - const splitString = (input, options = {}) => { - const sep = options.separator || '.'; - const preserve = sep === '/' ? false : options.preservePaths; - if (typeof input === 'string' && preserve !== false && /\//.test(input)) { - return [input]; - } - const parts = []; - let part = ''; - const push = part => { - let number; - if (part.trim() !== '' && Number.isInteger(number = Number(part))) { - parts.push(number); - } else { - parts.push(part); - } - }; - for (let i = 0; i < input.length; i++) { - const value = input[i]; - if (value === '\\') { - part += input[++i]; - continue; - } - if (value === sep) { - push(part); - part = ''; - continue; - } - part += value; - } - if (part) { - push(part); - } - return parts; - }; - const split = (input, options) => { - if (options && typeof options.split === 'function') return options.split(input); - if (typeof input === 'symbol') return [input]; - if (Array.isArray(input)) return input; - return memoize(input, options, () => splitString(input, options)); - }; - const assignProp = (obj, prop, value, options) => { - validateKey(prop); - - // Delete property when "value" is undefined - if (value === undefined) { - deleteProperty(obj, prop); - } else if (options && options.merge) { - const merge = options.merge === 'function' ? options.merge : Object.assign; - - // Only merge plain objects - if (merge && isPlainObject(obj[prop]) && isPlainObject(value)) { - obj[prop] = merge(obj[prop], value); - } else { - obj[prop] = value; - } - } else { - obj[prop] = value; - } - return obj; - }; - const setValue = (target, path, value, options) => { - if (!path || !isObject(target)) return target; - const keys = split(path, options); - let obj = target; - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const next = keys[i + 1]; - validateKey(key); - if (next === undefined) { - assignProp(obj, key, value, options); - break; - } - if (typeof next === 'number' && !Array.isArray(obj[key])) { - obj = obj[key] = []; - continue; - } - if (!isObject(obj[key])) { - obj[key] = {}; - } - obj = obj[key]; - } - return target; - }; - setValue.split = split; - setValue.cache = new Map(); - setValue.clear = () => { - setValue.cache = new Map(); - }; - module.exports = setValue; - - /***/ }), - - /***/ "../../../node_modules/style-value-types/dist/valueTypes.cjs.js": - /*!**********************************************************************!*\ - !*** ../../../node_modules/style-value-types/dist/valueTypes.cjs.js ***! - \**********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - const clamp = (min, max) => v => Math.max(Math.min(v, max), min); - const sanitize = v => v % 1 ? Number(v.toFixed(5)) : v; - const floatRegex = /(-)?([\d]*\.?[\d])+/g; - const colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi; - const singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i; - function isString(v) { - return typeof v === 'string'; - } - const number = { - test: v => typeof v === 'number', - parse: parseFloat, - transform: v => v - }; - const alpha = Object.assign(Object.assign({}, number), { - transform: clamp(0, 1) - }); - const scale = Object.assign(Object.assign({}, number), { - default: 1 - }); - const createUnitType = unit => ({ - test: v => isString(v) && v.endsWith(unit) && v.split(' ').length === 1, - parse: parseFloat, - transform: v => `${v}${unit}` - }); - const degrees = createUnitType('deg'); - const percent = createUnitType('%'); - const px = createUnitType('px'); - const vh = createUnitType('vh'); - const vw = createUnitType('vw'); - const progressPercentage = Object.assign(Object.assign({}, percent), { - parse: v => percent.parse(v) / 100, - transform: v => percent.transform(v * 100) - }); - const isColorString = (type, testProp) => v => { - return Boolean(isString(v) && singleColorRegex.test(v) && v.startsWith(type) || testProp && Object.prototype.hasOwnProperty.call(v, testProp)); - }; - const splitColor = (aName, bName, cName) => v => { - if (!isString(v)) return v; - const [a, b, c, alpha] = v.match(floatRegex); - return { - [aName]: parseFloat(a), - [bName]: parseFloat(b), - [cName]: parseFloat(c), - alpha: alpha !== undefined ? parseFloat(alpha) : 1 - }; - }; - const hsla = { - test: isColorString('hsl', 'hue'), - parse: splitColor('hue', 'saturation', 'lightness'), - transform: ({ - hue, - saturation, - lightness, - alpha: alpha$1 = 1 - }) => { - return 'hsla(' + Math.round(hue) + ', ' + percent.transform(sanitize(saturation)) + ', ' + percent.transform(sanitize(lightness)) + ', ' + sanitize(alpha.transform(alpha$1)) + ')'; - } - }; - const clampRgbUnit = clamp(0, 255); - const rgbUnit = Object.assign(Object.assign({}, number), { - transform: v => Math.round(clampRgbUnit(v)) - }); - const rgba = { - test: isColorString('rgb', 'red'), - parse: splitColor('red', 'green', 'blue'), - transform: ({ - red, - green, - blue, - alpha: alpha$1 = 1 - }) => 'rgba(' + rgbUnit.transform(red) + ', ' + rgbUnit.transform(green) + ', ' + rgbUnit.transform(blue) + ', ' + sanitize(alpha.transform(alpha$1)) + ')' - }; - function parseHex(v) { - let r = ''; - let g = ''; - let b = ''; - let a = ''; - if (v.length > 5) { - r = v.substr(1, 2); - g = v.substr(3, 2); - b = v.substr(5, 2); - a = v.substr(7, 2); - } else { - r = v.substr(1, 1); - g = v.substr(2, 1); - b = v.substr(3, 1); - a = v.substr(4, 1); - r += r; - g += g; - b += b; - a += a; - } - return { - red: parseInt(r, 16), - green: parseInt(g, 16), - blue: parseInt(b, 16), - alpha: a ? parseInt(a, 16) / 255 : 1 - }; - } - const hex = { - test: isColorString('#'), - parse: parseHex, - transform: rgba.transform - }; - const color = { - test: v => rgba.test(v) || hex.test(v) || hsla.test(v), - parse: v => { - if (rgba.test(v)) { - return rgba.parse(v); - } else if (hsla.test(v)) { - return hsla.parse(v); - } else { - return hex.parse(v); - } - }, - transform: v => { - return isString(v) ? v : v.hasOwnProperty('red') ? rgba.transform(v) : hsla.transform(v); - } - }; - const colorToken = '${c}'; - const numberToken = '${n}'; - function test(v) { - var _a, _b, _c, _d; - return isNaN(v) && isString(v) && ((_b = (_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0; - } - function analyse(v) { - if (typeof v === 'number') v = `${v}`; - const values = []; - let numColors = 0; - const colors = v.match(colorRegex); - if (colors) { - numColors = colors.length; - v = v.replace(colorRegex, colorToken); - values.push(...colors.map(color.parse)); - } - const numbers = v.match(floatRegex); - if (numbers) { - v = v.replace(floatRegex, numberToken); - values.push(...numbers.map(number.parse)); - } - return { - values, - numColors, - tokenised: v - }; - } - function parse(v) { - return analyse(v).values; - } - function createTransformer(v) { - const { - values, - numColors, - tokenised - } = analyse(v); - const numValues = values.length; - return v => { - let output = tokenised; - for (let i = 0; i < numValues; i++) { - output = output.replace(i < numColors ? colorToken : numberToken, i < numColors ? color.transform(v[i]) : sanitize(v[i])); - } - return output; - }; - } - const convertNumbersToZero = v => typeof v === 'number' ? 0 : v; - function getAnimatableNone(v) { - const parsed = parse(v); - const transformer = createTransformer(v); - return transformer(parsed.map(convertNumbersToZero)); - } - const complex = { - test, - parse, - createTransformer, - getAnimatableNone - }; - const maxDefaults = new Set(['brightness', 'contrast', 'saturate', 'opacity']); - function applyDefaultFilter(v) { - let [name, value] = v.slice(0, -1).split('('); - if (name === 'drop-shadow') return v; - const [number] = value.match(floatRegex) || []; - if (!number) return v; - const unit = value.replace(number, ''); - let defaultValue = maxDefaults.has(name) ? 1 : 0; - if (number !== value) defaultValue *= 100; - return name + '(' + defaultValue + unit + ')'; - } - const functionRegex = /([a-z-]*)\(.*?\)/g; - const filter = Object.assign(Object.assign({}, complex), { - getAnimatableNone: v => { - const functions = v.match(functionRegex); - return functions ? functions.map(applyDefaultFilter).join(' ') : v; - } - }); - exports.alpha = alpha; - exports.color = color; - exports.complex = complex; - exports.degrees = degrees; - exports.filter = filter; - exports.hex = hex; - exports.hsla = hsla; - exports.number = number; - exports.percent = percent; - exports.progressPercentage = progressPercentage; - exports.px = px; - exports.rgbUnit = rgbUnit; - exports.rgba = rgba; - exports.scale = scale; - exports.vh = vh; - exports.vw = vw; - - /***/ }), - - /***/ "../../../node_modules/toggle-selection/index.js": - /*!*******************************************************!*\ - !*** ../../../node_modules/toggle-selection/index.js ***! - \*******************************************************/ - /***/ (function(module) { - - - - module.exports = function () { - var selection = document.getSelection(); - if (!selection.rangeCount) { - return function () {}; - } - var active = document.activeElement; - var ranges = []; - for (var i = 0; i < selection.rangeCount; i++) { - ranges.push(selection.getRangeAt(i)); - } - switch (active.tagName.toUpperCase()) { - // .toUpperCase handles XHTML - case 'INPUT': - case 'TEXTAREA': - active.blur(); - break; - default: - active = null; - break; - } - selection.removeAllRanges(); - return function () { - selection.type === 'Caret' && selection.removeAllRanges(); - if (!selection.rangeCount) { - ranges.forEach(function (range) { - selection.addRange(range); - }); - } - active && active.focus(); - }; - }; - - /***/ }), - - /***/ "../../../node_modules/tslib/tslib.es6.mjs": - /*!*************************************************!*\ - !*** ../../../node_modules/tslib/tslib.es6.mjs ***! - \*************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.__addDisposableResource = __addDisposableResource; - exports.__assign = void 0; - exports.__asyncDelegator = __asyncDelegator; - exports.__asyncGenerator = __asyncGenerator; - exports.__asyncValues = __asyncValues; - exports.__await = __await; - exports.__awaiter = __awaiter; - exports.__classPrivateFieldGet = __classPrivateFieldGet; - exports.__classPrivateFieldIn = __classPrivateFieldIn; - exports.__classPrivateFieldSet = __classPrivateFieldSet; - exports.__createBinding = void 0; - exports.__decorate = __decorate; - exports.__disposeResources = __disposeResources; - exports.__esDecorate = __esDecorate; - exports.__exportStar = __exportStar; - exports.__extends = __extends; - exports.__generator = __generator; - exports.__importDefault = __importDefault; - exports.__importStar = __importStar; - exports.__makeTemplateObject = __makeTemplateObject; - exports.__metadata = __metadata; - exports.__param = __param; - exports.__propKey = __propKey; - exports.__read = __read; - exports.__rest = __rest; - exports.__runInitializers = __runInitializers; - exports.__setFunctionName = __setFunctionName; - exports.__spread = __spread; - exports.__spreadArray = __spreadArray; - exports.__spreadArrays = __spreadArrays; - exports.__values = __values; - exports["default"] = void 0; - /****************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise, SuppressedError, Symbol */ - - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || { - __proto__: [] - } instanceof Array && function (d, b) { - d.__proto__ = b; - } || function (d, b) { - for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; - }; - return extendStatics(d, b); - }; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - var __assign = function () { - exports.__assign = __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - exports.__assign = __assign; - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; - } - return t; - } - function __decorate(decorators, target, key, desc) { - var c = arguments.length, - r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, - d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - } - function __param(paramIndex, decorator) { - return function (target, key) { - decorator(target, key, paramIndex); - }; - } - function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, - key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, - done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { - get: descriptor.get, - set: descriptor.set - } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_);else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; - } - ; - function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; - } - ; - function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); - } - ; - function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { - configurable: true, - value: prefix ? "".concat(prefix, " ", name) : name - }); - } - ; - function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - } - function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } - function __generator(thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [] - }, - f, - y, - t, - g; - return g = { - next: verb(0), - "throw": verb(1), - "return": verb(2) - }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { - return this; - }), g; - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { - value: op[1], - done: false - }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { - value: op[0] ? op[1] : void 0, - done: true - }; - } - } - var __createBinding = exports.__createBinding = Object.create ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { - enumerable: true, - get: function () { - return m[k]; - } - }; - } - Object.defineProperty(o, k2, desc); - } : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }; - function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - } - function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, - m = s && o[s], - i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { - value: o && o[i++], - done: !o - }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - } - function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), - r, - ar = [], - e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error) { - e = { - error: error - }; - } finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; - } - - /** @deprecated */ - function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); - return ar; - } - - /** @deprecated */ - function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; - return r; - } - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - } - function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - } - function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } - } - function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function () { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function (v) { - return (p = !p) ? { - value: __await(o[n](v)), - done: false - } : f ? f(v) : v; - } : f; - } - } - function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function (v) { - return new Promise(function (resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } - } - function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { - value: raw - }); - } else { - cooked.raw = raw; - } - return cooked; - } - ; - var __setModuleDefault = Object.create ? function (o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); - } : function (o, v) { - o["default"] = v; - }; - function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - } - function __importDefault(mod) { - return mod && mod.__esModule ? mod : { - default: mod - }; - } - function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - } - function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; - } - function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); - } - function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - env.stack.push({ - value: value, - dispose: dispose, - async: async - }); - } else if (async) { - env.stack.push({ - async: true - }); - } - return value; - } - var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; - }; - function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - function next() { - while (env.stack.length) { - var rec = env.stack.pop(); - try { - var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) return Promise.resolve(result).then(next, function (e) { - fail(e); - return next(); - }); - } catch (e) { - fail(e); - } - } - if (env.hasError) throw env.error; - } - return next(); - } - var _default = exports["default"] = { - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources - }; - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/assignRef.js ***! - \***********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.assignRef = assignRef; - /** - * Assigns a value for a given ref, no matter of the ref format - * @param {RefObject} ref - a callback function or ref object - * @param value - a new value - * - * @see https://github.com/theKashey/use-callback-ref#assignref - * @example - * const refObject = useRef(); - * const refFn = (ref) => {....} - * - * assignRef(refObject, "refValue"); - * assignRef(refFn, "refValue"); - */ - function assignRef(ref, value) { - if (typeof ref === 'function') { - ref(value); - } else if (ref) { - ref.current = value; - } - return ref; - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js": - /*!***********************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/createRef.js ***! - \***********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.createCallbackRef = createCallbackRef; - /** - * creates a Ref object with on change callback - * @param callback - * @returns {RefObject} - * - * @see {@link useCallbackRef} - * @see https://reactjs.org/docs/refs-and-the-dom.html#creating-refs - */ - function createCallbackRef(callback) { - var current = null; - return { - get current() { - return current; - }, - set current(value) { - var last = current; - if (last !== value) { - current = value; - callback(value, last); - } - } - }; - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/index.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/index.js ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "assignRef", ({ - enumerable: true, - get: function () { - return _assignRef.assignRef; - } - })); - Object.defineProperty(exports, "createCallbackRef", ({ - enumerable: true, - get: function () { - return _createRef.createCallbackRef; - } - })); - Object.defineProperty(exports, "mergeRefs", ({ - enumerable: true, - get: function () { - return _mergeRef.mergeRefs; - } - })); - Object.defineProperty(exports, "refToCallback", ({ - enumerable: true, - get: function () { - return _refToCallback.refToCallback; - } - })); - Object.defineProperty(exports, "transformRef", ({ - enumerable: true, - get: function () { - return _transformRef.transformRef; - } - })); - Object.defineProperty(exports, "useCallbackRef", ({ - enumerable: true, - get: function () { - return _useRef.useCallbackRef; - } - })); - Object.defineProperty(exports, "useMergeRefs", ({ - enumerable: true, - get: function () { - return _useMergeRef.useMergeRefs; - } - })); - Object.defineProperty(exports, "useRefToCallback", ({ - enumerable: true, - get: function () { - return _refToCallback.useRefToCallback; - } - })); - Object.defineProperty(exports, "useTransformRef", ({ - enumerable: true, - get: function () { - return _useTransformRef.useTransformRef; - } - })); - var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); - var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); - var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); - var _mergeRef = __webpack_require__(/*! ./mergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js"); - var _useMergeRef = __webpack_require__(/*! ./useMergeRef */ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js"); - var _useTransformRef = __webpack_require__(/*! ./useTransformRef */ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js"); - var _transformRef = __webpack_require__(/*! ./transformRef */ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js"); - var _refToCallback = __webpack_require__(/*! ./refToCallback */ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js"); - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js": - /*!**********************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/mergeRef.js ***! - \**********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.mergeRefs = mergeRefs; - var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); - var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); - /** - * Merges two or more refs together providing a single interface to set their value - * @param {RefObject|Ref} refs - * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} - * - * @see {@link useMergeRefs} to be used in ReactComponents - * @example - * const Component = React.forwardRef((props, ref) => { - * const ownRef = useRef(); - * const domRef = mergeRefs([ref, ownRef]); // 👈 merge together - * return
    ...
    - * } - */ - function mergeRefs(refs) { - return (0, _createRef.createCallbackRef)(function (newValue) { - return refs.forEach(function (ref) { - return (0, _assignRef.assignRef)(ref, newValue); - }); - }); - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js": - /*!***************************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/refToCallback.js ***! - \***************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.refToCallback = refToCallback; - exports.useRefToCallback = useRefToCallback; - /** - * Unmemoized version of {@link useRefToCallback} - * @see {@link useRefToCallback} - * @param ref - */ - function refToCallback(ref) { - return function (newValue) { - if (typeof ref === 'function') { - ref(newValue); - } else if (ref) { - ref.current = newValue; - } - }; - } - var nullCallback = function () { - return null; - }; - // lets maintain a weak ref to, well, ref :) - // not using `kashe` to keep this package small - var weakMem = new WeakMap(); - var weakMemoize = function (ref) { - var usedRef = ref || nullCallback; - var storedRef = weakMem.get(usedRef); - if (storedRef) { - return storedRef; - } - var cb = refToCallback(usedRef); - weakMem.set(usedRef, cb); - return cb; - }; - /** - * Transforms a given `ref` into `callback`. - * - * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)} - * - * @param {ReactRef} ref - * @returns {Function} - * - * @see https://github.com/theKashey/use-callback-ref#reftocallback - * - * @example - * const ref = useRef(0); - * const setRef = useRefToCallback(ref); - * 👉 setRef(10); - * ✅ ref.current === 10 - */ - function useRefToCallback(ref) { - return weakMemoize(ref); - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/transformRef.js": - /*!**************************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/transformRef.js ***! - \**************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.transformRef = transformRef; - var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); - var _createRef = __webpack_require__(/*! ./createRef */ "../../../node_modules/use-callback-ref/dist/es2015/createRef.js"); - /** - * Transforms one ref to another - * @example - * ```tsx - * const ResizableWithRef = forwardRef((props, ref) => - * i ? i.resizable : null)}/> - * ); - * ``` - */ - function transformRef(ref, transformer) { - return (0, _createRef.createCallbackRef)(function (value) { - return (0, _assignRef.assignRef)(ref, transformer(value)); - }); - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js": - /*!*************************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/useMergeRef.js ***! - \*************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.useMergeRefs = useMergeRefs; - var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); - var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); - /** - * Merges two or more refs together providing a single interface to set their value - * @param {RefObject|Ref} refs - * @returns {MutableRefObject} - a new ref, which translates all changes to {refs} - * - * @see {@link mergeRefs} a version without buit-in memoization - * @see https://github.com/theKashey/use-callback-ref#usemergerefs - * @example - * const Component = React.forwardRef((props, ref) => { - * const ownRef = useRef(); - * const domRef = useMergeRefs([ref, ownRef]); // 👈 merge together - * return
    ...
    - * } - */ - function useMergeRefs(refs, defaultValue) { - return (0, _useRef.useCallbackRef)(defaultValue || null, function (newValue) { - return refs.forEach(function (ref) { - return (0, _assignRef.assignRef)(ref, newValue); - }); - }); - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js": - /*!********************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/useRef.js ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.useCallbackRef = useCallbackRef; - var _react = __webpack_require__(/*! react */ "react"); - /** - * creates a MutableRef with ref change callback - * @param initialValue - initial ref value - * @param {Function} callback - a callback to run when value changes - * - * @example - * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue); - * ref.current = 1; - * // prints 0 -> 1 - * - * @see https://reactjs.org/docs/hooks-reference.html#useref - * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref - * @returns {MutableRefObject} - */ - function useCallbackRef(initialValue, callback) { - var ref = (0, _react.useState)(function () { - return { - // value - value: initialValue, - // last callback - callback: callback, - // "memoized" public interface - facade: { - get current() { - return ref.value; - }, - set current(value) { - var last = ref.value; - if (last !== value) { - ref.value = value; - ref.callback(value, last); - } - } - } - }; - })[0]; - // update callback - ref.callback = callback; - return ref.facade; - } - - /***/ }), - - /***/ "../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js": - /*!*****************************************************************************!*\ - !*** ../../../node_modules/use-callback-ref/dist/es2015/useTransformRef.js ***! - \*****************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.useTransformRef = useTransformRef; - var _assignRef = __webpack_require__(/*! ./assignRef */ "../../../node_modules/use-callback-ref/dist/es2015/assignRef.js"); - var _useRef = __webpack_require__(/*! ./useRef */ "../../../node_modules/use-callback-ref/dist/es2015/useRef.js"); - /** - * Create a _lense_ on Ref, making it possible to transform ref value - * @param {ReactRef} ref - * @param {Function} transformer. 👉 Ref would be __NOT updated__ on `transformer` update. - * @returns {RefObject} - * - * @see https://github.com/theKashey/use-callback-ref#usetransformref-to-replace-reactuseimperativehandle - * @example - * - * const ResizableWithRef = forwardRef((props, ref) => - * i ? i.resizable : null)}/> - * ); - */ - function useTransformRef(ref, transformer) { - return (0, _useRef.useCallbackRef)(null, function (value) { - return (0, _assignRef.assignRef)(ref, transformer(value)); - }); - } - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/config.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/config.js ***! - \***************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.setConfig = exports.config = void 0; - var config = exports.config = { - onError: function (e) { - return console.error(e); - } - }; - var setConfig = function (conf) { - Object.assign(config, conf); - }; - exports.setConfig = setConfig; - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/env.js": - /*!************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/env.js ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.env = void 0; - var _detectNodeEs = __webpack_require__(/*! detect-node-es */ "../../../node_modules/detect-node-es/esm/browser.js"); - var env = exports.env = { - isNode: _detectNodeEs.isNode, - forceCache: false - }; - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/exports.js": - /*!****************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/exports.js ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.exportSidecar = exportSidecar; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - var SideCar = function (_a) { - var sideCar = _a.sideCar, - rest = (0, _tslib.__rest)(_a, ["sideCar"]); - if (!sideCar) { - throw new Error('Sidecar: please provide `sideCar` property to import the right car'); - } - var Target = sideCar.read(); - if (!Target) { - throw new Error('Sidecar medium not found'); - } - return /*#__PURE__*/React.createElement(Target, (0, _tslib.__assign)({}, rest)); - }; - SideCar.isSideCarExport = true; - function exportSidecar(medium, exported) { - medium.useMedium(exported); - return SideCar; - } - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/hoc.js": - /*!************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/hoc.js ***! - \************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.sidecar = sidecar; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var React = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - // eslint-disable-next-line @typescript-eslint/ban-types - function sidecar(importer, errorComponent) { - var ErrorCase = function () { - return errorComponent; - }; - return function Sidecar(props) { - var _a = (0, _hook.useSidecar)(importer, props.sideCar), - Car = _a[0], - error = _a[1]; - if (error && errorComponent) { - return ErrorCase; - } - // @ts-expect-error type shenanigans - return Car ? /*#__PURE__*/React.createElement(Car, (0, _tslib.__assign)({}, props)) : null; - }; - } - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/hook.js": - /*!*************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/hook.js ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.useSidecar = useSidecar; - var _react = __webpack_require__(/*! react */ "react"); - var _env = __webpack_require__(/*! ./env */ "../../../node_modules/use-sidecar/dist/es2015/env.js"); - var cache = new WeakMap(); - var NO_OPTIONS = {}; - function useSidecar(importer, effect) { - var options = effect && effect.options || NO_OPTIONS; - if (_env.env.isNode && !options.ssr) { - return [null, null]; - } - // eslint-disable-next-line react-hooks/rules-of-hooks - return useRealSidecar(importer, effect); - } - function useRealSidecar(importer, effect) { - var options = effect && effect.options || NO_OPTIONS; - var couldUseCache = _env.env.forceCache || _env.env.isNode && !!options.ssr || !options.async; - var _a = (0, _react.useState)(couldUseCache ? function () { - return cache.get(importer); - } : undefined), - Car = _a[0], - setCar = _a[1]; - var _b = (0, _react.useState)(null), - error = _b[0], - setError = _b[1]; - (0, _react.useEffect)(function () { - if (!Car) { - importer().then(function (car) { - var resolved = effect ? effect.read() : car.default || car; - if (!resolved) { - console.error('Sidecar error: with importer', importer); - var error_1; - if (effect) { - console.error('Sidecar error: with medium', effect); - error_1 = new Error('Sidecar medium was not found'); - } else { - error_1 = new Error('Sidecar was not found in exports'); - } - setError(function () { - return error_1; - }); - throw error_1; - } - cache.set(importer, resolved); - setCar(function () { - return resolved; - }); - }, function (e) { - return setError(function () { - return e; - }); - }); - } - }, []); - return [Car, error]; - } - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/index.js": - /*!**************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/index.js ***! - \**************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "createMedium", ({ - enumerable: true, - get: function () { - return _medium.createMedium; - } - })); - Object.defineProperty(exports, "createSidecarMedium", ({ - enumerable: true, - get: function () { - return _medium.createSidecarMedium; - } - })); - Object.defineProperty(exports, "exportSidecar", ({ - enumerable: true, - get: function () { - return _exports.exportSidecar; - } - })); - Object.defineProperty(exports, "renderCar", ({ - enumerable: true, - get: function () { - return _renderProp.renderCar; - } - })); - Object.defineProperty(exports, "setConfig", ({ - enumerable: true, - get: function () { - return _config.setConfig; - } - })); - Object.defineProperty(exports, "sidecar", ({ - enumerable: true, - get: function () { - return _hoc.sidecar; - } - })); - Object.defineProperty(exports, "useSidecar", ({ - enumerable: true, - get: function () { - return _hook.useSidecar; - } - })); - var _hoc = __webpack_require__(/*! ./hoc */ "../../../node_modules/use-sidecar/dist/es2015/hoc.js"); - var _hook = __webpack_require__(/*! ./hook */ "../../../node_modules/use-sidecar/dist/es2015/hook.js"); - var _config = __webpack_require__(/*! ./config */ "../../../node_modules/use-sidecar/dist/es2015/config.js"); - var _medium = __webpack_require__(/*! ./medium */ "../../../node_modules/use-sidecar/dist/es2015/medium.js"); - var _renderProp = __webpack_require__(/*! ./renderProp */ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js"); - var _exports = __webpack_require__(/*! ./exports */ "../../../node_modules/use-sidecar/dist/es2015/exports.js"); - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/medium.js": - /*!***************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/medium.js ***! - \***************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.createMedium = createMedium; - exports.createSidecarMedium = createSidecarMedium; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - function ItoI(a) { - return a; - } - function innerCreateMedium(defaults, middleware) { - if (middleware === void 0) { - middleware = ItoI; - } - var buffer = []; - var assigned = false; - var medium = { - read: function () { - if (assigned) { - throw new Error('Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.'); - } - if (buffer.length) { - return buffer[buffer.length - 1]; - } - return defaults; - }, - useMedium: function (data) { - var item = middleware(data, assigned); - buffer.push(item); - return function () { - buffer = buffer.filter(function (x) { - return x !== item; - }); - }; - }, - assignSyncMedium: function (cb) { - assigned = true; - while (buffer.length) { - var cbs = buffer; - buffer = []; - cbs.forEach(cb); - } - buffer = { - push: function (x) { - return cb(x); - }, - filter: function () { - return buffer; - } - }; - }, - assignMedium: function (cb) { - assigned = true; - var pendingQueue = []; - if (buffer.length) { - var cbs = buffer; - buffer = []; - cbs.forEach(cb); - pendingQueue = buffer; - } - var executeQueue = function () { - var cbs = pendingQueue; - pendingQueue = []; - cbs.forEach(cb); - }; - var cycle = function () { - return Promise.resolve().then(executeQueue); - }; - cycle(); - buffer = { - push: function (x) { - pendingQueue.push(x); - cycle(); - }, - filter: function (filter) { - pendingQueue = pendingQueue.filter(filter); - return buffer; - } - }; - } - }; - return medium; - } - function createMedium(defaults, middleware) { - if (middleware === void 0) { - middleware = ItoI; - } - return innerCreateMedium(defaults, middleware); - } - // eslint-disable-next-line @typescript-eslint/ban-types - function createSidecarMedium(options) { - if (options === void 0) { - options = {}; - } - var medium = innerCreateMedium(null); - medium.options = (0, _tslib.__assign)({ - async: true, - ssr: false - }, options); - return medium; - } - - /***/ }), - - /***/ "../../../node_modules/use-sidecar/dist/es2015/renderProp.js": - /*!*******************************************************************!*\ - !*** ../../../node_modules/use-sidecar/dist/es2015/renderProp.js ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.renderCar = renderCar; - var _tslib = __webpack_require__(/*! tslib */ "../../../node_modules/tslib/tslib.es6.mjs"); - var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var React = _react; - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - function renderCar(WrappedComponent, defaults) { - function State(_a) { - var stateRef = _a.stateRef, - props = _a.props; - var renderTarget = (0, _react.useCallback)(function SideTarget() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - (0, _react.useLayoutEffect)(function () { - stateRef.current(args); - }); - return null; - }, []); - // @ts-ignore - return /*#__PURE__*/React.createElement(WrappedComponent, (0, _tslib.__assign)({}, props, { - children: renderTarget - })); - } - var Children = /*#__PURE__*/React.memo(function (_a) { - var stateRef = _a.stateRef, - defaultState = _a.defaultState, - children = _a.children; - var _b = (0, _react.useState)(defaultState.current), - state = _b[0], - setState = _b[1]; - (0, _react.useEffect)(function () { - stateRef.current = setState; - }, []); - return children.apply(void 0, state); - }, function () { - return true; - }); - return function Combiner(props) { - var defaultState = React.useRef(defaults(props)); - var ref = React.useRef(function (state) { - return defaultState.current = state; - }); - return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(State, { - stateRef: ref, - props: props - }), /*#__PURE__*/React.createElement(Children, { - stateRef: ref, - defaultState: defaultState, - children: props.children - })); - }; - } - - /***/ }), - - /***/ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js": - /*!*************************************************************************!*\ - !*** ../../../node_modules/vscode-languageserver-types/lib/esm/main.js ***! - \*************************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - /* -------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - * ------------------------------------------------------------------------------------------ */ - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.uinteger = exports.integer = exports.WorkspaceSymbol = exports.WorkspaceFolder = exports.WorkspaceEdit = exports.WorkspaceChange = exports.VersionedTextDocumentIdentifier = exports.URI = exports.TextEdit = exports.TextDocumentItem = exports.TextDocumentIdentifier = exports.TextDocumentEdit = exports.TextDocument = exports.SymbolTag = exports.SymbolKind = exports.SymbolInformation = exports.SignatureInformation = exports.SemanticTokens = exports.SemanticTokenTypes = exports.SemanticTokenModifiers = exports.SelectionRange = exports.RenameFile = exports.Range = exports.Position = exports.ParameterInformation = exports.OptionalVersionedTextDocumentIdentifier = exports.MarkupKind = exports.MarkupContent = exports.MarkedString = exports.LocationLink = exports.Location = exports.InsertTextMode = exports.InsertTextFormat = exports.InsertReplaceEdit = exports.InlineValueVariableLookup = exports.InlineValueText = exports.InlineValueEvaluatableExpression = exports.InlineValueContext = exports.InlayHintLabelPart = exports.InlayHintKind = exports.InlayHint = exports.Hover = exports.FormattingOptions = exports.FoldingRangeKind = exports.FoldingRange = exports.EOL = exports.DocumentUri = exports.DocumentSymbol = exports.DocumentLink = exports.DocumentHighlightKind = exports.DocumentHighlight = exports.DiagnosticTag = exports.DiagnosticSeverity = exports.DiagnosticRelatedInformation = exports.Diagnostic = exports.DeleteFile = exports.CreateFile = exports.CompletionList = exports.CompletionItemTag = exports.CompletionItemLabelDetails = exports.CompletionItemKind = exports.CompletionItem = exports.Command = exports.ColorPresentation = exports.ColorInformation = exports.Color = exports.CodeLens = exports.CodeDescription = exports.CodeActionTriggerKind = exports.CodeActionKind = exports.CodeActionContext = exports.CodeAction = exports.ChangeAnnotationIdentifier = exports.ChangeAnnotation = exports.AnnotatedTextEdit = void 0; - var DocumentUri; - (function (DocumentUri) { - function is(value) { - return typeof value === 'string'; - } - DocumentUri.is = is; - })(DocumentUri || (exports.DocumentUri = DocumentUri = {})); - var URI; - (function (URI) { - function is(value) { - return typeof value === 'string'; - } - URI.is = is; - })(URI || (exports.URI = URI = {})); - var integer; - (function (integer) { - integer.MIN_VALUE = -2147483648; - integer.MAX_VALUE = 2147483647; - function is(value) { - return typeof value === 'number' && integer.MIN_VALUE <= value && value <= integer.MAX_VALUE; - } - integer.is = is; - })(integer || (exports.integer = integer = {})); - var uinteger; - (function (uinteger) { - uinteger.MIN_VALUE = 0; - uinteger.MAX_VALUE = 2147483647; - function is(value) { - return typeof value === 'number' && uinteger.MIN_VALUE <= value && value <= uinteger.MAX_VALUE; - } - uinteger.is = is; - })(uinteger || (exports.uinteger = uinteger = {})); - /** - * The Position namespace provides helper functions to work with - * {@link Position} literals. - */ - var Position; - (function (Position) { - /** - * Creates a new Position literal from the given line and character. - * @param line The position's line. - * @param character The position's character. - */ - function create(line, character) { - if (line === Number.MAX_VALUE) { - line = uinteger.MAX_VALUE; - } - if (character === Number.MAX_VALUE) { - character = uinteger.MAX_VALUE; - } - return { - line: line, - character: character - }; - } - Position.create = create; - /** - * Checks whether the given literal conforms to the {@link Position} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character); - } - Position.is = is; - })(Position || (exports.Position = Position = {})); - /** - * The Range namespace provides helper functions to work with - * {@link Range} literals. - */ - var Range; - (function (Range) { - function create(one, two, three, four) { - if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) { - return { - start: Position.create(one, two), - end: Position.create(three, four) - }; - } else if (Position.is(one) && Position.is(two)) { - return { - start: one, - end: two - }; - } else { - throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]")); - } - } - Range.create = create; - /** - * Checks whether the given literal conforms to the {@link Range} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end); - } - Range.is = is; - })(Range || (exports.Range = Range = {})); - /** - * The Location namespace provides helper functions to work with - * {@link Location} literals. - */ - var Location; - (function (Location) { - /** - * Creates a Location literal. - * @param uri The location's uri. - * @param range The location's range. - */ - function create(uri, range) { - return { - uri: uri, - range: range - }; - } - Location.create = create; - /** - * Checks whether the given literal conforms to the {@link Location} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri)); - } - Location.is = is; - })(Location || (exports.Location = Location = {})); - /** - * The LocationLink namespace provides helper functions to work with - * {@link LocationLink} literals. - */ - var LocationLink; - (function (LocationLink) { - /** - * Creates a LocationLink literal. - * @param targetUri The definition's uri. - * @param targetRange The full range of the definition. - * @param targetSelectionRange The span of the symbol definition at the target. - * @param originSelectionRange The span of the symbol being defined in the originating source file. - */ - function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) { - return { - targetUri: targetUri, - targetRange: targetRange, - targetSelectionRange: targetSelectionRange, - originSelectionRange: originSelectionRange - }; - } - LocationLink.create = create; - /** - * Checks whether the given literal conforms to the {@link LocationLink} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange)); - } - LocationLink.is = is; - })(LocationLink || (exports.LocationLink = LocationLink = {})); - /** - * The Color namespace provides helper functions to work with - * {@link Color} literals. - */ - var Color; - (function (Color) { - /** - * Creates a new Color literal. - */ - function create(red, green, blue, alpha) { - return { - red: red, - green: green, - blue: blue, - alpha: alpha - }; - } - Color.create = create; - /** - * Checks whether the given literal conforms to the {@link Color} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1); - } - Color.is = is; - })(Color || (exports.Color = Color = {})); - /** - * The ColorInformation namespace provides helper functions to work with - * {@link ColorInformation} literals. - */ - var ColorInformation; - (function (ColorInformation) { - /** - * Creates a new ColorInformation literal. - */ - function create(range, color) { - return { - range: range, - color: color - }; - } - ColorInformation.create = create; - /** - * Checks whether the given literal conforms to the {@link ColorInformation} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color); - } - ColorInformation.is = is; - })(ColorInformation || (exports.ColorInformation = ColorInformation = {})); - /** - * The Color namespace provides helper functions to work with - * {@link ColorPresentation} literals. - */ - var ColorPresentation; - (function (ColorPresentation) { - /** - * Creates a new ColorInformation literal. - */ - function create(label, textEdit, additionalTextEdits) { - return { - label: label, - textEdit: textEdit, - additionalTextEdits: additionalTextEdits - }; - } - ColorPresentation.create = create; - /** - * Checks whether the given literal conforms to the {@link ColorInformation} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is)); - } - ColorPresentation.is = is; - })(ColorPresentation || (exports.ColorPresentation = ColorPresentation = {})); - /** - * A set of predefined range kinds. - */ - var FoldingRangeKind; - (function (FoldingRangeKind) { - /** - * Folding range for a comment - */ - FoldingRangeKind.Comment = 'comment'; - /** - * Folding range for an import or include - */ - FoldingRangeKind.Imports = 'imports'; - /** - * Folding range for a region (e.g. `#region`) - */ - FoldingRangeKind.Region = 'region'; - })(FoldingRangeKind || (exports.FoldingRangeKind = FoldingRangeKind = {})); - /** - * The folding range namespace provides helper functions to work with - * {@link FoldingRange} literals. - */ - var FoldingRange; - (function (FoldingRange) { - /** - * Creates a new FoldingRange literal. - */ - function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) { - var result = { - startLine: startLine, - endLine: endLine - }; - if (Is.defined(startCharacter)) { - result.startCharacter = startCharacter; - } - if (Is.defined(endCharacter)) { - result.endCharacter = endCharacter; - } - if (Is.defined(kind)) { - result.kind = kind; - } - if (Is.defined(collapsedText)) { - result.collapsedText = collapsedText; - } - return result; - } - FoldingRange.create = create; - /** - * Checks whether the given literal conforms to the {@link FoldingRange} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind)); - } - FoldingRange.is = is; - })(FoldingRange || (exports.FoldingRange = FoldingRange = {})); - /** - * The DiagnosticRelatedInformation namespace provides helper functions to work with - * {@link DiagnosticRelatedInformation} literals. - */ - var DiagnosticRelatedInformation; - (function (DiagnosticRelatedInformation) { - /** - * Creates a new DiagnosticRelatedInformation literal. - */ - function create(location, message) { - return { - location: location, - message: message - }; - } - DiagnosticRelatedInformation.create = create; - /** - * Checks whether the given literal conforms to the {@link DiagnosticRelatedInformation} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message); - } - DiagnosticRelatedInformation.is = is; - })(DiagnosticRelatedInformation || (exports.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {})); - /** - * The diagnostic's severity. - */ - var DiagnosticSeverity; - (function (DiagnosticSeverity) { - /** - * Reports an error. - */ - DiagnosticSeverity.Error = 1; - /** - * Reports a warning. - */ - DiagnosticSeverity.Warning = 2; - /** - * Reports an information. - */ - DiagnosticSeverity.Information = 3; - /** - * Reports a hint. - */ - DiagnosticSeverity.Hint = 4; - })(DiagnosticSeverity || (exports.DiagnosticSeverity = DiagnosticSeverity = {})); - /** - * The diagnostic tags. - * - * @since 3.15.0 - */ - var DiagnosticTag; - (function (DiagnosticTag) { - /** - * Unused or unnecessary code. - * - * Clients are allowed to render diagnostics with this tag faded out instead of having - * an error squiggle. - */ - DiagnosticTag.Unnecessary = 1; - /** - * Deprecated or obsolete code. - * - * Clients are allowed to rendered diagnostics with this tag strike through. - */ - DiagnosticTag.Deprecated = 2; - })(DiagnosticTag || (exports.DiagnosticTag = DiagnosticTag = {})); - /** - * The CodeDescription namespace provides functions to deal with descriptions for diagnostic codes. - * - * @since 3.16.0 - */ - var CodeDescription; - (function (CodeDescription) { - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.href); - } - CodeDescription.is = is; - })(CodeDescription || (exports.CodeDescription = CodeDescription = {})); - /** - * The Diagnostic namespace provides helper functions to work with - * {@link Diagnostic} literals. - */ - var Diagnostic; - (function (Diagnostic) { - /** - * Creates a new Diagnostic literal. - */ - function create(range, message, severity, code, source, relatedInformation) { - var result = { - range: range, - message: message - }; - if (Is.defined(severity)) { - result.severity = severity; - } - if (Is.defined(code)) { - result.code = code; - } - if (Is.defined(source)) { - result.source = source; - } - if (Is.defined(relatedInformation)) { - result.relatedInformation = relatedInformation; - } - return result; - } - Diagnostic.create = create; - /** - * Checks whether the given literal conforms to the {@link Diagnostic} interface. - */ - function is(value) { - var _a; - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is)); - } - Diagnostic.is = is; - })(Diagnostic || (exports.Diagnostic = Diagnostic = {})); - /** - * The Command namespace provides helper functions to work with - * {@link Command} literals. - */ - var Command; - (function (Command) { - /** - * Creates a new Command literal. - */ - function create(title, command) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var result = { - title: title, - command: command - }; - if (Is.defined(args) && args.length > 0) { - result.arguments = args; - } - return result; - } - Command.create = create; - /** - * Checks whether the given literal conforms to the {@link Command} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command); - } - Command.is = is; - })(Command || (exports.Command = Command = {})); - /** - * The TextEdit namespace provides helper function to create replace, - * insert and delete edits more easily. - */ - var TextEdit; - (function (TextEdit) { - /** - * Creates a replace text edit. - * @param range The range of text to be replaced. - * @param newText The new text. - */ - function replace(range, newText) { - return { - range: range, - newText: newText - }; - } - TextEdit.replace = replace; - /** - * Creates an insert text edit. - * @param position The position to insert the text at. - * @param newText The text to be inserted. - */ - function insert(position, newText) { - return { - range: { - start: position, - end: position - }, - newText: newText - }; - } - TextEdit.insert = insert; - /** - * Creates a delete text edit. - * @param range The range of text to be deleted. - */ - function del(range) { - return { - range: range, - newText: '' - }; - } - TextEdit.del = del; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range); - } - TextEdit.is = is; - })(TextEdit || (exports.TextEdit = TextEdit = {})); - var ChangeAnnotation; - (function (ChangeAnnotation) { - function create(label, needsConfirmation, description) { - var result = { - label: label - }; - if (needsConfirmation !== undefined) { - result.needsConfirmation = needsConfirmation; - } - if (description !== undefined) { - result.description = description; - } - return result; - } - ChangeAnnotation.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined); - } - ChangeAnnotation.is = is; - })(ChangeAnnotation || (exports.ChangeAnnotation = ChangeAnnotation = {})); - var ChangeAnnotationIdentifier; - (function (ChangeAnnotationIdentifier) { - function is(value) { - var candidate = value; - return Is.string(candidate); - } - ChangeAnnotationIdentifier.is = is; - })(ChangeAnnotationIdentifier || (exports.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {})); - var AnnotatedTextEdit; - (function (AnnotatedTextEdit) { - /** - * Creates an annotated replace text edit. - * - * @param range The range of text to be replaced. - * @param newText The new text. - * @param annotation The annotation. - */ - function replace(range, newText, annotation) { - return { - range: range, - newText: newText, - annotationId: annotation - }; - } - AnnotatedTextEdit.replace = replace; - /** - * Creates an annotated insert text edit. - * - * @param position The position to insert the text at. - * @param newText The text to be inserted. - * @param annotation The annotation. - */ - function insert(position, newText, annotation) { - return { - range: { - start: position, - end: position - }, - newText: newText, - annotationId: annotation - }; - } - AnnotatedTextEdit.insert = insert; - /** - * Creates an annotated delete text edit. - * - * @param range The range of text to be deleted. - * @param annotation The annotation. - */ - function del(range, annotation) { - return { - range: range, - newText: '', - annotationId: annotation - }; - } - AnnotatedTextEdit.del = del; - function is(value) { - var candidate = value; - return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - AnnotatedTextEdit.is = is; - })(AnnotatedTextEdit || (exports.AnnotatedTextEdit = AnnotatedTextEdit = {})); - /** - * The TextDocumentEdit namespace provides helper function to create - * an edit that manipulates a text document. - */ - var TextDocumentEdit; - (function (TextDocumentEdit) { - /** - * Creates a new `TextDocumentEdit` - */ - function create(textDocument, edits) { - return { - textDocument: textDocument, - edits: edits - }; - } - TextDocumentEdit.create = create; - function is(value) { - var candidate = value; - return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits); - } - TextDocumentEdit.is = is; - })(TextDocumentEdit || (exports.TextDocumentEdit = TextDocumentEdit = {})); - var CreateFile; - (function (CreateFile) { - function create(uri, options, annotation) { - var result = { - kind: 'create', - uri: uri - }; - if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { - result.options = options; - } - if (annotation !== undefined) { - result.annotationId = annotation; - } - return result; - } - CreateFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'create' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - CreateFile.is = is; - })(CreateFile || (exports.CreateFile = CreateFile = {})); - var RenameFile; - (function (RenameFile) { - function create(oldUri, newUri, options, annotation) { - var result = { - kind: 'rename', - oldUri: oldUri, - newUri: newUri - }; - if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) { - result.options = options; - } - if (annotation !== undefined) { - result.annotationId = annotation; - } - return result; - } - RenameFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - RenameFile.is = is; - })(RenameFile || (exports.RenameFile = RenameFile = {})); - var DeleteFile; - (function (DeleteFile) { - function create(uri, options, annotation) { - var result = { - kind: 'delete', - uri: uri - }; - if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) { - result.options = options; - } - if (annotation !== undefined) { - result.annotationId = annotation; - } - return result; - } - DeleteFile.create = create; - function is(value) { - var candidate = value; - return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId)); - } - DeleteFile.is = is; - })(DeleteFile || (exports.DeleteFile = DeleteFile = {})); - var WorkspaceEdit; - (function (WorkspaceEdit) { - function is(value) { - var candidate = value; - return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function (change) { - if (Is.string(change.kind)) { - return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change); - } else { - return TextDocumentEdit.is(change); - } - })); - } - WorkspaceEdit.is = is; - })(WorkspaceEdit || (exports.WorkspaceEdit = WorkspaceEdit = {})); - var TextEditChangeImpl = /** @class */function () { - function TextEditChangeImpl(edits, changeAnnotations) { - this.edits = edits; - this.changeAnnotations = changeAnnotations; - } - TextEditChangeImpl.prototype.insert = function (position, newText, annotation) { - var edit; - var id; - if (annotation === undefined) { - edit = TextEdit.insert(position, newText); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit = AnnotatedTextEdit.insert(position, newText, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit = AnnotatedTextEdit.insert(position, newText, id); - } - this.edits.push(edit); - if (id !== undefined) { - return id; - } - }; - TextEditChangeImpl.prototype.replace = function (range, newText, annotation) { - var edit; - var id; - if (annotation === undefined) { - edit = TextEdit.replace(range, newText); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit = AnnotatedTextEdit.replace(range, newText, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit = AnnotatedTextEdit.replace(range, newText, id); - } - this.edits.push(edit); - if (id !== undefined) { - return id; - } - }; - TextEditChangeImpl.prototype.delete = function (range, annotation) { - var edit; - var id; - if (annotation === undefined) { - edit = TextEdit.del(range); - } else if (ChangeAnnotationIdentifier.is(annotation)) { - id = annotation; - edit = AnnotatedTextEdit.del(range, annotation); - } else { - this.assertChangeAnnotations(this.changeAnnotations); - id = this.changeAnnotations.manage(annotation); - edit = AnnotatedTextEdit.del(range, id); - } - this.edits.push(edit); - if (id !== undefined) { - return id; - } - }; - TextEditChangeImpl.prototype.add = function (edit) { - this.edits.push(edit); - }; - TextEditChangeImpl.prototype.all = function () { - return this.edits; - }; - TextEditChangeImpl.prototype.clear = function () { - this.edits.splice(0, this.edits.length); - }; - TextEditChangeImpl.prototype.assertChangeAnnotations = function (value) { - if (value === undefined) { - throw new Error("Text edit change is not configured to manage change annotations."); - } - }; - return TextEditChangeImpl; - }(); - /** - * A helper class - */ - var ChangeAnnotations = /** @class */function () { - function ChangeAnnotations(annotations) { - this._annotations = annotations === undefined ? Object.create(null) : annotations; - this._counter = 0; - this._size = 0; - } - ChangeAnnotations.prototype.all = function () { - return this._annotations; - }; - Object.defineProperty(ChangeAnnotations.prototype, "size", { - get: function () { - return this._size; - }, - enumerable: false, - configurable: true - }); - ChangeAnnotations.prototype.manage = function (idOrAnnotation, annotation) { - var id; - if (ChangeAnnotationIdentifier.is(idOrAnnotation)) { - id = idOrAnnotation; - } else { - id = this.nextId(); - annotation = idOrAnnotation; - } - if (this._annotations[id] !== undefined) { - throw new Error("Id ".concat(id, " is already in use.")); - } - if (annotation === undefined) { - throw new Error("No annotation provided for id ".concat(id)); - } - this._annotations[id] = annotation; - this._size++; - return id; - }; - ChangeAnnotations.prototype.nextId = function () { - this._counter++; - return this._counter.toString(); - }; - return ChangeAnnotations; - }(); - /** - * A workspace change helps constructing changes to a workspace. - */ - var WorkspaceChange = exports.WorkspaceChange = /** @class */function () { - function WorkspaceChange(workspaceEdit) { - var _this = this; - this._textEditChanges = Object.create(null); - if (workspaceEdit !== undefined) { - this._workspaceEdit = workspaceEdit; - if (workspaceEdit.documentChanges) { - this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations); - workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - workspaceEdit.documentChanges.forEach(function (change) { - if (TextDocumentEdit.is(change)) { - var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations); - _this._textEditChanges[change.textDocument.uri] = textEditChange; - } - }); - } else if (workspaceEdit.changes) { - Object.keys(workspaceEdit.changes).forEach(function (key) { - var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]); - _this._textEditChanges[key] = textEditChange; - }); - } - } else { - this._workspaceEdit = {}; - } - } - Object.defineProperty(WorkspaceChange.prototype, "edit", { - /** - * Returns the underlying {@link WorkspaceEdit} literal - * use to be returned from a workspace edit operation like rename. - */ - get: function () { - this.initDocumentChanges(); - if (this._changeAnnotations !== undefined) { - if (this._changeAnnotations.size === 0) { - this._workspaceEdit.changeAnnotations = undefined; - } else { - this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - } - } - return this._workspaceEdit; - }, - enumerable: false, - configurable: true - }); - WorkspaceChange.prototype.getTextEditChange = function (key) { - if (OptionalVersionedTextDocumentIdentifier.is(key)) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var textDocument = { - uri: key.uri, - version: key.version - }; - var result = this._textEditChanges[textDocument.uri]; - if (!result) { - var edits = []; - var textDocumentEdit = { - textDocument: textDocument, - edits: edits - }; - this._workspaceEdit.documentChanges.push(textDocumentEdit); - result = new TextEditChangeImpl(edits, this._changeAnnotations); - this._textEditChanges[textDocument.uri] = result; - } - return result; - } else { - this.initChanges(); - if (this._workspaceEdit.changes === undefined) { - throw new Error('Workspace edit is not configured for normal text edit changes.'); - } - var result = this._textEditChanges[key]; - if (!result) { - var edits = []; - this._workspaceEdit.changes[key] = edits; - result = new TextEditChangeImpl(edits); - this._textEditChanges[key] = result; - } - return result; - } - }; - WorkspaceChange.prototype.initDocumentChanges = function () { - if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { - this._changeAnnotations = new ChangeAnnotations(); - this._workspaceEdit.documentChanges = []; - this._workspaceEdit.changeAnnotations = this._changeAnnotations.all(); - } - }; - WorkspaceChange.prototype.initChanges = function () { - if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) { - this._workspaceEdit.changes = Object.create(null); - } - }; - WorkspaceChange.prototype.createFile = function (uri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === undefined) { - operation = CreateFile.create(uri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = CreateFile.create(uri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== undefined) { - return id; - } - }; - WorkspaceChange.prototype.renameFile = function (oldUri, newUri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === undefined) { - operation = RenameFile.create(oldUri, newUri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = RenameFile.create(oldUri, newUri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== undefined) { - return id; - } - }; - WorkspaceChange.prototype.deleteFile = function (uri, optionsOrAnnotation, options) { - this.initDocumentChanges(); - if (this._workspaceEdit.documentChanges === undefined) { - throw new Error('Workspace edit is not configured for document changes.'); - } - var annotation; - if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) { - annotation = optionsOrAnnotation; - } else { - options = optionsOrAnnotation; - } - var operation; - var id; - if (annotation === undefined) { - operation = DeleteFile.create(uri, options); - } else { - id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation); - operation = DeleteFile.create(uri, options, id); - } - this._workspaceEdit.documentChanges.push(operation); - if (id !== undefined) { - return id; - } - }; - return WorkspaceChange; - }(); - /** - * The TextDocumentIdentifier namespace provides helper functions to work with - * {@link TextDocumentIdentifier} literals. - */ - var TextDocumentIdentifier; - (function (TextDocumentIdentifier) { - /** - * Creates a new TextDocumentIdentifier literal. - * @param uri The document's uri. - */ - function create(uri) { - return { - uri: uri - }; - } - TextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the {@link TextDocumentIdentifier} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri); - } - TextDocumentIdentifier.is = is; - })(TextDocumentIdentifier || (exports.TextDocumentIdentifier = TextDocumentIdentifier = {})); - /** - * The VersionedTextDocumentIdentifier namespace provides helper functions to work with - * {@link VersionedTextDocumentIdentifier} literals. - */ - var VersionedTextDocumentIdentifier; - (function (VersionedTextDocumentIdentifier) { - /** - * Creates a new VersionedTextDocumentIdentifier literal. - * @param uri The document's uri. - * @param version The document's version. - */ - function create(uri, version) { - return { - uri: uri, - version: version - }; - } - VersionedTextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the {@link VersionedTextDocumentIdentifier} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version); - } - VersionedTextDocumentIdentifier.is = is; - })(VersionedTextDocumentIdentifier || (exports.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {})); - /** - * The OptionalVersionedTextDocumentIdentifier namespace provides helper functions to work with - * {@link OptionalVersionedTextDocumentIdentifier} literals. - */ - var OptionalVersionedTextDocumentIdentifier; - (function (OptionalVersionedTextDocumentIdentifier) { - /** - * Creates a new OptionalVersionedTextDocumentIdentifier literal. - * @param uri The document's uri. - * @param version The document's version. - */ - function create(uri, version) { - return { - uri: uri, - version: version - }; - } - OptionalVersionedTextDocumentIdentifier.create = create; - /** - * Checks whether the given literal conforms to the {@link OptionalVersionedTextDocumentIdentifier} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version)); - } - OptionalVersionedTextDocumentIdentifier.is = is; - })(OptionalVersionedTextDocumentIdentifier || (exports.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {})); - /** - * The TextDocumentItem namespace provides helper functions to work with - * {@link TextDocumentItem} literals. - */ - var TextDocumentItem; - (function (TextDocumentItem) { - /** - * Creates a new TextDocumentItem literal. - * @param uri The document's uri. - * @param languageId The document's language identifier. - * @param version The document's version number. - * @param text The document's text. - */ - function create(uri, languageId, version, text) { - return { - uri: uri, - languageId: languageId, - version: version, - text: text - }; - } - TextDocumentItem.create = create; - /** - * Checks whether the given literal conforms to the {@link TextDocumentItem} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text); - } - TextDocumentItem.is = is; - })(TextDocumentItem || (exports.TextDocumentItem = TextDocumentItem = {})); - /** - * Describes the content type that a client supports in various - * result literals like `Hover`, `ParameterInfo` or `CompletionItem`. - * - * Please note that `MarkupKinds` must not start with a `$`. This kinds - * are reserved for internal usage. - */ - var MarkupKind; - (function (MarkupKind) { - /** - * Plain text is supported as a content format - */ - MarkupKind.PlainText = 'plaintext'; - /** - * Markdown is supported as a content format - */ - MarkupKind.Markdown = 'markdown'; - /** - * Checks whether the given value is a value of the {@link MarkupKind} type. - */ - function is(value) { - var candidate = value; - return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown; - } - MarkupKind.is = is; - })(MarkupKind || (exports.MarkupKind = MarkupKind = {})); - var MarkupContent; - (function (MarkupContent) { - /** - * Checks whether the given value conforms to the {@link MarkupContent} interface. - */ - function is(value) { - var candidate = value; - return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value); - } - MarkupContent.is = is; - })(MarkupContent || (exports.MarkupContent = MarkupContent = {})); - /** - * The kind of a completion entry. - */ - var CompletionItemKind; - (function (CompletionItemKind) { - CompletionItemKind.Text = 1; - CompletionItemKind.Method = 2; - CompletionItemKind.Function = 3; - CompletionItemKind.Constructor = 4; - CompletionItemKind.Field = 5; - CompletionItemKind.Variable = 6; - CompletionItemKind.Class = 7; - CompletionItemKind.Interface = 8; - CompletionItemKind.Module = 9; - CompletionItemKind.Property = 10; - CompletionItemKind.Unit = 11; - CompletionItemKind.Value = 12; - CompletionItemKind.Enum = 13; - CompletionItemKind.Keyword = 14; - CompletionItemKind.Snippet = 15; - CompletionItemKind.Color = 16; - CompletionItemKind.File = 17; - CompletionItemKind.Reference = 18; - CompletionItemKind.Folder = 19; - CompletionItemKind.EnumMember = 20; - CompletionItemKind.Constant = 21; - CompletionItemKind.Struct = 22; - CompletionItemKind.Event = 23; - CompletionItemKind.Operator = 24; - CompletionItemKind.TypeParameter = 25; - })(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); - /** - * Defines whether the insert text in a completion item should be interpreted as - * plain text or a snippet. - */ - var InsertTextFormat; - (function (InsertTextFormat) { - /** - * The primary text to be inserted is treated as a plain string. - */ - InsertTextFormat.PlainText = 1; - /** - * The primary text to be inserted is treated as a snippet. - * - * A snippet can define tab stops and placeholders with `$1`, `$2` - * and `${3:foo}`. `$0` defines the final tab stop, it defaults to - * the end of the snippet. Placeholders with equal identifiers are linked, - * that is typing in one will update others too. - * - * See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax - */ - InsertTextFormat.Snippet = 2; - })(InsertTextFormat || (exports.InsertTextFormat = InsertTextFormat = {})); - /** - * Completion item tags are extra annotations that tweak the rendering of a completion - * item. - * - * @since 3.15.0 - */ - var CompletionItemTag; - (function (CompletionItemTag) { - /** - * Render a completion as obsolete, usually using a strike-out. - */ - CompletionItemTag.Deprecated = 1; - })(CompletionItemTag || (exports.CompletionItemTag = CompletionItemTag = {})); - /** - * The InsertReplaceEdit namespace provides functions to deal with insert / replace edits. - * - * @since 3.16.0 - */ - var InsertReplaceEdit; - (function (InsertReplaceEdit) { - /** - * Creates a new insert / replace edit - */ - function create(newText, insert, replace) { - return { - newText: newText, - insert: insert, - replace: replace - }; - } - InsertReplaceEdit.create = create; - /** - * Checks whether the given literal conforms to the {@link InsertReplaceEdit} interface. - */ - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace); - } - InsertReplaceEdit.is = is; - })(InsertReplaceEdit || (exports.InsertReplaceEdit = InsertReplaceEdit = {})); - /** - * How whitespace and indentation is handled during completion - * item insertion. - * - * @since 3.16.0 - */ - var InsertTextMode; - (function (InsertTextMode) { - /** - * The insertion or replace strings is taken as it is. If the - * value is multi line the lines below the cursor will be - * inserted using the indentation defined in the string value. - * The client will not apply any kind of adjustments to the - * string. - */ - InsertTextMode.asIs = 1; - /** - * The editor adjusts leading whitespace of new lines so that - * they match the indentation up to the cursor of the line for - * which the item is accepted. - * - * Consider a line like this: <2tabs><3tabs>foo. Accepting a - * multi line completion item is indented using 2 tabs and all - * following lines inserted will be indented using 2 tabs as well. - */ - InsertTextMode.adjustIndentation = 2; - })(InsertTextMode || (exports.InsertTextMode = InsertTextMode = {})); - var CompletionItemLabelDetails; - (function (CompletionItemLabelDetails) { - function is(value) { - var candidate = value; - return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) && (Is.string(candidate.description) || candidate.description === undefined); - } - CompletionItemLabelDetails.is = is; - })(CompletionItemLabelDetails || (exports.CompletionItemLabelDetails = CompletionItemLabelDetails = {})); - /** - * The CompletionItem namespace provides functions to deal with - * completion items. - */ - var CompletionItem; - (function (CompletionItem) { - /** - * Create a completion item and seed it with a label. - * @param label The completion item's label - */ - function create(label) { - return { - label: label - }; - } - CompletionItem.create = create; - })(CompletionItem || (exports.CompletionItem = CompletionItem = {})); - /** - * The CompletionList namespace provides functions to deal with - * completion lists. - */ - var CompletionList; - (function (CompletionList) { - /** - * Creates a new completion list. - * - * @param items The completion items. - * @param isIncomplete The list is not complete. - */ - function create(items, isIncomplete) { - return { - items: items ? items : [], - isIncomplete: !!isIncomplete - }; - } - CompletionList.create = create; - })(CompletionList || (exports.CompletionList = CompletionList = {})); - var MarkedString; - (function (MarkedString) { - /** - * Creates a marked string from plain text. - * - * @param plainText The plain text. - */ - function fromPlainText(plainText) { - return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash - } - MarkedString.fromPlainText = fromPlainText; - /** - * Checks whether the given value conforms to the {@link MarkedString} type. - */ - function is(value) { - var candidate = value; - return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value); - } - MarkedString.is = is; - })(MarkedString || (exports.MarkedString = MarkedString = {})); - var Hover; - (function (Hover) { - /** - * Checks whether the given value conforms to the {@link Hover} interface. - */ - function is(value) { - var candidate = value; - return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range)); - } - Hover.is = is; - })(Hover || (exports.Hover = Hover = {})); - /** - * The ParameterInformation namespace provides helper functions to work with - * {@link ParameterInformation} literals. - */ - var ParameterInformation; - (function (ParameterInformation) { - /** - * Creates a new parameter information literal. - * - * @param label A label string. - * @param documentation A doc string. - */ - function create(label, documentation) { - return documentation ? { - label: label, - documentation: documentation - } : { - label: label - }; - } - ParameterInformation.create = create; - })(ParameterInformation || (exports.ParameterInformation = ParameterInformation = {})); - /** - * The SignatureInformation namespace provides helper functions to work with - * {@link SignatureInformation} literals. - */ - var SignatureInformation; - (function (SignatureInformation) { - function create(label, documentation) { - var parameters = []; - for (var _i = 2; _i < arguments.length; _i++) { - parameters[_i - 2] = arguments[_i]; - } - var result = { - label: label - }; - if (Is.defined(documentation)) { - result.documentation = documentation; - } - if (Is.defined(parameters)) { - result.parameters = parameters; - } else { - result.parameters = []; - } - return result; - } - SignatureInformation.create = create; - })(SignatureInformation || (exports.SignatureInformation = SignatureInformation = {})); - /** - * A document highlight kind. - */ - var DocumentHighlightKind; - (function (DocumentHighlightKind) { - /** - * A textual occurrence. - */ - DocumentHighlightKind.Text = 1; - /** - * Read-access of a symbol, like reading a variable. - */ - DocumentHighlightKind.Read = 2; - /** - * Write-access of a symbol, like writing to a variable. - */ - DocumentHighlightKind.Write = 3; - })(DocumentHighlightKind || (exports.DocumentHighlightKind = DocumentHighlightKind = {})); - /** - * DocumentHighlight namespace to provide helper functions to work with - * {@link DocumentHighlight} literals. - */ - var DocumentHighlight; - (function (DocumentHighlight) { - /** - * Create a DocumentHighlight object. - * @param range The range the highlight applies to. - * @param kind The highlight kind - */ - function create(range, kind) { - var result = { - range: range - }; - if (Is.number(kind)) { - result.kind = kind; - } - return result; - } - DocumentHighlight.create = create; - })(DocumentHighlight || (exports.DocumentHighlight = DocumentHighlight = {})); - /** - * A symbol kind. - */ - var SymbolKind; - (function (SymbolKind) { - SymbolKind.File = 1; - SymbolKind.Module = 2; - SymbolKind.Namespace = 3; - SymbolKind.Package = 4; - SymbolKind.Class = 5; - SymbolKind.Method = 6; - SymbolKind.Property = 7; - SymbolKind.Field = 8; - SymbolKind.Constructor = 9; - SymbolKind.Enum = 10; - SymbolKind.Interface = 11; - SymbolKind.Function = 12; - SymbolKind.Variable = 13; - SymbolKind.Constant = 14; - SymbolKind.String = 15; - SymbolKind.Number = 16; - SymbolKind.Boolean = 17; - SymbolKind.Array = 18; - SymbolKind.Object = 19; - SymbolKind.Key = 20; - SymbolKind.Null = 21; - SymbolKind.EnumMember = 22; - SymbolKind.Struct = 23; - SymbolKind.Event = 24; - SymbolKind.Operator = 25; - SymbolKind.TypeParameter = 26; - })(SymbolKind || (exports.SymbolKind = SymbolKind = {})); - /** - * Symbol tags are extra annotations that tweak the rendering of a symbol. - * - * @since 3.16 - */ - var SymbolTag; - (function (SymbolTag) { - /** - * Render a symbol as obsolete, usually using a strike-out. - */ - SymbolTag.Deprecated = 1; - })(SymbolTag || (exports.SymbolTag = SymbolTag = {})); - var SymbolInformation; - (function (SymbolInformation) { - /** - * Creates a new symbol information literal. - * - * @param name The name of the symbol. - * @param kind The kind of the symbol. - * @param range The range of the location of the symbol. - * @param uri The resource of the location of symbol. - * @param containerName The name of the symbol containing the symbol. - */ - function create(name, kind, range, uri, containerName) { - var result = { - name: name, - kind: kind, - location: { - uri: uri, - range: range - } - }; - if (containerName) { - result.containerName = containerName; - } - return result; - } - SymbolInformation.create = create; - })(SymbolInformation || (exports.SymbolInformation = SymbolInformation = {})); - var WorkspaceSymbol; - (function (WorkspaceSymbol) { - /** - * Create a new workspace symbol. - * - * @param name The name of the symbol. - * @param kind The kind of the symbol. - * @param uri The resource of the location of the symbol. - * @param range An options range of the location. - * @returns A WorkspaceSymbol. - */ - function create(name, kind, uri, range) { - return range !== undefined ? { - name: name, - kind: kind, - location: { - uri: uri, - range: range - } - } : { - name: name, - kind: kind, - location: { - uri: uri - } - }; - } - WorkspaceSymbol.create = create; - })(WorkspaceSymbol || (exports.WorkspaceSymbol = WorkspaceSymbol = {})); - var DocumentSymbol; - (function (DocumentSymbol) { - /** - * Creates a new symbol information literal. - * - * @param name The name of the symbol. - * @param detail The detail of the symbol. - * @param kind The kind of the symbol. - * @param range The range of the symbol. - * @param selectionRange The selectionRange of the symbol. - * @param children Children of the symbol. - */ - function create(name, detail, kind, range, selectionRange, children) { - var result = { - name: name, - detail: detail, - kind: kind, - range: range, - selectionRange: selectionRange - }; - if (children !== undefined) { - result.children = children; - } - return result; - } - DocumentSymbol.create = create; - /** - * Checks whether the given literal conforms to the {@link DocumentSymbol} interface. - */ - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags)); - } - DocumentSymbol.is = is; - })(DocumentSymbol || (exports.DocumentSymbol = DocumentSymbol = {})); - /** - * A set of predefined code action kinds - */ - var CodeActionKind; - (function (CodeActionKind) { - /** - * Empty kind. - */ - CodeActionKind.Empty = ''; - /** - * Base kind for quickfix actions: 'quickfix' - */ - CodeActionKind.QuickFix = 'quickfix'; - /** - * Base kind for refactoring actions: 'refactor' - */ - CodeActionKind.Refactor = 'refactor'; - /** - * Base kind for refactoring extraction actions: 'refactor.extract' - * - * Example extract actions: - * - * - Extract method - * - Extract function - * - Extract variable - * - Extract interface from class - * - ... - */ - CodeActionKind.RefactorExtract = 'refactor.extract'; - /** - * Base kind for refactoring inline actions: 'refactor.inline' - * - * Example inline actions: - * - * - Inline function - * - Inline variable - * - Inline constant - * - ... - */ - CodeActionKind.RefactorInline = 'refactor.inline'; - /** - * Base kind for refactoring rewrite actions: 'refactor.rewrite' - * - * Example rewrite actions: - * - * - Convert JavaScript function to class - * - Add or remove parameter - * - Encapsulate field - * - Make method static - * - Move method to base class - * - ... - */ - CodeActionKind.RefactorRewrite = 'refactor.rewrite'; - /** - * Base kind for source actions: `source` - * - * Source code actions apply to the entire file. - */ - CodeActionKind.Source = 'source'; - /** - * Base kind for an organize imports source action: `source.organizeImports` - */ - CodeActionKind.SourceOrganizeImports = 'source.organizeImports'; - /** - * Base kind for auto-fix source actions: `source.fixAll`. - * - * Fix all actions automatically fix errors that have a clear fix that do not require user input. - * They should not suppress errors or perform unsafe fixes such as generating new types or classes. - * - * @since 3.15.0 - */ - CodeActionKind.SourceFixAll = 'source.fixAll'; - })(CodeActionKind || (exports.CodeActionKind = CodeActionKind = {})); - /** - * The reason why code actions were requested. - * - * @since 3.17.0 - */ - var CodeActionTriggerKind; - (function (CodeActionTriggerKind) { - /** - * Code actions were explicitly requested by the user or by an extension. - */ - CodeActionTriggerKind.Invoked = 1; - /** - * Code actions were requested automatically. - * - * This typically happens when current selection in a file changes, but can - * also be triggered when file content changes. - */ - CodeActionTriggerKind.Automatic = 2; - })(CodeActionTriggerKind || (exports.CodeActionTriggerKind = CodeActionTriggerKind = {})); - /** - * The CodeActionContext namespace provides helper functions to work with - * {@link CodeActionContext} literals. - */ - var CodeActionContext; - (function (CodeActionContext) { - /** - * Creates a new CodeActionContext literal. - */ - function create(diagnostics, only, triggerKind) { - var result = { - diagnostics: diagnostics - }; - if (only !== undefined && only !== null) { - result.only = only; - } - if (triggerKind !== undefined && triggerKind !== null) { - result.triggerKind = triggerKind; - } - return result; - } - CodeActionContext.create = create; - /** - * Checks whether the given literal conforms to the {@link CodeActionContext} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic); - } - CodeActionContext.is = is; - })(CodeActionContext || (exports.CodeActionContext = CodeActionContext = {})); - var CodeAction; - (function (CodeAction) { - function create(title, kindOrCommandOrEdit, kind) { - var result = { - title: title - }; - var checkKind = true; - if (typeof kindOrCommandOrEdit === 'string') { - checkKind = false; - result.kind = kindOrCommandOrEdit; - } else if (Command.is(kindOrCommandOrEdit)) { - result.command = kindOrCommandOrEdit; - } else { - result.edit = kindOrCommandOrEdit; - } - if (checkKind && kind !== undefined) { - result.kind = kind; - } - return result; - } - CodeAction.create = create; - function is(value) { - var candidate = value; - return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)); - } - CodeAction.is = is; - })(CodeAction || (exports.CodeAction = CodeAction = {})); - /** - * The CodeLens namespace provides helper functions to work with - * {@link CodeLens} literals. - */ - var CodeLens; - (function (CodeLens) { - /** - * Creates a new CodeLens literal. - */ - function create(range, data) { - var result = { - range: range - }; - if (Is.defined(data)) { - result.data = data; - } - return result; - } - CodeLens.create = create; - /** - * Checks whether the given literal conforms to the {@link CodeLens} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command)); - } - CodeLens.is = is; - })(CodeLens || (exports.CodeLens = CodeLens = {})); - /** - * The FormattingOptions namespace provides helper functions to work with - * {@link FormattingOptions} literals. - */ - var FormattingOptions; - (function (FormattingOptions) { - /** - * Creates a new FormattingOptions literal. - */ - function create(tabSize, insertSpaces) { - return { - tabSize: tabSize, - insertSpaces: insertSpaces - }; - } - FormattingOptions.create = create; - /** - * Checks whether the given literal conforms to the {@link FormattingOptions} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces); - } - FormattingOptions.is = is; - })(FormattingOptions || (exports.FormattingOptions = FormattingOptions = {})); - /** - * The DocumentLink namespace provides helper functions to work with - * {@link DocumentLink} literals. - */ - var DocumentLink; - (function (DocumentLink) { - /** - * Creates a new DocumentLink literal. - */ - function create(range, target, data) { - return { - range: range, - target: target, - data: data - }; - } - DocumentLink.create = create; - /** - * Checks whether the given literal conforms to the {@link DocumentLink} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target)); - } - DocumentLink.is = is; - })(DocumentLink || (exports.DocumentLink = DocumentLink = {})); - /** - * The SelectionRange namespace provides helper function to work with - * SelectionRange literals. - */ - var SelectionRange; - (function (SelectionRange) { - /** - * Creates a new SelectionRange - * @param range the range. - * @param parent an optional parent. - */ - function create(range, parent) { - return { - range: range, - parent: parent - }; - } - SelectionRange.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent)); - } - SelectionRange.is = is; - })(SelectionRange || (exports.SelectionRange = SelectionRange = {})); - /** - * A set of predefined token types. This set is not fixed - * an clients can specify additional token types via the - * corresponding client capabilities. - * - * @since 3.16.0 - */ - var SemanticTokenTypes; - (function (SemanticTokenTypes) { - SemanticTokenTypes["namespace"] = "namespace"; - /** - * Represents a generic type. Acts as a fallback for types which can't be mapped to - * a specific type like class or enum. - */ - SemanticTokenTypes["type"] = "type"; - SemanticTokenTypes["class"] = "class"; - SemanticTokenTypes["enum"] = "enum"; - SemanticTokenTypes["interface"] = "interface"; - SemanticTokenTypes["struct"] = "struct"; - SemanticTokenTypes["typeParameter"] = "typeParameter"; - SemanticTokenTypes["parameter"] = "parameter"; - SemanticTokenTypes["variable"] = "variable"; - SemanticTokenTypes["property"] = "property"; - SemanticTokenTypes["enumMember"] = "enumMember"; - SemanticTokenTypes["event"] = "event"; - SemanticTokenTypes["function"] = "function"; - SemanticTokenTypes["method"] = "method"; - SemanticTokenTypes["macro"] = "macro"; - SemanticTokenTypes["keyword"] = "keyword"; - SemanticTokenTypes["modifier"] = "modifier"; - SemanticTokenTypes["comment"] = "comment"; - SemanticTokenTypes["string"] = "string"; - SemanticTokenTypes["number"] = "number"; - SemanticTokenTypes["regexp"] = "regexp"; - SemanticTokenTypes["operator"] = "operator"; - /** - * @since 3.17.0 - */ - SemanticTokenTypes["decorator"] = "decorator"; - })(SemanticTokenTypes || (exports.SemanticTokenTypes = SemanticTokenTypes = {})); - /** - * A set of predefined token modifiers. This set is not fixed - * an clients can specify additional token types via the - * corresponding client capabilities. - * - * @since 3.16.0 - */ - var SemanticTokenModifiers; - (function (SemanticTokenModifiers) { - SemanticTokenModifiers["declaration"] = "declaration"; - SemanticTokenModifiers["definition"] = "definition"; - SemanticTokenModifiers["readonly"] = "readonly"; - SemanticTokenModifiers["static"] = "static"; - SemanticTokenModifiers["deprecated"] = "deprecated"; - SemanticTokenModifiers["abstract"] = "abstract"; - SemanticTokenModifiers["async"] = "async"; - SemanticTokenModifiers["modification"] = "modification"; - SemanticTokenModifiers["documentation"] = "documentation"; - SemanticTokenModifiers["defaultLibrary"] = "defaultLibrary"; - })(SemanticTokenModifiers || (exports.SemanticTokenModifiers = SemanticTokenModifiers = {})); - /** - * @since 3.16.0 - */ - var SemanticTokens; - (function (SemanticTokens) { - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === 'string') && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number'); - } - SemanticTokens.is = is; - })(SemanticTokens || (exports.SemanticTokens = SemanticTokens = {})); - /** - * The InlineValueText namespace provides functions to deal with InlineValueTexts. - * - * @since 3.17.0 - */ - var InlineValueText; - (function (InlineValueText) { - /** - * Creates a new InlineValueText literal. - */ - function create(range, text) { - return { - range: range, - text: text - }; - } - InlineValueText.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text); - } - InlineValueText.is = is; - })(InlineValueText || (exports.InlineValueText = InlineValueText = {})); - /** - * The InlineValueVariableLookup namespace provides functions to deal with InlineValueVariableLookups. - * - * @since 3.17.0 - */ - var InlineValueVariableLookup; - (function (InlineValueVariableLookup) { - /** - * Creates a new InlineValueText literal. - */ - function create(range, variableName, caseSensitiveLookup) { - return { - range: range, - variableName: variableName, - caseSensitiveLookup: caseSensitiveLookup - }; - } - InlineValueVariableLookup.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === undefined); - } - InlineValueVariableLookup.is = is; - })(InlineValueVariableLookup || (exports.InlineValueVariableLookup = InlineValueVariableLookup = {})); - /** - * The InlineValueEvaluatableExpression namespace provides functions to deal with InlineValueEvaluatableExpression. - * - * @since 3.17.0 - */ - var InlineValueEvaluatableExpression; - (function (InlineValueEvaluatableExpression) { - /** - * Creates a new InlineValueEvaluatableExpression literal. - */ - function create(range, expression) { - return { - range: range, - expression: expression - }; - } - InlineValueEvaluatableExpression.create = create; - function is(value) { - var candidate = value; - return candidate !== undefined && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === undefined); - } - InlineValueEvaluatableExpression.is = is; - })(InlineValueEvaluatableExpression || (exports.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {})); - /** - * The InlineValueContext namespace provides helper functions to work with - * {@link InlineValueContext} literals. - * - * @since 3.17.0 - */ - var InlineValueContext; - (function (InlineValueContext) { - /** - * Creates a new InlineValueContext literal. - */ - function create(frameId, stoppedLocation) { - return { - frameId: frameId, - stoppedLocation: stoppedLocation - }; - } - InlineValueContext.create = create; - /** - * Checks whether the given literal conforms to the {@link InlineValueContext} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Range.is(value.stoppedLocation); - } - InlineValueContext.is = is; - })(InlineValueContext || (exports.InlineValueContext = InlineValueContext = {})); - /** - * Inlay hint kinds. - * - * @since 3.17.0 - */ - var InlayHintKind; - (function (InlayHintKind) { - /** - * An inlay hint that for a type annotation. - */ - InlayHintKind.Type = 1; - /** - * An inlay hint that is for a parameter. - */ - InlayHintKind.Parameter = 2; - function is(value) { - return value === 1 || value === 2; - } - InlayHintKind.is = is; - })(InlayHintKind || (exports.InlayHintKind = InlayHintKind = {})); - var InlayHintLabelPart; - (function (InlayHintLabelPart) { - function create(value) { - return { - value: value - }; - } - InlayHintLabelPart.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === undefined || Location.is(candidate.location)) && (candidate.command === undefined || Command.is(candidate.command)); - } - InlayHintLabelPart.is = is; - })(InlayHintLabelPart || (exports.InlayHintLabelPart = InlayHintLabelPart = {})); - var InlayHint; - (function (InlayHint) { - function create(position, label, kind) { - var result = { - position: position, - label: label - }; - if (kind !== undefined) { - result.kind = kind; - } - return result; - } - InlayHint.create = create; - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === undefined || InlayHintKind.is(candidate.kind)) && candidate.textEdits === undefined || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight)); - } - InlayHint.is = is; - })(InlayHint || (exports.InlayHint = InlayHint = {})); - var WorkspaceFolder; - (function (WorkspaceFolder) { - function is(value) { - var candidate = value; - return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name); - } - WorkspaceFolder.is = is; - })(WorkspaceFolder || (exports.WorkspaceFolder = WorkspaceFolder = {})); - var EOL = exports.EOL = ['\n', '\r\n', '\r']; - /** - * @deprecated Use the text document from the new vscode-languageserver-textdocument package. - */ - var TextDocument; - (function (TextDocument) { - /** - * Creates a new ITextDocument literal from the given uri and content. - * @param uri The document's uri. - * @param languageId The document's language Id. - * @param version The document's version. - * @param content The document's content. - */ - function create(uri, languageId, version, content) { - return new FullTextDocument(uri, languageId, version, content); - } - TextDocument.create = create; - /** - * Checks whether the given literal conforms to the {@link ITextDocument} interface. - */ - function is(value) { - var candidate = value; - return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false; - } - TextDocument.is = is; - function applyEdits(document, edits) { - var text = document.getText(); - var sortedEdits = mergeSort(edits, function (a, b) { - var diff = a.range.start.line - b.range.start.line; - if (diff === 0) { - return a.range.start.character - b.range.start.character; - } - return diff; - }); - var lastModifiedOffset = text.length; - for (var i = sortedEdits.length - 1; i >= 0; i--) { - var e = sortedEdits[i]; - var startOffset = document.offsetAt(e.range.start); - var endOffset = document.offsetAt(e.range.end); - if (endOffset <= lastModifiedOffset) { - text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length); - } else { - throw new Error('Overlapping edit'); - } - lastModifiedOffset = startOffset; - } - return text; - } - TextDocument.applyEdits = applyEdits; - function mergeSort(data, compare) { - if (data.length <= 1) { - // sorted - return data; - } - var p = data.length / 2 | 0; - var left = data.slice(0, p); - var right = data.slice(p); - mergeSort(left, compare); - mergeSort(right, compare); - var leftIdx = 0; - var rightIdx = 0; - var i = 0; - while (leftIdx < left.length && rightIdx < right.length) { - var ret = compare(left[leftIdx], right[rightIdx]); - if (ret <= 0) { - // smaller_equal -> take left to preserve order - data[i++] = left[leftIdx++]; - } else { - // greater -> take right - data[i++] = right[rightIdx++]; - } - } - while (leftIdx < left.length) { - data[i++] = left[leftIdx++]; - } - while (rightIdx < right.length) { - data[i++] = right[rightIdx++]; - } - return data; - } - })(TextDocument || (exports.TextDocument = TextDocument = {})); - /** - * @deprecated Use the text document from the new vscode-languageserver-textdocument package. - */ - var FullTextDocument = /** @class */function () { - function FullTextDocument(uri, languageId, version, content) { - this._uri = uri; - this._languageId = languageId; - this._version = version; - this._content = content; - this._lineOffsets = undefined; - } - Object.defineProperty(FullTextDocument.prototype, "uri", { - get: function () { - return this._uri; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "languageId", { - get: function () { - return this._languageId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(FullTextDocument.prototype, "version", { - get: function () { - return this._version; - }, - enumerable: false, - configurable: true - }); - FullTextDocument.prototype.getText = function (range) { - if (range) { - var start = this.offsetAt(range.start); - var end = this.offsetAt(range.end); - return this._content.substring(start, end); - } - return this._content; - }; - FullTextDocument.prototype.update = function (event, version) { - this._content = event.text; - this._version = version; - this._lineOffsets = undefined; - }; - FullTextDocument.prototype.getLineOffsets = function () { - if (this._lineOffsets === undefined) { - var lineOffsets = []; - var text = this._content; - var isLineStart = true; - for (var i = 0; i < text.length; i++) { - if (isLineStart) { - lineOffsets.push(i); - isLineStart = false; - } - var ch = text.charAt(i); - isLineStart = ch === '\r' || ch === '\n'; - if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') { - i++; - } - } - if (isLineStart && text.length > 0) { - lineOffsets.push(text.length); - } - this._lineOffsets = lineOffsets; - } - return this._lineOffsets; - }; - FullTextDocument.prototype.positionAt = function (offset) { - offset = Math.max(Math.min(offset, this._content.length), 0); - var lineOffsets = this.getLineOffsets(); - var low = 0, - high = lineOffsets.length; - if (high === 0) { - return Position.create(0, offset); - } - while (low < high) { - var mid = Math.floor((low + high) / 2); - if (lineOffsets[mid] > offset) { - high = mid; - } else { - low = mid + 1; - } - } - // low is the least x for which the line offset is larger than the current offset - // or array.length if no line offset is larger than the current offset - var line = low - 1; - return Position.create(line, offset - lineOffsets[line]); - }; - FullTextDocument.prototype.offsetAt = function (position) { - var lineOffsets = this.getLineOffsets(); - if (position.line >= lineOffsets.length) { - return this._content.length; - } else if (position.line < 0) { - return 0; - } - var lineOffset = lineOffsets[position.line]; - var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length; - return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset); - }; - Object.defineProperty(FullTextDocument.prototype, "lineCount", { - get: function () { - return this.getLineOffsets().length; - }, - enumerable: false, - configurable: true - }); - return FullTextDocument; - }(); - var Is; - (function (Is) { - var toString = Object.prototype.toString; - function defined(value) { - return typeof value !== 'undefined'; - } - Is.defined = defined; - function undefined(value) { - return typeof value === 'undefined'; - } - Is.undefined = undefined; - function boolean(value) { - return value === true || value === false; - } - Is.boolean = boolean; - function string(value) { - return toString.call(value) === '[object String]'; - } - Is.string = string; - function number(value) { - return toString.call(value) === '[object Number]'; - } - Is.number = number; - function numberRange(value, min, max) { - return toString.call(value) === '[object Number]' && min <= value && value <= max; - } - Is.numberRange = numberRange; - function integer(value) { - return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647; - } - Is.integer = integer; - function uinteger(value) { - return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647; - } - Is.uinteger = uinteger; - function func(value) { - return toString.call(value) === '[object Function]'; - } - Is.func = func; - function objectLiteral(value) { - // Strictly speaking class instances pass this check as well. Since the LSP - // doesn't use classes we ignore this for now. If we do we need to add something - // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` - return value !== null && typeof value === 'object'; - } - Is.objectLiteral = objectLiteral; - function typedArray(value, check) { - return Array.isArray(value) && value.every(check); - } - Is.typedArray = typedArray; - })(Is || (Is = {})); - - /***/ }), - - /***/ "../../graphiql-react/dist/SchemaReference.cjs.js": - /*!********************************************************!*\ - !*** ../../graphiql-react/dist/SchemaReference.cjs.js ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); - function getTypeInfo(schema, tokenState) { - const info = { - schema, - type: null, - parentType: null, - inputType: null, - directiveDef: null, - fieldDef: null, - argDef: null, - argDefs: null, - objectFieldDefs: null - }; - forEachState.forEachState(tokenState, state => { - var _a, _b; - switch (state.kind) { - case "Query": - case "ShortQuery": - info.type = schema.getQueryType(); - break; - case "Mutation": - info.type = schema.getMutationType(); - break; - case "Subscription": - info.type = schema.getSubscriptionType(); - break; - case "InlineFragment": - case "FragmentDefinition": - if (state.type) { - info.type = schema.getType(state.type); - } - break; - case "Field": - case "AliasedField": - info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null; - info.type = (_a = info.fieldDef) === null || _a === void 0 ? void 0 : _a.type; - break; - case "SelectionSet": - info.parentType = info.type ? graphql.getNamedType(info.type) : null; - break; - case "Directive": - info.directiveDef = state.name ? schema.getDirective(state.name) : null; - break; - case "Arguments": - const parentDef = state.prevState ? state.prevState.kind === "Field" ? info.fieldDef : state.prevState.kind === "Directive" ? info.directiveDef : state.prevState.kind === "AliasedField" ? state.prevState.name && getFieldDef(schema, info.parentType, state.prevState.name) : null : null; - info.argDefs = parentDef ? parentDef.args : null; - break; - case "Argument": - info.argDef = null; - if (info.argDefs) { - for (let i = 0; i < info.argDefs.length; i++) { - if (info.argDefs[i].name === state.name) { - info.argDef = info.argDefs[i]; - break; - } - } - } - info.inputType = (_b = info.argDef) === null || _b === void 0 ? void 0 : _b.type; - break; - case "EnumValue": - const enumType = info.inputType ? graphql.getNamedType(info.inputType) : null; - info.enumValue = enumType instanceof graphql.GraphQLEnumType ? find(enumType.getValues(), val => val.value === state.name) : null; - break; - case "ListValue": - const nullableType = info.inputType ? graphql.getNullableType(info.inputType) : null; - info.inputType = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; - break; - case "ObjectValue": - const objectType = info.inputType ? graphql.getNamedType(info.inputType) : null; - info.objectFieldDefs = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; - break; - case "ObjectField": - const objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null; - info.inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; - info.fieldDef = objectField; - break; - case "NamedType": - info.type = state.name ? schema.getType(state.name) : null; - break; - } - }); - return info; - } - function getFieldDef(schema, type, fieldName) { - if (fieldName === graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { - return graphql.SchemaMetaFieldDef; - } - if (fieldName === graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { - return graphql.TypeMetaFieldDef; - } - if (fieldName === graphql.TypeNameMetaFieldDef.name && graphql.isCompositeType(type)) { - return graphql.TypeNameMetaFieldDef; - } - if (type && type.getFields) { - return type.getFields()[fieldName]; - } - } - function find(array, predicate) { - for (let i = 0; i < array.length; i++) { - if (predicate(array[i])) { - return array[i]; - } - } - } - function getFieldReference(typeInfo) { - return { - kind: "Field", - schema: typeInfo.schema, - field: typeInfo.fieldDef, - type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType - }; - } - function getDirectiveReference(typeInfo) { - return { - kind: "Directive", - schema: typeInfo.schema, - directive: typeInfo.directiveDef - }; - } - function getArgumentReference(typeInfo) { - return typeInfo.directiveDef ? { - kind: "Argument", - schema: typeInfo.schema, - argument: typeInfo.argDef, - directive: typeInfo.directiveDef - } : { - kind: "Argument", - schema: typeInfo.schema, - argument: typeInfo.argDef, - field: typeInfo.fieldDef, - type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType - }; - } - function getEnumValueReference(typeInfo) { - return { - kind: "EnumValue", - value: typeInfo.enumValue || void 0, - type: typeInfo.inputType ? graphql.getNamedType(typeInfo.inputType) : void 0 - }; - } - function getTypeReference(typeInfo, type) { - return { - kind: "Type", - schema: typeInfo.schema, - type: type || typeInfo.type - }; - } - function isMetaField(fieldDef) { - return fieldDef.name.slice(0, 2) === "__"; - } - exports.getArgumentReference = getArgumentReference; - exports.getDirectiveReference = getDirectiveReference; - exports.getEnumValueReference = getEnumValueReference; - exports.getFieldReference = getFieldReference; - exports.getTypeInfo = getTypeInfo; - exports.getTypeReference = getTypeReference; - - /***/ }), - - /***/ "../../graphiql-react/dist/brace-fold.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/brace-fold.cjs.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var braceFold$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function bracketFolding(pairs) { - return function (cm, start) { - var line = start.line, - lineText = cm.getLine(line); - function findOpening(pair) { - var tokenType; - for (var at = start.ch, pass = 0;;) { - var found2 = at <= 0 ? -1 : lineText.lastIndexOf(pair[0], at - 1); - if (found2 == -1) { - if (pass == 1) break; - pass = 1; - at = lineText.length; - continue; - } - if (pass == 1 && found2 < start.ch) break; - tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found2 + 1)); - if (!/^(comment|string)/.test(tokenType)) return { - ch: found2 + 1, - tokenType, - pair - }; - at = found2 - 1; - } - } - function findRange(found2) { - var count = 1, - lastLine = cm.lastLine(), - end, - startCh = found2.ch, - endCh; - outer: for (var i2 = line; i2 <= lastLine; ++i2) { - var text = cm.getLine(i2), - pos = i2 == line ? startCh : 0; - for (;;) { - var nextOpen = text.indexOf(found2.pair[0], pos), - nextClose = text.indexOf(found2.pair[1], pos); - if (nextOpen < 0) nextOpen = text.length; - if (nextClose < 0) nextClose = text.length; - pos = Math.min(nextOpen, nextClose); - if (pos == text.length) break; - if (cm.getTokenTypeAt(CodeMirror.Pos(i2, pos + 1)) == found2.tokenType) { - if (pos == nextOpen) ++count;else if (! --count) { - end = i2; - endCh = pos; - break outer; - } - } - ++pos; - } - } - if (end == null || line == end) return null; - return { - from: CodeMirror.Pos(line, startCh), - to: CodeMirror.Pos(end, endCh) - }; - } - var found = []; - for (var i = 0; i < pairs.length; i++) { - var open = findOpening(pairs[i]); - if (open) found.push(open); - } - found.sort(function (a, b) { - return a.ch - b.ch; - }); - for (var i = 0; i < found.length; i++) { - var range = findRange(found[i]); - if (range) return range; - } - return null; - }; - } - CodeMirror.registerHelper("fold", "brace", bracketFolding([["{", "}"], ["[", "]"]])); - CodeMirror.registerHelper("fold", "brace-paren", bracketFolding([["{", "}"], ["[", "]"], ["(", ")"]])); - CodeMirror.registerHelper("fold", "import", function (cm, start) { - function hasImport(line) { - if (line < cm.firstLine() || line > cm.lastLine()) return null; - var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); - if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); - if (start2.type != "keyword" || start2.string != "import") return null; - for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) { - var text = cm.getLine(i), - semi = text.indexOf(";"); - if (semi != -1) return { - startCh: start2.end, - end: CodeMirror.Pos(i, semi) - }; - } - } - var startLine = start.line, - has = hasImport(startLine), - prev; - if (!has || hasImport(startLine - 1) || (prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1) return null; - for (var end = has.end;;) { - var next = hasImport(end.line + 1); - if (next == null) break; - end = next.end; - } - return { - from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), - to: end - }; - }); - CodeMirror.registerHelper("fold", "include", function (cm, start) { - function hasInclude(line) { - if (line < cm.firstLine() || line > cm.lastLine()) return null; - var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); - if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); - if (start2.type == "meta" && start2.string.slice(0, 8) == "#include") return start2.start + 8; - } - var startLine = start.line, - has = hasInclude(startLine); - if (has == null || hasInclude(startLine - 1) != null) return null; - for (var end = startLine;;) { - var next = hasInclude(end + 1); - if (next == null) break; - ++end; - } - return { - from: CodeMirror.Pos(startLine, has + 1), - to: cm.clipPos(CodeMirror.Pos(end)) - }; - }); - }); - })(); - var braceFoldExports = braceFold$2.exports; - const braceFold = /* @__PURE__ */codemirror.getDefaultExportFromCjs(braceFoldExports); - const braceFold$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: braceFold - }, [braceFoldExports]); - exports.braceFold = braceFold$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/closebrackets.cjs.js": - /*!******************************************************!*\ - !*** ../../graphiql-react/dist/closebrackets.cjs.js ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var closebrackets$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var defaults = { - pairs: `()[]{}''""`, - closeBefore: `)]}'":;>`, - triples: "", - explode: "[]{}" - }; - var Pos = CodeMirror.Pos; - CodeMirror.defineOption("autoCloseBrackets", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.removeKeyMap(keyMap); - cm.state.closeBrackets = null; - } - if (val) { - ensureBound(getOption(val, "pairs")); - cm.state.closeBrackets = val; - cm.addKeyMap(keyMap); - } - }); - function getOption(conf, name) { - if (name == "pairs" && typeof conf == "string") return conf; - if (typeof conf == "object" && conf[name] != null) return conf[name]; - return defaults[name]; - } - var keyMap = { - Backspace: handleBackspace, - Enter: handleEnter - }; - function ensureBound(chars) { - for (var i = 0; i < chars.length; i++) { - var ch = chars.charAt(i), - key = "'" + ch + "'"; - if (!keyMap[key]) keyMap[key] = handler(ch); - } - } - ensureBound(defaults.pairs + "`"); - function handler(ch) { - return function (cm) { - return handleChar(cm, ch); - }; - } - function getConfig(cm) { - var deflt = cm.state.closeBrackets; - if (!deflt || deflt.override) return deflt; - var mode = cm.getModeAt(cm.getCursor()); - return mode.closeBrackets || deflt; - } - function handleBackspace(cm) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - var pairs = getOption(conf, "pairs"); - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - for (var i = ranges.length - 1; i >= 0; i--) { - var cur = ranges[i].head; - cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); - } - } - function handleEnter(cm) { - var conf = getConfig(cm); - var explode = conf && getOption(conf, "explode"); - if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - cm.operation(function () { - var linesep = cm.lineSeparator() || "\n"; - cm.replaceSelection(linesep + linesep, null); - moveSel(cm, -1); - ranges = cm.listSelections(); - for (var i2 = 0; i2 < ranges.length; i2++) { - var line = ranges[i2].head.line; - cm.indentLine(line, null, true); - cm.indentLine(line + 1, null, true); - } - }); - } - function moveSel(cm, dir) { - var newRanges = [], - ranges = cm.listSelections(), - primary = 0; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.head == cm.getCursor()) primary = i; - var pos = range.head.ch || dir > 0 ? { - line: range.head.line, - ch: range.head.ch + dir - } : { - line: range.head.line - 1 - }; - newRanges.push({ - anchor: pos, - head: pos - }); - } - cm.setSelections(newRanges, primary); - } - function contractSelection(sel) { - var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; - return { - anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), - head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1)) - }; - } - function handleChar(cm, ch) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - var pairs = getOption(conf, "pairs"); - var pos = pairs.indexOf(ch); - if (pos == -1) return CodeMirror.Pass; - var closeBefore = getOption(conf, "closeBefore"); - var triples = getOption(conf, "triples"); - var identical = pairs.charAt(pos + 1) == ch; - var ranges = cm.listSelections(); - var opening = pos % 2 == 0; - var type; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - cur = range.head, - curType; - var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); - if (opening && !range.empty()) { - curType = "surround"; - } else if ((identical || !opening) && next == ch) { - if (identical && stringStartsAfter(cm, cur)) curType = "both";else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree";else curType = "skip"; - } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { - if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; - curType = "addFour"; - } else if (identical) { - var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur); - if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";else return CodeMirror.Pass; - } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { - curType = "both"; - } else { - return CodeMirror.Pass; - } - if (!type) type = curType;else if (type != curType) return CodeMirror.Pass; - } - var left = pos % 2 ? pairs.charAt(pos - 1) : ch; - var right = pos % 2 ? ch : pairs.charAt(pos + 1); - cm.operation(function () { - if (type == "skip") { - moveSel(cm, 1); - } else if (type == "skipThree") { - moveSel(cm, 3); - } else if (type == "surround") { - var sels = cm.getSelections(); - for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = left + sels[i2] + right; - cm.replaceSelections(sels, "around"); - sels = cm.listSelections().slice(); - for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = contractSelection(sels[i2]); - cm.setSelections(sels); - } else if (type == "both") { - cm.replaceSelection(left + right, null); - cm.triggerElectric(left + right); - moveSel(cm, -1); - } else if (type == "addFour") { - cm.replaceSelection(left + left + left + left, "before"); - moveSel(cm, 1); - } - }); - } - function charsAround(cm, pos) { - var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); - return str.length == 2 ? str : null; - } - function stringStartsAfter(cm, pos) { - var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)); - return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))); - } - }); - })(); - var closebracketsExports = closebrackets$2.exports; - const closebrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(closebracketsExports); - const closebrackets$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: closebrackets - }, [closebracketsExports]); - exports.closebrackets = closebrackets$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/codemirror.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/codemirror.cjs.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror$1 = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var codemirrorExports = codemirror$1.requireCodemirror(); - const CodeMirror = /* @__PURE__ */codemirror$1.getDefaultExportFromCjs(codemirrorExports); - const codemirror = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: CodeMirror - }, [codemirrorExports]); - exports.CodeMirror = CodeMirror; - exports.codemirror = codemirror; - - /***/ }), - - /***/ "../../graphiql-react/dist/codemirror.cjs2.js": - /*!****************************************************!*\ - !*** ../../graphiql-react/dist/codemirror.cjs2.js ***! - \****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : {}; - function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; - } - var codemirror = { - exports: {} - }; - var hasRequiredCodemirror; - function requireCodemirror() { - if (hasRequiredCodemirror) return codemirror.exports; - hasRequiredCodemirror = 1; - (function (module2, exports2) { - (function (global2, factory) { - module2.exports = factory(); - })(commonjsGlobal, function () { - var userAgent = navigator.userAgent; - var platform = navigator.platform; - var gecko = /gecko\/\d/i.test(userAgent); - var ie_upto10 = /MSIE \d/.test(userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); - var edge = /Edge\/(\d+)/.exec(userAgent); - var ie = ie_upto10 || ie_11up || edge; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); - var webkit = !edge && /WebKit\//.test(userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); - var chrome = !edge && /Chrome\//.test(userAgent); - var presto = /Opera\//.test(userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); - var phantom = /PhantomJS/.test(userAgent); - var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); - var android = /Android/.test(userAgent); - var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); - var mac = ios || /Mac/.test(platform); - var chromeOS = /\bCrOS\b/.test(userAgent); - var windows = /win/i.test(platform); - var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) { - presto_version = Number(presto_version[1]); - } - if (presto_version && presto_version >= 15) { - presto = false; - webkit = true; - } - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || ie && ie_version >= 9; - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - var rmClass = function (node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) { - e.removeChild(e.firstChild); - } - return e; - } - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) { - e.className = className; - } - if (style) { - e.style.cssText = style; - } - if (typeof content == "string") { - e.appendChild(document.createTextNode(content)); - } else if (content) { - for (var i2 = 0; i2 < content.length; ++i2) { - e.appendChild(content[i2]); - } - } - return e; - } - function eltP(tag, content, className, style) { - var e = elt(tag, content, className, style); - e.setAttribute("role", "presentation"); - return e; - } - var range; - if (document.createRange) { - range = function (node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - } else { - range = function (node, start, end) { - var r = document.body.createTextRange(); - try { - r.moveToElementText(node.parentNode); - } catch (e) { - return r; - } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - } - function contains(parent, child) { - if (child.nodeType == 3) { - child = child.parentNode; - } - if (parent.contains) { - return parent.contains(child); - } - do { - if (child.nodeType == 11) { - child = child.host; - } - if (child == parent) { - return true; - } - } while (child = child.parentNode); - } - function activeElt() { - var activeElement; - try { - activeElement = document.activeElement; - } catch (e) { - activeElement = document.body || null; - } - while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { - activeElement = activeElement.shadowRoot.activeElement; - } - return activeElement; - } - function addClass(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) { - node.className += (current ? " " : "") + cls; - } - } - function joinClasses(a, b) { - var as = a.split(" "); - for (var i2 = 0; i2 < as.length; i2++) { - if (as[i2] && !classTest(as[i2]).test(b)) { - b += " " + as[i2]; - } - } - return b; - } - var selectInput = function (node) { - node.select(); - }; - if (ios) { - selectInput = function (node) { - node.selectionStart = 0; - node.selectionEnd = node.value.length; - }; - } else if (ie) { - selectInput = function (node) { - try { - node.select(); - } catch (_e) {} - }; - } - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return f.apply(null, args); - }; - } - function copyObj(obj, target, overwrite) { - if (!target) { - target = {}; - } - for (var prop2 in obj) { - if (obj.hasOwnProperty(prop2) && (overwrite !== false || !target.hasOwnProperty(prop2))) { - target[prop2] = obj[prop2]; - } - } - return target; - } - function countColumn(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) { - end = string.length; - } - } - for (var i2 = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf(" ", i2); - if (nextTab < 0 || nextTab >= end) { - return n + (end - i2); - } - n += nextTab - i2; - n += tabSize - n % tabSize; - i2 = nextTab + 1; - } - } - var Delayed = function () { - this.id = null; - this.f = null; - this.time = 0; - this.handler = bind(this.onTimeout, this); - }; - Delayed.prototype.onTimeout = function (self2) { - self2.id = 0; - if (self2.time <= + /* @__PURE__ */new Date()) { - self2.f(); - } else { - setTimeout(self2.handler, self2.time - + /* @__PURE__ */new Date()); - } - }; - Delayed.prototype.set = function (ms, f) { - this.f = f; - var time = + /* @__PURE__ */new Date() + ms; - if (!this.id || time < this.time) { - clearTimeout(this.id); - this.id = setTimeout(this.handler, ms); - this.time = time; - } - }; - function indexOf(array, elt2) { - for (var i2 = 0; i2 < array.length; ++i2) { - if (array[i2] == elt2) { - return i2; - } - } - return -1; - } - var scrollerGap = 50; - var Pass = { - toString: function () { - return "CodeMirror.Pass"; - } - }; - var sel_dontScroll = { - scroll: false - }, - sel_mouse = { - origin: "*mouse" - }, - sel_move = { - origin: "+move" - }; - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf(" ", pos); - if (nextTab == -1) { - nextTab = string.length; - } - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) { - return pos + Math.min(skipped, goal - col); - } - col += nextTab - pos; - col += tabSize - col % tabSize; - pos = nextTab + 1; - if (col >= goal) { - return pos; - } - } - } - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) { - spaceStrs.push(lst(spaceStrs) + " "); - } - return spaceStrs[n]; - } - function lst(arr) { - return arr[arr.length - 1]; - } - function map(array, f) { - var out = []; - for (var i2 = 0; i2 < array.length; i2++) { - out[i2] = f(array[i2], i2); - } - return out; - } - function insertSorted(array, value, score) { - var pos = 0, - priority = score(value); - while (pos < array.length && score(array[pos]) <= priority) { - pos++; - } - array.splice(pos, 0, value); - } - function nothing() {} - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) { - copyObj(props, inst); - } - return inst; - } - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - function isWordCharBasic(ch) { - return /\w/.test(ch) || ch > "€" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - } - function isWordChar(ch, helper) { - if (!helper) { - return isWordCharBasic(ch); - } - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { - return true; - } - return helper.test(ch); - } - function isEmpty(obj) { - for (var n in obj) { - if (obj.hasOwnProperty(n) && obj[n]) { - return false; - } - } - return true; - } - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { - return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); - } - function skipExtendingChars(str, pos, dir) { - while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { - pos += dir; - } - return pos; - } - function findFirst(pred, from, to) { - var dir = from > to ? -1 : 1; - for (;;) { - if (from == to) { - return from; - } - var midF = (from + to) / 2, - mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); - if (mid == from) { - return pred(mid) ? from : to; - } - if (pred(mid)) { - to = mid; - } else { - from = mid + dir; - } - } - } - function iterateBidiSections(order, from, to, f) { - if (!order) { - return f(from, to, "ltr", 0); - } - var found = false; - for (var i2 = 0; i2 < order.length; ++i2) { - var part = order[i2]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2); - found = true; - } - } - if (!found) { - f(from, to, "ltr"); - } - } - var bidiOther = null; - function getBidiPartAt(order, ch, sticky) { - var found; - bidiOther = null; - for (var i2 = 0; i2 < order.length; ++i2) { - var cur = order[i2]; - if (cur.from < ch && cur.to > ch) { - return i2; - } - if (cur.to == ch) { - if (cur.from != cur.to && sticky == "before") { - found = i2; - } else { - bidiOther = i2; - } - } - if (cur.from == ch) { - if (cur.from != cur.to && sticky != "before") { - found = i2; - } else { - bidiOther = i2; - } - } - } - return found != null ? found : bidiOther; - } - var bidiOrdering = /* @__PURE__ */function () { - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; - function charType(code) { - if (code <= 247) { - return lowTypes.charAt(code); - } else if (1424 <= code && code <= 1524) { - return "R"; - } else if (1536 <= code && code <= 1785) { - return arabicTypes.charAt(code - 1536); - } else if (1774 <= code && code <= 2220) { - return "r"; - } else if (8192 <= code && code <= 8203) { - return "w"; - } else if (code == 8204) { - return "b"; - } else { - return "L"; - } - } - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, - isStrong = /[LRr]/, - countsAsLeft = /[Lb1n]/, - countsAsNum = /[1n]/; - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; - this.to = to; - } - return function (str, direction) { - var outerType = direction == "ltr" ? "L" : "R"; - if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { - return false; - } - var len = str.length, - types = []; - for (var i2 = 0; i2 < len; ++i2) { - types.push(charType(str.charCodeAt(i2))); - } - for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) { - var type = types[i$12]; - if (type == "m") { - types[i$12] = prev; - } else { - prev = type; - } - } - for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) { - var type$1 = types[i$22]; - if (type$1 == "1" && cur == "r") { - types[i$22] = "n"; - } else if (isStrong.test(type$1)) { - cur = type$1; - if (type$1 == "r") { - types[i$22] = "R"; - } - } - } - for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { - var type$2 = types[i$3]; - if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { - types[i$3] = "1"; - } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) { - types[i$3] = prev$1; - } - prev$1 = type$2; - } - for (var i$4 = 0; i$4 < len; ++i$4) { - var type$3 = types[i$4]; - if (type$3 == ",") { - types[i$4] = "N"; - } else if (type$3 == "%") { - var end = void 0; - for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} - var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N"; - for (var j = i$4; j < end; ++j) { - types[j] = replace; - } - i$4 = end - 1; - } - } - for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { - var type$4 = types[i$5]; - if (cur$1 == "L" && type$4 == "1") { - types[i$5] = "L"; - } else if (isStrong.test(type$4)) { - cur$1 = type$4; - } - } - for (var i$6 = 0; i$6 < len; ++i$6) { - if (isNeutral.test(types[i$6])) { - var end$1 = void 0; - for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} - var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; - var after = (end$1 < len ? types[end$1] : outerType) == "L"; - var replace$1 = before == after ? before ? "L" : "R" : outerType; - for (var j$1 = i$6; j$1 < end$1; ++j$1) { - types[j$1] = replace$1; - } - i$6 = end$1 - 1; - } - } - var order = [], - m; - for (var i$7 = 0; i$7 < len;) { - if (countsAsLeft.test(types[i$7])) { - var start = i$7; - for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} - order.push(new BidiSpan(0, start, i$7)); - } else { - var pos = i$7, - at = order.length, - isRTL = direction == "rtl" ? 1 : 0; - for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} - for (var j$2 = pos; j$2 < i$7;) { - if (countsAsNum.test(types[j$2])) { - if (pos < j$2) { - order.splice(at, 0, new BidiSpan(1, pos, j$2)); - at += isRTL; - } - var nstart = j$2; - for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} - order.splice(at, 0, new BidiSpan(2, nstart, j$2)); - at += isRTL; - pos = j$2; - } else { - ++j$2; - } - } - if (pos < i$7) { - order.splice(at, 0, new BidiSpan(1, pos, i$7)); - } - } - } - if (direction == "ltr") { - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - } - return direction == "rtl" ? order.reverse() : order; - }; - }(); - function getOrder(line, direction) { - var order = line.order; - if (order == null) { - order = line.order = bidiOrdering(line.text, direction); - } - return order; - } - var noHandlers = []; - var on = function (emitter, type, f) { - if (emitter.addEventListener) { - emitter.addEventListener(type, f, false); - } else if (emitter.attachEvent) { - emitter.attachEvent("on" + type, f); - } else { - var map2 = emitter._handlers || (emitter._handlers = {}); - map2[type] = (map2[type] || noHandlers).concat(f); - } - }; - function getHandlers(emitter, type) { - return emitter._handlers && emitter._handlers[type] || noHandlers; - } - function off(emitter, type, f) { - if (emitter.removeEventListener) { - emitter.removeEventListener(type, f, false); - } else if (emitter.detachEvent) { - emitter.detachEvent("on" + type, f); - } else { - var map2 = emitter._handlers, - arr = map2 && map2[type]; - if (arr) { - var index = indexOf(arr, f); - if (index > -1) { - map2[type] = arr.slice(0, index).concat(arr.slice(index + 1)); - } - } - } - } - function signal(emitter, type) { - var handlers = getHandlers(emitter, type); - if (!handlers.length) { - return; - } - var args = Array.prototype.slice.call(arguments, 2); - for (var i2 = 0; i2 < handlers.length; ++i2) { - handlers[i2].apply(null, args); - } - } - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") { - e = { - type: e, - preventDefault: function () { - this.defaultPrevented = true; - } - }; - } - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) { - return; - } - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i2 = 0; i2 < arr.length; ++i2) { - if (indexOf(set, arr[i2]) == -1) { - set.push(arr[i2]); - } - } - } - function hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0; - } - function eventMixin(ctor) { - ctor.prototype.on = function (type, f) { - on(this, type, f); - }; - ctor.prototype.off = function (type, f) { - off(this, type, f); - }; - } - function e_preventDefault(e) { - if (e.preventDefault) { - e.preventDefault(); - } else { - e.returnValue = false; - } - } - function e_stopPropagation(e) { - if (e.stopPropagation) { - e.stopPropagation(); - } else { - e.cancelBubble = true; - } - } - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - function e_stop(e) { - e_preventDefault(e); - e_stopPropagation(e); - } - function e_target(e) { - return e.target || e.srcElement; - } - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) { - b = 1; - } else if (e.button & 2) { - b = 3; - } else if (e.button & 4) { - b = 2; - } - } - if (mac && e.ctrlKey && b == 1) { - b = 3; - } - return b; - } - var dragAndDrop = function () { - if (ie && ie_version < 9) { - return false; - } - var div = elt("div"); - return "draggable" in div || "dragDrop" in div; - }(); - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "​"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) { - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - } - var node = zwspSupported ? elt("span", "​") : elt("span", " ", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) { - return badBidiRects; - } - var txt = removeChildrenAndAdd(measure, document.createTextNode("AخA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - var r1 = range(txt, 1, 2).getBoundingClientRect(); - removeChildren(measure); - if (!r0 || r0.left == r0.right) { - return false; - } - return badBidiRects = r1.right - r0.right < 3; - } - var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { - var pos = 0, - result = [], - l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) { - nl = string.length; - } - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function (string) { - return string.split(/\r\n?|\n/); - }; - var hasSelection = window.getSelection ? function (te) { - try { - return te.selectionStart != te.selectionEnd; - } catch (e) { - return false; - } - } : function (te) { - var range2; - try { - range2 = te.ownerDocument.selection.createRange(); - } catch (e) {} - if (!range2 || range2.parentElement() != te) { - return false; - } - return range2.compareEndPoints("StartToEnd", range2) != 0; - }; - var hasCopyEvent = function () { - var e = elt("div"); - if ("oncopy" in e) { - return true; - } - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - }(); - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) { - return badZoomedRects; - } - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - var modes = {}, - mimeModes = {}; - function defineMode(name, mode) { - if (arguments.length > 2) { - mode.dependencies = Array.prototype.slice.call(arguments, 2); - } - modes[name] = mode; - } - function defineMIME(mime, spec) { - mimeModes[mime] = spec; - } - function resolveMode(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") { - found = { - name: found - }; - } - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return resolveMode("application/xml"); - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { - return resolveMode("application/json"); - } - if (typeof spec == "string") { - return { - name: spec - }; - } else { - return spec || { - name: "null" - }; - } - } - function getMode(options, spec) { - spec = resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) { - return getMode(options, "text/plain"); - } - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop2 in exts) { - if (!exts.hasOwnProperty(prop2)) { - continue; - } - if (modeObj.hasOwnProperty(prop2)) { - modeObj["_" + prop2] = modeObj[prop2]; - } - modeObj[prop2] = exts[prop2]; - } - } - modeObj.name = spec.name; - if (spec.helperType) { - modeObj.helperType = spec.helperType; - } - if (spec.modeProps) { - for (var prop$1 in spec.modeProps) { - modeObj[prop$1] = spec.modeProps[prop$1]; - } - } - return modeObj; - } - var modeExtensions = {}; - function extendMode(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {}; - copyObj(properties, exts); - } - function copyState(mode, state) { - if (state === true) { - return state; - } - if (mode.copyState) { - return mode.copyState(state); - } - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) { - val = val.concat([]); - } - nstate[n] = val; - } - return nstate; - } - function innerMode(mode, state) { - var info; - while (mode.innerMode) { - info = mode.innerMode(state); - if (!info || info.mode == mode) { - break; - } - state = info.state; - mode = info.mode; - } - return info || { - mode, - state - }; - } - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - } - var StringStream = function (string, tabSize, lineOracle) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - this.lineOracle = lineOracle; - }; - StringStream.prototype.eol = function () { - return this.pos >= this.string.length; - }; - StringStream.prototype.sol = function () { - return this.pos == this.lineStart; - }; - StringStream.prototype.peek = function () { - return this.string.charAt(this.pos) || void 0; - }; - StringStream.prototype.next = function () { - if (this.pos < this.string.length) { - return this.string.charAt(this.pos++); - } - }; - StringStream.prototype.eat = function (match) { - var ch = this.string.charAt(this.pos); - var ok; - if (typeof match == "string") { - ok = ch == match; - } else { - ok = ch && (match.test ? match.test(ch) : match(ch)); - } - if (ok) { - ++this.pos; - return ch; - } - }; - StringStream.prototype.eatWhile = function (match) { - var start = this.pos; - while (this.eat(match)) {} - return this.pos > start; - }; - StringStream.prototype.eatSpace = function () { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { - ++this.pos; - } - return this.pos > start; - }; - StringStream.prototype.skipToEnd = function () { - this.pos = this.string.length; - }; - StringStream.prototype.skipTo = function (ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) { - this.pos = found; - return true; - } - }; - StringStream.prototype.backUp = function (n) { - this.pos -= n; - }; - StringStream.prototype.column = function () { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }; - StringStream.prototype.indentation = function () { - return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }; - StringStream.prototype.match = function (pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function (str) { - return caseInsensitive ? str.toLowerCase() : str; - }; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) { - this.pos += pattern.length; - } - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) { - return null; - } - if (match && consume !== false) { - this.pos += match[0].length; - } - return match; - } - }; - StringStream.prototype.current = function () { - return this.string.slice(this.start, this.pos); - }; - StringStream.prototype.hideFirstChars = function (n, inner) { - this.lineStart += n; - try { - return inner(); - } finally { - this.lineStart -= n; - } - }; - StringStream.prototype.lookAhead = function (n) { - var oracle = this.lineOracle; - return oracle && oracle.lookAhead(n); - }; - StringStream.prototype.baseToken = function () { - var oracle = this.lineOracle; - return oracle && oracle.baseToken(this.pos); - }; - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) { - throw new Error("There is no line " + (n + doc.first) + " in the document."); - } - var chunk = doc; - while (!chunk.lines) { - for (var i2 = 0;; ++i2) { - var child = chunk.children[i2], - sz = child.chunkSize(); - if (n < sz) { - chunk = child; - break; - } - n -= sz; - } - } - return chunk.lines[n]; - } - function getBetween(doc, start, end) { - var out = [], - n = start.line; - doc.iter(start.line, end.line + 1, function (line) { - var text = line.text; - if (n == end.line) { - text = text.slice(0, end.ch); - } - if (n == start.line) { - text = text.slice(start.ch); - } - out.push(text); - ++n; - }); - return out; - } - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function (line) { - out.push(line.text); - }); - return out; - } - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) { - for (var n = line; n; n = n.parent) { - n.height += diff; - } - } - } - function lineNo(line) { - if (line.parent == null) { - return null; - } - var cur = line.parent, - no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i2 = 0;; ++i2) { - if (chunk.children[i2] == cur) { - break; - } - no += chunk.children[i2].chunkSize(); - } - } - return no + cur.first; - } - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) { - var child = chunk.children[i$12], - ch = child.height; - if (h < ch) { - chunk = child; - continue outer; - } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - var i2 = 0; - for (; i2 < chunk.lines.length; ++i2) { - var line = chunk.lines[i2], - lh = line.height; - if (h < lh) { - break; - } - h -= lh; - } - return n + i2; - } - function isLine(doc, l) { - return l >= doc.first && l < doc.first + doc.size; - } - function lineNumberFor(options, i2) { - return String(options.lineNumberFormatter(i2 + options.firstLineNumber)); - } - function Pos(line, ch, sticky) { - if (sticky === void 0) sticky = null; - if (!(this instanceof Pos)) { - return new Pos(line, ch, sticky); - } - this.line = line; - this.ch = ch; - this.sticky = sticky; - } - function cmp(a, b) { - return a.line - b.line || a.ch - b.ch; - } - function equalCursorPos(a, b) { - return a.sticky == b.sticky && cmp(a, b) == 0; - } - function copyPos(x) { - return Pos(x.line, x.ch); - } - function maxPos(a, b) { - return cmp(a, b) < 0 ? b : a; - } - function minPos(a, b) { - return cmp(a, b) < 0 ? a : b; - } - function clipLine(doc, n) { - return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)); - } - function clipPos(doc, pos) { - if (pos.line < doc.first) { - return Pos(doc.first, 0); - } - var last = doc.first + doc.size - 1; - if (pos.line > last) { - return Pos(last, getLine(doc, last).text.length); - } - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) { - return Pos(pos.line, linelen); - } else if (ch < 0) { - return Pos(pos.line, 0); - } else { - return pos; - } - } - function clipPosArray(doc, array) { - var out = []; - for (var i2 = 0; i2 < array.length; i2++) { - out[i2] = clipPos(doc, array[i2]); - } - return out; - } - var SavedContext = function (state, lookAhead) { - this.state = state; - this.lookAhead = lookAhead; - }; - var Context = function (doc, state, line, lookAhead) { - this.state = state; - this.doc = doc; - this.line = line; - this.maxLookAhead = lookAhead || 0; - this.baseTokens = null; - this.baseTokenPos = 1; - }; - Context.prototype.lookAhead = function (n) { - var line = this.doc.getLine(this.line + n); - if (line != null && n > this.maxLookAhead) { - this.maxLookAhead = n; - } - return line; - }; - Context.prototype.baseToken = function (n) { - if (!this.baseTokens) { - return null; - } - while (this.baseTokens[this.baseTokenPos] <= n) { - this.baseTokenPos += 2; - } - var type = this.baseTokens[this.baseTokenPos + 1]; - return { - type: type && type.replace(/( |^)overlay .*/, ""), - size: this.baseTokens[this.baseTokenPos] - n - }; - }; - Context.prototype.nextLine = function () { - this.line++; - if (this.maxLookAhead > 0) { - this.maxLookAhead--; - } - }; - Context.fromSaved = function (doc, saved, line) { - if (saved instanceof SavedContext) { - return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead); - } else { - return new Context(doc, copyState(doc.mode, saved), line); - } - }; - Context.prototype.save = function (copy) { - var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; - return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state; - }; - function highlightLine(cm, line, context, forceToEnd) { - var st = [cm.state.modeGen], - lineClasses = {}; - runMode(cm, line.text, cm.doc.mode, context, function (end, style) { - return st.push(end, style); - }, lineClasses, forceToEnd); - var state = context.state; - var loop = function (o2) { - context.baseTokens = st; - var overlay = cm.state.overlays[o2], - i2 = 1, - at = 0; - context.state = true; - runMode(cm, line.text, overlay.mode, context, function (end, style) { - var start = i2; - while (at < end) { - var i_end = st[i2]; - if (i_end > end) { - st.splice(i2, 1, end, st[i2 + 1], i_end); - } - i2 += 2; - at = Math.min(end, i_end); - } - if (!style) { - return; - } - if (overlay.opaque) { - st.splice(start, i2 - start, end, "overlay " + style); - i2 = start + 2; - } else { - for (; start < i2; start += 2) { - var cur = st[start + 1]; - st[start + 1] = (cur ? cur + " " : "") + "overlay " + style; - } - } - }, lineClasses); - context.state = state; - context.baseTokens = null; - context.baseTokenPos = 1; - }; - for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); - return { - styles: st, - classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null - }; - } - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var context = getContextBefore(cm, lineNo(line)); - var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); - var result = highlightLine(cm, line, context); - if (resetState) { - context.state = resetState; - } - line.stateAfter = context.save(!resetState); - line.styles = result.styles; - if (result.classes) { - line.styleClasses = result.classes; - } else if (line.styleClasses) { - line.styleClasses = null; - } - if (updateFrontier === cm.doc.highlightFrontier) { - cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); - } - } - return line.styles; - } - function getContextBefore(cm, n, precise) { - var doc = cm.doc, - display = cm.display; - if (!doc.mode.startState) { - return new Context(doc, true, n); - } - var start = findStartLine(cm, n, precise); - var saved = start > doc.first && getLine(doc, start - 1).stateAfter; - var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); - doc.iter(start, n, function (line) { - processLine(cm, line.text, context); - var pos = context.line; - line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; - context.nextLine(); - }); - if (precise) { - doc.modeFrontier = context.line; - } - return context; - } - function processLine(cm, text, context, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize, context); - stream.start = stream.pos = startAt || 0; - if (text == "") { - callBlankLine(mode, context.state); - } - while (!stream.eol()) { - readToken(mode, stream, context.state); - stream.start = stream.pos; - } - } - function callBlankLine(mode, state) { - if (mode.blankLine) { - return mode.blankLine(state); - } - if (!mode.innerMode) { - return; - } - var inner = innerMode(mode, state); - if (inner.mode.blankLine) { - return inner.mode.blankLine(inner.state); - } - } - function readToken(mode, stream, state, inner) { - for (var i2 = 0; i2 < 10; i2++) { - if (inner) { - inner[0] = innerMode(mode, state).mode; - } - var style = mode.token(stream, state); - if (stream.pos > stream.start) { - return style; - } - } - throw new Error("Mode " + mode.name + " failed to advance stream."); - } - var Token = function (stream, type, state) { - this.start = stream.start; - this.end = stream.pos; - this.string = stream.current(); - this.type = type || null; - this.state = state; - }; - function takeToken(cm, pos, precise, asArray) { - var doc = cm.doc, - mode = doc.mode, - style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), - context = getContextBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize, context), - tokens; - if (asArray) { - tokens = []; - } - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, context.state); - if (asArray) { - tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); - } - } - return asArray ? tokens : new Token(stream, style, context.state); - } - function extractLineClasses(type, output) { - if (type) { - for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) { - break; - } - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop2 = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop2] == null) { - output[prop2] = lineClass[2]; - } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop2])) { - output[prop2] += " " + lineClass[2]; - } - } - } - return type; - } - function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) { - flattenSpans = cm.options.flattenSpans; - } - var curStart = 0, - curStyle = null; - var stream = new StringStream(text, cm.options.tabSize, context), - style; - var inner = cm.options.addModeClass && [null]; - if (text == "") { - extractLineClasses(callBlankLine(mode, context.state), lineClasses); - } - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) { - processLine(cm, text, context, stream.pos); - } - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) { - style = "m-" + (style ? mName + " " + style : mName); - } - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 5e3); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - var pos = Math.min(stream.pos, curStart + 5e3); - f(pos, curStyle); - curStart = pos; - } - } - function findStartLine(cm, n, precise) { - var minindent, - minline, - doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) { - return doc.first; - } - var line = getLine(doc, search - 1), - after = line.stateAfter; - if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { - return search; - } - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - function retreatFrontier(doc, n) { - doc.modeFrontier = Math.min(doc.modeFrontier, n); - if (doc.highlightFrontier < n - 10) { - return; - } - var start = doc.first; - for (var line = n - 1; line > start; line--) { - var saved = getLine(doc, line).stateAfter; - if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { - start = line + 1; - break; - } - } - doc.highlightFrontier = Math.min(doc.highlightFrontier, start); - } - var sawReadOnlySpans = false, - sawCollapsedSpans = false; - function seeReadOnlySpans() { - sawReadOnlySpans = true; - } - function seeCollapsedSpans() { - sawCollapsedSpans = true; - } - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; - this.to = to; - } - function getMarkedSpanFor(spans, marker) { - if (spans) { - for (var i2 = 0; i2 < spans.length; ++i2) { - var span = spans[i2]; - if (span.marker == marker) { - return span; - } - } - } - } - function removeMarkedSpan(spans, span) { - var r; - for (var i2 = 0; i2 < spans.length; ++i2) { - if (spans[i2] != span) { - (r || (r = [])).push(spans[i2]); - } - } - return r; - } - function addMarkedSpan(line, span, op) { - var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = /* @__PURE__ */new WeakSet())); - if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { - line.markedSpans.push(span); - } else { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - if (inThisOp) { - inThisOp.add(line.markedSpans); - } - } - span.marker.attachLine(line); - } - function markedSpansBefore(old, startCh, isInsert) { - var nw; - if (old) { - for (var i2 = 0; i2 < old.length; ++i2) { - var span = old[i2], - marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } - } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - var nw; - if (old) { - for (var i2 = 0; i2 < old.length; ++i2) { - var span = old[i2], - marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); - } - } - } - return nw; - } - function stretchSpansOverChange(doc, change) { - if (change.full) { - return null; - } - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) { - return null; - } - var startCh = change.from.ch, - endCh = change.to.ch, - isInsert = cmp(change.from, change.to) == 0; - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - var sameLine = change.text.length == 1, - offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - for (var i2 = 0; i2 < first.length; ++i2) { - var span = first[i2]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) { - span.to = startCh; - } else if (sameLine) { - span.to = found.to == null ? null : found.to + offset; - } - } - } - } - if (last) { - for (var i$12 = 0; i$12 < last.length; ++i$12) { - var span$1 = last[i$12]; - if (span$1.to != null) { - span$1.to += offset; - } - if (span$1.from == null) { - var found$1 = getMarkedSpanFor(first, span$1.marker); - if (!found$1) { - span$1.from = offset; - if (sameLine) { - (first || (first = [])).push(span$1); - } - } - } else { - span$1.from += offset; - if (sameLine) { - (first || (first = [])).push(span$1); - } - } - } - } - if (first) { - first = clearEmptySpans(first); - } - if (last && last != first) { - last = clearEmptySpans(last); - } - var newMarkers = [first]; - if (!sameLine) { - var gap = change.text.length - 2, - gapMarkers; - if (gap > 0 && first) { - for (var i$22 = 0; i$22 < first.length; ++i$22) { - if (first[i$22].to == null) { - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null)); - } - } - } - for (var i$3 = 0; i$3 < gap; ++i$3) { - newMarkers.push(gapMarkers); - } - newMarkers.push(last); - } - return newMarkers; - } - function clearEmptySpans(spans) { - for (var i2 = 0; i2 < spans.length; ++i2) { - var span = spans[i2]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { - spans.splice(i2--, 1); - } - } - if (!spans.length) { - return null; - } - return spans; - } - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function (line) { - if (line.markedSpans) { - for (var i3 = 0; i3 < line.markedSpans.length; ++i3) { - var mark = line.markedSpans[i3].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { - (markers || (markers = [])).push(mark); - } - } - } - }); - if (!markers) { - return null; - } - var parts = [{ - from, - to - }]; - for (var i2 = 0; i2 < markers.length; ++i2) { - var mk = markers[i2], - m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { - continue; - } - var newParts = [j, 1], - dfrom = cmp(p.from, m.from), - dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { - newParts.push({ - from: p.from, - to: m.from - }); - } - if (dto > 0 || !mk.inclusiveRight && !dto) { - newParts.push({ - from: m.to, - to: p.to - }); - } - parts.splice.apply(parts, newParts); - j += newParts.length - 3; - } - } - return parts; - } - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) { - return; - } - for (var i2 = 0; i2 < spans.length; ++i2) { - spans[i2].marker.detachLine(line); - } - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) { - return; - } - for (var i2 = 0; i2 < spans.length; ++i2) { - spans[i2].marker.attachLine(line); - } - line.markedSpans = spans; - } - function extraLeft(marker) { - return marker.inclusiveLeft ? -1 : 0; - } - function extraRight(marker) { - return marker.inclusiveRight ? 1 : 0; - } - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) { - return lenDiff; - } - var aPos = a.find(), - bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) { - return -fromCmp; - } - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) { - return toCmp; - } - return b.id - a.id; - } - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, - found; - if (sps) { - for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { - sp = sps[i2]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { - found = sp.marker; - } - } - } - return found; - } - function collapsedSpanAtStart(line) { - return collapsedSpanAtSide(line, true); - } - function collapsedSpanAtEnd(line) { - return collapsedSpanAtSide(line, false); - } - function collapsedSpanAround(line, ch) { - var sps = sawCollapsedSpans && line.markedSpans, - found; - if (sps) { - for (var i2 = 0; i2 < sps.length; ++i2) { - var sp = sps[i2]; - if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { - found = sp.marker; - } - } - } - return found; - } - function conflictingCollapsedRange(doc, lineNo2, from, to, marker) { - var line = getLine(doc, lineNo2); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { - for (var i2 = 0; i2 < sps.length; ++i2) { - var sp = sps[i2]; - if (!sp.marker.collapsed) { - continue; - } - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { - continue; - } - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { - return true; - } - } - } - } - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) { - line = merged.find(-1, true).line; - } - return line; - } - function visualLineEnd(line) { - var merged; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - } - return line; - } - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), - vis = visualLine(line); - if (line == vis) { - return lineN; - } - return lineNo(vis); - } - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) { - return lineN; - } - var line = getLine(doc, lineN), - merged; - if (!lineIsHidden(doc, line)) { - return lineN; - } - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - } - return lineNo(line) + 1; - } - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { - for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { - sp = sps[i2]; - if (!sp.marker.collapsed) { - continue; - } - if (sp.from == null) { - return true; - } - if (sp.marker.widgetNode) { - continue; - } - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { - return true; - } - } - } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) { - return true; - } - for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) { - sp = line.markedSpans[i2]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { - return true; - } - } - } - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - var h = 0, - chunk = lineObj.parent; - for (var i2 = 0; i2 < chunk.lines.length; ++i2) { - var line = chunk.lines[i2]; - if (line == lineObj) { - break; - } else { - h += line.height; - } - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i$12 = 0; i$12 < p.children.length; ++i$12) { - var cur = p.children[i$12]; - if (cur == chunk) { - break; - } else { - h += cur.height; - } - } - } - return h; - } - function lineLength(line) { - if (line.height == 0) { - return 0; - } - var len = line.text.length, - merged, - cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found$1 = merged.find(0, true); - len -= cur.text.length - found$1.from.ch; - cur = found$1.to.line; - len += cur.text.length - found$1.to.ch; - } - return len; - } - function findMaxLine(cm) { - var d = cm.display, - doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function (line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - var Line = function (text, markedSpans, estimateHeight2) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight2 ? estimateHeight2(this) : 1; - }; - Line.prototype.lineNo = function () { - return lineNo(this); - }; - eventMixin(Line); - function updateLine(line, text, markedSpans, estimateHeight2) { - line.text = text; - if (line.stateAfter) { - line.stateAfter = null; - } - if (line.styles) { - line.styles = null; - } - if (line.order != null) { - line.order = null; - } - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight2 ? estimateHeight2(line) : 1; - if (estHeight != line.height) { - updateLineHeight(line, estHeight); - } - } - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - var styleToClassCache = {}, - styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) { - return null; - } - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - function buildLineContent(cm, lineView) { - var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = { - pre: eltP("pre", [content], "CodeMirror-line"), - content, - col: 0, - pos: 0, - cm, - trailingSpace: false, - splitSpaces: cm.getOption("lineWrapping") - }; - lineView.measure = {}; - for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) { - var line = i2 ? lineView.rest[i2 - 1] : lineView.line, - order = void 0; - builder.pos = 0; - builder.addToken = buildToken; - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { - builder.addToken = buildTokenBadBidi(builder.addToken, order); - } - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) { - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - } - if (line.styleClasses.textClass) { - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - } - if (builder.map.length == 0) { - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - } - if (i2 == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - if (webkit) { - var last = builder.content.lastChild; - if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) { - builder.content.className = "cm-tab-wrap-hack"; - } - } - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) { - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - } - return builder; - } - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "•", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { - if (!text) { - return; - } - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; - var special = builder.cm.state.specialChars, - mustWrap = false; - var content; - if (!special.test(text)) { - builder.col += text.length; - content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) { - mustWrap = true; - } - builder.pos += text.length; - } else { - content = document.createDocumentFragment(); - var pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) { - content.appendChild(elt("span", [txt])); - } else { - content.appendChild(txt); - } - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) { - break; - } - pos += skipped + 1; - var txt$1 = void 0; - if (m[0] == " ") { - var tabSize = builder.cm.options.tabSize, - tabWidth = tabSize - builder.col % tabSize; - txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt$1.setAttribute("role", "presentation"); - txt$1.setAttribute("cm-text", " "); - builder.col += tabWidth; - } else if (m[0] == "\r" || m[0] == "\n") { - txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar")); - txt$1.setAttribute("cm-text", m[0]); - builder.col += 1; - } else { - txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); - txt$1.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) { - content.appendChild(elt("span", [txt$1])); - } else { - content.appendChild(txt$1); - } - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt$1); - builder.pos++; - } - } - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; - if (style || startStyle || endStyle || mustWrap || css || attributes) { - var fullStyle = style || ""; - if (startStyle) { - fullStyle += startStyle; - } - if (endStyle) { - fullStyle += endStyle; - } - var token = elt("span", [content], fullStyle, css); - if (attributes) { - for (var attr in attributes) { - if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { - token.setAttribute(attr, attributes[attr]); - } - } - } - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - function splitSpaces(text, trailingBefore) { - if (text.length > 1 && !/ /.test(text)) { - return text; - } - var spaceBefore = trailingBefore, - result = ""; - for (var i2 = 0; i2 < text.length; i2++) { - var ch = text.charAt(i2); - if (ch == " " && spaceBefore && (i2 == text.length - 1 || text.charCodeAt(i2 + 1) == 32)) { - ch = " "; - } - result += ch; - spaceBefore = ch == " "; - } - return result; - } - function buildTokenBadBidi(inner, order) { - return function (builder, text, style, startStyle, endStyle, css, attributes) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, - end = start + text.length; - for (;;) { - var part = void 0; - for (var i2 = 0; i2 < order.length; i2++) { - part = order[i2]; - if (part.to > start && part.from <= start) { - break; - } - } - if (part.to >= end) { - return inner(builder, text, style, startStyle, endStyle, css, attributes); - } - inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) { - builder.map.push(builder.pos, builder.pos + size, widget); - } - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) { - widget = builder.content.appendChild(document.createElement("span")); - } - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - builder.trailingSpace = false; - } - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, - allText = line.text, - at = 0; - if (!spans) { - for (var i$12 = 1; i$12 < styles.length; i$12 += 2) { - builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options)); - } - return; - } - var len = allText.length, - pos = 0, - i2 = 1, - text = "", - style, - css; - var nextChange = 0, - spanStyle, - spanEndStyle, - spanStartStyle, - collapsed, - attributes; - for (;;) { - if (nextChange == pos) { - spanStyle = spanEndStyle = spanStartStyle = css = ""; - attributes = null; - collapsed = null; - nextChange = Infinity; - var foundBookmarks = [], - endStyles = void 0; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], - m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) { - spanStyle += " " + m.className; - } - if (m.css) { - css = (css ? css + ";" : "") + m.css; - } - if (m.startStyle && sp.from == pos) { - spanStartStyle += " " + m.startStyle; - } - if (m.endStyle && sp.to == nextChange) { - (endStyles || (endStyles = [])).push(m.endStyle, sp.to); - } - if (m.title) { - (attributes || (attributes = {})).title = m.title; - } - if (m.attributes) { - for (var attr in m.attributes) { - (attributes || (attributes = {}))[attr] = m.attributes[attr]; - } - } - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { - collapsed = sp; - } - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (endStyles) { - for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { - if (endStyles[j$1 + 1] == nextChange) { - spanEndStyle += " " + endStyles[j$1]; - } - } - } - if (!collapsed || collapsed.from == pos) { - for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { - buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); - } - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); - if (collapsed.to == null) { - return; - } - if (collapsed.to == pos) { - collapsed = false; - } - } - } - if (pos >= len) { - break; - } - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); - } - if (end >= upto) { - text = text.slice(upto - pos); - pos = upto; - break; - } - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i2++]); - style = interpretTokenStyle(styles[i2++], builder.cm.options); - } - } - } - function LineView(doc, line, lineN) { - this.line = line; - this.rest = visualLineContinued(line); - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - function buildViewArray(cm, from, to) { - var array = [], - nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array; - } - var operationGroup = null; - function pushOperation(op) { - if (operationGroup) { - operationGroup.ops.push(op); - } else { - op.ownsGroup = operationGroup = { - ops: [op], - delayedCallbacks: [] - }; - } - } - function fireCallbacksForOps(group) { - var callbacks = group.delayedCallbacks, - i2 = 0; - do { - for (; i2 < callbacks.length; i2++) { - callbacks[i2].call(null); - } - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) { - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { - op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); - } - } - } - } while (i2 < callbacks.length); - } - function finishOperation(op, endCb) { - var group = op.ownsGroup; - if (!group) { - return; - } - try { - fireCallbacksForOps(group); - } finally { - operationGroup = null; - endCb(group); - } - } - var orphanDelayedCallbacks = null; - function signalLater(emitter, type) { - var arr = getHandlers(emitter, type); - if (!arr.length) { - return; - } - var args = Array.prototype.slice.call(arguments, 2), - list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - var loop = function (i3) { - list.push(function () { - return arr[i3].apply(null, args); - }); - }; - for (var i2 = 0; i2 < arr.length; ++i2) loop(i2); - } - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i2 = 0; i2 < delayed.length; ++i2) { - delayed[i2](); - } - } - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") { - updateLineText(cm, lineView); - } else if (type == "gutter") { - updateLineGutter(cm, lineView, lineN, dims); - } else if (type == "class") { - updateLineClasses(cm, lineView); - } else if (type == "widget") { - updateLineWidgets(cm, lineView, dims); - } - } - lineView.changes = null; - } - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) { - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - } - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) { - lineView.node.style.zIndex = 2; - } - } - return lineView.node; - } - function updateLineBackground(cm, lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) { - cls += " CodeMirror-linebackground"; - } - if (lineView.background) { - if (cls) { - lineView.background.className = cls; - } else { - lineView.background.parentNode.removeChild(lineView.background); - lineView.background = null; - } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - cm.display.input.setUneditable(lineView.background); - } - } - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) { - lineView.node = built.pre; - } - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(cm, lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - function updateLineClasses(cm, lineView) { - updateLineBackground(cm, lineView); - if (lineView.line.wrapClass) { - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - } else if (lineView.node != lineView.text) { - lineView.node.className = ""; - } - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - if (lineView.gutterBackground) { - lineView.node.removeChild(lineView.gutterBackground); - lineView.gutterBackground = null; - } - if (lineView.line.gutterClass) { - var wrap = ensureLineWrapped(lineView); - lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px"); - cm.display.input.setUneditable(lineView.gutterBackground); - wrap.insertBefore(lineView.gutterBackground, lineView.text); - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap$1 = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); - gutterWrap.setAttribute("aria-hidden", "true"); - cm.display.input.setUneditable(gutterWrap); - wrap$1.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) { - gutterWrap.className += " " + lineView.line.gutterClass; - } - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { - lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px")); - } - if (markers) { - for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { - var id = cm.display.gutterSpecs[k].className, - found = markers.hasOwnProperty(id) && markers[id]; - if (found) { - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); - } - } - } - } - } - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) { - lineView.alignable = null; - } - var isWidget = classTest("CodeMirror-linewidget"); - for (var node = lineView.node.firstChild, next = void 0; node; node = next) { - next = node.nextSibling; - if (isWidget.test(node.className)) { - lineView.node.removeChild(node); - } - } - insertLineWidgets(cm, lineView, dims); - } - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) { - lineView.bgClass = built.bgClass; - } - if (built.textClass) { - lineView.textClass = built.textClass; - } - updateLineClasses(cm, lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; - } - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) { - for (var i2 = 0; i2 < lineView.rest.length; i2++) { - insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false); - } - } - } - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) { - return; - } - var wrap = ensureLineWrapped(lineView); - for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) { - var widget = ws[i2], - node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); - if (!widget.handleMouseEvents) { - node.setAttribute("cm-ignore-events", "true"); - } - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) { - wrap.insertBefore(node, lineView.gutter || lineView.text); - } else { - wrap.appendChild(node); - } - signalLater(widget, "redraw"); - } - } - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) { - node.style.marginLeft = -dims.gutterTotalWidth + "px"; - } - } - } - function widgetHeight(widget) { - if (widget.height != null) { - return widget.height; - } - var cm = widget.doc.cm; - if (!cm) { - return 0; - } - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) { - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; - } - if (widget.noHScroll) { - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; - } - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.parentNode.offsetHeight; - } - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) { - return true; - } - } - } - function paddingTop(display) { - return display.lineSpace.offsetTop; - } - function paddingVert(display) { - return display.mover.offsetHeight - display.lineSpace.offsetHeight; - } - function paddingH(display) { - if (display.cachedPaddingH) { - return display.cachedPaddingH; - } - var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = { - left: parseInt(style.paddingLeft), - right: parseInt(style.paddingRight) - }; - if (!isNaN(data.left) && !isNaN(data.right)) { - display.cachedPaddingH = data; - } - return data; - } - function scrollGap(cm) { - return scrollerGap - cm.display.nativeBarWidth; - } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; - } - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i2 = 0; i2 < rects.length - 1; i2++) { - var cur = rects[i2], - next = rects[i2 + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) { - heights.push((cur.bottom + next.top) / 2 - rect.top); - } - } - } - heights.push(rect.bottom - rect.top); - } - } - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) { - return { - map: lineView.measure.map, - cache: lineView.measure.cache - }; - } - if (lineView.rest) { - for (var i2 = 0; i2 < lineView.rest.length; i2++) { - if (lineView.rest[i2] == line) { - return { - map: lineView.measure.maps[i2], - cache: lineView.measure.caches[i2] - }; - } - } - for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) { - if (lineNo(lineView.rest[i$12]) > lineN) { - return { - map: lineView.measure.maps[i$12], - cache: lineView.measure.caches[i$12], - before: true - }; - } - } - } - } - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { - return cm.display.view[findViewIndex(cm, lineN)]; - } - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { - return ext; - } - } - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) { - view = null; - } else if (view && view.changes) { - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - cm.curOp.forceUpdate = true; - } - if (!view) { - view = updateExternalMeasurement(cm, line); - } - var info = mapFromLineView(view, line, lineN); - return { - line, - view, - rect: null, - map: info.map, - cache: info.cache, - before: info.before, - hasHeights: false - }; - } - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) { - ch = -1; - } - var key = ch + (bias || ""), - found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) { - prepared.rect = prepared.view.text.getBoundingClientRect(); - } - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) { - prepared.cache[key] = found; - } - } - return { - left: found.left, - right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom - }; - } - var nullRect = { - left: 0, - right: 0, - top: 0, - bottom: 0 - }; - function nodeAndOffsetInLineMap(map2, ch, bias) { - var node, start, end, collapse, mStart, mEnd; - for (var i2 = 0; i2 < map2.length; i2 += 3) { - mStart = map2[i2]; - mEnd = map2[i2 + 1]; - if (ch < mStart) { - start = 0; - end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i2 == map2.length - 3 || ch == mEnd && map2[i2 + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) { - collapse = "right"; - } - } - if (start != null) { - node = map2[i2 + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { - collapse = bias; - } - if (bias == "left" && start == 0) { - while (i2 && map2[i2 - 2] == map2[i2 - 3] && map2[i2 - 1].insertLeft) { - node = map2[(i2 -= 3) + 2]; - collapse = "left"; - } - } - if (bias == "right" && start == mEnd - mStart) { - while (i2 < map2.length - 3 && map2[i2 + 3] == map2[i2 + 4] && !map2[i2 + 5].insertLeft) { - node = map2[(i2 += 3) + 2]; - collapse = "right"; - } - } - break; - } - } - return { - node, - start, - end, - collapse, - coverStart: mStart, - coverEnd: mEnd - }; - } - function getUsefulRect(rects, bias) { - var rect = nullRect; - if (bias == "left") { - for (var i2 = 0; i2 < rects.length; i2++) { - if ((rect = rects[i2]).left != rect.right) { - break; - } - } - } else { - for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) { - if ((rect = rects[i$12]).left != rect.right) { - break; - } - } - } - return rect; - } - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, - start = place.start, - end = place.end, - collapse = place.collapse; - var rect; - if (node.nodeType == 3) { - for (var i$12 = 0; i$12 < 4; i$12++) { - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { - --start; - } - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { - ++end; - } - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { - rect = node.parentNode.getBoundingClientRect(); - } else { - rect = getUsefulRect(range(node, start, end).getClientRects(), bias); - } - if (rect.left || rect.right || start == 0) { - break; - } - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) { - rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } - } else { - if (start > 0) { - collapse = bias = "right"; - } - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { - rect = rects[bias == "right" ? rects.length - 1 : 0]; - } else { - rect = node.getBoundingClientRect(); - } - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) { - rect = { - left: rSpan.left, - right: rSpan.left + charWidth(cm.display), - top: rSpan.top, - bottom: rSpan.bottom - }; - } else { - rect = nullRect; - } - } - var rtop = rect.top - prepared.rect.top, - rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - var i2 = 0; - for (; i2 < heights.length - 1; i2++) { - if (mid < heights[i2]) { - break; - } - } - var top = i2 ? heights[i2 - 1] : 0, - bot = heights[i2]; - var result = { - left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top, - bottom: bot - }; - if (!rect.left && !rect.right) { - result.bogus = true; - } - if (!cm.options.singleCursorHeightPerLine) { - result.rtop = rtop; - result.rbottom = rbot; - } - return result; - } - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { - return rect; - } - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return { - left: rect.left * scaleX, - right: rect.right * scaleX, - top: rect.top * scaleY, - bottom: rect.bottom * scaleY - }; - } - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) { - for (var i2 = 0; i2 < lineView.rest.length; i2++) { - lineView.measure.caches[i2] = {}; - } - } - } - } - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i2 = 0; i2 < cm.display.view.length; i2++) { - clearLineMeasurementCacheFor(cm.display.view[i2]); - } - } - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) { - cm.display.maxLineChanged = true; - } - cm.display.lineNumChars = null; - } - function pageScrollX() { - if (chrome && android) { - return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)); - } - return window.pageXOffset || (document.documentElement || document.body).scrollLeft; - } - function pageScrollY() { - if (chrome && android) { - return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)); - } - return window.pageYOffset || (document.documentElement || document.body).scrollTop; - } - function widgetTopHeight(lineObj) { - var ref = visualLine(lineObj); - var widgets = ref.widgets; - var height = 0; - if (widgets) { - for (var i2 = 0; i2 < widgets.length; ++i2) { - if (widgets[i2].above) { - height += widgetHeight(widgets[i2]); - } - } - } - return height; - } - function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { - if (!includeWidgets) { - var height = widgetTopHeight(lineObj); - rect.top += height; - rect.bottom += height; - } - if (context == "line") { - return rect; - } - if (!context) { - context = "local"; - } - var yOff = heightAtLine(lineObj); - if (context == "local") { - yOff += paddingTop(cm.display); - } else { - yOff -= cm.display.viewOffset; - } - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; - rect.right += xOff; - } - rect.top += yOff; - rect.bottom += yOff; - return rect; - } - function fromCoordSystem(cm, coords, context) { - if (context == "div") { - return coords; - } - var left = coords.left, - top = coords.top; - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return { - left: left - lineSpaceBox.left, - top: top - lineSpaceBox.top - }; - } - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) { - lineObj = getLine(cm.doc, pos.line); - } - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) { - preparedMeasure = prepareMeasureForLine(cm, lineObj); - } - function get(ch2, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch2, right ? "right" : "left", varHeight); - if (right) { - m.left = m.right; - } else { - m.right = m.left; - } - return intoCoordSystem(cm, lineObj, m, context); - } - var order = getOrder(lineObj, cm.doc.direction), - ch = pos.ch, - sticky = pos.sticky; - if (ch >= lineObj.text.length) { - ch = lineObj.text.length; - sticky = "before"; - } else if (ch <= 0) { - ch = 0; - sticky = "after"; - } - if (!order) { - return get(sticky == "before" ? ch - 1 : ch, sticky == "before"); - } - function getBidi(ch2, partPos2, invert) { - var part = order[partPos2], - right = part.level == 1; - return get(invert ? ch2 - 1 : ch2, right != invert); - } - var partPos = getBidiPartAt(order, ch, sticky); - var other = bidiOther; - var val = getBidi(ch, partPos, sticky == "before"); - if (other != null) { - val.other = getBidi(ch, other, sticky != "before"); - } - return val; - } - function estimateCoords(cm, pos) { - var left = 0; - pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) { - left = charWidth(cm.display) * pos.ch; - } - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return { - left, - right: left, - top, - bottom: top + lineObj.height - }; - } - function PosWithInfo(line, ch, sticky, outside, xRel) { - var pos = Pos(line, ch, sticky); - pos.xRel = xRel; - if (outside) { - pos.outside = outside; - } - return pos; - } - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) { - return PosWithInfo(doc.first, 0, null, -1, -1); - } - var lineN = lineAtHeight(doc, y), - last = doc.first + doc.size - 1; - if (lineN > last) { - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1); - } - if (x < 0) { - x = 0; - } - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); - if (!collapsed) { - return found; - } - var rangeEnd = collapsed.find(1); - if (rangeEnd.line == lineN) { - return rangeEnd; - } - lineObj = getLine(doc, lineN = rangeEnd.line); - } - } - function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { - y -= widgetTopHeight(lineObj); - var end = lineObj.text.length; - var begin = findFirst(function (ch) { - return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; - }, end, 0); - end = findFirst(function (ch) { - return measureCharPrepared(cm, preparedMeasure, ch).top > y; - }, begin, end); - return { - begin, - end - }; - } - function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { - if (!preparedMeasure) { - preparedMeasure = prepareMeasureForLine(cm, lineObj); - } - var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; - return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop); - } - function boxIsAfter(box, x, y, left) { - return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x; - } - function coordsCharInner(cm, lineObj, lineNo2, x, y) { - y -= heightAtLine(lineObj); - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - var widgetHeight2 = widgetTopHeight(lineObj); - var begin = 0, - end = lineObj.text.length, - ltr = true; - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x, y); - ltr = part.level != 1; - begin = ltr ? part.from : part.to - 1; - end = ltr ? part.to : part.from - 1; - } - var chAround = null, - boxAround = null; - var ch = findFirst(function (ch2) { - var box = measureCharPrepared(cm, preparedMeasure, ch2); - box.top += widgetHeight2; - box.bottom += widgetHeight2; - if (!boxIsAfter(box, x, y, false)) { - return false; - } - if (box.top <= y && box.left <= x) { - chAround = ch2; - boxAround = box; - } - return true; - }, begin, end); - var baseX, - sticky, - outside = false; - if (boxAround) { - var atLeft = x - boxAround.left < boxAround.right - x, - atStart = atLeft == ltr; - ch = chAround + (atStart ? 0 : 1); - sticky = atStart ? "after" : "before"; - baseX = atLeft ? boxAround.left : boxAround.right; - } else { - if (!ltr && (ch == end || ch == begin)) { - ch++; - } - sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y == ltr ? "after" : "before"; - var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure); - baseX = coords.left; - outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; - } - ch = skipExtendingChars(lineObj.text, ch, 1); - return PosWithInfo(lineNo2, ch, sticky, outside, x - baseX); - } - function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x, y) { - var index = findFirst(function (i2) { - var part2 = order[i2], - ltr2 = part2.level != 1; - return boxIsAfter(cursorCoords(cm, Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true); - }, 0, order.length - 1); - var part = order[index]; - if (index > 0) { - var ltr = part.level != 1; - var start = cursorCoords(cm, Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); - if (boxIsAfter(start, x, y, true) && start.top > y) { - part = order[index - 1]; - } - } - return part; - } - function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { - var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); - var begin = ref.begin; - var end = ref.end; - if (/\s/.test(lineObj.text.charAt(end - 1))) { - end--; - } - var part = null, - closestDist = null; - for (var i2 = 0; i2 < order.length; i2++) { - var p = order[i2]; - if (p.from >= end || p.to <= begin) { - continue; - } - var ltr = p.level != 1; - var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; - var dist = endX < x ? x - endX + 1e9 : endX - x; - if (!part || closestDist > dist) { - part = p; - closestDist = dist; - } - } - if (!part) { - part = order[order.length - 1]; - } - if (part.from < begin) { - part = { - from: begin, - to: part.to, - level: part.level - }; - } - if (part.to > end) { - part = { - from: part.from, - to: end, - level: part.level - }; - } - return part; - } - var measureText; - function textHeight(display) { - if (display.cachedTextHeight != null) { - return display.cachedTextHeight; - } - if (measureText == null) { - measureText = elt("pre", null, "CodeMirror-line-like"); - for (var i2 = 0; i2 < 49; ++i2) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) { - display.cachedTextHeight = height; - } - removeChildren(display.measure); - return height || 1; - } - function charWidth(display) { - if (display.cachedCharWidth != null) { - return display.cachedCharWidth; - } - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor], "CodeMirror-line-like"); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), - width = (rect.right - rect.left) / 10; - if (width > 2) { - display.cachedCharWidth = width; - } - return width || 10; - } - function getDimensions(cm) { - var d = cm.display, - left = {}, - width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) { - var id = cm.display.gutterSpecs[i2].className; - left[id] = n.offsetLeft + n.clientLeft + gutterLeft; - width[id] = n.clientWidth; - } - return { - fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth - }; - } - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - function estimateHeight(cm) { - var th = textHeight(cm.display), - wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function (line) { - if (lineIsHidden(cm.doc, line)) { - return 0; - } - var widgetsHeight = 0; - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; i2++) { - if (line.widgets[i2].height) { - widgetsHeight += line.widgets[i2].height; - } - } - } - if (wrapping) { - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; - } else { - return widgetsHeight + th; - } - }; - } - function estimateLineHeights(cm) { - var doc = cm.doc, - est = estimateHeight(cm); - doc.iter(function (line) { - var estHeight = est(line); - if (estHeight != line.height) { - updateLineHeight(line, estHeight); - } - }); - } - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { - return null; - } - var x, - y, - space = display.lineSpace.getBoundingClientRect(); - try { - x = e.clientX - space.left; - y = e.clientY - space.top; - } catch (e$1) { - return null; - } - var coords = coordsChar(cm, x, y), - line; - if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) { - return null; - } - n -= cm.display.viewFrom; - if (n < 0) { - return null; - } - var view = cm.display.view; - for (var i2 = 0; i2 < view.length; i2++) { - n -= view[i2].size; - if (n < 0) { - return i2; - } - } - } - function regChange(cm, from, to, lendiff) { - if (from == null) { - from = cm.doc.first; - } - if (to == null) { - to = cm.doc.first + cm.doc.size; - } - if (!lendiff) { - lendiff = 0; - } - var display = cm.display; - if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { - display.updateLineNumbers = from; - } - cm.curOp.viewChanged = true; - if (from >= display.viewTo) { - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { - resetView(cm); - } - } else if (to <= display.viewFrom) { - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { - resetView(cm); - } else if (from <= display.viewFrom) { - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { - var cut$1 = viewCuttingPoint(cm, from, from, -1); - if (cut$1) { - display.view = display.view.slice(0, cut$1.index); - display.viewTo = cut$1.lineN; - } else { - resetView(cm); - } - } else { - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) { - ext.lineN += lendiff; - } else if (from < ext.lineN + ext.size) { - display.externalMeasured = null; - } - } - } - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, - ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { - display.externalMeasured = null; - } - if (line < display.viewFrom || line >= display.viewTo) { - return; - } - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) { - return; - } - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) { - arr.push(type); - } - } - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), - diff, - view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { - return { - index, - lineN: newN - }; - } - var n = cm.display.viewFrom; - for (var i2 = 0; i2 < index; i2++) { - n += view[i2].size; - } - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) { - return null; - } - diff = n + view[index].size - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; - newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) { - return null; - } - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return { - index, - lineN: newN - }; - } - function adjustView(cm, from, to) { - var display = cm.display, - view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) { - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - } else if (display.viewFrom < from) { - display.view = display.view.slice(findViewIndex(cm, from)); - } - display.viewFrom = from; - if (display.viewTo < to) { - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - } else if (display.viewTo > to) { - display.view = display.view.slice(0, findViewIndex(cm, to)); - } - } - display.viewTo = to; - } - function countDirtyView(cm) { - var view = cm.display.view, - dirty = 0; - for (var i2 = 0; i2 < view.length; i2++) { - var lineView = view[i2]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) { - ++dirty; - } - } - return dirty; - } - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - function prepareSelection(cm, primary) { - if (primary === void 0) primary = true; - var doc = cm.doc, - result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - var customCursor = cm.options.$customCursor; - if (customCursor) { - primary = true; - } - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - if (!primary && i2 == doc.sel.primIndex) { - continue; - } - var range2 = doc.sel.ranges[i2]; - if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) { - continue; - } - var collapsed = range2.empty(); - if (customCursor) { - var head = customCursor(cm, range2); - if (head) { - drawSelectionCursor(cm, head, curFragment); - } - } else if (collapsed || cm.options.showCursorWhenSelecting) { - drawSelectionCursor(cm, range2.head, curFragment); - } - if (!collapsed) { - drawSelectionRange(cm, range2, selFragment); - } - } - return result; - } - function drawSelectionCursor(cm, head, output) { - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); - var cursor = output.appendChild(elt("div", " ", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { - var charPos = charCoords(cm, head, "div", null, null); - var width = charPos.right - charPos.left; - cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; - } - if (pos.other) { - var otherCursor = output.appendChild(elt("div", " ", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px"; - } - } - function cmpCoords(a, b) { - return a.top - b.top || a.left - b.left; - } - function drawSelectionRange(cm, range2, output) { - var display = cm.display, - doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), - leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - var docLTR = doc.direction == "ltr"; - function add(left, top, width, bottom) { - if (top < 0) { - top = 0; - } - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")); - } - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } - function wrapX(pos, dir, side) { - var extent = wrappedLineExtentChar(cm, lineObj, null, pos); - var prop2 = dir == "ltr" == (side == "after") ? "left" : "right"; - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); - return coords(ch, prop2)[prop2]; - } - var order = getOrder(lineObj, doc.direction); - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i2) { - var ltr = dir == "ltr"; - var fromPos = coords(from, ltr ? "left" : "right"); - var toPos = coords(to - 1, ltr ? "right" : "left"); - var openStart = fromArg == null && from == 0, - openEnd = toArg == null && to == lineLen; - var first = i2 == 0, - last = !order || i2 == order.length - 1; - if (toPos.top - fromPos.top <= 3) { - var openLeft = (docLTR ? openStart : openEnd) && first; - var openRight = (docLTR ? openEnd : openStart) && last; - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; - add(left, fromPos.top, right - left, fromPos.bottom); - } else { - var topLeft, topRight, botLeft, botRight; - if (ltr) { - topLeft = docLTR && openStart && first ? leftSide : fromPos.left; - topRight = docLTR ? rightSide : wrapX(from, dir, "before"); - botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); - botRight = docLTR && openEnd && last ? rightSide : toPos.right; - } else { - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); - topRight = !docLTR && openStart && first ? rightSide : fromPos.right; - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; - botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); - } - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); - if (fromPos.bottom < toPos.top) { - add(leftSide, fromPos.bottom, null, toPos.top); - } - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); - } - if (!start || cmpCoords(fromPos, start) < 0) { - start = fromPos; - } - if (cmpCoords(toPos, start) < 0) { - start = toPos; - } - if (!end || cmpCoords(fromPos, end) < 0) { - end = fromPos; - } - if (cmpCoords(toPos, end) < 0) { - end = toPos; - } - }); - return { - start, - end - }; - } - var sFrom = range2.from(), - sTo = range2.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), - toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) { - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - } - output.appendChild(fragment); - } - function restartBlink(cm) { - if (!cm.state.focused) { - return; - } - var display = cm.display; - clearInterval(display.blinker); - var on2 = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) { - display.blinker = setInterval(function () { - if (!cm.hasFocus()) { - onBlur(cm); - } - display.cursorDiv.style.visibility = (on2 = !on2) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - } else if (cm.options.cursorBlinkRate < 0) { - display.cursorDiv.style.visibility = "hidden"; - } - } - function ensureFocus(cm) { - if (!cm.hasFocus()) { - cm.display.input.focus(); - if (!cm.state.focused) { - onFocus(cm); - } - } - } - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function () { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - if (cm.state.focused) { - onBlur(cm); - } - } - }, 100); - } - function onFocus(cm, e) { - if (cm.state.delayingBlurEvent && !cm.state.draggingText) { - cm.state.delayingBlurEvent = false; - } - if (cm.options.readOnly == "nocursor") { - return; - } - if (!cm.state.focused) { - signal(cm, "focus", cm, e); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) { - setTimeout(function () { - return cm.display.input.reset(true); - }, 20); - } - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm, e) { - if (cm.state.delayingBlurEvent) { - return; - } - if (cm.state.focused) { - signal(cm, "blur", cm, e); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function () { - if (!cm.state.focused) { - cm.display.shift = false; - } - }, 150); - } - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); - var oldHeight = display.lineDiv.getBoundingClientRect().top; - var mustScroll = 0; - for (var i2 = 0; i2 < display.view.length; i2++) { - var cur = display.view[i2], - wrapping = cm.options.lineWrapping; - var height = void 0, - width = 0; - if (cur.hidden) { - continue; - } - oldHeight += cur.line.height; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - if (!wrapping && cur.text.firstChild) { - width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; - } - } - var diff = cur.line.height - height; - if (diff > 5e-3 || diff < -5e-3) { - if (oldHeight < viewTop) { - mustScroll -= diff; - } - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) { - for (var j = 0; j < cur.rest.length; j++) { - updateWidgetHeight(cur.rest[j]); - } - } - } - if (width > cm.display.sizerWidth) { - var chWidth = Math.ceil(width / charWidth(cm.display)); - if (chWidth > cm.display.maxLineLength) { - cm.display.maxLineLength = chWidth; - cm.display.maxLine = cur.line; - cm.display.maxLineChanged = true; - } - } - } - if (Math.abs(mustScroll) > 2) { - display.scroller.scrollTop += mustScroll; - } - } - function updateWidgetHeight(line) { - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; ++i2) { - var w = line.widgets[i2], - parent = w.node.parentNode; - if (parent) { - w.height = parent.offsetHeight; - } - } - } - } - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - var from = lineAtHeight(doc, top), - to = lineAtHeight(doc, bottom); - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, - ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return { - from, - to: Math.max(to, from + 1) - }; - } - function maybeScrollWindow(cm, rect) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) { - return; - } - var display = cm.display, - box = display.sizer.getBoundingClientRect(), - doScroll = null; - if (rect.top + box.top < 0) { - doScroll = true; - } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { - doScroll = false; - } - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "​", null, "position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) { - margin = 0; - } - var rect; - if (!cm.options.lineWrapping && pos == end) { - end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; - pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; - } - for (var limit = 0; limit < 5; limit++) { - var changed = false; - var coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - rect = { - left: Math.min(coords.left, endCoords.left), - top: Math.min(coords.top, endCoords.top) - margin, - right: Math.max(coords.left, endCoords.left), - bottom: Math.max(coords.bottom, endCoords.bottom) + margin - }; - var scrollPos = calculateScrollPos(cm, rect); - var startTop = cm.doc.scrollTop, - startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) { - changed = true; - } - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { - changed = true; - } - } - if (!changed) { - break; - } - } - return rect; - } - function scrollIntoView(cm, rect) { - var scrollPos = calculateScrollPos(cm, rect); - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - } - } - function calculateScrollPos(cm, rect) { - var display = cm.display, - snapMargin = textHeight(cm.display); - if (rect.top < 0) { - rect.top = 0; - } - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen2 = displayHeight(cm), - result = {}; - if (rect.bottom - rect.top > screen2) { - rect.bottom = rect.top + screen2; - } - var docBottom = cm.doc.height + paddingVert(display); - var atTop = rect.top < snapMargin, - atBottom = rect.bottom > docBottom - snapMargin; - if (rect.top < screentop) { - result.scrollTop = atTop ? 0 : rect.top; - } else if (rect.bottom > screentop + screen2) { - var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2); - if (newTop != screentop) { - result.scrollTop = newTop; - } - } - var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; - var screenw = displayWidth(cm) - display.gutters.offsetWidth; - var tooWide = rect.right - rect.left > screenw; - if (tooWide) { - rect.right = rect.left + screenw; - } - if (rect.left < 10) { - result.scrollLeft = 0; - } else if (rect.left < screenleft) { - result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); - } else if (rect.right > screenw + screenleft - 3) { - result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; - } - return result; - } - function addToScrollTop(cm, top) { - if (top == null) { - return; - } - resolveScrollToPos(cm); - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(); - cm.curOp.scrollToPos = { - from: cur, - to: cur, - margin: cm.options.cursorScrollMargin - }; - } - function scrollToCoords(cm, x, y) { - if (x != null || y != null) { - resolveScrollToPos(cm); - } - if (x != null) { - cm.curOp.scrollLeft = x; - } - if (y != null) { - cm.curOp.scrollTop = y; - } - } - function scrollToRange(cm, range2) { - resolveScrollToPos(cm); - cm.curOp.scrollToPos = range2; - } - function resolveScrollToPos(cm) { - var range2 = cm.curOp.scrollToPos; - if (range2) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range2.from), - to = estimateCoords(cm, range2.to); - scrollToCoordsRange(cm, from, to, range2.margin); - } - } - function scrollToCoordsRange(cm, from, to, margin) { - var sPos = calculateScrollPos(cm, { - left: Math.min(from.left, to.left), - top: Math.min(from.top, to.top) - margin, - right: Math.max(from.right, to.right), - bottom: Math.max(from.bottom, to.bottom) + margin - }); - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); - } - function updateScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) { - return; - } - if (!gecko) { - updateDisplaySimple(cm, { - top: val - }); - } - setScrollTop(cm, val, true); - if (gecko) { - updateDisplaySimple(cm); - } - startWorker(cm, 100); - } - function setScrollTop(cm, val, forceScroll) { - val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); - if (cm.display.scroller.scrollTop == val && !forceScroll) { - return; - } - cm.doc.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (cm.display.scroller.scrollTop != val) { - cm.display.scroller.scrollTop = val; - } - } - function setScrollLeft(cm, val, isScroller, forceScroll) { - val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); - if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { - return; - } - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) { - cm.display.scroller.scrollLeft = val; - } - cm.display.scrollbars.setScrollLeft(val); - } - function measureForScrollbars(cm) { - var d = cm.display, - gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, - clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - }; - } - var NativeScrollbars = function (place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - vert.tabIndex = horiz.tabIndex = -1; - place(vert); - place(horiz); - on(vert, "scroll", function () { - if (vert.clientHeight) { - scroll(vert.scrollTop, "vertical"); - } - }); - on(horiz, "scroll", function () { - if (horiz.clientWidth) { - scroll(horiz.scrollLeft, "horizontal"); - } - }); - this.checkedZeroWidth = false; - if (ie && ie_version < 8) { - this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - }; - NativeScrollbars.prototype.update = function (measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.scrollTop = 0; - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) { - this.zeroWidthHack(); - } - this.checkedZeroWidth = true; - } - return { - right: needsV ? sWidth : 0, - bottom: needsH ? sWidth : 0 - }; - }; - NativeScrollbars.prototype.setScrollLeft = function (pos) { - if (this.horiz.scrollLeft != pos) { - this.horiz.scrollLeft = pos; - } - if (this.disableHoriz) { - this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); - } - }; - NativeScrollbars.prototype.setScrollTop = function (pos) { - if (this.vert.scrollTop != pos) { - this.vert.scrollTop = pos; - } - if (this.disableVert) { - this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); - } - }; - NativeScrollbars.prototype.zeroWidthHack = function () { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.height = this.vert.style.width = w; - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; - this.disableHoriz = new Delayed(); - this.disableVert = new Delayed(); - }; - NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { - bar.style.pointerEvents = "auto"; - function maybeDisable() { - var box = bar.getBoundingClientRect(); - var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); - if (elt2 != bar) { - bar.style.pointerEvents = "none"; - } else { - delay.set(1e3, maybeDisable); - } - } - delay.set(1e3, maybeDisable); - }; - NativeScrollbars.prototype.clear = function () { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - }; - var NullScrollbars = function () {}; - NullScrollbars.prototype.update = function () { - return { - bottom: 0, - right: 0 - }; - }; - NullScrollbars.prototype.setScrollLeft = function () {}; - NullScrollbars.prototype.setScrollTop = function () {}; - NullScrollbars.prototype.clear = function () {}; - function updateScrollbars(cm, measure) { - if (!measure) { - measure = measureForScrollbars(cm); - } - var startWidth = cm.display.barWidth, - startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { - updateHeightsInViewport(cm); - } - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; - startHeight = cm.display.barHeight; - } - } - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else { - d.scrollbarFiller.style.display = ""; - } - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else { - d.gutterFiller.style.display = ""; - } - } - var scrollbarModel = { - "native": NativeScrollbars, - "null": NullScrollbars - }; - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) { - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - } - cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - on(node, "mousedown", function () { - if (cm.state.focused) { - setTimeout(function () { - return cm.display.input.focus(); - }, 0); - } - }); - node.setAttribute("cm-not-content", "true"); - }, function (pos, axis) { - if (axis == "horizontal") { - setScrollLeft(cm, pos); - } else { - updateScrollTop(cm, pos); - } - }, cm); - if (cm.display.scrollbars.addClass) { - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - } - var nextOpId = 0; - function startOperation(cm) { - cm.curOp = { - cm, - viewChanged: false, - // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, - // Used to detect need to update scrollbar - forceUpdate: false, - // Used to force a redraw - updateInput: 0, - // Whether to reset the input textarea - typing: false, - // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, - // Accumulated changes, for firing change events - cursorActivityHandlers: null, - // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, - // Tracks which cursorActivity handlers have been called already - selectionChanged: false, - // Whether the selection needs to be redrawn - updateMaxLine: false, - // Set when the widest line needs to be determined anew - scrollLeft: null, - scrollTop: null, - // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, - // Used to scroll to a specific position - focus: false, - id: ++nextOpId, - // Unique ID - markArrays: null - // Used by addMarkedSpan - }; - pushOperation(cm.curOp); - } - function endOperation(cm) { - var op = cm.curOp; - if (op) { - finishOperation(op, function (group) { - for (var i2 = 0; i2 < group.ops.length; i2++) { - group.ops[i2].cm.curOp = null; - } - endOperations(group); - }); - } - } - function endOperations(group) { - var ops = group.ops; - for (var i2 = 0; i2 < ops.length; i2++) { - endOperation_R1(ops[i2]); - } - for (var i$12 = 0; i$12 < ops.length; i$12++) { - endOperation_W1(ops[i$12]); - } - for (var i$22 = 0; i$22 < ops.length; i$22++) { - endOperation_R2(ops[i$22]); - } - for (var i$3 = 0; i$3 < ops.length; i$3++) { - endOperation_W2(ops[i$3]); - } - for (var i$4 = 0; i$4 < ops.length; i$4++) { - endOperation_finish(ops[i$4]); - } - } - function endOperation_R1(op) { - var cm = op.cm, - display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) { - findMaxLine(cm); - } - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { - top: op.scrollTop, - ensure: op.scrollToPos - }, op.forceUpdate); - } - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } - function endOperation_R2(op) { - var cm = op.cm, - display = cm.display; - if (op.updatedDisplay) { - updateHeightsInViewport(cm); - } - op.barMeasure = measureForScrollbars(cm); - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - if (op.updatedDisplay || op.selectionChanged) { - op.preparedSelection = display.input.prepareSelection(); - } - } - function endOperation_W2(op) { - var cm = op.cm; - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) { - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); - } - cm.display.maxLineChanged = false; - } - var takeFocus = op.focus && op.focus == activeElt(); - if (op.preparedSelection) { - cm.display.input.showSelection(op.preparedSelection, takeFocus); - } - if (op.updatedDisplay || op.startHeight != cm.doc.height) { - updateScrollbars(cm, op.barMeasure); - } - if (op.updatedDisplay) { - setDocumentHeight(cm, op.barMeasure); - } - if (op.selectionChanged) { - restartBlink(cm); - } - if (cm.state.focused && op.updateInput) { - cm.display.input.reset(op.typing); - } - if (takeFocus) { - ensureFocus(op.cm); - } - } - function endOperation_finish(op) { - var cm = op.cm, - display = cm.display, - doc = cm.doc; - if (op.updatedDisplay) { - postUpdateDisplay(cm, op.update); - } - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { - display.wheelStartX = display.wheelStartY = null; - } - if (op.scrollTop != null) { - setScrollTop(cm, op.scrollTop, op.forceScroll); - } - if (op.scrollLeft != null) { - setScrollLeft(cm, op.scrollLeft, true, true); - } - if (op.scrollToPos) { - var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - maybeScrollWindow(cm, rect); - } - var hidden = op.maybeHiddenMarkers, - unhidden = op.maybeUnhiddenMarkers; - if (hidden) { - for (var i2 = 0; i2 < hidden.length; ++i2) { - if (!hidden[i2].lines.length) { - signal(hidden[i2], "hide"); - } - } - } - if (unhidden) { - for (var i$12 = 0; i$12 < unhidden.length; ++i$12) { - if (unhidden[i$12].lines.length) { - signal(unhidden[i$12], "unhide"); - } - } - } - if (display.wrapper.offsetHeight) { - doc.scrollTop = cm.display.scroller.scrollTop; - } - if (op.changeObjs) { - signal(cm, "changes", cm, op.changeObjs); - } - if (op.update) { - op.update.finish(); - } - } - function runInOp(cm, f) { - if (cm.curOp) { - return f(); - } - startOperation(cm); - try { - return f(); - } finally { - endOperation(cm); - } - } - function operation(cm, f) { - return function () { - if (cm.curOp) { - return f.apply(cm, arguments); - } - startOperation(cm); - try { - return f.apply(cm, arguments); - } finally { - endOperation(cm); - } - }; - } - function methodOp(f) { - return function () { - if (this.curOp) { - return f.apply(this, arguments); - } - startOperation(this); - try { - return f.apply(this, arguments); - } finally { - endOperation(this); - } - }; - } - function docMethodOp(f) { - return function () { - var cm = this.cm; - if (!cm || cm.curOp) { - return f.apply(this, arguments); - } - startOperation(cm); - try { - return f.apply(this, arguments); - } finally { - endOperation(cm); - } - }; - } - function startWorker(cm, time) { - if (cm.doc.highlightFrontier < cm.display.viewTo) { - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - } - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.highlightFrontier >= cm.display.viewTo) { - return; - } - var end = + /* @__PURE__ */new Date() + cm.options.workTime; - var context = getContextBefore(cm, doc.highlightFrontier); - var changedLines = []; - doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { - if (context.line >= cm.display.viewFrom) { - var oldStyles = line.styles; - var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; - var highlighted = highlightLine(cm, line, context, true); - if (resetState) { - context.state = resetState; - } - line.styles = highlighted.styles; - var oldCls = line.styleClasses, - newCls = highlighted.classes; - if (newCls) { - line.styleClasses = newCls; - } else if (oldCls) { - line.styleClasses = null; - } - var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) { - ischange = oldStyles[i2] != line.styles[i2]; - } - if (ischange) { - changedLines.push(context.line); - } - line.stateAfter = context.save(); - context.nextLine(); - } else { - if (line.text.length <= cm.options.maxHighlightLength) { - processLine(cm, line.text, context); - } - line.stateAfter = context.line % 5 == 0 ? context.save() : null; - context.nextLine(); - } - if (+ /* @__PURE__ */new Date() > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - doc.highlightFrontier = context.line; - doc.modeFrontier = Math.max(doc.modeFrontier, context.line); - if (changedLines.length) { - runInOp(cm, function () { - for (var i2 = 0; i2 < changedLines.length; i2++) { - regLineChange(cm, changedLines[i2], "text"); - } - }); - } - } - var DisplayUpdate = function (cm, viewport, force) { - var display = cm.display; - this.viewport = viewport; - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - }; - DisplayUpdate.prototype.signal = function (emitter, type) { - if (hasHandler(emitter, type)) { - this.events.push(arguments); - } - }; - DisplayUpdate.prototype.finish = function () { - for (var i2 = 0; i2 < this.events.length; i2++) { - signal.apply(null, this.events[i2]); - } - }; - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - function selectionSnapshot(cm) { - if (cm.hasFocus()) { - return null; - } - var active = activeElt(); - if (!active || !contains(cm.display.lineDiv, active)) { - return null; - } - var result = { - activeElt: active - }; - if (window.getSelection) { - var sel = window.getSelection(); - if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { - result.anchorNode = sel.anchorNode; - result.anchorOffset = sel.anchorOffset; - result.focusNode = sel.focusNode; - result.focusOffset = sel.focusOffset; - } - } - return result; - } - function restoreSelection(snapshot) { - if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { - return; - } - snapshot.activeElt.focus(); - if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { - var sel = window.getSelection(), - range2 = document.createRange(); - range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset); - range2.collapse(false); - sel.removeAllRanges(); - sel.addRange(range2); - sel.extend(snapshot.focusNode, snapshot.focusOffset); - } - } - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, - doc = cm.doc; - if (update.editorIsHidden) { - resetView(cm); - return false; - } - if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { - return false; - } - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); - } - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) { - from = Math.max(doc.first, display.viewFrom); - } - if (display.viewTo > to && display.viewTo - to < 20) { - to = Math.min(end, display.viewTo); - } - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); - } - var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - cm.display.mover.style.top = display.viewOffset + "px"; - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { - return false; - } - var selSnapshot = selectionSnapshot(cm); - if (toUpdate > 4) { - display.lineDiv.style.display = "none"; - } - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) { - display.lineDiv.style.display = ""; - } - display.renderedView = display.view; - restoreSelection(selSnapshot); - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = display.sizer.style.minHeight = 0; - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - display.updateLineNumbers = null; - return true; - } - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - if (viewport && viewport.top != null) { - viewport = { - top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) - }; - } - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { - break; - } - } else if (first) { - update.visible = visibleLines(cm.display, cm.doc, viewport); - } - if (!updateDisplayIfNeeded(cm, update)) { - break; - } - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.force = false; - } - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; - cm.display.reportedViewTo = cm.display.viewTo; - } - } - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.finish(); - } - } - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, - lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, - cur = container.firstChild; - function rm(node2) { - var next = node2.nextSibling; - if (webkit && mac && cm.display.currentWheelTarget == node2) { - node2.style.display = "none"; - } else { - node2.parentNode.removeChild(node2); - } - return next; - } - var view = display.view, - lineN = display.viewFrom; - for (var i2 = 0; i2 < view.length; i2++) { - var lineView = view[i2]; - if (lineView.hidden) ;else if (!lineView.node || lineView.node.parentNode != container) { - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { - while (cur != lineView.node) { - cur = rm(cur); - } - var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) { - updateNumber = false; - } - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) { - cur = rm(cur); - } - } - function updateGutterSpace(display) { - var width = display.gutters.offsetWidth; - display.sizer.style.marginLeft = width + "px"; - signalLater(display, "gutterChanged", display); - } - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - cm.display.heightForcer.style.top = measure.docHeight + "px"; - cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px"; - } - function alignHorizontally(cm) { - var display = cm.display, - view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { - return; - } - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, - left = comp + "px"; - for (var i2 = 0; i2 < view.length; i2++) { - if (!view[i2].hidden) { - if (cm.options.fixedGutter) { - if (view[i2].gutter) { - view[i2].gutter.style.left = left; - } - if (view[i2].gutterBackground) { - view[i2].gutterBackground.style.left = left; - } - } - var align = view[i2].alignable; - if (align) { - for (var j = 0; j < align.length; j++) { - align[j].style.left = left; - } - } - } - } - if (cm.options.fixedGutter) { - display.gutters.style.left = comp + gutterW + "px"; - } - } - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) { - return false; - } - var doc = cm.doc, - last = lineNumberFor(cm.options, doc.first + doc.size - 1), - display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, - padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm.display); - return true; - } - return false; - } - function getGutters(gutters, lineNumbers) { - var result = [], - sawLineNumbers = false; - for (var i2 = 0; i2 < gutters.length; i2++) { - var name = gutters[i2], - style = null; - if (typeof name != "string") { - style = name.style; - name = name.className; - } - if (name == "CodeMirror-linenumbers") { - if (!lineNumbers) { - continue; - } else { - sawLineNumbers = true; - } - } - result.push({ - className: name, - style - }); - } - if (lineNumbers && !sawLineNumbers) { - result.push({ - className: "CodeMirror-linenumbers", - style: null - }); - } - return result; - } - function renderGutters(display) { - var gutters = display.gutters, - specs = display.gutterSpecs; - removeChildren(gutters); - display.lineGutter = null; - for (var i2 = 0; i2 < specs.length; ++i2) { - var ref = specs[i2]; - var className = ref.className; - var style = ref.style; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); - if (style) { - gElt.style.cssText = style; - } - if (className == "CodeMirror-linenumbers") { - display.lineGutter = gElt; - gElt.style.width = (display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = specs.length ? "" : "none"; - updateGutterSpace(display); - } - function updateGutters(cm) { - renderGutters(cm.display); - regChange(cm); - alignHorizontally(cm); - } - function Display(place, doc, input, options) { - var d = this; - this.input = input; - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - d.lineDiv = eltP("div", null, "CodeMirror-code"); - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - d.measure = elt("div", null, "CodeMirror-measure"); - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); - var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); - d.mover = elt("div", [lines], null, "position: relative"); - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - d.wrapper.setAttribute("translate", "no"); - if (ie && ie_version < 8) { - d.gutters.style.zIndex = -1; - d.scroller.style.paddingRight = 0; - } - if (!webkit && !(gecko && mobile)) { - d.scroller.draggable = true; - } - if (place) { - if (place.appendChild) { - place.appendChild(d.wrapper); - } else { - place(d.wrapper); - } - } - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - d.view = []; - d.renderedView = null; - d.externalMeasured = null; - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - d.alignWidgets = false; - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - d.shift = false; - d.selForContextMenu = null; - d.activeTouch = null; - d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); - renderGutters(d); - input.init(d); - } - var wheelSamples = 0, - wheelPixelsPerUnit = null; - if (ie) { - wheelPixelsPerUnit = -0.53; - } else if (gecko) { - wheelPixelsPerUnit = 15; - } else if (chrome) { - wheelPixelsPerUnit = -0.7; - } else if (safari) { - wheelPixelsPerUnit = -1 / 3; - } - function wheelEventDelta(e) { - var dx = e.wheelDeltaX, - dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { - dx = e.detail; - } - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { - dy = e.detail; - } else if (dy == null) { - dy = e.wheelDelta; - } - return { - x: dx, - y: dy - }; - } - function wheelEventPixels(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - } - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), - dx = delta.x, - dy = delta.y; - var pixelsPerUnit = wheelPixelsPerUnit; - if (e.deltaMode === 0) { - dx = e.deltaX; - dy = e.deltaY; - pixelsPerUnit = 1; - } - var display = cm.display, - scroll = display.scroller; - var canScrollX = scroll.scrollWidth > scroll.clientWidth; - var canScrollY = scroll.scrollHeight > scroll.clientHeight; - if (!(dx && canScrollX || dy && canScrollY)) { - return; - } - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { - for (var i2 = 0; i2 < view.length; i2++) { - if (view[i2].node == cur) { - cm.display.currentWheelTarget = cur; - break outer; - } - } - } - } - if (dx && !gecko && !presto && pixelsPerUnit != null) { - if (dy && canScrollY) { - updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); - } - setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); - if (!dy || dy && canScrollY) { - e_preventDefault(e); - } - display.wheelStartX = null; - return; - } - if (dy && pixelsPerUnit != null) { - var pixels = dy * pixelsPerUnit; - var top = cm.doc.scrollTop, - bot = top + display.wrapper.clientHeight; - if (pixels < 0) { - top = Math.max(0, top + pixels - 50); - } else { - bot = Math.min(cm.doc.height, bot + pixels + 50); - } - updateDisplaySimple(cm, { - top, - bottom: bot - }); - } - if (wheelSamples < 20 && e.deltaMode !== 0) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; - display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; - display.wheelDY = dy; - setTimeout(function () { - if (display.wheelStartX == null) { - return; - } - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX; - display.wheelStartX = display.wheelStartY = null; - if (!sample) { - return; - } - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; - display.wheelDY += dy; - } - } - } - var Selection = function (ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - }; - Selection.prototype.primary = function () { - return this.ranges[this.primIndex]; - }; - Selection.prototype.equals = function (other) { - if (other == this) { - return true; - } - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { - return false; - } - for (var i2 = 0; i2 < this.ranges.length; i2++) { - var here = this.ranges[i2], - there = other.ranges[i2]; - if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { - return false; - } - } - return true; - }; - Selection.prototype.deepCopy = function () { - var out = []; - for (var i2 = 0; i2 < this.ranges.length; i2++) { - out[i2] = new Range(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head)); - } - return new Selection(out, this.primIndex); - }; - Selection.prototype.somethingSelected = function () { - for (var i2 = 0; i2 < this.ranges.length; i2++) { - if (!this.ranges[i2].empty()) { - return true; - } - } - return false; - }; - Selection.prototype.contains = function (pos, end) { - if (!end) { - end = pos; - } - for (var i2 = 0; i2 < this.ranges.length; i2++) { - var range2 = this.ranges[i2]; - if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) { - return i2; - } - } - return -1; - }; - var Range = function (anchor, head) { - this.anchor = anchor; - this.head = head; - }; - Range.prototype.from = function () { - return minPos(this.anchor, this.head); - }; - Range.prototype.to = function () { - return maxPos(this.anchor, this.head); - }; - Range.prototype.empty = function () { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - }; - function normalizeSelection(cm, ranges, primIndex) { - var mayTouch = cm && cm.options.selectionsMayTouch; - var prim = ranges[primIndex]; - ranges.sort(function (a, b) { - return cmp(a.from(), b.from()); - }); - primIndex = indexOf(ranges, prim); - for (var i2 = 1; i2 < ranges.length; i2++) { - var cur = ranges[i2], - prev = ranges[i2 - 1]; - var diff = cmp(prev.to(), cur.from()); - if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { - var from = minPos(prev.from(), cur.from()), - to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i2 <= primIndex) { - --primIndex; - } - ranges.splice(--i2, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex); - } - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - function changeEnd(change) { - if (!change.text) { - return change.to; - } - return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - } - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) { - return pos; - } - if (cmp(pos, change.to) <= 0) { - return changeEnd(change); - } - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, - ch = pos.ch; - if (pos.line == change.to.line) { - ch += changeEnd(change).ch - change.to.ch; - } - return Pos(line, ch); - } - function computeSelAfterChange(doc, change) { - var out = []; - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - var range2 = doc.sel.ranges[i2]; - out.push(new Range(adjustForChange(range2.anchor, change), adjustForChange(range2.head, change))); - } - return normalizeSelection(doc.cm, out, doc.sel.primIndex); - } - function offsetPos(pos, old, nw) { - if (pos.line == old.line) { - return Pos(nw.line, pos.ch - old.ch + nw.ch); - } else { - return Pos(nw.line + (pos.line - old.line), pos.ch); - } - } - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), - newPrev = oldPrev; - for (var i2 = 0; i2 < changes.length; i2++) { - var change = changes[i2]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range2 = doc.sel.ranges[i2], - inv = cmp(range2.head, range2.anchor) < 0; - out[i2] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i2] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex); - } - function loadMode(cm) { - cm.doc.mode = getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - function resetModeState(cm) { - cm.doc.iter(function (line) { - if (line.stateAfter) { - line.stateAfter = null; - } - if (line.styles) { - line.styles = null; - } - }); - cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) { - regChange(cm); - } - } - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - function updateDoc(doc, change, markedSpans, estimateHeight2) { - function spansFor(n) { - return markedSpans ? markedSpans[n] : null; - } - function update(line, text2, spans) { - updateLine(line, text2, spans, estimateHeight2); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - var result = []; - for (var i2 = start; i2 < end; ++i2) { - result.push(new Line(text[i2], spansFor(i2), estimateHeight2)); - } - return result; - } - var from = change.from, - to = change.to, - text = change.text; - var firstLine = getLine(doc, from.line), - lastLine = getLine(doc, to.line); - var lastText = lst(text), - lastSpans = spansFor(text.length - 1), - nlines = to.line - from.line; - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) { - doc.remove(from.line, nlines); - } - if (added.length) { - doc.insert(from.line, added); - } - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added$1 = linesFor(1, text.length - 1); - added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added$1); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added$2 = linesFor(1, text.length - 1); - if (nlines > 1) { - doc.remove(from.line + 1, nlines - 1); - } - doc.insert(from.line + 1, added$2); - } - signalLater(doc, "change", doc, change); - } - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc2, skip, sharedHist) { - if (doc2.linked) { - for (var i2 = 0; i2 < doc2.linked.length; ++i2) { - var rel = doc2.linked[i2]; - if (rel.doc == skip) { - continue; - } - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) { - continue; - } - f(rel.doc, shared); - propagate(rel.doc, doc2, shared); - } - } - } - propagate(doc, null, true); - } - function attachDoc(cm, doc) { - if (doc.cm) { - throw new Error("This document is already in use."); - } - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - setDirectionClass(cm); - cm.options.direction = doc.direction; - if (!cm.options.lineWrapping) { - findMaxLine(cm); - } - cm.options.mode = doc.modeOption; - regChange(cm); - } - function setDirectionClass(cm) { - (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); - } - function directionChanged(cm) { - runInOp(cm, function () { - setDirectionClass(cm); - regChange(cm); - }); - } - function History(prev) { - this.done = []; - this.undone = []; - this.undoDepth = prev ? prev.undoDepth : Infinity; - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; - } - function historyChangeFromChange(doc, change) { - var histChange = { - from: copyPos(change.from), - to: changeEnd(change), - text: getBetween(doc, change.from, change.to) - }; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function (doc2) { - return attachLocalSpans(doc2, histChange, change.from.line, change.to.line + 1); - }, true); - return histChange; - } - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) { - array.pop(); - } else { - break; - } - } - } - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = + /* @__PURE__ */new Date(), - cur; - var last; - if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - last.to = changeEnd(change); - } else { - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - var before = lst(hist.done); - if (!before || !before.ranges) { - pushSelectionToHistory(doc.sel, hist.done); - } - cur = { - changes: [historyChangeFromChange(doc, change)], - generation: hist.generation - }; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) { - hist.done.shift(); - } - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - if (!last) { - signal(doc, "historyAdded"); - } - } - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && /* @__PURE__ */new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, - origin = options && options.origin; - if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) { - hist.done[hist.done.length - 1] = sel; - } else { - pushSelectionToHistory(sel, hist.done); - } - hist.lastSelTime = + /* @__PURE__ */new Date(); - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) { - clearSelectionEvents(hist.undone); - } - } - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) { - dest.push(sel); - } - } - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], - n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { - if (line.markedSpans) { - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - } - ++n; - }); - } - function removeClearedSpans(spans) { - if (!spans) { - return null; - } - var out; - for (var i2 = 0; i2 < spans.length; ++i2) { - if (spans[i2].marker.explicitlyCleared) { - if (!out) { - out = spans.slice(0, i2); - } - } else if (out) { - out.push(spans[i2]); - } - } - return !out ? spans : out.length ? out : null; - } - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) { - return null; - } - var nw = []; - for (var i2 = 0; i2 < change.text.length; ++i2) { - nw.push(removeClearedSpans(found[i2])); - } - return nw; - } - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) { - return stretched; - } - if (!stretched) { - return old; - } - for (var i2 = 0; i2 < old.length; ++i2) { - var oldCur = old[i2], - stretchCur = stretched[i2]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) { - if (oldCur[k].marker == span.marker) { - continue spans; - } - } - oldCur.push(span); - } - } else if (stretchCur) { - old[i2] = stretchCur; - } - } - return old; - } - function copyHistoryArray(events, newGroup, instantiateSel) { - var copy = []; - for (var i2 = 0; i2 < events.length; ++i2) { - var event = events[i2]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, - newChanges = []; - copy.push({ - changes: newChanges - }); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], - m = void 0; - newChanges.push({ - from: change.from, - to: change.to, - text: change.text - }); - if (newGroup) { - for (var prop2 in change) { - if (m = prop2.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop2] = change[prop2]; - delete change[prop2]; - } - } - } - } - } - } - return copy; - } - function extendRange(range2, head, other, extend) { - if (extend) { - var anchor = range2.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != cmp(other, anchor) < 0) { - anchor = head; - head = other; - } else if (posBefore != cmp(head, other) < 0) { - head = other; - } - } - return new Range(anchor, head); - } else { - return new Range(other || head, head); - } - } - function extendSelection(doc, head, other, options, extend) { - if (extend == null) { - extend = doc.cm && (doc.cm.display.shift || doc.extend); - } - setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); - } - function extendSelections(doc, heads, options) { - var out = []; - var extend = doc.cm && (doc.cm.display.shift || doc.extend); - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - out[i2] = extendRange(doc.sel.ranges[i2], heads[i2], null, extend); - } - var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - function replaceOneSelection(doc, i2, range2, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i2] = range2; - setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); - } - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - function filterSelectionChange(doc, sel, options) { - var obj = { - ranges: sel.ranges, - update: function (ranges) { - this.ranges = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - this.ranges[i2] = new Range(clipPos(doc, ranges[i2].anchor), clipPos(doc, ranges[i2].head)); - } - }, - origin: options && options.origin - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) { - signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - } - if (obj.ranges != sel.ranges) { - return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1); - } else { - return sel; - } - } - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, - last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); - } - } - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { - sel = filterSelectionChange(doc, sel, options); - } - var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") { - ensureCursorVisible(doc.cm); - } - } - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) { - return; - } - doc.sel = sel; - if (doc.cm) { - doc.cm.curOp.updateInput = 1; - doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); - } - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i2 = 0; i2 < sel.ranges.length; i2++) { - var range2 = sel.ranges[i2]; - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i2]; - var newAnchor = skipAtomic(doc, range2.anchor, old && old.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range2.head, old && old.head, bias, mayClear); - if (out || newAnchor != range2.anchor || newHead != range2.head) { - if (!out) { - out = sel.ranges.slice(0, i2); - } - out[i2] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel; - } - function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { - var line = getLine(doc, pos.line); - if (line.markedSpans) { - for (var i2 = 0; i2 < line.markedSpans.length; ++i2) { - var sp = line.markedSpans[i2], - m = sp.marker; - var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; - var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight; - if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) { - break; - } else { - --i2; - continue; - } - } - } - if (!m.atomic) { - continue; - } - if (oldPos) { - var near = m.find(dir < 0 ? 1 : -1), - diff = void 0; - if (dir < 0 ? preventCursorRight : preventCursorLeft) { - near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); - } - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { - return skipAtomicInner(doc, near, pos, dir, mayClear); - } - } - var far = m.find(dir < 0 ? -1 : 1); - if (dir < 0 ? preventCursorLeft : preventCursorRight) { - far = movePos(doc, far, dir, far.line == pos.line ? line : null); - } - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; - } - } - } - return pos; - } - function skipAtomic(doc, pos, oldPos, bias, mayClear) { - var dir = bias || 1; - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true); - if (!found) { - doc.cantEdit = true; - return Pos(doc.first, 0); - } - return found; - } - function movePos(doc, pos, dir, line) { - if (dir < 0 && pos.ch == 0) { - if (pos.line > doc.first) { - return clipPos(doc, Pos(pos.line - 1)); - } else { - return null; - } - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { - if (pos.line < doc.first + doc.size - 1) { - return Pos(pos.line + 1, 0); - } else { - return null; - } - } else { - return new Pos(pos.line, pos.ch + dir); - } - } - function selectAll(cm) { - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); - } - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function () { - return obj.canceled = true; - } - }; - if (update) { - obj.update = function (from, to, text, origin) { - if (from) { - obj.from = clipPos(doc, from); - } - if (to) { - obj.to = clipPos(doc, to); - } - if (text) { - obj.text = text; - } - if (origin !== void 0) { - obj.origin = origin; - } - }; - } - signal(doc, "beforeChange", doc, obj); - if (doc.cm) { - signal(doc.cm, "beforeChange", doc.cm, obj); - } - if (obj.canceled) { - if (doc.cm) { - doc.cm.curOp.updateInput = 2; - } - return null; - } - return { - from: obj.from, - to: obj.to, - text: obj.text, - origin: obj.origin - }; - } - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) { - return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); - } - if (doc.cm.state.suppressEdits) { - return; - } - } - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) { - return; - } - } - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i2 = split.length - 1; i2 >= 0; --i2) { - makeChangeInner(doc, { - from: split[i2].from, - to: split[i2].to, - text: i2 ? [""] : change.text, - origin: change.origin - }); - } - } else { - makeChangeInner(doc, change); - } - } - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { - return; - } - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - linkedDocs(doc, function (doc2, sharedHist) { - if (!sharedHist && indexOf(rebased, doc2.history) == -1) { - rebaseHist(doc2.history, change); - rebased.push(doc2.history); - } - makeChangeSingleDoc(doc2, change, null, stretchSpansOverChange(doc2, change)); - }); - } - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - var suppress = doc.cm && doc.cm.state.suppressEdits; - if (suppress && !allowSelectionOnly) { - return; - } - var hist = doc.history, - event, - selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, - dest = type == "undo" ? hist.undone : hist.done; - var i2 = 0; - for (; i2 < source.length; i2++) { - event = source[i2]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { - break; - } - } - if (i2 == source.length) { - return; - } - hist.lastOrigin = hist.lastSelOrigin = null; - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, { - clearRedo: false - }); - return; - } - selAfter = event; - } else if (suppress) { - source.push(event); - return; - } else { - break; - } - } - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({ - changes: antiChanges, - generation: hist.generation - }); - hist.generation = event.generation || ++hist.maxGeneration; - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - var loop = function (i3) { - var change = event.changes[i3]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return {}; - } - antiChanges.push(historyChangeFromChange(doc, change)); - var after = i3 ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i3 && doc.cm) { - doc.cm.scrollIntoView({ - from: change.from, - to: changeEnd(change) - }); - } - var rebased = []; - linkedDocs(doc, function (doc2, sharedHist) { - if (!sharedHist && indexOf(rebased, doc2.history) == -1) { - rebaseHist(doc2.history, change); - rebased.push(doc2.history); - } - makeChangeSingleDoc(doc2, change, null, mergeOldSpans(doc2, change)); - }); - }; - for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) { - var returned = loop(i$12); - if (returned) return returned.v; - } - } - function shiftDoc(doc, distance) { - if (distance == 0) { - return; - } - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function (range2) { - return new Range(Pos(range2.anchor.line + distance, range2.anchor.ch), Pos(range2.head.line + distance, range2.head.ch)); - }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { - regLineChange(doc.cm, l, "gutter"); - } - } - } - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) { - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - } - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) { - return; - } - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = { - from: Pos(doc.first, 0), - to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], - origin: change.origin - }; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = { - from: change.from, - to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], - origin: change.origin - }; - } - change.removed = getBetween(doc, change.from, change.to); - if (!selAfter) { - selAfter = computeSelAfterChange(doc, change); - } - if (doc.cm) { - makeChangeSingleDocInEditor(doc.cm, change, spans); - } else { - updateDoc(doc, change, spans); - } - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { - doc.cantEdit = false; - } - } - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, - display = cm.display, - from = change.from, - to = change.to; - var recomputeMaxLength = false, - checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function (line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - if (doc.sel.contains(change.from, change.to) > -1) { - signalCursorActivity(cm); - } - updateDoc(doc, change, spans, estimateHeight(cm)); - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function (line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) { - cm.curOp.updateMaxLine = true; - } - } - retreatFrontier(doc, from.line); - startWorker(cm, 400); - var lendiff = change.text.length - (to.line - from.line) - 1; - if (change.full) { - regChange(cm); - } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { - regLineChange(cm, from.line, "text"); - } else { - regChange(cm, from.line, to.line + 1, lendiff); - } - var changesHandler = hasHandler(cm, "changes"), - changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from, - to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) { - signalLater(cm, "change", cm, obj); - } - if (changesHandler) { - (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - } - cm.display.selForContextMenu = null; - } - function replaceRange(doc, code, from, to, origin) { - var assign; - if (!to) { - to = from; - } - if (cmp(to, from) < 0) { - assign = [to, from], from = assign[0], to = assign[1]; - } - if (typeof code == "string") { - code = doc.splitLines(code); - } - makeChange(doc, { - from, - to, - text: code, - origin - }); - } - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - function rebaseHistArray(array, from, to, diff) { - for (var i2 = 0; i2 < array.length; ++i2) { - var sub = array[i2], - ok = true; - if (sub.ranges) { - if (!sub.copied) { - sub = array[i2] = sub.deepCopy(); - sub.copied = true; - } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue; - } - for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { - var cur = sub.changes[j$1]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!ok) { - array.splice(0, i2 + 1); - i2 = 0; - } - } - } - function rebaseHist(hist, change) { - var from = change.from.line, - to = change.to.line, - diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - function changeLine(doc, handle, changeType, op) { - var no = handle, - line = handle; - if (typeof handle == "number") { - line = getLine(doc, clipLine(doc, handle)); - } else { - no = lineNo(handle); - } - if (no == null) { - return null; - } - if (op(line, no) && doc.cm) { - regLineChange(doc.cm, no, changeType); - } - return line; - } - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - var height = 0; - for (var i2 = 0; i2 < lines.length; ++i2) { - lines[i2].parent = this; - height += lines[i2].height; - } - this.height = height; - } - LeafChunk.prototype = { - chunkSize: function () { - return this.lines.length; - }, - // Remove the n lines at offset 'at'. - removeInner: function (at, n) { - for (var i2 = at, e = at + n; i2 < e; ++i2) { - var line = this.lines[i2]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function (lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function (at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i2 = 0; i2 < lines.length; ++i2) { - lines[i2].parent = this; - } - }, - // Used to iterate over a part of the tree. - iterN: function (at, n, op) { - for (var e = at + n; at < e; ++at) { - if (op(this.lines[at])) { - return true; - } - } - } - }; - function BranchChunk(children) { - this.children = children; - var size = 0, - height = 0; - for (var i2 = 0; i2 < children.length; ++i2) { - var ch = children[i2]; - size += ch.chunkSize(); - height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - BranchChunk.prototype = { - chunkSize: function () { - return this.size; - }, - removeInner: function (at, n) { - this.size -= n; - for (var i2 = 0; i2 < this.children.length; ++i2) { - var child = this.children[i2], - sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), - oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { - this.children.splice(i2--, 1); - child.parent = null; - } - if ((n -= rm) == 0) { - break; - } - at = 0; - } else { - at -= sz; - } - } - if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function (lines) { - for (var i2 = 0; i2 < this.children.length; ++i2) { - this.children[i2].collapse(lines); - } - }, - insertInner: function (at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i2 = 0; i2 < this.children.length; ++i2) { - var child = this.children[i2], - sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - var remaining = child.lines.length % 25 + 25; - for (var pos = remaining; pos < child.lines.length;) { - var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); - child.height -= leaf.height; - this.children.splice(++i2, 0, leaf); - leaf.parent = this; - } - child.lines = child.lines.slice(0, remaining); - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function () { - if (this.children.length <= 10) { - return; - } - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function (at, n, op) { - for (var i2 = 0; i2 < this.children.length; ++i2) { - var child = this.children[i2], - sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) { - return true; - } - if ((n -= used) == 0) { - break; - } - at = 0; - } else { - at -= sz; - } - } - } - }; - var LineWidget = function (doc, node, options) { - if (options) { - for (var opt in options) { - if (options.hasOwnProperty(opt)) { - this[opt] = options[opt]; - } - } - } - this.doc = doc; - this.node = node; - }; - LineWidget.prototype.clear = function () { - var cm = this.doc.cm, - ws = this.line.widgets, - line = this.line, - no = lineNo(line); - if (no == null || !ws) { - return; - } - for (var i2 = 0; i2 < ws.length; ++i2) { - if (ws[i2] == this) { - ws.splice(i2--, 1); - } - } - if (!ws.length) { - line.widgets = null; - } - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) { - runInOp(cm, function () { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - signalLater(cm, "lineWidgetCleared", cm, this, no); - } - }; - LineWidget.prototype.changed = function () { - var this$1$1 = this; - var oldH = this.height, - cm = this.doc.cm, - line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) { - return; - } - if (!lineIsHidden(this.doc, line)) { - updateLineHeight(line, line.height + diff); - } - if (cm) { - runInOp(cm, function () { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line)); - }); - } - }; - eventMixin(LineWidget); - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) { - addToScrollTop(cm, diff); - } - } - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) { - cm.display.alignWidgets = true; - } - changeLine(doc, handle, "widget", function (line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) { - widgets.push(widget); - } else { - widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); - } - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) { - addToScrollTop(cm, widget.height); - } - cm.curOp.forceUpdate = true; - } - return true; - }); - if (cm) { - signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); - } - return widget; - } - var nextMarkerId = 0; - var TextMarker = function (doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - TextMarker.prototype.clear = function () { - if (this.explicitlyCleared) { - return; - } - var cm = this.doc.cm, - withOp = cm && !cm.curOp; - if (withOp) { - startOperation(cm); - } - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) { - signalLater(this, "clear", found.from, found.to); - } - } - var min = null, - max = null; - for (var i2 = 0; i2 < this.lines.length; ++i2) { - var line = this.lines[i2]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) { - regLineChange(cm, lineNo(line), "text"); - } else if (cm) { - if (span.to != null) { - max = lineNo(line); - } - if (span.from != null) { - min = lineNo(line); - } - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { - updateLineHeight(line, textHeight(cm.display)); - } - } - if (cm && this.collapsed && !cm.options.lineWrapping) { - for (var i$12 = 0; i$12 < this.lines.length; ++i$12) { - var visual = visualLine(this.lines[i$12]), - len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - } - if (min != null && cm && this.collapsed) { - regChange(cm, min, max + 1); - } - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) { - reCheckSelection(cm.doc); - } - } - if (cm) { - signalLater(cm, "markerCleared", cm, this, min, max); - } - if (withOp) { - endOperation(cm); - } - if (this.parent) { - this.parent.clear(); - } - }; - TextMarker.prototype.find = function (side, lineObj) { - if (side == null && this.type == "bookmark") { - side = 1; - } - var from, to; - for (var i2 = 0; i2 < this.lines.length; ++i2) { - var line = this.lines[i2]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) { - return from; - } - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) { - return to; - } - } - } - return from && { - from, - to - }; - }; - TextMarker.prototype.changed = function () { - var this$1$1 = this; - var pos = this.find(-1, true), - widget = this, - cm = this.doc.cm; - if (!pos || !cm) { - return; - } - runInOp(cm, function () { - var line = pos.line, - lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) { - updateLineHeight(line, line.height + dHeight); - } - } - signalLater(cm, "markerChanged", cm, this$1$1); - }); - }; - TextMarker.prototype.attachLine = function (line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function (line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - eventMixin(TextMarker); - function markText(doc, from, to, options, type) { - if (options && options.shared) { - return markTextShared(doc, from, to, options, type); - } - if (doc.cm && !doc.cm.curOp) { - return operation(doc.cm, markText)(doc, from, to, options, type); - } - var marker = new TextMarker(doc, type), - diff = cmp(from, to); - if (options) { - copyObj(options, marker, false); - } - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { - return marker; - } - if (marker.replacedWith) { - marker.collapsed = true; - marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) { - marker.widgetNode.setAttribute("cm-ignore-events", "true"); - } - if (options.insertLeft) { - marker.widgetNode.insertLeft = true; - } - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { - throw new Error("Inserting collapsed marker partially overlapping an existing one"); - } - seeCollapsedSpans(); - } - if (marker.addToHistory) { - addChangeToHistory(doc, { - from, - to, - origin: "markText" - }, doc.sel, NaN); - } - var curLine = from.line, - cm = doc.cm, - updateMaxLine; - doc.iter(curLine, to.line + 1, function (line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { - updateMaxLine = true; - } - if (marker.collapsed && curLine != from.line) { - updateLineHeight(line, 0); - } - addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); - ++curLine; - }); - if (marker.collapsed) { - doc.iter(from.line, to.line + 1, function (line) { - if (lineIsHidden(doc, line)) { - updateLineHeight(line, 0); - } - }); - } - if (marker.clearOnEnter) { - on(marker, "beforeCursorEnter", function () { - return marker.clear(); - }); - } - if (marker.readOnly) { - seeReadOnlySpans(); - if (doc.history.done.length || doc.history.undone.length) { - doc.clearHistory(); - } - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - if (updateMaxLine) { - cm.curOp.updateMaxLine = true; - } - if (marker.collapsed) { - regChange(cm, from.line, to.line + 1); - } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { - for (var i2 = from.line; i2 <= to.line; i2++) { - regLineChange(cm, i2, "text"); - } - } - if (marker.atomic) { - reCheckSelection(cm.doc); - } - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - var SharedTextMarker = function (markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i2 = 0; i2 < markers.length; ++i2) { - markers[i2].parent = this; - } - }; - SharedTextMarker.prototype.clear = function () { - if (this.explicitlyCleared) { - return; - } - this.explicitlyCleared = true; - for (var i2 = 0; i2 < this.markers.length; ++i2) { - this.markers[i2].clear(); - } - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function (side, lineObj) { - return this.primary.find(side, lineObj); - }; - eventMixin(SharedTextMarker); - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], - primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function (doc2) { - if (widget) { - options.widgetNode = widget.cloneNode(true); - } - markers.push(markText(doc2, clipPos(doc2, from), clipPos(doc2, to), options, type)); - for (var i2 = 0; i2 < doc2.linked.length; ++i2) { - if (doc2.linked[i2].isParent) { - return; - } - } - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { - return m.parent; - }); - } - function copySharedMarkers(doc, markers) { - for (var i2 = 0; i2 < markers.length; i2++) { - var marker = markers[i2], - pos = marker.find(); - var mFrom = doc.clipPos(pos.from), - mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - function detachSharedMarkers(markers) { - var loop = function (i3) { - var marker = markers[i3], - linked = [marker.primary.doc]; - linkedDocs(marker.primary.doc, function (d) { - return linked.push(d); - }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - }; - for (var i2 = 0; i2 < markers.length; i2++) loop(i2); - } - var nextDocId = 0; - var Doc = function (text, mode, firstLine, lineSep, direction) { - if (!(this instanceof Doc)) { - return new Doc(text, mode, firstLine, lineSep, direction); - } - if (firstLine == null) { - firstLine = 0; - } - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.modeFrontier = this.highlightFrontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - this.lineSep = lineSep; - this.direction = direction == "rtl" ? "rtl" : "ltr"; - this.extend = false; - if (typeof text == "string") { - text = this.splitLines(text); - } - updateDoc(this, { - from: start, - to: start, - text - }); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function (from, to, op) { - if (op) { - this.iterN(from - this.first, to - from, op); - } else { - this.iterN(this.first, this.first + this.size, from); - } - }, - // Non-public interface for adding and removing lines. - insert: function (at, lines) { - var height = 0; - for (var i2 = 0; i2 < lines.length; ++i2) { - height += lines[i2].height; - } - this.insertInner(at - this.first, lines, height); - }, - remove: function (at, n) { - this.removeInner(at - this.first, n); - }, - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - getValue: function (lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) { - return lines; - } - return lines.join(lineSep || this.lineSeparator()); - }, - setValue: docMethodOp(function (code) { - var top = Pos(this.first, 0), - last = this.first + this.size - 1; - makeChange(this, { - from: top, - to: Pos(last, getLine(this, last).text.length), - text: this.splitLines(code), - origin: "setValue", - full: true - }, true); - if (this.cm) { - scrollToCoords(this.cm, 0, 0); - } - setSelection(this, simpleSelection(top), sel_dontScroll); - }), - replaceRange: function (code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function (from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) { - return lines; - } - if (lineSep === "") { - return lines.join(""); - } - return lines.join(lineSep || this.lineSeparator()); - }, - getLine: function (line) { - var l = this.getLineHandle(line); - return l && l.text; - }, - getLineHandle: function (line) { - if (isLine(this, line)) { - return getLine(this, line); - } - }, - getLineNumber: function (line) { - return lineNo(line); - }, - getLineHandleVisualStart: function (line) { - if (typeof line == "number") { - line = getLine(this, line); - } - return visualLine(line); - }, - lineCount: function () { - return this.size; - }, - firstLine: function () { - return this.first; - }, - lastLine: function () { - return this.first + this.size - 1; - }, - clipPos: function (pos) { - return clipPos(this, pos); - }, - getCursor: function (start) { - var range2 = this.sel.primary(), - pos; - if (start == null || start == "head") { - pos = range2.head; - } else if (start == "anchor") { - pos = range2.anchor; - } else if (start == "end" || start == "to" || start === false) { - pos = range2.to(); - } else { - pos = range2.from(); - } - return pos; - }, - listSelections: function () { - return this.sel.ranges; - }, - somethingSelected: function () { - return this.sel.somethingSelected(); - }, - setCursor: docMethodOp(function (line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function (anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function (head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function (heads, options) { - extendSelections(this, clipPosArray(this, heads), options); - }), - extendSelectionsBy: docMethodOp(function (f, options) { - var heads = map(this.sel.ranges, f); - extendSelections(this, clipPosArray(this, heads), options); - }), - setSelections: docMethodOp(function (ranges, primary, options) { - if (!ranges.length) { - return; - } - var out = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - out[i2] = new Range(clipPos(this, ranges[i2].anchor), clipPos(this, ranges[i2].head || ranges[i2].anchor)); - } - if (primary == null) { - primary = Math.min(ranges.length - 1, this.sel.primIndex); - } - setSelection(this, normalizeSelection(this.cm, out, primary), options); - }), - addSelection: docMethodOp(function (anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); - }), - getSelection: function (lineSep) { - var ranges = this.sel.ranges, - lines; - for (var i2 = 0; i2 < ranges.length; i2++) { - var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) { - return lines; - } else { - return lines.join(lineSep || this.lineSeparator()); - } - }, - getSelections: function (lineSep) { - var parts = [], - ranges = this.sel.ranges; - for (var i2 = 0; i2 < ranges.length; i2++) { - var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); - if (lineSep !== false) { - sel = sel.join(lineSep || this.lineSeparator()); - } - parts[i2] = sel; - } - return parts; - }, - replaceSelection: function (code, collapse, origin) { - var dup = []; - for (var i2 = 0; i2 < this.sel.ranges.length; i2++) { - dup[i2] = code; - } - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function (code, collapse, origin) { - var changes = [], - sel = this.sel; - for (var i2 = 0; i2 < sel.ranges.length; i2++) { - var range2 = sel.ranges[i2]; - changes[i2] = { - from: range2.from(), - to: range2.to(), - text: this.splitLines(code[i2]), - origin - }; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) { - makeChange(this, changes[i$12]); - } - if (newSel) { - setSelectionReplaceHistory(this, newSel); - } else if (this.cm) { - ensureCursorVisible(this.cm); - } - }), - undo: docMethodOp(function () { - makeChangeFromHistory(this, "undo"); - }), - redo: docMethodOp(function () { - makeChangeFromHistory(this, "redo"); - }), - undoSelection: docMethodOp(function () { - makeChangeFromHistory(this, "undo", true); - }), - redoSelection: docMethodOp(function () { - makeChangeFromHistory(this, "redo", true); - }), - setExtending: function (val) { - this.extend = val; - }, - getExtending: function () { - return this.extend; - }, - historySize: function () { - var hist = this.history, - done = 0, - undone = 0; - for (var i2 = 0; i2 < hist.done.length; i2++) { - if (!hist.done[i2].ranges) { - ++done; - } - } - for (var i$12 = 0; i$12 < hist.undone.length; i$12++) { - if (!hist.undone[i$12].ranges) { - ++undone; - } - } - return { - undo: done, - redo: undone - }; - }, - clearHistory: function () { - var this$1$1 = this; - this.history = new History(this.history); - linkedDocs(this, function (doc) { - return doc.history = this$1$1.history; - }, true); - }, - markClean: function () { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function (forceSplit) { - if (forceSplit) { - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - } - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - getHistory: function () { - return { - done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone) - }; - }, - setHistory: function (histData) { - var hist = this.history = new History(this.history); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - setGutterMarker: docMethodOp(function (line, gutterID, value) { - return changeLine(this, line, "gutter", function (line2) { - var markers = line2.gutterMarkers || (line2.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) { - line2.gutterMarkers = null; - } - return true; - }); - }), - clearGutter: docMethodOp(function (gutterID) { - var this$1$1 = this; - this.iter(function (line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - changeLine(this$1$1, line, "gutter", function () { - line.gutterMarkers[gutterID] = null; - if (isEmpty(line.gutterMarkers)) { - line.gutterMarkers = null; - } - return true; - }); - } - }); - }), - lineInfo: function (line) { - var n; - if (typeof line == "number") { - if (!isLine(this, line)) { - return null; - } - n = line; - line = getLine(this, line); - if (!line) { - return null; - } - } else { - n = lineNo(line); - if (n == null) { - return null; - } - } - return { - line: n, - handle: line, - text: line.text, - gutterMarkers: line.gutterMarkers, - textClass: line.textClass, - bgClass: line.bgClass, - wrapClass: line.wrapClass, - widgets: line.widgets - }; - }, - addLineClass: docMethodOp(function (handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop2]) { - line[prop2] = cls; - } else if (classTest(cls).test(line[prop2])) { - return false; - } else { - line[prop2] += " " + cls; - } - return true; - }); - }), - removeLineClass: docMethodOp(function (handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop2]; - if (!cur) { - return false; - } else if (cls == null) { - line[prop2] = null; - } else { - var found = cur.match(classTest(cls)); - if (!found) { - return false; - } - var end = found.index + found[0].length; - line[prop2] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true; - }); - }), - addLineWidget: docMethodOp(function (handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - removeLineWidget: function (widget) { - widget.clear(); - }, - markText: function (from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); - }, - setBookmark: function (pos, options) { - var realOpts = { - replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, - shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents - }; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function (pos) { - pos = clipPos(this, pos); - var markers = [], - spans = getLine(this, pos.line).markedSpans; - if (spans) { - for (var i2 = 0; i2 < spans.length; ++i2) { - var span = spans[i2]; - if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { - markers.push(span.marker.parent || span.marker); - } - } - } - return markers; - }, - findMarks: function (from, to, filter) { - from = clipPos(this, from); - to = clipPos(this, to); - var found = [], - lineNo2 = from.line; - this.iter(from.line, to.line + 1, function (line) { - var spans = line.markedSpans; - if (spans) { - for (var i2 = 0; i2 < spans.length; i2++) { - var span = spans[i2]; - if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { - found.push(span.marker.parent || span.marker); - } - } - } - ++lineNo2; - }); - return found; - }, - getAllMarks: function () { - var markers = []; - this.iter(function (line) { - var sps = line.markedSpans; - if (sps) { - for (var i2 = 0; i2 < sps.length; ++i2) { - if (sps[i2].from != null) { - markers.push(sps[i2].marker); - } - } - } - }); - return markers; - }, - posFromIndex: function (off2) { - var ch, - lineNo2 = this.first, - sepSize = this.lineSeparator().length; - this.iter(function (line) { - var sz = line.text.length + sepSize; - if (sz > off2) { - ch = off2; - return true; - } - off2 -= sz; - ++lineNo2; - }); - return clipPos(this, Pos(lineNo2, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) { - return 0; - } - var sepSize = this.lineSeparator().length; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + sepSize; - }); - return index; - }, - copy: function (copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); - doc.scrollTop = this.scrollTop; - doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - linkedDoc: function (options) { - if (!options) { - options = {}; - } - var from = this.first, - to = this.first + this.size; - if (options.from != null && options.from > from) { - from = options.from; - } - if (options.to != null && options.to < to) { - to = options.to; - } - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); - if (options.sharedHist) { - copy.history = this.history; - } - (this.linked || (this.linked = [])).push({ - doc: copy, - sharedHist: options.sharedHist - }); - copy.linked = [{ - doc: this, - isParent: true, - sharedHist: options.sharedHist - }]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function (other) { - if (other instanceof CodeMirror) { - other = other.doc; - } - if (this.linked) { - for (var i2 = 0; i2 < this.linked.length; ++i2) { - var link = this.linked[i2]; - if (link.doc != other) { - continue; - } - this.linked.splice(i2, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; - } - } - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function (doc) { - return splitIds.push(doc.id); - }, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function (f) { - linkedDocs(this, f); - }, - getMode: function () { - return this.mode; - }, - getEditor: function () { - return this.cm; - }, - splitLines: function (str) { - if (this.lineSep) { - return str.split(this.lineSep); - } - return splitLinesAuto(str); - }, - lineSeparator: function () { - return this.lineSep || "\n"; - }, - setDirection: docMethodOp(function (dir) { - if (dir != "rtl") { - dir = "ltr"; - } - if (dir == this.direction) { - return; - } - this.direction = dir; - this.iter(function (line) { - return line.order = null; - }); - if (this.cm) { - directionChanged(this.cm); - } - }) - }); - Doc.prototype.eachLine = Doc.prototype.iter; - var lastDrop = 0; - function onDrop(e) { - var cm = this; - clearDragCursor(cm); - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e_preventDefault(e); - if (ie) { - lastDrop = + /* @__PURE__ */new Date(); - } - var pos = posFromMouse(cm, e, true), - files = e.dataTransfer.files; - if (!pos || cm.isReadOnly()) { - return; - } - if (files && files.length && window.FileReader && window.File) { - var n = files.length, - text = Array(n), - read = 0; - var markAsReadAndPasteIfAllFilesAreRead = function () { - if (++read == n) { - operation(cm, function () { - pos = clipPos(cm.doc, pos); - var change = { - from: pos, - to: pos, - text: cm.doc.splitLines(text.filter(function (t) { - return t != null; - }).join(cm.doc.lineSeparator())), - origin: "paste" - }; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); - })(); - } - }; - var readTextFromFile = function (file, i3) { - if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { - markAsReadAndPasteIfAllFilesAreRead(); - return; - } - var reader = new FileReader(); - reader.onerror = function () { - return markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.onload = function () { - var content = reader.result; - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { - markAsReadAndPasteIfAllFilesAreRead(); - return; - } - text[i3] = content; - markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.readAsText(file); - }; - for (var i2 = 0; i2 < files.length; i2++) { - readTextFromFile(files[i2], i2); - } - } else { - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - setTimeout(function () { - return cm.display.input.focus(); - }, 20); - return; - } - try { - var text$1 = e.dataTransfer.getData("Text"); - if (text$1) { - var selected; - if (cm.state.draggingText && !cm.state.draggingText.copy) { - selected = cm.listSelections(); - } - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) { - for (var i$12 = 0; i$12 < selected.length; ++i$12) { - replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag"); - } - } - cm.replaceSelection(text$1, "around", "paste"); - cm.display.input.focus(); - } - } catch (e$1) {} - } - } - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || + /* @__PURE__ */new Date() - lastDrop < 100)) { - e_stop(e); - return; - } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove"; - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) { - img.parentNode.removeChild(img); - } - } - } - function onDragOver(cm, e) { - var pos = posFromMouse(cm, e); - if (!pos) { - return; - } - var frag = document.createDocumentFragment(); - drawSelectionCursor(cm, pos, frag); - if (!cm.display.dragCursor) { - cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); - cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); - } - removeChildrenAndAdd(cm.display.dragCursor, frag); - } - function clearDragCursor(cm) { - if (cm.display.dragCursor) { - cm.display.lineSpace.removeChild(cm.display.dragCursor); - cm.display.dragCursor = null; - } - } - function forEachCodeMirror(f) { - if (!document.getElementsByClassName) { - return; - } - var byClass = document.getElementsByClassName("CodeMirror"), - editors = []; - for (var i2 = 0; i2 < byClass.length; i2++) { - var cm = byClass[i2].CodeMirror; - if (cm) { - editors.push(cm); - } - } - if (editors.length) { - editors[0].operation(function () { - for (var i3 = 0; i3 < editors.length; i3++) { - f(editors[i3]); - } - }); - } - } - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) { - return; - } - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - var resizeTimer; - on(window, "resize", function () { - if (resizeTimer == null) { - resizeTimer = setTimeout(function () { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); - } - }); - on(window, "blur", function () { - return forEachCodeMirror(onBlur); - }); - } - function onResize(cm) { - var d = cm.display; - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - var keyNames = { - 3: "Pause", - 8: "Backspace", - 9: "Tab", - 13: "Enter", - 16: "Shift", - 17: "Ctrl", - 18: "Alt", - 19: "Pause", - 20: "CapsLock", - 27: "Esc", - 32: "Space", - 33: "PageUp", - 34: "PageDown", - 35: "End", - 36: "Home", - 37: "Left", - 38: "Up", - 39: "Right", - 40: "Down", - 44: "PrintScrn", - 45: "Insert", - 46: "Delete", - 59: ";", - 61: "=", - 91: "Mod", - 92: "Mod", - 93: "Mod", - 106: "*", - 107: "=", - 109: "-", - 110: ".", - 111: "/", - 145: "ScrollLock", - 173: "-", - 186: ";", - 187: "=", - 188: ",", - 189: "-", - 190: ".", - 191: "/", - 192: "`", - 219: "[", - 220: "\\", - 221: "]", - 222: "'", - 224: "Mod", - 63232: "Up", - 63233: "Down", - 63234: "Left", - 63235: "Right", - 63272: "Delete", - 63273: "Home", - 63275: "End", - 63276: "PageUp", - 63277: "PageDown", - 63302: "Insert" - }; - for (var i = 0; i < 10; i++) { - keyNames[i + 48] = keyNames[i + 96] = String(i); - } - for (var i$1 = 65; i$1 <= 90; i$1++) { - keyNames[i$1] = String.fromCharCode(i$1); - } - for (var i$2 = 1; i$2 <= 12; i$2++) { - keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; - } - var keyMap = {}; - keyMap.basic = { - "Left": "goCharLeft", - "Right": "goCharRight", - "Up": "goLineUp", - "Down": "goLineDown", - "End": "goLineEnd", - "Home": "goLineStartSmart", - "PageUp": "goPageUp", - "PageDown": "goPageDown", - "Delete": "delCharAfter", - "Backspace": "delCharBefore", - "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", - "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", - "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - keyMap.pcDefault = { - "Ctrl-A": "selectAll", - "Ctrl-D": "deleteLine", - "Ctrl-Z": "undo", - "Shift-Ctrl-Z": "redo", - "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", - "Ctrl-End": "goDocEnd", - "Ctrl-Up": "goLineUp", - "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", - "Ctrl-Right": "goGroupRight", - "Alt-Left": "goLineStart", - "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", - "Ctrl-Delete": "delGroupAfter", - "Ctrl-S": "save", - "Ctrl-F": "find", - "Ctrl-G": "findNext", - "Shift-Ctrl-G": "findPrev", - "Shift-Ctrl-F": "replace", - "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", - "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", - "Shift-Ctrl-U": "redoSelection", - "Alt-U": "redoSelection", - "fallthrough": "basic" - }; - keyMap.emacsy = { - "Ctrl-F": "goCharRight", - "Ctrl-B": "goCharLeft", - "Ctrl-P": "goLineUp", - "Ctrl-N": "goLineDown", - "Ctrl-A": "goLineStart", - "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", - "Shift-Ctrl-V": "goPageUp", - "Ctrl-D": "delCharAfter", - "Ctrl-H": "delCharBefore", - "Alt-Backspace": "delWordBefore", - "Ctrl-K": "killLine", - "Ctrl-T": "transposeChars", - "Ctrl-O": "openLine" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", - "Cmd-D": "deleteLine", - "Cmd-Z": "undo", - "Shift-Cmd-Z": "redo", - "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", - "Cmd-Up": "goDocStart", - "Cmd-End": "goDocEnd", - "Cmd-Down": "goDocEnd", - "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", - "Cmd-Left": "goLineLeft", - "Cmd-Right": "goLineRight", - "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", - "Alt-Delete": "delGroupAfter", - "Cmd-S": "save", - "Cmd-F": "find", - "Cmd-G": "findNext", - "Shift-Cmd-G": "findPrev", - "Cmd-Alt-F": "replace", - "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", - "Cmd-]": "indentMore", - "Cmd-Backspace": "delWrappedLineLeft", - "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", - "Shift-Cmd-U": "redoSelection", - "Ctrl-Up": "goDocStart", - "Ctrl-Down": "goDocEnd", - "fallthrough": ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/); - name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i2 = 0; i2 < parts.length - 1; i2++) { - var mod = parts[i2]; - if (/^(cmd|meta|m)$/i.test(mod)) { - cmd = true; - } else if (/^a(lt)?$/i.test(mod)) { - alt = true; - } else if (/^(c|ctrl|control)$/i.test(mod)) { - ctrl = true; - } else if (/^s(hift)?$/i.test(mod)) { - shift = true; - } else { - throw new Error("Unrecognized modifier name: " + mod); - } - } - if (alt) { - name = "Alt-" + name; - } - if (ctrl) { - name = "Ctrl-" + name; - } - if (cmd) { - name = "Cmd-" + name; - } - if (shift) { - name = "Shift-" + name; - } - return name; - } - function normalizeKeyMap(keymap) { - var copy = {}; - for (var keyname in keymap) { - if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { - continue; - } - if (value == "...") { - delete keymap[keyname]; - continue; - } - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i2 = 0; i2 < keys.length; i2++) { - var val = void 0, - name = void 0; - if (i2 == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i2 + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) { - copy[name] = val; - } else if (prev != val) { - throw new Error("Inconsistent bindings for " + name); - } - } - delete keymap[keyname]; - } - } - for (var prop2 in copy) { - keymap[prop2] = copy[prop2]; - } - return keymap; + return FullTextDocument; +}(); +var Is; +(function (Is) { + var toString = Object.prototype.toString; + function defined(value) { + return typeof value !== 'undefined'; + } + Is.defined = defined; + function undefined(value) { + return typeof value === 'undefined'; + } + Is.undefined = undefined; + function boolean(value) { + return value === true || value === false; + } + Is.boolean = boolean; + function string(value) { + return toString.call(value) === '[object String]'; + } + Is.string = string; + function number(value) { + return toString.call(value) === '[object Number]'; + } + Is.number = number; + function numberRange(value, min, max) { + return toString.call(value) === '[object Number]' && min <= value && value <= max; + } + Is.numberRange = numberRange; + function integer(value) { + return toString.call(value) === '[object Number]' && -2147483648 <= value && value <= 2147483647; + } + Is.integer = integer; + function uinteger(value) { + return toString.call(value) === '[object Number]' && 0 <= value && value <= 2147483647; + } + Is.uinteger = uinteger; + function func(value) { + return toString.call(value) === '[object Function]'; + } + Is.func = func; + function objectLiteral(value) { + // Strictly speaking class instances pass this check as well. Since the LSP + // doesn't use classes we ignore this for now. If we do we need to add something + // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null` + return value !== null && typeof value === 'object'; + } + Is.objectLiteral = objectLiteral; + function typedArray(value, check) { + return Array.isArray(value) && value.every(check); + } + Is.typedArray = typedArray; +})(Is || (Is = {})); + +/***/ }), + +/***/ "../../graphiql-react/dist/SchemaReference.cjs.js": +/*!********************************************************!*\ + !*** ../../graphiql-react/dist/SchemaReference.cjs.js ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); +function getTypeInfo(schema, tokenState) { + const info = { + schema, + type: null, + parentType: null, + inputType: null, + directiveDef: null, + fieldDef: null, + argDef: null, + argDefs: null, + objectFieldDefs: null + }; + forEachState.forEachState(tokenState, state => { + var _a, _b; + switch (state.kind) { + case "Query": + case "ShortQuery": + info.type = schema.getQueryType(); + break; + case "Mutation": + info.type = schema.getMutationType(); + break; + case "Subscription": + info.type = schema.getSubscriptionType(); + break; + case "InlineFragment": + case "FragmentDefinition": + if (state.type) { + info.type = schema.getType(state.type); } - function lookupKey(key, map2, handle, context) { - map2 = getKeyMap(map2); - var found = map2.call ? map2.call(key, context) : map2[key]; - if (found === false) { - return "nothing"; - } - if (found === "...") { - return "multi"; - } - if (found != null && handle(found)) { - return "handled"; - } - if (map2.fallthrough) { - if (Object.prototype.toString.call(map2.fallthrough) != "[object Array]") { - return lookupKey(key, map2.fallthrough, handle, context); - } - for (var i2 = 0; i2 < map2.fallthrough.length; i2++) { - var result = lookupKey(key, map2.fallthrough[i2], handle, context); - if (result) { - return result; - } + break; + case "Field": + case "AliasedField": + info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null; + info.type = (_a = info.fieldDef) === null || _a === void 0 ? void 0 : _a.type; + break; + case "SelectionSet": + info.parentType = info.type ? graphql.getNamedType(info.type) : null; + break; + case "Directive": + info.directiveDef = state.name ? schema.getDirective(state.name) : null; + break; + case "Arguments": + const parentDef = state.prevState ? state.prevState.kind === "Field" ? info.fieldDef : state.prevState.kind === "Directive" ? info.directiveDef : state.prevState.kind === "AliasedField" ? state.prevState.name && getFieldDef(schema, info.parentType, state.prevState.name) : null : null; + info.argDefs = parentDef ? parentDef.args : null; + break; + case "Argument": + info.argDef = null; + if (info.argDefs) { + for (let i = 0; i < info.argDefs.length; i++) { + if (info.argDefs[i].name === state.name) { + info.argDef = info.argDefs[i]; + break; } } } - function isModifierKey(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - } - function addModifierNames(name, event, noShift) { - var base = name; - if (event.altKey && base != "Alt") { - name = "Alt-" + name; - } - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { - name = "Ctrl-" + name; - } - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { - name = "Cmd-" + name; - } - if (!noShift && event.shiftKey && base != "Shift") { - name = "Shift-" + name; - } - return name; - } - function keyName(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) { - return false; - } - var name = keyNames[event.keyCode]; - if (name == null || event.altGraphKey) { - return false; - } - if (event.keyCode == 3 && event.code) { - name = event.code; + info.inputType = (_b = info.argDef) === null || _b === void 0 ? void 0 : _b.type; + break; + case "EnumValue": + const enumType = info.inputType ? graphql.getNamedType(info.inputType) : null; + info.enumValue = enumType instanceof graphql.GraphQLEnumType ? find(enumType.getValues(), val => val.value === state.name) : null; + break; + case "ListValue": + const nullableType = info.inputType ? graphql.getNullableType(info.inputType) : null; + info.inputType = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; + break; + case "ObjectValue": + const objectType = info.inputType ? graphql.getNamedType(info.inputType) : null; + info.objectFieldDefs = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; + break; + case "ObjectField": + const objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null; + info.inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; + info.fieldDef = objectField; + break; + case "NamedType": + info.type = state.name ? schema.getType(state.name) : null; + break; + } + }); + return info; +} +function getFieldDef(schema, type, fieldName) { + if (fieldName === graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { + return graphql.SchemaMetaFieldDef; + } + if (fieldName === graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { + return graphql.TypeMetaFieldDef; + } + if (fieldName === graphql.TypeNameMetaFieldDef.name && graphql.isCompositeType(type)) { + return graphql.TypeNameMetaFieldDef; + } + if (type && type.getFields) { + return type.getFields()[fieldName]; + } +} +function find(array, predicate) { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { + return array[i]; + } + } +} +function getFieldReference(typeInfo) { + return { + kind: "Field", + schema: typeInfo.schema, + field: typeInfo.fieldDef, + type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType + }; +} +function getDirectiveReference(typeInfo) { + return { + kind: "Directive", + schema: typeInfo.schema, + directive: typeInfo.directiveDef + }; +} +function getArgumentReference(typeInfo) { + return typeInfo.directiveDef ? { + kind: "Argument", + schema: typeInfo.schema, + argument: typeInfo.argDef, + directive: typeInfo.directiveDef + } : { + kind: "Argument", + schema: typeInfo.schema, + argument: typeInfo.argDef, + field: typeInfo.fieldDef, + type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType + }; +} +function getEnumValueReference(typeInfo) { + return { + kind: "EnumValue", + value: typeInfo.enumValue || void 0, + type: typeInfo.inputType ? graphql.getNamedType(typeInfo.inputType) : void 0 + }; +} +function getTypeReference(typeInfo, type) { + return { + kind: "Type", + schema: typeInfo.schema, + type: type || typeInfo.type + }; +} +function isMetaField(fieldDef) { + return fieldDef.name.slice(0, 2) === "__"; +} +exports.getArgumentReference = getArgumentReference; +exports.getDirectiveReference = getDirectiveReference; +exports.getEnumValueReference = getEnumValueReference; +exports.getFieldReference = getFieldReference; +exports.getTypeInfo = getTypeInfo; +exports.getTypeReference = getTypeReference; + +/***/ }), + +/***/ "../../graphiql-react/dist/brace-fold.cjs.js": +/*!***************************************************!*\ + !*** ../../graphiql-react/dist/brace-fold.cjs.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - return addModifierNames(name, event, noShift); - } - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; } - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, - kill = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - var toKill = compute(ranges[i2]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break; - } + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var braceFold$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function bracketFolding(pairs) { + return function (cm, start) { + var line = start.line, + lineText = cm.getLine(line); + function findOpening(pair) { + var tokenType; + for (var at = start.ch, pass = 0;;) { + var found2 = at <= 0 ? -1 : lineText.lastIndexOf(pair[0], at - 1); + if (found2 == -1) { + if (pass == 1) break; + pass = 1; + at = lineText.length; + continue; } - kill.push(toKill); + if (pass == 1 && found2 < start.ch) break; + tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found2 + 1)); + if (!/^(comment|string)/.test(tokenType)) return { + ch: found2 + 1, + tokenType, + pair + }; + at = found2 - 1; } - runInOp(cm, function () { - for (var i3 = kill.length - 1; i3 >= 0; i3--) { - replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete"); - } - ensureCursorVisible(cm); - }); - } - function moveCharLogically(line, ch, dir) { - var target = skipExtendingChars(line.text, ch + dir, dir); - return target < 0 || target > line.text.length ? null : target; - } - function moveLogically(line, start, dir) { - var ch = moveCharLogically(line, start.ch, dir); - return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before"); } - function endOfLine(visually, cm, lineObj, lineNo2, dir) { - if (visually) { - if (cm.doc.direction == "rtl") { - dir = -dir; - } - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = dir < 0 ? lst(order) : order[0]; - var moveInStorageOrder = dir < 0 == (part.level == 1); - var sticky = moveInStorageOrder ? "after" : "before"; - var ch; - if (part.level > 0 || cm.doc.direction == "rtl") { - var prep = prepareMeasureForLine(cm, lineObj); - ch = dir < 0 ? lineObj.text.length - 1 : 0; - var targetTop = measureCharPrepared(cm, prep, ch).top; - ch = findFirst(function (ch2) { - return measureCharPrepared(cm, prep, ch2).top == targetTop; - }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch); - if (sticky == "before") { - ch = moveCharLogically(lineObj, ch, 1); + function findRange(found2) { + var count = 1, + lastLine = cm.lastLine(), + end, + startCh = found2.ch, + endCh; + outer: for (var i2 = line; i2 <= lastLine; ++i2) { + var text = cm.getLine(i2), + pos = i2 == line ? startCh : 0; + for (;;) { + var nextOpen = text.indexOf(found2.pair[0], pos), + nextClose = text.indexOf(found2.pair[1], pos); + if (nextOpen < 0) nextOpen = text.length; + if (nextClose < 0) nextClose = text.length; + pos = Math.min(nextOpen, nextClose); + if (pos == text.length) break; + if (cm.getTokenTypeAt(CodeMirror.Pos(i2, pos + 1)) == found2.tokenType) { + if (pos == nextOpen) ++count;else if (! --count) { + end = i2; + endCh = pos; + break outer; } - } else { - ch = dir < 0 ? part.to : part.from; } - return new Pos(lineNo2, ch, sticky); + ++pos; } } - return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after"); - } - function moveVisually(cm, line, start, dir) { - var bidi = getOrder(line, cm.doc.direction); - if (!bidi) { - return moveLogically(line, start, dir); - } - if (start.ch >= line.text.length) { - start.ch = line.text.length; - start.sticky = "before"; - } else if (start.ch <= 0) { - start.ch = 0; - start.sticky = "after"; - } - var partPos = getBidiPartAt(bidi, start.ch, start.sticky), - part = bidi[partPos]; - if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { - return moveLogically(line, start, dir); - } - var mv = function (pos, dir2) { - return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2); - }; - var prep; - var getWrappedLineExtent = function (ch2) { - if (!cm.options.lineWrapping) { - return { - begin: 0, - end: line.text.length - }; - } - prep = prep || prepareMeasureForLine(cm, line); - return wrappedLineExtentChar(cm, line, prep, ch2); + if (end == null || line == end) return null; + return { + from: CodeMirror.Pos(line, startCh), + to: CodeMirror.Pos(end, endCh) }; - var wrappedLineExtent2 = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); - if (cm.doc.direction == "rtl" || part.level == 1) { - var moveInStorageOrder = part.level == 1 == dir < 0; - var ch = mv(start, moveInStorageOrder ? 1 : -1); - if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) { - var sticky = moveInStorageOrder ? "before" : "after"; - return new Pos(start.line, ch, sticky); - } - } - var searchInVisualLine = function (partPos2, dir2, wrappedLineExtent3) { - var getRes = function (ch3, moveInStorageOrder3) { - return moveInStorageOrder3 ? new Pos(start.line, mv(ch3, 1), "before") : new Pos(start.line, ch3, "after"); - }; - for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) { - var part2 = bidi[partPos2]; - var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1); - var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1); - if (part2.from <= ch2 && ch2 < part2.to) { - return getRes(ch2, moveInStorageOrder2); - } - ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1); - if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) { - return getRes(ch2, moveInStorageOrder2); - } - } + } + var found = []; + for (var i = 0; i < pairs.length; i++) { + var open = findOpening(pairs[i]); + if (open) found.push(open); + } + found.sort(function (a, b) { + return a.ch - b.ch; + }); + for (var i = 0; i < found.length; i++) { + var range = findRange(found[i]); + if (range) return range; + } + return null; + }; + } + CodeMirror.registerHelper("fold", "brace", bracketFolding([["{", "}"], ["[", "]"]])); + CodeMirror.registerHelper("fold", "brace-paren", bracketFolding([["{", "}"], ["[", "]"], ["(", ")"]])); + CodeMirror.registerHelper("fold", "import", function (cm, start) { + function hasImport(line) { + if (line < cm.firstLine() || line > cm.lastLine()) return null; + var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); + if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); + if (start2.type != "keyword" || start2.string != "import") return null; + for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) { + var text = cm.getLine(i), + semi = text.indexOf(";"); + if (semi != -1) return { + startCh: start2.end, + end: CodeMirror.Pos(i, semi) }; - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2); - if (res) { - return res; - } - var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1); - if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { - res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); - if (res) { - return res; - } - } - return null; } - var commands = { - selectAll, - singleSelection: function (cm) { - return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function (cm) { - return deleteNearSelection(cm, function (range2) { - if (range2.empty()) { - var len = getLine(cm.doc, range2.head.line).text.length; - if (range2.head.ch == len && range2.head.line < cm.lastLine()) { - return { - from: range2.head, - to: Pos(range2.head.line + 1, 0) - }; - } else { - return { - from: range2.head, - to: Pos(range2.head.line, len) - }; - } - } else { - return { - from: range2.from(), - to: range2.to() - }; - } - }); - }, - deleteLine: function (cm) { - return deleteNearSelection(cm, function (range2) { - return { - from: Pos(range2.from().line, 0), - to: clipPos(cm.doc, Pos(range2.to().line + 1, 0)) - }; - }); - }, - delLineLeft: function (cm) { - return deleteNearSelection(cm, function (range2) { - return { - from: Pos(range2.from().line, 0), - to: range2.from() - }; - }); - }, - delWrappedLineLeft: function (cm) { - return deleteNearSelection(cm, function (range2) { - var top = cm.charCoords(range2.head, "div").top + 5; - var leftPos = cm.coordsChar({ - left: 0, - top - }, "div"); - return { - from: leftPos, - to: range2.from() - }; - }); - }, - delWrappedLineRight: function (cm) { - return deleteNearSelection(cm, function (range2) { - var top = cm.charCoords(range2.head, "div").top + 5; - var rightPos = cm.coordsChar({ - left: cm.display.lineDiv.offsetWidth + 100, - top - }, "div"); - return { - from: range2.from(), - to: rightPos - }; - }); - }, - undo: function (cm) { - return cm.undo(); - }, - redo: function (cm) { - return cm.redo(); - }, - undoSelection: function (cm) { - return cm.undoSelection(); - }, - redoSelection: function (cm) { - return cm.redoSelection(); - }, - goDocStart: function (cm) { - return cm.extendSelection(Pos(cm.firstLine(), 0)); - }, - goDocEnd: function (cm) { - return cm.extendSelection(Pos(cm.lastLine())); - }, - goLineStart: function (cm) { - return cm.extendSelectionsBy(function (range2) { - return lineStart(cm, range2.head.line); - }, { - origin: "+move", - bias: 1 - }); - }, - goLineStartSmart: function (cm) { - return cm.extendSelectionsBy(function (range2) { - return lineStartSmart(cm, range2.head); - }, { - origin: "+move", - bias: 1 - }); - }, - goLineEnd: function (cm) { - return cm.extendSelectionsBy(function (range2) { - return lineEnd(cm, range2.head.line); - }, { - origin: "+move", - bias: -1 - }); - }, - goLineRight: function (cm) { - return cm.extendSelectionsBy(function (range2) { - var top = cm.cursorCoords(range2.head, "div").top + 5; - return cm.coordsChar({ - left: cm.display.lineDiv.offsetWidth + 100, - top - }, "div"); - }, sel_move); - }, - goLineLeft: function (cm) { - return cm.extendSelectionsBy(function (range2) { - var top = cm.cursorCoords(range2.head, "div").top + 5; - return cm.coordsChar({ - left: 0, - top - }, "div"); - }, sel_move); - }, - goLineLeftSmart: function (cm) { - return cm.extendSelectionsBy(function (range2) { - var top = cm.cursorCoords(range2.head, "div").top + 5; - var pos = cm.coordsChar({ - left: 0, - top - }, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) { - return lineStartSmart(cm, range2.head); - } - return pos; - }, sel_move); - }, - goLineUp: function (cm) { - return cm.moveV(-1, "line"); - }, - goLineDown: function (cm) { - return cm.moveV(1, "line"); - }, - goPageUp: function (cm) { - return cm.moveV(-1, "page"); - }, - goPageDown: function (cm) { - return cm.moveV(1, "page"); - }, - goCharLeft: function (cm) { - return cm.moveH(-1, "char"); - }, - goCharRight: function (cm) { - return cm.moveH(1, "char"); - }, - goColumnLeft: function (cm) { - return cm.moveH(-1, "column"); - }, - goColumnRight: function (cm) { - return cm.moveH(1, "column"); - }, - goWordLeft: function (cm) { - return cm.moveH(-1, "word"); - }, - goGroupRight: function (cm) { - return cm.moveH(1, "group"); - }, - goGroupLeft: function (cm) { - return cm.moveH(-1, "group"); - }, - goWordRight: function (cm) { - return cm.moveH(1, "word"); - }, - delCharBefore: function (cm) { - return cm.deleteH(-1, "codepoint"); - }, - delCharAfter: function (cm) { - return cm.deleteH(1, "char"); - }, - delWordBefore: function (cm) { - return cm.deleteH(-1, "word"); - }, - delWordAfter: function (cm) { - return cm.deleteH(1, "word"); - }, - delGroupBefore: function (cm) { - return cm.deleteH(-1, "group"); - }, - delGroupAfter: function (cm) { - return cm.deleteH(1, "group"); - }, - indentAuto: function (cm) { - return cm.indentSelection("smart"); - }, - indentMore: function (cm) { - return cm.indentSelection("add"); - }, - indentLess: function (cm) { - return cm.indentSelection("subtract"); - }, - insertTab: function (cm) { - return cm.replaceSelection(" "); - }, - insertSoftTab: function (cm) { - var spaces = [], - ranges = cm.listSelections(), - tabSize = cm.options.tabSize; - for (var i2 = 0; i2 < ranges.length; i2++) { - var pos = ranges[i2].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(spaceStr(tabSize - col % tabSize)); - } - cm.replaceSelections(spaces); - }, - defaultTab: function (cm) { - if (cm.somethingSelected()) { - cm.indentSelection("add"); - } else { - cm.execCommand("insertTab"); - } - }, - // Swap the two chars left and right of each selection's head. - // Move cursor behind the two swapped characters afterwards. - // - // Doesn't consider line feeds a character. - // Doesn't scan more than one line above to find a character. - // Doesn't do anything on an empty line. - // Doesn't do anything with non-empty selections. - transposeChars: function (cm) { - return runInOp(cm, function () { - var ranges = cm.listSelections(), - newSel = []; - for (var i2 = 0; i2 < ranges.length; i2++) { - if (!ranges[i2].empty()) { - continue; - } - var cur = ranges[i2].head, - line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) { - cur = new Pos(cur.line, cur.ch - 1); - } - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) { - cur = new Pos(cur.line, 1); - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); - } - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function (cm) { - return runInOp(cm, function () { - var sels = cm.listSelections(); - for (var i2 = sels.length - 1; i2 >= 0; i2--) { - cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input"); - } - sels = cm.listSelections(); - for (var i$12 = 0; i$12 < sels.length; i$12++) { - cm.indentLine(sels[i$12].from().line, null, true); - } - ensureCursorVisible(cm); + } + var startLine = start.line, + has = hasImport(startLine), + prev; + if (!has || hasImport(startLine - 1) || (prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1) return null; + for (var end = has.end;;) { + var next = hasImport(end.line + 1); + if (next == null) break; + end = next.end; + } + return { + from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), + to: end + }; + }); + CodeMirror.registerHelper("fold", "include", function (cm, start) { + function hasInclude(line) { + if (line < cm.firstLine() || line > cm.lastLine()) return null; + var start2 = cm.getTokenAt(CodeMirror.Pos(line, 1)); + if (!/\S/.test(start2.string)) start2 = cm.getTokenAt(CodeMirror.Pos(line, start2.end + 1)); + if (start2.type == "meta" && start2.string.slice(0, 8) == "#include") return start2.start + 8; + } + var startLine = start.line, + has = hasInclude(startLine); + if (has == null || hasInclude(startLine - 1) != null) return null; + for (var end = startLine;;) { + var next = hasInclude(end + 1); + if (next == null) break; + ++end; + } + return { + from: CodeMirror.Pos(startLine, has + 1), + to: cm.clipPos(CodeMirror.Pos(end)) + }; + }); + }); +})(); +var braceFoldExports = braceFold$2.exports; +const braceFold = /* @__PURE__ */codemirror.getDefaultExportFromCjs(braceFoldExports); +const braceFold$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: braceFold +}, [braceFoldExports]); +exports.braceFold = braceFold$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/closebrackets.cjs.js": +/*!******************************************************!*\ + !*** ../../graphiql-react/dist/closebrackets.cjs.js ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] }); - }, - openLine: function (cm) { - return cm.replaceSelection("\n", "start"); - }, - toggleOverwrite: function (cm) { - return cm.toggleOverwrite(); } + } + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var closebrackets$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var defaults = { + pairs: `()[]{}''""`, + closeBefore: `)]}'":;>`, + triples: "", + explode: "[]{}" + }; + var Pos = CodeMirror.Pos; + CodeMirror.defineOption("autoCloseBrackets", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.removeKeyMap(keyMap); + cm.state.closeBrackets = null; + } + if (val) { + ensureBound(getOption(val, "pairs")); + cm.state.closeBrackets = val; + cm.addKeyMap(keyMap); + } + }); + function getOption(conf, name) { + if (name == "pairs" && typeof conf == "string") return conf; + if (typeof conf == "object" && conf[name] != null) return conf[name]; + return defaults[name]; + } + var keyMap = { + Backspace: handleBackspace, + Enter: handleEnter + }; + function ensureBound(chars) { + for (var i = 0; i < chars.length; i++) { + var ch = chars.charAt(i), + key = "'" + ch + "'"; + if (!keyMap[key]) keyMap[key] = handler(ch); + } + } + ensureBound(defaults.pairs + "`"); + function handler(ch) { + return function (cm) { + return handleChar(cm, ch); + }; + } + function getConfig(cm) { + var deflt = cm.state.closeBrackets; + if (!deflt || deflt.override) return deflt; + var mode = cm.getModeAt(cm.getCursor()); + return mode.closeBrackets || deflt; + } + function handleBackspace(cm) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + var pairs = getOption(conf, "pairs"); + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; + } + for (var i = ranges.length - 1; i >= 0; i--) { + var cur = ranges[i].head; + cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); + } + } + function handleEnter(cm) { + var conf = getConfig(cm); + var explode = conf && getOption(conf, "explode"); + if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) return CodeMirror.Pass; + var around = charsAround(cm, ranges[i].head); + if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; + } + cm.operation(function () { + var linesep = cm.lineSeparator() || "\n"; + cm.replaceSelection(linesep + linesep, null); + moveSel(cm, -1); + ranges = cm.listSelections(); + for (var i2 = 0; i2 < ranges.length; i2++) { + var line = ranges[i2].head.line; + cm.indentLine(line, null, true); + cm.indentLine(line + 1, null, true); + } + }); + } + function moveSel(cm, dir) { + var newRanges = [], + ranges = cm.listSelections(), + primary = 0; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head == cm.getCursor()) primary = i; + var pos = range.head.ch || dir > 0 ? { + line: range.head.line, + ch: range.head.ch + dir + } : { + line: range.head.line - 1 }; - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) { - lineN = lineNo(visual); - } - return endOfLine(true, cm, visual, lineN, 1); - } - function lineEnd(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLineEnd(line); - if (visual != line) { - lineN = lineNo(visual); - } - return endOfLine(true, cm, line, lineN, -1); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line, cm.doc.direction); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); - } - return start; - } - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) { - return false; - } - } - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, - done = false; - try { - if (cm.isReadOnly()) { - cm.state.suppressEdits = true; - } - if (dropShift) { - cm.display.shift = false; - } - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; + newRanges.push({ + anchor: pos, + head: pos + }); + } + cm.setSelections(newRanges, primary); + } + function contractSelection(sel) { + var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; + return { + anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), + head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1)) + }; + } + function handleChar(cm, ch) { + var conf = getConfig(cm); + if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; + var pairs = getOption(conf, "pairs"); + var pos = pairs.indexOf(ch); + if (pos == -1) return CodeMirror.Pass; + var closeBefore = getOption(conf, "closeBefore"); + var triples = getOption(conf, "triples"); + var identical = pairs.charAt(pos + 1) == ch; + var ranges = cm.listSelections(); + var opening = pos % 2 == 0; + var type; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + cur = range.head, + curType; + var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); + if (opening && !range.empty()) { + curType = "surround"; + } else if ((identical || !opening) && next == ch) { + if (identical && stringStartsAfter(cm, cur)) curType = "both";else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree";else curType = "skip"; + } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { + if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; + curType = "addFour"; + } else if (identical) { + var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur); + if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";else return CodeMirror.Pass; + } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { + curType = "both"; + } else { + return CodeMirror.Pass; + } + if (!type) type = curType;else if (type != curType) return CodeMirror.Pass; + } + var left = pos % 2 ? pairs.charAt(pos - 1) : ch; + var right = pos % 2 ? ch : pairs.charAt(pos + 1); + cm.operation(function () { + if (type == "skip") { + moveSel(cm, 1); + } else if (type == "skipThree") { + moveSel(cm, 3); + } else if (type == "surround") { + var sels = cm.getSelections(); + for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = left + sels[i2] + right; + cm.replaceSelections(sels, "around"); + sels = cm.listSelections().slice(); + for (var i2 = 0; i2 < sels.length; i2++) sels[i2] = contractSelection(sels[i2]); + cm.setSelections(sels); + } else if (type == "both") { + cm.replaceSelection(left + right, null); + cm.triggerElectric(left + right); + moveSel(cm, -1); + } else if (type == "addFour") { + cm.replaceSelection(left + left + left + left, "before"); + moveSel(cm, 1); + } + }); + } + function charsAround(cm, pos) { + var str = cm.getRange(Pos(pos.line, pos.ch - 1), Pos(pos.line, pos.ch + 1)); + return str.length == 2 ? str : null; + } + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)); + return /\bstring/.test(token.type) && token.start == pos.ch && (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))); + } + }); +})(); +var closebracketsExports = closebrackets$2.exports; +const closebrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(closebracketsExports); +const closebrackets$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: closebrackets +}, [closebracketsExports]); +exports.closebrackets = closebrackets$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/codemirror.cjs.js": +/*!***************************************************!*\ + !*** ../../graphiql-react/dist/codemirror.cjs.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror$1 = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - return done; } - function lookupKeyForEditor(cm, name, handle) { - for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) { - var result = lookupKey(name, cm.state.keyMaps[i2], handle, cm); - if (result) { - return result; - } - } - return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm); + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var codemirrorExports = codemirror$1.requireCodemirror(); +const CodeMirror = /* @__PURE__ */codemirror$1.getDefaultExportFromCjs(codemirrorExports); +const codemirror = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: CodeMirror +}, [codemirrorExports]); +exports.CodeMirror = CodeMirror; +exports.codemirror = codemirror; + +/***/ }), + +/***/ "../../graphiql-react/dist/codemirror.cjs2.js": +/*!****************************************************!*\ + !*** ../../graphiql-react/dist/codemirror.cjs2.js ***! + \****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : {}; +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} +var codemirror = { + exports: {} +}; +var hasRequiredCodemirror; +function requireCodemirror() { + if (hasRequiredCodemirror) return codemirror.exports; + hasRequiredCodemirror = 1; + (function (module2, exports2) { + (function (global2, factory) { + module2.exports = factory(); + })(commonjsGlobal, function () { + var userAgent = navigator.userAgent; + var platform = navigator.platform; + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var edge = /Edge\/(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up || edge; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); + var webkit = !edge && /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = !edge && /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); + var android = /Android/.test(userAgent); + var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) { + presto_version = Number(presto_version[1]); + } + if (presto_version && presto_version >= 15) { + presto = false; + webkit = true; + } + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || ie && ie_version >= 9; + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); + } + var rmClass = function (node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); } - var stopSeq = new Delayed(); - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) { - return "handled"; - } - if (/\'$/.test(name)) { - cm.state.keySeq = null; - } else { - stopSeq.set(50, function () { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); - } - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { - return true; - } - } - return dispatchKeyInner(cm, name, e, handle); + }; + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) { + e.removeChild(e.firstChild); } - function dispatchKeyInner(cm, name, e, handle) { - var result = lookupKeyForEditor(cm, name, handle); - if (result == "multi") { - cm.state.keySeq = name; - } - if (result == "handled") { - signalLater(cm, "keyHandled", cm, name, e); - } - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - return !!result; + return e; + } + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) { + e.className = className; } - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) { - return false; + if (style) { + e.style.cssText = style; + } + if (typeof content == "string") { + e.appendChild(document.createTextNode(content)); + } else if (content) { + for (var i2 = 0; i2 < content.length; ++i2) { + e.appendChild(content[i2]); } - if (e.shiftKey && !cm.state.keySeq) { - return dispatchKey(cm, "Shift-" + name, e, function (b) { - return doHandleBinding(cm, b, true); - }) || dispatchKey(cm, name, e, function (b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { - return doHandleBinding(cm, b); - } - }); - } else { - return dispatchKey(cm, name, e, function (b) { - return doHandleBinding(cm, b); - }); + } + return e; + } + function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style); + e.setAttribute("role", "presentation"); + return e; + } + var range; + if (document.createRange) { + range = function (node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + } else { + range = function (node, start, end) { + var r = document.body.createTextRange(); + try { + r.moveToElementText(node.parentNode); + } catch (e) { + return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + } + function contains(parent, child) { + if (child.nodeType == 3) { + child = child.parentNode; } - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, function (b) { - return doHandleBinding(cm, b, true); - }); + if (parent.contains) { + return parent.contains(child); } - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - if (e.target && e.target != cm.display.input.getField()) { - return; - } - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) { - return; - } - if (ie && ie_version < 11 && e.keyCode == 27) { - e.returnValue = false; - } - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { - cm.replaceSelection("", null, "cut"); - } - } - if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { - document.execCommand("cut"); + do { + if (child.nodeType == 11) { + child = child.host; } - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { - showCrossHair(cm); + if (child == parent) { + return true; } + } while (child = child.parentNode); + } + function activeElt() { + var activeElement; + try { + activeElement = document.activeElement; + } catch (e) { + activeElement = document.body || null; } - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { + activeElement = activeElement.shadowRoot.activeElement; } - function onKeyUp(e) { - if (e.keyCode == 16) { - this.doc.sel.shift = false; - } - signalDOMEvent(this, e); + return activeElement; + } + function addClass(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) { + node.className += (current ? " " : "") + cls; } - function onKeyPress(e) { - var cm = this; - if (e.target && e.target != cm.display.input.getField()) { - return; - } - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { - return; - } - var keyCode = e.keyCode, - charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) { - lastStoppedKey = null; - e_preventDefault(e); - return; - } - if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) { - return; - } - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (ch == "\b") { - return; - } - if (handleCharBinding(cm, e, ch)) { - return; + } + function joinClasses(a, b) { + var as = a.split(" "); + for (var i2 = 0; i2 < as.length; i2++) { + if (as[i2] && !classTest(as[i2]).test(b)) { + b += " " + as[i2]; } - cm.display.input.onKeyPress(e); } - var DOUBLECLICK_DELAY = 400; - var PastClick = function (time, pos, button) { - this.time = time; - this.pos = pos; - this.button = button; + return b; + } + var selectInput = function (node) { + node.select(); + }; + if (ios) { + selectInput = function (node) { + node.selectionStart = 0; + node.selectionEnd = node.value.length; }; - PastClick.prototype.compare = function (time, pos, button) { - return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button; + } else if (ie) { + selectInput = function (node) { + try { + node.select(); + } catch (_e) {} }; - var lastClick, lastDoubleClick; - function clickRepeat(pos, button) { - var now = + /* @__PURE__ */new Date(); - if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { - lastClick = lastDoubleClick = null; - return "triple"; - } else if (lastClick && lastClick.compare(now, pos, button)) { - lastDoubleClick = new PastClick(now, pos, button); - lastClick = null; - return "double"; - } else { - lastClick = new PastClick(now, pos, button); - lastDoubleClick = null; - return "single"; - } + } + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return f.apply(null, args); + }; + } + function copyObj(obj, target, overwrite) { + if (!target) { + target = {}; } - function onMouseDown(e) { - var cm = this, - display = cm.display; - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { - return; - } - display.input.ensurePolled(); - display.shift = e.shiftKey; - if (eventInWidget(display, e)) { - if (!webkit) { - display.scroller.draggable = false; - setTimeout(function () { - return display.scroller.draggable = true; - }, 100); - } - return; - } - if (clickInGutter(cm, e)) { - return; - } - var pos = posFromMouse(cm, e), - button = e_button(e), - repeat = pos ? clickRepeat(pos, button) : "single"; - window.focus(); - if (button == 1 && cm.state.selectingText) { - cm.state.selectingText(e); - } - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { - return; - } - if (button == 1) { - if (pos) { - leftButtonDown(cm, pos, repeat, e); - } else if (e_target(e) == display.scroller) { - e_preventDefault(e); - } - } else if (button == 2) { - if (pos) { - extendSelection(cm.doc, pos); - } - setTimeout(function () { - return display.input.focus(); - }, 20); - } else if (button == 3) { - if (captureRightClick) { - cm.display.input.onContextMenu(e); - } else { - delayBlurEvent(cm); - } + for (var prop2 in obj) { + if (obj.hasOwnProperty(prop2) && (overwrite !== false || !target.hasOwnProperty(prop2))) { + target[prop2] = obj[prop2]; } } - function handleMappedButton(cm, button, pos, repeat, event) { - var name = "Click"; - if (repeat == "double") { - name = "Double" + name; - } else if (repeat == "triple") { - name = "Triple" + name; + return target; + } + function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) { + end = string.length; } - name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; - return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { - if (typeof bound == "string") { - bound = commands[bound]; - } - if (!bound) { - return false; - } - var done = false; - try { - if (cm.isReadOnly()) { - cm.state.suppressEdits = true; - } - done = bound(cm, pos) != Pass; - } finally { - cm.state.suppressEdits = false; - } - return done; - }); } - function configureMouse(cm, repeat, event) { - var option = cm.getOption("configureMouse"); - var value = option ? option(cm, repeat, event) : {}; - if (value.unit == null) { - var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; - value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; - } - if (value.extend == null || cm.doc.extend) { - value.extend = cm.doc.extend || event.shiftKey; - } - if (value.addNew == null) { - value.addNew = mac ? event.metaKey : event.ctrlKey; + for (var i2 = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf(" ", i2); + if (nextTab < 0 || nextTab >= end) { + return n + (end - i2); } - if (value.moveOnDrag == null) { - value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); - } - return value; + n += nextTab - i2; + n += tabSize - n % tabSize; + i2 = nextTab + 1; } - function leftButtonDown(cm, pos, repeat, event) { - if (ie) { - setTimeout(bind(ensureFocus, cm), 0); - } else { - cm.curOp.focus = activeElt(); - } - var behavior = configureMouse(cm, repeat, event); - var sel = cm.doc.sel, - contained; - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { - leftButtonStartDrag(cm, event, pos, behavior); - } else { - leftButtonSelect(cm, event, pos, behavior); - } + } + var Delayed = function () { + this.id = null; + this.f = null; + this.time = 0; + this.handler = bind(this.onTimeout, this); + }; + Delayed.prototype.onTimeout = function (self2) { + self2.id = 0; + if (self2.time <= + /* @__PURE__ */new Date()) { + self2.f(); + } else { + setTimeout(self2.handler, self2.time - + /* @__PURE__ */new Date()); } - function leftButtonStartDrag(cm, event, pos, behavior) { - var display = cm.display, - moved = false; - var dragEnd = operation(cm, function (e) { - if (webkit) { - display.scroller.draggable = false; - } - cm.state.draggingText = false; - if (cm.state.delayingBlurEvent) { - if (cm.hasFocus()) { - cm.state.delayingBlurEvent = false; - } else { - delayBlurEvent(cm); - } - } - off(display.wrapper.ownerDocument, "mouseup", dragEnd); - off(display.wrapper.ownerDocument, "mousemove", mouseMove); - off(display.scroller, "dragstart", dragStart); - off(display.scroller, "drop", dragEnd); - if (!moved) { - e_preventDefault(e); - if (!behavior.addNew) { - extendSelection(cm.doc, pos, null, null, behavior.extend); - } - if (webkit && !safari || ie && ie_version == 9) { - setTimeout(function () { - display.wrapper.ownerDocument.body.focus({ - preventScroll: true - }); - display.input.focus(); - }, 20); - } else { - display.input.focus(); - } - } - }); - var mouseMove = function (e2) { - moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; - }; - var dragStart = function () { - return moved = true; - }; - if (webkit) { - display.scroller.draggable = true; - } - cm.state.draggingText = dragEnd; - dragEnd.copy = !behavior.moveOnDrag; - on(display.wrapper.ownerDocument, "mouseup", dragEnd); - on(display.wrapper.ownerDocument, "mousemove", mouseMove); - on(display.scroller, "dragstart", dragStart); - on(display.scroller, "drop", dragEnd); - cm.state.delayingBlurEvent = true; - setTimeout(function () { - return display.input.focus(); - }, 20); - if (display.scroller.dragDrop) { - display.scroller.dragDrop(); - } + }; + Delayed.prototype.set = function (ms, f) { + this.f = f; + var time = + /* @__PURE__ */new Date() + ms; + if (!this.id || time < this.time) { + clearTimeout(this.id); + this.id = setTimeout(this.handler, ms); + this.time = time; } - function rangeForUnit(cm, pos, unit) { - if (unit == "char") { - return new Range(pos, pos); - } - if (unit == "word") { - return cm.findWordAt(pos); - } - if (unit == "line") { - return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + }; + function indexOf(array, elt2) { + for (var i2 = 0; i2 < array.length; ++i2) { + if (array[i2] == elt2) { + return i2; } - var result = unit(cm, pos); - return new Range(result.from, result.to); } - function leftButtonSelect(cm, event, start, behavior) { - if (ie) { - delayBlurEvent(cm); - } - var display = cm.display, - doc = cm.doc; - e_preventDefault(event); - var ourRange, - ourIndex, - startSel = doc.sel, - ranges = startSel.ranges; - if (behavior.addNew && !behavior.extend) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) { - ourRange = ranges[ourIndex]; - } else { - ourRange = new Range(start, start); - } - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - if (behavior.unit == "rectangle") { - if (!behavior.addNew) { - ourRange = new Range(start, start); - } - start = posFromMouse(cm, event, true, true); - ourIndex = -1; - } else { - var range2 = rangeForUnit(cm, start, behavior.unit); - if (behavior.extend) { - ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend); - } else { - ourRange = range2; - } - } - if (!behavior.addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), { - scroll: false, - origin: "*mouse" - }); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { - setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), { - scroll: false, - origin: "*mouse" - }); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) { - return; - } - lastPos = pos; - if (behavior.unit == "rectangle") { - var ranges2 = [], - tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), - right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { - var text = getLine(doc, line).text, - leftPos = findColumn(text, left, tabSize); - if (left == right) { - ranges2.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - } else if (text.length > leftPos) { - ranges2.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - } - if (!ranges2.length) { - ranges2.push(new Range(start, start)); - } - setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex), { - origin: "*mouse", - scroll: false - }); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var range3 = rangeForUnit(cm, pos, behavior.unit); - var anchor = oldRange.anchor, - head; - if (cmp(range3.anchor, anchor) > 0) { - head = range3.head; - anchor = minPos(oldRange.from(), range3.anchor); - } else { - head = range3.anchor; - anchor = maxPos(oldRange.to(), range3.head); - } - var ranges$1 = startSel.ranges.slice(0); - ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); - setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); - } - } - var editorSize = display.wrapper.getBoundingClientRect(); - var counter = 0; - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); - if (!cur) { - return; - } - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) { - setTimeout(operation(cm, function () { - if (counter == curCount) { - extend(e); - } - }), 150); - } - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) { - setTimeout(operation(cm, function () { - if (counter != curCount) { - return; - } - display.scroller.scrollTop += outside; - extend(e); - }), 50); - } - } - } - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - if (e) { - e_preventDefault(e); - display.input.focus(); - } - off(display.wrapper.ownerDocument, "mousemove", move); - off(display.wrapper.ownerDocument, "mouseup", up); - doc.history.lastSelOrigin = null; - } - var move = operation(cm, function (e) { - if (e.buttons === 0 || !e_button(e)) { - done(e); - } else { - extend(e); - } - }); - var up = operation(cm, done); - cm.state.selectingText = up; - on(display.wrapper.ownerDocument, "mousemove", move); - on(display.wrapper.ownerDocument, "mouseup", up); + return -1; + } + var scrollerGap = 50; + var Pass = { + toString: function () { + return "CodeMirror.Pass"; } - function bidiSimplify(cm, range2) { - var anchor = range2.anchor; - var head = range2.head; - var anchorLine = getLine(cm.doc, anchor.line); - if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { - return range2; - } - var order = getOrder(anchorLine); - if (!order) { - return range2; - } - var index = getBidiPartAt(order, anchor.ch, anchor.sticky), - part = order[index]; - if (part.from != anchor.ch && part.to != anchor.ch) { - return range2; - } - var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1); - if (boundary == 0 || boundary == order.length) { - return range2; - } - var leftSide; - if (head.line != anchor.line) { - leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; - } else { - var headIndex = getBidiPartAt(order, head.ch, head.sticky); - var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); - if (headIndex == boundary - 1 || headIndex == boundary) { - leftSide = dir < 0; - } else { - leftSide = dir > 0; - } - } - var usePart = order[boundary + (leftSide ? -1 : 0)]; - var from = leftSide == (usePart.level == 1); - var ch = from ? usePart.from : usePart.to, - sticky = from ? "after" : "before"; - return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range(new Pos(anchor.line, ch, sticky), head); - } - function gutterEvent(cm, e, type, prevent) { - var mX, mY; - if (e.touches) { - mX = e.touches[0].clientX; - mY = e.touches[0].clientY; - } else { - try { - mX = e.clientX; - mY = e.clientY; - } catch (e$1) { - return false; - } + }; + var sel_dontScroll = { + scroll: false + }, + sel_mouse = { + origin: "*mouse" + }, + sel_move = { + origin: "+move" + }; + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf(" ", pos); + if (nextTab == -1) { + nextTab = string.length; + } + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) { + return pos + Math.min(skipped, goal - col); + } + col += nextTab - pos; + col += tabSize - col % tabSize; + pos = nextTab + 1; + if (col >= goal) { + return pos; } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { + } + } + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) { + spaceStrs.push(lst(spaceStrs) + " "); + } + return spaceStrs[n]; + } + function lst(arr) { + return arr[arr.length - 1]; + } + function map(array, f) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = f(array[i2], i2); + } + return out; + } + function insertSorted(array, value, score) { + var pos = 0, + priority = score(value); + while (pos < array.length && score(array[pos]) <= priority) { + pos++; + } + array.splice(pos, 0, value); + } + function nothing() {} + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) { + copyObj(props, inst); + } + return inst; + } + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "€" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + function isWordChar(ch, helper) { + if (!helper) { + return isWordCharBasic(ch); + } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { + return true; + } + return helper.test(ch); + } + function isEmpty(obj) { + for (var n in obj) { + if (obj.hasOwnProperty(n) && obj[n]) { return false; } - if (prevent) { - e_preventDefault(e); + } + return true; + } + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { + return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); + } + function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { + pos += dir; + } + return pos; + } + function findFirst(pred, from, to) { + var dir = from > to ? -1 : 1; + for (;;) { + if (from == to) { + return from; } - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - if (mY > lineBox.bottom || !hasHandler(cm, type)) { - return e_defaultPrevented(e); + var midF = (from + to) / 2, + mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); + if (mid == from) { + return pred(mid) ? from : to; } - mY -= lineBox.top - display.viewOffset; - for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) { - var g = display.gutters.childNodes[i2]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.display.gutterSpecs[i2]; - signal(cm, type, cm, line, gutter.className, e); - return e_defaultPrevented(e); - } + if (pred(mid)) { + to = mid; + } else { + from = mid + dir; } } - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true); + } + function iterateBidiSections(order, from, to, f) { + if (!order) { + return f(from, to, "ltr", 0); } - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { - return; + var found = false; + for (var i2 = 0; i2 < order.length; ++i2) { + var part = order[i2]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i2); + found = true; } - if (signalDOMEvent(cm, e, "contextmenu")) { - return; + } + if (!found) { + f(from, to, "ltr"); + } + } + var bidiOther = null; + function getBidiPartAt(order, ch, sticky) { + var found; + bidiOther = null; + for (var i2 = 0; i2 < order.length; ++i2) { + var cur = order[i2]; + if (cur.from < ch && cur.to > ch) { + return i2; } - if (!captureRightClick) { - cm.display.input.onContextMenu(e); + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { + found = i2; + } else { + bidiOther = i2; + } } - } - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) { - return false; + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { + found = i2; + } else { + bidiOther = i2; + } + } + } + return found != null ? found : bidiOther; + } + var bidiOrdering = /* @__PURE__ */function () { + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; + function charType(code) { + if (code <= 247) { + return lowTypes.charAt(code); + } else if (1424 <= code && code <= 1524) { + return "R"; + } else if (1536 <= code && code <= 1785) { + return arabicTypes.charAt(code - 1536); + } else if (1774 <= code && code <= 2220) { + return "r"; + } else if (8192 <= code && code <= 8203) { + return "w"; + } else if (code == 8204) { + return "b"; + } else { + return "L"; } - return gutterEvent(cm, e, "gutterContextMenu", false); } - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, + isStrong = /[LRr]/, + countsAsLeft = /[Lb1n]/, + countsAsNum = /[1n]/; + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; + this.to = to; } - var Init = { - toString: function () { - return "CodeMirror.Init"; + return function (str, direction) { + var outerType = direction == "ltr" ? "L" : "R"; + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { + return false; } - }; - var defaults = {}; - var optionHandlers = {}; - function defineOptions(CodeMirror2) { - var optionHandlers2 = CodeMirror2.optionHandlers; - function option(name, deflt, handle, notOnInit) { - CodeMirror2.defaults[name] = deflt; - if (handle) { - optionHandlers2[name] = notOnInit ? function (cm, val, old) { - if (old != Init) { - handle(cm, val, old); - } - } : handle; - } + var len = str.length, + types = []; + for (var i2 = 0; i2 < len; ++i2) { + types.push(charType(str.charCodeAt(i2))); } - CodeMirror2.defineOption = option; - CodeMirror2.Init = Init; - option("value", "", function (cm, val) { - return cm.setValue(val); - }, true); - option("mode", null, function (cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function (cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("lineSeparator", null, function (cm, val) { - cm.doc.lineSep = val; - if (!val) { - return; + for (var i$12 = 0, prev = outerType; i$12 < len; ++i$12) { + var type = types[i$12]; + if (type == "m") { + types[i$12] = prev; + } else { + prev = type; } - var newBreaks = [], - lineNo2 = cm.doc.first; - cm.doc.iter(function (line) { - for (var pos = 0;;) { - var found = line.text.indexOf(val, pos); - if (found == -1) { - break; - } - pos = found + val.length; - newBreaks.push(Pos(lineNo2, found)); + } + for (var i$22 = 0, cur = outerType; i$22 < len; ++i$22) { + var type$1 = types[i$22]; + if (type$1 == "1" && cur == "r") { + types[i$22] = "n"; + } else if (isStrong.test(type$1)) { + cur = type$1; + if (type$1 == "r") { + types[i$22] = "R"; } - lineNo2++; - }); - for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) { - replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length)); - } - }); - option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test(" ") ? "" : "| "), "g"); - if (old != Init) { - cm.refresh(); } - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { - return cm.refresh(); - }, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function () { - throw new Error("inputStyle can not (yet) be changed in a running editor"); - }, true); - option("spellcheck", false, function (cm, val) { - return cm.getInputField().spellcheck = val; - }, true); - option("autocorrect", false, function (cm, val) { - return cm.getInputField().autocorrect = val; - }, true); - option("autocapitalize", false, function (cm, val) { - return cm.getInputField().autocapitalize = val; - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - option("theme", "default", function (cm) { - themeChanged(cm); - updateGutters(cm); - }, true); - option("keyMap", "default", function (cm, val, old) { - var next = getKeyMap(val); - var prev = old != Init && getKeyMap(old); - if (prev && prev.detach) { - prev.detach(cm, next); + } + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3]; + if (type$2 == "+" && prev$1 == "1" && types[i$3 + 1] == "1") { + types[i$3] = "1"; + } else if (type$2 == "," && prev$1 == types[i$3 + 1] && (prev$1 == "1" || prev$1 == "n")) { + types[i$3] = prev$1; + } + prev$1 = type$2; + } + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4]; + if (type$3 == ",") { + types[i$4] = "N"; + } else if (type$3 == "%") { + var end = void 0; + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = i$4 && types[i$4 - 1] == "!" || end < len && types[end] == "1" ? "1" : "N"; + for (var j = i$4; j < end; ++j) { + types[j] = replace; + } + i$4 = end - 1; + } + } + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5]; + if (cur$1 == "L" && type$4 == "1") { + types[i$5] = "L"; + } else if (isStrong.test(type$4)) { + cur$1 = type$4; + } + } + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = void 0; + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6 - 1] : outerType) == "L"; + var after = (end$1 < len ? types[end$1] : outerType) == "L"; + var replace$1 = before == after ? before ? "L" : "R" : outerType; + for (var j$1 = i$6; j$1 < end$1; ++j$1) { + types[j$1] = replace$1; + } + i$6 = end$1 - 1; } - if (next.attach) { - next.attach(cm, prev || null); + } + var order = [], + m; + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7; + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)); + } else { + var pos = i$7, + at = order.length, + isRTL = direction == "rtl" ? 1 : 0; + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { + order.splice(at, 0, new BidiSpan(1, pos, j$2)); + at += isRTL; + } + var nstart = j$2; + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)); + at += isRTL; + pos = j$2; + } else { + ++j$2; + } + } + if (pos < i$7) { + order.splice(at, 0, new BidiSpan(1, pos, i$7)); + } } - }); - option("extraKeys", null); - option("configureMouse", null); - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function (cm, val) { - cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); - updateGutters(cm); - }, true); - option("fixedGutter", true, function (cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function (cm) { - return updateScrollbars(cm); - }, true); - option("scrollbarStyle", "native", function (cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function (cm, val) { - cm.display.gutterSpecs = getGutters(cm.options.gutters, val); - updateGutters(cm); - }, true); - option("firstLineNumber", 1, updateGutters, true); - option("lineNumberFormatter", function (integer) { - return integer; - }, updateGutters, true); - option("showCursorWhenSelecting", false, updateSelection, true); - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - option("pasteLinesPerSelection", true); - option("selectionsMayTouch", false); - option("readOnly", false, function (cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); } - cm.display.input.readOnlyChanged(val); - }); - option("screenReaderLabel", null, function (cm, val) { - val = val === "" ? null : val; - cm.display.input.screenReaderLabelChanged(val); - }); - option("disableInput", false, function (cm, val) { - if (!val) { - cm.display.input.reset(); + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); } - }, true); - option("dragDrop", true, dragDropChanged); - option("allowDropFileTypes", null); - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function (cm, val) { - return cm.doc.history.undoDepth = val; - }); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function (cm) { - return cm.refresh(); - }, true); - option("maxHighlightLength", 1e4, resetModeState, true); - option("moveInputWithCursor", true, function (cm, val) { - if (!val) { - cm.display.input.resetPosition(); + } + return direction == "rtl" ? order.reverse() : order; + }; + }(); + function getOrder(line, direction) { + var order = line.order; + if (order == null) { + order = line.order = bidiOrdering(line.text, direction); + } + return order; + } + var noHandlers = []; + var on = function (emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false); + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f); + } else { + var map2 = emitter._handlers || (emitter._handlers = {}); + map2[type] = (map2[type] || noHandlers).concat(f); + } + }; + function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers; + } + function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false); + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f); + } else { + var map2 = emitter._handlers, + arr = map2 && map2[type]; + if (arr) { + var index = indexOf(arr, f); + if (index > -1) { + map2[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } - }); - option("tabindex", null, function (cm, val) { - return cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - option("direction", "ltr", function (cm, val) { - return cm.doc.setDirection(val); - }, true); - option("phrases", null); - } - function dragDropChanged(cm, value, old) { - var wasOn = old && old != Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.enter); - toggle(cm.display.scroller, "dragover", funcs.over); - toggle(cm.display.scroller, "dragleave", funcs.leave); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function () { - return updateScrollbars(cm); - }, 100); } - function CodeMirror(place, options) { - var this$1$1 = this; - if (!(this instanceof CodeMirror)) { - return new CodeMirror(place, options); - } - this.options = options = options ? copyObj(options) : {}; - copyObj(defaults, options, false); - var doc = options.value; - if (typeof doc == "string") { - doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); - } else if (options.mode) { - doc.modeOption = options.mode; - } - this.doc = doc; - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input, options); - display.wrapper.CodeMirror = this; - themeChanged(this); - if (options.lineWrapping) { - this.display.wrapper.className += " CodeMirror-wrap"; - } - initScrollbars(this); - this.state = { - keyMaps: [], - // stores maps added by addKeyMap - overlays: [], - // highlighting overlays, as added by addOverlay - modeGen: 0, - // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, - // used to disable editing during key handlers when in readOnly mode - pasteIncoming: -1, - cutIncoming: -1, - // help recognize paste/cut edits in input.poll - selectingText: false, - draggingText: false, - highlight: new Delayed(), - // stores highlight worker timeout - keySeq: null, - // Unfinished key sequence - specialChars: null + } + function signal(emitter, type) { + var handlers = getHandlers(emitter, type); + if (!handlers.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2); + for (var i2 = 0; i2 < handlers.length; ++i2) { + handlers[i2].apply(null, args); + } + } + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") { + e = { + type: e, + preventDefault: function () { + this.defaultPrevented = true; + } }; - if (options.autofocus && !mobile) { - display.input.focus(); + } + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) { + return; + } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i2 = 0; i2 < arr.length; ++i2) { + if (indexOf(set, arr[i2]) == -1) { + set.push(arr[i2]); } - if (ie && ie_version < 11) { - setTimeout(function () { - return this$1$1.display.input.reset(true); - }, 20); + } + } + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0; + } + function eventMixin(ctor) { + ctor.prototype.on = function (type, f) { + on(this, type, f); + }; + ctor.prototype.off = function (type, f) { + off(this, type, f); + }; + } + function e_preventDefault(e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + } + } + function e_stopPropagation(e) { + if (e.stopPropagation) { + e.stopPropagation(); + } else { + e.cancelBubble = true; + } + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + function e_stop(e) { + e_preventDefault(e); + e_stopPropagation(e); + } + function e_target(e) { + return e.target || e.srcElement; + } + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) { + b = 1; + } else if (e.button & 2) { + b = 3; + } else if (e.button & 4) { + b = 2; } - registerEventHandlers(this); - ensureGlobalHandlers(); - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - if (options.autofocus && !mobile || this.hasFocus()) { - setTimeout(function () { - if (this$1$1.hasFocus() && !this$1$1.state.focused) { - onFocus(this$1$1); - } - }, 20); + } + if (mac && e.ctrlKey && b == 1) { + b = 3; + } + return b; + } + var dragAndDrop = function () { + if (ie && ie_version < 9) { + return false; + } + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + }(); + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "​"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) { + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); + } + } + var node = zwspSupported ? elt("span", "​") : elt("span", " ", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) { + return badBidiRects; + } + var txt = removeChildrenAndAdd(measure, document.createTextNode("AخA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + var r1 = range(txt, 1, 2).getBoundingClientRect(); + removeChildren(measure); + if (!r0 || r0.left == r0.right) { + return false; + } + return badBidiRects = r1.right - r0.right < 3; + } + var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, + result = [], + l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) { + nl = string.length; + } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; } else { - onBlur(this); - } - for (var opt in optionHandlers) { - if (optionHandlers.hasOwnProperty(opt)) { - optionHandlers[opt](this, options[opt], Init); - } - } - maybeUpdateLineNumberWidth(this); - if (options.finishInit) { - options.finishInit(this); - } - for (var i2 = 0; i2 < initHooks.length; ++i2) { - initHooks[i2](this); - } - endOperation(this); - if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { - display.lineDiv.style.textRendering = "auto"; + result.push(line); + pos = nl + 1; } } - CodeMirror.defaults = defaults; - CodeMirror.optionHandlers = optionHandlers; - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - if (ie && ie_version < 11) { - on(d.scroller, "dblclick", operation(cm, function (e) { - if (signalDOMEvent(cm, e)) { - return; - } - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { - return; - } - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - } else { - on(d.scroller, "dblclick", function (e) { - return signalDOMEvent(cm, e) || e_preventDefault(e); - }); + return result; + } : function (string) { + return string.split(/\r\n?|\n/); + }; + var hasSelection = window.getSelection ? function (te) { + try { + return te.selectionStart != te.selectionEnd; + } catch (e) { + return false; + } + } : function (te) { + var range2; + try { + range2 = te.ownerDocument.selection.createRange(); + } catch (e) {} + if (!range2 || range2.parentElement() != te) { + return false; + } + return range2.compareEndPoints("StartToEnd", range2) != 0; + }; + var hasCopyEvent = function () { + var e = elt("div"); + if ("oncopy" in e) { + return true; + } + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + }(); + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { + return badZoomedRects; + } + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + var modes = {}, + mimeModes = {}; + function defineMode(name, mode) { + if (arguments.length > 2) { + mode.dependencies = Array.prototype.slice.call(arguments, 2); + } + modes[name] = mode; + } + function defineMIME(mime, spec) { + mimeModes[mime] = spec; + } + function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") { + found = { + name: found + }; } - on(d.scroller, "contextmenu", function (e) { - return onContextMenu(cm, e); - }); - on(d.input.getField(), "contextmenu", function (e) { - if (!d.scroller.contains(e.target)) { - onContextMenu(cm, e); + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml"); + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json"); + } + if (typeof spec == "string") { + return { + name: spec + }; + } else { + return spec || { + name: "null" + }; + } + } + function getMode(options, spec) { + spec = resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) { + return getMode(options, "text/plain"); + } + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop2 in exts) { + if (!exts.hasOwnProperty(prop2)) { + continue; } - }); - var touchFinished, - prevTouch = { - end: 0 - }; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function () { - return d.activeTouch = null; - }, 1e3); - prevTouch = d.activeTouch; - prevTouch.end = + /* @__PURE__ */new Date(); + if (modeObj.hasOwnProperty(prop2)) { + modeObj["_" + prop2] = modeObj[prop2]; } + modeObj[prop2] = exts[prop2]; } - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) { - return false; - } - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; + } + modeObj.name = spec.name; + if (spec.helperType) { + modeObj.helperType = spec.helperType; + } + if (spec.modeProps) { + for (var prop$1 in spec.modeProps) { + modeObj[prop$1] = spec.modeProps[prop$1]; } - function farAway(touch, other) { - if (other.left == null) { - return true; - } - var dx = other.left - touch.left, - dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function (e) { - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { - d.input.ensurePolled(); - clearTimeout(touchFinished); - var now = + /* @__PURE__ */new Date(); - d.activeTouch = { - start: now, - moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null - }; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function () { - if (d.activeTouch) { - d.activeTouch.moved = true; - } - }); - on(d.scroller, "touchend", function (e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && /* @__PURE__ */new Date() - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), - range2; - if (!touch.prev || farAway(touch, touch.prev)) { - range2 = new Range(pos, pos); - } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) { - range2 = cm.findWordAt(pos); - } else { - range2 = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - } - cm.setSelection(range2.anchor, range2.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - on(d.scroller, "scroll", function () { - if (d.scroller.clientHeight) { - updateScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); - on(d.scroller, "mousewheel", function (e) { - return onScrollWheel(cm, e); - }); - on(d.scroller, "DOMMouseScroll", function (e) { - return onScrollWheel(cm, e); - }); - on(d.wrapper, "scroll", function () { - return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; - }); - d.dragFunctions = { - enter: function (e) { - if (!signalDOMEvent(cm, e)) { - e_stop(e); - } - }, - over: function (e) { - if (!signalDOMEvent(cm, e)) { - onDragOver(cm, e); - e_stop(e); - } - }, - start: function (e) { - return onDragStart(cm, e); - }, - drop: operation(cm, onDrop), - leave: function (e) { - if (!signalDOMEvent(cm, e)) { - clearDragCursor(cm); - } - } - }; - var inp = d.input.getField(); - on(inp, "keyup", function (e) { - return onKeyUp.call(cm, e); - }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", function (e) { - return onFocus(cm, e); - }); - on(inp, "blur", function (e) { - return onBlur(cm, e); - }); } - var initHooks = []; - CodeMirror.defineInitHook = function (f) { - return initHooks.push(f); + return modeObj; + } + var modeExtensions = {}; + function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : modeExtensions[mode] = {}; + copyObj(properties, exts); + } + function copyState(mode, state) { + if (state === true) { + return state; + } + if (mode.copyState) { + return mode.copyState(state); + } + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) { + val = val.concat([]); + } + nstate[n] = val; + } + return nstate; + } + function innerMode(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) { + break; + } + state = info.state; + mode = info.mode; + } + return info || { + mode, + state }; - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, - state; - if (how == null) { - how = "add"; - } - if (how == "smart") { - if (!doc.mode.indent) { - how = "prev"; - } else { - state = getContextBefore(cm, n).state; + } + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + var StringStream = function (string, tabSize, lineOracle) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.lineOracle = lineOracle; + }; + StringStream.prototype.eol = function () { + return this.pos >= this.string.length; + }; + StringStream.prototype.sol = function () { + return this.pos == this.lineStart; + }; + StringStream.prototype.peek = function () { + return this.string.charAt(this.pos) || void 0; + }; + StringStream.prototype.next = function () { + if (this.pos < this.string.length) { + return this.string.charAt(this.pos++); + } + }; + StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos); + var ok; + if (typeof match == "string") { + ok = ch == match; + } else { + ok = ch && (match.test ? match.test(ch) : match(ch)); + } + if (ok) { + ++this.pos; + return ch; + } + }; + StringStream.prototype.eatWhile = function (match) { + var start = this.pos; + while (this.eat(match)) {} + return this.pos > start; + }; + StringStream.prototype.eatSpace = function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { + ++this.pos; + } + return this.pos > start; + }; + StringStream.prototype.skipToEnd = function () { + this.pos = this.string.length; + }; + StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) { + this.pos = found; + return true; + } + }; + StringStream.prototype.backUp = function (n) { + this.pos -= n; + }; + StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }; + StringStream.prototype.indentation = function () { + return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }; + StringStream.prototype.match = function (pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { + return caseInsensitive ? str.toLowerCase() : str; + }; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) { + this.pos += pattern.length; } + return true; } - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), - curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) { - line.stateAfter = null; + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) { + return null; } - var curSpaceString = line.text.match(/^\s*/)[0], - indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) { - return; - } - how = "prev"; + if (match && consume !== false) { + this.pos += match[0].length; + } + return match; + } + }; + StringStream.prototype.current = function () { + return this.string.slice(this.start, this.pos); + }; + StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n; + try { + return inner(); + } finally { + this.lineStart -= n; + } + }; + StringStream.prototype.lookAhead = function (n) { + var oracle = this.lineOracle; + return oracle && oracle.lookAhead(n); + }; + StringStream.prototype.baseToken = function () { + var oracle = this.lineOracle; + return oracle && oracle.baseToken(this.pos); + }; + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) { + throw new Error("There is no line " + (n + doc.first) + " in the document."); + } + var chunk = doc; + while (!chunk.lines) { + for (var i2 = 0;; ++i2) { + var child = chunk.children[i2], + sz = child.chunkSize(); + if (n < sz) { + chunk = child; + break; } + n -= sz; } - if (how == "prev") { - if (n > doc.first) { - indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); - } else { - indentation = 0; - } - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - var indentString = "", - pos = 0; - if (cm.options.indentWithTabs) { - for (var i2 = Math.floor(indentation / tabSize); i2; --i2) { - pos += tabSize; - indentString += " "; - } + } + return chunk.lines[n]; + } + function getBetween(doc, start, end) { + var out = [], + n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) { + text = text.slice(0, end.ch); } - if (pos < indentation) { - indentString += spaceStr(indentation - pos); + if (n == start.line) { + text = text.slice(start.ch); } - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - for (var i$12 = 0; i$12 < doc.sel.ranges.length; i$12++) { - var range2 = doc.sel.ranges[i$12]; - if (range2.head.line == n && range2.head.ch < curSpaceString.length) { - var pos$1 = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i$12, new Range(pos$1, pos$1)); - break; - } - } + out.push(text); + ++n; + }); + return out; + } + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function (line) { + out.push(line.text); + }); + return out; + } + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) { + for (var n = line; n; n = n.parent) { + n.height += diff; } } - var lastCopied = null; - function setLastCopied(newLastCopied) { - lastCopied = newLastCopied; - } - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) { - sel = doc.sel; - } - var recent = + /* @__PURE__ */new Date() - 200; - var paste = origin == "paste" || cm.state.pasteIncoming > recent; - var textLines = splitLinesAuto(inserted), - multiPaste = null; - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.text.join("\n") == inserted) { - if (sel.ranges.length % lastCopied.text.length == 0) { - multiPaste = []; - for (var i2 = 0; i2 < lastCopied.text.length; i2++) { - multiPaste.push(doc.splitLines(lastCopied.text[i2])); - } - } - } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { - multiPaste = map(textLines, function (l) { - return [l]; - }); + } + function lineNo(line) { + if (line.parent == null) { + return null; + } + var cur = line.parent, + no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i2 = 0;; ++i2) { + if (chunk.children[i2] == cur) { + break; } + no += chunk.children[i2].chunkSize(); } - var updateInput = cm.curOp.updateInput; - for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) { - var range2 = sel.ranges[i$12]; - var from = range2.from(), - to = range2.to(); - if (range2.empty()) { - if (deleted && deleted > 0) { - from = Pos(from.line, from.ch - deleted); - } else if (cm.state.overwrite && !paste) { - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { - from = to = Pos(from.line, 0); - } + } + return no + cur.first; + } + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i$12 = 0; i$12 < chunk.children.length; ++i$12) { + var child = chunk.children[i$12], + ch = child.height; + if (h < ch) { + chunk = child; + continue outer; } - var changeEvent = { - from, - to, - text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input") - }; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); + h -= ch; + n += child.chunkSize(); } - if (inserted && !paste) { - triggerElectric(cm, inserted); - } - ensureCursorVisible(cm); - if (cm.curOp.updateInput < 2) { - cm.curOp.updateInput = updateInput; + return n; + } while (!chunk.lines); + var i2 = 0; + for (; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2], + lh = line.height; + if (h < lh) { + break; } - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = -1; + h -= lh; } - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) { - runInOp(cm, function () { - return applyTextInput(cm, pasted, 0, null, "paste"); - }); - } - return true; - } + return n + i2; + } + function isLine(doc, l) { + return l >= doc.first && l < doc.first + doc.size; + } + function lineNumberFor(options, i2) { + return String(options.lineNumberFormatter(i2 + options.firstLineNumber)); + } + function Pos(line, ch, sticky) { + if (sticky === void 0) sticky = null; + if (!(this instanceof Pos)) { + return new Pos(line, ch, sticky); } - function triggerElectric(cm, inserted) { - if (!cm.options.electricChars || !cm.options.smartIndent) { - return; - } - var sel = cm.doc.sel; - for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { - var range2 = sel.ranges[i2]; - if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) { - continue; - } - var mode = cm.getModeAt(range2.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) { - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range2.head.line, "smart"); - break; - } - } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) { - indented = indentLine(cm, range2.head.line, "smart"); + this.line = line; + this.ch = ch; + this.sticky = sticky; + } + function cmp(a, b) { + return a.line - b.line || a.ch - b.ch; + } + function equalCursorPos(a, b) { + return a.sticky == b.sticky && cmp(a, b) == 0; + } + function copyPos(x) { + return Pos(x.line, x.ch); + } + function maxPos(a, b) { + return cmp(a, b) < 0 ? b : a; + } + function minPos(a, b) { + return cmp(a, b) < 0 ? a : b; + } + function clipLine(doc, n) { + return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1)); + } + function clipPos(doc, pos) { + if (pos.line < doc.first) { + return Pos(doc.first, 0); + } + var last = doc.first + doc.size - 1; + if (pos.line > last) { + return Pos(last, getLine(doc, last).text.length); + } + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) { + return Pos(pos.line, linelen); + } else if (ch < 0) { + return Pos(pos.line, 0); + } else { + return pos; + } + } + function clipPosArray(doc, array) { + var out = []; + for (var i2 = 0; i2 < array.length; i2++) { + out[i2] = clipPos(doc, array[i2]); + } + return out; + } + var SavedContext = function (state, lookAhead) { + this.state = state; + this.lookAhead = lookAhead; + }; + var Context = function (doc, state, line, lookAhead) { + this.state = state; + this.doc = doc; + this.line = line; + this.maxLookAhead = lookAhead || 0; + this.baseTokens = null; + this.baseTokenPos = 1; + }; + Context.prototype.lookAhead = function (n) { + var line = this.doc.getLine(this.line + n); + if (line != null && n > this.maxLookAhead) { + this.maxLookAhead = n; + } + return line; + }; + Context.prototype.baseToken = function (n) { + if (!this.baseTokens) { + return null; + } + while (this.baseTokens[this.baseTokenPos] <= n) { + this.baseTokenPos += 2; + } + var type = this.baseTokens[this.baseTokenPos + 1]; + return { + type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n + }; + }; + Context.prototype.nextLine = function () { + this.line++; + if (this.maxLookAhead > 0) { + this.maxLookAhead--; + } + }; + Context.fromSaved = function (doc, saved, line) { + if (saved instanceof SavedContext) { + return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead); + } else { + return new Context(doc, copyState(doc.mode, saved), line); + } + }; + Context.prototype.save = function (copy) { + var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state; + }; + function highlightLine(cm, line, context, forceToEnd) { + var st = [cm.state.modeGen], + lineClasses = {}; + runMode(cm, line.text, cm.doc.mode, context, function (end, style) { + return st.push(end, style); + }, lineClasses, forceToEnd); + var state = context.state; + var loop = function (o2) { + context.baseTokens = st; + var overlay = cm.state.overlays[o2], + i2 = 1, + at = 0; + context.state = true; + runMode(cm, line.text, overlay.mode, context, function (end, style) { + var start = i2; + while (at < end) { + var i_end = st[i2]; + if (i_end > end) { + st.splice(i2, 1, end, st[i2 + 1], i_end); } + i2 += 2; + at = Math.min(end, i_end); + } + if (!style) { + return; } - if (indented) { - signalLater(cm, "electricInput", cm, range2.head.line); + if (overlay.opaque) { + st.splice(start, i2 - start, end, "overlay " + style); + i2 = start + 2; + } else { + for (; start < i2; start += 2) { + var cur = st[start + 1]; + st[start + 1] = (cur ? cur + " " : "") + "overlay " + style; + } } - } + }, lineClasses); + context.state = state; + context.baseTokens = null; + context.baseTokenPos = 1; + }; + for (var o = 0; o < cm.state.overlays.length; ++o) loop(o); + return { + styles: st, + classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null + }; + } + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)); + var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); + var result = highlightLine(cm, line, context); + if (resetState) { + context.state = resetState; + } + line.stateAfter = context.save(!resetState); + line.styles = result.styles; + if (result.classes) { + line.styleClasses = result.classes; + } else if (line.styleClasses) { + line.styleClasses = null; + } + if (updateFrontier === cm.doc.highlightFrontier) { + cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); + } + } + return line.styles; + } + function getContextBefore(cm, n, precise) { + var doc = cm.doc, + display = cm.display; + if (!doc.mode.startState) { + return new Context(doc, true, n); + } + var start = findStartLine(cm, n, precise); + var saved = start > doc.first && getLine(doc, start - 1).stateAfter; + var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); + doc.iter(start, n, function (line) { + processLine(cm, line.text, context); + var pos = context.line; + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; + context.nextLine(); + }); + if (precise) { + doc.modeFrontier = context.line; } - function copyableRanges(cm) { - var text = [], - ranges = []; - for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { - var line = cm.doc.sel.ranges[i2].head.line; - var lineRange = { - anchor: Pos(line, 0), - head: Pos(line + 1, 0) - }; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return { - text, - ranges - }; + return context; + } + function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize, context); + stream.start = stream.pos = startAt || 0; + if (text == "") { + callBlankLine(mode, context.state); } - function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { - field.setAttribute("autocorrect", autocorrect ? "" : "off"); - field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); - field.setAttribute("spellcheck", !!spellcheck); + while (!stream.eol()) { + readToken(mode, stream, context.state); + stream.start = stream.pos; } - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - if (webkit) { - te.style.width = "1000px"; - } else { - te.setAttribute("wrap", "off"); - } - if (ios) { - te.style.border = "1px solid black"; - } - disableBrowserMagic(te); - return div; - } - function addEditorMethods(CodeMirror2) { - var optionHandlers2 = CodeMirror2.optionHandlers; - var helpers = CodeMirror2.helpers = {}; - CodeMirror2.prototype = { - constructor: CodeMirror2, - focus: function () { - window.focus(); - this.display.input.focus(); - }, - setOption: function (option, value) { - var options = this.options, - old = options[option]; - if (options[option] == value && option != "mode") { - return; - } - options[option] = value; - if (optionHandlers2.hasOwnProperty(option)) { - operation(this, optionHandlers2[option])(this, value, old); - } - signal(this, "optionChange", this, option); - }, - getOption: function (option) { - return this.options[option]; - }, - getDoc: function () { - return this.doc; - }, - addKeyMap: function (map2, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map2)); - }, - removeKeyMap: function (map2) { - var maps = this.state.keyMaps; - for (var i2 = 0; i2 < maps.length; ++i2) { - if (maps[i2] == map2 || maps[i2].name == map2) { - maps.splice(i2, 1); - return true; - } - } - }, - addOverlay: methodOp(function (spec, options) { - var mode = spec.token ? spec : CodeMirror2.getMode(this.options, spec); - if (mode.startState) { - throw new Error("Overlays may not be stateful."); - } - insertSorted(this.state.overlays, { - mode, - modeSpec: spec, - opaque: options && options.opaque, - priority: options && options.priority || 0 - }, function (overlay) { - return overlay.priority; - }); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function (spec) { - var overlays = this.state.overlays; - for (var i2 = 0; i2 < overlays.length; ++i2) { - var cur = overlays[i2].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i2, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - indentLine: methodOp(function (n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) { - dir = this.options.smartIndent ? "smart" : "prev"; - } else { - dir = dir ? "add" : "subtract"; - } - } - if (isLine(this.doc, n)) { - indentLine(this, n, dir, aggressive); - } - }), - indentSelection: methodOp(function (how) { - var ranges = this.doc.sel.ranges, - end = -1; - for (var i2 = 0; i2 < ranges.length; i2++) { - var range2 = ranges[i2]; - if (!range2.empty()) { - var from = range2.from(), - to = range2.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) { - indentLine(this, j, how); - } - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) { - replaceOneSelection(this.doc, i2, new Range(from, newRanges[i2].to()), sel_dontScroll); - } - } else if (range2.head.line > end) { - indentLine(this, range2.head.line, how, true); - end = range2.head.line; - if (i2 == this.doc.sel.primIndex) { - ensureCursorVisible(this); - } - } - } - }), - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function (pos, precise) { - return takeToken(this, pos, precise); - }, - getLineTokens: function (line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - getTokenTypeAt: function (pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, - after = (styles.length - 1) / 2, - ch = pos.ch; - var type; - if (ch == 0) { - type = styles[2]; - } else { - for (;;) { - var mid = before + after >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { - after = mid; - } else if (styles[mid * 2 + 1] < ch) { - before = mid + 1; - } else { - type = styles[mid * 2 + 2]; - break; - } - } - } - var cut = type ? type.indexOf("overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - getModeAt: function (pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { - return mode; - } - return CodeMirror2.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - getHelper: function (pos, type) { - return this.getHelpers(pos, type)[0]; - }, - getHelpers: function (pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) { - return found; - } - var help = helpers[type], - mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) { - found.push(help[mode[type]]); - } - } else if (mode[type]) { - for (var i2 = 0; i2 < mode[type].length; i2++) { - var val = help[mode[type][i2]]; - if (val) { - found.push(val); - } - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i$12 = 0; i$12 < help._global.length; i$12++) { - var cur = help._global[i$12]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { - found.push(cur.val); - } - } - return found; - }, - getStateAfter: function (line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); - return getContextBefore(this, line + 1, precise).state; - }, - cursorCoords: function (start, mode) { - var pos, - range2 = this.doc.sel.primary(); - if (start == null) { - pos = range2.head; - } else if (typeof start == "object") { - pos = clipPos(this.doc, start); - } else { - pos = start ? range2.from() : range2.to(); - } - return cursorCoords(this, pos, mode || "page"); - }, - charCoords: function (pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - coordsChar: function (coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - lineAtHeight: function (height, mode) { - height = fromCoordSystem(this, { - top: height, - left: 0 - }, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function (line, mode, includeWidgets) { - var end = false, - lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) { - line = this.doc.first; - } else if (line > last) { - line = last; - end = true; - } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, { - top: 0, - left: 0 - }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, - defaultTextHeight: function () { - return textHeight(this.display); - }, - defaultCharWidth: function () { - return charWidth(this.display); - }, - getViewport: function () { - return { - from: this.display.viewFrom, - to: this.display.viewTo - }; - }, - addWidget: function (pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, - left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { - top = pos.top - node.offsetHeight; - } else if (pos.bottom + node.offsetHeight <= vspace) { - top = pos.bottom; - } - if (left + node.offsetWidth > hspace) { - left = hspace - node.offsetWidth; - } - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") { - left = 0; - } else if (horiz == "middle") { - left = (display.sizer.clientWidth - node.offsetWidth) / 2; - } - node.style.left = left + "px"; - } - if (scroll) { - scrollIntoView(this, { - left, - top, - right: left + node.offsetWidth, - bottom: top + node.offsetHeight - }); - } - }, - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - execCommand: function (cmd) { - if (commands.hasOwnProperty(cmd)) { - return commands[cmd].call(null, this); - } - }, - triggerElectric: methodOp(function (text) { - triggerElectric(this, text); - }), - findPosH: function (from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i2 = 0; i2 < amount; ++i2) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) { - break; - } - } - return cur; - }, - moveH: methodOp(function (dir, unit) { - var this$1$1 = this; - this.extendSelectionsBy(function (range2) { - if (this$1$1.display.shift || this$1$1.doc.extend || range2.empty()) { - return findPosH(this$1$1.doc, range2.head, dir, unit, this$1$1.options.rtlMoveVisually); - } else { - return dir < 0 ? range2.from() : range2.to(); - } - }, sel_move); - }), - deleteH: methodOp(function (dir, unit) { - var sel = this.doc.sel, - doc = this.doc; - if (sel.somethingSelected()) { - doc.replaceSelection("", null, "+delete"); - } else { - deleteNearSelection(this, function (range2) { - var other = findPosH(doc, range2.head, dir, unit, false); - return dir < 0 ? { - from: other, - to: range2.head - } : { - from: range2.head, - to: other - }; - }); - } - }), - findPosV: function (from, amount, unit, goalColumn) { - var dir = 1, - x = goalColumn; - if (amount < 0) { - dir = -1; - amount = -amount; - } - var cur = clipPos(this.doc, from); - for (var i2 = 0; i2 < amount; ++i2) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) { - x = coords.left; - } else { - coords.left = x; - } - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) { - break; - } - } - return cur; - }, - moveV: methodOp(function (dir, unit) { - var this$1$1 = this; - var doc = this.doc, - goals = []; - var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function (range2) { - if (collapse) { - return dir < 0 ? range2.from() : range2.to(); - } - var headPos = cursorCoords(this$1$1, range2.head, "div"); - if (range2.goalColumn != null) { - headPos.left = range2.goalColumn; - } - goals.push(headPos.left); - var pos = findPosV(this$1$1, headPos, dir, unit); - if (unit == "page" && range2 == doc.sel.primary()) { - addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top); - } - return pos; - }, sel_move); - if (goals.length) { - for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { - doc.sel.ranges[i2].goalColumn = goals[i2]; - } - } - }), - // Find the word at the given position (as returned by coordsChar). - findWordAt: function (pos) { - var doc = this.doc, - line = getLine(doc, pos.line).text; - var start = pos.ch, - end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.sticky == "before" || end == line.length) && start) { - --start; - } else { - ++end; - } - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) ? function (ch) { - return isWordChar(ch, helper); - } : /\s/.test(startChar) ? function (ch) { - return /\s/.test(ch); - } : function (ch) { - return !/\s/.test(ch) && !isWordChar(ch); - }; - while (start > 0 && check(line.charAt(start - 1))) { - --start; - } - while (end < line.length && check(line.charAt(end))) { - ++end; - } - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - toggleOverwrite: function (value) { - if (value != null && value == this.state.overwrite) { - return; - } - if (this.state.overwrite = !this.state.overwrite) { - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } else { - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - } - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function () { - return this.display.input.getField() == activeElt(); - }, - isReadOnly: function () { - return !!(this.options.readOnly || this.doc.cantEdit); - }, - scrollTo: methodOp(function (x, y) { - scrollToCoords(this, x, y); - }), - getScrollInfo: function () { - var scroller = this.display.scroller; - return { - left: scroller.scrollLeft, - top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), - clientWidth: displayWidth(this) - }; - }, - scrollIntoView: methodOp(function (range2, margin) { - if (range2 == null) { - range2 = { - from: this.doc.sel.primary().head, - to: null - }; - if (margin == null) { - margin = this.options.cursorScrollMargin; - } - } else if (typeof range2 == "number") { - range2 = { - from: Pos(range2, 0), - to: null - }; - } else if (range2.from == null) { - range2 = { - from: range2, - to: null - }; - } - if (!range2.to) { - range2.to = range2.from; - } - range2.margin = margin || 0; - if (range2.from.line != null) { - scrollToRange(this, range2); - } else { - scrollToCoordsRange(this, range2.from, range2.to, range2.margin); - } - }), - setSize: methodOp(function (width, height) { - var this$1$1 = this; - var interpret = function (val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - }; - if (width != null) { - this.display.wrapper.style.width = interpret(width); - } - if (height != null) { - this.display.wrapper.style.height = interpret(height); - } - if (this.options.lineWrapping) { - clearLineMeasurementCache(this); - } - var lineNo2 = this.display.viewFrom; - this.doc.iter(lineNo2, this.display.viewTo, function (line) { - if (line.widgets) { - for (var i2 = 0; i2 < line.widgets.length; i2++) { - if (line.widgets[i2].noHScroll) { - regLineChange(this$1$1, lineNo2, "widget"); - break; - } - } - } - ++lineNo2; - }); - this.curOp.forceUpdate = true; - signal(this, "refresh", this); - }), - operation: function (f) { - return runInOp(this, f); - }, - startOperation: function () { - return startOperation(this); - }, - endOperation: function () { - return endOperation(this); - }, - refresh: methodOp(function () { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this.display); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) { - estimateLineHeights(this); - } - signal(this, "refresh", this); - }), - swapDoc: methodOp(function (doc) { - var old = this.doc; - old.cm = null; - if (this.state.selectingText) { - this.state.selectingText(); - } - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - scrollToCoords(this, doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - phrase: function (phraseText) { - var phrases = this.options.phrases; - return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText; - }, - getInputField: function () { - return this.display.input.getField(); - }, - getWrapperElement: function () { - return this.display.wrapper; - }, - getScrollerElement: function () { - return this.display.scroller; - }, - getGutterElement: function () { - return this.display.gutters; + } + function callBlankLine(mode, state) { + if (mode.blankLine) { + return mode.blankLine(state); + } + if (!mode.innerMode) { + return; + } + var inner = innerMode(mode, state); + if (inner.mode.blankLine) { + return inner.mode.blankLine(inner.state); + } + } + function readToken(mode, stream, state, inner) { + for (var i2 = 0; i2 < 10; i2++) { + if (inner) { + inner[0] = innerMode(mode, state).mode; + } + var style = mode.token(stream, state); + if (stream.pos > stream.start) { + return style; + } + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + var Token = function (stream, type, state) { + this.start = stream.start; + this.end = stream.pos; + this.string = stream.current(); + this.type = type || null; + this.state = state; + }; + function takeToken(cm, pos, precise, asArray) { + var doc = cm.doc, + mode = doc.mode, + style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), + context = getContextBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize, context), + tokens; + if (asArray) { + tokens = []; + } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, context.state); + if (asArray) { + tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); + } + } + return asArray ? tokens : new Token(stream, style, context.state); + } + function extractLineClasses(type, output) { + if (type) { + for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) { + break; } - }; - eventMixin(CodeMirror2); - CodeMirror2.registerHelper = function (type, name, value) { - if (!helpers.hasOwnProperty(type)) { - helpers[type] = CodeMirror2[type] = { - _global: [] - }; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop2 = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop2] == null) { + output[prop2] = lineClass[2]; + } else if (!new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)").test(output[prop2])) { + output[prop2] += " " + lineClass[2]; } - helpers[type][name] = value; - }; - CodeMirror2.registerGlobalHelper = function (type, name, predicate, value) { - CodeMirror2.registerHelper(type, name, value); - helpers[type]._global.push({ - pred: predicate, - val: value - }); - }; + } } - function findPosH(doc, pos, dir, unit, visually) { - var oldPos = pos; - var origDir = dir; - var lineObj = getLine(doc, pos.line); - var lineDir = visually && doc.direction == "rtl" ? -dir : dir; - function findNextLine() { - var l = pos.line + lineDir; - if (l < doc.first || l >= doc.first + doc.size) { - return false; + return type; + } + function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) { + flattenSpans = cm.options.flattenSpans; + } + var curStart = 0, + curStyle = null; + var stream = new StringStream(text, cm.options.tabSize, context), + style; + var inner = cm.options.addModeClass && [null]; + if (text == "") { + extractLineClasses(callBlankLine(mode, context.state), lineClasses); + } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) { + processLine(cm, text, context, stream.pos); + } + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) { + style = "m-" + (style ? mName + " " + style : mName); } - pos = new Pos(l, pos.ch, pos.sticky); - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next; - if (unit == "codepoint") { - var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); - if (isNaN(ch)) { - next = null; - } else { - var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343; - next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); - } - } else if (visually) { - next = moveVisually(doc.cm, lineObj, pos, dir); - } else { - next = moveLogically(lineObj, pos, dir); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5e3); + f(curStart, curStyle); } - if (next == null) { - if (!boundToLine && findNextLine()) { - pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); - } else { - return false; - } - } else { - pos = next; + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + var pos = Math.min(stream.pos, curStart + 5e3); + f(pos, curStyle); + curStart = pos; + } + } + function findStartLine(cm, n, precise) { + var minindent, + minline, + doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1e3 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) { + return doc.first; + } + var line = getLine(doc, search - 1), + after = line.stateAfter; + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { + return search; + } + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n); + if (doc.highlightFrontier < n - 10) { + return; + } + var start = doc.first; + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc, line).stateAfter; + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1; + break; + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start); + } + var sawReadOnlySpans = false, + sawCollapsedSpans = false; + function seeReadOnlySpans() { + sawReadOnlySpans = true; + } + function seeCollapsedSpans() { + sawCollapsedSpans = true; + } + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; + this.to = to; + } + function getMarkedSpanFor(spans, marker) { + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.marker == marker) { + return span; } - return true; } - if (unit == "char" || unit == "codepoint") { - moveOnce(); - } else if (unit == "column") { - moveOnce(true); - } else if (unit == "word" || unit == "group") { - var sawType = null, - group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) { - break; - } - var cur = lineObj.text.charAt(pos.ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; - if (group && !first && !type) { - type = "s"; + } + } + function removeMarkedSpan(spans, span) { + var r; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2] != span) { + (r || (r = [])).push(spans[i2]); + } + } + return r; + } + function addMarkedSpan(line, span, op) { + var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = /* @__PURE__ */new WeakSet())); + if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) { + line.markedSpans.push(span); + } else { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + if (inThisOp) { + inThisOp.add(line.markedSpans); + } + } + span.marker.attachLine(line); + } + function markedSpansBefore(old, startCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], + marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + var nw; + if (old) { + for (var i2 = 0; i2 < old.length; ++i2) { + var span = old[i2], + marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); + } + } + } + return nw; + } + function stretchSpansOverChange(doc, change) { + if (change.full) { + return null; + } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) { + return null; + } + var startCh = change.from.ch, + endCh = change.to.ch, + isInsert = cmp(change.from, change.to) == 0; + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + var sameLine = change.text.length == 1, + offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + for (var i2 = 0; i2 < first.length; ++i2) { + var span = first[i2]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) { + span.to = startCh; + } else if (sameLine) { + span.to = found.to == null ? null : found.to + offset; } - if (sawType && sawType != type) { - if (dir < 0) { - dir = 1; - moveOnce(); - pos.sticky = "after"; + } + } + } + if (last) { + for (var i$12 = 0; i$12 < last.length; ++i$12) { + var span$1 = last[i$12]; + if (span$1.to != null) { + span$1.to += offset; + } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker); + if (!found$1) { + span$1.from = offset; + if (sameLine) { + (first || (first = [])).push(span$1); } - break; } - if (type) { - sawType = type; + } else { + span$1.from += offset; + if (sameLine) { + (first || (first = [])).push(span$1); } - if (dir > 0 && !moveOnce(!first)) { - break; + } + } + } + if (first) { + first = clearEmptySpans(first); + } + if (last && last != first) { + last = clearEmptySpans(last); + } + var newMarkers = [first]; + if (!sameLine) { + var gap = change.text.length - 2, + gapMarkers; + if (gap > 0 && first) { + for (var i$22 = 0; i$22 < first.length; ++i$22) { + if (first[i$22].to == null) { + (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$22].marker, null, null)); } } } - var result = skipAtomic(doc, pos, oldPos, origDir, true); - if (equalCursorPos(oldPos, result)) { - result.hitSide = true; + for (var i$3 = 0; i$3 < gap; ++i$3) { + newMarkers.push(gapMarkers); } - return result; + newMarkers.push(last); } - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, - x = pos.left, - y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - var target; - for (;;) { - target = coordsChar(cm, x, y); - if (!target.outside) { - break; + return newMarkers; + } + function clearEmptySpans(spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { + spans.splice(i2--, 1); + } + } + if (!spans.length) { + return null; + } + return spans; + } + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { + for (var i3 = 0; i3 < line.markedSpans.length; ++i3) { + var mark = line.markedSpans[i3].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { + (markers || (markers = [])).push(mark); + } } - if (dir < 0 ? y <= 0 : y >= doc.height) { - target.hitSide = true; - break; + } + }); + if (!markers) { + return null; + } + var parts = [{ + from, + to + }]; + for (var i2 = 0; i2 < markers.length; ++i2) { + var mk = markers[i2], + m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { + continue; + } + var newParts = [j, 1], + dfrom = cmp(p.from, m.from), + dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { + newParts.push({ + from: p.from, + to: m.from + }); } - y += dir * 5; + if (dto > 0 || !mk.inclusiveRight && !dto) { + newParts.push({ + from: m.to, + to: p.to + }); + } + parts.splice.apply(parts, newParts); + j += newParts.length - 3; } - return target; } - var ContentEditableInput = function (cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.composing = null; - this.gracePeriod = false; - this.readDOMTimeout = null; - }; - ContentEditableInput.prototype.init = function (display) { - var this$1$1 = this; - var input = this, - cm = input.cm; - var div = input.div = display.lineDiv; - div.contentEditable = true; - disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); - function belongsToInput(e) { - for (var t = e.target; t; t = t.parentNode) { - if (t == div) { - return true; - } - if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { - break; - } + return parts; + } + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.detachLine(line); + } + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) { + return; + } + for (var i2 = 0; i2 < spans.length; ++i2) { + spans[i2].marker.attachLine(line); + } + line.markedSpans = spans; + } + function extraLeft(marker) { + return marker.inclusiveLeft ? -1 : 0; + } + function extraRight(marker) { + return marker.inclusiveRight ? 1 : 0; + } + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) { + return lenDiff; + } + var aPos = a.find(), + bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) { + return -fromCmp; + } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) { + return toCmp; + } + return b.id - a.id; + } + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, + found; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { + found = sp.marker; } - return false; } - on(div, "paste", function (e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; + } + return found; + } + function collapsedSpanAtStart(line) { + return collapsedSpanAtSide(line, true); + } + function collapsedSpanAtEnd(line) { + return collapsedSpanAtSide(line, false); + } + function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, + found; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { + found = sp.marker; } - if (ie_version <= 11) { - setTimeout(operation(cm, function () { - return this$1$1.updateFromDOM(); - }), 20); + } + } + return found; + } + function conflictingCollapsedRange(doc, lineNo2, from, to, marker) { + var line = getLine(doc, lineNo2); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + var sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; } - }); - on(div, "compositionstart", function (e) { - this$1$1.composing = { - data: e.data, - done: false - }; - }); - on(div, "compositionupdate", function (e) { - if (!this$1$1.composing) { - this$1$1.composing = { - data: e.data, - done: false - }; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { + continue; } - }); - on(div, "compositionend", function (e) { - if (this$1$1.composing) { - if (e.data != this$1$1.composing.data) { - this$1$1.readFromDOMSoon(); - } - this$1$1.composing.done = true; + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { + return true; } - }); - on(div, "touchstart", function () { - return input.forceCompositionEnd(); - }); - on(div, "input", function () { - if (!this$1$1.composing) { - this$1$1.readFromDOMSoon(); + } + } + } + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) { + line = merged.find(-1, true).line; + } + return line; + } + function visualLineEnd(line) { + var merged; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + } + return line; + } + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), + vis = visualLine(line); + if (line == vis) { + return lineN; + } + return lineNo(vis); + } + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { + return lineN; + } + var line = getLine(doc, lineN), + merged; + if (!lineIsHidden(doc, line)) { + return lineN; + } + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + } + return lineNo(line) + 1; + } + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp = void 0, i2 = 0; i2 < sps.length; ++i2) { + sp = sps[i2]; + if (!sp.marker.collapsed) { + continue; } - }); - function onCopyCut(e) { - if (!belongsToInput(e) || signalDOMEvent(cm, e)) { - return; + if (sp.from == null) { + return true; } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections() - }); - if (e.type == "cut") { - cm.replaceSelection("", null, "cut"); - } - } else if (!cm.options.lineWiseCopyCut) { - return; + if (sp.marker.widgetNode) { + continue; + } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { + return true; + } + } + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) { + return true; + } + for (var sp = void 0, i2 = 0; i2 < line.markedSpans.length; ++i2) { + sp = line.markedSpans[i2]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { + return true; + } + } + } + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + var h = 0, + chunk = lineObj.parent; + for (var i2 = 0; i2 < chunk.lines.length; ++i2) { + var line = chunk.lines[i2]; + if (line == lineObj) { + break; + } else { + h += line.height; + } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$12 = 0; i$12 < p.children.length; ++i$12) { + var cur = p.children[i$12]; + if (cur == chunk) { + break; } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text - }); - if (e.type == "cut") { - cm.operation(function () { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); + h += cur.height; + } + } + } + return h; + } + function lineLength(line) { + if (line.height == 0) { + return 0; + } + var len = line.text.length, + merged, + cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true); + len -= cur.text.length - found$1.from.ch; + cur = found$1.to.line; + len += cur.text.length - found$1.to.ch; + } + return len; + } + function findMaxLine(cm) { + var d = cm.display, + doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + var Line = function (text, markedSpans, estimateHeight2) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight2 ? estimateHeight2(this) : 1; + }; + Line.prototype.lineNo = function () { + return lineNo(this); + }; + eventMixin(Line); + function updateLine(line, text, markedSpans, estimateHeight2) { + line.text = text; + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + if (line.order != null) { + line.order = null; + } + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight2 ? estimateHeight2(line) : 1; + if (estHeight != line.height) { + updateLineHeight(line, estHeight); + } + } + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + var styleToClassCache = {}, + styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { + return null; + } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + function buildLineContent(cm, lineView) { + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = { + pre: eltP("pre", [content], "CodeMirror-line"), + content, + col: 0, + pos: 0, + cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping") + }; + lineView.measure = {}; + for (var i2 = 0; i2 <= (lineView.rest ? lineView.rest.length : 0); i2++) { + var line = i2 ? lineView.rest[i2 - 1] : lineView.line, + order = void 0; + builder.pos = 0; + builder.addToken = buildToken; + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { + builder.addToken = buildTokenBadBidi(builder.addToken, order); + } + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) { + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); + } + if (line.styleClasses.textClass) { + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); + } + } + if (builder.map.length == 0) { + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); + } + if (i2 == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + if (webkit) { + var last = builder.content.lastChild; + if (/\bcm-tab\b/.test(last.className) || last.querySelector && last.querySelector(".cm-tab")) { + builder.content.className = "cm-tab-wrap-hack"; + } + } + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) { + builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); + } + return builder; + } + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "•", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { + if (!text) { + return; + } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; + var special = builder.cm.state.specialChars, + mustWrap = false; + var content; + if (!special.test(text)) { + builder.col += text.length; + content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) { + mustWrap = true; + } + builder.pos += text.length; + } else { + content = document.createDocumentFragment(); + var pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt])); + } else { + content.appendChild(txt); } + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; } - if (e.clipboardData) { - e.clipboardData.clearData(); - var content = lastCopied.text.join("\n"); - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return; + if (!m) { + break; + } + pos += skipped + 1; + var txt$1 = void 0; + if (m[0] == " ") { + var tabSize = builder.cm.options.tabSize, + tabWidth = tabSize - builder.col % tabSize; + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt$1.setAttribute("role", "presentation"); + txt$1.setAttribute("cm-text", " "); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "␍" : "␤", "cm-invalidchar")); + txt$1.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); + txt$1.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) { + content.appendChild(elt("span", [txt$1])); + } else { + content.appendChild(txt$1); } + builder.col += 1; } - var kludge = hiddenTextarea(), - te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.text.join("\n"); - var hadFocus = activeElt(); - selectInput(te); - setTimeout(function () { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) { - input.showPrimarySelection(); - } - }, 50); + builder.map.push(builder.pos, builder.pos + 1, txt$1); + builder.pos++; } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }; - ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { - if (label) { - this.div.setAttribute("aria-label", label); - } else { - this.div.removeAttribute("aria-label"); + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; + if (style || startStyle || endStyle || mustWrap || css || attributes) { + var fullStyle = style || ""; + if (startStyle) { + fullStyle += startStyle; } - }; - ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = activeElt() == this.div; - return result; - }; - ContentEditableInput.prototype.showSelection = function (info, takeFocus) { - if (!info || !this.cm.display.view.length) { - return; + if (endStyle) { + fullStyle += endStyle; } - if (info.focus || takeFocus) { - this.showPrimarySelection(); + var token = elt("span", [content], fullStyle, css); + if (attributes) { + for (var attr in attributes) { + if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { + token.setAttribute(attr, attributes[attr]); + } + } } - this.showMultipleSelections(info); - }; - ContentEditableInput.prototype.getSelection = function () { - return this.cm.display.wrapper.ownerDocument.getSelection(); - }; - ContentEditableInput.prototype.showPrimarySelection = function () { - var sel = this.getSelection(), - cm = this.cm, - prim = cm.doc.sel.primary(); - var from = prim.from(), - to = prim.to(); - if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { - sel.removeAllRanges(); - return; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { + return text; + } + var spaceBefore = trailingBefore, + result = ""; + for (var i2 = 0; i2 < text.length; i2++) { + var ch = text.charAt(i2); + if (ch == " " && spaceBefore && (i2 == text.length - 1 || text.charCodeAt(i2 + 1) == 32)) { + ch = " "; } - var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { - return; + result += ch; + spaceBefore = ch == " "; + } + return result; + } + function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, css, attributes) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, + end = start + text.length; + for (;;) { + var part = void 0; + for (var i2 = 0; i2 < order.length; i2++) { + part = order[i2]; + if (part.to > start && part.from <= start) { + break; + } + } + if (part.to >= end) { + return inner(builder, text, style, startStyle, endStyle, css, attributes); + } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; } - var view = cm.display.view; - var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { - node: view[0].measure.map[2], - offset: 0 - }; - var end = to.line < cm.display.viewTo && posToDOM(cm, to); - if (!end) { - var measure = view[view.length - 1].measure; - var map2 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = { - node: map2[map2.length - 1], - offset: map2[map2.length - 2] - map2[map2.length - 3] - }; + }; + } + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) { + builder.map.push(builder.pos, builder.pos + size, widget); + } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) { + widget = builder.content.appendChild(document.createElement("span")); } - if (!start || !end) { - sel.removeAllRanges(); - return; + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + builder.trailingSpace = false; + } + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, + allText = line.text, + at = 0; + if (!spans) { + for (var i$12 = 1; i$12 < styles.length; i$12 += 2) { + builder.addToken(builder, allText.slice(at, at = styles[i$12]), interpretTokenStyle(styles[i$12 + 1], builder.cm.options)); } - var old = sel.rangeCount && sel.getRangeAt(0), - rng; - try { - rng = range(start.node, start.offset, end.offset, end.node); - } catch (e) {} - if (rng) { - if (!gecko && cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) { - sel.removeAllRanges(); - sel.addRange(rng); + return; + } + var len = allText.length, + pos = 0, + i2 = 1, + text = "", + style, + css; + var nextChange = 0, + spanStyle, + spanEndStyle, + spanStartStyle, + collapsed, + attributes; + for (;;) { + if (nextChange == pos) { + spanStyle = spanEndStyle = spanStartStyle = css = ""; + attributes = null; + collapsed = null; + nextChange = Infinity; + var foundBookmarks = [], + endStyles = void 0; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], + m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) { + spanStyle += " " + m.className; + } + if (m.css) { + css = (css ? css + ";" : "") + m.css; + } + if (m.startStyle && sp.from == pos) { + spanStartStyle += " " + m.startStyle; + } + if (m.endStyle && sp.to == nextChange) { + (endStyles || (endStyles = [])).push(m.endStyle, sp.to); + } + if (m.title) { + (attributes || (attributes = {})).title = m.title; + } + if (m.attributes) { + for (var attr in m.attributes) { + (attributes || (attributes = {}))[attr] = m.attributes[attr]; + } + } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { + collapsed = sp; + } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; } - } else { - sel.removeAllRanges(); - sel.addRange(rng); } - if (old && sel.anchorNode == null) { - sel.addRange(old); - } else if (gecko) { - this.startGracePeriod(); + if (endStyles) { + for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { + if (endStyles[j$1 + 1] == nextChange) { + spanEndStyle += " " + endStyles[j$1]; + } + } } - } - this.rememberSelection(); - }; - ContentEditableInput.prototype.startGracePeriod = function () { - var this$1$1 = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function () { - this$1$1.gracePeriod = false; - if (this$1$1.selectionChanged()) { - this$1$1.cm.operation(function () { - return this$1$1.cm.curOp.selectionChanged = true; - }); + if (!collapsed || collapsed.from == pos) { + for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { + buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); + } } - }, 20); - }; - ContentEditableInput.prototype.showMultipleSelections = function (info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }; - ContentEditableInput.prototype.rememberSelection = function () { - var sel = this.getSelection(); - this.lastAnchorNode = sel.anchorNode; - this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; - this.lastFocusOffset = sel.focusOffset; - }; - ContentEditableInput.prototype.selectionInEditor = function () { - var sel = this.getSelection(); - if (!sel.rangeCount) { - return false; - } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }; - ContentEditableInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor") { - if (!this.selectionInEditor() || activeElt() != this.div) { - this.showSelection(this.prepareSelection(), true); + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); + if (collapsed.to == null) { + return; + } + if (collapsed.to == pos) { + collapsed = false; + } } - this.div.focus(); } - }; - ContentEditableInput.prototype.blur = function () { - this.div.blur(); - }; - ContentEditableInput.prototype.getField = function () { - return this.div; - }; - ContentEditableInput.prototype.supportsTouch = function () { - return true; - }; - ContentEditableInput.prototype.receivedFocus = function () { - var this$1$1 = this; - var input = this; - if (this.selectionInEditor()) { - setTimeout(function () { - return this$1$1.pollSelection(); - }, 20); - } else { - runInOp(this.cm, function () { - return input.cm.curOp.selectionChanged = true; - }); + if (pos >= len) { + break; } - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); + } + if (end >= upto) { + text = text.slice(upto - pos); + pos = upto; + break; + } + pos = end; + spanStartStyle = ""; } + text = allText.slice(at, at = styles[i2++]); + style = interpretTokenStyle(styles[i2++], builder.cm.options); } - this.polling.set(this.cm.options.pollInterval, poll); - }; - ContentEditableInput.prototype.selectionChanged = function () { - var sel = this.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }; - ContentEditableInput.prototype.pollSelection = function () { - if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { - return; - } - var sel = this.getSelection(), - cm = this.cm; - if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { - this.cm.triggerOnKeyDown({ - type: "keydown", - keyCode: 8, - preventDefault: Math.abs - }); - this.blur(); - this.focus(); - return; - } - if (this.composing) { - return; - } - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) { - runInOp(cm, function () { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) { - cm.curOp.selectionChanged = true; + } + } + function LineView(doc, line, lineN) { + this.line = line; + this.rest = visualLineContinued(line); + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + function buildViewArray(cm, from, to) { + var array = [], + nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + var operationGroup = null; + function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op); + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + }; + } + } + function fireCallbacksForOps(group) { + var callbacks = group.delayedCallbacks, + i2 = 0; + do { + for (; i2 < callbacks.length; i2++) { + callbacks[i2].call(null); + } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } - }); + } } + } while (i2 < callbacks.length); + } + function finishOperation(op, endCb) { + var group = op.ownsGroup; + if (!group) { + return; + } + try { + fireCallbacksForOps(group); + } finally { + operationGroup = null; + endCb(group); + } + } + var orphanDelayedCallbacks = null; + function signalLater(emitter, type) { + var arr = getHandlers(emitter, type); + if (!arr.length) { + return; + } + var args = Array.prototype.slice.call(arguments, 2), + list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + var loop = function (i3) { + list.push(function () { + return arr[i3].apply(null, args); + }); }; - ContentEditableInput.prototype.pollContent = function () { - if (this.readDOMTimeout != null) { - clearTimeout(this.readDOMTimeout); - this.readDOMTimeout = null; - } - var cm = this.cm, - display = cm.display, - sel = cm.doc.sel.primary(); - var from = sel.from(), - to = sel.to(); - if (from.ch == 0 && from.line > cm.firstLine()) { - from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); - } - if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { - to = Pos(to.line + 1, 0); - } - if (from.line < display.viewFrom || to.line > display.viewTo - 1) { - return false; - } - var fromIndex, fromLine, fromNode; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - fromLine = lineNo(display.view[0].line); - fromNode = display.view[0].node; - } else { - fromLine = lineNo(display.view[fromIndex].line); - fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - var toLine, toNode; - if (toIndex == display.view.length - 1) { - toLine = display.viewTo - 1; - toNode = display.lineDiv.lastChild; - } else { - toLine = lineNo(display.view[toIndex + 1].line) - 1; - toNode = display.view[toIndex + 1].node.previousSibling; - } - if (!fromNode) { - return false; + for (var i2 = 0; i2 < arr.length; ++i2) loop(i2); + } + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i2 = 0; i2 < delayed.length; ++i2) { + delayed[i2](); + } + } + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") { + updateLineText(cm, lineView); + } else if (type == "gutter") { + updateLineGutter(cm, lineView, lineN, dims); + } else if (type == "class") { + updateLineClasses(cm, lineView); + } else if (type == "widget") { + updateLineWidgets(cm, lineView, dims); } - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { - newText.pop(); - oldText.pop(); - toLine--; - } else if (newText[0] == oldText[0]) { - newText.shift(); - oldText.shift(); - fromLine++; - } else { - break; - } + } + lineView.changes = null; + } + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) { + lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } - var cutFront = 0, - cutEnd = 0; - var newTop = newText[0], - oldTop = oldText[0], - maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { - ++cutFront; - } - var newBot = lst(newText), - oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - ++cutEnd; - } - if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { - while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - cutFront--; - cutEnd++; - } + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) { + lineView.node.style.zIndex = 2; } - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; + } + return lineView.node; + } + function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) { + cls += " CodeMirror-linebackground"; + } + if (lineView.background) { + if (cls) { + lineView.background.className = cls; + } else { + lineView.background.parentNode.removeChild(lineView.background); + lineView.background = null; } - }; - ContentEditableInput.prototype.ensurePolled = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.reset = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.forceCompositionEnd = function () { - if (!this.composing) { - return; + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + cm.display.input.setUneditable(lineView.background); + } + } + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) { + lineView.node = built.pre; + } + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(cm, lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView); + if (lineView.line.wrapClass) { + ensureLineWrapped(lineView).className = lineView.line.wrapClass; + } else if (lineView.node != lineView.text) { + lineView.node.className = ""; + } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + dims.gutterTotalWidth + "px"); + cm.display.input.setUneditable(lineView.gutterBackground); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); + gutterWrap.setAttribute("aria-hidden", "true"); + cm.display.input.setUneditable(gutterWrap); + wrap$1.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) { + gutterWrap.className += " " + lineView.line.gutterClass; } - clearTimeout(this.readDOMTimeout); - this.composing = null; - this.updateFromDOM(); - this.div.blur(); - this.div.focus(); - }; - ContentEditableInput.prototype.readFromDOMSoon = function () { - var this$1$1 = this; - if (this.readDOMTimeout != null) { - return; + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { + lineView.lineNumber = gutterWrap.appendChild(elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + cm.display.lineNumInnerWidth + "px")); } - this.readDOMTimeout = setTimeout(function () { - this$1$1.readDOMTimeout = null; - if (this$1$1.composing) { - if (this$1$1.composing.done) { - this$1$1.composing = null; - } else { - return; + if (markers) { + for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { + var id = cm.display.gutterSpecs[k].className, + found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); } } - this$1$1.updateFromDOM(); - }, 80); - }; - ContentEditableInput.prototype.updateFromDOM = function () { - var this$1$1 = this; - if (this.cm.isReadOnly() || !this.pollContent()) { - runInOp(this.cm, function () { - return regChange(this$1$1.cm); - }); } - }; - ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; - }; - ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { - return; + } + } + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { + lineView.alignable = null; + } + var isWidget = classTest("CodeMirror-linewidget"); + for (var node = lineView.node.firstChild, next = void 0; node; node = next) { + next = node.nextSibling; + if (isWidget.test(node.className)) { + lineView.node.removeChild(node); } - e.preventDefault(); - if (!this.cm.isReadOnly()) { - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + } + insertLineWidgets(cm, lineView, dims); + } + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) { + lineView.bgClass = built.bgClass; + } + if (built.textClass) { + lineView.textClass = built.textClass; + } + updateLineClasses(cm, lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + insertLineWidgetsFor(cm, lineView.rest[i2], lineView, dims, false); } - }; - ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); - }; - ContentEditableInput.prototype.onContextMenu = function () {}; - ContentEditableInput.prototype.resetPosition = function () {}; - ContentEditableInput.prototype.needsContentAttribute = true; - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) { - return null; + } + } + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { + return; + } + var wrap = ensureLineWrapped(lineView); + for (var i2 = 0, ws = line.widgets; i2 < ws.length; ++i2) { + var widget = ws[i2], + node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); + if (!widget.handleMouseEvents) { + node.setAttribute("cm-ignore-events", "true"); + } + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) { + wrap.insertBefore(node, lineView.gutter || lineView.text); + } else { + wrap.appendChild(node); } - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - var order = getOrder(line, cm.doc.direction), - side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; + signalLater(widget, "redraw"); + } + } + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; + node.style.width = width + "px"; } - function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) { - if (/CodeMirror-gutter-wrapper/.test(scan.className)) { - return true; - } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) { + node.style.marginLeft = -dims.gutterTotalWidth + "px"; } - return false; } - function badPos(pos, bad) { - if (bad) { - pos.bad = true; + } + function widgetHeight(widget) { + if (widget.height != null) { + return widget.height; + } + var cm = widget.doc.cm; + if (!cm) { + return 0; + } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) { + parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } - return pos; + if (widget.noHScroll) { + parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); } - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", - closing = false, - lineSep = cm.doc.lineSeparator(), - extraLinebreak = false; - function recognizeMarker(id) { - return function (marker) { - return marker.id == id; - }; + return widget.height = widget.node.parentNode.offsetHeight; + } + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true" || n.parentNode == display.sizer && n != display.mover) { + return true; } - function close() { - if (closing) { - text += lineSep; - if (extraLinebreak) { - text += lineSep; + } + } + function paddingTop(display) { + return display.lineSpace.offsetTop; + } + function paddingVert(display) { + return display.mover.offsetHeight - display.lineSpace.offsetHeight; + } + function paddingH(display) { + if (display.cachedPaddingH) { + return display.cachedPaddingH; + } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = { + left: parseInt(style.paddingLeft), + right: parseInt(style.paddingRight) + }; + if (!isNaN(data.left) && !isNaN(data.right)) { + display.cachedPaddingH = data; + } + return data; + } + function scrollGap(cm) { + return scrollerGap - cm.display.nativeBarWidth; + } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i2 = 0; i2 < rects.length - 1; i2++) { + var cur = rects[i2], + next = rects[i2 + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) { + heights.push((cur.bottom + next.top) / 2 - rect.top); } - closing = extraLinebreak = false; - } - } - function addText(str) { - if (str) { - close(); - text += str; } } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText) { - addText(cmText); - return; - } - var markerID = node.getAttribute("cm-marker"), - range2; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range2 = found[0].find(0))) { - addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep)); - } - return; - } - if (node.getAttribute("contenteditable") == "false") { - return; - } - var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); - if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { - return; - } - if (isBlock) { - close(); - } - for (var i2 = 0; i2 < node.childNodes.length; i2++) { - walk(node.childNodes[i2]); - } - if (/^(pre|p)$/i.test(node.nodeName)) { - extraLinebreak = true; - } - if (isBlock) { - closing = true; - } - } else if (node.nodeType == 3) { - addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); + heights.push(rect.bottom - rect.top); + } + } + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) { + return { + map: lineView.measure.map, + cache: lineView.measure.cache + }; + } + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + if (lineView.rest[i2] == line) { + return { + map: lineView.measure.maps[i2], + cache: lineView.measure.caches[i2] + }; } } - for (;;) { - walk(from); - if (from == to) { - break; + for (var i$12 = 0; i$12 < lineView.rest.length; i$12++) { + if (lineNo(lineView.rest[i$12]) > lineN) { + return { + map: lineView.measure.maps[i$12], + cache: lineView.measure.caches[i$12], + before: true + }; } - from = from.nextSibling; - extraLinebreak = false; } - return text; } - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) { - return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - } - node = null; - offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) { - return null; - } - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { - break; - } - } + } + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { + return cm.display.view[findViewIndex(cm, lineN)]; + } + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { + return ext; + } + } + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) { + view = updateExternalMeasurement(cm, line); + } + var info = mapFromLineView(view, line, lineN); + return { + line, + view, + rect: null, + map: info.map, + cache: info.cache, + before: info.before, + hasHeights: false + }; + } + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { + ch = -1; + } + var key = ch + (bias || ""), + found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) { + prepared.rect = prepared.view.text.getBoundingClientRect(); } - for (var i2 = 0; i2 < cm.display.view.length; i2++) { - var lineView = cm.display.view[i2]; - if (lineView.node == lineNode) { - return locateNodeInLineView(lineView, node, offset); - } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; } - } - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, - bad = false; - if (!node || !contains(wrapper, node)) { - return badPos(Pos(lineNo(lineView.line), 0), true); + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) { + prepared.cache[key] = found; } - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); + } + return { + left: found.left, + right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom + }; + } + var nullRect = { + left: 0, + right: 0, + top: 0, + bottom: 0 + }; + function nodeAndOffsetInLineMap(map2, ch, bias) { + var node, start, end, collapse, mStart, mEnd; + for (var i2 = 0; i2 < map2.length; i2 += 3) { + mStart = map2[i2]; + mEnd = map2[i2 + 1]; + if (ch < mStart) { + start = 0; + end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i2 == map2.length - 3 || ch == mEnd && map2[i2 + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) { + collapse = "right"; } } - var textNode = node.nodeType == 3 ? node : null, - topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) { - offset = textNode.nodeValue.length; + if (start != null) { + node = map2[i2 + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { + collapse = bias; } - } - while (topNode.parentNode != wrapper) { - topNode = topNode.parentNode; - } - var measure = lineView.measure, - maps = measure.maps; - function find(textNode2, topNode2, offset2) { - for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { - var map2 = i2 < 0 ? measure.map : maps[i2]; - for (var j = 0; j < map2.length; j += 3) { - var curNode = map2[j + 2]; - if (curNode == textNode2 || curNode == topNode2) { - var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]); - var ch = map2[j] + offset2; - if (offset2 < 0 || curNode != textNode2) { - ch = map2[j + (offset2 ? 1 : 0)]; - } - return Pos(line2, ch); - } + if (bias == "left" && start == 0) { + while (i2 && map2[i2 - 2] == map2[i2 - 3] && map2[i2 - 1].insertLeft) { + node = map2[(i2 -= 3) + 2]; + collapse = "left"; } } + if (bias == "right" && start == mEnd - mStart) { + while (i2 < map2.length - 3 && map2[i2 + 3] == map2[i2 + 4] && !map2[i2 + 5].insertLeft) { + node = map2[(i2 += 3) + 2]; + collapse = "right"; + } + } + break; } - var found = find(textNode, topNode, offset); - if (found) { - return badPos(found, bad); - } - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) { - return badPos(Pos(found.line, found.ch - dist), bad); - } else { - dist += after.textContent.length; + } + return { + node, + start, + end, + collapse, + coverStart: mStart, + coverEnd: mEnd + }; + } + function getUsefulRect(rects, bias) { + var rect = nullRect; + if (bias == "left") { + for (var i2 = 0; i2 < rects.length; i2++) { + if ((rect = rects[i2]).left != rect.right) { + break; } } - for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) { - return badPos(Pos(found.line, found.ch + dist$1), bad); - } else { - dist$1 += before.textContent.length; + } else { + for (var i$12 = rects.length - 1; i$12 >= 0; i$12--) { + if ((rect = rects[i$12]).left != rect.right) { + break; } } } - var TextareaInput = function (cm) { - this.cm = cm; - this.prevInput = ""; - this.pollingFast = false; - this.polling = new Delayed(); - this.hasSelection = false; - this.composing = null; - }; - TextareaInput.prototype.init = function (display) { - var this$1$1 = this; - var input = this, - cm = this.cm; - this.createField(display); - var te = this.textarea; - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); - if (ios) { - te.style.width = "0px"; - } - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1$1.hasSelection) { - this$1$1.hasSelection = null; - } - input.poll(); - }); - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { - return; + return rect; + } + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, + start = place.start, + end = place.end, + collapse = place.collapse; + var rect; + if (node.nodeType == 3) { + for (var i$12 = 0; i$12 < 4; i$12++) { + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { + --start; } - cm.state.pasteIncoming = + /* @__PURE__ */new Date(); - input.fastPoll(); - }); - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) { - return; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { + ++end; } - if (cm.somethingSelected()) { - setLastCopied({ - lineWise: false, - text: cm.getSelections() - }); - } else if (!cm.options.lineWiseCopyCut) { - return; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); } else { - var ranges = copyableRanges(cm); - setLastCopied({ - lineWise: true, - text: ranges.text - }); - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } + rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } - if (e.type == "cut") { - cm.state.cutIncoming = + /* @__PURE__ */new Date(); + if (rect.left || rect.right || start == 0) { + break; } + end = start; + start = start - 1; + collapse = "right"; } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - on(display.scroller, "paste", function (e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { - return; - } - if (!te.dispatchEvent) { - cm.state.pasteIncoming = + /* @__PURE__ */new Date(); - input.focus(); - return; - } - var event = new Event("paste"); - event.clipboardData = e.clipboardData; - te.dispatchEvent(event); - }); - on(display.lineSpace, "selectstart", function (e) { - if (!eventInWidget(display, e)) { - e_preventDefault(e); - } - }); - on(te, "compositionstart", function () { - var start = cm.getCursor("from"); - if (input.composing) { - input.composing.range.clear(); - } - input.composing = { - start, - range: cm.markText(start, cm.getCursor("to"), { - className: "CodeMirror-composing" - }) + if (ie && ie_version < 11) { + rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } + } else { + if (start > 0) { + collapse = bias = "right"; + } + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { + rect = rects[bias == "right" ? rects.length - 1 : 0]; + } else { + rect = node.getBoundingClientRect(); + } + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) { + rect = { + left: rSpan.left, + right: rSpan.left + charWidth(cm.display), + top: rSpan.top, + bottom: rSpan.bottom }; - }); - on(te, "compositionend", function () { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }; - TextareaInput.prototype.createField = function (_display) { - this.wrapper = hiddenTextarea(); - this.textarea = this.wrapper.firstChild; - }; - TextareaInput.prototype.screenReaderLabelChanged = function (label) { - if (label) { - this.textarea.setAttribute("aria-label", label); } else { - this.textarea.removeAttribute("aria-label"); + rect = nullRect; } - }; - TextareaInput.prototype.prepareSelection = function () { - var cm = this.cm, - display = cm.display, - doc = cm.doc; - var result = prepareSelection(cm); - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), - lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); + } + var rtop = rect.top - prepared.rect.top, + rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + var i2 = 0; + for (; i2 < heights.length - 1; i2++) { + if (mid < heights[i2]) { + break; } - return result; + } + var top = i2 ? heights[i2 - 1] : 0, + bot = heights[i2]; + var result = { + left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top, + bottom: bot }; - TextareaInput.prototype.showSelection = function (drawn) { - var cm = this.cm, - display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } + if (!rect.left && !rect.right) { + result.bogus = true; + } + if (!cm.options.singleCursorHeightPerLine) { + result.rtop = rtop; + result.rbottom = rbot; + } + return result; + } + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { + return rect; + } + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return { + left: rect.left * scaleX, + right: rect.right * scaleX, + top: rect.top * scaleY, + bottom: rect.bottom * scaleY }; - TextareaInput.prototype.reset = function (typing) { - if (this.contextMenuPending || this.composing) { - return; - } - var cm = this.cm; - if (cm.somethingSelected()) { - this.prevInput = ""; - var content = cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) { - selectInput(this.textarea); - } - if (ie && ie_version >= 9) { - this.hasSelection = content; - } - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) { - this.hasSelection = null; + } + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i2 = 0; i2 < lineView.rest.length; i2++) { + lineView.measure.caches[i2] = {}; } } - }; - TextareaInput.prototype.getField = function () { - return this.textarea; - }; - TextareaInput.prototype.supportsTouch = function () { - return false; - }; - TextareaInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { - this.textarea.focus(); - } catch (e) {} + } + } + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + clearLineMeasurementCacheFor(cm.display.view[i2]); + } + } + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) { + cm.display.maxLineChanged = true; + } + cm.display.lineNumChars = null; + } + function pageScrollX() { + if (chrome && android) { + return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)); + } + return window.pageXOffset || (document.documentElement || document.body).scrollLeft; + } + function pageScrollY() { + if (chrome && android) { + return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)); + } + return window.pageYOffset || (document.documentElement || document.body).scrollTop; + } + function widgetTopHeight(lineObj) { + var ref = visualLine(lineObj); + var widgets = ref.widgets; + var height = 0; + if (widgets) { + for (var i2 = 0; i2 < widgets.length; ++i2) { + if (widgets[i2].above) { + height += widgetHeight(widgets[i2]); + } } + } + return height; + } + function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj); + rect.top += height; + rect.bottom += height; + } + if (context == "line") { + return rect; + } + if (!context) { + context = "local"; + } + var yOff = heightAtLine(lineObj); + if (context == "local") { + yOff += paddingTop(cm.display); + } else { + yOff -= cm.display.viewOffset; + } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; + rect.right += xOff; + } + rect.top += yOff; + rect.bottom += yOff; + return rect; + } + function fromCoordSystem(cm, coords, context) { + if (context == "div") { + return coords; + } + var left = coords.left, + top = coords.top; + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return { + left: left - lineSpaceBox.left, + top: top - lineSpaceBox.top }; - TextareaInput.prototype.blur = function () { - this.textarea.blur(); - }; - TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; - }; - TextareaInput.prototype.receivedFocus = function () { - this.slowPoll(); + } + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { + lineObj = getLine(cm.doc, pos.line); + } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + function get(ch2, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch2, right ? "right" : "left", varHeight); + if (right) { + m.left = m.right; + } else { + m.right = m.left; + } + return intoCoordSystem(cm, lineObj, m, context); + } + var order = getOrder(lineObj, cm.doc.direction), + ch = pos.ch, + sticky = pos.sticky; + if (ch >= lineObj.text.length) { + ch = lineObj.text.length; + sticky = "before"; + } else if (ch <= 0) { + ch = 0; + sticky = "after"; + } + if (!order) { + return get(sticky == "before" ? ch - 1 : ch, sticky == "before"); + } + function getBidi(ch2, partPos2, invert) { + var part = order[partPos2], + right = part.level == 1; + return get(invert ? ch2 - 1 : ch2, right != invert); + } + var partPos = getBidiPartAt(order, ch, sticky); + var other = bidiOther; + var val = getBidi(ch, partPos, sticky == "before"); + if (other != null) { + val.other = getBidi(ch, other, sticky != "before"); + } + return val; + } + function estimateCoords(cm, pos) { + var left = 0; + pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) { + left = charWidth(cm.display) * pos.ch; + } + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return { + left, + right: left, + top, + bottom: top + lineObj.height }; - TextareaInput.prototype.slowPoll = function () { - var this$1$1 = this; - if (this.pollingFast) { - return; + } + function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky); + pos.xRel = xRel; + if (outside) { + pos.outside = outside; + } + return pos; + } + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) { + return PosWithInfo(doc.first, 0, null, -1, -1); + } + var lineN = lineAtHeight(doc, y), + last = doc.first + doc.size - 1; + if (lineN > last) { + return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1); + } + if (x < 0) { + x = 0; + } + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); + if (!collapsed) { + return found; } - this.polling.set(this.cm.options.pollInterval, function () { - this$1$1.poll(); - if (this$1$1.cm.state.focused) { - this$1$1.slowPoll(); - } - }); - }; - TextareaInput.prototype.fastPoll = function () { - var missed = false, - input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) { - missed = true; - input.polling.set(60, p); - } else { - input.pollingFast = false; - input.slowPoll(); - } + var rangeEnd = collapsed.find(1); + if (rangeEnd.line == lineN) { + return rangeEnd; } - input.polling.set(20, p); + lineObj = getLine(doc, lineN = rangeEnd.line); + } + } + function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj); + var end = lineObj.text.length; + var begin = findFirst(function (ch) { + return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; + }, end, 0); + end = findFirst(function (ch) { + return measureCharPrepared(cm, preparedMeasure, ch).top > y; + }, begin, end); + return { + begin, + end }; - TextareaInput.prototype.poll = function () { - var this$1$1 = this; - var cm = this.cm, - input = this.textarea, - prevInput = this.prevInput; - if (this.contextMenuPending || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { + } + function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + if (!preparedMeasure) { + preparedMeasure = prepareMeasureForLine(cm, lineObj); + } + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop); + } + function boxIsAfter(box, x, y, left) { + return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x; + } + function coordsCharInner(cm, lineObj, lineNo2, x, y) { + y -= heightAtLine(lineObj); + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + var widgetHeight2 = widgetTopHeight(lineObj); + var begin = 0, + end = lineObj.text.length, + ltr = true; + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)(cm, lineObj, lineNo2, preparedMeasure, order, x, y); + ltr = part.level != 1; + begin = ltr ? part.from : part.to - 1; + end = ltr ? part.to : part.from - 1; + } + var chAround = null, + boxAround = null; + var ch = findFirst(function (ch2) { + var box = measureCharPrepared(cm, preparedMeasure, ch2); + box.top += widgetHeight2; + box.bottom += widgetHeight2; + if (!boxIsAfter(box, x, y, false)) { return false; } - var text = input.value; - if (text == prevInput && !cm.somethingSelected()) { - return false; + if (box.top <= y && box.left <= x) { + chAround = ch2; + boxAround = box; } - if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; + return true; + }, begin, end); + var baseX, + sticky, + outside = false; + if (boxAround) { + var atLeft = x - boxAround.left < boxAround.right - x, + atStart = atLeft == ltr; + ch = chAround + (atStart ? 0 : 1); + sticky = atStart ? "after" : "before"; + baseX = atLeft ? boxAround.left : boxAround.right; + } else { + if (!ltr && (ch == end || ch == begin)) { + ch++; + } + sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight2 <= y == ltr ? "after" : "before"; + var coords = cursorCoords(cm, Pos(lineNo2, ch, sticky), "line", lineObj, preparedMeasure); + baseX = coords.left; + outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + } + ch = skipExtendingChars(lineObj.text, ch, 1); + return PosWithInfo(lineNo2, ch, sticky, outside, x - baseX); + } + function coordsBidiPart(cm, lineObj, lineNo2, preparedMeasure, order, x, y) { + var index = findFirst(function (i2) { + var part2 = order[i2], + ltr2 = part2.level != 1; + return boxIsAfter(cursorCoords(cm, Pos(lineNo2, ltr2 ? part2.to : part2.from, ltr2 ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true); + }, 0, order.length - 1); + var part = order[index]; + if (index > 0) { + var ltr = part.level != 1; + var start = cursorCoords(cm, Pos(lineNo2, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); + if (boxIsAfter(start, x, y, true) && start.top > y) { + part = order[index - 1]; + } + } + return part; + } + function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { + end--; + } + var part = null, + closestDist = null; + for (var i2 = 0; i2 < order.length; i2++) { + var p = order[i2]; + if (p.from >= end || p.to <= begin) { + continue; } - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 8203 && !prevInput) { - prevInput = "​"; - } - if (first == 8666) { - this.reset(); - return this.cm.execCommand("undo"); - } + var ltr = p.level != 1; + var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; + var dist = endX < x ? x - endX + 1e9 : endX - x; + if (!part || closestDist > dist) { + part = p; + closestDist = dist; } - var same = 0, - l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { - ++same; + } + if (!part) { + part = order[order.length - 1]; + } + if (part.from < begin) { + part = { + from: begin, + to: part.to, + level: part.level + }; + } + if (part.to > end) { + part = { + from: part.from, + to: end, + level: part.level + }; + } + return part; + } + var measureText; + function textHeight(display) { + if (display.cachedTextHeight != null) { + return display.cachedTextHeight; + } + if (measureText == null) { + measureText = elt("pre", null, "CodeMirror-line-like"); + for (var i2 = 0; i2 < 49; ++i2) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) { + display.cachedTextHeight = height; + } + removeChildren(display.measure); + return height || 1; + } + function charWidth(display) { + if (display.cachedCharWidth != null) { + return display.cachedCharWidth; + } + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor], "CodeMirror-line-like"); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), + width = (rect.right - rect.left) / 10; + if (width > 2) { + display.cachedCharWidth = width; + } + return width || 10; + } + function getDimensions(cm) { + var d = cm.display, + left = {}, + width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i2 = 0; n; n = n.nextSibling, ++i2) { + var id = cm.display.gutterSpecs[i2].className; + left[id] = n.offsetLeft + n.clientLeft + gutterLeft; + width[id] = n.clientWidth; + } + return { + fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth + }; + } + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + function estimateHeight(cm) { + var th = textHeight(cm.display), + wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) { + return 0; } - runInOp(cm, function () { - applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1$1.composing ? "*compose" : null); - if (text.length > 1e3 || text.indexOf("\n") > -1) { - input.value = this$1$1.prevInput = ""; - } else { - this$1$1.prevInput = text; - } - if (this$1$1.composing) { - this$1$1.composing.range.clear(); - this$1$1.composing.range = cm.markText(this$1$1.composing.start, cm.getCursor("to"), { - className: "CodeMirror-composing" - }); + var widgetsHeight = 0; + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].height) { + widgetsHeight += line.widgets[i2].height; + } } - }); - return true; - }; - TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { - this.pollingFast = false; } - }; - TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { - this.hasSelection = null; + if (wrapping) { + return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + } else { + return widgetsHeight + th; } - this.fastPoll(); }; - TextareaInput.prototype.onContextMenu = function (e) { - var input = this, - cm = input.cm, - display = cm.display, - te = input.textarea; - if (input.contextMenuPending) { - input.contextMenuPending(); - } - var pos = posFromMouse(cm, e), - scrollPos = display.scroller.scrollTop; - if (!pos || presto) { - return; + } + function estimateLineHeights(cm) { + var doc = cm.doc, + est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) { + updateLineHeight(line, estHeight); } - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) { - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + }); + } + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { + return null; + } + var x, + y, + space = display.lineSpace.getBoundingClientRect(); + try { + x = e.clientX - space.left; + y = e.clientY - space.top; + } catch (e$1) { + return null; + } + var coords = coordsChar(cm, x, y), + line; + if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { + return null; + } + n -= cm.display.viewFrom; + if (n < 0) { + return null; + } + var view = cm.display.view; + for (var i2 = 0; i2 < view.length; i2++) { + n -= view[i2].size; + if (n < 0) { + return i2; } - var oldCSS = te.style.cssText, - oldWrapperCSS = input.wrapper.style.cssText; - var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); - input.wrapper.style.cssText = "position: static"; - te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - var oldScrollY; - if (webkit) { - oldScrollY = window.scrollY; + } + } + function regChange(cm, from, to, lendiff) { + if (from == null) { + from = cm.doc.first; + } + if (to == null) { + to = cm.doc.first + cm.doc.size; + } + if (!lendiff) { + lendiff = 0; + } + var display = cm.display; + if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { + display.updateLineNumbers = from; + } + cm.curOp.viewChanged = true; + if (from >= display.viewTo) { + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { + resetView(cm); } - display.input.focus(); - if (webkit) { - window.scrollTo(null, oldScrollY); - } - display.input.reset(); - if (!cm.somethingSelected()) { - te.value = input.prevInput = " "; - } - input.contextMenuPending = rehide; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "​" + (selected ? te.value : ""); - te.value = "⇚"; - te.value = extval; - input.prevInput = selected ? "" : "​"; - te.selectionStart = 1; - te.selectionEnd = extval.length; - display.selForContextMenu = cm.doc.sel; - } + } else if (to <= display.viewFrom) { + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { + resetView(cm); + } else if (from <= display.viewFrom) { + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); } - function rehide() { - if (input.contextMenuPending != rehide) { - return; - } - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) { - display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - } - if (te.selectionStart != null) { - if (!ie || ie && ie_version < 9) { - prepareSelectAllHack(); - } - var i2 = 0, - poll = function () { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "​") { - operation(cm, selectAll)(cm); - } else if (i2++ < 10) { - display.detectingSelectAll = setTimeout(poll, 500); - } else { - display.selForContextMenu = null; - display.input.reset(); - } - }; - display.detectingSelectAll = setTimeout(poll, 200); + } else if (to >= display.viewTo) { + var cut$1 = viewCuttingPoint(cm, from, from, -1); + if (cut$1) { + display.view = display.view.slice(0, cut$1.index); + display.viewTo = cut$1.lineN; + } else { + resetView(cm); + } + } else { + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index).concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)).concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) { + ext.lineN += lendiff; + } else if (from < ext.lineN + ext.size) { + display.externalMeasured = null; + } + } + } + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, + ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { + display.externalMeasured = null; + } + if (line < display.viewFrom || line >= display.viewTo) { + return; + } + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) { + return; + } + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) { + arr.push(type); + } + } + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), + diff, + view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { + return { + index, + lineN: newN + }; + } + var n = cm.display.viewFrom; + for (var i2 = 0; i2 < index; i2++) { + n += view[i2].size; + } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { + return null; } - } - if (ie && ie_version >= 9) { - prepareSelectAllHack(); - } - if (captureRightClick) { - e_stop(e); - var mouseup = function () { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); + diff = n + view[index].size - oldN; + index++; } else { - setTimeout(rehide, 50); + diff = n - oldN; } - }; - TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { - this.reset(); + oldN += diff; + newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { + return null; } - this.textarea.disabled = val == "nocursor"; - this.textarea.readOnly = !!val; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return { + index, + lineN: newN }; - TextareaInput.prototype.setUneditable = function () {}; - TextareaInput.prototype.needsContentAttribute = false; - function fromTextArea(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) { - options.tabindex = textarea.tabIndex; - } - if (!options.placeholder && textarea.placeholder) { - options.placeholder = textarea.placeholder; - } - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - function save() { - textarea.value = cm.getValue(); - } - var realSubmit; - if (textarea.form) { - on(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form; - realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function () { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch (e) {} + } + function adjustView(cm, from, to) { + var display = cm.display, + view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) { + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); + } else if (display.viewFrom < from) { + display.view = display.view.slice(findViewIndex(cm, from)); + } + display.viewFrom = from; + if (display.viewTo < to) { + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); + } else if (display.viewTo > to) { + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + } + display.viewTo = to; + } + function countDirtyView(cm) { + var view = cm.display.view, + dirty = 0; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) { + ++dirty; + } + } + return dirty; + } + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + function prepareSelection(cm, primary) { + if (primary === void 0) primary = true; + var doc = cm.doc, + result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + var customCursor = cm.options.$customCursor; + if (customCursor) { + primary = true; + } + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + if (!primary && i2 == doc.sel.primIndex) { + continue; + } + var range2 = doc.sel.ranges[i2]; + if (range2.from().line >= cm.display.viewTo || range2.to().line < cm.display.viewFrom) { + continue; + } + var collapsed = range2.empty(); + if (customCursor) { + var head = customCursor(cm, range2); + if (head) { + drawSelectionCursor(cm, head, curFragment); } + } else if (collapsed || cm.options.showCursorWhenSelecting) { + drawSelectionCursor(cm, range2.head, curFragment); } - options.finishInit = function (cm2) { - cm2.save = save; - cm2.getTextArea = function () { - return textarea; - }; - cm2.toTextArea = function () { - cm2.toTextArea = isNaN; - save(); - textarea.parentNode.removeChild(cm2.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { - textarea.form.submit = realSubmit; - } - } - }; - }; - textarea.style.display = "none"; - var cm = CodeMirror(function (node) { - return textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - } - function addLegacyProps(CodeMirror2) { - CodeMirror2.off = off; - CodeMirror2.on = on; - CodeMirror2.wheelEventPixels = wheelEventPixels; - CodeMirror2.Doc = Doc; - CodeMirror2.splitLines = splitLinesAuto; - CodeMirror2.countColumn = countColumn; - CodeMirror2.findColumn = findColumn; - CodeMirror2.isWordChar = isWordCharBasic; - CodeMirror2.Pass = Pass; - CodeMirror2.signal = signal; - CodeMirror2.Line = Line; - CodeMirror2.changeEnd = changeEnd; - CodeMirror2.scrollbarModel = scrollbarModel; - CodeMirror2.Pos = Pos; - CodeMirror2.cmpPos = cmp; - CodeMirror2.modes = modes; - CodeMirror2.mimeModes = mimeModes; - CodeMirror2.resolveMode = resolveMode; - CodeMirror2.getMode = getMode; - CodeMirror2.modeExtensions = modeExtensions; - CodeMirror2.extendMode = extendMode; - CodeMirror2.copyState = copyState; - CodeMirror2.startState = startState; - CodeMirror2.innerMode = innerMode; - CodeMirror2.commands = commands; - CodeMirror2.keyMap = keyMap; - CodeMirror2.keyName = keyName; - CodeMirror2.isModifierKey = isModifierKey; - CodeMirror2.lookupKey = lookupKey; - CodeMirror2.normalizeKeyMap = normalizeKeyMap; - CodeMirror2.StringStream = StringStream; - CodeMirror2.SharedTextMarker = SharedTextMarker; - CodeMirror2.TextMarker = TextMarker; - CodeMirror2.LineWidget = LineWidget; - CodeMirror2.e_preventDefault = e_preventDefault; - CodeMirror2.e_stopPropagation = e_stopPropagation; - CodeMirror2.e_stop = e_stop; - CodeMirror2.addClass = addClass; - CodeMirror2.contains = contains; - CodeMirror2.rmClass = rmClass; - CodeMirror2.keyNames = keyNames; - } - defineOptions(CodeMirror); - addEditorMethods(CodeMirror); - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) { - if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { - CodeMirror.prototype[prop] = /* @__PURE__ */function (method) { - return function () { - return method.apply(this.doc, arguments); - }; - }(Doc.prototype[prop]); + if (!collapsed) { + drawSelectionRange(cm, range2, selFragment); } } - eventMixin(Doc); - CodeMirror.inputStyles = { - "textarea": TextareaInput, - "contenteditable": ContentEditableInput - }; - CodeMirror.defineMode = function (name) { - if (!CodeMirror.defaults.mode && name != "null") { - CodeMirror.defaults.mode = name; - } - defineMode.apply(this, arguments); - }; - CodeMirror.defineMIME = defineMIME; - CodeMirror.defineMode("null", function () { - return { - token: function (stream) { - return stream.skipToEnd(); + return result; + } + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + var cursor = output.appendChild(elt("div", " ", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { + var charPos = charCoords(cm, head, "div", null, null); + var width = charPos.right - charPos.left; + cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; + } + if (pos.other) { + var otherCursor = output.appendChild(elt("div", " ", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * 0.85 + "px"; + } + } + function cmpCoords(a, b) { + return a.top - b.top || a.left - b.left; + } + function drawSelectionRange(cm, range2, output) { + var display = cm.display, + doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), + leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + var docLTR = doc.direction == "ltr"; + function add(left, top, width, bottom) { + if (top < 0) { + top = 0; + } + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")); + } + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos); + var prop2 = dir == "ltr" == (side == "after") ? "left" : "right"; + var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); + return coords(ch, prop2)[prop2]; + } + var order = getOrder(lineObj, doc.direction); + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i2) { + var ltr = dir == "ltr"; + var fromPos = coords(from, ltr ? "left" : "right"); + var toPos = coords(to - 1, ltr ? "right" : "left"); + var openStart = fromArg == null && from == 0, + openEnd = toArg == null && to == lineLen; + var first = i2 == 0, + last = !order || i2 == order.length - 1; + if (toPos.top - fromPos.top <= 3) { + var openLeft = (docLTR ? openStart : openEnd) && first; + var openRight = (docLTR ? openEnd : openStart) && last; + var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; + var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; + add(left, fromPos.top, right - left, fromPos.bottom); + } else { + var topLeft, topRight, botLeft, botRight; + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left; + topRight = docLTR ? rightSide : wrapX(from, dir, "before"); + botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); + botRight = docLTR && openEnd && last ? rightSide : toPos.right; + } else { + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); + topRight = !docLTR && openStart && first ? rightSide : fromPos.right; + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; + botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); + } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); + if (fromPos.bottom < toPos.top) { + add(leftSide, fromPos.bottom, null, toPos.top); + } + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); + } + if (!start || cmpCoords(fromPos, start) < 0) { + start = fromPos; + } + if (cmpCoords(toPos, start) < 0) { + start = toPos; + } + if (!end || cmpCoords(fromPos, end) < 0) { + end = fromPos; } + if (cmpCoords(toPos, end) < 0) { + end = toPos; + } + }); + return { + start, + end }; - }); - CodeMirror.defineMIME("text/plain", "null"); - CodeMirror.defineExtension = function (name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.fromTextArea = fromTextArea; - addLegacyProps(CodeMirror); - CodeMirror.version = "5.65.3"; - return CodeMirror; - }); - })(codemirror); - return codemirror.exports; - } - exports.getDefaultExportFromCjs = getDefaultExportFromCjs; - exports.requireCodemirror = requireCodemirror; - - /***/ }), - - /***/ "../../graphiql-react/dist/comment.cjs.js": - /*!************************************************!*\ - !*** ../../graphiql-react/dist/comment.cjs.js ***! - \************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + } + var sFrom = range2.from(), + sTo = range2.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), + toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } + if (leftEnd.bottom < rightStart.top) { + add(leftSide, leftEnd.bottom, null, rightStart.top); + } } + output.appendChild(fragment); } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var comment$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var noOptions = {}; - var nonWS = /[^\s\u00a0]/; - var Pos = CodeMirror.Pos, - cmp = CodeMirror.cmpPos; - function firstNonWS(str) { - var found = str.search(nonWS); - return found == -1 ? 0 : found; - } - CodeMirror.commands.toggleComment = function (cm) { - cm.toggleComment(); - }; - CodeMirror.defineExtension("toggleComment", function (options) { - if (!options) options = noOptions; - var cm = this; - var minLine = Infinity, - ranges = this.listSelections(), - mode = null; - for (var i = ranges.length - 1; i >= 0; i--) { - var from = ranges[i].from(), - to = ranges[i].to(); - if (from.line >= minLine) continue; - if (to.line >= minLine) to = Pos(minLine, 0); - minLine = from.line; - if (mode == null) { - if (cm.uncomment(from, to, options)) mode = "un";else { - cm.lineComment(from, to, options); - mode = "line"; + function restartBlink(cm) { + if (!cm.state.focused) { + return; + } + var display = cm.display; + clearInterval(display.blinker); + var on2 = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function () { + if (!cm.hasFocus()) { + onBlur(cm); } - } else if (mode == "un") { - cm.uncomment(from, to, options); - } else { - cm.lineComment(from, to, options); - } + display.cursorDiv.style.visibility = (on2 = !on2) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) { + display.cursorDiv.style.visibility = "hidden"; } - }); - function probablyInsideString(cm, pos, line) { - return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line); } - function getMode(cm, pos) { - var mode = cm.getMode(); - return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos); + function ensureFocus(cm) { + if (!cm.hasFocus()) { + cm.display.input.focus(); + if (!cm.state.focused) { + onFocus(cm); + } + } } - CodeMirror.defineExtension("lineComment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var firstLine = self.getLine(from.line); - if (firstLine == null || probablyInsideString(self, from, firstLine)) return; - var commentString = options.lineComment || mode.lineComment; - if (!commentString) { - if (options.blockCommentStart || mode.blockCommentStart) { - options.fullLines = true; - self.blockComment(from, to, options); + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + if (cm.state.focused) { + onBlur(cm); + } } + }, 100); + } + function onFocus(cm, e) { + if (cm.state.delayingBlurEvent && !cm.state.draggingText) { + cm.state.delayingBlurEvent = false; + } + if (cm.options.readOnly == "nocursor") { return; } - var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); - var pad = options.padding == null ? " " : options.padding; - var blankLines = options.commentBlankLines || from.line == to.line; - self.operation(function () { - if (options.indent) { - var baseString = null; - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i); - var whitespace = line.slice(0, firstNonWS(line)); - if (baseString == null || baseString.length > whitespace.length) { - baseString = whitespace; - } - } - for (var i = from.line; i < end; ++i) { - var line = self.getLine(i), - cut = baseString.length; - if (!blankLines && !nonWS.test(line)) continue; - if (line.slice(0, cut) != baseString) cut = firstNonWS(line); - self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); - } - } else { - for (var i = from.line; i < end; ++i) { - if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); + if (!cm.state.focused) { + signal(cm, "focus", cm, e); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) { + setTimeout(function () { + return cm.display.input.reset(true); + }, 20); } } - }); - }); - CodeMirror.defineExtension("blockComment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var startString = options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) { - if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return; } - if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return; - var end = Math.min(to.line, self.lastLine()); - if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; - var pad = options.padding == null ? " " : options.padding; - if (from.line > end) return; - self.operation(function () { - if (options.fullLines != false) { - var lastLineHasText = nonWS.test(self.getLine(end)); - self.replaceRange(pad + endString, Pos(end)); - self.replaceRange(startString + pad, Pos(from.line, 0)); - var lead = options.blockCommentLead || mode.blockCommentLead; - if (lead != null) { - for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); - } - } else { - var atCursor = cmp(self.getCursor("to"), to) == 0, - empty = !self.somethingSelected(); - self.replaceRange(endString, to); - if (atCursor) self.setSelection(empty ? to : self.getCursor("from"), to); - self.replaceRange(startString, from); + if (cm.state.focused) { + signal(cm, "blur", cm, e); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () { + if (!cm.state.focused) { + cm.display.shift = false; + } + }, 150); + } + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); + var oldHeight = display.lineDiv.getBoundingClientRect().top; + var mustScroll = 0; + for (var i2 = 0; i2 < display.view.length; i2++) { + var cur = display.view[i2], + wrapping = cm.options.lineWrapping; + var height = void 0, + width = 0; + if (cur.hidden) { + continue; } - }); - }); - CodeMirror.defineExtension("uncomment", function (from, to, options) { - if (!options) options = noOptions; - var self = this, - mode = getMode(self, from); - var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), - start = Math.min(from.line, end); - var lineString = options.lineComment || mode.lineComment, - lines = []; - var pad = options.padding == null ? " " : options.padding, - didSomething; - lineComment: { - if (!lineString) break lineComment; - for (var i = start; i <= end; ++i) { - var line = self.getLine(i); - var found = line.indexOf(lineString); - if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; - if (found == -1 && nonWS.test(line)) break lineComment; - if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; - lines.push(line); - } - self.operation(function () { - for (var i2 = start; i2 <= end; ++i2) { - var line2 = lines[i2 - start]; - var pos = line2.indexOf(lineString), - endPos = pos + lineString.length; - if (pos < 0) continue; - if (line2.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; - didSomething = true; - self.replaceRange("", Pos(i2, pos), Pos(i2, endPos)); + oldHeight += cur.line.height; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + if (!wrapping && cur.text.firstChild) { + width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; + } + } + var diff = cur.line.height - height; + if (diff > 5e-3 || diff < -5e-3) { + if (oldHeight < viewTop) { + mustScroll -= diff; + } + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) { + updateWidgetHeight(cur.rest[j]); + } } - }); - if (didSomething) return true; - } - var startString = options.blockCommentStart || mode.blockCommentStart; - var endString = options.blockCommentEnd || mode.blockCommentEnd; - if (!startString || !endString) return false; - var lead = options.blockCommentLead || mode.blockCommentLead; - var startLine = self.getLine(start), - open = startLine.indexOf(startString); - if (open == -1) return false; - var endLine = end == start ? startLine : self.getLine(end); - var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); - var insideStart = Pos(start, open + 1), - insideEnd = Pos(end, close + 1); - if (close == -1 || !/comment/.test(self.getTokenTypeAt(insideStart)) || !/comment/.test(self.getTokenTypeAt(insideEnd)) || self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1) return false; - var lastStart = startLine.lastIndexOf(startString, from.ch); - var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); - if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; - firstEnd = endLine.indexOf(endString, to.ch); - var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); - lastStart = firstEnd == -1 || almostLastStart == -1 ? -1 : to.ch + almostLastStart; - if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; - self.operation(function () { - self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); - var openEnd = open + startString.length; - if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; - self.replaceRange("", Pos(start, open), Pos(start, openEnd)); - if (lead) for (var i2 = start + 1; i2 <= end; ++i2) { - var line2 = self.getLine(i2), - found2 = line2.indexOf(lead); - if (found2 == -1 || nonWS.test(line2.slice(0, found2))) continue; - var foundEnd = found2 + lead.length; - if (pad && line2.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; - self.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd)); } - }); - return true; - }); - }); - })(); - var commentExports = comment$2.exports; - const comment = /* @__PURE__ */codemirror.getDefaultExportFromCjs(commentExports); - const comment$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: comment - }, [commentExports]); - exports.comment = comment$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/dialog.cjs.js": - /*!***********************************************!*\ - !*** ../../graphiql-react/dist/dialog.cjs.js ***! - \***********************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + if (width > cm.display.sizerWidth) { + var chWidth = Math.ceil(width / charWidth(cm.display)); + if (chWidth > cm.display.maxLineLength) { + cm.display.maxLineLength = chWidth; + cm.display.maxLine = cur.line; + cm.display.maxLineChanged = true; } } } + if (Math.abs(mustScroll) > 2) { + display.scroller.scrollTop += mustScroll; + } } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var dialog$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function dialogDiv(cm, template, bottom) { - var wrap = cm.getWrapperElement(); - var dialog2; - dialog2 = wrap.appendChild(document.createElement("div")); - if (bottom) dialog2.className = "CodeMirror-dialog CodeMirror-dialog-bottom";else dialog2.className = "CodeMirror-dialog CodeMirror-dialog-top"; - if (typeof template == "string") { - dialog2.innerHTML = template; - } else { - dialog2.appendChild(template); - } - CodeMirror.addClass(wrap, "dialog-opened"); - return dialog2; - } - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - CodeMirror.defineExtension("openDialog", function (template, callback, options) { - if (!options) options = {}; - closeNotification(this, null); - var dialog2 = dialogDiv(this, template, options.bottom); - var closed = false, - me = this; - function close(newVal) { - if (typeof newVal == "string") { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - me.focus(); - if (options.onClose) options.onClose(dialog2); - } - } - var inp = dialog2.getElementsByTagName("input")[0], - button; - if (inp) { - inp.focus(); - if (options.value) { - inp.value = options.value; - if (options.selectValueOnOpen !== false) { - inp.select(); + function updateWidgetHeight(line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; ++i2) { + var w = line.widgets[i2], + parent = w.node.parentNode; + if (parent) { + w.height = parent.offsetHeight; } } - if (options.onInput) CodeMirror.on(inp, "input", function (e) { - options.onInput(e, inp.value, close); - }); - if (options.onKeyUp) CodeMirror.on(inp, "keyup", function (e) { - options.onKeyUp(e, inp.value, close); - }); - CodeMirror.on(inp, "keydown", function (e) { - if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { - return; + } + } + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + var from = lineAtHeight(doc, top), + to = lineAtHeight(doc, bottom); + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, + ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return { + from, + to: Math.max(to, from + 1) + }; + } + function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { + return; + } + var display = cm.display, + box = display.sizer.getBoundingClientRect(), + doScroll = null; + if (rect.top + box.top < 0) { + doScroll = true; + } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { + doScroll = false; + } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "​", null, "position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + rect.left + "px; width: " + Math.max(2, rect.right - rect.left) + "px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { + margin = 0; + } + var rect; + if (!cm.options.lineWrapping && pos == end) { + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; + } + for (var limit = 0; limit < 5; limit++) { + var changed = false; + var coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + rect = { + left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin + }; + var scrollPos = calculateScrollPos(cm, rect); + var startTop = cm.doc.scrollTop, + startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { + changed = true; } - if (e.keyCode == 27 || options.closeOnEnter !== false && e.keyCode == 13) { - inp.blur(); - CodeMirror.e_stop(e); - close(); + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { + changed = true; } - if (e.keyCode == 13) callback(inp.value, e); - }); - if (options.closeOnBlur !== false) CodeMirror.on(dialog2, "focusout", function (evt) { - if (evt.relatedTarget !== null) close(); - }); - } else if (button = dialog2.getElementsByTagName("button")[0]) { - CodeMirror.on(button, "click", function () { - close(); - me.focus(); - }); - if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); - button.focus(); + } + if (!changed) { + break; + } } - return close; - }); - CodeMirror.defineExtension("openConfirm", function (template, callbacks, options) { - closeNotification(this, null); - var dialog2 = dialogDiv(this, template, options && options.bottom); - var buttons = dialog2.getElementsByTagName("button"); - var closed = false, - me = this, - blurring = 1; - function close() { - if (closed) return; - closed = true; - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); - me.focus(); + return rect; + } + function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect); + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); } - buttons[0].focus(); - for (var i = 0; i < buttons.length; ++i) { - var b = buttons[i]; - (function (callback) { - CodeMirror.on(b, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - if (callback) callback(me); - }); - })(callbacks[i]); - CodeMirror.on(b, "blur", function () { - --blurring; - setTimeout(function () { - if (blurring <= 0) close(); - }, 200); - }); - CodeMirror.on(b, "focus", function () { - ++blurring; - }); + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); } - }); - CodeMirror.defineExtension("openNotification", function (template, options) { - closeNotification(this, close); - var dialog2 = dialogDiv(this, template, options && options.bottom); - var closed = false, - doneTimer; - var duration = options && typeof options.duration !== "undefined" ? options.duration : 5e3; - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); - dialog2.parentNode.removeChild(dialog2); + } + function calculateScrollPos(cm, rect) { + var display = cm.display, + snapMargin = textHeight(cm.display); + if (rect.top < 0) { + rect.top = 0; } - CodeMirror.on(dialog2, "click", function (e) { - CodeMirror.e_preventDefault(e); - close(); - }); - if (duration) doneTimer = setTimeout(close, duration); - return close; - }); - }); - })(); - var dialogExports = dialog$2.exports; - const dialog = /* @__PURE__ */codemirror.getDefaultExportFromCjs(dialogExports); - const dialog$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: dialog - }, [dialogExports]); - exports.dialog = dialog$1; - exports.dialogExports = dialogExports; - - /***/ }), - - /***/ "../../graphiql-react/dist/foldgutter.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/foldgutter.cjs.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen2 = displayHeight(cm), + result = {}; + if (rect.bottom - rect.top > screen2) { + rect.bottom = rect.top + screen2; + } + var docBottom = cm.doc.height + paddingVert(display); + var atTop = rect.top < snapMargin, + atBottom = rect.bottom > docBottom - snapMargin; + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top; + } else if (rect.bottom > screentop + screen2) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen2); + if (newTop != screentop) { + result.scrollTop = newTop; } } + var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; + var screenw = displayWidth(cm) - display.gutters.offsetWidth; + var tooWide = rect.right - rect.left > screenw; + if (tooWide) { + rect.right = rect.left + screenw; + } + if (rect.left < 10) { + result.scrollLeft = 0; + } else if (rect.left < screenleft) { + result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); + } else if (rect.right > screenw + screenleft - 3) { + result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; + } + return result; } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var foldgutter$2 = { - exports: {} - }; - var foldcode = { - exports: {} - }; - var hasRequiredFoldcode; - function requireFoldcode() { - if (hasRequiredFoldcode) return foldcode.exports; - hasRequiredFoldcode = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - function doFold(cm, pos, options, force) { - if (options && options.call) { - var finder = options; - options = null; - } else { - var finder = getOption(cm, options, "rangeFinder"); - } - if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); - var minSize = getOption(cm, options, "minFoldSize"); - function getRange(allowFolded) { - var range2 = finder(cm, pos); - if (!range2 || range2.to.line - range2.from.line < minSize) return null; - if (force === "fold") return range2; - var marks = cm.findMarksAt(range2.from); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - if (!allowFolded) return null; - range2.cleared = true; - marks[i].clear(); - } - } - return range2; - } - var range = getRange(true); - if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) { - pos = CodeMirror.Pos(pos.line - 1, 0); - range = getRange(false); - } - if (!range || range.cleared || force === "unfold") return; - var myWidget = makeWidget(cm, options, range); - CodeMirror.on(myWidget, "mousedown", function (e) { - myRange.clear(); - CodeMirror.e_preventDefault(e); - }); - var myRange = cm.markText(range.from, range.to, { - replacedWith: myWidget, - clearOnEnter: getOption(cm, options, "clearOnEnter"), - __isFold: true - }); - myRange.on("clear", function (from, to) { - CodeMirror.signal(cm, "unfold", cm, from, to); + function addToScrollTop(cm, top) { + if (top == null) { + return; + } + resolveScrollToPos(cm); + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(); + cm.curOp.scrollToPos = { + from: cur, + to: cur, + margin: cm.options.cursorScrollMargin + }; + } + function scrollToCoords(cm, x, y) { + if (x != null || y != null) { + resolveScrollToPos(cm); + } + if (x != null) { + cm.curOp.scrollLeft = x; + } + if (y != null) { + cm.curOp.scrollTop = y; + } + } + function scrollToRange(cm, range2) { + resolveScrollToPos(cm); + cm.curOp.scrollToPos = range2; + } + function resolveScrollToPos(cm) { + var range2 = cm.curOp.scrollToPos; + if (range2) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range2.from), + to = estimateCoords(cm, range2.to); + scrollToCoordsRange(cm, from, to, range2.margin); + } + } + function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin + }); + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); + } + function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { + return; + } + if (!gecko) { + updateDisplaySimple(cm, { + top: val }); - CodeMirror.signal(cm, "fold", cm, range.from, range.to); - } - function makeWidget(cm, options, range) { - var widget = getOption(cm, options, "widget"); - if (typeof widget == "function") { - widget = widget(range.from, range.to); - } - if (typeof widget == "string") { - var text = document.createTextNode(widget); - widget = document.createElement("span"); - widget.appendChild(text); - widget.className = "CodeMirror-foldmarker"; - } else if (widget) { - widget = widget.cloneNode(true); - } - return widget; - } - CodeMirror.newFoldFunction = function (rangeFinder, widget) { - return function (cm, pos) { - doFold(cm, pos, { - rangeFinder, - widget - }); - }; + } + setScrollTop(cm, val, true); + if (gecko) { + updateDisplaySimple(cm); + } + startWorker(cm, 100); + } + function setScrollTop(cm, val, forceScroll) { + val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); + if (cm.display.scroller.scrollTop == val && !forceScroll) { + return; + } + cm.doc.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (cm.display.scroller.scrollTop != val) { + cm.display.scroller.scrollTop = val; + } + } + function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { + return; + } + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) { + cm.display.scroller.scrollLeft = val; + } + cm.display.scrollbars.setScrollLeft(val); + } + function measureForScrollbars(cm) { + var d = cm.display, + gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, + clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW }; - CodeMirror.defineExtension("foldCode", function (pos, options, force) { - doFold(this, pos, options, force); + } + var NativeScrollbars = function (place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + vert.tabIndex = horiz.tabIndex = -1; + place(vert); + place(horiz); + on(vert, "scroll", function () { + if (vert.clientHeight) { + scroll(vert.scrollTop, "vertical"); + } }); - CodeMirror.defineExtension("isFolded", function (pos) { - var marks = this.findMarksAt(pos); - for (var i = 0; i < marks.length; ++i) if (marks[i].__isFold) return true; + on(horiz, "scroll", function () { + if (horiz.clientWidth) { + scroll(horiz.scrollLeft, "horizontal"); + } }); - CodeMirror.commands.toggleFold = function (cm) { - cm.foldCode(cm.getCursor()); - }; - CodeMirror.commands.fold = function (cm) { - cm.foldCode(cm.getCursor(), null, "fold"); - }; - CodeMirror.commands.unfold = function (cm) { - cm.foldCode(cm.getCursor(), { - scanUp: false - }, "unfold"); + this.checkedZeroWidth = false; + if (ie && ie_version < 8) { + this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } + }; + NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.scrollTop = 0; + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { + this.zeroWidthHack(); + } + this.checkedZeroWidth = true; + } + return { + right: needsV ? sWidth : 0, + bottom: needsH ? sWidth : 0 }; - CodeMirror.commands.foldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { - scanUp: false - }, "fold"); - }); + }; + NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { + this.horiz.scrollLeft = pos; + } + if (this.disableHoriz) { + this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); + } + }; + NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { + this.vert.scrollTop = pos; + } + if (this.disableVert) { + this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); + } + }; + NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; + this.disableHoriz = new Delayed(); + this.disableVert = new Delayed(); + }; + NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { + bar.style.pointerEvents = "auto"; + function maybeDisable() { + var box = bar.getBoundingClientRect(); + var elt2 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); + if (elt2 != bar) { + bar.style.pointerEvents = "none"; + } else { + delay.set(1e3, maybeDisable); + } + } + delay.set(1e3, maybeDisable); + }; + NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + }; + var NullScrollbars = function () {}; + NullScrollbars.prototype.update = function () { + return { + bottom: 0, + right: 0 }; - CodeMirror.commands.unfoldAll = function (cm) { - cm.operation(function () { - for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { - scanUp: false - }, "unfold"); + }; + NullScrollbars.prototype.setScrollLeft = function () {}; + NullScrollbars.prototype.setScrollTop = function () {}; + NullScrollbars.prototype.clear = function () {}; + function updateScrollbars(cm, measure) { + if (!measure) { + measure = measureForScrollbars(cm); + } + var startWidth = cm.display.barWidth, + startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i2 = 0; i2 < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i2++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { + updateHeightsInViewport(cm); + } + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; + startHeight = cm.display.barHeight; + } + } + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else { + d.scrollbarFiller.style.display = ""; + } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else { + d.gutterFiller.style.display = ""; + } + } + var scrollbarModel = { + "native": NativeScrollbars, + "null": NullScrollbars + }; + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) { + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + on(node, "mousedown", function () { + if (cm.state.focused) { + setTimeout(function () { + return cm.display.input.focus(); + }, 0); + } }); + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") { + setScrollLeft(cm, pos); + } else { + updateScrollTop(cm, pos); + } + }, cm); + if (cm.display.scrollbars.addClass) { + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + } + var nextOpId = 0; + function startOperation(cm) { + cm.curOp = { + cm, + viewChanged: false, + // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, + // Used to detect need to update scrollbar + forceUpdate: false, + // Used to force a redraw + updateInput: 0, + // Whether to reset the input textarea + typing: false, + // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, + // Accumulated changes, for firing change events + cursorActivityHandlers: null, + // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, + // Tracks which cursorActivity handlers have been called already + selectionChanged: false, + // Whether the selection needs to be redrawn + updateMaxLine: false, + // Set when the widest line needs to be determined anew + scrollLeft: null, + scrollTop: null, + // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, + // Used to scroll to a specific position + focus: false, + id: ++nextOpId, + // Unique ID + markArrays: null + // Used by addMarkedSpan }; - CodeMirror.registerHelper("fold", "combine", function () { - var funcs = Array.prototype.slice.call(arguments, 0); - return function (cm, start) { - for (var i = 0; i < funcs.length; ++i) { - var found = funcs[i](cm, start); - if (found) return found; + pushOperation(cm.curOp); + } + function endOperation(cm) { + var op = cm.curOp; + if (op) { + finishOperation(op, function (group) { + for (var i2 = 0; i2 < group.ops.length; i2++) { + group.ops[i2].cm.curOp = null; } - }; - }); - CodeMirror.registerHelper("fold", "auto", function (cm, start) { - var helpers = cm.getHelpers(start, "fold"); - for (var i = 0; i < helpers.length; i++) { - var cur = helpers[i](cm, start); - if (cur) return cur; - } - }); - var defaultOptions = { - rangeFinder: CodeMirror.fold.auto, - widget: "↔", - minFoldSize: 0, - scanUp: false, - clearOnEnter: true - }; - CodeMirror.defineOption("foldOptions", null); - function getOption(cm, options, name) { - if (options && options[name] !== void 0) return options[name]; - var editorOptions = cm.options.foldOptions; - if (editorOptions && editorOptions[name] !== void 0) return editorOptions[name]; - return defaultOptions[name]; - } - CodeMirror.defineExtension("foldOption", function (options, name) { - return getOption(this, options, name); - }); - }); - })(); - return foldcode.exports; - } - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), requireFoldcode()); - })(function (CodeMirror) { - CodeMirror.defineOption("foldGutter", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.clearGutter(cm.state.foldGutter.options.gutter); - cm.state.foldGutter = null; - cm.off("gutterClick", onGutterClick); - cm.off("changes", onChange); - cm.off("viewportChange", onViewportChange); - cm.off("fold", onFold); - cm.off("unfold", onFold); - cm.off("swapDoc", onChange); + endOperations(group); + }); } - if (val) { - cm.state.foldGutter = new State(parseOptions(val)); - updateInViewport(cm); - cm.on("gutterClick", onGutterClick); - cm.on("changes", onChange); - cm.on("viewportChange", onViewportChange); - cm.on("fold", onFold); - cm.on("unfold", onFold); - cm.on("swapDoc", onChange); + } + function endOperations(group) { + var ops = group.ops; + for (var i2 = 0; i2 < ops.length; i2++) { + endOperation_R1(ops[i2]); } - }); - var Pos = CodeMirror.Pos; - function State(options) { - this.options = options; - this.from = this.to = 0; + for (var i$12 = 0; i$12 < ops.length; i$12++) { + endOperation_W1(ops[i$12]); + } + for (var i$22 = 0; i$22 < ops.length; i$22++) { + endOperation_R2(ops[i$22]); + } + for (var i$3 = 0; i$3 < ops.length; i$3++) { + endOperation_W2(ops[i$3]); + } + for (var i$4 = 0; i$4 < ops.length; i$4++) { + endOperation_finish(ops[i$4]); + } + } + function endOperation_R1(op) { + var cm = op.cm, + display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) { + findMaxLine(cm); + } + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && { + top: op.scrollTop, + ensure: op.scrollToPos + }, op.forceUpdate); } - function parseOptions(opts) { - if (opts === true) opts = {}; - if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; - if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; - if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; - return opts; + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + function endOperation_R2(op) { + var cm = op.cm, + display = cm.display; + if (op.updatedDisplay) { + updateHeightsInViewport(cm); + } + op.barMeasure = measureForScrollbars(cm); + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + if (op.updatedDisplay || op.selectionChanged) { + op.preparedSelection = display.input.prepareSelection(); + } } - function isFolded(cm, line) { - var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); - for (var i = 0; i < marks.length; ++i) { - if (marks[i].__isFold) { - var fromPos = marks[i].find(-1); - if (fromPos && fromPos.line === line) return marks[i]; + function endOperation_W2(op) { + var cm = op.cm; + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) { + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } + cm.display.maxLineChanged = false; + } + var takeFocus = op.focus && op.focus == activeElt(); + if (op.preparedSelection) { + cm.display.input.showSelection(op.preparedSelection, takeFocus); + } + if (op.updatedDisplay || op.startHeight != cm.doc.height) { + updateScrollbars(cm, op.barMeasure); + } + if (op.updatedDisplay) { + setDocumentHeight(cm, op.barMeasure); + } + if (op.selectionChanged) { + restartBlink(cm); + } + if (cm.state.focused && op.updateInput) { + cm.display.input.reset(op.typing); + } + if (takeFocus) { + ensureFocus(op.cm); } } - function marker(spec) { - if (typeof spec == "string") { - var elt = document.createElement("div"); - elt.className = spec + " CodeMirror-guttermarker-subtle"; - return elt; - } else { - return spec.cloneNode(true); - } - } - function updateFoldInfo(cm, from, to) { - var opts = cm.state.foldGutter.options, - cur = from - 1; - var minSize = cm.foldOption(opts, "minFoldSize"); - var func = cm.foldOption(opts, "rangeFinder"); - var clsFolded = typeof opts.indicatorFolded == "string" && classTest(opts.indicatorFolded); - var clsOpen = typeof opts.indicatorOpen == "string" && classTest(opts.indicatorOpen); - cm.eachLine(from, to, function (line) { - ++cur; - var mark = null; - var old = line.gutterMarkers; - if (old) old = old[opts.gutter]; - if (isFolded(cm, cur)) { - if (clsFolded && old && clsFolded.test(old.className)) return; - mark = marker(opts.indicatorFolded); - } else { - var pos = Pos(cur, 0); - var range = func && func(cm, pos); - if (range && range.to.line - range.from.line >= minSize) { - if (clsOpen && old && clsOpen.test(old.className)) return; - mark = marker(opts.indicatorOpen); + function endOperation_finish(op) { + var cm = op.cm, + display = cm.display, + doc = cm.doc; + if (op.updatedDisplay) { + postUpdateDisplay(cm, op.update); + } + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { + display.wheelStartX = display.wheelStartY = null; + } + if (op.scrollTop != null) { + setScrollTop(cm, op.scrollTop, op.forceScroll); + } + if (op.scrollLeft != null) { + setScrollLeft(cm, op.scrollLeft, true, true); + } + if (op.scrollToPos) { + var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + maybeScrollWindow(cm, rect); + } + var hidden = op.maybeHiddenMarkers, + unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i2 = 0; i2 < hidden.length; ++i2) { + if (!hidden[i2].lines.length) { + signal(hidden[i2], "hide"); } } - if (!mark && !old) return; - cm.setGutterMarker(line, opts.gutter, mark); - }); - } - function classTest(cls) { - return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); - } - function updateInViewport(cm) { - var vp = cm.getViewport(), - state = cm.state.foldGutter; - if (!state) return; - cm.operation(function () { - updateFoldInfo(cm, vp.from, vp.to); - }); - state.from = vp.from; - state.to = vp.to; - } - function onGutterClick(cm, line, gutter) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - if (gutter != opts.gutter) return; - var folded = isFolded(cm, line); - if (folded) folded.clear();else cm.foldCode(Pos(line, 0), opts); - } - function onChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - state.from = state.to = 0; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - updateInViewport(cm); - }, opts.foldOnChangeTimeSpan || 600); - } - function onViewportChange(cm) { - var state = cm.state.foldGutter; - if (!state) return; - var opts = state.options; - clearTimeout(state.changeUpdate); - state.changeUpdate = setTimeout(function () { - var vp = cm.getViewport(); - if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { - updateInViewport(cm); - } else { - cm.operation(function () { - if (vp.from < state.from) { - updateFoldInfo(cm, vp.from, state.from); - state.from = vp.from; - } - if (vp.to > state.to) { - updateFoldInfo(cm, state.to, vp.to); - state.to = vp.to; - } - }); + } + if (unhidden) { + for (var i$12 = 0; i$12 < unhidden.length; ++i$12) { + if (unhidden[i$12].lines.length) { + signal(unhidden[i$12], "unhide"); + } } - }, opts.updateViewportTimeSpan || 400); + } + if (display.wrapper.offsetHeight) { + doc.scrollTop = cm.display.scroller.scrollTop; + } + if (op.changeObjs) { + signal(cm, "changes", cm, op.changeObjs); + } + if (op.update) { + op.update.finish(); + } } - function onFold(cm, from) { - var state = cm.state.foldGutter; - if (!state) return; - var line = from.line; - if (line >= state.from && line < state.to) updateFoldInfo(cm, line, line + 1); + function runInOp(cm, f) { + if (cm.curOp) { + return f(); + } + startOperation(cm); + try { + return f(); + } finally { + endOperation(cm); + } } - }); - })(); - var foldgutterExports = foldgutter$2.exports; - const foldgutter = /* @__PURE__ */codemirror.getDefaultExportFromCjs(foldgutterExports); - const foldgutter$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: foldgutter - }, [foldgutterExports]); - exports.foldgutter = foldgutter$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/forEachState.cjs.js": - /*!*****************************************************!*\ - !*** ../../graphiql-react/dist/forEachState.cjs.js ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - function forEachState(stack, fn) { - const reverseStateStack = []; - let state = stack; - while (state === null || state === void 0 ? void 0 : state.kind) { - reverseStateStack.push(state); - state = state.prevState; - } - for (let i = reverseStateStack.length - 1; i >= 0; i--) { - fn(reverseStateStack[i]); - } - } - exports.forEachState = forEachState; - - /***/ }), - - /***/ "../../graphiql-react/dist/hint.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/hint.cjs.js ***! - \*********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - __webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js"); - const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); - codemirror.CodeMirror.registerHelper("hint", "graphql", (editor, options) => { - const { - schema, - externalFragments, - autocompleteOptions - } = options; - if (!schema) { - return; - } - const cur = editor.getCursor(); - const token = editor.getTokenAt(cur); - const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; - const position = new graphqlLanguageService.Position(cur.line, tokenStart); - const rawResults = graphqlLanguageService.getAutocompleteSuggestions(schema, editor.getValue(), position, token, externalFragments, autocompleteOptions); - const results = { - list: rawResults.map(item => { - var _a; - return { - text: (_a = item === null || item === void 0 ? void 0 : item.rawInsert) !== null && _a !== void 0 ? _a : item.label, - type: item.type, - description: item.documentation, - isDeprecated: item.isDeprecated, - deprecationReason: item.deprecationReason + function operation(cm, f) { + return function () { + if (cm.curOp) { + return f.apply(cm, arguments); + } + startOperation(cm); + try { + return f.apply(cm, arguments); + } finally { + endOperation(cm); + } }; - }), - from: { - line: cur.line, - ch: tokenStart - }, - to: { - line: cur.line, - ch: token.end - } - }; - if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { - results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); - results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); - codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); - } - return results; - }); - - /***/ }), - - /***/ "../../graphiql-react/dist/hint.cjs2.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/hint.cjs2.js ***! - \**********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); - function hintList(cursor, token, list) { - const hints = filterAndSortList(list, normalizeText(token.string)); - if (!hints) { - return; - } - const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; - return { - list: hints, - from: { - line: cursor.line, - ch: tokenStart - }, - to: { - line: cursor.line, - ch: token.end - } - }; - } - function filterAndSortList(list, text) { - if (!text) { - return filterNonEmpty(list, entry => !entry.isDeprecated); - } - const byProximity = list.map(entry => ({ - proximity: getProximity(normalizeText(entry.text), text), - entry - })); - const conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated); - const sortedMatches = conciseMatches.sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.text.length - b.entry.text.length); - return sortedMatches.map(pair => pair.entry); - } - function filterNonEmpty(array, predicate) { - const filtered = array.filter(predicate); - return filtered.length === 0 ? array : filtered; - } - function normalizeText(text) { - return text.toLowerCase().replaceAll(/\W/g, ""); - } - function getProximity(suggestion, text) { - let proximity = lexicalDistance(text, suggestion); - if (suggestion.length > text.length) { - proximity -= suggestion.length - text.length - 1; - proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; - } - return proximity; - } - function lexicalDistance(a, b) { - let i; - let j; - const d = []; - const aLength = a.length; - const bLength = b.length; - for (i = 0; i <= aLength; i++) { - d[i] = [i]; - } - for (j = 1; j <= bLength; j++) { - d[0][j] = j; - } - for (i = 1; i <= aLength; i++) { - for (j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); - } } - } - return d[aLength][bLength]; - } - codemirror.CodeMirror.registerHelper("hint", "graphql-variables", (editor, options) => { - const cur = editor.getCursor(); - const token = editor.getTokenAt(cur); - const results = getVariablesHint(cur, token, options); - if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { - results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); - results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); - codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); - } - return results; - }); - function getVariablesHint(cur, token, options) { - const state = token.state.kind === "Invalid" ? token.state.prevState : token.state; - const { - kind, - step - } = state; - if (kind === "Document" && step === 0) { - return hintList(cur, token, [{ - text: "{" - }]); - } - const { - variableToType - } = options; - if (!variableToType) { - return; - } - const typeInfo = getTypeInfo(variableToType, token.state); - if (kind === "Document" || kind === "Variable" && step === 0) { - const variableNames = Object.keys(variableToType); - return hintList(cur, token, variableNames.map(name => ({ - text: `"${name}": `, - type: variableToType[name] - }))); - } - if ((kind === "ObjectValue" || kind === "ObjectField" && step === 0) && typeInfo.fields) { - const inputFields = Object.keys(typeInfo.fields).map(fieldName => typeInfo.fields[fieldName]); - return hintList(cur, token, inputFields.map(field => ({ - text: `"${field.name}": `, - type: field.type, - description: field.description - }))); - } - if (kind === "StringValue" || kind === "NumberValue" || kind === "BooleanValue" || kind === "NullValue" || kind === "ListValue" && step === 1 || kind === "ObjectField" && step === 2 || kind === "Variable" && step === 2) { - const namedInputType = typeInfo.type ? graphql.getNamedType(typeInfo.type) : void 0; - if (namedInputType instanceof graphql.GraphQLInputObjectType) { - return hintList(cur, token, [{ - text: "{" - }]); - } - if (namedInputType instanceof graphql.GraphQLEnumType) { - const values = namedInputType.getValues(); - return hintList(cur, token, values.map(value => ({ - text: `"${value.name}"`, - type: namedInputType, - description: value.description - }))); - } - if (namedInputType === graphql.GraphQLBoolean) { - return hintList(cur, token, [{ - text: "true", - type: graphql.GraphQLBoolean, - description: "Not false." - }, { - text: "false", - type: graphql.GraphQLBoolean, - description: "Not true." - }]); - } - } - } - function getTypeInfo(variableToType, tokenState) { - const info = { - type: null, - fields: null - }; - forEachState.forEachState(tokenState, state => { - switch (state.kind) { - case "Variable": - { - info.type = variableToType[state.name]; - break; + function methodOp(f) { + return function () { + if (this.curOp) { + return f.apply(this, arguments); } - case "ListValue": - { - const nullableType = info.type ? graphql.getNullableType(info.type) : void 0; - info.type = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; - break; + startOperation(this); + try { + return f.apply(this, arguments); + } finally { + endOperation(this); } - case "ObjectValue": - { - const objectType = info.type ? graphql.getNamedType(info.type) : void 0; - info.fields = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; - break; + }; + } + function docMethodOp(f) { + return function () { + var cm = this.cm; + if (!cm || cm.curOp) { + return f.apply(this, arguments); } - case "ObjectField": - { - const objectField = state.name && info.fields ? info.fields[state.name] : null; - info.type = objectField === null || objectField === void 0 ? void 0 : objectField.type; - break; + startOperation(cm); + try { + return f.apply(this, arguments); + } finally { + endOperation(cm); } + }; } - }); - return info; - } - - /***/ }), - - /***/ "../../graphiql-react/dist/index.js": - /*!******************************************!*\ - !*** ../../graphiql-react/dist/index.js ***! - \******************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, Symbol.toStringTag, { - value: "Module" - }); - const jsxRuntime = __webpack_require__(/*! react/jsx-runtime */ "../../../node_modules/react/jsx-runtime.js"); - const React = __webpack_require__(/*! react */ "react"); - const clsx = __webpack_require__(/*! clsx */ "../../../node_modules/clsx/dist/clsx.m.js"); - const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const toolkit = __webpack_require__(/*! @graphiql/toolkit */ "../../graphiql-toolkit/esm/index.js"); - const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); - const setValue = __webpack_require__(/*! set-value */ "../../../node_modules/set-value/index.js"); - const copyToClipboard = __webpack_require__(/*! copy-to-clipboard */ "../../../node_modules/copy-to-clipboard/index.js"); - const D = __webpack_require__(/*! @radix-ui/react-dialog */ "../../../node_modules/@radix-ui/react-dialog/dist/index.js"); - const reactVisuallyHidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); - const reactDropdownMenu = __webpack_require__(/*! @radix-ui/react-dropdown-menu */ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js"); - const MarkdownIt = __webpack_require__(/*! markdown-it */ "../node_modules/markdown-it/dist/index.cjs.js"); - const framerMotion = __webpack_require__(/*! framer-motion */ "../../../node_modules/framer-motion/dist/cjs/index.js"); - const T = __webpack_require__(/*! @radix-ui/react-tooltip */ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js"); - const react = __webpack_require__(/*! @headlessui/react */ "../../../node_modules/@headlessui/react/dist/index.cjs"); - const ReactDOM = __webpack_require__(/*! react-dom */ "react-dom"); - function _interopNamespaceDefault(e) { - const n = Object.create(null, { - [Symbol.toStringTag]: { - value: "Module" + function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) { + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } } - }); - if (e) { - for (const k in e) { - if (k !== "default") { - const d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.highlightFrontier >= cm.display.viewTo) { + return; + } + var end = + /* @__PURE__ */new Date() + cm.options.workTime; + var context = getContextBefore(cm, doc.highlightFrontier); + var changedLines = []; + doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (context.line >= cm.display.viewFrom) { + var oldStyles = line.styles; + var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; + var highlighted = highlightLine(cm, line, context, true); + if (resetState) { + context.state = resetState; + } + line.styles = highlighted.styles; + var oldCls = line.styleClasses, + newCls = highlighted.classes; + if (newCls) { + line.styleClasses = newCls; + } else if (oldCls) { + line.styleClasses = null; + } + var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i2 = 0; !ischange && i2 < oldStyles.length; ++i2) { + ischange = oldStyles[i2] != line.styles[i2]; + } + if (ischange) { + changedLines.push(context.line); + } + line.stateAfter = context.save(); + context.nextLine(); + } else { + if (line.text.length <= cm.options.maxHighlightLength) { + processLine(cm, line.text, context); + } + line.stateAfter = context.line % 5 == 0 ? context.save() : null; + context.nextLine(); + } + if (+ /* @__PURE__ */new Date() > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + doc.highlightFrontier = context.line; + doc.modeFrontier = Math.max(doc.modeFrontier, context.line); + if (changedLines.length) { + runInOp(cm, function () { + for (var i2 = 0; i2 < changedLines.length; i2++) { + regLineChange(cm, changedLines[i2], "text"); + } }); } } - } - n.default = e; - return Object.freeze(n); - } - const React__namespace = /* @__PURE__ */_interopNamespaceDefault(React); - const D__namespace = /* @__PURE__ */_interopNamespaceDefault(D); - const T__namespace = /* @__PURE__ */_interopNamespaceDefault(T); - function createNullableContext(name) { - const context = React.createContext(null); - context.displayName = name; - return context; - } - function createContextHook(context) { - function useGivenContext(options) { - var _a; - const value = React.useContext(context); - if (value === null && (options == null ? void 0 : options.nonNull)) { - throw new Error(`Tried to use \`${((_a = options.caller) == null ? void 0 : _a.name) || useGivenContext.caller.name}\` without the necessary context. Make sure to render the \`${context.displayName}Provider\` component higher up the tree.`); - } - return value; - } - Object.defineProperty(useGivenContext, "name", { - value: `use${context.displayName}` - }); - return useGivenContext; - } - const StorageContext = createNullableContext("StorageContext"); - function StorageContextProvider(props) { - const isInitialRender = React.useRef(true); - const [storage, setStorage] = React.useState(new toolkit.StorageAPI(props.storage)); - React.useEffect(() => { - if (isInitialRender.current) { - isInitialRender.current = false; - } else { - setStorage(new toolkit.StorageAPI(props.storage)); - } - }, [props.storage]); - return /* @__PURE__ */jsxRuntime.jsx(StorageContext.Provider, { - value: storage, - children: props.children - }); - } - const useStorageContext = createContextHook(StorageContext); - const SvgArgument = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("rect", { - x: 6, - y: 6, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" - })); - const SvgChevronDown = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 9", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1 1L7 7L13 1", - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgChevronLeft = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 7 10", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M6 1.04819L2 5.04819L6 9.04819", - stroke: "currentColor", - strokeWidth: 1.75 - })); - const SvgChevronUp = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 9", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M13 8L7 2L1 8", - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgClose = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - stroke: "currentColor", - strokeWidth: 3, - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1 1L12.9998 12.9997" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M13 1L1.00079 13.0003" - })); - const SvgCopy = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "-2 -2 22 22", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.25 14.2105V15.235C11.25 16.3479 10.3479 17.25 9.23501 17.25H2.76499C1.65214 17.25 0.75 16.3479 0.75 15.235L0.75 8.76499C0.75 7.65214 1.65214 6.75 2.76499 6.75L3.78947 6.75", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("rect", { - x: 6.75, - y: 0.75, - width: 10.5, - height: 10.5, - rx: 2.2069, - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgDeprecatedArgument = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M5 9L9 5", - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M5 5L9 9", - stroke: "currentColor", - strokeWidth: 1.2 - })); - const SvgDeprecatedEnumValue = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 8L8 4", - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 4L8 8", - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", - fill: "currentColor" - })); - const SvgDeprecatedField = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 10.8, - height: 10.8, - rx: 3.4, - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 8L8 4", - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 4L8 8", - stroke: "currentColor", - strokeWidth: 1.2 - })); - const SvgDirective = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0.5 12 12", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 7, - y: 5.5, - width: 2, - height: 2, - rx: 1, - transform: "rotate(90 7 5.5)", - fill: "currentColor" - }), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M10.8 9L10.8 9.5C10.8 10.4941 9.99411 11.3 9 11.3L3 11.3C2.00589 11.3 1.2 10.4941 1.2 9.5L1.2 9L-3.71547e-07 9L-3.93402e-07 9.5C-4.65826e-07 11.1569 1.34314 12.5 3 12.5L9 12.5C10.6569 12.5 12 11.1569 12 9.5L12 9L10.8 9ZM10.8 4L12 4L12 3.5C12 1.84315 10.6569 0.5 9 0.5L3 0.5C1.34315 0.5 -5.87117e-08 1.84315 -1.31135e-07 3.5L-1.5299e-07 4L1.2 4L1.2 3.5C1.2 2.50589 2.00589 1.7 3 1.7L9 1.7C9.99411 1.7 10.8 2.50589 10.8 3.5L10.8 4Z", - fill: "currentColor" - })); - const SvgDocsFilled = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 20 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H17.25C17.8023 0.75 18.25 1.19772 18.25 1.75V5.25", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H18.25C18.8023 5.25 19.25 5.69771 19.25 6.25V22.25C19.25 22.8023 18.8023 23.25 18.25 23.25H3C1.75736 23.25 0.75 22.2426 0.75 21V3Z", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M3 5.25C1.75736 5.25 0.75 4.24264 0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H3ZM13 11L6 11V12.5L13 12.5V11Z", - fill: "currentColor" - })); - const SvgDocs = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 20 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H17.25M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H16.25C16.8023 0.75 17.25 1.19772 17.25 1.75V5.25M0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H17.25", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("line", { - x1: 13, - y1: 11.75, - x2: 6, - y2: 11.75, - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgEnumValue = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 5, - y: 5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" - }), /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", - fill: "currentColor" - })); - const SvgField = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 1.1, - width: 10.8, - height: 10.8, - rx: 2.4, - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("rect", { - x: 5, - y: 5.5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" - })); - const SvgHistory = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 24 20", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.59375 9.52344L4.87259 12.9944L8.07872 9.41249", - stroke: "currentColor", - strokeWidth: 1.5, - strokeLinecap: "square" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M13.75 5.25V10.75H18.75", - stroke: "currentColor", - strokeWidth: 1.5, - strokeLinecap: "square" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4.95427 11.9332C4.55457 10.0629 4.74441 8.11477 5.49765 6.35686C6.25089 4.59894 7.5305 3.11772 9.16034 2.11709C10.7902 1.11647 12.6901 0.645626 14.5986 0.769388C16.5071 0.893151 18.3303 1.60543 19.8172 2.80818C21.3042 4.01093 22.3818 5.64501 22.9017 7.48548C23.4216 9.32595 23.3582 11.2823 22.7203 13.0853C22.0824 14.8883 20.9013 16.4492 19.3396 17.5532C17.778 18.6572 15.9125 19.25 14 19.25", - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgImplements = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 12 12", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { - cx: 6, - cy: 6, - r: 5.4, - stroke: "currentColor", - strokeWidth: 1.2, - strokeDasharray: "4.241025 4.241025", - transform: "rotate(22.5)", - "transform-origin": "center" - }), /* @__PURE__ */React__namespace.createElement("circle", { - cx: 6, - cy: 6, - r: 1, - fill: "currentColor" - })); - const SvgKeyboardShortcut = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 19 18", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.5 14.5653C1.5 15.211 1.75652 15.8303 2.21314 16.2869C2.66975 16.7435 3.28905 17 3.9348 17C4.58054 17 5.19984 16.7435 5.65646 16.2869C6.11307 15.8303 6.36959 15.211 6.36959 14.5653V12.1305H3.9348C3.28905 12.1305 2.66975 12.387 2.21314 12.8437C1.75652 13.3003 1.5 13.9195 1.5 14.5653Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M3.9348 1.00063C3.28905 1.00063 2.66975 1.25715 2.21314 1.71375C1.75652 2.17035 1.5 2.78964 1.5 3.43537C1.5 4.0811 1.75652 4.70038 2.21314 5.15698C2.66975 5.61358 3.28905 5.8701 3.9348 5.8701H6.36959V3.43537C6.36959 2.78964 6.11307 2.17035 5.65646 1.71375C5.19984 1.25715 4.58054 1.00063 3.9348 1.00063Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M15.0652 12.1305H12.6304V14.5653C12.6304 15.0468 12.7732 15.5175 13.0407 15.9179C13.3083 16.3183 13.6885 16.6304 14.1334 16.8147C14.5783 16.9989 15.0679 17.0472 15.5402 16.9532C16.0125 16.8593 16.4464 16.6274 16.7869 16.2869C17.1274 15.9464 17.3593 15.5126 17.4532 15.0403C17.5472 14.568 17.4989 14.0784 17.3147 13.6335C17.1304 13.1886 16.8183 12.8084 16.4179 12.5409C16.0175 12.2733 15.5468 12.1305 15.0652 12.1305Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M12.6318 5.86775H6.36955V12.1285H12.6318V5.86775Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M17.5 3.43473C17.5 2.789 17.2435 2.16972 16.7869 1.71312C16.3303 1.25652 15.711 1 15.0652 1C14.4195 1 13.8002 1.25652 13.3435 1.71312C12.8869 2.16972 12.6304 2.789 12.6304 3.43473V5.86946H15.0652C15.711 5.86946 16.3303 5.61295 16.7869 5.15635C17.2435 4.69975 17.5 4.08046 17.5 3.43473Z", - stroke: "currentColor", - strokeWidth: 1.125, - strokeLinecap: "round", - strokeLinejoin: "round" - })); - const SvgMagnifyingGlass = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { - cx: 5, - cy: 5, - r: 4.35, - stroke: "currentColor", - strokeWidth: 1.3 - }), /* @__PURE__ */React__namespace.createElement("line", { - x1: 8.45962, - y1: 8.54038, - x2: 11.7525, - y2: 11.8333, - stroke: "currentColor", - strokeWidth: 1.3 - })); - const SvgMerge = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "-2 -2 22 22", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M17.2492 6V2.9569C17.2492 1.73806 16.2611 0.75 15.0423 0.75L2.9569 0.75C1.73806 0.75 0.75 1.73806 0.75 2.9569L0.75 6", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.749873 12V15.0431C0.749873 16.2619 1.73794 17.25 2.95677 17.25H15.0421C16.261 17.25 17.249 16.2619 17.249 15.0431V12", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M6 4.5L9 7.5L12 4.5", - stroke: "currentColor", - strokeWidth: 1.5 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M12 13.5L9 10.5L6 13.5", - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgPen = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M0.75 13.25L0.0554307 12.967C-0.0593528 13.2488 0.00743073 13.5719 0.224488 13.7851C0.441545 13.9983 0.765869 14.0592 1.04549 13.9393L0.75 13.25ZM12.8214 1.83253L12.2911 2.36286L12.2911 2.36286L12.8214 1.83253ZM12.8214 3.90194L13.3517 4.43227L12.8214 3.90194ZM10.0981 1.17859L9.56773 0.648259L10.0981 1.17859ZM12.1675 1.17859L12.6978 0.648258L12.6978 0.648257L12.1675 1.17859ZM2.58049 8.75697L3.27506 9.03994L2.58049 8.75697ZM2.70066 8.57599L3.23099 9.10632L2.70066 8.57599ZM5.2479 11.4195L4.95355 10.7297L5.2479 11.4195ZM5.42036 11.303L4.89003 10.7727L5.42036 11.303ZM4.95355 10.7297C4.08882 11.0987 3.41842 11.362 2.73535 11.6308C2.05146 11.9 1.35588 12.1743 0.454511 12.5607L1.04549 13.9393C1.92476 13.5624 2.60256 13.2951 3.28469 13.0266C3.96762 12.7578 4.65585 12.4876 5.54225 12.1093L4.95355 10.7297ZM1.44457 13.533L3.27506 9.03994L1.88592 8.474L0.0554307 12.967L1.44457 13.533ZM3.23099 9.10632L10.6284 1.70892L9.56773 0.648259L2.17033 8.04566L3.23099 9.10632ZM11.6371 1.70892L12.2911 2.36286L13.3517 1.3022L12.6978 0.648258L11.6371 1.70892ZM12.2911 3.37161L4.89003 10.7727L5.95069 11.8333L13.3517 4.43227L12.2911 3.37161ZM12.2911 2.36286C12.5696 2.64142 12.5696 3.09305 12.2911 3.37161L13.3517 4.43227C14.2161 3.56792 14.2161 2.16654 13.3517 1.3022L12.2911 2.36286ZM10.6284 1.70892C10.9069 1.43036 11.3586 1.43036 11.6371 1.70892L12.6978 0.648257C11.8335 -0.216088 10.4321 -0.216084 9.56773 0.648259L10.6284 1.70892ZM3.27506 9.03994C3.26494 9.06479 3.24996 9.08735 3.23099 9.10632L2.17033 8.04566C2.04793 8.16806 1.95123 8.31369 1.88592 8.474L3.27506 9.03994ZM5.54225 12.1093C5.69431 12.0444 5.83339 11.9506 5.95069 11.8333L4.89003 10.7727C4.90863 10.7541 4.92988 10.7398 4.95355 10.7297L5.54225 12.1093Z", - fill: "currentColor" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.5 4.5L9.5 2.5", - stroke: "currentColor", - strokeWidth: 1.4026, - strokeLinecap: "round", - strokeLinejoin: "round" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M5.5 10.5L3.5 8.5", - stroke: "currentColor", - strokeWidth: 1.4026, - strokeLinecap: "round", - strokeLinejoin: "round" - })); - const SvgPlay = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 16 18", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.32226e-07 1.6609C7.22332e-08 0.907329 0.801887 0.424528 1.46789 0.777117L15.3306 8.11621C16.0401 8.49182 16.0401 9.50818 15.3306 9.88379L1.46789 17.2229C0.801886 17.5755 1.36076e-06 17.0927 1.30077e-06 16.3391L1.32226e-07 1.6609Z", - fill: "currentColor" - })); - const SvgPlus = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 10 16", - fill: "currentColor", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M4.25 9.25V13.5H5.75V9.25L10 9.25V7.75L5.75 7.75V3.5H4.25V7.75L0 7.75V9.25L4.25 9.25Z" - })); - const SvgPrettify = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - width: 25, - height: 25, - viewBox: "0 0 25 25", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M10.2852 24.0745L13.7139 18.0742", - stroke: "currentColor", - strokeWidth: 1.5625 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M14.5742 24.0749L17.1457 19.7891", - stroke: "currentColor", - strokeWidth: 1.5625 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M19.4868 24.0735L20.7229 21.7523C21.3259 20.6143 21.5457 19.3122 21.3496 18.0394C21.1535 16.7666 20.5519 15.591 19.6342 14.6874L23.7984 6.87853C24.0123 6.47728 24.0581 6.00748 23.9256 5.57249C23.7932 5.1375 23.4933 4.77294 23.0921 4.55901C22.6908 4.34509 22.221 4.29932 21.7861 4.43178C21.3511 4.56424 20.9865 4.86408 20.7726 5.26533L16.6084 13.0742C15.3474 12.8142 14.0362 12.9683 12.8699 13.5135C11.7035 14.0586 10.7443 14.9658 10.135 16.1L6 24.0735", - stroke: "currentColor", - strokeWidth: 1.5625 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4 15L5 13L7 12L5 11L4 9L3 11L1 12L3 13L4 15Z", - stroke: "currentColor", - strokeWidth: 1.5625, - strokeLinejoin: "round" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.5 8L12.6662 5.6662L15 4.5L12.6662 3.3338L11.5 1L10.3338 3.3338L8 4.5L10.3338 5.6662L11.5 8Z", - stroke: "currentColor", - strokeWidth: 1.5625, - strokeLinejoin: "round" - })); - const SvgReload = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 16 16", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M4.75 9.25H1.25V12.75", - stroke: "currentColor", - strokeWidth: 1, - strokeLinecap: "square" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M11.25 6.75H14.75V3.25", - stroke: "currentColor", - strokeWidth: 1, - strokeLinecap: "square" - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M14.1036 6.65539C13.8 5.27698 13.0387 4.04193 11.9437 3.15131C10.8487 2.26069 9.48447 1.76694 8.0731 1.75043C6.66173 1.73392 5.28633 2.19563 4.17079 3.0604C3.05526 3.92516 2.26529 5.14206 1.92947 6.513", - stroke: "currentColor", - strokeWidth: 1 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M1.89635 9.34461C2.20001 10.723 2.96131 11.9581 4.05631 12.8487C5.15131 13.7393 6.51553 14.2331 7.9269 14.2496C9.33827 14.2661 10.7137 13.8044 11.8292 12.9396C12.9447 12.0748 13.7347 10.8579 14.0705 9.487", - stroke: "currentColor", - strokeWidth: 1 - })); - const SvgRootType = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 11.8, - height: 11.8, - rx: 5.9, - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("path", { - d: "M4.25 7.5C4.25 6 5.75 5 6.5 6.5C7.25 8 8.75 7 8.75 5.5", - stroke: "currentColor", - strokeWidth: 1.2 - })); - const SvgSettings = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 21 20", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M9.29186 1.92702C9.06924 1.82745 8.87014 1.68202 8.70757 1.50024L7.86631 0.574931C7.62496 0.309957 7.30773 0.12592 6.95791 0.0479385C6.60809 -0.0300431 6.24274 0.00182978 5.91171 0.139208C5.58068 0.276585 5.3001 0.512774 5.10828 0.815537C4.91645 1.1183 4.82272 1.47288 4.83989 1.83089L4.90388 3.08019C4.91612 3.32348 4.87721 3.56662 4.78968 3.79394C4.70215 4.02126 4.56794 4.2277 4.39571 4.39994C4.22347 4.57219 4.01704 4.7064 3.78974 4.79394C3.56243 4.88147 3.3193 4.92038 3.07603 4.90814L1.8308 4.84414C1.47162 4.82563 1.11553 4.91881 0.811445 5.11086C0.507359 5.30292 0.270203 5.58443 0.132561 5.91671C-0.00508149 6.249 -0.0364554 6.61576 0.0427496 6.9666C0.121955 7.31744 0.307852 7.63514 0.5749 7.87606L1.50016 8.71204C1.68193 8.87461 1.82735 9.07373 1.92692 9.29636C2.02648 9.51898 2.07794 9.76012 2.07794 10.004C2.07794 10.2479 2.02648 10.489 1.92692 10.7116C1.82735 10.9343 1.68193 11.1334 1.50016 11.296L0.5749 12.1319C0.309856 12.3729 0.125575 12.6898 0.0471809 13.0393C-0.0312128 13.3888 9.64098e-05 13.754 0.13684 14.0851C0.273583 14.4162 0.509106 14.6971 0.811296 14.8894C1.11349 15.0817 1.46764 15.1762 1.82546 15.1599L3.0707 15.0959C3.31397 15.0836 3.5571 15.1225 3.7844 15.2101C4.01171 15.2976 4.21814 15.4318 4.39037 15.6041C4.56261 15.7763 4.69682 15.9827 4.78435 16.2101C4.87188 16.4374 4.91078 16.6805 4.89855 16.9238L4.83455 18.1691C4.81605 18.5283 4.90921 18.8844 5.10126 19.1885C5.2933 19.4926 5.5748 19.7298 5.90707 19.8674C6.23934 20.0051 6.60608 20.0365 6.9569 19.9572C7.30772 19.878 7.6254 19.6921 7.86631 19.4251L8.7129 18.4998C8.87547 18.318 9.07458 18.1725 9.29719 18.073C9.51981 17.9734 9.76093 17.9219 10.0048 17.9219C10.2487 17.9219 10.4898 17.9734 10.7124 18.073C10.935 18.1725 11.1341 18.318 11.2967 18.4998L12.1326 19.4251C12.3735 19.6921 12.6912 19.878 13.042 19.9572C13.3929 20.0365 13.7596 20.0051 14.0919 19.8674C14.4241 19.7298 14.7056 19.4926 14.8977 19.1885C15.0897 18.8844 15.1829 18.5283 15.1644 18.1691L15.1004 16.9238C15.0882 16.6805 15.1271 16.4374 15.2146 16.2101C15.3021 15.9827 15.4363 15.7763 15.6086 15.6041C15.7808 15.4318 15.9872 15.2976 16.2145 15.2101C16.4418 15.1225 16.685 15.0836 16.9282 15.0959L18.1735 15.1599C18.5326 15.1784 18.8887 15.0852 19.1928 14.8931C19.4969 14.7011 19.7341 14.4196 19.8717 14.0873C20.0093 13.755 20.0407 13.3882 19.9615 13.0374C19.8823 12.6866 19.6964 12.3689 19.4294 12.1279L18.5041 11.292C18.3223 11.1294 18.1769 10.9303 18.0774 10.7076C17.9778 10.485 17.9263 10.2439 17.9263 10C17.9263 9.75612 17.9778 9.51499 18.0774 9.29236C18.1769 9.06973 18.3223 8.87062 18.5041 8.70804L19.4294 7.87206C19.6964 7.63114 19.8823 7.31344 19.9615 6.9626C20.0407 6.61176 20.0093 6.245 19.8717 5.91271C19.7341 5.58043 19.4969 5.29892 19.1928 5.10686C18.8887 4.91481 18.5326 4.82163 18.1735 4.84014L16.9282 4.90414C16.685 4.91638 16.4418 4.87747 16.2145 4.78994C15.9872 4.7024 15.7808 4.56818 15.6086 4.39594C15.4363 4.2237 15.3021 4.01726 15.2146 3.78994C15.1271 3.56262 15.0882 3.31948 15.1004 3.07619L15.1644 1.83089C15.1829 1.4717 15.0897 1.11559 14.8977 0.811487C14.7056 0.507385 14.4241 0.270217 14.0919 0.132568C13.7596 -0.00508182 13.3929 -0.0364573 13.042 0.0427519C12.6912 0.121961 12.3735 0.307869 12.1326 0.574931L11.2914 1.50024C11.1288 1.68202 10.9297 1.82745 10.7071 1.92702C10.4845 2.02659 10.2433 2.07805 9.99947 2.07805C9.7556 2.07805 9.51448 2.02659 9.29186 1.92702ZM14.3745 10C14.3745 12.4162 12.4159 14.375 9.99977 14.375C7.58365 14.375 5.625 12.4162 5.625 10C5.625 7.58375 7.58365 5.625 9.99977 5.625C12.4159 5.625 14.3745 7.58375 14.3745 10Z", - fill: "currentColor" - })); - const SvgStarFilled = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", - fill: "currentColor", - stroke: "currentColor" - })); - const SvgStar = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 14 14", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", - stroke: "currentColor", - strokeWidth: 1.5 - })); - const SvgStop = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 16 16", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - width: 16, - height: 16, - rx: 2, - fill: "currentColor" - })); - const SvgTrash = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - width: "1em", - height: "5em", - xmlns: "http://www.w3.org/2000/svg", - fillRule: "evenodd", - "aria-hidden": "true", - viewBox: "0 0 23 23", - style: { - height: "1.5em" - }, - clipRule: "evenodd", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("path", { - d: "M19 24h-14c-1.104 0-2-.896-2-2v-17h-1v-2h6v-1.5c0-.827.673-1.5 1.5-1.5h5c.825 0 1.5.671 1.5 1.5v1.5h6v2h-1v17c0 1.104-.896 2-2 2zm0-19h-14v16.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-16.5zm-7 7.586l3.293-3.293 1.414 1.414-3.293 3.293 3.293 3.293-1.414 1.414-3.293-3.293-3.293 3.293-1.414-1.414 3.293-3.293-3.293-3.293 1.414-1.414 3.293 3.293zm2-10.586h-4v1h4v-1z", - fill: "currentColor", - strokeWidth: 0.25, - stroke: "currentColor" - })); - const SvgType = ({ - title, - titleId, - ...props - }) => /* @__PURE__ */React__namespace.createElement("svg", { - height: "1em", - viewBox: "0 0 13 13", - fill: "none", - xmlns: "http://www.w3.org/2000/svg", - "aria-labelledby": titleId, - ...props - }, title ? /* @__PURE__ */React__namespace.createElement("title", { - id: titleId - }, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { - x: 0.6, - y: 0.6, - width: 11.8, - height: 11.8, - rx: 5.9, - stroke: "currentColor", - strokeWidth: 1.2 - }), /* @__PURE__ */React__namespace.createElement("rect", { - x: 5.5, - y: 5.5, - width: 2, - height: 2, - rx: 1, - fill: "currentColor" - })); - const ArgumentIcon = generateIcon(SvgArgument); - const ChevronDownIcon = generateIcon(SvgChevronDown); - const ChevronLeftIcon = generateIcon(SvgChevronLeft); - const ChevronUpIcon = generateIcon(SvgChevronUp); - const CloseIcon = generateIcon(SvgClose); - const CopyIcon = generateIcon(SvgCopy); - const DeprecatedArgumentIcon = generateIcon(SvgDeprecatedArgument); - const DeprecatedEnumValueIcon = generateIcon(SvgDeprecatedEnumValue); - const DeprecatedFieldIcon = generateIcon(SvgDeprecatedField); - const DirectiveIcon = generateIcon(SvgDirective); - const DocsFilledIcon = generateIcon(SvgDocsFilled); - const DocsIcon = generateIcon(SvgDocs); - const EnumValueIcon = generateIcon(SvgEnumValue); - const FieldIcon = generateIcon(SvgField); - const HistoryIcon = generateIcon(SvgHistory); - const ImplementsIcon = generateIcon(SvgImplements); - const KeyboardShortcutIcon = generateIcon(SvgKeyboardShortcut); - const MagnifyingGlassIcon = generateIcon(SvgMagnifyingGlass); - const MergeIcon = generateIcon(SvgMerge); - const PenIcon = generateIcon(SvgPen); - const PlayIcon = generateIcon(SvgPlay); - const PlusIcon = generateIcon(SvgPlus); - const PrettifyIcon = generateIcon(SvgPrettify); - const ReloadIcon = generateIcon(SvgReload); - const RootTypeIcon = generateIcon(SvgRootType); - const SettingsIcon = generateIcon(SvgSettings); - const StarFilledIcon = generateIcon(SvgStarFilled); - const StarIcon = generateIcon(SvgStar); - const StopIcon = generateIcon(SvgStop); - const TrashIcon = generateIcon(SvgTrash); - const TypeIcon = generateIcon(SvgType); - function generateIcon(RawComponent) { - const title = RawComponent.name.replace("Svg", "").replaceAll(/([A-Z])/g, " $1").trimStart().toLowerCase() + " icon"; - function IconComponent(props) { - return /* @__PURE__ */jsxRuntime.jsx(RawComponent, { - title, - ...props - }); - } - IconComponent.displayName = RawComponent.name; - return IconComponent; - } - const UnStyledButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-un-styled", props.className) - })); - UnStyledButton.displayName = "UnStyledButton"; - const Button$1 = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-button", { - success: "graphiql-button-success", - error: "graphiql-button-error" - }[props.state], props.className) - })); - Button$1.displayName = "Button"; - const ButtonGroup = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx("graphiql-button-group", props.className) - })); - ButtonGroup.displayName = "ButtonGroup"; - const createComponentGroup = (root, children) => Object.entries(children).reduce((r, [key, value]) => { - r[key] = value; - return r; - }, root); - const DialogClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(D__namespace.Close, { - asChild: true, - children: /* @__PURE__ */jsxRuntime.jsxs(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-dialog-close", props.className), - children: [/* @__PURE__ */jsxRuntime.jsx(reactVisuallyHidden.Root, { - children: "Close dialog" - }), /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {})] - }) - })); - DialogClose.displayName = "Dialog.Close"; - function DialogRoot({ - children, - ...props - }) { - return /* @__PURE__ */jsxRuntime.jsx(D__namespace.Root, { - ...props, - children: /* @__PURE__ */jsxRuntime.jsxs(D__namespace.Portal, { - children: [/* @__PURE__ */jsxRuntime.jsx(D__namespace.Overlay, { - className: "graphiql-dialog-overlay" - }), /* @__PURE__ */jsxRuntime.jsx(D__namespace.Content, { - className: "graphiql-dialog", - children - })] - }) - }); - } - const Dialog = createComponentGroup(DialogRoot, { - Close: DialogClose, - Title: D__namespace.Title, - Trigger: D__namespace.Trigger, - Description: D__namespace.Description - }); - const Button = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Trigger, { - asChild: true, - children: /* @__PURE__ */jsxRuntime.jsx("button", { - ...props, - ref, - className: clsx.clsx("graphiql-un-styled", props.className) - }) - })); - Button.displayName = "DropdownMenuButton"; - function Content({ - children, - align = "start", - sideOffset = 5, - className, - ...props - }) { - return /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Portal, { - children: /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Content, { - align, - sideOffset, - className: clsx.clsx("graphiql-dropdown-content", className), - ...props, - children - }) - }); - } - const Item = ({ - className, - children, - ...props - }) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Item, { - className: clsx.clsx("graphiql-dropdown-item", className), - ...props, - children - }); - const DropdownMenu = createComponentGroup(reactDropdownMenu.Root, { - Button, - Item, - Content - }); - const markdown = new MarkdownIt({ - breaks: true, - linkify: true - }); - const MarkdownContent = React.forwardRef(({ - children, - onlyShowFirstChild, - type, - ...props - }, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx(`graphiql-markdown-${type}`, onlyShowFirstChild && "graphiql-markdown-preview", props.className), - dangerouslySetInnerHTML: { - __html: markdown.render(children) - } - })); - MarkdownContent.displayName = "MarkdownContent"; - const Spinner = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { - ...props, - ref, - className: clsx.clsx("graphiql-spinner", props.className) - })); - Spinner.displayName = "Spinner"; - function TooltipRoot({ - children, - align = "start", - side = "bottom", - sideOffset = 5, - label - }) { - return /* @__PURE__ */jsxRuntime.jsxs(T__namespace.Root, { - children: [/* @__PURE__ */jsxRuntime.jsx(T__namespace.Trigger, { - asChild: true, - children - }), /* @__PURE__ */jsxRuntime.jsx(T__namespace.Portal, { - children: /* @__PURE__ */jsxRuntime.jsx(T__namespace.Content, { - className: "graphiql-tooltip", - align, - side, - sideOffset, - children: label - }) - })] - }); - } - const Tooltip = createComponentGroup(TooltipRoot, { - Provider: T__namespace.Provider - }); - const TabRoot = React.forwardRef(({ - isActive, - value, - children, - className, - ...props - }, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Item, { - ...props, - ref, - value, - "aria-selected": isActive ? "true" : void 0, - role: "tab", - className: clsx.clsx("graphiql-tab", isActive && "graphiql-tab-active", className), - children - })); - TabRoot.displayName = "Tab"; - const TabButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-tab-button", props.className), - children: props.children - })); - TabButton.displayName = "Tab.Button"; - const TabClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Close Tab", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - "aria-label": "Close Tab", - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-tab-close", props.className), - children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) - }) - })); - TabClose.displayName = "Tab.Close"; - const Tab = createComponentGroup(TabRoot, { - Button: TabButton, - Close: TabClose - }); - const Tabs = React.forwardRef(({ - values, - onReorder, - children, - className, - ...props - }, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Group, { - ...props, - ref, - values, - onReorder, - axis: "x", - role: "tablist", - className: clsx.clsx("graphiql-tabs", className), - children - })); - Tabs.displayName = "Tabs"; - const HistoryContext = createNullableContext("HistoryContext"); - function HistoryContextProvider(props) { - var _a; - const storage = useStorageContext(); - const historyStore = React.useRef(new toolkit.HistoryStore( - // Fall back to a noop storage when the StorageContext is empty - storage || new toolkit.StorageAPI(null), props.maxHistoryLength || DEFAULT_HISTORY_LENGTH)); - const [items, setItems] = React.useState(((_a = historyStore.current) == null ? void 0 : _a.queries) || []); - const addToHistory = React.useCallback(operation => { - var _a2; - (_a2 = historyStore.current) == null ? void 0 : _a2.updateHistory(operation); - setItems(historyStore.current.queries); - }, []); - const editLabel = React.useCallback((operation, index) => { - historyStore.current.editLabel(operation, index); - setItems(historyStore.current.queries); - }, []); - const toggleFavorite = React.useCallback(operation => { - historyStore.current.toggleFavorite(operation); - setItems(historyStore.current.queries); - }, []); - const setActive = React.useCallback(item => { - return item; - }, []); - const deleteFromHistory = React.useCallback((item, clearFavorites = false) => { - historyStore.current.deleteHistory(item, clearFavorites); - setItems(historyStore.current.queries); - }, []); - const value = React.useMemo(() => ({ - addToHistory, - editLabel, - items, - toggleFavorite, - setActive, - deleteFromHistory - }), [addToHistory, editLabel, items, toggleFavorite, setActive, deleteFromHistory]); - return /* @__PURE__ */jsxRuntime.jsx(HistoryContext.Provider, { - value, - children: props.children - }); - } - const useHistoryContext = createContextHook(HistoryContext); - const DEFAULT_HISTORY_LENGTH = 20; - function History() { - const { - items: all, - deleteFromHistory - } = useHistoryContext({ - nonNull: true - }); - let items = all.slice().map((item, i) => ({ - ...item, - index: i - })).reverse(); - const favorites = items.filter(item => item.favorite); - if (favorites.length) { - items = items.filter(item => !item.favorite); - } - const [clearStatus, setClearStatus] = React.useState(null); - React.useEffect(() => { - if (clearStatus) { - setTimeout(() => { - setClearStatus(null); - }, 2e3); - } - }, [clearStatus]); - const handleClearStatus = React.useCallback(() => { - try { - for (const item of items) { - deleteFromHistory(item, true); + var DisplayUpdate = function (cm, viewport, force) { + var display = cm.display; + this.viewport = viewport; + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + }; + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) { + this.events.push(arguments); + } + }; + DisplayUpdate.prototype.finish = function () { + for (var i2 = 0; i2 < this.events.length; i2++) { + signal.apply(null, this.events[i2]); + } + }; + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + function selectionSnapshot(cm) { + if (cm.hasFocus()) { + return null; + } + var active = activeElt(); + if (!active || !contains(cm.display.lineDiv, active)) { + return null; + } + var result = { + activeElt: active + }; + if (window.getSelection) { + var sel = window.getSelection(); + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode; + result.anchorOffset = sel.anchorOffset; + result.focusNode = sel.focusNode; + result.focusOffset = sel.focusOffset; + } } - setClearStatus("success"); - } catch { - setClearStatus("error"); + return result; } - }, [deleteFromHistory, items]); - return /* @__PURE__ */jsxRuntime.jsxs("section", { - "aria-label": "History", - className: "graphiql-history", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-history-header", - children: ["History", (clearStatus || items.length > 0) && /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - state: clearStatus || void 0, - disabled: !items.length, - onClick: handleClearStatus, - children: { - success: "Cleared", - error: "Failed to Clear" - }[clearStatus] || "Clear" - })] - }), Boolean(favorites.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { - className: "graphiql-history-items", - children: favorites.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { - item - }, item.index)) - }), Boolean(favorites.length) && Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-history-item-spacer" - }), Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { - className: "graphiql-history-items", - children: items.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { - item - }, item.index)) - })] - }); - } - function HistoryItem(props) { - const { - editLabel, - toggleFavorite, - deleteFromHistory, - setActive - } = useHistoryContext({ - nonNull: true, - caller: HistoryItem - }); - const { - headerEditor, - queryEditor, - variableEditor - } = useEditorContext({ - nonNull: true, - caller: HistoryItem - }); - const inputRef = React.useRef(null); - const buttonRef = React.useRef(null); - const [isEditable, setIsEditable] = React.useState(false); - React.useEffect(() => { - var _a; - if (isEditable) { - (_a = inputRef.current) == null ? void 0 : _a.focus(); + function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { + return; + } + snapshot.activeElt.focus(); + if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + var sel = window.getSelection(), + range2 = document.createRange(); + range2.setEnd(snapshot.anchorNode, snapshot.anchorOffset); + range2.collapse(false); + sel.removeAllRanges(); + sel.addRange(range2); + sel.extend(snapshot.focusNode, snapshot.focusOffset); + } + } + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, + doc = cm.doc; + if (update.editorIsHidden) { + resetView(cm); + return false; + } + if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { + return false; + } + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) { + from = Math.max(doc.first, display.viewFrom); + } + if (display.viewTo > to && display.viewTo - to < 20) { + to = Math.min(end, display.viewTo); + } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + cm.display.mover.style.top = display.viewOffset + "px"; + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { + return false; + } + var selSnapshot = selectionSnapshot(cm); + if (toUpdate > 4) { + display.lineDiv.style.display = "none"; + } + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) { + display.lineDiv.style.display = ""; + } + display.renderedView = display.view; + restoreSelection(selSnapshot); + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + display.updateLineNumbers = null; + return true; } - }, [isEditable]); - const displayName = props.item.label || props.item.operationName || formatQuery(props.item.query); - const handleSave = React.useCallback(() => { - var _a; - setIsEditable(false); - const { - index, - ...item - } = props.item; - editLabel({ - ...item, - label: (_a = inputRef.current) == null ? void 0 : _a.value - }, index); - }, [editLabel, props.item]); - const handleClose = React.useCallback(() => { - setIsEditable(false); - }, []); - const handleEditLabel = React.useCallback(e => { - e.stopPropagation(); - setIsEditable(true); - }, []); - const handleHistoryItemClick = React.useCallback(() => { - const { - query, - variables, - headers - } = props.item; - queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); - variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); - headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); - setActive(props.item); - }, [headerEditor, props.item, queryEditor, setActive, variableEditor]); - const handleDeleteItemFromHistory = React.useCallback(e => { - e.stopPropagation(); - deleteFromHistory(props.item); - }, [props.item, deleteFromHistory]); - const handleToggleFavorite = React.useCallback(e => { - e.stopPropagation(); - toggleFavorite(props.item); - }, [props.item, toggleFavorite]); - return /* @__PURE__ */jsxRuntime.jsx("li", { - className: clsx.clsx("graphiql-history-item", isEditable && "editable"), - children: isEditable ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx("input", { - type: "text", - defaultValue: props.item.label, - ref: inputRef, - onKeyDown: e => { - if (e.key === "Esc") { - setIsEditable(false); - } else if (e.key === "Enter") { - setIsEditable(false); - editLabel({ - ...props.item, - label: e.currentTarget.value - }); + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + if (viewport && viewport.top != null) { + viewport = { + top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top) + }; } - }, - placeholder: "Type a label" - }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - ref: buttonRef, - onClick: handleSave, - children: "Save" - }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - ref: buttonRef, - onClick: handleClose, - children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) - })] - }) : /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Set active", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-label", - onClick: handleHistoryItemClick, - "aria-label": "Set active", - children: displayName - }) - }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Edit label", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleEditLabel, - "aria-label": "Edit label", - children: /* @__PURE__ */jsxRuntime.jsx(PenIcon, { - "aria-hidden": "true" - }) - }) - }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: props.item.favorite ? "Remove favorite" : "Add favorite", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleToggleFavorite, - "aria-label": props.item.favorite ? "Remove favorite" : "Add favorite", - children: props.item.favorite ? /* @__PURE__ */jsxRuntime.jsx(StarFilledIcon, { - "aria-hidden": "true" - }) : /* @__PURE__ */jsxRuntime.jsx(StarIcon, { - "aria-hidden": "true" - }) - }) - }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label: "Delete from history", - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - type: "button", - className: "graphiql-history-item-action", - onClick: handleDeleteItemFromHistory, - "aria-label": "Delete from history", - children: /* @__PURE__ */jsxRuntime.jsx(TrashIcon, { - "aria-hidden": "true" - }) - }) - })] - }) - }); - } - function formatQuery(query) { - return query == null ? void 0 : query.split("\n").map(line => line.replace(/#(.*)/, "")).join(" ").replaceAll("{", " { ").replaceAll("}", " } ").replaceAll(/[\s]{2,}/g, " "); - } - const ExecutionContext = createNullableContext("ExecutionContext"); - function ExecutionContextProvider({ - fetcher, - getDefaultFieldNames, - children, - operationName - }) { - if (!fetcher) { - throw new TypeError("The `ExecutionContextProvider` component requires a `fetcher` function to be passed as prop."); - } - const { - externalFragments, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - updateActiveTabValues - } = useEditorContext({ - nonNull: true, - caller: ExecutionContextProvider - }); - const history = useHistoryContext(); - const autoCompleteLeafs = useAutoCompleteLeafs({ - getDefaultFieldNames, - caller: ExecutionContextProvider - }); - const [isFetching, setIsFetching] = React.useState(false); - const [subscription, setSubscription] = React.useState(null); - const queryIdRef = React.useRef(0); - const stop = React.useCallback(() => { - subscription == null ? void 0 : subscription.unsubscribe(); - setIsFetching(false); - setSubscription(null); - }, [subscription]); - const run = React.useCallback(async () => { - var _ref; - if (!queryEditor || !responseEditor) { - return; + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { + break; + } + } else if (first) { + update.visible = visibleLines(cm.display, cm.doc, viewport); + } + if (!updateDisplayIfNeeded(cm, update)) { + break; + } + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.force = false; + } + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; + cm.display.reportedViewTo = cm.display.viewTo; + } + } + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, + lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, + cur = container.firstChild; + function rm(node2) { + var next = node2.nextSibling; + if (webkit && mac && cm.display.currentWheelTarget == node2) { + node2.style.display = "none"; + } else { + node2.parentNode.removeChild(node2); + } + return next; + } + var view = display.view, + lineN = display.viewFrom; + for (var i2 = 0; i2 < view.length; i2++) { + var lineView = view[i2]; + if (lineView.hidden) ;else if (!lineView.node || lineView.node.parentNode != container) { + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { + while (cur != lineView.node) { + cur = rm(cur); + } + var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { + updateNumber = false; + } + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) { + cur = rm(cur); + } } - if (subscription) { - stop(); - return; + function updateGutterSpace(display) { + var width = display.gutters.offsetWidth; + display.sizer.style.marginLeft = width + "px"; + signalLater(display, "gutterChanged", display); } - const setResponse = value2 => { - responseEditor.setValue(value2); - updateActiveTabValues({ - response: value2 - }); - }; - queryIdRef.current += 1; - const queryId = queryIdRef.current; - let query = autoCompleteLeafs() || queryEditor.getValue(); - const variablesString = variableEditor == null ? void 0 : variableEditor.getValue(); - let variables; - try { - variables = tryParseJsonObject({ - json: variablesString, - errorMessageParse: "Variables are invalid JSON", - errorMessageType: "Variables are not a JSON object." - }); - } catch (error) { - setResponse(error instanceof Error ? error.message : `${error}`); - return; + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = measure.docHeight + cm.display.barHeight + scrollGap(cm) + "px"; } - const headersString = headerEditor == null ? void 0 : headerEditor.getValue(); - let headers; - try { - headers = tryParseJsonObject({ - json: headersString, - errorMessageParse: "Headers are invalid JSON", - errorMessageType: "Headers are not a JSON object." - }); - } catch (error) { - setResponse(error instanceof Error ? error.message : `${error}`); - return; + function alignHorizontally(cm) { + var display = cm.display, + view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { + return; + } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, + left = comp + "px"; + for (var i2 = 0; i2 < view.length; i2++) { + if (!view[i2].hidden) { + if (cm.options.fixedGutter) { + if (view[i2].gutter) { + view[i2].gutter.style.left = left; + } + if (view[i2].gutterBackground) { + view[i2].gutterBackground.style.left = left; + } + } + var align = view[i2].alignable; + if (align) { + for (var j = 0; j < align.length; j++) { + align[j].style.left = left; + } + } + } + } + if (cm.options.fixedGutter) { + display.gutters.style.left = comp + gutterW + "px"; + } } - if (externalFragments) { - const fragmentDependencies = queryEditor.documentAST ? graphqlLanguageService.getFragmentDependenciesForAST(queryEditor.documentAST, externalFragments) : []; - if (fragmentDependencies.length > 0) { - query += "\n" + fragmentDependencies.map(node => graphql.print(node)).join("\n"); + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { + return false; + } + var doc = cm.doc, + last = lineNumberFor(cm.options, doc.first + doc.size - 1), + display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, + padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm.display); + return true; } + return false; } - setResponse(""); - setIsFetching(true); - const opName = (_ref = operationName !== null && operationName !== void 0 ? operationName : queryEditor.operationName) !== null && _ref !== void 0 ? _ref : void 0; - history == null ? void 0 : history.addToHistory({ - query, - variables: variablesString, - headers: headersString, - operationName: opName - }); - try { - var _headers, _queryEditor$document; - const fullResponse = {}; - const handleResponse = result => { - if (queryId !== queryIdRef.current) { - return; - } - let maybeMultipart = Array.isArray(result) ? result : false; - if (!maybeMultipart && typeof result === "object" && result !== null && "hasNext" in result) { - maybeMultipart = [result]; - } - if (maybeMultipart) { - for (const part of maybeMultipart) { - mergeIncrementalResult(fullResponse, part); + function getGutters(gutters, lineNumbers) { + var result = [], + sawLineNumbers = false; + for (var i2 = 0; i2 < gutters.length; i2++) { + var name = gutters[i2], + style = null; + if (typeof name != "string") { + style = name.style; + name = name.className; + } + if (name == "CodeMirror-linenumbers") { + if (!lineNumbers) { + continue; + } else { + sawLineNumbers = true; } - setIsFetching(false); - setResponse(toolkit.formatResult(fullResponse)); - } else { - const response = toolkit.formatResult(result); - setIsFetching(false); - setResponse(response); } + result.push({ + className: name, + style + }); + } + if (lineNumbers && !sawLineNumbers) { + result.push({ + className: "CodeMirror-linenumbers", + style: null + }); + } + return result; + } + function renderGutters(display) { + var gutters = display.gutters, + specs = display.gutterSpecs; + removeChildren(gutters); + display.lineGutter = null; + for (var i2 = 0; i2 < specs.length; ++i2) { + var ref = specs[i2]; + var className = ref.className; + var style = ref.style; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); + if (style) { + gElt.style.cssText = style; + } + if (className == "CodeMirror-linenumbers") { + display.lineGutter = gElt; + gElt.style.width = (display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = specs.length ? "" : "none"; + updateGutterSpace(display); + } + function updateGutters(cm) { + renderGutters(cm.display); + regChange(cm); + alignHorizontally(cm); + } + function Display(place, doc, input, options) { + var d = this; + this.input = input; + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + d.lineDiv = eltP("div", null, "CodeMirror-code"); + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + d.measure = elt("div", null, "CodeMirror-measure"); + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); + d.mover = elt("div", [lines], null, "position: relative"); + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + d.wrapper.setAttribute("translate", "no"); + if (ie && ie_version < 8) { + d.gutters.style.zIndex = -1; + d.scroller.style.paddingRight = 0; + } + if (!webkit && !(gecko && mobile)) { + d.scroller.draggable = true; + } + if (place) { + if (place.appendChild) { + place.appendChild(d.wrapper); + } else { + place(d.wrapper); + } + } + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + d.view = []; + d.renderedView = null; + d.externalMeasured = null; + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + d.alignWidgets = false; + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + d.shift = false; + d.selForContextMenu = null; + d.activeTouch = null; + d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); + renderGutters(d); + input.init(d); + } + var wheelSamples = 0, + wheelPixelsPerUnit = null; + if (ie) { + wheelPixelsPerUnit = -0.53; + } else if (gecko) { + wheelPixelsPerUnit = 15; + } else if (chrome) { + wheelPixelsPerUnit = -0.7; + } else if (safari) { + wheelPixelsPerUnit = -1 / 3; + } + function wheelEventDelta(e) { + var dx = e.wheelDeltaX, + dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { + dx = e.detail; + } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { + dy = e.detail; + } else if (dy == null) { + dy = e.wheelDelta; + } + return { + x: dx, + y: dy }; - const fetch2 = fetcher({ - query, - variables, - operationName: opName - }, { - headers: (_headers = headers) !== null && _headers !== void 0 ? _headers : void 0, - documentAST: (_queryEditor$document = queryEditor.documentAST) !== null && _queryEditor$document !== void 0 ? _queryEditor$document : void 0 - }); - const value2 = await Promise.resolve(fetch2); - if (toolkit.isObservable(value2)) { - setSubscription(value2.subscribe({ - next(result) { - handleResponse(result); - }, - error(error) { - setIsFetching(false); - if (error) { - setResponse(toolkit.formatError(error)); + } + function wheelEventPixels(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + } + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), + dx = delta.x, + dy = delta.y; + var pixelsPerUnit = wheelPixelsPerUnit; + if (e.deltaMode === 0) { + dx = e.deltaX; + dy = e.deltaY; + pixelsPerUnit = 1; + } + var display = cm.display, + scroll = display.scroller; + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) { + return; + } + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i2 = 0; i2 < view.length; i2++) { + if (view[i2].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; } - setSubscription(null); - }, - complete() { - setIsFetching(false); - setSubscription(null); - } - })); - } else if (toolkit.isAsyncIterable(value2)) { - setSubscription({ - unsubscribe: () => { - var _a, _b; - return (_b = (_a = value2[Symbol.asyncIterator]()).return) == null ? void 0 : _b.call(_a); } + } + } + if (dx && !gecko && !presto && pixelsPerUnit != null) { + if (dy && canScrollY) { + updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); + } + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); + if (!dy || dy && canScrollY) { + e_preventDefault(e); + } + display.wheelStartX = null; + return; + } + if (dy && pixelsPerUnit != null) { + var pixels = dy * pixelsPerUnit; + var top = cm.doc.scrollTop, + bot = top + display.wrapper.clientHeight; + if (pixels < 0) { + top = Math.max(0, top + pixels - 50); + } else { + bot = Math.min(cm.doc.height, bot + pixels + 50); + } + updateDisplaySimple(cm, { + top, + bottom: bot }); - for await (const result of value2) { - handleResponse(result); + } + if (wheelSamples < 20 && e.deltaMode !== 0) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; + display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; + display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) { + return; + } + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = movedY && display.wheelDY && movedY / display.wheelDY || movedX && display.wheelDX && movedX / display.wheelDX; + display.wheelStartX = display.wheelStartY = null; + if (!sample) { + return; + } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; + display.wheelDY += dy; } - setIsFetching(false); - setSubscription(null); - } else { - handleResponse(value2); } - } catch (error) { - setIsFetching(false); - setResponse(toolkit.formatError(error)); - setSubscription(null); } - }, [autoCompleteLeafs, externalFragments, fetcher, headerEditor, history, operationName, queryEditor, responseEditor, stop, subscription, updateActiveTabValues, variableEditor]); - const isSubscribed = Boolean(subscription); - const value = React.useMemo(() => ({ - isFetching, - isSubscribed, - operationName: operationName !== null && operationName !== void 0 ? operationName : null, - run, - stop - }), [isFetching, isSubscribed, operationName, run, stop]); - return /* @__PURE__ */jsxRuntime.jsx(ExecutionContext.Provider, { - value, - children - }); - } - const useExecutionContext = createContextHook(ExecutionContext); - function tryParseJsonObject({ - json, - errorMessageParse, - errorMessageType - }) { - let parsed; - try { - parsed = json && json.trim() !== "" ? JSON.parse(json) : void 0; - } catch (error) { - throw new Error(`${errorMessageParse}: ${error instanceof Error ? error.message : error}.`); - } - const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed); - if (parsed !== void 0 && !isObject) { - throw new Error(errorMessageType); - } - return parsed; - } - function mergeIncrementalResult(executionResult, incrementalResult) { - var _incrementalResult$pa; - const path = ["data", ...((_incrementalResult$pa = incrementalResult.path) !== null && _incrementalResult$pa !== void 0 ? _incrementalResult$pa : [])]; - if (incrementalResult.items) { - for (const item of incrementalResult.items) { - setValue(executionResult, path.join("."), item); - path[path.length - 1]++; + var Selection = function (ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + }; + Selection.prototype.primary = function () { + return this.ranges[this.primIndex]; + }; + Selection.prototype.equals = function (other) { + if (other == this) { + return true; + } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { + return false; + } + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var here = this.ranges[i2], + there = other.ranges[i2]; + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { + return false; + } + } + return true; + }; + Selection.prototype.deepCopy = function () { + var out = []; + for (var i2 = 0; i2 < this.ranges.length; i2++) { + out[i2] = new Range(copyPos(this.ranges[i2].anchor), copyPos(this.ranges[i2].head)); + } + return new Selection(out, this.primIndex); + }; + Selection.prototype.somethingSelected = function () { + for (var i2 = 0; i2 < this.ranges.length; i2++) { + if (!this.ranges[i2].empty()) { + return true; + } + } + return false; + }; + Selection.prototype.contains = function (pos, end) { + if (!end) { + end = pos; + } + for (var i2 = 0; i2 < this.ranges.length; i2++) { + var range2 = this.ranges[i2]; + if (cmp(end, range2.from()) >= 0 && cmp(pos, range2.to()) <= 0) { + return i2; + } + } + return -1; + }; + var Range = function (anchor, head) { + this.anchor = anchor; + this.head = head; + }; + Range.prototype.from = function () { + return minPos(this.anchor, this.head); + }; + Range.prototype.to = function () { + return maxPos(this.anchor, this.head); + }; + Range.prototype.empty = function () { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + }; + function normalizeSelection(cm, ranges, primIndex) { + var mayTouch = cm && cm.options.selectionsMayTouch; + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { + return cmp(a.from(), b.from()); + }); + primIndex = indexOf(ranges, prim); + for (var i2 = 1; i2 < ranges.length; i2++) { + var cur = ranges[i2], + prev = ranges[i2 - 1]; + var diff = cmp(prev.to(), cur.from()); + if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { + var from = minPos(prev.from(), cur.from()), + to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i2 <= primIndex) { + --primIndex; + } + ranges.splice(--i2, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); } - } - if (incrementalResult.data) { - setValue(executionResult, path.join("."), incrementalResult.data, { - merge: true - }); - } - if (incrementalResult.errors) { - executionResult.errors || (executionResult.errors = []); - executionResult.errors.push(...incrementalResult.errors); - } - if (incrementalResult.extensions) { - setValue(executionResult, "extensions", incrementalResult.extensions, { - merge: true - }); - } - if (incrementalResult.incremental) { - for (const incrementalSubResult of incrementalResult.incremental) { - mergeIncrementalResult(executionResult, incrementalSubResult); + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); } - } - } - const DEFAULT_EDITOR_THEME = "graphiql"; - const DEFAULT_KEY_MAP = "sublime"; - let isMacOs = false; - if (typeof window === "object") { - isMacOs = window.navigator.platform.toLowerCase().indexOf("mac") === 0; - } - const commonKeys = { - // Persistent search box in Query Editor - [isMacOs ? "Cmd-F" : "Ctrl-F"]: "findPersistent", - "Cmd-G": "findPersistent", - "Ctrl-G": "findPersistent", - // Editor improvements - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight" - }; - async function importCodeMirror(addons, options) { - const CodeMirror = await Promise.resolve().then(() => __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js")).then(n => n.codemirror).then(c => - // Depending on bundler and settings the dynamic import either returns a - // function (e.g. parcel) or an object containing a `default` property - typeof c === "function" ? c : c.default); - await Promise.all((options == null ? void 0 : options.useCommonAddons) === false ? addons : [Promise.resolve().then(() => __webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js")).then(n => n.showHint), Promise.resolve().then(() => __webpack_require__(/*! ./matchbrackets.cjs.js */ "../../graphiql-react/dist/matchbrackets.cjs.js")).then(n => n.matchbrackets), Promise.resolve().then(() => __webpack_require__(/*! ./closebrackets.cjs.js */ "../../graphiql-react/dist/closebrackets.cjs.js")).then(n => n.closebrackets), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs.js */ "../../graphiql-react/dist/lint.cjs.js")).then(n => n.lint), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), - // @ts-expect-error - Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), ...addons]); - return CodeMirror; - } - const printDefault = ast => { - if (!ast) { - return ""; - } - return graphql.print(ast); - }; - function DefaultValue({ - field - }) { - if (!("defaultValue" in field) || field.defaultValue === void 0) { - return null; - } - const ast = graphql.astFromValue(field.defaultValue, field.type); - if (!ast) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [" = ", /* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-default-value", - children: printDefault(ast) - })] - }); - } - const SchemaContext = createNullableContext("SchemaContext"); - function SchemaContextProvider(props) { - if (!props.fetcher) { - throw new TypeError("The `SchemaContextProvider` component requires a `fetcher` function to be passed as prop."); - } - const { - initialHeaders, - headerEditor - } = useEditorContext({ - nonNull: true, - caller: SchemaContextProvider - }); - const [schema, setSchema] = React.useState(); - const [isFetching, setIsFetching] = React.useState(false); - const [fetchError, setFetchError] = React.useState(null); - const counterRef = React.useRef(0); - React.useEffect(() => { - setSchema(graphql.isSchema(props.schema) || props.schema === null || props.schema === void 0 ? props.schema : void 0); - counterRef.current++; - }, [props.schema]); - const headersRef = React.useRef(initialHeaders); - React.useEffect(() => { - if (headerEditor) { - headersRef.current = headerEditor.getValue(); + function changeEnd(change) { + if (!change.text) { + return change.to; + } + return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); } - }); - const { - introspectionQuery, - introspectionQueryName, - introspectionQuerySansSubscriptions - } = useIntrospectionQuery({ - inputValueDeprecation: props.inputValueDeprecation, - introspectionQueryName: props.introspectionQueryName, - schemaDescription: props.schemaDescription - }); - const { - fetcher, - onSchemaChange, - dangerouslyAssumeSchemaIsValid, - children - } = props; - const introspect = React.useCallback(() => { - if (graphql.isSchema(props.schema) || props.schema === null) { - return; + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { + return pos; + } + if (cmp(pos, change.to) <= 0) { + return changeEnd(change); + } + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, + ch = pos.ch; + if (pos.line == change.to.line) { + ch += changeEnd(change).ch - change.to.ch; + } + return Pos(line, ch); } - const counter = ++counterRef.current; - const maybeIntrospectionData = props.schema; - async function fetchIntrospectionData() { - if (maybeIntrospectionData) { - return maybeIntrospectionData; + function computeSelAfterChange(doc, change) { + var out = []; + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + var range2 = doc.sel.ranges[i2]; + out.push(new Range(adjustForChange(range2.anchor, change), adjustForChange(range2.head, change))); } - const parsedHeaders = parseHeaderString(headersRef.current); - if (!parsedHeaders.isValidJSON) { - setFetchError("Introspection failed as headers are invalid."); - return; + return normalizeSelection(doc.cm, out, doc.sel.primIndex); + } + function offsetPos(pos, old, nw) { + if (pos.line == old.line) { + return Pos(nw.line, pos.ch - old.ch + nw.ch); + } else { + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + } + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), + newPrev = oldPrev; + for (var i2 = 0; i2 < changes.length; i2++) { + var change = changes[i2]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range2 = doc.sel.ranges[i2], + inv = cmp(range2.head, range2.anchor) < 0; + out[i2] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i2] = new Range(from, from); + } } - const fetcherOpts = parsedHeaders.headers ? { - headers: parsedHeaders.headers - } : {}; - const fetch2 = toolkit.fetcherReturnToPromise(fetcher({ - query: introspectionQuery, - operationName: introspectionQueryName - }, fetcherOpts)); - if (!toolkit.isPromise(fetch2)) { - setFetchError("Fetcher did not return a Promise for introspection."); - return; + return new Selection(out, doc.sel.primIndex); + } + function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { + line.stateAfter = null; + } + if (line.styles) { + line.styles = null; + } + }); + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) { + regChange(cm); + } + } + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + function updateDoc(doc, change, markedSpans, estimateHeight2) { + function spansFor(n) { + return markedSpans ? markedSpans[n] : null; } - setIsFetching(true); - setFetchError(null); - let result = await fetch2; - if (typeof result !== "object" || result === null || !("data" in result)) { - const fetch22 = toolkit.fetcherReturnToPromise(fetcher({ - query: introspectionQuerySansSubscriptions, - operationName: introspectionQueryName - }, fetcherOpts)); - if (!toolkit.isPromise(fetch22)) { - throw new Error("Fetcher did not return a Promise for introspection."); + function update(line, text2, spans) { + updateLine(line, text2, spans, estimateHeight2); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + var result = []; + for (var i2 = start; i2 < end; ++i2) { + result.push(new Line(text[i2], spansFor(i2), estimateHeight2)); } - result = await fetch22; + return result; } - setIsFetching(false); - if ((result == null ? void 0 : result.data) && "__schema" in result.data) { - return result.data; + var from = change.from, + to = change.to, + text = change.text; + var firstLine = getLine(doc, from.line), + lastLine = getLine(doc, to.line); + var lastText = lst(text), + lastSpans = spansFor(text.length - 1), + nlines = to.line - from.line; + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) { + doc.remove(from.line, nlines); + } + if (added.length) { + doc.insert(from.line, added); + } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added$1 = linesFor(1, text.length - 1); + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight2)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added$1); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added$2 = linesFor(1, text.length - 1); + if (nlines > 1) { + doc.remove(from.line + 1, nlines - 1); + } + doc.insert(from.line + 1, added$2); } - const responseString = typeof result === "string" ? result : toolkit.formatResult(result); - setFetchError(responseString); + signalLater(doc, "change", doc, change); } - fetchIntrospectionData().then(introspectionData => { - if (counter !== counterRef.current || !introspectionData) { - return; + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc2, skip, sharedHist) { + if (doc2.linked) { + for (var i2 = 0; i2 < doc2.linked.length; ++i2) { + var rel = doc2.linked[i2]; + if (rel.doc == skip) { + continue; + } + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) { + continue; + } + f(rel.doc, shared); + propagate(rel.doc, doc2, shared); + } + } } - try { - const newSchema = graphql.buildClientSchema(introspectionData); - setSchema(newSchema); - onSchemaChange == null ? void 0 : onSchemaChange(newSchema); - } catch (error) { - setFetchError(toolkit.formatError(error)); - } - }).catch(error => { - if (counter !== counterRef.current) { - return; + propagate(doc, null, true); + } + function attachDoc(cm, doc) { + if (doc.cm) { + throw new Error("This document is already in use."); } - setFetchError(toolkit.formatError(error)); - setIsFetching(false); - }); - }, [fetcher, introspectionQueryName, introspectionQuery, introspectionQuerySansSubscriptions, onSchemaChange, props.schema]); - React.useEffect(() => { - introspect(); - }, [introspect]); - React.useEffect(() => { - function triggerIntrospection(event) { - if (event.ctrlKey && event.key === "R") { - introspect(); - } - } - window.addEventListener("keydown", triggerIntrospection); - return () => window.removeEventListener("keydown", triggerIntrospection); - }); - const validationErrors = React.useMemo(() => { - if (!schema || dangerouslyAssumeSchemaIsValid) { - return []; - } - return graphql.validateSchema(schema); - }, [schema, dangerouslyAssumeSchemaIsValid]); - const value = React.useMemo(() => ({ - fetchError, - introspect, - isFetching, - schema, - validationErrors - }), [fetchError, introspect, isFetching, schema, validationErrors]); - return /* @__PURE__ */jsxRuntime.jsx(SchemaContext.Provider, { - value, - children - }); - } - const useSchemaContext = createContextHook(SchemaContext); - function useIntrospectionQuery({ - inputValueDeprecation, - introspectionQueryName, - schemaDescription - }) { - return React.useMemo(() => { - const queryName = introspectionQueryName || "IntrospectionQuery"; - let query = graphql.getIntrospectionQuery({ - inputValueDeprecation, - schemaDescription - }); - if (introspectionQueryName) { - query = query.replace("query IntrospectionQuery", `query ${queryName}`); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + setDirectionClass(cm); + cm.options.direction = doc.direction; + if (!cm.options.lineWrapping) { + findMaxLine(cm); + } + cm.options.mode = doc.modeOption; + regChange(cm); } - const querySansSubscriptions = query.replace("subscriptionType { name }", ""); - return { - introspectionQueryName: queryName, - introspectionQuery: query, - introspectionQuerySansSubscriptions: querySansSubscriptions - }; - }, [inputValueDeprecation, introspectionQueryName, schemaDescription]); - } - function parseHeaderString(headersString) { - let headers = null; - let isValidJSON = true; - try { - if (headersString) { - headers = JSON.parse(headersString); + function setDirectionClass(cm) { + (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); } - } catch { - isValidJSON = false; - } - return { - headers, - isValidJSON - }; - } - const initialNavStackItem = { - name: "Docs" - }; - const ExplorerContext = createNullableContext("ExplorerContext"); - function ExplorerContextProvider(props) { - const { - schema, - validationErrors - } = useSchemaContext({ - nonNull: true, - caller: ExplorerContextProvider - }); - const [navStack, setNavStack] = React.useState([initialNavStackItem]); - const push = React.useCallback(item => { - setNavStack(currentState => { - const lastItem = currentState.at(-1); - return lastItem.def === item.def ? - // Avoid pushing duplicate items - currentState : [...currentState, item]; - }); - }, []); - const pop = React.useCallback(() => { - setNavStack(currentState => currentState.length > 1 ? currentState.slice(0, -1) : currentState); - }, []); - const reset = React.useCallback(() => { - setNavStack(currentState => currentState.length === 1 ? currentState : [initialNavStackItem]); - }, []); - React.useEffect(() => { - if (schema == null || validationErrors.length > 0) { - reset(); - } else { - setNavStack(oldNavStack => { - if (oldNavStack.length === 1) { - return oldNavStack; - } - const newNavStack = [initialNavStackItem]; - let lastEntity = null; - for (const item of oldNavStack) { - if (item === initialNavStackItem) { - continue; - } - if (item.def) { - if (graphql.isNamedType(item.def)) { - const newType = schema.getType(item.def.name); - if (newType) { - newNavStack.push({ - name: item.name, - def: newType - }); - lastEntity = newType; - } else { - break; - } - } else if (lastEntity === null) { - break; - } else if (graphql.isObjectType(lastEntity) || graphql.isInputObjectType(lastEntity)) { - const field = lastEntity.getFields()[item.name]; - if (field) { - newNavStack.push({ - name: item.name, - def: field - }); - } else { - break; - } - } else if (graphql.isScalarType(lastEntity) || graphql.isEnumType(lastEntity) || graphql.isInterfaceType(lastEntity) || graphql.isUnionType(lastEntity)) { - break; - } else { - const field = lastEntity; - const arg = field.args.find(a => a.name === item.name); - if (arg) { - newNavStack.push({ - name: item.name, - def: field - }); - } else { - break; - } - } - } else { - lastEntity = null; - newNavStack.push(item); + function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm); + regChange(cm); + }); + } + function History(prev) { + this.done = []; + this.undone = []; + this.undoDepth = prev ? prev.undoDepth : Infinity; + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; + } + function historyChangeFromChange(doc, change) { + var histChange = { + from: copyPos(change.from), + to: changeEnd(change), + text: getBetween(doc, change.from, change.to) + }; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc2) { + return attachLocalSpans(doc2, histChange, change.from.line, change.to.line + 1); + }, true); + return histChange; + } + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) { + array.pop(); + } else { + break; + } + } + } + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = + /* @__PURE__ */new Date(), + cur; + var last; + if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && (change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + last.to = changeEnd(change); + } else { + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + var before = lst(hist.done); + if (!before || !before.ranges) { + pushSelectionToHistory(doc.sel, hist.done); + } + cur = { + changes: [historyChangeFromChange(doc, change)], + generation: hist.generation + }; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) { + hist.done.shift(); } } - return newNavStack; - }); + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + if (!last) { + signal(doc, "historyAdded"); + } } - }, [reset, schema, validationErrors]); - const value = React.useMemo(() => ({ - explorerNavStack: navStack, - push, - pop, - reset - }), [navStack, push, pop, reset]); - return /* @__PURE__ */jsxRuntime.jsx(ExplorerContext.Provider, { - value, - children: props.children - }); - } - const useExplorerContext = createContextHook(ExplorerContext); - function renderType(type, renderNamedType) { - if (graphql.isNonNullType(type)) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [renderType(type.ofType, renderNamedType), "!"] - }); - } - if (graphql.isListType(type)) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["[", renderType(type.ofType, renderNamedType), "]"] - }); - } - return renderNamedType(type); - } - function TypeLink(props) { - const { - push - } = useExplorerContext({ - nonNull: true, - caller: TypeLink - }); - if (!props.type) { - return null; - } - return renderType(props.type, namedType => /* @__PURE__ */jsxRuntime.jsx("a", { - className: "graphiql-doc-explorer-type-name", - onClick: event => { - event.preventDefault(); - push({ - name: namedType.name, - def: namedType + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && /* @__PURE__ */new Date() - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, + origin = options && options.origin; + if (opId == hist.lastSelOp || origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))) { + hist.done[hist.done.length - 1] = sel; + } else { + pushSelectionToHistory(sel, hist.done); + } + hist.lastSelTime = + /* @__PURE__ */new Date(); + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) { + clearSelectionEvents(hist.undone); + } + } + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) { + dest.push(sel); + } + } + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], + n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) { + (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + } + ++n; }); - }, - href: "#", - children: namedType.name - })); - } - function Argument({ - arg, - showDefaultValue, - inline - }) { - const definition = /* @__PURE__ */jsxRuntime.jsxs("span", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-argument-name", - children: arg.name - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: arg.type - }), showDefaultValue !== false && /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { - field: arg - })] - }); - if (inline) { - return definition; - } - return /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-argument", - children: [definition, arg.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: arg.description - }) : null, arg.deprecationReason ? /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-argument-deprecation", - children: [/* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-argument-deprecation-label", - children: "Deprecated" - }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - children: arg.deprecationReason - })] - }) : null] - }); - } - function DeprecationReason(props) { - var _props$preview; - return props.children ? /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-deprecation", - children: [/* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-deprecation-label", - children: "Deprecated" - }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - onlyShowFirstChild: (_props$preview = props.preview) !== null && _props$preview !== void 0 ? _props$preview : true, - children: props.children - })] - }) : null; - } - function Directive({ - directive - }) { - return /* @__PURE__ */jsxRuntime.jsxs("span", { - className: "graphiql-doc-explorer-directive", - children: ["@", directive.name.value] - }); - } - function ExplorerSection(props) { - const Icon2 = TYPE_TO_ICON[props.title]; - return /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-section-title", - children: [/* @__PURE__ */jsxRuntime.jsx(Icon2, {}), props.title] - }), /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-section-content", - children: props.children - })] - }); - } - const TYPE_TO_ICON = { - Arguments: ArgumentIcon, - "Deprecated Arguments": DeprecatedArgumentIcon, - "Deprecated Enum Values": DeprecatedEnumValueIcon, - "Deprecated Fields": DeprecatedFieldIcon, - Directives: DirectiveIcon, - "Enum Values": EnumValueIcon, - Fields: FieldIcon, - Implements: ImplementsIcon, - Implementations: TypeIcon, - "Possible Types": TypeIcon, - "Root Types": RootTypeIcon, - Type: TypeIcon, - "All Schema Types": TypeIcon - }; - function FieldDocumentation(props) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [props.field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.field.description - }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { - preview: false, - children: props.field.deprecationReason - }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Type", - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: props.field.type - }) - }), /* @__PURE__ */jsxRuntime.jsx(Arguments, { - field: props.field - }), /* @__PURE__ */jsxRuntime.jsx(Directives, { - field: props.field - })] - }); - } - function Arguments({ - field - }) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!("args" in field)) { - return null; - } - const args = []; - const deprecatedArgs = []; - for (const argument of field.args) { - if (argument.deprecationReason) { - deprecatedArgs.push(argument); - } else { - args.push(argument); } - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [args.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Arguments", - children: args.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg - }, arg.name)) - }) : null, deprecatedArgs.length > 0 ? showDeprecated || args.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Arguments", - children: deprecatedArgs.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg - }, arg.name)) - }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Arguments" - }) : null] - }); - } - function Directives({ - field - }) { - var _a; - const directives = ((_a = field.astNode) == null ? void 0 : _a.directives) || []; - if (!directives || directives.length === 0) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Directives", - children: directives.map(directive => /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(Directive, { - directive - }) - }, directive.name.value)) - }); - } - function SchemaDocumentation(props) { - var _a, _b, _c, _d; - const queryType = props.schema.getQueryType(); - const mutationType = (_b = (_a = props.schema).getMutationType) == null ? void 0 : _b.call(_a); - const subscriptionType = (_d = (_c = props.schema).getSubscriptionType) == null ? void 0 : _d.call(_c); - const typeMap = props.schema.getTypeMap(); - const ignoreTypesInAllSchema = [queryType == null ? void 0 : queryType.name, mutationType == null ? void 0 : mutationType.name, subscriptionType == null ? void 0 : subscriptionType.name]; - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.schema.description || "A GraphQL schema provides a root type for each kind of operation." - }), /* @__PURE__ */jsxRuntime.jsxs(ExplorerSection, { - title: "Root Types", - children: [queryType ? /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "query" - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: queryType - })] - }) : null, mutationType && /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "mutation" - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: mutationType - })] - }), subscriptionType && /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-root-type", - children: "subscription" - }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: subscriptionType - })] - })] - }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "All Schema Types", - children: typeMap && /* @__PURE__ */jsxRuntime.jsx("div", { - children: Object.values(typeMap).map(type => { - if (ignoreTypesInAllSchema.includes(type.name) || type.name.startsWith("__")) { - return null; + function removeClearedSpans(spans) { + if (!spans) { + return null; + } + var out; + for (var i2 = 0; i2 < spans.length; ++i2) { + if (spans[i2].marker.explicitlyCleared) { + if (!out) { + out = spans.slice(0, i2); } - return /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type - }) - }, type.name); - }) - }) - })] - }); - } - function debounce(duration, fn) { - let timeout; - return function (...args) { - if (timeout) { - window.clearTimeout(timeout); + } else if (out) { + out.push(spans[i2]); + } + } + return !out ? spans : out.length ? out : null; } - timeout = window.setTimeout(() => { - timeout = null; - fn(...args); - }, duration); - }; - } - function Search() { - const { - explorerNavStack, - push - } = useExplorerContext({ - nonNull: true, - caller: Search - }); - const inputRef = React.useRef(null); - const getSearchResults = useSearchResults(); - const [searchValue, setSearchValue] = React.useState(""); - const [results, setResults] = React.useState(getSearchResults(searchValue)); - const debouncedGetSearchResults = React.useMemo(() => debounce(200, search => { - setResults(getSearchResults(search)); - }), [getSearchResults]); - React.useEffect(() => { - debouncedGetSearchResults(searchValue); - }, [debouncedGetSearchResults, searchValue]); - React.useEffect(() => { - function handleKeyDown(event) { - var _a; - if (event.metaKey && event.key === "k") { - (_a = inputRef.current) == null ? void 0 : _a.focus(); + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) { + return null; } + var nw = []; + for (var i2 = 0; i2 < change.text.length; ++i2) { + nw.push(removeClearedSpans(found[i2])); + } + return nw; } - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, []); - const navItem = explorerNavStack.at(-1); - const onSelect = React.useCallback(def => { - push("field" in def ? { - name: def.field.name, - def: def.field - } : { - name: def.type.name, - def: def.type - }); - }, [push]); - const isFocused = React.useRef(false); - const handleFocus = React.useCallback(e => { - isFocused.current = e.type === "focus"; - }, []); - const shouldSearchBoxAppear = explorerNavStack.length === 1 || graphql.isObjectType(navItem.def) || graphql.isInterfaceType(navItem.def) || graphql.isInputObjectType(navItem.def); - if (!shouldSearchBoxAppear) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsxs(react.Combobox, { - as: "div", - className: "graphiql-doc-explorer-search", - onChange: onSelect, - "data-state": isFocused ? void 0 : "idle", - "aria-label": `Search ${navItem.name}...`, - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-search-input", - onClick: () => { - var _a; - (_a = inputRef.current) == null ? void 0 : _a.focus(); - }, - children: [/* @__PURE__ */jsxRuntime.jsx(MagnifyingGlassIcon, {}), /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Input, { - autoComplete: "off", - onFocus: handleFocus, - onBlur: handleFocus, - onChange: event => setSearchValue(event.target.value), - placeholder: "⌘ K", - ref: inputRef, - value: searchValue, - "data-cy": "doc-explorer-input" - })] - }), isFocused.current && /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Options, { - "data-cy": "doc-explorer-list", - children: [results.within.length + results.types.length + results.fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx("li", { - className: "graphiql-doc-explorer-search-empty", - children: "No results found" - }) : results.within.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { - value: result, - "data-cy": "doc-explorer-option", - children: /* @__PURE__ */jsxRuntime.jsx(Field$1, { - field: result.field, - argument: result.argument - }) - }, `within-${i}`)), results.within.length > 0 && results.types.length + results.fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-search-divider", - children: "Other results" - }) : null, results.types.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { - value: result, - "data-cy": "doc-explorer-option", - children: /* @__PURE__ */jsxRuntime.jsx(Type, { - type: result.type - }) - }, `type-${i}`)), results.fields.map((result, i) => /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Option, { - value: result, - "data-cy": "doc-explorer-option", - children: [/* @__PURE__ */jsxRuntime.jsx(Type, { - type: result.type - }), ".", /* @__PURE__ */jsxRuntime.jsx(Field$1, { - field: result.field, - argument: result.argument - })] - }, `field-${i}`))] - })] - }); - } - function useSearchResults(caller) { - const { - explorerNavStack - } = useExplorerContext({ - nonNull: true, - caller: caller || useSearchResults - }); - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: caller || useSearchResults - }); - const navItem = explorerNavStack.at(-1); - return React.useCallback(searchValue => { - const matches = { - within: [], - types: [], - fields: [] - }; - if (!schema) { - return matches; - } - const withinType = navItem.def; - const typeMap = schema.getTypeMap(); - let typeNames = Object.keys(typeMap); - if (withinType) { - typeNames = typeNames.filter(n => n !== withinType.name); - typeNames.unshift(withinType.name); - } - for (const typeName of typeNames) { - if (matches.within.length + matches.types.length + matches.fields.length >= 100) { - break; + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) { + return stretched; } - const type = typeMap[typeName]; - if (withinType !== type && isMatch(typeName, searchValue)) { - matches.types.push({ - type - }); + if (!stretched) { + return old; } - if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { - continue; + for (var i2 = 0; i2 < old.length; ++i2) { + var oldCur = old[i2], + stretchCur = stretched[i2]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) { + if (oldCur[k].marker == span.marker) { + continue spans; + } + } + oldCur.push(span); + } + } else if (stretchCur) { + old[i2] = stretchCur; + } } - const fields = type.getFields(); - for (const fieldName in fields) { - const field = fields[fieldName]; - let matchingArgs; - if (!isMatch(fieldName, searchValue)) { - if ("args" in field) { - matchingArgs = field.args.filter(arg => isMatch(arg.name, searchValue)); - if (matchingArgs.length === 0) { - continue; + return old; + } + function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = []; + for (var i2 = 0; i2 < events.length; ++i2) { + var event = events[i2]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, + newChanges = []; + copy.push({ + changes: newChanges + }); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], + m = void 0; + newChanges.push({ + from: change.from, + to: change.to, + text: change.text + }); + if (newGroup) { + for (var prop2 in change) { + if (m = prop2.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop2] = change[prop2]; + delete change[prop2]; + } + } } - } else { - continue; } } - matches[withinType === type ? "within" : "fields"].push(...(matchingArgs ? matchingArgs.map(argument => ({ - type, - field, - argument - })) : [{ - type, - field - }])); } + return copy; } - return matches; - }, [navItem.def, schema]); - } - function isMatch(sourceText, searchValue) { - try { - const escaped = searchValue.replaceAll(/[^_0-9A-Za-z]/g, ch => "\\" + ch); - return sourceText.search(new RegExp(escaped, "i")) !== -1; - } catch { - return sourceText.toLowerCase().includes(searchValue.toLowerCase()); - } - } - function Type(props) { - return /* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-type", - children: props.type.name - }); - } - function Field$1({ - field, - argument - }) { - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [/* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-field", - children: field.name - }), argument ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { - className: "graphiql-doc-explorer-search-argument", - children: argument.name - }), ":", " ", renderType(argument.type, namedType => /* @__PURE__ */jsxRuntime.jsx(Type, { - type: namedType - })), ")"] - }) : null] - }); - } - function FieldLink(props) { - const { - push - } = useExplorerContext({ - nonNull: true - }); - return /* @__PURE__ */jsxRuntime.jsx("a", { - className: "graphiql-doc-explorer-field-name", - onClick: event => { - event.preventDefault(); - push({ - name: props.field.name, - def: props.field - }); - }, - href: "#", - children: props.field.name - }); - } - function TypeDocumentation(props) { - return graphql.isNamedType(props.type) ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [props.type.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: props.type.description - }) : null, /* @__PURE__ */jsxRuntime.jsx(ImplementsInterfaces, { - type: props.type - }), /* @__PURE__ */jsxRuntime.jsx(Fields, { - type: props.type - }), /* @__PURE__ */jsxRuntime.jsx(EnumValues, { - type: props.type - }), /* @__PURE__ */jsxRuntime.jsx(PossibleTypes, { - type: props.type - })] - }) : null; - } - function ImplementsInterfaces({ - type - }) { - if (!graphql.isObjectType(type)) { - return null; - } - const interfaces = type.getInterfaces(); - return interfaces.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Implements", - children: type.getInterfaces().map(implementedInterface => /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: implementedInterface - }) - }, implementedInterface.name)) - }) : null; - } - function Fields({ - type - }) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { - return null; - } - const fieldMap = type.getFields(); - const fields = []; - const deprecatedFields = []; - for (const field of Object.keys(fieldMap).map(name => fieldMap[name])) { - if (field.deprecationReason) { - deprecatedFields.push(field); - } else { - fields.push(field); + function extendRange(range2, head, other, extend) { + if (extend) { + var anchor = range2.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != cmp(other, anchor) < 0) { + anchor = head; + head = other; + } else if (posBefore != cmp(head, other) < 0) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); + } } - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Fields", - children: fields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { - field - }, field.name)) - }) : null, deprecatedFields.length > 0 ? showDeprecated || fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Fields", - children: deprecatedFields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { - field - }, field.name)) - }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Fields" - }) : null] - }); - } - function Field({ - field - }) { - const args = "args" in field ? field.args.filter(arg => !arg.deprecationReason) : []; - return /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-item", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx(FieldLink, { - field - }), args.length > 0 ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { - children: args.map(arg => args.length === 1 ? /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg, - inline: true - }, arg.name) : /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-argument-multiple", - children: /* @__PURE__ */jsxRuntime.jsx(Argument, { - arg, - inline: true - }) - }, arg.name)) - }), ")"] - }) : null, ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: field.type - }), /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { - field - })] - }), field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - onlyShowFirstChild: true, - children: field.description - }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { - children: field.deprecationReason - })] - }); - } - function EnumValues({ - type - }) { - const [showDeprecated, setShowDeprecated] = React.useState(false); - const handleShowDeprecated = React.useCallback(() => { - setShowDeprecated(true); - }, []); - if (!graphql.isEnumType(type)) { - return null; - } - const values = []; - const deprecatedValues = []; - for (const value of type.getValues()) { - if (value.deprecationReason) { - deprecatedValues.push(value); - } else { - values.push(value); + function extendSelection(doc, head, other, options, extend) { + if (extend == null) { + extend = doc.cm && (doc.cm.display.shift || doc.extend); + } + setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); } - } - return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [values.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Enum Values", - children: values.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { - value - }, value.name)) - }) : null, deprecatedValues.length > 0 ? showDeprecated || values.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: "Deprecated Enum Values", - children: deprecatedValues.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { - value - }, value.name)) - }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { - type: "button", - onClick: handleShowDeprecated, - children: "Show Deprecated Values" - }) : null] - }); - } - function EnumValue({ - value - }) { - return /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-item", - children: [/* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-enum-value", - children: value.name - }), value.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "description", - children: value.description - }) : null, value.deprecationReason ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { - type: "deprecation", - children: value.deprecationReason - }) : null] - }); - } - function PossibleTypes({ - type - }) { - const { - schema - } = useSchemaContext({ - nonNull: true - }); - if (!schema || !graphql.isAbstractType(type)) { - return null; - } - return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { - title: graphql.isInterfaceType(type) ? "Implementations" : "Possible Types", - children: schema.getPossibleTypes(type).map(possibleType => /* @__PURE__ */jsxRuntime.jsx("div", { - children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { - type: possibleType - }) - }, possibleType.name)) - }); - } - function DocExplorer() { - const { - fetchError, - isFetching, - schema, - validationErrors - } = useSchemaContext({ - nonNull: true, - caller: DocExplorer - }); - const { - explorerNavStack, - pop - } = useExplorerContext({ - nonNull: true, - caller: DocExplorer - }); - const navItem = explorerNavStack.at(-1); - let content = null; - if (fetchError) { - content = /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-error", - children: "Error fetching schema" - }); - } else if (validationErrors.length > 0) { - content = /* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-error", - children: ["Schema is invalid: ", validationErrors[0].message] - }); - } else if (isFetching) { - content = /* @__PURE__ */jsxRuntime.jsx(Spinner, {}); - } else if (!schema) { - content = /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-error", - children: "No GraphQL schema available" - }); - } else if (explorerNavStack.length === 1) { - content = /* @__PURE__ */jsxRuntime.jsx(SchemaDocumentation, { - schema - }); - } else if (graphql.isType(navItem.def)) { - content = /* @__PURE__ */jsxRuntime.jsx(TypeDocumentation, { - type: navItem.def - }); - } else if (navItem.def) { - content = /* @__PURE__ */jsxRuntime.jsx(FieldDocumentation, { - field: navItem.def - }); - } - let prevName; - if (explorerNavStack.length > 1) { - prevName = explorerNavStack.at(-2).name; - } - return /* @__PURE__ */jsxRuntime.jsxs("section", { - className: "graphiql-doc-explorer", - "aria-label": "Documentation Explorer", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-header", - children: [/* @__PURE__ */jsxRuntime.jsxs("div", { - className: "graphiql-doc-explorer-header-content", - children: [prevName && /* @__PURE__ */jsxRuntime.jsxs("a", { - href: "#", - className: "graphiql-doc-explorer-back", - onClick: event => { - event.preventDefault(); - pop(); - }, - "aria-label": `Go back to ${prevName}`, - children: [/* @__PURE__ */jsxRuntime.jsx(ChevronLeftIcon, {}), prevName] - }), /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-title", - children: navItem.name - })] - }), /* @__PURE__ */jsxRuntime.jsx(Search, {}, navItem.name)] - }), /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-doc-explorer-content", - children: content - })] - }); - } - const DOC_EXPLORER_PLUGIN = { - title: "Documentation Explorer", - icon: function Icon() { - const pluginContext = usePluginContext(); - return (pluginContext == null ? void 0 : pluginContext.visiblePlugin) === DOC_EXPLORER_PLUGIN ? /* @__PURE__ */jsxRuntime.jsx(DocsFilledIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(DocsIcon, {}); - }, - content: DocExplorer - }; - const HISTORY_PLUGIN = { - title: "History", - icon: HistoryIcon, - content: History - }; - const PluginContext = createNullableContext("PluginContext"); - function PluginContextProvider(props) { - const storage = useStorageContext(); - const explorerContext = useExplorerContext(); - const historyContext = useHistoryContext(); - const hasExplorerContext = Boolean(explorerContext); - const hasHistoryContext = Boolean(historyContext); - const plugins = React.useMemo(() => { - const pluginList = []; - const pluginTitles = {}; - if (hasExplorerContext) { - pluginList.push(DOC_EXPLORER_PLUGIN); - pluginTitles[DOC_EXPLORER_PLUGIN.title] = true; - } - if (hasHistoryContext) { - pluginList.push(HISTORY_PLUGIN); - pluginTitles[HISTORY_PLUGIN.title] = true; - } - for (const plugin of props.plugins || []) { - if (typeof plugin.title !== "string" || !plugin.title) { - throw new Error("All GraphiQL plugins must have a unique title"); - } - if (pluginTitles[plugin.title]) { - throw new Error(`All GraphiQL plugins must have a unique title, found two plugins with the title '${plugin.title}'`); + function extendSelections(doc, heads, options) { + var out = []; + var extend = doc.cm && (doc.cm.display.shift || doc.extend); + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + out[i2] = extendRange(doc.sel.ranges[i2], heads[i2], null, extend); + } + var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + function replaceOneSelection(doc, i2, range2, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i2] = range2; + setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); + } + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function (ranges) { + this.ranges = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + this.ranges[i2] = new Range(clipPos(doc, ranges[i2].anchor), clipPos(doc, ranges[i2].head)); + } + }, + origin: options && options.origin + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) { + signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + } + if (obj.ranges != sel.ranges) { + return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1); } else { - pluginList.push(plugin); - pluginTitles[plugin.title] = true; + return sel; } } - return pluginList; - }, [hasExplorerContext, hasHistoryContext, props.plugins]); - const [visiblePlugin, internalSetVisiblePlugin] = React.useState(() => { - const storedValue = storage == null ? void 0 : storage.get(STORAGE_KEY$4); - const pluginForStoredValue = plugins.find(plugin => plugin.title === storedValue); - if (pluginForStoredValue) { - return pluginForStoredValue; + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, + last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } } - if (storedValue) { - storage == null ? void 0 : storage.set(STORAGE_KEY$4, ""); + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); } - if (!props.visiblePlugin) { - return null; + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { + sel = filterSelectionChange(doc, sel, options); + } + var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") { + ensureCursorVisible(doc.cm); + } } - return plugins.find(plugin => (typeof props.visiblePlugin === "string" ? plugin.title : plugin) === props.visiblePlugin) || null; - }); - const { - onTogglePluginVisibility, - children - } = props; - const setVisiblePlugin = React.useCallback(plugin => { - const newVisiblePlugin = plugin ? plugins.find(p => (typeof plugin === "string" ? p.title : p) === plugin) || null : null; - internalSetVisiblePlugin(current => { - if (newVisiblePlugin === current) { - return current; - } - onTogglePluginVisibility == null ? void 0 : onTogglePluginVisibility(newVisiblePlugin); - return newVisiblePlugin; - }); - }, [onTogglePluginVisibility, plugins]); - React.useEffect(() => { - if (props.visiblePlugin) { - setVisiblePlugin(props.visiblePlugin); - } - }, [plugins, props.visiblePlugin, setVisiblePlugin]); - const value = React.useMemo(() => ({ - plugins, - setVisiblePlugin, - visiblePlugin - }), [plugins, setVisiblePlugin, visiblePlugin]); - return /* @__PURE__ */jsxRuntime.jsx(PluginContext.Provider, { - value, - children - }); - } - const usePluginContext = createContextHook(PluginContext); - const STORAGE_KEY$4 = "visiblePlugin"; - function onHasCompletion(_cm, data, schema, explorer, plugin, callback) { - void importCodeMirror([], { - useCommonAddons: false - }).then(CodeMirror => { - let information; - let fieldName; - let typeNamePill; - let typeNamePrefix; - let typeName; - let typeNameSuffix; - let description; - let deprecation; - let deprecationReason; - CodeMirror.on(data, "select", - // @ts-expect-error - (ctx, el) => { - if (!information) { - const hintsUl = el.parentNode; - information = document.createElement("div"); - information.className = "CodeMirror-hint-information"; - hintsUl.append(information); - const header = document.createElement("header"); - header.className = "CodeMirror-hint-information-header"; - information.append(header); - fieldName = document.createElement("span"); - fieldName.className = "CodeMirror-hint-information-field-name"; - header.append(fieldName); - typeNamePill = document.createElement("span"); - typeNamePill.className = "CodeMirror-hint-information-type-name-pill"; - header.append(typeNamePill); - typeNamePrefix = document.createElement("span"); - typeNamePill.append(typeNamePrefix); - typeName = document.createElement("a"); - typeName.className = "CodeMirror-hint-information-type-name"; - typeName.href = "javascript:void 0"; - typeName.addEventListener("click", onClickHintInformation); - typeNamePill.append(typeName); - typeNameSuffix = document.createElement("span"); - typeNamePill.append(typeNameSuffix); - description = document.createElement("div"); - description.className = "CodeMirror-hint-information-description"; - information.append(description); - deprecation = document.createElement("div"); - deprecation.className = "CodeMirror-hint-information-deprecation"; - information.append(deprecation); - const deprecationLabel = document.createElement("span"); - deprecationLabel.className = "CodeMirror-hint-information-deprecation-label"; - deprecationLabel.textContent = "Deprecated"; - deprecation.append(deprecationLabel); - deprecationReason = document.createElement("div"); - deprecationReason.className = "CodeMirror-hint-information-deprecation-reason"; - deprecation.append(deprecationReason); - const defaultInformationPadding = parseInt(window.getComputedStyle(information).paddingBottom.replace(/px$/, ""), 10) || 0; - const defaultInformationMaxHeight = parseInt(window.getComputedStyle(information).maxHeight.replace(/px$/, ""), 10) || 0; - const handleScroll = () => { - if (information) { - information.style.paddingTop = hintsUl.scrollTop + defaultInformationPadding + "px"; - information.style.maxHeight = hintsUl.scrollTop + defaultInformationMaxHeight + "px"; - } - }; - hintsUl.addEventListener("scroll", handleScroll); - let onRemoveFn; - hintsUl.addEventListener("DOMNodeRemoved", onRemoveFn = event => { - if (event.target !== hintsUl) { - return; - } - hintsUl.removeEventListener("scroll", handleScroll); - hintsUl.removeEventListener("DOMNodeRemoved", onRemoveFn); - if (information) { - information.removeEventListener("click", onClickHintInformation); - } - information = null; - fieldName = null; - typeNamePill = null; - typeNamePrefix = null; - typeName = null; - typeNameSuffix = null; - description = null; - deprecation = null; - deprecationReason = null; - onRemoveFn = null; - }); + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { + return; } - if (fieldName) { - fieldName.textContent = ctx.text; - } - if (typeNamePill && typeNamePrefix && typeName && typeNameSuffix) { - if (ctx.type) { - typeNamePill.style.display = "inline"; - const renderType2 = type => { - if (graphql.isNonNullType(type)) { - typeNameSuffix.textContent = "!" + typeNameSuffix.textContent; - renderType2(type.ofType); - } else if (graphql.isListType(type)) { - typeNamePrefix.textContent += "["; - typeNameSuffix.textContent = "]" + typeNameSuffix.textContent; - renderType2(type.ofType); - } else { - typeName.textContent = type.name; + doc.sel = sel; + if (doc.cm) { + doc.cm.curOp.updateInput = 1; + doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); + } + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i2]; + var newAnchor = skipAtomic(doc, range2.anchor, old && old.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range2.head, old && old.head, bias, mayClear); + if (out || newAnchor != range2.anchor || newHead != range2.head) { + if (!out) { + out = sel.ranges.slice(0, i2); + } + out[i2] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel; + } + function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line); + if (line.markedSpans) { + for (var i2 = 0; i2 < line.markedSpans.length; ++i2) { + var sp = line.markedSpans[i2], + m = sp.marker; + var preventCursorLeft = "selectLeft" in m ? !m.selectLeft : m.inclusiveLeft; + var preventCursorRight = "selectRight" in m ? !m.selectRight : m.inclusiveRight; + if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) { + break; + } else { + --i2; + continue; + } + } } - }; - typeNamePrefix.textContent = ""; - typeNameSuffix.textContent = ""; - renderType2(ctx.type); - } else { - typeNamePrefix.textContent = ""; - typeName.textContent = ""; - typeNameSuffix.textContent = ""; - typeNamePill.style.display = "none"; + if (!m.atomic) { + continue; + } + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), + diff = void 0; + if (dir < 0 ? preventCursorRight : preventCursorLeft) { + near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); + } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { + return skipAtomicInner(doc, near, pos, dir, mayClear); + } + } + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? preventCursorLeft : preventCursorRight) { + far = movePos(doc, far, dir, far.line == pos.line ? line : null); + } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; + } } } - if (description) { - if (ctx.description) { - description.style.display = "block"; - description.innerHTML = markdown.render(ctx.description); + return pos; + } + function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, dir, true) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || !mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true); + if (!found) { + doc.cantEdit = true; + return Pos(doc.first, 0); + } + return found; + } + function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { + return clipPos(doc, Pos(pos.line - 1)); } else { - description.style.display = "none"; - description.innerHTML = ""; + return null; } - } - if (deprecation && deprecationReason) { - if (ctx.deprecationReason) { - deprecation.style.display = "block"; - deprecationReason.innerHTML = markdown.render(ctx.deprecationReason); + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { + return Pos(pos.line + 1, 0); } else { - deprecation.style.display = "none"; - deprecationReason.innerHTML = ""; + return null; } + } else { + return new Pos(pos.line, pos.ch + dir); } - }); - }); - function onClickHintInformation(event) { - if (!schema || !explorer || !plugin || !(event.currentTarget instanceof HTMLElement)) { - return; - } - const typeName = event.currentTarget.textContent || ""; - const type = schema.getType(typeName); - if (type) { - plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); - explorer.push({ - name: type.name, - def: type - }); - callback == null ? void 0 : callback(type); } - } - } - function useSynchronizeValue(editor, value) { - React.useEffect(() => { - if (editor && typeof value === "string" && value !== editor.getValue()) { - editor.setValue(value); + function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); } - }, [editor, value]); - } - function useSynchronizeOption(editor, option, value) { - React.useEffect(() => { - if (editor) { - editor.setOption(option, value); + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { + return obj.canceled = true; + } + }; + if (update) { + obj.update = function (from, to, text, origin) { + if (from) { + obj.from = clipPos(doc, from); + } + if (to) { + obj.to = clipPos(doc, to); + } + if (text) { + obj.text = text; + } + if (origin !== void 0) { + obj.origin = origin; + } + }; + } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) { + signal(doc.cm, "beforeChange", doc.cm, obj); + } + if (obj.canceled) { + if (doc.cm) { + doc.cm.curOp.updateInput = 2; + } + return null; + } + return { + from: obj.from, + to: obj.to, + text: obj.text, + origin: obj.origin + }; } - }, [editor, option, value]); - } - function useChangeHandler(editor, callback, storageKey, tabProperty, caller) { - const { - updateActiveTabValues - } = useEditorContext({ - nonNull: true, - caller - }); - const storage = useStorageContext(); - React.useEffect(() => { - if (!editor) { - return; + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { + return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + } + if (doc.cm.state.suppressEdits) { + return; + } + } + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) { + return; + } + } + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i2 = split.length - 1; i2 >= 0; --i2) { + makeChangeInner(doc, { + from: split[i2].from, + to: split[i2].to, + text: i2 ? [""] : change.text, + origin: change.origin + }); + } + } else { + makeChangeInner(doc, change); + } } - const store = debounce(500, value => { - if (!storage || storageKey === null) { + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return; } - storage.set(storageKey, value); - }); - const updateTab = debounce(100, value => { - updateActiveTabValues({ - [tabProperty]: value + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + linkedDocs(doc, function (doc2, sharedHist) { + if (!sharedHist && indexOf(rebased, doc2.history) == -1) { + rebaseHist(doc2.history, change); + rebased.push(doc2.history); + } + makeChangeSingleDoc(doc2, change, null, stretchSpansOverChange(doc2, change)); }); - }); - const handleChange = (editorInstance, changeObj) => { - if (!changeObj) { + } + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + var suppress = doc.cm && doc.cm.state.suppressEdits; + if (suppress && !allowSelectionOnly) { return; } - const newValue = editorInstance.getValue(); - store(newValue); - updateTab(newValue); - callback == null ? void 0 : callback(newValue); - }; - editor.on("change", handleChange); - return () => editor.off("change", handleChange); - }, [callback, editor, storage, storageKey, tabProperty, updateActiveTabValues]); - } - function useCompletion(editor, callback, caller) { - const { - schema - } = useSchemaContext({ - nonNull: true, - caller - }); - const explorer = useExplorerContext(); - const plugin = usePluginContext(); - React.useEffect(() => { - if (!editor) { - return; - } - const handleCompletion = (instance, changeObj) => { - onHasCompletion(instance, changeObj, schema, explorer, plugin, type => { - callback == null ? void 0 : callback({ - kind: "Type", - type, - schema: schema || void 0 - }); + var hist = doc.history, + event, + selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, + dest = type == "undo" ? hist.undone : hist.done; + var i2 = 0; + for (; i2 < source.length; i2++) { + event = source[i2]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { + break; + } + } + if (i2 == source.length) { + return; + } + hist.lastOrigin = hist.lastSelOrigin = null; + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, { + clearRedo: false + }); + return; + } + selAfter = event; + } else if (suppress) { + source.push(event); + return; + } else { + break; + } + } + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({ + changes: antiChanges, + generation: hist.generation }); - }; - editor.on( - // @ts-expect-error @TODO additional args for hasCompletion event - "hasCompletion", handleCompletion); - return () => editor.off( - // @ts-expect-error @TODO additional args for hasCompletion event - "hasCompletion", handleCompletion); - }, [callback, editor, explorer, plugin, schema]); - } - function useKeyMap(editor, keys, callback) { - React.useEffect(() => { - if (!editor) { - return; - } - for (const key of keys) { - editor.removeKeyMap(key); - } - if (callback) { - const keyMap = {}; - for (const key of keys) { - keyMap[key] = () => callback(); + hist.generation = event.generation || ++hist.maxGeneration; + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + var loop = function (i3) { + var change = event.changes[i3]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return {}; + } + antiChanges.push(historyChangeFromChange(doc, change)); + var after = i3 ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i3 && doc.cm) { + doc.cm.scrollIntoView({ + from: change.from, + to: changeEnd(change) + }); + } + var rebased = []; + linkedDocs(doc, function (doc2, sharedHist) { + if (!sharedHist && indexOf(rebased, doc2.history) == -1) { + rebaseHist(doc2.history, change); + rebased.push(doc2.history); + } + makeChangeSingleDoc(doc2, change, null, mergeOldSpans(doc2, change)); + }); + }; + for (var i$12 = event.changes.length - 1; i$12 >= 0; --i$12) { + var returned = loop(i$12); + if (returned) return returned.v; } - editor.addKeyMap(keyMap); - } - }, [editor, keys, callback]); - } - function useCopyQuery({ - caller, - onCopyQuery - } = {}) { - const { - queryEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useCopyQuery - }); - return React.useCallback(() => { - if (!queryEditor) { - return; - } - const query = queryEditor.getValue(); - copyToClipboard(query); - onCopyQuery == null ? void 0 : onCopyQuery(query); - }, [queryEditor, onCopyQuery]); - } - function useMergeQuery({ - caller - } = {}) { - const { - queryEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useMergeQuery - }); - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: useMergeQuery - }); - return React.useCallback(() => { - const documentAST = queryEditor == null ? void 0 : queryEditor.documentAST; - const query = queryEditor == null ? void 0 : queryEditor.getValue(); - if (!documentAST || !query) { - return; } - queryEditor.setValue(graphql.print(toolkit.mergeAst(documentAST, schema))); - }, [queryEditor, schema]); - } - function usePrettifyEditors({ - caller - } = {}) { - const { - queryEditor, - headerEditor, - variableEditor - } = useEditorContext({ - nonNull: true, - caller: caller || usePrettifyEditors - }); - return React.useCallback(() => { - if (variableEditor) { - const variableEditorContent = variableEditor.getValue(); - try { - const prettifiedVariableEditorContent = JSON.stringify(JSON.parse(variableEditorContent), null, 2); - if (prettifiedVariableEditorContent !== variableEditorContent) { - variableEditor.setValue(prettifiedVariableEditorContent); + function shiftDoc(doc, distance) { + if (distance == 0) { + return; + } + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range2) { + return new Range(Pos(range2.anchor.line + distance, range2.anchor.ch), Pos(range2.head.line + distance, range2.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { + regLineChange(doc.cm, l, "gutter"); } - } catch {} + } } - if (headerEditor) { - const headerEditorContent = headerEditor.getValue(); - try { - const prettifiedHeaderEditorContent = JSON.stringify(JSON.parse(headerEditorContent), null, 2); - if (prettifiedHeaderEditorContent !== headerEditorContent) { - headerEditor.setValue(prettifiedHeaderEditorContent); + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) { + return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + } + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) { + return; + } + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = { + from: Pos(doc.first, 0), + to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], + origin: change.origin + }; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = { + from: change.from, + to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], + origin: change.origin + }; + } + change.removed = getBetween(doc, change.from, change.to); + if (!selAfter) { + selAfter = computeSelAfterChange(doc, change); + } + if (doc.cm) { + makeChangeSingleDocInEditor(doc.cm, change, spans); + } else { + updateDoc(doc, change, spans); + } + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) { + doc.cantEdit = false; + } + } + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, + display = cm.display, + from = change.from, + to = change.to; + var recomputeMaxLength = false, + checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + if (doc.sel.contains(change.from, change.to) > -1) { + signalCursorActivity(cm); + } + updateDoc(doc, change, spans, estimateHeight(cm)); + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) { + cm.curOp.updateMaxLine = true; + } + } + retreatFrontier(doc, from.line); + startWorker(cm, 400); + var lendiff = change.text.length - (to.line - from.line) - 1; + if (change.full) { + regChange(cm); + } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { + regLineChange(cm, from.line, "text"); + } else { + regChange(cm, from.line, to.line + 1, lendiff); + } + var changesHandler = hasHandler(cm, "changes"), + changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from, + to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) { + signalLater(cm, "change", cm, obj); + } + if (changesHandler) { + (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } - } catch {} + } + cm.display.selForContextMenu = null; } - if (queryEditor) { - const editorContent = queryEditor.getValue(); - const prettifiedEditorContent = graphql.print(graphql.parse(editorContent)); - if (prettifiedEditorContent !== editorContent) { - queryEditor.setValue(prettifiedEditorContent); + function replaceRange(doc, code, from, to, origin) { + var assign; + if (!to) { + to = from; + } + if (cmp(to, from) < 0) { + assign = [to, from], from = assign[0], to = assign[1]; } + if (typeof code == "string") { + code = doc.splitLines(code); + } + makeChange(doc, { + from, + to, + text: code, + origin + }); } - }, [queryEditor, variableEditor, headerEditor]); - } - function useAutoCompleteLeafs({ - getDefaultFieldNames, - caller - } = {}) { - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: caller || useAutoCompleteLeafs - }); - const { - queryEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useAutoCompleteLeafs - }); - return React.useCallback(() => { - if (!queryEditor) { - return; + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } } - const query = queryEditor.getValue(); - const { - insertions, - result - } = toolkit.fillLeafs(schema, query, getDefaultFieldNames); - if (insertions && insertions.length > 0) { - queryEditor.operation(() => { - const cursor = queryEditor.getCursor(); - const cursorIndex = queryEditor.indexFromPos(cursor); - queryEditor.setValue(result || ""); - let added = 0; - const markers = insertions.map(({ - index, - string - }) => queryEditor.markText(queryEditor.posFromIndex(index + added), queryEditor.posFromIndex(index + (added += string.length)), { - className: "auto-inserted-leaf", - clearOnEnter: true, - title: "Automatically added leaf fields" - })); - setTimeout(() => { - for (const marker of markers) { - marker.clear(); + function rebaseHistArray(array, from, to, diff) { + for (var i2 = 0; i2 < array.length; ++i2) { + var sub = array[i2], + ok = true; + if (sub.ranges) { + if (!sub.copied) { + sub = array[i2] = sub.deepCopy(); + sub.copied = true; } - }, 7e3); - let newCursorIndex = cursorIndex; - for (const { - index, - string - } of insertions) { - if (index < cursorIndex) { - newCursorIndex += string.length; + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); } + continue; } - queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex)); - }); - } - return result; - }, [getDefaultFieldNames, queryEditor, schema]); - } - const useEditorState = editor => { - var _ref2; - const context = useEditorContext({ - nonNull: true - }); - const editorInstance = context[`${editor}Editor`]; - let valueString = ""; - const editorValue = (_ref2 = editorInstance == null ? void 0 : editorInstance.getValue()) !== null && _ref2 !== void 0 ? _ref2 : false; - if (editorValue && editorValue.length > 0) { - valueString = editorValue; - } - const handleEditorValue = React.useCallback(value => editorInstance == null ? void 0 : editorInstance.setValue(value), [editorInstance]); - return React.useMemo(() => [valueString, handleEditorValue], [valueString, handleEditorValue]); - }; - const useOperationsEditorState = () => { - return useEditorState("query"); - }; - const useVariablesEditorState = () => { - return useEditorState("variable"); - }; - const useHeadersEditorState = () => { - return useEditorState("header"); - }; - function useOptimisticState([upstreamState, upstreamSetState]) { - const lastStateRef = React.useRef({ - /** The last thing that we sent upstream; we're expecting this back */ - pending: null, - /** The last thing we received from upstream */ - last: upstreamState - }); - const [state, setOperationsText] = React.useState(upstreamState); - React.useEffect(() => { - if (lastStateRef.current.last === upstreamState) ;else { - lastStateRef.current.last = upstreamState; - if (lastStateRef.current.pending === null) { - setOperationsText(upstreamState); - } else if (lastStateRef.current.pending === upstreamState) { - lastStateRef.current.pending = null; - if (upstreamState !== state) { - lastStateRef.current.pending = state; - upstreamSetState(state); + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } } + if (!ok) { + array.splice(0, i2 + 1); + i2 = 0; + } + } + } + function rebaseHist(hist, change) { + var from = change.from.line, + to = change.to.line, + diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + function changeLine(doc, handle, changeType, op) { + var no = handle, + line = handle; + if (typeof handle == "number") { + line = getLine(doc, clipLine(doc, handle)); } else { - lastStateRef.current.pending = null; - setOperationsText(upstreamState); - } - } - }, [upstreamState, state, upstreamSetState]); - const setState = React.useCallback(newState => { - setOperationsText(newState); - if (lastStateRef.current.pending === null && lastStateRef.current.last !== newState) { - lastStateRef.current.pending = newState; - upstreamSetState(newState); - } - }, [upstreamSetState]); - return React.useMemo(() => [state, setState], [state, setState]); - } - function useHeaderEditor({ - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onEdit, - readOnly = false - } = {}, caller) { - const { - initialHeaders, - headerEditor, - setHeaderEditor, - shouldPersistHeaders - } = useEditorContext({ - nonNull: true, - caller: caller || useHeaderEditor - }); - const executionContext = useExecutionContext(); - const merge = useMergeQuery({ - caller: caller || useHeaderEditor - }); - const prettify = usePrettifyEditors({ - caller: caller || useHeaderEditor - }); - const ref = React.useRef(null); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([ - // @ts-expect-error - Promise.resolve().then(() => __webpack_require__(/*! ./javascript.cjs.js */ "../../graphiql-react/dist/javascript.cjs.js")).then(n => n.javascript)]).then(CodeMirror => { - if (!isActive) { - return; + no = lineNo(handle); } - const container = ref.current; - if (!container) { - return; + if (no == null) { + return null; } - const newEditor = CodeMirror(container, { - value: initialHeaders, - lineNumbers: true, - tabSize: 2, - mode: { - name: "javascript", - json: true - }, - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - foldGutter: true, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: commonKeys - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); + if (op(line, no) && doc.cm) { + regLineChange(doc.cm, no, changeType); + } + return line; + } + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; + height += lines[i2].height; + } + this.height = height; + } + LeafChunk.prototype = { + chunkSize: function () { + return this.lines.length; + }, + // Remove the n lines at offset 'at'. + removeInner: function (at, n) { + for (var i2 = at, e = at + n; i2 < e; ++i2) { + var line = this.lines[i2]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function (lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function (at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i2 = 0; i2 < lines.length; ++i2) { + lines[i2].parent = this; } - }); - newEditor.on("keyup", (editorInstance, event) => { - const { - code, - key, - shiftKey - } = event; - const isLetter = code.startsWith("Key"); - const isNumber = !shiftKey && code.startsWith("Digit"); - if (isLetter || isNumber || key === "_" || key === '"') { - editorInstance.execCommand("autocomplete"); + }, + // Used to iterate over a part of the tree. + iterN: function (at, n, op) { + for (var e = at + n; at < e; ++at) { + if (op(this.lines[at])) { + return true; + } } - }); - setHeaderEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialHeaders, readOnly, setHeaderEditor]); - useSynchronizeOption(headerEditor, "keyMap", keyMap); - useChangeHandler(headerEditor, onEdit, shouldPersistHeaders ? STORAGE_KEY$3 : null, "headers", useHeaderEditor); - useKeyMap(headerEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); - useKeyMap(headerEditor, ["Shift-Ctrl-P"], prettify); - useKeyMap(headerEditor, ["Shift-Ctrl-M"], merge); - return ref; - } - const STORAGE_KEY$3 = "headers"; - const invalidCharacters = Array.from({ - length: 11 - }, (_, i) => { - return String.fromCharCode(8192 + i); - }).concat(["\u2028", "\u2029", " ", " "]); - const sanitizeRegex = new RegExp("[" + invalidCharacters.join("") + "]", "g"); - function normalizeWhitespace(line) { - return line.replace(sanitizeRegex, " "); - } - function useQueryEditor({ - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onClickReference, - onCopyQuery, - onEdit, - readOnly = false - } = {}, caller) { - const { - schema - } = useSchemaContext({ - nonNull: true, - caller: caller || useQueryEditor - }); - const { - externalFragments, - initialQuery, - queryEditor, - setOperationName, - setQueryEditor, - validationRules, - variableEditor, - updateActiveTabValues - } = useEditorContext({ - nonNull: true, - caller: caller || useQueryEditor - }); - const executionContext = useExecutionContext(); - const storage = useStorageContext(); - const explorer = useExplorerContext(); - const plugin = usePluginContext(); - const copy = useCopyQuery({ - caller: caller || useQueryEditor, - onCopyQuery - }); - const merge = useMergeQuery({ - caller: caller || useQueryEditor - }); - const prettify = usePrettifyEditors({ - caller: caller || useQueryEditor - }); - const ref = React.useRef(null); - const codeMirrorRef = React.useRef(); - const onClickReferenceRef = React.useRef(() => {}); - React.useEffect(() => { - onClickReferenceRef.current = reference => { - if (!explorer || !plugin) { - return; } - plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); - switch (reference.kind) { - case "Type": - { - explorer.push({ - name: reference.type.name, - def: reference.type - }); - break; - } - case "Field": - { - explorer.push({ - name: reference.field.name, - def: reference.field - }); - break; + }; + function BranchChunk(children) { + this.children = children; + var size = 0, + height = 0; + for (var i2 = 0; i2 < children.length; ++i2) { + var ch = children[i2]; + size += ch.chunkSize(); + height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + BranchChunk.prototype = { + chunkSize: function () { + return this.size; + }, + removeInner: function (at, n) { + this.size -= n; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), + oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { + this.children.splice(i2--, 1); + child.parent = null; + } + if ((n -= rm) == 0) { + break; + } + at = 0; + } else { + at -= sz; } - case "Argument": - { - if (reference.field) { - explorer.push({ - name: reference.field.name, - def: reference.field - }); + } + if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function (lines) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + this.children[i2].collapse(lines); + } + }, + insertInner: function (at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + var remaining = child.lines.length % 25 + 25; + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); + child.height -= leaf.height; + this.children.splice(++i2, 0, leaf); + leaf.parent = this; + } + child.lines = child.lines.slice(0, remaining); + this.maybeSpill(); } break; } - case "EnumValue": - { - if (reference.type) { - explorer.push({ - name: reference.type.name, - def: reference.type - }); + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function () { + if (this.children.length <= 10) { + return; + } + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function (at, n, op) { + for (var i2 = 0; i2 < this.children.length; ++i2) { + var child = this.children[i2], + sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) { + return true; } - break; + if ((n -= used) == 0) { + break; + } + at = 0; + } else { + at -= sz; } + } + } + }; + var LineWidget = function (doc, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) { + this[opt] = options[opt]; + } + } } - onClickReference == null ? void 0 : onClickReference(reference); + this.doc = doc; + this.node = node; }; - }, [explorer, onClickReference, plugin]); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./comment.cjs.js */ "../../graphiql-react/dist/comment.cjs.js")).then(n => n.comment), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs.js */ "../../graphiql-react/dist/hint.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs2.js */ "../../graphiql-react/dist/lint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info.cjs.js */ "../../graphiql-react/dist/info.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./jump.cjs.js */ "../../graphiql-react/dist/jump.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs.js */ "../../graphiql-react/dist/mode.cjs.js"))]).then(CodeMirror => { - if (!isActive) { + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, + ws = this.line.widgets, + line = this.line, + no = lineNo(line); + if (no == null || !ws) { return; } - codeMirrorRef.current = CodeMirror; - const container = ref.current; - if (!container) { + for (var i2 = 0; i2 < ws.length; ++i2) { + if (ws[i2] == this) { + ws.splice(i2--, 1); + } + } + if (!ws.length) { + line.widgets = null; + } + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + signalLater(cm, "lineWidgetCleared", cm, this, no); + } + }; + LineWidget.prototype.changed = function () { + var this$1$1 = this; + var oldH = this.height, + cm = this.doc.cm, + line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) { return; } - const newEditor = CodeMirror(container, { - value: initialQuery, - lineNumbers: true, - tabSize: 2, - foldGutter: true, - mode: "graphql", - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - lint: { - // @ts-expect-error - schema: void 0, - validationRules: null, - // linting accepts string or FragmentDefinitionNode[] - externalFragments: void 0 - }, - hintOptions: { - // @ts-expect-error - schema: void 0, - closeOnUnfocus: false, - completeSingle: false, - container, - externalFragments: void 0, - autocompleteOptions: { - // for the query editor, restrict to executable type definitions - mode: graphqlLanguageService.GraphQLDocumentMode.EXECUTABLE + if (!lineIsHidden(this.doc, line)) { + updateLineHeight(line, line.height + diff); + } + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + signalLater(cm, "lineWidgetChanged", cm, this$1$1, lineNo(line)); + }); + } + }; + eventMixin(LineWidget); + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < (cm.curOp && cm.curOp.scrollTop || cm.doc.scrollTop)) { + addToScrollTop(cm, diff); + } + } + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) { + cm.display.alignWidgets = true; + } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) { + widgets.push(widget); + } else { + widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); + } + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) { + addToScrollTop(cm, widget.height); } - }, - info: { - schema: void 0, - renderDescription: text => markdown.render(text), - onClick(reference) { - onClickReferenceRef.current(reference); + cm.curOp.forceUpdate = true; + } + return true; + }); + if (cm) { + signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); + } + return widget; + } + var nextMarkerId = 0; + var TextMarker = function (doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { + return; + } + var cm = this.doc.cm, + withOp = cm && !cm.curOp; + if (withOp) { + startOperation(cm); + } + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) { + signalLater(this, "clear", found.from, found.to); + } + } + var min = null, + max = null; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) { + regLineChange(cm, lineNo(line), "text"); + } else if (cm) { + if (span.to != null) { + max = lineNo(line); } - }, - jump: { - schema: void 0, - onClick(reference) { - onClickReferenceRef.current(reference); + if (span.from != null) { + min = lineNo(line); } - }, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: { - ...commonKeys, - "Cmd-S"() {}, - "Ctrl-S"() {} } - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: true, - container - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: true, - container - }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: true, - container - }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: true, - container - }); - }, - "Shift-Alt-Space"() { - newEditor.showHint({ - completeSingle: true, - container - }); + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) { + updateLineHeight(line, textHeight(cm.display)); } - }); - newEditor.on("keyup", (editorInstance, event) => { - if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { - editorInstance.execCommand("autocomplete"); + } + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i$12 = 0; i$12 < this.lines.length; ++i$12) { + var visual = visualLine(this.lines[i$12]), + len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } } - }); - let showingHints = false; - newEditor.on("startCompletion", () => { - showingHints = true; - }); - newEditor.on("endCompletion", () => { - showingHints = false; - }); - newEditor.on("keydown", (editorInstance, event) => { - if (event.key === "Escape" && showingHints) { - event.stopPropagation(); + } + if (min != null && cm && this.collapsed) { + regChange(cm, min, max + 1); + } + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) { + reCheckSelection(cm.doc); } - }); - newEditor.on("beforeChange", (editorInstance, change) => { - var _a; - if (change.origin === "paste") { - const text = change.text.map(normalizeWhitespace); - (_a = change.update) == null ? void 0 : _a.call(change, change.from, change.to, text); + } + if (cm) { + signalLater(cm, "markerCleared", cm, this, min, max); + } + if (withOp) { + endOperation(cm); + } + if (this.parent) { + this.parent.clear(); + } + }; + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") { + side = 1; + } + var from, to; + for (var i2 = 0; i2 < this.lines.length; ++i2) { + var line = this.lines[i2]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) { + return from; + } } - }); - newEditor.documentAST = null; - newEditor.operationName = null; - newEditor.operations = null; - newEditor.variableToType = null; - setQueryEditor(newEditor); - }); - return () => { - isActive = false; + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) { + return to; + } + } + } + return from && { + from, + to + }; }; - }, [editorTheme, initialQuery, readOnly, setQueryEditor]); - useSynchronizeOption(queryEditor, "keyMap", keyMap); - React.useEffect(() => { - if (!queryEditor) { - return; - } - function getAndUpdateOperationFacts(editorInstance) { - var _editorInstance$opera, _editorInstance$opera2, _ref3, _ref4; - var _a; - const operationFacts = graphqlLanguageService.getOperationFacts(schema, editorInstance.getValue()); - const operationName = toolkit.getSelectedOperationName((_editorInstance$opera = editorInstance.operations) !== null && _editorInstance$opera !== void 0 ? _editorInstance$opera : void 0, (_editorInstance$opera2 = editorInstance.operationName) !== null && _editorInstance$opera2 !== void 0 ? _editorInstance$opera2 : void 0, operationFacts == null ? void 0 : operationFacts.operations); - editorInstance.documentAST = (_ref3 = operationFacts == null ? void 0 : operationFacts.documentAST) !== null && _ref3 !== void 0 ? _ref3 : null; - editorInstance.operationName = operationName !== null && operationName !== void 0 ? operationName : null; - editorInstance.operations = (_ref4 = operationFacts == null ? void 0 : operationFacts.operations) !== null && _ref4 !== void 0 ? _ref4 : null; - if (variableEditor) { - variableEditor.state.lint.linterOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; - variableEditor.options.lint.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; - variableEditor.options.hintOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; - (_a = codeMirrorRef.current) == null ? void 0 : _a.signal(variableEditor, "change", variableEditor); - } - return operationFacts ? { - ...operationFacts, - operationName - } : null; - } - const handleChange = debounce(100, editorInstance => { - var _ref5; - const query = editorInstance.getValue(); - storage == null ? void 0 : storage.set(STORAGE_KEY_QUERY, query); - const currentOperationName = editorInstance.operationName; - const operationFacts = getAndUpdateOperationFacts(editorInstance); - if ((operationFacts == null ? void 0 : operationFacts.operationName) !== void 0) { - storage == null ? void 0 : storage.set(STORAGE_KEY_OPERATION_NAME, operationFacts.operationName); - } - onEdit == null ? void 0 : onEdit(query, operationFacts == null ? void 0 : operationFacts.documentAST); - if ((operationFacts == null ? void 0 : operationFacts.operationName) && currentOperationName !== operationFacts.operationName) { - setOperationName(operationFacts.operationName); - } - updateActiveTabValues({ - query, - operationName: (_ref5 = operationFacts == null ? void 0 : operationFacts.operationName) !== null && _ref5 !== void 0 ? _ref5 : null - }); - }); - getAndUpdateOperationFacts(queryEditor); - queryEditor.on("change", handleChange); - return () => queryEditor.off("change", handleChange); - }, [onEdit, queryEditor, schema, setOperationName, storage, variableEditor, updateActiveTabValues]); - useSynchronizeSchema(queryEditor, schema !== null && schema !== void 0 ? schema : null, codeMirrorRef); - useSynchronizeValidationRules(queryEditor, validationRules !== null && validationRules !== void 0 ? validationRules : null, codeMirrorRef); - useSynchronizeExternalFragments(queryEditor, externalFragments, codeMirrorRef); - useCompletion(queryEditor, onClickReference || null, useQueryEditor); - const run = executionContext == null ? void 0 : executionContext.run; - const runAtCursor = React.useCallback(() => { - var _a; - if (!run || !queryEditor || !queryEditor.operations || !queryEditor.hasFocus()) { - run == null ? void 0 : run(); - return; - } - const cursorIndex = queryEditor.indexFromPos(queryEditor.getCursor()); - let operationName; - for (const operation of queryEditor.operations) { - if (operation.loc && operation.loc.start <= cursorIndex && operation.loc.end >= cursorIndex) { - operationName = (_a = operation.name) == null ? void 0 : _a.value; + TextMarker.prototype.changed = function () { + var this$1$1 = this; + var pos = this.find(-1, true), + widget = this, + cm = this.doc.cm; + if (!pos || !cm) { + return; } - } - if (operationName && operationName !== queryEditor.operationName) { - setOperationName(operationName); - } - run(); - }, [queryEditor, run, setOperationName]); - useKeyMap(queryEditor, ["Cmd-Enter", "Ctrl-Enter"], runAtCursor); - useKeyMap(queryEditor, ["Shift-Ctrl-C"], copy); - useKeyMap(queryEditor, ["Shift-Ctrl-P", - // Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to prettify - "Shift-Ctrl-F"], prettify); - useKeyMap(queryEditor, ["Shift-Ctrl-M"], merge); - return ref; - } - function useSynchronizeSchema(editor, schema, codeMirrorRef) { - React.useEffect(() => { - if (!editor) { - return; - } - const didChange = editor.options.lint.schema !== schema; - editor.state.lint.linterOptions.schema = schema; - editor.options.lint.schema = schema; - editor.options.hintOptions.schema = schema; - editor.options.info.schema = schema; - editor.options.jump.schema = schema; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, schema, codeMirrorRef]); - } - function useSynchronizeValidationRules(editor, validationRules, codeMirrorRef) { - React.useEffect(() => { - if (!editor) { - return; - } - const didChange = editor.options.lint.validationRules !== validationRules; - editor.state.lint.linterOptions.validationRules = validationRules; - editor.options.lint.validationRules = validationRules; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, validationRules, codeMirrorRef]); - } - function useSynchronizeExternalFragments(editor, externalFragments, codeMirrorRef) { - const externalFragmentList = React.useMemo(() => [...externalFragments.values()], [externalFragments]); - React.useEffect(() => { - if (!editor) { - return; - } - const didChange = editor.options.lint.externalFragments !== externalFragmentList; - editor.state.lint.linterOptions.externalFragments = externalFragmentList; - editor.options.lint.externalFragments = externalFragmentList; - editor.options.hintOptions.externalFragments = externalFragmentList; - if (didChange && codeMirrorRef.current) { - codeMirrorRef.current.signal(editor, "change", editor); - } - }, [editor, externalFragmentList, codeMirrorRef]); - } - const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/; - const STORAGE_KEY_QUERY = "query"; - const STORAGE_KEY_OPERATION_NAME = "operationName"; - function getDefaultTabState({ - defaultQuery, - defaultHeaders, - headers, - defaultTabs, - query, - variables, - storage, - shouldPersistHeaders - }) { - const storedState = storage == null ? void 0 : storage.get(STORAGE_KEY$2); - try { - if (!storedState) { - throw new Error("Storage for tabs is empty"); - } - const parsed = JSON.parse(storedState); - const headersForHash = shouldPersistHeaders ? headers : void 0; - if (isTabsState(parsed)) { - const expectedHash = hashFromTabContents({ - query, - variables, - headers: headersForHash + runInOp(cm, function () { + var line = pos.line, + lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) { + updateLineHeight(line, line.height + dHeight); + } + } + signalLater(cm, "markerChanged", cm, this$1$1); }); - let matchingTabIndex = -1; - for (let index = 0; index < parsed.tabs.length; index++) { - const tab = parsed.tabs[index]; - tab.hash = hashFromTabContents({ - query: tab.query, - variables: tab.variables, - headers: tab.headers - }); - if (tab.hash === expectedHash) { - matchingTabIndex = index; + }; + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } } - if (matchingTabIndex >= 0) { - parsed.activeTabIndex = matchingTabIndex; - } else { - const operationName = query ? fuzzyExtractOperationName(query) : null; - parsed.tabs.push({ - id: guid(), - hash: expectedHash, - title: operationName || DEFAULT_TITLE, - query, - variables, - headers, - operationName, - response: null - }); - parsed.activeTabIndex = parsed.tabs.length - 1; + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } - return parsed; - } - throw new Error("Storage for tabs is invalid"); - } catch { - return { - activeTabIndex: 0, - tabs: (defaultTabs || [{ - query: query !== null && query !== void 0 ? query : defaultQuery, - variables, - headers: headers !== null && headers !== void 0 ? headers : defaultHeaders - }]).map(createTab) }; - } - } - function isTabsState(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj) && hasNumberKey(obj, "activeTabIndex") && "tabs" in obj && Array.isArray(obj.tabs) && obj.tabs.every(isTabState); - } - function isTabState(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj) && hasStringKey(obj, "id") && hasStringKey(obj, "title") && hasStringOrNullKey(obj, "query") && hasStringOrNullKey(obj, "variables") && hasStringOrNullKey(obj, "headers") && hasStringOrNullKey(obj, "operationName") && hasStringOrNullKey(obj, "response"); - } - function hasNumberKey(obj, key) { - return key in obj && typeof obj[key] === "number"; - } - function hasStringKey(obj, key) { - return key in obj && typeof obj[key] === "string"; - } - function hasStringOrNullKey(obj, key) { - return key in obj && (typeof obj[key] === "string" || obj[key] === null); - } - function useSynchronizeActiveTabValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor - }) { - return React.useCallback(state => { - var _ref6, _ref7, _ref8, _ref9, _ref10; - const query = (_ref6 = queryEditor == null ? void 0 : queryEditor.getValue()) !== null && _ref6 !== void 0 ? _ref6 : null; - const variables = (_ref7 = variableEditor == null ? void 0 : variableEditor.getValue()) !== null && _ref7 !== void 0 ? _ref7 : null; - const headers = (_ref8 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref8 !== void 0 ? _ref8 : null; - const operationName = (_ref9 = queryEditor == null ? void 0 : queryEditor.operationName) !== null && _ref9 !== void 0 ? _ref9 : null; - const response = (_ref10 = responseEditor == null ? void 0 : responseEditor.getValue()) !== null && _ref10 !== void 0 ? _ref10 : null; - return setPropertiesInActiveTab(state, { - query, - variables, - headers, - response, - operationName - }); - }, [queryEditor, variableEditor, headerEditor, responseEditor]); - } - function serializeTabState(tabState, shouldPersistHeaders = false) { - return JSON.stringify(tabState, (key, value) => key === "hash" || key === "response" || !shouldPersistHeaders && key === "headers" ? null : value); - } - function useStoreTabs({ - storage, - shouldPersistHeaders - }) { - const store = React.useMemo(() => debounce(500, value => { - storage == null ? void 0 : storage.set(STORAGE_KEY$2, value); - }), [storage]); - return React.useCallback(currentState => { - store(serializeTabState(currentState, shouldPersistHeaders)); - }, [shouldPersistHeaders, store]); - } - function useSetEditorValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor - }) { - return React.useCallback(({ - query, - variables, - headers, - response - }) => { - queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); - variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); - headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); - responseEditor == null ? void 0 : responseEditor.setValue(response !== null && response !== void 0 ? response : ""); - }, [headerEditor, queryEditor, responseEditor, variableEditor]); - } - function createTab({ - query = null, - variables = null, - headers = null - } = {}) { - return { - id: guid(), - hash: hashFromTabContents({ - query, - variables, - headers - }), - title: query && fuzzyExtractOperationName(query) || DEFAULT_TITLE, - query, - variables, - headers, - operationName: null, - response: null - }; - } - function setPropertiesInActiveTab(state, partialTab) { - return { - ...state, - tabs: state.tabs.map((tab, index) => { - if (index !== state.activeTabIndex) { - return tab; + eventMixin(TextMarker); + function markText(doc, from, to, options, type) { + if (options && options.shared) { + return markTextShared(doc, from, to, options, type); } - const newTab = { - ...tab, - ...partialTab - }; - return { - ...newTab, - hash: hashFromTabContents(newTab), - title: newTab.operationName || (newTab.query ? fuzzyExtractOperationName(newTab.query) : void 0) || DEFAULT_TITLE - }; - }) - }; - } - function guid() { - const s4 = () => { - return Math.floor((1 + Math.random()) * 65536).toString(16).slice(1); - }; - return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; - } - function hashFromTabContents(args) { - var _args$query, _args$variables, _args$headers; - return [(_args$query = args.query) !== null && _args$query !== void 0 ? _args$query : "", (_args$variables = args.variables) !== null && _args$variables !== void 0 ? _args$variables : "", (_args$headers = args.headers) !== null && _args$headers !== void 0 ? _args$headers : ""].join("|"); - } - function fuzzyExtractOperationName(str) { - var _ref11; - const regex = /^(?!#).*(query|subscription|mutation)\s+([a-zA-Z0-9_]+)/m; - const match = regex.exec(str); - return (_ref11 = match == null ? void 0 : match[2]) !== null && _ref11 !== void 0 ? _ref11 : null; - } - function clearHeadersFromTabs(storage) { - const persistedTabs = storage == null ? void 0 : storage.get(STORAGE_KEY$2); - if (persistedTabs) { - const parsedTabs = JSON.parse(persistedTabs); - storage == null ? void 0 : storage.set(STORAGE_KEY$2, JSON.stringify(parsedTabs, (key, value) => key === "headers" ? null : value)); - } - } - const DEFAULT_TITLE = ""; - const STORAGE_KEY$2 = "tabState"; - function useVariableEditor({ - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP, - onClickReference, - onEdit, - readOnly = false - } = {}, caller) { - const { - initialVariables, - variableEditor, - setVariableEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useVariableEditor - }); - const executionContext = useExecutionContext(); - const merge = useMergeQuery({ - caller: caller || useVariableEditor - }); - const prettify = usePrettifyEditors({ - caller: caller || useVariableEditor - }); - const ref = React.useRef(null); - const codeMirrorRef = React.useRef(); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs2.js */ "../../graphiql-react/dist/hint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs3.js */ "../../graphiql-react/dist/lint.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs2.js */ "../../graphiql-react/dist/mode.cjs2.js"))]).then(CodeMirror => { - if (!isActive) { - return; + if (doc.cm && !doc.cm.curOp) { + return operation(doc.cm, markText)(doc, from, to, options, type); + } + var marker = new TextMarker(doc, type), + diff = cmp(from, to); + if (options) { + copyObj(options, marker, false); + } + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { + return marker; + } + if (marker.replacedWith) { + marker.collapsed = true; + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) { + marker.widgetNode.setAttribute("cm-ignore-events", "true"); + } + if (options.insertLeft) { + marker.widgetNode.insertLeft = true; + } } - codeMirrorRef.current = CodeMirror; - const container = ref.current; - if (!container) { - return; + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { + throw new Error("Inserting collapsed marker partially overlapping an existing one"); + } + seeCollapsedSpans(); } - const newEditor = CodeMirror(container, { - value: initialVariables, - lineNumbers: true, - tabSize: 2, - mode: "graphql-variables", - theme: editorTheme, - autoCloseBrackets: true, - matchBrackets: true, - showCursorWhenSelecting: true, - readOnly: readOnly ? "nocursor" : false, - foldGutter: true, - lint: { - // @ts-expect-error - variableToType: void 0 - }, - hintOptions: { - closeOnUnfocus: false, - completeSingle: false, - container, - // @ts-expect-error - variableToType: void 0 - }, - gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - extraKeys: commonKeys - }); - newEditor.addKeyMap({ - "Cmd-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Ctrl-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Alt-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); - }, - "Shift-Space"() { - newEditor.showHint({ - completeSingle: false, - container - }); + if (marker.addToHistory) { + addChangeToHistory(doc, { + from, + to, + origin: "markText" + }, doc.sel, NaN); + } + var curLine = from.line, + cm = doc.cm, + updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { + updateMaxLine = true; } - }); - newEditor.on("keyup", (editorInstance, event) => { - const { - code, - key, - shiftKey - } = event; - const isLetter = code.startsWith("Key"); - const isNumber = !shiftKey && code.startsWith("Digit"); - if (isLetter || isNumber || key === "_" || key === '"') { - editorInstance.execCommand("autocomplete"); + if (marker.collapsed && curLine != from.line) { + updateLineHeight(line, 0); } + addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); + ++curLine; }); - setVariableEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialVariables, readOnly, setVariableEditor]); - useSynchronizeOption(variableEditor, "keyMap", keyMap); - useChangeHandler(variableEditor, onEdit, STORAGE_KEY$1, "variables", useVariableEditor); - useCompletion(variableEditor, onClickReference || null, useVariableEditor); - useKeyMap(variableEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); - useKeyMap(variableEditor, ["Shift-Ctrl-P"], prettify); - useKeyMap(variableEditor, ["Shift-Ctrl-M"], merge); - return ref; - } - const STORAGE_KEY$1 = "variables"; - const EditorContext = createNullableContext("EditorContext"); - function EditorContextProvider(props) { - const storage = useStorageContext(); - const [headerEditor, setHeaderEditor] = React.useState(null); - const [queryEditor, setQueryEditor] = React.useState(null); - const [responseEditor, setResponseEditor] = React.useState(null); - const [variableEditor, setVariableEditor] = React.useState(null); - const [shouldPersistHeaders, setShouldPersistHeadersInternal] = React.useState(() => { - const isStored = (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) !== null; - return props.shouldPersistHeaders !== false && isStored ? (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) === "true" : Boolean(props.shouldPersistHeaders); - }); - useSynchronizeValue(headerEditor, props.headers); - useSynchronizeValue(queryEditor, props.query); - useSynchronizeValue(responseEditor, props.response); - useSynchronizeValue(variableEditor, props.variables); - const storeTabs = useStoreTabs({ - storage, - shouldPersistHeaders - }); - const [initialState] = React.useState(() => { - var _ref12, _props$query, _ref13, _props$variables, _ref14, _props$headers, _props$response, _ref15, _ref16; - const query = (_ref12 = (_props$query = props.query) !== null && _props$query !== void 0 ? _props$query : storage == null ? void 0 : storage.get(STORAGE_KEY_QUERY)) !== null && _ref12 !== void 0 ? _ref12 : null; - const variables = (_ref13 = (_props$variables = props.variables) !== null && _props$variables !== void 0 ? _props$variables : storage == null ? void 0 : storage.get(STORAGE_KEY$1)) !== null && _ref13 !== void 0 ? _ref13 : null; - const headers = (_ref14 = (_props$headers = props.headers) !== null && _props$headers !== void 0 ? _props$headers : storage == null ? void 0 : storage.get(STORAGE_KEY$3)) !== null && _ref14 !== void 0 ? _ref14 : null; - const response = (_props$response = props.response) !== null && _props$response !== void 0 ? _props$response : ""; - const tabState2 = getDefaultTabState({ - query, - variables, - headers, - defaultTabs: props.defaultTabs, - defaultQuery: props.defaultQuery || DEFAULT_QUERY, - defaultHeaders: props.defaultHeaders, - storage, - shouldPersistHeaders - }); - storeTabs(tabState2); - return { - query: (_ref15 = query !== null && query !== void 0 ? query : tabState2.activeTabIndex === 0 ? tabState2.tabs[0].query : null) !== null && _ref15 !== void 0 ? _ref15 : "", - variables: variables !== null && variables !== void 0 ? variables : "", - headers: (_ref16 = headers !== null && headers !== void 0 ? headers : props.defaultHeaders) !== null && _ref16 !== void 0 ? _ref16 : "", - response, - tabState: tabState2 - }; - }); - const [tabState, setTabState] = React.useState(initialState.tabState); - const setShouldPersistHeaders = React.useCallback(persist => { - if (persist) { - var _ref17; - storage == null ? void 0 : storage.set(STORAGE_KEY$3, (_ref17 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref17 !== void 0 ? _ref17 : ""); - const serializedTabs = serializeTabState(tabState, true); - storage == null ? void 0 : storage.set(STORAGE_KEY$2, serializedTabs); - } else { - storage == null ? void 0 : storage.set(STORAGE_KEY$3, ""); - clearHeadersFromTabs(storage); - } - setShouldPersistHeadersInternal(persist); - storage == null ? void 0 : storage.set(PERSIST_HEADERS_STORAGE_KEY, persist.toString()); - }, [storage, tabState, headerEditor]); - const lastShouldPersistHeadersProp = React.useRef(); - React.useEffect(() => { - const propValue = Boolean(props.shouldPersistHeaders); - if ((lastShouldPersistHeadersProp == null ? void 0 : lastShouldPersistHeadersProp.current) !== propValue) { - setShouldPersistHeaders(propValue); - lastShouldPersistHeadersProp.current = propValue; - } - }, [props.shouldPersistHeaders, setShouldPersistHeaders]); - const synchronizeActiveTabValues = useSynchronizeActiveTabValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor - }); - const setEditorValues = useSetEditorValues({ - queryEditor, - variableEditor, - headerEditor, - responseEditor - }); - const { - onTabChange, - defaultHeaders, - children - } = props; - const addTab = React.useCallback(() => { - setTabState(current => { - const updatedValues = synchronizeActiveTabValues(current); - const updated = { - tabs: [...updatedValues.tabs, createTab({ - headers: defaultHeaders - })], - activeTabIndex: updatedValues.tabs.length - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [defaultHeaders, onTabChange, setEditorValues, storeTabs, synchronizeActiveTabValues]); - const changeTab = React.useCallback(index => { - setTabState(current => { - const updated = { - ...current, - activeTabIndex: index - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, setEditorValues, storeTabs]); - const moveTab = React.useCallback(newOrder => { - setTabState(current => { - const activeTab = current.tabs[current.activeTabIndex]; - const updated = { - tabs: newOrder, - activeTabIndex: newOrder.indexOf(activeTab) - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, setEditorValues, storeTabs]); - const closeTab = React.useCallback(index => { - setTabState(current => { - const updated = { - tabs: current.tabs.filter((_tab, i) => index !== i), - activeTabIndex: Math.max(current.activeTabIndex - 1, 0) - }; - storeTabs(updated); - setEditorValues(updated.tabs[updated.activeTabIndex]); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, setEditorValues, storeTabs]); - const updateActiveTabValues = React.useCallback(partialTab => { - setTabState(current => { - const updated = setPropertiesInActiveTab(current, partialTab); - storeTabs(updated); - onTabChange == null ? void 0 : onTabChange(updated); - return updated; - }); - }, [onTabChange, storeTabs]); - const { - onEditOperationName - } = props; - const setOperationName = React.useCallback(operationName => { - if (!queryEditor) { - return; + if (marker.collapsed) { + doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { + updateLineHeight(line, 0); + } + }); + } + if (marker.clearOnEnter) { + on(marker, "beforeCursorEnter", function () { + return marker.clear(); + }); + } + if (marker.readOnly) { + seeReadOnlySpans(); + if (doc.history.done.length || doc.history.undone.length) { + doc.clearHistory(); + } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + if (updateMaxLine) { + cm.curOp.updateMaxLine = true; + } + if (marker.collapsed) { + regChange(cm, from.line, to.line + 1); + } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { + for (var i2 = from.line; i2 <= to.line; i2++) { + regLineChange(cm, i2, "text"); + } + } + if (marker.atomic) { + reCheckSelection(cm.doc); + } + signalLater(cm, "markerAdded", cm, marker); + } + return marker; } - queryEditor.operationName = operationName; - updateActiveTabValues({ - operationName - }); - onEditOperationName == null ? void 0 : onEditOperationName(operationName); - }, [onEditOperationName, queryEditor, updateActiveTabValues]); - const externalFragments = React.useMemo(() => { - const map = /* @__PURE__ */new Map(); - if (Array.isArray(props.externalFragments)) { - for (const fragment of props.externalFragments) { - map.set(fragment.name.value, fragment); + var SharedTextMarker = function (markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i2 = 0; i2 < markers.length; ++i2) { + markers[i2].parent = this; } - } else if (typeof props.externalFragments === "string") { - graphql.visit(graphql.parse(props.externalFragments, {}), { - FragmentDefinition(fragment) { - map.set(fragment.name.value, fragment); + }; + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { + return; + } + this.explicitlyCleared = true; + for (var i2 = 0; i2 < this.markers.length; ++i2) { + this.markers[i2].clear(); + } + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj); + }; + eventMixin(SharedTextMarker); + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], + primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc2) { + if (widget) { + options.widgetNode = widget.cloneNode(true); + } + markers.push(markText(doc2, clipPos(doc2, from), clipPos(doc2, to), options, type)); + for (var i2 = 0; i2 < doc2.linked.length; ++i2) { + if (doc2.linked[i2].isParent) { + return; + } } + primary = lst(markers); }); - } else if (props.externalFragments) { - throw new Error("The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects."); - } - return map; - }, [props.externalFragments]); - const validationRules = React.useMemo(() => props.validationRules || [], [props.validationRules]); - const value = React.useMemo(() => ({ - ...tabState, - addTab, - changeTab, - moveTab, - closeTab, - updateActiveTabValues, - headerEditor, - queryEditor, - responseEditor, - variableEditor, - setHeaderEditor, - setQueryEditor, - setResponseEditor, - setVariableEditor, - setOperationName, - initialQuery: initialState.query, - initialVariables: initialState.variables, - initialHeaders: initialState.headers, - initialResponse: initialState.response, - externalFragments, - validationRules, - shouldPersistHeaders, - setShouldPersistHeaders - }), [tabState, addTab, changeTab, moveTab, closeTab, updateActiveTabValues, headerEditor, queryEditor, responseEditor, variableEditor, setOperationName, initialState, externalFragments, validationRules, shouldPersistHeaders, setShouldPersistHeaders]); - return /* @__PURE__ */jsxRuntime.jsx(EditorContext.Provider, { - value, - children - }); - } - const useEditorContext = createContextHook(EditorContext); - const PERSIST_HEADERS_STORAGE_KEY = "shouldPersistHeaders"; - const DEFAULT_QUERY = `# Welcome to GraphiQL - # - # GraphiQL is an in-browser tool for writing, validating, and - # testing GraphQL queries. - # - # Type queries into this side of the screen, and you will see intelligent - # typeaheads aware of the current GraphQL type schema and live syntax and - # validation errors highlighted within the text. - # - # GraphQL queries typically start with a "{" character. Lines that start - # with a # are ignored. - # - # An example GraphQL query might look like: - # - # { - # field(arg: "value") { - # subField - # } - # } - # - # Keyboard shortcuts: - # - # Prettify query: Shift-Ctrl-P (or press the prettify button) - # - # Merge fragments: Shift-Ctrl-M (or press the merge button) - # - # Run Query: Ctrl-Enter (or press the play button) - # - # Auto Complete: Ctrl-Space (or just start typing) - # - - `; - function HeaderEditor({ - isHidden, - ...hookArgs - }) { - const { - headerEditor - } = useEditorContext({ - nonNull: true, - caller: HeaderEditor - }); - const ref = useHeaderEditor(hookArgs, HeaderEditor); - React.useEffect(() => { - if (!isHidden) { - headerEditor == null ? void 0 : headerEditor.refresh(); - } - }, [headerEditor, isHidden]); - return /* @__PURE__ */jsxRuntime.jsx("div", { - className: clsx.clsx("graphiql-editor", isHidden && "hidden"), - ref - }); - } - function ImagePreview(props) { - var _a; - const [dimensions, setDimensions] = React.useState({ - width: null, - height: null - }); - const [mime, setMime] = React.useState(null); - const ref = React.useRef(null); - const src = (_a = tokenToURL(props.token)) == null ? void 0 : _a.href; - React.useEffect(() => { - if (!ref.current) { - return; + return new SharedTextMarker(markers, primary); } - if (!src) { - setDimensions({ - width: null, - height: null + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { + return m.parent; }); - setMime(null); - return; } - fetch(src, { - method: "HEAD" - }).then(response => { - setMime(response.headers.get("Content-Type")); - }).catch(() => { - setMime(null); - }); - }, [src]); - const dims = dimensions.width !== null && dimensions.height !== null ? /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [dimensions.width, "x", dimensions.height, mime === null ? null : " " + mime] - }) : null; - return /* @__PURE__ */jsxRuntime.jsxs("div", { - children: [/* @__PURE__ */jsxRuntime.jsx("img", { - onLoad: () => { - var _ref18, _ref19; - var _a2, _b; - setDimensions({ - width: (_ref18 = (_a2 = ref.current) == null ? void 0 : _a2.naturalWidth) !== null && _ref18 !== void 0 ? _ref18 : null, - height: (_ref19 = (_b = ref.current) == null ? void 0 : _b.naturalHeight) !== null && _ref19 !== void 0 ? _ref19 : null + function copySharedMarkers(doc, markers) { + for (var i2 = 0; i2 < markers.length; i2++) { + var marker = markers[i2], + pos = marker.find(); + var mFrom = doc.clipPos(pos.from), + mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + function detachSharedMarkers(markers) { + var loop = function (i3) { + var marker = markers[i3], + linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { + return linked.push(d); + }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + }; + for (var i2 = 0; i2 < markers.length; i2++) loop(i2); + } + var nextDocId = 0; + var Doc = function (text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { + return new Doc(text, mode, firstLine, lineSep, direction); + } + if (firstLine == null) { + firstLine = 0; + } + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.modeFrontier = this.highlightFrontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.direction = direction == "rtl" ? "rtl" : "ltr"; + this.extend = false; + if (typeof text == "string") { + text = this.splitLines(text); + } + updateDoc(this, { + from: start, + to: start, + text + }); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function (from, to, op) { + if (op) { + this.iterN(from - this.first, to - from, op); + } else { + this.iterN(this.first, this.first + this.size, from); + } + }, + // Non-public interface for adding and removing lines. + insert: function (at, lines) { + var height = 0; + for (var i2 = 0; i2 < lines.length; ++i2) { + height += lines[i2].height; + } + this.insertInner(at - this.first, lines, height); + }, + remove: function (at, n) { + this.removeInner(at - this.first, n); + }, + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + getValue: function (lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) { + return lines; + } + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function (code) { + var top = Pos(this.first, 0), + last = this.first + this.size - 1; + makeChange(this, { + from: top, + to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), + origin: "setValue", + full: true + }, true); + if (this.cm) { + scrollToCoords(this.cm, 0, 0); + } + setSelection(this, simpleSelection(top), sel_dontScroll); + }), + replaceRange: function (code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function (from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) { + return lines; + } + if (lineSep === "") { + return lines.join(""); + } + return lines.join(lineSep || this.lineSeparator()); + }, + getLine: function (line) { + var l = this.getLineHandle(line); + return l && l.text; + }, + getLineHandle: function (line) { + if (isLine(this, line)) { + return getLine(this, line); + } + }, + getLineNumber: function (line) { + return lineNo(line); + }, + getLineHandleVisualStart: function (line) { + if (typeof line == "number") { + line = getLine(this, line); + } + return visualLine(line); + }, + lineCount: function () { + return this.size; + }, + firstLine: function () { + return this.first; + }, + lastLine: function () { + return this.first + this.size - 1; + }, + clipPos: function (pos) { + return clipPos(this, pos); + }, + getCursor: function (start) { + var range2 = this.sel.primary(), + pos; + if (start == null || start == "head") { + pos = range2.head; + } else if (start == "anchor") { + pos = range2.anchor; + } else if (start == "end" || start == "to" || start === false) { + pos = range2.to(); + } else { + pos = range2.from(); + } + return pos; + }, + listSelections: function () { + return this.sel.ranges; + }, + somethingSelected: function () { + return this.sel.somethingSelected(); + }, + setCursor: docMethodOp(function (line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function (anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function (head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function (heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function (f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function (ranges, primary, options) { + if (!ranges.length) { + return; + } + var out = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + out[i2] = new Range(clipPos(this, ranges[i2].anchor), clipPos(this, ranges[i2].head || ranges[i2].anchor)); + } + if (primary == null) { + primary = Math.min(ranges.length - 1, this.sel.primIndex); + } + setSelection(this, normalizeSelection(this.cm, out, primary), options); + }), + addSelection: docMethodOp(function (anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); + }), + getSelection: function (lineSep) { + var ranges = this.sel.ranges, + lines; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) { + return lines; + } else { + return lines.join(lineSep || this.lineSeparator()); + } + }, + getSelections: function (lineSep) { + var parts = [], + ranges = this.sel.ranges; + for (var i2 = 0; i2 < ranges.length; i2++) { + var sel = getBetween(this, ranges[i2].from(), ranges[i2].to()); + if (lineSep !== false) { + sel = sel.join(lineSep || this.lineSeparator()); + } + parts[i2] = sel; + } + return parts; + }, + replaceSelection: function (code, collapse, origin) { + var dup = []; + for (var i2 = 0; i2 < this.sel.ranges.length; i2++) { + dup[i2] = code; + } + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function (code, collapse, origin) { + var changes = [], + sel = this.sel; + for (var i2 = 0; i2 < sel.ranges.length; i2++) { + var range2 = sel.ranges[i2]; + changes[i2] = { + from: range2.from(), + to: range2.to(), + text: this.splitLines(code[i2]), + origin + }; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i$12 = changes.length - 1; i$12 >= 0; i$12--) { + makeChange(this, changes[i$12]); + } + if (newSel) { + setSelectionReplaceHistory(this, newSel); + } else if (this.cm) { + ensureCursorVisible(this.cm); + } + }), + undo: docMethodOp(function () { + makeChangeFromHistory(this, "undo"); + }), + redo: docMethodOp(function () { + makeChangeFromHistory(this, "redo"); + }), + undoSelection: docMethodOp(function () { + makeChangeFromHistory(this, "undo", true); + }), + redoSelection: docMethodOp(function () { + makeChangeFromHistory(this, "redo", true); + }), + setExtending: function (val) { + this.extend = val; + }, + getExtending: function () { + return this.extend; + }, + historySize: function () { + var hist = this.history, + done = 0, + undone = 0; + for (var i2 = 0; i2 < hist.done.length; i2++) { + if (!hist.done[i2].ranges) { + ++done; + } + } + for (var i$12 = 0; i$12 < hist.undone.length; i$12++) { + if (!hist.undone[i$12].ranges) { + ++undone; + } + } + return { + undo: done, + redo: undone + }; + }, + clearHistory: function () { + var this$1$1 = this; + this.history = new History(this.history); + linkedDocs(this, function (doc) { + return doc.history = this$1$1.history; + }, true); + }, + markClean: function () { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function (forceSplit) { + if (forceSplit) { + this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; + } + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + getHistory: function () { + return { + done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone) + }; + }, + setHistory: function (histData) { + var hist = this.history = new History(this.history); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + setGutterMarker: docMethodOp(function (line, gutterID, value) { + return changeLine(this, line, "gutter", function (line2) { + var markers = line2.gutterMarkers || (line2.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) { + line2.gutterMarkers = null; + } + return true; + }); + }), + clearGutter: docMethodOp(function (gutterID) { + var this$1$1 = this; + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null; + if (isEmpty(line.gutterMarkers)) { + line.gutterMarkers = null; + } + return true; + }); + } + }); + }), + lineInfo: function (line) { + var n; + if (typeof line == "number") { + if (!isLine(this, line)) { + return null; + } + n = line; + line = getLine(this, line); + if (!line) { + return null; + } + } else { + n = lineNo(line); + if (n == null) { + return null; + } + } + return { + line: n, + handle: line, + text: line.text, + gutterMarkers: line.gutterMarkers, + textClass: line.textClass, + bgClass: line.bgClass, + wrapClass: line.wrapClass, + widgets: line.widgets + }; + }, + addLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop2]) { + line[prop2] = cls; + } else if (classTest(cls).test(line[prop2])) { + return false; + } else { + line[prop2] += " " + cls; + } + return true; + }); + }), + removeLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop2 = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop2]; + if (!cur) { + return false; + } else if (cls == null) { + line[prop2] = null; + } else { + var found = cur.match(classTest(cls)); + if (!found) { + return false; + } + var end = found.index + found[0].length; + line[prop2] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + addLineWidget: docMethodOp(function (handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function (widget) { + widget.clear(); + }, + markText: function (from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); + }, + setBookmark: function (pos, options) { + var realOpts = { + replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, + shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents + }; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function (pos) { + pos = clipPos(this, pos); + var markers = [], + spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; ++i2) { + var span = spans[i2]; + if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { + markers.push(span.marker.parent || span.marker); + } + } + } + return markers; + }, + findMarks: function (from, to, filter) { + from = clipPos(this, from); + to = clipPos(this, to); + var found = [], + lineNo2 = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { + for (var i2 = 0; i2 < spans.length; i2++) { + var span = spans[i2]; + if (!(span.to != null && lineNo2 == from.line && from.ch >= span.to || span.from == null && lineNo2 != from.line || span.from != null && lineNo2 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { + found.push(span.marker.parent || span.marker); + } + } + } + ++lineNo2; + }); + return found; + }, + getAllMarks: function () { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { + for (var i2 = 0; i2 < sps.length; ++i2) { + if (sps[i2].from != null) { + markers.push(sps[i2].marker); + } + } + } }); + return markers; }, - ref, - src - }), dims] - }); - } - ImagePreview.shouldRender = function shouldRender(token) { - const url = tokenToURL(token); - return url ? isImageURL(url) : false; - }; - function tokenToURL(token) { - if (token.type !== "string") { - return; - } - const value = token.string.slice(1).slice(0, -1).trim(); - try { - const { - location - } = window; - return new URL(value, location.protocol + "//" + location.host); - } catch { - return; - } - } - function isImageURL(url) { - return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname); - } - function QueryEditor(props) { - const ref = useQueryEditor(props, QueryEditor); - return /* @__PURE__ */jsxRuntime.jsx("div", { - className: "graphiql-editor", - ref - }); - } - function useResponseEditor({ - responseTooltip, - editorTheme = DEFAULT_EDITOR_THEME, - keyMap = DEFAULT_KEY_MAP - } = {}, caller) { - const { - fetchError, - validationErrors - } = useSchemaContext({ - nonNull: true, - caller: caller || useResponseEditor - }); - const { - initialResponse, - responseEditor, - setResponseEditor - } = useEditorContext({ - nonNull: true, - caller: caller || useResponseEditor - }); - const ref = React.useRef(null); - const responseTooltipRef = React.useRef(responseTooltip); - React.useEffect(() => { - responseTooltipRef.current = responseTooltip; - }, [responseTooltip]); - React.useEffect(() => { - let isActive = true; - void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), - // @ts-expect-error - Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs3.js */ "../../graphiql-react/dist/mode.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"))], { - useCommonAddons: false - }).then(CodeMirror => { - if (!isActive) { - return; - } - const tooltipDiv = document.createElement("div"); - CodeMirror.registerHelper("info", "graphql-results", (token, _options, _cm, pos) => { - const infoElements = []; - const ResponseTooltipComponent = responseTooltipRef.current; - if (ResponseTooltipComponent) { - infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ResponseTooltipComponent, { - pos, - token - })); + posFromIndex: function (off2) { + var ch, + lineNo2 = this.first, + sepSize = this.lineSeparator().length; + this.iter(function (line) { + var sz = line.text.length + sepSize; + if (sz > off2) { + ch = off2; + return true; + } + off2 -= sz; + ++lineNo2; + }); + return clipPos(this, Pos(lineNo2, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) { + return 0; } - if (ImagePreview.shouldRender(token)) { - infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ImagePreview, { - token - }, "image-preview")); + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + sepSize; + }); + return index; + }, + copy: function (copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); + doc.scrollTop = this.scrollTop; + doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + linkedDoc: function (options) { + if (!options) { + options = {}; } - if (!infoElements.length) { - ReactDOM.unmountComponentAtNode(tooltipDiv); - return null; + var from = this.first, + to = this.first + this.size; + if (options.from != null && options.from > from) { + from = options.from; } - ReactDOM.render(infoElements, tooltipDiv); - return tooltipDiv; - }); - const container = ref.current; - if (!container) { - return; - } - const newEditor = CodeMirror(container, { - value: initialResponse, - lineWrapping: true, - readOnly: true, - theme: editorTheme, - mode: "graphql-results", - foldGutter: true, - gutters: ["CodeMirror-foldgutter"], - // @ts-expect-error - info: true, - extraKeys: commonKeys - }); - setResponseEditor(newEditor); - }); - return () => { - isActive = false; - }; - }, [editorTheme, initialResponse, setResponseEditor]); - useSynchronizeOption(responseEditor, "keyMap", keyMap); - React.useEffect(() => { - if (fetchError) { - responseEditor == null ? void 0 : responseEditor.setValue(fetchError); - } - if (validationErrors.length > 0) { - responseEditor == null ? void 0 : responseEditor.setValue(toolkit.formatError(validationErrors)); - } - }, [responseEditor, fetchError, validationErrors]); - return ref; - } - function ResponseEditor(props) { - const ref = useResponseEditor(props, ResponseEditor); - return /* @__PURE__ */jsxRuntime.jsx("section", { - className: "result-window", - "aria-label": "Result Window", - "aria-live": "polite", - "aria-atomic": "true", - ref - }); - } - function VariableEditor({ - isHidden, - ...hookArgs - }) { - const { - variableEditor - } = useEditorContext({ - nonNull: true, - caller: VariableEditor - }); - const ref = useVariableEditor(hookArgs, VariableEditor); - React.useEffect(() => { - if (variableEditor && !isHidden) { - variableEditor.refresh(); - } - }, [variableEditor, isHidden]); - return /* @__PURE__ */jsxRuntime.jsx("div", { - className: clsx.clsx("graphiql-editor", isHidden && "hidden"), - ref - }); - } - function GraphiQLProvider({ - children, - dangerouslyAssumeSchemaIsValid, - defaultQuery, - defaultHeaders, - defaultTabs, - externalFragments, - fetcher, - getDefaultFieldNames, - headers, - inputValueDeprecation, - introspectionQueryName, - maxHistoryLength, - onEditOperationName, - onSchemaChange, - onTabChange, - onTogglePluginVisibility, - operationName, - plugins, - query, - response, - schema, - schemaDescription, - shouldPersistHeaders, - storage, - validationRules, - variables, - visiblePlugin - }) { - return /* @__PURE__ */jsxRuntime.jsx(StorageContextProvider, { - storage, - children: /* @__PURE__ */jsxRuntime.jsx(HistoryContextProvider, { - maxHistoryLength, - children: /* @__PURE__ */jsxRuntime.jsx(EditorContextProvider, { - defaultQuery, - defaultHeaders, - defaultTabs, - externalFragments, - headers, - onEditOperationName, - onTabChange, - query, - response, - shouldPersistHeaders, - validationRules, - variables, - children: /* @__PURE__ */jsxRuntime.jsx(SchemaContextProvider, { - dangerouslyAssumeSchemaIsValid, - fetcher, - inputValueDeprecation, - introspectionQueryName, - onSchemaChange, - schema, - schemaDescription, - children: /* @__PURE__ */jsxRuntime.jsx(ExecutionContextProvider, { - getDefaultFieldNames, - fetcher, - operationName, - children: /* @__PURE__ */jsxRuntime.jsx(ExplorerContextProvider, { - children: /* @__PURE__ */jsxRuntime.jsx(PluginContextProvider, { - onTogglePluginVisibility, - plugins, - visiblePlugin, - children - }) - }) - }) - }) - }) - }) - }); - } - function useTheme() { - const storageContext = useStorageContext(); - const [theme, setThemeInternal] = React.useState(() => { - if (!storageContext) { - return null; - } - const stored = storageContext.get(STORAGE_KEY); - switch (stored) { - case "light": - return "light"; - case "dark": - return "dark"; - default: - if (typeof stored === "string") { - storageContext.set(STORAGE_KEY, ""); + if (options.to != null && options.to < to) { + to = options.to; } - return null; - } - }); - React.useLayoutEffect(() => { - if (typeof window === "undefined") { - return; - } - document.body.classList.remove("graphiql-light", "graphiql-dark"); - if (theme) { - document.body.classList.add(`graphiql-${theme}`); - } - }, [theme]); - const setTheme = React.useCallback(newTheme => { - storageContext == null ? void 0 : storageContext.set(STORAGE_KEY, newTheme || ""); - setThemeInternal(newTheme); - }, [storageContext]); - return React.useMemo(() => ({ - theme, - setTheme - }), [theme, setTheme]); - } - const STORAGE_KEY = "theme"; - function useDragResize({ - defaultSizeRelation = DEFAULT_FLEX, - direction, - initiallyHidden, - onHiddenElementChange, - sizeThresholdFirst = 100, - sizeThresholdSecond = 100, - storageKey - }) { - const storage = useStorageContext(); - const store = React.useMemo(() => debounce(500, value => { - if (storageKey) { - storage == null ? void 0 : storage.set(storageKey, value); - } - }), [storage, storageKey]); - const [hiddenElement, setHiddenElement] = React.useState(() => { - const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)); - if (storedValue === HIDE_FIRST || initiallyHidden === "first") { - return "first"; - } - if (storedValue === HIDE_SECOND || initiallyHidden === "second") { - return "second"; - } - return null; - }); - const setHiddenElementWithCallback = React.useCallback(element => { - if (element !== hiddenElement) { - setHiddenElement(element); - onHiddenElementChange == null ? void 0 : onHiddenElementChange(element); - } - }, [hiddenElement, onHiddenElementChange]); - const firstRef = React.useRef(null); - const dragBarRef = React.useRef(null); - const secondRef = React.useRef(null); - const defaultFlexRef = React.useRef(`${defaultSizeRelation}`); - React.useLayoutEffect(() => { - const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)) || defaultFlexRef.current; - if (firstRef.current) { - firstRef.current.style.display = "flex"; - firstRef.current.style.flex = storedValue === HIDE_FIRST || storedValue === HIDE_SECOND ? defaultFlexRef.current : storedValue; - } - if (secondRef.current) { - secondRef.current.style.display = "flex"; - secondRef.current.style.flex = "1"; - } - if (dragBarRef.current) { - dragBarRef.current.style.display = "flex"; - } - }, [direction, storage, storageKey]); - const hide = React.useCallback(resizableElement => { - const element = resizableElement === "first" ? firstRef.current : secondRef.current; - if (!element) { - return; - } - element.style.left = "-1000px"; - element.style.position = "absolute"; - element.style.opacity = "0"; - element.style.height = "500px"; - element.style.width = "500px"; - if (firstRef.current) { - const flex = parseFloat(firstRef.current.style.flex); - if (!Number.isFinite(flex) || flex < 1) { - firstRef.current.style.flex = "1"; - } - } - }, []); - const show = React.useCallback(resizableElement => { - const element = resizableElement === "first" ? firstRef.current : secondRef.current; - if (!element) { - return; - } - element.style.width = ""; - element.style.height = ""; - element.style.opacity = ""; - element.style.position = ""; - element.style.left = ""; - if (storage && storageKey) { - const storedValue = storage.get(storageKey); - if (firstRef.current && storedValue !== HIDE_FIRST && storedValue !== HIDE_SECOND) { - firstRef.current.style.flex = storedValue || defaultFlexRef.current; - } - } - }, [storage, storageKey]); - React.useLayoutEffect(() => { - if (hiddenElement === "first") { - hide("first"); - } else { - show("first"); - } - if (hiddenElement === "second") { - hide("second"); - } else { - show("second"); - } - }, [hiddenElement, hide, show]); - React.useEffect(() => { - if (!dragBarRef.current || !firstRef.current || !secondRef.current) { - return; - } - const dragBarContainer = dragBarRef.current; - const firstContainer = firstRef.current; - const wrapper = firstContainer.parentElement; - const eventProperty = direction === "horizontal" ? "clientX" : "clientY"; - const rectProperty = direction === "horizontal" ? "left" : "top"; - const adjacentRectProperty = direction === "horizontal" ? "right" : "bottom"; - const sizeProperty = direction === "horizontal" ? "clientWidth" : "clientHeight"; - function handleMouseDown(downEvent) { - downEvent.preventDefault(); - const offset = downEvent[eventProperty] - dragBarContainer.getBoundingClientRect()[rectProperty]; - function handleMouseMove(moveEvent) { - if (moveEvent.buttons === 0) { - return handleMouseUp(); - } - const firstSize = moveEvent[eventProperty] - wrapper.getBoundingClientRect()[rectProperty] - offset; - const secondSize = wrapper.getBoundingClientRect()[adjacentRectProperty] - moveEvent[eventProperty] + offset - dragBarContainer[sizeProperty]; - if (firstSize < sizeThresholdFirst) { - setHiddenElementWithCallback("first"); - store(HIDE_FIRST); - } else if (secondSize < sizeThresholdSecond) { - setHiddenElementWithCallback("second"); - store(HIDE_SECOND); - } else { - setHiddenElementWithCallback(null); - const newFlex = `${firstSize / secondSize}`; - firstContainer.style.flex = newFlex; - store(newFlex); + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); + if (options.sharedHist) { + copy.history = this.history; } - } - function handleMouseUp() { - document.removeEventListener("mousemove", handleMouseMove); - document.removeEventListener("mouseup", handleMouseUp); - } - document.addEventListener("mousemove", handleMouseMove); - document.addEventListener("mouseup", handleMouseUp); - } - dragBarContainer.addEventListener("mousedown", handleMouseDown); - function reset() { - if (firstRef.current) { - firstRef.current.style.flex = defaultFlexRef.current; - } - store(defaultFlexRef.current); - setHiddenElementWithCallback(null); - } - dragBarContainer.addEventListener("dblclick", reset); - return () => { - dragBarContainer.removeEventListener("mousedown", handleMouseDown); - dragBarContainer.removeEventListener("dblclick", reset); - }; - }, [direction, setHiddenElementWithCallback, sizeThresholdFirst, sizeThresholdSecond, store]); - return React.useMemo(() => ({ - dragBarRef, - hiddenElement, - firstRef, - setHiddenElement, - secondRef - }), [hiddenElement, setHiddenElement]); - } - const DEFAULT_FLEX = 1; - const HIDE_FIRST = "hide-first"; - const HIDE_SECOND = "hide-second"; - const ToolbarButton = React.forwardRef(({ - label, - onClick, - ...props - }, ref) => { - const [error, setError] = React.useState(null); - const handleClick = React.useCallback(event => { - try { - onClick == null ? void 0 : onClick(event); - setError(null); - } catch (err) { - setError(err instanceof Error ? err : new Error(`Toolbar button click failed: ${err}`)); - } - }, [onClick]); - return /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { - ...props, - ref, - type: "button", - className: clsx.clsx("graphiql-toolbar-button", error && "error", props.className), - onClick: handleClick, - "aria-label": error ? error.message : label, - "aria-invalid": error ? "true" : props["aria-invalid"] - }) - }); - }); - ToolbarButton.displayName = "ToolbarButton"; - function ExecuteButton() { - const { - queryEditor, - setOperationName - } = useEditorContext({ - nonNull: true, - caller: ExecuteButton - }); - const { - isFetching, - isSubscribed, - operationName, - run, - stop - } = useExecutionContext({ - nonNull: true, - caller: ExecuteButton - }); - const operations = (queryEditor == null ? void 0 : queryEditor.operations) || []; - const hasOptions = operations.length > 1 && typeof operationName !== "string"; - const isRunning = isFetching || isSubscribed; - const label = `${isRunning ? "Stop" : "Execute"} query (Ctrl-Enter)`; - const buttonProps = { - type: "button", - className: "graphiql-execute-button", - children: isRunning ? /* @__PURE__ */jsxRuntime.jsx(StopIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(PlayIcon, {}), - "aria-label": label - }; - return hasOptions && !isRunning ? /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { - children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { - ...buttonProps - }) - }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { - children: operations.map((operation, i) => { - const opName = operation.name ? operation.name.value : ``; - return /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Item, { - onSelect: () => { - var _a; - const selectedOperationName = (_a = operation.name) == null ? void 0 : _a.value; - if (queryEditor && selectedOperationName && selectedOperationName !== queryEditor.operationName) { - setOperationName(selectedOperationName); + (this.linked || (this.linked = [])).push({ + doc: copy, + sharedHist: options.sharedHist + }); + copy.linked = [{ + doc: this, + isParent: true, + sharedHist: options.sharedHist + }]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function (other) { + if (other instanceof CodeMirror) { + other = other.doc; + } + if (this.linked) { + for (var i2 = 0; i2 < this.linked.length; ++i2) { + var link = this.linked[i2]; + if (link.doc != other) { + continue; } - run(); - }, - children: opName - }, `${opName}-${i}`); - }) - })] - }) : /* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx("button", { - ...buttonProps, - onClick: () => { - if (isRunning) { - stop(); - } else { - run(); + this.linked.splice(i2, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } } - } - }) - }); - } - const ToolbarMenuRoot = ({ - button, - children, - label, - ...props - }) => /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { - ...props, - children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { - label, - children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { - className: clsx.clsx("graphiql-un-styled graphiql-toolbar-menu", props.className), - "aria-label": label, - children: button - }) - }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { - children - })] - }); - const ToolbarMenu = createComponentGroup(ToolbarMenuRoot, { - Item: DropdownMenu.Item - }); - exports.Argument = Argument; - exports.ArgumentIcon = ArgumentIcon; - exports.Button = Button$1; - exports.ButtonGroup = ButtonGroup; - exports.ChevronDownIcon = ChevronDownIcon; - exports.ChevronLeftIcon = ChevronLeftIcon; - exports.ChevronUpIcon = ChevronUpIcon; - exports.CloseIcon = CloseIcon; - exports.CopyIcon = CopyIcon; - exports.DOC_EXPLORER_PLUGIN = DOC_EXPLORER_PLUGIN; - exports.DefaultValue = DefaultValue; - exports.DeprecatedArgumentIcon = DeprecatedArgumentIcon; - exports.DeprecatedEnumValueIcon = DeprecatedEnumValueIcon; - exports.DeprecatedFieldIcon = DeprecatedFieldIcon; - exports.DeprecationReason = DeprecationReason; - exports.Dialog = Dialog; - exports.DialogRoot = DialogRoot; - exports.Directive = Directive; - exports.DirectiveIcon = DirectiveIcon; - exports.DocExplorer = DocExplorer; - exports.DocsFilledIcon = DocsFilledIcon; - exports.DocsIcon = DocsIcon; - exports.DropdownMenu = DropdownMenu; - exports.EditorContext = EditorContext; - exports.EditorContextProvider = EditorContextProvider; - exports.EnumValueIcon = EnumValueIcon; - exports.ExecuteButton = ExecuteButton; - exports.ExecutionContext = ExecutionContext; - exports.ExecutionContextProvider = ExecutionContextProvider; - exports.ExplorerContext = ExplorerContext; - exports.ExplorerContextProvider = ExplorerContextProvider; - exports.ExplorerSection = ExplorerSection; - exports.FieldDocumentation = FieldDocumentation; - exports.FieldIcon = FieldIcon; - exports.FieldLink = FieldLink; - exports.GraphiQLProvider = GraphiQLProvider; - exports.HISTORY_PLUGIN = HISTORY_PLUGIN; - exports.HeaderEditor = HeaderEditor; - exports.History = History; - exports.HistoryContext = HistoryContext; - exports.HistoryContextProvider = HistoryContextProvider; - exports.HistoryIcon = HistoryIcon; - exports.ImagePreview = ImagePreview; - exports.ImplementsIcon = ImplementsIcon; - exports.KeyboardShortcutIcon = KeyboardShortcutIcon; - exports.MagnifyingGlassIcon = MagnifyingGlassIcon; - exports.MarkdownContent = MarkdownContent; - exports.MergeIcon = MergeIcon; - exports.PenIcon = PenIcon; - exports.PlayIcon = PlayIcon; - exports.PluginContext = PluginContext; - exports.PluginContextProvider = PluginContextProvider; - exports.PlusIcon = PlusIcon; - exports.PrettifyIcon = PrettifyIcon; - exports.QueryEditor = QueryEditor; - exports.ReloadIcon = ReloadIcon; - exports.ResponseEditor = ResponseEditor; - exports.RootTypeIcon = RootTypeIcon; - exports.SchemaContext = SchemaContext; - exports.SchemaContextProvider = SchemaContextProvider; - exports.SchemaDocumentation = SchemaDocumentation; - exports.Search = Search; - exports.SettingsIcon = SettingsIcon; - exports.Spinner = Spinner; - exports.StarFilledIcon = StarFilledIcon; - exports.StarIcon = StarIcon; - exports.StopIcon = StopIcon; - exports.StorageContext = StorageContext; - exports.StorageContextProvider = StorageContextProvider; - exports.Tab = Tab; - exports.Tabs = Tabs; - exports.ToolbarButton = ToolbarButton; - exports.ToolbarMenu = ToolbarMenu; - exports.Tooltip = Tooltip; - exports.TooltipRoot = TooltipRoot; - exports.TrashIcon = TrashIcon; - exports.TypeDocumentation = TypeDocumentation; - exports.TypeIcon = TypeIcon; - exports.TypeLink = TypeLink; - exports.UnStyledButton = UnStyledButton; - exports.VariableEditor = VariableEditor; - exports.useAutoCompleteLeafs = useAutoCompleteLeafs; - exports.useCopyQuery = useCopyQuery; - exports.useDragResize = useDragResize; - exports.useEditorContext = useEditorContext; - exports.useEditorState = useEditorState; - exports.useExecutionContext = useExecutionContext; - exports.useExplorerContext = useExplorerContext; - exports.useHeaderEditor = useHeaderEditor; - exports.useHeadersEditorState = useHeadersEditorState; - exports.useHistoryContext = useHistoryContext; - exports.useMergeQuery = useMergeQuery; - exports.useOperationsEditorState = useOperationsEditorState; - exports.useOptimisticState = useOptimisticState; - exports.usePluginContext = usePluginContext; - exports.usePrettifyEditors = usePrettifyEditors; - exports.useQueryEditor = useQueryEditor; - exports.useResponseEditor = useResponseEditor; - exports.useSchemaContext = useSchemaContext; - exports.useStorageContext = useStorageContext; - exports.useTheme = useTheme; - exports.useVariableEditor = useVariableEditor; - exports.useVariablesEditorState = useVariablesEditorState; - - /***/ }), - - /***/ "../../graphiql-react/dist/info-addon.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/info-addon.cjs.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - codemirror.CodeMirror.defineOption("info", false, (cm, options, old) => { - if (old && old !== codemirror.CodeMirror.Init) { - const oldOnMouseOver = cm.state.info.onMouseOver; - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); - clearTimeout(cm.state.info.hoverTimeout); - delete cm.state.info; - } - if (options) { - const state = cm.state.info = createState(options); - state.onMouseOver = onMouseOver.bind(null, cm); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - } - }); - function createState(options) { - return { - options: options instanceof Function ? { - render: options - } : options === true ? {} : options - }; - } - function getHoverTime(cm) { - const { - options - } = cm.state.info; - return (options === null || options === void 0 ? void 0 : options.hoverTime) || 500; - } - function onMouseOver(cm, e) { - const state = cm.state.info; - const target = e.target || e.srcElement; - if (!(target instanceof HTMLElement)) { - return; - } - if (target.nodeName !== "SPAN" || state.hoverTimeout !== void 0) { - return; - } - const box = target.getBoundingClientRect(); - const onMouseMove = function () { - clearTimeout(state.hoverTimeout); - state.hoverTimeout = setTimeout(onHover, hoverTime); - }; - const onMouseOut = function () { - codemirror.CodeMirror.off(document, "mousemove", onMouseMove); - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); - clearTimeout(state.hoverTimeout); - state.hoverTimeout = void 0; - }; - const onHover = function () { - codemirror.CodeMirror.off(document, "mousemove", onMouseMove); - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); - state.hoverTimeout = void 0; - onMouseHover(cm, box); - }; - const hoverTime = getHoverTime(cm); - state.hoverTimeout = setTimeout(onHover, hoverTime); - codemirror.CodeMirror.on(document, "mousemove", onMouseMove); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); - } - function onMouseHover(cm, box) { - const pos = cm.coordsChar({ - left: (box.left + box.right) / 2, - top: (box.top + box.bottom) / 2 - }, "window"); - const state = cm.state.info; - const { - options - } = state; - const render = options.render || cm.getHelper(pos, "info"); - if (render) { - const token = cm.getTokenAt(pos, true); - if (token) { - const info = render(token, options, cm, pos); - if (info) { - showPopup(cm, box, info); - } - } - } - } - function showPopup(cm, box, info) { - const popup = document.createElement("div"); - popup.className = "CodeMirror-info"; - popup.append(info); - document.body.append(popup); - const popupBox = popup.getBoundingClientRect(); - const popupStyle = window.getComputedStyle(popup); - const popupWidth = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight); - const popupHeight = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom); - let topPos = box.bottom; - if (popupHeight > window.innerHeight - box.bottom - 15 && box.top > window.innerHeight - box.bottom) { - topPos = box.top - popupHeight; - } - if (topPos < 0) { - topPos = box.bottom; - } - let leftPos = Math.max(0, window.innerWidth - popupWidth - 15); - if (leftPos > box.left) { - leftPos = box.left; - } - popup.style.opacity = "1"; - popup.style.top = topPos + "px"; - popup.style.left = leftPos + "px"; - let popupTimeout; - const onMouseOverPopup = function () { - clearTimeout(popupTimeout); - }; - const onMouseOut = function () { - clearTimeout(popupTimeout); - popupTimeout = setTimeout(hidePopup, 200); - }; - const hidePopup = function () { - codemirror.CodeMirror.off(popup, "mouseover", onMouseOverPopup); - codemirror.CodeMirror.off(popup, "mouseout", onMouseOut); - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); - if (popup.style.opacity) { - popup.style.opacity = "0"; - setTimeout(() => { - if (popup.parentNode) { - popup.remove(); + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) { + return splitIds.push(doc.id); + }, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); } - }, 600); - } else if (popup.parentNode) { - popup.remove(); - } - }; - codemirror.CodeMirror.on(popup, "mouseover", onMouseOverPopup); - codemirror.CodeMirror.on(popup, "mouseout", onMouseOut); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); - } - - /***/ }), - - /***/ "../../graphiql-react/dist/info.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/info.cjs.js ***! - \*********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); - __webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"); - codemirror.CodeMirror.registerHelper("info", "graphql", (token, options) => { - var _a; - if (!options.schema || !token.state) { - return; - } - const { - kind, - step - } = token.state; - const typeInfo = SchemaReference.getTypeInfo(options.schema, token.state); - if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef || kind === "ObjectField" && step === 0 && typeInfo.fieldDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderField(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.fieldDef); - return into; - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderDirective(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.directiveDef); - return into; - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderArg(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.argDef); - return into; - } - if (kind === "EnumValue" && ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.description)) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderEnumValue(header, typeInfo, options); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.enumValue); - return into; - } - if (kind === "NamedType" && typeInfo.type && typeInfo.type.description) { - const header = document.createElement("div"); - header.className = "CodeMirror-info-header"; - renderType(header, typeInfo, options, typeInfo.type); - const into = document.createElement("div"); - into.append(header); - renderDescription(into, options, typeInfo.type); - return into; - } - }); - function renderField(into, typeInfo, options) { - renderQualifiedField(into, typeInfo, options); - renderTypeAnnotation(into, typeInfo, options, typeInfo.type); - } - function renderQualifiedField(into, typeInfo, options) { - var _a; - const fieldName = ((_a = typeInfo.fieldDef) === null || _a === void 0 ? void 0 : _a.name) || ""; - text(into, fieldName, "field-name", options, SchemaReference.getFieldReference(typeInfo)); - } - function renderDirective(into, typeInfo, options) { - var _a; - const name = "@" + (((_a = typeInfo.directiveDef) === null || _a === void 0 ? void 0 : _a.name) || ""); - text(into, name, "directive-name", options, SchemaReference.getDirectiveReference(typeInfo)); - } - function renderArg(into, typeInfo, options) { - var _a; - const name = ((_a = typeInfo.argDef) === null || _a === void 0 ? void 0 : _a.name) || ""; - text(into, name, "arg-name", options, SchemaReference.getArgumentReference(typeInfo)); - renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); - } - function renderEnumValue(into, typeInfo, options) { - var _a; - const name = ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.name) || ""; - renderType(into, typeInfo, options, typeInfo.inputType); - text(into, "."); - text(into, name, "enum-value", options, SchemaReference.getEnumValueReference(typeInfo)); - } - function renderTypeAnnotation(into, typeInfo, options, t) { - const typeSpan = document.createElement("span"); - typeSpan.className = "type-name-pill"; - if (t instanceof graphql.GraphQLNonNull) { - renderType(typeSpan, typeInfo, options, t.ofType); - text(typeSpan, "!"); - } else if (t instanceof graphql.GraphQLList) { - text(typeSpan, "["); - renderType(typeSpan, typeInfo, options, t.ofType); - text(typeSpan, "]"); - } else { - text(typeSpan, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); - } - into.append(typeSpan); - } - function renderType(into, typeInfo, options, t) { - if (t instanceof graphql.GraphQLNonNull) { - renderType(into, typeInfo, options, t.ofType); - text(into, "!"); - } else if (t instanceof graphql.GraphQLList) { - text(into, "["); - renderType(into, typeInfo, options, t.ofType); - text(into, "]"); - } else { - text(into, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); - } - } - function renderDescription(into, options, def) { - const { - description - } = def; - if (description) { - const descriptionDiv = document.createElement("div"); - descriptionDiv.className = "info-description"; - if (options.renderDescription) { - descriptionDiv.innerHTML = options.renderDescription(description); - } else { - descriptionDiv.append(document.createTextNode(description)); - } - into.append(descriptionDiv); - } - renderDeprecation(into, options, def); - } - function renderDeprecation(into, options, def) { - const reason = def.deprecationReason; - if (reason) { - const deprecationDiv = document.createElement("div"); - deprecationDiv.className = "info-deprecation"; - into.append(deprecationDiv); - const label = document.createElement("span"); - label.className = "info-deprecation-label"; - label.append(document.createTextNode("Deprecated")); - deprecationDiv.append(label); - const reasonDiv = document.createElement("div"); - reasonDiv.className = "info-deprecation-reason"; - if (options.renderDescription) { - reasonDiv.innerHTML = options.renderDescription(reason); - } else { - reasonDiv.append(document.createTextNode(reason)); - } - deprecationDiv.append(reasonDiv); - } - } - function text(into, content, className = "", options = { - onClick: null - }, ref = null) { - if (className) { - const { - onClick - } = options; - let node; - if (onClick) { - node = document.createElement("a"); - node.href = "javascript:void 0"; - node.addEventListener("click", e => { - e.preventDefault(); - onClick(ref, e); - }); - } else { - node = document.createElement("span"); - } - node.className = className; - node.append(document.createTextNode(content)); - into.append(node); - } else { - into.append(document.createTextNode(content)); - } - } - - /***/ }), - - /***/ "../../graphiql-react/dist/javascript.cjs.js": - /*!***************************************************!*\ - !*** ../../graphiql-react/dist/javascript.cjs.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } + }, + iterLinkedDocs: function (f) { + linkedDocs(this, f); + }, + getMode: function () { + return this.mode; + }, + getEditor: function () { + return this.cm; + }, + splitLines: function (str) { + if (this.lineSep) { + return str.split(this.lineSep); + } + return splitLinesAuto(str); + }, + lineSeparator: function () { + return this.lineSep || "\n"; + }, + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { + dir = "ltr"; + } + if (dir == this.direction) { + return; + } + this.direction = dir; + this.iter(function (line) { + return line.order = null; + }); + if (this.cm) { + directionChanged(this.cm); } + }) + }); + Doc.prototype.eachLine = Doc.prototype.iter; + var lastDrop = 0; + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var javascript$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - CodeMirror.defineMode("javascript", function (config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var trackScope = parserConfig.trackScope !== false; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - var keywords = function () { - function kw(type2) { - return { - type: type2, - style: "keyword" + e_preventDefault(e); + if (ie) { + lastDrop = + /* @__PURE__ */new Date(); + } + var pos = posFromMouse(cm, e, true), + files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) { + return; + } + if (files && files.length && window.FileReader && window.File) { + var n = files.length, + text = Array(n), + read = 0; + var markAsReadAndPasteIfAllFilesAreRead = function () { + if (++read == n) { + operation(cm, function () { + pos = clipPos(cm.doc, pos); + var change = { + from: pos, + to: pos, + text: cm.doc.splitLines(text.filter(function (t) { + return t != null; + }).join(cm.doc.lineSeparator())), + origin: "paste" + }; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); + })(); + } + }; + var readTextFromFile = function (file, i3) { + if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + var reader = new FileReader(); + reader.onerror = function () { + return markAsReadAndPasteIfAllFilesAreRead(); }; - } - var A = kw("keyword a"), - B = kw("keyword b"), - C = kw("keyword c"), - D = kw("keyword d"); - var operator = kw("operator"), - atom = { - type: "atom", - style: "atom" + reader.onload = function () { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { + markAsReadAndPasteIfAllFilesAreRead(); + return; + } + text[i3] = content; + markAsReadAndPasteIfAllFilesAreRead(); }; - return { - "if": kw("if"), - "while": A, - "with": A, - "else": B, - "do": B, - "try": B, - "finally": B, - "return": D, - "break": D, - "continue": D, - "new": kw("new"), - "delete": C, - "void": C, - "throw": C, - "debugger": kw("debugger"), - "var": kw("var"), - "const": kw("var"), - "let": kw("var"), - "function": kw("function"), - "catch": kw("catch"), - "for": kw("for"), - "switch": kw("switch"), - "case": kw("case"), - "default": kw("default"), - "in": operator, - "typeof": operator, - "instanceof": operator, - "true": atom, - "false": atom, - "null": atom, - "undefined": atom, - "NaN": atom, - "Infinity": atom, - "this": kw("this"), - "class": kw("class"), - "super": kw("atom"), - "yield": C, - "export": kw("export"), - "import": kw("import"), - "extends": C, - "await": C + reader.readAsText(file); }; - }(); - var isOperatorChar = /[+\-*&%=<>!?|~^@]/; - var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - function readRegexp(stream) { - var escaped = false, - next, - inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true;else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; + for (var i2 = 0; i2 < files.length; i2++) { + readTextFromFile(files[i2], i2); } - } - var type, content; - function ret(tp, style, cont2) { - type = tp; - content = cont2; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (expressionAllowed(stream, state, 1)) { - readRegexp(stream); - stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); - return ret("regexp", "string-2"); - } else { - stream.eat("="); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#" && stream.peek() == "!") { - stream.skipToEnd(); - return ret("meta", "meta"); - } else if (ch == "#" && stream.eatWhile(wordRE)) { - return ret("variable", "property"); - } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (isOperatorChar.test(ch)) { - if (ch != ">" || !state.lexical || state.lexical.type != ">") { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("="); - } else if (/[<>*+\-|&?]/.test(ch)) { - stream.eat(ch); - if (ch == ">") stream.eat(ch); + } else { + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + setTimeout(function () { + return cm.display.input.focus(); + }, 20); + return; + } + try { + var text$1 = e.dataTransfer.getData("Text"); + if (text$1) { + var selected; + if (cm.state.draggingText && !cm.state.draggingText.copy) { + selected = cm.listSelections(); } - } - if (ch == "?" && stream.eat(".")) return ret("."); - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current(); - if (state.lastType != ".") { - if (keywords.propertyIsEnumerable(word)) { - var kw = keywords[word]; - return ret(kw.type, kw.style, word); + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i$12 = 0; i$12 < selected.length; ++i$12) { + replaceRange(cm.doc, "", selected[i$12].anchor, selected[i$12].head, "drag"); + } } - if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word); + cm.replaceSelection(text$1, "around", "paste"); + cm.display.input.focus(); } - return ret("variable", "variable", word); + } catch (e$1) {} + } + } + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || + /* @__PURE__ */new Date() - lastDrop < 100)) { + e_stop(e); + return; + } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { + return; + } + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove"; + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) { + img.parentNode.removeChild(img); } } - function tokenString(quote) { - return function (stream, state) { - var escaped = false, - next; - if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; + } + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) { + return; } - function tokenComment(stream, state) { - var maybeEnd = false, - ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = ch == "*"; + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { + return; + } + var byClass = document.getElementsByClassName("CodeMirror"), + editors = []; + for (var i2 = 0; i2 < byClass.length; i2++) { + var cm = byClass[i2].CodeMirror; + if (cm) { + editors.push(cm); } - return ret("comment", "comment"); } - function tokenQuasi(stream, state) { - var escaped = false, - next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; + if (editors.length) { + editors[0].operation(function () { + for (var i3 = 0; i3 < editors.length; i3++) { + f(editors[i3]); } - escaped = !escaped && next == "\\"; + }); + } + } + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) { + return; + } + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { + resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); } - return ret("quasi", "string-2", stream.current()); - } - var brackets = "([{}])"; - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - if (isTS) { - var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)); - if (m) arrow = m.index; - } - var depth = 0, - sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { - ++pos; - break; - } - if (--depth == 0) { - if (ch == "(") sawSomething = true; - break; + }); + on(window, "blur", function () { + return forEachCodeMirror(onBlur); + }); + } + function onResize(cm) { + var d = cm.display; + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + var keyNames = { + 3: "Pause", + 8: "Backspace", + 9: "Tab", + 13: "Enter", + 16: "Shift", + 17: "Ctrl", + 18: "Alt", + 19: "Pause", + 20: "CapsLock", + 27: "Esc", + 32: "Space", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "Left", + 38: "Up", + 39: "Right", + 40: "Down", + 44: "PrintScrn", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Mod", + 92: "Mod", + 93: "Mod", + 106: "*", + 107: "=", + 109: "-", + 110: ".", + 111: "/", + 145: "ScrollLock", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'", + 224: "Mod", + 63232: "Up", + 63233: "Down", + 63234: "Left", + 63235: "Right", + 63272: "Delete", + 63273: "Home", + 63275: "End", + 63276: "PageUp", + 63277: "PageDown", + 63302: "Insert" + }; + for (var i = 0; i < 10; i++) { + keyNames[i + 48] = keyNames[i + 96] = String(i); + } + for (var i$1 = 65; i$1 <= 90; i$1++) { + keyNames[i$1] = String.fromCharCode(i$1); + } + for (var i$2 = 1; i$2 <= 12; i$2++) { + keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; + } + var keyMap = {}; + keyMap.basic = { + "Left": "goCharLeft", + "Right": "goCharRight", + "Up": "goLineUp", + "Down": "goLineDown", + "End": "goLineEnd", + "Home": "goLineStartSmart", + "PageUp": "goPageUp", + "PageDown": "goPageDown", + "Delete": "delCharAfter", + "Backspace": "delCharBefore", + "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", + "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", + "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + keyMap.pcDefault = { + "Ctrl-A": "selectAll", + "Ctrl-D": "deleteLine", + "Ctrl-Z": "undo", + "Shift-Ctrl-Z": "redo", + "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", + "Ctrl-End": "goDocEnd", + "Ctrl-Up": "goLineUp", + "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", + "Ctrl-Right": "goGroupRight", + "Alt-Left": "goLineStart", + "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", + "Ctrl-Delete": "delGroupAfter", + "Ctrl-S": "save", + "Ctrl-F": "find", + "Ctrl-G": "findNext", + "Shift-Ctrl-G": "findPrev", + "Shift-Ctrl-F": "replace", + "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", + "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", + "Shift-Ctrl-U": "redoSelection", + "Alt-U": "redoSelection", + "fallthrough": "basic" + }; + keyMap.emacsy = { + "Ctrl-F": "goCharRight", + "Ctrl-B": "goCharLeft", + "Ctrl-P": "goLineUp", + "Ctrl-N": "goLineDown", + "Ctrl-A": "goLineStart", + "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", + "Shift-Ctrl-V": "goPageUp", + "Ctrl-D": "delCharAfter", + "Ctrl-H": "delCharBefore", + "Alt-Backspace": "delWordBefore", + "Ctrl-K": "killLine", + "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", + "Cmd-D": "deleteLine", + "Cmd-Z": "undo", + "Shift-Cmd-Z": "redo", + "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", + "Cmd-Up": "goDocStart", + "Cmd-End": "goDocEnd", + "Cmd-Down": "goDocEnd", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", + "Cmd-Left": "goLineLeft", + "Cmd-Right": "goLineRight", + "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", + "Alt-Delete": "delGroupAfter", + "Cmd-S": "save", + "Cmd-F": "find", + "Cmd-G": "findNext", + "Shift-Cmd-G": "findPrev", + "Cmd-Alt-F": "replace", + "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", + "Cmd-]": "indentMore", + "Cmd-Backspace": "delWrappedLineLeft", + "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", + "Shift-Cmd-U": "redoSelection", + "Ctrl-Up": "goDocStart", + "Ctrl-Down": "goDocEnd", + "fallthrough": ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/); + name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i2 = 0; i2 < parts.length - 1; i2++) { + var mod = parts[i2]; + if (/^(cmd|meta|m)$/i.test(mod)) { + cmd = true; + } else if (/^a(lt)?$/i.test(mod)) { + alt = true; + } else if (/^(c|ctrl|control)$/i.test(mod)) { + ctrl = true; + } else if (/^s(hift)?$/i.test(mod)) { + shift = true; + } else { + throw new Error("Unrecognized modifier name: " + mod); + } + } + if (alt) { + name = "Alt-" + name; + } + if (ctrl) { + name = "Ctrl-" + name; + } + if (cmd) { + name = "Cmd-" + name; + } + if (shift) { + name = "Shift-" + name; + } + return name; + } + function normalizeKeyMap(keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { + continue; + } + if (value == "...") { + delete keymap[keyname]; + continue; + } + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i2 = 0; i2 < keys.length; i2++) { + var val = void 0, + name = void 0; + if (i2 == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i2 + 1).join(" "); + val = "..."; } - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/`]/.test(ch)) { - for (;; --pos) { - if (pos == 0) return; - var next = stream.string.charAt(pos - 1); - if (next == ch && stream.string.charAt(pos - 2) != "\\") { - pos--; - break; - } + var prev = copy[name]; + if (!prev) { + copy[name] = val; + } else if (prev != val) { + throw new Error("Inconsistent bindings for " + name); } - } else if (sawSomething && !depth) { - ++pos; - break; } + delete keymap[keyname]; } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - var atomicTypes = { - "atom": true, - "number": true, - "variable": true, - "string": true, - "regexp": true, - "this": true, - "import": true, - "jsonld-keyword": true - }; - function JSLexical(indented, column, type2, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type2; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - function inScope(state, varname) { - if (!trackScope) return false; - for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; - for (var cx2 = state.context; cx2; cx2 = cx2.prev) { - for (var v = cx2.vars; v; v = v.next) if (v.name == varname) return true; - } - } - function parseJS(state, style, type2, content2, stream) { - var cc = state.cc; - cx.state = state; - cx.stream = stream; - cx.marked = null, cx.cc = cc; - cx.style = style; - if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; - while (true) { - var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; - if (combinator(type2, content2)) { - while (cc.length && cc[cc.length - 1].lex) cc.pop()(); - if (cx.marked) return cx.marked; - if (type2 == "variable" && inScope(state, content2)) return "variable-2"; - return style; + } + for (var prop2 in copy) { + keymap[prop2] = copy[prop2]; + } + return keymap; + } + function lookupKey(key, map2, handle, context) { + map2 = getKeyMap(map2); + var found = map2.call ? map2.call(key, context) : map2[key]; + if (found === false) { + return "nothing"; + } + if (found === "...") { + return "multi"; + } + if (found != null && handle(found)) { + return "handled"; + } + if (map2.fallthrough) { + if (Object.prototype.toString.call(map2.fallthrough) != "[object Array]") { + return lookupKey(key, map2.fallthrough, handle, context); + } + for (var i2 = 0; i2 < map2.fallthrough.length; i2++) { + var result = lookupKey(key, map2.fallthrough[i2], handle, context); + if (result) { + return result; } } } - var cx = { - state: null, - column: null, - marked: null, - cc: null - }; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + function addModifierNames(name, event, noShift) { + var base = name; + if (event.altKey && base != "Alt") { + name = "Alt-" + name; } - function cont() { - pass.apply(null, arguments); - return true; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { + name = "Ctrl-" + name; + } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { + name = "Cmd-" + name; } - function inList(name, list) { - for (var v = list; v; v = v.next) if (v.name == name) return true; + if (!noShift && event.shiftKey && base != "Shift") { + name = "Shift-" + name; + } + return name; + } + function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false; } - function register(varname) { - var state = cx.state; - cx.marked = "def"; - if (!trackScope) return; - if (state.context) { - if (state.lexical.info == "var" && state.context && state.context.block) { - var newContext = registerVarScoped(varname, state.context); - if (newContext != null) { - state.context = newContext; - return; - } - } else if (!inList(varname, state.localVars)) { - state.localVars = new Var(varname, state.localVars); - return; - } - } - if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars); + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) { + return false; } - function registerVarScoped(varname, context) { - if (!context) { - return null; - } else if (context.block) { - var inner = registerVarScoped(varname, context.prev); - if (!inner) return null; - if (inner == context.prev) return context; - return new Context(inner, context.vars, true); - } else if (inList(varname, context.vars)) { - return context; - } else { - return new Context(context.prev, new Var(varname, context.vars), false); - } - } - function isModifier(name) { - return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; - } - function Context(prev, vars, block2) { - this.prev = prev; - this.vars = vars; - this.block = block2; - } - function Var(name, next) { - this.name = name; - this.next = next; - } - var defaultVars = new Var("this", new Var("arguments", null)); - function pushcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, false); - cx.state.localVars = defaultVars; - } - function pushblockcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, true); - cx.state.localVars = null; - } - pushcontext.lex = pushblockcontext.lex = true; - function popcontext() { - cx.state.localVars = cx.state.context.vars; - cx.state.context = cx.state.context.prev; - } - popcontext.lex = true; - function pushlex(type2, info) { - var result = function () { - var state = cx.state, - indent = state.indented; - if (state.lexical.type == "stat") indent = state.lexical.indented;else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; - state.lexical = new JSLexical(indent, cx.stream.column(), type2, null, state.lexical, info); - }; - result.lex = true; - return result; + if (event.keyCode == 3 && event.code) { + name = event.code; } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - function expect(wanted) { - function exp(type2) { - if (type2 == wanted) return cont();else if (wanted == ";" || type2 == "}" || type2 == ")" || type2 == "]") return pass();else return cont(exp); - } - return exp; - } - function statement(type2, value) { - if (type2 == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); - if (type2 == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); - if (type2 == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type2 == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); - if (type2 == "debugger") return cont(expect(";")); - if (type2 == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); - if (type2 == ";") return cont(); - if (type2 == "if") { - if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); - return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); - } - if (type2 == "function") return cont(functiondef); - if (type2 == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); - if (type2 == "class" || isTS && value == "interface") { - cx.marked = "keyword"; - return cont(pushlex("form", type2 == "class" ? type2 : value), className, poplex); - } - if (type2 == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword"; - return cont(statement); - } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { - cx.marked = "keyword"; - if (value == "enum") return cont(enumdef);else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); - } else if (isTS && value == "namespace") { - cx.marked = "keyword"; - return cont(pushlex("form"), expression, statement, poplex); - } else if (isTS && value == "abstract") { - cx.marked = "keyword"; - return cont(statement); - } else { - return cont(pushlex("stat"), maybelabel); + return addModifierNames(name, event, noShift); + } + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, + kill = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + var toKill = compute(ranges[i2]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; } } - if (type2 == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); - if (type2 == "case") return cont(expression, expect(":")); - if (type2 == "default") return cont(expect(":")); - if (type2 == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); - if (type2 == "export") return cont(pushlex("stat"), afterExport, poplex); - if (type2 == "import") return cont(pushlex("stat"), afterImport, poplex); - if (type2 == "async") return cont(statement); - if (value == "@") return cont(expression, statement); - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function maybeCatchBinding(type2) { - if (type2 == "(") return cont(funarg, expect(")")); - } - function expression(type2, value) { - return expressionInner(type2, value, false); - } - function expressionNoComma(type2, value) { - return expressionInner(type2, value, true); - } - function parenExpr(type2) { - if (type2 != "(") return pass(); - return cont(pushlex(")"), maybeexpression, expect(")"), poplex); - } - function expressionInner(type2, value, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);else if (type2 == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); - } - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); - if (type2 == "function") return cont(functiondef, maybeop); - if (type2 == "class" || isTS && value == "interface") { - cx.marked = "keyword"; - return cont(pushlex("form"), classExpression, poplex); - } - if (type2 == "keyword c" || type2 == "async") return cont(noComma ? expressionNoComma : expression); - if (type2 == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); - if (type2 == "operator" || type2 == "spread") return cont(noComma ? expressionNoComma : expression); - if (type2 == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type2 == "{") return contCommasep(objprop, "}", null, maybeop); - if (type2 == "quasi") return pass(quasi, maybeop); - if (type2 == "new") return cont(maybeTarget(noComma)); - return cont(); + kill.push(toKill); } - function maybeexpression(type2) { - if (type2.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - function maybeoperatorComma(type2, value) { - if (type2 == ",") return cont(maybeexpression); - return maybeoperatorNoComma(type2, value, false); - } - function maybeoperatorNoComma(type2, value, noComma) { - var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type2 == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); - if (type2 == "operator") { - if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); - if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); - if (value == "?") return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type2 == "quasi") { - return pass(quasi, me); - } - if (type2 == ";") return; - if (type2 == "(") return contCommasep(expressionNoComma, ")", "call", me); - if (type2 == ".") return cont(property, me); - if (type2 == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); - if (isTS && value == "as") { - cx.marked = "keyword"; - return cont(typeexpr, me); + runInOp(cm, function () { + for (var i3 = kill.length - 1; i3 >= 0; i3--) { + replaceRange(cm.doc, "", kill[i3].from, kill[i3].to, "+delete"); } - if (type2 == "regexp") { - cx.state.lastType = cx.marked = "operator"; - cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); - return cont(expr); + ensureCursorVisible(cm); + }); + } + function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir); + return target < 0 || target > line.text.length ? null : target; + } + function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir); + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before"); + } + function endOfLine(visually, cm, lineObj, lineNo2, dir) { + if (visually) { + if (cm.doc.direction == "rtl") { + dir = -dir; } - } - function quasi(type2, value) { - if (type2 != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(maybeexpression, continueQuasi); - } - function continueQuasi(type2) { - if (type2 == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = dir < 0 ? lst(order) : order[0]; + var moveInStorageOrder = dir < 0 == (part.level == 1); + var sticky = moveInStorageOrder ? "after" : "before"; + var ch; + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj); + ch = dir < 0 ? lineObj.text.length - 1 : 0; + var targetTop = measureCharPrepared(cm, prep, ch).top; + ch = findFirst(function (ch2) { + return measureCharPrepared(cm, prep, ch2).top == targetTop; + }, dir < 0 == (part.level == 1) ? part.from : part.to - 1, ch); + if (sticky == "before") { + ch = moveCharLogically(lineObj, ch, 1); + } + } else { + ch = dir < 0 ? part.to : part.from; + } + return new Pos(lineNo2, ch, sticky); } } - function arrowBody(type2) { - findFatArrow(cx.stream, cx.state); - return pass(type2 == "{" ? statement : expression); + return new Pos(lineNo2, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after"); + } + function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction); + if (!bidi) { + return moveLogically(line, start, dir); + } + if (start.ch >= line.text.length) { + start.ch = line.text.length; + start.sticky = "before"; + } else if (start.ch <= 0) { + start.ch = 0; + start.sticky = "after"; } - function arrowBodyNoComma(type2) { - findFatArrow(cx.stream, cx.state); - return pass(type2 == "{" ? statement : expressionNoComma); + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), + part = bidi[partPos]; + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + return moveLogically(line, start, dir); } - function maybeTarget(noComma) { - return function (type2) { - if (type2 == ".") return cont(noComma ? targetNoComma : target);else if (type2 == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);else return pass(noComma ? expressionNoComma : expression); + var mv = function (pos, dir2) { + return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir2); + }; + var prep; + var getWrappedLineExtent = function (ch2) { + if (!cm.options.lineWrapping) { + return { + begin: 0, + end: line.text.length + }; + } + prep = prep || prepareMeasureForLine(cm, line); + return wrappedLineExtentChar(cm, line, prep, ch2); + }; + var wrappedLineExtent2 = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = part.level == 1 == dir < 0; + var ch = mv(start, moveInStorageOrder ? 1 : -1); + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent2.begin : ch <= part.to && ch <= wrappedLineExtent2.end)) { + var sticky = moveInStorageOrder ? "before" : "after"; + return new Pos(start.line, ch, sticky); + } + } + var searchInVisualLine = function (partPos2, dir2, wrappedLineExtent3) { + var getRes = function (ch3, moveInStorageOrder3) { + return moveInStorageOrder3 ? new Pos(start.line, mv(ch3, 1), "before") : new Pos(start.line, ch3, "after"); }; + for (; partPos2 >= 0 && partPos2 < bidi.length; partPos2 += dir2) { + var part2 = bidi[partPos2]; + var moveInStorageOrder2 = dir2 > 0 == (part2.level != 1); + var ch2 = moveInStorageOrder2 ? wrappedLineExtent3.begin : mv(wrappedLineExtent3.end, -1); + if (part2.from <= ch2 && ch2 < part2.to) { + return getRes(ch2, moveInStorageOrder2); + } + ch2 = moveInStorageOrder2 ? part2.from : mv(part2.to, -1); + if (wrappedLineExtent3.begin <= ch2 && ch2 < wrappedLineExtent3.end) { + return getRes(ch2, moveInStorageOrder2); + } + } + }; + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent2); + if (res) { + return res; } - function target(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorComma); + var nextCh = dir > 0 ? wrappedLineExtent2.end : mv(wrappedLineExtent2.begin, -1); + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); + if (res) { + return res; + } + } + return null; + } + var commands = { + selectAll, + singleSelection: function (cm) { + return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function (cm) { + return deleteNearSelection(cm, function (range2) { + if (range2.empty()) { + var len = getLine(cm.doc, range2.head.line).text.length; + if (range2.head.ch == len && range2.head.line < cm.lastLine()) { + return { + from: range2.head, + to: Pos(range2.head.line + 1, 0) + }; + } else { + return { + from: range2.head, + to: Pos(range2.head.line, len) + }; + } + } else { + return { + from: range2.from(), + to: range2.to() + }; + } + }); + }, + deleteLine: function (cm) { + return deleteNearSelection(cm, function (range2) { + return { + from: Pos(range2.from().line, 0), + to: clipPos(cm.doc, Pos(range2.to().line + 1, 0)) + }; + }); + }, + delLineLeft: function (cm) { + return deleteNearSelection(cm, function (range2) { + return { + from: Pos(range2.from().line, 0), + to: range2.from() + }; + }); + }, + delWrappedLineLeft: function (cm) { + return deleteNearSelection(cm, function (range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var leftPos = cm.coordsChar({ + left: 0, + top + }, "div"); + return { + from: leftPos, + to: range2.from() + }; + }); + }, + delWrappedLineRight: function (cm) { + return deleteNearSelection(cm, function (range2) { + var top = cm.charCoords(range2.head, "div").top + 5; + var rightPos = cm.coordsChar({ + left: cm.display.lineDiv.offsetWidth + 100, + top + }, "div"); + return { + from: range2.from(), + to: rightPos + }; + }); + }, + undo: function (cm) { + return cm.undo(); + }, + redo: function (cm) { + return cm.redo(); + }, + undoSelection: function (cm) { + return cm.undoSelection(); + }, + redoSelection: function (cm) { + return cm.redoSelection(); + }, + goDocStart: function (cm) { + return cm.extendSelection(Pos(cm.firstLine(), 0)); + }, + goDocEnd: function (cm) { + return cm.extendSelection(Pos(cm.lastLine())); + }, + goLineStart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + return lineStart(cm, range2.head.line); + }, { + origin: "+move", + bias: 1 + }); + }, + goLineStartSmart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + return lineStartSmart(cm, range2.head); + }, { + origin: "+move", + bias: 1 + }); + }, + goLineEnd: function (cm) { + return cm.extendSelectionsBy(function (range2) { + return lineEnd(cm, range2.head.line); + }, { + origin: "+move", + bias: -1 + }); + }, + goLineRight: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar({ + left: cm.display.lineDiv.offsetWidth + 100, + top + }, "div"); + }, sel_move); + }, + goLineLeft: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + return cm.coordsChar({ + left: 0, + top + }, "div"); + }, sel_move); + }, + goLineLeftSmart: function (cm) { + return cm.extendSelectionsBy(function (range2) { + var top = cm.cursorCoords(range2.head, "div").top + 5; + var pos = cm.coordsChar({ + left: 0, + top + }, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { + return lineStartSmart(cm, range2.head); + } + return pos; + }, sel_move); + }, + goLineUp: function (cm) { + return cm.moveV(-1, "line"); + }, + goLineDown: function (cm) { + return cm.moveV(1, "line"); + }, + goPageUp: function (cm) { + return cm.moveV(-1, "page"); + }, + goPageDown: function (cm) { + return cm.moveV(1, "page"); + }, + goCharLeft: function (cm) { + return cm.moveH(-1, "char"); + }, + goCharRight: function (cm) { + return cm.moveH(1, "char"); + }, + goColumnLeft: function (cm) { + return cm.moveH(-1, "column"); + }, + goColumnRight: function (cm) { + return cm.moveH(1, "column"); + }, + goWordLeft: function (cm) { + return cm.moveH(-1, "word"); + }, + goGroupRight: function (cm) { + return cm.moveH(1, "group"); + }, + goGroupLeft: function (cm) { + return cm.moveH(-1, "group"); + }, + goWordRight: function (cm) { + return cm.moveH(1, "word"); + }, + delCharBefore: function (cm) { + return cm.deleteH(-1, "codepoint"); + }, + delCharAfter: function (cm) { + return cm.deleteH(1, "char"); + }, + delWordBefore: function (cm) { + return cm.deleteH(-1, "word"); + }, + delWordAfter: function (cm) { + return cm.deleteH(1, "word"); + }, + delGroupBefore: function (cm) { + return cm.deleteH(-1, "group"); + }, + delGroupAfter: function (cm) { + return cm.deleteH(1, "group"); + }, + indentAuto: function (cm) { + return cm.indentSelection("smart"); + }, + indentMore: function (cm) { + return cm.indentSelection("add"); + }, + indentLess: function (cm) { + return cm.indentSelection("subtract"); + }, + insertTab: function (cm) { + return cm.replaceSelection(" "); + }, + insertSoftTab: function (cm) { + var spaces = [], + ranges = cm.listSelections(), + tabSize = cm.options.tabSize; + for (var i2 = 0; i2 < ranges.length; i2++) { + var pos = ranges[i2].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(spaceStr(tabSize - col % tabSize)); } - } - function targetNoComma(_, value) { - if (value == "target") { - cx.marked = "keyword"; - return cont(maybeoperatorNoComma); - } - } - function maybelabel(type2) { - if (type2 == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type2) { - if (type2 == "variable") { - cx.marked = "property"; - return cont(); - } - } - function objprop(type2, value) { - if (type2 == "async") { - cx.marked = "property"; - return cont(objprop); - } else if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(getterSetter); - var m; - if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length; - return cont(afterprop); - } else if (type2 == "number" || type2 == "string") { - cx.marked = jsonldMode ? "property" : cx.style + " property"; - return cont(afterprop); - } else if (type2 == "jsonld-keyword") { - return cont(afterprop); - } else if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(objprop); - } else if (type2 == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type2 == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } else if (type2 == ":") { - return pass(afterprop); + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { + cm.indentSelection("add"); + } else { + cm.execCommand("insertTab"); } - } - function getterSetter(type2) { - if (type2 != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type2) { - if (type2 == ":") return cont(expressionNoComma); - if (type2 == "(") return pass(functiondef); - } - function commasep(what, end, sep) { - function proceed(type2, value) { - if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(function (type3, value2) { - if (type3 == end || value2 == end) return pass(); - return pass(what); - }, proceed); + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { + return runInOp(cm, function () { + var ranges = cm.listSelections(), + newSel = []; + for (var i2 = 0; i2 < ranges.length; i2++) { + if (!ranges[i2].empty()) { + continue; + } + var cur = ranges[i2].head, + line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) { + cur = new Pos(cur.line, cur.ch - 1); + } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cur = new Pos(cur.line, 1); + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); + } + } + } + newSel.push(new Range(cur, cur)); } - if (type2 == end || value == end) return cont(); - if (sep && sep.indexOf(";") > -1) return pass(what); - return cont(expect(end)); - } - return function (type2, value) { - if (type2 == end || value == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type2) { - if (type2 == "}") return cont(); - return pass(statement, block); + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function (cm) { + return runInOp(cm, function () { + var sels = cm.listSelections(); + for (var i2 = sels.length - 1; i2 >= 0; i2--) { + cm.replaceRange(cm.doc.lineSeparator(), sels[i2].anchor, sels[i2].head, "+input"); + } + sels = cm.listSelections(); + for (var i$12 = 0; i$12 < sels.length; i$12++) { + cm.indentLine(sels[i$12].from().line, null, true); + } + ensureCursorVisible(cm); + }); + }, + openLine: function (cm) { + return cm.replaceSelection("\n", "start"); + }, + toggleOverwrite: function (cm) { + return cm.toggleOverwrite(); } - function maybetype(type2, value) { - if (isTS) { - if (type2 == ":") return cont(typeexpr); - if (value == "?") return cont(maybetype); + }; + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, visual, lineN, 1); + } + function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLineEnd(line); + if (visual != line) { + lineN = lineNo(visual); + } + return endOfLine(true, cm, line, lineN, -1); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line, cm.doc.direction); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky); + } + return start; + } + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) { + return false; } } - function maybetypeOrIn(type2, value) { - if (isTS && (type2 == ":" || value == "in")) return cont(typeexpr); - } - function mayberettype(type2) { - if (isTS && type2 == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);else return cont(typeexpr); + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, + done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword"; - return cont(); + if (dropShift) { + cm.display.shift = false; } + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; } - function typeexpr(type2, value) { - if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { - cx.marked = "keyword"; - return cont(value == "typeof" ? expressionNoComma : typeexpr); - } - if (type2 == "variable" || value == "void") { - cx.marked = "type"; - return cont(afterType); - } - if (value == "|" || value == "&") return cont(typeexpr); - if (type2 == "string" || type2 == "number" || type2 == "atom") return cont(afterType); - if (type2 == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); - if (type2 == "{") return cont(pushlex("}"), typeprops, poplex, afterType); - if (type2 == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType); - if (type2 == "<") return cont(commasep(typeexpr, ">"), typeexpr); - if (type2 == "quasi") { - return pass(quasiType, afterType); - } - } - function maybeReturnType(type2) { - if (type2 == "=>") return cont(typeexpr); - } - function typeprops(type2) { - if (type2.match(/[\}\)\]]/)) return cont(); - if (type2 == "," || type2 == ";") return cont(typeprops); - return pass(typeprop, typeprops); - } - function typeprop(type2, value) { - if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(typeprop); - } else if (value == "?" || type2 == "number" || type2 == "string") { - return cont(typeprop); - } else if (type2 == ":") { - return cont(typeexpr); - } else if (type2 == "[") { - return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); - } else if (type2 == "(") { - return pass(functiondecl, typeprop); - } else if (!type2.match(/[;\}\)\],]/)) { - return cont(); - } - } - function quasiType(type2, value) { - if (type2 != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasiType); - return cont(typeexpr, continueQuasiType); - } - function continueQuasiType(type2) { - if (type2 == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasiType); - } - } - function typearg(type2, value) { - if (type2 == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg); - if (type2 == ":") return cont(typeexpr); - if (type2 == "spread") return cont(typearg); - return pass(typeexpr); - } - function afterType(type2, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); - if (value == "|" || type2 == "." || value == "&") return cont(typeexpr); - if (type2 == "[") return cont(typeexpr, expect("]"), afterType); - if (value == "extends" || value == "implements") { - cx.marked = "keyword"; - return cont(typeexpr); + return done; + } + function lookupKeyForEditor(cm, name, handle) { + for (var i2 = 0; i2 < cm.state.keyMaps.length; i2++) { + var result = lookupKey(name, cm.state.keyMaps[i2], handle, cm); + if (result) { + return result; } - if (value == "?") return cont(typeexpr, expect(":"), typeexpr); - } - function maybeTypeArgs(_, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault); - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr); } - function vardef(_, value) { - if (value == "enum") { - cx.marked = "keyword"; - return cont(enumdef); + return cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm) || lookupKey(name, cm.options.keyMap, handle, cm); + } + var stopSeq = new Delayed(); + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) { + return "handled"; } - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type2, value) { - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(pattern); + if (/\'$/.test(name)) { + cm.state.keySeq = null; + } else { + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); } - if (type2 == "variable") { - register(value); - return cont(); + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { + return true; } - if (type2 == "spread") return cont(pattern); - if (type2 == "[") return contCommasep(eltpattern, "]"); - if (type2 == "{") return contCommasep(proppattern, "}"); } - function proppattern(type2, value) { - if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type2 == "variable") cx.marked = "property"; - if (type2 == "spread") return cont(pattern); - if (type2 == "}") return pass(); - if (type2 == "[") return cont(expression, expect("]"), expect(":"), proppattern); - return cont(expect(":"), pattern, maybeAssign); + return dispatchKeyInner(cm, name, e, handle); + } + function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle); + if (result == "multi") { + cm.state.keySeq = name; } - function eltpattern() { - return pass(pattern, maybeAssign); + if (result == "handled") { + signalLater(cm, "keyHandled", cm, name, e); } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); } - function vardefCont(type2) { - if (type2 == ",") return cont(vardef); + return !!result; + } + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) { + return false; } - function maybeelse(type2, value) { - if (type2 == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + if (e.shiftKey && !cm.state.keySeq) { + return dispatchKey(cm, "Shift-" + name, e, function (b) { + return doHandleBinding(cm, b, true); + }) || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { + return doHandleBinding(cm, b); + } + }); + } else { + return dispatchKey(cm, name, e, function (b) { + return doHandleBinding(cm, b); + }); } - function forspec(type2, value) { - if (value == "await") return cont(forspec); - if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); + } + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { + return doHandleBinding(cm, b, true); + }); + } + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; } - function forspec1(type2) { - if (type2 == "var") return cont(vardef, forspec2); - if (type2 == "variable") return cont(forspec2); - return pass(forspec2); + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) { + return; } - function forspec2(type2, value) { - if (type2 == ")") return cont(); - if (type2 == ";") return cont(forspec2); - if (value == "in" || value == "of") { - cx.marked = "keyword"; - return cont(expression, forspec2); - } - return pass(expression, forspec2); + if (ie && ie_version < 11 && e.keyCode == 27) { + e.returnValue = false; } - function functiondef(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondef); + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { + cm.replaceSelection("", null, "cut"); } - if (type2 == "variable") { - register(value); - return cont(functiondef); - } - if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); } - function functiondecl(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(functiondecl); - } - if (type2 == "variable") { - register(value); - return cont(functiondecl); - } - if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); + if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) { + document.execCommand("cut"); } - function typename(type2, value) { - if (type2 == "keyword" || type2 == "variable") { - cx.marked = "type"; - return cont(typename); - } else if (value == "<") { - return cont(pushlex(">"), commasep(typeparam, ">"), poplex); - } + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { + showCrossHair(cm); } - function funarg(type2, value) { - if (value == "@") cont(expression, funarg); - if (type2 == "spread") return cont(funarg); - if (isTS && isModifier(value)) { - cx.marked = "keyword"; - return cont(funarg); + } + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); } - if (isTS && type2 == "this") return cont(maybetype, maybeAssign); - return pass(pattern, maybetype, maybeAssign); } - function classExpression(type2, value) { - if (type2 == "variable") return className(type2, value); - return classNameAfter(type2, value); + on(document, "keyup", up); + on(document, "mouseover", up); + } + function onKeyUp(e) { + if (e.keyCode == 16) { + this.doc.sel.shift = false; } - function className(type2, value) { - if (type2 == "variable") { - register(value); - return cont(classNameAfter); - } + signalDOMEvent(this, e); + } + function onKeyPress(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { + return; } - function classNameAfter(type2, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); - if (value == "extends" || value == "implements" || isTS && type2 == ",") { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); - } - if (type2 == "{") return cont(pushlex("}"), classBody, poplex); + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { + return; } - function classBody(type2, value) { - if (type2 == "async" || type2 == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { - cx.marked = "keyword"; - return cont(classBody); - } - if (type2 == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(classfield, classBody); - } - if (type2 == "number" || type2 == "string") return cont(classfield, classBody); - if (type2 == "[") return cont(expression, maybetype, expect("]"), classfield, classBody); - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (isTS && type2 == "(") return pass(functiondecl, classBody); - if (type2 == ";" || type2 == ",") return cont(classBody); - if (type2 == "}") return cont(); - if (value == "@") return cont(expression, classBody); - } - function classfield(type2, value) { - if (value == "!") return cont(classfield); - if (value == "?") return cont(classfield); - if (type2 == ":") return cont(typeexpr, maybeAssign); - if (value == "=") return cont(expressionNoComma); - var context = cx.state.lexical.prev, - isInterface = context && context.info == "interface"; - return pass(isInterface ? functiondecl : functiondef); - } - function afterExport(type2, value) { - if (value == "*") { - cx.marked = "keyword"; - return cont(maybeFrom, expect(";")); - } - if (value == "default") { - cx.marked = "keyword"; - return cont(expression, expect(";")); - } - if (type2 == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); - return pass(statement); + var keyCode = e.keyCode, + charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) { + lastStoppedKey = null; + e_preventDefault(e); + return; } - function exportField(type2, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(expect("variable")); - } - if (type2 == "variable") return pass(expressionNoComma, exportField); + if (presto && (!e.which || e.which < 10) && handleKeyBinding(cm, e)) { + return; } - function afterImport(type2) { - if (type2 == "string") return cont(); - if (type2 == "(") return pass(expression); - if (type2 == ".") return pass(maybeoperatorComma); - return pass(importSpec, maybeMoreImports, maybeFrom); + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (ch == "\b") { + return; } - function importSpec(type2, value) { - if (type2 == "{") return contCommasep(importSpec, "}"); - if (type2 == "variable") register(value); - if (value == "*") cx.marked = "keyword"; - return cont(maybeAs); + if (handleCharBinding(cm, e, ch)) { + return; } - function maybeMoreImports(type2) { - if (type2 == ",") return cont(importSpec, maybeMoreImports); + cm.display.input.onKeyPress(e); + } + var DOUBLECLICK_DELAY = 400; + var PastClick = function (time, pos, button) { + this.time = time; + this.pos = pos; + this.button = button; + }; + PastClick.prototype.compare = function (time, pos, button) { + return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button; + }; + var lastClick, lastDoubleClick; + function clickRepeat(pos, button) { + var now = + /* @__PURE__ */new Date(); + if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { + lastClick = lastDoubleClick = null; + return "triple"; + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button); + lastClick = null; + return "double"; + } else { + lastClick = new PastClick(now, pos, button); + lastDoubleClick = null; + return "single"; } - function maybeAs(_type, value) { - if (value == "as") { - cx.marked = "keyword"; - return cont(importSpec); - } + } + function onMouseDown(e) { + var cm = this, + display = cm.display; + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { + return; } - function maybeFrom(_type, value) { - if (value == "from") { - cx.marked = "keyword"; - return cont(expression); + display.input.ensurePolled(); + display.shift = e.shiftKey; + if (eventInWidget(display, e)) { + if (!webkit) { + display.scroller.draggable = false; + setTimeout(function () { + return display.scroller.draggable = true; + }, 100); } + return; } - function arrayLiteral(type2) { - if (type2 == "]") return cont(); - return pass(commasep(expressionNoComma, "]")); - } - function enumdef() { - return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); - } - function enummember() { - return pass(pattern, maybeAssign); - } - function isContinuedStatement(state, textAfter) { - return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); + if (clickInGutter(cm, e)) { + return; } - function expressionAllowed(stream, state, backUp) { - return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); + var pos = posFromMouse(cm, e), + button = e_button(e), + repeat = pos ? clickRepeat(pos, button) : "single"; + window.focus(); + if (button == 1 && cm.state.selectingText) { + cm.state.selectingText(e); } - return { - startState: function (basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && new Context(null, null, false), - indented: basecolumn || 0 - }; - if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; - return state; - }, - token: function (stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; - return parseJS(state, style, type, content, stream); - }, - indent: function (state, textAfter) { - if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), - lexical = state.lexical, - top; - if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev;else if (c != maybeelse && c != popcontext) break; - } - while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) lexical = lexical.prev; - if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; - var type2 = lexical.type, - closing = firstChar == type2; - if (type2 == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);else if (type2 == "form" && firstChar == "{") return lexical.indented;else if (type2 == "form") return lexical.indented + indentUnit;else if (type2 == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);else if (lexical.align) return lexical.column + (closing ? 0 : 1);else return lexical.indented + (closing ? 0 : indentUnit); - }, - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - blockCommentContinue: jsonMode ? null : " * ", - lineComment: jsonMode ? null : "//", - fold: "brace", - closeBrackets: "()[]{}''\"\"``", - helperType: jsonMode ? "json" : "javascript", - jsonldMode, - jsonMode, - expressionAllowed, - skipExpression: function (state) { - parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); - } - }; - }); - CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - CodeMirror.defineMIME("text/javascript", "javascript"); - CodeMirror.defineMIME("text/ecmascript", "javascript"); - CodeMirror.defineMIME("application/javascript", "javascript"); - CodeMirror.defineMIME("application/x-javascript", "javascript"); - CodeMirror.defineMIME("application/ecmascript", "javascript"); - CodeMirror.defineMIME("application/json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/x-json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/manifest+json", { - name: "javascript", - json: true - }); - CodeMirror.defineMIME("application/ld+json", { - name: "javascript", - jsonld: true - }); - CodeMirror.defineMIME("text/typescript", { - name: "javascript", - typescript: true - }); - CodeMirror.defineMIME("application/typescript", { - name: "javascript", - typescript: true - }); - }); - })(); - var javascriptExports = javascript$2.exports; - const javascript = /* @__PURE__ */codemirror.getDefaultExportFromCjs(javascriptExports); - const javascript$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: javascript - }, [javascriptExports]); - exports.javascript = javascript$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/jump-to-line.cjs.js": - /*!*****************************************************!*\ - !*** ../../graphiql-react/dist/jump-to-line.cjs.js ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } - } + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { + return; } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var jumpToLine$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), dialog.dialogExports); - })(function (CodeMirror) { - CodeMirror.defineOption("search", { - bottom: false - }); - function dialog2(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom - });else f(prompt(shortText, deflt)); - } - function getJumpDialog(cm) { - return cm.phrase("Jump to line:") + ' ' + cm.phrase("(Use line:column or scroll% syntax)") + ""; - } - function interpretLine(cm, string) { - var num = Number(string); - if (/^[-+]/.test(string)) return cm.getCursor().line + num;else return num - 1; - } - CodeMirror.commands.jumpToLine = function (cm) { - var cur = cm.getCursor(); - dialog2(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), cur.line + 1 + ":" + cur.ch, function (posStr) { - if (!posStr) return; - var match; - if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) { - cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); - } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) { - var line = Math.round(cm.lineCount() * Number(match[1]) / 100); - if (/^[-+]/.test(match[1])) line = cur.line + line + 1; - cm.setCursor(line - 1, cur.ch); - } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) { - cm.setCursor(interpretLine(cm, match[1]), cur.ch); + if (button == 1) { + if (pos) { + leftButtonDown(cm, pos, repeat, e); + } else if (e_target(e) == display.scroller) { + e_preventDefault(e); } - }); - }; - CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; - }); - })(); - var jumpToLineExports = jumpToLine$2.exports; - const jumpToLine = /* @__PURE__ */codemirror.getDefaultExportFromCjs(jumpToLineExports); - const jumpToLine$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: jumpToLine - }, [jumpToLineExports]); - exports.jumpToLine = jumpToLine$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/jump.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/jump.cjs.js ***! - \*********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); - codemirror.CodeMirror.defineOption("jump", false, (cm, options, old) => { - if (old && old !== codemirror.CodeMirror.Init) { - const oldOnMouseOver = cm.state.jump.onMouseOver; - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); - const oldOnMouseOut = cm.state.jump.onMouseOut; - codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", oldOnMouseOut); - codemirror.CodeMirror.off(document, "keydown", cm.state.jump.onKeyDown); - delete cm.state.jump; - } - if (options) { - const state = cm.state.jump = { - options, - onMouseOver: onMouseOver.bind(null, cm), - onMouseOut: onMouseOut.bind(null, cm), - onKeyDown: onKeyDown.bind(null, cm) - }; - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", state.onMouseOut); - codemirror.CodeMirror.on(document, "keydown", state.onKeyDown); - } - }); - function onMouseOver(cm, event) { - const target = event.target || event.srcElement; - if (!(target instanceof HTMLElement)) { - return; - } - if ((target === null || target === void 0 ? void 0 : target.nodeName) !== "SPAN") { - return; - } - const box = target.getBoundingClientRect(); - const cursor = { - left: (box.left + box.right) / 2, - top: (box.top + box.bottom) / 2 - }; - cm.state.jump.cursor = cursor; - if (cm.state.jump.isHoldingModifier) { - enableJumpMode(cm); - } - } - function onMouseOut(cm) { - if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) { - cm.state.jump.cursor = null; - return; - } - if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) { - disableJumpMode(cm); - } - } - function onKeyDown(cm, event) { - if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) { - return; - } - cm.state.jump.isHoldingModifier = true; - if (cm.state.jump.cursor) { - enableJumpMode(cm); - } - const onKeyUp = upEvent => { - if (upEvent.code !== event.code) { - return; - } - cm.state.jump.isHoldingModifier = false; - if (cm.state.jump.marker) { - disableJumpMode(cm); - } - codemirror.CodeMirror.off(document, "keyup", onKeyUp); - codemirror.CodeMirror.off(document, "click", onClick); - cm.off("mousedown", onMouseDown); - }; - const onClick = clickEvent => { - const { - destination, - options - } = cm.state.jump; - if (destination) { - options.onClick(destination, clickEvent); - } - }; - const onMouseDown = (_, downEvent) => { - if (cm.state.jump.destination) { - downEvent.codemirrorIgnore = true; - } - }; - codemirror.CodeMirror.on(document, "keyup", onKeyUp); - codemirror.CodeMirror.on(document, "click", onClick); - cm.on("mousedown", onMouseDown); - } - const isMac = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.appVersion.includes("Mac")); - function isJumpModifier(key) { - return key === (isMac ? "Meta" : "Control"); - } - function enableJumpMode(cm) { - if (cm.state.jump.marker) { - return; - } - const { - cursor, - options - } = cm.state.jump; - const pos = cm.coordsChar(cursor); - const token = cm.getTokenAt(pos, true); - const getDestination = options.getDestination || cm.getHelper(pos, "jump"); - if (getDestination) { - const destination = getDestination(token, options, cm); - if (destination) { - const marker = cm.markText({ - line: pos.line, - ch: token.start - }, { - line: pos.line, - ch: token.end - }, { - className: "CodeMirror-jump-token" - }); - cm.state.jump.marker = marker; - cm.state.jump.destination = destination; - } - } - } - function disableJumpMode(cm) { - const { - marker - } = cm.state.jump; - cm.state.jump.marker = null; - cm.state.jump.destination = null; - marker.clear(); - } - codemirror.CodeMirror.registerHelper("jump", "graphql", (token, options) => { - if (!options.schema || !options.onClick || !token.state) { - return; - } - const { - state - } = token; - const { - kind, - step - } = state; - const typeInfo = SchemaReference.getTypeInfo(options.schema, state); - if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef) { - return SchemaReference.getFieldReference(typeInfo); - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - return SchemaReference.getDirectiveReference(typeInfo); - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - return SchemaReference.getArgumentReference(typeInfo); - } - if (kind === "EnumValue" && typeInfo.enumValue) { - return SchemaReference.getEnumValueReference(typeInfo); - } - if (kind === "NamedType" && typeInfo.type) { - return SchemaReference.getTypeReference(typeInfo); - } - }); - - /***/ }), - - /***/ "../../graphiql-react/dist/lint.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs.js ***! - \*********************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } + } else if (button == 2) { + if (pos) { + extendSelection(cm.doc, pos); } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var lint$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var GUTTER_ID = "CodeMirror-lint-markers"; - var LINT_LINE_ID = "CodeMirror-lint-line-"; - function showTooltip(cm, e, content) { - var tt = document.createElement("div"); - tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; - tt.appendChild(content.cloneNode(true)); - if (cm.state.lint.options.selfContain) cm.getWrapperElement().appendChild(tt);else document.body.appendChild(tt); - function position(e2) { - if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); - tt.style.top = Math.max(0, e2.clientY - tt.offsetHeight - 5) + "px"; - tt.style.left = e2.clientX + 5 + "px"; - } - CodeMirror.on(document, "mousemove", position); - position(e); - if (tt.style.opacity != null) tt.style.opacity = 1; - return tt; - } - function rm(elt) { - if (elt.parentNode) elt.parentNode.removeChild(elt); - } - function hideTooltip(tt) { - if (!tt.parentNode) return; - if (tt.style.opacity == null) rm(tt); - tt.style.opacity = 0; - setTimeout(function () { - rm(tt); - }, 600); - } - function showTooltipFor(cm, e, content, node) { - var tooltip = showTooltip(cm, e, content); - function hide() { - CodeMirror.off(node, "mouseout", hide); - if (tooltip) { - hideTooltip(tooltip); - tooltip = null; - } - } - var poll = setInterval(function () { - if (tooltip) for (var n = node;; n = n.parentNode) { - if (n && n.nodeType == 11) n = n.host; - if (n == document.body) return; - if (!n) { - hide(); - break; - } + setTimeout(function () { + return display.input.focus(); + }, 20); + } else if (button == 3) { + if (captureRightClick) { + cm.display.input.onContextMenu(e); + } else { + delayBlurEvent(cm); } - if (!tooltip) return clearInterval(poll); - }, 400); - CodeMirror.on(node, "mouseout", hide); - } - function LintState(cm, conf, hasGutter) { - this.marked = []; - if (conf instanceof Function) conf = { - getAnnotations: conf - }; - if (!conf || conf === true) conf = {}; - this.options = {}; - this.linterOptions = conf.options || {}; - for (var prop in defaults) this.options[prop] = defaults[prop]; - for (var prop in conf) { - if (defaults.hasOwnProperty(prop)) { - if (conf[prop] != null) this.options[prop] = conf[prop]; - } else if (!conf.options) { - this.linterOptions[prop] = conf[prop]; - } - } - this.timeout = null; - this.hasGutter = hasGutter; - this.onMouseOver = function (e) { - onMouseOver(cm, e); - }; - this.waitingFor = 0; - } - var defaults = { - highlightLines: false, - tooltips: true, - delay: 500, - lintOnChange: true, - getAnnotations: null, - async: false, - selfContain: null, - formatAnnotation: null, - onUpdateLinting: null - }; - function clearMarks(cm) { - var state = cm.state.lint; - if (state.hasGutter) cm.clearGutter(GUTTER_ID); - if (state.options.highlightLines) clearErrorLines(cm); - for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); - state.marked.length = 0; - } - function clearErrorLines(cm) { - cm.eachLine(function (line) { - var has = line.wrapClass && /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); - if (has) cm.removeLineClass(line, "wrap", has[0]); - }); + } } - function makeMarker(cm, labels, severity, multiple, tooltips) { - var marker = document.createElement("div"), - inner = marker; - marker.className = "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; - if (multiple) { - inner = marker.appendChild(document.createElement("div")); - inner.className = "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; + function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click"; + if (repeat == "double") { + name = "Double" + name; + } else if (repeat == "triple") { + name = "Triple" + name; } - if (tooltips != false) CodeMirror.on(inner, "mouseover", function (e) { - showTooltipFor(cm, e, labels, inner); + name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; + return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { + if (typeof bound == "string") { + bound = commands[bound]; + } + if (!bound) { + return false; + } + var done = false; + try { + if (cm.isReadOnly()) { + cm.state.suppressEdits = true; + } + done = bound(cm, pos) != Pass; + } finally { + cm.state.suppressEdits = false; + } + return done; }); - return marker; } - function getMaxSeverity(a, b) { - if (a == "error") return a;else return b; - } - function groupByLine(annotations) { - var lines = []; - for (var i = 0; i < annotations.length; ++i) { - var ann = annotations[i], - line = ann.from.line; - (lines[line] || (lines[line] = [])).push(ann); + function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse"); + var value = option ? option(cm, repeat, event) : {}; + if (value.unit == null) { + var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; + value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; } - return lines; + if (value.extend == null || cm.doc.extend) { + value.extend = cm.doc.extend || event.shiftKey; + } + if (value.addNew == null) { + value.addNew = mac ? event.metaKey : event.ctrlKey; + } + if (value.moveOnDrag == null) { + value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); + } + return value; } - function annotationTooltip(ann) { - var severity = ann.severity; - if (!severity) severity = "error"; - var tip = document.createElement("div"); - tip.className = "CodeMirror-lint-message CodeMirror-lint-message-" + severity; - if (typeof ann.messageHTML != "undefined") { - tip.innerHTML = ann.messageHTML; + function leftButtonDown(cm, pos, repeat, event) { + if (ie) { + setTimeout(bind(ensureFocus, cm), 0); } else { - tip.appendChild(document.createTextNode(ann.message)); - } - return tip; - } - function lintAsync(cm, getAnnotations) { - var state = cm.state.lint; - var id = ++state.waitingFor; - function abort() { - id = -1; - cm.off("change", abort); - } - cm.on("change", abort); - getAnnotations(cm.getValue(), function (annotations, arg2) { - cm.off("change", abort); - if (state.waitingFor != id) return; - if (arg2 && annotations instanceof CodeMirror) annotations = arg2; - cm.operation(function () { - updateLinting(cm, annotations); - }); - }, state.linterOptions, cm); - } - function startLinting(cm) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint"); - if (!getAnnotations) return; - if (options.async || getAnnotations.async) { - lintAsync(cm, getAnnotations); + cm.curOp.focus = activeElt(); + } + var behavior = configureMouse(cm, repeat, event); + var sel = cm.doc.sel, + contained; + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { + leftButtonStartDrag(cm, event, pos, behavior); } else { - var annotations = getAnnotations(cm.getValue(), state.linterOptions, cm); - if (!annotations) return; - if (annotations.then) annotations.then(function (issues) { - cm.operation(function () { - updateLinting(cm, issues); - }); - });else cm.operation(function () { - updateLinting(cm, annotations); - }); + leftButtonSelect(cm, event, pos, behavior); } } - function updateLinting(cm, annotationsNotSorted) { - var state = cm.state.lint; - if (!state) return; - var options = state.options; - clearMarks(cm); - var annotations = groupByLine(annotationsNotSorted); - for (var line = 0; line < annotations.length; ++line) { - var anns = annotations[line]; - if (!anns) continue; - var message = []; - anns = anns.filter(function (item) { - return message.indexOf(item.message) > -1 ? false : message.push(item.message); - }); - var maxSeverity = null; - var tipLabel = state.hasGutter && document.createDocumentFragment(); - for (var i = 0; i < anns.length; ++i) { - var ann = anns[i]; - var severity = ann.severity; - if (!severity) severity = "error"; - maxSeverity = getMaxSeverity(maxSeverity, severity); - if (options.formatAnnotation) ann = options.formatAnnotation(ann); - if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); - if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { - className: "CodeMirror-lint-mark CodeMirror-lint-mark-" + severity, - __annotation: ann - })); + function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, + moved = false; + var dragEnd = operation(cm, function (e) { + if (webkit) { + display.scroller.draggable = false; } - if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(cm, tipLabel, maxSeverity, annotations[line].length > 1, options.tooltips)); - if (options.highlightLines) cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); - } - if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm); - } - function onChange(cm) { - var state = cm.state.lint; - if (!state) return; - clearTimeout(state.timeout); - state.timeout = setTimeout(function () { - startLinting(cm); - }, state.options.delay); - } - function popupTooltips(cm, annotations, e) { - var target = e.target || e.srcElement; - var tooltip = document.createDocumentFragment(); - for (var i = 0; i < annotations.length; i++) { - var ann = annotations[i]; - tooltip.appendChild(annotationTooltip(ann)); - } - showTooltipFor(cm, e, tooltip, target); - } - function onMouseOver(cm, e) { - var target = e.target || e.srcElement; - if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; - var box = target.getBoundingClientRect(), - x = (box.left + box.right) / 2, - y = (box.top + box.bottom) / 2; - var spans = cm.findMarksAt(cm.coordsChar({ - left: x, - top: y - }, "client")); - var annotations = []; - for (var i = 0; i < spans.length; ++i) { - var ann = spans[i].__annotation; - if (ann) annotations.push(ann); - } - if (annotations.length) popupTooltips(cm, annotations, e); - } - CodeMirror.defineOption("lint", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - clearMarks(cm); - if (cm.state.lint.options.lintOnChange !== false) cm.off("change", onChange); - CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver); - clearTimeout(cm.state.lint.timeout); - delete cm.state.lint; - } - if (val) { - var gutters = cm.getOption("gutters"), - hasLintGutter = false; - for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; - var state = cm.state.lint = new LintState(cm, val, hasLintGutter); - if (state.options.lintOnChange) cm.on("change", onChange); - if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); - startLinting(cm); - } - }); - CodeMirror.defineExtension("performLint", function () { - startLinting(this); - }); - }); - })(); - var lintExports = lint$2.exports; - const lint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(lintExports); - const lint$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: lint - }, [lintExports]); - exports.lint = lint$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/lint.cjs2.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs2.js ***! - \**********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); - const SEVERITY = ["error", "warning", "information", "hint"]; - const TYPE = { - "GraphQL: Validation": "validation", - "GraphQL: Deprecation": "deprecation", - "GraphQL: Syntax": "syntax" - }; - codemirror.CodeMirror.registerHelper("lint", "graphql", (text, options) => { - const { - schema, - validationRules, - externalFragments - } = options; - const rawResults = graphqlLanguageService.getDiagnostics(text, schema, validationRules, void 0, externalFragments); - const results = rawResults.map(error => ({ - message: error.message, - severity: error.severity ? SEVERITY[error.severity - 1] : SEVERITY[0], - type: error.source ? TYPE[error.source] : void 0, - from: codemirror.CodeMirror.Pos(error.range.start.line, error.range.start.character), - to: codemirror.CodeMirror.Pos(error.range.end.line, error.range.end.character) - })); - return results; - }); - - /***/ }), - - /***/ "../../graphiql-react/dist/lint.cjs3.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/lint.cjs3.js ***! - \**********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function jsonParse(str) { - string = str; - strLen = str.length; - start = end = lastEnd = -1; - ch(); - lex(); - const ast = parseObj(); - expect("EOF"); - return ast; - } - let string; - let strLen; - let start; - let end; - let lastEnd; - let code; - let kind; - function parseObj() { - const nodeStart = start; - const members = []; - expect("{"); - if (!skip("}")) { - do { - members.push(parseMember()); - } while (skip(",")); - expect("}"); - } - return { - kind: "Object", - start: nodeStart, - end: lastEnd, - members - }; - } - function parseMember() { - const nodeStart = start; - const key = kind === "String" ? curToken() : null; - expect("String"); - expect(":"); - const value = parseVal(); - return { - kind: "Member", - start: nodeStart, - end: lastEnd, - key, - value - }; - } - function parseArr() { - const nodeStart = start; - const values = []; - expect("["); - if (!skip("]")) { - do { - values.push(parseVal()); - } while (skip(",")); - expect("]"); - } - return { - kind: "Array", - start: nodeStart, - end: lastEnd, - values - }; - } - function parseVal() { - switch (kind) { - case "[": - return parseArr(); - case "{": - return parseObj(); - case "String": - case "Number": - case "Boolean": - case "Null": - const token = curToken(); - lex(); - return token; - } - expect("Value"); - } - function curToken() { - return { - kind, - start, - end, - value: JSON.parse(string.slice(start, end)) - }; - } - function expect(str) { - if (kind === str) { - lex(); - return; - } - let found; - if (kind === "EOF") { - found = "[end of file]"; - } else if (end - start > 1) { - found = "`" + string.slice(start, end) + "`"; - } else { - const match = string.slice(start).match(/^.+?\b/); - found = "`" + (match ? match[0] : string[start]) + "`"; - } - throw syntaxError(`Expected ${str} but found ${found}.`); - } - class JSONSyntaxError extends Error { - constructor(message, position) { - super(message); - this.position = position; - } - } - function syntaxError(message) { - return new JSONSyntaxError(message, { - start, - end - }); - } - function skip(k) { - if (kind === k) { - lex(); - return true; - } - } - function ch() { - if (end < strLen) { - end++; - code = end === strLen ? 0 : string.charCodeAt(end); - } - return code; - } - function lex() { - lastEnd = end; - while (code === 9 || code === 10 || code === 13 || code === 32) { - ch(); - } - if (code === 0) { - kind = "EOF"; - return; - } - start = end; - switch (code) { - case 34: - kind = "String"; - return readString(); - case 45: - case 48: - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - kind = "Number"; - return readNumber(); - case 102: - if (string.slice(start, start + 5) !== "false") { - break; + cm.state.draggingText = false; + if (cm.state.delayingBlurEvent) { + if (cm.hasFocus()) { + cm.state.delayingBlurEvent = false; + } else { + delayBlurEvent(cm); + } + } + off(display.wrapper.ownerDocument, "mouseup", dragEnd); + off(display.wrapper.ownerDocument, "mousemove", mouseMove); + off(display.scroller, "dragstart", dragStart); + off(display.scroller, "drop", dragEnd); + if (!moved) { + e_preventDefault(e); + if (!behavior.addNew) { + extendSelection(cm.doc, pos, null, null, behavior.extend); + } + if (webkit && !safari || ie && ie_version == 9) { + setTimeout(function () { + display.wrapper.ownerDocument.body.focus({ + preventScroll: true + }); + display.input.focus(); + }, 20); + } else { + display.input.focus(); + } + } + }); + var mouseMove = function (e2) { + moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; + }; + var dragStart = function () { + return moved = true; + }; + if (webkit) { + display.scroller.draggable = true; + } + cm.state.draggingText = dragEnd; + dragEnd.copy = !behavior.moveOnDrag; + on(display.wrapper.ownerDocument, "mouseup", dragEnd); + on(display.wrapper.ownerDocument, "mousemove", mouseMove); + on(display.scroller, "dragstart", dragStart); + on(display.scroller, "drop", dragEnd); + cm.state.delayingBlurEvent = true; + setTimeout(function () { + return display.input.focus(); + }, 20); + if (display.scroller.dragDrop) { + display.scroller.dragDrop(); } - end += 4; - ch(); - kind = "Boolean"; - return; - case 110: - if (string.slice(start, start + 4) !== "null") { - break; + } + function rangeForUnit(cm, pos, unit) { + if (unit == "char") { + return new Range(pos, pos); } - end += 3; - ch(); - kind = "Null"; - return; - case 116: - if (string.slice(start, start + 4) !== "true") { - break; + if (unit == "word") { + return cm.findWordAt(pos); } - end += 3; - ch(); - kind = "Boolean"; - return; - } - kind = string[start]; - ch(); - } - function readString() { - ch(); - while (code !== 34 && code > 31) { - if (code === 92) { - code = ch(); - switch (code) { - case 34: - case 47: - case 92: - case 98: - case 102: - case 110: - case 114: - case 116: - ch(); - break; - case 117: - ch(); - readHex(); - readHex(); - readHex(); - readHex(); - break; - default: - throw syntaxError("Bad character escape sequence."); + if (unit == "line") { + return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } - } else if (end === strLen) { - throw syntaxError("Unterminated string."); - } else { - ch(); - } - } - if (code === 34) { - ch(); - return; - } - throw syntaxError("Unterminated string."); - } - function readHex() { - if (code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102) { - return ch(); - } - throw syntaxError("Expected hexadecimal digit."); - } - function readNumber() { - if (code === 45) { - ch(); - } - if (code === 48) { - ch(); - } else { - readDigits(); - } - if (code === 46) { - ch(); - readDigits(); - } - if (code === 69 || code === 101) { - code = ch(); - if (code === 43 || code === 45) { - ch(); + var result = unit(cm, pos); + return new Range(result.from, result.to); } - readDigits(); - } - } - function readDigits() { - if (code < 48 || code > 57) { - throw syntaxError("Expected decimal digit."); - } - do { - ch(); - } while (code >= 48 && code <= 57); - } - codemirror.CodeMirror.registerHelper("lint", "graphql-variables", (text, options, editor) => { - if (!text) { - return []; - } - let ast; - try { - ast = jsonParse(text); - } catch (error) { - if (error instanceof JSONSyntaxError) { - return [lintError(editor, error.position, error.message)]; - } - throw error; - } - const { - variableToType - } = options; - if (!variableToType) { - return []; - } - return validateVariables(editor, variableToType, ast); - }); - function validateVariables(editor, variableToType, variablesAST) { - var _a; - const errors = []; - for (const member of variablesAST.members) { - if (member) { - const variableName = (_a = member.key) === null || _a === void 0 ? void 0 : _a.value; - const type = variableToType[variableName]; - if (type) { - for (const [node, message] of validateValue(type, member.value)) { - errors.push(lintError(editor, node, message)); + function leftButtonSelect(cm, event, start, behavior) { + if (ie) { + delayBlurEvent(cm); + } + var display = cm.display, + doc = cm.doc; + e_preventDefault(event); + var ourRange, + ourIndex, + startSel = doc.sel, + ranges = startSel.ranges; + if (behavior.addNew && !behavior.extend) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) { + ourRange = ranges[ourIndex]; + } else { + ourRange = new Range(start, start); } } else { - errors.push(lintError(editor, member.key, `Variable "$${variableName}" does not appear in any GraphQL query.`)); - } - } - } - return errors; - } - function validateValue(type, valueAST) { - if (!type || !valueAST) { - return []; - } - if (type instanceof graphql.GraphQLNonNull) { - if (valueAST.kind === "Null") { - return [[valueAST, `Type "${type}" is non-nullable and cannot be null.`]]; - } - return validateValue(type.ofType, valueAST); - } - if (valueAST.kind === "Null") { - return []; - } - if (type instanceof graphql.GraphQLList) { - const itemType = type.ofType; - if (valueAST.kind === "Array") { - const values = valueAST.values || []; - return mapCat(values, item => validateValue(itemType, item)); - } - return validateValue(itemType, valueAST); - } - if (type instanceof graphql.GraphQLInputObjectType) { - if (valueAST.kind !== "Object") { - return [[valueAST, `Type "${type}" must be an Object.`]]; - } - const providedFields = /* @__PURE__ */Object.create(null); - const fieldErrors = mapCat(valueAST.members, member => { - var _a; - const fieldName = (_a = member === null || member === void 0 ? void 0 : member.key) === null || _a === void 0 ? void 0 : _a.value; - providedFields[fieldName] = true; - const inputField = type.getFields()[fieldName]; - if (!inputField) { - return [[member.key, `Type "${type}" does not have a field "${fieldName}".`]]; - } - const fieldType = inputField ? inputField.type : void 0; - return validateValue(fieldType, member.value); - }); - for (const fieldName of Object.keys(type.getFields())) { - const field = type.getFields()[fieldName]; - if (!providedFields[fieldName] && field.type instanceof graphql.GraphQLNonNull && !field.defaultValue) { - fieldErrors.push([valueAST, `Object of type "${type}" is missing required field "${fieldName}".`]); + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; } - } - return fieldErrors; - } - if (type.name === "Boolean" && valueAST.kind !== "Boolean" || type.name === "String" && valueAST.kind !== "String" || type.name === "ID" && valueAST.kind !== "Number" && valueAST.kind !== "String" || type.name === "Float" && valueAST.kind !== "Number" || type.name === "Int" && (valueAST.kind !== "Number" || (valueAST.value | 0) !== valueAST.value)) { - return [[valueAST, `Expected value of type "${type}".`]]; - } - if ((type instanceof graphql.GraphQLEnumType || type instanceof graphql.GraphQLScalarType) && (valueAST.kind !== "String" && valueAST.kind !== "Number" && valueAST.kind !== "Boolean" && valueAST.kind !== "Null" || isNullish(type.parseValue(valueAST.value)))) { - return [[valueAST, `Expected value of type "${type}".`]]; - } - return []; - } - function lintError(editor, node, message) { - return { - message, - severity: "error", - type: "validation", - from: editor.posFromIndex(node.start), - to: editor.posFromIndex(node.end) - }; - } - function isNullish(value) { - return value === null || value === void 0 || value !== value; - } - function mapCat(array, mapper) { - return Array.prototype.concat.apply([], array.map(mapper)); - } - - /***/ }), - - /***/ "../../graphiql-react/dist/matchbrackets.cjs.js": - /*!******************************************************!*\ - !*** ../../graphiql-react/dist/matchbrackets.cjs.js ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - const matchbrackets$2 = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { + ourRange = new Range(start, start); + } + start = posFromMouse(cm, event, true, true); + ourIndex = -1; + } else { + var range2 = rangeForUnit(cm, start, behavior.unit); + if (behavior.extend) { + ourRange = extendRange(ourRange, range2.anchor, range2.head, behavior.extend); + } else { + ourRange = range2; } } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var matchbracketsExports = matchbrackets$2.requireMatchbrackets(); - const matchbrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(matchbracketsExports); - const matchbrackets$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: matchbrackets - }, [matchbracketsExports]); - exports.matchbrackets = matchbrackets$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/matchbrackets.cjs2.js": - /*!*******************************************************!*\ - !*** ../../graphiql-react/dist/matchbrackets.cjs2.js ***! - \*******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - var matchbrackets = { - exports: {} - }; - var hasRequiredMatchbrackets; - function requireMatchbrackets() { - if (hasRequiredMatchbrackets) return matchbrackets.exports; - hasRequiredMatchbrackets = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); - var Pos = CodeMirror.Pos; - var matching = { - "(": ")>", - ")": "(<", - "[": "]>", - "]": "[<", - "{": "}>", - "}": "{<", - "<": ">>", - ">": "<<" - }; - function bracketRegex(config) { - return config && config.bracketRegex || /[(){}[\]]/; - } - function findMatchingBracket(cm, where, config) { - var line = cm.getLineHandle(where.line), - pos = where.ch - 1; - var afterCursor = config && config.afterCursor; - if (afterCursor == null) afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className); - var re = bracketRegex(config); - var match = !afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)] || re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (config && config.strict && dir > 0 != (pos == where.ch)) return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config); - if (found == null) return null; - return { - from: Pos(where.line, pos), - to: found && found.pos, - match: found && found.ch == match.charAt(0), - forward: dir > 0 - }; + if (!behavior.addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), { + scroll: false, + origin: "*mouse" + }); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), { + scroll: false, + origin: "*mouse" + }); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); } - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = config && config.maxScanLineLength || 1e4; - var maxScanLines = config && config.maxScanLines || 1e3; - var stack = []; - var re = bracketRegex(config); - var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, - end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if (re.test(ch) && (style === void 0 || (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) { - var match = matching[ch]; - if (match && match.charAt(1) == ">" == dir > 0) stack.push(ch);else if (!stack.length) return { - pos: Pos(lineNo, pos), - ch - };else stack.pop(); + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { + return; + } + lastPos = pos; + if (behavior.unit == "rectangle") { + var ranges2 = [], + tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), + right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { + var text = getLine(doc, line).text, + leftPos = findColumn(text, left, tabSize); + if (left == right) { + ranges2.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); + } else if (text.length > leftPos) { + ranges2.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } } - } - return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; - } - function matchBrackets(cm, autoclear, config) { - var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1e3, - highlightNonMatching = config && config.highlightNonMatching; - var marks = [], - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); - if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) { - var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), { - className: style - })); - if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), { - className: style - })); + if (!ranges2.length) { + ranges2.push(new Range(start, start)); } - } - if (marks.length) { - if (ie_lt8 && cm.state.focused) cm.focus(); - var clear = function () { - cm.operation(function () { - for (var i2 = 0; i2 < marks.length; i2++) marks[i2].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800);else return clear; + setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges2), ourIndex), { + origin: "*mouse", + scroll: false + }); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var range3 = rangeForUnit(cm, pos, behavior.unit); + var anchor = oldRange.anchor, + head; + if (cmp(range3.anchor, anchor) > 0) { + head = range3.head; + anchor = minPos(oldRange.from(), range3.anchor); + } else { + head = range3.anchor; + anchor = maxPos(oldRange.to(), range3.head); + } + var ranges$1 = startSel.ranges.slice(0); + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); + setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); } } - function doMatchBrackets(cm) { - cm.operation(function () { - if (cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; + var editorSize = display.wrapper.getBoundingClientRect(); + var counter = 0; + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); + if (!cur) { + return; + } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) { + setTimeout(operation(cm, function () { + if (counter == curCount) { + extend(e); + } + }), 150); + } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { + setTimeout(operation(cm, function () { + if (counter != curCount) { + return; + } + display.scroller.scrollTop += outside; + extend(e); + }), 50); } - cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); - }); - } - function clearHighlighted(cm) { - if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; } } - CodeMirror.defineOption("matchBrackets", false, function (cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.off("cursorActivity", doMatchBrackets); - cm.off("focus", doMatchBrackets); - cm.off("blur", clearHighlighted); - clearHighlighted(cm); + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + if (e) { + e_preventDefault(e); + display.input.focus(); } - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - cm.on("focus", doMatchBrackets); - cm.on("blur", clearHighlighted); + off(display.wrapper.ownerDocument, "mousemove", move); + off(display.wrapper.ownerDocument, "mouseup", up); + doc.history.lastSelOrigin = null; + } + var move = operation(cm, function (e) { + if (e.buttons === 0 || !e_button(e)) { + done(e); + } else { + extend(e); } }); - CodeMirror.defineExtension("matchBrackets", function () { - matchBrackets(this, true); - }); - CodeMirror.defineExtension("findMatchingBracket", function (pos, config, oldConfig) { - if (oldConfig || typeof config == "boolean") { - if (!oldConfig) { - config = config ? { - strict: true - } : null; - } else { - oldConfig.strict = config; - config = oldConfig; - } + var up = operation(cm, done); + cm.state.selectingText = up; + on(display.wrapper.ownerDocument, "mousemove", move); + on(display.wrapper.ownerDocument, "mouseup", up); + } + function bidiSimplify(cm, range2) { + var anchor = range2.anchor; + var head = range2.head; + var anchorLine = getLine(cm.doc, anchor.line); + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { + return range2; + } + var order = getOrder(anchorLine); + if (!order) { + return range2; + } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), + part = order[index]; + if (part.from != anchor.ch && part.to != anchor.ch) { + return range2; + } + var boundary = index + (part.from == anchor.ch == (part.level != 1) ? 0 : 1); + if (boundary == 0 || boundary == order.length) { + return range2; + } + var leftSide; + if (head.line != anchor.line) { + leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky); + var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); + if (headIndex == boundary - 1 || headIndex == boundary) { + leftSide = dir < 0; + } else { + leftSide = dir > 0; } - return findMatchingBracket(this, pos, config); - }); - CodeMirror.defineExtension("scanForBracket", function (pos, dir, style, config) { - return scanForBracket(this, pos, dir, style, config); - }); - }); - })(); - return matchbrackets.exports; - } - exports.requireMatchbrackets = requireMatchbrackets; - - /***/ }), - - /***/ "../../graphiql-react/dist/mode-indent.cjs.js": - /*!****************************************************!*\ - !*** ../../graphiql-react/dist/mode-indent.cjs.js ***! - \****************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - function indent(state, textAfter) { - var _a, _b; - const { - levels, - indentLevel - } = state; - const level = !levels || levels.length === 0 ? indentLevel : levels.at(-1) - (((_a = this.electricInput) === null || _a === void 0 ? void 0 : _a.test(textAfter)) ? 1 : 0); - return (level || 0) * (((_b = this.config) === null || _b === void 0 ? void 0 : _b.indentUnit) || 0); - } - exports.indent = indent; - - /***/ }), - - /***/ "../../graphiql-react/dist/mode.cjs.js": - /*!*********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs.js ***! - \*********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); - const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); - const graphqlModeFactory = config => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: stream => stream.eatWhile(graphqlLanguageService.isIgnored), - lexRules: graphqlLanguageService.LexRules, - parseRules: graphqlLanguageService.ParseRules, - editorConfig: { - tabSize: config.tabSize - } - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[})\]]/, - fold: "brace", - lineComment: "#", - closeBrackets: { - pairs: '()[]{}""', - explode: "()[]{}" - } - }; - }; - codemirror.CodeMirror.defineMode("graphql", graphqlModeFactory); - - /***/ }), - - /***/ "../../graphiql-react/dist/mode.cjs2.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs2.js ***! - \**********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); - const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); - codemirror.CodeMirror.defineMode("graphql-variables", config => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: stream => stream.eatSpace(), - lexRules: LexRules, - parseRules: ParseRules, - editorConfig: { - tabSize: config.tabSize - } - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[}\]]/, - fold: "brace", - closeBrackets: { - pairs: '[]{}""', - explode: "[]{}" + } + var usePart = order[boundary + (leftSide ? -1 : 0)]; + var from = leftSide == (usePart.level == 1); + var ch = from ? usePart.from : usePart.to, + sticky = from ? "after" : "before"; + return anchor.ch == ch && anchor.sticky == sticky ? range2 : new Range(new Pos(anchor.line, ch, sticky), head); } - }; - }); - const LexRules = { - Punctuation: /^\[|]|\{|\}|:|,/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, - Keyword: /^true|false|null/ - }; - const ParseRules = { - Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Variable", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], - Variable: [namedKey("variable"), graphqlLanguageService.p(":"), "Value"], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; + function gutterEvent(cm, e, type, prevent) { + var mX, mY; + if (e.touches) { + mX = e.touches[0].clientX; + mY = e.touches[0].clientY; + } else { + try { + mX = e.clientX; + mY = e.clientY; + } catch (e$1) { + return false; } - return null; - case "Keyword": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - case "null": - return "NullValue"; + } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { + return false; + } + if (prevent) { + e_preventDefault(e); + } + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + if (mY > lineBox.bottom || !hasHandler(cm, type)) { + return e_defaultPrevented(e); + } + mY -= lineBox.top - display.viewOffset; + for (var i2 = 0; i2 < cm.display.gutterSpecs.length; ++i2) { + var g = display.gutters.childNodes[i2]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.display.gutterSpecs[i2]; + signal(cm, type, cm, line, gutter.className, e); + return e_defaultPrevented(e); } - return null; + } } - }, - NumberValue: [graphqlLanguageService.t("Number", "number")], - StringValue: [graphqlLanguageService.t("String", "string")], - BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], - NullValue: [graphqlLanguageService.t("Keyword", "keyword")], - ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("]")], - ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], - ObjectField: [namedKey("attribute"), graphqlLanguageService.p(":"), "Value"] - }; - function namedKey(style) { - return { - style, - match: token => token.kind === "String", - update(state, token) { - state.name = token.value.slice(1, -1); + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true); } - }; - } - - /***/ }), - - /***/ "../../graphiql-react/dist/mode.cjs3.js": - /*!**********************************************!*\ - !*** ../../graphiql-react/dist/mode.cjs3.js ***! - \**********************************************/ - /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); - const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); - const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); - codemirror.CodeMirror.defineMode("graphql-results", config => { - const parser = graphqlLanguageService.onlineParser({ - eatWhitespace: stream => stream.eatSpace(), - lexRules: LexRules, - parseRules: ParseRules, - editorConfig: { - tabSize: config.tabSize + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { + return; + } + if (signalDOMEvent(cm, e, "contextmenu")) { + return; + } + if (!captureRightClick) { + cm.display.input.onContextMenu(e); + } } - }); - return { - config, - startState: parser.startState, - token: parser.token, - indent: modeIndent.indent, - electricInput: /^\s*[}\]]/, - fold: "brace", - closeBrackets: { - pairs: '[]{}""', - explode: "[]{}" + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { + return false; + } + return gutterEvent(cm, e, "gutterContextMenu", false); } - }; - }); - const LexRules = { - Punctuation: /^\[|]|\{|\}|:|,/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, - Keyword: /^true|false|null/ - }; - const ParseRules = { - Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Entry", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], - Entry: [graphqlLanguageService.t("String", "def"), graphqlLanguageService.p(":"), "Value"], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; - } - return null; - case "Keyword": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - case "null": - return "NullValue"; - } - return null; + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); } - }, - NumberValue: [graphqlLanguageService.t("Number", "number")], - StringValue: [graphqlLanguageService.t("String", "string")], - BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], - NullValue: [graphqlLanguageService.t("Keyword", "keyword")], - ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.p(",")), graphqlLanguageService.p("]")], - ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], - ObjectField: [graphqlLanguageService.t("String", "property"), graphqlLanguageService.p(":"), "Value"] - }; - - /***/ }), - - /***/ "../../graphiql-react/dist/search.cjs.js": - /*!***********************************************!*\ - !*** ../../graphiql-react/dist/search.cjs.js ***! - \***********************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); - const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); - } + var Init = { + toString: function () { + return "CodeMirror.Init"; + } + }; + var defaults = {}; + var optionHandlers = {}; + function defineOptions(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + function option(name, deflt, handle, notOnInit) { + CodeMirror2.defaults[name] = deflt; + if (handle) { + optionHandlers2[name] = notOnInit ? function (cm, val, old) { + if (old != Init) { + handle(cm, val, old); + } + } : handle; } } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var search$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), dialog.dialogExports); - })(function (CodeMirror) { - CodeMirror.defineOption("search", { - bottom: false - }); - function searchOverlay(query, caseInsensitive) { - if (typeof query == "string") query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");else if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); - return { - token: function (stream) { - query.lastIndex = stream.pos; - var match = query.exec(stream.string); - if (match && match.index == stream.pos) { - stream.pos += match[0].length || 1; - return "searching"; - } else if (match) { - stream.pos = match.index; - } else { - stream.skipToEnd(); + CodeMirror2.defineOption = option; + CodeMirror2.Init = Init; + option("value", "", function (cm, val) { + return cm.setValue(val); + }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val; + if (!val) { + return; + } + var newBreaks = [], + lineNo2 = cm.doc.first; + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) { + break; + } + pos = found + val.length; + newBreaks.push(Pos(lineNo2, found)); } + lineNo2++; + }); + for (var i2 = newBreaks.length - 1; i2 >= 0; i2--) { + replaceRange(cm.doc, val, newBreaks[i2], Pos(newBreaks[i2].line, newBreaks[i2].ch + val.length)); } - }; - } - function SearchState() { - this.posFrom = this.posTo = this.lastQuery = this.query = null; - this.overlay = null; - } - function getSearchState(cm) { - return cm.state.search || (cm.state.search = new SearchState()); - } - function queryCaseInsensitive(query) { - return typeof query == "string" && query == query.toLowerCase(); - } - function getSearchCursor(cm, query, pos) { - return cm.getSearchCursor(query, pos, { - caseFold: queryCaseInsensitive(query), - multiline: true }); - } - function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { - cm.openDialog(text, onEnter, { - value: deflt, - selectValueOnOpen: true, - closeOnEnter: false, - onClose: function () { - clearSearch(cm); - }, - onKeyDown, - bottom: cm.options.search.bottom + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test(" ") ? "" : "| "), "g"); + if (old != Init) { + cm.refresh(); + } }); - } - function dialog2(cm, text, shortText, deflt, f) { - if (cm.openDialog) cm.openDialog(text, f, { - value: deflt, - selectValueOnOpen: true, - bottom: cm.options.search.bottom - });else f(prompt(shortText, deflt)); - } - function confirmDialog(cm, text, shortText, fs) { - if (cm.openConfirm) cm.openConfirm(text, fs);else if (confirm(shortText)) fs[0](); - } - function parseString(string) { - return string.replace(/\\([nrt\\])/g, function (match, ch) { - if (ch == "n") return "\n"; - if (ch == "r") return "\r"; - if (ch == "t") return " "; - if (ch == "\\") return "\\"; - return match; + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { + return cm.refresh(); + }, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor"); + }, true); + option("spellcheck", false, function (cm, val) { + return cm.getInputField().spellcheck = val; + }, true); + option("autocorrect", false, function (cm, val) { + return cm.getInputField().autocorrect = val; + }, true); + option("autocapitalize", false, function (cm, val) { + return cm.getInputField().autocapitalize = val; + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + option("theme", "default", function (cm) { + themeChanged(cm); + updateGutters(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != Init && getKeyMap(old); + if (prev && prev.detach) { + prev.detach(cm, next); + } + if (next.attach) { + next.attach(cm, prev || null); + } }); - } - function parseQuery(query) { - var isRE = query.match(/^\/(.*)\/([a-z]*)$/); - if (isRE) { - try { - query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); - } catch (e) {} + option("extraKeys", null); + option("configureMouse", null); + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm, val) { + cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); + updateGutters(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) { + return updateScrollbars(cm); + }, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm, val) { + cm.display.gutterSpecs = getGutters(cm.options.gutters, val); + updateGutters(cm); + }, true); + option("firstLineNumber", 1, updateGutters, true); + option("lineNumberFormatter", function (integer) { + return integer; + }, updateGutters, true); + option("showCursorWhenSelecting", false, updateSelection, true); + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + option("selectionsMayTouch", false); + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + } + cm.display.input.readOnlyChanged(val); + }); + option("screenReaderLabel", null, function (cm, val) { + val = val === "" ? null : val; + cm.display.input.screenReaderLabelChanged(val); + }); + option("disableInput", false, function (cm, val) { + if (!val) { + cm.display.input.reset(); + } + }, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) { + return cm.doc.history.undoDepth = val; + }); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) { + return cm.refresh(); + }, true); + option("maxHighlightLength", 1e4, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { + cm.display.input.resetPosition(); + } + }); + option("tabindex", null, function (cm, val) { + return cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + option("direction", "ltr", function (cm, val) { + return cm.doc.setDirection(val); + }, true); + option("phrases", null); + } + function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; } else { - query = parseString(query); + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); } - if (typeof query == "string" ? query == "" : query.test("")) query = /x^/; - return query; - } - function startSearch(cm, state, query) { - state.queryText = query; - state.query = parseQuery(query); - cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); - state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); - cm.addOverlay(state.overlay); - if (cm.showMatchesOnScrollbar) { - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () { + return updateScrollbars(cm); + }, 100); + } + function CodeMirror(place, options) { + var this$1$1 = this; + if (!(this instanceof CodeMirror)) { + return new CodeMirror(place, options); + } + this.options = options = options ? copyObj(options) : {}; + copyObj(defaults, options, false); + var doc = options.value; + if (typeof doc == "string") { + doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); + } else if (options.mode) { + doc.modeOption = options.mode; + } + this.doc = doc; + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input, options); + display.wrapper.CodeMirror = this; + themeChanged(this); + if (options.lineWrapping) { + this.display.wrapper.className += " CodeMirror-wrap"; + } + initScrollbars(this); + this.state = { + keyMaps: [], + // stores maps added by addKeyMap + overlays: [], + // highlighting overlays, as added by addOverlay + modeGen: 0, + // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, + // used to disable editing during key handlers when in readOnly mode + pasteIncoming: -1, + cutIncoming: -1, + // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), + // stores highlight worker timeout + keySeq: null, + // Unfinished key sequence + specialChars: null + }; + if (options.autofocus && !mobile) { + display.input.focus(); + } + if (ie && ie_version < 11) { + setTimeout(function () { + return this$1$1.display.input.reset(true); + }, 20); + } + registerEventHandlers(this); + ensureGlobalHandlers(); + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + if (options.autofocus && !mobile || this.hasFocus()) { + setTimeout(function () { + if (this$1$1.hasFocus() && !this$1$1.state.focused) { + onFocus(this$1$1); + } + }, 20); + } else { + onBlur(this); + } + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) { + optionHandlers[opt](this, options[opt], Init); } - state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) { + options.finishInit(this); + } + for (var i2 = 0; i2 < initHooks.length; ++i2) { + initHooks[i2](this); + } + endOperation(this); + if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { + display.lineDiv.style.textRendering = "auto"; } } - function doSearch(cm, rev, persistent, immediate) { - var state = getSearchState(cm); - if (state.query) return findNext(cm, rev); - var q = cm.getSelection() || state.lastQuery; - if (q instanceof RegExp && q.source == "x^") q = null; - if (persistent && cm.openDialog) { - var hiding = null; - var searchNext = function (query, event) { - CodeMirror.e_stop(event); - if (!query) return; - if (query != state.queryText) { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); + CodeMirror.defaults = defaults; + CodeMirror.optionHandlers = optionHandlers; + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + if (ie && ie_version < 11) { + on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { + return; } - if (hiding) hiding.style.opacity = 1; - findNext(cm, event.shiftKey, function (_, to) { - var dialog3; - if (to.line < 3 && document.querySelector && (dialog3 = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && dialog3.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) (hiding = dialog3).style.opacity = 0.4; - }); - }; - persistentDialog(cm, getQueryDialog(cm), q, searchNext, function (event, query) { - var keyName = CodeMirror.keyName(event); - var extra = cm.getOption("extraKeys"), - cmd = extra && extra[keyName] || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; - if (cmd == "findNext" || cmd == "findPrev" || cmd == "findPersistentNext" || cmd == "findPersistentPrev") { - CodeMirror.e_stop(event); - startSearch(cm, getSearchState(cm), query); - cm.execCommand(cmd); - } else if (cmd == "find" || cmd == "findPersistent") { - CodeMirror.e_stop(event); - searchNext(query, event); + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { + return; } - }); - if (immediate && q) { - startSearch(cm, state, q); - findNext(cm, rev); - } + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); } else { - dialog2(cm, getQueryDialog(cm), "Search for:", q, function (query) { - if (query && !state.query) cm.operation(function () { - startSearch(cm, state, query); - state.posFrom = state.posTo = cm.getCursor(); - findNext(cm, rev); - }); + on(d.scroller, "dblclick", function (e) { + return signalDOMEvent(cm, e) || e_preventDefault(e); }); } - } - function findNext(cm, rev, callback) { - cm.operation(function () { - var state = getSearchState(cm); - var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); - if (!cursor.find(rev)) { - cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); - if (!cursor.find(rev)) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to() - }, 20); - state.posFrom = cursor.from(); - state.posTo = cursor.to(); - if (callback) callback(cursor.from(), cursor.to()); + on(d.scroller, "contextmenu", function (e) { + return onContextMenu(cm, e); }); - } - function clearSearch(cm) { - cm.operation(function () { - var state = getSearchState(cm); - state.lastQuery = state.query; - if (!state.query) return; - state.query = state.queryText = null; - cm.removeOverlay(state.overlay); - if (state.annotate) { - state.annotate.clear(); - state.annotate = null; + on(d.input.getField(), "contextmenu", function (e) { + if (!d.scroller.contains(e.target)) { + onContextMenu(cm, e); } }); - } - function el(tag, attrs) { - var element = tag ? document.createElement(tag) : document.createDocumentFragment(); - for (var key in attrs) { - element[key] = attrs[key]; + var touchFinished, + prevTouch = { + end: 0 + }; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { + return d.activeTouch = null; + }, 1e3); + prevTouch = d.activeTouch; + prevTouch.end = + /* @__PURE__ */new Date(); + } } - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - element.appendChild(typeof child == "string" ? document.createTextNode(child) : child); + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { + return false; + } + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; } - return element; - } - function getQueryDialog(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("Search:")), " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - }), " ", el("span", { - style: "color: #888", - className: "CodeMirror-search-hint" - }, cm.phrase("(Use /re/ syntax for regexp search)"))); - } - function getReplaceQueryDialog(cm) { - return el("", null, " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - }), " ", el("span", { - style: "color: #888", - className: "CodeMirror-search-hint" - }, cm.phrase("(Use /re/ syntax for regexp search)"))); - } - function getReplacementQueryDialog(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("With:")), " ", el("input", { - type: "text", - "style": "width: 10em", - className: "CodeMirror-search-field" - })); - } - function getDoReplaceConfirm(cm) { - return el("", null, el("span", { - className: "CodeMirror-search-label" - }, cm.phrase("Replace?")), " ", el("button", {}, cm.phrase("Yes")), " ", el("button", {}, cm.phrase("No")), " ", el("button", {}, cm.phrase("All")), " ", el("button", {}, cm.phrase("Stop"))); - } - function replaceAll(cm, query, text) { - cm.operation(function () { - for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { - if (typeof query != "string") { - var match = cm.getRange(cursor.from(), cursor.to()).match(query); - cursor.replace(text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - })); - } else cursor.replace(text); + function farAway(touch, other) { + if (other.left == null) { + return true; } - }); - } - function replace(cm, all) { - if (cm.getOption("readOnly")) return; - var query = cm.getSelection() || getSearchState(cm).lastQuery; - var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:"); - var fragment = el("", null, el("span", { - className: "CodeMirror-search-label" - }, dialogText), getReplaceQueryDialog(cm)); - dialog2(cm, fragment, dialogText, query, function (query2) { - if (!query2) return; - query2 = parseQuery(query2); - dialog2(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function (text) { - text = parseString(text); - if (all) { - replaceAll(cm, query2, text); - } else { - clearSearch(cm); - var cursor = getSearchCursor(cm, query2, cm.getCursor("from")); - var advance = function () { - var start = cursor.from(), - match; - if (!(match = cursor.findNext())) { - cursor = getSearchCursor(cm, query2); - if (!(match = cursor.findNext()) || start && cursor.from().line == start.line && cursor.from().ch == start.ch) return; - } - cm.setSelection(cursor.from(), cursor.to()); - cm.scrollIntoView({ - from: cursor.from(), - to: cursor.to() - }); - confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"), [function () { - doReplace(match); - }, advance, function () { - replaceAll(cm, query2, text); - }]); - }; - var doReplace = function (match) { - cursor.replace(typeof query2 == "string" ? text : text.replace(/\$(\d)/g, function (_, i) { - return match[i]; - })); - advance(); - }; - advance(); + var dx = other.left - touch.left, + dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { + d.input.ensurePolled(); + clearTimeout(touchFinished); + var now = + /* @__PURE__ */new Date(); + d.activeTouch = { + start: now, + moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null + }; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; } - }); + } }); - } - CodeMirror.commands.find = function (cm) { - clearSearch(cm); - doSearch(cm); - }; - CodeMirror.commands.findPersistent = function (cm) { - clearSearch(cm); - doSearch(cm, false, true); - }; - CodeMirror.commands.findPersistentNext = function (cm) { - doSearch(cm, false, true, true); - }; - CodeMirror.commands.findPersistentPrev = function (cm) { - doSearch(cm, true, true, true); - }; - CodeMirror.commands.findNext = doSearch; - CodeMirror.commands.findPrev = function (cm) { - doSearch(cm, true); - }; - CodeMirror.commands.clearSearch = clearSearch; - CodeMirror.commands.replace = replace; - CodeMirror.commands.replaceAll = function (cm) { - replace(cm, true); - }; - }); - })(); - var searchExports = search$2.exports; - const search = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchExports); - const search$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: search - }, [searchExports]); - exports.search = search$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/searchcursor.cjs.js": - /*!*****************************************************!*\ - !*** ../../graphiql-react/dist/searchcursor.cjs.js ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - const searchcursor$2 = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { + d.activeTouch.moved = true; + } + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && /* @__PURE__ */new Date() - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), + range2; + if (!touch.prev || farAway(touch, touch.prev)) { + range2 = new Range(pos, pos); + } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) { + range2 = cm.findWordAt(pos); + } else { + range2 = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } + cm.setSelection(range2.anchor, range2.head); + cm.focus(); + e_preventDefault(e); } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var searchcursorExports = searchcursor$2.requireSearchcursor(); - const searchcursor = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchcursorExports); - const searchcursor$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: searchcursor - }, [searchcursorExports]); - exports.searchcursor = searchcursor$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/searchcursor.cjs2.js": - /*!******************************************************!*\ - !*** ../../graphiql-react/dist/searchcursor.cjs2.js ***! - \******************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - var searchcursor = { - exports: {} - }; - var hasRequiredSearchcursor; - function requireSearchcursor() { - if (hasRequiredSearchcursor) return searchcursor.exports; - hasRequiredSearchcursor = 1; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var Pos = CodeMirror.Pos; - function regexpFlags(regexp) { - var flags = regexp.flags; - return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : ""); - } - function ensureFlags(regexp, flags) { - var current = regexpFlags(regexp), - target = current; - for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) target += flags.charAt(i); - return current == target ? regexp : new RegExp(regexp.source, target); - } - function maybeMultiline(regexp) { - return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); - } - function searchRegexpForward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { - regexp.lastIndex = ch; - var string = doc.getLine(line), - match = regexp.exec(string); - if (match) return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match - }; + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); } - } - function searchRegexpForwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunk = 1; - for (var line = start.line, last = doc.lastLine(); line <= last;) { - for (var i = 0; i < chunk; i++) { - if (line > last) break; - var curLine = doc.getLine(line++); - string = string == null ? curLine : string + "\n" + curLine; + }); + on(d.scroller, "mousewheel", function (e) { + return onScrollWheel(cm, e); + }); + on(d.scroller, "DOMMouseScroll", function (e) { + return onScrollWheel(cm, e); + }); + on(d.wrapper, "scroll", function () { + return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; + }); + d.dragFunctions = { + enter: function (e) { + if (!signalDOMEvent(cm, e)) { + e_stop(e); } - chunk = chunk * 2; - regexp.lastIndex = start.ch; - var match = regexp.exec(string); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = start.line + before.length - 1, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match - }; + }, + over: function (e) { + if (!signalDOMEvent(cm, e)) { + onDragOver(cm, e); + e_stop(e); + } + }, + start: function (e) { + return onDragStart(cm, e); + }, + drop: operation(cm, onDrop), + leave: function (e) { + if (!signalDOMEvent(cm, e)) { + clearDragCursor(cm); + } + } + }; + var inp = d.input.getField(); + on(inp, "keyup", function (e) { + return onKeyUp.call(cm, e); + }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", function (e) { + return onFocus(cm, e); + }); + on(inp, "blur", function (e) { + return onBlur(cm, e); + }); + } + var initHooks = []; + CodeMirror.defineInitHook = function (f) { + return initHooks.push(f); + }; + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, + state; + if (how == null) { + how = "add"; + } + if (how == "smart") { + if (!doc.mode.indent) { + how = "prev"; + } else { + state = getContextBefore(cm, n).state; + } + } + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), + curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) { + line.stateAfter = null; + } + var curSpaceString = line.text.match(/^\s*/)[0], + indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) { + return; } + how = "prev"; } } - function lastMatchIn(string, regexp, endMargin) { - var match, - from = 0; - while (from <= string.length) { - regexp.lastIndex = from; - var newMatch = regexp.exec(string); - if (!newMatch) break; - var end = newMatch.index + newMatch[0].length; - if (end > string.length - endMargin) break; - if (!match || end > match.index + match[0].length) match = newMatch; - from = newMatch.index + 1; + if (how == "prev") { + if (n > doc.first) { + indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); + } else { + indentation = 0; } - return match; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; } - function searchRegexpBackward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g"); - for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { - var string = doc.getLine(line); - var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch); - if (match) return { - from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match - }; + indentation = Math.max(0, indentation); + var indentString = "", + pos = 0; + if (cm.options.indentWithTabs) { + for (var i2 = Math.floor(indentation / tabSize); i2; --i2) { + pos += tabSize; + indentString += " "; } } - function searchRegexpBackwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start); - regexp = ensureFlags(regexp, "gm"); - var string, - chunkSize = 1, - endMargin = doc.getLine(start.line).length - start.ch; - for (var line = start.line, first = doc.firstLine(); line >= first;) { - for (var i = 0; i < chunkSize && line >= first; i++) { - var curLine = doc.getLine(line--); - string = string == null ? curLine : curLine + "\n" + string; - } - chunkSize *= 2; - var match = lastMatchIn(string, regexp, endMargin); - if (match) { - var before = string.slice(0, match.index).split("\n"), - inside = match[0].split("\n"); - var startLine = line + before.length, - startCh = before[before.length - 1].length; - return { - from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match - }; + if (pos < indentation) { + indentString += spaceStr(indentation - pos); + } + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } else { + for (var i$12 = 0; i$12 < doc.sel.ranges.length; i$12++) { + var range2 = doc.sel.ranges[i$12]; + if (range2.head.line == n && range2.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i$12, new Range(pos$1, pos$1)); + break; } } } - var doFold, noFold; - if (String.prototype.normalize) { - doFold = function (str) { - return str.normalize("NFD").toLowerCase(); - }; - noFold = function (str) { - return str.normalize("NFD"); - }; - } else { - doFold = function (str) { - return str.toLowerCase(); - }; - noFold = function (str) { - return str; - }; + } + var lastCopied = null; + function setLastCopied(newLastCopied) { + lastCopied = newLastCopied; + } + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) { + sel = doc.sel; } - function adjustPos(orig, folded, pos, foldFunc) { - if (orig.length == folded.length) return pos; - for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { - if (min == max) return min; - var mid = min + max >> 1; - var len = foldFunc(orig.slice(0, mid)).length; - if (len == pos) return mid;else if (len > pos) max = mid;else min = mid + 1; - } - } - function searchStringForward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { - var orig = doc.getLine(line).slice(ch), - string = fold(orig); - if (lines.length == 1) { - var found = string.indexOf(lines[0]); - if (found == -1) continue search; - var start = adjustPos(orig, string, found, fold) + ch; - return { - from: Pos(line, adjustPos(orig, string, found, fold) + ch), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch) - }; - } else { - var cutFrom = string.length - lines[0].length; - if (string.slice(cutFrom) != lines[0]) continue search; - for (var i = 1; i < lines.length - 1; i++) if (fold(doc.getLine(line + i)) != lines[i]) continue search; - var end = doc.getLine(line + lines.length - 1), - endString = fold(end), - lastLine = lines[lines.length - 1]; - if (endString.slice(0, lastLine.length) != lastLine) continue search; - return { - from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), - to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold)) - }; + var recent = + /* @__PURE__ */new Date() - 200; + var paste = origin == "paste" || cm.state.pasteIncoming > recent; + var textLines = splitLinesAuto(inserted), + multiPaste = null; + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i2 = 0; i2 < lastCopied.text.length; i2++) { + multiPaste.push(doc.splitLines(lastCopied.text[i2])); + } } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, function (l) { + return [l]; + }); } } - function searchStringBackward(doc, query, start, caseFold) { - if (!query.length) return null; - var fold = caseFold ? doFold : noFold; - var lines = fold(query).split(/\r|\n\r?/); - search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { - var orig = doc.getLine(line); - if (ch > -1) orig = orig.slice(0, ch); - var string = fold(orig); - if (lines.length == 1) { - var found = string.lastIndexOf(lines[0]); - if (found == -1) continue search; - return { - from: Pos(line, adjustPos(orig, string, found, fold)), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold)) - }; - } else { - var lastLine = lines[lines.length - 1]; - if (string.slice(0, lastLine.length) != lastLine) continue search; - for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) if (fold(doc.getLine(start + i)) != lines[i]) continue search; - var top = doc.getLine(line + 1 - lines.length), - topString = fold(top); - if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search; - return { - from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), - to: Pos(line, adjustPos(orig, string, lastLine.length, fold)) - }; + var updateInput = cm.curOp.updateInput; + for (var i$12 = sel.ranges.length - 1; i$12 >= 0; i$12--) { + var range2 = sel.ranges[i$12]; + var from = range2.from(), + to = range2.to(); + if (range2.empty()) { + if (deleted && deleted > 0) { + from = Pos(from.line, from.ch - deleted); + } else if (cm.state.overwrite && !paste) { + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); + } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) { + from = to = Pos(from.line, 0); } } - } - function SearchCursor(doc, query, pos, options) { - this.atOccurrence = false; - this.afterEmptyMatch = false; - this.doc = doc; - pos = pos ? doc.clipPos(pos) : Pos(0, 0); - this.pos = { - from: pos, - to: pos + var changeEvent = { + from, + to, + text: multiPaste ? multiPaste[i$12 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input") }; - var caseFold; - if (typeof options == "object") { - caseFold = options.caseFold; - } else { - caseFold = options; - options = null; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) { + triggerElectric(cm, inserted); + } + ensureCursorVisible(cm); + if (cm.curOp.updateInput < 2) { + cm.curOp.updateInput = updateInput; + } + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = -1; + } + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput) { + runInOp(cm, function () { + return applyTextInput(cm, pasted, 0, null, "paste"); + }); } - if (typeof query == "string") { - if (caseFold == null) caseFold = false; - this.matches = function (reverse, pos2) { - return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos2, caseFold); - }; - } else { - query = ensureFlags(query, "gm"); - if (!options || options.multiline !== false) this.matches = function (reverse, pos2) { - return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos2); - };else this.matches = function (reverse, pos2) { - return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos2); - }; + return true; + } + } + function triggerElectric(cm, inserted) { + if (!cm.options.electricChars || !cm.options.smartIndent) { + return; + } + var sel = cm.doc.sel; + for (var i2 = sel.ranges.length - 1; i2 >= 0; i2--) { + var range2 = sel.ranges[i2]; + if (range2.head.ch > 100 || i2 && sel.ranges[i2 - 1].head.line == range2.head.line) { + continue; + } + var mode = cm.getModeAt(range2.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range2.head.line, "smart"); + break; + } + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range2.head.line).text.slice(0, range2.head.ch))) { + indented = indentLine(cm, range2.head.line, "smart"); + } + } + if (indented) { + signalLater(cm, "electricInput", cm, range2.head.line); } } - SearchCursor.prototype = { - findNext: function () { - return this.find(false); + } + function copyableRanges(cm) { + var text = [], + ranges = []; + for (var i2 = 0; i2 < cm.doc.sel.ranges.length; i2++) { + var line = cm.doc.sel.ranges[i2].head.line; + var lineRange = { + anchor: Pos(line, 0), + head: Pos(line + 1, 0) + }; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return { + text, + ranges + }; + } + function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { + field.setAttribute("autocorrect", autocorrect ? "" : "off"); + field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); + field.setAttribute("spellcheck", !!spellcheck); + } + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + if (webkit) { + te.style.width = "1000px"; + } else { + te.setAttribute("wrap", "off"); + } + if (ios) { + te.style.border = "1px solid black"; + } + disableBrowserMagic(te); + return div; + } + function addEditorMethods(CodeMirror2) { + var optionHandlers2 = CodeMirror2.optionHandlers; + var helpers = CodeMirror2.helpers = {}; + CodeMirror2.prototype = { + constructor: CodeMirror2, + focus: function () { + window.focus(); + this.display.input.focus(); + }, + setOption: function (option, value) { + var options = this.options, + old = options[option]; + if (options[option] == value && option != "mode") { + return; + } + options[option] = value; + if (optionHandlers2.hasOwnProperty(option)) { + operation(this, optionHandlers2[option])(this, value, old); + } + signal(this, "optionChange", this, option); }, - findPrevious: function () { - return this.find(true); + getOption: function (option) { + return this.options[option]; }, - find: function (reverse) { - var head = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); - if (this.afterEmptyMatch && this.atOccurrence) { - head = Pos(head.line, head.ch); - if (reverse) { - head.ch--; - if (head.ch < 0) { - head.line--; - head.ch = (this.doc.getLine(head.line) || "").length; - } + getDoc: function () { + return this.doc; + }, + addKeyMap: function (map2, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map2)); + }, + removeKeyMap: function (map2) { + var maps = this.state.keyMaps; + for (var i2 = 0; i2 < maps.length; ++i2) { + if (maps[i2] == map2 || maps[i2].name == map2) { + maps.splice(i2, 1); + return true; + } + } + }, + addOverlay: methodOp(function (spec, options) { + var mode = spec.token ? spec : CodeMirror2.getMode(this.options, spec); + if (mode.startState) { + throw new Error("Overlays may not be stateful."); + } + insertSorted(this.state.overlays, { + mode, + modeSpec: spec, + opaque: options && options.opaque, + priority: options && options.priority || 0 + }, function (overlay) { + return overlay.priority; + }); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function (spec) { + var overlays = this.state.overlays; + for (var i2 = 0; i2 < overlays.length; ++i2) { + var cur = overlays[i2].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i2, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + indentLine: methodOp(function (n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { + dir = this.options.smartIndent ? "smart" : "prev"; } else { - head.ch++; - if (head.ch > (this.doc.getLine(head.line) || "").length) { - head.ch = 0; - head.line++; + dir = dir ? "add" : "subtract"; + } + } + if (isLine(this.doc, n)) { + indentLine(this, n, dir, aggressive); + } + }), + indentSelection: methodOp(function (how) { + var ranges = this.doc.sel.ranges, + end = -1; + for (var i2 = 0; i2 < ranges.length; i2++) { + var range2 = ranges[i2]; + if (!range2.empty()) { + var from = range2.from(), + to = range2.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) { + indentLine(this, j, how); + } + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i2].from().ch > 0) { + replaceOneSelection(this.doc, i2, new Range(from, newRanges[i2].to()), sel_dontScroll); + } + } else if (range2.head.line > end) { + indentLine(this, range2.head.line, how, true); + end = range2.head.line; + if (i2 == this.doc.sel.primIndex) { + ensureCursorVisible(this); } } - if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { - return this.atOccurrence = false; + } + }), + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function (pos, precise) { + return takeToken(this, pos, precise); + }, + getLineTokens: function (line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + getTokenTypeAt: function (pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, + after = (styles.length - 1) / 2, + ch = pos.ch; + var type; + if (ch == 0) { + type = styles[2]; + } else { + for (;;) { + var mid = before + after >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { + after = mid; + } else if (styles[mid * 2 + 1] < ch) { + before = mid + 1; + } else { + type = styles[mid * 2 + 2]; + break; + } } } - var result = this.matches(reverse, head); - this.afterEmptyMatch = result && CodeMirror.cmpPos(result.from, result.to) == 0; - if (result) { - this.pos = result; - this.atOccurrence = true; - return this.pos.match || true; + var cut = type ? type.indexOf("overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + getModeAt: function (pos) { + var mode = this.doc.mode; + if (!mode.innerMode) { + return mode; + } + return CodeMirror2.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + getHelper: function (pos, type) { + return this.getHelpers(pos, type)[0]; + }, + getHelpers: function (pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) { + return found; + } + var help = helpers[type], + mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) { + found.push(help[mode[type]]); + } + } else if (mode[type]) { + for (var i2 = 0; i2 < mode[type].length; i2++) { + var val = help[mode[type][i2]]; + if (val) { + found.push(val); + } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i$12 = 0; i$12 < help._global.length; i$12++) { + var cur = help._global[i$12]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) { + found.push(cur.val); + } + } + return found; + }, + getStateAfter: function (line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); + return getContextBefore(this, line + 1, precise).state; + }, + cursorCoords: function (start, mode) { + var pos, + range2 = this.doc.sel.primary(); + if (start == null) { + pos = range2.head; + } else if (typeof start == "object") { + pos = clipPos(this.doc, start); } else { - var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0); - this.pos = { - from: end, - to: end - }; - return this.atOccurrence = false; + pos = start ? range2.from() : range2.to(); } + return cursorCoords(this, pos, mode || "page"); }, - from: function () { - if (this.atOccurrence) return this.pos.from; + charCoords: function (pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); }, - to: function () { - if (this.atOccurrence) return this.pos.to; + coordsChar: function (coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); }, - replace: function (newText, origin) { - if (!this.atOccurrence) return; - var lines = CodeMirror.splitLines(newText); - this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin); - this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); - } - }; - CodeMirror.defineExtension("getSearchCursor", function (query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold); - }); - CodeMirror.defineDocExtension("getSearchCursor", function (query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold); - }); - CodeMirror.defineExtension("selectMatches", function (query, caseFold) { - var ranges = []; - var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); - while (cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; - ranges.push({ - anchor: cur.from(), - head: cur.to() - }); - } - if (ranges.length) this.setSelections(ranges, 0); - }); - }); - })(); - return searchcursor.exports; - } - exports.requireSearchcursor = requireSearchcursor; - - /***/ }), - - /***/ "../../graphiql-react/dist/show-hint.cjs.js": - /*!**************************************************!*\ - !*** ../../graphiql-react/dist/show-hint.cjs.js ***! - \**************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] + lineAtHeight: function (height, mode) { + height = fromCoordSystem(this, { + top: height, + left: 0 + }, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function (line, mode, includeWidgets) { + var end = false, + lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) { + line = this.doc.first; + } else if (line > last) { + line = last; + end = true; + } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, { + top: 0, + left: 0 + }, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + defaultTextHeight: function () { + return textHeight(this.display); + }, + defaultCharWidth: function () { + return charWidth(this.display); + }, + getViewport: function () { + return { + from: this.display.viewFrom, + to: this.display.viewTo + }; + }, + addWidget: function (pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, + left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { + top = pos.top - node.offsetHeight; + } else if (pos.bottom + node.offsetHeight <= vspace) { + top = pos.bottom; + } + if (left + node.offsetWidth > hspace) { + left = hspace - node.offsetWidth; + } + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") { + left = 0; + } else if (horiz == "middle") { + left = (display.sizer.clientWidth - node.offsetWidth) / 2; + } + node.style.left = left + "px"; + } + if (scroll) { + scrollIntoView(this, { + left, + top, + right: left + node.offsetWidth, + bottom: top + node.offsetHeight }); } - } - } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var showHint$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror()); - })(function (CodeMirror) { - var HINT_ELEMENT_CLASS = "CodeMirror-hint"; - var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; - CodeMirror.showHint = function (cm, getHints, options) { - if (!getHints) return cm.showHint(options); - if (options && options.async) getHints.async = true; - var newOpts = { - hint: getHints - }; - if (options) for (var prop in options) newOpts[prop] = options[prop]; - return cm.showHint(newOpts); - }; - CodeMirror.defineExtension("showHint", function (options) { - options = parseOptions(this, this.getCursor("start"), options); - var selections = this.listSelections(); - if (selections.length > 1) return; - if (this.somethingSelected()) { - if (!options.hint.supportsSelection) return; - for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; - } - if (this.state.completionActive) this.state.completionActive.close(); - var completion = this.state.completionActive = new Completion(this, options); - if (!completion.options.hint) return; - CodeMirror.signal(this, "startCompletion", this); - completion.update(true); - }); - CodeMirror.defineExtension("closeHint", function () { - if (this.state.completionActive) this.state.completionActive.close(); - }); - function Completion(cm, options) { - this.cm = cm; - this.options = options; - this.widget = null; - this.debounce = 0; - this.tick = 0; - this.startPos = this.cm.getCursor("start"); - this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; - if (this.options.updateOnCursorActivity) { - var self = this; - cm.on("cursorActivity", this.activityFunc = function () { - self.cursorActivity(); - }); - } - } - var requestAnimationFrame = window.requestAnimationFrame || function (fn) { - return setTimeout(fn, 1e3 / 60); - }; - var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; - Completion.prototype = { - close: function () { - if (!this.active()) return; - this.cm.state.completionActive = null; - this.tick = null; - if (this.options.updateOnCursorActivity) { - this.cm.off("cursorActivity", this.activityFunc); - } - if (this.widget && this.data) CodeMirror.signal(this.data, "close"); - if (this.widget) this.widget.close(); - CodeMirror.signal(this.cm, "endCompletion", this.cm); - }, - active: function () { - return this.cm.state.completionActive == this; - }, - pick: function (data, i) { - var completion = data.list[i], - self = this; - this.cm.operation(function () { - if (completion.hint) completion.hint(self.cm, data, completion);else self.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); - CodeMirror.signal(data, "pick", completion); - self.cm.scrollIntoView(); - }); - if (this.options.closeOnPick) { - this.close(); - } - }, - cursorActivity: function () { - if (this.debounce) { - cancelAnimationFrame(this.debounce); - this.debounce = 0; - } - var identStart = this.startPos; - if (this.data) { - identStart = this.data.from; - } - var pos = this.cm.getCursor(), - line = this.cm.getLine(pos.line); - if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < identStart.ch || this.cm.somethingSelected() || !pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1))) { - this.close(); - } else { - var self = this; - this.debounce = requestAnimationFrame(function () { - self.update(); - }); - if (this.widget) this.widget.disable(); - } - }, - update: function (first) { - if (this.tick == null) return; - var self = this, - myTick = ++this.tick; - fetchHints(this.options.hint, this.cm, this.options, function (data) { - if (self.tick == myTick) self.finishUpdate(data, first); - }); - }, - finishUpdate: function (data, first) { - if (this.data) CodeMirror.signal(this.data, "update"); - var picked = this.widget && this.widget.picked || first && this.options.completeSingle; - if (this.widget) this.widget.close(); - this.data = data; - if (data && data.list.length) { - if (picked && data.list.length == 1) { - this.pick(data, 0); + }, + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + execCommand: function (cmd) { + if (commands.hasOwnProperty(cmd)) { + return commands[cmd].call(null, this); + } + }, + triggerElectric: methodOp(function (text) { + triggerElectric(this, text); + }), + findPosH: function (from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveH: methodOp(function (dir, unit) { + var this$1$1 = this; + this.extendSelectionsBy(function (range2) { + if (this$1$1.display.shift || this$1$1.doc.extend || range2.empty()) { + return findPosH(this$1$1.doc, range2.head, dir, unit, this$1$1.options.rtlMoveVisually); + } else { + return dir < 0 ? range2.from() : range2.to(); + } + }, sel_move); + }), + deleteH: methodOp(function (dir, unit) { + var sel = this.doc.sel, + doc = this.doc; + if (sel.somethingSelected()) { + doc.replaceSelection("", null, "+delete"); + } else { + deleteNearSelection(this, function (range2) { + var other = findPosH(doc, range2.head, dir, unit, false); + return dir < 0 ? { + from: other, + to: range2.head + } : { + from: range2.head, + to: other + }; + }); + } + }), + findPosV: function (from, amount, unit, goalColumn) { + var dir = 1, + x = goalColumn; + if (amount < 0) { + dir = -1; + amount = -amount; + } + var cur = clipPos(this.doc, from); + for (var i2 = 0; i2 < amount; ++i2) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) { + x = coords.left; + } else { + coords.left = x; + } + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) { + break; + } + } + return cur; + }, + moveV: methodOp(function (dir, unit) { + var this$1$1 = this; + var doc = this.doc, + goals = []; + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range2) { + if (collapse) { + return dir < 0 ? range2.from() : range2.to(); + } + var headPos = cursorCoords(this$1$1, range2.head, "div"); + if (range2.goalColumn != null) { + headPos.left = range2.goalColumn; + } + goals.push(headPos.left); + var pos = findPosV(this$1$1, headPos, dir, unit); + if (unit == "page" && range2 == doc.sel.primary()) { + addToScrollTop(this$1$1, charCoords(this$1$1, pos, "div").top - headPos.top); + } + return pos; + }, sel_move); + if (goals.length) { + for (var i2 = 0; i2 < doc.sel.ranges.length; i2++) { + doc.sel.ranges[i2].goalColumn = goals[i2]; + } + } + }), + // Find the word at the given position (as returned by coordsChar). + findWordAt: function (pos) { + var doc = this.doc, + line = getLine(doc, pos.line).text; + var start = pos.ch, + end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.sticky == "before" || end == line.length) && start) { + --start; + } else { + ++end; + } + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) ? function (ch) { + return isWordChar(ch, helper); + } : /\s/.test(startChar) ? function (ch) { + return /\s/.test(ch); + } : function (ch) { + return !/\s/.test(ch) && !isWordChar(ch); + }; + while (start > 0 && check(line.charAt(start - 1))) { + --start; + } + while (end < line.length && check(line.charAt(end))) { + ++end; + } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + toggleOverwrite: function (value) { + if (value != null && value == this.state.overwrite) { + return; + } + if (this.state.overwrite = !this.state.overwrite) { + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } else { - this.widget = new Widget(this, data); - CodeMirror.signal(data, "shown"); + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } - } - } - }; - function parseOptions(cm, pos, options) { - var editor = cm.options.hintOptions; - var out = {}; - for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) { - for (var prop in editor) if (editor[prop] !== void 0) out[prop] = editor[prop]; - } - if (options) { - for (var prop in options) if (options[prop] !== void 0) out[prop] = options[prop]; - } - if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); - return out; - } - function getText(completion) { - if (typeof completion == "string") return completion;else return completion.text; - } - function buildKeyMap(completion, handle) { - var baseMap = { - Up: function () { - handle.moveFocus(-1); + signal(this, "overwriteToggle", this, this.state.overwrite); }, - Down: function () { - handle.moveFocus(1); + hasFocus: function () { + return this.display.input.getField() == activeElt(); }, - PageUp: function () { - handle.moveFocus(-handle.menuSize() + 1, true); + isReadOnly: function () { + return !!(this.options.readOnly || this.doc.cantEdit); }, - PageDown: function () { - handle.moveFocus(handle.menuSize() - 1, true); + scrollTo: methodOp(function (x, y) { + scrollToCoords(this, x, y); + }), + getScrollInfo: function () { + var scroller = this.display.scroller; + return { + left: scroller.scrollLeft, + top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), + clientWidth: displayWidth(this) + }; }, - Home: function () { - handle.setFocus(0); + scrollIntoView: methodOp(function (range2, margin) { + if (range2 == null) { + range2 = { + from: this.doc.sel.primary().head, + to: null + }; + if (margin == null) { + margin = this.options.cursorScrollMargin; + } + } else if (typeof range2 == "number") { + range2 = { + from: Pos(range2, 0), + to: null + }; + } else if (range2.from == null) { + range2 = { + from: range2, + to: null + }; + } + if (!range2.to) { + range2.to = range2.from; + } + range2.margin = margin || 0; + if (range2.from.line != null) { + scrollToRange(this, range2); + } else { + scrollToCoordsRange(this, range2.from, range2.to, range2.margin); + } + }), + setSize: methodOp(function (width, height) { + var this$1$1 = this; + var interpret = function (val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + }; + if (width != null) { + this.display.wrapper.style.width = interpret(width); + } + if (height != null) { + this.display.wrapper.style.height = interpret(height); + } + if (this.options.lineWrapping) { + clearLineMeasurementCache(this); + } + var lineNo2 = this.display.viewFrom; + this.doc.iter(lineNo2, this.display.viewTo, function (line) { + if (line.widgets) { + for (var i2 = 0; i2 < line.widgets.length; i2++) { + if (line.widgets[i2].noHScroll) { + regLineChange(this$1$1, lineNo2, "widget"); + break; + } + } + } + ++lineNo2; + }); + this.curOp.forceUpdate = true; + signal(this, "refresh", this); + }), + operation: function (f) { + return runInOp(this, f); }, - End: function () { - handle.setFocus(handle.length - 1); + startOperation: function () { + return startOperation(this); }, - Enter: handle.pick, - Tab: handle.pick, - Esc: handle.close - }; - var mac = /Mac/.test(navigator.platform); - if (mac) { - baseMap["Ctrl-P"] = function () { - handle.moveFocus(-1); - }; - baseMap["Ctrl-N"] = function () { - handle.moveFocus(1); - }; - } - var custom = completion.options.customKeys; - var ourMap = custom ? {} : baseMap; - function addBinding(key2, val) { - var bound; - if (typeof val != "string") bound = function (cm) { - return val(cm, handle); - };else if (baseMap.hasOwnProperty(val)) bound = baseMap[val];else bound = val; - ourMap[key2] = bound; - } - if (custom) { - for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); - } - var extra = completion.options.extraKeys; - if (extra) { - for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); - } - return ourMap; - } - function getHintElement(hintsElement, el) { - while (el && el != hintsElement) { - if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; - el = el.parentNode; - } - } - function Widget(completion, data) { - this.id = "cm-complete-" + Math.floor(Math.random(1e6)); - this.completion = completion; - this.data = data; - this.picked = false; - var widget = this, - cm = completion.cm; - var ownerDocument = cm.getInputField().ownerDocument; - var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow; - var hints = this.hints = ownerDocument.createElement("ul"); - hints.setAttribute("role", "listbox"); - hints.setAttribute("aria-expanded", "true"); - hints.id = this.id; - var theme = completion.cm.options.theme; - hints.className = "CodeMirror-hints " + theme; - this.selectedHint = data.selectedHint || 0; - var completions = data.list; - for (var i = 0; i < completions.length; ++i) { - var elt = hints.appendChild(ownerDocument.createElement("li")), - cur = completions[i]; - var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); - if (cur.className != null) className = cur.className + " " + className; - elt.className = className; - if (i == this.selectedHint) elt.setAttribute("aria-selected", "true"); - elt.id = this.id + "-" + i; - elt.setAttribute("role", "option"); - if (cur.render) cur.render(elt, data, cur);else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur))); - elt.hintId = i; - } - var container = completion.options.container || ownerDocument.body; - var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); - var left = pos.left, - top = pos.bottom, - below = true; - var offsetLeft = 0, - offsetTop = 0; - if (container !== ownerDocument.body) { - var isContainerPositioned = ["absolute", "relative", "fixed"].indexOf(parentWindow.getComputedStyle(container).position) !== -1; - var offsetParent = isContainerPositioned ? container : container.offsetParent; - var offsetParentPosition = offsetParent.getBoundingClientRect(); - var bodyPosition = ownerDocument.body.getBoundingClientRect(); - offsetLeft = offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft; - offsetTop = offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop; - } - hints.style.left = left - offsetLeft + "px"; - hints.style.top = top - offsetTop + "px"; - var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth); - var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight); - container.appendChild(hints); - cm.getInputField().setAttribute("aria-autocomplete", "list"); - cm.getInputField().setAttribute("aria-owns", this.id); - cm.getInputField().setAttribute("aria-activedescendant", this.id + "-" + this.selectedHint); - var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect(); - var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false; - var startScroll; - setTimeout(function () { - startScroll = cm.getScrollInfo(); - }); - var overlapY = box.bottom - winH; - if (overlapY > 0) { - var height = box.bottom - box.top, - curTop = pos.top - (pos.bottom - box.top); - if (curTop - height > 0) { - hints.style.top = (top = pos.top - height - offsetTop) + "px"; - below = false; - } else if (height > winH) { - hints.style.height = winH - 5 + "px"; - hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px"; - var cursor = cm.getCursor(); - if (data.from.ch != cursor.ch) { - pos = cm.cursorCoords(cursor); - hints.style.left = (left = pos.left - offsetLeft) + "px"; - box = hints.getBoundingClientRect(); - } - } - } - var overlapX = box.right - winW; - if (scrolls) overlapX += cm.display.nativeBarWidth; - if (overlapX > 0) { - if (box.right - box.left > winW) { - hints.style.width = winW - 5 + "px"; - overlapX -= box.right - box.left - winW; - } - hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px"; - } - if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling) node.style.paddingRight = cm.display.nativeBarWidth + "px"; - cm.addKeyMap(this.keyMap = buildKeyMap(completion, { - moveFocus: function (n, avoidWrap) { - widget.changeActive(widget.selectedHint + n, avoidWrap); + endOperation: function () { + return endOperation(this); }, - setFocus: function (n) { - widget.changeActive(n); + refresh: methodOp(function () { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this.display); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > 0.5 || this.options.lineWrapping) { + estimateLineHeights(this); + } + signal(this, "refresh", this); + }), + swapDoc: methodOp(function (doc) { + var old = this.doc; + old.cm = null; + if (this.state.selectingText) { + this.state.selectingText(); + } + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + scrollToCoords(this, doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + phrase: function (phraseText) { + var phrases = this.options.phrases; + return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText; }, - menuSize: function () { - return widget.screenAmount(); + getInputField: function () { + return this.display.input.getField(); }, - length: completions.length, - close: function () { - completion.close(); + getWrapperElement: function () { + return this.display.wrapper; }, - pick: function () { - widget.pick(); + getScrollerElement: function () { + return this.display.scroller; }, - data - })); - if (completion.options.closeOnUnfocus) { - var closingOnBlur; - cm.on("blur", this.onBlur = function () { - closingOnBlur = setTimeout(function () { - completion.close(); - }, 100); - }); - cm.on("focus", this.onFocus = function () { - clearTimeout(closingOnBlur); - }); - } - cm.on("scroll", this.onScroll = function () { - var curScroll = cm.getScrollInfo(), - editor = cm.getWrapperElement().getBoundingClientRect(); - if (!startScroll) startScroll = cm.getScrollInfo(); - var newTop = top + startScroll.top - curScroll.top; - var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop); - if (!below) point += hints.offsetHeight; - if (point <= editor.top || point >= editor.bottom) return completion.close(); - hints.style.top = newTop + "px"; - hints.style.left = left + startScroll.left - curScroll.left + "px"; - }); - CodeMirror.on(hints, "dblclick", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - widget.pick(); + getGutterElement: function () { + return this.display.gutters; } - }); - CodeMirror.on(hints, "click", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - if (completion.options.completeOnSingleClick) widget.pick(); + }; + eventMixin(CodeMirror2); + CodeMirror2.registerHelper = function (type, name, value) { + if (!helpers.hasOwnProperty(type)) { + helpers[type] = CodeMirror2[type] = { + _global: [] + }; } - }); - CodeMirror.on(hints, "mousedown", function () { - setTimeout(function () { - cm.focus(); - }, 20); - }); - var selectedHintRange = this.getSelectedHintRange(); - if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { - this.scrollToActive(); - } - CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]); - return true; + helpers[type][name] = value; + }; + CodeMirror2.registerGlobalHelper = function (type, name, predicate, value) { + CodeMirror2.registerHelper(type, name, value); + helpers[type]._global.push({ + pred: predicate, + val: value + }); + }; } - Widget.prototype = { - close: function () { - if (this.completion.widget != this) return; - this.completion.widget = null; - if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints); - this.completion.cm.removeKeyMap(this.keyMap); - var input = this.completion.cm.getInputField(); - input.removeAttribute("aria-activedescendant"); - input.removeAttribute("aria-owns"); - var cm = this.completion.cm; - if (this.completion.options.closeOnUnfocus) { - cm.off("blur", this.onBlur); - cm.off("focus", this.onFocus); - } - cm.off("scroll", this.onScroll); - }, - disable: function () { - this.completion.cm.removeKeyMap(this.keyMap); - var widget = this; - this.keyMap = { - Enter: function () { - widget.picked = true; - } - }; - this.completion.cm.addKeyMap(this.keyMap); - }, - pick: function () { - this.completion.pick(this.data, this.selectedHint); - }, - changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0;else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; - if (this.selectedHint == i) return; - var node = this.hints.childNodes[this.selectedHint]; - if (node) { - node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); - node.removeAttribute("aria-selected"); - } - node = this.hints.childNodes[this.selectedHint = i]; - node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - node.setAttribute("aria-selected", "true"); - this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id); - this.scrollToActive(); - CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); - }, - scrollToActive: function () { - var selectedHintRange = this.getSelectedHintRange(); - var node1 = this.hints.childNodes[selectedHintRange.from]; - var node2 = this.hints.childNodes[selectedHintRange.to]; - var firstNode = this.hints.firstChild; - if (node1.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop; - }, - screenAmount: function () { - return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; - }, - getSelectedHintRange: function () { - var margin = this.completion.options.scrollMargin || 0; - return { - from: Math.max(0, this.selectedHint - margin), - to: Math.min(this.data.list.length - 1, this.selectedHint + margin) - }; + function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos; + var origDir = dir; + var lineObj = getLine(doc, pos.line); + var lineDir = visually && doc.direction == "rtl" ? -dir : dir; + function findNextLine() { + var l = pos.line + lineDir; + if (l < doc.first || l >= doc.first + doc.size) { + return false; + } + pos = new Pos(l, pos.ch, pos.sticky); + return lineObj = getLine(doc, l); } - }; - function applicableHelpers(cm, helpers) { - if (!cm.somethingSelected()) return helpers; - var result = []; - for (var i = 0; i < helpers.length; i++) if (helpers[i].supportsSelection) result.push(helpers[i]); - return result; - } - function fetchHints(hint, cm, options, callback) { - if (hint.async) { - hint(cm, callback, options); - } else { - var result = hint(cm, options); - if (result && result.then) result.then(callback);else callback(result); - } - } - function resolveAutoHints(cm, pos) { - var helpers = cm.getHelpers(pos, "hint"), - words; - if (helpers.length) { - var resolved = function (cm2, callback, options) { - var app = applicableHelpers(cm2, helpers); - function run(i) { - if (i == app.length) return callback(null); - fetchHints(app[i], cm2, options, function (result) { - if (result && result.list.length > 0) callback(result);else run(i + 1); - }); + function moveOnce(boundToLine) { + var next; + if (unit == "codepoint") { + var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); + if (isNaN(ch)) { + next = null; + } else { + var astral = dir > 0 ? ch >= 55296 && ch < 56320 : ch >= 56320 && ch < 57343; + next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); } - run(0); - }; - resolved.async = true; - resolved.supportsSelection = true; - return resolved; - } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { - return function (cm2) { - return CodeMirror.hint.fromList(cm2, { - words - }); - }; - } else if (CodeMirror.hint.anyword) { - return function (cm2, options) { - return CodeMirror.hint.anyword(cm2, options); - }; - } else { - return function () {}; - } - } - CodeMirror.registerHelper("hint", "auto", { - resolve: resolveAutoHints - }); - CodeMirror.registerHelper("hint", "fromList", function (cm, options) { - var cur = cm.getCursor(), - token = cm.getTokenAt(cur); - var term, - from = CodeMirror.Pos(cur.line, token.start), - to = cur; - if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) { - term = token.string.substr(0, cur.ch - token.start); - } else { - term = ""; - from = cur; - } - var found = []; - for (var i = 0; i < options.words.length; i++) { - var word = options.words[i]; - if (word.slice(0, term.length) == term) found.push(word); - } - if (found.length) return { - list: found, - from, - to - }; - }); - CodeMirror.commands.autocomplete = CodeMirror.showHint; - var defaultOptions = { - hint: CodeMirror.hint.auto, - completeSingle: true, - alignWithWord: true, - closeCharacters: /[\s()\[\]{};:>,]/, - closeOnPick: true, - closeOnUnfocus: true, - updateOnCursorActivity: true, - completeOnSingleClick: true, - container: null, - customKeys: null, - extraKeys: null, - paddingForScrollbar: true, - moveOnOverlap: true - }; - CodeMirror.defineOption("hintOptions", null); - }); - })(); - var showHintExports = showHint$2.exports; - const showHint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(showHintExports); - const showHint$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: showHint - }, [showHintExports]); - exports.showHint = showHint$1; - - /***/ }), - - /***/ "../../graphiql-react/dist/sublime.cjs.js": - /*!************************************************!*\ - !*** ../../graphiql-react/dist/sublime.cjs.js ***! - \************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); - const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); - const matchbrackets = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); - function _mergeNamespaces(n, m) { - for (var i = 0; i < m.length; i++) { - const e = m[i]; - if (typeof e !== "string" && !Array.isArray(e)) { - for (const k in e) { - if (k !== "default" && !(k in n)) { - const d = Object.getOwnPropertyDescriptor(e, k); - if (d) { - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + } else if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir); + } else { + next = moveLogically(lineObj, pos, dir); + } + if (next == null) { + if (!boundToLine && findNextLine()) { + pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); + } else { + return false; } + } else { + pos = next; } + return true; } - } - } - return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { - value: "Module" - })); - } - var sublime$2 = { - exports: {} - }; - (function (module2, exports2) { - (function (mod) { - mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), matchbrackets.requireMatchbrackets()); - })(function (CodeMirror) { - var cmds = CodeMirror.commands; - var Pos = CodeMirror.Pos; - function findPosSubword(doc, start, dir) { - if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); - var line = doc.getLine(start.line); - if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); - var state = "start", - type, - startPos = start.ch; - for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { - var next = line.charAt(dir < 0 ? pos - 1 : pos); - var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; - if (cat == "w" && next.toUpperCase() == next) cat = "W"; - if (state == "start") { - if (cat != "o") { - state = "in"; - type = cat; - } else startPos = pos + dir; - } else if (state == "in") { - if (type != cat) { - if (type == "w" && cat == "W" && dir < 0) pos--; - if (type == "W" && cat == "w" && dir > 0) { - if (pos == startPos + 1) { - type = "w"; - continue; - } else pos--; + if (unit == "char" || unit == "codepoint") { + moveOnce(); + } else if (unit == "column") { + moveOnce(true); + } else if (unit == "word" || unit == "group") { + var sawType = null, + group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { + break; + } + var cur = lineObj.text.charAt(pos.ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; + if (group && !first && !type) { + type = "s"; + } + if (sawType && sawType != type) { + if (dir < 0) { + dir = 1; + moveOnce(); + pos.sticky = "after"; } break; } + if (type) { + sawType = type; + } + if (dir > 0 && !moveOnce(!first)) { + break; + } } } - return Pos(start.line, pos); - } - function moveSubword(cm, dir) { - cm.extendSelectionsBy(function (range) { - if (cm.display.shift || cm.doc.extend || range.empty()) return findPosSubword(cm.doc, range.head, dir);else return dir < 0 ? range.from() : range.to(); - }); - } - cmds.goSubwordLeft = function (cm) { - moveSubword(cm, -1); - }; - cmds.goSubwordRight = function (cm) { - moveSubword(cm, 1); - }; - cmds.scrollLineUp = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); - if (cm.getCursor().line >= visibleBottomLine) cm.execCommand("goLineUp"); - } - cm.scrollTo(null, info.top - cm.defaultTextHeight()); - }; - cmds.scrollLineDown = function (cm) { - var info = cm.getScrollInfo(); - if (!cm.somethingSelected()) { - var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; - if (cm.getCursor().line <= visibleTopLine) cm.execCommand("goLineDown"); - } - cm.scrollTo(null, info.top + cm.defaultTextHeight()); - }; - cmds.splitSelectionByLine = function (cm) { - var ranges = cm.listSelections(), - lineRanges = []; - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - for (var line = from.line; line <= to.line; ++line) if (!(to.line > from.line && line == to.line && to.ch == 0)) lineRanges.push({ - anchor: line == from.line ? from : Pos(line, 0), - head: line == to.line ? to : Pos(line) - }); - } - cm.setSelections(lineRanges, 0); - }; - cmds.singleSelectionTop = function (cm) { - var range = cm.listSelections()[0]; - cm.setSelection(range.anchor, range.head, { - scroll: false - }); - }; - cmds.selectLine = function (cm) { - var ranges = cm.listSelections(), - extended = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - extended.push({ - anchor: Pos(range.from().line, 0), - head: Pos(range.to().line + 1, 0) - }); + var result = skipAtomic(doc, pos, oldPos, origDir, true); + if (equalCursorPos(oldPos, result)) { + result.hitSide = true; } - cm.setSelections(extended); - }; - function insertLine(cm, above) { - if (cm.isReadOnly()) return CodeMirror.Pass; - cm.operation(function () { - var len = cm.listSelections().length, - newSelection = [], - last = -1; - for (var i = 0; i < len; i++) { - var head = cm.listSelections()[i].head; - if (head.line <= last) continue; - var at = Pos(head.line + (above ? 0 : 1), 0); - cm.replaceRange("\n", at, null, "+insertLine"); - cm.indentLine(at.line, null, true); - newSelection.push({ - head: at, - anchor: at - }); - last = head.line + 1; - } - cm.setSelections(newSelection); - }); - cm.execCommand("indentAuto"); - } - cmds.insertLineAfter = function (cm) { - return insertLine(cm, false); - }; - cmds.insertLineBefore = function (cm) { - return insertLine(cm, true); - }; - function wordAt(cm, pos) { - var start = pos.ch, - end = start, - line = cm.getLine(pos.line); - while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; - while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; - return { - from: Pos(pos.line, start), - to: Pos(pos.line, end), - word: line.slice(start, end) - }; + return result; } - cmds.selectNextOccurrence = function (cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - cm.setSelection(word.from, word.to); - fullWord = true; - } else { - var text = cm.getRange(from, to); - var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; - var cur = cm.getSearchCursor(query, to); - var found = cur.findNext(); - if (!found) { - cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); - found = cur.findNext(); - } - if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return; - cm.addSelection(cur.from(), cur.to()); - } - if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; - }; - cmds.skipAndSelectNextOccurrence = function (cm) { - var prevAnchor = cm.getCursor("anchor"), - prevHead = cm.getCursor("head"); - cmds.selectNextOccurrence(cm); - if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { - cm.doc.setSelections(cm.doc.listSelections().filter(function (sel) { - return sel.anchor != prevAnchor || sel.head != prevHead; - })); - } - }; - function addCursorToSelection(cm, dir) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var newAnchor = cm.findPosV(range.anchor, dir, "line", range.anchor.goalColumn); - var newHead = cm.findPosV(range.head, dir, "line", range.head.goalColumn); - newAnchor.goalColumn = range.anchor.goalColumn != null ? range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left; - newHead.goalColumn = range.head.goalColumn != null ? range.head.goalColumn : cm.cursorCoords(range.head, "div").left; - var newRange = { - anchor: newAnchor, - head: newHead - }; - newRanges.push(range); - newRanges.push(newRange); + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, + x = pos.left, + y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + var moveAmount = Math.max(pageSize - 0.5 * textHeight(cm.display), 3); + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + var target; + for (;;) { + target = coordsChar(cm, x, y); + if (!target.outside) { + break; + } + if (dir < 0 ? y <= 0 : y >= doc.height) { + target.hitSide = true; + break; + } + y += dir * 5; } - cm.setSelections(newRanges); + return target; } - cmds.addCursorToPrevLine = function (cm) { - addCursorToSelection(cm, -1); - }; - cmds.addCursorToNextLine = function (cm) { - addCursorToSelection(cm, 1); + var ContentEditableInput = function (cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.composing = null; + this.gracePeriod = false; + this.readDOMTimeout = null; }; - function isSelectedRange(ranges, from, to) { - for (var i = 0; i < ranges.length; i++) if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 && CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true; - return false; - } - var mirror = "(){}[]"; - function selectBetweenBrackets(cm) { - var ranges = cm.listSelections(), - newRanges = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - pos = range.head, - opening = cm.scanForBracket(pos, -1); - if (!opening) return false; - for (;;) { - var closing = cm.scanForBracket(pos, 1); - if (!closing) return false; - if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { - var startPos = Pos(opening.pos.line, opening.pos.ch + 1); - if (CodeMirror.cmpPos(startPos, range.from()) == 0 && CodeMirror.cmpPos(closing.pos, range.to()) == 0) { - opening = cm.scanForBracket(opening.pos, -1); - if (!opening) return false; - } else { - newRanges.push({ - anchor: startPos, - head: closing.pos - }); - break; - } + ContentEditableInput.prototype.init = function (display) { + var this$1$1 = this; + var input = this, + cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = true; + disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); + function belongsToInput(e) { + for (var t = e.target; t; t = t.parentNode) { + if (t == div) { + return true; + } + if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { + break; } - pos = Pos(closing.pos.line, closing.pos.ch + 1); } + return false; } - cm.setSelections(newRanges); - return true; - } - cmds.selectScope = function (cm) { - selectBetweenBrackets(cm) || cm.execCommand("selectAll"); - }; - cmds.selectBetweenBrackets = function (cm) { - if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; - }; - function puncType(type) { - return !type ? null : /\bpunctuation\b/.test(type) ? type : void 0; - } - cmds.goToBracket = function (cm) { - cm.extendSelectionsBy(function (range) { - var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head))); - if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; - var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)))); - return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; - }); - }; - cmds.swapLineUp = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.firstLine() - 1, - newSels = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from().line - 1, - to = range.to().line; - newSels.push({ - anchor: Pos(range.anchor.line - 1, range.anchor.ch), - head: Pos(range.head.line - 1, range.head.ch) - }); - if (range.to().ch == 0 && !range.empty()) --to; - if (from > at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i2 = 0; i2 < linesToMove.length; i2 += 2) { - var from2 = linesToMove[i2], - to2 = linesToMove[i2 + 1]; - var line = cm.getLine(from2); - cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); - if (to2 > cm.lastLine()) cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");else cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); - } - cm.setSelections(newSels); - cm.scrollIntoView(); + on(div, "paste", function (e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; + } + if (ie_version <= 11) { + setTimeout(operation(cm, function () { + return this$1$1.updateFromDOM(); + }), 20); + } }); - }; - cmds.swapLineDown = function (cm) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - linesToMove = [], - at = cm.lastLine() + 1; - for (var i = ranges.length - 1; i >= 0; i--) { - var range = ranges[i], - from = range.to().line + 1, - to = range.from().line; - if (range.to().ch == 0 && !range.empty()) from--; - if (from < at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; - at = to; - } - cm.operation(function () { - for (var i2 = linesToMove.length - 2; i2 >= 0; i2 -= 2) { - var from2 = linesToMove[i2], - to2 = linesToMove[i2 + 1]; - var line = cm.getLine(from2); - if (from2 == cm.lastLine()) cm.replaceRange("", Pos(from2 - 1), Pos(from2), "+swapLine");else cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); - cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); - } - cm.scrollIntoView(); + on(div, "compositionstart", function (e) { + this$1$1.composing = { + data: e.data, + done: false + }; }); - }; - cmds.toggleCommentIndented = function (cm) { - cm.toggleComment({ - indent: true + on(div, "compositionupdate", function (e) { + if (!this$1$1.composing) { + this$1$1.composing = { + data: e.data, + done: false + }; + } }); - }; - cmds.joinLines = function (cm) { - var ranges = cm.listSelections(), - joined = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], - from = range.from(); - var start = from.line, - end = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == end) end = ranges[++i].to().line; - joined.push({ - start, - end, - anchor: !range.empty() && from - }); - } - cm.operation(function () { - var offset = 0, - ranges2 = []; - for (var i2 = 0; i2 < joined.length; i2++) { - var obj = joined[i2]; - var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), - head; - for (var line = obj.start; line <= obj.end; line++) { - var actual = line - offset; - if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); - if (actual < cm.lastLine()) { - cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); - ++offset; - } + on(div, "compositionend", function (e) { + if (this$1$1.composing) { + if (e.data != this$1$1.composing.data) { + this$1$1.readFromDOMSoon(); } - ranges2.push({ - anchor: anchor || head, - head - }); + this$1$1.composing.done = true; } - cm.setSelections(ranges2, 0); }); - }; - cmds.duplicateLine = function (cm) { - cm.operation(function () { - var rangeCount = cm.listSelections().length; - for (var i = 0; i < rangeCount; i++) { - var range = cm.listSelections()[i]; - if (range.empty()) cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));else cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + on(div, "touchstart", function () { + return input.forceCompositionEnd(); + }); + on(div, "input", function () { + if (!this$1$1.composing) { + this$1$1.readFromDOMSoon(); + } + }); + function onCopyCut(e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e)) { + return; } - cm.scrollIntoView(); - }); - }; - function sortLines(cm, caseSensitive, direction) { - if (cm.isReadOnly()) return CodeMirror.Pass; - var ranges = cm.listSelections(), - toSort = [], - selected; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) continue; - var from = range.from().line, - to = range.to().line; - while (i < ranges.length - 1 && ranges[i + 1].from().line == to) to = ranges[++i].to().line; - if (!ranges[i].to().ch) to--; - toSort.push(from, to); - } - if (toSort.length) selected = true;else toSort.push(cm.firstLine(), cm.lastLine()); - cm.operation(function () { - var ranges2 = []; - for (var i2 = 0; i2 < toSort.length; i2 += 2) { - var from2 = toSort[i2], - to2 = toSort[i2 + 1]; - var start = Pos(from2, 0), - end = Pos(to2); - var lines = cm.getRange(start, end, false); - if (caseSensitive) lines.sort(function (a, b) { - return a < b ? -direction : a == b ? 0 : direction; - });else lines.sort(function (a, b) { - var au = a.toUpperCase(), - bu = b.toUpperCase(); - if (au != bu) { - a = au; - b = bu; - } - return a < b ? -direction : a == b ? 0 : direction; + if (cm.somethingSelected()) { + setLastCopied({ + lineWise: false, + text: cm.getSelections() }); - cm.replaceRange(lines, start, end); - if (selected) ranges2.push({ - anchor: start, - head: Pos(to2 + 1, 0) + if (e.type == "cut") { + cm.replaceSelection("", null, "cut"); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ + lineWise: true, + text: ranges.text }); + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } } - if (selected) cm.setSelections(ranges2, 0); - }); - } - cmds.sortLines = function (cm) { - sortLines(cm, true, 1); - }; - cmds.reverseSortLines = function (cm) { - sortLines(cm, true, -1); - }; - cmds.sortLinesInsensitive = function (cm) { - sortLines(cm, false, 1); - }; - cmds.reverseSortLinesInsensitive = function (cm) { - sortLines(cm, false, -1); - }; - cmds.nextBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) while (marks.length) { - var current = marks.shift(); - var found = current.find(); - if (found) { - marks.push(current); - return cm.setSelection(found.from, found.to); + if (e.clipboardData) { + e.clipboardData.clearData(); + var content = lastCopied.text.join("\n"); + e.clipboardData.setData("Text", content); + if (e.clipboardData.getData("Text") == content) { + e.preventDefault(); + return; + } } + var kludge = hiddenTextarea(), + te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.text.join("\n"); + var hadFocus = activeElt(); + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + if (hadFocus == div) { + input.showPrimarySelection(); + } + }, 50); } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); }; - cmds.prevBookmark = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) while (marks.length) { - marks.unshift(marks.pop()); - var found = marks[marks.length - 1].find(); - if (!found) marks.pop();else return cm.setSelection(found.from, found.to); + ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { + if (label) { + this.div.setAttribute("aria-label", label); + } else { + this.div.removeAttribute("aria-label"); } }; - cmds.toggleBookmark = function (cm) { - var ranges = cm.listSelections(); - var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); - for (var i = 0; i < ranges.length; i++) { - var from = ranges[i].from(), - to = ranges[i].to(); - var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to); - for (var j = 0; j < found.length; j++) { - if (found[j].sublimeBookmark) { - found[j].clear(); - for (var k = 0; k < marks.length; k++) if (marks[k] == found[j]) marks.splice(k--, 1); - break; - } - } - if (j == found.length) marks.push(cm.markText(from, to, { - sublimeBookmark: true, - clearWhenEmpty: false - })); + ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false); + result.focus = activeElt() == this.div; + return result; + }; + ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { + return; + } + if (info.focus || takeFocus) { + this.showPrimarySelection(); } + this.showMultipleSelections(info); }; - cmds.clearBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks; - if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); - marks.length = 0; + ContentEditableInput.prototype.getSelection = function () { + return this.cm.display.wrapper.ownerDocument.getSelection(); }; - cmds.selectBookmarks = function (cm) { - var marks = cm.state.sublimeBookmarks, - ranges = []; - if (marks) for (var i = 0; i < marks.length; i++) { - var found = marks[i].find(); - if (!found) marks.splice(i--, 0);else ranges.push({ - anchor: found.from, - head: found.to - }); + ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = this.getSelection(), + cm = this.cm, + prim = cm.doc.sel.primary(); + var from = prim.from(), + to = prim.to(); + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges(); + return; } - if (ranges.length) cm.setSelections(ranges, 0); - }; - function modifyWordOrSelection(cm, mod) { - cm.operation(function () { - var ranges = cm.listSelections(), - indices = [], - replacements = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (range.empty()) { - indices.push(i); - replacements.push(""); - } else replacements.push(mod(cm.getRange(range.from(), range.to()))); - } - cm.replaceSelections(replacements, "around", "case"); - for (var i = indices.length - 1, at; i >= 0; i--) { - var range = ranges[indices[i]]; - if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; - var word = wordAt(cm, range.head); - at = word.from; - cm.replaceRange(mod(word.word), word.from, word.to); - } - }); - } - cmds.smartBackspace = function (cm) { - if (cm.somethingSelected()) return CodeMirror.Pass; - cm.operation(function () { - var cursors = cm.listSelections(); - var indentUnit = cm.getOption("indentUnit"); - for (var i = cursors.length - 1; i >= 0; i--) { - var cursor = cursors[i].head; - var toStartOfLine = cm.getRange({ - line: cursor.line, - ch: 0 - }, cursor); - var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); - var deletePos = cm.findPosH(cursor, -1, "char", false); - if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { - var prevIndent = new Pos(cursor.line, CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); - if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { + return; + } + var view = cm.display.view; + var start = from.line >= cm.display.viewFrom && posToDOM(cm, from) || { + node: view[0].measure.map[2], + offset: 0 + }; + var end = to.line < cm.display.viewTo && posToDOM(cm, to); + if (!end) { + var measure = view[view.length - 1].measure; + var map2 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = { + node: map2[map2.length - 1], + offset: map2[map2.length - 2] - map2[map2.length - 3] + }; + } + if (!start || !end) { + sel.removeAllRanges(); + return; + } + var old = sel.rangeCount && sel.getRangeAt(0), + rng; + try { + rng = range(start.node, start.offset, end.offset, end.node); + } catch (e) {} + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) { + sel.removeAllRanges(); + sel.addRange(rng); } - cm.replaceRange("", deletePos, cursor, "+delete"); + } else { + sel.removeAllRanges(); + sel.addRange(rng); } - }); - }; - cmds.delLineRight = function (cm) { - cm.operation(function () { - var ranges = cm.listSelections(); - for (var i = ranges.length - 1; i >= 0; i--) cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); - cm.scrollIntoView(); - }); + if (old && sel.anchorNode == null) { + sel.addRange(old); + } else if (gecko) { + this.startGracePeriod(); + } + } + this.rememberSelection(); }; - cmds.upcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toUpperCase(); - }); + ContentEditableInput.prototype.startGracePeriod = function () { + var this$1$1 = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + this$1$1.gracePeriod = false; + if (this$1$1.selectionChanged()) { + this$1$1.cm.operation(function () { + return this$1$1.cm.curOp.selectionChanged = true; + }); + } + }, 20); }; - cmds.downcaseAtCursor = function (cm) { - modifyWordOrSelection(cm, function (str) { - return str.toLowerCase(); - }); + ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); }; - cmds.setSublimeMark = function (cm) { - if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + ContentEditableInput.prototype.rememberSelection = function () { + var sel = this.getSelection(); + this.lastAnchorNode = sel.anchorNode; + this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; + this.lastFocusOffset = sel.focusOffset; }; - cmds.selectToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) cm.setSelection(cm.getCursor(), found); + ContentEditableInput.prototype.selectionInEditor = function () { + var sel = this.getSelection(); + if (!sel.rangeCount) { + return false; + } + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); }; - cmds.deleteToSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - var from = cm.getCursor(), - to = found; - if (CodeMirror.cmpPos(from, to) > 0) { - var tmp = to; - to = from; - from = tmp; + ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor() || activeElt() != this.div) { + this.showSelection(this.prepareSelection(), true); } - cm.state.sublimeKilled = cm.getRange(from, to); - cm.replaceRange("", from, to); + this.div.focus(); } }; - cmds.swapWithSublimeMark = function (cm) { - var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); - if (found) { - cm.state.sublimeMark.clear(); - cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); - cm.setCursor(found); - } + ContentEditableInput.prototype.blur = function () { + this.div.blur(); }; - cmds.sublimeYank = function (cm) { - if (cm.state.sublimeKilled != null) cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + ContentEditableInput.prototype.getField = function () { + return this.div; }; - cmds.showInCenter = function (cm) { - var pos = cm.cursorCoords(null, "local"); - cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + ContentEditableInput.prototype.supportsTouch = function () { + return true; }; - function getTarget(cm) { - var from = cm.getCursor("from"), - to = cm.getCursor("to"); - if (CodeMirror.cmpPos(from, to) == 0) { - var word = wordAt(cm, from); - if (!word.word) return; - from = word.from; - to = word.to; - } - return { - from, - to, - query: cm.getRange(from, to), - word - }; - } - function findAndGoTo(cm, forward) { - var target = getTarget(cm); - if (!target) return; - var query = target.query; - var cur = cm.getSearchCursor(query, forward ? target.to : target.from); - if (forward ? cur.findNext() : cur.findPrevious()) { - cm.setSelection(cur.from(), cur.to()); + ContentEditableInput.prototype.receivedFocus = function () { + var this$1$1 = this; + var input = this; + if (this.selectionInEditor()) { + setTimeout(function () { + return this$1$1.pollSelection(); + }, 20); } else { - cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) : cm.clipPos(Pos(cm.lastLine()))); - if (forward ? cur.findNext() : cur.findPrevious()) cm.setSelection(cur.from(), cur.to());else if (target.word) cm.setSelection(target.from, target.to); + runInOp(this.cm, function () { + return input.cm.curOp.selectionChanged = true; + }); } - } - cmds.findUnder = function (cm) { - findAndGoTo(cm, true); + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); }; - cmds.findUnderPrevious = function (cm) { - findAndGoTo(cm, false); + ContentEditableInput.prototype.selectionChanged = function () { + var sel = this.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; }; - cmds.findAllUnder = function (cm) { - var target = getTarget(cm); - if (!target) return; - var cur = cm.getSearchCursor(target.query); - var matches = []; - var primaryIndex = -1; - while (cur.findNext()) { - matches.push({ - anchor: cur.from(), - head: cur.to() + ContentEditableInput.prototype.pollSelection = function () { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { + return; + } + var sel = this.getSelection(), + cm = this.cm; + if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({ + type: "keydown", + keyCode: 8, + preventDefault: Math.abs + }); + this.blur(); + this.focus(); + return; + } + if (this.composing) { + return; + } + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) { + cm.curOp.selectionChanged = true; + } }); - if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) primaryIndex++; } - cm.setSelections(matches, primaryIndex); - }; - var keyMap = CodeMirror.keyMap; - keyMap.macSublime = { - "Cmd-Left": "goLineStartSmart", - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-Left": "goSubwordLeft", - "Ctrl-Right": "goSubwordRight", - "Ctrl-Alt-Up": "scrollLineUp", - "Ctrl-Alt-Down": "scrollLineDown", - "Cmd-L": "selectLine", - "Shift-Cmd-L": "splitSelectionByLine", - "Esc": "singleSelectionTop", - "Cmd-Enter": "insertLineAfter", - "Shift-Cmd-Enter": "insertLineBefore", - "Cmd-D": "selectNextOccurrence", - "Shift-Cmd-Space": "selectScope", - "Shift-Cmd-M": "selectBetweenBrackets", - "Cmd-M": "goToBracket", - "Cmd-Ctrl-Up": "swapLineUp", - "Cmd-Ctrl-Down": "swapLineDown", - "Cmd-/": "toggleCommentIndented", - "Cmd-J": "joinLines", - "Shift-Cmd-D": "duplicateLine", - "F5": "sortLines", - "Shift-F5": "reverseSortLines", - "Cmd-F5": "sortLinesInsensitive", - "Shift-Cmd-F5": "reverseSortLinesInsensitive", - "F2": "nextBookmark", - "Shift-F2": "prevBookmark", - "Cmd-F2": "toggleBookmark", - "Shift-Cmd-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - "Backspace": "smartBackspace", - "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", - "Cmd-K Cmd-K": "delLineRight", - "Cmd-K Cmd-U": "upcaseAtCursor", - "Cmd-K Cmd-L": "downcaseAtCursor", - "Cmd-K Cmd-Space": "setSublimeMark", - "Cmd-K Cmd-A": "selectToSublimeMark", - "Cmd-K Cmd-W": "deleteToSublimeMark", - "Cmd-K Cmd-X": "swapWithSublimeMark", - "Cmd-K Cmd-Y": "sublimeYank", - "Cmd-K Cmd-C": "showInCenter", - "Cmd-K Cmd-G": "clearBookmarks", - "Cmd-K Cmd-Backspace": "delLineLeft", - "Cmd-K Cmd-1": "foldAll", - "Cmd-K Cmd-0": "unfoldAll", - "Cmd-K Cmd-J": "unfoldAll", - "Ctrl-Shift-Up": "addCursorToPrevLine", - "Ctrl-Shift-Down": "addCursorToNextLine", - "Cmd-F3": "findUnder", - "Shift-Cmd-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Cmd-[": "fold", - "Shift-Cmd-]": "unfold", - "Cmd-I": "findIncremental", - "Shift-Cmd-I": "findIncrementalReverse", - "Cmd-H": "replace", - "F3": "findNext", - "Shift-F3": "findPrev", - "fallthrough": "macDefault" - }; - CodeMirror.normalizeKeyMap(keyMap.macSublime); - keyMap.pcSublime = { - "Shift-Tab": "indentLess", - "Shift-Ctrl-K": "deleteLine", - "Alt-Q": "wrapLines", - "Ctrl-T": "transposeChars", - "Alt-Left": "goSubwordLeft", - "Alt-Right": "goSubwordRight", - "Ctrl-Up": "scrollLineUp", - "Ctrl-Down": "scrollLineDown", - "Ctrl-L": "selectLine", - "Shift-Ctrl-L": "splitSelectionByLine", - "Esc": "singleSelectionTop", - "Ctrl-Enter": "insertLineAfter", - "Shift-Ctrl-Enter": "insertLineBefore", - "Ctrl-D": "selectNextOccurrence", - "Shift-Ctrl-Space": "selectScope", - "Shift-Ctrl-M": "selectBetweenBrackets", - "Ctrl-M": "goToBracket", - "Shift-Ctrl-Up": "swapLineUp", - "Shift-Ctrl-Down": "swapLineDown", - "Ctrl-/": "toggleCommentIndented", - "Ctrl-J": "joinLines", - "Shift-Ctrl-D": "duplicateLine", - "F9": "sortLines", - "Shift-F9": "reverseSortLines", - "Ctrl-F9": "sortLinesInsensitive", - "Shift-Ctrl-F9": "reverseSortLinesInsensitive", - "F2": "nextBookmark", - "Shift-F2": "prevBookmark", - "Ctrl-F2": "toggleBookmark", - "Shift-Ctrl-F2": "clearBookmarks", - "Alt-F2": "selectBookmarks", - "Backspace": "smartBackspace", - "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", - "Ctrl-K Ctrl-K": "delLineRight", - "Ctrl-K Ctrl-U": "upcaseAtCursor", - "Ctrl-K Ctrl-L": "downcaseAtCursor", - "Ctrl-K Ctrl-Space": "setSublimeMark", - "Ctrl-K Ctrl-A": "selectToSublimeMark", - "Ctrl-K Ctrl-W": "deleteToSublimeMark", - "Ctrl-K Ctrl-X": "swapWithSublimeMark", - "Ctrl-K Ctrl-Y": "sublimeYank", - "Ctrl-K Ctrl-C": "showInCenter", - "Ctrl-K Ctrl-G": "clearBookmarks", - "Ctrl-K Ctrl-Backspace": "delLineLeft", - "Ctrl-K Ctrl-1": "foldAll", - "Ctrl-K Ctrl-0": "unfoldAll", - "Ctrl-K Ctrl-J": "unfoldAll", - "Ctrl-Alt-Up": "addCursorToPrevLine", - "Ctrl-Alt-Down": "addCursorToNextLine", - "Ctrl-F3": "findUnder", - "Shift-Ctrl-F3": "findUnderPrevious", - "Alt-F3": "findAllUnder", - "Shift-Ctrl-[": "fold", - "Shift-Ctrl-]": "unfold", - "Ctrl-I": "findIncremental", - "Shift-Ctrl-I": "findIncrementalReverse", - "Ctrl-H": "replace", - "F3": "findNext", - "Shift-F3": "findPrev", - "fallthrough": "pcDefault" }; - CodeMirror.normalizeKeyMap(keyMap.pcSublime); - var mac = keyMap.default == keyMap.macDefault; - keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; - }); - })(); - var sublimeExports = sublime$2.exports; - const sublime = /* @__PURE__ */codemirror.getDefaultExportFromCjs(sublimeExports); - const sublime$1 = /* @__PURE__ */_mergeNamespaces({ - __proto__: null, - default: sublime - }, [sublimeExports]); - exports.sublime = sublime$1; - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/async-helpers/index.js": - /*!*********************************************************!*\ - !*** ../../graphiql-toolkit/esm/async-helpers/index.js ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.fetcherReturnToPromise = fetcherReturnToPromise; - exports.isAsyncIterable = isAsyncIterable; - exports.isObservable = isObservable; - exports.isPromise = isPromise; - var __awaiter = void 0 && (void 0).__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); + ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout); + this.readDOMTimeout = null; } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + var cm = this.cm, + display = cm.display, + sel = cm.doc.sel.primary(); + var from = sel.from(), + to = sel.to(); + if (from.ch == 0 && from.line > cm.firstLine()) { + from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - function isPromise(value) { - return typeof value === 'object' && value !== null && typeof value.then === 'function'; - } - function observableToPromise(observable) { - return new Promise((resolve, reject) => { - const subscription = observable.subscribe({ - next(v) { - resolve(v); - subscription.unsubscribe(); - }, - error: reject, - complete() { - reject(new Error('no value resolved')); + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { + to = Pos(to.line + 1, 0); } - }); - }); - } - function isObservable(value) { - return typeof value === 'object' && value !== null && 'subscribe' in value && typeof value.subscribe === 'function'; - } - function isAsyncIterable(input) { - return typeof input === 'object' && input !== null && (input[Symbol.toStringTag] === 'AsyncGenerator' || Symbol.asyncIterator in input); - } - function asyncIterableToPromise(input) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const iteratorReturn = (_a = ('return' in input ? input : input[Symbol.asyncIterator]()).return) === null || _a === void 0 ? void 0 : _a.bind(input); - const iteratorNext = ('next' in input ? input : input[Symbol.asyncIterator]()).next.bind(input); - const result = yield iteratorNext(); - void (iteratorReturn === null || iteratorReturn === void 0 ? void 0 : iteratorReturn()); - return result.value; - }); - } - function fetcherReturnToPromise(fetcherResult) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield fetcherResult; - if (isAsyncIterable(result)) { - return asyncIterableToPromise(result); - } - if (isObservable(result)) { - return observableToPromise(result); - } - return result; - }); - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js": - /*!******************************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/createFetcher.js ***! - \******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.createGraphiQLFetcher = createGraphiQLFetcher; - var _lib = __webpack_require__(/*! ./lib */ "../../graphiql-toolkit/esm/create-fetcher/lib.js"); - function createGraphiQLFetcher(options) { - let httpFetch; - if (typeof window !== 'undefined' && window.fetch) { - httpFetch = window.fetch; - } - if ((options === null || options === void 0 ? void 0 : options.enableIncrementalDelivery) === null || options.enableIncrementalDelivery !== false) { - options.enableIncrementalDelivery = true; - } - if (options.fetch) { - httpFetch = options.fetch; - } - if (!httpFetch) { - throw new Error('No valid fetcher implementation available'); - } - const simpleFetcher = (0, _lib.createSimpleFetcher)(options, httpFetch); - const httpFetcher = options.enableIncrementalDelivery ? (0, _lib.createMultipartFetcher)(options, httpFetch) : simpleFetcher; - return (graphQLParams, fetcherOpts) => { - if (graphQLParams.operationName === 'IntrospectionQuery') { - return (options.schemaFetcher || simpleFetcher)(graphQLParams, fetcherOpts); - } - const isSubscription = (fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.documentAST) ? (0, _lib.isSubscriptionWithName)(fetcherOpts.documentAST, graphQLParams.operationName || undefined) : false; - if (isSubscription) { - const wsFetcher = (0, _lib.getWsFetcher)(options, fetcherOpts); - if (!wsFetcher) { - throw new Error(`Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${options.subscriptionUrl ? `Provided URL ${options.subscriptionUrl} failed` : 'Please provide subscriptionUrl, wsClient or legacyClient option first.'}`); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { + return false; } - return wsFetcher(graphQLParams); - } - return httpFetcher(graphQLParams, fetcherOpts); - }; - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/create-fetcher/index.js": - /*!**********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/index.js ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var _exportNames = { - createGraphiQLFetcher: true - }; - Object.defineProperty(exports, "createGraphiQLFetcher", ({ - enumerable: true, - get: function () { - return _createFetcher.createGraphiQLFetcher; - } - })); - var _types = __webpack_require__(/*! ./types */ "../../graphiql-toolkit/esm/create-fetcher/types.js"); - Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _types[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _types[key]; - } - }); - }); - var _createFetcher = __webpack_require__(/*! ./createFetcher */ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js"); - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/create-fetcher/lib.js": - /*!********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/lib.js ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isSubscriptionWithName = exports.getWsFetcher = exports.createWebsocketsFetcherFromUrl = exports.createWebsocketsFetcherFromClient = exports.createSimpleFetcher = exports.createMultipartFetcher = exports.createLegacyWebsocketsFetcher = void 0; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _meros = __webpack_require__(/*! meros */ "../../../node_modules/meros/browser/index.js"); - var _pushPullAsyncIterableIterator = __webpack_require__(/*! @n1ru4l/push-pull-async-iterable-iterator */ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js"); - var __awaiter = void 0 && (void 0).__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); + var fromIndex, fromLine, fromNode; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line); + fromNode = display.view[0].node; + } else { + fromLine = lineNo(display.view[fromIndex].line); + fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + var toLine, toNode; + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1; + toNode = display.lineDiv.lastChild; + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1; + toNode = display.view[toIndex + 1].node.previousSibling; } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + if (!fromNode) { + return false; + } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { + newText.pop(); + oldText.pop(); + toLine--; + } else if (newText[0] == oldText[0]) { + newText.shift(); + oldText.shift(); + fromLine++; + } else { + break; + } + } + var cutFront = 0, + cutEnd = 0; + var newTop = newText[0], + oldTop = oldText[0], + maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { + ++cutFront; + } + var newBot = lst(newText), + oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + ++cutEnd; + } + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront--; + cutEnd++; + } + } + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - var __await = void 0 && (void 0).__await || function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], - i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function (v) { - return new Promise(function (resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function (v) { - resolve({ - value: v, - done: d - }); - }, reject); - } - }; - var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), - i, - q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function (v) { - return new Promise(function (a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); + ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd(); }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } - }; - const errorHasCode = err => { - return typeof err === 'object' && err !== null && 'code' in err; - }; - const isSubscriptionWithName = (document, name) => { - let isSubscription = false; - (0, _graphql.visit)(document, { - OperationDefinition(node) { - var _a; - if (name === ((_a = node.name) === null || _a === void 0 ? void 0 : _a.value) && node.operation === 'subscription') { - isSubscription = true; + ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { + return; } - } - }); - return isSubscription; - }; - exports.isSubscriptionWithName = isSubscriptionWithName; - const createSimpleFetcher = (options, httpFetch) => (graphQLParams, fetcherOpts) => __awaiter(void 0, void 0, void 0, function* () { - const data = yield httpFetch(options.url, { - method: 'POST', - body: JSON.stringify(graphQLParams), - headers: Object.assign(Object.assign({ - 'content-type': 'application/json' - }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) - }); - return data.json(); - }); - exports.createSimpleFetcher = createSimpleFetcher; - const createWebsocketsFetcherFromUrl = (url, connectionParams) => { - let wsClient; - try { - const { - createClient - } = __webpack_require__(/*! graphql-ws */ "../../../node_modules/graphql-ws/lib/index.js"); - wsClient = createClient({ - url, - connectionParams - }); - return createWebsocketsFetcherFromClient(wsClient); - } catch (err) { - if (errorHasCode(err) && err.code === 'MODULE_NOT_FOUND') { - throw new Error("You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'"); - } - console.error(`Error creating websocket client for ${url}`, err); - } - }; - exports.createWebsocketsFetcherFromUrl = createWebsocketsFetcherFromUrl; - const createWebsocketsFetcherFromClient = wsClient => graphQLParams => (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => wsClient.subscribe(graphQLParams, Object.assign(Object.assign({}, sink), { - error(err) { - if (err instanceof CloseEvent) { - sink.error(new Error(`Socket closed with event ${err.code} ${err.reason || ''}`.trim())); - } else { - sink.error(err); - } - } - }))); - exports.createWebsocketsFetcherFromClient = createWebsocketsFetcherFromClient; - const createLegacyWebsocketsFetcher = legacyWsClient => graphQLParams => { - const observable = legacyWsClient.request(graphQLParams); - return (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => observable.subscribe(sink).unsubscribe); - }; - exports.createLegacyWebsocketsFetcher = createLegacyWebsocketsFetcher; - const createMultipartFetcher = (options, httpFetch) => function (graphQLParams, fetcherOpts) { - return __asyncGenerator(this, arguments, function* () { - var e_1, _a; - const response = yield __await(httpFetch(options.url, { - method: 'POST', - body: JSON.stringify(graphQLParams), - headers: Object.assign(Object.assign({ - 'content-type': 'application/json', - accept: 'application/json, multipart/mixed' - }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) - }).then(r => (0, _meros.meros)(r, { - multiple: true - }))); - if (!(0, _pushPullAsyncIterableIterator.isAsyncIterable)(response)) { - return yield __await(yield yield __await(response.json())); - } - try { - for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = yield __await(response_1.next()), !response_1_1.done;) { - const chunk = response_1_1.value; - if (chunk.some(part => !part.json)) { - const message = chunk.map(part => `Headers::\n${part.headers}\n\nBody::\n${part.body}`); - throw new Error(`Expected multipart chunks to be of json type. got:\n${message}`); + clearTimeout(this.readDOMTimeout); + this.composing = null; + this.updateFromDOM(); + this.div.blur(); + this.div.focus(); + }; + ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1$1 = this; + if (this.readDOMTimeout != null) { + return; + } + this.readDOMTimeout = setTimeout(function () { + this$1$1.readDOMTimeout = null; + if (this$1$1.composing) { + if (this$1$1.composing.done) { + this$1$1.composing = null; + } else { + return; + } } - yield yield __await(chunk.map(part => part.body)); + this$1$1.updateFromDOM(); + }, 80); + }; + ContentEditableInput.prototype.updateFromDOM = function () { + var this$1$1 = this; + if (this.cm.isReadOnly() || !this.pollContent()) { + runInOp(this.cm, function () { + return regChange(this$1$1.cm); + }); } - } catch (e_1_1) { - e_1 = { - error: e_1_1 - }; - } finally { - try { - if (response_1_1 && !response_1_1.done && (_a = response_1.return)) yield __await(_a.call(response_1)); - } finally { - if (e_1) throw e_1.error; + }; + ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false"; + }; + ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0 || this.composing) { + return; + } + e.preventDefault(); + if (!this.cm.isReadOnly()) { + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } - } - }); - }; - exports.createMultipartFetcher = createMultipartFetcher; - const getWsFetcher = (options, fetcherOpts) => { - if (options.wsClient) { - return createWebsocketsFetcherFromClient(options.wsClient); - } - if (options.subscriptionUrl) { - return createWebsocketsFetcherFromUrl(options.subscriptionUrl, Object.assign(Object.assign({}, options.wsConnectionParams), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers)); - } - const legacyWebsocketsClient = options.legacyClient || options.legacyWsClient; - if (legacyWebsocketsClient) { - return createLegacyWebsocketsFetcher(legacyWebsocketsClient); - } - }; - exports.getWsFetcher = getWsFetcher; - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/create-fetcher/types.js": - /*!**********************************************************!*\ - !*** ../../graphiql-toolkit/esm/create-fetcher/types.js ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/format/index.js": - /*!**************************************************!*\ - !*** ../../graphiql-toolkit/esm/format/index.js ***! - \**************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.formatError = formatError; - exports.formatResult = formatResult; - function stringify(obj) { - return JSON.stringify(obj, null, 2); - } - function formatSingleError(error) { - return Object.assign(Object.assign({}, error), { - message: error.message, - stack: error.stack - }); - } - function handleSingleError(error) { - if (error instanceof Error) { - return formatSingleError(error); - } - return error; - } - function formatError(error) { - if (Array.isArray(error)) { - return stringify({ - errors: error.map(e => handleSingleError(e)) - }); - } - return stringify({ - errors: [handleSingleError(error)] - }); - } - function formatResult(result) { - return stringify(result); - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js": - /*!*******************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js ***! - \*******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.fillLeafs = fillLeafs; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function fillLeafs(schema, docString, getDefaultFieldNames) { - const insertions = []; - if (!schema || !docString) { - return { - insertions, - result: docString }; - } - let ast; - try { - ast = (0, _graphql.parse)(docString); - } catch (_a) { - return { - insertions, - result: docString + ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor"); }; - } - const fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames; - const typeInfo = new _graphql.TypeInfo(schema); - (0, _graphql.visit)(ast, { - leave(node) { - typeInfo.leave(node); - }, - enter(node) { - typeInfo.enter(node); - if (node.kind === 'Field' && !node.selectionSet) { - const fieldType = typeInfo.getType(); - const selectionSet = buildSelectionSet(isFieldType(fieldType), fieldNameFn); - if (selectionSet && node.loc) { - const indent = getIndentation(docString, node.loc.start); - insertions.push({ - index: node.loc.end, - string: ' ' + (0, _graphql.print)(selectionSet).replaceAll('\n', '\n' + indent) - }); - } + ContentEditableInput.prototype.onContextMenu = function () {}; + ContentEditableInput.prototype.resetPosition = function () {}; + ContentEditableInput.prototype.needsContentAttribute = true; + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) { + return null; } + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + var order = getOrder(line, cm.doc.direction), + side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; } - }); - return { - insertions, - result: withInsertions(docString, insertions) - }; - } - function defaultGetDefaultFieldNames(type) { - if (!('getFields' in type)) { - return []; - } - const fields = type.getFields(); - if (fields.id) { - return ['id']; - } - if (fields.edges) { - return ['edges']; - } - if (fields.node) { - return ['node']; - } - const leafFieldNames = []; - for (const fieldName of Object.keys(fields)) { - if ((0, _graphql.isLeafType)(fields[fieldName].type)) { - leafFieldNames.push(fieldName); - } - } - return leafFieldNames; - } - function buildSelectionSet(type, getDefaultFieldNames) { - const namedType = (0, _graphql.getNamedType)(type); - if (!type || (0, _graphql.isLeafType)(type)) { - return; - } - const fieldNames = getDefaultFieldNames(namedType); - if (!Array.isArray(fieldNames) || fieldNames.length === 0 || !('getFields' in namedType)) { - return; - } - return { - kind: _graphql.Kind.SELECTION_SET, - selections: fieldNames.map(fieldName => { - const fieldDef = namedType.getFields()[fieldName]; - const fieldType = fieldDef ? fieldDef.type : null; - return { - kind: _graphql.Kind.FIELD, - name: { - kind: _graphql.Kind.NAME, - value: fieldName - }, - selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames) - }; - }) - }; - } - function withInsertions(initial, insertions) { - if (insertions.length === 0) { - return initial; - } - let edited = ''; - let prevIndex = 0; - for (const { - index, - string - } of insertions) { - edited += initial.slice(prevIndex, index) + string; - prevIndex = index; - } - edited += initial.slice(prevIndex); - return edited; - } - function getIndentation(str, index) { - let indentStart = index; - let indentEnd = index; - while (indentStart) { - const c = str.charCodeAt(indentStart - 1); - if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { - break; - } - indentStart--; - if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { - indentEnd = indentStart; - } - } - return str.slice(indentStart, indentEnd); - } - function isFieldType(fieldType) { - if (fieldType) { - return fieldType; - } - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/index.js": - /*!***********************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/index.js ***! - \***********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var _autoComplete = __webpack_require__(/*! ./auto-complete */ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js"); - Object.keys(_autoComplete).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _autoComplete[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _autoComplete[key]; - } - }); - }); - var _mergeAst = __webpack_require__(/*! ./merge-ast */ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js"); - Object.keys(_mergeAst).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _mergeAst[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _mergeAst[key]; - } - }); - }); - var _operationName = __webpack_require__(/*! ./operation-name */ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js"); - Object.keys(_operationName).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _operationName[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _operationName[key]; + function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) { + if (/CodeMirror-gutter-wrapper/.test(scan.className)) { + return true; + } + } + return false; } - }); - }); - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js": - /*!***************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js ***! - \***************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.mergeAst = mergeAst; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function uniqueBy(array, iteratee) { - var _a; - const FilteredMap = new Map(); - const result = []; - for (const item of array) { - if (item.kind === 'Field') { - const uniqueValue = iteratee(item); - const existing = FilteredMap.get(uniqueValue); - if ((_a = item.directives) === null || _a === void 0 ? void 0 : _a.length) { - const itemClone = Object.assign({}, item); - result.push(itemClone); - } else if ((existing === null || existing === void 0 ? void 0 : existing.selectionSet) && item.selectionSet) { - existing.selectionSet.selections = [...existing.selectionSet.selections, ...item.selectionSet.selections]; - } else if (!existing) { - const itemClone = Object.assign({}, item); - FilteredMap.set(uniqueValue, itemClone); - result.push(itemClone); + function badPos(pos, bad) { + if (bad) { + pos.bad = true; } - } else { - result.push(item); + return pos; } - } - return result; - } - function inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType) { - var _a; - const selectionSetTypeName = selectionSetType ? (0, _graphql.getNamedType)(selectionSetType).name : null; - const outputSelections = []; - const seenSpreads = []; - for (let selection of selections) { - if (selection.kind === 'FragmentSpread') { - const fragmentName = selection.name.value; - if (!selection.directives || selection.directives.length === 0) { - if (seenSpreads.includes(fragmentName)) { - continue; - } else { - seenSpreads.push(fragmentName); - } - } - const fragmentDefinition = fragmentDefinitions[selection.name.value]; - if (fragmentDefinition) { - const { - typeCondition, - directives, - selectionSet - } = fragmentDefinition; - selection = { - kind: _graphql.Kind.INLINE_FRAGMENT, - typeCondition, - directives, - selectionSet + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", + closing = false, + lineSep = cm.doc.lineSeparator(), + extraLinebreak = false; + function recognizeMarker(id) { + return function (marker) { + return marker.id == id; }; } - } - if (selection.kind === _graphql.Kind.INLINE_FRAGMENT && (!selection.directives || ((_a = selection.directives) === null || _a === void 0 ? void 0 : _a.length) === 0)) { - const fragmentTypeName = selection.typeCondition ? selection.typeCondition.name.value : null; - if (!fragmentTypeName || fragmentTypeName === selectionSetTypeName) { - outputSelections.push(...inlineRelevantFragmentSpreads(fragmentDefinitions, selection.selectionSet.selections, selectionSetType)); - continue; + function close() { + if (closing) { + text += lineSep; + if (extraLinebreak) { + text += lineSep; + } + closing = extraLinebreak = false; + } } - } - outputSelections.push(selection); - } - return outputSelections; - } - function mergeAst(documentAST, schema) { - const typeInfo = schema ? new _graphql.TypeInfo(schema) : null; - const fragmentDefinitions = Object.create(null); - for (const definition of documentAST.definitions) { - if (definition.kind === _graphql.Kind.FRAGMENT_DEFINITION) { - fragmentDefinitions[definition.name.value] = definition; - } - } - const flattenVisitors = { - SelectionSet(node) { - const selectionSetType = typeInfo ? typeInfo.getParentType() : null; - let { - selections - } = node; - selections = inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType); - return Object.assign(Object.assign({}, node), { - selections - }); - }, - FragmentDefinition() { - return null; - } - }; - const flattenedAST = (0, _graphql.visit)(documentAST, typeInfo ? (0, _graphql.visitWithTypeInfo)(typeInfo, flattenVisitors) : flattenVisitors); - const deduplicateVisitors = { - SelectionSet(node) { - let { - selections - } = node; - selections = uniqueBy(selections, selection => selection.alias ? selection.alias.value : selection.name.value); - return Object.assign(Object.assign({}, node), { - selections - }); - }, - FragmentDefinition() { - return null; - } - }; - return (0, _graphql.visit)(flattenedAST, deduplicateVisitors); - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js": - /*!********************************************************************!*\ - !*** ../../graphiql-toolkit/esm/graphql-helpers/operation-name.js ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getSelectedOperationName = getSelectedOperationName; - function getSelectedOperationName(prevOperations, prevSelectedOperationName, operations) { - if (!operations || operations.length < 1) { - return; - } - const names = operations.map(op => { - var _a; - return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; - }); - if (prevSelectedOperationName && names.includes(prevSelectedOperationName)) { - return prevSelectedOperationName; - } - if (prevSelectedOperationName && prevOperations) { - const prevNames = prevOperations.map(op => { - var _a; - return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; - }); - const prevIndex = prevNames.indexOf(prevSelectedOperationName); - if (prevIndex !== -1 && prevIndex < names.length) { - return names[prevIndex]; - } - } - return names[0]; - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/index.js": - /*!*******************************************!*\ - !*** ../../graphiql-toolkit/esm/index.js ***! - \*******************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var _asyncHelpers = __webpack_require__(/*! ./async-helpers */ "../../graphiql-toolkit/esm/async-helpers/index.js"); - Object.keys(_asyncHelpers).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _asyncHelpers[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _asyncHelpers[key]; - } - }); - }); - var _createFetcher = __webpack_require__(/*! ./create-fetcher */ "../../graphiql-toolkit/esm/create-fetcher/index.js"); - Object.keys(_createFetcher).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _createFetcher[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _createFetcher[key]; - } - }); - }); - var _format = __webpack_require__(/*! ./format */ "../../graphiql-toolkit/esm/format/index.js"); - Object.keys(_format).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _format[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _format[key]; - } - }); - }); - var _graphqlHelpers = __webpack_require__(/*! ./graphql-helpers */ "../../graphiql-toolkit/esm/graphql-helpers/index.js"); - Object.keys(_graphqlHelpers).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _graphqlHelpers[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _graphqlHelpers[key]; - } - }); - }); - var _storage = __webpack_require__(/*! ./storage */ "../../graphiql-toolkit/esm/storage/index.js"); - Object.keys(_storage).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _storage[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _storage[key]; - } - }); - }); - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/storage/base.js": - /*!**************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/base.js ***! - \**************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.StorageAPI = void 0; - function isQuotaError(storage, e) { - return e instanceof DOMException && (e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && storage.length !== 0; - } - class StorageAPI { - constructor(storage) { - if (storage) { - this.storage = storage; - } else if (storage === null) { - this.storage = null; - } else if (typeof window === 'undefined') { - this.storage = null; - } else { - this.storage = { - getItem: localStorage.getItem.bind(localStorage), - setItem: localStorage.setItem.bind(localStorage), - removeItem: localStorage.removeItem.bind(localStorage), - get length() { - let keys = 0; - for (const key in localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - keys += 1; + function addText(str) { + if (str) { + close(); + text += str; + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText) { + addText(cmText); + return; + } + var markerID = node.getAttribute("cm-marker"), + range2; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range2 = found[0].find(0))) { + addText(getBetween(cm.doc, range2.from, range2.to).join(lineSep)); } + return; } - return keys; - }, - clear() { - for (const key in localStorage) { - if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { - localStorage.removeItem(key); + if (node.getAttribute("contenteditable") == "false") { + return; + } + var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); + if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { + return; + } + if (isBlock) { + close(); + } + for (var i2 = 0; i2 < node.childNodes.length; i2++) { + walk(node.childNodes[i2]); + } + if (/^(pre|p)$/i.test(node.nodeName)) { + extraLinebreak = true; + } + if (isBlock) { + closing = true; + } + } else if (node.nodeType == 3) { + addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); + } + } + for (;;) { + walk(from); + if (from == to) { + break; + } + from = from.nextSibling; + extraLinebreak = false; + } + return text; + } + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) { + return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + } + node = null; + offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { + return null; + } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { + break; + } + } + } + for (var i2 = 0; i2 < cm.display.view.length; i2++) { + var lineView = cm.display.view[i2]; + if (lineView.node == lineNode) { + return locateNodeInLineView(lineView, node, offset); + } + } + } + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, + bad = false; + if (!node || !contains(wrapper, node)) { + return badPos(Pos(lineNo(lineView.line), 0), true); + } + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + var textNode = node.nodeType == 3 ? node : null, + topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) { + offset = textNode.nodeValue.length; + } + } + while (topNode.parentNode != wrapper) { + topNode = topNode.parentNode; + } + var measure = lineView.measure, + maps = measure.maps; + function find(textNode2, topNode2, offset2) { + for (var i2 = -1; i2 < (maps ? maps.length : 0); i2++) { + var map2 = i2 < 0 ? measure.map : maps[i2]; + for (var j = 0; j < map2.length; j += 3) { + var curNode = map2[j + 2]; + if (curNode == textNode2 || curNode == topNode2) { + var line2 = lineNo(i2 < 0 ? lineView.line : lineView.rest[i2]); + var ch = map2[j] + offset2; + if (offset2 < 0 || curNode != textNode2) { + ch = map2[j + (offset2 ? 1 : 0)]; + } + return Pos(line2, ch); } } } - }; - } - } - get(name) { - if (!this.storage) { - return null; - } - const key = `${STORAGE_NAMESPACE}:${name}`; - const value = this.storage.getItem(key); - if (value === 'null' || value === 'undefined') { - this.storage.removeItem(key); - return null; + } + var found = find(textNode, topNode, offset); + if (found) { + return badPos(found, bad); + } + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) { + return badPos(Pos(found.line, found.ch - dist), bad); + } else { + dist += after.textContent.length; + } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) { + return badPos(Pos(found.line, found.ch + dist$1), bad); + } else { + dist$1 += before.textContent.length; + } + } } - return value || null; - } - set(name, value) { - let quotaError = false; - let error = null; - if (this.storage) { - const key = `${STORAGE_NAMESPACE}:${name}`; - if (value) { - try { - this.storage.setItem(key, value); - } catch (e) { - error = e instanceof Error ? e : new Error(`${e}`); - quotaError = isQuotaError(this.storage, e); + var TextareaInput = function (cm) { + this.cm = cm; + this.prevInput = ""; + this.pollingFast = false; + this.polling = new Delayed(); + this.hasSelection = false; + this.composing = null; + }; + TextareaInput.prototype.init = function (display) { + var this$1$1 = this; + var input = this, + cm = this.cm; + this.createField(display); + var te = this.textarea; + display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); + if (ios) { + te.style.width = "0px"; + } + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1$1.hasSelection) { + this$1$1.hasSelection = null; + } + input.poll(); + }); + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { + return; + } + cm.state.pasteIncoming = + /* @__PURE__ */new Date(); + input.fastPoll(); + }); + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { + return; + } + if (cm.somethingSelected()) { + setLastCopied({ + lineWise: false, + text: cm.getSelections() + }); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + setLastCopied({ + lineWise: true, + text: ranges.text + }); + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") { + cm.state.cutIncoming = + /* @__PURE__ */new Date(); + } + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { + return; + } + if (!te.dispatchEvent) { + cm.state.pasteIncoming = + /* @__PURE__ */new Date(); + input.focus(); + return; + } + var event = new Event("paste"); + event.clipboardData = e.clipboardData; + te.dispatchEvent(event); + }); + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { + e_preventDefault(e); + } + }); + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + if (input.composing) { + input.composing.range.clear(); + } + input.composing = { + start, + range: cm.markText(start, cm.getCursor("to"), { + className: "CodeMirror-composing" + }) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; } + }); + }; + TextareaInput.prototype.createField = function (_display) { + this.wrapper = hiddenTextarea(); + this.textarea = this.wrapper.firstChild; + }; + TextareaInput.prototype.screenReaderLabelChanged = function (label) { + if (label) { + this.textarea.setAttribute("aria-label", label); } else { - this.storage.removeItem(key); + this.textarea.removeAttribute("aria-label"); } - } - return { - isQuotaError: quotaError, - error }; - } - clear() { - if (this.storage) { - this.storage.clear(); - } - } - } - exports.StorageAPI = StorageAPI; - const STORAGE_NAMESPACE = 'graphiql'; - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/storage/custom.js": - /*!****************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/custom.js ***! - \****************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.createLocalStorage = createLocalStorage; - function createLocalStorage({ - namespace - }) { - const storageKeyPrefix = `${namespace}:`; - const getStorageKey = key => `${storageKeyPrefix}${key}`; - const storage = { - setItem: (key, value) => localStorage.setItem(getStorageKey(key), value), - getItem: key => localStorage.getItem(getStorageKey(key)), - removeItem: key => localStorage.removeItem(getStorageKey(key)), - get length() { - let keys = 0; - for (const key in localStorage) { - if (key.indexOf(storageKeyPrefix) === 0) { - keys += 1; - } - } - return keys; - }, - clear() { - for (const key in localStorage) { - if (key.indexOf(storageKeyPrefix) === 0) { - localStorage.removeItem(key); + TextareaInput.prototype.prepareSelection = function () { + var cm = this.cm, + display = cm.display, + doc = cm.doc; + var result = prepareSelection(cm); + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), + lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); + } + return result; + }; + TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, + display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }; + TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending || this.composing) { + return; + } + var cm = this.cm; + if (cm.somethingSelected()) { + this.prevInput = ""; + var content = cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) { + selectInput(this.textarea); + } + if (ie && ie_version >= 9) { + this.hasSelection = content; + } + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) { + this.hasSelection = null; } } - } - }; - return storage; - } - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/storage/history.js": - /*!*****************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/history.js ***! - \*****************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.HistoryStore = void 0; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); - const MAX_QUERY_SIZE = 100000; - class HistoryStore { - constructor(storage, maxHistoryLength) { - this.storage = storage; - this.maxHistoryLength = maxHistoryLength; - this.updateHistory = ({ - query, - variables, - headers, - operationName - }) => { - if (!this.shouldSaveQuery(query, variables, headers, this.history.fetchRecent())) { + }; + TextareaInput.prototype.getField = function () { + return this.textarea; + }; + TextareaInput.prototype.supportsTouch = function () { + return false; + }; + TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { + this.textarea.focus(); + } catch (e) {} + } + }; + TextareaInput.prototype.blur = function () { + this.textarea.blur(); + }; + TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }; + TextareaInput.prototype.receivedFocus = function () { + this.slowPoll(); + }; + TextareaInput.prototype.slowPoll = function () { + var this$1$1 = this; + if (this.pollingFast) { return; } - this.history.push({ - query, - variables, - headers, - operationName + this.polling.set(this.cm.options.pollInterval, function () { + this$1$1.poll(); + if (this$1$1.cm.state.focused) { + this$1$1.slowPoll(); + } }); - const historyQueries = this.history.items; - const favoriteQueries = this.favorite.items; - this.queries = historyQueries.concat(favoriteQueries); }; - this.deleteHistory = ({ - query, - variables, - headers, - operationName, - favorite - }, clearFavorites = false) => { - function deleteFromStore(store) { - const found = store.items.find(x => x.query === query && x.variables === variables && x.headers === headers && x.operationName === operationName); - if (found) { - store.delete(found); + TextareaInput.prototype.fastPoll = function () { + var missed = false, + input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) { + missed = true; + input.polling.set(60, p); + } else { + input.pollingFast = false; + input.slowPoll(); + } + } + input.polling.set(20, p); + }; + TextareaInput.prototype.poll = function () { + var this$1$1 = this; + var cm = this.cm, + input = this.textarea, + prevInput = this.prevInput; + if (this.contextMenuPending || !cm.state.focused || hasSelection(input) && !prevInput && !this.composing || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { + return false; + } + var text = input.value; + if (text == prevInput && !cm.somethingSelected()) { + return false; + } + if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 8203 && !prevInput) { + prevInput = "​"; + } + if (first == 8666) { + this.reset(); + return this.cm.execCommand("undo"); } } - if (favorite || clearFavorites) { - deleteFromStore(this.favorite); + var same = 0, + l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { + ++same; + } + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1$1.composing ? "*compose" : null); + if (text.length > 1e3 || text.indexOf("\n") > -1) { + input.value = this$1$1.prevInput = ""; + } else { + this$1$1.prevInput = text; + } + if (this$1$1.composing) { + this$1$1.composing.range.clear(); + this$1$1.composing.range = cm.markText(this$1$1.composing.start, cm.getCursor("to"), { + className: "CodeMirror-composing" + }); + } + }); + return true; + }; + TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { + this.pollingFast = false; } - if (!favorite || clearFavorites) { - deleteFromStore(this.history); + }; + TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { + this.hasSelection = null; } - this.queries = [...this.history.items, ...this.favorite.items]; + this.fastPoll(); }; - this.history = new _query.QueryStore('queries', this.storage, this.maxHistoryLength); - this.favorite = new _query.QueryStore('favorites', this.storage, null); - this.queries = [...this.history.fetchAll(), ...this.favorite.fetchAll()]; - } - shouldSaveQuery(query, variables, headers, lastQuerySaved) { - if (!query) { - return false; - } - try { - (0, _graphql.parse)(query); - } catch (_a) { - return false; - } - if (query.length > MAX_QUERY_SIZE) { - return false; - } - if (!lastQuerySaved) { - return true; - } - if (JSON.stringify(query) === JSON.stringify(lastQuerySaved.query)) { - if (JSON.stringify(variables) === JSON.stringify(lastQuerySaved.variables)) { - if (JSON.stringify(headers) === JSON.stringify(lastQuerySaved.headers)) { - return false; + TextareaInput.prototype.onContextMenu = function (e) { + var input = this, + cm = input.cm, + display = cm.display, + te = input.textarea; + if (input.contextMenuPending) { + input.contextMenuPending(); + } + var pos = posFromMouse(cm, e), + scrollPos = display.scroller.scrollTop; + if (!pos || presto) { + return; + } + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) { + operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + } + var oldCSS = te.style.cssText, + oldWrapperCSS = input.wrapper.style.cssText; + var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); + input.wrapper.style.cssText = "position: static"; + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + var oldScrollY; + if (webkit) { + oldScrollY = window.scrollY; + } + display.input.focus(); + if (webkit) { + window.scrollTo(null, oldScrollY); + } + display.input.reset(); + if (!cm.somethingSelected()) { + te.value = input.prevInput = " "; + } + input.contextMenuPending = rehide; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "​" + (selected ? te.value : ""); + te.value = "⇚"; + te.value = extval; + input.prevInput = selected ? "" : "​"; + te.selectionStart = 1; + te.selectionEnd = extval.length; + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + if (input.contextMenuPending != rehide) { + return; } - if (headers && !lastQuerySaved.headers) { - return false; + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) { + display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + } + if (te.selectionStart != null) { + if (!ie || ie && ie_version < 9) { + prepareSelectAllHack(); + } + var i2 = 0, + poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "​") { + operation(cm, selectAll)(cm); + } else if (i2++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500); + } else { + display.selForContextMenu = null; + display.input.reset(); + } + }; + display.detectingSelectAll = setTimeout(poll, 200); } } - if (variables && !lastQuerySaved.variables) { - return false; + if (ie && ie_version >= 9) { + prepareSelectAllHack(); + } + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); } - } - return true; - } - toggleFavorite({ - query, - variables, - headers, - operationName, - label, - favorite - }) { - const item = { - query, - variables, - headers, - operationName, - label }; - if (favorite) { - item.favorite = false; - this.favorite.delete(item); - this.history.push(item); - } else { - item.favorite = true; - this.favorite.push(item); - this.history.delete(item); + TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { + this.reset(); + } + this.textarea.disabled = val == "nocursor"; + this.textarea.readOnly = !!val; + }; + TextareaInput.prototype.setUneditable = function () {}; + TextareaInput.prototype.needsContentAttribute = false; + function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) { + options.tabindex = textarea.tabIndex; + } + if (!options.placeholder && textarea.placeholder) { + options.placeholder = textarea.placeholder; + } + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + function save() { + textarea.value = cm.getValue(); + } + var realSubmit; + if (textarea.form) { + on(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form; + realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch (e) {} + } + } + options.finishInit = function (cm2) { + cm2.save = save; + cm2.getTextArea = function () { + return textarea; + }; + cm2.toTextArea = function () { + cm2.toTextArea = isNaN; + save(); + textarea.parentNode.removeChild(cm2.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") { + textarea.form.submit = realSubmit; + } + } + }; + }; + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { + return textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + } + function addLegacyProps(CodeMirror2) { + CodeMirror2.off = off; + CodeMirror2.on = on; + CodeMirror2.wheelEventPixels = wheelEventPixels; + CodeMirror2.Doc = Doc; + CodeMirror2.splitLines = splitLinesAuto; + CodeMirror2.countColumn = countColumn; + CodeMirror2.findColumn = findColumn; + CodeMirror2.isWordChar = isWordCharBasic; + CodeMirror2.Pass = Pass; + CodeMirror2.signal = signal; + CodeMirror2.Line = Line; + CodeMirror2.changeEnd = changeEnd; + CodeMirror2.scrollbarModel = scrollbarModel; + CodeMirror2.Pos = Pos; + CodeMirror2.cmpPos = cmp; + CodeMirror2.modes = modes; + CodeMirror2.mimeModes = mimeModes; + CodeMirror2.resolveMode = resolveMode; + CodeMirror2.getMode = getMode; + CodeMirror2.modeExtensions = modeExtensions; + CodeMirror2.extendMode = extendMode; + CodeMirror2.copyState = copyState; + CodeMirror2.startState = startState; + CodeMirror2.innerMode = innerMode; + CodeMirror2.commands = commands; + CodeMirror2.keyMap = keyMap; + CodeMirror2.keyName = keyName; + CodeMirror2.isModifierKey = isModifierKey; + CodeMirror2.lookupKey = lookupKey; + CodeMirror2.normalizeKeyMap = normalizeKeyMap; + CodeMirror2.StringStream = StringStream; + CodeMirror2.SharedTextMarker = SharedTextMarker; + CodeMirror2.TextMarker = TextMarker; + CodeMirror2.LineWidget = LineWidget; + CodeMirror2.e_preventDefault = e_preventDefault; + CodeMirror2.e_stopPropagation = e_stopPropagation; + CodeMirror2.e_stop = e_stop; + CodeMirror2.addClass = addClass; + CodeMirror2.contains = contains; + CodeMirror2.rmClass = rmClass; + CodeMirror2.keyNames = keyNames; + } + defineOptions(CodeMirror); + addEditorMethods(CodeMirror); + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { + CodeMirror.prototype[prop] = /* @__PURE__ */function (method) { + return function () { + return method.apply(this.doc, arguments); + }; + }(Doc.prototype[prop]); + } } - this.queries = [...this.history.items, ...this.favorite.items]; - } - editLabel({ - query, - variables, - headers, - operationName, - label, - favorite - }, index) { - const item = { - query, - variables, - headers, - operationName, - label + eventMixin(Doc); + CodeMirror.inputStyles = { + "textarea": TextareaInput, + "contenteditable": ContentEditableInput }; - if (favorite) { - this.favorite.edit(Object.assign(Object.assign({}, item), { - favorite - }), index); - } else { - this.history.edit(item, index); + CodeMirror.defineMode = function (name) { + if (!CodeMirror.defaults.mode && name != "null") { + CodeMirror.defaults.mode = name; + } + defineMode.apply(this, arguments); + }; + CodeMirror.defineMIME = defineMIME; + CodeMirror.defineMode("null", function () { + return { + token: function (stream) { + return stream.skipToEnd(); + } + }; + }); + CodeMirror.defineMIME("text/plain", "null"); + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.fromTextArea = fromTextArea; + addLegacyProps(CodeMirror); + CodeMirror.version = "5.65.3"; + return CodeMirror; + }); + })(codemirror); + return codemirror.exports; +} +exports.getDefaultExportFromCjs = getDefaultExportFromCjs; +exports.requireCodemirror = requireCodemirror; + +/***/ }), + +/***/ "../../graphiql-react/dist/comment.cjs.js": +/*!************************************************!*\ + !*** ../../graphiql-react/dist/comment.cjs.js ***! + \************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } } - this.queries = [...this.history.items, ...this.favorite.items]; } } - exports.HistoryStore = HistoryStore; - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/storage/index.js": - /*!***************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/index.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" })); - var _base = __webpack_require__(/*! ./base */ "../../graphiql-toolkit/esm/storage/base.js"); - Object.keys(_base).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _base[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _base[key]; - } - }); - }); - var _history = __webpack_require__(/*! ./history */ "../../graphiql-toolkit/esm/storage/history.js"); - Object.keys(_history).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _history[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _history[key]; +} +var comment$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var noOptions = {}; + var nonWS = /[^\s\u00a0]/; + var Pos = CodeMirror.Pos, + cmp = CodeMirror.cmpPos; + function firstNonWS(str) { + var found = str.search(nonWS); + return found == -1 ? 0 : found; + } + CodeMirror.commands.toggleComment = function (cm) { + cm.toggleComment(); + }; + CodeMirror.defineExtension("toggleComment", function (options) { + if (!options) options = noOptions; + var cm = this; + var minLine = Infinity, + ranges = this.listSelections(), + mode = null; + for (var i = ranges.length - 1; i >= 0; i--) { + var from = ranges[i].from(), + to = ranges[i].to(); + if (from.line >= minLine) continue; + if (to.line >= minLine) to = Pos(minLine, 0); + minLine = from.line; + if (mode == null) { + if (cm.uncomment(from, to, options)) mode = "un";else { + cm.lineComment(from, to, options); + mode = "line"; + } + } else if (mode == "un") { + cm.uncomment(from, to, options); + } else { + cm.lineComment(from, to, options); + } } }); - }); - var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); - Object.keys(_query).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _query[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _query[key]; + function probablyInsideString(cm, pos, line) { + return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line); + } + function getMode(cm, pos) { + var mode = cm.getMode(); + return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos); + } + CodeMirror.defineExtension("lineComment", function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var firstLine = self.getLine(from.line); + if (firstLine == null || probablyInsideString(self, from, firstLine)) return; + var commentString = options.lineComment || mode.lineComment; + if (!commentString) { + if (options.blockCommentStart || mode.blockCommentStart) { + options.fullLines = true; + self.blockComment(from, to, options); + } + return; } + var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1); + var pad = options.padding == null ? " " : options.padding; + var blankLines = options.commentBlankLines || from.line == to.line; + self.operation(function () { + if (options.indent) { + var baseString = null; + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i); + var whitespace = line.slice(0, firstNonWS(line)); + if (baseString == null || baseString.length > whitespace.length) { + baseString = whitespace; + } + } + for (var i = from.line; i < end; ++i) { + var line = self.getLine(i), + cut = baseString.length; + if (!blankLines && !nonWS.test(line)) continue; + if (line.slice(0, cut) != baseString) cut = firstNonWS(line); + self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut)); + } + } else { + for (var i = from.line; i < end; ++i) { + if (blankLines || nonWS.test(self.getLine(i))) self.replaceRange(commentString + pad, Pos(i, 0)); + } + } + }); }); - }); - var _custom = __webpack_require__(/*! ./custom */ "../../graphiql-toolkit/esm/storage/custom.js"); - Object.keys(_custom).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _custom[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _custom[key]; + CodeMirror.defineExtension("blockComment", function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var startString = options.blockCommentStart || mode.blockCommentStart; + var endString = options.blockCommentEnd || mode.blockCommentEnd; + if (!startString || !endString) { + if ((options.lineComment || mode.lineComment) && options.fullLines != false) self.lineComment(from, to, options); + return; } + if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return; + var end = Math.min(to.line, self.lastLine()); + if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end; + var pad = options.padding == null ? " " : options.padding; + if (from.line > end) return; + self.operation(function () { + if (options.fullLines != false) { + var lastLineHasText = nonWS.test(self.getLine(end)); + self.replaceRange(pad + endString, Pos(end)); + self.replaceRange(startString + pad, Pos(from.line, 0)); + var lead = options.blockCommentLead || mode.blockCommentLead; + if (lead != null) { + for (var i = from.line + 1; i <= end; ++i) if (i != end || lastLineHasText) self.replaceRange(lead + pad, Pos(i, 0)); + } + } else { + var atCursor = cmp(self.getCursor("to"), to) == 0, + empty = !self.somethingSelected(); + self.replaceRange(endString, to); + if (atCursor) self.setSelection(empty ? to : self.getCursor("from"), to); + self.replaceRange(startString, from); + } + }); + }); + CodeMirror.defineExtension("uncomment", function (from, to, options) { + if (!options) options = noOptions; + var self = this, + mode = getMode(self, from); + var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), + start = Math.min(from.line, end); + var lineString = options.lineComment || mode.lineComment, + lines = []; + var pad = options.padding == null ? " " : options.padding, + didSomething; + lineComment: { + if (!lineString) break lineComment; + for (var i = start; i <= end; ++i) { + var line = self.getLine(i); + var found = line.indexOf(lineString); + if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1; + if (found == -1 && nonWS.test(line)) break lineComment; + if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment; + lines.push(line); + } + self.operation(function () { + for (var i2 = start; i2 <= end; ++i2) { + var line2 = lines[i2 - start]; + var pos = line2.indexOf(lineString), + endPos = pos + lineString.length; + if (pos < 0) continue; + if (line2.slice(endPos, endPos + pad.length) == pad) endPos += pad.length; + didSomething = true; + self.replaceRange("", Pos(i2, pos), Pos(i2, endPos)); + } + }); + if (didSomething) return true; + } + var startString = options.blockCommentStart || mode.blockCommentStart; + var endString = options.blockCommentEnd || mode.blockCommentEnd; + if (!startString || !endString) return false; + var lead = options.blockCommentLead || mode.blockCommentLead; + var startLine = self.getLine(start), + open = startLine.indexOf(startString); + if (open == -1) return false; + var endLine = end == start ? startLine : self.getLine(end); + var close = endLine.indexOf(endString, end == start ? open + startString.length : 0); + var insideStart = Pos(start, open + 1), + insideEnd = Pos(end, close + 1); + if (close == -1 || !/comment/.test(self.getTokenTypeAt(insideStart)) || !/comment/.test(self.getTokenTypeAt(insideEnd)) || self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1) return false; + var lastStart = startLine.lastIndexOf(startString, from.ch); + var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length); + if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false; + firstEnd = endLine.indexOf(endString, to.ch); + var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch); + lastStart = firstEnd == -1 || almostLastStart == -1 ? -1 : to.ch + almostLastStart; + if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false; + self.operation(function () { + self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)), Pos(end, close + endString.length)); + var openEnd = open + startString.length; + if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length; + self.replaceRange("", Pos(start, open), Pos(start, openEnd)); + if (lead) for (var i2 = start + 1; i2 <= end; ++i2) { + var line2 = self.getLine(i2), + found2 = line2.indexOf(lead); + if (found2 == -1 || nonWS.test(line2.slice(0, found2))) continue; + var foundEnd = found2 + lead.length; + if (pad && line2.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length; + self.replaceRange("", Pos(i2, found2), Pos(i2, foundEnd)); + } + }); + return true; }); }); - - /***/ }), - - /***/ "../../graphiql-toolkit/esm/storage/query.js": - /*!***************************************************!*\ - !*** ../../graphiql-toolkit/esm/storage/query.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.QueryStore = void 0; - class QueryStore { - constructor(key, storage, maxSize = null) { - this.key = key; - this.storage = storage; - this.maxSize = maxSize; - this.items = this.fetchAll(); - } - get length() { - return this.items.length; - } - contains(item) { - return this.items.some(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); - } - edit(item, index) { - if (typeof index === 'number' && this.items[index]) { - const found = this.items[index]; - if (found.query === item.query && found.variables === item.variables && found.headers === item.headers && found.operationName === item.operationName) { - this.items.splice(index, 1, item); - this.save(); - return; +})(); +var commentExports = comment$2.exports; +const comment = /* @__PURE__ */codemirror.getDefaultExportFromCjs(commentExports); +const comment$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: comment +}, [commentExports]); +exports.comment = comment$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/dialog.cjs.js": +/*!***********************************************!*\ + !*** ../../graphiql-react/dist/dialog.cjs.js ***! + \***********************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } } - const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); - if (itemIndex !== -1) { - this.items.splice(itemIndex, 1, item); - this.save(); - } - } - delete(item) { - const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); - if (itemIndex !== -1) { - this.items.splice(itemIndex, 1); - this.save(); - } - } - fetchRecent() { - return this.items.at(-1); - } - fetchAll() { - const raw = this.storage.get(this.key); - if (raw) { - return JSON.parse(raw)[this.key]; - } - return []; } - push(item) { - const items = [...this.items, item]; - if (this.maxSize && items.length > this.maxSize) { - items.shift(); - } - for (let attempts = 0; attempts < 5; attempts++) { - const response = this.storage.set(this.key, JSON.stringify({ - [this.key]: items - })); - if (!(response === null || response === void 0 ? void 0 : response.error)) { - this.items = items; - } else if (response.isQuotaError && this.maxSize) { - items.shift(); + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var dialog$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function dialogDiv(cm, template, bottom) { + var wrap = cm.getWrapperElement(); + var dialog2; + dialog2 = wrap.appendChild(document.createElement("div")); + if (bottom) dialog2.className = "CodeMirror-dialog CodeMirror-dialog-bottom";else dialog2.className = "CodeMirror-dialog CodeMirror-dialog-top"; + if (typeof template == "string") { + dialog2.innerHTML = template; + } else { + dialog2.appendChild(template); + } + CodeMirror.addClass(wrap, "dialog-opened"); + return dialog2; + } + function closeNotification(cm, newVal) { + if (cm.state.currentNotificationClose) cm.state.currentNotificationClose(); + cm.state.currentNotificationClose = newVal; + } + CodeMirror.defineExtension("openDialog", function (template, callback, options) { + if (!options) options = {}; + closeNotification(this, null); + var dialog2 = dialogDiv(this, template, options.bottom); + var closed = false, + me = this; + function close(newVal) { + if (typeof newVal == "string") { + inp.value = newVal; } else { - return; + if (closed) return; + closed = true; + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + me.focus(); + if (options.onClose) options.onClose(dialog2); } } - } - save() { - this.storage.set(this.key, JSON.stringify({ - [this.key]: this.items - })); - } - } - exports.QueryStore = QueryStore; - - /***/ }), - - /***/ "../node_modules/linkify-it/build/index.cjs.js": - /*!*****************************************************!*\ - !*** ../node_modules/linkify-it/build/index.cjs.js ***! - \*****************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var uc_micro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); - function reFactory(opts) { - const re = {}; - opts = opts || {}; - re.src_Any = uc_micro.Any.source; - re.src_Cc = uc_micro.Cc.source; - re.src_Z = uc_micro.Z.source; - re.src_P = uc_micro.P.source; - - // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) - re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join('|'); - - // \p{\Z\Cc} (white spaces + control) - re.src_ZCc = [re.src_Z, re.src_Cc].join('|'); - - // Experimental. List of chars, completely prohibited in links - // because can separate it from other part of text - const text_separators = '[><\uff5c]'; - - // All possible word characters (everything without punctuation, spaces & controls) - // Defined via punctuation & spaces to save space - // Should be something like \p{\L\N\S\M} (\w but without `_`) - re.src_pseudo_letter = '(?:(?!' + text_separators + '|' + re.src_ZPCc + ')' + re.src_Any + ')'; - // The same as abothe but without [0-9] - // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; - - re.src_ip4 = '(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'; - - // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. - re.src_auth = '(?:(?:(?!' + re.src_ZCc + '|[@/\\[\\]()]).)+@)?'; - re.src_port = '(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?'; - re.src_host_terminator = '(?=$|' + text_separators + '|' + re.src_ZPCc + ')' + '(?!' + (opts['---'] ? '-(?!--)|' : '-|') + '_|:\\d|\\.-|\\.(?!$|' + re.src_ZPCc + '))'; - re.src_path = '(?:' + '[/?#]' + '(?:' + '(?!' + re.src_ZCc + '|' + text_separators + '|[()[\\]{}.,"\'?!\\-;]).|' + '\\[(?:(?!' + re.src_ZCc + '|\\]).)*\\]|' + '\\((?:(?!' + re.src_ZCc + '|[)]).)*\\)|' + '\\{(?:(?!' + re.src_ZCc + '|[}]).)*\\}|' + '\\"(?:(?!' + re.src_ZCc + '|["]).)+\\"|' + "\\'(?:(?!" + re.src_ZCc + "|[']).)+\\'|" + - // allow `I'm_king` if no pair found - "\\'(?=" + re.src_pseudo_letter + '|[-])|' + - // google has many dots in "google search" links (#66, #81). - // github has ... in commit range links, - // Restrict to - // - english - // - percent-encoded - // - parts of file path - // - params separator - // until more examples found. - '\\.{2,}[a-zA-Z0-9%/&]|' + '\\.(?!' + re.src_ZCc + '|[.]|$)|' + (opts['---'] ? '\\-(?!--(?:[^-]|$))(?:-*)|' // `---` => long dash, terminate - : '\\-+|') + - // allow `,,,` in paths - ',(?!' + re.src_ZCc + '|$)|' + - // allow `;` if not followed by space-like char - ';(?!' + re.src_ZCc + '|$)|' + - // allow `!!!` in paths, but not at the end - '\\!+(?!' + re.src_ZCc + '|[!]|$)|' + '\\?(?!' + re.src_ZCc + '|[?]|$)' + ')+' + '|\\/' + ')?'; - - // Allow anything in markdown spec, forbid quote (") at the first position - // because emails enclosed in quotes are far more common - re.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; - re.src_xn = 'xn--[a-z0-9\\-]{1,59}'; - - // More to read about domain names - // http://serverfault.com/questions/638260/ - - re.src_domain_root = - // Allow letters & digits (http://test1) - '(?:' + re.src_xn + '|' + re.src_pseudo_letter + '{1,63}' + ')'; - re.src_domain = '(?:' + re.src_xn + '|' + '(?:' + re.src_pseudo_letter + ')' + '|' + '(?:' + re.src_pseudo_letter + '(?:-|' + re.src_pseudo_letter + '){0,61}' + re.src_pseudo_letter + ')' + ')'; - re.src_host = '(?:' + - // Don't need IP check, because digits are already allowed in normal domain names - // src_ip4 + - // '|' + - '(?:(?:(?:' + re.src_domain + ')\\.)*' + re.src_domain /* _root */ + ')' + ')'; - re.tpl_host_fuzzy = '(?:' + re.src_ip4 + '|' + '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))' + ')'; - re.tpl_host_no_ip_fuzzy = '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))'; - re.src_host_strict = re.src_host + re.src_host_terminator; - re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; - re.src_host_port_strict = re.src_host + re.src_port + re.src_host_terminator; - re.tpl_host_port_fuzzy_strict = re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; - re.tpl_host_port_no_ip_fuzzy_strict = re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; - - // - // Main rules - // - - // Rude test fuzzy links by host, for quick deny - re.tpl_host_fuzzy_test = 'localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:' + re.src_ZPCc + '|>|$))'; - re.tpl_email_fuzzy = '(^|' + text_separators + '|"|\\(|' + re.src_ZCc + ')' + '(' + re.src_email_name + '@' + re.tpl_host_fuzzy_strict + ')'; - re.tpl_link_fuzzy = - // Fuzzy link can't be prepended with .:/\- and non punctuation. - // but can start with > (markdown blockquote) - '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_fuzzy_strict + re.src_path + ')'; - re.tpl_link_no_ip_fuzzy = - // Fuzzy link can't be prepended with .:/\- and non punctuation. - // but can start with > (markdown blockquote) - '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_no_ip_fuzzy_strict + re.src_path + ')'; - return re; - } - - // - // Helpers - // - - // Merge objects - // - function assign(obj /* from1, from2, from3, ... */) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; + var inp = dialog2.getElementsByTagName("input")[0], + button; + if (inp) { + inp.focus(); + if (options.value) { + inp.value = options.value; + if (options.selectValueOnOpen !== false) { + inp.select(); + } + } + if (options.onInput) CodeMirror.on(inp, "input", function (e) { + options.onInput(e, inp.value, close); + }); + if (options.onKeyUp) CodeMirror.on(inp, "keyup", function (e) { + options.onKeyUp(e, inp.value, close); + }); + CodeMirror.on(inp, "keydown", function (e) { + if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { + return; + } + if (e.keyCode == 27 || options.closeOnEnter !== false && e.keyCode == 13) { + inp.blur(); + CodeMirror.e_stop(e); + close(); + } + if (e.keyCode == 13) callback(inp.value, e); + }); + if (options.closeOnBlur !== false) CodeMirror.on(dialog2, "focusout", function (evt) { + if (evt.relatedTarget !== null) close(); + }); + } else if (button = dialog2.getElementsByTagName("button")[0]) { + CodeMirror.on(button, "click", function () { + close(); + me.focus(); + }); + if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); + button.focus(); + } + return close; + }); + CodeMirror.defineExtension("openConfirm", function (template, callbacks, options) { + closeNotification(this, null); + var dialog2 = dialogDiv(this, template, options && options.bottom); + var buttons = dialog2.getElementsByTagName("button"); + var closed = false, + me = this, + blurring = 1; + function close() { + if (closed) return; + closed = true; + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + me.focus(); + } + buttons[0].focus(); + for (var i = 0; i < buttons.length; ++i) { + var b = buttons[i]; + (function (callback) { + CodeMirror.on(b, "click", function (e) { + CodeMirror.e_preventDefault(e); + close(); + if (callback) callback(me); + }); + })(callbacks[i]); + CodeMirror.on(b, "blur", function () { + --blurring; + setTimeout(function () { + if (blurring <= 0) close(); + }, 200); + }); + CodeMirror.on(b, "focus", function () { + ++blurring; + }); } - Object.keys(source).forEach(function (key) { - obj[key] = source[key]; + }); + CodeMirror.defineExtension("openNotification", function (template, options) { + closeNotification(this, close); + var dialog2 = dialogDiv(this, template, options && options.bottom); + var closed = false, + doneTimer; + var duration = options && typeof options.duration !== "undefined" ? options.duration : 5e3; + function close() { + if (closed) return; + closed = true; + clearTimeout(doneTimer); + CodeMirror.rmClass(dialog2.parentNode, "dialog-opened"); + dialog2.parentNode.removeChild(dialog2); + } + CodeMirror.on(dialog2, "click", function (e) { + CodeMirror.e_preventDefault(e); + close(); }); + if (duration) doneTimer = setTimeout(close, duration); + return close; }); - return obj; - } - function _class(obj) { - return Object.prototype.toString.call(obj); - } - function isString(obj) { - return _class(obj) === '[object String]'; - } - function isObject(obj) { - return _class(obj) === '[object Object]'; - } - function isRegExp(obj) { - return _class(obj) === '[object RegExp]'; - } - function isFunction(obj) { - return _class(obj) === '[object Function]'; - } - function escapeRE(str) { - return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); - } - - // - - const defaultOptions = { - fuzzyLink: true, - fuzzyEmail: true, - fuzzyIP: false - }; - function isOptionsObj(obj) { - return Object.keys(obj || {}).reduce(function (acc, k) { - /* eslint-disable-next-line no-prototype-builtins */ - return acc || defaultOptions.hasOwnProperty(k); - }, false); - } - const defaultSchemas = { - 'http:': { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.http) { - // compile lazily, because "host"-containing variables can change on tlds update. - self.re.http = new RegExp('^\\/\\/' + self.re.src_auth + self.re.src_host_port_strict + self.re.src_path, 'i'); - } - if (self.re.http.test(tail)) { - return tail.match(self.re.http)[0].length; + }); +})(); +var dialogExports = dialog$2.exports; +const dialog = /* @__PURE__ */codemirror.getDefaultExportFromCjs(dialogExports); +const dialog$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: dialog +}, [dialogExports]); +exports.dialog = dialog$1; +exports.dialogExports = dialogExports; + +/***/ }), + +/***/ "../../graphiql-react/dist/foldgutter.cjs.js": +/*!***************************************************!*\ + !*** ../../graphiql-react/dist/foldgutter.cjs.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } - return 0; } - }, - 'https:': 'http:', - 'ftp:': 'http:', - '//': { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.no_http) { - // compile lazily, because "host"-containing variables can change on tlds update. - self.re.no_http = new RegExp('^' + self.re.src_auth + - // Don't allow single-level domains, because of false positives like '//test' - // with code comments - '(?:localhost|(?:(?:' + self.re.src_domain + ')\\.)+' + self.re.src_domain_root + ')' + self.re.src_port + self.re.src_host_terminator + self.re.src_path, 'i'); - } - if (self.re.no_http.test(tail)) { - // should not be `://` & `///`, that protects from errors in protocol name - if (pos >= 3 && text[pos - 3] === ':') { - return 0; - } - if (pos >= 3 && text[pos - 3] === '/') { - return 0; + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var foldgutter$2 = { + exports: {} +}; +var foldcode = { + exports: {} +}; +var hasRequiredFoldcode; +function requireFoldcode() { + if (hasRequiredFoldcode) return foldcode.exports; + hasRequiredFoldcode = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + function doFold(cm, pos, options, force) { + if (options && options.call) { + var finder = options; + options = null; + } else { + var finder = getOption(cm, options, "rangeFinder"); + } + if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0); + var minSize = getOption(cm, options, "minFoldSize"); + function getRange(allowFolded) { + var range2 = finder(cm, pos); + if (!range2 || range2.to.line - range2.from.line < minSize) return null; + if (force === "fold") return range2; + var marks = cm.findMarksAt(range2.from); + for (var i = 0; i < marks.length; ++i) { + if (marks[i].__isFold) { + if (!allowFolded) return null; + range2.cleared = true; + marks[i].clear(); + } + } + return range2; + } + var range = getRange(true); + if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) { + pos = CodeMirror.Pos(pos.line - 1, 0); + range = getRange(false); + } + if (!range || range.cleared || force === "unfold") return; + var myWidget = makeWidget(cm, options, range); + CodeMirror.on(myWidget, "mousedown", function (e) { + myRange.clear(); + CodeMirror.e_preventDefault(e); + }); + var myRange = cm.markText(range.from, range.to, { + replacedWith: myWidget, + clearOnEnter: getOption(cm, options, "clearOnEnter"), + __isFold: true + }); + myRange.on("clear", function (from, to) { + CodeMirror.signal(cm, "unfold", cm, from, to); + }); + CodeMirror.signal(cm, "fold", cm, range.from, range.to); + } + function makeWidget(cm, options, range) { + var widget = getOption(cm, options, "widget"); + if (typeof widget == "function") { + widget = widget(range.from, range.to); + } + if (typeof widget == "string") { + var text = document.createTextNode(widget); + widget = document.createElement("span"); + widget.appendChild(text); + widget.className = "CodeMirror-foldmarker"; + } else if (widget) { + widget = widget.cloneNode(true); + } + return widget; + } + CodeMirror.newFoldFunction = function (rangeFinder, widget) { + return function (cm, pos) { + doFold(cm, pos, { + rangeFinder, + widget + }); + }; + }; + CodeMirror.defineExtension("foldCode", function (pos, options, force) { + doFold(this, pos, options, force); + }); + CodeMirror.defineExtension("isFolded", function (pos) { + var marks = this.findMarksAt(pos); + for (var i = 0; i < marks.length; ++i) if (marks[i].__isFold) return true; + }); + CodeMirror.commands.toggleFold = function (cm) { + cm.foldCode(cm.getCursor()); + }; + CodeMirror.commands.fold = function (cm) { + cm.foldCode(cm.getCursor(), null, "fold"); + }; + CodeMirror.commands.unfold = function (cm) { + cm.foldCode(cm.getCursor(), { + scanUp: false + }, "unfold"); + }; + CodeMirror.commands.foldAll = function (cm) { + cm.operation(function () { + for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { + scanUp: false + }, "fold"); + }); + }; + CodeMirror.commands.unfoldAll = function (cm) { + cm.operation(function () { + for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) cm.foldCode(CodeMirror.Pos(i, 0), { + scanUp: false + }, "unfold"); + }); + }; + CodeMirror.registerHelper("fold", "combine", function () { + var funcs = Array.prototype.slice.call(arguments, 0); + return function (cm, start) { + for (var i = 0; i < funcs.length; ++i) { + var found = funcs[i](cm, start); + if (found) return found; } - return tail.match(self.re.no_http)[0].length; + }; + }); + CodeMirror.registerHelper("fold", "auto", function (cm, start) { + var helpers = cm.getHelpers(start, "fold"); + for (var i = 0; i < helpers.length; i++) { + var cur = helpers[i](cm, start); + if (cur) return cur; } - return 0; + }); + var defaultOptions = { + rangeFinder: CodeMirror.fold.auto, + widget: "↔", + minFoldSize: 0, + scanUp: false, + clearOnEnter: true + }; + CodeMirror.defineOption("foldOptions", null); + function getOption(cm, options, name) { + if (options && options[name] !== void 0) return options[name]; + var editorOptions = cm.options.foldOptions; + if (editorOptions && editorOptions[name] !== void 0) return editorOptions[name]; + return defaultOptions[name]; + } + CodeMirror.defineExtension("foldOption", function (options, name) { + return getOption(this, options, name); + }); + }); + })(); + return foldcode.exports; +} +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), requireFoldcode()); + })(function (CodeMirror) { + CodeMirror.defineOption("foldGutter", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.clearGutter(cm.state.foldGutter.options.gutter); + cm.state.foldGutter = null; + cm.off("gutterClick", onGutterClick); + cm.off("changes", onChange); + cm.off("viewportChange", onViewportChange); + cm.off("fold", onFold); + cm.off("unfold", onFold); + cm.off("swapDoc", onChange); + } + if (val) { + cm.state.foldGutter = new State(parseOptions(val)); + updateInViewport(cm); + cm.on("gutterClick", onGutterClick); + cm.on("changes", onChange); + cm.on("viewportChange", onViewportChange); + cm.on("fold", onFold); + cm.on("unfold", onFold); + cm.on("swapDoc", onChange); } - }, - 'mailto:': { - validate: function (text, pos, self) { - const tail = text.slice(pos); - if (!self.re.mailto) { - self.re.mailto = new RegExp('^' + self.re.src_email_name + '@' + self.re.src_host_strict, 'i'); + }); + var Pos = CodeMirror.Pos; + function State(options) { + this.options = options; + this.from = this.to = 0; + } + function parseOptions(opts) { + if (opts === true) opts = {}; + if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; + if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; + if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; + return opts; + } + function isFolded(cm, line) { + var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); + for (var i = 0; i < marks.length; ++i) { + if (marks[i].__isFold) { + var fromPos = marks[i].find(-1); + if (fromPos && fromPos.line === line) return marks[i]; + } + } + } + function marker(spec) { + if (typeof spec == "string") { + var elt = document.createElement("div"); + elt.className = spec + " CodeMirror-guttermarker-subtle"; + return elt; + } else { + return spec.cloneNode(true); + } + } + function updateFoldInfo(cm, from, to) { + var opts = cm.state.foldGutter.options, + cur = from - 1; + var minSize = cm.foldOption(opts, "minFoldSize"); + var func = cm.foldOption(opts, "rangeFinder"); + var clsFolded = typeof opts.indicatorFolded == "string" && classTest(opts.indicatorFolded); + var clsOpen = typeof opts.indicatorOpen == "string" && classTest(opts.indicatorOpen); + cm.eachLine(from, to, function (line) { + ++cur; + var mark = null; + var old = line.gutterMarkers; + if (old) old = old[opts.gutter]; + if (isFolded(cm, cur)) { + if (clsFolded && old && clsFolded.test(old.className)) return; + mark = marker(opts.indicatorFolded); + } else { + var pos = Pos(cur, 0); + var range = func && func(cm, pos); + if (range && range.to.line - range.from.line >= minSize) { + if (clsOpen && old && clsOpen.test(old.className)) return; + mark = marker(opts.indicatorOpen); + } } - if (self.re.mailto.test(tail)) { - return tail.match(self.re.mailto)[0].length; + if (!mark && !old) return; + cm.setGutterMarker(line, opts.gutter, mark); + }); + } + function classTest(cls) { + return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); + } + function updateInViewport(cm) { + var vp = cm.getViewport(), + state = cm.state.foldGutter; + if (!state) return; + cm.operation(function () { + updateFoldInfo(cm, vp.from, vp.to); + }); + state.from = vp.from; + state.to = vp.to; + } + function onGutterClick(cm, line, gutter) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + if (gutter != opts.gutter) return; + var folded = isFolded(cm, line); + if (folded) folded.clear();else cm.foldCode(Pos(line, 0), opts); + } + function onChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + state.from = state.to = 0; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function () { + updateInViewport(cm); + }, opts.foldOnChangeTimeSpan || 600); + } + function onViewportChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function () { + var vp = cm.getViewport(); + if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { + updateInViewport(cm); + } else { + cm.operation(function () { + if (vp.from < state.from) { + updateFoldInfo(cm, vp.from, state.from); + state.from = vp.from; + } + if (vp.to > state.to) { + updateFoldInfo(cm, state.to, vp.to); + state.to = vp.to; + } + }); } - return 0; - } + }, opts.updateViewportTimeSpan || 400); } - }; - - // RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) - /* eslint-disable-next-line max-len */ - const tlds_2ch_src_re = 'a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]'; - - // DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead - const tlds_default = 'biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф'.split('|'); - function resetScanCache(self) { - self.__index__ = -1; - self.__text_cache__ = ''; - } - function createValidator(re) { - return function (text, pos) { - const tail = text.slice(pos); - if (re.test(tail)) { - return tail.match(re)[0].length; - } - return 0; - }; + function onFold(cm, from) { + var state = cm.state.foldGutter; + if (!state) return; + var line = from.line; + if (line >= state.from && line < state.to) updateFoldInfo(cm, line, line + 1); + } + }); +})(); +var foldgutterExports = foldgutter$2.exports; +const foldgutter = /* @__PURE__ */codemirror.getDefaultExportFromCjs(foldgutterExports); +const foldgutter$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: foldgutter +}, [foldgutterExports]); +exports.foldgutter = foldgutter$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/forEachState.cjs.js": +/*!*****************************************************!*\ + !*** ../../graphiql-react/dist/forEachState.cjs.js ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +function forEachState(stack, fn) { + const reverseStateStack = []; + let state = stack; + while (state === null || state === void 0 ? void 0 : state.kind) { + reverseStateStack.push(state); + state = state.prevState; + } + for (let i = reverseStateStack.length - 1; i >= 0; i--) { + fn(reverseStateStack[i]); + } +} +exports.forEachState = forEachState; + +/***/ }), + +/***/ "../../graphiql-react/dist/hint.cjs.js": +/*!*********************************************!*\ + !*** ../../graphiql-react/dist/hint.cjs.js ***! + \*********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +__webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js"); +const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); +codemirror.CodeMirror.registerHelper("hint", "graphql", (editor, options) => { + const { + schema, + externalFragments, + autocompleteOptions + } = options; + if (!schema) { + return; } - function createNormalizer() { - return function (match, self) { - self.normalize(match); - }; + const cur = editor.getCursor(); + const token = editor.getTokenAt(cur); + const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; + const position = new graphqlLanguageService.Position(cur.line, tokenStart); + const rawResults = graphqlLanguageService.getAutocompleteSuggestions(schema, editor.getValue(), position, token, externalFragments, autocompleteOptions); + const results = { + list: rawResults.map(item => { + var _a; + return { + text: (_a = item === null || item === void 0 ? void 0 : item.rawInsert) !== null && _a !== void 0 ? _a : item.label, + type: item.type, + description: item.documentation, + isDeprecated: item.isDeprecated, + deprecationReason: item.deprecationReason + }; + }), + from: { + line: cur.line, + ch: tokenStart + }, + to: { + line: cur.line, + ch: token.end + } + }; + if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { + results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); + results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); + codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); } - - // Schemas compiler. Build regexps. - // - function compile(self) { - // Load & clone RE patterns. - const re = self.re = reFactory(self.__opts__); - - // Define dynamic patterns - const tlds = self.__tlds__.slice(); - self.onCompile(); - if (!self.__tlds_replaced__) { - tlds.push(tlds_2ch_src_re); - } - tlds.push(re.src_xn); - re.src_tlds = tlds.join('|'); - function untpl(tpl) { - return tpl.replace('%TLDS%', re.src_tlds); - } - re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i'); - re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i'); - re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i'); - re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i'); - - // - // Compile each schema - // - - const aliases = []; - self.__compiled__ = {}; // Reset compiled data - - function schemaError(name, val) { - throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val); + return results; +}); + +/***/ }), + +/***/ "../../graphiql-react/dist/hint.cjs2.js": +/*!**********************************************!*\ + !*** ../../graphiql-react/dist/hint.cjs2.js ***! + \**********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const forEachState = __webpack_require__(/*! ./forEachState.cjs.js */ "../../graphiql-react/dist/forEachState.cjs.js"); +function hintList(cursor, token, list) { + const hints = filterAndSortList(list, normalizeText(token.string)); + if (!hints) { + return; + } + const tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end; + return { + list: hints, + from: { + line: cursor.line, + ch: tokenStart + }, + to: { + line: cursor.line, + ch: token.end } - Object.keys(self.__schemas__).forEach(function (name) { - const val = self.__schemas__[name]; - - // skip disabled methods - if (val === null) { - return; - } - const compiled = { - validate: null, - link: null - }; - self.__compiled__[name] = compiled; - if (isObject(val)) { - if (isRegExp(val.validate)) { - compiled.validate = createValidator(val.validate); - } else if (isFunction(val.validate)) { - compiled.validate = val.validate; - } else { - schemaError(name, val); - } - if (isFunction(val.normalize)) { - compiled.normalize = val.normalize; - } else if (!val.normalize) { - compiled.normalize = createNormalizer(); - } else { - schemaError(name, val); - } - return; - } - if (isString(val)) { - aliases.push(name); - return; - } - schemaError(name, val); - }); - - // - // Compile postponed aliases - // - - aliases.forEach(function (alias) { - if (!self.__compiled__[self.__schemas__[alias]]) { - // Silently fail on missed schemas to avoid errons on disable. - // schemaError(alias, self.__schemas__[alias]); - return; - } - self.__compiled__[alias].validate = self.__compiled__[self.__schemas__[alias]].validate; - self.__compiled__[alias].normalize = self.__compiled__[self.__schemas__[alias]].normalize; - }); - - // - // Fake record for guessed links - // - self.__compiled__[''] = { - validate: null, - normalize: createNormalizer() - }; - - // - // Build schema condition - // - const slist = Object.keys(self.__compiled__).filter(function (name) { - // Filter disabled & fake schemas - return name.length > 0 && self.__compiled__[name]; - }).map(escapeRE).join('|'); - // (?!_) cause 1.5x slowdown - self.re.schema_test = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i'); - self.re.schema_search = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig'); - self.re.schema_at_start = RegExp('^' + self.re.schema_search.source, 'i'); - self.re.pretest = RegExp('(' + self.re.schema_test.source + ')|(' + self.re.host_fuzzy_test.source + ')|@', 'i'); - - // - // Cleanup - // - - resetScanCache(self); + }; +} +function filterAndSortList(list, text) { + if (!text) { + return filterNonEmpty(list, entry => !entry.isDeprecated); + } + const byProximity = list.map(entry => ({ + proximity: getProximity(normalizeText(entry.text), text), + entry + })); + const conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated); + const sortedMatches = conciseMatches.sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.text.length - b.entry.text.length); + return sortedMatches.map(pair => pair.entry); +} +function filterNonEmpty(array, predicate) { + const filtered = array.filter(predicate); + return filtered.length === 0 ? array : filtered; +} +function normalizeText(text) { + return text.toLowerCase().replaceAll(/\W/g, ""); +} +function getProximity(suggestion, text) { + let proximity = lexicalDistance(text, suggestion); + if (suggestion.length > text.length) { + proximity -= suggestion.length - text.length - 1; + proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + } + return proximity; +} +function lexicalDistance(a, b) { + let i; + let j; + const d = []; + const aLength = a.length; + const bLength = b.length; + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + return d[aLength][bLength]; +} +codemirror.CodeMirror.registerHelper("hint", "graphql-variables", (editor, options) => { + const cur = editor.getCursor(); + const token = editor.getTokenAt(cur); + const results = getVariablesHint(cur, token, options); + if ((results === null || results === void 0 ? void 0 : results.list) && results.list.length > 0) { + results.from = codemirror.CodeMirror.Pos(results.from.line, results.from.ch); + results.to = codemirror.CodeMirror.Pos(results.to.line, results.to.ch); + codemirror.CodeMirror.signal(editor, "hasCompletion", editor, results, token); + } + return results; +}); +function getVariablesHint(cur, token, options) { + const state = token.state.kind === "Invalid" ? token.state.prevState : token.state; + const { + kind, + step + } = state; + if (kind === "Document" && step === 0) { + return hintList(cur, token, [{ + text: "{" + }]); } - - /** - * class Match - * - * Match result. Single element of array, returned by [[LinkifyIt#match]] - **/ - function Match(self, shift) { - const start = self.__index__; - const end = self.__last_index__; - const text = self.__text_cache__.slice(start, end); - - /** - * Match#schema -> String - * - * Prefix (protocol) for matched string. - **/ - this.schema = self.__schema__.toLowerCase(); - /** - * Match#index -> Number - * - * First position of matched string. - **/ - this.index = start + shift; - /** - * Match#lastIndex -> Number - * - * Next position after matched string. - **/ - this.lastIndex = end + shift; - /** - * Match#raw -> String - * - * Matched string. - **/ - this.raw = text; - /** - * Match#text -> String - * - * Notmalized text of matched string. - **/ - this.text = text; - /** - * Match#url -> String - * - * Normalized url of matched string. - **/ - this.url = text; + const { + variableToType + } = options; + if (!variableToType) { + return; } - function createMatch(self, shift) { - const match = new Match(self, shift); - self.__compiled__[match.schema].normalize(match, self); - return match; + const typeInfo = getTypeInfo(variableToType, token.state); + if (kind === "Document" || kind === "Variable" && step === 0) { + const variableNames = Object.keys(variableToType); + return hintList(cur, token, variableNames.map(name => ({ + text: `"${name}": `, + type: variableToType[name] + }))); } - - /** - * class LinkifyIt - **/ - - /** - * new LinkifyIt(schemas, options) - * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) - * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } - * - * Creates new linkifier instance with optional additional schemas. - * Can be called without `new` keyword for convenience. - * - * By default understands: - * - * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links - * - "fuzzy" links and emails (example.com, foo@bar.com). - * - * `schemas` is an object, where each key/value describes protocol/rule: - * - * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` - * for example). `linkify-it` makes shure that prefix is not preceeded with - * alphanumeric char and symbols. Only whitespaces and punctuation allowed. - * - __value__ - rule to check tail after link prefix - * - _String_ - just alias to existing rule - * - _Object_ - * - _validate_ - validator function (should return matched length on success), - * or `RegExp`. - * - _normalize_ - optional function to normalize text & url of matched result - * (for example, for @twitter mentions). - * - * `options`: - * - * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. - * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts - * like version numbers. Default `false`. - * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. - * - **/ - function LinkifyIt(schemas, options) { - if (!(this instanceof LinkifyIt)) { - return new LinkifyIt(schemas, options); + if ((kind === "ObjectValue" || kind === "ObjectField" && step === 0) && typeInfo.fields) { + const inputFields = Object.keys(typeInfo.fields).map(fieldName => typeInfo.fields[fieldName]); + return hintList(cur, token, inputFields.map(field => ({ + text: `"${field.name}": `, + type: field.type, + description: field.description + }))); + } + if (kind === "StringValue" || kind === "NumberValue" || kind === "BooleanValue" || kind === "NullValue" || kind === "ListValue" && step === 1 || kind === "ObjectField" && step === 2 || kind === "Variable" && step === 2) { + const namedInputType = typeInfo.type ? graphql.getNamedType(typeInfo.type) : void 0; + if (namedInputType instanceof graphql.GraphQLInputObjectType) { + return hintList(cur, token, [{ + text: "{" + }]); } - if (!options) { - if (isOptionsObj(schemas)) { - options = schemas; - schemas = {}; - } + if (namedInputType instanceof graphql.GraphQLEnumType) { + const values = namedInputType.getValues(); + return hintList(cur, token, values.map(value => ({ + text: `"${value.name}"`, + type: namedInputType, + description: value.description + }))); + } + if (namedInputType === graphql.GraphQLBoolean) { + return hintList(cur, token, [{ + text: "true", + type: graphql.GraphQLBoolean, + description: "Not false." + }, { + text: "false", + type: graphql.GraphQLBoolean, + description: "Not true." + }]); } - this.__opts__ = assign({}, defaultOptions, options); - - // Cache last tested result. Used to skip repeating steps on next `match` call. - this.__index__ = -1; - this.__last_index__ = -1; // Next scan position - this.__schema__ = ''; - this.__text_cache__ = ''; - this.__schemas__ = assign({}, defaultSchemas, schemas); - this.__compiled__ = {}; - this.__tlds__ = tlds_default; - this.__tlds_replaced__ = false; - this.re = {}; - compile(this); } - - /** chainable - * LinkifyIt#add(schema, definition) - * - schema (String): rule name (fixed pattern prefix) - * - definition (String|RegExp|Object): schema definition - * - * Add new rule definition. See constructor description for details. - **/ - LinkifyIt.prototype.add = function add(schema, definition) { - this.__schemas__[schema] = definition; - compile(this); - return this; - }; - - /** chainable - * LinkifyIt#set(options) - * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } - * - * Set recognition options for links without schema. - **/ - LinkifyIt.prototype.set = function set(options) { - this.__opts__ = assign(this.__opts__, options); - return this; +} +function getTypeInfo(variableToType, tokenState) { + const info = { + type: null, + fields: null }; - - /** - * LinkifyIt#test(text) -> Boolean - * - * Searches linkifiable pattern and returns `true` on success or `false` on fail. - **/ - LinkifyIt.prototype.test = function test(text) { - // Reset scan cache - this.__text_cache__ = text; - this.__index__ = -1; - if (!text.length) { - return false; - } - let m, ml, me, len, shift, next, re, tld_pos, at_pos; - - // try to scan for link with schema - that's the most simple rule - if (this.re.schema_test.test(text)) { - re = this.re.schema_search; - re.lastIndex = 0; - while ((m = re.exec(text)) !== null) { - len = this.testSchemaAt(text, m[2], re.lastIndex); - if (len) { - this.__schema__ = m[2]; - this.__index__ = m.index + m[1].length; - this.__last_index__ = m.index + m[0].length + len; + forEachState.forEachState(tokenState, state => { + switch (state.kind) { + case "Variable": + { + info.type = variableToType[state.name]; break; } - } - } - if (this.__opts__.fuzzyLink && this.__compiled__['http:']) { - // guess schemaless links - tld_pos = text.search(this.re.host_fuzzy_test); - if (tld_pos >= 0) { - // if tld is located after found link - no need to check fuzzy pattern - if (this.__index__ < 0 || tld_pos < this.__index__) { - if ((ml = text.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) { - shift = ml.index + ml[1].length; - if (this.__index__ < 0 || shift < this.__index__) { - this.__schema__ = ''; - this.__index__ = shift; - this.__last_index__ = ml.index + ml[0].length; - } - } + case "ListValue": + { + const nullableType = info.type ? graphql.getNullableType(info.type) : void 0; + info.type = nullableType instanceof graphql.GraphQLList ? nullableType.ofType : null; + break; } - } - } - if (this.__opts__.fuzzyEmail && this.__compiled__['mailto:']) { - // guess schemaless emails - at_pos = text.indexOf('@'); - if (at_pos >= 0) { - // We can't skip this check, because this cases are possible: - // 192.168.1.1@gmail.com, my.in@example.com - if ((me = text.match(this.re.email_fuzzy)) !== null) { - shift = me.index + me[1].length; - next = me.index + me[0].length; - if (this.__index__ < 0 || shift < this.__index__ || shift === this.__index__ && next > this.__last_index__) { - this.__schema__ = 'mailto:'; - this.__index__ = shift; - this.__last_index__ = next; - } + case "ObjectValue": + { + const objectType = info.type ? graphql.getNamedType(info.type) : void 0; + info.fields = objectType instanceof graphql.GraphQLInputObjectType ? objectType.getFields() : null; + break; + } + case "ObjectField": + { + const objectField = state.name && info.fields ? info.fields[state.name] : null; + info.type = objectField === null || objectField === void 0 ? void 0 : objectField.type; + break; } - } } - return this.__index__ >= 0; - }; - - /** - * LinkifyIt#pretest(text) -> Boolean - * - * Very quick check, that can give false positives. Returns true if link MAY BE - * can exists. Can be used for speed optimization, when you need to check that - * link NOT exists. - **/ - LinkifyIt.prototype.pretest = function pretest(text) { - return this.re.pretest.test(text); - }; - - /** - * LinkifyIt#testSchemaAt(text, name, position) -> Number - * - text (String): text to scan - * - name (String): rule (schema) name - * - position (Number): text offset to check from - * - * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly - * at given position. Returns length of found pattern (0 on fail). - **/ - LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text, schema, pos) { - // If not supported schema check requested - terminate - if (!this.__compiled__[schema.toLowerCase()]) { - return 0; + }); + return info; +} + +/***/ }), + +/***/ "../../graphiql-react/dist/index.js": +/*!******************************************!*\ + !*** ../../graphiql-react/dist/index.js ***! + \******************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, Symbol.toStringTag, { + value: "Module" +}); +const jsxRuntime = __webpack_require__(/*! react/jsx-runtime */ "../../../node_modules/react/jsx-runtime.js"); +const React = __webpack_require__(/*! react */ "react"); +const clsx = __webpack_require__(/*! clsx */ "../../../node_modules/clsx/dist/clsx.m.js"); +const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const toolkit = __webpack_require__(/*! @graphiql/toolkit */ "../../graphiql-toolkit/esm/index.js"); +const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); +const setValue = __webpack_require__(/*! set-value */ "../../../node_modules/set-value/index.js"); +const copyToClipboard = __webpack_require__(/*! copy-to-clipboard */ "../../../node_modules/copy-to-clipboard/index.js"); +const D = __webpack_require__(/*! @radix-ui/react-dialog */ "../../../node_modules/@radix-ui/react-dialog/dist/index.js"); +const reactVisuallyHidden = __webpack_require__(/*! @radix-ui/react-visually-hidden */ "../../../node_modules/@radix-ui/react-visually-hidden/dist/index.js"); +const reactDropdownMenu = __webpack_require__(/*! @radix-ui/react-dropdown-menu */ "../../../node_modules/@radix-ui/react-dropdown-menu/dist/index.js"); +const MarkdownIt = __webpack_require__(/*! markdown-it */ "../node_modules/markdown-it/dist/index.cjs.js"); +const framerMotion = __webpack_require__(/*! framer-motion */ "../../../node_modules/framer-motion/dist/cjs/index.js"); +const T = __webpack_require__(/*! @radix-ui/react-tooltip */ "../../../node_modules/@radix-ui/react-tooltip/dist/index.js"); +const react = __webpack_require__(/*! @headlessui/react */ "../../../node_modules/@headlessui/react/dist/index.cjs"); +const ReactDOM = __webpack_require__(/*! react-dom */ "react-dom"); +function _interopNamespaceDefault(e) { + const n = Object.create(null, { + [Symbol.toStringTag]: { + value: "Module" } - return this.__compiled__[schema.toLowerCase()].validate(text, pos, this); - }; - - /** - * LinkifyIt#match(text) -> Array|null - * - * Returns array of found link descriptions or `null` on fail. We strongly - * recommend to use [[LinkifyIt#test]] first, for best speed. - * - * ##### Result match description - * - * - __schema__ - link schema, can be empty for fuzzy links, or `//` for - * protocol-neutral links. - * - __index__ - offset of matched text - * - __lastIndex__ - index of next char after mathch end - * - __raw__ - matched text - * - __text__ - normalized text - * - __url__ - link, generated from matched text - **/ - LinkifyIt.prototype.match = function match(text) { - const result = []; - let shift = 0; - - // Try to take previous element from cache, if .test() called before - if (this.__index__ >= 0 && this.__text_cache__ === text) { - result.push(createMatch(this, shift)); - shift = this.__last_index__; + }); + if (e) { + for (const k in e) { + if (k !== "default") { + const d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } - - // Cut head if cache was used - let tail = shift ? text.slice(shift) : text; - - // Scan string until end reached - while (this.test(tail)) { - result.push(createMatch(this, shift)); - tail = tail.slice(this.__last_index__); - shift += this.__last_index__; + } + n.default = e; + return Object.freeze(n); +} +const React__namespace = /* @__PURE__ */_interopNamespaceDefault(React); +const D__namespace = /* @__PURE__ */_interopNamespaceDefault(D); +const T__namespace = /* @__PURE__ */_interopNamespaceDefault(T); +function createNullableContext(name) { + const context = React.createContext(null); + context.displayName = name; + return context; +} +function createContextHook(context) { + function useGivenContext(options) { + var _a; + const value = React.useContext(context); + if (value === null && (options == null ? void 0 : options.nonNull)) { + throw new Error(`Tried to use \`${((_a = options.caller) == null ? void 0 : _a.name) || useGivenContext.caller.name}\` without the necessary context. Make sure to render the \`${context.displayName}Provider\` component higher up the tree.`); } - if (result.length) { - return result; + return value; + } + Object.defineProperty(useGivenContext, "name", { + value: `use${context.displayName}` + }); + return useGivenContext; +} +const StorageContext = createNullableContext("StorageContext"); +function StorageContextProvider(props) { + const isInitialRender = React.useRef(true); + const [storage, setStorage] = React.useState(new toolkit.StorageAPI(props.storage)); + React.useEffect(() => { + if (isInitialRender.current) { + isInitialRender.current = false; + } else { + setStorage(new toolkit.StorageAPI(props.storage)); } - return null; - }; - - /** - * LinkifyIt#matchAtStart(text) -> Match|null - * - * Returns fully-formed (not fuzzy) link if it starts at the beginning - * of the string, and null otherwise. - **/ - LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { - // Reset scan cache - this.__text_cache__ = text; - this.__index__ = -1; - if (!text.length) return null; - const m = this.re.schema_at_start.exec(text); - if (!m) return null; - const len = this.testSchemaAt(text, m[2], m[0].length); - if (!len) return null; - this.__schema__ = m[2]; - this.__index__ = m.index + m[1].length; - this.__last_index__ = m.index + m[0].length + len; - return createMatch(this, 0); - }; - - /** chainable - * LinkifyIt#tlds(list [, keepOld]) -> this - * - list (Array): list of tlds - * - keepOld (Boolean): merge with current list if `true` (`false` by default) - * - * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) - * to avoid false positives. By default this algorythm used: - * - * - hostname with any 2-letter root zones are ok. - * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф - * are ok. - * - encoded (`xn--...`) root zones are ok. - * - * If list is replaced, then exact match for 2-chars root zones will be checked. - **/ - LinkifyIt.prototype.tlds = function tlds(list, keepOld) { - list = Array.isArray(list) ? list : [list]; - if (!keepOld) { - this.__tlds__ = list.slice(); - this.__tlds_replaced__ = true; - compile(this); - return this; + }, [props.storage]); + return /* @__PURE__ */jsxRuntime.jsx(StorageContext.Provider, { + value: storage, + children: props.children + }); +} +const useStorageContext = createContextHook(StorageContext); +const SvgArgument = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("rect", { + x: 6, + y: 6, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" +})); +const SvgChevronDown = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 9", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1 1L7 7L13 1", + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgChevronLeft = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 7 10", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M6 1.04819L2 5.04819L6 9.04819", + stroke: "currentColor", + strokeWidth: 1.75 +})); +const SvgChevronUp = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 9", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M13 8L7 2L1 8", + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgClose = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + stroke: "currentColor", + strokeWidth: 3, + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1 1L12.9998 12.9997" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M13 1L1.00079 13.0003" +})); +const SvgCopy = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "-2 -2 22 22", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.25 14.2105V15.235C11.25 16.3479 10.3479 17.25 9.23501 17.25H2.76499C1.65214 17.25 0.75 16.3479 0.75 15.235L0.75 8.76499C0.75 7.65214 1.65214 6.75 2.76499 6.75L3.78947 6.75", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("rect", { + x: 6.75, + y: 0.75, + width: 10.5, + height: 10.5, + rx: 2.2069, + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgDeprecatedArgument = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M5.0484 1.40838C6.12624 0.33054 7.87376 0.330541 8.9516 1.40838L12.5916 5.0484C13.6695 6.12624 13.6695 7.87376 12.5916 8.9516L8.9516 12.5916C7.87376 13.6695 6.12624 13.6695 5.0484 12.5916L1.40838 8.9516C0.33054 7.87376 0.330541 6.12624 1.40838 5.0484L5.0484 1.40838Z", + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M5 9L9 5", + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M5 5L9 9", + stroke: "currentColor", + strokeWidth: 1.2 +})); +const SvgDeprecatedEnumValue = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 8L8 4", + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 4L8 8", + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", + fill: "currentColor" +})); +const SvgDeprecatedField = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 10.8, + height: 10.8, + rx: 3.4, + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 8L8 4", + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 4L8 8", + stroke: "currentColor", + strokeWidth: 1.2 +})); +const SvgDirective = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0.5 12 12", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 7, + y: 5.5, + width: 2, + height: 2, + rx: 1, + transform: "rotate(90 7 5.5)", + fill: "currentColor" +}), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M10.8 9L10.8 9.5C10.8 10.4941 9.99411 11.3 9 11.3L3 11.3C2.00589 11.3 1.2 10.4941 1.2 9.5L1.2 9L-3.71547e-07 9L-3.93402e-07 9.5C-4.65826e-07 11.1569 1.34314 12.5 3 12.5L9 12.5C10.6569 12.5 12 11.1569 12 9.5L12 9L10.8 9ZM10.8 4L12 4L12 3.5C12 1.84315 10.6569 0.5 9 0.5L3 0.5C1.34315 0.5 -5.87117e-08 1.84315 -1.31135e-07 3.5L-1.5299e-07 4L1.2 4L1.2 3.5C1.2 2.50589 2.00589 1.7 3 1.7L9 1.7C9.99411 1.7 10.8 2.50589 10.8 3.5L10.8 4Z", + fill: "currentColor" +})); +const SvgDocsFilled = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 20 24", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H17.25C17.8023 0.75 18.25 1.19772 18.25 1.75V5.25", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H18.25C18.8023 5.25 19.25 5.69771 19.25 6.25V22.25C19.25 22.8023 18.8023 23.25 18.25 23.25H3C1.75736 23.25 0.75 22.2426 0.75 21V3Z", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M3 5.25C1.75736 5.25 0.75 4.24264 0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H3ZM13 11L6 11V12.5L13 12.5V11Z", + fill: "currentColor" +})); +const SvgDocs = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 20 24", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 3C0.75 4.24264 1.75736 5.25 3 5.25H17.25M0.75 3C0.75 1.75736 1.75736 0.75 3 0.75H16.25C16.8023 0.75 17.25 1.19772 17.25 1.75V5.25M0.75 3V21C0.75 22.2426 1.75736 23.25 3 23.25H18.25C18.8023 23.25 19.25 22.8023 19.25 22.25V6.25C19.25 5.69771 18.8023 5.25 18.25 5.25H17.25", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("line", { + x1: 13, + y1: 11.75, + x2: 6, + y2: 11.75, + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgEnumValue = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 5, + y: 5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" +}), /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M8.5 1.2H9C9.99411 1.2 10.8 2.00589 10.8 3V9C10.8 9.99411 9.99411 10.8 9 10.8H8.5V12H9C10.6569 12 12 10.6569 12 9V3C12 1.34315 10.6569 0 9 0H8.5V1.2ZM3.5 1.2V0H3C1.34315 0 0 1.34315 0 3V9C0 10.6569 1.34315 12 3 12H3.5V10.8H3C2.00589 10.8 1.2 9.99411 1.2 9V3C1.2 2.00589 2.00589 1.2 3 1.2H3.5Z", + fill: "currentColor" +})); +const SvgField = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 1.1, + width: 10.8, + height: 10.8, + rx: 2.4, + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("rect", { + x: 5, + y: 5.5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" +})); +const SvgHistory = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 24 20", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.59375 9.52344L4.87259 12.9944L8.07872 9.41249", + stroke: "currentColor", + strokeWidth: 1.5, + strokeLinecap: "square" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M13.75 5.25V10.75H18.75", + stroke: "currentColor", + strokeWidth: 1.5, + strokeLinecap: "square" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4.95427 11.9332C4.55457 10.0629 4.74441 8.11477 5.49765 6.35686C6.25089 4.59894 7.5305 3.11772 9.16034 2.11709C10.7902 1.11647 12.6901 0.645626 14.5986 0.769388C16.5071 0.893151 18.3303 1.60543 19.8172 2.80818C21.3042 4.01093 22.3818 5.64501 22.9017 7.48548C23.4216 9.32595 23.3582 11.2823 22.7203 13.0853C22.0824 14.8883 20.9013 16.4492 19.3396 17.5532C17.778 18.6572 15.9125 19.25 14 19.25", + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgImplements = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 12 12", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { + cx: 6, + cy: 6, + r: 5.4, + stroke: "currentColor", + strokeWidth: 1.2, + strokeDasharray: "4.241025 4.241025", + transform: "rotate(22.5)", + "transform-origin": "center" +}), /* @__PURE__ */React__namespace.createElement("circle", { + cx: 6, + cy: 6, + r: 1, + fill: "currentColor" +})); +const SvgKeyboardShortcut = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 19 18", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.5 14.5653C1.5 15.211 1.75652 15.8303 2.21314 16.2869C2.66975 16.7435 3.28905 17 3.9348 17C4.58054 17 5.19984 16.7435 5.65646 16.2869C6.11307 15.8303 6.36959 15.211 6.36959 14.5653V12.1305H3.9348C3.28905 12.1305 2.66975 12.387 2.21314 12.8437C1.75652 13.3003 1.5 13.9195 1.5 14.5653Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M3.9348 1.00063C3.28905 1.00063 2.66975 1.25715 2.21314 1.71375C1.75652 2.17035 1.5 2.78964 1.5 3.43537C1.5 4.0811 1.75652 4.70038 2.21314 5.15698C2.66975 5.61358 3.28905 5.8701 3.9348 5.8701H6.36959V3.43537C6.36959 2.78964 6.11307 2.17035 5.65646 1.71375C5.19984 1.25715 4.58054 1.00063 3.9348 1.00063Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M15.0652 12.1305H12.6304V14.5653C12.6304 15.0468 12.7732 15.5175 13.0407 15.9179C13.3083 16.3183 13.6885 16.6304 14.1334 16.8147C14.5783 16.9989 15.0679 17.0472 15.5402 16.9532C16.0125 16.8593 16.4464 16.6274 16.7869 16.2869C17.1274 15.9464 17.3593 15.5126 17.4532 15.0403C17.5472 14.568 17.4989 14.0784 17.3147 13.6335C17.1304 13.1886 16.8183 12.8084 16.4179 12.5409C16.0175 12.2733 15.5468 12.1305 15.0652 12.1305Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M12.6318 5.86775H6.36955V12.1285H12.6318V5.86775Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M17.5 3.43473C17.5 2.789 17.2435 2.16972 16.7869 1.71312C16.3303 1.25652 15.711 1 15.0652 1C14.4195 1 13.8002 1.25652 13.3435 1.71312C12.8869 2.16972 12.6304 2.789 12.6304 3.43473V5.86946H15.0652C15.711 5.86946 16.3303 5.61295 16.7869 5.15635C17.2435 4.69975 17.5 4.08046 17.5 3.43473Z", + stroke: "currentColor", + strokeWidth: 1.125, + strokeLinecap: "round", + strokeLinejoin: "round" +})); +const SvgMagnifyingGlass = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("circle", { + cx: 5, + cy: 5, + r: 4.35, + stroke: "currentColor", + strokeWidth: 1.3 +}), /* @__PURE__ */React__namespace.createElement("line", { + x1: 8.45962, + y1: 8.54038, + x2: 11.7525, + y2: 11.8333, + stroke: "currentColor", + strokeWidth: 1.3 +})); +const SvgMerge = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "-2 -2 22 22", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M17.2492 6V2.9569C17.2492 1.73806 16.2611 0.75 15.0423 0.75L2.9569 0.75C1.73806 0.75 0.75 1.73806 0.75 2.9569L0.75 6", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.749873 12V15.0431C0.749873 16.2619 1.73794 17.25 2.95677 17.25H15.0421C16.261 17.25 17.249 16.2619 17.249 15.0431V12", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M6 4.5L9 7.5L12 4.5", + stroke: "currentColor", + strokeWidth: 1.5 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M12 13.5L9 10.5L6 13.5", + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgPen = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M0.75 13.25L0.0554307 12.967C-0.0593528 13.2488 0.00743073 13.5719 0.224488 13.7851C0.441545 13.9983 0.765869 14.0592 1.04549 13.9393L0.75 13.25ZM12.8214 1.83253L12.2911 2.36286L12.2911 2.36286L12.8214 1.83253ZM12.8214 3.90194L13.3517 4.43227L12.8214 3.90194ZM10.0981 1.17859L9.56773 0.648259L10.0981 1.17859ZM12.1675 1.17859L12.6978 0.648258L12.6978 0.648257L12.1675 1.17859ZM2.58049 8.75697L3.27506 9.03994L2.58049 8.75697ZM2.70066 8.57599L3.23099 9.10632L2.70066 8.57599ZM5.2479 11.4195L4.95355 10.7297L5.2479 11.4195ZM5.42036 11.303L4.89003 10.7727L5.42036 11.303ZM4.95355 10.7297C4.08882 11.0987 3.41842 11.362 2.73535 11.6308C2.05146 11.9 1.35588 12.1743 0.454511 12.5607L1.04549 13.9393C1.92476 13.5624 2.60256 13.2951 3.28469 13.0266C3.96762 12.7578 4.65585 12.4876 5.54225 12.1093L4.95355 10.7297ZM1.44457 13.533L3.27506 9.03994L1.88592 8.474L0.0554307 12.967L1.44457 13.533ZM3.23099 9.10632L10.6284 1.70892L9.56773 0.648259L2.17033 8.04566L3.23099 9.10632ZM11.6371 1.70892L12.2911 2.36286L13.3517 1.3022L12.6978 0.648258L11.6371 1.70892ZM12.2911 3.37161L4.89003 10.7727L5.95069 11.8333L13.3517 4.43227L12.2911 3.37161ZM12.2911 2.36286C12.5696 2.64142 12.5696 3.09305 12.2911 3.37161L13.3517 4.43227C14.2161 3.56792 14.2161 2.16654 13.3517 1.3022L12.2911 2.36286ZM10.6284 1.70892C10.9069 1.43036 11.3586 1.43036 11.6371 1.70892L12.6978 0.648257C11.8335 -0.216088 10.4321 -0.216084 9.56773 0.648259L10.6284 1.70892ZM3.27506 9.03994C3.26494 9.06479 3.24996 9.08735 3.23099 9.10632L2.17033 8.04566C2.04793 8.16806 1.95123 8.31369 1.88592 8.474L3.27506 9.03994ZM5.54225 12.1093C5.69431 12.0444 5.83339 11.9506 5.95069 11.8333L4.89003 10.7727C4.90863 10.7541 4.92988 10.7398 4.95355 10.7297L5.54225 12.1093Z", + fill: "currentColor" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.5 4.5L9.5 2.5", + stroke: "currentColor", + strokeWidth: 1.4026, + strokeLinecap: "round", + strokeLinejoin: "round" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M5.5 10.5L3.5 8.5", + stroke: "currentColor", + strokeWidth: 1.4026, + strokeLinecap: "round", + strokeLinejoin: "round" +})); +const SvgPlay = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 16 18", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.32226e-07 1.6609C7.22332e-08 0.907329 0.801887 0.424528 1.46789 0.777117L15.3306 8.11621C16.0401 8.49182 16.0401 9.50818 15.3306 9.88379L1.46789 17.2229C0.801886 17.5755 1.36076e-06 17.0927 1.30077e-06 16.3391L1.32226e-07 1.6609Z", + fill: "currentColor" +})); +const SvgPlus = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 10 16", + fill: "currentColor", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M4.25 9.25V13.5H5.75V9.25L10 9.25V7.75L5.75 7.75V3.5H4.25V7.75L0 7.75V9.25L4.25 9.25Z" +})); +const SvgPrettify = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + width: 25, + height: 25, + viewBox: "0 0 25 25", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M10.2852 24.0745L13.7139 18.0742", + stroke: "currentColor", + strokeWidth: 1.5625 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M14.5742 24.0749L17.1457 19.7891", + stroke: "currentColor", + strokeWidth: 1.5625 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M19.4868 24.0735L20.7229 21.7523C21.3259 20.6143 21.5457 19.3122 21.3496 18.0394C21.1535 16.7666 20.5519 15.591 19.6342 14.6874L23.7984 6.87853C24.0123 6.47728 24.0581 6.00748 23.9256 5.57249C23.7932 5.1375 23.4933 4.77294 23.0921 4.55901C22.6908 4.34509 22.221 4.29932 21.7861 4.43178C21.3511 4.56424 20.9865 4.86408 20.7726 5.26533L16.6084 13.0742C15.3474 12.8142 14.0362 12.9683 12.8699 13.5135C11.7035 14.0586 10.7443 14.9658 10.135 16.1L6 24.0735", + stroke: "currentColor", + strokeWidth: 1.5625 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4 15L5 13L7 12L5 11L4 9L3 11L1 12L3 13L4 15Z", + stroke: "currentColor", + strokeWidth: 1.5625, + strokeLinejoin: "round" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.5 8L12.6662 5.6662L15 4.5L12.6662 3.3338L11.5 1L10.3338 3.3338L8 4.5L10.3338 5.6662L11.5 8Z", + stroke: "currentColor", + strokeWidth: 1.5625, + strokeLinejoin: "round" +})); +const SvgReload = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 16 16", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M4.75 9.25H1.25V12.75", + stroke: "currentColor", + strokeWidth: 1, + strokeLinecap: "square" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M11.25 6.75H14.75V3.25", + stroke: "currentColor", + strokeWidth: 1, + strokeLinecap: "square" +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M14.1036 6.65539C13.8 5.27698 13.0387 4.04193 11.9437 3.15131C10.8487 2.26069 9.48447 1.76694 8.0731 1.75043C6.66173 1.73392 5.28633 2.19563 4.17079 3.0604C3.05526 3.92516 2.26529 5.14206 1.92947 6.513", + stroke: "currentColor", + strokeWidth: 1 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M1.89635 9.34461C2.20001 10.723 2.96131 11.9581 4.05631 12.8487C5.15131 13.7393 6.51553 14.2331 7.9269 14.2496C9.33827 14.2661 10.7137 13.8044 11.8292 12.9396C12.9447 12.0748 13.7347 10.8579 14.0705 9.487", + stroke: "currentColor", + strokeWidth: 1 +})); +const SvgRootType = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 11.8, + height: 11.8, + rx: 5.9, + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("path", { + d: "M4.25 7.5C4.25 6 5.75 5 6.5 6.5C7.25 8 8.75 7 8.75 5.5", + stroke: "currentColor", + strokeWidth: 1.2 +})); +const SvgSettings = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 21 20", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + fillRule: "evenodd", + clipRule: "evenodd", + d: "M9.29186 1.92702C9.06924 1.82745 8.87014 1.68202 8.70757 1.50024L7.86631 0.574931C7.62496 0.309957 7.30773 0.12592 6.95791 0.0479385C6.60809 -0.0300431 6.24274 0.00182978 5.91171 0.139208C5.58068 0.276585 5.3001 0.512774 5.10828 0.815537C4.91645 1.1183 4.82272 1.47288 4.83989 1.83089L4.90388 3.08019C4.91612 3.32348 4.87721 3.56662 4.78968 3.79394C4.70215 4.02126 4.56794 4.2277 4.39571 4.39994C4.22347 4.57219 4.01704 4.7064 3.78974 4.79394C3.56243 4.88147 3.3193 4.92038 3.07603 4.90814L1.8308 4.84414C1.47162 4.82563 1.11553 4.91881 0.811445 5.11086C0.507359 5.30292 0.270203 5.58443 0.132561 5.91671C-0.00508149 6.249 -0.0364554 6.61576 0.0427496 6.9666C0.121955 7.31744 0.307852 7.63514 0.5749 7.87606L1.50016 8.71204C1.68193 8.87461 1.82735 9.07373 1.92692 9.29636C2.02648 9.51898 2.07794 9.76012 2.07794 10.004C2.07794 10.2479 2.02648 10.489 1.92692 10.7116C1.82735 10.9343 1.68193 11.1334 1.50016 11.296L0.5749 12.1319C0.309856 12.3729 0.125575 12.6898 0.0471809 13.0393C-0.0312128 13.3888 9.64098e-05 13.754 0.13684 14.0851C0.273583 14.4162 0.509106 14.6971 0.811296 14.8894C1.11349 15.0817 1.46764 15.1762 1.82546 15.1599L3.0707 15.0959C3.31397 15.0836 3.5571 15.1225 3.7844 15.2101C4.01171 15.2976 4.21814 15.4318 4.39037 15.6041C4.56261 15.7763 4.69682 15.9827 4.78435 16.2101C4.87188 16.4374 4.91078 16.6805 4.89855 16.9238L4.83455 18.1691C4.81605 18.5283 4.90921 18.8844 5.10126 19.1885C5.2933 19.4926 5.5748 19.7298 5.90707 19.8674C6.23934 20.0051 6.60608 20.0365 6.9569 19.9572C7.30772 19.878 7.6254 19.6921 7.86631 19.4251L8.7129 18.4998C8.87547 18.318 9.07458 18.1725 9.29719 18.073C9.51981 17.9734 9.76093 17.9219 10.0048 17.9219C10.2487 17.9219 10.4898 17.9734 10.7124 18.073C10.935 18.1725 11.1341 18.318 11.2967 18.4998L12.1326 19.4251C12.3735 19.6921 12.6912 19.878 13.042 19.9572C13.3929 20.0365 13.7596 20.0051 14.0919 19.8674C14.4241 19.7298 14.7056 19.4926 14.8977 19.1885C15.0897 18.8844 15.1829 18.5283 15.1644 18.1691L15.1004 16.9238C15.0882 16.6805 15.1271 16.4374 15.2146 16.2101C15.3021 15.9827 15.4363 15.7763 15.6086 15.6041C15.7808 15.4318 15.9872 15.2976 16.2145 15.2101C16.4418 15.1225 16.685 15.0836 16.9282 15.0959L18.1735 15.1599C18.5326 15.1784 18.8887 15.0852 19.1928 14.8931C19.4969 14.7011 19.7341 14.4196 19.8717 14.0873C20.0093 13.755 20.0407 13.3882 19.9615 13.0374C19.8823 12.6866 19.6964 12.3689 19.4294 12.1279L18.5041 11.292C18.3223 11.1294 18.1769 10.9303 18.0774 10.7076C17.9778 10.485 17.9263 10.2439 17.9263 10C17.9263 9.75612 17.9778 9.51499 18.0774 9.29236C18.1769 9.06973 18.3223 8.87062 18.5041 8.70804L19.4294 7.87206C19.6964 7.63114 19.8823 7.31344 19.9615 6.9626C20.0407 6.61176 20.0093 6.245 19.8717 5.91271C19.7341 5.58043 19.4969 5.29892 19.1928 5.10686C18.8887 4.91481 18.5326 4.82163 18.1735 4.84014L16.9282 4.90414C16.685 4.91638 16.4418 4.87747 16.2145 4.78994C15.9872 4.7024 15.7808 4.56818 15.6086 4.39594C15.4363 4.2237 15.3021 4.01726 15.2146 3.78994C15.1271 3.56262 15.0882 3.31948 15.1004 3.07619L15.1644 1.83089C15.1829 1.4717 15.0897 1.11559 14.8977 0.811487C14.7056 0.507385 14.4241 0.270217 14.0919 0.132568C13.7596 -0.00508182 13.3929 -0.0364573 13.042 0.0427519C12.6912 0.121961 12.3735 0.307869 12.1326 0.574931L11.2914 1.50024C11.1288 1.68202 10.9297 1.82745 10.7071 1.92702C10.4845 2.02659 10.2433 2.07805 9.99947 2.07805C9.7556 2.07805 9.51448 2.02659 9.29186 1.92702ZM14.3745 10C14.3745 12.4162 12.4159 14.375 9.99977 14.375C7.58365 14.375 5.625 12.4162 5.625 10C5.625 7.58375 7.58365 5.625 9.99977 5.625C12.4159 5.625 14.3745 7.58375 14.3745 10Z", + fill: "currentColor" +})); +const SvgStarFilled = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", + fill: "currentColor", + stroke: "currentColor" +})); +const SvgStar = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 14 14", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M6.5782 1.07092C6.71096 0.643026 7.28904 0.643027 7.4218 1.07092L8.59318 4.84622C8.65255 5.03758 8.82284 5.16714 9.01498 5.16714L12.8056 5.16714C13.2353 5.16714 13.4139 5.74287 13.0663 6.00732L9.99962 8.34058C9.84418 8.45885 9.77913 8.66848 9.83851 8.85984L11.0099 12.6351C11.1426 13.063 10.675 13.4189 10.3274 13.1544L7.26069 10.8211C7.10524 10.7029 6.89476 10.7029 6.73931 10.8211L3.6726 13.1544C3.32502 13.4189 2.85735 13.063 2.99012 12.6351L4.16149 8.85984C4.22087 8.66848 4.15582 8.45885 4.00038 8.34058L0.933671 6.00732C0.586087 5.74287 0.764722 5.16714 1.19436 5.16714L4.98502 5.16714C5.17716 5.16714 5.34745 5.03758 5.40682 4.84622L6.5782 1.07092Z", + stroke: "currentColor", + strokeWidth: 1.5 +})); +const SvgStop = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 16 16", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + width: 16, + height: 16, + rx: 2, + fill: "currentColor" +})); +const SvgTrash = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + width: "1em", + height: "5em", + xmlns: "http://www.w3.org/2000/svg", + fillRule: "evenodd", + "aria-hidden": "true", + viewBox: "0 0 23 23", + style: { + height: "1.5em" + }, + clipRule: "evenodd", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("path", { + d: "M19 24h-14c-1.104 0-2-.896-2-2v-17h-1v-2h6v-1.5c0-.827.673-1.5 1.5-1.5h5c.825 0 1.5.671 1.5 1.5v1.5h6v2h-1v17c0 1.104-.896 2-2 2zm0-19h-14v16.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-16.5zm-7 7.586l3.293-3.293 1.414 1.414-3.293 3.293 3.293 3.293-1.414 1.414-3.293-3.293-3.293 3.293-1.414-1.414 3.293-3.293-3.293-3.293 1.414-1.414 3.293 3.293zm2-10.586h-4v1h4v-1z", + fill: "currentColor", + strokeWidth: 0.25, + stroke: "currentColor" +})); +const SvgType = ({ + title, + titleId, + ...props +}) => /* @__PURE__ */React__namespace.createElement("svg", { + height: "1em", + viewBox: "0 0 13 13", + fill: "none", + xmlns: "http://www.w3.org/2000/svg", + "aria-labelledby": titleId, + ...props +}, title ? /* @__PURE__ */React__namespace.createElement("title", { + id: titleId +}, title) : null, /* @__PURE__ */React__namespace.createElement("rect", { + x: 0.6, + y: 0.6, + width: 11.8, + height: 11.8, + rx: 5.9, + stroke: "currentColor", + strokeWidth: 1.2 +}), /* @__PURE__ */React__namespace.createElement("rect", { + x: 5.5, + y: 5.5, + width: 2, + height: 2, + rx: 1, + fill: "currentColor" +})); +const ArgumentIcon = generateIcon(SvgArgument); +const ChevronDownIcon = generateIcon(SvgChevronDown); +const ChevronLeftIcon = generateIcon(SvgChevronLeft); +const ChevronUpIcon = generateIcon(SvgChevronUp); +const CloseIcon = generateIcon(SvgClose); +const CopyIcon = generateIcon(SvgCopy); +const DeprecatedArgumentIcon = generateIcon(SvgDeprecatedArgument); +const DeprecatedEnumValueIcon = generateIcon(SvgDeprecatedEnumValue); +const DeprecatedFieldIcon = generateIcon(SvgDeprecatedField); +const DirectiveIcon = generateIcon(SvgDirective); +const DocsFilledIcon = generateIcon(SvgDocsFilled); +const DocsIcon = generateIcon(SvgDocs); +const EnumValueIcon = generateIcon(SvgEnumValue); +const FieldIcon = generateIcon(SvgField); +const HistoryIcon = generateIcon(SvgHistory); +const ImplementsIcon = generateIcon(SvgImplements); +const KeyboardShortcutIcon = generateIcon(SvgKeyboardShortcut); +const MagnifyingGlassIcon = generateIcon(SvgMagnifyingGlass); +const MergeIcon = generateIcon(SvgMerge); +const PenIcon = generateIcon(SvgPen); +const PlayIcon = generateIcon(SvgPlay); +const PlusIcon = generateIcon(SvgPlus); +const PrettifyIcon = generateIcon(SvgPrettify); +const ReloadIcon = generateIcon(SvgReload); +const RootTypeIcon = generateIcon(SvgRootType); +const SettingsIcon = generateIcon(SvgSettings); +const StarFilledIcon = generateIcon(SvgStarFilled); +const StarIcon = generateIcon(SvgStar); +const StopIcon = generateIcon(SvgStop); +const TrashIcon = generateIcon(SvgTrash); +const TypeIcon = generateIcon(SvgType); +function generateIcon(RawComponent) { + const title = RawComponent.name.replace("Svg", "").replaceAll(/([A-Z])/g, " $1").trimStart().toLowerCase() + " icon"; + function IconComponent(props) { + return /* @__PURE__ */jsxRuntime.jsx(RawComponent, { + title, + ...props + }); + } + IconComponent.displayName = RawComponent.name; + return IconComponent; +} +const UnStyledButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-un-styled", props.className) +})); +UnStyledButton.displayName = "UnStyledButton"; +const Button$1 = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-button", { + success: "graphiql-button-success", + error: "graphiql-button-error" + }[props.state], props.className) +})); +Button$1.displayName = "Button"; +const ButtonGroup = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx("graphiql-button-group", props.className) +})); +ButtonGroup.displayName = "ButtonGroup"; +const createComponentGroup = (root, children) => Object.entries(children).reduce((r, [key, value]) => { + r[key] = value; + return r; +}, root); +const DialogClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(D__namespace.Close, { + asChild: true, + children: /* @__PURE__ */jsxRuntime.jsxs(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-dialog-close", props.className), + children: [/* @__PURE__ */jsxRuntime.jsx(reactVisuallyHidden.Root, { + children: "Close dialog" + }), /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {})] + }) +})); +DialogClose.displayName = "Dialog.Close"; +function DialogRoot({ + children, + ...props +}) { + return /* @__PURE__ */jsxRuntime.jsx(D__namespace.Root, { + ...props, + children: /* @__PURE__ */jsxRuntime.jsxs(D__namespace.Portal, { + children: [/* @__PURE__ */jsxRuntime.jsx(D__namespace.Overlay, { + className: "graphiql-dialog-overlay" + }), /* @__PURE__ */jsxRuntime.jsx(D__namespace.Content, { + className: "graphiql-dialog", + children + })] + }) + }); +} +const Dialog = createComponentGroup(DialogRoot, { + Close: DialogClose, + Title: D__namespace.Title, + Trigger: D__namespace.Trigger, + Description: D__namespace.Description +}); +const Button = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Trigger, { + asChild: true, + children: /* @__PURE__ */jsxRuntime.jsx("button", { + ...props, + ref, + className: clsx.clsx("graphiql-un-styled", props.className) + }) +})); +Button.displayName = "DropdownMenuButton"; +function Content({ + children, + align = "start", + sideOffset = 5, + className, + ...props +}) { + return /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Portal, { + children: /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Content, { + align, + sideOffset, + className: clsx.clsx("graphiql-dropdown-content", className), + ...props, + children + }) + }); +} +const Item = ({ + className, + children, + ...props +}) => /* @__PURE__ */jsxRuntime.jsx(reactDropdownMenu.Item, { + className: clsx.clsx("graphiql-dropdown-item", className), + ...props, + children +}); +const DropdownMenu = createComponentGroup(reactDropdownMenu.Root, { + Button, + Item, + Content +}); +const markdown = new MarkdownIt({ + breaks: true, + linkify: true +}); +const MarkdownContent = React.forwardRef(({ + children, + onlyShowFirstChild, + type, + ...props +}, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx(`graphiql-markdown-${type}`, onlyShowFirstChild && "graphiql-markdown-preview", props.className), + dangerouslySetInnerHTML: { + __html: markdown.render(children) + } +})); +MarkdownContent.displayName = "MarkdownContent"; +const Spinner = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx("div", { + ...props, + ref, + className: clsx.clsx("graphiql-spinner", props.className) +})); +Spinner.displayName = "Spinner"; +function TooltipRoot({ + children, + align = "start", + side = "bottom", + sideOffset = 5, + label +}) { + return /* @__PURE__ */jsxRuntime.jsxs(T__namespace.Root, { + children: [/* @__PURE__ */jsxRuntime.jsx(T__namespace.Trigger, { + asChild: true, + children + }), /* @__PURE__ */jsxRuntime.jsx(T__namespace.Portal, { + children: /* @__PURE__ */jsxRuntime.jsx(T__namespace.Content, { + className: "graphiql-tooltip", + align, + side, + sideOffset, + children: label + }) + })] + }); +} +const Tooltip = createComponentGroup(TooltipRoot, { + Provider: T__namespace.Provider +}); +const TabRoot = React.forwardRef(({ + isActive, + value, + children, + className, + ...props +}, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Item, { + ...props, + ref, + value, + "aria-selected": isActive ? "true" : void 0, + role: "tab", + className: clsx.clsx("graphiql-tab", isActive && "graphiql-tab-active", className), + children +})); +TabRoot.displayName = "Tab"; +const TabButton = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-tab-button", props.className), + children: props.children +})); +TabButton.displayName = "Tab.Button"; +const TabClose = React.forwardRef((props, ref) => /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Close Tab", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + "aria-label": "Close Tab", + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-tab-close", props.className), + children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) + }) +})); +TabClose.displayName = "Tab.Close"; +const Tab = createComponentGroup(TabRoot, { + Button: TabButton, + Close: TabClose +}); +const Tabs = React.forwardRef(({ + values, + onReorder, + children, + className, + ...props +}, ref) => /* @__PURE__ */jsxRuntime.jsx(framerMotion.Reorder.Group, { + ...props, + ref, + values, + onReorder, + axis: "x", + role: "tablist", + className: clsx.clsx("graphiql-tabs", className), + children +})); +Tabs.displayName = "Tabs"; +const HistoryContext = createNullableContext("HistoryContext"); +function HistoryContextProvider(props) { + var _a; + const storage = useStorageContext(); + const historyStore = React.useRef(new toolkit.HistoryStore( + // Fall back to a noop storage when the StorageContext is empty + storage || new toolkit.StorageAPI(null), props.maxHistoryLength || DEFAULT_HISTORY_LENGTH)); + const [items, setItems] = React.useState(((_a = historyStore.current) == null ? void 0 : _a.queries) || []); + const addToHistory = React.useCallback(operation => { + var _a2; + (_a2 = historyStore.current) == null ? void 0 : _a2.updateHistory(operation); + setItems(historyStore.current.queries); + }, []); + const editLabel = React.useCallback((operation, index) => { + historyStore.current.editLabel(operation, index); + setItems(historyStore.current.queries); + }, []); + const toggleFavorite = React.useCallback(operation => { + historyStore.current.toggleFavorite(operation); + setItems(historyStore.current.queries); + }, []); + const setActive = React.useCallback(item => { + return item; + }, []); + const deleteFromHistory = React.useCallback((item, clearFavorites = false) => { + historyStore.current.deleteHistory(item, clearFavorites); + setItems(historyStore.current.queries); + }, []); + const value = React.useMemo(() => ({ + addToHistory, + editLabel, + items, + toggleFavorite, + setActive, + deleteFromHistory + }), [addToHistory, editLabel, items, toggleFavorite, setActive, deleteFromHistory]); + return /* @__PURE__ */jsxRuntime.jsx(HistoryContext.Provider, { + value, + children: props.children + }); +} +const useHistoryContext = createContextHook(HistoryContext); +const DEFAULT_HISTORY_LENGTH = 20; +function History() { + const { + items: all, + deleteFromHistory + } = useHistoryContext({ + nonNull: true + }); + let items = all.slice().map((item, i) => ({ + ...item, + index: i + })).reverse(); + const favorites = items.filter(item => item.favorite); + if (favorites.length) { + items = items.filter(item => !item.favorite); + } + const [clearStatus, setClearStatus] = React.useState(null); + React.useEffect(() => { + if (clearStatus) { + setTimeout(() => { + setClearStatus(null); + }, 2e3); + } + }, [clearStatus]); + const handleClearStatus = React.useCallback(() => { + try { + for (const item of items) { + deleteFromHistory(item, true); + } + setClearStatus("success"); + } catch { + setClearStatus("error"); + } + }, [deleteFromHistory, items]); + return /* @__PURE__ */jsxRuntime.jsxs("section", { + "aria-label": "History", + className: "graphiql-history", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-history-header", + children: ["History", (clearStatus || items.length > 0) && /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + state: clearStatus || void 0, + disabled: !items.length, + onClick: handleClearStatus, + children: { + success: "Cleared", + error: "Failed to Clear" + }[clearStatus] || "Clear" + })] + }), Boolean(favorites.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { + className: "graphiql-history-items", + children: favorites.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { + item + }, item.index)) + }), Boolean(favorites.length) && Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-history-item-spacer" + }), Boolean(items.length) && /* @__PURE__ */jsxRuntime.jsx("ul", { + className: "graphiql-history-items", + children: items.map(item => /* @__PURE__ */jsxRuntime.jsx(HistoryItem, { + item + }, item.index)) + })] + }); +} +function HistoryItem(props) { + const { + editLabel, + toggleFavorite, + deleteFromHistory, + setActive + } = useHistoryContext({ + nonNull: true, + caller: HistoryItem + }); + const { + headerEditor, + queryEditor, + variableEditor + } = useEditorContext({ + nonNull: true, + caller: HistoryItem + }); + const inputRef = React.useRef(null); + const buttonRef = React.useRef(null); + const [isEditable, setIsEditable] = React.useState(false); + React.useEffect(() => { + var _a; + if (isEditable) { + (_a = inputRef.current) == null ? void 0 : _a.focus(); } - this.__tlds__ = this.__tlds__.concat(list).sort().filter(function (el, idx, arr) { - return el !== arr[idx - 1]; - }).reverse(); - compile(this); - return this; - }; - - /** - * LinkifyIt#normalize(match) - * - * Default normalizer (if schema does not define it's own). - **/ - LinkifyIt.prototype.normalize = function normalize(match) { - // Do minimal possible changes by default. Need to collect feedback prior - // to move forward https://github.com/markdown-it/linkify-it/issues/1 - - if (!match.schema) { - match.url = 'http://' + match.url; + }, [isEditable]); + const displayName = props.item.label || props.item.operationName || formatQuery(props.item.query); + const handleSave = React.useCallback(() => { + var _a; + setIsEditable(false); + const { + index, + ...item + } = props.item; + editLabel({ + ...item, + label: (_a = inputRef.current) == null ? void 0 : _a.value + }, index); + }, [editLabel, props.item]); + const handleClose = React.useCallback(() => { + setIsEditable(false); + }, []); + const handleEditLabel = React.useCallback(e => { + e.stopPropagation(); + setIsEditable(true); + }, []); + const handleHistoryItemClick = React.useCallback(() => { + const { + query, + variables, + headers + } = props.item; + queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); + variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); + headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); + setActive(props.item); + }, [headerEditor, props.item, queryEditor, setActive, variableEditor]); + const handleDeleteItemFromHistory = React.useCallback(e => { + e.stopPropagation(); + deleteFromHistory(props.item); + }, [props.item, deleteFromHistory]); + const handleToggleFavorite = React.useCallback(e => { + e.stopPropagation(); + toggleFavorite(props.item); + }, [props.item, toggleFavorite]); + return /* @__PURE__ */jsxRuntime.jsx("li", { + className: clsx.clsx("graphiql-history-item", isEditable && "editable"), + children: isEditable ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx("input", { + type: "text", + defaultValue: props.item.label, + ref: inputRef, + onKeyDown: e => { + if (e.key === "Esc") { + setIsEditable(false); + } else if (e.key === "Enter") { + setIsEditable(false); + editLabel({ + ...props.item, + label: e.currentTarget.value + }); + } + }, + placeholder: "Type a label" + }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + ref: buttonRef, + onClick: handleSave, + children: "Save" + }), /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + ref: buttonRef, + onClick: handleClose, + children: /* @__PURE__ */jsxRuntime.jsx(CloseIcon, {}) + })] + }) : /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Set active", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-label", + onClick: handleHistoryItemClick, + "aria-label": "Set active", + children: displayName + }) + }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Edit label", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleEditLabel, + "aria-label": "Edit label", + children: /* @__PURE__ */jsxRuntime.jsx(PenIcon, { + "aria-hidden": "true" + }) + }) + }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: props.item.favorite ? "Remove favorite" : "Add favorite", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleToggleFavorite, + "aria-label": props.item.favorite ? "Remove favorite" : "Add favorite", + children: props.item.favorite ? /* @__PURE__ */jsxRuntime.jsx(StarFilledIcon, { + "aria-hidden": "true" + }) : /* @__PURE__ */jsxRuntime.jsx(StarIcon, { + "aria-hidden": "true" + }) + }) + }), /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label: "Delete from history", + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + type: "button", + className: "graphiql-history-item-action", + onClick: handleDeleteItemFromHistory, + "aria-label": "Delete from history", + children: /* @__PURE__ */jsxRuntime.jsx(TrashIcon, { + "aria-hidden": "true" + }) + }) + })] + }) + }); +} +function formatQuery(query) { + return query == null ? void 0 : query.split("\n").map(line => line.replace(/#(.*)/, "")).join(" ").replaceAll("{", " { ").replaceAll("}", " } ").replaceAll(/[\s]{2,}/g, " "); +} +const ExecutionContext = createNullableContext("ExecutionContext"); +function ExecutionContextProvider({ + fetcher, + getDefaultFieldNames, + children, + operationName +}) { + if (!fetcher) { + throw new TypeError("The `ExecutionContextProvider` component requires a `fetcher` function to be passed as prop."); + } + const { + externalFragments, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + updateActiveTabValues + } = useEditorContext({ + nonNull: true, + caller: ExecutionContextProvider + }); + const history = useHistoryContext(); + const autoCompleteLeafs = useAutoCompleteLeafs({ + getDefaultFieldNames, + caller: ExecutionContextProvider + }); + const [isFetching, setIsFetching] = React.useState(false); + const [subscription, setSubscription] = React.useState(null); + const queryIdRef = React.useRef(0); + const stop = React.useCallback(() => { + subscription == null ? void 0 : subscription.unsubscribe(); + setIsFetching(false); + setSubscription(null); + }, [subscription]); + const run = React.useCallback(async () => { + var _ref; + if (!queryEditor || !responseEditor) { + return; } - if (match.schema === 'mailto:' && !/^mailto:/i.test(match.url)) { - match.url = 'mailto:' + match.url; + if (subscription) { + stop(); + return; } - }; - - /** - * LinkifyIt#onCompile() - * - * Override to modify basic RegExp-s. - **/ - LinkifyIt.prototype.onCompile = function onCompile() {}; - module.exports = LinkifyIt; - - /***/ }), - - /***/ "../node_modules/markdown-it/dist/index.cjs.js": - /*!*****************************************************!*\ - !*** ../node_modules/markdown-it/dist/index.cjs.js ***! - \*****************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - - var mdurl = __webpack_require__(/*! mdurl */ "../node_modules/mdurl/build/index.cjs.js"); - var ucmicro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); - var entities = __webpack_require__(/*! entities */ "../../../node_modules/entities/lib/index.js"); - var LinkifyIt = __webpack_require__(/*! linkify-it */ "../node_modules/linkify-it/build/index.cjs.js"); - var punycode = __webpack_require__(/*! punycode.js */ "../../../node_modules/punycode.js/punycode.es6.js"); - function _interopNamespaceDefault(e) { - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { - return e[k]; - } - }); - } + const setResponse = value2 => { + responseEditor.setValue(value2); + updateActiveTabValues({ + response: value2 }); - } - n.default = e; - return Object.freeze(n); - } - var mdurl__namespace = /*#__PURE__*/_interopNamespaceDefault(mdurl); - var ucmicro__namespace = /*#__PURE__*/_interopNamespaceDefault(ucmicro); - - // Utilities - // - - function _class(obj) { - return Object.prototype.toString.call(obj); - } - function isString(obj) { - return _class(obj) === '[object String]'; - } - const _hasOwnProperty = Object.prototype.hasOwnProperty; - function has(object, key) { - return _hasOwnProperty.call(object, key); - } - - // Merge objects - // - function assign(obj /* from1, from2, from3, ... */) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; - } - if (typeof source !== 'object') { - throw new TypeError(source + 'must be object'); - } - Object.keys(source).forEach(function (key) { - obj[key] = source[key]; + }; + queryIdRef.current += 1; + const queryId = queryIdRef.current; + let query = autoCompleteLeafs() || queryEditor.getValue(); + const variablesString = variableEditor == null ? void 0 : variableEditor.getValue(); + let variables; + try { + variables = tryParseJsonObject({ + json: variablesString, + errorMessageParse: "Variables are invalid JSON", + errorMessageType: "Variables are not a JSON object." }); - }); - return obj; - } - - // Remove element from array and put another array at those position. - // Useful for some operations with tokens - function arrayReplaceAt(src, pos, newElements) { - return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); - } - function isValidEntityCode(c) { - /* eslint no-bitwise:0 */ - // broken sequence - if (c >= 0xD800 && c <= 0xDFFF) { - return false; - } - // never used - if (c >= 0xFDD0 && c <= 0xFDEF) { - return false; - } - if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { - return false; - } - // control codes - if (c >= 0x00 && c <= 0x08) { - return false; - } - if (c === 0x0B) { - return false; - } - if (c >= 0x0E && c <= 0x1F) { - return false; - } - if (c >= 0x7F && c <= 0x9F) { - return false; - } - // out of range - if (c > 0x10FFFF) { - return false; + } catch (error) { + setResponse(error instanceof Error ? error.message : `${error}`); + return; } - return true; - } - function fromCodePoint(c) { - /* eslint no-bitwise:0 */ - if (c > 0xffff) { - c -= 0x10000; - const surrogate1 = 0xd800 + (c >> 10); - const surrogate2 = 0xdc00 + (c & 0x3ff); - return String.fromCharCode(surrogate1, surrogate2); + const headersString = headerEditor == null ? void 0 : headerEditor.getValue(); + let headers; + try { + headers = tryParseJsonObject({ + json: headersString, + errorMessageParse: "Headers are invalid JSON", + errorMessageType: "Headers are not a JSON object." + }); + } catch (error) { + setResponse(error instanceof Error ? error.message : `${error}`); + return; } - return String.fromCharCode(c); - } - const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g; - const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; - const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi'); - const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i; - function replaceEntityPattern(match, name) { - if (name.charCodeAt(0) === 0x23 /* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) { - const code = name[1].toLowerCase() === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10); - if (isValidEntityCode(code)) { - return fromCodePoint(code); + if (externalFragments) { + const fragmentDependencies = queryEditor.documentAST ? graphqlLanguageService.getFragmentDependenciesForAST(queryEditor.documentAST, externalFragments) : []; + if (fragmentDependencies.length > 0) { + query += "\n" + fragmentDependencies.map(node => graphql.print(node)).join("\n"); } - return match; - } - const decoded = entities.decodeHTML(match); - if (decoded !== match) { - return decoded; - } - return match; - } - - /* function replaceEntities(str) { - if (str.indexOf('&') < 0) { return str; } - - return str.replace(ENTITY_RE, replaceEntityPattern); - } */ - - function unescapeMd(str) { - if (str.indexOf('\\') < 0) { - return str; - } - return str.replace(UNESCAPE_MD_RE, '$1'); - } - function unescapeAll(str) { - if (str.indexOf('\\') < 0 && str.indexOf('&') < 0) { - return str; } - return str.replace(UNESCAPE_ALL_RE, function (match, escaped, entity) { - if (escaped) { - return escaped; - } - return replaceEntityPattern(match, entity); + setResponse(""); + setIsFetching(true); + const opName = (_ref = operationName !== null && operationName !== void 0 ? operationName : queryEditor.operationName) !== null && _ref !== void 0 ? _ref : void 0; + history == null ? void 0 : history.addToHistory({ + query, + variables: variablesString, + headers: headersString, + operationName: opName }); - } - const HTML_ESCAPE_TEST_RE = /[&<>"]/; - const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; - const HTML_REPLACEMENTS = { - '&': '&', - '<': '<', - '>': '>', - '"': '"' - }; - function replaceUnsafeChar(ch) { - return HTML_REPLACEMENTS[ch]; - } - function escapeHtml(str) { - if (HTML_ESCAPE_TEST_RE.test(str)) { - return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); + try { + var _headers, _queryEditor$document; + const fullResponse = {}; + const handleResponse = result => { + if (queryId !== queryIdRef.current) { + return; + } + let maybeMultipart = Array.isArray(result) ? result : false; + if (!maybeMultipart && typeof result === "object" && result !== null && "hasNext" in result) { + maybeMultipart = [result]; + } + if (maybeMultipart) { + for (const part of maybeMultipart) { + mergeIncrementalResult(fullResponse, part); + } + setIsFetching(false); + setResponse(toolkit.formatResult(fullResponse)); + } else { + const response = toolkit.formatResult(result); + setIsFetching(false); + setResponse(response); + } + }; + const fetch2 = fetcher({ + query, + variables, + operationName: opName + }, { + headers: (_headers = headers) !== null && _headers !== void 0 ? _headers : void 0, + documentAST: (_queryEditor$document = queryEditor.documentAST) !== null && _queryEditor$document !== void 0 ? _queryEditor$document : void 0 + }); + const value2 = await Promise.resolve(fetch2); + if (toolkit.isObservable(value2)) { + setSubscription(value2.subscribe({ + next(result) { + handleResponse(result); + }, + error(error) { + setIsFetching(false); + if (error) { + setResponse(toolkit.formatError(error)); + } + setSubscription(null); + }, + complete() { + setIsFetching(false); + setSubscription(null); + } + })); + } else if (toolkit.isAsyncIterable(value2)) { + setSubscription({ + unsubscribe: () => { + var _a, _b; + return (_b = (_a = value2[Symbol.asyncIterator]()).return) == null ? void 0 : _b.call(_a); + } + }); + for await (const result of value2) { + handleResponse(result); + } + setIsFetching(false); + setSubscription(null); + } else { + handleResponse(value2); + } + } catch (error) { + setIsFetching(false); + setResponse(toolkit.formatError(error)); + setSubscription(null); } - return str; - } - const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; - function escapeRE(str) { - return str.replace(REGEXP_ESCAPE_RE, '\\$&'); + }, [autoCompleteLeafs, externalFragments, fetcher, headerEditor, history, operationName, queryEditor, responseEditor, stop, subscription, updateActiveTabValues, variableEditor]); + const isSubscribed = Boolean(subscription); + const value = React.useMemo(() => ({ + isFetching, + isSubscribed, + operationName: operationName !== null && operationName !== void 0 ? operationName : null, + run, + stop + }), [isFetching, isSubscribed, operationName, run, stop]); + return /* @__PURE__ */jsxRuntime.jsx(ExecutionContext.Provider, { + value, + children + }); +} +const useExecutionContext = createContextHook(ExecutionContext); +function tryParseJsonObject({ + json, + errorMessageParse, + errorMessageType +}) { + let parsed; + try { + parsed = json && json.trim() !== "" ? JSON.parse(json) : void 0; + } catch (error) { + throw new Error(`${errorMessageParse}: ${error instanceof Error ? error.message : error}.`); + } + const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed); + if (parsed !== void 0 && !isObject) { + throw new Error(errorMessageType); + } + return parsed; +} +function mergeIncrementalResult(executionResult, incrementalResult) { + var _incrementalResult$pa; + const path = ["data", ...((_incrementalResult$pa = incrementalResult.path) !== null && _incrementalResult$pa !== void 0 ? _incrementalResult$pa : [])]; + if (incrementalResult.items) { + for (const item of incrementalResult.items) { + setValue(executionResult, path.join("."), item); + path[path.length - 1]++; + } + } + if (incrementalResult.data) { + setValue(executionResult, path.join("."), incrementalResult.data, { + merge: true + }); } - function isSpace(code) { - switch (code) { - case 0x09: - case 0x20: - return true; - } - return false; + if (incrementalResult.errors) { + executionResult.errors || (executionResult.errors = []); + executionResult.errors.push(...incrementalResult.errors); } - - // Zs (unicode class) || [\t\f\v\r\n] - function isWhiteSpace(code) { - if (code >= 0x2000 && code <= 0x200A) { - return true; - } - switch (code) { - case 0x09: // \t - case 0x0A: // \n - case 0x0B: // \v - case 0x0C: // \f - case 0x0D: // \r - case 0x20: - case 0xA0: - case 0x1680: - case 0x202F: - case 0x205F: - case 0x3000: - return true; - } - return false; + if (incrementalResult.extensions) { + setValue(executionResult, "extensions", incrementalResult.extensions, { + merge: true + }); } - - /* eslint-disable max-len */ - - // Currently without astral characters support. - function isPunctChar(ch) { - return ucmicro__namespace.P.test(ch) || ucmicro__namespace.S.test(ch); + if (incrementalResult.incremental) { + for (const incrementalSubResult of incrementalResult.incremental) { + mergeIncrementalResult(executionResult, incrementalSubResult); + } + } +} +const DEFAULT_EDITOR_THEME = "graphiql"; +const DEFAULT_KEY_MAP = "sublime"; +let isMacOs = false; +if (typeof window === "object") { + isMacOs = window.navigator.platform.toLowerCase().indexOf("mac") === 0; +} +const commonKeys = { + // Persistent search box in Query Editor + [isMacOs ? "Cmd-F" : "Ctrl-F"]: "findPersistent", + "Cmd-G": "findPersistent", + "Ctrl-G": "findPersistent", + // Editor improvements + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight" +}; +async function importCodeMirror(addons, options) { + const CodeMirror = await Promise.resolve().then(() => __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js")).then(n => n.codemirror).then(c => + // Depending on bundler and settings the dynamic import either returns a + // function (e.g. parcel) or an object containing a `default` property + typeof c === "function" ? c : c.default); + await Promise.all((options == null ? void 0 : options.useCommonAddons) === false ? addons : [Promise.resolve().then(() => __webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js")).then(n => n.showHint), Promise.resolve().then(() => __webpack_require__(/*! ./matchbrackets.cjs.js */ "../../graphiql-react/dist/matchbrackets.cjs.js")).then(n => n.matchbrackets), Promise.resolve().then(() => __webpack_require__(/*! ./closebrackets.cjs.js */ "../../graphiql-react/dist/closebrackets.cjs.js")).then(n => n.closebrackets), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs.js */ "../../graphiql-react/dist/lint.cjs.js")).then(n => n.lint), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), + // @ts-expect-error + Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), ...addons]); + return CodeMirror; +} +const printDefault = ast => { + if (!ast) { + return ""; + } + return graphql.print(ast); +}; +function DefaultValue({ + field +}) { + if (!("defaultValue" in field) || field.defaultValue === void 0) { + return null; } - - // Markdown ASCII punctuation characters. - // - // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ - // http://spec.commonmark.org/0.15/#ascii-punctuation-character - // - // Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. - // - function isMdAsciiPunct(ch) { - switch (ch) { - case 0x21 /* ! */: - case 0x22 /* " */: - case 0x23 /* # */: - case 0x24 /* $ */: - case 0x25 /* % */: - case 0x26 /* & */: - case 0x27 /* ' */: - case 0x28 /* ( */: - case 0x29 /* ) */: - case 0x2A /* * */: - case 0x2B /* + */: - case 0x2C /* , */: - case 0x2D /* - */: - case 0x2E /* . */: - case 0x2F /* / */: - case 0x3A /* : */: - case 0x3B /* ; */: - case 0x3C /* < */: - case 0x3D /* = */: - case 0x3E /* > */: - case 0x3F /* ? */: - case 0x40 /* @ */: - case 0x5B /* [ */: - case 0x5C /* \ */: - case 0x5D /* ] */: - case 0x5E /* ^ */: - case 0x5F /* _ */: - case 0x60 /* ` */: - case 0x7B /* { */: - case 0x7C /* | */: - case 0x7D /* } */: - case 0x7E /* ~ */: - return true; - default: - return false; - } + const ast = graphql.astFromValue(field.defaultValue, field.type); + if (!ast) { + return null; } - - // Hepler to unify [reference labels]. - // - function normalizeReference(str) { - // Trim and collapse whitespace - // - str = str.trim().replace(/\s+/g, ' '); - - // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug - // fixed in v12 (couldn't find any details). - // - // So treat this one as a special case - // (remove this when node v10 is no longer supported). - // - if ('ẞ'.toLowerCase() === 'Ṿ') { - str = str.replace(/ẞ/g, 'ß'); - } - - // .toLowerCase().toUpperCase() should get rid of all differences - // between letter variants. - // - // Simple .toLowerCase() doesn't normalize 125 code points correctly, - // and .toUpperCase doesn't normalize 6 of them (list of exceptions: - // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently - // uppercased versions). - // - // Here's an example showing how it happens. Lets take greek letter omega: - // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) - // - // Unicode entries: - // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; - // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 - // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 - // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; - // - // Case-insensitive comparison should treat all of them as equivalent. - // - // But .toLowerCase() doesn't change ϑ (it's already lowercase), - // and .toUpperCase() doesn't change ϴ (already uppercase). - // - // Applying first lower then upper case normalizes any character: - // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' - // - // Note: this is equivalent to unicode case folding; unicode normalization - // is a different step that is not required here. - // - // Final result should be uppercased, because it's later stored in an object - // (this avoid a conflict with Object.prototype members, - // most notably, `__proto__`) - // - return str.toLowerCase().toUpperCase(); + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [" = ", /* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-default-value", + children: printDefault(ast) + })] + }); +} +const SchemaContext = createNullableContext("SchemaContext"); +function SchemaContextProvider(props) { + if (!props.fetcher) { + throw new TypeError("The `SchemaContextProvider` component requires a `fetcher` function to be passed as prop."); } - - // Re-export libraries commonly used in both markdown-it and its plugins, - // so plugins won't have to depend on them explicitly, which reduces their - // bundled size (e.g. a browser build). - // - const lib = { - mdurl: mdurl__namespace, - ucmicro: ucmicro__namespace - }; - var utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - arrayReplaceAt: arrayReplaceAt, - assign: assign, - escapeHtml: escapeHtml, - escapeRE: escapeRE, - fromCodePoint: fromCodePoint, - has: has, - isMdAsciiPunct: isMdAsciiPunct, - isPunctChar: isPunctChar, - isSpace: isSpace, - isString: isString, - isValidEntityCode: isValidEntityCode, - isWhiteSpace: isWhiteSpace, - lib: lib, - normalizeReference: normalizeReference, - unescapeAll: unescapeAll, - unescapeMd: unescapeMd + const { + initialHeaders, + headerEditor + } = useEditorContext({ + nonNull: true, + caller: SchemaContextProvider }); - - // Parse link label - // - // this function assumes that first character ("[") already matches; - // returns the end of the label - // - - function parseLinkLabel(state, start, disableNested) { - let level, found, marker, prevPos; - const max = state.posMax; - const oldPos = state.pos; - state.pos = start + 1; - level = 1; - while (state.pos < max) { - marker = state.src.charCodeAt(state.pos); - if (marker === 0x5D /* ] */) { - level--; - if (level === 0) { - found = true; - break; - } - } - prevPos = state.pos; - state.md.inline.skipToken(state); - if (marker === 0x5B /* [ */) { - if (prevPos === state.pos - 1) { - // increase level if we find text `[`, which is not a part of any token - level++; - } else if (disableNested) { - state.pos = oldPos; - return -1; - } - } + const [schema, setSchema] = React.useState(); + const [isFetching, setIsFetching] = React.useState(false); + const [fetchError, setFetchError] = React.useState(null); + const counterRef = React.useRef(0); + React.useEffect(() => { + setSchema(graphql.isSchema(props.schema) || props.schema === null || props.schema === void 0 ? props.schema : void 0); + counterRef.current++; + }, [props.schema]); + const headersRef = React.useRef(initialHeaders); + React.useEffect(() => { + if (headerEditor) { + headersRef.current = headerEditor.getValue(); } - let labelEnd = -1; - if (found) { - labelEnd = state.pos; - } - - // restore old state - state.pos = oldPos; - return labelEnd; - } - - // Parse link destination - // - - function parseLinkDestination(str, start, max) { - let code; - let pos = start; - const result = { - ok: false, - pos: 0, - str: '' - }; - if (str.charCodeAt(pos) === 0x3C /* < */) { - pos++; - while (pos < max) { - code = str.charCodeAt(pos); - if (code === 0x0A /* \n */) { - return result; - } - if (code === 0x3C /* < */) { - return result; - } - if (code === 0x3E /* > */) { - result.pos = pos + 1; - result.str = unescapeAll(str.slice(start + 1, pos)); - result.ok = true; - return result; - } - if (code === 0x5C /* \ */ && pos + 1 < max) { - pos += 2; - continue; - } - pos++; - } - - // no closing '>' - return result; + }); + const { + introspectionQuery, + introspectionQueryName, + introspectionQuerySansSubscriptions + } = useIntrospectionQuery({ + inputValueDeprecation: props.inputValueDeprecation, + introspectionQueryName: props.introspectionQueryName, + schemaDescription: props.schemaDescription + }); + const { + fetcher, + onSchemaChange, + dangerouslyAssumeSchemaIsValid, + children + } = props; + const introspect = React.useCallback(() => { + if (graphql.isSchema(props.schema) || props.schema === null) { + return; } - - // this should be ... } else { ... branch - - let level = 0; - while (pos < max) { - code = str.charCodeAt(pos); - if (code === 0x20) { - break; - } - - // ascii control characters - if (code < 0x20 || code === 0x7F) { - break; - } - if (code === 0x5C /* \ */ && pos + 1 < max) { - if (str.charCodeAt(pos + 1) === 0x20) { - break; - } - pos += 2; - continue; - } - if (code === 0x28 /* ( */) { - level++; - if (level > 32) { - return result; - } + const counter = ++counterRef.current; + const maybeIntrospectionData = props.schema; + async function fetchIntrospectionData() { + if (maybeIntrospectionData) { + return maybeIntrospectionData; } - if (code === 0x29 /* ) */) { - if (level === 0) { - break; - } - level--; + const parsedHeaders = parseHeaderString(headersRef.current); + if (!parsedHeaders.isValidJSON) { + setFetchError("Introspection failed as headers are invalid."); + return; } - pos++; - } - if (start === pos) { - return result; - } - if (level !== 0) { - return result; - } - result.str = unescapeAll(str.slice(start, pos)); - result.pos = pos; - result.ok = true; - return result; - } - - // Parse link title - // - - // Parse link title within `str` in [start, max] range, - // or continue previous parsing if `prev_state` is defined (equal to result of last execution). - // - function parseLinkTitle(str, start, max, prev_state) { - let code; - let pos = start; - const state = { - // if `true`, this is a valid link title - ok: false, - // if `true`, this link can be continued on the next line - can_continue: false, - // if `ok`, it's the position of the first character after the closing marker - pos: 0, - // if `ok`, it's the unescaped title - str: '', - // expected closing marker character code - marker: 0 - }; - if (prev_state) { - // this is a continuation of a previous parseLinkTitle call on the next line, - // used in reference links only - state.str = prev_state.str; - state.marker = prev_state.marker; - } else { - if (pos >= max) { - return state; + const fetcherOpts = parsedHeaders.headers ? { + headers: parsedHeaders.headers + } : {}; + const fetch2 = toolkit.fetcherReturnToPromise(fetcher({ + query: introspectionQuery, + operationName: introspectionQueryName + }, fetcherOpts)); + if (!toolkit.isPromise(fetch2)) { + setFetchError("Fetcher did not return a Promise for introspection."); + return; } - let marker = str.charCodeAt(pos); - if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { - return state; + setIsFetching(true); + setFetchError(null); + let result = await fetch2; + if (typeof result !== "object" || result === null || !("data" in result)) { + const fetch22 = toolkit.fetcherReturnToPromise(fetcher({ + query: introspectionQuerySansSubscriptions, + operationName: introspectionQueryName + }, fetcherOpts)); + if (!toolkit.isPromise(fetch22)) { + throw new Error("Fetcher did not return a Promise for introspection."); + } + result = await fetch22; } - start++; - pos++; - - // if opening marker is "(", switch it to closing marker ")" - if (marker === 0x28) { - marker = 0x29; + setIsFetching(false); + if ((result == null ? void 0 : result.data) && "__schema" in result.data) { + return result.data; } - state.marker = marker; + const responseString = typeof result === "string" ? result : toolkit.formatResult(result); + setFetchError(responseString); } - while (pos < max) { - code = str.charCodeAt(pos); - if (code === state.marker) { - state.pos = pos + 1; - state.str += unescapeAll(str.slice(start, pos)); - state.ok = true; - return state; - } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) { - return state; - } else if (code === 0x5C /* \ */ && pos + 1 < max) { - pos++; + fetchIntrospectionData().then(introspectionData => { + if (counter !== counterRef.current || !introspectionData) { + return; } - pos++; - } - - // no closing marker found, but this link title may continue on the next line (for references) - state.can_continue = true; - state.str += unescapeAll(str.slice(start, pos)); - return state; - } - - // Just a shortcut for bulk export - - var helpers = /*#__PURE__*/Object.freeze({ - __proto__: null, - parseLinkDestination: parseLinkDestination, - parseLinkLabel: parseLinkLabel, - parseLinkTitle: parseLinkTitle + try { + const newSchema = graphql.buildClientSchema(introspectionData); + setSchema(newSchema); + onSchemaChange == null ? void 0 : onSchemaChange(newSchema); + } catch (error) { + setFetchError(toolkit.formatError(error)); + } + }).catch(error => { + if (counter !== counterRef.current) { + return; + } + setFetchError(toolkit.formatError(error)); + setIsFetching(false); + }); + }, [fetcher, introspectionQueryName, introspectionQuery, introspectionQuerySansSubscriptions, onSchemaChange, props.schema]); + React.useEffect(() => { + introspect(); + }, [introspect]); + React.useEffect(() => { + function triggerIntrospection(event) { + if (event.ctrlKey && event.key === "R") { + introspect(); + } + } + window.addEventListener("keydown", triggerIntrospection); + return () => window.removeEventListener("keydown", triggerIntrospection); }); - - /** - * class Renderer - * - * Generates HTML from parsed token stream. Each instance has independent - * copy of rules. Those can be rewritten with ease. Also, you can add new - * rules if you create plugin and adds new token types. - **/ - - const default_rules = {}; - default_rules.code_inline = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - return '' + escapeHtml(token.content) + ''; - }; - default_rules.code_block = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - return '' + escapeHtml(tokens[idx].content) + '\n'; - }; - default_rules.fence = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - const info = token.info ? unescapeAll(token.info).trim() : ''; - let langName = ''; - let langAttrs = ''; - if (info) { - const arr = info.split(/(\s+)/g); - langName = arr[0]; - langAttrs = arr.slice(2).join(''); - } - let highlighted; - if (options.highlight) { - highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content); - } else { - highlighted = escapeHtml(token.content); + const validationErrors = React.useMemo(() => { + if (!schema || dangerouslyAssumeSchemaIsValid) { + return []; } - if (highlighted.indexOf(' ({ + fetchError, + introspect, + isFetching, + schema, + validationErrors + }), [fetchError, introspect, isFetching, schema, validationErrors]); + return /* @__PURE__ */jsxRuntime.jsx(SchemaContext.Provider, { + value, + children + }); +} +const useSchemaContext = createContextHook(SchemaContext); +function useIntrospectionQuery({ + inputValueDeprecation, + introspectionQueryName, + schemaDescription +}) { + return React.useMemo(() => { + const queryName = introspectionQueryName || "IntrospectionQuery"; + let query = graphql.getIntrospectionQuery({ + inputValueDeprecation, + schemaDescription + }); + if (introspectionQueryName) { + query = query.replace("query IntrospectionQuery", `query ${queryName}`); } - - // If language exists, inject class gently, without modifying original token. - // May be, one day we will add .deepClone() for token and simplify this part, but - // now we prefer to keep things local. - if (info) { - const i = token.attrIndex('class'); - const tmpAttrs = token.attrs ? token.attrs.slice() : []; - if (i < 0) { - tmpAttrs.push(['class', options.langPrefix + langName]); - } else { - tmpAttrs[i] = tmpAttrs[i].slice(); - tmpAttrs[i][1] += ' ' + options.langPrefix + langName; - } - - // Fake token just to render attributes - const tmpToken = { - attrs: tmpAttrs - }; - return `
    ${highlighted}
    \n`; + const querySansSubscriptions = query.replace("subscriptionType { name }", ""); + return { + introspectionQueryName: queryName, + introspectionQuery: query, + introspectionQuerySansSubscriptions: querySansSubscriptions + }; + }, [inputValueDeprecation, introspectionQueryName, schemaDescription]); +} +function parseHeaderString(headersString) { + let headers = null; + let isValidJSON = true; + try { + if (headersString) { + headers = JSON.parse(headersString); } - return `
    ${highlighted}
    \n`; - }; - default_rules.image = function (tokens, idx, options, env, slf) { - const token = tokens[idx]; - - // "alt" attr MUST be set, even if empty. Because it's mandatory and - // should be placed on proper position for tests. - // - // Replace content with actual value - - token.attrs[token.attrIndex('alt')][1] = slf.renderInlineAsText(token.children, options, env); - return slf.renderToken(tokens, idx, options); - }; - default_rules.hardbreak = function (tokens, idx, options /*, env */) { - return options.xhtmlOut ? '
    \n' : '
    \n'; - }; - default_rules.softbreak = function (tokens, idx, options /*, env */) { - return options.breaks ? options.xhtmlOut ? '
    \n' : '
    \n' : '\n'; - }; - default_rules.text = function (tokens, idx /*, options, env */) { - return escapeHtml(tokens[idx].content); - }; - default_rules.html_block = function (tokens, idx /*, options, env */) { - return tokens[idx].content; - }; - default_rules.html_inline = function (tokens, idx /*, options, env */) { - return tokens[idx].content; - }; - - /** - * new Renderer() - * - * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. - **/ - function Renderer() { - /** - * Renderer#rules -> Object - * - * Contains render rules for tokens. Can be updated and extended. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.renderer.rules.strong_open = function () { return ''; }; - * md.renderer.rules.strong_close = function () { return ''; }; - * - * var result = md.renderInline(...); - * ``` - * - * Each rule is called as independent static function with fixed signature: - * - * ```javascript - * function my_token_render(tokens, idx, options, env, renderer) { - * // ... - * return renderedHTML; - * } - * ``` - * - * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs) - * for more details and examples. - **/ - this.rules = assign({}, default_rules); + } catch { + isValidJSON = false; } - - /** - * Renderer.renderAttrs(token) -> String - * - * Render token attributes to string. - **/ - Renderer.prototype.renderAttrs = function renderAttrs(token) { - let i, l, result; - if (!token.attrs) { - return ''; - } - result = ''; - for (i = 0, l = token.attrs.length; i < l; i++) { - result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"'; - } - return result; + return { + headers, + isValidJSON }; - - /** - * Renderer.renderToken(tokens, idx, options) -> String - * - tokens (Array): list of tokens - * - idx (Numbed): token index to render - * - options (Object): params of parser instance - * - * Default token renderer. Can be overriden by custom function - * in [[Renderer#rules]]. - **/ - Renderer.prototype.renderToken = function renderToken(tokens, idx, options) { - const token = tokens[idx]; - let result = ''; - - // Tight list paragraphs - if (token.hidden) { - return ''; - } - - // Insert a newline between hidden paragraph and subsequent opening - // block-level tag. - // - // For example, here we should insert a newline before blockquote: - // - a - // > - // - if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) { - result += '\n'; - } - - // Add token name, e.g. ` { + setNavStack(currentState => { + const lastItem = currentState.at(-1); + return lastItem.def === item.def ? + // Avoid pushing duplicate items + currentState : [...currentState, item]; + }); + }, []); + const pop = React.useCallback(() => { + setNavStack(currentState => currentState.length > 1 ? currentState.slice(0, -1) : currentState); + }, []); + const reset = React.useCallback(() => { + setNavStack(currentState => currentState.length === 1 ? currentState : [initialNavStackItem]); + }, []); + React.useEffect(() => { + if (schema == null || validationErrors.length > 0) { + reset(); + } else { + setNavStack(oldNavStack => { + if (oldNavStack.length === 1) { + return oldNavStack; + } + const newNavStack = [initialNavStackItem]; + let lastEntity = null; + for (const item of oldNavStack) { + if (item === initialNavStackItem) { + continue; + } + if (item.def) { + if (graphql.isNamedType(item.def)) { + const newType = schema.getType(item.def.name); + if (newType) { + newNavStack.push({ + name: item.name, + def: newType + }); + lastEntity = newType; + } else { + break; + } + } else if (lastEntity === null) { + break; + } else if (graphql.isObjectType(lastEntity) || graphql.isInputObjectType(lastEntity)) { + const field = lastEntity.getFields()[item.name]; + if (field) { + newNavStack.push({ + name: item.name, + def: field + }); + } else { + break; + } + } else if (graphql.isScalarType(lastEntity) || graphql.isEnumType(lastEntity) || graphql.isInterfaceType(lastEntity) || graphql.isUnionType(lastEntity)) { + break; + } else { + const field = lastEntity; + const arg = field.args.find(a => a.name === item.name); + if (arg) { + newNavStack.push({ + name: item.name, + def: field + }); + } else { + break; + } + } + } else { + lastEntity = null; + newNavStack.push(item); + } + } + return newNavStack; + }); } - - // Check if we need to add a newline after this tag - let needLf = false; - if (token.block) { - needLf = true; - if (token.nesting === 1) { - if (idx + 1 < tokens.length) { - const nextToken = tokens[idx + 1]; - if (nextToken.type === 'inline' || nextToken.hidden) { - // Block-level tag containing an inline tag. - // - needLf = false; - } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) { - // Opening tag + closing tag of the same type. E.g. `
  • `. - // - needLf = false; - } - } - } - } - result += needLf ? '>\n' : '>'; - return result; + }, [reset, schema, validationErrors]); + const value = React.useMemo(() => ({ + explorerNavStack: navStack, + push, + pop, + reset + }), [navStack, push, pop, reset]); + return /* @__PURE__ */jsxRuntime.jsx(ExplorerContext.Provider, { + value, + children: props.children + }); +} +const useExplorerContext = createContextHook(ExplorerContext); +function renderType(type, renderNamedType) { + if (graphql.isNonNullType(type)) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [renderType(type.ofType, renderNamedType), "!"] + }); + } + if (graphql.isListType(type)) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["[", renderType(type.ofType, renderNamedType), "]"] + }); + } + return renderNamedType(type); +} +function TypeLink(props) { + const { + push + } = useExplorerContext({ + nonNull: true, + caller: TypeLink + }); + if (!props.type) { + return null; + } + return renderType(props.type, namedType => /* @__PURE__ */jsxRuntime.jsx("a", { + className: "graphiql-doc-explorer-type-name", + onClick: event => { + event.preventDefault(); + push({ + name: namedType.name, + def: namedType + }); + }, + href: "#", + children: namedType.name + })); +} +function Argument({ + arg, + showDefaultValue, + inline +}) { + const definition = /* @__PURE__ */jsxRuntime.jsxs("span", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-argument-name", + children: arg.name + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: arg.type + }), showDefaultValue !== false && /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { + field: arg + })] + }); + if (inline) { + return definition; + } + return /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-argument", + children: [definition, arg.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: arg.description + }) : null, arg.deprecationReason ? /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-argument-deprecation", + children: [/* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-argument-deprecation-label", + children: "Deprecated" + }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + children: arg.deprecationReason + })] + }) : null] + }); +} +function DeprecationReason(props) { + var _props$preview; + return props.children ? /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-deprecation", + children: [/* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-deprecation-label", + children: "Deprecated" + }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + onlyShowFirstChild: (_props$preview = props.preview) !== null && _props$preview !== void 0 ? _props$preview : true, + children: props.children + })] + }) : null; +} +function Directive({ + directive +}) { + return /* @__PURE__ */jsxRuntime.jsxs("span", { + className: "graphiql-doc-explorer-directive", + children: ["@", directive.name.value] + }); +} +function ExplorerSection(props) { + const Icon2 = TYPE_TO_ICON[props.title]; + return /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-section-title", + children: [/* @__PURE__ */jsxRuntime.jsx(Icon2, {}), props.title] + }), /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-section-content", + children: props.children + })] + }); +} +const TYPE_TO_ICON = { + Arguments: ArgumentIcon, + "Deprecated Arguments": DeprecatedArgumentIcon, + "Deprecated Enum Values": DeprecatedEnumValueIcon, + "Deprecated Fields": DeprecatedFieldIcon, + Directives: DirectiveIcon, + "Enum Values": EnumValueIcon, + Fields: FieldIcon, + Implements: ImplementsIcon, + Implementations: TypeIcon, + "Possible Types": TypeIcon, + "Root Types": RootTypeIcon, + Type: TypeIcon, + "All Schema Types": TypeIcon +}; +function FieldDocumentation(props) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [props.field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.field.description + }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { + preview: false, + children: props.field.deprecationReason + }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Type", + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: props.field.type + }) + }), /* @__PURE__ */jsxRuntime.jsx(Arguments, { + field: props.field + }), /* @__PURE__ */jsxRuntime.jsx(Directives, { + field: props.field + })] + }); +} +function Arguments({ + field +}) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!("args" in field)) { + return null; + } + const args = []; + const deprecatedArgs = []; + for (const argument of field.args) { + if (argument.deprecationReason) { + deprecatedArgs.push(argument); + } else { + args.push(argument); + } + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [args.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Arguments", + children: args.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg + }, arg.name)) + }) : null, deprecatedArgs.length > 0 ? showDeprecated || args.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Arguments", + children: deprecatedArgs.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg + }, arg.name)) + }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Arguments" + }) : null] + }); +} +function Directives({ + field +}) { + var _a; + const directives = ((_a = field.astNode) == null ? void 0 : _a.directives) || []; + if (!directives || directives.length === 0) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Directives", + children: directives.map(directive => /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(Directive, { + directive + }) + }, directive.name.value)) + }); +} +function SchemaDocumentation(props) { + var _a, _b, _c, _d; + const queryType = props.schema.getQueryType(); + const mutationType = (_b = (_a = props.schema).getMutationType) == null ? void 0 : _b.call(_a); + const subscriptionType = (_d = (_c = props.schema).getSubscriptionType) == null ? void 0 : _d.call(_c); + const typeMap = props.schema.getTypeMap(); + const ignoreTypesInAllSchema = [queryType == null ? void 0 : queryType.name, mutationType == null ? void 0 : mutationType.name, subscriptionType == null ? void 0 : subscriptionType.name]; + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.schema.description || "A GraphQL schema provides a root type for each kind of operation." + }), /* @__PURE__ */jsxRuntime.jsxs(ExplorerSection, { + title: "Root Types", + children: [queryType ? /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "query" + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: queryType + })] + }) : null, mutationType && /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "mutation" + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: mutationType + })] + }), subscriptionType && /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "subscription" + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: subscriptionType + })] + })] + }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "All Schema Types", + children: typeMap && /* @__PURE__ */jsxRuntime.jsx("div", { + children: Object.values(typeMap).map(type => { + if (ignoreTypesInAllSchema.includes(type.name) || type.name.startsWith("__")) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type + }) + }, type.name); + }) + }) + })] + }); +} +function debounce(duration, fn) { + let timeout; + return function (...args) { + if (timeout) { + window.clearTimeout(timeout); + } + timeout = window.setTimeout(() => { + timeout = null; + fn(...args); + }, duration); }; - - /** - * Renderer.renderInline(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * The same as [[Renderer.render]], but for single token of `inline` type. - **/ - Renderer.prototype.renderInline = function (tokens, options, env) { - let result = ''; - const rules = this.rules; - for (let i = 0, len = tokens.length; i < len; i++) { - const type = tokens[i].type; - if (typeof rules[type] !== 'undefined') { - result += rules[type](tokens, i, options, env, this); - } else { - result += this.renderToken(tokens, i, options); +} +function Search() { + const { + explorerNavStack, + push + } = useExplorerContext({ + nonNull: true, + caller: Search + }); + const inputRef = React.useRef(null); + const getSearchResults = useSearchResults(); + const [searchValue, setSearchValue] = React.useState(""); + const [results, setResults] = React.useState(getSearchResults(searchValue)); + const debouncedGetSearchResults = React.useMemo(() => debounce(200, search => { + setResults(getSearchResults(search)); + }), [getSearchResults]); + React.useEffect(() => { + debouncedGetSearchResults(searchValue); + }, [debouncedGetSearchResults, searchValue]); + React.useEffect(() => { + function handleKeyDown(event) { + var _a; + if (event.metaKey && event.key === "k") { + (_a = inputRef.current) == null ? void 0 : _a.focus(); } } - return result; - }; - - /** internal - * Renderer.renderInlineAsText(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * Special kludge for image `alt` attributes to conform CommonMark spec. - * Don't try to use it! Spec requires to show `alt` content with stripped markup, - * instead of simple escaping. - **/ - Renderer.prototype.renderInlineAsText = function (tokens, options, env) { - let result = ''; - for (let i = 0, len = tokens.length; i < len; i++) { - switch (tokens[i].type) { - case 'text': - result += tokens[i].content; - break; - case 'image': - result += this.renderInlineAsText(tokens[i].children, options, env); - break; - case 'html_inline': - case 'html_block': - result += tokens[i].content; - break; - case 'softbreak': - case 'hardbreak': - result += '\n'; - break; - // all other tokens are skipped - } + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, []); + const navItem = explorerNavStack.at(-1); + const onSelect = React.useCallback(def => { + push("field" in def ? { + name: def.field.name, + def: def.field + } : { + name: def.type.name, + def: def.type + }); + }, [push]); + const isFocused = React.useRef(false); + const handleFocus = React.useCallback(e => { + isFocused.current = e.type === "focus"; + }, []); + const shouldSearchBoxAppear = explorerNavStack.length === 1 || graphql.isObjectType(navItem.def) || graphql.isInterfaceType(navItem.def) || graphql.isInputObjectType(navItem.def); + if (!shouldSearchBoxAppear) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsxs(react.Combobox, { + as: "div", + className: "graphiql-doc-explorer-search", + onChange: onSelect, + "data-state": isFocused ? void 0 : "idle", + "aria-label": `Search ${navItem.name}...`, + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-search-input", + onClick: () => { + var _a; + (_a = inputRef.current) == null ? void 0 : _a.focus(); + }, + children: [/* @__PURE__ */jsxRuntime.jsx(MagnifyingGlassIcon, {}), /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Input, { + autoComplete: "off", + onFocus: handleFocus, + onBlur: handleFocus, + onChange: event => setSearchValue(event.target.value), + placeholder: "⌘ K", + ref: inputRef, + value: searchValue, + "data-cy": "doc-explorer-input" + })] + }), isFocused.current && /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Options, { + "data-cy": "doc-explorer-list", + children: [results.within.length + results.types.length + results.fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx("li", { + className: "graphiql-doc-explorer-search-empty", + children: "No results found" + }) : results.within.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { + value: result, + "data-cy": "doc-explorer-option", + children: /* @__PURE__ */jsxRuntime.jsx(Field$1, { + field: result.field, + argument: result.argument + }) + }, `within-${i}`)), results.within.length > 0 && results.types.length + results.fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-search-divider", + children: "Other results" + }) : null, results.types.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { + value: result, + "data-cy": "doc-explorer-option", + children: /* @__PURE__ */jsxRuntime.jsx(Type, { + type: result.type + }) + }, `type-${i}`)), results.fields.map((result, i) => /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Option, { + value: result, + "data-cy": "doc-explorer-option", + children: [/* @__PURE__ */jsxRuntime.jsx(Type, { + type: result.type + }), ".", /* @__PURE__ */jsxRuntime.jsx(Field$1, { + field: result.field, + argument: result.argument + })] + }, `field-${i}`))] + })] + }); +} +function useSearchResults(caller) { + const { + explorerNavStack + } = useExplorerContext({ + nonNull: true, + caller: caller || useSearchResults + }); + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: caller || useSearchResults + }); + const navItem = explorerNavStack.at(-1); + return React.useCallback(searchValue => { + const matches = { + within: [], + types: [], + fields: [] + }; + if (!schema) { + return matches; } - return result; - }; - - /** - * Renderer.render(tokens, options, env) -> String - * - tokens (Array): list on block tokens to render - * - options (Object): params of parser instance - * - env (Object): additional data from parsed input (references, for example) - * - * Takes token stream and generates HTML. Probably, you will never need to call - * this method directly. - **/ - Renderer.prototype.render = function (tokens, options, env) { - let result = ''; - const rules = this.rules; - for (let i = 0, len = tokens.length; i < len; i++) { - const type = tokens[i].type; - if (type === 'inline') { - result += this.renderInline(tokens[i].children, options, env); - } else if (typeof rules[type] !== 'undefined') { - result += rules[type](tokens, i, options, env, this); - } else { - result += this.renderToken(tokens, i, options, env); - } + const withinType = navItem.def; + const typeMap = schema.getTypeMap(); + let typeNames = Object.keys(typeMap); + if (withinType) { + typeNames = typeNames.filter(n => n !== withinType.name); + typeNames.unshift(withinType.name); } - return result; - }; - - /** - * class Ruler - * - * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and - * [[MarkdownIt#inline]] to manage sequences of functions (rules): - * - * - keep rules in defined order - * - assign the name to each rule - * - enable/disable rules - * - add/replace rules - * - allow assign rules to additional named chains (in the same) - * - cacheing lists of active rules - * - * You will not need use this class directly until write plugins. For simple - * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and - * [[MarkdownIt.use]]. - **/ - - /** - * new Ruler() - **/ - function Ruler() { - // List of added rules. Each element is: - // - // { - // name: XXX, - // enabled: Boolean, - // fn: Function(), - // alt: [ name2, name3 ] - // } - // - this.__rules__ = []; - - // Cached rule chains. - // - // First level - chain name, '' for default. - // Second level - diginal anchor for fast filtering by charcodes. - // - this.__cache__ = null; - } - - // Helper methods, should not be used directly - - // Find rule index by name - // - Ruler.prototype.__find__ = function (name) { - for (let i = 0; i < this.__rules__.length; i++) { - if (this.__rules__[i].name === name) { - return i; + for (const typeName of typeNames) { + if (matches.within.length + matches.types.length + matches.fields.length >= 100) { + break; + } + const type = typeMap[typeName]; + if (withinType !== type && isMatch(typeName, searchValue)) { + matches.types.push({ + type + }); } - } - return -1; - }; - - // Build rules lookup cache - // - Ruler.prototype.__compile__ = function () { - const self = this; - const chains = ['']; - - // collect unique names - self.__rules__.forEach(function (rule) { - if (!rule.enabled) { - return; + if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { + continue; } - rule.alt.forEach(function (altName) { - if (chains.indexOf(altName) < 0) { - chains.push(altName); + const fields = type.getFields(); + for (const fieldName in fields) { + const field = fields[fieldName]; + let matchingArgs; + if (!isMatch(fieldName, searchValue)) { + if ("args" in field) { + matchingArgs = field.args.filter(arg => isMatch(arg.name, searchValue)); + if (matchingArgs.length === 0) { + continue; + } + } else { + continue; + } } + matches[withinType === type ? "within" : "fields"].push(...(matchingArgs ? matchingArgs.map(argument => ({ + type, + field, + argument + })) : [{ + type, + field + }])); + } + } + return matches; + }, [navItem.def, schema]); +} +function isMatch(sourceText, searchValue) { + try { + const escaped = searchValue.replaceAll(/[^_0-9A-Za-z]/g, ch => "\\" + ch); + return sourceText.search(new RegExp(escaped, "i")) !== -1; + } catch { + return sourceText.toLowerCase().includes(searchValue.toLowerCase()); + } +} +function Type(props) { + return /* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-type", + children: props.type.name + }); +} +function Field$1({ + field, + argument +}) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-field", + children: field.name + }), argument ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-argument", + children: argument.name + }), ":", " ", renderType(argument.type, namedType => /* @__PURE__ */jsxRuntime.jsx(Type, { + type: namedType + })), ")"] + }) : null] + }); +} +function FieldLink(props) { + const { + push + } = useExplorerContext({ + nonNull: true + }); + return /* @__PURE__ */jsxRuntime.jsx("a", { + className: "graphiql-doc-explorer-field-name", + onClick: event => { + event.preventDefault(); + push({ + name: props.field.name, + def: props.field }); + }, + href: "#", + children: props.field.name + }); +} +function TypeDocumentation(props) { + return graphql.isNamedType(props.type) ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [props.type.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.type.description + }) : null, /* @__PURE__ */jsxRuntime.jsx(ImplementsInterfaces, { + type: props.type + }), /* @__PURE__ */jsxRuntime.jsx(Fields, { + type: props.type + }), /* @__PURE__ */jsxRuntime.jsx(EnumValues, { + type: props.type + }), /* @__PURE__ */jsxRuntime.jsx(PossibleTypes, { + type: props.type + })] + }) : null; +} +function ImplementsInterfaces({ + type +}) { + if (!graphql.isObjectType(type)) { + return null; + } + const interfaces = type.getInterfaces(); + return interfaces.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Implements", + children: type.getInterfaces().map(implementedInterface => /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: implementedInterface + }) + }, implementedInterface.name)) + }) : null; +} +function Fields({ + type +}) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { + return null; + } + const fieldMap = type.getFields(); + const fields = []; + const deprecatedFields = []; + for (const field of Object.keys(fieldMap).map(name => fieldMap[name])) { + if (field.deprecationReason) { + deprecatedFields.push(field); + } else { + fields.push(field); + } + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Fields", + children: fields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { + field + }, field.name)) + }) : null, deprecatedFields.length > 0 ? showDeprecated || fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Fields", + children: deprecatedFields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { + field + }, field.name)) + }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Fields" + }) : null] + }); +} +function Field({ + field +}) { + const args = "args" in field ? field.args.filter(arg => !arg.deprecationReason) : []; + return /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-item", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx(FieldLink, { + field + }), args.length > 0 ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { + children: args.map(arg => args.length === 1 ? /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg, + inline: true + }, arg.name) : /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-argument-multiple", + children: /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg, + inline: true + }) + }, arg.name)) + }), ")"] + }) : null, ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: field.type + }), /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { + field + })] + }), field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + onlyShowFirstChild: true, + children: field.description + }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { + children: field.deprecationReason + })] + }); +} +function EnumValues({ + type +}) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!graphql.isEnumType(type)) { + return null; + } + const values = []; + const deprecatedValues = []; + for (const value of type.getValues()) { + if (value.deprecationReason) { + deprecatedValues.push(value); + } else { + values.push(value); + } + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [values.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Enum Values", + children: values.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { + value + }, value.name)) + }) : null, deprecatedValues.length > 0 ? showDeprecated || values.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Enum Values", + children: deprecatedValues.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { + value + }, value.name)) + }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Values" + }) : null] + }); +} +function EnumValue({ + value +}) { + return /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-item", + children: [/* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-enum-value", + children: value.name + }), value.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: value.description + }) : null, value.deprecationReason ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + children: value.deprecationReason + }) : null] + }); +} +function PossibleTypes({ + type +}) { + const { + schema + } = useSchemaContext({ + nonNull: true + }); + if (!schema || !graphql.isAbstractType(type)) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: graphql.isInterfaceType(type) ? "Implementations" : "Possible Types", + children: schema.getPossibleTypes(type).map(possibleType => /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: possibleType + }) + }, possibleType.name)) + }); +} +function DocExplorer() { + const { + fetchError, + isFetching, + schema, + validationErrors + } = useSchemaContext({ + nonNull: true, + caller: DocExplorer + }); + const { + explorerNavStack, + pop + } = useExplorerContext({ + nonNull: true, + caller: DocExplorer + }); + const navItem = explorerNavStack.at(-1); + let content = null; + if (fetchError) { + content = /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-error", + children: "Error fetching schema" }); - self.__cache__ = {}; - chains.forEach(function (chain) { - self.__cache__[chain] = []; - self.__rules__.forEach(function (rule) { - if (!rule.enabled) { - return; - } - if (chain && rule.alt.indexOf(chain) < 0) { - return; - } - self.__cache__[chain].push(rule.fn); - }); + } else if (validationErrors.length > 0) { + content = /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-error", + children: ["Schema is invalid: ", validationErrors[0].message] }); - }; - - /** - * Ruler.at(name, fn [, options]) - * - name (String): rule name to replace. - * - fn (Function): new rule function. - * - options (Object): new rule options (not mandatory). - * - * Replace rule by name with new function & options. Throws error if name not - * found. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * Replace existing typographer replacement rule with new one: - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.core.ruler.at('replacements', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.at = function (name, fn, options) { - const index = this.__find__(name); - const opt = options || {}; - if (index === -1) { - throw new Error('Parser rule not found: ' + name); - } - this.__rules__[index].fn = fn; - this.__rules__[index].alt = opt.alt || []; - this.__cache__ = null; - }; - - /** - * Ruler.before(beforeName, ruleName, fn [, options]) - * - beforeName (String): new rule will be added before this one. - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Add new rule to chain before one with given name. See also - * [[Ruler.after]], [[Ruler.push]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.before = function (beforeName, ruleName, fn, options) { - const index = this.__find__(beforeName); - const opt = options || {}; - if (index === -1) { - throw new Error('Parser rule not found: ' + beforeName); - } - this.__rules__.splice(index, 0, { - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [] + } else if (isFetching) { + content = /* @__PURE__ */jsxRuntime.jsx(Spinner, {}); + } else if (!schema) { + content = /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-error", + children: "No GraphQL schema available" }); - this.__cache__ = null; - }; - - /** - * Ruler.after(afterName, ruleName, fn [, options]) - * - afterName (String): new rule will be added after this one. - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Add new rule to chain after one with given name. See also - * [[Ruler.before]], [[Ruler.push]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.inline.ruler.after('text', 'my_rule', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.after = function (afterName, ruleName, fn, options) { - const index = this.__find__(afterName); - const opt = options || {}; - if (index === -1) { - throw new Error('Parser rule not found: ' + afterName); - } - this.__rules__.splice(index + 1, 0, { - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [] + } else if (explorerNavStack.length === 1) { + content = /* @__PURE__ */jsxRuntime.jsx(SchemaDocumentation, { + schema }); - this.__cache__ = null; - }; - - /** - * Ruler.push(ruleName, fn [, options]) - * - ruleName (String): name of added rule. - * - fn (Function): rule function. - * - options (Object): rule options (not mandatory). - * - * Push new rule to the end of chain. See also - * [[Ruler.before]], [[Ruler.after]]. - * - * ##### Options: - * - * - __alt__ - array with names of "alternate" chains. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * md.core.ruler.push('my_rule', function replace(state) { - * //... - * }); - * ``` - **/ - Ruler.prototype.push = function (ruleName, fn, options) { - const opt = options || {}; - this.__rules__.push({ - name: ruleName, - enabled: true, - fn, - alt: opt.alt || [] + } else if (graphql.isType(navItem.def)) { + content = /* @__PURE__ */jsxRuntime.jsx(TypeDocumentation, { + type: navItem.def }); - this.__cache__ = null; - }; - - /** - * Ruler.enable(list [, ignoreInvalid]) -> Array - * - list (String|Array): list of rule names to enable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable rules with given names. If any rule name not found - throw Error. - * Errors can be disabled by second param. - * - * Returns list of found rule names (if no exception happened). - * - * See also [[Ruler.disable]], [[Ruler.enableOnly]]. - **/ - Ruler.prototype.enable = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; - } - const result = []; - - // Search by name and enable - list.forEach(function (name) { - const idx = this.__find__(name); - if (idx < 0) { - if (ignoreInvalid) { - return; - } - throw new Error('Rules manager: invalid rule name ' + name); + } else if (navItem.def) { + content = /* @__PURE__ */jsxRuntime.jsx(FieldDocumentation, { + field: navItem.def + }); + } + let prevName; + if (explorerNavStack.length > 1) { + prevName = explorerNavStack.at(-2).name; + } + return /* @__PURE__ */jsxRuntime.jsxs("section", { + className: "graphiql-doc-explorer", + "aria-label": "Documentation Explorer", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-header", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-header-content", + children: [prevName && /* @__PURE__ */jsxRuntime.jsxs("a", { + href: "#", + className: "graphiql-doc-explorer-back", + onClick: event => { + event.preventDefault(); + pop(); + }, + "aria-label": `Go back to ${prevName}`, + children: [/* @__PURE__ */jsxRuntime.jsx(ChevronLeftIcon, {}), prevName] + }), /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-title", + children: navItem.name + })] + }), /* @__PURE__ */jsxRuntime.jsx(Search, {}, navItem.name)] + }), /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-content", + children: content + })] + }); +} +const DOC_EXPLORER_PLUGIN = { + title: "Documentation Explorer", + icon: function Icon() { + const pluginContext = usePluginContext(); + return (pluginContext == null ? void 0 : pluginContext.visiblePlugin) === DOC_EXPLORER_PLUGIN ? /* @__PURE__ */jsxRuntime.jsx(DocsFilledIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(DocsIcon, {}); + }, + content: DocExplorer +}; +const HISTORY_PLUGIN = { + title: "History", + icon: HistoryIcon, + content: History +}; +const PluginContext = createNullableContext("PluginContext"); +function PluginContextProvider(props) { + const storage = useStorageContext(); + const explorerContext = useExplorerContext(); + const historyContext = useHistoryContext(); + const hasExplorerContext = Boolean(explorerContext); + const hasHistoryContext = Boolean(historyContext); + const plugins = React.useMemo(() => { + const pluginList = []; + const pluginTitles = {}; + if (hasExplorerContext) { + pluginList.push(DOC_EXPLORER_PLUGIN); + pluginTitles[DOC_EXPLORER_PLUGIN.title] = true; + } + if (hasHistoryContext) { + pluginList.push(HISTORY_PLUGIN); + pluginTitles[HISTORY_PLUGIN.title] = true; + } + for (const plugin of props.plugins || []) { + if (typeof plugin.title !== "string" || !plugin.title) { + throw new Error("All GraphiQL plugins must have a unique title"); + } + if (pluginTitles[plugin.title]) { + throw new Error(`All GraphiQL plugins must have a unique title, found two plugins with the title '${plugin.title}'`); + } else { + pluginList.push(plugin); + pluginTitles[plugin.title] = true; } - this.__rules__[idx].enabled = true; - result.push(name); - }, this); - this.__cache__ = null; - return result; - }; - - /** - * Ruler.enableOnly(list [, ignoreInvalid]) - * - list (String|Array): list of rule names to enable (whitelist). - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable rules with given names, and disable everything else. If any rule name - * not found - throw Error. Errors can be disabled by second param. - * - * See also [[Ruler.disable]], [[Ruler.enable]]. - **/ - Ruler.prototype.enableOnly = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; } - this.__rules__.forEach(function (rule) { - rule.enabled = false; - }); - this.enable(list, ignoreInvalid); - }; - - /** - * Ruler.disable(list [, ignoreInvalid]) -> Array - * - list (String|Array): list of rule names to disable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Disable rules with given names. If any rule name not found - throw Error. - * Errors can be disabled by second param. - * - * Returns list of found rule names (if no exception happened). - * - * See also [[Ruler.enable]], [[Ruler.enableOnly]]. - **/ - Ruler.prototype.disable = function (list, ignoreInvalid) { - if (!Array.isArray(list)) { - list = [list]; + return pluginList; + }, [hasExplorerContext, hasHistoryContext, props.plugins]); + const [visiblePlugin, internalSetVisiblePlugin] = React.useState(() => { + const storedValue = storage == null ? void 0 : storage.get(STORAGE_KEY$4); + const pluginForStoredValue = plugins.find(plugin => plugin.title === storedValue); + if (pluginForStoredValue) { + return pluginForStoredValue; } - const result = []; - - // Search by name and disable - list.forEach(function (name) { - const idx = this.__find__(name); - if (idx < 0) { - if (ignoreInvalid) { - return; - } - throw new Error('Rules manager: invalid rule name ' + name); + if (storedValue) { + storage == null ? void 0 : storage.set(STORAGE_KEY$4, ""); + } + if (!props.visiblePlugin) { + return null; + } + return plugins.find(plugin => (typeof props.visiblePlugin === "string" ? plugin.title : plugin) === props.visiblePlugin) || null; + }); + const { + onTogglePluginVisibility, + children + } = props; + const setVisiblePlugin = React.useCallback(plugin => { + const newVisiblePlugin = plugin ? plugins.find(p => (typeof plugin === "string" ? p.title : p) === plugin) || null : null; + internalSetVisiblePlugin(current => { + if (newVisiblePlugin === current) { + return current; } - this.__rules__[idx].enabled = false; - result.push(name); - }, this); - this.__cache__ = null; - return result; - }; - - /** - * Ruler.getRules(chainName) -> Array - * - * Return array of active functions (rules) for given chain name. It analyzes - * rules configuration, compiles caches if not exists and returns result. - * - * Default chain name is `''` (empty string). It can't be skipped. That's - * done intentionally, to keep signature monomorphic for high speed. - **/ - Ruler.prototype.getRules = function (chainName) { - if (this.__cache__ === null) { - this.__compile__(); + onTogglePluginVisibility == null ? void 0 : onTogglePluginVisibility(newVisiblePlugin); + return newVisiblePlugin; + }); + }, [onTogglePluginVisibility, plugins]); + React.useEffect(() => { + if (props.visiblePlugin) { + setVisiblePlugin(props.visiblePlugin); + } + }, [plugins, props.visiblePlugin, setVisiblePlugin]); + const value = React.useMemo(() => ({ + plugins, + setVisiblePlugin, + visiblePlugin + }), [plugins, setVisiblePlugin, visiblePlugin]); + return /* @__PURE__ */jsxRuntime.jsx(PluginContext.Provider, { + value, + children + }); +} +const usePluginContext = createContextHook(PluginContext); +const STORAGE_KEY$4 = "visiblePlugin"; +function onHasCompletion(_cm, data, schema, explorer, plugin, callback) { + void importCodeMirror([], { + useCommonAddons: false + }).then(CodeMirror => { + let information; + let fieldName; + let typeNamePill; + let typeNamePrefix; + let typeName; + let typeNameSuffix; + let description; + let deprecation; + let deprecationReason; + CodeMirror.on(data, "select", + // @ts-expect-error + (ctx, el) => { + if (!information) { + const hintsUl = el.parentNode; + information = document.createElement("div"); + information.className = "CodeMirror-hint-information"; + hintsUl.append(information); + const header = document.createElement("header"); + header.className = "CodeMirror-hint-information-header"; + information.append(header); + fieldName = document.createElement("span"); + fieldName.className = "CodeMirror-hint-information-field-name"; + header.append(fieldName); + typeNamePill = document.createElement("span"); + typeNamePill.className = "CodeMirror-hint-information-type-name-pill"; + header.append(typeNamePill); + typeNamePrefix = document.createElement("span"); + typeNamePill.append(typeNamePrefix); + typeName = document.createElement("a"); + typeName.className = "CodeMirror-hint-information-type-name"; + typeName.href = "javascript:void 0"; + typeName.addEventListener("click", onClickHintInformation); + typeNamePill.append(typeName); + typeNameSuffix = document.createElement("span"); + typeNamePill.append(typeNameSuffix); + description = document.createElement("div"); + description.className = "CodeMirror-hint-information-description"; + information.append(description); + deprecation = document.createElement("div"); + deprecation.className = "CodeMirror-hint-information-deprecation"; + information.append(deprecation); + const deprecationLabel = document.createElement("span"); + deprecationLabel.className = "CodeMirror-hint-information-deprecation-label"; + deprecationLabel.textContent = "Deprecated"; + deprecation.append(deprecationLabel); + deprecationReason = document.createElement("div"); + deprecationReason.className = "CodeMirror-hint-information-deprecation-reason"; + deprecation.append(deprecationReason); + const defaultInformationPadding = parseInt(window.getComputedStyle(information).paddingBottom.replace(/px$/, ""), 10) || 0; + const defaultInformationMaxHeight = parseInt(window.getComputedStyle(information).maxHeight.replace(/px$/, ""), 10) || 0; + const handleScroll = () => { + if (information) { + information.style.paddingTop = hintsUl.scrollTop + defaultInformationPadding + "px"; + information.style.maxHeight = hintsUl.scrollTop + defaultInformationMaxHeight + "px"; + } + }; + hintsUl.addEventListener("scroll", handleScroll); + let onRemoveFn; + hintsUl.addEventListener("DOMNodeRemoved", onRemoveFn = event => { + if (event.target !== hintsUl) { + return; + } + hintsUl.removeEventListener("scroll", handleScroll); + hintsUl.removeEventListener("DOMNodeRemoved", onRemoveFn); + if (information) { + information.removeEventListener("click", onClickHintInformation); + } + information = null; + fieldName = null; + typeNamePill = null; + typeNamePrefix = null; + typeName = null; + typeNameSuffix = null; + description = null; + deprecation = null; + deprecationReason = null; + onRemoveFn = null; + }); + } + if (fieldName) { + fieldName.textContent = ctx.text; + } + if (typeNamePill && typeNamePrefix && typeName && typeNameSuffix) { + if (ctx.type) { + typeNamePill.style.display = "inline"; + const renderType2 = type => { + if (graphql.isNonNullType(type)) { + typeNameSuffix.textContent = "!" + typeNameSuffix.textContent; + renderType2(type.ofType); + } else if (graphql.isListType(type)) { + typeNamePrefix.textContent += "["; + typeNameSuffix.textContent = "]" + typeNameSuffix.textContent; + renderType2(type.ofType); + } else { + typeName.textContent = type.name; + } + }; + typeNamePrefix.textContent = ""; + typeNameSuffix.textContent = ""; + renderType2(ctx.type); + } else { + typeNamePrefix.textContent = ""; + typeName.textContent = ""; + typeNameSuffix.textContent = ""; + typeNamePill.style.display = "none"; + } + } + if (description) { + if (ctx.description) { + description.style.display = "block"; + description.innerHTML = markdown.render(ctx.description); + } else { + description.style.display = "none"; + description.innerHTML = ""; + } + } + if (deprecation && deprecationReason) { + if (ctx.deprecationReason) { + deprecation.style.display = "block"; + deprecationReason.innerHTML = markdown.render(ctx.deprecationReason); + } else { + deprecation.style.display = "none"; + deprecationReason.innerHTML = ""; + } + } + }); + }); + function onClickHintInformation(event) { + if (!schema || !explorer || !plugin || !(event.currentTarget instanceof HTMLElement)) { + return; + } + const typeName = event.currentTarget.textContent || ""; + const type = schema.getType(typeName); + if (type) { + plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); + explorer.push({ + name: type.name, + def: type + }); + callback == null ? void 0 : callback(type); } - - // Chain can be empty, if rules disabled. But we still have to return Array. - return this.__cache__[chainName] || []; - }; - - // Token class - - /** - * class Token - **/ - - /** - * new Token(type, tag, nesting) - * - * Create new token and fill passed properties. - **/ - function Token(type, tag, nesting) { - /** - * Token#type -> String - * - * Type of the token (string, e.g. "paragraph_open") - **/ - this.type = type; - - /** - * Token#tag -> String - * - * html tag name, e.g. "p" - **/ - this.tag = tag; - - /** - * Token#attrs -> Array - * - * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` - **/ - this.attrs = null; - - /** - * Token#map -> Array - * - * Source map info. Format: `[ line_begin, line_end ]` - **/ - this.map = null; - - /** - * Token#nesting -> Number - * - * Level change (number in {-1, 0, 1} set), where: - * - * - `1` means the tag is opening - * - `0` means the tag is self-closing - * - `-1` means the tag is closing - **/ - this.nesting = nesting; - - /** - * Token#level -> Number - * - * nesting level, the same as `state.level` - **/ - this.level = 0; - - /** - * Token#children -> Array - * - * An array of child nodes (inline and img tokens) - **/ - this.children = null; - - /** - * Token#content -> String - * - * In a case of self-closing tag (code, html, fence, etc.), - * it has contents of this tag. - **/ - this.content = ''; - - /** - * Token#markup -> String - * - * '*' or '_' for emphasis, fence string for fence, etc. - **/ - this.markup = ''; - - /** - * Token#info -> String - * - * Additional information: - * - * - Info string for "fence" tokens - * - The value "auto" for autolink "link_open" and "link_close" tokens - * - The string value of the item marker for ordered-list "list_item_open" tokens - **/ - this.info = ''; - - /** - * Token#meta -> Object - * - * A place for plugins to store an arbitrary data - **/ - this.meta = null; - - /** - * Token#block -> Boolean - * - * True for block-level tokens, false for inline tokens. - * Used in renderer to calculate line breaks - **/ - this.block = false; - - /** - * Token#hidden -> Boolean - * - * If it's true, ignore this element when rendering. Used for tight lists - * to hide paragraphs. - **/ - this.hidden = false; } - - /** - * Token.attrIndex(name) -> Number - * - * Search attribute index by name. - **/ - Token.prototype.attrIndex = function attrIndex(name) { - if (!this.attrs) { - return -1; +} +function useSynchronizeValue(editor, value) { + React.useEffect(() => { + if (editor && typeof value === "string" && value !== editor.getValue()) { + editor.setValue(value); + } + }, [editor, value]); +} +function useSynchronizeOption(editor, option, value) { + React.useEffect(() => { + if (editor) { + editor.setOption(option, value); + } + }, [editor, option, value]); +} +function useChangeHandler(editor, callback, storageKey, tabProperty, caller) { + const { + updateActiveTabValues + } = useEditorContext({ + nonNull: true, + caller + }); + const storage = useStorageContext(); + React.useEffect(() => { + if (!editor) { + return; } - const attrs = this.attrs; - for (let i = 0, len = attrs.length; i < len; i++) { - if (attrs[i][0] === name) { - return i; + const store = debounce(500, value => { + if (!storage || storageKey === null) { + return; + } + storage.set(storageKey, value); + }); + const updateTab = debounce(100, value => { + updateActiveTabValues({ + [tabProperty]: value + }); + }); + const handleChange = (editorInstance, changeObj) => { + if (!changeObj) { + return; } + const newValue = editorInstance.getValue(); + store(newValue); + updateTab(newValue); + callback == null ? void 0 : callback(newValue); + }; + editor.on("change", handleChange); + return () => editor.off("change", handleChange); + }, [callback, editor, storage, storageKey, tabProperty, updateActiveTabValues]); +} +function useCompletion(editor, callback, caller) { + const { + schema + } = useSchemaContext({ + nonNull: true, + caller + }); + const explorer = useExplorerContext(); + const plugin = usePluginContext(); + React.useEffect(() => { + if (!editor) { + return; } - return -1; - }; - - /** - * Token.attrPush(attrData) - * - * Add `[ name, value ]` attribute to list. Init attrs if necessary - **/ - Token.prototype.attrPush = function attrPush(attrData) { - if (this.attrs) { - this.attrs.push(attrData); - } else { - this.attrs = [attrData]; + const handleCompletion = (instance, changeObj) => { + onHasCompletion(instance, changeObj, schema, explorer, plugin, type => { + callback == null ? void 0 : callback({ + kind: "Type", + type, + schema: schema || void 0 + }); + }); + }; + editor.on( + // @ts-expect-error @TODO additional args for hasCompletion event + "hasCompletion", handleCompletion); + return () => editor.off( + // @ts-expect-error @TODO additional args for hasCompletion event + "hasCompletion", handleCompletion); + }, [callback, editor, explorer, plugin, schema]); +} +function useKeyMap(editor, keys, callback) { + React.useEffect(() => { + if (!editor) { + return; } - }; - - /** - * Token.attrSet(name, value) - * - * Set `name` attribute to `value`. Override old value if exists. - **/ - Token.prototype.attrSet = function attrSet(name, value) { - const idx = this.attrIndex(name); - const attrData = [name, value]; - if (idx < 0) { - this.attrPush(attrData); - } else { - this.attrs[idx] = attrData; + for (const key of keys) { + editor.removeKeyMap(key); } - }; - - /** - * Token.attrGet(name) - * - * Get the value of attribute `name`, or null if it does not exist. - **/ - Token.prototype.attrGet = function attrGet(name) { - const idx = this.attrIndex(name); - let value = null; - if (idx >= 0) { - value = this.attrs[idx][1]; + if (callback) { + const keyMap = {}; + for (const key of keys) { + keyMap[key] = () => callback(); + } + editor.addKeyMap(keyMap); } - return value; - }; - - /** - * Token.attrJoin(name, value) - * - * Join value to existing attribute via space. Or create new attribute if not - * exists. Useful to operate with token classes. - **/ - Token.prototype.attrJoin = function attrJoin(name, value) { - const idx = this.attrIndex(name); - if (idx < 0) { - this.attrPush([name, value]); - } else { - this.attrs[idx][1] = this.attrs[idx][1] + ' ' + value; + }, [editor, keys, callback]); +} +function useCopyQuery({ + caller, + onCopyQuery +} = {}) { + const { + queryEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useCopyQuery + }); + return React.useCallback(() => { + if (!queryEditor) { + return; } - }; - - // Core state object - // - - function StateCore(src, md, env) { - this.src = src; - this.env = env; - this.tokens = []; - this.inlineMode = false; - this.md = md; // link to parser instance - } - - // re-export Token class to use in core rules - StateCore.prototype.Token = Token; - - // Normalize input string - - // https://spec.commonmark.org/0.29/#line-ending - const NEWLINES_RE = /\r\n?|\n/g; - const NULL_RE = /\0/g; - function normalize(state) { - let str; - - // Normalize newlines - str = state.src.replace(NEWLINES_RE, '\n'); - - // Replace NULL characters - str = str.replace(NULL_RE, '\uFFFD'); - state.src = str; - } - function block(state) { - let token; - if (state.inlineMode) { - token = new state.Token('inline', '', 0); - token.content = state.src; - token.map = [0, 1]; - token.children = []; - state.tokens.push(token); - } else { - state.md.block.parse(state.src, state.md, state.env, state.tokens); + const query = queryEditor.getValue(); + copyToClipboard(query); + onCopyQuery == null ? void 0 : onCopyQuery(query); + }, [queryEditor, onCopyQuery]); +} +function useMergeQuery({ + caller +} = {}) { + const { + queryEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useMergeQuery + }); + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: useMergeQuery + }); + return React.useCallback(() => { + const documentAST = queryEditor == null ? void 0 : queryEditor.documentAST; + const query = queryEditor == null ? void 0 : queryEditor.getValue(); + if (!documentAST || !query) { + return; } - } - function inline(state) { - const tokens = state.tokens; - - // Parse inlines - for (let i = 0, l = tokens.length; i < l; i++) { - const tok = tokens[i]; - if (tok.type === 'inline') { - state.md.inline.parse(tok.content, state.md, state.env, tok.children); + queryEditor.setValue(graphql.print(toolkit.mergeAst(documentAST, schema))); + }, [queryEditor, schema]); +} +function usePrettifyEditors({ + caller +} = {}) { + const { + queryEditor, + headerEditor, + variableEditor + } = useEditorContext({ + nonNull: true, + caller: caller || usePrettifyEditors + }); + return React.useCallback(() => { + if (variableEditor) { + const variableEditorContent = variableEditor.getValue(); + try { + const prettifiedVariableEditorContent = JSON.stringify(JSON.parse(variableEditorContent), null, 2); + if (prettifiedVariableEditorContent !== variableEditorContent) { + variableEditor.setValue(prettifiedVariableEditorContent); + } + } catch {} + } + if (headerEditor) { + const headerEditorContent = headerEditor.getValue(); + try { + const prettifiedHeaderEditorContent = JSON.stringify(JSON.parse(headerEditorContent), null, 2); + if (prettifiedHeaderEditorContent !== headerEditorContent) { + headerEditor.setValue(prettifiedHeaderEditorContent); + } + } catch {} + } + if (queryEditor) { + const editorContent = queryEditor.getValue(); + const prettifiedEditorContent = graphql.print(graphql.parse(editorContent)); + if (prettifiedEditorContent !== editorContent) { + queryEditor.setValue(prettifiedEditorContent); } } - } - - // Replace link-like texts with link nodes. - // - // Currently restricted by `md.validateLink()` to http/https/ftp - // - - function isLinkOpen$1(str) { - return /^\s]/i.test(str); - } - function isLinkClose$1(str) { - return /^<\/a\s*>/i.test(str); - } - function linkify$1(state) { - const blockTokens = state.tokens; - if (!state.md.options.linkify) { + }, [queryEditor, variableEditor, headerEditor]); +} +function useAutoCompleteLeafs({ + getDefaultFieldNames, + caller +} = {}) { + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: caller || useAutoCompleteLeafs + }); + const { + queryEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useAutoCompleteLeafs + }); + return React.useCallback(() => { + if (!queryEditor) { return; } - for (let j = 0, l = blockTokens.length; j < l; j++) { - if (blockTokens[j].type !== 'inline' || !state.md.linkify.pretest(blockTokens[j].content)) { - continue; - } - let tokens = blockTokens[j].children; - let htmlLinkLevel = 0; - - // We scan from the end, to keep position when new tags added. - // Use reversed logic in links start/end match - for (let i = tokens.length - 1; i >= 0; i--) { - const currentToken = tokens[i]; - - // Skip content of markdown links - if (currentToken.type === 'link_close') { - i--; - while (tokens[i].level !== currentToken.level && tokens[i].type !== 'link_open') { - i--; - } - continue; - } - - // Skip content of html tag links - if (currentToken.type === 'html_inline') { - if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) { - htmlLinkLevel--; + const query = queryEditor.getValue(); + const { + insertions, + result + } = toolkit.fillLeafs(schema, query, getDefaultFieldNames); + if (insertions && insertions.length > 0) { + queryEditor.operation(() => { + const cursor = queryEditor.getCursor(); + const cursorIndex = queryEditor.indexFromPos(cursor); + queryEditor.setValue(result || ""); + let added = 0; + const markers = insertions.map(({ + index, + string + }) => queryEditor.markText(queryEditor.posFromIndex(index + added), queryEditor.posFromIndex(index + (added += string.length)), { + className: "auto-inserted-leaf", + clearOnEnter: true, + title: "Automatically added leaf fields" + })); + setTimeout(() => { + for (const marker of markers) { + marker.clear(); } - if (isLinkClose$1(currentToken.content)) { - htmlLinkLevel++; + }, 7e3); + let newCursorIndex = cursorIndex; + for (const { + index, + string + } of insertions) { + if (index < cursorIndex) { + newCursorIndex += string.length; } } - if (htmlLinkLevel > 0) { - continue; + queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex)); + }); + } + return result; + }, [getDefaultFieldNames, queryEditor, schema]); +} +const useEditorState = editor => { + var _ref2; + const context = useEditorContext({ + nonNull: true + }); + const editorInstance = context[`${editor}Editor`]; + let valueString = ""; + const editorValue = (_ref2 = editorInstance == null ? void 0 : editorInstance.getValue()) !== null && _ref2 !== void 0 ? _ref2 : false; + if (editorValue && editorValue.length > 0) { + valueString = editorValue; + } + const handleEditorValue = React.useCallback(value => editorInstance == null ? void 0 : editorInstance.setValue(value), [editorInstance]); + return React.useMemo(() => [valueString, handleEditorValue], [valueString, handleEditorValue]); +}; +const useOperationsEditorState = () => { + return useEditorState("query"); +}; +const useVariablesEditorState = () => { + return useEditorState("variable"); +}; +const useHeadersEditorState = () => { + return useEditorState("header"); +}; +function useOptimisticState([upstreamState, upstreamSetState]) { + const lastStateRef = React.useRef({ + /** The last thing that we sent upstream; we're expecting this back */ + pending: null, + /** The last thing we received from upstream */ + last: upstreamState + }); + const [state, setOperationsText] = React.useState(upstreamState); + React.useEffect(() => { + if (lastStateRef.current.last === upstreamState) ;else { + lastStateRef.current.last = upstreamState; + if (lastStateRef.current.pending === null) { + setOperationsText(upstreamState); + } else if (lastStateRef.current.pending === upstreamState) { + lastStateRef.current.pending = null; + if (upstreamState !== state) { + lastStateRef.current.pending = state; + upstreamSetState(state); } - if (currentToken.type === 'text' && state.md.linkify.test(currentToken.content)) { - const text = currentToken.content; - let links = state.md.linkify.match(text); - - // Now split string to nodes - const nodes = []; - let level = currentToken.level; - let lastPos = 0; - - // forbid escape sequence at the start of the string, - // this avoids http\://example.com/ from being linkified as - // http://example.com/ - if (links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === 'text_special') { - links = links.slice(1); - } - for (let ln = 0; ln < links.length; ln++) { - const url = links[ln].url; - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) { - continue; - } - let urlText = links[ln].text; - - // Linkifier might send raw hostnames like "example.com", where url - // starts with domain name. So we prepend http:// in those cases, - // and remove it afterwards. - // - if (!links[ln].schema) { - urlText = state.md.normalizeLinkText('http://' + urlText).replace(/^http:\/\//, ''); - } else if (links[ln].schema === 'mailto:' && !/^mailto:/i.test(urlText)) { - urlText = state.md.normalizeLinkText('mailto:' + urlText).replace(/^mailto:/, ''); - } else { - urlText = state.md.normalizeLinkText(urlText); + } else { + lastStateRef.current.pending = null; + setOperationsText(upstreamState); + } + } + }, [upstreamState, state, upstreamSetState]); + const setState = React.useCallback(newState => { + setOperationsText(newState); + if (lastStateRef.current.pending === null && lastStateRef.current.last !== newState) { + lastStateRef.current.pending = newState; + upstreamSetState(newState); + } + }, [upstreamSetState]); + return React.useMemo(() => [state, setState], [state, setState]); +} +function useHeaderEditor({ + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onEdit, + readOnly = false +} = {}, caller) { + const { + initialHeaders, + headerEditor, + setHeaderEditor, + shouldPersistHeaders + } = useEditorContext({ + nonNull: true, + caller: caller || useHeaderEditor + }); + const executionContext = useExecutionContext(); + const merge = useMergeQuery({ + caller: caller || useHeaderEditor + }); + const prettify = usePrettifyEditors({ + caller: caller || useHeaderEditor + }); + const ref = React.useRef(null); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([ + // @ts-expect-error + Promise.resolve().then(() => __webpack_require__(/*! ./javascript.cjs.js */ "../../graphiql-react/dist/javascript.cjs.js")).then(n => n.javascript)]).then(CodeMirror => { + if (!isActive) { + return; + } + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialHeaders, + lineNumbers: true, + tabSize: 2, + mode: { + name: "javascript", + json: true + }, + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: commonKeys + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + }, + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + }, + "Alt-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + } + }); + newEditor.on("keyup", (editorInstance, event) => { + const { + code, + key, + shiftKey + } = event; + const isLetter = code.startsWith("Key"); + const isNumber = !shiftKey && code.startsWith("Digit"); + if (isLetter || isNumber || key === "_" || key === '"') { + editorInstance.execCommand("autocomplete"); + } + }); + setHeaderEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialHeaders, readOnly, setHeaderEditor]); + useSynchronizeOption(headerEditor, "keyMap", keyMap); + useChangeHandler(headerEditor, onEdit, shouldPersistHeaders ? STORAGE_KEY$3 : null, "headers", useHeaderEditor); + useKeyMap(headerEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); + useKeyMap(headerEditor, ["Shift-Ctrl-P"], prettify); + useKeyMap(headerEditor, ["Shift-Ctrl-M"], merge); + return ref; +} +const STORAGE_KEY$3 = "headers"; +const invalidCharacters = Array.from({ + length: 11 +}, (_, i) => { + return String.fromCharCode(8192 + i); +}).concat(["\u2028", "\u2029", " ", " "]); +const sanitizeRegex = new RegExp("[" + invalidCharacters.join("") + "]", "g"); +function normalizeWhitespace(line) { + return line.replace(sanitizeRegex, " "); +} +function useQueryEditor({ + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onClickReference, + onCopyQuery, + onEdit, + readOnly = false +} = {}, caller) { + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: caller || useQueryEditor + }); + const { + externalFragments, + initialQuery, + queryEditor, + setOperationName, + setQueryEditor, + validationRules, + variableEditor, + updateActiveTabValues + } = useEditorContext({ + nonNull: true, + caller: caller || useQueryEditor + }); + const executionContext = useExecutionContext(); + const storage = useStorageContext(); + const explorer = useExplorerContext(); + const plugin = usePluginContext(); + const copy = useCopyQuery({ + caller: caller || useQueryEditor, + onCopyQuery + }); + const merge = useMergeQuery({ + caller: caller || useQueryEditor + }); + const prettify = usePrettifyEditors({ + caller: caller || useQueryEditor + }); + const ref = React.useRef(null); + const codeMirrorRef = React.useRef(); + const onClickReferenceRef = React.useRef(() => {}); + React.useEffect(() => { + onClickReferenceRef.current = reference => { + if (!explorer || !plugin) { + return; + } + plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); + switch (reference.kind) { + case "Type": + { + explorer.push({ + name: reference.type.name, + def: reference.type + }); + break; + } + case "Field": + { + explorer.push({ + name: reference.field.name, + def: reference.field + }); + break; + } + case "Argument": + { + if (reference.field) { + explorer.push({ + name: reference.field.name, + def: reference.field + }); } - const pos = links[ln].index; - if (pos > lastPos) { - const token = new state.Token('text', '', 0); - token.content = text.slice(lastPos, pos); - token.level = level; - nodes.push(token); + break; + } + case "EnumValue": + { + if (reference.type) { + explorer.push({ + name: reference.type.name, + def: reference.type + }); } - const token_o = new state.Token('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.level = level++; - token_o.markup = 'linkify'; - token_o.info = 'auto'; - nodes.push(token_o); - const token_t = new state.Token('text', '', 0); - token_t.content = urlText; - token_t.level = level; - nodes.push(token_t); - const token_c = new state.Token('link_close', 'a', -1); - token_c.level = --level; - token_c.markup = 'linkify'; - token_c.info = 'auto'; - nodes.push(token_c); - lastPos = links[ln].lastIndex; - } - if (lastPos < text.length) { - const token = new state.Token('text', '', 0); - token.content = text.slice(lastPos); - token.level = level; - nodes.push(token); + break; } - - // replace current node - blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes); - } } + onClickReference == null ? void 0 : onClickReference(reference); + }; + }, [explorer, onClickReference, plugin]); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./comment.cjs.js */ "../../graphiql-react/dist/comment.cjs.js")).then(n => n.comment), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs.js */ "../../graphiql-react/dist/hint.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs2.js */ "../../graphiql-react/dist/lint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info.cjs.js */ "../../graphiql-react/dist/info.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./jump.cjs.js */ "../../graphiql-react/dist/jump.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs.js */ "../../graphiql-react/dist/mode.cjs.js"))]).then(CodeMirror => { + if (!isActive) { + return; + } + codeMirrorRef.current = CodeMirror; + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialQuery, + lineNumbers: true, + tabSize: 2, + foldGutter: true, + mode: "graphql", + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + lint: { + // @ts-expect-error + schema: void 0, + validationRules: null, + // linting accepts string or FragmentDefinitionNode[] + externalFragments: void 0 + }, + hintOptions: { + // @ts-expect-error + schema: void 0, + closeOnUnfocus: false, + completeSingle: false, + container, + externalFragments: void 0, + autocompleteOptions: { + // for the query editor, restrict to executable type definitions + mode: graphqlLanguageService.GraphQLDocumentMode.EXECUTABLE + } + }, + info: { + schema: void 0, + renderDescription: text => markdown.render(text), + onClick(reference) { + onClickReferenceRef.current(reference); + } + }, + jump: { + schema: void 0, + onClick(reference) { + onClickReferenceRef.current(reference); + } + }, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: { + ...commonKeys, + "Cmd-S"() {}, + "Ctrl-S"() {} + } + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); + }, + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); + }, + "Alt-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); + }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); + }, + "Shift-Alt-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); + } + }); + newEditor.on("keyup", (editorInstance, event) => { + if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { + editorInstance.execCommand("autocomplete"); + } + }); + let showingHints = false; + newEditor.on("startCompletion", () => { + showingHints = true; + }); + newEditor.on("endCompletion", () => { + showingHints = false; + }); + newEditor.on("keydown", (editorInstance, event) => { + if (event.key === "Escape" && showingHints) { + event.stopPropagation(); + } + }); + newEditor.on("beforeChange", (editorInstance, change) => { + var _a; + if (change.origin === "paste") { + const text = change.text.map(normalizeWhitespace); + (_a = change.update) == null ? void 0 : _a.call(change, change.from, change.to, text); + } + }); + newEditor.documentAST = null; + newEditor.operationName = null; + newEditor.operations = null; + newEditor.variableToType = null; + setQueryEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialQuery, readOnly, setQueryEditor]); + useSynchronizeOption(queryEditor, "keyMap", keyMap); + React.useEffect(() => { + if (!queryEditor) { + return; } - } - - // Simple typographic replacements - // - // (c) (C) → © - // (tm) (TM) → ™ - // (r) (R) → ® - // +- → ± - // ... → … (also ?.... → ?.., !.... → !..) - // ???????? → ???, !!!!! → !!!, `,,` → `,` - // -- → –, --- → — - // - - // TODO: - // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ - // - multiplications 2 x 4 -> 2 × 4 - - const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; - - // Workaround for phantomjs - need regex without /g flag, - // or root check will fail every second time - const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; - const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig; - const SCOPED_ABBR = { - c: '©', - r: '®', - tm: '™' - }; - function replaceFn(match, name) { - return SCOPED_ABBR[name.toLowerCase()]; - } - function replace_scoped(inlineTokens) { - let inside_autolink = 0; - for (let i = inlineTokens.length - 1; i >= 0; i--) { - const token = inlineTokens[i]; - if (token.type === 'text' && !inside_autolink) { - token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); - } - if (token.type === 'link_open' && token.info === 'auto') { - inside_autolink--; - } - if (token.type === 'link_close' && token.info === 'auto') { - inside_autolink++; + function getAndUpdateOperationFacts(editorInstance) { + var _editorInstance$opera, _editorInstance$opera2, _ref3, _ref4; + var _a; + const operationFacts = graphqlLanguageService.getOperationFacts(schema, editorInstance.getValue()); + const operationName = toolkit.getSelectedOperationName((_editorInstance$opera = editorInstance.operations) !== null && _editorInstance$opera !== void 0 ? _editorInstance$opera : void 0, (_editorInstance$opera2 = editorInstance.operationName) !== null && _editorInstance$opera2 !== void 0 ? _editorInstance$opera2 : void 0, operationFacts == null ? void 0 : operationFacts.operations); + editorInstance.documentAST = (_ref3 = operationFacts == null ? void 0 : operationFacts.documentAST) !== null && _ref3 !== void 0 ? _ref3 : null; + editorInstance.operationName = operationName !== null && operationName !== void 0 ? operationName : null; + editorInstance.operations = (_ref4 = operationFacts == null ? void 0 : operationFacts.operations) !== null && _ref4 !== void 0 ? _ref4 : null; + if (variableEditor) { + variableEditor.state.lint.linterOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; + variableEditor.options.lint.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; + variableEditor.options.hintOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; + (_a = codeMirrorRef.current) == null ? void 0 : _a.signal(variableEditor, "change", variableEditor); } + return operationFacts ? { + ...operationFacts, + operationName + } : null; } - } - function replace_rare(inlineTokens) { - let inside_autolink = 0; - for (let i = inlineTokens.length - 1; i >= 0; i--) { - const token = inlineTokens[i]; - if (token.type === 'text' && !inside_autolink) { - if (RARE_RE.test(token.content)) { - token.content = token.content.replace(/\+-/g, '±') - // .., ..., ....... -> … - // but ?..... & !..... -> ?.. & !.. - .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..').replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',') - // em-dash - .replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014') - // en-dash - .replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013').replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013'); - } + const handleChange = debounce(100, editorInstance => { + var _ref5; + const query = editorInstance.getValue(); + storage == null ? void 0 : storage.set(STORAGE_KEY_QUERY, query); + const currentOperationName = editorInstance.operationName; + const operationFacts = getAndUpdateOperationFacts(editorInstance); + if ((operationFacts == null ? void 0 : operationFacts.operationName) !== void 0) { + storage == null ? void 0 : storage.set(STORAGE_KEY_OPERATION_NAME, operationFacts.operationName); } - if (token.type === 'link_open' && token.info === 'auto') { - inside_autolink--; + onEdit == null ? void 0 : onEdit(query, operationFacts == null ? void 0 : operationFacts.documentAST); + if ((operationFacts == null ? void 0 : operationFacts.operationName) && currentOperationName !== operationFacts.operationName) { + setOperationName(operationFacts.operationName); } - if (token.type === 'link_close' && token.info === 'auto') { - inside_autolink++; + updateActiveTabValues({ + query, + operationName: (_ref5 = operationFacts == null ? void 0 : operationFacts.operationName) !== null && _ref5 !== void 0 ? _ref5 : null + }); + }); + getAndUpdateOperationFacts(queryEditor); + queryEditor.on("change", handleChange); + return () => queryEditor.off("change", handleChange); + }, [onEdit, queryEditor, schema, setOperationName, storage, variableEditor, updateActiveTabValues]); + useSynchronizeSchema(queryEditor, schema !== null && schema !== void 0 ? schema : null, codeMirrorRef); + useSynchronizeValidationRules(queryEditor, validationRules !== null && validationRules !== void 0 ? validationRules : null, codeMirrorRef); + useSynchronizeExternalFragments(queryEditor, externalFragments, codeMirrorRef); + useCompletion(queryEditor, onClickReference || null, useQueryEditor); + const run = executionContext == null ? void 0 : executionContext.run; + const runAtCursor = React.useCallback(() => { + var _a; + if (!run || !queryEditor || !queryEditor.operations || !queryEditor.hasFocus()) { + run == null ? void 0 : run(); + return; + } + const cursorIndex = queryEditor.indexFromPos(queryEditor.getCursor()); + let operationName; + for (const operation of queryEditor.operations) { + if (operation.loc && operation.loc.start <= cursorIndex && operation.loc.end >= cursorIndex) { + operationName = (_a = operation.name) == null ? void 0 : _a.value; } } - } - function replace(state) { - let blkIdx; - if (!state.md.options.typographer) { + if (operationName && operationName !== queryEditor.operationName) { + setOperationName(operationName); + } + run(); + }, [queryEditor, run, setOperationName]); + useKeyMap(queryEditor, ["Cmd-Enter", "Ctrl-Enter"], runAtCursor); + useKeyMap(queryEditor, ["Shift-Ctrl-C"], copy); + useKeyMap(queryEditor, ["Shift-Ctrl-P", + // Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to prettify + "Shift-Ctrl-F"], prettify); + useKeyMap(queryEditor, ["Shift-Ctrl-M"], merge); + return ref; +} +function useSynchronizeSchema(editor, schema, codeMirrorRef) { + React.useEffect(() => { + if (!editor) { return; } - for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { - if (state.tokens[blkIdx].type !== 'inline') { - continue; - } - if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { - replace_scoped(state.tokens[blkIdx].children); + const didChange = editor.options.lint.schema !== schema; + editor.state.lint.linterOptions.schema = schema; + editor.options.lint.schema = schema; + editor.options.hintOptions.schema = schema; + editor.options.info.schema = schema; + editor.options.jump.schema = schema; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, schema, codeMirrorRef]); +} +function useSynchronizeValidationRules(editor, validationRules, codeMirrorRef) { + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = editor.options.lint.validationRules !== validationRules; + editor.state.lint.linterOptions.validationRules = validationRules; + editor.options.lint.validationRules = validationRules; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, validationRules, codeMirrorRef]); +} +function useSynchronizeExternalFragments(editor, externalFragments, codeMirrorRef) { + const externalFragmentList = React.useMemo(() => [...externalFragments.values()], [externalFragments]); + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = editor.options.lint.externalFragments !== externalFragmentList; + editor.state.lint.linterOptions.externalFragments = externalFragmentList; + editor.options.lint.externalFragments = externalFragmentList; + editor.options.hintOptions.externalFragments = externalFragmentList; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, externalFragmentList, codeMirrorRef]); +} +const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/; +const STORAGE_KEY_QUERY = "query"; +const STORAGE_KEY_OPERATION_NAME = "operationName"; +function getDefaultTabState({ + defaultQuery, + defaultHeaders, + headers, + defaultTabs, + query, + variables, + storage, + shouldPersistHeaders +}) { + const storedState = storage == null ? void 0 : storage.get(STORAGE_KEY$2); + try { + if (!storedState) { + throw new Error("Storage for tabs is empty"); + } + const parsed = JSON.parse(storedState); + const headersForHash = shouldPersistHeaders ? headers : void 0; + if (isTabsState(parsed)) { + const expectedHash = hashFromTabContents({ + query, + variables, + headers: headersForHash + }); + let matchingTabIndex = -1; + for (let index = 0; index < parsed.tabs.length; index++) { + const tab = parsed.tabs[index]; + tab.hash = hashFromTabContents({ + query: tab.query, + variables: tab.variables, + headers: tab.headers + }); + if (tab.hash === expectedHash) { + matchingTabIndex = index; + } } - if (RARE_RE.test(state.tokens[blkIdx].content)) { - replace_rare(state.tokens[blkIdx].children); + if (matchingTabIndex >= 0) { + parsed.activeTabIndex = matchingTabIndex; + } else { + const operationName = query ? fuzzyExtractOperationName(query) : null; + parsed.tabs.push({ + id: guid(), + hash: expectedHash, + title: operationName || DEFAULT_TITLE, + query, + variables, + headers, + operationName, + response: null + }); + parsed.activeTabIndex = parsed.tabs.length - 1; } + return parsed; } + throw new Error("Storage for tabs is invalid"); + } catch { + return { + activeTabIndex: 0, + tabs: (defaultTabs || [{ + query: query !== null && query !== void 0 ? query : defaultQuery, + variables, + headers: headers !== null && headers !== void 0 ? headers : defaultHeaders + }]).map(createTab) + }; } - - // Convert straight quotation marks to typographic ones - // - - const QUOTE_TEST_RE = /['"]/; - const QUOTE_RE = /['"]/g; - const APOSTROPHE = '\u2019'; /* ’ */ - - function replaceAt(str, index, ch) { - return str.slice(0, index) + ch + str.slice(index + 1); - } - function process_inlines(tokens, state) { - let j; - const stack = []; - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - const thisLevel = tokens[i].level; - for (j = stack.length - 1; j >= 0; j--) { - if (stack[j].level <= thisLevel) { - break; - } +} +function isTabsState(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj) && hasNumberKey(obj, "activeTabIndex") && "tabs" in obj && Array.isArray(obj.tabs) && obj.tabs.every(isTabState); +} +function isTabState(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj) && hasStringKey(obj, "id") && hasStringKey(obj, "title") && hasStringOrNullKey(obj, "query") && hasStringOrNullKey(obj, "variables") && hasStringOrNullKey(obj, "headers") && hasStringOrNullKey(obj, "operationName") && hasStringOrNullKey(obj, "response"); +} +function hasNumberKey(obj, key) { + return key in obj && typeof obj[key] === "number"; +} +function hasStringKey(obj, key) { + return key in obj && typeof obj[key] === "string"; +} +function hasStringOrNullKey(obj, key) { + return key in obj && (typeof obj[key] === "string" || obj[key] === null); +} +function useSynchronizeActiveTabValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor +}) { + return React.useCallback(state => { + var _ref6, _ref7, _ref8, _ref9, _ref10; + const query = (_ref6 = queryEditor == null ? void 0 : queryEditor.getValue()) !== null && _ref6 !== void 0 ? _ref6 : null; + const variables = (_ref7 = variableEditor == null ? void 0 : variableEditor.getValue()) !== null && _ref7 !== void 0 ? _ref7 : null; + const headers = (_ref8 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref8 !== void 0 ? _ref8 : null; + const operationName = (_ref9 = queryEditor == null ? void 0 : queryEditor.operationName) !== null && _ref9 !== void 0 ? _ref9 : null; + const response = (_ref10 = responseEditor == null ? void 0 : responseEditor.getValue()) !== null && _ref10 !== void 0 ? _ref10 : null; + return setPropertiesInActiveTab(state, { + query, + variables, + headers, + response, + operationName + }); + }, [queryEditor, variableEditor, headerEditor, responseEditor]); +} +function serializeTabState(tabState, shouldPersistHeaders = false) { + return JSON.stringify(tabState, (key, value) => key === "hash" || key === "response" || !shouldPersistHeaders && key === "headers" ? null : value); +} +function useStoreTabs({ + storage, + shouldPersistHeaders +}) { + const store = React.useMemo(() => debounce(500, value => { + storage == null ? void 0 : storage.set(STORAGE_KEY$2, value); + }), [storage]); + return React.useCallback(currentState => { + store(serializeTabState(currentState, shouldPersistHeaders)); + }, [shouldPersistHeaders, store]); +} +function useSetEditorValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor +}) { + return React.useCallback(({ + query, + variables, + headers, + response + }) => { + queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); + variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); + headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); + responseEditor == null ? void 0 : responseEditor.setValue(response !== null && response !== void 0 ? response : ""); + }, [headerEditor, queryEditor, responseEditor, variableEditor]); +} +function createTab({ + query = null, + variables = null, + headers = null +} = {}) { + return { + id: guid(), + hash: hashFromTabContents({ + query, + variables, + headers + }), + title: query && fuzzyExtractOperationName(query) || DEFAULT_TITLE, + query, + variables, + headers, + operationName: null, + response: null + }; +} +function setPropertiesInActiveTab(state, partialTab) { + return { + ...state, + tabs: state.tabs.map((tab, index) => { + if (index !== state.activeTabIndex) { + return tab; + } + const newTab = { + ...tab, + ...partialTab + }; + return { + ...newTab, + hash: hashFromTabContents(newTab), + title: newTab.operationName || (newTab.query ? fuzzyExtractOperationName(newTab.query) : void 0) || DEFAULT_TITLE + }; + }) + }; +} +function guid() { + const s4 = () => { + return Math.floor((1 + Math.random()) * 65536).toString(16).slice(1); + }; + return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; +} +function hashFromTabContents(args) { + var _args$query, _args$variables, _args$headers; + return [(_args$query = args.query) !== null && _args$query !== void 0 ? _args$query : "", (_args$variables = args.variables) !== null && _args$variables !== void 0 ? _args$variables : "", (_args$headers = args.headers) !== null && _args$headers !== void 0 ? _args$headers : ""].join("|"); +} +function fuzzyExtractOperationName(str) { + var _ref11; + const regex = /^(?!#).*(query|subscription|mutation)\s+([a-zA-Z0-9_]+)/m; + const match = regex.exec(str); + return (_ref11 = match == null ? void 0 : match[2]) !== null && _ref11 !== void 0 ? _ref11 : null; +} +function clearHeadersFromTabs(storage) { + const persistedTabs = storage == null ? void 0 : storage.get(STORAGE_KEY$2); + if (persistedTabs) { + const parsedTabs = JSON.parse(persistedTabs); + storage == null ? void 0 : storage.set(STORAGE_KEY$2, JSON.stringify(parsedTabs, (key, value) => key === "headers" ? null : value)); + } +} +const DEFAULT_TITLE = ""; +const STORAGE_KEY$2 = "tabState"; +function useVariableEditor({ + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onClickReference, + onEdit, + readOnly = false +} = {}, caller) { + const { + initialVariables, + variableEditor, + setVariableEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useVariableEditor + }); + const executionContext = useExecutionContext(); + const merge = useMergeQuery({ + caller: caller || useVariableEditor + }); + const prettify = usePrettifyEditors({ + caller: caller || useVariableEditor + }); + const ref = React.useRef(null); + const codeMirrorRef = React.useRef(); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs2.js */ "../../graphiql-react/dist/hint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs3.js */ "../../graphiql-react/dist/lint.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs2.js */ "../../graphiql-react/dist/mode.cjs2.js"))]).then(CodeMirror => { + if (!isActive) { + return; } - stack.length = j + 1; - if (token.type !== 'text') { - continue; + codeMirrorRef.current = CodeMirror; + const container = ref.current; + if (!container) { + return; } - let text = token.content; - let pos = 0; - let max = text.length; - - /* eslint no-labels:0,block-scoped-var:0 */ - OUTER: while (pos < max) { - QUOTE_RE.lastIndex = pos; - const t = QUOTE_RE.exec(text); - if (!t) { - break; - } - let canOpen = true; - let canClose = true; - pos = t.index + 1; - const isSingle = t[0] === "'"; - - // Find previous character, - // default to space if it's the beginning of the line - // - let lastChar = 0x20; - if (t.index - 1 >= 0) { - lastChar = text.charCodeAt(t.index - 1); - } else { - for (j = i - 1; j >= 0; j--) { - if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // lastChar defaults to 0x20 - if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' - - lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1); - break; - } - } - - // Find next character, - // default to space if it's the end of the line - // - let nextChar = 0x20; - if (pos < max) { - nextChar = text.charCodeAt(pos); - } else { - for (j = i + 1; j < tokens.length; j++) { - if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // nextChar defaults to 0x20 - if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' - - nextChar = tokens[j].content.charCodeAt(0); - break; - } - } - const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); - const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); - const isLastWhiteSpace = isWhiteSpace(lastChar); - const isNextWhiteSpace = isWhiteSpace(nextChar); - if (isNextWhiteSpace) { - canOpen = false; - } else if (isNextPunctChar) { - if (!(isLastWhiteSpace || isLastPunctChar)) { - canOpen = false; - } + const newEditor = CodeMirror(container, { + value: initialVariables, + lineNumbers: true, + tabSize: 2, + mode: "graphql-variables", + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + foldGutter: true, + lint: { + // @ts-expect-error + variableToType: void 0 + }, + hintOptions: { + closeOnUnfocus: false, + completeSingle: false, + container, + // @ts-expect-error + variableToType: void 0 + }, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: commonKeys + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + }, + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + }, + "Alt-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); } - if (isLastWhiteSpace) { - canClose = false; - } else if (isLastPunctChar) { - if (!(isNextWhiteSpace || isNextPunctChar)) { - canClose = false; - } + }); + newEditor.on("keyup", (editorInstance, event) => { + const { + code, + key, + shiftKey + } = event; + const isLetter = code.startsWith("Key"); + const isNumber = !shiftKey && code.startsWith("Digit"); + if (isLetter || isNumber || key === "_" || key === '"') { + editorInstance.execCommand("autocomplete"); } - if (nextChar === 0x22 /* " */ && t[0] === '"') { - if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { - // special case: 1"" - count first quote as an inch - canClose = canOpen = false; - } + }); + setVariableEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialVariables, readOnly, setVariableEditor]); + useSynchronizeOption(variableEditor, "keyMap", keyMap); + useChangeHandler(variableEditor, onEdit, STORAGE_KEY$1, "variables", useVariableEditor); + useCompletion(variableEditor, onClickReference || null, useVariableEditor); + useKeyMap(variableEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); + useKeyMap(variableEditor, ["Shift-Ctrl-P"], prettify); + useKeyMap(variableEditor, ["Shift-Ctrl-M"], merge); + return ref; +} +const STORAGE_KEY$1 = "variables"; +const EditorContext = createNullableContext("EditorContext"); +function EditorContextProvider(props) { + const storage = useStorageContext(); + const [headerEditor, setHeaderEditor] = React.useState(null); + const [queryEditor, setQueryEditor] = React.useState(null); + const [responseEditor, setResponseEditor] = React.useState(null); + const [variableEditor, setVariableEditor] = React.useState(null); + const [shouldPersistHeaders, setShouldPersistHeadersInternal] = React.useState(() => { + const isStored = (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) !== null; + return props.shouldPersistHeaders !== false && isStored ? (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) === "true" : Boolean(props.shouldPersistHeaders); + }); + useSynchronizeValue(headerEditor, props.headers); + useSynchronizeValue(queryEditor, props.query); + useSynchronizeValue(responseEditor, props.response); + useSynchronizeValue(variableEditor, props.variables); + const storeTabs = useStoreTabs({ + storage, + shouldPersistHeaders + }); + const [initialState] = React.useState(() => { + var _ref12, _props$query, _ref13, _props$variables, _ref14, _props$headers, _props$response, _ref15, _ref16; + const query = (_ref12 = (_props$query = props.query) !== null && _props$query !== void 0 ? _props$query : storage == null ? void 0 : storage.get(STORAGE_KEY_QUERY)) !== null && _ref12 !== void 0 ? _ref12 : null; + const variables = (_ref13 = (_props$variables = props.variables) !== null && _props$variables !== void 0 ? _props$variables : storage == null ? void 0 : storage.get(STORAGE_KEY$1)) !== null && _ref13 !== void 0 ? _ref13 : null; + const headers = (_ref14 = (_props$headers = props.headers) !== null && _props$headers !== void 0 ? _props$headers : storage == null ? void 0 : storage.get(STORAGE_KEY$3)) !== null && _ref14 !== void 0 ? _ref14 : null; + const response = (_props$response = props.response) !== null && _props$response !== void 0 ? _props$response : ""; + const tabState2 = getDefaultTabState({ + query, + variables, + headers, + defaultTabs: props.defaultTabs, + defaultQuery: props.defaultQuery || DEFAULT_QUERY, + defaultHeaders: props.defaultHeaders, + storage, + shouldPersistHeaders + }); + storeTabs(tabState2); + return { + query: (_ref15 = query !== null && query !== void 0 ? query : tabState2.activeTabIndex === 0 ? tabState2.tabs[0].query : null) !== null && _ref15 !== void 0 ? _ref15 : "", + variables: variables !== null && variables !== void 0 ? variables : "", + headers: (_ref16 = headers !== null && headers !== void 0 ? headers : props.defaultHeaders) !== null && _ref16 !== void 0 ? _ref16 : "", + response, + tabState: tabState2 + }; + }); + const [tabState, setTabState] = React.useState(initialState.tabState); + const setShouldPersistHeaders = React.useCallback(persist => { + if (persist) { + var _ref17; + storage == null ? void 0 : storage.set(STORAGE_KEY$3, (_ref17 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref17 !== void 0 ? _ref17 : ""); + const serializedTabs = serializeTabState(tabState, true); + storage == null ? void 0 : storage.set(STORAGE_KEY$2, serializedTabs); + } else { + storage == null ? void 0 : storage.set(STORAGE_KEY$3, ""); + clearHeadersFromTabs(storage); + } + setShouldPersistHeadersInternal(persist); + storage == null ? void 0 : storage.set(PERSIST_HEADERS_STORAGE_KEY, persist.toString()); + }, [storage, tabState, headerEditor]); + const lastShouldPersistHeadersProp = React.useRef(); + React.useEffect(() => { + const propValue = Boolean(props.shouldPersistHeaders); + if ((lastShouldPersistHeadersProp == null ? void 0 : lastShouldPersistHeadersProp.current) !== propValue) { + setShouldPersistHeaders(propValue); + lastShouldPersistHeadersProp.current = propValue; + } + }, [props.shouldPersistHeaders, setShouldPersistHeaders]); + const synchronizeActiveTabValues = useSynchronizeActiveTabValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor + }); + const setEditorValues = useSetEditorValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor + }); + const { + onTabChange, + defaultHeaders, + children + } = props; + const addTab = React.useCallback(() => { + setTabState(current => { + const updatedValues = synchronizeActiveTabValues(current); + const updated = { + tabs: [...updatedValues.tabs, createTab({ + headers: defaultHeaders + })], + activeTabIndex: updatedValues.tabs.length + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [defaultHeaders, onTabChange, setEditorValues, storeTabs, synchronizeActiveTabValues]); + const changeTab = React.useCallback(index => { + setTabState(current => { + const updated = { + ...current, + activeTabIndex: index + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, setEditorValues, storeTabs]); + const moveTab = React.useCallback(newOrder => { + setTabState(current => { + const activeTab = current.tabs[current.activeTabIndex]; + const updated = { + tabs: newOrder, + activeTabIndex: newOrder.indexOf(activeTab) + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, setEditorValues, storeTabs]); + const closeTab = React.useCallback(index => { + setTabState(current => { + const updated = { + tabs: current.tabs.filter((_tab, i) => index !== i), + activeTabIndex: Math.max(current.activeTabIndex - 1, 0) + }; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, setEditorValues, storeTabs]); + const updateActiveTabValues = React.useCallback(partialTab => { + setTabState(current => { + const updated = setPropertiesInActiveTab(current, partialTab); + storeTabs(updated); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, storeTabs]); + const { + onEditOperationName + } = props; + const setOperationName = React.useCallback(operationName => { + if (!queryEditor) { + return; + } + queryEditor.operationName = operationName; + updateActiveTabValues({ + operationName + }); + onEditOperationName == null ? void 0 : onEditOperationName(operationName); + }, [onEditOperationName, queryEditor, updateActiveTabValues]); + const externalFragments = React.useMemo(() => { + const map = /* @__PURE__ */new Map(); + if (Array.isArray(props.externalFragments)) { + for (const fragment of props.externalFragments) { + map.set(fragment.name.value, fragment); + } + } else if (typeof props.externalFragments === "string") { + graphql.visit(graphql.parse(props.externalFragments, {}), { + FragmentDefinition(fragment) { + map.set(fragment.name.value, fragment); } - if (canOpen && canClose) { - // Replace quotes in the middle of punctuation sequence, but not - // in the middle of the words, i.e.: - // - // 1. foo " bar " baz - not replaced - // 2. foo-"-bar-"-baz - replaced - // 3. foo"bar"baz - not replaced - // - canOpen = isLastPunctChar; - canClose = isNextPunctChar; + }); + } else if (props.externalFragments) { + throw new Error("The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects."); + } + return map; + }, [props.externalFragments]); + const validationRules = React.useMemo(() => props.validationRules || [], [props.validationRules]); + const value = React.useMemo(() => ({ + ...tabState, + addTab, + changeTab, + moveTab, + closeTab, + updateActiveTabValues, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + setHeaderEditor, + setQueryEditor, + setResponseEditor, + setVariableEditor, + setOperationName, + initialQuery: initialState.query, + initialVariables: initialState.variables, + initialHeaders: initialState.headers, + initialResponse: initialState.response, + externalFragments, + validationRules, + shouldPersistHeaders, + setShouldPersistHeaders + }), [tabState, addTab, changeTab, moveTab, closeTab, updateActiveTabValues, headerEditor, queryEditor, responseEditor, variableEditor, setOperationName, initialState, externalFragments, validationRules, shouldPersistHeaders, setShouldPersistHeaders]); + return /* @__PURE__ */jsxRuntime.jsx(EditorContext.Provider, { + value, + children + }); +} +const useEditorContext = createContextHook(EditorContext); +const PERSIST_HEADERS_STORAGE_KEY = "shouldPersistHeaders"; +const DEFAULT_QUERY = `# Welcome to GraphiQL +# +# GraphiQL is an in-browser tool for writing, validating, and +# testing GraphQL queries. +# +# Type queries into this side of the screen, and you will see intelligent +# typeaheads aware of the current GraphQL type schema and live syntax and +# validation errors highlighted within the text. +# +# GraphQL queries typically start with a "{" character. Lines that start +# with a # are ignored. +# +# An example GraphQL query might look like: +# +# { +# field(arg: "value") { +# subField +# } +# } +# +# Keyboard shortcuts: +# +# Prettify query: Shift-Ctrl-P (or press the prettify button) +# +# Merge fragments: Shift-Ctrl-M (or press the merge button) +# +# Run Query: Ctrl-Enter (or press the play button) +# +# Auto Complete: Ctrl-Space (or just start typing) +# + +`; +function HeaderEditor({ + isHidden, + ...hookArgs +}) { + const { + headerEditor + } = useEditorContext({ + nonNull: true, + caller: HeaderEditor + }); + const ref = useHeaderEditor(hookArgs, HeaderEditor); + React.useEffect(() => { + if (!isHidden) { + headerEditor == null ? void 0 : headerEditor.refresh(); + } + }, [headerEditor, isHidden]); + return /* @__PURE__ */jsxRuntime.jsx("div", { + className: clsx.clsx("graphiql-editor", isHidden && "hidden"), + ref + }); +} +function ImagePreview(props) { + var _a; + const [dimensions, setDimensions] = React.useState({ + width: null, + height: null + }); + const [mime, setMime] = React.useState(null); + const ref = React.useRef(null); + const src = (_a = tokenToURL(props.token)) == null ? void 0 : _a.href; + React.useEffect(() => { + if (!ref.current) { + return; + } + if (!src) { + setDimensions({ + width: null, + height: null + }); + setMime(null); + return; + } + fetch(src, { + method: "HEAD" + }).then(response => { + setMime(response.headers.get("Content-Type")); + }).catch(() => { + setMime(null); + }); + }, [src]); + const dims = dimensions.width !== null && dimensions.height !== null ? /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [dimensions.width, "x", dimensions.height, mime === null ? null : " " + mime] + }) : null; + return /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("img", { + onLoad: () => { + var _ref18, _ref19; + var _a2, _b; + setDimensions({ + width: (_ref18 = (_a2 = ref.current) == null ? void 0 : _a2.naturalWidth) !== null && _ref18 !== void 0 ? _ref18 : null, + height: (_ref19 = (_b = ref.current) == null ? void 0 : _b.naturalHeight) !== null && _ref19 !== void 0 ? _ref19 : null + }); + }, + ref, + src + }), dims] + }); +} +ImagePreview.shouldRender = function shouldRender(token) { + const url = tokenToURL(token); + return url ? isImageURL(url) : false; +}; +function tokenToURL(token) { + if (token.type !== "string") { + return; + } + const value = token.string.slice(1).slice(0, -1).trim(); + try { + const { + location + } = window; + return new URL(value, location.protocol + "//" + location.host); + } catch { + return; + } +} +function isImageURL(url) { + return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname); +} +function QueryEditor(props) { + const ref = useQueryEditor(props, QueryEditor); + return /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-editor", + ref + }); +} +function useResponseEditor({ + responseTooltip, + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP +} = {}, caller) { + const { + fetchError, + validationErrors + } = useSchemaContext({ + nonNull: true, + caller: caller || useResponseEditor + }); + const { + initialResponse, + responseEditor, + setResponseEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useResponseEditor + }); + const ref = React.useRef(null); + const responseTooltipRef = React.useRef(responseTooltip); + React.useEffect(() => { + responseTooltipRef.current = responseTooltip; + }, [responseTooltip]); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), + // @ts-expect-error + Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs3.js */ "../../graphiql-react/dist/mode.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"))], { + useCommonAddons: false + }).then(CodeMirror => { + if (!isActive) { + return; + } + const tooltipDiv = document.createElement("div"); + CodeMirror.registerHelper("info", "graphql-results", (token, _options, _cm, pos) => { + const infoElements = []; + const ResponseTooltipComponent = responseTooltipRef.current; + if (ResponseTooltipComponent) { + infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ResponseTooltipComponent, { + pos, + token + })); } - if (!canOpen && !canClose) { - // middle of word - if (isSingle) { - token.content = replaceAt(token.content, t.index, APOSTROPHE); - } - continue; + if (ImagePreview.shouldRender(token)) { + infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ImagePreview, { + token + }, "image-preview")); } - if (canClose) { - // this could be a closing quote, rewind the stack to get a match - for (j = stack.length - 1; j >= 0; j--) { - let item = stack[j]; - if (stack[j].level < thisLevel) { - break; - } - if (item.single === isSingle && stack[j].level === thisLevel) { - item = stack[j]; - let openQuote; - let closeQuote; - if (isSingle) { - openQuote = state.md.options.quotes[2]; - closeQuote = state.md.options.quotes[3]; - } else { - openQuote = state.md.options.quotes[0]; - closeQuote = state.md.options.quotes[1]; - } - - // replace token.content *before* tokens[item.token].content, - // because, if they are pointing at the same token, replaceAt - // could mess up indices when quote length != 1 - token.content = replaceAt(token.content, t.index, closeQuote); - tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, openQuote); - pos += closeQuote.length - 1; - if (item.token === i) { - pos += openQuote.length - 1; - } - text = token.content; - max = text.length; - stack.length = j; - continue OUTER; - } - } + if (!infoElements.length) { + ReactDOM.unmountComponentAtNode(tooltipDiv); + return null; } - if (canOpen) { - stack.push({ - token: i, - pos: t.index, - single: isSingle, - level: thisLevel - }); - } else if (canClose && isSingle) { - token.content = replaceAt(token.content, t.index, APOSTROPHE); + ReactDOM.render(infoElements, tooltipDiv); + return tooltipDiv; + }); + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialResponse, + lineWrapping: true, + readOnly: true, + theme: editorTheme, + mode: "graphql-results", + foldGutter: true, + gutters: ["CodeMirror-foldgutter"], + // @ts-expect-error + info: true, + extraKeys: commonKeys + }); + setResponseEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialResponse, setResponseEditor]); + useSynchronizeOption(responseEditor, "keyMap", keyMap); + React.useEffect(() => { + if (fetchError) { + responseEditor == null ? void 0 : responseEditor.setValue(fetchError); + } + if (validationErrors.length > 0) { + responseEditor == null ? void 0 : responseEditor.setValue(toolkit.formatError(validationErrors)); + } + }, [responseEditor, fetchError, validationErrors]); + return ref; +} +function ResponseEditor(props) { + const ref = useResponseEditor(props, ResponseEditor); + return /* @__PURE__ */jsxRuntime.jsx("section", { + className: "result-window", + "aria-label": "Result Window", + "aria-live": "polite", + "aria-atomic": "true", + ref + }); +} +function VariableEditor({ + isHidden, + ...hookArgs +}) { + const { + variableEditor + } = useEditorContext({ + nonNull: true, + caller: VariableEditor + }); + const ref = useVariableEditor(hookArgs, VariableEditor); + React.useEffect(() => { + if (variableEditor && !isHidden) { + variableEditor.refresh(); + } + }, [variableEditor, isHidden]); + return /* @__PURE__ */jsxRuntime.jsx("div", { + className: clsx.clsx("graphiql-editor", isHidden && "hidden"), + ref + }); +} +function GraphiQLProvider({ + children, + dangerouslyAssumeSchemaIsValid, + defaultQuery, + defaultHeaders, + defaultTabs, + externalFragments, + fetcher, + getDefaultFieldNames, + headers, + inputValueDeprecation, + introspectionQueryName, + maxHistoryLength, + onEditOperationName, + onSchemaChange, + onTabChange, + onTogglePluginVisibility, + operationName, + plugins, + query, + response, + schema, + schemaDescription, + shouldPersistHeaders, + storage, + validationRules, + variables, + visiblePlugin +}) { + return /* @__PURE__ */jsxRuntime.jsx(StorageContextProvider, { + storage, + children: /* @__PURE__ */jsxRuntime.jsx(HistoryContextProvider, { + maxHistoryLength, + children: /* @__PURE__ */jsxRuntime.jsx(EditorContextProvider, { + defaultQuery, + defaultHeaders, + defaultTabs, + externalFragments, + headers, + onEditOperationName, + onTabChange, + query, + response, + shouldPersistHeaders, + validationRules, + variables, + children: /* @__PURE__ */jsxRuntime.jsx(SchemaContextProvider, { + dangerouslyAssumeSchemaIsValid, + fetcher, + inputValueDeprecation, + introspectionQueryName, + onSchemaChange, + schema, + schemaDescription, + children: /* @__PURE__ */jsxRuntime.jsx(ExecutionContextProvider, { + getDefaultFieldNames, + fetcher, + operationName, + children: /* @__PURE__ */jsxRuntime.jsx(ExplorerContextProvider, { + children: /* @__PURE__ */jsxRuntime.jsx(PluginContextProvider, { + onTogglePluginVisibility, + plugins, + visiblePlugin, + children + }) + }) + }) + }) + }) + }) + }); +} +function useTheme() { + const storageContext = useStorageContext(); + const [theme, setThemeInternal] = React.useState(() => { + if (!storageContext) { + return null; + } + const stored = storageContext.get(STORAGE_KEY); + switch (stored) { + case "light": + return "light"; + case "dark": + return "dark"; + default: + if (typeof stored === "string") { + storageContext.set(STORAGE_KEY, ""); } - } + return null; } - } - function smartquotes(state) { - /* eslint max-depth:0 */ - if (!state.md.options.typographer) { + }); + React.useLayoutEffect(() => { + if (typeof window === "undefined") { return; } - for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { - if (state.tokens[blkIdx].type !== 'inline' || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) { - continue; - } - process_inlines(state.tokens[blkIdx].children, state); + document.body.classList.remove("graphiql-light", "graphiql-dark"); + if (theme) { + document.body.classList.add(`graphiql-${theme}`); + } + }, [theme]); + const setTheme = React.useCallback(newTheme => { + storageContext == null ? void 0 : storageContext.set(STORAGE_KEY, newTheme || ""); + setThemeInternal(newTheme); + }, [storageContext]); + return React.useMemo(() => ({ + theme, + setTheme + }), [theme, setTheme]); +} +const STORAGE_KEY = "theme"; +function useDragResize({ + defaultSizeRelation = DEFAULT_FLEX, + direction, + initiallyHidden, + onHiddenElementChange, + sizeThresholdFirst = 100, + sizeThresholdSecond = 100, + storageKey +}) { + const storage = useStorageContext(); + const store = React.useMemo(() => debounce(500, value => { + if (storageKey) { + storage == null ? void 0 : storage.set(storageKey, value); + } + }), [storage, storageKey]); + const [hiddenElement, setHiddenElement] = React.useState(() => { + const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)); + if (storedValue === HIDE_FIRST || initiallyHidden === "first") { + return "first"; + } + if (storedValue === HIDE_SECOND || initiallyHidden === "second") { + return "second"; } - } - - // Join raw text tokens with the rest of the text - // - // This is set as a separate rule to provide an opportunity for plugins - // to run text replacements after text join, but before escape join. - // - // For example, `\:)` shouldn't be replaced with an emoji. - // - - function text_join(state) { - let curr, last; - const blockTokens = state.tokens; - const l = blockTokens.length; - for (let j = 0; j < l; j++) { - if (blockTokens[j].type !== 'inline') continue; - const tokens = blockTokens[j].children; - const max = tokens.length; - for (curr = 0; curr < max; curr++) { - if (tokens[curr].type === 'text_special') { - tokens[curr].type = 'text'; - } - } - for (curr = last = 0; curr < max; curr++) { - if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { - // collapse two adjacent text nodes - tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; + return null; + }); + const setHiddenElementWithCallback = React.useCallback(element => { + if (element !== hiddenElement) { + setHiddenElement(element); + onHiddenElementChange == null ? void 0 : onHiddenElementChange(element); + } + }, [hiddenElement, onHiddenElementChange]); + const firstRef = React.useRef(null); + const dragBarRef = React.useRef(null); + const secondRef = React.useRef(null); + const defaultFlexRef = React.useRef(`${defaultSizeRelation}`); + React.useLayoutEffect(() => { + const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)) || defaultFlexRef.current; + if (firstRef.current) { + firstRef.current.style.display = "flex"; + firstRef.current.style.flex = storedValue === HIDE_FIRST || storedValue === HIDE_SECOND ? defaultFlexRef.current : storedValue; + } + if (secondRef.current) { + secondRef.current.style.display = "flex"; + secondRef.current.style.flex = "1"; + } + if (dragBarRef.current) { + dragBarRef.current.style.display = "flex"; + } + }, [direction, storage, storageKey]); + const hide = React.useCallback(resizableElement => { + const element = resizableElement === "first" ? firstRef.current : secondRef.current; + if (!element) { + return; + } + element.style.left = "-1000px"; + element.style.position = "absolute"; + element.style.opacity = "0"; + element.style.height = "500px"; + element.style.width = "500px"; + if (firstRef.current) { + const flex = parseFloat(firstRef.current.style.flex); + if (!Number.isFinite(flex) || flex < 1) { + firstRef.current.style.flex = "1"; + } + } + }, []); + const show = React.useCallback(resizableElement => { + const element = resizableElement === "first" ? firstRef.current : secondRef.current; + if (!element) { + return; + } + element.style.width = ""; + element.style.height = ""; + element.style.opacity = ""; + element.style.position = ""; + element.style.left = ""; + if (storage && storageKey) { + const storedValue = storage.get(storageKey); + if (firstRef.current && storedValue !== HIDE_FIRST && storedValue !== HIDE_SECOND) { + firstRef.current.style.flex = storedValue || defaultFlexRef.current; + } + } + }, [storage, storageKey]); + React.useLayoutEffect(() => { + if (hiddenElement === "first") { + hide("first"); + } else { + show("first"); + } + if (hiddenElement === "second") { + hide("second"); + } else { + show("second"); + } + }, [hiddenElement, hide, show]); + React.useEffect(() => { + if (!dragBarRef.current || !firstRef.current || !secondRef.current) { + return; + } + const dragBarContainer = dragBarRef.current; + const firstContainer = firstRef.current; + const wrapper = firstContainer.parentElement; + const eventProperty = direction === "horizontal" ? "clientX" : "clientY"; + const rectProperty = direction === "horizontal" ? "left" : "top"; + const adjacentRectProperty = direction === "horizontal" ? "right" : "bottom"; + const sizeProperty = direction === "horizontal" ? "clientWidth" : "clientHeight"; + function handleMouseDown(downEvent) { + downEvent.preventDefault(); + const offset = downEvent[eventProperty] - dragBarContainer.getBoundingClientRect()[rectProperty]; + function handleMouseMove(moveEvent) { + if (moveEvent.buttons === 0) { + return handleMouseUp(); + } + const firstSize = moveEvent[eventProperty] - wrapper.getBoundingClientRect()[rectProperty] - offset; + const secondSize = wrapper.getBoundingClientRect()[adjacentRectProperty] - moveEvent[eventProperty] + offset - dragBarContainer[sizeProperty]; + if (firstSize < sizeThresholdFirst) { + setHiddenElementWithCallback("first"); + store(HIDE_FIRST); + } else if (secondSize < sizeThresholdSecond) { + setHiddenElementWithCallback("second"); + store(HIDE_SECOND); } else { - if (curr !== last) { - tokens[last] = tokens[curr]; - } - last++; + setHiddenElementWithCallback(null); + const newFlex = `${firstSize / secondSize}`; + firstContainer.style.flex = newFlex; + store(newFlex); } } - if (curr !== last) { - tokens.length = last; + function handleMouseUp() { + document.removeEventListener("mousemove", handleMouseMove); + document.removeEventListener("mouseup", handleMouseUp); } + document.addEventListener("mousemove", handleMouseMove); + document.addEventListener("mouseup", handleMouseUp); } - } - - /** internal - * class Core - * - * Top-level rules executor. Glues block/inline parsers and does intermediate - * transformations. - **/ - - const _rules$2 = [['normalize', normalize], ['block', block], ['inline', inline], ['linkify', linkify$1], ['replacements', replace], ['smartquotes', smartquotes], - // `text_join` finds `text_special` tokens (for escape sequences) - // and joins them with the rest of the text - ['text_join', text_join]]; - - /** - * new Core() - **/ - function Core() { - /** - * Core#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of core rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules$2.length; i++) { - this.ruler.push(_rules$2[i][0], _rules$2[i][1]); + dragBarContainer.addEventListener("mousedown", handleMouseDown); + function reset() { + if (firstRef.current) { + firstRef.current.style.flex = defaultFlexRef.current; + } + store(defaultFlexRef.current); + setHiddenElementWithCallback(null); } - } - - /** - * Core.process(state) - * - * Executes core chain rules. - **/ - Core.prototype.process = function (state) { - const rules = this.ruler.getRules(''); - for (let i = 0, l = rules.length; i < l; i++) { - rules[i](state); + dragBarContainer.addEventListener("dblclick", reset); + return () => { + dragBarContainer.removeEventListener("mousedown", handleMouseDown); + dragBarContainer.removeEventListener("dblclick", reset); + }; + }, [direction, setHiddenElementWithCallback, sizeThresholdFirst, sizeThresholdSecond, store]); + return React.useMemo(() => ({ + dragBarRef, + hiddenElement, + firstRef, + setHiddenElement, + secondRef + }), [hiddenElement, setHiddenElement]); +} +const DEFAULT_FLEX = 1; +const HIDE_FIRST = "hide-first"; +const HIDE_SECOND = "hide-second"; +const ToolbarButton = React.forwardRef(({ + label, + onClick, + ...props +}, ref) => { + const [error, setError] = React.useState(null); + const handleClick = React.useCallback(event => { + try { + onClick == null ? void 0 : onClick(event); + setError(null); + } catch (err) { + setError(err instanceof Error ? err : new Error(`Toolbar button click failed: ${err}`)); } + }, [onClick]); + return /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-toolbar-button", error && "error", props.className), + onClick: handleClick, + "aria-label": error ? error.message : label, + "aria-invalid": error ? "true" : props["aria-invalid"] + }) + }); +}); +ToolbarButton.displayName = "ToolbarButton"; +function ExecuteButton() { + const { + queryEditor, + setOperationName + } = useEditorContext({ + nonNull: true, + caller: ExecuteButton + }); + const { + isFetching, + isSubscribed, + operationName, + run, + stop + } = useExecutionContext({ + nonNull: true, + caller: ExecuteButton + }); + const operations = (queryEditor == null ? void 0 : queryEditor.operations) || []; + const hasOptions = operations.length > 1 && typeof operationName !== "string"; + const isRunning = isFetching || isSubscribed; + const label = `${isRunning ? "Stop" : "Execute"} query (Ctrl-Enter)`; + const buttonProps = { + type: "button", + className: "graphiql-execute-button", + children: isRunning ? /* @__PURE__ */jsxRuntime.jsx(StopIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(PlayIcon, {}), + "aria-label": label }; - Core.prototype.State = StateCore; - - // Parser state class - - function StateBlock(src, md, env, tokens) { - this.src = src; - - // link to parser instance - this.md = md; - this.env = env; - - // - // Internal state vartiables - // - - this.tokens = tokens; - this.bMarks = []; // line begin offsets for fast jumps - this.eMarks = []; // line end offsets for fast jumps - this.tShift = []; // offsets of the first non-space characters (tabs not expanded) - this.sCount = []; // indents for each line (tabs expanded) - - // An amount of virtual spaces (tabs expanded) between beginning - // of each line (bMarks) and real beginning of that line. - // - // It exists only as a hack because blockquotes override bMarks - // losing information in the process. - // - // It's used only when expanding tabs, you can think about it as - // an initial tab length, e.g. bsCount=21 applied to string `\t123` - // means first tab should be expanded to 4-21%4 === 3 spaces. - // - this.bsCount = []; - - // block parser variables - - // required block content indent (for example, if we are - // inside a list, it would be positioned after list marker) - this.blkIndent = 0; - this.line = 0; // line index in src - this.lineMax = 0; // lines count - this.tight = false; // loose/tight mode for lists - this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) - this.listIndent = -1; // indent of the current list block (-1 if there isn't any) - - // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' - // used in lists to determine if they interrupt a paragraph - this.parentType = 'root'; - this.level = 0; - - // Create caches - // Generate markers. - const s = this.src; - for (let start = 0, pos = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos < len; pos++) { - const ch = s.charCodeAt(pos); - if (!indent_found) { - if (isSpace(ch)) { - indent++; - if (ch === 0x09) { - offset += 4 - offset % 4; - } else { - offset++; - } - continue; + return hasOptions && !isRunning ? /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { + children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { + ...buttonProps + }) + }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { + children: operations.map((operation, i) => { + const opName = operation.name ? operation.name.value : ``; + return /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Item, { + onSelect: () => { + var _a; + const selectedOperationName = (_a = operation.name) == null ? void 0 : _a.value; + if (queryEditor && selectedOperationName && selectedOperationName !== queryEditor.operationName) { + setOperationName(selectedOperationName); + } + run(); + }, + children: opName + }, `${opName}-${i}`); + }) + })] + }) : /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx("button", { + ...buttonProps, + onClick: () => { + if (isRunning) { + stop(); } else { - indent_found = true; + run(); } } - if (ch === 0x0A || pos === len - 1) { - if (ch !== 0x0A) { - pos++; - } - this.bMarks.push(start); - this.eMarks.push(pos); - this.tShift.push(indent); - this.sCount.push(offset); - this.bsCount.push(0); - indent_found = false; - indent = 0; - offset = 0; - start = pos + 1; - } - } - - // Push fake entry to simplify cache bounds checks - this.bMarks.push(s.length); - this.eMarks.push(s.length); - this.tShift.push(0); - this.sCount.push(0); - this.bsCount.push(0); - this.lineMax = this.bMarks.length - 1; // don't count last fake line + }) + }); +} +const ToolbarMenuRoot = ({ + button, + children, + label, + ...props +}) => /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { + ...props, + children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { + className: clsx.clsx("graphiql-un-styled graphiql-toolbar-menu", props.className), + "aria-label": label, + children: button + }) + }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { + children + })] +}); +const ToolbarMenu = createComponentGroup(ToolbarMenuRoot, { + Item: DropdownMenu.Item +}); +exports.Argument = Argument; +exports.ArgumentIcon = ArgumentIcon; +exports.Button = Button$1; +exports.ButtonGroup = ButtonGroup; +exports.ChevronDownIcon = ChevronDownIcon; +exports.ChevronLeftIcon = ChevronLeftIcon; +exports.ChevronUpIcon = ChevronUpIcon; +exports.CloseIcon = CloseIcon; +exports.CopyIcon = CopyIcon; +exports.DOC_EXPLORER_PLUGIN = DOC_EXPLORER_PLUGIN; +exports.DefaultValue = DefaultValue; +exports.DeprecatedArgumentIcon = DeprecatedArgumentIcon; +exports.DeprecatedEnumValueIcon = DeprecatedEnumValueIcon; +exports.DeprecatedFieldIcon = DeprecatedFieldIcon; +exports.DeprecationReason = DeprecationReason; +exports.Dialog = Dialog; +exports.DialogRoot = DialogRoot; +exports.Directive = Directive; +exports.DirectiveIcon = DirectiveIcon; +exports.DocExplorer = DocExplorer; +exports.DocsFilledIcon = DocsFilledIcon; +exports.DocsIcon = DocsIcon; +exports.DropdownMenu = DropdownMenu; +exports.EditorContext = EditorContext; +exports.EditorContextProvider = EditorContextProvider; +exports.EnumValueIcon = EnumValueIcon; +exports.ExecuteButton = ExecuteButton; +exports.ExecutionContext = ExecutionContext; +exports.ExecutionContextProvider = ExecutionContextProvider; +exports.ExplorerContext = ExplorerContext; +exports.ExplorerContextProvider = ExplorerContextProvider; +exports.ExplorerSection = ExplorerSection; +exports.FieldDocumentation = FieldDocumentation; +exports.FieldIcon = FieldIcon; +exports.FieldLink = FieldLink; +exports.GraphiQLProvider = GraphiQLProvider; +exports.HISTORY_PLUGIN = HISTORY_PLUGIN; +exports.HeaderEditor = HeaderEditor; +exports.History = History; +exports.HistoryContext = HistoryContext; +exports.HistoryContextProvider = HistoryContextProvider; +exports.HistoryIcon = HistoryIcon; +exports.ImagePreview = ImagePreview; +exports.ImplementsIcon = ImplementsIcon; +exports.KeyboardShortcutIcon = KeyboardShortcutIcon; +exports.MagnifyingGlassIcon = MagnifyingGlassIcon; +exports.MarkdownContent = MarkdownContent; +exports.MergeIcon = MergeIcon; +exports.PenIcon = PenIcon; +exports.PlayIcon = PlayIcon; +exports.PluginContext = PluginContext; +exports.PluginContextProvider = PluginContextProvider; +exports.PlusIcon = PlusIcon; +exports.PrettifyIcon = PrettifyIcon; +exports.QueryEditor = QueryEditor; +exports.ReloadIcon = ReloadIcon; +exports.ResponseEditor = ResponseEditor; +exports.RootTypeIcon = RootTypeIcon; +exports.SchemaContext = SchemaContext; +exports.SchemaContextProvider = SchemaContextProvider; +exports.SchemaDocumentation = SchemaDocumentation; +exports.Search = Search; +exports.SettingsIcon = SettingsIcon; +exports.Spinner = Spinner; +exports.StarFilledIcon = StarFilledIcon; +exports.StarIcon = StarIcon; +exports.StopIcon = StopIcon; +exports.StorageContext = StorageContext; +exports.StorageContextProvider = StorageContextProvider; +exports.Tab = Tab; +exports.Tabs = Tabs; +exports.ToolbarButton = ToolbarButton; +exports.ToolbarMenu = ToolbarMenu; +exports.Tooltip = Tooltip; +exports.TooltipRoot = TooltipRoot; +exports.TrashIcon = TrashIcon; +exports.TypeDocumentation = TypeDocumentation; +exports.TypeIcon = TypeIcon; +exports.TypeLink = TypeLink; +exports.UnStyledButton = UnStyledButton; +exports.VariableEditor = VariableEditor; +exports.useAutoCompleteLeafs = useAutoCompleteLeafs; +exports.useCopyQuery = useCopyQuery; +exports.useDragResize = useDragResize; +exports.useEditorContext = useEditorContext; +exports.useEditorState = useEditorState; +exports.useExecutionContext = useExecutionContext; +exports.useExplorerContext = useExplorerContext; +exports.useHeaderEditor = useHeaderEditor; +exports.useHeadersEditorState = useHeadersEditorState; +exports.useHistoryContext = useHistoryContext; +exports.useMergeQuery = useMergeQuery; +exports.useOperationsEditorState = useOperationsEditorState; +exports.useOptimisticState = useOptimisticState; +exports.usePluginContext = usePluginContext; +exports.usePrettifyEditors = usePrettifyEditors; +exports.useQueryEditor = useQueryEditor; +exports.useResponseEditor = useResponseEditor; +exports.useSchemaContext = useSchemaContext; +exports.useStorageContext = useStorageContext; +exports.useTheme = useTheme; +exports.useVariableEditor = useVariableEditor; +exports.useVariablesEditorState = useVariablesEditorState; + +/***/ }), + +/***/ "../../graphiql-react/dist/info-addon.cjs.js": +/*!***************************************************!*\ + !*** ../../graphiql-react/dist/info-addon.cjs.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +codemirror.CodeMirror.defineOption("info", false, (cm, options, old) => { + if (old && old !== codemirror.CodeMirror.Init) { + const oldOnMouseOver = cm.state.info.onMouseOver; + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); + clearTimeout(cm.state.info.hoverTimeout); + delete cm.state.info; + } + if (options) { + const state = cm.state.info = createState(options); + state.onMouseOver = onMouseOver.bind(null, cm); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); + } +}); +function createState(options) { + return { + options: options instanceof Function ? { + render: options + } : options === true ? {} : options + }; +} +function getHoverTime(cm) { + const { + options + } = cm.state.info; + return (options === null || options === void 0 ? void 0 : options.hoverTime) || 500; +} +function onMouseOver(cm, e) { + const state = cm.state.info; + const target = e.target || e.srcElement; + if (!(target instanceof HTMLElement)) { + return; } - - // Push new token to "stream". - // - StateBlock.prototype.push = function (type, tag, nesting) { - const token = new Token(type, tag, nesting); - token.block = true; - if (nesting < 0) this.level--; // closing tag - token.level = this.level; - if (nesting > 0) this.level++; // opening tag - - this.tokens.push(token); - return token; + if (target.nodeName !== "SPAN" || state.hoverTimeout !== void 0) { + return; + } + const box = target.getBoundingClientRect(); + const onMouseMove = function () { + clearTimeout(state.hoverTimeout); + state.hoverTimeout = setTimeout(onHover, hoverTime); }; - StateBlock.prototype.isEmpty = function isEmpty(line) { - return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; + const onMouseOut = function () { + codemirror.CodeMirror.off(document, "mousemove", onMouseMove); + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); + clearTimeout(state.hoverTimeout); + state.hoverTimeout = void 0; }; - StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { - for (let max = this.lineMax; from < max; from++) { - if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { - break; - } - } - return from; + const onHover = function () { + codemirror.CodeMirror.off(document, "mousemove", onMouseMove); + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); + state.hoverTimeout = void 0; + onMouseHover(cm, box); }; - - // Skip spaces from given position. - StateBlock.prototype.skipSpaces = function skipSpaces(pos) { - for (let max = this.src.length; pos < max; pos++) { - const ch = this.src.charCodeAt(pos); - if (!isSpace(ch)) { - break; - } - } - return pos; + const hoverTime = getHoverTime(cm); + state.hoverTimeout = setTimeout(onHover, hoverTime); + codemirror.CodeMirror.on(document, "mousemove", onMouseMove); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); +} +function onMouseHover(cm, box) { + const pos = cm.coordsChar({ + left: (box.left + box.right) / 2, + top: (box.top + box.bottom) / 2 + }, "window"); + const state = cm.state.info; + const { + options + } = state; + const render = options.render || cm.getHelper(pos, "info"); + if (render) { + const token = cm.getTokenAt(pos, true); + if (token) { + const info = render(token, options, cm, pos); + if (info) { + showPopup(cm, box, info); + } + } + } +} +function showPopup(cm, box, info) { + const popup = document.createElement("div"); + popup.className = "CodeMirror-info"; + popup.append(info); + document.body.append(popup); + const popupBox = popup.getBoundingClientRect(); + const popupStyle = window.getComputedStyle(popup); + const popupWidth = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight); + const popupHeight = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom); + let topPos = box.bottom; + if (popupHeight > window.innerHeight - box.bottom - 15 && box.top > window.innerHeight - box.bottom) { + topPos = box.top - popupHeight; + } + if (topPos < 0) { + topPos = box.bottom; + } + let leftPos = Math.max(0, window.innerWidth - popupWidth - 15); + if (leftPos > box.left) { + leftPos = box.left; + } + popup.style.opacity = "1"; + popup.style.top = topPos + "px"; + popup.style.left = leftPos + "px"; + let popupTimeout; + const onMouseOverPopup = function () { + clearTimeout(popupTimeout); }; - - // Skip spaces from given position in reverse. - StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) { - if (pos <= min) { - return pos; - } - while (pos > min) { - if (!isSpace(this.src.charCodeAt(--pos))) { - return pos + 1; - } - } - return pos; + const onMouseOut = function () { + clearTimeout(popupTimeout); + popupTimeout = setTimeout(hidePopup, 200); }; - - // Skip char codes from given position - StateBlock.prototype.skipChars = function skipChars(pos, code) { - for (let max = this.src.length; pos < max; pos++) { - if (this.src.charCodeAt(pos) !== code) { - break; - } + const hidePopup = function () { + codemirror.CodeMirror.off(popup, "mouseover", onMouseOverPopup); + codemirror.CodeMirror.off(popup, "mouseout", onMouseOut); + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); + if (popup.style.opacity) { + popup.style.opacity = "0"; + setTimeout(() => { + if (popup.parentNode) { + popup.remove(); + } + }, 600); + } else if (popup.parentNode) { + popup.remove(); } - return pos; }; - - // Skip char codes reverse from given position - 1 - StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) { - if (pos <= min) { - return pos; - } - while (pos > min) { - if (code !== this.src.charCodeAt(--pos)) { - return pos + 1; - } + codemirror.CodeMirror.on(popup, "mouseover", onMouseOverPopup); + codemirror.CodeMirror.on(popup, "mouseout", onMouseOut); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); +} + +/***/ }), + +/***/ "../../graphiql-react/dist/info.cjs.js": +/*!*********************************************!*\ + !*** ../../graphiql-react/dist/info.cjs.js ***! + \*********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); +__webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"); +codemirror.CodeMirror.registerHelper("info", "graphql", (token, options) => { + var _a; + if (!options.schema || !token.state) { + return; + } + const { + kind, + step + } = token.state; + const typeInfo = SchemaReference.getTypeInfo(options.schema, token.state); + if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef || kind === "ObjectField" && step === 0 && typeInfo.fieldDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderField(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.fieldDef); + return into; + } + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderDirective(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.directiveDef); + return into; + } + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderArg(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.argDef); + return into; + } + if (kind === "EnumValue" && ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.description)) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderEnumValue(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.enumValue); + return into; + } + if (kind === "NamedType" && typeInfo.type && typeInfo.type.description) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderType(header, typeInfo, options, typeInfo.type); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.type); + return into; + } +}); +function renderField(into, typeInfo, options) { + renderQualifiedField(into, typeInfo, options); + renderTypeAnnotation(into, typeInfo, options, typeInfo.type); +} +function renderQualifiedField(into, typeInfo, options) { + var _a; + const fieldName = ((_a = typeInfo.fieldDef) === null || _a === void 0 ? void 0 : _a.name) || ""; + text(into, fieldName, "field-name", options, SchemaReference.getFieldReference(typeInfo)); +} +function renderDirective(into, typeInfo, options) { + var _a; + const name = "@" + (((_a = typeInfo.directiveDef) === null || _a === void 0 ? void 0 : _a.name) || ""); + text(into, name, "directive-name", options, SchemaReference.getDirectiveReference(typeInfo)); +} +function renderArg(into, typeInfo, options) { + var _a; + const name = ((_a = typeInfo.argDef) === null || _a === void 0 ? void 0 : _a.name) || ""; + text(into, name, "arg-name", options, SchemaReference.getArgumentReference(typeInfo)); + renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); +} +function renderEnumValue(into, typeInfo, options) { + var _a; + const name = ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.name) || ""; + renderType(into, typeInfo, options, typeInfo.inputType); + text(into, "."); + text(into, name, "enum-value", options, SchemaReference.getEnumValueReference(typeInfo)); +} +function renderTypeAnnotation(into, typeInfo, options, t) { + const typeSpan = document.createElement("span"); + typeSpan.className = "type-name-pill"; + if (t instanceof graphql.GraphQLNonNull) { + renderType(typeSpan, typeInfo, options, t.ofType); + text(typeSpan, "!"); + } else if (t instanceof graphql.GraphQLList) { + text(typeSpan, "["); + renderType(typeSpan, typeInfo, options, t.ofType); + text(typeSpan, "]"); + } else { + text(typeSpan, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); + } + into.append(typeSpan); +} +function renderType(into, typeInfo, options, t) { + if (t instanceof graphql.GraphQLNonNull) { + renderType(into, typeInfo, options, t.ofType); + text(into, "!"); + } else if (t instanceof graphql.GraphQLList) { + text(into, "["); + renderType(into, typeInfo, options, t.ofType); + text(into, "]"); + } else { + text(into, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); + } +} +function renderDescription(into, options, def) { + const { + description + } = def; + if (description) { + const descriptionDiv = document.createElement("div"); + descriptionDiv.className = "info-description"; + if (options.renderDescription) { + descriptionDiv.innerHTML = options.renderDescription(description); + } else { + descriptionDiv.append(document.createTextNode(description)); + } + into.append(descriptionDiv); + } + renderDeprecation(into, options, def); +} +function renderDeprecation(into, options, def) { + const reason = def.deprecationReason; + if (reason) { + const deprecationDiv = document.createElement("div"); + deprecationDiv.className = "info-deprecation"; + into.append(deprecationDiv); + const label = document.createElement("span"); + label.className = "info-deprecation-label"; + label.append(document.createTextNode("Deprecated")); + deprecationDiv.append(label); + const reasonDiv = document.createElement("div"); + reasonDiv.className = "info-deprecation-reason"; + if (options.renderDescription) { + reasonDiv.innerHTML = options.renderDescription(reason); + } else { + reasonDiv.append(document.createTextNode(reason)); } - return pos; - }; - - // cut lines range from source. - StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) { - if (begin >= end) { - return ''; + deprecationDiv.append(reasonDiv); + } +} +function text(into, content, className = "", options = { + onClick: null +}, ref = null) { + if (className) { + const { + onClick + } = options; + let node; + if (onClick) { + node = document.createElement("a"); + node.href = "javascript:void 0"; + node.addEventListener("click", e => { + e.preventDefault(); + onClick(ref, e); + }); + } else { + node = document.createElement("span"); } - const queue = new Array(end - begin); - for (let i = 0, line = begin; line < end; line++, i++) { - let lineIndent = 0; - const lineStart = this.bMarks[line]; - let first = lineStart; - let last; - if (line + 1 < end || keepLastLF) { - // No need for bounds check because we have fake entry on tail. - last = this.eMarks[line] + 1; - } else { - last = this.eMarks[line]; - } - while (first < last && lineIndent < indent) { - const ch = this.src.charCodeAt(first); - if (isSpace(ch)) { - if (ch === 0x09) { - lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4; - } else { - lineIndent++; + node.className = className; + node.append(document.createTextNode(content)); + into.append(node); + } else { + into.append(document.createTextNode(content)); + } +} + +/***/ }), + +/***/ "../../graphiql-react/dist/javascript.cjs.js": +/*!***************************************************!*\ + !*** ../../graphiql-react/dist/javascript.cjs.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - } else if (first - lineStart < this.tShift[line]) { - // patched tShift masked characters to look like spaces (blockquotes, list markers) - lineIndent++; - } else { - break; - } - first++; - } - if (lineIndent > indent) { - // partially expanding tabs in code blocks, e.g '\t\tfoobar' - // with indent=2 becomes ' \tfoobar' - queue[i] = new Array(lineIndent - indent + 1).join(' ') + this.src.slice(first, last); - } else { - queue[i] = this.src.slice(first, last); - } - } - return queue.join(''); - }; - - // re-export Token class to use in block rules - StateBlock.prototype.Token = Token; - - // GFM table, https://github.github.com/gfm/#tables-extension- - - // Limit the amount of empty autocompleted cells in a table, - // see https://github.com/markdown-it/markdown-it/issues/1000, - // - // Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. - // We set it to 65k, which can expand user input by a factor of x370 - // (256x256 square is 1.8kB expanded into 650kB). - const MAX_AUTOCOMPLETED_CELLS = 0x10000; - function getLine(state, line) { - const pos = state.bMarks[line] + state.tShift[line]; - const max = state.eMarks[line]; - return state.src.slice(pos, max); - } - function escapedSplit(str) { - const result = []; - const max = str.length; - let pos = 0; - let ch = str.charCodeAt(pos); - let isEscaped = false; - let lastPos = 0; - let current = ''; - while (pos < max) { - if (ch === 0x7c /* | */) { - if (!isEscaped) { - // pipe separating cells, '|' - result.push(current + str.substring(lastPos, pos)); - current = ''; - lastPos = pos + 1; - } else { - // escaped pipe, '\|' - current += str.substring(lastPos, pos - 1); - lastPos = pos; } } - isEscaped = ch === 0x5c /* \ */; - pos++; - ch = str.charCodeAt(pos); } - result.push(current + str.substring(lastPos)); - return result; } - function table(state, startLine, endLine, silent) { - // should have at least two lines - if (startLine + 2 > endLine) { - return false; - } - let nextLine = startLine + 1; - if (state.sCount[nextLine] < state.blkIndent) { - return false; - } - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - return false; - } - - // first character of the second line should be '|', '-', ':', - // and no other characters are allowed but spaces; - // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp - - let pos = state.bMarks[nextLine] + state.tShift[nextLine]; - if (pos >= state.eMarks[nextLine]) { - return false; - } - const firstCh = state.src.charCodeAt(pos++); - if (firstCh !== 0x7C /* | */ && firstCh !== 0x2D /* - */ && firstCh !== 0x3A /* : */) { - return false; - } - if (pos >= state.eMarks[nextLine]) { - return false; - } - const secondCh = state.src.charCodeAt(pos++); - if (secondCh !== 0x7C /* | */ && secondCh !== 0x2D /* - */ && secondCh !== 0x3A /* : */ && !isSpace(secondCh)) { - return false; - } - - // if first character is '-', then second character must not be a space - // (due to parsing ambiguity with list) - if (firstCh === 0x2D /* - */ && isSpace(secondCh)) { - return false; - } - while (pos < state.eMarks[nextLine]) { - const ch = state.src.charCodeAt(pos); - if (ch !== 0x7C /* | */ && ch !== 0x2D /* - */ && ch !== 0x3A /* : */ && !isSpace(ch)) { - return false; + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var javascript$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + CodeMirror.defineMode("javascript", function (config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var trackScope = parserConfig.trackScope !== false; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + var keywords = function () { + function kw(type2) { + return { + type: type2, + style: "keyword" + }; + } + var A = kw("keyword a"), + B = kw("keyword b"), + C = kw("keyword c"), + D = kw("keyword d"); + var operator = kw("operator"), + atom = { + type: "atom", + style: "atom" + }; + return { + "if": kw("if"), + "while": A, + "with": A, + "else": B, + "do": B, + "try": B, + "finally": B, + "return": D, + "break": D, + "continue": D, + "new": kw("new"), + "delete": C, + "void": C, + "throw": C, + "debugger": kw("debugger"), + "var": kw("var"), + "const": kw("var"), + "let": kw("var"), + "function": kw("function"), + "catch": kw("catch"), + "for": kw("for"), + "switch": kw("switch"), + "case": kw("case"), + "default": kw("default"), + "in": operator, + "typeof": operator, + "instanceof": operator, + "true": atom, + "false": atom, + "null": atom, + "undefined": atom, + "NaN": atom, + "Infinity": atom, + "this": kw("this"), + "class": kw("class"), + "super": kw("atom"), + "yield": C, + "export": kw("export"), + "import": kw("import"), + "extends": C, + "await": C + }; + }(); + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + function readRegexp(stream) { + var escaped = false, + next, + inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true;else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + var type, content; + function ret(tp, style, cont2) { + type = tp; + content = cont2; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#" && stream.peek() == "!") { + stream.skipToEnd(); + return ret("meta", "meta"); + } else if (ch == "#" && stream.eatWhile(wordRE)) { + return ret("variable", "property"); + } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("="); + } else if (/[<>*+\-|&?]/.test(ch)) { + stream.eat(ch); + if (ch == ">") stream.eat(ch); + } + } + if (ch == "?" && stream.eat(".")) return ret("."); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(); + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word]; + return ret(kw.type, kw.style, word); + } + if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word); + } + return ret("variable", "variable", word); + } } - pos++; - } - let lineText = getLine(state, startLine + 1); - let columns = lineText.split('|'); - const aligns = []; - for (let i = 0; i < columns.length; i++) { - const t = columns[i].trim(); - if (!t) { - // allow empty columns before and after table, but not in between columns; - // e.g. allow ` |---| `, disallow ` ---||--- ` - if (i === 0 || i === columns.length - 1) { - continue; - } else { - return false; + function tokenString(quote) { + return function (stream, state) { + var escaped = false, + next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = ch == "*"; } + return ret("comment", "comment"); } - if (!/^:?-+:?$/.test(t)) { - return false; + function tokenQuasi(stream, state) { + var escaped = false, + next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + var brackets = "([{}])"; + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + if (isTS) { + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)); + if (m) arrow = m.index; + } + var depth = 0, + sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { + ++pos; + break; + } + if (--depth == 0) { + if (ch == "(") sawSomething = true; + break; + } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (;; --pos) { + if (pos == 0) return; + var next = stream.string.charAt(pos - 1); + if (next == ch && stream.string.charAt(pos - 2) != "\\") { + pos--; + break; + } + } + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; } - if (t.charCodeAt(t.length - 1) === 0x3A /* : */) { - aligns.push(t.charCodeAt(0) === 0x3A /* : */ ? 'center' : 'right'); - } else if (t.charCodeAt(0) === 0x3A /* : */) { - aligns.push('left'); - } else { - aligns.push(''); + var atomicTypes = { + "atom": true, + "number": true, + "variable": true, + "string": true, + "regexp": true, + "this": true, + "import": true, + "jsonld-keyword": true + }; + function JSLexical(indented, column, type2, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type2; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + function inScope(state, varname) { + if (!trackScope) return false; + for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; + for (var cx2 = state.context; cx2; cx2 = cx2.prev) { + for (var v = cx2.vars; v; v = v.next) if (v.name == varname) return true; + } + } + function parseJS(state, style, type2, content2, stream) { + var cc = state.cc; + cx.state = state; + cx.stream = stream; + cx.marked = null, cx.cc = cc; + cx.style = style; + if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; + while (true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type2, content2)) { + while (cc.length && cc[cc.length - 1].lex) cc.pop()(); + if (cx.marked) return cx.marked; + if (type2 == "variable" && inScope(state, content2)) return "variable-2"; + return style; + } + } + } + var cx = { + state: null, + column: null, + marked: null, + cc: null + }; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } - } - lineText = getLine(state, startLine).trim(); - if (lineText.indexOf('|') === -1) { - return false; - } - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - columns = escapedSplit(lineText); - if (columns.length && columns[0] === '') columns.shift(); - if (columns.length && columns[columns.length - 1] === '') columns.pop(); - - // header row will define an amount of columns in the entire table, - // and align row should be exactly the same (the rest of the rows can differ) - const columnCount = columns.length; - if (columnCount === 0 || columnCount !== aligns.length) { - return false; - } - if (silent) { - return true; - } - const oldParentType = state.parentType; - state.parentType = 'table'; - - // use 'blockquote' lists for termination because it's - // the most similar to tables - const terminatorRules = state.md.block.ruler.getRules('blockquote'); - const token_to = state.push('table_open', 'table', 1); - const tableLines = [startLine, 0]; - token_to.map = tableLines; - const token_tho = state.push('thead_open', 'thead', 1); - token_tho.map = [startLine, startLine + 1]; - const token_htro = state.push('tr_open', 'tr', 1); - token_htro.map = [startLine, startLine + 1]; - for (let i = 0; i < columns.length; i++) { - const token_ho = state.push('th_open', 'th', 1); - if (aligns[i]) { - token_ho.attrs = [['style', 'text-align:' + aligns[i]]]; + function cont() { + pass.apply(null, arguments); + return true; } - const token_il = state.push('inline', '', 0); - token_il.content = columns[i].trim(); - token_il.children = []; - state.push('th_close', 'th', -1); - } - state.push('tr_close', 'tr', -1); - state.push('thead_close', 'thead', -1); - let tbodyLines; - let autocompletedCells = 0; - for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { - if (state.sCount[nextLine] < state.blkIndent) { - break; + function inList(name, list) { + for (var v = list; v; v = v.next) if (v.name == name) return true; + return false; } - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (!trackScope) return; + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + var newContext = registerVarScoped(varname, state.context); + if (newContext != null) { + state.context = newContext; + return; + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars); + return; + } } + if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars); } - if (terminate) { - break; + function registerVarScoped(varname, context) { + if (!context) { + return null; + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev); + if (!inner) return null; + if (inner == context.prev) return context; + return new Context(inner, context.vars, true); + } else if (inList(varname, context.vars)) { + return context; + } else { + return new Context(context.prev, new Var(varname, context.vars), false); + } + } + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; + } + function Context(prev, vars, block2) { + this.prev = prev; + this.vars = vars; + this.block = block2; + } + function Var(name, next) { + this.name = name; + this.next = next; + } + var defaultVars = new Var("this", new Var("arguments", null)); + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false); + cx.state.localVars = defaultVars; + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true); + cx.state.localVars = null; + } + pushcontext.lex = pushblockcontext.lex = true; + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + popcontext.lex = true; + function pushlex(type2, info) { + var result = function () { + var state = cx.state, + indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented;else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type2, null, state.lexical, info); + }; + result.lex = true; + return result; } - lineText = getLine(state, nextLine).trim(); - if (!lineText) { - break; + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + function expect(wanted) { + function exp(type2) { + if (type2 == wanted) return cont();else if (wanted == ";" || type2 == "}" || type2 == ")" || type2 == "]") return pass();else return cont(exp); + } + return exp; + } + function statement(type2, value) { + if (type2 == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type2 == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type2 == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type2 == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type2 == "debugger") return cont(expect(";")); + if (type2 == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type2 == ";") return cont(); + if (type2 == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type2 == "function") return cont(functiondef); + if (type2 == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form", type2 == "class" ? type2 : value), className, poplex); + } + if (type2 == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword"; + return cont(statement); + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword"; + if (value == "enum") return cont(enumdef);else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); + } else if (isTS && value == "namespace") { + cx.marked = "keyword"; + return cont(pushlex("form"), expression, statement, poplex); + } else if (isTS && value == "abstract") { + cx.marked = "keyword"; + return cont(statement); + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type2 == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); + if (type2 == "case") return cont(expression, expect(":")); + if (type2 == "default") return cont(expect(":")); + if (type2 == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type2 == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type2 == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type2 == "async") return cont(statement); + if (value == "@") return cont(expression, statement); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type2) { + if (type2 == "(") return cont(funarg, expect(")")); + } + function expression(type2, value) { + return expressionInner(type2, value, false); + } + function expressionNoComma(type2, value) { + return expressionInner(type2, value, true); + } + function parenExpr(type2) { + if (type2 != "(") return pass(); + return cont(pushlex(")"), maybeexpression, expect(")"), poplex); + } + function expressionInner(type2, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);else if (type2 == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); + if (type2 == "function") return cont(functiondef, maybeop); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form"), classExpression, poplex); + } + if (type2 == "keyword c" || type2 == "async") return cont(noComma ? expressionNoComma : expression); + if (type2 == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type2 == "operator" || type2 == "spread") return cont(noComma ? expressionNoComma : expression); + if (type2 == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type2 == "{") return contCommasep(objprop, "}", null, maybeop); + if (type2 == "quasi") return pass(quasi, maybeop); + if (type2 == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type2) { + if (type2.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + function maybeoperatorComma(type2, value) { + if (type2 == ",") return cont(maybeexpression); + return maybeoperatorNoComma(type2, value, false); + } + function maybeoperatorNoComma(type2, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type2 == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type2 == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type2 == "quasi") { + return pass(quasi, me); + } + if (type2 == ";") return; + if (type2 == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type2 == ".") return cont(property, me); + if (type2 == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { + cx.marked = "keyword"; + return cont(typeexpr, me); + } + if (type2 == "regexp") { + cx.state.lastType = cx.marked = "operator"; + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); + return cont(expr); + } + } + function quasi(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(maybeexpression, continueQuasi); + } + function continueQuasi(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expression); + } + function arrowBodyNoComma(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function (type2) { + if (type2 == ".") return cont(noComma ? targetNoComma : target);else if (type2 == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);else return pass(noComma ? expressionNoComma : expression); + }; } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - break; + function target(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorComma); + } } - columns = escapedSplit(lineText); - if (columns.length && columns[0] === '') columns.shift(); - if (columns.length && columns[columns.length - 1] === '') columns.pop(); - - // note: autocomplete count can be negative if user specifies more columns than header, - // but that does not affect intended use (which is limiting expansion) - autocompletedCells += columnCount - columns.length; - if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) { - break; + function targetNoComma(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorNoComma); + } } - if (nextLine === startLine + 2) { - const token_tbo = state.push('tbody_open', 'tbody', 1); - token_tbo.map = tbodyLines = [startLine + 2, 0]; + function maybelabel(type2) { + if (type2 == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); } - const token_tro = state.push('tr_open', 'tr', 1); - token_tro.map = [nextLine, nextLine + 1]; - for (let i = 0; i < columnCount; i++) { - const token_tdo = state.push('td_open', 'td', 1); - if (aligns[i]) { - token_tdo.attrs = [['style', 'text-align:' + aligns[i]]]; + function property(type2) { + if (type2 == "variable") { + cx.marked = "property"; + return cont(); } - const token_il = state.push('inline', '', 0); - token_il.content = columns[i] ? columns[i].trim() : ''; - token_il.children = []; - state.push('td_close', 'td', -1); } - state.push('tr_close', 'tr', -1); - } - if (tbodyLines) { - state.push('tbody_close', 'tbody', -1); - tbodyLines[1] = nextLine; - } - state.push('table_close', 'table', -1); - tableLines[1] = nextLine; - state.parentType = oldParentType; - state.line = nextLine; - return true; - } - - // Code block (4 spaces padded) - - function code(state, startLine, endLine /*, silent */) { - if (state.sCount[startLine] - state.blkIndent < 4) { - return false; - } - let nextLine = startLine + 1; - let last = nextLine; - while (nextLine < endLine) { - if (state.isEmpty(nextLine)) { - nextLine++; - continue; + function objprop(type2, value) { + if (type2 == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + var m; + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length; + return cont(afterprop); + } else if (type2 == "number" || type2 == "string") { + cx.marked = jsonldMode ? "property" : cx.style + " property"; + return cont(afterprop); + } else if (type2 == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type2 == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == ":") { + return pass(afterprop); + } + } + function getterSetter(type2) { + if (type2 != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type2) { + if (type2 == ":") return cont(expressionNoComma); + if (type2 == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type2, value) { + if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function (type3, value2) { + if (type3 == end || value2 == end) return pass(); + return pass(what); + }, proceed); + } + if (type2 == end || value == end) return cont(); + if (sep && sep.indexOf(";") > -1) return pass(what); + return cont(expect(end)); + } + return function (type2, value) { + if (type2 == end || value == end) return cont(); + return pass(what, proceed); + }; } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - nextLine++; - last = nextLine; - continue; + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); } - break; - } - state.line = last; - const token = state.push('code_block', 'code', 0); - token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + '\n'; - token.map = [startLine, state.line]; - return true; - } - - // fences (``` lang, ~~~ lang) - - function fence(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (pos + 3 > max) { - return false; - } - const marker = state.src.charCodeAt(pos); - if (marker !== 0x7E /* ~ */ && marker !== 0x60 /* ` */) { - return false; - } - - // scan marker length - let mem = pos; - pos = state.skipChars(pos, marker); - let len = pos - mem; - if (len < 3) { - return false; - } - const markup = state.src.slice(mem, pos); - const params = state.src.slice(pos, max); - if (marker === 0x60 /* ` */) { - if (params.indexOf(String.fromCharCode(marker)) >= 0) { - return false; + function block(type2) { + if (type2 == "}") return cont(); + return pass(statement, block); } - } - - // Since start is found, we can report success here in validation mode - if (silent) { - return true; - } - - // search end of block - let nextLine = startLine; - let haveEndMarker = false; - for (;;) { - nextLine++; - if (nextLine >= endLine) { - // unclosed block should be autoclosed by end of document. - // also block seems to be autoclosed by end of parent - break; + function maybetype(type2, value) { + if (isTS) { + if (type2 == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } } - pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - if (pos < max && state.sCount[nextLine] < state.blkIndent) { - // non-empty line with negative indent should stop the list: - // - ``` - // test - break; + function maybetypeOrIn(type2, value) { + if (isTS && (type2 == ":" || value == "in")) return cont(typeexpr); } - if (state.src.charCodeAt(pos) !== marker) { - continue; + function mayberettype(type2) { + if (isTS && type2 == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);else return cont(typeexpr); + } } - if (state.sCount[nextLine] - state.blkIndent >= 4) { - // closing fence should be indented less than 4 spaces - continue; + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword"; + return cont(); + } } - pos = state.skipChars(pos, marker); - - // closing code fence must be at least as long as the opening one - if (pos - mem < len) { - continue; + function typeexpr(type2, value) { + if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { + cx.marked = "keyword"; + return cont(value == "typeof" ? expressionNoComma : typeexpr); + } + if (type2 == "variable" || value == "void") { + cx.marked = "type"; + return cont(afterType); + } + if (value == "|" || value == "&") return cont(typeexpr); + if (type2 == "string" || type2 == "number" || type2 == "atom") return cont(afterType); + if (type2 == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); + if (type2 == "{") return cont(pushlex("}"), typeprops, poplex, afterType); + if (type2 == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType); + if (type2 == "<") return cont(commasep(typeexpr, ">"), typeexpr); + if (type2 == "quasi") { + return pass(quasiType, afterType); + } } - - // make sure tail has spaces only - pos = state.skipSpaces(pos); - if (pos < max) { - continue; + function maybeReturnType(type2) { + if (type2 == "=>") return cont(typeexpr); } - haveEndMarker = true; - // found! - break; - } - - // If a fence has heading spaces, they should be removed from its inner block - len = state.sCount[startLine]; - state.line = nextLine + (haveEndMarker ? 1 : 0); - const token = state.push('fence', 'code', 0); - token.info = params; - token.content = state.getLines(startLine + 1, nextLine, len, true); - token.markup = markup; - token.map = [startLine, state.line]; - return true; - } - - // Block quotes - - function blockquote(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - const oldLineMax = state.lineMax; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - - // check the block quote marker - if (state.src.charCodeAt(pos) !== 0x3E /* > */) { - return false; - } - - // we know that it's going to be a valid blockquote, - // so no point trying to find the end of it in silent mode - if (silent) { - return true; - } - const oldBMarks = []; - const oldBSCount = []; - const oldSCount = []; - const oldTShift = []; - const terminatorRules = state.md.block.ruler.getRules('blockquote'); - const oldParentType = state.parentType; - state.parentType = 'blockquote'; - let lastLineEmpty = false; - let nextLine; - - // Search the end of the block - // - // Block ends with either: - // 1. an empty line outside: - // ``` - // > test - // - // ``` - // 2. an empty line inside: - // ``` - // > - // test - // ``` - // 3. another tag: - // ``` - // > test - // - - - - // ``` - for (nextLine = startLine; nextLine < endLine; nextLine++) { - // check if it's outdented, i.e. it's inside list item and indented - // less than said list item: - // - // ``` - // 1. anything - // > current blockquote - // 2. checking this line - // ``` - const isOutdented = state.sCount[nextLine] < state.blkIndent; - pos = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - if (pos >= max) { - // Case 1: line is not inside the blockquote, and this line is empty. - break; + function typeprops(type2) { + if (type2.match(/[\}\)\]]/)) return cont(); + if (type2 == "," || type2 == ";") return cont(typeprops); + return pass(typeprop, typeprops); } - if (state.src.charCodeAt(pos++) === 0x3E /* > */ && !isOutdented) { - // This line is inside the blockquote. - - // set offset past spaces and ">" - let initial = state.sCount[nextLine] + 1; - let spaceAfterMarker; - let adjustTab; - - // skip one optional space after '>' - if (state.src.charCodeAt(pos) === 0x20 /* space */) { - // ' > test ' - // ^ -- position start of line here: - pos++; - initial++; - adjustTab = false; - spaceAfterMarker = true; - } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { - spaceAfterMarker = true; - if ((state.bsCount[nextLine] + initial) % 4 === 3) { - // ' >\t test ' - // ^ -- position start of line here (tab has width===1) - pos++; - initial++; - adjustTab = false; - } else { - // ' >\t test ' - // ^ -- position start of line here + shift bsCount slightly - // to make extra space appear - adjustTab = true; - } - } else { - spaceAfterMarker = false; - } - let offset = initial; - oldBMarks.push(state.bMarks[nextLine]); - state.bMarks[nextLine] = pos; - while (pos < max) { - const ch = state.src.charCodeAt(pos); - if (isSpace(ch)) { - if (ch === 0x09) { - offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4; - } else { - offset++; - } - } else { - break; - } - pos++; + function typeprop(type2, value) { + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(typeprop); + } else if (value == "?" || type2 == "number" || type2 == "string") { + return cont(typeprop); + } else if (type2 == ":") { + return cont(typeexpr); + } else if (type2 == "[") { + return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); + } else if (type2 == "(") { + return pass(functiondecl, typeprop); + } else if (!type2.match(/[;\}\)\],]/)) { + return cont(); } - lastLineEmpty = pos >= max; - oldBSCount.push(state.bsCount[nextLine]); - state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); - oldSCount.push(state.sCount[nextLine]); - state.sCount[nextLine] = offset - initial; - oldTShift.push(state.tShift[nextLine]); - state.tShift[nextLine] = pos - state.bMarks[nextLine]; - continue; } - - // Case 2: line is not inside the blockquote, and the last line was empty. - if (lastLineEmpty) { - break; + function quasiType(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasiType); + return cont(typeexpr, continueQuasiType); } - - // Case 3: another tag found. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; + function continueQuasiType(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasiType); } } - if (terminate) { - // Quirk to enforce "hard termination mode" for paragraphs; - // normally if you call `tokenize(state, startLine, nextLine)`, - // paragraphs will look below nextLine for paragraph continuation, - // but if blockquote is terminated by another tag, they shouldn't - state.lineMax = nextLine; - if (state.blkIndent !== 0) { - // state.blkIndent was non-zero, we now set it to zero, - // so we need to re-calculate all offsets to appear as - // if indent wasn't changed - oldBMarks.push(state.bMarks[nextLine]); - oldBSCount.push(state.bsCount[nextLine]); - oldTShift.push(state.tShift[nextLine]); - oldSCount.push(state.sCount[nextLine]); - state.sCount[nextLine] -= state.blkIndent; - } - break; + function typearg(type2, value) { + if (type2 == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg); + if (type2 == ":") return cont(typeexpr); + if (type2 == "spread") return cont(typearg); + return pass(typeexpr); } - oldBMarks.push(state.bMarks[nextLine]); - oldBSCount.push(state.bsCount[nextLine]); - oldTShift.push(state.tShift[nextLine]); - oldSCount.push(state.sCount[nextLine]); - - // A negative indentation means that this is a paragraph continuation - // - state.sCount[nextLine] = -1; - } - const oldIndent = state.blkIndent; - state.blkIndent = 0; - const token_o = state.push('blockquote_open', 'blockquote', 1); - token_o.markup = '>'; - const lines = [startLine, 0]; - token_o.map = lines; - state.md.block.tokenize(state, startLine, nextLine); - const token_c = state.push('blockquote_close', 'blockquote', -1); - token_c.markup = '>'; - state.lineMax = oldLineMax; - state.parentType = oldParentType; - lines[1] = state.line; - - // Restore original tShift; this might not be necessary since the parser - // has already been here, but just to make sure we can do that. - for (let i = 0; i < oldTShift.length; i++) { - state.bMarks[i + startLine] = oldBMarks[i]; - state.tShift[i + startLine] = oldTShift[i]; - state.sCount[i + startLine] = oldSCount[i]; - state.bsCount[i + startLine] = oldBSCount[i]; - } - state.blkIndent = oldIndent; - return true; - } - - // Horizontal rule - - function hr(state, startLine, endLine, silent) { - const max = state.eMarks[startLine]; - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - let pos = state.bMarks[startLine] + state.tShift[startLine]; - const marker = state.src.charCodeAt(pos++); - - // Check hr marker - if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x5F /* _ */) { - return false; - } - - // markers can be mixed with spaces, but there should be at least 3 of them - - let cnt = 1; - while (pos < max) { - const ch = state.src.charCodeAt(pos++); - if (ch !== marker && !isSpace(ch)) { - return false; + function afterType(type2, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + if (value == "|" || type2 == "." || value == "&") return cont(typeexpr); + if (type2 == "[") return cont(typeexpr, expect("]"), afterType); + if (value == "extends" || value == "implements") { + cx.marked = "keyword"; + return cont(typeexpr); + } + if (value == "?") return cont(typeexpr, expect(":"), typeexpr); } - if (ch === marker) { - cnt++; + function maybeTypeArgs(_, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); } - } - if (cnt < 3) { - return false; - } - if (silent) { - return true; - } - state.line = startLine + 1; - const token = state.push('hr', 'hr', 0); - token.map = [startLine, state.line]; - token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); - return true; - } - - // Lists - - // Search `[-+*][\n ]`, returns next pos after marker on success - // or -1 on fail. - function skipBulletListMarker(state, startLine) { - const max = state.eMarks[startLine]; - let pos = state.bMarks[startLine] + state.tShift[startLine]; - const marker = state.src.charCodeAt(pos++); - // Check bullet - if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x2B /* + */) { - return -1; - } - if (pos < max) { - const ch = state.src.charCodeAt(pos); - if (!isSpace(ch)) { - // " -test " - is not a list item - return -1; + function typeparam() { + return pass(typeexpr, maybeTypeDefault); } - } - return pos; - } - - // Search `\d+[.)][\n ]`, returns next pos after marker on success - // or -1 on fail. - function skipOrderedListMarker(state, startLine) { - const start = state.bMarks[startLine] + state.tShift[startLine]; - const max = state.eMarks[startLine]; - let pos = start; - - // List marker should have at least 2 chars (digit + dot) - if (pos + 1 >= max) { - return -1; - } - let ch = state.src.charCodeAt(pos++); - if (ch < 0x30 /* 0 */ || ch > 0x39 /* 9 */) { - return -1; - } - for (;;) { - // EOL -> fail - if (pos >= max) { - return -1; + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr); } - ch = state.src.charCodeAt(pos++); - if (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) { - // List marker should have no more than 9 digits - // (prevents integer overflow in browsers) - if (pos - start >= 10) { - return -1; + function vardef(_, value) { + if (value == "enum") { + cx.marked = "keyword"; + return cont(enumdef); } - continue; + return pass(pattern, maybetype, maybeAssign, vardefCont); } - - // found valid marker - if (ch === 0x29 /* ) */ || ch === 0x2e /* . */) { - break; + function pattern(type2, value) { + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(pattern); + } + if (type2 == "variable") { + register(value); + return cont(); + } + if (type2 == "spread") return cont(pattern); + if (type2 == "[") return contCommasep(eltpattern, "]"); + if (type2 == "{") return contCommasep(proppattern, "}"); } - return -1; - } - if (pos < max) { - ch = state.src.charCodeAt(pos); - if (!isSpace(ch)) { - // " 1.test " - is not a list item - return -1; + function proppattern(type2, value) { + if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type2 == "variable") cx.marked = "property"; + if (type2 == "spread") return cont(pattern); + if (type2 == "}") return pass(); + if (type2 == "[") return cont(expression, expect("]"), expect(":"), proppattern); + return cont(expect(":"), pattern, maybeAssign); } - } - return pos; - } - function markTightParagraphs(state, idx) { - const level = state.level + 2; - for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) { - if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') { - state.tokens[i + 2].hidden = true; - state.tokens[i].hidden = true; - i += 2; + function eltpattern() { + return pass(pattern, maybeAssign); } - } - } - function list(state, startLine, endLine, silent) { - let max, pos, start, token; - let nextLine = startLine; - let tight = true; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - return false; - } - - // Special case: - // - item 1 - // - item 2 - // - item 3 - // - item 4 - // - this one is a paragraph continuation - if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) { - return false; - } - let isTerminatingParagraph = false; - - // limit conditions when list can interrupt - // a paragraph (validation mode only) - if (silent && state.parentType === 'paragraph') { - // Next list item should still terminate previous list item; - // - // This code can fail if plugins use blkIndent as well as lists, - // but I hope the spec gets fixed long before that happens. - // - if (state.sCount[nextLine] >= state.blkIndent) { - isTerminatingParagraph = true; + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); } - } - - // Detect list type and position after marker - let isOrdered; - let markerValue; - let posAfterMarker; - if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) { - isOrdered = true; - start = state.bMarks[nextLine] + state.tShift[nextLine]; - markerValue = Number(state.src.slice(start, posAfterMarker - 1)); - - // If we're starting a new ordered list right after - // a paragraph, it should start with 1. - if (isTerminatingParagraph && markerValue !== 1) return false; - } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) { - isOrdered = false; - } else { - return false; - } - - // If we're starting a new unordered list right after - // a paragraph, first line should not be empty. - if (isTerminatingParagraph) { - if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false; - } - - // For validation mode we can terminate immediately - if (silent) { - return true; - } - - // We should terminate list on style change. Remember first one to compare. - const markerCharCode = state.src.charCodeAt(posAfterMarker - 1); - - // Start list - const listTokIdx = state.tokens.length; - if (isOrdered) { - token = state.push('ordered_list_open', 'ol', 1); - if (markerValue !== 1) { - token.attrs = [['start', markerValue]]; + function vardefCont(type2) { + if (type2 == ",") return cont(vardef); } - } else { - token = state.push('bullet_list_open', 'ul', 1); - } - const listLines = [nextLine, 0]; - token.map = listLines; - token.markup = String.fromCharCode(markerCharCode); - - // - // Iterate list items - // - - let prevEmptyEnd = false; - const terminatorRules = state.md.block.ruler.getRules('list'); - const oldParentType = state.parentType; - state.parentType = 'list'; - while (nextLine < endLine) { - pos = posAfterMarker; - max = state.eMarks[nextLine]; - const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]); - let offset = initial; - while (pos < max) { - const ch = state.src.charCodeAt(pos); - if (ch === 0x09) { - offset += 4 - (offset + state.bsCount[nextLine]) % 4; - } else if (ch === 0x20) { - offset++; - } else { - break; + function maybeelse(type2, value) { + if (type2 == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type2, value) { + if (value == "await") return cont(forspec); + if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type2) { + if (type2 == "var") return cont(vardef, forspec2); + if (type2 == "variable") return cont(forspec2); + return pass(forspec2); + } + function forspec2(type2, value) { + if (type2 == ")") return cont(); + if (type2 == ";") return cont(forspec2); + if (value == "in" || value == "of") { + cx.marked = "keyword"; + return cont(expression, forspec2); } - pos++; + return pass(expression, forspec2); } - const contentStart = pos; - let indentAfterMarker; - if (contentStart >= max) { - // trimming space in "- \n 3" case, indent is 1 here - indentAfterMarker = 1; - } else { - indentAfterMarker = offset - initial; + function functiondef(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondef); + } + if (type2 == "variable") { + register(value); + return cont(functiondef); + } + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); } - - // If we have more than 4 spaces, the indent is 1 - // (the rest is just indented code block) - if (indentAfterMarker > 4) { - indentAfterMarker = 1; + function functiondecl(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondecl); + } + if (type2 == "variable") { + register(value); + return cont(functiondecl); + } + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); } - - // " - test" - // ^^^^^ - calculating total length of this thing - const indent = initial + indentAfterMarker; - - // Run subparser & write tokens - token = state.push('list_item_open', 'li', 1); - token.markup = String.fromCharCode(markerCharCode); - const itemLines = [nextLine, 0]; - token.map = itemLines; - if (isOrdered) { - token.info = state.src.slice(start, posAfterMarker - 1); + function typename(type2, value) { + if (type2 == "keyword" || type2 == "variable") { + cx.marked = "type"; + return cont(typename); + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex); + } } - - // change current state, then restore it after parser subcall - const oldTight = state.tight; - const oldTShift = state.tShift[nextLine]; - const oldSCount = state.sCount[nextLine]; - - // - example list - // ^ listIndent position will be here - // ^ blkIndent position will be here - // - const oldListIndent = state.listIndent; - state.listIndent = state.blkIndent; - state.blkIndent = indent; - state.tight = true; - state.tShift[nextLine] = contentStart - state.bMarks[nextLine]; - state.sCount[nextLine] = offset; - if (contentStart >= max && state.isEmpty(nextLine + 1)) { - // workaround for this case - // (list item is empty, list terminates before "foo"): - // ~~~~~~~~ - // - - // - // foo - // ~~~~~~~~ - state.line = Math.min(state.line + 2, endLine); - } else { - state.md.block.tokenize(state, nextLine, endLine, true); + function funarg(type2, value) { + if (value == "@") cont(expression, funarg); + if (type2 == "spread") return cont(funarg); + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(funarg); + } + if (isTS && type2 == "this") return cont(maybetype, maybeAssign); + return pass(pattern, maybetype, maybeAssign); } - - // If any of list item is tight, mark list as tight - if (!state.tight || prevEmptyEnd) { - tight = false; - } - // Item become loose if finish with empty line, - // but we should filter last element, because it means list finish - prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1); - state.blkIndent = state.listIndent; - state.listIndent = oldListIndent; - state.tShift[nextLine] = oldTShift; - state.sCount[nextLine] = oldSCount; - state.tight = oldTight; - token = state.push('list_item_close', 'li', -1); - token.markup = String.fromCharCode(markerCharCode); - nextLine = state.line; - itemLines[1] = nextLine; - if (nextLine >= endLine) { - break; + function classExpression(type2, value) { + if (type2 == "variable") return className(type2, value); + return classNameAfter(type2, value); } - - // - // Try to check if list is terminated or continued. - // - if (state.sCount[nextLine] < state.blkIndent) { - break; + function className(type2, value) { + if (type2 == "variable") { + register(value); + return cont(classNameAfter); + } } - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[nextLine] - state.blkIndent >= 4) { - break; + function classNameAfter(type2, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); + if (value == "extends" || value == "implements" || isTS && type2 == ",") { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type2 == "{") return cont(pushlex("}"), classBody, poplex); } - - // fail if terminating block found - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; + function classBody(type2, value) { + if (type2 == "async" || type2 == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { + cx.marked = "keyword"; + return cont(classBody); } + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(classfield, classBody); + } + if (type2 == "number" || type2 == "string") return cont(classfield, classBody); + if (type2 == "[") return cont(expression, maybetype, expect("]"), classfield, classBody); + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type2 == "(") return pass(functiondecl, classBody); + if (type2 == ";" || type2 == ",") return cont(classBody); + if (type2 == "}") return cont(); + if (value == "@") return cont(expression, classBody); } - if (terminate) { - break; + function classfield(type2, value) { + if (value == "!") return cont(classfield); + if (value == "?") return cont(classfield); + if (type2 == ":") return cont(typeexpr, maybeAssign); + if (value == "=") return cont(expressionNoComma); + var context = cx.state.lexical.prev, + isInterface = context && context.info == "interface"; + return pass(isInterface ? functiondecl : functiondef); } - - // fail if list has another type - if (isOrdered) { - posAfterMarker = skipOrderedListMarker(state, nextLine); - if (posAfterMarker < 0) { - break; + function afterExport(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(maybeFrom, expect(";")); } - start = state.bMarks[nextLine] + state.tShift[nextLine]; - } else { - posAfterMarker = skipBulletListMarker(state, nextLine); - if (posAfterMarker < 0) { - break; + if (value == "default") { + cx.marked = "keyword"; + return cont(expression, expect(";")); } + if (type2 == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); } - if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { - break; + function exportField(type2, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(expect("variable")); + } + if (type2 == "variable") return pass(expressionNoComma, exportField); } - } - - // Finalize list - if (isOrdered) { - token = state.push('ordered_list_close', 'ol', -1); - } else { - token = state.push('bullet_list_close', 'ul', -1); - } - token.markup = String.fromCharCode(markerCharCode); - listLines[1] = nextLine; - state.line = nextLine; - state.parentType = oldParentType; - - // mark paragraphs tight if needed - if (tight) { - markTightParagraphs(state, listTokIdx); - } - return true; - } - function reference(state, startLine, _endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - let nextLine = startLine + 1; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (state.src.charCodeAt(pos) !== 0x5B /* [ */) { - return false; - } - function getNextLine(nextLine) { - const endLine = state.lineMax; - if (nextLine >= endLine || state.isEmpty(nextLine)) { - // empty line or end of input - return null; + function afterImport(type2) { + if (type2 == "string") return cont(); + if (type2 == "(") return pass(expression); + if (type2 == ".") return pass(maybeoperatorComma); + return pass(importSpec, maybeMoreImports, maybeFrom); } - let isContinuation = false; - - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - isContinuation = true; + function importSpec(type2, value) { + if (type2 == "{") return contCommasep(importSpec, "}"); + if (type2 == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - isContinuation = true; - } - if (!isContinuation) { - const terminatorRules = state.md.block.ruler.getRules('reference'); - const oldParentType = state.parentType; - state.parentType = 'reference'; - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; - } + function maybeMoreImports(type2) { + if (type2 == ",") return cont(importSpec, maybeMoreImports); + } + function maybeAs(_type, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(importSpec); } - state.parentType = oldParentType; - if (terminate) { - // terminated by another block - return null; + } + function maybeFrom(_type, value) { + if (value == "from") { + cx.marked = "keyword"; + return cont(expression); } } - const pos = state.bMarks[nextLine] + state.tShift[nextLine]; - const max = state.eMarks[nextLine]; - - // max + 1 explicitly includes the newline - return state.src.slice(pos, max + 1); - } - let str = state.src.slice(pos, max + 1); - max = str.length; - let labelEnd = -1; - for (pos = 1; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x5B /* [ */) { - return false; - } else if (ch === 0x5D /* ] */) { - labelEnd = pos; - break; - } else if (ch === 0x0A /* \n */) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + function arrayLiteral(type2) { + if (type2 == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); + } + function enummember() { + return pass(pattern, maybeAssign); + } + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); + } + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); + } + return { + startState: function (basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; + return state; + }, + token: function (stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + indent: function (state, textAfter) { + if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), + lexical = state.lexical, + top; + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev;else if (c != maybeelse && c != popcontext) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; + var type2 = lexical.type, + closing = firstChar == type2; + if (type2 == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);else if (type2 == "form" && firstChar == "{") return lexical.indented;else if (type2 == "form") return lexical.indented + indentUnit;else if (type2 == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);else if (lexical.align) return lexical.column + (closing ? 0 : 1);else return lexical.indented + (closing ? 0 : indentUnit); + }, + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + helperType: jsonMode ? "json" : "javascript", + jsonldMode, + jsonMode, + expressionAllowed, + skipExpression: function (state) { + parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); } - } else if (ch === 0x5C /* \ */) { - pos++; - if (pos < max && str.charCodeAt(pos) === 0x0A) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + }; + }); + CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + CodeMirror.defineMIME("text/javascript", "javascript"); + CodeMirror.defineMIME("text/ecmascript", "javascript"); + CodeMirror.defineMIME("application/javascript", "javascript"); + CodeMirror.defineMIME("application/x-javascript", "javascript"); + CodeMirror.defineMIME("application/ecmascript", "javascript"); + CodeMirror.defineMIME("application/json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/x-json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/manifest+json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/ld+json", { + name: "javascript", + jsonld: true + }); + CodeMirror.defineMIME("text/typescript", { + name: "javascript", + typescript: true + }); + CodeMirror.defineMIME("application/typescript", { + name: "javascript", + typescript: true + }); + }); +})(); +var javascriptExports = javascript$2.exports; +const javascript = /* @__PURE__ */codemirror.getDefaultExportFromCjs(javascriptExports); +const javascript$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: javascript +}, [javascriptExports]); +exports.javascript = javascript$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/jump-to-line.cjs.js": +/*!*****************************************************!*\ + !*** ../../graphiql-react/dist/jump-to-line.cjs.js ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } } } } - if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A /* : */) { - return false; - } - - // [label]: destination 'title' - // ^^^ skip optional whitespace here - for (pos = labelEnd + 2; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x0A) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var jumpToLine$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), dialog.dialogExports); + })(function (CodeMirror) { + CodeMirror.defineOption("search", { + bottom: false + }); + function dialog2(cm, text, shortText, deflt, f) { + if (cm.openDialog) cm.openDialog(text, f, { + value: deflt, + selectValueOnOpen: true, + bottom: cm.options.search.bottom + });else f(prompt(shortText, deflt)); + } + function getJumpDialog(cm) { + return cm.phrase("Jump to line:") + ' ' + cm.phrase("(Use line:column or scroll% syntax)") + ""; + } + function interpretLine(cm, string) { + var num = Number(string); + if (/^[-+]/.test(string)) return cm.getCursor().line + num;else return num - 1; + } + CodeMirror.commands.jumpToLine = function (cm) { + var cur = cm.getCursor(); + dialog2(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), cur.line + 1 + ":" + cur.ch, function (posStr) { + if (!posStr) return; + var match; + if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) { + cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); + } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) { + var line = Math.round(cm.lineCount() * Number(match[1]) / 100); + if (/^[-+]/.test(match[1])) line = cur.line + line + 1; + cm.setCursor(line - 1, cur.ch); + } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) { + cm.setCursor(interpretLine(cm, match[1]), cur.ch); } - } else if (isSpace(ch)) ;else { - break; - } + }); + }; + CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; + }); +})(); +var jumpToLineExports = jumpToLine$2.exports; +const jumpToLine = /* @__PURE__ */codemirror.getDefaultExportFromCjs(jumpToLineExports); +const jumpToLine$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: jumpToLine +}, [jumpToLineExports]); +exports.jumpToLine = jumpToLine$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/jump.cjs.js": +/*!*********************************************!*\ + !*** ../../graphiql-react/dist/jump.cjs.js ***! + \*********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); +codemirror.CodeMirror.defineOption("jump", false, (cm, options, old) => { + if (old && old !== codemirror.CodeMirror.Init) { + const oldOnMouseOver = cm.state.jump.onMouseOver; + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); + const oldOnMouseOut = cm.state.jump.onMouseOut; + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", oldOnMouseOut); + codemirror.CodeMirror.off(document, "keydown", cm.state.jump.onKeyDown); + delete cm.state.jump; + } + if (options) { + const state = cm.state.jump = { + options, + onMouseOver: onMouseOver.bind(null, cm), + onMouseOut: onMouseOut.bind(null, cm), + onKeyDown: onKeyDown.bind(null, cm) + }; + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", state.onMouseOut); + codemirror.CodeMirror.on(document, "keydown", state.onKeyDown); + } +}); +function onMouseOver(cm, event) { + const target = event.target || event.srcElement; + if (!(target instanceof HTMLElement)) { + return; + } + if ((target === null || target === void 0 ? void 0 : target.nodeName) !== "SPAN") { + return; + } + const box = target.getBoundingClientRect(); + const cursor = { + left: (box.left + box.right) / 2, + top: (box.top + box.bottom) / 2 + }; + cm.state.jump.cursor = cursor; + if (cm.state.jump.isHoldingModifier) { + enableJumpMode(cm); + } +} +function onMouseOut(cm) { + if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) { + cm.state.jump.cursor = null; + return; + } + if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) { + disableJumpMode(cm); + } +} +function onKeyDown(cm, event) { + if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) { + return; + } + cm.state.jump.isHoldingModifier = true; + if (cm.state.jump.cursor) { + enableJumpMode(cm); + } + const onKeyUp = upEvent => { + if (upEvent.code !== event.code) { + return; } - - // [label]: destination 'title' - // ^^^^^^^^^^^ parse this - const destRes = state.md.helpers.parseLinkDestination(str, pos, max); - if (!destRes.ok) { - return false; + cm.state.jump.isHoldingModifier = false; + if (cm.state.jump.marker) { + disableJumpMode(cm); } - const href = state.md.normalizeLink(destRes.str); - if (!state.md.validateLink(href)) { - return false; + codemirror.CodeMirror.off(document, "keyup", onKeyUp); + codemirror.CodeMirror.off(document, "click", onClick); + cm.off("mousedown", onMouseDown); + }; + const onClick = clickEvent => { + const { + destination, + options + } = cm.state.jump; + if (destination) { + options.onClick(destination, clickEvent); } - pos = destRes.pos; - - // save cursor state, we could require to rollback later - const destEndPos = pos; - const destEndLineNo = nextLine; - - // [label]: destination 'title' - // ^^^ skipping those spaces - const start = pos; - for (; pos < max; pos++) { - const ch = str.charCodeAt(pos); - if (ch === 0x0A) { - const lineContent = getNextLine(nextLine); - if (lineContent !== null) { - str += lineContent; - max = str.length; - nextLine++; + }; + const onMouseDown = (_, downEvent) => { + if (cm.state.jump.destination) { + downEvent.codemirrorIgnore = true; + } + }; + codemirror.CodeMirror.on(document, "keyup", onKeyUp); + codemirror.CodeMirror.on(document, "click", onClick); + cm.on("mousedown", onMouseDown); +} +const isMac = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.appVersion.includes("Mac")); +function isJumpModifier(key) { + return key === (isMac ? "Meta" : "Control"); +} +function enableJumpMode(cm) { + if (cm.state.jump.marker) { + return; + } + const { + cursor, + options + } = cm.state.jump; + const pos = cm.coordsChar(cursor); + const token = cm.getTokenAt(pos, true); + const getDestination = options.getDestination || cm.getHelper(pos, "jump"); + if (getDestination) { + const destination = getDestination(token, options, cm); + if (destination) { + const marker = cm.markText({ + line: pos.line, + ch: token.start + }, { + line: pos.line, + ch: token.end + }, { + className: "CodeMirror-jump-token" + }); + cm.state.jump.marker = marker; + cm.state.jump.destination = destination; + } + } +} +function disableJumpMode(cm) { + const { + marker + } = cm.state.jump; + cm.state.jump.marker = null; + cm.state.jump.destination = null; + marker.clear(); +} +codemirror.CodeMirror.registerHelper("jump", "graphql", (token, options) => { + if (!options.schema || !options.onClick || !token.state) { + return; + } + const { + state + } = token; + const { + kind, + step + } = state; + const typeInfo = SchemaReference.getTypeInfo(options.schema, state); + if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef) { + return SchemaReference.getFieldReference(typeInfo); + } + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + return SchemaReference.getDirectiveReference(typeInfo); + } + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + return SchemaReference.getArgumentReference(typeInfo); + } + if (kind === "EnumValue" && typeInfo.enumValue) { + return SchemaReference.getEnumValueReference(typeInfo); + } + if (kind === "NamedType" && typeInfo.type) { + return SchemaReference.getTypeReference(typeInfo); + } +}); + +/***/ }), + +/***/ "../../graphiql-react/dist/lint.cjs.js": +/*!*********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs.js ***! + \*********************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } - } else if (isSpace(ch)) ;else { - break; - } - } - - // [label]: destination 'title' - // ^^^^^^^ parse this - let titleRes = state.md.helpers.parseLinkTitle(str, pos, max); - while (titleRes.can_continue) { - const lineContent = getNextLine(nextLine); - if (lineContent === null) break; - str += lineContent; - pos = max; - max = str.length; - nextLine++; - titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes); - } - let title; - if (pos < max && start !== pos && titleRes.ok) { - title = titleRes.str; - pos = titleRes.pos; - } else { - title = ''; - pos = destEndPos; - nextLine = destEndLineNo; - } - - // skip trailing spaces until the rest of the line - while (pos < max) { - const ch = str.charCodeAt(pos); - if (!isSpace(ch)) { - break; } - pos++; } - if (pos < max && str.charCodeAt(pos) !== 0x0A) { - if (title) { - // garbage at the end of the line after title, - // but it could still be a valid reference if we roll back - title = ''; - pos = destEndPos; - nextLine = destEndLineNo; - while (pos < max) { - const ch = str.charCodeAt(pos); - if (!isSpace(ch)) { + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var lint$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var GUTTER_ID = "CodeMirror-lint-markers"; + var LINT_LINE_ID = "CodeMirror-lint-line-"; + function showTooltip(cm, e, content) { + var tt = document.createElement("div"); + tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; + tt.appendChild(content.cloneNode(true)); + if (cm.state.lint.options.selfContain) cm.getWrapperElement().appendChild(tt);else document.body.appendChild(tt); + function position(e2) { + if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); + tt.style.top = Math.max(0, e2.clientY - tt.offsetHeight - 5) + "px"; + tt.style.left = e2.clientX + 5 + "px"; + } + CodeMirror.on(document, "mousemove", position); + position(e); + if (tt.style.opacity != null) tt.style.opacity = 1; + return tt; + } + function rm(elt) { + if (elt.parentNode) elt.parentNode.removeChild(elt); + } + function hideTooltip(tt) { + if (!tt.parentNode) return; + if (tt.style.opacity == null) rm(tt); + tt.style.opacity = 0; + setTimeout(function () { + rm(tt); + }, 600); + } + function showTooltipFor(cm, e, content, node) { + var tooltip = showTooltip(cm, e, content); + function hide() { + CodeMirror.off(node, "mouseout", hide); + if (tooltip) { + hideTooltip(tooltip); + tooltip = null; + } + } + var poll = setInterval(function () { + if (tooltip) for (var n = node;; n = n.parentNode) { + if (n && n.nodeType == 11) n = n.host; + if (n == document.body) return; + if (!n) { + hide(); break; } - pos++; } - } - } - if (pos < max && str.charCodeAt(pos) !== 0x0A) { - // garbage at the end of the line - return false; - } - const label = normalizeReference(str.slice(1, labelEnd)); - if (!label) { - // CommonMark 0.20 disallows empty labels - return false; - } - - // Reference can not terminate anything. This check is for safety only. - /* istanbul ignore if */ - if (silent) { - return true; - } - if (typeof state.env.references === 'undefined') { - state.env.references = {}; + if (!tooltip) return clearInterval(poll); + }, 400); + CodeMirror.on(node, "mouseout", hide); } - if (typeof state.env.references[label] === 'undefined') { - state.env.references[label] = { - title, - href + function LintState(cm, conf, hasGutter) { + this.marked = []; + if (conf instanceof Function) conf = { + getAnnotations: conf }; + if (!conf || conf === true) conf = {}; + this.options = {}; + this.linterOptions = conf.options || {}; + for (var prop in defaults) this.options[prop] = defaults[prop]; + for (var prop in conf) { + if (defaults.hasOwnProperty(prop)) { + if (conf[prop] != null) this.options[prop] = conf[prop]; + } else if (!conf.options) { + this.linterOptions[prop] = conf[prop]; + } + } + this.timeout = null; + this.hasGutter = hasGutter; + this.onMouseOver = function (e) { + onMouseOver(cm, e); + }; + this.waitingFor = 0; + } + var defaults = { + highlightLines: false, + tooltips: true, + delay: 500, + lintOnChange: true, + getAnnotations: null, + async: false, + selfContain: null, + formatAnnotation: null, + onUpdateLinting: null + }; + function clearMarks(cm) { + var state = cm.state.lint; + if (state.hasGutter) cm.clearGutter(GUTTER_ID); + if (state.options.highlightLines) clearErrorLines(cm); + for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); + state.marked.length = 0; + } + function clearErrorLines(cm) { + cm.eachLine(function (line) { + var has = line.wrapClass && /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); + if (has) cm.removeLineClass(line, "wrap", has[0]); + }); } - state.line = nextLine; - return true; - } - - // List of valid html blocks names, according to commonmark spec - // https://spec.commonmark.org/0.30/#html-blocks - - var block_names = ['address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu', 'menuitem', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'search', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul']; - - // Regexps to match html elements - - const attr_name = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; - const unquoted = '[^"\'=<>`\\x00-\\x20]+'; - const single_quoted = "'[^']*'"; - const double_quoted = '"[^"]*"'; - const attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')'; - const attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)'; - const open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; - const close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; - const comment = ''; - const processing = '<[?][\\s\\S]*?[?]>'; - const declaration = ']*>'; - const cdata = ''; - const HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment + '|' + processing + '|' + declaration + '|' + cdata + ')'); - const HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')'); - - // HTML block - - // An array of opening and corresponding closing sequences for html tags, - // last argument defines whether it can terminate a paragraph or not - // - const HTML_SEQUENCES = [[/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true], [/^/, true], [/^<\?/, /\?>/, true], [/^/, true], [/^/, true], [new RegExp('^|$))', 'i'), /^$/, true], [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false]]; - function html_block(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - if (!state.md.options.html) { - return false; - } - if (state.src.charCodeAt(pos) !== 0x3C /* < */) { - return false; - } - let lineText = state.src.slice(pos, max); - let i = 0; - for (; i < HTML_SEQUENCES.length; i++) { - if (HTML_SEQUENCES[i][0].test(lineText)) { - break; + function makeMarker(cm, labels, severity, multiple, tooltips) { + var marker = document.createElement("div"), + inner = marker; + marker.className = "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; + if (multiple) { + inner = marker.appendChild(document.createElement("div")); + inner.className = "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; + } + if (tooltips != false) CodeMirror.on(inner, "mouseover", function (e) { + showTooltipFor(cm, e, labels, inner); + }); + return marker; + } + function getMaxSeverity(a, b) { + if (a == "error") return a;else return b; + } + function groupByLine(annotations) { + var lines = []; + for (var i = 0; i < annotations.length; ++i) { + var ann = annotations[i], + line = ann.from.line; + (lines[line] || (lines[line] = [])).push(ann); + } + return lines; + } + function annotationTooltip(ann) { + var severity = ann.severity; + if (!severity) severity = "error"; + var tip = document.createElement("div"); + tip.className = "CodeMirror-lint-message CodeMirror-lint-message-" + severity; + if (typeof ann.messageHTML != "undefined") { + tip.innerHTML = ann.messageHTML; + } else { + tip.appendChild(document.createTextNode(ann.message)); + } + return tip; + } + function lintAsync(cm, getAnnotations) { + var state = cm.state.lint; + var id = ++state.waitingFor; + function abort() { + id = -1; + cm.off("change", abort); + } + cm.on("change", abort); + getAnnotations(cm.getValue(), function (annotations, arg2) { + cm.off("change", abort); + if (state.waitingFor != id) return; + if (arg2 && annotations instanceof CodeMirror) annotations = arg2; + cm.operation(function () { + updateLinting(cm, annotations); + }); + }, state.linterOptions, cm); + } + function startLinting(cm) { + var state = cm.state.lint; + if (!state) return; + var options = state.options; + var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint"); + if (!getAnnotations) return; + if (options.async || getAnnotations.async) { + lintAsync(cm, getAnnotations); + } else { + var annotations = getAnnotations(cm.getValue(), state.linterOptions, cm); + if (!annotations) return; + if (annotations.then) annotations.then(function (issues) { + cm.operation(function () { + updateLinting(cm, issues); + }); + });else cm.operation(function () { + updateLinting(cm, annotations); + }); } } - if (i === HTML_SEQUENCES.length) { - return false; - } - if (silent) { - // true if this sequence can be a terminator, false otherwise - return HTML_SEQUENCES[i][2]; - } - let nextLine = startLine + 1; - - // If we are here - we detected HTML block. - // Let's roll down till block end. - if (!HTML_SEQUENCES[i][1].test(lineText)) { - for (; nextLine < endLine; nextLine++) { - if (state.sCount[nextLine] < state.blkIndent) { - break; - } - pos = state.bMarks[nextLine] + state.tShift[nextLine]; - max = state.eMarks[nextLine]; - lineText = state.src.slice(pos, max); - if (HTML_SEQUENCES[i][1].test(lineText)) { - if (lineText.length !== 0) { - nextLine++; - } - break; + function updateLinting(cm, annotationsNotSorted) { + var state = cm.state.lint; + if (!state) return; + var options = state.options; + clearMarks(cm); + var annotations = groupByLine(annotationsNotSorted); + for (var line = 0; line < annotations.length; ++line) { + var anns = annotations[line]; + if (!anns) continue; + var message = []; + anns = anns.filter(function (item) { + return message.indexOf(item.message) > -1 ? false : message.push(item.message); + }); + var maxSeverity = null; + var tipLabel = state.hasGutter && document.createDocumentFragment(); + for (var i = 0; i < anns.length; ++i) { + var ann = anns[i]; + var severity = ann.severity; + if (!severity) severity = "error"; + maxSeverity = getMaxSeverity(maxSeverity, severity); + if (options.formatAnnotation) ann = options.formatAnnotation(ann); + if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); + if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { + className: "CodeMirror-lint-mark CodeMirror-lint-mark-" + severity, + __annotation: ann + })); } + if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(cm, tipLabel, maxSeverity, annotations[line].length > 1, options.tooltips)); + if (options.highlightLines) cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); + } + if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm); + } + function onChange(cm) { + var state = cm.state.lint; + if (!state) return; + clearTimeout(state.timeout); + state.timeout = setTimeout(function () { + startLinting(cm); + }, state.options.delay); + } + function popupTooltips(cm, annotations, e) { + var target = e.target || e.srcElement; + var tooltip = document.createDocumentFragment(); + for (var i = 0; i < annotations.length; i++) { + var ann = annotations[i]; + tooltip.appendChild(annotationTooltip(ann)); + } + showTooltipFor(cm, e, tooltip, target); + } + function onMouseOver(cm, e) { + var target = e.target || e.srcElement; + if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; + var box = target.getBoundingClientRect(), + x = (box.left + box.right) / 2, + y = (box.top + box.bottom) / 2; + var spans = cm.findMarksAt(cm.coordsChar({ + left: x, + top: y + }, "client")); + var annotations = []; + for (var i = 0; i < spans.length; ++i) { + var ann = spans[i].__annotation; + if (ann) annotations.push(ann); } + if (annotations.length) popupTooltips(cm, annotations, e); } - state.line = nextLine; - const token = state.push('html_block', '', 0); - token.map = [startLine, nextLine]; - token.content = state.getLines(startLine, nextLine, state.blkIndent, true); - return true; + CodeMirror.defineOption("lint", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + clearMarks(cm); + if (cm.state.lint.options.lintOnChange !== false) cm.off("change", onChange); + CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver); + clearTimeout(cm.state.lint.timeout); + delete cm.state.lint; + } + if (val) { + var gutters = cm.getOption("gutters"), + hasLintGutter = false; + for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; + var state = cm.state.lint = new LintState(cm, val, hasLintGutter); + if (state.options.lintOnChange) cm.on("change", onChange); + if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); + startLinting(cm); + } + }); + CodeMirror.defineExtension("performLint", function () { + startLinting(this); + }); + }); +})(); +var lintExports = lint$2.exports; +const lint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(lintExports); +const lint$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: lint +}, [lintExports]); +exports.lint = lint$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/lint.cjs2.js": +/*!**********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs2.js ***! + \**********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); +const SEVERITY = ["error", "warning", "information", "hint"]; +const TYPE = { + "GraphQL: Validation": "validation", + "GraphQL: Deprecation": "deprecation", + "GraphQL: Syntax": "syntax" +}; +codemirror.CodeMirror.registerHelper("lint", "graphql", (text, options) => { + const { + schema, + validationRules, + externalFragments + } = options; + const rawResults = graphqlLanguageService.getDiagnostics(text, schema, validationRules, void 0, externalFragments); + const results = rawResults.map(error => ({ + message: error.message, + severity: error.severity ? SEVERITY[error.severity - 1] : SEVERITY[0], + type: error.source ? TYPE[error.source] : void 0, + from: codemirror.CodeMirror.Pos(error.range.start.line, error.range.start.character), + to: codemirror.CodeMirror.Pos(error.range.end.line, error.range.end.character) + })); + return results; +}); + +/***/ }), + +/***/ "../../graphiql-react/dist/lint.cjs3.js": +/*!**********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs3.js ***! + \**********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function jsonParse(str) { + string = str; + strLen = str.length; + start = end = lastEnd = -1; + ch(); + lex(); + const ast = parseObj(); + expect("EOF"); + return ast; +} +let string; +let strLen; +let start; +let end; +let lastEnd; +let code; +let kind; +function parseObj() { + const nodeStart = start; + const members = []; + expect("{"); + if (!skip("}")) { + do { + members.push(parseMember()); + } while (skip(",")); + expect("}"); + } + return { + kind: "Object", + start: nodeStart, + end: lastEnd, + members + }; +} +function parseMember() { + const nodeStart = start; + const key = kind === "String" ? curToken() : null; + expect("String"); + expect(":"); + const value = parseVal(); + return { + kind: "Member", + start: nodeStart, + end: lastEnd, + key, + value + }; +} +function parseArr() { + const nodeStart = start; + const values = []; + expect("["); + if (!skip("]")) { + do { + values.push(parseVal()); + } while (skip(",")); + expect("]"); + } + return { + kind: "Array", + start: nodeStart, + end: lastEnd, + values + }; +} +function parseVal() { + switch (kind) { + case "[": + return parseArr(); + case "{": + return parseObj(); + case "String": + case "Number": + case "Boolean": + case "Null": + const token = curToken(); + lex(); + return token; } - - // heading (#, ##, ...) - - function heading(state, startLine, endLine, silent) { - let pos = state.bMarks[startLine] + state.tShift[startLine]; - let max = state.eMarks[startLine]; - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - let ch = state.src.charCodeAt(pos); - if (ch !== 0x23 /* # */ || pos >= max) { - return false; - } - - // count heading level - let level = 1; - ch = state.src.charCodeAt(++pos); - while (ch === 0x23 /* # */ && pos < max && level <= 6) { - level++; - ch = state.src.charCodeAt(++pos); - } - if (level > 6 || pos < max && !isSpace(ch)) { - return false; - } - if (silent) { - return true; - } - - // Let's cut tails like ' ### ' from the end of string - - max = state.skipSpacesBack(max, pos); - const tmp = state.skipCharsBack(max, 0x23, pos); // # - if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { - max = tmp; - } - state.line = startLine + 1; - const token_o = state.push('heading_open', 'h' + String(level), 1); - token_o.markup = '########'.slice(0, level); - token_o.map = [startLine, state.line]; - const token_i = state.push('inline', '', 0); - token_i.content = state.src.slice(pos, max).trim(); - token_i.map = [startLine, state.line]; - token_i.children = []; - const token_c = state.push('heading_close', 'h' + String(level), -1); - token_c.markup = '########'.slice(0, level); + expect("Value"); +} +function curToken() { + return { + kind, + start, + end, + value: JSON.parse(string.slice(start, end)) + }; +} +function expect(str) { + if (kind === str) { + lex(); + return; + } + let found; + if (kind === "EOF") { + found = "[end of file]"; + } else if (end - start > 1) { + found = "`" + string.slice(start, end) + "`"; + } else { + const match = string.slice(start).match(/^.+?\b/); + found = "`" + (match ? match[0] : string[start]) + "`"; + } + throw syntaxError(`Expected ${str} but found ${found}.`); +} +class JSONSyntaxError extends Error { + constructor(message, position) { + super(message); + this.position = position; + } +} +function syntaxError(message) { + return new JSONSyntaxError(message, { + start, + end + }); +} +function skip(k) { + if (kind === k) { + lex(); return true; } - - // lheading (---, ===) - - function lheading(state, startLine, endLine /*, silent */) { - const terminatorRules = state.md.block.ruler.getRules('paragraph'); - - // if it's indented more than 3 spaces, it should be a code block - if (state.sCount[startLine] - state.blkIndent >= 4) { - return false; - } - const oldParentType = state.parentType; - state.parentType = 'paragraph'; // use paragraph to match terminatorRules - - // jump line-by-line until empty one or EOF - let level = 0; - let marker; - let nextLine = startLine + 1; - for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - continue; +} +function ch() { + if (end < strLen) { + end++; + code = end === strLen ? 0 : string.charCodeAt(end); + } + return code; +} +function lex() { + lastEnd = end; + while (code === 9 || code === 10 || code === 13 || code === 32) { + ch(); + } + if (code === 0) { + kind = "EOF"; + return; + } + start = end; + switch (code) { + case 34: + kind = "String"; + return readString(); + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + kind = "Number"; + return readNumber(); + case 102: + if (string.slice(start, start + 5) !== "false") { + break; } - - // - // Check for underline in setext header - // - if (state.sCount[nextLine] >= state.blkIndent) { - let pos = state.bMarks[nextLine] + state.tShift[nextLine]; - const max = state.eMarks[nextLine]; - if (pos < max) { - marker = state.src.charCodeAt(pos); - if (marker === 0x2D /* - */ || marker === 0x3D /* = */) { - pos = state.skipChars(pos, marker); - pos = state.skipSpaces(pos); - if (pos >= max) { - level = marker === 0x3D /* = */ ? 1 : 2; - break; - } - } - } + end += 4; + ch(); + kind = "Boolean"; + return; + case 110: + if (string.slice(start, start + 4) !== "null") { + break; } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - continue; + end += 3; + ch(); + kind = "Null"; + return; + case 116: + if (string.slice(start, start + 4) !== "true") { + break; } - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; + end += 3; + ch(); + kind = "Boolean"; + return; + } + kind = string[start]; + ch(); +} +function readString() { + ch(); + while (code !== 34 && code > 31) { + if (code === 92) { + code = ch(); + switch (code) { + case 34: + case 47: + case 92: + case 98: + case 102: + case 110: + case 114: + case 116: + ch(); break; - } - } - if (terminate) { - break; + case 117: + ch(); + readHex(); + readHex(); + readHex(); + readHex(); + break; + default: + throw syntaxError("Bad character escape sequence."); } + } else if (end === strLen) { + throw syntaxError("Unterminated string."); + } else { + ch(); } - if (!level) { - // Didn't find valid underline - return false; + } + if (code === 34) { + ch(); + return; + } + throw syntaxError("Unterminated string."); +} +function readHex() { + if (code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102) { + return ch(); + } + throw syntaxError("Expected hexadecimal digit."); +} +function readNumber() { + if (code === 45) { + ch(); + } + if (code === 48) { + ch(); + } else { + readDigits(); + } + if (code === 46) { + ch(); + readDigits(); + } + if (code === 69 || code === 101) { + code = ch(); + if (code === 43 || code === 45) { + ch(); } - const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); - state.line = nextLine + 1; - const token_o = state.push('heading_open', 'h' + String(level), 1); - token_o.markup = String.fromCharCode(marker); - token_o.map = [startLine, state.line]; - const token_i = state.push('inline', '', 0); - token_i.content = content; - token_i.map = [startLine, state.line - 1]; - token_i.children = []; - const token_c = state.push('heading_close', 'h' + String(level), -1); - token_c.markup = String.fromCharCode(marker); - state.parentType = oldParentType; - return true; + readDigits(); } - - // Paragraph - - function paragraph(state, startLine, endLine) { - const terminatorRules = state.md.block.ruler.getRules('paragraph'); - const oldParentType = state.parentType; - let nextLine = startLine + 1; - state.parentType = 'paragraph'; - - // jump line-by-line until empty one or EOF - for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { - // this would be a code block normally, but after paragraph - // it's considered a lazy continuation regardless of what's there - if (state.sCount[nextLine] - state.blkIndent > 3) { - continue; - } - - // quirk for blockquotes, this line should already be checked by that rule - if (state.sCount[nextLine] < 0) { - continue; - } - - // Some tags can terminate paragraph without empty line. - let terminate = false; - for (let i = 0, l = terminatorRules.length; i < l; i++) { - if (terminatorRules[i](state, nextLine, endLine, true)) { - terminate = true; - break; +} +function readDigits() { + if (code < 48 || code > 57) { + throw syntaxError("Expected decimal digit."); + } + do { + ch(); + } while (code >= 48 && code <= 57); +} +codemirror.CodeMirror.registerHelper("lint", "graphql-variables", (text, options, editor) => { + if (!text) { + return []; + } + let ast; + try { + ast = jsonParse(text); + } catch (error) { + if (error instanceof JSONSyntaxError) { + return [lintError(editor, error.position, error.message)]; + } + throw error; + } + const { + variableToType + } = options; + if (!variableToType) { + return []; + } + return validateVariables(editor, variableToType, ast); +}); +function validateVariables(editor, variableToType, variablesAST) { + var _a; + const errors = []; + for (const member of variablesAST.members) { + if (member) { + const variableName = (_a = member.key) === null || _a === void 0 ? void 0 : _a.value; + const type = variableToType[variableName]; + if (type) { + for (const [node, message] of validateValue(type, member.value)) { + errors.push(lintError(editor, node, message)); } + } else { + errors.push(lintError(editor, member.key, `Variable "$${variableName}" does not appear in any GraphQL query.`)); } - if (terminate) { - break; + } + } + return errors; +} +function validateValue(type, valueAST) { + if (!type || !valueAST) { + return []; + } + if (type instanceof graphql.GraphQLNonNull) { + if (valueAST.kind === "Null") { + return [[valueAST, `Type "${type}" is non-nullable and cannot be null.`]]; + } + return validateValue(type.ofType, valueAST); + } + if (valueAST.kind === "Null") { + return []; + } + if (type instanceof graphql.GraphQLList) { + const itemType = type.ofType; + if (valueAST.kind === "Array") { + const values = valueAST.values || []; + return mapCat(values, item => validateValue(itemType, item)); + } + return validateValue(itemType, valueAST); + } + if (type instanceof graphql.GraphQLInputObjectType) { + if (valueAST.kind !== "Object") { + return [[valueAST, `Type "${type}" must be an Object.`]]; + } + const providedFields = /* @__PURE__ */Object.create(null); + const fieldErrors = mapCat(valueAST.members, member => { + var _a; + const fieldName = (_a = member === null || member === void 0 ? void 0 : member.key) === null || _a === void 0 ? void 0 : _a.value; + providedFields[fieldName] = true; + const inputField = type.getFields()[fieldName]; + if (!inputField) { + return [[member.key, `Type "${type}" does not have a field "${fieldName}".`]]; + } + const fieldType = inputField ? inputField.type : void 0; + return validateValue(fieldType, member.value); + }); + for (const fieldName of Object.keys(type.getFields())) { + const field = type.getFields()[fieldName]; + if (!providedFields[fieldName] && field.type instanceof graphql.GraphQLNonNull && !field.defaultValue) { + fieldErrors.push([valueAST, `Object of type "${type}" is missing required field "${fieldName}".`]); } } - const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); - state.line = nextLine; - const token_o = state.push('paragraph_open', 'p', 1); - token_o.map = [startLine, state.line]; - const token_i = state.push('inline', '', 0); - token_i.content = content; - token_i.map = [startLine, state.line]; - token_i.children = []; - state.push('paragraph_close', 'p', -1); - state.parentType = oldParentType; - return true; + return fieldErrors; } - - /** internal - * class ParserBlock - * - * Block-level tokenizer. - **/ - - const _rules$1 = [ - // First 2 params - rule name & source. Secondary array - list of rules, - // which can be terminated by this one. - ['table', table, ['paragraph', 'reference']], ['code', code], ['fence', fence, ['paragraph', 'reference', 'blockquote', 'list']], ['blockquote', blockquote, ['paragraph', 'reference', 'blockquote', 'list']], ['hr', hr, ['paragraph', 'reference', 'blockquote', 'list']], ['list', list, ['paragraph', 'reference', 'blockquote']], ['reference', reference], ['html_block', html_block, ['paragraph', 'reference', 'blockquote']], ['heading', heading, ['paragraph', 'reference', 'blockquote']], ['lheading', lheading], ['paragraph', paragraph]]; - - /** - * new ParserBlock() - **/ - function ParserBlock() { - /** - * ParserBlock#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of block rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules$1.length; i++) { - this.ruler.push(_rules$1[i][0], _rules$1[i][1], { - alt: (_rules$1[i][2] || []).slice() - }); + if (type.name === "Boolean" && valueAST.kind !== "Boolean" || type.name === "String" && valueAST.kind !== "String" || type.name === "ID" && valueAST.kind !== "Number" && valueAST.kind !== "String" || type.name === "Float" && valueAST.kind !== "Number" || type.name === "Int" && (valueAST.kind !== "Number" || (valueAST.value | 0) !== valueAST.value)) { + return [[valueAST, `Expected value of type "${type}".`]]; + } + if ((type instanceof graphql.GraphQLEnumType || type instanceof graphql.GraphQLScalarType) && (valueAST.kind !== "String" && valueAST.kind !== "Number" && valueAST.kind !== "Boolean" && valueAST.kind !== "Null" || isNullish(type.parseValue(valueAST.value)))) { + return [[valueAST, `Expected value of type "${type}".`]]; + } + return []; +} +function lintError(editor, node, message) { + return { + message, + severity: "error", + type: "validation", + from: editor.posFromIndex(node.start), + to: editor.posFromIndex(node.end) + }; +} +function isNullish(value) { + return value === null || value === void 0 || value !== value; +} +function mapCat(array, mapper) { + return Array.prototype.concat.apply([], array.map(mapper)); +} + +/***/ }), + +/***/ "../../graphiql-react/dist/matchbrackets.cjs.js": +/*!******************************************************!*\ + !*** ../../graphiql-react/dist/matchbrackets.cjs.js ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +const matchbrackets$2 = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } } } - - // Generate tokens for input range - // - ParserBlock.prototype.tokenize = function (state, startLine, endLine) { - const rules = this.ruler.getRules(''); - const len = rules.length; - const maxNesting = state.md.options.maxNesting; - let line = startLine; - let hasEmptyLines = false; - while (line < endLine) { - state.line = line = state.skipEmptyLines(line); - if (line >= endLine) { - break; - } - - // Termination condition for nested calls. - // Nested calls currently used for blockquotes & lists - if (state.sCount[line] < state.blkIndent) { - break; - } - - // If nesting level exceeded - skip tail to the end. That's not ordinary - // situation and we should not care about content. - if (state.level >= maxNesting) { - state.line = endLine; - break; + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var matchbracketsExports = matchbrackets$2.requireMatchbrackets(); +const matchbrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(matchbracketsExports); +const matchbrackets$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: matchbrackets +}, [matchbracketsExports]); +exports.matchbrackets = matchbrackets$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/matchbrackets.cjs2.js": +/*!*******************************************************!*\ + !*** ../../graphiql-react/dist/matchbrackets.cjs2.js ***! + \*******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +var matchbrackets = { + exports: {} +}; +var hasRequiredMatchbrackets; +function requireMatchbrackets() { + if (hasRequiredMatchbrackets) return matchbrackets.exports; + hasRequiredMatchbrackets = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); + var Pos = CodeMirror.Pos; + var matching = { + "(": ")>", + ")": "(<", + "[": "]>", + "]": "[<", + "{": "}>", + "}": "{<", + "<": ">>", + ">": "<<" + }; + function bracketRegex(config) { + return config && config.bracketRegex || /[(){}[\]]/; + } + function findMatchingBracket(cm, where, config) { + var line = cm.getLineHandle(where.line), + pos = where.ch - 1; + var afterCursor = config && config.afterCursor; + if (afterCursor == null) afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className); + var re = bracketRegex(config); + var match = !afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)] || re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; + if (!match) return null; + var dir = match.charAt(1) == ">" ? 1 : -1; + if (config && config.strict && dir > 0 != (pos == where.ch)) return null; + var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); + var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config); + if (found == null) return null; + return { + from: Pos(where.line, pos), + to: found && found.pos, + match: found && found.ch == match.charAt(0), + forward: dir > 0 + }; } - - // Try all possible rules. - // On success, rule should: - // - // - update `state.line` - // - update `state.tokens` - // - return true - const prevLine = state.line; - let ok = false; - for (let i = 0; i < len; i++) { - ok = rules[i](state, line, endLine, false); - if (ok) { - if (prevLine >= state.line) { - throw new Error("block rule didn't increment state.line"); + function scanForBracket(cm, where, dir, style, config) { + var maxScanLen = config && config.maxScanLineLength || 1e4; + var maxScanLines = config && config.maxScanLines || 1e3; + var stack = []; + var re = bracketRegex(config); + var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) : Math.max(cm.firstLine() - 1, where.line - maxScanLines); + for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { + var line = cm.getLine(lineNo); + if (!line) continue; + var pos = dir > 0 ? 0 : line.length - 1, + end = dir > 0 ? line.length : -1; + if (line.length > maxScanLen) continue; + if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); + for (; pos != end; pos += dir) { + var ch = line.charAt(pos); + if (re.test(ch) && (style === void 0 || (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) { + var match = matching[ch]; + if (match && match.charAt(1) == ">" == dir > 0) stack.push(ch);else if (!stack.length) return { + pos: Pos(lineNo, pos), + ch + };else stack.pop(); + } + } + } + return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; + } + function matchBrackets(cm, autoclear, config) { + var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1e3, + highlightNonMatching = config && config.highlightNonMatching; + var marks = [], + ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); + if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) { + var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), { + className: style + })); + if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), { + className: style + })); } - break; + } + if (marks.length) { + if (ie_lt8 && cm.state.focused) cm.focus(); + var clear = function () { + cm.operation(function () { + for (var i2 = 0; i2 < marks.length; i2++) marks[i2].clear(); + }); + }; + if (autoclear) setTimeout(clear, 800);else return clear; } } - - // this can only happen if user disables paragraph rule - if (!ok) throw new Error('none of the block rules matched'); - - // set state.tight if we had an empty line before current tag - // i.e. latest empty line should not count - state.tight = !hasEmptyLines; - - // paragraph might "eat" one newline after it in nested lists - if (state.isEmpty(state.line - 1)) { - hasEmptyLines = true; + function doMatchBrackets(cm) { + cm.operation(function () { + if (cm.state.matchBrackets.currentlyHighlighted) { + cm.state.matchBrackets.currentlyHighlighted(); + cm.state.matchBrackets.currentlyHighlighted = null; + } + cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); + }); } - line = state.line; - if (line < endLine && state.isEmpty(line)) { - hasEmptyLines = true; - line++; - state.line = line; + function clearHighlighted(cm) { + if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { + cm.state.matchBrackets.currentlyHighlighted(); + cm.state.matchBrackets.currentlyHighlighted = null; + } } + CodeMirror.defineOption("matchBrackets", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.off("cursorActivity", doMatchBrackets); + cm.off("focus", doMatchBrackets); + cm.off("blur", clearHighlighted); + clearHighlighted(cm); + } + if (val) { + cm.state.matchBrackets = typeof val == "object" ? val : {}; + cm.on("cursorActivity", doMatchBrackets); + cm.on("focus", doMatchBrackets); + cm.on("blur", clearHighlighted); + } + }); + CodeMirror.defineExtension("matchBrackets", function () { + matchBrackets(this, true); + }); + CodeMirror.defineExtension("findMatchingBracket", function (pos, config, oldConfig) { + if (oldConfig || typeof config == "boolean") { + if (!oldConfig) { + config = config ? { + strict: true + } : null; + } else { + oldConfig.strict = config; + config = oldConfig; + } + } + return findMatchingBracket(this, pos, config); + }); + CodeMirror.defineExtension("scanForBracket", function (pos, dir, style, config) { + return scanForBracket(this, pos, dir, style, config); + }); + }); + })(); + return matchbrackets.exports; +} +exports.requireMatchbrackets = requireMatchbrackets; + +/***/ }), + +/***/ "../../graphiql-react/dist/mode-indent.cjs.js": +/*!****************************************************!*\ + !*** ../../graphiql-react/dist/mode-indent.cjs.js ***! + \****************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +function indent(state, textAfter) { + var _a, _b; + const { + levels, + indentLevel + } = state; + const level = !levels || levels.length === 0 ? indentLevel : levels.at(-1) - (((_a = this.electricInput) === null || _a === void 0 ? void 0 : _a.test(textAfter)) ? 1 : 0); + return (level || 0) * (((_b = this.config) === null || _b === void 0 ? void 0 : _b.indentUnit) || 0); +} +exports.indent = indent; + +/***/ }), + +/***/ "../../graphiql-react/dist/mode.cjs.js": +/*!*********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs.js ***! + \*********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); +const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); +const graphqlModeFactory = config => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: stream => stream.eatWhile(graphqlLanguageService.isIgnored), + lexRules: graphqlLanguageService.LexRules, + parseRules: graphqlLanguageService.ParseRules, + editorConfig: { + tabSize: config.tabSize } - }; - - /** - * ParserBlock.parse(str, md, env, outTokens) - * - * Process input string and push block tokens into `outTokens` - **/ - ParserBlock.prototype.parse = function (src, md, env, outTokens) { - if (!src) { - return; + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[})\]]/, + fold: "brace", + lineComment: "#", + closeBrackets: { + pairs: '()[]{}""', + explode: "()[]{}" } - const state = new this.State(src, md, env, outTokens); - this.tokenize(state, state.line, state.lineMax); - }; - ParserBlock.prototype.State = StateBlock; - - // Inline parser state - - function StateInline(src, md, env, outTokens) { - this.src = src; - this.env = env; - this.md = md; - this.tokens = outTokens; - this.tokens_meta = Array(outTokens.length); - this.pos = 0; - this.posMax = this.src.length; - this.level = 0; - this.pending = ''; - this.pendingLevel = 0; - - // Stores { start: end } pairs. Useful for backtrack - // optimization of pairs parse (emphasis, strikes). - this.cache = {}; - - // List of emphasis-like delimiters for current tag - this.delimiters = []; - - // Stack of delimiter lists for upper level tags - this._prev_delimiters = []; - - // backtick length => last seen position - this.backticks = {}; - this.backticksScanned = false; - - // Counter used to disable inline linkify-it execution - // inside and markdown links - this.linkLevel = 0; - } - - // Flush pending text - // - StateInline.prototype.pushPending = function () { - const token = new Token('text', '', 0); - token.content = this.pending; - token.level = this.pendingLevel; - this.tokens.push(token); - this.pending = ''; - return token; }; - - // Push new token to "stream". - // If pending text exists - flush it as text token - // - StateInline.prototype.push = function (type, tag, nesting) { - if (this.pending) { - this.pushPending(); - } - const token = new Token(type, tag, nesting); - let token_meta = null; - if (nesting < 0) { - // closing tag - this.level--; - this.delimiters = this._prev_delimiters.pop(); - } - token.level = this.level; - if (nesting > 0) { - // opening tag - this.level++; - this._prev_delimiters.push(this.delimiters); - this.delimiters = []; - token_meta = { - delimiters: this.delimiters - }; +}; +codemirror.CodeMirror.defineMode("graphql", graphqlModeFactory); + +/***/ }), + +/***/ "../../graphiql-react/dist/mode.cjs2.js": +/*!**********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs2.js ***! + \**********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); +const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); +codemirror.CodeMirror.defineMode("graphql-variables", config => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: stream => stream.eatSpace(), + lexRules: LexRules, + parseRules: ParseRules, + editorConfig: { + tabSize: config.tabSize + } + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[}\]]/, + fold: "brace", + closeBrackets: { + pairs: '[]{}""', + explode: "[]{}" } - this.pendingLevel = this.level; - this.tokens.push(token); - this.tokens_meta.push(token_meta); - return token; }; - - // Scan a sequence of emphasis-like markers, and determine whether - // it can start an emphasis sequence or end an emphasis sequence. - // - // - start - position to scan from (it should point at a valid marker); - // - canSplitWord - determine if these markers can be found inside a word - // - StateInline.prototype.scanDelims = function (start, canSplitWord) { - const max = this.posMax; - const marker = this.src.charCodeAt(start); - - // treat beginning of the line as a whitespace - const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; - let pos = start; - while (pos < max && this.src.charCodeAt(pos) === marker) { - pos++; +}); +const LexRules = { + Punctuation: /^\[|]|\{|\}|:|,/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, + Keyword: /^true|false|null/ +}; +const ParseRules = { + Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Variable", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], + Variable: [namedKey("variable"), graphqlLanguageService.p(":"), "Value"], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; + } + return null; + case "Keyword": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + case "null": + return "NullValue"; + } + return null; + } + }, + NumberValue: [graphqlLanguageService.t("Number", "number")], + StringValue: [graphqlLanguageService.t("String", "string")], + BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], + NullValue: [graphqlLanguageService.t("Keyword", "keyword")], + ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("]")], + ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], + ObjectField: [namedKey("attribute"), graphqlLanguageService.p(":"), "Value"] +}; +function namedKey(style) { + return { + style, + match: token => token.kind === "String", + update(state, token) { + state.name = token.value.slice(1, -1); } - const count = pos - start; - - // treat end of the line as a whitespace - const nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; - const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); - const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); - const isLastWhiteSpace = isWhiteSpace(lastChar); - const isNextWhiteSpace = isWhiteSpace(nextChar); - const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar); - const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar); - const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar); - const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar); - return { - can_open, - can_close, - length: count - }; }; - - // re-export Token class to use in block rules - StateInline.prototype.Token = Token; - - // Skip text characters for text token, place those to pending buffer - // and increment current pos - - // Rule to skip pure text - // '{}$%@~+=:' reserved for extentions - - // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ - - // !!!! Don't confuse with "Markdown ASCII Punctuation" chars - // http://spec.commonmark.org/0.15/#ascii-punctuation-character - function isTerminatorChar(ch) { - switch (ch) { - case 0x0A /* \n */: - case 0x21 /* ! */: - case 0x23 /* # */: - case 0x24 /* $ */: - case 0x25 /* % */: - case 0x26 /* & */: - case 0x2A /* * */: - case 0x2B /* + */: - case 0x2D /* - */: - case 0x3A /* : */: - case 0x3C /* < */: - case 0x3D /* = */: - case 0x3E /* > */: - case 0x40 /* @ */: - case 0x5B /* [ */: - case 0x5C /* \ */: - case 0x5D /* ] */: - case 0x5E /* ^ */: - case 0x5F /* _ */: - case 0x60 /* ` */: - case 0x7B /* { */: - case 0x7D /* } */: - case 0x7E /* ~ */: - return true; - default: - return false; +} + +/***/ }), + +/***/ "../../graphiql-react/dist/mode.cjs3.js": +/*!**********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs3.js ***! + \**********************************************/ +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); +const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); +const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); +codemirror.CodeMirror.defineMode("graphql-results", config => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: stream => stream.eatSpace(), + lexRules: LexRules, + parseRules: ParseRules, + editorConfig: { + tabSize: config.tabSize } - } - function text(state, silent) { - let pos = state.pos; - while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) { - pos++; + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[}\]]/, + fold: "brace", + closeBrackets: { + pairs: '[]{}""', + explode: "[]{}" } - if (pos === state.pos) { - return false; + }; +}); +const LexRules = { + Punctuation: /^\[|]|\{|\}|:|,/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, + Keyword: /^true|false|null/ +}; +const ParseRules = { + Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Entry", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], + Entry: [graphqlLanguageService.t("String", "def"), graphqlLanguageService.p(":"), "Value"], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; + } + return null; + case "Keyword": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + case "null": + return "NullValue"; + } + return null; } - if (!silent) { - state.pending += state.src.slice(state.pos, pos); + }, + NumberValue: [graphqlLanguageService.t("Number", "number")], + StringValue: [graphqlLanguageService.t("String", "string")], + BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], + NullValue: [graphqlLanguageService.t("Keyword", "keyword")], + ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.p(",")), graphqlLanguageService.p("]")], + ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], + ObjectField: [graphqlLanguageService.t("String", "property"), graphqlLanguageService.p(":"), "Value"] +}; + +/***/ }), + +/***/ "../../graphiql-react/dist/search.cjs.js": +/*!***********************************************!*\ + !*** ../../graphiql-react/dist/search.cjs.js ***! + \***********************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); +const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } } - state.pos = pos; - return true; } - - // Alternative implementation, for memory. - // - // It costs 10% of performance, but allows extend terminators list, if place it - // to `ParserInline` property. Probably, will switch to it sometime, such - // flexibility required. - - /* - var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; - - module.exports = function text(state, silent) { - var pos = state.pos, - idx = state.src.slice(pos).search(TERMINATOR_RE); - - // first char is terminator -> empty text - if (idx === 0) { return false; } - - // no terminator -> text till end of string - if (idx < 0) { - if (!silent) { state.pending += state.src.slice(pos); } - state.pos = state.src.length; - return true; + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var search$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), dialog.dialogExports); + })(function (CodeMirror) { + CodeMirror.defineOption("search", { + bottom: false + }); + function searchOverlay(query, caseInsensitive) { + if (typeof query == "string") query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");else if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); + return { + token: function (stream) { + query.lastIndex = stream.pos; + var match = query.exec(stream.string); + if (match && match.index == stream.pos) { + stream.pos += match[0].length || 1; + return "searching"; + } else if (match) { + stream.pos = match.index; + } else { + stream.skipToEnd(); + } + } + }; } - - if (!silent) { state.pending += state.src.slice(pos, pos + idx); } - - state.pos += idx; - - return true; - }; */ - - // Process links like https://example.org/ - - // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; - function linkify(state, silent) { - if (!state.md.options.linkify) return false; - if (state.linkLevel > 0) return false; - const pos = state.pos; - const max = state.posMax; - if (pos + 3 > max) return false; - if (state.src.charCodeAt(pos) !== 0x3A /* : */) return false; - if (state.src.charCodeAt(pos + 1) !== 0x2F /* / */) return false; - if (state.src.charCodeAt(pos + 2) !== 0x2F /* / */) return false; - const match = state.pending.match(SCHEME_RE); - if (!match) return false; - const proto = match[1]; - const link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length)); - if (!link) return false; - let url = link.url; - - // invalid link, but still detected by linkify somehow; - // need to check to prevent infinite loop below - if (url.length <= proto.length) return false; - - // disallow '*' at the end of the link (conflicts with emphasis) - url = url.replace(/\*+$/, ''); - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) return false; - if (!silent) { - state.pending = state.pending.slice(0, -proto.length); - const token_o = state.push('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.markup = 'linkify'; - token_o.info = 'auto'; - const token_t = state.push('text', '', 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push('link_close', 'a', -1); - token_c.markup = 'linkify'; - token_c.info = 'auto'; + function SearchState() { + this.posFrom = this.posTo = this.lastQuery = this.query = null; + this.overlay = null; } - state.pos += url.length - proto.length; - return true; - } - - // Proceess '\n' - - function newline(state, silent) { - let pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x0A /* \n */) { - return false; + function getSearchState(cm) { + return cm.state.search || (cm.state.search = new SearchState()); } - const pmax = state.pending.length - 1; - const max = state.posMax; - - // ' \n' -> hardbreak - // Lookup in pending chars is bad practice! Don't copy to other rules! - // Pending string is stored in concat mode, indexed lookups will cause - // convertion to flat mode. - if (!silent) { - if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { - if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { - // Find whitespaces tail of pending chars. - let ws = pmax - 1; - while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) ws--; - state.pending = state.pending.slice(0, ws); - state.push('hardbreak', 'br', 0); - } else { - state.pending = state.pending.slice(0, -1); - state.push('softbreak', 'br', 0); - } - } else { - state.push('softbreak', 'br', 0); - } + function queryCaseInsensitive(query) { + return typeof query == "string" && query == query.toLowerCase(); } - pos++; - - // skip heading spaces for next line - while (pos < max && isSpace(state.src.charCodeAt(pos))) { - pos++; + function getSearchCursor(cm, query, pos) { + return cm.getSearchCursor(query, pos, { + caseFold: queryCaseInsensitive(query), + multiline: true + }); } - state.pos = pos; - return true; - } - - // Process escaped chars and hardbreaks - - const ESCAPED = []; - for (let i = 0; i < 256; i++) { - ESCAPED.push(0); - } - '\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'.split('').forEach(function (ch) { - ESCAPED[ch.charCodeAt(0)] = 1; - }); - function escape(state, silent) { - let pos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(pos) !== 0x5C /* \ */) return false; - pos++; - - // '\' at the end of the inline block - if (pos >= max) return false; - let ch1 = state.src.charCodeAt(pos); - if (ch1 === 0x0A) { - if (!silent) { - state.push('hardbreak', 'br', 0); - } - pos++; - // skip leading whitespaces from next line - while (pos < max) { - ch1 = state.src.charCodeAt(pos); - if (!isSpace(ch1)) break; - pos++; - } - state.pos = pos; - return true; + function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { + cm.openDialog(text, onEnter, { + value: deflt, + selectValueOnOpen: true, + closeOnEnter: false, + onClose: function () { + clearSearch(cm); + }, + onKeyDown, + bottom: cm.options.search.bottom + }); } - let escapedStr = state.src[pos]; - if (ch1 >= 0xD800 && ch1 <= 0xDBFF && pos + 1 < max) { - const ch2 = state.src.charCodeAt(pos + 1); - if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { - escapedStr += state.src[pos + 1]; - pos++; - } + function dialog2(cm, text, shortText, deflt, f) { + if (cm.openDialog) cm.openDialog(text, f, { + value: deflt, + selectValueOnOpen: true, + bottom: cm.options.search.bottom + });else f(prompt(shortText, deflt)); + } + function confirmDialog(cm, text, shortText, fs) { + if (cm.openConfirm) cm.openConfirm(text, fs);else if (confirm(shortText)) fs[0](); + } + function parseString(string) { + return string.replace(/\\([nrt\\])/g, function (match, ch) { + if (ch == "n") return "\n"; + if (ch == "r") return "\r"; + if (ch == "t") return " "; + if (ch == "\\") return "\\"; + return match; + }); } - const origStr = '\\' + escapedStr; - if (!silent) { - const token = state.push('text_special', '', 0); - if (ch1 < 256 && ESCAPED[ch1] !== 0) { - token.content = escapedStr; + function parseQuery(query) { + var isRE = query.match(/^\/(.*)\/([a-z]*)$/); + if (isRE) { + try { + query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); + } catch (e) {} } else { - token.content = origStr; - } - token.markup = origStr; - token.info = 'escape'; - } - state.pos = pos + 1; - return true; - } - - // Parse backticks - - function backtick(state, silent) { - let pos = state.pos; - const ch = state.src.charCodeAt(pos); - if (ch !== 0x60 /* ` */) { - return false; + query = parseString(query); + } + if (typeof query == "string" ? query == "" : query.test("")) query = /x^/; + return query; + } + function startSearch(cm, state, query) { + state.queryText = query; + state.query = parseQuery(query); + cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); + state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); + cm.addOverlay(state.overlay); + if (cm.showMatchesOnScrollbar) { + if (state.annotate) { + state.annotate.clear(); + state.annotate = null; + } + state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); + } + } + function doSearch(cm, rev, persistent, immediate) { + var state = getSearchState(cm); + if (state.query) return findNext(cm, rev); + var q = cm.getSelection() || state.lastQuery; + if (q instanceof RegExp && q.source == "x^") q = null; + if (persistent && cm.openDialog) { + var hiding = null; + var searchNext = function (query, event) { + CodeMirror.e_stop(event); + if (!query) return; + if (query != state.queryText) { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + } + if (hiding) hiding.style.opacity = 1; + findNext(cm, event.shiftKey, function (_, to) { + var dialog3; + if (to.line < 3 && document.querySelector && (dialog3 = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && dialog3.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) (hiding = dialog3).style.opacity = 0.4; + }); + }; + persistentDialog(cm, getQueryDialog(cm), q, searchNext, function (event, query) { + var keyName = CodeMirror.keyName(event); + var extra = cm.getOption("extraKeys"), + cmd = extra && extra[keyName] || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; + if (cmd == "findNext" || cmd == "findPrev" || cmd == "findPersistentNext" || cmd == "findPersistentPrev") { + CodeMirror.e_stop(event); + startSearch(cm, getSearchState(cm), query); + cm.execCommand(cmd); + } else if (cmd == "find" || cmd == "findPersistent") { + CodeMirror.e_stop(event); + searchNext(query, event); + } + }); + if (immediate && q) { + startSearch(cm, state, q); + findNext(cm, rev); + } + } else { + dialog2(cm, getQueryDialog(cm), "Search for:", q, function (query) { + if (query && !state.query) cm.operation(function () { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + findNext(cm, rev); + }); + }); + } } - const start = pos; - pos++; - const max = state.posMax; - - // scan marker length - while (pos < max && state.src.charCodeAt(pos) === 0x60 /* ` */) { - pos++; + function findNext(cm, rev, callback) { + cm.operation(function () { + var state = getSearchState(cm); + var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); + if (!cursor.find(rev)) { + cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); + if (!cursor.find(rev)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({ + from: cursor.from(), + to: cursor.to() + }, 20); + state.posFrom = cursor.from(); + state.posTo = cursor.to(); + if (callback) callback(cursor.from(), cursor.to()); + }); } - const marker = state.src.slice(start, pos); - const openerLength = marker.length; - if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) { - if (!silent) state.pending += marker; - state.pos += openerLength; - return true; + function clearSearch(cm) { + cm.operation(function () { + var state = getSearchState(cm); + state.lastQuery = state.query; + if (!state.query) return; + state.query = state.queryText = null; + cm.removeOverlay(state.overlay); + if (state.annotate) { + state.annotate.clear(); + state.annotate = null; + } + }); } - let matchEnd = pos; - let matchStart; - - // Nothing found in the cache, scan until the end of the line (or until marker is found) - while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { - matchEnd = matchStart + 1; - - // scan marker length - while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60 /* ` */) { - matchEnd++; + function el(tag, attrs) { + var element = tag ? document.createElement(tag) : document.createDocumentFragment(); + for (var key in attrs) { + element[key] = attrs[key]; } - const closerLength = matchEnd - matchStart; - if (closerLength === openerLength) { - // Found matching closer length. - if (!silent) { - const token = state.push('code_inline', 'code', 0); - token.markup = marker; - token.content = state.src.slice(pos, matchStart).replace(/\n/g, ' ').replace(/^ (.+) $/, '$1'); - } - state.pos = matchEnd; - return true; + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + element.appendChild(typeof child == "string" ? document.createTextNode(child) : child); } - - // Some different length found, put it in cache as upper limit of where closer can be found - state.backticks[closerLength] = matchStart; - } - - // Scanned through the end, didn't find anything - state.backticksScanned = true; - if (!silent) state.pending += marker; - state.pos += openerLength; - return true; - } - - // ~~strike through~~ - // - - // Insert each marker as a separate text token, and add it to delimiter list - // - function strikethrough_tokenize(state, silent) { - const start = state.pos; - const marker = state.src.charCodeAt(start); - if (silent) { - return false; + return element; } - if (marker !== 0x7E /* ~ */) { - return false; + function getQueryDialog(cm) { + return el("", null, el("span", { + className: "CodeMirror-search-label" + }, cm.phrase("Search:")), " ", el("input", { + type: "text", + "style": "width: 10em", + className: "CodeMirror-search-field" + }), " ", el("span", { + style: "color: #888", + className: "CodeMirror-search-hint" + }, cm.phrase("(Use /re/ syntax for regexp search)"))); + } + function getReplaceQueryDialog(cm) { + return el("", null, " ", el("input", { + type: "text", + "style": "width: 10em", + className: "CodeMirror-search-field" + }), " ", el("span", { + style: "color: #888", + className: "CodeMirror-search-hint" + }, cm.phrase("(Use /re/ syntax for regexp search)"))); + } + function getReplacementQueryDialog(cm) { + return el("", null, el("span", { + className: "CodeMirror-search-label" + }, cm.phrase("With:")), " ", el("input", { + type: "text", + "style": "width: 10em", + className: "CodeMirror-search-field" + })); } - const scanned = state.scanDelims(state.pos, true); - let len = scanned.length; - const ch = String.fromCharCode(marker); - if (len < 2) { - return false; + function getDoReplaceConfirm(cm) { + return el("", null, el("span", { + className: "CodeMirror-search-label" + }, cm.phrase("Replace?")), " ", el("button", {}, cm.phrase("Yes")), " ", el("button", {}, cm.phrase("No")), " ", el("button", {}, cm.phrase("All")), " ", el("button", {}, cm.phrase("Stop"))); + } + function replaceAll(cm, query, text) { + cm.operation(function () { + for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { + if (typeof query != "string") { + var match = cm.getRange(cursor.from(), cursor.to()).match(query); + cursor.replace(text.replace(/\$(\d)/g, function (_, i) { + return match[i]; + })); + } else cursor.replace(text); + } + }); } - let token; - if (len % 2) { - token = state.push('text', '', 0); - token.content = ch; - len--; - } - for (let i = 0; i < len; i += 2) { - token = state.push('text', '', 0); - token.content = ch + ch; - state.delimiters.push({ - marker, - length: 0, - // disable "rule of 3" length checks meant for emphasis - token: state.tokens.length - 1, - end: -1, - open: scanned.can_open, - close: scanned.can_close + function replace(cm, all) { + if (cm.getOption("readOnly")) return; + var query = cm.getSelection() || getSearchState(cm).lastQuery; + var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:"); + var fragment = el("", null, el("span", { + className: "CodeMirror-search-label" + }, dialogText), getReplaceQueryDialog(cm)); + dialog2(cm, fragment, dialogText, query, function (query2) { + if (!query2) return; + query2 = parseQuery(query2); + dialog2(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function (text) { + text = parseString(text); + if (all) { + replaceAll(cm, query2, text); + } else { + clearSearch(cm); + var cursor = getSearchCursor(cm, query2, cm.getCursor("from")); + var advance = function () { + var start = cursor.from(), + match; + if (!(match = cursor.findNext())) { + cursor = getSearchCursor(cm, query2); + if (!(match = cursor.findNext()) || start && cursor.from().line == start.line && cursor.from().ch == start.ch) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({ + from: cursor.from(), + to: cursor.to() + }); + confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"), [function () { + doReplace(match); + }, advance, function () { + replaceAll(cm, query2, text); + }]); + }; + var doReplace = function (match) { + cursor.replace(typeof query2 == "string" ? text : text.replace(/\$(\d)/g, function (_, i) { + return match[i]; + })); + advance(); + }; + advance(); + } + }); }); } - state.pos += scanned.length; - return true; + CodeMirror.commands.find = function (cm) { + clearSearch(cm); + doSearch(cm); + }; + CodeMirror.commands.findPersistent = function (cm) { + clearSearch(cm); + doSearch(cm, false, true); + }; + CodeMirror.commands.findPersistentNext = function (cm) { + doSearch(cm, false, true, true); + }; + CodeMirror.commands.findPersistentPrev = function (cm) { + doSearch(cm, true, true, true); + }; + CodeMirror.commands.findNext = doSearch; + CodeMirror.commands.findPrev = function (cm) { + doSearch(cm, true); + }; + CodeMirror.commands.clearSearch = clearSearch; + CodeMirror.commands.replace = replace; + CodeMirror.commands.replaceAll = function (cm) { + replace(cm, true); + }; + }); +})(); +var searchExports = search$2.exports; +const search = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchExports); +const search$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: search +}, [searchExports]); +exports.search = search$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/searchcursor.cjs.js": +/*!*****************************************************!*\ + !*** ../../graphiql-react/dist/searchcursor.cjs.js ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +const searchcursor$2 = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } + } } - function postProcess$1(state, delimiters) { - let token; - const loneMarkers = []; - const max = delimiters.length; - for (let i = 0; i < max; i++) { - const startDelim = delimiters[i]; - if (startDelim.marker !== 0x7E /* ~ */) { - continue; + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var searchcursorExports = searchcursor$2.requireSearchcursor(); +const searchcursor = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchcursorExports); +const searchcursor$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: searchcursor +}, [searchcursorExports]); +exports.searchcursor = searchcursor$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/searchcursor.cjs2.js": +/*!******************************************************!*\ + !*** ../../graphiql-react/dist/searchcursor.cjs2.js ***! + \******************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +var searchcursor = { + exports: {} +}; +var hasRequiredSearchcursor; +function requireSearchcursor() { + if (hasRequiredSearchcursor) return searchcursor.exports; + hasRequiredSearchcursor = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var Pos = CodeMirror.Pos; + function regexpFlags(regexp) { + var flags = regexp.flags; + return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : ""); + } + function ensureFlags(regexp, flags) { + var current = regexpFlags(regexp), + target = current; + for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) target += flags.charAt(i); + return current == target ? regexp : new RegExp(regexp.source, target); + } + function maybeMultiline(regexp) { + return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); + } + function searchRegexpForward(doc, regexp, start) { + regexp = ensureFlags(regexp, "g"); + for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { + regexp.lastIndex = ch; + var string = doc.getLine(line), + match = regexp.exec(string); + if (match) return { + from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match + }; + } } - if (startDelim.end === -1) { - continue; + function searchRegexpForwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start); + regexp = ensureFlags(regexp, "gm"); + var string, + chunk = 1; + for (var line = start.line, last = doc.lastLine(); line <= last;) { + for (var i = 0; i < chunk; i++) { + if (line > last) break; + var curLine = doc.getLine(line++); + string = string == null ? curLine : string + "\n" + curLine; + } + chunk = chunk * 2; + regexp.lastIndex = start.ch; + var match = regexp.exec(string); + if (match) { + var before = string.slice(0, match.index).split("\n"), + inside = match[0].split("\n"); + var startLine = start.line + before.length - 1, + startCh = before[before.length - 1].length; + return { + from: Pos(startLine, startCh), + to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), + match + }; + } + } } - const endDelim = delimiters[startDelim.end]; - token = state.tokens[startDelim.token]; - token.type = 's_open'; - token.tag = 's'; - token.nesting = 1; - token.markup = '~~'; - token.content = ''; - token = state.tokens[endDelim.token]; - token.type = 's_close'; - token.tag = 's'; - token.nesting = -1; - token.markup = '~~'; - token.content = ''; - if (state.tokens[endDelim.token - 1].type === 'text' && state.tokens[endDelim.token - 1].content === '~') { - loneMarkers.push(endDelim.token - 1); + function lastMatchIn(string, regexp, endMargin) { + var match, + from = 0; + while (from <= string.length) { + regexp.lastIndex = from; + var newMatch = regexp.exec(string); + if (!newMatch) break; + var end = newMatch.index + newMatch[0].length; + if (end > string.length - endMargin) break; + if (!match || end > match.index + match[0].length) match = newMatch; + from = newMatch.index + 1; + } + return match; + } + function searchRegexpBackward(doc, regexp, start) { + regexp = ensureFlags(regexp, "g"); + for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { + var string = doc.getLine(line); + var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch); + if (match) return { + from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match + }; + } } - } - - // If a marker sequence has an odd number of characters, it's splitted - // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the - // start of the sequence. - // - // So, we have to move all those markers after subsequent s_close tags. - // - while (loneMarkers.length) { - const i = loneMarkers.pop(); - let j = i + 1; - while (j < state.tokens.length && state.tokens[j].type === 's_close') { - j++; + function searchRegexpBackwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start); + regexp = ensureFlags(regexp, "gm"); + var string, + chunkSize = 1, + endMargin = doc.getLine(start.line).length - start.ch; + for (var line = start.line, first = doc.firstLine(); line >= first;) { + for (var i = 0; i < chunkSize && line >= first; i++) { + var curLine = doc.getLine(line--); + string = string == null ? curLine : curLine + "\n" + string; + } + chunkSize *= 2; + var match = lastMatchIn(string, regexp, endMargin); + if (match) { + var before = string.slice(0, match.index).split("\n"), + inside = match[0].split("\n"); + var startLine = line + before.length, + startCh = before[before.length - 1].length; + return { + from: Pos(startLine, startCh), + to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), + match + }; + } + } + } + var doFold, noFold; + if (String.prototype.normalize) { + doFold = function (str) { + return str.normalize("NFD").toLowerCase(); + }; + noFold = function (str) { + return str.normalize("NFD"); + }; + } else { + doFold = function (str) { + return str.toLowerCase(); + }; + noFold = function (str) { + return str; + }; } - j--; - if (i !== j) { - token = state.tokens[j]; - state.tokens[j] = state.tokens[i]; - state.tokens[i] = token; + function adjustPos(orig, folded, pos, foldFunc) { + if (orig.length == folded.length) return pos; + for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { + if (min == max) return min; + var mid = min + max >> 1; + var len = foldFunc(orig.slice(0, mid)).length; + if (len == pos) return mid;else if (len > pos) max = mid;else min = mid + 1; + } + } + function searchStringForward(doc, query, start, caseFold) { + if (!query.length) return null; + var fold = caseFold ? doFold : noFold; + var lines = fold(query).split(/\r|\n\r?/); + search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { + var orig = doc.getLine(line).slice(ch), + string = fold(orig); + if (lines.length == 1) { + var found = string.indexOf(lines[0]); + if (found == -1) continue search; + var start = adjustPos(orig, string, found, fold) + ch; + return { + from: Pos(line, adjustPos(orig, string, found, fold) + ch), + to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch) + }; + } else { + var cutFrom = string.length - lines[0].length; + if (string.slice(cutFrom) != lines[0]) continue search; + for (var i = 1; i < lines.length - 1; i++) if (fold(doc.getLine(line + i)) != lines[i]) continue search; + var end = doc.getLine(line + lines.length - 1), + endString = fold(end), + lastLine = lines[lines.length - 1]; + if (endString.slice(0, lastLine.length) != lastLine) continue search; + return { + from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), + to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold)) + }; + } + } } - } - } - - // Walk through delimiter list and replace text tokens with tags - // - function strikethrough_postProcess(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - postProcess$1(state, state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - postProcess$1(state, tokens_meta[curr].delimiters); + function searchStringBackward(doc, query, start, caseFold) { + if (!query.length) return null; + var fold = caseFold ? doFold : noFold; + var lines = fold(query).split(/\r|\n\r?/); + search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { + var orig = doc.getLine(line); + if (ch > -1) orig = orig.slice(0, ch); + var string = fold(orig); + if (lines.length == 1) { + var found = string.lastIndexOf(lines[0]); + if (found == -1) continue search; + return { + from: Pos(line, adjustPos(orig, string, found, fold)), + to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold)) + }; + } else { + var lastLine = lines[lines.length - 1]; + if (string.slice(0, lastLine.length) != lastLine) continue search; + for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) if (fold(doc.getLine(start + i)) != lines[i]) continue search; + var top = doc.getLine(line + 1 - lines.length), + topString = fold(top); + if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search; + return { + from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), + to: Pos(line, adjustPos(orig, string, lastLine.length, fold)) + }; + } + } + } + function SearchCursor(doc, query, pos, options) { + this.atOccurrence = false; + this.afterEmptyMatch = false; + this.doc = doc; + pos = pos ? doc.clipPos(pos) : Pos(0, 0); + this.pos = { + from: pos, + to: pos + }; + var caseFold; + if (typeof options == "object") { + caseFold = options.caseFold; + } else { + caseFold = options; + options = null; + } + if (typeof query == "string") { + if (caseFold == null) caseFold = false; + this.matches = function (reverse, pos2) { + return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos2, caseFold); + }; + } else { + query = ensureFlags(query, "gm"); + if (!options || options.multiline !== false) this.matches = function (reverse, pos2) { + return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos2); + };else this.matches = function (reverse, pos2) { + return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos2); + }; + } + } + SearchCursor.prototype = { + findNext: function () { + return this.find(false); + }, + findPrevious: function () { + return this.find(true); + }, + find: function (reverse) { + var head = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); + if (this.afterEmptyMatch && this.atOccurrence) { + head = Pos(head.line, head.ch); + if (reverse) { + head.ch--; + if (head.ch < 0) { + head.line--; + head.ch = (this.doc.getLine(head.line) || "").length; + } + } else { + head.ch++; + if (head.ch > (this.doc.getLine(head.line) || "").length) { + head.ch = 0; + head.line++; + } + } + if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { + return this.atOccurrence = false; + } + } + var result = this.matches(reverse, head); + this.afterEmptyMatch = result && CodeMirror.cmpPos(result.from, result.to) == 0; + if (result) { + this.pos = result; + this.atOccurrence = true; + return this.pos.match || true; + } else { + var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0); + this.pos = { + from: end, + to: end + }; + return this.atOccurrence = false; + } + }, + from: function () { + if (this.atOccurrence) return this.pos.from; + }, + to: function () { + if (this.atOccurrence) return this.pos.to; + }, + replace: function (newText, origin) { + if (!this.atOccurrence) return; + var lines = CodeMirror.splitLines(newText); + this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin); + this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); + } + }; + CodeMirror.defineExtension("getSearchCursor", function (query, pos, caseFold) { + return new SearchCursor(this.doc, query, pos, caseFold); + }); + CodeMirror.defineDocExtension("getSearchCursor", function (query, pos, caseFold) { + return new SearchCursor(this, query, pos, caseFold); + }); + CodeMirror.defineExtension("selectMatches", function (query, caseFold) { + var ranges = []; + var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); + while (cur.findNext()) { + if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; + ranges.push({ + anchor: cur.from(), + head: cur.to() + }); + } + if (ranges.length) this.setSelections(ranges, 0); + }); + }); + })(); + return searchcursor.exports; +} +exports.requireSearchcursor = requireSearchcursor; + +/***/ }), + +/***/ "../../graphiql-react/dist/show-hint.cjs.js": +/*!**************************************************!*\ + !*** ../../graphiql-react/dist/show-hint.cjs.js ***! + \**************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } } } } - var r_strikethrough = { - tokenize: strikethrough_tokenize, - postProcess: strikethrough_postProcess - }; - - // Process *this* and _that_ - // - - // Insert each marker as a separate text token, and add it to delimiter list - // - function emphasis_tokenize(state, silent) { - const start = state.pos; - const marker = state.src.charCodeAt(start); - if (silent) { - return false; + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var showHint$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var HINT_ELEMENT_CLASS = "CodeMirror-hint"; + var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; + CodeMirror.showHint = function (cm, getHints, options) { + if (!getHints) return cm.showHint(options); + if (options && options.async) getHints.async = true; + var newOpts = { + hint: getHints + }; + if (options) for (var prop in options) newOpts[prop] = options[prop]; + return cm.showHint(newOpts); + }; + CodeMirror.defineExtension("showHint", function (options) { + options = parseOptions(this, this.getCursor("start"), options); + var selections = this.listSelections(); + if (selections.length > 1) return; + if (this.somethingSelected()) { + if (!options.hint.supportsSelection) return; + for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; + } + if (this.state.completionActive) this.state.completionActive.close(); + var completion = this.state.completionActive = new Completion(this, options); + if (!completion.options.hint) return; + CodeMirror.signal(this, "startCompletion", this); + completion.update(true); + }); + CodeMirror.defineExtension("closeHint", function () { + if (this.state.completionActive) this.state.completionActive.close(); + }); + function Completion(cm, options) { + this.cm = cm; + this.options = options; + this.widget = null; + this.debounce = 0; + this.tick = 0; + this.startPos = this.cm.getCursor("start"); + this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; + if (this.options.updateOnCursorActivity) { + var self = this; + cm.on("cursorActivity", this.activityFunc = function () { + self.cursorActivity(); + }); + } } - if (marker !== 0x5F /* _ */ && marker !== 0x2A /* * */) { - return false; + var requestAnimationFrame = window.requestAnimationFrame || function (fn) { + return setTimeout(fn, 1e3 / 60); + }; + var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; + Completion.prototype = { + close: function () { + if (!this.active()) return; + this.cm.state.completionActive = null; + this.tick = null; + if (this.options.updateOnCursorActivity) { + this.cm.off("cursorActivity", this.activityFunc); + } + if (this.widget && this.data) CodeMirror.signal(this.data, "close"); + if (this.widget) this.widget.close(); + CodeMirror.signal(this.cm, "endCompletion", this.cm); + }, + active: function () { + return this.cm.state.completionActive == this; + }, + pick: function (data, i) { + var completion = data.list[i], + self = this; + this.cm.operation(function () { + if (completion.hint) completion.hint(self.cm, data, completion);else self.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); + CodeMirror.signal(data, "pick", completion); + self.cm.scrollIntoView(); + }); + if (this.options.closeOnPick) { + this.close(); + } + }, + cursorActivity: function () { + if (this.debounce) { + cancelAnimationFrame(this.debounce); + this.debounce = 0; + } + var identStart = this.startPos; + if (this.data) { + identStart = this.data.from; + } + var pos = this.cm.getCursor(), + line = this.cm.getLine(pos.line); + if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < identStart.ch || this.cm.somethingSelected() || !pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1))) { + this.close(); + } else { + var self = this; + this.debounce = requestAnimationFrame(function () { + self.update(); + }); + if (this.widget) this.widget.disable(); + } + }, + update: function (first) { + if (this.tick == null) return; + var self = this, + myTick = ++this.tick; + fetchHints(this.options.hint, this.cm, this.options, function (data) { + if (self.tick == myTick) self.finishUpdate(data, first); + }); + }, + finishUpdate: function (data, first) { + if (this.data) CodeMirror.signal(this.data, "update"); + var picked = this.widget && this.widget.picked || first && this.options.completeSingle; + if (this.widget) this.widget.close(); + this.data = data; + if (data && data.list.length) { + if (picked && data.list.length == 1) { + this.pick(data, 0); + } else { + this.widget = new Widget(this, data); + CodeMirror.signal(data, "shown"); + } + } + } + }; + function parseOptions(cm, pos, options) { + var editor = cm.options.hintOptions; + var out = {}; + for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; + if (editor) { + for (var prop in editor) if (editor[prop] !== void 0) out[prop] = editor[prop]; + } + if (options) { + for (var prop in options) if (options[prop] !== void 0) out[prop] = options[prop]; + } + if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); + return out; } - const scanned = state.scanDelims(state.pos, marker === 0x2A); - for (let i = 0; i < scanned.length; i++) { - const token = state.push('text', '', 0); - token.content = String.fromCharCode(marker); - state.delimiters.push({ - // Char code of the starting marker (number). - // - marker, - // Total length of these series of delimiters. - // - length: scanned.length, - // A position of the token this delimiter corresponds to. - // - token: state.tokens.length - 1, - // If this delimiter is matched as a valid opener, `end` will be - // equal to its position, otherwise it's `-1`. - // - end: -1, - // Boolean flags that determine if this delimiter could open or close - // an emphasis. - // - open: scanned.can_open, - close: scanned.can_close - }); + function getText(completion) { + if (typeof completion == "string") return completion;else return completion.text; } - state.pos += scanned.length; - return true; - } - function postProcess(state, delimiters) { - const max = delimiters.length; - for (let i = max - 1; i >= 0; i--) { - const startDelim = delimiters[i]; - if (startDelim.marker !== 0x5F /* _ */ && startDelim.marker !== 0x2A /* * */) { - continue; - } - - // Process only opening markers - if (startDelim.end === -1) { - continue; + function buildKeyMap(completion, handle) { + var baseMap = { + Up: function () { + handle.moveFocus(-1); + }, + Down: function () { + handle.moveFocus(1); + }, + PageUp: function () { + handle.moveFocus(-handle.menuSize() + 1, true); + }, + PageDown: function () { + handle.moveFocus(handle.menuSize() - 1, true); + }, + Home: function () { + handle.setFocus(0); + }, + End: function () { + handle.setFocus(handle.length - 1); + }, + Enter: handle.pick, + Tab: handle.pick, + Esc: handle.close + }; + var mac = /Mac/.test(navigator.platform); + if (mac) { + baseMap["Ctrl-P"] = function () { + handle.moveFocus(-1); + }; + baseMap["Ctrl-N"] = function () { + handle.moveFocus(1); + }; } - const endDelim = delimiters[startDelim.end]; - - // If the previous delimiter has the same marker and is adjacent to this one, - // merge those into one strong delimiter. - // - // `whatever` -> `whatever` - // - const isStrong = i > 0 && delimiters[i - 1].end === startDelim.end + 1 && - // check that first two markers match and adjacent - delimiters[i - 1].marker === startDelim.marker && delimiters[i - 1].token === startDelim.token - 1 && - // check that last two markers are adjacent (we can safely assume they match) - delimiters[startDelim.end + 1].token === endDelim.token + 1; - const ch = String.fromCharCode(startDelim.marker); - const token_o = state.tokens[startDelim.token]; - token_o.type = isStrong ? 'strong_open' : 'em_open'; - token_o.tag = isStrong ? 'strong' : 'em'; - token_o.nesting = 1; - token_o.markup = isStrong ? ch + ch : ch; - token_o.content = ''; - const token_c = state.tokens[endDelim.token]; - token_c.type = isStrong ? 'strong_close' : 'em_close'; - token_c.tag = isStrong ? 'strong' : 'em'; - token_c.nesting = -1; - token_c.markup = isStrong ? ch + ch : ch; - token_c.content = ''; - if (isStrong) { - state.tokens[delimiters[i - 1].token].content = ''; - state.tokens[delimiters[startDelim.end + 1].token].content = ''; - i--; + var custom = completion.options.customKeys; + var ourMap = custom ? {} : baseMap; + function addBinding(key2, val) { + var bound; + if (typeof val != "string") bound = function (cm) { + return val(cm, handle); + };else if (baseMap.hasOwnProperty(val)) bound = baseMap[val];else bound = val; + ourMap[key2] = bound; + } + if (custom) { + for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); + } + var extra = completion.options.extraKeys; + if (extra) { + for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); + } + return ourMap; + } + function getHintElement(hintsElement, el) { + while (el && el != hintsElement) { + if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; + el = el.parentNode; + } + } + function Widget(completion, data) { + this.id = "cm-complete-" + Math.floor(Math.random(1e6)); + this.completion = completion; + this.data = data; + this.picked = false; + var widget = this, + cm = completion.cm; + var ownerDocument = cm.getInputField().ownerDocument; + var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow; + var hints = this.hints = ownerDocument.createElement("ul"); + hints.setAttribute("role", "listbox"); + hints.setAttribute("aria-expanded", "true"); + hints.id = this.id; + var theme = completion.cm.options.theme; + hints.className = "CodeMirror-hints " + theme; + this.selectedHint = data.selectedHint || 0; + var completions = data.list; + for (var i = 0; i < completions.length; ++i) { + var elt = hints.appendChild(ownerDocument.createElement("li")), + cur = completions[i]; + var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); + if (cur.className != null) className = cur.className + " " + className; + elt.className = className; + if (i == this.selectedHint) elt.setAttribute("aria-selected", "true"); + elt.id = this.id + "-" + i; + elt.setAttribute("role", "option"); + if (cur.render) cur.render(elt, data, cur);else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur))); + elt.hintId = i; + } + var container = completion.options.container || ownerDocument.body; + var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); + var left = pos.left, + top = pos.bottom, + below = true; + var offsetLeft = 0, + offsetTop = 0; + if (container !== ownerDocument.body) { + var isContainerPositioned = ["absolute", "relative", "fixed"].indexOf(parentWindow.getComputedStyle(container).position) !== -1; + var offsetParent = isContainerPositioned ? container : container.offsetParent; + var offsetParentPosition = offsetParent.getBoundingClientRect(); + var bodyPosition = ownerDocument.body.getBoundingClientRect(); + offsetLeft = offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft; + offsetTop = offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop; + } + hints.style.left = left - offsetLeft + "px"; + hints.style.top = top - offsetTop + "px"; + var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth); + var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight); + container.appendChild(hints); + cm.getInputField().setAttribute("aria-autocomplete", "list"); + cm.getInputField().setAttribute("aria-owns", this.id); + cm.getInputField().setAttribute("aria-activedescendant", this.id + "-" + this.selectedHint); + var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect(); + var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false; + var startScroll; + setTimeout(function () { + startScroll = cm.getScrollInfo(); + }); + var overlapY = box.bottom - winH; + if (overlapY > 0) { + var height = box.bottom - box.top, + curTop = pos.top - (pos.bottom - box.top); + if (curTop - height > 0) { + hints.style.top = (top = pos.top - height - offsetTop) + "px"; + below = false; + } else if (height > winH) { + hints.style.height = winH - 5 + "px"; + hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px"; + var cursor = cm.getCursor(); + if (data.from.ch != cursor.ch) { + pos = cm.cursorCoords(cursor); + hints.style.left = (left = pos.left - offsetLeft) + "px"; + box = hints.getBoundingClientRect(); + } + } + } + var overlapX = box.right - winW; + if (scrolls) overlapX += cm.display.nativeBarWidth; + if (overlapX > 0) { + if (box.right - box.left > winW) { + hints.style.width = winW - 5 + "px"; + overlapX -= box.right - box.left - winW; + } + hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px"; + } + if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling) node.style.paddingRight = cm.display.nativeBarWidth + "px"; + cm.addKeyMap(this.keyMap = buildKeyMap(completion, { + moveFocus: function (n, avoidWrap) { + widget.changeActive(widget.selectedHint + n, avoidWrap); + }, + setFocus: function (n) { + widget.changeActive(n); + }, + menuSize: function () { + return widget.screenAmount(); + }, + length: completions.length, + close: function () { + completion.close(); + }, + pick: function () { + widget.pick(); + }, + data + })); + if (completion.options.closeOnUnfocus) { + var closingOnBlur; + cm.on("blur", this.onBlur = function () { + closingOnBlur = setTimeout(function () { + completion.close(); + }, 100); + }); + cm.on("focus", this.onFocus = function () { + clearTimeout(closingOnBlur); + }); } - } - } - - // Walk through delimiter list and replace text tokens with tags - // - function emphasis_post_process(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - postProcess(state, state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - postProcess(state, tokens_meta[curr].delimiters); + cm.on("scroll", this.onScroll = function () { + var curScroll = cm.getScrollInfo(), + editor = cm.getWrapperElement().getBoundingClientRect(); + if (!startScroll) startScroll = cm.getScrollInfo(); + var newTop = top + startScroll.top - curScroll.top; + var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop); + if (!below) point += hints.offsetHeight; + if (point <= editor.top || point >= editor.bottom) return completion.close(); + hints.style.top = newTop + "px"; + hints.style.left = left + startScroll.left - curScroll.left + "px"; + }); + CodeMirror.on(hints, "dblclick", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + widget.pick(); + } + }); + CodeMirror.on(hints, "click", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + if (completion.options.completeOnSingleClick) widget.pick(); + } + }); + CodeMirror.on(hints, "mousedown", function () { + setTimeout(function () { + cm.focus(); + }, 20); + }); + var selectedHintRange = this.getSelectedHintRange(); + if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { + this.scrollToActive(); } + CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]); + return true; } - } - var r_emphasis = { - tokenize: emphasis_tokenize, - postProcess: emphasis_post_process - }; - - // Process [link]( "stuff") - - function link(state, silent) { - let code, label, res, ref; - let href = ''; - let title = ''; - let start = state.pos; - let parseReference = true; - if (state.src.charCodeAt(state.pos) !== 0x5B /* [ */) { - return false; + Widget.prototype = { + close: function () { + if (this.completion.widget != this) return; + this.completion.widget = null; + if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints); + this.completion.cm.removeKeyMap(this.keyMap); + var input = this.completion.cm.getInputField(); + input.removeAttribute("aria-activedescendant"); + input.removeAttribute("aria-owns"); + var cm = this.completion.cm; + if (this.completion.options.closeOnUnfocus) { + cm.off("blur", this.onBlur); + cm.off("focus", this.onFocus); + } + cm.off("scroll", this.onScroll); + }, + disable: function () { + this.completion.cm.removeKeyMap(this.keyMap); + var widget = this; + this.keyMap = { + Enter: function () { + widget.picked = true; + } + }; + this.completion.cm.addKeyMap(this.keyMap); + }, + pick: function () { + this.completion.pick(this.data, this.selectedHint); + }, + changeActive: function (i, avoidWrap) { + if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0;else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; + if (this.selectedHint == i) return; + var node = this.hints.childNodes[this.selectedHint]; + if (node) { + node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); + node.removeAttribute("aria-selected"); + } + node = this.hints.childNodes[this.selectedHint = i]; + node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; + node.setAttribute("aria-selected", "true"); + this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id); + this.scrollToActive(); + CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); + }, + scrollToActive: function () { + var selectedHintRange = this.getSelectedHintRange(); + var node1 = this.hints.childNodes[selectedHintRange.from]; + var node2 = this.hints.childNodes[selectedHintRange.to]; + var firstNode = this.hints.firstChild; + if (node1.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop; + }, + screenAmount: function () { + return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; + }, + getSelectedHintRange: function () { + var margin = this.completion.options.scrollMargin || 0; + return { + from: Math.max(0, this.selectedHint - margin), + to: Math.min(this.data.list.length - 1, this.selectedHint + margin) + }; + } + }; + function applicableHelpers(cm, helpers) { + if (!cm.somethingSelected()) return helpers; + var result = []; + for (var i = 0; i < helpers.length; i++) if (helpers[i].supportsSelection) result.push(helpers[i]); + return result; } - const oldPos = state.pos; - const max = state.posMax; - const labelStart = state.pos + 1; - const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true); - - // parser failed to find ']', so it's not a valid link - if (labelEnd < 0) { - return false; + function fetchHints(hint, cm, options, callback) { + if (hint.async) { + hint(cm, callback, options); + } else { + var result = hint(cm, options); + if (result && result.then) result.then(callback);else callback(result); + } + } + function resolveAutoHints(cm, pos) { + var helpers = cm.getHelpers(pos, "hint"), + words; + if (helpers.length) { + var resolved = function (cm2, callback, options) { + var app = applicableHelpers(cm2, helpers); + function run(i) { + if (i == app.length) return callback(null); + fetchHints(app[i], cm2, options, function (result) { + if (result && result.list.length > 0) callback(result);else run(i + 1); + }); + } + run(0); + }; + resolved.async = true; + resolved.supportsSelection = true; + return resolved; + } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { + return function (cm2) { + return CodeMirror.hint.fromList(cm2, { + words + }); + }; + } else if (CodeMirror.hint.anyword) { + return function (cm2, options) { + return CodeMirror.hint.anyword(cm2, options); + }; + } else { + return function () {}; + } } - let pos = labelEnd + 1; - if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { - // - // Inline link - // - - // might have found a valid shortcut link, disable reference parsing - parseReference = false; - - // [link]( "title" ) - // ^^ skipping these spaces - pos++; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; - } + CodeMirror.registerHelper("hint", "auto", { + resolve: resolveAutoHints + }); + CodeMirror.registerHelper("hint", "fromList", function (cm, options) { + var cur = cm.getCursor(), + token = cm.getTokenAt(cur); + var term, + from = CodeMirror.Pos(cur.line, token.start), + to = cur; + if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) { + term = token.string.substr(0, cur.ch - token.start); + } else { + term = ""; + from = cur; } - if (pos >= max) { - return false; + var found = []; + for (var i = 0; i < options.words.length; i++) { + var word = options.words[i]; + if (word.slice(0, term.length) == term) found.push(word); } - - // [link]( "title" ) - // ^^^^^^ parsing link destination - start = pos; - res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); - if (res.ok) { - href = state.md.normalizeLink(res.str); - if (state.md.validateLink(href)) { - pos = res.pos; - } else { - href = ''; - } - - // [link]( "title" ) - // ^^ skipping these spaces - start = pos; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + if (found.length) return { + list: found, + from, + to + }; + }); + CodeMirror.commands.autocomplete = CodeMirror.showHint; + var defaultOptions = { + hint: CodeMirror.hint.auto, + completeSingle: true, + alignWithWord: true, + closeCharacters: /[\s()\[\]{};:>,]/, + closeOnPick: true, + closeOnUnfocus: true, + updateOnCursorActivity: true, + completeOnSingleClick: true, + container: null, + customKeys: null, + extraKeys: null, + paddingForScrollbar: true, + moveOnOverlap: true + }; + CodeMirror.defineOption("hintOptions", null); + }); +})(); +var showHintExports = showHint$2.exports; +const showHint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(showHintExports); +const showHint$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: showHint +}, [showHintExports]); +exports.showHint = showHint$1; + +/***/ }), + +/***/ "../../graphiql-react/dist/sublime.cjs.js": +/*!************************************************!*\ + !*** ../../graphiql-react/dist/sublime.cjs.js ***! + \************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); +const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); +const matchbrackets = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); +function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } } - - // [link]( "title" ) - // ^^^^^^^ parsing link title - res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); - if (pos < max && start !== pos && res.ok) { - title = res.str; - pos = res.pos; - - // [link]( "title" ) - // ^^ skipping these spaces - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); +} +var sublime$2 = { + exports: {} +}; +(function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), matchbrackets.requireMatchbrackets()); + })(function (CodeMirror) { + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); + var line = doc.getLine(start.line); + if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); + var state = "start", + type, + startPos = start.ch; + for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { + var next = line.charAt(dir < 0 ? pos - 1 : pos); + var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { + state = "in"; + type = cat; + } else startPos = pos + dir; + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { + if (pos == startPos + 1) { + type = "w"; + continue; + } else pos--; } + break; } } } - if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { - // parsing a valid shortcut link failed, fallback to reference - parseReference = true; - } - pos++; + return Pos(start.line, pos); } - if (parseReference) { - // - // Link reference - // - if (typeof state.env.references === 'undefined') { - return false; - } - if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { - start = pos + 1; - pos = state.md.helpers.parseLinkLabel(state, pos); - if (pos >= 0) { - label = state.src.slice(start, pos++); - } else { - pos = labelEnd + 1; - } - } else { - pos = labelEnd + 1; + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function (range) { + if (cm.display.shift || cm.doc.extend || range.empty()) return findPosSubword(cm.doc, range.head, dir);else return dir < 0 ? range.from() : range.to(); + }); + } + cmds.goSubwordLeft = function (cm) { + moveSubword(cm, -1); + }; + cmds.goSubwordRight = function (cm) { + moveSubword(cm, 1); + }; + cmds.scrollLineUp = function (cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); + if (cm.getCursor().line >= visibleBottomLine) cm.execCommand("goLineUp"); } - - // covers label === '' and label === undefined - // (collapsed reference link and shortcut reference link respectively) - if (!label) { - label = state.src.slice(labelStart, labelEnd); + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds.scrollLineDown = function (cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; + if (cm.getCursor().line <= visibleTopLine) cm.execCommand("goLineDown"); } - ref = state.env.references[normalizeReference(label)]; - if (!ref) { - state.pos = oldPos; - return false; + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + cmds.splitSelectionByLine = function (cm) { + var ranges = cm.listSelections(), + lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), + to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) if (!(to.line > from.line && line == to.line && to.ch == 0)) lineRanges.push({ + anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line) + }); } - href = ref.href; - title = ref.title; - } - - // - // We found the end of the link, and know for a fact it's a valid link; - // so all that's left to do is to call tokenizer. - // - if (!silent) { - state.pos = labelStart; - state.posMax = labelEnd; - const token_o = state.push('link_open', 'a', 1); - const attrs = [['href', href]]; - token_o.attrs = attrs; - if (title) { - attrs.push(['title', title]); + cm.setSelections(lineRanges, 0); + }; + cmds.singleSelectionTop = function (cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, { + scroll: false + }); + }; + cmds.selectLine = function (cm) { + var ranges = cm.listSelections(), + extended = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + extended.push({ + anchor: Pos(range.from().line, 0), + head: Pos(range.to().line + 1, 0) + }); } - state.linkLevel++; - state.md.inline.tokenize(state); - state.linkLevel--; - state.push('link_close', 'a', -1); + cm.setSelections(extended); + }; + function insertLine(cm, above) { + if (cm.isReadOnly()) return CodeMirror.Pass; + cm.operation(function () { + var len = cm.listSelections().length, + newSelection = [], + last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({ + head: at, + anchor: at + }); + last = head.line + 1; + } + cm.setSelections(newSelection); + }); + cm.execCommand("indentAuto"); } - state.pos = pos; - state.posMax = max; - return true; - } - - // Process ![image]( "title") - - function image(state, silent) { - let code, content, label, pos, ref, res, title, start; - let href = ''; - const oldPos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(state.pos) !== 0x21 /* ! */) { - return false; + cmds.insertLineAfter = function (cm) { + return insertLine(cm, false); + }; + cmds.insertLineBefore = function (cm) { + return insertLine(cm, true); + }; + function wordAt(cm, pos) { + var start = pos.ch, + end = start, + line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; + while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; + return { + from: Pos(pos.line, start), + to: Pos(pos.line, end), + word: line.slice(start, end) + }; } - if (state.src.charCodeAt(state.pos + 1) !== 0x5B /* [ */) { - return false; + cmds.selectNextOccurrence = function (cm) { + var from = cm.getCursor("from"), + to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + var found = cur.findNext(); + if (!found) { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + found = cur.findNext(); + } + if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return; + cm.addSelection(cur.from(), cur.to()); + } + if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; + }; + cmds.skipAndSelectNextOccurrence = function (cm) { + var prevAnchor = cm.getCursor("anchor"), + prevHead = cm.getCursor("head"); + cmds.selectNextOccurrence(cm); + if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { + cm.doc.setSelections(cm.doc.listSelections().filter(function (sel) { + return sel.anchor != prevAnchor || sel.head != prevHead; + })); + } + }; + function addCursorToSelection(cm, dir) { + var ranges = cm.listSelections(), + newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var newAnchor = cm.findPosV(range.anchor, dir, "line", range.anchor.goalColumn); + var newHead = cm.findPosV(range.head, dir, "line", range.head.goalColumn); + newAnchor.goalColumn = range.anchor.goalColumn != null ? range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left; + newHead.goalColumn = range.head.goalColumn != null ? range.head.goalColumn : cm.cursorCoords(range.head, "div").left; + var newRange = { + anchor: newAnchor, + head: newHead + }; + newRanges.push(range); + newRanges.push(newRange); + } + cm.setSelections(newRanges); } - const labelStart = state.pos + 2; - const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false); - - // parser failed to find ']', so it's not a valid link - if (labelEnd < 0) { + cmds.addCursorToPrevLine = function (cm) { + addCursorToSelection(cm, -1); + }; + cmds.addCursorToNextLine = function (cm) { + addCursorToSelection(cm, 1); + }; + function isSelectedRange(ranges, from, to) { + for (var i = 0; i < ranges.length; i++) if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 && CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true; return false; } - pos = labelEnd + 1; - if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { - // - // Inline link - // - - // [link]( "title" ) - // ^^ skipping these spaces - pos++; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var ranges = cm.listSelections(), + newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + pos = range.head, + opening = cm.scanForBracket(pos, -1); + if (!opening) return false; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return false; + if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { + var startPos = Pos(opening.pos.line, opening.pos.ch + 1); + if (CodeMirror.cmpPos(startPos, range.from()) == 0 && CodeMirror.cmpPos(closing.pos, range.to()) == 0) { + opening = cm.scanForBracket(opening.pos, -1); + if (!opening) return false; + } else { + newRanges.push({ + anchor: startPos, + head: closing.pos + }); + break; + } + } + pos = Pos(closing.pos.line, closing.pos.ch + 1); } } - if (pos >= max) { - return false; + cm.setSelections(newRanges); + return true; + } + cmds.selectScope = function (cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds.selectBetweenBrackets = function (cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + function puncType(type) { + return !type ? null : /\bpunctuation\b/.test(type) ? type : void 0; + } + cmds.goToBracket = function (cm) { + cm.extendSelectionsBy(function (range) { + var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head))); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; + var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)))); + return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; + }); + }; + cmds.swapLineUp = function (cm) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + linesToMove = [], + at = cm.firstLine() - 1, + newSels = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + from = range.from().line - 1, + to = range.to().line; + newSels.push({ + anchor: Pos(range.anchor.line - 1, range.anchor.ch), + head: Pos(range.head.line - 1, range.head.ch) + }); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function () { + for (var i2 = 0; i2 < linesToMove.length; i2 += 2) { + var from2 = linesToMove[i2], + to2 = linesToMove[i2 + 1]; + var line = cm.getLine(from2); + cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); + if (to2 > cm.lastLine()) cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");else cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); + } + cm.setSelections(newSels); + cm.scrollIntoView(); + }); + }; + cmds.swapLineDown = function (cm) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + linesToMove = [], + at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], + from = range.to().line + 1, + to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function () { + for (var i2 = linesToMove.length - 2; i2 >= 0; i2 -= 2) { + var from2 = linesToMove[i2], + to2 = linesToMove[i2 + 1]; + var line = cm.getLine(from2); + if (from2 == cm.lastLine()) cm.replaceRange("", Pos(from2 - 1), Pos(from2), "+swapLine");else cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); + cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + cmds.toggleCommentIndented = function (cm) { + cm.toggleComment({ + indent: true + }); + }; + cmds.joinLines = function (cm) { + var ranges = cm.listSelections(), + joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + from = range.from(); + var start = from.line, + end = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == end) end = ranges[++i].to().line; + joined.push({ + start, + end, + anchor: !range.empty() && from + }); } - - // [link]( "title" ) - // ^^^^^^ parsing link destination - start = pos; - res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); - if (res.ok) { - href = state.md.normalizeLink(res.str); - if (state.md.validateLink(href)) { - pos = res.pos; - } else { - href = ''; + cm.operation(function () { + var offset = 0, + ranges2 = []; + for (var i2 = 0; i2 < joined.length; i2++) { + var obj = joined[i2]; + var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), + head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); + if (actual < cm.lastLine()) { + cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); + ++offset; + } + } + ranges2.push({ + anchor: anchor || head, + head + }); } - } - - // [link]( "title" ) - // ^^ skipping these spaces - start = pos; - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { - break; + cm.setSelections(ranges2, 0); + }); + }; + cmds.duplicateLine = function (cm) { + cm.operation(function () { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));else cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + } + cm.scrollIntoView(); + }); + }; + function sortLines(cm, caseSensitive, direction) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + toSort = [], + selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, + to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) to = ranges[++i].to().line; + if (!ranges[i].to().ch) to--; + toSort.push(from, to); + } + if (toSort.length) selected = true;else toSort.push(cm.firstLine(), cm.lastLine()); + cm.operation(function () { + var ranges2 = []; + for (var i2 = 0; i2 < toSort.length; i2 += 2) { + var from2 = toSort[i2], + to2 = toSort[i2 + 1]; + var start = Pos(from2, 0), + end = Pos(to2); + var lines = cm.getRange(start, end, false); + if (caseSensitive) lines.sort(function (a, b) { + return a < b ? -direction : a == b ? 0 : direction; + });else lines.sort(function (a, b) { + var au = a.toUpperCase(), + bu = b.toUpperCase(); + if (au != bu) { + a = au; + b = bu; + } + return a < b ? -direction : a == b ? 0 : direction; + }); + cm.replaceRange(lines, start, end); + if (selected) ranges2.push({ + anchor: start, + head: Pos(to2 + 1, 0) + }); + } + if (selected) cm.setSelections(ranges2, 0); + }); + } + cmds.sortLines = function (cm) { + sortLines(cm, true, 1); + }; + cmds.reverseSortLines = function (cm) { + sortLines(cm, true, -1); + }; + cmds.sortLinesInsensitive = function (cm) { + sortLines(cm, false, 1); + }; + cmds.reverseSortLinesInsensitive = function (cm) { + sortLines(cm, false, -1); + }; + cmds.nextBookmark = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); } } - - // [link]( "title" ) - // ^^^^^^^ parsing link title - res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); - if (pos < max && start !== pos && res.ok) { - title = res.str; - pos = res.pos; - - // [link]( "title" ) - // ^^ skipping these spaces - for (; pos < max; pos++) { - code = state.src.charCodeAt(pos); - if (!isSpace(code) && code !== 0x0A) { + }; + cmds.prevBookmark = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) marks.pop();else return cm.setSelection(found.from, found.to); + } + }; + cmds.toggleBookmark = function (cm) { + var ranges = cm.listSelections(); + var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), + to = ranges[i].to(); + var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) if (marks[k] == found[j]) marks.splice(k--, 1); break; } } - } else { - title = ''; + if (j == found.length) marks.push(cm.markText(from, to, { + sublimeBookmark: true, + clearWhenEmpty: false + })); } - if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { - state.pos = oldPos; - return false; + }; + cmds.clearBookmarks = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); + marks.length = 0; + }; + cmds.selectBookmarks = function (cm) { + var marks = cm.state.sublimeBookmarks, + ranges = []; + if (marks) for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) marks.splice(i--, 0);else ranges.push({ + anchor: found.from, + head: found.to + }); } - pos++; - } else { - // - // Link reference - // - if (typeof state.env.references === 'undefined') { - return false; + if (ranges.length) cm.setSelections(ranges, 0); + }; + function modifyWordOrSelection(cm, mod) { + cm.operation(function () { + var ranges = cm.listSelections(), + indices = [], + replacements = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) { + indices.push(i); + replacements.push(""); + } else replacements.push(mod(cm.getRange(range.from(), range.to()))); + } + cm.replaceSelections(replacements, "around", "case"); + for (var i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); + } + cmds.smartBackspace = function (cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + cm.operation(function () { + var cursors = cm.listSelections(); + var indentUnit = cm.getOption("indentUnit"); + for (var i = cursors.length - 1; i >= 0; i--) { + var cursor = cursors[i].head; + var toStartOfLine = cm.getRange({ + line: cursor.line, + ch: 0 + }, cursor); + var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); + var deletePos = cm.findPosH(cursor, -1, "char", false); + if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { + var prevIndent = new Pos(cursor.line, CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); + if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + } + cm.replaceRange("", deletePos, cursor, "+delete"); + } + }); + }; + cmds.delLineRight = function (cm) { + cm.operation(function () { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); + cm.scrollIntoView(); + }); + }; + cmds.upcaseAtCursor = function (cm) { + modifyWordOrSelection(cm, function (str) { + return str.toUpperCase(); + }); + }; + cmds.downcaseAtCursor = function (cm) { + modifyWordOrSelection(cm, function (str) { + return str.toLowerCase(); + }); + }; + cmds.setSublimeMark = function (cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds.selectToSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds.deleteToSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + var from = cm.getCursor(), + to = found; + if (CodeMirror.cmpPos(from, to) > 0) { + var tmp = to; + to = from; + from = tmp; + } + cm.state.sublimeKilled = cm.getRange(from, to); + cm.replaceRange("", from, to); } - if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { - start = pos + 1; - pos = state.md.helpers.parseLinkLabel(state, pos); - if (pos >= 0) { - label = state.src.slice(start, pos++); - } else { - pos = labelEnd + 1; - } + }; + cmds.swapWithSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + cm.setCursor(found); + } + }; + cmds.sublimeYank = function (cm) { + if (cm.state.sublimeKilled != null) cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + cmds.showInCenter = function (cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + function getTarget(cm) { + var from = cm.getCursor("from"), + to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + from = word.from; + to = word.to; + } + return { + from, + to, + query: cm.getRange(from, to), + word + }; + } + function findAndGoTo(cm, forward) { + var target = getTarget(cm); + if (!target) return; + var query = target.query; + var cur = cm.getSearchCursor(query, forward ? target.to : target.from); + if (forward ? cur.findNext() : cur.findPrevious()) { + cm.setSelection(cur.from(), cur.to()); } else { - pos = labelEnd + 1; + cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) : cm.clipPos(Pos(cm.lastLine()))); + if (forward ? cur.findNext() : cur.findPrevious()) cm.setSelection(cur.from(), cur.to());else if (target.word) cm.setSelection(target.from, target.to); } - - // covers label === '' and label === undefined - // (collapsed reference link and shortcut reference link respectively) - if (!label) { - label = state.src.slice(labelStart, labelEnd); + } + cmds.findUnder = function (cm) { + findAndGoTo(cm, true); + }; + cmds.findUnderPrevious = function (cm) { + findAndGoTo(cm, false); + }; + cmds.findAllUnder = function (cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({ + anchor: cur.from(), + head: cur.to() + }); + if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) primaryIndex++; } - ref = state.env.references[normalizeReference(label)]; - if (!ref) { - state.pos = oldPos; - return false; + cm.setSelections(matches, primaryIndex); + }; + var keyMap = CodeMirror.keyMap; + keyMap.macSublime = { + "Cmd-Left": "goLineStartSmart", + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Ctrl-Alt-Up": "scrollLineUp", + "Ctrl-Alt-Down": "scrollLineDown", + "Cmd-L": "selectLine", + "Shift-Cmd-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Cmd-Enter": "insertLineAfter", + "Shift-Cmd-Enter": "insertLineBefore", + "Cmd-D": "selectNextOccurrence", + "Shift-Cmd-Space": "selectScope", + "Shift-Cmd-M": "selectBetweenBrackets", + "Cmd-M": "goToBracket", + "Cmd-Ctrl-Up": "swapLineUp", + "Cmd-Ctrl-Down": "swapLineDown", + "Cmd-/": "toggleCommentIndented", + "Cmd-J": "joinLines", + "Shift-Cmd-D": "duplicateLine", + "F5": "sortLines", + "Shift-F5": "reverseSortLines", + "Cmd-F5": "sortLinesInsensitive", + "Shift-Cmd-F5": "reverseSortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Cmd-F2": "toggleBookmark", + "Shift-Cmd-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", + "Cmd-K Cmd-K": "delLineRight", + "Cmd-K Cmd-U": "upcaseAtCursor", + "Cmd-K Cmd-L": "downcaseAtCursor", + "Cmd-K Cmd-Space": "setSublimeMark", + "Cmd-K Cmd-A": "selectToSublimeMark", + "Cmd-K Cmd-W": "deleteToSublimeMark", + "Cmd-K Cmd-X": "swapWithSublimeMark", + "Cmd-K Cmd-Y": "sublimeYank", + "Cmd-K Cmd-C": "showInCenter", + "Cmd-K Cmd-G": "clearBookmarks", + "Cmd-K Cmd-Backspace": "delLineLeft", + "Cmd-K Cmd-1": "foldAll", + "Cmd-K Cmd-0": "unfoldAll", + "Cmd-K Cmd-J": "unfoldAll", + "Ctrl-Shift-Up": "addCursorToPrevLine", + "Ctrl-Shift-Down": "addCursorToNextLine", + "Cmd-F3": "findUnder", + "Shift-Cmd-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Cmd-[": "fold", + "Shift-Cmd-]": "unfold", + "Cmd-I": "findIncremental", + "Shift-Cmd-I": "findIncrementalReverse", + "Cmd-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "macDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.macSublime); + keyMap.pcSublime = { + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-T": "transposeChars", + "Alt-Left": "goSubwordLeft", + "Alt-Right": "goSubwordRight", + "Ctrl-Up": "scrollLineUp", + "Ctrl-Down": "scrollLineDown", + "Ctrl-L": "selectLine", + "Shift-Ctrl-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Ctrl-Enter": "insertLineAfter", + "Shift-Ctrl-Enter": "insertLineBefore", + "Ctrl-D": "selectNextOccurrence", + "Shift-Ctrl-Space": "selectScope", + "Shift-Ctrl-M": "selectBetweenBrackets", + "Ctrl-M": "goToBracket", + "Shift-Ctrl-Up": "swapLineUp", + "Shift-Ctrl-Down": "swapLineDown", + "Ctrl-/": "toggleCommentIndented", + "Ctrl-J": "joinLines", + "Shift-Ctrl-D": "duplicateLine", + "F9": "sortLines", + "Shift-F9": "reverseSortLines", + "Ctrl-F9": "sortLinesInsensitive", + "Shift-Ctrl-F9": "reverseSortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Ctrl-F2": "toggleBookmark", + "Shift-Ctrl-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", + "Ctrl-K Ctrl-K": "delLineRight", + "Ctrl-K Ctrl-U": "upcaseAtCursor", + "Ctrl-K Ctrl-L": "downcaseAtCursor", + "Ctrl-K Ctrl-Space": "setSublimeMark", + "Ctrl-K Ctrl-A": "selectToSublimeMark", + "Ctrl-K Ctrl-W": "deleteToSublimeMark", + "Ctrl-K Ctrl-X": "swapWithSublimeMark", + "Ctrl-K Ctrl-Y": "sublimeYank", + "Ctrl-K Ctrl-C": "showInCenter", + "Ctrl-K Ctrl-G": "clearBookmarks", + "Ctrl-K Ctrl-Backspace": "delLineLeft", + "Ctrl-K Ctrl-1": "foldAll", + "Ctrl-K Ctrl-0": "unfoldAll", + "Ctrl-K Ctrl-J": "unfoldAll", + "Ctrl-Alt-Up": "addCursorToPrevLine", + "Ctrl-Alt-Down": "addCursorToNextLine", + "Ctrl-F3": "findUnder", + "Shift-Ctrl-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Ctrl-[": "fold", + "Shift-Ctrl-]": "unfold", + "Ctrl-I": "findIncremental", + "Shift-Ctrl-I": "findIncrementalReverse", + "Ctrl-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "pcDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.pcSublime); + var mac = keyMap.default == keyMap.macDefault; + keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; + }); +})(); +var sublimeExports = sublime$2.exports; +const sublime = /* @__PURE__ */codemirror.getDefaultExportFromCjs(sublimeExports); +const sublime$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: sublime +}, [sublimeExports]); +exports.sublime = sublime$1; + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/async-helpers/index.js": +/*!*********************************************************!*\ + !*** ../../graphiql-toolkit/esm/async-helpers/index.js ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.fetcherReturnToPromise = fetcherReturnToPromise; +exports.isAsyncIterable = isAsyncIterable; +exports.isObservable = isObservable; +exports.isPromise = isPromise; +var __awaiter = void 0 && (void 0).__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); } - href = ref.href; - title = ref.title; } - - // - // We found the end of the link, and know for a fact it's a valid link; - // so all that's left to do is to call tokenizer. - // - if (!silent) { - content = state.src.slice(labelStart, labelEnd); - const tokens = []; - state.md.inline.parse(content, state.md, state.env, tokens); - const token = state.push('image', 'img', 0); - const attrs = [['src', href], ['alt', '']]; - token.attrs = attrs; - token.children = tokens; - token.content = content; - if (title) { - attrs.push(['title', title]); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - state.pos = pos; - state.posMax = max; - return true; - } - - // Process autolinks '' - - /* eslint max-len:0 */ - const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; - /* eslint-disable-next-line no-control-regex */ - const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/; - function autolink(state, silent) { - let pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x3C /* < */) { - return false; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - const start = state.pos; - const max = state.posMax; - for (;;) { - if (++pos >= max) return false; - const ch = state.src.charCodeAt(pos); - if (ch === 0x3C /* < */) return false; - if (ch === 0x3E /* > */) break; + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +function isPromise(value) { + return typeof value === 'object' && value !== null && typeof value.then === 'function'; +} +function observableToPromise(observable) { + return new Promise((resolve, reject) => { + const subscription = observable.subscribe({ + next(v) { + resolve(v); + subscription.unsubscribe(); + }, + error: reject, + complete() { + reject(new Error('no value resolved')); + } + }); + }); +} +function isObservable(value) { + return typeof value === 'object' && value !== null && 'subscribe' in value && typeof value.subscribe === 'function'; +} +function isAsyncIterable(input) { + return typeof input === 'object' && input !== null && (input[Symbol.toStringTag] === 'AsyncGenerator' || Symbol.asyncIterator in input); +} +function asyncIterableToPromise(input) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const iteratorReturn = (_a = ('return' in input ? input : input[Symbol.asyncIterator]()).return) === null || _a === void 0 ? void 0 : _a.bind(input); + const iteratorNext = ('next' in input ? input : input[Symbol.asyncIterator]()).next.bind(input); + const result = yield iteratorNext(); + void (iteratorReturn === null || iteratorReturn === void 0 ? void 0 : iteratorReturn()); + return result.value; + }); +} +function fetcherReturnToPromise(fetcherResult) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield fetcherResult; + if (isAsyncIterable(result)) { + return asyncIterableToPromise(result); } - const url = state.src.slice(start + 1, pos); - if (AUTOLINK_RE.test(url)) { - const fullUrl = state.md.normalizeLink(url); - if (!state.md.validateLink(fullUrl)) { - return false; + if (isObservable(result)) { + return observableToPromise(result); + } + return result; + }); +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js": +/*!******************************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/createFetcher.js ***! + \******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createGraphiQLFetcher = createGraphiQLFetcher; +var _lib = __webpack_require__(/*! ./lib */ "../../graphiql-toolkit/esm/create-fetcher/lib.js"); +function createGraphiQLFetcher(options) { + let httpFetch; + if (typeof window !== 'undefined' && window.fetch) { + httpFetch = window.fetch; + } + if ((options === null || options === void 0 ? void 0 : options.enableIncrementalDelivery) === null || options.enableIncrementalDelivery !== false) { + options.enableIncrementalDelivery = true; + } + if (options.fetch) { + httpFetch = options.fetch; + } + if (!httpFetch) { + throw new Error('No valid fetcher implementation available'); + } + const simpleFetcher = (0, _lib.createSimpleFetcher)(options, httpFetch); + const httpFetcher = options.enableIncrementalDelivery ? (0, _lib.createMultipartFetcher)(options, httpFetch) : simpleFetcher; + return (graphQLParams, fetcherOpts) => { + if (graphQLParams.operationName === 'IntrospectionQuery') { + return (options.schemaFetcher || simpleFetcher)(graphQLParams, fetcherOpts); + } + const isSubscription = (fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.documentAST) ? (0, _lib.isSubscriptionWithName)(fetcherOpts.documentAST, graphQLParams.operationName || undefined) : false; + if (isSubscription) { + const wsFetcher = (0, _lib.getWsFetcher)(options, fetcherOpts); + if (!wsFetcher) { + throw new Error(`Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${options.subscriptionUrl ? `Provided URL ${options.subscriptionUrl} failed` : 'Please provide subscriptionUrl, wsClient or legacyClient option first.'}`); + } + return wsFetcher(graphQLParams); + } + return httpFetcher(graphQLParams, fetcherOpts); + }; +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/create-fetcher/index.js": +/*!**********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/index.js ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + createGraphiQLFetcher: true +}; +Object.defineProperty(exports, "createGraphiQLFetcher", ({ + enumerable: true, + get: function () { + return _createFetcher.createGraphiQLFetcher; + } +})); +var _types = __webpack_require__(/*! ./types */ "../../graphiql-toolkit/esm/create-fetcher/types.js"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); +}); +var _createFetcher = __webpack_require__(/*! ./createFetcher */ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js"); + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/create-fetcher/lib.js": +/*!********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/lib.js ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isSubscriptionWithName = exports.getWsFetcher = exports.createWebsocketsFetcherFromUrl = exports.createWebsocketsFetcherFromClient = exports.createSimpleFetcher = exports.createMultipartFetcher = exports.createLegacyWebsocketsFetcher = void 0; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _meros = __webpack_require__(/*! meros */ "../../../node_modules/meros/browser/index.js"); +var _pushPullAsyncIterableIterator = __webpack_require__(/*! @n1ru4l/push-pull-async-iterable-iterator */ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js"); +var __awaiter = void 0 && (void 0).__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); } - if (!silent) { - const token_o = state.push('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.markup = 'autolink'; - token_o.info = 'auto'; - const token_t = state.push('text', '', 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push('link_close', 'a', -1); - token_c.markup = 'autolink'; - token_c.info = 'auto'; - } - state.pos += url.length + 2; - return true; } - if (EMAIL_RE.test(url)) { - const fullUrl = state.md.normalizeLink('mailto:' + url); - if (!state.md.validateLink(fullUrl)) { - return false; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - if (!silent) { - const token_o = state.push('link_open', 'a', 1); - token_o.attrs = [['href', fullUrl]]; - token_o.markup = 'autolink'; - token_o.info = 'auto'; - const token_t = state.push('text', '', 0); - token_t.content = state.md.normalizeLinkText(url); - const token_c = state.push('link_close', 'a', -1); - token_c.markup = 'autolink'; - token_c.info = 'auto'; - } - state.pos += url.length + 2; - return true; } - return false; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __await = void 0 && (void 0).__await || function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +}; +var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; } - - // Process html tags - - function isLinkOpen(str) { - return /^\s]/i.test(str); + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } +}; +var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; } - function isLinkClose(str) { - return /^<\/a\s*>/i.test(str); + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } } - function isLetter(ch) { - /* eslint no-bitwise:0 */ - const lc = ch | 0x20; // to lower case - return lc >= 0x61 /* a */ && lc <= 0x7a /* z */; + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function html_inline(state, silent) { - if (!state.md.options.html) { - return false; - } - - // Check start - const max = state.posMax; - const pos = state.pos; - if (state.src.charCodeAt(pos) !== 0x3C /* < */ || pos + 2 >= max) { - return false; - } - - // Quick fail on second char - const ch = state.src.charCodeAt(pos + 1); - if (ch !== 0x21 /* ! */ && ch !== 0x3F /* ? */ && ch !== 0x2F /* / */ && !isLetter(ch)) { - return false; - } - const match = state.src.slice(pos).match(HTML_TAG_RE); - if (!match) { - return false; - } - if (!silent) { - const token = state.push('html_inline', '', 0); - token.content = match[0]; - if (isLinkOpen(token.content)) state.linkLevel++; - if (isLinkClose(token.content)) state.linkLevel--; - } - state.pos += match[0].length; - return true; + function fulfill(value) { + resume("next", value); } - - // Process html entity - {, ¯, ", ... - - const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; - const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; - function entity(state, silent) { - const pos = state.pos; - const max = state.posMax; - if (state.src.charCodeAt(pos) !== 0x26 /* & */) return false; - if (pos + 1 >= max) return false; - const ch = state.src.charCodeAt(pos + 1); - if (ch === 0x23 /* # */) { - const match = state.src.slice(pos).match(DIGITAL_RE); - if (match) { - if (!silent) { - const code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10); - const token = state.push('text_special', '', 0); - token.content = isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD); - token.markup = match[0]; - token.info = 'entity'; - } - state.pos += match[0].length; - return true; + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +}; +const errorHasCode = err => { + return typeof err === 'object' && err !== null && 'code' in err; +}; +const isSubscriptionWithName = (document, name) => { + let isSubscription = false; + (0, _graphql.visit)(document, { + OperationDefinition(node) { + var _a; + if (name === ((_a = node.name) === null || _a === void 0 ? void 0 : _a.value) && node.operation === 'subscription') { + isSubscription = true; } + } + }); + return isSubscription; +}; +exports.isSubscriptionWithName = isSubscriptionWithName; +const createSimpleFetcher = (options, httpFetch) => (graphQLParams, fetcherOpts) => __awaiter(void 0, void 0, void 0, function* () { + const data = yield httpFetch(options.url, { + method: 'POST', + body: JSON.stringify(graphQLParams), + headers: Object.assign(Object.assign({ + 'content-type': 'application/json' + }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) + }); + return data.json(); +}); +exports.createSimpleFetcher = createSimpleFetcher; +const createWebsocketsFetcherFromUrl = (url, connectionParams) => { + let wsClient; + try { + const { + createClient + } = __webpack_require__(/*! graphql-ws */ "../../../node_modules/graphql-ws/lib/index.js"); + wsClient = createClient({ + url, + connectionParams + }); + return createWebsocketsFetcherFromClient(wsClient); + } catch (err) { + if (errorHasCode(err) && err.code === 'MODULE_NOT_FOUND') { + throw new Error("You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'"); + } + console.error(`Error creating websocket client for ${url}`, err); + } +}; +exports.createWebsocketsFetcherFromUrl = createWebsocketsFetcherFromUrl; +const createWebsocketsFetcherFromClient = wsClient => graphQLParams => (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => wsClient.subscribe(graphQLParams, Object.assign(Object.assign({}, sink), { + error(err) { + if (err instanceof CloseEvent) { + sink.error(new Error(`Socket closed with event ${err.code} ${err.reason || ''}`.trim())); } else { - const match = state.src.slice(pos).match(NAMED_RE); - if (match) { - const decoded = entities.decodeHTML(match[0]); - if (decoded !== match[0]) { - if (!silent) { - const token = state.push('text_special', '', 0); - token.content = decoded; - token.markup = match[0]; - token.info = 'entity'; - } - state.pos += match[0].length; - return true; - } - } + sink.error(err); + } + } +}))); +exports.createWebsocketsFetcherFromClient = createWebsocketsFetcherFromClient; +const createLegacyWebsocketsFetcher = legacyWsClient => graphQLParams => { + const observable = legacyWsClient.request(graphQLParams); + return (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => observable.subscribe(sink).unsubscribe); +}; +exports.createLegacyWebsocketsFetcher = createLegacyWebsocketsFetcher; +const createMultipartFetcher = (options, httpFetch) => function (graphQLParams, fetcherOpts) { + return __asyncGenerator(this, arguments, function* () { + var e_1, _a; + const response = yield __await(httpFetch(options.url, { + method: 'POST', + body: JSON.stringify(graphQLParams), + headers: Object.assign(Object.assign({ + 'content-type': 'application/json', + accept: 'application/json, multipart/mixed' + }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) + }).then(r => (0, _meros.meros)(r, { + multiple: true + }))); + if (!(0, _pushPullAsyncIterableIterator.isAsyncIterable)(response)) { + return yield __await(yield yield __await(response.json())); } - return false; - } - - // For each opening emphasis-like marker find a matching closing one - // - - function processDelimiters(delimiters) { - const openersBottom = {}; - const max = delimiters.length; - if (!max) return; - - // headerIdx is the first delimiter of the current (where closer is) delimiter run - let headerIdx = 0; - let lastTokenIdx = -2; // needs any value lower than -1 - const jumps = []; - for (let closerIdx = 0; closerIdx < max; closerIdx++) { - const closer = delimiters[closerIdx]; - jumps.push(0); - - // markers belong to same delimiter run if: - // - they have adjacent tokens - // - AND markers are the same - // - if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) { - headerIdx = closerIdx; - } - lastTokenIdx = closer.token; - - // Length is only used for emphasis-specific "rule of 3", - // if it's not defined (in strikethrough or 3rd party plugins), - // we can default it to 0 to disable those checks. - // - closer.length = closer.length || 0; - if (!closer.close) continue; - - // Previously calculated lower bounds (previous fails) - // for each marker, each delimiter length modulo 3, - // and for whether this closer can be an opener; - // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 - /* eslint-disable-next-line no-prototype-builtins */ - if (!openersBottom.hasOwnProperty(closer.marker)) { - openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]; - } - const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3]; - let openerIdx = headerIdx - jumps[headerIdx] - 1; - let newMinOpenerIdx = openerIdx; - for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) { - const opener = delimiters[openerIdx]; - if (opener.marker !== closer.marker) continue; - if (opener.open && opener.end < 0) { - let isOddMatch = false; - - // from spec: - // - // If one of the delimiters can both open and close emphasis, then the - // sum of the lengths of the delimiter runs containing the opening and - // closing delimiters must not be a multiple of 3 unless both lengths - // are multiples of 3. - // - if (opener.close || closer.open) { - if ((opener.length + closer.length) % 3 === 0) { - if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { - isOddMatch = true; - } - } - } - if (!isOddMatch) { - // If previous delimiter cannot be an opener, we can safely skip - // the entire sequence in future checks. This is required to make - // sure algorithm has linear complexity (see *_*_*_*_*_... case). - // - const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0; - jumps[closerIdx] = closerIdx - openerIdx + lastJump; - jumps[openerIdx] = lastJump; - closer.open = false; - opener.end = closerIdx; - opener.close = false; - newMinOpenerIdx = -1; - // treat next token as start of run, - // it optimizes skips in **<...>**a**<...>** pathological case - lastTokenIdx = -2; - break; - } + try { + for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = yield __await(response_1.next()), !response_1_1.done;) { + const chunk = response_1_1.value; + if (chunk.some(part => !part.json)) { + const message = chunk.map(part => `Headers::\n${part.headers}\n\nBody::\n${part.body}`); + throw new Error(`Expected multipart chunks to be of json type. got:\n${message}`); } + yield yield __await(chunk.map(part => part.body)); } - if (newMinOpenerIdx !== -1) { - // If match for this delimiter run failed, we want to set lower bound for - // future lookups. This is required to make sure algorithm has linear - // complexity. - // - // See details here: - // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 - // - openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx; + } catch (e_1_1) { + e_1 = { + error: e_1_1 + }; + } finally { + try { + if (response_1_1 && !response_1_1.done && (_a = response_1.return)) yield __await(_a.call(response_1)); + } finally { + if (e_1) throw e_1.error; } } + }); +}; +exports.createMultipartFetcher = createMultipartFetcher; +const getWsFetcher = (options, fetcherOpts) => { + if (options.wsClient) { + return createWebsocketsFetcherFromClient(options.wsClient); } - function link_pairs(state) { - const tokens_meta = state.tokens_meta; - const max = state.tokens_meta.length; - processDelimiters(state.delimiters); - for (let curr = 0; curr < max; curr++) { - if (tokens_meta[curr] && tokens_meta[curr].delimiters) { - processDelimiters(tokens_meta[curr].delimiters); - } - } + if (options.subscriptionUrl) { + return createWebsocketsFetcherFromUrl(options.subscriptionUrl, Object.assign(Object.assign({}, options.wsConnectionParams), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers)); } - - // Clean up tokens after emphasis and strikethrough postprocessing: - // merge adjacent text nodes into one and re-calculate all token levels - // - // This is necessary because initially emphasis delimiter markers (*, _, ~) - // are treated as their own separate text tokens. Then emphasis rule either - // leaves them as text (needed to merge with adjacent text) or turns them - // into opening/closing tags (which messes up levels inside). - // - - function fragments_join(state) { - let curr, last; - let level = 0; - const tokens = state.tokens; - const max = state.tokens.length; - for (curr = last = 0; curr < max; curr++) { - // re-calculate levels after emphasis/strikethrough turns some text nodes - // into opening/closing tags - if (tokens[curr].nesting < 0) level--; // closing tag - tokens[curr].level = level; - if (tokens[curr].nesting > 0) level++; // opening tag - - if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { - // collapse two adjacent text nodes - tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; - } else { - if (curr !== last) { - tokens[last] = tokens[curr]; + const legacyWebsocketsClient = options.legacyClient || options.legacyWsClient; + if (legacyWebsocketsClient) { + return createLegacyWebsocketsFetcher(legacyWebsocketsClient); + } +}; +exports.getWsFetcher = getWsFetcher; + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/create-fetcher/types.js": +/*!**********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/types.js ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/format/index.js": +/*!**************************************************!*\ + !*** ../../graphiql-toolkit/esm/format/index.js ***! + \**************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.formatError = formatError; +exports.formatResult = formatResult; +function stringify(obj) { + return JSON.stringify(obj, null, 2); +} +function formatSingleError(error) { + return Object.assign(Object.assign({}, error), { + message: error.message, + stack: error.stack + }); +} +function handleSingleError(error) { + if (error instanceof Error) { + return formatSingleError(error); + } + return error; +} +function formatError(error) { + if (Array.isArray(error)) { + return stringify({ + errors: error.map(e => handleSingleError(e)) + }); + } + return stringify({ + errors: [handleSingleError(error)] + }); +} +function formatResult(result) { + return stringify(result); +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js": +/*!*******************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js ***! + \*******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.fillLeafs = fillLeafs; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function fillLeafs(schema, docString, getDefaultFieldNames) { + const insertions = []; + if (!schema || !docString) { + return { + insertions, + result: docString + }; + } + let ast; + try { + ast = (0, _graphql.parse)(docString); + } catch (_a) { + return { + insertions, + result: docString + }; + } + const fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames; + const typeInfo = new _graphql.TypeInfo(schema); + (0, _graphql.visit)(ast, { + leave(node) { + typeInfo.leave(node); + }, + enter(node) { + typeInfo.enter(node); + if (node.kind === 'Field' && !node.selectionSet) { + const fieldType = typeInfo.getType(); + const selectionSet = buildSelectionSet(isFieldType(fieldType), fieldNameFn); + if (selectionSet && node.loc) { + const indent = getIndentation(docString, node.loc.start); + insertions.push({ + index: node.loc.end, + string: ' ' + (0, _graphql.print)(selectionSet).replaceAll('\n', '\n' + indent) + }); } - last++; } } - if (curr !== last) { - tokens.length = last; + }); + return { + insertions, + result: withInsertions(docString, insertions) + }; +} +function defaultGetDefaultFieldNames(type) { + if (!('getFields' in type)) { + return []; + } + const fields = type.getFields(); + if (fields.id) { + return ['id']; + } + if (fields.edges) { + return ['edges']; + } + if (fields.node) { + return ['node']; + } + const leafFieldNames = []; + for (const fieldName of Object.keys(fields)) { + if ((0, _graphql.isLeafType)(fields[fieldName].type)) { + leafFieldNames.push(fieldName); } } - - /** internal - * class ParserInline - * - * Tokenizes paragraph content. - **/ - - // Parser rules - - const _rules = [['text', text], ['linkify', linkify], ['newline', newline], ['escape', escape], ['backticks', backtick], ['strikethrough', r_strikethrough.tokenize], ['emphasis', r_emphasis.tokenize], ['link', link], ['image', image], ['autolink', autolink], ['html_inline', html_inline], ['entity', entity]]; - - // `rule2` ruleset was created specifically for emphasis/strikethrough - // post-processing and may be changed in the future. - // - // Don't use this for anything except pairs (plugins working with `balance_pairs`). - // - const _rules2 = [['balance_pairs', link_pairs], ['strikethrough', r_strikethrough.postProcess], ['emphasis', r_emphasis.postProcess], - // rules for pairs separate '**' into its own text tokens, which may be left unused, - // rule below merges unused segments back with the rest of the text - ['fragments_join', fragments_join]]; - - /** - * new ParserInline() - **/ - function ParserInline() { - /** - * ParserInline#ruler -> Ruler - * - * [[Ruler]] instance. Keep configuration of inline rules. - **/ - this.ruler = new Ruler(); - for (let i = 0; i < _rules.length; i++) { - this.ruler.push(_rules[i][0], _rules[i][1]); + return leafFieldNames; +} +function buildSelectionSet(type, getDefaultFieldNames) { + const namedType = (0, _graphql.getNamedType)(type); + if (!type || (0, _graphql.isLeafType)(type)) { + return; + } + const fieldNames = getDefaultFieldNames(namedType); + if (!Array.isArray(fieldNames) || fieldNames.length === 0 || !('getFields' in namedType)) { + return; + } + return { + kind: _graphql.Kind.SELECTION_SET, + selections: fieldNames.map(fieldName => { + const fieldDef = namedType.getFields()[fieldName]; + const fieldType = fieldDef ? fieldDef.type : null; + return { + kind: _graphql.Kind.FIELD, + name: { + kind: _graphql.Kind.NAME, + value: fieldName + }, + selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames) + }; + }) + }; +} +function withInsertions(initial, insertions) { + if (insertions.length === 0) { + return initial; + } + let edited = ''; + let prevIndex = 0; + for (const { + index, + string + } of insertions) { + edited += initial.slice(prevIndex, index) + string; + prevIndex = index; + } + edited += initial.slice(prevIndex); + return edited; +} +function getIndentation(str, index) { + let indentStart = index; + let indentEnd = index; + while (indentStart) { + const c = str.charCodeAt(indentStart - 1); + if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { + break; } - - /** - * ParserInline#ruler2 -> Ruler - * - * [[Ruler]] instance. Second ruler used for post-processing - * (e.g. in emphasis-like rules). - **/ - this.ruler2 = new Ruler(); - for (let i = 0; i < _rules2.length; i++) { - this.ruler2.push(_rules2[i][0], _rules2[i][1]); + indentStart--; + if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { + indentEnd = indentStart; } } - - // Skip single token by running all rules in validation mode; - // returns `true` if any rule reported success - // - ParserInline.prototype.skipToken = function (state) { - const pos = state.pos; - const rules = this.ruler.getRules(''); - const len = rules.length; - const maxNesting = state.md.options.maxNesting; - const cache = state.cache; - if (typeof cache[pos] !== 'undefined') { - state.pos = cache[pos]; - return; + return str.slice(indentStart, indentEnd); +} +function isFieldType(fieldType) { + if (fieldType) { + return fieldType; + } +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/graphql-helpers/index.js": +/*!***********************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/index.js ***! + \***********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _autoComplete = __webpack_require__(/*! ./auto-complete */ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js"); +Object.keys(_autoComplete).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _autoComplete[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _autoComplete[key]; } - let ok = false; - if (state.level < maxNesting) { - for (let i = 0; i < len; i++) { - // Increment state.level and decrement it later to limit recursion. - // It's harmless to do here, because no tokens are created. But ideally, - // we'd need a separate private state variable for this purpose. - // - state.level++; - ok = rules[i](state, true); - state.level--; - if (ok) { - if (pos >= state.pos) { - throw new Error("inline rule didn't increment state.pos"); - } - break; - } + }); +}); +var _mergeAst = __webpack_require__(/*! ./merge-ast */ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js"); +Object.keys(_mergeAst).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _mergeAst[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _mergeAst[key]; + } + }); +}); +var _operationName = __webpack_require__(/*! ./operation-name */ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js"); +Object.keys(_operationName).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _operationName[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _operationName[key]; + } + }); +}); + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js": +/*!***************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js ***! + \***************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.mergeAst = mergeAst; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function uniqueBy(array, iteratee) { + var _a; + const FilteredMap = new Map(); + const result = []; + for (const item of array) { + if (item.kind === 'Field') { + const uniqueValue = iteratee(item); + const existing = FilteredMap.get(uniqueValue); + if ((_a = item.directives) === null || _a === void 0 ? void 0 : _a.length) { + const itemClone = Object.assign({}, item); + result.push(itemClone); + } else if ((existing === null || existing === void 0 ? void 0 : existing.selectionSet) && item.selectionSet) { + existing.selectionSet.selections = [...existing.selectionSet.selections, ...item.selectionSet.selections]; + } else if (!existing) { + const itemClone = Object.assign({}, item); + FilteredMap.set(uniqueValue, itemClone); + result.push(itemClone); } } else { - // Too much nesting, just skip until the end of the paragraph. - // - // NOTE: this will cause links to behave incorrectly in the following case, - // when an amount of `[` is exactly equal to `maxNesting + 1`: - // - // [[[[[[[[[[[[[[[[[[[[[foo]() - // - // TODO: remove this workaround when CM standard will allow nested links - // (we can replace it by preventing links from being parsed in - // validation mode) - // - state.pos = state.posMax; - } - if (!ok) { - state.pos++; + result.push(item); } - cache[pos] = state.pos; - }; - - // Generate tokens for input range - // - ParserInline.prototype.tokenize = function (state) { - const rules = this.ruler.getRules(''); - const len = rules.length; - const end = state.posMax; - const maxNesting = state.md.options.maxNesting; - while (state.pos < end) { - // Try all possible rules. - // On success, rule should: - // - // - update `state.pos` - // - update `state.tokens` - // - return true - const prevPos = state.pos; - let ok = false; - if (state.level < maxNesting) { - for (let i = 0; i < len; i++) { - ok = rules[i](state, false); - if (ok) { - if (prevPos >= state.pos) { - throw new Error("inline rule didn't increment state.pos"); - } - break; - } + } + return result; +} +function inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType) { + var _a; + const selectionSetTypeName = selectionSetType ? (0, _graphql.getNamedType)(selectionSetType).name : null; + const outputSelections = []; + const seenSpreads = []; + for (let selection of selections) { + if (selection.kind === 'FragmentSpread') { + const fragmentName = selection.name.value; + if (!selection.directives || selection.directives.length === 0) { + if (seenSpreads.includes(fragmentName)) { + continue; + } else { + seenSpreads.push(fragmentName); } } - if (ok) { - if (state.pos >= end) { - break; - } - continue; + const fragmentDefinition = fragmentDefinitions[selection.name.value]; + if (fragmentDefinition) { + const { + typeCondition, + directives, + selectionSet + } = fragmentDefinition; + selection = { + kind: _graphql.Kind.INLINE_FRAGMENT, + typeCondition, + directives, + selectionSet + }; } - state.pending += state.src[state.pos++]; - } - if (state.pending) { - state.pushPending(); } - }; - - /** - * ParserInline.parse(str, md, env, outTokens) - * - * Process input string and push inline tokens into `outTokens` - **/ - ParserInline.prototype.parse = function (str, md, env, outTokens) { - const state = new this.State(str, md, env, outTokens); - this.tokenize(state); - const rules = this.ruler2.getRules(''); - const len = rules.length; - for (let i = 0; i < len; i++) { - rules[i](state); + if (selection.kind === _graphql.Kind.INLINE_FRAGMENT && (!selection.directives || ((_a = selection.directives) === null || _a === void 0 ? void 0 : _a.length) === 0)) { + const fragmentTypeName = selection.typeCondition ? selection.typeCondition.name.value : null; + if (!fragmentTypeName || fragmentTypeName === selectionSetTypeName) { + outputSelections.push(...inlineRelevantFragmentSpreads(fragmentDefinitions, selection.selectionSet.selections, selectionSetType)); + continue; + } } - }; - ParserInline.prototype.State = StateInline; - - // markdown-it default options - - var cfg_default = { - options: { - // Enable HTML tags in source - html: false, - // Use '/' to close single tags (
    ) - xhtmlOut: false, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: 'language-', - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: '\u201c\u201d\u2018\u2019', - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with ) - xhtmlOut: false, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: 'language-', - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: '\u201c\u201d\u2018\u2019', - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with ) - xhtmlOut: true, - // Convert '\n' in paragraphs into
    - breaks: false, - // CSS language prefix for fenced blocks - langPrefix: 'language-', - // autoconvert URL-like texts to links - linkify: false, - // Enable some language-neutral replacements + quotes beautification - typographer: false, - // Double + single quotes replacement pairs, when typographer enabled, - // and smartquotes on. Could be either a String or an Array. - // - // For example, you can use '«»„“' for Russian, '„“‚‘' for German, - // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). - quotes: '\u201c\u201d\u2018\u2019', - /* “”‘’ */ - - // Highlighter function. Should return escaped HTML, - // or '' if the source string is not changed and should be escaped externaly. - // If result starts with selection.alias ? selection.alias.value : selection.name.value); + return Object.assign(Object.assign({}, node), { + selections + }); }, - components: { - core: { - rules: ['normalize', 'block', 'inline', 'text_join'] - }, - block: { - rules: ['blockquote', 'code', 'fence', 'heading', 'hr', 'html_block', 'lheading', 'list', 'reference', 'paragraph'] - }, - inline: { - rules: ['autolink', 'backticks', 'emphasis', 'entity', 'escape', 'html_inline', 'image', 'link', 'newline', 'text'], - rules2: ['balance_pairs', 'emphasis', 'fragments_join'] - } + FragmentDefinition() { + return null; } }; - - // Main parser class - - const config = { - default: cfg_default, - zero: cfg_zero, - commonmark: cfg_commonmark - }; - - // - // This validator can prohibit more than really needed to prevent XSS. It's a - // tradeoff to keep code simple and to be secure by default. - // - // If you need different setup - override validator method as you wish. Or - // replace it with dummy function and use external sanitizer. - // - - const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/; - const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/; - function validateLink(url) { - // url should be normalized at this point, and existing entities are decoded - const str = url.trim().toLowerCase(); - return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true; - } - const RECODE_HOSTNAME_FOR = ['http:', 'https:', 'mailto:']; - function normalizeLink(url) { - const parsed = mdurl__namespace.parse(url, true); - if (parsed.hostname) { - // Encode hostnames in urls like: - // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` - // - // We don't encode unknown schemas, because it's likely that we encode - // something we shouldn't (e.g. `skype:name` treated as `skype:host`) - // - if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { - try { - parsed.hostname = punycode.toASCII(parsed.hostname); - } catch (er) {/**/} - } - } - return mdurl__namespace.encode(mdurl__namespace.format(parsed)); + return (0, _graphql.visit)(flattenedAST, deduplicateVisitors); +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js": +/*!********************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/operation-name.js ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getSelectedOperationName = getSelectedOperationName; +function getSelectedOperationName(prevOperations, prevSelectedOperationName, operations) { + if (!operations || operations.length < 1) { + return; } - function normalizeLinkText(url) { - const parsed = mdurl__namespace.parse(url, true); - if (parsed.hostname) { - // Encode hostnames in urls like: - // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` - // - // We don't encode unknown schemas, because it's likely that we encode - // something we shouldn't (e.g. `skype:name` treated as `skype:host`) - // - if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { - try { - parsed.hostname = punycode.toUnicode(parsed.hostname); - } catch (er) {/**/} - } + const names = operations.map(op => { + var _a; + return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; + }); + if (prevSelectedOperationName && names.includes(prevSelectedOperationName)) { + return prevSelectedOperationName; + } + if (prevSelectedOperationName && prevOperations) { + const prevNames = prevOperations.map(op => { + var _a; + return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; + }); + const prevIndex = prevNames.indexOf(prevSelectedOperationName); + if (prevIndex !== -1 && prevIndex < names.length) { + return names[prevIndex]; } - - // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 - return mdurl__namespace.decode(mdurl__namespace.format(parsed), mdurl__namespace.decode.defaultChars + '%'); } - - /** - * class MarkdownIt - * - * Main parser/renderer class. - * - * ##### Usage - * - * ```javascript - * // node.js, "classic" way: - * var MarkdownIt = require('markdown-it'), - * md = new MarkdownIt(); - * var result = md.render('# markdown-it rulezz!'); - * - * // node.js, the same, but with sugar: - * var md = require('markdown-it')(); - * var result = md.render('# markdown-it rulezz!'); - * - * // browser without AMD, added to "window" on script load - * // Note, there are no dash. - * var md = window.markdownit(); - * var result = md.render('# markdown-it rulezz!'); - * ``` - * - * Single line rendering, without paragraph wrap: - * - * ```javascript - * var md = require('markdown-it')(); - * var result = md.renderInline('__markdown-it__ rulezz!'); - * ``` - **/ - - /** - * new MarkdownIt([presetName, options]) - * - presetName (String): optional, `commonmark` / `zero` - * - options (Object) - * - * Creates parser instanse with given config. Can be called without `new`. - * - * ##### presetName - * - * MarkdownIt provides named presets as a convenience to quickly - * enable/disable active syntax rules and options for common use cases. - * - * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.mjs) - - * configures parser to strict [CommonMark](http://commonmark.org/) mode. - * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.mjs) - - * similar to GFM, used when no preset name given. Enables all available rules, - * but still without html, typographer & autolinker. - * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.mjs) - - * all rules disabled. Useful to quickly setup your config via `.enable()`. - * For example, when you need only `bold` and `italic` markup and nothing else. - * - * ##### options: - * - * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! - * That's not safe! You may need external sanitizer to protect output from XSS. - * It's better to extend features via plugins, instead of enabling HTML. - * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags - * (`
    `). This is needed only for full CommonMark compatibility. In real - * world you will need HTML output. - * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
    `. - * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. - * Can be useful for external highlighters. - * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. - * - __typographer__ - `false`. Set `true` to enable [some language-neutral - * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs) + - * quotes beautification (smartquotes). - * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement - * pairs, when typographer enabled and smartquotes on. For example, you can - * use `'«»„“'` for Russian, `'„“‚‘'` for German, and - * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). - * - __highlight__ - `null`. Highlighter function for fenced code blocks. - * Highlighter `function (str, lang)` should return escaped HTML. It can also - * return empty string if the source was not changed and should be escaped - * externaly. If result starts with ` or ``): - * - * ```javascript - * var hljs = require('highlight.js') // https://highlightjs.org/ - * - * // Actual default values - * var md = require('markdown-it')({ - * highlight: function (str, lang) { - * if (lang && hljs.getLanguage(lang)) { - * try { - * return '
    ' +
    -   *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
    -   *                '
    '; - * } catch (__) {} - * } - * - * return '
    ' + md.utils.escapeHtml(str) + '
    '; - * } - * }); - * ``` - * - **/ - function MarkdownIt(presetName, options) { - if (!(this instanceof MarkdownIt)) { - return new MarkdownIt(presetName, options); + return names[0]; +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/index.js": +/*!*******************************************!*\ + !*** ../../graphiql-toolkit/esm/index.js ***! + \*******************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _asyncHelpers = __webpack_require__(/*! ./async-helpers */ "../../graphiql-toolkit/esm/async-helpers/index.js"); +Object.keys(_asyncHelpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _asyncHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _asyncHelpers[key]; } - if (!options) { - if (!isString(presetName)) { - options = presetName || {}; - presetName = 'default'; - } + }); +}); +var _createFetcher = __webpack_require__(/*! ./create-fetcher */ "../../graphiql-toolkit/esm/create-fetcher/index.js"); +Object.keys(_createFetcher).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _createFetcher[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _createFetcher[key]; } - - /** - * MarkdownIt#inline -> ParserInline - * - * Instance of [[ParserInline]]. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.inline = new ParserInline(); - - /** - * MarkdownIt#block -> ParserBlock - * - * Instance of [[ParserBlock]]. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.block = new ParserBlock(); - - /** - * MarkdownIt#core -> Core - * - * Instance of [[Core]] chain executor. You may need it to add new rules when - * writing plugins. For simple rules control use [[MarkdownIt.disable]] and - * [[MarkdownIt.enable]]. - **/ - this.core = new Core(); - - /** - * MarkdownIt#renderer -> Renderer - * - * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering - * rules for new token types, generated by plugins. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')(); - * - * function myToken(tokens, idx, options, env, self) { - * //... - * return result; - * }; - * - * md.renderer.rules['my_token'] = myToken - * ``` - * - * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs). - **/ - this.renderer = new Renderer(); - - /** - * MarkdownIt#linkify -> LinkifyIt - * - * [linkify-it](https://github.com/markdown-it/linkify-it) instance. - * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs) - * rule. - **/ - this.linkify = new LinkifyIt(); - - /** - * MarkdownIt#validateLink(url) -> Boolean - * - * Link validation function. CommonMark allows too much in links. By default - * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas - * except some embedded image types. - * - * You can change this behaviour: - * - * ```javascript - * var md = require('markdown-it')(); - * // enable everything - * md.validateLink = function () { return true; } - * ``` - **/ - this.validateLink = validateLink; - - /** - * MarkdownIt#normalizeLink(url) -> String - * - * Function used to encode link url to a machine-readable format, - * which includes url-encoding, punycode, etc. - **/ - this.normalizeLink = normalizeLink; - - /** - * MarkdownIt#normalizeLinkText(url) -> String - * - * Function used to decode link url to a human-readable format` - **/ - this.normalizeLinkText = normalizeLinkText; - - // Expose utils & helpers for easy acces from plugins - - /** - * MarkdownIt#utils -> utils - * - * Assorted utility functions, useful to write plugins. See details - * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs). - **/ - this.utils = utils; - - /** - * MarkdownIt#helpers -> helpers - * - * Link components parser functions, useful to write plugins. See details - * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). - **/ - this.helpers = assign({}, helpers); - this.options = {}; - this.configure(presetName); - if (options) { - this.set(options); + }); +}); +var _format = __webpack_require__(/*! ./format */ "../../graphiql-toolkit/esm/format/index.js"); +Object.keys(_format).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _format[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _format[key]; + } + }); +}); +var _graphqlHelpers = __webpack_require__(/*! ./graphql-helpers */ "../../graphiql-toolkit/esm/graphql-helpers/index.js"); +Object.keys(_graphqlHelpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _graphqlHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _graphqlHelpers[key]; + } + }); +}); +var _storage = __webpack_require__(/*! ./storage */ "../../graphiql-toolkit/esm/storage/index.js"); +Object.keys(_storage).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _storage[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _storage[key]; + } + }); +}); + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/storage/base.js": +/*!**************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/base.js ***! + \**************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.StorageAPI = void 0; +function isQuotaError(storage, e) { + return e instanceof DOMException && (e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && storage.length !== 0; +} +class StorageAPI { + constructor(storage) { + if (storage) { + this.storage = storage; + } else if (storage === null) { + this.storage = null; + } else if (typeof window === 'undefined') { + this.storage = null; + } else { + this.storage = { + getItem: localStorage.getItem.bind(localStorage), + setItem: localStorage.setItem.bind(localStorage), + removeItem: localStorage.removeItem.bind(localStorage), + get length() { + let keys = 0; + for (const key in localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + keys += 1; + } + } + return keys; + }, + clear() { + for (const key in localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + localStorage.removeItem(key); + } + } + } + }; } } - - /** chainable - * MarkdownIt.set(options) - * - * Set parser options (in the same format as in constructor). Probably, you - * will never need it, but you can change options after constructor call. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')() - * .set({ html: true, breaks: true }) - * .set({ typographer, true }); - * ``` - * - * __Note:__ To achieve the best possible performance, don't modify a - * `markdown-it` instance options on the fly. If you need multiple configurations - * it's best to create multiple instances and initialize each with separate - * config. - **/ - MarkdownIt.prototype.set = function (options) { - assign(this.options, options); - return this; - }; - - /** chainable, internal - * MarkdownIt.configure(presets) - * - * Batch load of all options and compenent settings. This is internal method, - * and you probably will not need it. But if you will - see available presets - * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) - * - * We strongly recommend to use presets instead of direct config loads. That - * will give better compatibility with next versions. - **/ - MarkdownIt.prototype.configure = function (presets) { - const self = this; - if (isString(presets)) { - const presetName = presets; - presets = config[presetName]; - if (!presets) { - throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name'); - } + get(name) { + if (!this.storage) { + return null; } - if (!presets) { - throw new Error('Wrong `markdown-it` preset, can\'t be empty'); + const key = `${STORAGE_NAMESPACE}:${name}`; + const value = this.storage.getItem(key); + if (value === 'null' || value === 'undefined') { + this.storage.removeItem(key); + return null; + } + return value || null; + } + set(name, value) { + let quotaError = false; + let error = null; + if (this.storage) { + const key = `${STORAGE_NAMESPACE}:${name}`; + if (value) { + try { + this.storage.setItem(key, value); + } catch (e) { + error = e instanceof Error ? e : new Error(`${e}`); + quotaError = isQuotaError(this.storage, e); + } + } else { + this.storage.removeItem(key); + } } - if (presets.options) { - self.set(presets.options); + return { + isQuotaError: quotaError, + error + }; + } + clear() { + if (this.storage) { + this.storage.clear(); } - if (presets.components) { - Object.keys(presets.components).forEach(function (name) { - if (presets.components[name].rules) { - self[name].ruler.enableOnly(presets.components[name].rules); + } +} +exports.StorageAPI = StorageAPI; +const STORAGE_NAMESPACE = 'graphiql'; + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/storage/custom.js": +/*!****************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/custom.js ***! + \****************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createLocalStorage = createLocalStorage; +function createLocalStorage({ + namespace +}) { + const storageKeyPrefix = `${namespace}:`; + const getStorageKey = key => `${storageKeyPrefix}${key}`; + const storage = { + setItem: (key, value) => localStorage.setItem(getStorageKey(key), value), + getItem: key => localStorage.getItem(getStorageKey(key)), + removeItem: key => localStorage.removeItem(getStorageKey(key)), + get length() { + let keys = 0; + for (const key in localStorage) { + if (key.indexOf(storageKeyPrefix) === 0) { + keys += 1; } - if (presets.components[name].rules2) { - self[name].ruler2.enableOnly(presets.components[name].rules2); + } + return keys; + }, + clear() { + for (const key in localStorage) { + if (key.indexOf(storageKeyPrefix) === 0) { + localStorage.removeItem(key); } - }); - } - return this; - }; - - /** chainable - * MarkdownIt.enable(list, ignoreInvalid) - * - list (String|Array): rule name or list of rule names to enable - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * Enable list or rules. It will automatically find appropriate components, - * containing rules with given names. If rule not found, and `ignoreInvalid` - * not set - throws exception. - * - * ##### Example - * - * ```javascript - * var md = require('markdown-it')() - * .enable(['sub', 'sup']) - * .disable('smartquotes'); - * ``` - **/ - MarkdownIt.prototype.enable = function (list, ignoreInvalid) { - let result = []; - if (!Array.isArray(list)) { - list = [list]; - } - ['core', 'block', 'inline'].forEach(function (chain) { - result = result.concat(this[chain].ruler.enable(list, true)); - }, this); - result = result.concat(this.inline.ruler2.enable(list, true)); - const missed = list.filter(function (name) { - return result.indexOf(name) < 0; - }); - if (missed.length && !ignoreInvalid) { - throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed); + } } - return this; }; - - /** chainable - * MarkdownIt.disable(list, ignoreInvalid) - * - list (String|Array): rule name or list of rule names to disable. - * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. - * - * The same as [[MarkdownIt.enable]], but turn specified rules off. - **/ - MarkdownIt.prototype.disable = function (list, ignoreInvalid) { - let result = []; - if (!Array.isArray(list)) { - list = [list]; - } - ['core', 'block', 'inline'].forEach(function (chain) { - result = result.concat(this[chain].ruler.disable(list, true)); - }, this); - result = result.concat(this.inline.ruler2.disable(list, true)); - const missed = list.filter(function (name) { - return result.indexOf(name) < 0; - }); - if (missed.length && !ignoreInvalid) { - throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed); + return storage; +} + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/storage/history.js": +/*!*****************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/history.js ***! + \*****************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.HistoryStore = void 0; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); +const MAX_QUERY_SIZE = 100000; +class HistoryStore { + constructor(storage, maxHistoryLength) { + this.storage = storage; + this.maxHistoryLength = maxHistoryLength; + this.updateHistory = ({ + query, + variables, + headers, + operationName + }) => { + if (!this.shouldSaveQuery(query, variables, headers, this.history.fetchRecent())) { + return; + } + this.history.push({ + query, + variables, + headers, + operationName + }); + const historyQueries = this.history.items; + const favoriteQueries = this.favorite.items; + this.queries = historyQueries.concat(favoriteQueries); + }; + this.deleteHistory = ({ + query, + variables, + headers, + operationName, + favorite + }, clearFavorites = false) => { + function deleteFromStore(store) { + const found = store.items.find(x => x.query === query && x.variables === variables && x.headers === headers && x.operationName === operationName); + if (found) { + store.delete(found); + } + } + if (favorite || clearFavorites) { + deleteFromStore(this.favorite); + } + if (!favorite || clearFavorites) { + deleteFromStore(this.history); + } + this.queries = [...this.history.items, ...this.favorite.items]; + }; + this.history = new _query.QueryStore('queries', this.storage, this.maxHistoryLength); + this.favorite = new _query.QueryStore('favorites', this.storage, null); + this.queries = [...this.history.fetchAll(), ...this.favorite.fetchAll()]; + } + shouldSaveQuery(query, variables, headers, lastQuerySaved) { + if (!query) { + return false; } - return this; - }; - - /** chainable - * MarkdownIt.use(plugin, params) - * - * Load specified plugin with given params into current parser instance. - * It's just a sugar to call `plugin(md, params)` with curring. - * - * ##### Example - * - * ```javascript - * var iterator = require('markdown-it-for-inline'); - * var md = require('markdown-it')() - * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { - * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); - * }); - * ``` - **/ - MarkdownIt.prototype.use = function (plugin /*, params, ... */) { - const args = [this].concat(Array.prototype.slice.call(arguments, 1)); - plugin.apply(plugin, args); - return this; - }; - - /** internal - * MarkdownIt.parse(src, env) -> Array - * - src (String): source string - * - env (Object): environment sandbox - * - * Parse input string and return list of block tokens (special token type - * "inline" will contain list of inline tokens). You should not call this - * method directly, until you write custom renderer (for example, to produce - * AST). - * - * `env` is used to pass data between "distributed" rules and return additional - * metadata like reference info, needed for the renderer. It also can be used to - * inject data in specific cases. Usually, you will be ok to pass `{}`, - * and then pass updated object to renderer. - **/ - MarkdownIt.prototype.parse = function (src, env) { - if (typeof src !== 'string') { - throw new Error('Input data should be a String'); + try { + (0, _graphql.parse)(query); + } catch (_a) { + return false; } - const state = new this.core.State(src, this, env); - this.core.process(state); - return state.tokens; - }; - - /** - * MarkdownIt.render(src [, env]) -> String - * - src (String): source string - * - env (Object): environment sandbox - * - * Render markdown string into html. It does all magic for you :). - * - * `env` can be used to inject additional metadata (`{}` by default). - * But you will not need it with high probability. See also comment - * in [[MarkdownIt.parse]]. - **/ - MarkdownIt.prototype.render = function (src, env) { - env = env || {}; - return this.renderer.render(this.parse(src, env), this.options, env); - }; - - /** internal - * MarkdownIt.parseInline(src, env) -> Array - * - src (String): source string - * - env (Object): environment sandbox - * - * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the - * block tokens list with the single `inline` element, containing parsed inline - * tokens in `children` property. Also updates `env` object. - **/ - MarkdownIt.prototype.parseInline = function (src, env) { - const state = new this.core.State(src, this, env); - state.inlineMode = true; - this.core.process(state); - return state.tokens; - }; - - /** - * MarkdownIt.renderInline(src [, env]) -> String - * - src (String): source string - * - env (Object): environment sandbox - * - * Similar to [[MarkdownIt.render]] but for single paragraph content. Result - * will NOT be wrapped into `

    ` tags. - **/ - MarkdownIt.prototype.renderInline = function (src, env) { - env = env || {}; - return this.renderer.render(this.parseInline(src, env), this.options, env); - }; - module.exports = MarkdownIt; - - /***/ }), - - /***/ "../node_modules/mdurl/build/index.cjs.js": - /*!************************************************!*\ - !*** ../node_modules/mdurl/build/index.cjs.js ***! - \************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - /* eslint-disable no-bitwise */ - const decodeCache = {}; - function getDecodeCache(exclude) { - let cache = decodeCache[exclude]; - if (cache) { - return cache; - } - cache = decodeCache[exclude] = []; - for (let i = 0; i < 128; i++) { - const ch = String.fromCharCode(i); - cache.push(ch); + if (query.length > MAX_QUERY_SIZE) { + return false; } - for (let i = 0; i < exclude.length; i++) { - const ch = exclude.charCodeAt(i); - cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2); + if (!lastQuerySaved) { + return true; } - return cache; - } - - // Decode percent-encoded string. - // - function decode(string, exclude) { - if (typeof exclude !== 'string') { - exclude = decode.defaultChars; - } - const cache = getDecodeCache(exclude); - return string.replace(/(%[a-f0-9]{2})+/gi, function (seq) { - let result = ''; - for (let i = 0, l = seq.length; i < l; i += 3) { - const b1 = parseInt(seq.slice(i + 1, i + 3), 16); - if (b1 < 0x80) { - result += cache[b1]; - continue; - } - if ((b1 & 0xE0) === 0xC0 && i + 3 < l) { - // 110xxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - if ((b2 & 0xC0) === 0x80) { - const chr = b1 << 6 & 0x7C0 | b2 & 0x3F; - if (chr < 0x80) { - result += '\ufffd\ufffd'; - } else { - result += String.fromCharCode(chr); - } - i += 3; - continue; - } - } - if ((b1 & 0xF0) === 0xE0 && i + 6 < l) { - // 1110xxxx 10xxxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - const b3 = parseInt(seq.slice(i + 7, i + 9), 16); - if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { - const chr = b1 << 12 & 0xF000 | b2 << 6 & 0xFC0 | b3 & 0x3F; - if (chr < 0x800 || chr >= 0xD800 && chr <= 0xDFFF) { - result += '\ufffd\ufffd\ufffd'; - } else { - result += String.fromCharCode(chr); - } - i += 6; - continue; - } + if (JSON.stringify(query) === JSON.stringify(lastQuerySaved.query)) { + if (JSON.stringify(variables) === JSON.stringify(lastQuerySaved.variables)) { + if (JSON.stringify(headers) === JSON.stringify(lastQuerySaved.headers)) { + return false; } - if ((b1 & 0xF8) === 0xF0 && i + 9 < l) { - // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - const b3 = parseInt(seq.slice(i + 7, i + 9), 16); - const b4 = parseInt(seq.slice(i + 10, i + 12), 16); - if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) { - let chr = b1 << 18 & 0x1C0000 | b2 << 12 & 0x3F000 | b3 << 6 & 0xFC0 | b4 & 0x3F; - if (chr < 0x10000 || chr > 0x10FFFF) { - result += '\ufffd\ufffd\ufffd\ufffd'; - } else { - chr -= 0x10000; - result += String.fromCharCode(0xD800 + (chr >> 10), 0xDC00 + (chr & 0x3FF)); - } - i += 9; - continue; - } + if (headers && !lastQuerySaved.headers) { + return false; } - result += '\ufffd'; } - return result; - }); + if (variables && !lastQuerySaved.variables) { + return false; + } + } + return true; } - decode.defaultChars = ';/?:@&=+$,#'; - decode.componentChars = ''; - const encodeCache = {}; - - // Create a lookup array where anything but characters in `chars` string - // and alphanumeric chars is percent-encoded. - // - function getEncodeCache(exclude) { - let cache = encodeCache[exclude]; - if (cache) { - return cache; - } - cache = encodeCache[exclude] = []; - for (let i = 0; i < 128; i++) { - const ch = String.fromCharCode(i); - if (/^[0-9a-z]$/i.test(ch)) { - // always allow unencoded alphanumeric characters - cache.push(ch); - } else { - cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2)); + toggleFavorite({ + query, + variables, + headers, + operationName, + label, + favorite + }) { + const item = { + query, + variables, + headers, + operationName, + label + }; + if (favorite) { + item.favorite = false; + this.favorite.delete(item); + this.history.push(item); + } else { + item.favorite = true; + this.favorite.push(item); + this.history.delete(item); + } + this.queries = [...this.history.items, ...this.favorite.items]; + } + editLabel({ + query, + variables, + headers, + operationName, + label, + favorite + }, index) { + const item = { + query, + variables, + headers, + operationName, + label + }; + if (favorite) { + this.favorite.edit(Object.assign(Object.assign({}, item), { + favorite + }), index); + } else { + this.history.edit(item, index); + } + this.queries = [...this.history.items, ...this.favorite.items]; + } +} +exports.HistoryStore = HistoryStore; + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/storage/index.js": +/*!***************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/index.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _base = __webpack_require__(/*! ./base */ "../../graphiql-toolkit/esm/storage/base.js"); +Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _base[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _base[key]; + } + }); +}); +var _history = __webpack_require__(/*! ./history */ "../../graphiql-toolkit/esm/storage/history.js"); +Object.keys(_history).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _history[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _history[key]; + } + }); +}); +var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); +Object.keys(_query).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _query[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _query[key]; + } + }); +}); +var _custom = __webpack_require__(/*! ./custom */ "../../graphiql-toolkit/esm/storage/custom.js"); +Object.keys(_custom).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _custom[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _custom[key]; + } + }); +}); + +/***/ }), + +/***/ "../../graphiql-toolkit/esm/storage/query.js": +/*!***************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/query.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.QueryStore = void 0; +class QueryStore { + constructor(key, storage, maxSize = null) { + this.key = key; + this.storage = storage; + this.maxSize = maxSize; + this.items = this.fetchAll(); + } + get length() { + return this.items.length; + } + contains(item) { + return this.items.some(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); + } + edit(item, index) { + if (typeof index === 'number' && this.items[index]) { + const found = this.items[index]; + if (found.query === item.query && found.variables === item.variables && found.headers === item.headers && found.operationName === item.operationName) { + this.items.splice(index, 1, item); + this.save(); + return; } } - for (let i = 0; i < exclude.length; i++) { - cache[exclude.charCodeAt(i)] = exclude[i]; + const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); + if (itemIndex !== -1) { + this.items.splice(itemIndex, 1, item); + this.save(); } - return cache; } - - // Encode unsafe characters with percent-encoding, skipping already - // encoded sequences. + delete(item) { + const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); + if (itemIndex !== -1) { + this.items.splice(itemIndex, 1); + this.save(); + } + } + fetchRecent() { + return this.items.at(-1); + } + fetchAll() { + const raw = this.storage.get(this.key); + if (raw) { + return JSON.parse(raw)[this.key]; + } + return []; + } + push(item) { + const items = [...this.items, item]; + if (this.maxSize && items.length > this.maxSize) { + items.shift(); + } + for (let attempts = 0; attempts < 5; attempts++) { + const response = this.storage.set(this.key, JSON.stringify({ + [this.key]: items + })); + if (!(response === null || response === void 0 ? void 0 : response.error)) { + this.items = items; + } else if (response.isQuotaError && this.maxSize) { + items.shift(); + } else { + return; + } + } + } + save() { + this.storage.set(this.key, JSON.stringify({ + [this.key]: this.items + })); + } +} +exports.QueryStore = QueryStore; + +/***/ }), + +/***/ "../node_modules/linkify-it/build/index.cjs.js": +/*!*****************************************************!*\ + !*** ../node_modules/linkify-it/build/index.cjs.js ***! + \*****************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + +var uc_micro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); +function reFactory(opts) { + const re = {}; + opts = opts || {}; + re.src_Any = uc_micro.Any.source; + re.src_Cc = uc_micro.Cc.source; + re.src_Z = uc_micro.Z.source; + re.src_P = uc_micro.P.source; + + // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) + re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join('|'); + + // \p{\Z\Cc} (white spaces + control) + re.src_ZCc = [re.src_Z, re.src_Cc].join('|'); + + // Experimental. List of chars, completely prohibited in links + // because can separate it from other part of text + const text_separators = '[><\uff5c]'; + + // All possible word characters (everything without punctuation, spaces & controls) + // Defined via punctuation & spaces to save space + // Should be something like \p{\L\N\S\M} (\w but without `_`) + re.src_pseudo_letter = '(?:(?!' + text_separators + '|' + re.src_ZPCc + ')' + re.src_Any + ')'; + // The same as abothe but without [0-9] + // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; + + re.src_ip4 = '(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'; + + // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. + re.src_auth = '(?:(?:(?!' + re.src_ZCc + '|[@/\\[\\]()]).)+@)?'; + re.src_port = '(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?'; + re.src_host_terminator = '(?=$|' + text_separators + '|' + re.src_ZPCc + ')' + '(?!' + (opts['---'] ? '-(?!--)|' : '-|') + '_|:\\d|\\.-|\\.(?!$|' + re.src_ZPCc + '))'; + re.src_path = '(?:' + '[/?#]' + '(?:' + '(?!' + re.src_ZCc + '|' + text_separators + '|[()[\\]{}.,"\'?!\\-;]).|' + '\\[(?:(?!' + re.src_ZCc + '|\\]).)*\\]|' + '\\((?:(?!' + re.src_ZCc + '|[)]).)*\\)|' + '\\{(?:(?!' + re.src_ZCc + '|[}]).)*\\}|' + '\\"(?:(?!' + re.src_ZCc + '|["]).)+\\"|' + "\\'(?:(?!" + re.src_ZCc + "|[']).)+\\'|" + + // allow `I'm_king` if no pair found + "\\'(?=" + re.src_pseudo_letter + '|[-])|' + + // google has many dots in "google search" links (#66, #81). + // github has ... in commit range links, + // Restrict to + // - english + // - percent-encoded + // - parts of file path + // - params separator + // until more examples found. + '\\.{2,}[a-zA-Z0-9%/&]|' + '\\.(?!' + re.src_ZCc + '|[.]|$)|' + (opts['---'] ? '\\-(?!--(?:[^-]|$))(?:-*)|' // `---` => long dash, terminate + : '\\-+|') + + // allow `,,,` in paths + ',(?!' + re.src_ZCc + '|$)|' + + // allow `;` if not followed by space-like char + ';(?!' + re.src_ZCc + '|$)|' + + // allow `!!!` in paths, but not at the end + '\\!+(?!' + re.src_ZCc + '|[!]|$)|' + '\\?(?!' + re.src_ZCc + '|[?]|$)' + ')+' + '|\\/' + ')?'; + + // Allow anything in markdown spec, forbid quote (") at the first position + // because emails enclosed in quotes are far more common + re.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; + re.src_xn = 'xn--[a-z0-9\\-]{1,59}'; + + // More to read about domain names + // http://serverfault.com/questions/638260/ + + re.src_domain_root = + // Allow letters & digits (http://test1) + '(?:' + re.src_xn + '|' + re.src_pseudo_letter + '{1,63}' + ')'; + re.src_domain = '(?:' + re.src_xn + '|' + '(?:' + re.src_pseudo_letter + ')' + '|' + '(?:' + re.src_pseudo_letter + '(?:-|' + re.src_pseudo_letter + '){0,61}' + re.src_pseudo_letter + ')' + ')'; + re.src_host = '(?:' + + // Don't need IP check, because digits are already allowed in normal domain names + // src_ip4 + + // '|' + + '(?:(?:(?:' + re.src_domain + ')\\.)*' + re.src_domain /* _root */ + ')' + ')'; + re.tpl_host_fuzzy = '(?:' + re.src_ip4 + '|' + '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))' + ')'; + re.tpl_host_no_ip_fuzzy = '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))'; + re.src_host_strict = re.src_host + re.src_host_terminator; + re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; + re.src_host_port_strict = re.src_host + re.src_port + re.src_host_terminator; + re.tpl_host_port_fuzzy_strict = re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; + re.tpl_host_port_no_ip_fuzzy_strict = re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; + // - // - string - string to encode - // - exclude - list of characters to ignore (in addition to a-zA-Z0-9) - // - keepEscaped - don't encode '%' in a correct escape sequence (default: true) + // Main rules // - function encode(string, exclude, keepEscaped) { - if (typeof exclude !== 'string') { - // encode(string, keepEscaped) - keepEscaped = exclude; - exclude = encode.defaultChars; - } - if (typeof keepEscaped === 'undefined') { - keepEscaped = true; + + // Rude test fuzzy links by host, for quick deny + re.tpl_host_fuzzy_test = 'localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:' + re.src_ZPCc + '|>|$))'; + re.tpl_email_fuzzy = '(^|' + text_separators + '|"|\\(|' + re.src_ZCc + ')' + '(' + re.src_email_name + '@' + re.tpl_host_fuzzy_strict + ')'; + re.tpl_link_fuzzy = + // Fuzzy link can't be prepended with .:/\- and non punctuation. + // but can start with > (markdown blockquote) + '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_fuzzy_strict + re.src_path + ')'; + re.tpl_link_no_ip_fuzzy = + // Fuzzy link can't be prepended with .:/\- and non punctuation. + // but can start with > (markdown blockquote) + '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_no_ip_fuzzy_strict + re.src_path + ')'; + return re; +} + +// +// Helpers +// + +// Merge objects +// +function assign(obj /* from1, from2, from3, ... */) { + const sources = Array.prototype.slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) { + return; } - const cache = getEncodeCache(exclude); - let result = ''; - for (let i = 0, l = string.length; i < l; i++) { - const code = string.charCodeAt(i); - if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { - if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { - result += string.slice(i, i + 3); - i += 2; - continue; - } + Object.keys(source).forEach(function (key) { + obj[key] = source[key]; + }); + }); + return obj; +} +function _class(obj) { + return Object.prototype.toString.call(obj); +} +function isString(obj) { + return _class(obj) === '[object String]'; +} +function isObject(obj) { + return _class(obj) === '[object Object]'; +} +function isRegExp(obj) { + return _class(obj) === '[object RegExp]'; +} +function isFunction(obj) { + return _class(obj) === '[object Function]'; +} +function escapeRE(str) { + return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); +} + +// + +const defaultOptions = { + fuzzyLink: true, + fuzzyEmail: true, + fuzzyIP: false +}; +function isOptionsObj(obj) { + return Object.keys(obj || {}).reduce(function (acc, k) { + /* eslint-disable-next-line no-prototype-builtins */ + return acc || defaultOptions.hasOwnProperty(k); + }, false); +} +const defaultSchemas = { + 'http:': { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.http) { + // compile lazily, because "host"-containing variables can change on tlds update. + self.re.http = new RegExp('^\\/\\/' + self.re.src_auth + self.re.src_host_port_strict + self.re.src_path, 'i'); } - if (code < 128) { - result += cache[code]; - continue; + if (self.re.http.test(tail)) { + return tail.match(self.re.http)[0].length; } - if (code >= 0xD800 && code <= 0xDFFF) { - if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) { - const nextCode = string.charCodeAt(i + 1); - if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) { - result += encodeURIComponent(string[i] + string[i + 1]); - i++; - continue; - } + return 0; + } + }, + 'https:': 'http:', + 'ftp:': 'http:', + '//': { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.no_http) { + // compile lazily, because "host"-containing variables can change on tlds update. + self.re.no_http = new RegExp('^' + self.re.src_auth + + // Don't allow single-level domains, because of false positives like '//test' + // with code comments + '(?:localhost|(?:(?:' + self.re.src_domain + ')\\.)+' + self.re.src_domain_root + ')' + self.re.src_port + self.re.src_host_terminator + self.re.src_path, 'i'); + } + if (self.re.no_http.test(tail)) { + // should not be `://` & `///`, that protects from errors in protocol name + if (pos >= 3 && text[pos - 3] === ':') { + return 0; } - result += '%EF%BF%BD'; - continue; + if (pos >= 3 && text[pos - 3] === '/') { + return 0; + } + return tail.match(self.re.no_http)[0].length; } - result += encodeURIComponent(string[i]); + return 0; } - return result; - } - encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; - encode.componentChars = "-_.!~*'()"; - function format(url) { - let result = ''; - result += url.protocol || ''; - result += url.slashes ? '//' : ''; - result += url.auth ? url.auth + '@' : ''; - if (url.hostname && url.hostname.indexOf(':') !== -1) { - // ipv6 address - result += '[' + url.hostname + ']'; - } else { - result += url.hostname || ''; + }, + 'mailto:': { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.mailto) { + self.re.mailto = new RegExp('^' + self.re.src_email_name + '@' + self.re.src_host_strict, 'i'); + } + if (self.re.mailto.test(tail)) { + return tail.match(self.re.mailto)[0].length; + } + return 0; } - result += url.port ? ':' + url.port : ''; - result += url.pathname || ''; - result += url.search || ''; - result += url.hash || ''; - return result; } - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - // - // Changes from joyent/node: - // - // 1. No leading slash in paths, - // e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` - // - // 2. Backslashes are not replaced with slashes, - // so `http:\\example.org\` is treated like a relative path - // - // 3. Trailing colon is treated like a part of the path, - // i.e. in `http://example.org:foo` pathname is `:foo` - // - // 4. Nothing is URL-encoded in the resulting object, - // (in joyent/node some chars in auth and paths are encoded) - // - // 5. `url.parse()` does not have `parseQueryString` argument +}; + +// RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) +/* eslint-disable-next-line max-len */ +const tlds_2ch_src_re = 'a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]'; + +// DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead +const tlds_default = 'biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф'.split('|'); +function resetScanCache(self) { + self.__index__ = -1; + self.__text_cache__ = ''; +} +function createValidator(re) { + return function (text, pos) { + const tail = text.slice(pos); + if (re.test(tail)) { + return tail.match(re)[0].length; + } + return 0; + }; +} +function createNormalizer() { + return function (match, self) { + self.normalize(match); + }; +} + +// Schemas compiler. Build regexps. +// +function compile(self) { + // Load & clone RE patterns. + const re = self.re = reFactory(self.__opts__); + + // Define dynamic patterns + const tlds = self.__tlds__.slice(); + self.onCompile(); + if (!self.__tlds_replaced__) { + tlds.push(tlds_2ch_src_re); + } + tlds.push(re.src_xn); + re.src_tlds = tlds.join('|'); + function untpl(tpl) { + return tpl.replace('%TLDS%', re.src_tlds); + } + re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i'); + re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i'); + re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i'); + re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i'); + // - // 6. Removed extraneous result properties: `host`, `path`, `query`, etc., - // which can be constructed using other parts of the url. + // Compile each schema // - - function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; + + const aliases = []; + self.__compiled__ = {}; // Reset compiled data + + function schemaError(name, val) { + throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val); } - - // Reference: RFC 3986, RFC 1808, RFC 2396 - - // define these here so at least they only have to be - // compiled once on the first module load. - const protocolPattern = /^([a-z0-9.+-]+:)/i; - const portPattern = /:[0-9]*$/; - - // Special case for a simple path URL - /* eslint-disable-next-line no-useless-escape */ - const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - const delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t']; - - // RFC 2396: characters not allowed for various reasons. - const unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims); - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - const autoEscape = ['\''].concat(unwise); - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - const nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape); - const hostEndingChars = ['/', '?', '#']; - const hostnameMaxLen = 255; - const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; - const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; - // protocols that can allow "unsafe" and "unwise" chars. - // protocols that never have a hostname. - const hostlessProtocol = { - javascript: true, - 'javascript:': true - }; - // protocols that always contain a // bit. - const slashedProtocol = { - http: true, - https: true, - ftp: true, - gopher: true, - file: true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }; - function urlParse(url, slashesDenoteHost) { - if (url && url instanceof Url) return url; - const u = new Url(); - u.parse(url, slashesDenoteHost); - return u; - } - Url.prototype.parse = function (url, slashesDenoteHost) { - let lowerProto, hec, slashes; - let rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - const simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - } - return this; - } - } - let proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - lowerProto = proto.toLowerCase(); - this.protocol = proto; - rest = rest.substr(proto.length); + Object.keys(self.__schemas__).forEach(function (name) { + const val = self.__schemas__[name]; + + // skip disabled methods + if (val === null) { + return; } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - /* eslint-disable-next-line no-useless-escape */ - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) { - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - let hostEnd = -1; - for (let i = 0; i < hostEndingChars.length; i++) { - hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { - hostEnd = hec; - } - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - let auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); + const compiled = { + validate: null, + link: null + }; + self.__compiled__[name] = compiled; + if (isObject(val)) { + if (isRegExp(val.validate)) { + compiled.validate = createValidator(val.validate); + } else if (isFunction(val.validate)) { + compiled.validate = val.validate; } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = auth; - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (let i = 0; i < nonHostChars.length; i++) { - hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { - hostEnd = hec; - } - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) { - hostEnd = rest.length; - } - if (rest[hostEnd - 1] === ':') { - hostEnd--; - } - const host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(host); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - const ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - const hostparts = this.hostname.split(/\./); - for (let i = 0, l = hostparts.length; i < l; i++) { - const part = hostparts[i]; - if (!part) { - continue; - } - if (!part.match(hostnamePartPattern)) { - let newpart = ''; - for (let j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - const validParts = hostparts.slice(0, i); - const notHost = hostparts.slice(i + 1); - const bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; + schemaError(name, val); } - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (isFunction(val.normalize)) { + compiled.normalize = val.normalize; + } else if (!val.normalize) { + compiled.normalize = createNormalizer(); + } else { + schemaError(name, val); } + return; } - - // chop off from the tail first. - const hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - const qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - rest = rest.slice(0, qm); - } - if (rest) { - this.pathname = rest; - } - if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { - this.pathname = ''; - } - return this; - }; - Url.prototype.parseHost = function (host) { - let port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); + if (isString(val)) { + aliases.push(name); + return; } - if (host) { - this.hostname = host; + schemaError(name, val); + }); + + // + // Compile postponed aliases + // + + aliases.forEach(function (alias) { + if (!self.__compiled__[self.__schemas__[alias]]) { + // Silently fail on missed schemas to avoid errons on disable. + // schemaError(alias, self.__schemas__[alias]); + return; } + self.__compiled__[alias].validate = self.__compiled__[self.__schemas__[alias]].validate; + self.__compiled__[alias].normalize = self.__compiled__[self.__schemas__[alias]].normalize; + }); + + // + // Fake record for guessed links + // + self.__compiled__[''] = { + validate: null, + normalize: createNormalizer() }; - exports.decode = decode; - exports.encode = encode; - exports.format = format; - exports.parse = urlParse; - - /***/ }), - - /***/ "../node_modules/uc.micro/build/index.cjs.js": - /*!***************************************************!*\ - !*** ../node_modules/uc.micro/build/index.cjs.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - var regex$5 = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - var regex$4 = /[\0-\x1F\x7F-\x9F]/; - var regex$3 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/; - var regex$2 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/; - var regex$1 = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/; - var regex = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; - exports.Any = regex$5; - exports.Cc = regex$4; - exports.Cf = regex$3; - exports.P = regex$2; - exports.S = regex$1; - exports.Z = regex; - - /***/ }), - - /***/ "./components/GraphiQL.tsx": - /*!*********************************!*\ - !*** ./components/GraphiQL.tsx ***! - \*********************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.GraphiQL = GraphiQL; - exports.GraphiQLInterface = GraphiQLInterface; - var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); - var _react2 = __webpack_require__(/*! @graphiql/react */ "../../graphiql-react/dist/index.js"); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** - * Copyright (c) 2020 GraphQL Contributors. + + // + // Build schema condition + // + const slist = Object.keys(self.__compiled__).filter(function (name) { + // Filter disabled & fake schemas + return name.length > 0 && self.__compiled__[name]; + }).map(escapeRE).join('|'); + // (?!_) cause 1.5x slowdown + self.re.schema_test = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i'); + self.re.schema_search = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig'); + self.re.schema_at_start = RegExp('^' + self.re.schema_search.source, 'i'); + self.re.pretest = RegExp('(' + self.re.schema_test.source + ')|(' + self.re.host_fuzzy_test.source + ')|@', 'i'); + + // + // Cleanup + // + + resetScanCache(self); +} + +/** + * class Match + * + * Match result. Single element of array, returned by [[LinkifyIt#match]] + **/ +function Match(self, shift) { + const start = self.__index__; + const end = self.__last_index__; + const text = self.__text_cache__.slice(start, end); + + /** + * Match#schema -> String * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - const majorVersion = parseInt(_react.default.version.slice(0, 2), 10); - if (majorVersion < 16) { - throw new Error(['GraphiQL 0.18.0 and after is not compatible with React 15 or below.', 'If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:', 'https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49'].join('\n')); - } - + * Prefix (protocol) for matched string. + **/ + this.schema = self.__schema__.toLowerCase(); /** - * API docs for this live here: + * Match#index -> Number * - * https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops - */ - + * First position of matched string. + **/ + this.index = start + shift; /** - * The top-level React component for GraphiQL, intended to encompass the entire - * browser viewport. + * Match#lastIndex -> Number * - * @see https://github.com/graphql/graphiql#usage - */ - - function GraphiQL({ - dangerouslyAssumeSchemaIsValid, - defaultQuery, - defaultTabs, - externalFragments, - fetcher, - getDefaultFieldNames, - headers, - inputValueDeprecation, - introspectionQueryName, - maxHistoryLength, - onEditOperationName, - onSchemaChange, - onTabChange, - onTogglePluginVisibility, - operationName, - plugins, - query, - response, - schema, - schemaDescription, - shouldPersistHeaders, - storage, - validationRules, - variables, - visiblePlugin, - defaultHeaders, - ...props - }) { - var _props$disableTabs; - // Ensure props are correct - if (typeof fetcher !== 'function') { - throw new TypeError('The `GraphiQL` component requires a `fetcher` function to be passed as prop.'); - } - return /*#__PURE__*/_react.default.createElement(_react2.GraphiQLProvider, { - getDefaultFieldNames: getDefaultFieldNames, - dangerouslyAssumeSchemaIsValid: dangerouslyAssumeSchemaIsValid, - defaultQuery: defaultQuery, - defaultHeaders: defaultHeaders, - defaultTabs: defaultTabs, - externalFragments: externalFragments, - fetcher: fetcher, - headers: headers, - inputValueDeprecation: inputValueDeprecation, - introspectionQueryName: introspectionQueryName, - maxHistoryLength: maxHistoryLength, - onEditOperationName: onEditOperationName, - onSchemaChange: onSchemaChange, - onTabChange: onTabChange, - onTogglePluginVisibility: onTogglePluginVisibility, - plugins: plugins, - visiblePlugin: visiblePlugin, - operationName: operationName, - query: query, - response: response, - schema: schema, - schemaDescription: schemaDescription, - shouldPersistHeaders: shouldPersistHeaders, - storage: storage, - validationRules: validationRules, - variables: variables - }, /*#__PURE__*/_react.default.createElement(GraphiQLInterface, _extends({ - showPersistHeadersSettings: shouldPersistHeaders !== false, - disableTabs: (_props$disableTabs = props.disableTabs) !== null && _props$disableTabs !== void 0 ? _props$disableTabs : false, - forcedTheme: props.forcedTheme - }, props))); - } - - // Export main windows/panes to be used separately if desired. - GraphiQL.Logo = GraphiQLLogo; - GraphiQL.Toolbar = GraphiQLToolbar; - GraphiQL.Footer = GraphiQLFooter; - const THEMES = ['light', 'dark', 'system']; - function GraphiQLInterface(props) { - var _props$isHeadersEdito, _pluginContext$visibl, _props$toolbar, _props$toolbar2; - const isHeadersEditorEnabled = (_props$isHeadersEdito = props.isHeadersEditorEnabled) !== null && _props$isHeadersEdito !== void 0 ? _props$isHeadersEdito : true; - const editorContext = (0, _react2.useEditorContext)({ - nonNull: true - }); - const executionContext = (0, _react2.useExecutionContext)({ - nonNull: true - }); - const schemaContext = (0, _react2.useSchemaContext)({ - nonNull: true - }); - const storageContext = (0, _react2.useStorageContext)(); - const pluginContext = (0, _react2.usePluginContext)(); - const forcedTheme = (0, _react.useMemo)(() => props.forcedTheme && THEMES.includes(props.forcedTheme) ? props.forcedTheme : undefined, [props.forcedTheme]); - const copy = (0, _react2.useCopyQuery)({ - onCopyQuery: props.onCopyQuery - }); - const merge = (0, _react2.useMergeQuery)(); - const prettify = (0, _react2.usePrettifyEditors)(); - const { - theme, - setTheme - } = (0, _react2.useTheme)(); - (0, _react.useEffect)(() => { - if (forcedTheme === 'system') { - setTheme(null); - } else if (forcedTheme === 'light' || forcedTheme === 'dark') { - setTheme(forcedTheme); - } - }, [forcedTheme, setTheme]); - const PluginContent = pluginContext === null || pluginContext === void 0 ? void 0 : (_pluginContext$visibl = pluginContext.visiblePlugin) === null || _pluginContext$visibl === void 0 ? void 0 : _pluginContext$visibl.content; - const pluginResize = (0, _react2.useDragResize)({ - defaultSizeRelation: 1 / 3, - direction: 'horizontal', - initiallyHidden: pluginContext !== null && pluginContext !== void 0 && pluginContext.visiblePlugin ? undefined : 'first', - onHiddenElementChange(resizableElement) { - if (resizableElement === 'first') { - pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.setVisiblePlugin(null); - } - }, - sizeThresholdSecond: 200, - storageKey: 'docExplorerFlex' - }); - const editorResize = (0, _react2.useDragResize)({ - direction: 'horizontal', - storageKey: 'editorFlex' - }); - const editorToolsResize = (0, _react2.useDragResize)({ - defaultSizeRelation: 3, - direction: 'vertical', - initiallyHidden: (() => { - if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { - return; - } - if (typeof props.defaultEditorToolsVisibility === 'boolean') { - return props.defaultEditorToolsVisibility ? undefined : 'second'; - } - return editorContext.initialVariables || editorContext.initialHeaders ? undefined : 'second'; - })(), - sizeThresholdSecond: 60, - storageKey: 'secondaryEditorFlex' - }); - const [activeSecondaryEditor, setActiveSecondaryEditor] = (0, _react.useState)(() => { - if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { - return props.defaultEditorToolsVisibility; - } - return !editorContext.initialVariables && editorContext.initialHeaders && isHeadersEditorEnabled ? 'headers' : 'variables'; - }); - const [showDialog, setShowDialog] = (0, _react.useState)(null); - const [clearStorageStatus, setClearStorageStatus] = (0, _react.useState)(null); - const children = _react.default.Children.toArray(props.children); - const logo = children.find(child => isChildComponentType(child, GraphiQL.Logo)) || /*#__PURE__*/_react.default.createElement(GraphiQL.Logo, null); - const toolbar = children.find(child => isChildComponentType(child, GraphiQL.Toolbar)) || /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { - onClick: prettify, - label: "Prettify query (Shift-Ctrl-P)" - }, /*#__PURE__*/_react.default.createElement(_react2.PrettifyIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true" - })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { - onClick: merge, - label: "Merge fragments into query (Shift-Ctrl-M)" - }, /*#__PURE__*/_react.default.createElement(_react2.MergeIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true" - })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { - onClick: copy, - label: "Copy query (Shift-Ctrl-C)" - }, /*#__PURE__*/_react.default.createElement(_react2.CopyIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true" - })), (_props$toolbar = props.toolbar) === null || _props$toolbar === void 0 ? void 0 : _props$toolbar.additionalContent, ((_props$toolbar2 = props.toolbar) === null || _props$toolbar2 === void 0 ? void 0 : _props$toolbar2.additionalComponent) && /*#__PURE__*/_react.default.createElement(props.toolbar.additionalComponent, null)); - const footer = children.find(child => isChildComponentType(child, GraphiQL.Footer)); - const onClickReference = (0, _react.useCallback)(() => { - if (pluginResize.hiddenElement === 'first') { - pluginResize.setHiddenElement(null); - } - }, [pluginResize]); - const handleClearData = (0, _react.useCallback)(() => { - try { - storageContext === null || storageContext === void 0 ? void 0 : storageContext.clear(); - setClearStorageStatus('success'); - } catch { - setClearStorageStatus('error'); - } - }, [storageContext]); - const handlePersistHeaders = (0, _react.useCallback)(event => { - editorContext.setShouldPersistHeaders(event.currentTarget.dataset.value === 'true'); - }, [editorContext]); - const handleChangeTheme = (0, _react.useCallback)(event => { - const selectedTheme = event.currentTarget.dataset.theme; - setTheme(selectedTheme || null); - }, [setTheme]); - const handleAddTab = editorContext.addTab; - const handleRefetchSchema = schemaContext.introspect; - const handleReorder = editorContext.moveTab; - const handleShowDialog = (0, _react.useCallback)(event => { - setShowDialog(event.currentTarget.dataset.value); - }, []); - const handlePluginClick = (0, _react.useCallback)(e => { - const context = pluginContext; - const pluginIndex = Number(e.currentTarget.dataset.index); - const plugin = context.plugins.find((_, index) => pluginIndex === index); - const isVisible = plugin === context.visiblePlugin; - if (isVisible) { - context.setVisiblePlugin(null); - pluginResize.setHiddenElement('first'); - } else { - context.setVisiblePlugin(plugin); - pluginResize.setHiddenElement(null); - } - }, [pluginContext, pluginResize]); - const handleToolsTabClick = (0, _react.useCallback)(event => { - if (editorToolsResize.hiddenElement === 'second') { - editorToolsResize.setHiddenElement(null); - } - setActiveSecondaryEditor(event.currentTarget.dataset.name); - }, [editorToolsResize]); - const toggleEditorTools = (0, _react.useCallback)(() => { - editorToolsResize.setHiddenElement(editorToolsResize.hiddenElement === 'second' ? null : 'second'); - }, [editorToolsResize]); - const handleOpenShortKeysDialog = (0, _react.useCallback)(isOpen => { - if (!isOpen) { - setShowDialog(null); - } - }, []); - const handleOpenSettingsDialog = (0, _react.useCallback)(isOpen => { - if (!isOpen) { - setShowDialog(null); - setClearStorageStatus(null); - } - }, []); - const addTab = /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Add tab" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: "graphiql-tab-add", - onClick: handleAddTab, - "aria-label": "Add tab" - }, /*#__PURE__*/_react.default.createElement(_react2.PlusIcon, { - "aria-hidden": "true" - }))); - const className = props.className ? ` ${props.className}` : ''; - return /*#__PURE__*/_react.default.createElement(_react2.Tooltip.Provider, null, /*#__PURE__*/_react.default.createElement("div", { - "data-testid": "graphiql-container", - className: `graphiql-container${className}` - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-sidebar" - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-sidebar-section" - }, pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.plugins.map((plugin, index) => { - const isVisible = plugin === pluginContext.visiblePlugin; - const label = `${isVisible ? 'Hide' : 'Show'} ${plugin.title}`; - const Icon = plugin.icon; - return /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - key: plugin.title, - label: label - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: isVisible ? 'active' : '', - onClick: handlePluginClick, - "data-index": index, - "aria-label": label - }, /*#__PURE__*/_react.default.createElement(Icon, { - "aria-hidden": "true" - }))); - })), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-sidebar-section" - }, /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Re-fetch GraphQL schema" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - disabled: schemaContext.isFetching, - onClick: handleRefetchSchema, - "aria-label": "Re-fetch GraphQL schema" - }, /*#__PURE__*/_react.default.createElement(_react2.ReloadIcon, { - className: schemaContext.isFetching ? 'graphiql-spin' : '', - "aria-hidden": "true" - }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Open short keys dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - "data-value": "short-keys", - onClick: handleShowDialog, - "aria-label": "Open short keys dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.KeyboardShortcutIcon, { - "aria-hidden": "true" - }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: "Open settings dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - "data-value": "settings", - onClick: handleShowDialog, - "aria-label": "Open settings dialog" - }, /*#__PURE__*/_react.default.createElement(_react2.SettingsIcon, { - "aria-hidden": "true" - }))))), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-main" - }, /*#__PURE__*/_react.default.createElement("div", { - ref: pluginResize.firstRef, - style: { - // Make sure the container shrinks when containing long - // non-breaking texts - minWidth: '200px' - } - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-plugin" - }, PluginContent ? /*#__PURE__*/_react.default.createElement(PluginContent, null) : null)), (pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.visiblePlugin) && /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-horizontal-drag-bar", - ref: pluginResize.dragBarRef - }), /*#__PURE__*/_react.default.createElement("div", { - ref: pluginResize.secondRef, - className: "graphiql-sessions" - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-session-header" - }, !props.disableTabs && /*#__PURE__*/_react.default.createElement(_react2.Tabs, { - values: editorContext.tabs, - onReorder: handleReorder, - "aria-label": "Select active operation" - }, editorContext.tabs.length > 1 && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, editorContext.tabs.map((tab, index) => /*#__PURE__*/_react.default.createElement(_react2.Tab, { - key: tab.id, - value: tab, - isActive: index === editorContext.activeTabIndex - }, /*#__PURE__*/_react.default.createElement(_react2.Tab.Button, { - "aria-controls": "graphiql-session", - id: `graphiql-session-tab-${index}`, - onClick: () => { - executionContext.stop(); - editorContext.changeTab(index); - } - }, tab.title), /*#__PURE__*/_react.default.createElement(_react2.Tab.Close, { - onClick: () => { - if (editorContext.activeTabIndex === index) { - executionContext.stop(); - } - editorContext.closeTab(index); - } - }))), addTab)), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-session-header-right" - }, editorContext.tabs.length === 1 && addTab, logo)), /*#__PURE__*/_react.default.createElement("div", { - role: "tabpanel", - id: "graphiql-session", - className: "graphiql-session", - "aria-labelledby": `graphiql-session-tab-${editorContext.activeTabIndex}` - }, /*#__PURE__*/_react.default.createElement("div", { - ref: editorResize.firstRef - }, /*#__PURE__*/_react.default.createElement("div", { - className: `graphiql-editors${editorContext.tabs.length === 1 ? ' full-height' : ''}` - }, /*#__PURE__*/_react.default.createElement("div", { - ref: editorToolsResize.firstRef - }, /*#__PURE__*/_react.default.createElement("section", { - className: "graphiql-query-editor", - "aria-label": "Query Editor" - }, /*#__PURE__*/_react.default.createElement(_react2.QueryEditor, { - editorTheme: props.editorTheme, - keyMap: props.keyMap, - onClickReference: onClickReference, - onCopyQuery: props.onCopyQuery, - onEdit: props.onEditQuery, - readOnly: props.readOnly - }), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-toolbar", - role: "toolbar", - "aria-label": "Editor Commands" - }, /*#__PURE__*/_react.default.createElement(_react2.ExecuteButton, null), toolbar))), /*#__PURE__*/_react.default.createElement("div", { - ref: editorToolsResize.dragBarRef - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-editor-tools" - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: activeSecondaryEditor === 'variables' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', - onClick: handleToolsTabClick, - "data-name": "variables" - }, "Variables"), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - className: activeSecondaryEditor === 'headers' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', - onClick: handleToolsTabClick, - "data-name": "headers" - }, "Headers"), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { - label: editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools' - }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { - type: "button", - onClick: toggleEditorTools, - "aria-label": editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools', - className: "graphiql-toggle-editor-tools" - }, editorToolsResize.hiddenElement === 'second' ? /*#__PURE__*/_react.default.createElement(_react2.ChevronUpIcon, { - className: "graphiql-chevron-icon", - "aria-hidden": "true" - }) : /*#__PURE__*/_react.default.createElement(_react2.ChevronDownIcon, { - className: "graphiql-chevron-icon", - "aria-hidden": "true" - }))))), /*#__PURE__*/_react.default.createElement("div", { - ref: editorToolsResize.secondRef - }, /*#__PURE__*/_react.default.createElement("section", { - className: "graphiql-editor-tool", - "aria-label": activeSecondaryEditor === 'variables' ? 'Variables' : 'Headers' - }, /*#__PURE__*/_react.default.createElement(_react2.VariableEditor, { - editorTheme: props.editorTheme, - isHidden: activeSecondaryEditor !== 'variables', - keyMap: props.keyMap, - onEdit: props.onEditVariables, - onClickReference: onClickReference, - readOnly: props.readOnly - }), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.HeaderEditor, { - editorTheme: props.editorTheme, - isHidden: activeSecondaryEditor !== 'headers', - keyMap: props.keyMap, - onEdit: props.onEditHeaders, - readOnly: props.readOnly - }))))), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-horizontal-drag-bar", - ref: editorResize.dragBarRef - }), /*#__PURE__*/_react.default.createElement("div", { - ref: editorResize.secondRef - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-response" - }, executionContext.isFetching ? /*#__PURE__*/_react.default.createElement(_react2.Spinner, null) : null, /*#__PURE__*/_react.default.createElement(_react2.ResponseEditor, { - editorTheme: props.editorTheme, - responseTooltip: props.responseTooltip, - keyMap: props.keyMap - }), footer))))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { - open: showDialog === 'short-keys', - onOpenChange: handleOpenShortKeysDialog - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-header" - }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { - className: "graphiql-dialog-title" - }, "Short Keys"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement(ShortKeys, { - keyMap: props.keyMap || 'sublime' - }))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { - open: showDialog === 'settings', - onOpenChange: handleOpenSettingsDialog - }, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-header" - }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { - className: "graphiql-dialog-title" - }, "Settings"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), props.showPersistHeadersSettings ? /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-title" - }, "Persist headers"), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-caption" - }, "Save headers upon reloading.", ' ', /*#__PURE__*/_react.default.createElement("span", { - className: "graphiql-warning-text" - }, "Only enable if you trust this device."))), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - id: "enable-persist-headers", - className: editorContext.shouldPersistHeaders ? 'active' : '', - "data-value": "true", - onClick: handlePersistHeaders - }, "On"), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - id: "disable-persist-headers", - className: editorContext.shouldPersistHeaders ? '' : 'active', - onClick: handlePersistHeaders - }, "Off"))) : null, !forcedTheme && /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-title" - }, "Theme"), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-caption" - }, "Adjust how the interface appears.")), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - className: theme === null ? 'active' : '', - onClick: handleChangeTheme - }, "System"), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - className: theme === 'light' ? 'active' : '', - "data-theme": "light", - onClick: handleChangeTheme - }, "Light"), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - className: theme === 'dark' ? 'active' : '', - "data-theme": "dark", - onClick: handleChangeTheme - }, "Dark"))), storageContext ? /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section" - }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-title" - }, "Clear storage"), /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-dialog-section-caption" - }, "Remove all locally stored data and start fresh.")), /*#__PURE__*/_react.default.createElement(_react2.Button, { - type: "button", - state: clearStorageStatus || undefined, - disabled: clearStorageStatus === 'success', - onClick: handleClearData - }, { - success: 'Cleared data', - error: 'Failed' - }[clearStorageStatus] || 'Clear data')) : null))); - } - const modifier = typeof window !== 'undefined' && window.navigator.platform.toLowerCase().indexOf('mac') === 0 ? 'Cmd' : 'Ctrl'; - const SHORT_KEYS = Object.entries({ - 'Search in editor': [modifier, 'F'], - 'Search in documentation': [modifier, 'K'], - 'Execute query': [modifier, 'Enter'], - 'Prettify editors': ['Ctrl', 'Shift', 'P'], - 'Merge fragments definitions into operation definition': ['Ctrl', 'Shift', 'M'], - 'Copy query': ['Ctrl', 'Shift', 'C'], - 'Re-fetch schema using introspection': ['Ctrl', 'Shift', 'R'] - }); - function ShortKeys({ - keyMap - }) { - return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("table", { - className: "graphiql-table" - }, /*#__PURE__*/_react.default.createElement("thead", null, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("th", null, "Short Key"), /*#__PURE__*/_react.default.createElement("th", null, "Function"))), /*#__PURE__*/_react.default.createElement("tbody", null, SHORT_KEYS.map(([title, keys]) => /*#__PURE__*/_react.default.createElement("tr", { - key: title - }, /*#__PURE__*/_react.default.createElement("td", null, keys.map((key, index, array) => /*#__PURE__*/_react.default.createElement(_react.Fragment, { - key: key - }, /*#__PURE__*/_react.default.createElement("code", { - className: "graphiql-key" - }, key), index !== array.length - 1 && ' + '))), /*#__PURE__*/_react.default.createElement("td", null, title))))), /*#__PURE__*/_react.default.createElement("p", null, "The editors use", ' ', /*#__PURE__*/_react.default.createElement("a", { - href: "https://codemirror.net/5/doc/manual.html#keymaps", - target: "_blank", - rel: "noopener noreferrer" - }, "CodeMirror Key Maps"), ' ', "that add more short keys. This instance of Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL uses", ' ', /*#__PURE__*/_react.default.createElement("code", null, keyMap), ".")); - } - - // Configure the UI by providing this Component as a child of GraphiQL. - function GraphiQLLogo(props) { - return /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-logo" - }, props.children || /*#__PURE__*/_react.default.createElement("a", { - className: "graphiql-logo-link", - href: "https://github.com/graphql/graphiql", - target: "_blank", - rel: "noreferrer" - }, "Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL")); - } - GraphiQLLogo.displayName = 'GraphiQLLogo'; - - // Configure the UI by providing this Component as a child of GraphiQL. - function GraphiQLToolbar(props) { - // eslint-disable-next-line react/jsx-no-useless-fragment - return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, props.children); - } - GraphiQLToolbar.displayName = 'GraphiQLToolbar'; - - // Configure the UI by providing this Component as a child of GraphiQL. - function GraphiQLFooter(props) { - return /*#__PURE__*/_react.default.createElement("div", { - className: "graphiql-footer" - }, props.children); + * Next position after matched string. + **/ + this.lastIndex = end + shift; + /** + * Match#raw -> String + * + * Matched string. + **/ + this.raw = text; + /** + * Match#text -> String + * + * Notmalized text of matched string. + **/ + this.text = text; + /** + * Match#url -> String + * + * Normalized url of matched string. + **/ + this.url = text; +} +function createMatch(self, shift) { + const match = new Match(self, shift); + self.__compiled__[match.schema].normalize(match, self); + return match; +} + +/** + * class LinkifyIt + **/ + +/** + * new LinkifyIt(schemas, options) + * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) + * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } + * + * Creates new linkifier instance with optional additional schemas. + * Can be called without `new` keyword for convenience. + * + * By default understands: + * + * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links + * - "fuzzy" links and emails (example.com, foo@bar.com). + * + * `schemas` is an object, where each key/value describes protocol/rule: + * + * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` + * for example). `linkify-it` makes shure that prefix is not preceeded with + * alphanumeric char and symbols. Only whitespaces and punctuation allowed. + * - __value__ - rule to check tail after link prefix + * - _String_ - just alias to existing rule + * - _Object_ + * - _validate_ - validator function (should return matched length on success), + * or `RegExp`. + * - _normalize_ - optional function to normalize text & url of matched result + * (for example, for @twitter mentions). + * + * `options`: + * + * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. + * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts + * like version numbers. Default `false`. + * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. + * + **/ +function LinkifyIt(schemas, options) { + if (!(this instanceof LinkifyIt)) { + return new LinkifyIt(schemas, options); + } + if (!options) { + if (isOptionsObj(schemas)) { + options = schemas; + schemas = {}; + } + } + this.__opts__ = assign({}, defaultOptions, options); + + // Cache last tested result. Used to skip repeating steps on next `match` call. + this.__index__ = -1; + this.__last_index__ = -1; // Next scan position + this.__schema__ = ''; + this.__text_cache__ = ''; + this.__schemas__ = assign({}, defaultSchemas, schemas); + this.__compiled__ = {}; + this.__tlds__ = tlds_default; + this.__tlds_replaced__ = false; + this.re = {}; + compile(this); +} + +/** chainable + * LinkifyIt#add(schema, definition) + * - schema (String): rule name (fixed pattern prefix) + * - definition (String|RegExp|Object): schema definition + * + * Add new rule definition. See constructor description for details. + **/ +LinkifyIt.prototype.add = function add(schema, definition) { + this.__schemas__[schema] = definition; + compile(this); + return this; +}; + +/** chainable + * LinkifyIt#set(options) + * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } + * + * Set recognition options for links without schema. + **/ +LinkifyIt.prototype.set = function set(options) { + this.__opts__ = assign(this.__opts__, options); + return this; +}; + +/** + * LinkifyIt#test(text) -> Boolean + * + * Searches linkifiable pattern and returns `true` on success or `false` on fail. + **/ +LinkifyIt.prototype.test = function test(text) { + // Reset scan cache + this.__text_cache__ = text; + this.__index__ = -1; + if (!text.length) { + return false; } - GraphiQLFooter.displayName = 'GraphiQLFooter'; - - // Determines if the React child is of the same type of the provided React component - function isChildComponentType(child, component) { - var _child$type; - if (child !== null && child !== void 0 && (_child$type = child.type) !== null && _child$type !== void 0 && _child$type.displayName && child.type.displayName === component.displayName) { - return true; + let m, ml, me, len, shift, next, re, tld_pos, at_pos; + + // try to scan for link with schema - that's the most simple rule + if (this.re.schema_test.test(text)) { + re = this.re.schema_search; + re.lastIndex = 0; + while ((m = re.exec(text)) !== null) { + len = this.testSchemaAt(text, m[2], re.lastIndex); + if (len) { + this.__schema__ = m[2]; + this.__index__ = m.index + m[1].length; + this.__last_index__ = m.index + m[0].length + len; + break; + } } - return child.type === component; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/index.js": - /*!***************************************************!*\ - !*** ../../graphql-language-service/esm/index.js ***! - \***************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "CharacterStream", ({ - enumerable: true, - get: function () { - return _parser.CharacterStream; - } - })); - Object.defineProperty(exports, "CompletionItemKind", ({ - enumerable: true, - get: function () { - return _types.CompletionItemKind; - } - })); - Object.defineProperty(exports, "DIAGNOSTIC_SEVERITY", ({ - enumerable: true, - get: function () { - return _interface.DIAGNOSTIC_SEVERITY; - } - })); - Object.defineProperty(exports, "FileChangeTypeKind", ({ - enumerable: true, - get: function () { - return _types.FileChangeTypeKind; - } - })); - Object.defineProperty(exports, "GraphQLDocumentMode", ({ - enumerable: true, - get: function () { - return _parser.GraphQLDocumentMode; + if (this.__opts__.fuzzyLink && this.__compiled__['http:']) { + // guess schemaless links + tld_pos = text.search(this.re.host_fuzzy_test); + if (tld_pos >= 0) { + // if tld is located after found link - no need to check fuzzy pattern + if (this.__index__ < 0 || tld_pos < this.__index__) { + if ((ml = text.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) { + shift = ml.index + ml[1].length; + if (this.__index__ < 0 || shift < this.__index__) { + this.__schema__ = ''; + this.__index__ = shift; + this.__last_index__ = ml.index + ml[0].length; + } + } + } } - })); - Object.defineProperty(exports, "LexRules", ({ - enumerable: true, - get: function () { - return _parser.LexRules; + } + if (this.__opts__.fuzzyEmail && this.__compiled__['mailto:']) { + // guess schemaless emails + at_pos = text.indexOf('@'); + if (at_pos >= 0) { + // We can't skip this check, because this cases are possible: + // 192.168.1.1@gmail.com, my.in@example.com + if ((me = text.match(this.re.email_fuzzy)) !== null) { + shift = me.index + me[1].length; + next = me.index + me[0].length; + if (this.__index__ < 0 || shift < this.__index__ || shift === this.__index__ && next > this.__last_index__) { + this.__schema__ = 'mailto:'; + this.__index__ = shift; + this.__last_index__ = next; + } + } } - })); - Object.defineProperty(exports, "ParseRules", ({ - enumerable: true, - get: function () { - return _parser.ParseRules; + } + return this.__index__ >= 0; +}; + +/** + * LinkifyIt#pretest(text) -> Boolean + * + * Very quick check, that can give false positives. Returns true if link MAY BE + * can exists. Can be used for speed optimization, when you need to check that + * link NOT exists. + **/ +LinkifyIt.prototype.pretest = function pretest(text) { + return this.re.pretest.test(text); +}; + +/** + * LinkifyIt#testSchemaAt(text, name, position) -> Number + * - text (String): text to scan + * - name (String): rule (schema) name + * - position (Number): text offset to check from + * + * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly + * at given position. Returns length of found pattern (0 on fail). + **/ +LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text, schema, pos) { + // If not supported schema check requested - terminate + if (!this.__compiled__[schema.toLowerCase()]) { + return 0; + } + return this.__compiled__[schema.toLowerCase()].validate(text, pos, this); +}; + +/** + * LinkifyIt#match(text) -> Array|null + * + * Returns array of found link descriptions or `null` on fail. We strongly + * recommend to use [[LinkifyIt#test]] first, for best speed. + * + * ##### Result match description + * + * - __schema__ - link schema, can be empty for fuzzy links, or `//` for + * protocol-neutral links. + * - __index__ - offset of matched text + * - __lastIndex__ - index of next char after mathch end + * - __raw__ - matched text + * - __text__ - normalized text + * - __url__ - link, generated from matched text + **/ +LinkifyIt.prototype.match = function match(text) { + const result = []; + let shift = 0; + + // Try to take previous element from cache, if .test() called before + if (this.__index__ >= 0 && this.__text_cache__ === text) { + result.push(createMatch(this, shift)); + shift = this.__last_index__; + } + + // Cut head if cache was used + let tail = shift ? text.slice(shift) : text; + + // Scan string until end reached + while (this.test(tail)) { + result.push(createMatch(this, shift)); + tail = tail.slice(this.__last_index__); + shift += this.__last_index__; + } + if (result.length) { + return result; + } + return null; +}; + +/** + * LinkifyIt#matchAtStart(text) -> Match|null + * + * Returns fully-formed (not fuzzy) link if it starts at the beginning + * of the string, and null otherwise. + **/ +LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { + // Reset scan cache + this.__text_cache__ = text; + this.__index__ = -1; + if (!text.length) return null; + const m = this.re.schema_at_start.exec(text); + if (!m) return null; + const len = this.testSchemaAt(text, m[2], m[0].length); + if (!len) return null; + this.__schema__ = m[2]; + this.__index__ = m.index + m[1].length; + this.__last_index__ = m.index + m[0].length + len; + return createMatch(this, 0); +}; + +/** chainable + * LinkifyIt#tlds(list [, keepOld]) -> this + * - list (Array): list of tlds + * - keepOld (Boolean): merge with current list if `true` (`false` by default) + * + * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) + * to avoid false positives. By default this algorythm used: + * + * - hostname with any 2-letter root zones are ok. + * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф + * are ok. + * - encoded (`xn--...`) root zones are ok. + * + * If list is replaced, then exact match for 2-chars root zones will be checked. + **/ +LinkifyIt.prototype.tlds = function tlds(list, keepOld) { + list = Array.isArray(list) ? list : [list]; + if (!keepOld) { + this.__tlds__ = list.slice(); + this.__tlds_replaced__ = true; + compile(this); + return this; + } + this.__tlds__ = this.__tlds__.concat(list).sort().filter(function (el, idx, arr) { + return el !== arr[idx - 1]; + }).reverse(); + compile(this); + return this; +}; + +/** + * LinkifyIt#normalize(match) + * + * Default normalizer (if schema does not define it's own). + **/ +LinkifyIt.prototype.normalize = function normalize(match) { + // Do minimal possible changes by default. Need to collect feedback prior + // to move forward https://github.com/markdown-it/linkify-it/issues/1 + + if (!match.schema) { + match.url = 'http://' + match.url; + } + if (match.schema === 'mailto:' && !/^mailto:/i.test(match.url)) { + match.url = 'mailto:' + match.url; + } +}; + +/** + * LinkifyIt#onCompile() + * + * Override to modify basic RegExp-s. + **/ +LinkifyIt.prototype.onCompile = function onCompile() {}; +module.exports = LinkifyIt; + +/***/ }), + +/***/ "../node_modules/markdown-it/dist/index.cjs.js": +/*!*****************************************************!*\ + !*** ../node_modules/markdown-it/dist/index.cjs.js ***! + \*****************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + +var mdurl = __webpack_require__(/*! mdurl */ "../node_modules/mdurl/build/index.cjs.js"); +var ucmicro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); +var entities = __webpack_require__(/*! entities */ "../../../node_modules/entities/lib/index.js"); +var LinkifyIt = __webpack_require__(/*! linkify-it */ "../node_modules/linkify-it/build/index.cjs.js"); +var punycode = __webpack_require__(/*! punycode.js */ "../../../node_modules/punycode.js/punycode.es6.js"); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { + return e[k]; + } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} +var mdurl__namespace = /*#__PURE__*/_interopNamespaceDefault(mdurl); +var ucmicro__namespace = /*#__PURE__*/_interopNamespaceDefault(ucmicro); + +// Utilities +// + +function _class(obj) { + return Object.prototype.toString.call(obj); +} +function isString(obj) { + return _class(obj) === '[object String]'; +} +const _hasOwnProperty = Object.prototype.hasOwnProperty; +function has(object, key) { + return _hasOwnProperty.call(object, key); +} + +// Merge objects +// +function assign(obj /* from1, from2, from3, ... */) { + const sources = Array.prototype.slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) { + return; } - })); - Object.defineProperty(exports, "Position", ({ - enumerable: true, - get: function () { - return _utils.Position; + if (typeof source !== 'object') { + throw new TypeError(source + 'must be object'); } - })); - Object.defineProperty(exports, "Range", ({ - enumerable: true, - get: function () { - return _utils.Range; + Object.keys(source).forEach(function (key) { + obj[key] = source[key]; + }); + }); + return obj; +} + +// Remove element from array and put another array at those position. +// Useful for some operations with tokens +function arrayReplaceAt(src, pos, newElements) { + return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); +} +function isValidEntityCode(c) { + /* eslint no-bitwise:0 */ + // broken sequence + if (c >= 0xD800 && c <= 0xDFFF) { + return false; + } + // never used + if (c >= 0xFDD0 && c <= 0xFDEF) { + return false; + } + if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { + return false; + } + // control codes + if (c >= 0x00 && c <= 0x08) { + return false; + } + if (c === 0x0B) { + return false; + } + if (c >= 0x0E && c <= 0x1F) { + return false; + } + if (c >= 0x7F && c <= 0x9F) { + return false; + } + // out of range + if (c > 0x10FFFF) { + return false; + } + return true; +} +function fromCodePoint(c) { + /* eslint no-bitwise:0 */ + if (c > 0xffff) { + c -= 0x10000; + const surrogate1 = 0xd800 + (c >> 10); + const surrogate2 = 0xdc00 + (c & 0x3ff); + return String.fromCharCode(surrogate1, surrogate2); + } + return String.fromCharCode(c); +} +const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g; +const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; +const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi'); +const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i; +function replaceEntityPattern(match, name) { + if (name.charCodeAt(0) === 0x23 /* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) { + const code = name[1].toLowerCase() === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10); + if (isValidEntityCode(code)) { + return fromCodePoint(code); } - })); - Object.defineProperty(exports, "RuleKinds", ({ - enumerable: true, - get: function () { - return _parser.RuleKinds; + return match; + } + const decoded = entities.decodeHTML(match); + if (decoded !== match) { + return decoded; + } + return match; +} + +/* function replaceEntities(str) { + if (str.indexOf('&') < 0) { return str; } + + return str.replace(ENTITY_RE, replaceEntityPattern); +} */ + +function unescapeMd(str) { + if (str.indexOf('\\') < 0) { + return str; + } + return str.replace(UNESCAPE_MD_RE, '$1'); +} +function unescapeAll(str) { + if (str.indexOf('\\') < 0 && str.indexOf('&') < 0) { + return str; + } + return str.replace(UNESCAPE_ALL_RE, function (match, escaped, entity) { + if (escaped) { + return escaped; } - })); - Object.defineProperty(exports, "SEVERITY", ({ - enumerable: true, - get: function () { - return _interface.SEVERITY; + return replaceEntityPattern(match, entity); + }); +} +const HTML_ESCAPE_TEST_RE = /[&<>"]/; +const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; +const HTML_REPLACEMENTS = { + '&': '&', + '<': '<', + '>': '>', + '"': '"' +}; +function replaceUnsafeChar(ch) { + return HTML_REPLACEMENTS[ch]; +} +function escapeHtml(str) { + if (HTML_ESCAPE_TEST_RE.test(str)) { + return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); + } + return str; +} +const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; +function escapeRE(str) { + return str.replace(REGEXP_ESCAPE_RE, '\\$&'); +} +function isSpace(code) { + switch (code) { + case 0x09: + case 0x20: + return true; + } + return false; +} + +// Zs (unicode class) || [\t\f\v\r\n] +function isWhiteSpace(code) { + if (code >= 0x2000 && code <= 0x200A) { + return true; + } + switch (code) { + case 0x09: // \t + case 0x0A: // \n + case 0x0B: // \v + case 0x0C: // \f + case 0x0D: // \r + case 0x20: + case 0xA0: + case 0x1680: + case 0x202F: + case 0x205F: + case 0x3000: + return true; + } + return false; +} + +/* eslint-disable max-len */ + +// Currently without astral characters support. +function isPunctChar(ch) { + return ucmicro__namespace.P.test(ch) || ucmicro__namespace.S.test(ch); +} + +// Markdown ASCII punctuation characters. +// +// !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ +// http://spec.commonmark.org/0.15/#ascii-punctuation-character +// +// Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. +// +function isMdAsciiPunct(ch) { + switch (ch) { + case 0x21 /* ! */: + case 0x22 /* " */: + case 0x23 /* # */: + case 0x24 /* $ */: + case 0x25 /* % */: + case 0x26 /* & */: + case 0x27 /* ' */: + case 0x28 /* ( */: + case 0x29 /* ) */: + case 0x2A /* * */: + case 0x2B /* + */: + case 0x2C /* , */: + case 0x2D /* - */: + case 0x2E /* . */: + case 0x2F /* / */: + case 0x3A /* : */: + case 0x3B /* ; */: + case 0x3C /* < */: + case 0x3D /* = */: + case 0x3E /* > */: + case 0x3F /* ? */: + case 0x40 /* @ */: + case 0x5B /* [ */: + case 0x5C /* \ */: + case 0x5D /* ] */: + case 0x5E /* ^ */: + case 0x5F /* _ */: + case 0x60 /* ` */: + case 0x7B /* { */: + case 0x7C /* | */: + case 0x7D /* } */: + case 0x7E /* ~ */: + return true; + default: + return false; + } +} + +// Hepler to unify [reference labels]. +// +function normalizeReference(str) { + // Trim and collapse whitespace + // + str = str.trim().replace(/\s+/g, ' '); + + // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug + // fixed in v12 (couldn't find any details). + // + // So treat this one as a special case + // (remove this when node v10 is no longer supported). + // + if ('ẞ'.toLowerCase() === 'Ṿ') { + str = str.replace(/ẞ/g, 'ß'); + } + + // .toLowerCase().toUpperCase() should get rid of all differences + // between letter variants. + // + // Simple .toLowerCase() doesn't normalize 125 code points correctly, + // and .toUpperCase doesn't normalize 6 of them (list of exceptions: + // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently + // uppercased versions). + // + // Here's an example showing how it happens. Lets take greek letter omega: + // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) + // + // Unicode entries: + // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; + // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 + // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 + // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; + // + // Case-insensitive comparison should treat all of them as equivalent. + // + // But .toLowerCase() doesn't change ϑ (it's already lowercase), + // and .toUpperCase() doesn't change ϴ (already uppercase). + // + // Applying first lower then upper case normalizes any character: + // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' + // + // Note: this is equivalent to unicode case folding; unicode normalization + // is a different step that is not required here. + // + // Final result should be uppercased, because it's later stored in an object + // (this avoid a conflict with Object.prototype members, + // most notably, `__proto__`) + // + return str.toLowerCase().toUpperCase(); +} + +// Re-export libraries commonly used in both markdown-it and its plugins, +// so plugins won't have to depend on them explicitly, which reduces their +// bundled size (e.g. a browser build). +// +const lib = { + mdurl: mdurl__namespace, + ucmicro: ucmicro__namespace +}; +var utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arrayReplaceAt: arrayReplaceAt, + assign: assign, + escapeHtml: escapeHtml, + escapeRE: escapeRE, + fromCodePoint: fromCodePoint, + has: has, + isMdAsciiPunct: isMdAsciiPunct, + isPunctChar: isPunctChar, + isSpace: isSpace, + isString: isString, + isValidEntityCode: isValidEntityCode, + isWhiteSpace: isWhiteSpace, + lib: lib, + normalizeReference: normalizeReference, + unescapeAll: unescapeAll, + unescapeMd: unescapeMd +}); + +// Parse link label +// +// this function assumes that first character ("[") already matches; +// returns the end of the label +// + +function parseLinkLabel(state, start, disableNested) { + let level, found, marker, prevPos; + const max = state.posMax; + const oldPos = state.pos; + state.pos = start + 1; + level = 1; + while (state.pos < max) { + marker = state.src.charCodeAt(state.pos); + if (marker === 0x5D /* ] */) { + level--; + if (level === 0) { + found = true; + break; + } } - })); - Object.defineProperty(exports, "SuggestionCommand", ({ - enumerable: true, - get: function () { - return _interface.SuggestionCommand; + prevPos = state.pos; + state.md.inline.skipToken(state); + if (marker === 0x5B /* [ */) { + if (prevPos === state.pos - 1) { + // increase level if we find text `[`, which is not a part of any token + level++; + } else if (disableNested) { + state.pos = oldPos; + return -1; + } } - })); - Object.defineProperty(exports, "canUseDirective", ({ - enumerable: true, - get: function () { - return _interface.canUseDirective; + } + let labelEnd = -1; + if (found) { + labelEnd = state.pos; + } + + // restore old state + state.pos = oldPos; + return labelEnd; +} + +// Parse link destination +// + +function parseLinkDestination(str, start, max) { + let code; + let pos = start; + const result = { + ok: false, + pos: 0, + str: '' + }; + if (str.charCodeAt(pos) === 0x3C /* < */) { + pos++; + while (pos < max) { + code = str.charCodeAt(pos); + if (code === 0x0A /* \n */) { + return result; + } + if (code === 0x3C /* < */) { + return result; + } + if (code === 0x3E /* > */) { + result.pos = pos + 1; + result.str = unescapeAll(str.slice(start + 1, pos)); + result.ok = true; + return result; + } + if (code === 0x5C /* \ */ && pos + 1 < max) { + pos += 2; + continue; + } + pos++; } - })); - Object.defineProperty(exports, "collectVariables", ({ - enumerable: true, - get: function () { - return _utils.collectVariables; + + // no closing '>' + return result; + } + + // this should be ... } else { ... branch + + let level = 0; + while (pos < max) { + code = str.charCodeAt(pos); + if (code === 0x20) { + break; } - })); - Object.defineProperty(exports, "getASTNodeAtPosition", ({ - enumerable: true, - get: function () { - return _utils.getASTNodeAtPosition; + + // ascii control characters + if (code < 0x20 || code === 0x7F) { + break; } - })); - Object.defineProperty(exports, "getAutocompleteSuggestions", ({ - enumerable: true, - get: function () { - return _interface.getAutocompleteSuggestions; + if (code === 0x5C /* \ */ && pos + 1 < max) { + if (str.charCodeAt(pos + 1) === 0x20) { + break; + } + pos += 2; + continue; } - })); - Object.defineProperty(exports, "getDefinitionQueryResultForArgument", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForArgument; + if (code === 0x28 /* ( */) { + level++; + if (level > 32) { + return result; + } } - })); - Object.defineProperty(exports, "getDefinitionQueryResultForDefinitionNode", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForDefinitionNode; + if (code === 0x29 /* ) */) { + if (level === 0) { + break; + } + level--; } - })); - Object.defineProperty(exports, "getDefinitionQueryResultForField", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForField; + pos++; + } + if (start === pos) { + return result; + } + if (level !== 0) { + return result; + } + result.str = unescapeAll(str.slice(start, pos)); + result.pos = pos; + result.ok = true; + return result; +} + +// Parse link title +// + +// Parse link title within `str` in [start, max] range, +// or continue previous parsing if `prev_state` is defined (equal to result of last execution). +// +function parseLinkTitle(str, start, max, prev_state) { + let code; + let pos = start; + const state = { + // if `true`, this is a valid link title + ok: false, + // if `true`, this link can be continued on the next line + can_continue: false, + // if `ok`, it's the position of the first character after the closing marker + pos: 0, + // if `ok`, it's the unescaped title + str: '', + // expected closing marker character code + marker: 0 + }; + if (prev_state) { + // this is a continuation of a previous parseLinkTitle call on the next line, + // used in reference links only + state.str = prev_state.str; + state.marker = prev_state.marker; + } else { + if (pos >= max) { + return state; } - })); - Object.defineProperty(exports, "getDefinitionQueryResultForFragmentSpread", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForFragmentSpread; + let marker = str.charCodeAt(pos); + if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { + return state; } - })); - Object.defineProperty(exports, "getDefinitionQueryResultForNamedType", ({ - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForNamedType; + start++; + pos++; + + // if opening marker is "(", switch it to closing marker ")" + if (marker === 0x28) { + marker = 0x29; + } + state.marker = marker; + } + while (pos < max) { + code = str.charCodeAt(pos); + if (code === state.marker) { + state.pos = pos + 1; + state.str += unescapeAll(str.slice(start, pos)); + state.ok = true; + return state; + } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) { + return state; + } else if (code === 0x5C /* \ */ && pos + 1 < max) { + pos++; } - })); - Object.defineProperty(exports, "getDefinitionState", ({ - enumerable: true, - get: function () { - return _parser.getDefinitionState; + pos++; + } + + // no closing marker found, but this link title may continue on the next line (for references) + state.can_continue = true; + state.str += unescapeAll(str.slice(start, pos)); + return state; +} + +// Just a shortcut for bulk export + +var helpers = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseLinkDestination: parseLinkDestination, + parseLinkLabel: parseLinkLabel, + parseLinkTitle: parseLinkTitle +}); + +/** + * class Renderer + * + * Generates HTML from parsed token stream. Each instance has independent + * copy of rules. Those can be rewritten with ease. Also, you can add new + * rules if you create plugin and adds new token types. + **/ + +const default_rules = {}; +default_rules.code_inline = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + return '' + escapeHtml(token.content) + ''; +}; +default_rules.code_block = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + return '' + escapeHtml(tokens[idx].content) + '\n'; +}; +default_rules.fence = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + const info = token.info ? unescapeAll(token.info).trim() : ''; + let langName = ''; + let langAttrs = ''; + if (info) { + const arr = info.split(/(\s+)/g); + langName = arr[0]; + langAttrs = arr.slice(2).join(''); + } + let highlighted; + if (options.highlight) { + highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content); + } else { + highlighted = escapeHtml(token.content); + } + if (highlighted.indexOf('${highlighted}\n`; + } + return `

    ${highlighted}
    \n`; +}; +default_rules.image = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + + // "alt" attr MUST be set, even if empty. Because it's mandatory and + // should be placed on proper position for tests. + // + // Replace content with actual value + + token.attrs[token.attrIndex('alt')][1] = slf.renderInlineAsText(token.children, options, env); + return slf.renderToken(tokens, idx, options); +}; +default_rules.hardbreak = function (tokens, idx, options /*, env */) { + return options.xhtmlOut ? '
    \n' : '
    \n'; +}; +default_rules.softbreak = function (tokens, idx, options /*, env */) { + return options.breaks ? options.xhtmlOut ? '
    \n' : '
    \n' : '\n'; +}; +default_rules.text = function (tokens, idx /*, options, env */) { + return escapeHtml(tokens[idx].content); +}; +default_rules.html_block = function (tokens, idx /*, options, env */) { + return tokens[idx].content; +}; +default_rules.html_inline = function (tokens, idx /*, options, env */) { + return tokens[idx].content; +}; + +/** + * new Renderer() + * + * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. + **/ +function Renderer() { + /** + * Renderer#rules -> Object + * + * Contains render rules for tokens. Can be updated and extended. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.renderer.rules.strong_open = function () { return ''; }; + * md.renderer.rules.strong_close = function () { return ''; }; + * + * var result = md.renderInline(...); + * ``` + * + * Each rule is called as independent static function with fixed signature: + * + * ```javascript + * function my_token_render(tokens, idx, options, env, renderer) { + * // ... + * return renderedHTML; + * } + * ``` + * + * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs) + * for more details and examples. + **/ + this.rules = assign({}, default_rules); +} + +/** + * Renderer.renderAttrs(token) -> String + * + * Render token attributes to string. + **/ +Renderer.prototype.renderAttrs = function renderAttrs(token) { + let i, l, result; + if (!token.attrs) { + return ''; + } + result = ''; + for (i = 0, l = token.attrs.length; i < l; i++) { + result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"'; + } + return result; +}; + +/** + * Renderer.renderToken(tokens, idx, options) -> String + * - tokens (Array): list of tokens + * - idx (Numbed): token index to render + * - options (Object): params of parser instance + * + * Default token renderer. Can be overriden by custom function + * in [[Renderer#rules]]. + **/ +Renderer.prototype.renderToken = function renderToken(tokens, idx, options) { + const token = tokens[idx]; + let result = ''; + + // Tight list paragraphs + if (token.hidden) { + return ''; + } + + // Insert a newline between hidden paragraph and subsequent opening + // block-level tag. + // + // For example, here we should insert a newline before blockquote: + // - a + // > + // + if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) { + result += '\n'; + } + + // Add token name, e.g. ``. + // + needLf = false; + } + } } - })); - Object.defineProperty(exports, "getFieldDef", ({ - enumerable: true, - get: function () { - return _parser.getFieldDef; + } + result += needLf ? '>\n' : '>'; + return result; +}; + +/** + * Renderer.renderInline(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * The same as [[Renderer.render]], but for single token of `inline` type. + **/ +Renderer.prototype.renderInline = function (tokens, options, env) { + let result = ''; + const rules = this.rules; + for (let i = 0, len = tokens.length; i < len; i++) { + const type = tokens[i].type; + if (typeof rules[type] !== 'undefined') { + result += rules[type](tokens, i, options, env, this); + } else { + result += this.renderToken(tokens, i, options); } - })); - Object.defineProperty(exports, "getFragmentDefinitions", ({ - enumerable: true, - get: function () { - return _interface.getFragmentDefinitions; + } + return result; +}; + +/** internal + * Renderer.renderInlineAsText(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * Special kludge for image `alt` attributes to conform CommonMark spec. + * Don't try to use it! Spec requires to show `alt` content with stripped markup, + * instead of simple escaping. + **/ +Renderer.prototype.renderInlineAsText = function (tokens, options, env) { + let result = ''; + for (let i = 0, len = tokens.length; i < len; i++) { + switch (tokens[i].type) { + case 'text': + result += tokens[i].content; + break; + case 'image': + result += this.renderInlineAsText(tokens[i].children, options, env); + break; + case 'html_inline': + case 'html_block': + result += tokens[i].content; + break; + case 'softbreak': + case 'hardbreak': + result += '\n'; + break; + // all other tokens are skipped } - })); - Object.defineProperty(exports, "getFragmentDependencies", ({ - enumerable: true, - get: function () { - return _utils.getFragmentDependencies; + } + return result; +}; + +/** + * Renderer.render(tokens, options, env) -> String + * - tokens (Array): list on block tokens to render + * - options (Object): params of parser instance + * - env (Object): additional data from parsed input (references, for example) + * + * Takes token stream and generates HTML. Probably, you will never need to call + * this method directly. + **/ +Renderer.prototype.render = function (tokens, options, env) { + let result = ''; + const rules = this.rules; + for (let i = 0, len = tokens.length; i < len; i++) { + const type = tokens[i].type; + if (type === 'inline') { + result += this.renderInline(tokens[i].children, options, env); + } else if (typeof rules[type] !== 'undefined') { + result += rules[type](tokens, i, options, env, this); + } else { + result += this.renderToken(tokens, i, options, env); } - })); - Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ - enumerable: true, - get: function () { - return _utils.getFragmentDependenciesForAST; + } + return result; +}; + +/** + * class Ruler + * + * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and + * [[MarkdownIt#inline]] to manage sequences of functions (rules): + * + * - keep rules in defined order + * - assign the name to each rule + * - enable/disable rules + * - add/replace rules + * - allow assign rules to additional named chains (in the same) + * - cacheing lists of active rules + * + * You will not need use this class directly until write plugins. For simple + * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and + * [[MarkdownIt.use]]. + **/ + +/** + * new Ruler() + **/ +function Ruler() { + // List of added rules. Each element is: + // + // { + // name: XXX, + // enabled: Boolean, + // fn: Function(), + // alt: [ name2, name3 ] + // } + // + this.__rules__ = []; + + // Cached rule chains. + // + // First level - chain name, '' for default. + // Second level - diginal anchor for fast filtering by charcodes. + // + this.__cache__ = null; +} + +// Helper methods, should not be used directly + +// Find rule index by name +// +Ruler.prototype.__find__ = function (name) { + for (let i = 0; i < this.__rules__.length; i++) { + if (this.__rules__[i].name === name) { + return i; } - })); - Object.defineProperty(exports, "getHoverInformation", ({ - enumerable: true, - get: function () { - return _interface.getHoverInformation; + } + return -1; +}; + +// Build rules lookup cache +// +Ruler.prototype.__compile__ = function () { + const self = this; + const chains = ['']; + + // collect unique names + self.__rules__.forEach(function (rule) { + if (!rule.enabled) { + return; } - })); - Object.defineProperty(exports, "getOperationASTFacts", ({ - enumerable: true, - get: function () { - return _utils.getOperationASTFacts; + rule.alt.forEach(function (altName) { + if (chains.indexOf(altName) < 0) { + chains.push(altName); + } + }); + }); + self.__cache__ = {}; + chains.forEach(function (chain) { + self.__cache__[chain] = []; + self.__rules__.forEach(function (rule) { + if (!rule.enabled) { + return; + } + if (chain && rule.alt.indexOf(chain) < 0) { + return; + } + self.__cache__[chain].push(rule.fn); + }); + }); +}; + +/** + * Ruler.at(name, fn [, options]) + * - name (String): rule name to replace. + * - fn (Function): new rule function. + * - options (Object): new rule options (not mandatory). + * + * Replace rule by name with new function & options. Throws error if name not + * found. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * Replace existing typographer replacement rule with new one: + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.core.ruler.at('replacements', function replace(state) { + * //... + * }); + * ``` + **/ +Ruler.prototype.at = function (name, fn, options) { + const index = this.__find__(name); + const opt = options || {}; + if (index === -1) { + throw new Error('Parser rule not found: ' + name); + } + this.__rules__[index].fn = fn; + this.__rules__[index].alt = opt.alt || []; + this.__cache__ = null; +}; + +/** + * Ruler.before(beforeName, ruleName, fn [, options]) + * - beforeName (String): new rule will be added before this one. + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Add new rule to chain before one with given name. See also + * [[Ruler.after]], [[Ruler.push]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { + * //... + * }); + * ``` + **/ +Ruler.prototype.before = function (beforeName, ruleName, fn, options) { + const index = this.__find__(beforeName); + const opt = options || {}; + if (index === -1) { + throw new Error('Parser rule not found: ' + beforeName); + } + this.__rules__.splice(index, 0, { + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [] + }); + this.__cache__ = null; +}; + +/** + * Ruler.after(afterName, ruleName, fn [, options]) + * - afterName (String): new rule will be added after this one. + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Add new rule to chain after one with given name. See also + * [[Ruler.before]], [[Ruler.push]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.inline.ruler.after('text', 'my_rule', function replace(state) { + * //... + * }); + * ``` + **/ +Ruler.prototype.after = function (afterName, ruleName, fn, options) { + const index = this.__find__(afterName); + const opt = options || {}; + if (index === -1) { + throw new Error('Parser rule not found: ' + afterName); + } + this.__rules__.splice(index + 1, 0, { + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [] + }); + this.__cache__ = null; +}; + +/** + * Ruler.push(ruleName, fn [, options]) + * - ruleName (String): name of added rule. + * - fn (Function): rule function. + * - options (Object): rule options (not mandatory). + * + * Push new rule to the end of chain. See also + * [[Ruler.before]], [[Ruler.after]]. + * + * ##### Options: + * + * - __alt__ - array with names of "alternate" chains. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * md.core.ruler.push('my_rule', function replace(state) { + * //... + * }); + * ``` + **/ +Ruler.prototype.push = function (ruleName, fn, options) { + const opt = options || {}; + this.__rules__.push({ + name: ruleName, + enabled: true, + fn, + alt: opt.alt || [] + }); + this.__cache__ = null; +}; + +/** + * Ruler.enable(list [, ignoreInvalid]) -> Array + * - list (String|Array): list of rule names to enable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable rules with given names. If any rule name not found - throw Error. + * Errors can be disabled by second param. + * + * Returns list of found rule names (if no exception happened). + * + * See also [[Ruler.disable]], [[Ruler.enableOnly]]. + **/ +Ruler.prototype.enable = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + const result = []; + + // Search by name and enable + list.forEach(function (name) { + const idx = this.__find__(name); + if (idx < 0) { + if (ignoreInvalid) { + return; + } + throw new Error('Rules manager: invalid rule name ' + name); } - })); - Object.defineProperty(exports, "getOperationFacts", ({ - enumerable: true, - get: function () { - return _utils.getOperationFacts; + this.__rules__[idx].enabled = true; + result.push(name); + }, this); + this.__cache__ = null; + return result; +}; + +/** + * Ruler.enableOnly(list [, ignoreInvalid]) + * - list (String|Array): list of rule names to enable (whitelist). + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable rules with given names, and disable everything else. If any rule name + * not found - throw Error. Errors can be disabled by second param. + * + * See also [[Ruler.disable]], [[Ruler.enable]]. + **/ +Ruler.prototype.enableOnly = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + this.__rules__.forEach(function (rule) { + rule.enabled = false; + }); + this.enable(list, ignoreInvalid); +}; + +/** + * Ruler.disable(list [, ignoreInvalid]) -> Array + * - list (String|Array): list of rule names to disable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Disable rules with given names. If any rule name not found - throw Error. + * Errors can be disabled by second param. + * + * Returns list of found rule names (if no exception happened). + * + * See also [[Ruler.enable]], [[Ruler.enableOnly]]. + **/ +Ruler.prototype.disable = function (list, ignoreInvalid) { + if (!Array.isArray(list)) { + list = [list]; + } + const result = []; + + // Search by name and disable + list.forEach(function (name) { + const idx = this.__find__(name); + if (idx < 0) { + if (ignoreInvalid) { + return; + } + throw new Error('Rules manager: invalid rule name ' + name); } - })); - Object.defineProperty(exports, "getOutline", ({ - enumerable: true, - get: function () { - return _interface.getOutline; + this.__rules__[idx].enabled = false; + result.push(name); + }, this); + this.__cache__ = null; + return result; +}; + +/** + * Ruler.getRules(chainName) -> Array + * + * Return array of active functions (rules) for given chain name. It analyzes + * rules configuration, compiles caches if not exists and returns result. + * + * Default chain name is `''` (empty string). It can't be skipped. That's + * done intentionally, to keep signature monomorphic for high speed. + **/ +Ruler.prototype.getRules = function (chainName) { + if (this.__cache__ === null) { + this.__compile__(); + } + + // Chain can be empty, if rules disabled. But we still have to return Array. + return this.__cache__[chainName] || []; +}; + +// Token class + +/** + * class Token + **/ + +/** + * new Token(type, tag, nesting) + * + * Create new token and fill passed properties. + **/ +function Token(type, tag, nesting) { + /** + * Token#type -> String + * + * Type of the token (string, e.g. "paragraph_open") + **/ + this.type = type; + + /** + * Token#tag -> String + * + * html tag name, e.g. "p" + **/ + this.tag = tag; + + /** + * Token#attrs -> Array + * + * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` + **/ + this.attrs = null; + + /** + * Token#map -> Array + * + * Source map info. Format: `[ line_begin, line_end ]` + **/ + this.map = null; + + /** + * Token#nesting -> Number + * + * Level change (number in {-1, 0, 1} set), where: + * + * - `1` means the tag is opening + * - `0` means the tag is self-closing + * - `-1` means the tag is closing + **/ + this.nesting = nesting; + + /** + * Token#level -> Number + * + * nesting level, the same as `state.level` + **/ + this.level = 0; + + /** + * Token#children -> Array + * + * An array of child nodes (inline and img tokens) + **/ + this.children = null; + + /** + * Token#content -> String + * + * In a case of self-closing tag (code, html, fence, etc.), + * it has contents of this tag. + **/ + this.content = ''; + + /** + * Token#markup -> String + * + * '*' or '_' for emphasis, fence string for fence, etc. + **/ + this.markup = ''; + + /** + * Token#info -> String + * + * Additional information: + * + * - Info string for "fence" tokens + * - The value "auto" for autolink "link_open" and "link_close" tokens + * - The string value of the item marker for ordered-list "list_item_open" tokens + **/ + this.info = ''; + + /** + * Token#meta -> Object + * + * A place for plugins to store an arbitrary data + **/ + this.meta = null; + + /** + * Token#block -> Boolean + * + * True for block-level tokens, false for inline tokens. + * Used in renderer to calculate line breaks + **/ + this.block = false; + + /** + * Token#hidden -> Boolean + * + * If it's true, ignore this element when rendering. Used for tight lists + * to hide paragraphs. + **/ + this.hidden = false; +} + +/** + * Token.attrIndex(name) -> Number + * + * Search attribute index by name. + **/ +Token.prototype.attrIndex = function attrIndex(name) { + if (!this.attrs) { + return -1; + } + const attrs = this.attrs; + for (let i = 0, len = attrs.length; i < len; i++) { + if (attrs[i][0] === name) { + return i; } - })); - Object.defineProperty(exports, "getQueryFacts", ({ - enumerable: true, - get: function () { - return _utils.getQueryFacts; + } + return -1; +}; + +/** + * Token.attrPush(attrData) + * + * Add `[ name, value ]` attribute to list. Init attrs if necessary + **/ +Token.prototype.attrPush = function attrPush(attrData) { + if (this.attrs) { + this.attrs.push(attrData); + } else { + this.attrs = [attrData]; + } +}; + +/** + * Token.attrSet(name, value) + * + * Set `name` attribute to `value`. Override old value if exists. + **/ +Token.prototype.attrSet = function attrSet(name, value) { + const idx = this.attrIndex(name); + const attrData = [name, value]; + if (idx < 0) { + this.attrPush(attrData); + } else { + this.attrs[idx] = attrData; + } +}; + +/** + * Token.attrGet(name) + * + * Get the value of attribute `name`, or null if it does not exist. + **/ +Token.prototype.attrGet = function attrGet(name) { + const idx = this.attrIndex(name); + let value = null; + if (idx >= 0) { + value = this.attrs[idx][1]; + } + return value; +}; + +/** + * Token.attrJoin(name, value) + * + * Join value to existing attribute via space. Or create new attribute if not + * exists. Useful to operate with token classes. + **/ +Token.prototype.attrJoin = function attrJoin(name, value) { + const idx = this.attrIndex(name); + if (idx < 0) { + this.attrPush([name, value]); + } else { + this.attrs[idx][1] = this.attrs[idx][1] + ' ' + value; + } +}; + +// Core state object +// + +function StateCore(src, md, env) { + this.src = src; + this.env = env; + this.tokens = []; + this.inlineMode = false; + this.md = md; // link to parser instance +} + +// re-export Token class to use in core rules +StateCore.prototype.Token = Token; + +// Normalize input string + +// https://spec.commonmark.org/0.29/#line-ending +const NEWLINES_RE = /\r\n?|\n/g; +const NULL_RE = /\0/g; +function normalize(state) { + let str; + + // Normalize newlines + str = state.src.replace(NEWLINES_RE, '\n'); + + // Replace NULL characters + str = str.replace(NULL_RE, '\uFFFD'); + state.src = str; +} +function block(state) { + let token; + if (state.inlineMode) { + token = new state.Token('inline', '', 0); + token.content = state.src; + token.map = [0, 1]; + token.children = []; + state.tokens.push(token); + } else { + state.md.block.parse(state.src, state.md, state.env, state.tokens); + } +} +function inline(state) { + const tokens = state.tokens; + + // Parse inlines + for (let i = 0, l = tokens.length; i < l; i++) { + const tok = tokens[i]; + if (tok.type === 'inline') { + state.md.inline.parse(tok.content, state.md, state.env, tok.children); } - })); - Object.defineProperty(exports, "getRange", ({ - enumerable: true, - get: function () { - return _interface.getRange; + } +} + +// Replace link-like texts with link nodes. +// +// Currently restricted by `md.validateLink()` to http/https/ftp +// + +function isLinkOpen$1(str) { + return /^\s]/i.test(str); +} +function isLinkClose$1(str) { + return /^<\/a\s*>/i.test(str); +} +function linkify$1(state) { + const blockTokens = state.tokens; + if (!state.md.options.linkify) { + return; + } + for (let j = 0, l = blockTokens.length; j < l; j++) { + if (blockTokens[j].type !== 'inline' || !state.md.linkify.pretest(blockTokens[j].content)) { + continue; } - })); - Object.defineProperty(exports, "getTokenAtPosition", ({ - enumerable: true, - get: function () { - return _parser.getTokenAtPosition; + let tokens = blockTokens[j].children; + let htmlLinkLevel = 0; + + // We scan from the end, to keep position when new tags added. + // Use reversed logic in links start/end match + for (let i = tokens.length - 1; i >= 0; i--) { + const currentToken = tokens[i]; + + // Skip content of markdown links + if (currentToken.type === 'link_close') { + i--; + while (tokens[i].level !== currentToken.level && tokens[i].type !== 'link_open') { + i--; + } + continue; + } + + // Skip content of html tag links + if (currentToken.type === 'html_inline') { + if (isLinkOpen$1(currentToken.content) && htmlLinkLevel > 0) { + htmlLinkLevel--; + } + if (isLinkClose$1(currentToken.content)) { + htmlLinkLevel++; + } + } + if (htmlLinkLevel > 0) { + continue; + } + if (currentToken.type === 'text' && state.md.linkify.test(currentToken.content)) { + const text = currentToken.content; + let links = state.md.linkify.match(text); + + // Now split string to nodes + const nodes = []; + let level = currentToken.level; + let lastPos = 0; + + // forbid escape sequence at the start of the string, + // this avoids http\://example.com/ from being linkified as + // http:
    //example.com/ + if (links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === 'text_special') { + links = links.slice(1); + } + for (let ln = 0; ln < links.length; ln++) { + const url = links[ln].url; + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) { + continue; + } + let urlText = links[ln].text; + + // Linkifier might send raw hostnames like "example.com", where url + // starts with domain name. So we prepend http:// in those cases, + // and remove it afterwards. + // + if (!links[ln].schema) { + urlText = state.md.normalizeLinkText('http://' + urlText).replace(/^http:\/\//, ''); + } else if (links[ln].schema === 'mailto:' && !/^mailto:/i.test(urlText)) { + urlText = state.md.normalizeLinkText('mailto:' + urlText).replace(/^mailto:/, ''); + } else { + urlText = state.md.normalizeLinkText(urlText); + } + const pos = links[ln].index; + if (pos > lastPos) { + const token = new state.Token('text', '', 0); + token.content = text.slice(lastPos, pos); + token.level = level; + nodes.push(token); + } + const token_o = new state.Token('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.level = level++; + token_o.markup = 'linkify'; + token_o.info = 'auto'; + nodes.push(token_o); + const token_t = new state.Token('text', '', 0); + token_t.content = urlText; + token_t.level = level; + nodes.push(token_t); + const token_c = new state.Token('link_close', 'a', -1); + token_c.level = --level; + token_c.markup = 'linkify'; + token_c.info = 'auto'; + nodes.push(token_c); + lastPos = links[ln].lastIndex; + } + if (lastPos < text.length) { + const token = new state.Token('text', '', 0); + token.content = text.slice(lastPos); + token.level = level; + nodes.push(token); + } + + // replace current node + blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes); + } } - })); - Object.defineProperty(exports, "getTypeInfo", ({ - enumerable: true, - get: function () { - return _interface.getTypeInfo; + } +} + +// Simple typographic replacements +// +// (c) (C) → © +// (tm) (TM) → ™ +// (r) (R) → ® +// +- → ± +// ... → … (also ?.... → ?.., !.... → !..) +// ???????? → ???, !!!!! → !!!, `,,` → `,` +// -- → –, --- → — +// + +// TODO: +// - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ +// - multiplications 2 x 4 -> 2 × 4 + +const RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; + +// Workaround for phantomjs - need regex without /g flag, +// or root check will fail every second time +const SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; +const SCOPED_ABBR_RE = /\((c|tm|r)\)/ig; +const SCOPED_ABBR = { + c: '©', + r: '®', + tm: '™' +}; +function replaceFn(match, name) { + return SCOPED_ABBR[name.toLowerCase()]; +} +function replace_scoped(inlineTokens) { + let inside_autolink = 0; + for (let i = inlineTokens.length - 1; i >= 0; i--) { + const token = inlineTokens[i]; + if (token.type === 'text' && !inside_autolink) { + token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); + } + if (token.type === 'link_open' && token.info === 'auto') { + inside_autolink--; + } + if (token.type === 'link_close' && token.info === 'auto') { + inside_autolink++; + } + } +} +function replace_rare(inlineTokens) { + let inside_autolink = 0; + for (let i = inlineTokens.length - 1; i >= 0; i--) { + const token = inlineTokens[i]; + if (token.type === 'text' && !inside_autolink) { + if (RARE_RE.test(token.content)) { + token.content = token.content.replace(/\+-/g, '±') + // .., ..., ....... -> … + // but ?..... & !..... -> ?.. & !.. + .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..').replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',') + // em-dash + .replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014') + // en-dash + .replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013').replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013'); + } + } + if (token.type === 'link_open' && token.info === 'auto') { + inside_autolink--; + } + if (token.type === 'link_close' && token.info === 'auto') { + inside_autolink++; + } + } +} +function replace(state) { + let blkIdx; + if (!state.md.options.typographer) { + return; + } + for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { + if (state.tokens[blkIdx].type !== 'inline') { + continue; } - })); - Object.defineProperty(exports, "getVariableCompletions", ({ - enumerable: true, - get: function () { - return _interface.getVariableCompletions; + if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { + replace_scoped(state.tokens[blkIdx].children); } - })); - Object.defineProperty(exports, "getVariablesJSONSchema", ({ - enumerable: true, - get: function () { - return _utils.getVariablesJSONSchema; + if (RARE_RE.test(state.tokens[blkIdx].content)) { + replace_rare(state.tokens[blkIdx].children); } - })); - Object.defineProperty(exports, "isIgnored", ({ - enumerable: true, - get: function () { - return _parser.isIgnored; + } +} + +// Convert straight quotation marks to typographic ones +// + +const QUOTE_TEST_RE = /['"]/; +const QUOTE_RE = /['"]/g; +const APOSTROPHE = '\u2019'; /* ’ */ + +function replaceAt(str, index, ch) { + return str.slice(0, index) + ch + str.slice(index + 1); +} +function process_inlines(tokens, state) { + let j; + const stack = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const thisLevel = tokens[i].level; + for (j = stack.length - 1; j >= 0; j--) { + if (stack[j].level <= thisLevel) { + break; + } } - })); - Object.defineProperty(exports, "list", ({ - enumerable: true, - get: function () { - return _parser.list; + stack.length = j + 1; + if (token.type !== 'text') { + continue; } - })); - Object.defineProperty(exports, "offsetToPosition", ({ - enumerable: true, - get: function () { - return _utils.offsetToPosition; + let text = token.content; + let pos = 0; + let max = text.length; + + /* eslint no-labels:0,block-scoped-var:0 */ + OUTER: while (pos < max) { + QUOTE_RE.lastIndex = pos; + const t = QUOTE_RE.exec(text); + if (!t) { + break; + } + let canOpen = true; + let canClose = true; + pos = t.index + 1; + const isSingle = t[0] === "'"; + + // Find previous character, + // default to space if it's the beginning of the line + // + let lastChar = 0x20; + if (t.index - 1 >= 0) { + lastChar = text.charCodeAt(t.index - 1); + } else { + for (j = i - 1; j >= 0; j--) { + if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // lastChar defaults to 0x20 + if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + + lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1); + break; + } + } + + // Find next character, + // default to space if it's the end of the line + // + let nextChar = 0x20; + if (pos < max) { + nextChar = text.charCodeAt(pos); + } else { + for (j = i + 1; j < tokens.length; j++) { + if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // nextChar defaults to 0x20 + if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' + + nextChar = tokens[j].content.charCodeAt(0); + break; + } + } + const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); + const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); + const isLastWhiteSpace = isWhiteSpace(lastChar); + const isNextWhiteSpace = isWhiteSpace(nextChar); + if (isNextWhiteSpace) { + canOpen = false; + } else if (isNextPunctChar) { + if (!(isLastWhiteSpace || isLastPunctChar)) { + canOpen = false; + } + } + if (isLastWhiteSpace) { + canClose = false; + } else if (isLastPunctChar) { + if (!(isNextWhiteSpace || isNextPunctChar)) { + canClose = false; + } + } + if (nextChar === 0x22 /* " */ && t[0] === '"') { + if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { + // special case: 1"" - count first quote as an inch + canClose = canOpen = false; + } + } + if (canOpen && canClose) { + // Replace quotes in the middle of punctuation sequence, but not + // in the middle of the words, i.e.: + // + // 1. foo " bar " baz - not replaced + // 2. foo-"-bar-"-baz - replaced + // 3. foo"bar"baz - not replaced + // + canOpen = isLastPunctChar; + canClose = isNextPunctChar; + } + if (!canOpen && !canClose) { + // middle of word + if (isSingle) { + token.content = replaceAt(token.content, t.index, APOSTROPHE); + } + continue; + } + if (canClose) { + // this could be a closing quote, rewind the stack to get a match + for (j = stack.length - 1; j >= 0; j--) { + let item = stack[j]; + if (stack[j].level < thisLevel) { + break; + } + if (item.single === isSingle && stack[j].level === thisLevel) { + item = stack[j]; + let openQuote; + let closeQuote; + if (isSingle) { + openQuote = state.md.options.quotes[2]; + closeQuote = state.md.options.quotes[3]; + } else { + openQuote = state.md.options.quotes[0]; + closeQuote = state.md.options.quotes[1]; + } + + // replace token.content *before* tokens[item.token].content, + // because, if they are pointing at the same token, replaceAt + // could mess up indices when quote length != 1 + token.content = replaceAt(token.content, t.index, closeQuote); + tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, openQuote); + pos += closeQuote.length - 1; + if (item.token === i) { + pos += openQuote.length - 1; + } + text = token.content; + max = text.length; + stack.length = j; + continue OUTER; + } + } + } + if (canOpen) { + stack.push({ + token: i, + pos: t.index, + single: isSingle, + level: thisLevel + }); + } else if (canClose && isSingle) { + token.content = replaceAt(token.content, t.index, APOSTROPHE); + } } - })); - Object.defineProperty(exports, "onlineParser", ({ - enumerable: true, - get: function () { - return _parser.onlineParser; + } +} +function smartquotes(state) { + /* eslint max-depth:0 */ + if (!state.md.options.typographer) { + return; + } + for (let blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { + if (state.tokens[blkIdx].type !== 'inline' || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) { + continue; } - })); - Object.defineProperty(exports, "opt", ({ - enumerable: true, - get: function () { - return _parser.opt; + process_inlines(state.tokens[blkIdx].children, state); + } +} + +// Join raw text tokens with the rest of the text +// +// This is set as a separate rule to provide an opportunity for plugins +// to run text replacements after text join, but before escape join. +// +// For example, `\:)` shouldn't be replaced with an emoji. +// + +function text_join(state) { + let curr, last; + const blockTokens = state.tokens; + const l = blockTokens.length; + for (let j = 0; j < l; j++) { + if (blockTokens[j].type !== 'inline') continue; + const tokens = blockTokens[j].children; + const max = tokens.length; + for (curr = 0; curr < max; curr++) { + if (tokens[curr].type === 'text_special') { + tokens[curr].type = 'text'; + } } - })); - Object.defineProperty(exports, "p", ({ - enumerable: true, - get: function () { - return _parser.p; + for (curr = last = 0; curr < max; curr++) { + if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { + // collapse two adjacent text nodes + tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; + } else { + if (curr !== last) { + tokens[last] = tokens[curr]; + } + last++; + } } - })); - Object.defineProperty(exports, "pointToOffset", ({ - enumerable: true, - get: function () { - return _utils.pointToOffset; + if (curr !== last) { + tokens.length = last; } - })); - Object.defineProperty(exports, "t", ({ - enumerable: true, - get: function () { - return _parser.t; + } +} + +/** internal + * class Core + * + * Top-level rules executor. Glues block/inline parsers and does intermediate + * transformations. + **/ + +const _rules$2 = [['normalize', normalize], ['block', block], ['inline', inline], ['linkify', linkify$1], ['replacements', replace], ['smartquotes', smartquotes], +// `text_join` finds `text_special` tokens (for escape sequences) +// and joins them with the rest of the text +['text_join', text_join]]; + +/** + * new Core() + **/ +function Core() { + /** + * Core#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of core rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules$2.length; i++) { + this.ruler.push(_rules$2[i][0], _rules$2[i][1]); + } +} + +/** + * Core.process(state) + * + * Executes core chain rules. + **/ +Core.prototype.process = function (state) { + const rules = this.ruler.getRules(''); + for (let i = 0, l = rules.length; i < l; i++) { + rules[i](state); + } +}; +Core.prototype.State = StateCore; + +// Parser state class + +function StateBlock(src, md, env, tokens) { + this.src = src; + + // link to parser instance + this.md = md; + this.env = env; + + // + // Internal state vartiables + // + + this.tokens = tokens; + this.bMarks = []; // line begin offsets for fast jumps + this.eMarks = []; // line end offsets for fast jumps + this.tShift = []; // offsets of the first non-space characters (tabs not expanded) + this.sCount = []; // indents for each line (tabs expanded) + + // An amount of virtual spaces (tabs expanded) between beginning + // of each line (bMarks) and real beginning of that line. + // + // It exists only as a hack because blockquotes override bMarks + // losing information in the process. + // + // It's used only when expanding tabs, you can think about it as + // an initial tab length, e.g. bsCount=21 applied to string `\t123` + // means first tab should be expanded to 4-21%4 === 3 spaces. + // + this.bsCount = []; + + // block parser variables + + // required block content indent (for example, if we are + // inside a list, it would be positioned after list marker) + this.blkIndent = 0; + this.line = 0; // line index in src + this.lineMax = 0; // lines count + this.tight = false; // loose/tight mode for lists + this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) + this.listIndent = -1; // indent of the current list block (-1 if there isn't any) + + // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' + // used in lists to determine if they interrupt a paragraph + this.parentType = 'root'; + this.level = 0; + + // Create caches + // Generate markers. + const s = this.src; + for (let start = 0, pos = 0, indent = 0, offset = 0, len = s.length, indent_found = false; pos < len; pos++) { + const ch = s.charCodeAt(pos); + if (!indent_found) { + if (isSpace(ch)) { + indent++; + if (ch === 0x09) { + offset += 4 - offset % 4; + } else { + offset++; + } + continue; + } else { + indent_found = true; + } } - })); - Object.defineProperty(exports, "validateQuery", ({ - enumerable: true, - get: function () { - return _interface.validateQuery; + if (ch === 0x0A || pos === len - 1) { + if (ch !== 0x0A) { + pos++; + } + this.bMarks.push(start); + this.eMarks.push(pos); + this.tShift.push(indent); + this.sCount.push(offset); + this.bsCount.push(0); + indent_found = false; + indent = 0; + offset = 0; + start = pos + 1; } - })); - Object.defineProperty(exports, "validateWithCustomRules", ({ - enumerable: true, - get: function () { - return _utils.validateWithCustomRules; + } + + // Push fake entry to simplify cache bounds checks + this.bMarks.push(s.length); + this.eMarks.push(s.length); + this.tShift.push(0); + this.sCount.push(0); + this.bsCount.push(0); + this.lineMax = this.bMarks.length - 1; // don't count last fake line +} + +// Push new token to "stream". +// +StateBlock.prototype.push = function (type, tag, nesting) { + const token = new Token(type, tag, nesting); + token.block = true; + if (nesting < 0) this.level--; // closing tag + token.level = this.level; + if (nesting > 0) this.level++; // opening tag + + this.tokens.push(token); + return token; +}; +StateBlock.prototype.isEmpty = function isEmpty(line) { + return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; +}; +StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { + for (let max = this.lineMax; from < max; from++) { + if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { + break; } - })); - var _interface = __webpack_require__(/*! ./interface */ "../../graphql-language-service/esm/interface/index.js"); - var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); - var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/types.js"); - var _utils = __webpack_require__(/*! ./utils */ "../../graphql-language-service/esm/utils/index.js"); - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/autocompleteUtils.js": - /*!*************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/autocompleteUtils.js ***! - \*************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getInsertText = exports.getInputInsertText = exports.getFieldInsertText = void 0; - exports.hintList = hintList; - exports.objectValues = objectValues; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function objectValues(object) { - const keys = Object.keys(object); - const len = keys.length; - const values = new Array(len); - for (let i = 0; i < len; ++i) { - values[i] = object[keys[i]]; - } - return values; - } - function hintList(token, list) { - return filterAndSortList(list, normalizeText(token.string)); - } - function filterAndSortList(list, text) { - if (!text || text.trim() === '' || text.trim() === ':' || text.trim() === '{') { - return filterNonEmpty(list, entry => !entry.isDeprecated); - } - const byProximity = list.map(entry => ({ - proximity: getProximity(normalizeText(entry.label), text), - entry - })); - return filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated).sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.label.length - b.entry.label.length).map(pair => pair.entry); } - function filterNonEmpty(array, predicate) { - const filtered = array.filter(predicate); - return filtered.length === 0 ? array : filtered; + return from; +}; + +// Skip spaces from given position. +StateBlock.prototype.skipSpaces = function skipSpaces(pos) { + for (let max = this.src.length; pos < max; pos++) { + const ch = this.src.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } } - function normalizeText(text) { - return text.toLowerCase().replaceAll(/\W/g, ''); + return pos; +}; + +// Skip spaces from given position in reverse. +StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) { + if (pos <= min) { + return pos; } - function getProximity(suggestion, text) { - let proximity = lexicalDistance(text, suggestion); - if (suggestion.length > text.length) { - proximity -= suggestion.length - text.length - 1; - proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + while (pos > min) { + if (!isSpace(this.src.charCodeAt(--pos))) { + return pos + 1; } - return proximity; } - function lexicalDistance(a, b) { - let i; - let j; - const d = []; - const aLength = a.length; - const bLength = b.length; - for (i = 0; i <= aLength; i++) { - d[i] = [i]; + return pos; +}; + +// Skip char codes from given position +StateBlock.prototype.skipChars = function skipChars(pos, code) { + for (let max = this.src.length; pos < max; pos++) { + if (this.src.charCodeAt(pos) !== code) { + break; } - for (j = 1; j <= bLength; j++) { - d[0][j] = j; + } + return pos; +}; + +// Skip char codes reverse from given position - 1 +StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) { + if (pos <= min) { + return pos; + } + while (pos > min) { + if (code !== this.src.charCodeAt(--pos)) { + return pos + 1; } - for (i = 1; i <= aLength; i++) { - for (j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + return pos; +}; + +// cut lines range from source. +StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) { + if (begin >= end) { + return ''; + } + const queue = new Array(end - begin); + for (let i = 0, line = begin; line < end; line++, i++) { + let lineIndent = 0; + const lineStart = this.bMarks[line]; + let first = lineStart; + let last; + if (line + 1 < end || keepLastLF) { + // No need for bounds check because we have fake entry on tail. + last = this.eMarks[line] + 1; + } else { + last = this.eMarks[line]; + } + while (first < last && lineIndent < indent) { + const ch = this.src.charCodeAt(first); + if (isSpace(ch)) { + if (ch === 0x09) { + lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4; + } else { + lineIndent++; } + } else if (first - lineStart < this.tShift[line]) { + // patched tShift masked characters to look like spaces (blockquotes, list markers) + lineIndent++; + } else { + break; } + first++; + } + if (lineIndent > indent) { + // partially expanding tabs in code blocks, e.g '\t\tfoobar' + // with indent=2 becomes ' \tfoobar' + queue[i] = new Array(lineIndent - indent + 1).join(' ') + this.src.slice(first, last); + } else { + queue[i] = this.src.slice(first, last); } - return d[aLength][bLength]; } - const insertSuffix = n => ` {\n $${n !== null && n !== void 0 ? n : 1}\n}`; - const getInsertText = (prefix, type, fallback) => { - if (!type) { - return fallback !== null && fallback !== void 0 ? fallback : prefix; + return queue.join(''); +}; + +// re-export Token class to use in block rules +StateBlock.prototype.Token = Token; + +// GFM table, https://github.github.com/gfm/#tables-extension- + +// Limit the amount of empty autocompleted cells in a table, +// see https://github.com/markdown-it/markdown-it/issues/1000, +// +// Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k. +// We set it to 65k, which can expand user input by a factor of x370 +// (256x256 square is 1.8kB expanded into 650kB). +const MAX_AUTOCOMPLETED_CELLS = 0x10000; +function getLine(state, line) { + const pos = state.bMarks[line] + state.tShift[line]; + const max = state.eMarks[line]; + return state.src.slice(pos, max); +} +function escapedSplit(str) { + const result = []; + const max = str.length; + let pos = 0; + let ch = str.charCodeAt(pos); + let isEscaped = false; + let lastPos = 0; + let current = ''; + while (pos < max) { + if (ch === 0x7c /* | */) { + if (!isEscaped) { + // pipe separating cells, '|' + result.push(current + str.substring(lastPos, pos)); + current = ''; + lastPos = pos + 1; + } else { + // escaped pipe, '\|' + current += str.substring(lastPos, pos - 1); + lastPos = pos; + } } - const namedType = (0, _graphql.getNamedType)(type); - if ((0, _graphql.isObjectType)(namedType) || (0, _graphql.isInputObjectType)(namedType) || (0, _graphql.isListType)(namedType) || (0, _graphql.isAbstractType)(namedType)) { - return prefix + insertSuffix(); + isEscaped = ch === 0x5c /* \ */; + pos++; + ch = str.charCodeAt(pos); + } + result.push(current + str.substring(lastPos)); + return result; +} +function table(state, startLine, endLine, silent) { + // should have at least two lines + if (startLine + 2 > endLine) { + return false; + } + let nextLine = startLine + 1; + if (state.sCount[nextLine] < state.blkIndent) { + return false; + } + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + return false; + } + + // first character of the second line should be '|', '-', ':', + // and no other characters are allowed but spaces; + // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp + + let pos = state.bMarks[nextLine] + state.tShift[nextLine]; + if (pos >= state.eMarks[nextLine]) { + return false; + } + const firstCh = state.src.charCodeAt(pos++); + if (firstCh !== 0x7C /* | */ && firstCh !== 0x2D /* - */ && firstCh !== 0x3A /* : */) { + return false; + } + if (pos >= state.eMarks[nextLine]) { + return false; + } + const secondCh = state.src.charCodeAt(pos++); + if (secondCh !== 0x7C /* | */ && secondCh !== 0x2D /* - */ && secondCh !== 0x3A /* : */ && !isSpace(secondCh)) { + return false; + } + + // if first character is '-', then second character must not be a space + // (due to parsing ambiguity with list) + if (firstCh === 0x2D /* - */ && isSpace(secondCh)) { + return false; + } + while (pos < state.eMarks[nextLine]) { + const ch = state.src.charCodeAt(pos); + if (ch !== 0x7C /* | */ && ch !== 0x2D /* - */ && ch !== 0x3A /* : */ && !isSpace(ch)) { + return false; } - return fallback !== null && fallback !== void 0 ? fallback : prefix; - }; - exports.getInsertText = getInsertText; - const getInputInsertText = (prefix, type, fallback) => { - if ((0, _graphql.isListType)(type)) { - const baseType = (0, _graphql.getNamedType)(type.ofType); - return prefix + `[${getInsertText('', baseType, '$1')}]`; + pos++; + } + let lineText = getLine(state, startLine + 1); + let columns = lineText.split('|'); + const aligns = []; + for (let i = 0; i < columns.length; i++) { + const t = columns[i].trim(); + if (!t) { + // allow empty columns before and after table, but not in between columns; + // e.g. allow ` |---| `, disallow ` ---||--- ` + if (i === 0 || i === columns.length - 1) { + continue; + } else { + return false; + } } - return getInsertText(prefix, type, fallback); - }; - exports.getInputInsertText = getInputInsertText; - const getFieldInsertText = field => { - const requiredArgs = field.args.filter(arg => arg.type.toString().endsWith('!')); - if (!requiredArgs.length) { - return; + if (!/^:?-+:?$/.test(t)) { + return false; } - return field.name + `(${requiredArgs.map((arg, i) => `${arg.name}: $${i + 1}`)}) ${getInsertText('', field.type, '\n')}`; - }; - exports.getFieldInsertText = getFieldInsertText; - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js": - /*!**********************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js ***! - \**********************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.SuggestionCommand = void 0; - exports.canUseDirective = canUseDirective; - exports.getAutocompleteSuggestions = getAutocompleteSuggestions; - exports.getFragmentDefinitions = getFragmentDefinitions; - Object.defineProperty(exports, "getTypeInfo", ({ - enumerable: true, - get: function () { - return _parser.getTypeInfo; + if (t.charCodeAt(t.length - 1) === 0x3A /* : */) { + aligns.push(t.charCodeAt(0) === 0x3A /* : */ ? 'center' : 'right'); + } else if (t.charCodeAt(0) === 0x3A /* : */) { + aligns.push('left'); + } else { + aligns.push(''); } - })); - exports.getVariableCompletions = getVariableCompletions; - Object.defineProperty(exports, "runOnlineParser", ({ - enumerable: true, - get: function () { - return _parser.runOnlineParser; + } + lineText = getLine(state, startLine).trim(); + if (lineText.indexOf('|') === -1) { + return false; + } + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + columns = escapedSplit(lineText); + if (columns.length && columns[0] === '') columns.shift(); + if (columns.length && columns[columns.length - 1] === '') columns.pop(); + + // header row will define an amount of columns in the entire table, + // and align row should be exactly the same (the rest of the rows can differ) + const columnCount = columns.length; + if (columnCount === 0 || columnCount !== aligns.length) { + return false; + } + if (silent) { + return true; + } + const oldParentType = state.parentType; + state.parentType = 'table'; + + // use 'blockquote' lists for termination because it's + // the most similar to tables + const terminatorRules = state.md.block.ruler.getRules('blockquote'); + const token_to = state.push('table_open', 'table', 1); + const tableLines = [startLine, 0]; + token_to.map = tableLines; + const token_tho = state.push('thead_open', 'thead', 1); + token_tho.map = [startLine, startLine + 1]; + const token_htro = state.push('tr_open', 'tr', 1); + token_htro.map = [startLine, startLine + 1]; + for (let i = 0; i < columns.length; i++) { + const token_ho = state.push('th_open', 'th', 1); + if (aligns[i]) { + token_ho.attrs = [['style', 'text-align:' + aligns[i]]]; + } + const token_il = state.push('inline', '', 0); + token_il.content = columns[i].trim(); + token_il.children = []; + state.push('th_close', 'th', -1); + } + state.push('tr_close', 'tr', -1); + state.push('thead_close', 'thead', -1); + let tbodyLines; + let autocompletedCells = 0; + for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { + if (state.sCount[nextLine] < state.blkIndent) { + break; } - })); - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _types = __webpack_require__(/*! ../types */ "../../graphql-language-service/esm/types.js"); - var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); - var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); - var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); - const SuggestionCommand = exports.SuggestionCommand = { - command: 'editor.action.triggerSuggest', - title: 'Suggestions' - }; - const collectFragmentDefs = op => { - const externalFragments = []; - if (op) { - try { - (0, _graphql.visit)((0, _graphql.parse)(op), { - FragmentDefinition(def) { - externalFragments.push(def); - } - }); - } catch (_a) { - return []; + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; } } - return externalFragments; - }; - function getAutocompleteSuggestions(schema, queryText, cursor, contextToken, fragmentDefs, options) { - var _a; - const opts = Object.assign(Object.assign({}, options), { - schema - }); - const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken, options); - if (!context) { - return []; - } - const { - state, - typeInfo, - mode, - token - } = context; - const { - kind, - step, - prevState - } = state; - if (kind === _parser.RuleKinds.DOCUMENT) { - if (mode === _parser.GraphQLDocumentMode.TYPE_SYSTEM) { - return getSuggestionsForTypeSystemDefinitions(token); - } - if (mode === _parser.GraphQLDocumentMode.EXECUTABLE) { - return getSuggestionsForExecutableDefinitions(token); - } - return getSuggestionsForUnknownDocumentMode(token); + if (terminate) { + break; } - if (kind === _parser.RuleKinds.EXTEND_DEF) { - return getSuggestionsForExtensionDefinitions(token); + lineText = getLine(state, nextLine).trim(); + if (!lineText) { + break; } - if (((_a = prevState === null || prevState === void 0 ? void 0 : prevState.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.EXTENSION_DEFINITION && state.name) { - return (0, _autocompleteUtils.hintList)(token, []); + if (state.sCount[nextLine] - state.blkIndent >= 4) { + break; } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.SCALAR_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isScalarType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); + columns = escapedSplit(lineText); + if (columns.length && columns[0] === '') columns.shift(); + if (columns.length && columns[columns.length - 1] === '') columns.pop(); + + // note: autocomplete count can be negative if user specifies more columns than header, + // but that does not affect intended use (which is limiting expansion) + autocompletedCells += columnCount - columns.length; + if (autocompletedCells > MAX_AUTOCOMPLETED_CELLS) { + break; } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.OBJECT_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isObjectType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); + if (nextLine === startLine + 2) { + const token_tbo = state.push('tbody_open', 'tbody', 1); + token_tbo.map = tbodyLines = [startLine + 2, 0]; } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INTERFACE_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInterfaceType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); + const token_tro = state.push('tr_open', 'tr', 1); + token_tro.map = [nextLine, nextLine + 1]; + for (let i = 0; i < columnCount; i++) { + const token_tdo = state.push('td_open', 'td', 1); + if (aligns[i]) { + token_tdo.attrs = [['style', 'text-align:' + aligns[i]]]; + } + const token_il = state.push('inline', '', 0); + token_il.content = columns[i] ? columns[i].trim() : ''; + token_il.children = []; + state.push('td_close', 'td', -1); } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.UNION_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isUnionType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); + state.push('tr_close', 'tr', -1); + } + if (tbodyLines) { + state.push('tbody_close', 'tbody', -1); + tbodyLines[1] = nextLine; + } + state.push('table_close', 'table', -1); + tableLines[1] = nextLine; + state.parentType = oldParentType; + state.line = nextLine; + return true; +} + +// Code block (4 spaces padded) + +function code(state, startLine, endLine /*, silent */) { + if (state.sCount[startLine] - state.blkIndent < 4) { + return false; + } + let nextLine = startLine + 1; + let last = nextLine; + while (nextLine < endLine) { + if (state.isEmpty(nextLine)) { + nextLine++; + continue; } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.ENUM_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isEnumType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); + if (state.sCount[nextLine] - state.blkIndent >= 4) { + nextLine++; + last = nextLine; + continue; } - if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInputObjectType).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function - }))); + break; + } + state.line = last; + const token = state.push('code_block', 'code', 0); + token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + '\n'; + token.map = [startLine, state.line]; + return true; +} + +// fences (``` lang, ~~~ lang) + +function fence(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + if (pos + 3 > max) { + return false; + } + const marker = state.src.charCodeAt(pos); + if (marker !== 0x7E /* ~ */ && marker !== 0x60 /* ` */) { + return false; + } + + // scan marker length + let mem = pos; + pos = state.skipChars(pos, marker); + let len = pos - mem; + if (len < 3) { + return false; + } + const markup = state.src.slice(mem, pos); + const params = state.src.slice(pos, max); + if (marker === 0x60 /* ` */) { + if (params.indexOf(String.fromCharCode(marker)) >= 0) { + return false; } - if (kind === _parser.RuleKinds.IMPLEMENTS || kind === _parser.RuleKinds.NAMED_TYPE && (prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _parser.RuleKinds.IMPLEMENTS) { - return getSuggestionsForImplements(token, state, schema, queryText, typeInfo); + } + + // Since start is found, we can report success here in validation mode + if (silent) { + return true; + } + + // search end of block + let nextLine = startLine; + let haveEndMarker = false; + for (;;) { + nextLine++; + if (nextLine >= endLine) { + // unclosed block should be autoclosed by end of document. + // also block seems to be autoclosed by end of parent + break; } - if (kind === _parser.RuleKinds.SELECTION_SET || kind === _parser.RuleKinds.FIELD || kind === _parser.RuleKinds.ALIASED_FIELD) { - return getSuggestionsForFieldNames(token, typeInfo, opts); + pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + if (pos < max && state.sCount[nextLine] < state.blkIndent) { + // non-empty line with negative indent should stop the list: + // - ``` + // test + break; } - if (kind === _parser.RuleKinds.ARGUMENTS || kind === _parser.RuleKinds.ARGUMENT && step === 0) { - const { - argDefs - } = typeInfo; - if (argDefs) { - return (0, _autocompleteUtils.hintList)(token, argDefs.map(argDef => { - var _a; - return { - label: argDef.name, - insertText: (0, _autocompleteUtils.getInputInsertText)(argDef.name + ': ', argDef.type), - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - command: SuggestionCommand, - labelDetails: { - detail: ' ' + String(argDef.type) - }, - documentation: (_a = argDef.description) !== null && _a !== void 0 ? _a : undefined, - kind: _types.CompletionItemKind.Variable, - type: argDef.type - }; - })); - } + if (state.src.charCodeAt(pos) !== marker) { + continue; } - if ((kind === _parser.RuleKinds.OBJECT_VALUE || kind === _parser.RuleKinds.OBJECT_FIELD && step === 0) && typeInfo.objectFieldDefs) { - const objectFields = (0, _autocompleteUtils.objectValues)(typeInfo.objectFieldDefs); - const completionKind = kind === _parser.RuleKinds.OBJECT_VALUE ? _types.CompletionItemKind.Value : _types.CompletionItemKind.Field; - return (0, _autocompleteUtils.hintList)(token, objectFields.map(field => { - var _a; - return { - label: field.name, - detail: String(field.type), - documentation: (_a = field === null || field === void 0 ? void 0 : field.description) !== null && _a !== void 0 ? _a : undefined, - kind: completionKind, - type: field.type, - insertText: (0, _autocompleteUtils.getInputInsertText)(field.name + ': ', field.type), - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - command: SuggestionCommand - }; - })); + if (state.sCount[nextLine] - state.blkIndent >= 4) { + // closing fence should be indented less than 4 spaces + continue; } - if (kind === _parser.RuleKinds.ENUM_VALUE || kind === _parser.RuleKinds.LIST_VALUE && step === 1 || kind === _parser.RuleKinds.OBJECT_FIELD && step === 2 || kind === _parser.RuleKinds.ARGUMENT && step === 2) { - return getSuggestionsForInputValues(token, typeInfo, queryText, schema); + pos = state.skipChars(pos, marker); + + // closing code fence must be at least as long as the opening one + if (pos - mem < len) { + continue; } - if (kind === _parser.RuleKinds.VARIABLE && step === 1) { - const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); - const variableDefinitions = getVariableCompletions(queryText, schema, token); - return (0, _autocompleteUtils.hintList)(token, variableDefinitions.filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name))); + + // make sure tail has spaces only + pos = state.skipSpaces(pos); + if (pos < max) { + continue; } - if (kind === _parser.RuleKinds.TYPE_CONDITION && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState != null && prevState.kind === _parser.RuleKinds.TYPE_CONDITION) { - return getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, kind); + haveEndMarker = true; + // found! + break; + } + + // If a fence has heading spaces, they should be removed from its inner block + len = state.sCount[startLine]; + state.line = nextLine + (haveEndMarker ? 1 : 0); + const token = state.push('fence', 'code', 0); + token.info = params; + token.content = state.getLines(startLine + 1, nextLine, len, true); + token.markup = markup; + token.map = [startLine, state.line]; + return true; +} + +// Block quotes + +function blockquote(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + const oldLineMax = state.lineMax; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + + // check the block quote marker + if (state.src.charCodeAt(pos) !== 0x3E /* > */) { + return false; + } + + // we know that it's going to be a valid blockquote, + // so no point trying to find the end of it in silent mode + if (silent) { + return true; + } + const oldBMarks = []; + const oldBSCount = []; + const oldSCount = []; + const oldTShift = []; + const terminatorRules = state.md.block.ruler.getRules('blockquote'); + const oldParentType = state.parentType; + state.parentType = 'blockquote'; + let lastLineEmpty = false; + let nextLine; + + // Search the end of the block + // + // Block ends with either: + // 1. an empty line outside: + // ``` + // > test + // + // ``` + // 2. an empty line inside: + // ``` + // > + // test + // ``` + // 3. another tag: + // ``` + // > test + // - - - + // ``` + for (nextLine = startLine; nextLine < endLine; nextLine++) { + // check if it's outdented, i.e. it's inside list item and indented + // less than said list item: + // + // ``` + // 1. anything + // > current blockquote + // 2. checking this line + // ``` + const isOutdented = state.sCount[nextLine] < state.blkIndent; + pos = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + if (pos >= max) { + // Case 1: line is not inside the blockquote, and this line is empty. + break; } - if (kind === _parser.RuleKinds.FRAGMENT_SPREAD && step === 1) { - return getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, Array.isArray(fragmentDefs) ? fragmentDefs : collectFragmentDefs(fragmentDefs)); + if (state.src.charCodeAt(pos++) === 0x3E /* > */ && !isOutdented) { + // This line is inside the blockquote. + + // set offset past spaces and ">" + let initial = state.sCount[nextLine] + 1; + let spaceAfterMarker; + let adjustTab; + + // skip one optional space after '>' + if (state.src.charCodeAt(pos) === 0x20 /* space */) { + // ' > test ' + // ^ -- position start of line here: + pos++; + initial++; + adjustTab = false; + spaceAfterMarker = true; + } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { + spaceAfterMarker = true; + if ((state.bsCount[nextLine] + initial) % 4 === 3) { + // ' >\t test ' + // ^ -- position start of line here (tab has width===1) + pos++; + initial++; + adjustTab = false; + } else { + // ' >\t test ' + // ^ -- position start of line here + shift bsCount slightly + // to make extra space appear + adjustTab = true; + } + } else { + spaceAfterMarker = false; + } + let offset = initial; + oldBMarks.push(state.bMarks[nextLine]); + state.bMarks[nextLine] = pos; + while (pos < max) { + const ch = state.src.charCodeAt(pos); + if (isSpace(ch)) { + if (ch === 0x09) { + offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4; + } else { + offset++; + } + } else { + break; + } + pos++; + } + lastLineEmpty = pos >= max; + oldBSCount.push(state.bsCount[nextLine]); + state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); + oldSCount.push(state.sCount[nextLine]); + state.sCount[nextLine] = offset - initial; + oldTShift.push(state.tShift[nextLine]); + state.tShift[nextLine] = pos - state.bMarks[nextLine]; + continue; } - const unwrappedState = unwrapType(state); - if (unwrappedState.kind === _parser.RuleKinds.FIELD_DEF) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isOutputType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n' : type.name, - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation - }))); + + // Case 2: line is not inside the blockquote, and the last line was empty. + if (lastLineEmpty) { + break; } - if (unwrappedState.kind === _parser.RuleKinds.INPUT_VALUE_DEF && step === 2) { - return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isInputType)(type) && !type.name.startsWith('__')).map(type => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n$1' : type.name, - insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet - }))); + + // Case 3: another tag found. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } } - if (kind === _parser.RuleKinds.VARIABLE_DEFINITION && step === 2 || kind === _parser.RuleKinds.LIST_TYPE && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState && (prevState.kind === _parser.RuleKinds.VARIABLE_DEFINITION || prevState.kind === _parser.RuleKinds.LIST_TYPE || prevState.kind === _parser.RuleKinds.NON_NULL_TYPE)) { - return getSuggestionsForVariableDefinition(token, schema, kind); + if (terminate) { + // Quirk to enforce "hard termination mode" for paragraphs; + // normally if you call `tokenize(state, startLine, nextLine)`, + // paragraphs will look below nextLine for paragraph continuation, + // but if blockquote is terminated by another tag, they shouldn't + state.lineMax = nextLine; + if (state.blkIndent !== 0) { + // state.blkIndent was non-zero, we now set it to zero, + // so we need to re-calculate all offsets to appear as + // if indent wasn't changed + oldBMarks.push(state.bMarks[nextLine]); + oldBSCount.push(state.bsCount[nextLine]); + oldTShift.push(state.tShift[nextLine]); + oldSCount.push(state.sCount[nextLine]); + state.sCount[nextLine] -= state.blkIndent; + } + break; } - if (kind === _parser.RuleKinds.DIRECTIVE) { - return getSuggestionsForDirective(token, state, schema, kind); + oldBMarks.push(state.bMarks[nextLine]); + oldBSCount.push(state.bsCount[nextLine]); + oldTShift.push(state.tShift[nextLine]); + oldSCount.push(state.sCount[nextLine]); + + // A negative indentation means that this is a paragraph continuation + // + state.sCount[nextLine] = -1; + } + const oldIndent = state.blkIndent; + state.blkIndent = 0; + const token_o = state.push('blockquote_open', 'blockquote', 1); + token_o.markup = '>'; + const lines = [startLine, 0]; + token_o.map = lines; + state.md.block.tokenize(state, startLine, nextLine); + const token_c = state.push('blockquote_close', 'blockquote', -1); + token_c.markup = '>'; + state.lineMax = oldLineMax; + state.parentType = oldParentType; + lines[1] = state.line; + + // Restore original tShift; this might not be necessary since the parser + // has already been here, but just to make sure we can do that. + for (let i = 0; i < oldTShift.length; i++) { + state.bMarks[i + startLine] = oldBMarks[i]; + state.tShift[i + startLine] = oldTShift[i]; + state.sCount[i + startLine] = oldSCount[i]; + state.bsCount[i + startLine] = oldBSCount[i]; + } + state.blkIndent = oldIndent; + return true; +} + +// Horizontal rule + +function hr(state, startLine, endLine, silent) { + const max = state.eMarks[startLine]; + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; + } + let pos = state.bMarks[startLine] + state.tShift[startLine]; + const marker = state.src.charCodeAt(pos++); + + // Check hr marker + if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x5F /* _ */) { + return false; + } + + // markers can be mixed with spaces, but there should be at least 3 of them + + let cnt = 1; + while (pos < max) { + const ch = state.src.charCodeAt(pos++); + if (ch !== marker && !isSpace(ch)) { + return false; } - if (kind === _parser.RuleKinds.DIRECTIVE_DEF) { - return getSuggestionsForDirectiveArguments(token, state, schema, kind); + if (ch === marker) { + cnt++; } - return []; } - const typeSystemCompletionItems = [{ - label: 'type', - kind: _types.CompletionItemKind.Function - }, { - label: 'interface', - kind: _types.CompletionItemKind.Function - }, { - label: 'union', - kind: _types.CompletionItemKind.Function - }, { - label: 'input', - kind: _types.CompletionItemKind.Function - }, { - label: 'scalar', - kind: _types.CompletionItemKind.Function - }, { - label: 'schema', - kind: _types.CompletionItemKind.Function - }]; - const executableCompletionItems = [{ - label: 'query', - kind: _types.CompletionItemKind.Function - }, { - label: 'mutation', - kind: _types.CompletionItemKind.Function - }, { - label: 'subscription', - kind: _types.CompletionItemKind.Function - }, { - label: 'fragment', - kind: _types.CompletionItemKind.Function - }, { - label: '{', - kind: _types.CompletionItemKind.Constructor - }]; - function getSuggestionsForTypeSystemDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, [{ - label: 'extend', - kind: _types.CompletionItemKind.Function - }, ...typeSystemCompletionItems]); + if (cnt < 3) { + return false; } - function getSuggestionsForExecutableDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, executableCompletionItems); + if (silent) { + return true; } - function getSuggestionsForUnknownDocumentMode(token) { - return (0, _autocompleteUtils.hintList)(token, [{ - label: 'extend', - kind: _types.CompletionItemKind.Function - }, ...executableCompletionItems, ...typeSystemCompletionItems]); + state.line = startLine + 1; + const token = state.push('hr', 'hr', 0); + token.map = [startLine, state.line]; + token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); + return true; +} + +// Lists + +// Search `[-+*][\n ]`, returns next pos after marker on success +// or -1 on fail. +function skipBulletListMarker(state, startLine) { + const max = state.eMarks[startLine]; + let pos = state.bMarks[startLine] + state.tShift[startLine]; + const marker = state.src.charCodeAt(pos++); + // Check bullet + if (marker !== 0x2A /* * */ && marker !== 0x2D /* - */ && marker !== 0x2B /* + */) { + return -1; } - function getSuggestionsForExtensionDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, typeSystemCompletionItems); + if (pos < max) { + const ch = state.src.charCodeAt(pos); + if (!isSpace(ch)) { + // " -test " - is not a list item + return -1; + } } - function getSuggestionsForFieldNames(token, typeInfo, options) { - var _a; - if (typeInfo.parentType) { - const { - parentType - } = typeInfo; - let fields = []; - if ('getFields' in parentType) { - fields = (0, _autocompleteUtils.objectValues)(parentType.getFields()); - } - if ((0, _graphql.isCompositeType)(parentType)) { - fields.push(_graphql.TypeNameMetaFieldDef); - } - if (parentType === ((_a = options === null || options === void 0 ? void 0 : options.schema) === null || _a === void 0 ? void 0 : _a.getQueryType())) { - fields.push(_graphql.SchemaMetaFieldDef, _graphql.TypeMetaFieldDef); + return pos; +} + +// Search `\d+[.)][\n ]`, returns next pos after marker on success +// or -1 on fail. +function skipOrderedListMarker(state, startLine) { + const start = state.bMarks[startLine] + state.tShift[startLine]; + const max = state.eMarks[startLine]; + let pos = start; + + // List marker should have at least 2 chars (digit + dot) + if (pos + 1 >= max) { + return -1; + } + let ch = state.src.charCodeAt(pos++); + if (ch < 0x30 /* 0 */ || ch > 0x39 /* 9 */) { + return -1; + } + for (;;) { + // EOL -> fail + if (pos >= max) { + return -1; + } + ch = state.src.charCodeAt(pos++); + if (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) { + // List marker should have no more than 9 digits + // (prevents integer overflow in browsers) + if (pos - start >= 10) { + return -1; } - return (0, _autocompleteUtils.hintList)(token, fields.map((field, index) => { - var _a; - const suggestion = { - sortText: String(index) + field.name, - label: field.name, - detail: String(field.type), - documentation: (_a = field.description) !== null && _a !== void 0 ? _a : undefined, - deprecated: Boolean(field.deprecationReason), - isDeprecated: Boolean(field.deprecationReason), - deprecationReason: field.deprecationReason, - kind: _types.CompletionItemKind.Field, - labelDetails: { - detail: ' ' + field.type.toString() - }, - type: field.type - }; - if (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) { - suggestion.insertText = (0, _autocompleteUtils.getFieldInsertText)(field); - if (!suggestion.insertText) { - suggestion.insertText = (0, _autocompleteUtils.getInsertText)(field.name, field.type, field.name + (token.state.needsAdvance ? '' : '\n')); - } - if (suggestion.insertText) { - suggestion.insertTextFormat = _types.InsertTextFormat.Snippet; - suggestion.insertTextMode = _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation; - suggestion.command = SuggestionCommand; - } - } - return suggestion; - })); + continue; } - return []; + + // found valid marker + if (ch === 0x29 /* ) */ || ch === 0x2e /* . */) { + break; + } + return -1; } - function getSuggestionsForInputValues(token, typeInfo, queryText, schema) { - const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); - const queryVariables = getVariableCompletions(queryText, schema, token).filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name)); - if (namedInputType instanceof _graphql.GraphQLEnumType) { - const values = namedInputType.getValues(); - return (0, _autocompleteUtils.hintList)(token, values.map(value => { - var _a; - return { - label: value.name, - detail: String(namedInputType), - documentation: (_a = value.description) !== null && _a !== void 0 ? _a : undefined, - deprecated: Boolean(value.deprecationReason), - isDeprecated: Boolean(value.deprecationReason), - deprecationReason: value.deprecationReason, - kind: _types.CompletionItemKind.EnumMember, - type: namedInputType - }; - }).concat(queryVariables)); - } - if (namedInputType === _graphql.GraphQLBoolean) { - return (0, _autocompleteUtils.hintList)(token, queryVariables.concat([{ - label: 'true', - detail: String(_graphql.GraphQLBoolean), - documentation: 'Not false.', - kind: _types.CompletionItemKind.Variable, - type: _graphql.GraphQLBoolean - }, { - label: 'false', - detail: String(_graphql.GraphQLBoolean), - documentation: 'Not true.', - kind: _types.CompletionItemKind.Variable, - type: _graphql.GraphQLBoolean - }])); + if (pos < max) { + ch = state.src.charCodeAt(pos); + if (!isSpace(ch)) { + // " 1.test " - is not a list item + return -1; } - return queryVariables; } - function getSuggestionsForImplements(token, tokenState, schema, documentText, typeInfo) { - if (tokenState.needsSeparator) { - return []; + return pos; +} +function markTightParagraphs(state, idx) { + const level = state.level + 2; + for (let i = idx + 2, l = state.tokens.length - 2; i < l; i++) { + if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') { + state.tokens[i + 2].hidden = true; + state.tokens[i].hidden = true; + i += 2; + } + } +} +function list(state, startLine, endLine, silent) { + let max, pos, start, token; + let nextLine = startLine; + let tight = true; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + return false; + } + + // Special case: + // - item 1 + // - item 2 + // - item 3 + // - item 4 + // - this one is a paragraph continuation + if (state.listIndent >= 0 && state.sCount[nextLine] - state.listIndent >= 4 && state.sCount[nextLine] < state.blkIndent) { + return false; + } + let isTerminatingParagraph = false; + + // limit conditions when list can interrupt + // a paragraph (validation mode only) + if (silent && state.parentType === 'paragraph') { + // Next list item should still terminate previous list item; + // + // This code can fail if plugins use blkIndent as well as lists, + // but I hope the spec gets fixed long before that happens. + // + if (state.sCount[nextLine] >= state.blkIndent) { + isTerminatingParagraph = true; } - const typeMap = schema.getTypeMap(); - const schemaInterfaces = (0, _autocompleteUtils.objectValues)(typeMap).filter(_graphql.isInterfaceType); - const schemaInterfaceNames = schemaInterfaces.map(({ - name - }) => name); - const inlineInterfaces = new Set(); - (0, _parser.runOnlineParser)(documentText, (_, state) => { - var _a, _b, _c, _d, _e; - if (state.name) { - if (state.kind === _parser.RuleKinds.INTERFACE_DEF && !schemaInterfaceNames.includes(state.name)) { - inlineInterfaces.add(state.name); - } - if (state.kind === _parser.RuleKinds.NAMED_TYPE && ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.IMPLEMENTS) { - if (typeInfo.interfaceDef) { - const existingType = (_b = typeInfo.interfaceDef) === null || _b === void 0 ? void 0 : _b.getInterfaces().find(({ - name - }) => name === state.name); - if (existingType) { - return; - } - const type = schema.getType(state.name); - const interfaceConfig = (_c = typeInfo.interfaceDef) === null || _c === void 0 ? void 0 : _c.toConfig(); - typeInfo.interfaceDef = new _graphql.GraphQLInterfaceType(Object.assign(Object.assign({}, interfaceConfig), { - interfaces: [...interfaceConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ - name: state.name, - fields: {} - })] - })); - } else if (typeInfo.objectTypeDef) { - const existingType = (_d = typeInfo.objectTypeDef) === null || _d === void 0 ? void 0 : _d.getInterfaces().find(({ - name - }) => name === state.name); - if (existingType) { - return; - } - const type = schema.getType(state.name); - const objectTypeConfig = (_e = typeInfo.objectTypeDef) === null || _e === void 0 ? void 0 : _e.toConfig(); - typeInfo.objectTypeDef = new _graphql.GraphQLObjectType(Object.assign(Object.assign({}, objectTypeConfig), { - interfaces: [...objectTypeConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ - name: state.name, - fields: {} - })] - })); - } - } - } - }); - const currentTypeToExtend = typeInfo.interfaceDef || typeInfo.objectTypeDef; - const siblingInterfaces = (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.getInterfaces()) || []; - const siblingInterfaceNames = siblingInterfaces.map(({ - name - }) => name); - const possibleInterfaces = schemaInterfaces.concat([...inlineInterfaces].map(name => ({ - name - }))).filter(({ - name - }) => name !== (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.name) && !siblingInterfaceNames.includes(name)); - return (0, _autocompleteUtils.hintList)(token, possibleInterfaces.map(type => { - const result = { - label: type.name, - kind: _types.CompletionItemKind.Interface, - type - }; - if (type === null || type === void 0 ? void 0 : type.description) { - result.documentation = type.description; - } - return result; - })); } - function getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, _kind) { - let possibleTypes; - if (typeInfo.parentType) { - if ((0, _graphql.isAbstractType)(typeInfo.parentType)) { - const abstractType = (0, _graphql.assertAbstractType)(typeInfo.parentType); - const possibleObjTypes = schema.getPossibleTypes(abstractType); - const possibleIfaceMap = Object.create(null); - for (const type of possibleObjTypes) { - for (const iface of type.getInterfaces()) { - possibleIfaceMap[iface.name] = iface; - } - } - possibleTypes = possibleObjTypes.concat((0, _autocompleteUtils.objectValues)(possibleIfaceMap)); + + // Detect list type and position after marker + let isOrdered; + let markerValue; + let posAfterMarker; + if ((posAfterMarker = skipOrderedListMarker(state, nextLine)) >= 0) { + isOrdered = true; + start = state.bMarks[nextLine] + state.tShift[nextLine]; + markerValue = Number(state.src.slice(start, posAfterMarker - 1)); + + // If we're starting a new ordered list right after + // a paragraph, it should start with 1. + if (isTerminatingParagraph && markerValue !== 1) return false; + } else if ((posAfterMarker = skipBulletListMarker(state, nextLine)) >= 0) { + isOrdered = false; + } else { + return false; + } + + // If we're starting a new unordered list right after + // a paragraph, first line should not be empty. + if (isTerminatingParagraph) { + if (state.skipSpaces(posAfterMarker) >= state.eMarks[nextLine]) return false; + } + + // For validation mode we can terminate immediately + if (silent) { + return true; + } + + // We should terminate list on style change. Remember first one to compare. + const markerCharCode = state.src.charCodeAt(posAfterMarker - 1); + + // Start list + const listTokIdx = state.tokens.length; + if (isOrdered) { + token = state.push('ordered_list_open', 'ol', 1); + if (markerValue !== 1) { + token.attrs = [['start', markerValue]]; + } + } else { + token = state.push('bullet_list_open', 'ul', 1); + } + const listLines = [nextLine, 0]; + token.map = listLines; + token.markup = String.fromCharCode(markerCharCode); + + // + // Iterate list items + // + + let prevEmptyEnd = false; + const terminatorRules = state.md.block.ruler.getRules('list'); + const oldParentType = state.parentType; + state.parentType = 'list'; + while (nextLine < endLine) { + pos = posAfterMarker; + max = state.eMarks[nextLine]; + const initial = state.sCount[nextLine] + posAfterMarker - (state.bMarks[nextLine] + state.tShift[nextLine]); + let offset = initial; + while (pos < max) { + const ch = state.src.charCodeAt(pos); + if (ch === 0x09) { + offset += 4 - (offset + state.bsCount[nextLine]) % 4; + } else if (ch === 0x20) { + offset++; } else { - possibleTypes = [typeInfo.parentType]; + break; } + pos++; + } + const contentStart = pos; + let indentAfterMarker; + if (contentStart >= max) { + // trimming space in "- \n 3" case, indent is 1 here + indentAfterMarker = 1; } else { - const typeMap = schema.getTypeMap(); - possibleTypes = (0, _autocompleteUtils.objectValues)(typeMap).filter(type => (0, _graphql.isCompositeType)(type) && !type.name.startsWith('__')); + indentAfterMarker = offset - initial; } - return (0, _autocompleteUtils.hintList)(token, possibleTypes.map(type => { - const namedType = (0, _graphql.getNamedType)(type); - return { - label: String(type), - documentation: (namedType === null || namedType === void 0 ? void 0 : namedType.description) || '', - kind: _types.CompletionItemKind.Field - }; - })); - } - function getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, fragmentDefs) { - if (!queryText) { - return []; + + // If we have more than 4 spaces, the indent is 1 + // (the rest is just indented code block) + if (indentAfterMarker > 4) { + indentAfterMarker = 1; } - const typeMap = schema.getTypeMap(); - const defState = (0, _parser.getDefinitionState)(token.state); - const fragments = getFragmentDefinitions(queryText); - if (fragmentDefs && fragmentDefs.length > 0) { - fragments.push(...fragmentDefs); - } - const relevantFrags = fragments.filter(frag => typeMap[frag.typeCondition.name.value] && !(defState && defState.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && defState.name === frag.name.value) && (0, _graphql.isCompositeType)(typeInfo.parentType) && (0, _graphql.isCompositeType)(typeMap[frag.typeCondition.name.value]) && (0, _graphql.doTypesOverlap)(schema, typeInfo.parentType, typeMap[frag.typeCondition.name.value])); - return (0, _autocompleteUtils.hintList)(token, relevantFrags.map(frag => ({ - label: frag.name.value, - detail: String(typeMap[frag.typeCondition.name.value]), - documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, - labelDetails: { - detail: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}` - }, - kind: _types.CompletionItemKind.Field, - type: typeMap[frag.typeCondition.name.value] - }))); - } - const getParentDefinition = (state, kind) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - if (((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === kind) { - return state.prevState; + + // " - test" + // ^^^^^ - calculating total length of this thing + const indent = initial + indentAfterMarker; + + // Run subparser & write tokens + token = state.push('list_item_open', 'li', 1); + token.markup = String.fromCharCode(markerCharCode); + const itemLines = [nextLine, 0]; + token.map = itemLines; + if (isOrdered) { + token.info = state.src.slice(start, posAfterMarker - 1); + } + + // change current state, then restore it after parser subcall + const oldTight = state.tight; + const oldTShift = state.tShift[nextLine]; + const oldSCount = state.sCount[nextLine]; + + // - example list + // ^ listIndent position will be here + // ^ blkIndent position will be here + // + const oldListIndent = state.listIndent; + state.listIndent = state.blkIndent; + state.blkIndent = indent; + state.tight = true; + state.tShift[nextLine] = contentStart - state.bMarks[nextLine]; + state.sCount[nextLine] = offset; + if (contentStart >= max && state.isEmpty(nextLine + 1)) { + // workaround for this case + // (list item is empty, list terminates before "foo"): + // ~~~~~~~~ + // - + // + // foo + // ~~~~~~~~ + state.line = Math.min(state.line + 2, endLine); + } else { + state.md.block.tokenize(state, nextLine, endLine, true); } - if (((_c = (_b = state.prevState) === null || _b === void 0 ? void 0 : _b.prevState) === null || _c === void 0 ? void 0 : _c.kind) === kind) { - return state.prevState.prevState; + + // If any of list item is tight, mark list as tight + if (!state.tight || prevEmptyEnd) { + tight = false; + } + // Item become loose if finish with empty line, + // but we should filter last element, because it means list finish + prevEmptyEnd = state.line - nextLine > 1 && state.isEmpty(state.line - 1); + state.blkIndent = state.listIndent; + state.listIndent = oldListIndent; + state.tShift[nextLine] = oldTShift; + state.sCount[nextLine] = oldSCount; + state.tight = oldTight; + token = state.push('list_item_close', 'li', -1); + token.markup = String.fromCharCode(markerCharCode); + nextLine = state.line; + itemLines[1] = nextLine; + if (nextLine >= endLine) { + break; } - if (((_f = (_e = (_d = state.prevState) === null || _d === void 0 ? void 0 : _d.prevState) === null || _e === void 0 ? void 0 : _e.prevState) === null || _f === void 0 ? void 0 : _f.kind) === kind) { - return state.prevState.prevState.prevState; + + // + // Try to check if list is terminated or continued. + // + if (state.sCount[nextLine] < state.blkIndent) { + break; } - if (((_k = (_j = (_h = (_g = state.prevState) === null || _g === void 0 ? void 0 : _g.prevState) === null || _h === void 0 ? void 0 : _h.prevState) === null || _j === void 0 ? void 0 : _j.prevState) === null || _k === void 0 ? void 0 : _k.kind) === kind) { - return state.prevState.prevState.prevState.prevState; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[nextLine] - state.blkIndent >= 4) { + break; } - }; - function getVariableCompletions(queryText, schema, token) { - let variableName = null; - let variableType; - const definitions = Object.create({}); - (0, _parser.runOnlineParser)(queryText, (_, state) => { - var _a; - if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.VARIABLE && state.name) { - variableName = state.name; - } - if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.NAMED_TYPE && variableName) { - const parentDefinition = getParentDefinition(state, _parser.RuleKinds.TYPE); - if (parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type) { - variableType = schema.getType(parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type); - } - } - if (variableName && variableType && !definitions[variableName]) { - const replaceString = token.string === '$' || ((_a = token === null || token === void 0 ? void 0 : token.state) === null || _a === void 0 ? void 0 : _a.kind) === 'Variable' ? variableName : '$' + variableName; - definitions[variableName] = { - detail: variableType.toString(), - insertText: replaceString, - label: '$' + variableName, - rawInsert: replaceString, - type: variableType, - kind: _types.CompletionItemKind.Variable - }; - variableName = null; - variableType = null; + + // fail if terminating block found + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; } - }); - return (0, _autocompleteUtils.objectValues)(definitions); - } - function getFragmentDefinitions(queryText) { - const fragmentDefs = []; - (0, _parser.runOnlineParser)(queryText, (_, state) => { - if (state.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && state.name && state.type) { - fragmentDefs.push({ - kind: _parser.RuleKinds.FRAGMENT_DEFINITION, - name: { - kind: _graphql.Kind.NAME, - value: state.name - }, - selectionSet: { - kind: _parser.RuleKinds.SELECTION_SET, - selections: [] - }, - typeCondition: { - kind: _parser.RuleKinds.NAMED_TYPE, - name: { - kind: _graphql.Kind.NAME, - value: state.type - } - } - }); + } + if (terminate) { + break; + } + + // fail if list has another type + if (isOrdered) { + posAfterMarker = skipOrderedListMarker(state, nextLine); + if (posAfterMarker < 0) { + break; + } + start = state.bMarks[nextLine] + state.tShift[nextLine]; + } else { + posAfterMarker = skipBulletListMarker(state, nextLine); + if (posAfterMarker < 0) { + break; } - }); - return fragmentDefs; - } - function getSuggestionsForVariableDefinition(token, schema, _kind) { - const inputTypeMap = schema.getTypeMap(); - const inputTypes = (0, _autocompleteUtils.objectValues)(inputTypeMap).filter(_graphql.isInputType); - return (0, _autocompleteUtils.hintList)(token, inputTypes.map(type => ({ - label: type.name, - documentation: (type === null || type === void 0 ? void 0 : type.description) || '', - kind: _types.CompletionItemKind.Variable - }))); - } - function getSuggestionsForDirective(token, state, schema, _kind) { - var _a; - if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) { - const directives = schema.getDirectives().filter(directive => canUseDirective(state.prevState, directive)); - return (0, _autocompleteUtils.hintList)(token, directives.map(directive => ({ - label: directive.name, - documentation: (directive === null || directive === void 0 ? void 0 : directive.description) || '', - kind: _types.CompletionItemKind.Function - }))); } - return []; + if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { + break; + } } - function getSuggestionsForDirectiveArguments(token, state, schema, _kind) { - const directive = schema.getDirectives().find(d => d.name === state.name); - return (0, _autocompleteUtils.hintList)(token, (directive === null || directive === void 0 ? void 0 : directive.args.map(arg => ({ - label: arg.name, - documentation: arg.description || '', - kind: _types.CompletionItemKind.Field - }))) || []); + + // Finalize list + if (isOrdered) { + token = state.push('ordered_list_close', 'ol', -1); + } else { + token = state.push('bullet_list_close', 'ul', -1); + } + token.markup = String.fromCharCode(markerCharCode); + listLines[1] = nextLine; + state.line = nextLine; + state.parentType = oldParentType; + + // mark paragraphs tight if needed + if (tight) { + markTightParagraphs(state, listTokIdx); + } + return true; +} +function reference(state, startLine, _endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + let nextLine = startLine + 1; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; } - function canUseDirective(state, directive) { - if (!(state === null || state === void 0 ? void 0 : state.kind)) { - return false; - } - const { - kind, - prevState - } = state; - const { - locations - } = directive; - switch (kind) { - case _parser.RuleKinds.QUERY: - return locations.includes(_graphql.DirectiveLocation.QUERY); - case _parser.RuleKinds.MUTATION: - return locations.includes(_graphql.DirectiveLocation.MUTATION); - case _parser.RuleKinds.SUBSCRIPTION: - return locations.includes(_graphql.DirectiveLocation.SUBSCRIPTION); - case _parser.RuleKinds.FIELD: - case _parser.RuleKinds.ALIASED_FIELD: - return locations.includes(_graphql.DirectiveLocation.FIELD); - case _parser.RuleKinds.FRAGMENT_DEFINITION: - return locations.includes(_graphql.DirectiveLocation.FRAGMENT_DEFINITION); - case _parser.RuleKinds.FRAGMENT_SPREAD: - return locations.includes(_graphql.DirectiveLocation.FRAGMENT_SPREAD); - case _parser.RuleKinds.INLINE_FRAGMENT: - return locations.includes(_graphql.DirectiveLocation.INLINE_FRAGMENT); - case _parser.RuleKinds.SCHEMA_DEF: - return locations.includes(_graphql.DirectiveLocation.SCHEMA); - case _parser.RuleKinds.SCALAR_DEF: - return locations.includes(_graphql.DirectiveLocation.SCALAR); - case _parser.RuleKinds.OBJECT_TYPE_DEF: - return locations.includes(_graphql.DirectiveLocation.OBJECT); - case _parser.RuleKinds.FIELD_DEF: - return locations.includes(_graphql.DirectiveLocation.FIELD_DEFINITION); - case _parser.RuleKinds.INTERFACE_DEF: - return locations.includes(_graphql.DirectiveLocation.INTERFACE); - case _parser.RuleKinds.UNION_DEF: - return locations.includes(_graphql.DirectiveLocation.UNION); - case _parser.RuleKinds.ENUM_DEF: - return locations.includes(_graphql.DirectiveLocation.ENUM); - case _parser.RuleKinds.ENUM_VALUE: - return locations.includes(_graphql.DirectiveLocation.ENUM_VALUE); - case _parser.RuleKinds.INPUT_DEF: - return locations.includes(_graphql.DirectiveLocation.INPUT_OBJECT); - case _parser.RuleKinds.INPUT_VALUE_DEF: - const prevStateKind = prevState === null || prevState === void 0 ? void 0 : prevState.kind; - switch (prevStateKind) { - case _parser.RuleKinds.ARGUMENTS_DEF: - return locations.includes(_graphql.DirectiveLocation.ARGUMENT_DEFINITION); - case _parser.RuleKinds.INPUT_DEF: - return locations.includes(_graphql.DirectiveLocation.INPUT_FIELD_DEFINITION); - } - } + if (state.src.charCodeAt(pos) !== 0x5B /* [ */) { return false; } - function unwrapType(state) { - if (state.prevState && state.kind && [_parser.RuleKinds.NAMED_TYPE, _parser.RuleKinds.LIST_TYPE, _parser.RuleKinds.TYPE, _parser.RuleKinds.NON_NULL_TYPE].includes(state.kind)) { - return unwrapType(state.prevState); + function getNextLine(nextLine) { + const endLine = state.lineMax; + if (nextLine >= endLine || state.isEmpty(nextLine)) { + // empty line or end of input + return null; } - return state; - } - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/getDefinition.js": - /*!*********************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getDefinition.js ***! - \*********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.LANGUAGE = void 0; - exports.getDefinitionQueryResultForArgument = getDefinitionQueryResultForArgument; - exports.getDefinitionQueryResultForDefinitionNode = getDefinitionQueryResultForDefinitionNode; - exports.getDefinitionQueryResultForField = getDefinitionQueryResultForField; - exports.getDefinitionQueryResultForFragmentSpread = getDefinitionQueryResultForFragmentSpread; - exports.getDefinitionQueryResultForNamedType = getDefinitionQueryResultForNamedType; - var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); - var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function (resolve) { - resolve(value); - }); + let isContinuation = false; + + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + isContinuation = true; } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + isContinuation = true; + } + if (!isContinuation) { + const terminatorRules = state.md.block.ruler.getRules('reference'); + const oldParentType = state.parentType; + state.parentType = 'reference'; + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; } } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + state.parentType = oldParentType; + if (terminate) { + // terminated by another block + return null; } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + const pos = state.bMarks[nextLine] + state.tShift[nextLine]; + const max = state.eMarks[nextLine]; + + // max + 1 explicitly includes the newline + return state.src.slice(pos, max + 1); + } + let str = state.src.slice(pos, max + 1); + max = str.length; + let labelEnd = -1; + for (pos = 1; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x5B /* [ */) { + return false; + } else if (ch === 0x5D /* ] */) { + labelEnd = pos; + break; + } else if (ch === 0x0A /* \n */) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } + } else if (ch === 0x5C /* \ */) { + pos++; + if (pos < max && str.charCodeAt(pos) === 0x0A) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - const LANGUAGE = exports.LANGUAGE = 'GraphQL'; - function assert(value, message) { - if (!value) { - throw new Error(message); } } - function getRange(text, node) { - const location = node.loc; - assert(location, 'Expected ASTNode to have a location.'); - return (0, _utils.locToRange)(text, location); + if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A /* : */) { + return false; } - function getPosition(text, node) { - const location = node.loc; - assert(location, 'Expected ASTNode to have a location.'); - return (0, _utils.offsetToPosition)(text, location.start); + + // [label]: destination 'title' + // ^^^ skip optional whitespace here + for (pos = labelEnd + 2; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x0A) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; + } + } else if (isSpace(ch)) ;else { + break; + } } - function getDefinitionQueryResultForNamedType(text, node, dependencies) { - return __awaiter(this, void 0, void 0, function* () { - const name = node.name.value; - const defNodes = dependencies.filter(({ - definition - }) => definition.name && definition.name.value === name); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL type ${name}`); - } - const definitions = defNodes.map(({ - filePath, - content, - definition - }) => getDefinitionForNodeDefinition(filePath || '', content, definition)); - return { - definitions, - queryRange: definitions.map(_ => getRange(text, node)), - printedName: name - }; - }); + + // [label]: destination 'title' + // ^^^^^^^^^^^ parse this + const destRes = state.md.helpers.parseLinkDestination(str, pos, max); + if (!destRes.ok) { + return false; } - function getDefinitionQueryResultForField(fieldName, typeName, dependencies) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const defNodes = dependencies.filter(({ - definition - }) => definition.name && definition.name.value === typeName); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL type ${typeName}`); - } - const definitions = []; - for (const { - filePath, - content, - definition - } of defNodes) { - const fieldDefinition = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName); - if (fieldDefinition == null) { - continue; - } - definitions.push(getDefinitionForFieldDefinition(filePath || '', content, fieldDefinition)); + const href = state.md.normalizeLink(destRes.str); + if (!state.md.validateLink(href)) { + return false; + } + pos = destRes.pos; + + // save cursor state, we could require to rollback later + const destEndPos = pos; + const destEndLineNo = nextLine; + + // [label]: destination 'title' + // ^^^ skipping those spaces + const start = pos; + for (; pos < max; pos++) { + const ch = str.charCodeAt(pos); + if (ch === 0x0A) { + const lineContent = getNextLine(nextLine); + if (lineContent !== null) { + str += lineContent; + max = str.length; + nextLine++; } - return { - definitions, - queryRange: [], - printedName: [typeName, fieldName].join('.') - }; - }); + } else if (isSpace(ch)) ;else { + break; + } } - function getDefinitionQueryResultForArgument(argumentName, fieldName, typeName, dependencies) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const definitions = []; - for (const { - filePath, - content, - definition - } of dependencies) { - const argDefinition = (_c = (_b = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName)) === null || _b === void 0 ? void 0 : _b.arguments) === null || _c === void 0 ? void 0 : _c.find(item => item.name.value === argumentName); - if (argDefinition == null) { - continue; + + // [label]: destination 'title' + // ^^^^^^^ parse this + let titleRes = state.md.helpers.parseLinkTitle(str, pos, max); + while (titleRes.can_continue) { + const lineContent = getNextLine(nextLine); + if (lineContent === null) break; + str += lineContent; + pos = max; + max = str.length; + nextLine++; + titleRes = state.md.helpers.parseLinkTitle(str, pos, max, titleRes); + } + let title; + if (pos < max && start !== pos && titleRes.ok) { + title = titleRes.str; + pos = titleRes.pos; + } else { + title = ''; + pos = destEndPos; + nextLine = destEndLineNo; + } + + // skip trailing spaces until the rest of the line + while (pos < max) { + const ch = str.charCodeAt(pos); + if (!isSpace(ch)) { + break; + } + pos++; + } + if (pos < max && str.charCodeAt(pos) !== 0x0A) { + if (title) { + // garbage at the end of the line after title, + // but it could still be a valid reference if we roll back + title = ''; + pos = destEndPos; + nextLine = destEndLineNo; + while (pos < max) { + const ch = str.charCodeAt(pos); + if (!isSpace(ch)) { + break; } - definitions.push(getDefinitionForArgumentDefinition(filePath || '', content, argDefinition)); + pos++; } - return { - definitions, - queryRange: [], - printedName: `${[typeName, fieldName].join('.')}(${argumentName})` - }; - }); + } } - function getDefinitionQueryResultForFragmentSpread(text, fragment, dependencies) { - return __awaiter(this, void 0, void 0, function* () { - const name = fragment.name.value; - const defNodes = dependencies.filter(({ - definition - }) => definition.name.value === name); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL fragment ${name}`); - } - const definitions = defNodes.map(({ - filePath, - content, - definition - }) => getDefinitionForFragmentDefinition(filePath || '', content, definition)); - return { - definitions, - queryRange: definitions.map(_ => getRange(text, fragment)), - printedName: name - }; - }); + if (pos < max && str.charCodeAt(pos) !== 0x0A) { + // garbage at the end of the line + return false; } - function getDefinitionQueryResultForDefinitionNode(path, text, definition) { - var _a; - return { - definitions: [getDefinitionForFragmentDefinition(path, text, definition)], - queryRange: definition.name ? [getRange(text, definition.name)] : [], - printedName: (_a = definition.name) === null || _a === void 0 ? void 0 : _a.value - }; + const label = normalizeReference(str.slice(1, labelEnd)); + if (!label) { + // CommonMark 0.20 disallows empty labels + return false; } - function getDefinitionForFragmentDefinition(path, text, definition) { - const { - name - } = definition; - if (!name) { - throw new Error('Expected ASTNode to have a Name.'); - } - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; + + // Reference can not terminate anything. This check is for safety only. + /* istanbul ignore if */ + if (silent) { + return true; } - function getDefinitionForNodeDefinition(path, text, definition) { - const { - name - } = definition; - assert(name, 'Expected ASTNode to have a Name.'); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; + if (typeof state.env.references === 'undefined') { + state.env.references = {}; } - function getDefinitionForFieldDefinition(path, text, definition) { - const { - name - } = definition; - assert(name, 'Expected ASTNode to have a Name.'); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path + if (typeof state.env.references[label] === 'undefined') { + state.env.references[label] = { + title, + href }; } - function getDefinitionForArgumentDefinition(path, text, definition) { - const { - name - } = definition; - assert(name, 'Expected ASTNode to have a Name.'); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || '', - language: LANGUAGE, - projectRoot: path - }; + state.line = nextLine; + return true; +} + +// List of valid html blocks names, according to commonmark spec +// https://spec.commonmark.org/0.30/#html-blocks + +var block_names = ['address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu', 'menuitem', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'search', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul']; + +// Regexps to match html elements + +const attr_name = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; +const unquoted = '[^"\'=<>`\\x00-\\x20]+'; +const single_quoted = "'[^']*'"; +const double_quoted = '"[^"]*"'; +const attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')'; +const attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)'; +const open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; +const close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; +const comment = ''; +const processing = '<[?][\\s\\S]*?[?]>'; +const declaration = ']*>'; +const cdata = ''; +const HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment + '|' + processing + '|' + declaration + '|' + cdata + ')'); +const HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')'); + +// HTML block + +// An array of opening and corresponding closing sequences for html tags, +// last argument defines whether it can terminate a paragraph or not +// +const HTML_SEQUENCES = [[/^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true], [/^/, true], [/^<\?/, /\?>/, true], [/^/, true], [/^/, true], [new RegExp('^|$))', 'i'), /^$/, true], [new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false]]; +function html_block(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/getDiagnostics.js": - /*!**********************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getDiagnostics.js ***! - \**********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.SEVERITY = exports.DIAGNOSTIC_SEVERITY = void 0; - exports.getDiagnostics = getDiagnostics; - exports.getRange = getRange; - exports.validateQuery = validateQuery; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); - var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); - const SEVERITY = exports.SEVERITY = { - Error: 'Error', - Warning: 'Warning', - Information: 'Information', - Hint: 'Hint' - }; - const DIAGNOSTIC_SEVERITY = exports.DIAGNOSTIC_SEVERITY = { - [SEVERITY.Error]: 1, - [SEVERITY.Warning]: 2, - [SEVERITY.Information]: 3, - [SEVERITY.Hint]: 4 - }; - const invariant = (condition, message) => { - if (!condition) { - throw new Error(message); - } - }; - function getDiagnostics(query, schema = null, customRules, isRelayCompatMode, externalFragments) { - var _a, _b; - let ast = null; - let fragments = ''; - if (externalFragments) { - fragments = typeof externalFragments === 'string' ? externalFragments : externalFragments.reduce((acc, node) => acc + (0, _graphql.print)(node) + '\n\n', ''); - } - const enhancedQuery = fragments ? `${query}\n\n${fragments}` : query; - try { - ast = (0, _graphql.parse)(enhancedQuery); - } catch (error) { - if (error instanceof _graphql.GraphQLError) { - const range = getRange((_b = (_a = error.locations) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : { - line: 0, - column: 0 - }, enhancedQuery); - return [{ - severity: DIAGNOSTIC_SEVERITY.Error, - message: error.message, - source: 'GraphQL: Syntax', - range - }]; - } - throw error; - } - return validateQuery(ast, schema, customRules, isRelayCompatMode); + if (!state.md.options.html) { + return false; } - function validateQuery(ast, schema = null, customRules, isRelayCompatMode) { - if (!schema) { - return []; + if (state.src.charCodeAt(pos) !== 0x3C /* < */) { + return false; + } + let lineText = state.src.slice(pos, max); + let i = 0; + for (; i < HTML_SEQUENCES.length; i++) { + if (HTML_SEQUENCES[i][0].test(lineText)) { + break; } - const validationErrorAnnotations = (0, _utils.validateWithCustomRules)(schema, ast, customRules, isRelayCompatMode).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Error, 'Validation')); - const deprecationWarningAnnotations = (0, _graphql.validate)(schema, ast, [_graphql.NoDeprecatedCustomRule]).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Warning, 'Deprecation')); - return validationErrorAnnotations.concat(deprecationWarningAnnotations); } - function annotations(error, severity, type) { - if (!error.nodes) { - return []; - } - const highlightedNodes = []; - for (const [i, node] of error.nodes.entries()) { - const highlightNode = node.kind !== 'Variable' && 'name' in node && node.name !== undefined ? node.name : 'variable' in node && node.variable !== undefined ? node.variable : node; - if (highlightNode) { - invariant(error.locations, 'GraphQL validation error requires locations.'); - const loc = error.locations[i]; - const highlightLoc = getLocation(highlightNode); - const end = loc.column + (highlightLoc.end - highlightLoc.start); - highlightedNodes.push({ - source: `GraphQL: ${type}`, - message: error.message, - severity, - range: new _utils.Range(new _utils.Position(loc.line - 1, loc.column - 1), new _utils.Position(loc.line - 1, end)) - }); - } - } - return highlightedNodes; + if (i === HTML_SEQUENCES.length) { + return false; } - function getRange(location, queryText) { - const parser = (0, _parser.onlineParser)(); - const state = parser.startState(); - const lines = queryText.split('\n'); - invariant(lines.length >= location.line, 'Query text must have more lines than where the error happened'); - let stream = null; - for (let i = 0; i < location.line; i++) { - stream = new _parser.CharacterStream(lines[i]); - while (!stream.eol()) { - const style = parser.token(stream, state); - if (style === 'invalidchar') { - break; + if (silent) { + // true if this sequence can be a terminator, false otherwise + return HTML_SEQUENCES[i][2]; + } + let nextLine = startLine + 1; + + // If we are here - we detected HTML block. + // Let's roll down till block end. + if (!HTML_SEQUENCES[i][1].test(lineText)) { + for (; nextLine < endLine; nextLine++) { + if (state.sCount[nextLine] < state.blkIndent) { + break; + } + pos = state.bMarks[nextLine] + state.tShift[nextLine]; + max = state.eMarks[nextLine]; + lineText = state.src.slice(pos, max); + if (HTML_SEQUENCES[i][1].test(lineText)) { + if (lineText.length !== 0) { + nextLine++; } + break; } } - invariant(stream, 'Expected Parser stream to be available.'); - const line = location.line - 1; - const start = stream.getStartOfToken(); - const end = stream.getCurrentPosition(); - return new _utils.Range(new _utils.Position(line, start), new _utils.Position(line, end)); } - function getLocation(node) { - const typeCastedNode = node; - const location = typeCastedNode.loc; - invariant(location, 'Expected ASTNode to have a location.'); - return location; - } - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/getHoverInformation.js": - /*!***************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getHoverInformation.js ***! - \***************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getHoverInformation = getHoverInformation; - exports.renderArg = renderArg; - exports.renderDirective = renderDirective; - exports.renderEnumValue = renderEnumValue; - exports.renderField = renderField; - exports.renderType = renderType; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); - function getHoverInformation(schema, queryText, cursor, contextToken, config) { - const options = Object.assign(Object.assign({}, config), { - schema - }); - const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken); - if (!context) { - return ''; - } - const { - typeInfo, - token - } = context; - const { - kind, - step - } = token.state; - if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef || kind === 'ObjectField' && step === 0 && typeInfo.fieldDef) { - const into = []; - renderMdCodeStart(into, options); - renderField(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.fieldDef); - return into.join('').trim(); - } - if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) { - const into = []; - renderMdCodeStart(into, options); - renderDirective(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.directiveDef); - return into.join('').trim(); - } - if (kind === 'Variable' && typeInfo.type) { - const into = []; - renderMdCodeStart(into, options); - renderType(into, typeInfo, options, typeInfo.type); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.type); - return into.join('').trim(); - } - if (kind === 'Argument' && step === 0 && typeInfo.argDef) { - const into = []; - renderMdCodeStart(into, options); - renderArg(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.argDef); - return into.join('').trim(); - } - if (kind === 'EnumValue' && typeInfo.enumValue && 'description' in typeInfo.enumValue) { - const into = []; - renderMdCodeStart(into, options); - renderEnumValue(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.enumValue); - return into.join('').trim(); - } - if (kind === 'NamedType' && typeInfo.type && 'description' in typeInfo.type) { - const into = []; - renderMdCodeStart(into, options); - renderType(into, typeInfo, options, typeInfo.type); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.type); - return into.join('').trim(); - } - return ''; + state.line = nextLine; + const token = state.push('html_block', '', 0); + token.map = [startLine, nextLine]; + token.content = state.getLines(startLine, nextLine, state.blkIndent, true); + return true; +} + +// heading (#, ##, ...) + +function heading(state, startLine, endLine, silent) { + let pos = state.bMarks[startLine] + state.tShift[startLine]; + let max = state.eMarks[startLine]; + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; } - function renderMdCodeStart(into, options) { - if (options.useMarkdown) { - text(into, '```graphql\n'); - } + let ch = state.src.charCodeAt(pos); + if (ch !== 0x23 /* # */ || pos >= max) { + return false; } - function renderMdCodeEnd(into, options) { - if (options.useMarkdown) { - text(into, '\n```'); - } + + // count heading level + let level = 1; + ch = state.src.charCodeAt(++pos); + while (ch === 0x23 /* # */ && pos < max && level <= 6) { + level++; + ch = state.src.charCodeAt(++pos); } - function renderField(into, typeInfo, options) { - renderQualifiedField(into, typeInfo, options); - renderTypeAnnotation(into, typeInfo, options, typeInfo.type); + if (level > 6 || pos < max && !isSpace(ch)) { + return false; } - function renderQualifiedField(into, typeInfo, options) { - if (!typeInfo.fieldDef) { - return; - } - const fieldName = typeInfo.fieldDef.name; - if (fieldName.slice(0, 2) !== '__') { - renderType(into, typeInfo, options, typeInfo.parentType); - text(into, '.'); - } - text(into, fieldName); + if (silent) { + return true; } - function renderDirective(into, typeInfo, _options) { - if (!typeInfo.directiveDef) { - return; - } - const name = '@' + typeInfo.directiveDef.name; - text(into, name); + + // Let's cut tails like ' ### ' from the end of string + + max = state.skipSpacesBack(max, pos); + const tmp = state.skipCharsBack(max, 0x23, pos); // # + if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { + max = tmp; + } + state.line = startLine + 1; + const token_o = state.push('heading_open', 'h' + String(level), 1); + token_o.markup = '########'.slice(0, level); + token_o.map = [startLine, state.line]; + const token_i = state.push('inline', '', 0); + token_i.content = state.src.slice(pos, max).trim(); + token_i.map = [startLine, state.line]; + token_i.children = []; + const token_c = state.push('heading_close', 'h' + String(level), -1); + token_c.markup = '########'.slice(0, level); + return true; +} + +// lheading (---, ===) + +function lheading(state, startLine, endLine /*, silent */) { + const terminatorRules = state.md.block.ruler.getRules('paragraph'); + + // if it's indented more than 3 spaces, it should be a code block + if (state.sCount[startLine] - state.blkIndent >= 4) { + return false; } - function renderArg(into, typeInfo, options) { - if (typeInfo.directiveDef) { - renderDirective(into, typeInfo, options); - } else if (typeInfo.fieldDef) { - renderQualifiedField(into, typeInfo, options); + const oldParentType = state.parentType; + state.parentType = 'paragraph'; // use paragraph to match terminatorRules + + // jump line-by-line until empty one or EOF + let level = 0; + let marker; + let nextLine = startLine + 1; + for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + continue; } - if (!typeInfo.argDef) { - return; + + // + // Check for underline in setext header + // + if (state.sCount[nextLine] >= state.blkIndent) { + let pos = state.bMarks[nextLine] + state.tShift[nextLine]; + const max = state.eMarks[nextLine]; + if (pos < max) { + marker = state.src.charCodeAt(pos); + if (marker === 0x2D /* - */ || marker === 0x3D /* = */) { + pos = state.skipChars(pos, marker); + pos = state.skipSpaces(pos); + if (pos >= max) { + level = marker === 0x3D /* = */ ? 1 : 2; + break; + } + } + } } - const { - name - } = typeInfo.argDef; - text(into, '('); - text(into, name); - renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); - text(into, ')'); - } - function renderTypeAnnotation(into, typeInfo, options, t) { - text(into, ': '); - renderType(into, typeInfo, options, t); - } - function renderEnumValue(into, typeInfo, options) { - if (!typeInfo.enumValue) { - return; + + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + continue; } - const { - name - } = typeInfo.enumValue; - renderType(into, typeInfo, options, typeInfo.inputType); - text(into, '.'); - text(into, name); - } - function renderType(into, typeInfo, options, t) { - if (!t) { - return; + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } } - if (t instanceof _graphql.GraphQLNonNull) { - renderType(into, typeInfo, options, t.ofType); - text(into, '!'); - } else if (t instanceof _graphql.GraphQLList) { - text(into, '['); - renderType(into, typeInfo, options, t.ofType); - text(into, ']'); - } else { - text(into, t.name); + if (terminate) { + break; } } - function renderDescription(into, options, def) { - if (!def) { - return; + if (!level) { + // Didn't find valid underline + return false; + } + const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); + state.line = nextLine + 1; + const token_o = state.push('heading_open', 'h' + String(level), 1); + token_o.markup = String.fromCharCode(marker); + token_o.map = [startLine, state.line]; + const token_i = state.push('inline', '', 0); + token_i.content = content; + token_i.map = [startLine, state.line - 1]; + token_i.children = []; + const token_c = state.push('heading_close', 'h' + String(level), -1); + token_c.markup = String.fromCharCode(marker); + state.parentType = oldParentType; + return true; +} + +// Paragraph + +function paragraph(state, startLine, endLine) { + const terminatorRules = state.md.block.ruler.getRules('paragraph'); + const oldParentType = state.parentType; + let nextLine = startLine + 1; + state.parentType = 'paragraph'; + + // jump line-by-line until empty one or EOF + for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { + // this would be a code block normally, but after paragraph + // it's considered a lazy continuation regardless of what's there + if (state.sCount[nextLine] - state.blkIndent > 3) { + continue; } - const description = typeof def.description === 'string' ? def.description : null; - if (description) { - text(into, '\n\n'); - text(into, description); + + // quirk for blockquotes, this line should already be checked by that rule + if (state.sCount[nextLine] < 0) { + continue; } - renderDeprecation(into, options, def); - } - function renderDeprecation(into, _options, def) { - if (!def) { - return; + + // Some tags can terminate paragraph without empty line. + let terminate = false; + for (let i = 0, l = terminatorRules.length; i < l; i++) { + if (terminatorRules[i](state, nextLine, endLine, true)) { + terminate = true; + break; + } } - const reason = def.deprecationReason || null; - if (!reason) { - return; + if (terminate) { + break; } - text(into, '\n\n'); - text(into, 'Deprecated: '); - text(into, reason); } - function text(into, content) { - into.push(content); + const content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); + state.line = nextLine; + const token_o = state.push('paragraph_open', 'p', 1); + token_o.map = [startLine, state.line]; + const token_i = state.push('inline', '', 0); + token_i.content = content; + token_i.map = [startLine, state.line]; + token_i.children = []; + state.push('paragraph_close', 'p', -1); + state.parentType = oldParentType; + return true; +} + +/** internal + * class ParserBlock + * + * Block-level tokenizer. + **/ + +const _rules$1 = [ +// First 2 params - rule name & source. Secondary array - list of rules, +// which can be terminated by this one. +['table', table, ['paragraph', 'reference']], ['code', code], ['fence', fence, ['paragraph', 'reference', 'blockquote', 'list']], ['blockquote', blockquote, ['paragraph', 'reference', 'blockquote', 'list']], ['hr', hr, ['paragraph', 'reference', 'blockquote', 'list']], ['list', list, ['paragraph', 'reference', 'blockquote']], ['reference', reference], ['html_block', html_block, ['paragraph', 'reference', 'blockquote']], ['heading', heading, ['paragraph', 'reference', 'blockquote']], ['lheading', lheading], ['paragraph', paragraph]]; + +/** + * new ParserBlock() + **/ +function ParserBlock() { + /** + * ParserBlock#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of block rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules$1.length; i++) { + this.ruler.push(_rules$1[i][0], _rules$1[i][1], { + alt: (_rules$1[i][2] || []).slice() + }); } - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/getOutline.js": - /*!******************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getOutline.js ***! - \******************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getOutline = getOutline; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); - const { - INLINE_FRAGMENT - } = _graphql.Kind; - const OUTLINEABLE_KINDS = { - Field: true, - OperationDefinition: true, - Document: true, - SelectionSet: true, - Name: true, - FragmentDefinition: true, - FragmentSpread: true, - InlineFragment: true, - ObjectTypeDefinition: true, - InputObjectTypeDefinition: true, - InterfaceTypeDefinition: true, - EnumTypeDefinition: true, - EnumValueDefinition: true, - InputValueDefinition: true, - FieldDefinition: true - }; - function getOutline(documentText) { - let ast; - try { - ast = (0, _graphql.parse)(documentText); - } catch (_a) { - return null; +} + +// Generate tokens for input range +// +ParserBlock.prototype.tokenize = function (state, startLine, endLine) { + const rules = this.ruler.getRules(''); + const len = rules.length; + const maxNesting = state.md.options.maxNesting; + let line = startLine; + let hasEmptyLines = false; + while (line < endLine) { + state.line = line = state.skipEmptyLines(line); + if (line >= endLine) { + break; + } + + // Termination condition for nested calls. + // Nested calls currently used for blockquotes & lists + if (state.sCount[line] < state.blkIndent) { + break; + } + + // If nesting level exceeded - skip tail to the end. That's not ordinary + // situation and we should not care about content. + if (state.level >= maxNesting) { + state.line = endLine; + break; } - const visitorFns = outlineTreeConverter(documentText); - const outlineTrees = (0, _graphql.visit)(ast, { - leave(node) { - if (visitorFns !== undefined && node.kind in visitorFns) { - return visitorFns[node.kind](node); + + // Try all possible rules. + // On success, rule should: + // + // - update `state.line` + // - update `state.tokens` + // - return true + const prevLine = state.line; + let ok = false; + for (let i = 0; i < len; i++) { + ok = rules[i](state, line, endLine, false); + if (ok) { + if (prevLine >= state.line) { + throw new Error("block rule didn't increment state.line"); } - return null; + break; } - }); - return { - outlineTrees - }; + } + + // this can only happen if user disables paragraph rule + if (!ok) throw new Error('none of the block rules matched'); + + // set state.tight if we had an empty line before current tag + // i.e. latest empty line should not count + state.tight = !hasEmptyLines; + + // paragraph might "eat" one newline after it in nested lists + if (state.isEmpty(state.line - 1)) { + hasEmptyLines = true; + } + line = state.line; + if (line < endLine && state.isEmpty(line)) { + hasEmptyLines = true; + line++; + state.line = line; + } } - function outlineTreeConverter(docText) { - const meta = node => { - return { - representativeName: node.name, - startPosition: (0, _utils.offsetToPosition)(docText, node.loc.start), - endPosition: (0, _utils.offsetToPosition)(docText, node.loc.end), - kind: node.kind, - children: node.selectionSet || node.fields || node.values || node.arguments || [] - }; - }; - return { - Field(node) { - const tokenizedText = node.alias ? [buildToken('plain', node.alias), buildToken('plain', ': ')] : []; - tokenizedText.push(buildToken('plain', node.name)); - return Object.assign({ - tokenizedText - }, meta(node)); - }, - OperationDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', node.operation), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - Document: node => node.definitions, - SelectionSet: node => concatMap(node.selections, child => { - return child.kind === INLINE_FRAGMENT ? child.selectionSet : child; - }), - Name: node => node.value, - FragmentDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'fragment'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - InterfaceTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'interface'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - EnumTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'enum'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - EnumValueDefinition: node => Object.assign({ - tokenizedText: [buildToken('plain', node.name)] - }, meta(node)), - ObjectTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'type'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - InputObjectTypeDefinition: node => Object.assign({ - tokenizedText: [buildToken('keyword', 'input'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] - }, meta(node)), - FragmentSpread: node => Object.assign({ - tokenizedText: [buildToken('plain', '...'), buildToken('class-name', node.name)] - }, meta(node)), - InputValueDefinition(node) { - return Object.assign({ - tokenizedText: [buildToken('plain', node.name)] - }, meta(node)); - }, - FieldDefinition(node) { - return Object.assign({ - tokenizedText: [buildToken('plain', node.name)] - }, meta(node)); - }, - InlineFragment: node => node.selectionSet - }; +}; + +/** + * ParserBlock.parse(str, md, env, outTokens) + * + * Process input string and push block tokens into `outTokens` + **/ +ParserBlock.prototype.parse = function (src, md, env, outTokens) { + if (!src) { + return; } - function buildToken(kind, value) { - return { - kind, - value + const state = new this.State(src, md, env, outTokens); + this.tokenize(state, state.line, state.lineMax); +}; +ParserBlock.prototype.State = StateBlock; + +// Inline parser state + +function StateInline(src, md, env, outTokens) { + this.src = src; + this.env = env; + this.md = md; + this.tokens = outTokens; + this.tokens_meta = Array(outTokens.length); + this.pos = 0; + this.posMax = this.src.length; + this.level = 0; + this.pending = ''; + this.pendingLevel = 0; + + // Stores { start: end } pairs. Useful for backtrack + // optimization of pairs parse (emphasis, strikes). + this.cache = {}; + + // List of emphasis-like delimiters for current tag + this.delimiters = []; + + // Stack of delimiter lists for upper level tags + this._prev_delimiters = []; + + // backtick length => last seen position + this.backticks = {}; + this.backticksScanned = false; + + // Counter used to disable inline linkify-it execution + // inside
    and markdown links + this.linkLevel = 0; +} + +// Flush pending text +// +StateInline.prototype.pushPending = function () { + const token = new Token('text', '', 0); + token.content = this.pending; + token.level = this.pendingLevel; + this.tokens.push(token); + this.pending = ''; + return token; +}; + +// Push new token to "stream". +// If pending text exists - flush it as text token +// +StateInline.prototype.push = function (type, tag, nesting) { + if (this.pending) { + this.pushPending(); + } + const token = new Token(type, tag, nesting); + let token_meta = null; + if (nesting < 0) { + // closing tag + this.level--; + this.delimiters = this._prev_delimiters.pop(); + } + token.level = this.level; + if (nesting > 0) { + // opening tag + this.level++; + this._prev_delimiters.push(this.delimiters); + this.delimiters = []; + token_meta = { + delimiters: this.delimiters }; } - function concatMap(arr, fn) { - const res = []; - for (let i = 0; i < arr.length; i++) { - const x = fn(arr[i], i); - if (Array.isArray(x)) { - res.push(...x); - } else { - res.push(x); - } - } - return res; + this.pendingLevel = this.level; + this.tokens.push(token); + this.tokens_meta.push(token_meta); + return token; +}; + +// Scan a sequence of emphasis-like markers, and determine whether +// it can start an emphasis sequence or end an emphasis sequence. +// +// - start - position to scan from (it should point at a valid marker); +// - canSplitWord - determine if these markers can be found inside a word +// +StateInline.prototype.scanDelims = function (start, canSplitWord) { + const max = this.posMax; + const marker = this.src.charCodeAt(start); + + // treat beginning of the line as a whitespace + const lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; + let pos = start; + while (pos < max && this.src.charCodeAt(pos) === marker) { + pos++; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/interface/index.js": - /*!*************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/index.js ***! - \*************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var _exportNames = { - getOutline: true, - getHoverInformation: true + const count = pos - start; + + // treat end of the line as a whitespace + const nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; + const isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); + const isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); + const isLastWhiteSpace = isWhiteSpace(lastChar); + const isNextWhiteSpace = isWhiteSpace(nextChar); + const left_flanking = !isNextWhiteSpace && (!isNextPunctChar || isLastWhiteSpace || isLastPunctChar); + const right_flanking = !isLastWhiteSpace && (!isLastPunctChar || isNextWhiteSpace || isNextPunctChar); + const can_open = left_flanking && (canSplitWord || !right_flanking || isLastPunctChar); + const can_close = right_flanking && (canSplitWord || !left_flanking || isNextPunctChar); + return { + can_open, + can_close, + length: count }; - Object.defineProperty(exports, "getHoverInformation", ({ - enumerable: true, - get: function () { - return _getHoverInformation.getHoverInformation; - } - })); - Object.defineProperty(exports, "getOutline", ({ - enumerable: true, - get: function () { - return _getOutline.getOutline; - } - })); - var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); - Object.keys(_autocompleteUtils).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _autocompleteUtils[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _autocompleteUtils[key]; - } - }); - }); - var _getAutocompleteSuggestions = __webpack_require__(/*! ./getAutocompleteSuggestions */ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js"); - Object.keys(_getAutocompleteSuggestions).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getAutocompleteSuggestions[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getAutocompleteSuggestions[key]; - } - }); - }); - var _getDefinition = __webpack_require__(/*! ./getDefinition */ "../../graphql-language-service/esm/interface/getDefinition.js"); - Object.keys(_getDefinition).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getDefinition[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getDefinition[key]; - } - }); - }); - var _getDiagnostics = __webpack_require__(/*! ./getDiagnostics */ "../../graphql-language-service/esm/interface/getDiagnostics.js"); - Object.keys(_getDiagnostics).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getDiagnostics[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getDiagnostics[key]; - } - }); - }); - var _getOutline = __webpack_require__(/*! ./getOutline */ "../../graphql-language-service/esm/interface/getOutline.js"); - var _getHoverInformation = __webpack_require__(/*! ./getHoverInformation */ "../../graphql-language-service/esm/interface/getHoverInformation.js"); - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/CharacterStream.js": - /*!********************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/CharacterStream.js ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports["default"] = void 0; - class CharacterStream { - constructor(sourceText) { - this._start = 0; - this._pos = 0; - this.getStartOfToken = () => this._start; - this.getCurrentPosition = () => this._pos; - this.eol = () => this._sourceText.length === this._pos; - this.sol = () => this._pos === 0; - this.peek = () => { - return this._sourceText.charAt(this._pos) || null; - }; - this.next = () => { - const char = this._sourceText.charAt(this._pos); - this._pos++; - return char; - }; - this.eat = pattern => { - const isMatched = this._testNextCharacter(pattern); - if (isMatched) { - this._start = this._pos; - this._pos++; - return this._sourceText.charAt(this._pos - 1); - } - return undefined; - }; - this.eatWhile = match => { - let isMatched = this._testNextCharacter(match); - let didEat = false; - if (isMatched) { - didEat = isMatched; - this._start = this._pos; - } - while (isMatched) { - this._pos++; - isMatched = this._testNextCharacter(match); - didEat = true; - } - return didEat; - }; - this.eatSpace = () => this.eatWhile(/[\s\u00a0]/); - this.skipToEnd = () => { - this._pos = this._sourceText.length; - }; - this.skipTo = position => { - this._pos = position; - }; - this.match = (pattern, consume = true, caseFold = false) => { - let token = null; - let match = null; - if (typeof pattern === 'string') { - const regex = new RegExp(pattern, caseFold ? 'i' : 'g'); - match = regex.test(this._sourceText.slice(this._pos, this._pos + pattern.length)); - token = pattern; - } else if (pattern instanceof RegExp) { - match = this._sourceText.slice(this._pos).match(pattern); - token = match === null || match === void 0 ? void 0 : match[0]; - } - if (match != null && (typeof pattern === 'string' || match instanceof Array && this._sourceText.startsWith(match[0], this._pos))) { - if (consume) { - this._start = this._pos; - if (token && token.length) { - this._pos += token.length; - } - } - return match; - } - return false; - }; - this.backUp = num => { - this._pos -= num; - }; - this.column = () => this._pos; - this.indentation = () => { - const match = this._sourceText.match(/\s*/); - let indent = 0; - if (match && match.length !== 0) { - const whiteSpaces = match[0]; - let pos = 0; - while (whiteSpaces.length > pos) { - if (whiteSpaces.charCodeAt(pos) === 9) { - indent += 2; - } else { - indent++; - } - pos++; - } - } - return indent; - }; - this.current = () => this._sourceText.slice(this._start, this._pos); - this._sourceText = sourceText; - } - _testNextCharacter(pattern) { - const character = this._sourceText.charAt(this._pos); - let isMatched = false; - if (typeof pattern === 'string') { - isMatched = character === pattern; +}; + +// re-export Token class to use in block rules +StateInline.prototype.Token = Token; + +// Skip text characters for text token, place those to pending buffer +// and increment current pos + +// Rule to skip pure text +// '{}$%@~+=:' reserved for extentions + +// !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ + +// !!!! Don't confuse with "Markdown ASCII Punctuation" chars +// http://spec.commonmark.org/0.15/#ascii-punctuation-character +function isTerminatorChar(ch) { + switch (ch) { + case 0x0A /* \n */: + case 0x21 /* ! */: + case 0x23 /* # */: + case 0x24 /* $ */: + case 0x25 /* % */: + case 0x26 /* & */: + case 0x2A /* * */: + case 0x2B /* + */: + case 0x2D /* - */: + case 0x3A /* : */: + case 0x3C /* < */: + case 0x3D /* = */: + case 0x3E /* > */: + case 0x40 /* @ */: + case 0x5B /* [ */: + case 0x5C /* \ */: + case 0x5D /* ] */: + case 0x5E /* ^ */: + case 0x5F /* _ */: + case 0x60 /* ` */: + case 0x7B /* { */: + case 0x7D /* } */: + case 0x7E /* ~ */: + return true; + default: + return false; + } +} +function text(state, silent) { + let pos = state.pos; + while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) { + pos++; + } + if (pos === state.pos) { + return false; + } + if (!silent) { + state.pending += state.src.slice(state.pos, pos); + } + state.pos = pos; + return true; +} + +// Alternative implementation, for memory. +// +// It costs 10% of performance, but allows extend terminators list, if place it +// to `ParserInline` property. Probably, will switch to it sometime, such +// flexibility required. + +/* +var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; + +module.exports = function text(state, silent) { + var pos = state.pos, + idx = state.src.slice(pos).search(TERMINATOR_RE); + + // first char is terminator -> empty text + if (idx === 0) { return false; } + + // no terminator -> text till end of string + if (idx < 0) { + if (!silent) { state.pending += state.src.slice(pos); } + state.pos = state.src.length; + return true; + } + + if (!silent) { state.pending += state.src.slice(pos, pos + idx); } + + state.pos += idx; + + return true; +}; */ + +// Process links like https://example.org/ + +// RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) +const SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; +function linkify(state, silent) { + if (!state.md.options.linkify) return false; + if (state.linkLevel > 0) return false; + const pos = state.pos; + const max = state.posMax; + if (pos + 3 > max) return false; + if (state.src.charCodeAt(pos) !== 0x3A /* : */) return false; + if (state.src.charCodeAt(pos + 1) !== 0x2F /* / */) return false; + if (state.src.charCodeAt(pos + 2) !== 0x2F /* / */) return false; + const match = state.pending.match(SCHEME_RE); + if (!match) return false; + const proto = match[1]; + const link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length)); + if (!link) return false; + let url = link.url; + + // invalid link, but still detected by linkify somehow; + // need to check to prevent infinite loop below + if (url.length <= proto.length) return false; + + // disallow '*' at the end of the link (conflicts with emphasis) + url = url.replace(/\*+$/, ''); + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) return false; + if (!silent) { + state.pending = state.pending.slice(0, -proto.length); + const token_o = state.push('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.markup = 'linkify'; + token_o.info = 'auto'; + const token_t = state.push('text', '', 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push('link_close', 'a', -1); + token_c.markup = 'linkify'; + token_c.info = 'auto'; + } + state.pos += url.length - proto.length; + return true; +} + +// Proceess '\n' + +function newline(state, silent) { + let pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x0A /* \n */) { + return false; + } + const pmax = state.pending.length - 1; + const max = state.posMax; + + // ' \n' -> hardbreak + // Lookup in pending chars is bad practice! Don't copy to other rules! + // Pending string is stored in concat mode, indexed lookups will cause + // convertion to flat mode. + if (!silent) { + if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { + if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { + // Find whitespaces tail of pending chars. + let ws = pmax - 1; + while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) ws--; + state.pending = state.pending.slice(0, ws); + state.push('hardbreak', 'br', 0); } else { - isMatched = pattern instanceof RegExp ? pattern.test(character) : pattern(character); + state.pending = state.pending.slice(0, -1); + state.push('softbreak', 'br', 0); } - return isMatched; + } else { + state.push('softbreak', 'br', 0); } } - exports["default"] = CharacterStream; - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/RuleHelpers.js": - /*!****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/RuleHelpers.js ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.butNot = butNot; - exports.list = list; - exports.opt = opt; - exports.p = p; - exports.t = t; - function opt(ofRule) { - return { - ofRule - }; - } - function list(ofRule, separator) { - return { - ofRule, - isList: true, - separator - }; + pos++; + + // skip heading spaces for next line + while (pos < max && isSpace(state.src.charCodeAt(pos))) { + pos++; } - function butNot(rule, exclusions) { - const ruleMatch = rule.match; - rule.match = token => { - let check = false; - if (ruleMatch) { - check = ruleMatch(token); - } - return check && exclusions.every(exclusion => exclusion.match && !exclusion.match(token)); - }; - return rule; + state.pos = pos; + return true; +} + +// Process escaped chars and hardbreaks + +const ESCAPED = []; +for (let i = 0; i < 256; i++) { + ESCAPED.push(0); +} +'\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'.split('').forEach(function (ch) { + ESCAPED[ch.charCodeAt(0)] = 1; +}); +function escape(state, silent) { + let pos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(pos) !== 0x5C /* \ */) return false; + pos++; + + // '\' at the end of the inline block + if (pos >= max) return false; + let ch1 = state.src.charCodeAt(pos); + if (ch1 === 0x0A) { + if (!silent) { + state.push('hardbreak', 'br', 0); + } + pos++; + // skip leading whitespaces from next line + while (pos < max) { + ch1 = state.src.charCodeAt(pos); + if (!isSpace(ch1)) break; + pos++; + } + state.pos = pos; + return true; } - function t(kind, style) { - return { - style, - match: token => token.kind === kind - }; + let escapedStr = state.src[pos]; + if (ch1 >= 0xD800 && ch1 <= 0xDBFF && pos + 1 < max) { + const ch2 = state.src.charCodeAt(pos + 1); + if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { + escapedStr += state.src[pos + 1]; + pos++; + } } - function p(value, style) { - return { - style: style || 'punctuation', - match: token => token.kind === 'Punctuation' && token.value === value - }; + const origStr = '\\' + escapedStr; + if (!silent) { + const token = state.push('text_special', '', 0); + if (ch1 < 256 && ESCAPED[ch1] !== 0) { + token.content = escapedStr; + } else { + token.content = origStr; + } + token.markup = origStr; + token.info = 'escape'; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/Rules.js": - /*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/Rules.js ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.isIgnored = exports.ParseRules = exports.LexRules = void 0; - var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const isIgnored = ch => ch === ' ' || ch === '\t' || ch === ',' || ch === '\n' || ch === '\r' || ch === '\uFEFF' || ch === '\u00A0'; - exports.isIgnored = isIgnored; - const LexRules = exports.LexRules = { - Name: /^[_A-Za-z][_0-9A-Za-z]*/, - Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|&|@|\[|]|\{|\||\})/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/, - Comment: /^#.*/ - }; - const ParseRules = exports.ParseRules = { - Document: [(0, _RuleHelpers.list)('Definition')], - Definition(token) { - switch (token.value) { - case '{': - return 'ShortQuery'; - case 'query': - return 'Query'; - case 'mutation': - return 'Mutation'; - case 'subscription': - return 'Subscription'; - case 'fragment': - return _graphql.Kind.FRAGMENT_DEFINITION; - case 'schema': - return 'SchemaDef'; - case 'scalar': - return 'ScalarDef'; - case 'type': - return 'ObjectTypeDef'; - case 'interface': - return 'InterfaceDef'; - case 'union': - return 'UnionDef'; - case 'enum': - return 'EnumDef'; - case 'input': - return 'InputDef'; - case 'extend': - return 'ExtendDef'; - case 'directive': - return 'DirectiveDef'; - } - }, - ShortQuery: ['SelectionSet'], - Query: [word('query'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - Mutation: [word('mutation'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - Subscription: [word('subscription'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - VariableDefinitions: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('VariableDefinition'), (0, _RuleHelpers.p)(')')], - VariableDefinition: ['Variable', (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue')], - Variable: [(0, _RuleHelpers.p)('$', 'variable'), name('variable')], - DefaultValue: [(0, _RuleHelpers.p)('='), 'Value'], - SelectionSet: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Selection'), (0, _RuleHelpers.p)('}')], - Selection(token, stream) { - return token.value === '...' ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field'; - }, - AliasedField: [name('property'), (0, _RuleHelpers.p)(':'), name('qualifier'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], - Field: [name('property'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], - Arguments: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('Argument'), (0, _RuleHelpers.p)(')')], - Argument: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], - FragmentSpread: [(0, _RuleHelpers.p)('...'), name('def'), (0, _RuleHelpers.list)('Directive')], - InlineFragment: [(0, _RuleHelpers.p)('...'), (0, _RuleHelpers.opt)('TypeCondition'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - FragmentDefinition: [word('fragment'), (0, _RuleHelpers.opt)((0, _RuleHelpers.butNot)(name('def'), [word('on')])), 'TypeCondition', (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], - TypeCondition: [word('on'), 'NamedType'], - Value(token) { - switch (token.kind) { - case 'Number': - return 'NumberValue'; - case 'String': - return 'StringValue'; - case 'Punctuation': - switch (token.value) { - case '[': - return 'ListValue'; - case '{': - return 'ObjectValue'; - case '$': - return 'Variable'; - case '&': - return 'NamedType'; - } - return null; - case 'Name': - switch (token.value) { - case 'true': - case 'false': - return 'BooleanValue'; - } - if (token.value === 'null') { - return 'NullValue'; - } - return 'EnumValue'; - } - }, - NumberValue: [(0, _RuleHelpers.t)('Number', 'number')], - StringValue: [{ - style: 'string', - match: token => token.kind === 'String', - update(state, token) { - if (token.value.startsWith('"""')) { - state.inBlockstring = !token.value.slice(3).endsWith('"""'); - } - } - }], - BooleanValue: [(0, _RuleHelpers.t)('Name', 'builtin')], - NullValue: [(0, _RuleHelpers.t)('Name', 'keyword')], - EnumValue: [name('string-2')], - ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value'), (0, _RuleHelpers.p)(']')], - ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField'), (0, _RuleHelpers.p)('}')], - ObjectField: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], - Type(token) { - return token.value === '[' ? 'ListType' : 'NonNullType'; - }, - ListType: [(0, _RuleHelpers.p)('['), 'Type', (0, _RuleHelpers.p)(']'), (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], - NonNullType: ['NamedType', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], - NamedType: [type('atom')], - Directive: [(0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('Arguments')], - DirectiveDef: [word('directive'), (0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('ArgumentsDef'), word('on'), (0, _RuleHelpers.list)('DirectiveLocation', (0, _RuleHelpers.p)('|'))], - InterfaceDef: [word('interface'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], - Implements: [word('implements'), (0, _RuleHelpers.list)('NamedType', (0, _RuleHelpers.p)('&'))], - DirectiveLocation: [name('string-2')], - SchemaDef: [word('schema'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('OperationTypeDef'), (0, _RuleHelpers.p)('}')], - OperationTypeDef: [name('keyword'), (0, _RuleHelpers.p)(':'), name('atom')], - ScalarDef: [word('scalar'), name('atom'), (0, _RuleHelpers.list)('Directive')], - ObjectTypeDef: [word('type'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], - FieldDef: [name('property'), (0, _RuleHelpers.opt)('ArgumentsDef'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.list)('Directive')], - ArgumentsDef: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)(')')], - InputValueDef: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue'), (0, _RuleHelpers.list)('Directive')], - UnionDef: [word('union'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('='), (0, _RuleHelpers.list)('UnionMember', (0, _RuleHelpers.p)('|'))], - UnionMember: ['NamedType'], - EnumDef: [word('enum'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('EnumValueDef'), (0, _RuleHelpers.p)('}')], - EnumValueDef: [name('string-2'), (0, _RuleHelpers.list)('Directive')], - InputDef: [word('input'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)('}')], - ExtendDef: [word('extend'), 'ExtensionDefinition'], - ExtensionDefinition(token) { - switch (token.value) { - case 'schema': - return _graphql.Kind.SCHEMA_EXTENSION; - case 'scalar': - return _graphql.Kind.SCALAR_TYPE_EXTENSION; - case 'type': - return _graphql.Kind.OBJECT_TYPE_EXTENSION; - case 'interface': - return _graphql.Kind.INTERFACE_TYPE_EXTENSION; - case 'union': - return _graphql.Kind.UNION_TYPE_EXTENSION; - case 'enum': - return _graphql.Kind.ENUM_TYPE_EXTENSION; - case 'input': - return _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION; - } - }, - [_graphql.Kind.SCHEMA_EXTENSION]: ['SchemaDef'], - [_graphql.Kind.SCALAR_TYPE_EXTENSION]: ['ScalarDef'], - [_graphql.Kind.OBJECT_TYPE_EXTENSION]: ['ObjectTypeDef'], - [_graphql.Kind.INTERFACE_TYPE_EXTENSION]: ['InterfaceDef'], - [_graphql.Kind.UNION_TYPE_EXTENSION]: ['UnionDef'], - [_graphql.Kind.ENUM_TYPE_EXTENSION]: ['EnumDef'], - [_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]: ['InputDef'] - }; - function word(value) { - return { - style: 'keyword', - match: token => token.kind === 'Name' && token.value === value - }; + state.pos = pos + 1; + return true; +} + +// Parse backticks + +function backtick(state, silent) { + let pos = state.pos; + const ch = state.src.charCodeAt(pos); + if (ch !== 0x60 /* ` */) { + return false; } - function name(style) { - return { - style, - match: token => token.kind === 'Name', - update(state, token) { - state.name = token.value; - } - }; + const start = pos; + pos++; + const max = state.posMax; + + // scan marker length + while (pos < max && state.src.charCodeAt(pos) === 0x60 /* ` */) { + pos++; } - function type(style) { - return { - style, - match: token => token.kind === 'Name', - update(state, token) { - var _a; - if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.prevState) { - state.name = token.value; - state.prevState.prevState.type = token.value; - } - } - }; + const marker = state.src.slice(start, pos); + const openerLength = marker.length; + if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) { + if (!silent) state.pending += marker; + state.pos += openerLength; + return true; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/api.js": - /*!********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/api.js ***! - \********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.TYPE_SYSTEM_KINDS = exports.GraphQLDocumentMode = void 0; - exports.getContextAtPosition = getContextAtPosition; - exports.getDocumentMode = getDocumentMode; - exports.getTokenAtPosition = getTokenAtPosition; - exports.runOnlineParser = runOnlineParser; - var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function runOnlineParser(queryText, callback) { - const lines = queryText.split('\n'); - const parser = (0, _.onlineParser)(); - let state = parser.startState(); - let style = ''; - let stream = new _.CharacterStream(''); - for (let i = 0; i < lines.length; i++) { - stream = new _.CharacterStream(lines[i]); - while (!stream.eol()) { - style = parser.token(stream, state); - const code = callback(stream, state, style, i); - if (code === 'BREAK') { - break; - } - } - callback(stream, state, style, i); - if (!state.kind) { - state = parser.startState(); - } + let matchEnd = pos; + let matchStart; + + // Nothing found in the cache, scan until the end of the line (or until marker is found) + while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { + matchEnd = matchStart + 1; + + // scan marker length + while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60 /* ` */) { + matchEnd++; } - return { - start: stream.getStartOfToken(), - end: stream.getCurrentPosition(), - string: stream.current(), - state, - style - }; - } - var GraphQLDocumentMode; - (function (GraphQLDocumentMode) { - GraphQLDocumentMode["TYPE_SYSTEM"] = "TYPE_SYSTEM"; - GraphQLDocumentMode["EXECUTABLE"] = "EXECUTABLE"; - GraphQLDocumentMode["UNKNOWN"] = "UNKNOWN"; - })(GraphQLDocumentMode || (exports.GraphQLDocumentMode = GraphQLDocumentMode = {})); - const TYPE_SYSTEM_KINDS = exports.TYPE_SYSTEM_KINDS = [_graphql.Kind.SCHEMA_DEFINITION, _graphql.Kind.OPERATION_TYPE_DEFINITION, _graphql.Kind.SCALAR_TYPE_DEFINITION, _graphql.Kind.OBJECT_TYPE_DEFINITION, _graphql.Kind.INTERFACE_TYPE_DEFINITION, _graphql.Kind.UNION_TYPE_DEFINITION, _graphql.Kind.ENUM_TYPE_DEFINITION, _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION, _graphql.Kind.DIRECTIVE_DEFINITION, _graphql.Kind.SCHEMA_EXTENSION, _graphql.Kind.SCALAR_TYPE_EXTENSION, _graphql.Kind.OBJECT_TYPE_EXTENSION, _graphql.Kind.INTERFACE_TYPE_EXTENSION, _graphql.Kind.UNION_TYPE_EXTENSION, _graphql.Kind.ENUM_TYPE_EXTENSION, _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]; - const getParsedMode = sdl => { - let mode = GraphQLDocumentMode.UNKNOWN; - if (sdl) { - try { - (0, _graphql.visit)((0, _graphql.parse)(sdl), { - enter(node) { - if (node.kind === 'Document') { - mode = GraphQLDocumentMode.EXECUTABLE; - return; - } - if (TYPE_SYSTEM_KINDS.includes(node.kind)) { - mode = GraphQLDocumentMode.TYPE_SYSTEM; - return _graphql.BREAK; - } - return false; - } - }); - } catch (_a) { - return mode; + const closerLength = matchEnd - matchStart; + if (closerLength === openerLength) { + // Found matching closer length. + if (!silent) { + const token = state.push('code_inline', 'code', 0); + token.markup = marker; + token.content = state.src.slice(pos, matchStart).replace(/\n/g, ' ').replace(/^ (.+) $/, '$1'); } + state.pos = matchEnd; + return true; } - return mode; - }; - function getDocumentMode(documentText, uri) { - if (uri === null || uri === void 0 ? void 0 : uri.endsWith('.graphqls')) { - return GraphQLDocumentMode.TYPE_SYSTEM; - } - return getParsedMode(documentText); - } - function getTokenAtPosition(queryText, cursor, offset = 0) { - let styleAtCursor = null; - let stateAtCursor = null; - let stringAtCursor = null; - const token = runOnlineParser(queryText, (stream, state, style, index) => { - if (index !== cursor.line || stream.getCurrentPosition() + offset < cursor.character + 1) { - return; - } - styleAtCursor = style; - stateAtCursor = Object.assign({}, state); - stringAtCursor = stream.current(); - return 'BREAK'; + + // Some different length found, put it in cache as upper limit of where closer can be found + state.backticks[closerLength] = matchStart; + } + + // Scanned through the end, didn't find anything + state.backticksScanned = true; + if (!silent) state.pending += marker; + state.pos += openerLength; + return true; +} + +// ~~strike through~~ +// + +// Insert each marker as a separate text token, and add it to delimiter list +// +function strikethrough_tokenize(state, silent) { + const start = state.pos; + const marker = state.src.charCodeAt(start); + if (silent) { + return false; + } + if (marker !== 0x7E /* ~ */) { + return false; + } + const scanned = state.scanDelims(state.pos, true); + let len = scanned.length; + const ch = String.fromCharCode(marker); + if (len < 2) { + return false; + } + let token; + if (len % 2) { + token = state.push('text', '', 0); + token.content = ch; + len--; + } + for (let i = 0; i < len; i += 2) { + token = state.push('text', '', 0); + token.content = ch + ch; + state.delimiters.push({ + marker, + length: 0, + // disable "rule of 3" length checks meant for emphasis + token: state.tokens.length - 1, + end: -1, + open: scanned.can_open, + close: scanned.can_close }); - return { - start: token.start, - end: token.end, - string: stringAtCursor || token.string, - state: stateAtCursor || token.state, - style: styleAtCursor || token.style - }; } - function getContextAtPosition(queryText, cursor, schema, contextToken, options) { - const token = contextToken || getTokenAtPosition(queryText, cursor, 1); - if (!token) { - return null; - } - const state = token.state.kind === 'Invalid' ? token.state.prevState : token.state; - if (!state) { - return null; + state.pos += scanned.length; + return true; +} +function postProcess$1(state, delimiters) { + let token; + const loneMarkers = []; + const max = delimiters.length; + for (let i = 0; i < max; i++) { + const startDelim = delimiters[i]; + if (startDelim.marker !== 0x7E /* ~ */) { + continue; + } + if (startDelim.end === -1) { + continue; + } + const endDelim = delimiters[startDelim.end]; + token = state.tokens[startDelim.token]; + token.type = 's_open'; + token.tag = 's'; + token.nesting = 1; + token.markup = '~~'; + token.content = ''; + token = state.tokens[endDelim.token]; + token.type = 's_close'; + token.tag = 's'; + token.nesting = -1; + token.markup = '~~'; + token.content = ''; + if (state.tokens[endDelim.token - 1].type === 'text' && state.tokens[endDelim.token - 1].content === '~') { + loneMarkers.push(endDelim.token - 1); } - const typeInfo = (0, _.getTypeInfo)(schema, token.state); - const mode = (options === null || options === void 0 ? void 0 : options.mode) || getDocumentMode(queryText, options === null || options === void 0 ? void 0 : options.uri); - return { - token, - state, - typeInfo, - mode - }; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/getTypeInfo.js": - /*!****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/getTypeInfo.js ***! - \****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.forEachState = forEachState; - exports.getDefinitionState = getDefinitionState; - exports.getFieldDef = getFieldDef; - exports.getTypeInfo = getTypeInfo; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); - function getFieldDef(schema, type, fieldName) { - if (fieldName === _graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { - return _graphql.SchemaMetaFieldDef; - } - if (fieldName === _graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { - return _graphql.TypeMetaFieldDef; - } - if (fieldName === _graphql.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) { - return _graphql.TypeNameMetaFieldDef; + + // If a marker sequence has an odd number of characters, it's splitted + // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the + // start of the sequence. + // + // So, we have to move all those markers after subsequent s_close tags. + // + while (loneMarkers.length) { + const i = loneMarkers.pop(); + let j = i + 1; + while (j < state.tokens.length && state.tokens[j].type === 's_close') { + j++; } - if ('getFields' in type) { - return type.getFields()[fieldName]; + j--; + if (i !== j) { + token = state.tokens[j]; + state.tokens[j] = state.tokens[i]; + state.tokens[i] = token; } - return null; } - function forEachState(stack, fn) { - const reverseStateStack = []; - let state = stack; - while (state === null || state === void 0 ? void 0 : state.kind) { - reverseStateStack.push(state); - state = state.prevState; +} + +// Walk through delimiter list and replace text tokens with tags +// +function strikethrough_postProcess(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + postProcess$1(state, state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + postProcess$1(state, tokens_meta[curr].delimiters); + } + } +} +var r_strikethrough = { + tokenize: strikethrough_tokenize, + postProcess: strikethrough_postProcess +}; + +// Process *this* and _that_ +// + +// Insert each marker as a separate text token, and add it to delimiter list +// +function emphasis_tokenize(state, silent) { + const start = state.pos; + const marker = state.src.charCodeAt(start); + if (silent) { + return false; + } + if (marker !== 0x5F /* _ */ && marker !== 0x2A /* * */) { + return false; + } + const scanned = state.scanDelims(state.pos, marker === 0x2A); + for (let i = 0; i < scanned.length; i++) { + const token = state.push('text', '', 0); + token.content = String.fromCharCode(marker); + state.delimiters.push({ + // Char code of the starting marker (number). + // + marker, + // Total length of these series of delimiters. + // + length: scanned.length, + // A position of the token this delimiter corresponds to. + // + token: state.tokens.length - 1, + // If this delimiter is matched as a valid opener, `end` will be + // equal to its position, otherwise it's `-1`. + // + end: -1, + // Boolean flags that determine if this delimiter could open or close + // an emphasis. + // + open: scanned.can_open, + close: scanned.can_close + }); + } + state.pos += scanned.length; + return true; +} +function postProcess(state, delimiters) { + const max = delimiters.length; + for (let i = max - 1; i >= 0; i--) { + const startDelim = delimiters[i]; + if (startDelim.marker !== 0x5F /* _ */ && startDelim.marker !== 0x2A /* * */) { + continue; + } + + // Process only opening markers + if (startDelim.end === -1) { + continue; } - for (let i = reverseStateStack.length - 1; i >= 0; i--) { - fn(reverseStateStack[i]); + const endDelim = delimiters[startDelim.end]; + + // If the previous delimiter has the same marker and is adjacent to this one, + // merge those into one strong delimiter. + // + // `whatever` -> `whatever` + // + const isStrong = i > 0 && delimiters[i - 1].end === startDelim.end + 1 && + // check that first two markers match and adjacent + delimiters[i - 1].marker === startDelim.marker && delimiters[i - 1].token === startDelim.token - 1 && + // check that last two markers are adjacent (we can safely assume they match) + delimiters[startDelim.end + 1].token === endDelim.token + 1; + const ch = String.fromCharCode(startDelim.marker); + const token_o = state.tokens[startDelim.token]; + token_o.type = isStrong ? 'strong_open' : 'em_open'; + token_o.tag = isStrong ? 'strong' : 'em'; + token_o.nesting = 1; + token_o.markup = isStrong ? ch + ch : ch; + token_o.content = ''; + const token_c = state.tokens[endDelim.token]; + token_c.type = isStrong ? 'strong_close' : 'em_close'; + token_c.tag = isStrong ? 'strong' : 'em'; + token_c.nesting = -1; + token_c.markup = isStrong ? ch + ch : ch; + token_c.content = ''; + if (isStrong) { + state.tokens[delimiters[i - 1].token].content = ''; + state.tokens[delimiters[startDelim.end + 1].token].content = ''; + i--; } } - function getDefinitionState(tokenState) { - let definitionState; - forEachState(tokenState, state => { - switch (state.kind) { - case 'Query': - case 'ShortQuery': - case 'Mutation': - case 'Subscription': - case 'FragmentDefinition': - definitionState = state; - break; +} + +// Walk through delimiter list and replace text tokens with tags +// +function emphasis_post_process(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + postProcess(state, state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + postProcess(state, tokens_meta[curr].delimiters); + } + } +} +var r_emphasis = { + tokenize: emphasis_tokenize, + postProcess: emphasis_post_process +}; + +// Process [link]( "stuff") + +function link(state, silent) { + let code, label, res, ref; + let href = ''; + let title = ''; + let start = state.pos; + let parseReference = true; + if (state.src.charCodeAt(state.pos) !== 0x5B /* [ */) { + return false; + } + const oldPos = state.pos; + const max = state.posMax; + const labelStart = state.pos + 1; + const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true); + + // parser failed to find ']', so it's not a valid link + if (labelEnd < 0) { + return false; + } + let pos = labelEnd + 1; + if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { + // + // Inline link + // + + // might have found a valid shortcut link, disable reference parsing + parseReference = false; + + // [link]( "title" ) + // ^^ skipping these spaces + pos++; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } - }); - return definitionState; - } - function getTypeInfo(schema, tokenState) { - let argDef; - let argDefs; - let directiveDef; - let enumValue; - let fieldDef; - let inputType; - let objectTypeDef; - let objectFieldDefs; - let parentType; - let type; - let interfaceDef; - forEachState(tokenState, state => { - var _a; - switch (state.kind) { - case _.RuleKinds.QUERY: - case 'ShortQuery': - type = schema.getQueryType(); - break; - case _.RuleKinds.MUTATION: - type = schema.getMutationType(); - break; - case _.RuleKinds.SUBSCRIPTION: - type = schema.getSubscriptionType(); - break; - case _.RuleKinds.INLINE_FRAGMENT: - case _.RuleKinds.FRAGMENT_DEFINITION: - if (state.type) { - type = schema.getType(state.type); - } - break; - case _.RuleKinds.FIELD: - case _.RuleKinds.ALIASED_FIELD: - { - if (!type || !state.name) { - fieldDef = null; - } else { - fieldDef = parentType ? getFieldDef(schema, parentType, state.name) : null; - type = fieldDef ? fieldDef.type : null; - } - break; - } - case _.RuleKinds.SELECTION_SET: - parentType = (0, _graphql.getNamedType)(type); - break; - case _.RuleKinds.DIRECTIVE: - directiveDef = state.name ? schema.getDirective(state.name) : null; - break; - case _.RuleKinds.INTERFACE_DEF: - if (state.name) { - objectTypeDef = null; - interfaceDef = new _graphql.GraphQLInterfaceType({ - name: state.name, - interfaces: [], - fields: {} - }); - } - break; - case _.RuleKinds.OBJECT_TYPE_DEF: - if (state.name) { - interfaceDef = null; - objectTypeDef = new _graphql.GraphQLObjectType({ - name: state.name, - interfaces: [], - fields: {} - }); - } - break; - case _.RuleKinds.ARGUMENTS: - { - if (state.prevState) { - switch (state.prevState.kind) { - case _.RuleKinds.FIELD: - argDefs = fieldDef && fieldDef.args; - break; - case _.RuleKinds.DIRECTIVE: - argDefs = directiveDef && directiveDef.args; - break; - case _.RuleKinds.ALIASED_FIELD: - { - const name = (_a = state.prevState) === null || _a === void 0 ? void 0 : _a.name; - if (!name) { - argDefs = null; - break; - } - const field = parentType ? getFieldDef(schema, parentType, name) : null; - if (!field) { - argDefs = null; - break; - } - argDefs = field.args; - break; - } - default: - argDefs = null; - break; - } - } else { - argDefs = null; - } - break; - } - case _.RuleKinds.ARGUMENT: - if (argDefs) { - for (let i = 0; i < argDefs.length; i++) { - if (argDefs[i].name === state.name) { - argDef = argDefs[i]; - break; - } - } - } - inputType = argDef === null || argDef === void 0 ? void 0 : argDef.type; - break; - case _.RuleKinds.VARIABLE_DEFINITION: - case _.RuleKinds.VARIABLE: - type = inputType; - break; - case _.RuleKinds.ENUM_VALUE: - const enumType = (0, _graphql.getNamedType)(inputType); - enumValue = enumType instanceof _graphql.GraphQLEnumType ? enumType.getValues().find(val => val.value === state.name) : null; - break; - case _.RuleKinds.LIST_VALUE: - const nullableType = (0, _graphql.getNullableType)(inputType); - inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null; - break; - case _.RuleKinds.OBJECT_VALUE: - const objectType = (0, _graphql.getNamedType)(inputType); - objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null; - break; - case _.RuleKinds.OBJECT_FIELD: - const objectField = state.name && objectFieldDefs ? objectFieldDefs[state.name] : null; - inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; - fieldDef = objectField; - type = fieldDef ? fieldDef.type : null; + } + if (pos >= max) { + return false; + } + + // [link]( "title" ) + // ^^^^^^ parsing link destination + start = pos; + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); + if (res.ok) { + href = state.md.normalizeLink(res.str); + if (state.md.validateLink(href)) { + pos = res.pos; + } else { + href = ''; + } + + // [link]( "title" ) + // ^^ skipping these spaces + start = pos; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { break; - case _.RuleKinds.NAMED_TYPE: - if (state.name) { - type = schema.getType(state.name); + } + } + + // [link]( "title" ) + // ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); + if (pos < max && start !== pos && res.ok) { + title = res.str; + pos = res.pos; + + // [link]( "title" ) + // ^^ skipping these spaces + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; } - break; + } } - }); - return { - argDef, - argDefs, - directiveDef, - enumValue, - fieldDef, - inputType, - objectFieldDefs, - parentType, - type, - interfaceDef, - objectTypeDef - }; - } - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/index.js": - /*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/index.js ***! - \**********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - var _exportNames = { - CharacterStream: true, - LexRules: true, - ParseRules: true, - isIgnored: true, - butNot: true, - list: true, - opt: true, - p: true, - t: true, - onlineParser: true, - runOnlineParser: true, - getTokenAtPosition: true, - getContextAtPosition: true, - GraphQLDocumentMode: true, - getDocumentMode: true, - getTypeInfo: true, - getDefinitionState: true, - getFieldDef: true - }; - Object.defineProperty(exports, "CharacterStream", ({ - enumerable: true, - get: function () { - return _CharacterStream.default; - } - })); - Object.defineProperty(exports, "GraphQLDocumentMode", ({ - enumerable: true, - get: function () { - return _api.GraphQLDocumentMode; - } - })); - Object.defineProperty(exports, "LexRules", ({ - enumerable: true, - get: function () { - return _Rules.LexRules; } - })); - Object.defineProperty(exports, "ParseRules", ({ - enumerable: true, - get: function () { - return _Rules.ParseRules; + if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { + // parsing a valid shortcut link failed, fallback to reference + parseReference = true; } - })); - Object.defineProperty(exports, "butNot", ({ - enumerable: true, - get: function () { - return _RuleHelpers.butNot; + pos++; + } + if (parseReference) { + // + // Link reference + // + if (typeof state.env.references === 'undefined') { + return false; } - })); - Object.defineProperty(exports, "getContextAtPosition", ({ - enumerable: true, - get: function () { - return _api.getContextAtPosition; + if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { + start = pos + 1; + pos = state.md.helpers.parseLinkLabel(state, pos); + if (pos >= 0) { + label = state.src.slice(start, pos++); + } else { + pos = labelEnd + 1; + } + } else { + pos = labelEnd + 1; } - })); - Object.defineProperty(exports, "getDefinitionState", ({ - enumerable: true, - get: function () { - return _getTypeInfo.getDefinitionState; + + // covers label === '' and label === undefined + // (collapsed reference link and shortcut reference link respectively) + if (!label) { + label = state.src.slice(labelStart, labelEnd); } - })); - Object.defineProperty(exports, "getDocumentMode", ({ - enumerable: true, - get: function () { - return _api.getDocumentMode; + ref = state.env.references[normalizeReference(label)]; + if (!ref) { + state.pos = oldPos; + return false; } - })); - Object.defineProperty(exports, "getFieldDef", ({ - enumerable: true, - get: function () { - return _getTypeInfo.getFieldDef; + href = ref.href; + title = ref.title; + } + + // + // We found the end of the link, and know for a fact it's a valid link; + // so all that's left to do is to call tokenizer. + // + if (!silent) { + state.pos = labelStart; + state.posMax = labelEnd; + const token_o = state.push('link_open', 'a', 1); + const attrs = [['href', href]]; + token_o.attrs = attrs; + if (title) { + attrs.push(['title', title]); + } + state.linkLevel++; + state.md.inline.tokenize(state); + state.linkLevel--; + state.push('link_close', 'a', -1); + } + state.pos = pos; + state.posMax = max; + return true; +} + +// Process ![image]( "title") + +function image(state, silent) { + let code, content, label, pos, ref, res, title, start; + let href = ''; + const oldPos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(state.pos) !== 0x21 /* ! */) { + return false; + } + if (state.src.charCodeAt(state.pos + 1) !== 0x5B /* [ */) { + return false; + } + const labelStart = state.pos + 2; + const labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false); + + // parser failed to find ']', so it's not a valid link + if (labelEnd < 0) { + return false; + } + pos = labelEnd + 1; + if (pos < max && state.src.charCodeAt(pos) === 0x28 /* ( */) { + // + // Inline link + // + + // [link]( "title" ) + // ^^ skipping these spaces + pos++; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; + } } - })); - Object.defineProperty(exports, "getTokenAtPosition", ({ - enumerable: true, - get: function () { - return _api.getTokenAtPosition; + if (pos >= max) { + return false; } - })); - Object.defineProperty(exports, "getTypeInfo", ({ - enumerable: true, - get: function () { - return _getTypeInfo.getTypeInfo; + + // [link]( "title" ) + // ^^^^^^ parsing link destination + start = pos; + res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); + if (res.ok) { + href = state.md.normalizeLink(res.str); + if (state.md.validateLink(href)) { + pos = res.pos; + } else { + href = ''; + } } - })); - Object.defineProperty(exports, "isIgnored", ({ - enumerable: true, - get: function () { - return _Rules.isIgnored; + + // [link]( "title" ) + // ^^ skipping these spaces + start = pos; + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; + } } - })); - Object.defineProperty(exports, "list", ({ - enumerable: true, - get: function () { - return _RuleHelpers.list; + + // [link]( "title" ) + // ^^^^^^^ parsing link title + res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); + if (pos < max && start !== pos && res.ok) { + title = res.str; + pos = res.pos; + + // [link]( "title" ) + // ^^ skipping these spaces + for (; pos < max; pos++) { + code = state.src.charCodeAt(pos); + if (!isSpace(code) && code !== 0x0A) { + break; + } + } + } else { + title = ''; } - })); - Object.defineProperty(exports, "onlineParser", ({ - enumerable: true, - get: function () { - return _onlineParser.default; + if (pos >= max || state.src.charCodeAt(pos) !== 0x29 /* ) */) { + state.pos = oldPos; + return false; } - })); - Object.defineProperty(exports, "opt", ({ - enumerable: true, - get: function () { - return _RuleHelpers.opt; + pos++; + } else { + // + // Link reference + // + if (typeof state.env.references === 'undefined') { + return false; } - })); - Object.defineProperty(exports, "p", ({ - enumerable: true, - get: function () { - return _RuleHelpers.p; + if (pos < max && state.src.charCodeAt(pos) === 0x5B /* [ */) { + start = pos + 1; + pos = state.md.helpers.parseLinkLabel(state, pos); + if (pos >= 0) { + label = state.src.slice(start, pos++); + } else { + pos = labelEnd + 1; + } + } else { + pos = labelEnd + 1; } - })); - Object.defineProperty(exports, "runOnlineParser", ({ - enumerable: true, - get: function () { - return _api.runOnlineParser; + + // covers label === '' and label === undefined + // (collapsed reference link and shortcut reference link respectively) + if (!label) { + label = state.src.slice(labelStart, labelEnd); } - })); - Object.defineProperty(exports, "t", ({ - enumerable: true, - get: function () { - return _RuleHelpers.t; + ref = state.env.references[normalizeReference(label)]; + if (!ref) { + state.pos = oldPos; + return false; } - })); - var _CharacterStream = _interopRequireDefault(__webpack_require__(/*! ./CharacterStream */ "../../graphql-language-service/esm/parser/CharacterStream.js")); - var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); - var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); - var _onlineParser = _interopRequireDefault(__webpack_require__(/*! ./onlineParser */ "../../graphql-language-service/esm/parser/onlineParser.js")); - var _api = __webpack_require__(/*! ./api */ "../../graphql-language-service/esm/parser/api.js"); - var _getTypeInfo = __webpack_require__(/*! ./getTypeInfo */ "../../graphql-language-service/esm/parser/getTypeInfo.js"); - var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/parser/types.js"); - Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _types[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _types[key]; - } - }); - }); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/parser/onlineParser.js": - /*!*****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/onlineParser.js ***! - \*****************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports["default"] = onlineParser; - var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function onlineParser(options = { - eatWhitespace: stream => stream.eatWhile(_Rules.isIgnored), - lexRules: _Rules.LexRules, - parseRules: _Rules.ParseRules, - editorConfig: {} - }) { - return { - startState() { - const initialState = { - level: 0, - step: 0, - name: null, - kind: null, - type: null, - rule: null, - needsSeparator: false, - prevState: null - }; - pushRule(options.parseRules, initialState, _graphql.Kind.DOCUMENT); - return initialState; - }, - token(stream, state) { - return getToken(stream, state, options); - } - }; + href = ref.href; + title = ref.title; } - function getToken(stream, state, options) { - var _a; - if (state.inBlockstring) { - if (stream.match(/.*"""/)) { - state.inBlockstring = false; - return 'string'; - } - stream.skipToEnd(); - return 'string'; + + // + // We found the end of the link, and know for a fact it's a valid link; + // so all that's left to do is to call tokenizer. + // + if (!silent) { + content = state.src.slice(labelStart, labelEnd); + const tokens = []; + state.md.inline.parse(content, state.md, state.env, tokens); + const token = state.push('image', 'img', 0); + const attrs = [['src', href], ['alt', '']]; + token.attrs = attrs; + token.children = tokens; + token.content = content; + if (title) { + attrs.push(['title', title]); + } + } + state.pos = pos; + state.posMax = max; + return true; +} + +// Process autolinks '' + +/* eslint max-len:0 */ +const EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; +/* eslint-disable-next-line no-control-regex */ +const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/; +function autolink(state, silent) { + let pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x3C /* < */) { + return false; + } + const start = state.pos; + const max = state.posMax; + for (;;) { + if (++pos >= max) return false; + const ch = state.src.charCodeAt(pos); + if (ch === 0x3C /* < */) return false; + if (ch === 0x3E /* > */) break; + } + const url = state.src.slice(start + 1, pos); + if (AUTOLINK_RE.test(url)) { + const fullUrl = state.md.normalizeLink(url); + if (!state.md.validateLink(fullUrl)) { + return false; } - const { - lexRules, - parseRules, - eatWhitespace, - editorConfig - } = options; - if (state.rule && state.rule.length === 0) { - popRule(state); - } else if (state.needsAdvance) { - state.needsAdvance = false; - advanceRule(state, true); + if (!silent) { + const token_o = state.push('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.markup = 'autolink'; + token_o.info = 'auto'; + const token_t = state.push('text', '', 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push('link_close', 'a', -1); + token_c.markup = 'autolink'; + token_c.info = 'auto'; } - if (stream.sol()) { - const tabSize = (editorConfig === null || editorConfig === void 0 ? void 0 : editorConfig.tabSize) || 2; - state.indentLevel = Math.floor(stream.indentation() / tabSize); + state.pos += url.length + 2; + return true; + } + if (EMAIL_RE.test(url)) { + const fullUrl = state.md.normalizeLink('mailto:' + url); + if (!state.md.validateLink(fullUrl)) { + return false; } - if (eatWhitespace(stream)) { - return 'ws'; + if (!silent) { + const token_o = state.push('link_open', 'a', 1); + token_o.attrs = [['href', fullUrl]]; + token_o.markup = 'autolink'; + token_o.info = 'auto'; + const token_t = state.push('text', '', 0); + token_t.content = state.md.normalizeLinkText(url); + const token_c = state.push('link_close', 'a', -1); + token_c.markup = 'autolink'; + token_c.info = 'auto'; } - const token = lex(lexRules, stream); - if (!token) { - const matchedSomething = stream.match(/\S+/); - if (!matchedSomething) { - stream.match(/\s/); + state.pos += url.length + 2; + return true; + } + return false; +} + +// Process html tags + +function isLinkOpen(str) { + return /^\s]/i.test(str); +} +function isLinkClose(str) { + return /^<\/a\s*>/i.test(str); +} +function isLetter(ch) { + /* eslint no-bitwise:0 */ + const lc = ch | 0x20; // to lower case + return lc >= 0x61 /* a */ && lc <= 0x7a /* z */; +} +function html_inline(state, silent) { + if (!state.md.options.html) { + return false; + } + + // Check start + const max = state.posMax; + const pos = state.pos; + if (state.src.charCodeAt(pos) !== 0x3C /* < */ || pos + 2 >= max) { + return false; + } + + // Quick fail on second char + const ch = state.src.charCodeAt(pos + 1); + if (ch !== 0x21 /* ! */ && ch !== 0x3F /* ? */ && ch !== 0x2F /* / */ && !isLetter(ch)) { + return false; + } + const match = state.src.slice(pos).match(HTML_TAG_RE); + if (!match) { + return false; + } + if (!silent) { + const token = state.push('html_inline', '', 0); + token.content = match[0]; + if (isLinkOpen(token.content)) state.linkLevel++; + if (isLinkClose(token.content)) state.linkLevel--; + } + state.pos += match[0].length; + return true; +} + +// Process html entity - {, ¯, ", ... + +const DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; +const NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; +function entity(state, silent) { + const pos = state.pos; + const max = state.posMax; + if (state.src.charCodeAt(pos) !== 0x26 /* & */) return false; + if (pos + 1 >= max) return false; + const ch = state.src.charCodeAt(pos + 1); + if (ch === 0x23 /* # */) { + const match = state.src.slice(pos).match(DIGITAL_RE); + if (match) { + if (!silent) { + const code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10); + const token = state.push('text_special', '', 0); + token.content = isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD); + token.markup = match[0]; + token.info = 'entity'; } - pushRule(SpecialParseRules, state, 'Invalid'); - return 'invalidchar'; - } - if (token.kind === 'Comment') { - pushRule(SpecialParseRules, state, 'Comment'); - return 'comment'; + state.pos += match[0].length; + return true; } - const backupState = assign({}, state); - if (token.kind === 'Punctuation') { - if (/^[{([]/.test(token.value)) { - if (state.indentLevel !== undefined) { - state.levels = (state.levels || []).concat(state.indentLevel + 1); - } - } else if (/^[})\]]/.test(token.value)) { - const levels = state.levels = (state.levels || []).slice(0, -1); - if (state.indentLevel && levels.length > 0 && levels.at(-1) < state.indentLevel) { - state.indentLevel = levels.at(-1); + } else { + const match = state.src.slice(pos).match(NAMED_RE); + if (match) { + const decoded = entities.decodeHTML(match[0]); + if (decoded !== match[0]) { + if (!silent) { + const token = state.push('text_special', '', 0); + token.content = decoded; + token.markup = match[0]; + token.info = 'entity'; } + state.pos += match[0].length; + return true; } } - while (state.rule) { - let expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step]; - if (state.needsSeparator) { - expected = expected === null || expected === void 0 ? void 0 : expected.separator; - } - if (expected) { - if (expected.ofRule) { - expected = expected.ofRule; - } - if (typeof expected === 'string') { - pushRule(parseRules, state, expected); - continue; - } - if ((_a = expected.match) === null || _a === void 0 ? void 0 : _a.call(expected, token)) { - if (expected.update) { - expected.update(state, token); - } - if (token.kind === 'Punctuation') { - advanceRule(state, true); - } else { - state.needsAdvance = true; + } + return false; +} + +// For each opening emphasis-like marker find a matching closing one +// + +function processDelimiters(delimiters) { + const openersBottom = {}; + const max = delimiters.length; + if (!max) return; + + // headerIdx is the first delimiter of the current (where closer is) delimiter run + let headerIdx = 0; + let lastTokenIdx = -2; // needs any value lower than -1 + const jumps = []; + for (let closerIdx = 0; closerIdx < max; closerIdx++) { + const closer = delimiters[closerIdx]; + jumps.push(0); + + // markers belong to same delimiter run if: + // - they have adjacent tokens + // - AND markers are the same + // + if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) { + headerIdx = closerIdx; + } + lastTokenIdx = closer.token; + + // Length is only used for emphasis-specific "rule of 3", + // if it's not defined (in strikethrough or 3rd party plugins), + // we can default it to 0 to disable those checks. + // + closer.length = closer.length || 0; + if (!closer.close) continue; + + // Previously calculated lower bounds (previous fails) + // for each marker, each delimiter length modulo 3, + // and for whether this closer can be an opener; + // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 + /* eslint-disable-next-line no-prototype-builtins */ + if (!openersBottom.hasOwnProperty(closer.marker)) { + openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]; + } + const minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + closer.length % 3]; + let openerIdx = headerIdx - jumps[headerIdx] - 1; + let newMinOpenerIdx = openerIdx; + for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) { + const opener = delimiters[openerIdx]; + if (opener.marker !== closer.marker) continue; + if (opener.open && opener.end < 0) { + let isOddMatch = false; + + // from spec: + // + // If one of the delimiters can both open and close emphasis, then the + // sum of the lengths of the delimiter runs containing the opening and + // closing delimiters must not be a multiple of 3 unless both lengths + // are multiples of 3. + // + if (opener.close || closer.open) { + if ((opener.length + closer.length) % 3 === 0) { + if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { + isOddMatch = true; + } } - return expected.style; + } + if (!isOddMatch) { + // If previous delimiter cannot be an opener, we can safely skip + // the entire sequence in future checks. This is required to make + // sure algorithm has linear complexity (see *_*_*_*_*_... case). + // + const lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0; + jumps[closerIdx] = closerIdx - openerIdx + lastJump; + jumps[openerIdx] = lastJump; + closer.open = false; + opener.end = closerIdx; + opener.close = false; + newMinOpenerIdx = -1; + // treat next token as start of run, + // it optimizes skips in **<...>**a**<...>** pathological case + lastTokenIdx = -2; + break; } } - unsuccessful(state); } - assign(state, backupState); - pushRule(SpecialParseRules, state, 'Invalid'); - return 'invalidchar'; + if (newMinOpenerIdx !== -1) { + // If match for this delimiter run failed, we want to set lower bound for + // future lookups. This is required to make sure algorithm has linear + // complexity. + // + // See details here: + // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 + // + openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length || 0) % 3] = newMinOpenerIdx; + } } - function assign(to, from) { - const keys = Object.keys(from); - for (let i = 0; i < keys.length; i++) { - to[keys[i]] = from[keys[i]]; +} +function link_pairs(state) { + const tokens_meta = state.tokens_meta; + const max = state.tokens_meta.length; + processDelimiters(state.delimiters); + for (let curr = 0; curr < max; curr++) { + if (tokens_meta[curr] && tokens_meta[curr].delimiters) { + processDelimiters(tokens_meta[curr].delimiters); } - return to; } - const SpecialParseRules = { - Invalid: [], - Comment: [] - }; - function pushRule(rules, state, ruleKind) { - if (!rules[ruleKind]) { - throw new TypeError('Unknown rule: ' + ruleKind); - } - state.prevState = Object.assign({}, state); - state.kind = ruleKind; - state.name = null; - state.type = null; - state.rule = rules[ruleKind]; - state.step = 0; - state.needsSeparator = false; - } - function popRule(state) { - if (!state.prevState) { - return; +} + +// Clean up tokens after emphasis and strikethrough postprocessing: +// merge adjacent text nodes into one and re-calculate all token levels +// +// This is necessary because initially emphasis delimiter markers (*, _, ~) +// are treated as their own separate text tokens. Then emphasis rule either +// leaves them as text (needed to merge with adjacent text) or turns them +// into opening/closing tags (which messes up levels inside). +// + +function fragments_join(state) { + let curr, last; + let level = 0; + const tokens = state.tokens; + const max = state.tokens.length; + for (curr = last = 0; curr < max; curr++) { + // re-calculate levels after emphasis/strikethrough turns some text nodes + // into opening/closing tags + if (tokens[curr].nesting < 0) level--; // closing tag + tokens[curr].level = level; + if (tokens[curr].nesting > 0) level++; // opening tag + + if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { + // collapse two adjacent text nodes + tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; + } else { + if (curr !== last) { + tokens[last] = tokens[curr]; + } + last++; } - state.kind = state.prevState.kind; - state.name = state.prevState.name; - state.type = state.prevState.type; - state.rule = state.prevState.rule; - state.step = state.prevState.step; - state.needsSeparator = state.prevState.needsSeparator; - state.prevState = state.prevState.prevState; } - function advanceRule(state, successful) { - var _a; - if (isList(state) && state.rule) { - const step = state.rule[state.step]; - if (step.separator) { - const { - separator - } = step; - state.needsSeparator = !state.needsSeparator; - if (!state.needsSeparator && separator.ofRule) { - return; + if (curr !== last) { + tokens.length = last; + } +} + +/** internal + * class ParserInline + * + * Tokenizes paragraph content. + **/ + +// Parser rules + +const _rules = [['text', text], ['linkify', linkify], ['newline', newline], ['escape', escape], ['backticks', backtick], ['strikethrough', r_strikethrough.tokenize], ['emphasis', r_emphasis.tokenize], ['link', link], ['image', image], ['autolink', autolink], ['html_inline', html_inline], ['entity', entity]]; + +// `rule2` ruleset was created specifically for emphasis/strikethrough +// post-processing and may be changed in the future. +// +// Don't use this for anything except pairs (plugins working with `balance_pairs`). +// +const _rules2 = [['balance_pairs', link_pairs], ['strikethrough', r_strikethrough.postProcess], ['emphasis', r_emphasis.postProcess], +// rules for pairs separate '**' into its own text tokens, which may be left unused, +// rule below merges unused segments back with the rest of the text +['fragments_join', fragments_join]]; + +/** + * new ParserInline() + **/ +function ParserInline() { + /** + * ParserInline#ruler -> Ruler + * + * [[Ruler]] instance. Keep configuration of inline rules. + **/ + this.ruler = new Ruler(); + for (let i = 0; i < _rules.length; i++) { + this.ruler.push(_rules[i][0], _rules[i][1]); + } + + /** + * ParserInline#ruler2 -> Ruler + * + * [[Ruler]] instance. Second ruler used for post-processing + * (e.g. in emphasis-like rules). + **/ + this.ruler2 = new Ruler(); + for (let i = 0; i < _rules2.length; i++) { + this.ruler2.push(_rules2[i][0], _rules2[i][1]); + } +} + +// Skip single token by running all rules in validation mode; +// returns `true` if any rule reported success +// +ParserInline.prototype.skipToken = function (state) { + const pos = state.pos; + const rules = this.ruler.getRules(''); + const len = rules.length; + const maxNesting = state.md.options.maxNesting; + const cache = state.cache; + if (typeof cache[pos] !== 'undefined') { + state.pos = cache[pos]; + return; + } + let ok = false; + if (state.level < maxNesting) { + for (let i = 0; i < len; i++) { + // Increment state.level and decrement it later to limit recursion. + // It's harmless to do here, because no tokens are created. But ideally, + // we'd need a separate private state variable for this purpose. + // + state.level++; + ok = rules[i](state, true); + state.level--; + if (ok) { + if (pos >= state.pos) { + throw new Error("inline rule didn't increment state.pos"); } - } - if (successful) { - return; + break; } } - state.needsSeparator = false; - state.step++; - while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) { - popRule(state); - if (state.rule) { - if (isList(state)) { - if ((_a = state.rule) === null || _a === void 0 ? void 0 : _a[state.step].separator) { - state.needsSeparator = !state.needsSeparator; + } else { + // Too much nesting, just skip until the end of the paragraph. + // + // NOTE: this will cause links to behave incorrectly in the following case, + // when an amount of `[` is exactly equal to `maxNesting + 1`: + // + // [[[[[[[[[[[[[[[[[[[[[foo]() + // + // TODO: remove this workaround when CM standard will allow nested links + // (we can replace it by preventing links from being parsed in + // validation mode) + // + state.pos = state.posMax; + } + if (!ok) { + state.pos++; + } + cache[pos] = state.pos; +}; + +// Generate tokens for input range +// +ParserInline.prototype.tokenize = function (state) { + const rules = this.ruler.getRules(''); + const len = rules.length; + const end = state.posMax; + const maxNesting = state.md.options.maxNesting; + while (state.pos < end) { + // Try all possible rules. + // On success, rule should: + // + // - update `state.pos` + // - update `state.tokens` + // - return true + const prevPos = state.pos; + let ok = false; + if (state.level < maxNesting) { + for (let i = 0; i < len; i++) { + ok = rules[i](state, false); + if (ok) { + if (prevPos >= state.pos) { + throw new Error("inline rule didn't increment state.pos"); } - } else { - state.needsSeparator = false; - state.step++; + break; } } } + if (ok) { + if (state.pos >= end) { + break; + } + continue; + } + state.pending += state.src[state.pos++]; } - function isList(state) { - const step = Array.isArray(state.rule) && typeof state.rule[state.step] !== 'string' && state.rule[state.step]; - return step && step.isList; + if (state.pending) { + state.pushPending(); } - function unsuccessful(state) { - while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) { - popRule(state); - } - if (state.rule) { - advanceRule(state, false); +}; + +/** + * ParserInline.parse(str, md, env, outTokens) + * + * Process input string and push inline tokens into `outTokens` + **/ +ParserInline.prototype.parse = function (str, md, env, outTokens) { + const state = new this.State(str, md, env, outTokens); + this.tokenize(state); + const rules = this.ruler2.getRules(''); + const len = rules.length; + for (let i = 0; i < len; i++) { + rules[i](state); + } +}; +ParserInline.prototype.State = StateInline; + +// markdown-it default options + +var cfg_default = { + options: { + // Enable HTML tags in source + html: false, + // Use '/' to close single tags (
    ) + xhtmlOut: false, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: 'language-', + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: '\u201c\u201d\u2018\u2019', + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with ) + xhtmlOut: false, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: 'language-', + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: '\u201c\u201d\u2018\u2019', + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with ) + xhtmlOut: true, + // Convert '\n' in paragraphs into
    + breaks: false, + // CSS language prefix for fenced blocks + langPrefix: 'language-', + // autoconvert URL-like texts to links + linkify: false, + // Enable some language-neutral replacements + quotes beautification + typographer: false, + // Double + single quotes replacement pairs, when typographer enabled, + // and smartquotes on. Could be either a String or an Array. + // + // For example, you can use '«»„“' for Russian, '„“‚‘' for German, + // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). + quotes: '\u201c\u201d\u2018\u2019', + /* “”‘’ */ + + // Highlighter function. Should return escaped HTML, + // or '' if the source string is not changed and should be escaped externaly. + // If result starts with { - if (this.start.line === position.line) { - return this.start.character <= position.character; - } - if (this.end.line === position.line) { - return this.end.character >= position.character; - } - return this.start.line <= position.line && this.end.line >= position.line; - }; - this.start = start; - this.end = end; - } - setStart(line, character) { - this.start = new Position(line, character); - } - setEnd(line, character) { - this.end = new Position(line, character); +}; + +// Main parser class + +const config = { + default: cfg_default, + zero: cfg_zero, + commonmark: cfg_commonmark +}; + +// +// This validator can prohibit more than really needed to prevent XSS. It's a +// tradeoff to keep code simple and to be secure by default. +// +// If you need different setup - override validator method as you wish. Or +// replace it with dummy function and use external sanitizer. +// + +const BAD_PROTO_RE = /^(vbscript|javascript|file|data):/; +const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/; +function validateLink(url) { + // url should be normalized at this point, and existing entities are decoded + const str = url.trim().toLowerCase(); + return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : true; +} +const RECODE_HOSTNAME_FOR = ['http:', 'https:', 'mailto:']; +function normalizeLink(url) { + const parsed = mdurl__namespace.parse(url, true); + if (parsed.hostname) { + // Encode hostnames in urls like: + // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + // + // We don't encode unknown schemas, because it's likely that we encode + // something we shouldn't (e.g. `skype:name` treated as `skype:host`) + // + if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { + try { + parsed.hostname = punycode.toASCII(parsed.hostname); + } catch (er) {/**/} } } - exports.Range = Range; - class Position { - constructor(line, character) { - this.lessThanOrEqualTo = position => this.line < position.line || this.line === position.line && this.character <= position.character; - this.line = line; - this.character = character; - } - setLine(line) { - this.line = line; - } - setCharacter(character) { - this.character = character; + return mdurl__namespace.encode(mdurl__namespace.format(parsed)); +} +function normalizeLinkText(url) { + const parsed = mdurl__namespace.parse(url, true); + if (parsed.hostname) { + // Encode hostnames in urls like: + // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` + // + // We don't encode unknown schemas, because it's likely that we encode + // something we shouldn't (e.g. `skype:name` treated as `skype:host`) + // + if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { + try { + parsed.hostname = punycode.toUnicode(parsed.hostname); + } catch (er) {/**/} } } - exports.Position = Position; - function offsetToPosition(text, loc) { - const EOL = '\n'; - const buf = text.slice(0, loc); - const lines = buf.split(EOL).length - 1; - const lastLineIndex = buf.lastIndexOf(EOL); - return new Position(lines, loc - lastLineIndex - 1); + + // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 + return mdurl__namespace.decode(mdurl__namespace.format(parsed), mdurl__namespace.decode.defaultChars + '%'); +} + +/** + * class MarkdownIt + * + * Main parser/renderer class. + * + * ##### Usage + * + * ```javascript + * // node.js, "classic" way: + * var MarkdownIt = require('markdown-it'), + * md = new MarkdownIt(); + * var result = md.render('# markdown-it rulezz!'); + * + * // node.js, the same, but with sugar: + * var md = require('markdown-it')(); + * var result = md.render('# markdown-it rulezz!'); + * + * // browser without AMD, added to "window" on script load + * // Note, there are no dash. + * var md = window.markdownit(); + * var result = md.render('# markdown-it rulezz!'); + * ``` + * + * Single line rendering, without paragraph wrap: + * + * ```javascript + * var md = require('markdown-it')(); + * var result = md.renderInline('__markdown-it__ rulezz!'); + * ``` + **/ + +/** + * new MarkdownIt([presetName, options]) + * - presetName (String): optional, `commonmark` / `zero` + * - options (Object) + * + * Creates parser instanse with given config. Can be called without `new`. + * + * ##### presetName + * + * MarkdownIt provides named presets as a convenience to quickly + * enable/disable active syntax rules and options for common use cases. + * + * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.mjs) - + * configures parser to strict [CommonMark](http://commonmark.org/) mode. + * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.mjs) - + * similar to GFM, used when no preset name given. Enables all available rules, + * but still without html, typographer & autolinker. + * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.mjs) - + * all rules disabled. Useful to quickly setup your config via `.enable()`. + * For example, when you need only `bold` and `italic` markup and nothing else. + * + * ##### options: + * + * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! + * That's not safe! You may need external sanitizer to protect output from XSS. + * It's better to extend features via plugins, instead of enabling HTML. + * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags + * (`
    `). This is needed only for full CommonMark compatibility. In real + * world you will need HTML output. + * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
    `. + * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. + * Can be useful for external highlighters. + * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. + * - __typographer__ - `false`. Set `true` to enable [some language-neutral + * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs) + + * quotes beautification (smartquotes). + * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement + * pairs, when typographer enabled and smartquotes on. For example, you can + * use `'«»„“'` for Russian, `'„“‚‘'` for German, and + * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). + * - __highlight__ - `null`. Highlighter function for fenced code blocks. + * Highlighter `function (str, lang)` should return escaped HTML. It can also + * return empty string if the source was not changed and should be escaped + * externaly. If result starts with ` or ``): + * + * ```javascript + * var hljs = require('highlight.js') // https://highlightjs.org/ + * + * // Actual default values + * var md = require('markdown-it')({ + * highlight: function (str, lang) { + * if (lang && hljs.getLanguage(lang)) { + * try { + * return '
    ' +
    + *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
    + *                '
    '; + * } catch (__) {} + * } + * + * return '
    ' + md.utils.escapeHtml(str) + '
    '; + * } + * }); + * ``` + * + **/ +function MarkdownIt(presetName, options) { + if (!(this instanceof MarkdownIt)) { + return new MarkdownIt(presetName, options); + } + if (!options) { + if (!isString(presetName)) { + options = presetName || {}; + presetName = 'default'; + } } - function locToRange(text, loc) { - const start = offsetToPosition(text, loc.start); - const end = offsetToPosition(text, loc.end); - return new Range(start, end); + + /** + * MarkdownIt#inline -> ParserInline + * + * Instance of [[ParserInline]]. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.inline = new ParserInline(); + + /** + * MarkdownIt#block -> ParserBlock + * + * Instance of [[ParserBlock]]. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.block = new ParserBlock(); + + /** + * MarkdownIt#core -> Core + * + * Instance of [[Core]] chain executor. You may need it to add new rules when + * writing plugins. For simple rules control use [[MarkdownIt.disable]] and + * [[MarkdownIt.enable]]. + **/ + this.core = new Core(); + + /** + * MarkdownIt#renderer -> Renderer + * + * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering + * rules for new token types, generated by plugins. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')(); + * + * function myToken(tokens, idx, options, env, self) { + * //... + * return result; + * }; + * + * md.renderer.rules['my_token'] = myToken + * ``` + * + * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs). + **/ + this.renderer = new Renderer(); + + /** + * MarkdownIt#linkify -> LinkifyIt + * + * [linkify-it](https://github.com/markdown-it/linkify-it) instance. + * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.mjs) + * rule. + **/ + this.linkify = new LinkifyIt(); + + /** + * MarkdownIt#validateLink(url) -> Boolean + * + * Link validation function. CommonMark allows too much in links. By default + * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas + * except some embedded image types. + * + * You can change this behaviour: + * + * ```javascript + * var md = require('markdown-it')(); + * // enable everything + * md.validateLink = function () { return true; } + * ``` + **/ + this.validateLink = validateLink; + + /** + * MarkdownIt#normalizeLink(url) -> String + * + * Function used to encode link url to a machine-readable format, + * which includes url-encoding, punycode, etc. + **/ + this.normalizeLink = normalizeLink; + + /** + * MarkdownIt#normalizeLinkText(url) -> String + * + * Function used to decode link url to a human-readable format` + **/ + this.normalizeLinkText = normalizeLinkText; + + // Expose utils & helpers for easy acces from plugins + + /** + * MarkdownIt#utils -> utils + * + * Assorted utility functions, useful to write plugins. See details + * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.mjs). + **/ + this.utils = utils; + + /** + * MarkdownIt#helpers -> helpers + * + * Link components parser functions, useful to write plugins. See details + * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). + **/ + this.helpers = assign({}, helpers); + this.options = {}; + this.configure(presetName); + if (options) { + this.set(options); } - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/collectVariables.js": - /*!********************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/collectVariables.js ***! - \********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.collectVariables = collectVariables; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function collectVariables(schema, documentAST) { - const variableToType = Object.create(null); - for (const definition of documentAST.definitions) { - if (definition.kind === 'OperationDefinition') { - const { - variableDefinitions - } = definition; - if (variableDefinitions) { - for (const { - variable, - type - } of variableDefinitions) { - const inputType = (0, _graphql.typeFromAST)(schema, type); - if (inputType) { - variableToType[variable.name.value] = inputType; - } else if (type.kind === _graphql.Kind.NAMED_TYPE && type.name.value === 'Float') { - variableToType[variable.name.value] = _graphql.GraphQLFloat; - } - } - } - } +} + +/** chainable + * MarkdownIt.set(options) + * + * Set parser options (in the same format as in constructor). Probably, you + * will never need it, but you can change options after constructor call. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')() + * .set({ html: true, breaks: true }) + * .set({ typographer, true }); + * ``` + * + * __Note:__ To achieve the best possible performance, don't modify a + * `markdown-it` instance options on the fly. If you need multiple configurations + * it's best to create multiple instances and initialize each with separate + * config. + **/ +MarkdownIt.prototype.set = function (options) { + assign(this.options, options); + return this; +}; + +/** chainable, internal + * MarkdownIt.configure(presets) + * + * Batch load of all options and compenent settings. This is internal method, + * and you probably will not need it. But if you will - see available presets + * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) + * + * We strongly recommend to use presets instead of direct config loads. That + * will give better compatibility with next versions. + **/ +MarkdownIt.prototype.configure = function (presets) { + const self = this; + if (isString(presets)) { + const presetName = presets; + presets = config[presetName]; + if (!presets) { + throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name'); } - return variableToType; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/fragmentDependencies.js": - /*!************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/fragmentDependencies.js ***! - \************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getFragmentDependenciesForAST = exports.getFragmentDependencies = void 0; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _nullthrows = _interopRequireDefault(__webpack_require__(/*! nullthrows */ "../../../node_modules/nullthrows/nullthrows.js")); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - const getFragmentDependencies = (operationString, fragmentDefinitions) => { - if (!fragmentDefinitions) { - return []; - } - let parsedOperation; - try { - parsedOperation = (0, _graphql.parse)(operationString); - } catch (_a) { - return []; - } - return getFragmentDependenciesForAST(parsedOperation, fragmentDefinitions); - }; - exports.getFragmentDependencies = getFragmentDependencies; - const getFragmentDependenciesForAST = (parsedOperation, fragmentDefinitions) => { - if (!fragmentDefinitions) { - return []; - } - const existingFrags = new Map(); - const referencedFragNames = new Set(); - (0, _graphql.visit)(parsedOperation, { - FragmentDefinition(node) { - existingFrags.set(node.name.value, true); - }, - FragmentSpread(node) { - if (!referencedFragNames.has(node.name.value)) { - referencedFragNames.add(node.name.value); - } - } - }); - const asts = new Set(); - for (const name of referencedFragNames) { - if (!existingFrags.has(name) && fragmentDefinitions.has(name)) { - asts.add((0, _nullthrows.default)(fragmentDefinitions.get(name))); - } - } - const referencedFragments = []; - for (const ast of asts) { - (0, _graphql.visit)(ast, { - FragmentSpread(node) { - if (!referencedFragNames.has(node.name.value) && fragmentDefinitions.get(node.name.value)) { - asts.add((0, _nullthrows.default)(fragmentDefinitions.get(node.name.value))); - referencedFragNames.add(node.name.value); - } - } - }); - if (!existingFrags.has(ast.name.value)) { - referencedFragments.push(ast); - } - } - return referencedFragments; - }; - exports.getFragmentDependenciesForAST = getFragmentDependenciesForAST; - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js": - /*!************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getASTNodeAtPosition.js ***! - \************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.getASTNodeAtPosition = getASTNodeAtPosition; - exports.pointToOffset = pointToOffset; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - function getASTNodeAtPosition(query, ast, point) { - const offset = pointToOffset(query, point); - let nodeContainingPosition; - (0, _graphql.visit)(ast, { - enter(node) { - if (node.kind !== 'Name' && node.loc && node.loc.start <= offset && offset <= node.loc.end) { - nodeContainingPosition = node; - } else { - return false; - } - }, - leave(node) { - if (node.loc && node.loc.start <= offset && offset <= node.loc.end) { - return false; - } - } - }); - return nodeContainingPosition; + if (!presets) { + throw new Error('Wrong `markdown-it` preset, can\'t be empty'); } - function pointToOffset(text, point) { - const linesUntilPosition = text.split('\n').slice(0, point.line); - return point.character + linesUntilPosition.map(line => line.length + 1).reduce((a, b) => a + b, 0); + if (presets.options) { + self.set(presets.options); } - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/getOperationFacts.js": - /*!*********************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getOperationFacts.js ***! - \*********************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports["default"] = getOperationFacts; - exports.getOperationASTFacts = getOperationASTFacts; - exports.getQueryFacts = void 0; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); - function getOperationASTFacts(documentAST, schema) { - const variableToType = schema ? (0, _collectVariables.collectVariables)(schema, documentAST) : undefined; - const operations = []; - (0, _graphql.visit)(documentAST, { - OperationDefinition(node) { - operations.push(node); + if (presets.components) { + Object.keys(presets.components).forEach(function (name) { + if (presets.components[name].rules) { + self[name].ruler.enableOnly(presets.components[name].rules); + } + if (presets.components[name].rules2) { + self[name].ruler2.enableOnly(presets.components[name].rules2); } }); - return { - variableToType, - operations - }; } - function getOperationFacts(schema, documentString) { - if (!documentString) { - return; - } - try { - const documentAST = (0, _graphql.parse)(documentString); - return Object.assign(Object.assign({}, getOperationASTFacts(documentAST, schema)), { - documentAST - }); - } catch (_a) { - return; - } + return this; +}; + +/** chainable + * MarkdownIt.enable(list, ignoreInvalid) + * - list (String|Array): rule name or list of rule names to enable + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * Enable list or rules. It will automatically find appropriate components, + * containing rules with given names. If rule not found, and `ignoreInvalid` + * not set - throws exception. + * + * ##### Example + * + * ```javascript + * var md = require('markdown-it')() + * .enable(['sub', 'sup']) + * .disable('smartquotes'); + * ``` + **/ +MarkdownIt.prototype.enable = function (list, ignoreInvalid) { + let result = []; + if (!Array.isArray(list)) { + list = [list]; + } + ['core', 'block', 'inline'].forEach(function (chain) { + result = result.concat(this[chain].ruler.enable(list, true)); + }, this); + result = result.concat(this.inline.ruler2.enable(list, true)); + const missed = list.filter(function (name) { + return result.indexOf(name) < 0; + }); + if (missed.length && !ignoreInvalid) { + throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed); } - const getQueryFacts = exports.getQueryFacts = getOperationFacts; - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js": - /*!**************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getVariablesJSONSchema.js ***! - \**************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.defaultJSONSchemaOptions = void 0; - exports.getVariablesJSONSchema = getVariablesJSONSchema; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const defaultJSONSchemaOptions = exports.defaultJSONSchemaOptions = { - useMarkdownDescription: false - }; - function text(into, newText) { - into.push(newText); - } - function renderType(into, t) { - if ((0, _graphql.isNonNullType)(t)) { - renderType(into, t.ofType); - text(into, '!'); - } else if ((0, _graphql.isListType)(t)) { - text(into, '['); - renderType(into, t.ofType); - text(into, ']'); - } else { - text(into, t.name); - } + return this; +}; + +/** chainable + * MarkdownIt.disable(list, ignoreInvalid) + * - list (String|Array): rule name or list of rule names to disable. + * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. + * + * The same as [[MarkdownIt.enable]], but turn specified rules off. + **/ +MarkdownIt.prototype.disable = function (list, ignoreInvalid) { + let result = []; + if (!Array.isArray(list)) { + list = [list]; + } + ['core', 'block', 'inline'].forEach(function (chain) { + result = result.concat(this[chain].ruler.disable(list, true)); + }, this); + result = result.concat(this.inline.ruler2.disable(list, true)); + const missed = list.filter(function (name) { + return result.indexOf(name) < 0; + }); + if (missed.length && !ignoreInvalid) { + throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed); } - function renderDefinitionDescription(t, useMarkdown, description) { - const into = []; - const type = 'type' in t ? t.type : t; - if ('type' in t && t.description) { - text(into, t.description); - text(into, '\n\n'); - } - text(into, renderTypeToString(type, useMarkdown)); - if (description) { - text(into, '\n'); - text(into, description); - } else if (!(0, _graphql.isScalarType)(type) && 'description' in type && type.description) { - text(into, '\n'); - text(into, type.description); - } else if ('ofType' in type && !(0, _graphql.isScalarType)(type.ofType) && 'description' in type.ofType && type.ofType.description) { - text(into, '\n'); - text(into, type.ofType.description); - } - return into.join(''); - } - function renderTypeToString(t, useMarkdown) { - const into = []; - if (useMarkdown) { - text(into, '```graphql\n'); - } - renderType(into, t); - if (useMarkdown) { - text(into, '\n```'); - } - return into.join(''); + return this; +}; + +/** chainable + * MarkdownIt.use(plugin, params) + * + * Load specified plugin with given params into current parser instance. + * It's just a sugar to call `plugin(md, params)` with curring. + * + * ##### Example + * + * ```javascript + * var iterator = require('markdown-it-for-inline'); + * var md = require('markdown-it')() + * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { + * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); + * }); + * ``` + **/ +MarkdownIt.prototype.use = function (plugin /*, params, ... */) { + const args = [this].concat(Array.prototype.slice.call(arguments, 1)); + plugin.apply(plugin, args); + return this; +}; + +/** internal + * MarkdownIt.parse(src, env) -> Array + * - src (String): source string + * - env (Object): environment sandbox + * + * Parse input string and return list of block tokens (special token type + * "inline" will contain list of inline tokens). You should not call this + * method directly, until you write custom renderer (for example, to produce + * AST). + * + * `env` is used to pass data between "distributed" rules and return additional + * metadata like reference info, needed for the renderer. It also can be used to + * inject data in specific cases. Usually, you will be ok to pass `{}`, + * and then pass updated object to renderer. + **/ +MarkdownIt.prototype.parse = function (src, env) { + if (typeof src !== 'string') { + throw new Error('Input data should be a String'); + } + const state = new this.core.State(src, this, env); + this.core.process(state); + return state.tokens; +}; + +/** + * MarkdownIt.render(src [, env]) -> String + * - src (String): source string + * - env (Object): environment sandbox + * + * Render markdown string into html. It does all magic for you :). + * + * `env` can be used to inject additional metadata (`{}` by default). + * But you will not need it with high probability. See also comment + * in [[MarkdownIt.parse]]. + **/ +MarkdownIt.prototype.render = function (src, env) { + env = env || {}; + return this.renderer.render(this.parse(src, env), this.options, env); +}; + +/** internal + * MarkdownIt.parseInline(src, env) -> Array + * - src (String): source string + * - env (Object): environment sandbox + * + * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the + * block tokens list with the single `inline` element, containing parsed inline + * tokens in `children` property. Also updates `env` object. + **/ +MarkdownIt.prototype.parseInline = function (src, env) { + const state = new this.core.State(src, this, env); + state.inlineMode = true; + this.core.process(state); + return state.tokens; +}; + +/** + * MarkdownIt.renderInline(src [, env]) -> String + * - src (String): source string + * - env (Object): environment sandbox + * + * Similar to [[MarkdownIt.render]] but for single paragraph content. Result + * will NOT be wrapped into `

    ` tags. + **/ +MarkdownIt.prototype.renderInline = function (src, env) { + env = env || {}; + return this.renderer.render(this.parseInline(src, env), this.options, env); +}; +module.exports = MarkdownIt; + +/***/ }), + +/***/ "../node_modules/mdurl/build/index.cjs.js": +/*!************************************************!*\ + !*** ../node_modules/mdurl/build/index.cjs.js ***! + \************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +/* eslint-disable no-bitwise */ +const decodeCache = {}; +function getDecodeCache(exclude) { + let cache = decodeCache[exclude]; + if (cache) { + return cache; } - const defaultScalarTypesMap = { - Int: { - type: 'integer' - }, - String: { - type: 'string' - }, - Float: { - type: 'number' - }, - ID: { - type: 'string' - }, - Boolean: { - type: 'boolean' - }, - DateTime: { - type: 'string' - } - }; - class Marker { - constructor() { - this.set = new Set(); - } - mark(name) { - if (this.set.has(name)) { - return false; - } - this.set.add(name); - return true; - } + cache = decodeCache[exclude] = []; + for (let i = 0; i < 128; i++) { + const ch = String.fromCharCode(i); + cache.push(ch); } - function getJSONSchemaFromGraphQLType(fieldOrType, options) { - var _a, _b; - let definition = Object.create(null); - const definitions = Object.create(null); - const isField = ('type' in fieldOrType); - const type = isField ? fieldOrType.type : fieldOrType; - const baseType = (0, _graphql.isNonNullType)(type) ? type.ofType : type; - const required = (0, _graphql.isNonNullType)(type); - if ((0, _graphql.isScalarType)(baseType)) { - if ((_a = options === null || options === void 0 ? void 0 : options.scalarSchemas) === null || _a === void 0 ? void 0 : _a[baseType.name]) { - definition = JSON.parse(JSON.stringify(options.scalarSchemas[baseType.name])); - } else { - definition.type = ['string', 'number', 'boolean', 'integer']; - } - if (!required) { - if (Array.isArray(definition.type)) { - definition.type.push('null'); - } else if (definition.type) { - definition.type = [definition.type, 'null']; - } else if (definition.enum) { - definition.enum.push(null); - } else if (definition.oneOf) { - definition.oneOf.push({ - type: 'null' - }); - } else { - definition = { - oneOf: [definition, { - type: 'null' - }] - }; - } - } - } else if ((0, _graphql.isEnumType)(baseType)) { - definition.enum = baseType.getValues().map(val => val.name); - if (!required) { - definition.enum.push(null); - } - } else if ((0, _graphql.isListType)(baseType)) { - if (required) { - definition.type = 'array'; - } else { - definition.type = ['array', 'null']; + for (let i = 0; i < exclude.length; i++) { + const ch = exclude.charCodeAt(i); + cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2); + } + return cache; +} + +// Decode percent-encoded string. +// +function decode(string, exclude) { + if (typeof exclude !== 'string') { + exclude = decode.defaultChars; + } + const cache = getDecodeCache(exclude); + return string.replace(/(%[a-f0-9]{2})+/gi, function (seq) { + let result = ''; + for (let i = 0, l = seq.length; i < l; i += 3) { + const b1 = parseInt(seq.slice(i + 1, i + 3), 16); + if (b1 < 0x80) { + result += cache[b1]; + continue; } - const { - definition: def, - definitions: defs - } = getJSONSchemaFromGraphQLType(baseType.ofType, options); - definition.items = def; - if (defs) { - for (const defName of Object.keys(defs)) { - definitions[defName] = defs[defName]; + if ((b1 & 0xE0) === 0xC0 && i + 3 < l) { + // 110xxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + if ((b2 & 0xC0) === 0x80) { + const chr = b1 << 6 & 0x7C0 | b2 & 0x3F; + if (chr < 0x80) { + result += '\ufffd\ufffd'; + } else { + result += String.fromCharCode(chr); + } + i += 3; + continue; } } - } else if ((0, _graphql.isInputObjectType)(baseType)) { - if (required) { - definition.$ref = `#/definitions/${baseType.name}`; - } else { - definition.oneOf = [{ - $ref: `#/definitions/${baseType.name}` - }, { - type: 'null' - }]; - } - if ((_b = options === null || options === void 0 ? void 0 : options.definitionMarker) === null || _b === void 0 ? void 0 : _b.mark(baseType.name)) { - const fields = baseType.getFields(); - const fieldDef = { - type: 'object', - properties: {}, - required: [] - }; - fieldDef.description = renderDefinitionDescription(baseType); - if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { - fieldDef.markdownDescription = renderDefinitionDescription(baseType, true); - } - for (const fieldName of Object.keys(fields)) { - const field = fields[fieldName]; - const { - required: fieldRequired, - definition: fieldDefinition, - definitions: typeDefinitions - } = getJSONSchemaFromGraphQLType(field, options); - fieldDef.properties[fieldName] = fieldDefinition; - if (fieldRequired) { - fieldDef.required.push(fieldName); - } - if (typeDefinitions) { - for (const [defName, value] of Object.entries(typeDefinitions)) { - definitions[defName] = value; - } + if ((b1 & 0xF0) === 0xE0 && i + 6 < l) { + // 1110xxxx 10xxxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + const b3 = parseInt(seq.slice(i + 7, i + 9), 16); + if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { + const chr = b1 << 12 & 0xF000 | b2 << 6 & 0xFC0 | b3 & 0x3F; + if (chr < 0x800 || chr >= 0xD800 && chr <= 0xDFFF) { + result += '\ufffd\ufffd\ufffd'; + } else { + result += String.fromCharCode(chr); } + i += 6; + continue; } - definitions[baseType.name] = fieldDef; } - } - if ('defaultValue' in fieldOrType && fieldOrType.defaultValue !== undefined) { - definition.default = fieldOrType.defaultValue; - } - const { - description - } = definition; - definition.description = renderDefinitionDescription(fieldOrType, false, description); - if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { - definition.markdownDescription = renderDefinitionDescription(fieldOrType, true, description); - } - return { - required, - definition, - definitions - }; - } - function getVariablesJSONSchema(variableToType, options) { - var _a; - const jsonSchema = { - $schema: 'http://json-schema.org/draft-04/schema', - type: 'object', - properties: {}, - required: [] - }; - const runtimeOptions = Object.assign(Object.assign({}, options), { - definitionMarker: new Marker(), - scalarSchemas: Object.assign(Object.assign({}, defaultScalarTypesMap), options === null || options === void 0 ? void 0 : options.scalarSchemas) - }); - if (variableToType) { - for (const [variableName, type] of Object.entries(variableToType)) { - const { - definition, - required, - definitions - } = getJSONSchemaFromGraphQLType(type, runtimeOptions); - jsonSchema.properties[variableName] = definition; - if (required) { - (_a = jsonSchema.required) === null || _a === void 0 ? void 0 : _a.push(variableName); - } - if (definitions) { - jsonSchema.definitions = Object.assign(Object.assign({}, jsonSchema === null || jsonSchema === void 0 ? void 0 : jsonSchema.definitions), definitions); + if ((b1 & 0xF8) === 0xF0 && i + 9 < l) { + // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx + const b2 = parseInt(seq.slice(i + 4, i + 6), 16); + const b3 = parseInt(seq.slice(i + 7, i + 9), 16); + const b4 = parseInt(seq.slice(i + 10, i + 12), 16); + if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) { + let chr = b1 << 18 & 0x1C0000 | b2 << 12 & 0x3F000 | b3 << 6 & 0xFC0 | b4 & 0x3F; + if (chr < 0x10000 || chr > 0x10FFFF) { + result += '\ufffd\ufffd\ufffd\ufffd'; + } else { + chr -= 0x10000; + result += String.fromCharCode(0xD800 + (chr >> 10), 0xDC00 + (chr & 0x3FF)); + } + i += 9; + continue; } } + result += '\ufffd'; } - return jsonSchema; + return result; + }); +} +decode.defaultChars = ';/?:@&=+$,#'; +decode.componentChars = ''; +const encodeCache = {}; + +// Create a lookup array where anything but characters in `chars` string +// and alphanumeric chars is percent-encoded. +// +function getEncodeCache(exclude) { + let cache = encodeCache[exclude]; + if (cache) { + return cache; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/index.js": - /*!*********************************************************!*\ - !*** ../../graphql-language-service/esm/utils/index.js ***! - \*********************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - Object.defineProperty(exports, "Position", ({ - enumerable: true, - get: function () { - return _Range.Position; - } - })); - Object.defineProperty(exports, "Range", ({ - enumerable: true, - get: function () { - return _Range.Range; - } - })); - Object.defineProperty(exports, "collectVariables", ({ - enumerable: true, - get: function () { - return _collectVariables.collectVariables; - } - })); - Object.defineProperty(exports, "getASTNodeAtPosition", ({ - enumerable: true, - get: function () { - return _getASTNodeAtPosition.getASTNodeAtPosition; - } - })); - Object.defineProperty(exports, "getFragmentDependencies", ({ - enumerable: true, - get: function () { - return _fragmentDependencies.getFragmentDependencies; - } - })); - Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ - enumerable: true, - get: function () { - return _fragmentDependencies.getFragmentDependenciesForAST; - } - })); - Object.defineProperty(exports, "getOperationASTFacts", ({ - enumerable: true, - get: function () { - return _getOperationFacts.getOperationASTFacts; + cache = encodeCache[exclude] = []; + for (let i = 0; i < 128; i++) { + const ch = String.fromCharCode(i); + if (/^[0-9a-z]$/i.test(ch)) { + // always allow unencoded alphanumeric characters + cache.push(ch); + } else { + cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2)); } - })); - Object.defineProperty(exports, "getOperationFacts", ({ - enumerable: true, - get: function () { - return _getOperationFacts.default; + } + for (let i = 0; i < exclude.length; i++) { + cache[exclude.charCodeAt(i)] = exclude[i]; + } + return cache; +} + +// Encode unsafe characters with percent-encoding, skipping already +// encoded sequences. +// +// - string - string to encode +// - exclude - list of characters to ignore (in addition to a-zA-Z0-9) +// - keepEscaped - don't encode '%' in a correct escape sequence (default: true) +// +function encode(string, exclude, keepEscaped) { + if (typeof exclude !== 'string') { + // encode(string, keepEscaped) + keepEscaped = exclude; + exclude = encode.defaultChars; + } + if (typeof keepEscaped === 'undefined') { + keepEscaped = true; + } + const cache = getEncodeCache(exclude); + let result = ''; + for (let i = 0, l = string.length; i < l; i++) { + const code = string.charCodeAt(i); + if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { + if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { + result += string.slice(i, i + 3); + i += 2; + continue; + } } - })); - Object.defineProperty(exports, "getQueryFacts", ({ - enumerable: true, - get: function () { - return _getOperationFacts.getQueryFacts; + if (code < 128) { + result += cache[code]; + continue; } - })); - Object.defineProperty(exports, "getVariablesJSONSchema", ({ - enumerable: true, - get: function () { - return _getVariablesJSONSchema.getVariablesJSONSchema; + if (code >= 0xD800 && code <= 0xDFFF) { + if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) { + const nextCode = string.charCodeAt(i + 1); + if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) { + result += encodeURIComponent(string[i] + string[i + 1]); + i++; + continue; + } + } + result += '%EF%BF%BD'; + continue; + } + result += encodeURIComponent(string[i]); + } + return result; +} +encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; +encode.componentChars = "-_.!~*'()"; +function format(url) { + let result = ''; + result += url.protocol || ''; + result += url.slashes ? '//' : ''; + result += url.auth ? url.auth + '@' : ''; + if (url.hostname && url.hostname.indexOf(':') !== -1) { + // ipv6 address + result += '[' + url.hostname + ']'; + } else { + result += url.hostname || ''; + } + result += url.port ? ':' + url.port : ''; + result += url.pathname || ''; + result += url.search || ''; + result += url.hash || ''; + return result; +} + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// +// Changes from joyent/node: +// +// 1. No leading slash in paths, +// e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` +// +// 2. Backslashes are not replaced with slashes, +// so `http:\\example.org\` is treated like a relative path +// +// 3. Trailing colon is treated like a part of the path, +// i.e. in `http://example.org:foo` pathname is `:foo` +// +// 4. Nothing is URL-encoded in the resulting object, +// (in joyent/node some chars in auth and paths are encoded) +// +// 5. `url.parse()` does not have `parseQueryString` argument +// +// 6. Removed extraneous result properties: `host`, `path`, `query`, etc., +// which can be constructed using other parts of the url. +// + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +const protocolPattern = /^([a-z0-9.+-]+:)/i; +const portPattern = /:[0-9]*$/; + +// Special case for a simple path URL +/* eslint-disable-next-line no-useless-escape */ +const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; + +// RFC 2396: characters reserved for delimiting URLs. +// We actually just auto-escape these. +const delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t']; + +// RFC 2396: characters not allowed for various reasons. +const unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims); + +// Allowed by RFCs, but cause of XSS attacks. Always escape these. +const autoEscape = ['\''].concat(unwise); +// Characters that are never ever allowed in a hostname. +// Note that any invalid chars are also handled, but these +// are the ones that are *expected* to be seen, so we fast-path +// them. +const nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape); +const hostEndingChars = ['/', '?', '#']; +const hostnameMaxLen = 255; +const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; +const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; +// protocols that can allow "unsafe" and "unwise" chars. +// protocols that never have a hostname. +const hostlessProtocol = { + javascript: true, + 'javascript:': true +}; +// protocols that always contain a // bit. +const slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true +}; +function urlParse(url, slashesDenoteHost) { + if (url && url instanceof Url) return url; + const u = new Url(); + u.parse(url, slashesDenoteHost); + return u; +} +Url.prototype.parse = function (url, slashesDenoteHost) { + let lowerProto, hec, slashes; + let rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + const simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + } + return this; } - })); - Object.defineProperty(exports, "locToRange", ({ - enumerable: true, - get: function () { - return _Range.locToRange; + } + let proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + lowerProto = proto.toLowerCase(); + this.protocol = proto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + /* eslint-disable-next-line no-useless-escape */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; } - })); - Object.defineProperty(exports, "offsetToPosition", ({ - enumerable: true, - get: function () { - return _Range.offsetToPosition; + } + if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) { + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + let hostEnd = -1; + for (let i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; + } } - })); - Object.defineProperty(exports, "pointToOffset", ({ - enumerable: true, - get: function () { - return _getASTNodeAtPosition.pointToOffset; + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + let auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); } - })); - Object.defineProperty(exports, "validateWithCustomRules", ({ - enumerable: true, - get: function () { - return _validateWithCustomRules.validateWithCustomRules; + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = auth; } - })); - var _fragmentDependencies = __webpack_require__(/*! ./fragmentDependencies */ "../../graphql-language-service/esm/utils/fragmentDependencies.js"); - var _getVariablesJSONSchema = __webpack_require__(/*! ./getVariablesJSONSchema */ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js"); - var _getASTNodeAtPosition = __webpack_require__(/*! ./getASTNodeAtPosition */ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js"); - var _Range = __webpack_require__(/*! ./Range */ "../../graphql-language-service/esm/utils/Range.js"); - var _validateWithCustomRules = __webpack_require__(/*! ./validateWithCustomRules */ "../../graphql-language-service/esm/utils/validateWithCustomRules.js"); - var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); - var _getOperationFacts = _interopRequireWildcard(__webpack_require__(/*! ./getOperationFacts */ "../../graphql-language-service/esm/utils/getOperationFacts.js")); - function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } - function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } - - /***/ }), - - /***/ "../../graphql-language-service/esm/utils/validateWithCustomRules.js": - /*!***************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/validateWithCustomRules.js ***! - \***************************************************************************/ - /***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - - - Object.defineProperty(exports, "__esModule", ({ - value: true - })); - exports.validateWithCustomRules = validateWithCustomRules; - var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); - const specifiedSDLRules = [_graphql.LoneSchemaDefinitionRule, _graphql.UniqueOperationTypesRule, _graphql.UniqueTypeNamesRule, _graphql.UniqueEnumValueNamesRule, _graphql.UniqueFieldDefinitionNamesRule, _graphql.UniqueDirectiveNamesRule, _graphql.KnownTypeNamesRule, _graphql.KnownDirectivesRule, _graphql.UniqueDirectivesPerLocationRule, _graphql.PossibleTypeExtensionsRule, _graphql.UniqueArgumentNamesRule, _graphql.UniqueInputFieldNamesRule, _graphql.UniqueVariableNamesRule, _graphql.FragmentsOnCompositeTypesRule, _graphql.ProvidedRequiredArgumentsRule]; - function validateWithCustomRules(schema, ast, customRules, isRelayCompatMode, isSchemaDocument) { - const rules = _graphql.specifiedRules.filter(rule => { - if (rule === _graphql.NoUnusedFragmentsRule || rule === _graphql.ExecutableDefinitionsRule) { - return false; - } - if (isRelayCompatMode && rule === _graphql.KnownFragmentNamesRule) { - return false; - } - return true; - }); - if (customRules) { - Array.prototype.push.apply(rules, customRules); - } - if (isSchemaDocument) { - Array.prototype.push.apply(rules, specifiedSDLRules); - } - const errors = (0, _graphql.validate)(schema, ast, rules); - return errors.filter(error => { - if (error.message.includes('Unknown directive') && error.nodes) { - const node = error.nodes[0]; - if (node && node.kind === _graphql.Kind.DIRECTIVE) { - const name = node.name.value; - if (name === 'arguments' || name === 'argumentDefinitions') { - return false; - } - } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (let i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { + hostEnd = hec; } - return true; - }); - } - - /***/ }), - - /***/ "./style.css": - /*!*******************!*\ - !*** ./style.css ***! - \*******************/ - /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { - - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - - /***/ }), - - /***/ "../../graphiql-react/dist/style.css": - /*!*******************************************!*\ - !*** ../../graphiql-react/dist/style.css ***! - \*******************************************/ - /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { - - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - - /***/ }), - - /***/ "../../graphiql-react/font/fira-code.css": - /*!***********************************************!*\ - !*** ../../graphiql-react/font/fira-code.css ***! - \***********************************************/ - /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { - - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - - /***/ }), - - /***/ "../../graphiql-react/font/roboto.css": - /*!********************************************!*\ - !*** ../../graphiql-react/font/roboto.css ***! - \********************************************/ - /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { - - __webpack_require__.r(__webpack_exports__); - // extracted by mini-css-extract-plugin - - - /***/ }), - - /***/ "react": - /*!************************!*\ - !*** external "React" ***! - \************************/ - /***/ (function(module) { - - module.exports = window["React"]; - - /***/ }), - - /***/ "react-dom": - /*!***************************!*\ - !*** external "ReactDOM" ***! - \***************************/ - /***/ (function(module) { - - module.exports = window["ReactDOM"]; - - /***/ }), - - /***/ "../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs": - /*!***********************************************************************!*\ - !*** ../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs ***! - \***********************************************************************/ - /***/ (function(module, __unused_webpack_exports, __webpack_require__) { - - - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return to; - }; - var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod - )); - var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; - }; - - // src/index.ts - var src_exports = {}; - __export(src_exports, { - Combobox: () => Combobox, - Dialog: () => Dialog, - Disclosure: () => Disclosure, - FocusTrap: () => FocusTrap, - Listbox: () => Listbox, - Menu: () => Menu, - Popover: () => Popover, - Portal: () => Portal, - RadioGroup: () => RadioGroup, - Switch: () => Switch, - Tab: () => Tab, - Transition: () => Transition - }); - module.exports = __toCommonJS(src_exports); - - // src/components/combobox/combobox.tsx - var import_react19 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/hooks/use-computed.ts - var import_react3 = __webpack_require__(/*! react */ "react"); - - // src/hooks/use-iso-morphic-effect.ts - var import_react = __webpack_require__(/*! react */ "react"); - - // src/utils/env.ts - var Env = class { - constructor() { - __publicField(this, "current", this.detect()); - __publicField(this, "handoffState", "pending"); - __publicField(this, "currentId", 0); - } - set(env2) { - if (this.current === env2) - return; - this.handoffState = "pending"; - this.currentId = 0; - this.current = env2; + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { + hostEnd = rest.length; } - reset() { - this.set(this.detect()); + if (rest[hostEnd - 1] === ':') { + hostEnd--; } - nextId() { - return ++this.currentId; + const host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(host); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + const ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + const hostparts = this.hostname.split(/\./); + for (let i = 0, l = hostparts.length; i < l; i++) { + const part = hostparts[i]; + if (!part) { + continue; + } + if (!part.match(hostnamePartPattern)) { + let newpart = ''; + for (let j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + const validParts = hostparts.slice(0, i); + const notHost = hostparts.slice(i + 1); + const bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } } - get isServer() { - return this.current === "server"; + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; } - get isClient() { - return this.current === "client"; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); } - detect() { - if (typeof window === "undefined" || typeof document === "undefined") { - return "server"; + } + + // chop off from the tail first. + const hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + const qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + rest = rest.slice(0, qm); + } + if (rest) { + this.pathname = rest; + } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = ''; + } + return this; +}; +Url.prototype.parseHost = function (host) { + let port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { + this.hostname = host; + } +}; +exports.decode = decode; +exports.encode = encode; +exports.format = format; +exports.parse = urlParse; + +/***/ }), + +/***/ "../node_modules/uc.micro/build/index.cjs.js": +/*!***************************************************!*\ + !*** ../node_modules/uc.micro/build/index.cjs.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +var regex$5 = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var regex$4 = /[\0-\x1F\x7F-\x9F]/; +var regex$3 = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/; +var regex$2 = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/; +var regex$1 = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/; +var regex = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; +exports.Any = regex$5; +exports.Cc = regex$4; +exports.Cf = regex$3; +exports.P = regex$2; +exports.S = regex$1; +exports.Z = regex; + +/***/ }), + +/***/ "./components/GraphiQL.tsx": +/*!*********************************!*\ + !*** ./components/GraphiQL.tsx ***! + \*********************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.GraphiQL = GraphiQL; +exports.GraphiQLInterface = GraphiQLInterface; +var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "react")); +var _react2 = __webpack_require__(/*! @graphiql/react */ "../../graphiql-react/dist/index.js"); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } +function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** + * Copyright (c) 2020 GraphQL Contributors. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const majorVersion = parseInt(_react.default.version.slice(0, 2), 10); +if (majorVersion < 16) { + throw new Error(['GraphiQL 0.18.0 and after is not compatible with React 15 or below.', 'If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:', 'https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49'].join('\n')); +} + +/** + * API docs for this live here: + * + * https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops + */ + +/** + * The top-level React component for GraphiQL, intended to encompass the entire + * browser viewport. + * + * @see https://github.com/graphql/graphiql#usage + */ + +function GraphiQL({ + dangerouslyAssumeSchemaIsValid, + defaultQuery, + defaultTabs, + externalFragments, + fetcher, + getDefaultFieldNames, + headers, + inputValueDeprecation, + introspectionQueryName, + maxHistoryLength, + onEditOperationName, + onSchemaChange, + onTabChange, + onTogglePluginVisibility, + operationName, + plugins, + query, + response, + schema, + schemaDescription, + shouldPersistHeaders, + storage, + validationRules, + variables, + visiblePlugin, + defaultHeaders, + ...props +}) { + var _props$disableTabs; + // Ensure props are correct + if (typeof fetcher !== 'function') { + throw new TypeError('The `GraphiQL` component requires a `fetcher` function to be passed as prop.'); + } + return /*#__PURE__*/_react.default.createElement(_react2.GraphiQLProvider, { + getDefaultFieldNames: getDefaultFieldNames, + dangerouslyAssumeSchemaIsValid: dangerouslyAssumeSchemaIsValid, + defaultQuery: defaultQuery, + defaultHeaders: defaultHeaders, + defaultTabs: defaultTabs, + externalFragments: externalFragments, + fetcher: fetcher, + headers: headers, + inputValueDeprecation: inputValueDeprecation, + introspectionQueryName: introspectionQueryName, + maxHistoryLength: maxHistoryLength, + onEditOperationName: onEditOperationName, + onSchemaChange: onSchemaChange, + onTabChange: onTabChange, + onTogglePluginVisibility: onTogglePluginVisibility, + plugins: plugins, + visiblePlugin: visiblePlugin, + operationName: operationName, + query: query, + response: response, + schema: schema, + schemaDescription: schemaDescription, + shouldPersistHeaders: shouldPersistHeaders, + storage: storage, + validationRules: validationRules, + variables: variables + }, /*#__PURE__*/_react.default.createElement(GraphiQLInterface, _extends({ + showPersistHeadersSettings: shouldPersistHeaders !== false, + disableTabs: (_props$disableTabs = props.disableTabs) !== null && _props$disableTabs !== void 0 ? _props$disableTabs : false, + forcedTheme: props.forcedTheme + }, props))); +} + +// Export main windows/panes to be used separately if desired. +GraphiQL.Logo = GraphiQLLogo; +GraphiQL.Toolbar = GraphiQLToolbar; +GraphiQL.Footer = GraphiQLFooter; +const THEMES = ['light', 'dark', 'system']; +function GraphiQLInterface(props) { + var _props$isHeadersEdito, _pluginContext$visibl, _props$toolbar, _props$toolbar2; + const isHeadersEditorEnabled = (_props$isHeadersEdito = props.isHeadersEditorEnabled) !== null && _props$isHeadersEdito !== void 0 ? _props$isHeadersEdito : true; + const editorContext = (0, _react2.useEditorContext)({ + nonNull: true + }); + const executionContext = (0, _react2.useExecutionContext)({ + nonNull: true + }); + const schemaContext = (0, _react2.useSchemaContext)({ + nonNull: true + }); + const storageContext = (0, _react2.useStorageContext)(); + const pluginContext = (0, _react2.usePluginContext)(); + const forcedTheme = (0, _react.useMemo)(() => props.forcedTheme && THEMES.includes(props.forcedTheme) ? props.forcedTheme : undefined, [props.forcedTheme]); + const copy = (0, _react2.useCopyQuery)({ + onCopyQuery: props.onCopyQuery + }); + const merge = (0, _react2.useMergeQuery)(); + const prettify = (0, _react2.usePrettifyEditors)(); + const { + theme, + setTheme + } = (0, _react2.useTheme)(); + (0, _react.useEffect)(() => { + if (forcedTheme === 'system') { + setTheme(null); + } else if (forcedTheme === 'light' || forcedTheme === 'dark') { + setTheme(forcedTheme); + } + }, [forcedTheme, setTheme]); + const PluginContent = pluginContext === null || pluginContext === void 0 ? void 0 : (_pluginContext$visibl = pluginContext.visiblePlugin) === null || _pluginContext$visibl === void 0 ? void 0 : _pluginContext$visibl.content; + const pluginResize = (0, _react2.useDragResize)({ + defaultSizeRelation: 1 / 3, + direction: 'horizontal', + initiallyHidden: pluginContext !== null && pluginContext !== void 0 && pluginContext.visiblePlugin ? undefined : 'first', + onHiddenElementChange(resizableElement) { + if (resizableElement === 'first') { + pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.setVisiblePlugin(null); } - return "client"; - } - handoff() { - if (this.handoffState === "pending") { - this.handoffState = "complete"; + }, + sizeThresholdSecond: 200, + storageKey: 'docExplorerFlex' + }); + const editorResize = (0, _react2.useDragResize)({ + direction: 'horizontal', + storageKey: 'editorFlex' + }); + const editorToolsResize = (0, _react2.useDragResize)({ + defaultSizeRelation: 3, + direction: 'vertical', + initiallyHidden: (() => { + if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { + return; } + if (typeof props.defaultEditorToolsVisibility === 'boolean') { + return props.defaultEditorToolsVisibility ? undefined : 'second'; + } + return editorContext.initialVariables || editorContext.initialHeaders ? undefined : 'second'; + })(), + sizeThresholdSecond: 60, + storageKey: 'secondaryEditorFlex' + }); + const [activeSecondaryEditor, setActiveSecondaryEditor] = (0, _react.useState)(() => { + if (props.defaultEditorToolsVisibility === 'variables' || props.defaultEditorToolsVisibility === 'headers') { + return props.defaultEditorToolsVisibility; } - get isHandoffComplete() { - return this.handoffState === "complete"; - } - }; - var env = new Env(); - - // src/hooks/use-iso-morphic-effect.ts - var useIsoMorphicEffect = (effect, deps) => { - if (env.isServer) { - (0, import_react.useEffect)(effect, deps); + return !editorContext.initialVariables && editorContext.initialHeaders && isHeadersEditorEnabled ? 'headers' : 'variables'; + }); + const [showDialog, setShowDialog] = (0, _react.useState)(null); + const [clearStorageStatus, setClearStorageStatus] = (0, _react.useState)(null); + const children = _react.default.Children.toArray(props.children); + const logo = children.find(child => isChildComponentType(child, GraphiQL.Logo)) || /*#__PURE__*/_react.default.createElement(GraphiQL.Logo, null); + const toolbar = children.find(child => isChildComponentType(child, GraphiQL.Toolbar)) || /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { + onClick: prettify, + label: "Prettify query (Shift-Ctrl-P)" + }, /*#__PURE__*/_react.default.createElement(_react2.PrettifyIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true" + })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { + onClick: merge, + label: "Merge fragments into query (Shift-Ctrl-M)" + }, /*#__PURE__*/_react.default.createElement(_react2.MergeIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true" + })), /*#__PURE__*/_react.default.createElement(_react2.ToolbarButton, { + onClick: copy, + label: "Copy query (Shift-Ctrl-C)" + }, /*#__PURE__*/_react.default.createElement(_react2.CopyIcon, { + className: "graphiql-toolbar-icon", + "aria-hidden": "true" + })), (_props$toolbar = props.toolbar) === null || _props$toolbar === void 0 ? void 0 : _props$toolbar.additionalContent, ((_props$toolbar2 = props.toolbar) === null || _props$toolbar2 === void 0 ? void 0 : _props$toolbar2.additionalComponent) && /*#__PURE__*/_react.default.createElement(props.toolbar.additionalComponent, null)); + const footer = children.find(child => isChildComponentType(child, GraphiQL.Footer)); + const onClickReference = (0, _react.useCallback)(() => { + if (pluginResize.hiddenElement === 'first') { + pluginResize.setHiddenElement(null); + } + }, [pluginResize]); + const handleClearData = (0, _react.useCallback)(() => { + try { + storageContext === null || storageContext === void 0 ? void 0 : storageContext.clear(); + setClearStorageStatus('success'); + } catch { + setClearStorageStatus('error'); + } + }, [storageContext]); + const handlePersistHeaders = (0, _react.useCallback)(event => { + editorContext.setShouldPersistHeaders(event.currentTarget.dataset.value === 'true'); + }, [editorContext]); + const handleChangeTheme = (0, _react.useCallback)(event => { + const selectedTheme = event.currentTarget.dataset.theme; + setTheme(selectedTheme || null); + }, [setTheme]); + const handleAddTab = editorContext.addTab; + const handleRefetchSchema = schemaContext.introspect; + const handleReorder = editorContext.moveTab; + const handleShowDialog = (0, _react.useCallback)(event => { + setShowDialog(event.currentTarget.dataset.value); + }, []); + const handlePluginClick = (0, _react.useCallback)(e => { + const context = pluginContext; + const pluginIndex = Number(e.currentTarget.dataset.index); + const plugin = context.plugins.find((_, index) => pluginIndex === index); + const isVisible = plugin === context.visiblePlugin; + if (isVisible) { + context.setVisiblePlugin(null); + pluginResize.setHiddenElement('first'); } else { - (0, import_react.useLayoutEffect)(effect, deps); - } - }; - - // src/hooks/use-latest-value.ts - var import_react2 = __webpack_require__(/*! react */ "react"); - function useLatestValue(value) { - let cache = (0, import_react2.useRef)(value); - useIsoMorphicEffect(() => { - cache.current = value; - }, [value]); - return cache; - } - - // src/hooks/use-computed.ts - function useComputed(cb, dependencies) { - let [value, setValue] = (0, import_react3.useState)(cb); - let cbRef = useLatestValue(cb); - useIsoMorphicEffect(() => setValue(cbRef.current), [cbRef, setValue, ...dependencies]); - return value; + context.setVisiblePlugin(plugin); + pluginResize.setHiddenElement(null); + } + }, [pluginContext, pluginResize]); + const handleToolsTabClick = (0, _react.useCallback)(event => { + if (editorToolsResize.hiddenElement === 'second') { + editorToolsResize.setHiddenElement(null); + } + setActiveSecondaryEditor(event.currentTarget.dataset.name); + }, [editorToolsResize]); + const toggleEditorTools = (0, _react.useCallback)(() => { + editorToolsResize.setHiddenElement(editorToolsResize.hiddenElement === 'second' ? null : 'second'); + }, [editorToolsResize]); + const handleOpenShortKeysDialog = (0, _react.useCallback)(isOpen => { + if (!isOpen) { + setShowDialog(null); + } + }, []); + const handleOpenSettingsDialog = (0, _react.useCallback)(isOpen => { + if (!isOpen) { + setShowDialog(null); + setClearStorageStatus(null); + } + }, []); + const addTab = /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Add tab" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: "graphiql-tab-add", + onClick: handleAddTab, + "aria-label": "Add tab" + }, /*#__PURE__*/_react.default.createElement(_react2.PlusIcon, { + "aria-hidden": "true" + }))); + const className = props.className ? ` ${props.className}` : ''; + return /*#__PURE__*/_react.default.createElement(_react2.Tooltip.Provider, null, /*#__PURE__*/_react.default.createElement("div", { + "data-testid": "graphiql-container", + className: `graphiql-container${className}` + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-sidebar" + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-sidebar-section" + }, pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.plugins.map((plugin, index) => { + const isVisible = plugin === pluginContext.visiblePlugin; + const label = `${isVisible ? 'Hide' : 'Show'} ${plugin.title}`; + const Icon = plugin.icon; + return /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + key: plugin.title, + label: label + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: isVisible ? 'active' : '', + onClick: handlePluginClick, + "data-index": index, + "aria-label": label + }, /*#__PURE__*/_react.default.createElement(Icon, { + "aria-hidden": "true" + }))); + })), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-sidebar-section" + }, /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Re-fetch GraphQL schema" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + disabled: schemaContext.isFetching, + onClick: handleRefetchSchema, + "aria-label": "Re-fetch GraphQL schema" + }, /*#__PURE__*/_react.default.createElement(_react2.ReloadIcon, { + className: schemaContext.isFetching ? 'graphiql-spin' : '', + "aria-hidden": "true" + }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Open short keys dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + "data-value": "short-keys", + onClick: handleShowDialog, + "aria-label": "Open short keys dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.KeyboardShortcutIcon, { + "aria-hidden": "true" + }))), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: "Open settings dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + "data-value": "settings", + onClick: handleShowDialog, + "aria-label": "Open settings dialog" + }, /*#__PURE__*/_react.default.createElement(_react2.SettingsIcon, { + "aria-hidden": "true" + }))))), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-main" + }, /*#__PURE__*/_react.default.createElement("div", { + ref: pluginResize.firstRef, + style: { + // Make sure the container shrinks when containing long + // non-breaking texts + minWidth: '200px' + } + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-plugin" + }, PluginContent ? /*#__PURE__*/_react.default.createElement(PluginContent, null) : null)), (pluginContext === null || pluginContext === void 0 ? void 0 : pluginContext.visiblePlugin) && /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-horizontal-drag-bar", + ref: pluginResize.dragBarRef + }), /*#__PURE__*/_react.default.createElement("div", { + ref: pluginResize.secondRef, + className: "graphiql-sessions" + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-session-header" + }, !props.disableTabs && /*#__PURE__*/_react.default.createElement(_react2.Tabs, { + values: editorContext.tabs, + onReorder: handleReorder, + "aria-label": "Select active operation" + }, editorContext.tabs.length > 1 && /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, editorContext.tabs.map((tab, index) => /*#__PURE__*/_react.default.createElement(_react2.Tab, { + key: tab.id, + value: tab, + isActive: index === editorContext.activeTabIndex + }, /*#__PURE__*/_react.default.createElement(_react2.Tab.Button, { + "aria-controls": "graphiql-session", + id: `graphiql-session-tab-${index}`, + onClick: () => { + executionContext.stop(); + editorContext.changeTab(index); + } + }, tab.title), /*#__PURE__*/_react.default.createElement(_react2.Tab.Close, { + onClick: () => { + if (editorContext.activeTabIndex === index) { + executionContext.stop(); + } + editorContext.closeTab(index); + } + }))), addTab)), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-session-header-right" + }, editorContext.tabs.length === 1 && addTab, logo)), /*#__PURE__*/_react.default.createElement("div", { + role: "tabpanel", + id: "graphiql-session", + className: "graphiql-session", + "aria-labelledby": `graphiql-session-tab-${editorContext.activeTabIndex}` + }, /*#__PURE__*/_react.default.createElement("div", { + ref: editorResize.firstRef + }, /*#__PURE__*/_react.default.createElement("div", { + className: `graphiql-editors${editorContext.tabs.length === 1 ? ' full-height' : ''}` + }, /*#__PURE__*/_react.default.createElement("div", { + ref: editorToolsResize.firstRef + }, /*#__PURE__*/_react.default.createElement("section", { + className: "graphiql-query-editor", + "aria-label": "Query Editor" + }, /*#__PURE__*/_react.default.createElement(_react2.QueryEditor, { + editorTheme: props.editorTheme, + keyMap: props.keyMap, + onClickReference: onClickReference, + onCopyQuery: props.onCopyQuery, + onEdit: props.onEditQuery, + readOnly: props.readOnly + }), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-toolbar", + role: "toolbar", + "aria-label": "Editor Commands" + }, /*#__PURE__*/_react.default.createElement(_react2.ExecuteButton, null), toolbar))), /*#__PURE__*/_react.default.createElement("div", { + ref: editorToolsResize.dragBarRef + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-editor-tools" + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: activeSecondaryEditor === 'variables' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', + onClick: handleToolsTabClick, + "data-name": "variables" + }, "Variables"), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + className: activeSecondaryEditor === 'headers' && editorToolsResize.hiddenElement !== 'second' ? 'active' : '', + onClick: handleToolsTabClick, + "data-name": "headers" + }, "Headers"), /*#__PURE__*/_react.default.createElement(_react2.Tooltip, { + label: editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools' + }, /*#__PURE__*/_react.default.createElement(_react2.UnStyledButton, { + type: "button", + onClick: toggleEditorTools, + "aria-label": editorToolsResize.hiddenElement === 'second' ? 'Show editor tools' : 'Hide editor tools', + className: "graphiql-toggle-editor-tools" + }, editorToolsResize.hiddenElement === 'second' ? /*#__PURE__*/_react.default.createElement(_react2.ChevronUpIcon, { + className: "graphiql-chevron-icon", + "aria-hidden": "true" + }) : /*#__PURE__*/_react.default.createElement(_react2.ChevronDownIcon, { + className: "graphiql-chevron-icon", + "aria-hidden": "true" + }))))), /*#__PURE__*/_react.default.createElement("div", { + ref: editorToolsResize.secondRef + }, /*#__PURE__*/_react.default.createElement("section", { + className: "graphiql-editor-tool", + "aria-label": activeSecondaryEditor === 'variables' ? 'Variables' : 'Headers' + }, /*#__PURE__*/_react.default.createElement(_react2.VariableEditor, { + editorTheme: props.editorTheme, + isHidden: activeSecondaryEditor !== 'variables', + keyMap: props.keyMap, + onEdit: props.onEditVariables, + onClickReference: onClickReference, + readOnly: props.readOnly + }), isHeadersEditorEnabled && /*#__PURE__*/_react.default.createElement(_react2.HeaderEditor, { + editorTheme: props.editorTheme, + isHidden: activeSecondaryEditor !== 'headers', + keyMap: props.keyMap, + onEdit: props.onEditHeaders, + readOnly: props.readOnly + }))))), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-horizontal-drag-bar", + ref: editorResize.dragBarRef + }), /*#__PURE__*/_react.default.createElement("div", { + ref: editorResize.secondRef + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-response" + }, executionContext.isFetching ? /*#__PURE__*/_react.default.createElement(_react2.Spinner, null) : null, /*#__PURE__*/_react.default.createElement(_react2.ResponseEditor, { + editorTheme: props.editorTheme, + responseTooltip: props.responseTooltip, + keyMap: props.keyMap + }), footer))))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { + open: showDialog === 'short-keys', + onOpenChange: handleOpenShortKeysDialog + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-header" + }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { + className: "graphiql-dialog-title" + }, "Short Keys"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement(ShortKeys, { + keyMap: props.keyMap || 'sublime' + }))), /*#__PURE__*/_react.default.createElement(_react2.Dialog, { + open: showDialog === 'settings', + onOpenChange: handleOpenSettingsDialog + }, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-header" + }, /*#__PURE__*/_react.default.createElement(_react2.Dialog.Title, { + className: "graphiql-dialog-title" + }, "Settings"), /*#__PURE__*/_react.default.createElement(_react2.Dialog.Close, null)), props.showPersistHeadersSettings ? /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-title" + }, "Persist headers"), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-caption" + }, "Save headers upon reloading.", ' ', /*#__PURE__*/_react.default.createElement("span", { + className: "graphiql-warning-text" + }, "Only enable if you trust this device."))), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + id: "enable-persist-headers", + className: editorContext.shouldPersistHeaders ? 'active' : '', + "data-value": "true", + onClick: handlePersistHeaders + }, "On"), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + id: "disable-persist-headers", + className: editorContext.shouldPersistHeaders ? '' : 'active', + onClick: handlePersistHeaders + }, "Off"))) : null, !forcedTheme && /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-title" + }, "Theme"), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-caption" + }, "Adjust how the interface appears.")), /*#__PURE__*/_react.default.createElement(_react2.ButtonGroup, null, /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + className: theme === null ? 'active' : '', + onClick: handleChangeTheme + }, "System"), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + className: theme === 'light' ? 'active' : '', + "data-theme": "light", + onClick: handleChangeTheme + }, "Light"), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + className: theme === 'dark' ? 'active' : '', + "data-theme": "dark", + onClick: handleChangeTheme + }, "Dark"))), storageContext ? /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section" + }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-title" + }, "Clear storage"), /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-dialog-section-caption" + }, "Remove all locally stored data and start fresh.")), /*#__PURE__*/_react.default.createElement(_react2.Button, { + type: "button", + state: clearStorageStatus || undefined, + disabled: clearStorageStatus === 'success', + onClick: handleClearData + }, { + success: 'Cleared data', + error: 'Failed' + }[clearStorageStatus] || 'Clear data')) : null))); +} +const modifier = typeof window !== 'undefined' && window.navigator.platform.toLowerCase().indexOf('mac') === 0 ? 'Cmd' : 'Ctrl'; +const SHORT_KEYS = Object.entries({ + 'Search in editor': [modifier, 'F'], + 'Search in documentation': [modifier, 'K'], + 'Execute query': [modifier, 'Enter'], + 'Prettify editors': ['Ctrl', 'Shift', 'P'], + 'Merge fragments definitions into operation definition': ['Ctrl', 'Shift', 'M'], + 'Copy query': ['Ctrl', 'Shift', 'C'], + 'Re-fetch schema using introspection': ['Ctrl', 'Shift', 'R'] +}); +function ShortKeys({ + keyMap +}) { + return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("table", { + className: "graphiql-table" + }, /*#__PURE__*/_react.default.createElement("thead", null, /*#__PURE__*/_react.default.createElement("tr", null, /*#__PURE__*/_react.default.createElement("th", null, "Short Key"), /*#__PURE__*/_react.default.createElement("th", null, "Function"))), /*#__PURE__*/_react.default.createElement("tbody", null, SHORT_KEYS.map(([title, keys]) => /*#__PURE__*/_react.default.createElement("tr", { + key: title + }, /*#__PURE__*/_react.default.createElement("td", null, keys.map((key, index, array) => /*#__PURE__*/_react.default.createElement(_react.Fragment, { + key: key + }, /*#__PURE__*/_react.default.createElement("code", { + className: "graphiql-key" + }, key), index !== array.length - 1 && ' + '))), /*#__PURE__*/_react.default.createElement("td", null, title))))), /*#__PURE__*/_react.default.createElement("p", null, "The editors use", ' ', /*#__PURE__*/_react.default.createElement("a", { + href: "https://codemirror.net/5/doc/manual.html#keymaps", + target: "_blank", + rel: "noopener noreferrer" + }, "CodeMirror Key Maps"), ' ', "that add more short keys. This instance of Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL uses", ' ', /*#__PURE__*/_react.default.createElement("code", null, keyMap), ".")); +} + +// Configure the UI by providing this Component as a child of GraphiQL. +function GraphiQLLogo(props) { + return /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-logo" + }, props.children || /*#__PURE__*/_react.default.createElement("a", { + className: "graphiql-logo-link", + href: "https://github.com/graphql/graphiql", + target: "_blank", + rel: "noreferrer" + }, "Graph", /*#__PURE__*/_react.default.createElement("em", null, "i"), "QL")); +} +GraphiQLLogo.displayName = 'GraphiQLLogo'; + +// Configure the UI by providing this Component as a child of GraphiQL. +function GraphiQLToolbar(props) { + // eslint-disable-next-line react/jsx-no-useless-fragment + return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, props.children); +} +GraphiQLToolbar.displayName = 'GraphiQLToolbar'; + +// Configure the UI by providing this Component as a child of GraphiQL. +function GraphiQLFooter(props) { + return /*#__PURE__*/_react.default.createElement("div", { + className: "graphiql-footer" + }, props.children); +} +GraphiQLFooter.displayName = 'GraphiQLFooter'; + +// Determines if the React child is of the same type of the provided React component +function isChildComponentType(child, component) { + var _child$type; + if (child !== null && child !== void 0 && (_child$type = child.type) !== null && _child$type !== void 0 && _child$type.displayName && child.type.displayName === component.displayName) { + return true; } - - // src/hooks/use-disposables.ts - var import_react4 = __webpack_require__(/*! react */ "react"); - - // src/utils/micro-task.ts - function microTask(cb) { - if (typeof queueMicrotask === "function") { - queueMicrotask(cb); - } else { - Promise.resolve().then(cb).catch( - (e) => setTimeout(() => { - throw e; - }) - ); + return child.type === component; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/index.js": +/*!***************************************************!*\ + !*** ../../graphql-language-service/esm/index.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "CharacterStream", ({ + enumerable: true, + get: function () { + return _parser.CharacterStream; + } +})); +Object.defineProperty(exports, "CompletionItemKind", ({ + enumerable: true, + get: function () { + return _types.CompletionItemKind; + } +})); +Object.defineProperty(exports, "DIAGNOSTIC_SEVERITY", ({ + enumerable: true, + get: function () { + return _interface.DIAGNOSTIC_SEVERITY; + } +})); +Object.defineProperty(exports, "FileChangeTypeKind", ({ + enumerable: true, + get: function () { + return _types.FileChangeTypeKind; + } +})); +Object.defineProperty(exports, "GraphQLDocumentMode", ({ + enumerable: true, + get: function () { + return _parser.GraphQLDocumentMode; + } +})); +Object.defineProperty(exports, "LexRules", ({ + enumerable: true, + get: function () { + return _parser.LexRules; + } +})); +Object.defineProperty(exports, "ParseRules", ({ + enumerable: true, + get: function () { + return _parser.ParseRules; + } +})); +Object.defineProperty(exports, "Position", ({ + enumerable: true, + get: function () { + return _utils.Position; + } +})); +Object.defineProperty(exports, "Range", ({ + enumerable: true, + get: function () { + return _utils.Range; + } +})); +Object.defineProperty(exports, "RuleKinds", ({ + enumerable: true, + get: function () { + return _parser.RuleKinds; + } +})); +Object.defineProperty(exports, "SEVERITY", ({ + enumerable: true, + get: function () { + return _interface.SEVERITY; + } +})); +Object.defineProperty(exports, "SuggestionCommand", ({ + enumerable: true, + get: function () { + return _interface.SuggestionCommand; + } +})); +Object.defineProperty(exports, "canUseDirective", ({ + enumerable: true, + get: function () { + return _interface.canUseDirective; + } +})); +Object.defineProperty(exports, "collectVariables", ({ + enumerable: true, + get: function () { + return _utils.collectVariables; + } +})); +Object.defineProperty(exports, "getASTNodeAtPosition", ({ + enumerable: true, + get: function () { + return _utils.getASTNodeAtPosition; + } +})); +Object.defineProperty(exports, "getAutocompleteSuggestions", ({ + enumerable: true, + get: function () { + return _interface.getAutocompleteSuggestions; + } +})); +Object.defineProperty(exports, "getDefinitionQueryResultForArgument", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForArgument; + } +})); +Object.defineProperty(exports, "getDefinitionQueryResultForDefinitionNode", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForDefinitionNode; + } +})); +Object.defineProperty(exports, "getDefinitionQueryResultForField", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForField; + } +})); +Object.defineProperty(exports, "getDefinitionQueryResultForFragmentSpread", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForFragmentSpread; + } +})); +Object.defineProperty(exports, "getDefinitionQueryResultForNamedType", ({ + enumerable: true, + get: function () { + return _interface.getDefinitionQueryResultForNamedType; + } +})); +Object.defineProperty(exports, "getDefinitionState", ({ + enumerable: true, + get: function () { + return _parser.getDefinitionState; + } +})); +Object.defineProperty(exports, "getDiagnostics", ({ + enumerable: true, + get: function () { + return _interface.getDiagnostics; + } +})); +Object.defineProperty(exports, "getFieldDef", ({ + enumerable: true, + get: function () { + return _parser.getFieldDef; + } +})); +Object.defineProperty(exports, "getFragmentDefinitions", ({ + enumerable: true, + get: function () { + return _interface.getFragmentDefinitions; + } +})); +Object.defineProperty(exports, "getFragmentDependencies", ({ + enumerable: true, + get: function () { + return _utils.getFragmentDependencies; + } +})); +Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ + enumerable: true, + get: function () { + return _utils.getFragmentDependenciesForAST; + } +})); +Object.defineProperty(exports, "getHoverInformation", ({ + enumerable: true, + get: function () { + return _interface.getHoverInformation; + } +})); +Object.defineProperty(exports, "getOperationASTFacts", ({ + enumerable: true, + get: function () { + return _utils.getOperationASTFacts; + } +})); +Object.defineProperty(exports, "getOperationFacts", ({ + enumerable: true, + get: function () { + return _utils.getOperationFacts; + } +})); +Object.defineProperty(exports, "getOutline", ({ + enumerable: true, + get: function () { + return _interface.getOutline; + } +})); +Object.defineProperty(exports, "getQueryFacts", ({ + enumerable: true, + get: function () { + return _utils.getQueryFacts; + } +})); +Object.defineProperty(exports, "getRange", ({ + enumerable: true, + get: function () { + return _interface.getRange; + } +})); +Object.defineProperty(exports, "getTokenAtPosition", ({ + enumerable: true, + get: function () { + return _parser.getTokenAtPosition; + } +})); +Object.defineProperty(exports, "getTypeInfo", ({ + enumerable: true, + get: function () { + return _interface.getTypeInfo; + } +})); +Object.defineProperty(exports, "getVariableCompletions", ({ + enumerable: true, + get: function () { + return _interface.getVariableCompletions; + } +})); +Object.defineProperty(exports, "getVariablesJSONSchema", ({ + enumerable: true, + get: function () { + return _utils.getVariablesJSONSchema; + } +})); +Object.defineProperty(exports, "isIgnored", ({ + enumerable: true, + get: function () { + return _parser.isIgnored; + } +})); +Object.defineProperty(exports, "list", ({ + enumerable: true, + get: function () { + return _parser.list; + } +})); +Object.defineProperty(exports, "offsetToPosition", ({ + enumerable: true, + get: function () { + return _utils.offsetToPosition; + } +})); +Object.defineProperty(exports, "onlineParser", ({ + enumerable: true, + get: function () { + return _parser.onlineParser; + } +})); +Object.defineProperty(exports, "opt", ({ + enumerable: true, + get: function () { + return _parser.opt; + } +})); +Object.defineProperty(exports, "p", ({ + enumerable: true, + get: function () { + return _parser.p; + } +})); +Object.defineProperty(exports, "pointToOffset", ({ + enumerable: true, + get: function () { + return _utils.pointToOffset; + } +})); +Object.defineProperty(exports, "t", ({ + enumerable: true, + get: function () { + return _parser.t; + } +})); +Object.defineProperty(exports, "validateQuery", ({ + enumerable: true, + get: function () { + return _interface.validateQuery; + } +})); +Object.defineProperty(exports, "validateWithCustomRules", ({ + enumerable: true, + get: function () { + return _utils.validateWithCustomRules; + } +})); +var _interface = __webpack_require__(/*! ./interface */ "../../graphql-language-service/esm/interface/index.js"); +var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); +var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/types.js"); +var _utils = __webpack_require__(/*! ./utils */ "../../graphql-language-service/esm/utils/index.js"); + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/autocompleteUtils.js": +/*!*************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/autocompleteUtils.js ***! + \*************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getInsertText = exports.getInputInsertText = exports.getFieldInsertText = void 0; +exports.hintList = hintList; +exports.objectValues = objectValues; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function objectValues(object) { + const keys = Object.keys(object); + const len = keys.length; + const values = new Array(len); + for (let i = 0; i < len; ++i) { + values[i] = object[keys[i]]; + } + return values; +} +function hintList(token, list) { + return filterAndSortList(list, normalizeText(token.string)); +} +function filterAndSortList(list, text) { + if (!text || text.trim() === '' || text.trim() === ':' || text.trim() === '{') { + return filterNonEmpty(list, entry => !entry.isDeprecated); + } + const byProximity = list.map(entry => ({ + proximity: getProximity(normalizeText(entry.label), text), + entry + })); + return filterNonEmpty(filterNonEmpty(byProximity, pair => pair.proximity <= 2), pair => !pair.entry.isDeprecated).sort((a, b) => (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.label.length - b.entry.label.length).map(pair => pair.entry); +} +function filterNonEmpty(array, predicate) { + const filtered = array.filter(predicate); + return filtered.length === 0 ? array : filtered; +} +function normalizeText(text) { + return text.toLowerCase().replaceAll(/\W/g, ''); +} +function getProximity(suggestion, text) { + let proximity = lexicalDistance(text, suggestion); + if (suggestion.length > text.length) { + proximity -= suggestion.length - text.length - 1; + proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; + } + return proximity; +} +function lexicalDistance(a, b) { + let i; + let j; + const d = []; + const aLength = a.length; + const bLength = b.length; + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } } } - - // src/utils/disposables.ts - function disposables() { - let _disposables = []; - let api = { - addEventListener(element, name, listener, options) { - element.addEventListener(name, listener, options); - return api.add(() => element.removeEventListener(name, listener, options)); - }, - requestAnimationFrame(...args) { - let raf = requestAnimationFrame(...args); - return api.add(() => cancelAnimationFrame(raf)); - }, - nextFrame(...args) { - return api.requestAnimationFrame(() => { - return api.requestAnimationFrame(...args); - }); - }, - setTimeout(...args) { - let timer = setTimeout(...args); - return api.add(() => clearTimeout(timer)); - }, - microTask(...args) { - let task = { current: true }; - microTask(() => { - if (task.current) { - args[0](); - } - }); - return api.add(() => { - task.current = false; - }); - }, - style(node, property, value) { - let previous = node.style.getPropertyValue(property); - Object.assign(node.style, { [property]: value }); - return this.add(() => { - Object.assign(node.style, { [property]: previous }); - }); - }, - group(cb) { - let d = disposables(); - cb(d); - return this.add(() => d.dispose()); - }, - add(cb) { - _disposables.push(cb); - return () => { - let idx = _disposables.indexOf(cb); - if (idx >= 0) { - for (let dispose of _disposables.splice(idx, 1)) { - dispose(); - } - } - }; - }, - dispose() { - for (let dispose of _disposables.splice(0)) { - dispose(); - } - } - }; - return api; + return d[aLength][bLength]; +} +const insertSuffix = n => ` {\n $${n !== null && n !== void 0 ? n : 1}\n}`; +const getInsertText = (prefix, type, fallback) => { + if (!type) { + return fallback !== null && fallback !== void 0 ? fallback : prefix; } - - // src/hooks/use-disposables.ts - function useDisposables() { - let [d] = (0, import_react4.useState)(disposables); - (0, import_react4.useEffect)(() => () => d.dispose(), [d]); - return d; + const namedType = (0, _graphql.getNamedType)(type); + if ((0, _graphql.isObjectType)(namedType) || (0, _graphql.isInputObjectType)(namedType) || (0, _graphql.isListType)(namedType) || (0, _graphql.isAbstractType)(namedType)) { + return prefix + insertSuffix(); + } + return fallback !== null && fallback !== void 0 ? fallback : prefix; +}; +exports.getInsertText = getInsertText; +const getInputInsertText = (prefix, type, fallback) => { + if ((0, _graphql.isListType)(type)) { + const baseType = (0, _graphql.getNamedType)(type.ofType); + return prefix + `[${getInsertText('', baseType, '$1')}]`; + } + return getInsertText(prefix, type, fallback); +}; +exports.getInputInsertText = getInputInsertText; +const getFieldInsertText = field => { + const requiredArgs = field.args.filter(arg => arg.type.toString().endsWith('!')); + if (!requiredArgs.length) { + return; } - - // src/hooks/use-event.ts - var import_react5 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var useEvent = ( - // TODO: Add React.useEvent ?? once the useEvent hook is available - function useEvent2(cb) { - let cache = useLatestValue(cb); - return import_react5.default.useCallback((...args) => cache.current(...args), [cache]); + return field.name + `(${requiredArgs.map((arg, i) => `${arg.name}: $${i + 1}`)}) ${getInsertText('', field.type, '\n')}`; +}; +exports.getFieldInsertText = getFieldInsertText; + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js": +/*!**********************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js ***! + \**********************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SuggestionCommand = void 0; +exports.canUseDirective = canUseDirective; +exports.getAutocompleteSuggestions = getAutocompleteSuggestions; +exports.getFragmentDefinitions = getFragmentDefinitions; +Object.defineProperty(exports, "getTypeInfo", ({ + enumerable: true, + get: function () { + return _parser.getTypeInfo; + } +})); +exports.getVariableCompletions = getVariableCompletions; +Object.defineProperty(exports, "runOnlineParser", ({ + enumerable: true, + get: function () { + return _parser.runOnlineParser; + } +})); +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _types = __webpack_require__(/*! ../types */ "../../graphql-language-service/esm/types.js"); +var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); +var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); +var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); +const SuggestionCommand = exports.SuggestionCommand = { + command: 'editor.action.triggerSuggest', + title: 'Suggestions' +}; +const collectFragmentDefs = op => { + const externalFragments = []; + if (op) { + try { + (0, _graphql.visit)((0, _graphql.parse)(op), { + FragmentDefinition(def) { + externalFragments.push(def); + } + }); + } catch (_a) { + return []; } - ); - - // src/hooks/use-id.ts - var import_react7 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/hooks/use-server-handoff-complete.ts - var import_react6 = __webpack_require__(/*! react */ "react"); - function useServerHandoffComplete() { - let [complete, setComplete] = (0, import_react6.useState)(env.isHandoffComplete); - if (complete && env.isHandoffComplete === false) { - setComplete(false); - } - (0, import_react6.useEffect)(() => { - if (complete === true) - return; - setComplete(true); - }, [complete]); - (0, import_react6.useEffect)(() => env.handoff(), []); - return complete; } - - // src/hooks/use-id.ts + return externalFragments; +}; +function getAutocompleteSuggestions(schema, queryText, cursor, contextToken, fragmentDefs, options) { var _a; - var useId = ( - // Prefer React's `useId` if it's available. - // @ts-expect-error - `useId` doesn't exist in React < 18. - (_a = import_react7.default.useId) != null ? _a : function useId2() { - let ready = useServerHandoffComplete(); - let [id, setId] = import_react7.default.useState(ready ? () => env.nextId() : null); - useIsoMorphicEffect(() => { - if (id === null) - setId(env.nextId()); - }, [id]); - return id != null ? "" + id : void 0; - } - ); - - // src/hooks/use-outside-click.ts - var import_react10 = __webpack_require__(/*! react */ "react"); - - // src/utils/match.ts - function match(value, lookup, ...args) { - if (value in lookup) { - let returnValue = lookup[value]; - return typeof returnValue === "function" ? returnValue(...args) : returnValue; - } - let error = new Error( - `Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys( - lookup - ).map((key) => `"${key}"`).join(", ")}.` - ); - if (Error.captureStackTrace) - Error.captureStackTrace(error, match); - throw error; + const opts = Object.assign(Object.assign({}, options), { + schema + }); + const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken, options); + if (!context) { + return []; } - - // src/utils/owner.ts - function getOwnerDocument(element) { - if (env.isServer) - return null; - if (element instanceof Node) - return element.ownerDocument; - if (element == null ? void 0 : element.hasOwnProperty("current")) { - if (element.current instanceof Node) - return element.current.ownerDocument; + const { + state, + typeInfo, + mode, + token + } = context; + const { + kind, + step, + prevState + } = state; + if (kind === _parser.RuleKinds.DOCUMENT) { + if (mode === _parser.GraphQLDocumentMode.TYPE_SYSTEM) { + return getSuggestionsForTypeSystemDefinitions(token); } - return document; - } - - // src/utils/focus-management.ts - var focusableSelector = [ - "[contentEditable=true]", - "[tabindex]", - "a[href]", - "area[href]", - "button:not([disabled])", - "iframe", - "input:not([disabled])", - "select:not([disabled])", - "textarea:not([disabled])" - ].map( - false ? ( - // TODO: Remove this once JSDOM fixes the issue where an element that is - // "hidden" can be the document.activeElement, because this is not possible - // in real browsers. - 0 - ) : (selector) => `${selector}:not([tabindex='-1'])` - ).join(","); - function getFocusableElements(container = document.body) { - if (container == null) - return []; - return Array.from(container.querySelectorAll(focusableSelector)).sort( - // We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well. - (a, z) => Math.sign((a.tabIndex || Number.MAX_SAFE_INTEGER) - (z.tabIndex || Number.MAX_SAFE_INTEGER)) - ); + if (mode === _parser.GraphQLDocumentMode.EXECUTABLE) { + return getSuggestionsForExecutableDefinitions(token); + } + return getSuggestionsForUnknownDocumentMode(token); } - function isFocusableElement(element, mode = 0 /* Strict */) { - var _a3; - if (element === ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body)) - return false; - return match(mode, { - [0 /* Strict */]() { - return element.matches(focusableSelector); - }, - [1 /* Loose */]() { - let next = element; - while (next !== null) { - if (next.matches(focusableSelector)) - return true; - next = next.parentElement; - } - return false; - } - }); + if (kind === _parser.RuleKinds.EXTEND_DEF) { + return getSuggestionsForExtensionDefinitions(token); } - function restoreFocusIfNecessary(element) { - let ownerDocument = getOwnerDocument(element); - disposables().nextFrame(() => { - if (ownerDocument && !isFocusableElement(ownerDocument.activeElement, 0 /* Strict */)) { - focusElement(element); - } - }); + if (((_a = prevState === null || prevState === void 0 ? void 0 : prevState.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.EXTENSION_DEFINITION && state.name) { + return (0, _autocompleteUtils.hintList)(token, []); } - if (typeof window !== "undefined" && typeof document !== "undefined") { - document.addEventListener( - "keydown", - (event) => { - if (event.metaKey || event.altKey || event.ctrlKey) { - return; - } - document.documentElement.dataset.headlessuiFocusVisible = ""; - }, - true - ); - document.addEventListener( - "click", - (event) => { - if (event.detail === 1 /* Mouse */) { - delete document.documentElement.dataset.headlessuiFocusVisible; - } else if (event.detail === 0 /* Keyboard */) { - document.documentElement.dataset.headlessuiFocusVisible = ""; - } - }, - true - ); + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.SCALAR_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isScalarType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); } - function focusElement(element) { - element == null ? void 0 : element.focus({ preventScroll: true }); + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.OBJECT_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isObjectType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); } - var selectableSelector = ["textarea", "input"].join(","); - function isSelectableElement(element) { - var _a3, _b; - return (_b = (_a3 = element == null ? void 0 : element.matches) == null ? void 0 : _a3.call(element, selectableSelector)) != null ? _b : false; + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INTERFACE_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInterfaceType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); } - function sortByDomNode(nodes, resolveKey = (i) => i) { - return nodes.slice().sort((aItem, zItem) => { - let a = resolveKey(aItem); - let z = resolveKey(zItem); - if (a === null || z === null) - return 0; - let position = a.compareDocumentPosition(z); - if (position & Node.DOCUMENT_POSITION_FOLLOWING) - return -1; - if (position & Node.DOCUMENT_POSITION_PRECEDING) - return 1; - return 0; - }); + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.UNION_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isUnionType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); } - function focusFrom(current, focus) { - return focusIn(getFocusableElements(), focus, { relativeTo: current }); + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.ENUM_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isEnumType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); } - function focusIn(container, focus, { - sorted = true, - relativeTo = null, - skipElements = [] - } = {}) { - let ownerDocument = Array.isArray(container) ? container.length > 0 ? container[0].ownerDocument : document : container.ownerDocument; - let elements = Array.isArray(container) ? sorted ? sortByDomNode(container) : container : getFocusableElements(container); - if (skipElements.length > 0 && elements.length > 1) { - elements = elements.filter((x) => !skipElements.includes(x)); - } - relativeTo = relativeTo != null ? relativeTo : ownerDocument.activeElement; - let direction = (() => { - if (focus & (1 /* First */ | 4 /* Next */)) - return 1 /* Next */; - if (focus & (2 /* Previous */ | 8 /* Last */)) - return -1 /* Previous */; - throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); - })(); - let startIndex = (() => { - if (focus & 1 /* First */) - return 0; - if (focus & 2 /* Previous */) - return Math.max(0, elements.indexOf(relativeTo)) - 1; - if (focus & 4 /* Next */) - return Math.max(0, elements.indexOf(relativeTo)) + 1; - if (focus & 8 /* Last */) - return elements.length - 1; - throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); - })(); - let focusOptions = focus & 32 /* NoScroll */ ? { preventScroll: true } : {}; - let offset = 0; - let total = elements.length; - let next = void 0; - do { - if (offset >= total || offset + total <= 0) - return 0 /* Error */; - let nextIdx = startIndex + offset; - if (focus & 16 /* WrapAround */) { - nextIdx = (nextIdx + total) % total; - } else { - if (nextIdx < 0) - return 3 /* Underflow */; - if (nextIdx >= total) - return 1 /* Overflow */; - } - next = elements[nextIdx]; - next == null ? void 0 : next.focus(focusOptions); - offset += direction; - } while (next !== ownerDocument.activeElement); - if (focus & (4 /* Next */ | 2 /* Previous */) && isSelectableElement(next)) { - next.select(); - } - return 2 /* Success */; + if ((prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(_graphql.isInputObjectType).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function + }))); } - - // src/hooks/use-document-event.ts - var import_react8 = __webpack_require__(/*! react */ "react"); - function useDocumentEvent(type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react8.useEffect)(() => { - function handler(event) { - listenerRef.current(event); - } - document.addEventListener(type, handler, options); - return () => document.removeEventListener(type, handler, options); - }, [type, options]); + if (kind === _parser.RuleKinds.IMPLEMENTS || kind === _parser.RuleKinds.NAMED_TYPE && (prevState === null || prevState === void 0 ? void 0 : prevState.kind) === _parser.RuleKinds.IMPLEMENTS) { + return getSuggestionsForImplements(token, state, schema, queryText, typeInfo); } - - // src/hooks/use-window-event.ts - var import_react9 = __webpack_require__(/*! react */ "react"); - function useWindowEvent(type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react9.useEffect)(() => { - function handler(event) { - listenerRef.current(event); - } - window.addEventListener(type, handler, options); - return () => window.removeEventListener(type, handler, options); - }, [type, options]); + if (kind === _parser.RuleKinds.SELECTION_SET || kind === _parser.RuleKinds.FIELD || kind === _parser.RuleKinds.ALIASED_FIELD) { + return getSuggestionsForFieldNames(token, typeInfo, opts); } - - // src/hooks/use-outside-click.ts - function useOutsideClick(containers, cb, enabled = true) { - let enabledRef = (0, import_react10.useRef)(false); - (0, import_react10.useEffect)( - false ? 0 : () => { - requestAnimationFrame(() => { - enabledRef.current = enabled; - }); - }, - [enabled] - ); - function handleOutsideClick(event, resolveTarget) { - if (!enabledRef.current) - return; - if (event.defaultPrevented) - return; - let target = resolveTarget(event); - if (target === null) { - return; - } - if (!target.getRootNode().contains(target)) - return; - let _containers = function resolve(containers2) { - if (typeof containers2 === "function") { - return resolve(containers2()); - } - if (Array.isArray(containers2)) { - return containers2; - } - if (containers2 instanceof Set) { - return containers2; - } - return [containers2]; - }(containers); - for (let container of _containers) { - if (container === null) - continue; - let domNode = container instanceof HTMLElement ? container : container.current; - if (domNode == null ? void 0 : domNode.contains(target)) { - return; - } - if (event.composed && event.composedPath().includes(domNode)) { - return; - } - } - if ( - // This check alllows us to know whether or not we clicked on a "focusable" element like a - // button or an input. This is a backwards compatibility check so that you can open a

    and click on another which should close Menu A and open Menu B. We might - // revisit that so that you will require 2 clicks instead. - !isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1} to make it - // unfocusable via the keyboard so that tabbing to the next item from the input doesn't - // first go to the button. - target.tabIndex !== -1 - ) { - event.preventDefault(); - } - return cb(event, target); + if (kind === _parser.RuleKinds.ARGUMENTS || kind === _parser.RuleKinds.ARGUMENT && step === 0) { + const { + argDefs + } = typeInfo; + if (argDefs) { + return (0, _autocompleteUtils.hintList)(token, argDefs.map(argDef => { + var _a; + return { + label: argDef.name, + insertText: (0, _autocompleteUtils.getInputInsertText)(argDef.name + ': ', argDef.type), + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + command: SuggestionCommand, + labelDetails: { + detail: ' ' + String(argDef.type) + }, + documentation: (_a = argDef.description) !== null && _a !== void 0 ? _a : undefined, + kind: _types.CompletionItemKind.Variable, + type: argDef.type + }; + })); } - let initialClickTarget = (0, import_react10.useRef)(null); - useDocumentEvent( - "mousedown", - (event) => { - var _a3, _b; - if (enabledRef.current) { - initialClickTarget.current = ((_b = (_a3 = event.composedPath) == null ? void 0 : _a3.call(event)) == null ? void 0 : _b[0]) || event.target; - } - }, - true - ); - useDocumentEvent( - "click", - (event) => { - if (!initialClickTarget.current) { - return; - } - handleOutsideClick(event, () => { - return initialClickTarget.current; - }); - initialClickTarget.current = null; - }, - // We will use the `capture` phase so that layers in between with `event.stopPropagation()` - // don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu` - // is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However, - // the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this. - true - ); - useWindowEvent( - "blur", - (event) => handleOutsideClick( - event, - () => window.document.activeElement instanceof HTMLIFrameElement ? window.document.activeElement : null - ), - true - ); } - - // src/hooks/use-resolve-button-type.ts - var import_react11 = __webpack_require__(/*! react */ "react"); - function resolveType(props) { - var _a3; - if (props.type) - return props.type; - let tag = (_a3 = props.as) != null ? _a3 : "button"; - if (typeof tag === "string" && tag.toLowerCase() === "button") - return "button"; - return void 0; - } - function useResolveButtonType(props, ref) { - let [type, setType] = (0, import_react11.useState)(() => resolveType(props)); - useIsoMorphicEffect(() => { - setType(resolveType(props)); - }, [props.type, props.as]); - useIsoMorphicEffect(() => { - if (type) - return; - if (!ref.current) - return; - if (ref.current instanceof HTMLButtonElement && !ref.current.hasAttribute("type")) { - setType("button"); - } - }, [type, ref]); - return type; + if ((kind === _parser.RuleKinds.OBJECT_VALUE || kind === _parser.RuleKinds.OBJECT_FIELD && step === 0) && typeInfo.objectFieldDefs) { + const objectFields = (0, _autocompleteUtils.objectValues)(typeInfo.objectFieldDefs); + const completionKind = kind === _parser.RuleKinds.OBJECT_VALUE ? _types.CompletionItemKind.Value : _types.CompletionItemKind.Field; + return (0, _autocompleteUtils.hintList)(token, objectFields.map(field => { + var _a; + return { + label: field.name, + detail: String(field.type), + documentation: (_a = field === null || field === void 0 ? void 0 : field.description) !== null && _a !== void 0 ? _a : undefined, + kind: completionKind, + type: field.type, + insertText: (0, _autocompleteUtils.getInputInsertText)(field.name + ': ', field.type), + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet, + command: SuggestionCommand + }; + })); } - - // src/hooks/use-sync-refs.ts - var import_react12 = __webpack_require__(/*! react */ "react"); - var Optional = Symbol(); - function optionalRef(cb, isOptional = true) { - return Object.assign(cb, { [Optional]: isOptional }); - } - function useSyncRefs(...refs) { - let cache = (0, import_react12.useRef)(refs); - (0, import_react12.useEffect)(() => { - cache.current = refs; - }, [refs]); - let syncRefs = useEvent((value) => { - for (let ref of cache.current) { - if (ref == null) - continue; - if (typeof ref === "function") - ref(value); - else - ref.current = value; - } - }); - return refs.every( - (ref) => ref == null || // @ts-expect-error - (ref == null ? void 0 : ref[Optional]) - ) ? void 0 : syncRefs; + if (kind === _parser.RuleKinds.ENUM_VALUE || kind === _parser.RuleKinds.LIST_VALUE && step === 1 || kind === _parser.RuleKinds.OBJECT_FIELD && step === 2 || kind === _parser.RuleKinds.ARGUMENT && step === 2) { + return getSuggestionsForInputValues(token, typeInfo, queryText, schema); } - - // src/hooks/use-tree-walker.ts - var import_react13 = __webpack_require__(/*! react */ "react"); - function useTreeWalker({ - container, - accept, - walk, - enabled = true - }) { - let acceptRef = (0, import_react13.useRef)(accept); - let walkRef = (0, import_react13.useRef)(walk); - (0, import_react13.useEffect)(() => { - acceptRef.current = accept; - walkRef.current = walk; - }, [accept, walk]); - useIsoMorphicEffect(() => { - if (!container) - return; - if (!enabled) - return; - let ownerDocument = getOwnerDocument(container); - if (!ownerDocument) - return; - let accept2 = acceptRef.current; - let walk2 = walkRef.current; - let acceptNode = Object.assign((node) => accept2(node), { acceptNode: accept2 }); - let walker = ownerDocument.createTreeWalker( - container, - NodeFilter.SHOW_ELEMENT, - acceptNode, - // @ts-expect-error This `false` is a simple small fix for older browsers - false - ); - while (walker.nextNode()) - walk2(walker.currentNode); - }, [container, enabled, acceptRef, walkRef]); + if (kind === _parser.RuleKinds.VARIABLE && step === 1) { + const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); + const variableDefinitions = getVariableCompletions(queryText, schema, token); + return (0, _autocompleteUtils.hintList)(token, variableDefinitions.filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name))); } - - // src/utils/calculate-active-index.ts - function assertNever(x) { - throw new Error("Unexpected object: " + x); + if (kind === _parser.RuleKinds.TYPE_CONDITION && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState != null && prevState.kind === _parser.RuleKinds.TYPE_CONDITION) { + return getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, kind); } - function calculateActiveIndex(action, resolvers) { - let items = resolvers.resolveItems(); - if (items.length <= 0) - return null; - let currentActiveIndex = resolvers.resolveActiveIndex(); - let activeIndex = currentActiveIndex != null ? currentActiveIndex : -1; - let nextActiveIndex = (() => { - switch (action.focus) { - case 0 /* First */: - return items.findIndex((item) => !resolvers.resolveDisabled(item)); - case 1 /* Previous */: { - let idx = items.slice().reverse().findIndex((item, idx2, all) => { - if (activeIndex !== -1 && all.length - idx2 - 1 >= activeIndex) - return false; - return !resolvers.resolveDisabled(item); - }); - if (idx === -1) - return idx; - return items.length - 1 - idx; + if (kind === _parser.RuleKinds.FRAGMENT_SPREAD && step === 1) { + return getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, Array.isArray(fragmentDefs) ? fragmentDefs : collectFragmentDefs(fragmentDefs)); + } + const unwrappedState = unwrapType(state); + if (unwrappedState.kind === _parser.RuleKinds.FIELD_DEF) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isOutputType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n' : type.name, + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation + }))); + } + if (unwrappedState.kind === _parser.RuleKinds.INPUT_VALUE_DEF && step === 2) { + return (0, _autocompleteUtils.hintList)(token, Object.values(schema.getTypeMap()).filter(type => (0, _graphql.isInputType)(type) && !type.name.startsWith('__')).map(type => ({ + label: type.name, + kind: _types.CompletionItemKind.Function, + insertText: (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) ? type.name + '\n$1' : type.name, + insertTextMode: _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, + insertTextFormat: _types.InsertTextFormat.Snippet + }))); + } + if (kind === _parser.RuleKinds.VARIABLE_DEFINITION && step === 2 || kind === _parser.RuleKinds.LIST_TYPE && step === 1 || kind === _parser.RuleKinds.NAMED_TYPE && prevState && (prevState.kind === _parser.RuleKinds.VARIABLE_DEFINITION || prevState.kind === _parser.RuleKinds.LIST_TYPE || prevState.kind === _parser.RuleKinds.NON_NULL_TYPE)) { + return getSuggestionsForVariableDefinition(token, schema, kind); + } + if (kind === _parser.RuleKinds.DIRECTIVE) { + return getSuggestionsForDirective(token, state, schema, kind); + } + if (kind === _parser.RuleKinds.DIRECTIVE_DEF) { + return getSuggestionsForDirectiveArguments(token, state, schema, kind); + } + return []; +} +const typeSystemCompletionItems = [{ + label: 'type', + kind: _types.CompletionItemKind.Function +}, { + label: 'interface', + kind: _types.CompletionItemKind.Function +}, { + label: 'union', + kind: _types.CompletionItemKind.Function +}, { + label: 'input', + kind: _types.CompletionItemKind.Function +}, { + label: 'scalar', + kind: _types.CompletionItemKind.Function +}, { + label: 'schema', + kind: _types.CompletionItemKind.Function +}]; +const executableCompletionItems = [{ + label: 'query', + kind: _types.CompletionItemKind.Function +}, { + label: 'mutation', + kind: _types.CompletionItemKind.Function +}, { + label: 'subscription', + kind: _types.CompletionItemKind.Function +}, { + label: 'fragment', + kind: _types.CompletionItemKind.Function +}, { + label: '{', + kind: _types.CompletionItemKind.Constructor +}]; +function getSuggestionsForTypeSystemDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, [{ + label: 'extend', + kind: _types.CompletionItemKind.Function + }, ...typeSystemCompletionItems]); +} +function getSuggestionsForExecutableDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, executableCompletionItems); +} +function getSuggestionsForUnknownDocumentMode(token) { + return (0, _autocompleteUtils.hintList)(token, [{ + label: 'extend', + kind: _types.CompletionItemKind.Function + }, ...executableCompletionItems, ...typeSystemCompletionItems]); +} +function getSuggestionsForExtensionDefinitions(token) { + return (0, _autocompleteUtils.hintList)(token, typeSystemCompletionItems); +} +function getSuggestionsForFieldNames(token, typeInfo, options) { + var _a; + if (typeInfo.parentType) { + const { + parentType + } = typeInfo; + let fields = []; + if ('getFields' in parentType) { + fields = (0, _autocompleteUtils.objectValues)(parentType.getFields()); + } + if ((0, _graphql.isCompositeType)(parentType)) { + fields.push(_graphql.TypeNameMetaFieldDef); + } + if (parentType === ((_a = options === null || options === void 0 ? void 0 : options.schema) === null || _a === void 0 ? void 0 : _a.getQueryType())) { + fields.push(_graphql.SchemaMetaFieldDef, _graphql.TypeMetaFieldDef); + } + return (0, _autocompleteUtils.hintList)(token, fields.map((field, index) => { + var _a; + const suggestion = { + sortText: String(index) + field.name, + label: field.name, + detail: String(field.type), + documentation: (_a = field.description) !== null && _a !== void 0 ? _a : undefined, + deprecated: Boolean(field.deprecationReason), + isDeprecated: Boolean(field.deprecationReason), + deprecationReason: field.deprecationReason, + kind: _types.CompletionItemKind.Field, + labelDetails: { + detail: ' ' + field.type.toString() + }, + type: field.type + }; + if (options === null || options === void 0 ? void 0 : options.fillLeafsOnComplete) { + suggestion.insertText = (0, _autocompleteUtils.getFieldInsertText)(field); + if (!suggestion.insertText) { + suggestion.insertText = (0, _autocompleteUtils.getInsertText)(field.name, field.type, field.name + (token.state.needsAdvance ? '' : '\n')); + } + if (suggestion.insertText) { + suggestion.insertTextFormat = _types.InsertTextFormat.Snippet; + suggestion.insertTextMode = _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation; + suggestion.command = SuggestionCommand; } - case 2 /* Next */: - return items.findIndex((item, idx) => { - if (idx <= activeIndex) - return false; - return !resolvers.resolveDisabled(item); - }); - case 3 /* Last */: { - let idx = items.slice().reverse().findIndex((item) => !resolvers.resolveDisabled(item)); - if (idx === -1) - return idx; - return items.length - 1 - idx; - } - case 4 /* Specific */: - return items.findIndex((item) => resolvers.resolveId(item) === action.id); - case 5 /* Nothing */: - return null; - default: - assertNever(action); } - })(); - return nextActiveIndex === -1 ? currentActiveIndex : nextActiveIndex; + return suggestion; + })); } - - // src/utils/render.ts - var import_react14 = __webpack_require__(/*! react */ "react"); - - // src/utils/class-names.ts - function classNames(...classes) { - return classes.filter(Boolean).join(" "); + return []; +} +function getSuggestionsForInputValues(token, typeInfo, queryText, schema) { + const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); + const queryVariables = getVariableCompletions(queryText, schema, token).filter(v => v.detail === (namedInputType === null || namedInputType === void 0 ? void 0 : namedInputType.name)); + if (namedInputType instanceof _graphql.GraphQLEnumType) { + const values = namedInputType.getValues(); + return (0, _autocompleteUtils.hintList)(token, values.map(value => { + var _a; + return { + label: value.name, + detail: String(namedInputType), + documentation: (_a = value.description) !== null && _a !== void 0 ? _a : undefined, + deprecated: Boolean(value.deprecationReason), + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + kind: _types.CompletionItemKind.EnumMember, + type: namedInputType + }; + }).concat(queryVariables)); + } + if (namedInputType === _graphql.GraphQLBoolean) { + return (0, _autocompleteUtils.hintList)(token, queryVariables.concat([{ + label: 'true', + detail: String(_graphql.GraphQLBoolean), + documentation: 'Not false.', + kind: _types.CompletionItemKind.Variable, + type: _graphql.GraphQLBoolean + }, { + label: 'false', + detail: String(_graphql.GraphQLBoolean), + documentation: 'Not true.', + kind: _types.CompletionItemKind.Variable, + type: _graphql.GraphQLBoolean + }])); + } + return queryVariables; +} +function getSuggestionsForImplements(token, tokenState, schema, documentText, typeInfo) { + if (tokenState.needsSeparator) { + return []; } - - // src/utils/render.ts - function render({ - ourProps, - theirProps, - slot, - defaultTag, - features, - visible = true, + const typeMap = schema.getTypeMap(); + const schemaInterfaces = (0, _autocompleteUtils.objectValues)(typeMap).filter(_graphql.isInterfaceType); + const schemaInterfaceNames = schemaInterfaces.map(({ name - }) { - let props = mergeProps(theirProps, ourProps); - if (visible) - return _render(props, slot, defaultTag, name); - let featureFlags = features != null ? features : 0 /* None */; - if (featureFlags & 2 /* Static */) { - let { static: isStatic = false, ...rest } = props; - if (isStatic) - return _render(rest, slot, defaultTag, name); - } - if (featureFlags & 1 /* RenderStrategy */) { - let { unmount = true, ...rest } = props; - let strategy = unmount ? 0 /* Unmount */ : 1 /* Hidden */; - return match(strategy, { - [0 /* Unmount */]() { - return null; - }, - [1 /* Hidden */]() { - return _render( - { ...rest, ...{ hidden: true, style: { display: "none" } } }, - slot, - defaultTag, + }) => name); + const inlineInterfaces = new Set(); + (0, _parser.runOnlineParser)(documentText, (_, state) => { + var _a, _b, _c, _d, _e; + if (state.name) { + if (state.kind === _parser.RuleKinds.INTERFACE_DEF && !schemaInterfaceNames.includes(state.name)) { + inlineInterfaces.add(state.name); + } + if (state.kind === _parser.RuleKinds.NAMED_TYPE && ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === _parser.RuleKinds.IMPLEMENTS) { + if (typeInfo.interfaceDef) { + const existingType = (_b = typeInfo.interfaceDef) === null || _b === void 0 ? void 0 : _b.getInterfaces().find(({ name - ); + }) => name === state.name); + if (existingType) { + return; + } + const type = schema.getType(state.name); + const interfaceConfig = (_c = typeInfo.interfaceDef) === null || _c === void 0 ? void 0 : _c.toConfig(); + typeInfo.interfaceDef = new _graphql.GraphQLInterfaceType(Object.assign(Object.assign({}, interfaceConfig), { + interfaces: [...interfaceConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ + name: state.name, + fields: {} + })] + })); + } else if (typeInfo.objectTypeDef) { + const existingType = (_d = typeInfo.objectTypeDef) === null || _d === void 0 ? void 0 : _d.getInterfaces().find(({ + name + }) => name === state.name); + if (existingType) { + return; + } + const type = schema.getType(state.name); + const objectTypeConfig = (_e = typeInfo.objectTypeDef) === null || _e === void 0 ? void 0 : _e.toConfig(); + typeInfo.objectTypeDef = new _graphql.GraphQLObjectType(Object.assign(Object.assign({}, objectTypeConfig), { + interfaces: [...objectTypeConfig.interfaces, type || new _graphql.GraphQLInterfaceType({ + name: state.name, + fields: {} + })] + })); } - }); + } } - return _render(props, slot, defaultTag, name); - } - function _render(props, slot = {}, tag, name) { - let { - as: Component = tag, - children, - refName = "ref", - ...rest - } = omit(props, ["unmount", "static"]); - let refRelatedProps = props.ref !== void 0 ? { [refName]: props.ref } : {}; - let resolvedChildren = typeof children === "function" ? children(slot) : children; - if ("className" in rest && rest.className && typeof rest.className === "function") { - rest.className = rest.className(slot); - } - let dataAttributes = {}; - if (slot) { - let exposeState = false; - let states = []; - for (let [k, v] of Object.entries(slot)) { - if (typeof v === "boolean") { - exposeState = true; - } - if (v === true) { - states.push(k); - } - } - if (exposeState) - dataAttributes[`data-headlessui-state`] = states.join(" "); - } - if (Component === import_react14.Fragment) { - if (Object.keys(compact(rest)).length > 0) { - if (!(0, import_react14.isValidElement)(resolvedChildren) || Array.isArray(resolvedChildren) && resolvedChildren.length > 1) { - throw new Error( - [ - 'Passing props on "Fragment"!', - "", - `The current component <${name} /> is rendering a "Fragment".`, - `However we need to passthrough the following props:`, - Object.keys(rest).map((line) => ` - ${line}`).join("\n"), - "", - "You can apply a few solutions:", - [ - 'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', - "Render a single element as the child so that we can forward the props onto that element." - ].map((line) => ` - ${line}`).join("\n") - ].join("\n") - ); + }); + const currentTypeToExtend = typeInfo.interfaceDef || typeInfo.objectTypeDef; + const siblingInterfaces = (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.getInterfaces()) || []; + const siblingInterfaceNames = siblingInterfaces.map(({ + name + }) => name); + const possibleInterfaces = schemaInterfaces.concat([...inlineInterfaces].map(name => ({ + name + }))).filter(({ + name + }) => name !== (currentTypeToExtend === null || currentTypeToExtend === void 0 ? void 0 : currentTypeToExtend.name) && !siblingInterfaceNames.includes(name)); + return (0, _autocompleteUtils.hintList)(token, possibleInterfaces.map(type => { + const result = { + label: type.name, + kind: _types.CompletionItemKind.Interface, + type + }; + if (type === null || type === void 0 ? void 0 : type.description) { + result.documentation = type.description; + } + return result; + })); +} +function getSuggestionsForFragmentTypeConditions(token, typeInfo, schema, _kind) { + let possibleTypes; + if (typeInfo.parentType) { + if ((0, _graphql.isAbstractType)(typeInfo.parentType)) { + const abstractType = (0, _graphql.assertAbstractType)(typeInfo.parentType); + const possibleObjTypes = schema.getPossibleTypes(abstractType); + const possibleIfaceMap = Object.create(null); + for (const type of possibleObjTypes) { + for (const iface of type.getInterfaces()) { + possibleIfaceMap[iface.name] = iface; } - let childProps = resolvedChildren.props; - let newClassName = typeof (childProps == null ? void 0 : childProps.className) === "function" ? (...args) => classNames(childProps == null ? void 0 : childProps.className(...args), rest.className) : classNames(childProps == null ? void 0 : childProps.className, rest.className); - let classNameProps = newClassName ? { className: newClassName } : {}; - return (0, import_react14.cloneElement)( - resolvedChildren, - Object.assign( - {}, - // Filter out undefined values so that they don't override the existing values - mergeProps(resolvedChildren.props, compact(omit(rest, ["ref"]))), - dataAttributes, - refRelatedProps, - mergeRefs(resolvedChildren.ref, refRelatedProps.ref), - classNameProps - ) - ); } + possibleTypes = possibleObjTypes.concat((0, _autocompleteUtils.objectValues)(possibleIfaceMap)); + } else { + possibleTypes = [typeInfo.parentType]; } - return (0, import_react14.createElement)( - Component, - Object.assign( - {}, - omit(rest, ["ref"]), - Component !== import_react14.Fragment && refRelatedProps, - Component !== import_react14.Fragment && dataAttributes - ), - resolvedChildren - ); + } else { + const typeMap = schema.getTypeMap(); + possibleTypes = (0, _autocompleteUtils.objectValues)(typeMap).filter(type => (0, _graphql.isCompositeType)(type) && !type.name.startsWith('__')); } - function mergeRefs(...refs) { + return (0, _autocompleteUtils.hintList)(token, possibleTypes.map(type => { + const namedType = (0, _graphql.getNamedType)(type); return { - ref: refs.every((ref) => ref == null) ? void 0 : (value) => { - for (let ref of refs) { - if (ref == null) - continue; - if (typeof ref === "function") - ref(value); - else - ref.current = value; - } - } + label: String(type), + documentation: (namedType === null || namedType === void 0 ? void 0 : namedType.description) || '', + kind: _types.CompletionItemKind.Field }; + })); +} +function getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText, fragmentDefs) { + if (!queryText) { + return []; } - function mergeProps(...listOfProps) { - var _a3; - if (listOfProps.length === 0) - return {}; - if (listOfProps.length === 1) - return listOfProps[0]; - let target = {}; - let eventHandlers = {}; - for (let props of listOfProps) { - for (let prop in props) { - if (prop.startsWith("on") && typeof props[prop] === "function") { - (_a3 = eventHandlers[prop]) != null ? _a3 : eventHandlers[prop] = []; - eventHandlers[prop].push(props[prop]); - } else { - target[prop] = props[prop]; - } - } - } - if (target.disabled || target["aria-disabled"]) { - return Object.assign( - target, - // Set all event listeners that we collected to `undefined`. This is - // important because of the `cloneElement` from above, which merges the - // existing and new props, they don't just override therefore we have to - // explicitly nullify them. - Object.fromEntries(Object.keys(eventHandlers).map((eventName) => [eventName, void 0])) - ); + const typeMap = schema.getTypeMap(); + const defState = (0, _parser.getDefinitionState)(token.state); + const fragments = getFragmentDefinitions(queryText); + if (fragmentDefs && fragmentDefs.length > 0) { + fragments.push(...fragmentDefs); + } + const relevantFrags = fragments.filter(frag => typeMap[frag.typeCondition.name.value] && !(defState && defState.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && defState.name === frag.name.value) && (0, _graphql.isCompositeType)(typeInfo.parentType) && (0, _graphql.isCompositeType)(typeMap[frag.typeCondition.name.value]) && (0, _graphql.doTypesOverlap)(schema, typeInfo.parentType, typeMap[frag.typeCondition.name.value])); + return (0, _autocompleteUtils.hintList)(token, relevantFrags.map(frag => ({ + label: frag.name.value, + detail: String(typeMap[frag.typeCondition.name.value]), + documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, + labelDetails: { + detail: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}` + }, + kind: _types.CompletionItemKind.Field, + type: typeMap[frag.typeCondition.name.value] + }))); +} +const getParentDefinition = (state, kind) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + if (((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) === kind) { + return state.prevState; + } + if (((_c = (_b = state.prevState) === null || _b === void 0 ? void 0 : _b.prevState) === null || _c === void 0 ? void 0 : _c.kind) === kind) { + return state.prevState.prevState; + } + if (((_f = (_e = (_d = state.prevState) === null || _d === void 0 ? void 0 : _d.prevState) === null || _e === void 0 ? void 0 : _e.prevState) === null || _f === void 0 ? void 0 : _f.kind) === kind) { + return state.prevState.prevState.prevState; + } + if (((_k = (_j = (_h = (_g = state.prevState) === null || _g === void 0 ? void 0 : _g.prevState) === null || _h === void 0 ? void 0 : _h.prevState) === null || _j === void 0 ? void 0 : _j.prevState) === null || _k === void 0 ? void 0 : _k.kind) === kind) { + return state.prevState.prevState.prevState.prevState; + } +}; +function getVariableCompletions(queryText, schema, token) { + let variableName = null; + let variableType; + const definitions = Object.create({}); + (0, _parser.runOnlineParser)(queryText, (_, state) => { + var _a; + if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.VARIABLE && state.name) { + variableName = state.name; + } + if ((state === null || state === void 0 ? void 0 : state.kind) === _parser.RuleKinds.NAMED_TYPE && variableName) { + const parentDefinition = getParentDefinition(state, _parser.RuleKinds.TYPE); + if (parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type) { + variableType = schema.getType(parentDefinition === null || parentDefinition === void 0 ? void 0 : parentDefinition.type); + } + } + if (variableName && variableType && !definitions[variableName]) { + const replaceString = token.string === '$' || ((_a = token === null || token === void 0 ? void 0 : token.state) === null || _a === void 0 ? void 0 : _a.kind) === 'Variable' ? variableName : '$' + variableName; + definitions[variableName] = { + detail: variableType.toString(), + insertText: replaceString, + label: '$' + variableName, + rawInsert: replaceString, + type: variableType, + kind: _types.CompletionItemKind.Variable + }; + variableName = null; + variableType = null; } - for (let eventName in eventHandlers) { - Object.assign(target, { - [eventName](event, ...args) { - let handlers = eventHandlers[eventName]; - for (let handler of handlers) { - if ((event instanceof Event || (event == null ? void 0 : event.nativeEvent) instanceof Event) && event.defaultPrevented) { - return; - } - handler(event, ...args); + }); + return (0, _autocompleteUtils.objectValues)(definitions); +} +function getFragmentDefinitions(queryText) { + const fragmentDefs = []; + (0, _parser.runOnlineParser)(queryText, (_, state) => { + if (state.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && state.name && state.type) { + fragmentDefs.push({ + kind: _parser.RuleKinds.FRAGMENT_DEFINITION, + name: { + kind: _graphql.Kind.NAME, + value: state.name + }, + selectionSet: { + kind: _parser.RuleKinds.SELECTION_SET, + selections: [] + }, + typeCondition: { + kind: _parser.RuleKinds.NAMED_TYPE, + name: { + kind: _graphql.Kind.NAME, + value: state.type } } }); } - return target; + }); + return fragmentDefs; +} +function getSuggestionsForVariableDefinition(token, schema, _kind) { + const inputTypeMap = schema.getTypeMap(); + const inputTypes = (0, _autocompleteUtils.objectValues)(inputTypeMap).filter(_graphql.isInputType); + return (0, _autocompleteUtils.hintList)(token, inputTypes.map(type => ({ + label: type.name, + documentation: (type === null || type === void 0 ? void 0 : type.description) || '', + kind: _types.CompletionItemKind.Variable + }))); +} +function getSuggestionsForDirective(token, state, schema, _kind) { + var _a; + if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind) { + const directives = schema.getDirectives().filter(directive => canUseDirective(state.prevState, directive)); + return (0, _autocompleteUtils.hintList)(token, directives.map(directive => ({ + label: directive.name, + documentation: (directive === null || directive === void 0 ? void 0 : directive.description) || '', + kind: _types.CompletionItemKind.Function + }))); } - function forwardRefWithAs(component) { - var _a3; - return Object.assign((0, import_react14.forwardRef)(component), { - displayName: (_a3 = component.displayName) != null ? _a3 : component.name + return []; +} +function getSuggestionsForDirectiveArguments(token, state, schema, _kind) { + const directive = schema.getDirectives().find(d => d.name === state.name); + return (0, _autocompleteUtils.hintList)(token, (directive === null || directive === void 0 ? void 0 : directive.args.map(arg => ({ + label: arg.name, + documentation: arg.description || '', + kind: _types.CompletionItemKind.Field + }))) || []); +} +function canUseDirective(state, directive) { + if (!(state === null || state === void 0 ? void 0 : state.kind)) { + return false; + } + const { + kind, + prevState + } = state; + const { + locations + } = directive; + switch (kind) { + case _parser.RuleKinds.QUERY: + return locations.includes(_graphql.DirectiveLocation.QUERY); + case _parser.RuleKinds.MUTATION: + return locations.includes(_graphql.DirectiveLocation.MUTATION); + case _parser.RuleKinds.SUBSCRIPTION: + return locations.includes(_graphql.DirectiveLocation.SUBSCRIPTION); + case _parser.RuleKinds.FIELD: + case _parser.RuleKinds.ALIASED_FIELD: + return locations.includes(_graphql.DirectiveLocation.FIELD); + case _parser.RuleKinds.FRAGMENT_DEFINITION: + return locations.includes(_graphql.DirectiveLocation.FRAGMENT_DEFINITION); + case _parser.RuleKinds.FRAGMENT_SPREAD: + return locations.includes(_graphql.DirectiveLocation.FRAGMENT_SPREAD); + case _parser.RuleKinds.INLINE_FRAGMENT: + return locations.includes(_graphql.DirectiveLocation.INLINE_FRAGMENT); + case _parser.RuleKinds.SCHEMA_DEF: + return locations.includes(_graphql.DirectiveLocation.SCHEMA); + case _parser.RuleKinds.SCALAR_DEF: + return locations.includes(_graphql.DirectiveLocation.SCALAR); + case _parser.RuleKinds.OBJECT_TYPE_DEF: + return locations.includes(_graphql.DirectiveLocation.OBJECT); + case _parser.RuleKinds.FIELD_DEF: + return locations.includes(_graphql.DirectiveLocation.FIELD_DEFINITION); + case _parser.RuleKinds.INTERFACE_DEF: + return locations.includes(_graphql.DirectiveLocation.INTERFACE); + case _parser.RuleKinds.UNION_DEF: + return locations.includes(_graphql.DirectiveLocation.UNION); + case _parser.RuleKinds.ENUM_DEF: + return locations.includes(_graphql.DirectiveLocation.ENUM); + case _parser.RuleKinds.ENUM_VALUE: + return locations.includes(_graphql.DirectiveLocation.ENUM_VALUE); + case _parser.RuleKinds.INPUT_DEF: + return locations.includes(_graphql.DirectiveLocation.INPUT_OBJECT); + case _parser.RuleKinds.INPUT_VALUE_DEF: + const prevStateKind = prevState === null || prevState === void 0 ? void 0 : prevState.kind; + switch (prevStateKind) { + case _parser.RuleKinds.ARGUMENTS_DEF: + return locations.includes(_graphql.DirectiveLocation.ARGUMENT_DEFINITION); + case _parser.RuleKinds.INPUT_DEF: + return locations.includes(_graphql.DirectiveLocation.INPUT_FIELD_DEFINITION); + } + } + return false; +} +function unwrapType(state) { + if (state.prevState && state.kind && [_parser.RuleKinds.NAMED_TYPE, _parser.RuleKinds.LIST_TYPE, _parser.RuleKinds.TYPE, _parser.RuleKinds.NON_NULL_TYPE].includes(state.kind)) { + return unwrapType(state.prevState); + } + return state; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/getDefinition.js": +/*!*********************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getDefinition.js ***! + \*********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LANGUAGE = void 0; +exports.getDefinitionQueryResultForArgument = getDefinitionQueryResultForArgument; +exports.getDefinitionQueryResultForDefinitionNode = getDefinitionQueryResultForDefinitionNode; +exports.getDefinitionQueryResultForField = getDefinitionQueryResultForField; +exports.getDefinitionQueryResultForFragmentSpread = getDefinitionQueryResultForFragmentSpread; +exports.getDefinitionQueryResultForNamedType = getDefinitionQueryResultForNamedType; +var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); +var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); }); } - function compact(object) { - let clone = Object.assign({}, object); - for (let key in clone) { - if (clone[key] === void 0) - delete clone[key]; + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return clone; - } - function omit(object, keysToOmit = []) { - let clone = Object.assign({}, object); - for (let key of keysToOmit) { - if (key in clone) - delete clone[key]; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const LANGUAGE = exports.LANGUAGE = 'GraphQL'; +function assert(value, message) { + if (!value) { + throw new Error(message); + } +} +function getRange(text, node) { + const location = node.loc; + assert(location, 'Expected ASTNode to have a location.'); + return (0, _utils.locToRange)(text, location); +} +function getPosition(text, node) { + const location = node.loc; + assert(location, 'Expected ASTNode to have a location.'); + return (0, _utils.offsetToPosition)(text, location.start); +} +function getDefinitionQueryResultForNamedType(text, node, dependencies) { + return __awaiter(this, void 0, void 0, function* () { + const name = node.name.value; + const defNodes = dependencies.filter(({ + definition + }) => definition.name && definition.name.value === name); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL type ${name}`); + } + const definitions = defNodes.map(({ + filePath, + content, + definition + }) => getDefinitionForNodeDefinition(filePath || '', content, definition)); + return { + definitions, + queryRange: definitions.map(_ => getRange(text, node)), + printedName: name + }; + }); +} +function getDefinitionQueryResultForField(fieldName, typeName, dependencies) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const defNodes = dependencies.filter(({ + definition + }) => definition.name && definition.name.value === typeName); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL type ${typeName}`); + } + const definitions = []; + for (const { + filePath, + content, + definition + } of defNodes) { + const fieldDefinition = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName); + if (fieldDefinition == null) { + continue; + } + definitions.push(getDefinitionForFieldDefinition(filePath || '', content, fieldDefinition)); + } + return { + definitions, + queryRange: [], + printedName: [typeName, fieldName].join('.') + }; + }); +} +function getDefinitionQueryResultForArgument(argumentName, fieldName, typeName, dependencies) { + var _a, _b, _c; + return __awaiter(this, void 0, void 0, function* () { + const definitions = []; + for (const { + filePath, + content, + definition + } of dependencies) { + const argDefinition = (_c = (_b = (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.find(item => item.name.value === fieldName)) === null || _b === void 0 ? void 0 : _b.arguments) === null || _c === void 0 ? void 0 : _c.find(item => item.name.value === argumentName); + if (argDefinition == null) { + continue; + } + definitions.push(getDefinitionForArgumentDefinition(filePath || '', content, argDefinition)); + } + return { + definitions, + queryRange: [], + printedName: `${[typeName, fieldName].join('.')}(${argumentName})` + }; + }); +} +function getDefinitionQueryResultForFragmentSpread(text, fragment, dependencies) { + return __awaiter(this, void 0, void 0, function* () { + const name = fragment.name.value; + const defNodes = dependencies.filter(({ + definition + }) => definition.name.value === name); + if (defNodes.length === 0) { + throw new Error(`Definition not found for GraphQL fragment ${name}`); + } + const definitions = defNodes.map(({ + filePath, + content, + definition + }) => getDefinitionForFragmentDefinition(filePath || '', content, definition)); + return { + definitions, + queryRange: definitions.map(_ => getRange(text, fragment)), + printedName: name + }; + }); +} +function getDefinitionQueryResultForDefinitionNode(path, text, definition) { + var _a; + return { + definitions: [getDefinitionForFragmentDefinition(path, text, definition)], + queryRange: definition.name ? [getRange(text, definition.name)] : [], + printedName: (_a = definition.name) === null || _a === void 0 ? void 0 : _a.value + }; +} +function getDefinitionForFragmentDefinition(path, text, definition) { + const { + name + } = definition; + if (!name) { + throw new Error('Expected ASTNode to have a Name.'); + } + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; +} +function getDefinitionForNodeDefinition(path, text, definition) { + const { + name + } = definition; + assert(name, 'Expected ASTNode to have a Name.'); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; +} +function getDefinitionForFieldDefinition(path, text, definition) { + const { + name + } = definition; + assert(name, 'Expected ASTNode to have a Name.'); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; +} +function getDefinitionForArgumentDefinition(path, text, definition) { + const { + name + } = definition; + assert(name, 'Expected ASTNode to have a Name.'); + return { + path, + position: getPosition(text, definition), + range: getRange(text, definition), + name: name.value || '', + language: LANGUAGE, + projectRoot: path + }; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/getDiagnostics.js": +/*!**********************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getDiagnostics.js ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.SEVERITY = exports.DIAGNOSTIC_SEVERITY = void 0; +exports.getDiagnostics = getDiagnostics; +exports.getRange = getRange; +exports.validateQuery = validateQuery; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); +var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); +const SEVERITY = exports.SEVERITY = { + Error: 'Error', + Warning: 'Warning', + Information: 'Information', + Hint: 'Hint' +}; +const DIAGNOSTIC_SEVERITY = exports.DIAGNOSTIC_SEVERITY = { + [SEVERITY.Error]: 1, + [SEVERITY.Warning]: 2, + [SEVERITY.Information]: 3, + [SEVERITY.Hint]: 4 +}; +const invariant = (condition, message) => { + if (!condition) { + throw new Error(message); + } +}; +function getDiagnostics(query, schema = null, customRules, isRelayCompatMode, externalFragments) { + var _a, _b; + let ast = null; + let fragments = ''; + if (externalFragments) { + fragments = typeof externalFragments === 'string' ? externalFragments : externalFragments.reduce((acc, node) => acc + (0, _graphql.print)(node) + '\n\n', ''); + } + const enhancedQuery = fragments ? `${query}\n\n${fragments}` : query; + try { + ast = (0, _graphql.parse)(enhancedQuery); + } catch (error) { + if (error instanceof _graphql.GraphQLError) { + const range = getRange((_b = (_a = error.locations) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : { + line: 0, + column: 0 + }, enhancedQuery); + return [{ + severity: DIAGNOSTIC_SEVERITY.Error, + message: error.message, + source: 'GraphQL: Syntax', + range + }]; } - return clone; + throw error; } - - // src/utils/bugs.ts - function isDisabledReactIssue7711(element) { - let parent = element.parentElement; - let legend = null; - while (parent && !(parent instanceof HTMLFieldSetElement)) { - if (parent instanceof HTMLLegendElement) - legend = parent; - parent = parent.parentElement; - } - let isParentDisabled = (parent == null ? void 0 : parent.getAttribute("disabled")) === ""; - if (isParentDisabled && isFirstLegend(legend)) - return false; - return isParentDisabled; + return validateQuery(ast, schema, customRules, isRelayCompatMode); +} +function validateQuery(ast, schema = null, customRules, isRelayCompatMode) { + if (!schema) { + return []; } - function isFirstLegend(element) { - if (!element) - return false; - let previous = element.previousElementSibling; - while (previous !== null) { - if (previous instanceof HTMLLegendElement) - return false; - previous = previous.previousElementSibling; - } - return true; + const validationErrorAnnotations = (0, _utils.validateWithCustomRules)(schema, ast, customRules, isRelayCompatMode).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Error, 'Validation')); + const deprecationWarningAnnotations = (0, _graphql.validate)(schema, ast, [_graphql.NoDeprecatedCustomRule]).flatMap(error => annotations(error, DIAGNOSTIC_SEVERITY.Warning, 'Deprecation')); + return validationErrorAnnotations.concat(deprecationWarningAnnotations); +} +function annotations(error, severity, type) { + if (!error.nodes) { + return []; } - - // src/utils/form.ts - function objectToFormEntries(source = {}, parentKey = null, entries = []) { - for (let [key, value] of Object.entries(source)) { - append(entries, composeKey(parentKey, key), value); - } - return entries; - } - function composeKey(parent, key) { - return parent ? parent + "[" + key + "]" : key; - } - function append(entries, key, value) { - if (Array.isArray(value)) { - for (let [subkey, subvalue] of value.entries()) { - append(entries, composeKey(key, subkey.toString()), subvalue); - } - } else if (value instanceof Date) { - entries.push([key, value.toISOString()]); - } else if (typeof value === "boolean") { - entries.push([key, value ? "1" : "0"]); - } else if (typeof value === "string") { - entries.push([key, value]); - } else if (typeof value === "number") { - entries.push([key, `${value}`]); - } else if (value === null || value === void 0) { - entries.push([key, ""]); - } else { - objectToFormEntries(value, key, entries); + const highlightedNodes = []; + for (const [i, node] of error.nodes.entries()) { + const highlightNode = node.kind !== 'Variable' && 'name' in node && node.name !== undefined ? node.name : 'variable' in node && node.variable !== undefined ? node.variable : node; + if (highlightNode) { + invariant(error.locations, 'GraphQL validation error requires locations.'); + const loc = error.locations[i]; + const highlightLoc = getLocation(highlightNode); + const end = loc.column + (highlightLoc.end - highlightLoc.start); + highlightedNodes.push({ + source: `GraphQL: ${type}`, + message: error.message, + severity, + range: new _utils.Range(new _utils.Position(loc.line - 1, loc.column - 1), new _utils.Position(loc.line - 1, end)) + }); } } - function attemptSubmit(element) { - var _a3; - let form = (_a3 = element == null ? void 0 : element.form) != null ? _a3 : element.closest("form"); - if (!form) - return; - for (let element2 of form.elements) { - if (element2.tagName === "INPUT" && element2.type === "submit" || element2.tagName === "BUTTON" && element2.type === "submit" || element2.nodeName === "INPUT" && element2.type === "image") { - element2.click(); - return; + return highlightedNodes; +} +function getRange(location, queryText) { + const parser = (0, _parser.onlineParser)(); + const state = parser.startState(); + const lines = queryText.split('\n'); + invariant(lines.length >= location.line, 'Query text must have more lines than where the error happened'); + let stream = null; + for (let i = 0; i < location.line; i++) { + stream = new _parser.CharacterStream(lines[i]); + while (!stream.eol()) { + const style = parser.token(stream, state); + if (style === 'invalidchar') { + break; } } } - - // src/internal/hidden.tsx - var DEFAULT_VISUALLY_HIDDEN_TAG = "div"; - function VisuallyHidden(props, ref) { - let { features = 1 /* None */, ...theirProps } = props; - let ourProps = { - ref, - "aria-hidden": (features & 2 /* Focusable */) === 2 /* Focusable */ ? true : void 0, - style: { - position: "fixed", - top: 1, - left: 1, - width: 1, - height: 0, - padding: 0, - margin: -1, - overflow: "hidden", - clip: "rect(0, 0, 0, 0)", - whiteSpace: "nowrap", - borderWidth: "0", - ...(features & 4 /* Hidden */) === 4 /* Hidden */ && !((features & 2 /* Focusable */) === 2 /* Focusable */) && { display: "none" } - } - }; - return render({ - ourProps, - theirProps, - slot: {}, - defaultTag: DEFAULT_VISUALLY_HIDDEN_TAG, - name: "Hidden" - }); + invariant(stream, 'Expected Parser stream to be available.'); + const line = location.line - 1; + const start = stream.getStartOfToken(); + const end = stream.getCurrentPosition(); + return new _utils.Range(new _utils.Position(line, start), new _utils.Position(line, end)); +} +function getLocation(node) { + const typeCastedNode = node; + const location = typeCastedNode.loc; + invariant(location, 'Expected ASTNode to have a location.'); + return location; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/getHoverInformation.js": +/*!***************************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getHoverInformation.js ***! + \***************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getHoverInformation = getHoverInformation; +exports.renderArg = renderArg; +exports.renderDirective = renderDirective; +exports.renderEnumValue = renderEnumValue; +exports.renderField = renderField; +exports.renderType = renderType; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _parser = __webpack_require__(/*! ../parser */ "../../graphql-language-service/esm/parser/index.js"); +function getHoverInformation(schema, queryText, cursor, contextToken, config) { + const options = Object.assign(Object.assign({}, config), { + schema + }); + const context = (0, _parser.getContextAtPosition)(queryText, cursor, schema, contextToken); + if (!context) { + return ''; + } + const { + typeInfo, + token + } = context; + const { + kind, + step + } = token.state; + if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef || kind === 'ObjectField' && step === 0 && typeInfo.fieldDef) { + const into = []; + renderMdCodeStart(into, options); + renderField(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.fieldDef); + return into.join('').trim(); + } + if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) { + const into = []; + renderMdCodeStart(into, options); + renderDirective(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.directiveDef); + return into.join('').trim(); + } + if (kind === 'Variable' && typeInfo.type) { + const into = []; + renderMdCodeStart(into, options); + renderType(into, typeInfo, options, typeInfo.type); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.type); + return into.join('').trim(); + } + if (kind === 'Argument' && step === 0 && typeInfo.argDef) { + const into = []; + renderMdCodeStart(into, options); + renderArg(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.argDef); + return into.join('').trim(); + } + if (kind === 'EnumValue' && typeInfo.enumValue && 'description' in typeInfo.enumValue) { + const into = []; + renderMdCodeStart(into, options); + renderEnumValue(into, typeInfo, options); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.enumValue); + return into.join('').trim(); + } + if (kind === 'NamedType' && typeInfo.type && 'description' in typeInfo.type) { + const into = []; + renderMdCodeStart(into, options); + renderType(into, typeInfo, options, typeInfo.type); + renderMdCodeEnd(into, options); + renderDescription(into, options, typeInfo.type); + return into.join('').trim(); + } + return ''; +} +function renderMdCodeStart(into, options) { + if (options.useMarkdown) { + text(into, '```graphql\n'); + } +} +function renderMdCodeEnd(into, options) { + if (options.useMarkdown) { + text(into, '\n```'); + } +} +function renderField(into, typeInfo, options) { + renderQualifiedField(into, typeInfo, options); + renderTypeAnnotation(into, typeInfo, options, typeInfo.type); +} +function renderQualifiedField(into, typeInfo, options) { + if (!typeInfo.fieldDef) { + return; } - var Hidden = forwardRefWithAs(VisuallyHidden); - - // src/internal/open-closed.tsx - var import_react15 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var Context = (0, import_react15.createContext)(null); - Context.displayName = "OpenClosedContext"; - function useOpenClosed() { - return (0, import_react15.useContext)(Context); + const fieldName = typeInfo.fieldDef.name; + if (fieldName.slice(0, 2) !== '__') { + renderType(into, typeInfo, options, typeInfo.parentType); + text(into, '.'); } - function OpenClosedProvider({ value, children }) { - return /* @__PURE__ */ import_react15.default.createElement(Context.Provider, { value }, children); + text(into, fieldName); +} +function renderDirective(into, typeInfo, _options) { + if (!typeInfo.directiveDef) { + return; } - - // src/hooks/use-controllable.ts - var import_react16 = __webpack_require__(/*! react */ "react"); - function useControllable(controlledValue, onChange, defaultValue) { - let [internalValue, setInternalValue] = (0, import_react16.useState)(defaultValue); - let isControlled = controlledValue !== void 0; - let wasControlled = (0, import_react16.useRef)(isControlled); - let didWarnOnUncontrolledToControlled = (0, import_react16.useRef)(false); - let didWarnOnControlledToUncontrolled = (0, import_react16.useRef)(false); - if (isControlled && !wasControlled.current && !didWarnOnUncontrolledToControlled.current) { - didWarnOnUncontrolledToControlled.current = true; - wasControlled.current = isControlled; - console.error( - "A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen." - ); - } else if (!isControlled && wasControlled.current && !didWarnOnControlledToUncontrolled.current) { - didWarnOnControlledToUncontrolled.current = true; - wasControlled.current = isControlled; - console.error( - "A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen." - ); - } - return [ - isControlled ? controlledValue : internalValue, - useEvent((value) => { - if (isControlled) { - return onChange == null ? void 0 : onChange(value); - } else { - setInternalValue(value); - return onChange == null ? void 0 : onChange(value); - } - }) - ]; + const name = '@' + typeInfo.directiveDef.name; + text(into, name); +} +function renderArg(into, typeInfo, options) { + if (typeInfo.directiveDef) { + renderDirective(into, typeInfo, options); + } else if (typeInfo.fieldDef) { + renderQualifiedField(into, typeInfo, options); } - - // src/hooks/use-watch.ts - var import_react17 = __webpack_require__(/*! react */ "react"); - function useWatch(cb, dependencies) { - let track = (0, import_react17.useRef)([]); - let action = useEvent(cb); - (0, import_react17.useEffect)(() => { - let oldValues = [...track.current]; - for (let [idx, value] of dependencies.entries()) { - if (track.current[idx] !== value) { - let returnValue = action(dependencies, oldValues); - track.current = dependencies; - return returnValue; - } - } - }, [action, ...dependencies]); + if (!typeInfo.argDef) { + return; } - - // src/hooks/use-tracked-pointer.ts - var import_react18 = __webpack_require__(/*! react */ "react"); - function eventToPosition(evt) { - return [evt.screenX, evt.screenY]; + const { + name + } = typeInfo.argDef; + text(into, '('); + text(into, name); + renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); + text(into, ')'); +} +function renderTypeAnnotation(into, typeInfo, options, t) { + text(into, ': '); + renderType(into, typeInfo, options, t); +} +function renderEnumValue(into, typeInfo, options) { + if (!typeInfo.enumValue) { + return; } - function useTrackedPointer() { - let lastPos = (0, import_react18.useRef)([-1, -1]); - return { - wasMoved(evt) { - if (false) {} - let newPos = eventToPosition(evt); - if (lastPos.current[0] === newPos[0] && lastPos.current[1] === newPos[1]) { - return false; - } - lastPos.current = newPos; - return true; - }, - update(evt) { - lastPos.current = eventToPosition(evt); - } - }; + const { + name + } = typeInfo.enumValue; + renderType(into, typeInfo, options, typeInfo.inputType); + text(into, '.'); + text(into, name); +} +function renderType(into, typeInfo, options, t) { + if (!t) { + return; } - - // src/utils/platform.ts - function isIOS() { - return ( - // Check if it is an iPhone - /iPhone/gi.test(window.navigator.platform) || // Check if it is an iPad. iPad reports itself as "MacIntel", but we can check if it is a touch - // screen. Let's hope that Apple doesn't release a touch screen Mac (or maybe this would then - // work as expected 🤔). - /Mac/gi.test(window.navigator.platform) && window.navigator.maxTouchPoints > 0 - ); + if (t instanceof _graphql.GraphQLNonNull) { + renderType(into, typeInfo, options, t.ofType); + text(into, '!'); + } else if (t instanceof _graphql.GraphQLList) { + text(into, '['); + renderType(into, typeInfo, options, t.ofType); + text(into, ']'); + } else { + text(into, t.name); + } +} +function renderDescription(into, options, def) { + if (!def) { + return; + } + const description = typeof def.description === 'string' ? def.description : null; + if (description) { + text(into, '\n\n'); + text(into, description); } - function isAndroid() { - return /Android/gi.test(window.navigator.userAgent); + renderDeprecation(into, options, def); +} +function renderDeprecation(into, _options, def) { + if (!def) { + return; } - function isMobile() { - return isIOS() || isAndroid(); + const reason = def.deprecationReason || null; + if (!reason) { + return; } - - // src/components/combobox/combobox.tsx - function adjustOrderedState(state, adjustment = (i) => i) { - let currentActiveOption = state.activeOptionIndex !== null ? state.options[state.activeOptionIndex] : null; - let sortedOptions = sortByDomNode( - adjustment(state.options.slice()), - (option) => option.dataRef.current.domRef.current - ); - let adjustedActiveOptionIndex = currentActiveOption ? sortedOptions.indexOf(currentActiveOption) : null; - if (adjustedActiveOptionIndex === -1) { - adjustedActiveOptionIndex = null; + text(into, '\n\n'); + text(into, 'Deprecated: '); + text(into, reason); +} +function text(into, content) { + into.push(content); +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/getOutline.js": +/*!******************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/getOutline.js ***! + \******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getOutline = getOutline; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _utils = __webpack_require__(/*! ../utils */ "../../graphql-language-service/esm/utils/index.js"); +const { + INLINE_FRAGMENT +} = _graphql.Kind; +const OUTLINEABLE_KINDS = { + Field: true, + OperationDefinition: true, + Document: true, + SelectionSet: true, + Name: true, + FragmentDefinition: true, + FragmentSpread: true, + InlineFragment: true, + ObjectTypeDefinition: true, + InputObjectTypeDefinition: true, + InterfaceTypeDefinition: true, + EnumTypeDefinition: true, + EnumValueDefinition: true, + InputValueDefinition: true, + FieldDefinition: true +}; +function getOutline(documentText) { + let ast; + try { + ast = (0, _graphql.parse)(documentText); + } catch (_a) { + return null; + } + const visitorFns = outlineTreeConverter(documentText); + const outlineTrees = (0, _graphql.visit)(ast, { + leave(node) { + if (visitorFns !== undefined && node.kind in visitorFns) { + return visitorFns[node.kind](node); + } + return null; } + }); + return { + outlineTrees + }; +} +function outlineTreeConverter(docText) { + const meta = node => { return { - options: sortedOptions, - activeOptionIndex: adjustedActiveOptionIndex + representativeName: node.name, + startPosition: (0, _utils.offsetToPosition)(docText, node.loc.start), + endPosition: (0, _utils.offsetToPosition)(docText, node.loc.end), + kind: node.kind, + children: node.selectionSet || node.fields || node.values || node.arguments || [] }; - } - var reducers = { - [1 /* CloseCombobox */](state) { - var _a3; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (state.comboboxState === 1 /* Closed */) - return state; - return { ...state, activeOptionIndex: null, comboboxState: 1 /* Closed */ }; + }; + return { + Field(node) { + const tokenizedText = node.alias ? [buildToken('plain', node.alias), buildToken('plain', ': ')] : []; + tokenizedText.push(buildToken('plain', node.name)); + return Object.assign({ + tokenizedText + }, meta(node)); }, - [0 /* OpenCombobox */](state) { - var _a3; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (state.comboboxState === 0 /* Open */) - return state; - let activeOptionIndex = state.activeOptionIndex; - if (state.dataRef.current) { - let { isSelected } = state.dataRef.current; - let optionIdx = state.options.findIndex((option) => isSelected(option.dataRef.current.value)); - if (optionIdx !== -1) { - activeOptionIndex = optionIdx; - } - } - return { ...state, comboboxState: 0 /* Open */, activeOptionIndex }; + OperationDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', node.operation), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + Document: node => node.definitions, + SelectionSet: node => concatMap(node.selections, child => { + return child.kind === INLINE_FRAGMENT ? child.selectionSet : child; + }), + Name: node => node.value, + FragmentDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'fragment'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + InterfaceTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'interface'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + EnumTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'enum'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + EnumValueDefinition: node => Object.assign({ + tokenizedText: [buildToken('plain', node.name)] + }, meta(node)), + ObjectTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'type'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + InputObjectTypeDefinition: node => Object.assign({ + tokenizedText: [buildToken('keyword', 'input'), buildToken('whitespace', ' '), buildToken('class-name', node.name)] + }, meta(node)), + FragmentSpread: node => Object.assign({ + tokenizedText: [buildToken('plain', '...'), buildToken('class-name', node.name)] + }, meta(node)), + InputValueDefinition(node) { + return Object.assign({ + tokenizedText: [buildToken('plain', node.name)] + }, meta(node)); }, - [2 /* GoToOption */](state, action) { - var _a3, _b, _c, _d; - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) - return state; - if (((_b = state.dataRef.current) == null ? void 0 : _b.optionsRef.current) && !((_c = state.dataRef.current) == null ? void 0 : _c.optionsPropsRef.current.static) && state.comboboxState === 1 /* Closed */) { - return state; - } - let adjustedState = adjustOrderedState(state); - if (adjustedState.activeOptionIndex === null) { - let localActiveOptionIndex = adjustedState.options.findIndex( - (option) => !option.dataRef.current.disabled - ); - if (localActiveOptionIndex !== -1) { - adjustedState.activeOptionIndex = localActiveOptionIndex; - } - } - let activeOptionIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.options, - resolveActiveIndex: () => adjustedState.activeOptionIndex, - resolveId: (item) => item.id, - resolveDisabled: (item) => item.dataRef.current.disabled - }); - return { - ...state, - ...adjustedState, - activeOptionIndex, - activationTrigger: (_d = action.trigger) != null ? _d : 1 /* Other */ - }; + FieldDefinition(node) { + return Object.assign({ + tokenizedText: [buildToken('plain', node.name)] + }, meta(node)); }, - [3 /* RegisterOption */]: (state, action) => { - var _a3, _b; - let option = { id: action.id, dataRef: action.dataRef }; - let adjustedState = adjustOrderedState(state, (options) => [...options, option]); - if (state.activeOptionIndex === null) { - if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.isSelected(action.dataRef.current.value)) { - adjustedState.activeOptionIndex = adjustedState.options.indexOf(option); + InlineFragment: node => node.selectionSet + }; +} +function buildToken(kind, value) { + return { + kind, + value + }; +} +function concatMap(arr, fn) { + const res = []; + for (let i = 0; i < arr.length; i++) { + const x = fn(arr[i], i); + if (Array.isArray(x)) { + res.push(...x); + } else { + res.push(x); + } + } + return res; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/interface/index.js": +/*!*************************************************************!*\ + !*** ../../graphql-language-service/esm/interface/index.js ***! + \*************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + getOutline: true, + getHoverInformation: true +}; +Object.defineProperty(exports, "getHoverInformation", ({ + enumerable: true, + get: function () { + return _getHoverInformation.getHoverInformation; + } +})); +Object.defineProperty(exports, "getOutline", ({ + enumerable: true, + get: function () { + return _getOutline.getOutline; + } +})); +var _autocompleteUtils = __webpack_require__(/*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js"); +Object.keys(_autocompleteUtils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _autocompleteUtils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _autocompleteUtils[key]; + } + }); +}); +var _getAutocompleteSuggestions = __webpack_require__(/*! ./getAutocompleteSuggestions */ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js"); +Object.keys(_getAutocompleteSuggestions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getAutocompleteSuggestions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getAutocompleteSuggestions[key]; + } + }); +}); +var _getDefinition = __webpack_require__(/*! ./getDefinition */ "../../graphql-language-service/esm/interface/getDefinition.js"); +Object.keys(_getDefinition).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getDefinition[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getDefinition[key]; + } + }); +}); +var _getDiagnostics = __webpack_require__(/*! ./getDiagnostics */ "../../graphql-language-service/esm/interface/getDiagnostics.js"); +Object.keys(_getDiagnostics).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _getDiagnostics[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _getDiagnostics[key]; + } + }); +}); +var _getOutline = __webpack_require__(/*! ./getOutline */ "../../graphql-language-service/esm/interface/getOutline.js"); +var _getHoverInformation = __webpack_require__(/*! ./getHoverInformation */ "../../graphql-language-service/esm/interface/getHoverInformation.js"); + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/CharacterStream.js": +/*!********************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/CharacterStream.js ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +class CharacterStream { + constructor(sourceText) { + this._start = 0; + this._pos = 0; + this.getStartOfToken = () => this._start; + this.getCurrentPosition = () => this._pos; + this.eol = () => this._sourceText.length === this._pos; + this.sol = () => this._pos === 0; + this.peek = () => { + return this._sourceText.charAt(this._pos) || null; + }; + this.next = () => { + const char = this._sourceText.charAt(this._pos); + this._pos++; + return char; + }; + this.eat = pattern => { + const isMatched = this._testNextCharacter(pattern); + if (isMatched) { + this._start = this._pos; + this._pos++; + return this._sourceText.charAt(this._pos - 1); + } + return undefined; + }; + this.eatWhile = match => { + let isMatched = this._testNextCharacter(match); + let didEat = false; + if (isMatched) { + didEat = isMatched; + this._start = this._pos; + } + while (isMatched) { + this._pos++; + isMatched = this._testNextCharacter(match); + didEat = true; + } + return didEat; + }; + this.eatSpace = () => this.eatWhile(/[\s\u00a0]/); + this.skipToEnd = () => { + this._pos = this._sourceText.length; + }; + this.skipTo = position => { + this._pos = position; + }; + this.match = (pattern, consume = true, caseFold = false) => { + let token = null; + let match = null; + if (typeof pattern === 'string') { + const regex = new RegExp(pattern, caseFold ? 'i' : 'g'); + match = regex.test(this._sourceText.slice(this._pos, this._pos + pattern.length)); + token = pattern; + } else if (pattern instanceof RegExp) { + match = this._sourceText.slice(this._pos).match(pattern); + token = match === null || match === void 0 ? void 0 : match[0]; + } + if (match != null && (typeof pattern === 'string' || match instanceof Array && this._sourceText.startsWith(match[0], this._pos))) { + if (consume) { + this._start = this._pos; + if (token && token.length) { + this._pos += token.length; + } } + return match; } - let nextState = { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; - if (((_b = state.dataRef.current) == null ? void 0 : _b.__demoMode) && state.dataRef.current.value === void 0) { - nextState.activeOptionIndex = 0; + return false; + }; + this.backUp = num => { + this._pos -= num; + }; + this.column = () => this._pos; + this.indentation = () => { + const match = this._sourceText.match(/\s*/); + let indent = 0; + if (match && match.length !== 0) { + const whiteSpaces = match[0]; + let pos = 0; + while (whiteSpaces.length > pos) { + if (whiteSpaces.charCodeAt(pos) === 9) { + indent += 2; + } else { + indent++; + } + pos++; + } } - return nextState; - }, - [4 /* UnregisterOption */]: (state, action) => { - let adjustedState = adjustOrderedState(state, (options) => { - let idx = options.findIndex((a) => a.id === action.id); - if (idx !== -1) - options.splice(idx, 1); - return options; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; - }, - [5 /* RegisterLabel */]: (state, action) => { - return { - ...state, - labelId: action.id - }; + return indent; + }; + this.current = () => this._sourceText.slice(this._start, this._pos); + this._sourceText = sourceText; + } + _testNextCharacter(pattern) { + const character = this._sourceText.charAt(this._pos); + let isMatched = false; + if (typeof pattern === 'string') { + isMatched = character === pattern; + } else { + isMatched = pattern instanceof RegExp ? pattern.test(character) : pattern(character); } + return isMatched; + } +} +exports["default"] = CharacterStream; + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/RuleHelpers.js": +/*!****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/RuleHelpers.js ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.butNot = butNot; +exports.list = list; +exports.opt = opt; +exports.p = p; +exports.t = t; +function opt(ofRule) { + return { + ofRule }; - var ComboboxActionsContext = (0, import_react19.createContext)(null); - ComboboxActionsContext.displayName = "ComboboxActionsContext"; - function useActions(component) { - let context = (0, import_react19.useContext)(ComboboxActionsContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useActions); - throw err; - } - return context; - } - var ComboboxDataContext = (0, import_react19.createContext)(null); - ComboboxDataContext.displayName = "ComboboxDataContext"; - function useData(component) { - let context = (0, import_react19.useContext)(ComboboxDataContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useData); - throw err; - } - return context; - } - function stateReducer(state, action) { - return match(action.type, reducers, state, action); - } - var DEFAULT_COMBOBOX_TAG = import_react19.Fragment; - function ComboboxFn(props, ref) { - let { - value: controlledValue, - defaultValue, - onChange: controlledOnChange, - form: formName, - name, - by = (a, z) => a === z, - disabled = false, - __demoMode = false, - nullable = false, - multiple = false, - ...theirProps - } = props; - let [value = multiple ? [] : void 0, theirOnChange] = useControllable( - controlledValue, - controlledOnChange, - defaultValue - ); - let [state, dispatch] = (0, import_react19.useReducer)(stateReducer, { - dataRef: (0, import_react19.createRef)(), - comboboxState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - options: [], - activeOptionIndex: null, - activationTrigger: 1 /* Other */, - labelId: null - }); - let defaultToFirstOption = (0, import_react19.useRef)(false); - let optionsPropsRef = (0, import_react19.useRef)({ static: false, hold: false }); - let labelRef = (0, import_react19.useRef)(null); - let inputRef = (0, import_react19.useRef)(null); - let buttonRef = (0, import_react19.useRef)(null); - let optionsRef = (0, import_react19.useRef)(null); - let compare = useEvent( - // @ts-expect-error Eventually we'll want to tackle this, but for now this will do. - typeof by === "string" ? (a, z) => { - let property = by; - return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]); - } : by - ); - let isSelected = (0, import_react19.useCallback)( - (compareValue) => match(data.mode, { - [1 /* Multi */]: () => value.some((option) => compare(option, compareValue)), - [0 /* Single */]: () => compare(value, compareValue) - }), - [value] - ); - let data = (0, import_react19.useMemo)( - () => ({ - ...state, - optionsPropsRef, - labelRef, - inputRef, - buttonRef, - optionsRef, - value, - defaultValue, - disabled, - mode: multiple ? 1 /* Multi */ : 0 /* Single */, - get activeOptionIndex() { - if (defaultToFirstOption.current && state.activeOptionIndex === null && state.options.length > 0) { - let localActiveOptionIndex = state.options.findIndex( - (option) => !option.dataRef.current.disabled - ); - if (localActiveOptionIndex !== -1) { - return localActiveOptionIndex; - } - } - return state.activeOptionIndex; - }, - compare, - isSelected, - nullable, - __demoMode - }), - [value, defaultValue, disabled, multiple, nullable, __demoMode, state] - ); - let lastActiveOption = (0, import_react19.useRef)( - data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null - ); - (0, import_react19.useEffect)(() => { - let currentActiveOption = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null; - if (lastActiveOption.current !== currentActiveOption) { - lastActiveOption.current = currentActiveOption; - } - }); - useIsoMorphicEffect(() => { - state.dataRef.current = data; - }, [data]); - useOutsideClick( - [data.buttonRef, data.inputRef, data.optionsRef], - () => actions.closeCombobox(), - data.comboboxState === 0 /* Open */ - ); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled, - activeIndex: data.activeOptionIndex, - activeOption: data.activeOptionIndex === null ? null : data.options[data.activeOptionIndex].dataRef.current.value, - value - }), - [data, disabled, value] - ); - let selectOption = useEvent((id) => { - let option = data.options.find((item) => item.id === id); - if (!option) - return; - onChange(option.dataRef.current.value); - }); - let selectActiveOption = useEvent(() => { - if (data.activeOptionIndex !== null) { - let { dataRef, id } = data.options[data.activeOptionIndex]; - onChange(dataRef.current.value); - actions.goToOption(4 /* Specific */, id); +} +function list(ofRule, separator) { + return { + ofRule, + isList: true, + separator + }; +} +function butNot(rule, exclusions) { + const ruleMatch = rule.match; + rule.match = token => { + let check = false; + if (ruleMatch) { + check = ruleMatch(token); + } + return check && exclusions.every(exclusion => exclusion.match && !exclusion.match(token)); + }; + return rule; +} +function t(kind, style) { + return { + style, + match: token => token.kind === kind + }; +} +function p(value, style) { + return { + style: style || 'punctuation', + match: token => token.kind === 'Punctuation' && token.value === value + }; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/Rules.js": +/*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/Rules.js ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isIgnored = exports.ParseRules = exports.LexRules = void 0; +var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const isIgnored = ch => ch === ' ' || ch === '\t' || ch === ',' || ch === '\n' || ch === '\r' || ch === '\uFEFF' || ch === '\u00A0'; +exports.isIgnored = isIgnored; +const LexRules = exports.LexRules = { + Name: /^[_A-Za-z][_0-9A-Za-z]*/, + Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|&|@|\[|]|\{|\||\})/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/, + Comment: /^#.*/ +}; +const ParseRules = exports.ParseRules = { + Document: [(0, _RuleHelpers.list)('Definition')], + Definition(token) { + switch (token.value) { + case '{': + return 'ShortQuery'; + case 'query': + return 'Query'; + case 'mutation': + return 'Mutation'; + case 'subscription': + return 'Subscription'; + case 'fragment': + return _graphql.Kind.FRAGMENT_DEFINITION; + case 'schema': + return 'SchemaDef'; + case 'scalar': + return 'ScalarDef'; + case 'type': + return 'ObjectTypeDef'; + case 'interface': + return 'InterfaceDef'; + case 'union': + return 'UnionDef'; + case 'enum': + return 'EnumDef'; + case 'input': + return 'InputDef'; + case 'extend': + return 'ExtendDef'; + case 'directive': + return 'DirectiveDef'; + } + }, + ShortQuery: ['SelectionSet'], + Query: [word('query'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + Mutation: [word('mutation'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + Subscription: [word('subscription'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + VariableDefinitions: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('VariableDefinition'), (0, _RuleHelpers.p)(')')], + VariableDefinition: ['Variable', (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue')], + Variable: [(0, _RuleHelpers.p)('$', 'variable'), name('variable')], + DefaultValue: [(0, _RuleHelpers.p)('='), 'Value'], + SelectionSet: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Selection'), (0, _RuleHelpers.p)('}')], + Selection(token, stream) { + return token.value === '...' ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field'; + }, + AliasedField: [name('property'), (0, _RuleHelpers.p)(':'), name('qualifier'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], + Field: [name('property'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')], + Arguments: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('Argument'), (0, _RuleHelpers.p)(')')], + Argument: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], + FragmentSpread: [(0, _RuleHelpers.p)('...'), name('def'), (0, _RuleHelpers.list)('Directive')], + InlineFragment: [(0, _RuleHelpers.p)('...'), (0, _RuleHelpers.opt)('TypeCondition'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + FragmentDefinition: [word('fragment'), (0, _RuleHelpers.opt)((0, _RuleHelpers.butNot)(name('def'), [word('on')])), 'TypeCondition', (0, _RuleHelpers.list)('Directive'), 'SelectionSet'], + TypeCondition: [word('on'), 'NamedType'], + Value(token) { + switch (token.kind) { + case 'Number': + return 'NumberValue'; + case 'String': + return 'StringValue'; + case 'Punctuation': + switch (token.value) { + case '[': + return 'ListValue'; + case '{': + return 'ObjectValue'; + case '$': + return 'Variable'; + case '&': + return 'NamedType'; + } + return null; + case 'Name': + switch (token.value) { + case 'true': + case 'false': + return 'BooleanValue'; + } + if (token.value === 'null') { + return 'NullValue'; + } + return 'EnumValue'; + } + }, + NumberValue: [(0, _RuleHelpers.t)('Number', 'number')], + StringValue: [{ + style: 'string', + match: token => token.kind === 'String', + update(state, token) { + if (token.value.startsWith('"""')) { + state.inBlockstring = !token.value.slice(3).endsWith('"""'); + } + } + }], + BooleanValue: [(0, _RuleHelpers.t)('Name', 'builtin')], + NullValue: [(0, _RuleHelpers.t)('Name', 'keyword')], + EnumValue: [name('string-2')], + ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value'), (0, _RuleHelpers.p)(']')], + ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField'), (0, _RuleHelpers.p)('}')], + ObjectField: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'], + Type(token) { + return token.value === '[' ? 'ListType' : 'NonNullType'; + }, + ListType: [(0, _RuleHelpers.p)('['), 'Type', (0, _RuleHelpers.p)(']'), (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], + NonNullType: ['NamedType', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))], + NamedType: [type('atom')], + Directive: [(0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('Arguments')], + DirectiveDef: [word('directive'), (0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('ArgumentsDef'), word('on'), (0, _RuleHelpers.list)('DirectiveLocation', (0, _RuleHelpers.p)('|'))], + InterfaceDef: [word('interface'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], + Implements: [word('implements'), (0, _RuleHelpers.list)('NamedType', (0, _RuleHelpers.p)('&'))], + DirectiveLocation: [name('string-2')], + SchemaDef: [word('schema'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('OperationTypeDef'), (0, _RuleHelpers.p)('}')], + OperationTypeDef: [name('keyword'), (0, _RuleHelpers.p)(':'), name('atom')], + ScalarDef: [word('scalar'), name('atom'), (0, _RuleHelpers.list)('Directive')], + ObjectTypeDef: [word('type'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')], + FieldDef: [name('property'), (0, _RuleHelpers.opt)('ArgumentsDef'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.list)('Directive')], + ArgumentsDef: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)(')')], + InputValueDef: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue'), (0, _RuleHelpers.list)('Directive')], + UnionDef: [word('union'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('='), (0, _RuleHelpers.list)('UnionMember', (0, _RuleHelpers.p)('|'))], + UnionMember: ['NamedType'], + EnumDef: [word('enum'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('EnumValueDef'), (0, _RuleHelpers.p)('}')], + EnumValueDef: [name('string-2'), (0, _RuleHelpers.list)('Directive')], + InputDef: [word('input'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)('}')], + ExtendDef: [word('extend'), 'ExtensionDefinition'], + ExtensionDefinition(token) { + switch (token.value) { + case 'schema': + return _graphql.Kind.SCHEMA_EXTENSION; + case 'scalar': + return _graphql.Kind.SCALAR_TYPE_EXTENSION; + case 'type': + return _graphql.Kind.OBJECT_TYPE_EXTENSION; + case 'interface': + return _graphql.Kind.INTERFACE_TYPE_EXTENSION; + case 'union': + return _graphql.Kind.UNION_TYPE_EXTENSION; + case 'enum': + return _graphql.Kind.ENUM_TYPE_EXTENSION; + case 'input': + return _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + }, + [_graphql.Kind.SCHEMA_EXTENSION]: ['SchemaDef'], + [_graphql.Kind.SCALAR_TYPE_EXTENSION]: ['ScalarDef'], + [_graphql.Kind.OBJECT_TYPE_EXTENSION]: ['ObjectTypeDef'], + [_graphql.Kind.INTERFACE_TYPE_EXTENSION]: ['InterfaceDef'], + [_graphql.Kind.UNION_TYPE_EXTENSION]: ['UnionDef'], + [_graphql.Kind.ENUM_TYPE_EXTENSION]: ['EnumDef'], + [_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]: ['InputDef'] +}; +function word(value) { + return { + style: 'keyword', + match: token => token.kind === 'Name' && token.value === value + }; +} +function name(style) { + return { + style, + match: token => token.kind === 'Name', + update(state, token) { + state.name = token.value; + } + }; +} +function type(style) { + return { + style, + match: token => token.kind === 'Name', + update(state, token) { + var _a; + if ((_a = state.prevState) === null || _a === void 0 ? void 0 : _a.prevState) { + state.name = token.value; + state.prevState.prevState.type = token.value; } - }); - let openCombobox = useEvent(() => { - dispatch({ type: 0 /* OpenCombobox */ }); - defaultToFirstOption.current = true; - }); - let closeCombobox = useEvent(() => { - dispatch({ type: 1 /* CloseCombobox */ }); - defaultToFirstOption.current = false; - }); - let goToOption = useEvent((focus, id, trigger) => { - defaultToFirstOption.current = false; - if (focus === 4 /* Specific */) { - return dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id, trigger }); + } + }; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/api.js": +/*!********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/api.js ***! + \********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.TYPE_SYSTEM_KINDS = exports.GraphQLDocumentMode = void 0; +exports.getContextAtPosition = getContextAtPosition; +exports.getDocumentMode = getDocumentMode; +exports.getTokenAtPosition = getTokenAtPosition; +exports.runOnlineParser = runOnlineParser; +var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function runOnlineParser(queryText, callback) { + const lines = queryText.split('\n'); + const parser = (0, _.onlineParser)(); + let state = parser.startState(); + let style = ''; + let stream = new _.CharacterStream(''); + for (let i = 0; i < lines.length; i++) { + stream = new _.CharacterStream(lines[i]); + while (!stream.eol()) { + style = parser.token(stream, state); + const code = callback(stream, state, style, i); + if (code === 'BREAK') { + break; } - return dispatch({ type: 2 /* GoToOption */, focus, trigger }); - }); - let registerOption = useEvent((id, dataRef) => { - dispatch({ type: 3 /* RegisterOption */, id, dataRef }); - return () => { - var _a3; - if (((_a3 = lastActiveOption.current) == null ? void 0 : _a3.id) === id) { - defaultToFirstOption.current = true; - } - dispatch({ type: 4 /* UnregisterOption */, id }); - }; - }); - let registerLabel = useEvent((id) => { - dispatch({ type: 5 /* RegisterLabel */, id }); - return () => dispatch({ type: 5 /* RegisterLabel */, id: null }); - }); - let onChange = useEvent((value2) => { - return match(data.mode, { - [0 /* Single */]() { - return theirOnChange == null ? void 0 : theirOnChange(value2); - }, - [1 /* Multi */]() { - let copy = data.value.slice(); - let idx = copy.findIndex((item) => compare(item, value2)); - if (idx === -1) { - copy.push(value2); - } else { - copy.splice(idx, 1); + } + callback(stream, state, style, i); + if (!state.kind) { + state = parser.startState(); + } + } + return { + start: stream.getStartOfToken(), + end: stream.getCurrentPosition(), + string: stream.current(), + state, + style + }; +} +var GraphQLDocumentMode; +(function (GraphQLDocumentMode) { + GraphQLDocumentMode["TYPE_SYSTEM"] = "TYPE_SYSTEM"; + GraphQLDocumentMode["EXECUTABLE"] = "EXECUTABLE"; + GraphQLDocumentMode["UNKNOWN"] = "UNKNOWN"; +})(GraphQLDocumentMode || (exports.GraphQLDocumentMode = GraphQLDocumentMode = {})); +const TYPE_SYSTEM_KINDS = exports.TYPE_SYSTEM_KINDS = [_graphql.Kind.SCHEMA_DEFINITION, _graphql.Kind.OPERATION_TYPE_DEFINITION, _graphql.Kind.SCALAR_TYPE_DEFINITION, _graphql.Kind.OBJECT_TYPE_DEFINITION, _graphql.Kind.INTERFACE_TYPE_DEFINITION, _graphql.Kind.UNION_TYPE_DEFINITION, _graphql.Kind.ENUM_TYPE_DEFINITION, _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION, _graphql.Kind.DIRECTIVE_DEFINITION, _graphql.Kind.SCHEMA_EXTENSION, _graphql.Kind.SCALAR_TYPE_EXTENSION, _graphql.Kind.OBJECT_TYPE_EXTENSION, _graphql.Kind.INTERFACE_TYPE_EXTENSION, _graphql.Kind.UNION_TYPE_EXTENSION, _graphql.Kind.ENUM_TYPE_EXTENSION, _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]; +const getParsedMode = sdl => { + let mode = GraphQLDocumentMode.UNKNOWN; + if (sdl) { + try { + (0, _graphql.visit)((0, _graphql.parse)(sdl), { + enter(node) { + if (node.kind === 'Document') { + mode = GraphQLDocumentMode.EXECUTABLE; + return; + } + if (TYPE_SYSTEM_KINDS.includes(node.kind)) { + mode = GraphQLDocumentMode.TYPE_SYSTEM; + return _graphql.BREAK; } - return theirOnChange == null ? void 0 : theirOnChange(copy); + return false; } }); - }); - let actions = (0, import_react19.useMemo)( - () => ({ - onChange, - registerOption, - registerLabel, - goToOption, - closeCombobox, - openCombobox, - selectActiveOption, - selectOption - }), - [] - ); - let ourProps = ref === null ? {} : { ref }; - let form = (0, import_react19.useRef)(null); - let d = useDisposables(); - (0, import_react19.useEffect)(() => { - if (!form.current) - return; - if (defaultValue === void 0) - return; - d.addEventListener(form.current, "reset", () => { - onChange(defaultValue); - }); - }, [ - form, - onChange - /* Explicitly ignoring `defaultValue` */ - ]); - return /* @__PURE__ */ import_react19.default.createElement(ComboboxActionsContext.Provider, { value: actions }, /* @__PURE__ */ import_react19.default.createElement(ComboboxDataContext.Provider, { value: data }, /* @__PURE__ */ import_react19.default.createElement( - OpenClosedProvider, - { - value: match(data.comboboxState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - name != null && value != null && objectToFormEntries({ [name]: value }).map(([name2, value2], idx) => /* @__PURE__ */ import_react19.default.createElement( - Hidden, - { - features: 4 /* Hidden */, - ref: idx === 0 ? (element) => { - var _a3; - form.current = (_a3 = element == null ? void 0 : element.closest("form")) != null ? _a3 : null; - } : void 0, - ...compact({ - key: name2, - as: "input", - type: "hidden", - hidden: true, - readOnly: true, - form: formName, - name: name2, - value: value2 - }) - } - )), - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_COMBOBOX_TAG, - name: "Combobox" - }) - ))); + } catch (_a) { + return mode; + } + } + return mode; +}; +function getDocumentMode(documentText, uri) { + if (uri === null || uri === void 0 ? void 0 : uri.endsWith('.graphqls')) { + return GraphQLDocumentMode.TYPE_SYSTEM; + } + return getParsedMode(documentText); +} +function getTokenAtPosition(queryText, cursor, offset = 0) { + let styleAtCursor = null; + let stateAtCursor = null; + let stringAtCursor = null; + const token = runOnlineParser(queryText, (stream, state, style, index) => { + if (index !== cursor.line || stream.getCurrentPosition() + offset < cursor.character + 1) { + return; + } + styleAtCursor = style; + stateAtCursor = Object.assign({}, state); + stringAtCursor = stream.current(); + return 'BREAK'; + }); + return { + start: token.start, + end: token.end, + string: stringAtCursor || token.string, + state: stateAtCursor || token.state, + style: styleAtCursor || token.style + }; +} +function getContextAtPosition(queryText, cursor, schema, contextToken, options) { + const token = contextToken || getTokenAtPosition(queryText, cursor, 1); + if (!token) { + return null; } - var DEFAULT_INPUT_TAG = "input"; - function InputFn(props, ref) { - var _a3, _b, _c, _d; - let internalId = useId(); - let { - id = `headlessui-combobox-input-${internalId}`, - onChange, - displayValue, - // @ts-ignore: We know this MAY NOT exist for a given tag but we only care when it _does_ exist. - type = "text", - ...theirProps - } = props; - let data = useData("Combobox.Input"); - let actions = useActions("Combobox.Input"); - let inputRef = useSyncRefs(data.inputRef, ref); - let isTyping = (0, import_react19.useRef)(false); - let d = useDisposables(); - let currentDisplayValue = function() { - var _a4; - if (typeof displayValue === "function" && data.value !== void 0) { - return (_a4 = displayValue(data.value)) != null ? _a4 : ""; - } else if (typeof data.value === "string") { - return data.value; - } else { - return ""; - } - }(); - useWatch( - ([currentDisplayValue2, state], [oldCurrentDisplayValue, oldState]) => { - if (isTyping.current) - return; - if (!data.inputRef.current) - return; - if (oldState === 0 /* Open */ && state === 1 /* Closed */) { - data.inputRef.current.value = currentDisplayValue2; - } else if (currentDisplayValue2 !== oldCurrentDisplayValue) { - data.inputRef.current.value = currentDisplayValue2; + const state = token.state.kind === 'Invalid' ? token.state.prevState : token.state; + if (!state) { + return null; + } + const typeInfo = (0, _.getTypeInfo)(schema, token.state); + const mode = (options === null || options === void 0 ? void 0 : options.mode) || getDocumentMode(queryText, options === null || options === void 0 ? void 0 : options.uri); + return { + token, + state, + typeInfo, + mode + }; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/getTypeInfo.js": +/*!****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/getTypeInfo.js ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.forEachState = forEachState; +exports.getDefinitionState = getDefinitionState; +exports.getFieldDef = getFieldDef; +exports.getTypeInfo = getTypeInfo; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _ = __webpack_require__(/*! . */ "../../graphql-language-service/esm/parser/index.js"); +function getFieldDef(schema, type, fieldName) { + if (fieldName === _graphql.SchemaMetaFieldDef.name && schema.getQueryType() === type) { + return _graphql.SchemaMetaFieldDef; + } + if (fieldName === _graphql.TypeMetaFieldDef.name && schema.getQueryType() === type) { + return _graphql.TypeMetaFieldDef; + } + if (fieldName === _graphql.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) { + return _graphql.TypeNameMetaFieldDef; + } + if ('getFields' in type) { + return type.getFields()[fieldName]; + } + return null; +} +function forEachState(stack, fn) { + const reverseStateStack = []; + let state = stack; + while (state === null || state === void 0 ? void 0 : state.kind) { + reverseStateStack.push(state); + state = state.prevState; + } + for (let i = reverseStateStack.length - 1; i >= 0; i--) { + fn(reverseStateStack[i]); + } +} +function getDefinitionState(tokenState) { + let definitionState; + forEachState(tokenState, state => { + switch (state.kind) { + case 'Query': + case 'ShortQuery': + case 'Mutation': + case 'Subscription': + case 'FragmentDefinition': + definitionState = state; + break; + } + }); + return definitionState; +} +function getTypeInfo(schema, tokenState) { + let argDef; + let argDefs; + let directiveDef; + let enumValue; + let fieldDef; + let inputType; + let objectTypeDef; + let objectFieldDefs; + let parentType; + let type; + let interfaceDef; + forEachState(tokenState, state => { + var _a; + switch (state.kind) { + case _.RuleKinds.QUERY: + case 'ShortQuery': + type = schema.getQueryType(); + break; + case _.RuleKinds.MUTATION: + type = schema.getMutationType(); + break; + case _.RuleKinds.SUBSCRIPTION: + type = schema.getSubscriptionType(); + break; + case _.RuleKinds.INLINE_FRAGMENT: + case _.RuleKinds.FRAGMENT_DEFINITION: + if (state.type) { + type = schema.getType(state.type); } - }, - [currentDisplayValue, data.comboboxState] - ); - useWatch( - ([newState], [oldState]) => { - if (newState === 0 /* Open */ && oldState === 1 /* Closed */) { - let input = data.inputRef.current; - if (!input) - return; - let currentValue = input.value; - let { selectionStart, selectionEnd, selectionDirection } = input; - input.value = ""; - input.value = currentValue; - if (selectionDirection !== null) { - input.setSelectionRange(selectionStart, selectionEnd, selectionDirection); + break; + case _.RuleKinds.FIELD: + case _.RuleKinds.ALIASED_FIELD: + { + if (!type || !state.name) { + fieldDef = null; } else { - input.setSelectionRange(selectionStart, selectionEnd); + fieldDef = parentType ? getFieldDef(schema, parentType, state.name) : null; + type = fieldDef ? fieldDef.type : null; } + break; } - }, - [data.comboboxState] - ); - let isComposing = (0, import_react19.useRef)(false); - let composedChangeEvent = (0, import_react19.useRef)(null); - let handleCompositionStart = useEvent(() => { - isComposing.current = true; - }); - let handleCompositionEnd = useEvent(() => { - d.nextFrame(() => { - isComposing.current = false; - if (composedChangeEvent.current) { - actions.openCombobox(); - onChange == null ? void 0 : onChange(composedChangeEvent.current); - composedChangeEvent.current = null; - } - }); - }); - let handleKeyDown = useEvent((event) => { - isTyping.current = true; - switch (event.key) { - case "Backspace" /* Backspace */: - case "Delete" /* Delete */: - if (data.mode !== 0 /* Single */) - return; - if (!data.nullable) - return; - let input = event.currentTarget; - d.requestAnimationFrame(() => { - if (input.value === "") { - actions.onChange(null); - if (data.optionsRef.current) { - data.optionsRef.current.scrollTop = 0; - } - actions.goToOption(5 /* Nothing */); - } + case _.RuleKinds.SELECTION_SET: + parentType = (0, _graphql.getNamedType)(type); + break; + case _.RuleKinds.DIRECTIVE: + directiveDef = state.name ? schema.getDirective(state.name) : null; + break; + case _.RuleKinds.INTERFACE_DEF: + if (state.name) { + objectTypeDef = null; + interfaceDef = new _graphql.GraphQLInterfaceType({ + name: state.name, + interfaces: [], + fields: {} }); - break; - case "Enter" /* Enter */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) - return; - if (isComposing.current) - return; - event.preventDefault(); - event.stopPropagation(); - if (data.activeOptionIndex === null) { - actions.closeCombobox(); - return; - } - actions.selectActiveOption(); - if (data.mode === 0 /* Single */) { - actions.closeCombobox(); - } - break; - case "ArrowDown" /* ArrowDown */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return match(data.comboboxState, { - [0 /* Open */]: () => { - actions.goToOption(2 /* Next */); - }, - [1 /* Closed */]: () => { - actions.openCombobox(); - } + } + break; + case _.RuleKinds.OBJECT_TYPE_DEF: + if (state.name) { + interfaceDef = null; + objectTypeDef = new _graphql.GraphQLObjectType({ + name: state.name, + interfaces: [], + fields: {} }); - case "ArrowUp" /* ArrowUp */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return match(data.comboboxState, { - [0 /* Open */]: () => { - actions.goToOption(1 /* Previous */); - }, - [1 /* Closed */]: () => { - actions.openCombobox(); - d.nextFrame(() => { - if (!data.value) { - actions.goToOption(3 /* Last */); + } + break; + case _.RuleKinds.ARGUMENTS: + { + if (state.prevState) { + switch (state.prevState.kind) { + case _.RuleKinds.FIELD: + argDefs = fieldDef && fieldDef.args; + break; + case _.RuleKinds.DIRECTIVE: + argDefs = directiveDef && directiveDef.args; + break; + case _.RuleKinds.ALIASED_FIELD: + { + const name = (_a = state.prevState) === null || _a === void 0 ? void 0 : _a.name; + if (!name) { + argDefs = null; + break; + } + const field = parentType ? getFieldDef(schema, parentType, name) : null; + if (!field) { + argDefs = null; + break; + } + argDefs = field.args; + break; } - }); + default: + argDefs = null; + break; } - }); - case "Home" /* Home */: - if (event.shiftKey) { - break; - } - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "PageUp" /* PageUp */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "End" /* End */: - if (event.shiftKey) { - break; - } - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "PageDown" /* PageDown */: - isTyping.current = false; - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "Escape" /* Escape */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) - return; - event.preventDefault(); - if (data.optionsRef.current && !data.optionsPropsRef.current.static) { - event.stopPropagation(); + } else { + argDefs = null; } - return actions.closeCombobox(); - case "Tab" /* Tab */: - isTyping.current = false; - if (data.comboboxState !== 0 /* Open */) - return; - if (data.mode === 0 /* Single */) - actions.selectActiveOption(); - actions.closeCombobox(); break; + } + case _.RuleKinds.ARGUMENT: + if (argDefs) { + for (let i = 0; i < argDefs.length; i++) { + if (argDefs[i].name === state.name) { + argDef = argDefs[i]; + break; + } + } + } + inputType = argDef === null || argDef === void 0 ? void 0 : argDef.type; + break; + case _.RuleKinds.VARIABLE_DEFINITION: + case _.RuleKinds.VARIABLE: + type = inputType; + break; + case _.RuleKinds.ENUM_VALUE: + const enumType = (0, _graphql.getNamedType)(inputType); + enumValue = enumType instanceof _graphql.GraphQLEnumType ? enumType.getValues().find(val => val.value === state.name) : null; + break; + case _.RuleKinds.LIST_VALUE: + const nullableType = (0, _graphql.getNullableType)(inputType); + inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null; + break; + case _.RuleKinds.OBJECT_VALUE: + const objectType = (0, _graphql.getNamedType)(inputType); + objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null; + break; + case _.RuleKinds.OBJECT_FIELD: + const objectField = state.name && objectFieldDefs ? objectFieldDefs[state.name] : null; + inputType = objectField === null || objectField === void 0 ? void 0 : objectField.type; + fieldDef = objectField; + type = fieldDef ? fieldDef.type : null; + break; + case _.RuleKinds.NAMED_TYPE: + if (state.name) { + type = schema.getType(state.name); + } + break; + } + }); + return { + argDef, + argDefs, + directiveDef, + enumValue, + fieldDef, + inputType, + objectFieldDefs, + parentType, + type, + interfaceDef, + objectTypeDef + }; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/index.js": +/*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/index.js ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + CharacterStream: true, + LexRules: true, + ParseRules: true, + isIgnored: true, + butNot: true, + list: true, + opt: true, + p: true, + t: true, + onlineParser: true, + runOnlineParser: true, + getTokenAtPosition: true, + getContextAtPosition: true, + GraphQLDocumentMode: true, + getDocumentMode: true, + getTypeInfo: true, + getDefinitionState: true, + getFieldDef: true +}; +Object.defineProperty(exports, "CharacterStream", ({ + enumerable: true, + get: function () { + return _CharacterStream.default; + } +})); +Object.defineProperty(exports, "GraphQLDocumentMode", ({ + enumerable: true, + get: function () { + return _api.GraphQLDocumentMode; + } +})); +Object.defineProperty(exports, "LexRules", ({ + enumerable: true, + get: function () { + return _Rules.LexRules; + } +})); +Object.defineProperty(exports, "ParseRules", ({ + enumerable: true, + get: function () { + return _Rules.ParseRules; + } +})); +Object.defineProperty(exports, "butNot", ({ + enumerable: true, + get: function () { + return _RuleHelpers.butNot; + } +})); +Object.defineProperty(exports, "getContextAtPosition", ({ + enumerable: true, + get: function () { + return _api.getContextAtPosition; + } +})); +Object.defineProperty(exports, "getDefinitionState", ({ + enumerable: true, + get: function () { + return _getTypeInfo.getDefinitionState; + } +})); +Object.defineProperty(exports, "getDocumentMode", ({ + enumerable: true, + get: function () { + return _api.getDocumentMode; + } +})); +Object.defineProperty(exports, "getFieldDef", ({ + enumerable: true, + get: function () { + return _getTypeInfo.getFieldDef; + } +})); +Object.defineProperty(exports, "getTokenAtPosition", ({ + enumerable: true, + get: function () { + return _api.getTokenAtPosition; + } +})); +Object.defineProperty(exports, "getTypeInfo", ({ + enumerable: true, + get: function () { + return _getTypeInfo.getTypeInfo; + } +})); +Object.defineProperty(exports, "isIgnored", ({ + enumerable: true, + get: function () { + return _Rules.isIgnored; + } +})); +Object.defineProperty(exports, "list", ({ + enumerable: true, + get: function () { + return _RuleHelpers.list; + } +})); +Object.defineProperty(exports, "onlineParser", ({ + enumerable: true, + get: function () { + return _onlineParser.default; + } +})); +Object.defineProperty(exports, "opt", ({ + enumerable: true, + get: function () { + return _RuleHelpers.opt; + } +})); +Object.defineProperty(exports, "p", ({ + enumerable: true, + get: function () { + return _RuleHelpers.p; + } +})); +Object.defineProperty(exports, "runOnlineParser", ({ + enumerable: true, + get: function () { + return _api.runOnlineParser; + } +})); +Object.defineProperty(exports, "t", ({ + enumerable: true, + get: function () { + return _RuleHelpers.t; + } +})); +var _CharacterStream = _interopRequireDefault(__webpack_require__(/*! ./CharacterStream */ "../../graphql-language-service/esm/parser/CharacterStream.js")); +var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); +var _RuleHelpers = __webpack_require__(/*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js"); +var _onlineParser = _interopRequireDefault(__webpack_require__(/*! ./onlineParser */ "../../graphql-language-service/esm/parser/onlineParser.js")); +var _api = __webpack_require__(/*! ./api */ "../../graphql-language-service/esm/parser/api.js"); +var _getTypeInfo = __webpack_require__(/*! ./getTypeInfo */ "../../graphql-language-service/esm/parser/getTypeInfo.js"); +var _types = __webpack_require__(/*! ./types */ "../../graphql-language-service/esm/parser/types.js"); +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); +}); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/onlineParser.js": +/*!*****************************************************************!*\ + !*** ../../graphql-language-service/esm/parser/onlineParser.js ***! + \*****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = onlineParser; +var _Rules = __webpack_require__(/*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js"); +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function onlineParser(options = { + eatWhitespace: stream => stream.eatWhile(_Rules.isIgnored), + lexRules: _Rules.LexRules, + parseRules: _Rules.ParseRules, + editorConfig: {} +}) { + return { + startState() { + const initialState = { + level: 0, + step: 0, + name: null, + kind: null, + type: null, + rule: null, + needsSeparator: false, + prevState: null + }; + pushRule(options.parseRules, initialState, _graphql.Kind.DOCUMENT); + return initialState; + }, + token(stream, state) { + return getToken(stream, state, options); + } + }; +} +function getToken(stream, state, options) { + var _a; + if (state.inBlockstring) { + if (stream.match(/.*"""/)) { + state.inBlockstring = false; + return 'string'; + } + stream.skipToEnd(); + return 'string'; + } + const { + lexRules, + parseRules, + eatWhitespace, + editorConfig + } = options; + if (state.rule && state.rule.length === 0) { + popRule(state); + } else if (state.needsAdvance) { + state.needsAdvance = false; + advanceRule(state, true); + } + if (stream.sol()) { + const tabSize = (editorConfig === null || editorConfig === void 0 ? void 0 : editorConfig.tabSize) || 2; + state.indentLevel = Math.floor(stream.indentation() / tabSize); + } + if (eatWhitespace(stream)) { + return 'ws'; + } + const token = lex(lexRules, stream); + if (!token) { + const matchedSomething = stream.match(/\S+/); + if (!matchedSomething) { + stream.match(/\s/); + } + pushRule(SpecialParseRules, state, 'Invalid'); + return 'invalidchar'; + } + if (token.kind === 'Comment') { + pushRule(SpecialParseRules, state, 'Comment'); + return 'comment'; + } + const backupState = assign({}, state); + if (token.kind === 'Punctuation') { + if (/^[{([]/.test(token.value)) { + if (state.indentLevel !== undefined) { + state.levels = (state.levels || []).concat(state.indentLevel + 1); } - }); - let handleChange = useEvent((event) => { - if (isComposing.current) { - composedChangeEvent.current = event; - return; + } else if (/^[})\]]/.test(token.value)) { + const levels = state.levels = (state.levels || []).slice(0, -1); + if (state.indentLevel && levels.length > 0 && levels.at(-1) < state.indentLevel) { + state.indentLevel = levels.at(-1); } - actions.openCombobox(); - onChange == null ? void 0 : onChange(event); - }); - let handleBlur = useEvent(() => { - isTyping.current = false; - }); - let labelledby = useComputed(() => { - if (!data.labelId) - return void 0; - return [data.labelId].join(" "); - }, [data.labelId]); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */, disabled: data.disabled }), - [data] - ); - let ourProps = { - ref: inputRef, - id, - role: "combobox", - type, - "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled ? void 0 : data.comboboxState === 0 /* Open */, - "aria-activedescendant": data.activeOptionIndex === null ? void 0 : (_b = data.options[data.activeOptionIndex]) == null ? void 0 : _b.id, - "aria-labelledby": labelledby, - "aria-autocomplete": "list", - defaultValue: (_d = (_c = props.defaultValue) != null ? _c : data.defaultValue !== void 0 ? displayValue == null ? void 0 : displayValue(data.defaultValue) : null) != null ? _d : data.defaultValue, - disabled: data.disabled, - onCompositionStart: handleCompositionStart, - onCompositionEnd: handleCompositionEnd, - onKeyDown: handleKeyDown, - onChange: handleChange, - onBlur: handleBlur - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_INPUT_TAG, - name: "Combobox.Input" - }); + } } - var DEFAULT_BUTTON_TAG = "button"; - function ButtonFn(props, ref) { - var _a3; - let data = useData("Combobox.Button"); - let actions = useActions("Combobox.Button"); - let buttonRef = useSyncRefs(data.buttonRef, ref); - let internalId = useId(); - let { id = `headlessui-combobox-button-${internalId}`, ...theirProps } = props; - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - if (data.comboboxState === 1 /* Closed */) { - actions.openCombobox(); - } - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - if (data.comboboxState === 1 /* Closed */) { - actions.openCombobox(); - d.nextFrame(() => { - if (!data.value) { - actions.goToOption(3 /* Last */); - } - }); - } - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - case "Escape" /* Escape */: - if (data.comboboxState !== 0 /* Open */) - return; - event.preventDefault(); - if (data.optionsRef.current && !data.optionsPropsRef.current.static) { - event.stopPropagation(); - } - actions.closeCombobox(); - return d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - default: - return; + while (state.rule) { + let expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step]; + if (state.needsSeparator) { + expected = expected === null || expected === void 0 ? void 0 : expected.separator; + } + if (expected) { + if (expected.ofRule) { + expected = expected.ofRule; } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (data.comboboxState === 0 /* Open */) { - actions.closeCombobox(); + if (typeof expected === 'string') { + pushRule(parseRules, state, expected); + continue; + } + if ((_a = expected.match) === null || _a === void 0 ? void 0 : _a.call(expected, token)) { + if (expected.update) { + expected.update(state, token); + } + if (token.kind === 'Punctuation') { + advanceRule(state, true); + } else { + state.needsAdvance = true; + } + return expected.style; + } + } + unsuccessful(state); + } + assign(state, backupState); + pushRule(SpecialParseRules, state, 'Invalid'); + return 'invalidchar'; +} +function assign(to, from) { + const keys = Object.keys(from); + for (let i = 0; i < keys.length; i++) { + to[keys[i]] = from[keys[i]]; + } + return to; +} +const SpecialParseRules = { + Invalid: [], + Comment: [] +}; +function pushRule(rules, state, ruleKind) { + if (!rules[ruleKind]) { + throw new TypeError('Unknown rule: ' + ruleKind); + } + state.prevState = Object.assign({}, state); + state.kind = ruleKind; + state.name = null; + state.type = null; + state.rule = rules[ruleKind]; + state.step = 0; + state.needsSeparator = false; +} +function popRule(state) { + if (!state.prevState) { + return; + } + state.kind = state.prevState.kind; + state.name = state.prevState.name; + state.type = state.prevState.type; + state.rule = state.prevState.rule; + state.step = state.prevState.step; + state.needsSeparator = state.prevState.needsSeparator; + state.prevState = state.prevState.prevState; +} +function advanceRule(state, successful) { + var _a; + if (isList(state) && state.rule) { + const step = state.rule[state.step]; + if (step.separator) { + const { + separator + } = step; + state.needsSeparator = !state.needsSeparator; + if (!state.needsSeparator && separator.ofRule) { + return; + } + } + if (successful) { + return; + } + } + state.needsSeparator = false; + state.step++; + while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) { + popRule(state); + if (state.rule) { + if (isList(state)) { + if ((_a = state.rule) === null || _a === void 0 ? void 0 : _a[state.step].separator) { + state.needsSeparator = !state.needsSeparator; + } } else { - event.preventDefault(); - actions.openCombobox(); + state.needsSeparator = false; + state.step++; } - d.nextFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - }); - let labelledby = useComputed(() => { - if (!data.labelId) - return void 0; - return [data.labelId, id].join(" "); - }, [data.labelId, id]); - let slot = (0, import_react19.useMemo)( - () => ({ - open: data.comboboxState === 0 /* Open */, - disabled: data.disabled, - value: data.value - }), - [data] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, data.buttonRef), - tabIndex: -1, - "aria-haspopup": "listbox", - "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled ? void 0 : data.comboboxState === 0 /* Open */, - "aria-labelledby": labelledby, - disabled: data.disabled, - onClick: handleClick, - onKeyDown: handleKeyDown + } + } +} +function isList(state) { + const step = Array.isArray(state.rule) && typeof state.rule[state.step] !== 'string' && state.rule[state.step]; + return step && step.isList; +} +function unsuccessful(state) { + while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) { + popRule(state); + } + if (state.rule) { + advanceRule(state, false); + } +} +function lex(lexRules, stream) { + const kinds = Object.keys(lexRules); + for (let i = 0; i < kinds.length; i++) { + const match = stream.match(lexRules[kinds[i]]); + if (match && match instanceof Array) { + return { + kind: kinds[i], + value: match[0] + }; + } + } +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/parser/types.js": +/*!**********************************************************!*\ + !*** ../../graphql-language-service/esm/parser/types.js ***! + \**********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.RuleKinds = exports.AdditionalRuleKinds = void 0; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const AdditionalRuleKinds = exports.AdditionalRuleKinds = { + ALIASED_FIELD: 'AliasedField', + ARGUMENTS: 'Arguments', + SHORT_QUERY: 'ShortQuery', + QUERY: 'Query', + MUTATION: 'Mutation', + SUBSCRIPTION: 'Subscription', + TYPE_CONDITION: 'TypeCondition', + INVALID: 'Invalid', + COMMENT: 'Comment', + SCHEMA_DEF: 'SchemaDef', + SCALAR_DEF: 'ScalarDef', + OBJECT_TYPE_DEF: 'ObjectTypeDef', + OBJECT_VALUE: 'ObjectValue', + LIST_VALUE: 'ListValue', + INTERFACE_DEF: 'InterfaceDef', + UNION_DEF: 'UnionDef', + ENUM_DEF: 'EnumDef', + ENUM_VALUE: 'EnumValue', + FIELD_DEF: 'FieldDef', + INPUT_DEF: 'InputDef', + INPUT_VALUE_DEF: 'InputValueDef', + ARGUMENTS_DEF: 'ArgumentsDef', + EXTEND_DEF: 'ExtendDef', + EXTENSION_DEFINITION: 'ExtensionDefinition', + DIRECTIVE_DEF: 'DirectiveDef', + IMPLEMENTS: 'Implements', + VARIABLE_DEFINITIONS: 'VariableDefinitions', + TYPE: 'Type', + VARIABLE: 'Variable' +}; +const RuleKinds = exports.RuleKinds = Object.assign(Object.assign({}, _graphql.Kind), AdditionalRuleKinds); + +/***/ }), + +/***/ "../../graphql-language-service/esm/types.js": +/*!***************************************************!*\ + !*** ../../graphql-language-service/esm/types.js ***! + \***************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.FileChangeTypeKind = exports.CompletionItemKind = void 0; +Object.defineProperty(exports, "GraphQLDocumentMode", ({ + enumerable: true, + get: function () { + return _parser.GraphQLDocumentMode; + } +})); +Object.defineProperty(exports, "InsertTextFormat", ({ + enumerable: true, + get: function () { + return _vscodeLanguageserverTypes.InsertTextFormat; + } +})); +var _vscodeLanguageserverTypes = __webpack_require__(/*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js"); +var _parser = __webpack_require__(/*! ./parser */ "../../graphql-language-service/esm/parser/index.js"); +const FileChangeTypeKind = exports.FileChangeTypeKind = { + Created: 1, + Changed: 2, + Deleted: 3 +}; +var CompletionItemKind; +(function (CompletionItemKind) { + CompletionItemKind.Text = 1; + CompletionItemKind.Method = 2; + CompletionItemKind.Function = 3; + CompletionItemKind.Constructor = 4; + CompletionItemKind.Field = 5; + CompletionItemKind.Variable = 6; + CompletionItemKind.Class = 7; + CompletionItemKind.Interface = 8; + CompletionItemKind.Module = 9; + CompletionItemKind.Property = 10; + CompletionItemKind.Unit = 11; + CompletionItemKind.Value = 12; + CompletionItemKind.Enum = 13; + CompletionItemKind.Keyword = 14; + CompletionItemKind.Snippet = 15; + CompletionItemKind.Color = 16; + CompletionItemKind.File = 17; + CompletionItemKind.Reference = 18; + CompletionItemKind.Folder = 19; + CompletionItemKind.EnumMember = 20; + CompletionItemKind.Constant = 21; + CompletionItemKind.Struct = 22; + CompletionItemKind.Event = 23; + CompletionItemKind.Operator = 24; + CompletionItemKind.TypeParameter = 25; +})(CompletionItemKind || (exports.CompletionItemKind = CompletionItemKind = {})); + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/Range.js": +/*!*********************************************************!*\ + !*** ../../graphql-language-service/esm/utils/Range.js ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Range = exports.Position = void 0; +exports.locToRange = locToRange; +exports.offsetToPosition = offsetToPosition; +class Range { + constructor(start, end) { + this.containsPosition = position => { + if (this.start.line === position.line) { + return this.start.character <= position.character; + } + if (this.end.line === position.line) { + return this.end.character >= position.character; + } + return this.start.line <= position.line && this.end.line >= position.line; }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG, - name: "Combobox.Button" - }); + this.start = start; + this.end = end; + } + setStart(line, character) { + this.start = new Position(line, character); + } + setEnd(line, character) { + this.end = new Position(line, character); + } +} +exports.Range = Range; +class Position { + constructor(line, character) { + this.lessThanOrEqualTo = position => this.line < position.line || this.line === position.line && this.character <= position.character; + this.line = line; + this.character = character; + } + setLine(line) { + this.line = line; + } + setCharacter(character) { + this.character = character; + } +} +exports.Position = Position; +function offsetToPosition(text, loc) { + const EOL = '\n'; + const buf = text.slice(0, loc); + const lines = buf.split(EOL).length - 1; + const lastLineIndex = buf.lastIndexOf(EOL); + return new Position(lines, loc - lastLineIndex - 1); +} +function locToRange(text, loc) { + const start = offsetToPosition(text, loc.start); + const end = offsetToPosition(text, loc.end); + return new Range(start, end); +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/collectVariables.js": +/*!********************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/collectVariables.js ***! + \********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.collectVariables = collectVariables; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function collectVariables(schema, documentAST) { + const variableToType = Object.create(null); + for (const definition of documentAST.definitions) { + if (definition.kind === 'OperationDefinition') { + const { + variableDefinitions + } = definition; + if (variableDefinitions) { + for (const { + variable, + type + } of variableDefinitions) { + const inputType = (0, _graphql.typeFromAST)(schema, type); + if (inputType) { + variableToType[variable.name.value] = inputType; + } else if (type.kind === _graphql.Kind.NAMED_TYPE && type.name.value === 'Float') { + variableToType[variable.name.value] = _graphql.GraphQLFloat; + } + } + } + } } - var DEFAULT_LABEL_TAG = "label"; - function LabelFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-combobox-label-${internalId}`, ...theirProps } = props; - let data = useData("Combobox.Label"); - let actions = useActions("Combobox.Label"); - let labelRef = useSyncRefs(data.labelRef, ref); - useIsoMorphicEffect(() => actions.registerLabel(id), [id]); - let handleClick = useEvent(() => { - var _a3; - return (_a3 = data.inputRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); - }); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */, disabled: data.disabled }), - [data] - ); - let ourProps = { ref: labelRef, id, onClick: handleClick }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_LABEL_TAG, - name: "Combobox.Label" - }); + return variableToType; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/fragmentDependencies.js": +/*!************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/fragmentDependencies.js ***! + \************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getFragmentDependenciesForAST = exports.getFragmentDependencies = void 0; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _nullthrows = _interopRequireDefault(__webpack_require__(/*! nullthrows */ "../../../node_modules/nullthrows/nullthrows.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const getFragmentDependencies = (operationString, fragmentDefinitions) => { + if (!fragmentDefinitions) { + return []; + } + let parsedOperation; + try { + parsedOperation = (0, _graphql.parse)(operationString); + } catch (_a) { + return []; } - var DEFAULT_OPTIONS_TAG = "ul"; - var OptionsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; - function OptionsFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-combobox-options-${internalId}`, hold = false, ...theirProps } = props; - let data = useData("Combobox.Options"); - let optionsRef = useSyncRefs(data.optionsRef, ref); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return data.comboboxState === 0 /* Open */; - })(); - useIsoMorphicEffect(() => { - var _a3; - data.optionsPropsRef.current.static = (_a3 = props.static) != null ? _a3 : false; - }, [data.optionsPropsRef, props.static]); - useIsoMorphicEffect(() => { - data.optionsPropsRef.current.hold = hold; - }, [data.optionsPropsRef, hold]); - useTreeWalker({ - container: data.optionsRef.current, - enabled: data.comboboxState === 0 /* Open */, - accept(node) { - if (node.getAttribute("role") === "option") - return NodeFilter.FILTER_REJECT; - if (node.hasAttribute("role")) - return NodeFilter.FILTER_SKIP; - return NodeFilter.FILTER_ACCEPT; - }, - walk(node) { - node.setAttribute("role", "none"); - } - }); - let labelledby = useComputed( - () => { - var _a3, _b; - return (_b = data.labelId) != null ? _b : (_a3 = data.buttonRef.current) == null ? void 0 : _a3.id; - }, - [data.labelId, data.buttonRef.current] - ); - let slot = (0, import_react19.useMemo)( - () => ({ open: data.comboboxState === 0 /* Open */ }), - [data] - ); - let ourProps = { - "aria-labelledby": labelledby, - role: "listbox", - "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, - id, - ref: optionsRef - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTIONS_TAG, - features: OptionsRenderFeatures, - visible, - name: "Combobox.Options" - }); + return getFragmentDependenciesForAST(parsedOperation, fragmentDefinitions); +}; +exports.getFragmentDependencies = getFragmentDependencies; +const getFragmentDependenciesForAST = (parsedOperation, fragmentDefinitions) => { + if (!fragmentDefinitions) { + return []; } - var DEFAULT_OPTION_TAG = "li"; - function OptionFn(props, ref) { - var _a3, _b; - let internalId = useId(); - let { - id = `headlessui-combobox-option-${internalId}`, - disabled = false, - value, - ...theirProps - } = props; - let data = useData("Combobox.Option"); - let actions = useActions("Combobox.Option"); - let active = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex].id === id : false; - let selected = data.isSelected(value); - let internalOptionRef = (0, import_react19.useRef)(null); - let bag = useLatestValue({ - disabled, - value, - domRef: internalOptionRef, - textValue: (_b = (_a3 = internalOptionRef.current) == null ? void 0 : _a3.textContent) == null ? void 0 : _b.toLowerCase() - }); - let optionRef = useSyncRefs(ref, internalOptionRef); - let select = useEvent(() => actions.selectOption(id)); - useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); - let enableScrollIntoView = (0, import_react19.useRef)(data.__demoMode ? false : true); - useIsoMorphicEffect(() => { - if (!data.__demoMode) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - enableScrollIntoView.current = true; - }); - return d.dispose; - }, []); - useIsoMorphicEffect(() => { - if (data.comboboxState !== 0 /* Open */) - return; - if (!active) - return; - if (!enableScrollIntoView.current) - return; - if (data.activationTrigger === 0 /* Pointer */) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a4, _b2; - (_b2 = (_a4 = internalOptionRef.current) == null ? void 0 : _a4.scrollIntoView) == null ? void 0 : _b2.call(_a4, { block: "nearest" }); - }); - return d.dispose; - }, [ - internalOptionRef, - active, - data.comboboxState, - data.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - data.activeOptionIndex - ]); - let handleClick = useEvent((event) => { - if (disabled) - return event.preventDefault(); - select(); - if (data.mode === 0 /* Single */) { - actions.closeCombobox(); - } - if (!isMobile()) { - requestAnimationFrame(() => { - var _a4; - return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus(); - }); + const existingFrags = new Map(); + const referencedFragNames = new Set(); + (0, _graphql.visit)(parsedOperation, { + FragmentDefinition(node) { + existingFrags.set(node.name.value, true); + }, + FragmentSpread(node) { + if (!referencedFragNames.has(node.name.value)) { + referencedFragNames.add(node.name.value); } - }); - let handleFocus = useEvent(() => { - if (disabled) - return actions.goToOption(5 /* Nothing */); - actions.goToOption(4 /* Specific */, id); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (active) - return; - actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (!active) - return; - if (data.optionsPropsRef.current.hold) - return; - actions.goToOption(5 /* Nothing */); - }); - let slot = (0, import_react19.useMemo)( - () => ({ active, selected, disabled }), - [active, selected, disabled] - ); - let ourProps = { - id, - ref: optionRef, - role: "option", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - // According to the WAI-ARIA best practices, we should use aria-checked for - // multi-select,but Voice-Over disagrees. So we use aria-checked instead for - // both single and multi-select. - "aria-selected": selected, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTION_TAG, - name: "Combobox.Option" - }); + } + }); + const asts = new Set(); + for (const name of referencedFragNames) { + if (!existingFrags.has(name) && fragmentDefinitions.has(name)) { + asts.add((0, _nullthrows.default)(fragmentDefinitions.get(name))); + } } - var ComboboxRoot = forwardRefWithAs(ComboboxFn); - var Button = forwardRefWithAs(ButtonFn); - var Input = forwardRefWithAs(InputFn); - var Label = forwardRefWithAs(LabelFn); - var Options = forwardRefWithAs(OptionsFn); - var Option = forwardRefWithAs(OptionFn); - var Combobox = Object.assign(ComboboxRoot, { Input, Button, Label, Options, Option }); - - // src/components/dialog/dialog.tsx - var import_react31 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/components/focus-trap/focus-trap.tsx - var import_react25 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/hooks/use-tab-direction.ts - var import_react20 = __webpack_require__(/*! react */ "react"); - function useTabDirection() { - let direction = (0, import_react20.useRef)(0 /* Forwards */); - useWindowEvent( - "keydown", - (event) => { - if (event.key === "Tab") { - direction.current = event.shiftKey ? 1 /* Backwards */ : 0 /* Forwards */; + const referencedFragments = []; + for (const ast of asts) { + (0, _graphql.visit)(ast, { + FragmentSpread(node) { + if (!referencedFragNames.has(node.name.value) && fragmentDefinitions.get(node.name.value)) { + asts.add((0, _nullthrows.default)(fragmentDefinitions.get(node.name.value))); + referencedFragNames.add(node.name.value); } - }, - true - ); - return direction; + } + }); + if (!existingFrags.has(ast.name.value)) { + referencedFragments.push(ast); + } } - - // src/hooks/use-is-mounted.ts - var import_react21 = __webpack_require__(/*! react */ "react"); - function useIsMounted() { - let mounted = (0, import_react21.useRef)(false); - useIsoMorphicEffect(() => { - mounted.current = true; - return () => { - mounted.current = false; - }; - }, []); - return mounted; + return referencedFragments; +}; +exports.getFragmentDependenciesForAST = getFragmentDependenciesForAST; + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js": +/*!************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getASTNodeAtPosition.js ***! + \************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getASTNodeAtPosition = getASTNodeAtPosition; +exports.pointToOffset = pointToOffset; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +function getASTNodeAtPosition(query, ast, point) { + const offset = pointToOffset(query, point); + let nodeContainingPosition; + (0, _graphql.visit)(ast, { + enter(node) { + if (node.kind !== 'Name' && node.loc && node.loc.start <= offset && offset <= node.loc.end) { + nodeContainingPosition = node; + } else { + return false; + } + }, + leave(node) { + if (node.loc && node.loc.start <= offset && offset <= node.loc.end) { + return false; + } + } + }); + return nodeContainingPosition; +} +function pointToOffset(text, point) { + const linesUntilPosition = text.split('\n').slice(0, point.line); + return point.character + linesUntilPosition.map(line => line.length + 1).reduce((a, b) => a + b, 0); +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/getOperationFacts.js": +/*!*********************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getOperationFacts.js ***! + \*********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = getOperationFacts; +exports.getOperationASTFacts = getOperationASTFacts; +exports.getQueryFacts = void 0; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); +function getOperationASTFacts(documentAST, schema) { + const variableToType = schema ? (0, _collectVariables.collectVariables)(schema, documentAST) : undefined; + const operations = []; + (0, _graphql.visit)(documentAST, { + OperationDefinition(node) { + operations.push(node); + } + }); + return { + variableToType, + operations + }; +} +function getOperationFacts(schema, documentString) { + if (!documentString) { + return; } - - // src/hooks/use-owner.ts - var import_react22 = __webpack_require__(/*! react */ "react"); - function useOwnerDocument(...args) { - return (0, import_react22.useMemo)(() => getOwnerDocument(...args), [...args]); + try { + const documentAST = (0, _graphql.parse)(documentString); + return Object.assign(Object.assign({}, getOperationASTFacts(documentAST, schema)), { + documentAST + }); + } catch (_a) { + return; } - - // src/hooks/use-event-listener.ts - var import_react23 = __webpack_require__(/*! react */ "react"); - function useEventListener(element, type, listener, options) { - let listenerRef = useLatestValue(listener); - (0, import_react23.useEffect)(() => { - element = element != null ? element : window; - function handler(event) { - listenerRef.current(event); - } - element.addEventListener(type, handler, options); - return () => element.removeEventListener(type, handler, options); - }, [element, type, options]); +} +const getQueryFacts = exports.getQueryFacts = getOperationFacts; + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js": +/*!**************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/getVariablesJSONSchema.js ***! + \**************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.defaultJSONSchemaOptions = void 0; +exports.getVariablesJSONSchema = getVariablesJSONSchema; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const defaultJSONSchemaOptions = exports.defaultJSONSchemaOptions = { + useMarkdownDescription: false +}; +function text(into, newText) { + into.push(newText); +} +function renderType(into, t) { + if ((0, _graphql.isNonNullType)(t)) { + renderType(into, t.ofType); + text(into, '!'); + } else if ((0, _graphql.isListType)(t)) { + text(into, '['); + renderType(into, t.ofType); + text(into, ']'); + } else { + text(into, t.name); + } +} +function renderDefinitionDescription(t, useMarkdown, description) { + const into = []; + const type = 'type' in t ? t.type : t; + if ('type' in t && t.description) { + text(into, t.description); + text(into, '\n\n'); } - - // src/utils/document-ready.ts - function onDocumentReady(cb) { - function check() { - if (document.readyState === "loading") - return; - cb(); - document.removeEventListener("DOMContentLoaded", check); - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - document.addEventListener("DOMContentLoaded", check); - check(); + text(into, renderTypeToString(type, useMarkdown)); + if (description) { + text(into, '\n'); + text(into, description); + } else if (!(0, _graphql.isScalarType)(type) && 'description' in type && type.description) { + text(into, '\n'); + text(into, type.description); + } else if ('ofType' in type && !(0, _graphql.isScalarType)(type.ofType) && 'description' in type.ofType && type.ofType.description) { + text(into, '\n'); + text(into, type.ofType.description); + } + return into.join(''); +} +function renderTypeToString(t, useMarkdown) { + const into = []; + if (useMarkdown) { + text(into, '```graphql\n'); + } + renderType(into, t); + if (useMarkdown) { + text(into, '\n```'); + } + return into.join(''); +} +const defaultScalarTypesMap = { + Int: { + type: 'integer' + }, + String: { + type: 'string' + }, + Float: { + type: 'number' + }, + ID: { + type: 'string' + }, + Boolean: { + type: 'boolean' + }, + DateTime: { + type: 'string' + } +}; +class Marker { + constructor() { + this.set = new Set(); + } + mark(name) { + if (this.set.has(name)) { + return false; } + this.set.add(name); + return true; } - - // src/hooks/use-on-unmount.ts - var import_react24 = __webpack_require__(/*! react */ "react"); - function useOnUnmount(cb) { - let stableCb = useEvent(cb); - let trulyUnmounted = (0, import_react24.useRef)(false); - (0, import_react24.useEffect)(() => { - trulyUnmounted.current = false; - return () => { - trulyUnmounted.current = true; - microTask(() => { - if (!trulyUnmounted.current) - return; - stableCb(); +} +function getJSONSchemaFromGraphQLType(fieldOrType, options) { + var _a, _b; + let definition = Object.create(null); + const definitions = Object.create(null); + const isField = ('type' in fieldOrType); + const type = isField ? fieldOrType.type : fieldOrType; + const baseType = (0, _graphql.isNonNullType)(type) ? type.ofType : type; + const required = (0, _graphql.isNonNullType)(type); + if ((0, _graphql.isScalarType)(baseType)) { + if ((_a = options === null || options === void 0 ? void 0 : options.scalarSchemas) === null || _a === void 0 ? void 0 : _a[baseType.name]) { + definition = JSON.parse(JSON.stringify(options.scalarSchemas[baseType.name])); + } else { + definition.type = ['string', 'number', 'boolean', 'integer']; + } + if (!required) { + if (Array.isArray(definition.type)) { + definition.type.push('null'); + } else if (definition.type) { + definition.type = [definition.type, 'null']; + } else if (definition.enum) { + definition.enum.push(null); + } else if (definition.oneOf) { + definition.oneOf.push({ + type: 'null' }); + } else { + definition = { + oneOf: [definition, { + type: 'null' + }] + }; + } + } + } else if ((0, _graphql.isEnumType)(baseType)) { + definition.enum = baseType.getValues().map(val => val.name); + if (!required) { + definition.enum.push(null); + } + } else if ((0, _graphql.isListType)(baseType)) { + if (required) { + definition.type = 'array'; + } else { + definition.type = ['array', 'null']; + } + const { + definition: def, + definitions: defs + } = getJSONSchemaFromGraphQLType(baseType.ofType, options); + definition.items = def; + if (defs) { + for (const defName of Object.keys(defs)) { + definitions[defName] = defs[defName]; + } + } + } else if ((0, _graphql.isInputObjectType)(baseType)) { + if (required) { + definition.$ref = `#/definitions/${baseType.name}`; + } else { + definition.oneOf = [{ + $ref: `#/definitions/${baseType.name}` + }, { + type: 'null' + }]; + } + if ((_b = options === null || options === void 0 ? void 0 : options.definitionMarker) === null || _b === void 0 ? void 0 : _b.mark(baseType.name)) { + const fields = baseType.getFields(); + const fieldDef = { + type: 'object', + properties: {}, + required: [] }; - }, [stableCb]); - } - - // src/components/focus-trap/focus-trap.tsx - function resolveContainers(containers) { - if (!containers) - return /* @__PURE__ */ new Set(); - if (typeof containers === "function") - return new Set(containers()); - let all = /* @__PURE__ */ new Set(); - for (let container of containers.current) { - if (container.current instanceof HTMLElement) { - all.add(container.current); - } - } - return all; - } - var DEFAULT_FOCUS_TRAP_TAG = "div"; - var Features3 = /* @__PURE__ */ ((Features4) => { - Features4[Features4["None"] = 1] = "None"; - Features4[Features4["InitialFocus"] = 2] = "InitialFocus"; - Features4[Features4["TabLock"] = 4] = "TabLock"; - Features4[Features4["FocusLock"] = 8] = "FocusLock"; - Features4[Features4["RestoreFocus"] = 16] = "RestoreFocus"; - Features4[Features4["All"] = 30] = "All"; - return Features4; - })(Features3 || {}); - function FocusTrapFn(props, ref) { - let container = (0, import_react25.useRef)(null); - let focusTrapRef = useSyncRefs(container, ref); - let { initialFocus, containers, features = 30 /* All */, ...theirProps } = props; - if (!useServerHandoffComplete()) { - features = 1 /* None */; - } - let ownerDocument = useOwnerDocument(container); - useRestoreFocus({ ownerDocument }, Boolean(features & 16 /* RestoreFocus */)); - let previousActiveElement = useInitialFocus( - { ownerDocument, container, initialFocus }, - Boolean(features & 2 /* InitialFocus */) - ); - useFocusLock( - { ownerDocument, container, containers, previousActiveElement }, - Boolean(features & 8 /* FocusLock */) - ); - let direction = useTabDirection(); - let handleFocus = useEvent((e) => { - let el = container.current; - if (!el) - return; - let wrapper = false ? 0 : (cb) => cb(); - wrapper(() => { - match(direction.current, { - [0 /* Forwards */]: () => { - focusIn(el, 1 /* First */, { skipElements: [e.relatedTarget] }); - }, - [1 /* Backwards */]: () => { - focusIn(el, 8 /* Last */, { skipElements: [e.relatedTarget] }); - } - }); - }); - }); - let d = useDisposables(); - let recentlyUsedTabKey = (0, import_react25.useRef)(false); - let ourProps = { - ref: focusTrapRef, - onKeyDown(e) { - if (e.key == "Tab") { - recentlyUsedTabKey.current = true; - d.requestAnimationFrame(() => { - recentlyUsedTabKey.current = false; - }); - } - }, - onBlur(e) { - let allContainers = resolveContainers(containers); - if (container.current instanceof HTMLElement) - allContainers.add(container.current); - let relatedTarget = e.relatedTarget; - if (!(relatedTarget instanceof HTMLElement)) - return; - if (relatedTarget.dataset.headlessuiFocusGuard === "true") { - return; + fieldDef.description = renderDefinitionDescription(baseType); + if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { + fieldDef.markdownDescription = renderDefinitionDescription(baseType, true); + } + for (const fieldName of Object.keys(fields)) { + const field = fields[fieldName]; + const { + required: fieldRequired, + definition: fieldDefinition, + definitions: typeDefinitions + } = getJSONSchemaFromGraphQLType(field, options); + fieldDef.properties[fieldName] = fieldDefinition; + if (fieldRequired) { + fieldDef.required.push(fieldName); } - if (!contains(allContainers, relatedTarget)) { - if (recentlyUsedTabKey.current) { - focusIn( - container.current, - match(direction.current, { - [0 /* Forwards */]: () => 4 /* Next */, - [1 /* Backwards */]: () => 2 /* Previous */ - }) | 16 /* WrapAround */, - { relativeTo: e.target } - ); - } else if (e.target instanceof HTMLElement) { - focusElement(e.target); + if (typeDefinitions) { + for (const [defName, value] of Object.entries(typeDefinitions)) { + definitions[defName] = value; } } } - }; - return /* @__PURE__ */ import_react25.default.createElement(import_react25.default.Fragment, null, Boolean(features & 4 /* TabLock */) && /* @__PURE__ */ import_react25.default.createElement( - Hidden, - { - as: "button", - type: "button", - "data-headlessui-focus-guard": true, - onFocus: handleFocus, - features: 2 /* Focusable */ + definitions[baseType.name] = fieldDef; + } + } + if ('defaultValue' in fieldOrType && fieldOrType.defaultValue !== undefined) { + definition.default = fieldOrType.defaultValue; + } + const { + description + } = definition; + definition.description = renderDefinitionDescription(fieldOrType, false, description); + if (options === null || options === void 0 ? void 0 : options.useMarkdownDescription) { + definition.markdownDescription = renderDefinitionDescription(fieldOrType, true, description); + } + return { + required, + definition, + definitions + }; +} +function getVariablesJSONSchema(variableToType, options) { + var _a; + const jsonSchema = { + $schema: 'http://json-schema.org/draft-04/schema', + type: 'object', + properties: {}, + required: [] + }; + const runtimeOptions = Object.assign(Object.assign({}, options), { + definitionMarker: new Marker(), + scalarSchemas: Object.assign(Object.assign({}, defaultScalarTypesMap), options === null || options === void 0 ? void 0 : options.scalarSchemas) + }); + if (variableToType) { + for (const [variableName, type] of Object.entries(variableToType)) { + const { + definition, + required, + definitions + } = getJSONSchemaFromGraphQLType(type, runtimeOptions); + jsonSchema.properties[variableName] = definition; + if (required) { + (_a = jsonSchema.required) === null || _a === void 0 ? void 0 : _a.push(variableName); } - ), render({ - ourProps, - theirProps, - defaultTag: DEFAULT_FOCUS_TRAP_TAG, - name: "FocusTrap" - }), Boolean(features & 4 /* TabLock */) && /* @__PURE__ */ import_react25.default.createElement( - Hidden, - { - as: "button", - type: "button", - "data-headlessui-focus-guard": true, - onFocus: handleFocus, - features: 2 /* Focusable */ + if (definitions) { + jsonSchema.definitions = Object.assign(Object.assign({}, jsonSchema === null || jsonSchema === void 0 ? void 0 : jsonSchema.definitions), definitions); } - )); + } } - var FocusTrapRoot = forwardRefWithAs(FocusTrapFn); - var FocusTrap = Object.assign(FocusTrapRoot, { - features: Features3 - }); - var history = []; - onDocumentReady(() => { - function handle(e) { - if (!(e.target instanceof HTMLElement)) - return; - if (e.target === document.body) - return; - if (history[0] === e.target) - return; - history.unshift(e.target); - history = history.filter((x) => x != null && x.isConnected); - history.splice(10); - } - window.addEventListener("click", handle, { capture: true }); - window.addEventListener("mousedown", handle, { capture: true }); - window.addEventListener("focus", handle, { capture: true }); - document.body.addEventListener("click", handle, { capture: true }); - document.body.addEventListener("mousedown", handle, { capture: true }); - document.body.addEventListener("focus", handle, { capture: true }); + return jsonSchema; +} + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/index.js": +/*!*********************************************************!*\ + !*** ../../graphql-language-service/esm/utils/index.js ***! + \*********************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "Position", ({ + enumerable: true, + get: function () { + return _Range.Position; + } +})); +Object.defineProperty(exports, "Range", ({ + enumerable: true, + get: function () { + return _Range.Range; + } +})); +Object.defineProperty(exports, "collectVariables", ({ + enumerable: true, + get: function () { + return _collectVariables.collectVariables; + } +})); +Object.defineProperty(exports, "getASTNodeAtPosition", ({ + enumerable: true, + get: function () { + return _getASTNodeAtPosition.getASTNodeAtPosition; + } +})); +Object.defineProperty(exports, "getFragmentDependencies", ({ + enumerable: true, + get: function () { + return _fragmentDependencies.getFragmentDependencies; + } +})); +Object.defineProperty(exports, "getFragmentDependenciesForAST", ({ + enumerable: true, + get: function () { + return _fragmentDependencies.getFragmentDependenciesForAST; + } +})); +Object.defineProperty(exports, "getOperationASTFacts", ({ + enumerable: true, + get: function () { + return _getOperationFacts.getOperationASTFacts; + } +})); +Object.defineProperty(exports, "getOperationFacts", ({ + enumerable: true, + get: function () { + return _getOperationFacts.default; + } +})); +Object.defineProperty(exports, "getQueryFacts", ({ + enumerable: true, + get: function () { + return _getOperationFacts.getQueryFacts; + } +})); +Object.defineProperty(exports, "getVariablesJSONSchema", ({ + enumerable: true, + get: function () { + return _getVariablesJSONSchema.getVariablesJSONSchema; + } +})); +Object.defineProperty(exports, "locToRange", ({ + enumerable: true, + get: function () { + return _Range.locToRange; + } +})); +Object.defineProperty(exports, "offsetToPosition", ({ + enumerable: true, + get: function () { + return _Range.offsetToPosition; + } +})); +Object.defineProperty(exports, "pointToOffset", ({ + enumerable: true, + get: function () { + return _getASTNodeAtPosition.pointToOffset; + } +})); +Object.defineProperty(exports, "validateWithCustomRules", ({ + enumerable: true, + get: function () { + return _validateWithCustomRules.validateWithCustomRules; + } +})); +var _fragmentDependencies = __webpack_require__(/*! ./fragmentDependencies */ "../../graphql-language-service/esm/utils/fragmentDependencies.js"); +var _getVariablesJSONSchema = __webpack_require__(/*! ./getVariablesJSONSchema */ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js"); +var _getASTNodeAtPosition = __webpack_require__(/*! ./getASTNodeAtPosition */ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js"); +var _Range = __webpack_require__(/*! ./Range */ "../../graphql-language-service/esm/utils/Range.js"); +var _validateWithCustomRules = __webpack_require__(/*! ./validateWithCustomRules */ "../../graphql-language-service/esm/utils/validateWithCustomRules.js"); +var _collectVariables = __webpack_require__(/*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js"); +var _getOperationFacts = _interopRequireWildcard(__webpack_require__(/*! ./getOperationFacts */ "../../graphql-language-service/esm/utils/getOperationFacts.js")); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } + +/***/ }), + +/***/ "../../graphql-language-service/esm/utils/validateWithCustomRules.js": +/*!***************************************************************************!*\ + !*** ../../graphql-language-service/esm/utils/validateWithCustomRules.js ***! + \***************************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.validateWithCustomRules = validateWithCustomRules; +var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); +const specifiedSDLRules = [_graphql.LoneSchemaDefinitionRule, _graphql.UniqueOperationTypesRule, _graphql.UniqueTypeNamesRule, _graphql.UniqueEnumValueNamesRule, _graphql.UniqueFieldDefinitionNamesRule, _graphql.UniqueDirectiveNamesRule, _graphql.KnownTypeNamesRule, _graphql.KnownDirectivesRule, _graphql.UniqueDirectivesPerLocationRule, _graphql.PossibleTypeExtensionsRule, _graphql.UniqueArgumentNamesRule, _graphql.UniqueInputFieldNamesRule, _graphql.UniqueVariableNamesRule, _graphql.FragmentsOnCompositeTypesRule, _graphql.ProvidedRequiredArgumentsRule]; +function validateWithCustomRules(schema, ast, customRules, isRelayCompatMode, isSchemaDocument) { + const rules = _graphql.specifiedRules.filter(rule => { + if (rule === _graphql.NoUnusedFragmentsRule || rule === _graphql.ExecutableDefinitionsRule) { + return false; + } + if (isRelayCompatMode && rule === _graphql.KnownFragmentNamesRule) { + return false; + } + return true; }); - function useRestoreElement(enabled = true) { - let localHistory = (0, import_react25.useRef)(history.slice()); - useWatch( - ([newEnabled], [oldEnabled]) => { - if (oldEnabled === true && newEnabled === false) { - microTask(() => { - localHistory.current.splice(0); - }); - } - if (oldEnabled === false && newEnabled === true) { - localHistory.current = history.slice(); + if (customRules) { + Array.prototype.push.apply(rules, customRules); + } + if (isSchemaDocument) { + Array.prototype.push.apply(rules, specifiedSDLRules); + } + const errors = (0, _graphql.validate)(schema, ast, rules); + return errors.filter(error => { + if (error.message.includes('Unknown directive') && error.nodes) { + const node = error.nodes[0]; + if (node && node.kind === _graphql.Kind.DIRECTIVE) { + const name = node.name.value; + if (name === 'arguments' || name === 'argumentDefinitions') { + return false; } - }, - [enabled, history, localHistory] - ); - return useEvent(() => { - var _a3; - return (_a3 = localHistory.current.find((x) => x != null && x.isConnected)) != null ? _a3 : null; - }); + } + } + return true; + }); +} + +/***/ }), + +/***/ "./style.css": +/*!*******************!*\ + !*** ./style.css ***! + \*******************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "../../graphiql-react/dist/style.css": +/*!*******************************************!*\ + !*** ../../graphiql-react/dist/style.css ***! + \*******************************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "../../graphiql-react/font/fira-code.css": +/*!***********************************************!*\ + !*** ../../graphiql-react/font/fira-code.css ***! + \***********************************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "../../graphiql-react/font/roboto.css": +/*!********************************************!*\ + !*** ../../graphiql-react/font/roboto.css ***! + \********************************************/ +/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "react": +/*!************************!*\ + !*** external "React" ***! + \************************/ +/***/ (function(module) { + +module.exports = window["React"]; + +/***/ }), + +/***/ "react-dom": +/*!***************************!*\ + !*** external "ReactDOM" ***! + \***************************/ +/***/ (function(module) { + +module.exports = window["ReactDOM"]; + +/***/ }), + +/***/ "../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs": +/*!***********************************************************************!*\ + !*** ../../../node_modules/@headlessui/react/dist/headlessui.dev.cjs ***! + \***********************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Combobox: () => Combobox, + Dialog: () => Dialog, + Disclosure: () => Disclosure, + FocusTrap: () => FocusTrap, + Listbox: () => Listbox, + Menu: () => Menu, + Popover: () => Popover, + Portal: () => Portal, + RadioGroup: () => RadioGroup, + Switch: () => Switch, + Tab: () => Tab, + Transition: () => Transition +}); +module.exports = __toCommonJS(src_exports); + +// src/components/combobox/combobox.tsx +var import_react19 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/hooks/use-computed.ts +var import_react3 = __webpack_require__(/*! react */ "react"); + +// src/hooks/use-iso-morphic-effect.ts +var import_react = __webpack_require__(/*! react */ "react"); + +// src/utils/env.ts +var Env = class { + constructor() { + __publicField(this, "current", this.detect()); + __publicField(this, "handoffState", "pending"); + __publicField(this, "currentId", 0); + } + set(env2) { + if (this.current === env2) + return; + this.handoffState = "pending"; + this.currentId = 0; + this.current = env2; + } + reset() { + this.set(this.detect()); + } + nextId() { + return ++this.currentId; } - function useRestoreFocus({ ownerDocument }, enabled) { - let getRestoreElement = useRestoreElement(enabled); - useWatch(() => { - if (enabled) - return; - if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) === (ownerDocument == null ? void 0 : ownerDocument.body)) { - focusElement(getRestoreElement()); - } - }, [enabled]); - useOnUnmount(() => { - if (!enabled) - return; - focusElement(getRestoreElement()); - }); + get isServer() { + return this.current === "server"; } - function useInitialFocus({ - ownerDocument, - container, - initialFocus - }, enabled) { - let previousActiveElement = (0, import_react25.useRef)(null); - let mounted = useIsMounted(); - useWatch(() => { - if (!enabled) - return; - let containerElement = container.current; - if (!containerElement) - return; + get isClient() { + return this.current === "client"; + } + detect() { + if (typeof window === "undefined" || typeof document === "undefined") { + return "server"; + } + return "client"; + } + handoff() { + if (this.handoffState === "pending") { + this.handoffState = "complete"; + } + } + get isHandoffComplete() { + return this.handoffState === "complete"; + } +}; +var env = new Env(); + +// src/hooks/use-iso-morphic-effect.ts +var useIsoMorphicEffect = (effect, deps) => { + if (env.isServer) { + (0, import_react.useEffect)(effect, deps); + } else { + (0, import_react.useLayoutEffect)(effect, deps); + } +}; + +// src/hooks/use-latest-value.ts +var import_react2 = __webpack_require__(/*! react */ "react"); +function useLatestValue(value) { + let cache = (0, import_react2.useRef)(value); + useIsoMorphicEffect(() => { + cache.current = value; + }, [value]); + return cache; +} + +// src/hooks/use-computed.ts +function useComputed(cb, dependencies) { + let [value, setValue] = (0, import_react3.useState)(cb); + let cbRef = useLatestValue(cb); + useIsoMorphicEffect(() => setValue(cbRef.current), [cbRef, setValue, ...dependencies]); + return value; +} + +// src/hooks/use-disposables.ts +var import_react4 = __webpack_require__(/*! react */ "react"); + +// src/utils/micro-task.ts +function microTask(cb) { + if (typeof queueMicrotask === "function") { + queueMicrotask(cb); + } else { + Promise.resolve().then(cb).catch( + (e) => setTimeout(() => { + throw e; + }) + ); + } +} + +// src/utils/disposables.ts +function disposables() { + let _disposables = []; + let api = { + addEventListener(element, name, listener, options) { + element.addEventListener(name, listener, options); + return api.add(() => element.removeEventListener(name, listener, options)); + }, + requestAnimationFrame(...args) { + let raf = requestAnimationFrame(...args); + return api.add(() => cancelAnimationFrame(raf)); + }, + nextFrame(...args) { + return api.requestAnimationFrame(() => { + return api.requestAnimationFrame(...args); + }); + }, + setTimeout(...args) { + let timer = setTimeout(...args); + return api.add(() => clearTimeout(timer)); + }, + microTask(...args) { + let task = { current: true }; microTask(() => { - if (!mounted.current) { - return; + if (task.current) { + args[0](); } - let activeElement = ownerDocument == null ? void 0 : ownerDocument.activeElement; - if (initialFocus == null ? void 0 : initialFocus.current) { - if ((initialFocus == null ? void 0 : initialFocus.current) === activeElement) { - previousActiveElement.current = activeElement; - return; - } - } else if (containerElement.contains(activeElement)) { - previousActiveElement.current = activeElement; - return; - } - if (initialFocus == null ? void 0 : initialFocus.current) { - focusElement(initialFocus.current); - } else { - if (focusIn(containerElement, 1 /* First */) === 0 /* Error */) { - console.warn("There are no focusable elements inside the "); - } - } - previousActiveElement.current = ownerDocument == null ? void 0 : ownerDocument.activeElement; }); - }, [enabled]); - return previousActiveElement; - } - function useFocusLock({ - ownerDocument, - container, - containers, - previousActiveElement - }, enabled) { - let mounted = useIsMounted(); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "focus", - (event) => { - if (!enabled) - return; - if (!mounted.current) - return; - let allContainers = resolveContainers(containers); - if (container.current instanceof HTMLElement) - allContainers.add(container.current); - let previous = previousActiveElement.current; - if (!previous) - return; - let toElement = event.target; - if (toElement && toElement instanceof HTMLElement) { - if (!contains(allContainers, toElement)) { - event.preventDefault(); - event.stopPropagation(); - focusElement(previous); - } else { - previousActiveElement.current = toElement; - focusElement(toElement); + return api.add(() => { + task.current = false; + }); + }, + style(node, property, value) { + let previous = node.style.getPropertyValue(property); + Object.assign(node.style, { [property]: value }); + return this.add(() => { + Object.assign(node.style, { [property]: previous }); + }); + }, + group(cb) { + let d = disposables(); + cb(d); + return this.add(() => d.dispose()); + }, + add(cb) { + _disposables.push(cb); + return () => { + let idx = _disposables.indexOf(cb); + if (idx >= 0) { + for (let dispose of _disposables.splice(idx, 1)) { + dispose(); } - } else { - focusElement(previousActiveElement.current); } - }, - true - ); - } - function contains(containers, element) { - for (let container of containers) { - if (container.contains(element)) - return true; + }; + }, + dispose() { + for (let dispose of _disposables.splice(0)) { + dispose(); + } } - return false; - } - - // src/components/portal/portal.tsx - var import_react27 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var import_react_dom = __webpack_require__(/*! react-dom */ "react-dom"); - - // src/internal/portal-force-root.tsx - var import_react26 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var ForcePortalRootContext = (0, import_react26.createContext)(false); - function usePortalRoot() { - return (0, import_react26.useContext)(ForcePortalRootContext); - } - function ForcePortalRoot(props) { - return /* @__PURE__ */ import_react26.default.createElement(ForcePortalRootContext.Provider, { value: props.force }, props.children); + }; + return api; +} + +// src/hooks/use-disposables.ts +function useDisposables() { + let [d] = (0, import_react4.useState)(disposables); + (0, import_react4.useEffect)(() => () => d.dispose(), [d]); + return d; +} + +// src/hooks/use-event.ts +var import_react5 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var useEvent = ( + // TODO: Add React.useEvent ?? once the useEvent hook is available + function useEvent2(cb) { + let cache = useLatestValue(cb); + return import_react5.default.useCallback((...args) => cache.current(...args), [cache]); + } +); + +// src/hooks/use-id.ts +var import_react7 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/hooks/use-server-handoff-complete.ts +var import_react6 = __webpack_require__(/*! react */ "react"); +function useServerHandoffComplete() { + let [complete, setComplete] = (0, import_react6.useState)(env.isHandoffComplete); + if (complete && env.isHandoffComplete === false) { + setComplete(false); + } + (0, import_react6.useEffect)(() => { + if (complete === true) + return; + setComplete(true); + }, [complete]); + (0, import_react6.useEffect)(() => env.handoff(), []); + return complete; +} + +// src/hooks/use-id.ts +var _a; +var useId = ( + // Prefer React's `useId` if it's available. + // @ts-expect-error - `useId` doesn't exist in React < 18. + (_a = import_react7.default.useId) != null ? _a : function useId2() { + let ready = useServerHandoffComplete(); + let [id, setId] = import_react7.default.useState(ready ? () => env.nextId() : null); + useIsoMorphicEffect(() => { + if (id === null) + setId(env.nextId()); + }, [id]); + return id != null ? "" + id : void 0; } - - // src/components/portal/portal.tsx - function usePortalTarget(ref) { - let forceInRoot = usePortalRoot(); - let groupTarget = (0, import_react27.useContext)(PortalGroupContext); - let ownerDocument = useOwnerDocument(ref); - let [target, setTarget] = (0, import_react27.useState)(() => { - if (!forceInRoot && groupTarget !== null) - return null; - if (env.isServer) - return null; - let existingRoot = ownerDocument == null ? void 0 : ownerDocument.getElementById("headlessui-portal-root"); - if (existingRoot) - return existingRoot; - if (ownerDocument === null) - return null; - let root = ownerDocument.createElement("div"); - root.setAttribute("id", "headlessui-portal-root"); - return ownerDocument.body.appendChild(root); - }); - (0, import_react27.useEffect)(() => { - if (target === null) +); + +// src/hooks/use-outside-click.ts +var import_react10 = __webpack_require__(/*! react */ "react"); + +// src/utils/match.ts +function match(value, lookup, ...args) { + if (value in lookup) { + let returnValue = lookup[value]; + return typeof returnValue === "function" ? returnValue(...args) : returnValue; + } + let error = new Error( + `Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys( + lookup + ).map((key) => `"${key}"`).join(", ")}.` + ); + if (Error.captureStackTrace) + Error.captureStackTrace(error, match); + throw error; +} + +// src/utils/owner.ts +function getOwnerDocument(element) { + if (env.isServer) + return null; + if (element instanceof Node) + return element.ownerDocument; + if (element == null ? void 0 : element.hasOwnProperty("current")) { + if (element.current instanceof Node) + return element.current.ownerDocument; + } + return document; +} + +// src/utils/focus-management.ts +var focusableSelector = [ + "[contentEditable=true]", + "[tabindex]", + "a[href]", + "area[href]", + "button:not([disabled])", + "iframe", + "input:not([disabled])", + "select:not([disabled])", + "textarea:not([disabled])" +].map( + false ? ( + // TODO: Remove this once JSDOM fixes the issue where an element that is + // "hidden" can be the document.activeElement, because this is not possible + // in real browsers. + 0 + ) : (selector) => `${selector}:not([tabindex='-1'])` +).join(","); +function getFocusableElements(container = document.body) { + if (container == null) + return []; + return Array.from(container.querySelectorAll(focusableSelector)).sort( + // We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well. + (a, z) => Math.sign((a.tabIndex || Number.MAX_SAFE_INTEGER) - (z.tabIndex || Number.MAX_SAFE_INTEGER)) + ); +} +function isFocusableElement(element, mode = 0 /* Strict */) { + var _a3; + if (element === ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body)) + return false; + return match(mode, { + [0 /* Strict */]() { + return element.matches(focusableSelector); + }, + [1 /* Loose */]() { + let next = element; + while (next !== null) { + if (next.matches(focusableSelector)) + return true; + next = next.parentElement; + } + return false; + } + }); +} +function restoreFocusIfNecessary(element) { + let ownerDocument = getOwnerDocument(element); + disposables().nextFrame(() => { + if (ownerDocument && !isFocusableElement(ownerDocument.activeElement, 0 /* Strict */)) { + focusElement(element); + } + }); +} +if (typeof window !== "undefined" && typeof document !== "undefined") { + document.addEventListener( + "keydown", + (event) => { + if (event.metaKey || event.altKey || event.ctrlKey) { return; - if (!(ownerDocument == null ? void 0 : ownerDocument.body.contains(target))) { - ownerDocument == null ? void 0 : ownerDocument.body.appendChild(target); } - }, [target, ownerDocument]); - (0, import_react27.useEffect)(() => { - if (forceInRoot) + document.documentElement.dataset.headlessuiFocusVisible = ""; + }, + true + ); + document.addEventListener( + "click", + (event) => { + if (event.detail === 1 /* Mouse */) { + delete document.documentElement.dataset.headlessuiFocusVisible; + } else if (event.detail === 0 /* Keyboard */) { + document.documentElement.dataset.headlessuiFocusVisible = ""; + } + }, + true + ); +} +function focusElement(element) { + element == null ? void 0 : element.focus({ preventScroll: true }); +} +var selectableSelector = ["textarea", "input"].join(","); +function isSelectableElement(element) { + var _a3, _b; + return (_b = (_a3 = element == null ? void 0 : element.matches) == null ? void 0 : _a3.call(element, selectableSelector)) != null ? _b : false; +} +function sortByDomNode(nodes, resolveKey = (i) => i) { + return nodes.slice().sort((aItem, zItem) => { + let a = resolveKey(aItem); + let z = resolveKey(zItem); + if (a === null || z === null) + return 0; + let position = a.compareDocumentPosition(z); + if (position & Node.DOCUMENT_POSITION_FOLLOWING) + return -1; + if (position & Node.DOCUMENT_POSITION_PRECEDING) + return 1; + return 0; + }); +} +function focusFrom(current, focus) { + return focusIn(getFocusableElements(), focus, { relativeTo: current }); +} +function focusIn(container, focus, { + sorted = true, + relativeTo = null, + skipElements = [] +} = {}) { + let ownerDocument = Array.isArray(container) ? container.length > 0 ? container[0].ownerDocument : document : container.ownerDocument; + let elements = Array.isArray(container) ? sorted ? sortByDomNode(container) : container : getFocusableElements(container); + if (skipElements.length > 0 && elements.length > 1) { + elements = elements.filter((x) => !skipElements.includes(x)); + } + relativeTo = relativeTo != null ? relativeTo : ownerDocument.activeElement; + let direction = (() => { + if (focus & (1 /* First */ | 4 /* Next */)) + return 1 /* Next */; + if (focus & (2 /* Previous */ | 8 /* Last */)) + return -1 /* Previous */; + throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); + })(); + let startIndex = (() => { + if (focus & 1 /* First */) + return 0; + if (focus & 2 /* Previous */) + return Math.max(0, elements.indexOf(relativeTo)) - 1; + if (focus & 4 /* Next */) + return Math.max(0, elements.indexOf(relativeTo)) + 1; + if (focus & 8 /* Last */) + return elements.length - 1; + throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last"); + })(); + let focusOptions = focus & 32 /* NoScroll */ ? { preventScroll: true } : {}; + let offset = 0; + let total = elements.length; + let next = void 0; + do { + if (offset >= total || offset + total <= 0) + return 0 /* Error */; + let nextIdx = startIndex + offset; + if (focus & 16 /* WrapAround */) { + nextIdx = (nextIdx + total) % total; + } else { + if (nextIdx < 0) + return 3 /* Underflow */; + if (nextIdx >= total) + return 1 /* Overflow */; + } + next = elements[nextIdx]; + next == null ? void 0 : next.focus(focusOptions); + offset += direction; + } while (next !== ownerDocument.activeElement); + if (focus & (4 /* Next */ | 2 /* Previous */) && isSelectableElement(next)) { + next.select(); + } + return 2 /* Success */; +} + +// src/hooks/use-document-event.ts +var import_react8 = __webpack_require__(/*! react */ "react"); +function useDocumentEvent(type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react8.useEffect)(() => { + function handler(event) { + listenerRef.current(event); + } + document.addEventListener(type, handler, options); + return () => document.removeEventListener(type, handler, options); + }, [type, options]); +} + +// src/hooks/use-window-event.ts +var import_react9 = __webpack_require__(/*! react */ "react"); +function useWindowEvent(type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react9.useEffect)(() => { + function handler(event) { + listenerRef.current(event); + } + window.addEventListener(type, handler, options); + return () => window.removeEventListener(type, handler, options); + }, [type, options]); +} + +// src/hooks/use-outside-click.ts +function useOutsideClick(containers, cb, enabled = true) { + let enabledRef = (0, import_react10.useRef)(false); + (0, import_react10.useEffect)( + false ? 0 : () => { + requestAnimationFrame(() => { + enabledRef.current = enabled; + }); + }, + [enabled] + ); + function handleOutsideClick(event, resolveTarget) { + if (!enabledRef.current) + return; + if (event.defaultPrevented) + return; + let target = resolveTarget(event); + if (target === null) { + return; + } + if (!target.getRootNode().contains(target)) + return; + let _containers = function resolve(containers2) { + if (typeof containers2 === "function") { + return resolve(containers2()); + } + if (Array.isArray(containers2)) { + return containers2; + } + if (containers2 instanceof Set) { + return containers2; + } + return [containers2]; + }(containers); + for (let container of _containers) { + if (container === null) + continue; + let domNode = container instanceof HTMLElement ? container : container.current; + if (domNode == null ? void 0 : domNode.contains(target)) { return; - if (groupTarget === null) + } + if (event.composed && event.composedPath().includes(domNode)) { return; - setTarget(groupTarget.current); - }, [groupTarget, setTarget, forceInRoot]); - return target; + } + } + if ( + // This check alllows us to know whether or not we clicked on a "focusable" element like a + // button or an input. This is a backwards compatibility check so that you can open a and click on another which should close Menu A and open Menu B. We might + // revisit that so that you will require 2 clicks instead. + !isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1} to make it + // unfocusable via the keyboard so that tabbing to the next item from the input doesn't + // first go to the button. + target.tabIndex !== -1 + ) { + event.preventDefault(); + } + return cb(event, target); } - var DEFAULT_PORTAL_TAG = import_react27.Fragment; - function PortalFn(props, ref) { - let theirProps = props; - let internalPortalRootRef = (0, import_react27.useRef)(null); - let portalRef = useSyncRefs( - optionalRef((ref2) => { - internalPortalRootRef.current = ref2; - }), - ref - ); - let ownerDocument = useOwnerDocument(internalPortalRootRef); - let target = usePortalTarget(internalPortalRootRef); - let [element] = (0, import_react27.useState)( - () => { - var _a3; - return env.isServer ? null : (_a3 = ownerDocument == null ? void 0 : ownerDocument.createElement("div")) != null ? _a3 : null; + let initialClickTarget = (0, import_react10.useRef)(null); + useDocumentEvent( + "mousedown", + (event) => { + var _a3, _b; + if (enabledRef.current) { + initialClickTarget.current = ((_b = (_a3 = event.composedPath) == null ? void 0 : _a3.call(event)) == null ? void 0 : _b[0]) || event.target; } - ); - let parent = (0, import_react27.useContext)(PortalParentContext); - let ready = useServerHandoffComplete(); - useIsoMorphicEffect(() => { - if (!target || !element) + }, + true + ); + useDocumentEvent( + "click", + (event) => { + if (!initialClickTarget.current) { return; - if (!target.contains(element)) { - element.setAttribute("data-headlessui-portal", ""); - target.appendChild(element); } - }, [target, element]); - useIsoMorphicEffect(() => { - if (!element) - return; - if (!parent) - return; - return parent.register(element); - }, [parent, element]); - useOnUnmount(() => { - var _a3; - if (!target || !element) - return; - if (element instanceof Node && target.contains(element)) { - target.removeChild(element); + handleOutsideClick(event, () => { + return initialClickTarget.current; + }); + initialClickTarget.current = null; + }, + // We will use the `capture` phase so that layers in between with `event.stopPropagation()` + // don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu` + // is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However, + // the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this. + true + ); + useWindowEvent( + "blur", + (event) => handleOutsideClick( + event, + () => window.document.activeElement instanceof HTMLIFrameElement ? window.document.activeElement : null + ), + true + ); +} + +// src/hooks/use-resolve-button-type.ts +var import_react11 = __webpack_require__(/*! react */ "react"); +function resolveType(props) { + var _a3; + if (props.type) + return props.type; + let tag = (_a3 = props.as) != null ? _a3 : "button"; + if (typeof tag === "string" && tag.toLowerCase() === "button") + return "button"; + return void 0; +} +function useResolveButtonType(props, ref) { + let [type, setType] = (0, import_react11.useState)(() => resolveType(props)); + useIsoMorphicEffect(() => { + setType(resolveType(props)); + }, [props.type, props.as]); + useIsoMorphicEffect(() => { + if (type) + return; + if (!ref.current) + return; + if (ref.current instanceof HTMLButtonElement && !ref.current.hasAttribute("type")) { + setType("button"); + } + }, [type, ref]); + return type; +} + +// src/hooks/use-sync-refs.ts +var import_react12 = __webpack_require__(/*! react */ "react"); +var Optional = Symbol(); +function optionalRef(cb, isOptional = true) { + return Object.assign(cb, { [Optional]: isOptional }); +} +function useSyncRefs(...refs) { + let cache = (0, import_react12.useRef)(refs); + (0, import_react12.useEffect)(() => { + cache.current = refs; + }, [refs]); + let syncRefs = useEvent((value) => { + for (let ref of cache.current) { + if (ref == null) + continue; + if (typeof ref === "function") + ref(value); + else + ref.current = value; + } + }); + return refs.every( + (ref) => ref == null || // @ts-expect-error + (ref == null ? void 0 : ref[Optional]) + ) ? void 0 : syncRefs; +} + +// src/hooks/use-tree-walker.ts +var import_react13 = __webpack_require__(/*! react */ "react"); +function useTreeWalker({ + container, + accept, + walk, + enabled = true +}) { + let acceptRef = (0, import_react13.useRef)(accept); + let walkRef = (0, import_react13.useRef)(walk); + (0, import_react13.useEffect)(() => { + acceptRef.current = accept; + walkRef.current = walk; + }, [accept, walk]); + useIsoMorphicEffect(() => { + if (!container) + return; + if (!enabled) + return; + let ownerDocument = getOwnerDocument(container); + if (!ownerDocument) + return; + let accept2 = acceptRef.current; + let walk2 = walkRef.current; + let acceptNode = Object.assign((node) => accept2(node), { acceptNode: accept2 }); + let walker = ownerDocument.createTreeWalker( + container, + NodeFilter.SHOW_ELEMENT, + acceptNode, + // @ts-expect-error This `false` is a simple small fix for older browsers + false + ); + while (walker.nextNode()) + walk2(walker.currentNode); + }, [container, enabled, acceptRef, walkRef]); +} + +// src/utils/calculate-active-index.ts +function assertNever(x) { + throw new Error("Unexpected object: " + x); +} +function calculateActiveIndex(action, resolvers) { + let items = resolvers.resolveItems(); + if (items.length <= 0) + return null; + let currentActiveIndex = resolvers.resolveActiveIndex(); + let activeIndex = currentActiveIndex != null ? currentActiveIndex : -1; + let nextActiveIndex = (() => { + switch (action.focus) { + case 0 /* First */: + return items.findIndex((item) => !resolvers.resolveDisabled(item)); + case 1 /* Previous */: { + let idx = items.slice().reverse().findIndex((item, idx2, all) => { + if (activeIndex !== -1 && all.length - idx2 - 1 >= activeIndex) + return false; + return !resolvers.resolveDisabled(item); + }); + if (idx === -1) + return idx; + return items.length - 1 - idx; } - if (target.childNodes.length <= 0) { - (_a3 = target.parentElement) == null ? void 0 : _a3.removeChild(target); + case 2 /* Next */: + return items.findIndex((item, idx) => { + if (idx <= activeIndex) + return false; + return !resolvers.resolveDisabled(item); + }); + case 3 /* Last */: { + let idx = items.slice().reverse().findIndex((item) => !resolvers.resolveDisabled(item)); + if (idx === -1) + return idx; + return items.length - 1 - idx; + } + case 4 /* Specific */: + return items.findIndex((item) => resolvers.resolveId(item) === action.id); + case 5 /* Nothing */: + return null; + default: + assertNever(action); + } + })(); + return nextActiveIndex === -1 ? currentActiveIndex : nextActiveIndex; +} + +// src/utils/render.ts +var import_react14 = __webpack_require__(/*! react */ "react"); + +// src/utils/class-names.ts +function classNames(...classes) { + return classes.filter(Boolean).join(" "); +} + +// src/utils/render.ts +function render({ + ourProps, + theirProps, + slot, + defaultTag, + features, + visible = true, + name +}) { + let props = mergeProps(theirProps, ourProps); + if (visible) + return _render(props, slot, defaultTag, name); + let featureFlags = features != null ? features : 0 /* None */; + if (featureFlags & 2 /* Static */) { + let { static: isStatic = false, ...rest } = props; + if (isStatic) + return _render(rest, slot, defaultTag, name); + } + if (featureFlags & 1 /* RenderStrategy */) { + let { unmount = true, ...rest } = props; + let strategy = unmount ? 0 /* Unmount */ : 1 /* Hidden */; + return match(strategy, { + [0 /* Unmount */]() { + return null; + }, + [1 /* Hidden */]() { + return _render( + { ...rest, ...{ hidden: true, style: { display: "none" } } }, + slot, + defaultTag, + name + ); } }); - if (!ready) - return null; - let ourProps = { ref: portalRef }; - return !target || !element ? null : (0, import_react_dom.createPortal)( - render({ - ourProps, - theirProps, - defaultTag: DEFAULT_PORTAL_TAG, - name: "Portal" - }), - element - ); } - var DEFAULT_GROUP_TAG = import_react27.Fragment; - var PortalGroupContext = (0, import_react27.createContext)(null); - function GroupFn(props, ref) { - let { target, ...theirProps } = props; - let groupRef = useSyncRefs(ref); - let ourProps = { ref: groupRef }; - return /* @__PURE__ */ import_react27.default.createElement(PortalGroupContext.Provider, { value: target }, render({ - ourProps, - theirProps, - defaultTag: DEFAULT_GROUP_TAG, - name: "Popover.Group" - })); + return _render(props, slot, defaultTag, name); +} +function _render(props, slot = {}, tag, name) { + let { + as: Component = tag, + children, + refName = "ref", + ...rest + } = omit(props, ["unmount", "static"]); + let refRelatedProps = props.ref !== void 0 ? { [refName]: props.ref } : {}; + let resolvedChildren = typeof children === "function" ? children(slot) : children; + if ("className" in rest && rest.className && typeof rest.className === "function") { + rest.className = rest.className(slot); + } + let dataAttributes = {}; + if (slot) { + let exposeState = false; + let states = []; + for (let [k, v] of Object.entries(slot)) { + if (typeof v === "boolean") { + exposeState = true; + } + if (v === true) { + states.push(k); + } + } + if (exposeState) + dataAttributes[`data-headlessui-state`] = states.join(" "); + } + if (Component === import_react14.Fragment) { + if (Object.keys(compact(rest)).length > 0) { + if (!(0, import_react14.isValidElement)(resolvedChildren) || Array.isArray(resolvedChildren) && resolvedChildren.length > 1) { + throw new Error( + [ + 'Passing props on "Fragment"!', + "", + `The current component <${name} /> is rendering a "Fragment".`, + `However we need to passthrough the following props:`, + Object.keys(rest).map((line) => ` - ${line}`).join("\n"), + "", + "You can apply a few solutions:", + [ + 'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".', + "Render a single element as the child so that we can forward the props onto that element." + ].map((line) => ` - ${line}`).join("\n") + ].join("\n") + ); + } + let childProps = resolvedChildren.props; + let newClassName = typeof (childProps == null ? void 0 : childProps.className) === "function" ? (...args) => classNames(childProps == null ? void 0 : childProps.className(...args), rest.className) : classNames(childProps == null ? void 0 : childProps.className, rest.className); + let classNameProps = newClassName ? { className: newClassName } : {}; + return (0, import_react14.cloneElement)( + resolvedChildren, + Object.assign( + {}, + // Filter out undefined values so that they don't override the existing values + mergeProps(resolvedChildren.props, compact(omit(rest, ["ref"]))), + dataAttributes, + refRelatedProps, + mergeRefs(resolvedChildren.ref, refRelatedProps.ref), + classNameProps + ) + ); + } } - var PortalParentContext = (0, import_react27.createContext)(null); - function useNestedPortals() { - let parent = (0, import_react27.useContext)(PortalParentContext); - let portals = (0, import_react27.useRef)([]); - let register = useEvent((portal) => { - portals.current.push(portal); - if (parent) - parent.register(portal); - return () => unregister(portal); - }); - let unregister = useEvent((portal) => { - let idx = portals.current.indexOf(portal); - if (idx !== -1) - portals.current.splice(idx, 1); - if (parent) - parent.unregister(portal); - }); - let api = (0, import_react27.useMemo)( - () => ({ register, unregister, portals }), - [register, unregister, portals] - ); - return [ - portals, - (0, import_react27.useMemo)(() => { - return function PortalWrapper({ children }) { - return /* @__PURE__ */ import_react27.default.createElement(PortalParentContext.Provider, { value: api }, children); - }; - }, [api]) - ]; + return (0, import_react14.createElement)( + Component, + Object.assign( + {}, + omit(rest, ["ref"]), + Component !== import_react14.Fragment && refRelatedProps, + Component !== import_react14.Fragment && dataAttributes + ), + resolvedChildren + ); +} +function mergeRefs(...refs) { + return { + ref: refs.every((ref) => ref == null) ? void 0 : (value) => { + for (let ref of refs) { + if (ref == null) + continue; + if (typeof ref === "function") + ref(value); + else + ref.current = value; + } + } + }; +} +function mergeProps(...listOfProps) { + var _a3; + if (listOfProps.length === 0) + return {}; + if (listOfProps.length === 1) + return listOfProps[0]; + let target = {}; + let eventHandlers = {}; + for (let props of listOfProps) { + for (let prop in props) { + if (prop.startsWith("on") && typeof props[prop] === "function") { + (_a3 = eventHandlers[prop]) != null ? _a3 : eventHandlers[prop] = []; + eventHandlers[prop].push(props[prop]); + } else { + target[prop] = props[prop]; + } + } } - var PortalRoot = forwardRefWithAs(PortalFn); - var Group = forwardRefWithAs(GroupFn); - var Portal = Object.assign(PortalRoot, { Group }); - - // src/components/description/description.tsx - var import_react28 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var DescriptionContext = (0, import_react28.createContext)(null); - function useDescriptionContext() { - let context = (0, import_react28.useContext)(DescriptionContext); - if (context === null) { - let err = new Error( - "You used a component, but it is not inside a relevant parent." - ); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDescriptionContext); - throw err; - } - return context; - } - function useDescriptions() { - let [descriptionIds, setDescriptionIds] = (0, import_react28.useState)([]); - return [ - // The actual id's as string or undefined - descriptionIds.length > 0 ? descriptionIds.join(" ") : void 0, - // The provider component - (0, import_react28.useMemo)(() => { - return function DescriptionProvider(props) { - let register = useEvent((value) => { - setDescriptionIds((existing) => [...existing, value]); - return () => setDescriptionIds((existing) => { - let clone = existing.slice(); - let idx = clone.indexOf(value); - if (idx !== -1) - clone.splice(idx, 1); - return clone; - }); - }); - let contextBag = (0, import_react28.useMemo)( - () => ({ register, slot: props.slot, name: props.name, props: props.props }), - [register, props.slot, props.name, props.props] - ); - return /* @__PURE__ */ import_react28.default.createElement(DescriptionContext.Provider, { value: contextBag }, props.children); - }; - }, [setDescriptionIds]) - ]; + if (target.disabled || target["aria-disabled"]) { + return Object.assign( + target, + // Set all event listeners that we collected to `undefined`. This is + // important because of the `cloneElement` from above, which merges the + // existing and new props, they don't just override therefore we have to + // explicitly nullify them. + Object.fromEntries(Object.keys(eventHandlers).map((eventName) => [eventName, void 0])) + ); } - var DEFAULT_DESCRIPTION_TAG = "p"; - function DescriptionFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-description-${internalId}`, ...theirProps } = props; - let context = useDescriptionContext(); - let descriptionRef = useSyncRefs(ref); - useIsoMorphicEffect(() => context.register(id), [id, context.register]); - let ourProps = { ref: descriptionRef, ...context.props, id }; - return render({ - ourProps, - theirProps, - slot: context.slot || {}, - defaultTag: DEFAULT_DESCRIPTION_TAG, - name: context.name || "Description" + for (let eventName in eventHandlers) { + Object.assign(target, { + [eventName](event, ...args) { + let handlers = eventHandlers[eventName]; + for (let handler of handlers) { + if ((event instanceof Event || (event == null ? void 0 : event.nativeEvent) instanceof Event) && event.defaultPrevented) { + return; + } + handler(event, ...args); + } + } }); } - var DescriptionRoot = forwardRefWithAs(DescriptionFn); - var Description = Object.assign(DescriptionRoot, { - // - }); - - // src/internal/stack-context.tsx - var import_react29 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var StackContext = (0, import_react29.createContext)(() => { + return target; +} +function forwardRefWithAs(component) { + var _a3; + return Object.assign((0, import_react14.forwardRef)(component), { + displayName: (_a3 = component.displayName) != null ? _a3 : component.name }); - StackContext.displayName = "StackContext"; - function useStackContext() { - return (0, import_react29.useContext)(StackContext); - } - function StackProvider({ - children, - onUpdate, - type, - element, - enabled - }) { - let parentUpdate = useStackContext(); - let notify = useEvent((...args) => { - onUpdate == null ? void 0 : onUpdate(...args); - parentUpdate(...args); - }); - useIsoMorphicEffect(() => { - let shouldNotify = enabled === void 0 || enabled === true; - shouldNotify && notify(0 /* Add */, type, element); - return () => { - shouldNotify && notify(1 /* Remove */, type, element); - }; - }, [notify, type, element, enabled]); - return /* @__PURE__ */ import_react29.default.createElement(StackContext.Provider, { value: notify }, children); +} +function compact(object) { + let clone = Object.assign({}, object); + for (let key in clone) { + if (clone[key] === void 0) + delete clone[key]; + } + return clone; +} +function omit(object, keysToOmit = []) { + let clone = Object.assign({}, object); + for (let key of keysToOmit) { + if (key in clone) + delete clone[key]; + } + return clone; +} + +// src/utils/bugs.ts +function isDisabledReactIssue7711(element) { + let parent = element.parentElement; + let legend = null; + while (parent && !(parent instanceof HTMLFieldSetElement)) { + if (parent instanceof HTMLLegendElement) + legend = parent; + parent = parent.parentElement; + } + let isParentDisabled = (parent == null ? void 0 : parent.getAttribute("disabled")) === ""; + if (isParentDisabled && isFirstLegend(legend)) + return false; + return isParentDisabled; +} +function isFirstLegend(element) { + if (!element) + return false; + let previous = element.previousElementSibling; + while (previous !== null) { + if (previous instanceof HTMLLegendElement) + return false; + previous = previous.previousElementSibling; } - - // src/use-sync-external-store-shim/index.ts - var React11 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/use-sync-external-store-shim/useSyncExternalStoreShimClient.ts - var React10 = __toESM(__webpack_require__(/*! react */ "react"), 1); - function isPolyfill(x, y) { - return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; - } - var is = typeof Object.is === "function" ? Object.is : isPolyfill; - var { useState: useState8, useEffect: useEffect14, useLayoutEffect: useLayoutEffect2, useDebugValue } = React10; - var didWarnOld18Alpha = false; - var didWarnUncachedGetSnapshot = false; - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - if (true) { - if (!didWarnOld18Alpha) { - if ("startTransition" in React10) { - didWarnOld18Alpha = true; - console.error( - "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." - ); - } - } + return true; +} + +// src/utils/form.ts +function objectToFormEntries(source = {}, parentKey = null, entries = []) { + for (let [key, value] of Object.entries(source)) { + append(entries, composeKey(parentKey, key), value); + } + return entries; +} +function composeKey(parent, key) { + return parent ? parent + "[" + key + "]" : key; +} +function append(entries, key, value) { + if (Array.isArray(value)) { + for (let [subkey, subvalue] of value.entries()) { + append(entries, composeKey(key, subkey.toString()), subvalue); + } + } else if (value instanceof Date) { + entries.push([key, value.toISOString()]); + } else if (typeof value === "boolean") { + entries.push([key, value ? "1" : "0"]); + } else if (typeof value === "string") { + entries.push([key, value]); + } else if (typeof value === "number") { + entries.push([key, `${value}`]); + } else if (value === null || value === void 0) { + entries.push([key, ""]); + } else { + objectToFormEntries(value, key, entries); + } +} +function attemptSubmit(element) { + var _a3; + let form = (_a3 = element == null ? void 0 : element.form) != null ? _a3 : element.closest("form"); + if (!form) + return; + for (let element2 of form.elements) { + if (element2.tagName === "INPUT" && element2.type === "submit" || element2.tagName === "BUTTON" && element2.type === "submit" || element2.nodeName === "INPUT" && element2.type === "image") { + element2.click(); + return; } - const value = getSnapshot(); - if (true) { - if (!didWarnUncachedGetSnapshot) { - const cachedValue = getSnapshot(); - if (!is(value, cachedValue)) { - console.error("The result of getSnapshot should be cached to avoid an infinite loop"); - didWarnUncachedGetSnapshot = true; - } - } + } +} + +// src/internal/hidden.tsx +var DEFAULT_VISUALLY_HIDDEN_TAG = "div"; +function VisuallyHidden(props, ref) { + let { features = 1 /* None */, ...theirProps } = props; + let ourProps = { + ref, + "aria-hidden": (features & 2 /* Focusable */) === 2 /* Focusable */ ? true : void 0, + style: { + position: "fixed", + top: 1, + left: 1, + width: 1, + height: 0, + padding: 0, + margin: -1, + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + borderWidth: "0", + ...(features & 4 /* Hidden */) === 4 /* Hidden */ && !((features & 2 /* Focusable */) === 2 /* Focusable */) && { display: "none" } } - const [{ inst }, forceUpdate] = useState8({ inst: { value, getSnapshot } }); - useLayoutEffect2(() => { - inst.value = value; - inst.getSnapshot = getSnapshot; - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); + }; + return render({ + ourProps, + theirProps, + slot: {}, + defaultTag: DEFAULT_VISUALLY_HIDDEN_TAG, + name: "Hidden" + }); +} +var Hidden = forwardRefWithAs(VisuallyHidden); + +// src/internal/open-closed.tsx +var import_react15 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var Context = (0, import_react15.createContext)(null); +Context.displayName = "OpenClosedContext"; +function useOpenClosed() { + return (0, import_react15.useContext)(Context); +} +function OpenClosedProvider({ value, children }) { + return /* @__PURE__ */ import_react15.default.createElement(Context.Provider, { value }, children); +} + +// src/hooks/use-controllable.ts +var import_react16 = __webpack_require__(/*! react */ "react"); +function useControllable(controlledValue, onChange, defaultValue) { + let [internalValue, setInternalValue] = (0, import_react16.useState)(defaultValue); + let isControlled = controlledValue !== void 0; + let wasControlled = (0, import_react16.useRef)(isControlled); + let didWarnOnUncontrolledToControlled = (0, import_react16.useRef)(false); + let didWarnOnControlledToUncontrolled = (0, import_react16.useRef)(false); + if (isControlled && !wasControlled.current && !didWarnOnUncontrolledToControlled.current) { + didWarnOnUncontrolledToControlled.current = true; + wasControlled.current = isControlled; + console.error( + "A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen." + ); + } else if (!isControlled && wasControlled.current && !didWarnOnControlledToUncontrolled.current) { + didWarnOnControlledToUncontrolled.current = true; + wasControlled.current = isControlled; + console.error( + "A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen." + ); + } + return [ + isControlled ? controlledValue : internalValue, + useEvent((value) => { + if (isControlled) { + return onChange == null ? void 0 : onChange(value); + } else { + setInternalValue(value); + return onChange == null ? void 0 : onChange(value); } - }, [subscribe, value, getSnapshot]); - useEffect14(() => { - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); + }) + ]; +} + +// src/hooks/use-watch.ts +var import_react17 = __webpack_require__(/*! react */ "react"); +function useWatch(cb, dependencies) { + let track = (0, import_react17.useRef)([]); + let action = useEvent(cb); + (0, import_react17.useEffect)(() => { + let oldValues = [...track.current]; + for (let [idx, value] of dependencies.entries()) { + if (track.current[idx] !== value) { + let returnValue = action(dependencies, oldValues); + track.current = dependencies; + return returnValue; + } + } + }, [action, ...dependencies]); +} + +// src/hooks/use-tracked-pointer.ts +var import_react18 = __webpack_require__(/*! react */ "react"); +function eventToPosition(evt) { + return [evt.screenX, evt.screenY]; +} +function useTrackedPointer() { + let lastPos = (0, import_react18.useRef)([-1, -1]); + return { + wasMoved(evt) { + if (false) {} + let newPos = eventToPosition(evt); + if (lastPos.current[0] === newPos[0] && lastPos.current[1] === newPos[1]) { + return false; } - const handleStoreChange = () => { - if (checkIfSnapshotChanged(inst)) { - forceUpdate({ inst }); - } - }; - return subscribe(handleStoreChange); - }, [subscribe]); - useDebugValue(value); - return value; - } - function checkIfSnapshotChanged(inst) { - const latestGetSnapshot = inst.getSnapshot; - const prevValue = inst.value; - try { - const nextValue = latestGetSnapshot(); - return !is(prevValue, nextValue); - } catch (error) { + lastPos.current = newPos; return true; + }, + update(evt) { + lastPos.current = eventToPosition(evt); } + }; +} + +// src/utils/platform.ts +function isIOS() { + return ( + // Check if it is an iPhone + /iPhone/gi.test(window.navigator.platform) || // Check if it is an iPad. iPad reports itself as "MacIntel", but we can check if it is a touch + // screen. Let's hope that Apple doesn't release a touch screen Mac (or maybe this would then + // work as expected 🤔). + /Mac/gi.test(window.navigator.platform) && window.navigator.maxTouchPoints > 0 + ); +} +function isAndroid() { + return /Android/gi.test(window.navigator.userAgent); +} +function isMobile() { + return isIOS() || isAndroid(); +} + +// src/components/combobox/combobox.tsx +function adjustOrderedState(state, adjustment = (i) => i) { + let currentActiveOption = state.activeOptionIndex !== null ? state.options[state.activeOptionIndex] : null; + let sortedOptions = sortByDomNode( + adjustment(state.options.slice()), + (option) => option.dataRef.current.domRef.current + ); + let adjustedActiveOptionIndex = currentActiveOption ? sortedOptions.indexOf(currentActiveOption) : null; + if (adjustedActiveOptionIndex === -1) { + adjustedActiveOptionIndex = null; } - - // src/use-sync-external-store-shim/useSyncExternalStoreShimServer.ts - function useSyncExternalStore2(subscribe, getSnapshot, getServerSnapshot) { - return getSnapshot(); - } - - // src/use-sync-external-store-shim/index.ts - var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); - var isServerEnvironment = !canUseDOM; - var shim = isServerEnvironment ? useSyncExternalStore2 : useSyncExternalStore; - var useSyncExternalStore3 = "useSyncExternalStore" in React11 ? ((r) => r.useSyncExternalStore)(React11) : shim; - - // src/hooks/use-store.ts - function useStore(store) { - return useSyncExternalStore3(store.subscribe, store.getSnapshot, store.getSnapshot); - } - - // src/utils/store.ts - function createStore(initial, actions) { - let state = initial(); - let listeners = /* @__PURE__ */ new Set(); - return { - getSnapshot() { - return state; - }, - subscribe(onChange) { - listeners.add(onChange); - return () => listeners.delete(onChange); - }, - dispatch(key, ...args) { - let newState = actions[key].call(state, ...args); - if (newState) { - state = newState; - listeners.forEach((listener) => listener()); - } + return { + options: sortedOptions, + activeOptionIndex: adjustedActiveOptionIndex + }; +} +var reducers = { + [1 /* CloseCombobox */](state) { + var _a3; + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) + return state; + if (state.comboboxState === 1 /* Closed */) + return state; + return { ...state, activeOptionIndex: null, comboboxState: 1 /* Closed */ }; + }, + [0 /* OpenCombobox */](state) { + var _a3; + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) + return state; + if (state.comboboxState === 0 /* Open */) + return state; + let activeOptionIndex = state.activeOptionIndex; + if (state.dataRef.current) { + let { isSelected } = state.dataRef.current; + let optionIdx = state.options.findIndex((option) => isSelected(option.dataRef.current.value)); + if (optionIdx !== -1) { + activeOptionIndex = optionIdx; } - }; - } - - // src/hooks/document-overflow/adjust-scrollbar-padding.ts - function adjustScrollbarPadding() { - let scrollbarWidthBefore; - return { - before({ doc }) { - var _a3; - let documentElement = doc.documentElement; - let ownerWindow = (_a3 = doc.defaultView) != null ? _a3 : window; - scrollbarWidthBefore = ownerWindow.innerWidth - documentElement.clientWidth; - }, - after({ doc, d }) { - let documentElement = doc.documentElement; - let scrollbarWidthAfter = documentElement.clientWidth - documentElement.offsetWidth; - let scrollbarWidth = scrollbarWidthBefore - scrollbarWidthAfter; - d.style(documentElement, "paddingRight", `${scrollbarWidth}px`); + } + return { ...state, comboboxState: 0 /* Open */, activeOptionIndex }; + }, + [2 /* GoToOption */](state, action) { + var _a3, _b, _c, _d; + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.disabled) + return state; + if (((_b = state.dataRef.current) == null ? void 0 : _b.optionsRef.current) && !((_c = state.dataRef.current) == null ? void 0 : _c.optionsPropsRef.current.static) && state.comboboxState === 1 /* Closed */) { + return state; + } + let adjustedState = adjustOrderedState(state); + if (adjustedState.activeOptionIndex === null) { + let localActiveOptionIndex = adjustedState.options.findIndex( + (option) => !option.dataRef.current.disabled + ); + if (localActiveOptionIndex !== -1) { + adjustedState.activeOptionIndex = localActiveOptionIndex; } - }; - } - - // src/hooks/document-overflow/handle-ios-locking.ts - function handleIOSLocking() { - if (!isIOS()) { - return {}; } - let scrollPosition; + let activeOptionIndex = calculateActiveIndex(action, { + resolveItems: () => adjustedState.options, + resolveActiveIndex: () => adjustedState.activeOptionIndex, + resolveId: (item) => item.id, + resolveDisabled: (item) => item.dataRef.current.disabled + }); return { - before() { - scrollPosition = window.pageYOffset; - }, - after({ doc, d, meta }) { - function inAllowedContainer(el) { - return meta.containers.flatMap((resolve) => resolve()).some((container) => container.contains(el)); - } - d.style(doc.body, "marginTop", `-${scrollPosition}px`); - window.scrollTo(0, 0); - let scrollToElement = null; - d.addEventListener( - doc, - "click", - (e) => { - if (!(e.target instanceof HTMLElement)) { - return; - } - try { - let anchor = e.target.closest("a"); - if (!anchor) - return; - let { hash } = new URL(anchor.href); - let el = doc.querySelector(hash); - if (el && !inAllowedContainer(el)) { - scrollToElement = el; - } - } catch (err) { - } - }, - true - ); - d.addEventListener( - doc, - "touchmove", - (e) => { - if (e.target instanceof HTMLElement && !inAllowedContainer(e.target)) { - e.preventDefault(); - } - }, - { passive: false } - ); - d.add(() => { - window.scrollTo(0, window.pageYOffset + scrollPosition); - if (scrollToElement && scrollToElement.isConnected) { - scrollToElement.scrollIntoView({ block: "nearest" }); - scrollToElement = null; - } - }); + ...state, + ...adjustedState, + activeOptionIndex, + activationTrigger: (_d = action.trigger) != null ? _d : 1 /* Other */ + }; + }, + [3 /* RegisterOption */]: (state, action) => { + var _a3, _b; + let option = { id: action.id, dataRef: action.dataRef }; + let adjustedState = adjustOrderedState(state, (options) => [...options, option]); + if (state.activeOptionIndex === null) { + if ((_a3 = state.dataRef.current) == null ? void 0 : _a3.isSelected(action.dataRef.current.value)) { + adjustedState.activeOptionIndex = adjustedState.options.indexOf(option); } + } + let nextState = { + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */ }; - } - - // src/hooks/document-overflow/prevent-scroll.ts - function preventScroll() { + if (((_b = state.dataRef.current) == null ? void 0 : _b.__demoMode) && state.dataRef.current.value === void 0) { + nextState.activeOptionIndex = 0; + } + return nextState; + }, + [4 /* UnregisterOption */]: (state, action) => { + let adjustedState = adjustOrderedState(state, (options) => { + let idx = options.findIndex((a) => a.id === action.id); + if (idx !== -1) + options.splice(idx, 1); + return options; + }); return { - before({ doc, d }) { - d.style(doc.documentElement, "overflow", "hidden"); - } + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */ + }; + }, + [5 /* RegisterLabel */]: (state, action) => { + return { + ...state, + labelId: action.id }; } - - // src/hooks/document-overflow/overflow-store.ts - function buildMeta(fns) { - let tmp = {}; - for (let fn of fns) { - Object.assign(tmp, fn(tmp)); +}; +var ComboboxActionsContext = (0, import_react19.createContext)(null); +ComboboxActionsContext.displayName = "ComboboxActionsContext"; +function useActions(component) { + let context = (0, import_react19.useContext)(ComboboxActionsContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useActions); + throw err; + } + return context; +} +var ComboboxDataContext = (0, import_react19.createContext)(null); +ComboboxDataContext.displayName = "ComboboxDataContext"; +function useData(component) { + let context = (0, import_react19.useContext)(ComboboxDataContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useData); + throw err; + } + return context; +} +function stateReducer(state, action) { + return match(action.type, reducers, state, action); +} +var DEFAULT_COMBOBOX_TAG = import_react19.Fragment; +function ComboboxFn(props, ref) { + let { + value: controlledValue, + defaultValue, + onChange: controlledOnChange, + form: formName, + name, + by = (a, z) => a === z, + disabled = false, + __demoMode = false, + nullable = false, + multiple = false, + ...theirProps + } = props; + let [value = multiple ? [] : void 0, theirOnChange] = useControllable( + controlledValue, + controlledOnChange, + defaultValue + ); + let [state, dispatch] = (0, import_react19.useReducer)(stateReducer, { + dataRef: (0, import_react19.createRef)(), + comboboxState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + options: [], + activeOptionIndex: null, + activationTrigger: 1 /* Other */, + labelId: null + }); + let defaultToFirstOption = (0, import_react19.useRef)(false); + let optionsPropsRef = (0, import_react19.useRef)({ static: false, hold: false }); + let labelRef = (0, import_react19.useRef)(null); + let inputRef = (0, import_react19.useRef)(null); + let buttonRef = (0, import_react19.useRef)(null); + let optionsRef = (0, import_react19.useRef)(null); + let compare = useEvent( + // @ts-expect-error Eventually we'll want to tackle this, but for now this will do. + typeof by === "string" ? (a, z) => { + let property = by; + return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]); + } : by + ); + let isSelected = (0, import_react19.useCallback)( + (compareValue) => match(data.mode, { + [1 /* Multi */]: () => value.some((option) => compare(option, compareValue)), + [0 /* Single */]: () => compare(value, compareValue) + }), + [value] + ); + let data = (0, import_react19.useMemo)( + () => ({ + ...state, + optionsPropsRef, + labelRef, + inputRef, + buttonRef, + optionsRef, + value, + defaultValue, + disabled, + mode: multiple ? 1 /* Multi */ : 0 /* Single */, + get activeOptionIndex() { + if (defaultToFirstOption.current && state.activeOptionIndex === null && state.options.length > 0) { + let localActiveOptionIndex = state.options.findIndex( + (option) => !option.dataRef.current.disabled + ); + if (localActiveOptionIndex !== -1) { + return localActiveOptionIndex; + } + } + return state.activeOptionIndex; + }, + compare, + isSelected, + nullable, + __demoMode + }), + [value, defaultValue, disabled, multiple, nullable, __demoMode, state] + ); + let lastActiveOption = (0, import_react19.useRef)( + data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null + ); + (0, import_react19.useEffect)(() => { + let currentActiveOption = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex] : null; + if (lastActiveOption.current !== currentActiveOption) { + lastActiveOption.current = currentActiveOption; } - return tmp; - } - var overflows = createStore(() => /* @__PURE__ */ new Map(), { - PUSH(doc, meta) { + }); + useIsoMorphicEffect(() => { + state.dataRef.current = data; + }, [data]); + useOutsideClick( + [data.buttonRef, data.inputRef, data.optionsRef], + () => actions.closeCombobox(), + data.comboboxState === 0 /* Open */ + ); + let slot = (0, import_react19.useMemo)( + () => ({ + open: data.comboboxState === 0 /* Open */, + disabled, + activeIndex: data.activeOptionIndex, + activeOption: data.activeOptionIndex === null ? null : data.options[data.activeOptionIndex].dataRef.current.value, + value + }), + [data, disabled, value] + ); + let selectOption = useEvent((id) => { + let option = data.options.find((item) => item.id === id); + if (!option) + return; + onChange(option.dataRef.current.value); + }); + let selectActiveOption = useEvent(() => { + if (data.activeOptionIndex !== null) { + let { dataRef, id } = data.options[data.activeOptionIndex]; + onChange(dataRef.current.value); + actions.goToOption(4 /* Specific */, id); + } + }); + let openCombobox = useEvent(() => { + dispatch({ type: 0 /* OpenCombobox */ }); + defaultToFirstOption.current = true; + }); + let closeCombobox = useEvent(() => { + dispatch({ type: 1 /* CloseCombobox */ }); + defaultToFirstOption.current = false; + }); + let goToOption = useEvent((focus, id, trigger) => { + defaultToFirstOption.current = false; + if (focus === 4 /* Specific */) { + return dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id, trigger }); + } + return dispatch({ type: 2 /* GoToOption */, focus, trigger }); + }); + let registerOption = useEvent((id, dataRef) => { + dispatch({ type: 3 /* RegisterOption */, id, dataRef }); + return () => { var _a3; - let entry = (_a3 = this.get(doc)) != null ? _a3 : { - doc, - count: 0, - d: disposables(), - meta: /* @__PURE__ */ new Set() - }; - entry.count++; - entry.meta.add(meta); - this.set(doc, entry); - return this; - }, - POP(doc, meta) { - let entry = this.get(doc); - if (entry) { - entry.count--; - entry.meta.delete(meta); + if (((_a3 = lastActiveOption.current) == null ? void 0 : _a3.id) === id) { + defaultToFirstOption.current = true; } - return this; + dispatch({ type: 4 /* UnregisterOption */, id }); + }; + }); + let registerLabel = useEvent((id) => { + dispatch({ type: 5 /* RegisterLabel */, id }); + return () => dispatch({ type: 5 /* RegisterLabel */, id: null }); + }); + let onChange = useEvent((value2) => { + return match(data.mode, { + [0 /* Single */]() { + return theirOnChange == null ? void 0 : theirOnChange(value2); + }, + [1 /* Multi */]() { + let copy = data.value.slice(); + let idx = copy.findIndex((item) => compare(item, value2)); + if (idx === -1) { + copy.push(value2); + } else { + copy.splice(idx, 1); + } + return theirOnChange == null ? void 0 : theirOnChange(copy); + } + }); + }); + let actions = (0, import_react19.useMemo)( + () => ({ + onChange, + registerOption, + registerLabel, + goToOption, + closeCombobox, + openCombobox, + selectActiveOption, + selectOption + }), + [] + ); + let ourProps = ref === null ? {} : { ref }; + let form = (0, import_react19.useRef)(null); + let d = useDisposables(); + (0, import_react19.useEffect)(() => { + if (!form.current) + return; + if (defaultValue === void 0) + return; + d.addEventListener(form.current, "reset", () => { + onChange(defaultValue); + }); + }, [ + form, + onChange + /* Explicitly ignoring `defaultValue` */ + ]); + return /* @__PURE__ */ import_react19.default.createElement(ComboboxActionsContext.Provider, { value: actions }, /* @__PURE__ */ import_react19.default.createElement(ComboboxDataContext.Provider, { value: data }, /* @__PURE__ */ import_react19.default.createElement( + OpenClosedProvider, + { + value: match(data.comboboxState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) }, - SCROLL_PREVENT({ doc, d, meta }) { - let ctx = { - doc, - d, - meta: buildMeta(meta) - }; - let steps = [ - handleIOSLocking(), - adjustScrollbarPadding(), - preventScroll() - ]; - steps.forEach(({ before }) => before == null ? void 0 : before(ctx)); - steps.forEach(({ after }) => after == null ? void 0 : after(ctx)); + name != null && value != null && objectToFormEntries({ [name]: value }).map(([name2, value2], idx) => /* @__PURE__ */ import_react19.default.createElement( + Hidden, + { + features: 4 /* Hidden */, + ref: idx === 0 ? (element) => { + var _a3; + form.current = (_a3 = element == null ? void 0 : element.closest("form")) != null ? _a3 : null; + } : void 0, + ...compact({ + key: name2, + as: "input", + type: "hidden", + hidden: true, + readOnly: true, + form: formName, + name: name2, + value: value2 + }) + } + )), + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_COMBOBOX_TAG, + name: "Combobox" + }) + ))); +} +var DEFAULT_INPUT_TAG = "input"; +function InputFn(props, ref) { + var _a3, _b, _c, _d; + let internalId = useId(); + let { + id = `headlessui-combobox-input-${internalId}`, + onChange, + displayValue, + // @ts-ignore: We know this MAY NOT exist for a given tag but we only care when it _does_ exist. + type = "text", + ...theirProps + } = props; + let data = useData("Combobox.Input"); + let actions = useActions("Combobox.Input"); + let inputRef = useSyncRefs(data.inputRef, ref); + let isTyping = (0, import_react19.useRef)(false); + let d = useDisposables(); + let currentDisplayValue = function() { + var _a4; + if (typeof displayValue === "function" && data.value !== void 0) { + return (_a4 = displayValue(data.value)) != null ? _a4 : ""; + } else if (typeof data.value === "string") { + return data.value; + } else { + return ""; + } + }(); + useWatch( + ([currentDisplayValue2, state], [oldCurrentDisplayValue, oldState]) => { + if (isTyping.current) + return; + if (!data.inputRef.current) + return; + if (oldState === 0 /* Open */ && state === 1 /* Closed */) { + data.inputRef.current.value = currentDisplayValue2; + } else if (currentDisplayValue2 !== oldCurrentDisplayValue) { + data.inputRef.current.value = currentDisplayValue2; + } }, - SCROLL_ALLOW({ d }) { - d.dispose(); + [currentDisplayValue, data.comboboxState] + ); + useWatch( + ([newState], [oldState]) => { + if (newState === 0 /* Open */ && oldState === 1 /* Closed */) { + let input = data.inputRef.current; + if (!input) + return; + let currentValue = input.value; + let { selectionStart, selectionEnd, selectionDirection } = input; + input.value = ""; + input.value = currentValue; + if (selectionDirection !== null) { + input.setSelectionRange(selectionStart, selectionEnd, selectionDirection); + } else { + input.setSelectionRange(selectionStart, selectionEnd); + } + } }, - TEARDOWN({ doc }) { - this.delete(doc); + [data.comboboxState] + ); + let isComposing = (0, import_react19.useRef)(false); + let composedChangeEvent = (0, import_react19.useRef)(null); + let handleCompositionStart = useEvent(() => { + isComposing.current = true; + }); + let handleCompositionEnd = useEvent(() => { + d.nextFrame(() => { + isComposing.current = false; + if (composedChangeEvent.current) { + actions.openCombobox(); + onChange == null ? void 0 : onChange(composedChangeEvent.current); + composedChangeEvent.current = null; + } + }); + }); + let handleKeyDown = useEvent((event) => { + isTyping.current = true; + switch (event.key) { + case "Backspace" /* Backspace */: + case "Delete" /* Delete */: + if (data.mode !== 0 /* Single */) + return; + if (!data.nullable) + return; + let input = event.currentTarget; + d.requestAnimationFrame(() => { + if (input.value === "") { + actions.onChange(null); + if (data.optionsRef.current) { + data.optionsRef.current.scrollTop = 0; + } + actions.goToOption(5 /* Nothing */); + } + }); + break; + case "Enter" /* Enter */: + isTyping.current = false; + if (data.comboboxState !== 0 /* Open */) + return; + if (isComposing.current) + return; + event.preventDefault(); + event.stopPropagation(); + if (data.activeOptionIndex === null) { + actions.closeCombobox(); + return; + } + actions.selectActiveOption(); + if (data.mode === 0 /* Single */) { + actions.closeCombobox(); + } + break; + case "ArrowDown" /* ArrowDown */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return match(data.comboboxState, { + [0 /* Open */]: () => { + actions.goToOption(2 /* Next */); + }, + [1 /* Closed */]: () => { + actions.openCombobox(); + } + }); + case "ArrowUp" /* ArrowUp */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return match(data.comboboxState, { + [0 /* Open */]: () => { + actions.goToOption(1 /* Previous */); + }, + [1 /* Closed */]: () => { + actions.openCombobox(); + d.nextFrame(() => { + if (!data.value) { + actions.goToOption(3 /* Last */); + } + }); + } + }); + case "Home" /* Home */: + if (event.shiftKey) { + break; + } + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(0 /* First */); + case "PageUp" /* PageUp */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(0 /* First */); + case "End" /* End */: + if (event.shiftKey) { + break; + } + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(3 /* Last */); + case "PageDown" /* PageDown */: + isTyping.current = false; + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(3 /* Last */); + case "Escape" /* Escape */: + isTyping.current = false; + if (data.comboboxState !== 0 /* Open */) + return; + event.preventDefault(); + if (data.optionsRef.current && !data.optionsPropsRef.current.static) { + event.stopPropagation(); + } + return actions.closeCombobox(); + case "Tab" /* Tab */: + isTyping.current = false; + if (data.comboboxState !== 0 /* Open */) + return; + if (data.mode === 0 /* Single */) + actions.selectActiveOption(); + actions.closeCombobox(); + break; } }); - overflows.subscribe(() => { - let docs = overflows.getSnapshot(); - let styles = /* @__PURE__ */ new Map(); - for (let [doc] of docs) { - styles.set(doc, doc.documentElement.style.overflow); - } - for (let entry of docs.values()) { - let isHidden = styles.get(entry.doc) === "hidden"; - let isLocked = entry.count !== 0; - let willChange = isLocked && !isHidden || !isLocked && isHidden; - if (willChange) { - overflows.dispatch(entry.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", entry); - } - if (entry.count === 0) { - overflows.dispatch("TEARDOWN", entry); - } + let handleChange = useEvent((event) => { + if (isComposing.current) { + composedChangeEvent.current = event; + return; } + actions.openCombobox(); + onChange == null ? void 0 : onChange(event); }); - - // src/hooks/document-overflow/use-document-overflow.ts - function useDocumentOverflowLockedEffect(doc, shouldBeLocked, meta) { - let store = useStore(overflows); - let entry = doc ? store.get(doc) : void 0; - let locked = entry ? entry.count > 0 : false; - useIsoMorphicEffect(() => { - if (!doc || !shouldBeLocked) { - return; - } - overflows.dispatch("PUSH", doc, meta); - return () => overflows.dispatch("POP", doc, meta); - }, [shouldBeLocked, doc]); - return locked; - } - - // src/hooks/use-inert.tsx - var originals = /* @__PURE__ */ new Map(); - var counts = /* @__PURE__ */ new Map(); - function useInert(node, enabled = true) { - useIsoMorphicEffect(() => { - var _a3; - if (!enabled) - return; - let element = typeof node === "function" ? node() : node.current; - if (!element) - return; - function cleanup() { - var _a4; - if (!element) - return; - let count2 = (_a4 = counts.get(element)) != null ? _a4 : 1; - if (count2 === 1) - counts.delete(element); - else - counts.set(element, count2 - 1); - if (count2 !== 1) - return; - let original = originals.get(element); - if (!original) - return; - if (original["aria-hidden"] === null) - element.removeAttribute("aria-hidden"); - else - element.setAttribute("aria-hidden", original["aria-hidden"]); - element.inert = original.inert; - originals.delete(element); - } - let count = (_a3 = counts.get(element)) != null ? _a3 : 0; - counts.set(element, count + 1); - if (count !== 0) - return cleanup; - originals.set(element, { - "aria-hidden": element.getAttribute("aria-hidden"), - inert: element.inert - }); - element.setAttribute("aria-hidden", "true"); - element.inert = true; - return cleanup; - }, [node, enabled]); - } - - // src/hooks/use-root-containers.tsx - var import_react30 = __toESM(__webpack_require__(/*! react */ "react"), 1); - function useRootContainers({ - defaultContainers = [], - portals - } = {}) { - let mainTreeNodeRef = (0, import_react30.useRef)(null); - let ownerDocument = useOwnerDocument(mainTreeNodeRef); - let resolveContainers2 = useEvent(() => { - var _a3; - let containers = []; - for (let container of defaultContainers) { - if (container === null) - continue; - if (container instanceof HTMLElement) { - containers.push(container); - } else if ("current" in container && container.current instanceof HTMLElement) { - containers.push(container.current); + let handleBlur = useEvent(() => { + isTyping.current = false; + }); + let labelledby = useComputed(() => { + if (!data.labelId) + return void 0; + return [data.labelId].join(" "); + }, [data.labelId]); + let slot = (0, import_react19.useMemo)( + () => ({ open: data.comboboxState === 0 /* Open */, disabled: data.disabled }), + [data] + ); + let ourProps = { + ref: inputRef, + id, + role: "combobox", + type, + "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": data.disabled ? void 0 : data.comboboxState === 0 /* Open */, + "aria-activedescendant": data.activeOptionIndex === null ? void 0 : (_b = data.options[data.activeOptionIndex]) == null ? void 0 : _b.id, + "aria-labelledby": labelledby, + "aria-autocomplete": "list", + defaultValue: (_d = (_c = props.defaultValue) != null ? _c : data.defaultValue !== void 0 ? displayValue == null ? void 0 : displayValue(data.defaultValue) : null) != null ? _d : data.defaultValue, + disabled: data.disabled, + onCompositionStart: handleCompositionStart, + onCompositionEnd: handleCompositionEnd, + onKeyDown: handleKeyDown, + onChange: handleChange, + onBlur: handleBlur + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_INPUT_TAG, + name: "Combobox.Input" + }); +} +var DEFAULT_BUTTON_TAG = "button"; +function ButtonFn(props, ref) { + var _a3; + let data = useData("Combobox.Button"); + let actions = useActions("Combobox.Button"); + let buttonRef = useSyncRefs(data.buttonRef, ref); + let internalId = useId(); + let { id = `headlessui-combobox-button-${internalId}`, ...theirProps } = props; + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + if (data.comboboxState === 1 /* Closed */) { + actions.openCombobox(); } - } - if (portals == null ? void 0 : portals.current) { - for (let portal of portals.current) { - containers.push(portal); + return d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + }); + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + if (data.comboboxState === 1 /* Closed */) { + actions.openCombobox(); + d.nextFrame(() => { + if (!data.value) { + actions.goToOption(3 /* Last */); + } + }); } - } - for (let container of (_a3 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("html > *, body > *")) != null ? _a3 : []) { - if (container === document.body) - continue; - if (container === document.head) - continue; - if (!(container instanceof HTMLElement)) - continue; - if (container.id === "headlessui-portal-root") - continue; - if (container.contains(mainTreeNodeRef.current)) - continue; - if (containers.some((defaultContainer) => container.contains(defaultContainer))) - continue; - containers.push(container); - } - return containers; - }); - return { - resolveContainers: resolveContainers2, - contains: useEvent( - (element) => resolveContainers2().some((container) => container.contains(element)) - ), - mainTreeNodeRef, - MainTreeNode: (0, import_react30.useMemo)(() => { - return function MainTreeNode() { - return /* @__PURE__ */ import_react30.default.createElement(Hidden, { features: 4 /* Hidden */, ref: mainTreeNodeRef }); - }; - }, [mainTreeNodeRef]) - }; - } - - // src/components/dialog/dialog.tsx - var reducers2 = { - [0 /* SetTitleId */](state, action) { - if (state.titleId === action.id) - return state; - return { ...state, titleId: action.id }; + return d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + }); + case "Escape" /* Escape */: + if (data.comboboxState !== 0 /* Open */) + return; + event.preventDefault(); + if (data.optionsRef.current && !data.optionsPropsRef.current.static) { + event.stopPropagation(); + } + actions.closeCombobox(); + return d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + }); + default: + return; } - }; - var DialogContext = (0, import_react31.createContext)(null); - DialogContext.displayName = "DialogContext"; - function useDialogContext(component) { - let context = (0, import_react31.useContext)(DialogContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDialogContext); - throw err; - } - return context; - } - function useScrollLock(ownerDocument, enabled, resolveAllowedContainers = () => [document.body]) { - useDocumentOverflowLockedEffect(ownerDocument, enabled, (meta) => { - var _a3; - return { - containers: [...(_a3 = meta.containers) != null ? _a3 : [], resolveAllowedContainers] - }; + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (data.comboboxState === 0 /* Open */) { + actions.closeCombobox(); + } else { + event.preventDefault(); + actions.openCombobox(); + } + d.nextFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); }); - } - function stateReducer2(state, action) { - return match(action.type, reducers2, state, action); - } - var DEFAULT_DIALOG_TAG = "div"; - var DialogRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; - function DialogFn(props, ref) { + }); + let labelledby = useComputed(() => { + if (!data.labelId) + return void 0; + return [data.labelId, id].join(" "); + }, [data.labelId, id]); + let slot = (0, import_react19.useMemo)( + () => ({ + open: data.comboboxState === 0 /* Open */, + disabled: data.disabled, + value: data.value + }), + [data] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, data.buttonRef), + tabIndex: -1, + "aria-haspopup": "listbox", + "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": data.disabled ? void 0 : data.comboboxState === 0 /* Open */, + "aria-labelledby": labelledby, + disabled: data.disabled, + onClick: handleClick, + onKeyDown: handleKeyDown + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG, + name: "Combobox.Button" + }); +} +var DEFAULT_LABEL_TAG = "label"; +function LabelFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-combobox-label-${internalId}`, ...theirProps } = props; + let data = useData("Combobox.Label"); + let actions = useActions("Combobox.Label"); + let labelRef = useSyncRefs(data.labelRef, ref); + useIsoMorphicEffect(() => actions.registerLabel(id), [id]); + let handleClick = useEvent(() => { var _a3; - let internalId = useId(); - let { - id = `headlessui-dialog-${internalId}`, - open, - onClose, - initialFocus, - __demoMode = false, - ...theirProps - } = props; - let [nestedDialogCount, setNestedDialogCount] = (0, import_react31.useState)(0); - let usesOpenClosedState = useOpenClosed(); - if (open === void 0 && usesOpenClosedState !== null) { - open = (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - let internalDialogRef = (0, import_react31.useRef)(null); - let dialogRef = useSyncRefs(internalDialogRef, ref); - let ownerDocument = useOwnerDocument(internalDialogRef); - let hasOpen = props.hasOwnProperty("open") || usesOpenClosedState !== null; - let hasOnClose = props.hasOwnProperty("onClose"); - if (!hasOpen && !hasOnClose) { - throw new Error( - `You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.` - ); - } - if (!hasOpen) { - throw new Error( - `You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.` - ); - } - if (!hasOnClose) { - throw new Error( - `You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.` - ); - } - if (typeof open !== "boolean") { - throw new Error( - `You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${open}` - ); - } - if (typeof onClose !== "function") { - throw new Error( - `You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${onClose}` - ); + return (_a3 = data.inputRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); + }); + let slot = (0, import_react19.useMemo)( + () => ({ open: data.comboboxState === 0 /* Open */, disabled: data.disabled }), + [data] + ); + let ourProps = { ref: labelRef, id, onClick: handleClick }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_LABEL_TAG, + name: "Combobox.Label" + }); +} +var DEFAULT_OPTIONS_TAG = "ul"; +var OptionsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; +function OptionsFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-combobox-options-${internalId}`, hold = false, ...theirProps } = props; + let data = useData("Combobox.Options"); + let optionsRef = useSyncRefs(data.optionsRef, ref); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return data.comboboxState === 0 /* Open */; + })(); + useIsoMorphicEffect(() => { + var _a3; + data.optionsPropsRef.current.static = (_a3 = props.static) != null ? _a3 : false; + }, [data.optionsPropsRef, props.static]); + useIsoMorphicEffect(() => { + data.optionsPropsRef.current.hold = hold; + }, [data.optionsPropsRef, hold]); + useTreeWalker({ + container: data.optionsRef.current, + enabled: data.comboboxState === 0 /* Open */, + accept(node) { + if (node.getAttribute("role") === "option") + return NodeFilter.FILTER_REJECT; + if (node.hasAttribute("role")) + return NodeFilter.FILTER_SKIP; + return NodeFilter.FILTER_ACCEPT; + }, + walk(node) { + node.setAttribute("role", "none"); } - let dialogState = open ? 0 /* Open */ : 1 /* Closed */; - let [state, dispatch] = (0, import_react31.useReducer)(stateReducer2, { - titleId: null, - descriptionId: null, - panelRef: (0, import_react31.createRef)() - }); - let close = useEvent(() => onClose(false)); - let setTitleId = useEvent((id2) => dispatch({ type: 0 /* SetTitleId */, id: id2 })); - let ready = useServerHandoffComplete(); - let enabled = ready ? __demoMode ? false : dialogState === 0 /* Open */ : false; - let hasNestedDialogs = nestedDialogCount > 1; - let hasParentDialog = (0, import_react31.useContext)(DialogContext) !== null; - let [portals, PortalWrapper] = useNestedPortals(); - let { - resolveContainers: resolveRootContainers, - mainTreeNodeRef, - MainTreeNode - } = useRootContainers({ - portals, - defaultContainers: [(_a3 = state.panelRef.current) != null ? _a3 : internalDialogRef.current] + }); + let labelledby = useComputed( + () => { + var _a3, _b; + return (_b = data.labelId) != null ? _b : (_a3 = data.buttonRef.current) == null ? void 0 : _a3.id; + }, + [data.labelId, data.buttonRef.current] + ); + let slot = (0, import_react19.useMemo)( + () => ({ open: data.comboboxState === 0 /* Open */ }), + [data] + ); + let ourProps = { + "aria-labelledby": labelledby, + role: "listbox", + "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, + id, + ref: optionsRef + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTIONS_TAG, + features: OptionsRenderFeatures, + visible, + name: "Combobox.Options" + }); +} +var DEFAULT_OPTION_TAG = "li"; +function OptionFn(props, ref) { + var _a3, _b; + let internalId = useId(); + let { + id = `headlessui-combobox-option-${internalId}`, + disabled = false, + value, + ...theirProps + } = props; + let data = useData("Combobox.Option"); + let actions = useActions("Combobox.Option"); + let active = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex].id === id : false; + let selected = data.isSelected(value); + let internalOptionRef = (0, import_react19.useRef)(null); + let bag = useLatestValue({ + disabled, + value, + domRef: internalOptionRef, + textValue: (_b = (_a3 = internalOptionRef.current) == null ? void 0 : _a3.textContent) == null ? void 0 : _b.toLowerCase() + }); + let optionRef = useSyncRefs(ref, internalOptionRef); + let select = useEvent(() => actions.selectOption(id)); + useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); + let enableScrollIntoView = (0, import_react19.useRef)(data.__demoMode ? false : true); + useIsoMorphicEffect(() => { + if (!data.__demoMode) + return; + let d = disposables(); + d.requestAnimationFrame(() => { + enableScrollIntoView.current = true; }); - let position = !hasNestedDialogs ? "leaf" : "parent"; - let isClosing = usesOpenClosedState !== null ? (usesOpenClosedState & 4 /* Closing */) === 4 /* Closing */ : false; - let inertOthersEnabled = (() => { - if (hasParentDialog) - return false; - if (isClosing) - return false; - return enabled; - })(); - let resolveRootOfMainTreeNode = (0, import_react31.useCallback)(() => { - var _a4, _b; - return (_b = Array.from((_a4 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("body > *")) != null ? _a4 : []).find((root) => { - if (root.id === "headlessui-portal-root") - return false; - return root.contains(mainTreeNodeRef.current) && root instanceof HTMLElement; - })) != null ? _b : null; - }, [mainTreeNodeRef]); - useInert(resolveRootOfMainTreeNode, inertOthersEnabled); - let inertParentDialogs = (() => { - if (hasNestedDialogs) - return true; - return enabled; - })(); - let resolveRootOfParentDialog = (0, import_react31.useCallback)(() => { - var _a4, _b; - return (_b = Array.from((_a4 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("[data-headlessui-portal]")) != null ? _a4 : []).find( - (root) => root.contains(mainTreeNodeRef.current) && root instanceof HTMLElement - )) != null ? _b : null; - }, [mainTreeNodeRef]); - useInert(resolveRootOfParentDialog, inertParentDialogs); - let outsideClickEnabled = (() => { - if (!enabled) - return false; - if (hasNestedDialogs) - return false; - return true; - })(); - useOutsideClick(resolveRootContainers, close, outsideClickEnabled); - let escapeToCloseEnabled = (() => { - if (hasNestedDialogs) - return false; - if (dialogState !== 0 /* Open */) - return false; - return true; - })(); - useEventListener(ownerDocument == null ? void 0 : ownerDocument.defaultView, "keydown", (event) => { - if (!escapeToCloseEnabled) - return; - if (event.defaultPrevented) - return; - if (event.key !== "Escape" /* Escape */) - return; - event.preventDefault(); - event.stopPropagation(); - close(); + return d.dispose; + }, []); + useIsoMorphicEffect(() => { + if (data.comboboxState !== 0 /* Open */) + return; + if (!active) + return; + if (!enableScrollIntoView.current) + return; + if (data.activationTrigger === 0 /* Pointer */) + return; + let d = disposables(); + d.requestAnimationFrame(() => { + var _a4, _b2; + (_b2 = (_a4 = internalOptionRef.current) == null ? void 0 : _a4.scrollIntoView) == null ? void 0 : _b2.call(_a4, { block: "nearest" }); }); - let scrollLockEnabled = (() => { - if (isClosing) - return false; - if (dialogState !== 0 /* Open */) - return false; - if (hasParentDialog) - return false; - return true; - })(); - useScrollLock(ownerDocument, scrollLockEnabled, resolveRootContainers); - (0, import_react31.useEffect)(() => { - if (dialogState !== 0 /* Open */) - return; - if (!internalDialogRef.current) - return; - let observer = new ResizeObserver((entries) => { - for (let entry of entries) { - let rect = entry.target.getBoundingClientRect(); - if (rect.x === 0 && rect.y === 0 && rect.width === 0 && rect.height === 0) { - close(); - } - } + return d.dispose; + }, [ + internalOptionRef, + active, + data.comboboxState, + data.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + data.activeOptionIndex + ]); + let handleClick = useEvent((event) => { + if (disabled) + return event.preventDefault(); + select(); + if (data.mode === 0 /* Single */) { + actions.closeCombobox(); + } + if (!isMobile()) { + requestAnimationFrame(() => { + var _a4; + return (_a4 = data.inputRef.current) == null ? void 0 : _a4.focus(); }); - observer.observe(internalDialogRef.current); - return () => observer.disconnect(); - }, [dialogState, internalDialogRef, close]); - let [describedby, DescriptionProvider] = useDescriptions(); - let contextBag = (0, import_react31.useMemo)( - () => [{ dialogState, close, setTitleId }, state], - [dialogState, state, close, setTitleId] - ); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: dialogRef, - id, - role: "dialog", - "aria-modal": dialogState === 0 /* Open */ ? true : void 0, - "aria-labelledby": state.titleId, - "aria-describedby": describedby - }; - return /* @__PURE__ */ import_react31.default.createElement( - StackProvider, - { - type: "Dialog", - enabled: dialogState === 0 /* Open */, - element: internalDialogRef, - onUpdate: useEvent((message, type) => { - if (type !== "Dialog") - return; - match(message, { - [0 /* Add */]: () => setNestedDialogCount((count) => count + 1), - [1 /* Remove */]: () => setNestedDialogCount((count) => count - 1) - }); - }) - }, - /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: true }, /* @__PURE__ */ import_react31.default.createElement(Portal, null, /* @__PURE__ */ import_react31.default.createElement(DialogContext.Provider, { value: contextBag }, /* @__PURE__ */ import_react31.default.createElement(Portal.Group, { target: internalDialogRef }, /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: false }, /* @__PURE__ */ import_react31.default.createElement(DescriptionProvider, { slot, name: "Dialog.Description" }, /* @__PURE__ */ import_react31.default.createElement( - FocusTrap, - { - initialFocus, - containers: resolveRootContainers, - features: enabled ? match(position, { - parent: FocusTrap.features.RestoreFocus, - leaf: FocusTrap.features.All & ~FocusTrap.features.FocusLock - }) : FocusTrap.features.None - }, - /* @__PURE__ */ import_react31.default.createElement(PortalWrapper, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_DIALOG_TAG, - features: DialogRenderFeatures, - visible: dialogState === 0 /* Open */, - name: "Dialog" - })) - ))))))), - /* @__PURE__ */ import_react31.default.createElement(MainTreeNode, null) - ); - } - var DEFAULT_OVERLAY_TAG = "div"; - function OverlayFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-overlay-${internalId}`, ...theirProps } = props; - let [{ dialogState, close }] = useDialogContext("Dialog.Overlay"); - let overlayRef = useSyncRefs(ref); - let handleClick = useEvent((event) => { - if (event.target !== event.currentTarget) - return; - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - event.preventDefault(); - event.stopPropagation(); - close(); - }); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: overlayRef, - id, - "aria-hidden": true, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OVERLAY_TAG, - name: "Dialog.Overlay" - }); - } - var DEFAULT_BACKDROP_TAG = "div"; - function BackdropFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-backdrop-${internalId}`, ...theirProps } = props; - let [{ dialogState }, state] = useDialogContext("Dialog.Backdrop"); - let backdropRef = useSyncRefs(ref); - (0, import_react31.useEffect)(() => { - if (state.panelRef.current === null) { - throw new Error( - `A component is being used, but a component is missing.` - ); - } - }, [state.panelRef]); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { - ref: backdropRef, - id, - "aria-hidden": true - }; - return /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: true }, /* @__PURE__ */ import_react31.default.createElement(Portal, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BACKDROP_TAG, - name: "Dialog.Backdrop" - }))); - } - var DEFAULT_PANEL_TAG = "div"; - function PanelFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-panel-${internalId}`, ...theirProps } = props; - let [{ dialogState }, state] = useDialogContext("Dialog.Panel"); - let panelRef = useSyncRefs(ref, state.panelRef); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let handleClick = useEvent((event) => { - event.stopPropagation(); - }); - let ourProps = { - ref: panelRef, - id, - onClick: handleClick + } + }); + let handleFocus = useEvent(() => { + if (disabled) + return actions.goToOption(5 /* Nothing */); + actions.goToOption(4 /* Specific */, id); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (active) + return; + actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (!active) + return; + if (data.optionsPropsRef.current.hold) + return; + actions.goToOption(5 /* Nothing */); + }); + let slot = (0, import_react19.useMemo)( + () => ({ active, selected, disabled }), + [active, selected, disabled] + ); + let ourProps = { + id, + ref: optionRef, + role: "option", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + // According to the WAI-ARIA best practices, we should use aria-checked for + // multi-select,but Voice-Over disagrees. So we use aria-checked instead for + // both single and multi-select. + "aria-selected": selected, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTION_TAG, + name: "Combobox.Option" + }); +} +var ComboboxRoot = forwardRefWithAs(ComboboxFn); +var Button = forwardRefWithAs(ButtonFn); +var Input = forwardRefWithAs(InputFn); +var Label = forwardRefWithAs(LabelFn); +var Options = forwardRefWithAs(OptionsFn); +var Option = forwardRefWithAs(OptionFn); +var Combobox = Object.assign(ComboboxRoot, { Input, Button, Label, Options, Option }); + +// src/components/dialog/dialog.tsx +var import_react31 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/components/focus-trap/focus-trap.tsx +var import_react25 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/hooks/use-tab-direction.ts +var import_react20 = __webpack_require__(/*! react */ "react"); +function useTabDirection() { + let direction = (0, import_react20.useRef)(0 /* Forwards */); + useWindowEvent( + "keydown", + (event) => { + if (event.key === "Tab") { + direction.current = event.shiftKey ? 1 /* Backwards */ : 0 /* Forwards */; + } + }, + true + ); + return direction; +} + +// src/hooks/use-is-mounted.ts +var import_react21 = __webpack_require__(/*! react */ "react"); +function useIsMounted() { + let mounted = (0, import_react21.useRef)(false); + useIsoMorphicEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG, - name: "Dialog.Panel" - }); + }, []); + return mounted; +} + +// src/hooks/use-owner.ts +var import_react22 = __webpack_require__(/*! react */ "react"); +function useOwnerDocument(...args) { + return (0, import_react22.useMemo)(() => getOwnerDocument(...args), [...args]); +} + +// src/hooks/use-event-listener.ts +var import_react23 = __webpack_require__(/*! react */ "react"); +function useEventListener(element, type, listener, options) { + let listenerRef = useLatestValue(listener); + (0, import_react23.useEffect)(() => { + element = element != null ? element : window; + function handler(event) { + listenerRef.current(event); + } + element.addEventListener(type, handler, options); + return () => element.removeEventListener(type, handler, options); + }, [element, type, options]); +} + +// src/utils/document-ready.ts +function onDocumentReady(cb) { + function check() { + if (document.readyState === "loading") + return; + cb(); + document.removeEventListener("DOMContentLoaded", check); } - var DEFAULT_TITLE_TAG = "h2"; - function TitleFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-dialog-title-${internalId}`, ...theirProps } = props; - let [{ dialogState, setTitleId }] = useDialogContext("Dialog.Title"); - let titleRef = useSyncRefs(ref); - (0, import_react31.useEffect)(() => { - setTitleId(id); - return () => setTitleId(null); - }, [id, setTitleId]); - let slot = (0, import_react31.useMemo)( - () => ({ open: dialogState === 0 /* Open */ }), - [dialogState] - ); - let ourProps = { ref: titleRef, id }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_TITLE_TAG, - name: "Dialog.Title" - }); + if (typeof window !== "undefined" && typeof document !== "undefined") { + document.addEventListener("DOMContentLoaded", check); + check(); } - var DialogRoot = forwardRefWithAs(DialogFn); - var Backdrop = forwardRefWithAs(BackdropFn); - var Panel = forwardRefWithAs(PanelFn); - var Overlay = forwardRefWithAs(OverlayFn); - var Title = forwardRefWithAs(TitleFn); - var Dialog = Object.assign(DialogRoot, { - Backdrop, - Panel, - Overlay, - Title, - Description - }); - - // src/components/disclosure/disclosure.tsx - var import_react33 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/utils/start-transition.ts - var import_react32 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var _a2; - var startTransition = ( - // Prefer React's `startTransition` if it's available. - // @ts-expect-error - `startTransition` doesn't exist in React < 18. - (_a2 = import_react32.default.startTransition) != null ? _a2 : function startTransition2(cb) { - cb(); - } +} + +// src/hooks/use-on-unmount.ts +var import_react24 = __webpack_require__(/*! react */ "react"); +function useOnUnmount(cb) { + let stableCb = useEvent(cb); + let trulyUnmounted = (0, import_react24.useRef)(false); + (0, import_react24.useEffect)(() => { + trulyUnmounted.current = false; + return () => { + trulyUnmounted.current = true; + microTask(() => { + if (!trulyUnmounted.current) + return; + stableCb(); + }); + }; + }, [stableCb]); +} + +// src/components/focus-trap/focus-trap.tsx +function resolveContainers(containers) { + if (!containers) + return /* @__PURE__ */ new Set(); + if (typeof containers === "function") + return new Set(containers()); + let all = /* @__PURE__ */ new Set(); + for (let container of containers.current) { + if (container.current instanceof HTMLElement) { + all.add(container.current); + } + } + return all; +} +var DEFAULT_FOCUS_TRAP_TAG = "div"; +var Features3 = /* @__PURE__ */ ((Features4) => { + Features4[Features4["None"] = 1] = "None"; + Features4[Features4["InitialFocus"] = 2] = "InitialFocus"; + Features4[Features4["TabLock"] = 4] = "TabLock"; + Features4[Features4["FocusLock"] = 8] = "FocusLock"; + Features4[Features4["RestoreFocus"] = 16] = "RestoreFocus"; + Features4[Features4["All"] = 30] = "All"; + return Features4; +})(Features3 || {}); +function FocusTrapFn(props, ref) { + let container = (0, import_react25.useRef)(null); + let focusTrapRef = useSyncRefs(container, ref); + let { initialFocus, containers, features = 30 /* All */, ...theirProps } = props; + if (!useServerHandoffComplete()) { + features = 1 /* None */; + } + let ownerDocument = useOwnerDocument(container); + useRestoreFocus({ ownerDocument }, Boolean(features & 16 /* RestoreFocus */)); + let previousActiveElement = useInitialFocus( + { ownerDocument, container, initialFocus }, + Boolean(features & 2 /* InitialFocus */) ); - - // src/components/disclosure/disclosure.tsx - var reducers3 = { - [0 /* ToggleDisclosure */]: (state) => ({ - ...state, - disclosureState: match(state.disclosureState, { - [0 /* Open */]: 1 /* Closed */, - [1 /* Closed */]: 0 /* Open */ - }) - }), - [1 /* CloseDisclosure */]: (state) => { - if (state.disclosureState === 1 /* Closed */) - return state; - return { ...state, disclosureState: 1 /* Closed */ }; - }, - [4 /* LinkPanel */](state) { - if (state.linkedPanel === true) - return state; - return { ...state, linkedPanel: true }; - }, - [5 /* UnlinkPanel */](state) { - if (state.linkedPanel === false) - return state; - return { ...state, linkedPanel: false }; - }, - [2 /* SetButtonId */](state, action) { - if (state.buttonId === action.buttonId) - return state; - return { ...state, buttonId: action.buttonId }; - }, - [3 /* SetPanelId */](state, action) { - if (state.panelId === action.panelId) - return state; - return { ...state, panelId: action.panelId }; - } - }; - var DisclosureContext = (0, import_react33.createContext)(null); - DisclosureContext.displayName = "DisclosureContext"; - function useDisclosureContext(component) { - let context = (0, import_react33.useContext)(DisclosureContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDisclosureContext); - throw err; - } - return context; - } - var DisclosureAPIContext = (0, import_react33.createContext)(null); - DisclosureAPIContext.displayName = "DisclosureAPIContext"; - function useDisclosureAPIContext(component) { - let context = (0, import_react33.useContext)(DisclosureAPIContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useDisclosureAPIContext); - throw err; - } - return context; - } - var DisclosurePanelContext = (0, import_react33.createContext)(null); - DisclosurePanelContext.displayName = "DisclosurePanelContext"; - function useDisclosurePanelContext() { - return (0, import_react33.useContext)(DisclosurePanelContext); - } - function stateReducer3(state, action) { - return match(action.type, reducers3, state, action); - } - var DEFAULT_DISCLOSURE_TAG = import_react33.Fragment; - function DisclosureFn(props, ref) { - let { defaultOpen = false, ...theirProps } = props; - let internalDisclosureRef = (0, import_react33.useRef)(null); - let disclosureRef = useSyncRefs( - ref, - optionalRef( - (ref2) => { - internalDisclosureRef.current = ref2; + useFocusLock( + { ownerDocument, container, containers, previousActiveElement }, + Boolean(features & 8 /* FocusLock */) + ); + let direction = useTabDirection(); + let handleFocus = useEvent((e) => { + let el = container.current; + if (!el) + return; + let wrapper = false ? 0 : (cb) => cb(); + wrapper(() => { + match(direction.current, { + [0 /* Forwards */]: () => { + focusIn(el, 1 /* First */, { skipElements: [e.relatedTarget] }); }, - props.as === void 0 || // @ts-expect-error The `as` prop _can_ be a Fragment - props.as === import_react33.Fragment - ) - ); - let panelRef = (0, import_react33.useRef)(null); - let buttonRef = (0, import_react33.useRef)(null); - let reducerBag = (0, import_react33.useReducer)(stateReducer3, { - disclosureState: defaultOpen ? 0 /* Open */ : 1 /* Closed */, - linkedPanel: false, - buttonRef, - panelRef, - buttonId: null, - panelId: null + [1 /* Backwards */]: () => { + focusIn(el, 8 /* Last */, { skipElements: [e.relatedTarget] }); + } + }); }); - let [{ disclosureState, buttonId }, dispatch] = reducerBag; - let close = useEvent((focusableElement) => { - dispatch({ type: 1 /* CloseDisclosure */ }); - let ownerDocument = getOwnerDocument(internalDisclosureRef); - if (!ownerDocument) + }); + let d = useDisposables(); + let recentlyUsedTabKey = (0, import_react25.useRef)(false); + let ourProps = { + ref: focusTrapRef, + onKeyDown(e) { + if (e.key == "Tab") { + recentlyUsedTabKey.current = true; + d.requestAnimationFrame(() => { + recentlyUsedTabKey.current = false; + }); + } + }, + onBlur(e) { + let allContainers = resolveContainers(containers); + if (container.current instanceof HTMLElement) + allContainers.add(container.current); + let relatedTarget = e.relatedTarget; + if (!(relatedTarget instanceof HTMLElement)) return; - if (!buttonId) + if (relatedTarget.dataset.headlessuiFocusGuard === "true") { return; - let restoreElement = (() => { - if (!focusableElement) - return ownerDocument.getElementById(buttonId); - if (focusableElement instanceof HTMLElement) - return focusableElement; - if (focusableElement.current instanceof HTMLElement) - return focusableElement.current; - return ownerDocument.getElementById(buttonId); - })(); - restoreElement == null ? void 0 : restoreElement.focus(); - }); - let api = (0, import_react33.useMemo)(() => ({ close }), [close]); - let slot = (0, import_react33.useMemo)( - () => ({ open: disclosureState === 0 /* Open */, close }), - [disclosureState, close] - ); - let ourProps = { - ref: disclosureRef - }; - return /* @__PURE__ */ import_react33.default.createElement(DisclosureContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react33.default.createElement(DisclosureAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react33.default.createElement( - OpenClosedProvider, - { - value: match(disclosureState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_DISCLOSURE_TAG, - name: "Disclosure" - }) - ))); - } - var DEFAULT_BUTTON_TAG2 = "button"; - function ButtonFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-disclosure-button-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useDisclosureContext("Disclosure.Button"); - let panelContext = useDisclosurePanelContext(); - let isWithinPanel = panelContext === null ? false : panelContext === state.panelId; - let internalButtonRef = (0, import_react33.useRef)(null); - let buttonRef = useSyncRefs(internalButtonRef, ref, !isWithinPanel ? state.buttonRef : null); - (0, import_react33.useEffect)(() => { - if (isWithinPanel) + } + if (!contains(allContainers, relatedTarget)) { + if (recentlyUsedTabKey.current) { + focusIn( + container.current, + match(direction.current, { + [0 /* Forwards */]: () => 4 /* Next */, + [1 /* Backwards */]: () => 2 /* Previous */ + }) | 16 /* WrapAround */, + { relativeTo: e.target } + ); + } else if (e.target instanceof HTMLElement) { + focusElement(e.target); + } + } + } + }; + return /* @__PURE__ */ import_react25.default.createElement(import_react25.default.Fragment, null, Boolean(features & 4 /* TabLock */) && /* @__PURE__ */ import_react25.default.createElement( + Hidden, + { + as: "button", + type: "button", + "data-headlessui-focus-guard": true, + onFocus: handleFocus, + features: 2 /* Focusable */ + } + ), render({ + ourProps, + theirProps, + defaultTag: DEFAULT_FOCUS_TRAP_TAG, + name: "FocusTrap" + }), Boolean(features & 4 /* TabLock */) && /* @__PURE__ */ import_react25.default.createElement( + Hidden, + { + as: "button", + type: "button", + "data-headlessui-focus-guard": true, + onFocus: handleFocus, + features: 2 /* Focusable */ + } + )); +} +var FocusTrapRoot = forwardRefWithAs(FocusTrapFn); +var FocusTrap = Object.assign(FocusTrapRoot, { + features: Features3 +}); +var history = []; +onDocumentReady(() => { + function handle(e) { + if (!(e.target instanceof HTMLElement)) + return; + if (e.target === document.body) + return; + if (history[0] === e.target) + return; + history.unshift(e.target); + history = history.filter((x) => x != null && x.isConnected); + history.splice(10); + } + window.addEventListener("click", handle, { capture: true }); + window.addEventListener("mousedown", handle, { capture: true }); + window.addEventListener("focus", handle, { capture: true }); + document.body.addEventListener("click", handle, { capture: true }); + document.body.addEventListener("mousedown", handle, { capture: true }); + document.body.addEventListener("focus", handle, { capture: true }); +}); +function useRestoreElement(enabled = true) { + let localHistory = (0, import_react25.useRef)(history.slice()); + useWatch( + ([newEnabled], [oldEnabled]) => { + if (oldEnabled === true && newEnabled === false) { + microTask(() => { + localHistory.current.splice(0); + }); + } + if (oldEnabled === false && newEnabled === true) { + localHistory.current = history.slice(); + } + }, + [enabled, history, localHistory] + ); + return useEvent(() => { + var _a3; + return (_a3 = localHistory.current.find((x) => x != null && x.isConnected)) != null ? _a3 : null; + }); +} +function useRestoreFocus({ ownerDocument }, enabled) { + let getRestoreElement = useRestoreElement(enabled); + useWatch(() => { + if (enabled) + return; + if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) === (ownerDocument == null ? void 0 : ownerDocument.body)) { + focusElement(getRestoreElement()); + } + }, [enabled]); + useOnUnmount(() => { + if (!enabled) + return; + focusElement(getRestoreElement()); + }); +} +function useInitialFocus({ + ownerDocument, + container, + initialFocus +}, enabled) { + let previousActiveElement = (0, import_react25.useRef)(null); + let mounted = useIsMounted(); + useWatch(() => { + if (!enabled) + return; + let containerElement = container.current; + if (!containerElement) + return; + microTask(() => { + if (!mounted.current) { return; - dispatch({ type: 2 /* SetButtonId */, buttonId: id }); - return () => { - dispatch({ type: 2 /* SetButtonId */, buttonId: null }); - }; - }, [id, dispatch, isWithinPanel]); - let handleKeyDown = useEvent((event) => { - var _a3; - if (isWithinPanel) { - if (state.disclosureState === 1 /* Closed */) + } + let activeElement = ownerDocument == null ? void 0 : ownerDocument.activeElement; + if (initialFocus == null ? void 0 : initialFocus.current) { + if ((initialFocus == null ? void 0 : initialFocus.current) === activeElement) { + previousActiveElement.current = activeElement; return; - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* ToggleDisclosure */ }); - (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); - break; } + } else if (containerElement.contains(activeElement)) { + previousActiveElement.current = activeElement; + return; + } + if (initialFocus == null ? void 0 : initialFocus.current) { + focusElement(initialFocus.current); } else { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* ToggleDisclosure */ }); - break; + if (focusIn(containerElement, 1 /* First */) === 0 /* Error */) { + console.warn("There are no focusable elements inside the "); } } + previousActiveElement.current = ownerDocument == null ? void 0 : ownerDocument.activeElement; }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - var _a3; - if (isDisabledReactIssue7711(event.currentTarget)) + }, [enabled]); + return previousActiveElement; +} +function useFocusLock({ + ownerDocument, + container, + containers, + previousActiveElement +}, enabled) { + let mounted = useIsMounted(); + useEventListener( + ownerDocument == null ? void 0 : ownerDocument.defaultView, + "focus", + (event) => { + if (!enabled) return; - if (props.disabled) + if (!mounted.current) + return; + let allContainers = resolveContainers(containers); + if (container.current instanceof HTMLElement) + allContainers.add(container.current); + let previous = previousActiveElement.current; + if (!previous) return; - if (isWithinPanel) { - dispatch({ type: 0 /* ToggleDisclosure */ }); - (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); + let toElement = event.target; + if (toElement && toElement instanceof HTMLElement) { + if (!contains(allContainers, toElement)) { + event.preventDefault(); + event.stopPropagation(); + focusElement(previous); + } else { + previousActiveElement.current = toElement; + focusElement(toElement); + } } else { - dispatch({ type: 0 /* ToggleDisclosure */ }); + focusElement(previousActiveElement.current); } - }); - let slot = (0, import_react33.useMemo)( - () => ({ open: state.disclosureState === 0 /* Open */ }), - [state] - ); - let type = useResolveButtonType(props, internalButtonRef); - let ourProps = isWithinPanel ? { ref: buttonRef, type, onKeyDown: handleKeyDown, onClick: handleClick } : { - ref: buttonRef, - id, - type, - "aria-expanded": props.disabled ? void 0 : state.disclosureState === 0 /* Open */, - "aria-controls": state.linkedPanel ? state.panelId : void 0, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick - }; - return render({ + }, + true + ); +} +function contains(containers, element) { + for (let container of containers) { + if (container.contains(element)) + return true; + } + return false; +} + +// src/components/portal/portal.tsx +var import_react27 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var import_react_dom = __webpack_require__(/*! react-dom */ "react-dom"); + +// src/internal/portal-force-root.tsx +var import_react26 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var ForcePortalRootContext = (0, import_react26.createContext)(false); +function usePortalRoot() { + return (0, import_react26.useContext)(ForcePortalRootContext); +} +function ForcePortalRoot(props) { + return /* @__PURE__ */ import_react26.default.createElement(ForcePortalRootContext.Provider, { value: props.force }, props.children); +} + +// src/components/portal/portal.tsx +function usePortalTarget(ref) { + let forceInRoot = usePortalRoot(); + let groupTarget = (0, import_react27.useContext)(PortalGroupContext); + let ownerDocument = useOwnerDocument(ref); + let [target, setTarget] = (0, import_react27.useState)(() => { + if (!forceInRoot && groupTarget !== null) + return null; + if (env.isServer) + return null; + let existingRoot = ownerDocument == null ? void 0 : ownerDocument.getElementById("headlessui-portal-root"); + if (existingRoot) + return existingRoot; + if (ownerDocument === null) + return null; + let root = ownerDocument.createElement("div"); + root.setAttribute("id", "headlessui-portal-root"); + return ownerDocument.body.appendChild(root); + }); + (0, import_react27.useEffect)(() => { + if (target === null) + return; + if (!(ownerDocument == null ? void 0 : ownerDocument.body.contains(target))) { + ownerDocument == null ? void 0 : ownerDocument.body.appendChild(target); + } + }, [target, ownerDocument]); + (0, import_react27.useEffect)(() => { + if (forceInRoot) + return; + if (groupTarget === null) + return; + setTarget(groupTarget.current); + }, [groupTarget, setTarget, forceInRoot]); + return target; +} +var DEFAULT_PORTAL_TAG = import_react27.Fragment; +function PortalFn(props, ref) { + let theirProps = props; + let internalPortalRootRef = (0, import_react27.useRef)(null); + let portalRef = useSyncRefs( + optionalRef((ref2) => { + internalPortalRootRef.current = ref2; + }), + ref + ); + let ownerDocument = useOwnerDocument(internalPortalRootRef); + let target = usePortalTarget(internalPortalRootRef); + let [element] = (0, import_react27.useState)( + () => { + var _a3; + return env.isServer ? null : (_a3 = ownerDocument == null ? void 0 : ownerDocument.createElement("div")) != null ? _a3 : null; + } + ); + let parent = (0, import_react27.useContext)(PortalParentContext); + let ready = useServerHandoffComplete(); + useIsoMorphicEffect(() => { + if (!target || !element) + return; + if (!target.contains(element)) { + element.setAttribute("data-headlessui-portal", ""); + target.appendChild(element); + } + }, [target, element]); + useIsoMorphicEffect(() => { + if (!element) + return; + if (!parent) + return; + return parent.register(element); + }, [parent, element]); + useOnUnmount(() => { + var _a3; + if (!target || !element) + return; + if (element instanceof Node && target.contains(element)) { + target.removeChild(element); + } + if (target.childNodes.length <= 0) { + (_a3 = target.parentElement) == null ? void 0 : _a3.removeChild(target); + } + }); + if (!ready) + return null; + let ourProps = { ref: portalRef }; + return !target || !element ? null : (0, import_react_dom.createPortal)( + render({ ourProps, theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG2, - name: "Disclosure.Button" - }); - } - var DEFAULT_PANEL_TAG2 = "div"; - var PanelRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; - function PanelFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-disclosure-panel-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useDisclosureContext("Disclosure.Panel"); - let { close } = useDisclosureAPIContext("Disclosure.Panel"); - let panelRef = useSyncRefs(ref, state.panelRef, (el) => { - startTransition(() => dispatch({ type: el ? 4 /* LinkPanel */ : 5 /* UnlinkPanel */ })); - }); - (0, import_react33.useEffect)(() => { - dispatch({ type: 3 /* SetPanelId */, panelId: id }); - return () => { - dispatch({ type: 3 /* SetPanelId */, panelId: null }); + defaultTag: DEFAULT_PORTAL_TAG, + name: "Portal" + }), + element + ); +} +var DEFAULT_GROUP_TAG = import_react27.Fragment; +var PortalGroupContext = (0, import_react27.createContext)(null); +function GroupFn(props, ref) { + let { target, ...theirProps } = props; + let groupRef = useSyncRefs(ref); + let ourProps = { ref: groupRef }; + return /* @__PURE__ */ import_react27.default.createElement(PortalGroupContext.Provider, { value: target }, render({ + ourProps, + theirProps, + defaultTag: DEFAULT_GROUP_TAG, + name: "Popover.Group" + })); +} +var PortalParentContext = (0, import_react27.createContext)(null); +function useNestedPortals() { + let parent = (0, import_react27.useContext)(PortalParentContext); + let portals = (0, import_react27.useRef)([]); + let register = useEvent((portal) => { + portals.current.push(portal); + if (parent) + parent.register(portal); + return () => unregister(portal); + }); + let unregister = useEvent((portal) => { + let idx = portals.current.indexOf(portal); + if (idx !== -1) + portals.current.splice(idx, 1); + if (parent) + parent.unregister(portal); + }); + let api = (0, import_react27.useMemo)( + () => ({ register, unregister, portals }), + [register, unregister, portals] + ); + return [ + portals, + (0, import_react27.useMemo)(() => { + return function PortalWrapper({ children }) { + return /* @__PURE__ */ import_react27.default.createElement(PortalParentContext.Provider, { value: api }, children); }; - }, [id, dispatch]); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return state.disclosureState === 0 /* Open */; - })(); - let slot = (0, import_react33.useMemo)( - () => ({ open: state.disclosureState === 0 /* Open */, close }), - [state, close] + }, [api]) + ]; +} +var PortalRoot = forwardRefWithAs(PortalFn); +var Group = forwardRefWithAs(GroupFn); +var Portal = Object.assign(PortalRoot, { Group }); + +// src/components/description/description.tsx +var import_react28 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var DescriptionContext = (0, import_react28.createContext)(null); +function useDescriptionContext() { + let context = (0, import_react28.useContext)(DescriptionContext); + if (context === null) { + let err = new Error( + "You used a component, but it is not inside a relevant parent." ); - let ourProps = { - ref: panelRef, - id + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDescriptionContext); + throw err; + } + return context; +} +function useDescriptions() { + let [descriptionIds, setDescriptionIds] = (0, import_react28.useState)([]); + return [ + // The actual id's as string or undefined + descriptionIds.length > 0 ? descriptionIds.join(" ") : void 0, + // The provider component + (0, import_react28.useMemo)(() => { + return function DescriptionProvider(props) { + let register = useEvent((value) => { + setDescriptionIds((existing) => [...existing, value]); + return () => setDescriptionIds((existing) => { + let clone = existing.slice(); + let idx = clone.indexOf(value); + if (idx !== -1) + clone.splice(idx, 1); + return clone; + }); + }); + let contextBag = (0, import_react28.useMemo)( + () => ({ register, slot: props.slot, name: props.name, props: props.props }), + [register, props.slot, props.name, props.props] + ); + return /* @__PURE__ */ import_react28.default.createElement(DescriptionContext.Provider, { value: contextBag }, props.children); + }; + }, [setDescriptionIds]) + ]; +} +var DEFAULT_DESCRIPTION_TAG = "p"; +function DescriptionFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-description-${internalId}`, ...theirProps } = props; + let context = useDescriptionContext(); + let descriptionRef = useSyncRefs(ref); + useIsoMorphicEffect(() => context.register(id), [id, context.register]); + let ourProps = { ref: descriptionRef, ...context.props, id }; + return render({ + ourProps, + theirProps, + slot: context.slot || {}, + defaultTag: DEFAULT_DESCRIPTION_TAG, + name: context.name || "Description" + }); +} +var DescriptionRoot = forwardRefWithAs(DescriptionFn); +var Description = Object.assign(DescriptionRoot, { + // +}); + +// src/internal/stack-context.tsx +var import_react29 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var StackContext = (0, import_react29.createContext)(() => { +}); +StackContext.displayName = "StackContext"; +function useStackContext() { + return (0, import_react29.useContext)(StackContext); +} +function StackProvider({ + children, + onUpdate, + type, + element, + enabled +}) { + let parentUpdate = useStackContext(); + let notify = useEvent((...args) => { + onUpdate == null ? void 0 : onUpdate(...args); + parentUpdate(...args); + }); + useIsoMorphicEffect(() => { + let shouldNotify = enabled === void 0 || enabled === true; + shouldNotify && notify(0 /* Add */, type, element); + return () => { + shouldNotify && notify(1 /* Remove */, type, element); }; - return /* @__PURE__ */ import_react33.default.createElement(DisclosurePanelContext.Provider, { value: state.panelId }, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG2, - features: PanelRenderFeatures, - visible, - name: "Disclosure.Panel" - })); - } - var DisclosureRoot = forwardRefWithAs(DisclosureFn); - var Button2 = forwardRefWithAs(ButtonFn2); - var Panel2 = forwardRefWithAs(PanelFn2); - var Disclosure = Object.assign(DisclosureRoot, { Button: Button2, Panel: Panel2 }); - - // src/components/listbox/listbox.tsx - var import_react35 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/hooks/use-text-value.ts - var import_react34 = __webpack_require__(/*! react */ "react"); - - // src/utils/get-text-value.ts - var emojiRegex = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; - function getTextContents(element) { - var _a3, _b; - let currentInnerText = (_a3 = element.innerText) != null ? _a3 : ""; - let copy = element.cloneNode(true); - if (!(copy instanceof HTMLElement)) { - return currentInnerText; - } - let dropped = false; - for (let child of copy.querySelectorAll('[hidden],[aria-hidden],[role="img"]')) { - child.remove(); - dropped = true; - } - let value = dropped ? (_b = copy.innerText) != null ? _b : "" : currentInnerText; - if (emojiRegex.test(value)) { - value = value.replace(emojiRegex, ""); + }, [notify, type, element, enabled]); + return /* @__PURE__ */ import_react29.default.createElement(StackContext.Provider, { value: notify }, children); +} + +// src/use-sync-external-store-shim/index.ts +var React11 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/use-sync-external-store-shim/useSyncExternalStoreShimClient.ts +var React10 = __toESM(__webpack_require__(/*! react */ "react"), 1); +function isPolyfill(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; +} +var is = typeof Object.is === "function" ? Object.is : isPolyfill; +var { useState: useState8, useEffect: useEffect14, useLayoutEffect: useLayoutEffect2, useDebugValue } = React10; +var didWarnOld18Alpha = false; +var didWarnUncachedGetSnapshot = false; +function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (true) { + if (!didWarnOld18Alpha) { + if ("startTransition" in React10) { + didWarnOld18Alpha = true; + console.error( + "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." + ); + } } - return value; } - function getTextValue(element) { - let label = element.getAttribute("aria-label"); - if (typeof label === "string") - return label.trim(); - let labelledby = element.getAttribute("aria-labelledby"); - if (labelledby) { - let labels = labelledby.split(" ").map((labelledby2) => { - let labelEl = document.getElementById(labelledby2); - if (labelEl) { - let label2 = labelEl.getAttribute("aria-label"); - if (typeof label2 === "string") - return label2.trim(); - return getTextContents(labelEl).trim(); - } - return null; - }).filter(Boolean); - if (labels.length > 0) - return labels.join(", "); + const value = getSnapshot(); + if (true) { + if (!didWarnUncachedGetSnapshot) { + const cachedValue = getSnapshot(); + if (!is(value, cachedValue)) { + console.error("The result of getSnapshot should be cached to avoid an infinite loop"); + didWarnUncachedGetSnapshot = true; + } } - return getTextContents(element).trim(); - } - - // src/hooks/use-text-value.ts - function useTextValue(element) { - let cacheKey = (0, import_react34.useRef)(""); - let cacheValue = (0, import_react34.useRef)(""); - return useEvent(() => { - let el = element.current; - if (!el) - return ""; - let currentKey = el.innerText; - if (cacheKey.current === currentKey) { - return cacheValue.current; - } - let value = getTextValue(el).trim().toLowerCase(); - cacheKey.current = currentKey; - cacheValue.current = value; - return value; - }); } - - // src/components/listbox/listbox.tsx - function adjustOrderedState2(state, adjustment = (i) => i) { - let currentActiveOption = state.activeOptionIndex !== null ? state.options[state.activeOptionIndex] : null; - let sortedOptions = sortByDomNode( - adjustment(state.options.slice()), - (option) => option.dataRef.current.domRef.current - ); - let adjustedActiveOptionIndex = currentActiveOption ? sortedOptions.indexOf(currentActiveOption) : null; - if (adjustedActiveOptionIndex === -1) { - adjustedActiveOptionIndex = null; + const [{ inst }, forceUpdate] = useState8({ inst: { value, getSnapshot } }); + useLayoutEffect2(() => { + inst.value = value; + inst.getSnapshot = getSnapshot; + if (checkIfSnapshotChanged(inst)) { + forceUpdate({ inst }); } - return { - options: sortedOptions, - activeOptionIndex: adjustedActiveOptionIndex + }, [subscribe, value, getSnapshot]); + useEffect14(() => { + if (checkIfSnapshotChanged(inst)) { + forceUpdate({ inst }); + } + const handleStoreChange = () => { + if (checkIfSnapshotChanged(inst)) { + forceUpdate({ inst }); + } }; + return subscribe(handleStoreChange); + }, [subscribe]); + useDebugValue(value); + return value; +} +function checkIfSnapshotChanged(inst) { + const latestGetSnapshot = inst.getSnapshot; + const prevValue = inst.value; + try { + const nextValue = latestGetSnapshot(); + return !is(prevValue, nextValue); + } catch (error) { + return true; } - var reducers4 = { - [1 /* CloseListbox */](state) { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - return { ...state, activeOptionIndex: null, listboxState: 1 /* Closed */ }; - }, - [0 /* OpenListbox */](state) { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 0 /* Open */) - return state; - let activeOptionIndex = state.activeOptionIndex; - let { isSelected } = state.dataRef.current; - let optionIdx = state.options.findIndex((option) => isSelected(option.dataRef.current.value)); - if (optionIdx !== -1) { - activeOptionIndex = optionIdx; - } - return { ...state, listboxState: 0 /* Open */, activeOptionIndex }; - }, - [2 /* GoToOption */](state, action) { - var _a3; - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - let adjustedState = adjustOrderedState2(state); - let activeOptionIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.options, - resolveActiveIndex: () => adjustedState.activeOptionIndex, - resolveId: (option) => option.id, - resolveDisabled: (option) => option.dataRef.current.disabled - }); - return { - ...state, - ...adjustedState, - searchQuery: "", - activeOptionIndex, - activationTrigger: (_a3 = action.trigger) != null ? _a3 : 1 /* Other */ - }; - }, - [3 /* Search */]: (state, action) => { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - let wasAlreadySearching = state.searchQuery !== ""; - let offset = wasAlreadySearching ? 0 : 1; - let searchQuery = state.searchQuery + action.value.toLowerCase(); - let reOrderedOptions = state.activeOptionIndex !== null ? state.options.slice(state.activeOptionIndex + offset).concat(state.options.slice(0, state.activeOptionIndex + offset)) : state.options; - let matchingOption = reOrderedOptions.find( - (option) => { - var _a3; - return !option.dataRef.current.disabled && ((_a3 = option.dataRef.current.textValue) == null ? void 0 : _a3.startsWith(searchQuery)); - } - ); - let matchIdx = matchingOption ? state.options.indexOf(matchingOption) : -1; - if (matchIdx === -1 || matchIdx === state.activeOptionIndex) - return { ...state, searchQuery }; - return { - ...state, - searchQuery, - activeOptionIndex: matchIdx, - activationTrigger: 1 /* Other */ - }; +} + +// src/use-sync-external-store-shim/useSyncExternalStoreShimServer.ts +function useSyncExternalStore2(subscribe, getSnapshot, getServerSnapshot) { + return getSnapshot(); +} + +// src/use-sync-external-store-shim/index.ts +var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); +var isServerEnvironment = !canUseDOM; +var shim = isServerEnvironment ? useSyncExternalStore2 : useSyncExternalStore; +var useSyncExternalStore3 = "useSyncExternalStore" in React11 ? ((r) => r.useSyncExternalStore)(React11) : shim; + +// src/hooks/use-store.ts +function useStore(store) { + return useSyncExternalStore3(store.subscribe, store.getSnapshot, store.getSnapshot); +} + +// src/utils/store.ts +function createStore(initial, actions) { + let state = initial(); + let listeners = /* @__PURE__ */ new Set(); + return { + getSnapshot() { + return state; }, - [4 /* ClearSearch */](state) { - if (state.dataRef.current.disabled) - return state; - if (state.listboxState === 1 /* Closed */) - return state; - if (state.searchQuery === "") - return state; - return { ...state, searchQuery: "" }; + subscribe(onChange) { + listeners.add(onChange); + return () => listeners.delete(onChange); }, - [5 /* RegisterOption */]: (state, action) => { - let option = { id: action.id, dataRef: action.dataRef }; - let adjustedState = adjustOrderedState2(state, (options) => [...options, option]); - if (state.activeOptionIndex === null) { - if (state.dataRef.current.isSelected(action.dataRef.current.value)) { - adjustedState.activeOptionIndex = adjustedState.options.indexOf(option); - } + dispatch(key, ...args) { + let newState = actions[key].call(state, ...args); + if (newState) { + state = newState; + listeners.forEach((listener) => listener()); } - return { ...state, ...adjustedState }; - }, - [6 /* UnregisterOption */]: (state, action) => { - let adjustedState = adjustOrderedState2(state, (options) => { - let idx = options.findIndex((a) => a.id === action.id); - if (idx !== -1) - options.splice(idx, 1); - return options; - }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; + } + }; +} + +// src/hooks/document-overflow/adjust-scrollbar-padding.ts +function adjustScrollbarPadding() { + let scrollbarWidthBefore; + return { + before({ doc }) { + var _a3; + let documentElement = doc.documentElement; + let ownerWindow = (_a3 = doc.defaultView) != null ? _a3 : window; + scrollbarWidthBefore = ownerWindow.innerWidth - documentElement.clientWidth; }, - [7 /* RegisterLabel */]: (state, action) => { - return { - ...state, - labelId: action.id - }; + after({ doc, d }) { + let documentElement = doc.documentElement; + let scrollbarWidthAfter = documentElement.clientWidth - documentElement.offsetWidth; + let scrollbarWidth = scrollbarWidthBefore - scrollbarWidthAfter; + d.style(documentElement, "paddingRight", `${scrollbarWidth}px`); } }; - var ListboxActionsContext = (0, import_react35.createContext)(null); - ListboxActionsContext.displayName = "ListboxActionsContext"; - function useActions2(component) { - let context = (0, import_react35.useContext)(ListboxActionsContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useActions2); - throw err; - } - return context; - } - var ListboxDataContext = (0, import_react35.createContext)(null); - ListboxDataContext.displayName = "ListboxDataContext"; - function useData2(component) { - let context = (0, import_react35.useContext)(ListboxDataContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useData2); - throw err; - } - return context; - } - function stateReducer4(state, action) { - return match(action.type, reducers4, state, action); - } - var DEFAULT_LISTBOX_TAG = import_react35.Fragment; - function ListboxFn(props, ref) { - let { - value: controlledValue, - defaultValue, - form: formName, - name, - onChange: controlledOnChange, - by = (a, z) => a === z, - disabled = false, - horizontal = false, - multiple = false, - ...theirProps - } = props; - const orientation = horizontal ? "horizontal" : "vertical"; - let listboxRef = useSyncRefs(ref); - let [value = multiple ? [] : void 0, theirOnChange] = useControllable( - controlledValue, - controlledOnChange, - defaultValue - ); - let [state, dispatch] = (0, import_react35.useReducer)(stateReducer4, { - dataRef: (0, import_react35.createRef)(), - listboxState: 1 /* Closed */, - options: [], - searchQuery: "", - labelId: null, - activeOptionIndex: null, - activationTrigger: 1 /* Other */ - }); - let optionsPropsRef = (0, import_react35.useRef)({ static: false, hold: false }); - let labelRef = (0, import_react35.useRef)(null); - let buttonRef = (0, import_react35.useRef)(null); - let optionsRef = (0, import_react35.useRef)(null); - let compare = useEvent( - typeof by === "string" ? (a, z) => { - let property = by; - return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]); - } : by - ); - let isSelected = (0, import_react35.useCallback)( - (compareValue) => match(data.mode, { - [1 /* Multi */]: () => value.some((option) => compare(option, compareValue)), - [0 /* Single */]: () => compare(value, compareValue) - }), - [value] - ); - let data = (0, import_react35.useMemo)( - () => ({ - ...state, - value, - disabled, - mode: multiple ? 1 /* Multi */ : 0 /* Single */, - orientation, - compare, - isSelected, - optionsPropsRef, - labelRef, - buttonRef, - optionsRef - }), - [value, disabled, multiple, state] - ); - useIsoMorphicEffect(() => { - state.dataRef.current = data; - }, [data]); - useOutsideClick( - [data.buttonRef, data.optionsRef], - (event, target) => { - var _a3; - dispatch({ type: 1 /* CloseListbox */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus(); - } - }, - data.listboxState === 0 /* Open */ - ); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */, disabled, value }), - [data, disabled, value] - ); - let selectOption = useEvent((id) => { - let option = data.options.find((item) => item.id === id); - if (!option) - return; - onChange(option.dataRef.current.value); - }); - let selectActiveOption = useEvent(() => { - if (data.activeOptionIndex !== null) { - let { dataRef, id } = data.options[data.activeOptionIndex]; - onChange(dataRef.current.value); - dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id }); - } - }); - let openListbox = useEvent(() => dispatch({ type: 0 /* OpenListbox */ })); - let closeListbox = useEvent(() => dispatch({ type: 1 /* CloseListbox */ })); - let goToOption = useEvent((focus, id, trigger) => { - if (focus === 4 /* Specific */) { - return dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id, trigger }); - } - return dispatch({ type: 2 /* GoToOption */, focus, trigger }); - }); - let registerOption = useEvent((id, dataRef) => { - dispatch({ type: 5 /* RegisterOption */, id, dataRef }); - return () => dispatch({ type: 6 /* UnregisterOption */, id }); - }); - let registerLabel = useEvent((id) => { - dispatch({ type: 7 /* RegisterLabel */, id }); - return () => dispatch({ type: 7 /* RegisterLabel */, id: null }); - }); - let onChange = useEvent((value2) => { - return match(data.mode, { - [0 /* Single */]() { - return theirOnChange == null ? void 0 : theirOnChange(value2); +} + +// src/hooks/document-overflow/handle-ios-locking.ts +function handleIOSLocking() { + if (!isIOS()) { + return {}; + } + let scrollPosition; + return { + before() { + scrollPosition = window.pageYOffset; + }, + after({ doc, d, meta }) { + function inAllowedContainer(el) { + return meta.containers.flatMap((resolve) => resolve()).some((container) => container.contains(el)); + } + d.style(doc.body, "marginTop", `-${scrollPosition}px`); + window.scrollTo(0, 0); + let scrollToElement = null; + d.addEventListener( + doc, + "click", + (e) => { + if (!(e.target instanceof HTMLElement)) { + return; + } + try { + let anchor = e.target.closest("a"); + if (!anchor) + return; + let { hash } = new URL(anchor.href); + let el = doc.querySelector(hash); + if (el && !inAllowedContainer(el)) { + scrollToElement = el; + } + } catch (err) { + } }, - [1 /* Multi */]() { - let copy = data.value.slice(); - let idx = copy.findIndex((item) => compare(item, value2)); - if (idx === -1) { - copy.push(value2); - } else { - copy.splice(idx, 1); + true + ); + d.addEventListener( + doc, + "touchmove", + (e) => { + if (e.target instanceof HTMLElement && !inAllowedContainer(e.target)) { + e.preventDefault(); } - return theirOnChange == null ? void 0 : theirOnChange(copy); + }, + { passive: false } + ); + d.add(() => { + window.scrollTo(0, window.pageYOffset + scrollPosition); + if (scrollToElement && scrollToElement.isConnected) { + scrollToElement.scrollIntoView({ block: "nearest" }); + scrollToElement = null; } }); - }); - let search = useEvent((value2) => dispatch({ type: 3 /* Search */, value: value2 })); - let clearSearch = useEvent(() => dispatch({ type: 4 /* ClearSearch */ })); - let actions = (0, import_react35.useMemo)( - () => ({ - onChange, - registerOption, - registerLabel, - goToOption, - closeListbox, - openListbox, - selectActiveOption, - selectOption, - search, - clearSearch - }), - [] - ); - let ourProps = { ref: listboxRef }; - let form = (0, import_react35.useRef)(null); - let d = useDisposables(); - (0, import_react35.useEffect)(() => { - if (!form.current) + } + }; +} + +// src/hooks/document-overflow/prevent-scroll.ts +function preventScroll() { + return { + before({ doc, d }) { + d.style(doc.documentElement, "overflow", "hidden"); + } + }; +} + +// src/hooks/document-overflow/overflow-store.ts +function buildMeta(fns) { + let tmp = {}; + for (let fn of fns) { + Object.assign(tmp, fn(tmp)); + } + return tmp; +} +var overflows = createStore(() => /* @__PURE__ */ new Map(), { + PUSH(doc, meta) { + var _a3; + let entry = (_a3 = this.get(doc)) != null ? _a3 : { + doc, + count: 0, + d: disposables(), + meta: /* @__PURE__ */ new Set() + }; + entry.count++; + entry.meta.add(meta); + this.set(doc, entry); + return this; + }, + POP(doc, meta) { + let entry = this.get(doc); + if (entry) { + entry.count--; + entry.meta.delete(meta); + } + return this; + }, + SCROLL_PREVENT({ doc, d, meta }) { + let ctx = { + doc, + d, + meta: buildMeta(meta) + }; + let steps = [ + handleIOSLocking(), + adjustScrollbarPadding(), + preventScroll() + ]; + steps.forEach(({ before }) => before == null ? void 0 : before(ctx)); + steps.forEach(({ after }) => after == null ? void 0 : after(ctx)); + }, + SCROLL_ALLOW({ d }) { + d.dispose(); + }, + TEARDOWN({ doc }) { + this.delete(doc); + } +}); +overflows.subscribe(() => { + let docs = overflows.getSnapshot(); + let styles = /* @__PURE__ */ new Map(); + for (let [doc] of docs) { + styles.set(doc, doc.documentElement.style.overflow); + } + for (let entry of docs.values()) { + let isHidden = styles.get(entry.doc) === "hidden"; + let isLocked = entry.count !== 0; + let willChange = isLocked && !isHidden || !isLocked && isHidden; + if (willChange) { + overflows.dispatch(entry.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", entry); + } + if (entry.count === 0) { + overflows.dispatch("TEARDOWN", entry); + } + } +}); + +// src/hooks/document-overflow/use-document-overflow.ts +function useDocumentOverflowLockedEffect(doc, shouldBeLocked, meta) { + let store = useStore(overflows); + let entry = doc ? store.get(doc) : void 0; + let locked = entry ? entry.count > 0 : false; + useIsoMorphicEffect(() => { + if (!doc || !shouldBeLocked) { + return; + } + overflows.dispatch("PUSH", doc, meta); + return () => overflows.dispatch("POP", doc, meta); + }, [shouldBeLocked, doc]); + return locked; +} + +// src/hooks/use-inert.tsx +var originals = /* @__PURE__ */ new Map(); +var counts = /* @__PURE__ */ new Map(); +function useInert(node, enabled = true) { + useIsoMorphicEffect(() => { + var _a3; + if (!enabled) + return; + let element = typeof node === "function" ? node() : node.current; + if (!element) + return; + function cleanup() { + var _a4; + if (!element) return; - if (defaultValue === void 0) + let count2 = (_a4 = counts.get(element)) != null ? _a4 : 1; + if (count2 === 1) + counts.delete(element); + else + counts.set(element, count2 - 1); + if (count2 !== 1) return; - d.addEventListener(form.current, "reset", () => { - onChange(defaultValue); - }); - }, [ - form, - onChange - /* Explicitly ignoring `defaultValue` */ - ]); - return /* @__PURE__ */ import_react35.default.createElement(ListboxActionsContext.Provider, { value: actions }, /* @__PURE__ */ import_react35.default.createElement(ListboxDataContext.Provider, { value: data }, /* @__PURE__ */ import_react35.default.createElement( - OpenClosedProvider, - { - value: match(data.listboxState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - name != null && value != null && objectToFormEntries({ [name]: value }).map(([name2, value2], idx) => /* @__PURE__ */ import_react35.default.createElement( - Hidden, - { - features: 4 /* Hidden */, - ref: idx === 0 ? (element) => { - var _a3; - form.current = (_a3 = element == null ? void 0 : element.closest("form")) != null ? _a3 : null; - } : void 0, - ...compact({ - key: name2, - as: "input", - type: "hidden", - hidden: true, - readOnly: true, - form: formName, - name: name2, - value: value2 - }) - } - )), - render({ ourProps, theirProps, slot, defaultTag: DEFAULT_LISTBOX_TAG, name: "Listbox" }) - ))); - } - var DEFAULT_BUTTON_TAG3 = "button"; - function ButtonFn3(props, ref) { - var _a3; - let internalId = useId(); - let { id = `headlessui-listbox-button-${internalId}`, ...theirProps } = props; - let data = useData2("Listbox.Button"); - let actions = useActions2("Listbox.Button"); - let buttonRef = useSyncRefs(data.buttonRef, ref); - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - actions.openListbox(); - d.nextFrame(() => { - if (!data.value) - actions.goToOption(0 /* First */); - }); - break; - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - actions.openListbox(); - d.nextFrame(() => { - if (!data.value) - actions.goToOption(3 /* Last */); - }); - break; - } + let original = originals.get(element); + if (!original) + return; + if (original["aria-hidden"] === null) + element.removeAttribute("aria-hidden"); + else + element.setAttribute("aria-hidden", original["aria-hidden"]); + element.inert = original.inert; + originals.delete(element); + } + let count = (_a3 = counts.get(element)) != null ? _a3 : 0; + counts.set(element, count + 1); + if (count !== 0) + return cleanup; + originals.set(element, { + "aria-hidden": element.getAttribute("aria-hidden"), + inert: element.inert }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; + element.setAttribute("aria-hidden", "true"); + element.inert = true; + return cleanup; + }, [node, enabled]); +} + +// src/hooks/use-root-containers.tsx +var import_react30 = __toESM(__webpack_require__(/*! react */ "react"), 1); +function useRootContainers({ + defaultContainers = [], + portals +} = {}) { + let mainTreeNodeRef = (0, import_react30.useRef)(null); + let ownerDocument = useOwnerDocument(mainTreeNodeRef); + let resolveContainers2 = useEvent(() => { + var _a3; + let containers = []; + for (let container of defaultContainers) { + if (container === null) + continue; + if (container instanceof HTMLElement) { + containers.push(container); + } else if ("current" in container && container.current instanceof HTMLElement) { + containers.push(container.current); } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (data.listboxState === 0 /* Open */) { - actions.closeListbox(); - d.nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - } else { - event.preventDefault(); - actions.openListbox(); + } + if (portals == null ? void 0 : portals.current) { + for (let portal of portals.current) { + containers.push(portal); } - }); - let labelledby = useComputed(() => { - if (!data.labelId) - return void 0; - return [data.labelId, id].join(" "); - }, [data.labelId, id]); - let slot = (0, import_react35.useMemo)( - () => ({ - open: data.listboxState === 0 /* Open */, - disabled: data.disabled, - value: data.value - }), - [data] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, data.buttonRef), - "aria-haspopup": "listbox", - "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": data.disabled ? void 0 : data.listboxState === 0 /* Open */, - "aria-labelledby": labelledby, - disabled: data.disabled, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick + } + for (let container of (_a3 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("html > *, body > *")) != null ? _a3 : []) { + if (container === document.body) + continue; + if (container === document.head) + continue; + if (!(container instanceof HTMLElement)) + continue; + if (container.id === "headlessui-portal-root") + continue; + if (container.contains(mainTreeNodeRef.current)) + continue; + if (containers.some((defaultContainer) => container.contains(defaultContainer))) + continue; + containers.push(container); + } + return containers; + }); + return { + resolveContainers: resolveContainers2, + contains: useEvent( + (element) => resolveContainers2().some((container) => container.contains(element)) + ), + mainTreeNodeRef, + MainTreeNode: (0, import_react30.useMemo)(() => { + return function MainTreeNode() { + return /* @__PURE__ */ import_react30.default.createElement(Hidden, { features: 4 /* Hidden */, ref: mainTreeNodeRef }); + }; + }, [mainTreeNodeRef]) + }; +} + +// src/components/dialog/dialog.tsx +var reducers2 = { + [0 /* SetTitleId */](state, action) { + if (state.titleId === action.id) + return state; + return { ...state, titleId: action.id }; + } +}; +var DialogContext = (0, import_react31.createContext)(null); +DialogContext.displayName = "DialogContext"; +function useDialogContext(component) { + let context = (0, import_react31.useContext)(DialogContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDialogContext); + throw err; + } + return context; +} +function useScrollLock(ownerDocument, enabled, resolveAllowedContainers = () => [document.body]) { + useDocumentOverflowLockedEffect(ownerDocument, enabled, (meta) => { + var _a3; + return { + containers: [...(_a3 = meta.containers) != null ? _a3 : [], resolveAllowedContainers] }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG3, - name: "Listbox.Button" - }); + }); +} +function stateReducer2(state, action) { + return match(action.type, reducers2, state, action); +} +var DEFAULT_DIALOG_TAG = "div"; +var DialogRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; +function DialogFn(props, ref) { + var _a3; + let internalId = useId(); + let { + id = `headlessui-dialog-${internalId}`, + open, + onClose, + initialFocus, + __demoMode = false, + ...theirProps + } = props; + let [nestedDialogCount, setNestedDialogCount] = (0, import_react31.useState)(0); + let usesOpenClosedState = useOpenClosed(); + if (open === void 0 && usesOpenClosedState !== null) { + open = (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + let internalDialogRef = (0, import_react31.useRef)(null); + let dialogRef = useSyncRefs(internalDialogRef, ref); + let ownerDocument = useOwnerDocument(internalDialogRef); + let hasOpen = props.hasOwnProperty("open") || usesOpenClosedState !== null; + let hasOnClose = props.hasOwnProperty("onClose"); + if (!hasOpen && !hasOnClose) { + throw new Error( + `You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.` + ); } - var DEFAULT_LABEL_TAG2 = "label"; - function LabelFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-listbox-label-${internalId}`, ...theirProps } = props; - let data = useData2("Listbox.Label"); - let actions = useActions2("Listbox.Label"); - let labelRef = useSyncRefs(data.labelRef, ref); - useIsoMorphicEffect(() => actions.registerLabel(id), [id]); - let handleClick = useEvent(() => { - var _a3; - return (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); - }); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */, disabled: data.disabled }), - [data] + if (!hasOpen) { + throw new Error( + `You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.` + ); + } + if (!hasOnClose) { + throw new Error( + `You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.` ); - let ourProps = { ref: labelRef, id, onClick: handleClick }; - return render({ + } + if (typeof open !== "boolean") { + throw new Error( + `You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${open}` + ); + } + if (typeof onClose !== "function") { + throw new Error( + `You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${onClose}` + ); + } + let dialogState = open ? 0 /* Open */ : 1 /* Closed */; + let [state, dispatch] = (0, import_react31.useReducer)(stateReducer2, { + titleId: null, + descriptionId: null, + panelRef: (0, import_react31.createRef)() + }); + let close = useEvent(() => onClose(false)); + let setTitleId = useEvent((id2) => dispatch({ type: 0 /* SetTitleId */, id: id2 })); + let ready = useServerHandoffComplete(); + let enabled = ready ? __demoMode ? false : dialogState === 0 /* Open */ : false; + let hasNestedDialogs = nestedDialogCount > 1; + let hasParentDialog = (0, import_react31.useContext)(DialogContext) !== null; + let [portals, PortalWrapper] = useNestedPortals(); + let { + resolveContainers: resolveRootContainers, + mainTreeNodeRef, + MainTreeNode + } = useRootContainers({ + portals, + defaultContainers: [(_a3 = state.panelRef.current) != null ? _a3 : internalDialogRef.current] + }); + let position = !hasNestedDialogs ? "leaf" : "parent"; + let isClosing = usesOpenClosedState !== null ? (usesOpenClosedState & 4 /* Closing */) === 4 /* Closing */ : false; + let inertOthersEnabled = (() => { + if (hasParentDialog) + return false; + if (isClosing) + return false; + return enabled; + })(); + let resolveRootOfMainTreeNode = (0, import_react31.useCallback)(() => { + var _a4, _b; + return (_b = Array.from((_a4 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("body > *")) != null ? _a4 : []).find((root) => { + if (root.id === "headlessui-portal-root") + return false; + return root.contains(mainTreeNodeRef.current) && root instanceof HTMLElement; + })) != null ? _b : null; + }, [mainTreeNodeRef]); + useInert(resolveRootOfMainTreeNode, inertOthersEnabled); + let inertParentDialogs = (() => { + if (hasNestedDialogs) + return true; + return enabled; + })(); + let resolveRootOfParentDialog = (0, import_react31.useCallback)(() => { + var _a4, _b; + return (_b = Array.from((_a4 = ownerDocument == null ? void 0 : ownerDocument.querySelectorAll("[data-headlessui-portal]")) != null ? _a4 : []).find( + (root) => root.contains(mainTreeNodeRef.current) && root instanceof HTMLElement + )) != null ? _b : null; + }, [mainTreeNodeRef]); + useInert(resolveRootOfParentDialog, inertParentDialogs); + let outsideClickEnabled = (() => { + if (!enabled) + return false; + if (hasNestedDialogs) + return false; + return true; + })(); + useOutsideClick(resolveRootContainers, close, outsideClickEnabled); + let escapeToCloseEnabled = (() => { + if (hasNestedDialogs) + return false; + if (dialogState !== 0 /* Open */) + return false; + return true; + })(); + useEventListener(ownerDocument == null ? void 0 : ownerDocument.defaultView, "keydown", (event) => { + if (!escapeToCloseEnabled) + return; + if (event.defaultPrevented) + return; + if (event.key !== "Escape" /* Escape */) + return; + event.preventDefault(); + event.stopPropagation(); + close(); + }); + let scrollLockEnabled = (() => { + if (isClosing) + return false; + if (dialogState !== 0 /* Open */) + return false; + if (hasParentDialog) + return false; + return true; + })(); + useScrollLock(ownerDocument, scrollLockEnabled, resolveRootContainers); + (0, import_react31.useEffect)(() => { + if (dialogState !== 0 /* Open */) + return; + if (!internalDialogRef.current) + return; + let observer = new ResizeObserver((entries) => { + for (let entry of entries) { + let rect = entry.target.getBoundingClientRect(); + if (rect.x === 0 && rect.y === 0 && rect.width === 0 && rect.height === 0) { + close(); + } + } + }); + observer.observe(internalDialogRef.current); + return () => observer.disconnect(); + }, [dialogState, internalDialogRef, close]); + let [describedby, DescriptionProvider] = useDescriptions(); + let contextBag = (0, import_react31.useMemo)( + () => [{ dialogState, close, setTitleId }, state], + [dialogState, state, close, setTitleId] + ); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { + ref: dialogRef, + id, + role: "dialog", + "aria-modal": dialogState === 0 /* Open */ ? true : void 0, + "aria-labelledby": state.titleId, + "aria-describedby": describedby + }; + return /* @__PURE__ */ import_react31.default.createElement( + StackProvider, + { + type: "Dialog", + enabled: dialogState === 0 /* Open */, + element: internalDialogRef, + onUpdate: useEvent((message, type) => { + if (type !== "Dialog") + return; + match(message, { + [0 /* Add */]: () => setNestedDialogCount((count) => count + 1), + [1 /* Remove */]: () => setNestedDialogCount((count) => count - 1) + }); + }) + }, + /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: true }, /* @__PURE__ */ import_react31.default.createElement(Portal, null, /* @__PURE__ */ import_react31.default.createElement(DialogContext.Provider, { value: contextBag }, /* @__PURE__ */ import_react31.default.createElement(Portal.Group, { target: internalDialogRef }, /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: false }, /* @__PURE__ */ import_react31.default.createElement(DescriptionProvider, { slot, name: "Dialog.Description" }, /* @__PURE__ */ import_react31.default.createElement( + FocusTrap, + { + initialFocus, + containers: resolveRootContainers, + features: enabled ? match(position, { + parent: FocusTrap.features.RestoreFocus, + leaf: FocusTrap.features.All & ~FocusTrap.features.FocusLock + }) : FocusTrap.features.None + }, + /* @__PURE__ */ import_react31.default.createElement(PortalWrapper, null, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_DIALOG_TAG, + features: DialogRenderFeatures, + visible: dialogState === 0 /* Open */, + name: "Dialog" + })) + ))))))), + /* @__PURE__ */ import_react31.default.createElement(MainTreeNode, null) + ); +} +var DEFAULT_OVERLAY_TAG = "div"; +function OverlayFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-dialog-overlay-${internalId}`, ...theirProps } = props; + let [{ dialogState, close }] = useDialogContext("Dialog.Overlay"); + let overlayRef = useSyncRefs(ref); + let handleClick = useEvent((event) => { + if (event.target !== event.currentTarget) + return; + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + event.preventDefault(); + event.stopPropagation(); + close(); + }); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { + ref: overlayRef, + id, + "aria-hidden": true, + onClick: handleClick + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OVERLAY_TAG, + name: "Dialog.Overlay" + }); +} +var DEFAULT_BACKDROP_TAG = "div"; +function BackdropFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-dialog-backdrop-${internalId}`, ...theirProps } = props; + let [{ dialogState }, state] = useDialogContext("Dialog.Backdrop"); + let backdropRef = useSyncRefs(ref); + (0, import_react31.useEffect)(() => { + if (state.panelRef.current === null) { + throw new Error( + `A component is being used, but a component is missing.` + ); + } + }, [state.panelRef]); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { + ref: backdropRef, + id, + "aria-hidden": true + }; + return /* @__PURE__ */ import_react31.default.createElement(ForcePortalRoot, { force: true }, /* @__PURE__ */ import_react31.default.createElement(Portal, null, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BACKDROP_TAG, + name: "Dialog.Backdrop" + }))); +} +var DEFAULT_PANEL_TAG = "div"; +function PanelFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-dialog-panel-${internalId}`, ...theirProps } = props; + let [{ dialogState }, state] = useDialogContext("Dialog.Panel"); + let panelRef = useSyncRefs(ref, state.panelRef); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let handleClick = useEvent((event) => { + event.stopPropagation(); + }); + let ourProps = { + ref: panelRef, + id, + onClick: handleClick + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG, + name: "Dialog.Panel" + }); +} +var DEFAULT_TITLE_TAG = "h2"; +function TitleFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-dialog-title-${internalId}`, ...theirProps } = props; + let [{ dialogState, setTitleId }] = useDialogContext("Dialog.Title"); + let titleRef = useSyncRefs(ref); + (0, import_react31.useEffect)(() => { + setTitleId(id); + return () => setTitleId(null); + }, [id, setTitleId]); + let slot = (0, import_react31.useMemo)( + () => ({ open: dialogState === 0 /* Open */ }), + [dialogState] + ); + let ourProps = { ref: titleRef, id }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_TITLE_TAG, + name: "Dialog.Title" + }); +} +var DialogRoot = forwardRefWithAs(DialogFn); +var Backdrop = forwardRefWithAs(BackdropFn); +var Panel = forwardRefWithAs(PanelFn); +var Overlay = forwardRefWithAs(OverlayFn); +var Title = forwardRefWithAs(TitleFn); +var Dialog = Object.assign(DialogRoot, { + Backdrop, + Panel, + Overlay, + Title, + Description +}); + +// src/components/disclosure/disclosure.tsx +var import_react33 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/utils/start-transition.ts +var import_react32 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var _a2; +var startTransition = ( + // Prefer React's `startTransition` if it's available. + // @ts-expect-error - `startTransition` doesn't exist in React < 18. + (_a2 = import_react32.default.startTransition) != null ? _a2 : function startTransition2(cb) { + cb(); + } +); + +// src/components/disclosure/disclosure.tsx +var reducers3 = { + [0 /* ToggleDisclosure */]: (state) => ({ + ...state, + disclosureState: match(state.disclosureState, { + [0 /* Open */]: 1 /* Closed */, + [1 /* Closed */]: 0 /* Open */ + }) + }), + [1 /* CloseDisclosure */]: (state) => { + if (state.disclosureState === 1 /* Closed */) + return state; + return { ...state, disclosureState: 1 /* Closed */ }; + }, + [4 /* LinkPanel */](state) { + if (state.linkedPanel === true) + return state; + return { ...state, linkedPanel: true }; + }, + [5 /* UnlinkPanel */](state) { + if (state.linkedPanel === false) + return state; + return { ...state, linkedPanel: false }; + }, + [2 /* SetButtonId */](state, action) { + if (state.buttonId === action.buttonId) + return state; + return { ...state, buttonId: action.buttonId }; + }, + [3 /* SetPanelId */](state, action) { + if (state.panelId === action.panelId) + return state; + return { ...state, panelId: action.panelId }; + } +}; +var DisclosureContext = (0, import_react33.createContext)(null); +DisclosureContext.displayName = "DisclosureContext"; +function useDisclosureContext(component) { + let context = (0, import_react33.useContext)(DisclosureContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDisclosureContext); + throw err; + } + return context; +} +var DisclosureAPIContext = (0, import_react33.createContext)(null); +DisclosureAPIContext.displayName = "DisclosureAPIContext"; +function useDisclosureAPIContext(component) { + let context = (0, import_react33.useContext)(DisclosureAPIContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useDisclosureAPIContext); + throw err; + } + return context; +} +var DisclosurePanelContext = (0, import_react33.createContext)(null); +DisclosurePanelContext.displayName = "DisclosurePanelContext"; +function useDisclosurePanelContext() { + return (0, import_react33.useContext)(DisclosurePanelContext); +} +function stateReducer3(state, action) { + return match(action.type, reducers3, state, action); +} +var DEFAULT_DISCLOSURE_TAG = import_react33.Fragment; +function DisclosureFn(props, ref) { + let { defaultOpen = false, ...theirProps } = props; + let internalDisclosureRef = (0, import_react33.useRef)(null); + let disclosureRef = useSyncRefs( + ref, + optionalRef( + (ref2) => { + internalDisclosureRef.current = ref2; + }, + props.as === void 0 || // @ts-expect-error The `as` prop _can_ be a Fragment + props.as === import_react33.Fragment + ) + ); + let panelRef = (0, import_react33.useRef)(null); + let buttonRef = (0, import_react33.useRef)(null); + let reducerBag = (0, import_react33.useReducer)(stateReducer3, { + disclosureState: defaultOpen ? 0 /* Open */ : 1 /* Closed */, + linkedPanel: false, + buttonRef, + panelRef, + buttonId: null, + panelId: null + }); + let [{ disclosureState, buttonId }, dispatch] = reducerBag; + let close = useEvent((focusableElement) => { + dispatch({ type: 1 /* CloseDisclosure */ }); + let ownerDocument = getOwnerDocument(internalDisclosureRef); + if (!ownerDocument) + return; + if (!buttonId) + return; + let restoreElement = (() => { + if (!focusableElement) + return ownerDocument.getElementById(buttonId); + if (focusableElement instanceof HTMLElement) + return focusableElement; + if (focusableElement.current instanceof HTMLElement) + return focusableElement.current; + return ownerDocument.getElementById(buttonId); + })(); + restoreElement == null ? void 0 : restoreElement.focus(); + }); + let api = (0, import_react33.useMemo)(() => ({ close }), [close]); + let slot = (0, import_react33.useMemo)( + () => ({ open: disclosureState === 0 /* Open */, close }), + [disclosureState, close] + ); + let ourProps = { + ref: disclosureRef + }; + return /* @__PURE__ */ import_react33.default.createElement(DisclosureContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react33.default.createElement(DisclosureAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react33.default.createElement( + OpenClosedProvider, + { + value: match(disclosureState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) + }, + render({ ourProps, theirProps, slot, - defaultTag: DEFAULT_LABEL_TAG2, - name: "Listbox.Label" - }); - } - var DEFAULT_OPTIONS_TAG2 = "ul"; - var OptionsRenderFeatures2 = 1 /* RenderStrategy */ | 2 /* Static */; - function OptionsFn2(props, ref) { + defaultTag: DEFAULT_DISCLOSURE_TAG, + name: "Disclosure" + }) + ))); +} +var DEFAULT_BUTTON_TAG2 = "button"; +function ButtonFn2(props, ref) { + let internalId = useId(); + let { id = `headlessui-disclosure-button-${internalId}`, ...theirProps } = props; + let [state, dispatch] = useDisclosureContext("Disclosure.Button"); + let panelContext = useDisclosurePanelContext(); + let isWithinPanel = panelContext === null ? false : panelContext === state.panelId; + let internalButtonRef = (0, import_react33.useRef)(null); + let buttonRef = useSyncRefs(internalButtonRef, ref, !isWithinPanel ? state.buttonRef : null); + (0, import_react33.useEffect)(() => { + if (isWithinPanel) + return; + dispatch({ type: 2 /* SetButtonId */, buttonId: id }); + return () => { + dispatch({ type: 2 /* SetButtonId */, buttonId: null }); + }; + }, [id, dispatch, isWithinPanel]); + let handleKeyDown = useEvent((event) => { var _a3; - let internalId = useId(); - let { id = `headlessui-listbox-options-${internalId}`, ...theirProps } = props; - let data = useData2("Listbox.Options"); - let actions = useActions2("Listbox.Options"); - let optionsRef = useSyncRefs(data.optionsRef, ref); - let d = useDisposables(); - let searchDisposables = useDisposables(); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return data.listboxState === 0 /* Open */; - })(); - (0, import_react35.useEffect)(() => { - var _a4; - let container = data.optionsRef.current; - if (!container) - return; - if (data.listboxState !== 0 /* Open */) - return; - if (container === ((_a4 = getOwnerDocument(container)) == null ? void 0 : _a4.activeElement)) + if (isWithinPanel) { + if (state.disclosureState === 1 /* Closed */) return; - container.focus({ preventScroll: true }); - }, [data.listboxState, data.optionsRef]); - let handleKeyDown = useEvent((event) => { - searchDisposables.dispose(); switch (event.key) { case " " /* Space */: - if (data.searchQuery !== "") { - event.preventDefault(); - event.stopPropagation(); - return actions.search(event.key); - } case "Enter" /* Enter */: event.preventDefault(); event.stopPropagation(); - if (data.activeOptionIndex !== null) { - let { dataRef } = data.options[data.activeOptionIndex]; - actions.onChange(dataRef.current.value); - } - if (data.mode === 0 /* Single */) { - actions.closeListbox(); - disposables().nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - } + dispatch({ type: 0 /* ToggleDisclosure */ }); + (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); break; - case match(data.orientation, { vertical: "ArrowDown" /* ArrowDown */, horizontal: "ArrowRight" /* ArrowRight */ }): - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(2 /* Next */); - case match(data.orientation, { vertical: "ArrowUp" /* ArrowUp */, horizontal: "ArrowLeft" /* ArrowLeft */ }): - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(1 /* Previous */); - case "Home" /* Home */: - case "PageUp" /* PageUp */: - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(0 /* First */); - case "End" /* End */: - case "PageDown" /* PageDown */: - event.preventDefault(); - event.stopPropagation(); - return actions.goToOption(3 /* Last */); - case "Escape" /* Escape */: - event.preventDefault(); - event.stopPropagation(); - actions.closeListbox(); - return d.nextFrame(() => { - var _a4; - return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); - }); - case "Tab" /* Tab */: + } + } else { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: event.preventDefault(); event.stopPropagation(); - break; - default: - if (event.key.length === 1) { - actions.search(event.key); - searchDisposables.setTimeout(() => actions.clearSearch(), 350); - } + dispatch({ type: 0 /* ToggleDisclosure */ }); break; } - }); - let labelledby = useComputed( - () => { - var _a4, _b, _c; - return (_c = (_a4 = data.labelRef.current) == null ? void 0 : _a4.id) != null ? _c : (_b = data.buttonRef.current) == null ? void 0 : _b.id; - }, - [data.labelRef.current, data.buttonRef.current] - ); - let slot = (0, import_react35.useMemo)( - () => ({ open: data.listboxState === 0 /* Open */ }), - [data] - ); - let ourProps = { - "aria-activedescendant": data.activeOptionIndex === null ? void 0 : (_a3 = data.options[data.activeOptionIndex]) == null ? void 0 : _a3.id, - "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, - "aria-labelledby": labelledby, - "aria-orientation": data.orientation, - id, - onKeyDown: handleKeyDown, - role: "listbox", - tabIndex: 0, - ref: optionsRef + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + var _a3; + if (isDisabledReactIssue7711(event.currentTarget)) + return; + if (props.disabled) + return; + if (isWithinPanel) { + dispatch({ type: 0 /* ToggleDisclosure */ }); + (_a3 = state.buttonRef.current) == null ? void 0 : _a3.focus(); + } else { + dispatch({ type: 0 /* ToggleDisclosure */ }); + } + }); + let slot = (0, import_react33.useMemo)( + () => ({ open: state.disclosureState === 0 /* Open */ }), + [state] + ); + let type = useResolveButtonType(props, internalButtonRef); + let ourProps = isWithinPanel ? { ref: buttonRef, type, onKeyDown: handleKeyDown, onClick: handleClick } : { + ref: buttonRef, + id, + type, + "aria-expanded": props.disabled ? void 0 : state.disclosureState === 0 /* Open */, + "aria-controls": state.linkedPanel ? state.panelId : void 0, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG2, + name: "Disclosure.Button" + }); +} +var DEFAULT_PANEL_TAG2 = "div"; +var PanelRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; +function PanelFn2(props, ref) { + let internalId = useId(); + let { id = `headlessui-disclosure-panel-${internalId}`, ...theirProps } = props; + let [state, dispatch] = useDisclosureContext("Disclosure.Panel"); + let { close } = useDisclosureAPIContext("Disclosure.Panel"); + let panelRef = useSyncRefs(ref, state.panelRef, (el) => { + startTransition(() => dispatch({ type: el ? 4 /* LinkPanel */ : 5 /* UnlinkPanel */ })); + }); + (0, import_react33.useEffect)(() => { + dispatch({ type: 3 /* SetPanelId */, panelId: id }); + return () => { + dispatch({ type: 3 /* SetPanelId */, panelId: null }); }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTIONS_TAG2, - features: OptionsRenderFeatures2, - visible, - name: "Listbox.Options" - }); - } - var DEFAULT_OPTION_TAG2 = "li"; - function OptionFn2(props, ref) { - let internalId = useId(); - let { - id = `headlessui-listbox-option-${internalId}`, - disabled = false, - value, - ...theirProps - } = props; - let data = useData2("Listbox.Option"); - let actions = useActions2("Listbox.Option"); - let active = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex].id === id : false; - let selected = data.isSelected(value); - let internalOptionRef = (0, import_react35.useRef)(null); - let getTextValue2 = useTextValue(internalOptionRef); - let bag = useLatestValue({ - disabled, - value, - domRef: internalOptionRef, - get textValue() { - return getTextValue2(); + }, [id, dispatch]); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return state.disclosureState === 0 /* Open */; + })(); + let slot = (0, import_react33.useMemo)( + () => ({ open: state.disclosureState === 0 /* Open */, close }), + [state, close] + ); + let ourProps = { + ref: panelRef, + id + }; + return /* @__PURE__ */ import_react33.default.createElement(DisclosurePanelContext.Provider, { value: state.panelId }, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG2, + features: PanelRenderFeatures, + visible, + name: "Disclosure.Panel" + })); +} +var DisclosureRoot = forwardRefWithAs(DisclosureFn); +var Button2 = forwardRefWithAs(ButtonFn2); +var Panel2 = forwardRefWithAs(PanelFn2); +var Disclosure = Object.assign(DisclosureRoot, { Button: Button2, Panel: Panel2 }); + +// src/components/listbox/listbox.tsx +var import_react35 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/hooks/use-text-value.ts +var import_react34 = __webpack_require__(/*! react */ "react"); + +// src/utils/get-text-value.ts +var emojiRegex = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; +function getTextContents(element) { + var _a3, _b; + let currentInnerText = (_a3 = element.innerText) != null ? _a3 : ""; + let copy = element.cloneNode(true); + if (!(copy instanceof HTMLElement)) { + return currentInnerText; + } + let dropped = false; + for (let child of copy.querySelectorAll('[hidden],[aria-hidden],[role="img"]')) { + child.remove(); + dropped = true; + } + let value = dropped ? (_b = copy.innerText) != null ? _b : "" : currentInnerText; + if (emojiRegex.test(value)) { + value = value.replace(emojiRegex, ""); + } + return value; +} +function getTextValue(element) { + let label = element.getAttribute("aria-label"); + if (typeof label === "string") + return label.trim(); + let labelledby = element.getAttribute("aria-labelledby"); + if (labelledby) { + let labels = labelledby.split(" ").map((labelledby2) => { + let labelEl = document.getElementById(labelledby2); + if (labelEl) { + let label2 = labelEl.getAttribute("aria-label"); + if (typeof label2 === "string") + return label2.trim(); + return getTextContents(labelEl).trim(); } + return null; + }).filter(Boolean); + if (labels.length > 0) + return labels.join(", "); + } + return getTextContents(element).trim(); +} + +// src/hooks/use-text-value.ts +function useTextValue(element) { + let cacheKey = (0, import_react34.useRef)(""); + let cacheValue = (0, import_react34.useRef)(""); + return useEvent(() => { + let el = element.current; + if (!el) + return ""; + let currentKey = el.innerText; + if (cacheKey.current === currentKey) { + return cacheValue.current; + } + let value = getTextValue(el).trim().toLowerCase(); + cacheKey.current = currentKey; + cacheValue.current = value; + return value; + }); +} + +// src/components/listbox/listbox.tsx +function adjustOrderedState2(state, adjustment = (i) => i) { + let currentActiveOption = state.activeOptionIndex !== null ? state.options[state.activeOptionIndex] : null; + let sortedOptions = sortByDomNode( + adjustment(state.options.slice()), + (option) => option.dataRef.current.domRef.current + ); + let adjustedActiveOptionIndex = currentActiveOption ? sortedOptions.indexOf(currentActiveOption) : null; + if (adjustedActiveOptionIndex === -1) { + adjustedActiveOptionIndex = null; + } + return { + options: sortedOptions, + activeOptionIndex: adjustedActiveOptionIndex + }; +} +var reducers4 = { + [1 /* CloseListbox */](state) { + if (state.dataRef.current.disabled) + return state; + if (state.listboxState === 1 /* Closed */) + return state; + return { ...state, activeOptionIndex: null, listboxState: 1 /* Closed */ }; + }, + [0 /* OpenListbox */](state) { + if (state.dataRef.current.disabled) + return state; + if (state.listboxState === 0 /* Open */) + return state; + let activeOptionIndex = state.activeOptionIndex; + let { isSelected } = state.dataRef.current; + let optionIdx = state.options.findIndex((option) => isSelected(option.dataRef.current.value)); + if (optionIdx !== -1) { + activeOptionIndex = optionIdx; + } + return { ...state, listboxState: 0 /* Open */, activeOptionIndex }; + }, + [2 /* GoToOption */](state, action) { + var _a3; + if (state.dataRef.current.disabled) + return state; + if (state.listboxState === 1 /* Closed */) + return state; + let adjustedState = adjustOrderedState2(state); + let activeOptionIndex = calculateActiveIndex(action, { + resolveItems: () => adjustedState.options, + resolveActiveIndex: () => adjustedState.activeOptionIndex, + resolveId: (option) => option.id, + resolveDisabled: (option) => option.dataRef.current.disabled }); - let optionRef = useSyncRefs(ref, internalOptionRef); - useIsoMorphicEffect(() => { - if (data.listboxState !== 0 /* Open */) - return; - if (!active) - return; - if (data.activationTrigger === 0 /* Pointer */) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a3, _b; - (_b = (_a3 = internalOptionRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); - }); - return d.dispose; - }, [ - internalOptionRef, - active, - data.listboxState, - data.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - data.activeOptionIndex - ]); - useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); - let handleClick = useEvent((event) => { - if (disabled) - return event.preventDefault(); - actions.onChange(value); - if (data.mode === 0 /* Single */) { - actions.closeListbox(); - disposables().nextFrame(() => { - var _a3; - return (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); - }); + return { + ...state, + ...adjustedState, + searchQuery: "", + activeOptionIndex, + activationTrigger: (_a3 = action.trigger) != null ? _a3 : 1 /* Other */ + }; + }, + [3 /* Search */]: (state, action) => { + if (state.dataRef.current.disabled) + return state; + if (state.listboxState === 1 /* Closed */) + return state; + let wasAlreadySearching = state.searchQuery !== ""; + let offset = wasAlreadySearching ? 0 : 1; + let searchQuery = state.searchQuery + action.value.toLowerCase(); + let reOrderedOptions = state.activeOptionIndex !== null ? state.options.slice(state.activeOptionIndex + offset).concat(state.options.slice(0, state.activeOptionIndex + offset)) : state.options; + let matchingOption = reOrderedOptions.find( + (option) => { + var _a3; + return !option.dataRef.current.disabled && ((_a3 = option.dataRef.current.textValue) == null ? void 0 : _a3.startsWith(searchQuery)); } - }); - let handleFocus = useEvent(() => { - if (disabled) - return actions.goToOption(5 /* Nothing */); - actions.goToOption(4 /* Specific */, id); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (active) - return; - actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (!active) - return; - actions.goToOption(5 /* Nothing */); - }); - let slot = (0, import_react35.useMemo)( - () => ({ active, selected, disabled }), - [active, selected, disabled] ); - let ourProps = { - id, - ref: optionRef, - role: "option", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - // According to the WAI-ARIA best practices, we should use aria-checked for - // multi-select,but Voice-Over disagrees. So we use aria-checked instead for - // both single and multi-select. - "aria-selected": selected, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave + let matchIdx = matchingOption ? state.options.indexOf(matchingOption) : -1; + if (matchIdx === -1 || matchIdx === state.activeOptionIndex) + return { ...state, searchQuery }; + return { + ...state, + searchQuery, + activeOptionIndex: matchIdx, + activationTrigger: 1 /* Other */ }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_OPTION_TAG2, - name: "Listbox.Option" + }, + [4 /* ClearSearch */](state) { + if (state.dataRef.current.disabled) + return state; + if (state.listboxState === 1 /* Closed */) + return state; + if (state.searchQuery === "") + return state; + return { ...state, searchQuery: "" }; + }, + [5 /* RegisterOption */]: (state, action) => { + let option = { id: action.id, dataRef: action.dataRef }; + let adjustedState = adjustOrderedState2(state, (options) => [...options, option]); + if (state.activeOptionIndex === null) { + if (state.dataRef.current.isSelected(action.dataRef.current.value)) { + adjustedState.activeOptionIndex = adjustedState.options.indexOf(option); + } + } + return { ...state, ...adjustedState }; + }, + [6 /* UnregisterOption */]: (state, action) => { + let adjustedState = adjustOrderedState2(state, (options) => { + let idx = options.findIndex((a) => a.id === action.id); + if (idx !== -1) + options.splice(idx, 1); + return options; }); - } - var ListboxRoot = forwardRefWithAs(ListboxFn); - var Button3 = forwardRefWithAs(ButtonFn3); - var Label2 = forwardRefWithAs(LabelFn2); - var Options2 = forwardRefWithAs(OptionsFn2); - var Option2 = forwardRefWithAs(OptionFn2); - var Listbox = Object.assign(ListboxRoot, { Button: Button3, Label: Label2, Options: Options2, Option: Option2 }); - - // src/components/menu/menu.tsx - var import_react36 = __toESM(__webpack_require__(/*! react */ "react"), 1); - function adjustOrderedState3(state, adjustment = (i) => i) { - let currentActiveItem = state.activeItemIndex !== null ? state.items[state.activeItemIndex] : null; - let sortedItems = sortByDomNode( - adjustment(state.items.slice()), - (item) => item.dataRef.current.domRef.current - ); - let adjustedActiveItemIndex = currentActiveItem ? sortedItems.indexOf(currentActiveItem) : null; - if (adjustedActiveItemIndex === -1) { - adjustedActiveItemIndex = null; - } return { - items: sortedItems, - activeItemIndex: adjustedActiveItemIndex + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */ + }; + }, + [7 /* RegisterLabel */]: (state, action) => { + return { + ...state, + labelId: action.id }; } - var reducers5 = { - [1 /* CloseMenu */](state) { - if (state.menuState === 1 /* Closed */) - return state; - return { ...state, activeItemIndex: null, menuState: 1 /* Closed */ }; - }, - [0 /* OpenMenu */](state) { - if (state.menuState === 0 /* Open */) - return state; - return { - ...state, - /* We can turn off demo mode once we re-open the `Menu` */ - __demoMode: false, - menuState: 0 /* Open */ - }; - }, - [2 /* GoToItem */]: (state, action) => { +}; +var ListboxActionsContext = (0, import_react35.createContext)(null); +ListboxActionsContext.displayName = "ListboxActionsContext"; +function useActions2(component) { + let context = (0, import_react35.useContext)(ListboxActionsContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useActions2); + throw err; + } + return context; +} +var ListboxDataContext = (0, import_react35.createContext)(null); +ListboxDataContext.displayName = "ListboxDataContext"; +function useData2(component) { + let context = (0, import_react35.useContext)(ListboxDataContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useData2); + throw err; + } + return context; +} +function stateReducer4(state, action) { + return match(action.type, reducers4, state, action); +} +var DEFAULT_LISTBOX_TAG = import_react35.Fragment; +function ListboxFn(props, ref) { + let { + value: controlledValue, + defaultValue, + form: formName, + name, + onChange: controlledOnChange, + by = (a, z) => a === z, + disabled = false, + horizontal = false, + multiple = false, + ...theirProps + } = props; + const orientation = horizontal ? "horizontal" : "vertical"; + let listboxRef = useSyncRefs(ref); + let [value = multiple ? [] : void 0, theirOnChange] = useControllable( + controlledValue, + controlledOnChange, + defaultValue + ); + let [state, dispatch] = (0, import_react35.useReducer)(stateReducer4, { + dataRef: (0, import_react35.createRef)(), + listboxState: 1 /* Closed */, + options: [], + searchQuery: "", + labelId: null, + activeOptionIndex: null, + activationTrigger: 1 /* Other */ + }); + let optionsPropsRef = (0, import_react35.useRef)({ static: false, hold: false }); + let labelRef = (0, import_react35.useRef)(null); + let buttonRef = (0, import_react35.useRef)(null); + let optionsRef = (0, import_react35.useRef)(null); + let compare = useEvent( + typeof by === "string" ? (a, z) => { + let property = by; + return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]); + } : by + ); + let isSelected = (0, import_react35.useCallback)( + (compareValue) => match(data.mode, { + [1 /* Multi */]: () => value.some((option) => compare(option, compareValue)), + [0 /* Single */]: () => compare(value, compareValue) + }), + [value] + ); + let data = (0, import_react35.useMemo)( + () => ({ + ...state, + value, + disabled, + mode: multiple ? 1 /* Multi */ : 0 /* Single */, + orientation, + compare, + isSelected, + optionsPropsRef, + labelRef, + buttonRef, + optionsRef + }), + [value, disabled, multiple, state] + ); + useIsoMorphicEffect(() => { + state.dataRef.current = data; + }, [data]); + useOutsideClick( + [data.buttonRef, data.optionsRef], + (event, target) => { var _a3; - let adjustedState = adjustOrderedState3(state); - let activeItemIndex = calculateActiveIndex(action, { - resolveItems: () => adjustedState.items, - resolveActiveIndex: () => adjustedState.activeItemIndex, - resolveId: (item) => item.id, - resolveDisabled: (item) => item.dataRef.current.disabled - }); - return { - ...state, - ...adjustedState, - searchQuery: "", - activeItemIndex, - activationTrigger: (_a3 = action.trigger) != null ? _a3 : 1 /* Other */ - }; + dispatch({ type: 1 /* CloseListbox */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus(); + } }, - [3 /* Search */]: (state, action) => { - let wasAlreadySearching = state.searchQuery !== ""; - let offset = wasAlreadySearching ? 0 : 1; - let searchQuery = state.searchQuery + action.value.toLowerCase(); - let reOrderedItems = state.activeItemIndex !== null ? state.items.slice(state.activeItemIndex + offset).concat(state.items.slice(0, state.activeItemIndex + offset)) : state.items; - let matchingItem = reOrderedItems.find( - (item) => { - var _a3; - return ((_a3 = item.dataRef.current.textValue) == null ? void 0 : _a3.startsWith(searchQuery)) && !item.dataRef.current.disabled; + data.listboxState === 0 /* Open */ + ); + let slot = (0, import_react35.useMemo)( + () => ({ open: data.listboxState === 0 /* Open */, disabled, value }), + [data, disabled, value] + ); + let selectOption = useEvent((id) => { + let option = data.options.find((item) => item.id === id); + if (!option) + return; + onChange(option.dataRef.current.value); + }); + let selectActiveOption = useEvent(() => { + if (data.activeOptionIndex !== null) { + let { dataRef, id } = data.options[data.activeOptionIndex]; + onChange(dataRef.current.value); + dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id }); + } + }); + let openListbox = useEvent(() => dispatch({ type: 0 /* OpenListbox */ })); + let closeListbox = useEvent(() => dispatch({ type: 1 /* CloseListbox */ })); + let goToOption = useEvent((focus, id, trigger) => { + if (focus === 4 /* Specific */) { + return dispatch({ type: 2 /* GoToOption */, focus: 4 /* Specific */, id, trigger }); + } + return dispatch({ type: 2 /* GoToOption */, focus, trigger }); + }); + let registerOption = useEvent((id, dataRef) => { + dispatch({ type: 5 /* RegisterOption */, id, dataRef }); + return () => dispatch({ type: 6 /* UnregisterOption */, id }); + }); + let registerLabel = useEvent((id) => { + dispatch({ type: 7 /* RegisterLabel */, id }); + return () => dispatch({ type: 7 /* RegisterLabel */, id: null }); + }); + let onChange = useEvent((value2) => { + return match(data.mode, { + [0 /* Single */]() { + return theirOnChange == null ? void 0 : theirOnChange(value2); + }, + [1 /* Multi */]() { + let copy = data.value.slice(); + let idx = copy.findIndex((item) => compare(item, value2)); + if (idx === -1) { + copy.push(value2); + } else { + copy.splice(idx, 1); } - ); - let matchIdx = matchingItem ? state.items.indexOf(matchingItem) : -1; - if (matchIdx === -1 || matchIdx === state.activeItemIndex) - return { ...state, searchQuery }; - return { - ...state, - searchQuery, - activeItemIndex: matchIdx, - activationTrigger: 1 /* Other */ - }; - }, - [4 /* ClearSearch */](state) { - if (state.searchQuery === "") - return state; - return { ...state, searchQuery: "", searchActiveItemIndex: null }; - }, - [5 /* RegisterItem */]: (state, action) => { - let adjustedState = adjustOrderedState3(state, (items) => [ - ...items, - { id: action.id, dataRef: action.dataRef } - ]); - return { ...state, ...adjustedState }; + return theirOnChange == null ? void 0 : theirOnChange(copy); + } + }); + }); + let search = useEvent((value2) => dispatch({ type: 3 /* Search */, value: value2 })); + let clearSearch = useEvent(() => dispatch({ type: 4 /* ClearSearch */ })); + let actions = (0, import_react35.useMemo)( + () => ({ + onChange, + registerOption, + registerLabel, + goToOption, + closeListbox, + openListbox, + selectActiveOption, + selectOption, + search, + clearSearch + }), + [] + ); + let ourProps = { ref: listboxRef }; + let form = (0, import_react35.useRef)(null); + let d = useDisposables(); + (0, import_react35.useEffect)(() => { + if (!form.current) + return; + if (defaultValue === void 0) + return; + d.addEventListener(form.current, "reset", () => { + onChange(defaultValue); + }); + }, [ + form, + onChange + /* Explicitly ignoring `defaultValue` */ + ]); + return /* @__PURE__ */ import_react35.default.createElement(ListboxActionsContext.Provider, { value: actions }, /* @__PURE__ */ import_react35.default.createElement(ListboxDataContext.Provider, { value: data }, /* @__PURE__ */ import_react35.default.createElement( + OpenClosedProvider, + { + value: match(data.listboxState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) }, - [6 /* UnregisterItem */]: (state, action) => { - let adjustedState = adjustOrderedState3(state, (items) => { - let idx = items.findIndex((a) => a.id === action.id); - if (idx !== -1) - items.splice(idx, 1); - return items; + name != null && value != null && objectToFormEntries({ [name]: value }).map(([name2, value2], idx) => /* @__PURE__ */ import_react35.default.createElement( + Hidden, + { + features: 4 /* Hidden */, + ref: idx === 0 ? (element) => { + var _a3; + form.current = (_a3 = element == null ? void 0 : element.closest("form")) != null ? _a3 : null; + } : void 0, + ...compact({ + key: name2, + as: "input", + type: "hidden", + hidden: true, + readOnly: true, + form: formName, + name: name2, + value: value2 + }) + } + )), + render({ ourProps, theirProps, slot, defaultTag: DEFAULT_LISTBOX_TAG, name: "Listbox" }) + ))); +} +var DEFAULT_BUTTON_TAG3 = "button"; +function ButtonFn3(props, ref) { + var _a3; + let internalId = useId(); + let { id = `headlessui-listbox-button-${internalId}`, ...theirProps } = props; + let data = useData2("Listbox.Button"); + let actions = useActions2("Listbox.Button"); + let buttonRef = useSyncRefs(data.buttonRef, ref); + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + actions.openListbox(); + d.nextFrame(() => { + if (!data.value) + actions.goToOption(0 /* First */); + }); + break; + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + actions.openListbox(); + d.nextFrame(() => { + if (!data.value) + actions.goToOption(3 /* Last */); + }); + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (data.listboxState === 0 /* Open */) { + actions.closeListbox(); + d.nextFrame(() => { + var _a4; + return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); }); - return { - ...state, - ...adjustedState, - activationTrigger: 1 /* Other */ - }; + } else { + event.preventDefault(); + actions.openListbox(); } + }); + let labelledby = useComputed(() => { + if (!data.labelId) + return void 0; + return [data.labelId, id].join(" "); + }, [data.labelId, id]); + let slot = (0, import_react35.useMemo)( + () => ({ + open: data.listboxState === 0 /* Open */, + disabled: data.disabled, + value: data.value + }), + [data] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, data.buttonRef), + "aria-haspopup": "listbox", + "aria-controls": (_a3 = data.optionsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": data.disabled ? void 0 : data.listboxState === 0 /* Open */, + "aria-labelledby": labelledby, + disabled: data.disabled, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick }; - var MenuContext = (0, import_react36.createContext)(null); - MenuContext.displayName = "MenuContext"; - function useMenuContext(component) { - let context = (0, import_react36.useContext)(MenuContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, useMenuContext); - throw err; - } - return context; - } - function stateReducer5(state, action) { - return match(action.type, reducers5, state, action); - } - var DEFAULT_MENU_TAG = import_react36.Fragment; - function MenuFn(props, ref) { - let { __demoMode = false, ...theirProps } = props; - let reducerBag = (0, import_react36.useReducer)(stateReducer5, { - __demoMode, - menuState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - buttonRef: (0, import_react36.createRef)(), - itemsRef: (0, import_react36.createRef)(), - items: [], - searchQuery: "", - activeItemIndex: null, - activationTrigger: 1 /* Other */ - }); - let [{ menuState, itemsRef, buttonRef }, dispatch] = reducerBag; - let menuRef = useSyncRefs(ref); - useOutsideClick( - [buttonRef, itemsRef], - (event, target) => { - var _a3; - dispatch({ type: 1 /* CloseMenu */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { - event.preventDefault(); - (_a3 = buttonRef.current) == null ? void 0 : _a3.focus(); - } - }, - menuState === 0 /* Open */ - ); - let close = useEvent(() => { - dispatch({ type: 1 /* CloseMenu */ }); - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: menuState === 0 /* Open */, close }), - [menuState, close] - ); - let ourProps = { ref: menuRef }; - return /* @__PURE__ */ import_react36.default.createElement(MenuContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react36.default.createElement( - OpenClosedProvider, - { - value: match(menuState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_MENU_TAG, - name: "Menu" - }) - )); - } - var DEFAULT_BUTTON_TAG4 = "button"; - function ButtonFn4(props, ref) { + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG3, + name: "Listbox.Button" + }); +} +var DEFAULT_LABEL_TAG2 = "label"; +function LabelFn2(props, ref) { + let internalId = useId(); + let { id = `headlessui-listbox-label-${internalId}`, ...theirProps } = props; + let data = useData2("Listbox.Label"); + let actions = useActions2("Listbox.Label"); + let labelRef = useSyncRefs(data.labelRef, ref); + useIsoMorphicEffect(() => actions.registerLabel(id), [id]); + let handleClick = useEvent(() => { var _a3; - let internalId = useId(); - let { id = `headlessui-menu-button-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useMenuContext("Menu.Button"); - let buttonRef = useSyncRefs(state.buttonRef, ref); - let d = useDisposables(); - let handleKeyDown = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 0 /* OpenMenu */ }); - d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ })); - break; - case "ArrowUp" /* ArrowUp */: + return (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); + }); + let slot = (0, import_react35.useMemo)( + () => ({ open: data.listboxState === 0 /* Open */, disabled: data.disabled }), + [data] + ); + let ourProps = { ref: labelRef, id, onClick: handleClick }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_LABEL_TAG2, + name: "Listbox.Label" + }); +} +var DEFAULT_OPTIONS_TAG2 = "ul"; +var OptionsRenderFeatures2 = 1 /* RenderStrategy */ | 2 /* Static */; +function OptionsFn2(props, ref) { + var _a3; + let internalId = useId(); + let { id = `headlessui-listbox-options-${internalId}`, ...theirProps } = props; + let data = useData2("Listbox.Options"); + let actions = useActions2("Listbox.Options"); + let optionsRef = useSyncRefs(data.optionsRef, ref); + let d = useDisposables(); + let searchDisposables = useDisposables(); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return data.listboxState === 0 /* Open */; + })(); + (0, import_react35.useEffect)(() => { + var _a4; + let container = data.optionsRef.current; + if (!container) + return; + if (data.listboxState !== 0 /* Open */) + return; + if (container === ((_a4 = getOwnerDocument(container)) == null ? void 0 : _a4.activeElement)) + return; + container.focus({ preventScroll: true }); + }, [data.listboxState, data.optionsRef]); + let handleKeyDown = useEvent((event) => { + searchDisposables.dispose(); + switch (event.key) { + case " " /* Space */: + if (data.searchQuery !== "") { event.preventDefault(); event.stopPropagation(); - dispatch({ type: 0 /* OpenMenu */ }); - d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ })); - break; - } - }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; - } - }); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); - if (props.disabled) - return; - if (state.menuState === 0 /* Open */) { - dispatch({ type: 1 /* CloseMenu */ }); - d.nextFrame(() => { + return actions.search(event.key); + } + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + if (data.activeOptionIndex !== null) { + let { dataRef } = data.options[data.activeOptionIndex]; + actions.onChange(dataRef.current.value); + } + if (data.mode === 0 /* Single */) { + actions.closeListbox(); + disposables().nextFrame(() => { + var _a4; + return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + }); + } + break; + case match(data.orientation, { vertical: "ArrowDown" /* ArrowDown */, horizontal: "ArrowRight" /* ArrowRight */ }): + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(2 /* Next */); + case match(data.orientation, { vertical: "ArrowUp" /* ArrowUp */, horizontal: "ArrowLeft" /* ArrowLeft */ }): + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(1 /* Previous */); + case "Home" /* Home */: + case "PageUp" /* PageUp */: + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(0 /* First */); + case "End" /* End */: + case "PageDown" /* PageDown */: + event.preventDefault(); + event.stopPropagation(); + return actions.goToOption(3 /* Last */); + case "Escape" /* Escape */: + event.preventDefault(); + event.stopPropagation(); + actions.closeListbox(); + return d.nextFrame(() => { var _a4; - return (_a4 = state.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + return (_a4 = data.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); }); - } else { + case "Tab" /* Tab */: event.preventDefault(); - dispatch({ type: 0 /* OpenMenu */ }); - } - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: state.menuState === 0 /* Open */ }), - [state] - ); - let ourProps = { - ref: buttonRef, - id, - type: useResolveButtonType(props, state.buttonRef), - "aria-haspopup": "menu", - "aria-controls": (_a3 = state.itemsRef.current) == null ? void 0 : _a3.id, - "aria-expanded": props.disabled ? void 0 : state.menuState === 0 /* Open */, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick - }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG4, - name: "Menu.Button" + event.stopPropagation(); + break; + default: + if (event.key.length === 1) { + actions.search(event.key); + searchDisposables.setTimeout(() => actions.clearSearch(), 350); + } + break; + } + }); + let labelledby = useComputed( + () => { + var _a4, _b, _c; + return (_c = (_a4 = data.labelRef.current) == null ? void 0 : _a4.id) != null ? _c : (_b = data.buttonRef.current) == null ? void 0 : _b.id; + }, + [data.labelRef.current, data.buttonRef.current] + ); + let slot = (0, import_react35.useMemo)( + () => ({ open: data.listboxState === 0 /* Open */ }), + [data] + ); + let ourProps = { + "aria-activedescendant": data.activeOptionIndex === null ? void 0 : (_a3 = data.options[data.activeOptionIndex]) == null ? void 0 : _a3.id, + "aria-multiselectable": data.mode === 1 /* Multi */ ? true : void 0, + "aria-labelledby": labelledby, + "aria-orientation": data.orientation, + id, + onKeyDown: handleKeyDown, + role: "listbox", + tabIndex: 0, + ref: optionsRef + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTIONS_TAG2, + features: OptionsRenderFeatures2, + visible, + name: "Listbox.Options" + }); +} +var DEFAULT_OPTION_TAG2 = "li"; +function OptionFn2(props, ref) { + let internalId = useId(); + let { + id = `headlessui-listbox-option-${internalId}`, + disabled = false, + value, + ...theirProps + } = props; + let data = useData2("Listbox.Option"); + let actions = useActions2("Listbox.Option"); + let active = data.activeOptionIndex !== null ? data.options[data.activeOptionIndex].id === id : false; + let selected = data.isSelected(value); + let internalOptionRef = (0, import_react35.useRef)(null); + let getTextValue2 = useTextValue(internalOptionRef); + let bag = useLatestValue({ + disabled, + value, + domRef: internalOptionRef, + get textValue() { + return getTextValue2(); + } + }); + let optionRef = useSyncRefs(ref, internalOptionRef); + useIsoMorphicEffect(() => { + if (data.listboxState !== 0 /* Open */) + return; + if (!active) + return; + if (data.activationTrigger === 0 /* Pointer */) + return; + let d = disposables(); + d.requestAnimationFrame(() => { + var _a3, _b; + (_b = (_a3 = internalOptionRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); }); + return d.dispose; + }, [ + internalOptionRef, + active, + data.listboxState, + data.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + data.activeOptionIndex + ]); + useIsoMorphicEffect(() => actions.registerOption(id, bag), [bag, id]); + let handleClick = useEvent((event) => { + if (disabled) + return event.preventDefault(); + actions.onChange(value); + if (data.mode === 0 /* Single */) { + actions.closeListbox(); + disposables().nextFrame(() => { + var _a3; + return (_a3 = data.buttonRef.current) == null ? void 0 : _a3.focus({ preventScroll: true }); + }); + } + }); + let handleFocus = useEvent(() => { + if (disabled) + return actions.goToOption(5 /* Nothing */); + actions.goToOption(4 /* Specific */, id); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (active) + return; + actions.goToOption(4 /* Specific */, id, 0 /* Pointer */); + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (!active) + return; + actions.goToOption(5 /* Nothing */); + }); + let slot = (0, import_react35.useMemo)( + () => ({ active, selected, disabled }), + [active, selected, disabled] + ); + let ourProps = { + id, + ref: optionRef, + role: "option", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + // According to the WAI-ARIA best practices, we should use aria-checked for + // multi-select,but Voice-Over disagrees. So we use aria-checked instead for + // both single and multi-select. + "aria-selected": selected, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OPTION_TAG2, + name: "Listbox.Option" + }); +} +var ListboxRoot = forwardRefWithAs(ListboxFn); +var Button3 = forwardRefWithAs(ButtonFn3); +var Label2 = forwardRefWithAs(LabelFn2); +var Options2 = forwardRefWithAs(OptionsFn2); +var Option2 = forwardRefWithAs(OptionFn2); +var Listbox = Object.assign(ListboxRoot, { Button: Button3, Label: Label2, Options: Options2, Option: Option2 }); + +// src/components/menu/menu.tsx +var import_react36 = __toESM(__webpack_require__(/*! react */ "react"), 1); +function adjustOrderedState3(state, adjustment = (i) => i) { + let currentActiveItem = state.activeItemIndex !== null ? state.items[state.activeItemIndex] : null; + let sortedItems = sortByDomNode( + adjustment(state.items.slice()), + (item) => item.dataRef.current.domRef.current + ); + let adjustedActiveItemIndex = currentActiveItem ? sortedItems.indexOf(currentActiveItem) : null; + if (adjustedActiveItemIndex === -1) { + adjustedActiveItemIndex = null; } - var DEFAULT_ITEMS_TAG = "div"; - var ItemsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; - function ItemsFn(props, ref) { - var _a3, _b; - let internalId = useId(); - let { id = `headlessui-menu-items-${internalId}`, ...theirProps } = props; - let [state, dispatch] = useMenuContext("Menu.Items"); - let itemsRef = useSyncRefs(state.itemsRef, ref); - let ownerDocument = useOwnerDocument(state.itemsRef); - let searchDisposables = useDisposables(); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return state.menuState === 0 /* Open */; - })(); - (0, import_react36.useEffect)(() => { - let container = state.itemsRef.current; - if (!container) - return; - if (state.menuState !== 0 /* Open */) - return; - if (container === (ownerDocument == null ? void 0 : ownerDocument.activeElement)) - return; - container.focus({ preventScroll: true }); - }, [state.menuState, state.itemsRef, ownerDocument]); - useTreeWalker({ - container: state.itemsRef.current, - enabled: state.menuState === 0 /* Open */, - accept(node) { - if (node.getAttribute("role") === "menuitem") - return NodeFilter.FILTER_REJECT; - if (node.hasAttribute("role")) - return NodeFilter.FILTER_SKIP; - return NodeFilter.FILTER_ACCEPT; - }, - walk(node) { - node.setAttribute("role", "none"); - } - }); - let handleKeyDown = useEvent((event) => { - var _a4, _b2; - searchDisposables.dispose(); - switch (event.key) { - case " " /* Space */: - if (state.searchQuery !== "") { - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 3 /* Search */, value: event.key }); - } - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - if (state.activeItemIndex !== null) { - let { dataRef } = state.items[state.activeItemIndex]; - (_b2 = (_a4 = dataRef.current) == null ? void 0 : _a4.domRef.current) == null ? void 0 : _b2.click(); - } - restoreFocusIfNecessary(state.buttonRef.current); - break; - case "ArrowDown" /* ArrowDown */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 2 /* Next */ }); - case "ArrowUp" /* ArrowUp */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 1 /* Previous */ }); - case "Home" /* Home */: - case "PageUp" /* PageUp */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ }); - case "End" /* End */: - case "PageDown" /* PageDown */: - event.preventDefault(); - event.stopPropagation(); - return dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ }); - case "Escape" /* Escape */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - disposables().nextFrame(() => { - var _a5; - return (_a5 = state.buttonRef.current) == null ? void 0 : _a5.focus({ preventScroll: true }); - }); - break; - case "Tab" /* Tab */: - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* CloseMenu */ }); - disposables().nextFrame(() => { - focusFrom( - state.buttonRef.current, - event.shiftKey ? 2 /* Previous */ : 4 /* Next */ - ); - }); - break; - default: - if (event.key.length === 1) { - dispatch({ type: 3 /* Search */, value: event.key }); - searchDisposables.setTimeout(() => dispatch({ type: 4 /* ClearSearch */ }), 350); - } - break; - } + return { + items: sortedItems, + activeItemIndex: adjustedActiveItemIndex + }; +} +var reducers5 = { + [1 /* CloseMenu */](state) { + if (state.menuState === 1 /* Closed */) + return state; + return { ...state, activeItemIndex: null, menuState: 1 /* Closed */ }; + }, + [0 /* OpenMenu */](state) { + if (state.menuState === 0 /* Open */) + return state; + return { + ...state, + /* We can turn off demo mode once we re-open the `Menu` */ + __demoMode: false, + menuState: 0 /* Open */ + }; + }, + [2 /* GoToItem */]: (state, action) => { + var _a3; + let adjustedState = adjustOrderedState3(state); + let activeItemIndex = calculateActiveIndex(action, { + resolveItems: () => adjustedState.items, + resolveActiveIndex: () => adjustedState.activeItemIndex, + resolveId: (item) => item.id, + resolveDisabled: (item) => item.dataRef.current.disabled }); - let handleKeyUp = useEvent((event) => { - switch (event.key) { - case " " /* Space */: - event.preventDefault(); - break; + return { + ...state, + ...adjustedState, + searchQuery: "", + activeItemIndex, + activationTrigger: (_a3 = action.trigger) != null ? _a3 : 1 /* Other */ + }; + }, + [3 /* Search */]: (state, action) => { + let wasAlreadySearching = state.searchQuery !== ""; + let offset = wasAlreadySearching ? 0 : 1; + let searchQuery = state.searchQuery + action.value.toLowerCase(); + let reOrderedItems = state.activeItemIndex !== null ? state.items.slice(state.activeItemIndex + offset).concat(state.items.slice(0, state.activeItemIndex + offset)) : state.items; + let matchingItem = reOrderedItems.find( + (item) => { + var _a3; + return ((_a3 = item.dataRef.current.textValue) == null ? void 0 : _a3.startsWith(searchQuery)) && !item.dataRef.current.disabled; } - }); - let slot = (0, import_react36.useMemo)( - () => ({ open: state.menuState === 0 /* Open */ }), - [state] ); - let ourProps = { - "aria-activedescendant": state.activeItemIndex === null ? void 0 : (_a3 = state.items[state.activeItemIndex]) == null ? void 0 : _a3.id, - "aria-labelledby": (_b = state.buttonRef.current) == null ? void 0 : _b.id, - id, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - role: "menu", - tabIndex: 0, - ref: itemsRef + let matchIdx = matchingItem ? state.items.indexOf(matchingItem) : -1; + if (matchIdx === -1 || matchIdx === state.activeItemIndex) + return { ...state, searchQuery }; + return { + ...state, + searchQuery, + activeItemIndex: matchIdx, + activationTrigger: 1 /* Other */ }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_ITEMS_TAG, - features: ItemsRenderFeatures, - visible, - name: "Menu.Items" - }); - } - var DEFAULT_ITEM_TAG = import_react36.Fragment; - function ItemFn(props, ref) { - let internalId = useId(); - let { id = `headlessui-menu-item-${internalId}`, disabled = false, ...theirProps } = props; - let [state, dispatch] = useMenuContext("Menu.Item"); - let active = state.activeItemIndex !== null ? state.items[state.activeItemIndex].id === id : false; - let internalItemRef = (0, import_react36.useRef)(null); - let itemRef = useSyncRefs(ref, internalItemRef); - useIsoMorphicEffect(() => { - if (state.__demoMode) - return; - if (state.menuState !== 0 /* Open */) - return; - if (!active) - return; - if (state.activationTrigger === 0 /* Pointer */) - return; - let d = disposables(); - d.requestAnimationFrame(() => { - var _a3, _b; - (_b = (_a3 = internalItemRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); - }); - return d.dispose; - }, [ - state.__demoMode, - internalItemRef, - active, - state.menuState, - state.activationTrigger, - /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ - state.activeItemIndex + }, + [4 /* ClearSearch */](state) { + if (state.searchQuery === "") + return state; + return { ...state, searchQuery: "", searchActiveItemIndex: null }; + }, + [5 /* RegisterItem */]: (state, action) => { + let adjustedState = adjustOrderedState3(state, (items) => [ + ...items, + { id: action.id, dataRef: action.dataRef } ]); - let getTextValue2 = useTextValue(internalItemRef); - let bag = (0, import_react36.useRef)({ - disabled, - domRef: internalItemRef, - get textValue() { - return getTextValue2(); - } - }); - useIsoMorphicEffect(() => { - bag.current.disabled = disabled; - }, [bag, disabled]); - useIsoMorphicEffect(() => { - dispatch({ type: 5 /* RegisterItem */, id, dataRef: bag }); - return () => dispatch({ type: 6 /* UnregisterItem */, id }); - }, [bag, id]); - let close = useEvent(() => { - dispatch({ type: 1 /* CloseMenu */ }); - }); - let handleClick = useEvent((event) => { - if (disabled) - return event.preventDefault(); - dispatch({ type: 1 /* CloseMenu */ }); - restoreFocusIfNecessary(state.buttonRef.current); - }); - let handleFocus = useEvent(() => { - if (disabled) - return dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); - dispatch({ type: 2 /* GoToItem */, focus: 4 /* Specific */, id }); - }); - let pointer = useTrackedPointer(); - let handleEnter = useEvent((evt) => pointer.update(evt)); - let handleMove = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (active) - return; - dispatch({ - type: 2 /* GoToItem */, - focus: 4 /* Specific */, - id, - trigger: 0 /* Pointer */ - }); - }); - let handleLeave = useEvent((evt) => { - if (!pointer.wasMoved(evt)) - return; - if (disabled) - return; - if (!active) - return; - dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); + return { ...state, ...adjustedState }; + }, + [6 /* UnregisterItem */]: (state, action) => { + let adjustedState = adjustOrderedState3(state, (items) => { + let idx = items.findIndex((a) => a.id === action.id); + if (idx !== -1) + items.splice(idx, 1); + return items; }); - let slot = (0, import_react36.useMemo)( - () => ({ active, disabled, close }), - [active, disabled, close] - ); - let ourProps = { - id, - ref: itemRef, - role: "menuitem", - tabIndex: disabled === true ? void 0 : -1, - "aria-disabled": disabled === true ? true : void 0, - disabled: void 0, - // Never forward the `disabled` prop - onClick: handleClick, - onFocus: handleFocus, - onPointerEnter: handleEnter, - onMouseEnter: handleEnter, - onPointerMove: handleMove, - onMouseMove: handleMove, - onPointerLeave: handleLeave, - onMouseLeave: handleLeave + return { + ...state, + ...adjustedState, + activationTrigger: 1 /* Other */ }; - return render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_ITEM_TAG, - name: "Menu.Item" - }); } - var MenuRoot = forwardRefWithAs(MenuFn); - var Button4 = forwardRefWithAs(ButtonFn4); - var Items = forwardRefWithAs(ItemsFn); - var Item = forwardRefWithAs(ItemFn); - var Menu = Object.assign(MenuRoot, { Button: Button4, Items, Item }); - - // src/components/popover/popover.tsx - var import_react37 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var reducers6 = { - [0 /* TogglePopover */]: (state) => { - let nextState = { - ...state, - popoverState: match(state.popoverState, { - [0 /* Open */]: 1 /* Closed */, - [1 /* Closed */]: 0 /* Open */ - }) - }; - if (nextState.popoverState === 0 /* Open */) { - nextState.__demoMode = false; +}; +var MenuContext = (0, import_react36.createContext)(null); +MenuContext.displayName = "MenuContext"; +function useMenuContext(component) { + let context = (0, import_react36.useContext)(MenuContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, useMenuContext); + throw err; + } + return context; +} +function stateReducer5(state, action) { + return match(action.type, reducers5, state, action); +} +var DEFAULT_MENU_TAG = import_react36.Fragment; +function MenuFn(props, ref) { + let { __demoMode = false, ...theirProps } = props; + let reducerBag = (0, import_react36.useReducer)(stateReducer5, { + __demoMode, + menuState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + buttonRef: (0, import_react36.createRef)(), + itemsRef: (0, import_react36.createRef)(), + items: [], + searchQuery: "", + activeItemIndex: null, + activationTrigger: 1 /* Other */ + }); + let [{ menuState, itemsRef, buttonRef }, dispatch] = reducerBag; + let menuRef = useSyncRefs(ref); + useOutsideClick( + [buttonRef, itemsRef], + (event, target) => { + var _a3; + dispatch({ type: 1 /* CloseMenu */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + (_a3 = buttonRef.current) == null ? void 0 : _a3.focus(); } - return nextState; - }, - [1 /* ClosePopover */](state) { - if (state.popoverState === 1 /* Closed */) - return state; - return { ...state, popoverState: 1 /* Closed */ }; }, - [2 /* SetButton */](state, action) { - if (state.button === action.button) - return state; - return { ...state, button: action.button }; - }, - [3 /* SetButtonId */](state, action) { - if (state.buttonId === action.buttonId) - return state; - return { ...state, buttonId: action.buttonId }; - }, - [4 /* SetPanel */](state, action) { - if (state.panel === action.panel) - return state; - return { ...state, panel: action.panel }; + menuState === 0 /* Open */ + ); + let close = useEvent(() => { + dispatch({ type: 1 /* CloseMenu */ }); + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: menuState === 0 /* Open */, close }), + [menuState, close] + ); + let ourProps = { ref: menuRef }; + return /* @__PURE__ */ import_react36.default.createElement(MenuContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react36.default.createElement( + OpenClosedProvider, + { + value: match(menuState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) }, - [5 /* SetPanelId */](state, action) { - if (state.panelId === action.panelId) - return state; - return { ...state, panelId: action.panelId }; + render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_MENU_TAG, + name: "Menu" + }) + )); +} +var DEFAULT_BUTTON_TAG4 = "button"; +function ButtonFn4(props, ref) { + var _a3; + let internalId = useId(); + let { id = `headlessui-menu-button-${internalId}`, ...theirProps } = props; + let [state, dispatch] = useMenuContext("Menu.Button"); + let buttonRef = useSyncRefs(state.buttonRef, ref); + let d = useDisposables(); + let handleKeyDown = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* OpenMenu */ }); + d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ })); + break; + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 0 /* OpenMenu */ }); + d.nextFrame(() => dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ })); + break; } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: + event.preventDefault(); + break; + } + }); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + if (props.disabled) + return; + if (state.menuState === 0 /* Open */) { + dispatch({ type: 1 /* CloseMenu */ }); + d.nextFrame(() => { + var _a4; + return (_a4 = state.buttonRef.current) == null ? void 0 : _a4.focus({ preventScroll: true }); + }); + } else { + event.preventDefault(); + dispatch({ type: 0 /* OpenMenu */ }); + } + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: state.menuState === 0 /* Open */ }), + [state] + ); + let ourProps = { + ref: buttonRef, + id, + type: useResolveButtonType(props, state.buttonRef), + "aria-haspopup": "menu", + "aria-controls": (_a3 = state.itemsRef.current) == null ? void 0 : _a3.id, + "aria-expanded": props.disabled ? void 0 : state.menuState === 0 /* Open */, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick }; - var PopoverContext = (0, import_react37.createContext)(null); - PopoverContext.displayName = "PopoverContext"; - function usePopoverContext(component) { - let context = (0, import_react37.useContext)(PopoverContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, usePopoverContext); - throw err; - } - return context; - } - var PopoverAPIContext = (0, import_react37.createContext)(null); - PopoverAPIContext.displayName = "PopoverAPIContext"; - function usePopoverAPIContext(component) { - let context = (0, import_react37.useContext)(PopoverAPIContext); - if (context === null) { - let err = new Error(`<${component} /> is missing a parent component.`); - if (Error.captureStackTrace) - Error.captureStackTrace(err, usePopoverAPIContext); - throw err; - } - return context; - } - var PopoverGroupContext = (0, import_react37.createContext)(null); - PopoverGroupContext.displayName = "PopoverGroupContext"; - function usePopoverGroupContext() { - return (0, import_react37.useContext)(PopoverGroupContext); - } - var PopoverPanelContext = (0, import_react37.createContext)(null); - PopoverPanelContext.displayName = "PopoverPanelContext"; - function usePopoverPanelContext() { - return (0, import_react37.useContext)(PopoverPanelContext); - } - function stateReducer6(state, action) { - return match(action.type, reducers6, state, action); - } - var DEFAULT_POPOVER_TAG = "div"; - function PopoverFn(props, ref) { - var _a3; - let { __demoMode = false, ...theirProps } = props; - let internalPopoverRef = (0, import_react37.useRef)(null); - let popoverRef = useSyncRefs( - ref, - optionalRef((ref2) => { - internalPopoverRef.current = ref2; - }) - ); - let buttons = (0, import_react37.useRef)([]); - let reducerBag = (0, import_react37.useReducer)(stateReducer6, { - __demoMode, - popoverState: __demoMode ? 0 /* Open */ : 1 /* Closed */, - buttons, - button: null, - buttonId: null, - panel: null, - panelId: null, - beforePanelSentinel: (0, import_react37.createRef)(), - afterPanelSentinel: (0, import_react37.createRef)() - }); - let [ - { popoverState, button, buttonId, panel, panelId, beforePanelSentinel, afterPanelSentinel }, - dispatch - ] = reducerBag; - let ownerDocument = useOwnerDocument((_a3 = internalPopoverRef.current) != null ? _a3 : button); - let isPortalled = (0, import_react37.useMemo)(() => { - if (!button) - return false; - if (!panel) - return false; - for (let root2 of document.querySelectorAll("body > *")) { - if (Number(root2 == null ? void 0 : root2.contains(button)) ^ Number(root2 == null ? void 0 : root2.contains(panel))) { - return true; - } - } - let elements = getFocusableElements(); - let buttonIdx = elements.indexOf(button); - let beforeIdx = (buttonIdx + elements.length - 1) % elements.length; - let afterIdx = (buttonIdx + 1) % elements.length; - let beforeElement = elements[beforeIdx]; - let afterElement = elements[afterIdx]; - if (!panel.contains(beforeElement) && !panel.contains(afterElement)) { - return true; - } - return false; - }, [button, panel]); - let buttonIdRef = useLatestValue(buttonId); - let panelIdRef = useLatestValue(panelId); - let registerBag = (0, import_react37.useMemo)( - () => ({ - buttonId: buttonIdRef, - panelId: panelIdRef, - close: () => dispatch({ type: 1 /* ClosePopover */ }) - }), - [buttonIdRef, panelIdRef, dispatch] - ); - let groupContext = usePopoverGroupContext(); - let registerPopover = groupContext == null ? void 0 : groupContext.registerPopover; - let isFocusWithinPopoverGroup = useEvent(() => { - var _a4; - return (_a4 = groupContext == null ? void 0 : groupContext.isFocusWithinPopoverGroup()) != null ? _a4 : (ownerDocument == null ? void 0 : ownerDocument.activeElement) && ((button == null ? void 0 : button.contains(ownerDocument.activeElement)) || (panel == null ? void 0 : panel.contains(ownerDocument.activeElement))); - }); - (0, import_react37.useEffect)(() => registerPopover == null ? void 0 : registerPopover(registerBag), [registerPopover, registerBag]); - let [portals, PortalWrapper] = useNestedPortals(); - let root = useRootContainers({ - portals, - defaultContainers: [button, panel] - }); - useEventListener( - ownerDocument == null ? void 0 : ownerDocument.defaultView, - "focus", - (event) => { - var _a4, _b, _c, _d; - if (event.target === window) - return; - if (!(event.target instanceof HTMLElement)) - return; - if (popoverState !== 0 /* Open */) - return; - if (isFocusWithinPopoverGroup()) - return; - if (!button) - return; - if (!panel) - return; - if (root.contains(event.target)) - return; - if ((_b = (_a4 = beforePanelSentinel.current) == null ? void 0 : _a4.contains) == null ? void 0 : _b.call(_a4, event.target)) - return; - if ((_d = (_c = afterPanelSentinel.current) == null ? void 0 : _c.contains) == null ? void 0 : _d.call(_c, event.target)) - return; - dispatch({ type: 1 /* ClosePopover */ }); - }, - true - ); - useOutsideClick( - root.resolveContainers, - (event, target) => { - dispatch({ type: 1 /* ClosePopover */ }); - if (!isFocusableElement(target, 1 /* Loose */)) { + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG4, + name: "Menu.Button" + }); +} +var DEFAULT_ITEMS_TAG = "div"; +var ItemsRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; +function ItemsFn(props, ref) { + var _a3, _b; + let internalId = useId(); + let { id = `headlessui-menu-items-${internalId}`, ...theirProps } = props; + let [state, dispatch] = useMenuContext("Menu.Items"); + let itemsRef = useSyncRefs(state.itemsRef, ref); + let ownerDocument = useOwnerDocument(state.itemsRef); + let searchDisposables = useDisposables(); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return state.menuState === 0 /* Open */; + })(); + (0, import_react36.useEffect)(() => { + let container = state.itemsRef.current; + if (!container) + return; + if (state.menuState !== 0 /* Open */) + return; + if (container === (ownerDocument == null ? void 0 : ownerDocument.activeElement)) + return; + container.focus({ preventScroll: true }); + }, [state.menuState, state.itemsRef, ownerDocument]); + useTreeWalker({ + container: state.itemsRef.current, + enabled: state.menuState === 0 /* Open */, + accept(node) { + if (node.getAttribute("role") === "menuitem") + return NodeFilter.FILTER_REJECT; + if (node.hasAttribute("role")) + return NodeFilter.FILTER_SKIP; + return NodeFilter.FILTER_ACCEPT; + }, + walk(node) { + node.setAttribute("role", "none"); + } + }); + let handleKeyDown = useEvent((event) => { + var _a4, _b2; + searchDisposables.dispose(); + switch (event.key) { + case " " /* Space */: + if (state.searchQuery !== "") { event.preventDefault(); - button == null ? void 0 : button.focus(); + event.stopPropagation(); + return dispatch({ type: 3 /* Search */, value: event.key }); } - }, - popoverState === 0 /* Open */ - ); - let close = useEvent( - (focusableElement) => { - dispatch({ type: 1 /* ClosePopover */ }); - let restoreElement = (() => { - if (!focusableElement) - return button; - if (focusableElement instanceof HTMLElement) - return focusableElement; - if ("current" in focusableElement && focusableElement.current instanceof HTMLElement) - return focusableElement.current; - return button; - })(); - restoreElement == null ? void 0 : restoreElement.focus(); - } - ); - let api = (0, import_react37.useMemo)( - () => ({ close, isPortalled }), - [close, isPortalled] - ); - let slot = (0, import_react37.useMemo)( - () => ({ open: popoverState === 0 /* Open */, close }), - [popoverState, close] - ); - let ourProps = { ref: popoverRef }; - return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: null }, /* @__PURE__ */ import_react37.default.createElement(PopoverContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react37.default.createElement(PopoverAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react37.default.createElement( - OpenClosedProvider, - { - value: match(popoverState, { - [0 /* Open */]: 1 /* Open */, - [1 /* Closed */]: 2 /* Closed */ - }) - }, - /* @__PURE__ */ import_react37.default.createElement(PortalWrapper, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_POPOVER_TAG, - name: "Popover" - }), /* @__PURE__ */ import_react37.default.createElement(root.MainTreeNode, null)) - )))); - } - var DEFAULT_BUTTON_TAG5 = "button"; - function ButtonFn5(props, ref) { - let internalId = useId(); - let { id = `headlessui-popover-button-${internalId}`, ...theirProps } = props; - let [state, dispatch] = usePopoverContext("Popover.Button"); - let { isPortalled } = usePopoverAPIContext("Popover.Button"); - let internalButtonRef = (0, import_react37.useRef)(null); - let sentinelId = `headlessui-focus-sentinel-${useId()}`; - let groupContext = usePopoverGroupContext(); - let closeOthers = groupContext == null ? void 0 : groupContext.closeOthers; - let panelContext = usePopoverPanelContext(); - let isWithinPanel = panelContext !== null; - (0, import_react37.useEffect)(() => { - if (isWithinPanel) - return; - dispatch({ type: 3 /* SetButtonId */, buttonId: id }); - return () => { - dispatch({ type: 3 /* SetButtonId */, buttonId: null }); - }; - }, [isWithinPanel, id, dispatch]); - let [uniqueIdentifier] = (0, import_react37.useState)(() => Symbol()); - let buttonRef = useSyncRefs( - internalButtonRef, - ref, - isWithinPanel ? null : (button) => { - if (button) { - state.buttons.current.push(uniqueIdentifier); - } else { - let idx = state.buttons.current.indexOf(uniqueIdentifier); - if (idx !== -1) - state.buttons.current.splice(idx, 1); + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + if (state.activeItemIndex !== null) { + let { dataRef } = state.items[state.activeItemIndex]; + (_b2 = (_a4 = dataRef.current) == null ? void 0 : _a4.domRef.current) == null ? void 0 : _b2.click(); } - if (state.buttons.current.length > 1) { - console.warn( - "You are already using a but only 1 is supported." + restoreFocusIfNecessary(state.buttonRef.current); + break; + case "ArrowDown" /* ArrowDown */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 2 /* Next */ }); + case "ArrowUp" /* ArrowUp */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 1 /* Previous */ }); + case "Home" /* Home */: + case "PageUp" /* PageUp */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 0 /* First */ }); + case "End" /* End */: + case "PageDown" /* PageDown */: + event.preventDefault(); + event.stopPropagation(); + return dispatch({ type: 2 /* GoToItem */, focus: 3 /* Last */ }); + case "Escape" /* Escape */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + disposables().nextFrame(() => { + var _a5; + return (_a5 = state.buttonRef.current) == null ? void 0 : _a5.focus({ preventScroll: true }); + }); + break; + case "Tab" /* Tab */: + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* CloseMenu */ }); + disposables().nextFrame(() => { + focusFrom( + state.buttonRef.current, + event.shiftKey ? 2 /* Previous */ : 4 /* Next */ ); + }); + break; + default: + if (event.key.length === 1) { + dispatch({ type: 3 /* Search */, value: event.key }); + searchDisposables.setTimeout(() => dispatch({ type: 4 /* ClearSearch */ }), 350); } - button && dispatch({ type: 2 /* SetButton */, button }); - } - ); - let withinPanelButtonRef = useSyncRefs(internalButtonRef, ref); - let ownerDocument = useOwnerDocument(internalButtonRef); - let handleKeyDown = useEvent((event) => { - var _a3, _b, _c; - if (isWithinPanel) { - if (state.popoverState === 1 /* Closed */) - return; - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - (_b = (_a3 = event.target).click) == null ? void 0 : _b.call(_a3); - dispatch({ type: 1 /* ClosePopover */ }); - (_c = state.button) == null ? void 0 : _c.focus(); - break; - } - } else { - switch (event.key) { - case " " /* Space */: - case "Enter" /* Enter */: - event.preventDefault(); - event.stopPropagation(); - if (state.popoverState === 1 /* Closed */) - closeOthers == null ? void 0 : closeOthers(state.buttonId); - dispatch({ type: 0 /* TogglePopover */ }); - break; - case "Escape" /* Escape */: - if (state.popoverState !== 0 /* Open */) - return closeOthers == null ? void 0 : closeOthers(state.buttonId); - if (!internalButtonRef.current) - return; - if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) && !internalButtonRef.current.contains(ownerDocument.activeElement)) { - return; - } - event.preventDefault(); - event.stopPropagation(); - dispatch({ type: 1 /* ClosePopover */ }); - break; - } - } - }); - let handleKeyUp = useEvent((event) => { - if (isWithinPanel) - return; - if (event.key === " " /* Space */) { + break; + } + }); + let handleKeyUp = useEvent((event) => { + switch (event.key) { + case " " /* Space */: event.preventDefault(); - } - }); - let handleClick = useEvent((event) => { + break; + } + }); + let slot = (0, import_react36.useMemo)( + () => ({ open: state.menuState === 0 /* Open */ }), + [state] + ); + let ourProps = { + "aria-activedescendant": state.activeItemIndex === null ? void 0 : (_a3 = state.items[state.activeItemIndex]) == null ? void 0 : _a3.id, + "aria-labelledby": (_b = state.buttonRef.current) == null ? void 0 : _b.id, + id, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + role: "menu", + tabIndex: 0, + ref: itemsRef + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_ITEMS_TAG, + features: ItemsRenderFeatures, + visible, + name: "Menu.Items" + }); +} +var DEFAULT_ITEM_TAG = import_react36.Fragment; +function ItemFn(props, ref) { + let internalId = useId(); + let { id = `headlessui-menu-item-${internalId}`, disabled = false, ...theirProps } = props; + let [state, dispatch] = useMenuContext("Menu.Item"); + let active = state.activeItemIndex !== null ? state.items[state.activeItemIndex].id === id : false; + let internalItemRef = (0, import_react36.useRef)(null); + let itemRef = useSyncRefs(ref, internalItemRef); + useIsoMorphicEffect(() => { + if (state.__demoMode) + return; + if (state.menuState !== 0 /* Open */) + return; + if (!active) + return; + if (state.activationTrigger === 0 /* Pointer */) + return; + let d = disposables(); + d.requestAnimationFrame(() => { var _a3, _b; - if (isDisabledReactIssue7711(event.currentTarget)) - return; - if (props.disabled) - return; - if (isWithinPanel) { - dispatch({ type: 1 /* ClosePopover */ }); - (_a3 = state.button) == null ? void 0 : _a3.focus(); - } else { - event.preventDefault(); - event.stopPropagation(); - if (state.popoverState === 1 /* Closed */) - closeOthers == null ? void 0 : closeOthers(state.buttonId); - dispatch({ type: 0 /* TogglePopover */ }); - (_b = state.button) == null ? void 0 : _b.focus(); - } + (_b = (_a3 = internalItemRef.current) == null ? void 0 : _a3.scrollIntoView) == null ? void 0 : _b.call(_a3, { block: "nearest" }); }); - let handleMouseDown = useEvent((event) => { - event.preventDefault(); - event.stopPropagation(); + return d.dispose; + }, [ + state.__demoMode, + internalItemRef, + active, + state.menuState, + state.activationTrigger, + /* We also want to trigger this when the position of the active item changes so that we can re-trigger the scrollIntoView */ + state.activeItemIndex + ]); + let getTextValue2 = useTextValue(internalItemRef); + let bag = (0, import_react36.useRef)({ + disabled, + domRef: internalItemRef, + get textValue() { + return getTextValue2(); + } + }); + useIsoMorphicEffect(() => { + bag.current.disabled = disabled; + }, [bag, disabled]); + useIsoMorphicEffect(() => { + dispatch({ type: 5 /* RegisterItem */, id, dataRef: bag }); + return () => dispatch({ type: 6 /* UnregisterItem */, id }); + }, [bag, id]); + let close = useEvent(() => { + dispatch({ type: 1 /* CloseMenu */ }); + }); + let handleClick = useEvent((event) => { + if (disabled) + return event.preventDefault(); + dispatch({ type: 1 /* CloseMenu */ }); + restoreFocusIfNecessary(state.buttonRef.current); + }); + let handleFocus = useEvent(() => { + if (disabled) + return dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); + dispatch({ type: 2 /* GoToItem */, focus: 4 /* Specific */, id }); + }); + let pointer = useTrackedPointer(); + let handleEnter = useEvent((evt) => pointer.update(evt)); + let handleMove = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (active) + return; + dispatch({ + type: 2 /* GoToItem */, + focus: 4 /* Specific */, + id, + trigger: 0 /* Pointer */ }); - let visible = state.popoverState === 0 /* Open */; - let slot = (0, import_react37.useMemo)(() => ({ open: visible }), [visible]); - let type = useResolveButtonType(props, internalButtonRef); - let ourProps = isWithinPanel ? { - ref: withinPanelButtonRef, - type, - onKeyDown: handleKeyDown, - onClick: handleClick - } : { - ref: buttonRef, - id: state.buttonId, - type, - "aria-expanded": props.disabled ? void 0 : state.popoverState === 0 /* Open */, - "aria-controls": state.panel ? state.panelId : void 0, - onKeyDown: handleKeyDown, - onKeyUp: handleKeyUp, - onClick: handleClick, - onMouseDown: handleMouseDown + }); + let handleLeave = useEvent((evt) => { + if (!pointer.wasMoved(evt)) + return; + if (disabled) + return; + if (!active) + return; + dispatch({ type: 2 /* GoToItem */, focus: 5 /* Nothing */ }); + }); + let slot = (0, import_react36.useMemo)( + () => ({ active, disabled, close }), + [active, disabled, close] + ); + let ourProps = { + id, + ref: itemRef, + role: "menuitem", + tabIndex: disabled === true ? void 0 : -1, + "aria-disabled": disabled === true ? true : void 0, + disabled: void 0, + // Never forward the `disabled` prop + onClick: handleClick, + onFocus: handleFocus, + onPointerEnter: handleEnter, + onMouseEnter: handleEnter, + onPointerMove: handleMove, + onMouseMove: handleMove, + onPointerLeave: handleLeave, + onMouseLeave: handleLeave + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_ITEM_TAG, + name: "Menu.Item" + }); +} +var MenuRoot = forwardRefWithAs(MenuFn); +var Button4 = forwardRefWithAs(ButtonFn4); +var Items = forwardRefWithAs(ItemsFn); +var Item = forwardRefWithAs(ItemFn); +var Menu = Object.assign(MenuRoot, { Button: Button4, Items, Item }); + +// src/components/popover/popover.tsx +var import_react37 = __toESM(__webpack_require__(/*! react */ "react"), 1); +var reducers6 = { + [0 /* TogglePopover */]: (state) => { + let nextState = { + ...state, + popoverState: match(state.popoverState, { + [0 /* Open */]: 1 /* Closed */, + [1 /* Closed */]: 0 /* Open */ + }) }; - let direction = useTabDirection(); - let handleFocus = useEvent(() => { - let el = state.panel; - if (!el) - return; - function run() { - let result = match(direction.current, { - [0 /* Forwards */]: () => focusIn(el, 1 /* First */), - [1 /* Backwards */]: () => focusIn(el, 8 /* Last */) - }); - if (result === 0 /* Error */) { - focusIn( - getFocusableElements().filter((el2) => el2.dataset.headlessuiFocusGuard !== "true"), - match(direction.current, { - [0 /* Forwards */]: 4 /* Next */, - [1 /* Backwards */]: 2 /* Previous */ - }), - { relativeTo: state.button } - ); - } + if (nextState.popoverState === 0 /* Open */) { + nextState.__demoMode = false; + } + return nextState; + }, + [1 /* ClosePopover */](state) { + if (state.popoverState === 1 /* Closed */) + return state; + return { ...state, popoverState: 1 /* Closed */ }; + }, + [2 /* SetButton */](state, action) { + if (state.button === action.button) + return state; + return { ...state, button: action.button }; + }, + [3 /* SetButtonId */](state, action) { + if (state.buttonId === action.buttonId) + return state; + return { ...state, buttonId: action.buttonId }; + }, + [4 /* SetPanel */](state, action) { + if (state.panel === action.panel) + return state; + return { ...state, panel: action.panel }; + }, + [5 /* SetPanelId */](state, action) { + if (state.panelId === action.panelId) + return state; + return { ...state, panelId: action.panelId }; + } +}; +var PopoverContext = (0, import_react37.createContext)(null); +PopoverContext.displayName = "PopoverContext"; +function usePopoverContext(component) { + let context = (0, import_react37.useContext)(PopoverContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, usePopoverContext); + throw err; + } + return context; +} +var PopoverAPIContext = (0, import_react37.createContext)(null); +PopoverAPIContext.displayName = "PopoverAPIContext"; +function usePopoverAPIContext(component) { + let context = (0, import_react37.useContext)(PopoverAPIContext); + if (context === null) { + let err = new Error(`<${component} /> is missing a parent component.`); + if (Error.captureStackTrace) + Error.captureStackTrace(err, usePopoverAPIContext); + throw err; + } + return context; +} +var PopoverGroupContext = (0, import_react37.createContext)(null); +PopoverGroupContext.displayName = "PopoverGroupContext"; +function usePopoverGroupContext() { + return (0, import_react37.useContext)(PopoverGroupContext); +} +var PopoverPanelContext = (0, import_react37.createContext)(null); +PopoverPanelContext.displayName = "PopoverPanelContext"; +function usePopoverPanelContext() { + return (0, import_react37.useContext)(PopoverPanelContext); +} +function stateReducer6(state, action) { + return match(action.type, reducers6, state, action); +} +var DEFAULT_POPOVER_TAG = "div"; +function PopoverFn(props, ref) { + var _a3; + let { __demoMode = false, ...theirProps } = props; + let internalPopoverRef = (0, import_react37.useRef)(null); + let popoverRef = useSyncRefs( + ref, + optionalRef((ref2) => { + internalPopoverRef.current = ref2; + }) + ); + let buttons = (0, import_react37.useRef)([]); + let reducerBag = (0, import_react37.useReducer)(stateReducer6, { + __demoMode, + popoverState: __demoMode ? 0 /* Open */ : 1 /* Closed */, + buttons, + button: null, + buttonId: null, + panel: null, + panelId: null, + beforePanelSentinel: (0, import_react37.createRef)(), + afterPanelSentinel: (0, import_react37.createRef)() + }); + let [ + { popoverState, button, buttonId, panel, panelId, beforePanelSentinel, afterPanelSentinel }, + dispatch + ] = reducerBag; + let ownerDocument = useOwnerDocument((_a3 = internalPopoverRef.current) != null ? _a3 : button); + let isPortalled = (0, import_react37.useMemo)(() => { + if (!button) + return false; + if (!panel) + return false; + for (let root2 of document.querySelectorAll("body > *")) { + if (Number(root2 == null ? void 0 : root2.contains(button)) ^ Number(root2 == null ? void 0 : root2.contains(panel))) { + return true; } - if (false) {} else { - run(); + } + let elements = getFocusableElements(); + let buttonIdx = elements.indexOf(button); + let beforeIdx = (buttonIdx + elements.length - 1) % elements.length; + let afterIdx = (buttonIdx + 1) % elements.length; + let beforeElement = elements[beforeIdx]; + let afterElement = elements[afterIdx]; + if (!panel.contains(beforeElement) && !panel.contains(afterElement)) { + return true; + } + return false; + }, [button, panel]); + let buttonIdRef = useLatestValue(buttonId); + let panelIdRef = useLatestValue(panelId); + let registerBag = (0, import_react37.useMemo)( + () => ({ + buttonId: buttonIdRef, + panelId: panelIdRef, + close: () => dispatch({ type: 1 /* ClosePopover */ }) + }), + [buttonIdRef, panelIdRef, dispatch] + ); + let groupContext = usePopoverGroupContext(); + let registerPopover = groupContext == null ? void 0 : groupContext.registerPopover; + let isFocusWithinPopoverGroup = useEvent(() => { + var _a4; + return (_a4 = groupContext == null ? void 0 : groupContext.isFocusWithinPopoverGroup()) != null ? _a4 : (ownerDocument == null ? void 0 : ownerDocument.activeElement) && ((button == null ? void 0 : button.contains(ownerDocument.activeElement)) || (panel == null ? void 0 : panel.contains(ownerDocument.activeElement))); + }); + (0, import_react37.useEffect)(() => registerPopover == null ? void 0 : registerPopover(registerBag), [registerPopover, registerBag]); + let [portals, PortalWrapper] = useNestedPortals(); + let root = useRootContainers({ + portals, + defaultContainers: [button, panel] + }); + useEventListener( + ownerDocument == null ? void 0 : ownerDocument.defaultView, + "focus", + (event) => { + var _a4, _b, _c, _d; + if (event.target === window) + return; + if (!(event.target instanceof HTMLElement)) + return; + if (popoverState !== 0 /* Open */) + return; + if (isFocusWithinPopoverGroup()) + return; + if (!button) + return; + if (!panel) + return; + if (root.contains(event.target)) + return; + if ((_b = (_a4 = beforePanelSentinel.current) == null ? void 0 : _a4.contains) == null ? void 0 : _b.call(_a4, event.target)) + return; + if ((_d = (_c = afterPanelSentinel.current) == null ? void 0 : _c.contains) == null ? void 0 : _d.call(_c, event.target)) + return; + dispatch({ type: 1 /* ClosePopover */ }); + }, + true + ); + useOutsideClick( + root.resolveContainers, + (event, target) => { + dispatch({ type: 1 /* ClosePopover */ }); + if (!isFocusableElement(target, 1 /* Loose */)) { + event.preventDefault(); + button == null ? void 0 : button.focus(); } - }); - return /* @__PURE__ */ import_react37.default.createElement(import_react37.default.Fragment, null, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_BUTTON_TAG5, - name: "Popover.Button" - }), visible && !isWithinPanel && isPortalled && /* @__PURE__ */ import_react37.default.createElement( - Hidden, - { - id: sentinelId, - features: 2 /* Focusable */, - "data-headlessui-focus-guard": true, - as: "button", - type: "button", - onFocus: handleFocus - } - )); - } - var DEFAULT_OVERLAY_TAG2 = "div"; - var OverlayRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; - function OverlayFn2(props, ref) { - let internalId = useId(); - let { id = `headlessui-popover-overlay-${internalId}`, ...theirProps } = props; - let [{ popoverState }, dispatch] = usePopoverContext("Popover.Overlay"); - let overlayRef = useSyncRefs(ref); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; - } - return popoverState === 0 /* Open */; - })(); - let handleClick = useEvent((event) => { - if (isDisabledReactIssue7711(event.currentTarget)) - return event.preventDefault(); + }, + popoverState === 0 /* Open */ + ); + let close = useEvent( + (focusableElement) => { dispatch({ type: 1 /* ClosePopover */ }); - }); - let slot = (0, import_react37.useMemo)( - () => ({ open: popoverState === 0 /* Open */ }), - [popoverState] - ); - let ourProps = { - ref: overlayRef, - id, - "aria-hidden": true, - onClick: handleClick - }; - return render({ + let restoreElement = (() => { + if (!focusableElement) + return button; + if (focusableElement instanceof HTMLElement) + return focusableElement; + if ("current" in focusableElement && focusableElement.current instanceof HTMLElement) + return focusableElement.current; + return button; + })(); + restoreElement == null ? void 0 : restoreElement.focus(); + } + ); + let api = (0, import_react37.useMemo)( + () => ({ close, isPortalled }), + [close, isPortalled] + ); + let slot = (0, import_react37.useMemo)( + () => ({ open: popoverState === 0 /* Open */, close }), + [popoverState, close] + ); + let ourProps = { ref: popoverRef }; + return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: null }, /* @__PURE__ */ import_react37.default.createElement(PopoverContext.Provider, { value: reducerBag }, /* @__PURE__ */ import_react37.default.createElement(PopoverAPIContext.Provider, { value: api }, /* @__PURE__ */ import_react37.default.createElement( + OpenClosedProvider, + { + value: match(popoverState, { + [0 /* Open */]: 1 /* Open */, + [1 /* Closed */]: 2 /* Closed */ + }) + }, + /* @__PURE__ */ import_react37.default.createElement(PortalWrapper, null, render({ ourProps, theirProps, slot, - defaultTag: DEFAULT_OVERLAY_TAG2, - features: OverlayRenderFeatures, - visible, - name: "Popover.Overlay" - }); - } - var DEFAULT_PANEL_TAG3 = "div"; - var PanelRenderFeatures2 = 1 /* RenderStrategy */ | 2 /* Static */; - function PanelFn3(props, ref) { - let internalId = useId(); - let { id = `headlessui-popover-panel-${internalId}`, focus = false, ...theirProps } = props; - let [state, dispatch] = usePopoverContext("Popover.Panel"); - let { close, isPortalled } = usePopoverAPIContext("Popover.Panel"); - let beforePanelSentinelId = `headlessui-focus-sentinel-before-${useId()}`; - let afterPanelSentinelId = `headlessui-focus-sentinel-after-${useId()}`; - let internalPanelRef = (0, import_react37.useRef)(null); - let panelRef = useSyncRefs(internalPanelRef, ref, (panel) => { - dispatch({ type: 4 /* SetPanel */, panel }); - }); - let ownerDocument = useOwnerDocument(internalPanelRef); - useIsoMorphicEffect(() => { - dispatch({ type: 5 /* SetPanelId */, panelId: id }); - return () => { - dispatch({ type: 5 /* SetPanelId */, panelId: null }); - }; - }, [id, dispatch]); - let usesOpenClosedState = useOpenClosed(); - let visible = (() => { - if (usesOpenClosedState !== null) { - return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + defaultTag: DEFAULT_POPOVER_TAG, + name: "Popover" + }), /* @__PURE__ */ import_react37.default.createElement(root.MainTreeNode, null)) + )))); +} +var DEFAULT_BUTTON_TAG5 = "button"; +function ButtonFn5(props, ref) { + let internalId = useId(); + let { id = `headlessui-popover-button-${internalId}`, ...theirProps } = props; + let [state, dispatch] = usePopoverContext("Popover.Button"); + let { isPortalled } = usePopoverAPIContext("Popover.Button"); + let internalButtonRef = (0, import_react37.useRef)(null); + let sentinelId = `headlessui-focus-sentinel-${useId()}`; + let groupContext = usePopoverGroupContext(); + let closeOthers = groupContext == null ? void 0 : groupContext.closeOthers; + let panelContext = usePopoverPanelContext(); + let isWithinPanel = panelContext !== null; + (0, import_react37.useEffect)(() => { + if (isWithinPanel) + return; + dispatch({ type: 3 /* SetButtonId */, buttonId: id }); + return () => { + dispatch({ type: 3 /* SetButtonId */, buttonId: null }); + }; + }, [isWithinPanel, id, dispatch]); + let [uniqueIdentifier] = (0, import_react37.useState)(() => Symbol()); + let buttonRef = useSyncRefs( + internalButtonRef, + ref, + isWithinPanel ? null : (button) => { + if (button) { + state.buttons.current.push(uniqueIdentifier); + } else { + let idx = state.buttons.current.indexOf(uniqueIdentifier); + if (idx !== -1) + state.buttons.current.splice(idx, 1); } - return state.popoverState === 0 /* Open */; - })(); - let handleKeyDown = useEvent((event) => { - var _a3; + if (state.buttons.current.length > 1) { + console.warn( + "You are already using a but only 1 is supported." + ); + } + button && dispatch({ type: 2 /* SetButton */, button }); + } + ); + let withinPanelButtonRef = useSyncRefs(internalButtonRef, ref); + let ownerDocument = useOwnerDocument(internalButtonRef); + let handleKeyDown = useEvent((event) => { + var _a3, _b, _c; + if (isWithinPanel) { + if (state.popoverState === 1 /* Closed */) + return; + switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + (_b = (_a3 = event.target).click) == null ? void 0 : _b.call(_a3); + dispatch({ type: 1 /* ClosePopover */ }); + (_c = state.button) == null ? void 0 : _c.focus(); + break; + } + } else { switch (event.key) { + case " " /* Space */: + case "Enter" /* Enter */: + event.preventDefault(); + event.stopPropagation(); + if (state.popoverState === 1 /* Closed */) + closeOthers == null ? void 0 : closeOthers(state.buttonId); + dispatch({ type: 0 /* TogglePopover */ }); + break; case "Escape" /* Escape */: if (state.popoverState !== 0 /* Open */) + return closeOthers == null ? void 0 : closeOthers(state.buttonId); + if (!internalButtonRef.current) return; - if (!internalPanelRef.current) - return; - if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) && !internalPanelRef.current.contains(ownerDocument.activeElement)) { + if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) && !internalButtonRef.current.contains(ownerDocument.activeElement)) { return; } event.preventDefault(); event.stopPropagation(); dispatch({ type: 1 /* ClosePopover */ }); - (_a3 = state.button) == null ? void 0 : _a3.focus(); break; } - }); - (0, import_react37.useEffect)(() => { - var _a3; - if (props.static) - return; - if (state.popoverState === 1 /* Closed */ && ((_a3 = props.unmount) != null ? _a3 : true)) { - dispatch({ type: 4 /* SetPanel */, panel: null }); + } + }); + let handleKeyUp = useEvent((event) => { + if (isWithinPanel) + return; + if (event.key === " " /* Space */) { + event.preventDefault(); + } + }); + let handleClick = useEvent((event) => { + var _a3, _b; + if (isDisabledReactIssue7711(event.currentTarget)) + return; + if (props.disabled) + return; + if (isWithinPanel) { + dispatch({ type: 1 /* ClosePopover */ }); + (_a3 = state.button) == null ? void 0 : _a3.focus(); + } else { + event.preventDefault(); + event.stopPropagation(); + if (state.popoverState === 1 /* Closed */) + closeOthers == null ? void 0 : closeOthers(state.buttonId); + dispatch({ type: 0 /* TogglePopover */ }); + (_b = state.button) == null ? void 0 : _b.focus(); + } + }); + let handleMouseDown = useEvent((event) => { + event.preventDefault(); + event.stopPropagation(); + }); + let visible = state.popoverState === 0 /* Open */; + let slot = (0, import_react37.useMemo)(() => ({ open: visible }), [visible]); + let type = useResolveButtonType(props, internalButtonRef); + let ourProps = isWithinPanel ? { + ref: withinPanelButtonRef, + type, + onKeyDown: handleKeyDown, + onClick: handleClick + } : { + ref: buttonRef, + id: state.buttonId, + type, + "aria-expanded": props.disabled ? void 0 : state.popoverState === 0 /* Open */, + "aria-controls": state.panel ? state.panelId : void 0, + onKeyDown: handleKeyDown, + onKeyUp: handleKeyUp, + onClick: handleClick, + onMouseDown: handleMouseDown + }; + let direction = useTabDirection(); + let handleFocus = useEvent(() => { + let el = state.panel; + if (!el) + return; + function run() { + let result = match(direction.current, { + [0 /* Forwards */]: () => focusIn(el, 1 /* First */), + [1 /* Backwards */]: () => focusIn(el, 8 /* Last */) + }); + if (result === 0 /* Error */) { + focusIn( + getFocusableElements().filter((el2) => el2.dataset.headlessuiFocusGuard !== "true"), + match(direction.current, { + [0 /* Forwards */]: 4 /* Next */, + [1 /* Backwards */]: 2 /* Previous */ + }), + { relativeTo: state.button } + ); } - }, [state.popoverState, props.unmount, props.static, dispatch]); - (0, import_react37.useEffect)(() => { - if (state.__demoMode) - return; - if (!focus) - return; - if (state.popoverState !== 0 /* Open */) - return; - if (!internalPanelRef.current) - return; - let activeElement = ownerDocument == null ? void 0 : ownerDocument.activeElement; - if (internalPanelRef.current.contains(activeElement)) - return; - focusIn(internalPanelRef.current, 1 /* First */); - }, [state.__demoMode, focus, internalPanelRef, state.popoverState]); - let slot = (0, import_react37.useMemo)( - () => ({ open: state.popoverState === 0 /* Open */, close }), - [state, close] - ); - let ourProps = { - ref: panelRef, - id, - onKeyDown: handleKeyDown, - onBlur: focus && state.popoverState === 0 /* Open */ ? (event) => { - var _a3, _b, _c, _d, _e; - let el = event.relatedTarget; - if (!el) + } + if (false) {} else { + run(); + } + }); + return /* @__PURE__ */ import_react37.default.createElement(import_react37.default.Fragment, null, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_BUTTON_TAG5, + name: "Popover.Button" + }), visible && !isWithinPanel && isPortalled && /* @__PURE__ */ import_react37.default.createElement( + Hidden, + { + id: sentinelId, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleFocus + } + )); +} +var DEFAULT_OVERLAY_TAG2 = "div"; +var OverlayRenderFeatures = 1 /* RenderStrategy */ | 2 /* Static */; +function OverlayFn2(props, ref) { + let internalId = useId(); + let { id = `headlessui-popover-overlay-${internalId}`, ...theirProps } = props; + let [{ popoverState }, dispatch] = usePopoverContext("Popover.Overlay"); + let overlayRef = useSyncRefs(ref); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return popoverState === 0 /* Open */; + })(); + let handleClick = useEvent((event) => { + if (isDisabledReactIssue7711(event.currentTarget)) + return event.preventDefault(); + dispatch({ type: 1 /* ClosePopover */ }); + }); + let slot = (0, import_react37.useMemo)( + () => ({ open: popoverState === 0 /* Open */ }), + [popoverState] + ); + let ourProps = { + ref: overlayRef, + id, + "aria-hidden": true, + onClick: handleClick + }; + return render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_OVERLAY_TAG2, + features: OverlayRenderFeatures, + visible, + name: "Popover.Overlay" + }); +} +var DEFAULT_PANEL_TAG3 = "div"; +var PanelRenderFeatures2 = 1 /* RenderStrategy */ | 2 /* Static */; +function PanelFn3(props, ref) { + let internalId = useId(); + let { id = `headlessui-popover-panel-${internalId}`, focus = false, ...theirProps } = props; + let [state, dispatch] = usePopoverContext("Popover.Panel"); + let { close, isPortalled } = usePopoverAPIContext("Popover.Panel"); + let beforePanelSentinelId = `headlessui-focus-sentinel-before-${useId()}`; + let afterPanelSentinelId = `headlessui-focus-sentinel-after-${useId()}`; + let internalPanelRef = (0, import_react37.useRef)(null); + let panelRef = useSyncRefs(internalPanelRef, ref, (panel) => { + dispatch({ type: 4 /* SetPanel */, panel }); + }); + let ownerDocument = useOwnerDocument(internalPanelRef); + useIsoMorphicEffect(() => { + dispatch({ type: 5 /* SetPanelId */, panelId: id }); + return () => { + dispatch({ type: 5 /* SetPanelId */, panelId: null }); + }; + }, [id, dispatch]); + let usesOpenClosedState = useOpenClosed(); + let visible = (() => { + if (usesOpenClosedState !== null) { + return (usesOpenClosedState & 1 /* Open */) === 1 /* Open */; + } + return state.popoverState === 0 /* Open */; + })(); + let handleKeyDown = useEvent((event) => { + var _a3; + switch (event.key) { + case "Escape" /* Escape */: + if (state.popoverState !== 0 /* Open */) return; if (!internalPanelRef.current) return; - if ((_a3 = internalPanelRef.current) == null ? void 0 : _a3.contains(el)) + if ((ownerDocument == null ? void 0 : ownerDocument.activeElement) && !internalPanelRef.current.contains(ownerDocument.activeElement)) { return; - dispatch({ type: 1 /* ClosePopover */ }); - if (((_c = (_b = state.beforePanelSentinel.current) == null ? void 0 : _b.contains) == null ? void 0 : _c.call(_b, el)) || ((_e = (_d = state.afterPanelSentinel.current) == null ? void 0 : _d.contains) == null ? void 0 : _e.call(_d, el))) { - el.focus({ preventScroll: true }); } - } : void 0, - tabIndex: -1 - }; - let direction = useTabDirection(); - let handleBeforeFocus = useEvent(() => { - let el = internalPanelRef.current; + event.preventDefault(); + event.stopPropagation(); + dispatch({ type: 1 /* ClosePopover */ }); + (_a3 = state.button) == null ? void 0 : _a3.focus(); + break; + } + }); + (0, import_react37.useEffect)(() => { + var _a3; + if (props.static) + return; + if (state.popoverState === 1 /* Closed */ && ((_a3 = props.unmount) != null ? _a3 : true)) { + dispatch({ type: 4 /* SetPanel */, panel: null }); + } + }, [state.popoverState, props.unmount, props.static, dispatch]); + (0, import_react37.useEffect)(() => { + if (state.__demoMode) + return; + if (!focus) + return; + if (state.popoverState !== 0 /* Open */) + return; + if (!internalPanelRef.current) + return; + let activeElement = ownerDocument == null ? void 0 : ownerDocument.activeElement; + if (internalPanelRef.current.contains(activeElement)) + return; + focusIn(internalPanelRef.current, 1 /* First */); + }, [state.__demoMode, focus, internalPanelRef, state.popoverState]); + let slot = (0, import_react37.useMemo)( + () => ({ open: state.popoverState === 0 /* Open */, close }), + [state, close] + ); + let ourProps = { + ref: panelRef, + id, + onKeyDown: handleKeyDown, + onBlur: focus && state.popoverState === 0 /* Open */ ? (event) => { + var _a3, _b, _c, _d, _e; + let el = event.relatedTarget; if (!el) return; - function run() { - match(direction.current, { - [0 /* Forwards */]: () => { - var _a3; - let result = focusIn(el, 1 /* First */); - if (result === 0 /* Error */) { - (_a3 = state.afterPanelSentinel.current) == null ? void 0 : _a3.focus(); - } - }, - [1 /* Backwards */]: () => { - var _a3; - (_a3 = state.button) == null ? void 0 : _a3.focus({ preventScroll: true }); - } - }); - } - if (false) {} else { - run(); - } - }); - let handleAfterFocus = useEvent(() => { - let el = internalPanelRef.current; - if (!el) + if (!internalPanelRef.current) return; - function run() { - match(direction.current, { - [0 /* Forwards */]: () => { - var _a3; - if (!state.button) - return; - let elements = getFocusableElements(); - let idx = elements.indexOf(state.button); - let before = elements.slice(0, idx + 1); - let after = elements.slice(idx + 1); - let combined = [...after, ...before]; - for (let element of combined.slice()) { - if (element.dataset.headlessuiFocusGuard === "true" || ((_a3 = state.panel) == null ? void 0 : _a3.contains(element))) { - let idx2 = combined.indexOf(element); - if (idx2 !== -1) - combined.splice(idx2, 1); - } - } - focusIn(combined, 1 /* First */, { sorted: false }); - }, - [1 /* Backwards */]: () => { - var _a3; - let result = focusIn(el, 2 /* Previous */); - if (result === 0 /* Error */) { - (_a3 = state.button) == null ? void 0 : _a3.focus(); - } - } - }); - } - if (false) {} else { - run(); - } - }); - return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: id }, visible && isPortalled && /* @__PURE__ */ import_react37.default.createElement( - Hidden, - { - id: beforePanelSentinelId, - ref: state.beforePanelSentinel, - features: 2 /* Focusable */, - "data-headlessui-focus-guard": true, - as: "button", - type: "button", - onFocus: handleBeforeFocus + if ((_a3 = internalPanelRef.current) == null ? void 0 : _a3.contains(el)) + return; + dispatch({ type: 1 /* ClosePopover */ }); + if (((_c = (_b = state.beforePanelSentinel.current) == null ? void 0 : _b.contains) == null ? void 0 : _c.call(_b, el)) || ((_e = (_d = state.afterPanelSentinel.current) == null ? void 0 : _d.contains) == null ? void 0 : _e.call(_d, el))) { + el.focus({ preventScroll: true }); } - ), render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_PANEL_TAG3, - features: PanelRenderFeatures2, - visible, - name: "Popover.Panel" - }), visible && isPortalled && /* @__PURE__ */ import_react37.default.createElement( - Hidden, - { - id: afterPanelSentinelId, - ref: state.afterPanelSentinel, - features: 2 /* Focusable */, - "data-headlessui-focus-guard": true, - as: "button", - type: "button", - onFocus: handleAfterFocus - } - )); - } - var DEFAULT_GROUP_TAG2 = "div"; - function GroupFn2(props, ref) { - let internalGroupRef = (0, import_react37.useRef)(null); - let groupRef = useSyncRefs(internalGroupRef, ref); - let [popovers, setPopovers] = (0, import_react37.useState)([]); - let unregisterPopover = useEvent((registerbag) => { - setPopovers((existing) => { - let idx = existing.indexOf(registerbag); - if (idx !== -1) { - let clone = existing.slice(); - clone.splice(idx, 1); - return clone; - } - return existing; + } : void 0, + tabIndex: -1 + }; + let direction = useTabDirection(); + let handleBeforeFocus = useEvent(() => { + let el = internalPanelRef.current; + if (!el) + return; + function run() { + match(direction.current, { + [0 /* Forwards */]: () => { + var _a3; + let result = focusIn(el, 1 /* First */); + if (result === 0 /* Error */) { + (_a3 = state.afterPanelSentinel.current) == null ? void 0 : _a3.focus(); + } + }, + [1 /* Backwards */]: () => { + var _a3; + (_a3 = state.button) == null ? void 0 : _a3.focus({ preventScroll: true }); + } }); - }); - let registerPopover = useEvent((registerbag) => { - setPopovers((existing) => [...existing, registerbag]); - return () => unregisterPopover(registerbag); - }); - let isFocusWithinPopoverGroup = useEvent(() => { - var _a3; - let ownerDocument = getOwnerDocument(internalGroupRef); - if (!ownerDocument) - return false; - let element = ownerDocument.activeElement; - if ((_a3 = internalGroupRef.current) == null ? void 0 : _a3.contains(element)) - return true; - return popovers.some((bag) => { - var _a4, _b; - return ((_a4 = ownerDocument.getElementById(bag.buttonId.current)) == null ? void 0 : _a4.contains(element)) || ((_b = ownerDocument.getElementById(bag.panelId.current)) == null ? void 0 : _b.contains(element)); + } + if (false) {} else { + run(); + } + }); + let handleAfterFocus = useEvent(() => { + let el = internalPanelRef.current; + if (!el) + return; + function run() { + match(direction.current, { + [0 /* Forwards */]: () => { + var _a3; + if (!state.button) + return; + let elements = getFocusableElements(); + let idx = elements.indexOf(state.button); + let before = elements.slice(0, idx + 1); + let after = elements.slice(idx + 1); + let combined = [...after, ...before]; + for (let element of combined.slice()) { + if (element.dataset.headlessuiFocusGuard === "true" || ((_a3 = state.panel) == null ? void 0 : _a3.contains(element))) { + let idx2 = combined.indexOf(element); + if (idx2 !== -1) + combined.splice(idx2, 1); + } + } + focusIn(combined, 1 /* First */, { sorted: false }); + }, + [1 /* Backwards */]: () => { + var _a3; + let result = focusIn(el, 2 /* Previous */); + if (result === 0 /* Error */) { + (_a3 = state.button) == null ? void 0 : _a3.focus(); + } + } }); + } + if (false) {} else { + run(); + } + }); + return /* @__PURE__ */ import_react37.default.createElement(PopoverPanelContext.Provider, { value: id }, visible && isPortalled && /* @__PURE__ */ import_react37.default.createElement( + Hidden, + { + id: beforePanelSentinelId, + ref: state.beforePanelSentinel, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleBeforeFocus + } + ), render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_PANEL_TAG3, + features: PanelRenderFeatures2, + visible, + name: "Popover.Panel" + }), visible && isPortalled && /* @__PURE__ */ import_react37.default.createElement( + Hidden, + { + id: afterPanelSentinelId, + ref: state.afterPanelSentinel, + features: 2 /* Focusable */, + "data-headlessui-focus-guard": true, + as: "button", + type: "button", + onFocus: handleAfterFocus + } + )); +} +var DEFAULT_GROUP_TAG2 = "div"; +function GroupFn2(props, ref) { + let internalGroupRef = (0, import_react37.useRef)(null); + let groupRef = useSyncRefs(internalGroupRef, ref); + let [popovers, setPopovers] = (0, import_react37.useState)([]); + let unregisterPopover = useEvent((registerbag) => { + setPopovers((existing) => { + let idx = existing.indexOf(registerbag); + if (idx !== -1) { + let clone = existing.slice(); + clone.splice(idx, 1); + return clone; + } + return existing; }); - let closeOthers = useEvent((buttonId) => { - for (let popover of popovers) { - if (popover.buttonId.current !== buttonId) - popover.close(); - } + }); + let registerPopover = useEvent((registerbag) => { + setPopovers((existing) => [...existing, registerbag]); + return () => unregisterPopover(registerbag); + }); + let isFocusWithinPopoverGroup = useEvent(() => { + var _a3; + let ownerDocument = getOwnerDocument(internalGroupRef); + if (!ownerDocument) + return false; + let element = ownerDocument.activeElement; + if ((_a3 = internalGroupRef.current) == null ? void 0 : _a3.contains(element)) + return true; + return popovers.some((bag) => { + var _a4, _b; + return ((_a4 = ownerDocument.getElementById(bag.buttonId.current)) == null ? void 0 : _a4.contains(element)) || ((_b = ownerDocument.getElementById(bag.panelId.current)) == null ? void 0 : _b.contains(element)); }); - let contextBag = (0, import_react37.useMemo)( - () => ({ - registerPopover, - unregisterPopover, - isFocusWithinPopoverGroup, - closeOthers - }), - [registerPopover, unregisterPopover, isFocusWithinPopoverGroup, closeOthers] - ); - let slot = (0, import_react37.useMemo)(() => ({}), []); - let theirProps = props; - let ourProps = { ref: groupRef }; - return /* @__PURE__ */ import_react37.default.createElement(PopoverGroupContext.Provider, { value: contextBag }, render({ - ourProps, - theirProps, - slot, - defaultTag: DEFAULT_GROUP_TAG2, - name: "Popover.Group" - })); - } - var PopoverRoot = forwardRefWithAs(PopoverFn); - var Button5 = forwardRefWithAs(ButtonFn5); - var Overlay2 = forwardRefWithAs(OverlayFn2); - var Panel3 = forwardRefWithAs(PanelFn3); - var Group2 = forwardRefWithAs(GroupFn2); - var Popover = Object.assign(PopoverRoot, { Button: Button5, Overlay: Overlay2, Panel: Panel3, Group: Group2 }); - - // src/components/radio-group/radio-group.tsx - var import_react40 = __toESM(__webpack_require__(/*! react */ "react"), 1); - - // src/hooks/use-flags.ts - var import_react38 = __webpack_require__(/*! react */ "react"); - function useFlags(initialFlags = 0) { - let [flags, setFlags] = (0, import_react38.useState)(initialFlags); - let mounted = useIsMounted(); - let addFlag = (0, import_react38.useCallback)( - (flag) => { - if (!mounted.current) - return; - setFlags((flags2) => flags2 | flag); - }, - [flags, mounted] - ); - let hasFlag = (0, import_react38.useCallback)((flag) => Boolean(flags & flag), [flags]); - let removeFlag = (0, import_react38.useCallback)( - (flag) => { - if (!mounted.current) - return; - setFlags((flags2) => flags2 & ~flag); - }, - [setFlags, mounted] - ); - let toggleFlag = (0, import_react38.useCallback)( - (flag) => { - if (!mounted.current) - return; - setFlags((flags2) => flags2 ^ flag); - }, - [setFlags] - ); - return { flags, addFlag, hasFlag, removeFlag, toggleFlag }; - } - - // src/components/label/label.tsx - var import_react39 = __toESM(__webpack_require__(/*! react */ "react"), 1); - var LabelContext = (0, import_react39.createContext)( - null + }); + let closeOthers = useEvent((buttonId) => { + for (let popover of popovers) { + if (popover.buttonId.current !== buttonId) + popover.close(); + } + }); + let contextBag = (0, import_react37.useMemo)( + () => ({ + registerPopover, + unregisterPopover, + isFocusWithinPopoverGroup, + closeOthers + }), + [registerPopover, unregisterPopover, isFocusWithinPopoverGroup, closeOthers] + ); + let slot = (0, import_react37.useMemo)(() => ({}), []); + let theirProps = props; + let ourProps = { ref: groupRef }; + return /* @__PURE__ */ import_react37.default.createElement(PopoverGroupContext.Provider, { value: contextBag }, render({ + ourProps, + theirProps, + slot, + defaultTag: DEFAULT_GROUP_TAG2, + name: "Popover.Group" + })); +} +var PopoverRoot = forwardRefWithAs(PopoverFn); +var Button5 = forwardRefWithAs(ButtonFn5); +var Overlay2 = forwardRefWithAs(OverlayFn2); +var Panel3 = forwardRefWithAs(PanelFn3); +var Group2 = forwardRefWithAs(GroupFn2); +var Popover = Object.assign(PopoverRoot, { Button: Button5, Overlay: Overlay2, Panel: Panel3, Group: Group2 }); + +// src/components/radio-group/radio-group.tsx +var import_react40 = __toESM(__webpack_require__(/*! react */ "react"), 1); + +// src/hooks/use-flags.ts +var import_react38 = __webpack_require__(/*! react */ "react"); +function useFlags(initialFlags = 0) { + let [flags, setFlags] = (0, import_react38.useState)(initialFlags); + let mounted = useIsMounted(); + let addFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) + return; + setFlags((flags2) => flags2 | flag); + }, + [flags, mounted] + ); + let hasFlag = (0, import_react38.useCallback)((flag) => Boolean(flags & flag), [flags]); + let removeFlag = (0, import_react38.useCallback)( + (flag) => { + if (!mounted.current) + return; + setFlags((flags2) => flags2 & ~flag); + }, + [setFlags, mounted] ); - function useLabelContext() { - let context = (0, import_react39.useContext)(LabelContext); - if (context === null) { - let err = new Error("You used a

    ` tags. - **/ - MarkdownIt.prototype.renderInline = function (src, env) { - env = env || {}; - return this.renderer.render( - this.parseInline(src, env), - this.options, - env - ); - }; - module.exports = MarkdownIt; - - /***/ - }, - - /***/ "../node_modules/mdurl/build/index.cjs.js": - /*!************************************************!*\ - !*** ../node_modules/mdurl/build/index.cjs.js ***! - \************************************************/ - /***/ function (__unused_webpack_module, exports) { - /* eslint-disable no-bitwise */ - const decodeCache = {}; - function getDecodeCache(exclude) { - let cache = decodeCache[exclude]; - if (cache) { - return cache; - } - cache = decodeCache[exclude] = []; - for (let i = 0; i < 128; i++) { - const ch = String.fromCharCode(i); - cache.push(ch); - } - for (let i = 0; i < exclude.length; i++) { - const ch = exclude.charCodeAt(i); - cache[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2); - } - return cache; - } - - // Decode percent-encoded string. - // - function decode(string, exclude) { - if (typeof exclude !== "string") { - exclude = decode.defaultChars; - } - const cache = getDecodeCache(exclude); - return string.replace(/(%[a-f0-9]{2})+/gi, function (seq) { - let result = ""; - for (let i = 0, l = seq.length; i < l; i += 3) { - const b1 = parseInt(seq.slice(i + 1, i + 3), 16); - if (b1 < 0x80) { - result += cache[b1]; - continue; - } - if ((b1 & 0xe0) === 0xc0 && i + 3 < l) { - // 110xxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - if ((b2 & 0xc0) === 0x80) { - const chr = ((b1 << 6) & 0x7c0) | (b2 & 0x3f); - if (chr < 0x80) { - result += "\ufffd\ufffd"; - } else { - result += String.fromCharCode(chr); - } - i += 3; - continue; - } - } - if ((b1 & 0xf0) === 0xe0 && i + 6 < l) { - // 1110xxxx 10xxxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - const b3 = parseInt(seq.slice(i + 7, i + 9), 16); - if ((b2 & 0xc0) === 0x80 && (b3 & 0xc0) === 0x80) { - const chr = - ((b1 << 12) & 0xf000) | ((b2 << 6) & 0xfc0) | (b3 & 0x3f); - if (chr < 0x800 || (chr >= 0xd800 && chr <= 0xdfff)) { - result += "\ufffd\ufffd\ufffd"; - } else { - result += String.fromCharCode(chr); - } - i += 6; - continue; - } - } - if ((b1 & 0xf8) === 0xf0 && i + 9 < l) { - // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx - const b2 = parseInt(seq.slice(i + 4, i + 6), 16); - const b3 = parseInt(seq.slice(i + 7, i + 9), 16); - const b4 = parseInt(seq.slice(i + 10, i + 12), 16); - if ( - (b2 & 0xc0) === 0x80 && - (b3 & 0xc0) === 0x80 && - (b4 & 0xc0) === 0x80 - ) { - let chr = - ((b1 << 18) & 0x1c0000) | - ((b2 << 12) & 0x3f000) | - ((b3 << 6) & 0xfc0) | - (b4 & 0x3f); - if (chr < 0x10000 || chr > 0x10ffff) { - result += "\ufffd\ufffd\ufffd\ufffd"; - } else { - chr -= 0x10000; - result += String.fromCharCode( - 0xd800 + (chr >> 10), - 0xdc00 + (chr & 0x3ff) - ); - } - i += 9; - continue; - } + const fetch2 = fetcher({ + query, + variables, + operationName: opName + }, { + headers: (_headers = headers) !== null && _headers !== void 0 ? _headers : void 0, + documentAST: (_queryEditor$document = queryEditor.documentAST) !== null && _queryEditor$document !== void 0 ? _queryEditor$document : void 0 + }); + const value2 = await Promise.resolve(fetch2); + if (toolkit.isObservable(value2)) { + setSubscription(value2.subscribe({ + next(result) { + handleResponse(result); + }, + error(error) { + setIsFetching(false); + if (error) { + setResponse(toolkit.formatError(error)); } - result += "\ufffd"; + setSubscription(null); + }, + complete() { + setIsFetching(false); + setSubscription(null); } - return result; - }); - } - decode.defaultChars = ";/?:@&=+$,#"; - decode.componentChars = ""; - const encodeCache = {}; - - // Create a lookup array where anything but characters in `chars` string - // and alphanumeric chars is percent-encoded. - // - function getEncodeCache(exclude) { - let cache = encodeCache[exclude]; - if (cache) { - return cache; - } - cache = encodeCache[exclude] = []; - for (let i = 0; i < 128; i++) { - const ch = String.fromCharCode(i); - if (/^[0-9a-z]$/i.test(ch)) { - // always allow unencoded alphanumeric characters - cache.push(ch); - } else { - cache.push("%" + ("0" + i.toString(16).toUpperCase()).slice(-2)); + })); + } else if (toolkit.isAsyncIterable(value2)) { + setSubscription({ + unsubscribe: () => { + var _a, _b; + return (_b = (_a = value2[Symbol.asyncIterator]()).return) == null ? void 0 : _b.call(_a); } + }); + for await (const result of value2) { + handleResponse(result); } - for (let i = 0; i < exclude.length; i++) { - cache[exclude.charCodeAt(i)] = exclude[i]; - } - return cache; + setIsFetching(false); + setSubscription(null); + } else { + handleResponse(value2); } - - // Encode unsafe characters with percent-encoding, skipping already - // encoded sequences. - // - // - string - string to encode - // - exclude - list of characters to ignore (in addition to a-zA-Z0-9) - // - keepEscaped - don't encode '%' in a correct escape sequence (default: true) - // - function encode(string, exclude, keepEscaped) { - if (typeof exclude !== "string") { - // encode(string, keepEscaped) - keepEscaped = exclude; - exclude = encode.defaultChars; - } - if (typeof keepEscaped === "undefined") { - keepEscaped = true; - } - const cache = getEncodeCache(exclude); - let result = ""; - for (let i = 0, l = string.length; i < l; i++) { - const code = string.charCodeAt(i); - if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { - if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { - result += string.slice(i, i + 3); - i += 2; - continue; - } - } - if (code < 128) { - result += cache[code]; - continue; - } - if (code >= 0xd800 && code <= 0xdfff) { - if (code >= 0xd800 && code <= 0xdbff && i + 1 < l) { - const nextCode = string.charCodeAt(i + 1); - if (nextCode >= 0xdc00 && nextCode <= 0xdfff) { - result += encodeURIComponent(string[i] + string[i + 1]); - i++; - continue; - } - } - result += "%EF%BF%BD"; - continue; - } - result += encodeURIComponent(string[i]); - } - return result; + } catch (error) { + setIsFetching(false); + setResponse(toolkit.formatError(error)); + setSubscription(null); + } + }, [autoCompleteLeafs, externalFragments, fetcher, headerEditor, history, operationName, queryEditor, responseEditor, stop, subscription, updateActiveTabValues, variableEditor]); + const isSubscribed = Boolean(subscription); + const value = React.useMemo(() => ({ + isFetching, + isSubscribed, + operationName: operationName !== null && operationName !== void 0 ? operationName : null, + run, + stop + }), [isFetching, isSubscribed, operationName, run, stop]); + return /* @__PURE__ */jsxRuntime.jsx(ExecutionContext.Provider, { + value, + children + }); + } + const useExecutionContext = createContextHook(ExecutionContext); + function tryParseJsonObject({ + json, + errorMessageParse, + errorMessageType + }) { + let parsed; + try { + parsed = json && json.trim() !== "" ? JSON.parse(json) : void 0; + } catch (error) { + throw new Error(`${errorMessageParse}: ${error instanceof Error ? error.message : error}.`); + } + const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed); + if (parsed !== void 0 && !isObject) { + throw new Error(errorMessageType); + } + return parsed; + } + function mergeIncrementalResult(executionResult, incrementalResult) { + var _incrementalResult$pa; + const path = ["data", ...((_incrementalResult$pa = incrementalResult.path) !== null && _incrementalResult$pa !== void 0 ? _incrementalResult$pa : [])]; + if (incrementalResult.items) { + for (const item of incrementalResult.items) { + setValue(executionResult, path.join("."), item); + path[path.length - 1]++; + } + } + if (incrementalResult.data) { + setValue(executionResult, path.join("."), incrementalResult.data, { + merge: true + }); + } + if (incrementalResult.errors) { + executionResult.errors || (executionResult.errors = []); + executionResult.errors.push(...incrementalResult.errors); + } + if (incrementalResult.extensions) { + setValue(executionResult, "extensions", incrementalResult.extensions, { + merge: true + }); + } + if (incrementalResult.incremental) { + for (const incrementalSubResult of incrementalResult.incremental) { + mergeIncrementalResult(executionResult, incrementalSubResult); + } + } + } + const DEFAULT_EDITOR_THEME = "graphiql"; + const DEFAULT_KEY_MAP = "sublime"; + let isMacOs = false; + if (typeof window === "object") { + isMacOs = window.navigator.platform.toLowerCase().indexOf("mac") === 0; + } + const commonKeys = { + // Persistent search box in Query Editor + [isMacOs ? "Cmd-F" : "Ctrl-F"]: "findPersistent", + "Cmd-G": "findPersistent", + "Ctrl-G": "findPersistent", + // Editor improvements + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight" + }; + async function importCodeMirror(addons, options) { + const CodeMirror = await Promise.resolve().then(() => __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js")).then(n => n.codemirror).then(c => + // Depending on bundler and settings the dynamic import either returns a + // function (e.g. parcel) or an object containing a `default` property + typeof c === "function" ? c : c.default); + await Promise.all((options == null ? void 0 : options.useCommonAddons) === false ? addons : [Promise.resolve().then(() => __webpack_require__(/*! ./show-hint.cjs.js */ "../../graphiql-react/dist/show-hint.cjs.js")).then(n => n.showHint), Promise.resolve().then(() => __webpack_require__(/*! ./matchbrackets.cjs.js */ "../../graphiql-react/dist/matchbrackets.cjs.js")).then(n => n.matchbrackets), Promise.resolve().then(() => __webpack_require__(/*! ./closebrackets.cjs.js */ "../../graphiql-react/dist/closebrackets.cjs.js")).then(n => n.closebrackets), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs.js */ "../../graphiql-react/dist/lint.cjs.js")).then(n => n.lint), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), + // @ts-expect-error + Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), ...addons]); + return CodeMirror; + } + const printDefault = ast => { + if (!ast) { + return ""; + } + return graphql.print(ast); + }; + function DefaultValue({ + field + }) { + if (!("defaultValue" in field) || field.defaultValue === void 0) { + return null; + } + const ast = graphql.astFromValue(field.defaultValue, field.type); + if (!ast) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [" = ", /* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-default-value", + children: printDefault(ast) + })] + }); + } + const SchemaContext = createNullableContext("SchemaContext"); + function SchemaContextProvider(props) { + if (!props.fetcher) { + throw new TypeError("The `SchemaContextProvider` component requires a `fetcher` function to be passed as prop."); + } + const { + initialHeaders, + headerEditor + } = useEditorContext({ + nonNull: true, + caller: SchemaContextProvider + }); + const [schema, setSchema] = React.useState(); + const [isFetching, setIsFetching] = React.useState(false); + const [fetchError, setFetchError] = React.useState(null); + const counterRef = React.useRef(0); + React.useEffect(() => { + setSchema(graphql.isSchema(props.schema) || props.schema === null || props.schema === void 0 ? props.schema : void 0); + counterRef.current++; + }, [props.schema]); + const headersRef = React.useRef(initialHeaders); + React.useEffect(() => { + if (headerEditor) { + headersRef.current = headerEditor.getValue(); + } + }); + const { + introspectionQuery, + introspectionQueryName, + introspectionQuerySansSubscriptions + } = useIntrospectionQuery({ + inputValueDeprecation: props.inputValueDeprecation, + introspectionQueryName: props.introspectionQueryName, + schemaDescription: props.schemaDescription + }); + const { + fetcher, + onSchemaChange, + dangerouslyAssumeSchemaIsValid, + children + } = props; + const introspect = React.useCallback(() => { + if (graphql.isSchema(props.schema) || props.schema === null) { + return; + } + const counter = ++counterRef.current; + const maybeIntrospectionData = props.schema; + async function fetchIntrospectionData() { + if (maybeIntrospectionData) { + return maybeIntrospectionData; + } + const parsedHeaders = parseHeaderString(headersRef.current); + if (!parsedHeaders.isValidJSON) { + setFetchError("Introspection failed as headers are invalid."); + return; } - encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; - encode.componentChars = "-_.!~*'()"; - function format(url) { - let result = ""; - result += url.protocol || ""; - result += url.slashes ? "//" : ""; - result += url.auth ? url.auth + "@" : ""; - if (url.hostname && url.hostname.indexOf(":") !== -1) { - // ipv6 address - result += "[" + url.hostname + "]"; - } else { - result += url.hostname || ""; - } - result += url.port ? ":" + url.port : ""; - result += url.pathname || ""; - result += url.search || ""; - result += url.hash || ""; - return result; + const fetcherOpts = parsedHeaders.headers ? { + headers: parsedHeaders.headers + } : {}; + const fetch2 = toolkit.fetcherReturnToPromise(fetcher({ + query: introspectionQuery, + operationName: introspectionQueryName + }, fetcherOpts)); + if (!toolkit.isPromise(fetch2)) { + setFetchError("Fetcher did not return a Promise for introspection."); + return; } - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - // - // Changes from joyent/node: - // - // 1. No leading slash in paths, - // e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` - // - // 2. Backslashes are not replaced with slashes, - // so `http:\\example.org\` is treated like a relative path - // - // 3. Trailing colon is treated like a part of the path, - // i.e. in `http://example.org:foo` pathname is `:foo` - // - // 4. Nothing is URL-encoded in the resulting object, - // (in joyent/node some chars in auth and paths are encoded) - // - // 5. `url.parse()` does not have `parseQueryString` argument - // - // 6. Removed extraneous result properties: `host`, `path`, `query`, etc., - // which can be constructed using other parts of the url. - // - - function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; + setIsFetching(true); + setFetchError(null); + let result = await fetch2; + if (typeof result !== "object" || result === null || !("data" in result)) { + const fetch22 = toolkit.fetcherReturnToPromise(fetcher({ + query: introspectionQuerySansSubscriptions, + operationName: introspectionQueryName + }, fetcherOpts)); + if (!toolkit.isPromise(fetch22)) { + throw new Error("Fetcher did not return a Promise for introspection."); + } + result = await fetch22; + } + setIsFetching(false); + if ((result == null ? void 0 : result.data) && "__schema" in result.data) { + return result.data; } - - // Reference: RFC 3986, RFC 1808, RFC 2396 - - // define these here so at least they only have to be - // compiled once on the first module load. - const protocolPattern = /^([a-z0-9.+-]+:)/i; - const portPattern = /:[0-9]*$/; - - // Special case for a simple path URL - /* eslint-disable-next-line no-useless-escape */ - const simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/; - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - const delims = ["<", ">", '"', "`", " ", "\r", "\n", "\t"]; - - // RFC 2396: characters not allowed for various reasons. - const unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims); - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - const autoEscape = ["'"].concat(unwise); - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - const nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape); - const hostEndingChars = ["/", "?", "#"]; - const hostnameMaxLen = 255; - const hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/; - const hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/; - // protocols that can allow "unsafe" and "unwise" chars. - // protocols that never have a hostname. - const hostlessProtocol = { - javascript: true, - "javascript:": true, - }; - // protocols that always contain a // bit. - const slashedProtocol = { - http: true, - https: true, - ftp: true, - gopher: true, - file: true, - "http:": true, - "https:": true, - "ftp:": true, - "gopher:": true, - "file:": true, - }; - function urlParse(url, slashesDenoteHost) { - if (url && url instanceof Url) return url; - const u = new Url(); - u.parse(url, slashesDenoteHost); - return u; - } - Url.prototype.parse = function (url, slashesDenoteHost) { - let lowerProto, hec, slashes; - let rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - if (!slashesDenoteHost && url.split("#").length === 1) { - // Try fast path regexp - const simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - } - return this; - } - } - let proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - lowerProto = proto.toLowerCase(); - this.protocol = proto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - /* eslint-disable-next-line no-useless-escape */ - if ( - slashesDenoteHost || - proto || - rest.match(/^\/\/[^@\/]+@[^@\/]+/) - ) { - slashes = rest.substr(0, 2) === "//"; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - if ( - !hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto])) - ) { - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - let hostEnd = -1; - for (let i = 0; i < hostEndingChars.length; i++) { - hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { - hostEnd = hec; - } - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - let auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf("@"); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf("@", hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = auth; - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (let i = 0; i < nonHostChars.length; i++) { - hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { - hostEnd = hec; - } - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) { - hostEnd = rest.length; - } - if (rest[hostEnd - 1] === ":") { - hostEnd--; + const responseString = typeof result === "string" ? result : toolkit.formatResult(result); + setFetchError(responseString); + } + fetchIntrospectionData().then(introspectionData => { + if (counter !== counterRef.current || !introspectionData) { + return; + } + try { + const newSchema = graphql.buildClientSchema(introspectionData); + setSchema(newSchema); + onSchemaChange == null ? void 0 : onSchemaChange(newSchema); + } catch (error) { + setFetchError(toolkit.formatError(error)); + } + }).catch(error => { + if (counter !== counterRef.current) { + return; + } + setFetchError(toolkit.formatError(error)); + setIsFetching(false); + }); + }, [fetcher, introspectionQueryName, introspectionQuery, introspectionQuerySansSubscriptions, onSchemaChange, props.schema]); + React.useEffect(() => { + introspect(); + }, [introspect]); + React.useEffect(() => { + function triggerIntrospection(event) { + if (event.ctrlKey && event.key === "R") { + introspect(); + } + } + window.addEventListener("keydown", triggerIntrospection); + return () => window.removeEventListener("keydown", triggerIntrospection); + }); + const validationErrors = React.useMemo(() => { + if (!schema || dangerouslyAssumeSchemaIsValid) { + return []; + } + return graphql.validateSchema(schema); + }, [schema, dangerouslyAssumeSchemaIsValid]); + const value = React.useMemo(() => ({ + fetchError, + introspect, + isFetching, + schema, + validationErrors + }), [fetchError, introspect, isFetching, schema, validationErrors]); + return /* @__PURE__ */jsxRuntime.jsx(SchemaContext.Provider, { + value, + children + }); + } + const useSchemaContext = createContextHook(SchemaContext); + function useIntrospectionQuery({ + inputValueDeprecation, + introspectionQueryName, + schemaDescription + }) { + return React.useMemo(() => { + const queryName = introspectionQueryName || "IntrospectionQuery"; + let query = graphql.getIntrospectionQuery({ + inputValueDeprecation, + schemaDescription + }); + if (introspectionQueryName) { + query = query.replace("query IntrospectionQuery", `query ${queryName}`); + } + const querySansSubscriptions = query.replace("subscriptionType { name }", ""); + return { + introspectionQueryName: queryName, + introspectionQuery: query, + introspectionQuerySansSubscriptions: querySansSubscriptions + }; + }, [inputValueDeprecation, introspectionQueryName, schemaDescription]); + } + function parseHeaderString(headersString) { + let headers = null; + let isValidJSON = true; + try { + if (headersString) { + headers = JSON.parse(headersString); + } + } catch { + isValidJSON = false; + } + return { + headers, + isValidJSON + }; + } + const initialNavStackItem = { + name: "Docs" + }; + const ExplorerContext = createNullableContext("ExplorerContext"); + function ExplorerContextProvider(props) { + const { + schema, + validationErrors + } = useSchemaContext({ + nonNull: true, + caller: ExplorerContextProvider + }); + const [navStack, setNavStack] = React.useState([initialNavStackItem]); + const push = React.useCallback(item => { + setNavStack(currentState => { + const lastItem = currentState.at(-1); + return lastItem.def === item.def ? + // Avoid pushing duplicate items + currentState : [...currentState, item]; + }); + }, []); + const pop = React.useCallback(() => { + setNavStack(currentState => currentState.length > 1 ? currentState.slice(0, -1) : currentState); + }, []); + const reset = React.useCallback(() => { + setNavStack(currentState => currentState.length === 1 ? currentState : [initialNavStackItem]); + }, []); + React.useEffect(() => { + if (schema == null || validationErrors.length > 0) { + reset(); + } else { + setNavStack(oldNavStack => { + if (oldNavStack.length === 1) { + return oldNavStack; + } + const newNavStack = [initialNavStackItem]; + let lastEntity = null; + for (const item of oldNavStack) { + if (item === initialNavStackItem) { + continue; } - const host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(host); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ""; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - const ipv6Hostname = - this.hostname[0] === "[" && - this.hostname[this.hostname.length - 1] === "]"; - - // validate a little. - if (!ipv6Hostname) { - const hostparts = this.hostname.split(/\./); - for (let i = 0, l = hostparts.length; i < l; i++) { - const part = hostparts[i]; - if (!part) { - continue; + if (item.def) { + if (graphql.isNamedType(item.def)) { + const newType = schema.getType(item.def.name); + if (newType) { + newNavStack.push({ + name: item.name, + def: newType + }); + lastEntity = newType; + } else { + break; + } + } else if (lastEntity === null) { + break; + } else if (graphql.isObjectType(lastEntity) || graphql.isInputObjectType(lastEntity)) { + const field = lastEntity.getFields()[item.name]; + if (field) { + newNavStack.push({ + name: item.name, + def: field + }); + } else { + break; } - if (!part.match(hostnamePartPattern)) { - let newpart = ""; - for (let j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += "x"; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - const validParts = hostparts.slice(0, i); - const notHost = hostparts.slice(i + 1); - const bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = notHost.join(".") + rest; - } - this.hostname = validParts.join("."); - break; - } + } else if (graphql.isScalarType(lastEntity) || graphql.isEnumType(lastEntity) || graphql.isInterfaceType(lastEntity) || graphql.isUnionType(lastEntity)) { + break; + } else { + const field = lastEntity; + const arg = field.args.find(a => a.name === item.name); + if (arg) { + newNavStack.push({ + name: item.name, + def: field + }); + } else { + break; } } + } else { + lastEntity = null; + newNavStack.push(item); } - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ""; - } - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - } - } - - // chop off from the tail first. - const hash = rest.indexOf("#"); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - const qm = rest.indexOf("?"); - if (qm !== -1) { - this.search = rest.substr(qm); - rest = rest.slice(0, qm); - } - if (rest) { - this.pathname = rest; - } - if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { - this.pathname = ""; - } - return this; - }; - Url.prototype.parseHost = function (host) { - let port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ":") { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); } - if (host) { - this.hostname = host; - } - }; - exports.decode = decode; - exports.encode = encode; - exports.format = format; - exports.parse = urlParse; - - /***/ - }, - - /***/ "../node_modules/uc.micro/build/index.cjs.js": - /*!***************************************************!*\ - !*** ../node_modules/uc.micro/build/index.cjs.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports) { - var regex$5 = - /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - var regex$4 = /[\0-\x1F\x7F-\x9F]/; - var regex$3 = - /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/; - var regex$2 = - /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/; - var regex$1 = - /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/; - var regex = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/; - exports.Any = regex$5; - exports.Cc = regex$4; - exports.Cf = regex$3; - exports.P = regex$2; - exports.S = regex$1; - exports.Z = regex; - - /***/ - }, - - /***/ "./components/GraphiQL.tsx": - /*!*********************************!*\ - !*** ./components/GraphiQL.tsx ***! - \*********************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, + return newNavStack; }); - exports.GraphiQL = GraphiQL; - exports.GraphiQLInterface = GraphiQLInterface; - var _react = _interopRequireWildcard( - __webpack_require__(/*! react */ "react") - ); - var _react2 = __webpack_require__( - /*! @graphiql/react */ "../../graphiql-react/dist/index.js" - ); - function _getRequireWildcardCache(e) { - if ("function" != typeof WeakMap) return null; - var r = new WeakMap(), - t = new WeakMap(); - return (_getRequireWildcardCache = function (e) { - return e ? t : r; - })(e); - } - function _interopRequireWildcard(e, r) { - if (!r && e && e.__esModule) return e; - if (null === e || ("object" != typeof e && "function" != typeof e)) - return { default: e }; - var t = _getRequireWildcardCache(r); - if (t && t.has(e)) return t.get(e); - var n = { __proto__: null }, - a = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var u in e) - if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { - var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; - i && (i.get || i.set) - ? Object.defineProperty(n, u, i) - : (n[u] = e[u]); - } - return (n.default = e), t && t.set(e, n), n; - } - function _extends() { - _extends = Object.assign - ? Object.assign.bind() - : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends.apply(this, arguments); - } - /** - * Copyright (c) 2020 GraphQL Contributors. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - const majorVersion = parseInt(_react.default.version.slice(0, 2), 10); - if (majorVersion < 16) { - throw new Error( - [ - "GraphiQL 0.18.0 and after is not compatible with React 15 or below.", - "If you are using a CDN source (jsdelivr, unpkg, etc), follow this example:", - "https://github.com/graphql/graphiql/blob/master/examples/graphiql-cdn/index.html#L49", - ].join("\n") - ); - } - - /** - * API docs for this live here: - * - * https://graphiql-test.netlify.app/typedoc/modules/graphiql.html#graphiqlprops - */ - - /** - * The top-level React component for GraphiQL, intended to encompass the entire - * browser viewport. - * - * @see https://github.com/graphql/graphiql#usage - */ - - function GraphiQL({ - dangerouslyAssumeSchemaIsValid, - defaultQuery, - defaultTabs, - externalFragments, - fetcher, - getDefaultFieldNames, - headers, - inputValueDeprecation, - introspectionQueryName, - maxHistoryLength, - onEditOperationName, - onSchemaChange, - onTabChange, - onTogglePluginVisibility, - operationName, - plugins, - query, - response, - schema, - schemaDescription, - shouldPersistHeaders, - storage, - validationRules, - variables, - visiblePlugin, - defaultHeaders, - ...props - }) { - var _props$disableTabs; - // Ensure props are correct - if (typeof fetcher !== "function") { - throw new TypeError( - "The `GraphiQL` component requires a `fetcher` function to be passed as prop." - ); - } - return /*#__PURE__*/ _react.default.createElement( - _react2.GraphiQLProvider, - { - getDefaultFieldNames: getDefaultFieldNames, - dangerouslyAssumeSchemaIsValid: dangerouslyAssumeSchemaIsValid, - defaultQuery: defaultQuery, - defaultHeaders: defaultHeaders, - defaultTabs: defaultTabs, - externalFragments: externalFragments, - fetcher: fetcher, - headers: headers, - inputValueDeprecation: inputValueDeprecation, - introspectionQueryName: introspectionQueryName, - maxHistoryLength: maxHistoryLength, - onEditOperationName: onEditOperationName, - onSchemaChange: onSchemaChange, - onTabChange: onTabChange, - onTogglePluginVisibility: onTogglePluginVisibility, - plugins: plugins, - visiblePlugin: visiblePlugin, - operationName: operationName, - query: query, - response: response, - schema: schema, - schemaDescription: schemaDescription, - shouldPersistHeaders: shouldPersistHeaders, - storage: storage, - validationRules: validationRules, - variables: variables, - }, - /*#__PURE__*/ _react.default.createElement( - GraphiQLInterface, - _extends( - { - showPersistHeadersSettings: shouldPersistHeaders !== false, - disableTabs: - (_props$disableTabs = props.disableTabs) !== null && - _props$disableTabs !== void 0 - ? _props$disableTabs - : false, - forcedTheme: props.forcedTheme, - }, - props - ) - ) - ); + } + }, [reset, schema, validationErrors]); + const value = React.useMemo(() => ({ + explorerNavStack: navStack, + push, + pop, + reset + }), [navStack, push, pop, reset]); + return /* @__PURE__ */jsxRuntime.jsx(ExplorerContext.Provider, { + value, + children: props.children + }); + } + const useExplorerContext = createContextHook(ExplorerContext); + function renderType(type, renderNamedType) { + if (graphql.isNonNullType(type)) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [renderType(type.ofType, renderNamedType), "!"] + }); + } + if (graphql.isListType(type)) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["[", renderType(type.ofType, renderNamedType), "]"] + }); + } + return renderNamedType(type); + } + function TypeLink(props) { + const { + push + } = useExplorerContext({ + nonNull: true, + caller: TypeLink + }); + if (!props.type) { + return null; + } + return renderType(props.type, namedType => /* @__PURE__ */jsxRuntime.jsx("a", { + className: "graphiql-doc-explorer-type-name", + onClick: event => { + event.preventDefault(); + push({ + name: namedType.name, + def: namedType + }); + }, + href: "#", + children: namedType.name + })); + } + function Argument({ + arg, + showDefaultValue, + inline + }) { + const definition = /* @__PURE__ */jsxRuntime.jsxs("span", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-argument-name", + children: arg.name + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: arg.type + }), showDefaultValue !== false && /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { + field: arg + })] + }); + if (inline) { + return definition; + } + return /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-argument", + children: [definition, arg.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: arg.description + }) : null, arg.deprecationReason ? /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-argument-deprecation", + children: [/* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-argument-deprecation-label", + children: "Deprecated" + }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + children: arg.deprecationReason + })] + }) : null] + }); + } + function DeprecationReason(props) { + var _props$preview; + return props.children ? /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-deprecation", + children: [/* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-deprecation-label", + children: "Deprecated" + }), /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + onlyShowFirstChild: (_props$preview = props.preview) !== null && _props$preview !== void 0 ? _props$preview : true, + children: props.children + })] + }) : null; + } + function Directive({ + directive + }) { + return /* @__PURE__ */jsxRuntime.jsxs("span", { + className: "graphiql-doc-explorer-directive", + children: ["@", directive.name.value] + }); + } + function ExplorerSection(props) { + const Icon2 = TYPE_TO_ICON[props.title]; + return /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-section-title", + children: [/* @__PURE__ */jsxRuntime.jsx(Icon2, {}), props.title] + }), /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-section-content", + children: props.children + })] + }); + } + const TYPE_TO_ICON = { + Arguments: ArgumentIcon, + "Deprecated Arguments": DeprecatedArgumentIcon, + "Deprecated Enum Values": DeprecatedEnumValueIcon, + "Deprecated Fields": DeprecatedFieldIcon, + Directives: DirectiveIcon, + "Enum Values": EnumValueIcon, + Fields: FieldIcon, + Implements: ImplementsIcon, + Implementations: TypeIcon, + "Possible Types": TypeIcon, + "Root Types": RootTypeIcon, + Type: TypeIcon, + "All Schema Types": TypeIcon + }; + function FieldDocumentation(props) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [props.field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.field.description + }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { + preview: false, + children: props.field.deprecationReason + }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Type", + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: props.field.type + }) + }), /* @__PURE__ */jsxRuntime.jsx(Arguments, { + field: props.field + }), /* @__PURE__ */jsxRuntime.jsx(Directives, { + field: props.field + })] + }); + } + function Arguments({ + field + }) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!("args" in field)) { + return null; + } + const args = []; + const deprecatedArgs = []; + for (const argument of field.args) { + if (argument.deprecationReason) { + deprecatedArgs.push(argument); + } else { + args.push(argument); + } + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [args.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Arguments", + children: args.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg + }, arg.name)) + }) : null, deprecatedArgs.length > 0 ? showDeprecated || args.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Arguments", + children: deprecatedArgs.map(arg => /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg + }, arg.name)) + }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Arguments" + }) : null] + }); + } + function Directives({ + field + }) { + var _a; + const directives = ((_a = field.astNode) == null ? void 0 : _a.directives) || []; + if (!directives || directives.length === 0) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Directives", + children: directives.map(directive => /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(Directive, { + directive + }) + }, directive.name.value)) + }); + } + function SchemaDocumentation(props) { + var _a, _b, _c, _d; + const queryType = props.schema.getQueryType(); + const mutationType = (_b = (_a = props.schema).getMutationType) == null ? void 0 : _b.call(_a); + const subscriptionType = (_d = (_c = props.schema).getSubscriptionType) == null ? void 0 : _d.call(_c); + const typeMap = props.schema.getTypeMap(); + const ignoreTypesInAllSchema = [queryType == null ? void 0 : queryType.name, mutationType == null ? void 0 : mutationType.name, subscriptionType == null ? void 0 : subscriptionType.name]; + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.schema.description || "A GraphQL schema provides a root type for each kind of operation." + }), /* @__PURE__ */jsxRuntime.jsxs(ExplorerSection, { + title: "Root Types", + children: [queryType ? /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "query" + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: queryType + })] + }) : null, mutationType && /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "mutation" + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: mutationType + })] + }), subscriptionType && /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-root-type", + children: "subscription" + }), ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: subscriptionType + })] + })] + }), /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "All Schema Types", + children: typeMap && /* @__PURE__ */jsxRuntime.jsx("div", { + children: Object.values(typeMap).map(type => { + if (ignoreTypesInAllSchema.includes(type.name) || type.name.startsWith("__")) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type + }) + }, type.name); + }) + }) + })] + }); + } + function debounce(duration, fn) { + let timeout; + return function (...args) { + if (timeout) { + window.clearTimeout(timeout); + } + timeout = window.setTimeout(() => { + timeout = null; + fn(...args); + }, duration); + }; + } + function Search() { + const { + explorerNavStack, + push + } = useExplorerContext({ + nonNull: true, + caller: Search + }); + const inputRef = React.useRef(null); + const getSearchResults = useSearchResults(); + const [searchValue, setSearchValue] = React.useState(""); + const [results, setResults] = React.useState(getSearchResults(searchValue)); + const debouncedGetSearchResults = React.useMemo(() => debounce(200, search => { + setResults(getSearchResults(search)); + }), [getSearchResults]); + React.useEffect(() => { + debouncedGetSearchResults(searchValue); + }, [debouncedGetSearchResults, searchValue]); + React.useEffect(() => { + function handleKeyDown(event) { + var _a; + if (event.metaKey && event.key === "k") { + (_a = inputRef.current) == null ? void 0 : _a.focus(); } - - // Export main windows/panes to be used separately if desired. - GraphiQL.Logo = GraphiQLLogo; - GraphiQL.Toolbar = GraphiQLToolbar; - GraphiQL.Footer = GraphiQLFooter; - const THEMES = ["light", "dark", "system"]; - function GraphiQLInterface(props) { - var _props$isHeadersEdito, - _pluginContext$visibl, - _props$toolbar, - _props$toolbar2; - const isHeadersEditorEnabled = - (_props$isHeadersEdito = props.isHeadersEditorEnabled) !== null && - _props$isHeadersEdito !== void 0 - ? _props$isHeadersEdito - : true; - const editorContext = (0, _react2.useEditorContext)({ - nonNull: true, - }); - const executionContext = (0, _react2.useExecutionContext)({ - nonNull: true, - }); - const schemaContext = (0, _react2.useSchemaContext)({ - nonNull: true, - }); - const storageContext = (0, _react2.useStorageContext)(); - const pluginContext = (0, _react2.usePluginContext)(); - const forcedTheme = (0, _react.useMemo)( - () => - props.forcedTheme && THEMES.includes(props.forcedTheme) - ? props.forcedTheme - : undefined, - [props.forcedTheme] - ); - const copy = (0, _react2.useCopyQuery)({ - onCopyQuery: props.onCopyQuery, - }); - const merge = (0, _react2.useMergeQuery)(); - const prettify = (0, _react2.usePrettifyEditors)(); - const { theme, setTheme } = (0, _react2.useTheme)(); - (0, _react.useEffect)(() => { - if (forcedTheme === "system") { - setTheme(null); - } else if (forcedTheme === "light" || forcedTheme === "dark") { - setTheme(forcedTheme); - } - }, [forcedTheme, setTheme]); - const PluginContent = - pluginContext === null || pluginContext === void 0 - ? void 0 - : (_pluginContext$visibl = pluginContext.visiblePlugin) === - null || _pluginContext$visibl === void 0 - ? void 0 - : _pluginContext$visibl.content; - const pluginResize = (0, _react2.useDragResize)({ - defaultSizeRelation: 1 / 3, - direction: "horizontal", - initiallyHidden: - pluginContext !== null && - pluginContext !== void 0 && - pluginContext.visiblePlugin - ? undefined - : "first", - onHiddenElementChange(resizableElement) { - if (resizableElement === "first") { - pluginContext === null || pluginContext === void 0 - ? void 0 - : pluginContext.setVisiblePlugin(null); - } - }, - sizeThresholdSecond: 200, - storageKey: "docExplorerFlex", - }); - const editorResize = (0, _react2.useDragResize)({ - direction: "horizontal", - storageKey: "editorFlex", - }); - const editorToolsResize = (0, _react2.useDragResize)({ - defaultSizeRelation: 3, - direction: "vertical", - initiallyHidden: (() => { - if ( - props.defaultEditorToolsVisibility === "variables" || - props.defaultEditorToolsVisibility === "headers" - ) { - return; - } - if (typeof props.defaultEditorToolsVisibility === "boolean") { - return props.defaultEditorToolsVisibility - ? undefined - : "second"; + } + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, []); + const navItem = explorerNavStack.at(-1); + const onSelect = React.useCallback(def => { + push("field" in def ? { + name: def.field.name, + def: def.field + } : { + name: def.type.name, + def: def.type + }); + }, [push]); + const isFocused = React.useRef(false); + const handleFocus = React.useCallback(e => { + isFocused.current = e.type === "focus"; + }, []); + const shouldSearchBoxAppear = explorerNavStack.length === 1 || graphql.isObjectType(navItem.def) || graphql.isInterfaceType(navItem.def) || graphql.isInputObjectType(navItem.def); + if (!shouldSearchBoxAppear) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsxs(react.Combobox, { + as: "div", + className: "graphiql-doc-explorer-search", + onChange: onSelect, + "data-state": isFocused ? void 0 : "idle", + "aria-label": `Search ${navItem.name}...`, + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-search-input", + onClick: () => { + var _a; + (_a = inputRef.current) == null ? void 0 : _a.focus(); + }, + children: [/* @__PURE__ */jsxRuntime.jsx(MagnifyingGlassIcon, {}), /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Input, { + autoComplete: "off", + onFocus: handleFocus, + onBlur: handleFocus, + onChange: event => setSearchValue(event.target.value), + placeholder: "⌘ K", + ref: inputRef, + value: searchValue, + "data-cy": "doc-explorer-input" + })] + }), isFocused.current && /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Options, { + "data-cy": "doc-explorer-list", + children: [results.within.length + results.types.length + results.fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx("li", { + className: "graphiql-doc-explorer-search-empty", + children: "No results found" + }) : results.within.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { + value: result, + "data-cy": "doc-explorer-option", + children: /* @__PURE__ */jsxRuntime.jsx(Field$1, { + field: result.field, + argument: result.argument + }) + }, `within-${i}`)), results.within.length > 0 && results.types.length + results.fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-search-divider", + children: "Other results" + }) : null, results.types.map((result, i) => /* @__PURE__ */jsxRuntime.jsx(react.Combobox.Option, { + value: result, + "data-cy": "doc-explorer-option", + children: /* @__PURE__ */jsxRuntime.jsx(Type, { + type: result.type + }) + }, `type-${i}`)), results.fields.map((result, i) => /* @__PURE__ */jsxRuntime.jsxs(react.Combobox.Option, { + value: result, + "data-cy": "doc-explorer-option", + children: [/* @__PURE__ */jsxRuntime.jsx(Type, { + type: result.type + }), ".", /* @__PURE__ */jsxRuntime.jsx(Field$1, { + field: result.field, + argument: result.argument + })] + }, `field-${i}`))] + })] + }); + } + function useSearchResults(caller) { + const { + explorerNavStack + } = useExplorerContext({ + nonNull: true, + caller: caller || useSearchResults + }); + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: caller || useSearchResults + }); + const navItem = explorerNavStack.at(-1); + return React.useCallback(searchValue => { + const matches = { + within: [], + types: [], + fields: [] + }; + if (!schema) { + return matches; + } + const withinType = navItem.def; + const typeMap = schema.getTypeMap(); + let typeNames = Object.keys(typeMap); + if (withinType) { + typeNames = typeNames.filter(n => n !== withinType.name); + typeNames.unshift(withinType.name); + } + for (const typeName of typeNames) { + if (matches.within.length + matches.types.length + matches.fields.length >= 100) { + break; + } + const type = typeMap[typeName]; + if (withinType !== type && isMatch(typeName, searchValue)) { + matches.types.push({ + type + }); + } + if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { + continue; + } + const fields = type.getFields(); + for (const fieldName in fields) { + const field = fields[fieldName]; + let matchingArgs; + if (!isMatch(fieldName, searchValue)) { + if ("args" in field) { + matchingArgs = field.args.filter(arg => isMatch(arg.name, searchValue)); + if (matchingArgs.length === 0) { + continue; } - return editorContext.initialVariables || - editorContext.initialHeaders - ? undefined - : "second"; - })(), - sizeThresholdSecond: 60, - storageKey: "secondaryEditorFlex", - }); - const [activeSecondaryEditor, setActiveSecondaryEditor] = (0, - _react.useState)(() => { - if ( - props.defaultEditorToolsVisibility === "variables" || - props.defaultEditorToolsVisibility === "headers" - ) { - return props.defaultEditorToolsVisibility; - } - return !editorContext.initialVariables && - editorContext.initialHeaders && - isHeadersEditorEnabled - ? "headers" - : "variables"; - }); - const [showDialog, setShowDialog] = (0, _react.useState)(null); - const [clearStorageStatus, setClearStorageStatus] = (0, - _react.useState)(null); - const children = _react.default.Children.toArray(props.children); - const logo = - children.find((child) => - isChildComponentType(child, GraphiQL.Logo) - ) || - /*#__PURE__*/ _react.default.createElement(GraphiQL.Logo, null); - const toolbar = - children.find((child) => - isChildComponentType(child, GraphiQL.Toolbar) - ) || - /*#__PURE__*/ _react.default.createElement( - _react.default.Fragment, - null, - /*#__PURE__*/ _react.default.createElement( - _react2.ToolbarButton, - { - onClick: prettify, - label: "Prettify query (Shift-Ctrl-P)", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.PrettifyIcon, - { - className: "graphiql-toolbar-icon", - "aria-hidden": "true", - } - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.ToolbarButton, - { - onClick: merge, - label: "Merge fragments into query (Shift-Ctrl-M)", - }, - /*#__PURE__*/ _react.default.createElement(_react2.MergeIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true", - }) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.ToolbarButton, - { - onClick: copy, - label: "Copy query (Shift-Ctrl-C)", - }, - /*#__PURE__*/ _react.default.createElement(_react2.CopyIcon, { - className: "graphiql-toolbar-icon", - "aria-hidden": "true", - }) - ), - (_props$toolbar = props.toolbar) === null || - _props$toolbar === void 0 - ? void 0 - : _props$toolbar.additionalContent, - ((_props$toolbar2 = props.toolbar) === null || - _props$toolbar2 === void 0 - ? void 0 - : _props$toolbar2.additionalComponent) && - /*#__PURE__*/ _react.default.createElement( - props.toolbar.additionalComponent, - null - ) - ); - const footer = children.find((child) => - isChildComponentType(child, GraphiQL.Footer) - ); - const onClickReference = (0, _react.useCallback)(() => { - if (pluginResize.hiddenElement === "first") { - pluginResize.setHiddenElement(null); + } else { + continue; } - }, [pluginResize]); - const handleClearData = (0, _react.useCallback)(() => { - try { - storageContext === null || storageContext === void 0 - ? void 0 - : storageContext.clear(); - setClearStorageStatus("success"); - } catch { - setClearStorageStatus("error"); - } - }, [storageContext]); - const handlePersistHeaders = (0, _react.useCallback)( - (event) => { - editorContext.setShouldPersistHeaders( - event.currentTarget.dataset.value === "true" - ); - }, - [editorContext] - ); - const handleChangeTheme = (0, _react.useCallback)( - (event) => { - const selectedTheme = event.currentTarget.dataset.theme; - setTheme(selectedTheme || null); - }, - [setTheme] - ); - const handleAddTab = editorContext.addTab; - const handleRefetchSchema = schemaContext.introspect; - const handleReorder = editorContext.moveTab; - const handleShowDialog = (0, _react.useCallback)((event) => { - setShowDialog(event.currentTarget.dataset.value); - }, []); - const handlePluginClick = (0, _react.useCallback)( - (e) => { - const context = pluginContext; - const pluginIndex = Number(e.currentTarget.dataset.index); - const plugin = context.plugins.find( - (_, index) => pluginIndex === index - ); - const isVisible = plugin === context.visiblePlugin; - if (isVisible) { - context.setVisiblePlugin(null); - pluginResize.setHiddenElement("first"); - } else { - context.setVisiblePlugin(plugin); - pluginResize.setHiddenElement(null); - } - }, - [pluginContext, pluginResize] - ); - const handleToolsTabClick = (0, _react.useCallback)( - (event) => { - if (editorToolsResize.hiddenElement === "second") { - editorToolsResize.setHiddenElement(null); - } - setActiveSecondaryEditor(event.currentTarget.dataset.name); - }, - [editorToolsResize] - ); - const toggleEditorTools = (0, _react.useCallback)(() => { - editorToolsResize.setHiddenElement( - editorToolsResize.hiddenElement === "second" ? null : "second" - ); - }, [editorToolsResize]); - const handleOpenShortKeysDialog = (0, _react.useCallback)( - (isOpen) => { - if (!isOpen) { - setShowDialog(null); - } - }, - [] - ); - const handleOpenSettingsDialog = (0, _react.useCallback)((isOpen) => { - if (!isOpen) { - setShowDialog(null); - setClearStorageStatus(null); - } - }, []); - const addTab = /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip, - { - label: "Add tab", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - className: "graphiql-tab-add", - onClick: handleAddTab, - "aria-label": "Add tab", - }, - /*#__PURE__*/ _react.default.createElement(_react2.PlusIcon, { - "aria-hidden": "true", + } + matches[withinType === type ? "within" : "fields"].push(...(matchingArgs ? matchingArgs.map(argument => ({ + type, + field, + argument + })) : [{ + type, + field + }])); + } + } + return matches; + }, [navItem.def, schema]); + } + function isMatch(sourceText, searchValue) { + try { + const escaped = searchValue.replaceAll(/[^_0-9A-Za-z]/g, ch => "\\" + ch); + return sourceText.search(new RegExp(escaped, "i")) !== -1; + } catch { + return sourceText.toLowerCase().includes(searchValue.toLowerCase()); + } + } + function Type(props) { + return /* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-type", + children: props.type.name + }); + } + function Field$1({ + field, + argument + }) { + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [/* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-field", + children: field.name + }), argument ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { + className: "graphiql-doc-explorer-search-argument", + children: argument.name + }), ":", " ", renderType(argument.type, namedType => /* @__PURE__ */jsxRuntime.jsx(Type, { + type: namedType + })), ")"] + }) : null] + }); + } + function FieldLink(props) { + const { + push + } = useExplorerContext({ + nonNull: true + }); + return /* @__PURE__ */jsxRuntime.jsx("a", { + className: "graphiql-doc-explorer-field-name", + onClick: event => { + event.preventDefault(); + push({ + name: props.field.name, + def: props.field + }); + }, + href: "#", + children: props.field.name + }); + } + function TypeDocumentation(props) { + return graphql.isNamedType(props.type) ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [props.type.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: props.type.description + }) : null, /* @__PURE__ */jsxRuntime.jsx(ImplementsInterfaces, { + type: props.type + }), /* @__PURE__ */jsxRuntime.jsx(Fields, { + type: props.type + }), /* @__PURE__ */jsxRuntime.jsx(EnumValues, { + type: props.type + }), /* @__PURE__ */jsxRuntime.jsx(PossibleTypes, { + type: props.type + })] + }) : null; + } + function ImplementsInterfaces({ + type + }) { + if (!graphql.isObjectType(type)) { + return null; + } + const interfaces = type.getInterfaces(); + return interfaces.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Implements", + children: type.getInterfaces().map(implementedInterface => /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: implementedInterface + }) + }, implementedInterface.name)) + }) : null; + } + function Fields({ + type + }) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!graphql.isObjectType(type) && !graphql.isInterfaceType(type) && !graphql.isInputObjectType(type)) { + return null; + } + const fieldMap = type.getFields(); + const fields = []; + const deprecatedFields = []; + for (const field of Object.keys(fieldMap).map(name => fieldMap[name])) { + if (field.deprecationReason) { + deprecatedFields.push(field); + } else { + fields.push(field); + } + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [fields.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Fields", + children: fields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { + field + }, field.name)) + }) : null, deprecatedFields.length > 0 ? showDeprecated || fields.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Fields", + children: deprecatedFields.map(field => /* @__PURE__ */jsxRuntime.jsx(Field, { + field + }, field.name)) + }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Fields" + }) : null] + }); + } + function Field({ + field + }) { + const args = "args" in field ? field.args.filter(arg => !arg.deprecationReason) : []; + return /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-item", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx(FieldLink, { + field + }), args.length > 0 ? /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: ["(", /* @__PURE__ */jsxRuntime.jsx("span", { + children: args.map(arg => args.length === 1 ? /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg, + inline: true + }, arg.name) : /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-argument-multiple", + children: /* @__PURE__ */jsxRuntime.jsx(Argument, { + arg, + inline: true }) - ) - ); - const className = props.className ? ` ${props.className}` : ""; - return /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip.Provider, - null, - /*#__PURE__*/ _react.default.createElement( - "div", - { - "data-testid": "graphiql-container", - className: `graphiql-container${className}`, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-sidebar", - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-sidebar-section", - }, - pluginContext === null || pluginContext === void 0 - ? void 0 - : pluginContext.plugins.map((plugin, index) => { - const isVisible = - plugin === pluginContext.visiblePlugin; - const label = `${isVisible ? "Hide" : "Show"} ${ - plugin.title - }`; - const Icon = plugin.icon; - return /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip, - { - key: plugin.title, - label: label, - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - className: isVisible ? "active" : "", - onClick: handlePluginClick, - "data-index": index, - "aria-label": label, - }, - /*#__PURE__*/ _react.default.createElement(Icon, { - "aria-hidden": "true", - }) - ) - ); - }) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-sidebar-section", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip, - { - label: "Re-fetch GraphQL schema", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - disabled: schemaContext.isFetching, - onClick: handleRefetchSchema, - "aria-label": "Re-fetch GraphQL schema", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.ReloadIcon, - { - className: schemaContext.isFetching - ? "graphiql-spin" - : "", - "aria-hidden": "true", - } - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip, - { - label: "Open short keys dialog", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - "data-value": "short-keys", - onClick: handleShowDialog, - "aria-label": "Open short keys dialog", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.KeyboardShortcutIcon, - { - "aria-hidden": "true", - } - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip, - { - label: "Open settings dialog", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - "data-value": "settings", - onClick: handleShowDialog, - "aria-label": "Open settings dialog", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.SettingsIcon, - { - "aria-hidden": "true", - } - ) - ) - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-main", - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: pluginResize.firstRef, - style: { - // Make sure the container shrinks when containing long - // non-breaking texts - minWidth: "200px", - }, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-plugin", - }, - PluginContent - ? /*#__PURE__*/ _react.default.createElement( - PluginContent, - null - ) - : null - ) - ), - (pluginContext === null || pluginContext === void 0 - ? void 0 - : pluginContext.visiblePlugin) && - /*#__PURE__*/ _react.default.createElement("div", { - className: "graphiql-horizontal-drag-bar", - ref: pluginResize.dragBarRef, - }), - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: pluginResize.secondRef, - className: "graphiql-sessions", - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-session-header", - }, - !props.disableTabs && - /*#__PURE__*/ _react.default.createElement( - _react2.Tabs, - { - values: editorContext.tabs, - onReorder: handleReorder, - "aria-label": "Select active operation", - }, - editorContext.tabs.length > 1 && - /*#__PURE__*/ _react.default.createElement( - _react.default.Fragment, - null, - editorContext.tabs.map((tab, index) => - /*#__PURE__*/ _react.default.createElement( - _react2.Tab, - { - key: tab.id, - value: tab, - isActive: - index === editorContext.activeTabIndex, - }, - /*#__PURE__*/ _react.default.createElement( - _react2.Tab.Button, - { - "aria-controls": "graphiql-session", - id: `graphiql-session-tab-${index}`, - onClick: () => { - executionContext.stop(); - editorContext.changeTab(index); - }, - }, - tab.title - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Tab.Close, - { - onClick: () => { - if ( - editorContext.activeTabIndex === index - ) { - executionContext.stop(); - } - editorContext.closeTab(index); - }, - } - ) - ) - ), - addTab - ) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-session-header-right", - }, - editorContext.tabs.length === 1 && addTab, - logo - ) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - role: "tabpanel", - id: "graphiql-session", - className: "graphiql-session", - "aria-labelledby": `graphiql-session-tab-${editorContext.activeTabIndex}`, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: editorResize.firstRef, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: `graphiql-editors${ - editorContext.tabs.length === 1 - ? " full-height" - : "" - }`, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: editorToolsResize.firstRef, - }, - /*#__PURE__*/ _react.default.createElement( - "section", - { - className: "graphiql-query-editor", - "aria-label": "Query Editor", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.QueryEditor, - { - editorTheme: props.editorTheme, - keyMap: props.keyMap, - onClickReference: onClickReference, - onCopyQuery: props.onCopyQuery, - onEdit: props.onEditQuery, - readOnly: props.readOnly, - } - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-toolbar", - role: "toolbar", - "aria-label": "Editor Commands", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.ExecuteButton, - null - ), - toolbar - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: editorToolsResize.dragBarRef, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-editor-tools", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - className: - activeSecondaryEditor === "variables" && - editorToolsResize.hiddenElement !== "second" - ? "active" - : "", - onClick: handleToolsTabClick, - "data-name": "variables", - }, - "Variables" - ), - isHeadersEditorEnabled && - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - className: - activeSecondaryEditor === "headers" && - editorToolsResize.hiddenElement !== "second" - ? "active" - : "", - onClick: handleToolsTabClick, - "data-name": "headers", - }, - "Headers" - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Tooltip, - { - label: - editorToolsResize.hiddenElement === "second" - ? "Show editor tools" - : "Hide editor tools", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.UnStyledButton, - { - type: "button", - onClick: toggleEditorTools, - "aria-label": - editorToolsResize.hiddenElement === "second" - ? "Show editor tools" - : "Hide editor tools", - className: "graphiql-toggle-editor-tools", - }, - editorToolsResize.hiddenElement === "second" - ? /*#__PURE__*/ _react.default.createElement( - _react2.ChevronUpIcon, - { - className: "graphiql-chevron-icon", - "aria-hidden": "true", - } - ) - : /*#__PURE__*/ _react.default.createElement( - _react2.ChevronDownIcon, - { - className: "graphiql-chevron-icon", - "aria-hidden": "true", - } - ) - ) - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: editorToolsResize.secondRef, - }, - /*#__PURE__*/ _react.default.createElement( - "section", - { - className: "graphiql-editor-tool", - "aria-label": - activeSecondaryEditor === "variables" - ? "Variables" - : "Headers", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.VariableEditor, - { - editorTheme: props.editorTheme, - isHidden: activeSecondaryEditor !== "variables", - keyMap: props.keyMap, - onEdit: props.onEditVariables, - onClickReference: onClickReference, - readOnly: props.readOnly, - } - ), - isHeadersEditorEnabled && - /*#__PURE__*/ _react.default.createElement( - _react2.HeaderEditor, - { - editorTheme: props.editorTheme, - isHidden: activeSecondaryEditor !== "headers", - keyMap: props.keyMap, - onEdit: props.onEditHeaders, - readOnly: props.readOnly, - } - ) - ) - ) - ) - ), - /*#__PURE__*/ _react.default.createElement("div", { - className: "graphiql-horizontal-drag-bar", - ref: editorResize.dragBarRef, - }), - /*#__PURE__*/ _react.default.createElement( - "div", - { - ref: editorResize.secondRef, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-response", - }, - executionContext.isFetching - ? /*#__PURE__*/ _react.default.createElement( - _react2.Spinner, - null - ) - : null, - /*#__PURE__*/ _react.default.createElement( - _react2.ResponseEditor, - { - editorTheme: props.editorTheme, - responseTooltip: props.responseTooltip, - keyMap: props.keyMap, - } - ), - footer - ) - ) - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Dialog, - { - open: showDialog === "short-keys", - onOpenChange: handleOpenShortKeysDialog, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-header", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.Dialog.Title, - { - className: "graphiql-dialog-title", - }, - "Short Keys" - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Dialog.Close, - null - ) - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section", - }, - /*#__PURE__*/ _react.default.createElement(ShortKeys, { - keyMap: props.keyMap || "sublime", - }) - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Dialog, - { - open: showDialog === "settings", - onOpenChange: handleOpenSettingsDialog, - }, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-header", - }, - /*#__PURE__*/ _react.default.createElement( - _react2.Dialog.Title, - { - className: "graphiql-dialog-title", - }, - "Settings" - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Dialog.Close, - null - ) - ), - props.showPersistHeadersSettings - ? /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section", - }, - /*#__PURE__*/ _react.default.createElement( - "div", - null, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section-title", - }, - "Persist headers" - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section-caption", - }, - "Save headers upon reloading.", - " ", - /*#__PURE__*/ _react.default.createElement( - "span", - { - className: "graphiql-warning-text", - }, - "Only enable if you trust this device." - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.ButtonGroup, - null, - /*#__PURE__*/ _react.default.createElement( - _react2.Button, - { - type: "button", - id: "enable-persist-headers", - className: editorContext.shouldPersistHeaders - ? "active" - : "", - "data-value": "true", - onClick: handlePersistHeaders, - }, - "On" - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Button, - { - type: "button", - id: "disable-persist-headers", - className: editorContext.shouldPersistHeaders - ? "" - : "active", - onClick: handlePersistHeaders, - }, - "Off" - ) - ) - ) - : null, - !forcedTheme && - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section", - }, - /*#__PURE__*/ _react.default.createElement( - "div", - null, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section-title", - }, - "Theme" - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section-caption", - }, - "Adjust how the interface appears." - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.ButtonGroup, - null, - /*#__PURE__*/ _react.default.createElement( - _react2.Button, - { - type: "button", - className: theme === null ? "active" : "", - onClick: handleChangeTheme, - }, - "System" - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Button, - { - type: "button", - className: theme === "light" ? "active" : "", - "data-theme": "light", - onClick: handleChangeTheme, - }, - "Light" - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Button, - { - type: "button", - className: theme === "dark" ? "active" : "", - "data-theme": "dark", - onClick: handleChangeTheme, - }, - "Dark" - ) - ) - ), - storageContext - ? /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section", - }, - /*#__PURE__*/ _react.default.createElement( - "div", - null, - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section-title", - }, - "Clear storage" - ), - /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-dialog-section-caption", - }, - "Remove all locally stored data and start fresh." - ) - ), - /*#__PURE__*/ _react.default.createElement( - _react2.Button, - { - type: "button", - state: clearStorageStatus || undefined, - disabled: clearStorageStatus === "success", - onClick: handleClearData, - }, - { - success: "Cleared data", - error: "Failed", - }[clearStorageStatus] || "Clear data" - ) - ) - : null - ) - ) - ); + }, arg.name)) + }), ")"] + }) : null, ": ", /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: field.type + }), /* @__PURE__ */jsxRuntime.jsx(DefaultValue, { + field + })] + }), field.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + onlyShowFirstChild: true, + children: field.description + }) : null, /* @__PURE__ */jsxRuntime.jsx(DeprecationReason, { + children: field.deprecationReason + })] + }); + } + function EnumValues({ + type + }) { + const [showDeprecated, setShowDeprecated] = React.useState(false); + const handleShowDeprecated = React.useCallback(() => { + setShowDeprecated(true); + }, []); + if (!graphql.isEnumType(type)) { + return null; + } + const values = []; + const deprecatedValues = []; + for (const value of type.getValues()) { + if (value.deprecationReason) { + deprecatedValues.push(value); + } else { + values.push(value); + } + } + return /* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment, { + children: [values.length > 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Enum Values", + children: values.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { + value + }, value.name)) + }) : null, deprecatedValues.length > 0 ? showDeprecated || values.length === 0 ? /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: "Deprecated Enum Values", + children: deprecatedValues.map(value => /* @__PURE__ */jsxRuntime.jsx(EnumValue, { + value + }, value.name)) + }) : /* @__PURE__ */jsxRuntime.jsx(Button$1, { + type: "button", + onClick: handleShowDeprecated, + children: "Show Deprecated Values" + }) : null] + }); + } + function EnumValue({ + value + }) { + return /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-item", + children: [/* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-enum-value", + children: value.name + }), value.description ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "description", + children: value.description + }) : null, value.deprecationReason ? /* @__PURE__ */jsxRuntime.jsx(MarkdownContent, { + type: "deprecation", + children: value.deprecationReason + }) : null] + }); + } + function PossibleTypes({ + type + }) { + const { + schema + } = useSchemaContext({ + nonNull: true + }); + if (!schema || !graphql.isAbstractType(type)) { + return null; + } + return /* @__PURE__ */jsxRuntime.jsx(ExplorerSection, { + title: graphql.isInterfaceType(type) ? "Implementations" : "Possible Types", + children: schema.getPossibleTypes(type).map(possibleType => /* @__PURE__ */jsxRuntime.jsx("div", { + children: /* @__PURE__ */jsxRuntime.jsx(TypeLink, { + type: possibleType + }) + }, possibleType.name)) + }); + } + function DocExplorer() { + const { + fetchError, + isFetching, + schema, + validationErrors + } = useSchemaContext({ + nonNull: true, + caller: DocExplorer + }); + const { + explorerNavStack, + pop + } = useExplorerContext({ + nonNull: true, + caller: DocExplorer + }); + const navItem = explorerNavStack.at(-1); + let content = null; + if (fetchError) { + content = /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-error", + children: "Error fetching schema" + }); + } else if (validationErrors.length > 0) { + content = /* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-error", + children: ["Schema is invalid: ", validationErrors[0].message] + }); + } else if (isFetching) { + content = /* @__PURE__ */jsxRuntime.jsx(Spinner, {}); + } else if (!schema) { + content = /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-error", + children: "No GraphQL schema available" + }); + } else if (explorerNavStack.length === 1) { + content = /* @__PURE__ */jsxRuntime.jsx(SchemaDocumentation, { + schema + }); + } else if (graphql.isType(navItem.def)) { + content = /* @__PURE__ */jsxRuntime.jsx(TypeDocumentation, { + type: navItem.def + }); + } else if (navItem.def) { + content = /* @__PURE__ */jsxRuntime.jsx(FieldDocumentation, { + field: navItem.def + }); + } + let prevName; + if (explorerNavStack.length > 1) { + prevName = explorerNavStack.at(-2).name; + } + return /* @__PURE__ */jsxRuntime.jsxs("section", { + className: "graphiql-doc-explorer", + "aria-label": "Documentation Explorer", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-header", + children: [/* @__PURE__ */jsxRuntime.jsxs("div", { + className: "graphiql-doc-explorer-header-content", + children: [prevName && /* @__PURE__ */jsxRuntime.jsxs("a", { + href: "#", + className: "graphiql-doc-explorer-back", + onClick: event => { + event.preventDefault(); + pop(); + }, + "aria-label": `Go back to ${prevName}`, + children: [/* @__PURE__ */jsxRuntime.jsx(ChevronLeftIcon, {}), prevName] + }), /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-title", + children: navItem.name + })] + }), /* @__PURE__ */jsxRuntime.jsx(Search, {}, navItem.name)] + }), /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-doc-explorer-content", + children: content + })] + }); + } + const DOC_EXPLORER_PLUGIN = { + title: "Documentation Explorer", + icon: function Icon() { + const pluginContext = usePluginContext(); + return (pluginContext == null ? void 0 : pluginContext.visiblePlugin) === DOC_EXPLORER_PLUGIN ? /* @__PURE__ */jsxRuntime.jsx(DocsFilledIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(DocsIcon, {}); + }, + content: DocExplorer + }; + const HISTORY_PLUGIN = { + title: "History", + icon: HistoryIcon, + content: History + }; + const PluginContext = createNullableContext("PluginContext"); + function PluginContextProvider(props) { + const storage = useStorageContext(); + const explorerContext = useExplorerContext(); + const historyContext = useHistoryContext(); + const hasExplorerContext = Boolean(explorerContext); + const hasHistoryContext = Boolean(historyContext); + const plugins = React.useMemo(() => { + const pluginList = []; + const pluginTitles = {}; + if (hasExplorerContext) { + pluginList.push(DOC_EXPLORER_PLUGIN); + pluginTitles[DOC_EXPLORER_PLUGIN.title] = true; + } + if (hasHistoryContext) { + pluginList.push(HISTORY_PLUGIN); + pluginTitles[HISTORY_PLUGIN.title] = true; + } + for (const plugin of props.plugins || []) { + if (typeof plugin.title !== "string" || !plugin.title) { + throw new Error("All GraphiQL plugins must have a unique title"); } - const modifier = - typeof window !== "undefined" && - window.navigator.platform.toLowerCase().indexOf("mac") === 0 - ? "Cmd" - : "Ctrl"; - const SHORT_KEYS = Object.entries({ - "Search in editor": [modifier, "F"], - "Search in documentation": [modifier, "K"], - "Execute query": [modifier, "Enter"], - "Prettify editors": ["Ctrl", "Shift", "P"], - "Merge fragments definitions into operation definition": [ - "Ctrl", - "Shift", - "M", - ], - "Copy query": ["Ctrl", "Shift", "C"], - "Re-fetch schema using introspection": ["Ctrl", "Shift", "R"], - }); - function ShortKeys({ keyMap }) { - return /*#__PURE__*/ _react.default.createElement( - "div", - null, - /*#__PURE__*/ _react.default.createElement( - "table", - { - className: "graphiql-table", - }, - /*#__PURE__*/ _react.default.createElement( - "thead", - null, - /*#__PURE__*/ _react.default.createElement( - "tr", - null, - /*#__PURE__*/ _react.default.createElement( - "th", - null, - "Short Key" - ), - /*#__PURE__*/ _react.default.createElement( - "th", - null, - "Function" - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - "tbody", - null, - SHORT_KEYS.map(([title, keys]) => - /*#__PURE__*/ _react.default.createElement( - "tr", - { - key: title, - }, - /*#__PURE__*/ _react.default.createElement( - "td", - null, - keys.map((key, index, array) => - /*#__PURE__*/ _react.default.createElement( - _react.Fragment, - { - key: key, - }, - /*#__PURE__*/ _react.default.createElement( - "code", - { - className: "graphiql-key", - }, - key - ), - index !== array.length - 1 && " + " - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - "td", - null, - title - ) - ) - ) - ) - ), - /*#__PURE__*/ _react.default.createElement( - "p", - null, - "The editors use", - " ", - /*#__PURE__*/ _react.default.createElement( - "a", - { - href: "https://codemirror.net/5/doc/manual.html#keymaps", - target: "_blank", - rel: "noopener noreferrer", - }, - "CodeMirror Key Maps" - ), - " ", - "that add more short keys. This instance of Graph", - /*#__PURE__*/ _react.default.createElement("em", null, "i"), - "QL uses", - " ", - /*#__PURE__*/ _react.default.createElement("code", null, keyMap), - "." - ) - ); + if (pluginTitles[plugin.title]) { + throw new Error(`All GraphiQL plugins must have a unique title, found two plugins with the title '${plugin.title}'`); + } else { + pluginList.push(plugin); + pluginTitles[plugin.title] = true; } - - // Configure the UI by providing this Component as a child of GraphiQL. - function GraphiQLLogo(props) { - return /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-logo", - }, - props.children || - /*#__PURE__*/ _react.default.createElement( - "a", - { - className: "graphiql-logo-link", - href: "https://github.com/graphql/graphiql", - target: "_blank", - rel: "noreferrer", - }, - "Graph", - /*#__PURE__*/ _react.default.createElement("em", null, "i"), - "QL" - ) - ); + } + return pluginList; + }, [hasExplorerContext, hasHistoryContext, props.plugins]); + const [visiblePlugin, internalSetVisiblePlugin] = React.useState(() => { + const storedValue = storage == null ? void 0 : storage.get(STORAGE_KEY$4); + const pluginForStoredValue = plugins.find(plugin => plugin.title === storedValue); + if (pluginForStoredValue) { + return pluginForStoredValue; + } + if (storedValue) { + storage == null ? void 0 : storage.set(STORAGE_KEY$4, ""); + } + if (!props.visiblePlugin) { + return null; + } + return plugins.find(plugin => (typeof props.visiblePlugin === "string" ? plugin.title : plugin) === props.visiblePlugin) || null; + }); + const { + onTogglePluginVisibility, + children + } = props; + const setVisiblePlugin = React.useCallback(plugin => { + const newVisiblePlugin = plugin ? plugins.find(p => (typeof plugin === "string" ? p.title : p) === plugin) || null : null; + internalSetVisiblePlugin(current => { + if (newVisiblePlugin === current) { + return current; } - GraphiQLLogo.displayName = "GraphiQLLogo"; - - // Configure the UI by providing this Component as a child of GraphiQL. - function GraphiQLToolbar(props) { - // eslint-disable-next-line react/jsx-no-useless-fragment - return /*#__PURE__*/ _react.default.createElement( - _react.default.Fragment, - null, - props.children - ); + onTogglePluginVisibility == null ? void 0 : onTogglePluginVisibility(newVisiblePlugin); + return newVisiblePlugin; + }); + }, [onTogglePluginVisibility, plugins]); + React.useEffect(() => { + if (props.visiblePlugin) { + setVisiblePlugin(props.visiblePlugin); + } + }, [plugins, props.visiblePlugin, setVisiblePlugin]); + const value = React.useMemo(() => ({ + plugins, + setVisiblePlugin, + visiblePlugin + }), [plugins, setVisiblePlugin, visiblePlugin]); + return /* @__PURE__ */jsxRuntime.jsx(PluginContext.Provider, { + value, + children + }); + } + const usePluginContext = createContextHook(PluginContext); + const STORAGE_KEY$4 = "visiblePlugin"; + function onHasCompletion(_cm, data, schema, explorer, plugin, callback) { + void importCodeMirror([], { + useCommonAddons: false + }).then(CodeMirror => { + let information; + let fieldName; + let typeNamePill; + let typeNamePrefix; + let typeName; + let typeNameSuffix; + let description; + let deprecation; + let deprecationReason; + CodeMirror.on(data, "select", + // @ts-expect-error + (ctx, el) => { + if (!information) { + const hintsUl = el.parentNode; + information = document.createElement("div"); + information.className = "CodeMirror-hint-information"; + hintsUl.append(information); + const header = document.createElement("header"); + header.className = "CodeMirror-hint-information-header"; + information.append(header); + fieldName = document.createElement("span"); + fieldName.className = "CodeMirror-hint-information-field-name"; + header.append(fieldName); + typeNamePill = document.createElement("span"); + typeNamePill.className = "CodeMirror-hint-information-type-name-pill"; + header.append(typeNamePill); + typeNamePrefix = document.createElement("span"); + typeNamePill.append(typeNamePrefix); + typeName = document.createElement("a"); + typeName.className = "CodeMirror-hint-information-type-name"; + typeName.href = "javascript:void 0"; + typeName.addEventListener("click", onClickHintInformation); + typeNamePill.append(typeName); + typeNameSuffix = document.createElement("span"); + typeNamePill.append(typeNameSuffix); + description = document.createElement("div"); + description.className = "CodeMirror-hint-information-description"; + information.append(description); + deprecation = document.createElement("div"); + deprecation.className = "CodeMirror-hint-information-deprecation"; + information.append(deprecation); + const deprecationLabel = document.createElement("span"); + deprecationLabel.className = "CodeMirror-hint-information-deprecation-label"; + deprecationLabel.textContent = "Deprecated"; + deprecation.append(deprecationLabel); + deprecationReason = document.createElement("div"); + deprecationReason.className = "CodeMirror-hint-information-deprecation-reason"; + deprecation.append(deprecationReason); + const defaultInformationPadding = parseInt(window.getComputedStyle(information).paddingBottom.replace(/px$/, ""), 10) || 0; + const defaultInformationMaxHeight = parseInt(window.getComputedStyle(information).maxHeight.replace(/px$/, ""), 10) || 0; + const handleScroll = () => { + if (information) { + information.style.paddingTop = hintsUl.scrollTop + defaultInformationPadding + "px"; + information.style.maxHeight = hintsUl.scrollTop + defaultInformationMaxHeight + "px"; + } + }; + hintsUl.addEventListener("scroll", handleScroll); + let onRemoveFn; + hintsUl.addEventListener("DOMNodeRemoved", onRemoveFn = event => { + if (event.target !== hintsUl) { + return; + } + hintsUl.removeEventListener("scroll", handleScroll); + hintsUl.removeEventListener("DOMNodeRemoved", onRemoveFn); + if (information) { + information.removeEventListener("click", onClickHintInformation); + } + information = null; + fieldName = null; + typeNamePill = null; + typeNamePrefix = null; + typeName = null; + typeNameSuffix = null; + description = null; + deprecation = null; + deprecationReason = null; + onRemoveFn = null; + }); + } + if (fieldName) { + fieldName.textContent = ctx.text; + } + if (typeNamePill && typeNamePrefix && typeName && typeNameSuffix) { + if (ctx.type) { + typeNamePill.style.display = "inline"; + const renderType2 = type => { + if (graphql.isNonNullType(type)) { + typeNameSuffix.textContent = "!" + typeNameSuffix.textContent; + renderType2(type.ofType); + } else if (graphql.isListType(type)) { + typeNamePrefix.textContent += "["; + typeNameSuffix.textContent = "]" + typeNameSuffix.textContent; + renderType2(type.ofType); + } else { + typeName.textContent = type.name; + } + }; + typeNamePrefix.textContent = ""; + typeNameSuffix.textContent = ""; + renderType2(ctx.type); + } else { + typeNamePrefix.textContent = ""; + typeName.textContent = ""; + typeNameSuffix.textContent = ""; + typeNamePill.style.display = "none"; + } } - GraphiQLToolbar.displayName = "GraphiQLToolbar"; - - // Configure the UI by providing this Component as a child of GraphiQL. - function GraphiQLFooter(props) { - return /*#__PURE__*/ _react.default.createElement( - "div", - { - className: "graphiql-footer", - }, - props.children - ); + if (description) { + if (ctx.description) { + description.style.display = "block"; + description.innerHTML = markdown.render(ctx.description); + } else { + description.style.display = "none"; + description.innerHTML = ""; + } } - GraphiQLFooter.displayName = "GraphiQLFooter"; - - // Determines if the React child is of the same type of the provided React component - function isChildComponentType(child, component) { - var _child$type; - if ( - child !== null && - child !== void 0 && - (_child$type = child.type) !== null && - _child$type !== void 0 && - _child$type.displayName && - child.type.displayName === component.displayName - ) { - return true; + if (deprecation && deprecationReason) { + if (ctx.deprecationReason) { + deprecation.style.display = "block"; + deprecationReason.innerHTML = markdown.render(ctx.deprecationReason); + } else { + deprecation.style.display = "none"; + deprecationReason.innerHTML = ""; } - return child.type === component; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/index.js": - /*!***************************************************!*\ - !*** ../../graphql-language-service/esm/index.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - Object.defineProperty(exports, "CharacterStream", { - enumerable: true, - get: function () { - return _parser.CharacterStream; - }, - }); - Object.defineProperty(exports, "CompletionItemKind", { - enumerable: true, - get: function () { - return _types.CompletionItemKind; - }, - }); - Object.defineProperty(exports, "DIAGNOSTIC_SEVERITY", { - enumerable: true, - get: function () { - return _interface.DIAGNOSTIC_SEVERITY; - }, - }); - Object.defineProperty(exports, "FileChangeTypeKind", { - enumerable: true, - get: function () { - return _types.FileChangeTypeKind; - }, - }); - Object.defineProperty(exports, "GraphQLDocumentMode", { - enumerable: true, - get: function () { - return _parser.GraphQLDocumentMode; - }, - }); - Object.defineProperty(exports, "LexRules", { - enumerable: true, - get: function () { - return _parser.LexRules; - }, - }); - Object.defineProperty(exports, "ParseRules", { - enumerable: true, - get: function () { - return _parser.ParseRules; - }, - }); - Object.defineProperty(exports, "Position", { - enumerable: true, - get: function () { - return _utils.Position; - }, - }); - Object.defineProperty(exports, "Range", { - enumerable: true, - get: function () { - return _utils.Range; - }, - }); - Object.defineProperty(exports, "RuleKinds", { - enumerable: true, - get: function () { - return _parser.RuleKinds; - }, - }); - Object.defineProperty(exports, "SEVERITY", { - enumerable: true, - get: function () { - return _interface.SEVERITY; - }, - }); - Object.defineProperty(exports, "SuggestionCommand", { - enumerable: true, - get: function () { - return _interface.SuggestionCommand; - }, - }); - Object.defineProperty(exports, "canUseDirective", { - enumerable: true, - get: function () { - return _interface.canUseDirective; - }, - }); - Object.defineProperty(exports, "collectVariables", { - enumerable: true, - get: function () { - return _utils.collectVariables; - }, - }); - Object.defineProperty(exports, "getASTNodeAtPosition", { - enumerable: true, - get: function () { - return _utils.getASTNodeAtPosition; - }, - }); - Object.defineProperty(exports, "getAutocompleteSuggestions", { - enumerable: true, - get: function () { - return _interface.getAutocompleteSuggestions; - }, + }); + }); + function onClickHintInformation(event) { + if (!schema || !explorer || !plugin || !(event.currentTarget instanceof HTMLElement)) { + return; + } + const typeName = event.currentTarget.textContent || ""; + const type = schema.getType(typeName); + if (type) { + plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); + explorer.push({ + name: type.name, + def: type + }); + callback == null ? void 0 : callback(type); + } + } + } + function useSynchronizeValue(editor, value) { + React.useEffect(() => { + if (editor && typeof value === "string" && value !== editor.getValue()) { + editor.setValue(value); + } + }, [editor, value]); + } + function useSynchronizeOption(editor, option, value) { + React.useEffect(() => { + if (editor) { + editor.setOption(option, value); + } + }, [editor, option, value]); + } + function useChangeHandler(editor, callback, storageKey, tabProperty, caller) { + const { + updateActiveTabValues + } = useEditorContext({ + nonNull: true, + caller + }); + const storage = useStorageContext(); + React.useEffect(() => { + if (!editor) { + return; + } + const store = debounce(500, value => { + if (!storage || storageKey === null) { + return; + } + storage.set(storageKey, value); + }); + const updateTab = debounce(100, value => { + updateActiveTabValues({ + [tabProperty]: value }); - Object.defineProperty(exports, "getDefinitionQueryResultForArgument", { - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForArgument; - }, + }); + const handleChange = (editorInstance, changeObj) => { + if (!changeObj) { + return; + } + const newValue = editorInstance.getValue(); + store(newValue); + updateTab(newValue); + callback == null ? void 0 : callback(newValue); + }; + editor.on("change", handleChange); + return () => editor.off("change", handleChange); + }, [callback, editor, storage, storageKey, tabProperty, updateActiveTabValues]); + } + function useCompletion(editor, callback, caller) { + const { + schema + } = useSchemaContext({ + nonNull: true, + caller + }); + const explorer = useExplorerContext(); + const plugin = usePluginContext(); + React.useEffect(() => { + if (!editor) { + return; + } + const handleCompletion = (instance, changeObj) => { + onHasCompletion(instance, changeObj, schema, explorer, plugin, type => { + callback == null ? void 0 : callback({ + kind: "Type", + type, + schema: schema || void 0 + }); }); - Object.defineProperty( - exports, - "getDefinitionQueryResultForDefinitionNode", - { - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForDefinitionNode; - }, + }; + editor.on( + // @ts-expect-error @TODO additional args for hasCompletion event + "hasCompletion", handleCompletion); + return () => editor.off( + // @ts-expect-error @TODO additional args for hasCompletion event + "hasCompletion", handleCompletion); + }, [callback, editor, explorer, plugin, schema]); + } + function useKeyMap(editor, keys, callback) { + React.useEffect(() => { + if (!editor) { + return; + } + for (const key of keys) { + editor.removeKeyMap(key); + } + if (callback) { + const keyMap = {}; + for (const key of keys) { + keyMap[key] = () => callback(); + } + editor.addKeyMap(keyMap); + } + }, [editor, keys, callback]); + } + function useCopyQuery({ + caller, + onCopyQuery + } = {}) { + const { + queryEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useCopyQuery + }); + return React.useCallback(() => { + if (!queryEditor) { + return; + } + const query = queryEditor.getValue(); + copyToClipboard(query); + onCopyQuery == null ? void 0 : onCopyQuery(query); + }, [queryEditor, onCopyQuery]); + } + function useMergeQuery({ + caller + } = {}) { + const { + queryEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useMergeQuery + }); + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: useMergeQuery + }); + return React.useCallback(() => { + const documentAST = queryEditor == null ? void 0 : queryEditor.documentAST; + const query = queryEditor == null ? void 0 : queryEditor.getValue(); + if (!documentAST || !query) { + return; + } + queryEditor.setValue(graphql.print(toolkit.mergeAst(documentAST, schema))); + }, [queryEditor, schema]); + } + function usePrettifyEditors({ + caller + } = {}) { + const { + queryEditor, + headerEditor, + variableEditor + } = useEditorContext({ + nonNull: true, + caller: caller || usePrettifyEditors + }); + return React.useCallback(() => { + if (variableEditor) { + const variableEditorContent = variableEditor.getValue(); + try { + const prettifiedVariableEditorContent = JSON.stringify(JSON.parse(variableEditorContent), null, 2); + if (prettifiedVariableEditorContent !== variableEditorContent) { + variableEditor.setValue(prettifiedVariableEditorContent); } - ); - Object.defineProperty(exports, "getDefinitionQueryResultForField", { - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForField; - }, - }); - Object.defineProperty( - exports, - "getDefinitionQueryResultForFragmentSpread", - { - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForFragmentSpread; - }, + } catch {} + } + if (headerEditor) { + const headerEditorContent = headerEditor.getValue(); + try { + const prettifiedHeaderEditorContent = JSON.stringify(JSON.parse(headerEditorContent), null, 2); + if (prettifiedHeaderEditorContent !== headerEditorContent) { + headerEditor.setValue(prettifiedHeaderEditorContent); } - ); - Object.defineProperty(exports, "getDefinitionQueryResultForNamedType", { - enumerable: true, - get: function () { - return _interface.getDefinitionQueryResultForNamedType; - }, - }); - Object.defineProperty(exports, "getDefinitionState", { - enumerable: true, - get: function () { - return _parser.getDefinitionState; - }, - }); - Object.defineProperty(exports, "getDiagnostics", { - enumerable: true, - get: function () { - return _interface.getDiagnostics; - }, - }); - Object.defineProperty(exports, "getFieldDef", { - enumerable: true, - get: function () { - return _parser.getFieldDef; - }, - }); - Object.defineProperty(exports, "getFragmentDefinitions", { - enumerable: true, - get: function () { - return _interface.getFragmentDefinitions; - }, - }); - Object.defineProperty(exports, "getFragmentDependencies", { - enumerable: true, - get: function () { - return _utils.getFragmentDependencies; - }, + } catch {} + } + if (queryEditor) { + const editorContent = queryEditor.getValue(); + const prettifiedEditorContent = graphql.print(graphql.parse(editorContent)); + if (prettifiedEditorContent !== editorContent) { + queryEditor.setValue(prettifiedEditorContent); + } + } + }, [queryEditor, variableEditor, headerEditor]); + } + function useAutoCompleteLeafs({ + getDefaultFieldNames, + caller + } = {}) { + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: caller || useAutoCompleteLeafs + }); + const { + queryEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useAutoCompleteLeafs + }); + return React.useCallback(() => { + if (!queryEditor) { + return; + } + const query = queryEditor.getValue(); + const { + insertions, + result + } = toolkit.fillLeafs(schema, query, getDefaultFieldNames); + if (insertions && insertions.length > 0) { + queryEditor.operation(() => { + const cursor = queryEditor.getCursor(); + const cursorIndex = queryEditor.indexFromPos(cursor); + queryEditor.setValue(result || ""); + let added = 0; + const markers = insertions.map(({ + index, + string + }) => queryEditor.markText(queryEditor.posFromIndex(index + added), queryEditor.posFromIndex(index + (added += string.length)), { + className: "auto-inserted-leaf", + clearOnEnter: true, + title: "Automatically added leaf fields" + })); + setTimeout(() => { + for (const marker of markers) { + marker.clear(); + } + }, 7e3); + let newCursorIndex = cursorIndex; + for (const { + index, + string + } of insertions) { + if (index < cursorIndex) { + newCursorIndex += string.length; + } + } + queryEditor.setCursor(queryEditor.posFromIndex(newCursorIndex)); }); - Object.defineProperty(exports, "getFragmentDependenciesForAST", { - enumerable: true, - get: function () { - return _utils.getFragmentDependenciesForAST; + } + return result; + }, [getDefaultFieldNames, queryEditor, schema]); + } + const useEditorState = editor => { + var _ref2; + const context = useEditorContext({ + nonNull: true + }); + const editorInstance = context[`${editor}Editor`]; + let valueString = ""; + const editorValue = (_ref2 = editorInstance == null ? void 0 : editorInstance.getValue()) !== null && _ref2 !== void 0 ? _ref2 : false; + if (editorValue && editorValue.length > 0) { + valueString = editorValue; + } + const handleEditorValue = React.useCallback(value => editorInstance == null ? void 0 : editorInstance.setValue(value), [editorInstance]); + return React.useMemo(() => [valueString, handleEditorValue], [valueString, handleEditorValue]); + }; + const useOperationsEditorState = () => { + return useEditorState("query"); + }; + const useVariablesEditorState = () => { + return useEditorState("variable"); + }; + const useHeadersEditorState = () => { + return useEditorState("header"); + }; + function useOptimisticState([upstreamState, upstreamSetState]) { + const lastStateRef = React.useRef({ + /** The last thing that we sent upstream; we're expecting this back */ + pending: null, + /** The last thing we received from upstream */ + last: upstreamState + }); + const [state, setOperationsText] = React.useState(upstreamState); + React.useEffect(() => { + if (lastStateRef.current.last === upstreamState) ;else { + lastStateRef.current.last = upstreamState; + if (lastStateRef.current.pending === null) { + setOperationsText(upstreamState); + } else if (lastStateRef.current.pending === upstreamState) { + lastStateRef.current.pending = null; + if (upstreamState !== state) { + lastStateRef.current.pending = state; + upstreamSetState(state); + } + } else { + lastStateRef.current.pending = null; + setOperationsText(upstreamState); + } + } + }, [upstreamState, state, upstreamSetState]); + const setState = React.useCallback(newState => { + setOperationsText(newState); + if (lastStateRef.current.pending === null && lastStateRef.current.last !== newState) { + lastStateRef.current.pending = newState; + upstreamSetState(newState); + } + }, [upstreamSetState]); + return React.useMemo(() => [state, setState], [state, setState]); + } + function useHeaderEditor({ + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onEdit, + readOnly = false + } = {}, caller) { + const { + initialHeaders, + headerEditor, + setHeaderEditor, + shouldPersistHeaders + } = useEditorContext({ + nonNull: true, + caller: caller || useHeaderEditor + }); + const executionContext = useExecutionContext(); + const merge = useMergeQuery({ + caller: caller || useHeaderEditor + }); + const prettify = usePrettifyEditors({ + caller: caller || useHeaderEditor + }); + const ref = React.useRef(null); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([ + // @ts-expect-error + Promise.resolve().then(() => __webpack_require__(/*! ./javascript.cjs.js */ "../../graphiql-react/dist/javascript.cjs.js")).then(n => n.javascript)]).then(CodeMirror => { + if (!isActive) { + return; + } + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialHeaders, + lineNumbers: true, + tabSize: 2, + mode: { + name: "javascript", + json: true + }, + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: commonKeys + }); + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); }, - }); - Object.defineProperty(exports, "getHoverInformation", { - enumerable: true, - get: function () { - return _interface.getHoverInformation; + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); }, - }); - Object.defineProperty(exports, "getOperationASTFacts", { - enumerable: true, - get: function () { - return _utils.getOperationASTFacts; + "Alt-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); }, + "Shift-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); + } }); - Object.defineProperty(exports, "getOperationFacts", { - enumerable: true, - get: function () { - return _utils.getOperationFacts; + newEditor.on("keyup", (editorInstance, event) => { + const { + code, + key, + shiftKey + } = event; + const isLetter = code.startsWith("Key"); + const isNumber = !shiftKey && code.startsWith("Digit"); + if (isLetter || isNumber || key === "_" || key === '"') { + editorInstance.execCommand("autocomplete"); + } + }); + setHeaderEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialHeaders, readOnly, setHeaderEditor]); + useSynchronizeOption(headerEditor, "keyMap", keyMap); + useChangeHandler(headerEditor, onEdit, shouldPersistHeaders ? STORAGE_KEY$3 : null, "headers", useHeaderEditor); + useKeyMap(headerEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); + useKeyMap(headerEditor, ["Shift-Ctrl-P"], prettify); + useKeyMap(headerEditor, ["Shift-Ctrl-M"], merge); + return ref; + } + const STORAGE_KEY$3 = "headers"; + const invalidCharacters = Array.from({ + length: 11 + }, (_, i) => { + return String.fromCharCode(8192 + i); + }).concat(["\u2028", "\u2029", " ", " "]); + const sanitizeRegex = new RegExp("[" + invalidCharacters.join("") + "]", "g"); + function normalizeWhitespace(line) { + return line.replace(sanitizeRegex, " "); + } + function useQueryEditor({ + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onClickReference, + onCopyQuery, + onEdit, + readOnly = false + } = {}, caller) { + const { + schema + } = useSchemaContext({ + nonNull: true, + caller: caller || useQueryEditor + }); + const { + externalFragments, + initialQuery, + queryEditor, + setOperationName, + setQueryEditor, + validationRules, + variableEditor, + updateActiveTabValues + } = useEditorContext({ + nonNull: true, + caller: caller || useQueryEditor + }); + const executionContext = useExecutionContext(); + const storage = useStorageContext(); + const explorer = useExplorerContext(); + const plugin = usePluginContext(); + const copy = useCopyQuery({ + caller: caller || useQueryEditor, + onCopyQuery + }); + const merge = useMergeQuery({ + caller: caller || useQueryEditor + }); + const prettify = usePrettifyEditors({ + caller: caller || useQueryEditor + }); + const ref = React.useRef(null); + const codeMirrorRef = React.useRef(); + const onClickReferenceRef = React.useRef(() => {}); + React.useEffect(() => { + onClickReferenceRef.current = reference => { + if (!explorer || !plugin) { + return; + } + plugin.setVisiblePlugin(DOC_EXPLORER_PLUGIN); + switch (reference.kind) { + case "Type": + { + explorer.push({ + name: reference.type.name, + def: reference.type + }); + break; + } + case "Field": + { + explorer.push({ + name: reference.field.name, + def: reference.field + }); + break; + } + case "Argument": + { + if (reference.field) { + explorer.push({ + name: reference.field.name, + def: reference.field + }); + } + break; + } + case "EnumValue": + { + if (reference.type) { + explorer.push({ + name: reference.type.name, + def: reference.type + }); + } + break; + } + } + onClickReference == null ? void 0 : onClickReference(reference); + }; + }, [explorer, onClickReference, plugin]); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./comment.cjs.js */ "../../graphiql-react/dist/comment.cjs.js")).then(n => n.comment), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs.js */ "../../graphiql-react/dist/hint.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs2.js */ "../../graphiql-react/dist/lint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info.cjs.js */ "../../graphiql-react/dist/info.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./jump.cjs.js */ "../../graphiql-react/dist/jump.cjs.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs.js */ "../../graphiql-react/dist/mode.cjs.js"))]).then(CodeMirror => { + if (!isActive) { + return; + } + codeMirrorRef.current = CodeMirror; + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialQuery, + lineNumbers: true, + tabSize: 2, + foldGutter: true, + mode: "graphql", + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + lint: { + // @ts-expect-error + schema: void 0, + validationRules: null, + // linting accepts string or FragmentDefinitionNode[] + externalFragments: void 0 }, - }); - Object.defineProperty(exports, "getOutline", { - enumerable: true, - get: function () { - return _interface.getOutline; + hintOptions: { + // @ts-expect-error + schema: void 0, + closeOnUnfocus: false, + completeSingle: false, + container, + externalFragments: void 0, + autocompleteOptions: { + // for the query editor, restrict to executable type definitions + mode: graphqlLanguageService.GraphQLDocumentMode.EXECUTABLE + } }, - }); - Object.defineProperty(exports, "getQueryFacts", { - enumerable: true, - get: function () { - return _utils.getQueryFacts; + info: { + schema: void 0, + renderDescription: text => markdown.render(text), + onClick(reference) { + onClickReferenceRef.current(reference); + } }, - }); - Object.defineProperty(exports, "getRange", { - enumerable: true, - get: function () { - return _interface.getRange; + jump: { + schema: void 0, + onClick(reference) { + onClickReferenceRef.current(reference); + } }, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: { + ...commonKeys, + "Cmd-S"() {}, + "Ctrl-S"() {} + } }); - Object.defineProperty(exports, "getTokenAtPosition", { - enumerable: true, - get: function () { - return _parser.getTokenAtPosition; + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); }, - }); - Object.defineProperty(exports, "getTypeInfo", { - enumerable: true, - get: function () { - return _interface.getTypeInfo; + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); }, - }); - Object.defineProperty(exports, "getVariableCompletions", { - enumerable: true, - get: function () { - return _interface.getVariableCompletions; + "Alt-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); }, - }); - Object.defineProperty(exports, "getVariablesJSONSchema", { - enumerable: true, - get: function () { - return _utils.getVariablesJSONSchema; + "Shift-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); }, + "Shift-Alt-Space"() { + newEditor.showHint({ + completeSingle: true, + container + }); + } }); - Object.defineProperty(exports, "isIgnored", { - enumerable: true, - get: function () { - return _parser.isIgnored; - }, + newEditor.on("keyup", (editorInstance, event) => { + if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { + editorInstance.execCommand("autocomplete"); + } }); - Object.defineProperty(exports, "list", { - enumerable: true, - get: function () { - return _parser.list; - }, + let showingHints = false; + newEditor.on("startCompletion", () => { + showingHints = true; }); - Object.defineProperty(exports, "offsetToPosition", { - enumerable: true, - get: function () { - return _utils.offsetToPosition; - }, + newEditor.on("endCompletion", () => { + showingHints = false; }); - Object.defineProperty(exports, "onlineParser", { - enumerable: true, - get: function () { - return _parser.onlineParser; - }, + newEditor.on("keydown", (editorInstance, event) => { + if (event.key === "Escape" && showingHints) { + event.stopPropagation(); + } }); - Object.defineProperty(exports, "opt", { - enumerable: true, - get: function () { - return _parser.opt; - }, + newEditor.on("beforeChange", (editorInstance, change) => { + var _a; + if (change.origin === "paste") { + const text = change.text.map(normalizeWhitespace); + (_a = change.update) == null ? void 0 : _a.call(change, change.from, change.to, text); + } + }); + newEditor.documentAST = null; + newEditor.operationName = null; + newEditor.operations = null; + newEditor.variableToType = null; + setQueryEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialQuery, readOnly, setQueryEditor]); + useSynchronizeOption(queryEditor, "keyMap", keyMap); + React.useEffect(() => { + if (!queryEditor) { + return; + } + function getAndUpdateOperationFacts(editorInstance) { + var _editorInstance$opera, _editorInstance$opera2, _ref3, _ref4; + var _a; + const operationFacts = graphqlLanguageService.getOperationFacts(schema, editorInstance.getValue()); + const operationName = toolkit.getSelectedOperationName((_editorInstance$opera = editorInstance.operations) !== null && _editorInstance$opera !== void 0 ? _editorInstance$opera : void 0, (_editorInstance$opera2 = editorInstance.operationName) !== null && _editorInstance$opera2 !== void 0 ? _editorInstance$opera2 : void 0, operationFacts == null ? void 0 : operationFacts.operations); + editorInstance.documentAST = (_ref3 = operationFacts == null ? void 0 : operationFacts.documentAST) !== null && _ref3 !== void 0 ? _ref3 : null; + editorInstance.operationName = operationName !== null && operationName !== void 0 ? operationName : null; + editorInstance.operations = (_ref4 = operationFacts == null ? void 0 : operationFacts.operations) !== null && _ref4 !== void 0 ? _ref4 : null; + if (variableEditor) { + variableEditor.state.lint.linterOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; + variableEditor.options.lint.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; + variableEditor.options.hintOptions.variableToType = operationFacts == null ? void 0 : operationFacts.variableToType; + (_a = codeMirrorRef.current) == null ? void 0 : _a.signal(variableEditor, "change", variableEditor); + } + return operationFacts ? { + ...operationFacts, + operationName + } : null; + } + const handleChange = debounce(100, editorInstance => { + var _ref5; + const query = editorInstance.getValue(); + storage == null ? void 0 : storage.set(STORAGE_KEY_QUERY, query); + const currentOperationName = editorInstance.operationName; + const operationFacts = getAndUpdateOperationFacts(editorInstance); + if ((operationFacts == null ? void 0 : operationFacts.operationName) !== void 0) { + storage == null ? void 0 : storage.set(STORAGE_KEY_OPERATION_NAME, operationFacts.operationName); + } + onEdit == null ? void 0 : onEdit(query, operationFacts == null ? void 0 : operationFacts.documentAST); + if ((operationFacts == null ? void 0 : operationFacts.operationName) && currentOperationName !== operationFacts.operationName) { + setOperationName(operationFacts.operationName); + } + updateActiveTabValues({ + query, + operationName: (_ref5 = operationFacts == null ? void 0 : operationFacts.operationName) !== null && _ref5 !== void 0 ? _ref5 : null + }); + }); + getAndUpdateOperationFacts(queryEditor); + queryEditor.on("change", handleChange); + return () => queryEditor.off("change", handleChange); + }, [onEdit, queryEditor, schema, setOperationName, storage, variableEditor, updateActiveTabValues]); + useSynchronizeSchema(queryEditor, schema !== null && schema !== void 0 ? schema : null, codeMirrorRef); + useSynchronizeValidationRules(queryEditor, validationRules !== null && validationRules !== void 0 ? validationRules : null, codeMirrorRef); + useSynchronizeExternalFragments(queryEditor, externalFragments, codeMirrorRef); + useCompletion(queryEditor, onClickReference || null, useQueryEditor); + const run = executionContext == null ? void 0 : executionContext.run; + const runAtCursor = React.useCallback(() => { + var _a; + if (!run || !queryEditor || !queryEditor.operations || !queryEditor.hasFocus()) { + run == null ? void 0 : run(); + return; + } + const cursorIndex = queryEditor.indexFromPos(queryEditor.getCursor()); + let operationName; + for (const operation of queryEditor.operations) { + if (operation.loc && operation.loc.start <= cursorIndex && operation.loc.end >= cursorIndex) { + operationName = (_a = operation.name) == null ? void 0 : _a.value; + } + } + if (operationName && operationName !== queryEditor.operationName) { + setOperationName(operationName); + } + run(); + }, [queryEditor, run, setOperationName]); + useKeyMap(queryEditor, ["Cmd-Enter", "Ctrl-Enter"], runAtCursor); + useKeyMap(queryEditor, ["Shift-Ctrl-C"], copy); + useKeyMap(queryEditor, ["Shift-Ctrl-P", + // Shift-Ctrl-P is hard coded in Firefox for private browsing so adding an alternative to prettify + "Shift-Ctrl-F"], prettify); + useKeyMap(queryEditor, ["Shift-Ctrl-M"], merge); + return ref; + } + function useSynchronizeSchema(editor, schema, codeMirrorRef) { + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = editor.options.lint.schema !== schema; + editor.state.lint.linterOptions.schema = schema; + editor.options.lint.schema = schema; + editor.options.hintOptions.schema = schema; + editor.options.info.schema = schema; + editor.options.jump.schema = schema; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, schema, codeMirrorRef]); + } + function useSynchronizeValidationRules(editor, validationRules, codeMirrorRef) { + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = editor.options.lint.validationRules !== validationRules; + editor.state.lint.linterOptions.validationRules = validationRules; + editor.options.lint.validationRules = validationRules; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, validationRules, codeMirrorRef]); + } + function useSynchronizeExternalFragments(editor, externalFragments, codeMirrorRef) { + const externalFragmentList = React.useMemo(() => [...externalFragments.values()], [externalFragments]); + React.useEffect(() => { + if (!editor) { + return; + } + const didChange = editor.options.lint.externalFragments !== externalFragmentList; + editor.state.lint.linterOptions.externalFragments = externalFragmentList; + editor.options.lint.externalFragments = externalFragmentList; + editor.options.hintOptions.externalFragments = externalFragmentList; + if (didChange && codeMirrorRef.current) { + codeMirrorRef.current.signal(editor, "change", editor); + } + }, [editor, externalFragmentList, codeMirrorRef]); + } + const AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/; + const STORAGE_KEY_QUERY = "query"; + const STORAGE_KEY_OPERATION_NAME = "operationName"; + function getDefaultTabState({ + defaultQuery, + defaultHeaders, + headers, + defaultTabs, + query, + variables, + storage, + shouldPersistHeaders + }) { + const storedState = storage == null ? void 0 : storage.get(STORAGE_KEY$2); + try { + if (!storedState) { + throw new Error("Storage for tabs is empty"); + } + const parsed = JSON.parse(storedState); + const headersForHash = shouldPersistHeaders ? headers : void 0; + if (isTabsState(parsed)) { + const expectedHash = hashFromTabContents({ + query, + variables, + headers: headersForHash }); - Object.defineProperty(exports, "p", { - enumerable: true, - get: function () { - return _parser.p; + let matchingTabIndex = -1; + for (let index = 0; index < parsed.tabs.length; index++) { + const tab = parsed.tabs[index]; + tab.hash = hashFromTabContents({ + query: tab.query, + variables: tab.variables, + headers: tab.headers + }); + if (tab.hash === expectedHash) { + matchingTabIndex = index; + } + } + if (matchingTabIndex >= 0) { + parsed.activeTabIndex = matchingTabIndex; + } else { + const operationName = query ? fuzzyExtractOperationName(query) : null; + parsed.tabs.push({ + id: guid(), + hash: expectedHash, + title: operationName || DEFAULT_TITLE, + query, + variables, + headers, + operationName, + response: null + }); + parsed.activeTabIndex = parsed.tabs.length - 1; + } + return parsed; + } + throw new Error("Storage for tabs is invalid"); + } catch { + return { + activeTabIndex: 0, + tabs: (defaultTabs || [{ + query: query !== null && query !== void 0 ? query : defaultQuery, + variables, + headers: headers !== null && headers !== void 0 ? headers : defaultHeaders + }]).map(createTab) + }; + } + } + function isTabsState(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj) && hasNumberKey(obj, "activeTabIndex") && "tabs" in obj && Array.isArray(obj.tabs) && obj.tabs.every(isTabState); + } + function isTabState(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj) && hasStringKey(obj, "id") && hasStringKey(obj, "title") && hasStringOrNullKey(obj, "query") && hasStringOrNullKey(obj, "variables") && hasStringOrNullKey(obj, "headers") && hasStringOrNullKey(obj, "operationName") && hasStringOrNullKey(obj, "response"); + } + function hasNumberKey(obj, key) { + return key in obj && typeof obj[key] === "number"; + } + function hasStringKey(obj, key) { + return key in obj && typeof obj[key] === "string"; + } + function hasStringOrNullKey(obj, key) { + return key in obj && (typeof obj[key] === "string" || obj[key] === null); + } + function useSynchronizeActiveTabValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor + }) { + return React.useCallback(state => { + var _ref6, _ref7, _ref8, _ref9, _ref10; + const query = (_ref6 = queryEditor == null ? void 0 : queryEditor.getValue()) !== null && _ref6 !== void 0 ? _ref6 : null; + const variables = (_ref7 = variableEditor == null ? void 0 : variableEditor.getValue()) !== null && _ref7 !== void 0 ? _ref7 : null; + const headers = (_ref8 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref8 !== void 0 ? _ref8 : null; + const operationName = (_ref9 = queryEditor == null ? void 0 : queryEditor.operationName) !== null && _ref9 !== void 0 ? _ref9 : null; + const response = (_ref10 = responseEditor == null ? void 0 : responseEditor.getValue()) !== null && _ref10 !== void 0 ? _ref10 : null; + return setPropertiesInActiveTab(state, { + query, + variables, + headers, + response, + operationName + }); + }, [queryEditor, variableEditor, headerEditor, responseEditor]); + } + function serializeTabState(tabState, shouldPersistHeaders = false) { + return JSON.stringify(tabState, (key, value) => key === "hash" || key === "response" || !shouldPersistHeaders && key === "headers" ? null : value); + } + function useStoreTabs({ + storage, + shouldPersistHeaders + }) { + const store = React.useMemo(() => debounce(500, value => { + storage == null ? void 0 : storage.set(STORAGE_KEY$2, value); + }), [storage]); + return React.useCallback(currentState => { + store(serializeTabState(currentState, shouldPersistHeaders)); + }, [shouldPersistHeaders, store]); + } + function useSetEditorValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor + }) { + return React.useCallback(({ + query, + variables, + headers, + response + }) => { + queryEditor == null ? void 0 : queryEditor.setValue(query !== null && query !== void 0 ? query : ""); + variableEditor == null ? void 0 : variableEditor.setValue(variables !== null && variables !== void 0 ? variables : ""); + headerEditor == null ? void 0 : headerEditor.setValue(headers !== null && headers !== void 0 ? headers : ""); + responseEditor == null ? void 0 : responseEditor.setValue(response !== null && response !== void 0 ? response : ""); + }, [headerEditor, queryEditor, responseEditor, variableEditor]); + } + function createTab({ + query = null, + variables = null, + headers = null + } = {}) { + return { + id: guid(), + hash: hashFromTabContents({ + query, + variables, + headers + }), + title: query && fuzzyExtractOperationName(query) || DEFAULT_TITLE, + query, + variables, + headers, + operationName: null, + response: null + }; + } + function setPropertiesInActiveTab(state, partialTab) { + return { + ...state, + tabs: state.tabs.map((tab, index) => { + if (index !== state.activeTabIndex) { + return tab; + } + const newTab = { + ...tab, + ...partialTab + }; + return { + ...newTab, + hash: hashFromTabContents(newTab), + title: newTab.operationName || (newTab.query ? fuzzyExtractOperationName(newTab.query) : void 0) || DEFAULT_TITLE + }; + }) + }; + } + function guid() { + const s4 = () => { + return Math.floor((1 + Math.random()) * 65536).toString(16).slice(1); + }; + return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`; + } + function hashFromTabContents(args) { + var _args$query, _args$variables, _args$headers; + return [(_args$query = args.query) !== null && _args$query !== void 0 ? _args$query : "", (_args$variables = args.variables) !== null && _args$variables !== void 0 ? _args$variables : "", (_args$headers = args.headers) !== null && _args$headers !== void 0 ? _args$headers : ""].join("|"); + } + function fuzzyExtractOperationName(str) { + var _ref11; + const regex = /^(?!#).*(query|subscription|mutation)\s+([a-zA-Z0-9_]+)/m; + const match = regex.exec(str); + return (_ref11 = match == null ? void 0 : match[2]) !== null && _ref11 !== void 0 ? _ref11 : null; + } + function clearHeadersFromTabs(storage) { + const persistedTabs = storage == null ? void 0 : storage.get(STORAGE_KEY$2); + if (persistedTabs) { + const parsedTabs = JSON.parse(persistedTabs); + storage == null ? void 0 : storage.set(STORAGE_KEY$2, JSON.stringify(parsedTabs, (key, value) => key === "headers" ? null : value)); + } + } + const DEFAULT_TITLE = ""; + const STORAGE_KEY$2 = "tabState"; + function useVariableEditor({ + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP, + onClickReference, + onEdit, + readOnly = false + } = {}, caller) { + const { + initialVariables, + variableEditor, + setVariableEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useVariableEditor + }); + const executionContext = useExecutionContext(); + const merge = useMergeQuery({ + caller: caller || useVariableEditor + }); + const prettify = usePrettifyEditors({ + caller: caller || useVariableEditor + }); + const ref = React.useRef(null); + const codeMirrorRef = React.useRef(); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./hint.cjs2.js */ "../../graphiql-react/dist/hint.cjs2.js")), Promise.resolve().then(() => __webpack_require__(/*! ./lint.cjs3.js */ "../../graphiql-react/dist/lint.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs2.js */ "../../graphiql-react/dist/mode.cjs2.js"))]).then(CodeMirror => { + if (!isActive) { + return; + } + codeMirrorRef.current = CodeMirror; + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialVariables, + lineNumbers: true, + tabSize: 2, + mode: "graphql-variables", + theme: editorTheme, + autoCloseBrackets: true, + matchBrackets: true, + showCursorWhenSelecting: true, + readOnly: readOnly ? "nocursor" : false, + foldGutter: true, + lint: { + // @ts-expect-error + variableToType: void 0 }, - }); - Object.defineProperty(exports, "pointToOffset", { - enumerable: true, - get: function () { - return _utils.pointToOffset; + hintOptions: { + closeOnUnfocus: false, + completeSingle: false, + container, + // @ts-expect-error + variableToType: void 0 }, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], + extraKeys: commonKeys }); - Object.defineProperty(exports, "t", { - enumerable: true, - get: function () { - return _parser.t; + newEditor.addKeyMap({ + "Cmd-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); }, - }); - Object.defineProperty(exports, "validateQuery", { - enumerable: true, - get: function () { - return _interface.validateQuery; + "Ctrl-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); }, - }); - Object.defineProperty(exports, "validateWithCustomRules", { - enumerable: true, - get: function () { - return _utils.validateWithCustomRules; + "Alt-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); }, - }); - var _interface = __webpack_require__( - /*! ./interface */ "../../graphql-language-service/esm/interface/index.js" - ); - var _parser = __webpack_require__( - /*! ./parser */ "../../graphql-language-service/esm/parser/index.js" - ); - var _types = __webpack_require__( - /*! ./types */ "../../graphql-language-service/esm/types.js" - ); - var _utils = __webpack_require__( - /*! ./utils */ "../../graphql-language-service/esm/utils/index.js" - ); - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/autocompleteUtils.js": - /*!*************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/autocompleteUtils.js ***! - \*************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getInsertText = - exports.getInputInsertText = - exports.getFieldInsertText = - void 0; - exports.hintList = hintList; - exports.objectValues = objectValues; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function objectValues(object) { - const keys = Object.keys(object); - const len = keys.length; - const values = new Array(len); - for (let i = 0; i < len; ++i) { - values[i] = object[keys[i]]; - } - return values; - } - function hintList(token, list) { - return filterAndSortList(list, normalizeText(token.string)); - } - function filterAndSortList(list, text) { - if ( - !text || - text.trim() === "" || - text.trim() === ":" || - text.trim() === "{" - ) { - return filterNonEmpty(list, (entry) => !entry.isDeprecated); - } - const byProximity = list.map((entry) => ({ - proximity: getProximity(normalizeText(entry.label), text), - entry, - })); - return filterNonEmpty( - filterNonEmpty(byProximity, (pair) => pair.proximity <= 2), - (pair) => !pair.entry.isDeprecated - ) - .sort( - (a, b) => - (a.entry.isDeprecated ? 1 : 0) - - (b.entry.isDeprecated ? 1 : 0) || - a.proximity - b.proximity || - a.entry.label.length - b.entry.label.length - ) - .map((pair) => pair.entry); - } - function filterNonEmpty(array, predicate) { - const filtered = array.filter(predicate); - return filtered.length === 0 ? array : filtered; - } - function normalizeText(text) { - return text.toLowerCase().replaceAll(/\W/g, ""); - } - function getProximity(suggestion, text) { - let proximity = lexicalDistance(text, suggestion); - if (suggestion.length > text.length) { - proximity -= suggestion.length - text.length - 1; - proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5; - } - return proximity; - } - function lexicalDistance(a, b) { - let i; - let j; - const d = []; - const aLength = a.length; - const bLength = b.length; - for (i = 0; i <= aLength; i++) { - d[i] = [i]; - } - for (j = 1; j <= bLength; j++) { - d[0][j] = j; - } - for (i = 1; i <= aLength; i++) { - for (j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - d[i][j] = Math.min( - d[i - 1][j] + 1, - d[i][j - 1] + 1, - d[i - 1][j - 1] + cost - ); - if ( - i > 1 && - j > 1 && - a[i - 1] === b[j - 2] && - a[i - 2] === b[j - 1] - ) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); - } - } - } - return d[aLength][bLength]; - } - const insertSuffix = (n) => - ` {\n $${n !== null && n !== void 0 ? n : 1}\n}`; - const getInsertText = (prefix, type, fallback) => { - if (!type) { - return fallback !== null && fallback !== void 0 ? fallback : prefix; - } - const namedType = (0, _graphql.getNamedType)(type); - if ( - (0, _graphql.isObjectType)(namedType) || - (0, _graphql.isInputObjectType)(namedType) || - (0, _graphql.isListType)(namedType) || - (0, _graphql.isAbstractType)(namedType) - ) { - return prefix + insertSuffix(); + "Shift-Space"() { + newEditor.showHint({ + completeSingle: false, + container + }); } - return fallback !== null && fallback !== void 0 ? fallback : prefix; + }); + newEditor.on("keyup", (editorInstance, event) => { + const { + code, + key, + shiftKey + } = event; + const isLetter = code.startsWith("Key"); + const isNumber = !shiftKey && code.startsWith("Digit"); + if (isLetter || isNumber || key === "_" || key === '"') { + editorInstance.execCommand("autocomplete"); + } + }); + setVariableEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialVariables, readOnly, setVariableEditor]); + useSynchronizeOption(variableEditor, "keyMap", keyMap); + useChangeHandler(variableEditor, onEdit, STORAGE_KEY$1, "variables", useVariableEditor); + useCompletion(variableEditor, onClickReference || null, useVariableEditor); + useKeyMap(variableEditor, ["Cmd-Enter", "Ctrl-Enter"], executionContext == null ? void 0 : executionContext.run); + useKeyMap(variableEditor, ["Shift-Ctrl-P"], prettify); + useKeyMap(variableEditor, ["Shift-Ctrl-M"], merge); + return ref; + } + const STORAGE_KEY$1 = "variables"; + const EditorContext = createNullableContext("EditorContext"); + function EditorContextProvider(props) { + const storage = useStorageContext(); + const [headerEditor, setHeaderEditor] = React.useState(null); + const [queryEditor, setQueryEditor] = React.useState(null); + const [responseEditor, setResponseEditor] = React.useState(null); + const [variableEditor, setVariableEditor] = React.useState(null); + const [shouldPersistHeaders, setShouldPersistHeadersInternal] = React.useState(() => { + const isStored = (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) !== null; + return props.shouldPersistHeaders !== false && isStored ? (storage == null ? void 0 : storage.get(PERSIST_HEADERS_STORAGE_KEY)) === "true" : Boolean(props.shouldPersistHeaders); + }); + useSynchronizeValue(headerEditor, props.headers); + useSynchronizeValue(queryEditor, props.query); + useSynchronizeValue(responseEditor, props.response); + useSynchronizeValue(variableEditor, props.variables); + const storeTabs = useStoreTabs({ + storage, + shouldPersistHeaders + }); + const [initialState] = React.useState(() => { + var _ref12, _props$query, _ref13, _props$variables, _ref14, _props$headers, _props$response, _ref15, _ref16; + const query = (_ref12 = (_props$query = props.query) !== null && _props$query !== void 0 ? _props$query : storage == null ? void 0 : storage.get(STORAGE_KEY_QUERY)) !== null && _ref12 !== void 0 ? _ref12 : null; + const variables = (_ref13 = (_props$variables = props.variables) !== null && _props$variables !== void 0 ? _props$variables : storage == null ? void 0 : storage.get(STORAGE_KEY$1)) !== null && _ref13 !== void 0 ? _ref13 : null; + const headers = (_ref14 = (_props$headers = props.headers) !== null && _props$headers !== void 0 ? _props$headers : storage == null ? void 0 : storage.get(STORAGE_KEY$3)) !== null && _ref14 !== void 0 ? _ref14 : null; + const response = (_props$response = props.response) !== null && _props$response !== void 0 ? _props$response : ""; + const tabState2 = getDefaultTabState({ + query, + variables, + headers, + defaultTabs: props.defaultTabs, + defaultQuery: props.defaultQuery || DEFAULT_QUERY, + defaultHeaders: props.defaultHeaders, + storage, + shouldPersistHeaders + }); + storeTabs(tabState2); + return { + query: (_ref15 = query !== null && query !== void 0 ? query : tabState2.activeTabIndex === 0 ? tabState2.tabs[0].query : null) !== null && _ref15 !== void 0 ? _ref15 : "", + variables: variables !== null && variables !== void 0 ? variables : "", + headers: (_ref16 = headers !== null && headers !== void 0 ? headers : props.defaultHeaders) !== null && _ref16 !== void 0 ? _ref16 : "", + response, + tabState: tabState2 + }; + }); + const [tabState, setTabState] = React.useState(initialState.tabState); + const setShouldPersistHeaders = React.useCallback(persist => { + if (persist) { + var _ref17; + storage == null ? void 0 : storage.set(STORAGE_KEY$3, (_ref17 = headerEditor == null ? void 0 : headerEditor.getValue()) !== null && _ref17 !== void 0 ? _ref17 : ""); + const serializedTabs = serializeTabState(tabState, true); + storage == null ? void 0 : storage.set(STORAGE_KEY$2, serializedTabs); + } else { + storage == null ? void 0 : storage.set(STORAGE_KEY$3, ""); + clearHeadersFromTabs(storage); + } + setShouldPersistHeadersInternal(persist); + storage == null ? void 0 : storage.set(PERSIST_HEADERS_STORAGE_KEY, persist.toString()); + }, [storage, tabState, headerEditor]); + const lastShouldPersistHeadersProp = React.useRef(); + React.useEffect(() => { + const propValue = Boolean(props.shouldPersistHeaders); + if ((lastShouldPersistHeadersProp == null ? void 0 : lastShouldPersistHeadersProp.current) !== propValue) { + setShouldPersistHeaders(propValue); + lastShouldPersistHeadersProp.current = propValue; + } + }, [props.shouldPersistHeaders, setShouldPersistHeaders]); + const synchronizeActiveTabValues = useSynchronizeActiveTabValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor + }); + const setEditorValues = useSetEditorValues({ + queryEditor, + variableEditor, + headerEditor, + responseEditor + }); + const { + onTabChange, + defaultHeaders, + children + } = props; + const addTab = React.useCallback(() => { + setTabState(current => { + const updatedValues = synchronizeActiveTabValues(current); + const updated = { + tabs: [...updatedValues.tabs, createTab({ + headers: defaultHeaders + })], + activeTabIndex: updatedValues.tabs.length }; - exports.getInsertText = getInsertText; - const getInputInsertText = (prefix, type, fallback) => { - if ((0, _graphql.isListType)(type)) { - const baseType = (0, _graphql.getNamedType)(type.ofType); - return prefix + `[${getInsertText("", baseType, "$1")}]`; - } - return getInsertText(prefix, type, fallback); + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [defaultHeaders, onTabChange, setEditorValues, storeTabs, synchronizeActiveTabValues]); + const changeTab = React.useCallback(index => { + setTabState(current => { + const updated = { + ...current, + activeTabIndex: index }; - exports.getInputInsertText = getInputInsertText; - const getFieldInsertText = (field) => { - const requiredArgs = field.args.filter((arg) => - arg.type.toString().endsWith("!") - ); - if (!requiredArgs.length) { - return; - } - return ( - field.name + - `(${requiredArgs.map( - (arg, i) => `${arg.name}: $${i + 1}` - )}) ${getInsertText("", field.type, "\n")}` - ); + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, setEditorValues, storeTabs]); + const moveTab = React.useCallback(newOrder => { + setTabState(current => { + const activeTab = current.tabs[current.activeTabIndex]; + const updated = { + tabs: newOrder, + activeTabIndex: newOrder.indexOf(activeTab) }; - exports.getFieldInsertText = getFieldInsertText; - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js": - /*!**********************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js ***! - \**********************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.SuggestionCommand = void 0; - exports.canUseDirective = canUseDirective; - exports.getAutocompleteSuggestions = getAutocompleteSuggestions; - exports.getFragmentDefinitions = getFragmentDefinitions; - Object.defineProperty(exports, "getTypeInfo", { - enumerable: true, - get: function () { - return _parser.getTypeInfo; - }, - }); - exports.getVariableCompletions = getVariableCompletions; - Object.defineProperty(exports, "runOnlineParser", { - enumerable: true, - get: function () { - return _parser.runOnlineParser; - }, - }); - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _types = __webpack_require__( - /*! ../types */ "../../graphql-language-service/esm/types.js" - ); - var _parser = __webpack_require__( - /*! ../parser */ "../../graphql-language-service/esm/parser/index.js" - ); - var _autocompleteUtils = __webpack_require__( - /*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js" - ); - var _vscodeLanguageserverTypes = __webpack_require__( - /*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js" - ); - const SuggestionCommand = (exports.SuggestionCommand = { - command: "editor.action.triggerSuggest", - title: "Suggestions", - }); - const collectFragmentDefs = (op) => { - const externalFragments = []; - if (op) { - try { - (0, _graphql.visit)((0, _graphql.parse)(op), { - FragmentDefinition(def) { - externalFragments.push(def); - }, - }); - } catch (_a) { - return []; - } - } - return externalFragments; + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, setEditorValues, storeTabs]); + const closeTab = React.useCallback(index => { + setTabState(current => { + const updated = { + tabs: current.tabs.filter((_tab, i) => index !== i), + activeTabIndex: Math.max(current.activeTabIndex - 1, 0) }; - function getAutocompleteSuggestions( - schema, - queryText, - cursor, - contextToken, - fragmentDefs, - options - ) { - var _a; - const opts = Object.assign(Object.assign({}, options), { - schema, - }); - const context = (0, _parser.getContextAtPosition)( - queryText, - cursor, - schema, - contextToken, - options - ); - if (!context) { - return []; - } - const { state, typeInfo, mode, token } = context; - const { kind, step, prevState } = state; - if (kind === _parser.RuleKinds.DOCUMENT) { - if (mode === _parser.GraphQLDocumentMode.TYPE_SYSTEM) { - return getSuggestionsForTypeSystemDefinitions(token); - } - if (mode === _parser.GraphQLDocumentMode.EXECUTABLE) { - return getSuggestionsForExecutableDefinitions(token); - } - return getSuggestionsForUnknownDocumentMode(token); - } - if (kind === _parser.RuleKinds.EXTEND_DEF) { - return getSuggestionsForExtensionDefinitions(token); - } - if ( - ((_a = - prevState === null || prevState === void 0 - ? void 0 - : prevState.prevState) === null || _a === void 0 - ? void 0 - : _a.kind) === _parser.RuleKinds.EXTENSION_DEFINITION && - state.name - ) { - return (0, _autocompleteUtils.hintList)(token, []); - } - if ( - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _graphql.Kind.SCALAR_TYPE_EXTENSION - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter(_graphql.isScalarType) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - })) - ); - } - if ( - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _graphql.Kind.OBJECT_TYPE_EXTENSION - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter( - (type) => - (0, _graphql.isObjectType)(type) && - !type.name.startsWith("__") - ) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - })) - ); - } - if ( - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _graphql.Kind.INTERFACE_TYPE_EXTENSION - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter(_graphql.isInterfaceType) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - })) - ); - } - if ( - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _graphql.Kind.UNION_TYPE_EXTENSION - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter(_graphql.isUnionType) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - })) - ); - } - if ( - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _graphql.Kind.ENUM_TYPE_EXTENSION - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter( - (type) => - (0, _graphql.isEnumType)(type) && - !type.name.startsWith("__") - ) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - })) - ); + storeTabs(updated); + setEditorValues(updated.tabs[updated.activeTabIndex]); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, setEditorValues, storeTabs]); + const updateActiveTabValues = React.useCallback(partialTab => { + setTabState(current => { + const updated = setPropertiesInActiveTab(current, partialTab); + storeTabs(updated); + onTabChange == null ? void 0 : onTabChange(updated); + return updated; + }); + }, [onTabChange, storeTabs]); + const { + onEditOperationName + } = props; + const setOperationName = React.useCallback(operationName => { + if (!queryEditor) { + return; + } + queryEditor.operationName = operationName; + updateActiveTabValues({ + operationName + }); + onEditOperationName == null ? void 0 : onEditOperationName(operationName); + }, [onEditOperationName, queryEditor, updateActiveTabValues]); + const externalFragments = React.useMemo(() => { + const map = /* @__PURE__ */new Map(); + if (Array.isArray(props.externalFragments)) { + for (const fragment of props.externalFragments) { + map.set(fragment.name.value, fragment); + } + } else if (typeof props.externalFragments === "string") { + graphql.visit(graphql.parse(props.externalFragments, {}), { + FragmentDefinition(fragment) { + map.set(fragment.name.value, fragment); + } + }); + } else if (props.externalFragments) { + throw new Error("The `externalFragments` prop must either be a string that contains the fragment definitions in SDL or a list of FragmentDefinitionNode objects."); + } + return map; + }, [props.externalFragments]); + const validationRules = React.useMemo(() => props.validationRules || [], [props.validationRules]); + const value = React.useMemo(() => ({ + ...tabState, + addTab, + changeTab, + moveTab, + closeTab, + updateActiveTabValues, + headerEditor, + queryEditor, + responseEditor, + variableEditor, + setHeaderEditor, + setQueryEditor, + setResponseEditor, + setVariableEditor, + setOperationName, + initialQuery: initialState.query, + initialVariables: initialState.variables, + initialHeaders: initialState.headers, + initialResponse: initialState.response, + externalFragments, + validationRules, + shouldPersistHeaders, + setShouldPersistHeaders + }), [tabState, addTab, changeTab, moveTab, closeTab, updateActiveTabValues, headerEditor, queryEditor, responseEditor, variableEditor, setOperationName, initialState, externalFragments, validationRules, shouldPersistHeaders, setShouldPersistHeaders]); + return /* @__PURE__ */jsxRuntime.jsx(EditorContext.Provider, { + value, + children + }); + } + const useEditorContext = createContextHook(EditorContext); + const PERSIST_HEADERS_STORAGE_KEY = "shouldPersistHeaders"; + const DEFAULT_QUERY = `# Welcome to GraphiQL + # + # GraphiQL is an in-browser tool for writing, validating, and + # testing GraphQL queries. + # + # Type queries into this side of the screen, and you will see intelligent + # typeaheads aware of the current GraphQL type schema and live syntax and + # validation errors highlighted within the text. + # + # GraphQL queries typically start with a "{" character. Lines that start + # with a # are ignored. + # + # An example GraphQL query might look like: + # + # { + # field(arg: "value") { + # subField + # } + # } + # + # Keyboard shortcuts: + # + # Prettify query: Shift-Ctrl-P (or press the prettify button) + # + # Merge fragments: Shift-Ctrl-M (or press the merge button) + # + # Run Query: Ctrl-Enter (or press the play button) + # + # Auto Complete: Ctrl-Space (or just start typing) + # + + `; + function HeaderEditor({ + isHidden, + ...hookArgs + }) { + const { + headerEditor + } = useEditorContext({ + nonNull: true, + caller: HeaderEditor + }); + const ref = useHeaderEditor(hookArgs, HeaderEditor); + React.useEffect(() => { + if (!isHidden) { + headerEditor == null ? void 0 : headerEditor.refresh(); + } + }, [headerEditor, isHidden]); + return /* @__PURE__ */jsxRuntime.jsx("div", { + className: clsx.clsx("graphiql-editor", isHidden && "hidden"), + ref + }); + } + function ImagePreview(props) { + var _a; + const [dimensions, setDimensions] = React.useState({ + width: null, + height: null + }); + const [mime, setMime] = React.useState(null); + const ref = React.useRef(null); + const src = (_a = tokenToURL(props.token)) == null ? void 0 : _a.href; + React.useEffect(() => { + if (!ref.current) { + return; + } + if (!src) { + setDimensions({ + width: null, + height: null + }); + setMime(null); + return; + } + fetch(src, { + method: "HEAD" + }).then(response => { + setMime(response.headers.get("Content-Type")); + }).catch(() => { + setMime(null); + }); + }, [src]); + const dims = dimensions.width !== null && dimensions.height !== null ? /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [dimensions.width, "x", dimensions.height, mime === null ? null : " " + mime] + }) : null; + return /* @__PURE__ */jsxRuntime.jsxs("div", { + children: [/* @__PURE__ */jsxRuntime.jsx("img", { + onLoad: () => { + var _ref18, _ref19; + var _a2, _b; + setDimensions({ + width: (_ref18 = (_a2 = ref.current) == null ? void 0 : _a2.naturalWidth) !== null && _ref18 !== void 0 ? _ref18 : null, + height: (_ref19 = (_b = ref.current) == null ? void 0 : _b.naturalHeight) !== null && _ref19 !== void 0 ? _ref19 : null + }); + }, + ref, + src + }), dims] + }); + } + ImagePreview.shouldRender = function shouldRender(token) { + const url = tokenToURL(token); + return url ? isImageURL(url) : false; + }; + function tokenToURL(token) { + if (token.type !== "string") { + return; + } + const value = token.string.slice(1).slice(0, -1).trim(); + try { + const { + location + } = window; + return new URL(value, location.protocol + "//" + location.host); + } catch { + return; + } + } + function isImageURL(url) { + return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname); + } + function QueryEditor(props) { + const ref = useQueryEditor(props, QueryEditor); + return /* @__PURE__ */jsxRuntime.jsx("div", { + className: "graphiql-editor", + ref + }); + } + function useResponseEditor({ + responseTooltip, + editorTheme = DEFAULT_EDITOR_THEME, + keyMap = DEFAULT_KEY_MAP + } = {}, caller) { + const { + fetchError, + validationErrors + } = useSchemaContext({ + nonNull: true, + caller: caller || useResponseEditor + }); + const { + initialResponse, + responseEditor, + setResponseEditor + } = useEditorContext({ + nonNull: true, + caller: caller || useResponseEditor + }); + const ref = React.useRef(null); + const responseTooltipRef = React.useRef(responseTooltip); + React.useEffect(() => { + responseTooltipRef.current = responseTooltip; + }, [responseTooltip]); + React.useEffect(() => { + let isActive = true; + void importCodeMirror([Promise.resolve().then(() => __webpack_require__(/*! ./foldgutter.cjs.js */ "../../graphiql-react/dist/foldgutter.cjs.js")).then(n => n.foldgutter), Promise.resolve().then(() => __webpack_require__(/*! ./brace-fold.cjs.js */ "../../graphiql-react/dist/brace-fold.cjs.js")).then(n => n.braceFold), Promise.resolve().then(() => __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js")).then(n => n.dialog), Promise.resolve().then(() => __webpack_require__(/*! ./search.cjs.js */ "../../graphiql-react/dist/search.cjs.js")).then(n => n.search), Promise.resolve().then(() => __webpack_require__(/*! ./searchcursor.cjs.js */ "../../graphiql-react/dist/searchcursor.cjs.js")).then(n => n.searchcursor), Promise.resolve().then(() => __webpack_require__(/*! ./jump-to-line.cjs.js */ "../../graphiql-react/dist/jump-to-line.cjs.js")).then(n => n.jumpToLine), + // @ts-expect-error + Promise.resolve().then(() => __webpack_require__(/*! ./sublime.cjs.js */ "../../graphiql-react/dist/sublime.cjs.js")).then(n => n.sublime), Promise.resolve().then(() => __webpack_require__(/*! ./mode.cjs3.js */ "../../graphiql-react/dist/mode.cjs3.js")), Promise.resolve().then(() => __webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"))], { + useCommonAddons: false + }).then(CodeMirror => { + if (!isActive) { + return; + } + const tooltipDiv = document.createElement("div"); + CodeMirror.registerHelper("info", "graphql-results", (token, _options, _cm, pos) => { + const infoElements = []; + const ResponseTooltipComponent = responseTooltipRef.current; + if (ResponseTooltipComponent) { + infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ResponseTooltipComponent, { + pos, + token + })); } - if ( - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter(_graphql.isInputObjectType) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - })) - ); + if (ImagePreview.shouldRender(token)) { + infoElements.push( /* @__PURE__ */jsxRuntime.jsx(ImagePreview, { + token + }, "image-preview")); } - if ( - kind === _parser.RuleKinds.IMPLEMENTS || - (kind === _parser.RuleKinds.NAMED_TYPE && - (prevState === null || prevState === void 0 - ? void 0 - : prevState.kind) === _parser.RuleKinds.IMPLEMENTS) - ) { - return getSuggestionsForImplements( - token, - state, - schema, - queryText, - typeInfo - ); + if (!infoElements.length) { + ReactDOM.unmountComponentAtNode(tooltipDiv); + return null; } - if ( - kind === _parser.RuleKinds.SELECTION_SET || - kind === _parser.RuleKinds.FIELD || - kind === _parser.RuleKinds.ALIASED_FIELD - ) { - return getSuggestionsForFieldNames(token, typeInfo, opts); - } - if ( - kind === _parser.RuleKinds.ARGUMENTS || - (kind === _parser.RuleKinds.ARGUMENT && step === 0) - ) { - const { argDefs } = typeInfo; - if (argDefs) { - return (0, _autocompleteUtils.hintList)( - token, - argDefs.map((argDef) => { - var _a; - return { - label: argDef.name, - insertText: (0, _autocompleteUtils.getInputInsertText)( - argDef.name + ": ", - argDef.type - ), - insertTextMode: - _vscodeLanguageserverTypes.InsertTextMode - .adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - command: SuggestionCommand, - labelDetails: { - detail: " " + String(argDef.type), - }, - documentation: - (_a = argDef.description) !== null && _a !== void 0 - ? _a - : undefined, - kind: _types.CompletionItemKind.Variable, - type: argDef.type, - }; + ReactDOM.render(infoElements, tooltipDiv); + return tooltipDiv; + }); + const container = ref.current; + if (!container) { + return; + } + const newEditor = CodeMirror(container, { + value: initialResponse, + lineWrapping: true, + readOnly: true, + theme: editorTheme, + mode: "graphql-results", + foldGutter: true, + gutters: ["CodeMirror-foldgutter"], + // @ts-expect-error + info: true, + extraKeys: commonKeys + }); + setResponseEditor(newEditor); + }); + return () => { + isActive = false; + }; + }, [editorTheme, initialResponse, setResponseEditor]); + useSynchronizeOption(responseEditor, "keyMap", keyMap); + React.useEffect(() => { + if (fetchError) { + responseEditor == null ? void 0 : responseEditor.setValue(fetchError); + } + if (validationErrors.length > 0) { + responseEditor == null ? void 0 : responseEditor.setValue(toolkit.formatError(validationErrors)); + } + }, [responseEditor, fetchError, validationErrors]); + return ref; + } + function ResponseEditor(props) { + const ref = useResponseEditor(props, ResponseEditor); + return /* @__PURE__ */jsxRuntime.jsx("section", { + className: "result-window", + "aria-label": "Result Window", + "aria-live": "polite", + "aria-atomic": "true", + ref + }); + } + function VariableEditor({ + isHidden, + ...hookArgs + }) { + const { + variableEditor + } = useEditorContext({ + nonNull: true, + caller: VariableEditor + }); + const ref = useVariableEditor(hookArgs, VariableEditor); + React.useEffect(() => { + if (variableEditor && !isHidden) { + variableEditor.refresh(); + } + }, [variableEditor, isHidden]); + return /* @__PURE__ */jsxRuntime.jsx("div", { + className: clsx.clsx("graphiql-editor", isHidden && "hidden"), + ref + }); + } + function GraphiQLProvider({ + children, + dangerouslyAssumeSchemaIsValid, + defaultQuery, + defaultHeaders, + defaultTabs, + externalFragments, + fetcher, + getDefaultFieldNames, + headers, + inputValueDeprecation, + introspectionQueryName, + maxHistoryLength, + onEditOperationName, + onSchemaChange, + onTabChange, + onTogglePluginVisibility, + operationName, + plugins, + query, + response, + schema, + schemaDescription, + shouldPersistHeaders, + storage, + validationRules, + variables, + visiblePlugin + }) { + return /* @__PURE__ */jsxRuntime.jsx(StorageContextProvider, { + storage, + children: /* @__PURE__ */jsxRuntime.jsx(HistoryContextProvider, { + maxHistoryLength, + children: /* @__PURE__ */jsxRuntime.jsx(EditorContextProvider, { + defaultQuery, + defaultHeaders, + defaultTabs, + externalFragments, + headers, + onEditOperationName, + onTabChange, + query, + response, + shouldPersistHeaders, + validationRules, + variables, + children: /* @__PURE__ */jsxRuntime.jsx(SchemaContextProvider, { + dangerouslyAssumeSchemaIsValid, + fetcher, + inputValueDeprecation, + introspectionQueryName, + onSchemaChange, + schema, + schemaDescription, + children: /* @__PURE__ */jsxRuntime.jsx(ExecutionContextProvider, { + getDefaultFieldNames, + fetcher, + operationName, + children: /* @__PURE__ */jsxRuntime.jsx(ExplorerContextProvider, { + children: /* @__PURE__ */jsxRuntime.jsx(PluginContextProvider, { + onTogglePluginVisibility, + plugins, + visiblePlugin, + children }) - ); - } - } - if ( - (kind === _parser.RuleKinds.OBJECT_VALUE || - (kind === _parser.RuleKinds.OBJECT_FIELD && step === 0)) && - typeInfo.objectFieldDefs - ) { - const objectFields = (0, _autocompleteUtils.objectValues)( - typeInfo.objectFieldDefs - ); - const completionKind = - kind === _parser.RuleKinds.OBJECT_VALUE - ? _types.CompletionItemKind.Value - : _types.CompletionItemKind.Field; - return (0, _autocompleteUtils.hintList)( - token, - objectFields.map((field) => { - var _a; - return { - label: field.name, - detail: String(field.type), - documentation: - (_a = - field === null || field === void 0 - ? void 0 - : field.description) !== null && _a !== void 0 - ? _a - : undefined, - kind: completionKind, - type: field.type, - insertText: (0, _autocompleteUtils.getInputInsertText)( - field.name + ": ", - field.type - ), - insertTextMode: - _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - command: SuggestionCommand, - }; }) - ); - } - if ( - kind === _parser.RuleKinds.ENUM_VALUE || - (kind === _parser.RuleKinds.LIST_VALUE && step === 1) || - (kind === _parser.RuleKinds.OBJECT_FIELD && step === 2) || - (kind === _parser.RuleKinds.ARGUMENT && step === 2) - ) { - return getSuggestionsForInputValues( - token, - typeInfo, - queryText, - schema - ); - } - if (kind === _parser.RuleKinds.VARIABLE && step === 1) { - const namedInputType = (0, _graphql.getNamedType)( - typeInfo.inputType - ); - const variableDefinitions = getVariableCompletions( - queryText, - schema, - token - ); - return (0, _autocompleteUtils.hintList)( - token, - variableDefinitions.filter( - (v) => - v.detail === - (namedInputType === null || namedInputType === void 0 - ? void 0 - : namedInputType.name) - ) - ); - } - if ( - (kind === _parser.RuleKinds.TYPE_CONDITION && step === 1) || - (kind === _parser.RuleKinds.NAMED_TYPE && - prevState != null && - prevState.kind === _parser.RuleKinds.TYPE_CONDITION) - ) { - return getSuggestionsForFragmentTypeConditions( - token, - typeInfo, - schema, - kind - ); - } - if (kind === _parser.RuleKinds.FRAGMENT_SPREAD && step === 1) { - return getSuggestionsForFragmentSpread( - token, - typeInfo, - schema, - queryText, - Array.isArray(fragmentDefs) - ? fragmentDefs - : collectFragmentDefs(fragmentDefs) - ); - } - const unwrappedState = unwrapType(state); - if (unwrappedState.kind === _parser.RuleKinds.FIELD_DEF) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter( - (type) => - (0, _graphql.isOutputType)(type) && - !type.name.startsWith("__") - ) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - insertText: ( - options === null || options === void 0 - ? void 0 - : options.fillLeafsOnComplete - ) - ? type.name + "\n" - : type.name, - insertTextMode: - _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - })) - ); - } - if ( - unwrappedState.kind === _parser.RuleKinds.INPUT_VALUE_DEF && - step === 2 - ) { - return (0, _autocompleteUtils.hintList)( - token, - Object.values(schema.getTypeMap()) - .filter( - (type) => - (0, _graphql.isInputType)(type) && - !type.name.startsWith("__") - ) - .map((type) => ({ - label: type.name, - kind: _types.CompletionItemKind.Function, - insertText: ( - options === null || options === void 0 - ? void 0 - : options.fillLeafsOnComplete - ) - ? type.name + "\n$1" - : type.name, - insertTextMode: - _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation, - insertTextFormat: _types.InsertTextFormat.Snippet, - })) - ); + }) + }) + }) + }) + }); + } + function useTheme() { + const storageContext = useStorageContext(); + const [theme, setThemeInternal] = React.useState(() => { + if (!storageContext) { + return null; + } + const stored = storageContext.get(STORAGE_KEY); + switch (stored) { + case "light": + return "light"; + case "dark": + return "dark"; + default: + if (typeof stored === "string") { + storageContext.set(STORAGE_KEY, ""); } - if ( - (kind === _parser.RuleKinds.VARIABLE_DEFINITION && step === 2) || - (kind === _parser.RuleKinds.LIST_TYPE && step === 1) || - (kind === _parser.RuleKinds.NAMED_TYPE && - prevState && - (prevState.kind === _parser.RuleKinds.VARIABLE_DEFINITION || - prevState.kind === _parser.RuleKinds.LIST_TYPE || - prevState.kind === _parser.RuleKinds.NON_NULL_TYPE)) - ) { - return getSuggestionsForVariableDefinition(token, schema, kind); - } - if (kind === _parser.RuleKinds.DIRECTIVE) { - return getSuggestionsForDirective(token, state, schema, kind); - } - if (kind === _parser.RuleKinds.DIRECTIVE_DEF) { - return getSuggestionsForDirectiveArguments( - token, - state, - schema, - kind - ); + return null; + } + }); + React.useLayoutEffect(() => { + if (typeof window === "undefined") { + return; + } + document.body.classList.remove("graphiql-light", "graphiql-dark"); + if (theme) { + document.body.classList.add(`graphiql-${theme}`); + } + }, [theme]); + const setTheme = React.useCallback(newTheme => { + storageContext == null ? void 0 : storageContext.set(STORAGE_KEY, newTheme || ""); + setThemeInternal(newTheme); + }, [storageContext]); + return React.useMemo(() => ({ + theme, + setTheme + }), [theme, setTheme]); + } + const STORAGE_KEY = "theme"; + function useDragResize({ + defaultSizeRelation = DEFAULT_FLEX, + direction, + initiallyHidden, + onHiddenElementChange, + sizeThresholdFirst = 100, + sizeThresholdSecond = 100, + storageKey + }) { + const storage = useStorageContext(); + const store = React.useMemo(() => debounce(500, value => { + if (storageKey) { + storage == null ? void 0 : storage.set(storageKey, value); + } + }), [storage, storageKey]); + const [hiddenElement, setHiddenElement] = React.useState(() => { + const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)); + if (storedValue === HIDE_FIRST || initiallyHidden === "first") { + return "first"; + } + if (storedValue === HIDE_SECOND || initiallyHidden === "second") { + return "second"; + } + return null; + }); + const setHiddenElementWithCallback = React.useCallback(element => { + if (element !== hiddenElement) { + setHiddenElement(element); + onHiddenElementChange == null ? void 0 : onHiddenElementChange(element); + } + }, [hiddenElement, onHiddenElementChange]); + const firstRef = React.useRef(null); + const dragBarRef = React.useRef(null); + const secondRef = React.useRef(null); + const defaultFlexRef = React.useRef(`${defaultSizeRelation}`); + React.useLayoutEffect(() => { + const storedValue = storageKey && (storage == null ? void 0 : storage.get(storageKey)) || defaultFlexRef.current; + if (firstRef.current) { + firstRef.current.style.display = "flex"; + firstRef.current.style.flex = storedValue === HIDE_FIRST || storedValue === HIDE_SECOND ? defaultFlexRef.current : storedValue; + } + if (secondRef.current) { + secondRef.current.style.display = "flex"; + secondRef.current.style.flex = "1"; + } + if (dragBarRef.current) { + dragBarRef.current.style.display = "flex"; + } + }, [direction, storage, storageKey]); + const hide = React.useCallback(resizableElement => { + const element = resizableElement === "first" ? firstRef.current : secondRef.current; + if (!element) { + return; + } + element.style.left = "-1000px"; + element.style.position = "absolute"; + element.style.opacity = "0"; + element.style.height = "500px"; + element.style.width = "500px"; + if (firstRef.current) { + const flex = parseFloat(firstRef.current.style.flex); + if (!Number.isFinite(flex) || flex < 1) { + firstRef.current.style.flex = "1"; + } + } + }, []); + const show = React.useCallback(resizableElement => { + const element = resizableElement === "first" ? firstRef.current : secondRef.current; + if (!element) { + return; + } + element.style.width = ""; + element.style.height = ""; + element.style.opacity = ""; + element.style.position = ""; + element.style.left = ""; + if (storage && storageKey) { + const storedValue = storage.get(storageKey); + if (firstRef.current && storedValue !== HIDE_FIRST && storedValue !== HIDE_SECOND) { + firstRef.current.style.flex = storedValue || defaultFlexRef.current; + } + } + }, [storage, storageKey]); + React.useLayoutEffect(() => { + if (hiddenElement === "first") { + hide("first"); + } else { + show("first"); + } + if (hiddenElement === "second") { + hide("second"); + } else { + show("second"); + } + }, [hiddenElement, hide, show]); + React.useEffect(() => { + if (!dragBarRef.current || !firstRef.current || !secondRef.current) { + return; + } + const dragBarContainer = dragBarRef.current; + const firstContainer = firstRef.current; + const wrapper = firstContainer.parentElement; + const eventProperty = direction === "horizontal" ? "clientX" : "clientY"; + const rectProperty = direction === "horizontal" ? "left" : "top"; + const adjacentRectProperty = direction === "horizontal" ? "right" : "bottom"; + const sizeProperty = direction === "horizontal" ? "clientWidth" : "clientHeight"; + function handleMouseDown(downEvent) { + downEvent.preventDefault(); + const offset = downEvent[eventProperty] - dragBarContainer.getBoundingClientRect()[rectProperty]; + function handleMouseMove(moveEvent) { + if (moveEvent.buttons === 0) { + return handleMouseUp(); + } + const firstSize = moveEvent[eventProperty] - wrapper.getBoundingClientRect()[rectProperty] - offset; + const secondSize = wrapper.getBoundingClientRect()[adjacentRectProperty] - moveEvent[eventProperty] + offset - dragBarContainer[sizeProperty]; + if (firstSize < sizeThresholdFirst) { + setHiddenElementWithCallback("first"); + store(HIDE_FIRST); + } else if (secondSize < sizeThresholdSecond) { + setHiddenElementWithCallback("second"); + store(HIDE_SECOND); + } else { + setHiddenElementWithCallback(null); + const newFlex = `${firstSize / secondSize}`; + firstContainer.style.flex = newFlex; + store(newFlex); } - return []; } - const typeSystemCompletionItems = [ - { - label: "type", - kind: _types.CompletionItemKind.Function, - }, - { - label: "interface", - kind: _types.CompletionItemKind.Function, - }, - { - label: "union", - kind: _types.CompletionItemKind.Function, - }, - { - label: "input", - kind: _types.CompletionItemKind.Function, - }, - { - label: "scalar", - kind: _types.CompletionItemKind.Function, - }, - { - label: "schema", - kind: _types.CompletionItemKind.Function, - }, - ]; - const executableCompletionItems = [ - { - label: "query", - kind: _types.CompletionItemKind.Function, - }, - { - label: "mutation", - kind: _types.CompletionItemKind.Function, - }, - { - label: "subscription", - kind: _types.CompletionItemKind.Function, - }, - { - label: "fragment", - kind: _types.CompletionItemKind.Function, - }, - { - label: "{", - kind: _types.CompletionItemKind.Constructor, - }, - ]; - function getSuggestionsForTypeSystemDefinitions(token) { - return (0, _autocompleteUtils.hintList)(token, [ - { - label: "extend", - kind: _types.CompletionItemKind.Function, - }, - ...typeSystemCompletionItems, - ]); + function handleMouseUp() { + document.removeEventListener("mousemove", handleMouseMove); + document.removeEventListener("mouseup", handleMouseUp); } - function getSuggestionsForExecutableDefinitions(token) { - return (0, _autocompleteUtils.hintList)( - token, - executableCompletionItems - ); + document.addEventListener("mousemove", handleMouseMove); + document.addEventListener("mouseup", handleMouseUp); + } + dragBarContainer.addEventListener("mousedown", handleMouseDown); + function reset() { + if (firstRef.current) { + firstRef.current.style.flex = defaultFlexRef.current; } - function getSuggestionsForUnknownDocumentMode(token) { - return (0, _autocompleteUtils.hintList)(token, [ - { - label: "extend", - kind: _types.CompletionItemKind.Function, + store(defaultFlexRef.current); + setHiddenElementWithCallback(null); + } + dragBarContainer.addEventListener("dblclick", reset); + return () => { + dragBarContainer.removeEventListener("mousedown", handleMouseDown); + dragBarContainer.removeEventListener("dblclick", reset); + }; + }, [direction, setHiddenElementWithCallback, sizeThresholdFirst, sizeThresholdSecond, store]); + return React.useMemo(() => ({ + dragBarRef, + hiddenElement, + firstRef, + setHiddenElement, + secondRef + }), [hiddenElement, setHiddenElement]); + } + const DEFAULT_FLEX = 1; + const HIDE_FIRST = "hide-first"; + const HIDE_SECOND = "hide-second"; + const ToolbarButton = React.forwardRef(({ + label, + onClick, + ...props + }, ref) => { + const [error, setError] = React.useState(null); + const handleClick = React.useCallback(event => { + try { + onClick == null ? void 0 : onClick(event); + setError(null); + } catch (err) { + setError(err instanceof Error ? err : new Error(`Toolbar button click failed: ${err}`)); + } + }, [onClick]); + return /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx(UnStyledButton, { + ...props, + ref, + type: "button", + className: clsx.clsx("graphiql-toolbar-button", error && "error", props.className), + onClick: handleClick, + "aria-label": error ? error.message : label, + "aria-invalid": error ? "true" : props["aria-invalid"] + }) + }); + }); + ToolbarButton.displayName = "ToolbarButton"; + function ExecuteButton() { + const { + queryEditor, + setOperationName + } = useEditorContext({ + nonNull: true, + caller: ExecuteButton + }); + const { + isFetching, + isSubscribed, + operationName, + run, + stop + } = useExecutionContext({ + nonNull: true, + caller: ExecuteButton + }); + const operations = (queryEditor == null ? void 0 : queryEditor.operations) || []; + const hasOptions = operations.length > 1 && typeof operationName !== "string"; + const isRunning = isFetching || isSubscribed; + const label = `${isRunning ? "Stop" : "Execute"} query (Ctrl-Enter)`; + const buttonProps = { + type: "button", + className: "graphiql-execute-button", + children: isRunning ? /* @__PURE__ */jsxRuntime.jsx(StopIcon, {}) : /* @__PURE__ */jsxRuntime.jsx(PlayIcon, {}), + "aria-label": label + }; + return hasOptions && !isRunning ? /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { + children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { + ...buttonProps + }) + }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { + children: operations.map((operation, i) => { + const opName = operation.name ? operation.name.value : ``; + return /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Item, { + onSelect: () => { + var _a; + const selectedOperationName = (_a = operation.name) == null ? void 0 : _a.value; + if (queryEditor && selectedOperationName && selectedOperationName !== queryEditor.operationName) { + setOperationName(selectedOperationName); + } + run(); }, - ...executableCompletionItems, - ...typeSystemCompletionItems, - ]); - } - function getSuggestionsForExtensionDefinitions(token) { - return (0, _autocompleteUtils.hintList)( - token, - typeSystemCompletionItems - ); + children: opName + }, `${opName}-${i}`); + }) + })] + }) : /* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx("button", { + ...buttonProps, + onClick: () => { + if (isRunning) { + stop(); + } else { + run(); + } } - function getSuggestionsForFieldNames(token, typeInfo, options) { - var _a; - if (typeInfo.parentType) { - const { parentType } = typeInfo; - let fields = []; - if ("getFields" in parentType) { - fields = (0, _autocompleteUtils.objectValues)( - parentType.getFields() - ); - } - if ((0, _graphql.isCompositeType)(parentType)) { - fields.push(_graphql.TypeNameMetaFieldDef); - } - if ( - parentType === - ((_a = - options === null || options === void 0 - ? void 0 - : options.schema) === null || _a === void 0 - ? void 0 - : _a.getQueryType()) - ) { - fields.push( - _graphql.SchemaMetaFieldDef, - _graphql.TypeMetaFieldDef - ); + }) + }); + } + const ToolbarMenuRoot = ({ + button, + children, + label, + ...props + }) => /* @__PURE__ */jsxRuntime.jsxs(DropdownMenu, { + ...props, + children: [/* @__PURE__ */jsxRuntime.jsx(Tooltip, { + label, + children: /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Button, { + className: clsx.clsx("graphiql-un-styled graphiql-toolbar-menu", props.className), + "aria-label": label, + children: button + }) + }), /* @__PURE__ */jsxRuntime.jsx(DropdownMenu.Content, { + children + })] + }); + const ToolbarMenu = createComponentGroup(ToolbarMenuRoot, { + Item: DropdownMenu.Item + }); + exports.Argument = Argument; + exports.ArgumentIcon = ArgumentIcon; + exports.Button = Button$1; + exports.ButtonGroup = ButtonGroup; + exports.ChevronDownIcon = ChevronDownIcon; + exports.ChevronLeftIcon = ChevronLeftIcon; + exports.ChevronUpIcon = ChevronUpIcon; + exports.CloseIcon = CloseIcon; + exports.CopyIcon = CopyIcon; + exports.DOC_EXPLORER_PLUGIN = DOC_EXPLORER_PLUGIN; + exports.DefaultValue = DefaultValue; + exports.DeprecatedArgumentIcon = DeprecatedArgumentIcon; + exports.DeprecatedEnumValueIcon = DeprecatedEnumValueIcon; + exports.DeprecatedFieldIcon = DeprecatedFieldIcon; + exports.DeprecationReason = DeprecationReason; + exports.Dialog = Dialog; + exports.DialogRoot = DialogRoot; + exports.Directive = Directive; + exports.DirectiveIcon = DirectiveIcon; + exports.DocExplorer = DocExplorer; + exports.DocsFilledIcon = DocsFilledIcon; + exports.DocsIcon = DocsIcon; + exports.DropdownMenu = DropdownMenu; + exports.EditorContext = EditorContext; + exports.EditorContextProvider = EditorContextProvider; + exports.EnumValueIcon = EnumValueIcon; + exports.ExecuteButton = ExecuteButton; + exports.ExecutionContext = ExecutionContext; + exports.ExecutionContextProvider = ExecutionContextProvider; + exports.ExplorerContext = ExplorerContext; + exports.ExplorerContextProvider = ExplorerContextProvider; + exports.ExplorerSection = ExplorerSection; + exports.FieldDocumentation = FieldDocumentation; + exports.FieldIcon = FieldIcon; + exports.FieldLink = FieldLink; + exports.GraphiQLProvider = GraphiQLProvider; + exports.HISTORY_PLUGIN = HISTORY_PLUGIN; + exports.HeaderEditor = HeaderEditor; + exports.History = History; + exports.HistoryContext = HistoryContext; + exports.HistoryContextProvider = HistoryContextProvider; + exports.HistoryIcon = HistoryIcon; + exports.ImagePreview = ImagePreview; + exports.ImplementsIcon = ImplementsIcon; + exports.KeyboardShortcutIcon = KeyboardShortcutIcon; + exports.MagnifyingGlassIcon = MagnifyingGlassIcon; + exports.MarkdownContent = MarkdownContent; + exports.MergeIcon = MergeIcon; + exports.PenIcon = PenIcon; + exports.PlayIcon = PlayIcon; + exports.PluginContext = PluginContext; + exports.PluginContextProvider = PluginContextProvider; + exports.PlusIcon = PlusIcon; + exports.PrettifyIcon = PrettifyIcon; + exports.QueryEditor = QueryEditor; + exports.ReloadIcon = ReloadIcon; + exports.ResponseEditor = ResponseEditor; + exports.RootTypeIcon = RootTypeIcon; + exports.SchemaContext = SchemaContext; + exports.SchemaContextProvider = SchemaContextProvider; + exports.SchemaDocumentation = SchemaDocumentation; + exports.Search = Search; + exports.SettingsIcon = SettingsIcon; + exports.Spinner = Spinner; + exports.StarFilledIcon = StarFilledIcon; + exports.StarIcon = StarIcon; + exports.StopIcon = StopIcon; + exports.StorageContext = StorageContext; + exports.StorageContextProvider = StorageContextProvider; + exports.Tab = Tab; + exports.Tabs = Tabs; + exports.ToolbarButton = ToolbarButton; + exports.ToolbarMenu = ToolbarMenu; + exports.Tooltip = Tooltip; + exports.TooltipRoot = TooltipRoot; + exports.TrashIcon = TrashIcon; + exports.TypeDocumentation = TypeDocumentation; + exports.TypeIcon = TypeIcon; + exports.TypeLink = TypeLink; + exports.UnStyledButton = UnStyledButton; + exports.VariableEditor = VariableEditor; + exports.useAutoCompleteLeafs = useAutoCompleteLeafs; + exports.useCopyQuery = useCopyQuery; + exports.useDragResize = useDragResize; + exports.useEditorContext = useEditorContext; + exports.useEditorState = useEditorState; + exports.useExecutionContext = useExecutionContext; + exports.useExplorerContext = useExplorerContext; + exports.useHeaderEditor = useHeaderEditor; + exports.useHeadersEditorState = useHeadersEditorState; + exports.useHistoryContext = useHistoryContext; + exports.useMergeQuery = useMergeQuery; + exports.useOperationsEditorState = useOperationsEditorState; + exports.useOptimisticState = useOptimisticState; + exports.usePluginContext = usePluginContext; + exports.usePrettifyEditors = usePrettifyEditors; + exports.useQueryEditor = useQueryEditor; + exports.useResponseEditor = useResponseEditor; + exports.useSchemaContext = useSchemaContext; + exports.useStorageContext = useStorageContext; + exports.useTheme = useTheme; + exports.useVariableEditor = useVariableEditor; + exports.useVariablesEditorState = useVariablesEditorState; + + /***/ }), + + /***/ "../../graphiql-react/dist/info-addon.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/info-addon.cjs.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + codemirror.CodeMirror.defineOption("info", false, (cm, options, old) => { + if (old && old !== codemirror.CodeMirror.Init) { + const oldOnMouseOver = cm.state.info.onMouseOver; + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); + clearTimeout(cm.state.info.hoverTimeout); + delete cm.state.info; + } + if (options) { + const state = cm.state.info = createState(options); + state.onMouseOver = onMouseOver.bind(null, cm); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); + } + }); + function createState(options) { + return { + options: options instanceof Function ? { + render: options + } : options === true ? {} : options + }; + } + function getHoverTime(cm) { + const { + options + } = cm.state.info; + return (options === null || options === void 0 ? void 0 : options.hoverTime) || 500; + } + function onMouseOver(cm, e) { + const state = cm.state.info; + const target = e.target || e.srcElement; + if (!(target instanceof HTMLElement)) { + return; + } + if (target.nodeName !== "SPAN" || state.hoverTimeout !== void 0) { + return; + } + const box = target.getBoundingClientRect(); + const onMouseMove = function () { + clearTimeout(state.hoverTimeout); + state.hoverTimeout = setTimeout(onHover, hoverTime); + }; + const onMouseOut = function () { + codemirror.CodeMirror.off(document, "mousemove", onMouseMove); + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); + clearTimeout(state.hoverTimeout); + state.hoverTimeout = void 0; + }; + const onHover = function () { + codemirror.CodeMirror.off(document, "mousemove", onMouseMove); + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); + state.hoverTimeout = void 0; + onMouseHover(cm, box); + }; + const hoverTime = getHoverTime(cm); + state.hoverTimeout = setTimeout(onHover, hoverTime); + codemirror.CodeMirror.on(document, "mousemove", onMouseMove); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); + } + function onMouseHover(cm, box) { + const pos = cm.coordsChar({ + left: (box.left + box.right) / 2, + top: (box.top + box.bottom) / 2 + }, "window"); + const state = cm.state.info; + const { + options + } = state; + const render = options.render || cm.getHelper(pos, "info"); + if (render) { + const token = cm.getTokenAt(pos, true); + if (token) { + const info = render(token, options, cm, pos); + if (info) { + showPopup(cm, box, info); + } + } + } + } + function showPopup(cm, box, info) { + const popup = document.createElement("div"); + popup.className = "CodeMirror-info"; + popup.append(info); + document.body.append(popup); + const popupBox = popup.getBoundingClientRect(); + const popupStyle = window.getComputedStyle(popup); + const popupWidth = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight); + const popupHeight = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom); + let topPos = box.bottom; + if (popupHeight > window.innerHeight - box.bottom - 15 && box.top > window.innerHeight - box.bottom) { + topPos = box.top - popupHeight; + } + if (topPos < 0) { + topPos = box.bottom; + } + let leftPos = Math.max(0, window.innerWidth - popupWidth - 15); + if (leftPos > box.left) { + leftPos = box.left; + } + popup.style.opacity = "1"; + popup.style.top = topPos + "px"; + popup.style.left = leftPos + "px"; + let popupTimeout; + const onMouseOverPopup = function () { + clearTimeout(popupTimeout); + }; + const onMouseOut = function () { + clearTimeout(popupTimeout); + popupTimeout = setTimeout(hidePopup, 200); + }; + const hidePopup = function () { + codemirror.CodeMirror.off(popup, "mouseover", onMouseOverPopup); + codemirror.CodeMirror.off(popup, "mouseout", onMouseOut); + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", onMouseOut); + if (popup.style.opacity) { + popup.style.opacity = "0"; + setTimeout(() => { + if (popup.parentNode) { + popup.remove(); + } + }, 600); + } else if (popup.parentNode) { + popup.remove(); + } + }; + codemirror.CodeMirror.on(popup, "mouseover", onMouseOverPopup); + codemirror.CodeMirror.on(popup, "mouseout", onMouseOut); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", onMouseOut); + } + + /***/ }), + + /***/ "../../graphiql-react/dist/info.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/info.cjs.js ***! + \*********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); + __webpack_require__(/*! ./info-addon.cjs.js */ "../../graphiql-react/dist/info-addon.cjs.js"); + codemirror.CodeMirror.registerHelper("info", "graphql", (token, options) => { + var _a; + if (!options.schema || !token.state) { + return; + } + const { + kind, + step + } = token.state; + const typeInfo = SchemaReference.getTypeInfo(options.schema, token.state); + if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef || kind === "ObjectField" && step === 0 && typeInfo.fieldDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderField(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.fieldDef); + return into; + } + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderDirective(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.directiveDef); + return into; + } + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderArg(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.argDef); + return into; + } + if (kind === "EnumValue" && ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.description)) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderEnumValue(header, typeInfo, options); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.enumValue); + return into; + } + if (kind === "NamedType" && typeInfo.type && typeInfo.type.description) { + const header = document.createElement("div"); + header.className = "CodeMirror-info-header"; + renderType(header, typeInfo, options, typeInfo.type); + const into = document.createElement("div"); + into.append(header); + renderDescription(into, options, typeInfo.type); + return into; + } + }); + function renderField(into, typeInfo, options) { + renderQualifiedField(into, typeInfo, options); + renderTypeAnnotation(into, typeInfo, options, typeInfo.type); + } + function renderQualifiedField(into, typeInfo, options) { + var _a; + const fieldName = ((_a = typeInfo.fieldDef) === null || _a === void 0 ? void 0 : _a.name) || ""; + text(into, fieldName, "field-name", options, SchemaReference.getFieldReference(typeInfo)); + } + function renderDirective(into, typeInfo, options) { + var _a; + const name = "@" + (((_a = typeInfo.directiveDef) === null || _a === void 0 ? void 0 : _a.name) || ""); + text(into, name, "directive-name", options, SchemaReference.getDirectiveReference(typeInfo)); + } + function renderArg(into, typeInfo, options) { + var _a; + const name = ((_a = typeInfo.argDef) === null || _a === void 0 ? void 0 : _a.name) || ""; + text(into, name, "arg-name", options, SchemaReference.getArgumentReference(typeInfo)); + renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); + } + function renderEnumValue(into, typeInfo, options) { + var _a; + const name = ((_a = typeInfo.enumValue) === null || _a === void 0 ? void 0 : _a.name) || ""; + renderType(into, typeInfo, options, typeInfo.inputType); + text(into, "."); + text(into, name, "enum-value", options, SchemaReference.getEnumValueReference(typeInfo)); + } + function renderTypeAnnotation(into, typeInfo, options, t) { + const typeSpan = document.createElement("span"); + typeSpan.className = "type-name-pill"; + if (t instanceof graphql.GraphQLNonNull) { + renderType(typeSpan, typeInfo, options, t.ofType); + text(typeSpan, "!"); + } else if (t instanceof graphql.GraphQLList) { + text(typeSpan, "["); + renderType(typeSpan, typeInfo, options, t.ofType); + text(typeSpan, "]"); + } else { + text(typeSpan, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); + } + into.append(typeSpan); + } + function renderType(into, typeInfo, options, t) { + if (t instanceof graphql.GraphQLNonNull) { + renderType(into, typeInfo, options, t.ofType); + text(into, "!"); + } else if (t instanceof graphql.GraphQLList) { + text(into, "["); + renderType(into, typeInfo, options, t.ofType); + text(into, "]"); + } else { + text(into, (t === null || t === void 0 ? void 0 : t.name) || "", "type-name", options, SchemaReference.getTypeReference(typeInfo, t)); + } + } + function renderDescription(into, options, def) { + const { + description + } = def; + if (description) { + const descriptionDiv = document.createElement("div"); + descriptionDiv.className = "info-description"; + if (options.renderDescription) { + descriptionDiv.innerHTML = options.renderDescription(description); + } else { + descriptionDiv.append(document.createTextNode(description)); + } + into.append(descriptionDiv); + } + renderDeprecation(into, options, def); + } + function renderDeprecation(into, options, def) { + const reason = def.deprecationReason; + if (reason) { + const deprecationDiv = document.createElement("div"); + deprecationDiv.className = "info-deprecation"; + into.append(deprecationDiv); + const label = document.createElement("span"); + label.className = "info-deprecation-label"; + label.append(document.createTextNode("Deprecated")); + deprecationDiv.append(label); + const reasonDiv = document.createElement("div"); + reasonDiv.className = "info-deprecation-reason"; + if (options.renderDescription) { + reasonDiv.innerHTML = options.renderDescription(reason); + } else { + reasonDiv.append(document.createTextNode(reason)); + } + deprecationDiv.append(reasonDiv); + } + } + function text(into, content, className = "", options = { + onClick: null + }, ref = null) { + if (className) { + const { + onClick + } = options; + let node; + if (onClick) { + node = document.createElement("a"); + node.href = "javascript:void 0"; + node.addEventListener("click", e => { + e.preventDefault(); + onClick(ref, e); + }); + } else { + node = document.createElement("span"); + } + node.className = className; + node.append(document.createTextNode(content)); + into.append(node); + } else { + into.append(document.createTextNode(content)); + } + } + + /***/ }), + + /***/ "../../graphiql-react/dist/javascript.cjs.js": + /*!***************************************************!*\ + !*** ../../graphiql-react/dist/javascript.cjs.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - return (0, _autocompleteUtils.hintList)( - token, - fields.map((field, index) => { - var _a; - const suggestion = { - sortText: String(index) + field.name, - label: field.name, - detail: String(field.type), - documentation: - (_a = field.description) !== null && _a !== void 0 - ? _a - : undefined, - deprecated: Boolean(field.deprecationReason), - isDeprecated: Boolean(field.deprecationReason), - deprecationReason: field.deprecationReason, - kind: _types.CompletionItemKind.Field, - labelDetails: { - detail: " " + field.type.toString(), - }, - type: field.type, - }; - if ( - options === null || options === void 0 - ? void 0 - : options.fillLeafsOnComplete - ) { - suggestion.insertText = (0, - _autocompleteUtils.getFieldInsertText)(field); - if (!suggestion.insertText) { - suggestion.insertText = (0, - _autocompleteUtils.getInsertText)( - field.name, - field.type, - field.name + (token.state.needsAdvance ? "" : "\n") - ); - } - if (suggestion.insertText) { - suggestion.insertTextFormat = - _types.InsertTextFormat.Snippet; - suggestion.insertTextMode = - _vscodeLanguageserverTypes.InsertTextMode.adjustIndentation; - suggestion.command = SuggestionCommand; - } - } - return suggestion; - }) - ); } - return []; } - function getSuggestionsForInputValues( - token, - typeInfo, - queryText, - schema - ) { - const namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType); - const queryVariables = getVariableCompletions( - queryText, - schema, - token - ).filter( - (v) => - v.detail === - (namedInputType === null || namedInputType === void 0 - ? void 0 - : namedInputType.name) - ); - if (namedInputType instanceof _graphql.GraphQLEnumType) { - const values = namedInputType.getValues(); - return (0, _autocompleteUtils.hintList)( - token, - values - .map((value) => { - var _a; - return { - label: value.name, - detail: String(namedInputType), - documentation: - (_a = value.description) !== null && _a !== void 0 - ? _a - : undefined, - deprecated: Boolean(value.deprecationReason), - isDeprecated: Boolean(value.deprecationReason), - deprecationReason: value.deprecationReason, - kind: _types.CompletionItemKind.EnumMember, - type: namedInputType, - }; - }) - .concat(queryVariables) - ); + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var javascript$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + CodeMirror.defineMode("javascript", function (config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var trackScope = parserConfig.trackScope !== false; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + var keywords = function () { + function kw(type2) { + return { + type: type2, + style: "keyword" + }; } - if (namedInputType === _graphql.GraphQLBoolean) { - return (0, _autocompleteUtils.hintList)( - token, - queryVariables.concat([ - { - label: "true", - detail: String(_graphql.GraphQLBoolean), - documentation: "Not false.", - kind: _types.CompletionItemKind.Variable, - type: _graphql.GraphQLBoolean, - }, - { - label: "false", - detail: String(_graphql.GraphQLBoolean), - documentation: "Not true.", - kind: _types.CompletionItemKind.Variable, - type: _graphql.GraphQLBoolean, - }, - ]) - ); + var A = kw("keyword a"), + B = kw("keyword b"), + C = kw("keyword c"), + D = kw("keyword d"); + var operator = kw("operator"), + atom = { + type: "atom", + style: "atom" + }; + return { + "if": kw("if"), + "while": A, + "with": A, + "else": B, + "do": B, + "try": B, + "finally": B, + "return": D, + "break": D, + "continue": D, + "new": kw("new"), + "delete": C, + "void": C, + "throw": C, + "debugger": kw("debugger"), + "var": kw("var"), + "const": kw("var"), + "let": kw("var"), + "function": kw("function"), + "catch": kw("catch"), + "for": kw("for"), + "switch": kw("switch"), + "case": kw("case"), + "default": kw("default"), + "in": operator, + "typeof": operator, + "instanceof": operator, + "true": atom, + "false": atom, + "null": atom, + "undefined": atom, + "NaN": atom, + "Infinity": atom, + "this": kw("this"), + "class": kw("class"), + "super": kw("atom"), + "yield": C, + "export": kw("export"), + "import": kw("import"), + "extends": C, + "await": C + }; + }(); + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + function readRegexp(stream) { + var escaped = false, + next, + inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true;else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + var type, content; + function ret(tp, style, cont2) { + type = tp; + content = cont2; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#" && stream.peek() == "!") { + stream.skipToEnd(); + return ret("meta", "meta"); + } else if (ch == "#" && stream.eatWhile(wordRE)) { + return ret("variable", "property"); + } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start))) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("="); + } else if (/[<>*+\-|&?]/.test(ch)) { + stream.eat(ch); + if (ch == ">") stream.eat(ch); + } + } + if (ch == "?" && stream.eat(".")) return ret("."); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(); + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word]; + return ret(kw.type, kw.style, word); + } + if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word); + } + return ret("variable", "variable", word); + } + } + function tokenString(quote) { + return function (stream, state) { + var escaped = false, + next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)) { + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = ch == "*"; } - return queryVariables; - } - function getSuggestionsForImplements( - token, - tokenState, - schema, - documentText, - typeInfo - ) { - if (tokenState.needsSeparator) { - return []; - } - const typeMap = schema.getTypeMap(); - const schemaInterfaces = (0, _autocompleteUtils.objectValues)( - typeMap - ).filter(_graphql.isInterfaceType); - const schemaInterfaceNames = schemaInterfaces.map(({ name }) => name); - const inlineInterfaces = new Set(); - (0, _parser.runOnlineParser)(documentText, (_, state) => { - var _a, _b, _c, _d, _e; - if (state.name) { - if ( - state.kind === _parser.RuleKinds.INTERFACE_DEF && - !schemaInterfaceNames.includes(state.name) - ) { - inlineInterfaces.add(state.name); + return ret("comment", "comment"); + } + function tokenQuasi(stream, state) { + var escaped = false, + next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + var brackets = "([{}])"; + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + if (isTS) { + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)); + if (m) arrow = m.index; + } + var depth = 0, + sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { + ++pos; + break; } - if ( - state.kind === _parser.RuleKinds.NAMED_TYPE && - ((_a = state.prevState) === null || _a === void 0 - ? void 0 - : _a.kind) === _parser.RuleKinds.IMPLEMENTS - ) { - if (typeInfo.interfaceDef) { - const existingType = - (_b = typeInfo.interfaceDef) === null || _b === void 0 - ? void 0 - : _b - .getInterfaces() - .find(({ name }) => name === state.name); - if (existingType) { - return; - } - const type = schema.getType(state.name); - const interfaceConfig = - (_c = typeInfo.interfaceDef) === null || _c === void 0 - ? void 0 - : _c.toConfig(); - typeInfo.interfaceDef = new _graphql.GraphQLInterfaceType( - Object.assign(Object.assign({}, interfaceConfig), { - interfaces: [ - ...interfaceConfig.interfaces, - type || - new _graphql.GraphQLInterfaceType({ - name: state.name, - fields: {}, - }), - ], - }) - ); - } else if (typeInfo.objectTypeDef) { - const existingType = - (_d = typeInfo.objectTypeDef) === null || _d === void 0 - ? void 0 - : _d - .getInterfaces() - .find(({ name }) => name === state.name); - if (existingType) { - return; - } - const type = schema.getType(state.name); - const objectTypeConfig = - (_e = typeInfo.objectTypeDef) === null || _e === void 0 - ? void 0 - : _e.toConfig(); - typeInfo.objectTypeDef = new _graphql.GraphQLObjectType( - Object.assign(Object.assign({}, objectTypeConfig), { - interfaces: [ - ...objectTypeConfig.interfaces, - type || - new _graphql.GraphQLInterfaceType({ - name: state.name, - fields: {}, - }), - ], - }) - ); + if (--depth == 0) { + if (ch == "(") sawSomething = true; + break; + } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (;; --pos) { + if (pos == 0) return; + var next = stream.string.charAt(pos - 1); + if (next == ch && stream.string.charAt(pos - 2) != "\\") { + pos--; + break; } } + } else if (sawSomething && !depth) { + ++pos; + break; } - }); - const currentTypeToExtend = - typeInfo.interfaceDef || typeInfo.objectTypeDef; - const siblingInterfaces = - (currentTypeToExtend === null || currentTypeToExtend === void 0 - ? void 0 - : currentTypeToExtend.getInterfaces()) || []; - const siblingInterfaceNames = siblingInterfaces.map( - ({ name }) => name - ); - const possibleInterfaces = schemaInterfaces - .concat( - [...inlineInterfaces].map((name) => ({ - name, - })) - ) - .filter( - ({ name }) => - name !== - (currentTypeToExtend === null || - currentTypeToExtend === void 0 - ? void 0 - : currentTypeToExtend.name) && - !siblingInterfaceNames.includes(name) - ); - return (0, _autocompleteUtils.hintList)( - token, - possibleInterfaces.map((type) => { - const result = { - label: type.name, - kind: _types.CompletionItemKind.Interface, - type, - }; - if ( - type === null || type === void 0 ? void 0 : type.description - ) { - result.documentation = type.description; - } - return result; - }) - ); + } + if (sawSomething && !depth) state.fatArrowAt = pos; } - function getSuggestionsForFragmentTypeConditions( - token, - typeInfo, - schema, - _kind - ) { - let possibleTypes; - if (typeInfo.parentType) { - if ((0, _graphql.isAbstractType)(typeInfo.parentType)) { - const abstractType = (0, _graphql.assertAbstractType)( - typeInfo.parentType - ); - const possibleObjTypes = schema.getPossibleTypes(abstractType); - const possibleIfaceMap = Object.create(null); - for (const type of possibleObjTypes) { - for (const iface of type.getInterfaces()) { - possibleIfaceMap[iface.name] = iface; - } + var atomicTypes = { + "atom": true, + "number": true, + "variable": true, + "string": true, + "regexp": true, + "this": true, + "import": true, + "jsonld-keyword": true + }; + function JSLexical(indented, column, type2, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type2; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + function inScope(state, varname) { + if (!trackScope) return false; + for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; + for (var cx2 = state.context; cx2; cx2 = cx2.prev) { + for (var v = cx2.vars; v; v = v.next) if (v.name == varname) return true; + } + } + function parseJS(state, style, type2, content2, stream) { + var cc = state.cc; + cx.state = state; + cx.stream = stream; + cx.marked = null, cx.cc = cc; + cx.style = style; + if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; + while (true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type2, content2)) { + while (cc.length && cc[cc.length - 1].lex) cc.pop()(); + if (cx.marked) return cx.marked; + if (type2 == "variable" && inScope(state, content2)) return "variable-2"; + return style; + } + } + } + var cx = { + state: null, + column: null, + marked: null, + cc: null + }; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) if (v.name == name) return true; + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (!trackScope) return; + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + var newContext = registerVarScoped(varname, state.context); + if (newContext != null) { + state.context = newContext; + return; } - possibleTypes = possibleObjTypes.concat( - (0, _autocompleteUtils.objectValues)(possibleIfaceMap) - ); + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars); + return; + } + } + if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars); + } + function registerVarScoped(varname, context) { + if (!context) { + return null; + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev); + if (!inner) return null; + if (inner == context.prev) return context; + return new Context(inner, context.vars, true); + } else if (inList(varname, context.vars)) { + return context; + } else { + return new Context(context.prev, new Var(varname, context.vars), false); + } + } + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"; + } + function Context(prev, vars, block2) { + this.prev = prev; + this.vars = vars; + this.block = block2; + } + function Var(name, next) { + this.name = name; + this.next = next; + } + var defaultVars = new Var("this", new Var("arguments", null)); + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false); + cx.state.localVars = defaultVars; + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true); + cx.state.localVars = null; + } + pushcontext.lex = pushblockcontext.lex = true; + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + popcontext.lex = true; + function pushlex(type2, info) { + var result = function () { + var state = cx.state, + indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented;else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type2, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + function expect(wanted) { + function exp(type2) { + if (type2 == wanted) return cont();else if (wanted == ";" || type2 == "}" || type2 == ")" || type2 == "]") return pass();else return cont(exp); + } + return exp; + } + function statement(type2, value) { + if (type2 == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type2 == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type2 == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type2 == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type2 == "debugger") return cont(expect(";")); + if (type2 == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type2 == ";") return cont(); + if (type2 == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type2 == "function") return cont(functiondef); + if (type2 == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form", type2 == "class" ? type2 : value), className, poplex); + } + if (type2 == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword"; + return cont(statement); + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword"; + if (value == "enum") return cont(enumdef);else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex); + } else if (isTS && value == "namespace") { + cx.marked = "keyword"; + return cont(pushlex("form"), expression, statement, poplex); + } else if (isTS && value == "abstract") { + cx.marked = "keyword"; + return cont(statement); } else { - possibleTypes = [typeInfo.parentType]; - } - } else { - const typeMap = schema.getTypeMap(); - possibleTypes = (0, _autocompleteUtils.objectValues)( - typeMap - ).filter( - (type) => - (0, _graphql.isCompositeType)(type) && - !type.name.startsWith("__") - ); + return cont(pushlex("stat"), maybelabel); + } + } + if (type2 == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); + if (type2 == "case") return cont(expression, expect(":")); + if (type2 == "default") return cont(expect(":")); + if (type2 == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type2 == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type2 == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type2 == "async") return cont(statement); + if (value == "@") return cont(expression, statement); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type2) { + if (type2 == "(") return cont(funarg, expect(")")); + } + function expression(type2, value) { + return expressionInner(type2, value, false); + } + function expressionNoComma(type2, value) { + return expressionInner(type2, value, true); + } + function parenExpr(type2) { + if (type2 != "(") return pass(); + return cont(pushlex(")"), maybeexpression, expect(")"), poplex); + } + function expressionInner(type2, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);else if (type2 == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type2)) return cont(maybeop); + if (type2 == "function") return cont(functiondef, maybeop); + if (type2 == "class" || isTS && value == "interface") { + cx.marked = "keyword"; + return cont(pushlex("form"), classExpression, poplex); + } + if (type2 == "keyword c" || type2 == "async") return cont(noComma ? expressionNoComma : expression); + if (type2 == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type2 == "operator" || type2 == "spread") return cont(noComma ? expressionNoComma : expression); + if (type2 == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type2 == "{") return contCommasep(objprop, "}", null, maybeop); + if (type2 == "quasi") return pass(quasi, maybeop); + if (type2 == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type2) { + if (type2.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + function maybeoperatorComma(type2, value) { + if (type2 == ",") return cont(maybeexpression); + return maybeoperatorNoComma(type2, value, false); + } + function maybeoperatorNoComma(type2, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type2 == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type2 == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type2 == "quasi") { + return pass(quasi, me); + } + if (type2 == ";") return; + if (type2 == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type2 == ".") return cont(property, me); + if (type2 == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { + cx.marked = "keyword"; + return cont(typeexpr, me); + } + if (type2 == "regexp") { + cx.state.lastType = cx.marked = "operator"; + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1); + return cont(expr); + } + } + function quasi(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(maybeexpression, continueQuasi); + } + function continueQuasi(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expression); + } + function arrowBodyNoComma(type2) { + findFatArrow(cx.stream, cx.state); + return pass(type2 == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function (type2) { + if (type2 == ".") return cont(noComma ? targetNoComma : target);else if (type2 == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma);else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorComma); + } + } + function targetNoComma(_, value) { + if (value == "target") { + cx.marked = "keyword"; + return cont(maybeoperatorNoComma); + } + } + function maybelabel(type2) { + if (type2 == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type2) { + if (type2 == "variable") { + cx.marked = "property"; + return cont(); + } + } + function objprop(type2, value) { + if (type2 == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + var m; + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length; + return cont(afterprop); + } else if (type2 == "number" || type2 == "string") { + cx.marked = jsonldMode ? "property" : cx.style + " property"; + return cont(afterprop); + } else if (type2 == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type2 == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type2 == ":") { + return pass(afterprop); + } + } + function getterSetter(type2) { + if (type2 != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type2) { + if (type2 == ":") return cont(expressionNoComma); + if (type2 == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type2, value) { + if (sep ? sep.indexOf(type2) > -1 : type2 == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function (type3, value2) { + if (type3 == end || value2 == end) return pass(); + return pass(what); + }, proceed); + } + if (type2 == end || value == end) return cont(); + if (sep && sep.indexOf(";") > -1) return pass(what); + return cont(expect(end)); + } + return function (type2, value) { + if (type2 == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type2) { + if (type2 == "}") return cont(); + return pass(statement, block); + } + function maybetype(type2, value) { + if (isTS) { + if (type2 == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); } - return (0, _autocompleteUtils.hintList)( - token, - possibleTypes.map((type) => { - const namedType = (0, _graphql.getNamedType)(type); - return { - label: String(type), - documentation: - (namedType === null || namedType === void 0 - ? void 0 - : namedType.description) || "", - kind: _types.CompletionItemKind.Field, - }; - }) - ); } - function getSuggestionsForFragmentSpread( - token, - typeInfo, - schema, - queryText, - fragmentDefs - ) { - if (!queryText) { - return []; - } - const typeMap = schema.getTypeMap(); - const defState = (0, _parser.getDefinitionState)(token.state); - const fragments = getFragmentDefinitions(queryText); - if (fragmentDefs && fragmentDefs.length > 0) { - fragments.push(...fragmentDefs); - } - const relevantFrags = fragments.filter( - (frag) => - typeMap[frag.typeCondition.name.value] && - !( - defState && - defState.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && - defState.name === frag.name.value - ) && - (0, _graphql.isCompositeType)(typeInfo.parentType) && - (0, _graphql.isCompositeType)( - typeMap[frag.typeCondition.name.value] - ) && - (0, _graphql.doTypesOverlap)( - schema, - typeInfo.parentType, - typeMap[frag.typeCondition.name.value] - ) - ); - return (0, _autocompleteUtils.hintList)( - token, - relevantFrags.map((frag) => ({ - label: frag.name.value, - detail: String(typeMap[frag.typeCondition.name.value]), - documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, - labelDetails: { - detail: `fragment ${frag.name.value} on ${frag.typeCondition.name.value}`, - }, - kind: _types.CompletionItemKind.Field, - type: typeMap[frag.typeCondition.name.value], - })) - ); + function maybetypeOrIn(type2, value) { + if (isTS && (type2 == ":" || value == "in")) return cont(typeexpr); } - const getParentDefinition = (state, kind) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - if ( - ((_a = state.prevState) === null || _a === void 0 - ? void 0 - : _a.kind) === kind - ) { - return state.prevState; - } - if ( - ((_c = - (_b = state.prevState) === null || _b === void 0 - ? void 0 - : _b.prevState) === null || _c === void 0 - ? void 0 - : _c.kind) === kind - ) { - return state.prevState.prevState; - } - if ( - ((_f = - (_e = - (_d = state.prevState) === null || _d === void 0 - ? void 0 - : _d.prevState) === null || _e === void 0 - ? void 0 - : _e.prevState) === null || _f === void 0 - ? void 0 - : _f.kind) === kind - ) { - return state.prevState.prevState.prevState; - } - if ( - ((_k = - (_j = - (_h = - (_g = state.prevState) === null || _g === void 0 - ? void 0 - : _g.prevState) === null || _h === void 0 - ? void 0 - : _h.prevState) === null || _j === void 0 - ? void 0 - : _j.prevState) === null || _k === void 0 - ? void 0 - : _k.kind) === kind - ) { - return state.prevState.prevState.prevState.prevState; + function mayberettype(type2) { + if (isTS && type2 == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr);else return cont(typeexpr); } - }; - function getVariableCompletions(queryText, schema, token) { - let variableName = null; - let variableType; - const definitions = Object.create({}); - (0, _parser.runOnlineParser)(queryText, (_, state) => { - var _a; - if ( - (state === null || state === void 0 ? void 0 : state.kind) === - _parser.RuleKinds.VARIABLE && - state.name - ) { - variableName = state.name; - } - if ( - (state === null || state === void 0 ? void 0 : state.kind) === - _parser.RuleKinds.NAMED_TYPE && - variableName - ) { - const parentDefinition = getParentDefinition( - state, - _parser.RuleKinds.TYPE - ); - if ( - parentDefinition === null || parentDefinition === void 0 - ? void 0 - : parentDefinition.type - ) { - variableType = schema.getType( - parentDefinition === null || parentDefinition === void 0 - ? void 0 - : parentDefinition.type - ); - } - } - if (variableName && variableType && !definitions[variableName]) { - const replaceString = - token.string === "$" || - ((_a = - token === null || token === void 0 ? void 0 : token.state) === - null || _a === void 0 - ? void 0 - : _a.kind) === "Variable" - ? variableName - : "$" + variableName; - definitions[variableName] = { - detail: variableType.toString(), - insertText: replaceString, - label: "$" + variableName, - rawInsert: replaceString, - type: variableType, - kind: _types.CompletionItemKind.Variable, - }; - variableName = null; - variableType = null; - } - }); - return (0, _autocompleteUtils.objectValues)(definitions); - } - function getFragmentDefinitions(queryText) { - const fragmentDefs = []; - (0, _parser.runOnlineParser)(queryText, (_, state) => { - if ( - state.kind === _parser.RuleKinds.FRAGMENT_DEFINITION && - state.name && - state.type - ) { - fragmentDefs.push({ - kind: _parser.RuleKinds.FRAGMENT_DEFINITION, - name: { - kind: _graphql.Kind.NAME, - value: state.name, - }, - selectionSet: { - kind: _parser.RuleKinds.SELECTION_SET, - selections: [], - }, - typeCondition: { - kind: _parser.RuleKinds.NAMED_TYPE, - name: { - kind: _graphql.Kind.NAME, - value: state.type, - }, - }, - }); - } - }); - return fragmentDefs; - } - function getSuggestionsForVariableDefinition(token, schema, _kind) { - const inputTypeMap = schema.getTypeMap(); - const inputTypes = (0, _autocompleteUtils.objectValues)( - inputTypeMap - ).filter(_graphql.isInputType); - return (0, _autocompleteUtils.hintList)( - token, - inputTypes.map((type) => ({ - label: type.name, - documentation: - (type === null || type === void 0 - ? void 0 - : type.description) || "", - kind: _types.CompletionItemKind.Variable, - })) - ); } - function getSuggestionsForDirective(token, state, schema, _kind) { - var _a; - if ( - (_a = state.prevState) === null || _a === void 0 ? void 0 : _a.kind - ) { - const directives = schema - .getDirectives() - .filter((directive) => - canUseDirective(state.prevState, directive) - ); - return (0, _autocompleteUtils.hintList)( - token, - directives.map((directive) => ({ - label: directive.name, - documentation: - (directive === null || directive === void 0 - ? void 0 - : directive.description) || "", - kind: _types.CompletionItemKind.Function, - })) - ); + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword"; + return cont(); + } + } + function typeexpr(type2, value) { + if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { + cx.marked = "keyword"; + return cont(value == "typeof" ? expressionNoComma : typeexpr); } - return []; - } - function getSuggestionsForDirectiveArguments( - token, - state, - schema, - _kind - ) { - const directive = schema - .getDirectives() - .find((d) => d.name === state.name); - return (0, _autocompleteUtils.hintList)( - token, - (directive === null || directive === void 0 - ? void 0 - : directive.args.map((arg) => ({ - label: arg.name, - documentation: arg.description || "", - kind: _types.CompletionItemKind.Field, - }))) || [] - ); + if (type2 == "variable" || value == "void") { + cx.marked = "type"; + return cont(afterType); + } + if (value == "|" || value == "&") return cont(typeexpr); + if (type2 == "string" || type2 == "number" || type2 == "atom") return cont(afterType); + if (type2 == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType); + if (type2 == "{") return cont(pushlex("}"), typeprops, poplex, afterType); + if (type2 == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType); + if (type2 == "<") return cont(commasep(typeexpr, ">"), typeexpr); + if (type2 == "quasi") { + return pass(quasiType, afterType); + } + } + function maybeReturnType(type2) { + if (type2 == "=>") return cont(typeexpr); } - function canUseDirective(state, directive) { - if (!(state === null || state === void 0 ? void 0 : state.kind)) { - return false; + function typeprops(type2) { + if (type2.match(/[\}\)\]]/)) return cont(); + if (type2 == "," || type2 == ";") return cont(typeprops); + return pass(typeprop, typeprops); + } + function typeprop(type2, value) { + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(typeprop); + } else if (value == "?" || type2 == "number" || type2 == "string") { + return cont(typeprop); + } else if (type2 == ":") { + return cont(typeexpr); + } else if (type2 == "[") { + return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop); + } else if (type2 == "(") { + return pass(functiondecl, typeprop); + } else if (!type2.match(/[;\}\)\],]/)) { + return cont(); } - const { kind, prevState } = state; - const { locations } = directive; - switch (kind) { - case _parser.RuleKinds.QUERY: - return locations.includes(_graphql.DirectiveLocation.QUERY); - case _parser.RuleKinds.MUTATION: - return locations.includes(_graphql.DirectiveLocation.MUTATION); - case _parser.RuleKinds.SUBSCRIPTION: - return locations.includes( - _graphql.DirectiveLocation.SUBSCRIPTION - ); - case _parser.RuleKinds.FIELD: - case _parser.RuleKinds.ALIASED_FIELD: - return locations.includes(_graphql.DirectiveLocation.FIELD); - case _parser.RuleKinds.FRAGMENT_DEFINITION: - return locations.includes( - _graphql.DirectiveLocation.FRAGMENT_DEFINITION - ); - case _parser.RuleKinds.FRAGMENT_SPREAD: - return locations.includes( - _graphql.DirectiveLocation.FRAGMENT_SPREAD - ); - case _parser.RuleKinds.INLINE_FRAGMENT: - return locations.includes( - _graphql.DirectiveLocation.INLINE_FRAGMENT - ); - case _parser.RuleKinds.SCHEMA_DEF: - return locations.includes(_graphql.DirectiveLocation.SCHEMA); - case _parser.RuleKinds.SCALAR_DEF: - return locations.includes(_graphql.DirectiveLocation.SCALAR); - case _parser.RuleKinds.OBJECT_TYPE_DEF: - return locations.includes(_graphql.DirectiveLocation.OBJECT); - case _parser.RuleKinds.FIELD_DEF: - return locations.includes( - _graphql.DirectiveLocation.FIELD_DEFINITION - ); - case _parser.RuleKinds.INTERFACE_DEF: - return locations.includes(_graphql.DirectiveLocation.INTERFACE); - case _parser.RuleKinds.UNION_DEF: - return locations.includes(_graphql.DirectiveLocation.UNION); - case _parser.RuleKinds.ENUM_DEF: - return locations.includes(_graphql.DirectiveLocation.ENUM); - case _parser.RuleKinds.ENUM_VALUE: - return locations.includes(_graphql.DirectiveLocation.ENUM_VALUE); - case _parser.RuleKinds.INPUT_DEF: - return locations.includes( - _graphql.DirectiveLocation.INPUT_OBJECT - ); - case _parser.RuleKinds.INPUT_VALUE_DEF: - const prevStateKind = - prevState === null || prevState === void 0 - ? void 0 - : prevState.kind; - switch (prevStateKind) { - case _parser.RuleKinds.ARGUMENTS_DEF: - return locations.includes( - _graphql.DirectiveLocation.ARGUMENT_DEFINITION - ); - case _parser.RuleKinds.INPUT_DEF: - return locations.includes( - _graphql.DirectiveLocation.INPUT_FIELD_DEFINITION - ); - } + } + function quasiType(type2, value) { + if (type2 != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasiType); + return cont(typeexpr, continueQuasiType); + } + function continueQuasiType(type2) { + if (type2 == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasiType); + } + } + function typearg(type2, value) { + if (type2 == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg); + if (type2 == ":") return cont(typeexpr); + if (type2 == "spread") return cont(typearg); + return pass(typeexpr); + } + function afterType(type2, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + if (value == "|" || type2 == "." || value == "&") return cont(typeexpr); + if (type2 == "[") return cont(typeexpr, expect("]"), afterType); + if (value == "extends" || value == "implements") { + cx.marked = "keyword"; + return cont(typeexpr); + } + if (value == "?") return cont(typeexpr, expect(":"), typeexpr); + } + function maybeTypeArgs(_, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType); + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault); + } + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr); + } + function vardef(_, value) { + if (value == "enum") { + cx.marked = "keyword"; + return cont(enumdef); + } + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type2, value) { + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(pattern); + } + if (type2 == "variable") { + register(value); + return cont(); + } + if (type2 == "spread") return cont(pattern); + if (type2 == "[") return contCommasep(eltpattern, "]"); + if (type2 == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type2, value) { + if (type2 == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type2 == "variable") cx.marked = "property"; + if (type2 == "spread") return cont(pattern); + if (type2 == "}") return pass(); + if (type2 == "[") return cont(expression, expect("]"), expect(":"), proppattern); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign); + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type2) { + if (type2 == ",") return cont(vardef); + } + function maybeelse(type2, value) { + if (type2 == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type2, value) { + if (value == "await") return cont(forspec); + if (type2 == "(") return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type2) { + if (type2 == "var") return cont(vardef, forspec2); + if (type2 == "variable") return cont(forspec2); + return pass(forspec2); + } + function forspec2(type2, value) { + if (type2 == ")") return cont(); + if (type2 == ";") return cont(forspec2); + if (value == "in" || value == "of") { + cx.marked = "keyword"; + return cont(expression, forspec2); + } + return pass(expression, forspec2); + } + function functiondef(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondef); + } + if (type2 == "variable") { + register(value); + return cont(functiondef); + } + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef); + } + function functiondecl(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(functiondecl); + } + if (type2 == "variable") { + register(value); + return cont(functiondecl); + } + if (type2 == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl); + } + function typename(type2, value) { + if (type2 == "keyword" || type2 == "variable") { + cx.marked = "type"; + return cont(typename); + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex); + } + } + function funarg(type2, value) { + if (value == "@") cont(expression, funarg); + if (type2 == "spread") return cont(funarg); + if (isTS && isModifier(value)) { + cx.marked = "keyword"; + return cont(funarg); + } + if (isTS && type2 == "this") return cont(maybetype, maybeAssign); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type2, value) { + if (type2 == "variable") return className(type2, value); + return classNameAfter(type2, value); + } + function className(type2, value) { + if (type2 == "variable") { + register(value); + return cont(classNameAfter); + } + } + function classNameAfter(type2, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter); + if (value == "extends" || value == "implements" || isTS && type2 == ",") { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type2 == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type2, value) { + if (type2 == "async" || type2 == "variable" && (value == "static" || value == "get" || value == "set" || isTS && isModifier(value)) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type2 == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(classfield, classBody); + } + if (type2 == "number" || type2 == "string") return cont(classfield, classBody); + if (type2 == "[") return cont(expression, maybetype, expect("]"), classfield, classBody); + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type2 == "(") return pass(functiondecl, classBody); + if (type2 == ";" || type2 == ",") return cont(classBody); + if (type2 == "}") return cont(); + if (value == "@") return cont(expression, classBody); + } + function classfield(type2, value) { + if (value == "!") return cont(classfield); + if (value == "?") return cont(classfield); + if (type2 == ":") return cont(typeexpr, maybeAssign); + if (value == "=") return cont(expressionNoComma); + var context = cx.state.lexical.prev, + isInterface = context && context.info == "interface"; + return pass(isInterface ? functiondecl : functiondef); + } + function afterExport(type2, value) { + if (value == "*") { + cx.marked = "keyword"; + return cont(maybeFrom, expect(";")); + } + if (value == "default") { + cx.marked = "keyword"; + return cont(expression, expect(";")); + } + if (type2 == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type2, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(expect("variable")); + } + if (type2 == "variable") return pass(expressionNoComma, exportField); + } + function afterImport(type2) { + if (type2 == "string") return cont(); + if (type2 == "(") return pass(expression); + if (type2 == ".") return pass(maybeoperatorComma); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type2, value) { + if (type2 == "{") return contCommasep(importSpec, "}"); + if (type2 == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type2) { + if (type2 == ",") return cont(importSpec, maybeMoreImports); + } + function maybeAs(_type, value) { + if (value == "as") { + cx.marked = "keyword"; + return cont(importSpec); + } + } + function maybeFrom(_type, value) { + if (value == "from") { + cx.marked = "keyword"; + return cont(expression); + } + } + function arrayLiteral(type2) { + if (type2 == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex); + } + function enummember() { + return pass(pattern, maybeAssign); + } + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); + } + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))); + } + return { + startState: function (basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; + return state; + }, + token: function (stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + indent: function (state, textAfter) { + if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), + lexical = state.lexical, + top; + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev;else if (c != maybeelse && c != popcontext) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || (top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter))) lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; + var type2 = lexical.type, + closing = firstChar == type2; + if (type2 == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);else if (type2 == "form" && firstChar == "{") return lexical.indented;else if (type2 == "form") return lexical.indented + indentUnit;else if (type2 == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);else if (lexical.align) return lexical.column + (closing ? 0 : 1);else return lexical.indented + (closing ? 0 : indentUnit); + }, + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + helperType: jsonMode ? "json" : "javascript", + jsonldMode, + jsonMode, + expressionAllowed, + skipExpression: function (state) { + parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)); + } + }; + }); + CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + CodeMirror.defineMIME("text/javascript", "javascript"); + CodeMirror.defineMIME("text/ecmascript", "javascript"); + CodeMirror.defineMIME("application/javascript", "javascript"); + CodeMirror.defineMIME("application/x-javascript", "javascript"); + CodeMirror.defineMIME("application/ecmascript", "javascript"); + CodeMirror.defineMIME("application/json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/x-json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/manifest+json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("application/ld+json", { + name: "javascript", + jsonld: true + }); + CodeMirror.defineMIME("text/typescript", { + name: "javascript", + typescript: true + }); + CodeMirror.defineMIME("application/typescript", { + name: "javascript", + typescript: true + }); + }); + })(); + var javascriptExports = javascript$2.exports; + const javascript = /* @__PURE__ */codemirror.getDefaultExportFromCjs(javascriptExports); + const javascript$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: javascript + }, [javascriptExports]); + exports.javascript = javascript$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/jump-to-line.cjs.js": + /*!*****************************************************!*\ + !*** ../../graphiql-react/dist/jump-to-line.cjs.js ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } - return false; } - function unwrapType(state) { - if ( - state.prevState && - state.kind && - [ - _parser.RuleKinds.NAMED_TYPE, - _parser.RuleKinds.LIST_TYPE, - _parser.RuleKinds.TYPE, - _parser.RuleKinds.NON_NULL_TYPE, - ].includes(state.kind) - ) { - return unwrapType(state.prevState); + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var jumpToLine$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), dialog.dialogExports); + })(function (CodeMirror) { + CodeMirror.defineOption("search", { + bottom: false + }); + function dialog2(cm, text, shortText, deflt, f) { + if (cm.openDialog) cm.openDialog(text, f, { + value: deflt, + selectValueOnOpen: true, + bottom: cm.options.search.bottom + });else f(prompt(shortText, deflt)); + } + function getJumpDialog(cm) { + return cm.phrase("Jump to line:") + ' ' + cm.phrase("(Use line:column or scroll% syntax)") + ""; + } + function interpretLine(cm, string) { + var num = Number(string); + if (/^[-+]/.test(string)) return cm.getCursor().line + num;else return num - 1; + } + CodeMirror.commands.jumpToLine = function (cm) { + var cur = cm.getCursor(); + dialog2(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), cur.line + 1 + ":" + cur.ch, function (posStr) { + if (!posStr) return; + var match; + if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) { + cm.setCursor(interpretLine(cm, match[1]), Number(match[2])); + } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) { + var line = Math.round(cm.lineCount() * Number(match[1]) / 100); + if (/^[-+]/.test(match[1])) line = cur.line + line + 1; + cm.setCursor(line - 1, cur.ch); + } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) { + cm.setCursor(interpretLine(cm, match[1]), cur.ch); + } + }); + }; + CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; + }); + })(); + var jumpToLineExports = jumpToLine$2.exports; + const jumpToLine = /* @__PURE__ */codemirror.getDefaultExportFromCjs(jumpToLineExports); + const jumpToLine$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: jumpToLine + }, [jumpToLineExports]); + exports.jumpToLine = jumpToLine$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/jump.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/jump.cjs.js ***! + \*********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const SchemaReference = __webpack_require__(/*! ./SchemaReference.cjs.js */ "../../graphiql-react/dist/SchemaReference.cjs.js"); + codemirror.CodeMirror.defineOption("jump", false, (cm, options, old) => { + if (old && old !== codemirror.CodeMirror.Init) { + const oldOnMouseOver = cm.state.jump.onMouseOver; + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseover", oldOnMouseOver); + const oldOnMouseOut = cm.state.jump.onMouseOut; + codemirror.CodeMirror.off(cm.getWrapperElement(), "mouseout", oldOnMouseOut); + codemirror.CodeMirror.off(document, "keydown", cm.state.jump.onKeyDown); + delete cm.state.jump; + } + if (options) { + const state = cm.state.jump = { + options, + onMouseOver: onMouseOver.bind(null, cm), + onMouseOut: onMouseOut.bind(null, cm), + onKeyDown: onKeyDown.bind(null, cm) + }; + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); + codemirror.CodeMirror.on(cm.getWrapperElement(), "mouseout", state.onMouseOut); + codemirror.CodeMirror.on(document, "keydown", state.onKeyDown); + } + }); + function onMouseOver(cm, event) { + const target = event.target || event.srcElement; + if (!(target instanceof HTMLElement)) { + return; + } + if ((target === null || target === void 0 ? void 0 : target.nodeName) !== "SPAN") { + return; + } + const box = target.getBoundingClientRect(); + const cursor = { + left: (box.left + box.right) / 2, + top: (box.top + box.bottom) / 2 + }; + cm.state.jump.cursor = cursor; + if (cm.state.jump.isHoldingModifier) { + enableJumpMode(cm); + } + } + function onMouseOut(cm) { + if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) { + cm.state.jump.cursor = null; + return; + } + if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) { + disableJumpMode(cm); + } + } + function onKeyDown(cm, event) { + if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) { + return; + } + cm.state.jump.isHoldingModifier = true; + if (cm.state.jump.cursor) { + enableJumpMode(cm); + } + const onKeyUp = upEvent => { + if (upEvent.code !== event.code) { + return; + } + cm.state.jump.isHoldingModifier = false; + if (cm.state.jump.marker) { + disableJumpMode(cm); + } + codemirror.CodeMirror.off(document, "keyup", onKeyUp); + codemirror.CodeMirror.off(document, "click", onClick); + cm.off("mousedown", onMouseDown); + }; + const onClick = clickEvent => { + const { + destination, + options + } = cm.state.jump; + if (destination) { + options.onClick(destination, clickEvent); + } + }; + const onMouseDown = (_, downEvent) => { + if (cm.state.jump.destination) { + downEvent.codemirrorIgnore = true; + } + }; + codemirror.CodeMirror.on(document, "keyup", onKeyUp); + codemirror.CodeMirror.on(document, "click", onClick); + cm.on("mousedown", onMouseDown); + } + const isMac = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.appVersion.includes("Mac")); + function isJumpModifier(key) { + return key === (isMac ? "Meta" : "Control"); + } + function enableJumpMode(cm) { + if (cm.state.jump.marker) { + return; + } + const { + cursor, + options + } = cm.state.jump; + const pos = cm.coordsChar(cursor); + const token = cm.getTokenAt(pos, true); + const getDestination = options.getDestination || cm.getHelper(pos, "jump"); + if (getDestination) { + const destination = getDestination(token, options, cm); + if (destination) { + const marker = cm.markText({ + line: pos.line, + ch: token.start + }, { + line: pos.line, + ch: token.end + }, { + className: "CodeMirror-jump-token" + }); + cm.state.jump.marker = marker; + cm.state.jump.destination = destination; + } + } + } + function disableJumpMode(cm) { + const { + marker + } = cm.state.jump; + cm.state.jump.marker = null; + cm.state.jump.destination = null; + marker.clear(); + } + codemirror.CodeMirror.registerHelper("jump", "graphql", (token, options) => { + if (!options.schema || !options.onClick || !token.state) { + return; + } + const { + state + } = token; + const { + kind, + step + } = state; + const typeInfo = SchemaReference.getTypeInfo(options.schema, state); + if (kind === "Field" && step === 0 && typeInfo.fieldDef || kind === "AliasedField" && step === 2 && typeInfo.fieldDef) { + return SchemaReference.getFieldReference(typeInfo); + } + if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { + return SchemaReference.getDirectiveReference(typeInfo); + } + if (kind === "Argument" && step === 0 && typeInfo.argDef) { + return SchemaReference.getArgumentReference(typeInfo); + } + if (kind === "EnumValue" && typeInfo.enumValue) { + return SchemaReference.getEnumValueReference(typeInfo); + } + if (kind === "NamedType" && typeInfo.type) { + return SchemaReference.getTypeReference(typeInfo); + } + }); + + /***/ }), + + /***/ "../../graphiql-react/dist/lint.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs.js ***! + \*********************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } - return state; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/getDefinition.js": - /*!*********************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getDefinition.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.LANGUAGE = void 0; - exports.getDefinitionQueryResultForArgument = - getDefinitionQueryResultForArgument; - exports.getDefinitionQueryResultForDefinitionNode = - getDefinitionQueryResultForDefinitionNode; - exports.getDefinitionQueryResultForField = - getDefinitionQueryResultForField; - exports.getDefinitionQueryResultForFragmentSpread = - getDefinitionQueryResultForFragmentSpread; - exports.getDefinitionQueryResultForNamedType = - getDefinitionQueryResultForNamedType; - var _utils = __webpack_require__( - /*! ../utils */ "../../graphql-language-service/esm/utils/index.js" - ); - var __awaiter = - (void 0 && (void 0).__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var lint$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var GUTTER_ID = "CodeMirror-lint-markers"; + var LINT_LINE_ID = "CodeMirror-lint-line-"; + function showTooltip(cm, e, content) { + var tt = document.createElement("div"); + tt.className = "CodeMirror-lint-tooltip cm-s-" + cm.options.theme; + tt.appendChild(content.cloneNode(true)); + if (cm.state.lint.options.selfContain) cm.getWrapperElement().appendChild(tt);else document.body.appendChild(tt); + function position(e2) { + if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); + tt.style.top = Math.max(0, e2.clientY - tt.offsetHeight - 5) + "px"; + tt.style.left = e2.clientX + 5 + "px"; + } + CodeMirror.on(document, "mousemove", position); + position(e); + if (tt.style.opacity != null) tt.style.opacity = 1; + return tt; + } + function rm(elt) { + if (elt.parentNode) elt.parentNode.removeChild(elt); + } + function hideTooltip(tt) { + if (!tt.parentNode) return; + if (tt.style.opacity == null) rm(tt); + tt.style.opacity = 0; + setTimeout(function () { + rm(tt); + }, 600); + } + function showTooltipFor(cm, e, content, node) { + var tooltip = showTooltip(cm, e, content); + function hide() { + CodeMirror.off(node, "mouseout", hide); + if (tooltip) { + hideTooltip(tooltip); + tooltip = null; + } + } + var poll = setInterval(function () { + if (tooltip) for (var n = node;; n = n.parentNode) { + if (n && n.nodeType == 11) n = n.host; + if (n == document.body) return; + if (!n) { + hide(); + break; } - 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() - ); + } + if (!tooltip) return clearInterval(poll); + }, 400); + CodeMirror.on(node, "mouseout", hide); + } + function LintState(cm, conf, hasGutter) { + this.marked = []; + if (conf instanceof Function) conf = { + getAnnotations: conf + }; + if (!conf || conf === true) conf = {}; + this.options = {}; + this.linterOptions = conf.options || {}; + for (var prop in defaults) this.options[prop] = defaults[prop]; + for (var prop in conf) { + if (defaults.hasOwnProperty(prop)) { + if (conf[prop] != null) this.options[prop] = conf[prop]; + } else if (!conf.options) { + this.linterOptions[prop] = conf[prop]; + } + } + this.timeout = null; + this.hasGutter = hasGutter; + this.onMouseOver = function (e) { + onMouseOver(cm, e); + }; + this.waitingFor = 0; + } + var defaults = { + highlightLines: false, + tooltips: true, + delay: 500, + lintOnChange: true, + getAnnotations: null, + async: false, + selfContain: null, + formatAnnotation: null, + onUpdateLinting: null + }; + function clearMarks(cm) { + var state = cm.state.lint; + if (state.hasGutter) cm.clearGutter(GUTTER_ID); + if (state.options.highlightLines) clearErrorLines(cm); + for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); + state.marked.length = 0; + } + function clearErrorLines(cm) { + cm.eachLine(function (line) { + var has = line.wrapClass && /\bCodeMirror-lint-line-\w+\b/.exec(line.wrapClass); + if (has) cm.removeLineClass(line, "wrap", has[0]); + }); + } + function makeMarker(cm, labels, severity, multiple, tooltips) { + var marker = document.createElement("div"), + inner = marker; + marker.className = "CodeMirror-lint-marker CodeMirror-lint-marker-" + severity; + if (multiple) { + inner = marker.appendChild(document.createElement("div")); + inner.className = "CodeMirror-lint-marker CodeMirror-lint-marker-multiple"; + } + if (tooltips != false) CodeMirror.on(inner, "mouseover", function (e) { + showTooltipFor(cm, e, labels, inner); + }); + return marker; + } + function getMaxSeverity(a, b) { + if (a == "error") return a;else return b; + } + function groupByLine(annotations) { + var lines = []; + for (var i = 0; i < annotations.length; ++i) { + var ann = annotations[i], + line = ann.from.line; + (lines[line] || (lines[line] = [])).push(ann); + } + return lines; + } + function annotationTooltip(ann) { + var severity = ann.severity; + if (!severity) severity = "error"; + var tip = document.createElement("div"); + tip.className = "CodeMirror-lint-message CodeMirror-lint-message-" + severity; + if (typeof ann.messageHTML != "undefined") { + tip.innerHTML = ann.messageHTML; + } else { + tip.appendChild(document.createTextNode(ann.message)); + } + return tip; + } + function lintAsync(cm, getAnnotations) { + var state = cm.state.lint; + var id = ++state.waitingFor; + function abort() { + id = -1; + cm.off("change", abort); + } + cm.on("change", abort); + getAnnotations(cm.getValue(), function (annotations, arg2) { + cm.off("change", abort); + if (state.waitingFor != id) return; + if (arg2 && annotations instanceof CodeMirror) annotations = arg2; + cm.operation(function () { + updateLinting(cm, annotations); + }); + }, state.linterOptions, cm); + } + function startLinting(cm) { + var state = cm.state.lint; + if (!state) return; + var options = state.options; + var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint"); + if (!getAnnotations) return; + if (options.async || getAnnotations.async) { + lintAsync(cm, getAnnotations); + } else { + var annotations = getAnnotations(cm.getValue(), state.linterOptions, cm); + if (!annotations) return; + if (annotations.then) annotations.then(function (issues) { + cm.operation(function () { + updateLinting(cm, issues); }); - }; - const LANGUAGE = (exports.LANGUAGE = "GraphQL"); - function assert(value, message) { - if (!value) { - throw new Error(message); - } - } - function getRange(text, node) { - const location = node.loc; - assert(location, "Expected ASTNode to have a location."); - return (0, _utils.locToRange)(text, location); - } - function getPosition(text, node) { - const location = node.loc; - assert(location, "Expected ASTNode to have a location."); - return (0, _utils.offsetToPosition)(text, location.start); - } - function getDefinitionQueryResultForNamedType( - text, - node, - dependencies - ) { - return __awaiter(this, void 0, void 0, function* () { - const name = node.name.value; - const defNodes = dependencies.filter( - ({ definition }) => - definition.name && definition.name.value === name - ); - if (defNodes.length === 0) { - throw new Error(`Definition not found for GraphQL type ${name}`); - } - const definitions = defNodes.map( - ({ filePath, content, definition }) => - getDefinitionForNodeDefinition( - filePath || "", - content, - definition - ) - ); - return { - definitions, - queryRange: definitions.map((_) => getRange(text, node)), - printedName: name, - }; + });else cm.operation(function () { + updateLinting(cm, annotations); }); } - function getDefinitionQueryResultForField( - fieldName, - typeName, - dependencies - ) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const defNodes = dependencies.filter( - ({ definition }) => - definition.name && definition.name.value === typeName - ); - if (defNodes.length === 0) { - throw new Error( - `Definition not found for GraphQL type ${typeName}` - ); - } - const definitions = []; - for (const { filePath, content, definition } of defNodes) { - const fieldDefinition = - (_a = definition.fields) === null || _a === void 0 - ? void 0 - : _a.find((item) => item.name.value === fieldName); - if (fieldDefinition == null) { - continue; - } - definitions.push( - getDefinitionForFieldDefinition( - filePath || "", - content, - fieldDefinition - ) - ); - } - return { - definitions, - queryRange: [], - printedName: [typeName, fieldName].join("."), - }; - }); + } + function updateLinting(cm, annotationsNotSorted) { + var state = cm.state.lint; + if (!state) return; + var options = state.options; + clearMarks(cm); + var annotations = groupByLine(annotationsNotSorted); + for (var line = 0; line < annotations.length; ++line) { + var anns = annotations[line]; + if (!anns) continue; + var message = []; + anns = anns.filter(function (item) { + return message.indexOf(item.message) > -1 ? false : message.push(item.message); + }); + var maxSeverity = null; + var tipLabel = state.hasGutter && document.createDocumentFragment(); + for (var i = 0; i < anns.length; ++i) { + var ann = anns[i]; + var severity = ann.severity; + if (!severity) severity = "error"; + maxSeverity = getMaxSeverity(maxSeverity, severity); + if (options.formatAnnotation) ann = options.formatAnnotation(ann); + if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); + if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { + className: "CodeMirror-lint-mark CodeMirror-lint-mark-" + severity, + __annotation: ann + })); + } + if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(cm, tipLabel, maxSeverity, annotations[line].length > 1, options.tooltips)); + if (options.highlightLines) cm.addLineClass(line, "wrap", LINT_LINE_ID + maxSeverity); + } + if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm); + } + function onChange(cm) { + var state = cm.state.lint; + if (!state) return; + clearTimeout(state.timeout); + state.timeout = setTimeout(function () { + startLinting(cm); + }, state.options.delay); + } + function popupTooltips(cm, annotations, e) { + var target = e.target || e.srcElement; + var tooltip = document.createDocumentFragment(); + for (var i = 0; i < annotations.length; i++) { + var ann = annotations[i]; + tooltip.appendChild(annotationTooltip(ann)); + } + showTooltipFor(cm, e, tooltip, target); + } + function onMouseOver(cm, e) { + var target = e.target || e.srcElement; + if (!/\bCodeMirror-lint-mark-/.test(target.className)) return; + var box = target.getBoundingClientRect(), + x = (box.left + box.right) / 2, + y = (box.top + box.bottom) / 2; + var spans = cm.findMarksAt(cm.coordsChar({ + left: x, + top: y + }, "client")); + var annotations = []; + for (var i = 0; i < spans.length; ++i) { + var ann = spans[i].__annotation; + if (ann) annotations.push(ann); + } + if (annotations.length) popupTooltips(cm, annotations, e); + } + CodeMirror.defineOption("lint", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + clearMarks(cm); + if (cm.state.lint.options.lintOnChange !== false) cm.off("change", onChange); + CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver); + clearTimeout(cm.state.lint.timeout); + delete cm.state.lint; + } + if (val) { + var gutters = cm.getOption("gutters"), + hasLintGutter = false; + for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; + var state = cm.state.lint = new LintState(cm, val, hasLintGutter); + if (state.options.lintOnChange) cm.on("change", onChange); + if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); + startLinting(cm); + } + }); + CodeMirror.defineExtension("performLint", function () { + startLinting(this); + }); + }); + })(); + var lintExports = lint$2.exports; + const lint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(lintExports); + const lint$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: lint + }, [lintExports]); + exports.lint = lint$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/lint.cjs2.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs2.js ***! + \**********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); + const SEVERITY = ["error", "warning", "information", "hint"]; + const TYPE = { + "GraphQL: Validation": "validation", + "GraphQL: Deprecation": "deprecation", + "GraphQL: Syntax": "syntax" + }; + codemirror.CodeMirror.registerHelper("lint", "graphql", (text, options) => { + const { + schema, + validationRules, + externalFragments + } = options; + const rawResults = graphqlLanguageService.getDiagnostics(text, schema, validationRules, void 0, externalFragments); + const results = rawResults.map(error => ({ + message: error.message, + severity: error.severity ? SEVERITY[error.severity - 1] : SEVERITY[0], + type: error.source ? TYPE[error.source] : void 0, + from: codemirror.CodeMirror.Pos(error.range.start.line, error.range.start.character), + to: codemirror.CodeMirror.Pos(error.range.end.line, error.range.end.character) + })); + return results; + }); + + /***/ }), + + /***/ "../../graphiql-react/dist/lint.cjs3.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/lint.cjs3.js ***! + \**********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function jsonParse(str) { + string = str; + strLen = str.length; + start = end = lastEnd = -1; + ch(); + lex(); + const ast = parseObj(); + expect("EOF"); + return ast; + } + let string; + let strLen; + let start; + let end; + let lastEnd; + let code; + let kind; + function parseObj() { + const nodeStart = start; + const members = []; + expect("{"); + if (!skip("}")) { + do { + members.push(parseMember()); + } while (skip(",")); + expect("}"); + } + return { + kind: "Object", + start: nodeStart, + end: lastEnd, + members + }; + } + function parseMember() { + const nodeStart = start; + const key = kind === "String" ? curToken() : null; + expect("String"); + expect(":"); + const value = parseVal(); + return { + kind: "Member", + start: nodeStart, + end: lastEnd, + key, + value + }; + } + function parseArr() { + const nodeStart = start; + const values = []; + expect("["); + if (!skip("]")) { + do { + values.push(parseVal()); + } while (skip(",")); + expect("]"); + } + return { + kind: "Array", + start: nodeStart, + end: lastEnd, + values + }; + } + function parseVal() { + switch (kind) { + case "[": + return parseArr(); + case "{": + return parseObj(); + case "String": + case "Number": + case "Boolean": + case "Null": + const token = curToken(); + lex(); + return token; + } + expect("Value"); + } + function curToken() { + return { + kind, + start, + end, + value: JSON.parse(string.slice(start, end)) + }; + } + function expect(str) { + if (kind === str) { + lex(); + return; + } + let found; + if (kind === "EOF") { + found = "[end of file]"; + } else if (end - start > 1) { + found = "`" + string.slice(start, end) + "`"; + } else { + const match = string.slice(start).match(/^.+?\b/); + found = "`" + (match ? match[0] : string[start]) + "`"; + } + throw syntaxError(`Expected ${str} but found ${found}.`); + } + class JSONSyntaxError extends Error { + constructor(message, position) { + super(message); + this.position = position; + } + } + function syntaxError(message) { + return new JSONSyntaxError(message, { + start, + end + }); + } + function skip(k) { + if (kind === k) { + lex(); + return true; + } + } + function ch() { + if (end < strLen) { + end++; + code = end === strLen ? 0 : string.charCodeAt(end); + } + return code; + } + function lex() { + lastEnd = end; + while (code === 9 || code === 10 || code === 13 || code === 32) { + ch(); + } + if (code === 0) { + kind = "EOF"; + return; + } + start = end; + switch (code) { + case 34: + kind = "String"; + return readString(); + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + kind = "Number"; + return readNumber(); + case 102: + if (string.slice(start, start + 5) !== "false") { + break; + } + end += 4; + ch(); + kind = "Boolean"; + return; + case 110: + if (string.slice(start, start + 4) !== "null") { + break; + } + end += 3; + ch(); + kind = "Null"; + return; + case 116: + if (string.slice(start, start + 4) !== "true") { + break; + } + end += 3; + ch(); + kind = "Boolean"; + return; + } + kind = string[start]; + ch(); + } + function readString() { + ch(); + while (code !== 34 && code > 31) { + if (code === 92) { + code = ch(); + switch (code) { + case 34: + case 47: + case 92: + case 98: + case 102: + case 110: + case 114: + case 116: + ch(); + break; + case 117: + ch(); + readHex(); + readHex(); + readHex(); + readHex(); + break; + default: + throw syntaxError("Bad character escape sequence."); + } + } else if (end === strLen) { + throw syntaxError("Unterminated string."); + } else { + ch(); + } + } + if (code === 34) { + ch(); + return; + } + throw syntaxError("Unterminated string."); + } + function readHex() { + if (code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102) { + return ch(); + } + throw syntaxError("Expected hexadecimal digit."); + } + function readNumber() { + if (code === 45) { + ch(); + } + if (code === 48) { + ch(); + } else { + readDigits(); + } + if (code === 46) { + ch(); + readDigits(); + } + if (code === 69 || code === 101) { + code = ch(); + if (code === 43 || code === 45) { + ch(); + } + readDigits(); + } + } + function readDigits() { + if (code < 48 || code > 57) { + throw syntaxError("Expected decimal digit."); + } + do { + ch(); + } while (code >= 48 && code <= 57); + } + codemirror.CodeMirror.registerHelper("lint", "graphql-variables", (text, options, editor) => { + if (!text) { + return []; + } + let ast; + try { + ast = jsonParse(text); + } catch (error) { + if (error instanceof JSONSyntaxError) { + return [lintError(editor, error.position, error.message)]; + } + throw error; + } + const { + variableToType + } = options; + if (!variableToType) { + return []; + } + return validateVariables(editor, variableToType, ast); + }); + function validateVariables(editor, variableToType, variablesAST) { + var _a; + const errors = []; + for (const member of variablesAST.members) { + if (member) { + const variableName = (_a = member.key) === null || _a === void 0 ? void 0 : _a.value; + const type = variableToType[variableName]; + if (type) { + for (const [node, message] of validateValue(type, member.value)) { + errors.push(lintError(editor, node, message)); + } + } else { + errors.push(lintError(editor, member.key, `Variable "$${variableName}" does not appear in any GraphQL query.`)); } - function getDefinitionQueryResultForArgument( - argumentName, - fieldName, - typeName, - dependencies - ) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const definitions = []; - for (const { filePath, content, definition } of dependencies) { - const argDefinition = - (_c = - (_b = - (_a = definition.fields) === null || _a === void 0 - ? void 0 - : _a.find((item) => item.name.value === fieldName)) === - null || _b === void 0 - ? void 0 - : _b.arguments) === null || _c === void 0 - ? void 0 - : _c.find((item) => item.name.value === argumentName); - if (argDefinition == null) { - continue; - } - definitions.push( - getDefinitionForArgumentDefinition( - filePath || "", - content, - argDefinition - ) - ); - } - return { - definitions, - queryRange: [], - printedName: `${[typeName, fieldName].join( - "." - )}(${argumentName})`, - }; - }); + } + } + return errors; + } + function validateValue(type, valueAST) { + if (!type || !valueAST) { + return []; + } + if (type instanceof graphql.GraphQLNonNull) { + if (valueAST.kind === "Null") { + return [[valueAST, `Type "${type}" is non-nullable and cannot be null.`]]; + } + return validateValue(type.ofType, valueAST); + } + if (valueAST.kind === "Null") { + return []; + } + if (type instanceof graphql.GraphQLList) { + const itemType = type.ofType; + if (valueAST.kind === "Array") { + const values = valueAST.values || []; + return mapCat(values, item => validateValue(itemType, item)); + } + return validateValue(itemType, valueAST); + } + if (type instanceof graphql.GraphQLInputObjectType) { + if (valueAST.kind !== "Object") { + return [[valueAST, `Type "${type}" must be an Object.`]]; + } + const providedFields = /* @__PURE__ */Object.create(null); + const fieldErrors = mapCat(valueAST.members, member => { + var _a; + const fieldName = (_a = member === null || member === void 0 ? void 0 : member.key) === null || _a === void 0 ? void 0 : _a.value; + providedFields[fieldName] = true; + const inputField = type.getFields()[fieldName]; + if (!inputField) { + return [[member.key, `Type "${type}" does not have a field "${fieldName}".`]]; + } + const fieldType = inputField ? inputField.type : void 0; + return validateValue(fieldType, member.value); + }); + for (const fieldName of Object.keys(type.getFields())) { + const field = type.getFields()[fieldName]; + if (!providedFields[fieldName] && field.type instanceof graphql.GraphQLNonNull && !field.defaultValue) { + fieldErrors.push([valueAST, `Object of type "${type}" is missing required field "${fieldName}".`]); } - function getDefinitionQueryResultForFragmentSpread( - text, - fragment, - dependencies - ) { - return __awaiter(this, void 0, void 0, function* () { - const name = fragment.name.value; - const defNodes = dependencies.filter( - ({ definition }) => definition.name.value === name - ); - if (defNodes.length === 0) { - throw new Error( - `Definition not found for GraphQL fragment ${name}` - ); + } + return fieldErrors; + } + if (type.name === "Boolean" && valueAST.kind !== "Boolean" || type.name === "String" && valueAST.kind !== "String" || type.name === "ID" && valueAST.kind !== "Number" && valueAST.kind !== "String" || type.name === "Float" && valueAST.kind !== "Number" || type.name === "Int" && (valueAST.kind !== "Number" || (valueAST.value | 0) !== valueAST.value)) { + return [[valueAST, `Expected value of type "${type}".`]]; + } + if ((type instanceof graphql.GraphQLEnumType || type instanceof graphql.GraphQLScalarType) && (valueAST.kind !== "String" && valueAST.kind !== "Number" && valueAST.kind !== "Boolean" && valueAST.kind !== "Null" || isNullish(type.parseValue(valueAST.value)))) { + return [[valueAST, `Expected value of type "${type}".`]]; + } + return []; + } + function lintError(editor, node, message) { + return { + message, + severity: "error", + type: "validation", + from: editor.posFromIndex(node.start), + to: editor.posFromIndex(node.end) + }; + } + function isNullish(value) { + return value === null || value === void 0 || value !== value; + } + function mapCat(array, mapper) { + return Array.prototype.concat.apply([], array.map(mapper)); + } + + /***/ }), + + /***/ "../../graphiql-react/dist/matchbrackets.cjs.js": + /*!******************************************************!*\ + !*** ../../graphiql-react/dist/matchbrackets.cjs.js ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + const matchbrackets$2 = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } - const definitions = defNodes.map( - ({ filePath, content, definition }) => - getDefinitionForFragmentDefinition( - filePath || "", - content, - definition - ) - ); - return { - definitions, - queryRange: definitions.map((_) => getRange(text, fragment)), - printedName: name, - }; - }); + } } - function getDefinitionQueryResultForDefinitionNode( - path, - text, - definition - ) { - var _a; + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var matchbracketsExports = matchbrackets$2.requireMatchbrackets(); + const matchbrackets = /* @__PURE__ */codemirror.getDefaultExportFromCjs(matchbracketsExports); + const matchbrackets$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: matchbrackets + }, [matchbracketsExports]); + exports.matchbrackets = matchbrackets$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/matchbrackets.cjs2.js": + /*!*******************************************************!*\ + !*** ../../graphiql-react/dist/matchbrackets.cjs2.js ***! + \*******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + var matchbrackets = { + exports: {} + }; + var hasRequiredMatchbrackets; + function requireMatchbrackets() { + if (hasRequiredMatchbrackets) return matchbrackets.exports; + hasRequiredMatchbrackets = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && (document.documentMode == null || document.documentMode < 8); + var Pos = CodeMirror.Pos; + var matching = { + "(": ")>", + ")": "(<", + "[": "]>", + "]": "[<", + "{": "}>", + "}": "{<", + "<": ">>", + ">": "<<" + }; + function bracketRegex(config) { + return config && config.bracketRegex || /[(){}[\]]/; + } + function findMatchingBracket(cm, where, config) { + var line = cm.getLineHandle(where.line), + pos = where.ch - 1; + var afterCursor = config && config.afterCursor; + if (afterCursor == null) afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className); + var re = bracketRegex(config); + var match = !afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)] || re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; + if (!match) return null; + var dir = match.charAt(1) == ">" ? 1 : -1; + if (config && config.strict && dir > 0 != (pos == where.ch)) return null; + var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); + var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style, config); + if (found == null) return null; return { - definitions: [ - getDefinitionForFragmentDefinition(path, text, definition), - ], - queryRange: definition.name - ? [getRange(text, definition.name)] - : [], - printedName: - (_a = definition.name) === null || _a === void 0 - ? void 0 - : _a.value, + from: Pos(where.line, pos), + to: found && found.pos, + match: found && found.ch == match.charAt(0), + forward: dir > 0 }; } - function getDefinitionForFragmentDefinition(path, text, definition) { - const { name } = definition; - if (!name) { - throw new Error("Expected ASTNode to have a Name."); + function scanForBracket(cm, where, dir, style, config) { + var maxScanLen = config && config.maxScanLineLength || 1e4; + var maxScanLines = config && config.maxScanLines || 1e3; + var stack = []; + var re = bracketRegex(config); + var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) : Math.max(cm.firstLine() - 1, where.line - maxScanLines); + for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { + var line = cm.getLine(lineNo); + if (!line) continue; + var pos = dir > 0 ? 0 : line.length - 1, + end = dir > 0 ? line.length : -1; + if (line.length > maxScanLen) continue; + if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); + for (; pos != end; pos += dir) { + var ch = line.charAt(pos); + if (re.test(ch) && (style === void 0 || (cm.getTokenTypeAt(Pos(lineNo, pos + 1)) || "") == (style || ""))) { + var match = matching[ch]; + if (match && match.charAt(1) == ">" == dir > 0) stack.push(ch);else if (!stack.length) return { + pos: Pos(lineNo, pos), + ch + };else stack.pop(); + } + } + } + return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; + } + function matchBrackets(cm, autoclear, config) { + var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1e3, + highlightNonMatching = config && config.highlightNonMatching; + var marks = [], + ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); + if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) { + var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), { + className: style + })); + if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), { + className: style + })); + } + } + if (marks.length) { + if (ie_lt8 && cm.state.focused) cm.focus(); + var clear = function () { + cm.operation(function () { + for (var i2 = 0; i2 < marks.length; i2++) marks[i2].clear(); + }); + }; + if (autoclear) setTimeout(clear, 800);else return clear; } - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || "", - language: LANGUAGE, - projectRoot: path, - }; - } - function getDefinitionForNodeDefinition(path, text, definition) { - const { name } = definition; - assert(name, "Expected ASTNode to have a Name."); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || "", - language: LANGUAGE, - projectRoot: path, - }; } - function getDefinitionForFieldDefinition(path, text, definition) { - const { name } = definition; - assert(name, "Expected ASTNode to have a Name."); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || "", - language: LANGUAGE, - projectRoot: path, - }; + function doMatchBrackets(cm) { + cm.operation(function () { + if (cm.state.matchBrackets.currentlyHighlighted) { + cm.state.matchBrackets.currentlyHighlighted(); + cm.state.matchBrackets.currentlyHighlighted = null; + } + cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); + }); } - function getDefinitionForArgumentDefinition(path, text, definition) { - const { name } = definition; - assert(name, "Expected ASTNode to have a Name."); - return { - path, - position: getPosition(text, definition), - range: getRange(text, definition), - name: name.value || "", - language: LANGUAGE, - projectRoot: path, - }; + function clearHighlighted(cm) { + if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { + cm.state.matchBrackets.currentlyHighlighted(); + cm.state.matchBrackets.currentlyHighlighted = null; + } } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/getDiagnostics.js": - /*!**********************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getDiagnostics.js ***! - \**********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, + CodeMirror.defineOption("matchBrackets", false, function (cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.off("cursorActivity", doMatchBrackets); + cm.off("focus", doMatchBrackets); + cm.off("blur", clearHighlighted); + clearHighlighted(cm); + } + if (val) { + cm.state.matchBrackets = typeof val == "object" ? val : {}; + cm.on("cursorActivity", doMatchBrackets); + cm.on("focus", doMatchBrackets); + cm.on("blur", clearHighlighted); + } }); - exports.SEVERITY = exports.DIAGNOSTIC_SEVERITY = void 0; - exports.getDiagnostics = getDiagnostics; - exports.getRange = getRange; - exports.validateQuery = validateQuery; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _parser = __webpack_require__( - /*! ../parser */ "../../graphql-language-service/esm/parser/index.js" - ); - var _utils = __webpack_require__( - /*! ../utils */ "../../graphql-language-service/esm/utils/index.js" - ); - const SEVERITY = (exports.SEVERITY = { - Error: "Error", - Warning: "Warning", - Information: "Information", - Hint: "Hint", + CodeMirror.defineExtension("matchBrackets", function () { + matchBrackets(this, true); + }); + CodeMirror.defineExtension("findMatchingBracket", function (pos, config, oldConfig) { + if (oldConfig || typeof config == "boolean") { + if (!oldConfig) { + config = config ? { + strict: true + } : null; + } else { + oldConfig.strict = config; + config = oldConfig; + } + } + return findMatchingBracket(this, pos, config); }); - const DIAGNOSTIC_SEVERITY = (exports.DIAGNOSTIC_SEVERITY = { - [SEVERITY.Error]: 1, - [SEVERITY.Warning]: 2, - [SEVERITY.Information]: 3, - [SEVERITY.Hint]: 4, + CodeMirror.defineExtension("scanForBracket", function (pos, dir, style, config) { + return scanForBracket(this, pos, dir, style, config); }); - const invariant = (condition, message) => { - if (!condition) { - throw new Error(message); + }); + })(); + return matchbrackets.exports; + } + exports.requireMatchbrackets = requireMatchbrackets; + + /***/ }), + + /***/ "../../graphiql-react/dist/mode-indent.cjs.js": + /*!****************************************************!*\ + !*** ../../graphiql-react/dist/mode-indent.cjs.js ***! + \****************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + function indent(state, textAfter) { + var _a, _b; + const { + levels, + indentLevel + } = state; + const level = !levels || levels.length === 0 ? indentLevel : levels.at(-1) - (((_a = this.electricInput) === null || _a === void 0 ? void 0 : _a.test(textAfter)) ? 1 : 0); + return (level || 0) * (((_b = this.config) === null || _b === void 0 ? void 0 : _b.indentUnit) || 0); + } + exports.indent = indent; + + /***/ }), + + /***/ "../../graphiql-react/dist/mode.cjs.js": + /*!*********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs.js ***! + \*********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); + const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); + const graphqlModeFactory = config => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: stream => stream.eatWhile(graphqlLanguageService.isIgnored), + lexRules: graphqlLanguageService.LexRules, + parseRules: graphqlLanguageService.ParseRules, + editorConfig: { + tabSize: config.tabSize + } + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[})\]]/, + fold: "brace", + lineComment: "#", + closeBrackets: { + pairs: '()[]{}""', + explode: "()[]{}" + } + }; + }; + codemirror.CodeMirror.defineMode("graphql", graphqlModeFactory); + + /***/ }), + + /***/ "../../graphiql-react/dist/mode.cjs2.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs2.js ***! + \**********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); + const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); + codemirror.CodeMirror.defineMode("graphql-variables", config => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: stream => stream.eatSpace(), + lexRules: LexRules, + parseRules: ParseRules, + editorConfig: { + tabSize: config.tabSize + } + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[}\]]/, + fold: "brace", + closeBrackets: { + pairs: '[]{}""', + explode: "[]{}" + } + }; + }); + const LexRules = { + Punctuation: /^\[|]|\{|\}|:|,/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, + Keyword: /^true|false|null/ + }; + const ParseRules = { + Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Variable", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], + Variable: [namedKey("variable"), graphqlLanguageService.p(":"), "Value"], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; } - }; - function getDiagnostics( - query, - schema = null, - customRules, - isRelayCompatMode, - externalFragments - ) { - var _a, _b; - let ast = null; - let fragments = ""; - if (externalFragments) { - fragments = - typeof externalFragments === "string" - ? externalFragments - : externalFragments.reduce( - (acc, node) => acc + (0, _graphql.print)(node) + "\n\n", - "" - ); - } - const enhancedQuery = fragments ? `${query}\n\n${fragments}` : query; - try { - ast = (0, _graphql.parse)(enhancedQuery); - } catch (error) { - if (error instanceof _graphql.GraphQLError) { - const range = getRange( - (_b = - (_a = error.locations) === null || _a === void 0 - ? void 0 - : _a[0]) !== null && _b !== void 0 - ? _b - : { - line: 0, - column: 0, - }, - enhancedQuery - ); - return [ - { - severity: DIAGNOSTIC_SEVERITY.Error, - message: error.message, - source: "GraphQL: Syntax", - range, - }, - ]; - } - throw error; - } - return validateQuery(ast, schema, customRules, isRelayCompatMode); - } - function validateQuery( - ast, - schema = null, - customRules, - isRelayCompatMode - ) { - if (!schema) { - return []; - } - const validationErrorAnnotations = (0, - _utils.validateWithCustomRules)( - schema, - ast, - customRules, - isRelayCompatMode - ).flatMap((error) => - annotations(error, DIAGNOSTIC_SEVERITY.Error, "Validation") - ); - const deprecationWarningAnnotations = (0, _graphql.validate)( - schema, - ast, - [_graphql.NoDeprecatedCustomRule] - ).flatMap((error) => - annotations(error, DIAGNOSTIC_SEVERITY.Warning, "Deprecation") - ); - return validationErrorAnnotations.concat( - deprecationWarningAnnotations - ); - } - function annotations(error, severity, type) { - if (!error.nodes) { - return []; - } - const highlightedNodes = []; - for (const [i, node] of error.nodes.entries()) { - const highlightNode = - node.kind !== "Variable" && - "name" in node && - node.name !== undefined - ? node.name - : "variable" in node && node.variable !== undefined - ? node.variable - : node; - if (highlightNode) { - invariant( - error.locations, - "GraphQL validation error requires locations." - ); - const loc = error.locations[i]; - const highlightLoc = getLocation(highlightNode); - const end = loc.column + (highlightLoc.end - highlightLoc.start); - highlightedNodes.push({ - source: `GraphQL: ${type}`, - message: error.message, - severity, - range: new _utils.Range( - new _utils.Position(loc.line - 1, loc.column - 1), - new _utils.Position(loc.line - 1, end) - ), + return null; + case "Keyword": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + case "null": + return "NullValue"; + } + return null; + } + }, + NumberValue: [graphqlLanguageService.t("Number", "number")], + StringValue: [graphqlLanguageService.t("String", "string")], + BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], + NullValue: [graphqlLanguageService.t("Keyword", "keyword")], + ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("]")], + ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.opt(graphqlLanguageService.p(","))), graphqlLanguageService.p("}")], + ObjectField: [namedKey("attribute"), graphqlLanguageService.p(":"), "Value"] + }; + function namedKey(style) { + return { + style, + match: token => token.kind === "String", + update(state, token) { + state.name = token.value.slice(1, -1); + } + }; + } + + /***/ }), + + /***/ "../../graphiql-react/dist/mode.cjs3.js": + /*!**********************************************!*\ + !*** ../../graphiql-react/dist/mode.cjs3.js ***! + \**********************************************/ + /***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs.js */ "../../graphiql-react/dist/codemirror.cjs.js"); + const graphqlLanguageService = __webpack_require__(/*! graphql-language-service */ "../../graphql-language-service/esm/index.js"); + const modeIndent = __webpack_require__(/*! ./mode-indent.cjs.js */ "../../graphiql-react/dist/mode-indent.cjs.js"); + codemirror.CodeMirror.defineMode("graphql-results", config => { + const parser = graphqlLanguageService.onlineParser({ + eatWhitespace: stream => stream.eatSpace(), + lexRules: LexRules, + parseRules: ParseRules, + editorConfig: { + tabSize: config.tabSize + } + }); + return { + config, + startState: parser.startState, + token: parser.token, + indent: modeIndent.indent, + electricInput: /^\s*[}\]]/, + fold: "brace", + closeBrackets: { + pairs: '[]{}""', + explode: "[]{}" + } + }; + }); + const LexRules = { + Punctuation: /^\[|]|\{|\}|:|,/, + Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, + String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/, + Keyword: /^true|false|null/ + }; + const ParseRules = { + Document: [graphqlLanguageService.p("{"), graphqlLanguageService.list("Entry", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], + Entry: [graphqlLanguageService.t("String", "def"), graphqlLanguageService.p(":"), "Value"], + Value(token) { + switch (token.kind) { + case "Number": + return "NumberValue"; + case "String": + return "StringValue"; + case "Punctuation": + switch (token.value) { + case "[": + return "ListValue"; + case "{": + return "ObjectValue"; + } + return null; + case "Keyword": + switch (token.value) { + case "true": + case "false": + return "BooleanValue"; + case "null": + return "NullValue"; + } + return null; + } + }, + NumberValue: [graphqlLanguageService.t("Number", "number")], + StringValue: [graphqlLanguageService.t("String", "string")], + BooleanValue: [graphqlLanguageService.t("Keyword", "builtin")], + NullValue: [graphqlLanguageService.t("Keyword", "keyword")], + ListValue: [graphqlLanguageService.p("["), graphqlLanguageService.list("Value", graphqlLanguageService.p(",")), graphqlLanguageService.p("]")], + ObjectValue: [graphqlLanguageService.p("{"), graphqlLanguageService.list("ObjectField", graphqlLanguageService.p(",")), graphqlLanguageService.p("}")], + ObjectField: [graphqlLanguageService.t("String", "property"), graphqlLanguageService.p(":"), "Value"] + }; + + /***/ }), + + /***/ "../../graphiql-react/dist/search.cjs.js": + /*!***********************************************!*\ + !*** ../../graphiql-react/dist/search.cjs.js ***! + \***********************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); + const dialog = __webpack_require__(/*! ./dialog.cjs.js */ "../../graphiql-react/dist/dialog.cjs.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] }); } } - return highlightedNodes; } - function getRange(location, queryText) { - const parser = (0, _parser.onlineParser)(); - const state = parser.startState(); - const lines = queryText.split("\n"); - invariant( - lines.length >= location.line, - "Query text must have more lines than where the error happened" - ); - let stream = null; - for (let i = 0; i < location.line; i++) { - stream = new _parser.CharacterStream(lines[i]); - while (!stream.eol()) { - const style = parser.token(stream, state); - if (style === "invalidchar") { - break; - } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var search$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), dialog.dialogExports); + })(function (CodeMirror) { + CodeMirror.defineOption("search", { + bottom: false + }); + function searchOverlay(query, caseInsensitive) { + if (typeof query == "string") query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");else if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); + return { + token: function (stream) { + query.lastIndex = stream.pos; + var match = query.exec(stream.string); + if (match && match.index == stream.pos) { + stream.pos += match[0].length || 1; + return "searching"; + } else if (match) { + stream.pos = match.index; + } else { + stream.skipToEnd(); } } - invariant(stream, "Expected Parser stream to be available."); - const line = location.line - 1; - const start = stream.getStartOfToken(); - const end = stream.getCurrentPosition(); - return new _utils.Range( - new _utils.Position(line, start), - new _utils.Position(line, end) - ); + }; + } + function SearchState() { + this.posFrom = this.posTo = this.lastQuery = this.query = null; + this.overlay = null; + } + function getSearchState(cm) { + return cm.state.search || (cm.state.search = new SearchState()); + } + function queryCaseInsensitive(query) { + return typeof query == "string" && query == query.toLowerCase(); + } + function getSearchCursor(cm, query, pos) { + return cm.getSearchCursor(query, pos, { + caseFold: queryCaseInsensitive(query), + multiline: true + }); + } + function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { + cm.openDialog(text, onEnter, { + value: deflt, + selectValueOnOpen: true, + closeOnEnter: false, + onClose: function () { + clearSearch(cm); + }, + onKeyDown, + bottom: cm.options.search.bottom + }); + } + function dialog2(cm, text, shortText, deflt, f) { + if (cm.openDialog) cm.openDialog(text, f, { + value: deflt, + selectValueOnOpen: true, + bottom: cm.options.search.bottom + });else f(prompt(shortText, deflt)); + } + function confirmDialog(cm, text, shortText, fs) { + if (cm.openConfirm) cm.openConfirm(text, fs);else if (confirm(shortText)) fs[0](); + } + function parseString(string) { + return string.replace(/\\([nrt\\])/g, function (match, ch) { + if (ch == "n") return "\n"; + if (ch == "r") return "\r"; + if (ch == "t") return " "; + if (ch == "\\") return "\\"; + return match; + }); + } + function parseQuery(query) { + var isRE = query.match(/^\/(.*)\/([a-z]*)$/); + if (isRE) { + try { + query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); + } catch (e) {} + } else { + query = parseString(query); } - function getLocation(node) { - const typeCastedNode = node; - const location = typeCastedNode.loc; - invariant(location, "Expected ASTNode to have a location."); - return location; + if (typeof query == "string" ? query == "" : query.test("")) query = /x^/; + return query; + } + function startSearch(cm, state, query) { + state.queryText = query; + state.query = parseQuery(query); + cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); + state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); + cm.addOverlay(state.overlay); + if (cm.showMatchesOnScrollbar) { + if (state.annotate) { + state.annotate.clear(); + state.annotate = null; + } + state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/getHoverInformation.js": - /*!***************************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getHoverInformation.js ***! - \***************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, + } + function doSearch(cm, rev, persistent, immediate) { + var state = getSearchState(cm); + if (state.query) return findNext(cm, rev); + var q = cm.getSelection() || state.lastQuery; + if (q instanceof RegExp && q.source == "x^") q = null; + if (persistent && cm.openDialog) { + var hiding = null; + var searchNext = function (query, event) { + CodeMirror.e_stop(event); + if (!query) return; + if (query != state.queryText) { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + } + if (hiding) hiding.style.opacity = 1; + findNext(cm, event.shiftKey, function (_, to) { + var dialog3; + if (to.line < 3 && document.querySelector && (dialog3 = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && dialog3.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) (hiding = dialog3).style.opacity = 0.4; + }); + }; + persistentDialog(cm, getQueryDialog(cm), q, searchNext, function (event, query) { + var keyName = CodeMirror.keyName(event); + var extra = cm.getOption("extraKeys"), + cmd = extra && extra[keyName] || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]; + if (cmd == "findNext" || cmd == "findPrev" || cmd == "findPersistentNext" || cmd == "findPersistentPrev") { + CodeMirror.e_stop(event); + startSearch(cm, getSearchState(cm), query); + cm.execCommand(cmd); + } else if (cmd == "find" || cmd == "findPersistent") { + CodeMirror.e_stop(event); + searchNext(query, event); + } + }); + if (immediate && q) { + startSearch(cm, state, q); + findNext(cm, rev); + } + } else { + dialog2(cm, getQueryDialog(cm), "Search for:", q, function (query) { + if (query && !state.query) cm.operation(function () { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + findNext(cm, rev); + }); + }); + } + } + function findNext(cm, rev, callback) { + cm.operation(function () { + var state = getSearchState(cm); + var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); + if (!cursor.find(rev)) { + cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); + if (!cursor.find(rev)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({ + from: cursor.from(), + to: cursor.to() + }, 20); + state.posFrom = cursor.from(); + state.posTo = cursor.to(); + if (callback) callback(cursor.from(), cursor.to()); }); - exports.getHoverInformation = getHoverInformation; - exports.renderArg = renderArg; - exports.renderDirective = renderDirective; - exports.renderEnumValue = renderEnumValue; - exports.renderField = renderField; - exports.renderType = renderType; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _parser = __webpack_require__( - /*! ../parser */ "../../graphql-language-service/esm/parser/index.js" - ); - function getHoverInformation( - schema, - queryText, - cursor, - contextToken, - config - ) { - const options = Object.assign(Object.assign({}, config), { - schema, + } + function clearSearch(cm) { + cm.operation(function () { + var state = getSearchState(cm); + state.lastQuery = state.query; + if (!state.query) return; + state.query = state.queryText = null; + cm.removeOverlay(state.overlay); + if (state.annotate) { + state.annotate.clear(); + state.annotate = null; + } + }); + } + function el(tag, attrs) { + var element = tag ? document.createElement(tag) : document.createDocumentFragment(); + for (var key in attrs) { + element[key] = attrs[key]; + } + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + element.appendChild(typeof child == "string" ? document.createTextNode(child) : child); + } + return element; + } + function getQueryDialog(cm) { + return el("", null, el("span", { + className: "CodeMirror-search-label" + }, cm.phrase("Search:")), " ", el("input", { + type: "text", + "style": "width: 10em", + className: "CodeMirror-search-field" + }), " ", el("span", { + style: "color: #888", + className: "CodeMirror-search-hint" + }, cm.phrase("(Use /re/ syntax for regexp search)"))); + } + function getReplaceQueryDialog(cm) { + return el("", null, " ", el("input", { + type: "text", + "style": "width: 10em", + className: "CodeMirror-search-field" + }), " ", el("span", { + style: "color: #888", + className: "CodeMirror-search-hint" + }, cm.phrase("(Use /re/ syntax for regexp search)"))); + } + function getReplacementQueryDialog(cm) { + return el("", null, el("span", { + className: "CodeMirror-search-label" + }, cm.phrase("With:")), " ", el("input", { + type: "text", + "style": "width: 10em", + className: "CodeMirror-search-field" + })); + } + function getDoReplaceConfirm(cm) { + return el("", null, el("span", { + className: "CodeMirror-search-label" + }, cm.phrase("Replace?")), " ", el("button", {}, cm.phrase("Yes")), " ", el("button", {}, cm.phrase("No")), " ", el("button", {}, cm.phrase("All")), " ", el("button", {}, cm.phrase("Stop"))); + } + function replaceAll(cm, query, text) { + cm.operation(function () { + for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { + if (typeof query != "string") { + var match = cm.getRange(cursor.from(), cursor.to()).match(query); + cursor.replace(text.replace(/\$(\d)/g, function (_, i) { + return match[i]; + })); + } else cursor.replace(text); + } + }); + } + function replace(cm, all) { + if (cm.getOption("readOnly")) return; + var query = cm.getSelection() || getSearchState(cm).lastQuery; + var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:"); + var fragment = el("", null, el("span", { + className: "CodeMirror-search-label" + }, dialogText), getReplaceQueryDialog(cm)); + dialog2(cm, fragment, dialogText, query, function (query2) { + if (!query2) return; + query2 = parseQuery(query2); + dialog2(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function (text) { + text = parseString(text); + if (all) { + replaceAll(cm, query2, text); + } else { + clearSearch(cm); + var cursor = getSearchCursor(cm, query2, cm.getCursor("from")); + var advance = function () { + var start = cursor.from(), + match; + if (!(match = cursor.findNext())) { + cursor = getSearchCursor(cm, query2); + if (!(match = cursor.findNext()) || start && cursor.from().line == start.line && cursor.from().ch == start.ch) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({ + from: cursor.from(), + to: cursor.to() + }); + confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"), [function () { + doReplace(match); + }, advance, function () { + replaceAll(cm, query2, text); + }]); + }; + var doReplace = function (match) { + cursor.replace(typeof query2 == "string" ? text : text.replace(/\$(\d)/g, function (_, i) { + return match[i]; + })); + advance(); + }; + advance(); + } }); - const context = (0, _parser.getContextAtPosition)( - queryText, - cursor, - schema, - contextToken - ); - if (!context) { - return ""; - } - const { typeInfo, token } = context; - const { kind, step } = token.state; - if ( - (kind === "Field" && step === 0 && typeInfo.fieldDef) || - (kind === "AliasedField" && step === 2 && typeInfo.fieldDef) || - (kind === "ObjectField" && step === 0 && typeInfo.fieldDef) - ) { - const into = []; - renderMdCodeStart(into, options); - renderField(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.fieldDef); - return into.join("").trim(); - } - if (kind === "Directive" && step === 1 && typeInfo.directiveDef) { - const into = []; - renderMdCodeStart(into, options); - renderDirective(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.directiveDef); - return into.join("").trim(); - } - if (kind === "Variable" && typeInfo.type) { - const into = []; - renderMdCodeStart(into, options); - renderType(into, typeInfo, options, typeInfo.type); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.type); - return into.join("").trim(); - } - if (kind === "Argument" && step === 0 && typeInfo.argDef) { - const into = []; - renderMdCodeStart(into, options); - renderArg(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.argDef); - return into.join("").trim(); - } - if ( - kind === "EnumValue" && - typeInfo.enumValue && - "description" in typeInfo.enumValue - ) { - const into = []; - renderMdCodeStart(into, options); - renderEnumValue(into, typeInfo, options); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.enumValue); - return into.join("").trim(); - } - if ( - kind === "NamedType" && - typeInfo.type && - "description" in typeInfo.type - ) { - const into = []; - renderMdCodeStart(into, options); - renderType(into, typeInfo, options, typeInfo.type); - renderMdCodeEnd(into, options); - renderDescription(into, options, typeInfo.type); - return into.join("").trim(); - } - return ""; - } - function renderMdCodeStart(into, options) { - if (options.useMarkdown) { - text(into, "```graphql\n"); - } - } - function renderMdCodeEnd(into, options) { - if (options.useMarkdown) { - text(into, "\n```"); - } - } - function renderField(into, typeInfo, options) { - renderQualifiedField(into, typeInfo, options); - renderTypeAnnotation(into, typeInfo, options, typeInfo.type); - } - function renderQualifiedField(into, typeInfo, options) { - if (!typeInfo.fieldDef) { - return; + }); + } + CodeMirror.commands.find = function (cm) { + clearSearch(cm); + doSearch(cm); + }; + CodeMirror.commands.findPersistent = function (cm) { + clearSearch(cm); + doSearch(cm, false, true); + }; + CodeMirror.commands.findPersistentNext = function (cm) { + doSearch(cm, false, true, true); + }; + CodeMirror.commands.findPersistentPrev = function (cm) { + doSearch(cm, true, true, true); + }; + CodeMirror.commands.findNext = doSearch; + CodeMirror.commands.findPrev = function (cm) { + doSearch(cm, true); + }; + CodeMirror.commands.clearSearch = clearSearch; + CodeMirror.commands.replace = replace; + CodeMirror.commands.replaceAll = function (cm) { + replace(cm, true); + }; + }); + })(); + var searchExports = search$2.exports; + const search = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchExports); + const search$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: search + }, [searchExports]); + exports.search = search$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/searchcursor.cjs.js": + /*!*****************************************************!*\ + !*** ../../graphiql-react/dist/searchcursor.cjs.js ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + const searchcursor$2 = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var searchcursorExports = searchcursor$2.requireSearchcursor(); + const searchcursor = /* @__PURE__ */codemirror.getDefaultExportFromCjs(searchcursorExports); + const searchcursor$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: searchcursor + }, [searchcursorExports]); + exports.searchcursor = searchcursor$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/searchcursor.cjs2.js": + /*!******************************************************!*\ + !*** ../../graphiql-react/dist/searchcursor.cjs2.js ***! + \******************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + var searchcursor = { + exports: {} + }; + var hasRequiredSearchcursor; + function requireSearchcursor() { + if (hasRequiredSearchcursor) return searchcursor.exports; + hasRequiredSearchcursor = 1; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var Pos = CodeMirror.Pos; + function regexpFlags(regexp) { + var flags = regexp.flags; + return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + (regexp.global ? "g" : "") + (regexp.multiline ? "m" : ""); + } + function ensureFlags(regexp, flags) { + var current = regexpFlags(regexp), + target = current; + for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) target += flags.charAt(i); + return current == target ? regexp : new RegExp(regexp.source, target); + } + function maybeMultiline(regexp) { + return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source); + } + function searchRegexpForward(doc, regexp, start) { + regexp = ensureFlags(regexp, "g"); + for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { + regexp.lastIndex = ch; + var string = doc.getLine(line), + match = regexp.exec(string); + if (match) return { + from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match + }; } - const fieldName = typeInfo.fieldDef.name; - if (fieldName.slice(0, 2) !== "__") { - renderType(into, typeInfo, options, typeInfo.parentType); - text(into, "."); + } + function searchRegexpForwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start); + regexp = ensureFlags(regexp, "gm"); + var string, + chunk = 1; + for (var line = start.line, last = doc.lastLine(); line <= last;) { + for (var i = 0; i < chunk; i++) { + if (line > last) break; + var curLine = doc.getLine(line++); + string = string == null ? curLine : string + "\n" + curLine; + } + chunk = chunk * 2; + regexp.lastIndex = start.ch; + var match = regexp.exec(string); + if (match) { + var before = string.slice(0, match.index).split("\n"), + inside = match[0].split("\n"); + var startLine = start.line + before.length - 1, + startCh = before[before.length - 1].length; + return { + from: Pos(startLine, startCh), + to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), + match + }; + } } - text(into, fieldName); } - function renderDirective(into, typeInfo, _options) { - if (!typeInfo.directiveDef) { - return; + function lastMatchIn(string, regexp, endMargin) { + var match, + from = 0; + while (from <= string.length) { + regexp.lastIndex = from; + var newMatch = regexp.exec(string); + if (!newMatch) break; + var end = newMatch.index + newMatch[0].length; + if (end > string.length - endMargin) break; + if (!match || end > match.index + match[0].length) match = newMatch; + from = newMatch.index + 1; } - const name = "@" + typeInfo.directiveDef.name; - text(into, name); + return match; } - function renderArg(into, typeInfo, options) { - if (typeInfo.directiveDef) { - renderDirective(into, typeInfo, options); - } else if (typeInfo.fieldDef) { - renderQualifiedField(into, typeInfo, options); + function searchRegexpBackward(doc, regexp, start) { + regexp = ensureFlags(regexp, "g"); + for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { + var string = doc.getLine(line); + var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch); + if (match) return { + from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match + }; } - if (!typeInfo.argDef) { - return; + } + function searchRegexpBackwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start); + regexp = ensureFlags(regexp, "gm"); + var string, + chunkSize = 1, + endMargin = doc.getLine(start.line).length - start.ch; + for (var line = start.line, first = doc.firstLine(); line >= first;) { + for (var i = 0; i < chunkSize && line >= first; i++) { + var curLine = doc.getLine(line--); + string = string == null ? curLine : curLine + "\n" + string; + } + chunkSize *= 2; + var match = lastMatchIn(string, regexp, endMargin); + if (match) { + var before = string.slice(0, match.index).split("\n"), + inside = match[0].split("\n"); + var startLine = line + before.length, + startCh = before[before.length - 1].length; + return { + from: Pos(startLine, startCh), + to: Pos(startLine + inside.length - 1, inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), + match + }; + } } - const { name } = typeInfo.argDef; - text(into, "("); - text(into, name); - renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType); - text(into, ")"); } - function renderTypeAnnotation(into, typeInfo, options, t) { - text(into, ": "); - renderType(into, typeInfo, options, t); + var doFold, noFold; + if (String.prototype.normalize) { + doFold = function (str) { + return str.normalize("NFD").toLowerCase(); + }; + noFold = function (str) { + return str.normalize("NFD"); + }; + } else { + doFold = function (str) { + return str.toLowerCase(); + }; + noFold = function (str) { + return str; + }; } - function renderEnumValue(into, typeInfo, options) { - if (!typeInfo.enumValue) { - return; + function adjustPos(orig, folded, pos, foldFunc) { + if (orig.length == folded.length) return pos; + for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { + if (min == max) return min; + var mid = min + max >> 1; + var len = foldFunc(orig.slice(0, mid)).length; + if (len == pos) return mid;else if (len > pos) max = mid;else min = mid + 1; + } + } + function searchStringForward(doc, query, start, caseFold) { + if (!query.length) return null; + var fold = caseFold ? doFold : noFold; + var lines = fold(query).split(/\r|\n\r?/); + search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { + var orig = doc.getLine(line).slice(ch), + string = fold(orig); + if (lines.length == 1) { + var found = string.indexOf(lines[0]); + if (found == -1) continue search; + var start = adjustPos(orig, string, found, fold) + ch; + return { + from: Pos(line, adjustPos(orig, string, found, fold) + ch), + to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch) + }; + } else { + var cutFrom = string.length - lines[0].length; + if (string.slice(cutFrom) != lines[0]) continue search; + for (var i = 1; i < lines.length - 1; i++) if (fold(doc.getLine(line + i)) != lines[i]) continue search; + var end = doc.getLine(line + lines.length - 1), + endString = fold(end), + lastLine = lines[lines.length - 1]; + if (endString.slice(0, lastLine.length) != lastLine) continue search; + return { + from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), + to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold)) + }; + } } - const { name } = typeInfo.enumValue; - renderType(into, typeInfo, options, typeInfo.inputType); - text(into, "."); - text(into, name); } - function renderType(into, typeInfo, options, t) { - if (!t) { - return; + function searchStringBackward(doc, query, start, caseFold) { + if (!query.length) return null; + var fold = caseFold ? doFold : noFold; + var lines = fold(query).split(/\r|\n\r?/); + search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { + var orig = doc.getLine(line); + if (ch > -1) orig = orig.slice(0, ch); + var string = fold(orig); + if (lines.length == 1) { + var found = string.lastIndexOf(lines[0]); + if (found == -1) continue search; + return { + from: Pos(line, adjustPos(orig, string, found, fold)), + to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold)) + }; + } else { + var lastLine = lines[lines.length - 1]; + if (string.slice(0, lastLine.length) != lastLine) continue search; + for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) if (fold(doc.getLine(start + i)) != lines[i]) continue search; + var top = doc.getLine(line + 1 - lines.length), + topString = fold(top); + if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search; + return { + from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), + to: Pos(line, adjustPos(orig, string, lastLine.length, fold)) + }; + } + } + } + function SearchCursor(doc, query, pos, options) { + this.atOccurrence = false; + this.afterEmptyMatch = false; + this.doc = doc; + pos = pos ? doc.clipPos(pos) : Pos(0, 0); + this.pos = { + from: pos, + to: pos + }; + var caseFold; + if (typeof options == "object") { + caseFold = options.caseFold; + } else { + caseFold = options; + options = null; } - if (t instanceof _graphql.GraphQLNonNull) { - renderType(into, typeInfo, options, t.ofType); - text(into, "!"); - } else if (t instanceof _graphql.GraphQLList) { - text(into, "["); - renderType(into, typeInfo, options, t.ofType); - text(into, "]"); + if (typeof query == "string") { + if (caseFold == null) caseFold = false; + this.matches = function (reverse, pos2) { + return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos2, caseFold); + }; } else { - text(into, t.name); + query = ensureFlags(query, "gm"); + if (!options || options.multiline !== false) this.matches = function (reverse, pos2) { + return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos2); + };else this.matches = function (reverse, pos2) { + return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos2); + }; } } - function renderDescription(into, options, def) { - if (!def) { - return; + SearchCursor.prototype = { + findNext: function () { + return this.find(false); + }, + findPrevious: function () { + return this.find(true); + }, + find: function (reverse) { + var head = this.doc.clipPos(reverse ? this.pos.from : this.pos.to); + if (this.afterEmptyMatch && this.atOccurrence) { + head = Pos(head.line, head.ch); + if (reverse) { + head.ch--; + if (head.ch < 0) { + head.line--; + head.ch = (this.doc.getLine(head.line) || "").length; + } + } else { + head.ch++; + if (head.ch > (this.doc.getLine(head.line) || "").length) { + head.ch = 0; + head.line++; + } + } + if (CodeMirror.cmpPos(head, this.doc.clipPos(head)) != 0) { + return this.atOccurrence = false; + } + } + var result = this.matches(reverse, head); + this.afterEmptyMatch = result && CodeMirror.cmpPos(result.from, result.to) == 0; + if (result) { + this.pos = result; + this.atOccurrence = true; + return this.pos.match || true; + } else { + var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0); + this.pos = { + from: end, + to: end + }; + return this.atOccurrence = false; + } + }, + from: function () { + if (this.atOccurrence) return this.pos.from; + }, + to: function () { + if (this.atOccurrence) return this.pos.to; + }, + replace: function (newText, origin) { + if (!this.atOccurrence) return; + var lines = CodeMirror.splitLines(newText); + this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin); + this.pos.to = Pos(this.pos.from.line + lines.length - 1, lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)); } - const description = - typeof def.description === "string" ? def.description : null; - if (description) { - text(into, "\n\n"); - text(into, description); + }; + CodeMirror.defineExtension("getSearchCursor", function (query, pos, caseFold) { + return new SearchCursor(this.doc, query, pos, caseFold); + }); + CodeMirror.defineDocExtension("getSearchCursor", function (query, pos, caseFold) { + return new SearchCursor(this, query, pos, caseFold); + }); + CodeMirror.defineExtension("selectMatches", function (query, caseFold) { + var ranges = []; + var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold); + while (cur.findNext()) { + if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break; + ranges.push({ + anchor: cur.from(), + head: cur.to() + }); } - renderDeprecation(into, options, def); - } - function renderDeprecation(into, _options, def) { - if (!def) { - return; + if (ranges.length) this.setSelections(ranges, 0); + }); + }); + })(); + return searchcursor.exports; + } + exports.requireSearchcursor = requireSearchcursor; + + /***/ }), + + /***/ "../../graphiql-react/dist/show-hint.cjs.js": + /*!**************************************************!*\ + !*** ../../graphiql-react/dist/show-hint.cjs.js ***! + \**************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } } - const reason = def.deprecationReason || null; - if (!reason) { - return; + } + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var showHint$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror()); + })(function (CodeMirror) { + var HINT_ELEMENT_CLASS = "CodeMirror-hint"; + var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; + CodeMirror.showHint = function (cm, getHints, options) { + if (!getHints) return cm.showHint(options); + if (options && options.async) getHints.async = true; + var newOpts = { + hint: getHints + }; + if (options) for (var prop in options) newOpts[prop] = options[prop]; + return cm.showHint(newOpts); + }; + CodeMirror.defineExtension("showHint", function (options) { + options = parseOptions(this, this.getCursor("start"), options); + var selections = this.listSelections(); + if (selections.length > 1) return; + if (this.somethingSelected()) { + if (!options.hint.supportsSelection) return; + for (var i = 0; i < selections.length; i++) if (selections[i].head.line != selections[i].anchor.line) return; + } + if (this.state.completionActive) this.state.completionActive.close(); + var completion = this.state.completionActive = new Completion(this, options); + if (!completion.options.hint) return; + CodeMirror.signal(this, "startCompletion", this); + completion.update(true); + }); + CodeMirror.defineExtension("closeHint", function () { + if (this.state.completionActive) this.state.completionActive.close(); + }); + function Completion(cm, options) { + this.cm = cm; + this.options = options; + this.widget = null; + this.debounce = 0; + this.tick = 0; + this.startPos = this.cm.getCursor("start"); + this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; + if (this.options.updateOnCursorActivity) { + var self = this; + cm.on("cursorActivity", this.activityFunc = function () { + self.cursorActivity(); + }); + } + } + var requestAnimationFrame = window.requestAnimationFrame || function (fn) { + return setTimeout(fn, 1e3 / 60); + }; + var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; + Completion.prototype = { + close: function () { + if (!this.active()) return; + this.cm.state.completionActive = null; + this.tick = null; + if (this.options.updateOnCursorActivity) { + this.cm.off("cursorActivity", this.activityFunc); + } + if (this.widget && this.data) CodeMirror.signal(this.data, "close"); + if (this.widget) this.widget.close(); + CodeMirror.signal(this.cm, "endCompletion", this.cm); + }, + active: function () { + return this.cm.state.completionActive == this; + }, + pick: function (data, i) { + var completion = data.list[i], + self = this; + this.cm.operation(function () { + if (completion.hint) completion.hint(self.cm, data, completion);else self.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); + CodeMirror.signal(data, "pick", completion); + self.cm.scrollIntoView(); + }); + if (this.options.closeOnPick) { + this.close(); + } + }, + cursorActivity: function () { + if (this.debounce) { + cancelAnimationFrame(this.debounce); + this.debounce = 0; + } + var identStart = this.startPos; + if (this.data) { + identStart = this.data.from; + } + var pos = this.cm.getCursor(), + line = this.cm.getLine(pos.line); + if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || pos.ch < identStart.ch || this.cm.somethingSelected() || !pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1))) { + this.close(); + } else { + var self = this; + this.debounce = requestAnimationFrame(function () { + self.update(); + }); + if (this.widget) this.widget.disable(); + } + }, + update: function (first) { + if (this.tick == null) return; + var self = this, + myTick = ++this.tick; + fetchHints(this.options.hint, this.cm, this.options, function (data) { + if (self.tick == myTick) self.finishUpdate(data, first); + }); + }, + finishUpdate: function (data, first) { + if (this.data) CodeMirror.signal(this.data, "update"); + var picked = this.widget && this.widget.picked || first && this.options.completeSingle; + if (this.widget) this.widget.close(); + this.data = data; + if (data && data.list.length) { + if (picked && data.list.length == 1) { + this.pick(data, 0); + } else { + this.widget = new Widget(this, data); + CodeMirror.signal(data, "shown"); + } } - text(into, "\n\n"); - text(into, "Deprecated: "); - text(into, reason); } - function text(into, content) { - into.push(content); + }; + function parseOptions(cm, pos, options) { + var editor = cm.options.hintOptions; + var out = {}; + for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; + if (editor) { + for (var prop in editor) if (editor[prop] !== void 0) out[prop] = editor[prop]; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/getOutline.js": - /*!******************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/getOutline.js ***! - \******************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getOutline = getOutline; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _utils = __webpack_require__( - /*! ../utils */ "../../graphql-language-service/esm/utils/index.js" - ); - const { INLINE_FRAGMENT } = _graphql.Kind; - const OUTLINEABLE_KINDS = { - Field: true, - OperationDefinition: true, - Document: true, - SelectionSet: true, - Name: true, - FragmentDefinition: true, - FragmentSpread: true, - InlineFragment: true, - ObjectTypeDefinition: true, - InputObjectTypeDefinition: true, - InterfaceTypeDefinition: true, - EnumTypeDefinition: true, - EnumValueDefinition: true, - InputValueDefinition: true, - FieldDefinition: true, + if (options) { + for (var prop in options) if (options[prop] !== void 0) out[prop] = options[prop]; + } + if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos); + return out; + } + function getText(completion) { + if (typeof completion == "string") return completion;else return completion.text; + } + function buildKeyMap(completion, handle) { + var baseMap = { + Up: function () { + handle.moveFocus(-1); + }, + Down: function () { + handle.moveFocus(1); + }, + PageUp: function () { + handle.moveFocus(-handle.menuSize() + 1, true); + }, + PageDown: function () { + handle.moveFocus(handle.menuSize() - 1, true); + }, + Home: function () { + handle.setFocus(0); + }, + End: function () { + handle.setFocus(handle.length - 1); + }, + Enter: handle.pick, + Tab: handle.pick, + Esc: handle.close }; - function getOutline(documentText) { - let ast; - try { - ast = (0, _graphql.parse)(documentText); - } catch (_a) { - return null; - } - const visitorFns = outlineTreeConverter(documentText); - const outlineTrees = (0, _graphql.visit)(ast, { - leave(node) { - if (visitorFns !== undefined && node.kind in visitorFns) { - return visitorFns[node.kind](node); - } - return null; - }, - }); - return { - outlineTrees, + var mac = /Mac/.test(navigator.platform); + if (mac) { + baseMap["Ctrl-P"] = function () { + handle.moveFocus(-1); + }; + baseMap["Ctrl-N"] = function () { + handle.moveFocus(1); }; } - function outlineTreeConverter(docText) { - const meta = (node) => { - return { - representativeName: node.name, - startPosition: (0, _utils.offsetToPosition)( - docText, - node.loc.start - ), - endPosition: (0, _utils.offsetToPosition)(docText, node.loc.end), - kind: node.kind, - children: - node.selectionSet || - node.fields || - node.values || - node.arguments || - [], - }; + var custom = completion.options.customKeys; + var ourMap = custom ? {} : baseMap; + function addBinding(key2, val) { + var bound; + if (typeof val != "string") bound = function (cm) { + return val(cm, handle); + };else if (baseMap.hasOwnProperty(val)) bound = baseMap[val];else bound = val; + ourMap[key2] = bound; + } + if (custom) { + for (var key in custom) if (custom.hasOwnProperty(key)) addBinding(key, custom[key]); + } + var extra = completion.options.extraKeys; + if (extra) { + for (var key in extra) if (extra.hasOwnProperty(key)) addBinding(key, extra[key]); + } + return ourMap; + } + function getHintElement(hintsElement, el) { + while (el && el != hintsElement) { + if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; + el = el.parentNode; + } + } + function Widget(completion, data) { + this.id = "cm-complete-" + Math.floor(Math.random(1e6)); + this.completion = completion; + this.data = data; + this.picked = false; + var widget = this, + cm = completion.cm; + var ownerDocument = cm.getInputField().ownerDocument; + var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow; + var hints = this.hints = ownerDocument.createElement("ul"); + hints.setAttribute("role", "listbox"); + hints.setAttribute("aria-expanded", "true"); + hints.id = this.id; + var theme = completion.cm.options.theme; + hints.className = "CodeMirror-hints " + theme; + this.selectedHint = data.selectedHint || 0; + var completions = data.list; + for (var i = 0; i < completions.length; ++i) { + var elt = hints.appendChild(ownerDocument.createElement("li")), + cur = completions[i]; + var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); + if (cur.className != null) className = cur.className + " " + className; + elt.className = className; + if (i == this.selectedHint) elt.setAttribute("aria-selected", "true"); + elt.id = this.id + "-" + i; + elt.setAttribute("role", "option"); + if (cur.render) cur.render(elt, data, cur);else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur))); + elt.hintId = i; + } + var container = completion.options.container || ownerDocument.body; + var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); + var left = pos.left, + top = pos.bottom, + below = true; + var offsetLeft = 0, + offsetTop = 0; + if (container !== ownerDocument.body) { + var isContainerPositioned = ["absolute", "relative", "fixed"].indexOf(parentWindow.getComputedStyle(container).position) !== -1; + var offsetParent = isContainerPositioned ? container : container.offsetParent; + var offsetParentPosition = offsetParent.getBoundingClientRect(); + var bodyPosition = ownerDocument.body.getBoundingClientRect(); + offsetLeft = offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft; + offsetTop = offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop; + } + hints.style.left = left - offsetLeft + "px"; + hints.style.top = top - offsetTop + "px"; + var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth); + var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight); + container.appendChild(hints); + cm.getInputField().setAttribute("aria-autocomplete", "list"); + cm.getInputField().setAttribute("aria-owns", this.id); + cm.getInputField().setAttribute("aria-activedescendant", this.id + "-" + this.selectedHint); + var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect(); + var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false; + var startScroll; + setTimeout(function () { + startScroll = cm.getScrollInfo(); + }); + var overlapY = box.bottom - winH; + if (overlapY > 0) { + var height = box.bottom - box.top, + curTop = pos.top - (pos.bottom - box.top); + if (curTop - height > 0) { + hints.style.top = (top = pos.top - height - offsetTop) + "px"; + below = false; + } else if (height > winH) { + hints.style.height = winH - 5 + "px"; + hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px"; + var cursor = cm.getCursor(); + if (data.from.ch != cursor.ch) { + pos = cm.cursorCoords(cursor); + hints.style.left = (left = pos.left - offsetLeft) + "px"; + box = hints.getBoundingClientRect(); + } + } + } + var overlapX = box.right - winW; + if (scrolls) overlapX += cm.display.nativeBarWidth; + if (overlapX > 0) { + if (box.right - box.left > winW) { + hints.style.width = winW - 5 + "px"; + overlapX -= box.right - box.left - winW; + } + hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px"; + } + if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling) node.style.paddingRight = cm.display.nativeBarWidth + "px"; + cm.addKeyMap(this.keyMap = buildKeyMap(completion, { + moveFocus: function (n, avoidWrap) { + widget.changeActive(widget.selectedHint + n, avoidWrap); + }, + setFocus: function (n) { + widget.changeActive(n); + }, + menuSize: function () { + return widget.screenAmount(); + }, + length: completions.length, + close: function () { + completion.close(); + }, + pick: function () { + widget.pick(); + }, + data + })); + if (completion.options.closeOnUnfocus) { + var closingOnBlur; + cm.on("blur", this.onBlur = function () { + closingOnBlur = setTimeout(function () { + completion.close(); + }, 100); + }); + cm.on("focus", this.onFocus = function () { + clearTimeout(closingOnBlur); + }); + } + cm.on("scroll", this.onScroll = function () { + var curScroll = cm.getScrollInfo(), + editor = cm.getWrapperElement().getBoundingClientRect(); + if (!startScroll) startScroll = cm.getScrollInfo(); + var newTop = top + startScroll.top - curScroll.top; + var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop); + if (!below) point += hints.offsetHeight; + if (point <= editor.top || point >= editor.bottom) return completion.close(); + hints.style.top = newTop + "px"; + hints.style.left = left + startScroll.left - curScroll.left + "px"; + }); + CodeMirror.on(hints, "dblclick", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + widget.pick(); + } + }); + CodeMirror.on(hints, "click", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + if (completion.options.completeOnSingleClick) widget.pick(); + } + }); + CodeMirror.on(hints, "mousedown", function () { + setTimeout(function () { + cm.focus(); + }, 20); + }); + var selectedHintRange = this.getSelectedHintRange(); + if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) { + this.scrollToActive(); + } + CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]); + return true; + } + Widget.prototype = { + close: function () { + if (this.completion.widget != this) return; + this.completion.widget = null; + if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints); + this.completion.cm.removeKeyMap(this.keyMap); + var input = this.completion.cm.getInputField(); + input.removeAttribute("aria-activedescendant"); + input.removeAttribute("aria-owns"); + var cm = this.completion.cm; + if (this.completion.options.closeOnUnfocus) { + cm.off("blur", this.onBlur); + cm.off("focus", this.onFocus); + } + cm.off("scroll", this.onScroll); + }, + disable: function () { + this.completion.cm.removeKeyMap(this.keyMap); + var widget = this; + this.keyMap = { + Enter: function () { + widget.picked = true; + } }; + this.completion.cm.addKeyMap(this.keyMap); + }, + pick: function () { + this.completion.pick(this.data, this.selectedHint); + }, + changeActive: function (i, avoidWrap) { + if (i >= this.data.list.length) i = avoidWrap ? this.data.list.length - 1 : 0;else if (i < 0) i = avoidWrap ? 0 : this.data.list.length - 1; + if (this.selectedHint == i) return; + var node = this.hints.childNodes[this.selectedHint]; + if (node) { + node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); + node.removeAttribute("aria-selected"); + } + node = this.hints.childNodes[this.selectedHint = i]; + node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; + node.setAttribute("aria-selected", "true"); + this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id); + this.scrollToActive(); + CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); + }, + scrollToActive: function () { + var selectedHintRange = this.getSelectedHintRange(); + var node1 = this.hints.childNodes[selectedHintRange.from]; + var node2 = this.hints.childNodes[selectedHintRange.to]; + var firstNode = this.hints.firstChild; + if (node1.offsetTop < this.hints.scrollTop) this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop; + }, + screenAmount: function () { + return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; + }, + getSelectedHintRange: function () { + var margin = this.completion.options.scrollMargin || 0; return { - Field(node) { - const tokenizedText = node.alias - ? [buildToken("plain", node.alias), buildToken("plain", ": ")] - : []; - tokenizedText.push(buildToken("plain", node.name)); - return Object.assign( - { - tokenizedText, - }, - meta(node) - ); - }, - OperationDefinition: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("keyword", node.operation), - buildToken("whitespace", " "), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - Document: (node) => node.definitions, - SelectionSet: (node) => - concatMap(node.selections, (child) => { - return child.kind === INLINE_FRAGMENT - ? child.selectionSet - : child; - }), - Name: (node) => node.value, - FragmentDefinition: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("keyword", "fragment"), - buildToken("whitespace", " "), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - InterfaceTypeDefinition: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("keyword", "interface"), - buildToken("whitespace", " "), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - EnumTypeDefinition: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("keyword", "enum"), - buildToken("whitespace", " "), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - EnumValueDefinition: (node) => - Object.assign( - { - tokenizedText: [buildToken("plain", node.name)], - }, - meta(node) - ), - ObjectTypeDefinition: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("keyword", "type"), - buildToken("whitespace", " "), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - InputObjectTypeDefinition: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("keyword", "input"), - buildToken("whitespace", " "), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - FragmentSpread: (node) => - Object.assign( - { - tokenizedText: [ - buildToken("plain", "..."), - buildToken("class-name", node.name), - ], - }, - meta(node) - ), - InputValueDefinition(node) { - return Object.assign( - { - tokenizedText: [buildToken("plain", node.name)], - }, - meta(node) - ); - }, - FieldDefinition(node) { - return Object.assign( - { - tokenizedText: [buildToken("plain", node.name)], - }, - meta(node) - ); - }, - InlineFragment: (node) => node.selectionSet, + from: Math.max(0, this.selectedHint - margin), + to: Math.min(this.data.list.length - 1, this.selectedHint + margin) }; } - function buildToken(kind, value) { - return { - kind, - value, + }; + function applicableHelpers(cm, helpers) { + if (!cm.somethingSelected()) return helpers; + var result = []; + for (var i = 0; i < helpers.length; i++) if (helpers[i].supportsSelection) result.push(helpers[i]); + return result; + } + function fetchHints(hint, cm, options, callback) { + if (hint.async) { + hint(cm, callback, options); + } else { + var result = hint(cm, options); + if (result && result.then) result.then(callback);else callback(result); + } + } + function resolveAutoHints(cm, pos) { + var helpers = cm.getHelpers(pos, "hint"), + words; + if (helpers.length) { + var resolved = function (cm2, callback, options) { + var app = applicableHelpers(cm2, helpers); + function run(i) { + if (i == app.length) return callback(null); + fetchHints(app[i], cm2, options, function (result) { + if (result && result.list.length > 0) callback(result);else run(i + 1); + }); + } + run(0); + }; + resolved.async = true; + resolved.supportsSelection = true; + return resolved; + } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { + return function (cm2) { + return CodeMirror.hint.fromList(cm2, { + words + }); }; + } else if (CodeMirror.hint.anyword) { + return function (cm2, options) { + return CodeMirror.hint.anyword(cm2, options); + }; + } else { + return function () {}; } - function concatMap(arr, fn) { - const res = []; - for (let i = 0; i < arr.length; i++) { - const x = fn(arr[i], i); - if (Array.isArray(x)) { - res.push(...x); - } else { - res.push(x); + } + CodeMirror.registerHelper("hint", "auto", { + resolve: resolveAutoHints + }); + CodeMirror.registerHelper("hint", "fromList", function (cm, options) { + var cur = cm.getCursor(), + token = cm.getTokenAt(cur); + var term, + from = CodeMirror.Pos(cur.line, token.start), + to = cur; + if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) { + term = token.string.substr(0, cur.ch - token.start); + } else { + term = ""; + from = cur; + } + var found = []; + for (var i = 0; i < options.words.length; i++) { + var word = options.words[i]; + if (word.slice(0, term.length) == term) found.push(word); + } + if (found.length) return { + list: found, + from, + to + }; + }); + CodeMirror.commands.autocomplete = CodeMirror.showHint; + var defaultOptions = { + hint: CodeMirror.hint.auto, + completeSingle: true, + alignWithWord: true, + closeCharacters: /[\s()\[\]{};:>,]/, + closeOnPick: true, + closeOnUnfocus: true, + updateOnCursorActivity: true, + completeOnSingleClick: true, + container: null, + customKeys: null, + extraKeys: null, + paddingForScrollbar: true, + moveOnOverlap: true + }; + CodeMirror.defineOption("hintOptions", null); + }); + })(); + var showHintExports = showHint$2.exports; + const showHint = /* @__PURE__ */codemirror.getDefaultExportFromCjs(showHintExports); + const showHint$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: showHint + }, [showHintExports]); + exports.showHint = showHint$1; + + /***/ }), + + /***/ "../../graphiql-react/dist/sublime.cjs.js": + /*!************************************************!*\ + !*** ../../graphiql-react/dist/sublime.cjs.js ***! + \************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + const codemirror = __webpack_require__(/*! ./codemirror.cjs2.js */ "../../graphiql-react/dist/codemirror.cjs2.js"); + const searchcursor = __webpack_require__(/*! ./searchcursor.cjs2.js */ "../../graphiql-react/dist/searchcursor.cjs2.js"); + const matchbrackets = __webpack_require__(/*! ./matchbrackets.cjs2.js */ "../../graphiql-react/dist/matchbrackets.cjs2.js"); + function _mergeNamespaces(n, m) { + for (var i = 0; i < m.length; i++) { + const e = m[i]; + if (typeof e !== "string" && !Array.isArray(e)) { + for (const k in e) { + if (k !== "default" && !(k in n)) { + const d = Object.getOwnPropertyDescriptor(e, k); + if (d) { + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); } } - return res; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/interface/index.js": - /*!*************************************************************!*\ - !*** ../../graphql-language-service/esm/interface/index.js ***! - \*************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var _exportNames = { - getOutline: true, - getHoverInformation: true, - }; - Object.defineProperty(exports, "getHoverInformation", { - enumerable: true, - get: function () { - return _getHoverInformation.getHoverInformation; - }, - }); - Object.defineProperty(exports, "getOutline", { - enumerable: true, - get: function () { - return _getOutline.getOutline; - }, - }); - var _autocompleteUtils = __webpack_require__( - /*! ./autocompleteUtils */ "../../graphql-language-service/esm/interface/autocompleteUtils.js" - ); - Object.keys(_autocompleteUtils).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _autocompleteUtils[key]) - return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _autocompleteUtils[key]; - }, - }); - }); - var _getAutocompleteSuggestions = __webpack_require__( - /*! ./getAutocompleteSuggestions */ "../../graphql-language-service/esm/interface/getAutocompleteSuggestions.js" - ); - Object.keys(_getAutocompleteSuggestions).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if ( - key in exports && - exports[key] === _getAutocompleteSuggestions[key] - ) - return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getAutocompleteSuggestions[key]; - }, - }); - }); - var _getDefinition = __webpack_require__( - /*! ./getDefinition */ "../../graphql-language-service/esm/interface/getDefinition.js" - ); - Object.keys(_getDefinition).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getDefinition[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getDefinition[key]; - }, - }); - }); - var _getDiagnostics = __webpack_require__( - /*! ./getDiagnostics */ "../../graphql-language-service/esm/interface/getDiagnostics.js" - ); - Object.keys(_getDiagnostics).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _getDiagnostics[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _getDiagnostics[key]; - }, - }); + } + } + return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { + value: "Module" + })); + } + var sublime$2 = { + exports: {} + }; + (function (module2, exports2) { + (function (mod) { + mod(codemirror.requireCodemirror(), searchcursor.requireSearchcursor(), matchbrackets.requireMatchbrackets()); + })(function (CodeMirror) { + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); + var line = doc.getLine(start.line); + if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); + var state = "start", + type, + startPos = start.ch; + for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { + var next = line.charAt(dir < 0 ? pos - 1 : pos); + var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { + state = "in"; + type = cat; + } else startPos = pos + dir; + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { + if (pos == startPos + 1) { + type = "w"; + continue; + } else pos--; + } + break; + } + } + } + return Pos(start.line, pos); + } + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function (range) { + if (cm.display.shift || cm.doc.extend || range.empty()) return findPosSubword(cm.doc, range.head, dir);else return dir < 0 ? range.from() : range.to(); }); - var _getOutline = __webpack_require__( - /*! ./getOutline */ "../../graphql-language-service/esm/interface/getOutline.js" - ); - var _getHoverInformation = __webpack_require__( - /*! ./getHoverInformation */ "../../graphql-language-service/esm/interface/getHoverInformation.js" - ); - - /***/ - }, - - /***/ "../../graphql-language-service/esm/parser/CharacterStream.js": - /*!********************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/CharacterStream.js ***! - \********************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, + } + cmds.goSubwordLeft = function (cm) { + moveSubword(cm, -1); + }; + cmds.goSubwordRight = function (cm) { + moveSubword(cm, 1); + }; + cmds.scrollLineUp = function (cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); + if (cm.getCursor().line >= visibleBottomLine) cm.execCommand("goLineUp"); + } + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds.scrollLineDown = function (cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local") + 1; + if (cm.getCursor().line <= visibleTopLine) cm.execCommand("goLineDown"); + } + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + cmds.splitSelectionByLine = function (cm) { + var ranges = cm.listSelections(), + lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), + to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) if (!(to.line > from.line && line == to.line && to.ch == 0)) lineRanges.push({ + anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line) + }); + } + cm.setSelections(lineRanges, 0); + }; + cmds.singleSelectionTop = function (cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, { + scroll: false + }); + }; + cmds.selectLine = function (cm) { + var ranges = cm.listSelections(), + extended = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + extended.push({ + anchor: Pos(range.from().line, 0), + head: Pos(range.to().line + 1, 0) + }); + } + cm.setSelections(extended); + }; + function insertLine(cm, above) { + if (cm.isReadOnly()) return CodeMirror.Pass; + cm.operation(function () { + var len = cm.listSelections().length, + newSelection = [], + last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({ + head: at, + anchor: at + }); + last = head.line + 1; + } + cm.setSelections(newSelection); }); - exports["default"] = void 0; - class CharacterStream { - constructor(sourceText) { - this._start = 0; - this._pos = 0; - this.getStartOfToken = () => this._start; - this.getCurrentPosition = () => this._pos; - this.eol = () => this._sourceText.length === this._pos; - this.sol = () => this._pos === 0; - this.peek = () => { - return this._sourceText.charAt(this._pos) || null; - }; - this.next = () => { - const char = this._sourceText.charAt(this._pos); - this._pos++; - return char; - }; - this.eat = (pattern) => { - const isMatched = this._testNextCharacter(pattern); - if (isMatched) { - this._start = this._pos; - this._pos++; - return this._sourceText.charAt(this._pos - 1); - } - return undefined; - }; - this.eatWhile = (match) => { - let isMatched = this._testNextCharacter(match); - let didEat = false; - if (isMatched) { - didEat = isMatched; - this._start = this._pos; - } - while (isMatched) { - this._pos++; - isMatched = this._testNextCharacter(match); - didEat = true; - } - return didEat; - }; - this.eatSpace = () => this.eatWhile(/[\s\u00a0]/); - this.skipToEnd = () => { - this._pos = this._sourceText.length; - }; - this.skipTo = (position) => { - this._pos = position; - }; - this.match = (pattern, consume = true, caseFold = false) => { - let token = null; - let match = null; - if (typeof pattern === "string") { - const regex = new RegExp(pattern, caseFold ? "i" : "g"); - match = regex.test( - this._sourceText.slice(this._pos, this._pos + pattern.length) - ); - token = pattern; - } else if (pattern instanceof RegExp) { - match = this._sourceText.slice(this._pos).match(pattern); - token = match === null || match === void 0 ? void 0 : match[0]; - } - if ( - match != null && - (typeof pattern === "string" || - (match instanceof Array && - this._sourceText.startsWith(match[0], this._pos))) - ) { - if (consume) { - this._start = this._pos; - if (token && token.length) { - this._pos += token.length; - } - } - return match; - } - return false; - }; - this.backUp = (num) => { - this._pos -= num; - }; - this.column = () => this._pos; - this.indentation = () => { - const match = this._sourceText.match(/\s*/); - let indent = 0; - if (match && match.length !== 0) { - const whiteSpaces = match[0]; - let pos = 0; - while (whiteSpaces.length > pos) { - if (whiteSpaces.charCodeAt(pos) === 9) { - indent += 2; - } else { - indent++; - } - pos++; - } + cm.execCommand("indentAuto"); + } + cmds.insertLineAfter = function (cm) { + return insertLine(cm, false); + }; + cmds.insertLineBefore = function (cm) { + return insertLine(cm, true); + }; + function wordAt(cm, pos) { + var start = pos.ch, + end = start, + line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; + while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; + return { + from: Pos(pos.line, start), + to: Pos(pos.line, end), + word: line.slice(start, end) + }; + } + cmds.selectNextOccurrence = function (cm) { + var from = cm.getCursor("from"), + to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + var found = cur.findNext(); + if (!found) { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + found = cur.findNext(); + } + if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return; + cm.addSelection(cur.from(), cur.to()); + } + if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; + }; + cmds.skipAndSelectNextOccurrence = function (cm) { + var prevAnchor = cm.getCursor("anchor"), + prevHead = cm.getCursor("head"); + cmds.selectNextOccurrence(cm); + if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) { + cm.doc.setSelections(cm.doc.listSelections().filter(function (sel) { + return sel.anchor != prevAnchor || sel.head != prevHead; + })); + } + }; + function addCursorToSelection(cm, dir) { + var ranges = cm.listSelections(), + newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var newAnchor = cm.findPosV(range.anchor, dir, "line", range.anchor.goalColumn); + var newHead = cm.findPosV(range.head, dir, "line", range.head.goalColumn); + newAnchor.goalColumn = range.anchor.goalColumn != null ? range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left; + newHead.goalColumn = range.head.goalColumn != null ? range.head.goalColumn : cm.cursorCoords(range.head, "div").left; + var newRange = { + anchor: newAnchor, + head: newHead + }; + newRanges.push(range); + newRanges.push(newRange); + } + cm.setSelections(newRanges); + } + cmds.addCursorToPrevLine = function (cm) { + addCursorToSelection(cm, -1); + }; + cmds.addCursorToNextLine = function (cm) { + addCursorToSelection(cm, 1); + }; + function isSelectedRange(ranges, from, to) { + for (var i = 0; i < ranges.length; i++) if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 && CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true; + return false; + } + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var ranges = cm.listSelections(), + newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + pos = range.head, + opening = cm.scanForBracket(pos, -1); + if (!opening) return false; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return false; + if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { + var startPos = Pos(opening.pos.line, opening.pos.ch + 1); + if (CodeMirror.cmpPos(startPos, range.from()) == 0 && CodeMirror.cmpPos(closing.pos, range.to()) == 0) { + opening = cm.scanForBracket(opening.pos, -1); + if (!opening) return false; + } else { + newRanges.push({ + anchor: startPos, + head: closing.pos + }); + break; } - return indent; - }; - this.current = () => this._sourceText.slice(this._start, this._pos); - this._sourceText = sourceText; - } - _testNextCharacter(pattern) { - const character = this._sourceText.charAt(this._pos); - let isMatched = false; - if (typeof pattern === "string") { - isMatched = character === pattern; - } else { - isMatched = - pattern instanceof RegExp - ? pattern.test(character) - : pattern(character); } - return isMatched; + pos = Pos(closing.pos.line, closing.pos.ch + 1); } } - exports["default"] = CharacterStream; - - /***/ - }, - - /***/ "../../graphql-language-service/esm/parser/RuleHelpers.js": - /*!****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/RuleHelpers.js ***! - \****************************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, + cm.setSelections(newRanges); + return true; + } + cmds.selectScope = function (cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds.selectBetweenBrackets = function (cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + function puncType(type) { + return !type ? null : /\bpunctuation\b/.test(type) ? type : void 0; + } + cmds.goToBracket = function (cm) { + cm.extendSelectionsBy(function (range) { + var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head))); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; + var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1)))); + return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; + }); + }; + cmds.swapLineUp = function (cm) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + linesToMove = [], + at = cm.firstLine() - 1, + newSels = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + from = range.from().line - 1, + to = range.to().line; + newSels.push({ + anchor: Pos(range.anchor.line - 1, range.anchor.ch), + head: Pos(range.head.line - 1, range.head.ch) + }); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function () { + for (var i2 = 0; i2 < linesToMove.length; i2 += 2) { + var from2 = linesToMove[i2], + to2 = linesToMove[i2 + 1]; + var line = cm.getLine(from2); + cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); + if (to2 > cm.lastLine()) cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");else cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); + } + cm.setSelections(newSels); + cm.scrollIntoView(); + }); + }; + cmds.swapLineDown = function (cm) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + linesToMove = [], + at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], + from = range.to().line + 1, + to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to);else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; + at = to; + } + cm.operation(function () { + for (var i2 = linesToMove.length - 2; i2 >= 0; i2 -= 2) { + var from2 = linesToMove[i2], + to2 = linesToMove[i2 + 1]; + var line = cm.getLine(from2); + if (from2 == cm.lastLine()) cm.replaceRange("", Pos(from2 - 1), Pos(from2), "+swapLine");else cm.replaceRange("", Pos(from2, 0), Pos(from2 + 1, 0), "+swapLine"); + cm.replaceRange(line + "\n", Pos(to2, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + cmds.toggleCommentIndented = function (cm) { + cm.toggleComment({ + indent: true + }); + }; + cmds.joinLines = function (cm) { + var ranges = cm.listSelections(), + joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], + from = range.from(); + var start = from.line, + end = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == end) end = ranges[++i].to().line; + joined.push({ + start, + end, + anchor: !range.empty() && from + }); + } + cm.operation(function () { + var offset = 0, + ranges2 = []; + for (var i2 = 0; i2 < joined.length; i2++) { + var obj = joined[i2]; + var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), + head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); + if (actual < cm.lastLine()) { + cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); + ++offset; + } + } + ranges2.push({ + anchor: anchor || head, + head + }); + } + cm.setSelections(ranges2, 0); + }); + }; + cmds.duplicateLine = function (cm) { + cm.operation(function () { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));else cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + } + cm.scrollIntoView(); + }); + }; + function sortLines(cm, caseSensitive, direction) { + if (cm.isReadOnly()) return CodeMirror.Pass; + var ranges = cm.listSelections(), + toSort = [], + selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, + to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) to = ranges[++i].to().line; + if (!ranges[i].to().ch) to--; + toSort.push(from, to); + } + if (toSort.length) selected = true;else toSort.push(cm.firstLine(), cm.lastLine()); + cm.operation(function () { + var ranges2 = []; + for (var i2 = 0; i2 < toSort.length; i2 += 2) { + var from2 = toSort[i2], + to2 = toSort[i2 + 1]; + var start = Pos(from2, 0), + end = Pos(to2); + var lines = cm.getRange(start, end, false); + if (caseSensitive) lines.sort(function (a, b) { + return a < b ? -direction : a == b ? 0 : direction; + });else lines.sort(function (a, b) { + var au = a.toUpperCase(), + bu = b.toUpperCase(); + if (au != bu) { + a = au; + b = bu; + } + return a < b ? -direction : a == b ? 0 : direction; + }); + cm.replaceRange(lines, start, end); + if (selected) ranges2.push({ + anchor: start, + head: Pos(to2 + 1, 0) + }); + } + if (selected) cm.setSelections(ranges2, 0); }); - exports.butNot = butNot; - exports.list = list; - exports.opt = opt; - exports.p = p; - exports.t = t; - function opt(ofRule) { - return { - ofRule, - }; + } + cmds.sortLines = function (cm) { + sortLines(cm, true, 1); + }; + cmds.reverseSortLines = function (cm) { + sortLines(cm, true, -1); + }; + cmds.sortLinesInsensitive = function (cm) { + sortLines(cm, false, 1); + }; + cmds.reverseSortLinesInsensitive = function (cm) { + sortLines(cm, false, -1); + }; + cmds.nextBookmark = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); + } + } + }; + cmds.prevBookmark = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) marks.pop();else return cm.setSelection(found.from, found.to); + } + }; + cmds.toggleBookmark = function (cm) { + var ranges = cm.listSelections(); + var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), + to = ranges[i].to(); + var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) if (marks[k] == found[j]) marks.splice(k--, 1); + break; + } + } + if (j == found.length) marks.push(cm.markText(from, to, { + sublimeBookmark: true, + clearWhenEmpty: false + })); } - function list(ofRule, separator) { - return { - ofRule, - isList: true, - separator, - }; + }; + cmds.clearBookmarks = function (cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); + marks.length = 0; + }; + cmds.selectBookmarks = function (cm) { + var marks = cm.state.sublimeBookmarks, + ranges = []; + if (marks) for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) marks.splice(i--, 0);else ranges.push({ + anchor: found.from, + head: found.to + }); + } + if (ranges.length) cm.setSelections(ranges, 0); + }; + function modifyWordOrSelection(cm, mod) { + cm.operation(function () { + var ranges = cm.listSelections(), + indices = [], + replacements = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) { + indices.push(i); + replacements.push(""); + } else replacements.push(mod(cm.getRange(range.from(), range.to()))); + } + cm.replaceSelections(replacements, "around", "case"); + for (var i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); + } + cmds.smartBackspace = function (cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + cm.operation(function () { + var cursors = cm.listSelections(); + var indentUnit = cm.getOption("indentUnit"); + for (var i = cursors.length - 1; i >= 0; i--) { + var cursor = cursors[i].head; + var toStartOfLine = cm.getRange({ + line: cursor.line, + ch: 0 + }, cursor); + var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); + var deletePos = cm.findPosH(cursor, -1, "char", false); + if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { + var prevIndent = new Pos(cursor.line, CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); + if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + } + cm.replaceRange("", deletePos, cursor, "+delete"); + } + }); + }; + cmds.delLineRight = function (cm) { + cm.operation(function () { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); + cm.scrollIntoView(); + }); + }; + cmds.upcaseAtCursor = function (cm) { + modifyWordOrSelection(cm, function (str) { + return str.toUpperCase(); + }); + }; + cmds.downcaseAtCursor = function (cm) { + modifyWordOrSelection(cm, function (str) { + return str.toLowerCase(); + }); + }; + cmds.setSublimeMark = function (cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds.selectToSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds.deleteToSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + var from = cm.getCursor(), + to = found; + if (CodeMirror.cmpPos(from, to) > 0) { + var tmp = to; + to = from; + from = tmp; + } + cm.state.sublimeKilled = cm.getRange(from, to); + cm.replaceRange("", from, to); + } + }; + cmds.swapWithSublimeMark = function (cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) { + cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + cm.setCursor(found); + } + }; + cmds.sublimeYank = function (cm) { + if (cm.state.sublimeKilled != null) cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + cmds.showInCenter = function (cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + function getTarget(cm) { + var from = cm.getCursor("from"), + to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + from = word.from; + to = word.to; + } + return { + from, + to, + query: cm.getRange(from, to), + word + }; + } + function findAndGoTo(cm, forward) { + var target = getTarget(cm); + if (!target) return; + var query = target.query; + var cur = cm.getSearchCursor(query, forward ? target.to : target.from); + if (forward ? cur.findNext() : cur.findPrevious()) { + cm.setSelection(cur.from(), cur.to()); + } else { + cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) : cm.clipPos(Pos(cm.lastLine()))); + if (forward ? cur.findNext() : cur.findPrevious()) cm.setSelection(cur.from(), cur.to());else if (target.word) cm.setSelection(target.from, target.to); } - function butNot(rule, exclusions) { - const ruleMatch = rule.match; - rule.match = (token) => { - let check = false; - if (ruleMatch) { - check = ruleMatch(token); - } - return ( - check && - exclusions.every( - (exclusion) => exclusion.match && !exclusion.match(token) - ) - ); - }; - return rule; + } + cmds.findUnder = function (cm) { + findAndGoTo(cm, true); + }; + cmds.findUnderPrevious = function (cm) { + findAndGoTo(cm, false); + }; + cmds.findAllUnder = function (cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({ + anchor: cur.from(), + head: cur.to() + }); + if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) primaryIndex++; + } + cm.setSelections(matches, primaryIndex); + }; + var keyMap = CodeMirror.keyMap; + keyMap.macSublime = { + "Cmd-Left": "goLineStartSmart", + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Ctrl-Alt-Up": "scrollLineUp", + "Ctrl-Alt-Down": "scrollLineDown", + "Cmd-L": "selectLine", + "Shift-Cmd-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Cmd-Enter": "insertLineAfter", + "Shift-Cmd-Enter": "insertLineBefore", + "Cmd-D": "selectNextOccurrence", + "Shift-Cmd-Space": "selectScope", + "Shift-Cmd-M": "selectBetweenBrackets", + "Cmd-M": "goToBracket", + "Cmd-Ctrl-Up": "swapLineUp", + "Cmd-Ctrl-Down": "swapLineDown", + "Cmd-/": "toggleCommentIndented", + "Cmd-J": "joinLines", + "Shift-Cmd-D": "duplicateLine", + "F5": "sortLines", + "Shift-F5": "reverseSortLines", + "Cmd-F5": "sortLinesInsensitive", + "Shift-Cmd-F5": "reverseSortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Cmd-F2": "toggleBookmark", + "Shift-Cmd-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Cmd-K Cmd-D": "skipAndSelectNextOccurrence", + "Cmd-K Cmd-K": "delLineRight", + "Cmd-K Cmd-U": "upcaseAtCursor", + "Cmd-K Cmd-L": "downcaseAtCursor", + "Cmd-K Cmd-Space": "setSublimeMark", + "Cmd-K Cmd-A": "selectToSublimeMark", + "Cmd-K Cmd-W": "deleteToSublimeMark", + "Cmd-K Cmd-X": "swapWithSublimeMark", + "Cmd-K Cmd-Y": "sublimeYank", + "Cmd-K Cmd-C": "showInCenter", + "Cmd-K Cmd-G": "clearBookmarks", + "Cmd-K Cmd-Backspace": "delLineLeft", + "Cmd-K Cmd-1": "foldAll", + "Cmd-K Cmd-0": "unfoldAll", + "Cmd-K Cmd-J": "unfoldAll", + "Ctrl-Shift-Up": "addCursorToPrevLine", + "Ctrl-Shift-Down": "addCursorToNextLine", + "Cmd-F3": "findUnder", + "Shift-Cmd-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Cmd-[": "fold", + "Shift-Cmd-]": "unfold", + "Cmd-I": "findIncremental", + "Shift-Cmd-I": "findIncrementalReverse", + "Cmd-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "macDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.macSublime); + keyMap.pcSublime = { + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-T": "transposeChars", + "Alt-Left": "goSubwordLeft", + "Alt-Right": "goSubwordRight", + "Ctrl-Up": "scrollLineUp", + "Ctrl-Down": "scrollLineDown", + "Ctrl-L": "selectLine", + "Shift-Ctrl-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Ctrl-Enter": "insertLineAfter", + "Shift-Ctrl-Enter": "insertLineBefore", + "Ctrl-D": "selectNextOccurrence", + "Shift-Ctrl-Space": "selectScope", + "Shift-Ctrl-M": "selectBetweenBrackets", + "Ctrl-M": "goToBracket", + "Shift-Ctrl-Up": "swapLineUp", + "Shift-Ctrl-Down": "swapLineDown", + "Ctrl-/": "toggleCommentIndented", + "Ctrl-J": "joinLines", + "Shift-Ctrl-D": "duplicateLine", + "F9": "sortLines", + "Shift-F9": "reverseSortLines", + "Ctrl-F9": "sortLinesInsensitive", + "Shift-Ctrl-F9": "reverseSortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Ctrl-F2": "toggleBookmark", + "Shift-Ctrl-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence", + "Ctrl-K Ctrl-K": "delLineRight", + "Ctrl-K Ctrl-U": "upcaseAtCursor", + "Ctrl-K Ctrl-L": "downcaseAtCursor", + "Ctrl-K Ctrl-Space": "setSublimeMark", + "Ctrl-K Ctrl-A": "selectToSublimeMark", + "Ctrl-K Ctrl-W": "deleteToSublimeMark", + "Ctrl-K Ctrl-X": "swapWithSublimeMark", + "Ctrl-K Ctrl-Y": "sublimeYank", + "Ctrl-K Ctrl-C": "showInCenter", + "Ctrl-K Ctrl-G": "clearBookmarks", + "Ctrl-K Ctrl-Backspace": "delLineLeft", + "Ctrl-K Ctrl-1": "foldAll", + "Ctrl-K Ctrl-0": "unfoldAll", + "Ctrl-K Ctrl-J": "unfoldAll", + "Ctrl-Alt-Up": "addCursorToPrevLine", + "Ctrl-Alt-Down": "addCursorToNextLine", + "Ctrl-F3": "findUnder", + "Shift-Ctrl-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Ctrl-[": "fold", + "Shift-Ctrl-]": "unfold", + "Ctrl-I": "findIncremental", + "Shift-Ctrl-I": "findIncrementalReverse", + "Ctrl-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "pcDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.pcSublime); + var mac = keyMap.default == keyMap.macDefault; + keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; + }); + })(); + var sublimeExports = sublime$2.exports; + const sublime = /* @__PURE__ */codemirror.getDefaultExportFromCjs(sublimeExports); + const sublime$1 = /* @__PURE__ */_mergeNamespaces({ + __proto__: null, + default: sublime + }, [sublimeExports]); + exports.sublime = sublime$1; + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/async-helpers/index.js": + /*!*********************************************************!*\ + !*** ../../graphiql-toolkit/esm/async-helpers/index.js ***! + \*********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.fetcherReturnToPromise = fetcherReturnToPromise; + exports.isAsyncIterable = isAsyncIterable; + exports.isObservable = isObservable; + exports.isPromise = isPromise; + var __awaiter = void 0 && (void 0).__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 t(kind, style) { - return { - style, - match: (token) => token.kind === kind, - }; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - function p(value, style) { - return { - style: style || "punctuation", - match: (token) => - token.kind === "Punctuation" && token.value === value, - }; + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + function isPromise(value) { + return typeof value === 'object' && value !== null && typeof value.then === 'function'; + } + function observableToPromise(observable) { + return new Promise((resolve, reject) => { + const subscription = observable.subscribe({ + next(v) { + resolve(v); + subscription.unsubscribe(); + }, + error: reject, + complete() { + reject(new Error('no value resolved')); + } + }); + }); + } + function isObservable(value) { + return typeof value === 'object' && value !== null && 'subscribe' in value && typeof value.subscribe === 'function'; + } + function isAsyncIterable(input) { + return typeof input === 'object' && input !== null && (input[Symbol.toStringTag] === 'AsyncGenerator' || Symbol.asyncIterator in input); + } + function asyncIterableToPromise(input) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const iteratorReturn = (_a = ('return' in input ? input : input[Symbol.asyncIterator]()).return) === null || _a === void 0 ? void 0 : _a.bind(input); + const iteratorNext = ('next' in input ? input : input[Symbol.asyncIterator]()).next.bind(input); + const result = yield iteratorNext(); + void (iteratorReturn === null || iteratorReturn === void 0 ? void 0 : iteratorReturn()); + return result.value; + }); + } + function fetcherReturnToPromise(fetcherResult) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield fetcherResult; + if (isAsyncIterable(result)) { + return asyncIterableToPromise(result); + } + if (isObservable(result)) { + return observableToPromise(result); + } + return result; + }); + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js": + /*!******************************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/createFetcher.js ***! + \******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createGraphiQLFetcher = createGraphiQLFetcher; + var _lib = __webpack_require__(/*! ./lib */ "../../graphiql-toolkit/esm/create-fetcher/lib.js"); + function createGraphiQLFetcher(options) { + let httpFetch; + if (typeof window !== 'undefined' && window.fetch) { + httpFetch = window.fetch; + } + if ((options === null || options === void 0 ? void 0 : options.enableIncrementalDelivery) === null || options.enableIncrementalDelivery !== false) { + options.enableIncrementalDelivery = true; + } + if (options.fetch) { + httpFetch = options.fetch; + } + if (!httpFetch) { + throw new Error('No valid fetcher implementation available'); + } + const simpleFetcher = (0, _lib.createSimpleFetcher)(options, httpFetch); + const httpFetcher = options.enableIncrementalDelivery ? (0, _lib.createMultipartFetcher)(options, httpFetch) : simpleFetcher; + return (graphQLParams, fetcherOpts) => { + if (graphQLParams.operationName === 'IntrospectionQuery') { + return (options.schemaFetcher || simpleFetcher)(graphQLParams, fetcherOpts); + } + const isSubscription = (fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.documentAST) ? (0, _lib.isSubscriptionWithName)(fetcherOpts.documentAST, graphQLParams.operationName || undefined) : false; + if (isSubscription) { + const wsFetcher = (0, _lib.getWsFetcher)(options, fetcherOpts); + if (!wsFetcher) { + throw new Error(`Your GraphiQL createFetcher is not properly configured for websocket subscriptions yet. ${options.subscriptionUrl ? `Provided URL ${options.subscriptionUrl} failed` : 'Please provide subscriptionUrl, wsClient or legacyClient option first.'}`); } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/parser/Rules.js": - /*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/Rules.js ***! - \**********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.isIgnored = exports.ParseRules = exports.LexRules = void 0; - var _RuleHelpers = __webpack_require__( - /*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js" - ); - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const isIgnored = (ch) => - ch === " " || - ch === "\t" || - ch === "," || - ch === "\n" || - ch === "\r" || - ch === "\uFEFF" || - ch === "\u00A0"; - exports.isIgnored = isIgnored; - const LexRules = (exports.LexRules = { - Name: /^[_A-Za-z][_0-9A-Za-z]*/, - Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|&|@|\[|]|\{|\||\})/, - Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/, - String: - /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/, - Comment: /^#.*/, - }); - const ParseRules = (exports.ParseRules = { - Document: [(0, _RuleHelpers.list)("Definition")], - Definition(token) { - switch (token.value) { - case "{": - return "ShortQuery"; - case "query": - return "Query"; - case "mutation": - return "Mutation"; - case "subscription": - return "Subscription"; - case "fragment": - return _graphql.Kind.FRAGMENT_DEFINITION; - case "schema": - return "SchemaDef"; - case "scalar": - return "ScalarDef"; - case "type": - return "ObjectTypeDef"; - case "interface": - return "InterfaceDef"; - case "union": - return "UnionDef"; - case "enum": - return "EnumDef"; - case "input": - return "InputDef"; - case "extend": - return "ExtendDef"; - case "directive": - return "DirectiveDef"; - } - }, - ShortQuery: ["SelectionSet"], - Query: [ - word("query"), - (0, _RuleHelpers.opt)(name("def")), - (0, _RuleHelpers.opt)("VariableDefinitions"), - (0, _RuleHelpers.list)("Directive"), - "SelectionSet", - ], - Mutation: [ - word("mutation"), - (0, _RuleHelpers.opt)(name("def")), - (0, _RuleHelpers.opt)("VariableDefinitions"), - (0, _RuleHelpers.list)("Directive"), - "SelectionSet", - ], - Subscription: [ - word("subscription"), - (0, _RuleHelpers.opt)(name("def")), - (0, _RuleHelpers.opt)("VariableDefinitions"), - (0, _RuleHelpers.list)("Directive"), - "SelectionSet", - ], - VariableDefinitions: [ - (0, _RuleHelpers.p)("("), - (0, _RuleHelpers.list)("VariableDefinition"), - (0, _RuleHelpers.p)(")"), - ], - VariableDefinition: [ - "Variable", - (0, _RuleHelpers.p)(":"), - "Type", - (0, _RuleHelpers.opt)("DefaultValue"), - ], - Variable: [(0, _RuleHelpers.p)("$", "variable"), name("variable")], - DefaultValue: [(0, _RuleHelpers.p)("="), "Value"], - SelectionSet: [ - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("Selection"), - (0, _RuleHelpers.p)("}"), - ], - Selection(token, stream) { - return token.value === "..." - ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) - ? "InlineFragment" - : "FragmentSpread" - : stream.match(/[\s\u00a0,]*:/, false) - ? "AliasedField" - : "Field"; - }, - AliasedField: [ - name("property"), - (0, _RuleHelpers.p)(":"), - name("qualifier"), - (0, _RuleHelpers.opt)("Arguments"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.opt)("SelectionSet"), - ], - Field: [ - name("property"), - (0, _RuleHelpers.opt)("Arguments"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.opt)("SelectionSet"), - ], - Arguments: [ - (0, _RuleHelpers.p)("("), - (0, _RuleHelpers.list)("Argument"), - (0, _RuleHelpers.p)(")"), - ], - Argument: [name("attribute"), (0, _RuleHelpers.p)(":"), "Value"], - FragmentSpread: [ - (0, _RuleHelpers.p)("..."), - name("def"), - (0, _RuleHelpers.list)("Directive"), - ], - InlineFragment: [ - (0, _RuleHelpers.p)("..."), - (0, _RuleHelpers.opt)("TypeCondition"), - (0, _RuleHelpers.list)("Directive"), - "SelectionSet", - ], - FragmentDefinition: [ - word("fragment"), - (0, _RuleHelpers.opt)( - (0, _RuleHelpers.butNot)(name("def"), [word("on")]) - ), - "TypeCondition", - (0, _RuleHelpers.list)("Directive"), - "SelectionSet", - ], - TypeCondition: [word("on"), "NamedType"], - Value(token) { - switch (token.kind) { - case "Number": - return "NumberValue"; - case "String": - return "StringValue"; - case "Punctuation": - switch (token.value) { - case "[": - return "ListValue"; - case "{": - return "ObjectValue"; - case "$": - return "Variable"; - case "&": - return "NamedType"; - } - return null; - case "Name": - switch (token.value) { - case "true": - case "false": - return "BooleanValue"; - } - if (token.value === "null") { - return "NullValue"; - } - return "EnumValue"; - } - }, - NumberValue: [(0, _RuleHelpers.t)("Number", "number")], - StringValue: [ - { - style: "string", - match: (token) => token.kind === "String", - update(state, token) { - if (token.value.startsWith('"""')) { - state.inBlockstring = !token.value.slice(3).endsWith('"""'); - } - }, - }, - ], - BooleanValue: [(0, _RuleHelpers.t)("Name", "builtin")], - NullValue: [(0, _RuleHelpers.t)("Name", "keyword")], - EnumValue: [name("string-2")], - ListValue: [ - (0, _RuleHelpers.p)("["), - (0, _RuleHelpers.list)("Value"), - (0, _RuleHelpers.p)("]"), - ], - ObjectValue: [ - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("ObjectField"), - (0, _RuleHelpers.p)("}"), - ], - ObjectField: [name("attribute"), (0, _RuleHelpers.p)(":"), "Value"], - Type(token) { - return token.value === "[" ? "ListType" : "NonNullType"; - }, - ListType: [ - (0, _RuleHelpers.p)("["), - "Type", - (0, _RuleHelpers.p)("]"), - (0, _RuleHelpers.opt)((0, _RuleHelpers.p)("!")), - ], - NonNullType: [ - "NamedType", - (0, _RuleHelpers.opt)((0, _RuleHelpers.p)("!")), - ], - NamedType: [type("atom")], - Directive: [ - (0, _RuleHelpers.p)("@", "meta"), - name("meta"), - (0, _RuleHelpers.opt)("Arguments"), - ], - DirectiveDef: [ - word("directive"), - (0, _RuleHelpers.p)("@", "meta"), - name("meta"), - (0, _RuleHelpers.opt)("ArgumentsDef"), - word("on"), - (0, _RuleHelpers.list)( - "DirectiveLocation", - (0, _RuleHelpers.p)("|") - ), - ], - InterfaceDef: [ - word("interface"), - name("atom"), - (0, _RuleHelpers.opt)("Implements"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("FieldDef"), - (0, _RuleHelpers.p)("}"), - ], - Implements: [ - word("implements"), - (0, _RuleHelpers.list)("NamedType", (0, _RuleHelpers.p)("&")), - ], - DirectiveLocation: [name("string-2")], - SchemaDef: [ - word("schema"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("OperationTypeDef"), - (0, _RuleHelpers.p)("}"), - ], - OperationTypeDef: [ - name("keyword"), - (0, _RuleHelpers.p)(":"), - name("atom"), - ], - ScalarDef: [ - word("scalar"), - name("atom"), - (0, _RuleHelpers.list)("Directive"), - ], - ObjectTypeDef: [ - word("type"), - name("atom"), - (0, _RuleHelpers.opt)("Implements"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("FieldDef"), - (0, _RuleHelpers.p)("}"), - ], - FieldDef: [ - name("property"), - (0, _RuleHelpers.opt)("ArgumentsDef"), - (0, _RuleHelpers.p)(":"), - "Type", - (0, _RuleHelpers.list)("Directive"), - ], - ArgumentsDef: [ - (0, _RuleHelpers.p)("("), - (0, _RuleHelpers.list)("InputValueDef"), - (0, _RuleHelpers.p)(")"), - ], - InputValueDef: [ - name("attribute"), - (0, _RuleHelpers.p)(":"), - "Type", - (0, _RuleHelpers.opt)("DefaultValue"), - (0, _RuleHelpers.list)("Directive"), - ], - UnionDef: [ - word("union"), - name("atom"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.p)("="), - (0, _RuleHelpers.list)("UnionMember", (0, _RuleHelpers.p)("|")), - ], - UnionMember: ["NamedType"], - EnumDef: [ - word("enum"), - name("atom"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("EnumValueDef"), - (0, _RuleHelpers.p)("}"), - ], - EnumValueDef: [name("string-2"), (0, _RuleHelpers.list)("Directive")], - InputDef: [ - word("input"), - name("atom"), - (0, _RuleHelpers.list)("Directive"), - (0, _RuleHelpers.p)("{"), - (0, _RuleHelpers.list)("InputValueDef"), - (0, _RuleHelpers.p)("}"), - ], - ExtendDef: [word("extend"), "ExtensionDefinition"], - ExtensionDefinition(token) { - switch (token.value) { - case "schema": - return _graphql.Kind.SCHEMA_EXTENSION; - case "scalar": - return _graphql.Kind.SCALAR_TYPE_EXTENSION; - case "type": - return _graphql.Kind.OBJECT_TYPE_EXTENSION; - case "interface": - return _graphql.Kind.INTERFACE_TYPE_EXTENSION; - case "union": - return _graphql.Kind.UNION_TYPE_EXTENSION; - case "enum": - return _graphql.Kind.ENUM_TYPE_EXTENSION; - case "input": - return _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION; - } - }, - [_graphql.Kind.SCHEMA_EXTENSION]: ["SchemaDef"], - [_graphql.Kind.SCALAR_TYPE_EXTENSION]: ["ScalarDef"], - [_graphql.Kind.OBJECT_TYPE_EXTENSION]: ["ObjectTypeDef"], - [_graphql.Kind.INTERFACE_TYPE_EXTENSION]: ["InterfaceDef"], - [_graphql.Kind.UNION_TYPE_EXTENSION]: ["UnionDef"], - [_graphql.Kind.ENUM_TYPE_EXTENSION]: ["EnumDef"], - [_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION]: ["InputDef"], - }); - function word(value) { - return { - style: "keyword", - match: (token) => token.kind === "Name" && token.value === value, - }; + return wsFetcher(graphQLParams); + } + return httpFetcher(graphQLParams, fetcherOpts); + }; + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/create-fetcher/index.js": + /*!**********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/index.js ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _exportNames = { + createGraphiQLFetcher: true + }; + Object.defineProperty(exports, "createGraphiQLFetcher", ({ + enumerable: true, + get: function () { + return _createFetcher.createGraphiQLFetcher; + } + })); + var _types = __webpack_require__(/*! ./types */ "../../graphiql-toolkit/esm/create-fetcher/types.js"); + Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); + }); + var _createFetcher = __webpack_require__(/*! ./createFetcher */ "../../graphiql-toolkit/esm/create-fetcher/createFetcher.js"); + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/create-fetcher/lib.js": + /*!********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/lib.js ***! + \********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.isSubscriptionWithName = exports.getWsFetcher = exports.createWebsocketsFetcherFromUrl = exports.createWebsocketsFetcherFromClient = exports.createSimpleFetcher = exports.createMultipartFetcher = exports.createLegacyWebsocketsFetcher = void 0; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _meros = __webpack_require__(/*! meros */ "../../../node_modules/meros/browser/index.js"); + var _pushPullAsyncIterableIterator = __webpack_require__(/*! @n1ru4l/push-pull-async-iterable-iterator */ "../../../node_modules/@n1ru4l/push-pull-async-iterable-iterator/index.js"); + var __awaiter = void 0 && (void 0).__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 name(style) { - return { - style, - match: (token) => token.kind === "Name", - update(state, token) { - state.name = token.value; - }, - }; + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - function type(style) { - return { - style, - match: (token) => token.kind === "Name", - update(state, token) { - var _a; - if ( - (_a = state.prevState) === null || _a === void 0 - ? void 0 - : _a.prevState - ) { - state.name = token.value; - state.prevState.prevState.type = token.value; - } - }, - }; + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __await = void 0 && (void 0).__await || function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + var __asyncValues = void 0 && (void 0).__asyncValues || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + }; + var __asyncGenerator = void 0 && (void 0).__asyncGenerator || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } + }; + const errorHasCode = err => { + return typeof err === 'object' && err !== null && 'code' in err; + }; + const isSubscriptionWithName = (document, name) => { + let isSubscription = false; + (0, _graphql.visit)(document, { + OperationDefinition(node) { + var _a; + if (name === ((_a = node.name) === null || _a === void 0 ? void 0 : _a.value) && node.operation === 'subscription') { + isSubscription = true; } - - /***/ + } + }); + return isSubscription; + }; + exports.isSubscriptionWithName = isSubscriptionWithName; + const createSimpleFetcher = (options, httpFetch) => (graphQLParams, fetcherOpts) => __awaiter(void 0, void 0, void 0, function* () { + const data = yield httpFetch(options.url, { + method: 'POST', + body: JSON.stringify(graphQLParams), + headers: Object.assign(Object.assign({ + 'content-type': 'application/json' + }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) + }); + return data.json(); + }); + exports.createSimpleFetcher = createSimpleFetcher; + const createWebsocketsFetcherFromUrl = (url, connectionParams) => { + let wsClient; + try { + const { + createClient + } = __webpack_require__(/*! graphql-ws */ "../../../node_modules/graphql-ws/lib/index.js"); + wsClient = createClient({ + url, + connectionParams + }); + return createWebsocketsFetcherFromClient(wsClient); + } catch (err) { + if (errorHasCode(err) && err.code === 'MODULE_NOT_FOUND') { + throw new Error("You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'"); + } + console.error(`Error creating websocket client for ${url}`, err); + } + }; + exports.createWebsocketsFetcherFromUrl = createWebsocketsFetcherFromUrl; + const createWebsocketsFetcherFromClient = wsClient => graphQLParams => (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => wsClient.subscribe(graphQLParams, Object.assign(Object.assign({}, sink), { + error(err) { + if (err instanceof CloseEvent) { + sink.error(new Error(`Socket closed with event ${err.code} ${err.reason || ''}`.trim())); + } else { + sink.error(err); + } + } + }))); + exports.createWebsocketsFetcherFromClient = createWebsocketsFetcherFromClient; + const createLegacyWebsocketsFetcher = legacyWsClient => graphQLParams => { + const observable = legacyWsClient.request(graphQLParams); + return (0, _pushPullAsyncIterableIterator.makeAsyncIterableIteratorFromSink)(sink => observable.subscribe(sink).unsubscribe); + }; + exports.createLegacyWebsocketsFetcher = createLegacyWebsocketsFetcher; + const createMultipartFetcher = (options, httpFetch) => function (graphQLParams, fetcherOpts) { + return __asyncGenerator(this, arguments, function* () { + var e_1, _a; + const response = yield __await(httpFetch(options.url, { + method: 'POST', + body: JSON.stringify(graphQLParams), + headers: Object.assign(Object.assign({ + 'content-type': 'application/json', + accept: 'application/json, multipart/mixed' + }, options.headers), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers) + }).then(r => (0, _meros.meros)(r, { + multiple: true + }))); + if (!(0, _pushPullAsyncIterableIterator.isAsyncIterable)(response)) { + return yield __await(yield yield __await(response.json())); + } + try { + for (var response_1 = __asyncValues(response), response_1_1; response_1_1 = yield __await(response_1.next()), !response_1_1.done;) { + const chunk = response_1_1.value; + if (chunk.some(part => !part.json)) { + const message = chunk.map(part => `Headers::\n${part.headers}\n\nBody::\n${part.body}`); + throw new Error(`Expected multipart chunks to be of json type. got:\n${message}`); + } + yield yield __await(chunk.map(part => part.body)); + } + } catch (e_1_1) { + e_1 = { + error: e_1_1 + }; + } finally { + try { + if (response_1_1 && !response_1_1.done && (_a = response_1.return)) yield __await(_a.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + }); + }; + exports.createMultipartFetcher = createMultipartFetcher; + const getWsFetcher = (options, fetcherOpts) => { + if (options.wsClient) { + return createWebsocketsFetcherFromClient(options.wsClient); + } + if (options.subscriptionUrl) { + return createWebsocketsFetcherFromUrl(options.subscriptionUrl, Object.assign(Object.assign({}, options.wsConnectionParams), fetcherOpts === null || fetcherOpts === void 0 ? void 0 : fetcherOpts.headers)); + } + const legacyWebsocketsClient = options.legacyClient || options.legacyWsClient; + if (legacyWebsocketsClient) { + return createLegacyWebsocketsFetcher(legacyWebsocketsClient); + } + }; + exports.getWsFetcher = getWsFetcher; + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/create-fetcher/types.js": + /*!**********************************************************!*\ + !*** ../../graphiql-toolkit/esm/create-fetcher/types.js ***! + \**********************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/format/index.js": + /*!**************************************************!*\ + !*** ../../graphiql-toolkit/esm/format/index.js ***! + \**************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.formatError = formatError; + exports.formatResult = formatResult; + function stringify(obj) { + return JSON.stringify(obj, null, 2); + } + function formatSingleError(error) { + return Object.assign(Object.assign({}, error), { + message: error.message, + stack: error.stack + }); + } + function handleSingleError(error) { + if (error instanceof Error) { + return formatSingleError(error); + } + return error; + } + function formatError(error) { + if (Array.isArray(error)) { + return stringify({ + errors: error.map(e => handleSingleError(e)) + }); + } + return stringify({ + errors: [handleSingleError(error)] + }); + } + function formatResult(result) { + return stringify(result); + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js": + /*!*******************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js ***! + \*******************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.fillLeafs = fillLeafs; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function fillLeafs(schema, docString, getDefaultFieldNames) { + const insertions = []; + if (!schema || !docString) { + return { + insertions, + result: docString + }; + } + let ast; + try { + ast = (0, _graphql.parse)(docString); + } catch (_a) { + return { + insertions, + result: docString + }; + } + const fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames; + const typeInfo = new _graphql.TypeInfo(schema); + (0, _graphql.visit)(ast, { + leave(node) { + typeInfo.leave(node); }, - - /***/ "../../graphql-language-service/esm/parser/api.js": - /*!********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/api.js ***! - \********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.TYPE_SYSTEM_KINDS = exports.GraphQLDocumentMode = void 0; - exports.getContextAtPosition = getContextAtPosition; - exports.getDocumentMode = getDocumentMode; - exports.getTokenAtPosition = getTokenAtPosition; - exports.runOnlineParser = runOnlineParser; - var _ = __webpack_require__( - /*! . */ "../../graphql-language-service/esm/parser/index.js" - ); - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function runOnlineParser(queryText, callback) { - const lines = queryText.split("\n"); - const parser = (0, _.onlineParser)(); - let state = parser.startState(); - let style = ""; - let stream = new _.CharacterStream(""); - for (let i = 0; i < lines.length; i++) { - stream = new _.CharacterStream(lines[i]); - while (!stream.eol()) { - style = parser.token(stream, state); - const code = callback(stream, state, style, i); - if (code === "BREAK") { - break; - } - } - callback(stream, state, style, i); - if (!state.kind) { - state = parser.startState(); - } + enter(node) { + typeInfo.enter(node); + if (node.kind === 'Field' && !node.selectionSet) { + const fieldType = typeInfo.getType(); + const selectionSet = buildSelectionSet(isFieldType(fieldType), fieldNameFn); + if (selectionSet && node.loc) { + const indent = getIndentation(docString, node.loc.start); + insertions.push({ + index: node.loc.end, + string: ' ' + (0, _graphql.print)(selectionSet).replaceAll('\n', '\n' + indent) + }); + } + } + } + }); + return { + insertions, + result: withInsertions(docString, insertions) + }; + } + function defaultGetDefaultFieldNames(type) { + if (!('getFields' in type)) { + return []; + } + const fields = type.getFields(); + if (fields.id) { + return ['id']; + } + if (fields.edges) { + return ['edges']; + } + if (fields.node) { + return ['node']; + } + const leafFieldNames = []; + for (const fieldName of Object.keys(fields)) { + if ((0, _graphql.isLeafType)(fields[fieldName].type)) { + leafFieldNames.push(fieldName); + } + } + return leafFieldNames; + } + function buildSelectionSet(type, getDefaultFieldNames) { + const namedType = (0, _graphql.getNamedType)(type); + if (!type || (0, _graphql.isLeafType)(type)) { + return; + } + const fieldNames = getDefaultFieldNames(namedType); + if (!Array.isArray(fieldNames) || fieldNames.length === 0 || !('getFields' in namedType)) { + return; + } + return { + kind: _graphql.Kind.SELECTION_SET, + selections: fieldNames.map(fieldName => { + const fieldDef = namedType.getFields()[fieldName]; + const fieldType = fieldDef ? fieldDef.type : null; + return { + kind: _graphql.Kind.FIELD, + name: { + kind: _graphql.Kind.NAME, + value: fieldName + }, + selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames) + }; + }) + }; + } + function withInsertions(initial, insertions) { + if (insertions.length === 0) { + return initial; + } + let edited = ''; + let prevIndex = 0; + for (const { + index, + string + } of insertions) { + edited += initial.slice(prevIndex, index) + string; + prevIndex = index; + } + edited += initial.slice(prevIndex); + return edited; + } + function getIndentation(str, index) { + let indentStart = index; + let indentEnd = index; + while (indentStart) { + const c = str.charCodeAt(indentStart - 1); + if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { + break; + } + indentStart--; + if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { + indentEnd = indentStart; + } + } + return str.slice(indentStart, indentEnd); + } + function isFieldType(fieldType) { + if (fieldType) { + return fieldType; + } + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/index.js": + /*!***********************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/index.js ***! + \***********************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _autoComplete = __webpack_require__(/*! ./auto-complete */ "../../graphiql-toolkit/esm/graphql-helpers/auto-complete.js"); + Object.keys(_autoComplete).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _autoComplete[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _autoComplete[key]; + } + }); + }); + var _mergeAst = __webpack_require__(/*! ./merge-ast */ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js"); + Object.keys(_mergeAst).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _mergeAst[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _mergeAst[key]; + } + }); + }); + var _operationName = __webpack_require__(/*! ./operation-name */ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js"); + Object.keys(_operationName).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _operationName[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _operationName[key]; + } + }); + }); + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js": + /*!***************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/merge-ast.js ***! + \***************************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.mergeAst = mergeAst; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + function uniqueBy(array, iteratee) { + var _a; + const FilteredMap = new Map(); + const result = []; + for (const item of array) { + if (item.kind === 'Field') { + const uniqueValue = iteratee(item); + const existing = FilteredMap.get(uniqueValue); + if ((_a = item.directives) === null || _a === void 0 ? void 0 : _a.length) { + const itemClone = Object.assign({}, item); + result.push(itemClone); + } else if ((existing === null || existing === void 0 ? void 0 : existing.selectionSet) && item.selectionSet) { + existing.selectionSet.selections = [...existing.selectionSet.selections, ...item.selectionSet.selections]; + } else if (!existing) { + const itemClone = Object.assign({}, item); + FilteredMap.set(uniqueValue, itemClone); + result.push(itemClone); + } + } else { + result.push(item); + } + } + return result; + } + function inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType) { + var _a; + const selectionSetTypeName = selectionSetType ? (0, _graphql.getNamedType)(selectionSetType).name : null; + const outputSelections = []; + const seenSpreads = []; + for (let selection of selections) { + if (selection.kind === 'FragmentSpread') { + const fragmentName = selection.name.value; + if (!selection.directives || selection.directives.length === 0) { + if (seenSpreads.includes(fragmentName)) { + continue; + } else { + seenSpreads.push(fragmentName); } - return { - start: stream.getStartOfToken(), - end: stream.getCurrentPosition(), - string: stream.current(), - state, - style, - }; } - var GraphQLDocumentMode; - (function (GraphQLDocumentMode) { - GraphQLDocumentMode["TYPE_SYSTEM"] = "TYPE_SYSTEM"; - GraphQLDocumentMode["EXECUTABLE"] = "EXECUTABLE"; - GraphQLDocumentMode["UNKNOWN"] = "UNKNOWN"; - })( - GraphQLDocumentMode || - (exports.GraphQLDocumentMode = GraphQLDocumentMode = {}) - ); - const TYPE_SYSTEM_KINDS = (exports.TYPE_SYSTEM_KINDS = [ - _graphql.Kind.SCHEMA_DEFINITION, - _graphql.Kind.OPERATION_TYPE_DEFINITION, - _graphql.Kind.SCALAR_TYPE_DEFINITION, - _graphql.Kind.OBJECT_TYPE_DEFINITION, - _graphql.Kind.INTERFACE_TYPE_DEFINITION, - _graphql.Kind.UNION_TYPE_DEFINITION, - _graphql.Kind.ENUM_TYPE_DEFINITION, - _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION, - _graphql.Kind.DIRECTIVE_DEFINITION, - _graphql.Kind.SCHEMA_EXTENSION, - _graphql.Kind.SCALAR_TYPE_EXTENSION, - _graphql.Kind.OBJECT_TYPE_EXTENSION, - _graphql.Kind.INTERFACE_TYPE_EXTENSION, - _graphql.Kind.UNION_TYPE_EXTENSION, - _graphql.Kind.ENUM_TYPE_EXTENSION, - _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION, - ]); - const getParsedMode = (sdl) => { - let mode = GraphQLDocumentMode.UNKNOWN; - if (sdl) { - try { - (0, _graphql.visit)((0, _graphql.parse)(sdl), { - enter(node) { - if (node.kind === "Document") { - mode = GraphQLDocumentMode.EXECUTABLE; - return; - } - if (TYPE_SYSTEM_KINDS.includes(node.kind)) { - mode = GraphQLDocumentMode.TYPE_SYSTEM; - return _graphql.BREAK; - } - return false; - }, - }); - } catch (_a) { - return mode; - } - } - return mode; - }; - function getDocumentMode(documentText, uri) { - if ( - uri === null || uri === void 0 ? void 0 : uri.endsWith(".graphqls") - ) { - return GraphQLDocumentMode.TYPE_SYSTEM; - } - return getParsedMode(documentText); - } - function getTokenAtPosition(queryText, cursor, offset = 0) { - let styleAtCursor = null; - let stateAtCursor = null; - let stringAtCursor = null; - const token = runOnlineParser( - queryText, - (stream, state, style, index) => { - if ( - index !== cursor.line || - stream.getCurrentPosition() + offset < cursor.character + 1 - ) { - return; - } - styleAtCursor = style; - stateAtCursor = Object.assign({}, state); - stringAtCursor = stream.current(); - return "BREAK"; - } - ); - return { - start: token.start, - end: token.end, - string: stringAtCursor || token.string, - state: stateAtCursor || token.state, - style: styleAtCursor || token.style, + const fragmentDefinition = fragmentDefinitions[selection.name.value]; + if (fragmentDefinition) { + const { + typeCondition, + directives, + selectionSet + } = fragmentDefinition; + selection = { + kind: _graphql.Kind.INLINE_FRAGMENT, + typeCondition, + directives, + selectionSet }; } - function getContextAtPosition( - queryText, - cursor, - schema, - contextToken, - options - ) { - const token = - contextToken || getTokenAtPosition(queryText, cursor, 1); - if (!token) { - return null; - } - const state = - token.state.kind === "Invalid" - ? token.state.prevState - : token.state; - if (!state) { - return null; - } - const typeInfo = (0, _.getTypeInfo)(schema, token.state); - const mode = - (options === null || options === void 0 ? void 0 : options.mode) || - getDocumentMode( - queryText, - options === null || options === void 0 ? void 0 : options.uri - ); - return { - token, - state, - typeInfo, - mode, - }; + } + if (selection.kind === _graphql.Kind.INLINE_FRAGMENT && (!selection.directives || ((_a = selection.directives) === null || _a === void 0 ? void 0 : _a.length) === 0)) { + const fragmentTypeName = selection.typeCondition ? selection.typeCondition.name.value : null; + if (!fragmentTypeName || fragmentTypeName === selectionSetTypeName) { + outputSelections.push(...inlineRelevantFragmentSpreads(fragmentDefinitions, selection.selectionSet.selections, selectionSetType)); + continue; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/parser/getTypeInfo.js": - /*!****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/getTypeInfo.js ***! - \****************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, + } + outputSelections.push(selection); + } + return outputSelections; + } + function mergeAst(documentAST, schema) { + const typeInfo = schema ? new _graphql.TypeInfo(schema) : null; + const fragmentDefinitions = Object.create(null); + for (const definition of documentAST.definitions) { + if (definition.kind === _graphql.Kind.FRAGMENT_DEFINITION) { + fragmentDefinitions[definition.name.value] = definition; + } + } + const flattenVisitors = { + SelectionSet(node) { + const selectionSetType = typeInfo ? typeInfo.getParentType() : null; + let { + selections + } = node; + selections = inlineRelevantFragmentSpreads(fragmentDefinitions, selections, selectionSetType); + return Object.assign(Object.assign({}, node), { + selections }); - exports.forEachState = forEachState; - exports.getDefinitionState = getDefinitionState; - exports.getFieldDef = getFieldDef; - exports.getTypeInfo = getTypeInfo; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _ = __webpack_require__( - /*! . */ "../../graphql-language-service/esm/parser/index.js" - ); - function getFieldDef(schema, type, fieldName) { - if ( - fieldName === _graphql.SchemaMetaFieldDef.name && - schema.getQueryType() === type - ) { - return _graphql.SchemaMetaFieldDef; - } - if ( - fieldName === _graphql.TypeMetaFieldDef.name && - schema.getQueryType() === type - ) { - return _graphql.TypeMetaFieldDef; - } - if ( - fieldName === _graphql.TypeNameMetaFieldDef.name && - (0, _graphql.isCompositeType)(type) - ) { - return _graphql.TypeNameMetaFieldDef; - } - if ("getFields" in type) { - return type.getFields()[fieldName]; - } - return null; - } - function forEachState(stack, fn) { - const reverseStateStack = []; - let state = stack; - while (state === null || state === void 0 ? void 0 : state.kind) { - reverseStateStack.push(state); - state = state.prevState; - } - for (let i = reverseStateStack.length - 1; i >= 0; i--) { - fn(reverseStateStack[i]); - } - } - function getDefinitionState(tokenState) { - let definitionState; - forEachState(tokenState, (state) => { - switch (state.kind) { - case "Query": - case "ShortQuery": - case "Mutation": - case "Subscription": - case "FragmentDefinition": - definitionState = state; - break; - } - }); - return definitionState; - } - function getTypeInfo(schema, tokenState) { - let argDef; - let argDefs; - let directiveDef; - let enumValue; - let fieldDef; - let inputType; - let objectTypeDef; - let objectFieldDefs; - let parentType; - let type; - let interfaceDef; - forEachState(tokenState, (state) => { - var _a; - switch (state.kind) { - case _.RuleKinds.QUERY: - case "ShortQuery": - type = schema.getQueryType(); - break; - case _.RuleKinds.MUTATION: - type = schema.getMutationType(); - break; - case _.RuleKinds.SUBSCRIPTION: - type = schema.getSubscriptionType(); - break; - case _.RuleKinds.INLINE_FRAGMENT: - case _.RuleKinds.FRAGMENT_DEFINITION: - if (state.type) { - type = schema.getType(state.type); - } - break; - case _.RuleKinds.FIELD: - case _.RuleKinds.ALIASED_FIELD: { - if (!type || !state.name) { - fieldDef = null; - } else { - fieldDef = parentType - ? getFieldDef(schema, parentType, state.name) - : null; - type = fieldDef ? fieldDef.type : null; - } - break; - } - case _.RuleKinds.SELECTION_SET: - parentType = (0, _graphql.getNamedType)(type); - break; - case _.RuleKinds.DIRECTIVE: - directiveDef = state.name - ? schema.getDirective(state.name) - : null; - break; - case _.RuleKinds.INTERFACE_DEF: - if (state.name) { - objectTypeDef = null; - interfaceDef = new _graphql.GraphQLInterfaceType({ - name: state.name, - interfaces: [], - fields: {}, - }); - } - break; - case _.RuleKinds.OBJECT_TYPE_DEF: - if (state.name) { - interfaceDef = null; - objectTypeDef = new _graphql.GraphQLObjectType({ - name: state.name, - interfaces: [], - fields: {}, - }); - } - break; - case _.RuleKinds.ARGUMENTS: { - if (state.prevState) { - switch (state.prevState.kind) { - case _.RuleKinds.FIELD: - argDefs = fieldDef && fieldDef.args; - break; - case _.RuleKinds.DIRECTIVE: - argDefs = directiveDef && directiveDef.args; - break; - case _.RuleKinds.ALIASED_FIELD: { - const name = - (_a = state.prevState) === null || _a === void 0 - ? void 0 - : _a.name; - if (!name) { - argDefs = null; - break; - } - const field = parentType - ? getFieldDef(schema, parentType, name) - : null; - if (!field) { - argDefs = null; - break; - } - argDefs = field.args; - break; - } - default: - argDefs = null; - break; - } - } else { - argDefs = null; - } - break; - } - case _.RuleKinds.ARGUMENT: - if (argDefs) { - for (let i = 0; i < argDefs.length; i++) { - if (argDefs[i].name === state.name) { - argDef = argDefs[i]; - break; - } - } - } - inputType = - argDef === null || argDef === void 0 ? void 0 : argDef.type; - break; - case _.RuleKinds.VARIABLE_DEFINITION: - case _.RuleKinds.VARIABLE: - type = inputType; - break; - case _.RuleKinds.ENUM_VALUE: - const enumType = (0, _graphql.getNamedType)(inputType); - enumValue = - enumType instanceof _graphql.GraphQLEnumType - ? enumType - .getValues() - .find((val) => val.value === state.name) - : null; - break; - case _.RuleKinds.LIST_VALUE: - const nullableType = (0, _graphql.getNullableType)(inputType); - inputType = - nullableType instanceof _graphql.GraphQLList - ? nullableType.ofType - : null; - break; - case _.RuleKinds.OBJECT_VALUE: - const objectType = (0, _graphql.getNamedType)(inputType); - objectFieldDefs = - objectType instanceof _graphql.GraphQLInputObjectType - ? objectType.getFields() - : null; - break; - case _.RuleKinds.OBJECT_FIELD: - const objectField = - state.name && objectFieldDefs - ? objectFieldDefs[state.name] - : null; - inputType = - objectField === null || objectField === void 0 - ? void 0 - : objectField.type; - fieldDef = objectField; - type = fieldDef ? fieldDef.type : null; - break; - case _.RuleKinds.NAMED_TYPE: - if (state.name) { - type = schema.getType(state.name); - } - break; - } - }); - return { - argDef, - argDefs, - directiveDef, - enumValue, - fieldDef, - inputType, - objectFieldDefs, - parentType, - type, - interfaceDef, - objectTypeDef, - }; - } - - /***/ }, - - /***/ "../../graphql-language-service/esm/parser/index.js": - /*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/index.js ***! - \**********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - var _exportNames = { - CharacterStream: true, - LexRules: true, - ParseRules: true, - isIgnored: true, - butNot: true, - list: true, - opt: true, - p: true, - t: true, - onlineParser: true, - runOnlineParser: true, - getTokenAtPosition: true, - getContextAtPosition: true, - GraphQLDocumentMode: true, - getDocumentMode: true, - getTypeInfo: true, - getDefinitionState: true, - getFieldDef: true, - }; - Object.defineProperty(exports, "CharacterStream", { - enumerable: true, - get: function () { - return _CharacterStream.default; - }, - }); - Object.defineProperty(exports, "GraphQLDocumentMode", { - enumerable: true, - get: function () { - return _api.GraphQLDocumentMode; - }, - }); - Object.defineProperty(exports, "LexRules", { - enumerable: true, - get: function () { - return _Rules.LexRules; - }, - }); - Object.defineProperty(exports, "ParseRules", { - enumerable: true, - get: function () { - return _Rules.ParseRules; - }, - }); - Object.defineProperty(exports, "butNot", { - enumerable: true, - get: function () { - return _RuleHelpers.butNot; - }, - }); - Object.defineProperty(exports, "getContextAtPosition", { - enumerable: true, - get: function () { - return _api.getContextAtPosition; - }, - }); - Object.defineProperty(exports, "getDefinitionState", { - enumerable: true, - get: function () { - return _getTypeInfo.getDefinitionState; - }, - }); - Object.defineProperty(exports, "getDocumentMode", { - enumerable: true, - get: function () { - return _api.getDocumentMode; - }, - }); - Object.defineProperty(exports, "getFieldDef", { - enumerable: true, - get: function () { - return _getTypeInfo.getFieldDef; - }, - }); - Object.defineProperty(exports, "getTokenAtPosition", { - enumerable: true, - get: function () { - return _api.getTokenAtPosition; - }, - }); - Object.defineProperty(exports, "getTypeInfo", { - enumerable: true, - get: function () { - return _getTypeInfo.getTypeInfo; - }, - }); - Object.defineProperty(exports, "isIgnored", { - enumerable: true, - get: function () { - return _Rules.isIgnored; - }, - }); - Object.defineProperty(exports, "list", { - enumerable: true, - get: function () { - return _RuleHelpers.list; - }, - }); - Object.defineProperty(exports, "onlineParser", { - enumerable: true, - get: function () { - return _onlineParser.default; - }, - }); - Object.defineProperty(exports, "opt", { - enumerable: true, - get: function () { - return _RuleHelpers.opt; - }, - }); - Object.defineProperty(exports, "p", { - enumerable: true, - get: function () { - return _RuleHelpers.p; - }, - }); - Object.defineProperty(exports, "runOnlineParser", { - enumerable: true, - get: function () { - return _api.runOnlineParser; - }, - }); - Object.defineProperty(exports, "t", { - enumerable: true, - get: function () { - return _RuleHelpers.t; - }, - }); - var _CharacterStream = _interopRequireDefault( - __webpack_require__( - /*! ./CharacterStream */ "../../graphql-language-service/esm/parser/CharacterStream.js" - ) - ); - var _Rules = __webpack_require__( - /*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js" - ); - var _RuleHelpers = __webpack_require__( - /*! ./RuleHelpers */ "../../graphql-language-service/esm/parser/RuleHelpers.js" - ); - var _onlineParser = _interopRequireDefault( - __webpack_require__( - /*! ./onlineParser */ "../../graphql-language-service/esm/parser/onlineParser.js" - ) - ); - var _api = __webpack_require__( - /*! ./api */ "../../graphql-language-service/esm/parser/api.js" - ); - var _getTypeInfo = __webpack_require__( - /*! ./getTypeInfo */ "../../graphql-language-service/esm/parser/getTypeInfo.js" - ); - var _types = __webpack_require__( - /*! ./types */ "../../graphql-language-service/esm/parser/types.js" - ); - Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _types[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function () { - return _types[key]; - }, - }); + FragmentDefinition() { + return null; + } + }; + const flattenedAST = (0, _graphql.visit)(documentAST, typeInfo ? (0, _graphql.visitWithTypeInfo)(typeInfo, flattenVisitors) : flattenVisitors); + const deduplicateVisitors = { + SelectionSet(node) { + let { + selections + } = node; + selections = uniqueBy(selections, selection => selection.alias ? selection.alias.value : selection.name.value); + return Object.assign(Object.assign({}, node), { + selections }); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - - /***/ }, - - /***/ "../../graphql-language-service/esm/parser/onlineParser.js": - /*!*****************************************************************!*\ - !*** ../../graphql-language-service/esm/parser/onlineParser.js ***! - \*****************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports["default"] = onlineParser; - var _Rules = __webpack_require__( - /*! ./Rules */ "../../graphql-language-service/esm/parser/Rules.js" - ); - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function onlineParser( - options = { - eatWhitespace: (stream) => stream.eatWhile(_Rules.isIgnored), - lexRules: _Rules.LexRules, - parseRules: _Rules.ParseRules, - editorConfig: {}, - } - ) { - return { - startState() { - const initialState = { - level: 0, - step: 0, - name: null, - kind: null, - type: null, - rule: null, - needsSeparator: false, - prevState: null, - }; - pushRule( - options.parseRules, - initialState, - _graphql.Kind.DOCUMENT - ); - return initialState; - }, - token(stream, state) { - return getToken(stream, state, options); - }, - }; - } - function getToken(stream, state, options) { - var _a; - if (state.inBlockstring) { - if (stream.match(/.*"""/)) { - state.inBlockstring = false; - return "string"; - } - stream.skipToEnd(); - return "string"; - } - const { lexRules, parseRules, eatWhitespace, editorConfig } = options; - if (state.rule && state.rule.length === 0) { - popRule(state); - } else if (state.needsAdvance) { - state.needsAdvance = false; - advanceRule(state, true); - } - if (stream.sol()) { - const tabSize = - (editorConfig === null || editorConfig === void 0 - ? void 0 - : editorConfig.tabSize) || 2; - state.indentLevel = Math.floor(stream.indentation() / tabSize); - } - if (eatWhitespace(stream)) { - return "ws"; - } - const token = lex(lexRules, stream); - if (!token) { - const matchedSomething = stream.match(/\S+/); - if (!matchedSomething) { - stream.match(/\s/); - } - pushRule(SpecialParseRules, state, "Invalid"); - return "invalidchar"; - } - if (token.kind === "Comment") { - pushRule(SpecialParseRules, state, "Comment"); - return "comment"; - } - const backupState = assign({}, state); - if (token.kind === "Punctuation") { - if (/^[{([]/.test(token.value)) { - if (state.indentLevel !== undefined) { - state.levels = (state.levels || []).concat( - state.indentLevel + 1 - ); - } - } else if (/^[})\]]/.test(token.value)) { - const levels = (state.levels = (state.levels || []).slice(0, -1)); - if ( - state.indentLevel && - levels.length > 0 && - levels.at(-1) < state.indentLevel - ) { - state.indentLevel = levels.at(-1); + FragmentDefinition() { + return null; + } + }; + return (0, _graphql.visit)(flattenedAST, deduplicateVisitors); + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/graphql-helpers/operation-name.js": + /*!********************************************************************!*\ + !*** ../../graphiql-toolkit/esm/graphql-helpers/operation-name.js ***! + \********************************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.getSelectedOperationName = getSelectedOperationName; + function getSelectedOperationName(prevOperations, prevSelectedOperationName, operations) { + if (!operations || operations.length < 1) { + return; + } + const names = operations.map(op => { + var _a; + return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; + }); + if (prevSelectedOperationName && names.includes(prevSelectedOperationName)) { + return prevSelectedOperationName; + } + if (prevSelectedOperationName && prevOperations) { + const prevNames = prevOperations.map(op => { + var _a; + return (_a = op.name) === null || _a === void 0 ? void 0 : _a.value; + }); + const prevIndex = prevNames.indexOf(prevSelectedOperationName); + if (prevIndex !== -1 && prevIndex < names.length) { + return names[prevIndex]; + } + } + return names[0]; + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/index.js": + /*!*******************************************!*\ + !*** ../../graphiql-toolkit/esm/index.js ***! + \*******************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _asyncHelpers = __webpack_require__(/*! ./async-helpers */ "../../graphiql-toolkit/esm/async-helpers/index.js"); + Object.keys(_asyncHelpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _asyncHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _asyncHelpers[key]; + } + }); + }); + var _createFetcher = __webpack_require__(/*! ./create-fetcher */ "../../graphiql-toolkit/esm/create-fetcher/index.js"); + Object.keys(_createFetcher).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _createFetcher[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _createFetcher[key]; + } + }); + }); + var _format = __webpack_require__(/*! ./format */ "../../graphiql-toolkit/esm/format/index.js"); + Object.keys(_format).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _format[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _format[key]; + } + }); + }); + var _graphqlHelpers = __webpack_require__(/*! ./graphql-helpers */ "../../graphiql-toolkit/esm/graphql-helpers/index.js"); + Object.keys(_graphqlHelpers).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _graphqlHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _graphqlHelpers[key]; + } + }); + }); + var _storage = __webpack_require__(/*! ./storage */ "../../graphiql-toolkit/esm/storage/index.js"); + Object.keys(_storage).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _storage[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _storage[key]; + } + }); + }); + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/storage/base.js": + /*!**************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/base.js ***! + \**************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.StorageAPI = void 0; + function isQuotaError(storage, e) { + return e instanceof DOMException && (e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && storage.length !== 0; + } + class StorageAPI { + constructor(storage) { + if (storage) { + this.storage = storage; + } else if (storage === null) { + this.storage = null; + } else if (typeof window === 'undefined') { + this.storage = null; + } else { + this.storage = { + getItem: localStorage.getItem.bind(localStorage), + setItem: localStorage.setItem.bind(localStorage), + removeItem: localStorage.removeItem.bind(localStorage), + get length() { + let keys = 0; + for (const key in localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + keys += 1; } } - } - while (state.rule) { - let expected = - typeof state.rule === "function" - ? state.step === 0 - ? state.rule(token, stream) - : null - : state.rule[state.step]; - if (state.needsSeparator) { - expected = - expected === null || expected === void 0 - ? void 0 - : expected.separator; - } - if (expected) { - if (expected.ofRule) { - expected = expected.ofRule; - } - if (typeof expected === "string") { - pushRule(parseRules, state, expected); - continue; - } - if ( - (_a = expected.match) === null || _a === void 0 - ? void 0 - : _a.call(expected, token) - ) { - if (expected.update) { - expected.update(state, token); - } - if (token.kind === "Punctuation") { - advanceRule(state, true); - } else { - state.needsAdvance = true; - } - return expected.style; + return keys; + }, + clear() { + for (const key in localStorage) { + if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) { + localStorage.removeItem(key); } } - unsuccessful(state); } - assign(state, backupState); - pushRule(SpecialParseRules, state, "Invalid"); - return "invalidchar"; + }; + } + } + get(name) { + if (!this.storage) { + return null; + } + const key = `${STORAGE_NAMESPACE}:${name}`; + const value = this.storage.getItem(key); + if (value === 'null' || value === 'undefined') { + this.storage.removeItem(key); + return null; + } + return value || null; + } + set(name, value) { + let quotaError = false; + let error = null; + if (this.storage) { + const key = `${STORAGE_NAMESPACE}:${name}`; + if (value) { + try { + this.storage.setItem(key, value); + } catch (e) { + error = e instanceof Error ? e : new Error(`${e}`); + quotaError = isQuotaError(this.storage, e); + } + } else { + this.storage.removeItem(key); + } + } + return { + isQuotaError: quotaError, + error + }; + } + clear() { + if (this.storage) { + this.storage.clear(); + } + } + } + exports.StorageAPI = StorageAPI; + const STORAGE_NAMESPACE = 'graphiql'; + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/storage/custom.js": + /*!****************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/custom.js ***! + \****************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.createLocalStorage = createLocalStorage; + function createLocalStorage({ + namespace + }) { + const storageKeyPrefix = `${namespace}:`; + const getStorageKey = key => `${storageKeyPrefix}${key}`; + const storage = { + setItem: (key, value) => localStorage.setItem(getStorageKey(key), value), + getItem: key => localStorage.getItem(getStorageKey(key)), + removeItem: key => localStorage.removeItem(getStorageKey(key)), + get length() { + let keys = 0; + for (const key in localStorage) { + if (key.indexOf(storageKeyPrefix) === 0) { + keys += 1; + } + } + return keys; + }, + clear() { + for (const key in localStorage) { + if (key.indexOf(storageKeyPrefix) === 0) { + localStorage.removeItem(key); + } + } + } + }; + return storage; + } + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/storage/history.js": + /*!*****************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/history.js ***! + \*****************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.HistoryStore = void 0; + var _graphql = __webpack_require__(/*! graphql */ "../../../node_modules/graphql/index.mjs"); + var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); + const MAX_QUERY_SIZE = 100000; + class HistoryStore { + constructor(storage, maxHistoryLength) { + this.storage = storage; + this.maxHistoryLength = maxHistoryLength; + this.updateHistory = ({ + query, + variables, + headers, + operationName + }) => { + if (!this.shouldSaveQuery(query, variables, headers, this.history.fetchRecent())) { + return; } - function assign(to, from) { - const keys = Object.keys(from); - for (let i = 0; i < keys.length; i++) { - to[keys[i]] = from[keys[i]]; + this.history.push({ + query, + variables, + headers, + operationName + }); + const historyQueries = this.history.items; + const favoriteQueries = this.favorite.items; + this.queries = historyQueries.concat(favoriteQueries); + }; + this.deleteHistory = ({ + query, + variables, + headers, + operationName, + favorite + }, clearFavorites = false) => { + function deleteFromStore(store) { + const found = store.items.find(x => x.query === query && x.variables === variables && x.headers === headers && x.operationName === operationName); + if (found) { + store.delete(found); } - return to; } - const SpecialParseRules = { - Invalid: [], - Comment: [], - }; - function pushRule(rules, state, ruleKind) { - if (!rules[ruleKind]) { - throw new TypeError("Unknown rule: " + ruleKind); - } - state.prevState = Object.assign({}, state); - state.kind = ruleKind; - state.name = null; - state.type = null; - state.rule = rules[ruleKind]; - state.step = 0; - state.needsSeparator = false; + if (favorite || clearFavorites) { + deleteFromStore(this.favorite); } - function popRule(state) { - if (!state.prevState) { - return; - } - state.kind = state.prevState.kind; - state.name = state.prevState.name; - state.type = state.prevState.type; - state.rule = state.prevState.rule; - state.step = state.prevState.step; - state.needsSeparator = state.prevState.needsSeparator; - state.prevState = state.prevState.prevState; + if (!favorite || clearFavorites) { + deleteFromStore(this.history); } - function advanceRule(state, successful) { - var _a; - if (isList(state) && state.rule) { - const step = state.rule[state.step]; - if (step.separator) { - const { separator } = step; - state.needsSeparator = !state.needsSeparator; - if (!state.needsSeparator && separator.ofRule) { - return; - } - } - if (successful) { - return; - } + this.queries = [...this.history.items, ...this.favorite.items]; + }; + this.history = new _query.QueryStore('queries', this.storage, this.maxHistoryLength); + this.favorite = new _query.QueryStore('favorites', this.storage, null); + this.queries = [...this.history.fetchAll(), ...this.favorite.fetchAll()]; + } + shouldSaveQuery(query, variables, headers, lastQuerySaved) { + if (!query) { + return false; + } + try { + (0, _graphql.parse)(query); + } catch (_a) { + return false; + } + if (query.length > MAX_QUERY_SIZE) { + return false; + } + if (!lastQuerySaved) { + return true; + } + if (JSON.stringify(query) === JSON.stringify(lastQuerySaved.query)) { + if (JSON.stringify(variables) === JSON.stringify(lastQuerySaved.variables)) { + if (JSON.stringify(headers) === JSON.stringify(lastQuerySaved.headers)) { + return false; } - state.needsSeparator = false; - state.step++; - while ( - state.rule && - !(Array.isArray(state.rule) && state.step < state.rule.length) - ) { - popRule(state); - if (state.rule) { - if (isList(state)) { - if ( - (_a = state.rule) === null || _a === void 0 - ? void 0 - : _a[state.step].separator - ) { - state.needsSeparator = !state.needsSeparator; - } - } else { - state.needsSeparator = false; - state.step++; - } - } + if (headers && !lastQuerySaved.headers) { + return false; } } - function isList(state) { - const step = - Array.isArray(state.rule) && - typeof state.rule[state.step] !== "string" && - state.rule[state.step]; - return step && step.isList; + if (variables && !lastQuerySaved.variables) { + return false; + } + } + return true; + } + toggleFavorite({ + query, + variables, + headers, + operationName, + label, + favorite + }) { + const item = { + query, + variables, + headers, + operationName, + label + }; + if (favorite) { + item.favorite = false; + this.favorite.delete(item); + this.history.push(item); + } else { + item.favorite = true; + this.favorite.push(item); + this.history.delete(item); + } + this.queries = [...this.history.items, ...this.favorite.items]; + } + editLabel({ + query, + variables, + headers, + operationName, + label, + favorite + }, index) { + const item = { + query, + variables, + headers, + operationName, + label + }; + if (favorite) { + this.favorite.edit(Object.assign(Object.assign({}, item), { + favorite + }), index); + } else { + this.history.edit(item, index); + } + this.queries = [...this.history.items, ...this.favorite.items]; + } + } + exports.HistoryStore = HistoryStore; + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/storage/index.js": + /*!***************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/index.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports, __webpack_require__) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + var _base = __webpack_require__(/*! ./base */ "../../graphiql-toolkit/esm/storage/base.js"); + Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _base[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _base[key]; + } + }); + }); + var _history = __webpack_require__(/*! ./history */ "../../graphiql-toolkit/esm/storage/history.js"); + Object.keys(_history).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _history[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _history[key]; + } + }); + }); + var _query = __webpack_require__(/*! ./query */ "../../graphiql-toolkit/esm/storage/query.js"); + Object.keys(_query).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _query[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _query[key]; + } + }); + }); + var _custom = __webpack_require__(/*! ./custom */ "../../graphiql-toolkit/esm/storage/custom.js"); + Object.keys(_custom).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _custom[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _custom[key]; + } + }); + }); + + /***/ }), + + /***/ "../../graphiql-toolkit/esm/storage/query.js": + /*!***************************************************!*\ + !*** ../../graphiql-toolkit/esm/storage/query.js ***! + \***************************************************/ + /***/ (function(__unused_webpack_module, exports) { + + + + Object.defineProperty(exports, "__esModule", ({ + value: true + })); + exports.QueryStore = void 0; + class QueryStore { + constructor(key, storage, maxSize = null) { + this.key = key; + this.storage = storage; + this.maxSize = maxSize; + this.items = this.fetchAll(); + } + get length() { + return this.items.length; + } + contains(item) { + return this.items.some(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); + } + edit(item, index) { + if (typeof index === 'number' && this.items[index]) { + const found = this.items[index]; + if (found.query === item.query && found.variables === item.variables && found.headers === item.headers && found.operationName === item.operationName) { + this.items.splice(index, 1, item); + this.save(); + return; + } + } + const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); + if (itemIndex !== -1) { + this.items.splice(itemIndex, 1, item); + this.save(); + } + } + delete(item) { + const itemIndex = this.items.findIndex(x => x.query === item.query && x.variables === item.variables && x.headers === item.headers && x.operationName === item.operationName); + if (itemIndex !== -1) { + this.items.splice(itemIndex, 1); + this.save(); + } + } + fetchRecent() { + return this.items.at(-1); + } + fetchAll() { + const raw = this.storage.get(this.key); + if (raw) { + return JSON.parse(raw)[this.key]; + } + return []; + } + push(item) { + const items = [...this.items, item]; + if (this.maxSize && items.length > this.maxSize) { + items.shift(); + } + for (let attempts = 0; attempts < 5; attempts++) { + const response = this.storage.set(this.key, JSON.stringify({ + [this.key]: items + })); + if (!(response === null || response === void 0 ? void 0 : response.error)) { + this.items = items; + } else if (response.isQuotaError && this.maxSize) { + items.shift(); + } else { + return; } - function unsuccessful(state) { - while ( - state.rule && - !(Array.isArray(state.rule) && state.rule[state.step].ofRule) - ) { - popRule(state); + } + } + save() { + this.storage.set(this.key, JSON.stringify({ + [this.key]: this.items + })); + } + } + exports.QueryStore = QueryStore; + + /***/ }), + + /***/ "../node_modules/linkify-it/build/index.cjs.js": + /*!*****************************************************!*\ + !*** ../node_modules/linkify-it/build/index.cjs.js ***! + \*****************************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + + var uc_micro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); + function reFactory(opts) { + const re = {}; + opts = opts || {}; + re.src_Any = uc_micro.Any.source; + re.src_Cc = uc_micro.Cc.source; + re.src_Z = uc_micro.Z.source; + re.src_P = uc_micro.P.source; + + // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) + re.src_ZPCc = [re.src_Z, re.src_P, re.src_Cc].join('|'); + + // \p{\Z\Cc} (white spaces + control) + re.src_ZCc = [re.src_Z, re.src_Cc].join('|'); + + // Experimental. List of chars, completely prohibited in links + // because can separate it from other part of text + const text_separators = '[><\uff5c]'; + + // All possible word characters (everything without punctuation, spaces & controls) + // Defined via punctuation & spaces to save space + // Should be something like \p{\L\N\S\M} (\w but without `_`) + re.src_pseudo_letter = '(?:(?!' + text_separators + '|' + re.src_ZPCc + ')' + re.src_Any + ')'; + // The same as abothe but without [0-9] + // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; + + re.src_ip4 = '(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'; + + // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. + re.src_auth = '(?:(?:(?!' + re.src_ZCc + '|[@/\\[\\]()]).)+@)?'; + re.src_port = '(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?'; + re.src_host_terminator = '(?=$|' + text_separators + '|' + re.src_ZPCc + ')' + '(?!' + (opts['---'] ? '-(?!--)|' : '-|') + '_|:\\d|\\.-|\\.(?!$|' + re.src_ZPCc + '))'; + re.src_path = '(?:' + '[/?#]' + '(?:' + '(?!' + re.src_ZCc + '|' + text_separators + '|[()[\\]{}.,"\'?!\\-;]).|' + '\\[(?:(?!' + re.src_ZCc + '|\\]).)*\\]|' + '\\((?:(?!' + re.src_ZCc + '|[)]).)*\\)|' + '\\{(?:(?!' + re.src_ZCc + '|[}]).)*\\}|' + '\\"(?:(?!' + re.src_ZCc + '|["]).)+\\"|' + "\\'(?:(?!" + re.src_ZCc + "|[']).)+\\'|" + + // allow `I'm_king` if no pair found + "\\'(?=" + re.src_pseudo_letter + '|[-])|' + + // google has many dots in "google search" links (#66, #81). + // github has ... in commit range links, + // Restrict to + // - english + // - percent-encoded + // - parts of file path + // - params separator + // until more examples found. + '\\.{2,}[a-zA-Z0-9%/&]|' + '\\.(?!' + re.src_ZCc + '|[.]|$)|' + (opts['---'] ? '\\-(?!--(?:[^-]|$))(?:-*)|' // `---` => long dash, terminate + : '\\-+|') + + // allow `,,,` in paths + ',(?!' + re.src_ZCc + '|$)|' + + // allow `;` if not followed by space-like char + ';(?!' + re.src_ZCc + '|$)|' + + // allow `!!!` in paths, but not at the end + '\\!+(?!' + re.src_ZCc + '|[!]|$)|' + '\\?(?!' + re.src_ZCc + '|[?]|$)' + ')+' + '|\\/' + ')?'; + + // Allow anything in markdown spec, forbid quote (") at the first position + // because emails enclosed in quotes are far more common + re.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; + re.src_xn = 'xn--[a-z0-9\\-]{1,59}'; + + // More to read about domain names + // http://serverfault.com/questions/638260/ + + re.src_domain_root = + // Allow letters & digits (http://test1) + '(?:' + re.src_xn + '|' + re.src_pseudo_letter + '{1,63}' + ')'; + re.src_domain = '(?:' + re.src_xn + '|' + '(?:' + re.src_pseudo_letter + ')' + '|' + '(?:' + re.src_pseudo_letter + '(?:-|' + re.src_pseudo_letter + '){0,61}' + re.src_pseudo_letter + ')' + ')'; + re.src_host = '(?:' + + // Don't need IP check, because digits are already allowed in normal domain names + // src_ip4 + + // '|' + + '(?:(?:(?:' + re.src_domain + ')\\.)*' + re.src_domain /* _root */ + ')' + ')'; + re.tpl_host_fuzzy = '(?:' + re.src_ip4 + '|' + '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))' + ')'; + re.tpl_host_no_ip_fuzzy = '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))'; + re.src_host_strict = re.src_host + re.src_host_terminator; + re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; + re.src_host_port_strict = re.src_host + re.src_port + re.src_host_terminator; + re.tpl_host_port_fuzzy_strict = re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; + re.tpl_host_port_no_ip_fuzzy_strict = re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; + + // + // Main rules + // + + // Rude test fuzzy links by host, for quick deny + re.tpl_host_fuzzy_test = 'localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:' + re.src_ZPCc + '|>|$))'; + re.tpl_email_fuzzy = '(^|' + text_separators + '|"|\\(|' + re.src_ZCc + ')' + '(' + re.src_email_name + '@' + re.tpl_host_fuzzy_strict + ')'; + re.tpl_link_fuzzy = + // Fuzzy link can't be prepended with .:/\- and non punctuation. + // but can start with > (markdown blockquote) + '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_fuzzy_strict + re.src_path + ')'; + re.tpl_link_no_ip_fuzzy = + // Fuzzy link can't be prepended with .:/\- and non punctuation. + // but can start with > (markdown blockquote) + '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_no_ip_fuzzy_strict + re.src_path + ')'; + return re; + } + + // + // Helpers + // + + // Merge objects + // + function assign(obj /* from1, from2, from3, ... */) { + const sources = Array.prototype.slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) { + return; + } + Object.keys(source).forEach(function (key) { + obj[key] = source[key]; + }); + }); + return obj; + } + function _class(obj) { + return Object.prototype.toString.call(obj); + } + function isString(obj) { + return _class(obj) === '[object String]'; + } + function isObject(obj) { + return _class(obj) === '[object Object]'; + } + function isRegExp(obj) { + return _class(obj) === '[object RegExp]'; + } + function isFunction(obj) { + return _class(obj) === '[object Function]'; + } + function escapeRE(str) { + return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); + } + + // + + const defaultOptions = { + fuzzyLink: true, + fuzzyEmail: true, + fuzzyIP: false + }; + function isOptionsObj(obj) { + return Object.keys(obj || {}).reduce(function (acc, k) { + /* eslint-disable-next-line no-prototype-builtins */ + return acc || defaultOptions.hasOwnProperty(k); + }, false); + } + const defaultSchemas = { + 'http:': { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.http) { + // compile lazily, because "host"-containing variables can change on tlds update. + self.re.http = new RegExp('^\\/\\/' + self.re.src_auth + self.re.src_host_port_strict + self.re.src_path, 'i'); + } + if (self.re.http.test(tail)) { + return tail.match(self.re.http)[0].length; + } + return 0; + } + }, + 'https:': 'http:', + 'ftp:': 'http:', + '//': { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.no_http) { + // compile lazily, because "host"-containing variables can change on tlds update. + self.re.no_http = new RegExp('^' + self.re.src_auth + + // Don't allow single-level domains, because of false positives like '//test' + // with code comments + '(?:localhost|(?:(?:' + self.re.src_domain + ')\\.)+' + self.re.src_domain_root + ')' + self.re.src_port + self.re.src_host_terminator + self.re.src_path, 'i'); + } + if (self.re.no_http.test(tail)) { + // should not be `://` & `///`, that protects from errors in protocol name + if (pos >= 3 && text[pos - 3] === ':') { + return 0; } - if (state.rule) { - advanceRule(state, false); + if (pos >= 3 && text[pos - 3] === '/') { + return 0; } + return tail.match(self.re.no_http)[0].length; } - function lex(lexRules, stream) { - const kinds = Object.keys(lexRules); - for (let i = 0; i < kinds.length; i++) { - const match = stream.match(lexRules[kinds[i]]); - if (match && match instanceof Array) { - return { - kind: kinds[i], - value: match[0], - }; + return 0; + } + }, + 'mailto:': { + validate: function (text, pos, self) { + const tail = text.slice(pos); + if (!self.re.mailto) { + self.re.mailto = new RegExp('^' + self.re.src_email_name + '@' + self.re.src_host_strict, 'i'); + } + if (self.re.mailto.test(tail)) { + return tail.match(self.re.mailto)[0].length; + } + return 0; + } + } + }; + + // RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) + /* eslint-disable-next-line max-len */ + const tlds_2ch_src_re = 'a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]'; + + // DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead + const tlds_default = 'biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф'.split('|'); + function resetScanCache(self) { + self.__index__ = -1; + self.__text_cache__ = ''; + } + function createValidator(re) { + return function (text, pos) { + const tail = text.slice(pos); + if (re.test(tail)) { + return tail.match(re)[0].length; + } + return 0; + }; + } + function createNormalizer() { + return function (match, self) { + self.normalize(match); + }; + } + + // Schemas compiler. Build regexps. + // + function compile(self) { + // Load & clone RE patterns. + const re = self.re = reFactory(self.__opts__); + + // Define dynamic patterns + const tlds = self.__tlds__.slice(); + self.onCompile(); + if (!self.__tlds_replaced__) { + tlds.push(tlds_2ch_src_re); + } + tlds.push(re.src_xn); + re.src_tlds = tlds.join('|'); + function untpl(tpl) { + return tpl.replace('%TLDS%', re.src_tlds); + } + re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i'); + re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i'); + re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i'); + re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i'); + + // + // Compile each schema + // + + const aliases = []; + self.__compiled__ = {}; // Reset compiled data + + function schemaError(name, val) { + throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val); + } + Object.keys(self.__schemas__).forEach(function (name) { + const val = self.__schemas__[name]; + + // skip disabled methods + if (val === null) { + return; + } + const compiled = { + validate: null, + link: null + }; + self.__compiled__[name] = compiled; + if (isObject(val)) { + if (isRegExp(val.validate)) { + compiled.validate = createValidator(val.validate); + } else if (isFunction(val.validate)) { + compiled.validate = val.validate; + } else { + schemaError(name, val); + } + if (isFunction(val.normalize)) { + compiled.normalize = val.normalize; + } else if (!val.normalize) { + compiled.normalize = createNormalizer(); + } else { + schemaError(name, val); + } + return; + } + if (isString(val)) { + aliases.push(name); + return; + } + schemaError(name, val); + }); + + // + // Compile postponed aliases + // + + aliases.forEach(function (alias) { + if (!self.__compiled__[self.__schemas__[alias]]) { + // Silently fail on missed schemas to avoid errons on disable. + // schemaError(alias, self.__schemas__[alias]); + return; + } + self.__compiled__[alias].validate = self.__compiled__[self.__schemas__[alias]].validate; + self.__compiled__[alias].normalize = self.__compiled__[self.__schemas__[alias]].normalize; + }); + + // + // Fake record for guessed links + // + self.__compiled__[''] = { + validate: null, + normalize: createNormalizer() + }; + + // + // Build schema condition + // + const slist = Object.keys(self.__compiled__).filter(function (name) { + // Filter disabled & fake schemas + return name.length > 0 && self.__compiled__[name]; + }).map(escapeRE).join('|'); + // (?!_) cause 1.5x slowdown + self.re.schema_test = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i'); + self.re.schema_search = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig'); + self.re.schema_at_start = RegExp('^' + self.re.schema_search.source, 'i'); + self.re.pretest = RegExp('(' + self.re.schema_test.source + ')|(' + self.re.host_fuzzy_test.source + ')|@', 'i'); + + // + // Cleanup + // + + resetScanCache(self); + } + + /** + * class Match + * + * Match result. Single element of array, returned by [[LinkifyIt#match]] + **/ + function Match(self, shift) { + const start = self.__index__; + const end = self.__last_index__; + const text = self.__text_cache__.slice(start, end); + + /** + * Match#schema -> String + * + * Prefix (protocol) for matched string. + **/ + this.schema = self.__schema__.toLowerCase(); + /** + * Match#index -> Number + * + * First position of matched string. + **/ + this.index = start + shift; + /** + * Match#lastIndex -> Number + * + * Next position after matched string. + **/ + this.lastIndex = end + shift; + /** + * Match#raw -> String + * + * Matched string. + **/ + this.raw = text; + /** + * Match#text -> String + * + * Notmalized text of matched string. + **/ + this.text = text; + /** + * Match#url -> String + * + * Normalized url of matched string. + **/ + this.url = text; + } + function createMatch(self, shift) { + const match = new Match(self, shift); + self.__compiled__[match.schema].normalize(match, self); + return match; + } + + /** + * class LinkifyIt + **/ + + /** + * new LinkifyIt(schemas, options) + * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) + * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } + * + * Creates new linkifier instance with optional additional schemas. + * Can be called without `new` keyword for convenience. + * + * By default understands: + * + * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links + * - "fuzzy" links and emails (example.com, foo@bar.com). + * + * `schemas` is an object, where each key/value describes protocol/rule: + * + * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` + * for example). `linkify-it` makes shure that prefix is not preceeded with + * alphanumeric char and symbols. Only whitespaces and punctuation allowed. + * - __value__ - rule to check tail after link prefix + * - _String_ - just alias to existing rule + * - _Object_ + * - _validate_ - validator function (should return matched length on success), + * or `RegExp`. + * - _normalize_ - optional function to normalize text & url of matched result + * (for example, for @twitter mentions). + * + * `options`: + * + * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. + * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts + * like version numbers. Default `false`. + * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. + * + **/ + function LinkifyIt(schemas, options) { + if (!(this instanceof LinkifyIt)) { + return new LinkifyIt(schemas, options); + } + if (!options) { + if (isOptionsObj(schemas)) { + options = schemas; + schemas = {}; + } + } + this.__opts__ = assign({}, defaultOptions, options); + + // Cache last tested result. Used to skip repeating steps on next `match` call. + this.__index__ = -1; + this.__last_index__ = -1; // Next scan position + this.__schema__ = ''; + this.__text_cache__ = ''; + this.__schemas__ = assign({}, defaultSchemas, schemas); + this.__compiled__ = {}; + this.__tlds__ = tlds_default; + this.__tlds_replaced__ = false; + this.re = {}; + compile(this); + } + + /** chainable + * LinkifyIt#add(schema, definition) + * - schema (String): rule name (fixed pattern prefix) + * - definition (String|RegExp|Object): schema definition + * + * Add new rule definition. See constructor description for details. + **/ + LinkifyIt.prototype.add = function add(schema, definition) { + this.__schemas__[schema] = definition; + compile(this); + return this; + }; + + /** chainable + * LinkifyIt#set(options) + * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } + * + * Set recognition options for links without schema. + **/ + LinkifyIt.prototype.set = function set(options) { + this.__opts__ = assign(this.__opts__, options); + return this; + }; + + /** + * LinkifyIt#test(text) -> Boolean + * + * Searches linkifiable pattern and returns `true` on success or `false` on fail. + **/ + LinkifyIt.prototype.test = function test(text) { + // Reset scan cache + this.__text_cache__ = text; + this.__index__ = -1; + if (!text.length) { + return false; + } + let m, ml, me, len, shift, next, re, tld_pos, at_pos; + + // try to scan for link with schema - that's the most simple rule + if (this.re.schema_test.test(text)) { + re = this.re.schema_search; + re.lastIndex = 0; + while ((m = re.exec(text)) !== null) { + len = this.testSchemaAt(text, m[2], re.lastIndex); + if (len) { + this.__schema__ = m[2]; + this.__index__ = m.index + m[1].length; + this.__last_index__ = m.index + m[0].length + len; + break; + } + } + } + if (this.__opts__.fuzzyLink && this.__compiled__['http:']) { + // guess schemaless links + tld_pos = text.search(this.re.host_fuzzy_test); + if (tld_pos >= 0) { + // if tld is located after found link - no need to check fuzzy pattern + if (this.__index__ < 0 || tld_pos < this.__index__) { + if ((ml = text.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) { + shift = ml.index + ml[1].length; + if (this.__index__ < 0 || shift < this.__index__) { + this.__schema__ = ''; + this.__index__ = shift; + this.__last_index__ = ml.index + ml[0].length; } } } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/parser/types.js": - /*!**********************************************************!*\ - !*** ../../graphql-language-service/esm/parser/types.js ***! - \**********************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.RuleKinds = exports.AdditionalRuleKinds = void 0; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const AdditionalRuleKinds = (exports.AdditionalRuleKinds = { - ALIASED_FIELD: "AliasedField", - ARGUMENTS: "Arguments", - SHORT_QUERY: "ShortQuery", - QUERY: "Query", - MUTATION: "Mutation", - SUBSCRIPTION: "Subscription", - TYPE_CONDITION: "TypeCondition", - INVALID: "Invalid", - COMMENT: "Comment", - SCHEMA_DEF: "SchemaDef", - SCALAR_DEF: "ScalarDef", - OBJECT_TYPE_DEF: "ObjectTypeDef", - OBJECT_VALUE: "ObjectValue", - LIST_VALUE: "ListValue", - INTERFACE_DEF: "InterfaceDef", - UNION_DEF: "UnionDef", - ENUM_DEF: "EnumDef", - ENUM_VALUE: "EnumValue", - FIELD_DEF: "FieldDef", - INPUT_DEF: "InputDef", - INPUT_VALUE_DEF: "InputValueDef", - ARGUMENTS_DEF: "ArgumentsDef", - EXTEND_DEF: "ExtendDef", - EXTENSION_DEFINITION: "ExtensionDefinition", - DIRECTIVE_DEF: "DirectiveDef", - IMPLEMENTS: "Implements", - VARIABLE_DEFINITIONS: "VariableDefinitions", - TYPE: "Type", - VARIABLE: "Variable", - }); - const RuleKinds = (exports.RuleKinds = Object.assign( - Object.assign({}, _graphql.Kind), - AdditionalRuleKinds - )); - - /***/ - }, - - /***/ "../../graphql-language-service/esm/types.js": - /*!***************************************************!*\ - !*** ../../graphql-language-service/esm/types.js ***! - \***************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.FileChangeTypeKind = exports.CompletionItemKind = void 0; - Object.defineProperty(exports, "GraphQLDocumentMode", { - enumerable: true, - get: function () { - return _parser.GraphQLDocumentMode; - }, - }); - Object.defineProperty(exports, "InsertTextFormat", { - enumerable: true, - get: function () { - return _vscodeLanguageserverTypes.InsertTextFormat; - }, - }); - var _vscodeLanguageserverTypes = __webpack_require__( - /*! vscode-languageserver-types */ "../../../node_modules/vscode-languageserver-types/lib/esm/main.js" - ); - var _parser = __webpack_require__( - /*! ./parser */ "../../graphql-language-service/esm/parser/index.js" - ); - const FileChangeTypeKind = (exports.FileChangeTypeKind = { - Created: 1, - Changed: 2, - Deleted: 3, - }); - var CompletionItemKind; - (function (CompletionItemKind) { - CompletionItemKind.Text = 1; - CompletionItemKind.Method = 2; - CompletionItemKind.Function = 3; - CompletionItemKind.Constructor = 4; - CompletionItemKind.Field = 5; - CompletionItemKind.Variable = 6; - CompletionItemKind.Class = 7; - CompletionItemKind.Interface = 8; - CompletionItemKind.Module = 9; - CompletionItemKind.Property = 10; - CompletionItemKind.Unit = 11; - CompletionItemKind.Value = 12; - CompletionItemKind.Enum = 13; - CompletionItemKind.Keyword = 14; - CompletionItemKind.Snippet = 15; - CompletionItemKind.Color = 16; - CompletionItemKind.File = 17; - CompletionItemKind.Reference = 18; - CompletionItemKind.Folder = 19; - CompletionItemKind.EnumMember = 20; - CompletionItemKind.Constant = 21; - CompletionItemKind.Struct = 22; - CompletionItemKind.Event = 23; - CompletionItemKind.Operator = 24; - CompletionItemKind.TypeParameter = 25; - })( - CompletionItemKind || - (exports.CompletionItemKind = CompletionItemKind = {}) - ); - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/Range.js": - /*!*********************************************************!*\ - !*** ../../graphql-language-service/esm/utils/Range.js ***! - \*********************************************************/ - /***/ function (__unused_webpack_module, exports) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.Range = exports.Position = void 0; - exports.locToRange = locToRange; - exports.offsetToPosition = offsetToPosition; - class Range { - constructor(start, end) { - this.containsPosition = (position) => { - if (this.start.line === position.line) { - return this.start.character <= position.character; - } - if (this.end.line === position.line) { - return this.end.character >= position.character; - } - return ( - this.start.line <= position.line && - this.end.line >= position.line - ); - }; - this.start = start; - this.end = end; - } - setStart(line, character) { - this.start = new Position(line, character); - } - setEnd(line, character) { - this.end = new Position(line, character); + } + } + if (this.__opts__.fuzzyEmail && this.__compiled__['mailto:']) { + // guess schemaless emails + at_pos = text.indexOf('@'); + if (at_pos >= 0) { + // We can't skip this check, because this cases are possible: + // 192.168.1.1@gmail.com, my.in@example.com + if ((me = text.match(this.re.email_fuzzy)) !== null) { + shift = me.index + me[1].length; + next = me.index + me[0].length; + if (this.__index__ < 0 || shift < this.__index__ || shift === this.__index__ && next > this.__last_index__) { + this.__schema__ = 'mailto:'; + this.__index__ = shift; + this.__last_index__ = next; } } - exports.Range = Range; - class Position { - constructor(line, character) { - this.lessThanOrEqualTo = (position) => - this.line < position.line || - (this.line === position.line && - this.character <= position.character); - this.line = line; - this.character = character; - } - setLine(line) { - this.line = line; - } - setCharacter(character) { - this.character = character; - } + } + } + return this.__index__ >= 0; + }; + + /** + * LinkifyIt#pretest(text) -> Boolean + * + * Very quick check, that can give false positives. Returns true if link MAY BE + * can exists. Can be used for speed optimization, when you need to check that + * link NOT exists. + **/ + LinkifyIt.prototype.pretest = function pretest(text) { + return this.re.pretest.test(text); + }; + + /** + * LinkifyIt#testSchemaAt(text, name, position) -> Number + * - text (String): text to scan + * - name (String): rule (schema) name + * - position (Number): text offset to check from + * + * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly + * at given position. Returns length of found pattern (0 on fail). + **/ + LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text, schema, pos) { + // If not supported schema check requested - terminate + if (!this.__compiled__[schema.toLowerCase()]) { + return 0; + } + return this.__compiled__[schema.toLowerCase()].validate(text, pos, this); + }; + + /** + * LinkifyIt#match(text) -> Array|null + * + * Returns array of found link descriptions or `null` on fail. We strongly + * recommend to use [[LinkifyIt#test]] first, for best speed. + * + * ##### Result match description + * + * - __schema__ - link schema, can be empty for fuzzy links, or `//` for + * protocol-neutral links. + * - __index__ - offset of matched text + * - __lastIndex__ - index of next char after mathch end + * - __raw__ - matched text + * - __text__ - normalized text + * - __url__ - link, generated from matched text + **/ + LinkifyIt.prototype.match = function match(text) { + const result = []; + let shift = 0; + + // Try to take previous element from cache, if .test() called before + if (this.__index__ >= 0 && this.__text_cache__ === text) { + result.push(createMatch(this, shift)); + shift = this.__last_index__; + } + + // Cut head if cache was used + let tail = shift ? text.slice(shift) : text; + + // Scan string until end reached + while (this.test(tail)) { + result.push(createMatch(this, shift)); + tail = tail.slice(this.__last_index__); + shift += this.__last_index__; + } + if (result.length) { + return result; + } + return null; + }; + + /** + * LinkifyIt#matchAtStart(text) -> Match|null + * + * Returns fully-formed (not fuzzy) link if it starts at the beginning + * of the string, and null otherwise. + **/ + LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { + // Reset scan cache + this.__text_cache__ = text; + this.__index__ = -1; + if (!text.length) return null; + const m = this.re.schema_at_start.exec(text); + if (!m) return null; + const len = this.testSchemaAt(text, m[2], m[0].length); + if (!len) return null; + this.__schema__ = m[2]; + this.__index__ = m.index + m[1].length; + this.__last_index__ = m.index + m[0].length + len; + return createMatch(this, 0); + }; + + /** chainable + * LinkifyIt#tlds(list [, keepOld]) -> this + * - list (Array): list of tlds + * - keepOld (Boolean): merge with current list if `true` (`false` by default) + * + * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) + * to avoid false positives. By default this algorythm used: + * + * - hostname with any 2-letter root zones are ok. + * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф + * are ok. + * - encoded (`xn--...`) root zones are ok. + * + * If list is replaced, then exact match for 2-chars root zones will be checked. + **/ + LinkifyIt.prototype.tlds = function tlds(list, keepOld) { + list = Array.isArray(list) ? list : [list]; + if (!keepOld) { + this.__tlds__ = list.slice(); + this.__tlds_replaced__ = true; + compile(this); + return this; + } + this.__tlds__ = this.__tlds__.concat(list).sort().filter(function (el, idx, arr) { + return el !== arr[idx - 1]; + }).reverse(); + compile(this); + return this; + }; + + /** + * LinkifyIt#normalize(match) + * + * Default normalizer (if schema does not define it's own). + **/ + LinkifyIt.prototype.normalize = function normalize(match) { + // Do minimal possible changes by default. Need to collect feedback prior + // to move forward https://github.com/markdown-it/linkify-it/issues/1 + + if (!match.schema) { + match.url = 'http://' + match.url; + } + if (match.schema === 'mailto:' && !/^mailto:/i.test(match.url)) { + match.url = 'mailto:' + match.url; + } + }; + + /** + * LinkifyIt#onCompile() + * + * Override to modify basic RegExp-s. + **/ + LinkifyIt.prototype.onCompile = function onCompile() {}; + module.exports = LinkifyIt; + + /***/ }), + + /***/ "../node_modules/markdown-it/dist/index.cjs.js": + /*!*****************************************************!*\ + !*** ../node_modules/markdown-it/dist/index.cjs.js ***! + \*****************************************************/ + /***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + + var mdurl = __webpack_require__(/*! mdurl */ "../node_modules/mdurl/build/index.cjs.js"); + var ucmicro = __webpack_require__(/*! uc.micro */ "../node_modules/uc.micro/build/index.cjs.js"); + var entities = __webpack_require__(/*! entities */ "../../../node_modules/entities/lib/index.js"); + var LinkifyIt = __webpack_require__(/*! linkify-it */ "../node_modules/linkify-it/build/index.cjs.js"); + var punycode = __webpack_require__(/*! punycode.js */ "../../../node_modules/punycode.js/punycode.es6.js"); + function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { + return e[k]; + } + }); + } + }); + } + n.default = e; + return Object.freeze(n); + } + var mdurl__namespace = /*#__PURE__*/_interopNamespaceDefault(mdurl); + var ucmicro__namespace = /*#__PURE__*/_interopNamespaceDefault(ucmicro); + + // Utilities + // + + function _class(obj) { + return Object.prototype.toString.call(obj); + } + function isString(obj) { + return _class(obj) === '[object String]'; + } + const _hasOwnProperty = Object.prototype.hasOwnProperty; + function has(object, key) { + return _hasOwnProperty.call(object, key); + } + + // Merge objects + // + function assign(obj /* from1, from2, from3, ... */) { + const sources = Array.prototype.slice.call(arguments, 1); + sources.forEach(function (source) { + if (!source) { + return; + } + if (typeof source !== 'object') { + throw new TypeError(source + 'must be object'); + } + Object.keys(source).forEach(function (key) { + obj[key] = source[key]; + }); + }); + return obj; + } + + // Remove element from array and put another array at those position. + // Useful for some operations with tokens + function arrayReplaceAt(src, pos, newElements) { + return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); + } + function isValidEntityCode(c) { + /* eslint no-bitwise:0 */ + // broken sequence + if (c >= 0xD800 && c <= 0xDFFF) { + return false; + } + // never used + if (c >= 0xFDD0 && c <= 0xFDEF) { + return false; + } + if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { + return false; + } + // control codes + if (c >= 0x00 && c <= 0x08) { + return false; + } + if (c === 0x0B) { + return false; + } + if (c >= 0x0E && c <= 0x1F) { + return false; + } + if (c >= 0x7F && c <= 0x9F) { + return false; + } + // out of range + if (c > 0x10FFFF) { + return false; + } + return true; + } + function fromCodePoint(c) { + /* eslint no-bitwise:0 */ + if (c > 0xffff) { + c -= 0x10000; + const surrogate1 = 0xd800 + (c >> 10); + const surrogate2 = 0xdc00 + (c & 0x3ff); + return String.fromCharCode(surrogate1, surrogate2); + } + return String.fromCharCode(c); + } + const UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g; + const ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; + const UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi'); + const DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i; + function replaceEntityPattern(match, name) { + if (name.charCodeAt(0) === 0x23 /* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) { + const code = name[1].toLowerCase() === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10); + if (isValidEntityCode(code)) { + return fromCodePoint(code); + } + return match; + } + const decoded = entities.decodeHTML(match); + if (decoded !== match) { + return decoded; + } + return match; + } + + /* function replaceEntities(str) { + if (str.indexOf('&') < 0) { return str; } + + return str.replace(ENTITY_RE, replaceEntityPattern); + } */ + + function unescapeMd(str) { + if (str.indexOf('\\') < 0) { + return str; + } + return str.replace(UNESCAPE_MD_RE, '$1'); + } + function unescapeAll(str) { + if (str.indexOf('\\') < 0 && str.indexOf('&') < 0) { + return str; + } + return str.replace(UNESCAPE_ALL_RE, function (match, escaped, entity) { + if (escaped) { + return escaped; + } + return replaceEntityPattern(match, entity); + }); + } + const HTML_ESCAPE_TEST_RE = /[&<>"]/; + const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; + const HTML_REPLACEMENTS = { + '&': '&', + '<': '<', + '>': '>', + '"': '"' + }; + function replaceUnsafeChar(ch) { + return HTML_REPLACEMENTS[ch]; + } + function escapeHtml(str) { + if (HTML_ESCAPE_TEST_RE.test(str)) { + return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); + } + return str; + } + const REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; + function escapeRE(str) { + return str.replace(REGEXP_ESCAPE_RE, '\\$&'); + } + function isSpace(code) { + switch (code) { + case 0x09: + case 0x20: + return true; + } + return false; + } + + // Zs (unicode class) || [\t\f\v\r\n] + function isWhiteSpace(code) { + if (code >= 0x2000 && code <= 0x200A) { + return true; + } + switch (code) { + case 0x09: // \t + case 0x0A: // \n + case 0x0B: // \v + case 0x0C: // \f + case 0x0D: // \r + case 0x20: + case 0xA0: + case 0x1680: + case 0x202F: + case 0x205F: + case 0x3000: + return true; + } + return false; + } + + /* eslint-disable max-len */ + + // Currently without astral characters support. + function isPunctChar(ch) { + return ucmicro__namespace.P.test(ch) || ucmicro__namespace.S.test(ch); + } + + // Markdown ASCII punctuation characters. + // + // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ + // http://spec.commonmark.org/0.15/#ascii-punctuation-character + // + // Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. + // + function isMdAsciiPunct(ch) { + switch (ch) { + case 0x21 /* ! */: + case 0x22 /* " */: + case 0x23 /* # */: + case 0x24 /* $ */: + case 0x25 /* % */: + case 0x26 /* & */: + case 0x27 /* ' */: + case 0x28 /* ( */: + case 0x29 /* ) */: + case 0x2A /* * */: + case 0x2B /* + */: + case 0x2C /* , */: + case 0x2D /* - */: + case 0x2E /* . */: + case 0x2F /* / */: + case 0x3A /* : */: + case 0x3B /* ; */: + case 0x3C /* < */: + case 0x3D /* = */: + case 0x3E /* > */: + case 0x3F /* ? */: + case 0x40 /* @ */: + case 0x5B /* [ */: + case 0x5C /* \ */: + case 0x5D /* ] */: + case 0x5E /* ^ */: + case 0x5F /* _ */: + case 0x60 /* ` */: + case 0x7B /* { */: + case 0x7C /* | */: + case 0x7D /* } */: + case 0x7E /* ~ */: + return true; + default: + return false; + } + } + + // Hepler to unify [reference labels]. + // + function normalizeReference(str) { + // Trim and collapse whitespace + // + str = str.trim().replace(/\s+/g, ' '); + + // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug + // fixed in v12 (couldn't find any details). + // + // So treat this one as a special case + // (remove this when node v10 is no longer supported). + // + if ('ẞ'.toLowerCase() === 'Ṿ') { + str = str.replace(/ẞ/g, 'ß'); + } + + // .toLowerCase().toUpperCase() should get rid of all differences + // between letter variants. + // + // Simple .toLowerCase() doesn't normalize 125 code points correctly, + // and .toUpperCase doesn't normalize 6 of them (list of exceptions: + // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently + // uppercased versions). + // + // Here's an example showing how it happens. Lets take greek letter omega: + // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) + // + // Unicode entries: + // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; + // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 + // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 + // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; + // + // Case-insensitive comparison should treat all of them as equivalent. + // + // But .toLowerCase() doesn't change ϑ (it's already lowercase), + // and .toUpperCase() doesn't change ϴ (already uppercase). + // + // Applying first lower then upper case normalizes any character: + // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' + // + // Note: this is equivalent to unicode case folding; unicode normalization + // is a different step that is not required here. + // + // Final result should be uppercased, because it's later stored in an object + // (this avoid a conflict with Object.prototype members, + // most notably, `__proto__`) + // + return str.toLowerCase().toUpperCase(); + } + + // Re-export libraries commonly used in both markdown-it and its plugins, + // so plugins won't have to depend on them explicitly, which reduces their + // bundled size (e.g. a browser build). + // + const lib = { + mdurl: mdurl__namespace, + ucmicro: ucmicro__namespace + }; + var utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + arrayReplaceAt: arrayReplaceAt, + assign: assign, + escapeHtml: escapeHtml, + escapeRE: escapeRE, + fromCodePoint: fromCodePoint, + has: has, + isMdAsciiPunct: isMdAsciiPunct, + isPunctChar: isPunctChar, + isSpace: isSpace, + isString: isString, + isValidEntityCode: isValidEntityCode, + isWhiteSpace: isWhiteSpace, + lib: lib, + normalizeReference: normalizeReference, + unescapeAll: unescapeAll, + unescapeMd: unescapeMd + }); + + // Parse link label + // + // this function assumes that first character ("[") already matches; + // returns the end of the label + // + + function parseLinkLabel(state, start, disableNested) { + let level, found, marker, prevPos; + const max = state.posMax; + const oldPos = state.pos; + state.pos = start + 1; + level = 1; + while (state.pos < max) { + marker = state.src.charCodeAt(state.pos); + if (marker === 0x5D /* ] */) { + level--; + if (level === 0) { + found = true; + break; } - exports.Position = Position; - function offsetToPosition(text, loc) { - const EOL = "\n"; - const buf = text.slice(0, loc); - const lines = buf.split(EOL).length - 1; - const lastLineIndex = buf.lastIndexOf(EOL); - return new Position(lines, loc - lastLineIndex - 1); + } + prevPos = state.pos; + state.md.inline.skipToken(state); + if (marker === 0x5B /* [ */) { + if (prevPos === state.pos - 1) { + // increase level if we find text `[`, which is not a part of any token + level++; + } else if (disableNested) { + state.pos = oldPos; + return -1; } - function locToRange(text, loc) { - const start = offsetToPosition(text, loc.start); - const end = offsetToPosition(text, loc.end); - return new Range(start, end); + } + } + let labelEnd = -1; + if (found) { + labelEnd = state.pos; + } + + // restore old state + state.pos = oldPos; + return labelEnd; + } + + // Parse link destination + // + + function parseLinkDestination(str, start, max) { + let code; + let pos = start; + const result = { + ok: false, + pos: 0, + str: '' + }; + if (str.charCodeAt(pos) === 0x3C /* < */) { + pos++; + while (pos < max) { + code = str.charCodeAt(pos); + if (code === 0x0A /* \n */) { + return result; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/collectVariables.js": - /*!********************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/collectVariables.js ***! - \********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.collectVariables = collectVariables; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function collectVariables(schema, documentAST) { - const variableToType = Object.create(null); - for (const definition of documentAST.definitions) { - if (definition.kind === "OperationDefinition") { - const { variableDefinitions } = definition; - if (variableDefinitions) { - for (const { variable, type } of variableDefinitions) { - const inputType = (0, _graphql.typeFromAST)(schema, type); - if (inputType) { - variableToType[variable.name.value] = inputType; - } else if ( - type.kind === _graphql.Kind.NAMED_TYPE && - type.name.value === "Float" - ) { - variableToType[variable.name.value] = _graphql.GraphQLFloat; - } - } - } - } - } - return variableToType; + if (code === 0x3C /* < */) { + return result; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/fragmentDependencies.js": - /*!************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/fragmentDependencies.js ***! - \************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getFragmentDependenciesForAST = - exports.getFragmentDependencies = void 0; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _nullthrows = _interopRequireDefault( - __webpack_require__( - /*! nullthrows */ "../../../node_modules/nullthrows/nullthrows.js" - ) - ); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; + if (code === 0x3E /* > */) { + result.pos = pos + 1; + result.str = unescapeAll(str.slice(start + 1, pos)); + result.ok = true; + return result; } - const getFragmentDependencies = ( - operationString, - fragmentDefinitions - ) => { - if (!fragmentDefinitions) { - return []; - } - let parsedOperation; - try { - parsedOperation = (0, _graphql.parse)(operationString); - } catch (_a) { - return []; - } - return getFragmentDependenciesForAST( - parsedOperation, - fragmentDefinitions - ); - }; - exports.getFragmentDependencies = getFragmentDependencies; - const getFragmentDependenciesForAST = ( - parsedOperation, - fragmentDefinitions - ) => { - if (!fragmentDefinitions) { - return []; - } - const existingFrags = new Map(); - const referencedFragNames = new Set(); - (0, _graphql.visit)(parsedOperation, { - FragmentDefinition(node) { - existingFrags.set(node.name.value, true); - }, - FragmentSpread(node) { - if (!referencedFragNames.has(node.name.value)) { - referencedFragNames.add(node.name.value); - } - }, - }); - const asts = new Set(); - for (const name of referencedFragNames) { - if (!existingFrags.has(name) && fragmentDefinitions.has(name)) { - asts.add((0, _nullthrows.default)(fragmentDefinitions.get(name))); - } - } - const referencedFragments = []; - for (const ast of asts) { - (0, _graphql.visit)(ast, { - FragmentSpread(node) { - if ( - !referencedFragNames.has(node.name.value) && - fragmentDefinitions.get(node.name.value) - ) { - asts.add( - (0, _nullthrows.default)( - fragmentDefinitions.get(node.name.value) - ) - ); - referencedFragNames.add(node.name.value); - } - }, - }); - if (!existingFrags.has(ast.name.value)) { - referencedFragments.push(ast); - } - } - return referencedFragments; - }; - exports.getFragmentDependenciesForAST = getFragmentDependenciesForAST; - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/getASTNodeAtPosition.js": - /*!************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getASTNodeAtPosition.js ***! - \************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.getASTNodeAtPosition = getASTNodeAtPosition; - exports.pointToOffset = pointToOffset; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - function getASTNodeAtPosition(query, ast, point) { - const offset = pointToOffset(query, point); - let nodeContainingPosition; - (0, _graphql.visit)(ast, { - enter(node) { - if ( - node.kind !== "Name" && - node.loc && - node.loc.start <= offset && - offset <= node.loc.end - ) { - nodeContainingPosition = node; - } else { - return false; - } - }, - leave(node) { - if ( - node.loc && - node.loc.start <= offset && - offset <= node.loc.end - ) { - return false; - } - }, - }); - return nodeContainingPosition; - } - function pointToOffset(text, point) { - const linesUntilPosition = text.split("\n").slice(0, point.line); - return ( - point.character + - linesUntilPosition - .map((line) => line.length + 1) - .reduce((a, b) => a + b, 0) - ); + if (code === 0x5C /* \ */ && pos + 1 < max) { + pos += 2; + continue; } - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/getOperationFacts.js": - /*!*********************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getOperationFacts.js ***! - \*********************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports["default"] = getOperationFacts; - exports.getOperationASTFacts = getOperationASTFacts; - exports.getQueryFacts = void 0; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - var _collectVariables = __webpack_require__( - /*! ./collectVariables */ "../../graphql-language-service/esm/utils/collectVariables.js" - ); - function getOperationASTFacts(documentAST, schema) { - const variableToType = schema - ? (0, _collectVariables.collectVariables)(schema, documentAST) - : undefined; - const operations = []; - (0, _graphql.visit)(documentAST, { - OperationDefinition(node) { - operations.push(node); - }, - }); - return { - variableToType, - operations, - }; + pos++; + } + + // no closing '>' + return result; + } + + // this should be ... } else { ... branch + + let level = 0; + while (pos < max) { + code = str.charCodeAt(pos); + if (code === 0x20) { + break; + } + + // ascii control characters + if (code < 0x20 || code === 0x7F) { + break; + } + if (code === 0x5C /* \ */ && pos + 1 < max) { + if (str.charCodeAt(pos + 1) === 0x20) { + break; } - function getOperationFacts(schema, documentString) { - if (!documentString) { - return; - } - try { - const documentAST = (0, _graphql.parse)(documentString); - return Object.assign( - Object.assign({}, getOperationASTFacts(documentAST, schema)), - { - documentAST, - } - ); - } catch (_a) { - return; - } + pos += 2; + continue; + } + if (code === 0x28 /* ( */) { + level++; + if (level > 32) { + return result; } - const getQueryFacts = (exports.getQueryFacts = getOperationFacts); - - /***/ - }, - - /***/ "../../graphql-language-service/esm/utils/getVariablesJSONSchema.js": - /*!**************************************************************************!*\ - !*** ../../graphql-language-service/esm/utils/getVariablesJSONSchema.js ***! - \**************************************************************************/ - /***/ function (__unused_webpack_module, exports, __webpack_require__) { - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.defaultJSONSchemaOptions = void 0; - exports.getVariablesJSONSchema = getVariablesJSONSchema; - var _graphql = __webpack_require__( - /*! graphql */ "../../../node_modules/graphql/index.mjs" - ); - const defaultJSONSchemaOptions = (exports.defaultJSONSchemaOptions = { - useMarkdownDescription: false, - }); - function text(into, newText) { - into.push(newText); - } - function renderType(into, t) { - if ((0, _graphql.isNonNullType)(t)) { - renderType(into, t.ofType); - text(into, "!"); - } else if ((0, _graphql.isListType)(t)) { - text(into, "["); - renderType(into, t.ofType); - text(into, "]"); - } else { - text(into, t.name); - } - } - function renderDefinitionDescription(t, useMarkdown, description) { - const into = []; - const type = "type" in t ? t.type : t; - if ("type" in t && t.description) { - text(into, t.description); - text(into, "\n\n"); - } - text(into, renderTypeToString(type, useMarkdown)); - if (description) { - text(into, "\n"); - text(into, description); - } else if ( - !(0, _graphql.isScalarType)(type) && - "description" in type && - type.description - ) { - text(into, "\n"); - text(into, type.description); - } else if ( - "ofType" in type && - !(0, _graphql.isScalarType)(type.ofType) && - "description" in type.ofType && - type.ofType.description - ) { - text(into, "\n"); - text(into, type.ofType.description); - } - return into.join(""); - } - function renderTypeToString(t, useMarkdown) { - const into = []; - if (useMarkdown) { - text(into, "```graphql\n"); - } - renderType(into, t); - if (useMarkdown) { - text(into, "\n```"); - } - return into.join(""); - } - const defaultScalarTypesMap = { - Int: { - type: "integer", - }, - String: { - type: "string", - }, - Float: { - type: "number", - }, - ID: { - type: "string", - }, - Boolean: { - type: "boolean", - }, - DateTime: { - type: "string", - }, - }; - class Marker { - constructor() { - this.set = new Set(); - } - mark(name) { - if (this.set.has(name)) { - return false; - } - this.set.add(name); - return true; + } + if (code === 0x29 /* ) */) { + if (level === 0) { + break; + } + level--; + } + pos++; + } + if (start === pos) { + return result; + } + if (level !== 0) { + return result; + } + result.str = unescapeAll(str.slice(start, pos)); + result.pos = pos; + result.ok = true; + return result; + } + + // Parse link title + // + + // Parse link title within `str` in [start, max] range, + // or continue previous parsing if `prev_state` is defined (equal to result of last execution). + // + function parseLinkTitle(str, start, max, prev_state) { + let code; + let pos = start; + const state = { + // if `true`, this is a valid link title + ok: false, + // if `true`, this link can be continued on the next line + can_continue: false, + // if `ok`, it's the position of the first character after the closing marker + pos: 0, + // if `ok`, it's the unescaped title + str: '', + // expected closing marker character code + marker: 0 + }; + if (prev_state) { + // this is a continuation of a previous parseLinkTitle call on the next line, + // used in reference links only + state.str = prev_state.str; + state.marker = prev_state.marker; + } else { + if (pos >= max) { + return state; + } + let marker = str.charCodeAt(pos); + if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { + return state; + } + start++; + pos++; + + // if opening marker is "(", switch it to closing marker ")" + if (marker === 0x28) { + marker = 0x29; + } + state.marker = marker; + } + while (pos < max) { + code = str.charCodeAt(pos); + if (code === state.marker) { + state.pos = pos + 1; + state.str += unescapeAll(str.slice(start, pos)); + state.ok = true; + return state; + } else if (code === 0x28 /* ( */ && state.marker === 0x29 /* ) */) { + return state; + } else if (code === 0x5C /* \ */ && pos + 1 < max) { + pos++; + } + pos++; + } + + // no closing marker found, but this link title may continue on the next line (for references) + state.can_continue = true; + state.str += unescapeAll(str.slice(start, pos)); + return state; + } + + // Just a shortcut for bulk export + + var helpers = /*#__PURE__*/Object.freeze({ + __proto__: null, + parseLinkDestination: parseLinkDestination, + parseLinkLabel: parseLinkLabel, + parseLinkTitle: parseLinkTitle + }); + + /** + * class Renderer + * + * Generates HTML from parsed token stream. Each instance has independent + * copy of rules. Those can be rewritten with ease. Also, you can add new + * rules if you create plugin and adds new token types. + **/ + + const default_rules = {}; + default_rules.code_inline = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + return '' + escapeHtml(token.content) + ''; + }; + default_rules.code_block = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + return '' + escapeHtml(tokens[idx].content) + '\n'; + }; + default_rules.fence = function (tokens, idx, options, env, slf) { + const token = tokens[idx]; + const info = token.info ? unescapeAll(token.info).trim() : ''; + let langName = ''; + let langAttrs = ''; + if (info) { + const arr = info.split(/(\s+)/g); + langName = arr[0]; + langAttrs = arr.slice(2).join(''); + } + let highlighted; + if (options.highlight) { + highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content); + } else { + highlighted = escapeHtml(token.content); + } + if (highlighted.indexOf('${highlighted}\n`; + } + return `